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
862c2a5df38117d6c1d365b5fc73f98c9689caa2
3,059
cc
C++
src/bindings/text-writer.cc
sergei-dyshel/superstring
115ade9cc39aeef93e85a43bd8fb6b8affe28c2d
[ "MIT" ]
156
2017-01-20T16:57:42.000Z
2022-03-20T15:45:39.000Z
src/bindings/text-writer.cc
Og-ChRoNiC/superstring
cca27783026fee1d607a2b97d07289e000e1bf53
[ "MIT" ]
50
2016-12-20T02:12:07.000Z
2021-06-16T14:07:56.000Z
src/bindings/text-writer.cc
Og-ChRoNiC/superstring
cca27783026fee1d607a2b97d07289e000e1bf53
[ "MIT" ]
44
2017-01-13T18:23:21.000Z
2022-03-20T15:45:46.000Z
#include "text-writer.h" using std::string; using std::move; using std::u16string; using namespace v8; void TextWriter::init(Local<Object> exports) { Local<FunctionTemplate> constructor_template = Nan::New<FunctionTemplate>(construct); constructor_template->SetClassName(Nan::New<String>("TextWriter").ToLocalChecked()); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); const auto &prototype_template = constructor_template->PrototypeTemplate(); Nan::SetTemplate(prototype_template, Nan::New("write").ToLocalChecked(), Nan::New<FunctionTemplate>(write), None); Nan::SetTemplate(prototype_template, Nan::New("end").ToLocalChecked(), Nan::New<FunctionTemplate>(end), None); Nan::Set(exports, Nan::New("TextWriter").ToLocalChecked(), Nan::GetFunction(constructor_template).ToLocalChecked()); } TextWriter::TextWriter(EncodingConversion &&conversion) : conversion{move(conversion)} {} void TextWriter::construct(const Nan::FunctionCallbackInfo<Value> &info) { Local<String> js_encoding_name; if (!Nan::To<String>(info[0]).ToLocal(&js_encoding_name)) return; Nan::Utf8String encoding_name(js_encoding_name); auto conversion = transcoding_from(*encoding_name); if (!conversion) { Nan::ThrowError((string("Invalid encoding name: ") + *encoding_name).c_str()); return; } TextWriter *wrapper = new TextWriter(move(*conversion)); wrapper->Wrap(info.This()); } void TextWriter::write(const Nan::FunctionCallbackInfo<Value> &info) { auto writer = Nan::ObjectWrap::Unwrap<TextWriter>(info.This()); Local<String> js_chunk; if (Nan::To<String>(info[0]).ToLocal(&js_chunk)) { size_t size = writer->content.size(); writer->content.resize(size + js_chunk->Length()); js_chunk->Write( // Nan doesn't wrap this functionality #if NODE_MAJOR_VERSION >= 12 Isolate::GetCurrent(), #endif reinterpret_cast<uint16_t *>(&writer->content[0]) + size, 0, -1, String::WriteOptions::NO_NULL_TERMINATION ); } else if (info[0]->IsUint8Array()) { auto *data = node::Buffer::Data(info[0]); size_t length = node::Buffer::Length(info[0]); if (!writer->leftover_bytes.empty()) { writer->leftover_bytes.insert( writer->leftover_bytes.end(), data, data + length ); data = writer->leftover_bytes.data(); length = writer->leftover_bytes.size(); } size_t bytes_written = writer->conversion.decode( writer->content, data, length ); if (bytes_written < length) { writer->leftover_bytes.assign(data + bytes_written, data + length); } else { writer->leftover_bytes.clear(); } } } void TextWriter::end(const Nan::FunctionCallbackInfo<Value> &info) { auto writer = Nan::ObjectWrap::Unwrap<TextWriter>(info.This()); if (!writer->leftover_bytes.empty()) { writer->conversion.decode( writer->content, writer->leftover_bytes.data(), writer->leftover_bytes.size(), true ); } } u16string TextWriter::get_text() { return move(content); }
32.892473
118
0.689768
sergei-dyshel
862c334e725df615f51db8ed8870724ea5982cb3
551
hpp
C++
Axis/Renderer/Include/Axis/RendererExport.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-23T14:51:51.000Z
2022-01-23T14:51:51.000Z
Axis/Renderer/Include/Axis/RendererExport.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
null
null
null
Axis/Renderer/Include/Axis/RendererExport.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-10T21:01:54.000Z
2022-01-10T21:01:54.000Z
/// \copyright Simmypeet - Copyright (C) /// This file is subject to the terms and conditions defined in /// file `LICENSE`, which is part of this source code package. #ifndef AXIS_RENDERER_RENDEREREXPORT_HPP #define AXIS_RENDERER_RENDEREREXPORT_HPP #pragma once #include "../../../System/Include/Axis/Config.hpp" /// Portable import / export macro #if defined(BUILD_AXIS_RENDERER) # define AXIS_RENDERER_API AXIS_EXPORT #else # define AXIS_RENDERER_API AXIS_IMPORT #endif #endif // AXIS_RENDERER_RENDEREREXPORT_HPP
25.045455
74
0.740472
SimmyPeet
862c896fcc9f082a8175468d51ee681e60687869
8,521
cc
C++
src/compiler/table_gen.cc
chzchzchz/fsl
2df9e4422995f58e719e730c8974ea77c5196bc6
[ "MIT" ]
1
2019-01-02T18:38:28.000Z
2019-01-02T18:38:28.000Z
src/compiler/table_gen.cc
chzchzchz/fsl
2df9e4422995f58e719e730c8974ea77c5196bc6
[ "MIT" ]
1
2015-04-21T21:38:57.000Z
2015-10-27T01:26:29.000Z
src/compiler/table_gen.cc
chzchzchz/fsl
2df9e4422995f58e719e730c8974ea77c5196bc6
[ "MIT" ]
null
null
null
/* generates tables that tools will use to work with data. */ #include <iostream> #include <string> #include <map> #include <typeinfo> #include "util.h" #include "struct_writer.h" #include "AST.h" #include "type.h" #include "func.h" #include "symtab.h" #include "eval.h" #include "points.h" #include "asserts.h" #include "stat.h" #include "virt.h" #include "reloc.h" #include "repair.h" #include "writepkt.h" #include "table_gen.h" #include "thunk_fieldoffset_cond.h" #include "memotab.h" #include <stdint.h> extern type_list types_list; extern type_map types_map; extern func_list funcs_list; extern const_map constants; extern pointing_list points_list; extern pointing_map points_map; extern assert_map asserts_map; extern assert_list asserts_list; extern stat_map stats_map; extern stat_list stats_list; extern typevirt_map typevirts_map; extern typevirt_list typevirts_list; extern writepkt_list writepkts_list; extern typereloc_map typerelocs_map; extern typereloc_list typerelocs_list; extern repair_list repairs_list; extern repair_map repairs_map; extern MemoTab memotab; using namespace std; void TableGen::genThunksTableBySymtab( const string& table_name, const SymbolTable& st) { StructWriter sw(out, "fsl_rtt_field", table_name + "[]", true); for ( sym_list::const_iterator it = st.begin(); it != st.end(); it++) { const SymbolTableEnt *st_ent; st_ent = *it; sw.beginWrite(); st_ent->getFieldThunk()->genFieldEntry(this); } } void TableGen::genUserFieldsByType(const Type *t) { SymbolTable *st; SymbolTable *st_all; SymbolTable *st_types; SymbolTable *st_complete; st = t->getSymsByUserTypeStrong(); genThunksTableBySymtab( string("__rt_tab_thunks_") + t->getName(), *st); delete st; st_all = t->getSymsStrongOrConditional(); genThunksTableBySymtab( string("__rt_tab_thunksall_") + t->getName(), *st_all); delete st_all; st_types = t->getSymsByUserTypeStrongOrConditional(); genThunksTableBySymtab( string("__rt_tab_thunkstypes_") + t->getName(), *st_types); delete st_types; st_complete = t->getSyms(); genThunksTableBySymtab( string("__rt_tab_thunkcomplete_") + t->getName(), *st_complete); delete st_complete; } void TableGen::genUserFieldTables(void) { for ( type_list::const_iterator it = types_list.begin(); it != types_list.end(); it++) genUserFieldsByType(*it); } void TableGen::genInstanceType(const Type *t) { StructWriter sw(out); SymbolTable *st, *st_all, *st_types, *st_complete; FCall *size_fc; const string tname(t->getName()); st = t->getSymsByUserTypeStrong(); st_all = t->getSymsStrongOrConditional(); st_types = t->getSymsByUserTypeStrongOrConditional(); st_complete = t->getSyms(); assert (st != NULL); size_fc = st->getThunkType()->getSize()->copyFCall(); sw.writeStr("tt_name", tname); sw.write("tt_param_c", t->getParamBufEntryCount()); sw.write("tt_arg_c", t->getNumArgs()); sw.write("tt_size", size_fc->getName()); sw.write("tt_fieldstrong_c", st->size()); sw.write("tt_fieldstrong", "__rt_tab_thunks_" + tname); sw.write("tt_pointsto_c", points_map[tname]->getNumPointing()); sw.write("tt_pointsto", "__rt_tab_pointsto_" + tname); sw.write("tt_assert_c", asserts_map[tname]->getNumAsserts()); sw.write("tt_assert", "__rt_tab_asserts_" + tname); sw.write("tt_stat_c", stats_map[tname]->getNumStat()); sw.write("tt_stat", "__rt_tab_stats_"+tname); sw.write("tt_reloc_c", typerelocs_map[tname]->getNumRelocs()); sw.write("tt_reloc", "__rt_tab_reloc_" + tname); sw.write("tt_fieldall_c", st_all->size()); sw.write("tt_fieldall_thunkoff", "__rt_tab_thunksall_" + tname); sw.write("tt_fieldtypes_c", st_types->size()); sw.write("tt_fieldtypes_thunkoff","__rt_tab_thunkstypes_"+tname); sw.write("tt_virt_c", typevirts_map[tname]->getNumVirts()); sw.write("tt_virt", "__rt_tab_virt_" + tname); sw.write("tt_field_c", st_complete->size()); sw.write("tt_field_table", "__rt_tab_thunkcomplete_" + tname); sw.write("tt_repair_c", repairs_map[tname]->getNumRepairs()); sw.write("tt_repair", "__rt_tab_repair_" + tname); delete size_fc; delete st_complete; delete st_types; delete st_all; delete st; } void TableGen::printExternFunc( const string& fname, const char* return_type, const vector<string>& args) { vector<string>::const_iterator it = args.begin(); out << "extern " << return_type << ' ' << fname << '(' << (*it); for (it++; it != args.end(); it++) out << ", " << (*it); out << ");\n"; } void TableGen::printExternFuncThunk( const std::string& funcname, const char* return_type) { const string args[] = {"const struct fsl_rt_closure*"}; printExternFunc( funcname, return_type, vector<string>(args, args+1)); } void TableGen::printExternFuncThunkParams(const ThunkParams* tp) { const string args[] = { "const struct fsl_rt_closure*", /* parent pointer */ "uint64_t", /* idx */ "uint64_t*", }; FCall *fc; fc = tp->copyFCall(); printExternFunc(fc->getName(), "void", vector<string>(args, args+3)); delete fc; } void TableGen::genExternsFieldsByType(const Type *t) { SymbolTable *st; FCall *fc_type_size; st = t->getSyms(); assert (st != NULL); for ( sym_list::const_iterator it = st->begin(); it != st->end(); it++) { const SymbolTableEnt *st_ent; st_ent = *it; st_ent->getFieldThunk()->genFieldExtern(this); } fc_type_size = st->getThunkType()->getSize()->copyFCall(); printExternFuncThunk(fc_type_size->getName()); delete fc_type_size; } void TableGen::genExternsFields(void) { for ( type_list::const_iterator it = types_list.begin(); it != types_list.end(); it++) genExternsFieldsByType(*it); } void TableGen::genExternsUserFuncs(void) { for ( func_list::const_iterator it = funcs_list.begin(); it != funcs_list.end(); it++) { const Func *f = *it; if (!memotab.canMemoize(f)) continue; out << "extern "; if (f->getRetType() == NULL) out << "uint64_t " << f->getName() << "(void)"; else out << "void " << f->getName() << "(struct fsl_rt_closure*)"; out << ';' << endl; } } void TableGen::genTable_fsl_rt_table(void) { StructWriter sw(out, "fsl_rtt_type", "fsl_rt_table[]"); for ( type_list::iterator it = types_list.begin(); it != types_list.end(); it++) { sw.beginWrite(); genInstanceType(*it); } } void TableGen::genTableHeaders(void) { out << "#include <stdint.h>" << endl; out << "#include \"runtime/runtime.h\"" << endl; } template<class T> void TableGen::genTableWriters(const PtrList<T>& tw_list) { for (auto &t : tw_list) { t->genExterns(this); t->genTables(this); } } template<class T> void TableGen::genTableWriters(const std::list<T*>& tw_list) { for (auto &t : tw_list) { t->genExterns(this); t->genTables(this); } } void TableGen::genScalarConstants(void) { const Type *origin_type; origin_type = types_map["disk"]; assert (origin_type != NULL && "No origin type 'disk' declared"); assert (origin_type->getNumArgs() == 0 && "Type 'disk' should not take parameters"); out << "unsigned int fsl_rtt_entries = "<<types_list.size()<<";\n"; out << "unsigned int fsl_rt_origin_typenum = "; out << origin_type->getTypeNum() << ';' << endl; out << "char fsl_rt_fsname[] = \""; if (constants.count("__FSL_FSNAME") == 0) out << "__FSL_FSNAME"; else { const Id* id; id = dynamic_cast<const Id*>(constants["__FSL_FSNAME"]); out << ((id != NULL) ? id->getName() : "__FSL_FSNAME"); } out << "\";" << endl; out << "int __fsl_mode = "; if (constants.count("__FSL_MODE") == 0) out << "0"; /* mode little endian */ else { const Number* num; num = dynamic_cast<const Number*>(constants["__FSL_MODE"]); out << ((num != NULL) ? num->getValue() : 0); } out << ";" << endl; } void TableGen::genWritePktTables(void) { writepkt_list::const_iterator it; for (it = writepkts_list.begin(); it != writepkts_list.end(); it++) (*it)->genExterns(this); for (it = writepkts_list.begin(); it != writepkts_list.end(); it++) (*it)->genTables(this); } void TableGen::gen(const string& fname) { out.open(fname.c_str()); genTableHeaders(); genScalarConstants(); genExternsFields(); genExternsUserFuncs(); genUserFieldTables(); genTableWriters<Points>(points_list); genTableWriters<Asserts>(asserts_list); genTableWriters<VirtualTypes>(typevirts_list); genTableWriters<Stat>(stats_list); genWritePktTables(); genTableWriters<RelocTypes>(typerelocs_list); genTableWriters<Repairs>(repairs_list); memotab.genTables(this); genTable_fsl_rt_table(); out.close(); }
23.868347
70
0.69405
chzchzchz
862dbd381c687467d22b0b25f68e05d5030ee81b
828
cc
C++
src/engine/assets/audio_manager.cc
ProjectSulphur/ProjectSulphur
cb9ee8298f5020fda4a9130802e72034408f050f
[ "Apache-2.0" ]
11
2017-12-19T14:33:02.000Z
2022-03-26T00:34:48.000Z
src/engine/assets/audio_manager.cc
ProjectSulphur/ProjectSulphur
cb9ee8298f5020fda4a9130802e72034408f050f
[ "Apache-2.0" ]
1
2018-05-28T10:32:32.000Z
2018-05-28T10:32:35.000Z
src/engine/assets/audio_manager.cc
ProjectSulphur/ProjectSulphur
cb9ee8298f5020fda4a9130802e72034408f050f
[ "Apache-2.0" ]
1
2021-01-25T11:31:57.000Z
2021-01-25T11:31:57.000Z
#include "engine/assets/audio_manager.h" #include "engine/audio/audio_bank.h" #include <foundation/io/binary_reader.h> #include <foundation/memory/memory.h> #include <foundation/pipeline-assets/audio.h> #include <foundation/io/filesystem.h> namespace sulphur { namespace engine { //-------------------------------------------------------------------------------- AudioBankData* AudioManager::ImportAsset(const foundation::Path& asset_file) { foundation::BinaryReader reader( foundation::Path(application_->project_directory()) + asset_file); if (reader.is_ok()) { AudioBankData* audio_bank = foundation::Memory::Construct<AudioBankData>(); *audio_bank = reader.Read<foundation::AudioBankData>(); return audio_bank; } return nullptr; } } }
26.709677
86
0.621981
ProjectSulphur
86343790fe7741172d56e0a9292368b43dfe6533
709
cpp
C++
linux/service/source/ErrCode.cpp
elastos/Elastos.Service.CarrierGroup
235904845c2548274e0d87eb29a424716a60cbf8
[ "MIT" ]
null
null
null
linux/service/source/ErrCode.cpp
elastos/Elastos.Service.CarrierGroup
235904845c2548274e0d87eb29a424716a60cbf8
[ "MIT" ]
null
null
null
linux/service/source/ErrCode.cpp
elastos/Elastos.Service.CarrierGroup
235904845c2548274e0d87eb29a424716a60cbf8
[ "MIT" ]
1
2019-08-07T07:55:00.000Z
2019-08-07T07:55:00.000Z
// // Created by luocf on 2019/6/14. // #include <system_error> #include "ErrCode.h" namespace chatrobot { std::string ErrCode::ToString(int errCode) { std::string errMsg; switch (errCode) { case InvalidArgument: errMsg = "InvalidArgument"; break; case StdSystemErrorIndex: errMsg = "StdSystemErrorIndex"; break; } if(errCode < StdSystemErrorIndex) { int stdErrVal = StdSystemErrorIndex - errCode; auto stdErrCode = std::error_code(stdErrVal, std::generic_category()); errMsg = stdErrCode.message(); } return errMsg; } }
23.633333
82
0.551481
elastos
863449e05350490113ac883727fff2a77329627f
742
cpp
C++
plugins/x11input/src/device/valuator/make_absolute.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/x11input/src/device/valuator/make_absolute.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/x11input/src/device/valuator/make_absolute.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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) #include <sge/x11input/device/valuator/absolute.hpp> #include <sge/x11input/device/valuator/make_absolute.hpp> #include <sge/x11input/device/valuator/value.hpp> #include <fcppt/config/external_begin.hpp> #include <X11/extensions/XInput2.h> #include <fcppt/config/external_end.hpp> sge::x11input::device::valuator::absolute sge::x11input::device::valuator::make_absolute(XIValuatorClassInfo const &_info) { return sge::x11input::device::valuator::absolute{ sge::x11input::device::valuator::value{_info.value}}; }
39.052632
80
0.747978
cpreh
86345b61bf4d232435a01bb2225acf34e422e66f
1,067
hpp
C++
include/md/forcefield.hpp
snsinfu/micromd
a886d68d5452800bf342f0db8b477979f9f10a04
[ "BSL-1.0" ]
3
2018-12-06T11:45:56.000Z
2020-10-09T08:23:03.000Z
include/md/forcefield.hpp
snsinfu/micromd
a886d68d5452800bf342f0db8b477979f9f10a04
[ "BSL-1.0" ]
14
2018-12-02T08:16:16.000Z
2020-09-29T18:19:35.000Z
include/md/forcefield.hpp
snsinfu/micromd
a886d68d5452800bf342f0db8b477979f9f10a04
[ "BSL-1.0" ]
null
null
null
// Copyright snsinfu 2018. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef MD_FORCEFIELD_HPP #define MD_FORCEFIELD_HPP // This module defines the interface of forcefield implementations. #include "basic_types.hpp" namespace md { class system; // forcefield is an abstract base class of forcefield classes. // // A forcefield class computes potential energy and forces acting on the // particles in a system. class forcefield { public: virtual ~forcefield() = default; // compute_energy computes the total potential energy of the system for // this forcefield. virtual md::scalar compute_energy(md::system const& system) = 0; // compute_force computes forces acting on each particle in the system // and adds (not assigns) force vectors to given array. virtual void compute_force(md::system const& system, md::array_view<md::vector> forces) = 0; }; } #endif
28.837838
100
0.700094
snsinfu
863524fffb7b903b4b172c469a7f4f11c4fa1c22
4,199
cpp
C++
NbrhdNash/Scenes/scene_Settings.cpp
OlavJDigranes/groupD
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
[ "MIT" ]
null
null
null
NbrhdNash/Scenes/scene_Settings.cpp
OlavJDigranes/groupD
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
[ "MIT" ]
null
null
null
NbrhdNash/Scenes/scene_Settings.cpp
OlavJDigranes/groupD
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
[ "MIT" ]
null
null
null
#include <iostream> #include <thread> #include "LevelSystem.h" #include "scene_Settings.h" #include "scene_MainMenu.h" #include "../lib_ecm/components/cmp_text.h" #include "../game.h" #include "SFML/Window.hpp" #include "SFML/Window/Joystick.hpp" #include <iostream> #include <fstream> #include <stdio.h> using namespace std; using namespace sf; void Settings::Load() { tag = -1; sf::Joystick::Identification joystickID = sf::Joystick::getIdentification(0); auto esc = makeEntity(); esc->setPosition(Vector2f(5, 5)); if (Joystick::isConnected(0)) { auto y = esc->addComponent<ESCTextComponent>("Press Start to exit the game"); } else { auto y = esc->addComponent<ESCTextComponent>("Press ESC to exit the game"); } auto info = makeEntity(); info->setPosition(Vector2f(Engine::getWindowSize().x * 0.3, Engine::getWindowSize().y * 0.2)); if (Joystick::isConnected(0)) { auto i = info->addComponent<TextComponent>("CONTROLS:\nRT for acceleration\nLT for braking\nLeft Joystick for turning\n\nPress BACK to save settings"); } else { auto i = info->addComponent<TextComponent>("CONTROLS:\nW for acceleration\nS for braking\nA for turning left\nD for turning rightz\n\nPress X to save settings"); } auto info2 = makeEntity(); info2->setPosition(Vector2f(Engine::getWindowSize().x * 0.5, Engine::getWindowSize().y * 0.2)); if (Joystick::isConnected(0)) { auto i2 = info2->addComponent<TextComponent>("SELECT RESOLUTION:\nA: 1280 x 720\nY: 1920 x 1080\nX: 2560 x 1440\n\nV-SYNC:\nLB: On\nRB: Off"); } else { auto i2 = info2->addComponent<TextComponent>("SELECT RESOLUTION:\nQ: 1280 x 720\nW: 1920 x 1080\nE: 2560 x 1440\n\nV-SYNC:\nV: On\nB: Off"); } setLoaded(true); } void Settings::UnLoad() { Scene::UnLoad(); } void Settings::Update(const double& dt) { Scene::Update(dt); if (Keyboard::isKeyPressed(Keyboard::Q)) { resTag = 1; imageSetting = "Q "; Settings::UnLoad(); Settings::Load(); } if (Keyboard::isKeyPressed(Keyboard::W)) { resTag = 2; imageSetting = "W "; Settings::UnLoad(); Settings::Load(); } if (Keyboard::isKeyPressed(Keyboard::E)) { resTag = 3; imageSetting = "E "; Settings::UnLoad(); Settings::Load(); } if (Keyboard::isKeyPressed(Keyboard::V)) { Engine::setVsync(true); vsyncSetting = "V "; } if (Keyboard::isKeyPressed(Keyboard::B)) { Engine::setVsync(false); vsyncSetting = "B "; } if (Keyboard::isKeyPressed(Keyboard::X)) { saveSettings(); } if (Joystick::isConnected(0)) { if (sf::Joystick::isButtonPressed(0, 0)) { resTag = 1; imageSetting = "Q "; Settings::UnLoad(); Settings::Load(); } if (sf::Joystick::isButtonPressed(0, 3)) { resTag = 2; imageSetting = "W "; Settings::UnLoad(); Settings::Load(); } if (sf::Joystick::isButtonPressed(0, 2)) { resTag = 3; imageSetting = "E "; Settings::UnLoad(); Settings::Load(); } if (sf::Joystick::isButtonPressed(0, 4)) { Engine::setVsync(true); vsyncSetting = "V "; } if (sf::Joystick::isButtonPressed(0, 5)) { Engine::setVsync(false); vsyncSetting = "B "; } if (sf::Joystick::isButtonPressed(0, 7)) { saveSettings(); } } } void Settings::Render() { Scene::Render(); } void Settings::saveSettings() { settingsFile.open("settings.txt", std::ios_base::out); settingsFile << imageSetting; settingsFile << vsyncSetting; settingsFile.close(); } //Helper function for ingesting file if it exists void Settings::ingestFile() { std::string line; ifstream settingsFileIn; settingsFileIn.open("settings.txt", std::ios_base::in); //checking if file is empty if (settingsFileIn.is_open()) { while (!settingsFileIn.eof()) { line.resize(settingsFileIn.tellg()); settingsFileIn >> line; lines.push_back(line); counter++; } } if (counter-1 == 1) { if (lines[0] == "Q") { imageSetting = lines[0]; } if (lines[0] == "W") { imageSetting = lines[0]; } if (lines[0] == "E") { imageSetting = lines[0]; } if (lines[0] == "V") { vsyncSetting = lines[0]; } if (lines[0] == "B") { vsyncSetting = lines[0]; } } if (counter-1 == 2) { imageSetting = lines[0]; vsyncSetting = lines[1]; } settingsFileIn.close(); }
24.412791
163
0.652536
OlavJDigranes
8636367d660d21365ef92c917705ef5c797ce508
25,150
cpp
C++
src/runtime/Spprintf.cpp
normal-coder/polarphp
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
[ "PHP-3.01" ]
1
2019-01-28T01:33:49.000Z
2019-01-28T01:33:49.000Z
src/runtime/Spprintf.cpp
normal-coder/polarphp
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
[ "PHP-3.01" ]
null
null
null
src/runtime/Spprintf.cpp
normal-coder/polarphp
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
[ "PHP-3.01" ]
null
null
null
// This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2018 polarphp software foundation // Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2018/12/25. /* This is the spprintf implementation. * It has emerged from apache snprintf. See original header: */ /* ==================================================================== * Copyright (c) 1995-1998 The Apache Group. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the Apache Group * for use in the Apache HTTP server project (http://www.apache.org/)." * * 4. The names "Apache Server" and "Apache Group" must not be used to * endorse or promote products derived from this software without * prior written permission. * * 5. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the Apache Group * for use in the Apache HTTP server project (http://www.apache.org/)." * * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY * EXPRESSED 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 APACHE GROUP 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Group and was originally based * on public domain software written at the National Center for * Supercomputing Applications, University of Illinois, Urbana-Champaign. * For more information on the Apache Group and the Apache HTTP server * project, please see <http://www.apache.org/>. * * This code is based on, and used with the permission of, the * SIO stdio-replacement strx_* functions by Panos Tsirigotis * <panos@alumni.cs.colorado.edu> for xinetd. */ #include "polarphp/runtime/internal/DepsZendVmHeaders.h" #include "polarphp/runtime/Spprintf.h" #include "polarphp/runtime/Snprintf.h" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <stddef.h> #include <stdio.h> #include <ctype.h> #include <sys/types.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include <math.h> #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef HAVE_LOCALE_H #include <locale.h> #ifdef ZTS #define LCONV_DECIMAL_POINT (*lconv.decimal_point) #else #define LCONV_DECIMAL_POINT (*lconv->decimal_point) #endif #else #define LCONV_DECIMAL_POINT '.' #endif #define FALSE 0 #define TRUE 1 #define NUL '\0' #define INT_NULL ((int *)0) #define S_NULL const_cast<char *>("(null)") #define S_NULL_LEN 6 #define FLOAT_DIGITS 6 #define EXPONENT_LENGTH 10 #define INS_CHAR(xbuf, ch, is_char) do { \ if ((is_char)) { \ smart_string_appendc((smart_string *)(xbuf), (ch)); \ } else { \ smart_str_appendc((smart_str *)(xbuf), (ch)); \ } \ } while (0); #define INS_STRING(xbuf, str, len, is_char) do { \ if ((is_char)) { \ smart_string_appendl((smart_string *)(xbuf), (str), (len)); \ } else { \ smart_str_appendl((smart_str *)(xbuf), (str), (len)); \ } \ } while (0); #define PAD_CHAR(xbuf, ch, count, is_char) do { \ if ((is_char)) { \ smart_string_alloc(((smart_string *)(xbuf)), (count), 0); \ memset(((smart_string *)(xbuf))->c + ((smart_string *)(xbuf))->len, (ch), (count)); \ ((smart_string *)(xbuf))->len += (count); \ } else { \ smart_str_alloc(((smart_str *)(xbuf)), (count), 0); \ memset(ZSTR_VAL(((smart_str *)(xbuf))->s) + ZSTR_LEN(((smart_str *)(xbuf))->s), (ch), (count)); \ ZSTR_LEN(((smart_str *)(xbuf))->s) += (count); \ } \ } while (0); /* * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions * which can be at most max length of double */ #define NUM_BUF_SIZE PHP_DOUBLE_MAX_LENGTH #define NUM(c) (c - '0') #define STR_TO_DEC(str, num) do { \ num = NUM(*str++); \ while (isdigit((int)*str)) { \ num *= 10; \ num += NUM(*str++); \ if (num >= INT_MAX / 10) { \ while (isdigit((int)*str++)); \ break; \ } \ } \ } while (0) /* * This macro does zero padding so that the precision * requirement is satisfied. The padding is done by * adding '0's to the left of the string that is going * to be printed. */ #define FIX_PRECISION(adjust, precision, s, s_len) do { \ if (adjust) \ while (s_len < (size_t)precision) { \ *--s = '0'; \ s_len++; \ } \ } while (0) #if !HAVE_STRNLEN static size_t strnlen(const char *s, size_t maxlen) { char *r = memchr(s, '\0', maxlen); return r ? r-s : maxlen; } #endif namespace polar { namespace runtime { /* * Do format conversion placing the output in buffer */ static void xbuf_format_converter(void *xbuf, zend_bool is_char, const char *fmt, va_list ap) /* {{{ */ { char *s = nullptr; size_t s_len; int free_zcopy; zval *zvp, zcopy; int min_width = 0; int precision = 0; enum { LEFT, RIGHT } adjust; char pad_char; char prefix_char; double fp_num; wide_int i_num = (wide_int) 0; u_wide_int ui_num = (u_wide_int) 0; char num_buf[NUM_BUF_SIZE]; char char_buf[2]; /* for printing %% and %<unknown> */ #ifdef HAVE_LOCALE_H #ifdef ZTS struct lconv lconv; #else struct lconv *lconv = nullptr; #endif #endif /* * Flag variables */ length_modifier_e modifier; boolean_e alternate_form; boolean_e print_sign; boolean_e print_blank; boolean_e adjust_precision; boolean_e adjust_width; bool_int is_negative; while (*fmt) { if (*fmt != '%') { INS_CHAR(xbuf, *fmt, is_char); } else { /* * Default variable settings */ adjust = RIGHT; alternate_form = print_sign = print_blank = NO; pad_char = ' '; prefix_char = NUL; free_zcopy = 0; fmt++; /* * Try to avoid checking for flags, width or precision */ if (isascii((int)*fmt) && !islower((int)*fmt)) { /* * Recognize flags: -, #, BLANK, + */ for (;; fmt++) { if (*fmt == '-') adjust = LEFT; else if (*fmt == '+') print_sign = YES; else if (*fmt == '#') alternate_form = YES; else if (*fmt == ' ') print_blank = YES; else if (*fmt == '0') pad_char = '0'; else break; } /* * Check if a width was specified */ if (isdigit((int)*fmt)) { STR_TO_DEC(fmt, min_width); adjust_width = YES; } else if (*fmt == '*') { min_width = va_arg(ap, int); fmt++; adjust_width = YES; if (min_width < 0) { adjust = LEFT; min_width = -min_width; } } else adjust_width = NO; /* * Check if a precision was specified */ if (*fmt == '.') { adjust_precision = YES; fmt++; if (isdigit((int)*fmt)) { STR_TO_DEC(fmt, precision); } else if (*fmt == '*') { precision = va_arg(ap, int); fmt++; if (precision < -1) precision = -1; } else precision = 0; if (precision > FORMAT_CONV_MAX_PRECISION) { precision = FORMAT_CONV_MAX_PRECISION; } } else adjust_precision = NO; } else adjust_precision = adjust_width = NO; /* * Modifier check */ switch (*fmt) { case 'L': fmt++; modifier = LM_LONG_DOUBLE; break; case 'I': fmt++; #if SIZEOF_LONG_LONG if (*fmt == '6' && *(fmt+1) == '4') { fmt += 2; modifier = LM_LONG_LONG; } else #endif if (*fmt == '3' && *(fmt+1) == '2') { fmt += 2; modifier = LM_LONG; } else { #ifdef _WIN64 modifier = LM_LONG_LONG; #else modifier = LM_LONG; #endif } break; case 'l': fmt++; #if SIZEOF_LONG_LONG if (*fmt == 'l') { fmt++; modifier = LM_LONG_LONG; } else #endif modifier = LM_LONG; break; case 'z': fmt++; modifier = LM_SIZE_T; break; case 'j': fmt++; #if SIZEOF_INTMAX_T modifier = LM_INTMAX_T; #else modifier = LM_SIZE_T; #endif break; case 't': fmt++; #if SIZEOF_PTRDIFF_T modifier = LM_PTRDIFF_T; #else modifier = LM_SIZE_T; #endif break; case 'p': { char __next = *(fmt+1); if ('d' == __next || 'u' == __next || 'x' == __next || 'o' == __next) { fmt++; modifier = LM_PHP_INT_T; } else { modifier = LM_STD; } } break; case 'h': fmt++; if (*fmt == 'h') { fmt++; } POLAR_FALLTHROUGH; /* these are promoted to int, so no break */ default: modifier = LM_STD; break; } /* * Argument extraction and printing. * First we determine the argument type. * Then, we convert the argument to a string. * On exit from the switch, s points to the string that * must be printed, s_len has the length of the string * The precision requirements, if any, are reflected in s_len. * * NOTE: pad_char may be set to '0' because of the 0 flag. * It is reset to ' ' by non-numeric formats */ switch (*fmt) { case 'Z': { zvp = (zval*) va_arg(ap, zval*); free_zcopy = zend_make_printable_zval(zvp, &zcopy); if (free_zcopy) { zvp = &zcopy; } s_len = Z_STRLEN_P(zvp); s = Z_STRVAL_P(zvp); if (adjust_precision && (size_t)precision < s_len) { s_len = precision; } break; } case 'u': switch(modifier) { default: i_num = (wide_int) va_arg(ap, unsigned int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: i_num = (wide_int) va_arg(ap, unsigned long int); break; case LM_SIZE_T: i_num = (wide_int) va_arg(ap, size_t); break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: i_num = (wide_int) va_arg(ap, u_wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: i_num = (wide_int) va_arg(ap, uintmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: i_num = (wide_int) va_arg(ap, ptrdiff_t); break; #endif case LM_PHP_INT_T: i_num = (wide_int) va_arg(ap, zend_ulong); break; } POLAR_FALLTHROUGH; /* * The rest also applies to other integer formats, so fall * into that case. */ case 'd': POLAR_FALLTHROUGH; case 'i': /* * Get the arg if we haven't already. */ if ((*fmt) != 'u') { switch(modifier) { default: i_num = (wide_int) va_arg(ap, int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: i_num = (wide_int) va_arg(ap, long int); break; case LM_SIZE_T: #if SIZEOF_SSIZE_T i_num = (wide_int) va_arg(ap, ssize_t); #else i_num = (wide_int) va_arg(ap, size_t); #endif break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: i_num = (wide_int) va_arg(ap, wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: i_num = (wide_int) va_arg(ap, intmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: i_num = (wide_int) va_arg(ap, ptrdiff_t); break; #endif case LM_PHP_INT_T: i_num = (wide_int) va_arg(ap, zend_long); break; } } s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative, &num_buf[NUM_BUF_SIZE], &s_len); FIX_PRECISION(adjust_precision, precision, s, s_len); if (*fmt != 'u') { if (is_negative) prefix_char = '-'; else if (print_sign) prefix_char = '+'; else if (print_blank) prefix_char = ' '; } break; case 'o': switch(modifier) { default: ui_num = (u_wide_int) va_arg(ap, unsigned int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: ui_num = (u_wide_int) va_arg(ap, unsigned long int); break; case LM_SIZE_T: ui_num = (u_wide_int) va_arg(ap, size_t); break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: ui_num = (u_wide_int) va_arg(ap, u_wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: ui_num = (u_wide_int) va_arg(ap, uintmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: ui_num = (u_wide_int) va_arg(ap, ptrdiff_t); break; #endif case LM_PHP_INT_T: ui_num = (u_wide_int) va_arg(ap, zend_ulong); break; } s = ap_php_conv_p2(ui_num, 3, *fmt, &num_buf[NUM_BUF_SIZE], &s_len); FIX_PRECISION(adjust_precision, precision, s, s_len); if (alternate_form && *s != '0') { *--s = '0'; s_len++; } break; case 'x': case 'X': switch(modifier) { default: ui_num = (u_wide_int) va_arg(ap, unsigned int); break; case LM_LONG_DOUBLE: goto fmt_error; case LM_LONG: ui_num = (u_wide_int) va_arg(ap, unsigned long int); break; case LM_SIZE_T: ui_num = (u_wide_int) va_arg(ap, size_t); break; #if SIZEOF_LONG_LONG case LM_LONG_LONG: ui_num = (u_wide_int) va_arg(ap, u_wide_int); break; #endif #if SIZEOF_INTMAX_T case LM_INTMAX_T: ui_num = (u_wide_int) va_arg(ap, uintmax_t); break; #endif #if SIZEOF_PTRDIFF_T case LM_PTRDIFF_T: ui_num = (u_wide_int) va_arg(ap, ptrdiff_t); break; #endif case LM_PHP_INT_T: ui_num = (u_wide_int) va_arg(ap, zend_ulong); break; } s = ap_php_conv_p2(ui_num, 4, *fmt, &num_buf[NUM_BUF_SIZE], &s_len); FIX_PRECISION(adjust_precision, precision, s, s_len); if (alternate_form && ui_num != 0) { *--s = *fmt; /* 'x' or 'X' */ *--s = '0'; s_len += 2; } break; case 's': case 'v': s = va_arg(ap, char *); if (s != nullptr) { if (!adjust_precision) { s_len = strlen(s); } else { s_len = strnlen(s, precision); } } else { s = S_NULL; s_len = S_NULL_LEN; } pad_char = ' '; break; case 'f': case 'F': case 'e': case 'E': switch(modifier) { case LM_LONG_DOUBLE: fp_num = (double) va_arg(ap, long double); break; case LM_STD: fp_num = va_arg(ap, double); break; default: goto fmt_error; } if (zend_isnan(fp_num)) { s = const_cast<char *>("nan"); s_len = 3; } else if (zend_isinf(fp_num)) { s = const_cast<char *>("inf"); s_len = 3; } else { #ifdef HAVE_LOCALE_H #ifdef ZTS localeconv_r(&lconv); #else if (!lconv) { lconv = localeconv(); } #endif #endif s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form, (adjust_precision == NO) ? FLOAT_DIGITS : precision, (*fmt == 'f')?LCONV_DECIMAL_POINT:'.', &is_negative, &num_buf[1], &s_len); if (is_negative) prefix_char = '-'; else if (print_sign) prefix_char = '+'; else if (print_blank) prefix_char = ' '; } break; case 'g': case 'k': case 'G': case 'H': switch(modifier) { case LM_LONG_DOUBLE: fp_num = (double) va_arg(ap, long double); break; case LM_STD: fp_num = va_arg(ap, double); break; default: goto fmt_error; } if (zend_isnan(fp_num)) { s = const_cast<char *>("NAN"); s_len = 3; break; } else if (zend_isinf(fp_num)) { if (fp_num > 0) { s = const_cast<char *>("INF"); s_len = 3; } else { s = const_cast<char *>("-INF"); s_len = 4; } break; } if (adjust_precision == NO) precision = FLOAT_DIGITS; else if (precision == 0) precision = 1; /* * * We use &num_buf[ 1 ], so that we have room for the sign */ #ifdef HAVE_LOCALE_H #ifdef ZTS localeconv_r(&lconv); #else if (!lconv) { lconv = localeconv(); } #endif #endif s = php_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]); if (*s == '-') prefix_char = *s++; else if (print_sign) prefix_char = '+'; else if (print_blank) prefix_char = ' '; s_len = strlen(s); if (alternate_form && (strchr(s, '.')) == nullptr) s[s_len++] = '.'; break; case 'c': char_buf[0] = (char) (va_arg(ap, int)); s = &char_buf[0]; s_len = 1; pad_char = ' '; break; case '%': char_buf[0] = '%'; s = &char_buf[0]; s_len = 1; pad_char = ' '; break; case 'n': *(va_arg(ap, int *)) = is_char? (int)((smart_string *)xbuf)->len : (int)ZSTR_LEN(((smart_str *)xbuf)->s); goto skip_output; /* * Always extract the argument as a "char *" pointer. We * should be using "void *" but there are still machines * that don't understand it. * If the pointer size is equal to the size of an unsigned * integer we convert the pointer to a hex number, otherwise * we print "%p" to indicate that we don't handle "%p". */ case 'p': if (sizeof(char *) <= sizeof(u_wide_int)) { ui_num = (u_wide_int)((size_t) va_arg(ap, char *)); s = ap_php_conv_p2(ui_num, 4, 'x', &num_buf[NUM_BUF_SIZE], &s_len); if (ui_num != 0) { *--s = 'x'; *--s = '0'; s_len += 2; } } else { s = const_cast<char *>("%p"); s_len = 2; } pad_char = ' '; break; case NUL: /* * The last character of the format string was %. * We ignore it. */ continue; fmt_error: php_error(E_ERROR, "Illegal length modifier specified '%c' in s[np]printf call", *fmt); /* * The default case is for unrecognized %'s. * We print %<char> to help the user identify what * option is not understood. * This is also useful in case the user wants to pass * the output of format_converter to another function * that understands some other %<char> (like syslog). * Note that we can't point s inside fmt because the * unknown <char> could be preceded by width etc. */ POLAR_FALLTHROUGH; default: char_buf[0] = '%'; char_buf[1] = *fmt; s = char_buf; s_len = 2; pad_char = ' '; break; } if (prefix_char != NUL) { *--s = prefix_char; s_len++; } if (adjust_width && adjust == RIGHT && (size_t)min_width > s_len) { if (pad_char == '0' && prefix_char != NUL) { INS_CHAR(xbuf, *s, is_char); s++; s_len--; min_width--; } PAD_CHAR(xbuf, pad_char, min_width - s_len, is_char); } /* * Print the string s. */ INS_STRING(xbuf, s, s_len, is_char); if (adjust_width && adjust == LEFT && (size_t)min_width > s_len) { PAD_CHAR(xbuf, pad_char, min_width - s_len, is_char); } if (free_zcopy) { zval_ptr_dtor_str(&zcopy); } } skip_output: fmt++; } return; } /* }}} */ void php_printf_to_smart_string(smart_string *buf, const char *format, va_list ap) /* {{{ */ { xbuf_format_converter(buf, 1, format, ap); } void php_printf_to_smart_str(smart_str *buf, const char *format, va_list ap) /* {{{ */ { xbuf_format_converter(buf, 0, format, ap); } } // runtime } // polar
30.04779
151
0.484453
normal-coder
8636c6931c7698a57238c12fd7388e91097d6d4c
5,189
cpp
C++
munin/src/tabbed_panel.cpp
KazDragon/paradice9
bb89ce8bff2f99d2526f45b064bfdd3412feb992
[ "MIT" ]
9
2015-12-16T07:00:39.000Z
2021-05-05T13:29:28.000Z
munin/src/tabbed_panel.cpp
KazDragon/paradice9
bb89ce8bff2f99d2526f45b064bfdd3412feb992
[ "MIT" ]
43
2015-07-18T11:13:15.000Z
2017-07-15T13:18:43.000Z
munin/src/tabbed_panel.cpp
KazDragon/paradice9
bb89ce8bff2f99d2526f45b064bfdd3412feb992
[ "MIT" ]
3
2015-10-09T13:33:35.000Z
2016-07-11T02:23:08.000Z
// ========================================================================== // Munin Tabbed Panel. // // Copyright (C) 2013 Matthew Chaplain, All Rights Reserved. // // Permission to reproduce, distribute, perform, display, and to prepare // derivitive works from this file under the following conditions: // // 1. Any copy, reproduction or derivitive work of any part of this file // contains this copyright notice and licence in its entirety. // // 2. The rights granted to you under this license automatically terminate // should you attempt to assert any patent claims against the licensor // or contributors, which in any way restrict the ability of any party // from using this software or portions thereof in any form under the // terms of this license. // // Disclaimer: 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 "munin/tabbed_panel.hpp" #include "munin/card.hpp" #include "munin/container.hpp" #include "munin/framed_component.hpp" #include "munin/grid_layout.hpp" #include "munin/tabbed_frame.hpp" namespace munin { // ========================================================================== // TABBED_PANEL::IMPLEMENTATION STRUCTURE // ========================================================================== struct tabbed_panel::impl { std::shared_ptr<card> card_; std::shared_ptr<tabbed_frame> frame_; // ====================================================================== // TAB_SELECTED // ====================================================================== void tab_selected(std::string const &text) { card_->select_face(text); } // ====================================================================== // FOCUS_CHANGE // ====================================================================== void focus_change() { frame_->set_highlight(card_->has_focus() || frame_->has_focus()); } }; // ========================================================================== // CONSTRUCTOR // ========================================================================== tabbed_panel::tabbed_panel() : pimpl_(new impl) { pimpl_->card_ = make_card(); pimpl_->frame_ = make_tabbed_frame(); auto inner = make_framed_component(pimpl_->frame_, pimpl_->card_); auto content = get_container(); content->set_layout(make_grid_layout(1, 1)); content->add_component(inner); pimpl_->frame_->on_tab_selected.connect( [wpthis=std::weak_ptr<impl>(pimpl_)] (auto idx) { auto pthis = wpthis.lock(); if (pthis) { pthis->tab_selected(idx); } }); auto focus_callback = [wpthis=std::weak_ptr<impl>(pimpl_)] { auto pthis = wpthis.lock(); if (pthis) { pthis->focus_change(); } }; pimpl_->frame_->on_focus_set.connect(focus_callback); pimpl_->frame_->on_focus_lost.connect(focus_callback); pimpl_->card_->on_focus_set.connect(focus_callback); pimpl_->card_->on_focus_lost.connect(focus_callback); } // ========================================================================== // DESTRUCTOR // ========================================================================== tabbed_panel::~tabbed_panel() { } // ========================================================================== // INSERT_TAB // ========================================================================== void tabbed_panel::insert_tab( std::string const &text, std::shared_ptr<component> const &comp, boost::optional<odin::u32> index /*= optional<u32>()*/) { pimpl_->card_->add_face(comp, text); pimpl_->frame_->insert_tab(text, index); if (pimpl_->card_->get_number_of_faces() == 1) { pimpl_->card_->select_face(text); } } // ========================================================================== // REMOVE_TAB // ========================================================================== void tabbed_panel::remove_tab(odin::u32 index) { pimpl_->frame_->remove_tab(index); } // ========================================================================== // MAKE_TABBED_PANEL // ========================================================================== std::shared_ptr<tabbed_panel> make_tabbed_panel() { return std::make_shared<tabbed_panel>(); } }
35.541096
78
0.45847
KazDragon
8639048aa53cb722105ffc8a6d34f028d4855f29
2,062
hpp
C++
sxe/include/sxe/pc/PcInputManager.hpp
Spidey01/sxe
60a91e594f1460115f565b097f8133c324af6f1c
[ "Zlib" ]
null
null
null
sxe/include/sxe/pc/PcInputManager.hpp
Spidey01/sxe
60a91e594f1460115f565b097f8133c324af6f1c
[ "Zlib" ]
null
null
null
sxe/include/sxe/pc/PcInputManager.hpp
Spidey01/sxe
60a91e594f1460115f565b097f8133c324af6f1c
[ "Zlib" ]
null
null
null
#ifndef SXE_PC_PCINPUTMANAGER__HPP #define SXE_PC_PCINPUTMANAGER__HPP /*- * Copyright (c) 2012-current, Terry Mathew Poulin <BigBoss1964@gmail.com> * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from the * use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must * not claim that you wrote the original software. If you use this * software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must * not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ #include <sxe/api.hpp> #include <sxe/input/InputManager.hpp> struct GLFWwindow; namespace sxe { namespace pc { class SXE_PUBLIC PcInputManager : public sxe::input::InputManager { public: /** Creates an InputManager for PC. */ PcInputManager(); virtual ~PcInputManager(); bool uninitialize() override; void poll() override; /** Callback for GLFW key events. * * @param window The window that received the event. * @param key The keyboard key that was pressed or released. * @param scancode The system-specific scancode of the key. * @param action GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT. * @param mods Bit field describing which modifier keys were held down */ static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); private: static const string_type TAG; bool mCallbackSet; }; } } #endif // SXE_PC_PCINPUTMANAGER__HPP
31.723077
98
0.692532
Spidey01
863917c98697564a59eea3d227901fc2de184cfc
10,843
hpp
C++
source/AsioExpress/EventHandling/ResourceCache.hpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/EventHandling/ResourceCache.hpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/EventHandling/ResourceCache.hpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
// Copyright Ross MacGregor 2013 // 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) #pragma once #include <vector> #include <map> #include <set> #include <boost/shared_ptr.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include "AsioExpressError/CallStack.hpp" #include "AsioExpress/CompletionHandler.hpp" #include "AsioExpress/ErrorCodes.hpp" #include "AsioExpress/Timer/Timer.hpp" #include "AsioExpress/EventHandling/ResourceCachePrivate/CacheRequest.hpp" #include "AsioExpress/EventHandling/ResourceCachePrivate/CacheUpdateProcessor.hpp" #include "AsioExpress/EventHandling/ResourceCachePrivate/AddResourceItemsProcessor.hpp" namespace AsioExpress { template<typename R, typename K = int> class ResourceCache { public: typedef R ResourceItem; typedef K Key; typedef boost::shared_ptr<ResourceItem> ResourceItemPointer; ResourceCache(); /// /// Determines the currently active caches and their sizes. You need to call /// this to properly initialize the resource cache and perhaps occasionally /// to remove caches that are no longer in use. /// @param completionHandler The completion hander is called when the /// operation is complete. /// void AsyncUpdate( CompletionHandler completionHandler); /// /// Gets a resource item from the resource cache. The particular cache to /// use is identified by the key. /// @param key Identifies the cache to rerieve the item. /// @param item A pointer to a resource item. This item will /// be set to a valid resource item if the operation /// successfully completes. /// @param waitTimer How long to wait to receive a resource item. /// @param completionHandler The completion hander is called when the /// operation is complete. /// void AsyncGet( Key key, ResourceItemPointer item, TimerPointer waitTimer, CompletionHandler completionHandler); /// /// Gets a resource item from the resource cache. Use this if you do not need /// multiple resource caches. /// /// @param item A pointer to a resource item. This item will /// be set to a valid resource item if the operation /// successfully completes. /// @param waitTimer How long to wait to receive a resource item. /// @param completionHandler The completion hander is called when the /// operation is complete. /// void AsyncGet( ResourceItemPointer item, TimerPointer waitTimer, CompletionHandler completionHandler); /// /// Notify the resource cache that items have been added. /// @param key Identifies the cache. /// @param count The number of resoure items added to the cache. /// void Add(Key key, int count); /// /// Notify the resource cache that items have been added. Use this if you do /// not need multiple resource caches. /// @param count The number of resoure items added to the cache. /// void Add(int count); /// /// Gets the size of a resource cache. /// @param key Identifies the cache. /// unsigned int GetCacheSize(Key key) const; /// /// This method cancels any pending operations on all caches. If /// AsyncGet is called on a canceled cache an operation aborted error /// is returned immediately. /// void ShutDown(); public: class CacheSize { public: CacheSize(Key key, unsigned int size): m_key(key), m_size(size) {} Key GetKey() { return m_key; } unsigned int GetSize() { return m_size; } bool operator==(CacheSize const & that) const { return m_key == that.m_key && m_size == that.m_size; } private: Key m_key; unsigned int m_size; }; /// /// Class used to update the active resource caches. /// class CacheUpdate { public: typedef std::vector<CacheSize> CacheSizes; typedef typename CacheSizes::iterator Iterator; void SetSize(Key key, unsigned int size) { m_sizes.push_back(CacheSize(key,size)); } Iterator Begin() { return m_sizes.begin(); } Iterator End() {return m_sizes.end(); } bool operator==(CacheUpdate const & that) const { return m_sizes == that.m_sizes; } bool operator!=(CacheUpdate const & that) const { return !operator==(that); } private: CacheSizes m_sizes; }; typedef boost::shared_ptr<CacheUpdate> CacheUpdatePointer; protected: /// /// This virtual method must be implemented by derived classes. It is used /// to extract the resource item from implemenattion defined storage. /// @param key Identifies the cache to rerieve the item. /// @param item A pointer to a resource item. This item will /// be set to a valid resource item if the operation /// successfully completes. /// @param completionHandler The completion hander is called when the /// operation is complete. /// virtual void AsyncRemoveItem( Key key, ResourceItemPointer item, CompletionHandler completionHandler) = 0; /// /// This virtual method must be implemented by derived classes. It is used /// to determine the currently active caches and their sizes. You need to call /// this to properly initialize the resource cache and occasionally to remove /// caches that are no longer in use. /// Call update->SetSize(key,size) to update cache size of active resource /// caches. /// @param update The cache update object used to update the /// resource cache information. /// @param completionHandler The completion hander is called when the /// operation is complete. /// virtual void AsyncUpdateAllItems( CacheUpdatePointer update, CompletionHandler completionHandler) = 0; /// /// If an error occurs as a result of an Add() operation this virtual method /// is called for the derived class to handle. /// virtual void ErrorHandler( AsioExpress::Error error) = 0; private: typedef ResourceCachePrivate::CacheRequest<ResourceItem, Key> Request; typedef std::vector<Request> Requests; typedef boost::shared_ptr<Requests> RequestsPointer; typedef std::map<Key,int> ItemCount; typedef boost::shared_ptr<ItemCount> ItemCountPointer; void Timeout(AsioExpress::Error error, ResourceItemPointer item); void ReturnError(AsioExpress::Error error, ResourceItemPointer item); bool CanDelete(Request const & request, Key key); RequestsPointer m_requests; ItemCountPointer m_itemCount; bool m_isShutDown; }; template<typename R, typename K> ResourceCache<R,K>::ResourceCache() : m_requests(new Requests), m_itemCount(new ItemCount), m_isShutDown(false) { } template<typename R, typename K> void ResourceCache<R,K>::AsyncUpdate( CompletionHandler completionHandler) { ResourceCachePrivate::CacheUpdateProcessor<CacheUpdate, ItemCount> proc( m_itemCount, boost::bind(&ResourceCache<R,K>::AsyncUpdateAllItems, this, _1, _2), completionHandler); proc(); } template<typename R, typename K> void ResourceCache<R,K>::AsyncGet( Key key, ResourceItemPointer item, TimerPointer waitTimer, CompletionHandler completionHandler) { // If the event has been canceled return operation aborted immediately. if ( m_isShutDown ) { completionHandler(Error(boost::asio::error::operation_aborted)); return; } if ((*m_itemCount)[key] > 0) { --(*m_itemCount)[key]; AsyncRemoveItem(key, item, completionHandler); return; } // Queue this event to be handled. // waitTimer->AsyncWait(boost::bind(&ResourceCache<R,K>::Timeout, this, _1, item)); m_requests->push_back( Request(key, item, completionHandler, waitTimer)); } template<typename R, typename K> void ResourceCache<R,K>::AsyncGet( ResourceItemPointer item, TimerPointer waitTimer, CompletionHandler completionHandler) { AsyncGet(Key(), item, waitTimer, completionHandler); } template<typename R, typename K> void ResourceCache<R,K>::Add(Key key, int count) { (*m_itemCount)[key] += count; ResourceCachePrivate::AddResourceItemsProcessor<ResourceItem, Key> proc( key, m_requests, m_itemCount, boost::bind(&ResourceCache<R,K>::AsyncRemoveItem, this, _1, _2, _3), boost::bind(&ResourceCache<R,K>::ErrorHandler, this, _1)); proc(); } template<typename R, typename K> void ResourceCache<R,K>::Add(int count) { Add(Key(), count); } //template<typename R, typename K> //void ResourceCache<R,K>::Delete(Key key) //{ // Requests::iterator begin = m_requests->begin(); // Requests::iterator end = m_requests->end(); // Requests::iterator new_end = std::remove_if( // begin, // end, // boost::bind(&ResourceCache<R,K>::CanDelete, this, _1, key)); // // m_requests->erase(new_end, end); // // m_itemCount->erase(key); //} template<typename R, typename K> unsigned int ResourceCache<R,K>::GetCacheSize(Key key) const { return (*m_itemCount)[key]; } template<typename R, typename K> void ResourceCache<R,K>::ShutDown() { // Indicate that this event is canceled. m_isShutDown = true; typename Requests::iterator request = m_requests->begin(); typename Requests::iterator end = m_requests->end(); for(; request != end; ++request) { request->timer->Stop(); } } template<typename R, typename K> void ResourceCache<R,K>::Timeout(AsioExpress::Error error, ResourceItemPointer item) { ReturnError(error, item); } template<typename R, typename K> void ResourceCache<R,K>::ReturnError(AsioExpress::Error error, ResourceItemPointer item) { typename Requests::iterator request = std::find(m_requests->begin(), m_requests->end(), item); if (request != m_requests->end()) { CompletionHandler handler(request->completionHandler); m_requests->erase(request); if (error) handler(error); else handler(Error(AsioExpress::ErrorCode::ResourceCacheTimeout)); } } template<typename R, typename K> bool ResourceCache<R,K>::CanDelete(Request const & request, Key key) { return request.key == key; } } // namespace AsioExpress
32.464072
107
0.654063
suhao
863c7297bce9c86eb92462b56ef98b53d436b741
3,985
cpp
C++
activemq-cpp/src/test/activemq/util/IdGeneratorTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
87
2015-03-02T17:58:20.000Z
2022-02-11T02:52:52.000Z
activemq-cpp/src/test/activemq/util/IdGeneratorTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
3
2017-05-10T13:16:08.000Z
2019-01-23T20:21:53.000Z
activemq-cpp/src/test/activemq/util/IdGeneratorTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
71
2015-04-28T06:04:04.000Z
2022-03-15T13:34:06.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "IdGeneratorTest.h" #include <activemq/util/IdGenerator.h> #include <decaf/lang/Thread.h> using namespace activemq; using namespace activemq::util; using namespace decaf; using namespace decaf::lang; //////////////////////////////////////////////////////////////////////////////// namespace { class CreateIdThread : public Thread { public: bool failed; CreateIdThread() : failed( false ) {} public: virtual void run() { try{ IdGenerator idGen; CPPUNIT_ASSERT( idGen.generateId() != "" ); CPPUNIT_ASSERT( idGen.generateId() != "" ); std::string id1 = idGen.generateId(); std::string id2 = idGen.generateId(); CPPUNIT_ASSERT( id1 != id2 ); std::size_t idPos = id1.find("ID:"); CPPUNIT_ASSERT( idPos == 0 ); std::size_t firstColon = id1.find(':'); std::size_t lastColon = id1.rfind(':'); CPPUNIT_ASSERT( firstColon != lastColon ); CPPUNIT_ASSERT( ( lastColon - firstColon ) > 1 ); } catch(...) { failed = true; } } }; } //////////////////////////////////////////////////////////////////////////////// IdGeneratorTest::IdGeneratorTest() { } //////////////////////////////////////////////////////////////////////////////// IdGeneratorTest::~IdGeneratorTest() { } //////////////////////////////////////////////////////////////////////////////// void IdGeneratorTest::testConstructor1() { IdGenerator idGen; CPPUNIT_ASSERT( idGen.generateId() != "" ); CPPUNIT_ASSERT( idGen.generateId() != "" ); } //////////////////////////////////////////////////////////////////////////////// void IdGeneratorTest::testConstructor2() { IdGenerator idGen( "TEST-PREFIX" ); std::string id = idGen.generateId(); std::size_t pos = id.find( "TEST-PREFIX" ); CPPUNIT_ASSERT( pos != std::string::npos ); } //////////////////////////////////////////////////////////////////////////////// void IdGeneratorTest::testCompare() { IdGenerator idGen; std::string id1 = idGen.generateId(); std::string id2 = idGen.generateId(); CPPUNIT_ASSERT( IdGenerator::compare( id1, id1 ) == 0 ); CPPUNIT_ASSERT( IdGenerator::compare( id1, id2 ) < 0 ); CPPUNIT_ASSERT( IdGenerator::compare( id2, id1 ) > 0 ); } //////////////////////////////////////////////////////////////////////////////// void IdGeneratorTest::testThreadSafety() { bool failed = false; static const int COUNT = 50; std::vector<CreateIdThread*> threads; for( int i = 0; i < COUNT; i++ ) { threads.push_back( new CreateIdThread ); } for( int i = 0; i < COUNT; i++ ) { threads[i]->start(); } for( int i = 0; i < COUNT; i++ ) { threads[i]->join(); } for( int i = 0; i < COUNT; i++ ) { if( !failed ) { threads[i]->failed ? failed = true : failed = false; } delete threads[i]; } CPPUNIT_ASSERT_MESSAGE( "One of the Thread Tester failed", !failed ); }
27.482759
80
0.517942
novomatic-tech
86401129457fcbf250bf9a7419dd6cdc1a1ec5ce
5,602
cpp
C++
base/src/easywsclient/AndroidImplSockets.cpp
djdron/gamesparks-cpp-base
00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8
[ "Apache-2.0" ]
7
2019-07-11T02:05:32.000Z
2020-11-01T18:57:51.000Z
base/src/easywsclient/AndroidImplSockets.cpp
djdron/gamesparks-cpp-base
00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8
[ "Apache-2.0" ]
3
2019-02-26T15:59:03.000Z
2019-06-04T10:46:07.000Z
base/src/easywsclient/AndroidImplSockets.cpp
djdron/gamesparks-cpp-base
00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8
[ "Apache-2.0" ]
6
2020-05-18T08:44:47.000Z
2022-02-26T12:18:17.000Z
#include "GameSparks/GSPlatformDeduction.h" #include "easywsclient/easywsclient.hpp" #if (GS_TARGET_PLATFORM == GS_PLATFORM_ANDROID) #include <mbedtls/entropy.h> #include <mbedtls/ctr_drbg.h> #include <mbedtls/net.h> #include <mbedtls/error.h> #include <mbedtls/platform.h> #include <mbedtls/debug.h> #include <cassert> #include <cstdio> #include <iostream> #include <string.h> #include "GameSparks/GSLeakDetector.h" #include "GameSparks/GSUtil.h" #include "easywsclient/CertificateStore.hpp" #if defined(__UNREAL__) int GameSparks::Util::CertificateStore::numCerts = 0; unsigned char *GameSparks::Util::CertificateStore::pCertsEncoded = NULL; int *GameSparks::Util::CertificateStore::pCertsLength = NULL; #endif class BaseSocket; class TCPSocket : public BaseSocket { private: bool is_connected; volatile bool is_aborted; protected: mbedtls_net_context net; public: TCPSocket() :is_connected(false), is_aborted(false) { mbedtls_net_init(&net); } virtual ~TCPSocket() { mbedtls_net_free(&net); } virtual bool connect(const char *host, short port) { if (is_connected) return true; char port_str[8]; snprintf(port_str, 8, "%hu", port); int res = mbedtls_net_connect(&net, host, port_str, MBEDTLS_NET_PROTO_TCP); if (res != 0) { set_errstr(res); close(); return false; } if (is_aborted) { set_errstr("connection aborted!"); return false; } is_connected = true; return true; } virtual void close() { is_connected = false; } virtual int send(const char *buf, size_t siz) { if (is_aborted) return MBEDTLS_ERR_NET_INVALID_CONTEXT; return mbedtls_net_send(&net, (unsigned char *)buf, siz); } virtual int recv(char *buf, size_t siz) { if (is_aborted) return MBEDTLS_ERR_NET_INVALID_CONTEXT; return mbedtls_net_recv(&net, (unsigned char *)buf, siz); } virtual void set_blocking(bool should_block) { assert(is_connected); if (!is_connected || is_aborted) return; if (should_block) mbedtls_net_set_block(&net); else mbedtls_net_set_nonblock(&net); } virtual void abort() { is_aborted = true; is_connected = false; mbedtls_net_free(&net); mbedtls_net_init(&net); } }; class TLSSocket : public TCPSocket { private: bool is_connected; mbedtls_ssl_context ssl; mbedtls_ssl_config conf; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; static void debug_print(void *ctx, int level, const char *file, int line, const char *str) { ((void)level); mbedtls_fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str); //fflush((FILE *)ctx); } public: TLSSocket() :is_connected(false) { //mbedtls_debug_set_threshold( 1000 ); mbedtls_ssl_init(&ssl); mbedtls_ssl_config_init(&conf); mbedtls_ctr_drbg_init(&ctr_drbg); mbedtls_entropy_init(&entropy); } virtual ~TLSSocket() { mbedtls_ssl_free(&ssl); mbedtls_ssl_config_free(&conf); mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); } virtual bool connect(const char *host, short port) { if (is_connected) return true; if (!TCPSocket::connect(host, port)) { return false; } int res = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0); res = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if (res != 0) { set_errstr(res); close(); return false; } mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE); // this performs platform specific initialisation by retrieving the certificate store from the OS. // if implemented for this platform, it also sets mbedtls_ssl_conf_authmode to MBEDTLS_SSL_VERIFY_REQUIRED res = GameSparks::Util::CertificateStore::setup(conf); if (res != 0) { set_errstr(res); close(); return false; } mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg); mbedtls_ssl_conf_dbg(&conf, debug_print, stderr); res = mbedtls_ssl_setup(&ssl, &conf); if (res != 0) { set_errstr(res); close(); return false; } res = mbedtls_ssl_set_hostname(&ssl, host); if (res != 0) { set_errstr(res); close(); return false; } mbedtls_ssl_set_bio(&ssl, &net, mbedtls_net_send, mbedtls_net_recv, 0);// , mbedtls_net_recv_timeout); do res = mbedtls_ssl_handshake(&ssl); while (res == MBEDTLS_ERR_SSL_WANT_READ || res == MBEDTLS_ERR_SSL_WANT_WRITE); if (res != 0) { set_errstr(res); close(); return false; } uint32_t flags; if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0) { char vrfy_buf[512]; mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", flags); set_errstr(vrfy_buf); close(); return false; } is_connected = true; return true; } virtual void close() { TCPSocket::close(); is_connected = false; } virtual int send(const char *buf, size_t siz) { return mbedtls_ssl_write(&ssl, (unsigned char *)buf, siz); /*int ret = 0; do ret = mbedtls_ssl_write(&ssl, (unsigned char *)buf, siz); while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); if (ret < 0) set_errstr(ret); return ret;*/ } virtual int recv(char *buf, size_t siz) { return mbedtls_ssl_read(&ssl, (unsigned char *)buf, siz); /*int ret = 0; do ret = mbedtls_ssl_read(&ssl, (unsigned char *)buf, siz); while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); if (ret < 0) set_errstr(ret); return ret;*/ } }; BaseSocket *BaseSocket::create(bool useSSL) { if (useSSL) { return new TLSSocket(); } else { return new TCPSocket(); } } #endif
21.546154
108
0.704927
djdron
8640f84460b28358c1aacc3e474e11cf4d870c7e
165
cpp
C++
misc/misc/misc/test5.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
misc/misc/misc/test5.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
misc/misc/misc/test5.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<cstdio> main() { FILE *fp; char x[999]; freopen("CON","w",stdout); while(1) { scanf("%s",&x); printf("%s\n",x); } }
12.692308
30
0.424242
dk00
864c3ae95b169486e26bf405daace1d0f4e7a93c
1,407
hpp
C++
modules/core/restructuring/include/nt2/core/functions/ctranspose.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
2
2016-09-14T00:23:53.000Z
2018-01-14T12:51:18.000Z
modules/core/restructuring/include/nt2/core/functions/ctranspose.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/core/restructuring/include/nt2/core/functions/ctranspose.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_CORE_FUNCTIONS_CTRANSPOSE_HPP_INCLUDED #define NT2_CORE_FUNCTIONS_CTRANSPOSE_HPP_INCLUDED /*! * \file * \brief Defines and implements the nt2::ctranspose function */ #include <nt2/include/functor.hpp> namespace nt2 { namespace tag { struct ctranspose_ : ext::elementwise_<ctranspose_> { typedef ext::elementwise_<ctranspose_> parent; }; } //============================================================================ /*! * conjugate and transpose a matrix. On real matrice this is just transpose * * \param xpr 2D table (must verify is_matrix(a)) */ //============================================================================ NT2_FUNCTION_IMPLEMENTATION(nt2::tag::ctranspose_, ctranspose, 1) NT2_FUNCTION_IMPLEMENTATION(nt2::tag::ctranspose_, ctrans, 1) NT2_FUNCTION_IMPLEMENTATION(nt2::tag::ctranspose_, ct , 1) } #endif
31.977273
80
0.527363
pbrunet
864e9604f4ed17b0987e1fe2e820882fe20f0e11
17,996
cpp
C++
scripts/da_cratemanager.cpp
mpforums/RenSharp
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
[ "Apache-2.0" ]
1
2021-10-04T02:34:33.000Z
2021-10-04T02:34:33.000Z
scripts/da_cratemanager.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
9
2019-07-03T19:19:59.000Z
2020-03-02T22:00:21.000Z
scripts/da_cratemanager.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
2
2019-08-14T08:37:36.000Z
2020-09-29T06:44:26.000Z
/* Renegade Scripts.dll Dragonade Crate Manager Copyright 2017 Whitedragon, Tiberian Technologies This file is part of the Renegade scripts.dll The Renegade scripts.dll is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. See the file COPYING for more details. In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence. Only the source code to the module(s) containing the licenced code has to be released. */ #include "general.h" #include "scripts.h" #include "engine.h" #include "engine_da.h" #include "da.h" #include "da_crate.h" #include "da_cratemanager.h" #include "da_settings.h" #include "da_player.h" #include "da_log.h" #include "da_game.h" #include "da_gameobj.h" #include "SpawnerClass.h" #include "SpawnerDefClass.h" #include "GameObjManager.h" #pragma warning(disable: 4073) #pragma init_seg(lib) DynamicVectorClass <DACrateFactoryClass*> DACrateManager::Crates; DynamicVectorClass <DACrateModifierFactoryClass*> DACrateManager::CrateModifiers; float DACrateManager::Odds = 0; void DACrateManager::Static_Init() { DASettingsManager::Add_Settings("da_crates.ini"); } void DACrateManager::Add_Crate(DACrateFactoryClass *Factory) { for (int i = 0;i < Crates.Count();i++) { if (!_stricmp(Crates[i]->Get_Name(),Factory->Get_Name())) { Crates.Delete(i); break; } } Crates.Add(Factory); } void DACrateManager::Add_Crate_Modifier(DACrateModifierFactoryClass *Factory) { for (int i = 0;i < CrateModifiers.Count();i++) { if (!_stricmp(CrateModifiers[i]->Get_Name(),Factory->Get_Name())) { CrateModifiers.Delete(i); break; } } CrateModifiers.Add(Factory); } DACrateClass *DACrateManager::Get_Crate(const char *Name) { Iterate_Crates(Crate,i) if (!_stricmp(Crate->Get_Name(),Name)) { return Crate; } } return 0; } DACrateModifierClass *DACrateManager::Create_Crate_Modifier(const char *Name,const char *Parameters) { for (int i = 0;i < CrateModifiers.Count();i++) { if (!_stricmp(CrateModifiers[i]->Get_Name(),Name)) { return CrateModifiers[i]->Create(Parameters); } } return 0; } void DACrateManager::Calculate_Odds(cPlayer *Player) { Odds = 0; float BaseOdds = 0; float ModifiedOdds = 0; Iterate_Crates(Crate,i) //Apply modifiers. if (Crate->Check_Type(Player)) { Crate->Calculate_Odds(Player); BaseOdds += Crate->Get_Base_Odds(); ModifiedOdds += Crate->Get_Modified_Odds(); } } if (BaseOdds != ModifiedOdds) { //The odds difference from modified crates needs to be taken from crates with greater or equal base odds. Iterate_Crates(Crate,i) //If this is not done the total odds will increase which will lead to the odds of other crates being unitentionally affected. if (Crate->Check_Type(Player) && Crate->Get_Modified_Odds() != Crate->Get_Base_Odds()) { //This crate has modified odds. float OddsDifference = Crate->Get_Base_Odds()-Crate->Get_Modified_Odds(); //Get the difference between base odds and modified odds. float OddsGreater = 0; int OddsEqual = 0; if (OddsDifference > 0 && Crate->Get_Final_Odds() && !Crate->Get_Cap_Odds()) { OddsEqual--; } Iterate_Crates(Crate2,x) //Add up the base odds of all crates with greater or equal base odds and not disabled(0 modified odds). if (Crate2->Check_Type(Player) && Crate2->Get_Final_Odds() && (OddsDifference < 0 || !Crate2->Get_Cap_Odds())) { if (Crate2->Get_Base_Odds() > Crate->Get_Base_Odds()) { OddsGreater += Crate2->Get_Final_Odds(); } else if (Crate2->Get_Base_Odds() == Crate->Get_Base_Odds()) { OddsEqual++; } } } Iterate_Crates(Crate2,x) if (Crate2->Check_Type(Player) && Crate2->Get_Final_Odds() && (OddsDifference < 0 || !Crate2->Get_Cap_Odds())) { if (Crate2->Get_Base_Odds() > Crate->Get_Base_Odds()) { float OddsBefore = Crate2->Get_Final_Odds(); Crate2->Adjust_Odds(OddsBefore/OddsGreater*OddsDifference); //Modify odds as a percentage of this crate's odds relative to the odds of all crates that are being modified. OddsDifference += OddsBefore-Crate2->Get_Final_Odds(); //I.E Crates with higher odds get more odds taken/granted. OddsGreater -= OddsBefore; } else if (Crate2->Get_Base_Odds() == Crate->Get_Base_Odds() && Crate != Crate2) { float OddsBefore = Crate2->Get_Final_Odds(); Crate2->Adjust_Odds(OddsDifference/OddsEqual); OddsDifference += OddsBefore-Crate2->Get_Final_Odds(); OddsEqual--; } } } if (OddsDifference < 0) { Crate->Adjust_Odds(OddsDifference); } } } Iterate_Crates(Crate,i) if (Crate->Check_Type(Player)) { Odds += Crate->Get_Final_Odds(); } } } else { Odds = BaseOdds; } } float DACrateManager::Get_Odds() { return Odds; } DACrateClass *DACrateManager::Select_Crate(cPlayer *Player) { Calculate_Odds(Player); float Rand = Get_Random_Float(1,Odds); float Total = 0; Iterate_Crates(Crate,i) if (Crate->Check_Type(Player)) { if (Crate->Get_Final_Odds() && Rand <= (Total+=Crate->Get_Final_Odds())) { return Crate; } } } return 0; } void DACrateManager::Init() { Register_Event(DAEvent::LEVELLOADED); Register_Event(DAEvent::SETTINGSLOADED); Register_Event(DAEvent::GAMEOVER); Register_Event(DAEvent::POWERUPGRANT); Register_Object_Event(DAObjectEvent::DESTROYED,DAObjectEvent::POWERUP); Register_Chat_Command((DAECC)&DACrateManager::Crate_Chat_Command,"!crate"); Register_Chat_Command((DAECC)&DACrateManager::Crates_Chat_Command,"!crates"); Register_Chat_Command((DAECC)&DACrateManager::ShowCrateSpawners_Chat_Command,"!showcratespawners",0,DAAccessLevel::ADMINISTRATOR); Register_Chat_Command((DAECC)&DACrateManager::HideCrateSpawners_Chat_Command,"!hidecratespawners",0,DAAccessLevel::ADMINISTRATOR); } DACrateManager::~DACrateManager() { for (int i = 0;i < Crates.Count();i++) { Crates[i]->Destroy_Instance(); } if (!DAGameManager::Is_Shutdown_Pending()) { for (int i = 0;i < CrateObjs.Count();i++) { CrateObjs[i]->Set_Delete_Pending(); } } } void DACrateManager::Settings_Loaded_Event() { //Basic settings MaxCrates = DASettingsManager::Get_Int("MaxCrates",1); DASettingsManager::Get_String(Model,"CrateModel","vehcol2m"); StringClass SpawnTime; DASettingsManager::Get_String(SpawnTime,"CrateSpawnTime","120-180"); DATokenParserClass Parser(SpawnTime,'-'); if (!Parser.Get_Float(SpawnTimeMin) || !Parser.Get_Float(SpawnTimeMax)) { SpawnTimeMin = 120.0f; SpawnTimeMax = 180.0f; } DASettingsManager::Get_String(SpawnTime,"FirstCrateSpawnTime","60-90"); Parser.Set(SpawnTime,'-'); if (!Parser.Get_Float(FirstSpawnTimeMin) || !Parser.Get_Float(FirstSpawnTimeMax)) { FirstSpawnTimeMin = 60.0f; FirstSpawnTimeMax = 90.0f; } //Crates for (int i = 0;i < Crates.Count();i++) { if (Crates[i]->Get_Instance()) { if (!Crates[i]->Check_Enabled()) { Crates[i]->Destroy_Instance(); } else { Crates[i]->Get_Instance()->Settings_Loaded(); } } else if (Crates[i]->Check_Enabled()) { Crates[i]->Create_Instance()->Settings_Loaded(); } } DynamicVectorClass<DACrateFactoryClass*> CratesCopy = Crates; Crates.Delete_All(); for (int i = 0;i < CratesCopy.Count();i++) { //Order crates from highest base odds to lowest base odds. bool Added = false; if (CratesCopy[i]->Get_Instance()) { for (int x = 0;x < Crates.Count();x++) { if (Crates[x]->Get_Instance() && Crates[x]->Get_Instance()->Get_Base_Odds() < CratesCopy[i]->Get_Instance()->Get_Base_Odds()) { Crates.Insert(x,CratesCopy[i]); Added = true; break; } } } if (!Added) { Crates.Add(CratesCopy[i]); } } //Spawn locations ActiveSpawners.Delete_All(); Spawners.Delete_All(); LastCratePosition = Vector3(-1000.0f,-1000.0f,-1000.0f); if (DASettingsManager::Get_Bool("EnableNewCrateSpawners",true)) { //Get new crate spawners from da_crates.ini if enabled. for (int i = 1;;i++) { Vector3 Buffer; DASettingsManager::Get_Vector3(Buffer,StringFormat("Crate%d",i),Buffer); if (Buffer.X || Buffer.Y || Buffer.Z) { if (Spawners.ID(Buffer) == -1) { Spawners.Add(Buffer); } } else { break; } } } if (DASettingsManager::Get_Bool("EnableOldCrateSpawners",true) || !Spawners.Count()) { //Get old crate spawners from level if enabled or if no new spawners could be loaded. for (int i = 0;i < SpawnerList.Count();i++) { const SpawnerDefClass *Def = SpawnerList[i]->Get_Definition(); if (Def->Get_Spawn_Definition_ID_List().Count() && stristr(Get_Definition_Name(Def->Get_Spawn_Definition_ID_List()[0]),"Crate")) { Vector3 Buffer; for (int x = 0;x < SpawnerList[i]->Get_Spawn_Point_List().Count();x++) { //Alternate positions. SpawnerList[i]->Get_Spawn_Point_List()[x].Get_Translation(&Buffer); if (Spawners.ID(Buffer) == -1 && (Buffer.X || Buffer.Y || Buffer.Z)) { Spawners.Add(Buffer); } } SpawnerList[i]->Get_TM().Get_Translation(&Buffer); //Default position. if (Spawners.ID(Buffer) == -1 && (Buffer.X || Buffer.Y || Buffer.Z)) { Spawners.Add(Buffer); } SpawnerList[i]->Enable(false); //Disable default crate spawner. } } } else { for (int i = 0;i < SpawnerList.Count();i++) { const SpawnerDefClass *Def = SpawnerList[i]->Get_Definition(); if (Def->Get_Spawn_Definition_ID_List().Count() && stristr(Get_Definition_Name(Def->Get_Spawn_Definition_ID_List()[0]),"Crate")) { SpawnerList[i]->Enable(false); //Disable default crate spawner. } } } for (int i = 0;i < Spawners.Count();i++) { ActiveSpawners.Add(&Spawners[i]); } //Start spawn timer Stop_Timer(1); if (Spawners.Count()) { float Rand = Get_Random_Float(FirstSpawnTimeMin,FirstSpawnTimeMax); for (int i = 1;i <= (MaxCrates-CrateObjs.Count());i++) { Start_Timer(1,Rand*i); } } } void DACrateManager::Game_Over_Event() { Stop_Timer(1); } Vector3 *DACrateManager::Select_Spawner() { Vector3 *Spawner = 0; if (CrateObjs.Count()) { float MaxDistance = FLT_MIN; for (int i = 0;i < ActiveSpawners.Count();i++) { //Select active spawner farthest from any crate. float SpawnerMinDistance = FLT_MAX; for (int x = 0;x < CrateObjs.Count();x++) { float Distance = Commands->Get_Distance(CrateObjs[x]->Get_Position(),*ActiveSpawners[i]); if (Distance < SpawnerMinDistance) { SpawnerMinDistance = Distance; } } float Distance = Commands->Get_Distance(LastCratePosition,*ActiveSpawners[i]); if (Distance < SpawnerMinDistance) { SpawnerMinDistance = Distance; } if (SpawnerMinDistance > MaxDistance) { MaxDistance = SpawnerMinDistance; Spawner = ActiveSpawners[i]; } } } else if (ActiveSpawners.Count()) { //No crates exist, so get a random spawner. int Rand = Get_Random_Int(0,ActiveSpawners.Count()); Spawner = ActiveSpawners[Rand]; } ActiveSpawners.DeleteObj(Spawner); if (!ActiveSpawners.Count()) { //All spawners have been used, refill active list. for (int i = 0;i < Spawners.Count();i++) { if (&Spawners[i] != Spawner) { bool Valid = true; for (int x = 0;x < CrateObjs.Count();x++) { //Don't use any spawner that is near an existing crate. if (Commands->Get_Distance(CrateObjs[x]->Get_Position(),Spawners[i]) < 10.0f) { Valid = false; } } if (Valid) { ActiveSpawners.Add(&Spawners[i]); } } } } return Spawner; } void DACrateManager::Timer_Expired(int Number,unsigned int Data) { if (The_Game()->Get_Current_Players() && The_Game()->Is_Gameplay_Permitted()) { Vector3 *Position = Select_Spawner(); if (Position) { PhysicalGameObj *Crate = Create_Object("Soldier PowerUps",*Position); Commands->Set_Model(Crate,Model); CrateObjs.Add(Crate); return; } } Start_Timer(1,Get_Random_Float(SpawnTimeMin,SpawnTimeMax)); } void DACrateManager::PowerUp_Grant_Event(cPlayer *Player,const PowerUpGameObjDef *PowerUp,PowerUpGameObj *PowerUpObj) { if (PowerUpObj && CrateObjs.ID(PowerUpObj) != -1 && (Player->Get_Player_Type() == 0 || Player->Get_Player_Type() == 1)) { DACrateClass *Crate = DACrateManager::Select_Crate(Player); if (Crate) { SoldierGameObj *Soldier = Player->Get_GameObj(); Soldier->Get_Position(&LastCratePosition); DALogManager::Write_Log("_CRATE","%ls picked up the %s Crate(%s).",Player->Get_Name(),Crate->Get_Name(),Soldier->Get_Vehicle()?"Vehicle":"Infantry"); DALogManager::Write_GameLog("CRATE;%s;%s;%d;%s;%f;%f;%f;%f;%f;%f;%d",Crate->Get_Name(),Soldier->Get_Vehicle()?"Vehicle":"Infantry",Soldier->Get_ID(),Soldier->Get_Definition().Get_Name(),LastCratePosition.Y,LastCratePosition.X,LastCratePosition.Z,Soldier->Get_Facing(),Soldier->Get_Defense_Object()->Get_Health_Max(),Soldier->Get_Defense_Object()->Get_Shield_Strength_Max(),Soldier->Get_Player_Type()); Crate->Activate(Player); PowerUpObj->Set_Delete_Pending(); Start_Timer(1,Get_Random_Float(SpawnTimeMin,SpawnTimeMax)); DA::Private_HUD_Message(Player,COLORGRAY, "%s Crate", Crate->Get_Name()); } } } void DACrateManager::Object_Destroyed_Event(GameObject *obj) { CrateObjs.DeleteObj((PhysicalGameObj*)obj); } bool DACrateManager::Crate_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) { if (!Text.Size()) { DACrateClass *Crate = Select_Crate(Player); if (Crate) { DA::Page_Player(Player,"You got the %s Crate with a %.2f%% chance!",Crate->Get_Name(),Crate->Get_Final_Odds()/Odds*100); } else { DA::Page_Player(Player,"A crate could not be selected."); } } else if (Player->Get_DA_Player()->Get_Access_Level() >= DAAccessLevel::ADMINISTRATOR && (Player->Get_Player_Type() == 0 || Player->Get_Player_Type() == 1)) { DACrateClass *Crate = Get_Crate(Text[0]); if (Crate) { if (!Crate->Check_Type(Player) || !Crate->Can_Activate(Player)) { DA::Page_Player(Player,"You cannot currently receive that crate."); } else { Crate->Activate(Player); } } else { DA::Page_Player(Player,"Crate could not be found."); } } return true; } bool DACrateManager::Crates_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) { float InfantryOdds = 0; float VehicleOdds = 0; Iterate_Crates(Crate,i) if (Crate->Check_Type(DACrateType::INFANTRY)) { InfantryOdds += Crate->Get_Base_Odds(); } if (Crate->Check_Type(DACrateType::VEHICLE)) { VehicleOdds += Crate->Get_Base_Odds(); } } Calculate_Odds(Player); if (InfantryOdds) { DA::Page_Player(Player,"Base Infantry Odds:"); StringClass Send; Iterate_Crates(Crate,i) if (Crate->Check_Type(DACrateType::INFANTRY)) { StringClass Buffer; Buffer.Format("%s(%.2f%%), ",Crates[i]->Get_Name(),Crate->Get_Base_Odds()/InfantryOdds*100); if (Send.Get_Length() + Buffer.Get_Length() > 220) { Send.TruncateRight(2); DA::Page_Player(Player,"%s",Send); Send = Buffer; } else { Send += Buffer; } } } if (!Send.Is_Empty()) { Send.TruncateRight(2); DA::Page_Player(Player,"%s",Send); } } if (VehicleOdds) { DA::Page_Player(Player,"Base Vehicle Odds:"); StringClass Send; Iterate_Crates(Crate,i) if (Crate->Check_Type(DACrateType::VEHICLE)) { StringClass Buffer; Buffer.Format("%s(%.2f%%), ",Crates[i]->Get_Name(),Crate->Get_Base_Odds()/VehicleOdds*100); if (Send.Get_Length() + Buffer.Get_Length() > 220) { Send.TruncateRight(2); DA::Page_Player(Player,"%s",Send); Send = Buffer; } else { Send += Buffer; } } } if (!Send.Is_Empty()) { Send.TruncateRight(2); DA::Page_Player(Player,"%s",Send); } } if (Odds) { DA::Page_Player(Player,"Current Odds:"); StringClass Send; Iterate_Crates(Crate,i) if (Crate->Check_Type(Player)) { StringClass Buffer; if (Crate->Get_Final_Odds()) { Buffer.Format("%s(%.2f%%), ",Crates[i]->Get_Name(),Crate->Get_Final_Odds()/Odds*100); } else { Buffer.Format("%s(0%%), ",Crates[i]->Get_Name()); } if (Send.Get_Length() + Buffer.Get_Length() > 220) { Send.TruncateRight(2); DA::Page_Player(Player,"%s",Send); Send = Buffer; } else { Send += Buffer; } } } if (!Send.Is_Empty()) { Send.TruncateRight(2); DA::Page_Player(Player,"%s",Send); } } return true; } class DAShowCrateSpawnersObserverClass : public DAGameObjObserverClass { public: virtual const char *Get_Name() { return "DAShowCrateSpawnersObserverClass"; } DAShowCrateSpawnersObserverClass(int Number) { this->Number = Number; } virtual void Poked(GameObject *obj,GameObject *Poker) { Vector3 Position; Get_Owner()->Get_Position(&Position); DA::Host_Message("Crate spawner #%d at %f %f %f",Number,Position.X,Position.Y,Position.Z); } int Number; }; bool DACrateManager::ShowCrateSpawners_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) { HideCrateSpawners_Chat_Command(Player,Text,ChatType); int i = 0; for (;i < Spawners.Count();i++) { PhysicalGameObj *Marker = Create_Object("Invisible_Object",Spawners[i]); Marker->Set_Collision_Group(TERRAIN_AND_BULLET_COLLISION_GROUP); Marker->Peek_Physical_Object()->Set_Immovable(true); Commands->Set_Model(Marker,"dsp_holo"); Marker->Add_Observer(new DAShowCrateSpawnersObserverClass(i+1)); } DA::Host_Message("Created markers for %d crate spawners.",i); return true; } bool DACrateManager::HideCrateSpawners_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) { for (SLNode<BaseGameObj> *x = GameObjManager::GameObjList.Head();x;x = x->Next()) { if (x->Data()->As_ScriptableGameObj() && ((ScriptableGameObj*)x->Data())->Find_Observer("DAShowCrateSpawnersObserverClass")) { x->Data()->Set_Delete_Pending(); } } return true; } Register_Game_Feature(DACrateManager,"Crates","EnableCrates",0);
33.890772
404
0.692487
mpforums
8653002418fe6aad40b27089ade30361e7127879
3,343
cpp
C++
MathTutorRevised.cpp
krisf01/Computer-Systems-and-C-Programming
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
[ "MIT" ]
null
null
null
MathTutorRevised.cpp
krisf01/Computer-Systems-and-C-Programming
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
[ "MIT" ]
null
null
null
MathTutorRevised.cpp
krisf01/Computer-Systems-and-C-Programming
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { const int MIN_VALUE = 100; const int MAX_VALUE = 1000; const int addition = 1, subtraction = 2, multiplication = 3, division = 4, quit = 5; int randomnumber1, randomnumber2, useranswer, randnumanswer; int choice; std::setw(5); unsigned seed = time(0); srand(seed); do { randomnumber1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; randomnumber2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; cout << " " << "Math Tutor Menu" << endl; cout << "----------------------------" << endl; cout << "1. Addition problem" << endl; cout << "2. Subtraction problem" << endl; cout << "3. Multiplication problem" << endl; cout << "4. Division problem" << endl; cout << "5. Quit this program" << endl; cout << "----------------------------" << endl; cout << "Enter your choice (1-5): "; while(!(cin >> choice) || choice < addition || choice > quit) { cout << "Choose numbers only between 1, 2, 3, 4, 5: "; } if (choice != quit) { switch (choice) { case 1: { randnumanswer = randomnumber1 + randomnumber2; cout << setw(5) << randomnumber1 << endl; cout << "+" << endl; cout << setw(5) << randomnumber2 << endl; cout << "------" << endl; cout << " "; cin >> useranswer; cout << endl; break; } case 2: { randnumanswer = randomnumber2 - randomnumber1; cout << setw(5) << randomnumber2 << endl; cout << "-" << endl; cout << setw(5) << randomnumber1 << endl; cout << "------" << endl; cout << " "; cin >> useranswer; cout << endl; break; } case 3: { randnumanswer = randomnumber1 * randomnumber2; cout << setw(5) << randomnumber1 << endl; cout << "*" << endl; cout << setw(5) << randomnumber2 << endl; cout << "------" << endl; cout << " "; cin >> useranswer; cout << endl; break; } case 4: { randnumanswer = randomnumber1 % randomnumber2; cout << setw(5) << randomnumber1 << endl; cout << "%" << endl; cout << setw(5) << randomnumber2 << endl; cout << "------" << endl; cout << " "; cin >> useranswer; cout << endl; break; } } if (useranswer == randnumanswer) { cout << "\nCongratulations!" << endl << endl; } else if(useranswer != randnumanswer) { cout << "Sorry, the correct answer: " << randnumanswer << endl << endl; } } else cout << "Thank you for using Math Tutor." << endl; } while (choice != quit); cout << endl; return 0; }
30.117117
88
0.417589
krisf01
86558e89ec9ecfb438bf15e28d0e4bcec4d00b07
488
cpp
C++
searchlib/src/vespa/searchlib/features/utils.cpp
kennyeric/vespa
f69f960d5ae48d246f56a60e6e46c90a58f836ba
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/features/utils.cpp
kennyeric/vespa
f69f960d5ae48d246f56a60e6e46c90a58f836ba
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/features/utils.cpp
kennyeric/vespa
f69f960d5ae48d246f56a60e6e46c90a58f836ba
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "utils.hpp" namespace search::features::util { template double strToNum<double>(vespalib::stringref str); template uint32_t strToNum<uint32_t>(vespalib::stringref str); template uint64_t strToNum<uint64_t>(vespalib::stringref str); template int32_t strToNum<int32_t>(vespalib::stringref str); template int64_t strToNum<int64_t>(vespalib::stringref str); }
34.857143
118
0.793033
kennyeric
86586fa7d8409801b39c5a8d81f0ebfefcc6cd93
6,539
hpp
C++
fltl/include/tdop/Unbound.hpp
iambrosie/Grail-Plus
e102de735e86df241e4311394190ad39181f073b
[ "MIT" ]
null
null
null
fltl/include/tdop/Unbound.hpp
iambrosie/Grail-Plus
e102de735e86df241e4311394190ad39181f073b
[ "MIT" ]
null
null
null
fltl/include/tdop/Unbound.hpp
iambrosie/Grail-Plus
e102de735e86df241e4311394190ad39181f073b
[ "MIT" ]
1
2020-07-14T03:58:19.000Z
2020-07-14T03:58:19.000Z
/* * Unbound.hpp * * Created on: May 11, 2012 * Author: petergoodman * Version: $Id$ */ #ifndef Grail_Plus_TDOP_UNBOUND_HPP_ #define Grail_Plus_TDOP_UNBOUND_HPP_ namespace fltl { namespace tdop { template <typename, typename> class Unbound; template <typename, typename> class Bound; /// unbound rules template <typename AlphaT> class Unbound<AlphaT, rule_tag> { private: friend class OpaqueRule<AlphaT>; friend class TDOP<AlphaT>; OpaqueRule<AlphaT> *expr; Unbound(const OpaqueRule<AlphaT> *expr_) throw() : expr(const_cast<OpaqueRule<AlphaT> *>(expr_)) { } public: ~Unbound(void) throw() { expr = 0; } }; /// unbound symbol template <typename AlphaT> class Unbound<AlphaT, symbol_tag> { private: friend class detail::PatternData<AlphaT>; friend class Symbol<AlphaT>; friend class TDOP<AlphaT>; Symbol<AlphaT> *expr; Unbound(const Symbol<AlphaT> *expr_) throw() : expr(const_cast<Symbol<AlphaT> *>(expr_)) { } public: typedef Unbound<AlphaT, symbol_tag> self_type; typedef unbound_symbol_tag tag_type; ~Unbound(void) throw() { expr = 0; } /// unbound predicate symbol, e.g. *(~s), where 's' is a symbol. const Unbound<AlphaT, ubound_symbol_predicate_tag> operator*(void) const throw() { return Unbound<AlphaT, ubound_symbol_predicate_tag>(expr); } }; /// unbound predicate symbol template <typename AlphaT> class Unbound<AlphaT, ubound_symbol_predicate_tag> { private: friend class detail::PatternData<AlphaT>; friend class Unbound<AlphaT, symbol_tag>; Symbol<AlphaT> *expr; Unbound(const Symbol<AlphaT> *expr_) throw() : expr(const_cast<Symbol<AlphaT> *>(expr_)) { } public: typedef Unbound<AlphaT, ubound_symbol_predicate_tag> self_type; typedef ubound_symbol_predicate_tag tag_type; ~Unbound(void) throw() { expr = 0; } }; /// unbound operator template <typename AlphaT> class Unbound<AlphaT, operator_tag> { private: friend class detail::PatternData<AlphaT>; friend class Operator<AlphaT>; Operator<AlphaT> *expr; Unbound(const Operator<AlphaT> *expr_) throw() : expr(const_cast<Operator<AlphaT> *>(expr_)) { } public: typedef Unbound<AlphaT, operator_tag> self_type; typedef unbound_operator_tag tag_type; ~Unbound(void) throw() { expr = 0; } }; /// unbound operator string template <typename AlphaT> class Unbound<AlphaT, operator_string_tag> { private: friend class detail::PatternData<AlphaT>; friend class OperatorString<AlphaT>; OperatorString<AlphaT> *expr; Unbound(const OperatorString<AlphaT> *expr_) throw() : expr(const_cast<OperatorString<AlphaT> *>(expr_)) { } public: typedef Unbound<AlphaT, operator_string_tag> self_type; typedef unbound_operator_string_tag tag_type; ~Unbound(void) throw() { expr = 0; } }; /// unbound term template <typename AlphaT> class Unbound<AlphaT, term_tag> { private: friend class detail::PatternData<AlphaT>; friend class Term<AlphaT>; Term<AlphaT> *expr; Unbound(const Term<AlphaT> *expr_) throw() : expr(const_cast<Term<AlphaT> *>(expr_)) { } public: typedef Unbound<AlphaT, term_tag> self_type; typedef unbound_term_tag tag_type; ~Unbound(void) throw() { expr = 0; } }; /// unbound category template <typename AlphaT> class Unbound<AlphaT, category_tag> { private: friend class detail::PatternData<AlphaT>; friend class OpaqueCategory<AlphaT>; friend class TDOP<AlphaT>; OpaqueCategory<AlphaT> *expr; Unbound(const OpaqueCategory<AlphaT> *expr_) throw() : expr(const_cast<OpaqueCategory<AlphaT> *>(expr_)) { } public: typedef Unbound<AlphaT, category_tag> self_type; typedef unbound_category_tag tag_type; /// (~c)[n], unbound category, unbound lower bound const Unbound<AlphaT, category_lb_tag> operator[](unsigned &lower_bound) const throw() { return Unbound<AlphaT, category_lb_tag>(expr, &lower_bound); } // an initial rule, with an unbound category FLTL_TDOP_RULE_PATTERN(unbound_category_tag) ~Unbound(void) throw() { expr = 0; } }; /// unbound category, unbound lower bound template <typename AlphaT> class Unbound<AlphaT, category_lb_tag> { private: friend class detail::PatternData<AlphaT>; friend class Unbound<AlphaT, category_tag>; OpaqueCategory<AlphaT> *expr; unsigned *lower_bound; Unbound(const OpaqueCategory<AlphaT> *expr_, unsigned *lb) throw() : expr(const_cast<OpaqueCategory<AlphaT> *>(expr_)) , lower_bound(lb) { } public: typedef Unbound<AlphaT, category_lb_tag> self_type; typedef unbound_category_lb_tag tag_type; // an extension rule, with an unbound category and upper bound FLTL_TDOP_RULE_PATTERN(unbound_category_lb_tag) ~Unbound(void) throw() { expr = 0; lower_bound = 0; } }; /// bound category, unbound lower bound template <typename AlphaT> class Bound<AlphaT, category_lb_tag> { private: friend class detail::PatternData<AlphaT>; friend class OpaqueCategory<AlphaT>; OpaqueCategory<AlphaT> *expr; unsigned *lower_bound; Bound(const OpaqueCategory<AlphaT> *expr_, unsigned *lb) throw() : expr(const_cast<OpaqueCategory<AlphaT> *>(expr_)) , lower_bound(lb) { } public: typedef Bound<AlphaT, category_lb_tag> self_type; typedef category_lb_tag tag_type; // an extension rule, with an unbound upper bound, and a definite // category FLTL_TDOP_RULE_PATTERN(category_lb_tag) ~Bound(void) throw() { expr = 0; lower_bound = 0; } }; }} #endif /* Grail_Plus_TDOP_UNBOUND_HPP_ */
24.958015
74
0.605138
iambrosie
865a71163dedde3fcde4c7e3e55f582b7d27cef3
4,481
cpp
C++
PA3/lex.cpp
Elmojica/CS280
6feeb34ea4e577c09df77ded4e0e0d00638994d7
[ "CC0-1.0" ]
null
null
null
PA3/lex.cpp
Elmojica/CS280
6feeb34ea4e577c09df77ded4e0e0d00638994d7
[ "CC0-1.0" ]
null
null
null
PA3/lex.cpp
Elmojica/CS280
6feeb34ea4e577c09df77ded4e0e0d00638994d7
[ "CC0-1.0" ]
null
null
null
/* * lex.cpp * * CS280 - Fall 2021 */ #include <cctype> #include <map> using std::map; using namespace std; #include "lex.h" static map<Token,string> tokenPrint = { {PROGRAM, "PROGRAM"}, {WRITE, "WRITE"}, {INT, "INT"}, { END, "END" }, { IF, "IF" }, {FLOAT, "FLOAT"}, {STRING, "STRING"}, { REPEAT, "REPEAT" }, {BEGIN, "BEGIN"}, { IDENT, "IDENT" }, { ICONST, "ICONST" }, { RCONST, "RCONST" }, { SCONST, "SCONST" }, { PLUS, "PLUS" }, { MINUS, "MINUS" }, { MULT, "MULT" }, { DIV, "DIV" }, {REM, "REM"}, { ASSOP, "ASSOP" }, { LPAREN, "LPAREN" }, { RPAREN, "RPAREN" }, { COMMA, "COMMA" }, { EQUAL, "EQUAL" }, { GTHAN, "GTHAN" }, { SEMICOL, "SEMICOL" }, { ERR, "ERR" }, { DONE, "DONE" }, }; //Keywords mapping static map<string,Token> kwmap = { {"PROGRAM", PROGRAM}, {"WRITE", WRITE}, { "INT", INT}, { "FLOAT", FLOAT}, { "STRING", STRING}, { "REPEAT", REPEAT }, { "BEGIN", BEGIN }, {"IF", IF}, { "END", END }, }; ostream& operator<<(ostream& out, const LexItem& tok) { Token tt = tok.GetToken(); out << tokenPrint[ tt ]; if( tt == IDENT || tt == ICONST || tt == SCONST || tt == RCONST || tt == ERR ) { out << "(" << tok.GetLexeme() << ")"; } return out; } LexItem id_or_kw(const string& lexeme, int linenum) { Token tt = IDENT; auto kIt = kwmap.find(lexeme); if( kIt != kwmap.end() ) tt = kIt->second; return LexItem(tt, lexeme, linenum); } LexItem getNextToken(istream& in, int& linenum) { enum TokState { START, INID, INSTRING, ININT, INFLOAT, INCOMMENT } lexstate = START; string lexeme; char ch, nextch, nextchar; //cout << "in getNestToken" << endl; while(in.get(ch)) { //cout << "in while " << ch << endl; switch( lexstate ) { case START: if( ch == '\n' ) linenum++; if( isspace(ch) ) continue; lexeme = ch; if( isalpha(ch) ) { lexeme = toupper(ch); lexstate = INID; } else if( ch == '"' ) { lexstate = INSTRING; } else if( isdigit(ch) ) { lexstate = ININT; } else if( ch == '#' ) { lexstate = INCOMMENT; } else { Token tt = ERR; switch( ch ) { case '+': tt = PLUS; break; case '-': tt = MINUS; break; case '*': tt = MULT; break; case '/': tt = DIV; break; case '%': tt = REM; break; case '=': nextchar = in.peek(); if(nextchar == '='){ in.get(ch); tt = EQUAL; break; } tt = ASSOP; break; case '(': tt = LPAREN; break; case ')': tt = RPAREN; break; case ';': tt = SEMICOL; break; case ',': tt = COMMA; break; case '>': tt = GTHAN; break; case '.': nextch = in.peek(); if(isdigit(nextch)){ lexstate = INFLOAT; continue; } else { lexeme += nextch; return LexItem(ERR, lexeme, linenum); cout << "Here what?" << endl; } } return LexItem(tt, lexeme, linenum); } break; case INID: if( isalpha(ch) || isdigit(ch) || ch == '_') { ch = toupper(ch); //cout << "inid " << ch << endl; lexeme += ch; } else { in.putback(ch); return id_or_kw(lexeme, linenum); } break; case INSTRING: if( ch == '\n' ) { return LexItem(ERR, lexeme, linenum); } lexeme += ch; if( ch == '"' ) { lexeme = lexeme.substr(1, lexeme.length()-2); return LexItem(SCONST, lexeme, linenum); } break; case ININT: if( isdigit(ch) ) { lexeme += ch; } else if(ch == '.') { lexstate = INFLOAT; in.putback(ch); } else { in.putback(ch); return LexItem(ICONST, lexeme, linenum); } break; case INFLOAT: if( ch == '.' && isdigit(in.peek()) ) { lexeme += ch; } else if(isdigit(ch)){ lexeme += ch; } else if(ch == '.' && !isdigit(in.peek())){ lexeme += ch; return LexItem(ERR, lexeme, linenum); } else { in.putback(ch); return LexItem(RCONST, lexeme, linenum); } break; case INCOMMENT: if( ch == '\n' ) { ++linenum; lexstate = START; } break; } }//end of while loop if( in.eof() ) return LexItem(DONE, "", linenum); return LexItem(ERR, "some strange I/O error", linenum); }
16.782772
85
0.481143
Elmojica
865ae8c64863361690329855a977334660c8a6e0
11,160
cc
C++
chrome/browser/ui/meegotouch/find_bar_qt.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
chrome/browser/ui/meegotouch/find_bar_qt.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/meegotouch/find_bar_qt.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/meegotouch/find_bar_qt.h" #include "base/i18n/rtl.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "grit/generated_resources.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_bar_state.h" #include "chrome/browser/ui/find_bar/find_tab_helper.h" #include "chrome/browser/ui/meegotouch/browser_window_qt.h" #include "chrome/browser/ui/meegotouch/tab_contents_container_qt.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "content/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view_qt.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/chrome_switches.h" #include "content/common/notification_details.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include <QDeclarativeEngine> #include <QDeclarativeView> #include <QDeclarativeContext> #include <QDeclarativeItem> #include <QGraphicsLineItem> class FindBarQtImpl: public QObject { Q_OBJECT public: FindBarQtImpl(FindBarQt* findbar): QObject(NULL), find_bar_(findbar) { } void Show(bool animate) { visible_ = true; emit show(animate); } void Hide() { visible_ = false; emit hide(); } bool isVisible() const { return visible_; } QString GetSearchText() const { return search_text_; } void SetSearchText (QString text) { emit setSearchText(text); } void SetMatchesLabel(QString text) { emit setMatchesLabel(text); } void SetX(int x) { rect_.moveTo(x, rect_.y()); emit setX(x); } QRect GetRect() const { return rect_; } Q_SIGNALS: void show(bool animate); void hide(); // void close(); void setSearchText(QString text); void setMatchesLabel(QString text); void setX(int x); public slots: void textChanged(QString text) { search_text_ = text; find_bar_->OnChanged(); } void positionUpdated(int x, int y, int width, int height) { rect_.setRect(x, y, width, height); } void visibleChanged(bool visible) { visible_ = visible; } void closeButtonClicked(){ find_bar_->Close(); } void prevButtonClicked() { find_bar_->FindPrev(); } void nextButtonClicked() { find_bar_->FindNext(); } private: FindBarQt* find_bar_; QString search_text_; bool visible_; QRect rect_; }; FindBarQt::FindBarQt(Browser* browser, BrowserWindowQt* window) : browser_(browser), window_(window), impl_(new FindBarQtImpl(this)), ignore_changed_signal_(false) { QDeclarativeView* view = window_->DeclarativeView(); QDeclarativeContext *context = view->rootContext(); context->setContextProperty("findBarModel", impl_); } FindBarQt::~FindBarQt() { delete impl_; } void FindBarQt::Show(bool animate) { impl_->Show(animate); } void FindBarQt::Hide(bool animate) { impl_->Hide(); } void FindBarQt::Close() { find_bar_controller_->EndFindSession( FindBarController::kKeepSelection); } void FindBarQt::SetFocusAndSelection() { //Show(true); ///\todo 1. remove hard code of animate state ///\todo 2. Is this the proper way to simply show for this function? // StoreOutsideFocus(); // gtk_widget_grab_focus(text_entry_); // // Select all the text. // gtk_entry_select_region(GTK_ENTRY(text_entry_), 0, -1); } void FindBarQt::ClearResults(const FindNotificationDetails& results) { UpdateUIForFindResult(results, string16()); } void FindBarQt::StopAnimation() { DNOTIMPLEMENTED(); // slide_widget_->End(); } void FindBarQt::MoveWindowIfNecessary(const gfx::Rect& selection_rect, bool no_redraw) { DNOTIMPLEMENTED(); // Not moving the window on demand, so do nothing. } void FindBarQt::SetFindText(const string16& find_text) { std::wstring find_text_wide = UTF16ToWide(find_text); // Ignore the "changed" signal handler because programatically setting the // text should not fire a "changed" event. ignore_changed_signal_ = true; impl_->SetSearchText(QString::fromStdWString(find_text_wide)); //text_entry_->setText(QString::fromStdWString(find_text_wide)); // gtk_entry_set_text(GTK_ENTRY(text_entry_), find_text_utf8.c_str()); ignore_changed_signal_ = false; } void FindBarQt::UpdateUIForFindResult(const FindNotificationDetails& result, const string16& find_text) { //DNOTIMPLEMENTED(); if (!result.selection_rect().IsEmpty()) { selection_rect_ = result.selection_rect(); DLOG(INFO) << "selection_rect : " << selection_rect_.x() << " , " << selection_rect_.y(); QRect rect = impl_->GetRect(); DLOG(INFO) << "overlay_ : " << rect.x() << " , " << rect.y(); int xposition = GetDialogPosition(result.selection_rect()).x(); DLOG(INFO) << "xposition: " << xposition; if (xposition != rect.x()) { // Reposition(); impl_->SetX(xposition); } } // // Once we find a match we no longer want to keep track of what had // // focus. EndFindSession will then set the focus to the page content. // if (result.number_of_matches() > 0) // focus_store_.Store(NULL); std::wstring find_text_wide = UTF16ToWide(find_text); bool have_valid_range = result.number_of_matches() != -1 && result.active_match_ordinal() != -1; std::wstring entry_text(impl_->GetSearchText().toStdWString()); if (entry_text != find_text_wide) { SetFindText(find_text); // gtk_entry_select_region(GTK_ENTRY(text_entry_), 0, -1); //text_entry_->setSelection(0, -1); } if (!find_text.empty() && have_valid_range) { impl_->SetMatchesLabel(QString::fromUtf16(l10n_util::GetStringFUTF16(IDS_FIND_IN_PAGE_COUNT, base::IntToString16(result.active_match_ordinal()), base::IntToString16(result.number_of_matches())).c_str())); } else { // If there was no text entered, we don't show anything in the result count // area. impl_->SetMatchesLabel(" "); UpdateMatchLabelAppearance(false); } } void FindBarQt::AudibleAlert() { DNOTIMPLEMENTED(); // This call causes a lot of weird bugs, especially when using the custom // frame. TODO(estade): if people complain, re-enable it. See // http://crbug.com/27635 and others. // // gtk_widget_error_bell(widget()); } gfx::Rect FindBarQt::GetDialogPosition(gfx::Rect avoid_overlapping_rect) { bool ltr = !base::i18n::IsRTL(); // 15 is the size of the scrollbar, copied from ScrollbarThemeChromium. // The height is not used. // At very low browser widths we can wind up with a negative |dialog_bounds| // width, so clamp it to 0. QRect wr = window_->window()->geometry(); gfx::Rect dialog_bounds = gfx::Rect(ltr ? 0 : 15, 0, std::max(0, wr.width() - (ltr ? 15 : 0)), 0); // GtkRequisition req; // gtk_widget_size_request(container_, &req); QRect rect = impl_->GetRect(); gfx::Size prefsize(rect.width(), rect.height()); gfx::Rect view_location( ltr ? dialog_bounds.width() - prefsize.width() : dialog_bounds.x(), dialog_bounds.y(), prefsize.width(), prefsize.height()); gfx::Rect new_pos = FindBarController::GetLocationForFindbarView( view_location, dialog_bounds, avoid_overlapping_rect); return new_pos; } bool FindBarQt::IsFindBarVisible() { return impl_->isVisible(); // return overlay_->isOnDisplay(); } void FindBarQt::RestoreSavedFocus() { DNOTIMPLEMENTED(); // // This function sometimes gets called when we don't have focus. We should do // // nothing in this case. // if (!gtk_widget_is_focus(text_entry_)) // return; // if (focus_store_.widget()) // gtk_widget_grab_focus(focus_store_.widget()); // else // find_bar_controller_->tab_contents()->Focus(); } FindBarTesting* FindBarQt::GetFindBarTesting() { return this; } bool FindBarQt::GetFindBarWindowInfo(gfx::Point* position, bool* fully_visible) { DNOTIMPLEMENTED(); // if (position) // *position = GetPosition(); // if (fully_visible) { // *fully_visible = !slide_widget_->IsAnimating() && // slide_widget_->IsShowing(); // } return true; } string16 FindBarQt::GetFindText() { std::wstring contents = impl_->GetSearchText().toStdWString(); return WideToUTF16(contents); // std::wstring contents(text_entry_->text().toStdWString()); // // std::string contents(gtk_entry_get_text(GTK_ENTRY(text_entry_))); // return WideToUTF16(contents); } void FindBarQt::FindEntryTextInContents(bool forward_search) { TabContentsWrapper* tab_contents = find_bar_controller_->tab_contents(); if (!tab_contents) return; FindTabHelper* find_tab_helper = tab_contents->find_tab_helper(); std::wstring new_contents = impl_->GetSearchText().toStdWString(); if (new_contents.length() > 0) { find_tab_helper->StartFinding(WideToUTF16(new_contents), forward_search, false); // Not case sensitive. } else { // The textbox is empty so we reset. find_tab_helper->StopFinding(FindBarController::kClearSelection); UpdateUIForFindResult(find_tab_helper->find_result(), string16()); // Clearing the text box should also clear the prepopulate state so that // when we close and reopen the Find box it doesn't show the search we // just deleted. FindBarState* find_bar_state = browser_->profile()->GetFindBarState(); find_bar_state->set_last_prepopulate_text(string16()); } } void FindBarQt::UpdateMatchLabelAppearance(bool failure) { DNOTIMPLEMENTED(); } void FindBarQt::Reposition() { if (!IsFindBarVisible()) return; DNOTIMPLEMENTED(); // // This will trigger an allocate, which allows us to reposition. // if (widget()->parent) // gtk_widget_queue_resize(widget()->parent); } void FindBarQt::StoreOutsideFocus() { DNOTIMPLEMENTED(); // // |text_entry_| is the only widget in the find bar that can be focused, // // so it's the only one we have to check. // // TODO(estade): when we make the find bar buttons focusable, we'll have // // to change this (same above in RestoreSavedFocus). // if (!gtk_widget_is_focus(text_entry_)) // focus_store_.Store(text_entry_); } void FindBarQt::AdjustTextAlignment() { DNOTIMPLEMENTED(); } gfx::Point FindBarQt::GetPosition() { DNOTIMPLEMENTED(); // gfx::Point point; // // return point; } // static void FindBarQt::OnChanged() { AdjustTextAlignment(); if (!ignore_changed_signal_) FindEntryTextInContents(true); return; } #include "moc_find_bar_qt.cc"
30.914127
121
0.693011
meego-tablet-ux
865e81b0270c0350c28729fe96a0564681538cae
10,114
cc
C++
src_extra/jitterbug.cc
antiprism/antiprism
c1bc8cc44a92773dd42540de26d578b1e2c831c7
[ "MIT" ]
45
2016-04-11T19:21:10.000Z
2022-03-30T08:47:43.000Z
src_extra/jitterbug.cc
CyberSpock/antiprism
0a3278d8285d308e21d0aa660b860fe2b803a562
[ "MIT" ]
null
null
null
src_extra/jitterbug.cc
CyberSpock/antiprism
0a3278d8285d308e21d0aa660b860fe2b803a562
[ "MIT" ]
7
2016-04-12T11:35:53.000Z
2022-03-30T08:47:46.000Z
/* Copyright (c) 2006-2016, Adrian Rossiter Antiprism - http://www.antiprism.com 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. */ /* Name: jitterbug.cc Description: jitterbug transformation Project: Antiprism - http://www.antiprism.com */ #include "../base/antiprism.h" #include <algorithm> #include <cctype> #include <cmath> #include <cstring> #include <map> #include <string> #include <vector> using std::string; using std::vector; using namespace anti; enum face_types { f_none = 0, f_equ = 1, f_oth = 2, f_quad = 4 }; class jb_opts : public ProgramOpts { private: public: double stage; unsigned int faces; char cycle_type; int lat_size; bool tri_fix; bool tri_top; bool fix_connect; string ofile; jb_opts() : ProgramOpts("jitterbug"), stage(0.0), faces(f_equ | f_oth), cycle_type('f'), lat_size(1), tri_fix(false), tri_top(false), fix_connect(false) { } void process_command_line(int argc, char **argv); void usage(); }; void jb_opts::usage() { fprintf(stdout, R"( Usage: %s [options] [cycle_stage] Create a stage of the jitterbug transformation in OFF format. The cycles run from 0.0 to 1.0. The fractional part of cycle_stage is tied to a stage in a full rotation jitterbug. This stage is measured by the distance travelled by a point moving around a square which halves a cube of edge 0.25, and which determines the jitterbug shape. Options %s -f <fces> faces to includ x - none a - all e - equilateral triangles (default) o - other triangles -c <cyc> cycle type: f - full rotation o - alternating between left and right octahedron stages r - rolling between left and right octahedron stages i - alternating between left and right icosahedron stages -l <size> lattice size, nummber of jitterbugs along an edge (default 1) -r allow lattice reversal by fixing connections between jitterbug neighbours -t fix an opposing pair of triangles, stopping them from rotating -T rotate so equilateral triangle is on top (suports -t) -o <file> write output to file (default: write to standard output) )", prog_name(), help_ver_text); } void jb_opts::process_command_line(int argc, char **argv) { opterr = 0; int c; handle_long_opts(argc, argv); while ((c = getopt(argc, argv, ":hf:c:l:tTro:")) != -1) { if (common_opts(c, optopt)) continue; switch (c) { case 'f': if (strspn(optarg, "xaAeo") != strlen(optarg)) error( msg_str("faces to show are '%s', must be from x, a, e, o", optarg), c); switch (*optarg) { case 'a': faces = f_equ | f_oth; break; case 'A': faces = f_equ | f_quad; break; case 'e': faces = f_equ; break; case 'o': faces = f_oth; break; default: faces = f_none; } break; case 'c': if (strspn(optarg, "fori") != strlen(optarg)) error(msg_str("cycle type is '%s', must be from f, o, r, i", optarg), c); cycle_type = *optarg; break; case 'l': print_status_or_exit(read_int(optarg, &lat_size), c); if (lat_size <= 0) error("lattice size must be a positive integer", c); break; case 't': tri_fix = true; break; case 'T': tri_top = true; break; case 'r': fix_connect = true; break; case 'o': ofile = optarg; break; default: error("unknown command line error"); } } if (argc - optind > 1) { error("too many arguments"); exit(1); } stage = 0.0; if (argc - optind == 1) { print_status_or_exit(read_double(argv[optind], &stage), c); } stage = stage - floor(stage); } double get_tri_ang(double cyc_val) { double tri_ang; double c = fmod(cyc_val, 0.25) * 4; if ((cyc_val > 0.25 && cyc_val < 0.5) || cyc_val > 0.75) c = 1 - c; double ang = asin(safe_for_trig(sqrt(3 * c * c / (4 * c * c - 2 * c + 1)))); if (cyc_val < 0.25) tri_ang = ang; else if (cyc_val < 0.5) tri_ang = (M_PI - ang) * 1; else if (cyc_val < 0.75) tri_ang = (M_PI + ang) * 1; else tri_ang = (2 * M_PI - ang) * 1; return tri_ang; } double jb_make_verts(Geometry &geom, double t) { geom.clear_all(); t = t - floor(t); double x, y, z; x = 0; if (t >= 0 && t < 0.25) { y = 1; z = 1 - 8 * t; } else if (t >= 0.25 && t < 0.5) { y = 3 - 8 * t; z = -1; } else if (t >= 0.5 && t < 0.75) { y = -1; z = 8 * t - 5; } else { y = 8 * t - 7; z = 1; } geom.add_vert(Vec3d(x, y, z)); geom.add_vert(Vec3d(x, -y, z)); geom.add_vert(Vec3d(x, -y, -z)); geom.add_vert(Vec3d(x, y, -z)); geom.add_vert(Vec3d(z, x, y)); geom.add_vert(Vec3d(z, x, -y)); geom.add_vert(Vec3d(-z, x, -y)); geom.add_vert(Vec3d(-z, x, y)); geom.add_vert(Vec3d(y, z, x)); geom.add_vert(Vec3d(-y, z, x)); geom.add_vert(Vec3d(-y, -z, x)); geom.add_vert(Vec3d(y, -z, x)); double scale = 1.0 / geom.edge_vec(4, 0).len(); geom.transform(Trans3d::scale(scale)); return scale; } void jb_add_equ_tris(Geometry &jb) { int faces[] = {4, 8, 0, 5, 3, 8, 6, 9, 3, 7, 0, 9, 7, 10, 1, 6, 2, 10, 5, 11, 2, 4, 1, 11}; vector<int> face(3); for (int i = 0; i < 8; i++) { for (int j = 0; j < 3; j++) face[j] = faces[3 * i + j]; jb.add_face(face, 1); } } void jb_add_oth_quads(Geometry &jb) { int quads[] = {7, 1, 4, 0, 11, 5, 8, 4, 6, 3, 5, 2, 9, 6, 10, 7, 3, 9, 0, 8, 2, 11, 1, 10}; vector<int> face(4); for (int i = 0; i < 6; i++) { for (int j = 0; j < 4; j++) face[j] = (quads[4 * i + j]); jb.add_face(face, 2); } } void jb_add_oth_tris(Geometry &jb) { int quads[] = {7, 1, 4, 0, 11, 5, 8, 4, 6, 3, 5, 2, 9, 6, 10, 7, 3, 9, 0, 8, 2, 11, 1, 10}; vector<int> face(3); for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) face[j] = (quads[4 * i + j]); jb.add_face(face, 2); for (int j = 0; j < 3; j++) face[j] = quads[4 * i + (j + 2) % 4]; jb.add_face(face, 2); } } double jb_make(Geometry &jb, double t, int f_types) { double scale = jb_make_verts(jb, t); if (f_types & f_equ) jb_add_equ_tris(jb); if (f_types & f_oth) jb_add_oth_tris(jb); if (f_types & f_quad) jb_add_oth_quads(jb); return scale; } double cycle_value(double fract, char cycle_type) { double val; double ico_fract = (3 - sqrt(5)) / 16; switch (cycle_type) { case 'f': /* full cycle */ return fract; case 'o': /* 1/8 cycle to octahedron */ if (fract < 0.25) val = fract / 2; else if (fract < 0.75) val = 0.125 - (fract - 0.25) / 2; else val = -0.125 + (fract - 0.75) / 2; if (val < 0) val = val + 1; return val; case 'r': /* 1/8 cycle to octahedron with rotation*/ if (fract < 0.5) val = fract / 4; else val = -0.125 + (fract - 0.5) / 4; if (val < 0) val = val + 1; return val; case 'i': /* 1/8 cycle to octahedron with rotation*/ if (fract < 0.25) val = 4 * fract * ico_fract; else if (fract < 0.75) val = ico_fract - 4 * (fract - 0.25) * ico_fract; else val = -ico_fract + 4 * (fract - 0.75) * ico_fract; if (val < 0) val = val + 1; return val; default: return 0; } } double get_r_scale(double c_val) { double r_scale; if (c_val < 0.25) r_scale = 1; else if (c_val < 0.5) r_scale = 8 * (0.375 - c_val); else if (c_val < 0.75) r_scale = -1; else r_scale = 8 * (c_val - 0.875); return r_scale; } void lattice_make(Geometry &lat_jb, Geometry &jb, double cycle_val, double scale, int lat_sz, bool fix_connect) { for (int i = 1 - lat_sz; i < lat_sz; i += 2) for (int j = 1 - lat_sz; j < lat_sz; j += 2) for (int k = 1 - lat_sz; k < lat_sz; k += 2) { Geometry jb_elem = jb; double scl = scale; if (fix_connect) scl *= get_r_scale(cycle_val); jb_elem.transform(Trans3d::translate(Vec3d(i * scl, j * scl, k * scl))); lat_jb.append(jb_elem); } } void lattice_trans(Geometry &lat_jb, double cyc_val, bool tri_fix, bool tri_top) { Trans3d trans; if (tri_fix) trans = Trans3d::rotate(Vec3d(1, 1, 1), get_tri_ang(cyc_val)) * trans; if (tri_top) trans = Trans3d::rotate(Vec3d(1, 0, 0), Vec3d(1, 0, 1)) * Trans3d::rotate(Vec3d(1, 1, 1), Vec3d(0, 1, 0)) * trans; lat_jb.transform(trans); } int main(int argc, char *argv[]) { jb_opts opts; opts.process_command_line(argc, argv); double cyc_val = cycle_value(opts.stage, opts.cycle_type); Geometry jb, lat_jb; double scale = jb_make(jb, cyc_val, opts.faces); lattice_make(lat_jb, jb, cyc_val, scale, opts.lat_size, opts.fix_connect); lattice_trans(lat_jb, cyc_val, opts.tri_fix, opts.tri_top); opts.write_or_error(lat_jb, opts.ofile); return 0; }
25.348371
80
0.584635
antiprism
86669d7d3fd632dcabacd5da344bf82a5807a691
444
cpp
C++
src/detail/flow.cpp
szdanowi/bflow
71cb2e6d8e55b0cd07337815d690ced8a0cb583a
[ "MIT" ]
null
null
null
src/detail/flow.cpp
szdanowi/bflow
71cb2e6d8e55b0cd07337815d690ced8a0cb583a
[ "MIT" ]
null
null
null
src/detail/flow.cpp
szdanowi/bflow
71cb2e6d8e55b0cd07337815d690ced8a0cb583a
[ "MIT" ]
null
null
null
#include "flow.hpp" #include <ostream> namespace bflow { namespace { const char* to_str(result value) { switch (value) { case result::rejected: return "rejected"; case result::accepted: return "accepted"; case result::completed: return "completed"; default: return "[INVALID RESULT]"; } } } // namespace std::ostream& operator<<(std::ostream& os, result value) { os << to_str(value); return os; } } // namespace bflow
19.304348
58
0.668919
szdanowi
86691d79f1e662bab84bb05369b9a3df857aad85
70
cpp
C++
cpp/uninit_val.cpp
lindsayad/misc_programming
60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e
[ "MIT" ]
null
null
null
cpp/uninit_val.cpp
lindsayad/misc_programming
60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e
[ "MIT" ]
null
null
null
cpp/uninit_val.cpp
lindsayad/misc_programming
60d4056a99d52e247bc1ae08b9eaaf0b13cc1b2e
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { int x; printf ("x = %d\n", x); }
8.75
25
0.485714
lindsayad
866f2edae264cbdb37de5e4701e0fb4d6d3f0a44
2,517
hpp
C++
libvast/vast/system/start_command.hpp
a4z/vast
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/system/start_command.hpp
a4z/vast
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
[ "BSD-3-Clause" ]
null
null
null
libvast/vast/system/start_command.hpp
a4z/vast
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <functional> #include "vast/command.hpp" namespace vast::system { /// Callback for adding additional application logic to `start_command_impl`. /// @relates start_command_impl using start_command_extra_steps = std::function<caf::error( caf::scoped_actor& self, const caf::settings& options, const caf::actor&)>; /// Extensible base implementation for the *start* command that allows /// users to add additional application logic. /// @param extra_steps Function that adds additional application logic after /// the node is connected and before the command enters its /// loop to wait for CTRL+C or system shutdown. /// @param invocation Invocation object that dispatches to this function. /// @param sys The hosting CAF actor system. /// @returns An non-default error on if the extra steps fail and /// `start_command_impl` needs to stop running, `caf::none` otherwise. /// @relates start_command caf::message start_command_impl(start_command_extra_steps extra_steps, const invocation& inv, caf::actor_system& sys); /// Default implementation for the *start* command. /// @param invocation Invocation object that dispatches to this function. /// @param sys The hosting CAF actor system. /// @returns An error on invalid arguments or when unable to connect to the /// remote node, an empty message otherwise. /// @relates application caf::message start_command(const invocation& inv, caf::actor_system& sys); } // namespace vast::system
51.367347
80
0.57052
a4z
86725899a1ff01ae0ac03e5b7f105187ae1a3f86
1,260
cc
C++
tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc
alecgunny/tensorrt-inference-server
6a9ae2936489c681d5ab7b6589d8aff7dd48829a
[ "BSD-3-Clause" ]
1
2019-02-25T22:50:58.000Z
2019-02-25T22:50:58.000Z
tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc
alecgunny/tensorrt-inference-server
6a9ae2936489c681d5ab7b6589d8aff7dd48829a
[ "BSD-3-Clause" ]
null
null
null
tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc
alecgunny/tensorrt-inference-server
6a9ae2936489c681d5ab7b6589d8aff7dd48829a
[ "BSD-3-Clause" ]
null
null
null
--- tensorflow_serving/util/net_http/server/internal/evhttp_request.cc 2018-11-01 12:04:22.185086318 -0700 +++ /home/david/dev/gitlab/dgx/tensorrtserver/tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc 2018-11-02 11:47:57.254526547 -0700 @@ -44,6 +44,8 @@ evhttp_uri_free(decoded_uri); } + evhttp_clear_headers(&params); + if (request && evhttp_request_is_owned(request)) { evhttp_request_free(request); } @@ -98,6 +100,8 @@ path = "/"; } + evhttp_parse_query(uri, &params); + headers = evhttp_request_get_input_headers(request); return true; @@ -123,6 +127,26 @@ return parsed_request_->method; } +bool EvHTTPRequest::QueryParam(absl::string_view key, std::string* str) const { + std::string key_str(key.data(), key.size()); + const char* val = + evhttp_find_header(&parsed_request_->params, key_str.c_str()); + if (val != nullptr) { + *str = val; + return true; + } + + return false; +} + +evbuffer* EvHTTPRequest::InputBuffer() const { + return evhttp_request_get_input_buffer(parsed_request_->request); +} + +evbuffer* EvHTTPRequest::OutputBuffer() { + return output_buf; +} + bool EvHTTPRequest::Initialize() { output_buf = evbuffer_new(); return output_buf != nullptr;
26.25
145
0.688889
alecgunny
86728652ddbe81b5541d33ef0a8aed6bb389c686
3,871
cc
C++
chrome/browser/install_verification/win/imported_module_verification.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
chrome/browser/install_verification/win/imported_module_verification.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
chrome/browser/install_verification/win/imported_module_verification.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/install_verification/win/imported_module_verification.h" #include <Windows.h> #include <algorithm> #include <iterator> #include <string> #include <vector> #include "base/logging.h" #include "base/strings/string16.h" #include "chrome/browser/install_verification/win/module_info.h" namespace { // We must make sure not to include modules here that are likely to get unloaded // because the scanning of the module is not done within a loader lock, so is // not resilient to changes made to the modules list. const wchar_t* const kModulesToScan[] = { L"chrome.dll", L"kernel32.dll", L"user32.dll" }; bool AddressBeyondRange(const ModuleInfo& module, uintptr_t address) { return module.base_address + module.size < address; } void ScanImportAddressTable( HMODULE module_handle, const std::set<ModuleInfo>& loaded_modules, std::set<base::string16>* imported_modules) { DCHECK(module_handle); DCHECK(imported_modules); // To find the Import Address Table address, we start from the DOS header. // The module handle is actually the base address where the header is. IMAGE_DOS_HEADER* dos_header = reinterpret_cast<IMAGE_DOS_HEADER*>(module_handle); // The e_lfanew is an offset from the DOS header to the NT header. It should // never be 0. DCHECK(dos_header->e_lfanew); IMAGE_NT_HEADERS* nt_headers = reinterpret_cast<IMAGE_NT_HEADERS*>( module_handle + dos_header->e_lfanew / sizeof(uintptr_t)); // For modules that have an import address table, its offset from the // DOS header is stored in the second data directory's VirtualAddress. if (!nt_headers->OptionalHeader.DataDirectory[1].VirtualAddress) return; IMAGE_IMPORT_DESCRIPTOR* image_descriptor = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(module_handle + nt_headers->OptionalHeader.DataDirectory[1].VirtualAddress / sizeof(uintptr_t)); // The list of Import Address Tables ends with an empty {0} descriptor. while (image_descriptor->Characteristics) { uintptr_t* address = reinterpret_cast<uintptr_t*>( module_handle + image_descriptor->FirstThunk / sizeof(uintptr_t)); // Each section of the Import Address Table ends with a NULL funcpointer. while (*address) { std::set<ModuleInfo>::const_iterator lower_bound = std::lower_bound( loaded_modules.begin(), loaded_modules.end(), *address, AddressBeyondRange); if (lower_bound != loaded_modules.end() && lower_bound->ContainsAddress(*address)) { imported_modules->insert(lower_bound->name); } ++address; } image_descriptor += sizeof(image_descriptor) / sizeof(uintptr_t); } } } // namespace void VerifyImportedModules(const std::set<ModuleInfo>& loaded_modules, const ModuleIDs& module_ids, ModuleVerificationDelegate* delegate){ // Note that module verification is temporarily disabled for 64-bit builds. // See crbug.com/316274. #if !defined(_WIN64) std::set<base::string16> imported_module_names; for (size_t i = 0; i < arraysize(kModulesToScan); ++i) { HMODULE module_handle = ::GetModuleHandle(kModulesToScan[i]); if (module_handle) { ScanImportAddressTable(module_handle, loaded_modules, &imported_module_names); } } std::vector<std::string> module_name_digests; std::transform(imported_module_names.begin(), imported_module_names.end(), std::back_inserter(module_name_digests), &CalculateModuleNameDigest); ReportModuleMatches(module_name_digests, module_ids, delegate); #endif }
38.326733
81
0.709636
kjthegod
86728d91158e94e2ffce76bb5a3a85a0179a34a5
2,495
cpp
C++
tui/component/searchedit.cpp
mkinsz/QModule
ec7c0f8af8c33b9765d7a4e0350059284206d8a0
[ "MIT" ]
null
null
null
tui/component/searchedit.cpp
mkinsz/QModule
ec7c0f8af8c33b9765d7a4e0350059284206d8a0
[ "MIT" ]
null
null
null
tui/component/searchedit.cpp
mkinsz/QModule
ec7c0f8af8c33b9765d7a4e0350059284206d8a0
[ "MIT" ]
null
null
null
#include "searchedit.h" #include <QLineEdit> #include <QToolButton> #include <QHBoxLayout> #include <QDebug> #include <QFocusEvent> #include <QApplication> #include <QClipboard> SearchEdit::SearchEdit(QWidget *parent) : QLineEdit(parent) { this->initForm(); this->initConnect(); this->translator(); } SearchEdit::~SearchEdit() { } void SearchEdit::initForm() { this->setFixedSize(260, 24); this->setContextMenuPolicy(Qt::CustomContextMenu); m_tbnSearch = new QToolButton(this); m_tbnSearch->setFixedSize(25, 24); m_tbnSearch->setAutoRaise(true); m_tbnSearch->setCursor(Qt::PointingHandCursor); m_tbnSearch->setStyleSheet("QToolButton{border-image:url(:/component/search_dark.png);" "background:transparent;}"); m_mainLayout = new QHBoxLayout(); m_mainLayout->addStretch(); m_mainLayout->addWidget(m_tbnSearch); //设置文本边框,防止文本覆盖按钮 setTextMargins(0, 0, 20, 0); setContentsMargins(0, 0, 0, 0); m_mainLayout->setContentsMargins(2, 2, 4, 0); this->setLayout(m_mainLayout); setStyleSheet("height:24px;border:1px ;border-radius:6px;" "background-color:#E1DDDD"); } void SearchEdit::initConnect() { connect(m_tbnSearch, SIGNAL(clicked(bool)), this, SLOT(searchContent())); connect(this, SIGNAL(returnPressed()), this, SLOT(searchContent())); } //翻译控件 void SearchEdit::translator() { setPlaceholderText(QStringLiteral("请输入要查找的内容")); setToolTip(QStringLiteral("查找内容")); m_tbnSearch->setToolTip(QStringLiteral("查找")); } void SearchEdit::focusInEvent(QFocusEvent *event) { QLineEdit::focusInEvent(event); setStyleSheet("height:24px;border:1px ;border-radius:6px;" "background-color:#FFFFFF"); m_tbnSearch->setStyleSheet("QToolButton{border-image:url(:/component/search.png);" "background:transparent;}"); } void SearchEdit::focusOutEvent(QFocusEvent *event) { QLineEdit::focusOutEvent(event); setPlaceholderText(QStringLiteral("请输入要查找的内容")); setStyleSheet("height:24px;border:1px ;border-radius:6px;" "background-color:#CCC7C7"); m_tbnSearch->setStyleSheet("QToolButton{border-image:url(:/component/search_dark.png);" "background:transparent;}"); } void SearchEdit::searchContent() { QString str = text().isEmpty() ? placeholderText() : text(); emit search(str); } #include "moc_searchedit.cpp"
26.827957
91
0.671743
mkinsz
8672e2fd6634d5727b1d5434a132567378bfe01b
2,495
cpp
C++
src/solo/stb/SoloSTBTrueTypeFont.cpp
0xc0dec/solo
381276451767690b5fdb5a50a6b74a92ba78aa15
[ "Zlib" ]
31
2015-02-20T04:03:43.000Z
2022-03-07T19:04:02.000Z
src/solo/stb/SoloSTBTrueTypeFont.cpp
0xc0dec/solo
381276451767690b5fdb5a50a6b74a92ba78aa15
[ "Zlib" ]
14
2015-07-13T09:24:22.000Z
2016-10-24T10:09:58.000Z
src/solo/stb/SoloSTBTrueTypeFont.cpp
0xc0dec/solo
381276451767690b5fdb5a50a6b74a92ba78aa15
[ "Zlib" ]
1
2020-02-22T15:09:36.000Z
2020-02-22T15:09:36.000Z
/* * Copyright (c) Aleksey Fedotov * MIT license */ #include "SoloSTBTrueTypeFont.h" #include "SoloTexture.h" #include "SoloDevice.h" #include "SoloFileSystem.h" #include "SoloStringUtils.h" #include "SoloTextureData.h" #define STB_TRUETYPE_IMPLEMENTATION #include <stb_truetype.h> using namespace solo; auto STBTrueTypeFont::glyphInfo(u32 character, float offsetX, float offsetY) -> GlyphInfo { const auto dimensions = atlas_->dimensions(); stbtt_aligned_quad quad; stbtt_GetPackedQuad(charInfo_.get(), static_cast<u32>(dimensions.x()), static_cast<u32>(dimensions.y()), character - firstChar_, &offsetX, &offsetY, &quad, 1); auto xmin = quad.x0; auto xmax = quad.x1; auto ymin = -quad.y1; auto ymax = -quad.y0; GlyphInfo result{}; result.offsetX = offsetX; result.offsetY = offsetY; result.positions = { { xmin, ymin, 0 }, { xmin, ymax, 0 }, { xmax, ymax, 0 }, { xmax, ymin, 0 } }; result.uvs = { { quad.s0, quad.t1 }, { quad.s0, quad.t0 }, { quad.s1, quad.t0 }, { quad.s1, quad.t1 } }; return result; // TODO move } bool STBTrueTypeFont::canLoadFromFile(const str &path) { return stringutils::endsWith(path, ".ttf"); } auto STBTrueTypeFont::loadFromFile(Device *device, const str &path, u32 size, u32 atlasWidth, u32 atlasHeight, u32 firstChar, u32 charCount, u32 oversampleX, u32 oversampleY) -> sptr<STBTrueTypeFont> { auto data = device->fileSystem()->readBytes(path); auto result = sptr<STBTrueTypeFont>(new STBTrueTypeFont()); result->firstChar_ = firstChar; result->charInfo_ = std::make_unique<stbtt_packedchar[]>(charCount); vec<u8> pixels; pixels.resize(atlasWidth * atlasHeight); stbtt_pack_context context; const auto ret = stbtt_PackBegin(&context, pixels.data(), atlasWidth, atlasHeight, 0, 1, nullptr); panicIf(!ret, "Unable to process font ", path); stbtt_PackSetOversampling(&context, oversampleX, oversampleY); stbtt_PackFontRange(&context, data.data(), 0, static_cast<float>(size), firstChar, charCount, result->charInfo_.get()); stbtt_PackEnd(&context); const auto atlasData = Texture2DData::fromMemory(atlasWidth, atlasHeight, TextureDataFormat::Red, pixels); result->atlas_ = Texture2D::fromData(device, atlasData, true); result->atlas_->setFilter(TextureFilter::Linear, TextureFilter::Linear, TextureMipFilter::Linear); return result; }
30.426829
123
0.67976
0xc0dec
867536b48253f6ae10e7ffc8e0c299e3229da0ba
1,522
cpp
C++
mindsystem/mindsee/mindbase/baseDemo.cpp
Jack2Hub/mindproject
7d0e3651711fa3e8234e91ada7c2767f87d687d5
[ "BSD-2-Clause" ]
2
2021-04-06T11:43:37.000Z
2021-08-31T10:50:02.000Z
mindsystem/mindsee/mindbase/baseDemo.cpp
Jack2Hub/mindproject
7d0e3651711fa3e8234e91ada7c2767f87d687d5
[ "BSD-2-Clause" ]
null
null
null
mindsystem/mindsee/mindbase/baseDemo.cpp
Jack2Hub/mindproject
7d0e3651711fa3e8234e91ada7c2767f87d687d5
[ "BSD-2-Clause" ]
2
2021-02-26T11:46:48.000Z
2021-09-15T09:54:03.000Z
#include <iostream> #include <unistd.h> #include "stream.hpp" using namespace std; int main() { Stream testStream1; testStream1.SetCtrlCb([](std::string _cmd, void* userdata){return;}); // the cmd callback function must be set, you can just return without doing anything testStream1.SetFrameCb([](Stream::sFrame_t& frame, void* userdata){ // TODO // save frame to file // just test here printf("the %s Stream send %s data, CODEC typeis %s, size is %d\n", "master", (Stream::CHANNEL_VIDEO == frame.channel_type)?"video":"other data", (Stream::VIDEO_CODEC_H265 == frame.codec_type)?"h265":"other type", frame.data.c_str() ); }); testStream1.Start("172.19.24.95/0"); //the url fotmat: ip/channel Stream testStream2; testStream2.SetCtrlCb([](std::string _cmd, void* userdata){return;}); testStream2.SetFrameCb([](Stream::sFrame_t& frame, void* userdata){ // TODO // save frame to file // just test here printf("the %s Stream send %s data, CODEC typeis %s, size is %d\n", "slave", (Stream::CHANNEL_VIDEO == frame.channel_type)?"video":"other data", (Stream::VIDEO_CODEC_H265 == frame.codec_type)?"h265":"other type", frame.data.c_str() ); }); testStream2.Start("172.19.24.95/1"); while(true) { printf("looping...\n"); sleep(1); } return 0; }
32.382979
158
0.575558
Jack2Hub
8678fb918341e9392898e82578cf6a07f302f288
70
cpp
C++
multimedia/directx/dinput/dicfgddk/cfrmwrk_stub.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/dinput/dicfgddk/cfrmwrk_stub.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/dinput/dicfgddk/cfrmwrk_stub.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "common_stub.hpp" #include "..\\..\\diconfig\\cfrmwrk.cpp"
23.333333
41
0.657143
npocmaka
867c8a204338df55f6778dd49c730737fdd07e19
3,882
cpp
C++
core/common/cstream.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
28
2017-04-30T13:56:13.000Z
2022-03-20T06:54:37.000Z
core/common/cstream.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
72
2017-04-25T03:42:58.000Z
2021-12-04T06:35:28.000Z
core/common/cstream.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
12
2017-04-16T06:25:24.000Z
2021-07-07T13:28:27.000Z
// ------------------------------------------------ // File : cstream.cpp // Date: 4-apr-2002 // Author: giles // Desc: // Channel streaming classes. These do the actual // streaming of media between clients. // // (c) 2002 peercast.org // // ------------------------------------------------ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // ------------------------------------------------ #include "channel.h" #include "cstream.h" #include "pcp.h" #include "servmgr.h" #include "version2.h" #include "chanmgr.h" // ------------------------------------------ bool ChannelStream::getStatus(std::shared_ptr<Channel> ch, ChanPacket &pack) { unsigned int ctime = sys->getTime(); ChanHitList *chl = chanMgr->findHitListByID(ch->info.id); if (!chl) return false; int newLocalListeners = ch->localListeners(); int newLocalRelays = ch->localRelays(); if ( ( (numListeners != newLocalListeners) || (numRelays != newLocalRelays) || (ch->isPlaying() != isPlaying) || (servMgr->getFirewall(ch->ipVersion) != fwState) || ((ctime - lastUpdate) > 120) ) && ((ctime - lastUpdate) > 10) ) { numListeners = newLocalListeners; numRelays = newLocalRelays; isPlaying = ch->isPlaying(); fwState = servMgr->getFirewall(ch->ipVersion); lastUpdate = ctime; ChanHit hit; unsigned int oldp = ch->rawData.getOldestPos(); unsigned int newp = ch->rawData.getLatestPos(); hit.initLocal(numListeners, numRelays, ch->info.numSkips, ch->info.getUptime(), isPlaying, oldp, newp, ch->canAddRelay(), ch->sourceHost.host, (ch->ipVersion == Channel::IP_V6)); hit.tracker = ch->isBroadcasting(); MemoryStream pmem(pack.data, sizeof(pack.data)); AtomStream atom(pmem); atom.writeParent(PCP_BCST, 10); atom.writeChar(PCP_BCST_GROUP, PCP_BCST_GROUP_TRACKERS); atom.writeChar(PCP_BCST_HOPS, 0); atom.writeChar(PCP_BCST_TTL, 11); atom.writeBytes(PCP_BCST_FROM, servMgr->sessionID.id, 16); atom.writeInt(PCP_BCST_VERSION, PCP_CLIENT_VERSION); atom.writeInt(PCP_BCST_VERSION_VP, PCP_CLIENT_VERSION_VP); atom.writeBytes(PCP_BCST_VERSION_EX_PREFIX, PCP_CLIENT_VERSION_EX_PREFIX, 2); atom.writeShort(PCP_BCST_VERSION_EX_NUMBER, PCP_CLIENT_VERSION_EX_NUMBER); atom.writeBytes(PCP_BCST_CHANID, ch->info.id.id, 16); hit.writeAtoms(atom, GnuID()); pack.len = pmem.pos; pack.type = ChanPacket::T_PCP; return true; }else return false; } // ------------------------------------------ void ChannelStream::updateStatus(std::shared_ptr<Channel> ch) { ChanPacket pack; if (getStatus(ch, pack)) { if (!ch->isBroadcasting()) { int cnt = chanMgr->broadcastPacketUp(pack, ch->info.id, servMgr->sessionID, GnuID()); LOG_INFO("Sent channel status update to %d clients", cnt); } } } // ----------------------------------- void ChannelStream::readRaw(Stream &in, std::shared_ptr<Channel> ch) { ChanPacket pack; const int readLen = 8192; pack.init(ChanPacket::T_DATA, pack.data, readLen, ch->streamPos); in.read(pack.data, pack.len); ch->newPacket(pack); ch->checkReadDelay(pack.len); ch->streamPos += pack.len; }
33.179487
186
0.600206
plonk
868352890ebe1060b61787575a86d86b99309706
1,343
cpp
C++
avalon/utils/platform.cpp
michaelcontento/avalon
9207fbe2b3be61050794eca123303f56a08930db
[ "MIT" ]
46
2015-02-20T07:20:39.000Z
2021-07-25T02:57:47.000Z
avalon/utils/platform.cpp
michaelcontento/avalon
9207fbe2b3be61050794eca123303f56a08930db
[ "MIT" ]
31
2015-09-20T09:07:29.000Z
2015-09-22T13:52:56.000Z
avalon/utils/platform.cpp
michaelcontento/avalon
9207fbe2b3be61050794eca123303f56a08930db
[ "MIT" ]
18
2015-01-15T12:30:03.000Z
2020-03-25T18:46:45.000Z
#include <avalon/utils/platform.h> namespace avalon { namespace utils { namespace platform { std::string getName() { #if AVALON_PLATFORM_IS_IOS return std::string("ios"); #elif AVALON_PLATFORM_IS_ANDROID return std::string("android"); #elif AVALON_PLATFORM_IS_WIN32 return std::string("win32"); #elif AVALON_PLATFORM_IS_MARMALADE return std::string("marmalade"); #elif AVALON_PLATFORM_IS_LINUX return std::string("linux"); #elif AVALON_PLATFORM_IS_BADA return std::string("bada"); #elif AVALON_PLATFORM_IS_BLACKBERRY return std::string("blackberry"); #elif AVALON_PLATFORM_IS_MAC return std::string("mac"); #elif AVALON_PLATFORM_IS_NACL return std::string("nacl"); #elif AVALON_PLATFORM_IS_EMSCRIPTEN return std::string("emscripten"); #elif AVALON_PLATFORM_IS_TIZEN return std::string("tizen"); #elif AVALON_PLATFORM_IS_QT5 return std::string("qt5"); #else #error "No name defined for current used CC_TARGET_PLATFORM" #endif } std::string getFlavor() { #if AVALON_PLATFORM_IS_ANDROID_AMAZON return std::string("amazon"); #elif AVALON_PLATFORM_IS_ANDROID_GOOGLE return std::string("google"); #elif AVALON_PLATFORM_IS_ANDROID_SAMSUNG return std::string("samsung"); #else return std::string(); #endif } } // namespace platform } // namespace utils } // namespace avalon
24.87037
64
0.744602
michaelcontento
86849cf9a2c0ac1a5f11afdd2c94bb8083994bda
19,319
cc
C++
notification/src/macro_generator.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
notification/src/macro_generator.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
notification/src/macro_generator.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2011-2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include <sstream> #include <iomanip> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/notification/utilities/qhash_func.hh" #include "com/centreon/broker/notification/macro_generator.hh" #include "com/centreon/broker/notification/utilities/get_datetime_string.hh" #include "com/centreon/broker/notification/macro_getters.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::notification; // Used for contact macros. const char* get_email_key() {return "email";} const char* get_pager_key() {return "pager";} macro_generator::x_macro_map macro_generator::_map; /** * Default constructor. */ macro_generator::macro_generator() { if (_map.empty()) _fill_x_macro_map(_map); } /** * Generate macros. * * @param[in,out] container A container of asked macro, which will be filled as a result. * @param[in] id The id of the node for which we create macros. * @param[in] cnt The contact. * @param[in] st The state. * @param[in] cache The node cache. * @param[in] act The notification action. */ void macro_generator::generate( macro_container& container, objects::node_id id, objects::contact const& cnt, state const& st, node_cache const& cache, action const& act) const { objects::node::ptr node = st.get_node_by_id(id); if (!node) throw (exceptions::msg() << "notification: can't find the node (" << id.get_host_id() << ", " << id.get_service_id() << ") while generating its macros"); objects::node::ptr host = node; if (id.is_service()) host = st.get_node_by_id(objects::node_id(id.get_host_id())); if (!host) throw (exceptions::msg() << "notification: can't find the host " << id.get_host_id() << " while generating macros"); for (macro_container::iterator it(container.begin()), end(container.end()); it != end; ++it) { logging::debug(logging::low) << "notification: searching macro " << it.key(); if (_get_global_macros(it.key(), st, it.value())) continue ; else if (_get_x_macros( it.key(), macro_context(id, cnt, st, cache, act), it.value())) continue ; else if (_get_custom_macros( it.key(), id, cache, it.value())) continue ; else { logging::debug(logging::medium) << "notification: macro '" << it.key() << "' was not found for node (" << id.get_host_id() << ", " << id.get_service_id() << ")"; it->clear(); } } } /** * Get this macro if it's a global macro. * * @param[in] macro_name The name of the macro. * @param[in] st The state. * @param[out] result The result, filled if the macro is global. * @return True if this macro was found in the global macros. */ bool macro_generator::_get_global_macros( std::string const& macro_name, state const& st, std::string& result) { QHash<std::string, std::string> const& global_macros = st.get_global_macros(); QHash<std::string, std::string>::const_iterator found = global_macros.find(macro_name); if (found == global_macros.end()) return (false); result = *found; return (true); } /** * Get standard nagios macros. * * @param[in] macro_name The macro name. * @param[in] contact The macro context. * @param[out] result The result, filled if the macro is standard. * * @return True if the macro was found in the standard macros. */ bool macro_generator::_get_x_macros( std::string const& macro_name, macro_context const& context, std::string& result) const { x_macro_map::const_iterator found = _map.find(macro_name); if (found == _map.end()) return (false); else { result = (*found)(context); return (true); } } /** * Get custom macros. * * @param[in] macro_name The macro name. * @param[in] id The id of the node being notified. * @param[in] cache The node cache. * @param[out] result The result, filled if the macro is a custom macro. * * @return True if the macro was found in the custom macros. */ bool macro_generator::_get_custom_macros( std::string const& macro_name, objects::node_id id, node_cache const& cache, std::string& result) { QHash<std::string, neb::custom_variable_status> const* custom_vars; if (id.is_host()) custom_vars = &cache.get_host(id).get_custom_vars(); else custom_vars = &cache.get_service(id).get_custom_vars(); QHash<std::string, neb::custom_variable_status>::const_iterator found = custom_vars->find(macro_name); if (found != custom_vars->end()) { result = found->value.toStdString(); return (true); } else return (false); } /** * Fill the macro generator map with functions used to generate macros. * * @param[in] map The map to fill. */ void macro_generator::_fill_x_macro_map(x_macro_map& map) { // Time macros. map.insert( "LONGDATETIME", &get_datetime_string<utilities::long_date_time>); map.insert( "SHORTDATETIME", &get_datetime_string<utilities::short_date_time>); map.insert( "DATE", &get_datetime_string<utilities::short_date>); map.insert( "TIME", &get_datetime_string<utilities::short_time>); map.insert( "TIMET", &get_timet_string); // Host specific macros. map.insert( "HOSTNAME", &get_host_member_as_string< neb::host, QString, &neb::host::host_name, 0>); map.insert( "HOSTALIAS", &get_host_member_as_string<neb::host, QString, &neb::host::alias, 0>); map.insert( "HOSTADDRESS", &get_host_member_as_string<neb::host, QString, &neb::host::address, 0>); map.insert( "HOSTSTATE", &get_host_state); map.insert( "HOSTSTATEID", &get_host_status_member_as_string< neb::host_service_status, short, &neb::host_service_status::current_state, 0>); map.insert( "LASTHOSTSTATE", &get_last_host_state); map.insert( "LASTHOSTSTATEID", &get_host_prevstatus_member_as_string< neb::host_service_status, short, &neb::host_service_status::current_state, 0>); map.insert( "HOSTSTATETYPE", &get_host_state_type); map.insert( "HOSTATTEMPT", &get_host_status_member_as_string< neb::host_service_status, short, &neb::host_service_status::current_check_attempt, 0>); map.insert( "MAXHOSTATTEMPTS", &get_host_status_member_as_string< neb::host_service_status, short, &neb::host_service_status::max_check_attempts, 0>); // Event and problem id macros are ignored. map.insert("HOSTEVENTID", &null_getter); map.insert("LASTHOSTEVENTID", &null_getter); map.insert("HOSTPROBLEMID", &null_getter); map.insert("LASTHOSTPROBLEMID", &null_getter); map.insert( "HOSTLATENCY", &get_host_status_member_as_string< neb::host_service_status, double, &neb::host_service_status::latency, 3>); map.insert( "HOSTEXECUTIONTIME", &get_host_status_member_as_string< neb::host_service_status, double, &neb::host_service_status::execution_time, 3>); map.insert( "HOSTDURATION", get_host_duration); map.insert( "HOSTDURATIONSEC", get_host_duration_sec); map.insert( "HOSTDOWNTIME", &get_node_downtime_number); map.insert( "HOSTPERCENTCHANGE", &get_host_status_member_as_string< neb::host_service_status, double, &neb::host_service_status::percent_state_change, 2>); map.insert( "HOSTGROUPNAME", &null_getter); map.insert( "HOSTGROUPNAMES", &null_getter); map.insert( "LASTHOSTCHECK", &get_host_status_member_as_string< neb::host_service_status, timestamp, &neb::host_service_status::last_check, 0>); map.insert( "LASTHOSTSTATECHANGE", &get_host_status_member_as_string< neb::host_service_status, timestamp, &neb::host_service_status::last_state_change, 0>); map.insert( "LASTHOSTUP", &get_host_status_member_as_string< neb::host_status, timestamp, &neb::host_status::last_time_up, 0>); map.insert( "LASTHOSTDOWN", &get_host_status_member_as_string< neb::host_status, timestamp, &neb::host_status::last_time_down, 0>); map.insert( "LASTHOSTUNREACHABLE", &get_host_status_member_as_string< neb::host_status, timestamp, &neb::host_status::last_time_unreachable, 0>); map.insert( "HOSTOUTPUT", &get_host_output<false>); map.insert( "LONGHOSTOUTPUT", &get_host_output<true>); map.insert( "HOSTPERFDATA", &get_host_status_member_as_string< neb::host_service_status, QString, &neb::host_service_status::perf_data, 0>); map.insert( "HOSTCHECKCOMMAND", &get_host_status_member_as_string< neb::host_service_status, QString, &neb::host_service_status::check_command, 0>); // Hst ack macros are deprecated and ignored. map.insert("HOSTACKAUTHOR", &null_getter); map.insert("HOSTACKAUTHORNAME", &null_getter); map.insert("HOSTACKAUTHORALIAS", &null_getter); map.insert("HOSTACKCOMMENT", &null_getter); map.insert( "TOTALHOSTSERVICES", &get_total_host_services<-1>); map.insert( "TOTALHOSTSERVICESOK", &get_total_host_services<objects::node_state::service_ok>); map.insert( "TOTALHOSTSERVICESWARNING", &get_total_host_services<objects::node_state::service_warning>); map.insert( "TOTALHOSTSERVICESUNKNOWN", &get_total_host_services<objects::node_state::service_unknown>); map.insert( "TOTALHOSTSERVICESCRITICAL", &get_total_host_services<objects::node_state::service_critical>); // Service macros map.insert( "SERVICEDESC", &get_service_status_member_as_string< neb::service_status, QString, &neb::service_status::service_description, 0>); map.insert( "SERVICESTATE", &get_service_state); map.insert( "SERVICESTATEID", &get_service_status_member_as_string< neb::host_service_status, short, &neb::host_service_status::current_state, 0>); map.insert( "LASTSERVICESTATE", &get_last_service_state); map.insert( "LASTSERVICESTATEID", &get_service_prevstatus_member_as_string< neb::host_service_status, short, &neb::host_service_status::current_state, 0>); map.insert( "SERVICESTATETYPE", &get_service_state_type); map.insert( "SERVICEATTEMPT", &get_service_status_member_as_string< neb::host_service_status, short, &neb::host_service_status::current_check_attempt, 0>); map.insert( "MAXSERVICEATTEMPTS", &get_service_status_member_as_string< neb::host_service_status, short, &neb::host_service_status::max_check_attempts, 0>); map.insert( "SERVICEISVOLATILE", &get_service_member_as_string< neb::service, bool, &neb::service::is_volatile, 0>); // Event id are ignored. map.insert("SERVICEEVENTID", &null_getter); map.insert("LASTSERVICEEVENTID", &null_getter); map.insert("SERVICEPROBLEMID", &null_getter); map.insert("LASTSERVICEPROBLEMID", &null_getter); map.insert( "SERVICELATENCY", &get_service_status_member_as_string< neb::host_service_status, double, &neb::host_service_status::latency, 3>); map.insert( "SERVICEEXECUTIONTIME", &get_service_status_member_as_string< neb::host_service_status, double, &neb::host_service_status::execution_time, 3>); map.insert( "SERVICEDURATION", &get_service_duration); map.insert( "SERVICEDURATIONSEC", &get_service_duration_sec); // XXX map.insert( // "SERVICEDOWNTIME", // &get_service_status_member_as_string< // neb::host_service_status, // short, // &neb::host_service_status::scheduled_downtime_depth, // 0>); map.insert( "SERVICEPERCENTCHANGE", &get_service_status_member_as_string< neb::host_service_status, double, &neb::host_service_status::percent_state_change, 2>); map.insert( "SERVICEGROUPNAME", &null_getter); map.insert( "SERVICEGROUPNAMES", &null_getter); map.insert( "LASTSERVICECHECK", &get_service_status_member_as_string< neb::host_service_status, timestamp, &neb::host_service_status::last_check, 0>); map.insert( "LASTSERVICESTATECHANGE", &get_service_status_member_as_string< neb::host_service_status, timestamp, &neb::host_service_status::last_state_change, 0>); map.insert( "LASTSERVICEOK", &get_service_status_member_as_string< neb::service_status, timestamp, &neb::service_status::last_time_ok, 0>); map.insert( "LASTSERVICEWARNING", &get_service_status_member_as_string< neb::service_status, timestamp, &neb::service_status::last_time_warning, 0>); map.insert( "LASTSERVICEUNKNOWN", &get_service_status_member_as_string< neb::service_status, timestamp, &neb::service_status::last_time_unknown, 0>); map.insert( "LASTSERVICECRITICAL", &get_service_status_member_as_string< neb::service_status, timestamp, &neb::service_status::last_time_critical, 0>); map.insert( "SERVICEOUTPUT", &get_service_output<false>); map.insert( "LONGSERVICEOUTPUT", &get_service_output<true>); map.insert( "SERVICEPERFDATA", &get_service_status_member_as_string< neb::host_service_status, QString, &neb::host_service_status::perf_data, 0>); map.insert( "SERVICECHECKCOMMAND", &get_service_status_member_as_string< neb::host_service_status, QString, &neb::host_service_status::check_command, 0>); // Deprecated, ignored. map.insert("SERVICEACKAUTHOR", &null_getter); map.insert("SERVICEACKAUTHORNAME", &null_getter); map.insert("SERVICEACKAUTHORALIAS", &null_getter); map.insert("SERVICEACKCOMMENT", &null_getter); // Counting macros. map.insert( "TOTALHOSTSUP", &get_total_hosts<objects::node_state::host_up>); map.insert( "TOTALHOSTSDOWN", &get_total_hosts<objects::node_state::host_down>); map.insert( "TOTALHOSTSUNREACHABLE", &get_total_hosts<objects::node_state::host_unreachable>); map.insert( "TOTALHOSTSDOWNUNHANDLED", &get_total_hosts_unhandled<objects::node_state::host_down>); map.insert( "TOTALHOSTSUNREACHABLEUNHANDLED", &get_total_hosts_unhandled<objects::node_state::host_unreachable>); map.insert( "TOTALHOSTPROBLEMS", &get_total_hosts<-1>); map.insert( "TOTALHOSTPROBLEMSUNHANDLED", &get_total_hosts_unhandled<-1>); map.insert( "TOTALSERVICESOK", &get_total_services<objects::node_state::service_ok>); map.insert( "TOTALSERVICESWARNING", &get_total_services<objects::node_state::service_warning>); map.insert( "TOTALSERVICESCRITICAL", &get_total_services<objects::node_state::service_critical>); map.insert( "TOTALSERVICESUNKNOWN", &get_total_services<objects::node_state::service_unknown>); map.insert( "TOTALSERVICESWARNINGUNHANDLED", &get_total_services_unhandled<objects::node_state::service_warning>); map.insert( "TOTALSERVICESCRITICALUNHANDLED", &get_total_services_unhandled<objects::node_state::service_critical>); map.insert( "TOTALSERVICESUNKNOWNUNHANDLED", &get_total_services_unhandled<objects::node_state::service_unknown>); map.insert( "TOTALSERVICEPROBLEMS", &get_total_services<-1>); map.insert( "TOTALSERVICEPROBLEMSUNHANDLED", &get_total_services_unhandled<-1>); // Groups macros. map.insert( "HOSTGROUPALIAS", &null_getter); map.insert( "HOSTGROUPMEMBERS", &null_getter); map.insert( "SERVICEGROUPALIAS", &null_getter); map.insert( "SERVICEGROUPMEMBERS", &null_getter); // Contact macros. map.insert( "CONTACTNAME", &get_contact_member<std::string const&, &objects::contact::get_description, 0>); map.insert( "CONTACTALIAS", &get_contact_member<std::string const&, &objects::contact::get_description, 0>); map.insert( "CONTACTEMAIL", &get_contact_info<get_email_key>); map.insert( "CONTACTPAGER", &get_contact_info<get_pager_key>); map.insert( "CONTACTADDRESS1", &get_address_of_contact<1>); map.insert( "CONTACTADDRESS2", &get_address_of_contact<2>); map.insert( "CONTACTADDRESS3", &get_address_of_contact<3>); map.insert( "CONTACTADDRESS4", &get_address_of_contact<4>); map.insert( "CONTACTADDRESS5", &get_address_of_contact<5>); map.insert( "CONTACTADDRESS6", &get_address_of_contact<6>); map.insert( "CONTACTGROUPALIAS", &null_getter); map.insert( "CONTACTGROUPMEMBERS", &null_getter); // Notification macro. map.insert( "NOTIFICATIONTYPE", &get_notification_type); map.insert( "NOTIFICATIONRECIPIENTS", &get_contact_member<std::string const&, &objects::contact::get_description, 0>); map.insert( "HOSTNOTIFICATIONNUMBER", &get_action_member<unsigned int, &action::get_notification_number, 0>); map.insert( "SERVICENOTIFICATIONNUMBER", &get_action_member<unsigned int, &action::get_notification_number, 0>); // We will manage notification escalation/downtime macros // when we will manage escalations and downtimes. map.insert("NOTIFICATIONISESCALATED", &null_getter); map.insert("NOTIFICATIONCOMMENT", &null_getter); // For now, notification author macros are ignored. map.insert("NOTIFICATIONAUTHOR", &null_getter); map.insert("NOTIFICATIONAUTHORNAME", &null_getter); map.insert("NOTIFICATIONAUTHORALIAS", &null_getter); // Notification id rightfully ignored. map.insert("HOSTNOTIFICATIONID", &null_getter); map.insert("SERVICENOTIFICATIONID", &null_getter); }
29.138763
91
0.661266
sdelafond
868504c3b01afe7814aed8af1def27d945d7d3c4
2,989
cpp
C++
2020/day24/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2020/day24/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2020/day24/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
#include <climits> #include "common/types.h" #include "utils/file.h" #include "utils/utils.h" #define DEBUG_LEVEL 5 #include "common/debug.h" enum Color { WHITE, BLACK }; struct Floor { Floor() { this->minX = INT_MAX; this->maxX = INT_MIN; this->minY = INT_MAX; this->maxY = INT_MIN; } Color getColor(const Point<int> &p) { Color ret = WHITE; auto row = this->floor.find(p.y()); if (row != this->floor.end()) { auto col = row->second.find(p.x()); if (col != row->second.end()) { ret = col->second; } } return ret; } void setColor(const Point<int> &p, Color color) { if (p.x() > this->maxX) this->maxX = p.x(); if (p.x() < this->minX) this->minX = p.x(); if (p.y() > this->maxY) this->maxY = p.y(); if (p.y() < this->minY) this->minY = p.y(); this->floor[p.y()][p.x()] = color; } void spread() { this->minX--; this->maxX++; this->minY--; this->maxY++; } void toggle(const Point<int> &p) { this->setColor(p, (this->getColor(p) == WHITE) ? BLACK : WHITE); } int getBlack() { int ret = 0; for (auto row : this->floor) { for (auto col : row.second) { if (col.second == BLACK) { ret++; } } } return ret; } std::map<int, std::map<int, Color>> floor; int minX, maxX, minY, maxY; }; int main(int argc, char *argv[]) { auto lines = File::readAllLines(argv[1]); Floor floor; for (const auto &line : lines) { Point<int> center; for (int i = 0; i < line.size(); i++) { switch (line[i]) { // e, se, sw, w, nw, ne case 'n': { center.incY(); if (line[i + 1] == 'e') { center.incX(); } i++; } break; case 'e': center.incX(); break; case 's': { center.decY(); if (line[i + 1] == 'w') { center.decX(); } i++; } break; case 'w': center.decX(); break; } } floor.toggle(center); } PRINTF(("PART_A: %d", floor.getBlack())); for (int day = 0; day < 100; day++) { floor.spread(); Floor oldFloor = floor; for (int x = oldFloor.minX; x <= oldFloor.maxX; x++) { for (int y = oldFloor.minY; y <= oldFloor.maxY; y++) { int neighbours = 0; if (oldFloor.getColor(Point<int>(x, y + 1)) == BLACK) neighbours++; if (oldFloor.getColor(Point<int>(x + 1, y + 1)) == BLACK) neighbours++; if (oldFloor.getColor(Point<int>(x + 1, y )) == BLACK) neighbours++; if (oldFloor.getColor(Point<int>(x, y - 1)) == BLACK) neighbours++; if (oldFloor.getColor(Point<int>(x - 1, y - 1)) == BLACK) neighbours++; if (oldFloor.getColor(Point<int>(x - 1, y )) == BLACK) neighbours++; if (oldFloor.getColor(Point<int>(x, y)) == BLACK) { if (neighbours == 0 || neighbours > 2) { floor.setColor(Point<int>(x, y), WHITE); } } else { if (neighbours == 2) { floor.setColor(Point<int>(x, y), BLACK); } } } } } PRINTF(("PART_B: %d", floor.getBlack())); return 0; }
18.337423
75
0.526932
bielskij
868b1bde7f085fe3b5311e181e6ff8dfbda49128
11,557
cpp
C++
test/conformance/conformance_multifunction_node.cpp
andrewseidl/oneTBB
2d9df245c7084ea187ceeafdd31ea9767e3a4bea
[ "Apache-2.0" ]
1
2021-01-22T06:36:30.000Z
2021-01-22T06:36:30.000Z
test/conformance/conformance_multifunction_node.cpp
andrewseidl/oneTBB
2d9df245c7084ea187ceeafdd31ea9767e3a4bea
[ "Apache-2.0" ]
null
null
null
test/conformance/conformance_multifunction_node.cpp
andrewseidl/oneTBB
2d9df245c7084ea187ceeafdd31ea9767e3a4bea
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "common/test.h" #include "common/utils.h" #include "common/graph_utils.h" #include "oneapi/tbb/flow_graph.h" #include "oneapi/tbb/task_arena.h" #include "oneapi/tbb/global_control.h" #include "conformance_flowgraph.h" //! \file conformance_multifunction_node.cpp //! \brief Test for [flow_graph.function_node] specification /* TODO: implement missing conformance tests for multifunction_node: - [ ] Implement test_forwarding that checks messages are broadcast to all the successors connected to the output port the message is being sent to. And check that the value passed is the actual one received. - [ ] Explicit test for copy constructor of the node. - [ ] Constructor with explicitly passed Policy parameter: `template<typename Body> multifunction_node( graph &g, size_t concurrency, Body body, Policy(), node_priority_t priority = no_priority )'. - [ ] Concurrency testing of the node: make a loop over possible concurrency levels. It is important to test at least on five values: 1, oneapi::tbb::flow::serial, `max_allowed_parallelism' obtained from `oneapi::tbb::global_control', `oneapi::tbb::flow::unlimited', and, if `max allowed parallelism' is > 2, use something in the middle of the [1, max_allowed_parallelism] interval. Use `utils::ExactConcurrencyLevel' entity (extending it if necessary). - [ ] make `test_rejecting' deterministic, i.e. avoid dependency on OS scheduling of the threads; add check that `try_put()' returns `false' - [ ] The `copy_body' function copies altered body (e.g. after successful `try_put()' call). - [ ] `output_ports_type' is defined and accessible by the user. - [ ] Explicit test on `mfn::output_ports()' method. - [ ] The copy constructor and copy assignment are called for the node's input and output types. - [ ] Add CTAD test. */ template< typename OutputType > struct mf_functor { std::atomic<std::size_t>& local_execute_count; mf_functor(std::atomic<std::size_t>& execute_count ) : local_execute_count (execute_count) { } mf_functor( const mf_functor &f ) : local_execute_count(f.local_execute_count) { } void operator=(const mf_functor &f) { local_execute_count = std::size_t(f.local_execute_count); } void operator()( const int& argument, oneapi::tbb::flow::multifunction_node<int, std::tuple<int>>::output_ports_type &op ) { ++local_execute_count; std::get<0>(op).try_put(argument); } }; template<typename I, typename O> void test_inheritance(){ using namespace oneapi::tbb::flow; CHECK_MESSAGE( (std::is_base_of<graph_node, multifunction_node<I, O>>::value), "multifunction_node should be derived from graph_node"); CHECK_MESSAGE( (std::is_base_of<receiver<I>, multifunction_node<I, O>>::value), "multifunction_node should be derived from receiver<Input>"); } void test_multifunc_body(){ oneapi::tbb::flow::graph g; std::atomic<size_t> local_count(0); mf_functor<std::tuple<int>> fun(local_count); oneapi::tbb::flow::multifunction_node<int, std::tuple<int>, oneapi::tbb::flow::rejecting> node1(g, oneapi::tbb::flow::unlimited, fun); const size_t n = 10; for(size_t i = 0; i < n; ++i) { CHECK_MESSAGE((node1.try_put(1) == true), "try_put needs to return true"); } g.wait_for_all(); CHECK_MESSAGE( (local_count == n), "Body of the node needs to be executed N times"); } template<typename I, typename O> struct CopyCounterBody{ size_t copy_count; CopyCounterBody(): copy_count(0) {} CopyCounterBody(const CopyCounterBody<I, O>& other): copy_count(other.copy_count + 1) {} CopyCounterBody& operator=(const CopyCounterBody<I, O>& other) { copy_count = other.copy_count + 1; return *this;} void operator()( const I& argument, oneapi::tbb::flow::multifunction_node<int, std::tuple<int>>::output_ports_type &op ) { std::get<0>(op).try_put(argument); } }; void test_copies(){ using namespace oneapi::tbb::flow; CopyCounterBody<int, std::tuple<int>> b; graph g; multifunction_node<int, std::tuple<int>> fn(g, unlimited, b); CopyCounterBody<int, std::tuple<int>> b2 = copy_body<CopyCounterBody<int, std::tuple<int>>, multifunction_node<int, std::tuple<int>>>(fn); CHECK_MESSAGE( (b.copy_count + 2 <= b2.copy_count), "copy_body and constructor should copy bodies"); } template< typename OutputType > struct id_functor { void operator()( const int& argument, oneapi::tbb::flow::multifunction_node<int, std::tuple<int>>::output_ports_type &op ) { std::get<0>(op).try_put(argument); } }; void test_forwarding(){ oneapi::tbb::flow::graph g; id_functor<int> fun; oneapi::tbb::flow::multifunction_node<int, std::tuple<int>> node1(g, oneapi::tbb::flow::unlimited, fun); test_push_receiver<int> node2(g); test_push_receiver<int> node3(g); oneapi::tbb::flow::make_edge(node1, node2); oneapi::tbb::flow::make_edge(node1, node3); node1.try_put(1); g.wait_for_all(); CHECK_MESSAGE( (get_count(node3) == 1), "Descendant of the node must receive one message."); CHECK_MESSAGE( (get_count(node2) == 1), "Descendant of the node must receive one message."); } void test_rejecting_buffering(){ oneapi::tbb::flow::graph g; id_functor<int> fun; oneapi::tbb::flow::multifunction_node<int, std::tuple<int>, oneapi::tbb::flow::rejecting> node(g, oneapi::tbb::flow::unlimited, fun); oneapi::tbb::flow::limiter_node<int> rejecter(g, 0); oneapi::tbb::flow::make_edge(node, rejecter); node.try_put(1); int tmp = -1; CHECK_MESSAGE( (std::get<0>(node.output_ports()).try_get(tmp) == false), "try_get after rejection should not succeed"); CHECK_MESSAGE( (tmp == -1), "try_get after rejection should alter passed value"); g.wait_for_all(); } void test_policy_ctors(){ using namespace oneapi::tbb::flow; graph g; id_functor<int> fun; multifunction_node<int, std::tuple<int>, lightweight> lw_node(g, oneapi::tbb::flow::serial, fun); multifunction_node<int, std::tuple<int>, queueing_lightweight> qlw_node(g, oneapi::tbb::flow::serial, fun); multifunction_node<int, std::tuple<int>, rejecting_lightweight> rlw_node(g, oneapi::tbb::flow::serial, fun); } std::atomic<size_t> my_concurrency; std::atomic<size_t> my_max_concurrency; struct concurrency_functor { void operator()( const int& argument, oneapi::tbb::flow::multifunction_node<int, std::tuple<int>>::output_ports_type &op ) { ++my_concurrency; size_t old_value = my_max_concurrency; while(my_max_concurrency < my_concurrency && !my_max_concurrency.compare_exchange_weak(old_value, my_concurrency)) ; size_t ms = 1000; std::chrono::milliseconds sleep_time( ms ); std::this_thread::sleep_for( sleep_time ); --my_concurrency; std::get<0>(op).try_put(argument); } }; void test_node_concurrency(){ my_concurrency = 0; my_max_concurrency = 0; oneapi::tbb::flow::graph g; concurrency_functor counter; oneapi::tbb::flow::multifunction_node <int, std::tuple<int>> fnode(g, oneapi::tbb::flow::serial, counter); test_push_receiver<int> sink(g); make_edge(std::get<0>(fnode.output_ports()), sink); for(int i = 0; i < 10; ++i){ fnode.try_put(i); } g.wait_for_all(); CHECK_MESSAGE( ( my_max_concurrency.load() == 1), "Measured parallelism over limit"); } void test_priority(){ size_t concurrency_limit = 1; oneapi::tbb::global_control control(oneapi::tbb::global_control::max_allowed_parallelism, concurrency_limit); oneapi::tbb::flow::graph g; oneapi::tbb::flow::continue_node<int> source(g, [](oneapi::tbb::flow::continue_msg){ return 1;}); source.try_put(oneapi::tbb::flow::continue_msg()); first_functor<int>::first_id = -1; first_functor<int> low_functor(1); first_functor<int> high_functor(2); oneapi::tbb::flow::multifunction_node<int, std::tuple<int>> high(g, oneapi::tbb::flow::unlimited, high_functor, oneapi::tbb::flow::node_priority_t(1)); oneapi::tbb::flow::multifunction_node<int, std::tuple<int>> low(g, oneapi::tbb::flow::unlimited, low_functor); make_edge(source, low); make_edge(source, high); g.wait_for_all(); CHECK_MESSAGE( (first_functor<int>::first_id == 2), "High priority node should execute first"); } void test_rejecting(){ oneapi::tbb::flow::graph g; oneapi::tbb::flow::multifunction_node <int, std::tuple<int>, oneapi::tbb::flow::rejecting> fnode(g, oneapi::tbb::flow::serial, [&](const int& argument, oneapi::tbb::flow::multifunction_node<int, std::tuple<int>>::output_ports_type &op ){ size_t ms = 50; std::chrono::milliseconds sleep_time( ms ); std::this_thread::sleep_for( sleep_time ); std::get<0>(op).try_put(argument); }); test_push_receiver<int> sink(g); make_edge(std::get<0>(fnode.output_ports()), sink); for(int i = 0; i < 10; ++i){ fnode.try_put(i); } g.wait_for_all(); CHECK_MESSAGE( (get_count(sink) == 1), "Messages should be rejected while the first is being processed"); } //! Test multifunction_node with rejecting policy //! \brief \ref interface TEST_CASE("multifunction_node with rejecting policy"){ test_rejecting(); } //! Test priorities //! \brief \ref interface TEST_CASE("multifunction_node priority"){ test_priority(); } //! Test concurrency //! \brief \ref interface TEST_CASE("multifunction_node concurrency"){ test_node_concurrency(); } //! Test constructors //! \brief \ref interface TEST_CASE("multifunction_node constructors"){ test_policy_ctors(); } //! Test function_node buffering //! \brief \ref requirement TEST_CASE("multifunction_node buffering"){ test_rejecting_buffering(); } //! Test function_node broadcasting //! \brief \ref requirement TEST_CASE("multifunction_node broadcast"){ test_forwarding(); } //! Test body copying and copy_body logic //! \brief \ref interface TEST_CASE("multifunction_node constructors"){ test_copies(); } //! Test calling function body //! \brief \ref interface \ref requirement TEST_CASE("multifunction_node body") { test_multifunc_body(); } //! Test inheritance relations //! \brief \ref interface TEST_CASE("multifunction_node superclasses"){ test_inheritance<int, std::tuple<int>>(); test_inheritance<void*, std::tuple<float>>(); }
35.45092
178
0.666263
andrewseidl
868da85e54ad3dcd519f495da100e320daece72b
10,602
cpp
C++
ChaosDataService/ChaosDataService.cpp
fast01/chaosframework
28194bcca5f976fd5cf61448ca84ce545e94d822
[ "Apache-2.0" ]
2
2020-04-16T13:20:57.000Z
2021-06-24T02:05:25.000Z
ChaosDataService/ChaosDataService.cpp
fast01/chaosframework
28194bcca5f976fd5cf61448ca84ce545e94d822
[ "Apache-2.0" ]
null
null
null
ChaosDataService/ChaosDataService.cpp
fast01/chaosframework
28194bcca5f976fd5cf61448ca84ce545e94d822
[ "Apache-2.0" ]
null
null
null
/* * ChaosDataService.cpp * !CHOAS * Created by Bisegni Claudio. * * Copyright 2014 INFN, National Institute of Nuclear Physics * * 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 <csignal> #include "ChaosDataService.h" #include <boost/format.hpp> #include <chaos/common//direct_io/DirectIOServerEndpoint.h> using namespace std; using namespace chaos; using namespace chaos::data_service; using boost::shared_ptr; //! Regular expression for check server endpoint with the sintax hostname:[priority_port:service_port] static const boost::regex KVParamRegex("[a-zA-Z0-9/_]+:[a-zA-Z0-9/_]+(-[a-zA-Z0-9/_]+:[a-zA-Z0-9/_]+)*"); #define ChaosDataService_LOG_HEAD "[ChaosDataService] - " #define CDSLAPP_ LAPP_ << ChaosDataService_LOG_HEAD #define CDSLDBG_ LDBG_ << ChaosDataService_LOG_HEAD #define CDSLERR_ LERR_ << ChaosDataService_LOG_HEAD //boost::mutex ChaosCUToolkit::monitor; //boost::condition ChaosCUToolkit::endWaithCondition; WaitSemaphore ChaosDataService::waitCloseSemaphore; ChaosDataService::ChaosDataService() { } ChaosDataService::~ChaosDataService() { } //! C and C++ attribute parser /*! Specialized option for startup c and cpp program main options parameter */ void ChaosDataService::init(int argc, char* argv[]) throw (CException) { ChaosCommon<ChaosDataService>::init(argc, argv); } //!stringbuffer parser /* specialized option for string stream buffer with boost semantics */ void ChaosDataService::init(istringstream &initStringStream) throw (CException) { ChaosCommon<ChaosDataService>::init(initStringStream); } void ChaosDataService::fillKVParameter(std::map<std::string, std::string>& kvmap, const char * param_key) { //no cache server provided std::string kv_param_value = getGlobalConfigurationInstance()->getOption<std::string>(param_key); if(!regex_match(kv_param_value, KVParamRegex)) { throw chaos::CException(-3, "Malformed kv parameter string", __PRETTY_FUNCTION__); } std::vector<std::string> kvtokens; std::vector<std::string> kv_splitted; boost::algorithm::split(kvtokens, kv_param_value, boost::algorithm::is_any_of("-"), boost::algorithm::token_compress_on); for (int idx = 0; idx < kvtokens.size(); idx++) { //clear previosly pair kv_splitted.clear(); //get new pair boost::algorithm::split(kv_splitted, kvtokens[idx], boost::algorithm::is_any_of(":"), boost::algorithm::token_compress_on); // add key/value pair kvmap.insert(make_pair(kv_splitted[0], kv_splitted[1])); } } /* * */ void ChaosDataService::init(void *init_data) throw(CException) { try { ChaosCommon<ChaosDataService>::init(init_data); CDSLAPP_ << "Initializing CHAOS Control System Library"; if (signal((int) SIGINT, ChaosDataService::signalHanlder) == SIG_ERR){ CDSLERR_ << "SIGINT Signal handler registraiton error"; } if (signal((int) SIGQUIT, ChaosDataService::signalHanlder) == SIG_ERR){ CDSLERR_ << "SIGQUIT Signal handler registraiton error"; } if (signal((int) SIGTERM, ChaosDataService::signalHanlder) == SIG_ERR){ CDSLERR_ << "SIGTERM Signal handler registraiton error"; } //check for mandatory configuration if(!getGlobalConfigurationInstance()->hasOption(OPT_RUN_MODE)) { //no cache server provided throw chaos::CException(-1, "No run mode specified", __PRETTY_FUNCTION__); } if(!settings.cache_only && //we aren't in cache only (getGlobalConfigurationInstance()->getOption<unsigned int>(OPT_RUN_MODE) > BOTH || //check if we have a valid run mode getGlobalConfigurationInstance()->getOption<unsigned int>(OPT_RUN_MODE) < QUERY)) { //no cache server provided throw chaos::CException(-1, "Invalid run mode", __PRETTY_FUNCTION__); } //get the run mode and if we are in cache only.... enable only query mode run_mode = settings.cache_only?QUERY:(RunMode)getGlobalConfigurationInstance()->getOption<unsigned int>(OPT_RUN_MODE); //check for mandatory configuration if(!getGlobalConfigurationInstance()->hasOption(OPT_CACHE_SERVER_LIST)) { //no cache server provided throw chaos::CException(-1, "No cache server provided", __PRETTY_FUNCTION__); } if(run_mode == !getGlobalConfigurationInstance()->hasOption(OPT_DB_DRIVER_SERVERS)) { //no cache server provided throw chaos::CException(-2, "No index server provided", __PRETTY_FUNCTION__); } if(!settings.cache_only && getGlobalConfigurationInstance()->hasOption(OPT_VFS_STORAGE_DRIVER_KVP)) { fillKVParameter(ChaosDataService::getInstance()->settings.file_manager_setting.storage_driver_setting.key_value_custom_param, OPT_VFS_STORAGE_DRIVER_KVP); } if(!settings.cache_only && getGlobalConfigurationInstance()->hasOption(OPT_DB_DRIVER_KVP)) { fillKVParameter(ChaosDataService::getInstance()->settings.db_driver_setting.key_value_custom_param, OPT_DB_DRIVER_KVP); } //allocate the network broker CDSLAPP_ << "Allocate Network Brocker"; network_broker.reset(new NetworkBroker(), "NetworkBroker"); if(!network_broker.get()) throw chaos::CException(-1, "Error instantiating network broker", __PRETTY_FUNCTION__); network_broker.init(NULL, __PRETTY_FUNCTION__); //allocate the db driver if(!settings.cache_only && settings.db_driver_impl.compare("")) { //we have a db driver setuped std::string db_driver_class_name = boost::str(boost::format("%1%DBDriver") % settings.db_driver_impl); CDSLAPP_ << "Allocate index driver of type "<<db_driver_class_name; db_driver_ptr = chaos::ObjectFactoryRegister<db_system::DBDriver>::getInstance()->getNewInstanceByName(db_driver_class_name); if(!db_driver_ptr) throw chaos::CException(-1, "No index driver found", __PRETTY_FUNCTION__); chaos::utility::InizializableService::initImplementation(db_driver_ptr, &settings.db_driver_setting, db_driver_ptr->getName(), __PRETTY_FUNCTION__); } //chec if we ar ein cache only if(!settings.cache_only) { //configure the domain url equal to the directio io server one plus the deafult endpoint "0" settings.file_manager_setting.storage_driver_setting.domain.local_url = network_broker->getDirectIOUrl(); settings.file_manager_setting.storage_driver_setting.domain.local_url.append("|0"); //initialize vfs file manager CDSLAPP_ << "Allocate VFS Manager"; vfs_file_manager.reset(new vfs::VFSManager(db_driver_ptr), "VFSFileManager"); vfs_file_manager.init(&settings.file_manager_setting, __PRETTY_FUNCTION__); } if(run_mode == QUERY || run_mode == BOTH) { CDSLAPP_ << "Allocate the Query Data Consumer"; data_consumer.reset(new QueryDataConsumer(vfs_file_manager.get(), db_driver_ptr), "QueryDataConsumer"); if(!data_consumer.get()) throw chaos::CException(-1, "Error instantiating data consumer", __PRETTY_FUNCTION__); data_consumer->settings = &settings; data_consumer->network_broker = network_broker.get(); data_consumer.init(NULL, __PRETTY_FUNCTION__); } if(run_mode == INDEXER || run_mode == BOTH) { CDSLAPP_ << "Allocate the Data Consumer"; stage_data_consumer.reset(new StageDataConsumer(vfs_file_manager.get(), db_driver_ptr, &settings), "StageDataConsumer"); if(!stage_data_consumer.get()) throw chaos::CException(-1, "Error instantiating stage data consumer", __PRETTY_FUNCTION__); stage_data_consumer.init(NULL, __PRETTY_FUNCTION__); } } catch (CException& ex) { DECODE_CHAOS_EXCEPTION(ex) exit(1); } } /* * */ void ChaosDataService::start() throw(CException) { try { network_broker.start(__PRETTY_FUNCTION__); if(run_mode == QUERY || run_mode == BOTH) { data_consumer.start( __PRETTY_FUNCTION__); } if(run_mode == INDEXER || run_mode == BOTH) { stage_data_consumer.start(__PRETTY_FUNCTION__); } //print information header on CDS address CDSLAPP_ << "--------------------------------------------------------------------------------------"; CDSLAPP_ << "Chaos Data Service publisched with url: " << network_broker->getDirectIOUrl() << "|0"; CDSLAPP_ << "--------------------------------------------------------------------------------------"; waitCloseSemaphore.wait(); } catch (CException& ex) { DECODE_CHAOS_EXCEPTION(ex) } try { CDSLAPP_ << "Stoppping CHAOS Data Service"; stop(); deinit(); } catch (CException& ex) { DECODE_CHAOS_EXCEPTION(ex) exit(1); } } /* Stop the toolkit execution */ void ChaosDataService::stop() throw(CException) { network_broker.stop(__PRETTY_FUNCTION__); if(run_mode == QUERY || run_mode == BOTH) { data_consumer.stop( __PRETTY_FUNCTION__); } if(run_mode == INDEXER || run_mode == BOTH) { stage_data_consumer.stop(__PRETTY_FUNCTION__); } } /* Deiniti all the manager */ void ChaosDataService::deinit() throw(CException) { if((run_mode == QUERY || run_mode == BOTH ) && data_consumer.get()) { data_consumer.deinit(__PRETTY_FUNCTION__); CDSLAPP_ << "Release the endpoint associated to the Data Consumer"; network_broker->releaseDirectIOServerEndpoint(data_consumer->server_endpoint); } if((run_mode == INDEXER || run_mode == BOTH ) && stage_data_consumer.get()) { stage_data_consumer.deinit(__PRETTY_FUNCTION__); } if(network_broker.get()) { CDSLAPP_ << "Deinitializing CHAOS Data Service"; network_broker.deinit(__PRETTY_FUNCTION__); } //deinitialize vfs file manager vfs_file_manager.deinit(__PRETTY_FUNCTION__); if(db_driver_ptr) { CDSLAPP_ << "Deallocate index driver"; try { chaos::utility::InizializableService::deinitImplementation(db_driver_ptr, db_driver_ptr->getName(), __PRETTY_FUNCTION__); } catch (chaos::CException e) { CDSLAPP_ << e.what(); } delete (db_driver_ptr); } ChaosCommon<ChaosDataService>::deinit(); CDSLAPP_ << "Chaos Data service will exit now"; } /* * */ void ChaosDataService::signalHanlder(int signalNumber) { waitCloseSemaphore.unlock(); }
34.760656
157
0.709489
fast01
8692cf354b00f73644524d8b25e9052a004d8043
12,880
cpp
C++
temoto_action_assistant/src/ta_package_generator.cpp
temoto-framework/temoto_utils
208956e46a3d362a8db18c14ef0bcfc82bfb0b9a
[ "Apache-2.0" ]
null
null
null
temoto_action_assistant/src/ta_package_generator.cpp
temoto-framework/temoto_utils
208956e46a3d362a8db18c14ef0bcfc82bfb0b9a
[ "Apache-2.0" ]
1
2021-06-30T22:13:27.000Z
2021-06-30T22:13:27.000Z
temoto_action_assistant/src/ta_package_generator.cpp
temoto-telerobotics/temoto_utils
9492de31dbadeb7029e9746d55f934943acc3b99
[ "Apache-2.0" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2019 TeMoto Telerobotics * * 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 "temoto_action_assistant/ta_package_generator.h" #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <fstream> #include <set> namespace temoto_action_assistant { ActionPackageGenerator::ActionPackageGenerator(const std::string& file_template_path) : file_template_path_(file_template_path + "/") , file_templates_loaded_(false) { if (file_template_path_.empty()) { return; } // Import the CMakeLists template t_cmakelists = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_cmakelists.xml"); // Import the package.xml template t_packagexml = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_packagexml.xml"); // Import the action test templates //t_testlaunch_standalone = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_action_test_standalone.xml"); t_testlaunch_separate = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_action_test_separate.xml"); t_umrf_graph = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_umrf_graphtxt.xml"); // Import the macros.h template t_macros_header = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_macros_header.xml"); // Import the temoto_action.h template t_bridge_header = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_bridge_header.xml"); t_bridge_header_elif = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_update_params_elif.xml"); // Import the action implementation c++ code templates t_class_base = tp::TemplateContainer(file_template_path_ + "file_templates/ta_class_base.xml"); t_execute_action = tp::TemplateContainer(file_template_path_ + "file_templates/ta_execute_action.xml"); t_get_input_params = tp::TemplateContainer(file_template_path_ + "file_templates/ta_get_input_params.xml"); t_set_output_params = tp::TemplateContainer(file_template_path_ + "file_templates/ta_set_output_params.xml"); t_parameter_in = tp::TemplateContainer(file_template_path_ + "file_templates/ta_parameter_in.xml"); t_parameter_out = tp::TemplateContainer(file_template_path_ + "file_templates/ta_parameter_out.xml"); t_parameter_decl = tp::TemplateContainer(file_template_path_ + "file_templates/ta_parameter_decl.xml"); t_line_comment = tp::TemplateContainer(file_template_path_ + "file_templates/ta_line_comment.xml"); file_templates_loaded_ = true; } void ActionPackageGenerator::generatePackage(const UmrfNode& umrf, const std::string& package_path) { if (!file_templates_loaded_) { std::cout << "Could not generate a TeMoto action package because the file templates are not loaded" << std::endl; return; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * CREATE AI PACKAGE DIRECTORY STRUCTURE * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // Get the name of the package const std::string ta_package_name = umrf.getPackageName(); const std::string ta_dst_path = package_path + "/" + ta_package_name + "/"; // Create a package directory boost::filesystem::create_directories(ta_dst_path + "/src"); boost::filesystem::create_directories(ta_dst_path + "/launch"); boost::filesystem::create_directories(ta_dst_path + "/test"); boost::filesystem::create_directories(ta_dst_path + "/include/" + ta_package_name); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GENERATE THE CONTENT * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Extract the necessary datastructures from the umrf */ std::string ta_class_name = umrf.getName(); /* * Generate umrf.json */ std::ofstream umrf_json_file; umrf_json_file.open (ta_dst_path + "/umrf.json"); umrf_json_file << umrf_json_converter::toUmrfJsonStr(umrf, true); umrf_json_file.close(); /* * Generate invoker umrf graph */ UmrfNode invoker_umrf = umrf; invoker_umrf.getInputParametersNc().clear(); // Give input parameters some dummy values for (auto& param_in : umrf.getInputParameters()) { if (param_in.getType() == "string") { ActionParameters::ParameterContainer pc = param_in; pc.setData(boost::any(std::string("MODIFY THIS FIELD"))); invoker_umrf.getInputParametersNc().setParameter(pc, true); } else if (param_in.getType() == "number") { ActionParameters::ParameterContainer pc = param_in; pc.setData(boost::any(double(0.0))); invoker_umrf.getInputParametersNc().setParameter(pc, true); } } invoker_umrf.setSuffix(0); UmrfGraph invoker_umrf_graph(ta_package_name, std::vector<UmrfNode>{invoker_umrf}); generateGraph(invoker_umrf_graph, ta_dst_path + "/test"); /* * Generate CMakeLists.txt */ t_cmakelists.setArgument("ta_name", ta_package_name); t_cmakelists.processAndSaveTemplate(ta_dst_path, "CMakeLists"); /* * Generate package.xml */ t_packagexml.setArgument("ta_name", ta_package_name); t_packagexml.processAndSaveTemplate(ta_dst_path, "package"); /* * Generate the temoto_action header */ t_bridge_header.setArgument("ta_package_name", ta_package_name); std::ofstream bridge_header_file; bridge_header_file.open (ta_dst_path + "/include/" + ta_package_name + "/temoto_action.h"); bridge_header_file << t_bridge_header.processTemplate(); bridge_header_file.close(); /* * Generate invoke_action.launch */ t_testlaunch_separate.setArgument("ta_package_name", ta_package_name); t_testlaunch_separate.processAndSaveTemplate(ta_dst_path + "launch/", "invoke_action"); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Generate the action implementation c++ source file * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ std::string generated_content_cpp; std::set<std::string> input_param_update_set; /* * Generate the "getInputParameters()" function */ std::string gen_content_get_input_params; for (const auto& input_param : umrf.getInputParameters()) { std::string parameter_name = "in_param_" + input_param.getName(); boost::replace_all(parameter_name, "::", "_"); t_parameter_in.setArgument("param_name", input_param.getName()); t_parameter_in.setArgument("param_name_us", parameter_name); t_parameter_in.setArgument("param_type", input_param.getType()); t_bridge_header_elif.setArgument("param_type", input_param.getType()); if (action_parameter::PARAMETER_MAP.find(input_param.getType()) != action_parameter::PARAMETER_MAP.end()) { t_parameter_in.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(input_param.getType())); t_bridge_header_elif.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(input_param.getType())); } else { t_parameter_in.setArgument("param_type_us", input_param.getType()); t_bridge_header_elif.setArgument("param_type_us", input_param.getType()); } gen_content_get_input_params += " " + t_parameter_in.processTemplate() + "\n"; input_param_update_set.insert(t_bridge_header_elif.processTemplate()); } t_get_input_params.setArgument("function_body", gen_content_get_input_params); /* * Generate the "setOutputParameters()" function */ std::string gen_content_set_output_params; for (const auto& output_param : umrf.getOutputParameters()) { std::string parameter_name = "out_param_" + output_param.getName(); boost::replace_all(parameter_name, "::", "_"); t_parameter_out.setArgument("param_name_us", parameter_name); t_parameter_out.setArgument("param_name", output_param.getName()); t_parameter_out.setArgument("param_type", output_param.getType()); // if (action_parameter::PARAMETER_MAP.find(output_param.getType()) != action_parameter::PARAMETER_MAP.end()) // { // t_parameter_out.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(output_param.getType())); // } // else // { // t_parameter_out.setArgument("param_type_us", output_param.getType()); // } gen_content_set_output_params += " " + t_parameter_out.processTemplate() + "\n"; } t_set_output_params.setArgument("function_body", gen_content_set_output_params); /* * Declare input parameters */ std::string gen_content_input_param_decl; if (!umrf.getInputParameters().empty()) { t_line_comment.setArgument("comment", "Declaration of input parameters"); t_line_comment.setArgument("whitespace", "\n"); gen_content_input_param_decl += t_line_comment.processTemplate(); for (const auto& input_param : umrf.getInputParameters()) { std::string parameter_name = "in_param_" + input_param.getName(); boost::replace_all(parameter_name, "::", "_"); t_parameter_decl.setArgument("param_name_us", parameter_name); if (action_parameter::PARAMETER_MAP.find(input_param.getType()) != action_parameter::PARAMETER_MAP.end()) { t_parameter_decl.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(input_param.getType())); } else { t_parameter_decl.setArgument("param_type_us", input_param.getType()); } gen_content_input_param_decl += t_parameter_decl.processTemplate() + "\n"; } } /* * Declare output parameters */ std::string gen_content_output_param_decl; if (!umrf.getOutputParameters().empty()) { t_line_comment.setArgument("comment", "Declaration of output parameters"); t_line_comment.setArgument("whitespace", "\n"); gen_content_output_param_decl += t_line_comment.processTemplate(); for (const auto& output_param : umrf.getOutputParameters()) { std::string parameter_name = "out_param_" + output_param.getName(); boost::replace_all(parameter_name, "::", "_"); t_parameter_decl.setArgument("param_name_us", parameter_name); if (action_parameter::PARAMETER_MAP.find(output_param.getType()) != action_parameter::PARAMETER_MAP.end()) { t_parameter_decl.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(output_param.getType())); } else { t_parameter_decl.setArgument("param_type_us", output_param.getType()); } gen_content_output_param_decl += t_parameter_decl.processTemplate() + "\n"; } } /* * Put it all together and generate the whole class */ t_class_base.setArgument("ta_class_name", ta_class_name); t_class_base.setArgument("ta_package_name", ta_package_name); t_class_base.setArgument("fn_get_input_parameters", t_get_input_params.processTemplate()); t_class_base.setArgument("fn_set_output_parameters", t_set_output_params.processTemplate()); t_class_base.setArgument("fn_execute_action", t_execute_action.processTemplate()); t_class_base.setArgument("class_members", gen_content_input_param_decl + gen_content_output_param_decl); /* * Save the generated c++ content */ tp::saveStrToFile(t_class_base.processTemplate(), ta_dst_path + "/src", ta_package_name, ".cpp"); /* * Generate the temoto_action header */ t_bridge_header.setArgument("ta_package_name", ta_package_name); std::string elif_blocks; for (const auto& elif_block : input_param_update_set) { elif_blocks += elif_block; } t_bridge_header.setArgument("update_parameters_content", elif_blocks); tp::saveStrToFile(t_bridge_header.processTemplate(), ta_dst_path + "/include/" + ta_package_name, "temoto_action", ".h"); } void ActionPackageGenerator::generateGraph(const UmrfGraph& umrf_graph, const std::string& graphs_path) { std::ofstream umrf_graph_json_file; umrf_graph_json_file.open (graphs_path + "/" + umrf_graph.getName() + ".umrfg.json"); umrf_graph_json_file << umrf_json_converter::toUmrfGraphJsonStr(umrf_graph); umrf_graph_json_file.close(); } }// temoto_action_assistant namespace
41.548387
129
0.700233
temoto-framework
86950f91a7985ee46b02d1481306e0d3e26c72c8
921
cpp
C++
ex_12/principal.cpp
mihaioltean/poo
9c03eef52a0a03867af3e65f66f979b1ad702ccc
[ "MIT" ]
null
null
null
ex_12/principal.cpp
mihaioltean/poo
9c03eef52a0a03867af3e65f66f979b1ad702ccc
[ "MIT" ]
null
null
null
ex_12/principal.cpp
mihaioltean/poo
9c03eef52a0a03867af3e65f66f979b1ad702ccc
[ "MIT" ]
null
null
null
// ConsoleApplication15.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "complex.h" #include <stdio.h> int main() { t_complex c1; printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar()); t_complex c2(1, 2); printf("real = %f, imaginar = %f\n", c2.get_real(), c2.get_imaginar()); c1.aduna(c2); printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar()); c1.scade(c2); printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar()); t_complex c3; c3.set_real(4); c3.set_imaginar(2); c3.inmulteste(c2); printf("real = %f, imaginar = %f\n", c3.get_real(), c3.get_imaginar()); c1.aduna(c2, c3); printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar()); t_complex c4(c1); printf("real = %f, imaginar = %f\n", c4.get_real(), c4.get_imaginar()); printf("modul = %f\n", c4.modul()); getchar(); }
22.463415
111
0.631922
mihaioltean
8695b55ae79442abf1e50bc76548f0d30957e7c1
5,288
cpp
C++
src/core/Log.cpp
ElmerDellson/deferred-shading-full
4ed351028fe13432327164a551f71fd368b933b7
[ "MIT" ]
null
null
null
src/core/Log.cpp
ElmerDellson/deferred-shading-full
4ed351028fe13432327164a551f71fd368b933b7
[ "MIT" ]
null
null
null
src/core/Log.cpp
ElmerDellson/deferred-shading-full
4ed351028fe13432327164a551f71fd368b933b7
[ "MIT" ]
null
null
null
#include "config.hpp" #include "Log.h" #include <cstring> #include <cstdio> #include <sstream> #include <string> #include <iostream> #include <thread> #include <unordered_map> #ifdef _WIN32 # include <Windows.h> #endif #include <mutex> namespace Log { #define RESULT_MAX_STRING_LENGTH 16384 FILE *logfile = nullptr; void (* textout_func)(Type, const char *) = nullptr; std::unordered_map<size_t, size_t> once_map; size_t output_targets = LOG_OUT_STD | LOG_OUT_CUSTOM | LOG_OUT_FILE; std::mutex fileMutex; char log_result_string[RESULT_MAX_STRING_LENGTH]; bool logIncludeThreadID = false; struct LogSettings { Type type; std::string prefix; Verbosity verbosity; Severity severity; }; LogSettings logSettings[] = { { TYPE_SUCCESS , "Success: " , LOUD_UNSITUATED , OK }, { TYPE_INFO , "" , LOUD_UNSITUATED , OK }, { TYPE_NEUTRAL , "" , LOUD_UNSITUATED , OK }, { TYPE_WARNING , "Warning: " , LOUD , OK }, { TYPE_ERROR , "Error: " , LOUD , BAD }, { TYPE_FILE , "" , LOUD_UNSITUATED , OK }, { TYPE_ASSERT , "Assert: " , LOUD , BAD }, { TYPE_PARAM , "Parameter error: " , LOUD , BAD }, { TYPE_TRIVIA , "" , LOUD_UNSITUATED , OK } }; /*----------------------------------------------------------------------------*/ void Init() { SetOutputTargets(output_targets); } /*----------------------------------------------------------------------------*/ void Destroy() { fileMutex.lock(); if (!logfile) return; fprintf(logfile, "\n === End of log === \n\n"); fflush(logfile); fclose(logfile); logfile = nullptr; fileMutex.unlock(); } /*----------------------------------------------------------------------------*/ void SetCustomOutputTargetFunc(void (* textout)(Type, const char *)) { textout_func = textout; } /*----------------------------------------------------------------------------*/ void SetOutputTargets(size_t flags) { output_targets = flags; if (flags & LOG_OUT_FILE) { fileMutex.lock(); if (logfile == nullptr) { // Lazily initiate file logfile = fopen("log.txt", "w"); fprintf(logfile, "\n === Log (%s, %s) === \n\n", __DATE__, __TIME__); fflush(logfile); } fileMutex.unlock(); } } /*----------------------------------------------------------------------------*/ void SetVerbosity(Type type, Verbosity verbosity) { logSettings[size_t(type)].verbosity = verbosity; } /*----------------------------------------------------------------------------*/ void SetIncludeThreadID(bool inc) { logIncludeThreadID = inc; } /*----------------------------------------------------------------------------*/ void Report( unsigned int flags, const char *file, const char *function, int line, Type type, const char *str, ... ) { if (output_targets == 0) return; size_t t = size_t(type); #ifndef LOG_WHISPERS if (logSettings[t].verbosity == Verbosity::WHISPER) return; #endif size_t len; va_list args; va_start(args, str); vsnprintf(log_result_string, RESULT_MAX_STRING_LENGTH - 1, str, args); va_end(args); len = strlen(log_result_string); if (len >= (RESULT_MAX_STRING_LENGTH - 1)) strcat(&log_result_string[RESULT_MAX_STRING_LENGTH - 5], "..."); if (flags != 0) { std::ostringstream os; if ((flags & LOG_MESSAGE_ONCE_FLAG) != 0) os << file << function << std::to_string(line) << log_result_string; if ((type & LOG_LOCATION_ONCE_FLAG) != 0) os << "_Loc" << file << function << std::to_string(line); std::hash<std::string> hash_func; size_t hash = hash_func(os.str()); auto elem = once_map.find(hash); if (elem != once_map.end()) { elem->second++; // Count the number of hits return; } once_map[hash] = 1; } std::ostringstream os; if (logIncludeThreadID) { std::thread::id tid = std::this_thread::get_id(); os << "{" << tid << "} "; } if (logSettings[t].verbosity == LOUD) { if (line == -1) os << "[Unknown location]" << std::endl; else os << "[" << file << ", " << function << " (" << std::to_string(line) << ")]" << std::endl; } os << logSettings[t].prefix << log_result_string << std::endl; if (output_targets & LOG_OUT_STD) { #if defined(_WIN32) auto const widened_string = utils::widen(os.str()); fwprintf(logSettings[t].severity != Severity::OK ? stderr : stdout, L"%s", widened_string.c_str()); #else fprintf(logSettings[t].severity != Severity::OK ? stderr : stdout, "%s", os.str().c_str()); #endif } if (output_targets & LOG_OUT_FILE) { fileMutex.lock(); fprintf(logfile, "%s", os.str().c_str()); fflush(logfile); fileMutex.unlock(); } if (output_targets & LOG_OUT_CUSTOM && textout_func != nullptr) textout_func(type, os.str().c_str()); #ifdef _WIN32 if (logSettings[t].severity != Severity::OK && IsDebuggerPresent()) __debugbreak(); #endif if (logSettings[t].severity == Severity::TERMINAL) { Destroy(); exit(1); // TODO: Proper deconstruction } } /*----------------------------------------------------------------------------*/ bool ReportParam( unsigned int test, const char *file, const char *function, int line ) { bool t = test != 0; if (!t) Report(0, file, function, line, Type::TYPE_PARAM, "Bad parameter!"); return t; } /*----------------------------------------------------------------------------*/ };
25.669903
101
0.559191
ElmerDellson
8695dbf74fe9a4aa6113a3ddb2ffb2d1c86f0238
2,025
cpp
C++
bin/libs/systemc-2.3.1/src/sysc/kernel/sc_main.cpp
buaawj/Research
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
[ "OML" ]
9
2019-07-15T10:05:29.000Z
2022-03-14T12:55:19.000Z
bin/libs/systemc-2.3.1/src/sysc/kernel/sc_main.cpp
buaawj/Research
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
[ "OML" ]
2
2019-11-30T23:27:47.000Z
2021-11-02T12:01:05.000Z
systemc-2.3.1/src/sysc/kernel/sc_main.cpp
tianzhuqiao/bsmedit
3e443ed6db7b44b3b0da0e4bc024b65dcfe8e7a4
[ "MIT" ]
null
null
null
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** sc_main.cpp - Wrapper around user's toplevel routine `sc_main'. Original Author: Stan Y. Liao, Synopsys, Inc. CHANGE LOG APPEARS AT THE END OF THE FILE *****************************************************************************/ #include "sysc/kernel/sc_cmnhdr.h" #include "sysc/kernel/sc_externs.h" int main( int argc, char* argv[] ) { return sc_core::sc_elab_and_sim( argc, argv ); } // $Log: sc_main.cpp,v $ // Revision 1.5 2011/08/26 20:46:09 acg // Andy Goodrich: moved the modification log to the end of the file to // eliminate source line number skew when check-ins are done. // // Revision 1.4 2011/02/18 20:27:14 acg // Andy Goodrich: Updated Copyrights. // // Revision 1.3 2011/02/13 21:47:37 acg // Andy Goodrich: update copyright notice. // // Revision 1.2 2008/05/22 17:06:25 acg // Andy Goodrich: updated copyright notice to include 2008. // // Revision 1.1.1.1 2006/12/15 20:20:05 acg // SystemC 2.3 // // Revision 1.3 2006/01/13 18:44:29 acg // Added $Log to record CVS changes into the source. //
35.526316
79
0.614321
buaawj
8697a4bc2ddf75656c2d4f98a5b5280861daa1b2
1,796
cpp
C++
vulkan/source/QueryPool.cpp
mtezych/cpp
05c1b85eb89117a9b406f3f32470367937331614
[ "BSD-3-Clause" ]
null
null
null
vulkan/source/QueryPool.cpp
mtezych/cpp
05c1b85eb89117a9b406f3f32470367937331614
[ "BSD-3-Clause" ]
null
null
null
vulkan/source/QueryPool.cpp
mtezych/cpp
05c1b85eb89117a9b406f3f32470367937331614
[ "BSD-3-Clause" ]
2
2019-12-21T00:31:17.000Z
2021-07-14T23:16:23.000Z
#include <vulkan/QueryPool.h> #include <vulkan/Symbols.h> #include <vulkan/Device.h> namespace vk { QueryPool::CreateInfo::CreateInfo ( const VkQueryType queryType, const uint32_t queryCount ): createInfo { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, nullptr, 0, queryType, queryCount, VkQueryPipelineStatisticFlags { 0 }, } { assert(queryType != VK_QUERY_TYPE_PIPELINE_STATISTICS); } QueryPool::CreateInfo::CreateInfo ( const VkQueryType queryType, const uint32_t queryCount, const VkQueryPipelineStatisticFlags pipelineStatistics ): createInfo { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, nullptr, 0, queryType, queryCount, pipelineStatistics, } { assert(queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS); } QueryPool::QueryPool ( const Device& device, const CreateInfo& createInfo ): device { &device }, vkQueryPool { VK_NULL_HANDLE } { const auto result = device.vkCreateQueryPool ( device.vkDevice, &createInfo.createInfo, nullptr, &vkQueryPool ); assert(result == VK_SUCCESS); } QueryPool::~QueryPool () { if (vkQueryPool != VK_NULL_HANDLE) { device->vkDestroyQueryPool(device->vkDevice, vkQueryPool, nullptr); } } QueryPool::QueryPool (QueryPool&& queryPool) : device { queryPool.device }, vkQueryPool { queryPool.vkQueryPool } { queryPool.device = nullptr; queryPool.vkQueryPool = VK_NULL_HANDLE; } QueryPool& QueryPool::operator = (QueryPool&& queryPool) { if (vkQueryPool != VK_NULL_HANDLE) { device->vkDestroyQueryPool(device->vkDevice, vkQueryPool, nullptr); } device = queryPool.device; vkQueryPool = queryPool.vkQueryPool; queryPool.device = nullptr; queryPool.vkQueryPool = VK_NULL_HANDLE; return *this; } }
20.179775
70
0.711581
mtezych
869d12cee80b66df20a9d0c75be4533dab9e912e
18,679
hpp
C++
orb/include/morbid/handle_request_body.hpp
felipealmeida/mORBid
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
[ "BSL-1.0" ]
2
2018-01-31T07:06:23.000Z
2021-02-18T00:49:05.000Z
orb/include/morbid/handle_request_body.hpp
felipealmeida/mORBid
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
[ "BSL-1.0" ]
null
null
null
orb/include/morbid/handle_request_body.hpp
felipealmeida/mORBid
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
[ "BSL-1.0" ]
null
null
null
/* (c) Copyright 2012 Felipe Magno de Almeida * * 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 MORBID_HANDLE_REQUEST_BODY_HPP #define MORBID_HANDLE_REQUEST_BODY_HPP #include <morbid/any.hpp> #include <morbid/detail/max_args.hpp> #include <morbid/primitive_types.hpp> #include <morbid/type_tag.hpp> #include <morbid/in_out_traits.hpp> #include <morbid/arguments_traits.hpp> #include <morbid/transforms.hpp> #include <morbid/giop/grammars/arguments.hpp> #include <morbid/giop/grammars/message_1_0.hpp> #include <morbid/giop/grammars/reply_1_0.hpp> #include <morbid/iiop/all.hpp> #include <boost/fusion/include/fused.hpp> #include <boost/fusion/include/as_vector.hpp> #include <boost/fusion/include/make_vector.hpp> #include <boost/fusion/include/io.hpp> #include <boost/mpl/size.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/copy_if.hpp> #include <boost/type_traits/is_fundamental.hpp> namespace morbid { namespace fusion = boost::fusion; template <typename T> struct create_argument_transform; template <typename T> struct create_argument_transform<type_tag::value_type_tag<T, type_tag::in_tag> > { typedef type_tag::value_type_tag<T, type_tag::in_tag> tagged; BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename tagged::type> >)); typedef typename boost::add_reference<typename tagged::type>::type type; typedef type result_type; result_type operator()(result_type r) const { return r; } }; template <typename T> struct create_argument_transform<type_tag::value_type_tag<T, type_tag::out_tag> > { typedef type_tag::value_type_tag<T, type_tag::out_tag> tagged; typedef typename tagged::type type; typedef type result_type; result_type operator()(result_type r) const { return r; } }; template <typename T> struct create_argument_transform<type_tag::value_type_tag<T, type_tag::inout_tag> > { typedef type_tag::value_type_tag<T, type_tag::inout_tag> tagged; BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename tagged::type> >)); typedef typename boost::add_reference<typename tagged::type>::type type; typedef type result_type; result_type operator()(result_type r) const { return r; } }; template <> struct create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::in_tag> > { typedef const char* type; typedef type result_type; result_type operator()(std::string const& str) const { return str.c_str(); } }; template <> struct create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::out_tag> > : create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::in_tag> > { }; template <> struct create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::inout_tag> > : create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::in_tag> > { }; template <typename T> struct reply_argument_transform; template <typename T> struct reply_argument_transform<type_tag::value_type_tag<T, type_tag::out_tag> > { typedef type_tag::value_type_tag<T, type_tag::in_tag> tagged; typedef typename boost::add_reference<typename tagged::type>::type type; typedef type result_type; result_type operator()(result_type r) const { return r; } }; template <typename T> struct reply_argument_transform<type_tag::value_type_tag<T, type_tag::inout_tag> > : reply_argument_transform<type_tag::value_type_tag<T, type_tag::out_tag> > { }; template <> struct reply_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::out_tag> > { typedef std::string type; typedef type result_type; result_type operator()(const char* str) const { return str; } }; template <> struct reply_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::inout_tag> > : reply_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::out_tag> > { }; template <typename T> struct tag { }; template <typename ParseArguments, typename Condition, typename ResultLambda> struct initialize_arguments { template <typename R> struct result; template <typename This, int I, typename S, typename T> struct result<This(std::pair<mpl::int_<I>, S>const&, tag<T>const&)> { typedef typename mpl::apply1<typename mpl::lambda<Condition>::type, T>::type condition; typedef typename mpl::apply1<typename mpl::lambda<ResultLambda>::type, T>::type transform_result; typedef typename mpl::if_ <condition , std::pair<mpl::int_<I> , fusion::cons <transform_result, S> > , std::pair<mpl::int_<I+1> , fusion::cons <transform_result, S> > >::type type; }; initialize_arguments(ParseArguments& parse_arguments) : parse_arguments(parse_arguments) {} template <int I, typename S, typename T> typename result<initialize_arguments<ParseArguments, Condition, ResultLambda> (std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type call(std::pair<mpl::int_<I>, S>const& s, tag<T>const&, mpl::true_) const { BOOST_MPL_ASSERT((mpl::not_<boost::is_fundamental<T> >)); typedef typename mpl::apply1<typename mpl::lambda<ResultLambda>::type, T>::type type; return std::pair<mpl::int_<I>, fusion::cons<type, S> > (mpl::int_<I>(), fusion::cons<type, S>(type(), s.second)); } template <int I, typename S, typename T> typename result<initialize_arguments<ParseArguments, Condition, ResultLambda> (std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type call(std::pair<mpl::int_<I>, S>const& s, tag<T>const&, mpl::false_) const { BOOST_MPL_ASSERT((mpl::not_<boost::is_fundamental<T> >)); typedef typename mpl::apply1<typename mpl::lambda<ResultLambda>::type, T>::type type; typedef create_argument_transform<T> transform; typedef fusion::result_of::at_c<ParseArguments, I> arg_type; // BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename boost::remove_reference<arg_type>::type> >)); // BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename boost::remove_reference<typename transform::result_type>::type> >)); BOOST_MPL_ASSERT((boost::is_same<typename boost::result_of<transform(arg_type)>::type, type>)); return std::pair<mpl::int_<I+1>, fusion::cons<type, S> > (mpl::int_<I+1>(), fusion::cons<type, S> (transform()(fusion::at_c<I>(parse_arguments)), s.second)); } template <int I, typename S, typename T> typename result<initialize_arguments<ParseArguments, Condition, ResultLambda> (std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type operator()(std::pair<mpl::int_<I>, S>const& s, tag<T>const& t) const { BOOST_MPL_ASSERT((mpl::not_<boost::is_fundamental<T> >)); typedef typename mpl::apply1<typename mpl::lambda<Condition>::type, T>::type condition; return call(s, t, condition()); } ParseArguments& parse_arguments; }; template <typename ParseArguments> struct reply_arguments_generator { template <typename R> struct result; template <typename This, int I, typename S, typename T> struct result<This(std::pair<mpl::int_<I>, S>const&, tag<T>const&)> { template <typename U> struct create_pair { typedef std::pair<mpl::int_<I+1>, fusion::cons<typename reply_argument_transform<U>::type, S> > type; }; typedef type_tag::is_not_in_type_tag<T> is_not_in; typedef typename mpl::eval_if <is_not_in , create_pair<T> , mpl::identity<std::pair<mpl::int_<I>, S> > >::type type; }; reply_arguments_generator(ParseArguments& parse_arguments) : parse_arguments(parse_arguments) {} template <int I, typename S, typename T> typename result<reply_arguments_generator<ParseArguments>(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type call(std::pair<mpl::int_<I>, S> const& s, tag<T>const&, type_tag::in_tag) const { return s; } template <int I, typename S, typename T, typename Tag> typename result<reply_arguments_generator<ParseArguments>(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type call(std::pair<mpl::int_<I>, S> const& s, tag<T>const&, Tag) const { typedef reply_argument_transform<T> transform; typedef typename transform::type type; return std::pair<mpl::int_<I+1>, fusion::cons<type, S> > (mpl::int_<I+1>(), fusion::cons<type, S>(transform()(fusion::at_c<I>(parse_arguments)), s.second)); } template <int I, typename S, typename T> typename result<reply_arguments_generator<ParseArguments>(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type operator()(std::pair<mpl::int_<I>, S> const& s, tag<T>const& t) const { return call(s, t, typename T::tag()); } ParseArguments& parse_arguments; }; template <typename NotInParams, typename ReplyArguments> void make_request_reply(reply& r, ReplyArguments& reply_arguments) { std::cout << "Generating reply with reply arguments " << typeid(ReplyArguments).name() << std::endl; typedef ReplyArguments reply_argument_types; typedef giop::forward_back_insert_iterator<std::vector<char> > output_iterator_type; typedef std::vector<fusion::vector2<unsigned int, std::vector<char> > > service_context_list; typedef fusion::vector4<service_context_list , unsigned int, unsigned int , typename reply_argument_types::second_type> reply_attribute_type; typedef fusion::vector1<fusion::vector1<reply_attribute_type> > message_reply_attribute_type; typedef giop::grammars::arguments<iiop::generator_domain , output_iterator_type, NotInParams , typename reply_argument_types::second_type> arguments_grammar; typedef giop::grammars::reply_1_0<iiop::generator_domain , output_iterator_type, reply_attribute_type> reply_grammar; typedef giop::grammars::message_1_0<iiop::generator_domain , output_iterator_type, message_reply_attribute_type , 1u /* reply */> message_reply_grammar; morbid::arguments_traits arguments_traits; arguments_grammar arguments_grammar_(arguments_traits); reply_grammar reply_grammar_(arguments_grammar_); message_reply_grammar message_grammar_(reply_grammar_); service_context_list l; message_reply_attribute_type message_attribute (fusion::make_vector (reply_attribute_type (l , r.request_id , 0u /* NO_EXCEPTION */ , reply_arguments.second))); output_iterator_type iterator(r.reply_body); namespace karma = boost::spirit::karma; if(karma::generate(iterator, giop::compile<iiop::generator_domain> (message_grammar_(giop::native_endian)) , message_attribute)) { std::cout << "reply generated" << std::endl; } else { std::cout << "Failed generating reply" << std::endl; throw morbid::MARSHALL(); } } template <typename R, typename SeqParam, typename F, typename T, typename Args> void handle_request_reply(F f, T* self, reply& r, Args& args, mpl::identity<void>) { fusion::single_view<T*> self_view(self); fusion::joint_view<fusion::single_view<T*> const, Args> new_args(self_view, args); f(new_args); typedef Args argument_types; typedef typename mpl::lambda<type_tag::is_not_in_type_tag<mpl::_1> >::type is_not_in_lambda; typedef typename mpl::copy_if<SeqParam, is_not_in_lambda>::type not_in_params; typedef typename mpl::transform<SeqParam, create_argument_transform<mpl::_1> >::type mpl_argument_types; typedef typename mpl::transform<SeqParam, tag<mpl::_1> >::type mpl_identity_argument_types; typedef typename fusion::result_of::as_vector<mpl_identity_argument_types>::type identity_argument_types; identity_argument_types const identity_arguments; typedef typename boost::remove_reference< typename fusion::result_of::fold<identity_argument_types const, std::pair<mpl::int_<0>, fusion::nil> , reply_arguments_generator<argument_types> >::type >::type reply_argument_types; std::cout << "reply_argument_types " << typeid(reply_argument_types).name() << std::endl; reply_argument_types reply_arguments = fusion::fold(identity_arguments, std::pair<mpl::int_<0>, fusion::nil>() , reply_arguments_generator<argument_types>(args)); make_request_reply<not_in_params>(r, reply_arguments); } template <typename R, typename SeqParam, typename F, typename T, typename Args> void handle_request_reply(F f, T* self, reply& r, Args& args, mpl::identity<R>) { fusion::single_view<T*> self_view(self); fusion::joint_view<fusion::single_view<T*> const, Args> new_args(self_view, args); typename return_traits<R>::type result = f(new_args); typedef Args argument_types; typedef type_tag::value_type_tag<R, type_tag::out_tag> result_tag; typedef typename mpl::push_front<SeqParam, result_tag>::type sequence_params; typedef typename mpl::lambda<type_tag::is_not_in_type_tag<mpl::_1> >::type is_not_in_lambda; typedef typename mpl::copy_if<sequence_params, is_not_in_lambda>::type not_in_params; typedef typename mpl::transform<sequence_params, create_argument_transform<mpl::_1> >::type mpl_argument_types; typedef typename mpl::transform<sequence_params, tag<mpl::_1> >::type mpl_identity_argument_types; typedef typename fusion::result_of::as_vector<mpl_identity_argument_types>::type identity_argument_types; identity_argument_types const identity_arguments; typedef fusion::cons<typename return_traits<R>::type, argument_types> args_with_result_type; typedef typename boost::remove_reference< typename fusion::result_of::fold<identity_argument_types const, std::pair<mpl::int_<0>, fusion::nil> , reply_arguments_generator<args_with_result_type> >::type >::type reply_argument_types; std::cout << "reply_argument_types " << typeid(reply_argument_types).name() << std::endl; args_with_result_type args_with_result(result, args); reply_argument_types reply_arguments = fusion::fold(identity_arguments, std::pair<mpl::int_<0>, fusion::nil>() , reply_arguments_generator <args_with_result_type> (args_with_result)); make_request_reply<not_in_params>(r, reply_arguments); } template <typename R, typename SeqParam, typename T, typename F> void handle_request_body(T* self, F f, std::size_t align_offset , const char* rq_first, const char* rq_last , bool little_endian, reply& r) { std::cout << "handle_request_body " << typeid(f).name() << " align_offset " << align_offset << std::endl; typedef typename mpl::lambda<type_tag::is_not_out_type_tag<mpl::_1> >::type is_not_out_lambda; typedef typename mpl::copy_if<SeqParam, is_not_out_lambda>::type not_out_params; typedef typename mpl::transform <not_out_params, transforms::from_unmanaged_to_managed<mpl::_1> >::type mpl_parse_argument_types; typedef typename fusion::result_of::as_vector<mpl_parse_argument_types>::type parse_argument_types; parse_argument_types parse_arguments; morbid::arguments_traits arguments_traits; typedef giop::grammars::arguments<iiop::parser_domain , const char*, not_out_params , parse_argument_types> arguments_grammar; arguments_grammar arguments_grammar_(arguments_traits); namespace qi = boost::spirit::qi; if(qi::parse(rq_first, rq_last , giop::compile<iiop::parser_domain> (iiop::aligned(align_offset)[arguments_grammar_(giop::endian(little_endian))]) , parse_arguments)) { std::cout << "Parsed arguments correctly " << typeid(parse_arguments).name() << std::endl; std::cout << "Arguments parsed " << parse_arguments << std::endl; std::cout << "handle_request_body not_out_params " << typeid(parse_argument_types).name() << std::endl; typedef typename mpl::transform<SeqParam, create_argument_transform<mpl::_1> >::type mpl_argument_types; typedef typename mpl::transform<SeqParam, tag<mpl::_1> >::type mpl_identity_argument_types; typedef typename fusion::result_of::as_vector<mpl_identity_argument_types>::type identity_argument_types; identity_argument_types const identity_arguments; typedef typename boost::remove_reference< typename fusion::result_of::fold <identity_argument_types const , std::pair<mpl::int_<0>, fusion::nil> , initialize_arguments <parse_argument_types , type_tag::is_out_type_tag<mpl::_> , mpl::if_ < mpl::and_ <type_tag::is_not_out_type_tag<mpl::_1> , mpl::not_<boost::is_same <mpl::_1, type_tag::value_type_tag<morbid::string, type_tag::in_tag> > > > , boost::add_reference<type_tag::value_type<mpl::_1> > , boost::remove_reference<type_tag::value_type<mpl::_1> > > > >::type >::type argument_types; std::cout << "handle_request_body not_out_params " << typeid(identity_argument_types).name() << std::endl; std::cout << "handle_request_body not_out_params " << typeid(argument_types).name() << std::endl; std::pair<mpl::int_<0>, fusion::nil> const pair; argument_types arguments = fusion::fold (identity_arguments, pair, initialize_arguments <parse_argument_types // Default construct out types , type_tag::is_out_type_tag<mpl::_> // Add reference to not out types (to avoid copying) , mpl::if_ < mpl::and_ <type_tag::is_not_out_type_tag<mpl::_1> , mpl::not_<boost::is_same <mpl::_1, type_tag::value_type_tag<morbid::string, type_tag::in_tag> > > > , boost::add_reference<type_tag::value_type<mpl::_1> > , boost::remove_reference<type_tag::value_type<mpl::_1> > > > (parse_arguments)); // Calling function with arguments fusion::fused<F> fused(f); // Create reply handle_request_reply<R, SeqParam>(fused, self, r, arguments.second , mpl::identity<R>()); } else { throw morbid::MARSHALL(); } } } #endif
38.198364
128
0.693506
felipealmeida
869f10223b79d175e5bdc5e96de65f67f7c57dfe
2,050
cpp
C++
week 1/Arrays/10First_Repeating_Element.cpp
arpit456jain/gfg-11-Weeks-Workshop-on-DSA-in-CPP
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
[ "MIT" ]
6
2021-08-06T14:36:41.000Z
2022-03-22T11:22:07.000Z
week 1/Arrays/10First_Repeating_Element.cpp
arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
[ "MIT" ]
1
2021-08-09T05:09:48.000Z
2021-08-09T05:09:48.000Z
week 1/Arrays/10First_Repeating_Element.cpp
arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
[ "MIT" ]
1
2021-08-09T14:25:17.000Z
2021-08-09T14:25:17.000Z
// Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest. // Input: // n = 7 // arr[] = {1, 5, 3, 4, 3, 5, 6} // Output: 2 // Explanation: // 5 is appearing twice and // its first appearence is at index 2 // which is less than 3 whose first // occuring index is 3. #include<bits/stdc++.h> using namespace std; class Solution{ public: int optimizeApproch(int arr[],int n) { // T.C : O(N) // logic is i will take a another array and will store position of 1st occurence at that number vector<int> arr2(1000000,0); int min=-1; for(int i = 0; i < n; i++) { if(arr2[arr[i]]==0) arr2[arr[i]] = i+1; // inserting index of 1st occurence of element at that number else { // min = arr2[arr[i]]; if(min == -1) min = arr2[arr[i]]; else { if(arr2[arr[i]]<=min) min = arr2[arr[i]]; } } // cout<<min<<"\n"; } return min; } int naiveApproch(int arr[],int n) { // T.C : O(n*n) for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(arr[i] == arr[j]) return i+1; } } } //Function to return the position of the first repeating element. int firstRepeated(int arr[], int n) { //code here // int res = naiveApproch(arr,n); int res = optimizeApproch(arr,n); return res; } }; // { Driver Code Starts. int main(){ int t; cin >> t; while(t--){ int n; cin >> n; int arr[n]; for(int i = 0 ; i < n ; ++ i ) cin >> arr[i] ; Solution ob; cout << ob.firstRepeated(arr,n) << "\n"; } return 0; } // } Driver Code Ends
24.698795
171
0.46
arpit456jain
869fbf4e6e0ec99cada0c4b1137a78c2d16fe019
3,070
cpp
C++
trainings/2015-07-25-Multi-University-2015-1 /F.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-07-25-Multi-University-2015-1 /F.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-07-25-Multi-University-2015-1 /F.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <cstdio> #include <algorithm> #include <vector> using namespace std; const int N = 222222; int n, m; vector<int> adj[N]; int height[N], parent[N], dist[N], dp[N]; int father[N][20]; vector<pair<pair<int, int>, int> > chain[N]; int jump(int x, int k) { for (int i = 0; i < 20; ++i) { if (k >> i & 1) { x = father[x][i]; } } return x; } int lca(int x, int y) { if (height[x] < height[y]) { swap(x, y); } x = jump(x, height[x] - height[y]); if (x == y) { return x; } for (int i = 19; i >= 0; --i) { if (father[x][i] != father[y][i]) { x = father[x][i]; y = father[y][i]; } } return father[x][0]; } int find(int x) { if (parent[x] != x) { int root = find(parent[x]); dist[x] += dist[parent[x]]; return parent[x] = root; } else { return x; } } void mergy(int x, int y, int w) { x = find(x); y = find(y); parent[x] = y; dist[x] = w; } void solve(void) { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { adj[i].clear(); chain[i].clear(); } for (int i = 1; i < n; ++i) { int x, y; scanf("%d%d", &x, &y); adj[x].push_back(y); adj[y].push_back(x); } vector<int> queue; height[1] = 0; father[1][0] = 0; queue.push_back(1); for (int head = 0; head < (int)queue.size(); ++head) { int x = queue[head]; for (int i = 0; i < (int)adj[x].size(); ++i) { int y = adj[x][i]; if (y == father[x][0]) { continue; } height[y] = height[x] + 1; father[y][0] = x; queue.push_back(y); } } for (int j = 1; j < 20; ++j) { for (int i = 1; i <= n; ++i) { father[i][j] = father[father[i][j - 1]][j - 1]; } } for (int i = 1; i <= m; ++i) { int x, y, w; scanf("%d%d%d", &x, &y, &w); chain[lca(x, y)].push_back(make_pair(make_pair(x, y), w)); } for (int i = 1; i <= n; ++i) { parent[i] = i; dist[i] = 0; } for (int head = n - 1; head >= 0; --head) { int x = queue[head]; int sum = 0; for (int i = 0; i < (int)adj[x].size(); ++i) { int y = adj[x][i]; if (y == father[x][0]) { continue; } sum += dp[y]; } dp[x] = sum; for (int i = 0; i < (int)chain[x].size(); ++i) { int a = chain[x][i].first.first; int b = chain[x][i].first.second; int son1 = jump(a, height[a] - height[x] - 1); int son2 = jump(b, height[b] - height[x] - 1); find(a); find(b); dp[x] = max(dp[x], chain[x][i].second + sum + dist[a] + dist[b]); } mergy(x, father[x][0], sum - dp[x]); } printf("%d\n", dp[1]); } int main(void) { int tests; for (scanf("%d", &tests); tests--; solve()) { } }
21.928571
77
0.400977
HcPlu
86a1de77dee7fd33df55aee618ae8d1601b75d41
191
cpp
C++
regression/esbmc-cpp/cbmc/Templates14/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/cbmc/Templates14/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/cbmc/Templates14/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
#include<cassert> namespace n1 { template <class S> struct A{ S a; }; } template <class T> struct B{ n1::A<T> b; }; int main() { B<bool> o; o.b.a = true; assert(o.b.a==true); };
8.681818
22
0.560209
shmarovfedor
86a241a4e23586a1c13ad92a9e9114eb42fdcac3
6,313
cpp
C++
3rdparty/webkit/Source/WebCore/PAL/pal/crypto/commoncrypto/CryptoDigestCommonCrypto.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
WebLayoutCore/Source/WebCore/PAL/pal/crypto/commoncrypto/CryptoDigestCommonCrypto.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebCore/PAL/pal/crypto/commoncrypto/CryptoDigestCommonCrypto.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
1
2018-07-10T10:53:18.000Z
2018-07-10T10:53:18.000Z
/* * Copyright (C) 2013 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. 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. */ #include "config.h" #include "CryptoDigest.h" #include <CommonCrypto/CommonCrypto.h> namespace PAL { struct CryptoDigestContext { CryptoDigest::Algorithm algorithm; void* ccContext; }; inline CC_SHA1_CTX* toSHA1Context(CryptoDigestContext* context) { ASSERT(context->algorithm == CryptoDigest::Algorithm::SHA_1); return static_cast<CC_SHA1_CTX*>(context->ccContext); } inline CC_SHA256_CTX* toSHA224Context(CryptoDigestContext* context) { ASSERT(context->algorithm == CryptoDigest::Algorithm::SHA_224); return static_cast<CC_SHA256_CTX*>(context->ccContext); } inline CC_SHA256_CTX* toSHA256Context(CryptoDigestContext* context) { ASSERT(context->algorithm == CryptoDigest::Algorithm::SHA_256); return static_cast<CC_SHA256_CTX*>(context->ccContext); } inline CC_SHA512_CTX* toSHA384Context(CryptoDigestContext* context) { ASSERT(context->algorithm == CryptoDigest::Algorithm::SHA_384); return static_cast<CC_SHA512_CTX*>(context->ccContext); } inline CC_SHA512_CTX* toSHA512Context(CryptoDigestContext* context) { ASSERT(context->algorithm == CryptoDigest::Algorithm::SHA_512); return static_cast<CC_SHA512_CTX*>(context->ccContext); } CryptoDigest::CryptoDigest() : m_context(new CryptoDigestContext) { } CryptoDigest::~CryptoDigest() { switch (m_context->algorithm) { case CryptoDigest::Algorithm::SHA_1: delete toSHA1Context(m_context.get()); return; case CryptoDigest::Algorithm::SHA_224: delete toSHA224Context(m_context.get()); return; case CryptoDigest::Algorithm::SHA_256: delete toSHA256Context(m_context.get()); return; case CryptoDigest::Algorithm::SHA_384: delete toSHA384Context(m_context.get()); return; case CryptoDigest::Algorithm::SHA_512: delete toSHA512Context(m_context.get()); return; } } std::unique_ptr<CryptoDigest> CryptoDigest::create(CryptoDigest::Algorithm algorithm) { std::unique_ptr<CryptoDigest> digest(new CryptoDigest); digest->m_context->algorithm = algorithm; switch (algorithm) { case CryptoDigest::Algorithm::SHA_1: { CC_SHA1_CTX* context = new CC_SHA1_CTX; digest->m_context->ccContext = context; CC_SHA1_Init(context); return digest; } case CryptoDigest::Algorithm::SHA_224: { CC_SHA256_CTX* context = new CC_SHA256_CTX; digest->m_context->ccContext = context; CC_SHA224_Init(context); return digest; } case CryptoDigest::Algorithm::SHA_256: { CC_SHA256_CTX* context = new CC_SHA256_CTX; digest->m_context->ccContext = context; CC_SHA256_Init(context); return digest; } case CryptoDigest::Algorithm::SHA_384: { CC_SHA512_CTX* context = new CC_SHA512_CTX; digest->m_context->ccContext = context; CC_SHA384_Init(context); return digest; } case CryptoDigest::Algorithm::SHA_512: { CC_SHA512_CTX* context = new CC_SHA512_CTX; digest->m_context->ccContext = context; CC_SHA512_Init(context); return digest; } } } void CryptoDigest::addBytes(const void* input, size_t length) { switch (m_context->algorithm) { case CryptoDigest::Algorithm::SHA_1: CC_SHA1_Update(toSHA1Context(m_context.get()), input, length); return; case CryptoDigest::Algorithm::SHA_224: CC_SHA224_Update(toSHA224Context(m_context.get()), input, length); return; case CryptoDigest::Algorithm::SHA_256: CC_SHA256_Update(toSHA256Context(m_context.get()), input, length); return; case CryptoDigest::Algorithm::SHA_384: CC_SHA384_Update(toSHA384Context(m_context.get()), input, length); return; case CryptoDigest::Algorithm::SHA_512: CC_SHA512_Update(toSHA512Context(m_context.get()), input, length); return; } } Vector<uint8_t> CryptoDigest::computeHash() { Vector<uint8_t> result; switch (m_context->algorithm) { case CryptoDigest::Algorithm::SHA_1: result.resize(CC_SHA1_DIGEST_LENGTH); CC_SHA1_Final(result.data(), toSHA1Context(m_context.get())); break; case CryptoDigest::Algorithm::SHA_224: result.resize(CC_SHA224_DIGEST_LENGTH); CC_SHA224_Final(result.data(), toSHA224Context(m_context.get())); break; case CryptoDigest::Algorithm::SHA_256: result.resize(CC_SHA256_DIGEST_LENGTH); CC_SHA256_Final(result.data(), toSHA256Context(m_context.get())); break; case CryptoDigest::Algorithm::SHA_384: result.resize(CC_SHA384_DIGEST_LENGTH); CC_SHA384_Final(result.data(), toSHA384Context(m_context.get())); break; case CryptoDigest::Algorithm::SHA_512: result.resize(CC_SHA512_DIGEST_LENGTH); CC_SHA512_Final(result.data(), toSHA512Context(m_context.get())); break; } return result; } } // namespace PAL
35.072222
85
0.708063
mchiasson
86a62e1bbf39a71c8842b26242f5954e67788ccd
505
cpp
C++
test/TestCell.cpp
samsparks/climaze
a49dc0a926f86311212a61e837ebb46e2a387fe2
[ "MIT" ]
null
null
null
test/TestCell.cpp
samsparks/climaze
a49dc0a926f86311212a61e837ebb46e2a387fe2
[ "MIT" ]
null
null
null
test/TestCell.cpp
samsparks/climaze
a49dc0a926f86311212a61e837ebb46e2a387fe2
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include "Cell.hpp" BOOST_AUTO_TEST_SUITE(TestCell) BOOST_AUTO_TEST_CASE( Initialization ) { Cell c; BOOST_CHECK_EQUAL( c.Visited(), false ); BOOST_CHECK_EQUAL( c.Opened(), false ); } BOOST_AUTO_TEST_CASE( Accessors ) { Cell c; BOOST_CHECK_EQUAL( c.Visited(), false ); BOOST_CHECK_EQUAL( c.Visit().Visited(), true ); BOOST_CHECK_EQUAL( c.Opened(), false ); BOOST_CHECK_EQUAL( c.Open().Opened(), true ); } BOOST_AUTO_TEST_SUITE_END()
21.956522
51
0.69901
samsparks
86a696f79263c4449c62684bb7931f717285dd35
3,711
cpp
C++
src/game/cmd/LsPlayers.cpp
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
25
2016-05-27T11:53:58.000Z
2021-10-17T00:13:41.000Z
src/game/cmd/LsPlayers.cpp
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
1
2016-07-09T05:25:03.000Z
2016-07-09T05:25:03.000Z
src/game/cmd/LsPlayers.cpp
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
16
2016-05-28T23:06:50.000Z
2022-01-26T13:47:12.000Z
#include <bgame/impl.h> namespace cmd { /////////////////////////////////////////////////////////////////////////////// LsPlayers::LsPlayers() : AbstractBuiltin( "lsplayers" ) { __usage << xvalue( "!" + _name ); __descr << "Display all players connected, their client numbers and admin levels."; } /////////////////////////////////////////////////////////////////////////////// LsPlayers::~LsPlayers() { } /////////////////////////////////////////////////////////////////////////////// AbstractCommand::PostAction LsPlayers::doExecute( Context& txt ) { if (txt._args.size() != 1) return PA_USAGE; // bail if nothing to display if (level.numConnectedClients < 1) { txt._ebuf << "There are no players online."; return PA_ERROR; } InlineText colA = xheader; InlineText colB = xheader; InlineText colC = xheader; InlineText colD = xheader; InlineText colE = xheader; InlineText colF = xheader; InlineText colG = xheader; InlineText colH = xheader; InlineText colI = xheader; colC.flags |= ios::left; colD.flags |= ios::left; colE.flags |= ios::left; colF.flags |= ios::left; colA.width = 2; colB.width = 1; colC.width = 1; colD.width = 31; colE.width = 15; colF.width = 6; colG.width = 6; colH.width = 4; colI.width = 2; colB.prefixOutside = " "; colD.prefixOutside = " "; colE.prefixOutside = " "; colF.prefixOutside = " "; colG.prefixOutside = " "; colH.prefixOutside = " "; colI.prefixOutside = " "; Buffer buf; buf << colA( "##" ) << colB( "C" ) << colC( "M" ) << colD( "NAME" ) << colE( "LEVEL" ) << colF( "TEAM" ) << colG( "XP" ) << colH( "PING" ) << colI( "NC" ) << '\n'; colA.color = xcnone; colB.color = xcnone; colC.color = xcnone; colD.color = xcnone; colE.color = xcnone; colF.color = xcnone; colG.color = xcnone; colH.color = xcnone; colI.color = xcnone; string tmp; for (int i = 0; i < MAX_CLIENTS; i++) { User& user = *connectedUsers[i]; if (user == User::BAD) continue; Client& cobj = g_clientObjects[i]; string err; Level& lev = levelDB.fetchByKey( user.authLevel, err ); gclient_t& client = level.clients[i]; buf << colA( i ) << colB( (client.pers.connected == CON_CONNECTING ? 'C' : '-') ) << colC( (user.muted ? 'M' : '-') ) << colD( str::etAlignLeft( user.namex, colD.width, tmp )); if (lev.namex.empty()) buf << colE( lev.level ); else buf << colE( str::etAlignLeft( lev.namex, colE.width, tmp )); switch (client.sess.sessionTeam) { case TEAM_ALLIES: colF.color = xcblue; buf << colF( "allies" ); break; case TEAM_AXIS: colF.color = xcred; buf << colF( "axis" ); break; case TEAM_SPECTATOR: default: colF.color = xcyellow; buf << colF( "spec" ); break; } // FIELD: XP float xp = 0.0f; for (int si = 0; si < SK_NUM_SKILLS; si++) xp += client.sess.skillpoints[si]; buf << colG( int(xp) ) << colH( client.ps.ping ) << colI( cobj.numNameChanges > 99 ? 99 : cobj.numNameChanges ) << '\n'; } print( txt._client, buf ); return PA_NONE; } /////////////////////////////////////////////////////////////////////////////// } // namespace cmd
25.244898
87
0.466451
jumptohistory
86ab04821b716af2f4d5e29a2f3d8159b6f8e943
1,255
cc
C++
src/constants.cc
IoanaIleana/SigmodContest
589bc86deecea953b40c2ce07759d35e397bd9c8
[ "MIT" ]
null
null
null
src/constants.cc
IoanaIleana/SigmodContest
589bc86deecea953b40c2ce07759d35e397bd9c8
[ "MIT" ]
null
null
null
src/constants.cc
IoanaIleana/SigmodContest
589bc86deecea953b40c2ce07759d35e397bd9c8
[ "MIT" ]
null
null
null
#include <sys/types.h> #include <stdint.h> #include "constants.h" uint64_t one64 = (uint64_t)1; uint64_t zero64 = (uint64_t)0; uint64_t max64 = ~zero64; uint64_t mod64mask=(uint64_t)63; uint64_t masks64[(int)64] = { one64<<(int)0, one64<<(int)1, one64<<(int)2, one64<<(int)3, one64<<(int)4, one64<<(int)5, one64<<(int)6, one64<<(int)7, one64<<(int)8, one64<<(int)9, one64<<(int)10, one64<<(int)11, one64<<(int)12, one64<<(int)13, one64<<(int)14, one64<<(int)15, one64<<(int)16, one64<<(int)17, one64<<(int)18, one64<<(int)19, one64<<(int)20, one64<<(int)21, one64<<(int)22, one64<<(int)23, one64<<(int)24, one64<<(int)25, one64<<(int)26, one64<<(int)27, one64<<(int)28, one64<<(int)29, one64<<(int)30, one64<<(int)31, one64<<(int)32, one64<<(int)33, one64<<(int)34, one64<<(int)35, one64<<(int)36, one64<<(int)37, one64<<(int)38, one64<<(int)39, one64<<(int)40, one64<<(int)41, one64<<(int)42, one64<<(int)43, one64<<(int)44, one64<<(int)45, one64<<(int)46, one64<<(int)47, one64<<(int)48, one64<<(int)49, one64<<(int)50, one64<<(int)51, one64<<(int)52, one64<<(int)53, one64<<(int)54, one64<<(int)55, one64<<(int)56, one64<<(int)57, one64<<(int)58, one64<<(int)59, one64<<(int)60, one64<<(int)61, one64<<(int)62, one64<<(int)63 };
54.565217
129
0.627888
IoanaIleana
86ad2f272ece6f715f3e4a3865c7db6c9eefbb4c
1,158
cpp
C++
084-Largest-Rectangle-in-Histogram-recursion/solution.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
3
2019-05-27T06:47:32.000Z
2020-12-22T05:57:10.000Z
084-Largest-Rectangle-in-Histogram-recursion/solution.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
null
null
null
084-Largest-Rectangle-in-Histogram-recursion/solution.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
5
2020-04-01T10:26:04.000Z
2022-02-05T18:21:01.000Z
#include "solution.hpp" static auto x = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams cin.tie(NULL); return 0; }(); int Solution::largestRectangleArea(vector<int>& heights) { if (heights.empty()) return 0; list<pair<int, int>> lowest; for (int i = 0; i < heights.size(); ++i) lowest.emplace_back(make_pair(heights[i], i)); lowest.sort([](const pair<int, int>& a, const pair<int, int>& b) {return a.first < b.first;}); return findRect(heights, lowest, 0, heights.size()-1); } int Solution::findRect(vector<int>& heights, list<pair<int, int>>& lowest, int start, int end) { if (start > end) return 0; else if (start == end) return heights[start]; auto itr = lowest.begin(); int k; while (itr != lowest.end()) { int i = itr->second; if (i >= start && i <= end) { k = i; break; } itr++; } if (itr == lowest.end()) return 0; lowest.erase(itr); int middle = (end - start + 1) * heights[k]; int left = findRect(heights, lowest, start, k-1); int right = findRect(heights, lowest, k+1, end); return std::max(left, std::max(middle, right)); }
26.930233
97
0.604491
johnhany
86aebf64d96bab3224c7033e0f19fc7e07caa00c
549
hpp
C++
src/toolkits/style_transfer/class_registrations.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/toolkits/style_transfer/class_registrations.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/toolkits/style_transfer/class_registrations.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/* Copyright © 2019 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at * https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_STYLE_TRANSFER_REGISTRATION_H_ #define TURI_STYLE_TRANSFER_REGISTRATION_H_ #include <model_server/lib/toolkit_function_macros.hpp> namespace turi { namespace style_transfer { std::vector<toolkit_class_specification> get_toolkit_class_registration(); } // namespace style_transfer } // namespace turi #endif
27.45
74
0.788707
Bpowers4
86afcbe00d257676a7de93191471ab9a62e960cd
411
cpp
C++
src/view/progress.cpp
lucekdudek/ceppem_i_mieczem
cf94d0aa64811ea056cba342fc7f93e9ae27ffa5
[ "Apache-2.0" ]
null
null
null
src/view/progress.cpp
lucekdudek/ceppem_i_mieczem
cf94d0aa64811ea056cba342fc7f93e9ae27ffa5
[ "Apache-2.0" ]
null
null
null
src/view/progress.cpp
lucekdudek/ceppem_i_mieczem
cf94d0aa64811ea056cba342fc7f93e9ae27ffa5
[ "Apache-2.0" ]
null
null
null
#include "progress.h" Progress::Progress(int x, int y, int width, int height, char* name, char* path) : Texture(x, y, width, height, path) { this->name = _strdup(name); this->max_width = width; fill = 100; } Progress::~Progress() { delete name; } void Progress::setFill(unsigned char fill) { this->fill = fill; this->width = max_width*fill / 100; } char* Progress::getName() { return this->name; }
15.222222
116
0.6618
lucekdudek
86b891def1227fbabd7f4c6cc149f0376a3c67c2
2,440
cpp
C++
cpp/libs/src/opendnp3/master/ClearRestartTask.cpp
spazzarama/opendnp3
44c06cb148d40ed150e539895b3fa951376e5f74
[ "Apache-2.0" ]
1
2020-05-07T16:31:30.000Z
2020-05-07T16:31:30.000Z
cpp/libs/src/opendnp3/master/ClearRestartTask.cpp
spazzarama/opendnp3
44c06cb148d40ed150e539895b3fa951376e5f74
[ "Apache-2.0" ]
null
null
null
cpp/libs/src/opendnp3/master/ClearRestartTask.cpp
spazzarama/opendnp3
44c06cb148d40ed150e539895b3fa951376e5f74
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2013-2019 Automatak, LLC * * Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak * LLC (www.automatak.com) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Green Energy Corp and Automatak LLC license * this file to you under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain * a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ClearRestartTask.h" #include <openpal/logging/LogMacros.h> #include "opendnp3/LogLevels.h" #include "opendnp3/app/APDUBuilders.h" #include "opendnp3/master/MasterTasks.h" using namespace openpal; namespace opendnp3 { ClearRestartTask::ClearRestartTask(const std::shared_ptr<TaskContext>& context, IMasterApplication& application, const openpal::Logger& logger) : IMasterTask(context, application, TaskBehavior::ReactsToIINOnly(), logger, TaskConfig::Default()) { } bool ClearRestartTask::BuildRequest(APDURequest& request, uint8_t seq) { build::ClearRestartIIN(request, seq); return true; } IMasterTask::ResponseResult ClearRestartTask::ProcessResponse(const APDUResponseHeader& response, const openpal::RSlice& /*objects*/) { // we only care that the response to this has FIR/FIN if (ValidateSingleResponse(response)) { if (response.IIN.IsSet(IINBit::DEVICE_RESTART)) { // we tried to clear the restart, but the device responded with the restart still set SIMPLE_LOG_BLOCK(logger, flags::ERR, "Clear restart task failed to clear restart bit, permanently disabling task"); return ResponseResult::ERROR_BAD_RESPONSE; } return ResponseResult::OK_FINAL; } else { return ResponseResult::ERROR_BAD_RESPONSE; } } } // namespace opendnp3
35.362319
107
0.690164
spazzarama
86bd7fc0594dfde72fb9d711ca70b6741b599ffe
3,199
cpp
C++
src/basegui/TextViewControllerImplementor.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
1
2016-03-26T13:25:08.000Z
2016-03-26T13:25:08.000Z
src/basegui/TextViewControllerImplementor.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
src/basegui/TextViewControllerImplementor.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
#include "TextViewControllerImplementor.h" #include "TextViewController.h" #include "qt_glue/FontMetrics.h" using namespace Magna::Glue; namespace Magna{ namespace GUI{ TextViewControllerImplementor::TextViewControllerImplementor( TextViewController & binding ) :m_textBoundingRect() ,m_binding( binding ) ,m_avgHeight( 0 ) ,m_lineBreakStrings() ,m_vtextSpacing(0) ,m_text(){ _remeasureText(); } TextViewControllerImplementor::TextViewControllerImplementor( TextViewController & binding , const String& text ) :m_textBoundingRect() ,m_binding( binding ) ,m_avgHeight( 0 ) ,m_lineBreakStrings() ,m_vtextSpacing(0) ,m_text( text ){ _remeasureText(); } TextViewControllerImplementor::~TextViewControllerImplementor(){ } void TextViewControllerImplementor::rendering( RenderingEventArgs& eventArgs ){ if( eventArgs.isAccepted() ){ auto *_2d_manager = eventArgs.getRenderManager2D(); if( _2d_manager != Nullptr ){ Canvas2DDrawer _drawer; if( _2d_manager->retrieveDrawer( _drawer ) != false ){ //normal state _drawer.clearRectRegion( eventArgs.getRenderingRectRegion() ); _drawer.setFont( m_binding.getFont() ); auto _each_x = m_textBoundingRect.getBottomLeftCoord().getX(); auto _each_y = m_textBoundingRect.getBottomLeftCoord().getY(); for( auto _iter = m_lineBreakStrings.begin(); _iter != m_lineBreakStrings.end(); ++_iter ){ _each_y += m_avgHeight; _drawer.drawText( IntegerDyadCoordinate(_each_x, _each_y ), *_iter ); _each_y += m_vtextSpacing; } _2d_manager->pullbackDrawer( _drawer ); } } } } void TextViewControllerImplementor::_remeasureText(){ //get split strings m_lineBreakStrings = m_text.split( L"\\n" ); FontMetrics _metrics = FontMetrics( m_binding.getFont() ); IntegerSize _boundingTextSize; for( auto _iter = m_lineBreakStrings.begin(); _iter != m_lineBreakStrings.end(); ++_iter ){ _metrics.setMetricsText( *_iter ); const auto &_each_size = _metrics.measureSize(); m_avgHeight += _each_size.getHeight(); _boundingTextSize.joinedBy( _each_size ); } //get average height m_avgHeight /= m_lineBreakStrings.size(); m_textBoundingRect.setSize( _boundingTextSize ); //get bounding size and center pos const auto &_half_size = (m_binding.getSize() / 2); if( _half_size.getWidth() - _boundingTextSize.getWidth() > 0 && _half_size.getHeight() - _boundingTextSize.getHeight() > 0){ IntegerDyadCoordinate _translated_coord( _half_size.getWidth() - (_boundingTextSize.getWidth() / 2 ) , _half_size.getHeight() - (_boundingTextSize.getHeight() / 2 ) - (_boundingTextSize.getHeight() / 4 ) ); /* normalized value */ m_textBoundingRect.translatedBy( _translated_coord ); } } } }
33.673684
147
0.626758
0of
86c19bcc21103493fbaf704185b71f7c110bad87
269
cpp
C++
Beginner/P1150.cpp
Muntaha-Islam0019/URI-Online-Judge-Solutions
9db9cdfffe81378512e406eb14cd8525f0e013c3
[ "MIT" ]
1
2019-08-28T21:19:21.000Z
2019-08-28T21:19:21.000Z
Beginner/P1150.cpp
Muntaha-Islam0019/URI-Online-Judge-Solutions
9db9cdfffe81378512e406eb14cd8525f0e013c3
[ "MIT" ]
null
null
null
Beginner/P1150.cpp
Muntaha-Islam0019/URI-Online-Judge-Solutions
9db9cdfffe81378512e406eb14cd8525f0e013c3
[ "MIT" ]
null
null
null
#include<stdio.h> int main() { int x,z,a=1,c=0,i; scanf("%d %d",&x,&z); while(x>=z) { scanf("%d",&z); } for(i=x; i<z; i++) { c += i; if(c>z) break; a++; } printf("%d\n",a); return 0; }
13.45
25
0.330855
Muntaha-Islam0019
f864a7c0098829c3fb06d77aee813880b0866700
4,521
cpp
C++
sources/test/Main.cpp
Naoki-Nakagawa/GameLibrary
0b20938a19a293f76c177726a8e70ddce0dbeeb5
[ "MIT" ]
2
2017-05-23T17:19:17.000Z
2017-05-30T10:28:38.000Z
sources/test/Main.cpp
Naoki-Nakagawa/GameDevelopmentKit
0b20938a19a293f76c177726a8e70ddce0dbeeb5
[ "MIT" ]
61
2018-02-11T08:27:32.000Z
2018-06-01T11:01:57.000Z
sources/test/Main.cpp
itukikikuti/GameLibrary
0b20938a19a293f76c177726a8e70ddce0dbeeb5
[ "MIT" ]
null
null
null
#define XLIBRARY_NAMESPACE_BEGIN #define XLIBRARY_NAMESPACE_END #include "../Library.hpp" #include "../LibraryGenerator.cpp" #include <sstream> #include "Sub.hpp" using namespace std; int Main() { LibraryGenerator::Generate(L"sources/Library.hpp", L"XLibrary11.hpp"); Debug::OpenConsole(); printf("aaaaaa"); Sprite sprite1(L"assets/box.jpg"); Camera camera; camera.position = Float3(0.0f, 1.0f, -5.0f); camera.SetupPerspective(); camera.color = Float4(0.0f, 0.0f, 0.0f, 1.0f); Camera uiCamera; uiCamera.color = Float4(1.0f, 0.0f, 1.0f, 1.0f); uiCamera.clear = false; uiCamera.SetupOrthographic((float)Window::GetSize().y, true); Texture texture(L"assets/box.jpg"); Texture playerTexture(L"assets/player.png"); Mesh mesh; mesh.CreateCube(Float3(2.0f, 1.0f, 0.5f)); mesh.SetTexture(&texture); Mesh sphere; sphere.CreateSphere(); sphere.SetTexture(&playerTexture); sphere.position.y = 2.0f; Light directionalLight; directionalLight.type = Light::Type::Directional; directionalLight.angles = Float3(-50.0f, 30.0f, 0.0); directionalLight.intensity = 0.5f; directionalLight.Update(); Light light; light.type = Light::Type::Point; light.position.z = -1.0f; light.color = Float4(0.0f, 1.0f, 0.0f, 0.0f); Light light2; light2.type = Light::Type::Point; light2.position = Float3(1.0f, 1.0f, 0.5f); light2.range = 2.0f; light2.color = Float4(1.0f, 0.0f, 0.0f, 0.0f); light2.intensity = 2.0f; light2.Update(); Light light3; light3.type = Light::Type::Point; light3.position = Float3(-0.5f, 1.0f, -2.0f); light3.range = 3.0f; light3.color = Float4(0.0f, 0.0f, 1.0f, 0.0f); light3.intensity = 10.0f; light3.Update(); Text number(L"0", 100.0f); number.position.y = 3.0f; number.scale = 1.0f / 100.0f; number.color = Float4(1.0f, 0.0f, 0.0f, 1.0f); number.antialias = false; Sound music(L"assets/music.mp3"); music.SetPitch(1.0f); music.SetVolume(0.5f); music.SetPan(0.0f); music.SetLoop(true); music.Play(); Sound sound(L"assets/sound.wav"); sprite1.position.x = 1.0f; sprite1.scale = 1.0f / 256.0f; Text text(L"あいうえおかきくけこさしすせそ\nabcdefghijklmnopqrstuvwxyz", 16.0f); //text.SetPivot(Float2(-1.0f, 1.0f)); text.position.x = 200.0f; text.position.y = 100.0f; text.scale = 2.0f; text.color = Float4(1.0f, 1.0f, 1.0f, 1.0f); Sprite sprite(L"assets/box.jpg"); sprite.scale = 0.5f; sprite.color.w = 0.5f; Sprite clock(L"assets/clock.png"); clock.scale = 0.2f; clock.angles.z = -135.0f; float pos1 = -2.0f; float pos2 = -3.0f; while (Refresh()) { camera.Update(); PrintFrameRate(); //printf("%d\n", Random::Range(0, 10)); light.position.x = Input::GetMousePosition().x * 0.01f; light.position.y = Input::GetMousePosition().y * 0.01f; light.Update(); music.SetPitch(Input::GetMousePosition().x / (Window::GetSize().x / 2.0f)); if (Input::GetKeyDown('J')) music.Play(); if (Input::GetKeyDown('K')) music.Pause(); if (Input::GetKeyDown('L')) music.Stop(); if (Input::GetKeyDown(VK_SPACE)) { sound.Play(); } if (Input::GetPadButtonDown(0, XINPUT_GAMEPAD_A)) { sound.Play(); } if (Input::GetKeyDown('3')) { Window::SetMode(Window::Mode::FullScreen); } number.angles.y += 1.0f; number.Create(std::to_wstring(Input::GetMouseWheel()), 100.0f); if (Input::GetKey('2')) { wstringstream ss; ss << Timer::GetTime(); number.Create(ss.str(), 100.0f); } number.position.x = pos1; number.color = Float4(1.0f, 0.0f, 0.0f, 1.0f); number.Draw(); pos2 += 0.01f; number.position.x = pos2; number.color = Float4(0.0f, 0.0f, 1.0f, 1.0f); number.Draw(); mesh.angles.z += Input::GetPadLeftThumb(0).y * 3.0f; mesh.angles.y += -Input::GetPadLeftThumb(0).x * 3.0f; mesh.position.x = 0.5f; mesh.angles.x = Input::GetPadRightTrigger(0) * 90.0f; mesh.Draw(); mesh.position.x = -0.5f; mesh.angles.x = Input::GetPadLeftTrigger(0) * 90.0f; mesh.Draw(); sphere.angles.x += Input::GetMouseWheel() * 0.5f; sphere.Draw(); if (Input::GetKey('1')) Input::SetMousePosition(0.0f, 0.0f); sprite1.angles.z = Random::GetValue() * 360.0f; sprite1.Draw(); uiCamera.Update(); text.angles.z += Timer::GetDeltaTime() * 30.0f; text.Draw(); sprite.position.x = Window::GetSize().x / 2.0f - sprite.GetSize().x * sprite.scale.x / 2.0f; sprite.position.y = Window::GetSize().y / 2.0f - sprite.GetSize().y * sprite.scale.y / 2.0f; //sprite.angles.z += 10.0f; sprite.Draw(); clock.position = Input::GetMousePosition(); clock.Draw(); } return 0; }
23.670157
94
0.65605
Naoki-Nakagawa
f8657d1c9ea4495e752b30883a01aadab8614356
6,878
cc
C++
src/ufo/filters/ProcessAMVQI.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
null
null
null
src/ufo/filters/ProcessAMVQI.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
10
2020-12-10T22:57:51.000Z
2020-12-17T15:57:04.000Z
src/ufo/filters/ProcessAMVQI.cc
NOAA-EMC/ufo
3bf1407731b79eab16ceff64129552577d9cfcd0
[ "Apache-2.0" ]
3
2020-12-10T18:38:22.000Z
2020-12-11T01:36:37.000Z
/* * (C) Copyright 2021 Met Office * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include "ufo/filters/ProcessAMVQI.h" #include <algorithm> #include <string> #include <vector> #include "ioda/distribution/Accumulator.h" #include "ioda/ObsSpace.h" #include "oops/util/Logger.h" #include "ufo/filters/processWhere.h" namespace ufo { // ----------------------------------------------------------------------------- ProcessAMVQI::ProcessAMVQI(ioda::ObsSpace & obsdb, const Parameters_ & parameters, std::shared_ptr<ioda::ObsDataVector<int>> flags, std::shared_ptr<ioda::ObsDataVector<float>> obserr) : ObsProcessorBase(obsdb, false /*deferToPost?*/, flags, obserr), parameters_(parameters) { oops::Log::trace() << "ProcessAMVQI contructor starting" << std::endl; } // ----------------------------------------------------------------------------- ProcessAMVQI::~ProcessAMVQI() { oops::Log::trace() << "ProcessAMVQI destructed" << std::endl; } // ----------------------------------------------------------------------------- /*! \brief A filter to convert new BUFR formatted data into variables with names * corressponding to the wind generating application. * * Example: * \code{.unparsed} * obs filter: * - filter: Process AMV QI * number of generating apps: 4 * \endcode * * \author A.Martins (Met Office) * * \date 02/08/2021: Created */ void ProcessAMVQI::doFilter() const { oops::Log::trace() << "ProcessAMVQI doFilter" << std::endl; const float missing = util::missingValue(float()); const int int_missing = util::missingValue(int()); const size_t nlocs = obsdb_.nlocs(); const size_t number_of_apps = parameters_.number_of_apps.value(); // vectors to store BUFR data std::vector<float> percent_confidence(nlocs); std::vector<int> wind_generating_application(nlocs); // Create vector of strings for percent_confidence_<number> to new variable // Wind generating application number = QI type // Table 1: // 1 = Full weighted mixture of individual quality tests // 2 = Weighted mixture of individual tests, but excluding forecast comparison // 3 = Recursive filter function // 4 = Common quality index (QI) without forecast // 5 = QI without forecast // 6 = QI with forecast // 7 = Estimated Error (EE) in m/s converted to a percent confidence std::vector<std::string> new_variables = { "QI_full_weighted_mixture", "QI_weighted_mixture_exc_forecast_comparison", "QI_recursive_filter_function", "QI_common", "QI_without_forecast", "QI_with_forecast", "QI_estimated_error" }; const size_t total_variables = new_variables.size(); // create variable to write to obsdb std::vector<std::vector<float>> new_percent_confidence(total_variables, std::vector<float>(nlocs, missing)); // diagnostic variables to be summed over all processors std::unique_ptr<ioda::Accumulator<size_t>> count_bad_app_accumulator = obsdb_.distribution()->createAccumulator<size_t>(); // Get BUFR data for (size_t iapp = 0; iapp < number_of_apps; ++iapp) { // names of variables std::string percent_confidence_name = "percent_confidence_"; std::string wind_generating_application_name = "wind_generating_application_"; obsdb_.get_db("MetaData", percent_confidence_name.append(std::to_string(iapp + 1)), percent_confidence); obsdb_.get_db("MetaData", wind_generating_application_name.append(std::to_string(iapp + 1)), wind_generating_application); for (size_t idata = 0; idata < nlocs; ++idata) { if (wind_generating_application[idata] != int_missing) { // check index is in range before filling new percent confidence values if (wind_generating_application[idata] >= 1 && wind_generating_application[idata] <= total_variables) { new_percent_confidence[wind_generating_application[idata] - 1][idata] = percent_confidence[idata]; } else { count_bad_app_accumulator->addTerm(idata, 1); } } } } // sum number of generating application values that are out of range const std::size_t count_bad_app = count_bad_app_accumulator->computeResult(); if (count_bad_app > 0) { oops::Log::warning() << "Process AMV QI: " << count_bad_app << " instances of generating application out of range" << std::endl; } // Need to check database for the named variables and add to them if they exist. for (size_t inum = 0; inum < total_variables; ++inum) { if (std::any_of(new_percent_confidence[inum].begin(), new_percent_confidence[inum].end(), [missing] (float elem) {return elem != missing;})) { // Check if new_variable already exists in obsdb std::vector<float> existing_new_percent_confidence(nlocs, missing); if (obsdb_.has("MetaData", new_variables[inum])) { obsdb_.get_db("MetaData", new_variables[inum], existing_new_percent_confidence); } else { oops::Log::trace() << "ProcessAMIQI: New variable: " << new_variables[inum] << " not present in input data" << std::endl; } // Check if existing_new_percent_confidence has non-missing values // and update new_percent_confidence. for (size_t idata = 0; idata < nlocs; ++idata) { if (existing_new_percent_confidence[idata] != missing) { if (new_percent_confidence[inum][idata] == missing) { new_percent_confidence[inum][idata] = existing_new_percent_confidence[idata]; } else { oops::Log::trace() << "[WARN] New variable (created from new BUFR data)" << "\n" "[WARN] already has value in old BUFR format" << "\n" "[WARN] new BUFR: " << new_percent_confidence[inum][idata] << "\n" "[WARN] old BUFR: " << existing_new_percent_confidence[idata] << "\n"; } } } // write to new or existing QI vectors obsdb_.put_db("MetaData", new_variables[inum], new_percent_confidence[inum]); } } } // ----------------------------------------------------------------------------- void ProcessAMVQI::print(std::ostream & os) const { os << "ProcessAMVQI filter" << parameters_ << std::endl; } // ----------------------------------------------------------------------------- } // namespace ufo
37.791209
93
0.597267
NOAA-EMC
f8716a35f8febaa7bcaacc60edae0820d3de250b
1,297
hpp
C++
src/llvm-passes/Location.hpp
ucd-plse/eesi
aacbcecbb8c1f1d2e152ee4a0aa417ac92ae74bb
[ "BSD-3-Clause" ]
5
2019-07-01T09:05:32.000Z
2019-09-03T17:36:26.000Z
src/llvm-passes/Location.hpp
defreez-ucd/eesi-doi
49b51f9a01b8c1dbbe110898c27ec714034132aa
[ "CC-BY-4.0" ]
3
2019-08-01T03:14:48.000Z
2019-09-03T20:40:52.000Z
src/llvm-passes/Location.hpp
defreez-ucd/eesi-doi
49b51f9a01b8c1dbbe110898c27ec714034132aa
[ "CC-BY-4.0" ]
2
2019-06-10T23:08:27.000Z
2020-09-29T01:20:49.000Z
// The pair of file / line number is the best unique identifier for an // instruction that we have that remains constant between llvm instantiations. #ifndef LOCATION_HPP #define LOCATION_HPP #include "llvm/Support/raw_ostream.h" #include <string> class Location { public: std::string file; unsigned line = 0; Location() {} Location(std::string file, unsigned line) : file(file), line(line) {} Location(std::pair<std::string, unsigned> loc) : file(loc.first), line(loc.second) {} bool empty() const { return line == 0; } bool operator==(const Location& right) const { return file == right.file && line == right.line; } bool operator!=(const Location& right) const { return file != right.file || line != right.line; } // So Locations can be inserted into sets bool operator<(const Location& right) const { if (file == right.file) { return line < right.line; } else { return file < right.file; } } // TODO: Add hash std::string str() const { return file + ":" + std::to_string(line); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Location &L) { return OS << L.str(); } friend std::ostream &operator<<(std::ostream &OS, const Location &L) { return OS << L.str(); } }; #endif
23.160714
87
0.643793
ucd-plse
f874668564f613d9c24db90e684e040d5d3ee28e
678
hh
C++
include/helper.hh
kretash/old_school_fps
c9c1951939fdf810fff58ebc04818972e92ffc77
[ "MIT" ]
null
null
null
include/helper.hh
kretash/old_school_fps
c9c1951939fdf810fff58ebc04818972e92ffc77
[ "MIT" ]
null
null
null
include/helper.hh
kretash/old_school_fps
c9c1951939fdf810fff58ebc04818972e92ffc77
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #include "math.hh" static inline uint32_t create_color( float r, float g, float b, float a ) { uint32_t color = ( uint8_t ) ( def_clamp( a * 255.0f, 0.0f, 255.0f ) ) << 24 | ( uint8_t ) ( def_clamp( b * 255.0f, 0.0f, 255.0f ) ) << 16 | ( uint8_t ) ( def_clamp( g * 255.0f, 0.0f, 255.0f ) ) << 8 | ( uint8_t ) ( def_clamp( r * 255.0f, 0.0f, 255.0f ) ); return color; } static inline uint32_t create_color( float r, float g, float b ) { return create_color( r, g, b, 1.0f ); } static inline uint32_t create_color( float4 color ) { return create_color( color.x, color.y, color.z, color.w ); }
27.12
75
0.591445
kretash
f87521729fac8e1404a245d2045aa299107a68f2
1,374
cpp
C++
Samples/ObjectInOffice/IDataObject.cpp
ntclark/Graphic
86acc119d172bb53c1666432538836b461d8a3f2
[ "BSD-3-Clause" ]
12
2018-03-15T00:20:55.000Z
2021-08-11T10:02:15.000Z
Samples/ObjectInOffice/IDataObject.cpp
ntclark/Graphic
86acc119d172bb53c1666432538836b461d8a3f2
[ "BSD-3-Clause" ]
null
null
null
Samples/ObjectInOffice/IDataObject.cpp
ntclark/Graphic
86acc119d172bb53c1666432538836b461d8a3f2
[ "BSD-3-Clause" ]
2
2019-04-09T17:15:31.000Z
2020-12-05T19:52:59.000Z
// Copyright 2018 InnoVisioNate Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ObjectInOffice.h" STDMETHODIMP ObjectInOffice::GetData(FORMATETC *,STGMEDIUM *) { return S_OK; } STDMETHODIMP ObjectInOffice::GetDataHere(FORMATETC *,STGMEDIUM *) { return S_OK; } STDMETHODIMP ObjectInOffice::QueryGetData(FORMATETC *) { return S_OK; } STDMETHODIMP ObjectInOffice::GetCanonicalFormatEtc(FORMATETC *,FORMATETC *) { return S_OK; } STDMETHODIMP ObjectInOffice::SetData(FORMATETC *,STGMEDIUM *,BOOL) { return S_OK; } STDMETHODIMP ObjectInOffice::EnumFormatEtc(DWORD,IEnumFORMATETC **) { return S_OK; } STDMETHODIMP ObjectInOffice::DAdvise(FORMATETC *pFormatEtc,DWORD advf,IAdviseSink *pIAS,DWORD *pdwConnection) { return E_NOTIMPL; //if ( ! pDataAdviseHolder ) // CreateDataAdviseHolder(&pDataAdviseHolder); //if ( pDataAdviseHolder ) // pDataAdviseHolder -> Advise(static_cast<IDataObject *>(this),pFormatEtc,advf,pIAS,pdwConnection); //return S_OK; } STDMETHODIMP ObjectInOffice::DUnadvise(DWORD dwConnection) { if ( pDataAdviseHolder ) pDataAdviseHolder -> Unadvise(dwConnection); return S_OK; } STDMETHODIMP ObjectInOffice::EnumDAdvise(IEnumSTATDATA **) { return S_OK; }
28.040816
114
0.720524
ntclark
f8767f849911f1eca9300a2ea16e8808007407f3
476
cc
C++
2021_1011_1017/887.cc
guohaoqiang/leetcode
802447c029c36892e8dd7391c825bcfc7ac0fd0b
[ "MIT" ]
null
null
null
2021_1011_1017/887.cc
guohaoqiang/leetcode
802447c029c36892e8dd7391c825bcfc7ac0fd0b
[ "MIT" ]
null
null
null
2021_1011_1017/887.cc
guohaoqiang/leetcode
802447c029c36892e8dd7391c825bcfc7ac0fd0b
[ "MIT" ]
null
null
null
class Solution { public: int superEggDrop(int k, int n) { vector<vector<int>> dp(10001,vector<int>(k+1,0)); int m = 0; // m: #move // dp[m][k]: the #floors can be tested using m moves and k eggs while (dp[m][k]<n){ m++; for (int j=1; j<=k; ++j){ // the j-th drop + not break + break dp[m][j] = 1 + dp[m-1][j] + dp[m-1][j-1]; } } return m; } };
26.444444
71
0.413866
guohaoqiang
f879833a3b649dfc90b7f50ad0a2c0bbb8b3b7bf
1,677
cpp
C++
solutions/c++/problems/[0017_Medium] Letter Combinations of a Phone Number.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
6
2021-02-20T14:00:22.000Z
2022-03-31T15:26:44.000Z
solutions/c++/problems/[0017_Medium] Letter Combinations of a Phone Number.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
solutions/c++/problems/[0017_Medium] Letter Combinations of a Phone Number.cpp
RageBill/leetcode
a11d411f4e38b5c3f05ca506a193f50b25294497
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<vector<char>> cart_product(const vector<vector<char>> &v) { vector<vector<char>> s = {{}}; for (auto &u: v) { vector<vector<char>> r; for (auto &x: s) { for (auto y: u) { r.push_back(x); r.back().push_back(y); } } s.swap(r); } return s; } vector<char> getLetter(char num) { switch (num) { case '2': return {'a', 'b', 'c'}; case '3': return {'d', 'e', 'f'}; case '4': return {'g', 'h', 'i'}; case '5': return {'j', 'k', 'l'}; case '6': return {'m', 'n', 'o'}; case '7': return {'p', 'q', 'r', 's'}; case '8': return {'t', 'u', 'v'}; case '9': return {'w', 'x', 'y', 'z'}; default: return {}; } } vector<string> letterCombinations(string digits) { if (digits.size() == 0) return {}; vector<char> digitVector = vector<char>(digits.begin(), digits.end()); vector<vector<char>> lettersVector = {}; for (auto digit: digitVector) { lettersVector.push_back(getLetter(digit)); } vector<vector<char>> product = cart_product(lettersVector); vector<string> ans = {}; for (auto res: product) { ans.push_back(string(res.begin(), res.end())); } return ans; } };
27.95
78
0.408468
RageBill
f881f992d4faa5d20f4649883ba1b1a4687a8a1e
1,037
cpp
C++
algorithm-challenges/baekjoon-online-judge/challenges/9000/9251.cpp
nbsp1221/algorithm
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
[ "MIT" ]
null
null
null
algorithm-challenges/baekjoon-online-judge/challenges/9000/9251.cpp
nbsp1221/algorithm
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
[ "MIT" ]
null
null
null
algorithm-challenges/baekjoon-online-judge/challenges/9000/9251.cpp
nbsp1221/algorithm
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); string small, big, temponary; cin >> small >> big; if (small.size() > big.size()) { temponary = small; small = big; big = temponary; } vector<vector<int>> lcs(big.size(), vector<int>(big.size(), 0)); lcs[0][0] = small[0] == big[0]; for (uint i = 1; i < small.size(); i++) { lcs[i][0] = lcs[i - 1][0] ? 1 : small[i] == big[0]; } for (uint i = 1; i < big.size(); i++) { lcs[0][i] = lcs[0][i - 1] ? 1 : small[0] == big[i]; } for (uint i = 1; i < small.size(); i++) { for (uint j = 1; j < big.size(); j++) { if (small[i] == big[j]) { lcs[i][j] = lcs[i - 1][j - 1] + 1; } else { lcs[i][j] = max(lcs[i][j - 1], lcs[i - 1][j]); } } } cout << lcs[small.size() - 1][big.size() - 1] << "\n"; return 0; }
22.543478
68
0.427194
nbsp1221
f8837cbfab9cd082989c2ec26848513a735149e4
1,490
hpp
C++
include/boost/mysql/detail/auth/auth_calculator.hpp
AlexAndDad/mysql-asio
a56d390a2ef4426744483dcbaeb54a65af524356
[ "BSL-1.0" ]
null
null
null
include/boost/mysql/detail/auth/auth_calculator.hpp
AlexAndDad/mysql-asio
a56d390a2ef4426744483dcbaeb54a65af524356
[ "BSL-1.0" ]
null
null
null
include/boost/mysql/detail/auth/auth_calculator.hpp
AlexAndDad/mysql-asio
a56d390a2ef4426744483dcbaeb54a65af524356
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2019-2020 Ruben Perez Hidalgo (rubenperez038 at gmail dot com) // // 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 BOOST_MYSQL_DETAIL_AUTH_AUTH_CALCULATOR_HPP #define BOOST_MYSQL_DETAIL_AUTH_AUTH_CALCULATOR_HPP #include "boost/mysql/error.hpp" #include <array> #include <string> #include <string_view> namespace boost { namespace mysql { namespace detail { struct authentication_plugin { using calculator_signature = error_code (*)( std::string_view password, std::string_view challenge, bool use_ssl, std::string& output ); std::string_view name; calculator_signature calculator; }; class auth_calculator { const authentication_plugin* plugin_ {nullptr}; std::string response_; inline static const authentication_plugin* find_plugin(std::string_view name); public: inline error_code calculate( std::string_view plugin_name, std::string_view password, std::string_view challenge, bool use_ssl ); std::string_view response() const noexcept { return response_; } std::string_view plugin_name() const noexcept { assert(plugin_); return plugin_->name; } }; } // detail } // mysql } // boost #include "boost/mysql/detail/auth/impl/auth_calculator.ipp" #endif /* INCLUDE_BOOST_MYSQL_DETAIL_AUTH_AUTH_CALCULATOR_HPP_ */
24.42623
82
0.715436
AlexAndDad
f8855eb1341381ea5f4fc52289a2b47947a7be9f
3,204
cxx
C++
Dax/LHMC/ArgumentsParser.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
9
2015-01-10T04:31:50.000Z
2019-03-04T13:55:08.000Z
Dax/LHMC/ArgumentsParser.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
2
2016-10-19T12:56:47.000Z
2017-06-02T13:55:35.000Z
Dax/LHMC/ArgumentsParser.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
5
2015-01-05T15:52:50.000Z
2018-02-14T18:08:19.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. // // Copyright 2012 Sandia Corporation. // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // //============================================================================= #include "ArgumentsParser.h" #include <dax/testing/OptionParser.h> #include <iostream> #include <sstream> #include <string> namespace mandle { //----------------------------------------------------------------------------- ArgumentsParser::ArgumentsParser(): Time(0), AutoPlay(false), Size(200) { } //----------------------------------------------------------------------------- ArgumentsParser::~ArgumentsParser() { } //----------------------------------------------------------------------------- bool ArgumentsParser::parseArguments(int argc, char* argv[]) { std::stringstream usageStream; usageStream << "USAGE: " << argv[0] << " [options]\n\nOptions:"; std::string usageStatement = usageStream.str(); enum optionIndex { UNKNOWN, HELP, TIME, AUTO, SIZE}; const dax::testing::option::Descriptor usage[] = { {UNKNOWN, 0, "" , "", dax::testing::option::Arg::None, usageStatement.c_str() }, {HELP, 0, "h", "help", dax::testing::option::Arg::None, " --help, -h \tPrint usage and exit." }, {TIME, 0, "", "time", dax::testing::option::Arg::Optional, " --time \t Time to run the test in milliseconds." }, {AUTO, 0, "", "auto-play", dax::testing::option::Arg::None, " --auto-play \t Automatically run marching cubes demo." }, {SIZE, 0, "", "size", dax::testing::option::Arg::Optional, " --size \t Size (# data points) along each dimension of starting grid." }, {0,0,0,0,0,0} }; argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present dax::testing::option::Stats stats(usage, argc, argv); dax::testing::option::Option* options = new dax::testing::option::Option[stats.options_max]; dax::testing::option::Option* buffer = new dax::testing::option::Option[stats.options_max]; dax::testing::option::Parser parse(usage, argc, argv, options, buffer); if (parse.error()) { delete[] options; delete[] buffer; return false; } if (options[HELP] || argc == 0) { dax::testing::option::printUsage(std::cout, usage); delete[] options; delete[] buffer; return false; } if ( options[TIME] ) { std::string sarg(options[TIME].last()->arg); std::stringstream argstream(sarg); argstream >> this->Time; } if ( options[AUTO] ) { this->AutoPlay = true; } if ( options[SIZE] ) { std::string sarg(options[SIZE].last()->arg); std::stringstream argstream(sarg); argstream >> this->Size; } delete[] options; delete[] buffer; return true; } } // namespace mandle
30.514286
144
0.56211
robertmaynard
f8861774b76b6ca3c19ece69a76a608e4d86a12e
1,852
cpp
C++
chromium/third_party/WebKit/Source/modules/vr/VREyeParameters.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/modules/vr/VREyeParameters.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/modules/vr/VREyeParameters.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/vr/VREyeParameters.h" namespace blink { namespace { void setDomPoint(DOMPoint* point, const WebVRVector3& vec) { point->setX(vec.x); point->setY(vec.y); point->setZ(vec.z); point->setW(1.0); } } // namespace VREyeParameters::VREyeParameters() { m_minimumFieldOfView = new VRFieldOfView(); m_maximumFieldOfView = new VRFieldOfView(); m_recommendedFieldOfView = new VRFieldOfView(); m_eyeTranslation = DOMPoint::create(0, 0, 0, 0); m_currentFieldOfView = new VRFieldOfView(); m_renderRect = DOMRect::create(0, 0, 0, 0); } void VREyeParameters::setFromWebVREyeParameters(const WebVREyeParameters &state) { // FIXME: We should expose proper min/max FOV eventually but for now set the // min/max equal to the recommended FOV to reduce need for synchronous // queries and reduce rendering complexity. m_minimumFieldOfView->setFromWebVRFieldOfView(state.recommendedFieldOfView); m_maximumFieldOfView->setFromWebVRFieldOfView(state.recommendedFieldOfView); m_recommendedFieldOfView->setFromWebVRFieldOfView(state.recommendedFieldOfView); setDomPoint(m_eyeTranslation, state.eyeTranslation); m_currentFieldOfView->setFromWebVRFieldOfView(state.recommendedFieldOfView); m_renderRect = DOMRect::create(state.renderRect.x, state.renderRect.y, state.renderRect.width, state.renderRect.height); } DEFINE_TRACE(VREyeParameters) { visitor->trace(m_minimumFieldOfView); visitor->trace(m_maximumFieldOfView); visitor->trace(m_recommendedFieldOfView); visitor->trace(m_eyeTranslation); visitor->trace(m_currentFieldOfView); visitor->trace(m_renderRect); } } // namespace blink
32.491228
124
0.757559
wedataintelligence
f886b196bebdc5e2f992f0cf120344c37ba5a990
7,678
cpp
C++
case-studies/PoDoFo/podofo/cib/podofo/base/PdfDataType.h.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
30
2018-03-05T17:35:29.000Z
2022-03-17T18:59:34.000Z
case-studies/PoDoFo/podofo/cib/podofo/base/PdfDataType.h.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
2
2016-05-26T04:47:13.000Z
2019-02-15T05:17:43.000Z
case-studies/PoDoFo/podofo/cib/podofo/base/PdfDataType.h.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
5
2019-02-15T05:09:22.000Z
2021-04-14T12:10:16.000Z
#include "podofo/base/PdfDataType.h" #include "podofo/base/PdfDefines.h" #include "podofo/base/PdfEncrypt.h" #include "podofo/base/PdfOutputDevice.h" #include "__zz_cib_CibPoDoFo-class-down-cast.h" #include "__zz_cib_CibPoDoFo-delegate-helper.h" #include "__zz_cib_CibPoDoFo-generic.h" #include "__zz_cib_CibPoDoFo-ids.h" #include "__zz_cib_CibPoDoFo-type-converters.h" #include "__zz_cib_CibPoDoFo-mtable-helper.h" #include "__zz_cib_CibPoDoFo-proxy-mgr.h" namespace __zz_cib_ { using namespace ::PoDoFo; template<> struct __zz_cib_Delegator<::PoDoFo::PdfDataType>; template <> class __zz_cib_Generic<::PoDoFo::PdfDataType> : public ::PoDoFo::PdfDataType { public: using __zz_cib_Proxy = __zz_cib_Proxy_t<::PoDoFo::PdfDataType>; using __zz_cib_ProxyDeleter = __zz_cib_ProxyDeleter_t<::PoDoFo::PdfDataType>; __zz_cib_Generic(__zz_cib_Proxy __zz_cib_proxy, const __zz_cib_MethodTable* __zz_cib_GetMethodTable) : ::PoDoFo::PdfDataType::PdfDataType() , __zz_cib_h_(__zz_cib_proxy) , __zz_cib_methodTableHelper(__zz_cib_GetMethodTable) {} void SetDirty(bool bDirty) override { auto __zz_cib_h = __zz_cib_h_; using __zz_cib_ProcType = __zz_cib_AbiType_t<void>(__zz_cib_decl *) (__zz_cib_Proxy, __zz_cib_AbiType_t<decltype(bDirty)>); __zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::SetDirty_0>( __zz_cib_h, __zz_cib_::__zz_cib_ToAbiType<decltype(bDirty)>(std::move(bDirty)) ); } void Write(::PoDoFo::PdfOutputDevice* pDevice, ::PoDoFo::EPdfWriteMode eWriteMode, const ::PoDoFo::PdfEncrypt* pEncrypt) const override { auto __zz_cib_h = __zz_cib_h_; using __zz_cib_ProcType = __zz_cib_AbiType_t<void>(__zz_cib_decl *) (const __zz_cib_Proxy, __zz_cib_AbiType_t<decltype(pDevice)>, __zz_cib_AbiType_t<decltype(eWriteMode)>, __zz_cib_AbiType_t<decltype(pEncrypt)>); __zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::Write_1>( __zz_cib_h, __zz_cib_::__zz_cib_ToAbiType<decltype(pDevice)>(std::move(pDevice)), __zz_cib_::__zz_cib_ToAbiType<decltype(eWriteMode)>(std::move(eWriteMode)), __zz_cib_::__zz_cib_ToAbiType<decltype(pEncrypt)>(std::move(pEncrypt)) ); } bool IsDirty() const override { auto __zz_cib_h = __zz_cib_h_; using __zz_cib_ProcType = __zz_cib_AbiType_t<bool>(__zz_cib_decl *) (const __zz_cib_Proxy); return __zz_cib_FromAbiType<bool>( __zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::IsDirty_2>( __zz_cib_h ) ); } ~__zz_cib_Generic() override { if (!__zz_cib_h_) return; auto __zz_cib_h = __zz_cib_h_; using __zz_cib_ProcType = void(__zz_cib_decl *) (__zz_cib_Proxy); __zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::__zz_cib_Delete_3>( __zz_cib_h ); } void __zz_cib_ReleaseProxy() { __zz_cib_h_ = nullptr; } __ZZ_CIB_DELEGATOR_MEMBERS(__zz_cib_Generic, ::PoDoFo::PdfDataType) private: __zz_cib_Proxy __zz_cib_h_; const __zz_cib_MethodTableHelper __zz_cib_methodTableHelper; const __zz_cib_MethodTableHelper& __zz_cib_GetMethodTableHelper() const { return __zz_cib_methodTableHelper; } friend struct __zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>; using __zz_cib_MethodId = __zz_cib_::__zz_cib_ids::__zz_cib_Class333::__zz_cib_Class346::__zz_cib_Generic::__zz_cib_MethodId; }; } namespace __zz_cib_ { using namespace ::PoDoFo; template <> struct __zz_cib_Delegator<::PoDoFo::PdfDataType> : public ::PoDoFo::PdfDataType { using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Generic<::PoDoFo::PdfDataType>; using __zz_cib_AbiType = __zz_cib_Delegatee*; using __zz_cib_Proxy = __zz_cib_Proxy_t<::PoDoFo::PdfDataType>; using __zz_cib_ProxyDeleter = __zz_cib_ProxyDeleter_t<::PoDoFo::PdfDataType>; using ::PoDoFo::PdfDataType::PdfDataType; static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_0(__zz_cib_Proxy __zz_cib_proxy, const __zz_cib_MethodTable* __zz_cib_GetMethodTable) { return new __zz_cib_::__zz_cib_Generic<::PoDoFo::PdfDataType>(__zz_cib_proxy, __zz_cib_GetMethodTable); } static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) { delete __zz_cib_obj; } static __zz_cib_AbiType_t<void> __zz_cib_decl Write_2(const __zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfOutputDevice*> pDevice, __zz_cib_AbiType_t<::PoDoFo::EPdfWriteMode> eWriteMode, __zz_cib_AbiType_t<const ::PoDoFo::PdfEncrypt*> pEncrypt) { __zz_cib_obj->Write( __zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfOutputDevice*>(pDevice), __zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfWriteMode>(eWriteMode), __zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfEncrypt*>(pEncrypt) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl IsDirty_3(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::PoDoFo::PdfDataType::IsDirty() ); } static __zz_cib_AbiType_t<void> __zz_cib_decl SetDirty_4(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> bDirty) { __zz_cib_obj->::PoDoFo::PdfDataType::SetDirty( __zz_cib_::__zz_cib_FromAbiType<bool>(bDirty) ); } static __zz_cib_AbiType_t<void> __zz_cib_decl SetImmutable_5(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> bImmutable) { __zz_cib_obj->::PoDoFo::PdfDataType::SetImmutable( __zz_cib_::__zz_cib_FromAbiType<bool>(bImmutable) ); } static __zz_cib_AbiType_t<bool> __zz_cib_decl GetImmutable_6(const __zz_cib_Delegatee* __zz_cib_obj) { return __zz_cib_ToAbiType<bool>( __zz_cib_obj->::PoDoFo::PdfDataType::GetImmutable() ); } static __zz_cib_AbiType_t<void> __zz_cib_decl AssertMutable_7(const __zz_cib_Delegatee* __zz_cib_obj) { __zz_cib_obj->::PoDoFo::PdfDataType::AssertMutable(); } static void __zz_cib_decl __zz_cib_RegisterProxy(::PoDoFo::PdfDataType* obj, __zz_cib_Proxy proxy, __zz_cib_ProxyDeleter deleter) { __zz_cib_ProxyManagerDelegator::__zz_cib_RegisterProxy(obj, proxy, deleter); } static void __zz_cib_decl __zz_cib_ReleaseProxy(__zz_cib_Delegatee* __zz_cib_obj) { __zz_cib_obj->__zz_cib_ReleaseProxy(); } }; } namespace __zz_cib_ { namespace __zz_cib_Class333 { using namespace ::PoDoFo; namespace __zz_cib_Class346 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable() { static const __zz_cib_MTableEntry methodArray[] = { reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_New_0), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_Delete_1), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::Write_2), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::IsDirty_3), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::SetDirty_4), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::SetImmutable_5), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::GetImmutable_6), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::AssertMutable_7), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_ReleaseProxy), reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_RegisterProxy) }; static const __zz_cib_MethodTable methodTable = { methodArray, 10 }; return &methodTable; } }}}
49.535484
267
0.784189
satya-das
f887ca22daabb759148bfa85756f2ceb98904ee7
14,837
cpp
C++
Libs/GL.CallBacks.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
Libs/GL.CallBacks.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
Libs/GL.CallBacks.cpp
thiagofigcosta/The.COM-Game
653b7174767b6dc2351807a44c2c4ac67c7dc1d6
[ "MIT" ]
null
null
null
#include "GL.Callbacks.h" bool glCallbacksReleaseMouseOffSet=false;//evita de definir o mouse solto no meio ou final da funcao update e o programa nao fazer a leitura bool glCallbacksReleaseMouseROffSet=false;//evita de definir o mouse solto no meio ou final da funcao update e o programa nao fazer a leitura bool glCallbacksReleaseZOffSet=false; void drawScene(void){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); GL::framesInGame++; if(GL::framesInGame>=100000000000) GL::framesInGame=0; if(Scenes::current==Scenes::game) Scenes::drawGame(); else if(Scenes::current==Scenes::mapEdit) Scenes::drawMapEdit(); else if(Scenes::current==Scenes::menu) Scenes::drawMenu(); else if(Scenes::current==Scenes::credits) Scenes::drawCredits(); else if(Scenes::current==Scenes::splash) Scenes::drawSplash(); else if(Scenes::current==Scenes::options) Scenes::drawOptions(); else if(Scenes::current==Scenes::preGame) Scenes::drawPreGame(); else if(Scenes::current==Scenes::preCampaign) Scenes::drawPreCampaign(); else if(Scenes::current==Scenes::preFreeMode) Scenes::drawPreFreeMode(); else if(Scenes::current==Scenes::posGame) Scenes::drawPosGame(); else if(Scenes::current==Scenes::posGameEnd) Scenes::drawEndGame(); else if(Scenes::current==Scenes::posYouWin) Scenes::drawYouWin(); glutSwapBuffers(); } void reshape(int width, int height){ // float windowAspectRatio,worldAspectRatio,xViewport,yViewport; // int WindowWidth,WindowHeight; // realHeight=height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(Scenes::camera.x.movedCam, GL::defaultSize.x+Scenes::camera.x.movedCam,GL::defaultSize.y+Scenes::camera.y.movedCam, Scenes::camera.y.movedCam, -1, 1); // windowAspectRatio = ((float)width)/height; // worldAspectRatio = ((float) GL::defaultSize.x)/ GL::defaultSize.y; // xViewport=0;yViewport=0; // if (windowAspectRatio < worldAspectRatio) { // cout<<"menor\n"; // xViewport = width / worldAspectRatio; // yViewport = (height - xViewport)/2; glViewport(0, 0, width, height); GL::currentSize.x=width; GL::currentSize.y=height; // }else if (windowAspectRatio > worldAspectRatio) { // yViewport = ((float)height) * worldAspectRatio; // xViewport = (width - yViewport)/2; // glViewport(xViewport, 0, yViewport, height); // GL::currentSize.x=height-xViewport; // GL::currentSize.y=yViewport; // } else { // glViewport(0, 0, width, height); // GL::currentSize.x=width; // GL::currentSize.y=height; // } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int GLSpecReleaseKey=0; void specialKeyboard(int key, int x, int y){ switch(key) { case GLUT_KEY_UP: if(Scenes::current==Scenes::game&&!GL::isPaused){ Tutorials::pressedKey=GLUT_KEY_UP; player->atackDirection=Util::up;//NAO PULA!!! if(Scenes::freeCam) Scenes::camera.y.movingCam=-1; }else if(Scenes::current==Scenes::mapEdit) Scenes::camera.y.movingCam=-1; break; case GLUT_KEY_DOWN: if(Scenes::current==Scenes::game&&!GL::isPaused){ Tutorials::pressedKey=GLUT_KEY_UP; player->atackDirection=Util::down; player->canTp=true; if(Scenes::freeCam) Scenes::camera.y.movingCam=1; } else if(Scenes::current==Scenes::mapEdit) Scenes::camera.y.movingCam=1; break; case GLUT_KEY_LEFT: if(Scenes::current==Scenes::game&&!GL::isPaused){ if(GLSpecReleaseKey==-1) GLSpecReleaseKey=0; Tutorials::pressedKey=GLUT_KEY_UP; player->orientation=-1; player->atackDirection=Util::left; if(glutGetModifiers()==GLUT_ACTIVE_SHIFT){ if(player->canWalk&&!player->atacking)player->run(Util::left); }else{ if(player->canWalk&&!player->atacking)player->walk(Util::left); } if(Scenes::freeCam) Scenes::camera.x.movingCam=-1; }else if(Scenes::current==Scenes::mapEdit) Scenes::camera.x.movingCam=-1; break; case GLUT_KEY_RIGHT: if(Scenes::current==Scenes::game&&!GL::isPaused){ if(GLSpecReleaseKey==1) GLSpecReleaseKey=0; Tutorials::pressedKey=GLUT_KEY_UP; player->orientation=1; player->atackDirection=Util::right; if(glutGetModifiers()==GLUT_ACTIVE_SHIFT){ if(player->canWalk&&!player->atacking)player->run(Util::right); }else{ if(player->canWalk&&!player->atacking)player->walk(Util::right); } if(Scenes::freeCam) Scenes::camera.x.movingCam=1; }else if(Scenes::current==Scenes::mapEdit) Scenes::camera.x.movingCam=1; break; } } void keyboard(unsigned char key, int x, int y){ switch(key){ case ' ': if(!GL::isPaused&&Scenes::current==Scenes::game){ if(!Tutorials::isPaused)player->jump(); player->spacePressed=true; Tutorials::pressedKey=' '; } if(Scenes::current==Scenes::splash) Scenes::skipScene=true; break; case 'Z': case 'z': if(!GL::isPaused){ glCallbacksReleaseZOffSet=false; Tutorials::pressedKey='z'; player->atacking=Player::melee; } break; case 'X': case 'x': if(!GL::isPaused){ Tutorials::pressedKey='x'; player->atacking=Player::ranged; } break; case 27: if(!GL::isPaused){ Tutorials::pressedKey=27; } if(Scenes::current==Scenes::game) GL::isPaused=!GL::isPaused; break; default:break; } if(key>0) if(Scenes::current==Scenes::splash) Scenes::skipScene=true; } void specialKeyboardUp(int key,int x,int y){ switch(key) { case GLUT_KEY_UP: if(Scenes::current==Scenes::game){ if(player->orientation>0) player->atackDirection=Util::right; else player->atackDirection=Util::left; } Scenes::camera.y.movingCam=0; break; case GLUT_KEY_DOWN: if(Scenes::current==Scenes::game){ player->canTp=false; if(player->orientation>0) player->atackDirection=Util::right; else player->atackDirection=Util::left; } Scenes::camera.y.movingCam=0; break; case GLUT_KEY_LEFT: if(Scenes::current==Scenes::game){ if(player->orientation>0) player->atackDirection=Util::right; else player->atackDirection=Util::left; GLSpecReleaseKey=-1; } Scenes::camera.x.movingCam=0; break; case GLUT_KEY_RIGHT: if(Scenes::current==Scenes::game){ if(player->orientation>0) player->atackDirection=Util::right; else player->atackDirection=Util::left; GLSpecReleaseKey=1; } Scenes::camera.x.movingCam=0; break; default: break; } } void keyboardUp(unsigned char key,int x,int y){ switch(key){ case ' ': if(!GL::isPaused&&Scenes::current==Scenes::game){ player->spacePressed=false; } break; case 'z': case 'Z': glCallbacksReleaseZOffSet=true; break; case '0': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '1': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '2': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '3': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '4': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '5': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '6': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '7': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '8': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case '9': if(Scenes::current==Scenes::mapEdit) mapEdit::input+=key; break; case 'D': case 'd': if(Scenes::current==Scenes::mapEdit) mapEdit::isUser=!mapEdit::isUser; break; case 'U': case 'u': if(Scenes::current==Scenes::mapEdit&&mapEdit::size.y==0) mapEdit::load(-1); break; case 'C': case 'c': if(!GL::isPaused&&Scenes::current==Scenes::game){ player->god=!player->god; if(player->god){ al->stopSound(AL::getSoundByName("cafeSong")); player->superMan=false; } } break; case 13://enter if(Scenes::current==Scenes::mapEdit&&mapEdit::input!=""){ float tmp; istringstream (mapEdit::input) >> tmp; mapEdit::input=""; if(mapEdit::isCreating==1){ if(tmp>=19&&tmp<65000&&(mapEdit::size.y==0||mapEdit::size.x==0)){ if(mapEdit::size.y==0){ mapEdit::size.y=tmp; }else{ mapEdit::size.x=tmp; mapEdit::setMapSize(); } } }else if(mapEdit::isCreating==-1){ if(tmp>=0&&tmp<maps.size()&&(mapEdit::size.y==0||mapEdit::size.x==0)){ mapEdit::load(tmp); } } } break; case 8://backSpace if(Scenes::current==Scenes::mapEdit) if(mapEdit::input.size()) mapEdit::input.erase(mapEdit::input.begin()+mapEdit::input.size()-1); break; } } void update(int n){ if(GLSpecReleaseKey!=0){ vector <mapCollision> var; bool condition=false; Blocks* bl; int type; nTPoint point; point.y=player->pos.y+1; point.x=player->pos.x; var=Map::checkCollision(point,player->size); for(int i=0; i<var.size(); i++){ if(var[i].collision.firstObj==1){ if(var[i].blockRef<=Map::staticBlocks.size()){ bl=(Blocks*)Map::staticBlocks[var[i].blockRef]; type=bl->type; if(type==17){ condition=true; } }else if(var[i].blockRef-Map::staticBlocks.size()<Map::dynamicBlocks.size()){ bl=(Blocks*)Map::dynamicBlocks[var[i].blockRef-Map::staticBlocks.size()]; type=bl->type; if(type==204||type==254){ condition=true; if(player->hSpeed!=0) al->playSoundByName("ice"); } } } } if(condition) player->reducing=true; else player->hSpeed=0; } GL::mousePos.x=GL::rawMousePos.x*(float)GL::defaultSize.x/(float)GL::currentSize.x+Scenes::camera.x.movedCam; GL::mousePos.y=GL::rawMousePos.y*(float)GL::defaultSize.y/(float)GL::currentSize.y+Scenes::camera.y.movedCam; if(glCallbacksReleaseZOffSet){ glCallbacksReleaseZOffSet=false; if(!GL::isPaused){ Tutorials::pressedKey='z'; player->atacking=Player::meleeProjectile; }} if(glCallbacksReleaseMouseOffSet){ GL::leftMouseReleased=false; glCallbacksReleaseMouseOffSet=false; } if(GL::leftMouseReleased)glCallbacksReleaseMouseOffSet=true; if(glCallbacksReleaseMouseROffSet){ GL::rightMouseReleased=false; glCallbacksReleaseMouseROffSet=false; } if(GL::rightMouseReleased)glCallbacksReleaseMouseROffSet=true; glutPostRedisplay(); glutTimerFunc(GL::getMs(), update, 0); } void mousePress(int button,int state,int x,int y){ if(button==GLUT_LEFT_BUTTON){ if(state==GLUT_DOWN){ GL::leftMouseClicked=true; GL::leftMouseReleased=false; } if(state==GLUT_UP){ GL::leftMouseClicked=false; GL::leftMouseReleased=true; } } if(button==GLUT_RIGHT_BUTTON){ if(state==GLUT_DOWN){ GL::rightMouseClicked=true; GL::rightMouseReleased=false; } if(state==GLUT_UP){ GL::rightMouseClicked=false; GL::rightMouseReleased=true; } } if(button==GLUT_MIDDLE_BUTTON){ if(state==GLUT_DOWN){ } if(state==GLUT_UP){ if(Scenes::current==Scenes::mapEdit) mapEdit::currentBlock=60000; } } } void mousePassiveMotion(int x,int y){ // GLdouble model[16]; // GLdouble proj[16]; // GLint view[4]; // glGetDoublev(GL_MODELVIEW_MATRIX, model); // glGetDoublev(GL_PROJECTION_MATRIX, proj); // glGetIntegerv(GL_VIEWPORT, view); // double tX=0,tY=0,tZ=0; // int newY=view[3]-view[1]-y-view[1]; // gluProject((double)x, (double)newY, 0 , model, (const GLdouble*)proj, view, &tX,&tY,&tZ); // GL::mousePos.setPoint(tX+Scenes::camera.x.movedCam,tY+Scenes::camera.y.movedCam,tZ); GL::rawMousePos.setPoint(x,y,0); } void mouseActiveMotion(int x,int y){ GL::rawMousePos.setPoint(x,y,0); } void mouseWheel(int button, int dir, int x, int y){ if (dir > 0){ // Zoom in if(Scenes::current=Scenes::mapEdit){ if(mapEdit::scale.x<0.99){ mapEdit::scale.x+=0.01; mapEdit::scale.y+=0.01; } } }else{ // Zoom out if(Scenes::current=Scenes::mapEdit){ if(mapEdit::scale.x>0.01){ mapEdit::scale.x-=0.01; mapEdit::scale.y-=0.01; } } } }
32.537281
162
0.539193
thiagofigcosta
f8890a3a056ff61efd82778c8997d1b70f77e01f
2,267
cpp
C++
PolyEngine/UnitTests/Src/AllocatorTests.cpp
MuniuDev/PolyEngine
9389537e4f551fa5dd621ebd3704e55b04c98792
[ "MIT" ]
1
2017-04-30T13:55:54.000Z
2017-04-30T13:55:54.000Z
PolyEngine/UnitTests/Src/AllocatorTests.cpp
MuniuDev/PolyEngine
9389537e4f551fa5dd621ebd3704e55b04c98792
[ "MIT" ]
null
null
null
PolyEngine/UnitTests/Src/AllocatorTests.cpp
MuniuDev/PolyEngine
9389537e4f551fa5dd621ebd3704e55b04c98792
[ "MIT" ]
3
2017-11-22T16:37:26.000Z
2019-04-24T17:47:58.000Z
#include <catch.hpp> #include <PoolAllocator.hpp> #include <IterablePoolAllocator.hpp> using namespace Poly; TEST_CASE("Pool allocator", "[Allocator]") { PoolAllocator<size_t> allocator(10); REQUIRE(allocator.GetSize() == 0); size_t* a = allocator.Alloc(); REQUIRE(a != nullptr); REQUIRE(allocator.GetSize() == 1); size_t* b = allocator.Alloc(); REQUIRE(b != nullptr); REQUIRE((a + 1) == b); REQUIRE(allocator.GetSize() == 2); size_t* c = allocator.Alloc(); REQUIRE(c != nullptr); REQUIRE((a + 2) == c); REQUIRE((b + 1) == c); REQUIRE(allocator.GetSize() == 3); allocator.Free(b); REQUIRE(allocator.GetSize() == 2); size_t* d = allocator.Alloc(); REQUIRE(d == b); REQUIRE(allocator.GetSize() == 3); } TEST_CASE("Iterable pool allocator", "[Allocator]") { // test allocation IterablePoolAllocator<size_t> allocator(10); REQUIRE(allocator.GetSize() == 0); size_t* a = allocator.Alloc(); REQUIRE(a != nullptr); REQUIRE(allocator.GetSize() == 1); size_t* b = allocator.Alloc(); REQUIRE(b != nullptr); REQUIRE(allocator.GetSize() == 2); size_t* c = allocator.Alloc(); REQUIRE(c != nullptr); REQUIRE(allocator.GetSize() == 3); allocator.Free(b); REQUIRE(allocator.GetSize() == 2); size_t* b_2 = allocator.Alloc(); REQUIRE(b_2 == b); REQUIRE(allocator.GetSize() == 3); // test iterators *a = 1; *b_2 = 2; *c = 3; size_t i = 0; for (size_t val : allocator) REQUIRE(val == ++i); IterablePoolAllocator<size_t> empty_allocator(10); REQUIRE(empty_allocator.Begin() == empty_allocator.End()); } TEST_CASE("Iterable pool allocator corner case test", "[Allocator]") { // test allocation IterablePoolAllocator<size_t> allocator(3); size_t* a = allocator.Alloc(); REQUIRE(a != nullptr); REQUIRE(allocator.GetSize() == 1); size_t* b = allocator.Alloc(); REQUIRE(b != nullptr); REQUIRE(allocator.GetSize() == 2); allocator.Free(a); REQUIRE(allocator.GetSize() == 1); size_t* c = allocator.Alloc(); REQUIRE(c != nullptr); REQUIRE(allocator.GetSize() == 2); size_t* d = allocator.Alloc(); REQUIRE(d != nullptr); REQUIRE(allocator.GetSize() == 3); allocator.Free(d); REQUIRE(allocator.GetSize() == 2); size_t* e = allocator.Alloc(); REQUIRE(e != nullptr); REQUIRE(allocator.GetSize() == 3); }
22.445545
70
0.659462
MuniuDev
f889a8743f81ad633163e794d37ae91c293f278d
1,134
cpp
C++
c++/remove_duplicates_from_sorted_list.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/remove_duplicates_from_sorted_list.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/remove_duplicates_from_sorted_list.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. */ /* * note how to free memory */ #include "helper.h" /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { ListNode *p = head; while (p && p->next) { if (p->val == p->next->val) { ListNode *tmp = p->next; p->next = p->next->next; delete tmp; // delete only works if the list node is allocated by new } else { p = p->next; } } return head; } }; int main() { Solution s; vector<int> v1({1, 1, 1}); ListNode *headA = buildList(v1); s.deleteDuplicates(headA); printList(headA); vector<int> v2({1, 1, 2, 3, 3}); ListNode *headB = buildList(v2); s.deleteDuplicates(headB); printList(headB); return 0; }
21
90
0.534392
SongZhao
f88af9fc4d172ba3f31ffd822945287a72660d72
4,943
hpp
C++
src/serial/serializer_basic.hpp
yxtj/FAB
f483672e13ea96a3f1da450c9655b1fc239233b1
[ "MIT" ]
null
null
null
src/serial/serializer_basic.hpp
yxtj/FAB
f483672e13ea96a3f1da450c9655b1fc239233b1
[ "MIT" ]
1
2019-01-28T21:39:07.000Z
2019-01-28T21:39:07.000Z
src/serial/serializer_basic.hpp
haku117/FAB
80957e7627f48c1934cb051ae79f267611482112
[ "MIT" ]
null
null
null
#pragma once #include <utility> #include <type_traits> #include <cstdint> #include <cstring> #include "../type_traits/is_container.h" #include "../type_traits/is_pair.h" #include "../type_traits/type_traits_dummy.h" template <class T, class Enable = void> struct _Serializer { int estimateSize(const T& item) { static_assert(impl::type_traits::template_false_type<T>::value, "serialization of this type is not provided."); return 0; } char* serial(char* res, int bufSize, const T& item) { static_assert(impl::type_traits::template_false_type<T>::value, "serialization of this type is not provided."); return nullptr; } char* serial(char* res, const T& item) { static_assert(impl::type_traits::template_false_type<T>::value, "serialization of this type is not provided."); return nullptr; } std::pair<T, const char*> deserial(const char* p) { static_assert(impl::type_traits::template_false_type<T>::value, "deserialization of this type is not provided."); return std::make_pair(T(), nullptr); } }; // POD template <class T> struct _Serializer<T, typename std::enable_if<std::is_pod<T>::value>::type> { static constexpr uint32_t size = sizeof(T); int estimateSize(const T& item) { return size; } char* serial(char* res, int bufSize, const T& item) { if(size > bufSize) return nullptr; return serial(res, item); } char* serial(char* res, const T& item) { char* p = reinterpret_cast<char*>(res); std::memcpy(p, reinterpret_cast<const char*>(&item), size); return p + size; } std::pair<T, const char*> deserial(const char* p) { T item = *reinterpret_cast<const T*>(p); return std::make_pair(std::move(item), p + size); } }; // string: template <> struct _Serializer<std::string> { int estimateSize(const std::string& item) { return static_cast<int>(sizeof(uint32_t) + item.size()); } char* serial(char* res, int bufSize, const std::string& item) { if(estimateSize(item) > bufSize) return nullptr; return serial(res, item); } char* serial(char* res, const std::string& item) { uint32_t size = static_cast<uint32_t>(item.size()); *reinterpret_cast<uint32_t*>(res) = size; std::memcpy(res + sizeof(uint32_t), item.data(), item.size()); return res + sizeof(uint32_t) + item.size(); } std::pair<std::string, const char*> deserial(const char* p) { uint32_t size = *reinterpret_cast<const uint32_t*>(p); std::string str(size, 0); std::memcpy(const_cast<char*>(str.data()), p + sizeof(uint32_t), size); return std::make_pair(std::move(str), p + sizeof(uint32_t) + size); } }; // pair: template <class T> struct _Serializer<T, typename std::enable_if<is_pair<T>::value>::type> { typedef typename T::first_type T1; typedef typename T::second_type T2; _Serializer<typename std::remove_cv<T1>::type> s1; _Serializer<typename std::remove_cv<T2>::type> s2; int estimateSize(const T& item) { return s1.estimateSize(item.first) + s2.estimateSize(item.second); } char* serial(char* res, int bufSize, const T& item) { if(estimateSize(item) > bufSize) return nullptr; return serial(res, item); } char* serial(char* res, const T& item) { res = s1.serial(res, item.first); res = s2.serial(res, item.second); return res; } std::pair<T, const char*> deserial(const char* p) { auto t1 = s1.deserial(p); auto t2 = s2.deserial(t1.second); return std::make_pair(std::make_pair(std::move(t1.first), std::move(t2.first)), t2.second); } }; // containter: template <class T> struct _Serializer<T, typename std::enable_if<is_container<T>::value>::type> { typedef typename T::const_iterator const_iterator; typedef typename std::remove_cv<typename T::value_type>::type value_type; _Serializer<value_type> sv; int estimateSize(const T& item) { int c = sizeof(uint32_t); if(std::is_pod<value_type>::value) { c += static_cast<int>(item.size() * sizeof(value_type)); } else { for(auto& v : item) c += sv.estimateSize(v); } return c; } char* serial(char* res, int bufSize, const T& item) { static_assert(impl::type_traits::template_false_type<T>::value, "Please use iterator version for container"); return nullptr; } char* serial(char* res, const T& item) { //static_assert(impl::type_traits::template_false_type<T>::value, // "Please use iterator version for container"); uint32_t* numObj = reinterpret_cast<uint32_t*>(res); res += sizeof(uint32_t); uint32_t count = 0; auto last = item.end(); for(auto first=item.begin(); first != last; ++first) { char* p = sv.serial(res, *first); res = p; ++count; } *numObj = count; return res; } std::pair<T, const char*> deserial(const char* p) { uint32_t n = *reinterpret_cast<const uint32_t*>(p); p += sizeof(uint32_t); T res; while(n--) { auto mp = sv.deserial(p); //auto mp = deserialize<value_type>(p); res.insert(res.end(), std::move(mp.first)); p = mp.second; } return std::make_pair(std::move(res), p); } };
31.28481
93
0.682784
yxtj
f88e19a2599b4d3b6e63bb590eb7da1478dcf03b
480
cpp
C++
DP/746. Min Cost Climbing Stairs.cpp
sumiya-NJU/LeetCode-
8e6065e160da3db423a51aaf3ae53b2023068d05
[ "MIT" ]
2
2019-10-28T06:40:09.000Z
2022-03-09T10:50:06.000Z
DP/746. Min Cost Climbing Stairs.cpp
sumiya-NJU/LeetCode
8e6065e160da3db423a51aaf3ae53b2023068d05
[ "MIT" ]
null
null
null
DP/746. Min Cost Climbing Stairs.cpp
sumiya-NJU/LeetCode
8e6065e160da3db423a51aaf3ae53b2023068d05
[ "MIT" ]
1
2018-12-09T13:46:06.000Z
2018-12-09T13:46:06.000Z
// author: ypz // 数组dp表示落地到第i位的最低代价,注意返回值取落地到第n位和第n-1位中代价的较小者。 class Solution { public: int minCostClimbingStairs(vector<int>& cost) { if(cost.size() == 0) return 0; if(cost.size() == 1) return cost[0]; vector<int> dp(cost.size(), 0); dp[0] = cost[0]; dp[1] = cost[1]; for(int i = 2; i < cost.size(); i++) dp[i] = min(dp[i-1], dp[i-2]) + cost[i]; return min(dp[cost.size()-1], dp[cost.size()-2]); } };
28.235294
57
0.520833
sumiya-NJU
f8901f6e1876b927d707f7faa558179dfdfb3f08
9,194
cpp
C++
examples/ex28.cpp
ajithvallabai/mfem
5920fbf645f328c29a9d6489f2474d989f808451
[ "BSD-3-Clause" ]
969
2015-07-10T02:28:17.000Z
2022-03-31T17:28:02.000Z
examples/ex28.cpp
ajithvallabai/mfem
5920fbf645f328c29a9d6489f2474d989f808451
[ "BSD-3-Clause" ]
2,604
2015-07-14T08:22:22.000Z
2022-03-31T23:51:41.000Z
examples/ex28.cpp
ajithvallabai/mfem
5920fbf645f328c29a9d6489f2474d989f808451
[ "BSD-3-Clause" ]
407
2015-08-26T14:14:22.000Z
2022-03-31T03:32:16.000Z
// MFEM Example 28 // // Compile with: make ex28 // // Sample runs: ex28 // ex28 --visit-datafiles // ex28 --order 2 // // Description: Demonstrates a sliding boundary condition in an elasticity // problem. A trapezoid, roughly as pictured below, is pushed // from the right into a rigid notch. Normal displacement is // restricted, but tangential movement is allowed, so the // trapezoid compresses into the notch. // // /-------+ // normal constrained --->/ | <--- boundary force (2) // boundary (4) /---------+ // ^ // | // normal constrained boundary (1) // // This example demonstrates the use of the ConstrainedSolver // framework. // // We recommend viewing Example 2 before viewing this example. #include "mfem.hpp" #include <fstream> #include <iostream> #include <set> using namespace std; using namespace mfem; // Return a mesh with a single element with vertices (0, 0), (1, 0), (1, 1), // (offset, 1) to demonstrate boundary conditions on a surface that is not // axis-aligned. Mesh * build_trapezoid_mesh(double offset) { MFEM_VERIFY(offset < 0.9, "offset is too large!"); const int dimension = 2; const int nvt = 4; // vertices const int nbe = 4; // num boundary elements Mesh * mesh = new Mesh(dimension, nvt, 1, nbe); // vertices double vc[dimension]; vc[0] = 0.0; vc[1] = 0.0; mesh->AddVertex(vc); vc[0] = 1.0; vc[1] = 0.0; mesh->AddVertex(vc); vc[0] = offset; vc[1] = 1.0; mesh->AddVertex(vc); vc[0] = 1.0; vc[1] = 1.0; mesh->AddVertex(vc); // element Array<int> vert(4); vert[0] = 0; vert[1] = 1; vert[2] = 3; vert[3] = 2; mesh->AddQuad(vert, 1); // boundary Array<int> sv(2); sv[0] = 0; sv[1] = 1; mesh->AddBdrSegment(sv, 1); sv[0] = 1; sv[1] = 3; mesh->AddBdrSegment(sv, 2); sv[0] = 2; sv[1] = 3; mesh->AddBdrSegment(sv, 3); sv[0] = 0; sv[1] = 2; mesh->AddBdrSegment(sv, 4); mesh->FinalizeQuadMesh(1, 0, true); return mesh; } int main(int argc, char *argv[]) { // 1. Parse command-line options. int order = 1; bool visualization = 1; double offset = 0.3; bool visit = false; OptionsParser args(argc, argv); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree)."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.AddOption(&offset, "--offset", "--offset", "How much to offset the trapezoid."); args.AddOption(&visit, "-visit", "--visit-datafiles", "-no-visit", "--no-visit-datafiles", "Save data files for VisIt (visit.llnl.gov) visualization."); args.Parse(); if (!args.Good()) { args.PrintUsage(cout); return 1; } args.PrintOptions(cout); // 2. Build a trapezoidal mesh with a single quadrilateral element, where // 'offset' determines how far off it is from a rectangle. Mesh *mesh = build_trapezoid_mesh(offset); int dim = mesh->Dimension(); // 3. Refine the mesh to increase the resolution. In this example we do // 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the // largest number that gives a final mesh with no more than 1,000 // elements. { int ref_levels = (int)floor(log(1000./mesh->GetNE())/log(2.)/dim); for (int l = 0; l < ref_levels; l++) { mesh->UniformRefinement(); } } // 4. Define a finite element space on the mesh. Here we use vector finite // elements, i.e. dim copies of a scalar finite element space. The vector // dimension is specified by the last argument of the FiniteElementSpace // constructor. FiniteElementCollection *fec = new H1_FECollection(order, dim); FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec, dim); cout << "Number of finite element unknowns: " << fespace->GetTrueVSize() << endl; cout << "Assembling matrix and r.h.s... " << flush; // 5. Determine the list of true (i.e. parallel conforming) essential // boundary dofs. In this example, there are no essential boundary // conditions in the usual sense, but we leave the machinery here for // users to modify if they wish. Array<int> ess_tdof_list, ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 0; fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list); // 6. Set up the linear form b(.) which corresponds to the right-hand side of // the FEM linear system. In this case, b_i equals the boundary integral // of f*phi_i where f represents a "push" force on the right side of the // trapezoid. VectorArrayCoefficient f(dim); for (int i = 0; i < dim-1; i++) { f.Set(i, new ConstantCoefficient(0.0)); } { Vector push_force(mesh->bdr_attributes.Max()); push_force = 0.0; push_force(1) = -5.0e-2; // index 1 attribute 2 f.Set(0, new PWConstCoefficient(push_force)); } LinearForm *b = new LinearForm(fespace); b->AddBoundaryIntegrator(new VectorBoundaryLFIntegrator(f)); b->Assemble(); // 7. Define the solution vector x as a finite element grid function // corresponding to fespace. GridFunction x(fespace); x = 0.0; // 8. Set up the bilinear form a(.,.) on the finite element space // corresponding to the linear elasticity integrator with piece-wise // constants coefficient lambda and mu. We use constant coefficients, // but see ex2 for how to set up piecewise constant coefficients based // on attribute. Vector lambda(mesh->attributes.Max()); lambda = 1.0; PWConstCoefficient lambda_func(lambda); Vector mu(mesh->attributes.Max()); mu = 1.0; PWConstCoefficient mu_func(mu); BilinearForm *a = new BilinearForm(fespace); a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func, mu_func)); // 9. Assemble the bilinear form and the corresponding linear system, // applying any necessary transformations such as: eliminating boundary // conditions, applying conforming constraints for non-conforming AMR, // static condensation, etc. a->Assemble(); SparseMatrix A; Vector B, X; a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B); cout << "done." << endl; cout << "Size of linear system: " << A.Height() << endl; // 10. Set up constraint matrix to constrain normal displacement (but // allow tangential displacement) on specified boundaries. Array<int> constraint_atts(2); constraint_atts[0] = 1; // attribute 1 bottom constraint_atts[1] = 4; // attribute 4 left side Array<int> lagrange_rowstarts; SparseMatrix* local_constraints = BuildNormalConstraints(*fespace, constraint_atts, lagrange_rowstarts); // 11. Define and apply an iterative solver for the constrained system // in saddle-point form with a Gauss-Seidel smoother for the // displacement block. GSSmoother M(A); SchurConstrainedSolver * solver = new SchurConstrainedSolver(A, *local_constraints, M); solver->SetRelTol(1e-5); solver->SetMaxIter(2000); solver->SetPrintLevel(1); solver->Mult(B, X); // 12. Recover the solution as a finite element grid function. Move the // mesh to reflect the displacement of the elastic body being // simulated, for purposes of output. a->RecoverFEMSolution(X, *b, x); mesh->SetNodalFESpace(fespace); GridFunction *nodes = mesh->GetNodes(); *nodes += x; // 13. Save the refined mesh and the solution in VisIt format. if (visit) { VisItDataCollection visit_dc("ex28", mesh); visit_dc.SetLevelsOfDetail(4); visit_dc.RegisterField("displacement", &x); visit_dc.Save(); } // 14. Save the displaced mesh and the inverted solution (which gives the // backward displacements to the original grid). This output can be // viewed later using GLVis: "glvis -m displaced.mesh -g sol.gf". { x *= -1; // sign convention for GLVis displacements ofstream mesh_ofs("displaced.mesh"); mesh_ofs.precision(8); mesh->Print(mesh_ofs); ofstream sol_ofs("sol.gf"); sol_ofs.precision(8); x.Save(sol_ofs); } // 15. Send the above data by socket to a GLVis server. Use the "n" and "b" // keys in GLVis to visualize the displacements. if (visualization) { char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); sol_sock.precision(8); sol_sock << "solution\n" << *mesh << x << flush; } // 16. Free the used memory. delete local_constraints; delete solver; delete a; delete b; if (fec) { delete fespace; delete fec; } delete mesh; return 0; }
34.30597
80
0.618447
ajithvallabai
f890eff19a63ff3179c2ee29e8ce78a049fd3372
359
cpp
C++
src/main.cpp
baconpaul/faust-toy-surge-osc
97d0dfb79d27b97f3b062883ed2dee3222fa5da2
[ "MIT" ]
null
null
null
src/main.cpp
baconpaul/faust-toy-surge-osc
97d0dfb79d27b97f3b062883ed2dee3222fa5da2
[ "MIT" ]
null
null
null
src/main.cpp
baconpaul/faust-toy-surge-osc
97d0dfb79d27b97f3b062883ed2dee3222fa5da2
[ "MIT" ]
null
null
null
#include <iostream> namespace Surge { namespace FaustOscs { int spawn_justASin(); int spawn_basicOsc(); } } int main( int argc, char **argv ) { std::cout << "Hello World" << std::endl; std::cout << "Spawing basic" << std::endl; Surge::FaustOscs::spawn_basicOsc(); std::cout << "Spawing just" << std::endl; Surge::FaustOscs::spawn_justASin(); }
17.095238
45
0.651811
baconpaul
f892c30f6be5835882420eefb535e93b57ad5d09
1,577
cpp
C++
src/Motors.cpp
fu7mu4/entonetics
d0b2643f039a890b25d5036cc94bfe3b4d840480
[ "MIT" ]
null
null
null
src/Motors.cpp
fu7mu4/entonetics
d0b2643f039a890b25d5036cc94bfe3b4d840480
[ "MIT" ]
null
null
null
src/Motors.cpp
fu7mu4/entonetics
d0b2643f039a890b25d5036cc94bfe3b4d840480
[ "MIT" ]
null
null
null
#include "Motors.hpp" #include <iostream> namespace ento { Motor::Motor( void ) : m_dead(false), m_enabled(true) {} Motor::~Motor( void ) {} Linear_motor::Linear_motor( b2Body* body ) : m_body(body) {} void Linear_motor:: apply( float dt ) { std::cout << "Linear_motor::apply\n"; b2Vec2 vel = m_body->GetLinearVelocity(); float speed = b2Dot( vel, m_direction ); float speed_diff = m_target_speed - speed; // traveling left if( speed < 0.f ) { // want to travel left if( m_target_speed < 0.f ) { // want to travel left faster if( speed_diff < 0.f ) { float accel = std::max( speed_diff / dt, -m_max_accel ); m_body->ApplyForce( accel * m_body->GetMass() * m_direction, m_body->GetWorldCenter() ); } } // want to travel right else { assert( speed_diff >= 0.f ); float accel = std::min( speed_diff / dt, m_max_accel ); m_body->ApplyForce( accel * m_body->GetMass() * m_direction, m_body->GetWorldCenter() ); } } // traveling right else { // want to travel left if( m_target_speed < 0.f ) { assert( speed_diff <= 0.f ); float accel = std::max( speed_diff / dt, -m_max_accel ); m_body->ApplyForce( accel * m_body->GetMass() * m_direction, m_body->GetWorldCenter() ); } // want to travel right else { // want to travel right faster if( speed_diff > 0.f ) { float accel = std::min( speed_diff / dt, m_max_accel ); m_body->ApplyForce( accel * m_body->GetMass() * m_direction, m_body->GetWorldCenter() ); } } } } }
21.026667
64
0.610653
fu7mu4
f8969197258efbec51f45e4510bdfccefbf47f61
1,350
cpp
C++
test/test_typed_test.cpp
ncihnegn/jctest
92139e9b6362c2cb1d252caba4a268a852652554
[ "MIT" ]
38
2019-02-28T07:23:15.000Z
2021-11-22T14:08:00.000Z
test/test_typed_test.cpp
ncihnegn/jctest
92139e9b6362c2cb1d252caba4a268a852652554
[ "MIT" ]
5
2019-04-13T21:37:03.000Z
2020-04-11T13:06:31.000Z
test/test_typed_test.cpp
ncihnegn/jctest
92139e9b6362c2cb1d252caba4a268a852652554
[ "MIT" ]
4
2019-04-13T21:22:22.000Z
2020-07-13T20:09:13.000Z
#include <string.h> #include <stdio.h> #include "testutil.h" // To test the testing framework ///////////// void GlobalTestSetup(); // to silence a warning void GlobalTestSetup() { printf("Setting up the test\n"); } int GlobalTestTeardown(); // to silence a warning int GlobalTestTeardown() { printf("Verifying the the test\n"); return 0; } ////////////////////////////////////////////// struct TestClass1 { int value; int _pad; TestClass1() : value(2) {} }; struct TestClass2 { int value; int _pad; TestClass2() : value(4) {} }; ////////////////////////////////////////////// #if defined(USE_GTEST) typedef ::testing::Types<TestClass1, TestClass2> TestTypes; #else typedef jc_test_type2<TestClass1, TestClass2> TestTypes; #endif TYPED_TEST_CASE(TypedTest, TestTypes); ////////////////////////////////////////////// template<typename T> class TypedTest : public jc_test_base_class { protected: virtual void SetUp(); virtual void TearDown(); T instance; }; template<typename T> void TypedTest<T>::SetUp() { } template<typename T> void TypedTest<T>::TearDown() { } TYPED_TEST(TypedTest, NonZero) { ASSERT_NE(0, TestFixture::instance.value); } TYPED_TEST(TypedTest, Even) { ASSERT_EQ(0, TestFixture::instance.value & 0x1); } //////////////////////////////////////////////
18.493151
63
0.586667
ncihnegn
f897961b41157b5c190c4a8a80a8199a2030e1c3
2,734
cpp
C++
src/StoneCold.3D.Game/GameCore.cpp
krck/StoneCold_3D
5661a96e5167922b0ba555714a6d337acdea48c5
[ "BSD-3-Clause" ]
null
null
null
src/StoneCold.3D.Game/GameCore.cpp
krck/StoneCold_3D
5661a96e5167922b0ba555714a6d337acdea48c5
[ "BSD-3-Clause" ]
null
null
null
src/StoneCold.3D.Game/GameCore.cpp
krck/StoneCold_3D
5661a96e5167922b0ba555714a6d337acdea48c5
[ "BSD-3-Clause" ]
null
null
null
#include "GameCore.hpp" using namespace StoneCold::Game; //using namespace StoneCold::Resources; GameCore::GameCore() : _inputManager(InputManager()) , _windowManager(WindowManager()) { }; bool GameCore::Initialize(const std::string& windowName) { try { if (_windowManager.Initialize(&_inputManager)) { // Get the SDL_Renderer and setup the Engine _windowManager.SetupWindow("StoneCold 3D", WINDOW_WIDTH, WINDOW_HEIGHT, false); // Setup all the additional Managers in the correct order // ... // Setup the randomizer with a seed std::srand(RNG_SEED); //// Load all global Resources and create the basic States //_simulation.CreateIntroState(); //_simulation.CreateGameState(); //_simulation.CreateMenuState(); //// Load a first Level and add it to the GameState //_simulation.LoadLevel(); //// Push the first State to update and render //auto firstState = _engine.GetState<IntroState>(); //_engine.PushState(firstState); return true; } else { return false; } } catch (const std::exception & ex) { std::cout << ex.what() << std::endl; return false; } } // // Run the main Game-loop // int GameCore::Run() { try { const MouseClient mouse = MouseClient(MouseServer::GetInstance()); const KeyboardClient keyboard = KeyboardClient(KeyboardServer::GetInstance()); // Loop timer variables uint64 timeStamp_new = GetTicks(); uint64 timeStamp_old = GetTicks(); uint64 frameTime = 0; // delta in ms // FPS Counter variables const uint8 frameTimeSize = 20; auto frameTimes = std::array<uint64, frameTimeSize>(); uint64 frameCount = 0; float averageFPS = 0.f; // Start the main loop while (!_windowManager.IsClosed()) { timeStamp_new = GetTicks(); frameTime = timeStamp_new - timeStamp_old; _windowManager.Clear(); // Handle Input if (keyboard.IsKeyPressed(GLFW_KEY_A)) { std::cout << "A" << std::endl; } if (keyboard.IsKeyPressed(GLFW_KEY_D)) { std::cout << "D" << std::endl; } if (keyboard.IsKeyPressed(GLFW_KEY_W)) { std::cout << "W" << std::endl; } if (keyboard.IsKeyPressed(GLFW_KEY_S)) { std::cout << "S" << std::endl; } // Update Display-Screen and get Events _windowManager.Update(); // FPS counter (average) frameTimes[frameCount] = frameTime; frameCount++; if (frameCount == frameTimeSize) { frameCount = 0; averageFPS = 0.f; for (uint8 i = 0; i < frameTimeSize; i++) { averageFPS += frameTimes[i]; } averageFPS = 1000.f / (averageFPS / frameTimeSize); std::cout << "FPS: " << (uint16)averageFPS << "\n"; } timeStamp_old = timeStamp_new; } return 0; } catch (const std::exception & ex) { std::cout << ex.what() << std::endl; return -1; } }
26.288462
82
0.666057
krck
f897d643631ae458df51b555ea1faf510535b1e9
1,508
cc
C++
src/logic/propositional-kb.cc
obs145628/ai-cpp
32ff9365e0d3a36d219352ee6e3a01e62c633cc9
[ "MIT" ]
null
null
null
src/logic/propositional-kb.cc
obs145628/ai-cpp
32ff9365e0d3a36d219352ee6e3a01e62c633cc9
[ "MIT" ]
null
null
null
src/logic/propositional-kb.cc
obs145628/ai-cpp
32ff9365e0d3a36d219352ee6e3a01e62c633cc9
[ "MIT" ]
null
null
null
#include "logic/propositional-kb.hh" #include <sstream> #include "logic/ast-and.hh" #include "logic/eval-visitor.hh" #include "logic/parser.hh" #include "logic/symbols-visitor.hh" namespace logic { PropositionalKB::PropositionalKB() : kb_(nullptr) {} PropositionalKB::~PropositionalKB() { delete kb_; } void PropositionalKB::tell(const std::string& sentence) { std::istringstream is(sentence); Parser parser(is); AST* ast = parser.parse(); if (kb_) kb_ = new ASTAnd(Token{"&", Token::Type::AND}, kb_, ast); else kb_ = ast; } bool PropositionalKB::ask(const std::string& sentence) { std::istringstream is(sentence); Parser parser(is); AST* ast = parser.parse(); auto symbols = SymbolsVisitor::get(*kb_); for (const auto& sym : SymbolsVisitor::get(*ast)) symbols.insert(sym); Model model; auto res = check_all_(*ast, symbols, model); delete ast; return res; } bool PropositionalKB::check_all_(AST& ast, std::set<std::string>& symbols, Model& model) { if (symbols.empty()) return !EvalVisitor::eval(*kb_, model) || EvalVisitor::eval(ast, model); auto sym = symbols.begin(); symbols.erase(sym); model.var_set(*sym, true); if (!check_all_(ast, symbols, model)) return false; model.var_set(*sym, false); if (!check_all_(ast, symbols, model)) return false; symbols.insert(*sym); return true; } }
21.542857
78
0.618037
obs145628
f8a085d06c69abbcb0c5afbf0d66bf04f7f7e40b
833
cpp
C++
rt/rt/solids/sky.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/solids/sky.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/solids/sky.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
#include <rt/bbox.h> #include <rt/intersection.h> #include <rt/solids/sky.h> namespace rt { Sky::Sky(CoordMapper* texMapper, Material* material) : Solid(texMapper, material) { } BBox Sky::getBounds() const { return BBox::full(); } Intersection Sky::intersect(const Ray& ray, float previousBestDistance) const { if(previousBestDistance < std::numeric_limits<float>::infinity() && previousBestDistance != FLT_MAX) return Intersection::failure(); return Intersection(std::numeric_limits<float>::infinity(), ray, this, ray.d, Point::rep(std::numeric_limits<float>::infinity())); } Solid::Sample Sky::sample() const { const auto inv = Point::rep(std::numeric_limits<float>::infinity()); return { inv, inv - Point::rep(0.f) }; } float Sky::getArea() const { return std::numeric_limits<float>::infinity(); } }
23.8
79
0.70108
DasNaCl
f8a12320e7923737dd065eb25132e17ffc5a46dd
1,353
hpp
C++
ntree/hashentry.hpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
1
2015-06-14T15:54:27.000Z
2015-06-14T15:54:27.000Z
ntree/hashentry.hpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
null
null
null
ntree/hashentry.hpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
null
null
null
#pragma once #include "ntree.hpp" namespace boom { namespace ntree { //! ハッシュマップによるエントリ実装 /*! \tparam Ent エントリクラス \tparam NDiv 分割度 \tparam NL 次元数(2 or 3) */ template <class Ent, int NDiv, int Dim> class CTEnt_Hash : public CTEnt_Base<NDiv,Dim> { public: using Entry = Ent; private: using ObjHash = std::unordered_map<MortonId, Entry>; ObjHash _ent; public: CTEnt_Hash() { // ルートノードだけは作成しておく _ent[0]; } bool hasEntry(MortonId n) const { return _ent.count(n) == 1; } const Entry& getEntry(MortonId n) const { return _ent.at(n); } Entry& refEntry(MortonId n) { return _ent[n]; } void remEntry(MortonId n) { auto itr = _ent.find(n); AssertP(Trap, itr->second.isEmpty()) if(n != 0) _ent.erase(itr); } void increment(MortonId num) { AssertP(Trap, _ent[num].getLowerCount() >= 0) _ent[num].incrementLowerCount(); } void decrement(MortonId num) { // カウンタが0になったらエントリを削除 (ルートは消さない) auto itr = _ent.find(num); AssertP(Trap, itr!=_ent.end() && itr->second.getLowerCount()>0) itr->second.decrementLowerCount(); if(itr->second.isEmpty() && num!=0) { AssertP(Trap, itr->second.getObjList().empty()) _ent.erase(itr); } } void clear() { _ent.clear(); } }; } }
23.736842
68
0.593496
degarashi
f8a12e414e47ceed52e955a4c643f48ec8dd1500
504
hpp
C++
distributed_systems/locks/Locksmith.hpp
joaovicentesouto/INE5418
69edd7be883bde01068d58df85ba9dc49f9d23c1
[ "MIT" ]
null
null
null
distributed_systems/locks/Locksmith.hpp
joaovicentesouto/INE5418
69edd7be883bde01068d58df85ba9dc49f9d23c1
[ "MIT" ]
null
null
null
distributed_systems/locks/Locksmith.hpp
joaovicentesouto/INE5418
69edd7be883bde01068d58df85ba9dc49f9d23c1
[ "MIT" ]
null
null
null
#ifndef LOCKS_LOCKSMITH_HPP #define LOCKS_LOCKSMITH_HPP #include <iostream> #include <cstdlib> #include <utility> #include <functional> #include <distributed_systems/types/BasicTypes.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> namespace locks { class Locksmith { public: // Class constructors virtual ~Locksmith() = default; virtual void lock() = 0; virtual void unlock() = 0; }; } // namespace lock #endif // LOCKS_LOCKSMITH_HPP
20.16
58
0.69246
joaovicentesouto
f8a3e3ed5ee3a438a912821caae79e53dd206495
1,501
cpp
C++
Leetcode/Q44.cpp
kingium/Leetcode
f23029637f3a16545f15abcd8eafa8eadd56f146
[ "Unlicense" ]
1
2019-01-21T09:05:32.000Z
2019-01-21T09:05:32.000Z
Leetcode/Q44.cpp
kingium/Leetcode
f23029637f3a16545f15abcd8eafa8eadd56f146
[ "Unlicense" ]
1
2019-08-08T09:58:02.000Z
2019-08-08T09:58:02.000Z
Leetcode/Q44.cpp
goldsail/Leetcode
f23029637f3a16545f15abcd8eafa8eadd56f146
[ "Unlicense" ]
null
null
null
class Solution { public: bool isMatch(string s, string p) { bool result = false; // create the 2D table for dynamic programming bool **table = new bool*[p.size() + 1]; for (int i = 0; i < p.size() + 1; i++) { table[i] = new bool[s.size() + 1]; } // initialize the table's first row and first column table[0][0] = true; for (int j = 0; j < s.size(); j++) { table[0][j + 1] = false; } for (int i = 0; i < p.size(); i++) { table[i + 1][0] = table[i][0] && (p[i] == '*'); } // calculate other entries using DP for (int i = 0; i < p.size(); i++) { for (int j = 0; j < s.size(); j++) { switch (p[i]) { case '*': table[i + 1][j + 1] = table[i + 1][j] || table[i][j] || table[i][j + 1]; break; case '?': table[i + 1][j + 1] = table[i][j]; break; default: table[i + 1][j + 1] = table[i][j] && (p[i] == s[j]); break; } } } result = table[p.size()][s.size()]; // destroy the 2D table for (int i = 0; i < p.size() + 1; i++) { delete[] table[i]; } delete[] table; return result; } };
30.632653
96
0.345103
kingium
f8a6e2740e2576bef26f842ac1bb9aaa0692e661
435
hpp
C++
src/world/timer.hpp
ComLarsic/FinishTheGame_Rayjam
a5ddb7af9c0c4fd285cad26b13f9b58440fe3a89
[ "MIT" ]
null
null
null
src/world/timer.hpp
ComLarsic/FinishTheGame_Rayjam
a5ddb7af9c0c4fd285cad26b13f9b58440fe3a89
[ "MIT" ]
null
null
null
src/world/timer.hpp
ComLarsic/FinishTheGame_Rayjam
a5ddb7af9c0c4fd285cad26b13f9b58440fe3a89
[ "MIT" ]
null
null
null
#pragma once /** Represents the game tumer */ class Timer { public: Timer(); ~Timer(); /** Tick the timer */ void Tick(); /** Set the timer */ void Set(int minutes, int seconds); /** Add time to the timer */ void Add(int minutes, int seconds); /** Display the game timer */ void Draw(); /** Check if the timer is over */ bool IsOver(); private: int _minutes; float _seconds; };
19.772727
39
0.572414
ComLarsic
f8a8f59476c5abb81b72122783847f8e1da98b0a
7,008
cxx
C++
TivaWare/third_party/windows/fltk-1.1.10/src/Fl_Menu_.cxx
bumblebee96/pacman
1b82f1747765e807bef3040e4dac72c744fc3bc1
[ "MIT" ]
25
2015-04-20T13:03:05.000Z
2022-01-06T07:25:02.000Z
TivaWare/third_party/windows/fltk-1.1.10/src/Fl_Menu_.cxx
bumblebee96/pacman
1b82f1747765e807bef3040e4dac72c744fc3bc1
[ "MIT" ]
1
2021-03-21T03:00:58.000Z
2021-03-22T10:05:45.000Z
TivaWare/third_party/windows/fltk-1.1.10/src/Fl_Menu_.cxx
bumblebee96/pacman
1b82f1747765e807bef3040e4dac72c744fc3bc1
[ "MIT" ]
24
2015-09-22T12:08:11.000Z
2021-12-30T10:17:30.000Z
// // "$Id: Fl_Menu_.cxx 5190 2006-06-09 16:16:34Z mike $" // // Common menu code for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2005 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // // This is a base class for all items that have a menu: // Fl_Menu_Bar, Fl_Menu_Button, Fl_Choice // This provides storage for a menu item, functions to add/modify/delete // items, and a call for when the user picks a menu item. // More code in Fl_Menu_add.cxx #include <FL/Fl.H> #include <FL/Fl_Menu_.H> #include "flstring.h" #include <stdio.h> #include <stdlib.h> // Set 'pathname' of specified menuitem // If finditem==NULL, mvalue() is used (the most recently picked menuitem) // Returns: // 0 : OK // -1 : item not found (name="") // -2 : 'name' not large enough (name="") // #define SAFE_STRCAT(s) \ { len += strlen(s); if ( len >= namelen ) { *name='\0'; return(-2); } else strcat(name,(s)); } int Fl_Menu_::item_pathname(char *name, int namelen, const Fl_Menu_Item *finditem) const { int len = 0; finditem = finditem ? finditem : mvalue(); name[0] = '\0'; for ( int t=0; t<size(); t++ ) { const Fl_Menu_Item *m = &(menu()[t]); if ( m->submenu() ) { // submenu? descend if (*name) SAFE_STRCAT("/"); if (m->label()) SAFE_STRCAT(m->label()); } else { if (m->label()) { // menu item? if ( m == finditem ) { // found? tack on itemname, done. SAFE_STRCAT("/"); SAFE_STRCAT(m->label()); return(0); } } else { // end of submenu? pop char *ss = strrchr(name, '/'); if ( ss ) { *ss = 0; len = strlen(name); } // "File/Edit" -> "File" else { name[0] = '\0'; len = 0; } // "File" -> "" continue; } } } *name = '\0'; return(-1); // item not found } // FIND MENU ITEM INDEX, GIVEN MENU PATHNAME // eg. "Edit/Copy" // Will also return submenus, eg. "Edit" // Returns NULL if not found. // const Fl_Menu_Item * Fl_Menu_::find_item(const char *name) { char menupath[1024] = ""; // File/Export for ( int t=0; t < size(); t++ ) { Fl_Menu_Item *m = menu_ + t; if (m->flags&FL_SUBMENU) { // IT'S A SUBMENU // we do not support searches through FL_SUBMENU_POINTER links if (menupath[0]) strlcat(menupath, "/", sizeof(menupath)); strlcat(menupath, m->label(), sizeof(menupath)); if (!strcmp(menupath, name)) return m; } else { if (!m->label()) { // END OF SUBMENU? Pop back one level. char *ss = strrchr(menupath, '/'); if ( ss ) *ss = 0; else menupath[0] = '\0'; continue; } // IT'S A MENU ITEM char itempath[1024]; // eg. Edit/Copy strcpy(itempath, menupath); if (itempath[0]) strlcat(itempath, "/", sizeof(itempath)); strlcat(itempath, m->label(), sizeof(itempath)); if (!strcmp(itempath, name)) return m; } } return (const Fl_Menu_Item *)0; } int Fl_Menu_::value(const Fl_Menu_Item* m) { clear_changed(); if (value_ != m) {value_ = m; return 1;} return 0; } // When user picks a menu item, call this. It will do the callback. // Unfortunatly this also casts away const for the checkboxes, but this // was necessary so non-checkbox menus can really be declared const... const Fl_Menu_Item* Fl_Menu_::picked(const Fl_Menu_Item* v) { if (v) { if (v->radio()) { if (!v->value()) { // they are turning on a radio item set_changed(); ((Fl_Menu_Item*)v)->setonly(); } redraw(); } else if (v->flags & FL_MENU_TOGGLE) { set_changed(); ((Fl_Menu_Item*)v)->flags ^= FL_MENU_VALUE; redraw(); } else if (v != value_) { // normal item set_changed(); } value_ = v; if (when()&(FL_WHEN_CHANGED|FL_WHEN_RELEASE)) { if (changed() || when()&FL_WHEN_NOT_CHANGED) { if (value_ && value_->callback_) value_->do_callback((Fl_Widget*)this); else do_callback(); } } } return v; } // turn on one of a set of radio buttons void Fl_Menu_Item::setonly() { flags |= FL_MENU_RADIO | FL_MENU_VALUE; Fl_Menu_Item* j; for (j = this; ; ) { // go down if (j->flags & FL_MENU_DIVIDER) break; // stop on divider lines j++; if (!j->text || !j->radio()) break; // stop after group j->clear(); } for (j = this-1; ; j--) { // go up if (!j->text || (j->flags&FL_MENU_DIVIDER) || !j->radio()) break; j->clear(); } } Fl_Menu_::Fl_Menu_(int X,int Y,int W,int H,const char* l) : Fl_Widget(X,Y,W,H,l) { set_flag(SHORTCUT_LABEL); box(FL_UP_BOX); when(FL_WHEN_RELEASE_ALWAYS); value_ = menu_ = 0; alloc = 0; selection_color(FL_SELECTION_COLOR); textfont(FL_HELVETICA); textsize((uchar)FL_NORMAL_SIZE); textcolor(FL_FOREGROUND_COLOR); down_box(FL_NO_BOX); } int Fl_Menu_::size() const { if (!menu_) return 0; return menu_->size(); } void Fl_Menu_::menu(const Fl_Menu_Item* m) { clear(); value_ = menu_ = (Fl_Menu_Item*)m; } // this version is ok with new Fl_Menu_add code with fl_menu_array_owner: void Fl_Menu_::copy(const Fl_Menu_Item* m, void* ud) { int n = m->size(); Fl_Menu_Item* newMenu = new Fl_Menu_Item[n]; memcpy(newMenu, m, n*sizeof(Fl_Menu_Item)); menu(newMenu); alloc = 1; // make destructor free array, but not strings // for convienence, provide way to change all the user data pointers: if (ud) for (; n--;) { if (newMenu->callback_) newMenu->user_data_ = ud; newMenu++; } } Fl_Menu_::~Fl_Menu_() { clear(); } // Fl_Menu::add() uses this to indicate the owner of the dynamically- // expanding array. We must not free this array: Fl_Menu_* fl_menu_array_owner = 0; void Fl_Menu_::clear() { if (alloc) { if (alloc>1) for (int i = size(); i--;) if (menu_[i].text) free((void*)menu_[i].text); if (this == fl_menu_array_owner) fl_menu_array_owner = 0; else delete[] menu_; menu_ = 0; value_ = 0; alloc = 0; } } // // End of "$Id: Fl_Menu_.cxx 5190 2006-06-09 16:16:34Z mike $". //
30.077253
99
0.60117
bumblebee96
f8b191b1a4f2b63ce624657becd10b459e2c25a0
5,497
cpp
C++
Firmware/Flavors/ErisBici/btnpwm.cpp
JonathanCamargo/Eris
34c389f0808c8b47933605ed19d98e62280e56dd
[ "MIT" ]
null
null
null
Firmware/Flavors/ErisBici/btnpwm.cpp
JonathanCamargo/Eris
34c389f0808c8b47933605ed19d98e62280e56dd
[ "MIT" ]
null
null
null
Firmware/Flavors/ErisBici/btnpwm.cpp
JonathanCamargo/Eris
34c389f0808c8b47933605ed19d98e62280e56dd
[ "MIT" ]
null
null
null
#include "Eris.h" #include "btnpwm.h" namespace ButtonPWM{ thread_t *generatePWM = NULL; thread_t *transitions = NULL; static const int PERIOD_LOW_MS=(int) 1000/FREQ_LOW_HZ; static const int PERIOD_HIGH_MS=(int) 1000/FREQ_HIGH_HZ; typedef enum btnstates_t{ BTN_OFF, // Button is released BTN_PRESSED, // Button is pressed BTN_HOLD // Button is hold }; typedef enum btnactions_t{ ACTION_PRESS=0b0001, // Button is press ACTION_RELEASE=0b0010 // Button is release }; static btnstates_t btnstate=BTN_OFF; typedef enum pwmstates_t{ PWM_ZERO, PWM_LOW, PWM_HIGH }; static pwmstates_t pwmstate=PWM_ZERO; // Current state of the PWM static pwmstates_t pwmvel=PWM_LOW; // Current velocity of the PWM static THD_WORKING_AREA(waGeneratePWM_T, 16); static THD_FUNCTION(GeneratePWM_T, arg) { while(1){ // Update the pulse switch (pwmstate){ case PWM_ZERO: digitalWrite(PIN_LED,HIGH); chThdSleepMilliseconds(PERIOD_LOW_MS); break; case PWM_LOW: digitalWrite(PIN_LED,!digitalRead(PIN_LED)); chThdSleepMilliseconds(PERIOD_LOW_MS); break; case PWM_HIGH: digitalWrite(PIN_LED,!digitalRead(PIN_LED)); chThdSleepMilliseconds(PERIOD_HIGH_MS); break; } } } void PrintState(){ switch (btnstate){ case (BTN_OFF): Serial.println(F("BTN_OFF")); break; case (BTN_PRESSED): Serial.println(F("BTN_PRESSED")); break; case (BTN_HOLD): Serial.println(F("BTN_HOLD")); break; } } event_source_t action_event_source; static THD_WORKING_AREA(waTransitions_T, 16); static THD_FUNCTION(Transitions_T, arg) { long t0=millis(); long elapsed=0; // Check the button acctions and transition the state of the system event_listener_t action_event_listener; chEvtRegisterMaskWithFlags(&action_event_source, &action_event_listener, EVENT_MASK(0), ACTION_PRESS | ACTION_RELEASE); while(1){ PrintState(); eventmask_t evt = chEvtWaitOneTimeout(EVENT_MASK(0),TIME_IMMEDIATE); if (evt & EVENT_MASK(0)){ eventflags_t flags=chEvtGetAndClearFlags(&action_event_listener); switch (btnstate){ case (BTN_OFF): if (flags | ACTION_PRESS){ btnstate=BTN_PRESSED; t0=millis(); elapsed=0; // Chill } break; case (BTN_PRESSED): if (flags | ACTION_RELEASE){ btnstate=BTN_OFF; // Change velocity Serial.println(F("Toggle ON/OFF")); pwmstate==PWM_ZERO ? pwmstate=pwmvel : pwmstate=PWM_ZERO; } break; case (BTN_HOLD): if (flags | ACTION_RELEASE){ btnstate=BTN_OFF; // Chill } break; } } else{ // If no event registered the button could be still pressed or on hold switch (btnstate){ case (BTN_PRESSED): case (BTN_HOLD): elapsed=millis()-t0; if (elapsed>TIME_MIN_HOLD_MS && !digitalRead(PIN_BTN) ){ btnstate=BTN_HOLD; pwmvel==PWM_LOW ? pwmvel=PWM_HIGH : pwmvel=PWM_LOW; pwmstate=pwmvel; t0=millis(); Serial.println(F("Change speed")); } else if (elapsed>TIME_MIN_HOLD_MS){ btnstate=BTN_OFF; } break; } } chThdSleepMilliseconds(20); } } static long prevTime=0; static void ISR_PIN_BTN(){ chSysLockFromISR(); long time=millis(); if ((time-prevTime)<20){ //Prevent bouncing chSysUnlockFromISR(); return; } prevTime=time; switch (btnstate){ case BTN_OFF: // Button pressed :) eriscommon::println(F("press")); chEvtBroadcastFlagsI(&action_event_source,ACTION_PRESS); break; case BTN_PRESSED: eriscommon::println(F("release")); chEvtBroadcastFlagsI(&action_event_source,ACTION_RELEASE); break; case BTN_HOLD: eriscommon::println(F("release")); chEvtBroadcastFlagsI(&action_event_source,ACTION_RELEASE); break; } chSysUnlockFromISR(); } void start(void){ prevTime=millis(); chEvtObjectInit(&action_event_source); pinMode(PIN_BTN,INPUT_PULLUP); digitalWrite(PIN_LED,LOW); /*eriscommon::print(F("Low ms:")); eriscommon::println(PERIOD_LOW_MS); eriscommon::print(F("High ms:")); eriscommon::println(PERIOD_HIGH_MS); */ attachInterrupt(digitalPinToInterrupt(PIN_BTN), ISR_PIN_BTN,CHANGE); // create tasks at priority lowest priority generatePWM=chThdCreateStatic(waGeneratePWM_T, sizeof(waGeneratePWM_T),NORMALPRIO+1, GeneratePWM_T, NULL); transitions=chThdCreateStatic(waTransitions_T, sizeof(waTransitions_T),NORMALPRIO+1, Transitions_T, NULL); } }
30.370166
111
0.565035
JonathanCamargo
f8b37a7e1df401b2e3dd4e733422f340108a895d
310
cpp
C++
Phoebe-core/src/ph/renderer/objects/BufferLayout.cpp
JRBonilla/Slate
9bcb3befced30d8f9ffb2dcce0a0209ba76093e4
[ "MIT" ]
1
2017-02-26T23:37:37.000Z
2017-02-26T23:37:37.000Z
Phoebe-core/src/ph/renderer/objects/BufferLayout.cpp
JRBonilla/Slate
9bcb3befced30d8f9ffb2dcce0a0209ba76093e4
[ "MIT" ]
null
null
null
Phoebe-core/src/ph/renderer/objects/BufferLayout.cpp
JRBonilla/Slate
9bcb3befced30d8f9ffb2dcce0a0209ba76093e4
[ "MIT" ]
null
null
null
#include "BufferLayout.h" namespace ph { namespace renderer { BufferLayout::BufferLayout() { } void BufferLayout::Push(const std::string& name, uint type, uint size, uint count, bool normalized) { m_Layout.push_back({ name, type, size, count, m_Stride, normalized }); m_Stride += size * count; } }}
25.833333
102
0.703226
JRBonilla
f8b59b44718cd2acb8e291ab8d87881e209617c8
1,518
cpp
C++
LeetCode/ThousandOne/0682-baseball_game.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0682-baseball_game.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0682-baseball_game.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 682. 棒球比赛 你现在是棒球比赛记录员。 给定一个字符串列表,每个字符串可以是以下四种类型之一: 1.整数(一轮的得分):直接表示您在本轮中获得的积分数。 2. "+"(一轮的得分):表示本轮获得的得分是前两轮有效 回合得分的总和。 3. "D"(一轮的得分):表示本轮获得的得分是前一轮有效 回合得分的两倍。 4. "C"(一个操作,这不是一个回合的分数):表示您获得的最后一个有效 回合的分数是无效的,应该被移除。 每一轮的操作都是永久性的,可能会对前一轮和后一轮产生影响。 你需要返回你在所有回合中得分的总和。 示例 1: 输入: ["5","2","C","D","+"] 输出: 30 解释: 第1轮:你可以得到5分。总和是:5。 第2轮:你可以得到2分。总和是:7。 操作1:第2轮的数据无效。总和是:5。 第3轮:你可以得到10分(第2轮的数据已被删除)。总数是:15。 第4轮:你可以得到5 + 10 = 15分。总数是:30。 示例 2: 输入: ["5","-2","4","C","D","9","+","+"] 输出: 27 解释: 第1轮:你可以得到5分。总和是:5。 第2轮:你可以得到-2分。总数是:3。 第3轮:你可以得到4分。总和是:7。 操作1:第3轮的数据无效。总数是:3。 第4轮:你可以得到-4分(第三轮的数据已被删除)。总和是:-1。 第5轮:你可以得到9分。总数是:8。 第6轮:你可以得到-4 + 9 = 5分。总数是13。 第7轮:你可以得到9 + 5 = 14分。总数是27。 注意: 输入列表的大小将介于1和1000之间。 列表中的每个整数都将介于-30000和30000之间。 */ int calPoints(vector<string>& ops) { int sum = 0; vector<int> scores; scores.reserve(ops.size()); for (string const& p : ops) { if (p == "C") { sum -= scores.back(); scores.pop_back(); } else if (p == "D") { int t = scores.back() * 2; scores.push_back(t); sum += t; } else if (p == "+") { size_t len = scores.size(); int t = scores[len - 1] + scores[len - 2]; scores.push_back(t); sum += t; } else { int t; sscanf(p.c_str(), "%d", &t); scores.push_back(t); sum += t; } } return sum; } int main() { vector<string> ops1 = { "5", "2", "C", "D", "+" }; vector<string> ops2 = { "5", "-2", "4", "C", "D", "9", "+", "+" }; OutExpr(calPoints(ops1), "%d"); OutExpr(calPoints(ops2), "%d"); }
17.25
67
0.589592
Ginkgo-Biloba
f8b5f363224aafce2447cb956d9a6a3f4838c93e
2,192
cpp
C++
Extensions/ZilchShaders/CodeRangeMapping.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Extensions/ZilchShaders/CodeRangeMapping.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Extensions/ZilchShaders/CodeRangeMapping.cpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { //-------------------------------------------------------------------CodeRangeMapping CodeRangeMapping::CodeRangeMapping() { mSourcePositionStart = 0; mSourcePositionEnd = 0; mDestPositionStart = 0; mDestPositionEnd = 0; mIsRoot = false; } void CodeRangeMapping::Set(Zilch::CodeLocation& sourceLocation) { mSourcePositionStart = sourceLocation.StartPosition; mSourcePositionEnd = sourceLocation.EndPosition; mSourceFile = sourceLocation.Origin; } //-------------------------------------------------------------------ScopedRangeMapping ScopedRangeMapping::ScopedRangeMapping(ShaderCodeBuilder& builder, CodeRangeMapping* parent, Zilch::CodeLocation* zilchLocation, bool generateRanges, StringParam debugStr) { mGenerateRanges = generateRanges; if(!mGenerateRanges) return; mBuilder = &builder; mTotalOffset = builder.GetSize(); mParentTotalOffset = 0; mRange = &parent->mChildren.PushBack(); mRange->mDestPositionStart = mTotalOffset; mRange->mDebugString = debugStr; } ScopedRangeMapping::ScopedRangeMapping(ShaderCodeBuilder& builder, ScopedRangeMapping* parent, CodeRangeMapping* rangeToCopy, Zilch::CodeLocation* zilchLocation, bool generateRanges, StringParam debugStr) { mGenerateRanges = generateRanges; if(!mGenerateRanges) return; mBuilder = &builder; mParentTotalOffset = parent->mTotalOffset; mTotalOffset = builder.GetSize(); mRange = &parent->mRange->mChildren.PushBack(); if(rangeToCopy) *mRange = *rangeToCopy; mRange->mDestPositionStart = builder.GetSize() - parent->mTotalOffset; if(zilchLocation) mRange->Set(*zilchLocation); mRange->mDebugString = debugStr; } ScopedRangeMapping::~ScopedRangeMapping() { if(!mGenerateRanges) return; mRange->mDestPositionEnd = mBuilder->GetSize() - mParentTotalOffset; } }//namespace Zero
29.621622
205
0.635036
RachelWilSingh
f8bdce16c6c82fbda03543d2bce8ee439bee6e46
1,053
hpp
C++
modules/cvv/src/qtutil/matchview/keypointsettings.hpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/cvv/src/qtutil/matchview/keypointsettings.hpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/cvv/src/qtutil/matchview/keypointsettings.hpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
#ifndef CVVISUAL_KEYPOINT_SETTINGS #define CVVISUAL_KEYPOINT_SETTINGS #include <QFrame> #include <QPen> #include "cvvkeypoint.hpp" namespace cvv { namespace qtutil { class CVVKeyPoint; /** * @brief this abstract class returns an individual Setting for a CVVKeyPoint. */ class KeyPointSettings : public QFrame { Q_OBJECT public: /** * @brief KeyPointPen * @param parent the parent Widget */ KeyPointSettings(QWidget *parent) : QFrame(parent){} /** * @brief set individual settings for a selected cvvkeypoint */ virtual void setSettings(CVVKeyPoint &key) = 0; /** * @brief set individual settings for a non-selected cvvkeypoint */ /*virtual void setUnSelectedSettings(CVVKeyPoint &) {}*/ public slots: /** * @brief this method emits the signal settingsChanged(); */ void updateAll() { emit settingsChanged(*this); } signals: /** * @brief this signal will be emitted if the settings changed * and the CVVKeyPoint must update their Settings */ void settingsChanged(KeyPointSettings &); }; } } #endif
18.155172
78
0.71415
Nondzu
f8be55bece8a975d5d896358b1dff13a14fb954c
715
cpp
C++
src/Shared/Utils/Observer.cpp
Marukyu/NecroEdit
4b2380cc3417c6578476a213e05f4cbc846e5a77
[ "MIT", "Unlicense" ]
13
2016-04-02T14:21:49.000Z
2021-01-10T17:32:43.000Z
src/Shared/Utils/Observer.cpp
Marukyu/NecroEdit
4b2380cc3417c6578476a213e05f4cbc846e5a77
[ "MIT", "Unlicense" ]
24
2016-04-02T12:08:39.000Z
2021-01-27T01:21:58.000Z
src/Shared/Utils/Observer.cpp
Marukyu/NecroEdit
4b2380cc3417c6578476a213e05f4cbc846e5a77
[ "MIT", "Unlicense" ]
6
2016-04-02T12:05:28.000Z
2017-05-10T14:13:39.000Z
#include "Shared/Utils/Observer.hpp" Observer::~Observer() { while (!mySubjects.empty()) { (*mySubjects.begin())->removeObserver(this); } } Observable::~Observable() { while (!myObservers.empty()) { removeObserver(*myObservers.begin()); } } void Observable::addObserver(Observer* observer) { myObservers.insert(observer); observer->mySubjects.insert(this); } void Observable::removeObserver(Observer* observer) { myObservers.erase(observer); observer->mySubjects.erase(this); } bool Observable::isObserving(Observer* observer) const { return myObservers.count(observer); } void Observable::notify(int message) { for (auto observer : myObservers) { observer->onNotify(*this, message); } }
16.25
54
0.723077
Marukyu
f8c05003e5ea6b242a520651c161b3c4edf0b049
98,404
cpp
C++
STrenD/TrendHeatmapWindow.cpp
RoysamLab/STrend
1e8d84adfb28c0a2ea78d311daeac6afd04bc275
[ "BSD-4-Clause-UC" ]
null
null
null
STrenD/TrendHeatmapWindow.cpp
RoysamLab/STrend
1e8d84adfb28c0a2ea78d311daeac6afd04bc275
[ "BSD-4-Clause-UC" ]
null
null
null
STrenD/TrendHeatmapWindow.cpp
RoysamLab/STrend
1e8d84adfb28c0a2ea78d311daeac6afd04bc275
[ "BSD-4-Clause-UC" ]
null
null
null
#include "TrendHeatmapWindow.h" #define pi 3.1415926 #define POWER_PARAM 0.2 TrendHeatmapWindow::TrendHeatmapWindow(const QString title, QWidget *parent) : QMainWindow(parent) { this->mainQTRenderWidget; this->view = NULL; this->theme = NULL; this->graph_Layout = NULL; this->aPlane = NULL; this->cellData = NULL; this->celllut = NULL; this->mapper = NULL; this->actor = NULL; this->v = NULL; this->points = NULL; this->vertexColors = NULL; this->vetexlut = NULL; this->myCellPicker = NULL; this->ids1 = vtkSmartPointer<vtkIdTypeArray>::New(); this->ids2 = vtkSmartPointer<vtkIdTypeArray>::New(); this->ids1->SetNumberOfComponents(1); this->ids2->SetNumberOfComponents(1); this->dencolors1 = vtkSmartPointer<vtkUnsignedCharArray>::New(); this->denpoints1 = vtkSmartPointer<vtkPoints>::New(); this->denlines1 = vtkSmartPointer<vtkCellArray>::New(); this->denlinesPolyData1 =vtkSmartPointer<vtkPolyData>::New(); this->denmapper1 = vtkSmartPointer<vtkPolyDataMapper>::New(); this->denactor1 = vtkSmartPointer<vtkActor>::New(); this->dencolors2 = vtkSmartPointer<vtkUnsignedCharArray>::New(); this->denpoints2 = vtkSmartPointer<vtkPoints>::New(); this->denlines2 = vtkSmartPointer<vtkCellArray>::New(); this->denlinesPolyData2 =vtkSmartPointer<vtkPolyData>::New(); this->denmapper2 = vtkSmartPointer<vtkPolyDataMapper>::New(); this->denactor2 = vtkSmartPointer<vtkActor>::New(); this->removeActorflag = 0; this->denResetflag1 = 0; this->denResetflag2 = 0; this->continueselectnum = 0; this->continueselect = false; this->intersectionselect = false; this->clusflag = false; this->mapdata = NULL; this->Optimal_Leaf_Order1 = NULL; this->Optimal_Leaf_Order2 = NULL; this->connect_Data_Tree1 = NULL; this->connect_Data_Tree2 = NULL; this->ftreedata = NULL; setWindowTitle(title); } TrendHeatmapWindow::~TrendHeatmapWindow() { if(this->mapdata) { for(int i=0; i<num_samples; i++) delete this->mapdata[i]; delete this->mapdata; } if(this->Optimal_Leaf_Order1) delete this->Optimal_Leaf_Order1; if(this->Optimal_Leaf_Order2) delete this->Optimal_Leaf_Order2; if(this->connect_Data_Tree1) for(int i = 0; i<this->num_samples - 1; i++) delete this->connect_Data_Tree1[i]; delete this->connect_Data_Tree1; if(this->connect_Data_Tree2) for(int i = 0; i<this->num_features - 1; i++) delete this->connect_Data_Tree2[i]; delete this->connect_Data_Tree2; if(ftreedata) { for( int i = 0; i < this->table->GetNumberOfRows() - 1; i++) { delete ftreedata[i]; } delete ftreedata; } } void TrendHeatmapWindow::setDataForHeatmap(double** features, int* optimalleaforder1, int* optimalleaforder2,int num_samples, int num_features) { this->num_samples = num_samples; this->num_features = num_features; this->rowMapFromOriginalToReorder.clear(); this->columnMapFromOriginalToReorder.clear(); this->mapdata = new double*[num_samples]; for(int i=0; i<num_samples; i++) { this->mapdata[i] = new double[num_features]; for(int j = 0 ; j<num_features; j++) this->mapdata[i][j] = features[i][j]; } this->Optimal_Leaf_Order1 = new int[num_samples] ; for(int i=0; i<num_samples; i++) { this->Optimal_Leaf_Order1[i] = optimalleaforder1[i]; this->rowMapFromOriginalToReorder.insert( std::pair< int, int>(optimalleaforder1[i], i)); } this->Optimal_Leaf_Order2 = new int[num_features]; for(int i=0; i<num_features; i++) { this->Optimal_Leaf_Order2[i] = optimalleaforder2[i]; this->columnMapFromOriginalToReorder.insert( std::pair< int, int>(optimalleaforder2[i], i)); } } void TrendHeatmapWindow::creatDataForHeatmap(double powCof) { //double** mustd = new double*[2]; //mustd[0] = new double[107]; //mustd[1] = new double[107]; //this->readmustd(mustd); //this->scaleData(mustd); this->scaleData(); std::vector< double > temp; temp.resize(num_features); double** tempdata; tempdata = new double*[this->num_samples]; for(int i = 0; i < this->num_samples; i++) tempdata[i] = new double[this->num_features]; for(int i = 0; i < this->num_samples; i++) { double mean = 0.0; double std = 0.0; double sum = 0.0; for(int j = 0; j < this->num_features; j++) { temp[j] = mapdata[i][Optimal_Leaf_Order2[j]]; } for(int j = 0; j < this->num_features; j++) tempdata[i][j] = temp[j]; } for(int i = 0; i < this->num_samples; i++) mapdata[this->num_samples - i - 1] = tempdata[Optimal_Leaf_Order1[i]]; //const char* filename = "mapdata.txt"; //FILE *fp1 = fopen(filename,"w"); //for(int i=0; i<num_samples; i++) //{ // for(int j=0; j<num_features; j++) // fprintf(fp1,"%f\t",mapdata[i][j]); // fprintf(fp1,"\n"); //} //fclose(fp1); if( this->connect_Data_Tree1 != NULL) { this->createDataForDendogram1(powCof); } if( this->connect_Data_Tree2 != NULL) { this->createDataForDendogram2(powCof); } else { this->createDataForDendogram2(); } } void TrendHeatmapWindow::scaleData() { for(int i = 0; i<this->num_features; i++) { double mean = 0.0; double std = 0.0; double sum = 0.0; for(int j = 0; j<this->num_samples; j++) mean += mapdata[j][i]; mean /= this->num_samples; for(int j = 0; j<this->num_samples; j++) sum += (mapdata[j][i] - mean) * (mapdata[j][i] - mean); std = sqrt(sum/this->num_samples); if(std) for(int j = 0; j<this->num_samples; j++) mapdata[j][i] = (mapdata[j][i] - mean)/std; else for(int j = 0; j<this->num_samples; j++) mapdata[j][i] = 0; } } void TrendHeatmapWindow::scaleData(double** mustd) { for(int i = 0; i<this->num_features; i++) { if(mustd[1][i+1]) for(int j = 0; j<this->num_samples; j++) mapdata[j][Optimal_Leaf_Order2[i]] = (mapdata[j][Optimal_Leaf_Order2[i]] - mustd[0][i+1])/mustd[1][i+1]; else for(int j = 0; j<this->num_samples; j++) mapdata[j][i] = 0; } } void TrendHeatmapWindow::readmustd(double** mustd) { double temp[107]; const int MAXLINESIZE = 10024; char line[MAXLINESIZE]; ifstream infile; infile.open("mustd.txt"); if(infile.is_open()) { int i = 0; for(int t = 0 ;t<2; t++) { infile.getline(line, MAXLINESIZE); char* pch = strtok(line, "\t"); int k = 0; while(pch) { temp[k++] = atof(pch); pch = strtok(NULL, "\t"); } for(int j = 0; j<107; j++) mustd[i][j] = temp[j]; i++; } } infile.close(); for(int i=0; i<2 ;i++) { for(int j = 0; j<107; j++) cout<<mustd[i][j]<<"\t"; cout<<endl; } } void TrendHeatmapWindow::setModels(vtkSmartPointer<vtkTable> table, ObjectSelection * sels, ObjectSelection * sels2) { this->table = table; this->indMapFromVertexToInd.clear(); this->indMapFromIndToVertex.clear(); if( this->table) { for( int i = 0; i < this->table->GetNumberOfRows(); i++) { int var = this->table->GetValue( i, 0).ToInt(); this->indMapFromVertexToInd.insert( std::pair< int, int>(var, i)); this->indMapFromIndToVertex.push_back( var); } } if(!sels) this->Selection = new ObjectSelection(); else this->Selection = sels; if(!sels2) this->Selection2 = new ObjectSelection(); else this->Selection2 = sels2; connect(Selection, SIGNAL(changed()), this, SLOT(GetSelecectedIDs())); } void TrendHeatmapWindow::runClusclus() { double** datas; vtkVariant temp; datas = new double*[this->table->GetNumberOfRows()]; std::cout<<"number of rows"<<this->table->GetNumberOfRows()<<endl; std::cout<<"number of columns"<<this->table->GetNumberOfColumns()<<endl; for (int i = 0; i < this->table->GetNumberOfRows(); i++) { datas[i] = new double[this->table->GetNumberOfColumns() - 1 + 2 ]; } for(int i = 0; i < this->table->GetNumberOfRows(); i++) { for(int j = 1; j < this->table->GetNumberOfColumns(); j++) { temp = this->table->GetValue(i, j); datas[i][j-1] = temp.ToDouble(); } } cc1 = new clusclus(datas, (int)this->table->GetNumberOfRows(), (int)this->table->GetNumberOfColumns() - 1); cc1->Transpose(); cc2 = new clusclus(cc1->transposefeatures,cc1->num_features, cc1->num_samples); #pragma omp parallel sections { #pragma omp section { cc1->RunClusClus(); /*cc1->WriteClusteringOutputToFile("mergers.txt","features.txt","progress.txt", "members.txt", "gap.txt", "treedata.txt", "Optimalleaforder.txt");*/ } #pragma omp section { cc2->RunClusClus(); /*cc2->WriteClusteringOutputToFile("mergers2.txt","features2.txt","progress2.txt", "members2.txt", "gap2.txt", "treedata2.txt", "Optimalleaforder2.txt");*/ } } cout<<"finish clusclus....."<<endl; this->setDataForHeatmap(cc1->features, cc1->optimalleaforder, cc2->optimalleaforder,cc1->num_samples, cc2->num_samples); this->setDataForDendrograms(cc1->treedata, cc2->treedata); this->creatDataForHeatmap(POWER_PARAM); for (int i = 0; i < this->table->GetNumberOfRows(); i++) { delete datas[i]; } delete datas; delete cc1; delete cc2; } void TrendHeatmapWindow::runClus() { this->clusflag = true; double** datas; vtkVariant temp; datas = new double*[this->table->GetNumberOfRows()]; std::cout<<this->table->GetNumberOfRows()<<endl; std::cout<<this->table->GetNumberOfColumns()<<endl; for (int i = 0; i < this->table->GetNumberOfRows(); i++) { datas[i] = new double[this->table->GetNumberOfColumns() - 1 + 2 ]; } for(int i = 0; i < this->table->GetNumberOfRows(); i++) { for(int j = 1; j < this->table->GetNumberOfColumns(); j++) { temp = this->table->GetValue(i, j); datas[i][j-1] = temp.ToDouble(); } } cc1 = new clusclus(datas, (int)this->table->GetNumberOfRows(), (int)this->table->GetNumberOfColumns() - 1); cc1->RunClusClus(); cout<<"finish clusclus....."<<endl; cout<<this->table->GetNumberOfRows(); cout<<this->table->GetNumberOfColumns(); cc1->WriteClusteringOutputToFile("mergers.txt","features.txt","progress.txt", "members.txt", "gap.txt", "treedata.txt", "Optimalleaforder.txt"); int* optimalleaforder2 = new int[cc1->num_features]; for(int i = 0;i<cc1->num_features; i++) optimalleaforder2[i]=i; this->setDataForHeatmap(cc1->features, cc1->optimalleaforder, optimalleaforder2,cc1->num_samples, cc1->num_features); this->setDataForDendrograms(cc1->treedata); this->creatDataForHeatmap(POWER_PARAM); for (int i = 0; i < this->table->GetNumberOfRows(); i++) { delete datas[i]; } delete datas; delete cc1; } void TrendHeatmapWindow::showGraph() { if(this->clusflag == true) this->drawPoints3(); else this->drawPoints1(); this->aPlane = vtkSmartPointer<vtkPlaneSource>::New(); this->aPlane->SetXResolution(this->num_features); this->aPlane->SetYResolution(this->num_samples); this->cellData = vtkSmartPointer<vtkFloatArray>::New(); int index = 0; for (int i = 0; i < this->num_samples; i++) { for(int j = 0; j < this->num_features; j++) { cellData->InsertNextValue(index++); } } this->celllut = vtkSmartPointer<vtkLookupTable>::New(); this->celllut->SetNumberOfTableValues(this->num_samples*this->num_features); this->celllut->SetTableRange(0, this->num_samples*this->num_features - 1); this->celllut->Build(); //int k = 0; //boost::math::normal N; //try //{ // for(int i = 0; i < this->num_samples; i++) // { // for(int j = 0; j < this->num_features; j++) // { // if(mapdata[num_samples - i - 1][j] < 0) // celllut->SetTableValue(k++, 0, 1 - cdf(N,mapdata[num_samples - i - 1][j]), 0); // else if(mapdata[num_samples - i - 1][j] > 0) // celllut->SetTableValue(k++, cdf(N,mapdata[num_samples - i - 1][j]), 0, 0); // else // celllut->SetTableValue(k++, 0, 0, 0); // } // } //} //catch(...) //{ // cout<<"Boost call failed! please try again!"<<endl; //} int k = 0; for(int i = 0; i < this->num_samples; i++) { for(int j = 0; j < this->num_features; j++) { rgb rgb = GetRGBValue( mapdata[num_samples - i - 1][j]); celllut->SetTableValue(k++, rgb.r, rgb.g, rgb.b); } } this->aPlane->Update(); this->aPlane->GetOutput()->GetCellData()->SetScalars(cellData); this->mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); this->mapper->SetInputConnection(aPlane->GetOutputPort()); this->mapper->SetScalarRange(0, this->num_samples*this->num_features - 1); this->mapper->SetLookupTable(celllut); this->actor = vtkSmartPointer<vtkActor>::New(); this->actor->SetMapper(mapper); vtkSmartPointer<vtkLookupTable> scalarbarLut = vtkSmartPointer<vtkLookupTable>::New(); scalarbarLut->SetTableRange (-1, 1); scalarbarLut->SetNumberOfTableValues(COLOR_MAP_SIZE); for(int index = 0; index<COLOR_MAP_SIZE;index++) { rgb rgbscalar = COLORMAP[index]; scalarbarLut->SetTableValue(index, rgbscalar.r, rgbscalar.g, rgbscalar.b); } scalarbarLut->Build(); vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar->SetLookupTable(scalarbarLut); scalarBar->SetTitle("Color Map"); scalarBar->SetNumberOfLabels(10); scalarBar->GetTitleTextProperty()->SetColor(0,0,0); scalarBar->GetTitleTextProperty()->SetFontSize (10); scalarBar->GetLabelTextProperty()->SetColor(0,0,0); scalarBar->GetTitleTextProperty()->SetFontSize (10); scalarBar->SetMaximumHeightInPixels(1000); scalarBar->SetMaximumWidthInPixels(100); this->view->GetRenderer()->AddActor(actor); this->view->GetRenderer()->AddActor2D(scalarBar); this->SetInteractStyle(); this->view->GetRenderer()->GradientBackgroundOff(); this->view->GetRenderer()->SetBackground(1,1,1); try { if(this->clusflag == true) this->showDendrogram1(); else { this->showDendrogram1(); this->showDendrogram2(); } } catch(...) { cout<<"Draw dendrogram failed ! Please try again!"<<endl; } this->view->Render(); this->view->GetInteractor()->Start(); } void TrendHeatmapWindow::SetInteractStyle() { this->theme->SetCellValueRange(0, this->num_samples*this->num_features - 1); this->theme->SetSelectedCellColor(1,0,1); this->theme->SetSelectedPointColor(1,0,1); this->view->ApplyViewTheme(theme); this->myCellPicker = vtkSmartPointer<vtkCellPicker>::New(); this->view->GetInteractor()->SetPicker(this->myCellPicker); this->myCellPicker->SetTolerance(0.004); vtkSmartPointer<vtkCallbackCommand> selectionCallback2 =vtkSmartPointer<vtkCallbackCommand>::New(); selectionCallback2->SetClientData(this); selectionCallback2->SetCallback(SelectionCallbackFunction2 ); vtkSmartPointer<vtkCallbackCommand> selectionCallback3 =vtkSmartPointer<vtkCallbackCommand>::New(); selectionCallback3->SetClientData(this); selectionCallback3->SetCallback(SelectionCallbackFunction3); this->keyPress = vtkSmartPointer<vtkCallbackCommand>::New(); this->keyPress->SetCallback(HandleKeyPress); this->keyPress->SetClientData(this); this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonPressEvent); this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonReleaseEvent); this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyPressEvent); this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyReleaseEvent); this->view->GetInteractor()->AddObserver(vtkCommand::RightButtonPressEvent, selectionCallback2); this->view->GetInteractor()->AddObserver(vtkCommand::RightButtonReleaseEvent, selectionCallback3); this->view->GetInteractor()->AddObserver(vtkCommand::KeyPressEvent, this->keyPress); this->mainQTRenderWidget.SetRenderWindow(view->GetRenderWindow()); this->mainQTRenderWidget.resize(600, 600); this->mainQTRenderWidget.show(); } rgb TrendHeatmapWindow::GetRGBValue(double val) { int index = 64 * (val+1) - 1; // when val = 1; index should be the max index if( index >= COLOR_MAP_SIZE) { index = COLOR_MAP_SIZE - 1; } else if( index < 0) { index = 0; } return COLORMAP[index]; } void TrendHeatmapWindow::setDataForDendrograms(double** treedata1, double** treedata2) { if(treedata1 != NULL) { this->connect_Data_Tree1 = new double*[this->num_samples-1]; this->rowMapForTreeData.clear(); for(int i = 0; i<this->num_samples - 1; i++) { this->connect_Data_Tree1[i] = new double[4]; for(int j = 0; j<4; j++) this->connect_Data_Tree1[i][j] = treedata1[i][j]; this->rowMapForTreeData.insert( std::pair< int, int>(treedata1[i][3], i)); } } if( treedata2 != NULL) { this->connect_Data_Tree2 = new double*[this->num_features-1]; this->columnMapForTreeData.clear(); for(int i = 0; i<this->num_features - 1; i++) { this->connect_Data_Tree2[i] = new double[4]; for(int j = 0; j<4; j++) this->connect_Data_Tree2[i][j] = treedata2[i][j]; this->columnMapForTreeData.insert( std::pair< int, int>(treedata2[i][3], i)); } } } void TrendHeatmapWindow::createDataForDendogram1(double powCof) { this->Processed_Coordinate_Data_Tree1.resize(2*(this->num_samples) - 1); for(int i = 0; i < 2*(this->num_samples) - 1; i++) { this->Processed_Coordinate_Data_Tree1[i].resize(4); } for(int i = 0; i < num_samples; i++) { Processed_Coordinate_Data_Tree1[i][0] = i; int k = rowMapFromOriginalToReorder.find(i)->second; Processed_Coordinate_Data_Tree1[i][2] = (k + 0.5)/(double)this->num_samples - 0.5; Processed_Coordinate_Data_Tree1[i][1] = -0.5; Processed_Coordinate_Data_Tree1[i][3] = 0; } std::cout<<std::endl; std::cout<< "Max value:"<<connect_Data_Tree1[num_samples-2][2]<<std::endl; std::cout<< "devided by:"<<2 * pow(connect_Data_Tree1[num_samples - 2][2], powCof)<<std::endl; for(int i = 0; i < num_samples-1; i++) { connect_Data_Tree1[i][2] = pow(connect_Data_Tree1[i][2], powCof); connect_Data_Tree1[i][2] /= pow(connect_Data_Tree1[num_samples-2][2], powCof); connect_Data_Tree1[i][2] /= 2; } connect_Data_Tree1[num_samples-2][2] = 0.5; for(int i = num_samples ; i < 2*num_samples - 1; i++) { Processed_Coordinate_Data_Tree1[i][0] = i; for(int k = 0; k < num_samples -1 ; k++) { if(i == connect_Data_Tree1[k][3]) { double temp1, temp2; temp1 = connect_Data_Tree1[k][0]; temp2 = connect_Data_Tree1[k][1]; Processed_Coordinate_Data_Tree1[i][2] = (Processed_Coordinate_Data_Tree1[temp1][2] + Processed_Coordinate_Data_Tree1[temp2][2])/2; Processed_Coordinate_Data_Tree1[i][1] = -connect_Data_Tree1[k][2] - 0.5; } } Processed_Coordinate_Data_Tree1[i][3] = 0; } } void TrendHeatmapWindow::createDataForDendogram2() { this->Processed_Coordinate_Data_Tree2.resize(this->num_features); for(int i = 0; i < this->num_features; i++) { this->Processed_Coordinate_Data_Tree2[i].resize(4); } for(int i = 0; i < num_features; i++) { Processed_Coordinate_Data_Tree2[i][0] = i; int k = columnMapFromOriginalToReorder.find(i)->second; Processed_Coordinate_Data_Tree2[i][1] = (k+0.5)/(double)this->num_features - 0.5; Processed_Coordinate_Data_Tree2[i][2] = 0.5; Processed_Coordinate_Data_Tree2[i][3] = 0; } } void TrendHeatmapWindow::createDataForDendogram2(double powCof) { this->Processed_Coordinate_Data_Tree2.resize(2*(this->num_features) - 1); for(int i = 0; i < 2*(this->num_features) - 1; i++) { this->Processed_Coordinate_Data_Tree2[i].resize(4); } for(int i = 0; i < num_features; i++) { Processed_Coordinate_Data_Tree2[i][0] = i; int k = columnMapFromOriginalToReorder.find(i)->second; Processed_Coordinate_Data_Tree2[i][1] = (k+0.5)/(double)this->num_features - 0.5; Processed_Coordinate_Data_Tree2[i][2] = 0.5; Processed_Coordinate_Data_Tree2[i][3] = 0; } for(int i = 0; i < num_features-1; i++) { connect_Data_Tree2[i][2] = pow(connect_Data_Tree2[i][2], powCof); connect_Data_Tree2[i][2] /= pow(connect_Data_Tree2[num_features - 2][2], powCof); connect_Data_Tree2[i][2] /= 2; } connect_Data_Tree2[num_features - 2][2] = 0.5; for(int i = num_features ; i < 2*num_features - 1; i++) { Processed_Coordinate_Data_Tree2[i][0] = i; for(int k = 0; k < num_features -1 ; k++) { if(i == connect_Data_Tree2[k][3]) { double temp1, temp2; temp1 = connect_Data_Tree2[k][0]; temp2 = connect_Data_Tree2[k][1]; Processed_Coordinate_Data_Tree2[i][1] = (Processed_Coordinate_Data_Tree2[temp1][1] + Processed_Coordinate_Data_Tree2[temp2][1])/2; Processed_Coordinate_Data_Tree2[i][2] = connect_Data_Tree2[k][2] + 0.5; } } Processed_Coordinate_Data_Tree2[i][3] = 0; } } void TrendHeatmapWindow::showDendrogram1() { double p1[3]; double p2[3]; double p3[3]; double p4[3]; this->dencolors1->SetNumberOfComponents(3); this->dencolors1->SetName("denColors1"); unsigned char color[3] = {0, 0, 0}; for(int i=0; i<3*(this->num_samples - 1);i++) this->dencolors1->InsertNextTupleValue(color); for(int i=0; i<this->num_samples-1;i++) { double temp1 = this->connect_Data_Tree1[i][0]; double temp2 = this->connect_Data_Tree1[i][1]; for(int j=0; j<(2*(this->num_samples))-1; j++) { if(this->Processed_Coordinate_Data_Tree1[j][0]==temp1) { p1[0]=this->Processed_Coordinate_Data_Tree1[j][1]; p1[1]=this->Processed_Coordinate_Data_Tree1[j][2]; p1[2]=this->Processed_Coordinate_Data_Tree1[j][3]; } if(this->Processed_Coordinate_Data_Tree1[j][0]==temp2) { p2[0]=this->Processed_Coordinate_Data_Tree1[j][1]; p2[1]=this->Processed_Coordinate_Data_Tree1[j][2]; p2[2]=this->Processed_Coordinate_Data_Tree1[j][3]; } } p3[0]=-connect_Data_Tree1[i][2] - 0.5; p3[1]=p1[1]; p3[2]=p1[2]; p4[0]=-connect_Data_Tree1[i][2] - 0.5; p4[1]=p2[1]; p4[2]=p2[2]; this->denpoints1->InsertNextPoint(p1); this->denpoints1->InsertNextPoint(p2); this->denpoints1->InsertNextPoint(p3); this->denpoints1->InsertNextPoint(p4); vtkSmartPointer<vtkLine> line0 = vtkSmartPointer<vtkLine>::New(); line0->GetPointIds()->SetId(0,0 + i*4); line0->GetPointIds()->SetId(1,2 + i*4); this->denlines1->InsertNextCell(line0); vtkSmartPointer<vtkLine> line1 = vtkSmartPointer<vtkLine>::New(); line1->GetPointIds()->SetId(0,1 + i*4); line1->GetPointIds()->SetId(1,3 + i*4); this->denlines1->InsertNextCell(line1); vtkSmartPointer<vtkLine> line2 = vtkSmartPointer<vtkLine>::New(); line2->GetPointIds()->SetId(0,2 + i*4); line2->GetPointIds()->SetId(1,3 + i*4); this->denlines1->InsertNextCell(line2); } this->denlinesPolyData1->SetPoints(denpoints1); this->denlinesPolyData1->SetLines(denlines1); this->denlinesPolyData1->GetCellData()->SetScalars(dencolors1); this->denmapper1->SetInputData(denlinesPolyData1); this->denmapper1->SetScalarRange(0, 3*this->num_samples-1); this->denactor1 = vtkSmartPointer<vtkActor>::New(); this->denactor1->SetMapper(denmapper1); this->view->GetRenderer()->AddActor(denactor1); } void TrendHeatmapWindow::showDendrogram2() { double p1[3]; double p2[3]; double p3[3]; double p4[3]; this->dencolors2->SetNumberOfComponents(3); this->dencolors2->SetName("denColors2"); unsigned char color[3] = {0, 0, 0}; for(int i=0; i<3*(this->num_features - 1);i++) this->dencolors2->InsertNextTupleValue(color); for(int i=0; i<this->num_features-1; i++) { double temp1 = this->connect_Data_Tree2[i][0]; double temp2 = this->connect_Data_Tree2[i][1]; for(int j=0; j<(2*(this->num_features))-1; j++) { if(this->Processed_Coordinate_Data_Tree2[j][0]==temp1) { p1[0]=this->Processed_Coordinate_Data_Tree2[j][1]; p1[1]=this->Processed_Coordinate_Data_Tree2[j][2]; p1[2]=this->Processed_Coordinate_Data_Tree2[j][3]; } if(this->Processed_Coordinate_Data_Tree2[j][0]==temp2) { p2[0]=this->Processed_Coordinate_Data_Tree2[j][1]; p2[1]=this->Processed_Coordinate_Data_Tree2[j][2]; p2[2]=this->Processed_Coordinate_Data_Tree2[j][3]; } } p3[0]=p1[0]; p3[1]=this->connect_Data_Tree2[i][2] + 0.5; p3[2]=p1[2]; p4[0]=p2[0]; p4[1]=this->connect_Data_Tree2[i][2] + 0.5; p4[2]=p2[2]; this->denpoints2->InsertNextPoint(p1); this->denpoints2->InsertNextPoint(p2); this->denpoints2->InsertNextPoint(p3); this->denpoints2->InsertNextPoint(p4); vtkSmartPointer<vtkLine> line0 = vtkSmartPointer<vtkLine>::New(); line0->GetPointIds()->SetId(0,0 + i*4); line0->GetPointIds()->SetId(1,2 + i*4); this->denlines2->InsertNextCell(line0); vtkSmartPointer<vtkLine> line1 = vtkSmartPointer<vtkLine>::New(); line1->GetPointIds()->SetId(0,1 + i*4); line1->GetPointIds()->SetId(1,3 + i*4); this->denlines2->InsertNextCell(line1); vtkSmartPointer<vtkLine> line2 = vtkSmartPointer<vtkLine>::New(); line2->GetPointIds()->SetId(0,2 + i*4); line2->GetPointIds()->SetId(1,3 + i*4); this->denlines2->InsertNextCell(line2); } this->denlinesPolyData2->SetPoints(denpoints2); this->denlinesPolyData2->SetLines(denlines2); this->denlinesPolyData2->GetCellData()->SetScalars(dencolors2); this->denmapper2->SetInputData(denlinesPolyData2); this->denmapper2->SetScalarRange(0, 3*this->num_features-1); this->denactor2->SetMapper(denmapper2); this->view->GetRenderer()->AddActor(denactor2); } void TrendHeatmapWindow::GetSelecectedIDs() { cout<<"get selected"<<endl; std::set<long int> selectedIDs2 = this->Selection2->getSelections(); std::set<long int> selectedIDs1 = this->Selection->getSelections(); std::set<long int>::iterator iter1 = selectedIDs1.begin(); std::set<long int>::iterator iter2 = selectedIDs2.begin(); vtkSmartPointer<vtkIdTypeArray> cellids = vtkSmartPointer<vtkIdTypeArray>::New(); cellids->SetNumberOfComponents(1); int num1 = selectedIDs1.size(); int num2 = selectedIDs2.size(); std::vector<int > IDs1; std::vector<int > IDs2; IDs1.resize(num1); IDs2.resize(num2); int count1 = 0; int count2 = 0; #pragma omp parallel sections { #pragma omp section while(iter1 != selectedIDs1.end()) { int index1 = *iter1; int var = indMapFromVertexToInd.find(index1)->second; int id1 = rowMapFromOriginalToReorder.find(var)->second; IDs1[count1++] = id1; iter1++; } #pragma omp section while(iter2 != selectedIDs2.end()) { int index2 = *iter2; int id2 = columnMapFromOriginalToReorder.find(index2)->second; IDs2[count2++] = id2; iter2++; } } if( num1 == 0 && num2 != 0) { num1 = this->num_samples; IDs1.resize(num1); for( int i = 0; i < this->num_samples; i++) { IDs1[i] = i; } } if( num2 == 0 && num1 != 0) { num2 = this->num_features; IDs2.resize(num2); for( int i = 0; i < this->num_features; i++) { IDs2[i] = i; } } for(int i = 0; i<num1; i++) for(int j = 0; j<num2; j++) cellids->InsertNextValue( (IDs1[i])*(this->num_features) + IDs2[j]); vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New(); selectionNode->SetFieldType(vtkSelectionNode::CELL); selectionNode->SetContentType(vtkSelectionNode::INDICES); selectionNode->SetSelectionList(cellids); vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); selection->AddNode(selectionNode); vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New(); extractSelection->SetInputData(0, this->aPlane->GetOutput()); extractSelection->SetInputData(1, selection); extractSelection->Update(); vtkSmartPointer<vtkUnstructuredGrid> selected = vtkSmartPointer<vtkUnstructuredGrid>::New(); selected->ShallowCopy(extractSelection->GetOutput()); vtkSmartPointer<vtkDataSetMapper> selectedMapper = vtkSmartPointer<vtkDataSetMapper>::New(); selectedMapper->SetInputData(selected); vtkSmartPointer<vtkActor> selectedActor = vtkSmartPointer<vtkActor>::New(); selectedActor->SetMapper(selectedMapper); selectedActor->GetProperty()->EdgeVisibilityOn(); selectedActor->GetProperty()->SetEdgeColor(1,1,1); selectedActor->GetProperty()->SetLineWidth(0.5); if(this->dragLineFlag) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(dragLineActor); try { if(continueselect == false) { if(continueselectnum > 0) { cout<<"I'm here "<<continueselectnum<<endl; for(int i = 0; i<continueselectnum + 1; i++) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor()); continueselectnum = 0; } else { if (this->removeActorflag != 0) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor()); } this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor); this->removeActorflag += 1; } else { this->continueselectnum += 1; this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor); } if(this->dragLineFlag) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(dragLineActor); this->view->Render(); } catch(...) { cout<<"GetSelecectedIDs failed, please try it again!"<<endl; } } void TrendHeatmapWindow::drawPoints1() { int max_table_values = 2*this->num_samples + 2*this->num_features-2; this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); this->points = vtkSmartPointer<vtkPoints>::New(); this->v = vtkSmartPointer<vtkIdTypeArray>::New(); v->SetNumberOfValues (max_table_values); for(int i=0; i<2*this->num_samples-1;i++) { v->SetValue (i,graph_Layout->AddVertex()); this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree1[i][1],this->Processed_Coordinate_Data_Tree1[i][2],this->Processed_Coordinate_Data_Tree1[i][3]); } for(int i=0; i<(2*this->num_features-1);i++) { v->SetValue (i+2*this->num_samples-1,graph_Layout->AddVertex()); this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1],this->Processed_Coordinate_Data_Tree2[i][2],this->Processed_Coordinate_Data_Tree2[i][3]); } this->graph_Layout->SetPoints(this->points); this->vertexColors = vtkSmartPointer<vtkIntArray>::New(); vertexColors->SetNumberOfComponents(1); vertexColors->SetName("Color1"); this->vetexlut = vtkSmartPointer<vtkLookupTable>::New(); vetexlut->SetNumberOfTableValues(max_table_values); for(int i=0; i<max_table_values;i++) { vetexlut->SetTableValue(i, 0.5, 0.5,0.5); // color the vertices- blue } vetexlut->Build(); vtkSmartPointer<vtkFloatArray> scales1 = vtkSmartPointer<vtkFloatArray>::New(); /// scales for vertex size scales1->SetNumberOfComponents(1); scales1->SetName("Scales1"); for(int j=0;j<max_table_values;j++) { vertexColors->InsertNextValue(j); scales1->InsertNextValue(1); } this->graph_Layout->GetVertexData()->AddArray(vertexColors); this->graph_Layout->GetVertexData()->AddArray(scales1); this->view = vtkSmartPointer<vtkGraphLayoutView>::New(); this->view->AddRepresentationFromInput(graph_Layout); this->view->SetLayoutStrategy("Pass Through"); this->view->ScaledGlyphsOn(); this->view->SetScalingArrayName("Scales1"); this->view->ColorVerticesOn(); this->view->SetVertexColorArrayName("Color1"); vtkRenderedGraphRepresentation::SafeDownCast(this->view->GetRepresentation()) ->SetGlyphType(vtkGraphToGlyphs::CIRCLE); this->theme = vtkSmartPointer<vtkViewTheme>::New(); this->theme->SetPointLookupTable(vetexlut); vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New(); verts->SetNumberOfCells(1); vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New(); orient->SetNumberOfComponents(1); orient->SetName("orientation"); vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New(); label->SetNumberOfComponents(1); label->SetName("label"); for(int i=0; i<max_table_values;i++) { verts->InsertNextCell(1); verts->InsertCellPoint(i); } for(int i = 0; i < this->num_samples; i++) { vtkVariant v = i; label->InsertNextValue(v.ToString()); orient->InsertNextValue(0.0); } for(int i = this->num_samples; i <2*(this->num_samples)-1; i++) { label->InsertNextValue(""); orient->InsertNextValue(0.0); } for(int i = 2*(this->num_samples)-1; i <2*(this->num_samples)-1 + this->num_features; i++) { vtkIdType id = i - (2*this->num_samples-1) + 1 ; label->InsertNextValue(this->table->GetColumn(id)->GetName ()); orient->InsertNextValue(45.0); } for(int i = 2*(this->num_samples)-1 + this->num_features; i <2*(this->num_samples)-1 + 2*(this->num_features)-1; i++) { label->InsertNextValue(""); orient->InsertNextValue(0.0); } pd->SetPoints(points); pd->SetVerts(verts); pd->GetPointData()->AddArray(label); pd->GetPointData()->AddArray(orient); vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New(); hier->SetInputData(pd); hier->SetOrientationArrayName("orientation"); hier->SetLabelArrayName("label"); hier->GetTextProperty()->SetColor(1.0, 1.0, 1.0); vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New(); lmapper->SetInputConnection(hier->GetOutputPort()); vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New(); lmapper->SetRenderStrategy(strategy); lmapper->SetShapeToNone(); lmapper->SetBackgroundOpacity(0.0); lmapper->SetMargin(0); vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New(); lactor->SetMapper(lmapper); vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); rmapper->SetInputData(pd); vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New(); ractor->SetMapper(rmapper); this->view->GetRenderer()->AddActor(lactor); this->view->GetRenderer()->AddActor(ractor); this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New(); this->selectionCallback1->SetClientData(this); this->selectionCallback1->SetCallback ( SelectionCallbackFunction1); this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1); } void TrendHeatmapWindow::drawPoints3() { int max_table_values = 2*this->num_samples-1; this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); this->points = vtkSmartPointer<vtkPoints>::New(); this->v = vtkSmartPointer<vtkIdTypeArray>::New(); v->SetNumberOfValues (max_table_values); for(int i=0; i<max_table_values;i++) { v->SetValue (i,graph_Layout->AddVertex()); this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree1[i][1],this->Processed_Coordinate_Data_Tree1[i][2],this->Processed_Coordinate_Data_Tree1[i][3]); } this->graph_Layout->SetPoints(this->points); this->vertexColors = vtkSmartPointer<vtkIntArray>::New(); vertexColors->SetNumberOfComponents(1); vertexColors->SetName("Color1"); this->vetexlut = vtkSmartPointer<vtkLookupTable>::New(); vetexlut->SetNumberOfTableValues(max_table_values); for(int i=0; i<max_table_values;i++) { vetexlut->SetTableValue(i, 0.5, 0.5,0.5); } vetexlut->Build(); vtkSmartPointer<vtkFloatArray> scales1 = vtkSmartPointer<vtkFloatArray>::New(); /// scales for vertex size scales1->SetNumberOfComponents(1); scales1->SetName("Scales1"); for(int j=0; j<max_table_values;j++) { vertexColors->InsertNextValue(j); scales1->InsertNextValue(1); } this->graph_Layout->GetVertexData()->AddArray(scales1); this->graph_Layout->GetVertexData()->AddArray(vertexColors); this->view = vtkSmartPointer<vtkGraphLayoutView>::New(); this->view->AddRepresentationFromInput(graph_Layout); this->view->SetLayoutStrategy("Pass Through"); this->view->ScaledGlyphsOn(); this->view->SetScalingArrayName("Scales1"); this->view->ColorVerticesOn(); this->view->SetVertexColorArrayName("Color1"); vtkRenderedGraphRepresentation::SafeDownCast(this->view->GetRepresentation()) ->SetGlyphType(vtkGraphToGlyphs::CIRCLE); this->theme = vtkSmartPointer<vtkViewTheme>::New(); this->theme->SetPointLookupTable(vetexlut); vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New(); verts->SetNumberOfCells(1); vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New(); orient->SetNumberOfComponents(1); orient->SetName("orientation"); vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New(); label->SetNumberOfComponents(1); label->SetName("label"); vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New(); for(int i=0; i<this->num_features;i++) { pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0); } for(int i=0; i<this->num_features;i++) { verts->InsertNextCell(1); verts->InsertCellPoint(i); orient->InsertNextValue(45.0); vtkIdType id = i+1 ; label->InsertNextValue(this->table->GetColumn(id)->GetName()); } pd->SetPoints(pts); pd->SetVerts(verts); pd->GetPointData()->AddArray(label); pd->GetPointData()->AddArray(orient); vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New(); hier->SetInputData(pd); hier->SetOrientationArrayName("orientation"); hier->SetLabelArrayName("label"); hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0); vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New(); lmapper->SetInputConnection(hier->GetOutputPort()); vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New(); lmapper->SetRenderStrategy(strategy); lmapper->SetShapeToNone(); lmapper->SetBackgroundOpacity(0.0); lmapper->SetMargin(0); vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New(); lactor->SetMapper(lmapper); vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); rmapper->SetInputData(pd); vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New(); ractor->SetMapper(rmapper); this->view->GetRenderer()->AddActor(lactor); this->view->GetRenderer()->AddActor(ractor); this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New(); this->selectionCallback1->SetClientData(this); this->selectionCallback1->SetCallback (SelectionCallbackFunction1); this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1); } void TrendHeatmapWindow::drawPointsForSPD() { int max_table_values = 2 * this->num_samples-1 + this->num_features; this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); this->points = vtkSmartPointer<vtkPoints>::New(); this->v = vtkSmartPointer<vtkIdTypeArray>::New(); v->SetNumberOfValues (max_table_values); for( int i = 0; i < 2 * this->num_samples - 1; i++) { v->SetValue(i, graph_Layout->AddVertex()); this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree1[i][1],this->Processed_Coordinate_Data_Tree1[i][2],this->Processed_Coordinate_Data_Tree1[i][3]); } for( int i = 0; i < this->num_features; i++) { v->SetValue(i + 2 * this->num_samples - 1, graph_Layout->AddVertex()); this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1],this->Processed_Coordinate_Data_Tree2[i][2],this->Processed_Coordinate_Data_Tree2[i][3]); } this->graph_Layout->SetPoints(this->points); this->vertexColors = vtkSmartPointer<vtkIntArray>::New(); vertexColors->SetNumberOfComponents(1); vertexColors->SetName("Color1"); this->vetexlut = vtkSmartPointer<vtkLookupTable>::New(); vetexlut->SetNumberOfTableValues(max_table_values); for(int i=0; i<max_table_values;i++) { vetexlut->SetTableValue(i, 0.5, 0.5,0.5); } vetexlut->Build(); vtkSmartPointer<vtkFloatArray> scales1 = vtkSmartPointer<vtkFloatArray>::New(); /// scales for vertex size scales1->SetNumberOfComponents(1); scales1->SetName("Scales1"); for(int j=0; j<max_table_values;j++) { vertexColors->InsertNextValue(j); scales1->InsertNextValue(1); } this->graph_Layout->GetVertexData()->AddArray(scales1); this->graph_Layout->GetVertexData()->AddArray(vertexColors); this->view = vtkSmartPointer<vtkGraphLayoutView>::New(); this->view->AddRepresentationFromInput(graph_Layout); this->view->SetLayoutStrategy("Pass Through"); this->view->ScaledGlyphsOn(); this->view->SetScalingArrayName("Scales1"); this->view->ColorVerticesOn(); this->view->SetVertexColorArrayName("Color1"); vtkRenderedGraphRepresentation::SafeDownCast(this->view->GetRepresentation()) ->SetGlyphType(vtkGraphToGlyphs::CIRCLE); this->theme = vtkSmartPointer<vtkViewTheme>::New(); this->theme->SetPointLookupTable(vetexlut); vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New(); verts->SetNumberOfCells(1); vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New(); orient->SetNumberOfComponents(1); orient->SetName("orientation"); vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New(); label->SetNumberOfComponents(1); label->SetName("label"); vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New(); for(int i=0; i<this->num_features;i++) { pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0); } bool bplus = true; if(this->num_features == table->GetNumberOfColumns()) { bplus = false; } for(int i=0; i<this->num_features;i++) { verts->InsertNextCell(1); verts->InsertCellPoint(i); orient->InsertNextValue(45.0); if(bplus) { label->InsertNextValue(this->table->GetColumn(i+1)->GetName()); } else { label->InsertNextValue(this->table->GetColumn(i)->GetName()); } } pd->SetPoints(pts); pd->SetVerts(verts); pd->GetPointData()->AddArray(label); pd->GetPointData()->AddArray(orient); vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New(); hier->SetInputData(pd); hier->SetOrientationArrayName("orientation"); hier->SetLabelArrayName("label"); hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0); vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New(); lmapper->SetInputConnection(hier->GetOutputPort()); vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New(); lmapper->SetRenderStrategy(strategy); lmapper->SetShapeToNone(); lmapper->SetBackgroundOpacity(0.0); lmapper->SetMargin(0); vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New(); lactor->SetMapper(lmapper); vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); rmapper->SetInputData(pd); vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New(); ractor->SetMapper(rmapper); this->view->GetRenderer()->AddActor(lactor); this->view->GetRenderer()->AddActor(ractor); this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New(); this->selectionCallback1->SetClientData(this); this->selectionCallback1->SetCallback (SelectionCallbackFunctionForSPD); this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1); } void TrendHeatmapWindow::drawPointsForOrderHeatmap() { this->view = vtkSmartPointer<vtkGraphLayoutView>::New(); this->theme = vtkSmartPointer<vtkViewTheme>::New(); vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New(); verts->SetNumberOfCells(1); vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New(); orient->SetNumberOfComponents(1); orient->SetName("orientation"); vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New(); label->SetNumberOfComponents(1); label->SetName("label"); vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New(); for(int i=0; i<this->num_features;i++) { pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0); } for(int i=0; i<this->num_features;i++) { verts->InsertNextCell(1); verts->InsertCellPoint(i); orient->InsertNextValue(45.0); vtkIdType id = i+1 ; label->InsertNextValue(this->table->GetColumn(id)->GetName()); } pd->SetPoints(pts); pd->SetVerts(verts); pd->GetPointData()->AddArray(label); pd->GetPointData()->AddArray(orient); vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New(); hier->SetInputData(pd); hier->SetOrientationArrayName("orientation"); hier->SetLabelArrayName("label"); hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0); vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New(); lmapper->SetInputConnection(hier->GetOutputPort()); vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New(); lmapper->SetRenderStrategy(strategy); lmapper->SetShapeToNone(); lmapper->SetBackgroundOpacity(0.0); lmapper->SetMargin(0); vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New(); lactor->SetMapper(lmapper); vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); rmapper->SetInputData(pd); vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New(); ractor->SetMapper(rmapper); this->view->GetRenderer()->AddActor(lactor); this->view->GetRenderer()->AddActor(ractor); //this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New(); //this->selectionCallback1->SetClientData(this); //this->selectionCallback1->SetCallback ( SelectionCallbackFunctionForSPD); //this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1); } void TrendHeatmapWindow::SelectionCallbackFunction(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ) { vtkAnnotationLink* annotationLink = static_cast<vtkAnnotationLink*>(caller); vtkSelection* selection = annotationLink->GetCurrentSelection(); TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData; vtkSelectionNode* vertices = NULL; vtkSelectionNode* edges = NULL; vtkSelectionNode* cells = NULL; if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX) { vertices = selection->GetNode(0); } else if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::EDGE) { edges = selection->GetNode(0); } if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX) { vertices = selection->GetNode(1); } else if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::EDGE) { edges = selection->GetNode(1); } if( vertices != NULL) { vtkIdTypeArray* vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList()); std::set<long int> IDs; if(vertexList->GetNumberOfTuples() > 0) { for( vtkIdType i = 0; i < vertexList->GetNumberOfTuples(); i++) { long int value = vertexList->GetValue(i); IDs.insert(value); } } try { heatmapWin->SetdenSelectedIds1( IDs, false); } catch(...) { cout<<"SetdenSelectedIds1 failed, please try again !"<<endl; } } } void TrendHeatmapWindow::SelectionCallbackFunction1(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ) { vtkAnnotationLink* annotationLink = static_cast<vtkAnnotationLink*>(caller); vtkSelection* selection = annotationLink->GetCurrentSelection(); TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData; vtkSelectionNode* vertices = NULL; vtkSelectionNode* edges = NULL; vtkSelectionNode* cells = NULL; if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX) { vertices = selection->GetNode(0); } else if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::EDGE) { edges = selection->GetNode(0); } if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX) { vertices = selection->GetNode(1); } else if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::EDGE) { edges = selection->GetNode(1); } if( vertices != NULL) { vtkIdTypeArray* vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList()); std::set<long int> IDs; if(vertexList->GetNumberOfTuples() > 0) { for( vtkIdType i = 0; i < vertexList->GetNumberOfTuples(); i++) { long int value = vertexList->GetValue(i); IDs.insert(value); } } try { heatmapWin->SetdenSelectedIds1( IDs, true); } catch(...) { cout<<"SetdenSelectedIds1 failed, please try again !"<<endl; } } } void TrendHeatmapWindow::SelectionCallbackFunction2(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ) { TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData; int* pos = heatmapWin->view->GetInteractor()->GetEventPosition(); vtkCellPicker *cell_picker = (vtkCellPicker *)heatmapWin->view->GetInteractor()->GetPicker(); cell_picker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer()); double* worldPosition = cell_picker->GetPickPosition(); if((worldPosition[0]<=0.5) && (worldPosition[0]>=-0.5) && (worldPosition[1]<=0.5) && (worldPosition[0]>=-0.5)) { vtkSmartPointer<vtkCellPicker> cellpicker = vtkSmartPointer<vtkCellPicker>::New(); cellpicker->SetTolerance(0.0005); // Pick from this location. cellpicker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer()); double* worldPosition = cellpicker->GetPickPosition(); if(cellpicker->GetCellId() != -1) heatmapWin->id1 = cellpicker->GetCellId(); } if(worldPosition[0]<-0.5) { std::cout<<"world position: "<<worldPosition[0] <<endl; std::cout<<"rescaled value: "<< - ( worldPosition[0] + 0.5) <<endl; heatmapWin->addDragLineforSPD(worldPosition); } } void TrendHeatmapWindow::SelectionCallbackFunction3(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ) { TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData; int* pos = heatmapWin->view->GetInteractor()->GetEventPosition(); vtkCellPicker *cell_picker = (vtkCellPicker *)heatmapWin->view->GetInteractor()->GetPicker(); // Pick from this location. cell_picker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer()); double* worldPosition = cell_picker->GetPickPosition(); if((worldPosition[0]<=0.5) && (worldPosition[0]>=-0.5) && (worldPosition[1]<=0.5) && (worldPosition[0]>=-0.5)) { vtkSmartPointer<vtkCellPicker> cellpicker = vtkSmartPointer<vtkCellPicker>::New(); cellpicker->SetTolerance(0.0005); // Pick from this location. cellpicker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer()); double* worldPosition = cellpicker->GetPickPosition(); if(cellpicker->GetCellId() != -1) { try { heatmapWin->id2 = cellpicker->GetCellId(); heatmapWin->ids = vtkSmartPointer<vtkIdTypeArray>::New(); heatmapWin->ids->SetNumberOfComponents(1); heatmapWin->computeselectedcells(); heatmapWin->setselectedCellIds(); emit heatmapWin->SelChanged(); } catch(...) { cout<<"SelectionCallbackFunction3 failed, please try again !"<<endl; } } } } void TrendHeatmapWindow::HandleKeyPress(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ) { /*TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData; char key = heatmapWin->view->GetInteractor()->GetKeyCode(); int size = 0; switch (key) { case 'c': heatmapWin->continueselect = true; break; case 'i': heatmapWin->intersectionselect = true; break; case 'r': heatmapWin->continueselect = false; heatmapWin->intersectionselect = false; break; case 'd': size = heatmapWin->Selection->getSelections().size(); if( size > 0) { std::cout<< size<< " items deleted! Please rerun STrenD analysis!"<<endl; heatmapWin->Selection->DeleteCurrentSelectionInTable(); } else { std::cout<< "No items have been selected!"<<endl; } break; default: break; }*/ } void TrendHeatmapWindow::SetdenSelectedIds1(std::set<long int>& IDs, bool bfirst) { std::set<long int> selectedIDs1; std::set<long int> selectedIDs2; std::set<long int>::iterator it; long int id; if(continueselect == false) { if(this->denResetflag1 == 1) { for(int i = 0; i<this->dencolors1->GetSize() ; i++) this->dencolors1->SetValue(i, 0); denlinesPolyData1->Modified(); //denlinesPolyData1->Update(); denmapper1->Modified(); denmapper1->Update(); denactor1->Modified(); } if(this->denResetflag2 == 1) { for(int i = 0; i<this->dencolors2->GetSize() ; i++) this->dencolors2->SetValue(i, 0); denlinesPolyData2->Modified(); //denlinesPolyData2->Update(); denmapper2->Modified(); denmapper2->Update(); denactor2->Modified(); } } if( bfirst) { if( IDs.size() > 0) { for( it = IDs.begin(); it != IDs.end(); it++ ) { id = *it; //cout<<"id ====="<<id<<endl; if(id < 2*this->num_samples-1) { reselectIds1(selectedIDs1, id); } else { try { reselectIds2(selectedIDs2, id - (2*this->num_samples-1)); } catch(...) { cout<<"reselectIds2 failed, please try again!"<<endl; } } } } } else { if( IDs.size() > 0) { for( it = IDs.begin(); it != IDs.end(); it++ ) { id = *it; if(id < 2 * this->num_features - 1) { reselectIds2(selectedIDs2, id); } } } } if(selectedIDs1.size() > 0) { for(int i = 0; i<this->num_features; i++) { selectedIDs2.insert(i); } denmapper1->ScalarVisibilityOn(); denlinesPolyData1->Modified(); //denlinesPolyData1->Update(); denmapper1->Modified(); denmapper1->Update(); denactor1->Modified(); this->view->Render(); this->denResetflag1 = 1; if(intersectionselect == true) this->interselectedIDs = selectedIDs1; try { //cout<<"set select============="<<endl; this->Selection2->select(selectedIDs2); this->Selection->select(selectedIDs1); } catch(...) { cout<<"Setcelected id after reselect failed, please try again!"<<endl; } } else if(selectedIDs2.size() > 0) { this->Selection2->select(selectedIDs2); if(intersectionselect == false) { for(int i = 0; i<this->num_samples; i++) selectedIDs1.insert( indMapFromIndToVertex[i]); //cout<<"set select============="<<endl; this->Selection->select(selectedIDs1); } else { //cout<<"set select============="<<endl; this->Selection->select(interselectedIDs); } denmapper2->ScalarVisibilityOn(); denlinesPolyData2->Modified(); //denlinesPolyData2->Update(); denmapper2->Modified(); denmapper2->Update(); denactor2->Modified(); this->view->Render(); this->denResetflag2 = 1; } else { this->Selection2->clear(); //cout<<"set select============="<<endl; this->Selection->clear(); } } void TrendHeatmapWindow::reselectIds1(std::set<long int>& selectedIDs, long int id) { if(id < this->num_samples) { selectedIDs.insert( indMapFromIndToVertex[id]); } else { this->dencolors1->SetValue((id - this->num_samples)*9, 153); this->dencolors1->SetValue((id - this->num_samples)*9 + 1, 50); this->dencolors1->SetValue((id - this->num_samples)*9 + 2, 204); this->dencolors1->SetValue((id - this->num_samples)*9 + 3, 153); this->dencolors1->SetValue((id - this->num_samples)*9 + 4, 50); this->dencolors1->SetValue((id - this->num_samples)*9 + 5, 204); this->dencolors1->SetValue((id - this->num_samples)*9 + 6, 153); this->dencolors1->SetValue((id - this->num_samples)*9 + 7, 50); this->dencolors1->SetValue((id - this->num_samples)*9 + 8, 204); this->reselectIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][0]); this->reselectIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][1]); } } void TrendHeatmapWindow::reselectSPDIds1(std::set<long int>& selectedIDs, long int id) { if(id < this->num_samples) { for( int i = 0; i < indSPDMapFromIndToVertex[id].size(); i++) { selectedIDs.insert( indSPDMapFromIndToVertex[id][i]); } } else { this->dencolors1->SetValue((id - this->num_samples)*9, 153); this->dencolors1->SetValue((id - this->num_samples)*9 + 1, 50); this->dencolors1->SetValue((id - this->num_samples)*9 + 2, 204); this->dencolors1->SetValue((id - this->num_samples)*9 + 3, 153); this->dencolors1->SetValue((id - this->num_samples)*9 + 4, 50); this->dencolors1->SetValue((id - this->num_samples)*9 + 5, 204); this->dencolors1->SetValue((id - this->num_samples)*9 + 6, 153); this->dencolors1->SetValue((id - this->num_samples)*9 + 7, 50); this->dencolors1->SetValue((id - this->num_samples)*9 + 8, 204); this->reselectSPDIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][0]); this->reselectSPDIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][1]); } } void TrendHeatmapWindow::reselectIds2(std::set<long int>& selectedIDs2, long int id) { if(id < this->num_features) { selectedIDs2.insert( id); } else { this->dencolors2->SetValue((id - this->num_features)*9, 153); this->dencolors2->SetValue((id - this->num_features)*9 + 1, 50); this->dencolors2->SetValue((id - this->num_features)*9 + 2, 204); this->dencolors2->SetValue((id - this->num_features)*9 + 3, 153); this->dencolors2->SetValue((id - this->num_features)*9 + 4, 50); this->dencolors2->SetValue((id - this->num_features)*9 + 5, 204); this->dencolors2->SetValue((id - this->num_features)*9 + 6, 153); this->dencolors2->SetValue((id - this->num_features)*9 + 7, 50); this->dencolors2->SetValue((id - this->num_features)*9 + 8, 204); this->reselectIds2(selectedIDs2, connect_Data_Tree2[columnMapForTreeData.find(id)->second][0]); this->reselectIds2(selectedIDs2, connect_Data_Tree2[columnMapForTreeData.find(id)->second][1]); } } void TrendHeatmapWindow::computeselectedcells() { this->r1 = id1/this->num_features; this->r2 = id2/this->num_features; this->c1 = id1%this->num_features; this->c2 = id2%this->num_features; cout<<r1<<endl; cout<<r2<<endl; for(int i = 0; i <= r1 - r2; i++) { for(int j = 0; j <= c2 - c1; j++) { ids->InsertNextValue(id2 - j + this->num_features*i); } } } void TrendHeatmapWindow::setselectedCellIds() { std::set<long int> selectedIDs1; std::set<long int> selectedIDs2; if(continueselect == false) { if(this->denResetflag1 == 1) { for(int i = 0; i<this->dencolors1->GetSize() ; i++) this->dencolors1->SetValue(i, 0); denmapper1->ScalarVisibilityOn(); denlinesPolyData1->Modified(); //denlinesPolyData1->Update(); denmapper1->Modified(); denmapper1->Update(); denactor1->Modified(); this->view->Render(); this->denResetflag1 = 0; } if(this->denResetflag2 == 1) { for(int i = 0; i<this->dencolors2->GetSize() ; i++) this->dencolors2->SetValue(i, 0); denmapper2->ScalarVisibilityOn(); denlinesPolyData2->Modified(); //denlinesPolyData2->Update(); denmapper2->Modified(); denmapper2->Update(); denactor2->Modified(); this->view->Render(); this->denResetflag2 = 0; } } for(int i = r2; i<=r1; i++) { selectedIDs1.insert( indMapFromIndToVertex[ this->Optimal_Leaf_Order1[i]]); } for(int j = c1; j<=c2; j++) { selectedIDs2.insert(this->Optimal_Leaf_Order2[j]); } try { this->Selection2->select(selectedIDs2); this->Selection->select(selectedIDs1); } catch(...) { cout<<"setselectedCellIds failed, please try again!"<<endl; } } void TrendHeatmapWindow::GetSelRowCol(int &r1, int &c1, int &r2, int &c2) { r1 = this->r1; r2 = this->r2; c1 = this->c1; c2 = this->c2; } void TrendHeatmapWindow::SetSelRowCol(int r1, int c1, int r2, int c2) { this->r1 = r1; this->r2 = r2; this->c1 = c1; this->c2 = c2; setselectedCellIds(); } void TrendHeatmapWindow::SetSPDInteractStyle() { this->theme->SetCellValueRange(0, this->num_samples*this->num_features - 1); this->theme->SetSelectedCellColor(1,0,1); this->theme->SetSelectedPointColor(1,0,1); this->view->ApplyViewTheme(theme); this->myCellPicker = vtkSmartPointer<vtkCellPicker>::New(); this->view->GetInteractor()->SetPicker(this->myCellPicker); this->myCellPicker->SetTolerance(0.004); vtkSmartPointer<vtkCallbackCommand> selectionCallback2 =vtkSmartPointer<vtkCallbackCommand>::New(); selectionCallback2->SetClientData(this); selectionCallback2->SetCallback(SelectionCallbackFunction2); this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonPressEvent); this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonReleaseEvent); this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyPressEvent); this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyReleaseEvent); this->view->GetInteractor()->AddObserver(vtkCommand::RightButtonReleaseEvent, selectionCallback2); this->mainQTRenderWidget.SetRenderWindow(view->GetRenderWindow()); this->mainQTRenderWidget.resize(600, 600); this->mainQTRenderWidget.show(); } void TrendHeatmapWindow::showGraphforSPD( int selCol, int unselCol, bool bprogressionHeatmap) { if(bprogressionHeatmap) { drawPointsForOrderHeatmap(); } else { drawPointsForSPD(); } this->dragLineFlag = false; this->aPlane = vtkSmartPointer<vtkPlaneSource>::New(); this->aPlane->SetXResolution(this->num_features); this->aPlane->SetYResolution(this->num_samples); this->cellData = vtkSmartPointer<vtkFloatArray>::New(); int index = 0; for (int i = 0; i < this->num_samples; i++) { for(int j = 0; j < this->num_features; j++) { cellData->InsertNextValue(index++); } } this->celllut = vtkSmartPointer<vtkLookupTable>::New(); this->celllut->SetNumberOfTableValues(this->num_samples*this->num_features); this->celllut->SetTableRange(0, this->num_samples*this->num_features - 1); this->celllut->Build(); int k = 0; for(int i = 0; i < this->num_samples; i++) { for(int j = 0; j < this->num_features; j++) { rgb rgb = GetRGBValue( mapdata[num_samples - i - 1][j]); celllut->SetTableValue(k++, rgb.r, rgb.g, rgb.b); } } this->aPlane->Update(); this->aPlane->GetOutput()->GetCellData()->SetScalars(cellData); this->mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); this->mapper->SetInputConnection(aPlane->GetOutputPort()); this->mapper->SetScalarRange(0, this->num_samples*this->num_features - 1); this->mapper->SetLookupTable(celllut); this->actor = vtkSmartPointer<vtkActor>::New(); this->actor->SetMapper(mapper); vtkSmartPointer<vtkLookupTable> scalarbarLut = vtkSmartPointer<vtkLookupTable>::New(); scalarbarLut->SetTableRange (-1, 1); scalarbarLut->SetNumberOfTableValues(COLOR_MAP_SIZE); for(int index = 0; index<COLOR_MAP_SIZE;index++) { rgb rgbscalar = COLORMAP[index]; scalarbarLut->SetTableValue(index, rgbscalar.r, rgbscalar.g, rgbscalar.b); } scalarbarLut->Build(); vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar->SetLookupTable(scalarbarLut); scalarBar->SetTitle("Color Map"); scalarBar->SetNumberOfLabels(10); scalarBar->GetTitleTextProperty()->SetColor(0,0,0); scalarBar->GetTitleTextProperty()->SetFontSize (10); scalarBar->GetLabelTextProperty()->SetColor(0,0,0); scalarBar->GetTitleTextProperty()->SetFontSize (10); scalarBar->SetMaximumHeightInPixels(1000); scalarBar->SetMaximumWidthInPixels(100); this->view->GetRenderer()->AddActor(actor); this->view->GetRenderer()->AddActor2D(scalarBar); this->SetSPDInteractStyle(); this->view->GetRenderer()->GradientBackgroundOff(); this->view->GetRenderer()->SetBackground(1,1,1); if( selCol > 0 || unselCol > 0) { double p1[3]; double p2[3]; double p3[3]; double length = 0.3; double angle = pi / 4; p1[0]= -0.5 + 1.0 / (selCol + unselCol) * selCol; p1[1]= -0.5; p1[2]=0; p2[0]= p1[0]; p2[1]=0.5; p2[2]=0; p3[0] = p2[0] + length * cos( angle); p3[1] = p2[1] + length * sin( angle); p3[2] = 0; vtkSmartPointer<vtkLineSource> lineSource = vtkSmartPointer<vtkLineSource>::New(); vtkSmartPointer<vtkLineSource> lineSourceForText = vtkSmartPointer<vtkLineSource>::New(); vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); vtkSmartPointer<vtkPolyDataMapper> lineMapperForText = vtkSmartPointer<vtkPolyDataMapper>::New(); vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); vtkSmartPointer<vtkActor> lineActorForText = vtkSmartPointer<vtkActor>::New(); lineSource->SetPoint1(p1); lineSource->SetPoint2(p2); lineMapper->SetInputConnection(lineSource->GetOutputPort()); lineActor->SetMapper(lineMapper); lineActor->GetProperty()->SetColor(1,1,1); lineActor->GetProperty()->SetLineWidth(2); lineSourceForText->SetPoint1(p2); lineSourceForText->SetPoint2(p3); lineMapperForText->SetInputConnection(lineSourceForText->GetOutputPort()); lineActorForText->SetMapper(lineMapperForText); lineActorForText->GetProperty()->SetColor(1,0,0); lineActorForText->GetProperty()->SetLineWidth(2); this->view->GetRenderer()->AddActor(lineActor); this->view->GetRenderer()->AddActor(lineActorForText); } try { if( bprogressionHeatmap == false) { if(this->clusflag == true) this->showDendrogram1(); else { this->showDendrogram1(); this->showDendrogram2(); } } } catch(...) { cout<<"Draw dendrogram failed ! Please try again!"<<endl; } this->view->Render(); this->view->GetInteractor()->Start(); } void TrendHeatmapWindow::addDragLineforSPD(double* worldPosition) { if(this->dragLineFlag) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(dragLineActor); double p1[3]; double p2[3]; p1[0]=worldPosition[0]; p1[1]=-0.75; p1[2]=0; p2[0]=worldPosition[0]; p2[1]=0.75; p2[2]=0; dragLineSource = vtkSmartPointer<vtkLineSource>::New(); dragLineSource->SetPoint1(p1); dragLineSource->SetPoint2(p2); dragLineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); dragLineMapper->SetInputConnection(dragLineSource->GetOutputPort()); dragLineActor = vtkSmartPointer<vtkActor>::New(); dragLineActor->SetMapper(dragLineMapper); dragLineActor->GetProperty()->SetColor(0.5,0.7,0); dragLineActor->GetProperty()->SetLineWidth(1.5); dragLineActor->DragableOn(); this->view->GetRenderer()->AddActor(dragLineActor); this->dragLineFlag = true; this->view->Render(); this->selectClustersforSPD(worldPosition); } void TrendHeatmapWindow::selectClustersforSPD(double* worldPosition) { reselectedClusterSPD.clear(); clusterNumVec.set_size(parentIndex.size()); for( int i = 0; i < clusterNumVec.size(); i++) { clusterNumVec[i] = 0; } std::set<long int> selectedClusterSPD; for( long int index = 0; index < 2 * this->num_samples - 1; index++) { if(worldPosition[0] > Processed_Coordinate_Data_Tree1[index][1]) { selectedClusterSPD.insert(index); } } std::set<long int>::iterator it; for(it = selectedClusterSPD.begin(); it != selectedClusterSPD.end(); it++) { long int id = *it; long int id1 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][0]; long int id2 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][1]; std::set<long int>::iterator it1 = selectedClusterSPD.find(id1); std::set<long int>::iterator it2 = selectedClusterSPD.find(id2); unsigned char num = 0; if( it1 == selectedClusterSPD.end() && it2 != selectedClusterSPD.end() || it2 == selectedClusterSPD.end() && it1 != selectedClusterSPD.end()) { num = 1; } else if( it1 == selectedClusterSPD.end() && it2 == selectedClusterSPD.end()) { num = 2; } else { num = 0; } if( parentIndex.size() > 0) { if( id <= parentIndex[0]) { clusterNumVec[0] += num; } else { for( int j = 0; j < parentIndex.size() - 1; j++) { if( id > parentIndex[j] && id <= parentIndex[j+1]) { clusterNumVec[j+1] += num; break; } } } } } for( int i = 0; i < clusterNumVec.size(); i++) { if( clusterNumVec[i] == 0) { clusterNumVec[i] = 1; } } this->reselectClustersforSPD(selectedClusterSPD); } void TrendHeatmapWindow::GetSubTreeClusterNum(std::vector<int> &clusterNum) { clusterNum.resize( clusterNumVec.size()); for( int i = 0; i < clusterNumVec.size(); i++) { clusterNum[i] = clusterNumVec[i]; } } void TrendHeatmapWindow::reselectClustersforSPD(std::set<long int>& selectedClusterSPD) { std::set<long int>::iterator it; int clusternumber = 0; for(it = selectedClusterSPD.begin(); it != selectedClusterSPD.end(); it++) { long int id = *it; long int id1 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][0]; long int id2 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][1]; std::set<long int>::iterator it1 = selectedClusterSPD.find(id1); std::set<long int>::iterator it2 = selectedClusterSPD.find(id2); if(it1 == selectedClusterSPD.end()) { reselectedClusterSPD.insert(id1); clusternumber++; } if(it2 == selectedClusterSPD.end()) { reselectedClusterSPD.insert(id2); clusternumber++; } } //cout<<"cluster number is "<<clusternumber<<endl; std::vector< std::vector< long int> > clusIndex; std::vector< std::vector< long int> > sampleIndex; for(it = reselectedClusterSPD.begin(); it != reselectedClusterSPD.end(); it++) { std::vector<long int> sampleIdsVec; std::set<long int> clusIdsforSPD; std::vector<long int> clusIdsVec; this->reselectIdsforSPD(*it, &clusIdsforSPD); for( int i = 0; i < this->num_samples; i++) { if(clusIdsforSPD.find(Optimal_Leaf_Order1[i]) != clusIdsforSPD.end()) { for( int k = 0; k < clusIdsforSPD.size(); k++) { int ind = Optimal_Leaf_Order1[i + k]; clusIdsVec.push_back(ind); for( int j = 0; j < indSPDMapFromIndToVertex[ind].size(); j++) { sampleIdsVec.push_back( indSPDMapFromIndToVertex[ind][j]); } } break; } } sampleIndex.push_back(sampleIdsVec); clusIndex.push_back(clusIdsVec); } this->Selection->SetClusterIndex(clusIndex); this->Selection->SetSampleIndex(sampleIndex); } vtkSmartPointer<vtkTable> TrendHeatmapWindow::GetTreeTable() { std::vector<std::string> headers; headers.push_back("node1"); headers.push_back("node2"); headers.push_back("weight"); vtkSmartPointer<vtkTable> table = vtkSmartPointer<vtkTable>::New(); for(int i = 0; i < headers.size(); i++) { vtkSmartPointer<vtkDoubleArray> column = vtkSmartPointer<vtkDoubleArray>::New(); column->SetName( headers[i].c_str()); table->AddColumn(column); } /// ordering the tree by weight std::multimap< double, int> treeMap; for( int i = 0; i < this->table->GetNumberOfRows() - 1; i++) { treeMap.insert(std::pair<double, int>(ftreedata[i][2], i)); } std::vector<int> orderInd(this->table->GetNumberOfRows() - 1); std::multimap< double, int>::iterator treeMapIter; int mt = 0; for(treeMapIter = treeMap.begin(); treeMapIter != treeMap.end(); treeMapIter++) { orderInd[mt++] = treeMapIter->second; } if( reselectedClusterSPD.size() > 0 && this->ftreedata) { std::set<long int>::iterator it; std::map<long int, int> idMap; int ind = 0; for(it = reselectedClusterSPD.begin(); it != reselectedClusterSPD.end(); it++) { idMap.insert(std::pair<long int, int>(*it, ind++)); } for( int i = this->table->GetNumberOfRows() - reselectedClusterSPD.size(); i < this->table->GetNumberOfRows() - 1; i++) { vtkSmartPointer<vtkVariantArray> DataRow = vtkSmartPointer<vtkVariantArray>::New(); int pos = orderInd[i]; int node1 = ftreedata[pos][0]; int node2 = ftreedata[pos][1]; int parent = ftreedata[pos][3]; DataRow->InsertNextValue(idMap[ node1]); DataRow->InsertNextValue(idMap[ node2]); DataRow->InsertNextValue(pow(this->ftreedata[i][2], POWER_PARAM)); table->InsertNextRow(DataRow); idMap.insert(std::pair<long int, int>(parent, idMap[ node2])); } } //ftk::SaveTable("TreeTable.txt", table); return table; } void TrendHeatmapWindow::reselectIdsforSPD(long int id, std::set<long int> *clusidforSPD) { if(id < this->num_samples) { //cout<<id<<"\t"; if( clusidforSPD != NULL) { clusidforSPD->insert(id); } } else { this->reselectIdsforSPD(connect_Data_Tree1[rowMapForTreeData.find(id)->second][0], clusidforSPD); this->reselectIdsforSPD(connect_Data_Tree1[rowMapForTreeData.find(id)->second][1], clusidforSPD); } } void TrendHeatmapWindow::setModelsforSPD(vtkSmartPointer<vtkTable> table, ObjectSelection * sels, std::vector< int> selOrder, std::vector< int> unselOrder, std::map< int, int> *indexCluster, std::vector<int> *component, int numOfComponenets, vnl_matrix<double> *subTreeDistance, ObjectSelection * sels2) { this->table = table; this->indMapFromVertexToInd.clear(); this->indMapFromIndToVertex.clear(); std::cout<< "TrendHeatmapWindow input table: "<<this->table->GetNumberOfRows()<<"\t"<<this->table->GetNumberOfColumns()<<std::endl; if( indexCluster) { indMapFromVertexToInd = *indexCluster; indSPDMapFromIndToVertex.resize( table->GetNumberOfRows()); std::map<int, int>::iterator iter; for( iter = indMapFromVertexToInd.begin(); iter != indMapFromVertexToInd.end(); iter++) { std::pair<int, int> pair = *iter; indSPDMapFromIndToVertex[ pair.second].push_back( pair.first); } } if(!sels) this->Selection = new ObjectSelection(); else this->Selection = sels; if(!sels2) this->Selection2 = new ObjectSelection(); else this->Selection2 = sels2; if(component) { connectedComponent = *component; } selectedFeatureIDs.clear(); for( int i = 0; i < selOrder.size(); i++) { selectedFeatureIDs.insert( selOrder[i]); } std::cout<< "TrendHeatmapWindow input selected features: "<<selectedFeatureIDs.size()<<std::endl; connect(Selection, SIGNAL(changed()), this, SLOT(GetSelecectedIDsForSPD())); if( subTreeDistance != NULL && numOfComponenets >= 1) { this->runClusforSPD(selOrder, unselOrder, numOfComponenets, *subTreeDistance); } else { this->runClusforSPD(selOrder, unselOrder); } } void TrendHeatmapWindow::setModelsforSPD(vtkSmartPointer<vtkTable> table, ObjectSelection * sels, std::vector< int> sampleOrder, std::vector< int> selOrder, std::vector< int> unselOrder, std::map< int, int> *indexCluster, ObjectSelection * sels2) { this->table = table; this->indMapFromVertexToInd.clear(); this->indMapFromIndToVertex.clear(); if( indexCluster) { indMapFromVertexToInd = *indexCluster; indSPDMapFromIndToVertex.resize( table->GetNumberOfRows()); std::map<int, int>::iterator iter; for( iter = indMapFromVertexToInd.begin(); iter != indMapFromVertexToInd.end(); iter++) { std::pair<int, int> pair = *iter; indSPDMapFromIndToVertex[ pair.second].push_back( pair.first); } } if(!sels) this->Selection = new ObjectSelection(); else this->Selection = sels; if(!sels2) this->Selection2 = new ObjectSelection(); else this->Selection2 = sels2; selectedFeatureIDs.clear(); for( int i = 0; i < selOrder.size(); i++) { selectedFeatureIDs.insert( selOrder[i]); } //connect(Selection, SIGNAL(thresChanged()), this, SLOT(GetSelecectedIDsforSPD())); connect(Selection, SIGNAL(changed()), this, SLOT(GetSelecectedIDsForSPD())); this->runClusforSPD( sampleOrder, selOrder, unselOrder); } void TrendHeatmapWindow::runClusforSPD(std::vector< int> selOrder, std::vector< int> unselOrder) { this->clusflag = true; clock_t start_time = clock(); double** datas = new double*[this->table->GetNumberOfRows()]; double** datasforclus = new double*[this->table->GetNumberOfRows()]; for (int i = 0; i < this->table->GetNumberOfRows(); i++) { datas[i] = new double[this->table->GetNumberOfColumns() - 1]; datasforclus[i] = new double[selOrder.size()]; for(int j = 1; j < this->table->GetNumberOfColumns(); j++) { vtkVariant temp = this->table->GetValue(i, j); datas[i][j-1] = temp.ToDouble(); } for(int j = 0; j < selOrder.size(); j++) { int coln = selOrder[j]; datasforclus[i][j] = datas[i][coln]; } } clusclus *cc = new clusclus(datasforclus, this->table->GetNumberOfRows(), (int)selOrder.size()); cc->RunClusClus(); int featureNum = selOrder.size() + unselOrder.size(); int* optimalleaforder2 = new int[featureNum]; int counter = 0; for(int i = 0; i < selOrder.size(); i++) { optimalleaforder2[i] = selOrder[i]; counter++; } for(int i = 0; i < unselOrder.size(); i++) { optimalleaforder2[i + counter] = unselOrder[i]; } this->setDataForHeatmap( datas, cc->optimalleaforder, optimalleaforder2, this->table->GetNumberOfRows(), featureNum); this->setDataForDendrograms(cc->treedata); this->creatDataForHeatmap(POWER_PARAM); for (int i = 0; i < this->table->GetNumberOfRows(); i++) { delete datas[i]; delete datasforclus[i]; } delete datas; delete datasforclus; delete cc; std::cout << "Total time to generate progression heatmap is: " << (clock() - start_time) / (float) CLOCKS_PER_SEC << std::endl; } void TrendHeatmapWindow::runClusforSPD(std::vector< int> selOrder, std::vector< int> unselOrder, int numberofcomponents, vnl_matrix<double> &subTreeDistance) { this->clusflag = true; if(connectedComponent.size() == this->table->GetNumberOfRows()) { clock_t start_time = clock(); std::vector< std::vector<int> > graphVertex; graphVertex.resize(numberofcomponents); for( int i = 0; i < connectedComponent.size(); i++) { int n = connectedComponent[i]; graphVertex[n].push_back(i); } double** datas = new double*[this->table->GetNumberOfRows()]; for (int i = 0; i < this->table->GetNumberOfRows(); i++) { datas[i] = new double[this->table->GetNumberOfColumns() - 1]; for(int j = 1; j < this->table->GetNumberOfColumns(); j++) { vtkVariant temp = this->table->GetValue(i, j); datas[i][j-1] = temp.ToDouble(); } } std::vector< std::vector< ClusterTree> > treeVec; treeVec.resize( numberofcomponents); #pragma omp parallel for for( int i = 0; i < graphVertex.size(); i++) { double** datasforclus = new double*[graphVertex[i].size()]; for (int j = 0; j < graphVertex[i].size(); j++) { datasforclus[j] = new double[selOrder.size()]; } int index = 0; for(std::set<long int >::iterator iter = selectedFeatureIDs.begin(); iter != selectedFeatureIDs.end(); iter++) { for( int k = 0; k < graphVertex[i].size(); k++) { int ni = graphVertex[i][k]; datasforclus[k][index] = datas[ni][*iter]; } index++; } clusclus *cc = new clusclus(datasforclus, (int)graphVertex[i].size(), (int)selOrder.size()); cc->RunClusClus(); ///save the tree cc->GetTreeStructure(treeVec[i]); for (int j = 0; j < graphVertex[i].size(); j++) { delete datasforclus[j]; } delete datasforclus; delete cc; } //std::ofstream ofs("Tree.txt"); /// adjust the local tree index to fit the global tree index int clusNo = this->table->GetNumberOfRows(); double maxdis = 0; // find the maximum distance of all the tree std::vector< int> parentIndex; parentIndex.resize(treeVec.size()); for( int i = 0; i < treeVec.size(); i++) { int maxi = treeVec[i].size() + 1; //ofs<<maxi<<std::endl; parentIndex[i] = 0; for( int j = 0; j < treeVec[i].size(); j++) { ClusterTree tree = treeVec[i][j]; tree.first = tree.first < maxi ? graphVertex[i][tree.first] : tree.first - maxi + clusNo; tree.second = tree.second < maxi ? graphVertex[i][tree.second] : tree.second - maxi + clusNo; tree.parent = tree.parent < maxi ? graphVertex[i][tree.parent] : tree.parent - maxi + clusNo; treeVec[i][j] = tree; if(tree.dis > maxdis) { maxdis = tree.dis; } } clusNo += treeVec[i].size(); parentIndex[i] = clusNo - 1; } this->parentIndex = parentIndex; /// print out the tree structure //for( int i = 0; i < treeVec.size(); i++) //{ // for( int j = 0; j < treeVec[i].size(); j++) // { // ClusterTree tree = treeVec[i][j]; // ofs<< tree.first<< "\t"<< tree.second << "\t"<<tree.dis<< "\t"<< tree.parent <<std::endl; // } // ofs<< std::endl; //} /// construct the overal tree and the overal order if( maxdis <= 1e-6) { maxdis = 1; } std::vector< ClusterTree> overallTree; while(overallTree.size() < numberofcomponents - 1) { unsigned int location = subTreeDistance.arg_min(); int nrow = location / subTreeDistance.rows(); int ncol = location % subTreeDistance.rows(); if( parentIndex[nrow] != parentIndex[ncol]) { ClusterTree tree( parentIndex[nrow], parentIndex[ncol], 2 * maxdis, clusNo); overallTree.push_back(tree); subTreeDistance(ncol, nrow)= 1e9; subTreeDistance(nrow, ncol)= 1e9; int ind1 = parentIndex[nrow]; int ind2 = parentIndex[ncol]; for( int i = 0; i < parentIndex.size(); i++) { if( parentIndex[i] == ind1 || parentIndex[i] == ind2) { parentIndex[i] = clusNo; } } clusNo++; } else { subTreeDistance(ncol, nrow)= 1e9; subTreeDistance(nrow, ncol)= 1e9; } } //for( int i = 0; i < overallTree.size(); i++) //{ // ClusterTree tree = overallTree[i]; // //ofs<< tree.first<< "\t"<< tree.second << "\t"<<tree.dis<< "\t"<< tree.parent <<std::endl; //} //ofs.close(); int featureNum = selOrder.size() + unselOrder.size(); int* optimalleaforder2 = new int[featureNum]; int counter = 0; for(int i = 0; i < selOrder.size(); i++) { optimalleaforder2[i] = selOrder[i]; counter++; } for(int i = 0; i < unselOrder.size(); i++) { optimalleaforder2[i + counter] = unselOrder[i]; } if(ftreedata) { for( int i = 0; i < this->table->GetNumberOfRows() - 1; i++) { delete ftreedata[i]; } delete ftreedata; } ftreedata = new double*[ this->table->GetNumberOfRows() - 1]; int count = 0; for( int i = 0; i < treeVec.size(); i++) { for( int j = 0; j < treeVec[i].size(); j++) { ClusterTree tree = treeVec[i][j]; ftreedata[count] = new double[4]; ftreedata[count][0] = tree.first; ftreedata[count][1] = tree.second; ftreedata[count][2] = tree.dis; ftreedata[count][3] = tree.parent; count++; } } for(int i = 0; i < overallTree.size(); i++) { ClusterTree tree = overallTree[i]; ftreedata[count] = new double[4]; ftreedata[count][0] = tree.first; ftreedata[count][1] = tree.second; ftreedata[count][2] = tree.dis; ftreedata[count][3] = tree.parent; count++; } clusclus *cc1 = new clusclus(); cc1->Initialize(ftreedata, this->table->GetNumberOfRows()); cc1->GetOptimalLeafOrderD(); this->setDataForHeatmap( datas, cc1->optimalleaforder, optimalleaforder2, this->table->GetNumberOfRows(), featureNum); this->setDataForDendrograms(cc1->treedata); this->creatDataForHeatmap(POWER_PARAM); for (int i = 0; i < this->table->GetNumberOfRows(); i++) { delete datas[i]; } delete datas; std::cout << "Total time to generate progression heatmap is: " << (clock() - start_time) / (float) CLOCKS_PER_SEC << std::endl; } else { std::cout<< "Error in component array size"<<std::endl; } } void TrendHeatmapWindow::runClusforSPD(std::vector< int> sampleOrder, std::vector< int> selOrder, std::vector< int> unselOrder) { this->clusflag = true; double** datas; vtkVariant temp; int nFeature = selOrder.size() + unselOrder.size(); datas = new double*[this->table->GetNumberOfRows()]; std::cout<<this->table->GetNumberOfRows()<<endl; std::cout<<this->table->GetNumberOfColumns()<<endl; for (int i = 0; i < this->table->GetNumberOfRows(); i++) { datas[i] = new double[nFeature + 2 ]; for(int j = 1; j <= nFeature; j++) { vtkVariant temp = this->table->GetValue(i, j); datas[i][j-1] = temp.ToDouble(); } } int* optimalleaforder1 = new int[this->table->GetNumberOfRows()]; for(int i = 0; i < sampleOrder.size(); i++) { optimalleaforder1[i] = sampleOrder[i]; } int* optimalleaforder2 = new int[ nFeature]; int counter = 0; for(int i = 0; i < selOrder.size(); i++) { optimalleaforder2[i] = selOrder[i]; counter++; } for(int i = 0; i < unselOrder.size(); i++) { optimalleaforder2[i + counter] = unselOrder[i]; } this->setDataForHeatmap( datas, optimalleaforder1, optimalleaforder2, this->table->GetNumberOfRows(), nFeature); //this->setDataForDendrograms(); this->creatDataForHeatmap(POWER_PARAM); for (int i = 0; i < this->table->GetNumberOfRows(); i++) { delete datas[i]; } delete datas; } void TrendHeatmapWindow::SelectionCallbackFunctionForSPD(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData ) { vtkAnnotationLink* annotationLink = static_cast<vtkAnnotationLink*>(caller); vtkSelection* selection = annotationLink->GetCurrentSelection(); TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData; vtkSelectionNode* vertices = NULL; vtkSelectionNode* edges = NULL; vtkSelectionNode* cells = NULL; if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX) { vertices = selection->GetNode(0); } else if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::EDGE) { edges = selection->GetNode(0); } if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX) { vertices = selection->GetNode(1); } else if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::EDGE) { edges = selection->GetNode(1); } if( vertices != NULL) { vtkIdTypeArray* vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList()); std::set<long int> IDs; if(vertexList->GetNumberOfTuples() > 0) { for( vtkIdType i = 0; i < vertexList->GetNumberOfTuples(); i++) { long int value = vertexList->GetValue(i); if( value < 2 * heatmapWin->num_samples - 1) { if( heatmapWin->reselectedClusterSPD.find(value) != heatmapWin->reselectedClusterSPD.end()) { IDs.insert(value); } } else { value = value - 2 * heatmapWin->num_samples + 1; emit heatmapWin->columnToColorChanged(value); break; } } } try { heatmapWin->SetdenSelectedIdsForSPD( IDs); } catch(...) { cout<<"SetdenSelectedIds1 failed, please try again !"<<endl; } } } void TrendHeatmapWindow::SetdenSelectedIdsForSPD(std::set<long int>& IDs) { std::set<long int> selectedIDs1; std::set<long int>::iterator it; long int id; if(continueselect == false) { if(this->denResetflag1 == 1) { for(int i = 0; i<this->dencolors1->GetSize() ; i++) this->dencolors1->SetValue(i, 0); denlinesPolyData1->Modified(); //denlinesPolyData1->Update(); denmapper1->Modified(); denmapper1->Update(); denactor1->Modified(); } } if( IDs.size() > 0) { for( it = IDs.begin(); it != IDs.end(); it++ ) { id = *it; if(id < 2*this->num_samples-1) { reselectSPDIds1(selectedIDs1, id); } } } if(selectedIDs1.size() > 0) { denmapper1->ScalarVisibilityOn(); denlinesPolyData1->Modified(); //denlinesPolyData1->Update(); denmapper1->Modified(); denmapper1->Update(); denactor1->Modified(); this->view->Render(); this->denResetflag1 = 1; //std::set<long int>::iterator iter; //std::set<long int> selectedIDs; //for( iter = selectedIDs1.begin(); iter != selectedIDs1.end(); iter++) //{ // long int var = *iter; // for( int i = 0; i < indSPDMapFromIndToVertex[ var].size(); i++) // { // selectedIDs.insert( indSPDMapFromIndToVertex[ var][i]); // } //} try { this->Selection2->select(selectedFeatureIDs); this->Selection->select(selectedIDs1); } catch(...) { cout<<"Setcelected id after reselect failed, please try again!"<<endl; } } //else //{ // this->Selection2->clear(); // this->Selection->clear(); //} } void TrendHeatmapWindow::GetSelecectedIDsForSPD() { std::set<long int> selectedIDs2 = selectedFeatureIDs; std::set<long int> selectedIDs1 = this->Selection->getSelections(); std::set<long int>::iterator iter1 = selectedIDs1.begin(); std::set<long int>::iterator iter2 = selectedIDs2.begin(); vtkSmartPointer<vtkIdTypeArray> cellids = vtkSmartPointer<vtkIdTypeArray>::New(); cellids->SetNumberOfComponents(1); int num1 = selectedIDs1.size(); int num2 = selectedIDs2.size(); std::vector<int > IDs1; std::vector<int > IDs2; IDs1.resize(num1); IDs2.resize(num2); int count1 = 0; int count2 = 0; #pragma omp parallel sections { #pragma omp section while(iter1 != selectedIDs1.end()) { int index1 = *iter1; int var = indMapFromVertexToInd.find(index1)->second; int id1 = rowMapFromOriginalToReorder.find(var)->second; IDs1[count1++] = id1; iter1++; } #pragma omp section while(iter2 != selectedIDs2.end()) { int index2 = *iter2; int id2 = columnMapFromOriginalToReorder.find(index2)->second; IDs2[count2++] = id2; iter2++; } } for(int i = 0; i<num1; i++) for(int j = 0; j<num2; j++) cellids->InsertNextValue( (IDs1[i])*(this->num_features) + IDs2[j]); vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New(); selectionNode->SetFieldType(vtkSelectionNode::CELL); selectionNode->SetContentType(vtkSelectionNode::INDICES); selectionNode->SetSelectionList(cellids); vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); selection->AddNode(selectionNode); vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New(); extractSelection->SetInputData(0, this->aPlane->GetOutput()); extractSelection->SetInputData(1, selection); extractSelection->Update(); vtkSmartPointer<vtkUnstructuredGrid> selected = vtkSmartPointer<vtkUnstructuredGrid>::New(); selected->ShallowCopy(extractSelection->GetOutput()); vtkSmartPointer<vtkDataSetMapper> selectedMapper = vtkSmartPointer<vtkDataSetMapper>::New(); selectedMapper->SetInputData(selected); vtkSmartPointer<vtkActor> selectedActor = vtkSmartPointer<vtkActor>::New(); selectedActor->SetMapper(selectedMapper); selectedActor->GetProperty()->EdgeVisibilityOn(); selectedActor->GetProperty()->SetEdgeColor(1,1,1); selectedActor->GetProperty()->SetLineWidth(0.5); if(this->dragLineFlag) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(dragLineActor); try { if(continueselect == false) { if(continueselectnum > 0) { cout<<"I'm here "<<continueselectnum<<endl; for(int i = 0; i<continueselectnum + 1; i++) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor()); continueselectnum = 0; } else { if (this->removeActorflag != 0) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor()); } this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor); this->removeActorflag += 1; } else { this->continueselectnum += 1; this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor); } if(this->dragLineFlag) this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(dragLineActor); this->view->Render(); } catch(...) { cout<<"GetSelecectedIDs failed, please try it again!"<<endl; } } void TrendHeatmapWindow::closeEvent(QCloseEvent *event) { mainQTRenderWidget.close(); } void TrendHeatmapWindow::reRunClus() { double** datas; vtkVariant temp; datas = new double*[this->table->GetNumberOfRows()]; std::cout<<this->table->GetNumberOfRows()<<endl; std::cout<<this->table->GetNumberOfColumns()<<endl; for (int i = 0; i < this->table->GetNumberOfRows(); i++) { datas[i] = new double[this->table->GetNumberOfColumns() - 1 + 2 ]; } for(int i = 0; i < this->table->GetNumberOfRows(); i++) { for(int j = 1; j < this->table->GetNumberOfColumns(); j++) { temp = this->table->GetValue(i, j); datas[i][j-1] = temp.ToDouble(); } } int* optimalleaforder1 = new int[this->table->GetNumberOfRows()]; for(int i = 0;i<this->table->GetNumberOfRows(); i++) optimalleaforder1[i]=i; int* optimalleaforder2 = new int[this->table->GetNumberOfColumns() - 1]; for(int i = 0;i<this->table->GetNumberOfColumns() - 1; i++) optimalleaforder2[i]=i; this->setDataForHeatmap(datas, optimalleaforder1, optimalleaforder2,this->table->GetNumberOfRows(), this->table->GetNumberOfColumns() - 1); this->creatDataForHeatmap(POWER_PARAM); } void TrendHeatmapWindow::showGraphforNe() { this->drawPointsforNe(); this->aPlane = vtkSmartPointer<vtkPlaneSource>::New(); this->aPlane->SetXResolution(this->num_features); this->aPlane->SetYResolution(this->num_samples); this->cellData = vtkSmartPointer<vtkFloatArray>::New(); int index = 0; for (int i = 0; i < this->num_samples; i++) { for(int j = 0; j < this->num_features; j++) { cellData->InsertNextValue(index++); } } this->celllut = vtkSmartPointer<vtkLookupTable>::New(); this->celllut->SetNumberOfTableValues(this->num_samples*this->num_features); this->celllut->SetTableRange(0, this->num_samples*this->num_features - 1); this->celllut->Build(); int k = 0; for(int i = 0; i < this->num_samples; i++) { for(int j = 0; j < this->num_features; j++) { rgb rgb = GetRGBValue( mapdata[num_samples - i - 1][j]); celllut->SetTableValue(k++, rgb.r, rgb.g, rgb.b); } } this->aPlane->Update(); this->aPlane->GetOutput()->GetCellData()->SetScalars(cellData); this->mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); this->mapper->SetInputConnection(aPlane->GetOutputPort()); this->mapper->SetScalarRange(0, this->num_samples*this->num_features - 1); this->mapper->SetLookupTable(celllut); this->actor = vtkSmartPointer<vtkActor>::New(); this->actor->SetMapper(mapper); vtkSmartPointer<vtkLookupTable> scalarbarLut = vtkSmartPointer<vtkLookupTable>::New(); scalarbarLut->SetTableRange (-1, 1); scalarbarLut->SetNumberOfTableValues(COLOR_MAP_SIZE); for(int index = 0; index<COLOR_MAP_SIZE;index++) { rgb rgbscalar = COLORMAP[index]; scalarbarLut->SetTableValue(index, rgbscalar.r, rgbscalar.g, rgbscalar.b); } scalarbarLut->Build(); vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New(); scalarBar->SetLookupTable(scalarbarLut); scalarBar->SetTitle("Color Map"); scalarBar->SetNumberOfLabels(10); scalarBar->GetTitleTextProperty()->SetColor(0,0,0); scalarBar->GetTitleTextProperty()->SetFontSize (10); scalarBar->GetLabelTextProperty()->SetColor(0,0,0); scalarBar->GetTitleTextProperty()->SetFontSize (10); scalarBar->SetMaximumHeightInPixels(1000); scalarBar->SetMaximumWidthInPixels(100); this->view->GetRenderer()->AddActor(actor); this->view->GetRenderer()->AddActor2D(scalarBar); this->SetInteractStyle(); this->view->GetRenderer()->GradientBackgroundOff(); this->view->GetRenderer()->SetBackground(1,1,1); //this->showDendrogram2(); this->view->Render(); //this->view->GetInteractor()->Start(); return; } void TrendHeatmapWindow::drawPointsforNe() { this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); this->view = vtkSmartPointer<vtkGraphLayoutView>::New(); this->view->AddRepresentationFromInput(graph_Layout); this->view->SetLayoutStrategy("Pass Through"); this->view->ScaledGlyphsOn(); this->theme = vtkSmartPointer<vtkViewTheme>::New(); vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New(); verts->SetNumberOfCells(1); vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New(); orient->SetNumberOfComponents(1); orient->SetName("orientation"); vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New(); label->SetNumberOfComponents(1); label->SetName("label"); vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New(); for(int i=0; i<this->num_features;i++) { pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0); } for(int i=0; i<this->num_features;i++) { verts->InsertNextCell(1); verts->InsertCellPoint(i); orient->InsertNextValue(45.0); vtkIdType id = i+1 ; label->InsertNextValue(this->table->GetColumn(id)->GetName()); } pd->SetPoints(pts); pd->SetVerts(verts); pd->GetPointData()->AddArray(label); pd->GetPointData()->AddArray(orient); vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New(); hier->SetInputData(pd); hier->SetOrientationArrayName("orientation"); hier->SetLabelArrayName("label"); hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0); vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New(); lmapper->SetInputConnection(hier->GetOutputPort()); vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New(); lmapper->SetRenderStrategy(strategy); lmapper->SetShapeToNone(); lmapper->SetBackgroundOpacity(0.0); lmapper->SetMargin(0); vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New(); lactor->SetMapper(lmapper); vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); rmapper->SetInputData(pd); vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New(); ractor->SetMapper(rmapper); this->view->GetRenderer()->AddActor(lactor); this->view->GetRenderer()->AddActor(ractor); this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New(); this->selectionCallback1->SetClientData(this); this->selectionCallback1->SetCallback (SelectionCallbackFunction1); this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1); }
30.399753
246
0.689606
RoysamLab
f8c183669d511351d46bb0da7553277ff7b2d98b
2,009
cpp
C++
src/base/throw_lock_exception.cpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/base/throw_lock_exception.cpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/base/throw_lock_exception.cpp
CoSoSys/cppdevtk
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \file /// /// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n /// Licensed under the Apache License, Version 2.0 (the "License");\n /// you may not use this file except in compliance with the License.\n /// You may obtain a copy of the License at\n /// http://www.apache.org/licenses/LICENSE-2.0\n /// Unless required by applicable law or agreed to in writing, software\n /// distributed under the License is distributed on an "AS IS" BASIS,\n /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n /// See the License for the specific language governing permissions and\n /// limitations under the License.\n /// Please see the file COPYING. /// /// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "throw_lock_exception.hpp" #include <cppdevtk/base/lock_exception.hpp> #include <cppdevtk/base/deadlock_exception.hpp> #include <cppdevtk/base/cassert.hpp> namespace cppdevtk { namespace base { namespace detail { #if (CPPDEVTK_HAVE_CPP11_SYSTEM_ERROR) void ThrowLockException(const ::std::system_error& exc) { const ::std::error_code& kErrorCode = exc.code(); if (kErrorCode == ::std::errc::resource_deadlock_would_occur) { throw CPPDEVTK_DEADLOCK_EXCEPTION_WA(exc.what()); } if (kErrorCode.category() == ::std::system_category()) { throw CPPDEVTK_LOCK_EXCEPTION_W_EC_WA(ErrorCode(kErrorCode.value(), SystemCategoryRef()), exc.what()); } CPPDEVTK_ASSERT(kErrorCode.category() == ::std::generic_category()); throw CPPDEVTK_LOCK_EXCEPTION_W_EC_WA(ErrorCode(kErrorCode.value(), GenericCategoryRef()), exc.what()); } #endif } // namespace detail } // namespace base } // namespace cppdevtk
37.203704
126
0.628173
CoSoSys
f8c4591f863666fa47e610293ffd0fd7e3e0eae0
696
hpp
C++
nmpp/exception.hpp
ltekieli/nanomsgpp
179fcb46f8849a02c1940a728828dbfbb4737575
[ "MIT" ]
1
2017-07-19T12:34:35.000Z
2017-07-19T12:34:35.000Z
nmpp/exception.hpp
ltekieli/nanomsgpp
179fcb46f8849a02c1940a728828dbfbb4737575
[ "MIT" ]
null
null
null
nmpp/exception.hpp
ltekieli/nanomsgpp
179fcb46f8849a02c1940a728828dbfbb4737575
[ "MIT" ]
null
null
null
#ifndef NMPP_EXCEPTION_HPP_ #define NMPP_EXCEPTION_HPP_ #include <exception> #include <nanomsg/nn.h> namespace nmpp { class exception final : std::exception { public: exception() : m_err(nn_errno()) { } int num() const noexcept { return m_err; } virtual const char* what() const throw() { return nn_strerror(m_err); } private: int m_err; }; inline void throw_when(bool condition) { if (condition) throw exception(); } template <typename exception_type, typename... Args> inline void throw_when(bool condition, Args&&... args) { if (condition) throw exception_type(std::forward<Args>(args)...); } } // namespace nmpp #endif // NMPP_EXCEPTION_HPP_
14.808511
54
0.686782
ltekieli
f8c629278f4b2e121781e1e7350441168f9c06a1
1,025
hpp
C++
a21/eeprom.hpp
biappi/a21
6d008bebdbd6c51816ed61aa45664fa3b2715d9b
[ "MIT" ]
6
2017-07-28T13:36:24.000Z
2022-01-30T14:00:32.000Z
a21/eeprom.hpp
carkang/a21
8f472e75de5734514f152828033a93b88401069a
[ "MIT" ]
3
2018-10-26T20:10:49.000Z
2021-05-15T20:31:45.000Z
a21/eeprom.hpp
carkang/a21
8f472e75de5734514f152828033a93b88401069a
[ "MIT" ]
2
2021-02-14T14:12:58.000Z
2022-01-13T23:08:26.000Z
// // a21 — Arduino Toolkit. // Copyright (C) 2016-2018, Aleh Dzenisiuk. http://github.com/aleh/a21 // #pragma once #include "Arduino.h" namespace a21 { /** * Digispark boards have no EEPROM library, so here is a simple one. * TODO: something is wrong here, investigate */ class EEPROM { public: static uint8_t read(uint16_t address) { // Wait for any previous write to complete. while (EECR & _BV(EEPE)) ; EEARL = address; EECR |= _BV(EERE); return EEDR; } static void update(uint16_t address, uint8_t data) { if (read(address) == data) return; // No need to wait for the prvious write to complete, already did this in read(). // Make sure we'll use Erase & Write in one operation. EECR &= ~(_BV(EEPM1) | _BV(EEPM0)); EEARL = address; EEDR = data; // These two bits have to be set separately: first Master Program Enable, then Program Enable. EECR |= _BV(EEMPE); EECR |= _BV(EEPE); } }; } // namespace a21
21.354167
98
0.620488
biappi
f8c6dc2c4a65dcfd565e941fc5cb749c49236333
1,135
cc
C++
color_01.cc
bellcorreia/learn-gl
c9be56b1a9b7da984b0d499df8b92fbe11e8a75c
[ "MIT" ]
3
2022-01-04T01:23:25.000Z
2022-01-04T01:28:45.000Z
color_01.cc
bellcorreia/learn-gl
c9be56b1a9b7da984b0d499df8b92fbe11e8a75c
[ "MIT" ]
null
null
null
color_01.cc
bellcorreia/learn-gl
c9be56b1a9b7da984b0d499df8b92fbe11e8a75c
[ "MIT" ]
null
null
null
/* * Source code written by Gabriel Correia */ #include <iostream> #include <GLFW/glfw3.h> constexpr GLint WINDOW_WIDTH = 640, WINDOW_HEIGHT = 480; static GLfloat current_colors[3]; int main (int argc, char **argv) { GLFWwindow *main_window; glfwInit (); /* Creating a window to render into it */ main_window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Color 01", nullptr, nullptr); glfwMakeContextCurrent (main_window); while (! glfwWindowShouldClose (main_window)) { /* Collecting the current color buffer */ glGetFloatv (GL_CURRENT_COLOR, current_colors); std::printf ("Current colors R: %f G: %f B: %f\n", current_colors[0], current_colors[1], current_colors[2]); glClear (GL_COLOR_BUFFER_BIT); glBegin (GL_TRIANGLES); glColor3f (1.0f, 0.0f, 0.0f); glVertex2f (-0.5f, 0.0f); glVertex2f (0.0f, 0.5f); glVertex2f (0.5f, 0.0f); glEnd (); glfwSwapBuffers (main_window); glfwPollEvents (); } glfwDestroyWindow (main_window); glfwTerminate (); return 0; }
22.254902
69
0.626432
bellcorreia
f8c7df245a2677f66e71e3f19d199835a45839c7
661
cpp
C++
codeforces/cf584 div2/B.cpp
songhn233/ACM_Steps
6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
codeforces/cf584 div2/B.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
codeforces/cf584 div2/B.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #define ll long long using namespace std; const int inf=0x3f3f3f3f; int n; string s; int a[110],b[110],c[110]; int p[10500]; int main() { int ans=0; cin>>n; cin>>s; for(int i=1;i<=n;i++) cin>>a[i]>>b[i]; for(int i=0;i<s.size();i++) c[i+1]=s[i]-'0'; for(int i=1;i<=n;i++) if(c[i]==1) p[0]++; ans=p[0]; for(int i=1;i<=n;i++) { for(int j=1;j<=b[i]-1;j++) p[j]+=c[i]; for(int j=0;j<=10000;j++) { if(b[i]+j>=10010) break; if(j%a[i]==0) { c[i]^=1; } p[b[i]+j]+=c[i]; } } for(int i=1;i<=10000;i++) ans=max(ans,p[i]); cout<<ans<<endl; return 0; }
16.525
45
0.526475
songhn233
f8c980368e2aee02760aeed67828c6e39659f62c
1,478
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/DateTime.ToLocalTime ToUniversalTime/CPP/class1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR/DateTime.ToLocalTime ToUniversalTime/CPP/class1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR/DateTime.ToLocalTime ToUniversalTime/CPP/class1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> using namespace System; void main() { Console::WriteLine("Enter a date and time."); String^ strDateTime = Console::ReadLine(); DateTime localDateTime, univDateTime; try { localDateTime = DateTime::Parse(strDateTime); univDateTime = localDateTime.ToUniversalTime(); Console::WriteLine("{0} local time is {1} universal time.", localDateTime, univDateTime ); } catch (FormatException^) { Console::WriteLine("Invalid format."); return; } Console::WriteLine("Enter a date and time in universal time."); strDateTime = Console::ReadLine(); try { univDateTime = DateTime::Parse(strDateTime); localDateTime = univDateTime.ToLocalTime(); Console::WriteLine("{0} universal time is {1} local time.", univDateTime, localDateTime ); } catch (FormatException^) { Console::WriteLine("Invalid format."); return; } } // The example displays output like the following when run on a // computer whose culture is en-US in the Pacific Standard Time zone: // Enter a date and time. // 12/10/2015 6:18 AM // 12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time. // Enter a date and time in universal time. // 12/20/2015 6:42:00 // 12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time. // </Snippet1>
30.163265
82
0.610961
hamarb123
f8cf9d154f13f7d416811dbfddf21e699c69a6cb
515
cpp
C++
lang/C++/last-friday-of-each-month.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:38.000Z
2018-11-09T22:08:38.000Z
lang/C++/last-friday-of-each-month.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/last-friday-of-each-month.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
#include <boost/date_time/gregorian/gregorian.hpp> #include <iostream> #include <cstdlib> int main( int argc , char* argv[ ] ) { using namespace boost::gregorian ; greg_month months[ ] = { Jan , Feb , Mar , Apr , May , Jun , Jul , Aug , Sep , Oct , Nov , Dec } ; greg_year gy = atoi( argv[ 1 ] ) ; for ( int i = 0 ; i < 12 ; i++ ) { last_day_of_the_week_in_month lwdm ( Friday , months[ i ] ) ; date d = lwdm.get_date( gy ) ; std::cout << d << std::endl ; } return 0 ; }
28.611111
69
0.56699
ethansaxenian