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
3c4d485b8d037c6db1a13c41aead2be4e41f4172
1,300
cc
C++
below2.1/okviri.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/okviri.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/okviri.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main(){ string str; cin>>str; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<"..*."; }else{ cout<<"..#."; } } cout<<".\n"; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<".*.*"; }else{ cout<<".#.#"; } }cout<<".\n"; // 3rd line; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<"*."<<str[i]<<"."; }else{ if(i!=0){ if((i-1)%3 == 2){ cout<<"*"; } else{ cout<<"#"; } } else{ cout<<"#"; } cout<<"."<<str[i]<<"."; } } if(str.length()%3 == 0){ cout<<"*\n"; } else{ cout<<"#\n"; } // 3rd line ends for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<".*.*"; }else{ cout<<".#.#"; } } cout<<".\n"; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<"..*."; }else{ cout<<"..#."; } } cout<<".\n"; return 0; }
18.309859
42
0.264615
danzel-py
3c4f392ac7bef2878ac80d7395a328678389d6f1
4,065
cpp
C++
index.cpp
travc/vt
20ba6b7a313aebf2162eb877c38a5c818322bafe
[ "MIT" ]
166
2015-01-14T23:14:05.000Z
2022-03-31T14:15:56.000Z
index.cpp
travc/vt
20ba6b7a313aebf2162eb877c38a5c818322bafe
[ "MIT" ]
108
2015-01-16T13:21:07.000Z
2022-01-26T22:47:55.000Z
index.cpp
travc/vt
20ba6b7a313aebf2162eb877c38a5c818322bafe
[ "MIT" ]
48
2015-01-16T23:35:18.000Z
2022-03-01T12:14:53.000Z
/* The MIT License Copyright (c) 2013 Adrian Tan <atks@umich.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "index.h" namespace { class Igor : Program { public: /////////// //options// /////////// std::string input_vcf_file; kstring_t output_vcf_index_file; bool print; Igor(int argc, char **argv) { version = "0.5"; ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "Indexes a VCF.GZ or BCF file."; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::SwitchArg arg_print("p", "p", "print options and summary []", cmd, false); TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd); cmd.parse(argc, argv); input_vcf_file = arg_input_vcf_file.getValue(); print = arg_print.getValue(); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { } void index() { htsFile *file = hts_open(input_vcf_file.c_str(), "r"); if (file==NULL) { exit(1); } htsFormat ftype = file->format; if (ftype.compression!=bgzf&&ftype.format!=vcf&&ftype.format!=bcf) { fprintf(stderr, "[%s:%d %s] Not a BGZF VCF/BCF file: %s\n", __FILE__, __LINE__, __FUNCTION__, input_vcf_file.c_str()); exit(1); } int32_t min_shift; output_vcf_index_file = {0,0,0}; int32_t ret; if (ftype.format==bcf) { kputs(input_vcf_file.c_str(), &output_vcf_index_file); kputs(".csi", &output_vcf_index_file); min_shift = 14; ret = bcf_index_build(input_vcf_file.c_str(), min_shift); } else if (ftype.format==vcf) { kputs(input_vcf_file.c_str(), &output_vcf_index_file); kputs(".tbi", &output_vcf_index_file); min_shift = 0; tbx_conf_t conf = tbx_conf_vcf; ret = tbx_index_build(input_vcf_file.c_str(), min_shift, &conf); } if (ret) { exit(1); } }; void print_options() { if (!print) return; std::clog << "index v" << version << "\n\n"; std::clog << "options: input VCF file " << input_vcf_file << "\n"; std::clog << " output index file " << output_vcf_index_file.s << "\n"; std::clog << "\n"; } void print_stats() { }; ~Igor() {}; private: }; } bool index(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.index(); igor.print_stats(); return igor.print; };
28.229167
130
0.566052
travc
3c4f3bc1c91e31be87122fea0d5e67ba119b3d43
2,983
cpp
C++
Chapter03/LibraryBasic/Book.cpp
linuxemb/datastructure
efc9e2ef897bf1f626b67d08c3892c8f41a008f9
[ "MIT" ]
25
2018-04-04T15:36:26.000Z
2021-11-08T13:12:21.000Z
Chapter03/LibraryBasic/Book.cpp
linuxemb/datastructure
efc9e2ef897bf1f626b67d08c3892c8f41a008f9
[ "MIT" ]
1
2021-06-29T04:14:07.000Z
2021-07-05T19:48:36.000Z
Chapter03/LibraryBasic/Book.cpp
linuxemb/datastructure
efc9e2ef897bf1f626b67d08c3892c8f41a008f9
[ "MIT" ]
16
2018-04-04T15:36:42.000Z
2022-02-07T08:31:16.000Z
#include <Set> #include <Map> #include <List> #include <String> #include <FStream> using namespace std; #include "Book.h" #include "Customer.h" #include "Library.h" int Book::MaxBookId = 0; Book::Book(void) { // Empty. } Book::Book(const string& author, const string& title) :m_bookId(++MaxBookId), m_author(author), m_title(title) { // Empty. } /* Book::Book(const Book& book) :m_bookId(book.m_bookId), m_author(book.m_author), m_title(book.m_title), m_borrowed(book.m_borrowed), m_customerId(book.m_customerId), m_reservationList(book.m_reservationList) { // Empty. } Book& Book::operator=(const Book& book) { m_bookId = book.m_bookId; m_author = book.m_author; m_title = book.m_title; m_borrowed = book.m_borrowed; m_customerId = book.m_customerId; m_reservationList = book.m_reservationList; return *this; } */ void Book::read(ifstream& inStream) { inStream.read((char*) &m_bookId, sizeof m_bookId); getline(inStream, m_author); getline(inStream, m_title); inStream.read((char*)&m_borrowed, sizeof m_borrowed); inStream.read((char*) &m_customerId, sizeof m_customerId); { int reserveListSize; inStream.read((char*) &reserveListSize, sizeof reserveListSize); for (int count = 0; count < reserveListSize; ++count) { int customerId; inStream.read((char*) &customerId, sizeof customerId); m_reservationList.push_back(customerId); } } } void Book::write(ofstream& outStream) const { outStream.write((char*) &m_bookId, sizeof m_bookId); outStream << m_author << endl; outStream << m_title << endl; outStream.write((char*)&m_borrowed, sizeof m_borrowed); outStream.write((char*) &m_customerId, sizeof m_customerId); { int reserveListSize = m_reservationList.size(); outStream.write((char*) &reserveListSize, sizeof reserveListSize); for (int customerId : m_reservationList) { outStream.write((char*) &customerId, sizeof customerId); } } } void Book::borrowBook(int customerId) { m_borrowed = true; m_customerId = customerId; } int Book::reserveBook(int customerId) { m_reservationList.push_back(customerId); return m_reservationList.size(); } void Book::returnBook() { m_borrowed = false; } void Book::unreserveBook(int customerId) { m_reservationList.remove(customerId); } ostream& operator<<(ostream& outStream, const Book& book) { outStream << "\"" << book.m_title << "\" by " << book.m_author; if (book.m_borrowed) { outStream << endl << " Borrowed by: " << Library::s_customerMap[book.m_customerId].name() << "."; } if (!book.m_reservationList.empty()) { outStream << endl << " Reserved by: "; bool first = true; for (int customerId : book.m_reservationList) { outStream << (first ? "" : ",") << Library::s_customerMap[customerId].name(); first = false; } outStream << "."; } return outStream; }
23.304688
65
0.663091
linuxemb
3c50d0e01474815b4c2160695d4db8a48f26b07a
1,107
hpp
C++
Server/Server.hpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
Server/Server.hpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
Server/Server.hpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2021 ** R-TYPE ** File description: ** Created by stun3r, */ #ifndef SERVER_HPP #define SERVER_HPP #include "Room/Room.hpp" class Server { public: Server(); ~Server(); void run(); void startReceive(); void refresh(); private: void handleReceive(const boost::system::error_code &, std::size_t); void handleSend(std::shared_ptr<std::string>, const boost::system::error_code &, std::size_t); bool hasRoom(const std::string &); Room *getRoomsByName(const std::string &) const; void createRoom(const boost::property_tree::ptree &); void joinRoom(const boost::property_tree::ptree &); void destroyRoom(const boost::property_tree::ptree &); void listRoom(const boost::property_tree::ptree &); void roomReceive(const boost::property_tree::ptree &); std::set<Room *> _rooms; boost::asio::io_service _ioservice; std::shared_ptr<boost::asio::ip::udp::socket> _socket; boost::asio::ip::udp::endpoint _endpoint; std::array<char, 128> _buffer; std::map<std::string, std::function<void(const boost::property_tree::ptree &)>> _command; }; #endif //SERVER_HPP
20.5
95
0.709124
Stun3R
3c56201c97620297be4a3b9555938a16194ee4b0
860
hpp
C++
Config.hpp
Krozark/2D-infinite-map
a9d23b937ea89d34a4f793899cea7276caf7adc9
[ "BSD-2-Clause" ]
1
2018-06-25T08:49:37.000Z
2018-06-25T08:49:37.000Z
Config.hpp
Krozark/2D-infinite-map
a9d23b937ea89d34a4f793899cea7276caf7adc9
[ "BSD-2-Clause" ]
1
2015-03-12T10:22:54.000Z
2017-11-24T14:36:07.000Z
Config.hpp
Krozark/2D-infinite-map
a9d23b937ea89d34a4f793899cea7276caf7adc9
[ "BSD-2-Clause" ]
1
2018-06-25T08:50:12.000Z
2018-06-25T08:50:12.000Z
#ifndef CONFIG_HPP #define CONFIG_HPP #include <string> #include <SFML/Graphics.hpp> #include <ResourceManager/ResourceManager.hpp> #include <Map/TileIsoHexa.hpp> namespace cfg { class Config { Config() = delete; Config(const Config&) = delete; Config& operator=(const Config&) = delete; public: static std::string tex_path; static std::string map_path; static sf::Font font; static rm::ResourceManager<std::string,sf::Texture> textureManager; static sf::Vector2i mapMoussPosition; static map::TileIsoHexa moussCursorTile; static sf::Texture moussCursorTex; static sf::Sprite moussCursorSpr; static void clear(); static void drawCursor(sf::RenderWindow& target,sf::RenderStates states = sf::RenderStates::Default); }; }; #endif
23.888889
109
0.660465
Krozark
3c594b0eb36a7306dbd96c581c3e8e92eb371ce0
3,421
cpp
C++
src/core/tree/double_property.cpp
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
4
2018-09-11T14:27:57.000Z
2019-12-16T21:06:26.000Z
src/core/tree/double_property.cpp
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
null
null
null
src/core/tree/double_property.cpp
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
2
2018-06-11T14:15:30.000Z
2019-01-09T12:23:35.000Z
/* * djnn v2 * * The copyright holders for the contents of this file are: * Ecole Nationale de l'Aviation Civile, France (2018-2019) * See file "license.terms" for the rights and conditions * defined by copyright holders. * * * Contributors: * Mathieu Magnaudet <mathieu.magnaudet@enac.fr> * Stephane Conversy <stephane.conversy@enac.fr> * */ #include <stdexcept> #include "double_property.h" #include "core/serializer/serializer.h" #include "core/utils/error.h" #include "core/utils/djnn_dynamic_cast.h" #if !defined(DJNN_NO_DEBUG) || !defined(DJNN_NO_SERIALIZE) #include "core/utils/iostream.h" #endif namespace djnn { double getDouble (CoreProcess* p) { DoubleProperty *dp = djnn_dynamic_cast<DoubleProperty*> (p); if (dp != nullptr) return dp->get_value(); else warning (p, "getDouble only works on double properties"); return 0; } void setDouble (CoreProcess* p, double v) { DoubleProperty *dp = djnn_dynamic_cast<DoubleProperty*> (p); if (dp != nullptr) dp->set_value(v, true); else warning (p, "setDouble only works on double properties"); } void AbstractDoubleProperty::set_value (int v, bool propagate) { set_value((double)v, propagate); } void AbstractDoubleProperty::set_value (double v, bool propagate) { get_ref_value() = v; if (is_activable () && propagate) { notify_activation (); notify_parent (); } } void AbstractDoubleProperty::set_value (bool v, bool propagate) { set_value((double)(v ? 1 : 0), propagate); } void AbstractDoubleProperty::set_value (const string& v, bool propagate) { double oldVal = get_value(); try { if (!v.empty ()) { set_value((double)stof (v), propagate); } } catch (const std::invalid_argument& ia) { get_ref_value() = oldVal; warning (this, "failed to convert the string \"" + v + "\" into a double property value\n"); } } void AbstractDoubleProperty::set_value (CoreProcess* v, bool propagate) { warning (this, "undefined conversion from Process to Double\n"); } #ifndef DJNN_NO_DEBUG void AbstractDoubleProperty::dump (int level) { loginfonofl ( (get_parent () ? get_parent ()->find_child_name(this) : get_name ()) + " [ " + get_string_value() + " ]"); //std::cout << (get_parent () ? get_parent ()->find_child_name(this) : get_name ()) << " [ " << get_value() << " ]"; } #endif #ifndef DJNN_NO_SERIALIZE void AbstractDoubleProperty::serialize (const djnn::string& format) { AbstractSerializer::pre_serialize(this, format); AbstractSerializer::serializer->start ("core:doubleproperty"); AbstractSerializer::serializer->text_attribute ("id", get_name ()); AbstractSerializer::serializer->float_attribute ("value", get_value ()); AbstractSerializer::serializer->end (); AbstractSerializer::post_serialize(this); } #endif DoubleProperty* DoubleProperty::impl_clone (map<CoreProcess*, CoreProcess*>& origs_clones) { auto res = new DoubleProperty (nullptr, get_name (), get_value()); origs_clones[this] = res; return res; } DoublePropertyProxy* DoublePropertyProxy::impl_clone (map<CoreProcess*, CoreProcess*>& origs_clones) { auto res = new DoublePropertyProxy (nullptr, get_name (), get_ref_value()); origs_clones[this] = res; return res; } }
25.529851
124
0.665303
lii-enac
3c596be6e3144042d1bed3be644e4c3d00aa4b60
1,224
cpp
C++
exploringBB/chp10/cgicc/LED.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
1
2019-05-28T18:38:29.000Z
2019-05-28T18:38:29.000Z
exploringBB/chp10/cgicc/LED.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
null
null
null
exploringBB/chp10/cgicc/LED.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
null
null
null
#include "LED.h" LED::LED(int number){ this->number = number; // much easier with C++11 using to_string(number) ostringstream s; // using a stream to contruct the path s << LED_PATH << number; //append LED number to LED_PATH path = string(s.str()); //convert back from stream to string } void LED::writeLED(string filename, string value){ ofstream fs; fs.open((path + filename).c_str()); fs << value; fs.close(); } void LED::removeTrigger(){ writeLED("/trigger", "none"); } void LED::turnOn(){ cout << "Turning LED" << number << " on." << endl; removeTrigger(); writeLED("/brightness", "1"); } void LED::turnOff(){ cout << "Turning LED" << number << " off." << endl; removeTrigger(); writeLED("/brightness", "0"); } void LED::flash(string delayms = "50"){ cout << "Making LED" << number << " flash." << endl; writeLED("/trigger", "timer"); writeLED("/delay_on", delayms); writeLED("/delay_off", delayms); } void LED::outputState(){ ifstream fs; fs.open( (path + "/trigger").c_str()); string line; while(getline(fs,line)) cout << line << endl; fs.close(); } LED::~LED(){ cout << "destroying the LED with path: " << path << endl; }
23.538462
66
0.601307
chaicko
3c5dc6e14cd0646e8e635c18c53db42bb6a9169d
3,351
hpp
C++
third_party/omr/jitbuilder/ilgen/JBIlGeneratorMethodDetails.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/jitbuilder/ilgen/JBIlGeneratorMethodDetails.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/jitbuilder/ilgen/JBIlGeneratorMethodDetails.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2014, 2016 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #ifndef JITBUILDER_ILGENERATOR_METHOD_DETAILS_INCL #define JITBUILDER_ILGENERATOR_METHOD_DETAILS_INCL /* * The following #define and typedef must appear before any #includes in this file */ #ifndef JITBUILDER_ILGENERATOR_METHOD_DETAILS_CONNECTOR #define JITBUILDER_ILGENERATOR_METHOD_DETAILS_CONNECTOR namespace JitBuilder { class IlGeneratorMethodDetails; } namespace JitBuilder { typedef ::JitBuilder::IlGeneratorMethodDetails IlGeneratorMethodDetailsConnector; } #endif // !defined(JITBUILDER_ILGENERATOR_METHOD_DETAILS_CONNECTOR) #include "ilgen/OMRIlGeneratorMethodDetails.hpp" #include "infra/Annotations.hpp" #include "env/IO.hpp" class TR_InlineBlocks; class TR_ResolvedMethod; class TR_IlGenerator; namespace TR { class Compilation; } namespace TR { class ResolvedMethod; } namespace TR { class ResolvedMethodSymbol; } namespace TR { class SymbolReferenceTable; } namespace JitBuilder { class ResolvedMethod; class OMR_EXTENSIBLE IlGeneratorMethodDetails : public OMR::IlGeneratorMethodDetailsConnector { public: IlGeneratorMethodDetails() : OMR::IlGeneratorMethodDetailsConnector(), _method(NULL) { } IlGeneratorMethodDetails(TR::ResolvedMethod *method) : OMR::IlGeneratorMethodDetailsConnector(), _method(method) { } IlGeneratorMethodDetails(TR_ResolvedMethod *method); TR::ResolvedMethod * getMethod() { return _method; } TR_ResolvedMethod * getResolvedMethod() { return (TR_ResolvedMethod *)_method; } bool sameAs(TR::IlGeneratorMethodDetails & other, TR_FrontEnd *fe); void print(TR_FrontEnd *fe, TR::FILE *file); virtual TR_IlGenerator *getIlGenerator(TR::ResolvedMethodSymbol *methodSymbol, TR_FrontEnd * fe, TR::Compilation *comp, TR::SymbolReferenceTable *symRefTab, bool forceClassLookahead, TR_InlineBlocks *blocksToInline); protected: TR::ResolvedMethod * _method; }; } #endif // defined(JITBUILDER_ILGENERATOR_METHOD_DETAILS_INCL)
36.423913
135
0.693524
xiacijie
3c5f504f277e4122e1395f9e39f9dd30f9e43831
1,587
cc
C++
test/h265_sps_scc_extension_parser_unittest.cc
sivapatibandla/h265nal
d128722c717e0656ae64a9fc386c9725bcd26da3
[ "BSD-3-Clause" ]
6
2020-10-05T21:55:52.000Z
2022-03-20T13:28:21.000Z
test/h265_sps_scc_extension_parser_unittest.cc
sivapatibandla/h265nal
d128722c717e0656ae64a9fc386c9725bcd26da3
[ "BSD-3-Clause" ]
5
2020-10-26T13:48:11.000Z
2022-01-28T01:47:19.000Z
test/h265_sps_scc_extension_parser_unittest.cc
sivapatibandla/h265nal
d128722c717e0656ae64a9fc386c9725bcd26da3
[ "BSD-3-Clause" ]
4
2020-10-06T21:08:59.000Z
2022-03-21T06:05:55.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. */ #include "h265_sps_scc_extension_parser.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "h265_common.h" #include "rtc_base/arraysize.h" #include "rtc_base/bit_buffer.h" namespace h265nal { class H265SpsSccExtensionParserTest : public ::testing::Test { public: H265SpsSccExtensionParserTest() {} ~H265SpsSccExtensionParserTest() override {} }; TEST_F(H265SpsSccExtensionParserTest, TestSampleSpsSccExtension) { // sps_scc_extension // fuzzer::conv: data const uint8_t buffer[] = {0x80}; // fuzzer::conv: begin auto sps_scc_extension = H265SpsSccExtensionParser::ParseSpsSccExtension( buffer, arraysize(buffer), /* sps->chroma_format_idc */ 1, /* sps->bit_depth_luma_minus8 */ 0, /* sps->bit_depth_chroma_minus8 */ 0); // fuzzer::conv: end EXPECT_TRUE(sps_scc_extension != nullptr); EXPECT_EQ(1, sps_scc_extension->sps_curr_pic_ref_enabled_flag); EXPECT_EQ(0, sps_scc_extension->palette_mode_enabled_flag); EXPECT_EQ(0, sps_scc_extension->palette_max_size); EXPECT_EQ(0, sps_scc_extension->delta_palette_max_predictor_size); EXPECT_EQ(0, sps_scc_extension->sps_palette_predictor_initializers_present_flag); EXPECT_EQ(0, sps_scc_extension->sps_num_palette_predictor_initializers_minus1); EXPECT_EQ(0, sps_scc_extension->sps_palette_predictor_initializers.size()); EXPECT_EQ(0, sps_scc_extension->motion_vector_resolution_control_idc); EXPECT_EQ(0, sps_scc_extension->intra_boundary_filtering_disabled_flag); } } // namespace h265nal
33.0625
80
0.768746
sivapatibandla
3c5fd1faeca10f416993a5918c9aae8c43a9495e
21,541
hpp
C++
mpi/abstract_comm.hpp
mnakao/graph500
74275945ae6be87ad9f65655ca7af919e04d3c6a
[ "Apache-1.1" ]
1
2022-02-14T19:25:41.000Z
2022-02-14T19:25:41.000Z
mpi/abstract_comm.hpp
mnakao/graph500
74275945ae6be87ad9f65655ca7af919e04d3c6a
[ "Apache-1.1" ]
null
null
null
mpi/abstract_comm.hpp
mnakao/graph500
74275945ae6be87ad9f65655ca7af919e04d3c6a
[ "Apache-1.1" ]
1
2020-07-31T06:22:13.000Z
2020-07-31T06:22:13.000Z
/* * abstract_comm.hpp * * Created on: 2014/05/17 * Author: ueno */ #ifndef ABSTRACT_COMM_HPP_ #define ABSTRACT_COMM_HPP_ #ifdef PROFILE_REGIONS extern int current_fold; #endif #include <limits.h> #include "utils.hpp" #include "fiber.hpp" #define debug(...) debug_print(ABSCO, __VA_ARGS__) class AlltoallBufferHandler { public: virtual ~AlltoallBufferHandler() { } virtual void* get_buffer() = 0; virtual void add(void* buffer, void* data, int offset, int length) = 0; virtual void* clear_buffers() = 0; virtual void* second_buffer() = 0; virtual int max_size() = 0; virtual int buffer_length() = 0; virtual MPI_Datatype data_type() = 0; virtual int element_size() = 0; virtual void received(void* buf, int offset, int length, int from) = 0; virtual void finish() = 0; }; class AsyncAlltoallManager { struct Buffer { void* ptr; int length; }; struct PointerData { void* ptr; int length; int64_t header; }; struct CommTarget { CommTarget() : reserved_size_(0) , filled_size_(0) { cur_buf.ptr = NULL; cur_buf.length = 0; pthread_mutex_init(&send_mutex, NULL); } ~CommTarget() { pthread_mutex_destroy(&send_mutex); } pthread_mutex_t send_mutex; // monitor : send_mutex volatile int reserved_size_; volatile int filled_size_; Buffer cur_buf; std::vector<Buffer> send_data; std::vector<PointerData> send_ptr; }; public: AsyncAlltoallManager(MPI_Comm comm_, AlltoallBufferHandler* buffer_provider_) : comm_(comm_) , buffer_provider_(buffer_provider_) , scatter_(comm_) { CTRACER(AsyncA2A_construtor); MPI_Comm_size(comm_, &comm_size_); node_ = new CommTarget[comm_size_](); d_ = new DynamicDataSet(); pthread_mutex_init(&d_->thread_sync_, NULL); buffer_size_ = buffer_provider_->buffer_length(); } virtual ~AsyncAlltoallManager() { delete [] node_; node_ = NULL; } void prepare() { CTRACER(prepare); debug("prepare idx=%d", sub_comm); for(int i = 0; i < comm_size_; ++i) { node_[i].reserved_size_ = node_[i].filled_size_ = buffer_size_; } } /** * Asynchronous send. * When the communicator receive data, it will call fold_received(FoldCommBuffer*) function. * To reduce the memory consumption, when the communicator detects stacked jobs, * it also process the tasks in the fiber_man_ except the tasks that have the lowest priority (0). * This feature realize the fixed memory consumption. */ void put(void* ptr, int length, int target) { CTRACER(comm_send); if(length == 0) { assert(length > 0); return ; } CommTarget& node = node_[target]; //#if ASYNC_COMM_LOCK_FREE do { int offset = __sync_fetch_and_add(&node.reserved_size_, length); if(offset > buffer_size_) { // wait while(node.reserved_size_ > buffer_size_) ; continue ; } else if(offset + length > buffer_size_) { // swap buffer assert (offset > 0); while(offset != node.filled_size_) ; flush(node); node.cur_buf.ptr = get_send_buffer(); // Maybe, this takes much time. // This order is important. offset = node.filled_size_ = 0; __sync_synchronize(); // membar node.reserved_size_ = length; } buffer_provider_->add(node.cur_buf.ptr, ptr, offset, length); __sync_fetch_and_add(&node.filled_size_, length); break; } while(true); // #endif } void put_ptr(void* ptr, int length, int64_t header, int target) { CommTarget& node = node_[target]; PointerData data = { ptr, length, header }; pthread_mutex_lock(&node.send_mutex); node.send_ptr.push_back(data); pthread_mutex_unlock(&node.send_mutex); } void run_with_ptr() { PROF(profiling::TimeKeeper tk_all); int es = buffer_provider_->element_size(); int max_size = buffer_provider_->max_size() / (es * comm_size_); VERVOSE(last_send_size_ = 0); VERVOSE(last_recv_size_ = 0); const int MINIMUM_POINTER_SPACE = 40; for(int loop = 0; ; ++loop) { USER_START(a2a_merge); #pragma omp parallel { int* counts = scatter_.get_counts(); #pragma omp for schedule(static) for(int i = 0; i < comm_size_; ++i) { CommTarget& node = node_[i]; flush(node); for(int b = 0; b < (int)node.send_data.size(); ++b) { counts[i] += node.send_data[b].length; } for(int b = 0; b < (int)node.send_ptr.size(); ++b) { PointerData& buffer = node.send_ptr[b]; int length = buffer.length; if(length == 0) continue; int size = length + 3; if(counts[i] + size >= max_size) { counts[i] = max_size; break; } counts[i] += size; if(counts[i] + MINIMUM_POINTER_SPACE >= max_size) { // too small space break; } } } // #pragma omp for schedule(static) } scatter_.sum(); if(loop > 0) { int has_data = (scatter_.get_send_count() > 0); MPI_Allreduce(MPI_IN_PLACE, &has_data, 1, MPI_INT, MPI_LOR, comm_); if(has_data == 0) break; } #pragma omp parallel { int* offsets = scatter_.get_offsets(); uint8_t* dst = (uint8_t*)buffer_provider_->second_buffer(); #pragma omp for schedule(static) for(int i = 0; i < comm_size_; ++i) { CommTarget& node = node_[i]; int& offset = offsets[i]; int count = 0; for(int b = 0; b < (int)node.send_data.size(); ++b) { Buffer buffer = node.send_data[b]; void* ptr = buffer.ptr; int length = buffer.length; memcpy(dst + offset * es, ptr, length * es); offset += length; count += length; } for(int b = 0; b < (int)node.send_ptr.size(); ++b) { PointerData& buffer = node.send_ptr[b]; int64_t* ptr = (int64_t*)buffer.ptr; int length = buffer.length; if(length == 0) continue; int size = length + 3; if(count + size >= max_size) { length = max_size - count - 3; count = max_size; } else { count += size; } uint32_t* dst_ptr = (uint32_t*)&dst[offset * es]; dst_ptr[0] = (buffer.header >> 32) | 0x80000000u | 0x40000000u; dst_ptr[1] = (uint32_t)buffer.header; dst_ptr[2] = length; dst_ptr += 3; for(int i = 0; i < length; ++i) { dst_ptr[i] = ptr[i] & 0x7FFFFFFF; } offset += 3 + length; buffer.length -= length; buffer.ptr = (int64_t*)buffer.ptr + length; if(count + MINIMUM_POINTER_SPACE >= max_size) break; } node.send_data.clear(); } // #pragma omp for schedule(static) } // #pragma omp parallel USER_END(a2a_merge); void* sendbuf = buffer_provider_->second_buffer(); void* recvbuf = buffer_provider_->clear_buffers(); MPI_Datatype type = buffer_provider_->data_type(); int recvbufsize = buffer_provider_->max_size(); PROF(merge_time_ += tk_all); USER_START(a2a_comm); VERVOSE(if(loop > 0 && mpi.isMaster()) print_with_prefix("Alltoall with pointer (Again)")); #ifdef PROFILE_REGIONS timer_start(current_fold); #endif scatter_.alltoallv(sendbuf, recvbuf, type, recvbufsize); #ifdef PROFILE_REGIONS timer_stop(current_fold); #endif PROF(comm_time_ += tk_all); USER_END(a2a_comm); VERVOSE(last_send_size_ += scatter_.get_send_count() * es); VERVOSE(last_recv_size_ += scatter_.get_recv_count() * es); int* recv_offsets = scatter_.get_recv_offsets(); #pragma omp parallel for for(int i = 0; i < comm_size_; ++i) { int offset = recv_offsets[i]; int length = recv_offsets[i+1] - offset; buffer_provider_->received(recvbuf, offset, length, i); } PROF(recv_proc_time_ += tk_all); buffer_provider_->finish(); PROF(recv_proc_large_time_ += tk_all); } // clear for(int i = 0; i < comm_size_; ++i) { CommTarget& node = node_[i]; node.send_ptr.clear(); } } void run() { // merge PROF(profiling::TimeKeeper tk_all); int es = buffer_provider_->element_size(); VERVOSE(last_send_size_ = 0); VERVOSE(last_recv_size_ = 0); USER_START(a2a_merge); #pragma omp parallel { int* counts = scatter_.get_counts(); #pragma omp for schedule(static) for(int i = 0; i < comm_size_; ++i) { CommTarget& node = node_[i]; flush(node); for(int b = 0; b < (int)node.send_data.size(); ++b) { counts[i] += node.send_data[b].length; } } // #pragma omp for schedule(static) } scatter_.sum(); #pragma omp parallel { int* offsets = scatter_.get_offsets(); uint8_t* dst = (uint8_t*)buffer_provider_->second_buffer(); #pragma omp for schedule(static) for(int i = 0; i < comm_size_; ++i) { CommTarget& node = node_[i]; int& offset = offsets[i]; for(int b = 0; b < (int)node.send_data.size(); ++b) { Buffer buffer = node.send_data[b]; void* ptr = buffer.ptr; int length = buffer.length; memcpy(dst + offset * es, ptr, length * es); offset += length; } node.send_data.clear(); } // #pragma omp for schedule(static) } // #pragma omp parallel USER_END(a2a_merge); void* sendbuf = buffer_provider_->second_buffer(); void* recvbuf = buffer_provider_->clear_buffers(); MPI_Datatype type = buffer_provider_->data_type(); int recvbufsize = buffer_provider_->max_size(); PROF(merge_time_ += tk_all); USER_START(a2a_comm); #ifdef PROFILE_REGIONS timer_start(current_fold); #endif scatter_.alltoallv(sendbuf, recvbuf, type, recvbufsize); #ifdef PROFILE_REGIONS timer_stop(current_fold); #endif PROF(comm_time_ += tk_all); USER_END(a2a_comm); VERVOSE(last_send_size_ = scatter_.get_send_count() * es); VERVOSE(last_recv_size_ = scatter_.get_recv_count() * es); int* recv_offsets = scatter_.get_recv_offsets(); #pragma omp parallel for schedule(dynamic,1) for(int i = 0; i < comm_size_; ++i) { int offset = recv_offsets[i]; int length = recv_offsets[i+1] - offset; buffer_provider_->received(recvbuf, offset, length, i); } PROF(recv_proc_time_ += tk_all); } #if PROFILING_MODE void submit_prof_info(int level, bool with_ptr) { merge_time_.submit("merge a2a data", level); comm_time_.submit("a2a comm", level); recv_proc_time_.submit("proc recv data", level); if(with_ptr) { recv_proc_large_time_.submit("proc recv large data", level); } VERVOSE(profiling::g_pis.submitCounter(last_send_size_, "a2a send data", level);) VERVOSE(profiling::g_pis.submitCounter(last_recv_size_, "a2a recv data", level);) } #endif #if VERVOSE_MODE int get_last_send_size() { return last_send_size_; } #endif private: struct DynamicDataSet { // lock topology // FoldNode::send_mutex -> thread_sync_ pthread_mutex_t thread_sync_; } *d_; MPI_Comm comm_; int buffer_size_; int comm_size_; int node_list_length_; CommTarget* node_; AlltoallBufferHandler* buffer_provider_; ScatterContext scatter_; PROF(profiling::TimeSpan merge_time_); PROF(profiling::TimeSpan comm_time_); PROF(profiling::TimeSpan recv_proc_time_); PROF(profiling::TimeSpan recv_proc_large_time_); VERVOSE(int last_send_size_); VERVOSE(int last_recv_size_); void flush(CommTarget& node) { if(node.cur_buf.ptr != NULL) { node.cur_buf.length = node.filled_size_; node.send_data.push_back(node.cur_buf); node.cur_buf.ptr = NULL; } } void* get_send_buffer() { CTRACER(get_send_buffer); pthread_mutex_lock(&d_->thread_sync_); void* ret = buffer_provider_->get_buffer(); pthread_mutex_unlock(&d_->thread_sync_); return ret; } }; // Allgather class MpiCompletionHandler { public: virtual ~MpiCompletionHandler() { } virtual void complete(MPI_Status* status) = 0; }; class MpiRequestManager { public: MpiRequestManager(int MAX_REQUESTS) : MAX_REQUESTS(MAX_REQUESTS) , finish_count(0) , reqs(new MPI_Request[MAX_REQUESTS]) , handlers(new MpiCompletionHandler*[MAX_REQUESTS]) { for(int i = 0; i < MAX_REQUESTS; ++i) { reqs[i] = MPI_REQUEST_NULL; empty_list.push_back(i); } } ~MpiRequestManager() { delete [] reqs; reqs = NULL; delete [] handlers; handlers = NULL; } MPI_Request* submit_handler(MpiCompletionHandler* handler) { if(empty_list.size() == 0) { fprintf(IMD_OUT, "No more empty MPI requests...\n"); throw "No more empty MPI requests..."; } int empty = empty_list.back(); empty_list.pop_back(); handlers[empty] = handler; return &reqs[empty]; } void finished() { --finish_count; } void run(int finish_count__) { finish_count += finish_count__; while(finish_count > 0) { if(empty_list.size() == MAX_REQUESTS) { fprintf(IMD_OUT, "Error: No active request\n"); throw "Error: No active request"; } int index; MPI_Status status; MPI_Waitany(MAX_REQUESTS, reqs, &index, &status); if(index == MPI_UNDEFINED) { fprintf(IMD_OUT, "MPI_Waitany returns MPI_UNDEFINED ...\n"); throw "MPI_Waitany returns MPI_UNDEFINED ..."; } MpiCompletionHandler* handler = handlers[index]; reqs[index] = MPI_REQUEST_NULL; empty_list.push_back(index); handler->complete(&status); } } private: int MAX_REQUESTS; int finish_count; MPI_Request *reqs; MpiCompletionHandler** handlers; std::vector<int> empty_list; }; template <typename T> class AllgatherHandler : public MpiCompletionHandler { public: AllgatherHandler() { } virtual ~AllgatherHandler() { } void start(MpiRequestManager* req_man_, T *buffer_, int* count_, int* offset_, MPI_Comm comm_, int rank_, int size_, int left_, int right_, int tag_) { req_man = req_man_; buffer = buffer_; count = count_; offset = offset_; comm = comm_; rank = rank_; size = size_; left = left_; right = right_; tag = tag_; current = 1; l_sendidx = rank; l_recvidx = (rank + size + 1) % size; r_sendidx = rank; r_recvidx = (rank + size - 1) % size; next(); } virtual void complete(MPI_Status* status) { if(++complete_count == 4) { next(); } } private: MpiRequestManager* req_man; T *buffer; int *count; int *offset; MPI_Comm comm; int rank; int size; int left; int right; int tag; int current; int l_sendidx; int l_recvidx; int r_sendidx; int r_recvidx; int complete_count; void next() { if(current >= size) { req_man->finished(); return ; } if(l_sendidx >= size) l_sendidx -= size; if(l_recvidx >= size) l_recvidx -= size; if(r_sendidx < 0) r_sendidx += size; if(r_recvidx < 0) r_recvidx += size; int l_send_off = offset[l_sendidx]; int l_send_cnt = count[l_sendidx] / 2; int l_recv_off = offset[l_recvidx]; int l_recv_cnt = count[l_recvidx] / 2; int r_send_off = offset[r_sendidx] + count[r_sendidx] / 2; int r_send_cnt = count[r_sendidx] - count[r_sendidx] / 2; int r_recv_off = offset[r_recvidx] + count[r_recvidx] / 2; int r_recv_cnt = count[r_recvidx] - count[r_recvidx] / 2; MPI_Irecv(&buffer[l_recv_off], l_recv_cnt, MpiTypeOf<T>::type, right, tag, comm, req_man->submit_handler(this)); MPI_Irecv(&buffer[r_recv_off], r_recv_cnt, MpiTypeOf<T>::type, left, tag, comm, req_man->submit_handler(this)); MPI_Isend(&buffer[l_send_off], l_send_cnt, MpiTypeOf<T>::type, left, tag, comm, req_man->submit_handler(this)); MPI_Isend(&buffer[r_send_off], r_send_cnt, MpiTypeOf<T>::type, right, tag, comm, req_man->submit_handler(this)); ++current; ++l_sendidx; ++l_recvidx; --r_sendidx; --r_recvidx; complete_count = 0; } }; template <typename T> class AllgatherStep1Handler : public MpiCompletionHandler { public: AllgatherStep1Handler() { } virtual ~AllgatherStep1Handler() { } void start(MpiRequestManager* req_man_, T *buffer_, int* count_, int* offset_, COMM_2D comm_, int unit_x_, int unit_y_, int steps_, int tag_) { req_man = req_man_; buffer = buffer_; count = count_; offset = offset_; comm = comm_; unit_x = unit_x_; unit_y = unit_y_; steps = steps_; tag = tag_; current = 1; send_to = get_rank(-1); recv_from = get_rank(1); next(); } virtual void complete(MPI_Status* status) { if(++complete_count == 2) { next(); } } private: MpiRequestManager* req_man; T *buffer; int *count; int *offset; COMM_2D comm; int unit_x; int unit_y; int steps; int tag; int send_to; int recv_from; int current; int complete_count; int get_rank(int diff) { int pos_x = (comm.rank_x + unit_x * diff + comm.size_x) % comm.size_x; int pos_y = (comm.rank_y + unit_y * diff + comm.size_y) % comm.size_y; return comm.rank_map[pos_x + pos_y * comm.size_x]; } void next() { if(current >= steps) { req_man->finished(); return ; } int sendidx = get_rank(current - 1); int recvidx = get_rank(current); int send_off = offset[sendidx]; int send_cnt = count[sendidx]; int recv_off = offset[recvidx]; int recv_cnt = count[recvidx]; MPI_Irecv(&buffer[recv_off], recv_cnt, MpiTypeOf<T>::type, recv_from, tag, comm.comm, req_man->submit_handler(this)); MPI_Isend(&buffer[send_off], send_cnt, MpiTypeOf<T>::type, send_to, tag, comm.comm, req_man->submit_handler(this)); ++current; complete_count = 0; } }; template <typename T> class AllgatherStep2Handler : public MpiCompletionHandler { public: AllgatherStep2Handler() { } virtual ~AllgatherStep2Handler() { } void start(MpiRequestManager* req_man_, T *buffer_, int* count_, int* offset_, COMM_2D comm_, int unit_x_, int unit_y_, int steps_, int width_, int tag_) { req_man = req_man_; buffer = buffer_; count = count_; offset = offset_; comm = comm_; unit_x = unit_x_; unit_y = unit_y_; steps = steps_; width = width_; tag = tag_; current = 1; send_to = get_rank(-1, 0); recv_from = get_rank(1, 0); next(); } virtual void complete(MPI_Status* status) { if(++complete_count == width*2) { next(); } } private: MpiRequestManager* req_man; T *buffer; int *count; int *offset; COMM_2D comm; int unit_x; int unit_y; int steps; int width; int tag; int send_to; int recv_from; int current; int complete_count; int get_rank(int step_diff, int idx) { int pos_x = (comm.rank_x + unit_x * step_diff + (!unit_x * idx) + comm.size_x) % comm.size_x; int pos_y = (comm.rank_y + unit_y * step_diff + (!unit_y * idx) + comm.size_y) % comm.size_y; return comm.rank_map[pos_x + pos_y * comm.size_x]; } void next() { if(current >= steps) { req_man->finished(); return ; } for(int i = 0; i < width; ++i) { int sendidx = get_rank(current - 1, i); int recvidx = get_rank(current, i); int send_off = offset[sendidx]; int send_cnt = count[sendidx]; int recv_off = offset[recvidx]; int recv_cnt = count[recvidx]; MPI_Irecv(&buffer[recv_off], recv_cnt, MpiTypeOf<T>::type, recv_from, tag, comm.comm, req_man->submit_handler(this)); MPI_Isend(&buffer[send_off], send_cnt, MpiTypeOf<T>::type, send_to, tag, comm.comm, req_man->submit_handler(this)); } ++current; complete_count = 0; } }; template <typename T> void my_allgatherv_2d(T *sendbuf, int send_count, T *recvbuf, int* recv_count, int* recv_offset, COMM_2D comm) { // copy own data memcpy(&recvbuf[recv_offset[comm.rank]], sendbuf, sizeof(T) * send_count); if(mpi.isMultiDimAvailable == false) { MpiRequestManager req_man(8); AllgatherHandler<T> handler; int size; MPI_Comm_size(comm.comm, &size); int rank; MPI_Comm_rank(comm.comm, &rank); int left = (rank + size - 1) % size; int right = (rank + size + 1) % size; handler.start(&req_man, recvbuf, recv_count, recv_offset, comm.comm, rank, size, left, right, PRM::MY_EXPAND_TAG1); req_man.run(1); return ; } //MPI_Allgatherv(sendbuf, send_count, MpiTypeOf<T>::type, recvbuf, recv_count, recv_offset, MpiTypeOf<T>::type, comm.comm); //return; MpiRequestManager req_man((comm.size_x + comm.size_y)*4); int split_count[4][comm.size]; int split_offset[4][comm.size]; for(int s = 0; s < 4; ++s) { for(int i = 0; i < comm.size; ++i) { int max = recv_count[i]; int split = (max + 3) / 4; int start = recv_offset[i] + std::min(max, split * s); int end = recv_offset[i] + std::min(max, split * (s+1)); split_count[s][i] = end - start; split_offset[s][i] = start; } } { AllgatherStep1Handler<T> handler[4]; handler[0].start(&req_man, recvbuf, split_count[0], split_offset[0], comm, 1, 0, comm.size_x, PRM::MY_EXPAND_TAG1); handler[1].start(&req_man, recvbuf, split_count[1], split_offset[1], comm,-1, 0, comm.size_x, PRM::MY_EXPAND_TAG1); handler[2].start(&req_man, recvbuf, split_count[2], split_offset[2], comm, 0, 1, comm.size_y, PRM::MY_EXPAND_TAG2); handler[3].start(&req_man, recvbuf, split_count[3], split_offset[3], comm, 0,-1, comm.size_y, PRM::MY_EXPAND_TAG2); req_man.run(4); } { AllgatherStep2Handler<T> handler[4]; handler[0].start(&req_man, recvbuf, split_count[0], split_offset[0], comm, 0, 1, comm.size_y, comm.size_x, PRM::MY_EXPAND_TAG1); handler[1].start(&req_man, recvbuf, split_count[1], split_offset[1], comm, 0,-1, comm.size_y, comm.size_x, PRM::MY_EXPAND_TAG1); handler[2].start(&req_man, recvbuf, split_count[2], split_offset[2], comm, 1, 0, comm.size_x, comm.size_y, PRM::MY_EXPAND_TAG2); handler[3].start(&req_man, recvbuf, split_count[3], split_offset[3], comm,-1, 0, comm.size_x, comm.size_y, PRM::MY_EXPAND_TAG2); req_man.run(4); } } template <typename T> void my_allgather_2d(T *sendbuf, int count, T *recvbuf, COMM_2D comm) { memcpy(&recvbuf[count * comm.rank], sendbuf, sizeof(T) * count); int recv_count[comm.size]; int recv_offset[comm.size+1]; recv_offset[0] = 0; for(int i = 0; i < comm.size; ++i) { recv_count[i] = count; recv_offset[i+1] = recv_offset[i] + count; } my_allgatherv_2d(sendbuf, count, recvbuf, recv_count, recv_offset, comm); } #undef debug #endif /* ABSTRACT_COMM_HPP_ */
26.463145
130
0.671835
mnakao
3c615cb4b0825c7d7b453fe6ec7bf630d9ab6f7e
11,797
cpp
C++
test/test_pool.cpp
twam/etl
a332a8ab336c4bea97579e4c5aa2fdaf216ce9d9
[ "MIT" ]
1
2020-04-09T03:08:56.000Z
2020-04-09T03:08:56.000Z
test/test_pool.cpp
ProgmaticProgrammer/etl
9d8eafe16d46c0db49d8d705a7352e5b67ef8d18
[ "MIT" ]
null
null
null
test/test_pool.cpp
ProgmaticProgrammer/etl
9d8eafe16d46c0db49d8d705a7352e5b67ef8d18
[ "MIT" ]
null
null
null
/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl http://www.etlcpp.com Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "UnitTest++/UnitTest++.h" #include "ExtraCheckMacros.h" #include "data.h" #include <set> #include <vector> #include <string> #include "etl/pool.h" #include "etl/largest.h" #if defined(ETL_COMPILER_GCC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif typedef TestDataDC<std::string> Test_Data; typedef TestDataNDC<std::string> Test_Data2; namespace { struct D0 { D0() { } }; struct D1 { D1(const std::string& a_) : a(a_) { } std::string a; }; struct D2 { D2(const std::string& a_, const std::string& b_) : a(a_), b(b_) { } std::string a; std::string b; }; struct D3 { D3(const std::string& a_, const std::string& b_, const std::string& c_) : a(a_), b(b_), c(c_) { } std::string a; std::string b; std::string c; }; struct D4 { D4(const std::string& a_, const std::string& b_, const std::string& c_, const std::string& d_) : a(a_), b(b_), c(c_), d(d_) { } std::string a; std::string b; std::string c; std::string d; }; bool operator == (const D0&, const D0&) { return true; } bool operator == (const D1& lhs, const D1& rhs) { return (lhs.a == rhs.a); } bool operator == (const D2& lhs, const D2& rhs) { return (lhs.a == rhs.a) && (lhs.b == rhs.b); } bool operator == (const D3& lhs, const D3& rhs) { return (lhs.a == rhs.a) && (lhs.b == rhs.b) && (lhs.c == rhs.c); } bool operator == (const D4& lhs, const D4& rhs) { return (lhs.a == rhs.a) && (lhs.b == rhs.b) && (lhs.c == rhs.c) && (lhs.d == rhs.d); } std::ostream& operator <<(std::ostream& os, const D0&) { return os; } std::ostream& operator <<(std::ostream& os, const D1& d) { os << d.a; return os; } std::ostream& operator <<(std::ostream& os, const D2& d) { os << d.a << " " << d.b; return os; } std::ostream& operator <<(std::ostream& os, const D3& d) { os << d.a << " " << d.b << " " << d.c; return os; } std::ostream& operator <<(std::ostream& os, const D4& d) { os << d.a << " " << d.b << " " << d.c << " " << d.d; return os; } SUITE(test_pool) { //************************************************************************* TEST(test_allocate) { etl::pool<Test_Data, 4> pool; Test_Data* p1 = nullptr; Test_Data* p2 = nullptr; Test_Data* p3 = nullptr; Test_Data* p4 = nullptr; CHECK_NO_THROW(p1 = pool.allocate<Test_Data>()); CHECK_NO_THROW(p2 = pool.allocate<Test_Data>()); CHECK_NO_THROW(p3 = pool.allocate<Test_Data>()); CHECK_NO_THROW(p4 = pool.allocate<Test_Data>()); CHECK(p1 != p2); CHECK(p1 != p3); CHECK(p1 != p4); CHECK(p2 != p3); CHECK(p2 != p4); CHECK(p3 != p4); CHECK_THROW(pool.allocate<Test_Data>(), etl::pool_no_allocation); } //************************************************************************* TEST(test_release) { etl::pool<Test_Data, 4> pool; Test_Data* p1 = pool.allocate<Test_Data>(); Test_Data* p2 = pool.allocate<Test_Data>(); Test_Data* p3 = pool.allocate<Test_Data>(); Test_Data* p4 = pool.allocate<Test_Data>(); CHECK_NO_THROW(pool.release(p2)); CHECK_NO_THROW(pool.release(p3)); CHECK_NO_THROW(pool.release(p1)); CHECK_NO_THROW(pool.release(p4)); CHECK_EQUAL(4U, pool.available()); Test_Data not_in_pool; CHECK_THROW(pool.release(&not_in_pool), etl::pool_object_not_in_pool); } //************************************************************************* TEST(test_allocate_release) { etl::pool<Test_Data, 4> pool; Test_Data* p1 = pool.allocate<Test_Data>(); Test_Data* p2 = pool.allocate<Test_Data>(); Test_Data* p3 = pool.allocate<Test_Data>(); Test_Data* p4 = pool.allocate<Test_Data>(); // Allocated p1, p2, p3, p4 CHECK_EQUAL(0U, pool.available()); CHECK_NO_THROW(pool.release(p2)); CHECK_NO_THROW(pool.release(p3)); // Allocated p1, p4 CHECK_EQUAL(2U, pool.available()); Test_Data* p5 = pool.allocate<Test_Data>(); Test_Data* p6 = pool.allocate<Test_Data>(); // Allocated p1, p4, p5, p6 CHECK_EQUAL(0U, pool.available()); CHECK(p5 != p1); CHECK(p5 != p4); CHECK(p6 != p1); CHECK(p6 != p4); CHECK_NO_THROW(pool.release(p5)); // Allocated p1, p4, p6 CHECK_EQUAL(1U, pool.available()); Test_Data* p7 = pool.allocate<Test_Data>(); // Allocated p1, p4, p6, p7 CHECK(p7 != p1); CHECK(p7 != p4); CHECK(p7 != p6); CHECK(pool.full()); } //************************************************************************* TEST(test_available) { etl::pool<Test_Data, 4> pool; CHECK_EQUAL(4U, pool.available()); Test_Data* p; p = pool.allocate<Test_Data>(); CHECK_EQUAL(3U, pool.available()); p = pool.allocate<Test_Data>(); CHECK_EQUAL(2U, pool.available()); p = pool.allocate<Test_Data>(); CHECK_EQUAL(1U, pool.available()); p = pool.allocate<Test_Data>(); CHECK_EQUAL(0U, pool.available()); } //************************************************************************* TEST(test_max_size) { etl::pool<Test_Data, 4> pool; CHECK(pool.max_size() == 4U); } //************************************************************************* TEST(test_size) { etl::pool<Test_Data, 4> pool; CHECK_EQUAL(0U, pool.size()); Test_Data* p; p = pool.allocate<Test_Data>(); CHECK_EQUAL(1U, pool.size()); p = pool.allocate<Test_Data>(); CHECK_EQUAL(2U, pool.size()); p = pool.allocate<Test_Data>(); CHECK_EQUAL(3U, pool.size()); p = pool.allocate<Test_Data>(); CHECK_EQUAL(4U, pool.size()); } //************************************************************************* TEST(test_empty_full) { etl::pool<Test_Data, 4> pool; CHECK(pool.empty()); CHECK(!pool.full()); Test_Data* p; p = pool.allocate<Test_Data>(); CHECK(!pool.empty()); CHECK(!pool.full()); p = pool.allocate<Test_Data>(); CHECK(!pool.empty()); CHECK(!pool.full()); p = pool.allocate<Test_Data>(); CHECK(!pool.empty()); CHECK(!pool.full()); p = pool.allocate<Test_Data>(); CHECK(!pool.empty()); CHECK(pool.full()); } //************************************************************************* TEST(test_is_in_pool) { etl::pool<Test_Data, 4> pool; Test_Data not_in_pool; Test_Data* p1 = pool.allocate<Test_Data>(); CHECK(pool.is_in_pool(p1)); CHECK(!pool.is_in_pool(&not_in_pool)); } //************************************************************************* TEST(test_generic_storage) { union Storage { uint64_t dummy; // For alignment purposes. char buffer[1000]; }; etl::pool<Storage, 4> pool; Test_Data* pdata = pool.allocate<Test_Data>(); new (pdata) Test_Data("ABC", 3); etl::array<int, 10>* parray = pool.allocate<etl::array<int, 10>>(); new (parray) etl::array<int, 10>(); parray->fill(0x12345678); etl::array<int, 10> compare; compare.fill(0x12345678); CHECK(pdata->value == "ABC"); CHECK(pdata->index == 3); CHECK(*parray == compare); pool.release(parray); pool.release(pdata); CHECK_EQUAL(4U, pool.available()); } //************************************************************************* TEST(test_type_error) { struct Test { uint64_t a; uint64_t b; }; etl::pool<uint32_t, 4> pool; etl::ipool& ip = pool; CHECK_THROW(ip.allocate<Test>(), etl::pool_element_size); } //************************************************************************* TEST(test_generic_allocate) { typedef etl::largest<uint8_t, uint32_t, double, Test_Data> largest; etl::generic_pool<largest::size, largest::alignment, 4> pool; uint8_t* p1 = nullptr; uint32_t* p2 = nullptr; double* p3 = nullptr; Test_Data* p4 = nullptr; CHECK_NO_THROW(p1 = pool.allocate<uint8_t>()); CHECK_NO_THROW(p2 = pool.allocate<uint32_t>()); CHECK_NO_THROW(p3 = pool.allocate<double>()); CHECK_NO_THROW(p4 = pool.allocate<Test_Data>()); } }; //************************************************************************* TEST(test_create_destroy) { etl::pool<D0, 4> pool0; etl::pool<D1, 4> pool1; etl::pool<D2, 4> pool2; etl::pool<D3, 4> pool3; etl::pool<D4, 4> pool4; D0* p0 = pool0.create<D0>(); D1* p1 = pool1.create<D1>("1"); D2* p2 = pool2.create<D2>("1", "2"); D3* p3 = pool3.create<D3>("1", "2", "3"); D4* p4 = pool4.create<D4>("1", "2", "3", "4"); CHECK_EQUAL(pool0.max_size() - 1, pool0.available()); CHECK_EQUAL(1U, pool0.size()); CHECK_EQUAL(pool1.max_size() - 1, pool1.available()); CHECK_EQUAL(1U, pool1.size()); CHECK_EQUAL(pool2.max_size() - 1, pool2.available()); CHECK_EQUAL(1U, pool2.size()); CHECK_EQUAL(pool3.max_size() - 1, pool3.available()); CHECK_EQUAL(1U, pool3.size()); CHECK_EQUAL(pool4.max_size() - 1, pool4.available()); CHECK_EQUAL(1U, pool4.size()); CHECK_EQUAL(D0(), *p0); CHECK_EQUAL(D1("1"), *p1); CHECK_EQUAL(D2("1", "2"), *p2); CHECK_EQUAL(D3("1", "2", "3"), *p3); CHECK_EQUAL(D4("1", "2", "3", "4"), *p4); pool0.destroy<D0>(p0); pool1.destroy<D1>(p1); pool2.destroy<D2>(p2); pool3.destroy<D3>(p3); pool4.destroy<D4>(p4); CHECK_EQUAL(pool0.max_size(), pool0.available()); CHECK_EQUAL(0U, pool0.size()); CHECK_EQUAL(pool1.max_size(), pool1.available()); CHECK_EQUAL(0U, pool1.size()); CHECK_EQUAL(pool2.max_size(), pool2.available()); CHECK_EQUAL(0U, pool2.size()); CHECK_EQUAL(pool3.max_size(), pool3.available()); CHECK_EQUAL(0U, pool3.size()); CHECK_EQUAL(pool4.max_size(), pool4.available()); CHECK_EQUAL(0U, pool4.size()); } } #if defined(ETL_COMPILER_GCC) #pragma GCC diagnostic pop #endif
24.577083
98
0.535645
twam
3c6523550f9e948f6130c60fbdaeed277dbce5a3
1,353
hpp
C++
sdk/structs.hpp
Nixer1337/gmod-sdk
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
[ "MIT" ]
6
2020-03-30T05:11:50.000Z
2021-02-08T02:26:29.000Z
sdk/structs.hpp
Nixer1337/gmod-sdk
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
[ "MIT" ]
1
2020-12-05T11:18:51.000Z
2020-12-27T18:34:22.000Z
sdk/structs.hpp
Nixer1337/gmod-sdk
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
[ "MIT" ]
2
2020-03-24T15:27:38.000Z
2022-03-03T17:32:31.000Z
#pragma once #include "vfunc.hpp" #include "../utilities/utilities.hpp" #include "../utilities/math.hpp" #include "../utilities/netvars.hpp" #define NETVAR(type, name, table, netvar) \ type& name##() const { \ static const auto _##name = Netvars::GetOffset(hash::fnv1a_32(table), hash::fnv1a_32(netvar)); \ return *(type*)(uintptr_t(this) + _##name); \ } class CWeapon; class CEntity { public: int GetFlags(); size_t GetIndex(); NETVAR(uintptr_t, m_hActiveWeapon, "DT_BaseCombatCharacter", "m_hActiveWeapon"); NETVAR(uintptr_t, m_vecOrigin, "DT_BaseEntity", "m_vecOrigin"); CWeapon* GetActiveWeapon(); const char* GetClassName(); bool IsNPC(); bool IsPlayer(); bool IsDormant(); bool IsAlive(); int GetHealth(); int GetMaxHealth(); Vector GetViewOffset(); Vector GetEyePos(); Vector& GetAbsOrigin(); bool SetupBones(matrix3x4_t* pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime); void* GetModel(); int& GetTickBase(); }; class CWeapon { public: bool UsesLua(); bool PushEntity(); bool HasPrimaryAmmo(); float LUASpread(); const char* GetWeaponBase(); float TTTSpread(); float LUASpread2(); const Vector& orgGetBulletSpread(); Vector GetBulletSpread(); const char* GetName(); bool IsExplosive(); bool IsHoldingTool(); bool IsNospreadWeapon(); float m_flNextPrimaryAttack(); bool CanFire(); };
23.327586
98
0.716925
Nixer1337
3c652c2ed79d4044f0bf8180c6246000adb12d5a
476
hpp
C++
src/core/lib/core_qt_common/qt_resource_system.hpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_qt_common/qt_resource_system.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_qt_common/qt_resource_system.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#ifndef QT_RESOURCE_SYSTEM_HPP #define QT_RESOURCE_SYSTEM_HPP #include "core_dependency_system/i_interface.hpp" #include "core_serialization/i_resource_system.hpp" namespace wgt { class QtResourceSystem : public Implements<IResourceSystem> { public: QtResourceSystem(); virtual ~QtResourceSystem(); virtual bool exists(const char* resource) const override; virtual BinaryBlockPtr readBinaryContent(const char* resource) const override; }; } // end namespace wgt #endif
23.8
79
0.815126
wgsyd
3c657086cadbc5031299384fa1eb3e70c24b4038
560
hpp
C++
Siv3D/include/Siv3D/InputDevice.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
709
2016-03-19T07:55:58.000Z
2022-03-31T08:02:22.000Z
Siv3D/include/Siv3D/InputDevice.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
415
2017-05-21T05:05:02.000Z
2022-03-29T16:08:27.000Z
Siv3D/include/Siv3D/InputDevice.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
123
2016-03-19T12:47:08.000Z
2022-03-25T03:47:51.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Common.hpp" namespace s3d { /// @brief 入力デバイスの種類 enum class InputDeviceType : uint8 { /// @brief 未定義 Undefined, /// @brief キーボード Keyboard, /// @brief マウス Mouse, /// @brief ゲームパッド Gamepad, /// @brief XInput 対応ゲームコントローラー XInput, }; }
15.555556
50
0.523214
emadurandal
3c664286581b4bceda140fe32248da790b15559b
269
cpp
C++
12-coding-practice-problems/12.40-functions-number-to-words/main.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
2
2020-09-04T22:06:06.000Z
2020-09-09T04:00:25.000Z
12-coding-practice-problems/12.40-functions-number-to-words/main.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
14
2020-08-24T01:44:36.000Z
2021-01-01T08:44:17.000Z
12-coding-practice-problems/12.40-functions-number-to-words/main.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
1
2020-09-04T22:13:13.000Z
2020-09-04T22:13:13.000Z
#include <iostream> #include <string> using namespace std; string DigitToWord(int digitIn) { // FINISH } string TensDigitToWord(int digitIn) { // FINISH } string TwoDigitNumToWords(int numIn) { // FINISH } int main() { // FINISH return 0; }
8.966667
38
0.643123
trangnart
3c69914c1a2306008d9e2f042155d8a0ddae948a
6,599
hpp
C++
ql/models/shortrate/twofactormodels/g2.hpp
SoftwareIngenieur/QuantLib
7a59dd749869f7a679536df322482bf9c6531d38
[ "BSD-3-Clause" ]
null
null
null
ql/models/shortrate/twofactormodels/g2.hpp
SoftwareIngenieur/QuantLib
7a59dd749869f7a679536df322482bf9c6531d38
[ "BSD-3-Clause" ]
null
null
null
ql/models/shortrate/twofactormodels/g2.hpp
SoftwareIngenieur/QuantLib
7a59dd749869f7a679536df322482bf9c6531d38
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb Copyright (C) 2004 Mike Parker This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file g2.hpp \brief Two-factor additive Gaussian Model G2++ */ #ifndef quantlib_two_factor_models_g2_h #define quantlib_two_factor_models_g2_h #include <ql/models/shortrate/twofactormodel.hpp> #include <ql/processes/ornsteinuhlenbeckprocess.hpp> #include <ql/instruments/swaption.hpp> namespace QuantLib { //! Two-additive-factor gaussian model class. /*! This class implements a two-additive-factor model defined by \f[ dr_t = \varphi(t) + x_t + y_t \f] where \f$ x_t \f$ and \f$ y_t \f$ are defined by \f[ dx_t = -a x_t dt + \sigma dW^1_t, x_0 = 0 \f] \f[ dy_t = -b y_t dt + \sigma dW^2_t, y_0 = 0 \f] and \f$ dW^1_t dW^2_t = \rho dt \f$. \bug This class was not tested enough to guarantee its functionality. \ingroup shortrate */ class G2 : public TwoFactorModel, public AffineModel, public TermStructureConsistentModel { public: G2(const Handle<YieldTermStructure>& termStructure, Real a = 0.1, Real sigma = 0.01, Real b = 0.1, Real eta = 0.01, Real rho = -0.75); ext::shared_ptr<ShortRateDynamics> dynamics() const override; Real discountBond(Time now, Time maturity, Array factors) const override { QL_REQUIRE(factors.size()>1, "g2 model needs two factors to compute discount bond"); return discountBond(now, maturity, factors[0], factors[1]); } Real discountBond(Time, Time, Rate, Rate) const; Real discountBondOption(Option::Type type, Real strike, Time maturity, Time bondMaturity) const override; Real swaption(const Swaption::arguments& arguments, Rate fixedRate, Real range, Size intervals) const; DiscountFactor discount(Time t) const override { return termStructure()->discount(t); } Real a() const { return a_(0.0); } Real sigma() const { return sigma_(0.0); } Real b() const { return b_(0.0); } Real eta() const { return eta_(0.0); } Real rho() const { return rho_(0.0); } protected: void generateArguments() override; Real A(Time t, Time T) const; Real B(Real x, Time t) const; private: class Dynamics; class FittingParameter; Real sigmaP(Time t, Time s) const; Parameter& a_; Parameter& sigma_; Parameter& b_; Parameter& eta_; Parameter& rho_; Parameter phi_; Real V(Time t) const; class SwaptionPricingFunction; friend class SwaptionPricingFunction; }; class G2::Dynamics : public TwoFactorModel::ShortRateDynamics { public: Dynamics(const Parameter& fitting, Real a, Real sigma, Real b, Real eta, Real rho) : ShortRateDynamics(ext::shared_ptr<StochasticProcess1D>( new OrnsteinUhlenbeckProcess(a, sigma)), ext::shared_ptr<StochasticProcess1D>( new OrnsteinUhlenbeckProcess(b, eta)), rho), fitting_(fitting) {} Rate shortRate(Time t, Real x, Real y) const override { return fitting_(t) + x + y; } private: Parameter fitting_; }; //! Analytical term-structure fitting parameter \f$ \varphi(t) \f$. /*! \f$ \varphi(t) \f$ is analytically defined by \f[ \varphi(t) = f(t) + \frac{1}{2}(\frac{\sigma(1-e^{-at})}{a})^2 + \frac{1}{2}(\frac{\eta(1-e^{-bt})}{b})^2 + \rho\frac{\sigma(1-e^{-at})}{a}\frac{\eta(1-e^{-bt})}{b}, \f] where \f$ f(t) \f$ is the instantaneous forward rate at \f$ t \f$. */ class G2::FittingParameter : public TermStructureFittingParameter { private: class Impl : public Parameter::Impl { public: Impl(const Handle<YieldTermStructure>& termStructure, Real a, Real sigma, Real b, Real eta, Real rho) : termStructure_(termStructure), a_(a), sigma_(sigma), b_(b), eta_(eta), rho_(rho) {} Real value(const Array&, Time t) const override { Rate forward = termStructure_->forwardRate(t, t, Continuous, NoFrequency); Real temp1 = sigma_*(1.0-std::exp(-a_*t))/a_; Real temp2 = eta_*(1.0-std::exp(-b_*t))/b_; Real value = 0.5*temp1*temp1 + 0.5*temp2*temp2 + rho_*temp1*temp2 + forward; return value; } private: Handle<YieldTermStructure> termStructure_; Real a_, sigma_, b_, eta_, rho_; }; public: FittingParameter(const Handle<YieldTermStructure>& termStructure, Real a, Real sigma, Real b, Real eta, Real rho) : TermStructureFittingParameter(ext::shared_ptr<Parameter::Impl>( new FittingParameter::Impl(termStructure, a, sigma, b, eta, rho))) {} }; } #endif
34.19171
95
0.537203
SoftwareIngenieur
3c6c6344c979d9380ecd68baee34ced672ac3cf7
957
hpp
C++
include/blackhole/config/json.hpp
JakariaBlaine/blackhole
e340329c6e2e3166858d8466656ad12300b686bd
[ "MIT" ]
193
2015-01-05T08:48:05.000Z
2022-01-31T22:04:01.000Z
include/blackhole/config/json.hpp
JakariaBlaine/blackhole
e340329c6e2e3166858d8466656ad12300b686bd
[ "MIT" ]
135
2015-01-13T13:02:49.000Z
2022-01-12T15:06:48.000Z
include/blackhole/config/json.hpp
JakariaBlaine/blackhole
e340329c6e2e3166858d8466656ad12300b686bd
[ "MIT" ]
40
2015-01-21T16:37:30.000Z
2022-01-25T15:54:04.000Z
#pragma once #include <memory> #include "factory.hpp" namespace blackhole { inline namespace v1 { namespace config { class json_t; template<> class factory_traits<json_t> { public: /// Constructs and initializes the JSON config factory by reading the given stream reference /// until EOF and parsing its content. /// /// The content should be valid JSON object. /// /// \param stream lvalue reference to the input stream. static auto construct(std::istream& stream) -> std::unique_ptr<factory_t>; /// Constructs and initializes the JSON config factory by reading the given stream until EOF /// and parsing its content. /// /// The content should be valid JSON object. /// /// \overload /// \param stream rvalue reference to the input stream. static auto construct(std::istream&& stream) -> std::unique_ptr<factory_t>; }; } // namespace config } // namespace v1 } // namespace blackhole
25.864865
97
0.684431
JakariaBlaine
3c6c86b19599f0796b26798ce8f6030d24436cc9
1,725
cpp
C++
Day_18/03_Diameter.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_18/03_Diameter.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_18/03_Diameter.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
// Problem Link: // https://leetcode.com/problems/diameter-of-binary-tree/ // Approach 1 // TC: O(n^2) // SC: O(n) // Approach 2 // TC: O(n) // SC: O(n) #include <bits/stdc++.h> using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" class TreeNode { public: TreeNode *left; int val; TreeNode *right; TreeNode() { TreeNode(-1); } TreeNode(int _val) : left(NULL), val(_val), right(NULL) {} }; // Approach 1 int maxHeight(TreeNode *root) { if (!root) return 0; return max(maxHeight(root->left) + 1, maxHeight(root->right) + 1); } int diameterOfBinaryTree1(TreeNode *root) { if (!root) return 0; int currMax = maxHeight(root->left) + maxHeight(root->right); currMax = max(diameterOfBinaryTree1(root->left), currMax); currMax = max(diameterOfBinaryTree1(root->right), currMax); return currMax; } // Approach 2 int helper(TreeNode *root, int &res) { if (!root) return 0; int leftDia = helper(root->left, res); int rightDia = helper(root->right, res); res = max(res, leftDia + rightDia); return max(leftDia + 1, rightDia + 1); } int diameterOfBinaryTree2(TreeNode *root) { int res{}; helper(root, res); return res; } void solve() { TreeNode *root = new TreeNode(10); root->left = new TreeNode(20); root->right = new TreeNode(30); root->left->left = new TreeNode(40); root->left->right = new TreeNode(60); cout << diameterOfBinaryTree1(root) << endl; cout << diameterOfBinaryTree2(root) << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
19.166667
70
0.602899
premnaaath
3c6dbf6181ebfd729aace0f3fa9fdde3177e7939
704
cc
C++
CPP/No744.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
CPP/No744.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
CPP/No744.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
/** * Created by Xiaozhong on 2020/11/27. * Copyright (c) 2020/11/27 Xiaozhong. All rights reserved. */ #include <vector> #include <iostream> #include <algorithm> using namespace std; class Solution { public: char nextGreatestLetter(vector<char> &letters, char target) { vector<char>::iterator iter = upper_bound(letters.begin(), letters.end(), target); if (iter == letters.end()) iter = letters.begin(); return *iter; } }; int main() { Solution s; vector<char> letters = {'c', 'f', 'j'}; cout << s.nextGreatestLetter(letters, 'g') << endl; cout << s.nextGreatestLetter(letters, 'j') << endl; cout << s.nextGreatestLetter(letters, 'k') << endl; }
27.076923
90
0.632102
hxz1998
3c70d93e4c7540924f3bec69553882eead15655f
4,164
cpp
C++
ImportantExample/cuteReportView/cutereport/src/thirdparty/propertyeditor/plugins/stringlist/stringlist.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/CuteReport/src/thirdparty/propertyeditor/plugins/stringlist/stringlist.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/CuteReport/src/thirdparty/propertyeditor/plugins/stringlist/stringlist.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
/*************************************************************************** * This file is part of the propertyEditor project * * Copyright (C) 2008 by BogDan Vatra * * bog_dan_ro@yahoo.com * ** GNU General Public License Usage ** * * * This library is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ** GNU Lesser General Public License ** * * * This library is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public * * License along with this library. * * If not, see <http://www.gnu.org/licenses/>. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ****************************************************************************/ #include <QtCore> #include <QMetaProperty> #include <QMetaEnum> #include <QPushButton> #include "stringlist.h" #include "stringlisteditor.h" //inline void initMyResource() //{ // Q_INIT_RESOURCE(stringlist); //} StringList::StringList(QObject* parent, QObject* object, int property, const PropertyModel * propertyModel): PropertyInterface(parent, object, property, propertyModel) { // initMyResource(); } QWidget* StringList::createEditor(QWidget * parent, const QModelIndex & index) { Q_UNUSED(index); QPushButton * bt = new QPushButton(parent); bt->setText(tr("Change stringlist")); connect(bt, SIGNAL(pressed()), this, SLOT(buttonPressed())); return bt; } void StringList::buttonPressed() { int result; QStringList lst = StringListEditor::getStringList(0, value().toStringList(), &result); if (result == QDialog::Accepted) setValue(lst); } QVariant StringList::data(const QModelIndex & index) { if (!index.isValid() || !object() || -1 == objectProperty()) return QVariant(); switch (index.column()) { case 0: return object()->metaObject()->property(objectProperty()).name(); case 1: QString s = "{" + value().toStringList().join(", ") + "}"; return s; } return QVariant(); } bool StringList::setData(QVariant data, const QModelIndex & index) { Q_UNUSED(index); return PropertyInterface::setValue(data); } bool StringList::canHandle(QObject * object, int property)const { if (object->metaObject()->property(property).isEnumType() || object->metaObject()->property(property).isFlagType()) return false; switch (object->property(object->metaObject()->property(property).name()).type()) { case QVariant::StringList: return true; default: return false; } } PropertyInterface* StringList::createInstance(QObject * object, int property, const PropertyModel * propertyModel) const { return new StringList(parent(), object, property, propertyModel); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(StringListProperty, StringList) #endif
36.849558
167
0.568924
xiaohaijin
3c71ba99bd1635633681209b7552b93ae1c90c87
18,068
cpp
C++
ksp_plugin_test/plugin_compatibility_test.cpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
2
2016-02-14T21:18:48.000Z
2017-02-11T23:23:20.000Z
ksp_plugin_test/plugin_compatibility_test.cpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
1
2015-07-27T21:27:46.000Z
2015-07-27T21:27:46.000Z
ksp_plugin_test/plugin_compatibility_test.cpp
pleroy/Principia
64c4c6c124f4744381b6489e39e6b53e2a440ce9
[ "MIT" ]
null
null
null
 #include <memory> #include <string> #include <utility> #include <vector> #include "astronomy/time_scales.hpp" #include "astronomy/mercury_orbiter.hpp" #include "base/array.hpp" #include "base/file.hpp" #include "base/not_null.hpp" #include "base/pull_serializer.hpp" #include "base/push_deserializer.hpp" #include "base/serialization.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin/frames.hpp" #include "ksp_plugin/interface.hpp" #include "ksp_plugin/plugin.hpp" #include "physics/discrete_trajectory.hpp" #include "serialization/ksp_plugin.pb.h" #include "testing_utilities/is_near.hpp" #include "testing_utilities/serialization.hpp" #include "testing_utilities/string_log_sink.hpp" namespace principia { namespace interface { using astronomy::operator""_TT; using astronomy::MercuryOrbiterInitialDegreesOfFreedom; using astronomy::MercuryOrbiterInitialTime; using astronomy::TTSecond; using astronomy::date_time::DateTime; using astronomy::date_time::operator""_DateTime; using base::not_null; using base::OFStream; using base::ParseFromBytes; using base::PullSerializer; using base::PushDeserializer; using ksp_plugin::Barycentric; using ksp_plugin::Plugin; using physics::DiscreteTrajectory; using quantities::Speed; using quantities::si::Degree; using quantities::si::Kilo; using quantities::si::Second; using testing_utilities::operator""_⑴; using testing_utilities::IsNear; using testing_utilities::ReadFromBinaryFile; using testing_utilities::ReadLinesFromBase64File; using testing_utilities::ReadLinesFromHexadecimalFile; using testing_utilities::StringLogSink; using testing_utilities::WriteToBinaryFile; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Not; using ::testing::NotNull; using ::testing::Pair; using ::testing::SizeIs; using ::testing::internal::CaptureStderr; using ::testing::internal::GetCapturedStderr; const char preferred_compressor[] = "gipfeli"; const char preferred_encoder[] = "base64"; class PluginCompatibilityTest : public testing::Test { protected: PluginCompatibilityTest() : stderrthreshold_(FLAGS_stderrthreshold) { google::SetStderrLogging(google::WARNING); } ~PluginCompatibilityTest() override { google::SetStderrLogging(stderrthreshold_); } // Reads a plugin from a file containing only the "serialized_plugin = " // lines, with "serialized_plugin = " dropped. static not_null<std::unique_ptr<Plugin const>> ReadPluginFromFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { Plugin const* plugin = nullptr; PushDeserializer* deserializer = nullptr; auto const lines = encoder == "hexadecimal" ? ReadLinesFromHexadecimalFile(filename) : encoder == "base64" ? ReadLinesFromBase64File(filename) : std::vector<std::string>{}; CHECK(!lines.empty()); LOG(ERROR) << "Deserialization starting"; for (std::string const& line : lines) { principia__DeserializePlugin(line.c_str(), &deserializer, &plugin, compressor.data(), encoder.data()); } principia__DeserializePlugin("", &deserializer, &plugin, compressor.data(), encoder.data()); LOG(ERROR) << "Deserialization complete"; return std::unique_ptr<Plugin const>(plugin); } // Writes a plugin to a file. static void WritePluginToFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder, not_null<std::unique_ptr<Plugin const>> plugin) { OFStream file(filename); PullSerializer* serializer = nullptr; char const* b64 = nullptr; LOG(ERROR) << "Serialization starting"; for (;;) { b64 = principia__SerializePlugin(plugin.get(), &serializer, preferred_compressor, preferred_encoder); if (b64 == nullptr) { break; } file << b64 << "\n"; principia__DeleteString(&b64); } LOG(ERROR) << "Serialization complete"; Plugin const* released_plugin = plugin.release(); principia__DeletePlugin(&released_plugin); } static void WriteAndReadBack( not_null<std::unique_ptr<Plugin const>> plugin1) { // Write the plugin to a new file with the preferred format. WritePluginToFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder, std::move(plugin1)); // Read the plugin from the new file to make sure that it's fine. auto plugin2 = ReadPluginFromFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder); } static void CheckSaveCompatibility(std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { // Read a plugin from the given file. auto plugin = ReadPluginFromFile(filename, compressor, encoder); WriteAndReadBack(std::move(plugin)); } int const stderrthreshold_; }; TEST_F(PluginCompatibilityTest, PreCartan) { // This space for rent. } TEST_F(PluginCompatibilityTest, PreCohen) { StringLogSink log_warning(google::WARNING); CheckSaveCompatibility( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3039.proto.hex", /*compressor=*/"", /*decoder=*/"hexadecimal"); EXPECT_THAT( log_warning.string(), AllOf( HasSubstr( "pre-Cohen ContinuousTrajectory"), // Regression test for #3039. HasSubstr("pre-Cauchy"), // The save is even older. Not(HasSubstr("pre-Cartan")))); // But not *that* old. } #if !_DEBUG TEST_F(PluginCompatibilityTest, Reach) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3072.proto.b64", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Galileo"), Not(HasSubstr("pre-Frobenius")))); auto const test = plugin->GetVessel("f2d77873-4776-4809-9dfb-de9e7a0620a6"); EXPECT_THAT(test->name(), Eq("TEST")); EXPECT_THAT(TTSecond(test->history()->front().time), Eq("1970-08-14T08:03:18"_DateTime)); EXPECT_THAT(TTSecond(test->psychohistory()->back().time), Eq("1970-08-14T08:47:05"_DateTime)); EXPECT_FALSE(test->has_flight_plan()); auto const ifnity = plugin->GetVessel("29142a79-7acd-47a9-a34d-f9f2a8e1b4ed"); EXPECT_THAT(ifnity->name(), Eq("IFNITY-5.2")); EXPECT_THAT(TTSecond(ifnity->history()->front().time), Eq("1970-08-14T08:03:46"_DateTime)); EXPECT_THAT(TTSecond(ifnity->psychohistory()->back().time), Eq("1970-08-14T08:47:05"_DateTime)); ASSERT_TRUE(ifnity->has_flight_plan()); EXPECT_THAT(ifnity->flight_plan().number_of_manœuvres(), Eq(16)); std::vector<std::pair<DateTime, Speed>> manœuvre_ignition_tt_seconds_and_Δvs; for (int i = 0; i < ifnity->flight_plan().number_of_manœuvres(); ++i) { manœuvre_ignition_tt_seconds_and_Δvs.emplace_back( TTSecond(ifnity->flight_plan().GetManœuvre(i).initial_time()), ifnity->flight_plan().GetManœuvre(i).Δv().Norm()); } // The flight plan only covers the inner solar system (this is probably // because of #3035). // It also differs from https://youtu.be/7BDxZV7UD9I?t=439. // TODO(egg): Compute the flybys and figure out what exactly is going on in // this flight plan. EXPECT_THAT(manœuvre_ignition_tt_seconds_and_Δvs, ElementsAre(Pair("1970-08-14T09:34:49"_DateTime, 3.80488671073918022e+03 * (Metre / Second)), Pair("1970-08-15T13:59:24"_DateTime, 3.04867185471741759e-04 * (Metre / Second)), Pair("1970-12-22T07:48:21"_DateTime, 1.58521291818444873e-03 * (Metre / Second)), Pair("1971-01-08T17:36:55"_DateTime, 1.40000000034068623e-03 * (Metre / Second)), Pair("1971-07-02T17:16:00"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1971-09-06T03:27:33"_DateTime, 1.78421858738381537e-03 * (Metre / Second)), Pair("1972-02-13T22:47:26"_DateTime, 7.72606625794511597e-04 * (Metre / Second)), Pair("1972-03-25T16:30:19"_DateTime, 5.32846131747503372e-03 * (Metre / Second)), Pair("1972-12-24T04:09:32"_DateTime, 3.45000000046532824e-03 * (Metre / Second)), Pair("1973-06-04T01:59:07"_DateTime, 9.10695453328359134e-03 * (Metre / Second)), Pair("1973-07-09T06:07:17"_DateTime, 4.49510921430966881e-01 * (Metre / Second)), Pair("1973-09-10T03:59:44"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1974-11-20T17:34:27"_DateTime, 5.10549409572428781e-01 * (Metre / Second)), Pair("1975-10-07T01:29:45"_DateTime, 2.86686518692948443e-02 * (Metre / Second)), Pair("1975-12-29T21:27:13"_DateTime, 1.00404183285598275e-03 * (Metre / Second)), Pair("1977-07-28T22:47:53"_DateTime, 1.39666705839172456e-01 * (Metre / Second)))); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } #endif TEST_F(PluginCompatibilityTest, DISABLED_Butcher) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\1119\1119.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Haar"), Not(HasSubstr(u8"pre-Gröbner")))); auto const& orbiter = *plugin->GetVessel("e180ca12-492f-45bf-a194-4c5255aec8a0"); EXPECT_THAT(orbiter.name(), Eq("Mercury Orbiter 1")); auto const begin = orbiter.history()->begin(); EXPECT_THAT(begin->time, Eq("1966-05-10T00:14:03"_TT + 0.0879862308502197 * Second)); EXPECT_THAT(begin->degrees_of_freedom, Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {-9.83735958466250000e+10 * Metre, -1.05659916408781250e+11 * Metre, -4.58171358797500000e+10 * Metre}), Velocity<Barycentric>( {+2.18567382812500000e+04 * (Metre / Second), -1.76616533203125000e+04 * (Metre / Second), -7.76112133789062500e+03 * (Metre / Second)})))); auto const& mercury = plugin->GetCelestial(2); EXPECT_THAT(mercury.body()->name(), Eq("Mercury")); plugin->RequestReanimation(begin->time); while (mercury.trajectory().t_min() > begin->time) { absl::SleepFor(absl::Milliseconds(1)); } // The history goes back far enough that we are still on our way to Mercury at // the beginning. EXPECT_THAT((begin->degrees_of_freedom.position() - mercury.trajectory().EvaluatePosition(begin->time)).Norm(), IsNear(176'400'999_⑴ * Kilo(Metre))); EXPECT_THAT(begin->time, Eq("1966-05-10T00:14:03"_TT + 0.0879862308502197 * Second)); EXPECT_THAT(begin->degrees_of_freedom, Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {-9.83735958466250000e+10 * Metre, -1.05659916408781250e+11 * Metre, -4.58171358797500000e+10 * Metre}), Velocity<Barycentric>( {+2.18567382812500000e+04 * (Metre / Second), -1.76616533203125000e+04 * (Metre / Second), -7.76112133789062500e+03 * (Metre / Second)})))); // We arrive in late August. Check the state in the beginning of September. auto const it = orbiter.trajectory().lower_bound("1966-09-01T00:00:00"_TT); EXPECT_THAT(it->time, Eq(MercuryOrbiterInitialTime)); EXPECT_THAT(it->degrees_of_freedom, Eq(MercuryOrbiterInitialDegreesOfFreedom<Barycentric>)); EXPECT_THAT((it->degrees_of_freedom.position() - mercury.trajectory().EvaluatePosition(it->time)).Norm(), IsNear(19'163_⑴ * Kilo(Metre))); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } TEST_F(PluginCompatibilityTest, DISABLED_Lpg) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\3136\3136.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Hamilton"), Not(HasSubstr("pre-Haar")))); // The vessel with the longest history. auto const& vessel = *plugin->GetVessel("77ddea45-47ee-48c0-aee9-d55cdb35ffcd"); auto history = vessel.history(); auto psychohistory = vessel.psychohistory(); EXPECT_THAT(*history, SizeIs(435'927)); EXPECT_THAT(*psychohistory, SizeIs(3)); // Evaluate a point in each of the two segments. EXPECT_THAT(history->EvaluateDegreesOfFreedom("1957-10-04T19:28:34"_TT), Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {+1.47513683827317657e+11 * Metre, +2.88696086355042419e+10 * Metre, +1.24740082262952404e+10 * Metre}), Velocity<Barycentric>( {-6.28845231836519179e+03 * (Metre / Second), +2.34046542233168329e+04 * (Metre / Second), +4.64410011408655919e+03 * (Metre / Second)})))); EXPECT_THAT(psychohistory->EvaluateDegreesOfFreedom("1958-10-07T09:38:30"_TT), Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {+1.45814173315801941e+11 * Metre, +3.45409490426372147e+10 * Metre, +1.49445864962450924e+10 * Metre}), Velocity<Barycentric>( {-8.70708379504568074e+03 * (Metre / Second), +2.61488327506437054e+04 * (Metre / Second), +1.90319283138508908e+04 * (Metre / Second)})))); // Serialize the history and psychohistory to a temporary file. { serialization::DiscreteTrajectory message; vessel.trajectory().WriteToMessage( &message, /*tracked=*/{history, psychohistory}, /*exact=*/{}); auto const serialized_message = base::SerializeAsBytes(message); WriteToBinaryFile(TEMP_DIR / "trajectory_3136.proto.bin", serialized_message.get()); } // Deserialize the temporary file to make sure that it's valid. { auto const serialized_message = ReadFromBinaryFile(TEMP_DIR / "trajectory_3136.proto.bin"); auto const message = ParseFromBytes<serialization::DiscreteTrajectory>(serialized_message); auto const trajectory = DiscreteTrajectory<Barycentric>::ReadFromMessage( message, /*tracked=*/{&history, &psychohistory}); EXPECT_THAT(*history, SizeIs(435'927)); EXPECT_THAT(*psychohistory, SizeIs(3)); } // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } TEST_F(PluginCompatibilityTest, DISABLED_Egg) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\3136\3136b.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Hamilton"), Not(HasSubstr("pre-Haar")))); auto& mutable_plugin = const_cast<Plugin&>(*plugin); // This would fail if segment iterators were invalidated during part // deserialization. mutable_plugin.AdvanceTime( mutable_plugin.GameEpoch() + 133218.91123694609 * Second, 295.52698460805016 * Degree); mutable_plugin.CatchUpVessel("1e07aaa2-d1f8-4f6d-8b32-495b46109d98"); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } // Use for debugging saves given by users. TEST_F(PluginCompatibilityTest, DISABLED_SECULAR_Debug) { not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\3203\wip.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); } } // namespace interface } // namespace principia
42.713948
80
0.615176
net-lisias-ksp
3c72d81813c24325c2bfd0bd6d81a1d1889a6ef8
1,661
cpp
C++
ql/time/calendars/bespokecalendar.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/time/calendars/bespokecalendar.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/time/calendars/bespokecalendar.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/time/calendars/bespokecalendar.hpp> #include <sstream> namespace QuantLib { BespokeCalendar::Impl::Impl(const std::string& name) : name_(name) {} std::string BespokeCalendar::Impl::name() const { return name_; } bool BespokeCalendar::Impl::isWeekend(Weekday w) const { return (weekend_.find(w) != weekend_.end()); } bool BespokeCalendar::Impl::isBusinessDay(const Date& date) const { return !isWeekend(date.weekday()); } void BespokeCalendar::Impl::addWeekend(Weekday w) { weekend_.insert(w); } BespokeCalendar::BespokeCalendar(const std::string& name) { bespokeImpl_ = std::make_shared<BespokeCalendar::Impl>(name); impl_ = bespokeImpl_; } void BespokeCalendar::addWeekend(Weekday w) { bespokeImpl_->addWeekend(w); } }
29.660714
79
0.698374
haozhangphd
3c77896cc5a1449d7de88e0d115c51d3bf8c6c49
2,524
cpp
C++
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/ImageTests/gnu_hash_app.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
326
2019-08-10T21:17:22.000Z
2022-03-22T08:40:47.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/ImageTests/gnu_hash_app.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
42
2019-08-13T12:48:19.000Z
2021-11-03T12:57:59.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/source/tools/ImageTests/gnu_hash_app.cpp
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
66
2019-08-10T21:41:38.000Z
2022-03-17T13:03:42.000Z
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include <cstdio> #include <cstdlib> #include <string> #include <fstream> #include <sstream> #include <vector> using std::string; extern "C" void TellPinSectionCount(int sectionCount) { // Pin tool can place instrumentation here to learn sections count. } int GetSectionCount(string command) { string result, file, word; FILE* output(popen(command.c_str(), "r")); char buffer[256]; std::vector<string> vec; while(fgets(buffer, sizeof(buffer), output) != NULL) { file = buffer; result += file.substr(0, file.size() - 1); } std::istringstream iss(result); while (iss >> word) { vec.push_back(word); } pclose(output); return atoi(vec.back().c_str()); } int main(int argc, char** argv) { int sectionCount = 0; string imgName(argv[0]); sectionCount = GetSectionCount("readelf -h " + imgName + " | grep 'Number of section headers'"); TellPinSectionCount(sectionCount); return 0; }
31.55
100
0.745246
DigitalAlchemist
3c79c64fef31c1470dd78139d88b29c7c6498fd7
1,344
cpp
C++
artifact/storm/src/storm/builder/jit/JitModelBuilderInterface.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/builder/jit/JitModelBuilderInterface.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/builder/jit/JitModelBuilderInterface.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/builder/jit/JitModelBuilderInterface.h" #include "storm/adapters/RationalFunctionAdapter.h" namespace storm { namespace builder { namespace jit { template <typename IndexType, typename ValueType> JitModelBuilderInterface<IndexType, ValueType>::JitModelBuilderInterface(ModelComponentsBuilder<IndexType, ValueType>& modelComponentsBuilder) : modelComponentsBuilder(modelComponentsBuilder) { // Intentionally left empty. } template <typename IndexType, typename ValueType> JitModelBuilderInterface<IndexType, ValueType>::~JitModelBuilderInterface() { // Intentionally left empty. } template <typename IndexType, typename ValueType> void JitModelBuilderInterface<IndexType, ValueType>::addStateBehaviour(IndexType const& stateId, StateBehaviour<IndexType, ValueType>& behaviour) { modelComponentsBuilder.addStateBehaviour(stateId, behaviour); } template class JitModelBuilderInterface<uint32_t, double>; template class JitModelBuilderInterface<uint32_t, storm::RationalNumber>; template class JitModelBuilderInterface<uint32_t, storm::RationalFunction>; } } }
43.354839
205
0.671131
glatteis
3c7ac66de72e373f825c48bbd2d02ef16fa6706d
1,565
cxx
C++
smtk/extension/vtk/io/testing/cxx/UnitTestMeshIOVTK.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/extension/vtk/io/testing/cxx/UnitTestMeshIOVTK.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/extension/vtk/io/testing/cxx/UnitTestMeshIOVTK.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/io/ImportMesh.h" #include "smtk/mesh/core/Resource.h" #include "smtk/mesh/testing/cxx/helpers.h" namespace { //SMTK_DATA_DIR is a define setup by cmake std::string data_root = SMTK_DATA_DIR; void verify_import_unstructured_grid() { smtk::mesh::ResourcePtr c = smtk::mesh::Resource::create(); std::string file_path(data_root); file_path += "/mesh/3d/nickel_superalloy.vtu"; test(smtk::io::importMesh(file_path, c), "should be able to import unstructured grid"); } void verify_import_polydata() { smtk::mesh::ResourcePtr c = smtk::mesh::Resource::create(); std::string file_path(data_root); file_path += "/scene/BasicScene_12_20_07/PolygonMesh_f8e612a9-876c-4145-9c74-ee6c39f2a157.vtp"; test(smtk::io::importMesh(file_path, c), "should be able to import polydata"); } } // namespace int UnitTestMeshIOVTK(int argc, char* argv[]) { (void)argc; (void)argv; verify_import_unstructured_grid(); verify_import_polydata(); return 0; } // This macro ensures the vtk io library is loaded into the executable smtkComponentInitMacro(smtk_extension_vtk_io_mesh_MeshIOVTK)
27.946429
97
0.673482
jcfr
3c7bbe87cadb94597644da05b31063719b764295
5,965
cpp
C++
tests/simple/test_model_cereal.cpp
GasparQ/Cerealization
42ed8e78fc42f7e032633eb5c06635cb92980c59
[ "MIT" ]
1
2018-03-16T08:51:35.000Z
2018-03-16T08:51:35.000Z
tests/simple/test_model_cereal.cpp
GasparQ/Cerealization
42ed8e78fc42f7e032633eb5c06635cb92980c59
[ "MIT" ]
null
null
null
tests/simple/test_model_cereal.cpp
GasparQ/Cerealization
42ed8e78fc42f7e032633eb5c06635cb92980c59
[ "MIT" ]
null
null
null
// // Created by GasparQ on 03/04/2018. // #include <cassert> #include <iostream> #include <typeinfo> #include "Cerealizable/Scalar.hpp" #include "Cerealizable/List.hpp" #include "Cerealizable/Tuple.hpp" #include "Cerealizable/Object.hpp" #include "Cerealizer/Binary/Binary.hpp" #include "Cerealizer/JSON/JSON.hpp" using namespace Cerealization; template <typename Cerealizer, typename Data> bool test_cerealize(Data const &toser) { Cerealizer cerealizer; Data witness; std::string dataname(typeid(Data).name()); std::string cername(typeid(Cerealizer).name()); std::cout << "Cerealizing " << dataname.substr(31) << " into " << cername.substr(30) << " ===> "; cerealizer << toser; if (std::is_same<std::string, decltype(cerealizer.Data())>::value) std::cout << cerealizer.Data() << " ===> "; cerealizer >> witness; if (toser == witness) { std::cout << "Success" << std::endl; return true; } std::cout << "Failure" << std::endl; return false; } template <typename Cerealizer> void test_scalar() { assert(test_cerealize<Cerealizer>(Cerealizable::Char('t'))); assert(test_cerealize<Cerealizer>(Cerealizable::Char(-128))); assert(test_cerealize<Cerealizer>(Cerealizable::UChar('t'))); assert(test_cerealize<Cerealizer>(Cerealizable::UChar(255))); assert(test_cerealize<Cerealizer>(Cerealizable::Short(-42))); assert(test_cerealize<Cerealizer>(Cerealizable::UShort(42))); assert(test_cerealize<Cerealizer>(Cerealizable::Int(-2000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::UInt(4000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::Long(-2000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::ULong(4000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::LongLong(-8000000000000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::ULongLong(9000000000000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::Float(50.3f))); assert(test_cerealize<Cerealizer>(Cerealizable::Float(-50.3f))); assert(test_cerealize<Cerealizer>(Cerealizable::Double(50.3))); assert(test_cerealize<Cerealizer>(Cerealizable::Double(-50.3))); } template <typename Cerealizer> void test_list() { assert(test_cerealize<Cerealizer>(Cerealizable::String("Coucou"))); std::string toto("coucou"); assert(test_cerealize<Cerealizer>(Cerealizable::String(toto))); assert(test_cerealize<Cerealizer>(Cerealizable::List<int>({3, 1, 20}))); assert(test_cerealize<Cerealizer>( Cerealizable::List<Cerealizable::String>( { Cerealizable::String("hey"), Cerealizable::String("ho"), Cerealizable::String("hello") } ))); assert(test_cerealize<Cerealizer>(Cerealizable::Vector<int>({3, 1, 20}))); assert(test_cerealize<Cerealizer>( Cerealizable::Vector<Cerealizable::String>( { Cerealizable::String("hey"), Cerealizable::String("ho"), Cerealizable::String("hello") } ))); assert(test_cerealize<Cerealizer>(Cerealizable::Set <int>({3, 1, 20}))); assert(test_cerealize<Cerealizer>(Cerealizable::Set <std::string>({ "hey", "ho", "hello" }))); assert(test_cerealize<Cerealizer>(Cerealizable::Map <char, int>({ {'j', 3}, {'l', 1}, {'i', 20} }))); assert(test_cerealize<Cerealizer>( Cerealizable::Map <std::string, Cerealizable::String>( { {"hey", Cerealizable::String("hey")}, {"ho", Cerealizable::String("ho")}, {"hello", Cerealizable::String("hello")} } ))); assert(test_cerealize<Cerealizer>(Cerealizable::List<Tuple<int, String, Int>>{ Tuple<int, String, Int>(43, String("toto"), 50), Tuple<int, String, Int>(78, String("tutu"), 90), Tuple<int, String, Int>(-78, String("tata"), 120), Tuple<int, String, Int>(-388, String("titi"), -3920) })); } template <typename Cerealizer> void test_tuple() { assert(test_cerealize<Cerealizer>(Tuple<int, int, int>(-43, 29, 39))); assert(test_cerealize<Cerealizer>(Tuple<int, char, double>(-43, 'd', 3.14))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, char, double>(-43, 'd', 3.14))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, double>(-43, String("Coucou"), 3.14))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, Tuple<int, int, int>>(-43, String("Coucou"), Tuple<int, int, int>(3, -42, 39)))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, Tuple<int, String, int>>(-43, String("Coucou"), Tuple<int, String, int>(3, String("C'est moit"), 39)))); } template <typename Cerelizer> void test_object() { assert(test_cerealize<Cerelizer>(Object<int, int, int>({"x", 42}, {"y", -42}, {"z", 390}))); assert(test_cerealize<Cerelizer>(Object<int, char, double>({"x", 42}, {"id", 'k'}, {"radius", 3.14}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, char, double>({"x", 42}, {"id", 'k'}, {"radius", 3.14}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, double>({"x", 42}, {"id", String("Toto")}, {"radius", 3.14}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, Tuple<int, int, int>>({"x", 42}, {"id", String("Toto")}, {"radius", Tuple<int, int, int>(3, -42, 39)}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, Tuple<int, String, int>>({"x", 42}, {"id", String("Toto")}, {"radius", Tuple<int, String, int>(3, String("C'est moi"), 39)}))); } int main() { test_scalar<Cerealizer::BinaryStream>(); test_scalar<Cerealizer::JSONStream>(); test_list<Cerealizer::BinaryStream>(); test_list<Cerealizer::JSONStream>(); test_tuple<Cerealizer::BinaryStream>(); test_tuple<Cerealizer::JSONStream>(); test_object<Cerealizer::BinaryStream>(); test_object<Cerealizer::JSONStream>(); return 0; }
40.578231
192
0.652473
GasparQ
3c7f3b3fa4d64d06e0af48646a0fc92560c34a5c
257
cpp
C++
sources/common/_VS/FatFS/ff_gen_drv.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
sources/common/_VS/FatFS/ff_gen_drv.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
sources/common/_VS/FatFS/ff_gen_drv.cpp
Sasha7b9Work/S8-57M
24531cf6d285a400e8be20a939acb842a775a989
[ "MIT" ]
null
null
null
#include "defines.h" #include "ff_gen_drv.h" const Diskio_drvTypeDef USBH_Driver{ 0, 0, 0 }; uint8_t FATFS_LinkDriver(const Diskio_drvTypeDef * /*drv*/, char * /*path*/) { return 0; } uint8_t FATFS_UnLinkDriver(char * /*path*/) { return 0; }
13.526316
76
0.669261
Sasha7b9Work
3c80a17cc34ff0f0e8ae6a866398c3b1785ea714
9,367
cxx
C++
src/Recon.cxx
fermi-lat/AncillaryDataEvent
4f8f9677971b36628b0949e3ccd8b708e4932c38
[ "BSD-3-Clause" ]
null
null
null
src/Recon.cxx
fermi-lat/AncillaryDataEvent
4f8f9677971b36628b0949e3ccd8b708e4932c38
[ "BSD-3-Clause" ]
null
null
null
src/Recon.cxx
fermi-lat/AncillaryDataEvent
4f8f9677971b36628b0949e3ccd8b708e4932c38
[ "BSD-3-Clause" ]
null
null
null
#include "AncillaryDataEvent/Recon.h" #include <algorithm> //using namespace AncillaryData; namespace AncillaryData { Recon::Recon(AncillaryData::Digi *digiEvent) { setEventNumber(digiEvent->getEventNumber()); setSpillNumber(digiEvent->getSpillNumber()); setQdcHitCol(digiEvent->getQdcHitCol()); setScalerHitCol(digiEvent->getScalerHitCol()); PX = -9999.0; PY= -9999.0; PZ= -9999.0; E_rec=0; E_corr=0; PhiIn=-100; PhiOut=-100; Dphi=-100; Theta=-100; m_NumberHigestClusters=0; m_NumberTotalClusters=0; for(unsigned int m=0; m < N_MODULES; m++) { m_NumberClusters[0][m]=0; m_NumberClusters[1][m]=0; } } void Recon::print() { std::cout<< " Ancillary Recon Event: "<<getEventNumber()<<" Spill Number: "<<getSpillNumber()<<std::endl; std::cout<< " --- number of Tagger Clusters: "<<m_taggerClusterCol.size()<<std::endl; for(std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); pos!=m_taggerClusterCol.end(); ++pos) (*pos).print(); std::cout<< " --- number of QDC Hits : "<<m_qdcHitCol.size()<<std::endl; for(std::vector<QdcHit>::iterator pos= m_qdcHitCol.begin(); pos!= m_qdcHitCol.end(); ++pos) (*pos).print(); std::cout<< " --- number of Scaler Hits : "<<m_scalerHitCol.size()<<std::endl; for(std::vector<ScalerHit>::iterator pos= m_scalerHitCol.begin(); pos!= m_scalerHitCol.end(); ++pos) (*pos).print(); } void Recon::ComputeClustersProperties() { for(std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); pos!=m_taggerClusterCol.end(); ++pos) (*pos).calculateProperties(); } std::vector<TaggerCluster> Recon::GetHighestClusters() { SortClusters(); for(unsigned int m=0;m < N_MODULES;m++) { m_NumberClusters[0][m]=0; m_NumberClusters[1][m]=0; } // std::cout<<"std::vector<TaggerCluster> Recon::GetHighestClusters: "<<m_taggerClusterCol.size()<<std::endl; // m_NumberClusters = m_taggerClusterCol.size(); if(m_taggerClusterCol.size()<=1) return m_taggerClusterCol; std::vector<TaggerCluster> HigestsClusters; /////// for(std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); pos<m_taggerClusterCol.end();pos++) m_NumberClusters[(*pos).getLayerId()][(*pos).getModuleId()]++; m_NumberTotalClusters = 0; for(unsigned int m=0; m < N_MODULES; m++) { m_NumberTotalClusters += m_NumberClusters[0][m]; m_NumberTotalClusters += m_NumberClusters[1][m]; } ////// std::vector<TaggerCluster>::iterator pos=m_taggerClusterCol.begin(); TaggerCluster selectedCluster=(*pos); pos++; while(pos<m_taggerClusterCol.end()) { TaggerCluster newCluster=(*pos); // std::cout<<"selected cluster:"<<selectedCluster.getModuleId()<<", "<<selectedCluster.getLayerId()<<std::endl; // std::cout<<"new Cluster cluster:"<<newCluster.getModuleId()<<", "<<newCluster.getLayerId()<<std::endl; if(selectedCluster.getModuleId()==newCluster.getModuleId() && selectedCluster.getLayerId()==newCluster.getLayerId()) { selectedCluster=MaxCluster(newCluster,selectedCluster); } else { HigestsClusters.push_back(selectedCluster); selectedCluster=newCluster; } pos++; } HigestsClusters.push_back(selectedCluster); m_NumberHigestClusters=HigestsClusters.size(); // std::cout<<"std::vector<TaggerCluster> Recon::GetHighestClusters m_NumberHigestClusters "<<m_NumberHigestClusters<<std::endl; return HigestsClusters; } void Recon::SortClusters() { std::sort(m_taggerClusterCol.begin(),m_taggerClusterCol.end(),ClusterSortPredicate); } void Recon::computePositions(AncillaryGeometry *geometry) { std::vector<TaggerCluster> higestClusters = GetHighestClusters(); for (unsigned int i = 0 ; i < N_MODULES ; i++) { X[i] = 0.0; Y[i] = 0.0; Z[i] = 0.0; } for(std::vector<TaggerCluster>::iterator pos=higestClusters.begin();pos!=higestClusters.end(); ++pos) { const unsigned int M= (*pos).getModuleId(); const unsigned int L= (*pos).getLayerId(); // 0 or 1 // View and direction of the first view unsigned int V,D; if(L==0) { V = geometry->getView1(M); D = geometry->getDirection1(M); } else { V = geometry->getView2(M); D = geometry->getDirection2(M); } const double HalfWafer = N_CHANNELS_PER_LAYER*STRIPS_PITCH/2.0; // this is valid for both views: X[M] = geometry->getX(M); // case of first view if(V==1 && D == 0) // case : V = Z, D = + Z[M] = geometry->getZ(M) - HalfWafer + (*pos).getPosition(); else if(V==1 && D == 1 ) // case : V = Z, D = - Z[M] = geometry->getZ(M) + HalfWafer - (*pos).getPosition(); else if(V==0 && D == 0) // case : V = Y, D = + Y[M] = geometry->getY(M) - HalfWafer + (*pos).getPosition(); else if(V==0 && D == 1 ) // case : V = Y, D = - Y[M] = geometry->getY(M) + HalfWafer - (*pos).getPosition(); } } void Recon::reconstructEnergy(AncillaryGeometry *geometry) { E_rec = 0.0; E_corr = 0.0; double bt=geometry->getBL(); double beamMomentum=geometry->getBeamMomentum()*1000.0; //MeV // first track: const double Dist1 = X[1]-X[0]; const double Disp1 = Y[1]-Y[0]; const double Dist2 = X[3]-X[2]; const double Disp2 = Y[3]-Y[2]; double a1,a2,b1,b2; if(Disp1!=0) { a1 = Disp1/Dist1; b1 = (Y[0]*X[1]-Y[1]*X[0])/Dist1; PhiIn = atan2(Disp1,Dist1); } if(Disp2!=0) { // r1 = a2*x + b2 a2 = Disp2/Dist2; b2 = (Y[2]*X[3]-Y[3]*X[2])/Dist2; PhiOut = atan2(Disp2,Dist2); } if(Disp1!=0 && Disp2!=0 ) { Dphi = PhiOut - PhiIn; double phiErrIn = STRIPS_PITCH/Dist1; double phiErrOut = STRIPS_PITCH/Dist2; // double DphiErr = sqrt(phiErrIn*phiErrIn+phiErrOut*phiErrOut); if(fabs(sin(PhiOut)-sin(PhiIn))>0) { E_rec = beamMomentum - (300.*bt/(sin(PhiOut)-sin(PhiIn))); Error_E_rec = (300.*bt/pow(sin(PhiOut)-sin(PhiIn),2.0)*sqrt(pow(cos(PhiOut)*phiErrOut,2.0)+pow(cos(PhiIn)*phiErrIn,2.0))); if(fabs(a1-a2)>0) { PX = (b2-b1)/(a1-a2); PY = a1 * PX + b1; } } // Z = A* X + B // Case with two points in z: if(m_NumberHigestClusters==8 && m_NumberTotalClusters == 8) { double SX = X[0]+X[1]+X[2]+X[3]; double SZ = Z[0]+Z[1]+Z[2]+Z[3]; double SXX = X[0]*X[0] + X[1]*X[1] + X[2]*X[2] + X[3]*X[3]; double SZX = Z[0]*X[0] + Z[1]*X[1] + Z[2]*X[2] + Z[3]*X[3]; double A = (4.*SZX-SZ*SX)/(4.*SXX-SX*SX); double B = (SZ-A*SX)/4.; if(fabs(a1-a2)>0) PZ = A * PX + B; Theta=atan2(4.*SZX-SZ*SX,4.*SXX-SX*SX); if(fabs(cos(Theta))>0) { E_corr = E_rec/cos(Theta); Error_E_corr=Error_E_rec; } } } } void Recon::report() { std::cout<<" RECON EVENT REPORT: Total Clusters: "<<m_NumberTotalClusters<<" Higest:" <<m_NumberHigestClusters<<std::endl; { const double Disp1 = Y[1]-Y[0]; const double Disp2 = Y[3]-Y[2]; if(Disp1!=0) std::cout<<" Electron Incoming Angle: \t"<<PhiIn<<std::endl; if(Disp2!=0) std::cout<<" Electron Outgoing Angle: \t"<<PhiOut<<std::endl; if(Disp1!=0 && Disp2!=0) { std::cout<<" Delta angle : \t"<<Dphi<<std::endl; std::cout<<" Reconstructed Energy : \t"<<E_rec<<" +- "<< Error_E_rec <<std::endl; if(m_NumberHigestClusters==8 && m_NumberTotalClusters == 8) { std::cout<<" Theta Angle : \t"<<Theta<<std::endl; std::cout<<" Corrected Energy : \t"<<E_corr<<" +- "<< Error_E_corr <<std::endl; } std::cout<<" Intesection Point "<<std::endl; std::cout<<" \t X \t Y \t Z "<<std::endl; std::cout<<" \t "<<PX<<" \t "<<PY<<" \t "<<PZ<<std::endl; std::cout<<" Higest Selected Clusters: "<<std::endl; } std::cout<<" \t X \t Y \t Z "<<std::endl; for(unsigned int m=0; m < N_MODULES; m++) std::cout<<" \t "<<X[m]<<" \t "<<Y[m]<<" \t "<<Z[m]<<std::endl; /* std::cout<<" Sorry, not enough clusters!"<<std::endl; std::cout<<" M = "<<m<<" Num Clusters: L = 0: "<< m_NumberClusters[0][m]<<" L = 1: "<<m_NumberClusters[1][m]<<std::endl; */ } } } // end namespace AncillaryData /* AD_TIMESTAMP Trigger Time-stamp measured in the AD system AD_PID particle ID code from AD data (use same as G4 particle code?) TAG_PHI_IN electron incoming angle before magnet measured by silicon chambers 1 and 2 in the bending plane TAG_THETA_IN electron incoming angle before magnet measured by silicon chambers 1 and 2 in the bending plane TAG_XYZ[3,4] X,Y,Z coordinates of highest cluster in each of the four silicon tagger station TAG_XYZ_IN_CU[3] X,Y,Z coordinates of photon impact point on CU (assuming photon collinear with e beam) TAG_DPHI electron deflection angle after magnet in the bending plane TAG_EGAMMA photon energy (Ebeam - Edeflected_electron) TAG_EGAMMA_ERR error on photon energy measuement CRNKV_PHA[2] pulse height amplitude in the 2 cerenkov SCINT_PHA[8] array of floats - PHA for scintillators in the setup (8 is a placeholder for a reasonable number, might change) TRD_NUM[16] void Recon::computeFinalTupla() { } */
33.938406
131
0.610761
fermi-lat
3c815e863e22a09ba29c0a09896d2983aaa9a55e
153
cpp
C++
lib/src/public.cpp
nontan-rh/cpp-template
b0b618307b54a432c3a18af308f887a21a57dccd
[ "Unlicense" ]
1
2020-11-18T08:43:11.000Z
2020-11-18T08:43:11.000Z
lib/src/public.cpp
nontan-rh/cpp-template
b0b618307b54a432c3a18af308f887a21a57dccd
[ "Unlicense" ]
null
null
null
lib/src/public.cpp
nontan-rh/cpp-template
b0b618307b54a432c3a18af308f887a21a57dccd
[ "Unlicense" ]
null
null
null
#include <sample/public.hpp> #include "internal.hpp" namespace sample { int add(int a, int b) { return internal::sub(a, -b); } } // namespace sample
15.3
54
0.673203
nontan-rh
3c81f7b2ab6b966b25164ffec35a7906edcc381c
24,092
cpp
C++
dev/Code/Sandbox/Editor/EntityPanel.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Code/Sandbox/Editor/EntityPanel.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/EntityPanel.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "EntityPanel.h" #include "AIWavePanel.h" #include "ShapePanel.h" #include "Objects/EntityObject.h" #include "Objects/ShapeObject.h" #include "Objects/AIWave.h" #include "StringDlg.h" #include "CryEditDoc.h" #include "Mission.h" #include "MissionScript.h" #include "EntityPrototype.h" #include "QtViewPaneManager.h" #include "GenericSelectItemDialog.h" #include <HyperGraph/FlowGraphManager.h> #include <HyperGraph/FlowGraph.h> #include <HyperGraph/FlowGraphHelpers.h> #include <HyperGraph/HyperGraphDialog.h> #include <HyperGraph/FlowGraphSearchCtrl.h> #include <TrackView/TrackViewDialog.h> #include <ui_EntityPanel.h> #include <ui_EntityEventsPanel.h> #include "QtUtil.h" #include <QInputDialog> #include <QMenu> #include <QTreeWidgetItem> ///////////////////////////////////////////////////////////////////////////// // CEntityPanel dialog CEntityPanel::CEntityPanel(QWidget* pParent /*=nullptr*/) : QWidget(pParent) , ui(new Ui::CEntityPanel) { m_entity = 0; ui->setupUi(this); m_editScriptButton = ui->EDITSCRIPT; m_reloadScriptButton = ui->RELOADSCRIPT; m_prototypeButton = ui->PROTOTYPE; m_flowGraphOpenBtn = ui->OPENFLOWGRAPH; m_flowGraphRemoveBtn = ui->REMOVEFLOWGRAPH; m_flowGraphListBtn = ui->LIST_ENTITY_FLOWGRAPHS; m_physicsBtn[0] = ui->GETPHYSICS; m_physicsBtn[1] = ui->RESETPHYSICS; m_trackViewSequenceButton = ui->TRACKVIEW_SEQUENCE; m_frame = ui->FRAME2; connect(m_editScriptButton, &QPushButton::clicked, this, &CEntityPanel::OnEditScript); connect(m_reloadScriptButton, &QPushButton::clicked, this, &CEntityPanel::OnReloadScript); connect(ui->FILE_COMMANDS, &QPushButton::clicked, this, &CEntityPanel::OnFileCommands); connect(m_prototypeButton, &QPushButton::clicked, this, &CEntityPanel::OnPrototype); connect(m_flowGraphOpenBtn, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedOpenFlowGraph); connect(m_flowGraphRemoveBtn, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedRemoveFlowGraph); connect(m_flowGraphListBtn, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedListFlowGraphs); connect(m_physicsBtn[0], &QPushButton::clicked, this, &CEntityPanel::OnBnClickedGetphysics); connect(m_physicsBtn[1], &QPushButton::clicked, this, &CEntityPanel::OnBnClickedResetphysics); connect(m_trackViewSequenceButton, &QPushButton::clicked, this, &CEntityPanel::OnBnClickedTrackViewSequence); } ///////////////////////////////////////////////////////////////////////////// // CEntityPanel message handlers void CEntityPanel::SetEntity(CEntityObject* entity) { assert(entity); m_entity = entity; if (m_entity != NULL && m_entity->GetScript()) { ui->SCRIPT_NAME->setText(m_entity->GetScript()->GetFile()); } if (!qobject_cast<CAITerritoryObject*>(entity) && !qobject_cast<CAIWaveObject*>(entity)) { if (qobject_cast<CAITerritoryPanel*>(this) || qobject_cast<CAIWavePanel*>(this)) { return; } if (m_entity != NULL && !entity->GetPrototype()) { m_prototypeButton->setEnabled(false); m_prototypeButton->setText(tr("Entity Archetype")); } else { m_prototypeButton->setEnabled(true); m_prototypeButton->setText(entity->GetPrototype()->GetFullName()); } } if (m_entity != NULL && m_entity->GetFlowGraph()) { m_flowGraphOpenBtn->setText(tr("Open")); m_flowGraphOpenBtn->setEnabled(true); m_flowGraphRemoveBtn->setEnabled(true); } else { m_flowGraphOpenBtn->setText(tr("Create")); m_flowGraphOpenBtn->setEnabled(true); m_flowGraphRemoveBtn->setEnabled(false); } if (m_trackViewSequenceButton->isVisible()) { CTrackViewAnimNode* pAnimNode = nullptr; m_trackViewSequenceButton->setText(tr("Sequence")); if (m_entity != nullptr && (pAnimNode = GetIEditor()->GetSequenceManager()->GetActiveAnimNode(entity)) && pAnimNode->GetSequence()) { m_trackViewSequenceButton->setEnabled(true); } else { m_trackViewSequenceButton->setEnabled(false); } } } void CEntityPanel::OnEditScript() { assert(m_entity != 0); CEntityScript* script = m_entity->GetScript(); AZStd::string cmd = AZStd::string::format("general.launch_lua_editor \'%s\'", script->GetFile().toUtf8().data()); GetIEditor()->ExecuteCommand(cmd.c_str()); } void CEntityPanel::OnReloadScript() { assert(m_entity != 0); m_entity->OnMenuReloadScripts(); } void CEntityPanel::OnFileCommands() { assert(m_entity != 0); CEntityScript* pScript = m_entity->GetScript(); if (pScript) { CFileUtil::PopupQMenu(Path::GetFile(pScript->GetFile()), Path::GetPath(pScript->GetFile()), this); } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnPrototype() { // Go to the entity prototype. // Open corresponding prototype. if (m_entity) { if (m_entity->GetPrototype()) { GetIEditor()->OpenDataBaseLibrary(EDB_TYPE_ENTITY_ARCHETYPE, m_entity->GetPrototype()); } } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnBnClickedTrackViewSequence() { if (m_entity) { CTrackViewAnimNodeBundle bundle = GetIEditor()->GetSequenceManager()->GetAllRelatedAnimNodes(m_entity); CTrackViewAnimNodeBundle finalBundle; if (bundle.GetCount() > 0) { QMenu menu; unsigned int id = 1; for (unsigned int i = 0; i < bundle.GetCount(); ++i) { CTrackViewAnimNode* pNode = bundle.GetNode(i); if (pNode->GetSequence()) { menu.addAction(QtUtil::ToQString(pNode->GetSequence()->GetName()))->setData(id); finalBundle.AppendAnimNode(pNode); id++; // KDAB_PORT original code never incremented, so first one was always chosen. Right/Wrong? } } QAction* res = menu.exec(QCursor::pos()); int chosen = res ? (res->data().toInt() - 1) : -1; if (chosen >= 0) { QtViewPaneManager::instance()->OpenPane(LyViewPane::TrackView); CTrackViewDialog* pTVDlg = CTrackViewDialog::GetCurrentInstance(); if (pTVDlg) { GetIEditor()->GetAnimation()->SetSequence(finalBundle.GetNode(chosen)->GetSequence(), false, false); CTrackViewAnimNode* pNode = finalBundle.GetNode(chosen); if (pNode) { pNode->SetSelected(true); } } } } } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnBnClickedGetphysics() { if (m_entity) { CUndo undo("Accept Physics State"); m_entity->AcceptPhysicsState(); } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnBnClickedResetphysics() { if (m_entity) { CUndo undo("Reset Physics State"); m_entity->ResetPhysicsState(); } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnBnClickedOpenFlowGraph() { if (m_entity) { if (!m_entity->GetFlowGraph()) { m_entity->CreateFlowGraphWithGroupDialog(); } else { // Flow graph already present. m_entity->OpenFlowGraph(""); } } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnBnClickedRemoveFlowGraph() { if (m_entity) { if (m_entity->GetFlowGraph()) { CUndo undo("Remove Flow graph"); QString str(tr("Remove Flow Graph for Entity %1?").arg(m_entity->GetName())); if (QMessageBox::question(this, "Confirm", str, QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { m_entity->RemoveFlowGraph(); SetEntity(m_entity); } } } } ////////////////////////////////////////////////////////////////////////// void CEntityPanel::OnBnClickedListFlowGraphs() { std::vector<CFlowGraph*> flowgraphs; CFlowGraph* entityFG = 0; FlowGraphHelpers::FindGraphsForEntity(m_entity, flowgraphs, entityFG); if (flowgraphs.size() > 0) { QMenu menu; unsigned int id = 1; std::vector<CFlowGraph*>::const_iterator iter (flowgraphs.begin()); while (iter != flowgraphs.end()) { QString name; FlowGraphHelpers::GetHumanName(*iter, name); if (*iter == entityFG) { name += " <GraphEntity>"; menu.addAction(name)->setData(id); if (flowgraphs.size() > 1) { menu.addSeparator(); } } else { menu.addAction(name)->setData(id); } ++id; ++iter; } QAction* res = menu.exec(QCursor::pos()); int chosen = res ? (res->data().toInt() - 1) : -1; if (chosen >= 0) { GetIEditor()->GetFlowGraphManager()->OpenView(flowgraphs[chosen]); CHyperGraphDialog* pHGDlg = CHyperGraphDialog::instance(); if (pHGDlg) { CFlowGraphSearchCtrl* pSC = pHGDlg->GetSearchControl(); if (pSC) { CFlowGraphSearchOptions* pOpts = CFlowGraphSearchOptions::GetSearchOptions(); pOpts->m_bIncludeEntities = true; pOpts->m_findSpecial = CFlowGraphSearchOptions::eFLS_None; pOpts->m_LookinIndex = CFlowGraphSearchOptions::eFL_Current; pSC->Find(m_entity->GetName(), false, true, true); } } } } } ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CEntityEventsPanel dialog CEntityEventsPanel::CEntityEventsPanel(QWidget* pParent /*=nullptr*/) : QWidget(pParent) , ui(new Ui::CEntityEventsPanel) { ui->setupUi(this); m_entity = 0; m_pickTool = 0; m_sendEvent = ui->EVENT_SEND; connect(m_sendEvent, &QPushButton::clicked, this, &CEntityEventsPanel::OnEventSend); m_runButton = ui->RUN_METHOD; connect(m_runButton, &QPushButton::clicked, this, &CEntityEventsPanel::OnRunMethod); m_gotoMethodBtn = ui->GOTO_METHOD; connect(m_gotoMethodBtn, &QPushButton::clicked, this, &CEntityEventsPanel::OnGotoMethod); m_addMethodBtn = ui->ADD_METHOD; connect(m_addMethodBtn, &QPushButton::clicked, this, &CEntityEventsPanel::OnAddMethod); m_removeButton = ui->EVENT_REMOVE; connect(m_removeButton, &QPushButton::clicked, this, &CEntityEventsPanel::OnEventRemove); m_eventTree = ui->EVENTTREE; m_eventTree->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_eventTree, &QTreeWidget::customContextMenuRequested, this, &CEntityEventsPanel::OnRclickEventTree); connect(m_eventTree, &QTreeWidget::itemDoubleClicked, this, &CEntityEventsPanel::OnDblClickEventTree); connect(m_eventTree, &QTreeWidget::itemSelectionChanged, this, &CEntityEventsPanel::OnSelChangedEventTree); m_pickButton = ui->EVENT_ADD; //connect(m_pickButton, &QPushButton::clicked, this, &CEntityEventsPanel::OnEventAdd); //m_pickButton.SetPickCallback(this, _T("Pick Target Entity for Event"), RUNTIME_CLASS(CEntityObject)); m_addMissionBtn = ui->EVENT_ADDMISSION; connect(m_addMissionBtn, &QPushButton::clicked, this, &CEntityEventsPanel::OnBnAddMission); m_methods = ui->METHODS; connect(m_methods, &QListWidget::itemDoubleClicked, this, &CEntityEventsPanel::OnDblclkMethods); connect(m_methods, &QListWidget::itemSelectionChanged, this, &CEntityEventsPanel::OnSelChangedMethods); } CEntityEventsPanel::~CEntityEventsPanel() { if (m_pickTool == GetIEditor()->GetEditTool()) { GetIEditor()->SetEditTool(0); } m_pickTool = 0; } ///////////////////////////////////////////////////////////////////////////// // CEntityEventsPanel message handlers void CEntityEventsPanel::SetEntity(CEntityObject* entity) { assert(entity); m_entity = entity; ReloadMethods(); ReloadEvents(); } void CEntityEventsPanel::ReloadMethods() { assert(m_entity != 0); // Parse entity lua file. CEntityScript* script = m_entity->GetScript(); // Since method CEntityScriptDialog::SetScript, checks for script, we are checking here too. if (!script) { return; } m_methods->clear(); ///if (script->Load( m_entity->GetEntityClass() )) { for (int i = 0; i < script->GetMethodCount(); i++) { m_methods->addItem(script->GetMethod(i)); } } } void CEntityEventsPanel::OnSelChangedMethods() { m_selectedMethod = m_methods->selectedItems().size() ? m_methods->selectedItems().front()->text() : QStringLiteral(""); } void CEntityEventsPanel::OnDblclkMethods(QListWidgetItem* item) { GotoMethod(m_selectedMethod); } void CEntityEventsPanel::OnRunMethod() { assert(m_entity != 0); CEntityScript* script = m_entity->GetScript(); if (m_entity->GetIEntity()) { script->RunMethod(m_entity->GetIEntity(), m_selectedMethod); } } void CEntityEventsPanel::GotoMethod(const QString& method) { assert(m_entity != 0); CEntityScript* script = m_entity->GetScript(); script->GotoMethod(method); } void CEntityEventsPanel::OnGotoMethod() { GotoMethod(m_selectedMethod); } void CEntityEventsPanel::OnAddMethod() { assert(m_entity != 0); bool ok; QString method = QInputDialog::getText(this, tr("Add Method"), tr("Enter Method Name:"), QLineEdit::Normal, QStringLiteral(""), &ok); if (ok && !method.isEmpty()) { if (m_methods->findItems(method, Qt::MatchExactly).isEmpty()) { CEntityScript* script = m_entity->GetScript(); script->AddMethod(method); script->GotoMethod(method); script->Reload(); m_entity->Reload(true); } } } void CEntityEventsPanel::ReloadEvents() { assert(m_entity != 0); CEntityScript* script = m_entity->GetScript(); int i; // Reload events tree. m_eventTree->clear(); for (i = 0; i < script->GetEventCount(); i++) { QString sourceEvent = script->GetEvent(i); QTreeWidgetItem* hRootItem = new QTreeWidgetItem(); hRootItem->setText(0, QString("On %1").arg(sourceEvent)); m_eventTree->addTopLevelItem(hRootItem); bool haveEvents = false; for (int j = 0; j < m_entity->GetEventTargetCount(); j++) { QString targetName; CEntityEventTarget& et = m_entity->GetEventTarget(j); if (sourceEvent.compare(et.sourceEvent, Qt::CaseInsensitive) != 0) { continue; } if (et.target) { targetName = et.target->GetName(); } else { targetName = "Mission"; } targetName += QString(" [%1]").arg(et.event); QTreeWidgetItem* hEventItem = new QTreeWidgetItem(hRootItem); hEventItem->setText(0, targetName); hEventItem->setIcon(0, QIcon(":/Panels/EntityEventsPanel/res/icon_dot.png")); hEventItem->setData(0, Qt::UserRole, j); haveEvents = true; } if (haveEvents) { hRootItem->setExpanded(true); QFont f = hRootItem->font(0); f.setBold(true); hRootItem->setFont(0, f); } } m_pickButton->setEnabled(false); m_removeButton->setEnabled(false); m_sendEvent->setEnabled(false); m_addMissionBtn->setEnabled(false); m_currentTrgEventId = -1; m_currentSourceEvent = ""; } void CEntityEventsPanel::OnEventAdd() { // KDAB_PORT never called assert(m_entity != 0); //m_entity->PickEntity(); if (m_pickTool) { // If pick tool already enabled, disable it. OnCancelPick(); } GetIEditor()->PickObject(this, &CEntityObject::staticMetaObject, "Pick Target Entity for Event"); m_pickButton->setChecked(true); } ////////////////////////////////////////////////////////////////////////// void CEntityEventsPanel::OnEventRemove() { if (m_currentTrgEventId >= 0) { { CUndo undo("Remove Event Target"); m_entity->RemoveEventTarget(m_currentTrgEventId); } ReloadEvents(); } } ////////////////////////////////////////////////////////////////////////// void CEntityEventsPanel::OnBnAddMission() { assert(m_entity); if (!m_currentSourceEvent.isEmpty()) { CMissionScript* script = GetIEditor()->GetDocument()->GetCurrentMission()->GetScript(); if (!script) { return; } if (script->GetEventCount() < 1) { return; } // Popup Menu with Event selection. QMenu menu; for (int i = 0; i < script->GetEventCount(); i++) { menu.addAction(script->GetEvent(i))->setData(i + 1); } QAction* action = menu.exec(QCursor::pos()); int res = action ? action->data().toInt() : 0; if (res > 0 && res < script->GetEventCount() + 1) { CUndo undo("Change Event"); QString event = script->GetEvent(res - 1); m_entity->AddEventTarget(0, event, m_currentSourceEvent); // Update script event table. if (m_entity->GetScript()) { m_entity->GetScript()->SetEventsTable(m_entity); } ReloadEvents(); } } } ////////////////////////////////////////////////////////////////////////// void CEntityEventsPanel::OnPick(CBaseObject* picked) { m_pickTool = 0; CEntityObject* pickedEntity = (CEntityObject*)picked; if (!pickedEntity) { return; } m_pickButton->setChecked(false); if (pickedEntity->GetScript()->GetEventCount() > 0) { if (!m_currentSourceEvent.isEmpty()) { CUndo undo("Add Event Target"); m_entity->AddEventTarget(pickedEntity, pickedEntity->GetScript()->GetEvent(0), m_currentSourceEvent); if (m_entity->GetScript()) { m_entity->GetScript()->SetEventsTable(m_entity); } ReloadEvents(); } } } void CEntityEventsPanel::OnCancelPick() { m_pickButton->setChecked(false); m_pickTool = 0; } void CEntityEventsPanel::OnSelChangedEventTree() { assert(m_entity != 0); QTreeWidgetItem* selectedItem = m_eventTree->selectedItems().empty() ? nullptr : m_eventTree->selectedItems().front(); QString str; if (selectedItem) { m_currentSourceEvent = selectedItem->text(0); m_currentTrgEventId = -1; ////////////////////////////////////////////////////////////////////////// // Timur: Old system disabled for now. ////////////////////////////////////////////////////////////////////////// //m_pickButton->setEnabled(true); m_removeButton->setEnabled(false); m_sendEvent->setEnabled(true); m_addMissionBtn->setEnabled(true); if (selectedItem->data(0, Qt::UserRole).isValid()) { int id = selectedItem->data(0, Qt::UserRole).toInt(); m_currentSourceEvent = m_entity->GetEventTarget(id).sourceEvent; m_currentTrgEventId = id; m_pickButton->setEnabled(false); m_removeButton->setEnabled(true); m_sendEvent->setEnabled(true); m_addMissionBtn->setEnabled(false); } } } void CEntityEventsPanel::OnRclickEventTree() { // TODO: Add your control notification handler code here if (m_currentTrgEventId >= 0) { CEntityScript* script = 0; CMissionScript* missionScript = 0; int eventCount = 0; // Popup Menu with Event selection. QMenu menu; CBaseObject* trgObject = m_entity->GetEventTarget(m_currentTrgEventId).target; if (trgObject != 0) { CEntityObject* targetEntity = (CEntityObject*)trgObject; if (!targetEntity) { return; } script = targetEntity->GetScript(); if (!script) { return; } eventCount = script->GetEventCount(); for (int i = 0; i < eventCount; i++) { menu.addAction(script->GetEvent(i))->setData(i + 1); } } else { missionScript = GetIEditor()->GetDocument()->GetCurrentMission()->GetScript(); if (!missionScript) { return; } eventCount = missionScript->GetEventCount(); for (int i = 0; i < eventCount; i++) { menu.addAction(missionScript->GetEvent(i))->setData(i + 1); } } QAction* action = menu.exec(QCursor::pos()); int res = action ? action->data().toInt() : 0; if (res > 0 && res < eventCount + 1) { CUndo undo("Change Event"); QString event; if (script) { event = script->GetEvent(res - 1); } else if (missionScript) { event = missionScript->GetEvent(res - 1); } m_entity->GetEventTarget(m_currentTrgEventId).event = event; // Update script event table. if (m_entity->GetScript()) { m_entity->GetScript()->SetEventsTable(m_entity); } ReloadEvents(); } } } ////////////////////////////////////////////////////////////////////////// void CEntityEventsPanel::OnDblClickEventTree() { /* if (m_currentTrgEventId >= 0) { CBaseObject *trgObject = m_entity->GetEventTarget(m_currentTrgEventId).target; if (trgObject != 0) { CUndo undo("Select Object" ); GetIEditor()->ClearSelection(); GetIEditor()->SelectObject( trgObject ); } }*/ if (!m_currentSourceEvent.isEmpty()) { CEntityScript* script = m_entity->GetScript(); if (m_entity->GetIEntity()) { script->SendEvent(m_entity->GetIEntity(), m_currentSourceEvent); } } } ////////////////////////////////////////////////////////////////////////// void CEntityEventsPanel::OnEventSend() { if (!m_currentSourceEvent.isEmpty()) { CEntityScript* script = m_entity->GetScript(); if (m_entity->GetIEntity()) { script->SendEvent(m_entity->GetIEntity(), m_currentSourceEvent); } } } #include <EntityPanel.moc>
30.729592
139
0.567118
jeikabu
3c8416e8d972c5e20dd3215b9755f9271cb4f4e4
618
hpp
C++
sdl1/TicTacToe/BoardInputComponent.hpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/TicTacToe/BoardInputComponent.hpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/TicTacToe/BoardInputComponent.hpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
#ifndef __BOARDINPUTCOMPONENT_H #define __BOARDINPUTCOMPONENT_H #include "InputComponent.hpp" #include "SDL.h" class BoardInputComponent : public InputComponent { public: virtual void update( GameState *obj, GameEngine *engine ); BoardInputComponent( GameBoard *board, SDL_Event *event ); ~BoardInputComponent(); protected: SDL_Rect **_squares; int _rows; int _columns; static const int _tile_x_offset = 4; static const int _tile_y_offset = 4; static const int _tile_width = 142; static const int _tile_height =142; int _mouse_x; int _mouse_y; }; #endif /* __BOARDINPUTCOMPONENT_H */
20.6
60
0.749191
pdpdds
3c898ce133d81b6a3813845c6ebac9b33717451f
9,472
cpp
C++
GazeboFluidSimulator/FluidSimulator.cpp
ManosAgelidis/SPlisHSPlasH
c206ce867c15104a70e05e4e8792072ca9b364a3
[ "MIT" ]
null
null
null
GazeboFluidSimulator/FluidSimulator.cpp
ManosAgelidis/SPlisHSPlasH
c206ce867c15104a70e05e4e8792072ca9b364a3
[ "MIT" ]
null
null
null
GazeboFluidSimulator/FluidSimulator.cpp
ManosAgelidis/SPlisHSPlasH
c206ce867c15104a70e05e4e8792072ca9b364a3
[ "MIT" ]
null
null
null
#include "SPlisHSPlasH/Common.h" #include "SPlisHSPlasH/TimeManager.h" #include "Utilities/OBJLoader.h" #include "SPlisHSPlasH/Utilities/SurfaceSampling.h" #include "SPlisHSPlasH/Viscosity/ViscosityBase.h" #include <fstream> #include "SPlisHSPlasH/Simulation.h" #include "FluidSimulator.h" #include "Utilities/Timing.h" #include "Utilities/Counting.h" #include "Utilities/FileSystem.h" #include "GazeboSceneLoader.h" #include <memory> // Enable memory leak detection #ifdef _DEBUG #ifndef EIGEN_ALIGN #define new DEBUG_NEW #endif #endif using namespace SPH; using namespace Eigen; using namespace std; using namespace Utilities; using namespace GenParam; using namespace gazebo; const std::string objFilePath("/tmp/"); FluidSimulator::FluidSimulator() { REPORT_MEMORY_LEAKS; std::cout << "Plugin loaded" << std::endl; } void FluidSimulator::RunStep() { simulationSteps++; base->timeStepNoGUI(); // publish all the boundary particles positions this->publishFluidParticles(); this->publishBoundaryParticles(); } FluidSimulator::~FluidSimulator() { this->connections.clear(); base->cleanup(); Utilities::Timing::printAverageTimes(); Utilities::Timing::printTimeSums(); Utilities::Counting::printAverageCounts(); Utilities::Counting::printCounterSums(); delete Simulation::getCurrent(); } void FluidSimulator::publishBoundaryParticles() { msgs::Fluid boundary_particles_msg; boundary_particles_msg.set_name("boundary_particles"); for (int i = 0; i < SPH::Simulation::getCurrent()->numberOfBoundaryModels(); ++i) //scene.boundaryModels.size(); ++i) { BoundaryModel_Akinci2012 *bm = static_cast<BoundaryModel_Akinci2012 *>(SPH::Simulation::getCurrent()->getBoundaryModel(i)); for (int j = 0; j < (int)bm->numberOfParticles(); j++) { ignition::math::Vector3d boundary_particles = ignition::math::Vector3d( bm->getPosition(j)[0], bm->getPosition(j)[1], bm->getPosition(j)[2]); gazebo::msgs::Set(boundary_particles_msg.add_position(), boundary_particles); } } this->rigidObjPub->Publish(boundary_particles_msg); } void FluidSimulator::publishFluidParticles() { if (simulationSteps % 5 == 0) { msgs::Fluid fluid_positions_msg; fluid_positions_msg.set_name("fluid_positions"); for (unsigned int j = 0; j < Simulation::getCurrent()->numberOfFluidModels(); j++) { FluidModel *model = Simulation::getCurrent()->getFluidModel(j); //std::cout << "Density " << model->getViscosityBase()->VISCOSITY_COEFFICIENT << std::endl;; for (unsigned int i = 0; i < model->numActiveParticles(); ++i) { gazebo::msgs::Set(fluid_positions_msg.add_position(), ignition::math::Vector3d( model->getPosition(i)[0], model->getPosition(i)[1], model->getPosition(i)[2])); } this->fluidObjPub->Publish(fluid_positions_msg); } } } void FluidSimulator::Init() { this->node = transport::NodePtr(new transport::Node()); this->node->Init(this->world->Name()); this->fluidObjPub = this->node->Advertise<msgs::Fluid>("~/fluid_pos", 10); this->rigidObjPub = this->node->Advertise<msgs::Fluid>("~/rigids_pos", 10); base = std::make_unique<GazeboSimulatorBase>(); base->init(this->fluidPluginSdf); this->ParseSDF(); base->initSimulation(); base->initBoundaryData(); this->publishBoundaryParticles(); } void FluidSimulator::Load(physics::WorldPtr parent, sdf::ElementPtr sdf) { this->world = parent; this->fluidPluginSdf = sdf; this->connections.push_back(event::Events::ConnectWorldUpdateEnd( boost::bind(&FluidSimulator::RunStep, this))); } void FluidSimulator::RegisterMesh(physics::CollisionPtr collision, std::string extension, std::string path) { // Get collision mesh by name const gazebo::common::Mesh *mesh = common::MeshManager::Instance()->GetMesh(collision->GetName()); // Export the mesh to a temp file in the selected format std::string objFilePath = path + collision->GetModel()->GetName() + "_" + collision->GetName() + ".obj"; common::MeshManager::Instance()->Export(mesh, FileSystem::normalizePath(objFilePath), extension); base->processBoundary(collision, objFilePath); } void FluidSimulator::ParseSDF() { // get all models from the world physics::Model_V models = world->Models(); // iterate through all models for (physics::Model_V::iterator currentModel = models.begin(); currentModel != models.end(); ++currentModel) { // get all links from the model physics::Link_V model_links = currentModel->get()->GetLinks(); std::cout << "Model: " << currentModel->get()->GetName() << std::endl; // iterate through all the links for (physics::Link_V::iterator link_it = model_links.begin(); link_it != model_links.end(); ++link_it) { // get all collisions of the link physics::Collision_V collisions = link_it->get()->GetCollisions(); std::cout << "\t Link: " << link_it->get()->GetName() << std::endl; // iterate through all the collisions for (physics::Collision_V::iterator collision_it = collisions.begin(); collision_it != collisions.end(); ++collision_it) { std::cout << "\t\t Collision: " << (*collision_it)->GetName() << std::endl; physics::CollisionPtr coll_ptr = boost::static_pointer_cast<physics::Collision>(*collision_it); // check the geometry type of the given collision sdf::ElementPtr geometry_elem = coll_ptr->GetSDF()->GetElement("geometry"); // get the name of the geometry std::string geometry_type = geometry_elem->GetFirstElement()->GetName(); // check type of the geometry if (geometry_type == "box") { // Get the size of the box ignition::math::Vector3d size = geometry_elem->GetElement(geometry_type)->Get<ignition::math::Vector3d>("size"); // Create box shape common::MeshManager::Instance()->CreateBox((*collision_it)->GetName(), ignition::math::Vector3d(size.X(), size.Y(), size.Z()), ignition::math::Vector2d(1, 1)); // Generate an obj file in the temporary directory containing the mesh of the box RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "cylinder") { // Cylinder dimensions double radius = geometry_elem->GetElement(geometry_type)->GetElement("radius")->Get<double>(); double length = geometry_elem->GetElement(geometry_type)->GetElement("length")->Get<double>(); // Create cylinder mesh common::MeshManager::Instance()->CreateCylinder((*collision_it)->GetName(), radius, length, 32, 32); //Generate an obj file in the temporary directory containing the mesh of the cylinder RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "sphere") { // Sphere radius double radius = geometry_elem->GetElement(geometry_type)->GetElement("radius")->Get<double>(); // Create a sphere mesh common::MeshManager::Instance()->CreateSphere((*collision_it)->GetName(), radius, 32, 32); // Generate an obj file in the temporary directory containing the mesh of the sphere RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "plane") { ignition::math::Vector3d normal; ignition::math::Vector2d size; // Plane dimensions. To prevent a huge plane which causes problems when // sampling it, for now it is harcoded if ((*collision_it)->GetName() == "collision_ground_plane") { normal = ignition::math::Vector3d(0, 0, 1); // = geom_elem->GetElement(geom_type)->GetElement("normal")->Get<ignition::math::Vector3d>(); size = ignition::math::Vector2d(2.0, 2.0); //= geom_elem->GetElement(geom_type)->GetElement("size")->Get<ignition::math::Vector2d>(); } else { normal = geometry_elem->GetElement(geometry_type)->GetElement("normal")->Get<ignition::math::Vector3d>(); size = geometry_elem->GetElement(geometry_type)->GetElement("size")->Get<ignition::math::Vector2d>(); } // Generate the plane mesh common::MeshManager::Instance()->CreatePlane((*collision_it)->GetName(), ignition::math::Vector3d(0.0, 0.0, 1.0), 0.0, size, ignition::math::Vector2d(4.0, 4.0), ignition::math::Vector2d()); //Generate an obj file in the temporary directory containing the mesh of the plane RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "mesh") { // get the uri element value const std::string uri = geometry_elem->GetElement(geometry_type)->GetElement("uri")->Get<std::string>(); // get the filepath from the uri const std::string filepath = common::SystemPaths::Instance()->FindFileURI(uri); const gazebo::common::Mesh *mesh = common::MeshManager::Instance()->GetMesh(filepath); std::string fullMeshPath = objFilePath + (*collision_it)->GetModel()->GetName() + "_" + (*collision_it)->GetName() + ".obj"; // Export the mesh to a temp file in the selected format common::MeshManager::Instance()->Export(mesh, FileSystem::normalizePath(fullMeshPath), "obj"); base->processBoundary(*collision_it, fullMeshPath); } else { // Error for other possible weird types gzerr << "Collision type [" << geometry_type << "] unimplemented\n"; } } } } } void FluidSimulator::reset() { /* Utilities::Timing::printAverageTimes(); Utilities::Timing::reset(); Utilities::Counting::printAverageCounts(); Utilities::Counting::reset(); Simulation::getCurrent()->reset(); base->reset(); */ } GZ_REGISTER_WORLD_PLUGIN(FluidSimulator)
34.823529
194
0.694785
ManosAgelidis
3c8aa450c85ee35f33e7ec707c374146b4c4a929
792
cpp
C++
Leetcode/construct_binary_search_tree.cpp
amrfahmyy/Problem-Solving
4c7540a1df3c4be206fc6dc6c77d754b513b314f
[ "Apache-2.0" ]
null
null
null
Leetcode/construct_binary_search_tree.cpp
amrfahmyy/Problem-Solving
4c7540a1df3c4be206fc6dc6c77d754b513b314f
[ "Apache-2.0" ]
null
null
null
Leetcode/construct_binary_search_tree.cpp
amrfahmyy/Problem-Solving
4c7540a1df3c4be206fc6dc6c77d754b513b314f
[ "Apache-2.0" ]
1
2021-04-02T14:20:11.000Z
2021-04-02T14:20:11.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int id; TreeNode* solve(vector<int>& preorder , int limit ){ if(id >= preorder.size() ){ return NULL; } int curr_value = preorder[id]; if(curr_value > limit){ return NULL; } TreeNode* root = new TreeNode(curr_value); id++; root->left = solve(preorder, curr_value ); root->right = solve(preorder, limit ); return root; } TreeNode* bstFromPreorder(vector<int>& preorder) { id = 0; return solve(preorder , INT_MAX); } };
20.842105
59
0.525253
amrfahmyy
3c91660a1a83bf1f254ed3c383b561cd43f2cbf8
292
cpp
C++
BlueprintToRSTDoc/Source/BlueprintToRSTDoc/Private/Commands.cpp
kant/UE4-BlueprintToRSTDoc
68353d924c24ab28fbe142503102413a2658adb4
[ "MIT" ]
1
2020-10-04T13:02:29.000Z
2020-10-04T13:02:29.000Z
BlueprintToRSTDoc/Source/BlueprintToRSTDoc/Private/Commands.cpp
kant/UE4-BlueprintToRSTDoc
68353d924c24ab28fbe142503102413a2658adb4
[ "MIT" ]
null
null
null
BlueprintToRSTDoc/Source/BlueprintToRSTDoc/Private/Commands.cpp
kant/UE4-BlueprintToRSTDoc
68353d924c24ab28fbe142503102413a2658adb4
[ "MIT" ]
1
2021-06-19T19:53:09.000Z
2021-06-19T19:53:09.000Z
#include "Commands.h" #define LOCTEXT_NAMESPACE "FBlueprintToRSTDocModule" void FBlueprintToRSTDocCommands::RegisterCommands() { UI_COMMAND(Action, "BlueprintToRSTDoc", "Execute BlueprintToRSTDoc action", EUserInterfaceActionType::Button, FInputGesture()); } #undef LOCTEXT_NAMESPACE
24.333333
131
0.811644
kant
3c937dfd6c6cbc326643346943b5242e24a5697f
3,170
cpp
C++
RedneckEngine/TestCube.cpp
TheHolyBell/RedneckEngine
3534b24de3ef5336bec9f7b04c31cbb4a5b8cc6e
[ "MIT" ]
null
null
null
RedneckEngine/TestCube.cpp
TheHolyBell/RedneckEngine
3534b24de3ef5336bec9f7b04c31cbb4a5b8cc6e
[ "MIT" ]
null
null
null
RedneckEngine/TestCube.cpp
TheHolyBell/RedneckEngine
3534b24de3ef5336bec9f7b04c31cbb4a5b8cc6e
[ "MIT" ]
null
null
null
#include "TestCube.h" #include "Cube.h" #include "BindableCodex.h" #include "ImGui\imgui.h" #include "BindableCommon.h" #include "Texture.h" #include "Sampler.h" #include "TransformCbufDoubleBoi.h" #include "DepthStencil.h" using namespace DirectX; TestCube::TestCube(Graphics& gfx, float size) { using namespace Bind; auto model = Cube::MakeIndependentTextured(); model.Transform(XMMatrixScaling(size, size, size)); model.SetNormalsIndependentFlat(); m_UID = "$cube." + std::to_string(size); AddBind(VertexBuffer::Resolve(gfx, m_UID, model.vertices)); AddBind(IndexBuffer::Resolve(gfx, m_UID, model.indices)); AddBind(Texture::Resolve(gfx, "Images\\brickwall.jpg")); AddBind(Texture::Resolve(gfx, "Images\\brickwall_normal.jpg", 1.0f)); AddBind(Sampler::Resolve(gfx)); auto pvs = VertexShader::Resolve(gfx, "PhongVS.cso"); auto pvsbc = pvs->GetBytecode(); AddBind(std::move(pvs)); AddBind(PixelShader::Resolve(gfx, "PhongPSNormalMap.cso")); AddBind(PixelConstantBuffer<PSMaterialConstant>::Resolve(gfx, pmc, 1.0f)); AddBind(InputLayout::Resolve(gfx, model.vertices.GetLayout(), pvsbc)); AddBind(Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST)); AddBind(std::make_shared<TransformCbufDoubleBoi>(gfx, *this, 0, 2)); AddBind(std::make_shared<Blender>(gfx, false, 0.5f)); AddBind(Rasterizer::Resolve(gfx, false)); AddBind(Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST)); AddBind(DepthStencil::Resolve(gfx)); } void TestCube::SetPos(DirectX::XMFLOAT3 pos) noexcept { m_pos = pos; } void TestCube::SetRotation(float pitch, float yaw, float roll) noexcept { this->pitch = pitch; this->yaw = yaw; this->roll = roll; } void TestCube::Draw(Graphics& gfx) const noexcept(!IS_DEBUG) { Drawable::Draw(gfx); } DirectX::XMMATRIX TestCube::GetTransformXM() const noexcept { return XMMatrixRotationRollPitchYaw(pitch, yaw, roll) * XMMatrixTranslation(m_pos.x, m_pos.y, m_pos.z); } std::string TestCube::GetUID() const noexcept { return m_UID; } void TestCube::ItemSelected() noexcept { m_bMenu = true; } bool TestCube::IsMenuDrawable() const noexcept { return m_bMenu; } void TestCube::DrawMenu(Graphics& gfx) noexcept { if (ImGui::Begin(m_UID.c_str(), &m_bMenu)) { ImGui::Text("Position"); ImGui::SliderFloat("X", &m_pos.x, -80.0f, 80.0f, "%.1f"); ImGui::SliderFloat("Y", &m_pos.y, -80.0f, 80.0f, "%.1f"); ImGui::SliderFloat("Z", &m_pos.z, -80.0f, 80.0f, "%.1f"); ImGui::Text("Orientation"); ImGui::SliderAngle("Pitch", &pitch, -180.0f, 180.0f); ImGui::SliderAngle("Yaw", &yaw, -180.0f, 180.0f); ImGui::SliderAngle("Roll", &roll, -180.0f, 180.0f); ImGui::Text("Shading"); bool changed0 = ImGui::SliderFloat("Spec. Int.", &pmc.specularIntensity, 0.0f, 1.0f); bool changed1 = ImGui::SliderFloat("Spec. Power", &pmc.specularPower, 0.0f, 100.0f); bool checkState = pmc.normalMappingEnabled == TRUE; bool changed2 = ImGui::Checkbox("Enable Normal Map", &checkState); pmc.normalMappingEnabled = checkState ? TRUE : FALSE; if (changed0 || changed1 || changed2) { QueryBindable<Bind::PixelConstantBuffer<PSMaterialConstant>>()->Update(gfx, pmc); } } ImGui::End(); }
27.327586
87
0.714196
TheHolyBell
3c9440e837a8092f0aa831c54ba9f3b65900d62e
2,969
cpp
C++
Behaviour/Source/Behaviour/BehaviourModifier.cpp
DeLaMercedRichard/AIbs_Demo
e5a1d2e870c1d0919d456df31f34fe0520b6975d
[ "MIT" ]
1
2020-04-05T22:10:34.000Z
2020-04-05T22:10:34.000Z
Behaviour/Source/Behaviour/BehaviourModifier.cpp
DeLaMercedRichard/AIbs_Demo
e5a1d2e870c1d0919d456df31f34fe0520b6975d
[ "MIT" ]
null
null
null
Behaviour/Source/Behaviour/BehaviourModifier.cpp
DeLaMercedRichard/AIbs_Demo
e5a1d2e870c1d0919d456df31f34fe0520b6975d
[ "MIT" ]
1
2020-02-04T11:36:54.000Z
2020-02-04T11:36:54.000Z
#include "BehaviourModifier.h" BehaviourModifier::BehaviourModifier() { } BehaviourModifier::~BehaviourModifier() { //Do I still Delete ID? //Or just set it to nullptr delete ID; ID = nullptr; } void BehaviourModifier::AttachID(std::string &ID_) { *ID = ID_; } void BehaviourModifier::GenerateGenderTrait(bool autoGenerateGenders, int genderRatio) { //Takes the string value of the ID and assigns 1/2 male and 1/2 female population if (autoGenerateGenders) { if (std::stoi(*ID) % genderRatio == 0) { genderTrait = true; } else { genderTrait = false; } } else { genderTrait = true; } } void BehaviourModifier::AdjustPersonality(int personalityType, double distributionMean, double distributionOffset) { switch (personalityType) { case 0: personality00.adjustDistribution(distributionMean, distributionOffset); break; case 1: personality01.adjustDistribution(distributionMean, distributionOffset); break; case 2: personality02.adjustDistribution(distributionMean, distributionOffset); break; case 3: personality03.adjustDistribution(distributionMean, distributionOffset); break; default: personalityType = 0; break; } } void BehaviourModifier::ForcefullySetPersonalityValue(int personalityValue, double value) { switch (personalityValue) { case 0: personality00.setValueForcefully(value); break; case 1: personality01.setValueForcefully(value); break; case 2: personality02.setValueForcefully(value); break; case 3: personality03.setValueForcefully(value); break; default: personalityValue = 0; break; } } void BehaviourModifier::EstablishPersonality() { personality00.EstablishPersonality(genderTrait); personality01.EstablishPersonality(genderTrait); personality02.EstablishPersonality(genderTrait); personality03.EstablishPersonality(genderTrait); } void BehaviourModifier::PrintPersonalityInfo(int personalityType) { switch (personalityType) { case 0: personality00.Print(); break; case 1: personality01.Print(); break; case 2: personality02.Print(); break; case 3: personality03.Print(); break; default: personalityType = 0; break; } } std::string BehaviourModifier::getPersonalityName(int personalityType) { switch (personalityType) { case 0: return personality00.getPersonalityName(); break; case 1: return personality01.getPersonalityName(); break; case 2: return personality02.getPersonalityName(); break; case 3: return personality03.getPersonalityName(); break; default: return personality00.getPersonalityName(); break; } } double BehaviourModifier::getPersonalityValue(int personalityType) { switch (personalityType) { case 0: return personality00.getValue(); break; case 1: return personality01.getValue(); break; case 2: return personality02.getValue(); break; case 3: return personality03.getValue(); break; default: return personality00.getValue(); break; } }
17.993939
114
0.748063
DeLaMercedRichard
3c961b08ca4de85f011a68851f48edffdc14be40
4,332
cpp
C++
utils/Utils.cpp
turol/smaaDemo
d6e02955b1b5396162d2ba67b78798e43cebfc57
[ "MIT" ]
64
2015-10-30T10:06:24.000Z
2022-03-10T01:47:25.000Z
utils/Utils.cpp
turol/smaaDemo
d6e02955b1b5396162d2ba67b78798e43cebfc57
[ "MIT" ]
7
2015-11-29T09:52:37.000Z
2020-12-14T11:00:33.000Z
utils/Utils.cpp
turol/smaaDemo
d6e02955b1b5396162d2ba67b78798e43cebfc57
[ "MIT" ]
5
2015-12-28T21:07:20.000Z
2021-01-28T09:25:36.000Z
/* Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cassert> #include <cerrno> #include <cstring> #include <sys/stat.h> #include <stdexcept> #include "Utils.h" #include <SDL.h> struct FILEDeleter { void operator()(FILE *f) { fclose(f); } }; static FILE *logFile; void logInit() { assert(!logFile); char *logFilePath = SDL_GetPrefPath("", "SMAADemo"); std::string logFileName(logFilePath); SDL_free(logFilePath); logFileName += "logfile.txt"; logFile = fopen(logFileName.c_str(), "wb"); } void logWrite(const nonstd::string_view &message) { // Write to console if opening log file failed FILE *f = logFile ? logFile : stdout; fwrite(message.data(), 1, message.size(), f); fputc('\n', f); } void logWriteError(const nonstd::string_view &message) { // Write to log and stderr if (logFile) { fwrite(message.data(), 1, message.size(), logFile); fputc('\n', logFile); fflush(logFile); } fwrite(message.data(), 1, message.size(), stderr); fputc('\n', stderr); fflush(stderr); } void logShutdown() { assert(logFile); fflush(logFile); fclose(logFile); logFile = nullptr; } void logFlush() { assert(logFile); fflush(logFile); } std::vector<char> readTextFile(std::string filename) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb")); if (!file) { THROW_ERROR("file not found {}", filename); } int fd = fileno(file.get()); if (fd < 0) { THROW_ERROR("no fd"); } struct stat statbuf; memset(&statbuf, 0, sizeof(struct stat)); int retval = fstat(fd, &statbuf); if (retval < 0) { THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno)); } unsigned int filesize = static_cast<unsigned int>(statbuf.st_size); // ensure NUL -termination std::vector<char> buf(filesize + 1, '\0'); size_t ret = fread(&buf[0], 1, filesize, file.get()); if (ret != filesize) { THROW_ERROR("fread failed"); } return buf; } std::vector<char> readFile(std::string filename) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb")); if (!file) { THROW_ERROR("file not found {}", filename); } int fd = fileno(file.get()); if (fd < 0) { THROW_ERROR("no fd"); } struct stat statbuf; memset(&statbuf, 0, sizeof(struct stat)); int retval = fstat(fd, &statbuf); if (retval < 0) { THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno)); } unsigned int filesize = static_cast<unsigned int>(statbuf.st_size); std::vector<char> buf(filesize, '\0'); size_t ret = fread(&buf[0], 1, filesize, file.get()); if (ret != filesize) { THROW_ERROR("fread failed"); } return buf; } void writeFile(const std::string &filename, const void *contents, size_t size) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "wb")); fwrite(contents, 1, size, file.get()); } bool fileExists(const std::string &filename) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb")); if (file) { return true; } else { return false; } } int64_t getFileTimestamp(const std::string &filename) { struct stat statbuf; memset(&statbuf, 0, sizeof(struct stat)); int retval = stat(filename.c_str(), &statbuf); if (retval < 0) { THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno)); } return statbuf.st_mtime; }
23.416216
80
0.695522
turol
3c9675a5b03d019456953620329634d31e6c657b
5,188
hpp
C++
domain/include/cstone/util/util.hpp
j-piccinali/SPH-EXA_mini-app
c3ba4d37f2edf433710d5c0bc2362ec35e75df32
[ "MIT" ]
14
2019-03-18T12:51:43.000Z
2021-11-09T14:40:36.000Z
domain/include/cstone/util/util.hpp
j-piccinali/SPH-EXA_mini-app
c3ba4d37f2edf433710d5c0bc2362ec35e75df32
[ "MIT" ]
41
2019-10-08T19:53:55.000Z
2021-11-23T06:56:03.000Z
domain/include/cstone/util/util.hpp
j-piccinali/SPH-EXA_mini-app
c3ba4d37f2edf433710d5c0bc2362ec35e75df32
[ "MIT" ]
8
2019-06-20T07:11:52.000Z
2021-10-05T13:44:07.000Z
/* * MIT License * * Copyright (c) 2021 CSCS, ETH Zurich * 2021 University of Basel * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /*! @file * @brief General purpose utilities * * @author Sebastian Keller <sebastian.f.keller@gmail.com> */ #pragma once #include <utility> #include "cstone/cuda/annotation.hpp" /*! @brief A template to create structs as a type-safe version to using declarations * * Used in public API functions where a distinction between different * arguments of the same underlying type is desired. This provides a type-safe * version to using declarations. Instead of naming a type alias, the name * is used to define a struct that inherits from StrongType<T>, where T is * the underlying type. * * Due to the T() conversion and assignment from T, * an instance of StrongType<T> struct behaves essentially like an actual T, while construction * from T is disabled. This makes it impossible to pass a T as a function parameter * of type StrongType<T>. */ template<class T, class Phantom> struct StrongType { using ValueType [[maybe_unused]] = T; //! default ctor constexpr HOST_DEVICE_FUN StrongType() : value_{} {} //! construction from the underlying type T, implicit conversions disabled explicit constexpr HOST_DEVICE_FUN StrongType(T v) : value_(std::move(v)) {} //! assignment from T constexpr HOST_DEVICE_FUN StrongType& operator=(T v) { value_ = std::move(v); return *this; } //! conversion to T constexpr HOST_DEVICE_FUN operator T() const { return value_; } // NOLINT //! access the underlying value constexpr HOST_DEVICE_FUN T value() const { return value_; } private: T value_; }; /*! @brief StrongType equality comparison * * Requires that both T and Phantom template parameters match. * For the case where a comparison between StrongTypes with matching T, but differing Phantom * parameters is desired, the underlying value attribute should be compared instead */ template<class T, class Phantom> constexpr HOST_DEVICE_FUN bool operator==(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return lhs.value() == rhs.value(); } //! @brief comparison function < template<class T, class Phantom> constexpr HOST_DEVICE_FUN bool operator<(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return lhs.value() < rhs.value(); } //! @brief comparison function > template<class T, class Phantom> constexpr HOST_DEVICE_FUN bool operator>(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return lhs.value() > rhs.value(); } //! @brief addition template<class T, class Phantom> constexpr HOST_DEVICE_FUN StrongType<T, Phantom> operator+(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return StrongType<T, Phantom>(lhs.value() + rhs.value()); } //! @brief subtraction template<class T, class Phantom> constexpr HOST_DEVICE_FUN StrongType<T, Phantom> operator-(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return StrongType<T, Phantom>(lhs.value() - rhs.value()); } //! @brief simple pair that's usable in both CPU and GPU code template<class T> class pair { public: constexpr pair() = default; HOST_DEVICE_FUN constexpr pair(T first, T second) : data{first, second} {} HOST_DEVICE_FUN constexpr T& operator[](int i) { return data[i]; } HOST_DEVICE_FUN constexpr const T& operator[](int i) const { return data[i]; } private: HOST_DEVICE_FUN friend constexpr bool operator==(const pair& a, const pair& b) { return a.data[0] == b.data[0] && a.data[1] == b.data[1]; } HOST_DEVICE_FUN friend constexpr bool operator<(const pair& a, const pair& b) { bool c0 = a.data[0] < b.data[0]; bool e0 = a.data[0] == b.data[0]; bool c1 = a.data[1] < b.data[1]; return c0 || (e0 && c1); } T data[2]; }; //! @brief ceil(divident/divisor) for integers HOST_DEVICE_FUN constexpr unsigned iceil(size_t dividend, unsigned divisor) { return (dividend + divisor - 1) / divisor; }
32.223602
102
0.707016
j-piccinali
3c977fa0b4aff05ed2221cfc9967e8e5ed81746e
5,583
hpp
C++
core/KVMESC.hpp
Domaman202/DmNKVM
e867f5369426954ad7836aba47cc86f9b657d5b2
[ "MIT" ]
1
2021-07-24T14:33:54.000Z
2021-07-24T14:33:54.000Z
core/KVMESC.hpp
Domaman202/DmNKVM
e867f5369426954ad7836aba47cc86f9b657d5b2
[ "MIT" ]
null
null
null
core/KVMESC.hpp
Domaman202/DmNKVM
e867f5369426954ad7836aba47cc86f9b657d5b2
[ "MIT" ]
null
null
null
#ifndef DMN_KVM_NO_USE_PRAGMA #pragma once #endif /* DMN_KVM_NO_USE_PRAGMA */ #ifndef DMN_KVM_ESC_HPP #define DMN_KVM_ESC_HPP #include "KVMTypes.hpp" #include <cstdint> namespace DmN::KVM { /// Объект (нет) который может быть инстансирован struct Instanceble_t { virtual Object_t *newInstance(Value_t **args, size_t args_c) { return nullptr; }; }; /// Универсальная основа для Enum-а struct Enum_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t { explicit Enum_t(SI_t name, uint8_t modifier, Value_t **enums, SI_t *names, uint8_t enumsCount) : LLTNameble(name, LLTypes::ENUM), Modifiable(modifier) { this->enums = enums; this->names = names; this->enumsCount = enumsCount; } SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } struct Object_t *newInstance(Value_t **args, size_t args_c) override { return nullptr; // TODO: } /// Перечисления Value_t **enums; /// Имена перечислений SI_t *names; /// Кол-во перечислений uint8_t enumsCount; }; /// Универсальная основа для структуры struct Struct_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t { explicit Struct_t(SI_t name, uint8_t modifier, Field_t **fields, uint8_t fieldsCount, CI_t *parents, uint8_t parentsCount) : LLTNameble(name, LLTypes::STRUCT), Modifiable(modifier) { this->fields = fields; this->fieldsCount = fieldsCount; this->parents = parents; this->parentsCount = parentsCount; } SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } struct Object_t *newInstance(Value_t **args, size_t args_c) override { return nullptr; // TODO: } /// Поля Field_t **fields; /// Кол-во полей uint8_t fieldsCount; /// Предки (ID предков) CI_t *parents; /// Кол-во предков uint8_t parentsCount: 5; }; /// Универсальная основа для Class-а class Class_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t, public MethodStorage_t { public: explicit Class_t(SI_t name, uint8_t modifier, Field_t **fields, uint8_t fieldsCount, Method_t **methods, uint8_t methodsCount, CI_t *parents, uint8_t parentsCount) : LLTNameble(name, LLTypes::CLASS), Modifiable(modifier) { this->fields = fields; this->fieldsCount = fieldsCount; this->methods = methods; this->methodsCount = methodsCount; this->parents = parents; this->parentsCount = parentsCount; } SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } SDL::DmNCollection<Method_t> *getMethods() override { return nullptr; // TODO: } struct Object_t *newInstance(Value_t **args, size_t args_c) override { return nullptr; // TODO: } /// Массив полей Field_t **fields; /// Кол-во полей uint8_t fieldsCount; /// Массив методов Method_t **methods; /// Кол-во методов uint8_t methodsCount; /// Предки (ID предков) CI_t *parents; /// Кол-во предков uint8_t parentsCount: 5; }; /// Основа класса со встроенными классами class ISClass_t : public Class_t { public: explicit ISClass_t(Class_t *base, SI_t name, uint8_t modifier, Field_t **fields, uint32_t fieldsCount, Method_t **methods, uint32_t methodsCount, CI_t *parents, uint8_t parentsCount) : Class_t(name, modifier, fields, fieldsCount, methods, methodsCount, parents, parentsCount) { this->base = base; } /// Основной класс Class_t *base; }; class EnumClass_t : public Class_t, public Enum_t { SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } SDL::DmNCollection<Method_t> *getMethods() override { return nullptr; // TODO: } }; } #endif /* DMN_KVM_ESC_HPP */
36.253247
113
0.475551
Domaman202
3c9a4725911773f54a598f628eee18203143752a
955
cpp
C++
binary-search-tree-iterator/binary-search-tree-iterator.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
2
2021-08-29T12:51:09.000Z
2021-10-18T23:24:41.000Z
binary-search-tree-iterator/binary-search-tree-iterator.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
binary-search-tree-iterator/binary-search-tree-iterator.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class BSTIterator { public: stack<int> st; void getin(TreeNode* root) { if(!root) return ; getin(root->right); st.push(root->val); getin(root->left); } BSTIterator(TreeNode* root) { getin(root); } int next() { int i =st.top(); st.pop(); return i; } bool hasNext() { return !st.empty(); } }; /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator* obj = new BSTIterator(root); * int param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
22.738095
93
0.543455
itzpankajpanwar
3c9a649771c9a9087e5c623efd774c7e68b059bc
6,747
cpp
C++
firmware/examples/4_temp_logger.cpp
monkbroc/makerkit
e6924eee209da662a47df9a5da1bf97d07ee599d
[ "BSD-3-Clause" ]
3
2019-03-20T01:23:22.000Z
2020-09-17T20:04:48.000Z
firmware/examples/4_temp_logger.cpp
monkbroc/makerkit
e6924eee209da662a47df9a5da1bf97d07ee599d
[ "BSD-3-Clause" ]
null
null
null
firmware/examples/4_temp_logger.cpp
monkbroc/makerkit
e6924eee209da662a47df9a5da1bf97d07ee599d
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ This sketch reads the temperature from a OneWire device and then publishes to the Particle cloud. From there, IFTTT can be used to log the date, time, and temperature to a Google Spreadsheet. Read more in our tutorial here: http://docs.particle.io/tutorials/topics/maker-kit This sketch is the same as the example from the OneWire library, but with the addition of three lines at the end to publish the data to the cloud. Use this sketch to read the temperature from 1-Wire devices you have attached to your Particle device (core, p0, p1, photon, electron) Temperature is read from: DS18S20, DS18B20, DS1822, DS2438 Expanding on the enumeration process in the address scanner, this example reads the temperature and outputs it from known device types as it scans. I/O setup: These made it easy to just 'plug in' my 18B20 (note that a bare TO-92 sensor may read higher than it should if it's right next to the Photon) D3 - 1-wire ground, or just use regular pin and comment out below. D4 - 1-wire signal, 2K-10K resistor to D5 (3v3) D5 - 1-wire power, ditto ground comment. A pull-up resistor is required on the signal line. The spec calls for a 4.7K. I have used 1K-10K depending on the bus configuration and what I had out on the bench. If you are powering the device, they all work. If you are using parisidic power it gets more picky about the value. NOTE: This sketch requires the OneWire library, which can be added from the <-- Libraries tab on the left. ************************************************************************/ OneWire ds = OneWire(D4); // 1-wire signal on pin D4 unsigned long lastUpdate = 0; float lastTemp; void setup() { Serial.begin(9600); // Set up 'power' pins, comment out if not used! pinMode(D3, OUTPUT); pinMode(D5, OUTPUT); digitalWrite(D3, LOW); digitalWrite(D5, HIGH); } // up to here, it is the same as the address acanner // we need a few more variables for this example void loop(void) { byte i; byte present = 0; byte type_s; byte data[12]; byte addr[8]; float celsius, fahrenheit; if ( !ds.search(addr)) { Serial.println("No more addresses."); Serial.println(); ds.reset_search(); delay(250); return; } // The order is changed a bit in this example // first the returned address is printed Serial.print("ROM ="); for( i = 0; i < 8; i++) { Serial.write(' '); Serial.print(addr[i], HEX); } // second the CRC is checked, on fail, // print error and just return to try again if (OneWire::crc8(addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return; } Serial.println(); // we have a good address at this point // what kind of chip do we have? // we will set a type_s value for known types or just return // the first ROM byte indicates which chip switch (addr[0]) { case 0x10: Serial.println(" Chip = DS1820/DS18S20"); type_s = 1; break; case 0x28: Serial.println(" Chip = DS18B20"); type_s = 0; break; case 0x22: Serial.println(" Chip = DS1822"); type_s = 0; break; case 0x26: Serial.println(" Chip = DS2438"); type_s = 2; break; default: Serial.println("Unknown device type."); return; } // this device has temp so let's read it ds.reset(); // first clear the 1-wire bus ds.select(addr); // now select the device we just found // ds.write(0x44, 1); // tell it to start a conversion, with parasite power on at the end ds.write(0x44, 0); // or start conversion in powered mode (bus finishes low) // just wait a second while the conversion takes place // different chips have different conversion times, check the specs, 1 sec is worse case + 250ms // you could also communicate with other devices if you like but you would need // to already know their address to select them. delay(1000); // maybe 750ms is enough, maybe not, wait 1 sec for conversion // we might do a ds.depower() (parasite) here, but the reset will take care of it. // first make sure current values are in the scratch pad present = ds.reset(); ds.select(addr); ds.write(0xB8,0); // Recall Memory 0 ds.write(0x00,0); // Recall Memory 0 // now read the scratch pad present = ds.reset(); ds.select(addr); ds.write(0xBE,0); // Read Scratchpad if (type_s == 2) { ds.write(0x00,0); // The DS2438 needs a page# to read } // transfer and print the values Serial.print(" Data = "); Serial.print(present, HEX); Serial.print(" "); for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); Serial.print(data[i], HEX); Serial.print(" "); } Serial.print(" CRC="); Serial.print(OneWire::crc8(data, 8), HEX); Serial.println(); // Convert the data to actual temperature // because the result is a 16 bit signed integer, it should // be stored to an "int16_t" type, which is always 16 bits // even when compiled on a 32 bit processor. int16_t raw = (data[1] << 8) | data[0]; if (type_s == 2) raw = (data[2] << 8) | data[1]; byte cfg = (data[4] & 0x60); switch (type_s) { case 1: raw = raw << 3; // 9 bit resolution default if (data[7] == 0x10) { // "count remain" gives full 12 bit resolution raw = (raw & 0xFFF0) + 12 - data[6]; } celsius = (float)raw * 0.0625; break; case 0: // at lower res, the low bits are undefined, so let's zero them if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms // default is 12 bit resolution, 750 ms conversion time celsius = (float)raw * 0.0625; break; case 2: data[1] = (data[1] >> 3) & 0x1f; if (data[2] > 127) { celsius = (float)data[2] - ((float)data[1] * .03125); }else{ celsius = (float)data[2] + ((float)data[1] * .03125); } } // remove random errors if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) { celsius = lastTemp; } fahrenheit = celsius * 1.8 + 32.0; lastTemp = celsius; Serial.print(" Temperature = "); Serial.print(celsius); Serial.print(" Celsius, "); Serial.print(fahrenheit); Serial.println(" Fahrenheit"); // now that we have the readings, we can publish them to the cloud String temperature = String(fahrenheit); // store temp in "temperature" string Particle.publish("temperature", temperature, PRIVATE); // publish to dashboard delay(5000); // 5-sec delay }
31.528037
98
0.625019
monkbroc
3c9a7c548c0ee4a27e8807207146ef45e767a93b
2,030
cpp
C++
src/126.word_ladder_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/126.word_ladder_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/126.word_ladder_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { private: unordered_map<string, int> pathLevel; unordered_map<string, vector<string>> nextNode; vector<vector<string>> ans; public: vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) { bfs(wordList, beginWord, endWord); vector<string> myans; dfs(wordList, beginWord, endWord, myans); return ans; } void bfs(unordered_set<string>& wordList, string beginWord, string endWord) { queue<string> q; q.push(beginWord); pathLevel[beginWord] = 0; while (!q.empty()) { string curWord = q.front(); q.pop(); int level = pathLevel[curWord]; if (curWord == endWord) continue; vector<string> myNextNode; for (int i = 0; i < curWord.length(); i++) { string nextWord = curWord; for (int j = 0; j < 26; j++) { if (curWord[i] == 'a' + j) continue; nextWord[i] = 'a' + j; if (wordList.find(nextWord) == wordList.end()) continue; if (pathLevel.find(nextWord) == pathLevel.end()) { pathLevel[nextWord] = level + 1; q.push(nextWord); } if (pathLevel[nextWord] == level + 1) myNextNode.push_back(nextWord); } } nextNode[curWord] = myNextNode; } } void dfs(unordered_set<string>& wordList, string curWord, string endWord, vector<string>& myans) { myans.push_back(curWord); if (curWord == endWord) { ans.push_back(myans); myans.pop_back(); return; } int level = pathLevel[curWord]; vector<string> myNextNode = nextNode[curWord]; for (int i = 0; i < myNextNode.size(); i++) { dfs(wordList, myNextNode[i], endWord, myans); } myans.pop_back(); } };
35.614035
107
0.519704
cloudzfy
3c9df28370629a72fd052162faba89972dee0c8d
17,105
cxx
C++
logger/dnk_biphasic_offset_cli.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
logger/dnk_biphasic_offset_cli.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
logger/dnk_biphasic_offset_cli.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
/* * dnk_biphasic_offset_cli.cxx * * Created on: 30 сент. 2019 г. * Author: root */ #include "dnk_biphasic_offset_cli.h" #ifdef _HIREDIS eErrorTp dnk_biphasic_offset_cli::make_selection_by_interval(u64 ts_start_ms,u64 ts_stop_ms,u32 limit,rapidjson::Document & result_root){ if (fault==ERROR){ GPRINT(NORMAL_LEVEL,"make_selection_by_interval is fault\n"); return ERROR; } GPRINT(MEDIUM_LEVEL,"Make_selection_by_interval ts_start_ms %llu ts_stop_ms %llu point_limit %u\n",ts_start_ms,ts_stop_ms,limit); //GPRINT(NORMAL_LEVEL,"make_selection_by_interval M1\n"); result_root.SetObject(); std::pair<eErrorTp, vector<string>> res,res2; TIME_T ts_stop=(u64)ts_stop_ms/1000; TIME_T ts_start=(u64)ts_start_ms/1000; TIME_T tss; //Json::Reader read; string fn_old; string format_path[total_storage]; //Json::Value header_root; rapidjson::Document header_root; bool format_getting=false; // bool result_root_init=false; u32 aidx=0; u32 limf=(limit/dal_lines_in_block)+1; res=command("ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1",ts_start,0); TIME_T ts_start_tmp=ts_start; if ((res.second.size()==0)||(res.first==ERROR)){ GPRINT(HARD_LEVEL,"ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1 result is null, try next time %llu\n",ts_start,0,ts_start_ms); } else //поиск предыдущего фрагмента, для захвата всего диапазона ts_start_tmp=stol(res.second[0]); res=command("HMGET %u te",ts_start_tmp); if ((res.second.size()==0)||(res.first==ERROR)){ GPRINT(HARD_LEVEL,"HMGET %u te result is null\n",ts_start_tmp); } else{ //пропустить фрагмент если его содержимое старее ts_start_tmp TIME_T et=stol(res.second[0]); if (et<ts_start) ts_start_tmp=et; } if (ts_start_tmp>ts_stop) return NO_ERROR; //printf("sts %lu ts_start %lu ts_stop %lu limf %u\n",TIME(NULL),ts_start,ts_stop,limf); //Search in files GPRINT(MEDIUM_LEVEL,"ZRANGEBYSCORE ts %u %u LIMIT 0 %u\n",ts_start_tmp,ts_stop,limf); res=command("ZRANGEBYSCORE ts %u %u LIMIT 0 %u",ts_start_tmp,ts_stop,limf); if ((res.first==ERROR)||(res.second.size()==0)){ GetFormatPath(format_path); if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } return make_selection_step_by_step_DB_All(ts_start_ms,ts_stop_ms,header_root,result_root); } u32 ctr=res.second.size(); GPRINT(MEDIUM_LEVEL,"Founded %d arch files\n",ctr); //printf("ts_start_ms %llu ts_stop_ms %llu ctr %u\n",ts_start_ms,ts_stop_ms,ctr); for (u32 z=0;z<ctr;z++){ res2=command("HMGET %s te cn ext crc",res.second[z].c_str()); TIME_T t_end=stoll(res2.second[0]); TIME_T t_st=stoll(res.second[z]); string fn=res.second[z]+'_'+res2.second[0]+':'+res2.second[1]+'['+res2.second[3]+"]."+res2.second[2]; string data; if (GetDataFromGzip(data,fn,t_st,format_path)==NO_ERROR){ rapidjson::Document dr_root; dr_root.SetObject(); rapidjson::Document data_root; rapidjson::ParseResult rapid_result=data_root.Parse(data.c_str()); if (rapid_result.Code()==0){ if (format_getting==false){ if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } format_getting=true; } MakeObjectFromDataAndHeader_rpd(data_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ return ERROR; } for (u32 e=0;e<dr_root["m"].Size();e++){ TIME_T t=dr_root["t"][e].GetInt(); ts_start_ms=dr_root["m"][e].GetUint64()+1; if (t<ts_start){ GPRINT(MEDIUM_LEVEL,"Skip ts %lu < start_ts %lu\n",t,ts_start); continue; } if (t>ts_stop){ GPRINT(MEDIUM_LEVEL,"Skip ts %lu > ts_stop %lu\n",t,ts_stop); continue; } // printf(" point %llu, found %llu\n",dia[r].ts[k],dr_root["m"][e].asUInt64()); for (auto & key:dr_root.GetObject() ){ const char* keys=key.name.GetString(); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } //if (dr_root[keys][e].IsString()) // printf("add %s\n",dr_root[keys][e].GetString()); // if (dr_root[keys][e].IsUint()) // printf("add %u\n",dr_root[keys][e].GetUint()); result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } aidx++; if (aidx>=limit) break; //result_root_init=true; } } } } if (format_getting==false){ GetFormatPath(format_path); if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } } make_selection_step_by_step_DB_All(ts_start_ms,ts_stop_ms,header_root,result_root); //printf("Search in DB %d\n",result_root["m"].size()); return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_rpd(u64 ts_start_ms,u64 ts_stop_ms,u32 interval_ms,TIME_T point_limit,rapidjson::Document & result_root){ if (fault==ERROR){ GPRINT(NORMAL_LEVEL,"make_selection_step_by_step is fault\n"); return ERROR; } if (interval_ms==0) return ERROR; GPRINT(MEDIUM_LEVEL,"Make_selection_step_by_step ts_start_ms %llu ts_stop_ms %llu interval_ms %llu point_limit %u\n",ts_start_ms,ts_stop_ms,interval_ms,point_limit); result_root.SetObject(); std::pair<eErrorTp, vector<string>> res_t,res,res2; vector<diapason> dia; u64 saved_ts_stop_ms=ts_stop_ms; TIME_T ts_stop=ts_stop_ms/1000; TIME_T ts_start=ts_start_ms/1000; TIME_T ctr=((ts_stop_ms-ts_start_ms)/interval_ms)+1; if (ctr>point_limit) ctr=point_limit; TIME_T t_st; TIME_T t_end; string fn; u64 t_end_ms; u64 t_st_ms; TIME_T ctr_cntr=0; GPRINT(MEDIUM_LEVEL,"\n*****\n**make_selection_step_by_step [start %llu stop %llu cntr %u interval_ms %u]\n",ts_start_ms,ts_stop_ms,ctr,interval_ms); while ((ts_start_ms<ts_stop_ms)&&(ctr>=ctr_cntr)){ ts_start=ts_start_ms/1000; ctr_cntr++; res=command("ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1",ts_start,0); if ((res.second.size()==0)||(res.first==ERROR)){ ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1 result is null, try next time %llu\n",ts_start,0,ts_start_ms); continue; } t_st=stoll(res.second[0]); GPRINT(HARD_LEVEL,"got %d\n",res.second.size()); res2=command("HMGET %s te cn ext crc",res.second[0].c_str()); if ((res2.second.size()==0)||(res2.first==ERROR)){ ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"HMGET %s te cn ext crc result is null, try next time %llu\n",res.second[0].c_str(),ts_start_ms); continue; } t_end=stoll(res2.second[0]); t_end_ms=(u64)t_end*1000; t_st_ms=(u64)t_st*1000; if ((ts_start>=t_st)&&(ts_start<=t_end)){ fn=res.second[0]+'_'+res2.second[0]+':'+res2.second[1]+'['+res2.second[3]+"]."+res2.second[2]; dia.emplace_back(ts_start_ms,ts_start,fn); ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"Collect %s, ts_start enter to diapason\n",fn.c_str()); //printf("t_st_ms %llu ts_start_ms %llu t_end_ms %llu\n",t_st_ms,ts_start_ms,t_end_ms); while((ts_start_ms>=t_st_ms)&&(ts_start_ms<=t_end_ms)){ dia[dia.size()-1].add(ts_start_ms); //printf("* fn %s point %llu>=%llu<=%llu\n",fn.c_str(),t_st_ms,ts_start_ms,t_end_ms); ts_start_ms+=interval_ms; } } else{ ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"Skip ts_start out in diapason [%u] %u [%u]\n",t_st,ts_start,t_end); } } u32 tp=0; bool result_root_init=false; u32 aidx=0; bool format_getting=false; rapidjson::Document header_root; string format_path[total_storage]; for (u32 r=0;r<dia.size();r++){ string data; if (GetDataFromGzip(data,dia[r].fname,dia[r].start_ts,format_path)==NO_ERROR){ rapidjson::Document dr_root; dr_root.SetObject(); rapidjson::Document data_root; rapidjson::ParseResult rapid_result=data_root.Parse(data.c_str()); if (rapid_result.Code()==0){ if (format_getting==false){ if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } format_getting=true; } MakeObjectFromDataAndHeader_rpd(data_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ return ERROR; } u32 k=0; u32 diasz=dia[r].ts.size(); for (u32 e=0;e<dr_root["m"].Size();e++){ if (((u64)dr_root["m"][e].GetInt64())>=dia[r].ts[k]){ for (auto& key : dr_root.GetObject()) { const char* keys=key.name.GetString(); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } k++; if (k>=diasz) { break; } } } } } tp+=dia[r].ts.size(); } if (format_getting==false){ GetFormatPath(format_path); if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } } if (dal_upload_from_DB_method==SBS_UPLOAD_METHOD_IN_DB_ALL) make_selection_step_by_step_DB_All(ts_start_ms,saved_ts_stop_ms,header_root,result_root); else make_selection_step_by_step_DB_step(ts_start_ms,saved_ts_stop_ms,interval_ms,header_root,result_root,aidx); return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_DB_All(u64 ts_start_ms,u64 saved_ts_stop_ms,rapidjson::Document & header_root,rapidjson::Document & result_root){ rapidjson::Document result_db_root; result_db_root.SetArray(); rapidjson::Document dr_root; dr_root.SetObject(); //u64 saved_ts_stop_ms=UINT64_MAX; //bool result_root_init=false; GPRINT(MEDIUM_LEVEL,"search elements in redis start %llu stop %llu\n",ts_start_ms,saved_ts_stop_ms); if ((make_selection_from_db(ts_start_ms,saved_ts_stop_ms,result_db_root)==NO_ERROR)){ if ((result_db_root.IsArray())&&(result_db_root.Size()!=0)){ MakeObjectFromDataAndHeader_rpd(result_db_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ GPRINT(MEDIUM_LEVEL,"temporary elements in redis is broken dump: %s\n",(char*)StyledWriteJSON(&dr_root).c_str()); return ERROR; } GPRINT(MEDIUM_LEVEL,"found [%u] temporary elements in redis\n",dr_root["m"].Size()); for (u32 e=0;e<dr_root["m"].Size();e++){ for (auto& key : dr_root.GetObject()){ const char* keys=key.name.GetString(); //printf("obj %s\n",keys); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } } return NO_ERROR; } else{ GPRINT(MEDIUM_LEVEL,"not found temporary elements in redis\n"); return ERROR; } } else{ GPRINT(MEDIUM_LEVEL,"redis db is broken\n"); return ERROR; } return ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_DB_step(u64 ts_start_ms,u64 saved_ts_stop_ms,u64 interval_ms,rapidjson::Document & header_root,rapidjson::Document & result_root,u32 & aidx){ rapidjson::Document result_db_root; result_db_root.SetArray(); rapidjson::Document dr_root; dr_root.SetObject(); //bool result_root_init=false; if ((make_selection_from_db(ts_start_ms,saved_ts_stop_ms,result_db_root)==NO_ERROR)){ if ((result_db_root.IsArray())&&(result_db_root.Size()!=0)){ MakeObjectFromDataAndHeader_rpd(result_db_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ return ERROR; } GPRINT(MEDIUM_LEVEL,"found [%u] temporary elements in redis\n",dr_root["m"].Size()); u64 fval=(u64)dr_root["m"][0].GetInt64(); while(ts_start_ms<fval){ ts_start_ms+=interval_ms; } for (u32 e=0;e<dr_root["m"].Size();e++){ //printf(" in db %llu ts_start_ms %llu\n",dr_root["m"][e].asUInt64(),ts_start_ms); if ((u64)dr_root["m"][e].GetInt64()>=ts_start_ms){ //printf(" found in db %llu ts_start_ms %llu\n",dr_root["m"][e].asUInt64(),ts_start_ms); for (auto & key:dr_root.GetObject() ){ const char* keys=key.name.GetString(); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } ts_start_ms+=interval_ms; } } } } else{ GPRINT(MEDIUM_LEVEL,"not found temporary elements in redis\n"); } return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::search_min_max(TIME_T & ts_start,TIME_T & ts_stop){ std::pair<eErrorTp, vector<string>> resmin,resmin_for_max,resmax; resmin=command("ZRANGEBYSCORE ts 0 %u LIMIT 0 1",ts_stop); if ((resmin.first==ERROR)||(resmin.second.size()==0)) return ERROR; resmin_for_max=command("ZRANGE ts -1 -1"); if ((resmin_for_max.first==ERROR)||(resmin_for_max.second.size()==0)) return ERROR; resmax=command("HMGET %s te",resmin_for_max.second[0].c_str()); if ((resmax.first==ERROR)||(resmax.second.size()==0)) return ERROR; TIME_T minval=stol(resmin.second[0]); TIME_T maxval=stol(resmax.second[0]); if (ts_stop<minval){ GPRINT(MEDIUM_LEVEL,"Skip search:ts_stop[%u]<minval[%u]\n",ts_stop,minval); return ERROR; } if (ts_start>maxval){ GPRINT(MEDIUM_LEVEL,"Skip search:ts_start[%u]<maxval[%u]\n",ts_start,maxval); return ERROR; } if (ts_start<minval) ts_start=minval; if (ts_stop>maxval) ts_stop=maxval; if (ts_start>ts_stop){ GPRINT(MEDIUM_LEVEL,"Skip search:ts_start[%u]>ts_stop[%u]\n",ts_start,ts_stop); return ERROR; } GPRINT(MEDIUM_LEVEL,"Found min %u max %u\n",ts_start,ts_stop); //if (((minval>=ts_start)||(ts_start<0))&&((maxval<=ts_stop)||(ts_stop<0))){ // ts_start=minval // ts_stop=maxval; // return NO_ERROR; //} return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_from_db(u64 ts_start_ms,u64 ts_stop_ms,rapidjson::Document & result_db_root){ std::pair<eErrorTp, vector<string>> res=command("GET u"); if (res.first==NO_ERROR){ std::pair<eErrorTp, vector<string>> res1=command("ZRANGEBYSCORE u%s %llu %llu",res.second[0].c_str(),ts_start_ms,ts_stop_ms); if (res1.first==NO_ERROR){ if (res1.second.size()!=0){ string s="["; for (u32 z=0;z<res1.second.size();z++){ s=s+res1.second[z]+','; } s[s.size()-1]=']'; rapidjson::ParseResult rp =result_db_root.Parse(s.c_str()); if (rp.Code()==0){ return NO_ERROR; } else return ERROR; } return NO_ERROR; } else return ERROR; } else return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::GetFormatPath(string * format_path){ TIME_T t=TIME((u32*)NULL); struct tm * ptm=GMTIME(&t); u32 year=ptm->tm_year+1900; //printf("e\n"); string dal_path0=string_format("%s/%s/%d/%s",dal_base_path[0].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); //printf("e1\n"); string dal_path1=string_format("%s/%s/%d/%s",dal_base_path[1].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); //printf("e2\n"); format_path[0]=dal_path0+'/'+FORMAT_TABLE_FILENAME; format_path[1]=dal_path1+'/'+FORMAT_TABLE_FILENAME; return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::GetDataFromGzip(string & result,string & fname,TIME_T ts,string * format_path){ struct tm * ptm=GMTIME(&ts); u32 year=ptm->tm_year+1900; string dal_path0=string_format("%s/%s/%d/%s",dal_base_path[0].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); string dal_path1=string_format("%s/%s/%d/%s",dal_base_path[1].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); string p0=dal_path0+'/'+fname; string p1=dal_path1+'/'+fname; format_path[0]=dal_path0+'/'+FORMAT_TABLE_FILENAME; format_path[1]=dal_path1+'/'+FORMAT_TABLE_FILENAME; //if (GetFileSize(p1.c_str()!=0)){ if (UngzipFile((char*)p0.c_str(),result)==NO_ERROR){ GPRINT(MEDIUM_LEVEL,"Success gunzip file %s\n",p0.c_str()); return NO_ERROR; } else{ GPRINT(NORMAL_LEVEL,"Error gunzip file %s, try gunzip reserved %s\n",p0.c_str(),p1.c_str()); if (UngzipFile((char*)p1.c_str(),result)==NO_ERROR) { GPRINT(MEDIUM_LEVEL,"Success gunzip file %s\n",p1.c_str()); remove((char*)p0.c_str()); CopyFile((char*)p1.c_str(),(char*)p0.c_str()); return NO_ERROR; } else{ GPRINT(NORMAL_LEVEL,"Error gunzip file %s\n",p1.c_str()); return ERROR; } } return ERROR; } #endif
33.27821
203
0.676878
trotill
3c9e8d9a4280c66a313fd5fa0ffdc6e0ce66bd2b
8,008
cpp
C++
3rdparty/optee/optee_os/external/RIoT/Sample/Barnacle/Shared/Tool/BarT/helper.cpp
mrragava/ragava_openenclave_6
78ffbd4ce16ec698576c432ca1fa8340663ca229
[ "MIT" ]
null
null
null
3rdparty/optee/optee_os/external/RIoT/Sample/Barnacle/Shared/Tool/BarT/helper.cpp
mrragava/ragava_openenclave_6
78ffbd4ce16ec698576c432ca1fa8340663ca229
[ "MIT" ]
null
null
null
3rdparty/optee/optee_os/external/RIoT/Sample/Barnacle/Shared/Tool/BarT/helper.cpp
mrragava/ragava_openenclave_6
78ffbd4ce16ec698576c432ca1fa8340663ca229
[ "MIT" ]
null
null
null
#include "stdafx.h" std::vector<BYTE> ReadHex(std::wstring strIn) { std::vector<BYTE> dataOut(strIn.size() / 2); for (uint32_t cursor = 0; cursor < dataOut.size(); cursor++) { dataOut[cursor] = (BYTE)std::stoul(strIn.substr(cursor * 2, 2), NULL, 16); //if (swscanf_s(strIn.substr(cursor * 2, 2).c_str(), L"%x", &scannedDigit) != 1) //{ // throw; //} // dataOut[cursor] = (BYTE)(scannedDigit & 0x000000FF); } return dataOut; } uint32_t GetTimeStamp(void) { FILETIME now = { 0 }; LARGE_INTEGER convert = { 0 }; // Get the current timestamp GetSystemTimeAsFileTime(&now); convert.LowPart = now.dwLowDateTime; convert.HighPart = now.dwHighDateTime; convert.QuadPart = (convert.QuadPart - (UINT64)(11644473600000 * 10000)) / 10000000; return convert.LowPart; } void WriteToFile(std::wstring fileName, std::vector<BYTE> data, DWORD dwCreationDisposition) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); SetFilePointer(hFile.get(), 0, 0, FILE_END); DWORD bytesWritten = 0; if (!WriteFile(hFile.get(), data.data(), data.size(), &bytesWritten, NULL)) { throw GetLastError(); } } void WriteToFile(std::wstring fileName, std::string data) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesWritten = 0; if (!WriteFile(hFile.get(), data.c_str(), data.size(), &bytesWritten, NULL)) { throw GetLastError(); } } void WriteToFile(std::wstring fileName, UINT32 data) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesWritten = 0; std::vector<byte> dataOut(16, 0); dataOut.resize(sprintf_s((char*)dataOut.data(), dataOut.size(), "%ul", data) - 1); if (!WriteFile(hFile.get(), dataOut.data(), dataOut.size(), &bytesWritten, NULL)) { throw GetLastError(); } } std::string ReadStrFromFile(std::wstring fileName) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesRead = 0; std::string data(GetFileSize(hFile.get(), NULL), '\0'); if (!ReadFile(hFile.get(), (LPVOID)data.c_str(), data.size(), &bytesRead, NULL)) { throw GetLastError(); } return data; } std::vector<BYTE> ReadFromFile(std::wstring fileName) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesRead = 0; std::vector<BYTE> data(GetFileSize(hFile.get(), NULL)); if (!ReadFile(hFile.get(), data.data(), data.size(), &bytesRead, NULL)) { throw GetLastError(); } return data; } FILETIME ConvertWinTimeStamp(UINT32 timeStamp) { LARGE_INTEGER convert = { 0 }; convert.QuadPart = ((LONGLONG)timeStamp * 10000000) + (LONGLONG)(11644473600000 * 10000); FILETIME out = { 0 }; out.dwLowDateTime = convert.LowPart; out.dwHighDateTime = convert.HighPart; return out; } PCCERT_CONTEXT CertFromFile(std::wstring fileName) { uint32_t retVal = 0; std::vector<BYTE> rawCert = ReadFromFile(fileName); DWORD result; if (CryptStringToBinaryA((LPSTR)rawCert.data(), rawCert.size(), CRYPT_STRING_BASE64HEADER, NULL, &result, NULL, NULL)) { std::vector<BYTE> derCert(result, 0); if (!CryptStringToBinaryA((LPSTR)rawCert.data(), rawCert.size(), CRYPT_STRING_BASE64HEADER, derCert.data(), &result, NULL, NULL)) { throw GetLastError(); } rawCert = derCert; } PCCERT_CONTEXT hCert = NULL; if ((hCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, rawCert.data(), rawCert.size())) == NULL) { throw retVal; } return hCert; } std::vector<BYTE> CertThumbPrint(PCCERT_CONTEXT hCert) { uint32_t retVal = 0; BCRYPT_ALG_HANDLE hSha1 = NULL; if ((retVal = BCryptOpenAlgorithmProvider(&hSha1, BCRYPT_SHA1_ALGORITHM, NULL, 0)) != 0) { throw retVal; } std::vector<BYTE> digest(20, 0); if ((retVal = BCryptHash(hSha1, NULL, 0, hCert->pbCertEncoded, hCert->cbCertEncoded, digest.data(), digest.size())) != 0) { throw retVal; } BCryptCloseAlgorithmProvider(hSha1, 0); return digest; } std::wstring ToHexWString(std::vector<BYTE> &byteVector) { std::wstring stringOut((byteVector.size() + 2) * 2, '\0'); DWORD result = stringOut.size(); if (!CryptBinaryToStringW(byteVector.data(), byteVector.size(), CRYPT_STRING_HEXRAW, (LPWSTR)stringOut.c_str(), &result)) { throw GetLastError(); } stringOut.resize(stringOut.size() - 4); return stringOut; } std::string ToHexString(std::vector<BYTE> &byteVector) { std::string stringOut((byteVector.size() + 2) * 2, '\0'); DWORD result = stringOut.size(); if (!CryptBinaryToStringA(byteVector.data(), byteVector.size(), CRYPT_STRING_HEXRAW, (LPSTR)stringOut.c_str(), &result)) { throw GetLastError(); } stringOut.resize(stringOut.size() - 4); return stringOut; } std::wstring ToDevIDWString(std::vector<BYTE> &byteVector, bool uri) { DWORD retVal; DWORD result; std::vector<BYTE> devID(byteVector.size() / 4, 0); for (UINT32 n = 0; n < byteVector.size(); n++) { devID[n] = byteVector[n] ^ byteVector[byteVector.size() / 4 + n] ^ byteVector[byteVector.size() / 2 + n] ^ byteVector[byteVector.size() / 4 * 3 + n]; } if (!CryptBinaryToStringW(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, NULL, &result)) { retVal = GetLastError(); throw retVal; } std::wstring devIDStr(result, '\0'); if (!CryptBinaryToStringW(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, (LPWSTR)devIDStr.c_str(), &result)) { retVal = GetLastError(); throw retVal; } devIDStr.resize(devIDStr.size() - 2); devIDStr[devIDStr.size() - 1] = L'\0'; return devIDStr; } std::string ToDevIDString(std::vector<BYTE> &byteVector, bool uri) { DWORD retVal; DWORD result; std::vector<BYTE> devID(byteVector.size() / 4, 0); for (UINT32 n = 0; n < byteVector.size(); n++) { devID[n] = byteVector[n] ^ byteVector[byteVector.size() / 4 + n] ^ byteVector[byteVector.size() / 2 + n] ^ byteVector[byteVector.size() / 4 * 3 + n]; } if (!CryptBinaryToStringA(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, NULL, &result)) { retVal = GetLastError(); throw retVal; } std::string devIDStr(result, '\0'); if (!CryptBinaryToStringA(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, (LPSTR)devIDStr.c_str(), &result)) { retVal = GetLastError(); throw retVal; } devIDStr.resize(devIDStr.size() - 2); devIDStr[devIDStr.size() - 1] = '\0'; return devIDStr; }
37.074074
211
0.657717
mrragava
3ca0e624176ab8a4a10b23fa0108f3877cfd1cf1
1,966
cpp
C++
tests/ttl_cache/ttl_cache.cpp
alessandrolenzi/cpp-cachetools
d978d43e61f36cb1a9b5ed6e76b16203e9982cbe
[ "MIT" ]
null
null
null
tests/ttl_cache/ttl_cache.cpp
alessandrolenzi/cpp-cachetools
d978d43e61f36cb1a9b5ed6e76b16203e9982cbe
[ "MIT" ]
null
null
null
tests/ttl_cache/ttl_cache.cpp
alessandrolenzi/cpp-cachetools
d978d43e61f36cb1a9b5ed6e76b16203e9982cbe
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "cpp_cachetools/policies.hpp" #include "cpp_cachetools/indexes.hpp" #include "cpp_cachetools/cache.hpp" #include "../fake_clock/fake_clock.hh" struct TTLTestCache: Cache<policies::Builder<policies::TTL<testing::fake_clock>::Class>::with_index<indexes::HashedIndex>::Class> {}; using namespace std::chrono_literals; TEST(TTLCache, EvictsWhenTimeIsOver) { auto cache_duration = testing::fake_clock::duration(60); auto advance = testing::fake_clock::duration(31); auto &&cache = TTLTestCache::build<int, int>(10, cache_duration); cache->insert(1, 1); testing::fake_clock::advance(advance); auto not_expired = cache->get(1); EXPECT_EQ(not_expired.value(), 1); testing::fake_clock::advance(advance); auto retrieved = cache->get(1); EXPECT_EQ(retrieved, std::optional<int>{}); } TEST(TTLCache, EvictsOlderFirstWhenFull) { auto cache_duration = testing::fake_clock::duration(60); auto advance = testing::fake_clock::duration(31); auto &&cache = TTLTestCache::build<int, int>(2, cache_duration); cache->insert(1, 1); cache->insert(2, 2); cache->insert(3, 3); auto evicted_because_old = cache->get(1); EXPECT_EQ(evicted_because_old, std::optional<int>{}); testing::fake_clock::advance(advance); EXPECT_EQ(cache->get(2), 2); EXPECT_EQ(cache->get(3), 3); } TEST(TTLCache, EvictsExpiredFirst) { auto cache_duration = testing::fake_clock::duration(60); auto advance = testing::fake_clock::duration(31); auto &&cache = TTLTestCache::build<int, int>(2, cache_duration); cache->insert(1, 1); testing::fake_clock::advance(advance); cache->insert(2, 2); testing::fake_clock::advance(advance); cache->insert(3, 3); auto evicted_because_old = cache->get(1); EXPECT_EQ(evicted_because_old, std::optional<int>{}); EXPECT_EQ(cache->get(2), 2); testing::fake_clock::advance(advance); EXPECT_EQ(cache->get(3), 3); }
37.09434
133
0.696338
alessandrolenzi
3ca184777beb7651871edcf251a7f82895ca4ce2
3,520
cpp
C++
frameworks/core/src/common_event_listener.cpp
chaoyangcui/notification_ces_standard
7689176a838b62d498ce9c645f34b0be3376ce06
[ "Apache-2.0" ]
null
null
null
frameworks/core/src/common_event_listener.cpp
chaoyangcui/notification_ces_standard
7689176a838b62d498ce9c645f34b0be3376ce06
[ "Apache-2.0" ]
null
null
null
frameworks/core/src/common_event_listener.cpp
chaoyangcui/notification_ces_standard
7689176a838b62d498ce9c645f34b0be3376ce06
[ "Apache-2.0" ]
1
2021-09-13T12:06:55.000Z
2021-09-13T12:06:55.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "common_event_listener.h" #include "event_log_wrapper.h" namespace OHOS { namespace EventFwk { CommonEventListener::CommonEventListener(const std::shared_ptr<CommonEventSubscriber> &commonEventSubscriber) : commonEventSubscriber_(commonEventSubscriber) { Init(); } CommonEventListener::~CommonEventListener() {} void CommonEventListener::NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky) { EVENT_LOGI("enter"); if (!IsReady()) { EVENT_LOGE("not ready"); return; } std::function<void()> onReceiveEventFunc = std::bind(&CommonEventListener::OnReceiveEvent, this, commonEventData, ordered, sticky); handler_->PostTask(onReceiveEventFunc); } ErrCode CommonEventListener::Init() { EVENT_LOGD("ready to init"); if (runner_ == nullptr) { if (!commonEventSubscriber_) { EVENT_LOGE("Failed to init with CommonEventSubscriber nullptr"); return ERR_INVALID_OPERATION; } if (CommonEventSubscribeInfo::HANDLER == commonEventSubscriber_->GetSubscribeInfo().GetThreadMode()) { runner_ = EventRunner::GetMainEventRunner(); } else { runner_ = EventRunner::Create(true); } if (!runner_) { EVENT_LOGE("Failed to init due to create runner error"); return ERR_INVALID_OPERATION; } } if (handler_ == nullptr) { handler_ = std::make_shared<EventHandler>(runner_); if (!handler_) { EVENT_LOGE("Failed to init due to create handler error"); return ERR_INVALID_OPERATION; } } return ERR_OK; } bool CommonEventListener::IsReady() { if (runner_ == nullptr) { EVENT_LOGE("runner is not ready"); return false; } if (handler_ == nullptr) { EVENT_LOGE("handler is not ready"); return false; } return true; } void CommonEventListener::OnReceiveEvent( const CommonEventData &commonEventData, const bool &ordered, const bool &sticky) { EVENT_LOGI("enter"); int code = commonEventData.GetCode(); std::string data = commonEventData.GetData(); std::shared_ptr<AsyncCommonEventResult> result = std::make_shared<AsyncCommonEventResult>(code, data, ordered, sticky, this); if (result == nullptr) { EVENT_LOGE("Failed to create AsyncCommonEventResult"); return; } if (!commonEventSubscriber_) { EVENT_LOGE("CommonEventSubscriber ptr is nullptr"); return; } commonEventSubscriber_->SetAsyncCommonEventResult(result); commonEventSubscriber_->OnReceiveEvent(commonEventData); if ((commonEventSubscriber_->GetAsyncCommonEventResult() != nullptr) && ordered) { commonEventSubscriber_->GetAsyncCommonEventResult()->FinishCommonEvent(); } } } // namespace EventFwk } // namespace OHOS
29.830508
118
0.678977
chaoyangcui
3ca325f5fe2483cd02853e038b800d780fda921b
508
cpp
C++
src/SvgLib/OpenCommand.cpp
steneva/svg-lib
47a754f71be923bd75bfef35ab529c61702b93ae
[ "MIT" ]
2
2020-08-11T20:46:31.000Z
2020-08-14T09:51:02.000Z
src/SvgLib/OpenCommand.cpp
steneva/svg-lib
47a754f71be923bd75bfef35ab529c61702b93ae
[ "MIT" ]
null
null
null
src/SvgLib/OpenCommand.cpp
steneva/svg-lib
47a754f71be923bd75bfef35ab529c61702b93ae
[ "MIT" ]
null
null
null
#include "OpenCommand.h" bool OpenCommand::can_execute(const CommandContext& context) const { return !context.is_file_open(); } void OpenCommand::execute(const CommandContext& context) const { if (context.args_count() != 2) { throw CommandParamsException(); } const std::string path = context.arg(PATH_INDEX); context.open_svg(path); } void OpenCommand::onSuccess(const CommandContext& context) const { context.out() << "Successfully opened file " << context.file_path() << "." << std::endl; }
22.086957
89
0.724409
steneva
3ca34061241a85dd87de2277bb950e72848cbef7
4,249
cpp
C++
llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
AnthonyLatsis/llvm-project
2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74
[ "Apache-2.0" ]
null
null
null
llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
AnthonyLatsis/llvm-project
2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74
[ "Apache-2.0" ]
9
2020-04-24T21:51:04.000Z
2020-11-06T01:04:09.000Z
llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
AnthonyLatsis/llvm-project
2acd6cdb9a4bfb2c34b701527e04dd4ffe791d74
[ "Apache-2.0" ]
null
null
null
//===-- MCTargetOptionsCommandFlags.cpp --------------------------*- C++ //-*-===// // // 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 // //===----------------------------------------------------------------------===// // // This file contains machine code-specific flags that are shared between // different command line tools. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCTargetOptionsCommandFlags.h" using namespace llvm; #define MCOPT(TY, NAME) \ static cl::opt<TY> *NAME##View; \ TY llvm::mc::get##NAME() { \ assert(NAME##View && "RegisterMCTargetOptionsFlags not created."); \ return *NAME##View; \ } #define MCOPT_EXP(TY, NAME) \ MCOPT(TY, NAME) \ Optional<TY> llvm::mc::getExplicit##NAME() { \ if (NAME##View->getNumOccurrences()) { \ TY res = *NAME##View; \ return res; \ } \ return None; \ } MCOPT_EXP(bool, RelaxAll) MCOPT(bool, IncrementalLinkerCompatible) MCOPT(int, DwarfVersion) MCOPT(bool, ShowMCInst) MCOPT(bool, FatalWarnings) MCOPT(bool, NoWarn) MCOPT(bool, NoDeprecatedWarn) MCOPT(std::string, ABIName) llvm::mc::RegisterMCTargetOptionsFlags::RegisterMCTargetOptionsFlags() { #define MCBINDOPT(NAME) \ do { \ NAME##View = std::addressof(NAME); \ } while (0) static cl::opt<bool> RelaxAll( "mc-relax-all", cl::desc("When used with filetype=obj, relax all fixups " "in the emitted object file")); MCBINDOPT(RelaxAll); static cl::opt<bool> IncrementalLinkerCompatible( "incremental-linker-compatible", cl::desc( "When used with filetype=obj, " "emit an object file which can be used with an incremental linker")); MCBINDOPT(IncrementalLinkerCompatible); static cl::opt<int> DwarfVersion("dwarf-version", cl::desc("Dwarf version"), cl::init(0)); MCBINDOPT(DwarfVersion); static cl::opt<bool> ShowMCInst( "asm-show-inst", cl::desc("Emit internal instruction representation to assembly file")); MCBINDOPT(ShowMCInst); static cl::opt<bool> FatalWarnings("fatal-warnings", cl::desc("Treat warnings as errors")); MCBINDOPT(FatalWarnings); static cl::opt<bool> NoWarn("no-warn", cl::desc("Suppress all warnings")); static cl::alias NoWarnW("W", cl::desc("Alias for --no-warn"), cl::aliasopt(NoWarn)); MCBINDOPT(NoWarn); static cl::opt<bool> NoDeprecatedWarn( "no-deprecated-warn", cl::desc("Suppress all deprecated warnings")); MCBINDOPT(NoDeprecatedWarn); static cl::opt<std::string> ABIName( "target-abi", cl::Hidden, cl::desc("The name of the ABI to be targeted from the backend."), cl::init("")); MCBINDOPT(ABIName); #undef MCBINDOPT } MCTargetOptions llvm::mc::InitMCTargetOptionsFromFlags() { MCTargetOptions Options; Options.MCRelaxAll = getRelaxAll(); Options.MCIncrementalLinkerCompatible = getIncrementalLinkerCompatible(); Options.DwarfVersion = getDwarfVersion(); Options.ShowMCInst = getShowMCInst(); Options.ABIName = getABIName(); Options.MCFatalWarnings = getFatalWarnings(); Options.MCNoWarn = getNoWarn(); Options.MCNoDeprecatedWarn = getNoDeprecatedWarn(); return Options; }
40.084906
80
0.513062
AnthonyLatsis
3ca45d491eaec4429e7b0512ea9978f7d7750935
8,685
cpp
C++
3rd_party_libs/chai3d_a4/src/system/CString.cpp
atp42/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
3
2017-02-02T13:27:45.000Z
2018-06-17T11:52:13.000Z
3rd_party_libs/chai3d_a4/src/system/CString.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
3rd_party_libs/chai3d_a4/src/system/CString.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
//=========================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2012, CHAI3D. (www.chai3d.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CHAI3D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \author <http://www.chai3d.org> \author Sebastien Grange \version $MAJOR.$MINOR.$RELEASE $Rev: 387 $ */ //=========================================================================== //--------------------------------------------------------------------------- #include "system/CString.h" #include "math/CMaths.h" //--------------------------------------------------------------------------- #include <iostream> #include <iomanip> using namespace std; //--------------------------------------------------------------------------- //=========================================================================== /*! Compute the length of a string up to 255 characters. If the end of string cannot be found, then -1 is returned as a result. \param a_string Input string. Pointer to a char. \return Return the length of the string. */ //=========================================================================== int cStringLength(const char* a_input) { return (int)(strlen(a_input)); } //=========================================================================== /*! Convert a string into lower case. \param a_string Input string \return Returns the output string. */ //=========================================================================== string cStringToLower(const string& a_input) { string result = a_input; transform(result.begin(), result.end(), result.begin(), ::tolower); return (result); } //=========================================================================== /*! Finds the extension in a filename. \param a_input Input filename. \param a_includeDot If \b true, include the dot at the beginning of the extension. (example: ".jpg") \return Returns a string containing the extension. */ //=========================================================================== string cFindFileExtension(const string& a_input, const bool a_includeDot) { int pos = (int)(a_input.find_last_of(".")); if (pos < 0) return ""; if (a_includeDot) { return a_input.substr(pos, a_input.length()); } else { return a_input.substr(pos+1, a_input.length()); } } //=========================================================================== /*! Discards the path component of a filename and returns the filename itself, optionally including the extension. \param a_input Input string containing path and filename \param a_includeExtension Should the output include the extension? \return Returns the output string. */ //=========================================================================== string cFindFilename(const string& a_input, const bool a_includeFileExtension) { string result = a_input; int pos = (int)(result.find_last_of("\\")); if (pos > -1) result = result.substr(pos+1, result.length()-pos-1); pos = (int)(result.find_last_of("/")); if (pos > -1) result = result.substr(pos+1, result.length()-pos-1); if (!a_includeFileExtension) { pos = (int)(result.find_last_of(".")); result = result.substr(0, pos); } return (result); } //=========================================================================== /*! Returns the string a_filename by replacing its extension with a new string provided by parameter a_extension. \param a_filename The input filename \param a_extension The extension to replace a_input's extension with \return Returns the output string. */ //=========================================================================== string cReplaceFileExtension(const string& a_filename, const string& a_extension) { string result = a_filename; int pos = (int)(result.find_last_of(".")); if (pos < 0) return a_filename; result.replace(pos+1, result.length(), a_extension); return (result); } //=========================================================================== /*! Finds only the _path_ portion of source, and copies it with _no_ trailing '\\'. If there's no /'s or \\'s, writes an empty string. \param a_dest String which will contain the directory name. \param a_source Input string containing path and filename. \return Return \b true for success, \b false if there's no separator. */ //=========================================================================== string cFindDirectory(const string& a_input) { return (a_input.substr(0, a_input.length() - cFindFilename(a_input, true).length())); } //=========================================================================== /*! Convert a \e boolean into a \e string. \param a_value Input value of type \e boolean. \return Return output string. */ //=========================================================================== string cStr(const bool a_value) { string result; if (a_value) result = "true"; else result = "false"; return (result); } //=========================================================================== /*! Convert an \e integer into a \e string. \param a_value Input value of type \e integer. \return Return output string. */ //=========================================================================== string cStr(const int a_value) { ostringstream result; result << a_value; return (result.str()); } //=========================================================================== /*! Convert a \e float into a \e string. \param a_value Input value of type \e float. \param a_precision Number of digits displayed after the decimal point. \return Return output string. */ //=========================================================================== string cStr(const float a_value, const unsigned int a_precision) { ostringstream result; result << fixed << setprecision(a_precision) << a_value; return (result.str()); } //=========================================================================== /*! Convert a \e double into a \e string. \param a_value Input value of type \e double. \param a_precision Number of digits displayed after the decimal point. \return Return output string. */ //=========================================================================== string cStr(const double& a_value, const unsigned int a_precision) { ostringstream result; result << fixed << setprecision(a_precision) << a_value; return (result.str()); }
34.192913
90
0.499252
atp42
3ca6a6dc39c20d86b71366e5026047f8e8783a7b
4,831
hpp
C++
source/cppx-core-language/syntax/collection-util/Sequence_.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
3
2020-05-24T16:29:42.000Z
2021-09-10T13:33:15.000Z
source/cppx-core-language/syntax/collection-util/Sequence_.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
source/cppx-core-language/syntax/collection-util/Sequence_.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
#pragma once // Source encoding: UTF-8 with BOM (π is a firstcase Greek "pi"). #include <cppx-core-language/assert-cpp/is-c++17-or-later.hpp> #include <cppx-core-language/mix-in/Adapt_as_forward_iterator_.hpp> // cppx::mix_in::Adapt_as_forward_iterator_ #include <cppx-core-language/types/Truth.hpp> // cppx::Truth #include <cppx-core-language/tmp/Enable_if_.hpp> // cppx::Enable_if_ #include <cppx-core-language/tmp/type-checkers.hpp> // cppx::is_integral_ #include <cppx-core-language/tmp/type-modifiers.hpp> // cppx::As_unsigned_ #include <cppx-core-language/calc/number-type-properties.hpp> // cppx::(min_, max_) #include <c/assert.hpp> namespace cppx::_{ template< class Integer, class = Enable_if_< is_integral_<Integer> > > class Sequence_ { using Unsigned = As_unsigned_<Integer>; Unsigned m_first; Unsigned m_last; class Iterator: public mix_in::Adapt_as_forward_iterator_<Iterator, Integer> { Unsigned m_current; public: void advance() { ++m_current; } auto operator*() const noexcept -> Integer { return static_cast<Integer>( m_current ); } friend auto operator==( const Iterator& a, const Iterator& b ) noexcept -> Truth { return a.m_current == b.m_current; } explicit Iterator( const Integer value ) noexcept : m_current( static_cast<Unsigned>( value ) ) {} }; public: constexpr auto first() const noexcept -> Integer { return static_cast<Integer>( m_first ); } constexpr auto last() const noexcept -> Integer { return static_cast<Integer>( m_last ); } constexpr auto n_values() const noexcept -> Integer { return static_cast<Integer>( 1 + m_last - m_first ); } constexpr auto is_empty() const noexcept -> Truth { return n_values() == 0; } template< class Value_integer > constexpr auto contains( const Value_integer x ) const noexcept -> Truth { if constexpr( max_<Value_integer> > max_<Integer> ) { if( x > max_<Integer> ) { return false; } } if constexpr( min_<Value_integer> < min_<Integer> ) { // Here Value_integer is necessarily a signed type. if constexpr( is_signed_<Integer> ) { if( x < min_<Integer> ) { return false; } } else { if( x < 0 ) { // Comparing to Integer(0) could wrap. return false; } } } return m_first <= Unsigned( x ) and Unsigned( x ) <= m_last; } auto begin() const noexcept -> Iterator { return Iterator( m_first ); } auto end() const noexcept -> Iterator { return Iterator( m_last + 1 ); } constexpr Sequence_( const Integer first, const Integer last ) noexcept : m_first( first ) , m_last( last ) { assert( first <= last or static_cast<Unsigned>( first ) == static_cast<Unsigned>( last ) + 1 ); } }; using Sequence = Sequence_<int>; // Free function notation / convention adapters: template< class Integer > inline constexpr auto n_items( const Sequence_<Integer>& seq ) noexcept -> Size { return seq.n_values(); } template< class Integer > inline constexpr auto is_empty( const Sequence_<Integer>& seq ) noexcept -> Size { return seq.is_empty(); } template< class Integer, class Value_integer > inline constexpr auto is_in( const Sequence_<Integer>& seq, const Value_integer v ) noexcept -> Truth { return seq.contains( v ); } // Factory functions: template< class Integer > inline constexpr auto zero_to( const Integer n ) noexcept -> Sequence_<Integer> { return Sequence_<Integer>( 0, n - 1 ); } template< class Integer > inline constexpr auto one_through( const Integer n ) noexcept -> Sequence_<Integer> { return Sequence_<Integer>( 1, n ); } } // namespace cppx::_ // Exporting namespaces: namespace cppx { namespace syntax { CPPX_USE_FROM_NAMESPACE( _, Sequence_, Sequence, zero_to, one_through, is_in ); } // namespace syntax using namespace cppx::syntax; } // namespace cppx
32.863946
111
0.551025
alf-p-steinbach
3ca7fb745ac9271b0984cde75675f25e4adb9fe9
598
hpp
C++
Strategy Pattern/Strategy Pattern/Strategy Pattern/EreDownloader.hpp
glc12125/design_patterns
bede229910e939ac3bb4d78fa030bf3f0156f86f
[ "MIT" ]
null
null
null
Strategy Pattern/Strategy Pattern/Strategy Pattern/EreDownloader.hpp
glc12125/design_patterns
bede229910e939ac3bb4d78fa030bf3f0156f86f
[ "MIT" ]
null
null
null
Strategy Pattern/Strategy Pattern/Strategy Pattern/EreDownloader.hpp
glc12125/design_patterns
bede229910e939ac3bb4d78fa030bf3f0156f86f
[ "MIT" ]
null
null
null
// // EreDownloader.hpp // Strategy Pattern // // Created by Liangchuan Gu on 12/12/2015. // Copyright © 2015 Lee Inc. All rights reserved. // #ifndef EreDownloader_hpp #define EreDownloader_hpp #include "FeedDownloader.hpp" namespace Li{ class EreDownloader : public FeedDownloader { public: EreDownloader(const std::string& externalRetrievalId); EreDownloader(const EreDownloader& other); EreDownloader& operator=(const EreDownloader& other); virtual int retrieveFileList(); }; } // End of namespace Li #endif /* EreDownloader_hpp */
21.357143
62
0.690635
glc12125
3ca827a992d80b75ed7415a2fb686428eb5dee0e
10,424
cc
C++
ash/projector/projector_controller_impl.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/projector/projector_controller_impl.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-03-13T10:32:53.000Z
2019-03-13T11:05:30.000Z
ash/projector/projector_controller_impl.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/projector/projector_controller_impl.h" #include "ash/capture_mode/capture_mode_controller.h" #include "ash/capture_mode/capture_mode_metrics.h" #include "ash/projector/projector_metadata_controller.h" #include "ash/projector/projector_ui_controller.h" #include "ash/public/cpp/projector/projector_client.h" #include "ash/public/cpp/projector/projector_session.h" #include "ash/shell.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "media/mojo/mojom/speech_recognition_service.mojom.h" namespace ash { namespace { // String format of the screencast name. constexpr char kScreencastPathFmtStr[] = "Screencast %d-%02d-%02d %02d.%02d.%02d"; // Create directory. Returns true if saving succeeded, or false otherwise. bool CreateDirectory(const base::FilePath& path) { DCHECK(!base::CurrentUIThread::IsSet()); DCHECK(!path.empty()); // The path is constructed from datetime which should be unique for most // cases. In case it is already exist, returns false. if (base::PathExists(path)) { LOG(ERROR) << "Path has already existed: " << path; return false; } if (!base::CreateDirectory(path)) { LOG(ERROR) << "Failed to create path: " << path; return false; } return true; } std::string GetScreencastName() { base::Time::Exploded exploded_time; base::Time::Now().LocalExplode(&exploded_time); return base::StringPrintf(kScreencastPathFmtStr, exploded_time.year, exploded_time.month, exploded_time.day_of_month, exploded_time.hour, exploded_time.minute, exploded_time.second); } } // namespace ProjectorControllerImpl::ProjectorControllerImpl() : projector_session_(std::make_unique<ash::ProjectorSessionImpl>()), ui_controller_(std::make_unique<ash::ProjectorUiController>(this)), metadata_controller_( std::make_unique<ash::ProjectorMetadataController>()) {} ProjectorControllerImpl::~ProjectorControllerImpl() = default; // static ProjectorControllerImpl* ProjectorControllerImpl::Get() { return static_cast<ProjectorControllerImpl*>(ProjectorController::Get()); } void ProjectorControllerImpl::StartProjectorSession( const std::string& storage_dir) { DCHECK(CanStartNewSession()); auto* controller = CaptureModeController::Get(); if (!controller->is_recording_in_progress()) { // A capture mode session can be blocked by many factors, such as policy, // DLP, ... etc. We don't start a Projector session until we're sure a // capture session started. controller->Start(CaptureModeEntryType::kProjector); if (controller->IsActive()) projector_session_->Start(storage_dir); } } void ProjectorControllerImpl::CreateScreencastContainerFolder( CreateScreencastContainerFolderCallback callback) { base::FilePath mounted_path; if (!client_->GetDriveFsMountPointPath(&mounted_path)) { LOG(ERROR) << "Failed to get DriveFs mounted point path."; // TODO(b/200846160): Notify user when there is an error. std::move(callback).Run(base::FilePath()); return; } auto path = mounted_path.Append("root") .Append(projector_session_->storage_dir()) .Append(GetScreencastName()); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock()}, base::BindOnce(&CreateDirectory, path), base::BindOnce(&ProjectorControllerImpl::OnContainerFolderCreated, weak_factory_.GetWeakPtr(), path, std::move(callback))); } void ProjectorControllerImpl::SetClient(ProjectorClient* client) { client_ = client; } void ProjectorControllerImpl::OnSpeechRecognitionAvailable(bool available) { if (ProjectorController::AreExtendedProjectorFeaturesDisabled()) return; if (available == is_speech_recognition_available_) return; is_speech_recognition_available_ = available; } void ProjectorControllerImpl::OnTranscription( const media::SpeechRecognitionResult& result) { // Render transcription. if (is_caption_on_) { ui_controller_->OnTranscription(result.transcription, result.is_final); } if (result.is_final && result.timing_information.has_value()) { // Records final transcript. metadata_controller_->RecordTranscription(result); } } void ProjectorControllerImpl::OnTranscriptionError() { CaptureModeController::Get()->EndVideoRecording( EndRecordingReason::kProjectorTranscriptionError); } bool ProjectorControllerImpl::IsEligible() const { return is_speech_recognition_available_ || ProjectorController::AreExtendedProjectorFeaturesDisabled(); } bool ProjectorControllerImpl::CanStartNewSession() const { // TODO(crbug.com/1165435) Add other pre-conditions to starting a new // projector session. return IsEligible() && !projector_session_->is_active() && client_->IsDriveFsMounted(); } void ProjectorControllerImpl::OnToolSet(const chromeos::AnnotatorTool& tool) { // TODO(b/198184362): Reflect the annotator tool changes on the Projector // toolbar. } void ProjectorControllerImpl::OnUndoRedoAvailabilityChanged( bool undo_available, bool redo_available) { // TODO(b/198184362): Reflect undo and redo buttons availability on the // Projector toolbar. } void ProjectorControllerImpl::SetCaptionBubbleState(bool is_on) { ui_controller_->SetCaptionBubbleState(is_on); } void ProjectorControllerImpl::OnCaptionBubbleModelStateChanged(bool is_on) { is_caption_on_ = is_on; } void ProjectorControllerImpl::MarkKeyIdea() { metadata_controller_->RecordKeyIdea(); ui_controller_->OnKeyIdeaMarked(); } void ProjectorControllerImpl::OnRecordingStarted() { ui_controller_->ShowToolbar(); StartSpeechRecognition(); ui_controller_->OnRecordingStateChanged(true /* started */); metadata_controller_->OnRecordingStarted(); } void ProjectorControllerImpl::OnRecordingEnded() { DCHECK(projector_session_->is_active()); StopSpeechRecognition(); ui_controller_->OnRecordingStateChanged(false /* started */); // TODO(b/197152209): move closing selfie cam to ProjectorUiController. if (client_->IsSelfieCamVisible()) client_->CloseSelfieCam(); // Close Projector toolbar. ui_controller_->CloseToolbar(); if (projector_session_->screencast_container_path()) { // Finish saving the screencast if the container is available. The container // might be unavailable if fail in creating the directory. SaveScreencast(); } projector_session_->Stop(); // At this point, the screencast might not synced to Drive yet. Open // Projector App which showing the Gallery view by default. client_->OpenProjectorApp(); } void ProjectorControllerImpl::OnRecordingStartAborted() { DCHECK(projector_session_->is_active()); // Delete the DriveFS path that might have been created for this aborted // session if any. if (projector_session_->screencast_container_path()) { base::ThreadPool::PostTask( FROM_HERE, {base::MayBlock()}, base::BindOnce(base::GetDeletePathRecursivelyCallback(), *projector_session_->screencast_container_path())); } projector_session_->Stop(); } void ProjectorControllerImpl::OnLaserPointerPressed() { ui_controller_->OnLaserPointerPressed(); } void ProjectorControllerImpl::OnMarkerPressed() { ui_controller_->OnMarkerPressed(); } void ProjectorControllerImpl::OnClearAllMarkersPressed() { ui_controller_->OnClearAllMarkersPressed(); } void ProjectorControllerImpl::OnUndoPressed() { ui_controller_->OnUndoPressed(); } void ProjectorControllerImpl::OnSelfieCamPressed(bool enabled) { ui_controller_->OnSelfieCamPressed(enabled); DCHECK_NE(client_, nullptr); if (enabled == client_->IsSelfieCamVisible()) return; if (enabled) { client_->ShowSelfieCam(); return; } client_->CloseSelfieCam(); } void ProjectorControllerImpl::OnMagnifierButtonPressed(bool enabled) { ui_controller_->OnMagnifierButtonPressed(enabled); } void ProjectorControllerImpl::OnChangeMarkerColorPressed(SkColor new_color) { ui_controller_->OnChangeMarkerColorPressed(new_color); } void ProjectorControllerImpl::SetProjectorUiControllerForTest( std::unique_ptr<ProjectorUiController> ui_controller) { ui_controller_ = std::move(ui_controller); } void ProjectorControllerImpl::SetProjectorMetadataControllerForTest( std::unique_ptr<ProjectorMetadataController> metadata_controller) { metadata_controller_ = std::move(metadata_controller); } void ProjectorControllerImpl::StartSpeechRecognition() { if (ProjectorController::AreExtendedProjectorFeaturesDisabled()) return; DCHECK(is_speech_recognition_available_); DCHECK(!is_speech_recognition_on_); DCHECK_NE(client_, nullptr); client_->StartSpeechRecognition(); is_speech_recognition_on_ = true; } void ProjectorControllerImpl::StopSpeechRecognition() { if (ProjectorController::AreExtendedProjectorFeaturesDisabled()) return; DCHECK(is_speech_recognition_available_); DCHECK(is_speech_recognition_on_); DCHECK_NE(client_, nullptr); client_->StopSpeechRecognition(); is_speech_recognition_on_ = false; } void ProjectorControllerImpl::OnContainerFolderCreated( const base::FilePath& path, CreateScreencastContainerFolderCallback callback, bool success) { if (!success) { LOG(ERROR) << "Failed to create screencast container path: " << path.DirName(); std::move(callback).Run(base::FilePath()); return; } projector_session_->set_screencast_container_path(path); std::move(callback).Run(GetScreencastFilePathNoExtension()); } void ProjectorControllerImpl::SaveScreencast() { metadata_controller_->SaveMetadata(GetScreencastFilePathNoExtension()); } base::FilePath ProjectorControllerImpl::GetScreencastFilePathNoExtension() const { auto screencast_container_path = projector_session_->screencast_container_path(); DCHECK(screencast_container_path.has_value()); return screencast_container_path->Append(GetScreencastName()); } } // namespace ash
32.073846
80
0.752782
Yannic
3caa10eda52c9973047845c4ed92e2970aa3ef3b
1,724
cpp
C++
framework/Source/GPUImageLookupFilter.cpp
autolotto/GPUImage
35f499ce2f59bba92a1c82e2baa2ee4e54e88736
[ "BSD-3-Clause" ]
17
2015-02-28T13:16:21.000Z
2020-01-07T06:10:48.000Z
framework/Source/GPUImageLookupFilter.cpp
JonathanKranz/GPUImage
fcd9576822e4015dc4b1ac514c372d71cfb57b8a
[ "BSD-3-Clause" ]
2
2016-05-29T01:53:18.000Z
2016-09-02T01:15:39.000Z
framework/Source/GPUImageLookupFilter.cpp
JonathanKranz/GPUImage
fcd9576822e4015dc4b1ac514c372d71cfb57b8a
[ "BSD-3-Clause" ]
12
2015-06-19T07:26:39.000Z
2020-01-07T09:31:15.000Z
/** * Author: Alessio Placitelli * Contact: a.placitelli _@_ a2p.it * */ #include "GPUImageLookupFilter.h" const std::string GPUImageLookupFilter::kGPUImageLookupFragmentShaderString("\ varying highp vec2 textureCoordinate;\ varying highp vec2 textureCoordinate2;\ \ uniform sampler2D inputImageTexture;\ uniform sampler2D inputImageTexture2;\ \ void main()\ {\ lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\ \ mediump float blueColor = textureColor.b * 63.0;\ \ mediump vec2 quad1;\ quad1.y = floor(floor(blueColor) / 8.0);\ quad1.x = floor(blueColor) - (quad1.y * 8.0);\ \ mediump vec2 quad2;\ quad2.y = floor(ceil(blueColor) / 8.0);\ quad2.x = ceil(blueColor) - (quad2.y * 8.0);\ \ highp vec2 texPos1;\ texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\ texPos1.y = (quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\ \ highp vec2 texPos2;\ texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\ texPos2.y = (quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\ \ lowp vec4 newColor1 = texture2D(inputImageTexture2, texPos1);\ lowp vec4 newColor2 = texture2D(inputImageTexture2, texPos2);\ \ lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));\ gl_FragColor = vec4(newColor.rgb, textureColor.w);\ }" ); GPUImageLookupFilter::GPUImageLookupFilter() : GPUImageTwoInputFilter() { GPUImageTwoInputFilter::initWithFragmentShaderFromString(kGPUImageLookupFragmentShaderString); } GPUImageLookupFilter::~GPUImageLookupFilter() { }
31.345455
98
0.656032
autolotto
3cabf5409460c978ad5c85217f5ccd6991ba7004
6,148
hxx
C++
Eudora71/SpelChek/src/nuspell/aff_data.hxx
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
1
2019-06-15T17:46:11.000Z
2019-06-15T17:46:11.000Z
Eudora71/SpelChek/src/nuspell/aff_data.hxx
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
null
null
null
Eudora71/SpelChek/src/nuspell/aff_data.hxx
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
null
null
null
/* Copyright 2016-2018 Dimitrij Mijoski * * This file is part of Nuspell. * * Nuspell is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Nuspell is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Nuspell. If not, see <http://www.gnu.org/licenses/>. */ /** * @file aff_data.hxx * Affixing data structures. */ #ifndef NUSPELL_AFF_DATA_HXX #define NUSPELL_AFF_DATA_HXX #include <iosfwd> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "locale_utils.hxx" #include "structures.hxx" namespace nuspell { auto get_locale_name(std::string lang, std::string enc, const std::string& filename = "") -> std::string; class Encoding { std::string name; public: enum Enc_Type { SINGLEBYTE = false, UTF8 = true }; Encoding() = default; Encoding(const std::string& e); auto operator=(const std::string& e) -> Encoding&; auto empty() const -> bool { return name.empty(); } operator const std::string&() const { return name; } auto value() const -> const std::string& { return name; } auto is_utf8() const -> bool { return name == "UTF-8"; } operator Enc_Type() const { return is_utf8() ? UTF8 : SINGLEBYTE; } }; enum Flag_Type { FLAG_SINGLE_CHAR /**< single-character flag, e.g. for "a" */, FLAG_DOUBLE_CHAR /**< double-character flag, e.g for "aa" */, FLAG_NUMBER /**< numerical flag, e.g. for 61 */, FLAG_UTF8 /**< UTF-8 flag, e.g. for "á" */ }; template <class CharT> struct Aff_Structures { Substr_Replacer<CharT> input_substr_replacer; Substr_Replacer<CharT> output_substr_replacer; Break_Table<CharT> break_table; std::basic_string<CharT> ignored_chars; Prefix_Table<CharT> prefixes; Suffix_Table<CharT> suffixes; std::vector<Compound_Pattern<CharT>> compound_patterns; }; struct Affix { using string = std::string; template <class T> using vector = std::vector<T>; char16_t flag; bool cross_product; string stripping; string appending; Flag_Set new_flags; string condition; vector<string> morphological_fields; }; struct Compound_Check_Pattern { using string = std::string; string first_word_end; string second_word_begin; string replacement; char16_t first_word_flag; char16_t second_word_flag; }; using Dic_Data_Base = Hash_Multiset<std::pair<std::string, Flag_Set>, std::string, member<std::pair<std::string, Flag_Set>, std::string, &std::pair<std::string, Flag_Set>::first>>; /** * @brief Map between words and word_flags. * * Flags are stored as part of the container. Maybe for the future flags should * be stored elsewhere (flag aliases) and this should store pointers. * * Does not store morphological data as is low priority feature and is out of * scope. */ class Dic_Data : public Dic_Data_Base { public: using Dic_Data_Base::equal_range; auto equal_range(const std::wstring& word) const -> std::pair<Dic_Data_Base::local_const_iterator, Dic_Data_Base::local_const_iterator> { return equal_range(boost::locale::conv::utf_to_utf<char>(word)); } }; struct Aff_Data { // types using string = std::string; using u16string = std::u16string; using istream = std::istream; template <class T> using vector = std::vector<T>; template <class T, class U> using pair = std::pair<T, U>; // data members // word list Dic_Data words; Aff_Structures<char> structures; Aff_Structures<wchar_t> wide_structures; // general options std::locale locale_aff; Flag_Type flag_type; bool complex_prefixes; bool fullstrip; bool checksharps; bool forbid_warn; char16_t circumfix_flag; char16_t forbiddenword_flag; char16_t keepcase_flag; char16_t need_affix_flag; char16_t substandard_flag; char16_t warn_flag; vector<Flag_Set> flag_aliases; string wordchars; // deprecated? // suggestion options string keyboard_layout; string try_chars; char16_t nosuggest_flag; unsigned short max_compound_suggestions; unsigned short max_ngram_suggestions; unsigned short max_diff_factor; bool only_max_diff; bool no_split_suggestions; bool suggest_with_dots; vector<pair<string, string>> replacements; vector<string> map_related_chars; // vector<vector<string>>? vector<pair<string, string>> phonetic_replacements; // compounding options unsigned short compound_min_length; unsigned short compound_max_word_count; char16_t compound_flag; char16_t compound_begin_flag; char16_t compound_last_flag; char16_t compound_middle_flag; char16_t compound_onlyin_flag; char16_t compound_permit_flag; char16_t compound_forbid_flag; char16_t compound_root_flag; char16_t compound_force_uppercase; bool compound_more_suffixes; bool compound_check_up; bool compound_check_rep; bool compound_check_case; bool compound_check_triple; bool compound_simplified_triple; vector<u16string> compound_rules; unsigned short compound_syllable_max; string compound_syllable_vowels; Flag_Set compound_syllable_num; // methods auto set_encoding_and_language(const string& enc, const string& lang = "") -> void; auto parse_aff(istream& in) -> bool; auto parse_dic(istream& in) -> bool; auto parse_aff_dic(std::istream& aff, std::istream& dic) { if (parse_aff(aff)) return parse_dic(dic); return false; } template <class CharT> auto get_structures() const -> const Aff_Structures<CharT>&; }; template <> auto inline Aff_Data::get_structures<char>() const -> const Aff_Structures<char>& { return structures; } template <> auto inline Aff_Data::get_structures<wchar_t>() const -> const Aff_Structures<wchar_t>& { return wide_structures; } } // namespace nuspell #endif // NUSPELL_AFF_DATA_HXX
27.20354
79
0.737313
ivanagui2
3cb11c0669d2ffc65dd1bd6de28260679d4cfdf0
3,046
cpp
C++
protocols/ace/RMCast/Retransmit.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
protocols/ace/RMCast/Retransmit.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
protocols/ace/RMCast/Retransmit.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// author : Boris Kolpackov <boris@kolpackov.net> // $Id: Retransmit.cpp 91626 2010-09-07 10:59:20Z johnnyw $ #include "ace/Time_Value.h" // ACE_Time_Value #include "ace/OS_NS_stdlib.h" // abort #include "ace/OS_NS_sys_time.h" // gettimeofday #include "Retransmit.h" namespace ACE_RMCast { Retransmit:: Retransmit (Parameters const& params) : params_ (params), cond_ (mutex_), stop_ (false) { } void Retransmit:: out_start (Out_Element* out) { Element::out_start (out); tracker_mgr_.spawn (track_thunk, this); } void Retransmit:: out_stop () { { Lock l (mutex_); stop_ = true; cond_.signal (); } tracker_mgr_.wait (); Element::out_stop (); } void Retransmit::send (Message_ptr m) { if (m->find (Data::id) != 0) { SN const* sn = static_cast<SN const*> (m->find (SN::id)); Lock l (mutex_); queue_.bind (sn->num (), Descr (m->clone ())); } out_->send (m); } void Retransmit::recv (Message_ptr m) { if (NAK const* nak = static_cast<NAK const*> (m->find (NAK::id))) { Address to (static_cast<To const*> (m->find (To::id))->address ()); if (nak->address () == to) { Lock l (mutex_); for (NAK::iterator j (const_cast<NAK*> (nak)->begin ()); !j.done (); j.advance ()) { u64* psn; j.next (psn); Message_ptr m; Queue::ENTRY* pair; if (queue_.find (*psn, pair) == 0) { //cerr << 5 << "PRTM " << to << " " << pair->ext_id_ << endl; m = pair->int_id_.message (); pair->int_id_.reset (); } else { //cerr << 4 << "message " << *psn << " not available" << endl; m = Message_ptr (new Message); m->add (Profile_ptr (new SN (*psn))); m->add (Profile_ptr (new NoData)); } out_->send (m); } } } in_->recv (m); } ACE_THR_FUNC_RETURN Retransmit:: track_thunk (void* obj) { reinterpret_cast<Retransmit*> (obj)->track (); return 0; } void Retransmit:: track () { while (true) { Lock l (mutex_); for (Queue::iterator i (queue_); !i.done ();) { if ((*i).int_id_.inc () >= params_.retention_timeout ()) { u64 sn ((*i).ext_id_); i.advance (); queue_.unbind (sn); } else { i.advance (); } } //FUZZ: disable check_for_lack_ACE_OS // Go to sleep but watch for "manual cancellation" request. // ACE_Time_Value time (ACE_OS::gettimeofday ()); //FUZZ: enable check_for_lack_ACE_OS time += params_.tick (); while (!stop_) { if (cond_.wait (&time) == -1) { if (errno != ETIME) ACE_OS::abort (); else break; } } if (stop_) break; } } }
19.908497
74
0.48851
cflowe
3cb2e04465d34e08dcdedb41ff4160c31eadc078
2,660
cpp
C++
franka_low_level_simulation_driver/src/LowLevelDriver/DegreeOfFreedom.cpp
User-TGK/franka_robot_control
48d62b2056aca2226cbe5ac3914f01bef3659f49
[ "MIT" ]
3
2019-12-12T13:09:49.000Z
2021-09-07T09:08:56.000Z
franka_low_level_simulation_driver/src/LowLevelDriver/DegreeOfFreedom.cpp
User-TGK/franka_robot_control
48d62b2056aca2226cbe5ac3914f01bef3659f49
[ "MIT" ]
null
null
null
franka_low_level_simulation_driver/src/LowLevelDriver/DegreeOfFreedom.cpp
User-TGK/franka_robot_control
48d62b2056aca2226cbe5ac3914f01bef3659f49
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <DegreeOfFreedom.hpp> namespace RobotControl { namespace FrankaLowLevelDriver { DegreeOfFreedom::DegreeOfFreedom(unsigned short aChannel, unsigned long aMinPulseWidth, unsigned long aMaxPulseWidth, double aMinAngle, double aMaxAngle, double aMaxSpeedPerSecond, unsigned long aCurrentPos, unsigned long aTargetPos) : channel(aChannel), minPulseWidth(aMinPulseWidth), maxPulseWidth(aMaxPulseWidth), minAngle(aMinAngle), maxAngle(aMaxAngle), maxSpeedPerSecond(aMaxSpeedPerSecond), currentPos(aCurrentPos), targetPos(aTargetPos) { } unsigned long DegreeOfFreedom::pulseWidthFromAngle(double angle) const { unsigned long result = ((angle - minAngle) * (maxPulseWidth - minPulseWidth) / (maxAngle - minAngle) + minPulseWidth); if(result > maxPulseWidth) { return maxPulseWidth; } else if(result < minPulseWidth) { return minPulseWidth; } return result; } double DegreeOfFreedom::angleFromPulseWidth(unsigned long pulseWidth) const { if(pulseWidth < minPulseWidth) { pulseWidth = minPulseWidth; } else if(pulseWidth > maxPulseWidth) { pulseWidth = maxPulseWidth; } return ((pulseWidth - minPulseWidth) * (maxAngle - minAngle) / (maxPulseWidth - minPulseWidth) + minAngle); } unsigned long DegreeOfFreedom::getConvertedSpeedFromDegreesPerSecond(double speed) const { unsigned short speedFactor = maxSpeed / minSpeed; double result = ((speed - (maxSpeedPerSecond / speedFactor)) * (maxSpeed - minSpeed) / (maxSpeedPerSecond - (maxSpeedPerSecond / speedFactor)) + minSpeed); if(result > maxSpeed) { return maxSpeed; } if(result < minSpeed) { ROS_DEBUG("THE MINIMUM DEGREES PER SECOND FOR THE DOF ON CHANNEL %s IS %s.", std::to_string(channel).c_str(), std::to_string(maxSpeedPerSecond / speedFactor).c_str()); return minSpeed; } return result; } unsigned short DegreeOfFreedom::getChannel() const { return this->channel; } unsigned long DegreeOfFreedom::getCurrentPos() const { return this->currentPos; } unsigned long DegreeOfFreedom::getTargetPos() const { return this->targetPos; } void DegreeOfFreedom::setCurrentPos(unsigned long aCurrentPos) { this->currentPos = aCurrentPos; } void DegreeOfFreedom::setTargetPos(unsigned long aTargetPos) { this->targetPos = aTargetPos; } } }
26.078431
120
0.652256
User-TGK
3cb3a1595c943ad6f1312bb4eafc020e575f5649
255
cpp
C++
source/Main.cpp
Dovgalyuk/QemuGUI
12ac1522bc02e5635fcd7b873a465f38a562b641
[ "Apache-2.0" ]
null
null
null
source/Main.cpp
Dovgalyuk/QemuGUI
12ac1522bc02e5635fcd7b873a465f38a562b641
[ "Apache-2.0" ]
null
null
null
source/Main.cpp
Dovgalyuk/QemuGUI
12ac1522bc02e5635fcd7b873a465f38a562b641
[ "Apache-2.0" ]
null
null
null
#include "QEMU-GUI.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QEMUGUI w; //QObject::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(saveSettingsBeforeQuit())); w.show(); return a.exec(); }
18.214286
86
0.627451
Dovgalyuk
3cb6f0fca73939c5590d4a394b2aaae2f47a8cc5
7,545
cpp
C++
Milestone 5/Product.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
Milestone 5/Product.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
Milestone 5/Product.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
// Aria Avazkhani //2018-07-31 //updated: 2018-08-08 #include "Product.h" namespace AMA { Product::Product(char type) { v_type = type; v_sku[0] = '\0'; v_unit[0] = '\0'; v_name = nullptr; v_qty = 0; v_need = 0; v_price = 0.0; v_status = false; } Product::Product(const char* sku, const char* n, const char* unit, int qty, bool status, double price, int need) { name(n); strncpy(v_sku, sku, max_sku_length); v_sku[max_sku_length] = '\0'; strncpy(v_unit, unit, max_unit_length); v_unit[max_unit_length] = '\0'; v_qty = qty; v_need = need; v_price = price; v_status = status; } Product::~Product() { delete[] v_name; } Product::Product(const Product& src) { int c = strlen(src.v_name); v_type = src.v_type; strncpy(v_sku, src.v_sku, max_sku_length); v_sku[max_sku_length] = '\0'; strncpy(v_unit, src.v_unit, max_unit_length); v_unit[max_unit_length] = '\0'; v_qty = src.v_qty; v_need = src.v_need; v_price = src.v_price; v_status = src.v_status; if (src.v_name != nullptr) { v_name = nullptr; v_name = new char[c]; for (int i = 0; i < c; ++i) { v_name[i] = src.v_name[i]; } v_name[c] = '\0'; } else v_name = nullptr; } void Product::name(const char* name) { if (name != nullptr) { int c = strlen(name); v_name = new char[c +1]; for (int i = 0; i < c; ++i){ v_name[i] = name[i]; } v_name[c] = '\0'; } } const char* Product::name() const { if (v_name[0] == '\0') return nullptr; else return v_name; } const char* Product::sku() const { return v_sku; } const char* Product::unit() const { return v_unit; } bool Product::taxed() const { return v_status; } double Product::price() const { return v_price; } double Product::cost() const { if (v_status == true) return price() * (tax + 1); else return price(); } void Product::message(const char* err) { v_err.message(err); } bool Product::isClear() const { return v_err.isClear(); } Product& Product::operator=(const Product& cpy) { if (this != &cpy){ v_type = cpy.v_type; v_qty = cpy.v_qty; v_need = cpy.v_need; v_price = cpy.v_price; v_status = cpy.v_status; name(cpy.v_name); strncpy(v_sku, cpy.v_sku, strlen(cpy.v_sku)); v_sku[strlen(cpy.v_sku)] = '\0'; strncpy(v_unit, cpy.v_unit, strlen(cpy.v_unit)); v_unit[strlen(cpy.v_unit)] = '\0'; } return *this; } std::fstream& Product::store(std::fstream& file, bool newLine) const { file << v_type << ',' << v_sku << ',' << v_name << ',' << v_unit << ',' << v_status << ',' << v_price << ',' << v_qty << ',' << v_need; if (newLine == true) file << endl; return file; } std::fstream& Product::load(std::fstream& file) { char t_sku[max_sku_length]; char t_name[max_name_length]; char t_unit[max_unit_length]; double t_price; int t_qty, t_need; char t_tax; bool t_status; if (file.is_open()){ file.getline(t_sku, max_sku_length, ','); t_sku[strlen(t_sku)] = '\0'; file.getline(t_name, max_name_length, ','); t_name[strlen(t_name)] = '\0'; file.getline(t_unit, max_unit_length, ','); t_unit[strlen(t_unit)] = '\0'; file >> t_tax; if (t_tax == '1') t_status = true; else if (t_tax == '0') t_status = false; file.ignore(); file >> t_price; file.ignore(); file >> t_qty; file.ignore(); file >> t_need; file.ignore(); *this = Product(t_sku, t_name, t_unit, t_qty, t_status, t_price, t_need); } return file; } std::ostream& Product::write(std::ostream& os, bool linear) const { if (!(v_err.isClear())){ os << v_err.message(); } else if (linear){ os << setw(max_sku_length) << left << setfill(' ') << v_sku << '|' << setw(20) << left << v_name << '|' << setw(7) << right << fixed << setprecision(2) << cost() << '|' << setw(4) << right << v_qty << '|' << setw(10) << left << v_unit << '|' << setw(4) << right << v_need << '|'; } else{ os << " Sku: " << v_sku << endl << " Name (no spaces): " << v_name << endl << " Price: " << v_price << endl; if (v_status == true) os << " Price after tax: " << cost() << endl; else{ os << " Price after tax: N/A"<< endl; } os << " Quantity on Hand: " << v_qty << " " << v_unit << endl << " Quantity needed: " << v_need; } return os; } std::istream& Product::read(std::istream& is) { char tax; char* address = new char[max_name_length + 1]; int qty, need; double t_price; if (!is.fail()){ cout << " Sku: "; is >> v_sku; cin.ignore(); cout << " Name (no spaces): "; is >> address; name(address); cout << " Unit: "; is >> v_unit; cout << " Taxed? (y/n): "; is >> tax; if (!is.fail()){ v_err.clear(); if (tax){ bool yes = tax == 'y' || tax == 'Y'; bool no = tax == 'n' || tax == 'N'; if (yes) v_status = true; if (no) v_status = false; if (!(yes || no)){ is.setstate(std::ios::failbit); v_err.message("Only (Y)es or (N)o are acceptable"); return is; } } } else{ is.setstate(std::ios::failbit); v_err.message("Only (Y)es or (N)o are acceptable"); return is; } cout << " Price: "; is >> t_price; if (is.fail()) { v_err.clear(); is.setstate(ios::failbit); v_err.message("Invalid Price Entry"); return is; } else prices(t_price); cout << " Quantity on hand: "; is >> qty; if (is.fail()){ v_err.clear(); v_err.message("Invalid Quantity Entry"); is.setstate(ios::failbit); return is; } else quantity(qty); cout << " Quantity needed: "; is >> need; cin.ignore(); if (is.fail()) { v_err.clear(); v_err.message("Invalid Quantity Needed Entry"); is.setstate(ios::failbit); return is; } else qtyNeed(need); if (!is.fail()){ v_err.clear(); } } return is; } bool Product::operator==(const char* src) const { if (strcmp(src, this->v_sku) == 0) return true; else return false; } double Product::total_cost() const { return static_cast<double>(v_qty * (v_price + (v_price * tax))); } void Product::quantity(int stock) { v_qty = stock; } bool Product::isEmpty() const { if (v_name == nullptr) return true; else return false; } int Product::qtyNeeded() const { return v_need; } int Product::quantity() const { return v_qty; } void Product::qtyNeed(int nd){ v_need = nd; } void Product::prices(double pr){ v_price = pr; } bool Product::operator>(const char* prd) const { if (strcmp(v_sku, prd) > 0) return true; else return false; } bool Product::operator>(const iProduct& src) const { if (strcmp(v_name, src.name()) > 0) return true; else return false; } int Product::operator+=(int add) { if (add > 0) v_qty += add; return v_qty; } std::ostream& operator<<(std::ostream& os, const iProduct& pr) { return pr.write(os, true); } std::istream& operator>>(std::istream& is, iProduct& pr) { return pr.read(is); } double operator+=(double& num, const iProduct& pr) { return num + pr.total_cost(); } }
21.618911
116
0.544599
ariaav
3cb73ff5d7cec0899102c859270959d80be1a58e
15,073
cpp
C++
40_cpnLearnTesting.cpp
KathrynLaing/CPNLearning
b5123f7f1fe5adda8a63a73ed117c67e282cea69
[ "MIT" ]
null
null
null
40_cpnLearnTesting.cpp
KathrynLaing/CPNLearning
b5123f7f1fe5adda8a63a73ed117c67e282cea69
[ "MIT" ]
null
null
null
40_cpnLearnTesting.cpp
KathrynLaing/CPNLearning
b5123f7f1fe5adda8a63a73ed117c67e282cea69
[ "MIT" ]
null
null
null
#include "40_cpnlTest.h" double dataAgreementWithFlips(string filename, int D, cpn cpnet){ //Calculates DFA between data and cpnet //filename tells us the location of the data - Assumed to be written on 1 comma separated line, each entry is an observed outcome //D tells us the number of data points //cpnet is the cpn of interest //first we read in the data and enter it into vector data vector<int> data(D); int line=1; int cols=D; int d; ifstream file(filename); char dummy; for (int i = 0; i < line; i++){ for (int j = 0; j < cols; j++){ file >> d; data[j]=d; if (j < (cols - 1)){ file >> dummy; } } } file.close(); //nvar is the number of variables in the CP-net int nvar=cpnet.size; //convert the data into counts - instead of a list of observed outcomes we have a vector where the ith entry is the number of times outcome i was observed //outcomes are assumed to be in lexicographic order vector<int> counts(pow(2,nvar),0); for(int i=0;i<D;i++){ counts[data[i]]+=1; } //LexMult is the lexicographic multipliers of the variables (the mutlipliers we use to convert between outcomes and their enumeration) vector<int> LexMult(nvar); for(int i=0;i<nvar;i++){ LexMult[i]=pow(2,nvar-i-1); } //AgreementScore will be the DFA score numerator int AgreementScore=0; //adjMat is the adjacency matrix of the CP-net structure. entries and breaks are the cpt details vector<int> adjMat=cpnet.structure; vector<int> entries=cpnet.cptEntries; vector<int> breaks=cpnet.cptBreaks; //for each variable, X, calculate (and add) the the data differences over X flips for(int i=0;i<nvar;i++){ //parents - 0/1 vector giving the parents of X //nPa - number of parents vector<int> parents(nvar); int nPa=0; for(int j=0;j<nvar;j++){ parents[j]=adjMat[j*nvar+i]; nPa+=parents[j]; } //Pa - an nPa vector giving the indices of the parents vector<int> Pa(nPa); int counter=0; for(int j=0;j<nvar;j++){ if(parents[j]==1){ Pa[counter]=j; counter+=1; } } // nother is the number of variables which are not X or parents of X int nOther=nvar-1-nPa; // otherWeights - list of all possible weights these other variables can add to the lexicographic posn of an outcome //otherAssts - cycles through all possible assignments to these other variables std::vector<int> otherWeights(pow(2,nOther)); std::vector<int> otherAssts(nOther,0); std::vector<int> otherMult(nOther); if(nOther>0){ int counter=0; for(int k=0;k<nvar;k++){ if(k!=i){ if(parents[k]==0){ otherMult[counter]=LexMult[k]; counter+=1; } } } for(int k=0;k<pow(2,nOther);k++){ int weight=0; for(int l=0;l<nOther;l++){ weight+= otherAssts[l]*otherMult[l]; } otherWeights[k]=weight; if(k!=(pow(2,nOther)-1)){ int max=0; for(int l=0;l<nOther;l++){ if(otherAssts[l]==0){ if(l>max){ max=l; } } } otherAssts[max]=1; for(int l=max+1;l<nOther;l++){ otherAssts[l]=0; } } } } //For each parent assignment to Pa(X) we find the data differences over all X flips under this assignment //PaAsst cycles through all possible parental assignments vector<int> PaAsst(nPa,0); for(int j=0; j<pow(2,nPa);j++){ //fixedweight is the weight contributed by parent assignment PaAsst to the lexicographic position of an outcome int fixedweight=0; for(int k=0;k<nPa;k++){ fixedweight+=PaAsst[k]*LexMult[Pa[k]]; } //group1/2 are the lists of the lexicographic positions of outcomes with Pa(x)=PaAsst and X=1/2 vector<int> group1(pow(2,nOther)); vector<int> group2(pow(2,nOther)); if(nOther==0){ group1[0]=fixedweight; group2[0]=fixedweight+LexMult[i]; } else{ for(int k=0;k<pow(2,nOther);k++){ group1[k]=fixedweight+otherWeights[k]; group2[k]=fixedweight+otherWeights[k]+LexMult[i]; } } //value1/2 is the number of data observations of outcomes in group 1/2 int value1=0; int value2=0; for(int k=0;k<pow(2,nOther);k++){ value1+=counts[group1[k]]; value2+=counts[group2[k]]; } //if the CPT rule corresponding to PaAsst is 1>2, then the data difference is value1-value2 // Add this to our score if(entries[breaks[i]+2*j]==1){ AgreementScore+=value1-value2; } else{//if the CPT rule is 2>1, then the data difference is value2-value1 AgreementScore+=value2-value1; } //move to next parent assignmnent if(j!=(pow(2,nPa)-1)){ int max=0; for(int k=0;k<nPa;k++){ if(PaAsst[k]==0){ max=k; } } PaAsst[max]=1; for(int k=max+1;k<nPa;k++){ PaAsst[k]=0; } } //We have added the data differences for all PaAsst X-flips to the score } //After cycling through all parental assignments, we have now added all X-flip data differences } //AgreementScore is now the sum of all variable flip data differences //To obtain DFA, we must divide this by n*#data points double ScaledFlipAgreement = (double) AgreementScore/ ((double) nvar* (double) D); return ScaledFlipAgreement; } double dataOrderCompatibleWithCPN(string filename, int D, cpn cpnet, long long int nTests){ //Calculates DOC between the cpnet and data located at filename. nTests the level of approximation we will use in our calculation. //filename - location of data //D - number of data points in file //cpn - CP-net of interest //nTests - number of comparisons we are going to do (max possible number of tests is number of unordered pairs of outcomes) //first we read in the data and enter it into vector data vector<int> data(D); int line=1; int cols=D; int d; ifstream file(filename); char dummy; for (int i = 0; i < line; i++){ for (int j = 0; j < cols; j++){ file >> d; data[j]=d; if (j < (cols - 1)){ file >> dummy; } } } file.close(); //nvar is the number of variables in the CP-net int nvar=cpnet.size; //convert the data into counts - instead of a list of observed outcomes we have a vector where the ith entry is the number of times outcome i was observed //outcomes are assumed to be in lexicographic order vector<int> counts(pow(2,nvar),0); for(int i=0;i<D;i++){ counts[data[i]]+=1; } //next we ensure that the number of comparisons is not more than the maximum possible long long int maxComp= (pow(2,nvar)*(pow(2,nvar)-1))/2; if(nTests>maxComp){ nTests=maxComp; } //Comparisons will be a 0/1 vector recording which outcome pairs have been done already. //Every outcome corresponds to a number between 0 and 2^n-1 (they are enumerated lexicographically) //A distinct outcome pair can thus be written (a,b) a=/=b. If we order outcome pairs in lexicographic order (when considered as coordinate pair) then the ithe pair corresponds to ith entry of comparisons //That is (1,0), (2,0), (2,1),(3,0),(3,1),(3,2),(4,0),........ vector<int> Comparisons(maxComp,0); //if nTests=maxposns then we can just move through the outcome pairs systematically as all need to be tested //Otherwise, we must select a (not yet considered) outcome pair at random each time //outposn1 - lexicographic position of outcome 1 in our pair //outposn2 - lexicographic position of outcome 2 long long int outPosn1=1; long long int outPosn2=0; //LexMult is a vector of lexicographic multipliers that we use to move between an outcome and its lex position vector<long long int> LexMult(nvar); for(int i=0;i<nvar;i++){ LexMult[i]=pow(2,nvar-i-1); } //initiate a random generator for uniform selection of an outcome pair //randomly selects a number between 0 and maxComp-1, this then gives an outcome pair by the enumeration of pairs we use in Comparisons struct timeval tv; gettimeofday(&tv,0); unsigned long mySeed = tv.tv_sec + tv.tv_usec; typedef std::mt19937 G; G g(mySeed); typedef std::uniform_int_distribution<long long int> Dist; Dist uni(0, maxComp-1); //later in the function we need to perform dominance testing. We must add 1 to our breaks vector before feeding the CP-net into this function //This is an issue left over from translating functions from R to C++ vector<int> breaks=cpnet.cptBreaks; for(int i=0;i<breaks.size();i++){ breaks[i]+=1; } //supportedRelns will count the number of outcomes pairs we test where the cpnet does not contradict the data; long long int supportedRelns=0; //perform nTests many outcome pair tests: for(long long int i=0;i<nTests;i++){ //if nTests<maxposns, we need to randomly select a new outcome pair. if(nTests<maxComp){ bool newOutcome=false; while(!newOutcome){ //randomly select an outcome pair by generating its lexicographic position long long int outPair=uni(g); //Check Comparisons vector to see if it has been considered previously if(Comparisons[outPair]==0){ //If it hasn't been considered previously, mark in Comparisons that we have now done this pair Comparisons[outPair]=1; newOutcome=true; //convert the lexicographic position of the pair into the coordinate pair that gives the lex positions of outcome 1 and 2 in the pair outPosn1=2; bool identified=false; while(!identified){ if(outPair<(outPosn1*(outPosn1-1))/2){ identified=true; outPosn1-=1; } else{ outPosn1+=1; } } outPosn2=outPair - ((outPosn1*(outPosn1-1))/2); } //If it has been considered previously, generate a new pair and try again } } //If we are systematically moving through the pairs, then mark this pair as considered if(nTests==maxComp){ Comparisons[i]=1; } // let us copy outPosn1/2 to new ints to preserve them long long int posn1=outPosn1; long long int posn2=outPosn2; //next we need to turn the pair of outcome positions into two outcomes (vectors out1 and out2) vector<int> out1(nvar,1); vector<int> out2(nvar,1); for(int j=0;j<nvar;j++){ int div1=posn1/LexMult[j]; if(div1==1){ out1[j]=2; posn1-=LexMult[j]; } int div2=posn2/LexMult[j]; if(div2==1){ out2[j]=2; posn2-=LexMult[j]; } } //next we want to find the number of observed data points for the selected outcomes: int data1=counts[outPosn1]; int data2=counts[outPosn2]; if(data1>data2){ //out1 preferred to out2 is only contradicted by the cpnet if it entails out2>out1 so perform dominance test out2>out1 List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out2,out1); bool outcome=DTOut.result; if(!outcome){ //If dominance test false then cpnet does not entail out2>out1 so the data is not contradicted //Thus, we say the CP-net is consistent with this relation in the data and we add a support count supportedRelns+=1; } } if(data2>data1){ //out2 preferred to out1 is only contradicted by the cpnet if it entails out1>out2 so perform dominance test out1>out2 List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out1,out2); bool outcome=DTOut.result; if(!outcome){ //If dominance test false then cpnet does not entail out1>out2 so the data is not contradicted //Thus, we say the CP-net is consistent with this relation in the data and we add a support count supportedRelns+=1; } } if(data1==data2){ //out1 equally preferred to out2 is contradicted by the cpnet if it entails either out1>out2 or out2>out1 so dominance test both //First we dominance test out1>out2 List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out1,out2); bool outcome=DTOut.result; if(!outcome){ //If dominance test is false, we then test out2>out1 DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out2,out1); outcome=DTOut.result; if(!outcome){ //If both dominance tests are false, neither direction is entailed and the CP-net is consistent with the data relation so we add a support count supportedRelns+=1; } } } //if we are moving through the pairs systematically, we then move on to next pair: if(nTests==maxComp){ if(outPosn2==(outPosn1-1)){ outPosn1+=1; outPosn2=0; } else{ outPosn2+=1; } } } //supportedRelns now counts the number of tests (outcome pairs) for which the CP-net was consistent with the data relation //DOC is then obtained by dividing by the number of tests performed return (double)supportedRelns/(double)nTests; }
44.594675
207
0.569362
KathrynLaing
3cba5846488d51a78aa69fea139728e4b5c8400e
622
cpp
C++
SomeOpenMPFirst/order.cpp
Roomanidzee/cpp_projects
0474ca1bb9ce33c5a58d87ab4bd5c618e74328f8
[ "MIT" ]
null
null
null
SomeOpenMPFirst/order.cpp
Roomanidzee/cpp_projects
0474ca1bb9ce33c5a58d87ab4bd5c618e74328f8
[ "MIT" ]
null
null
null
SomeOpenMPFirst/order.cpp
Roomanidzee/cpp_projects
0474ca1bb9ce33c5a58d87ab4bd5c618e74328f8
[ "MIT" ]
null
null
null
// // Created by andrey on 19.09.18. // #include <iostream> #include <omp.h> #define N1 3 #define N2 1 int main(){ omp_set_num_threads(N1); #pragma omp parallel if(omp_get_max_threads() > 2) { if(omp_in_parallel()){ printf("Количество нитей: %d; Номер нити : %d\n", omp_get_num_threads(), omp_get_thread_num()); } } omp_set_num_threads(N2); #pragma omp parallel if(omp_get_max_threads() > 2) { if(omp_in_parallel()){ printf("Количество нитей: %d; Номер нити : %d\n", omp_get_num_threads(), omp_get_thread_num()); } } return 0; };
18.848485
107
0.602894
Roomanidzee
3cbc021ff111d38ed567faa35393a52e3890d2be
767
cpp
C++
solved/r-t/tex-quotes/tex.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/r-t/tex-quotes/tex.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/r-t/tex-quotes/tex.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> // I/O #define BUF 65536 struct Reader { char buf[BUF]; char b; int bi, bz; Reader() { bi=bz=0; read(); } void read() { if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); } b = bz ? buf[bi++] : 0; } void process() { bool open = true; while (b != 0) { if (b == '"') { if (open) { putchar('`'); putchar('`'); } else { putchar('\''); putchar('\''); } open = !open; } else putchar(b); read(); } } }; int main() { Reader rr; rr.process(); return 0; }
18.261905
61
0.324641
abuasifkhan
3cbc431c3c0c54fe18f5aef5320ef2a53ba2383a
2,338
cpp
C++
samples/cpp/polar_transforms.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
null
null
null
samples/cpp/polar_transforms.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
null
null
null
samples/cpp/polar_transforms.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
1
2019-09-05T06:47:23.000Z
2019-09-05T06:47:23.000Z
#include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace cv; static void help( void ) { printf("\nThis program illustrates Linear-Polar and Log-Polar image transforms\n" "Usage :\n" "./polar_transforms [[camera number -- Default 0],[path_to_filename]]\n\n"); } int main( int argc, char** argv ) { VideoCapture capture; Mat log_polar_img, lin_polar_img, recovered_log_polar, recovered_lin_polar_img; help(); CommandLineParser parser(argc, argv, "{@input|0|}"); std::string arg = parser.get<std::string>("@input"); if( arg.size() == 1 && isdigit(arg[0]) ) capture.open( arg[0] - '0' ); else capture.open( arg.c_str() ); if( !capture.isOpened() ) { const char* name = argv[0]; fprintf(stderr,"Could not initialize capturing...\n"); fprintf(stderr,"Usage: %s <CAMERA_NUMBER> , or \n %s <VIDEO_FILE>\n", name, name); return -1; } namedWindow( "Linear-Polar", WINDOW_NORMAL ); namedWindow( "Log-Polar", WINDOW_NORMAL ); namedWindow( "Recovered Linear-Polar", WINDOW_NORMAL ); namedWindow( "Recovered Log-Polar", WINDOW_NORMAL ); moveWindow( "Linear-Polar", 20,20 ); moveWindow( "Log-Polar", 700,20 ); moveWindow( "Recovered Linear-Polar", 20, 350 ); moveWindow( "Recovered Log-Polar", 700, 350 ); for(;;) { Mat frame; capture >> frame; if( frame.empty() ) break; Point2f center( (float)frame.cols / 2, (float)frame.rows / 2 ); double M = (double)frame.cols / 8; logPolar(frame,log_polar_img, center, M, INTER_LINEAR + WARP_FILL_OUTLIERS); linearPolar(frame,lin_polar_img, center, M, INTER_LINEAR + WARP_FILL_OUTLIERS); logPolar(log_polar_img, recovered_log_polar, center, M, WARP_INVERSE_MAP + INTER_LINEAR); linearPolar(lin_polar_img, recovered_lin_polar_img, center, M, WARP_INVERSE_MAP + INTER_LINEAR + WARP_FILL_OUTLIERS); imshow("Log-Polar", log_polar_img ); imshow("Linear-Polar", lin_polar_img ); imshow("Recovered Linear-Polar", recovered_lin_polar_img ); imshow("Recovered Log-Polar", recovered_log_polar ); if( waitKey(10) >= 0 ) break; } waitKey(0); return 0; }
30.763158
125
0.627887
snosov1
3cbe802b4fa7aa4df9f6916e8fcca2aa907a1a43
13,925
cpp
C++
software/test/testLogTable/main.cpp
greenenergyprojects/electro-vehicle-charger-met16
cf8c274da60ee8c340915f377c3b352e3ed3e552
[ "MIT" ]
1
2022-03-18T18:49:50.000Z
2022-03-18T18:49:50.000Z
software/test/testLogTable/main.cpp
greenenergyprojects/electro-vehicle-charger-met16
cf8c274da60ee8c340915f377c3b352e3ed3e552
[ "MIT" ]
null
null
null
software/test/testLogTable/main.cpp
greenenergyprojects/electro-vehicle-charger-met16
cf8c274da60ee8c340915f377c3b352e3ed3e552
[ "MIT" ]
null
null
null
#include <string> #include <stdint.h> #include <string.h> #include "mon.hpp" namespace std { uint8_t eep [E2END + 1]; void cli() {} void sei() {} void popSREG () {} void pushSREGAndCli () {} void eeprom_init () { for (int i = 0; i < sizeof(eep); i++) { eep[i] = 0xff; } } void eeprom_busy_wait() { } void eeprom_update_byte (u1_mon::plogtable_t p, uint8_t v) { if (p >= 0 && p < sizeof(eep)) { // printf(" eep %04x <- %02x\n", p, v); eep[p] = v; } } void eeprom_write_byte (u1_mon::plogtable_t p, uint8_t v) { if (p >= 0 && p < sizeof(eep)) { // printf(" eep %04x <- %02x\n", p, v); eep[p] = v; } } uint8_t eeprom_read_byte (u1_mon::plogtable_t p) { if (p >= 0 && p < sizeof(eep)) { return eep[p]; } return 0xff; } uint16_t eeprom_read_word (u1_mon::plogtable_t p) { return (eeprom_read_byte(p + 1) << 8) | eeprom_read_byte(p); } void eeprom_read_block (void *dest, u1_mon::plogtable_t src, int size) { uint8_t *p = (uint8_t *)dest; if (p == NULL) { return; } while (size > 0) { if (src >= 0 && src < sizeof(eep) ) { *p++ = eep[src++]; } size--; } } void eeprom_update_block (void *src, u1_mon::plogtable_t dst, int size) { uint8_t *pFrom = (uint8_t *)src; while (size-- > 0) { uint8_t b = *pFrom++; eeprom_write_byte(dst++, b); } } } namespace u1_app { struct Clock { uint16_t ms; uint8_t sec; uint8_t min; uint8_t hrs; }; struct Trim { uint32_t magic; uint16_t startCnt; // only 15 bits used -> log record uint8_t vcpK; uint8_t vcpD; uint8_t currK; int8_t tempK; int8_t tempOffs; }; struct LogChargingHistory { uint8_t typ; uint32_t time; struct u1_mon::LogDataCharging data; }; struct App { struct u1_mon::LogDataCharging logDataCharging; struct LogChargingHistory logChargingHistory[4]; struct Trim trim; struct Clock clock; } app; void clearLogHistory (); void addLogCharging (uint8_t typ, uint32_t time, uint8_t logIndex); } using namespace std; namespace u1_mon { struct Mon mon; // uint8_t nextLogIndex (int16_t index) { // if (index < 0) { // return 0; // } // return index >= EEP_LOG_DESCRIPTORS ? 0 : index + 1; // } int16_t findLogDescriptorIndex (uint32_t time) { int16_t rv = -1; uint32_t rvTimeDiff = 0xffffffff; uint8_t index = 0; plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index; struct LogDescriptor d; while (index < EEP_LOG_DESCRIPTORS) { eeprom_busy_wait(); eeprom_read_block(&d, p, sizeof (d)); uint8_t typ = d.typ & 0x0f; if (typ != 0x0f) { uint32_t diff = d.time > time ? d.time - time : time - d.time; if (diff < rvTimeDiff) { rvTimeDiff = diff; rv = index; } u1_app::addLogCharging(typ, d.time, index); } index++; p += sizeof(struct LogDescriptor); } return rv; } int16_t findNewestLogDescriptorIndex () { return findLogDescriptorIndex(0xffffffff); } int16_t findOldestLogDescriptorIndex () { return findLogDescriptorIndex(0); } void readLogData (uint8_t index, uint8_t *pDest, uint8_t destSize) { if (index >= EEP_LOG_DESCRIPTORS) { return; } eeprom_busy_wait(); plogtable_t pFrom = (plogtable_t)EEP_LOG_SLOTS_START + EEP_LOG_SLOT_SIZE * index; eeprom_read_block(pDest, pFrom, destSize); printf(" readLogData %d %p %d -> %02x %02x %02x %02x\n", index, (void *)(pDest), destSize, pDest[0], pDest[1], pDest[2], pDest[3]); } uint8_t saveLog (uint8_t typ, void *pData, uint8_t size) { if (typ >= 0x0f) { return 0xff; // error } struct LogDescriptor d; d.typ = 0x0f; pushSREGAndCli(); { uint16_t tHigh = (u1_app::app.trim.startCnt << 1) | ((u1_app::app.clock.hrs >> 4) & 0x01); uint16_t tLow = ((u1_app::app.clock.hrs & 0x0f) << 12) | ((u1_app::app.clock.min & 0x3f) << 6) | (u1_app::app.clock.sec & 0x3f); d.time = (((uint32_t)tHigh) << 16) | tLow; } popSREG(); uint8_t index = 0; plogtable_t p = (plogtable_t)EEP_LOG_START; plogtable_t pTo = (plogtable_t)EEP_LOG_SLOTS_START; uint8_t lastTyp = typ; if (mon.log.index < EEP_LOG_DESCRIPTORS) { index = mon.log.index; p += index * sizeof (struct LogDescriptor); pTo += index * EEP_LOG_SLOT_SIZE; lastTyp = mon.log.lastTyp == 0 ? 0xff : mon.log.lastTyp; } uint8_t rv; int16_t bytes = size; uint8_t slotCnt = 0; do { if (lastTyp != typ || slotCnt > 0) { index++; p += sizeof (struct LogDescriptor); pTo += EEP_LOG_SLOT_SIZE; if (index >= EEP_LOG_DESCRIPTORS) { p = (plogtable_t)EEP_LOG_START; pTo = (plogtable_t)EEP_LOG_SLOTS_START; index = 0; } } if (slotCnt == 0) { rv = index; } d.typ = (d.typ & 0x0f) | (slotCnt++ << 4); eeprom_busy_wait(); eeprom_update_block(&d, p, sizeof(d)); uint8_t l = bytes < EEP_LOG_SLOT_SIZE ? bytes : EEP_LOG_SLOT_SIZE; eeprom_busy_wait(); if (pData != NULL && size > 0) { eeprom_update_block(pData, pTo, l); bytes -= EEP_LOG_SLOT_SIZE; pData = ((uint8_t *)pData) + l; } } while (bytes > 0 && slotCnt < 16); index = rv; p = (plogtable_t)EEP_LOG_START + index * sizeof (struct LogDescriptor); d.typ = typ; uint8_t slot = 0; while (slotCnt-- > 0) { d.typ = (d.typ & 0x0f) | (slot << 4); eeprom_busy_wait(); eeprom_write_byte(p, *((uint8_t *)&d)); p += sizeof (struct LogDescriptor); mon.log.index = index++; slot++; if (index >= EEP_LOG_DESCRIPTORS) { p = (plogtable_t)EEP_LOG_START; index = 0; } } mon.log.lastTyp = typ; u1_app::addLogCharging(typ, d.time, rv); return rv; } void startupLog () { int16_t startIndex = findNewestLogDescriptorIndex(); mon.log.index = startIndex < 0 ? EEP_LOG_DESCRIPTORS : startIndex + 1; if (mon.log.index >= EEP_LOG_DESCRIPTORS) { mon.log.index = 0; } mon.log.lastTyp = 0xff; saveLog(LOG_TYPE_SYSTEMSTART, NULL, 0); } void clearEEP (plogtable_t pStartAddr, uint16_t size) { while (size-- > 0 && (uint16_t)pStartAddr <= E2END) { eeprom_busy_wait(); eeprom_write_byte(pStartAddr++, 0xff); } eeprom_busy_wait(); } void clearLogTable () { clearEEP((plogtable_t)EEP_LOG_START, E2END + 1 - EEP_LOG_START); mon.log.index = 0xff; mon.log.lastTyp = 0x0f; } int8_t cmd_log (uint8_t argc, const char **argv) { if (argc == 2 && strcmp("clear", argv[1]) == 0) { clearLogTable(); return 0; } if (argc > 1) { return -1; } struct LogDescriptor d; int16_t startIndex = findOldestLogDescriptorIndex(); uint8_t cnt = 0; if (startIndex >= 0) { uint8_t index = (uint8_t)startIndex; plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index; struct LogDescriptor d; do { eeprom_busy_wait(); eeprom_read_block(&d, p, sizeof (d)); if ((d.typ & 0x0f) != 0x0f) { cnt++; uint8_t typ = d.typ & 0x0f; uint8_t subIndex = d.typ >> 4; uint16_t startupCnt = d.time >> 17; uint8_t hrs = (d.time >> 12) & 0x1f; uint8_t min = (d.time >> 6) & 0x3f; uint8_t sec = d.time & 0x3f; printf(" %2d(%01x/%01x) %5d-%02d:%02d:%02d -> ", index, typ, subIndex, startupCnt, hrs, min, sec); uint8_t slot[EEP_LOG_SLOT_SIZE]; eeprom_busy_wait(); eeprom_read_block(&slot, (plogtable_t)EEP_LOG_SLOTS_START + index * EEP_LOG_SLOT_SIZE, sizeof (slot)); switch (d.typ) { case LOG_TYPE_SYSTEMSTART: { printf("system start"); break; } case LOG_TYPE_STARTCHARGE: { struct LogDataStartCharge *pData = (struct LogDataStartCharge *)&slot; printf("start charge maxAmps=%u", pData->maxAmps); break; } case LOG_TYPE_CHARGING: case LOG_TYPE_STOPCHARGING: { struct LogDataCharging *pData = (struct LogDataCharging *)&slot; uint8_t e = pData->energyKwhX256 >> 8; uint8_t nk = ((pData->energyKwhX256 & 0xff) * 100 + 128) / 256; if (d.typ == LOG_TYPE_STOPCHARGING) { printf("stop "); } printf("charge %u:%02u, E=%u.%02ukWh", pData->chgTimeHours, pData->chgTimeMinutes, e, nk); break; } default: { printf("? ("); for (uint8_t i = 0; i < sizeof slot; i++) { printf(" %02x", slot[i]); } printf(")"); break; } } printf("\n"); } index++; p += sizeof(struct LogDescriptor); if (index >= EEP_LOG_DESCRIPTORS) { index = 0; p = (plogtable_t)EEP_LOG_START; } } while (index != startIndex); } printf("%d valid log records\n", cnt); printf("\nLog history:\n"); for (uint8_t i = 0; i < (sizeof (u1_app::app.logChargingHistory) / sizeof (u1_app::app.logChargingHistory[0])); i++) { struct u1_app::LogChargingHistory *p= &(u1_app::app.logChargingHistory[i]); printf(" %u: typ=%u time=%04x%04x ", i, p->typ, (uint16_t)(p->time >> 16), (uint16_t)(p->time)); printf("= %u-%u:%02u:%02u -> ", (uint16_t)(p->time >> 17), (uint16_t)((p->time >> 12) & 0x1f), (uint16_t)((p->time >> 6) & 0x3f), (uint16_t)(p->time & 0x3f)); printf(" %u:%02umin", p->data.chgTimeHours, p->data.chgTimeMinutes); printf(" %u.%02ukWh", p->data.energyKwhX256 >> 8, ((p->data.energyKwhX256 & 0xff) * 100 + 128) / 256); printf("\n"); } return 0; } } namespace u1_app { void clearLogHistory () { int s = sizeof (u1_app::app.logChargingHistory); memset(u1_app::app.logChargingHistory, 0, sizeof (u1_app::app.logChargingHistory)); } void addLogCharging (uint8_t typ, uint32_t time, uint8_t logIndex) { static uint8_t index = 0; if (typ != LOG_TYPE_STOPCHARGING) { return; } struct u1_app::LogChargingHistory *px = &u1_app::app.logChargingHistory[index]; px->typ = typ; px->time = time; u1_mon::readLogData(logIndex, (uint8_t*)&px->data, sizeof(px->data)); printf("hist[%d]: set %p ... %u %04x%04x\n", index, (void *)px, logIndex, (uint16_t)(time >> 16), (uint16_t)time); index++; if (index >= (sizeof(app.logChargingHistory) / sizeof(app.logChargingHistory[0]))) { index } } } int main () { eeprom_init(); u1_app::app.trim.startCnt = 0x01; u1_app::app.clock.hrs = 0; u1_app::app.clock.min = 0x00; u1_app::app.clock.sec = 0x00; u1_mon::mon.log.index = 0xff; u1_mon::startupLog(); struct u1_mon::LogDataStartCharge x1 = { 10 }; struct u1_mon::LogDataCharging x2 = { 0, 0, 0 }; u1_mon::saveLog(1, &x1, sizeof x1); for (int i = 0; i < 100; i++) { if (i % 100 == 99) { uint8_t f[16]; for (int i = 0; i < sizeof f; i++) { f[i] = i + 10; } u1_mon::saveLog(14, &f, sizeof f); } else if (i % 10 == 9) { u1_mon::saveLog(3, &x2, sizeof x2); } else { u1_mon::saveLog(2, &x2, sizeof x2); } u1_app::app.clock.sec++; if (u1_app::app.clock.sec == 60) { u1_app::app.clock.min++; u1_app::app.clock.sec = 0; } x2.chgTimeMinutes += 2; if (x2.chgTimeMinutes >= 60) { x2.chgTimeMinutes -= 60; x2.chgTimeHours++; } x2.energyKwhX256 += 200; } u1_app::clearLogHistory(); u1_mon::startupLog(); const char *argv[] = { "cmd_log" }; u1_mon::cmd_log(1, argv); return 0; }
32.611241
170
0.488977
greenenergyprojects
3cbea37cb4afc94db99bf6fa442ce481d8828b2a
3,410
inl
C++
clove/components/core/graphics/include/Clove/Graphics/Validation/ValidationQueue.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
33
2020-01-09T04:57:29.000Z
2021-08-14T08:02:43.000Z
clove/components/core/graphics/include/Clove/Graphics/Validation/ValidationQueue.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
234
2019-10-25T06:04:35.000Z
2021-08-18T05:47:41.000Z
clove/components/core/graphics/include/Clove/Graphics/Validation/ValidationQueue.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
4
2020-02-11T15:28:42.000Z
2020-09-07T16:22:58.000Z
#include "Clove/Graphics/Validation/ValidationCommandBuffer.hpp" namespace clove { namespace detail { template<typename QueueType, typename BufferType> void initialiseBuffer(QueueType *queue, BufferType *buffer) { bool const allowBufferReuse{ (queue->getDescriptor().flags & QueueFlags::ReuseBuffers) != 0 }; dynamic_cast<ValidationCommandBuffer *>(buffer)->setAllowBufferReuse(allowBufferReuse); } template<typename SubmissionType> void validateBuffersUsage(SubmissionType const &submission) { for(auto &commandBuffer : submission.commandBuffers) { auto *buffer{ dynamic_cast<ValidationCommandBuffer *>(commandBuffer) }; if(buffer->getCommandBufferUsage() == CommandBufferUsage::OneTimeSubmit && buffer->bufferHasBeenUsed()) { CLOVE_ASSERT_MSG(false, "GraphicsCommandBuffer recorded with CommandBufferUsage::OneTimeSubmit has already been used. Only buffers recorded with CommandBufferUsage::Default can submitted multiples times after being recorded once."); break; } } } template<typename SubmissionType> void markBuffersAsUsed(SubmissionType const &submission) { for(auto &commandBuffer : submission.commandBuffers) { dynamic_cast<ValidationCommandBuffer *>(commandBuffer)->markAsUsed(); } } } //Graphics template<typename BaseQueueType> std::unique_ptr<GhaGraphicsCommandBuffer> ValidationGraphicsQueue<BaseQueueType>::allocateCommandBuffer() { auto commandBuffer{ BaseQueueType::allocateCommandBuffer() }; detail::initialiseBuffer(this, commandBuffer.get()); return commandBuffer; } template<typename BaseQueueType> void ValidationGraphicsQueue<BaseQueueType>::submit(GraphicsSubmitInfo const &submission, GhaFence *signalFence) { detail::validateBuffersUsage(submission); BaseQueueType::submit(submission, signalFence); detail::markBuffersAsUsed(submission); } //Compute template<typename BaseQueueType> std::unique_ptr<GhaComputeCommandBuffer> ValidationComputeQueue<BaseQueueType>::allocateCommandBuffer() { auto commandBuffer{ BaseQueueType::allocateCommandBuffer() }; detail::initialiseBuffer(this, commandBuffer.get()); return commandBuffer; } template<typename BaseQueueType> void ValidationComputeQueue<BaseQueueType>::submit(ComputeSubmitInfo const &submission, GhaFence *signalFence) { detail::validateBuffersUsage(submission); BaseQueueType::submit(submission, signalFence); detail::markBuffersAsUsed(submission); } //Transfer template<typename BaseQueueType> std::unique_ptr<GhaTransferCommandBuffer> ValidationTransferQueue<BaseQueueType>::allocateCommandBuffer() { auto commandBuffer{ BaseQueueType::allocateCommandBuffer() }; detail::initialiseBuffer(this, commandBuffer.get()); return commandBuffer; } template<typename BaseQueueType> void ValidationTransferQueue<BaseQueueType>::submit(TransferSubmitInfo const &submission, GhaFence *signalFence) { detail::validateBuffersUsage(submission); BaseQueueType::submit(submission, signalFence); detail::markBuffersAsUsed(submission); } }
39.195402
252
0.707038
mondoo
3cc017bbd63a7a87c775f8cc3af8be787175083c
1,854
hpp
C++
tket/src/Utils/EigenConfig.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
tket/src/Utils/EigenConfig.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
tket/src/Utils/EigenConfig.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
// Copyright 2019-2021 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once /** * @file * @brief Include this file rather than including the Eigen headers directly */ #include "Utils/Json.hpp" #if defined(__clang__) #pragma GCC diagnostic push #if __has_warning("-Wdeprecated-copy") #pragma GCC diagnostic ignored "-Wdeprecated-copy" #endif #endif #include <Eigen/Dense> #include <Eigen/SparseCore> #include <unsupported/Eigen/KroneckerProduct> #include <unsupported/Eigen/MatrixFunctions> #if defined(__clang__) #pragma GCC diagnostic pop #endif namespace Eigen { template <typename _Scalar, int _Rows, int _Cols> void to_json(nlohmann::json& j, const Matrix<_Scalar, _Rows, _Cols>& matrix) { for (Index i = 0; i < matrix.rows(); ++i) { nlohmann::json row = nlohmann::json::array(); for (Index j = 0; j < matrix.cols(); ++j) { row.push_back(matrix(i, j)); } j.push_back(row); } } template <typename _Scalar, int _Rows, int _Cols> void from_json(const nlohmann::json& j, Matrix<_Scalar, _Rows, _Cols>& matrix) { for (size_t i = 0; i < j.size(); ++i) { const auto& j_row = j.at(i); for (size_t j = 0; j < j_row.size(); ++j) { matrix(i, j) = j_row.at(j).get<typename Matrix<_Scalar, _Rows, _Cols>::Scalar>(); } } } } // namespace Eigen
27.671642
80
0.692017
NewGitter2017
3cc0b245fafc9db219b108d495c5a2fd1d701163
1,690
cpp
C++
mouselistener.cpp
YoungMetroid/Perceptron
25c9914b59af8bde2e53bdfa6b3301b1f4899623
[ "MIT" ]
null
null
null
mouselistener.cpp
YoungMetroid/Perceptron
25c9914b59af8bde2e53bdfa6b3301b1f4899623
[ "MIT" ]
null
null
null
mouselistener.cpp
YoungMetroid/Perceptron
25c9914b59af8bde2e53bdfa6b3301b1f4899623
[ "MIT" ]
null
null
null
#include "mouselistener.h" mouseListener::mouseListener():colorAzul(0),colorRojo(0) { } //type_class is the color RED or BLUE //The temps are the weight for each coordiante and the Bias //which are generated randomly void mouseListener::addObject(int &Xcoordinate, int &Ycoordinate, int type_class) { if(!checkIfExist(Xcoordinate,Ycoordinate)) { if(type_class == 1) colorRojo++; else colorAzul++; std::vector<int> temp; temp.push_back(Xcoordinate-250); temp.push_back((Ycoordinate-250)*-1); temp.push_back(type_class); objects.push_back(temp); } } std::vector<std::vector<int>>mouseListener::getObject() { return objects; } void mouseListener::print() { for(int x = 0; x < objects.size();x++) { for(int y = 0; y < 2;y++) { std::cout << std::setprecision(4); if(y ==1 ) { std::cout << "Y:" << (objects[x][y]-250)*-1 << " "; } else std::cout << "X:" << objects[x][y]-250 << " "; } std::cout << std::endl; } } //Checks if the coordinate has already been taken //ensuring that only one class can only be on one coordinate (x,y) bool mouseListener::checkIfExist(int &Xcoordinate,int&Ycoordinate) { for(int x = 0; x < objects.size();x++) { for(int y = 0; y < 2;y++) { if(objects[x][y] == Xcoordinate and objects[x][y]== Ycoordinate) return true; } } return false; } std::vector<int>mouseListener::getClassesSize() { std::vector<int>temp; temp.push_back(colorAzul); temp.push_back(colorRojo); return temp; }
23.802817
81
0.573964
YoungMetroid
3cc2bf3fce850f480abecf39f67d7e473583e934
11,673
cpp
C++
Photosynthesis(notManaged).cpp
ARS-CSGCL-DT/PhotoSynthesisModule
6493ea851e8c65e43ce0780b0f258a5a87ffb082
[ "Unlicense" ]
7
2016-01-10T07:05:28.000Z
2021-03-09T02:41:06.000Z
Photosynthesis(notManaged).cpp
ARS-CSGCL-DT/PhotoSynthesisModule
6493ea851e8c65e43ce0780b0f258a5a87ffb082
[ "Unlicense" ]
1
2018-02-28T12:46:36.000Z
2018-03-07T06:31:12.000Z
Photosynthesis(notManaged).cpp
ARS-CSGCL-DT/PhotoSynthesisModule
6493ea851e8c65e43ce0780b0f258a5a87ffb082
[ "Unlicense" ]
1
2016-06-16T19:37:35.000Z
2016-06-16T19:37:35.000Z
/*! @file * Defines the entry point for the console application. @author $Author \n */ #include "stdafx.h" #include "gas_exchange.h" #include <iostream> #include <fstream> #include <algorithm> #include <sstream> using namespace std; // uses std::string, a more generic method than CString /*! \namespace photomod \details photomod is the namespace and contains the code needed to run the model. In includes an interface \b _tmain (named by Visual Studio), and \b gasexchange.cpp, the model itself */ using namespace photomod; //Photosynthesis module /*! \b Program _tmain * \page Interface * \par Interface to photosynthesis module * \details This program demonstrates how to call the photosynthesis module * * * \par Use of this interface * Two input files are needed (@b parameters.csv and @b ClimateIn.dat) and one output file is created (@b Results.dat). ClimateIn.dat is the default name, any file can be input when prompted by the program. A detailed description of the input files follows. * -# A comma delimited parameter file containing the parameters for the photosynthesis module, one line for each species (Parameters.csv) * -# An comma delimted environmental file @b (ClimateIn.dat) each line should have these variables (separated by commas): * \li temperature (C) * \li PAR (umol photons m-2 s-1) \li CO2 content (umol mol-1) \li humidity (%) \li wind (m s-1) \li a flag (0,1) to tell the program if constant temperature is used (or let temperature of leaf vary with stomatal conductance). * -# an output file is produced with results @b (Results.dat) each line is written as: * \li PAR (umol photons m-2 s-1) \li Net Photosynthesis (umol CO2 m-2 s-1) \li Gross Photosynthesis \li VPD (kPa) \li LeafTemperature (C) \li BoundaryLayerConductance (mol m-2 s-1) \li Internal CO2 (umol mol-1) \li Respiration (umolCO2 m-2 s-1) \li Transpiration (umol H2O m-2 s-1) \n -# In your calling program, execute the function SetParams first to initialize the calculator for a specific plant species * Then execute the function: \b SetVal(PFD, Temperature, CO2, RelativeHumidity, Wind, Pressure, ConstantTemperature) to pass environmental parameters needed to calculate carbon assimilation and transpiration. This will call the function \b GasEx() which carries out the calculations \n * -# Use the public get functions described in the CGasExchange Class to retrieve the calculated * variables. */ int _tmain(int argc, _TCHAR* argv[]) { /*! \brief these are the variables for the interface */ string DataLine; //!< \b DataLine, holds line of data read from file with climate data string Remark; //!< \b Remark, remark from parameter file char* context = NULL; //!< \b context, pointer needed to use strtok_s function bool ConstantTemperature; //!< \b ConstantTemperature, if set to 1, model does not solve for leaf temperature photomod::CGasExchange::tParms thisParms; //!< \b thisParms, object to hold parameters sent to photosynthesis module const char *pDelim=","; //!< \b pDelim, -pointer to character (delimiter) that separates entries in the parameter file char * pnt; //!< \b pnt, -pointer to the next word to be read from parameter file char CharTest ='A'; //!< \b CharTest -variable to test if there are characters in the line of data (indicates end of data) bool found=false; //!< \b found -Boolean to indicate the species line was found in the parameter file string temp ; //!< \b temp -temporary variable for holding string objects /*! \brief \li these variables hold data sent to model */ double PFD, /*!< \b PFD light umol ppfd m-2 s-1- */ Temperature, /*!< \b Temperature leaf temperature C*/ RelativeHumidity,Wind, CO2, Pressure=100; ifstream ParamFile, DataFile; //!< \b ParamFile, \b DataFile - files to hold parameters and variables for a single run ofstream OutputFile; //!< \b OutputFile holds data output from photosynthesis module //Define a pointer to a new variable as a GasExchange Object photomod::CGasExchange *MyLeafGasEx; //!< \b MyLeafGasEx - define a gas exchange object type // Create a new GasExchange Object MyLeafGasEx= new CGasExchange(); //create a new gas exchange object on the stack //variables to hold results from gas exchange module. double Anet, VPD,Agross,LeafTemperature, Respiration, InternalCO2, StomatalConductance, BoundaryLayerConductance, Transpiration; //assign defaults in case user does not want to enter other information (DataLine is empty) string DataFileName="ClimateIn.dat", OutputFileName="Results.dat"; string Species ="Maize"; //!< \b Species of plant for calculatioins // Get datafile name, and species name if entered by user. cout << "enter name of file with input data and species name separated by commas:" <<endl << "hit Enter with empty string for defaults" <<endl; getline(cin,DataLine); if (!DataLine.empty()) //if empty defaults to string names assigned above { pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); //pnt is a pointer to the last recently found token in the string DataFileName.assign(pnt); // first token is a file name pnt=strtok_s(NULL, pDelim, &context ); //get ready for the next token by getting pointer to recently found token in the string Species.assign(pnt); // next token is species Species.erase(remove(Species.begin(),Species.end(),' '),Species.end()); //remove blanks from species name in case any are present pnt=NULL; //finished with these two } // open file with parameters and data ParamFile.open("parameters.csv", std::ifstream::in); if (!ParamFile) { std::cerr << "Parameter file not found \n"; return 0; } DataFile.open(DataFileName.c_str()); if (!DataFile) { std::cerr << "Data file with input not found \n"; return 0; } FILE * pFile; pFile=fopen((char*)OutputFileName.c_str(),"w"); fprintf(pFile, "PAR ANet AGross VPD Leaf_Temp BoundaryL_Conduc InternalCO2 Respiration StomatalConduct Transpiration\n"); OutputFile.open(OutputFileName.c_str()); std::getline(ParamFile,DataLine); //get header from parameter file // last line of file may be empty or contain numbers, this indicates file is at the end while (!ParamFile.eof() && isalpha(CharTest)) //loops through file reads each line and tests if the correct species is found { getline(ParamFile,DataLine); // get the first line of data CharTest=DataLine.at(0); //check that line contains alphabetical text at beginning pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); // pick off the first word before the token (',') //First read file to find the desired plant species temp.assign(pnt); temp.erase(remove(temp.begin(),temp.end(),' '),temp.end()); // removes spaces from string thisParms.ID=temp; temp.clear(); //Eliminate case issues - convert everything to lower case transform(thisParms.ID.begin(), thisParms.ID.end(),thisParms.ID.begin(), ::tolower); transform(Species.begin(), Species.end(),Species.begin(), ::tolower); //Search for the correct species in file if (thisParms.ID.compare(Species)==0 && !found) //continue to parse string { pnt = strtok_s( NULL,pDelim, &context ); // iterate to clean string of characters already read // This section parses string, each iteration it cleans string of characters already read while(pnt!=NULL ) { // printf( "Tokenized string using * is:: %s\n", pnt ); // for debugging temp.assign(pnt); thisParms.species=temp; temp.clear(); pnt = strtok_s( NULL,pDelim, &context ); temp.assign(pnt); thisParms.Type=temp; temp.clear(); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Vcm25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Jm25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Vpm25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.TPU25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Rd25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Theta=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.EaVc=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Eaj=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Hj=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Sj=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Hv=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.EaVp=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Sv=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Eap=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Ear=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.g0=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.g1=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.stomaRatio=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.LfWidth=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.LfAngFact=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); temp.assign(pnt); thisParms.Remark=temp; temp.clear(); pnt=strtok_s(NULL,pDelim, &context); found=true; } } } // Implementation to interact with photosynthesis model is here CharTest='1'; //initialize CharTest int start=1; bool LineEmpty=false; //Checks if file with environmental data is finished. //output variables //Initialize Gas exchange object by passing species and relavent parameters read earlier MyLeafGasEx->SetParams(&thisParms); // loop to read environmental input data and call object to calculate results while (!LineEmpty) { getline(DataFile, DataLine); if (DataLine.length()==0) LineEmpty=true; else { //CharTest=DataLine.at(0); // check for valid data pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); //token is the delimiter PFD=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); Temperature=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); CO2=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); RelativeHumidity=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); Wind=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); ConstantTemperature=atoi(pnt); // pass relavent environmental variables to gas exchange object and execute module MyLeafGasEx->SetVal(PFD, Temperature, CO2, RelativeHumidity, Wind, Pressure, ConstantTemperature); // Return calculated variables from gas exchange object Anet=MyLeafGasEx->get_ANet(); Agross=MyLeafGasEx->get_AGross(); VPD=MyLeafGasEx->get_VPD(); LeafTemperature=MyLeafGasEx->get_LeafTemperature(); BoundaryLayerConductance=MyLeafGasEx->get_BoundaryLayerConductance(); InternalCO2=MyLeafGasEx->get_Ci(); Respiration=MyLeafGasEx->get_Respiration(); StomatalConductance=MyLeafGasEx->get_StomatalConductance(); Transpiration=MyLeafGasEx->get_Transpiration(); fprintf(pFile,"%8.2f %6.2f %6.2f %8.3f %4.1f %8.3f %4.1f %6.2f %8.3f %8.3f\n", PFD, Anet, Agross, VPD, LeafTemperature, BoundaryLayerConductance,InternalCO2,Respiration, StomatalConductance, Transpiration); } } DataFile.close(); DataFile.close(); fclose(pFile); return 0; }
41.83871
147
0.69014
ARS-CSGCL-DT
3cc62a7c894ff5eeab72751fe113b9a6eb7a751d
858
cpp
C++
examples/md-flexible/parsing/MDFlexParser.cpp
ssauermann/AutoPas
309f9a43840101933b8d06324ea910c780954f61
[ "BSD-2-Clause" ]
null
null
null
examples/md-flexible/parsing/MDFlexParser.cpp
ssauermann/AutoPas
309f9a43840101933b8d06324ea910c780954f61
[ "BSD-2-Clause" ]
null
null
null
examples/md-flexible/parsing/MDFlexParser.cpp
ssauermann/AutoPas
309f9a43840101933b8d06324ea910c780954f61
[ "BSD-2-Clause" ]
null
null
null
/** * @file MDFlexParser.cpp * @author F. Gratl * @date 10/18/19 */ #include "MDFlexParser.h" bool MDFlexParser::parseInput(int argc, char **argv, MDFlexConfig &config) { // we need to copy argv because the call to getOpt in _cliParser.inputFilesPresent reorders it... auto argvCopy = new char *[argc + 1]; for (int i = 0; i < argc; i++) { auto len = std::string(argv[i]).length() + 1; argvCopy[i] = new char[len]; strcpy(argvCopy[i], argv[i]); } argvCopy[argc] = nullptr; CLIParser::inputFilesPresent(argc, argv, config); if (not config.yamlFilename.empty()) { if (not YamlParser::parseYamlFile(config)) { return false; } } auto parseSuccess = CLIParser::parseInput(argc, argvCopy, config); for (int i = 0; i < argc; i++) { delete[] argvCopy[i]; } delete[] argvCopy; return parseSuccess; }
23.833333
99
0.638695
ssauermann
3cc80eee9d476ede270f86cb67ad64312c16b882
25,466
cc
C++
md-parser/src/content.cc
kev0960/ModooCode
aae17e3be86da2f39bf93d7a91364b2a6a348525
[ "Apache-2.0" ]
39
2019-02-26T08:21:06.000Z
2022-03-24T06:38:25.000Z
md-parser/src/content.cc
kev0960/ModooCode
aae17e3be86da2f39bf93d7a91364b2a6a348525
[ "Apache-2.0" ]
9
2019-03-01T05:07:44.000Z
2022-02-21T07:39:11.000Z
md-parser/src/content.cc
kev0960/ModooCode
aae17e3be86da2f39bf93d7a91364b2a6a348525
[ "Apache-2.0" ]
5
2021-02-08T05:52:01.000Z
2022-03-08T06:37:34.000Z
#include "content.h" #include <unistd.h> #include <cstdlib> #include <fstream> #include <functional> #include <limits> #include <memory> #include <thread> #include <unordered_set> #ifdef USE_CHROMA #include "chroma.h" #endif #include "fast_cpp_syntax_highlighter.h" #include "fast_py_syntax_highlighter.h" #include "tex_util.h" #include "util.h" static const std::unordered_set<string> kSpecialCommands = { "sidenote", "sc", "newline", "serif", "htmlonly", "latexonly", "footnote", "esc", "tooltip"}; namespace md_parser { namespace { // Remove empty p tags. (e.g <p> </p>). void RemoveEmptyPTag(string* s) { for (size_t i = 0; i < s->size(); i++) { if (s->at(i) == '<') { if (i + 2 < s->size() && s->substr(i, 3) == "<p>") { size_t p_tag_start = i; i += 3; // Ignore whitespaces (tab and space). while (s->at(i) == ' ' || s->at(i) == '\t') { i++; } if (i + 3 < s->size() && s->substr(i, 4) == "</p>") { s->erase(p_tag_start, (i + 4) - p_tag_start); i = p_tag_start - 1; } } } } } void EscapeHtmlString(string* s) { for (size_t i = 0; i < s->length(); i++) { if (s->at(i) == '<') { s->replace(i, 1, "&lt;"); } else if (s->at(i) == '>') { s->replace(i, 1, "&gt;"); } } } [[maybe_unused]] std::unique_ptr<char[]> cstring_from_string(const string& s) { std::unique_ptr<char[]> c_str{new char[s.size() + 1]}; for (size_t i = 0; i < s.size(); i++) { c_str[i] = s.at(i); } c_str[s.size()] = '\0'; return c_str; } size_t FindNonEscapedChar(const string& content, char c, size_t start) { size_t pos = start; while (pos < content.size()) { pos = content.find(c, pos); if (pos == string::npos) { break; } if (pos == 0 || content[pos - 1] != '\\') { return pos; } pos++; } return std::string::npos; } string UnescapeEscapedString(const string& content) { std::string s; s.reserve(content.size()); for (size_t i = 0; i < content.size(); i++) { if (content[i] == '\\' && i + 1 < content.size()) { s.push_back(content[i + 1]); i++; } else { s.push_back(content[i]); } } return s; } string GetHtmlFragmentText(const string& content, const Fragments& fragment, bool is_str = true) { if (is_str) { return content.substr(fragment.str_start, fragment.str_end - fragment.str_start + 1); } return content.substr(fragment.link_start, fragment.link_end - fragment.link_start + 1); } string GetLatexFragmentText(const string& content, const Fragments& fragment, bool is_str = true, bool no_escape = false) { if (is_str) { if (!no_escape) { return EscapeLatexString(content.substr( fragment.str_start, fragment.str_end - fragment.str_start + 1)); } else { return content.substr(fragment.str_start, fragment.str_end - fragment.str_start + 1); } } return content.substr(fragment.link_start, fragment.link_end - fragment.link_start + 1); } #ifdef USE_CHROMA [[maybe_unused]] string FormatCodeUsingChroma(const string& code, const string& lang, const string& schema) { auto code_ = cstring_from_string(code); auto lang_ = cstring_from_string(lang); auto schema_ = cstring_from_string(schema); char* formatted = FormatCodeWithoutInlineCss(code_.get(), lang_.get(), schema_.get()); string formatted_code = formatted; free(formatted); return formatted_code; } #endif void StripItguruFromLink(string* link) { const string itguru = "http://itguru.tistory.com"; size_t itguru_pos = link->find(itguru); if (itguru_pos == string::npos) { return; } link->replace(itguru_pos, itguru.length(), ""); } bool IsFileExist(const string& filename) { std::ifstream f(filename); return f.good(); } bool CompareToken(const string& content_, int pos, const string& token) { if (pos + token.size() > content_.size()) { return false; } return content_.substr(pos, token.size()) == token; } } // namespace Content::Content(const string& content) : content_(content), already_preprocessed_(false) { return; } void Content::AddContent(const string& s) { content_ += s; } void Content::Preprocess(ParserEnvironment* parser_env) { if (already_preprocessed_) { return; } GenerateFragments(); already_preprocessed_ = true; } void Content::GenerateFragments() { // Priorities in processing content. // Inline Code ( ` ) // Inline Math ( $$ ) // ---------------------------------- // StrikeThrough (~) // Bold (**, __) // Italic (*, _) // Note that when closing, whichever came first must close first. std::unordered_map<string, int> token_start_pos = { {"**", -1}, {"*", -1}, {"__", -1}, {"_", -1}, {"`", -1}, {"$$", -1}, {"~~", -1}}; std::unordered_map<string, Fragments::Types> token_and_type = { {"`", Fragments::Types::INLINE_CODE}, {"$$", Fragments::Types::INLINE_MATH}, {"~~", Fragments::Types::STRIKE_THROUGH}, {"**", Fragments::Types::BOLD}, {"__", Fragments::Types::BOLD}, {"*", Fragments::Types::ITALIC}, {"_", Fragments::Types::ITALIC}}; // When one of following tokens are activated, it ignores anything that // comes after. std::vector<string> high_priorities = {"`", "$$"}; // Following tokens can come play between each other. std::vector<string> low_priorities = {"~~", "**", "__", "*", "_"}; int text_start = -1; // Now iterate through each character in the content and parse it. for (size_t i = 0; i < content_.size(); i++) { string activated_high_priority_token; for (const string& token : high_priorities) { if (token_start_pos.at(token) != -1) { activated_high_priority_token = token; break; } } // When high priority token is already activated, then we do not // proceed to process other token. if (!activated_high_priority_token.empty()) { if (CompareToken(content_, i, activated_high_priority_token)) { fragments_.emplace_back(token_and_type[activated_high_priority_token], token_start_pos[activated_high_priority_token] + activated_high_priority_token.size(), i - 1); token_start_pos[activated_high_priority_token] = -1; i += (activated_high_priority_token.size() - 1); } continue; } bool token_handled = false; for (const string& token : high_priorities) { if (CompareToken(content_, i, token)) { if (text_start != -1) { fragments_.emplace_back(Fragments::Types::TEXT, text_start, i - 1); text_start = -1; } token_start_pos[token] = i; token_handled = true; i += (token.size() - 1); break; } } if (token_handled) { continue; } // Handle links and images. std::vector<std::function<size_t(Content*, const size_t, int*)>> handlers = {&Content::HandleLinks, &Content::HandleImages, &Content::HandleSpecialCommands}; bool handled = false; for (const auto& handler : handlers) { size_t result = handler(this, i, &text_start); if (result != i) { i = result; handled = true; break; } } if (handled) { continue; } // Now try to process low priority tokens. for (const string& token : low_priorities) { if (CompareToken(content_, i, token)) { token_handled = true; int token_start = token_start_pos[token]; if (token_start == -1) { if (text_start != -1) { fragments_.emplace_back(Fragments::Types::TEXT, text_start, i - 1); text_start = -1; } fragments_.emplace_back(token_and_type[token]); token_start_pos[token] = i; i += (token.size() - 1); } else { // There is one edge case we have to care about. // When '**' is found, it is possible that it is actually two // separate '*' and '*'. The only case this is true is // '**' token came before '*' is entered. // E.g **abc*c*** // ==> **abc*c* ** (1) // *abc**c*** // ==> *abc**c** * (2) if (text_start != -1) { fragments_.emplace_back(Fragments::Types::TEXT, text_start, i - 1); text_start = -1; } if (token.size() == 2) { string half_token = token.substr(0, 1); if (token_start < token_start_pos[half_token]) { // In this case we have to recognize token as a half token. // Note that this is the case (1). fragments_.emplace_back(token_and_type[half_token]); token_start_pos[half_token] = -1; i += (half_token.size() - 1); } else { fragments_.emplace_back(token_and_type[token]); token_start_pos[token] = -1; i += (token.size() - 1); } } else { fragments_.emplace_back(token_and_type[token]); token_start_pos[token] = -1; i += (token.size() - 1); } text_start = -1; } break; } } if (token_handled) { continue; } // Otherwise, it is a simple text token. if (text_start == -1) { text_start = i; } } // Handle last chunk of text_start (if exists). if (text_start != -1) { fragments_.emplace_back(Fragments::Types::TEXT, text_start, content_.size() - 1); } } string Content::OutputHtml(ParserEnvironment* parser_env) { bool bold = false; bool italic = false; bool strike_through = false; string html = "<p>"; for (size_t i = 0; i < fragments_.size(); i++) { if (fragments_[i].type == Fragments::Types::BOLD) { if (!bold) { html += "<span class='font-weight-bold'>"; } else { html += "</span>"; } bold = !bold; } else if (fragments_[i].type == Fragments::Types::ITALIC) { if (!italic) { html += "<span class='font-italic'>"; } else { html += "</span>"; } italic = !italic; } else if (fragments_[i].type == Fragments::Types::STRIKE_THROUGH) { if (!strike_through) { html += "<span class='font-strike'>"; } else { html += "</span>"; } strike_through = !strike_through; } else if (fragments_[i].type == Fragments::Types::SIDENOTE) { html += StrCat("</p><aside class='sidenote'>", GetHtmlFragmentText(content_, fragments_[i]), "</aside><p>"); } else if (fragments_[i].type == Fragments::Types::SMALL_CAPS) { html += StrCat("<span class='font-smallcaps'>", GetHtmlFragmentText(content_, fragments_[i]), "</span>"); } else if (fragments_[i].type == Fragments::Types::SERIF) { html += StrCat("<span class='font-serif-italic'>", GetHtmlFragmentText(content_, fragments_[i]), "</span>"); } else if (fragments_[i].type == Fragments::Types::HTML_ONLY) { html += GetHtmlFragmentText(content_, fragments_[i]); } else if (fragments_[i].type == Fragments::Types::ESCAPE) { html += GetHtmlFragmentText(content_, fragments_[i]); } else if (fragments_[i].type == Fragments::Types::FOOTNOTE) { html += StrCat("<sup>", GetHtmlFragmentText(content_, fragments_[i]), "</sup>"); } else if (fragments_[i].type == Fragments::Types::TOOLTIP) { html += StrCat( "<span class='page-tooltip' data-tooltip='", UnescapeEscapedString( GetHtmlFragmentText(content_, fragments_[i], false)), "' data-tooltip-position='bottom'>", UnescapeEscapedString(GetHtmlFragmentText(content_, fragments_[i])), "</span>"); } else if (fragments_[i].type == Fragments::Types::FORCE_NEWLINE) { html += "<br>"; } else if (fragments_[i].type == Fragments::Types::LINK) { string url = GetHtmlFragmentText(content_, fragments_[i], false); StripItguruFromLink(&url); // If the link does not contain "http://", then this is a link that goes // back to our website. string link_text = GetHtmlFragmentText(content_, fragments_[i]); if (url.find("http") == string::npos) { string url = parser_env->GetUrlOfReference(&link_text); EscapeHtmlString(&link_text); if (!url.empty()) { html += StrCat("<a href='", url, "' class='link-code'>", link_text, "</a>"); continue; } } html += StrCat("<a href='", url, "'>", link_text, "</a>"); } else if (fragments_[i].type == Fragments::Types::IMAGE) { string img_src = GetHtmlFragmentText(content_, fragments_[i], false); // (alt) caption= (caption) string alt_and_caption = GetHtmlFragmentText(content_, fragments_[i]); string caption, alt; auto caption_pos = alt_and_caption.find("caption="); if (caption_pos != string::npos) { caption = alt_and_caption.substr(caption_pos + 8); alt = alt_and_caption.substr(caption_pos); } else { alt = alt_and_caption; } // If this image is from old tistory dump, then we have to switch to the // local iamge. if (img_src.find("http://img1.daumcdn.net") != string::npos) { auto id_start = img_src.find("image%2F"); if (id_start == string::npos) { LOG << "Daum Image URL is weird"; } else { id_start += 8; const string image_name = img_src.substr(id_start); std::vector<string> file_ext_candidate = {".png", ".jpg", ".jpeg", ".gif"}; for (const auto& ext : file_ext_candidate) { if (IsFileExist(StrCat("../static/img/", image_name, ext))) { img_src = StrCat("/img/", image_name, ext); break; } } } } // Check webp version exist. If exists, then we use picture tag instead. auto image_name_end = img_src.find_last_of("."); if (image_name_end != string::npos) { const string webp_image_name = img_src.substr(0, image_name_end) + ".webp"; if (IsFileExist("../static" + webp_image_name)) { html += StrCat( R"(</p><figure><picture><source type="image/webp" srcset=")", webp_image_name, R"("><img class="content-img" src=")", img_src, R"(" alt=")", alt, R"("></picture><figcaption>)", caption, R"(</figcaption></figure><p>)"); continue; } } html += StrCat("</p><figure><img class='content-img' src='", img_src, "' alt='", alt, "'><figcaption>", caption, "</figcaption></figure><p>"); } else if (fragments_[i].type == Fragments::Types::CODE) { html += StrCat("</p>", fragments_[i].formatted_code, "<p>"); } else if (fragments_[i].type == Fragments::Types::INLINE_CODE) { string inline_code = GetHtmlFragmentText(content_, fragments_[i]); string ref_url = parser_env->GetUrlOfReference(&inline_code); EscapeHtmlString(&inline_code); if (!ref_url.empty()) { html += StrCat("<a href='", ref_url, "' class='link-code'>", inline_code, "</a>"); } else { html += StrCat("<code class='inline-code'>", inline_code, "</code>"); } } else if (fragments_[i].type == Fragments::Types::INLINE_MATH) { html += StrCat("<span class='math-latex'>$", GetHtmlFragmentText(content_, fragments_[i]), "$</span>"); } else if (fragments_[i].type != Fragments::Types::LATEX_ONLY) { string text = GetHtmlFragmentText(content_, fragments_[i]); EscapeHtmlString(&text); html += text; } } html += "</p>"; RemoveEmptyPTag(&html); return html; } string Content::OutputLatex(ParserEnvironment* parser_env) { bool bold = false; bool italic = false; bool strike_through = false; string latex; for (const auto& fragment : fragments_) { if (fragment.type == Fragments::Types::BOLD) { if (!bold) { latex += "\\textbf{"; } else { latex += "}"; } bold = !bold; } else if (fragment.type == Fragments::Types::ITALIC) { if (!italic) { latex += "\\emph{"; } else { latex += "}"; } italic = !italic; } else if (fragment.type == Fragments::Types::STRIKE_THROUGH) { if (!strike_through) { // \usepackage[normalem]{ulem} latex += "\\sout{"; } else { latex += "}"; } strike_through = !strike_through; } else if (fragment.type == Fragments::Types::SIDENOTE) { latex += StrCat(R"(\footnote{)", GetLatexFragmentText(content_, fragment), "} "); /* latex += StrCat("\n\\begin{sidenotebox}\n", GetLatexFragmentText(content_, fragment), "\n\\end{sidenotebox}\n"); latex += StrCat(" \\marginpar{\\footnotesize ", GetLatexFragmentText(content_, fragment), "}\n"); */ } else if (fragment.type == Fragments::Types::SMALL_CAPS) { latex += StrCat("\\textsc{", GetLatexFragmentText(content_, fragment), "}"); } else if (fragment.type == Fragments::Types::SERIF) { latex += StrCat("\\emph{", GetLatexFragmentText(content_, fragment), "}"); } else if (fragment.type == Fragments::Types::LATEX_ONLY) { latex += GetLatexFragmentText(content_, fragment); } else if (fragment.type == Fragments::Types::ESCAPE) { latex += GetLatexFragmentText(content_, fragment); } else if (fragment.type == Fragments::Types::FORCE_NEWLINE) { latex += "\\newline"; } else if (fragment.type == Fragments::Types::LINK) { // \usepackage{hyperref} string url = GetLatexFragmentText(content_, fragment, false); StripItguruFromLink(&url); // If the link does not contain "http://", then this is a link that goes // back to our website. string link_text = GetLatexFragmentText(content_, fragment); if (url.find("http") == string::npos) { string url = parser_env->GetUrlOfReference(&link_text); if (!url.empty()) { latex += StrCat("\\href{", url, "}{", link_text, "}"); continue; } } latex += StrCat("\\href{", url, "}{", link_text, "}"); } else if (fragment.type == Fragments::Types::IMAGE) { string img_src = GetLatexFragmentText(content_, fragment, false); // (alt) caption= (caption) string alt_and_caption = GetLatexFragmentText(content_, fragment); string caption, alt; auto caption_pos = alt_and_caption.find("caption="); if (caption_pos != string::npos) { caption = alt_and_caption.substr(caption_pos + 8); alt = alt_and_caption.substr(caption_pos); } else { alt = alt_and_caption; } // If this image is from old tistory dump, then we have to switch to the // local iamge. if (img_src.find("http://img1.daumcdn.net") != string::npos) { auto id_start = img_src.find("image%2F"); if (id_start == string::npos) { LOG << "Daum Image URL is weird"; } else { id_start += 8; const string image_name = img_src.substr(id_start); std::vector<string> file_ext_candidate = {".png", ".jpg", ".jpeg", ".gif"}; for (const auto& ext : file_ext_candidate) { if (IsFileExist(StrCat("../static/img/", image_name, ext))) { img_src = StrCat("/img/", image_name, ext); break; } } } } string ext = img_src.substr(img_src.size() - 3); if (ext == "gif" || ext == "svg") { img_src.erase(img_src.size() - 3); img_src.append("png"); } if (caption.empty()) { latex += StrCat( "\n\\begin{figure}[H]\n\\centering\n\\includegraphics[max width=" "0.7\\linewidth]{", img_src, "}\n\\end{figure}\n"); } else { latex += StrCat( "\n\\begin{figure}[H]\n\\centering\n\\includegraphics[max width=" "0.7\\linewidth]{", img_src, "}\n\\caption*{", caption, "}\n\\end{figure}\n"); } } else if (fragment.type == Fragments::Types::INLINE_CODE) { string inline_code = GetLatexFragmentText(content_, fragment); latex += StrCat("\\texttt{", inline_code, "}"); } else if (fragment.type == Fragments::Types::INLINE_MATH) { // Should use unescaped fragment text. latex += StrCat("$", GetHtmlFragmentText(content_, fragment), "$"); } else if (fragment.type != Fragments::Types::HTML_ONLY) { latex += GetLatexFragmentText(content_, fragment); } } return latex; } size_t Content::HandleLinks(const size_t start_pos, int* text_start) { if (content_[start_pos] != '[') { return start_pos; } // Search for the ending ']'. size_t end_bracket = content_.find(']', start_pos); if (end_bracket == string::npos) return start_pos; if (end_bracket + 1 >= content_.size() || content_[end_bracket + 1] != '(') { return start_pos; } size_t link_start = end_bracket + 1; size_t link_end = content_.find(')', link_start); if (link_end == string::npos) return start_pos; if (*text_start != -1) { fragments_.emplace_back(Fragments::Types::TEXT, *text_start, start_pos - 1); *text_start = -1; } fragments_.emplace_back(Fragments::Types::LINK, start_pos + 1, end_bracket - 1, link_start + 1, link_end - 1); return link_end; } size_t Content::HandleSpecialCommands(const size_t start_pos, int* text_start) { if (content_[start_pos] != '\\') { return start_pos; } const auto delimiter_pos = FindNonEscapedChar(content_, '{', start_pos + 1); if (delimiter_pos == string::npos) { return start_pos; } const auto body_end = FindNonEscapedChar(content_, '}', delimiter_pos + 1); if (body_end == string::npos) { return start_pos; } const auto delimiter = content_.substr(start_pos + 1, delimiter_pos - (start_pos + 1)); if (!SetContains(kSpecialCommands, delimiter)) { return start_pos; } if (*text_start != -1) { fragments_.emplace_back(Fragments::Types::TEXT, *text_start, start_pos - 1); *text_start = -1; } if (delimiter == "sidenote") { fragments_.emplace_back(Fragments::Types::SIDENOTE, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "sc") { fragments_.emplace_back(Fragments::Types::SMALL_CAPS, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "newline") { fragments_.emplace_back(Fragments::Types::FORCE_NEWLINE, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "serif") { fragments_.emplace_back(Fragments::Types::SERIF, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "latexonly") { fragments_.emplace_back(Fragments::Types::LATEX_ONLY, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "htmlonly") { fragments_.emplace_back(Fragments::Types::HTML_ONLY, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "footnote") { fragments_.emplace_back(Fragments::Types::FOOTNOTE, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "esc") { fragments_.emplace_back(Fragments::Types::ESCAPE, delimiter_pos + 1, body_end - 1); return body_end; } else if (delimiter == "tooltip") { const auto tooltip_desc_start = FindNonEscapedChar(content_, '{', body_end + 1); if (tooltip_desc_start == string::npos) { return start_pos; } const auto tooltip_desc_end = FindNonEscapedChar(content_, '}', tooltip_desc_start + 1); if (tooltip_desc_end == string::npos) { return start_pos; } fragments_.emplace_back(Fragments::Types::TOOLTIP, delimiter_pos + 1, body_end - 1, tooltip_desc_start + 1, tooltip_desc_end - 1); return tooltip_desc_end; } return start_pos; } size_t Content::HandleImages(const size_t start_pos, int* text_start) { if (content_[start_pos] != '!' || start_pos == content_.size() - 1) { return start_pos; } // Images are in exact same format as the links except for the starting ! // symbol. size_t res = HandleLinks(start_pos + 1, text_start); if (res == start_pos + 1) return start_pos; // Need to change LINK to IMAGE. fragments_.back().type = Fragments::Types::IMAGE; return res; } } // namespace md_parser
34.742156
80
0.568758
kev0960
3cca0f8474b70bc5de851b1988b367f1fcdb0aa5
2,259
cpp
C++
src/third_party/swiftshader/third_party/marl/src/conditionvariable_test.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
20
2019-04-18T07:37:34.000Z
2022-02-02T21:43:47.000Z
src/third_party/swiftshader/third_party/marl/src/conditionvariable_test.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
11
2019-10-21T13:39:41.000Z
2021-11-05T08:11:54.000Z
src/third_party/swiftshader/third_party/marl/src/conditionvariable_test.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
1
2021-12-03T18:11:36.000Z
2021-12-03T18:11:36.000Z
// Copyright 2019 The Marl Authors. // // 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 // // https://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 "marl/conditionvariable.h" #include "marl_test.h" TEST_F(WithoutBoundScheduler, ConditionVariable) { bool trigger[3] = {false, false, false}; bool signal[3] = {false, false, false}; std::mutex mutex; marl::ConditionVariable cv; std::thread thread([&] { for (int i = 0; i < 3; i++) { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock, [&] { return trigger[i]; }); signal[i] = true; cv.notify_one(); } }); ASSERT_FALSE(signal[0]); ASSERT_FALSE(signal[1]); ASSERT_FALSE(signal[2]); for (int i = 0; i < 3; i++) { { std::unique_lock<std::mutex> lock(mutex); trigger[i] = true; cv.notify_one(); cv.wait(lock, [&] { return signal[i]; }); } ASSERT_EQ(signal[0], 0 <= i); ASSERT_EQ(signal[1], 1 <= i); ASSERT_EQ(signal[2], 2 <= i); } thread.join(); } TEST_P(WithBoundScheduler, ConditionVariable) { bool trigger[3] = {false, false, false}; bool signal[3] = {false, false, false}; std::mutex mutex; marl::ConditionVariable cv; std::thread thread([&] { for (int i = 0; i < 3; i++) { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock, [&] { return trigger[i]; }); signal[i] = true; cv.notify_one(); } }); ASSERT_FALSE(signal[0]); ASSERT_FALSE(signal[1]); ASSERT_FALSE(signal[2]); for (int i = 0; i < 3; i++) { { std::unique_lock<std::mutex> lock(mutex); trigger[i] = true; cv.notify_one(); cv.wait(lock, [&] { return signal[i]; }); } ASSERT_EQ(signal[0], 0 <= i); ASSERT_EQ(signal[1], 1 <= i); ASSERT_EQ(signal[2], 2 <= i); } thread.join(); }
25.670455
75
0.611332
rhencke
3ccab0df60fb79547d7b11c8b82c917295c6821a
3,025
cpp
C++
src/detail/helper_detail.cpp
Chrizzly/libunicomm
3aefc02445a5b1e047cc40daaddb7cf9b5082404
[ "BSL-1.0" ]
null
null
null
src/detail/helper_detail.cpp
Chrizzly/libunicomm
3aefc02445a5b1e047cc40daaddb7cf9b5082404
[ "BSL-1.0" ]
null
null
null
src/detail/helper_detail.cpp
Chrizzly/libunicomm
3aefc02445a5b1e047cc40daaddb7cf9b5082404
[ "BSL-1.0" ]
2
2019-03-16T07:07:16.000Z
2020-01-05T11:14:58.000Z
/////////////////////////////////////////////////////////////////////////////// // helper_detail.cpp // // unicomm - Unified Communication protocol C++ library. // // Unified Communication protocol different helper entities. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // 2009, (c) Dmitry Timoshenko. #include <unicomm/detail/helper_detail.hpp> #include <smart/utils.hpp> #include <boost/filesystem.hpp> #include <boost/bind.hpp> #include <stdexcept> #include <functional> #include <locale> #include <sstream> #include <iomanip> #include <limits> #ifdef max # undef max #endif #ifdef min # undef min #endif using std::runtime_error; using std::out_of_range; using std::string; using std::isxdigit; using std::equal_to; using std::greater; using std::stringstream; using std::numeric_limits; using boost::filesystem::exists; using boost::filesystem::path; //----------------------------------------------------------------------------- void unicomm::detail::check_path(const string &s) { if (!exists(path(s))) { throw runtime_error("File or directory doesn't exist [" + s + "]"); } } //----------------------------------------------------------------------------- string& unicomm::detail::normalize_path(string &s) { if (!s.empty()) { const string::value_type c = *(s.end() - 1); if (c != '\\' && c != '/') { s += '/'; } } return s; } //----------------------------------------------------------------------------- string unicomm::detail::normalize_path(const string &s) { string ss = s; return normalize_path(ss); } //----------------------------------------------------------------------------- // declaration for compiler namespace unicomm { namespace detail { string& process_hex_str(string& s); } // namespace unicomm } // namespace detail // fixme: use boost regex to implement this routine string& unicomm::detail::process_hex_str(string& s) { static const char* token = "\\x"; for (size_t pos = s.find(token); pos != string::npos; pos = s.find(token)) { size_t end = pos += 2; while (end < s.size() && isxdigit(s[end])) { ++end; } smart::throw_if<runtime_error>(boost::bind(equal_to<size_t>(), end, pos), "Hexadecimal number should have at least one digit"); BOOST_ASSERT(end > pos && " - End index should be greater start"); stringstream ss(s.substr(pos, end - pos)); size_t char_code = 0; ss >> std::hex >> char_code; smart::throw_if<out_of_range>(boost::bind(greater<size_t>(), char_code, numeric_limits<unsigned char>::max()), "Number too big for char code"); pos -= 2; s.replace(pos, end - pos, 1, static_cast<char>(char_code)); } return s; } //----------------------------------------------------------------------------- string unicomm::detail::process_hex_str(const std::string& s) { string ss = s; return process_hex_str(ss); }
22.574627
79
0.556364
Chrizzly
3ccc0692f3020c0a2b00e9cb6dea4f437472dc46
839
cpp
C++
Learning/Contests/Codechef/Feb/Cook0ff/PuppyAndBoard.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
Learning/Contests/Codechef/Feb/Cook0ff/PuppyAndBoard.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
Learning/Contests/Codechef/Feb/Cook0ff/PuppyAndBoard.cpp
shiva92/Contests
720bb3699f774a6ea1f99e888e0cd784e63130c8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; int state[5][1000010]; int solve(int i, int j) { if (i == 1 && j == 1) return 0; if (state[i][j] != -1) return state[i][j]; state[i][j] = 0; for (int k = 1; k <= 2; k++) if (j - k > 0) state[i][j] |= (1 - solve(i, j - k)); for (int k = 1; k <= 3; k++) if (i - k > 0) state[i][j] |= (1 - solve(i - k, j)); return state[i][j]; } int main() { // #ifndef ONLINE_JUDGE // freopen("/home/shiva/Learning/1.txt", "r", stdin); // freopen("/home/shiva/Learning/2.txt", "w", stdout); // #endif memset(state, -1, sizeof state); for (int i = 1; i <= 4; i++) for (int j = 1; j < 1000010; j++) state[i][j] = solve(i, j); int t, n, m; cin >> t; while (t--) { cin >> n >> m; if (state[(n - 1) % 4 + 1][m]) cout << "Tuzik\n"; else cout << "Vanya\n"; } }
22.078947
55
0.500596
shiva92
3cd0967970a5c88f259566148fb7865aba403e52
8,663
hpp
C++
inst/include/barry/counters-meat.hpp
USCbiostats/geese
0af2ade66a7da42737be613f6b8129347dcae4b2
[ "MIT" ]
8
2020-07-21T01:30:35.000Z
2022-03-09T15:51:14.000Z
inst/include/barry/counters-meat.hpp
USCbiostats/geese
0af2ade66a7da42737be613f6b8129347dcae4b2
[ "MIT" ]
2
2022-01-24T20:51:46.000Z
2022-03-16T23:08:40.000Z
include/barry/counters-meat.hpp
USCbiostats/barry
79c363b9f31d9ee03b3ae199e98c688ffc2abdd0
[ "MIT" ]
null
null
null
#include "counters-bones.hpp" #ifndef BARRY_COUNTERS_MEAT_HPP #define BARRY_COUNTERS_MEAT_HPP 1 #define COUNTER_TYPE() Counter<Array_Type,Data_Type> #define COUNTER_TEMPLATE_ARGS() <typename Array_Type, typename Data_Type> #define COUNTER_TEMPLATE(a,b) \ template COUNTER_TEMPLATE_ARGS() inline a COUNTER_TYPE()::b COUNTER_TEMPLATE(,Counter)( const Counter<Array_Type,Data_Type> & counter_ ) : count_fun(counter_.count_fun), init_fun(counter_.init_fun) { if (counter_.delete_data) { this->data = new Data_Type(*counter_.data); this->delete_data = true; } else { this->data = counter_.data; this->delete_data = false; } this->name = counter_.name; this->desc = counter_.desc; return; } COUNTER_TEMPLATE(,Counter)( Counter<Array_Type,Data_Type> && counter_ ) noexcept : count_fun(std::move(counter_.count_fun)), init_fun(std::move(counter_.init_fun)), data(std::move(counter_.data)), delete_data(std::move(counter_.delete_data)), name(std::move(counter_.name)), desc(std::move(counter_.desc)) { counter_.data = nullptr; counter_.delete_data = false; } ///< Move constructor COUNTER_TEMPLATE(COUNTER_TYPE(),operator=)( const Counter<Array_Type,Data_Type> & counter_ ) { if (this != &counter_) { this->count_fun = counter_.count_fun; this->init_fun = counter_.init_fun; if (counter_.delete_data) { this->data = new Data_Type(*counter_.data); this->delete_data = true; } else { this->data = counter_.data; this->delete_data = false; } this->name = counter_.name; this->desc = counter_.desc; } return *this; } COUNTER_TEMPLATE(COUNTER_TYPE() &,operator=)( Counter<Array_Type,Data_Type> && counter_ ) noexcept { if (this != &counter_) { // Data if (delete_data) delete data; this->data = std::move(counter_.data); this->delete_data = std::move(counter_.delete_data); counter_.data = nullptr; counter_.delete_data = false; // Functions this->count_fun = std::move(counter_.count_fun); this->init_fun = std::move(counter_.init_fun); // Descriptions this->name = std::move(counter_.name); this->desc = std::move(counter_.desc); } return *this; } ///< Move assignment COUNTER_TEMPLATE(double, count)(Array_Type & Array, uint i, uint j) { if (count_fun == nullptr) return 0.0; return count_fun(Array, i, j, data); } COUNTER_TEMPLATE(double, init)(Array_Type & Array, uint i, uint j) { if (init_fun == nullptr) return 0.0; return init_fun(Array, i, j, data); } COUNTER_TEMPLATE(std::string, get_name)() const { return this->name; } COUNTER_TEMPLATE(std::string, get_description)() const { return this->name; } //////////////////////////////////////////////////////////////////////////////// // Counters //////////////////////////////////////////////////////////////////////////////// #define COUNTERS_TYPE() Counters<Array_Type,Data_Type> #define COUNTERS_TEMPLATE_ARGS() <typename Array_Type, typename Data_Type> #define COUNTERS_TEMPLATE(a,b) \ template COUNTERS_TEMPLATE_ARGS() inline a COUNTERS_TYPE()::b COUNTERS_TEMPLATE(, Counters)() { this->data = new std::vector<Counter<Array_Type,Data_Type>*>(0u); this->to_be_deleted = new std::vector< uint >(0u); this->delete_data = true; this->delete_to_be_deleted = true; } COUNTERS_TEMPLATE(COUNTER_TYPE() &, operator[])(uint idx) { return *(data->operator[](idx)); } COUNTERS_TEMPLATE(, Counters)(const Counters<Array_Type,Data_Type> & counter_) : data(new std::vector< Counter<Array_Type,Data_Type>* >(0u)), to_be_deleted(new std::vector< uint >(0u)), delete_data(true), delete_to_be_deleted(true) { // Checking which need to be deleted std::vector< bool > tbd(counter_.size(), false); for (auto& i : *(counter_.to_be_deleted)) tbd[i] = true; // Copy all counters, if a counter is tagged as // to be deleted, then copy the value for (auto i = 0u; i != counter_.size(); ++i) { if (tbd[i]) this->add_counter(*counter_.data->operator[](i)); else this->add_counter(counter_.data->operator[](i)); } return; } COUNTERS_TEMPLATE(, Counters)(Counters<Array_Type,Data_Type> && counters_) noexcept : data(std::move(counters_.data)), to_be_deleted(std::move(counters_.to_be_deleted)), delete_data(std::move(counters_.delete_data)), delete_to_be_deleted(std::move(counters_.delete_to_be_deleted)) { // Taking care of memory counters_.data = nullptr; counters_.to_be_deleted = nullptr; counters_.delete_data = false; counters_.delete_to_be_deleted = false; } COUNTERS_TEMPLATE(COUNTERS_TYPE(), operator=)(const Counters<Array_Type,Data_Type> & counter_) { if (this != &counter_) { // Checking which need to be deleted std::vector< bool > tbd(counter_.size(), false); for (auto i : *(counter_.to_be_deleted)) tbd[i] = true; // Removing the data currently stored in the this->clear(); data = new std::vector< Counter<Array_Type,Data_Type>* >(0u); to_be_deleted = new std::vector< uint >(0u); delete_data = true; delete_to_be_deleted = true; // Copy all counters, if a counter is tagged as // to be deleted, then copy the value for (uint i = 0u; i != counter_.size(); ++i) { if (tbd[i]) this->add_counter(*counter_.data->operator[](i)); else this->add_counter(counter_.data->operator[](i)); } } return *this; } COUNTERS_TEMPLATE(COUNTERS_TYPE() &, operator=)(Counters<Array_Type,Data_Type> && counters_) noexcept { if (this != &counters_) { // Removing the data currently stored in the this->clear(); data = std::move(counters_.data); to_be_deleted = std::move(counters_.to_be_deleted); delete_data = std::move(counters_.delete_data); delete_to_be_deleted = std::move(counters_.delete_to_be_deleted); counters_.data = nullptr; counters_.to_be_deleted = nullptr; counters_.delete_data = false; counters_.delete_to_be_deleted = false; } return *this; } COUNTERS_TEMPLATE(void, add_counter)(Counter<Array_Type, Data_Type> & counter) { to_be_deleted->push_back(data->size()); data->push_back(new Counter<Array_Type, Data_Type>(counter)); return; } COUNTERS_TEMPLATE(void, add_counter)(Counter<Array_Type, Data_Type> * counter) { data->push_back(counter); return; } COUNTERS_TEMPLATE(void, add_counter)( Counter_fun_type<Array_Type,Data_Type> count_fun_, Counter_fun_type<Array_Type,Data_Type> init_fun_, Data_Type * data_, bool delete_data_, std::string name_, std::string desc_ ) { /* We still need to delete the counter since we are using the 'new' operator. * Yet, the actual data may not need to be deleted. */ to_be_deleted->push_back(data->size()); data->push_back(new Counter<Array_Type,Data_Type>( count_fun_, init_fun_, data_, delete_data_, name_, desc_ )); return; } COUNTERS_TEMPLATE(void, clear)() { for (auto& i : (*to_be_deleted)) delete data->operator[](i); if (delete_data) delete data; if (delete_to_be_deleted) delete to_be_deleted; data = nullptr; to_be_deleted = nullptr; return; } COUNTERS_TEMPLATE(std::vector<std::string>, get_names)() const { std::vector< std::string > out(this->size()); for (unsigned int i = 0u; i < out.size(); ++i) out[i] = this->data->at(i)->get_name(); return out; } COUNTERS_TEMPLATE(std::vector<std::string>, get_descriptions)() const { std::vector< std::string > out(this->size()); for (unsigned int i = 0u; i < out.size(); ++i) out[i] = this->data->at(i)->get_description(); return this->name; } #undef COUNTER_TYPE #undef COUNTER_TEMPLATE_ARGS #undef COUNTER_TEMPLATE #undef COUNTERS_TYPE #undef COUNTERS_TEMPLATE_ARGS #undef COUNTERS_TEMPLATE #endif
23.669399
102
0.606603
USCbiostats
3cd1cf2b435b86de97331c58e96ce1f6333d7a67
749
cpp
C++
_small_src_bucket/copy-move_functional.cpp
NesterovMaxim/all_mini_tests
d6837c28e3b6dfc3cfa12794168356dfd4810a0b
[ "MIT" ]
1
2018-02-27T14:29:50.000Z
2018-02-27T14:29:50.000Z
_small_src_bucket/copy-move_functional.cpp
NesterovMaxim/all_mini_tests
d6837c28e3b6dfc3cfa12794168356dfd4810a0b
[ "MIT" ]
null
null
null
_small_src_bucket/copy-move_functional.cpp
NesterovMaxim/all_mini_tests
d6837c28e3b6dfc3cfa12794168356dfd4810a0b
[ "MIT" ]
null
null
null
//clang 3.8.0 #include <iostream> #include <functional> using ft = std::function<void(int)>; void p(const char* m, int i){ std::cout << m << ":" << i << std::endl; } int i; class test{ int j; public: test(){j = ++i; p("ctor", j);} ~test(){p("dtor", j);} test(const test& t){j = t.j*10; p("copy ctor", j);} test(test&& t){j = t.j*100; p("move ctor", j);} void operator()(int i){ std::cout << i << std::endl; } }; int main() { test o; ft f; //f = [&o](int i){o(i);}; f = o; f(1); std::cout << "Hello, world!\n"; return 0; } /* ctor:1 copy ctor:10 move ctor:1000 dtor:10 1 Hello, world! dtor:1000 dtor:1 */
15.285714
56
0.452603
NesterovMaxim
3cd52b7b39dda1a32821c83dc529a9d4426212f1
1,913
cpp
C++
media/labfiles/calculator.cpp
jared-wallace/jared-wallace.com
af58635d18f394906b6a0125eb4573f89546d7d5
[ "WTFPL" ]
null
null
null
media/labfiles/calculator.cpp
jared-wallace/jared-wallace.com
af58635d18f394906b6a0125eb4573f89546d7d5
[ "WTFPL" ]
null
null
null
media/labfiles/calculator.cpp
jared-wallace/jared-wallace.com
af58635d18f394906b6a0125eb4573f89546d7d5
[ "WTFPL" ]
null
null
null
/* *Name: Jared Wallace *Date: 09-05-2014 *Section: 18 * * Answers to questions: * 1) const int NUM = 200; * int x = 0; * cout << "Please enter the value of x"; * cin >> x; * if (x < NUM) * { * cout << "Hooray"; * } * 2) T && F = F * T || F = T * F && F = F * !(T && T) = F * !T && T = F * 3) 3 * awww... * 4 * *This program will function as a simple calculator, only performing one *operation at a time. */ #include <iostream> #include <cstdlib> #include <cmath> // For the pow operation (Not required for this lab) using namespace std; int main() { const int OP_ADD = 0; const int OP_SUB = 1; const int OP_MUL = 2; const int OP_DIV = 3; const int OP_MOD = 4; const int OP_EXP = 5; const int OP_RED = 6; const int OP_WRT = 7; int inst = 0; int data0 = 0; int data1 = 0; int data2 = 0; cout << "Please enter the value for the instruction "; cin >> inst; cout << endl << "\nPlease enter the first operand "; cin >> data1; cout << endl << "\nPlease enter the second operand "; cin >> data2; if (inst == OP_ADD) data0 = data1 + data2; else if (inst == OP_SUB) data0 = data1 - data2; else if (inst == OP_MUL) data0 = data1 * data2; else if (inst == OP_DIV) data0 = data1 / data2; else if (inst == OP_MOD) data0 = data1 % data2; else if (inst == OP_EXP) // Not required for this lab data0 = pow(data1, data2); else { cout << "\nUnable to perform operation."; data0 = -1; } cout << "\nYour calculation is complete."; if (data0 != -1) cout << "\nThe result is " << data0 << endl; else cout << "\nNo result obtained.\n"; return EXIT_SUCCESS; }
22.77381
72
0.503921
jared-wallace
3cd729cf62a781dcee151b67ca80518d7e8f42e9
453
hpp
C++
addons/slingload/script_component.hpp
pterolatypus/sling-load-rigging
06f6b414b30127e60cc2a9440a693c77cbe9d9c3
[ "MIT" ]
1
2020-07-17T01:03:07.000Z
2020-07-17T01:03:07.000Z
addons/slingload/script_component.hpp
pterolatypus/sling-load-rigging
06f6b414b30127e60cc2a9440a693c77cbe9d9c3
[ "MIT" ]
3
2021-03-06T13:07:07.000Z
2021-10-20T19:27:49.000Z
addons/slingload/script_component.hpp
pterolatypus/sling-load-rigging
06f6b414b30127e60cc2a9440a693c77cbe9d9c3
[ "MIT" ]
1
2020-06-24T08:34:59.000Z
2020-06-24T08:34:59.000Z
#define COMPONENT slingload #define COMPONENT_BEAUTIFIED SlingLoad #include "\z\slr\addons\main\script_mod.hpp" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define CBA_DEBUG_SYNCHRONOUS // #define ENABLE_PERFORMANCE_COUNTERS #ifdef DEBUG_ENABLED_SLINGLOAD #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_SLINGLOAD #define DEBUG_SETTINGS DEBUG_SETTINGS_SLINGLOAD #endif #include "\z\slr\addons\main\script_macros.hpp"
23.842105
51
0.816777
pterolatypus
3cd7ea9bdea035b78f83a2f9e1ad1163d4005848
1,167
cpp
C++
GameDownloaderTest/src/SimpleContinueHook.cpp
ProtocolONE/cord.game-downloader
90950019937cd2974801ca2f53ed3b4ecd1d219b
[ "Apache-2.0" ]
1
2019-08-07T06:13:15.000Z
2019-08-07T06:13:15.000Z
GameDownloaderTest/src/SimpleContinueHook.cpp
ProtocolONE/cord.game-downloader
90950019937cd2974801ca2f53ed3b4ecd1d219b
[ "Apache-2.0" ]
null
null
null
GameDownloaderTest/src/SimpleContinueHook.cpp
ProtocolONE/cord.game-downloader
90950019937cd2974801ca2f53ed3b4ecd1d219b
[ "Apache-2.0" ]
null
null
null
#include "SimpleContinueHook.h" #include <GameDownloader/GameDownloadService.h> #include <Core/Service.h> #include <QtCore/QDebug> SimpleContinueHook::SimpleContinueHook(int hookId, QList<int> *preList, QList<int> *postList) : HookBase(QString("hookId_%1").arg(hookId)) , _hookId(hookId) , _preList(preList) , _postList(postList) , _beforeCallCount(0) , _afterCallCount(0) { } SimpleContinueHook::~SimpleContinueHook() { } HookBase::HookResult SimpleContinueHook::beforeDownload(GameDownloadService *, ServiceState *state) { const P1::Core::Service *service = state->service(); this->_beforeCallCount++; this->_preList->append(this->_hookId); qDebug() << "beforeDownload " << (service == 0 ? "service is null" : service->id()); return HookBase::Continue; } HookBase::HookResult SimpleContinueHook::afterDownload(GameDownloadService *, ServiceState *state) { const P1::Core::Service *service = state->service(); this->_afterCallCount++; this->_postList->append(this->_hookId); qDebug() << "afterDownload " << (service == 0 ? "service is null" : service->id()); return HookBase::Continue; }
29.175
100
0.696658
ProtocolONE
3cd834ef1e97d0dcf6b88c2a21f09e29aad650c1
372
cpp
C++
dev/VisualStudio/Simulator/EmbeddedDLL/EmbeddedDLL/MainEntry.cpp
brandonbraun653/RF24NodeDev
e5a9ff1bcd5397640ca553fca4881fb2d17560ef
[ "MIT" ]
null
null
null
dev/VisualStudio/Simulator/EmbeddedDLL/EmbeddedDLL/MainEntry.cpp
brandonbraun653/RF24NodeDev
e5a9ff1bcd5397640ca553fca4881fb2d17560ef
[ "MIT" ]
null
null
null
dev/VisualStudio/Simulator/EmbeddedDLL/EmbeddedDLL/MainEntry.cpp
brandonbraun653/RF24NodeDev
e5a9ff1bcd5397640ca553fca4881fb2d17560ef
[ "MIT" ]
null
null
null
#include <windows.h> BOOL WINAPI DllMain( HINSTANCE hinstDLL, // handle to DLL module DWORD fdwReason, // reason for calling function LPVOID lpReserved ) // reserved { switch (fdwReason) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; }
16.909091
49
0.696237
brandonbraun653
3cdab282c6f7bfcced76427359057666c679d908
1,541
cpp
C++
1.Collisions/EDBase/EDCommon.cpp
Cabrra/Advanced-Algorithms
062c469e575ef18ce22dc5320be3188dbe3b409d
[ "MIT" ]
null
null
null
1.Collisions/EDBase/EDCommon.cpp
Cabrra/Advanced-Algorithms
062c469e575ef18ce22dc5320be3188dbe3b409d
[ "MIT" ]
null
null
null
1.Collisions/EDBase/EDCommon.cpp
Cabrra/Advanced-Algorithms
062c469e575ef18ce22dc5320be3188dbe3b409d
[ "MIT" ]
null
null
null
#include "EDCommon.h" #include "EDDefault.h" // (THIS SHOULD BE THE FIRST FUNCTION YOU COMPLETE. YOUR OTHER FUNCTIONS WILL NOT APPEAR TO WORK PROPERLY WITHOUT IT.) void OrthoNormalInverse( matrix4f &MatrixO, const matrix4f &MatrixA ) { // Replace this call with your own implementation of the Orthnormal Inverse algorithm EDOrthoNormalInverse( MatrixO, MatrixA ); } void MouseLook( matrix4f &mat, float fTime ) { POINT mousePos; GetCursorPos( &mousePos ); SetCursorPos( 400, 300 ); float mouseDiff[2] = { float(400 - mousePos.x), float(mousePos.y - 300) }; // Replace this call with your own implementation of the Mouse-Look algorithm float fCameraRotateRate = 0.002f; EDMouseLook( mat, mouseDiff, fCameraRotateRate ); } void LookAt( matrix4f &mat, const vec3f &target ) { // Replace this call with your own implementation of the Look-At algorithm EDLookAt( mat, target ); } void TurnTo( matrix4f &mat, const vec3f &target, float fTime ) { // Replace this call with your own implementation of the Turn-To algorithm EDTurnTo( mat, target, fTime ); } void HardAttach( matrix4f &AttachMat, const matrix4f &AttachToMat, const vec3f &offset ) { // Replace this call with your own implementation of the Hard-Attach algorithm EDHardAttach( AttachMat, AttachToMat, offset ); } void SoftAttach( matrix4f &AttachMat, const matrix4f &AttachToMat, queue< matrix4f > &Buffer, const vec3f &offset ) { // Replace this call with your own implementation of the Soft-Attach algorithm EDSoftAttach( AttachMat, AttachToMat, offset ); }
33.5
118
0.752758
Cabrra
3cdc6867c40b40c46dc4aec91b5cea9e9d4048dd
340
cpp
C++
Project/src/Device/Device.cpp
svez-net/GFW
b9b455e0576c441cc53f0e8d7d295887afaf4c49
[ "MIT" ]
1
2016-05-11T01:23:20.000Z
2016-05-11T01:23:20.000Z
Project/src/Device/Device.cpp
svez-net/GFW
b9b455e0576c441cc53f0e8d7d295887afaf4c49
[ "MIT" ]
2
2016-05-19T08:37:00.000Z
2016-05-19T08:40:08.000Z
Project/src/Device/Device.cpp
khs2-net/GFW
b9b455e0576c441cc53f0e8d7d295887afaf4c49
[ "MIT" ]
null
null
null
/* using namespace GFW; Device::Device() { } Device::~Device() { } void Device::Begin(String str) { assert(this->device.find(str) == this->device.end()); this->stack.push_back(&this->device[str]); } void Device::End() { assert(this->stack_count,TEXT("Error:DeviceStackCount")); this->stack.pop_back(); if(this->stack.size()){} } */
17
58
0.655882
svez-net
3cdd89c091169a2aa6413844ea2b99ac09abc9dd
528
cpp
C++
4. Recursion/1_count_digit.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
3
2021-02-01T07:56:21.000Z
2021-02-01T11:56:50.000Z
4. Recursion/1_count_digit.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
4. Recursion/1_count_digit.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
// Given an number N count How many digit present in that number /* Example :- Input :- N = 2000 Output :- 4 Input :- N = 12345678 Output :- 8 */ #include <iostream> using namespace std; int countDigit(int n) { if(n==0) return 0 ; int count = 1; n = n/10; return count+countDigit(n); } int main() { int n; cin>>n; int count = countDigit(n); cout<<"The digit present in that number are : "<<count<<endl; } /* Input :- 2000 Output :- The digit present in that number are : 4 */
14.27027
65
0.592803
manishhedau
3cdd9dfce99d7c2bda4e805c6e6b4ca1728e66d2
5,011
hpp
C++
inc/lak/window.hpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
3
2021-07-12T02:32:50.000Z
2022-01-30T03:39:53.000Z
inc/lak/window.hpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
1
2020-11-03T08:57:04.000Z
2020-11-03T09:04:41.000Z
inc/lak/window.hpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
null
null
null
/* Typical usage for an OpenGL program: int main() { lak::core_init(); lak::window window(...); window.init_opengl(...); uint32_t framerate = 60; auto last_counter = lak::performance_counter(); // main loop while(...) { // event handlers // update code // draw code window.swap(); last_counter = lak::yield_frame(last_counter, framerate); } window.close(); lak::core_quit(); } */ #ifndef LAK_WINDOW_HPP #define LAK_WINDOW_HPP #include "lak/platform.hpp" #include "lak/events.hpp" #include "lak/bank_ptr.hpp" #include "lak/image.hpp" #include "lak/memmanip.hpp" #include "lak/string.hpp" #include "lak/surface.hpp" #include "lak/vec.hpp" #include "lak/profile.hpp" namespace lak { enum struct graphics_mode { None = 0, Software = 1, OpenGL = 2, Vulkan = 3 }; struct software_settings { }; struct opengl_settings { bool double_buffered = false; uint8_t depth_size = 24; uint8_t colour_size = 8; uint8_t stencil_size = 8; int major = 3; int minor = 2; }; struct vulkan_settings { }; struct software_context; struct opengl_context; struct vulkan_context; struct window_handle; extern template struct lak::array<lak::window_handle, lak::dynamic_extent>; extern template struct lak::railcar<lak::window_handle>; extern template struct lak::bank<lak::window_handle>; extern template size_t lak::bank<lak::window_handle>::internal_create< lak::window_handle>(lak::window_handle &&); using const_window_handle_ref = const lak::window_handle &; extern template size_t lak::bank<lak::window_handle>::internal_create< lak::const_window_handle_ref>(lak::const_window_handle_ref &&); extern template struct lak::unique_bank_ptr<lak::window_handle>; extern template struct lak::shared_bank_ptr<lak::window_handle>; using window_handle_bank = lak::bank<lak::window_handle>; /* --- create/destroy window --- */ lak::window_handle *create_window(const lak::software_settings &s); lak::window_handle *create_window(const lak::opengl_settings &s); lak::window_handle *create_window(const lak::vulkan_settings &s); bool destroy_window(lak::window_handle *w); /* --- window state --- */ lak::wstring window_title(const lak::window_handle *w); bool set_window_title(lak::window_handle *w, const lak::wstring &s); lak::vec2l_t window_size(const lak::window_handle *w); lak::vec2l_t window_drawable_size(const lak::window_handle *w); bool set_window_size(lak::window_handle *w, lak::vec2l_t s); bool set_window_cursor_pos(const lak::window_handle *w, lak::vec2l_t p); // :TODO: // bool set_window_drawable_size(lak::window_handle *w, lak::vec2l_t s); /* --- graphics control --- */ lak::graphics_mode window_graphics_mode(const lak::window_handle *w); // :TODO: This probably belongs in the platform header. bool set_opengl_swap_interval(const lak::opengl_context &c, int interval); bool swap_window(lak::window_handle *w); // Yield this thread until the target framerate is achieved. uint64_t yield_frame(const uint64_t last_counter, const uint32_t target_framerate); /* --- window wrapper class --- */ struct window { private: lak::unique_bank_ptr<lak::window_handle> _handle; window(lak::unique_bank_ptr<lak::window_handle> &&handle); public: inline window(window &&w) : _handle(lak::move(w._handle)) {} static lak::result<window> make(const lak::software_settings &s); static lak::result<window> make(const lak::opengl_settings &s); static lak::result<window> make(const lak::vulkan_settings &s); ~window(); inline lak::window_handle *handle() { return _handle.get(); } inline const lak::window_handle *handle() const { return _handle.get(); } inline lak::graphics_mode graphics() const { return lak::window_graphics_mode(handle()); } inline lak::wstring title() const { return lak::window_title(handle()); } inline window &set_title(const lak::wstring &title) { ASSERT(lak::set_window_title(handle(), title)); return *this; } inline lak::vec2l_t size() const { return lak::window_size(handle()); } inline lak::vec2l_t drawable_size() const { return lak::window_drawable_size(handle()); } inline window &set_size(lak::vec2l_t size) { ASSERT(lak::set_window_size(handle(), size)); return *this; } inline const window &set_cursor_pos(lak::vec2l_t pos) const { ASSERT(lak::set_window_cursor_pos(handle(), pos)); return *this; } inline bool swap() { return lak::swap_window(handle()); } }; } #include <ostream> [[maybe_unused]] inline std::ostream &operator<<(std::ostream &strm, lak::graphics_mode mode) { switch (mode) { case lak::graphics_mode::OpenGL: strm << "OpenGL"; break; case lak::graphics_mode::Software: strm << "Software"; break; case lak::graphics_mode::Vulkan: strm << "Vulkan"; break; default: strm << "None"; break; } return strm; } #endif
23.199074
76
0.694073
LAK132
3cdf61068e32d08c7e615fb4ff00c6b9f144e8c6
3,596
cpp
C++
Practicafinal/conecta4_v2.1/src/arboltablero_test.cpp
guillegalor/PracticasED
5e4fbc830c79741997734003add6eae1ee736d61
[ "MIT" ]
null
null
null
Practicafinal/conecta4_v2.1/src/arboltablero_test.cpp
guillegalor/PracticasED
5e4fbc830c79741997734003add6eae1ee736d61
[ "MIT" ]
null
null
null
Practicafinal/conecta4_v2.1/src/arboltablero_test.cpp
guillegalor/PracticasED
5e4fbc830c79741997734003add6eae1ee736d61
[ "MIT" ]
null
null
null
#include <iostream> #include "ArbolGeneral.hpp" #include "tablero.hpp" #include <string> using namespace std; int main(int argc, char *argv[]){ //Tablero vacío 6x7 Tablero tablero(6, 7); //Manualmente se insertan algunos movimientos: tablero.colocarFicha(3); //Jugador 1 inserta ficha en columna 3 tablero.cambiarTurno(); tablero.colocarFicha(1); //Jugador 2 inserta ficha en columna 1 tablero.cambiarTurno(); tablero.colocarFicha(3); //Jugador 1 inserta ficha en columna 3. tablero.cambiarTurno(); //Se muestra el tablero cout << "Tablero obtenido tras tres movimientos: \n"<<tablero; //A partir de la situación actual del tablero, montamos un árbol para estudiar algunas posibilidades. // Éste es el árbol que queremos montar: // tablero // | // |---------------| // tablero1 tablero2 // | // tablero3 //Árbol 'partida', con 'tablero' como nodo raíz ArbolGeneral<Tablero> partida(tablero); //Estudio opciones a partir de tablero: Jugador 2 coloca ficha en columna 1. (tablero1) Tablero tablero1(tablero); //tablero queda sin modificar tablero1.colocarFicha(1); ArbolGeneral<Tablero> arbol1 (tablero1); //creo árbol con un nodo (tablero1) //Otra opción: Jugador 2 coloca ficha en columna 2. (tablero2) Tablero tablero2(tablero); //tablero queda sin modificar tablero2.colocarFicha(2); ArbolGeneral<Tablero> arbol2(tablero2); //creo árbol con un nodo // Sobre la última opción, ahora contemplo la posibilidad de que // Jugador 1 coloque ficha también en columna 2. tablero2.cambiarTurno(); //modifico tablero2 (esta modificación sería tablero3) tablero2.colocarFicha(2); ArbolGeneral<Tablero> arbol3 (tablero2); //creo árbol con un nodo arbol2.insertar_hijomasizquierda(arbol2.raiz(), arbol3); //añado este árbol como hijo de arbol2 // Inserto arbol1 y arbol2 como hijos de partida. // arbol1 es el hijo más a la izquierda y arbol2 es hermano a la derecha de arbol1 // Forma de hacerlo A: inserto varios hijomasizquierda en el orden inverso al deseado // partida.insertar_hijomasizquierda(partida.raiz(), arbol2); // partida.insertar_hijomasizquierda(partida.raiz(), arbol1); //hijomasizquierda desplaza al anterior a la derecha // Forma de hacerlo B: inserto un hijomasizquierda y hermanoderecha partida.insertar_hijomasizquierda(partida.raiz(), arbol1); //inserto un hijomasizquierda partida.insertar_hermanoderecha(partida.hijomasizquierda(partida.raiz()), arbol2); //le inserto un hermanoderecha // Recorremos en preorden para comprobar el arbol 'partida' resultante cout << "\nÁrbol en preorden: \n"<<endl; partida.recorrer_preorden(); // Podamos el hijomasizquierda y recorremos en preorden: ArbolGeneral<Tablero> rama_podada; partida.podar_hermanoderecha(partida.hijomasizquierda(partida.raiz()), rama_podada); cout << "\nRecorrido preorden después de podar arbol2: \n"<<endl; partida.recorrer_preorden(); cout << "\nRecorrido preorden de la rama podada: \n"<<endl; rama_podada.recorrer_preorden(); // Probamos ArbolGeneral::asignar_subarbol. Asignamos a partida la rama_podada: partida.asignar_subarbol(rama_podada, rama_podada.raiz()); cout << "\nRecorrido preorden después de asignar a la raiz la rama_podada: \n"<<endl; partida.recorrer_preorden(); cout << "\nRecorrido postorden después de asignar a la raiz la rama_podada: \n"<<endl; partida.recorrer_postorden(); return 0; }
39.086957
116
0.708287
guillegalor
3ce0829d8f8f47766099d258659642dea1740943
386
cpp
C++
pointimposters/NdfImposters/NdfImposterLibraryTests/selectionV.cpp
reinago/sndfs
0d152e6bf4f63d1468c8e91915a4ff970c978882
[ "MIT" ]
null
null
null
pointimposters/NdfImposters/NdfImposterLibraryTests/selectionV.cpp
reinago/sndfs
0d152e6bf4f63d1468c8e91915a4ff970c978882
[ "MIT" ]
null
null
null
pointimposters/NdfImposters/NdfImposterLibraryTests/selectionV.cpp
reinago/sndfs
0d152e6bf4f63d1468c8e91915a4ff970c978882
[ "MIT" ]
1
2021-11-19T15:30:43.000Z
2021-11-19T15:30:43.000Z
#version 420 in vec2 Position; out vec2 texCoords; void main() { gl_Position = vec4(Position.xy, 0.0f ,1.0f); gl_Position.x /=(.5f* 1280.0f); //gl_Position.x = gl_Position.x; gl_Position.y /= (.5f*720.0f); gl_Position.x -= 1f; gl_Position.y -= 1f; gl_Position.y *= -1.0f; texCoords = vec2(1.0f-Position.x/1280.0f,Position.y/720.0f); //(gl_Position.xy + 1.0f) * 0.5f; }
18.380952
95
0.645078
reinago
c9e51f5a7aa832ad06068b200e6ab69b67498f85
3,694
cpp
C++
Engine/Source/Programs/UnrealFrontend/Private/Commands/LaunchFromProfileCommand.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Programs/UnrealFrontend/Private/Commands/LaunchFromProfileCommand.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Programs/UnrealFrontend/Private/Commands/LaunchFromProfileCommand.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "LaunchFromProfileCommand.h" #include "DesktopPlatformModule.h" #include "ILauncherProfile.h" #include "ILauncherProfileManager.h" #include "ILauncherTask.h" #include "ILauncherWorker.h" #include "ILauncher.h" #include "ILauncherServicesModule.h" #include "ITargetDeviceServicesModule.h" #include "UserInterfaceCommand.h" #include "Misc/CommandLine.h" #include "Misc/OutputDeviceRedirector.h" DEFINE_LOG_CATEGORY_STATIC(LogUFECommands, All, All); void FLaunchFromProfileCommand::Run(const FString& Params) { // Get the name of the profile from the command line. FString ProfileName; FParse::Value(FCommandLine::Get(), TEXT("-PROFILENAME="), ProfileName); if (ProfileName.IsEmpty()) { UE_LOG(LogUFECommands, Warning, TEXT("Profile name was found. Please use '-PROFILENAME=' in your command line.")); return; } // Loading the launcher services module to get the needed profile. ILauncherServicesModule& LauncherServicesModule = FModuleManager::LoadModuleChecked<ILauncherServicesModule>(TEXT("LauncherServices")); ILauncherProfileManagerRef ProfileManager = LauncherServicesModule.GetProfileManager(); ILauncherProfilePtr Profile = ProfileManager->FindProfile(ProfileName); // Loading the Device Proxy Manager to get the needed Device Manager. ITargetDeviceServicesModule& DeviceServiceModule = FModuleManager::LoadModuleChecked<ITargetDeviceServicesModule>(TEXT("TargetDeviceServices")); TSharedRef<ITargetDeviceProxyManager> DeviceProxyManager = DeviceServiceModule.GetDeviceProxyManager(); UE_LOG(LogUFECommands, Display, TEXT("Begin the process of launching a project using the provided profile.")); ILauncherRef LauncherRef = LauncherServicesModule.CreateLauncher(); ILauncherWorkerPtr LauncherWorkerPtr = LauncherRef->Launch(DeviceProxyManager, Profile.ToSharedRef()); // This will allow us to pipe the launcher messages into the command window. LauncherWorkerPtr.Get()->OnOutputReceived().AddStatic(&FLaunchFromProfileCommand::MessageReceived); // Allows us to exit this command once the launcher worker has completed or is canceled LauncherWorkerPtr.Get()->OnCompleted().AddRaw(this, &FLaunchFromProfileCommand::LaunchCompleted); LauncherWorkerPtr.Get()->OnCanceled().AddRaw(this, &FLaunchFromProfileCommand::LaunchCanceled); TArray<ILauncherTaskPtr> TaskList; int32 NumOfTasks = LauncherWorkerPtr->GetTasks(TaskList); UE_LOG(LogUFECommands, Display, TEXT("There are '%i' tasks to be completed."), NumOfTasks); // Holds the current element in the TaskList array. int32 TaskIndex = 0; // Holds the name of the current tasked. FString TriggeredTask; bTestRunning = true; while (bTestRunning) { if (TaskIndex >= NumOfTasks) continue; ILauncherTaskPtr CurrentTask = TaskList[TaskIndex]; // Log the current task, but only once per run. if (CurrentTask->GetStatus() == ELauncherTaskStatus::Busy) { if (CurrentTask->GetDesc() == TriggeredTask) continue; TriggeredTask = *CurrentTask->GetDesc(); UE_LOG(LogUFECommands, Display, TEXT("Current Task is %s"), *TriggeredTask); TaskIndex++; } } } void FLaunchFromProfileCommand::MessageReceived(const FString& InMessage) { GLog->Logf(ELogVerbosity::Log, TEXT("%s"), *InMessage); } void FLaunchFromProfileCommand::LaunchCompleted(bool Outcome, double ExecutionTime, int32 ReturnCode) { UE_LOG(LogUFECommands, Log, TEXT("Profile launch command %s."), Outcome ? TEXT("is SUCCESSFUL") : TEXT("has FAILED")); bTestRunning = false; } void FLaunchFromProfileCommand::LaunchCanceled(double ExecutionTime) { UE_LOG(LogUFECommands, Log, TEXT("Profile launch command was canceled.")); bTestRunning = false; }
41.044444
145
0.784245
windystrife
c9e61369099bda6417da15f6a84daefcfe9aca44
1,358
cpp
C++
.history/001_GFG/Data-Structures-And-Algorithms-Self-Paced/008_Hashing/Practice/007_IMP_Intersection of two arrays_20210617172337.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
.history/001_GFG/Data-Structures-And-Algorithms-Self-Paced/008_Hashing/Practice/007_IMP_Intersection of two arrays_20210617172337.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
.history/001_GFG/Data-Structures-And-Algorithms-Self-Paced/008_Hashing/Practice/007_IMP_Intersection of two arrays_20210617172337.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
Given two arrays a[] and b[] respectively of size n and m, the task is to print the count of elements in the intersection (or common elements) of the two arrays. For this question, the intersection of two arrays can be defined as the set containing distinct common elements between the two arrays. Example 1: Input: n = 5, m = 3 a[] = {89, 24, 75, 11, 23} b[] = {89, 2, 4} Output: 1 Explanation: 89 is the only element in the intersection of two arrays. class Solution{ public: //Function to return the count of the number of elements in //the intersection of two arrays. int NumberofElementsInIntersection (int a[], int b[], int n, int m ) { // Your code goes here unordered_map<int,int> mp; for(int i=0;i<n;i++) { mp[a[i]]++; if(mp[a[i]]>1) mp[a[i]]--; } for(int i=0;i<m;i++) { // Insert only if there is element present from last array. //Else this could lead to error because one array can also contain one ele more than one time if(mp[b[i]]==1) mp[b[i]]++; } int count=0; for(auto ele: mp) { if(ele.second>1) count++; } return count; } }; Correct Answer.Correct Answer Execution Time:0.81
25.622642
161
0.566274
Sahil1515
c9e67ff488fd2921f511eba619e1a4e8310097f5
48,897
cc
C++
src/imreg_sift/imreg_sift.cc
kaloyan13/imcomp
4f9ed3134e835f329716a6364c046e42d2d28b61
[ "BSD-2-Clause" ]
null
null
null
src/imreg_sift/imreg_sift.cc
kaloyan13/imcomp
4f9ed3134e835f329716a6364c046e42d2d28b61
[ "BSD-2-Clause" ]
null
null
null
src/imreg_sift/imreg_sift.cc
kaloyan13/imcomp
4f9ed3134e835f329716a6364c046e42d2d28b61
[ "BSD-2-Clause" ]
null
null
null
/* Register an image pair based on SIFT features Author: Abhishek Dutta <adutta@robots.ox.ac.uk> Date: 3 Jan. 2018 some code borrowed from: vlfeat-0.9.20/src/sift.c */ #include "imreg_sift/imreg_sift.h" // normalize input points such that their centroid is the coordinate origin (0, 0) // and their average distance from the origin is sqrt(2). // pts is 3 x n matrix void imreg_sift::get_norm_matrix(const MatrixXd& pts, Matrix<double,3,3>& T) { Vector3d mu = pts.rowwise().mean(); MatrixXd norm_pts = (pts).colwise() - mu; VectorXd x2 = norm_pts.row(0).array().pow(2); VectorXd y2 = norm_pts.row(1).array().pow(2); VectorXd dist = (x2 + y2).array().sqrt(); double scale = sqrt(2) / dist.array().mean(); T(0,0) = scale; T(0,1) = 0; T(0,2) = -scale * mu(0); T(1,0) = 0; T(1,1) = scale; T(1,2) = -scale * mu(1); T(2,0) = 0; T(2,1) = 0; T(2,2) = 1; } // Implementation of Direct Linear Transform (DLT) algorithm as described in pg. 91 // Multiple View Geometry in Computer Vision, Richard Hartley and Andrew Zisserman, 2nd Edition // assumption: X and Y are point correspondences. Four 2D points. (4 X 3 in homogenous coordinates) // X and Y : n x 3 matrix // H : 3x3 matrix void imreg_sift::dlt(const MatrixXd& X, const MatrixXd& Y, Matrix<double,3,3>& H) { size_t n = X.rows(); MatrixXd A(2*n, 9); A.setZero(); for(size_t i=0; i<n; ++i) { A.row(2*i).block(0,3,1,3) = -Y(i,2) * X.row(i); A.row(2*i).block(0,6,1,3) = Y(i,1) * X.row(i); A.row(2*i + 1).block(0,0,1,3) = Y(i,2) * X.row(i); A.row(2*i + 1).block(0,6,1,3) = -Y(i,0) * X.row(i); } JacobiSVD<MatrixXd> svd(A, ComputeFullV); // Caution: the last column of V are reshaped into 3x3 matrix as shown in Pg. 89 // of Hartley and Zisserman (2nd Edition) // svd.matrixV().col(8).array().resize(3,3) is not correct! H << svd.matrixV()(0,8), svd.matrixV()(1,8), svd.matrixV()(2,8), svd.matrixV()(3,8), svd.matrixV()(4,8), svd.matrixV()(5,8), 0, 0, svd.matrixV()(8,8); // affine transform // svd.matrixV()(6,8), svd.matrixV()(7,8), svd.matrixV()(8,8); // projective transform } void imreg_sift::estimate_transform(const MatrixXd& X, const MatrixXd& Y, string& transform, Matrix<double,3,3>& T) { if (transform == "identity") { T << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0; } if (transform == "translation" || transform == "rigid" || transform == "similarity") { // ignore homogenous representation Matrix<double,4,2> X_, Y_; X_ = X.block<4,2>(0,0); Y_ = Y.block<4,2>(0,0); // example values to test with spot the difference demo image. // should give identity rotation // X_ << -1.1684, -1.34154, // -1.3568, -1.28858, // -1.08083,-1.0768, // -1.47721,-1.02969; // Y_ << -1.15706, -1.33154, // -1.35822,-1.28466, // -1.08694, -1.07509, // -1.48525, -1.02964; size_t m = X_.cols(); size_t n = X_.rows(); Matrix<double,2,4> Xt_, Yt_; Xt_ = X_.transpose(); Yt_ = Y_.transpose(); // subtract mean from points VectorXd X_mu = Xt_.rowwise().mean(); VectorXd Y_mu = Yt_.rowwise().mean(); Xt_.colwise() -= X_mu; Yt_.colwise() -= Y_mu; MatrixXd X_norm = Xt_.transpose(); MatrixXd Y_norm = Yt_.transpose(); // compute matrix A first (3 X 3 rotation matrix) MatrixXd A = (1.0 / n) * (Y_norm.transpose() * X_norm); // rotation matrix to compute Matrix<double,2,2> R; Matrix<double,2,2> d = Matrix<double,2,2>::Identity(); // do SVD of A JacobiSVD<MatrixXd> svd_u(A, ComputeFullU); Matrix<double,2,2> U = svd_u.matrixU(); U(0,0) = -1.0 * U(0,0); U(1,0) = -1.0 * U(1,0); JacobiSVD<MatrixXd> svd_v(A, ComputeFullV); Matrix<double,2,2> V = svd_v.matrixV(); V(0,0) = -1.0 * V(0,0); V(1,0) = -1.0 * V(1,0); if (svd_u.rank() == 0) { cout << "SVD leads to 0 rank!" << endl; return; } if (svd_u.rank() == (m - 1)) { if ( (U.determinant() * V.determinant() ) > 0) { R = U * V; } else { double s = d(1,1); d(1,1) = -1; R = U * d * V; d(1,1) = s; } } else { R = U * d * V; } double scale = 1.0; // compute scale if its similarity transform if (transform == "similarity") { double s_dot_d = svd_u.singularValues().dot(d.diagonal()); double x_norm_var = X_norm.transpose().cwiseAbs2().rowwise().mean().sum(); scale = (1.0 / x_norm_var) * (svd_u.singularValues().dot(d.diagonal())); } // apply scale to rotation and translation Vector2d t = Y_mu - (scale * (R * X_mu)); R = R * scale; if (transform == "translation") { // apply identity rotation T << 1, 0, t(0), 0, 1, t(1), 0, 0, 1; } else { T << R(0,0), R(0,1), t(0), R(1,0), R(1,1), t(1), 0, 0, 1.0; } } if (transform == "affine") { // estimate affine transform using DLT algorithm dlt(X, Y, T); } // cout << "Final T value is: " << endl; // cout << T << endl; } void imreg_sift::compute_photo_transform(Magick::Image img_one, Magick::Image img_two, Magick::Image& transformed_img) { int w = img_two.rows(); int h = img_two.columns(); int ransac_iters = 10; float error_threshold = 0.05; int num_pts = min(400, min(w,h)); int score = 0; int max_score = 0; std::vector<int> x_pts, y_pts; std::vector<int> inlier_x_pts, inlier_y_pts; std::vector<int> best_inlier_x_pts, best_inlier_y_pts; // initialize random number generator to randomly sample pixels from images random_device rand_device; mt19937 generator(rand_device()); uniform_int_distribution<int> x_dist(0, w); uniform_int_distribution<int> y_dist(0, h); Magick::Color pix = img_one.pixelColor(10,10); for (int r = 0; r < ransac_iters; r++) { x_pts.clear(); y_pts.clear(); inlier_x_pts.clear(); inlier_y_pts.clear(); // pick random x and y points for (int i = 0; i < num_pts; i++) { x_pts.push_back(x_dist(generator)); y_pts.push_back(y_dist(generator)); } // select intensities at the random points Eigen::VectorXd img_one_red(num_pts), img_two_red(num_pts); Eigen::VectorXd img_one_green(num_pts), img_two_green(num_pts); Eigen::VectorXd img_one_blue(num_pts), img_two_blue(num_pts); for (int i = 0; i < num_pts; i++) { Magick::ColorRGB img_one_px(img_one.pixelColor(x_pts[i], y_pts[i])); img_one_blue[i] = img_one_px.blue(); img_one_red[i] = img_one_px.red(); img_one_green[i] = img_one_px.green(); // cout << img_one_red[i] << " " << img_one_green[i] << " " << img_one_blue[i] << endl; Magick::ColorRGB img_two_px(img_two.pixelColor(x_pts[i], y_pts[i])); img_two_blue[i] = img_two_px.blue(); img_two_red[i] = img_two_px.red(); img_two_green[i] = img_two_px.green(); } // estimate photometric transform Matrix3d A = Matrix3d::Identity(); Vector3d b; VectorXd a_b; solve_lse(img_one_red, img_two_red, a_b); A(0,0) = a_b(0); b(0) = a_b(1); solve_lse(img_one_green, img_two_green, a_b); A(1,1) = a_b(0); b(1) = a_b(1); solve_lse(img_one_blue, img_two_blue, a_b); A(2,2) = a_b(0); b(2) = a_b(1); MatrixXd B = b.transpose().replicate(num_pts, 1); // cout << "Computed A amd B are: " << endl; // cout << A << endl; // cout << B << endl; MatrixXd iter_img_one = MatrixXd::Ones(num_pts, 3); MatrixXd iter_img_two = MatrixXd::Ones(num_pts, 3); iter_img_one.col(0) << img_one_red; iter_img_one.col(1) << img_one_green; iter_img_one.col(2) << img_one_blue; iter_img_two.col(0) << img_two_red; iter_img_two.col(1) << img_two_green; iter_img_two.col(2) << img_two_blue; // compute image one from estimate MatrixXd computed_img_one = (iter_img_two * A) + B; VectorXd errors = (iter_img_one - computed_img_one).cwiseAbs2().rowwise().sum().cwiseSqrt(); for(int k = 0; k < errors.size(); k++) { // cout << errors(k) << endl; if (errors(k) < error_threshold) { inlier_x_pts.push_back(x_pts[k]); inlier_y_pts.push_back(y_pts[k]); } } score = inlier_x_pts.size(); if (score > max_score) { best_inlier_x_pts.clear(); best_inlier_y_pts.clear(); for (int j=0; j < inlier_x_pts.size(); j++) { best_inlier_x_pts.push_back(inlier_x_pts[j]); best_inlier_y_pts.push_back(inlier_y_pts[j]); } } max_score = best_inlier_x_pts.size(); } // end of ransac loop // cout << "best inliers are: " << endl; // cout << best_inlier_x_pts.size() << endl; if (max_score < 2) { cout << "Less than 2 points in best inliers. Returning!" << endl; return; } // select intensities at the best inlier points int best_num_pts = best_inlier_x_pts.size(); Eigen::VectorXd img_one_red(best_num_pts), img_two_red(best_num_pts); Eigen::VectorXd img_one_green(best_num_pts), img_two_green(best_num_pts); Eigen::VectorXd img_one_blue(best_num_pts), img_two_blue(best_num_pts); img_one.modifyImage(); img_two.modifyImage(); transformed_img.modifyImage(); for (int i = 0; i < best_num_pts; i++) { Magick::ColorRGB img_one_px(img_one.pixelColor(best_inlier_x_pts[i], best_inlier_y_pts[i])); img_one_blue[i] = img_one_px.blue(); img_one_green[i] = img_one_px.green(); img_one_red[i] = img_one_px.red(); Magick::ColorRGB img_two_px(img_two.pixelColor(best_inlier_x_pts[i], best_inlier_y_pts[i])); img_two_blue[i] = img_two_px.blue(); img_two_green[i] = img_two_px.green(); img_two_red[i] = img_two_px.red(); } // estimate photometric transform Matrix3d A = Matrix3d::Identity(); Vector3d b; VectorXd a_b; solve_lse(img_one_red, img_two_red, a_b); A(0,0) = a_b(0); b(0) = a_b(1); solve_lse(img_one_green, img_two_green, a_b); A(1,1) = a_b(0); b(1) = a_b(1); solve_lse(img_one_blue, img_two_blue, a_b); A(2,2) = a_b(0); b(2) = a_b(1); MatrixXd B = b.transpose().replicate(num_pts, 1); // cout << "Final A and B values are: " << endl; // cout << A << endl; // cout << B << endl; for(unsigned int ii = 0; ii < transformed_img.rows(); ii++) { for(unsigned int jj = 0; jj < transformed_img.columns(); jj++) { Magick::ColorRGB img_two_pixel(img_two.pixelColor(jj, ii)); // apply the computed transform double r = (img_two_pixel.red() * A(0,0)) + B(0,0); double g = (img_two_pixel.green() * A(1,1)) + B(0,1); double b = (img_two_pixel.blue() * A(2,2)) + B(0,2); img_two_pixel.red(r); img_two_pixel.green(g); img_two_pixel.blue(b); transformed_img.pixelColor(jj,ii,img_two_pixel); } } // cout << "done with photometric transform!" << endl; // transformed_img.write("/home/shrinivasan/Desktop/res_test.jpg"); return; } void imreg_sift::solve_lse(Eigen::VectorXd x, Eigen::VectorXd y, VectorXd& a_and_b) { MatrixXd S = MatrixXd::Ones(y.size(), 2); double tolerance = 1e-4; S.col(0) << y; JacobiSVD<MatrixXd> svd(S, ComputeThinU | ComputeThinV); MatrixXd singular_values = svd.singularValues(); MatrixXd singular_values_inv(S.rows(), S.cols()); singular_values_inv.setZero(); for (unsigned int i = 0; i < singular_values.rows(); ++i) { if (singular_values(i) > tolerance) { singular_values_inv(i, i) = 1. / singular_values(i); } else { singular_values_inv(i, i) = 0.; } } a_and_b = (svd.matrixU() * singular_values_inv * svd.matrixV().transpose()).transpose() * x; } double imreg_sift::clamp(double v, double min, double max) { if( v > min ) { if( v < max ) { return v; } else { return max; } } else { return min; } } void imreg_sift::compute_sift_features(const Magick::Image& img, vector<VlSiftKeypoint>& keypoint_list, vector< vector<vl_uint8> >& descriptor_list, bool verbose) { vl_bool err = VL_ERR_OK ; // algorithm parameters based on vlfeat-0.9.20/toolbox/sift/vl_sift.c int O = - 1 ; int S = 3 ; int o_min = 0 ; double edge_thresh = -1 ; double peak_thresh = -1 ; double norm_thresh = -1 ; double magnif = -1 ; double window_size = -1 ; int ndescriptors = 0; vl_sift_pix *fdata = 0 ; vl_size q ; int i ; vl_bool first ; double *ikeys = 0 ; int nikeys = 0, ikeys_size = 0 ; // move image data to fdata for processing by vl_sift // @todo: optimize and avoid this overhead fdata = (vl_sift_pix *) malloc( img.rows() * img.columns() * sizeof(vl_sift_pix) ) ; if( fdata == NULL ) { cout << "\nfailed to allocated memory for vl_sift_pix array" << flush; return; } size_t flat_index = 0; for( unsigned int i=0; i<img.rows(); ++i ) { for( unsigned int j=0; j<img.columns(); ++j ) { Magick::ColorGray c = img.pixelColor( j, i ); fdata[flat_index] = c.shade(); ++flat_index; } } // create filter VlSiftFilt *filt = 0 ; filt = vl_sift_new (img.columns(), img.rows(), O, S, o_min) ; if (peak_thresh >= 0) vl_sift_set_peak_thresh (filt, peak_thresh) ; if (edge_thresh >= 0) vl_sift_set_edge_thresh (filt, edge_thresh) ; if (norm_thresh >= 0) vl_sift_set_norm_thresh (filt, norm_thresh) ; if (magnif >= 0) vl_sift_set_magnif (filt, magnif) ; if (window_size >= 0) vl_sift_set_window_size (filt, window_size) ; if (!filt) { cout << "\nCould not create SIFT filter." << flush; goto done ; } /* ............................................................... * Process each octave * ............................................................ */ i = 0 ; first = 1 ; descriptor_list.clear(); keypoint_list.clear(); while (1) { VlSiftKeypoint const *keys = 0 ; int nkeys ; /* calculate the GSS for the next octave .................... */ if (first) { first = 0 ; err = vl_sift_process_first_octave (filt, fdata) ; } else { err = vl_sift_process_next_octave (filt) ; } if (err) { err = VL_ERR_OK ; break ; } /* run detector ............................................. */ vl_sift_detect(filt) ; keys = vl_sift_get_keypoints(filt) ; nkeys = vl_sift_get_nkeypoints(filt) ; i = 0 ; /* for each keypoint ........................................ */ for (; i < nkeys ; ++i) { double angles [4] ; int nangles ; VlSiftKeypoint const *k ; /* obtain keypoint orientations ........................... */ k = keys + i ; VlSiftKeypoint key_data = *k; nangles = vl_sift_calc_keypoint_orientations(filt, angles, k) ; vl_uint8 d[128]; // added by @adutta /* for each orientation ................................... */ for (q = 0 ; q < (unsigned) nangles ; ++q) { vl_sift_pix descr[128]; /* compute descriptor (if necessary) */ vl_sift_calc_keypoint_descriptor(filt, descr, k, angles[q]) ; vector<vl_uint8> descriptor(128); int j; for( j=0; j<128; ++j ) { float value = 512.0 * descr[j]; value = ( value < 255.0F ) ? value : 255.0F; descriptor[j] = (vl_uint8) value; d[j] = (vl_uint8) value; } descriptor_list.push_back(descriptor); ++ndescriptors; keypoint_list.push_back(key_data); // add corresponding keypoint } } } done : /* release filter */ if (filt) { vl_sift_delete (filt) ; filt = 0 ; } /* release image data */ if (fdata) { free (fdata) ; fdata = 0 ; } } void imreg_sift::get_putative_matches(vector< vector<vl_uint8> >& descriptor_list1, vector< vector<vl_uint8> >& descriptor_list2, std::vector< std::pair<uint32_t,uint32_t> >& putative_matches, float threshold) { size_t n1 = descriptor_list1.size(); size_t n2 = descriptor_list2.size(); putative_matches.clear(); for( uint32_t i=0; i<n1; i++ ) { unsigned int dist_best1 = numeric_limits<unsigned int>::max(); unsigned int dist_best2 = numeric_limits<unsigned int>::max(); uint32_t dist_best1_index = -1; for( uint32_t j=0; j<n2; j++ ) { unsigned int dist = 0; for( int d=0; d<128; d++ ) { int del = descriptor_list1[i][d] - descriptor_list2[j][d]; dist += del*del; if (dist >= dist_best2) { break; } } // find the nearest and second nearest point in descriptor_list2 if( dist < dist_best1 ) { dist_best2 = dist_best1; dist_best1 = dist; dist_best1_index = j; } else { if( dist < dist_best2 ) { dist_best2 = dist; } } } // use Lowe's 2nd nearest neighbour test float d1 = threshold * (float) dist_best1; if( (d1 < (float) dist_best2) && dist_best1_index != -1 ) { putative_matches.push_back( std::make_pair(i, dist_best1_index) ); } } } void imreg_sift::get_diff_image(Magick::Image& im1, Magick::Image& im2, Magick::Image& cdiff) { Magick::Image im1_gray = im1; Magick::Image im2_gray = im2; im1_gray.type(Magick::GrayscaleType); im2_gray.type(Magick::GrayscaleType); // difference between im1 and im2 is red Channel // difference between im2 and im1 is blue channel // green channel is then just the gray scale image Magick::Image diff_gray(im1_gray); diff_gray.composite(im1_gray, 0, 0, Magick::AtopCompositeOp); diff_gray.composite(im2_gray, 0, 0, Magick::AtopCompositeOp); cdiff.composite(diff_gray, 0, 0, Magick::CopyGreenCompositeOp); cdiff.composite(im1_gray, 0, 0, Magick::CopyRedCompositeOp); cdiff.composite(im2_gray, 0, 0, Magick::CopyBlueCompositeOp); } bool imreg_sift::cache_img_with_fid(boost::filesystem::path upload_dir, string fid, imcomp_cache* cache) { // compute sift features for the selected file boost::filesystem::path fn = upload_dir / ( fid + ".jpg"); Magick::Image im; im.read( fn.string() ); im.type(Magick::TrueColorType); // cache the image features vector<VlSiftKeypoint> keypoints; vector< vector<vl_uint8> > descriptors; bool is_cached = cache->get(fid, keypoints, descriptors); if ( !is_cached ) { compute_sift_features(im, keypoints, descriptors, false); cache->put(fid, keypoints, descriptors); cout << "\n Successfully cached fid: " << fid << "features! " << flush; cout << "\n first keypoint is: " << keypoints.at(1).x << " " << keypoints.at(1).y << flush; } return true; } void imreg_sift::ransac_dlt(const char im1_fn[], const char im2_fn[], double xl, double xu, double yl, double yu, MatrixXd& Hopt, size_t& fp_match_count, const char im1_crop_fn[], const char im2_crop_fn[], const char im2_tx_fn[], const char diff_image_fn[], const char overlap_image_fn[], bool& success, std::string& message, imcomp_cache * cache, std::string& transform, bool is_photometric) { try { high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); success = false; message = ""; string im1_file_name(im1_fn); string im2_file_name(im2_fn); string base_filename1 = im1_file_name.substr(im1_file_name.find_last_of("/\\") + 1); std::string::size_type const p1(base_filename1.find_last_of('.')); base_filename1 = base_filename1.substr(0, p1); string base_filename2 = im2_file_name.substr(im2_file_name.find_last_of("/\\") + 1); std::string::size_type const p2(base_filename2.find_last_of('.')); base_filename2 = base_filename2.substr(0, p2); Magick::Image im1; im1.read( im1_fn ); Magick::Image im2; im2.read( im2_fn ); // to ensure that image pixel values are 8bit RGB im1.type(Magick::TrueColorType); im2.type(Magick::TrueColorType); // the photometric transformed image Magick::Image im2_pt(im2.size(), "black"); im2_pt.type(Magick::TrueColorType); if (is_photometric) { compute_photo_transform(im1, im2, im2_pt); } Magick::Image im1_g = im1; im1_g.crop( Magick::Geometry(xu-xl, yu-yl, xl, yl) ); Magick::Image im2_g = im2; // use the photometric transformed image for geometric transform estimation // Magick::Image im2_g = im2_pt; vector<VlSiftKeypoint> keypoint_list1, keypoint_list2; vector< vector<vl_uint8> > descriptor_list1, descriptor_list2; high_resolution_clock::time_point before_sift = std::chrono::high_resolution_clock::now(); //cout << "time before sift computation: " << (duration_cast<duration<double>>(before_sift - start)).count() << endl; // check cache before computing features // TODO: Enable when we have a proper implementation of caching mechanism. // Disabled for now. // bool is_im1_cached = cache->get(base_filename1, keypoint_list1, descriptor_list1); // if (is_im1_cached) { // cout << "using cached data for fid: " << base_filename1 << endl; // } // if (!is_im1_cached) { // // images are converted to gray scale before processing // compute_sift_features(im1_g, keypoint_list1, descriptor_list1, false); // // cache for future use // cache->put(base_filename1, keypoint_list1, descriptor_list1); // cout << "successfully cached fid: " << base_filename1 << endl; // } // cout << "cached first keypoint is: " << keypoint_list1.at(1).x << " " << keypoint_list1.at(1).y << endl; // // bool is_im2_cached = cache->get(base_filename2, keypoint_list2, descriptor_list2); // if (is_im2_cached) { // cout << "using cached data for fid: " << base_filename2 << endl; // } // if (!is_im2_cached) { // // images are converted to gray scale before processing // compute_sift_features(im2_g, keypoint_list2, descriptor_list2, false); // // cache for future use // cache->put(base_filename2, keypoint_list2, descriptor_list2); // cout << "successfully cached fid: " << base_filename2 << endl; // } // cout << "second keypoint is: " << keypoint_list2.at(1).x << " " << keypoint_list2.at(1).y << endl; // compute SIFT features without caching compute_sift_features(im1_g, keypoint_list1, descriptor_list1, false); compute_sift_features(im2_g, keypoint_list2, descriptor_list2, false); // use Lowe's 2nd nn test to find putative matches float threshold = 1.5f; std::vector< std::pair<uint32_t, uint32_t> > putative_matches; get_putative_matches(descriptor_list1, descriptor_list2, putative_matches, threshold); size_t n_match = putative_matches.size(); fp_match_count = n_match; // cout << "Putative matches (using Lowe's 2nd NN test) = " << n_match << endl; // high_resolution_clock::time_point after_putative_match = std::chrono::high_resolution_clock::now(); // cout << "time after putative match computation: " << (duration_cast<duration<double>>(after_putative_match - after_second_sift)).count() << endl; if( n_match < 9 ) { message = "Number of feature points that match are very low"; return; } // Normalize points so that centroid lies at origin and mean distance to // original points in sqrt(2) MatrixXd im1_match_kp(3, n_match); MatrixXd im2_match_kp(3, n_match); for( size_t i=0; i<n_match; ++i) { VlSiftKeypoint kp1 = keypoint_list1.at( putative_matches[i].first ); VlSiftKeypoint kp2 = keypoint_list2.at( putative_matches[i].second ); im1_match_kp(0, i) = kp1.x; im1_match_kp(1, i) = kp1.y; im1_match_kp(2, i) = 1.0; im2_match_kp(0, i) = kp2.x; im2_match_kp(1, i) = kp2.y; im2_match_kp(2, i) = 1.0; } Matrix<double,3,3> im1_match_kp_tform, im2_match_kp_tform; get_norm_matrix(im1_match_kp, im1_match_kp_tform); get_norm_matrix(im2_match_kp, im2_match_kp_tform); MatrixXd im2_match_kp_tform_inv = im2_match_kp_tform.inverse(); MatrixXd im1_match_norm = im1_match_kp_tform * im1_match_kp; MatrixXd im2_match_norm = im2_match_kp_tform * im2_match_kp; //cout << "im1_match_kp_tform=" << im1_match_kp_tform << endl; //cout << "im2_match_kp_tform=" << im2_match_kp_tform << endl; // memory cleanup as these are not required anymore im1_match_kp.resize(0,0); im2_match_kp.resize(0,0); // initialize random number generator to randomly sample putative_matches random_device rand_device; mt19937 generator(rand_device()); uniform_int_distribution<> dist(0, n_match-1); // estimate homography using RANSAC size_t max_score = 0; Matrix<double,3,3> Hi; vector<unsigned int> best_inliers_index; // see Hartley and Zisserman p.119 // in the original image 2 domain, error = sqrt(5.99) * 1 ~ 3 (for SD of 1 pixel error) // in the normalized image 2 domain, we have to transform this 3 pixel to normalized coordinates double geom_err_threshold_norm = im2_match_kp_tform(0,0) * 3; size_t RANSAC_ITER_COUNT = (size_t) ((double) n_match * 0.6); for( unsigned int iter=0; iter<RANSAC_ITER_COUNT; iter++ ) { // cout << "==========================[ iter=" << iter << " ]==============================" << endl; // randomly select 4 matches from putative_matches int kp_id1 = dist(generator); int kp_id2 = dist(generator); int kp_id3 = dist(generator); int kp_id4 = dist(generator); //cout << "Random entries from putative_matches: " << kp_id1 << "," << kp_id2 << "," << kp_id3 << "," << kp_id4 << endl; MatrixXd X(4,3); X.row(0) = im1_match_norm.col(kp_id1).transpose(); X.row(1) = im1_match_norm.col(kp_id2).transpose(); X.row(2) = im1_match_norm.col(kp_id3).transpose(); X.row(3) = im1_match_norm.col(kp_id4).transpose(); MatrixXd Y(4,3); Y.row(0) = im2_match_norm.col(kp_id1).transpose(); Y.row(1) = im2_match_norm.col(kp_id2).transpose(); Y.row(2) = im2_match_norm.col(kp_id3).transpose(); Y.row(3) = im2_match_norm.col(kp_id4).transpose(); // dlt(X, Y, Hi); estimate_transform(X, Y, transform, Hi); size_t score = 0; vector<unsigned int> inliers_index; inliers_index.reserve(n_match); MatrixXd im1tx_norm = Hi * im1_match_norm; // 3 x n im1tx_norm.row(0) = im1tx_norm.row(0).array() / im1tx_norm.row(2).array(); im1tx_norm.row(1) = im1tx_norm.row(1).array() / im1tx_norm.row(2).array(); MatrixXd del(2,n_match); del.row(0) = im1tx_norm.row(0) - im2_match_norm.row(0); del.row(1) = im1tx_norm.row(1) - im2_match_norm.row(1); del = del.array().pow(2); VectorXd error = del.row(0) + del.row(1); error = error.array().sqrt(); for( size_t k = 0; k < n_match; k++ ) { if(error(k) < geom_err_threshold_norm) { score++; inliers_index.push_back(k); } } // cout << "iter " << iter << " of " << RANSAC_ITER_COUNT << " : score=" << score << ", max_score=" << max_score << ", total_matches=" << putative_matches.size() << endl; if( score > max_score ) { max_score = score; best_inliers_index.swap(inliers_index); } } // end RANSAC_ITER_COUNT loop // high_resolution_clock::time_point after_ransac = std::chrono::high_resolution_clock::now(); // cout << "after ransac is: " << (duration_cast<duration<double>>(after_ransac - after_putative_match)).count() << endl; if(transform != "identity" && max_score < 3 ) { message = "Failed to find a suitable transformation"; return; } // Recompute homography using all the inliers // This does not improve the registration // cout << "re-computing homography using inliers" << endl; size_t n_inliers = best_inliers_index.size(); MatrixXd X(n_inliers,3); MatrixXd Y(n_inliers,3); for( size_t i=0; i<n_inliers; ++i ) { X.row(i) = im1_match_norm.col( best_inliers_index.at(i) ).transpose(); Y.row(i) = im2_match_norm.col( best_inliers_index.at(i) ).transpose(); } Matrix<double, 3, 3> Hopt_norm, H; // dlt(X, Y, Hopt_norm); //cout << "estimateing transform: " << transform << endl; estimate_transform(X, Y, transform, Hopt_norm); // see Hartley and Zisserman p.109 H = im2_match_kp_tform_inv * Hopt_norm * im1_match_kp_tform; H = H / H(2,2); // Hopt is the reference variable passed to this method Hopt = H; // im1 crop Magick::Image im1_crop(im1); Magick::Geometry cropRect1(xu-xl, yu-yl, xl, yl); im1_crop.crop( cropRect1 ); im1_crop.write( im1_crop_fn ); Magick::Image im2_crop(im2); im2_crop.crop( cropRect1 ); im2_crop.write( im2_crop_fn ); // ---------------------------------------------------------------- // apply Homography to im2 in order to visualize it along with im1. // ---------------------------------------------------------------- Matrix<double, 3, 3> Hinv = H.inverse(); // if we are doing photometric, use photometric transformed image // else just the image 2. Magick::Image im2t_crop; if (is_photometric) { im2t_crop = im2_pt; } else { im2t_crop = im2; } // some simple affine tralsformations for testing: // Magick::DrawableAffine affine(1.0, 1.0, 0, 0, 0.0, 0.0); // Magick::DrawableAffine hinv_affine(1,1,.3,0,0,0); // simple shearing // Magick::DrawableAffine hinv_affine(1,-1,0,0,0,0); // flip // Magick::DrawableAffine hinv_affine(1,0.5,0,0,0,0); // scale // set rotation as per Hinv Magick::DrawableAffine hinv_affine(Hinv(0,0), Hinv(1,1), Hinv(1,0), Hinv(0,1), 0, 0); // set translation and resizing using viewport function. // See: http://www.imagemagick.org/discourse-server/viewtopic.php?f=27&t=33029#p157520. // As we need to render the image on a webpage canvas, we need to resize the // width and height of im2. Then offset in x and y direction based on the translation // computed by Homography (H and Hinv matrices). string op_w_h_and_offsets = std::to_string(xu-xl) + "x" + std::to_string(yu-yl) + "-" + to_string((int) Hinv(0,2)) + "-" + to_string((int) Hinv(1,2)); im2t_crop.artifact("distort:viewport", op_w_h_and_offsets); im2t_crop.affineTransform(hinv_affine); //cout << "done applying Affine Transform" << endl; // save result im2t_crop.write(im2_tx_fn); // TODO: fix the javascript so that we don't use overlap image as im2t!! im2t_crop.write(overlap_image_fn); // high_resolution_clock::time_point before_diff = std::chrono::high_resolution_clock::now(); // cout << "before diff image comp is: " << (duration_cast<duration<double>>(before_diff - after_ransac)).count() << flush; // difference image Magick::Image cdiff(im1_crop); get_diff_image(im1_crop, im2t_crop, cdiff); cdiff.write(diff_image_fn); // high_resolution_clock::time_point after_diff = std::chrono::high_resolution_clock::now(); // cout << "after diff image comp is: " << (duration_cast<duration<double>>(after_diff - before_diff)).count() << flush; success = true; message = ""; } catch( std::exception &e ) { success = false; std::ostringstream ss; ss << "Exception occured: [" << e.what() << "]"; std::cout << ss.str() << std::endl; message = ss.str(); } } /// /// Robust matching and Thin Plate Spline based image registration /// /// Robust matching based on: /// Tran, Q.H., Chin, T.J., Carneiro, G., Brown, M.S. and Suter, D., 2012, October. In defence of RANSAC for outlier rejection in deformable registration. ECCV. /// /// Thin plate spline registration based on: /// Bookstein, F.L., 1989. Principal warps: Thin-plate splines and the decomposition of deformations. IEEE TPAMI. /// void imreg_sift::robust_ransac_tps(const char im1_fn[], const char im2_fn[], double xl, double xu, double yl, double yu, MatrixXd& Hopt, size_t& fp_match_count, const char im1_crop_fn[], const char im2_crop_fn[], const char im2_tx_fn[], const char diff_image_fn[], const char overlap_image_fn[], bool& success, std::string& message, imcomp_cache * cache, bool is_photometric) { try { auto start = std::chrono::high_resolution_clock::now(); success = false; message = ""; Magick::Image im1; im1.read( im1_fn ); Magick::Image im2; im2.read( im2_fn ); string im1_file_name(im1_fn); string im2_file_name(im2_fn); string base_filename1 = im1_file_name.substr(im1_file_name.find_last_of("/\\") + 1); std::string::size_type const p1(base_filename1.find_last_of('.')); base_filename1 = base_filename1.substr(0, p1); string base_filename2 = im2_file_name.substr(im2_file_name.find_last_of("/\\") + 1); std::string::size_type const p2(base_filename2.find_last_of('.')); base_filename2 = base_filename2.substr(0, p2); // to ensure that image pixel values are 8bit RGB im1.type(Magick::TrueColorType); im2.type(Magick::TrueColorType); // the photometric transformed image Magick::Image im2_pt(im2.size(), "black"); im2_pt.type(Magick::TrueColorType); if (is_photometric) { compute_photo_transform(im1, im2, im2_pt); } Magick::Image im1_g = im1; im1_g.crop(Magick::Geometry(xu-xl, yu-yl, xl, yl)); Magick::Image im2_g = im2; vector<VlSiftKeypoint> keypoint_list1, keypoint_list2; vector< vector<vl_uint8> > descriptor_list1, descriptor_list2; // check cache before computing features // TODO: Enable when we have a proper implementation of caching. // Disabled for now. // bool is_im1_cached = cache->get(base_filename1, keypoint_list1, descriptor_list1); // if (is_im1_cached) { // cout << "using cached data for fid: " << base_filename1 << endl; // } // if (!is_im1_cached) { // // images are converted to gray scale before processing // compute_sift_features(im1_g, keypoint_list1, descriptor_list1, false); // // cache for future use // cache->put(base_filename1, keypoint_list1, descriptor_list1); // cout << "successfully cached fid: " << base_filename1 << endl; // } // cout << "cached first keypoint is: " << keypoint_list1.at(1).x << " " << keypoint_list1.at(1).y << endl; // bool is_im2_cached = cache->get(base_filename2, keypoint_list2, descriptor_list2); // if (is_im2_cached) { // cout << "using cached data for fid: " << base_filename2 << endl; // } // if (!is_im2_cached) { // // images are converted to gray scale before processing // compute_sift_features(im2_g, keypoint_list2, descriptor_list2, false); // // cache for future use // cache->put(base_filename2, keypoint_list2, descriptor_list2); // cout << "successfully cached fid: " << base_filename2 << endl; // } // cout << "second keypoint is: " << keypoint_list2.at(1).x << " " << keypoint_list2.at(1).y << endl; // Compute SIFT features without caching. compute_sift_features(im1_g, keypoint_list1, descriptor_list1); compute_sift_features(im2_g, keypoint_list2, descriptor_list2); // use Lowe's 2nd nn test to find putative matches float threshold = 1.5f; std::vector< std::pair<uint32_t, uint32_t> > putative_matches; get_putative_matches(descriptor_list1, descriptor_list2, putative_matches, threshold); size_t n_lowe_match = putative_matches.size(); //cout << "Putative matches (using Lowe's 2nd NN test) = " << putative_matches.size() << endl; if( n_lowe_match < 9 ) { fp_match_count = n_lowe_match; message = "Number of feature points that match are very low"; return; } // Normalize points so that centroid lies at origin and mean distance to // original points in sqrt(2) //cout << "Creating matrix of size 3x" << n_lowe_match << " ..." << endl; MatrixXd pts1(3, n_lowe_match); MatrixXd pts2(3, n_lowe_match); //cout << "Creating point set matched using lowe ..." << endl; for( size_t i=0; i<n_lowe_match; ++i) { VlSiftKeypoint kp1 = keypoint_list1.at( putative_matches[i].first ); VlSiftKeypoint kp2 = keypoint_list2.at( putative_matches[i].second ); pts1(0, i) = kp1.x; pts1(1, i) = kp1.y; pts1(2, i) = 1.0; pts2(0, i) = kp2.x; pts2(1, i) = kp2.y; pts2(2, i) = 1.0; } //cout << "Normalizing points ..." << endl; Matrix3d pts1_tform; get_norm_matrix(pts1, pts1_tform); //cout << "Normalizing matrix (T) = " << pts1_tform << endl; MatrixXd pts1_norm = pts1_tform * pts1; MatrixXd pts2_norm = pts1_tform * pts2; // form a matrix containing match pair (x,y) <-> (x',y') as follows // [x y x' y'; ...] MatrixXd S_all(4, n_lowe_match); S_all.row(0) = pts1_norm.row(0); S_all.row(1) = pts1_norm.row(1); S_all.row(2) = pts2_norm.row(0); S_all.row(3) = pts2_norm.row(1); // initialize random number generator to randomly sample putative_matches mt19937 generator(9973); uniform_int_distribution<> dist(0, n_lowe_match-1); MatrixXd S(4,3), hatS(4,3); double residual; vector<size_t> best_robust_match_idx; // @todo: tune this threshold for better generalization double robust_ransac_threshold = 0.09; size_t RANSAC_ITER_COUNT = (size_t) ((double) n_lowe_match * 0.6); //cout << "RANSAC_ITER_COUNT = " << RANSAC_ITER_COUNT << endl; for( int i=0; i<RANSAC_ITER_COUNT; ++i ) { S.col(0) = S_all.col( dist(generator) ); // randomly select a match from S_all S.col(1) = S_all.col( dist(generator) ); S.col(2) = S_all.col( dist(generator) ); Vector4d muS = S.rowwise().mean(); hatS = S.colwise() - muS; JacobiSVD<MatrixXd> svd(hatS, ComputeFullU); MatrixXd As = svd.matrixU().block(0, 0, svd.matrixU().rows(), 2); MatrixXd dx = S_all.colwise() - muS; MatrixXd del = dx - (As * As.transpose() * dx); vector<size_t> robust_match_idx; robust_match_idx.clear(); for( int j=0; j<del.cols(); ++j ) { residual = sqrt( del(0,j)*del(0,j) + del(1,j)*del(1,j) + del(2,j)*del(2,j) + del(3,j)*del(3,j) ); if ( residual < robust_ransac_threshold ) { robust_match_idx.push_back(j); } } //cout << i << ": robust_match_idx=" << robust_match_idx.size() << endl; if ( robust_match_idx.size() > best_robust_match_idx.size() ) { best_robust_match_idx.clear(); best_robust_match_idx.swap(robust_match_idx); //cout << "[MIN]" << endl; } } // end RANSAC_ITER_COUNT loop fp_match_count = best_robust_match_idx.size(); if ( fp_match_count < 3 ) { message = "Very low number of robust matching feature points"; return; } //cout << "robust match pairs = " << fp_match_count << endl; // bin each correspondence pair into cells dividing the original image into KxK cells // a single point in each cell ensures that no two control points are very close unsigned int POINTS_PER_CELL = 1; unsigned int n_cell_w, n_cell_h; if( im1.rows() > 500 ) { n_cell_h = 9; } else { n_cell_h = 5; } unsigned int ch = (unsigned int) (im1.rows() / n_cell_h); if( im1.columns() > 500 ) { n_cell_w = 9; } else { n_cell_w = 5; } unsigned int cw = (unsigned int) (im1.columns() / n_cell_w); //printf("n_cell_w=%d, n_cell_h=%d, cw=%d, ch=%d", n_cell_w, n_cell_h, cw, ch); //printf("image size = %ld x %ld", im1.columns(), im1.rows()); vector<size_t> sel_best_robust_match_idx; for( unsigned int i=0; i<n_cell_w; ++i ) { for( unsigned int j=0; j<n_cell_h; ++j ) { unsigned int xl = i * cw; unsigned int xh = (i+1)*cw - 1; if( xh > im1.columns() ) { xh = im1.columns() - 1; } unsigned int yl = j * ch; unsigned int yh = (j+1)*ch - 1; if( yh > im1.rows() ) { yh = im1.rows() - 1; } //printf("\ncell(%d,%d) = (%d,%d) to (%d,%d)", i, j, xl, yl, xh, yh); //cout << flush; vector< size_t > cell_pts; for( unsigned int k=0; k<best_robust_match_idx.size(); ++k ) { size_t match_idx = best_robust_match_idx.at(k); double x = pts1(0, match_idx); double y = pts1(1, match_idx); if( x >= xl && x < xh && y >= yl && y < yh ) { cell_pts.push_back( match_idx ); } } if( cell_pts.size() >= POINTS_PER_CELL ) { uniform_int_distribution<> dist2(0, cell_pts.size()-1); for( unsigned int k=0; k<POINTS_PER_CELL; ++k ) { unsigned long cell_pts_idx = dist2(generator); sel_best_robust_match_idx.push_back( cell_pts.at(cell_pts_idx) ); } } } } size_t n_cp = sel_best_robust_match_idx.size(); MatrixXd cp1(2,n_cp); MatrixXd cp2(2,n_cp); for( size_t i=0; i<n_cp; ++i ) { unsigned long match_idx = sel_best_robust_match_idx.at(i); cp1(0,i) = pts1(0, match_idx ); cp1(1,i) = pts1(1, match_idx ); cp2(0,i) = pts2(0, match_idx ); cp2(1,i) = pts2(1, match_idx ); } // im1 crop Magick::Image im1_crop(im1); Magick::Geometry cropRect1(xu-xl, yu-yl, xl, yl); im1_crop.crop( cropRect1 ); im1_crop.magick("JPEG"); //cout << "\nWriting to " << im1_crop_fn << flush; im1_crop.write( im1_crop_fn ); Magick::Image im2_crop(im2); im2_crop.crop( cropRect1 ); //im2_crop.write( im2_crop_fn ); double lambda = 0.001; double lambda_norm = lambda * (im1_crop.rows() * im1_crop.columns()); // create matrix K MatrixXd K(n_cp, n_cp); K.setZero(); double rx, ry, r, r2; for(unsigned int i=0; i<n_cp; ++i ) { for(unsigned int j=i; j<n_cp; ++j ) { // image grid coordinate = (i,j) // control point coordinate = cp(:,k) rx = cp1(0,i) - cp1(0,j); ry = cp1(1,i) - cp1(1,j); r = sqrt(rx*rx + ry*ry); r2 = r * r; K(i, j) = r2*log(r2); K(j, i) = K(i,j); } } //cout << "K=" << K.rows() << "," << K.cols() << endl; //cout << "lambda = " << lambda << endl; // create matrix P MatrixXd P(n_cp, 3); for(unsigned int i=0; i<n_cp; ++i ) { //K(i,i) = 0; // ensure that the diagonal elements of K are 0 (as log(0) = nan) // approximating thin-plate splines based on: // Rohr, K., Stiehl, H.S., Sprengel, R., Buzug, T.M., Weese, J. and Kuhn, M.H., 2001. Landmark-based elastic registration using approximating thin-plate splines. K(i,i) = ((double) n_cp) * lambda * 1; P(i,0) = 1; P(i,1) = cp1(0,i); P(i,2) = cp1(1,i); } // cout << "P=" << P.rows() << "," << P.cols() << endl; //cout << "K=" << endl << K.block(0,0,6,6) << endl; // cout << "K=" << endl << K << endl; // create matrix L MatrixXd L(n_cp+3, n_cp+3); L.block(0, 0, n_cp, n_cp) = K; L.block(0, n_cp, n_cp, 3) = P; L.block(n_cp, 0, 3, n_cp) = P.transpose(); L.block(n_cp, n_cp, 3, 3).setZero(); // cout << "L rows and cols are: " << L.rows() << "," << L.cols() << endl; // create matrix V MatrixXd V(n_cp+3, 2); V.setZero(); for(unsigned int i=0; i<n_cp; ++i ) { V(i,0) = cp2(0,i); V(i,1) = cp2(1,i); } MatrixXd Linv = L.inverse(); MatrixXd W = Linv * V; // apply compyute transformations to second image // cout << "L matrix is: " << endl; // cout << L << endl; // Magick::Image im2t_crop( im1_crop.size(), "white"); // string op_w_h_and_offsets; // Magick::DrawableAffine hinv_affine(W(0,0), W(1,1), W(1,0), W(0,1), 0, 0); // op_w_h_and_offsets = std::to_string(xu-xl) + // "x" + // std::to_string(yu-yl) + // "-" + to_string((int) W(0,2)) + // "-" + to_string((int) W(1,2)); // im2t_crop.affineTransform(hinv_affine); // im2t_crop.artifact("distort:viewport", op_w_h_and_offsets); Magick::Image im2t_crop( im1_crop.size(), "white"); double x0,x1,y0,y1; double x, y; double dx0, dx1, dy0, dy1; double fxy0, fxy1; double fxy_red, fxy_green, fxy_blue; double xi, yi; double x_non_linear_terms, y_non_linear_terms; double x_affine_terms, y_affine_terms; for(unsigned int j=0; j<im1_crop.rows(); j++) { for(unsigned int i=0; i<im1_crop.columns(); i++) { //cout << "(" << i << "," << j << ") :" << endl; xi = ((double) i) + 0.5; // center of pixel yi = ((double) j) + 0.5; // center of pixel x_non_linear_terms = 0.0; y_non_linear_terms = 0.0; for(unsigned int k=0; k<n_cp; ++k) { //cout << " k=" << k << endl; rx = cp1(0,k) - xi; ry = cp1(1,k) - yi; r = sqrt(rx*rx + ry*ry); r2 = r*r; x_non_linear_terms += W(k, 0) * r2 * log(r2); y_non_linear_terms += W(k, 1) * r2 * log(r2); //cout << "(" << x_non_linear_terms << "," << y_non_linear_terms << ")" << flush; } x_affine_terms = W(n_cp,0) + W(n_cp+1,0)*xi + W(n_cp+2,0)*yi; y_affine_terms = W(n_cp,1) + W(n_cp+1,1)*xi + W(n_cp+2,1)*yi; x = x_affine_terms + x_non_linear_terms; y = y_affine_terms + y_non_linear_terms; //printf("(%d,%d) : (xi,yi)=(%.2f,%.2f) (x,y)=(%.2f,%.2f) : (x,y)-affine = (%.2f,%.2f) (x,y)-nonlin = (%.2f,%.2f)", i, j, xi, yi, x, y, x_affine_terms, y_affine_terms, x_non_linear_terms, y_non_linear_terms); // neighbourhood of xh x0 = ((int) x); x1 = x0 + 1; dx0 = x - x0; dx1 = x1 - x; y0 = ((int) y); y1 = y0 + 1; dy0 = y - y0; dy1 = y1 - y; Magick::ColorRGB fx0y0, fx1y0, fx0y1, fx1y1; if (is_photometric) { fx0y0 = im2_pt.pixelColor(x0, y0); fx1y0 = im2_pt.pixelColor(x1, y0); fx0y1 = im2_pt.pixelColor(x0, y1); fx1y1 = im2_pt.pixelColor(x1, y1); } else { fx0y0 = im2.pixelColor(x0, y0); fx1y0 = im2.pixelColor(x1, y0); fx0y1 = im2.pixelColor(x0, y1); fx1y1 = im2.pixelColor(x1, y1); } // Bilinear interpolation: https://en.wikipedia.org/wiki/Bilinear_interpolation fxy0 = dx1 * fx0y0.red() + dx0 * fx1y0.red(); // note: x1 - x0 = 1 fxy1 = dx1 * fx0y1.red() + dx0 * fx1y1.red(); // note: x1 - x0 = 1 fxy_red = dy1 * fxy0 + dy0 * fxy1; fxy0 = dx1 * fx0y0.green() + dx0 * fx1y0.green(); // note: x1 - x0 = 1 fxy1 = dx1 * fx0y1.green() + dx0 * fx1y1.green(); // note: x1 - x0 = 1 fxy_green = dy1 * fxy0 + dy0 * fxy1; fxy0 = dx1 * fx0y0.blue() + dx0 * fx1y0.blue(); // note: x1 - x0 = 1 fxy1 = dx1 * fx0y1.blue() + dx0 * fx1y1.blue(); // note: x1 - x0 = 1 fxy_blue = dy1 * fxy0 + dy0 * fxy1; // cout << "red is: " << fx0y0.red() << " green is: " << fx0y0.green() << " blue is: " << fx0y0.blue() << endl; Magick::ColorRGB fxy(fxy_red, fxy_green, fxy_blue); im2t_crop.pixelColor(i, j, fxy); } } im2t_crop.write( im2_tx_fn ); im2t_crop.write( overlap_image_fn ); //auto finish = std::chrono::high_resolution_clock::now(); //std::chrono::duration<double> elapsed = finish - start; //std::cout << "tps registration completed in " << elapsed.count() << " s" << endl; // difference image Magick::Image cdiff(im1_crop.size(), "black"); get_diff_image(im1_crop, im2t_crop, cdiff); cdiff.write(diff_image_fn); success = true; message = ""; } catch( std::exception &e ) { success = false; std::ostringstream ss; ss << "Exception occured: [" << e.what() << "]"; message = ss.str(); } }
36.490299
216
0.592736
kaloyan13
c9e6865f455005a01f2ea3f3a1da44b9e4b15931
1,451
cpp
C++
FootSoldier.cpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
FootSoldier.cpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
FootSoldier.cpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
// // Created by rotem levy on 27/05/2020. // #include "FootSoldier.hpp" FootSoldier::FootSoldier(uint player_number) { player_num = player_number; hp = MAX_HP; damage = -10; type = Type::FootSoldierType; } uint FootSoldier::getMaxHP() { return MAX_HP; } void FootSoldier::attack(std::vector<std::vector<Soldier*>> &b, std::pair<int,int> location) { int row = location.first; int col = location.second; Soldier* near_enemy = nullptr; std::pair<int,int> near_enemy_location; double min = b.size()*b.size(); for(int i = 0 ; i < b.size() ; i ++) { for(int j = 0 ; j < b[i].size(); j++) { Soldier * temp = b[i][j]; if(temp != nullptr) { if(temp->getPlayer_number() != player_num) { double dist = Utils::distance(row,col,i,j); if(dist < min) { min = dist; near_enemy = temp; near_enemy_location = {i,j}; } } } } } if(near_enemy != nullptr) { int new_hp = near_enemy->getHp() + damage; near_enemy->setHp(new_hp); if(new_hp <= 0) { b[near_enemy_location.first][near_enemy_location.second] = nullptr; } } }
24.59322
93
0.465196
rotemish7
c9e6e6216c7f602fa8d1fb55d29709a7fcc36744
10,104
cpp
C++
stm32/cm/CmPinMap.cpp
lupyuen/codal-libopencm3
8a7b50ba7b146232e358f2c8b50fc0b27d757113
[ "MIT" ]
7
2020-02-03T07:15:14.000Z
2020-12-03T07:05:13.000Z
stm32/cm/CmPinMap.cpp
lupyuen/codal-libopencm3
8a7b50ba7b146232e358f2c8b50fc0b27d757113
[ "MIT" ]
null
null
null
stm32/cm/CmPinMap.cpp
lupyuen/codal-libopencm3
8a7b50ba7b146232e358f2c8b50fc0b27d757113
[ "MIT" ]
4
2019-12-04T10:26:33.000Z
2021-02-10T06:47:25.000Z
#include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #include <logger.h> #include "CmPinMap.h" #define error(x) { debug_println(x); debug_flush(); } static CmPeripheral pinmap_find_peripheral(codal::PinNumber pin, const PinMap *map); static CmPinMode pinmap_find_mode(codal::PinNumber pin, const PinMap *map); static CmPinCnf pinmap_find_cnf(codal::PinNumber pin, const PinMap *map); CmPeripheral pinmap_peripheral(codal::PinNumber pin, const PinMap* map) { // Return the peripheral for the pin e.g. SPI1. CmPeripheral peripheral = CM_PERIPHERAL_NC; if (pin == CM_PIN_NC) { return CM_PERIPHERAL_NC; } peripheral = pinmap_find_peripheral(pin, map); if (peripheral == CM_PERIPHERAL_NC) // no mapping available { error("pinmap not found for peripheral"); } return peripheral; } CmPinMode pinmap_mode(codal::PinNumber pin, const PinMap* map) { // Return the pin mode for the peripheral e.g. GPIO_MODE_OUTPUT_2_MHZ. CmPinMode mode = CM_PINMODE_NC; if (pin == CM_PIN_NC) { return CM_PINMODE_NC; } mode = pinmap_find_mode(pin, map); if (mode == CM_PINMODE_NC) // no mapping available { error("pinmap not found for mode"); } return mode; } CmPinCnf pinmap_cnf(codal::PinNumber pin, const PinMap* map) { // Return the pin config for the peripheral e.g. GPIO_CNF_OUTPUT_PUSHPULL. CmPinCnf cnf = CM_PINCNF_NC; if (pin == CM_PIN_NC) { return CM_PINCNF_NC; } cnf = pinmap_find_cnf(pin, map); if (cnf == CM_PINCNF_NC) // no mapping available { error("pinmap not found for cnf"); } return cnf; } static CmPeripheral pinmap_find_peripheral(codal::PinNumber pin, const PinMap* map) { // Return the peripheral for the pin e.g. SPI1. while (map->pin != CM_PIN_NC) { if (map->pin == pin) { return map->peripheral; } map++; } return CM_PERIPHERAL_NC; } static CmPinMode pinmap_find_mode(codal::PinNumber pin, const PinMap* map) { // Return the pin mode for the peripheral e.g. GPIO_MODE_OUTPUT_2_MHZ. while (map->pin != CM_PIN_NC) { if (map->pin == pin) { return map->mode; } map++; } return CM_PINMODE_NC; } static CmPinCnf pinmap_find_cnf(codal::PinNumber pin, const PinMap* map) { // Return the pin config for the peripheral e.g. GPIO_CNF_OUTPUT_PUSHPULL. while (map->pin != CM_PIN_NC) { if (map->pin == pin) { return map->cnf; } map++; } return CM_PINCNF_NC; } #ifdef TODO uint32_t pinmap_merge(uint32_t a, uint32_t b) { // both are the same (inc both NC) if (a == b) return a; // one (or both) is not connected if (a == (uint32_t)NC) return b; if (b == (uint32_t)NC) return a; // mis-match error case error("pinmap mis-match"); return (uint32_t)NC; } void pinmap_pinout(codal::PinNumber pin, const PinMap *map) { if (pin == NC) return; while (map->pin != NC) { if (map->pin == pin) { pin_function(pin, map->function); pin_mode(pin, PullNone); return; } map++; } error("could not pinout"); } #endif // TODO #ifdef NOTUSED #define error MBED_ERROR extern GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx); const uint32_t ll_pin_defines[16] = { #ifdef TODO LL_GPIO_PIN_0, LL_GPIO_PIN_1, LL_GPIO_PIN_2, LL_GPIO_PIN_3, LL_GPIO_PIN_4, LL_GPIO_PIN_5, LL_GPIO_PIN_6, LL_GPIO_PIN_7, LL_GPIO_PIN_8, LL_GPIO_PIN_9, LL_GPIO_PIN_10, LL_GPIO_PIN_11, LL_GPIO_PIN_12, LL_GPIO_PIN_13, LL_GPIO_PIN_14, LL_GPIO_PIN_15 #endif // TODO }; typedef enum { PortA = 0, PortB = 1, PortC = 2, PortD = 3, PortE = 4, PortF = 5, PortG = 6, PortH = 7, PortI = 8, PortJ = 9, PortK = 10 } PortName; // Enable GPIO clock and return GPIO base address GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx) { return NULL; ////TODO #ifdef TODO uint32_t gpio_add = 0; switch (port_idx) { case PortA: gpio_add = GPIOA_BASE; __HAL_RCC_GPIOA_CLK_ENABLE(); break; case PortB: gpio_add = GPIOB_BASE; __HAL_RCC_GPIOB_CLK_ENABLE(); break; #if defined(GPIOC_BASE) case PortC: gpio_add = GPIOC_BASE; __HAL_RCC_GPIOC_CLK_ENABLE(); break; #endif #if defined GPIOD_BASE case PortD: gpio_add = GPIOD_BASE; __HAL_RCC_GPIOD_CLK_ENABLE(); break; #endif #if defined GPIOE_BASE case PortE: gpio_add = GPIOE_BASE; __HAL_RCC_GPIOE_CLK_ENABLE(); break; #endif #if defined GPIOF_BASE case PortF: gpio_add = GPIOF_BASE; __HAL_RCC_GPIOF_CLK_ENABLE(); break; #endif #if defined GPIOG_BASE case PortG: #if defined TARGET_STM32L4 __HAL_RCC_PWR_CLK_ENABLE(); HAL_PWREx_EnableVddIO2(); #endif gpio_add = GPIOG_BASE; __HAL_RCC_GPIOG_CLK_ENABLE(); break; #endif #if defined GPIOH_BASE case PortH: gpio_add = GPIOH_BASE; __HAL_RCC_GPIOH_CLK_ENABLE(); break; #endif #if defined GPIOI_BASE case PortI: gpio_add = GPIOI_BASE; __HAL_RCC_GPIOI_CLK_ENABLE(); break; #endif #if defined GPIOJ_BASE case PortJ: gpio_add = GPIOJ_BASE; __HAL_RCC_GPIOJ_CLK_ENABLE(); break; #endif #if defined GPIOK_BASE case PortK: gpio_add = GPIOK_BASE; __HAL_RCC_GPIOK_CLK_ENABLE(); break; #endif default: error("Pinmap error: wrong port number."); break; } return (GPIO_TypeDef *) gpio_add; #endif // TODO } /** * Configure pin (mode, speed, output type and pull-up/pull-down) */ void pin_function(codal::PinNumber pin, int data) { #ifdef TODO MBED_ASSERT(pin != CM_PIN_NC); // Get the pin informations uint32_t mode = STM_PIN_FUNCTION(data); uint32_t afnum = STM_PIN_AFNUM(data); uint32_t port = STM_PORT(pin); uint32_t ll_pin = ll_pin_defines[STM_PIN(pin)]; uint32_t ll_mode = 0; // Enable GPIO clock GPIO_TypeDef *gpio = Set_GPIO_Clock(port); /* Set default speed to high. * For most families there are dedicated registers so it is * not so important, register can be set at any time. * But for families like F1, speed only applies to output. */ #if defined (TARGET_STM32F1) if (mode == STM_PIN_OUTPUT) { #endif LL_GPIO_SetPinSpeed(gpio, ll_pin, LL_GPIO_SPEED_FREQ_HIGH); #if defined (TARGET_STM32F1) } #endif switch (mode) { case STM_PIN_INPUT: ll_mode = LL_GPIO_MODE_INPUT; break; case STM_PIN_OUTPUT: ll_mode = LL_GPIO_MODE_OUTPUT; break; case STM_PIN_ALTERNATE: ll_mode = LL_GPIO_MODE_ALTERNATE; // In case of ALT function, also set he afnum stm_pin_SetAFPin(gpio, pin, afnum); break; case STM_PIN_ANALOG: ll_mode = LL_GPIO_MODE_ANALOG; break; default: MBED_ASSERT(0); break; } LL_GPIO_SetPinMode(gpio, ll_pin, ll_mode); #if defined(GPIO_ASCR_ASC0) /* For families where Analog Control ASC0 register is present */ if (STM_PIN_ANALOG_CONTROL(data)) { LL_GPIO_EnablePinAnalogControl(gpio, ll_pin); } else { LL_GPIO_DisablePinAnalogControl(gpio, ll_pin); } #endif /* For now by default use Speed HIGH for output or alt modes */ if ((mode == STM_PIN_OUTPUT) ||(mode == STM_PIN_ALTERNATE)) { if (STM_PIN_OD(data)) { LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_OPENDRAIN); } else { LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_PUSHPULL); } } stm_pin_PullConfig(gpio, ll_pin, STM_PIN_PUPD(data)); stm_pin_DisconnectDebug(pin); #endif // TODO } /** * Configure pin pull-up/pull-down */ void pin_mode(codal::PinNumber pin, PinMode mode) { #ifdef TODO MBED_ASSERT(pin != CM_PIN_NC); uint32_t port_index = STM_PORT(pin); uint32_t ll_pin = ll_pin_defines[STM_PIN(pin)]; // Enable GPIO clock GPIO_TypeDef *gpio = Set_GPIO_Clock(port_index); uint32_t function = LL_GPIO_GetPinMode(gpio, ll_pin); if ((function == LL_GPIO_MODE_OUTPUT) || (function == LL_GPIO_MODE_ALTERNATE)) { if ((mode == OpenDrainNoPull) || (mode == OpenDrainPullUp) || (mode == OpenDrainPullDown)) { LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_OPENDRAIN); } else { LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_PUSHPULL); } } if ((mode == OpenDrainPullUp) || (mode == PullUp)) { stm_pin_PullConfig(gpio, ll_pin, GPIO_PULLUP); } else if ((mode == OpenDrainPullDown) || (mode == PullDown)) { stm_pin_PullConfig(gpio, ll_pin, GPIO_PULLDOWN); } else { stm_pin_PullConfig(gpio, ll_pin, GPIO_NOPULL); } #endif // TODO } #endif // NOTUSED
29.982196
104
0.570269
lupyuen
c9eb48dfea9c04d460ffd21cb5f3b927dd82e812
3,984
cpp
C++
engine/source/PADO/PADO_Object.cpp
Goldenbough44/PADO
a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6
[ "MIT" ]
1
2021-08-13T04:39:53.000Z
2021-08-13T04:39:53.000Z
engine/source/PADO/PADO_Object.cpp
Goldenbough44/PADO
a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6
[ "MIT" ]
2
2021-08-13T04:49:02.000Z
2022-03-25T19:20:56.000Z
engine/source/PADO/PADO_Object.cpp
Goldenbough44/PADO
a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6
[ "MIT" ]
null
null
null
// // (c) 2019 Highwater Games Co. All Rights Reserved. // #include "PADO_Object.h" PADO_Object::PADO_Object() : position(0, 0) { } PADO_Object::~PADO_Object() { } void PADO_Object::Initialize() { } void PADO_Object::BeginPlay() { } void PADO_Object::Update() { } void PADO_Object::EndPlay() { } void PADO_Object::Render() { } void PADO_Object::Destroy() { if(!spawned) PADO_CatchError(210, "Cannot destroy object! The object isn't spawned : %s", "PADO_Object"); objectContainer->Destroy(); } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; this->parent = parent; this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer* objectContainer, std::string name, unsigned int layer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent, unsigned int layer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); this->parent = parent; this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer* objectContainer, std::string name, unsigned int layer, unsigned int sortInLayer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); if (0 > setSortInLayer(sortInLayer)) setSortInLayer(0); this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent, unsigned int layer, unsigned int sortInLayer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); if (0 > setSortInLayer(sortInLayer)) setSortInLayer(0); this->parent = parent; this->objectContainer = objectContainer; } std::string PADO_Object::GetName() { if(!spawned) PADO_CatchError(221, "Cannot get the name! The object isn't spawned : %s", "PADO_Object"); return objectName; } void PADO_Object::setActive(bool active) { this->active = active; } bool PADO_Object::isActive() { return active; } void PADO_Object::setVisibility(bool visibility) { this->visible = visibility; } bool PADO_Object::isVisible() { return visible; } bool PADO_Object::isSpawned() { return spawned; } void PADO_Object::setUpdate(bool update) { this->update = update; } bool PADO_Object::getUpdate() { return update; } void PADO_Object::setPosition(PADO_Vector2 position) { this->position = position; } const PADO_Vector2 *PADO_Object::getPosition() { return &position; } int PADO_Object::setLayer(unsigned int layer) { if(layer >= MAX_LAYER) { return -1; } this->layer = layer; return layer; } int PADO_Object::getLayer() { return sortInLayer; } int PADO_Object::setSortInLayer(unsigned int sortInLayer) { if(layer >= MAX_SORT_IN_LAYER) { return -1; } this->sortInLayer = sortInLayer; return sortInLayer; } int PADO_Object::getSortInLayer() { return sortInLayer; }
24.145455
109
0.682229
Goldenbough44
c9ed10547ad050426ff7fa6c90f63326213c4b22
881
cpp
C++
WildMagic4/LibFoundation/Mathematics/Wm4Vector2.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
23
2015-08-13T07:36:00.000Z
2022-01-24T19:00:04.000Z
WildMagic4/LibFoundation/Mathematics/Wm4Vector2.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
null
null
null
WildMagic4/LibFoundation/Mathematics/Wm4Vector2.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
6
2015-07-06T21:37:31.000Z
2020-07-01T04:07:50.000Z
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 4.10.0 (2009/11/18) #include "Wm4FoundationPCH.h" #include "Wm4Vector2.h" using namespace Wm4; template<> const Vector2<float> Vector2<float>::ZERO(0.0f,0.0f); template<> const Vector2<float> Vector2<float>::UNIT_X(1.0f,0.0f); template<> const Vector2<float> Vector2<float>::UNIT_Y(0.0f,1.0f); template<> const Vector2<float> Vector2<float>::ONE(1.0f,1.0f); template<> const Vector2<double> Vector2<double>::ZERO(0.0,0.0); template<> const Vector2<double> Vector2<double>::UNIT_X(1.0,0.0); template<> const Vector2<double> Vector2<double>::UNIT_Y(0.0,1.0); template<> const Vector2<double> Vector2<double>::ONE(1.0,1.0);
40.045455
67
0.710556
rms80
c9ee6afef62776cfed6f043a24baffe689015a98
16,405
cc
C++
wrappers/8.1.1/vtkBrushWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkBrushWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkBrushWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkObjectWrap.h" #include "vtkBrushWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkImageDataWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkBrushWrap::ptpl; VtkBrushWrap::VtkBrushWrap() { } VtkBrushWrap::VtkBrushWrap(vtkSmartPointer<vtkBrush> _native) { native = _native; } VtkBrushWrap::~VtkBrushWrap() { } void VtkBrushWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkBrush").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("Brush").ToLocalChecked(), ConstructorGetter); } void VtkBrushWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkBrushWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkObjectWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl)); tpl->SetClassName(Nan::New("VtkBrushWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "DeepCopy", DeepCopy); Nan::SetPrototypeMethod(tpl, "deepCopy", DeepCopy); Nan::SetPrototypeMethod(tpl, "GetColor", GetColor); Nan::SetPrototypeMethod(tpl, "getColor", GetColor); Nan::SetPrototypeMethod(tpl, "GetColorF", GetColorF); Nan::SetPrototypeMethod(tpl, "getColorF", GetColorF); Nan::SetPrototypeMethod(tpl, "GetOpacity", GetOpacity); Nan::SetPrototypeMethod(tpl, "getOpacity", GetOpacity); Nan::SetPrototypeMethod(tpl, "GetOpacityF", GetOpacityF); Nan::SetPrototypeMethod(tpl, "getOpacityF", GetOpacityF); Nan::SetPrototypeMethod(tpl, "GetTexture", GetTexture); Nan::SetPrototypeMethod(tpl, "getTexture", GetTexture); Nan::SetPrototypeMethod(tpl, "GetTextureProperties", GetTextureProperties); Nan::SetPrototypeMethod(tpl, "getTextureProperties", GetTextureProperties); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetColor", SetColor); Nan::SetPrototypeMethod(tpl, "setColor", SetColor); Nan::SetPrototypeMethod(tpl, "SetColorF", SetColorF); Nan::SetPrototypeMethod(tpl, "setColorF", SetColorF); Nan::SetPrototypeMethod(tpl, "SetOpacity", SetOpacity); Nan::SetPrototypeMethod(tpl, "setOpacity", SetOpacity); Nan::SetPrototypeMethod(tpl, "SetOpacityF", SetOpacityF); Nan::SetPrototypeMethod(tpl, "setOpacityF", SetOpacityF); Nan::SetPrototypeMethod(tpl, "SetTexture", SetTexture); Nan::SetPrototypeMethod(tpl, "setTexture", SetTexture); Nan::SetPrototypeMethod(tpl, "SetTextureProperties", SetTextureProperties); Nan::SetPrototypeMethod(tpl, "setTextureProperties", SetTextureProperties); #ifdef VTK_NODE_PLUS_VTKBRUSHWRAP_INITPTPL VTK_NODE_PLUS_VTKBRUSHWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkBrushWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkBrush> native = vtkSmartPointer<vtkBrush>::New(); VtkBrushWrap* obj = new VtkBrushWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkBrushWrap::DeepCopy(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkBrushWrap::ptpl))->HasInstance(info[0])) { VtkBrushWrap *a0 = ObjectWrap::Unwrap<VtkBrushWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->DeepCopy( (vtkBrush *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::GetColor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsUint8Array()) { v8::Local<v8::Uint8Array>a0(v8::Local<v8::Uint8Array>::Cast(info[0]->ToObject())); if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColor( (unsigned char *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); unsigned char b0[4]; if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 4; i++ ) { if( !a0->Get(i)->IsUint32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Uint32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColor( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::GetColorF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColorF( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[4]; if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 4; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColorF( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::GetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); unsigned char r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacity(); info.GetReturnValue().Set(Nan::New(r)); } void VtkBrushWrap::GetOpacityF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacityF(); info.GetReturnValue().Set(Nan::New(r)); } void VtkBrushWrap::GetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); vtkImageData * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTexture(); VtkImageDataWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageDataWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageDataWrap *w = new VtkImageDataWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkBrushWrap::GetTextureProperties(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTextureProperties(); info.GetReturnValue().Set(Nan::New(r)); } void VtkBrushWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); vtkBrush * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkBrushWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkBrushWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkBrushWrap *w = new VtkBrushWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkBrushWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkBrush * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkBrushWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkBrushWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkBrushWrap *w = new VtkBrushWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetColor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsUint8Array()) { v8::Local<v8::Uint8Array>a0(v8::Local<v8::Uint8Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( (unsigned char *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); unsigned char b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsUint32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Uint32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( b0 ); return; } else if(info.Length() > 0 && info[0]->IsUint32()) { if(info.Length() > 1 && info[1]->IsUint32()) { if(info.Length() > 2 && info[2]->IsUint32()) { if(info.Length() > 3 && info[3]->IsUint32()) { if(info.Length() != 4) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( info[0]->Uint32Value(), info[1]->Uint32Value(), info[2]->Uint32Value(), info[3]->Uint32Value() ); return; } if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( info[0]->Uint32Value(), info[1]->Uint32Value(), info[2]->Uint32Value() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetColorF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( b0 ); return; } else if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() > 1 && info[1]->IsNumber()) { if(info.Length() > 2 && info[2]->IsNumber()) { if(info.Length() > 3 && info[3]->IsNumber()) { if(info.Length() != 4) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( info[0]->NumberValue(), info[1]->NumberValue(), info[2]->NumberValue(), info[3]->NumberValue() ); return; } if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( info[0]->NumberValue(), info[1]->NumberValue(), info[2]->NumberValue() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsUint32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacity( info[0]->Uint32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetOpacityF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacityF( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkImageDataWrap::ptpl))->HasInstance(info[0])) { VtkImageDataWrap *a0 = ObjectWrap::Unwrap<VtkImageDataWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTexture( (vtkImageData *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetTextureProperties(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTextureProperties( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
25.713166
106
0.654617
axkibe
c9ef8dcf34ae1e8a51bb41ee9a5c34e1f011cd7a
4,186
cpp
C++
src/crypto/openssl/symmetric_key.cpp
Jerryxia32/CCF
2514a92ff96ca22aff37994d211ace2e1c918097
[ "Apache-2.0" ]
530
2019-05-07T03:07:15.000Z
2022-03-29T16:33:06.000Z
src/crypto/openssl/symmetric_key.cpp
Jerryxia32/CCF
2514a92ff96ca22aff37994d211ace2e1c918097
[ "Apache-2.0" ]
3,393
2019-05-07T08:33:32.000Z
2022-03-31T14:57:14.000Z
src/crypto/openssl/symmetric_key.cpp
beejones/CCF
335fc3613c2dd4a3bda38e10e8e8196dba52465e
[ "Apache-2.0" ]
158
2019-05-07T09:17:56.000Z
2022-03-25T16:45:04.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #include "symmetric_key.h" #include "../mbedtls/symmetric_key.h" #include "crypto/openssl/openssl_wrappers.h" #include "crypto/symmetric_key.h" #include "ds/logger.h" #include "ds/thread_messaging.h" #include <openssl/aes.h> #include <openssl/evp.h> namespace crypto { using namespace OpenSSL; KeyAesGcm_OpenSSL::KeyAesGcm_OpenSSL(CBuffer rawKey) : key(std::vector<uint8_t>(rawKey.p, rawKey.p + rawKey.n)), evp_cipher(nullptr) { const auto n = static_cast<unsigned int>(rawKey.rawSize() * 8); if (n >= 256) { evp_cipher = EVP_aes_256_gcm(); evp_cipher_wrap_pad = EVP_aes_256_wrap_pad(); } else if (n >= 192) { evp_cipher = EVP_aes_192_gcm(); evp_cipher_wrap_pad = EVP_aes_192_wrap_pad(); } else if (n >= 128) { evp_cipher = EVP_aes_128_gcm(); evp_cipher_wrap_pad = EVP_aes_128_wrap_pad(); } else { throw std::logic_error( fmt::format("Need at least {} bits, only have {}", 128, n)); } } size_t KeyAesGcm_OpenSSL::key_size() const { return key.size() * 8; } void KeyAesGcm_OpenSSL::encrypt( CBuffer iv, CBuffer plain, CBuffer aad, uint8_t* cipher, uint8_t tag[GCM_SIZE_TAG]) const { std::vector<uint8_t> cb(plain.n + GCM_SIZE_TAG); int len = 0; Unique_EVP_CIPHER_CTX ctx; CHECK1(EVP_EncryptInit_ex(ctx, evp_cipher, NULL, key.data(), NULL)); CHECK1(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.n, NULL)); CHECK1(EVP_EncryptInit_ex(ctx, NULL, NULL, key.data(), iv.p)); if (aad.n > 0) CHECK1(EVP_EncryptUpdate(ctx, NULL, &len, aad.p, aad.n)); CHECK1(EVP_EncryptUpdate(ctx, cb.data(), &len, plain.p, plain.n)); CHECK1(EVP_EncryptFinal_ex(ctx, cb.data() + len, &len)); CHECK1( EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_SIZE_TAG, &tag[0])); if (plain.n > 0) memcpy(cipher, cb.data(), plain.n); } bool KeyAesGcm_OpenSSL::decrypt( CBuffer iv, const uint8_t tag[GCM_SIZE_TAG], CBuffer cipher, CBuffer aad, uint8_t* plain) const { std::vector<uint8_t> pb(cipher.n + GCM_SIZE_TAG); int len = 0; Unique_EVP_CIPHER_CTX ctx; CHECK1(EVP_DecryptInit_ex(ctx, evp_cipher, NULL, NULL, NULL)); CHECK1(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.n, NULL)); CHECK1(EVP_DecryptInit_ex(ctx, NULL, NULL, key.data(), iv.p)); if (aad.n > 0) CHECK1(EVP_DecryptUpdate(ctx, NULL, &len, aad.p, aad.n)); CHECK1(EVP_DecryptUpdate(ctx, pb.data(), &len, cipher.p, cipher.n)); CHECK1(EVP_CIPHER_CTX_ctrl( ctx, EVP_CTRL_GCM_SET_TAG, GCM_SIZE_TAG, (uint8_t*)tag)); int r = EVP_DecryptFinal_ex(ctx, pb.data() + len, &len) > 0; if (r == 1 && cipher.n > 0) memcpy(plain, pb.data(), cipher.n); return r == 1; } std::vector<uint8_t> KeyAesGcm_OpenSSL::ckm_aes_key_wrap_pad( CBuffer plain) const { int len = 0; Unique_EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); CHECK1(EVP_EncryptInit_ex(ctx, evp_cipher_wrap_pad, NULL, NULL, NULL)); CHECK1(EVP_EncryptInit_ex(ctx, NULL, NULL, key.data(), NULL)); CHECK1(EVP_EncryptUpdate(ctx, NULL, &len, plain.p, plain.n)); std::vector<uint8_t> cipher(len); CHECK1(EVP_EncryptUpdate(ctx, cipher.data(), &len, plain.p, plain.n)); CHECK1(EVP_EncryptFinal_ex(ctx, NULL, &len)); return cipher; } std::vector<uint8_t> KeyAesGcm_OpenSSL::ckm_aes_key_unwrap_pad( CBuffer cipher) const { int len = 0; Unique_EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); CHECK1(EVP_DecryptInit_ex(ctx, evp_cipher_wrap_pad, NULL, NULL, NULL)); CHECK1(EVP_DecryptInit_ex(ctx, NULL, NULL, key.data(), NULL)); CHECK1(EVP_DecryptUpdate(ctx, NULL, &len, cipher.p, cipher.n)); std::vector<uint8_t> plain(len); CHECK1(EVP_DecryptUpdate(ctx, plain.data(), &len, cipher.p, cipher.n)); plain.resize(len); if (EVP_DecryptFinal_ex(ctx, NULL, &len) != 1) { plain.clear(); } return plain; } }
30.779412
77
0.666985
Jerryxia32
c9ef9054639d5f33b2bcf68dd02a4e080b8813c9
550
cpp
C++
CppTranslate/sample_be.cpp
PooiaFerdowsi/Cpp-Translate
e41d32d9feb3ebb07e3b756a836ee215998f74fe
[ "MIT" ]
48
2020-03-25T16:52:10.000Z
2022-03-28T17:11:13.000Z
CppTranslate/sample_be.cpp
PooiaFerdowsi/Cpp-Translate
e41d32d9feb3ebb07e3b756a836ee215998f74fe
[ "MIT" ]
22
2021-04-22T14:48:17.000Z
2021-11-02T06:45:51.000Z
CppTranslate/sample_be.cpp
PooiaFerdowsi/Cpp-Translate
e41d32d9feb3ebb07e3b756a836ee215998f74fe
[ "MIT" ]
19
2020-06-09T22:29:05.000Z
2022-03-21T20:44:41.000Z
#include "be_belarusian.h" узор<кляса t> кляса прыклад { }; цэлы_лік зачатак() { статычны булеев элемент прыраўнай праўда; калі(элемент ілжывы) { вярні 1; } указка_на_поле_сыбалаў_які_закончаны_нулявым_сымбалем p = новы сымбаль[10]; p індэкс(0) прыраўнай 'c'; p індэкс(1) прыраўнай 0; выпіш(p); вярні 0; } // bad and evil source code: template<class T> class exemple { }; int main() { static bool element = true; if (element == false) { return 1; } char* p = new char[10]; p[0] = 'c'; p[1] = 0; printf(p); return 0; }
12.222222
76
0.656364
PooiaFerdowsi
c9f0dfb3c7fb00695aa70c191a5177f22c3a2b10
1,806
cc
C++
sources/tests/stresstests.test.cc
arcanis/text-layout
bfa95293ed06c9b355e803968fceb00b421352ba
[ "Unlicense", "MIT" ]
22
2017-05-13T07:03:02.000Z
2021-11-08T08:34:42.000Z
sources/tests/stresstests.test.cc
arcanis/text-layout
bfa95293ed06c9b355e803968fceb00b421352ba
[ "Unlicense", "MIT" ]
null
null
null
sources/tests/stresstests.test.cc
arcanis/text-layout
bfa95293ed06c9b355e803968fceb00b421352ba
[ "Unlicense", "MIT" ]
5
2017-05-13T07:03:05.000Z
2020-05-25T06:19:03.000Z
#include "./framework.hh" TEST_CASE("stress test #1") { SETUP(""); for (auto t = 0u; t < 30; ++t) APPEND("Foo\n"); ASSERT_EQ(LINE_COUNT(), 31); ASSERT_EQ(TEXT(), "Foo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\n"); } TEST_CASE("stress test #2") { SETUP(""); for (auto t = 0u; t < 30; ++t) { APPEND("a"); APPEND(" "); } ASSERT_EQ(LINE_COUNT(), 1); ASSERT_EQ(TEXT(), "a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a"); } TEST_CASE("stress test #3") { SETUP(""); layout.setColumns(10); layout.setSoftWrap(true); layout.setCollapseWhitespaces(true); layout.setJustifyText(true); RESET(); for (auto t = 0u; t < 30; ++t) { APPEND("a"); APPEND(" "); } ASSERT_EQ(LINE_COUNT(), 6); ASSERT_EQ(TEXT(), "a a a a a\na a a a a\na a a a a\na a a a a\na a a a a\na a a a a"); } TEST_CASE("stress test #4") { SETUP(""); layout.setColumns(10); layout.setSoftWrap(true); layout.setCollapseWhitespaces(true); layout.setPreserveTrailingSpaces(true); layout.setJustifyText(true); RESET(); auto currentPosition = Position(0, 0); FOR(c, "a b c d e f g h i j k l m n o p q r s t u v w x y z\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z") { auto characterIndex = layout.getCharacterIndexForPosition(currentPosition); SPLICE(characterIndex, 0, c); currentPosition = layout.getPositionForCharacterIndex(characterIndex + 1); } ASSERT_EQ(LINE_COUNT(), 12); ASSERT_EQ(TEXT(), "a b c d e\nf g h i j\nk l m n o\np q r s t\nu v w x y\nz\nA B C D E\nF G H I J\nK L M N O\nP Q R S T\nU V W X Y\nZ"); }
26.558824
176
0.582503
arcanis
c9f1d68067156e6683e47e5eef3b5cbfaedebc76
2,688
cpp
C++
workspace/src/render_world.cpp
nadnbuds/cs130
982dac98005dcf0675eacaf7b56a9ec6c53a8877
[ "MIT" ]
null
null
null
workspace/src/render_world.cpp
nadnbuds/cs130
982dac98005dcf0675eacaf7b56a9ec6c53a8877
[ "MIT" ]
null
null
null
workspace/src/render_world.cpp
nadnbuds/cs130
982dac98005dcf0675eacaf7b56a9ec6c53a8877
[ "MIT" ]
null
null
null
#include <vector> #include <limits> #include "render_world.h" #include "flat_shader.h" #include "object.h" #include "light.h" #include "ray.h" Render_World::Render_World() :background_shader(0),ambient_intensity(0),enable_shadows(true), recursion_depth_limit(3),disable_fresnel_reflection(false),disable_fresnel_refraction(false) {} Render_World::~Render_World() { delete background_shader; for(size_t i=0;i<objects.size();i++) delete objects[i]; for(size_t i=0;i<lights.size();i++) delete lights[i]; } // Find the closest object of intersection and return the object that was // intersected. Record the Hit structure in hit. If no intersection occurred, // return NULL. Note that in the case of a Boolean, the object returned will be // the Boolean, but the object stored in hit will be the underlying primitive. // Any intersection with t<=small_t should be ignored. Object* Render_World::Closest_Intersection(const Ray& ray,Hit& hit) { Object* closestObj = nullptr; double minT = std::numeric_limits<double>::max(); for(Object* var : objects) { std::vector<Hit> hits; var->Intersection(ray, hits); for(Hit h : hits) { if (h.t < minT && h.t > small_t) { minT = h.t; hit = h; closestObj = var; } } } return closestObj; } // set up the initial view ray and call void Render_World::Render_Pixel(const ivec2& pixel_index) { Ray ray; ray.endpoint = camera.position; ray.direction = (camera.World_Position(pixel_index) - camera.position).normalized(); vec3 color=Cast_Ray(ray, 0); camera.Set_Pixel(pixel_index,Pixel_Color(color)); } void Render_World::Render() { for(int j=0;j<camera.number_pixels[1];j++) for(int i=0;i<camera.number_pixels[0];i++) Render_Pixel(ivec2(i,j)); } // cast ray and return the color of the closest intersected surface point, // or the background color if there is no object intersection vec3 Render_World::Cast_Ray(const Ray& ray,int recursion_depth) { Hit objHit; objHit.object = nullptr; objHit.t = 0; objHit.ray_exiting = false; Object* obj = Closest_Intersection(ray, objHit); vec3 color; //If there is an Obj for the ray if (obj != nullptr && recursion_depth < recursion_depth_limit) { vec3 point = ray.Point(objHit.t); vec3 normal = obj->Normal(point); if (objHit.ray_exiting) { normal *= -1; } color = obj->material_shader->Shade_Surface( ray, point, normal, recursion_depth, objHit.ray_exiting); } //If there is no Obj, use the background else { vec3 dummy; color = background_shader->Shade_Surface( ray, ray.endpoint, ray.direction, recursion_depth, false); } return color; }
27.151515
96
0.697545
nadnbuds
c9f6ee8d75a66e04607361715b3130bfa133d12d
1,706
hpp
C++
libs/core/include/fcppt/variant/object_impl.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/core/include/fcppt/variant/object_impl.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/core/include/fcppt/variant/object_impl.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_VARIANT_OBJECT_IMPL_HPP_INCLUDED #define FCPPT_VARIANT_OBJECT_IMPL_HPP_INCLUDED #include <fcppt/variant/object_decl.hpp> #include <fcppt/variant/size_type.hpp> #include <fcppt/variant/detail/get_unsafe_impl.hpp> #include <fcppt/config/external_begin.hpp> #include <utility> #include <variant> #include <fcppt/config/external_end.hpp> template <typename... Types> template <typename U, typename> fcppt::variant::object<Types...>::object(U &&_other) : impl_{std::forward<U>(_other)} { } template <typename... Types> template <typename U> U &fcppt::variant::object<Types...>::get_unsafe() { return fcppt::variant::detail::get_unsafe_impl<this_type, U>(this->impl_); } template <typename... Types> template <typename U> U const &fcppt::variant::object<Types...>::get_unsafe() const { return fcppt::variant::detail::get_unsafe_impl<this_type, U>(this->impl_); } template <typename... Types> fcppt::variant::size_type fcppt::variant::object<Types...>::type_index() const { return this->impl_.index(); } template <typename... Types> bool fcppt::variant::object<Types...>::is_invalid() const { return this->type_index() == std::variant_npos; } template <typename... Types> typename fcppt::variant::object<Types...>::std_type &fcppt::variant::object<Types...>::impl() { return this->impl_; } template <typename... Types> typename fcppt::variant::object<Types...>::std_type const & fcppt::variant::object<Types...>::impl() const { return this->impl_; } #endif
27.079365
93
0.721571
freundlich
c9f72b2e01bc87e5839ec3566dab21cfdfb8e6f7
1,433
cpp
C++
ARPREC/arprec-2.2.13/tests/pslq3_main.cpp
paveloom-p/P3
57df3b6263db81685f137a7ed9428dbd3c1b4a5b
[ "Unlicense" ]
null
null
null
ARPREC/arprec-2.2.13/tests/pslq3_main.cpp
paveloom-p/P3
57df3b6263db81685f137a7ed9428dbd3c1b4a5b
[ "Unlicense" ]
null
null
null
ARPREC/arprec-2.2.13/tests/pslq3_main.cpp
paveloom-p/P3
57df3b6263db81685f137a7ed9428dbd3c1b4a5b
[ "Unlicense" ]
null
null
null
#include <iostream> #include <iomanip> #include <cfloat> #include <cmath> #include <arprec/mp_real.h> #include <arprec/mp_int.h> #include "pslq3.h" #include "pslq_main.h" using std::cout; using std::endl; int main(int argc, char **argv) { int mode = 0; int n; int r = 7, s = 8; int nr_digits = 780; int n_eps; /* Parse command line arguments. */ parse_command(argc, argv, mode, n, r, s, nr_digits, n_eps); n = r * s + 1; n_eps = (nr_digits < 700 ? 10 : 20) - nr_digits; cout << "nr_digits = " << nr_digits << endl; cout << "debug_level = " << debug_level << endl; cout << "n = " << n << endl; if (debug_level > 0) { cout << "r = " << r << " s = " << s << endl; cout << "n_eps = " << n_eps << endl;; } /* Initialize data */ mp::mp_init(nr_digits); matrix<mp_real> x(n); matrix<mp_real> rel(n); mp_real eps = pow(mp_real(10.0), n_eps); init_data(mode, n, r, s, x, rel); if (debug_level >= 1) { x.print("Initial x:"); } /* Perform Level-1 PSLQ. */ int result = pslq3(x, rel, eps); /* Output recovered relation. */ if (result == RESULT_RELATION_FOUND) { cout << "Relation found:" << endl; cout << std::fixed << std::setprecision(0); for (int i = 0; i < n; i++) { cout << std::setw(3) << i; cout << std::setw(24) << rel(i) << endl; } } else { cout << "Precision exhausted." << endl; } mp::mp_finalize(); return 0; }
21.712121
61
0.556874
paveloom-p
c9fe678f7afef814b5e579bdca5177d562856b09
16,630
cpp
C++
src/shogun/machine/gp/VarDTCInferenceMethod.cpp
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
1
2020-03-30T10:45:09.000Z
2020-03-30T10:45:09.000Z
src/shogun/machine/gp/VarDTCInferenceMethod.cpp
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
null
null
null
src/shogun/machine/gp/VarDTCInferenceMethod.cpp
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (W) 2015 Wu Lin * 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 OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. * * This code specifically adapted from function in varsgpLikelihood.m and varsgpPredict.m * * The reference paper is * Titsias, Michalis K. * "Variational learning of inducing variables in sparse Gaussian processes." * International Conference on Artificial Intelligence and Statistics. 2009. * */ #include <shogun/machine/gp/VarDTCInferenceMethod.h> #include <shogun/machine/gp/GaussianLikelihood.h> #include <shogun/machine/visitors/ShapeVisitor.h> #include <shogun/mathematics/Math.h> #include <shogun/labels/RegressionLabels.h> #include <shogun/mathematics/eigen3.h> #include <utility> using namespace shogun; using namespace Eigen; VarDTCInferenceMethod::VarDTCInferenceMethod() : SingleSparseInference() { init(); } VarDTCInferenceMethod::VarDTCInferenceMethod(std::shared_ptr<Kernel> kern, std::shared_ptr<Features> feat, std::shared_ptr<MeanFunction> m, std::shared_ptr<Labels> lab, std::shared_ptr<LikelihoodModel> mod, std::shared_ptr<Features> lat) : SingleSparseInference(std::move(kern), std::move(feat), std::move(m), std::move(lab), std::move(mod), std::move(lat)) { init(); } void VarDTCInferenceMethod::init() { m_yy=0.0; m_f3=0.0; m_sigma2=0.0; m_trk=0.0; m_Tmm=SGMatrix<float64_t>(); m_Tnm=SGMatrix<float64_t>(); m_inv_Lm=SGMatrix<float64_t>(); m_inv_La=SGMatrix<float64_t>(); m_Knm_inv_Lm=SGMatrix<float64_t>(); SG_ADD(&m_yy, "yy", "yy"); SG_ADD(&m_f3, "f3", "f3"); SG_ADD(&m_sigma2, "sigma2", "sigma2"); SG_ADD(&m_trk, "trk", "trk"); SG_ADD(&m_Tmm, "Tmm", "Tmm"); SG_ADD(&m_Tnm, "Tnm", "Tnm"); SG_ADD(&m_inv_Lm, "inv_Lm", "inv_Lm"); SG_ADD(&m_inv_La, "inv_La", "inv_La"); SG_ADD(&m_Knm_inv_Lm, "Knm_Inv_Lm", "Knm_Inv_Lm"); } VarDTCInferenceMethod::~VarDTCInferenceMethod() { } void VarDTCInferenceMethod::compute_gradient() { Inference::compute_gradient(); if (!m_gradient_update) { update_deriv(); m_gradient_update=true; update_parameter_hash(); } } void VarDTCInferenceMethod::update() { SG_TRACE("entering"); Inference::update(); update_chol(); update_alpha(); m_gradient_update=false; update_parameter_hash(); SG_TRACE("leaving"); } std::shared_ptr<VarDTCInferenceMethod> VarDTCInferenceMethod::obtain_from_generic( const std::shared_ptr<Inference>& inference) { if (inference==NULL) return NULL; if (inference->get_inference_type()!=INF_KL_SPARSE_REGRESSION) error("Provided inference is not of type CVarDTCInferenceMethod!"); return inference->as<VarDTCInferenceMethod>(); } void VarDTCInferenceMethod::check_members() const { SingleSparseInference::check_members(); require(m_model->get_model_type()==LT_GAUSSIAN, "VarDTC inference method can only use Gaussian likelihood function"); require(m_labels->get_label_type()==LT_REGRESSION, "Labels must be type " "of RegressionLabels"); } SGVector<float64_t> VarDTCInferenceMethod::get_diagonal_vector() { not_implemented(SOURCE_LOCATION); return SGVector<float64_t>(); } float64_t VarDTCInferenceMethod::get_negative_log_marginal_likelihood() { if (parameter_hash_changed()) update(); Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols); Map<VectorXd> eigen_ktrtr_diag(m_ktrtr_diag.vector, m_ktrtr_diag.vlen); //F012 =-(model.n-model.m)*model.Likelihood.logtheta-0.5*model.n*log(2*pi)-(0.5/sigma2)*(model.yy)-sum(log(diag(La))); float64_t neg_f012 = (m_ktru.num_cols - m_ktru.num_rows) * std::log(m_sigma2) / 2.0 + 0.5 * m_ktru.num_cols * std::log(2 * Math::PI) + 0.5 * m_yy / (m_sigma2)-eigen_inv_La.diagonal().array().log().sum(); //F3 = (0.5/sigma2)*(yKnmInvLmInvLa*yKnmInvLmInvLa'); float64_t neg_f3=-m_f3; //model.TrKnn = sum(model.diagKnn); //TrK = - (0.5/sigma2)*(model.TrKnn - sum(diag(C)) ); float64_t neg_trk=-m_trk; //F = F012 + F3 + TrK; //F = - F; return neg_f012+neg_f3+neg_trk; } void VarDTCInferenceMethod::update_chol() { // get the sigma variable from the Gaussian likelihood model auto lik = m_model->as<GaussianLikelihood>(); float64_t sigma=lik->get_sigma(); m_sigma2=sigma*sigma; //m-by-m matrix Map<MatrixXd> eigen_kuu(m_kuu.matrix, m_kuu.num_rows, m_kuu.num_cols); //m-by-n matrix Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); Map<VectorXd> eigen_ktrtr_diag(m_ktrtr_diag.vector, m_ktrtr_diag.vlen); //Lm = chol(model.Kmm + model.jitter*eye(model.m)) LLT<MatrixXd> Luu( eigen_kuu * std::exp(m_log_scale * 2.0) + std::exp(m_log_ind_noise) * MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)); m_inv_Lm=SGMatrix<float64_t>(Luu.rows(), Luu.cols()); Map<MatrixXd> eigen_inv_Lm(m_inv_Lm.matrix, m_inv_Lm.num_rows, m_inv_Lm.num_cols); //invLm = Lm\eye(model.m); eigen_inv_Lm=Luu.matrixU().solve(MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)); m_Knm_inv_Lm=SGMatrix<float64_t>(m_ktru.num_cols, m_ktru.num_rows); Map<MatrixXd> eigen_Knm_inv_Lm(m_Knm_inv_Lm.matrix, m_Knm_inv_Lm.num_rows, m_Knm_inv_Lm.num_cols); // KnmInvLm = model.Knm*invLm; eigen_Knm_inv_Lm = (eigen_ktru.transpose() * std::exp(m_log_scale * 2.0)) * eigen_inv_Lm; m_Tmm=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols); Map<MatrixXd> eigen_C(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols); //C = KnmInvLm'*KnmInvLm; eigen_C=eigen_Knm_inv_Lm.transpose()*eigen_Knm_inv_Lm; m_inv_La=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols); Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols); //A = sigma2*eye(model.m) + C; LLT<MatrixXd> chol_A(m_sigma2*MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)+eigen_C); //La = chol(A); //invLa = La\eye(model.m); eigen_inv_La=chol_A.matrixU().solve(MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)); //L=-invLm*invLm' + sigma2*(invLm*invLa*invLa'*invLm'); m_L=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols); Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols); eigen_L=eigen_inv_Lm*( m_sigma2*eigen_inv_La*eigen_inv_La.transpose()-MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols) )*eigen_inv_Lm.transpose(); //TrK = - (0.5/sigma2)*(model.TrKnn - sum(diag(C)) ); m_trk = -0.5 / (m_sigma2) * (eigen_ktrtr_diag.array().sum() * std::exp(m_log_scale * 2.0) - eigen_C.diagonal().array().sum()); } void VarDTCInferenceMethod::update_alpha() { Map<MatrixXd> eigen_Knm_inv_Lm(m_Knm_inv_Lm.matrix, m_Knm_inv_Lm.num_rows, m_Knm_inv_Lm.num_cols); Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols); Map<MatrixXd> eigen_inv_Lm(m_inv_Lm.matrix, m_inv_Lm.num_rows, m_inv_Lm.num_cols); SGVector<float64_t> y=m_labels->as<RegressionLabels>()->get_labels(); Map<VectorXd> eigen_y(y.vector, y.vlen); SGVector<float64_t> m=m_mean->get_mean_vector(m_features); Map<VectorXd> eigen_m(m.vector, m.vlen); //yKnmInvLm = (model.y'*KnmInvLm); //yKnmInvLmInvLa = yKnmInvLm*invLa; VectorXd y_cor=eigen_y-eigen_m; VectorXd eigen_y_Knm_inv_Lm_inv_La_transpose=eigen_inv_La.transpose()*( eigen_Knm_inv_Lm.transpose()*y_cor); //alpha = invLm*invLa*yKnmInvLmInvLa'; m_alpha=SGVector<float64_t>(m_kuu.num_rows); Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen); eigen_alpha=eigen_inv_Lm*eigen_inv_La*eigen_y_Knm_inv_Lm_inv_La_transpose; m_yy=y_cor.dot(y_cor); //F3 = (0.5/sigma2)*(yKnmInvLmInvLa*yKnmInvLmInvLa'); m_f3=0.5*eigen_y_Knm_inv_Lm_inv_La_transpose.dot(eigen_y_Knm_inv_Lm_inv_La_transpose)/m_sigma2; } void VarDTCInferenceMethod::update_deriv() { Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols); Map<MatrixXd> eigen_inv_Lm(m_inv_Lm.matrix, m_inv_Lm.num_rows, m_inv_Lm.num_cols); Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen); Map<MatrixXd> eigen_L(m_L.matrix, m_L.num_rows, m_L.num_cols); //m-by-n matrix Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); Map<MatrixXd> eigen_C(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols); //m_Tmm=SGMatrix<float64_t>(m_kuu.num_rows, m_kuu.num_cols); m_Tnm=SGMatrix<float64_t>(m_ktru.num_cols, m_ktru.num_rows); Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols); Map<MatrixXd> eigen_Tnm(m_Tnm.matrix, m_Tnm.num_rows, m_Tnm.num_cols); auto lik = m_model->as<GaussianLikelihood>(); float64_t sigma=lik->get_sigma(); m_sigma2=sigma*sigma; //invLmInvLa = invLm*invLa; //invA = invLmInvLa*invLmInvLa'; //yKnmInvA = yKnmInvLmInvLa*invLmInvLa'; //invKmm = invLm*invLm'; //Tmm = sigma2*invA + yKnmInvA'*yKnmInvA; //Tmm = invKmm - Tmm; MatrixXd Tmm=-eigen_L-eigen_alpha*eigen_alpha.transpose(); // Tnm = model.Knm*Tmm; eigen_Tnm = (eigen_ktru.transpose() * std::exp(m_log_scale * 2.0)) * Tmm; //Tmm = Tmm - (invLm*(C*invLm'))/sigma2; eigen_Tmm = Tmm - (eigen_inv_Lm*eigen_C*eigen_inv_Lm.transpose()/m_sigma2); SGVector<float64_t> y=m_labels->as<RegressionLabels>()->get_labels(); Map<VectorXd> eigen_y(y.vector, y.vlen); SGVector<float64_t> m=m_mean->get_mean_vector(m_features); Map<VectorXd> eigen_m(m.vector, m.vlen); //Tnm = Tnm + (model.y*yKnmInvA); eigen_Tnm += (eigen_y-eigen_m)*eigen_alpha.transpose(); } SGVector<float64_t> VarDTCInferenceMethod::get_posterior_mean() { not_implemented(SOURCE_LOCATION); //TODO: implement this method once I get time return SGVector<float64_t>(); } SGMatrix<float64_t> VarDTCInferenceMethod::get_posterior_covariance() { not_implemented(SOURCE_LOCATION); //TODO: implement this method once I get time return SGMatrix<float64_t>(); } SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_likelihood_model( Parameters::const_reference param) { require(param.first == "log_sigma", "Can't compute derivative of " "the nagative log marginal likelihood wrt {}.{} parameter", m_model->get_name(), param.first); SGVector<float64_t> dlik(1); Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen); Map<MatrixXd> eigen_inv_La(m_inv_La.matrix, m_inv_La.num_rows, m_inv_La.num_cols); Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); Map<MatrixXd> eigen_kuu(m_kuu.matrix, m_kuu.num_rows, m_kuu.num_cols); //yKnmInvLmInvLainvLa = yKnmInvLmInvLa*invLa'; //sigma2aux = sigma2*sum(sum(invLa.*invLa)) + yKnmInvLmInvLainvLa*yKnmInvLmInvLainvLa'; float64_t sigma2aux = m_sigma2 * eigen_inv_La.cwiseProduct(eigen_inv_La).array().sum() + eigen_alpha.transpose() * (eigen_kuu * std::exp(m_log_scale * 2.0) + std::exp(m_log_ind_noise) * MatrixXd::Identity(m_kuu.num_rows, m_kuu.num_cols)) * eigen_alpha; //Dlik_neg = - (model.n-model.m) + model.yy/sigma2 - 2*F3 - sigma2aux - 2*TrK; dlik[0]=(m_ktru.num_cols-m_ktru.num_rows)-m_yy/m_sigma2+2.0*m_f3+sigma2aux+2.0*m_trk; return dlik; } SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_inducing_features( Parameters::const_reference param) { //[DXu DXunm] = kernelSparseGradInd(model, Tmm, Tnm); //DXu_neg = DXu + DXunm/model.sigma2; Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols); Map<MatrixXd> eigen_Tnm(m_Tnm.matrix, m_Tnm.num_rows, m_Tnm.num_cols); int32_t dim=m_inducing_features.num_rows; int32_t num_samples=m_inducing_features.num_cols; SGVector<float64_t>deriv_lat(dim*num_samples); deriv_lat.zero(); m_lock.lock(); auto inducing_features=get_inducing_features(); //asymtric part (related to xu and x) m_kernel->init(inducing_features, m_features); for(int32_t lat_idx=0; lat_idx<eigen_Tnm.cols(); lat_idx++) { Map<VectorXd> deriv_lat_col_vec(deriv_lat.vector+lat_idx*dim,dim); //p by n SGMatrix<float64_t> deriv_mat=m_kernel->get_parameter_gradient(param, lat_idx); Map<MatrixXd> eigen_deriv_mat(deriv_mat.matrix, deriv_mat.num_rows, deriv_mat.num_cols); //DXunm/model.sigma2; deriv_lat_col_vec += eigen_deriv_mat * (-std::exp(m_log_scale * 2.0) / m_sigma2 * eigen_Tnm.col(lat_idx)); } //symtric part (related to xu and xu) m_kernel->init(inducing_features, inducing_features); for(int32_t lat_lidx=0; lat_lidx<eigen_Tmm.cols(); lat_lidx++) { Map<VectorXd> deriv_lat_col_vec(deriv_lat.vector+lat_lidx*dim,dim); //p by n SGMatrix<float64_t> deriv_mat=m_kernel->get_parameter_gradient(param, lat_lidx); Map<MatrixXd> eigen_deriv_mat(deriv_mat.matrix, deriv_mat.num_rows, deriv_mat.num_cols); //DXu deriv_lat_col_vec += eigen_deriv_mat * (-std::exp(m_log_scale * 2.0) * eigen_Tmm.col(lat_lidx)); } m_lock.unlock(); return deriv_lat; } SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_inducing_noise( Parameters::const_reference param) { require(param.first == "log_inducing_noise", "Can't compute derivative of " "the nagative log marginal likelihood wrt {}.{} parameter", get_name(), param.first); Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols); SGVector<float64_t> result(1); result[0] = -0.5 * std::exp(m_log_ind_noise) * eigen_Tmm.diagonal().array().sum(); return result; } float64_t VarDTCInferenceMethod::get_derivative_related_cov(SGVector<float64_t> ddiagKi, SGMatrix<float64_t> dKuui, SGMatrix<float64_t> dKui) { Map<VectorXd> eigen_ddiagKi(ddiagKi.vector, ddiagKi.vlen); Map<MatrixXd> eigen_dKuui(dKuui.matrix, dKuui.num_rows, dKuui.num_cols); Map<MatrixXd> eigen_dKui(dKui.matrix, dKui.num_rows, dKui.num_cols); Map<MatrixXd> eigen_Tmm(m_Tmm.matrix, m_Tmm.num_rows, m_Tmm.num_cols); Map<MatrixXd> eigen_Tnm(m_Tnm.matrix, m_Tnm.num_rows, m_Tnm.num_cols); //[Dkern Dkernnm DTrKnn] = kernelSparseGradHyp(model, Tmm, Tnm); //Dkern_neg = 0.5*Dkern + Dkernnm/model.sigma2 - (0.5/model.sigma2)*DTrKnn; float64_t dkern= -0.5*eigen_dKuui.cwiseProduct(eigen_Tmm).sum() -eigen_dKui.cwiseProduct(eigen_Tnm.transpose()).sum()/m_sigma2 +0.5*eigen_ddiagKi.array().sum()/m_sigma2; return dkern; } SGVector<float64_t> VarDTCInferenceMethod::get_derivative_wrt_mean( Parameters::const_reference param) { SGVector<float64_t> result; auto visitor = std::make_unique<ShapeVisitor>(); param.second->get_value().visit(visitor.get()); int64_t len= visitor->get_size(); result=SGVector<float64_t>(len); SGVector<float64_t> y=m_labels->as<RegressionLabels>()->get_labels(); Map<VectorXd> eigen_y(y.vector, y.vlen); SGVector<float64_t> m=m_mean->get_mean_vector(m_features); Map<VectorXd> eigen_m(m.vector, m.vlen); Map<VectorXd> eigen_alpha(m_alpha.vector, m_alpha.vlen); //m-by-n matrix Map<MatrixXd> eigen_ktru(m_ktru.matrix, m_ktru.num_rows, m_ktru.num_cols); for (index_t i=0; i<result.vlen; i++) { SGVector<float64_t> dmu=m_mean->get_parameter_derivative(m_features, param, i); Map<VectorXd> eigen_dmu(dmu.vector, dmu.vlen); result[i] = eigen_dmu.dot( eigen_ktru.transpose() * std::exp(m_log_scale * 2.0) * eigen_alpha + (eigen_m - eigen_y)) / m_sigma2; } return result; } void VarDTCInferenceMethod::register_minimizer(std::shared_ptr<Minimizer> minimizer) { io::warn("The method does not require a minimizer. The provided minimizer will not be used."); }
36.549451
132
0.745941
ShankarNara
c9ffc6fba005eaeffb1a50e23e874db2db42d124
1,287
cpp
C++
graph-source-code/233-C/2345881.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/233-C/2345881.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/233-C/2345881.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #include <set> #include <cmath> #include <vector> #include <string> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; int k, n; char m[110][110]; int main(){ #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif cin >> k; memset(m, 0, sizeof(m)); int l = 1, r = 100; while (r - l > 1){ int m1 = (l + r) / 2; if (m1 * (m1 - 1) * (m1 - 2) / 6 <= k) l = m1; else r = m1; } for (int i = n; i < n + l; i++) for (int j = n; j < n + l; j++) if (i != j) m[i][j] = 1; n = l; k -= l * (l - 1) * (l - 2) / 6; while (k){ l = 1, r = 100; while (r - l > 1){ int m1 = (l + r) / 2; if (m1 * (m1 - 1) / 2 <= k) l = m1; else r = m1; } k -= l * (l - 1) / 2; for (int i = 0; i < l; i++) m[i][n] = 1, m[n][i] = 1; n++; } cout << n << '\n'; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) cout << (char)(m[i][j] + 48); cout << '\n'; } return 0; }
21.098361
47
0.337995
AmrARaouf