blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
83023e982c5787ed993fc71f801ab4ff0063b0d1
33563f7e62dfb35e7cf4309ef190a9d0b7a84f44
/code/scripting/api/libs/ui.cpp
9d5880140faaa3c5e20a416df3127206ef393ae4
[ "Unlicense" ]
permissive
marek-g/freespace2_vr3d
2868dceec2c3b5ef7a340e5a4e11b13b5a6787a0
60047116fd2ed49002e101d1cb7358d8b16bcd1e
refs/heads/master
2023-02-24T10:28:48.969117
2021-01-22T15:54:54
2021-01-22T15:54:54
332,247,013
0
0
null
null
null
null
UTF-8
C++
false
false
13,920
cpp
// // #include "ui.h" #include "globalincs/alphacolors.h" #include "cmdline/cmdline.h" #include "gamesnd/eventmusic.h" #include "menuui/barracks.h" #include "menuui/mainhallmenu.h" #include "menuui/optionsmenu.h" #include "menuui/playermenu.h" #include "menuui/readyroom.h" #include "mission/missionbriefcommon.h" #include "mission/missioncampaign.h" #include "missionui/missionscreencommon.h" #include "playerman/managepilot.h" #include "scpui/SoundPlugin.h" #include "scpui/rocket_ui.h" #include "scripting/api/objs/cmd_brief.h" #include "scripting/api/objs/color.h" #include "scripting/api/objs/player.h" #include "scripting/lua/LuaTable.h" // Our Assert conflicts with the definitions inside libRocket #pragma push_macro("Assert") #undef Assert #include <Rocket/Core/Lua/LuaType.h> #pragma pop_macro("Assert") namespace scripting { namespace api { //*************************Testing stuff************************* // This section is for stuff that's considered experimental. ADE_LIB(l_UserInterface, "UserInterface", "ui", "Functions for managing the \"scpui\" user interface system."); ADE_FUNC(setOffset, l_UserInterface, "number x, number y", "Sets the offset from the top left corner at which <b>all</b> rocket contexts will be rendered", "boolean", "true if the operation was successful, false otherwise") { float x; float y; if (!ade_get_args(L, "ff", &x, &y)) { return ADE_RETURN_FALSE; } scpui::setOffset(x, y); return ADE_RETURN_TRUE; } ADE_FUNC(enableInput, l_UserInterface, "any context /* A libRocket Context value */", "Enables input for the specified libRocket context", "boolean", "true if successfull") { using namespace Rocket::Core; // Check parameter number if (!ade_get_args(L, "*")) { return ADE_RETURN_FALSE; } auto ctx = Lua::LuaType<Context>::check(L, 1); if (ctx == nullptr) { LuaError(L, "Parameter 1 is not a valid context handle!"); return ADE_RETURN_FALSE; } scpui::enableInput(ctx); return ADE_RETURN_TRUE; } ADE_FUNC(disableInput, l_UserInterface, "", "Disables UI input", "boolean", "true if successfull") { scpui::disableInput(); return ADE_RETURN_TRUE; } ADE_FUNC(playElementSound, l_UserInterface, "any element /* A libRocket element */, string event, string state = \"\"", "Plays an element specific sound with an optional state for differentiating different UI states.", "boolean", "true if a sound was played, false otherwise") { using namespace Rocket::Core; const char* event; const char* state = ""; if (!ade_get_args(L, "*s|s", &event, &state)) { return ADE_RETURN_FALSE; } auto el = Lua::LuaType<Element>::check(L, 1); if (el == nullptr) { return ADE_RETURN_FALSE; } return ade_set_args(L, "b", scpui::SoundPlugin::instance()->PlayElementSound(el, event, state)); } //**********SUBLIBRARY: UserInterface/PilotSelect ADE_LIB_DERIV(l_UserInterface_PilotSelect, "PilotSelect", nullptr, "API for accessing values specific to the pilot select screen.<br><b>Warning:</b> This is an internal " "API for the new UI system. This should not be used by other code and may be removed in the future!", l_UserInterface); ADE_VIRTVAR(MAX_PILOTS, l_UserInterface_PilotSelect, nullptr, "Gets the maximum number of possible pilots.", "number", "The maximum number of pilots") { return ade_set_args(L, "i", MAX_PILOTS); } ADE_VIRTVAR(WarningCount, l_UserInterface_PilotSelect, nullptr, "The amount of warnings caused by the mod while loading.", "number", "The maximum number of pilots") { return ade_set_args(L, "i", Global_warning_count); } ADE_VIRTVAR(ErrorCount, l_UserInterface_PilotSelect, nullptr, "The amount of errors caused by the mod while loading.", "number", "The maximum number of pilots") { return ade_set_args(L, "i", Global_error_count); } ADE_FUNC(enumeratePilots, l_UserInterface_PilotSelect, nullptr, "Lists all pilots available for the pilot selection<br>", ade_type_array("string"), "A table containing the pilots (without a file extension) or nil on error") { using namespace luacpp; auto table = LuaTable::create(L); auto pilots = player_select_enumerate_pilots(); for (size_t i = 0; i < pilots.size(); ++i) { table.addValue(i + 1, pilots[i]); } return ade_set_args(L, "t", &table); } ADE_FUNC(getLastPilot, l_UserInterface_PilotSelect, nullptr, "Reads the last active pilot from the config file and returns some information about it. callsign is the name " "of the player and is_multi indicates whether the pilot was last active as a multiplayer pilot.", "string", "The pilot name or nil if there was no last pilot") { using namespace luacpp; auto callsign = player_get_last_player(); if (callsign.empty()) { return ADE_RETURN_NIL; } return ade_set_args(L, "s", callsign.c_str()); } ADE_FUNC(checkPilotLanguage, l_UserInterface_PilotSelect, "string callsign", "Checks if the pilot with the specified callsign has the right language.", "boolean", "true if pilot is valid, false otherwise") { const char* callsign; if (!ade_get_args(L, "s", &callsign)) { return ADE_RETURN_FALSE; } return ade_set_args(L, "b", valid_pilot_lang(callsign)); } ADE_FUNC(selectPilot, l_UserInterface_PilotSelect, "string callsign, boolean is_multi", "Selects the pilot with the specified callsign and advances the game to the main menu.", nullptr, "nothing") { const char* callsign; bool is_multi; if (!ade_get_args(L, "sb", &callsign, &is_multi)) { return ADE_RETURN_NIL; } player_finish_select(callsign, is_multi); return ADE_RETURN_NIL; } ADE_FUNC(deletePilot, l_UserInterface_PilotSelect, "string callsign", "Deletes the pilot with the specified callsign. This is not reversible!", "boolean", "true on success, false otherwise") { const char* callsign; if (!ade_get_args(L, "s", &callsign)) { return ADE_RETURN_NIL; } return ade_set_args(L, "b", delete_pilot_file(callsign)); } ADE_FUNC( createPilot, l_UserInterface_PilotSelect, "string callsign, boolean is_multi, [string copy_from]", "Creates a new pilot in either single or multiplayer mode and optionally copies settings from an existing pilot.", "boolean", "true on success, false otherwise") { const char* callsign; bool is_multi; const char* copy_from = nullptr; if (!ade_get_args(L, "sb|s", &callsign, &is_multi, &copy_from)) { return ADE_RETURN_NIL; } return ade_set_args(L, "b", player_create_new_pilot(callsign, is_multi, copy_from)); } ADE_FUNC(isAutoselect, l_UserInterface_PilotSelect, nullptr, "Determines if the pilot selection screen should automatically select the default user.", "boolean", "true if autoselect is enabled, false otherwise") { return ade_set_args(L, "b", Cmdline_benchmark_mode); } //**********SUBLIBRARY: UserInterface/MainHall ADE_LIB_DERIV(l_UserInterface_MainHall, "MainHall", nullptr, "API for accessing values specific to the main hall screen.<br><b>Warning:</b> This is an internal " "API for the new UI system. This should not be used by other code and may be removed in the future!", l_UserInterface); ADE_FUNC(startAmbientSound, l_UserInterface_MainHall, nullptr, "Starts the ambient mainhall sound.", nullptr, "nothing") { (void)L; main_hall_start_ambient(); return ADE_RETURN_NIL; } //**********SUBLIBRARY: UserInterface/Barracks ADE_LIB_DERIV(l_UserInterface_Barracks, "Barracks", nullptr, "API for accessing values specific to the barracks screen.<br><b>Warning:</b> This is an internal " "API for the new UI system. This should not be used by other code and may be removed in the future!", l_UserInterface); ADE_FUNC(listPilotImages, l_UserInterface_Barracks, nullptr, "Lists the names of the available pilot images.", ade_type_array("string"), "The list of pilot filenames or nil on error") { pilot_load_pic_list(); using namespace luacpp; LuaTable out = LuaTable::create(L); for (auto i = 0; i < Num_pilot_images; ++i) { out.addValue(i + 1, Pilot_image_names[i]); } return ade_set_args(L, "t", &out); } ADE_FUNC(listSquadImages, l_UserInterface_Barracks, nullptr, "Lists the names of the available squad images.", ade_type_array("string"), "The list of squad filenames or nil on error") { pilot_load_squad_pic_list(); using namespace luacpp; LuaTable out = LuaTable::create(L); for (auto i = 0; i < Num_pilot_squad_images; ++i) { out.addValue(i + 1, Pilot_squad_image_names[i]); } return ade_set_args(L, "t", &out); } ADE_FUNC(acceptPilot, l_UserInterface_Barracks, "player selection", "Accept the given player as the current player", "boolean", "true on sucess, false otherwise") { player_h* plh; if (!ade_get_args(L, "o", l_Player.GetPtr(&plh))) { return ADE_RETURN_FALSE; } barracks_accept_pilot(plh->get()); return ADE_RETURN_TRUE; } //**********SUBLIBRARY: UserInterface/OptionsMenu // This needs a slightly different name since there is already a type called "Options" ADE_LIB_DERIV(l_UserInterface_Options, "OptionsMenu", nullptr, "API for accessing values specific to the options screen.<br><b>Warning:</b> This is an internal " "API for the new UI system. This should not be used by other code and may be removed in the future!", l_UserInterface); ADE_FUNC(playVoiceClip, l_UserInterface_Options, nullptr, "Plays the example voice clip used for checking the voice volume", "boolean", "true on sucess, false otherwise") { options_play_voice_clip(); return ADE_RETURN_TRUE; } //**********SUBLIBRARY: UserInterface/CampaignMenu // This needs a slightly different name since there is already a type called "Options" ADE_LIB_DERIV(l_UserInterface_Campaign, "CampaignMenu", nullptr, "API for accessing data related to the campaign UI.<br><b>Warning:</b> This is an internal " "API for the new UI system. This should not be used by other code and may be removed in the future!", l_UserInterface); ADE_FUNC(loadCampaignList, l_UserInterface_Campaign, nullptr, "Loads the list of available campaigns", "boolean", // ade_type_info({ade_type_array("string"), ade_type_array("string")}), "false if something failed while loading the list, true otherwise") { return ade_set_args(L, "b", !campaign_build_campaign_list()); } ADE_FUNC(getCampaignList, l_UserInterface_Campaign, nullptr, "Get the campaign name and description lists", ade_type_info({ade_type_array("string"), ade_type_array("string"), ade_type_array("string")}), "Three tables with the names, file names, and descriptions of the campaigns") { luacpp::LuaTable nameTable = luacpp::LuaTable::create(L); luacpp::LuaTable fileNameTable = luacpp::LuaTable::create(L); luacpp::LuaTable descriptionTable = luacpp::LuaTable::create(L); for (int i = 0; i < Num_campaigns; ++i) { nameTable.addValue(i + 1, Campaign_names[i]); fileNameTable.addValue(i + 1, Campaign_file_names[i]); auto description = Campaign_descs[i]; descriptionTable.addValue(i + 1, description ? description : ""); } // We actually do not need this anymore now so free it immediately mission_campaign_free_list(); return ade_set_args(L, "ttt", nameTable, fileNameTable, descriptionTable); } ADE_FUNC(selectCampaign, l_UserInterface_Campaign, "string campaign_file", "Selects the specified campaign file name", "boolean", "true if successful, false otherwise") { const char* filename = nullptr; if (!ade_get_args(L, "s", &filename)) { return ADE_RETURN_FALSE; } campaign_select_campaign(filename); return ADE_RETURN_TRUE; } ADE_FUNC(resetCampaign, l_UserInterface_Campaign, "string campaign_file", "Resets the campaign with the specified file name", "boolean", "true if successful, false otherwise") { const char* filename = nullptr; if (!ade_get_args(L, "s", &filename)) { return ADE_RETURN_FALSE; } campaign_reset(filename); return ADE_RETURN_TRUE; } //**********SUBLIBRARY: UserInterface/CommandBriefing // This needs a slightly different name since there is already a type called "Options" ADE_LIB_DERIV(l_UserInterface_CmdBrief, "CommandBriefing", nullptr, "API for accessing data related to the command briefing UI.<br><b>Warning:</b> This is an internal " "API for the new UI system. This should not be used by other code and may be removed in the future!", l_UserInterface); ADE_VIRTVAR(ColorTags, l_UserInterface_CmdBrief, nullptr, "The available tagged colors", ade_type_map("string", "color"), "A mapping from tag string to color value") { using namespace luacpp; LuaTable mapping = LuaTable::create(L); for (const auto& tagged : Tagged_Colors) { SCP_string tag; tag.resize(1, tagged.first); mapping.addValue(tag, l_Color.Set(*tagged.second)); } return ade_set_args(L, "t", mapping); } ADE_VIRTVAR(DefaultTextColorTag, l_UserInterface_CmdBrief, nullptr, "Gets the default color tag string for the command briefing. Index into ColorTags.", "string", "The default color tag") { SCP_string tagStr; auto defaultColor = default_command_briefing_color; if (defaultColor == '\0' || !brief_verify_color_tag(defaultColor)) { defaultColor = Color_Tags[0]; } tagStr.resize(1, defaultColor); return ade_set_args(L, "s", tagStr); } ADE_FUNC(getBriefing, l_UserInterface_CmdBrief, nullptr, "Get the command briefing.", "cmd_briefing", "The briefing data") { // The cmd briefing code has support for specifying the team but only sets the index to 0 return ade_set_args(L, "o", l_CmdBrief.Set(Cmd_briefs[0])); } ADE_FUNC(getBriefingMusicName, l_UserInterface_CmdBrief, nullptr, "Gets the file name of the music file to play for the briefing.", "string", "The file name or empty if no music") { return ade_set_args(L, "s", common_music_get_filename(SCORE_BRIEFING).c_str()); } } // namespace api } // namespace scripting
[ "asarium@gmail.com" ]
asarium@gmail.com
c0f97ee7513a9289af1721b410fe8e27f7fda1ef
48d3c7f2b4953ca3b25cce6f82c26c4e0c74db30
/17_Operator_Overloading/04_Identify_Error.cpp
b467274796eea95ed42455e4e593b0c94f617c2b
[]
no_license
syedyasar/Cpp_Programming_Fundamentals
b62f3dd73738b7ecbe372c4fec3e2ea2d11c9e41
07290adccc7505dac051147aaa342e85ec254917
refs/heads/main
2023-06-17T14:09:29.823641
2021-06-29T20:16:27
2021-06-29T20:16:27
376,637,978
0
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
// Identify error #include <iostream> using namespace std; int& f1(int x) // It is RBR function { return x; // Error becoz normal parameter can not be returned } // 'x' is lost main() { int a = 25; cout << a << "\n"; // 25 f1(a) = 35; // Error cout << a << "\n"; }
[ "syedyasar.mjcet@gmail.com" ]
syedyasar.mjcet@gmail.com
f614485ffcded1adb356e6a2c1ed495462ec4d9e
15e016df284b9250f7b5b92753abcc792f692c03
/src-cpp/impl/Interstitial.cpp
0c60bb8aff6a939e37e77e7c2b90a973e868f08b
[]
no_license
uc-union/union-ads-sdk-cocos-sdk
5f2c2f7e0076ac9f9c8cfb13132ff5407b2d2ce5
39fedf88113a07341c5c823bcf25901b8026b3d4
refs/heads/master
2021-01-21T04:59:55.438956
2016-07-05T08:33:09
2016-07-05T08:33:09
53,843,013
0
0
null
null
null
null
UTF-8
C++
false
false
3,385
cpp
#include "Interstitial.h" #include "JNICommon.h" #include "AdListener.h" #include "AdRequest.h" namespace com_ucweb_union_ads_sdk { class InterstitialImpl { public: InterstitialImpl():mRequest(0) { ScopedJniMethodInfo info; JniMethodInfo_& rawInfo = info.get(); if( JniHelper::getMethodInfo(rawInfo , "com.ucweb.union.ads.InterstitialAdImpl" , "<init>" , "(Landroid/content/Context;)V")) { mJavaInterstitial.Reset(rawInfo.env->NewObject(rawInfo.classID, rawInfo.methodID, Context::get())); } else { LOGE("Failed to get method InterstitialAdImpl.InterstitialAdImpl!"); } } ~InterstitialImpl() { if(mRequest){ delete mRequest; } } void show() { ScopedJniMethodInfo info; JniMethodInfo_& rawInfo = info.get(); if( JniHelper::getMethodInfo(rawInfo , "com.ucweb.union.ads.InterstitialAdImpl" , "show" , "()V")) { rawInfo.env->CallVoidMethod(mJavaInterstitial.get(), rawInfo.methodID); } else { LOGE("Failed to get method InterstitialAdImpl.show!"); } } void setListener(AdListener* listener){ ScopedJniMethodInfo info; JniMethodInfo_& rawInfo = info.get(); if( JniHelper::getMethodInfo(rawInfo , "com.ucweb.union.ads.InterstitialAdImpl" , "setAdListener" , "(J)V")) { rawInfo.env->CallVoidMethod(mJavaInterstitial.get(), rawInfo.methodID, reinterpret_cast<jlong>(listener)); } else { LOGE("Failed to get method InterstitialAdImpl.setAdListener!"); } } void load(const AdRequest& request){ if(mRequest) { delete mRequest; } mRequest = &request; ScopedJniMethodInfo info; JniMethodInfo_& rawInfo = info.get(); if( JniHelper::getMethodInfo(rawInfo , "com.ucweb.union.ads.InterstitialAdImpl" , "loadAd" , "(Lcom/ucweb/union/ads/AdRequest;)V")) { rawInfo.env->CallVoidMethod(mJavaInterstitial.get(), rawInfo.methodID, request.asJavaObject()); } else { LOGE("Failed to get method InterstitialAdImpl.loadAd!"); } } void stopLoading(){ ScopedJniMethodInfo info; JniMethodInfo_& rawInfo = info.get(); if( JniHelper::getMethodInfo(rawInfo , "com.ucweb.union.ads.InterstitialAdImpl" , "stopLoading" , "()V")) { rawInfo.env->CallVoidMethod(mJavaInterstitial.get(), rawInfo.methodID); } else { LOGE("Failed to get method InterstitialAdImpl.stopLoading!"); } } private: ScopedJavaGlobalRef mJavaInterstitial; const AdRequest* mRequest; };//InterstitialImpl Interstitial::Interstitial(): mImpl(new InterstitialImpl()){ } Interstitial::~Interstitial(){ delete mImpl; } void Interstitial::show() { mImpl->show(); } //should be a weak reference void Interstitial::setListener(AdListener* listener){ mImpl->setListener(listener); } void Interstitial::load(const AdRequest& request){ mImpl->load(request); } void Interstitial::stopLoading(){ mImpl->stopLoading(); } }//com_ucweb_union_ads_sdk
[ "wl89397@alibaba-inc.com" ]
wl89397@alibaba-inc.com
77dba847be26ae1c2257ea6f95f9a0b243b45bd6
a789a57af328ddc0421869e610028ef9174a3b56
/Header Files/NeuralNet.h
227dd6e5b0878cefb1b8296bed160baa245f376d
[]
no_license
17ijcurtis/ANN
ae0f4f2845b0bdcccd246dacad50c5129145033e
e79f688ff11cfc7be9b7569d973cf8402162eac8
refs/heads/master
2021-01-11T23:19:50.225505
2017-02-10T19:40:39
2017-02-10T19:41:02
78,568,472
1
0
null
null
null
null
UTF-8
C++
false
false
927
h
/* Author: Isaiah Curtis Date: 1/10/2017 */ #pragma once #ifndef NEURALNET_H #define NEURALNET_H #include <iostream> #include <vector> using namespace std; #include "Neuron.h" #include "ILayer.h" #include "InputLayer.h" #include "Layer.h" #include "EnumsANN.h" class NeuralNet { private: // Array of layers vector<ILayer*> layers; double learningRate; CostFunctions costFunction; public: NeuralNet(vector<unsigned short>, double, CostFunctions); ~NeuralNet(); vector<double> getOutput(vector<double>); double getTotalCost(vector<double>, vector<double>); double getCost(double, double); Layer* getOutputLayer(); void trainNetwork(vector<double>, vector<double>); void calculateNeuronError(vector<double>, vector<double>); void calculateWeightGradients(); void adjustBiases(); void adjustWeights(); double sigmoidPrime(double z) { return pow(exp(1.0), -z) / pow(1 + pow(exp(1.0), -z), 2); } }; #endif
[ "17ijcurtis@gmail.com" ]
17ijcurtis@gmail.com
eb68945b3c10a396f9ae8f097bc5c6d50d1da4eb
726cf6a267312666a32a5b92de7343a51a8bd90f
/game_v3_lb6/map/field.cpp
7887f5f0d42c1126108a5fcc7fcdf3127b031f40
[]
no_license
Sergei4302/BAZA
9137b7e62384ec824ae742f3db4f3a6adac7901b
f1d9978154db25e5e927158c421fdc0db21a106d
refs/heads/master
2022-02-07T05:24:27.387388
2021-12-27T07:24:40
2021-12-27T07:24:40
237,601,129
0
1
null
null
null
null
UTF-8
C++
false
false
1,147
cpp
#include "field.h" #include <iostream> Field::Field() { /* _hight=hight; _width=width;*/ _cell= new Cell*[_hight]; for (int i=0; i<_hight; i++){ _cell[i]=new Cell[_width]; } } Field::Field(const Field &source) : Field() { for (int i = 0; i < _hight; i++) { std::copy(source._cell[i], source._cell[i] + _width, this->_cell[i]); } } Field::Field(Field&& other) { std::swap(this->_cell, other._cell); other._cell = nullptr; } Field& Field::operator= (const Field &other) { if (this != &other){ for (int i = 0; i < _hight; i++) { for (int j = 0; j < _width; j++) _cell[i][j] = other._cell[i][j]; } } return *this; } Field& Field::operator= (Field&& other) { if (this != &other) { delete this; this->_cell = other._cell; other._cell = nullptr; } return *this; } Field::~Field() { for (int i = 0; i < _hight; ++i) { delete[] _cell[i]; } delete _cell; } void Field::setCell(int i, int j, Cell &cells) { this->_cell[i][j] = cells; } Cell** Field::getCell() { return _cell; }
[ "tikhon4302@gmail.com" ]
tikhon4302@gmail.com
b7d58f3be802844d41ec5c28c7e3464fae6b054b
553d308dfd800faf7008eebabbe609af76b019a5
/cpp/core/src/scene/scene.cpp
f514cc4efa7245d9890653519ef0befef58dfb56
[]
no_license
PeterZs/diff_stokes_flow
751636b9d998f2bca7bceabd48bf003641221220
dd9daef5dd55fcce687ba28d527e84f8364e2003
refs/heads/master
2023-01-03T01:35:13.489246
2020-10-09T03:42:34
2020-10-09T03:42:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,234
cpp
#include "scene/scene.h" #include "common/common.h" template<int dim> Scene<dim>::Scene() : boundary_type_(BoundaryType::NoSeparation) {} template<int dim> void Scene<dim>::InitializeShapeComposition(const std::array<int, dim>& cell_nums, const std::vector<std::string>& shape_names, const std::vector<std::vector<real>>& shape_params) { CheckError(shape_names.size() == shape_params.size(), "Inconsistent shape names and parameters."); shape_.Clear(); const int shape_num = static_cast<int>(shape_names.size()); std::vector<real> params; for (int i = 0; i < shape_num; ++i) { shape_.AddParametricShape(shape_names[i], static_cast<int>(shape_params[i].size())); params.insert(params.end(), shape_params[i].begin(), shape_params[i].end()); } shape_.Initialize(cell_nums, params); } template<int dim> void Scene<dim>::InitializeCell(const real E, const real nu, const real threshold, const int edge_sample_num) { CheckError(shape_.param_num(), "You must call InitializeShapeComposition first."); cells_.clear(); const int cell_num_prod = shape_.cell_num_prod(); cells_.resize(cell_num_prod); #pragma omp parallel for for (int i = 0; i < cell_num_prod; ++i) { Cell<dim>& cell = cells_[i]; const auto cell_idx = GetIndex(i, shape_.cell_nums()); std::vector<real> sdf_at_corners(cell.corner_num_prod()); for (int j = 0; j < cell.corner_num_prod(); ++j) { const auto corner_idx = GetIndex(j, cell.corner_nums()); std::array<int, dim> node_idx = cell_idx; for (int k = 0; k < dim; ++k) node_idx[k] += corner_idx[k]; sdf_at_corners[j] = shape_.signed_distance(node_idx); } // Ready to initialize this cell. cell.Initialize(E, nu, threshold, edge_sample_num, sdf_at_corners); } } template<int dim> void Scene<dim>::InitializeDirichletBoundaryCondition(const std::vector<int>& dofs, const std::vector<real>& values) { CheckError(dofs.size() == values.size(), "Inconsistent dofs and values"); CheckError(!cells_.empty(), "You must call InitializeCell first."); dirichlet_conditions_.clear(); const int dofs_num = static_cast<int>(dofs.size()); for (int i = 0; i < dofs_num; ++i) dirichlet_conditions_[dofs[i]] = values[i]; // For nodes that are not adjacent to fluid or mixed cells, velocities are fixed to 0. std::vector<bool> free_dofs(shape_.node_num_prod() * dim, false); for (int i = 0; i < shape_.cell_num_prod(); ++i) { const auto& cell = cells_[i]; if (cell.IsSolidCell()) continue; const auto cell_idx = GetIndex(i, shape_.cell_nums()); for (int j = 0; j < cell.corner_num_prod(); ++j) { const auto corner_idx = GetIndex(j, cell.corner_nums()); std::array<int, dim> node_idx = cell_idx; for (int k = 0; k < dim; ++k) node_idx[k] += corner_idx[k]; const int idx = GetIndex(node_idx, shape_.node_nums()); for (int k = 0; k < dim; ++k) free_dofs[idx * dim + k] = true; } } for (int i = 0; i < shape_.node_num_prod() * dim; ++i) { if (free_dofs[i]) continue; const bool consistency = dirichlet_conditions_.find(i) == dirichlet_conditions_.end() || dirichlet_conditions_.at(i) == 0; if (!consistency) { std::cout << "Dof " << i << " should have been a solid node but was given nonzero velocity: " << dirichlet_conditions_.at(i) << "." << std::endl; const auto node_idx = GetIndex(i / dim, shape_.node_nums()); std::cout << "Node coordinates:"; for (int k = 0; k < dim; ++k) std::cout << " " << node_idx[k]; std::cout << std::endl; CheckError(false, "Inconsistent Dirichlet conditions."); } dirichlet_conditions_[i] = 0; } } template<int dim> void Scene<dim>::InitializeBoundaryType(const std::string& boundary_type) { if (boundary_type == "no_slip") boundary_type_ = BoundaryType::NoSlip; else if (boundary_type == "no_separation") boundary_type_ = BoundaryType::NoSeparation; else PrintError("Unsupported boundary type: " + boundary_type); } template<int dim> const std::vector<real> Scene<dim>::Forward(const std::string& qp_solver_name) { CheckError(!cells_.empty() && shape_.param_num(), "You must call all initialization function first."); // Now assemble the QP problem. // min 0.5 * u * K * u // s.t. C * u = d // u_i = u_i* // Assemble K, C, and d. // TODO: Use OpenMP to parallelize the code? const int cell_num = shape_.cell_num_prod(); SparseMatrixElements K_nonzeros, C_nonzeros; std::vector<real> d_vec; const int param_num = shape_.param_num(); std::vector<SparseMatrixElements> dK_nonzeros(param_num), dC_nonzeros(param_num); int C_row_num = 0; for (int i = 0; i < cell_num; ++i) { const auto& cell = cells_[i]; if (cell.IsSolidCell()) continue; // Remap node indices from this cell to the grid. const auto cell_idx = GetIndex(i, shape_.cell_nums()); std::vector<int> dof_map; const int dof_map_size = cell.corner_num_prod() * dim; dof_map.reserve(dof_map_size); for (int j = 0; j < cell.corner_num_prod(); ++j) { const auto corner_idx = GetIndex(j, cell.corner_nums()); std::array<int, dim> node_idx = cell_idx; for (int k = 0; k < dim; ++k) node_idx[k] += corner_idx[k]; const int idx = GetIndex(node_idx, shape_.node_nums()); for (int k = 0; k < dim; ++k) dof_map.push_back(idx * dim + k); } // Assemble K. const MatrixXr& K = cell.energy_matrix(); for (int ii = 0; ii < dof_map_size; ++ii) for (int jj = 0; jj < dof_map_size; ++jj) K_nonzeros.push_back(Eigen::Triplet<real>(dof_map[ii], dof_map[jj], K(ii, jj))); // Assemble dK. for (int p = 0; p < param_num; ++p) { MatrixXr dK = K; dK.setZero(); for (int j = 0; j < cell.corner_num_prod(); ++j) { const auto corner_idx = GetIndex(j, cell.corner_nums()); std::array<int, dim> node_idx = cell_idx; for (int k = 0; k < dim; ++k) node_idx[k] += corner_idx[k]; dK += cell.energy_matrix_gradients()[j] * shape_.signed_distance_gradients(node_idx)[p]; } for (int ii = 0; ii < dof_map_size; ++ii) for (int jj = 0; jj < dof_map_size; ++jj) dK_nonzeros[p].push_back(Eigen::Triplet<real>(dof_map[ii], dof_map[jj], dK(ii, jj))); } // Assemble C. if (cell.IsFluidCell()) continue; const VectorXr& c = cell.dirichlet_vector(); std::vector<VectorXr> dc(param_num, VectorXr::Zero(c.size())); for (int p = 0; p < param_num; ++p) { for (int j = 0; j < cell.corner_num_prod(); ++j) { const auto corner_idx = GetIndex(j, cell.corner_nums()); std::array<int, dim> node_idx = cell_idx; for (int k = 0; k < dim; ++k) node_idx[k] += corner_idx[k]; dc[p] += cell.dirichlet_vector_gradients().col(j) * shape_.signed_distance_gradients(node_idx)[p]; } } if (boundary_type_ == BoundaryType::NoSlip) { for (int j = 0; j < dim; ++j) { for (int k = 0; k < cell.corner_num_prod(); ++k) { C_nonzeros.push_back(Eigen::Triplet<real>(C_row_num, dof_map[k * dim + j], c(k))); for (int p = 0; p < param_num; ++p) { dC_nonzeros[p].push_back(Eigen::Triplet<real>(C_row_num, dof_map[k * dim + j], dc[p](k))); } } d_vec.push_back(0); ++C_row_num; } } else if (boundary_type_ == BoundaryType::NoSeparation) { const Eigen::Matrix<real, dim, 1>& normal = cell.normal(); std::vector<Eigen::Matrix<real, dim, 1>> dnormal(param_num, Eigen::Matrix<real, dim, 1>::Zero()); for (int p = 0; p < param_num; ++p) { for (int j = 0; j < cell.corner_num_prod(); ++j) { const auto corner_idx = GetIndex(j, cell.corner_nums()); std::array<int, dim> node_idx = cell_idx; for (int k = 0; k < dim; ++k) node_idx[k] += corner_idx[k]; dnormal[p] += cell.normal_gradients().col(j) * shape_.signed_distance_gradients(node_idx)[p]; } } for (int j = 0; j < dim; ++j) { for (int k = 0; k < cell.corner_num_prod(); ++k) { C_nonzeros.push_back(Eigen::Triplet<real>(C_row_num, dof_map[k * dim + j], c(k) * normal(j))); for (int p = 0; p < param_num; ++p) { dC_nonzeros[p].push_back(Eigen::Triplet<real>(C_row_num, dof_map[k * dim + j], dc[p](k) * normal(j) + c(k) * dnormal[p](j) )); } } } d_vec.push_back(0); ++C_row_num; } else PrintError("Unsupported boundary type."); } // Enforce Dirichlet boundary conditions. for (const auto& pair : dirichlet_conditions_) { C_nonzeros.push_back(Eigen::Triplet<real>(C_row_num, pair.first, 1)); d_vec.push_back(pair.second); ++C_row_num; } const int var_num = shape_.node_num_prod() * dim; // For our reference, here are the definitions of K and C. // const SparseMatrix K = ToSparseMatrix(var_num, var_num, K_nonzeros); // const SparseMatrix C = ToSparseMatrix(C_row_num, var_num, C_nonzeros); const VectorXr d = Eigen::Map<const VectorXr>(d_vec.data(), d_vec.size()); // Solve QP problem: // min 0.5 * u * K * u // s.t. C * u = d. // The KKT system: // K * u + C' * la = 0 // C * u = d // [K, C'] * [u ] = [0] // [C, 0] [la] [d] SparseMatrixElements KC_nonzeros = K_nonzeros; for (const auto& triplet : C_nonzeros) { const int row = triplet.row(); const int col = triplet.col(); const real val = triplet.value(); KC_nonzeros.push_back(Eigen::Triplet<real>(var_num + row, col, val)); KC_nonzeros.push_back(Eigen::Triplet<real>(col, var_num + row, val)); } KC_ = ToSparseMatrix(var_num + C_row_num, var_num + C_row_num, KC_nonzeros); VectorXr d_ext = VectorXr::Zero(var_num + C_row_num); d_ext.tail(C_row_num) = d; dKC_nonzeros_ = dK_nonzeros; for (int p = 0; p < param_num; ++p) { for (const auto& triplet : dC_nonzeros[p]) { const int row = triplet.row(); const int col = triplet.col(); const real val = triplet.value(); dKC_nonzeros_[p].push_back(Eigen::Triplet<real>(var_num + row, col, val)); dKC_nonzeros_[p].push_back(Eigen::Triplet<real>(col, var_num + row, val)); } } // Solve KC * x = d_ext and compute dloss_dparams. // KC * x = d_ext. // dKC * x + KC * dx = 0. // KC * dx = -dKC * x. // dx = -KC^(-1) * (dKC * x). // dloss_dparams[i] = -dloss_du * (KC^(-1) * (dKC * x))[:var_num]. // So, here is our solution to d_loss_d_params: // - Append 0 to dloss_du so that it has the length (var_num + C_row_num). // - Solve for KC * y = -dloss_du. y = -KC^(-1) * dloss_du. // - For each parameter index i, compute dloss_dparams[i] = y.dot(dKC[i] * x). if (boundary_type_ != BoundaryType::NoSlip && boundary_type_ != BoundaryType::NoSeparation) { PrintError("You must implement delta d_ext since you are using a new boundary type."); } VectorXr x = VectorXr::Zero(var_num + C_row_num); if (qp_solver_name == "eigen") { eigen_solver_.compute(KC_); CheckError(eigen_solver_.info() == Eigen::Success, "SparseLU fails to compute the sparse matrix: " + std::to_string(eigen_solver_.info())); x = eigen_solver_.solve(d_ext); CheckError(eigen_solver_.info() == Eigen::Success, "SparseLU fails to solve d_ext: " + std::to_string(eigen_solver_.info())); } else if (qp_solver_name == "pardiso") { pardiso_solver_.Compute(KC_); x = pardiso_solver_.Solve(d_ext); } else { PrintError("Unsupported QP solver: " + qp_solver_name + ". Please use eigen or pardiso."); } // Sanity check. const real abs_tol = ToReal(1e-4); const real rel_tol = ToReal(1e-3); const real abs_error_x = (KC_ * x - d_ext).norm(); CheckError(abs_error_x <= d_ext.norm() * rel_tol + abs_tol, "QP solver fails to solve d_ext."); // Return the solution. return ToStdVector(x); } template<int dim> const std::vector<real> Scene<dim>::Backward(const std::string& qp_solver_name, const std::vector<real>& forward_result, const std::vector<real>& partial_loss_partial_solution_field) { // Obtain dimension information. const int var_num = shape_.node_num_prod() * dim; const int C_row_num = static_cast<int>(forward_result.size()) - var_num; // - For each parameter index i, compute dloss_dparams[i] = y.dot(dKC[i] * x). VectorXr dloss_du = VectorXr::Zero(var_num + C_row_num); CheckError(static_cast<int>(partial_loss_partial_solution_field.size()) == var_num, "Inconsistent length of partial_loss_partial_solution_field."); for (int i = 0; i < var_num; ++i) dloss_du(i) = partial_loss_partial_solution_field[i]; VectorXr y = VectorXr::Zero(var_num + C_row_num); if (qp_solver_name == "eigen") { y = eigen_solver_.solve(-dloss_du); CheckError(eigen_solver_.info() == Eigen::Success, "SparseLU fails to solve dloss_du: " + std::to_string(eigen_solver_.info())); } else if (qp_solver_name == "pardiso") { y = pardiso_solver_.Solve(-dloss_du); } else { PrintError("Unsupported QP solver: " + qp_solver_name + ". Please use eigen or pardiso."); } const real abs_tol = ToReal(1e-4); const real rel_tol = ToReal(1e-3); const real abs_error_y = (KC_ * y + dloss_du).norm(); CheckError(abs_error_y <= dloss_du.norm() * rel_tol + abs_tol, "QP solver fails to solve dloss_du."); const int param_num = shape_.param_num(); std::vector<real> d_loss_d_params(param_num, 0); #pragma omp parallel for for (int i = 0; i < param_num; ++i) { for (const auto& triplet : dKC_nonzeros_[i]) { d_loss_d_params[i] += y(triplet.row()) * triplet.value() * forward_result[triplet.col()]; } } return d_loss_d_params; } template<int dim> const std::vector<real> Scene<dim>::GetVelocityFieldFromForward(const std::vector<real>& forward_result) const { const int var_num = shape_.node_num_prod() * dim; return std::vector<real>(forward_result.data(), forward_result.data() + var_num); } template<int dim> const int Scene<dim>::GetNodeDof(const std::array<int, dim>& node_idx, const int node_dim) const { return GetIndex(node_idx, shape_.node_nums()) * dim + node_dim; } template<int dim> const real Scene<dim>::GetSignedDistance(const std::array<int, dim>& node_idx) const { return shape_.signed_distance(node_idx); } template<int dim> const std::vector<real> Scene<dim>::GetSignedDistanceGradients(const std::array<int, dim>& node_idx) const { return shape_.signed_distance_gradients(node_idx); } template<int dim> const bool Scene<dim>::IsSolidCell(const std::array<int, dim>& cell_idx) const { const auto& cell = cells_.at(GetIndex(cell_idx, shape_.cell_nums())); return cell.IsSolidCell(); } template<int dim> const bool Scene<dim>::IsFluidCell(const std::array<int, dim>& cell_idx) const { const auto& cell = cells_.at(GetIndex(cell_idx, shape_.cell_nums())); return cell.IsFluidCell(); } template<int dim> const bool Scene<dim>::IsMixedCell(const std::array<int, dim>& cell_idx) const { const auto& cell = cells_.at(GetIndex(cell_idx, shape_.cell_nums())); return cell.IsMixedCell(); } template class Scene<2>; template class Scene<3>;
[ "taodu@csail.mit.edu" ]
taodu@csail.mit.edu
124a4a532085b19df98e63c81d53e994765ed1c5
ddcbd4c166a13283b8cc8b6a6147d789b3214822
/CustomListCtrl/DynDialogItemEx.cpp
81dc773c9933bb21d002e9852bad7b79bd062833
[]
no_license
fenglimin/MultiExplorer
c59999a4c1f3f901c5ad21d74220ffa107e98276
258a5afd80fb299444e81d34bc98e2b641b02dab
refs/heads/master
2021-01-10T11:26:53.429696
2015-12-14T05:19:51
2015-12-14T05:19:51
47,388,433
0
0
null
null
null
null
UTF-8
C++
false
false
15,325
cpp
// DynDialogItemEx.cpp: implementation of the CDynDialogItemEx class. // // Written by Marcel Scherpenisse // mailto:Marcel_Scherpenisse@insad.nl // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name and all copyright // notices remains intact. If the source code in this file is used in // any commercial application then a statement along the lines of // "Portions copyright (c) Marcel Scherpenisse, 2002" must be included in // the startup banner, "About" box or printed documentation. An email // letting me know that you are using it would be nice as well. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability for any damage/loss of business that // this product may cause. // // Expect bugs! ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "DynDialogItemEx.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif struct _RuntimeLicense { LPCTSTR lpszRegisteredControlName; WCHAR *wchLicenseKey; long lLicenseLength; }_TAGRUNTIMELICENSE; /*mgkgtgnnmnmninigthkgogggvmkhinjggnvm*/ //(MS Multimedia MCI Control - mci32.ocx) WCHAR pwchMCIMMControl1LicenseKey[] = { 0x006D, 0x0067, 0x006B, 0x0067, 0x0074, 0x0067, 0x006E, 0x006E, 0x006D, 0x006E, 0x006D, 0x006E, 0x0069, 0x006E, 0x0069, 0x0067, 0x0074, 0x0068, 0x006B, 0x0067, 0x006F, 0x0067, 0x0067, 0x0067, 0x0076, 0x006D, 0x006B, 0x0068, 0x0069, 0x006E, 0x006A, 0x0067, 0x0067, 0x006E, 0x0076, 0x006D }; /*Copyright (c) 1994 */ //(MS Communications Control - mscomm32.ocx) WCHAR pwchMSCOMMLibMSComm1LicenseKey[] = { 0x0043, 0x006F, 0x0070, 0x0079, 0x0072, 0x0069, 0x0067, 0x0068, 0x0074, 0x0020, 0x0028, 0x0063, 0x0029, 0x0020, 0x0031, 0x0039, 0x0039, 0x0034, 0x0020 }; /*72E67120-5959-11cf-91F6-C2863C385E30*/ //(MS Flex Grid Control - msflxgrd.ocx) WCHAR pwchMSFlexGridLibMSFlexGrid1LicenseKey[] = { 0x0037, 0x0032, 0x0045, 0x0036, 0x0037, 0x0031, 0x0032, 0x0030, 0x002D, 0x0035, 0x0039, 0x0035, 0x0039, 0x002D, 0x0031, 0x0031, 0x0063, 0x0066, 0x002D, 0x0039, 0x0031, 0x0046, 0x0036, 0x002D, 0x0043, 0x0032, 0x0038, 0x0036, 0x0033, 0x0043, 0x0033, 0x0038, 0x0035, 0x0045, 0x0033, 0x0030 }; /*mgkgtgnnmnmninigthkgogggvmkhinjggnvm*/ //(MS Masked Edit - msmask32.ocx) WCHAR pwchMSMaskMaskEdBox1LicenseKey[] = { 0x006D, 0x0067, 0x006B, 0x0067, 0x0074, 0x0067, 0x006E, 0x006E, 0x006D, 0x006E, 0x006D, 0x006E, 0x0069, 0x006E, 0x0069, 0x0067, 0x0074, 0x0068, 0x006B, 0x0067, 0x006F, 0x0067, 0x0067, 0x0067, 0x0076, 0x006D, 0x006B, 0x0068, 0x0069, 0x006E, 0x006A, 0x0067, 0x0067, 0x006E, 0x0076, 0x006D }; /*GL........*/ //(MS Grid Control - grid32.ocx) WCHAR pwchMSDBGridDBGridLicenseKey[] = { 0x0047, 0x004C, 0x0005, 0x0008, 0x0001, 0x0005, 0x0002, 0x0008, 0x0001, 0x0004 }; /*DB4C0D09-400B-101B-A3C9-08002B2F49FB*/ //(MS Picture Clip Control - picclp32.ocx) WCHAR pwchPicClipPictureClip1LicenseKey[] = { 0x0044, 0x0042, 0x0034, 0x0043, 0x0030, 0x0044, 0x0030, 0x0039, 0x002D, 0x0034, 0x0030, 0x0030, 0x0042, 0x002D, 0x0031, 0x0030, 0x0031, 0x0042, 0x002D, 0x0041, 0x0033, 0x0043, 0x0039, 0x002D, 0x0030, 0x0038, 0x0030, 0x0030, 0x0032, 0x0042, 0x0032, 0x0046, 0x0034, 0x0039, 0x0046, 0x0042 }; /*04746E60CE4F11CDB23C0000C076FE*/ //(MS Tab Control - tabctl32.ocx) static WCHAR pwchTabDlgSSTab1LicenseKey[] = { 0x0030, 0x0034, 0x0037, 0x0034, 0x0036, 0x0045, 0x0036, 0x0030, 0x0043, 0x0045, 0x0034, 0x0046, 0x0031, 0x0031, 0x0043, 0x0044, 0x0042, 0x0032, 0x0033, 0x0043, 0x0030, 0x0030, 0x0030, 0x0030, 0x0043, 0x0030, 0x0037, 0x0036, 0x0046, 0x0045 }; static _RuntimeLicense RuntimeLicenses[] = { {_T("MCI.MMControl.1"), pwchMCIMMControl1LicenseKey, sizeof(pwchMCIMMControl1LicenseKey)}, {_T("MSCOMMLib.MSComm.1"), pwchMSCOMMLibMSComm1LicenseKey, sizeof(pwchMSCOMMLibMSComm1LicenseKey)}, {_T("MSFlexGridLib.MSFlexGrid.1"), pwchMSFlexGridLibMSFlexGrid1LicenseKey, sizeof(pwchMSFlexGridLibMSFlexGrid1LicenseKey)}, {_T("MSMask.MaskEdBox.1"), pwchMSMaskMaskEdBox1LicenseKey, sizeof(pwchMSMaskMaskEdBox1LicenseKey)}, {_T("MSDBGrid.DBGrid"), pwchMSDBGridDBGridLicenseKey, sizeof(pwchMSDBGridDBGridLicenseKey)}, {_T("PicClip.PictureClip.1"), pwchPicClipPictureClip1LicenseKey, sizeof(pwchPicClipPictureClip1LicenseKey)}, {_T("TabDlg.SSTab.1"), pwchTabDlgSSTab1LicenseKey, sizeof(pwchTabDlgSSTab1LicenseKey)}, {NULL, NULL, 0} }; static UINT glb_nNextID = WM_USER; // We have to start somewhere... UINT GetNewUniqueID(void) { glb_nNextID++; return glb_nNextID - 1; } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDynDialogItemEx::CDynDialogItemEx() : CWnd() { m_eTypeControl = NOCONTROL; m_strClassName = _T(""); m_dwStyle = 0; m_dwStyleEx = 0; m_strCaption = _T(""); m_ControlID = 0; m_pData = NULL; m_bSubclassed = FALSE; } void CDynDialogItemEx::DoDataExchange(CDataExchange *pDX) { if (m_pData != NULL) { switch(m_eTypeControl) { case BUTTON: if ((m_dwStyle & BS_AUTORADIOBUTTON) == BS_AUTORADIOBUTTON) { DDX_Radio(pDX, m_ControlID, *(int*)m_pData); } else if ((m_dwStyle & BS_AUTOCHECKBOX) == BS_AUTOCHECKBOX) { DDX_Check(pDX, m_ControlID, *(int*)m_pData); } else { DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); } break; case EDITCONTROL: DDX_Text(pDX, m_ControlID, *(CString*)m_pData); break; case STATICTEXT: DDX_Text(pDX, m_ControlID, *(CString*)m_pData); break; case LISTBOX: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case HSCROLL: DDX_Scroll(pDX, m_ControlID, *(int*)m_pData); break; case COMBOBOX: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case SPIN: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case PROGRES: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case SLIDER: DDX_Slider(pDX, m_ControlID, *(int*)m_pData); break; case HOTKEY: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case LISTCTRL: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case TREECTRL: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case TABCTRL: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case ANIMATE: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case RICHEDIT: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case DATETIMEPICKER: //if ((m_dwStyle & DTS_TIMEFORMAT) == DTS_TIMEFORMAT) { //DDX_DateTimeCtrl(pDX, m_ControlID, *(CTime*)m_pData); //} //else { DDX_DateTimeCtrl(pDX, m_ControlID, *(COleDateTime*)m_pData); //} break; case MONTHCALENDER: DDX_MonthCalCtrl(pDX, m_ControlID, *(COleDateTime*)m_pData); break; case IPADRESS: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; case COMBOBOXEX: DDX_Control(pDX, m_ControlID, *(CWnd*)m_pData); break; default: break; } } CWnd::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDynDialogItemEx, CWnd) //{{AFX_MSG_MAP(CDynDialogItemEx) //}}AFX_MSG_MAP END_MESSAGE_MAP() char* CDynDialogItemEx::GetClassNameByType(DLGITEMTEMPLATECONTROLS TypeControl) { switch(TypeControl) { case BUTTON: return _T("BUTTON"); case EDITCONTROL: return _T("EDIT"); case STATICTEXT: return _T("STATIC"); case LISTBOX: return _T("LISTBOX"); case HSCROLL: return _T("SCROLLBAR"); case COMBOBOX: return _T("COMBOBOX"); case SPIN: return _T("msctls_updown32"); case PROGRES: return _T("msctls_progress32"); case SLIDER: return _T("msctls_trackbar32"); case HOTKEY: return _T("msctls_hotkey32"); case LISTCTRL: return _T("SysListView32"); case TREECTRL: return _T("SysTreeView32"); case TABCTRL: return _T("SysTabControl32"); case ANIMATE: return _T("SysAnimate32"); case RICHEDIT: return _T("RICHEDIT"); case DATETIMEPICKER: return _T("SysDateTimePick32"); case MONTHCALENDER: return _T("SysMonthCal32"); case IPADRESS: return _T("SysIPAddress32"); case COMBOBOXEX: return _T("ComboBoxEx32"); } return _T(""); } DLGITEMTEMPLATECONTROLS CDynDialogItemEx::GetClassTypeByName(LPCSTR lpszClassName) { if (memcmp(lpszClassName, _T("BUTTON"), 6) == 0) { return BUTTON; } else if (memcmp(lpszClassName, _T("EDIT"), 4) == 0) { return EDITCONTROL; } else if (memcmp(lpszClassName, _T("STATIC"), 6) == 0) { return STATICTEXT; } else if (memcmp(lpszClassName, _T("LISTBOX"), 7) == 0) { return LISTBOX; } else if (memcmp(lpszClassName, _T("SCROLLBAR"), 9) == 0) { return HSCROLL; } else if (memcmp(lpszClassName, _T("COMBOBOX"), 8) == 0) { return COMBOBOX; } else if (memcmp(lpszClassName, _T("msctls_updown32"), 15) == 0) { return SPIN; } else if (memcmp(lpszClassName, _T("msctls_progress32"), 17) == 0) { return PROGRES; } else if (memcmp(lpszClassName, _T("msctls_trackbar32"), 17) == 0) { return SLIDER; } else if (memcmp(lpszClassName, _T("msctls_hotkey32"), 15) == 0) { return HOTKEY; } else if (memcmp(lpszClassName, _T("SysListView32"), 13) == 0) { return LISTCTRL; } else if (memcmp(lpszClassName, _T("SysTreeView32"), 13) == 0) { return TREECTRL; } else if (memcmp(lpszClassName, _T("SysTabControl32"), 15) == 0) { return TABCTRL; } else if (memcmp(lpszClassName, _T("SysAnimate32"), 12) == 0) { return ANIMATE; } else if (memcmp(lpszClassName, _T("RICHEDIT"), 8) == 0) { return RICHEDIT; } else if (memcmp(lpszClassName, _T("SysDateTimePick32"), 17) == 0) { return DATETIMEPICKER; } else if (memcmp(lpszClassName, _T("SysMonthCal32"), 13) == 0) { return MONTHCALENDER; } else if (memcmp(lpszClassName, _T("SysIPAddress32"), 14) == 0) { return IPADRESS; } else if (memcmp(lpszClassName, _T("ComboBoxEx32"), 12) == 0) { return COMBOBOXEX; } return NOCONTROL; } UINT CDynDialogItemEx::InitDialogItem(DLGITEMTEMPLATECONTROLS TypeControl, DWORD dwStyle, DWORD dwExtendedStyle, LPRECT pRect, LPCTSTR lpszCaption, UINT nID /*= 0*/, BOOL bSubclassed /*= FALSE*/, void *pData /*= NULL*/) { m_eTypeControl = TypeControl; m_strClassName = GetClassNameByType(m_eTypeControl); m_dwStyle = dwStyle; m_dwStyleEx = dwExtendedStyle; m_Rect = pRect; m_strCaption = lpszCaption; m_bSubclassed = bSubclassed; m_pData = pData; if (nID == 0) { m_ControlID = ::GetNewUniqueID(); } else { m_ControlID = nID; } return m_ControlID; } UINT CDynDialogItemEx::InitDialogItem(LPCSTR lpszClassName, DWORD dwStyle, DWORD dwExtendedStyle, LPRECT pRect, LPCTSTR lpszCaption, UINT nID /*= 0*/, BOOL bSubclassed /*= FALSE*/, void *pData /*= NULL*/) { m_strClassName = lpszClassName; m_eTypeControl = GetClassTypeByName(lpszClassName); m_dwStyle = dwStyle; m_dwStyleEx = dwExtendedStyle; m_Rect = pRect; m_strCaption = lpszCaption; m_bSubclassed = bSubclassed; m_pData = pData; if (nID == 0) { m_ControlID = ::GetNewUniqueID(); } else { m_ControlID = nID; } return m_ControlID; } BOOL CDynDialogItemEx::CreateEx(CWnd *pParent) { BOOL bRet = FALSE; if (m_eTypeControl == NOCONTROL) { //It will probably be an OCX... // // Create the control later.... // if it's created here then the rectangle is not OK and SetWindowPos doesn't work on OCX's???? // bRet = TRUE; } else if (m_pData != NULL && IsDataMemberPointerToWnd()) { bRet = ((CWnd*)m_pData)->CreateEx(m_dwStyleEx, m_strClassName, m_strCaption, m_dwStyle, m_Rect, pParent, m_ControlID); } else { bRet = CWnd::CreateEx(m_dwStyleEx, m_strClassName, m_strCaption, m_dwStyle, m_Rect, pParent, m_ControlID); } return bRet; } BOOL CDynDialogItemEx::SetWindowPos(CWnd *pParent) { BOOL bRet = FALSE; //Conversion of Dialog units to screenunits CRect rect(m_Rect); ((CDialog *)pParent)->MapDialogRect(&rect); ASSERT(rect.IsRectEmpty() == FALSE); if (m_eTypeControl == NOCONTROL) { BSTR bstrLicKey = GetRuntimeLicense(m_strClassName); bRet = CreateControl(m_strClassName, m_strCaption, m_dwStyle, rect, pParent, m_ControlID, NULL, FALSE, bstrLicKey); if (bstrLicKey != NULL) { ::SysFreeString(bstrLicKey); } } else if (m_pData != NULL && IsDataMemberPointerToWnd()) { bRet = ((CWnd*)m_pData)->SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOZORDER); } else { bRet = CWnd::SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOZORDER); } return bRet; } void CDynDialogItemEx::SetFont(CFont* pFont, BOOL bRedraw /*= TRUE*/) { if (m_pData != NULL && IsDataMemberPointerToWnd()) { ((CWnd*)m_pData)->SetFont(pFont, bRedraw); } else { CWnd::SetFont(pFont, bRedraw); } } PBYTE CDynDialogItemEx::FillBufferWithItemTemplate(BYTE *pdest) { pdest = (BYTE*)(((DWORD)pdest + 3) & ~3); // make the pointer DWORD aligned DLGITEMTEMPLATE dlgItemTemplate; dlgItemTemplate.x = (short)m_Rect.left; dlgItemTemplate.y = (short)m_Rect.top; dlgItemTemplate.cx = (short)m_Rect.Width(); dlgItemTemplate.cy = (short)m_Rect.Height(); dlgItemTemplate.style = m_dwStyle; dlgItemTemplate.dwExtendedStyle = m_dwStyleEx; dlgItemTemplate.id = (USHORT)m_ControlID; memcpy(pdest, (void *)&dlgItemTemplate, sizeof(DLGITEMTEMPLATE)); pdest += sizeof(DLGITEMTEMPLATE); *(WORD*)pdest = 0xFFFF; // indicating atom value pdest += sizeof(WORD); *(WORD*)pdest = (USHORT)m_eTypeControl; // atom value for the control pdest += sizeof(WORD); // transfer the caption even when it is an empty string WCHAR* pchCaption; int nChars, nActualChars; nChars = m_strCaption.GetLength() + 1; pchCaption = new WCHAR[nChars]; nActualChars = MultiByteToWideChar(CP_ACP, 0, m_strCaption, -1, pchCaption, nChars); ASSERT(nActualChars > 0); memcpy(pdest, pchCaption, nActualChars * sizeof(WCHAR)); pdest += nActualChars * sizeof(WCHAR); delete pchCaption; *(WORD*)pdest = 0; // How many bytes in data for control pdest += sizeof(WORD); return pdest; } BSTR CDynDialogItemEx::GetRuntimeLicense(CString &strControlName) { BSTR bstrLicKey = NULL; int i = 0; while (RuntimeLicenses[i].lpszRegisteredControlName != NULL) { if (strControlName.Compare(RuntimeLicenses[i].lpszRegisteredControlName) == 0) { bstrLicKey = ::SysAllocStringLen(RuntimeLicenses[i].wchLicenseKey, RuntimeLicenses[i].lLicenseLength/sizeof(WCHAR)); break; } i++; } return bstrLicKey; } BOOL CDynDialogItemEx::IsDataMemberPointerToWnd() { BOOL bRet = TRUE; switch(m_eTypeControl) { case BUTTON: if ((m_dwStyle & BS_AUTORADIOBUTTON) == BS_AUTORADIOBUTTON) { bRet = FALSE; } else if ((m_dwStyle & BS_AUTOCHECKBOX) == BS_AUTOCHECKBOX) { bRet = FALSE; } break; case EDITCONTROL: bRet = FALSE; break; case STATICTEXT: bRet = FALSE; break; case HSCROLL: bRet = FALSE; break; case SLIDER: bRet = FALSE; break; case DATETIMEPICKER: bRet = FALSE; break; case MONTHCALENDER: bRet = FALSE; break; default: break; } return bRet; }
[ "mailflm@163.com" ]
mailflm@163.com
6ceb623863b9ce8aeff572bb1538c06aaf113c1f
3c188593997cc06eab489328d81a661de16eb9fe
/src/qt/receiverequestdialog.cpp
fd0f90be03ec27b9064ac29bb313455519025862
[ "MIT" ]
permissive
yangchigi/BitHao-Source
304fc1ec94e985090ccced61a008defd61a523dc
76f330020a917d6680d3d15867773afc6887d541
refs/heads/master
2020-05-05T12:49:45.934520
2019-02-28T05:32:44
2019-02-28T05:32:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,621
cpp
// Copyright (c) 2011-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "receiverequestdialog.h" #include "ui_receiverequestdialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "walletmodel.h" #include <QClipboard> #include <QDrag> #include <QMenu> #include <QMimeData> #include <QMouseEvent> #include <QPixmap> #if QT_VERSION < 0x050000 #include <QUrl> #endif #if defined(HAVE_CONFIG_H) #include "config/bithao-config.h" /* for USE_QRCODE */ #endif #ifdef USE_QRCODE #include <qrencode.h> #endif QRImageWidget::QRImageWidget(QWidget *parent): QLabel(parent), contextMenu(0) { contextMenu = new QMenu(this); QAction *saveImageAction = new QAction(tr("&Save Image..."), this); connect(saveImageAction, SIGNAL(triggered()), this, SLOT(saveImage())); contextMenu->addAction(saveImageAction); QAction *copyImageAction = new QAction(tr("&Copy Image"), this); connect(copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage())); contextMenu->addAction(copyImageAction); } QImage QRImageWidget::exportImage() { if(!pixmap()) return QImage(); return pixmap()->toImage().scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE); } void QRImageWidget::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton && pixmap()) { event->accept(); QMimeData *mimeData = new QMimeData; mimeData->setImageData(exportImage()); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); drag->exec(); } else { QLabel::mousePressEvent(event); } } void QRImageWidget::saveImage() { if(!pixmap()) return; QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL); if (!fn.isEmpty()) { exportImage().save(fn); } } void QRImageWidget::copyImage() { if(!pixmap()) return; QApplication::clipboard()->setImage(exportImage()); } void QRImageWidget::contextMenuEvent(QContextMenuEvent *event) { if(!pixmap()) return; contextMenu->exec(event->globalPos()); } ReceiveRequestDialog::ReceiveRequestDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveRequestDialog), model(0) { ui->setupUi(this); #ifndef USE_QRCODE ui->btnSaveAs->setVisible(false); ui->lblQRCode->setVisible(false); #endif connect(ui->btnSaveAs, SIGNAL(clicked()), ui->lblQRCode, SLOT(saveImage())); } ReceiveRequestDialog::~ReceiveRequestDialog() { delete ui; } void ReceiveRequestDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(update())); // update the display unit if necessary update(); } void ReceiveRequestDialog::setInfo(const SendCoinsRecipient &info) { this->info = info; update(); } void ReceiveRequestDialog::update() { if(!model) return; QString target = info.label; if(target.isEmpty()) target = info.address; setWindowTitle(tr("Request payment to %1").arg(target)); QString uri = GUIUtil::formatBitcoinURI(info); ui->btnSaveAs->setEnabled(false); QString html; html += "<html><font face='verdana, arial, helvetica, sans-serif'>"; html += "<b>"+tr("Payment information")+"</b><br>"; html += "<b>"+tr("URI")+"</b>: "; html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>"; html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>"; if(info.amount) html += "<b>"+tr("Amount")+"</b>: " + BitcoinUnits::formatHtmlWithUnit(model->getDisplayUnit(), info.amount) + "<br>"; if(!info.label.isEmpty()) html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>"; if(!info.message.isEmpty()) html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>"; html += "<b>"+tr("InstantSend")+"</b>: " + (info.fUseInstantSend ? tr("Yes") : tr("No")) + "<br>"; ui->outUri->setText(html); #ifdef USE_QRCODE ui->lblQRCode->setText(""); if(!uri.isEmpty()) { // limit URI length if (uri.length() > MAX_URI_LENGTH) { ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); } else { QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->btnSaveAs->setEnabled(true); } } #endif } void ReceiveRequestDialog::on_btnCopyURI_clicked() { GUIUtil::setClipboard(GUIUtil::formatBitcoinURI(info)); } void ReceiveRequestDialog::on_btnCopyAddress_clicked() { GUIUtil::setClipboard(info.address); }
[ "48000899+cqcrypto@users.noreply.github.com" ]
48000899+cqcrypto@users.noreply.github.com
390fdba212421b7bd2870c4511e8c494088672bb
f9c49badd8b655b080ac98c99e4d1644000a3500
/Casino-Number-Guessing-Game.cpp
05704ae9fb7fa832daa3d9c04d18da7874c1eae4
[]
no_license
FurkanCiftcibasi/Casino-Number-Guessing-Game
79daab66c629b8593aa71002ca89049442008617
5e702ada3823edab7bad2f11287735caa7d8f408
refs/heads/main
2023-06-13T08:05:24.554719
2021-07-02T21:23:43
2021-07-02T21:23:43
382,055,537
0
0
null
null
null
null
UTF-8
C++
false
false
2,080
cpp
#include <iostream> #include <time.h> // Casino number guessing game int main() { int DiceRoll, RndRange{}, GuessNumber, Choice; srand(time(NULL)); // Input Begin: std::cout << "(1) for custom range (2) for random range [Limit 100]\n"; std::cin >> Choice; if (Choice == 1) { goto Switch; } else if (Choice == 2) { goto Switch; } else { std::cout << "Choose either 1 or 2.\n"; goto Begin; } Switch: switch (Choice) { case 1: { Range: std::cout << "Enter a custom range: \n"; std::cin >> RndRange; if (RndRange > 100) { std::cout << "Your choice can't be higher than 100.\n"; goto Range; } DiceRoll = rand() % RndRange + 1; goto Guess; // 1- Input // std::cout << DiceRoll << "\n"; break; } case 2: { DiceRoll = rand() % 100 + 1; RndRange = 100; goto Guess; // 1-100 // std::cout << DiceRoll << "\n"; } Guess: int Guess; std::cout << "What number do you guess? Range (1-" << RndRange << ")\n"; std::cin >> Guess; if (Guess != DiceRoll) { std::cout << "Your guess is wrong "; if (Guess > DiceRoll) { std::cout << "the number is lower.\n"; } else if (Guess < DiceRoll) { std::cout << "the number is higher.\n"; } goto Guess; } else { std::cout << "Congratulations, you guessed it right!"; std::cout << "\n" << "\n" << "\n" << "\n"; } std::string terminate; std::cout << "Enter Q to Quit!\n"; std::cin >> terminate; if (terminate == "q" || terminate == "Q") { exit(1); } } }
[ "noreply@github.com" ]
noreply@github.com
2bc97de9b0740c7ec0bf962a12347c24a1e1bc6b
c654bdb7ff47f8534d2c7eed1bc878bd6209825d
/src/sdchain/overlay/impl/TrafficCount.h
e4d0379641f30f92a296e11e4b3f4aeac01fdc59
[]
no_license
Gamma-Token/SDChain-Core
6c2884b65efc2e53a53a10656b101a335a2ec50b
88dc4cdd7c8f8c04144ffe9acd694958d34703a7
refs/heads/master
2020-06-18T06:37:12.570366
2019-04-29T05:27:18
2019-04-29T05:27:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,810
h
//------------------------------------------------------------------------------ /* This file is part of sdchaind: https://github.com/SDChain/SDChain-core Copyright (c) 2017, 2018 SDChain Alliance. */ //============================================================================== #ifndef SDCHAIN_OVERLAY_TRAFFIC_H_INCLUDED #define SDCHAIN_OVERLAY_TRAFFIC_H_INCLUDED #include "sdchain.pb.h" #include <atomic> #include <map> namespace sdchain { class TrafficCount { public: using count_t = std::atomic <unsigned long>; class TrafficStats { public: count_t bytesIn; count_t bytesOut; count_t messagesIn; count_t messagesOut; TrafficStats() : bytesIn(0), bytesOut(0), messagesIn(0), messagesOut(0) { ; } TrafficStats(const TrafficStats& ts) : bytesIn (ts.bytesIn.load()) , bytesOut (ts.bytesOut.load()) , messagesIn (ts.messagesIn.load()) , messagesOut (ts.messagesOut.load()) { ; } operator bool () const { return messagesIn || messagesOut; } }; enum class category { CT_base, // basic peer overhead, must be first CT_overlay, // overlay management CT_transaction, CT_proposal, CT_validation, CT_get_ledger, // ledgers we try to get CT_share_ledger, // ledgers we share CT_get_trans, // transaction sets we try to get CT_share_trans, // transaction sets we get CT_unknown // must be last }; static const char* getName (category c); static category categorize ( ::google::protobuf::Message const& message, int type, bool inbound); void addCount (category cat, bool inbound, int number) { if (inbound) { counts_[cat].bytesIn += number; ++counts_[cat].messagesIn; } else { counts_[cat].bytesOut += number; ++counts_[cat].messagesOut; } } TrafficCount() { for (category i = category::CT_base; i <= category::CT_unknown; i = static_cast<category>(static_cast<int>(i) + 1)) { counts_[i]; } } std::map <std::string, TrafficStats> getCounts () const { std::map <std::string, TrafficStats> ret; for (auto& i : counts_) { if (i.second) ret.emplace (std::piecewise_construct, std::forward_as_tuple (getName (i.first)), std::forward_as_tuple (i.second)); } return ret; } protected: std::map <category, TrafficStats> counts_; }; } #endif
[ "996707589@qq.com" ]
996707589@qq.com
847c267963fe7865af916f6c46bf0267db534435
b0dd7779c225971e71ae12c1093dc75ed9889921
/boost/mpl/assert.hpp
aa275a042d0b334c10a6176ca656b2b654da6d4c
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
12,674
hpp
#ifndef BOOST_MPL_ASSERT_HPP_INCLUDED #define BOOST_MPL_ASSERT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2006 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: assert.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/not.hpp> #include <boost/mpl/aux_/value_wknd.hpp> #include <boost/mpl/aux_/nested_type_wknd.hpp> #include <boost/mpl/aux_/yes_no.hpp> #include <boost/mpl/aux_/na.hpp> #include <boost/mpl/aux_/adl_barrier.hpp> #include <boost/mpl/aux_/config/nttp.hpp> #include <boost/mpl/aux_/config/dtp.hpp> #include <boost/mpl/aux_/config/gcc.hpp> #include <boost/mpl/aux_/config/msvc.hpp> #include <boost/mpl/aux_/config/static_constant.hpp> #include <boost/mpl/aux_/config/pp_counter.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/config.hpp> // make sure 'size_t' is placed into 'std' #include <cstddef> #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) \ || (BOOST_MPL_CFG_GCC != 0) \ || BOOST_WORKAROUND(__IBMCPP__, <= 600) # define BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES #endif #if BOOST_WORKAROUND(__MWERKS__, < 0x3202) \ || BOOST_WORKAROUND(__EDG_VERSION__, <= 238) \ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) \ || BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840)) # define BOOST_MPL_CFG_ASSERT_BROKEN_POINTER_TO_POINTER_TO_MEMBER #endif // agurt, 10/nov/06: use enums for Borland (which cannot cope with static constants) // and GCC (which issues "unused variable" warnings when static constants are used // at a function scope) #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) \ || (BOOST_MPL_CFG_GCC != 0) # define BOOST_MPL_AUX_ASSERT_CONSTANT(T, expr) enum { expr } #else # define BOOST_MPL_AUX_ASSERT_CONSTANT(T, expr) BOOST_STATIC_CONSTANT(T, expr) #endif BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN struct failed {}; // agurt, 24/aug/04: MSVC 7.1 workaround here and below: return/accept // 'assert<false>' by reference; can't apply it unconditionally -- apparently it // degrades the quality of GCC diagnostics #if BOOST_WORKAROUND(BOOST_MSVC, == 1310) # define AUX778076_ASSERT_ARG(x) x& #else # define AUX778076_ASSERT_ARG(x) x #endif template< bool C > struct assert { typedef void* type; }; template<> struct assert<false> { typedef AUX778076_ASSERT_ARG(assert) type; }; template< bool C > int assertion_failed( typename assert<C>::type ); template< bool C > struct assertion { static int failed( assert<false> ); }; template<> struct assertion<true> { static int failed( void* ); }; struct assert_ { #if !defined(BOOST_MPL_CFG_NO_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES) template< typename T1, typename T2 = na, typename T3 = na, typename T4 = na > struct types {}; #endif static assert_ const arg; enum relations { equal = 1, not_equal, greater, greater_equal, less, less_equal }; }; #if !defined(BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES) bool operator==( failed, failed ); bool operator!=( failed, failed ); bool operator>( failed, failed ); bool operator>=( failed, failed ); bool operator<( failed, failed ); bool operator<=( failed, failed ); #if defined(__EDG_VERSION__) template< bool (*)(failed, failed), long x, long y > struct assert_relation {}; # define BOOST_MPL_AUX_ASSERT_RELATION(x, y, r) assert_relation<r,x,y> #else template< BOOST_MPL_AUX_NTTP_DECL(long, x), BOOST_MPL_AUX_NTTP_DECL(long, y), bool (*)(failed, failed) > struct assert_relation {}; # define BOOST_MPL_AUX_ASSERT_RELATION(x, y, r) assert_relation<x,y,r> #endif #else // BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES boost::mpl::aux::weighted_tag<1>::type operator==( assert_, assert_ ); boost::mpl::aux::weighted_tag<2>::type operator!=( assert_, assert_ ); boost::mpl::aux::weighted_tag<3>::type operator>( assert_, assert_ ); boost::mpl::aux::weighted_tag<4>::type operator>=( assert_, assert_ ); boost::mpl::aux::weighted_tag<5>::type operator<( assert_, assert_ ); boost::mpl::aux::weighted_tag<6>::type operator<=( assert_, assert_ ); template< assert_::relations r, long x, long y > struct assert_relation {}; #endif #if !defined(BOOST_MPL_CFG_ASSERT_BROKEN_POINTER_TO_POINTER_TO_MEMBER) template< bool > struct assert_arg_pred_impl { typedef int type; }; template<> struct assert_arg_pred_impl<true> { typedef void* type; }; template< typename P > struct assert_arg_pred { typedef typename P::type p_type; typedef typename assert_arg_pred_impl< p_type::value >::type type; }; template< typename P > struct assert_arg_pred_not { typedef typename P::type p_type; BOOST_MPL_AUX_ASSERT_CONSTANT( bool, p = !p_type::value ); typedef typename assert_arg_pred_impl<p>::type type; }; template< typename Pred > failed ************ (Pred::************ assert_arg( void (*)(Pred), typename assert_arg_pred<Pred>::type ) ); template< typename Pred > failed ************ (boost::mpl::not_<Pred>::************ assert_not_arg( void (*)(Pred), typename assert_arg_pred_not<Pred>::type ) ); template< typename Pred > AUX778076_ASSERT_ARG(assert<false>) assert_arg( void (*)(Pred), typename assert_arg_pred_not<Pred>::type ); template< typename Pred > AUX778076_ASSERT_ARG(assert<false>) assert_not_arg( void (*)(Pred), typename assert_arg_pred<Pred>::type ); #else // BOOST_MPL_CFG_ASSERT_BROKEN_POINTER_TO_POINTER_TO_MEMBER template< bool c, typename Pred > struct assert_arg_type_impl { typedef failed ************ Pred::* mwcw83_wknd; typedef mwcw83_wknd ************* type; }; template< typename Pred > struct assert_arg_type_impl<true,Pred> { typedef AUX778076_ASSERT_ARG(assert<false>) type; }; template< typename Pred > struct assert_arg_type : assert_arg_type_impl< BOOST_MPL_AUX_VALUE_WKND(BOOST_MPL_AUX_NESTED_TYPE_WKND(Pred))::value, Pred > { }; template< typename Pred > typename assert_arg_type<Pred>::type assert_arg(void (*)(Pred), int); template< typename Pred > typename assert_arg_type< boost::mpl::not_<Pred> >::type assert_not_arg(void (*)(Pred), int); # if !defined(BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES) template< long x, long y, bool (*r)(failed, failed) > typename assert_arg_type_impl< false,BOOST_MPL_AUX_ASSERT_RELATION(x,y,r) >::type assert_rel_arg( BOOST_MPL_AUX_ASSERT_RELATION(x,y,r) ); # else template< assert_::relations r, long x, long y > typename assert_arg_type_impl< false,assert_relation<r,x,y> >::type assert_rel_arg( assert_relation<r,x,y> ); # endif #endif // BOOST_MPL_CFG_ASSERT_BROKEN_POINTER_TO_POINTER_TO_MEMBER #undef AUX778076_ASSERT_ARG BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE // BOOST_MPL_ASSERT((pred<x,...>)) #define BOOST_MPL_ASSERT(pred) \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,BOOST_MPL_AUX_PP_COUNTER()) = sizeof( \ boost::mpl::assertion_failed<false>( \ boost::mpl::assert_arg( (void (*) pred)0, 1 ) \ ) \ ) \ ) \ /**/ // BOOST_MPL_ASSERT_NOT((pred<x,...>)) #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) # define BOOST_MPL_ASSERT_NOT(pred) \ enum { \ BOOST_PP_CAT(mpl_assertion_in_line_,BOOST_MPL_AUX_PP_COUNTER()) = sizeof( \ boost::mpl::assertion<false>::failed( \ boost::mpl::assert_not_arg( (void (*) pred)0, 1 ) \ ) \ ) \ }\ /**/ #else # define BOOST_MPL_ASSERT_NOT(pred) \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,BOOST_MPL_AUX_PP_COUNTER()) = sizeof( \ boost::mpl::assertion_failed<false>( \ boost::mpl::assert_not_arg( (void (*) pred)0, 1 ) \ ) \ ) \ ) \ /**/ #endif // BOOST_MPL_ASSERT_RELATION(x, ==|!=|<=|<|>=|>, y) #if defined(BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES) # if !defined(BOOST_MPL_CFG_ASSERT_BROKEN_POINTER_TO_POINTER_TO_MEMBER) // agurt, 9/nov/06: 'enum' below is a workaround for gcc 4.0.4/4.1.1 bugs #29522 and #29518 # define BOOST_MPL_ASSERT_RELATION_IMPL(counter, x, rel, y) \ enum { BOOST_PP_CAT(mpl_assert_rel_value,counter) = (x rel y) }; \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,counter) = sizeof( \ boost::mpl::assertion_failed<BOOST_PP_CAT(mpl_assert_rel_value,counter)>( \ (boost::mpl::failed ************ ( boost::mpl::assert_relation< \ boost::mpl::assert_::relations( sizeof( \ boost::mpl::assert_::arg rel boost::mpl::assert_::arg \ ) ) \ , x \ , y \ >::************)) 0 ) \ ) \ ) \ /**/ # else # define BOOST_MPL_ASSERT_RELATION_IMPL(counter, x, rel, y) \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assert_rel,counter) = sizeof( \ boost::mpl::assert_::arg rel boost::mpl::assert_::arg \ ) \ ); \ BOOST_MPL_AUX_ASSERT_CONSTANT( bool, BOOST_PP_CAT(mpl_assert_rel_value,counter) = (x rel y) ); \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,counter) = sizeof( \ boost::mpl::assertion_failed<BOOST_PP_CAT(mpl_assert_rel_value,counter)>( \ boost::mpl::assert_rel_arg( boost::mpl::assert_relation< \ boost::mpl::assert_::relations(BOOST_PP_CAT(mpl_assert_rel,counter)) \ , x \ , y \ >() ) \ ) \ ) \ ) \ /**/ # endif # define BOOST_MPL_ASSERT_RELATION(x, rel, y) \ BOOST_MPL_ASSERT_RELATION_IMPL(BOOST_MPL_AUX_PP_COUNTER(), x, rel, y) \ /**/ #else // !BOOST_MPL_CFG_ASSERT_USE_RELATION_NAMES # if defined(BOOST_MPL_CFG_ASSERT_BROKEN_POINTER_TO_POINTER_TO_MEMBER) # define BOOST_MPL_ASSERT_RELATION(x, rel, y) \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,BOOST_MPL_AUX_PP_COUNTER()) = sizeof( \ boost::mpl::assertion_failed<(x rel y)>( boost::mpl::assert_rel_arg( \ boost::mpl::BOOST_MPL_AUX_ASSERT_RELATION(x,y,(&boost::mpl::operator rel))() \ ) ) \ ) \ ) \ /**/ # else # define BOOST_MPL_ASSERT_RELATION(x, rel, y) \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,BOOST_MPL_AUX_PP_COUNTER()) = sizeof( \ boost::mpl::assertion_failed<(x rel y)>( (boost::mpl::failed ************ ( \ boost::mpl::BOOST_MPL_AUX_ASSERT_RELATION(x,y,(&boost::mpl::operator rel))::************))0 ) \ ) \ ) \ /**/ # endif #endif // BOOST_MPL_ASSERT_MSG( (pred<x,...>::value), USER_PROVIDED_MESSAGE, (types<x,...>) ) #if BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3202)) # define BOOST_MPL_ASSERT_MSG_IMPL( counter, c, msg, types_ ) \ struct msg; \ typedef struct BOOST_PP_CAT(msg,counter) : boost::mpl::assert_ \ { \ using boost::mpl::assert_::types; \ static boost::mpl::failed ************ (msg::************ assert_arg()) types_ \ { return 0; } \ } BOOST_PP_CAT(mpl_assert_arg,counter); \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,counter) = sizeof( \ boost::mpl::assertion<(c)>::failed( BOOST_PP_CAT(mpl_assert_arg,counter)::assert_arg() ) \ ) \ ) \ /**/ #else # define BOOST_MPL_ASSERT_MSG_IMPL( counter, c, msg, types_ ) \ struct msg; \ typedef struct BOOST_PP_CAT(msg,counter) : boost::mpl::assert_ \ { \ static boost::mpl::failed ************ (msg::************ assert_arg()) types_ \ { return 0; } \ } BOOST_PP_CAT(mpl_assert_arg,counter); \ BOOST_MPL_AUX_ASSERT_CONSTANT( \ std::size_t \ , BOOST_PP_CAT(mpl_assertion_in_line_,counter) = sizeof( \ boost::mpl::assertion_failed<(c)>( BOOST_PP_CAT(mpl_assert_arg,counter)::assert_arg() ) \ ) \ ) \ /**/ #endif #define BOOST_MPL_ASSERT_MSG( c, msg, types_ ) \ BOOST_MPL_ASSERT_MSG_IMPL( BOOST_MPL_AUX_PP_COUNTER(), c, msg, types_ ) \ /**/ #endif // BOOST_MPL_ASSERT_HPP_INCLUDED
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
566c205be8b96a586711e59fcbfceba1ce098e50
2501133cffae109f561ccd0ea2061dd2c92cabd6
/etc/dark-c/src/low.cpp
78dc61fcb62578a2d469cca711b1e5e1b36a2a0b
[ "MIT" ]
permissive
kvark/dark
c7eba303c0101d29bf4281ce280b6e088f07c3c6
50174d101e798b91fe583e2430d40df971050792
refs/heads/master
2020-05-27T21:35:30.644111
2015-07-03T02:59:32
2015-07-03T02:59:32
16,617,787
6
0
null
2014-02-21T03:44:03
2014-02-07T15:00:47
Rust
UTF-8
C++
false
false
4,568
cpp
/* * Low-level coding routines * (C) kvark, Aug 2006 */ #include "total.h" #include "ptax.h" /* ark section */ #define BOT (1<<14) #define RESTUP 8 namespace ark { tbord lo,hi,rng,code; FILE *f; char act; void nben() { fputc(lo>>24,f); } void nbde() { code = (code<<8)|fgetc(f); } void Set(char nact, FILE *nf) { act=nact; f=nf; } void Init() { lo=0; rng=(uint)(-1); } void StartDecode() { for(char i=0;i<4;i++) nbde(); } void FinalEncode() { for(char i=0;i<4;i++) nben(),lo<<=8; } void parse(tfreq,tfreq); void State(FILE *ff) { fprintf(ff,"\n\tLow:%8x Rng:%8x",lo,rng);} } void ark::parse(tfreq toff, tfreq tran) { Info("\n\tProcessing [%d-%d)", toff, toff+tran); lo += rng*toff; rng *= tran; //main [en|de]coding loop do { hi = lo+rng; if((lo^hi)>=1<<24) { if(rng>BOT) break; tbord lim = hi&0xFF000000; if(hi-lim >= lim-lo) lo=lim; else hi=lim-1; }do {//shift Info("\n\tShifting on [%u-%u) to symbol %u", lo, hi, lo>>24); act==MDEC ? nbde():nben(); lo<<=8; hi<<=8; }while((lo^hi) < 1<<24); rng = hi-lo; }while(rng<BOT); } #undef BOT /* Eiler section */ int getlog(long ran) { int log; for(log=0; ran>>log; log++); return log; } #define FMB 12 #define FMAX (1<<FMB) #define getfreq(id) (2*t0[id]+t1[id]) void EilerCoder::Update(tfreq *tab, uchar log, uchar sd) { tfreq add = (tab[0]>>sd)+5; tab[log] += add; Info("\n\tUpdating by adding %d to value %d", add, log); if((tab[0] += add) >= FMAX) { int i; Info("\n\tDownscaling frequencies"); for(tab[0]=0,i=1; i<=LIN; i++) tab[0] += (++tab[i] >>= 1); } } void EilerCoder::Parse(tfreq off, uchar log) { ark::parse(off, getfreq(log)); Update(t0,log,a0); Update(t1,log,a1); } void EilerCoder::PutLog(int log) { tfreq fcur; int i; ark::rng /= getfreq(0); Info("\n\tPutting a log %d with total %d of range %u", log, getfreq(0), ark::rng); for(fcur=0,i=1; i<log; i++) fcur += getfreq(i); Parse(fcur, log); } int EilerCoder::GetLog() { int log; ark::rng /= getfreq(0); tfreq fcur,val = (ark::code - ark::lo)/ark::rng; for(fcur=0,log=1; fcur+getfreq(log) <= val; log++) fcur += getfreq(log); Parse(fcur,log); return log; } void EilerCoder::Start(uchar na0, uchar na1, uchar nb0, uchar nb1) { a0=na0; a1=na1; b0=nb0; b1=nb1; InitBits(cbit[0], NB); } void EilerCoder::InitBits(tfreq *v0, int num) { num <<= 5; // for 32 bits while(num--) *v0++ = FMAX>>1; } void EilerCoder::InitFreq(locon *vr, int num) { for(int i=0; i<num; i++) { for(int j=1; j <= LIN; j++) vr[i][j] = 1; vr[i][0] = LIN; } } void EilerCoder::Finish() {} #undef getfreq #define curfreq() ((u[0]+v[0])>>1) #define LOBIT (3+1) //Encoding routine void EilerCoder::EncodeEl(long num, int *pv) { tfreq *u,*v; uchar log; for(log=0; num>>log; log++); if(log >= LIN) { tfreq fcur; uchar fl; PutLog(LIN); for(u=r0,v=r1,fl=LIN; ;fl++,u++,v++) { Info("\n\tAppending bit %d", fl==log); fcur = curfreq(); ark::rng >>= FMB; if(fl == log) break; ark::parse(fcur, FMAX-fcur); Info("\n\tUpdating one with factors %d, %d", b0, b1); u[0] -= u[0]>>b0; v[0] -= v[0]>>b1; }//stop bit ark::parse(0, fcur); Info("\n\tUpdating zero with factors %d, %d", b0, b1); u[0] += (FMAX-u[0])>>b0; v[0] += (FMAX-v[0])>>b1; }else PutLog(log); u = cbit[log]; for(int i=log-2; i>=0; i--,u++) { Info("\n\tCoding bit %d at position %d", (num>>i)&1, i); bool upd = (i>=log-LOBIT); ark::rng >>= FMB; if(num & (1<<i)) { ark::parse(u[0], FMAX-u[0]); if(upd) u[0] -= u[0]>>RESTUP; }else { ark::parse(0, u[0]); if(upd) u[0] += (FMAX-u[0])>>RESTUP; } if (upd) Info("\n\tUpdating bit %d with factor %d", (num>>i)&1, RESTUP); }pv[0]=log; } //Decoding routine long EilerCoder::DecodeEl(int *pv) { tbord val; ulong ran; tfreq *u,*v; uchar log; if((log = GetLog()) == LIN) { tfreq fcur; for(u=r0,v=r1; ;log++,u++,v++) { ark::rng >>= FMB; fcur = curfreq(); val = ark::code - ark::lo; if(val < fcur * ark::rng) break; ark::parse(fcur, FMAX-fcur); u[0] -= u[0]>>b0; v[0] -= v[0]>>b1; }//stop bit ark::parse(0, fcur); u[0] += (FMAX-u[0])>>b0; v[0] += (FMAX-v[0])>>b1; }//the rest u = cbit[log]; ran = 1<<(log-1); for(int i=log-2; i>=0; i--,u++) { bool upd = (i>=log-LOBIT); ark::rng >>= FMB; val = ark::code - ark::lo; if(val >= u[0] * ark::rng) { ran |= 1<<i; ark::parse(u[0], FMAX-u[0]); if(upd) u[0] -= u[0]>>RESTUP; }else { ark::parse(0, u[0]); if(upd) u[0] += (FMAX-u[0])>>RESTUP; } }pv[0]=log; return ran; } #undef curfreq #undef LOBIT #undef FMB #undef FMAX #undef RESTUP
[ "kvarkus@gmail.com" ]
kvarkus@gmail.com
ac2058e9f33b44634063ade4614aaf07e768bb75
a37fe8de18e82d2fbc04da4c409897de34c2d0b2
/KOE/PV/FORMDEF/BOGENORI.CPP
5c9abbf32627424c4ddbbf21679e02c189ffc90b
[]
no_license
jskripsky/ancient
e469354deef1ed2fee652f8686a033ee5d4bb970
052d342d5ca701c9b74b2505bd745d7849f66dcd
refs/heads/master
2016-09-05T14:26:45.625760
2014-04-15T17:34:38
2014-04-15T17:36:17
18,808,800
3
0
null
null
null
null
ISO-8859-2
C++
false
false
11,242
cpp
/*----------------------------------------------*/ /* */ /* PV 1.0 */ /* Bogenhausen */ /* Form Definition Source File */ /* */ /*----------------------------------------------*/ #include "FormDef\SpecDef.Use" #include <TV.H> #include "FormDef\SpecDef.H" TSpecDefinition::TSpecDefinition( TForm *(*)(), TStrListMaker *(*)() ) : TFormDefinition( TSpecDefinition::initForm, TSpecDefinition::initStringList ) { } TForm *TSpecDefinition::initForm() { TForm *f = new TForm(); TPage *p; TMeasurements m = TMeasurements(); /* Contructing Page 1... */ p = new TPage( "Aufnahme" ); m.reset(); p->insert( new TNameField( m, "Name ", 30 ) ); p->lastInserted->makeNecessary(); p->insert( new TNameField( m, "Vorname", 15, moNoSpace ) ); p->lastInserted->makeNecessary(); m.control.a.y --; //!!! m.control.b.y --; //!!! p->insert( new TBirthDateField( m, "Geb.datum", 10, "TT.MM.JJJJ" ) ); p->lastInserted->setInfoLevel( ilNormal ); p->lastInserted->makeNecessary(); p->insert( new TRadioField( m, "Geschlecht", 1, new TSItem( "M„nnlich", new TSItem( "Weiblich", 0 )), new TSItem( "M", new TSItem( "W", 0 )), moDown ) ); m.control.a.y ++; m.control.b.y ++; m.control.a.y --; //!!! m.control.b.y --; //!!! p->insert( new TPNumberField( m, "Aufnahmenr.", 8, "Bereich.Ini", moDown | moVert ) ); p->lastInserted->setInfoLevel( ilNormal ); p->lastInserted->makeNecessary(); p->insert( new TSystemDateField( m, "Datum", 8, "TT.MM.JJ" ) ); p->lastInserted->makeNecessary(); p->insert( new TSystemTimeField( m, "Zeit" ) ); p->lastInserted->makeNecessary(); p->insert( new TTextField( m, "Strasse", 30, moHor ) ); p->lastInserted->makeNecessary(); p->insert( new TTextField( m, "PLZ ", 8, moHor | moNoSpace ) ); p->lastInserted->makeNecessary(); p->insert( new TTextField( m, "Ort ", 20, moHor | moNoSpace ) ); p->lastInserted->makeNecessary(); m.control.a.y --; //!!! m.control.b.y --; //!!! p->insert( new TTextField( m, "Kassennr.", 7, moVert ) ); p->insert( new TTextField( m, "Krankenkassenname", 28, moRight ) ); m.control.a.y --; //!!! m.control.b.y --; //!!! p->insert( new TRadioField( m, "Allgemein/Privat", 10, new TSItem( "", new TSItem( "Allgemein", new TSItem( "Privat", 0 ))), new TSItem( "", new TSItem( "Akut 2", new TSItem( "Akut ML 1", 0 ))), moHor ) ); p->lastInserted->makeNecessary(); m.control.a.y += 2; m.control.b.y += 2; f->insert( p ); /* Contructing Page 3... */ p = new TPage( "Kostentr„ger" ); m.reset(); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TListField( m, "Kostentr„ger", 25, "KOSTENTR.LST", 11, moDown | moVert ) ); p->lastInserted->makeNecessary(); m.control.a.y += 10; m.control.b.y += 10; p->insert( new TTextField( m, "Zusatzinfo (z.B. Krzel, Adresse)", 38, moVert ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); f->insert( p ); /* Contructing Page 2... */ p = new TPage( "Station" ); m.reset(); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TListField( m, "Befund an/Entlassen auf:", 24, "STATION.LST", 16, moDown | moVert ) ); p->lastInserted->setInfoLevel( ilNormal ); p->lastInserted->makeNecessary(); f->insert( p ); /* Contructing Page 3... */ p = new TPage( "Personalien" ); m.reset(); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TRadioField( m, "Eingeliefert durch", 20, new TSItem( "Selbst", new TSItem( "Rettungswagen", new TSItem( "Notarztwagen", new TSItem( "Hubschrauber", 0 )))), new TSItem( "Selbst", new TSItem( "Rettungswagen", new TSItem( "Notarztwagen", new TSItem( "Hubschrauber", 0 )))), moDown | moVert ) ); m.control.a.y += 3; m.control.b.y += 3; p->insert( new TTextField( m, "Arbeitgeber Name, Str., PLZ, Ort", 30, moVert ) ); p->insert( new TTextField( m, 0, 30, moNoSpace ) ); p->insert( new TTextField( m, 0, 28, moNoSpace ) ); f->insert( p ); /* Contructing Page 4... */ p = new TPage( "Anamnese" ); m.reset(); // m.control.a.y ++; // m.control.b.y ++; m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TTextField( m, "Hauptversicherter", 30, moHor ) ); p->insert( new TBirthDateField( m, "Geb.datum ", 10, "TT.MM.JJJJ", moHor | moNoSpace ) ); p->insert( new TRadioField( m, "Status", 3, new TSItem( "HV", new TSItem( "FAM", new TSItem( "REN", 0 ))), new TSItem( "HV", new TSItem( "FAM", new TSItem( "REN", 0 ))), moDown | moHor ) ); m.control.a.y += 2; m.control.b.y += 2; p->insert( new THiddenConstField( m, "Anamnese", 8 ) ); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TTextField( m, "Anamnese", 38, moVert ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); f->insert( p ); /* Contructing Page 5... */ p = new TPage( "Aufnahmebefund" ); m.reset(); // m.control.a.y ++; // m.control.b.y ++; p->insert( new THiddenConstField( m, "Aufnahmebefund", 14 ) ); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TTextField( m, "Aufnahmebefund", 38, moVert ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); f->insert( p ); /* Contructing Page 6... */ p = new TPage( "Diagnose/Behandlung" ); m.reset(); // m.control.a.y ++; // m.control.b.y ++; p->insert( new THiddenConstField( m, "Diagnose", 8 ) ); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TTextField( m, "Aufnahmediagnose", 38, moVert ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new THiddenConstField( m, "Behandlung", 10 ) ); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TTextField( m, "Behandlung", 38, moVert ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); f->insert( p ); /* Contructing Page 7... */ p = new TPage( "Sonstiges" ); m.reset(); // m.control.a.y ++; // m.control.b.y ++; m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new THiddenConstField( m, "Medikamente + Leistungen", 24 ) ); m.control.a.y -= 2; m.control.b.y -= 2; p->insert( new TTextField( m, "Medikamente + Leistungen", 38, moVert ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 38, moNoSpace ) ); p->insert( new TTextField( m, 0, 40, moNoSpace ) ); p->insert( new THiddenConstField( m, " ", 2 ) ); m.control.a.y -= 2; m.control.b.y -= 2; // p->insert( new TRadioField( m, "D13-Eigenunfall", // 4, // new TSItem( "Nein", // new TSItem( "Ja", 0 )), // new TSItem( "Nein", // new TSItem( "Ja", 0 )), // moHor | moDown ) ); // m.control.a.y ++; // m.control.b.y ++; p->insert( new TDateField( m, "Nachschau am", 8, "TT.MM.JJ", moHor | moDown ) ); p->insert( new TNumericField( m, "Uhr", 5, ":" ) ); p->insert( new TControlField( m, "Ambulant/Station„r", 1, new TSItem( "in Behandlung", new TSItem( "entlassen/verlegt", new TSItem( "station„r aufgenommen", new TSItem( "D13-Eigenunfall", new TSItem( "D13 entlassen/verlegt", new TSItem( "D13 station„r aufgen.", 0 )))))), new TSItem( "1", new TSItem( "2", new TSItem( "3", new TSItem( "4", new TSItem( "5", new TSItem( "6", 0 )))))), moDown | moVert ) ); f->insert( p ); /* Contructing Page 7... */ p = new TPage( "Konsil„rzte" ); m.reset(); m.control.a.y ++; m.control.b.y ++; p->insert( new TTextField( m, "Arzt Name", 30, moVert ) ); p->insert( new TTextField( m, "Konsilarzt 1", 30 ) ); p->insert( new TTextField( m, "Konsilarzt 2", 30 ) ); p->insert( new TTextField( m, "Konsilarzt 3", 30 ) ); p->insert( new TTextField( m, "Konsilarzt 4", 30 ) ); f->insert( p ); return f; } TStrListMaker *TSpecDefinition::initStringList() { TStrListMaker *sl = new TStrListMaker( strSize, indexSize ); sl->put( skCorporation, "Krankenhaus Mnchen Bogenhausen" ); sl->put( skPerson, "Patient" ); sl->put( skPersonList, "~P~atienten" ); sl->put( skNewPerson, "~N~euer Patient..." ); sl->put( skDeletePerson, "" ); sl->put( skEditPerson, "Daten ~m~odifizieren..." ); sl->put( skPrintPerson, "~F~ormular drucken" ); sl->put( skRawPrintPerson, "" ); sl->put( skEncodeCard, "" ); sl->put( skHeapView, "" ); sl->put( skOldDevice, "" ); sl->put( skFormatedRawPrint, "" ); sl->put( skNumRPCopiesDlg, "" ); sl->put( skAutoSave, "" ); sl->put( skFormDlgOK, "" ); sl->put( skFormDlgCancel, "" ); sl->put( skPrintLog, "~R~eportliste..." ); sl->put( skConfirmNewPerson, "1" ); sl->put( skDisableOptions, "1" ); sl->put( skListWindowTitle, "Patientendaten-Verwaltung" ); sl->put( skExportData, "Daten ~e~xportieren..." ); return sl; }
[ "js@hotfeet.ch" ]
js@hotfeet.ch
7ad78b78ddbe2f7a4d57c3a86fff69001b768f1b
b51c117a5fa2b3ce070107dbf2540bdc7022a6fb
/CudaTracer2/FractalRenderer.cpp
1668fd71e2e925f7b1eec2b7268a062a3d2b82ba
[ "MIT" ]
permissive
bbtarzan12/CudaTracer2
5b3f815b1c61f37fec56822cd5619ddda3520f4e
89b6454bf84ef6b1300f84c6580c867cb8419ce3
refs/heads/master
2022-03-29T05:10:44.151809
2020-01-31T12:35:51
2020-01-31T12:35:51
148,148,523
0
0
null
null
null
null
UTF-8
C++
false
false
3,349
cpp
#include "FractalRenderer.h" #include "ShaderCommon.h" #include "FractalKernel.cuh" using namespace std; FractalRenderer::FractalRenderer() { } FractalRenderer::~FractalRenderer() { cout << "[Renderer] FractalRenderer Released" << endl; glDeleteProgram(cudaViewProgramID); glDeleteBuffers(1, &cudaVBO); glDeleteVertexArrays(1, &cudaVAO); if (renderThread) renderThread.release(); cudaDeviceReset(); } void FractalRenderer::Init(RendererOption option) { Renderer::Init(option); GLFWManager::Init(option.width, option.height, "Fractal Tracer", this); cout << "[Renderer] Init FractalRenderer" << endl; { // Cuda Opengl Interop glEnable(GL_TEXTURE_2D); glGenTextures(1, &viewGLTexture); glBindTexture(GL_TEXTURE_2D, viewGLTexture); { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, option.width, option.height, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } gpuErrorCheck(cudaGraphicsGLRegisterImage(&viewResource, viewGLTexture, GL_TEXTURE_2D, cudaGraphicsRegisterFlagsWriteDiscard)); glBindTexture(GL_TEXTURE_2D, 0); cudaViewProgramID = LoadShaders("cudaView.vert", "cudaView.frag"); GLfloat vertices[] = { // positions // normal // texture Coords -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, }; glGenVertexArrays(1, &cudaVAO); glGenBuffers(1, &cudaVBO); glBindVertexArray(cudaVAO); glBindBuffer(GL_ARRAY_BUFFER, cudaVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*) 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*) (3 * sizeof(float))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*) (6 * sizeof(float))); glBindVertexArray(0); } } void FractalRenderer::SetCamera(CameraOption option) { Renderer::SetCamera(option); camera->UpdateScreen(option.width, option.height); camera->UpdateCamera(0); cout << "[Renderer] Set Camera To Renderer" << endl; } void FractalRenderer::Start() { cout << "[Renderer] Start FractalRenderer" << endl; renderThread = make_unique<thread>( [&]() { while (true) { Render(deltaTime); } }); double lastTime = glfwGetTime(); while (GLFWManager::WindowShouldClose() == 0) { glfwPollEvents(); double currentTime = glfwGetTime(); deltaTime = currentTime - lastTime; lastTime = currentTime; Update(deltaTime); } } void FractalRenderer::HandleKeyboard(int key, int scancode, int action, int mods) { } void FractalRenderer::HandleMouseClick(int button, int action, int mods) { } void FractalRenderer::HandleMouseMotion(double xPos, double yPos) { } void FractalRenderer::HandleResize(int width, int height) { } void FractalRenderer::Update(double deltaTime) { } void FractalRenderer::Render(double deltaTime) { }
[ "bbtarzan12@gmail.com" ]
bbtarzan12@gmail.com
e542810a26ec060fdc5f5258304044005898b2c4
56dbbf58b200078d702fd1a05b6261c57437713c
/Classical Problems/Hamiltonian Circuit/Hamiltonian Circuit/Main.h
ed5ce2708e989fb145181e288a600fd7fddc1dbb
[]
no_license
ImTheRealOne/CPP-Practice
1908235d2705bd7c05a5d4eb2b6d7daff397d036
d8204629e79335cd2030585aa48910728ceba5ce
refs/heads/master
2020-03-28T20:09:00.237593
2018-10-02T20:20:17
2018-10-02T20:20:17
149,044,478
0
0
null
null
null
null
UTF-8
C++
false
false
97
h
#pragma once #include <iostream> #include <Graph.h> class Main { public: Main(); ~Main(); };
[ "kowasockilendaro@yahoo.com" ]
kowasockilendaro@yahoo.com
996c94a50a302ce0d987b9d053e80dd6fba836e0
8d6922d765f8a92edda3167091cd469fa6642f0a
/app/src/main/cpp/native-lib.cpp
13f6dd8b25e98517f46fd5f7bfa72d85cab5a8ee
[]
no_license
bajwa143/HelloNDK
5d981df1cfa4158a471c9db74f69bb2838756b55
4e812c901541c1d5aefc6f4528bdd56c4cbc81d3
refs/heads/master
2020-06-27T04:46:48.074646
2019-07-29T10:13:23
2019-07-29T10:13:23
199,847,386
0
0
null
null
null
null
UTF-8
C++
false
false
1,970
cpp
#include <jni.h> #include <string> #include "PrimeNumber.h" using namespace std; // The naming convention for the C function is Java_{package_and_classname}_{function_name}(JNI_arguments). // The dot in package name is replaced by underscore // JNIEnv*: reference to JNI environment, which lets you access all the JNI functions. // The extern "C" is recognized by C++ compiler only. It notifies the C++ compiler that these functions are to // be compiled using C's function naming protocol instead of C++ naming protocol. C and C++ have different function // naming protocols as C++ support function overloading and uses a name mangling scheme to differentiate the overloaded functions. extern "C" JNIEXPORT jstring JNICALL Java_com_hellondk_MainActivity_getPrimeNumber(JNIEnv *env, jobject) { PrimeNumber primeNumber = PrimeNumber(43); int pNum = primeNumber.getNumber(); string message = "Prime Number = " + to_string(pNum); return env->NewStringUTF(message.c_str()); } extern "C" JNIEXPORT jstring JNICALL Java_com_hellondk_MainActivity_findPrime(JNIEnv *env, jobject, jint inputNumber) { // We don't need to convert jint to int, because // Java Primitives: jint, jbyte, jshort, jlong, jfloat, jdouble, jchar, jboolean for // Java Primitive of int, byte, short, long, float, double, char and boolean, respectively // It is interesting to note that jint is mapped to C's long (which is at least 32 bits), instead of of C's int // (which could be 16 bits). Hence, it is important to use jint in the C program, instead of simply using int. PrimeNumber primeNumber = PrimeNumber(inputNumber); string message; bool result = primeNumber.isPrime(); if (result == true) { message = "Prime Number"; } else { message = "Not Prime Number"; } return env->NewStringUTF(message.c_str()); } // JNI is a C interface, which is not object-oriented. It does not really pass the objects
[ "hello_friends_1@yahoo.com" ]
hello_friends_1@yahoo.com
542eb57065bd2adcb4398ce0341cd5704d2e7d39
61ae7b5d6c64e1558d11fd1c69935d7f470b9988
/src/XmlEvaluationWriter.h
7ac6bb4ce3b3b3451eb2dbc7a8a7780ee54e9d51
[ "Apache-2.0" ]
permissive
PRImA-Research-Lab/prima-layout-eval
853023e1e8c0a44a58aa521ec1e5da7614266368
bbf2187fcae15f43461cf521dafeb3350004acf8
refs/heads/master
2020-07-19T21:15:12.483478
2019-09-06T12:48:41
2019-09-06T12:48:41
206,515,827
3
1
null
null
null
null
UTF-8
C++
false
false
4,062
h
#pragma once /* * University of Salford * Pattern Recognition and Image Analysis Research Lab * Author: Christian Clausner */ #include "evaluationwriter.h" #include "XmlValidator.h" #include "XmlEvaluationReader.h" #include "ExtraString.h" #include "ExtraFileHelper.h" #include "MsXmlWriter.h" #include "MsXmlNode.h" #include "MsXmlParameterWriter.h" namespace PRImA { class CXmlEvaluationReader; class CWeightSetting; /* * Class CXmlEvaluationWriter * * Writer for evaluation profile and results. * * CC */ class CXmlEvaluationWriter : public CEvaluationWriter { public: CXmlEvaluationWriter(void); CXmlEvaluationWriter(CValidator * validator); ~CXmlEvaluationWriter(void); void WriteLayoutEvaluation( CLayoutEvaluation * layoutEval, CMetaData * metaData, CUniString fileName); void WriteEvaluationProfile(CEvaluationProfile * profile, CMetaData * metaData, CUniString fileName); void Write( CLayoutEvaluation * layoutEval, CEvaluationProfile * profile, CMetaData * metaData, CUniString fileName); private: //xmlNsPtr SetNameSpace(xmlNodePtr node); void WriteProfile(CEvaluationProfile * profile, CMsXmlNode * parentNode); CMsXmlNode * WriteWeightNode( CWeight * weight, CMsXmlNode * parentNode, CWeightSetting * defaultSetting, const wchar_t * elementName = NULL); void WriteReadingOrderPenalties(CEvaluationProfile * profile, CMsXmlNode * profileNode); void WriteRawDataAndMetrics(CLayoutEvaluation * layoutEval, CMsXmlNode * parentNode); void WriteRawData(CEvaluationResults * results, CMsXmlNode * parentNode); void WriteMetricResults(CEvaluationResults * results, CMsXmlNode * metricsNode); void WriteMetricResult(CLayoutObjectEvaluationMetrics * metricResult, CMsXmlNode * metricsNode); void WriteOverlapEntries(CUniString region1, set<CUniString> * regions2, CMsXmlNode * overlapNode); void WriteRegionResults(CUniString region, CLayoutObjectEvaluationResult * results, CMsXmlNode * resultsNode); void WriteRegionError(CLayoutObjectEvaluationError * error, CMsXmlNode * errorNode); void WriteRects(list<CRect*> * rects, CMsXmlNode * rectsNode); void WriteOverlaps(COverlapRects * overlapRects, CMsXmlNode * node); void WriteReadingOrderError(CReadingOrderError * error, CMsXmlNode * readingOrderErrorNode); void WriteRelation(set<int> * relation, CMsXmlNode * node); void WriteIntPerRegionTypeNode(map<int, int> * values, const wchar_t * elementName, CMsXmlNode * parentNode); void WriteDoublePerRegionTypeNode(map<int, double> * values, const wchar_t * elementName, CMsXmlNode * parentNode); void WriteIntPerErrorTypeNode(map<int, int> * values, const wchar_t * elementName, CMsXmlNode * parentNode); void WriteDoublePerErrorTypeNode(map<int, double> * values, const wchar_t * elementName, CMsXmlNode * parentNode); CWeightSetting * FindMostCommonSetting(CWeight * weight); void FindMostCommonSetting(CWeight * weight, std::vector<CWeightSetting> * weightSettings); bool CompareAllchildWeightsAgainstSetting(CWeight * weight, CWeightSetting * weightSetting); CUniString RegionTypeIntToString(int type); CUniString PageObjectLevelIntToString(int level); CUniString ErrorTypeIntToString(int type); CUniString ReadingOrderRelationTypeIntToString(int type); private: CValidator * m_XmlValidator; }; /* * Class CWeightSetting * * CC 11.03.2013 */ class CWeightSetting { public: CWeightSetting(double value, double allowableValue, bool enableAllowable, bool useAllowable); CWeightSetting(CWeightSetting * toCopy); ~CWeightSetting(); bool operator==(const CWeightSetting& other); inline void IncrementCount() { m_Count++; }; inline int GetCount() { return m_Count; }; inline double GetValue() { return m_Value; }; inline double GetAllowableValue() { return m_AllowableValue; }; inline bool IsAllowableWeightEnabled() { return m_EnableAllowable; }; inline bool IsUseAllowableWeight() { return m_UseAllowable; }; private: int m_Count; double m_Value; double m_AllowableValue; bool m_EnableAllowable; bool m_UseAllowable; }; }
[ "chris1010010@gmail.com" ]
chris1010010@gmail.com
94e4e2136a1221b3e340c5d3acc6c3fa21c0780e
b124d88ab08ded781e08598b838593bf841fa08e
/VideoDemo/VideoDemo/FlameDecider.h
39189ee3a220096c66bb42babbbae885c77e749f
[ "MIT" ]
permissive
hdhyy/video_detect_demo
eba58fbf4eccc6fc1d4addd0fbcf27e7cf9d82f1
3e082a253073df3905cc147f48ff993ce3d06920
refs/heads/master
2022-03-31T15:52:08.060037
2019-08-27T08:07:24
2019-08-27T08:07:24
187,223,319
0
0
null
null
null
null
UTF-8
C++
false
false
920
h
#pragma once #ifndef __FlameDetection__FlameDecider__ #define __FlameDetection__FlameDecider__ #include "PublicHeader.h" struct Target; class Feature; class FlameDecider { private: static const string SVM_DATA_FILE; #ifdef TRAIN_MODE static const string SAMPLE_FILE; static const int MIN_SAMPLE_COUNT = 1000; static const int FRAME_GAP = 5; #endif Mat mFrame; Ptr<SVM> mSVM; #ifdef TRAIN_MODE bool mSampleEnough; int mFlameCount; int mNonFlameCount; vector<Feature> mFeatureVec; vector<bool> mResultVec; int mFrameCount; #endif #ifdef TRAIN_MODE void userInput(const map<int, Target>& targets); void svmStudy(); void train(const map<int, Target>& targets); #else bool svmPredict(const Feature& feature); bool judge(map<int, Target>& targets); #endif public: FlameDecider(); bool decide(const Mat& frame, map<int, Target>& targets); }; #endif /* defined(__FlameDetection__FlameDecider__) */
[ "fuyunhuayu@foxmail.com" ]
fuyunhuayu@foxmail.com
a436189bea0f6cef2e771df61c583efbb4e3bcf4
dceff34eaceed8f7a52ea908958645104167e3e1
/src/backup-n3l2.0/relation-v7/model/Driver.h
502f42cc1dc5380114a15a543dde16707c722d92
[]
no_license
zhangmeishan/NNRelationExtraction
a100acc0f6c9d5fd0db7686249b647a21ae908b2
8efd8173b2503bc75274b2238b2392476a86a8e9
refs/heads/master
2021-01-11T19:48:25.552293
2017-07-30T13:23:56
2017-07-30T13:23:56
79,401,948
14
2
null
null
null
null
UTF-8
C++
false
false
4,995
h
#ifndef SRC_Driver_H_ #define SRC_Driver_H_ #include "N3L.h" #include "State.h" #include "ActionedNodes.h" #include "Action.h" #include "ComputionGraph.h" class Driver { public: Driver(size_t memsize) : aligned_mem(memsize) { _pcg = NULL; _batch = 0; } ~Driver() { if (_pcg != NULL) delete _pcg; _pcg = NULL; _batch = 0; } public: ComputionGraph *_pcg; ModelParams _modelparams; // model parameters HyperParams _hyperparams; Metric _eval; CheckGrad _checkgrad; ModelUpdate _ada; // model update AlignedMemoryPool aligned_mem; int _batch; public: inline void initial() { if (!_hyperparams.bValid()) { std::cout << "hyper parameter initialization Error, Please check!" << std::endl; return; } if (!_modelparams.initial(_hyperparams, &aligned_mem)) { std::cout << "model parameter initialization Error, Please check!" << std::endl; return; } _hyperparams.print(); _pcg = new ComputionGraph(); _pcg->initial(_modelparams, _hyperparams, &aligned_mem); std::cout << "allocated memory: " << aligned_mem.capacity << ", total required memory: " << aligned_mem.required << ", perc = " << aligned_mem.capacity * 1.0 / aligned_mem.required << std::endl; setUpdateParameters(_hyperparams.nnRegular, _hyperparams.adaAlpha, _hyperparams.adaEps); _batch = 0; } public: dtype train(std::vector<Instance > &sentences, const vector<vector<CAction> > &goldACs) { _eval.reset(); dtype cost = 0.0; int num = sentences.size(); for (int idx = 0; idx < num; idx++) { _pcg->forward((sentences[idx]), &(goldACs[idx])); //_batch += goldACs[idx].size(); cost += loss_google(); if (_pcg->outputs.size() != goldACs[idx].size()) { std::cout << "strange error: step not equal action_size" << std::endl; } _pcg->backward(); } return cost; } void decode(Instance &sentence, CResult &result) { _pcg->forward(sentence); predict(result); } void updateModel() { if (_ada._params.empty()) { _modelparams.exportModelParams(_ada); } //_ada.update(10); _ada.updateAdam(10); _batch = 0; } void writeModel(); void loadModel(); private: dtype loss_google() { int maxstep = _pcg->outputs.size(); if (maxstep == 0) return 1.0; //_eval.correct_label_count += maxstep; static PNode pBestNode = NULL; static PNode pGoldNode = NULL; static PNode pCurNode; static dtype sum, max; static int curcount, goldIndex; static vector<dtype> scores; dtype cost = 0.0; for (int step = 0; step < maxstep; step++) { curcount = _pcg->outputs[step].size(); if (curcount == 1)continue; max = 0.0; goldIndex = -1; pBestNode = pGoldNode = NULL; for (int idx = 0; idx < curcount; idx++) { pCurNode = _pcg->outputs[step][idx].in; if (pBestNode == NULL || pCurNode->val[0] > pBestNode->val[0]) { pBestNode = pCurNode; } if (_pcg->outputs[step][idx].bGold) { pGoldNode = pCurNode; goldIndex = idx; } } if (goldIndex == -1) { std::cout << "impossible" << std::endl; } pGoldNode->loss[0] = -1.0; pGoldNode->lossed = true; max = pBestNode->val[0]; sum = 0.0; scores.resize(curcount); for (int idx = 0; idx < curcount; idx++) { pCurNode = _pcg->outputs[step][idx].in; scores[idx] = exp(pCurNode->val[0] - max); sum += scores[idx]; } for (int idx = 0; idx < curcount; idx++) { pCurNode = _pcg->outputs[step][idx].in; pCurNode->loss[0] += scores[idx] / sum; pCurNode->lossed = true; } if (pBestNode == pGoldNode)_eval.correct_label_count++; _eval.overall_label_count++; _batch++; cost += -log(scores[goldIndex] / sum); if (std::isnan(cost)) { std::cout << "debug" << std::endl; } } return cost; } void predict(CResult &result) { int step = _pcg->outputs.size(); _pcg->states[step - 1].getResults(result, _hyperparams); //TODO: } inline void setUpdateParameters(dtype nnRegular, dtype adaAlpha, dtype adaEps) { _ada._alpha = adaAlpha; _ada._eps = adaEps; _ada._reg = nnRegular; } }; #endif /* SRC_Driver_H_ */
[ "mason.zms@gmail.com" ]
mason.zms@gmail.com
219199e98cd3980d00ca8c3d91763de55703c187
70418d8faa76b41715c707c54a8b0cddfb393fb3
/11010.cpp
1e3cd4698875412722e530e6f9435d3b1df3c2c9
[]
no_license
evandrix/UVa
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
refs/heads/master
2021-06-05T01:44:17.908960
2017-10-22T18:59:42
2017-10-22T18:59:42
107,893,680
3
1
null
null
null
null
UTF-8
C++
false
false
2,421
cpp
#include <bits/stdc++.h> using namespace std; struct Board { char a[3][3]; int encode() { int r = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { r = r * 3 + a[i][j]; } return r; } bool complete() { int r = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (a[i][j] != 0) { r++; } return r == 9; } bool wins(int p) { for (int i = 0; i < 3; i++) { if (a[i][0] == p && a[i][1] == p && a[i][2] == p) { return true; } if (a[0][i] == p && a[1][i] == p && a[2][i] == p) { return true; } } if (a[0][0] == p && a[1][1] == p && a[2][2] == p) { return true; } return a[0][2] == p && a[1][1] == p && a[2][0] == p; } bool read() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3;) { int c = getchar(); if (c == EOF) { return false; } else if (c == '.') { a[i][j] = 0; } else if (c == 'O') { a[i][j] = 1; } else if (c == 'X') { a[i][j] = 2; } else { continue; } j++; } } return true; } }; int memo[20000][2]; int perfect(Board &b, int st) { int &ret = memo[b.encode()][st - 1]; if (ret != -1) { return ret; } int w1 = b.wins(1), w2 = b.wins(2); if (w1 && w2) { return ret = 0; } if (w1 || w2) { return ret = (w1 ? 1 : 2); } if (b.complete()) { return ret = 0; } ret = 3 - st; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (b.a[i][j] != 0) { continue; } b.a[i][j] = st; int t = perfect(b, 3 - st); b.a[i][j] = 0; if (t == st) { return ret = st; } if (t == 0) { ret = 0; } } } return ret; } int sc(int a, int b) { if (a == 0) { return 0; } if (a == b) { return 1; } return -1; } int main() { Board b; int a[1024], n; memset(memo, 0xff, sizeof(memo)); for (int cs = 1; scanf("%d", &n) == 1 && n >= 2; cs++) { int s = 0; for (int i = 0; i < n; i++) { if (!b.read()) { return 0; } int mary = sc(perfect(b, 1), 1); int john = sc(perfect(b, 2), 2); a[i] = mary + john; s -= john; } sort(a, a + n); for (int i = n - 2; i >= 0; i -= 2) { s += a[i]; } printf("Case %d: ", cs); if (s == 0) { printf("Draw.\n"); } else if (s > 0) { printf("Mary wins.\n"); } else { printf("Johnny wins.\n"); } } return 0; }
[ "yleewei@dso.org.sg" ]
yleewei@dso.org.sg
8f56c25fc302508f134906b6c4e9b079002c5bce
08fff4f148982bbbb7b3bab44abda97c58708f3a
/KontrolaPristupa/stdafx.cpp
c26e726bfcdacaa4d8e6a9800bc4f06442c61238
[]
no_license
ivblazek/Kontrola-Pristupa
3506d0c40ee9bf1c8a18eb8833a6f54dd0ad8b1d
26ee8015337ff92d7e2c46827210421ebf6ad8c2
refs/heads/master
2022-12-17T20:04:36.239338
2020-09-16T23:58:32
2020-09-16T23:58:32
291,552,307
0
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
// stdafx.cpp : source file that includes just the standard includes // KontrolaPristupa.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "ivblazek@vsite.hr" ]
ivblazek@vsite.hr
7f0286cb9b66aea9f97e9fd83a2f31f450288768
6617c93eca89fcfecaba1c22be159dd6c6654f23
/src/render_object.h
26e7afa8553b6eea67da0449cd32930c09632210
[ "MIT" ]
permissive
rilpires/saucer_engine
94a073c8ba90736e009260f0b58ea84f45708806
909264a999715623736456b1541185d7dd0e2c58
refs/heads/master
2023-03-11T07:45:02.801893
2021-02-26T19:13:24
2021-02-26T19:13:24
321,767,118
5
0
null
null
null
null
UTF-8
C++
false
false
963
h
#ifndef RENDER_OBJECT_H #define RENDER_OBJECT_H #include "component.h" #include "engine.h" #include "render_engine.h" class RenderObject : public Component { REGISTER_AS_COMPONENT(RenderObject) friend class RenderEngine; private: bool use_parent_shader; ShaderResource* current_shader; protected: VertexData* vertex_data; unsigned short vertex_data_count; bool dirty_vertex_data; // useful for some big VBOs RenderObject(); ~RenderObject(); public: virtual std::vector<RenderData> generate_render_data() ; bool get_use_parent_shader() const ; void set_use_parent_shader( bool new_val ); ShaderResource* get_current_shader() const ; void set_current_shader( ShaderResource* p ); static void bind_methods(); }; #endif
[ "rilpires@gmail.com" ]
rilpires@gmail.com
061aa3cc1db8b35436f89c171e6e553527082ad3
d11235048abad36a8f09b5881c225074869aca71
/include/thrust/system/detail/generic/adjacent_difference.inl
b0e2407e0ef1c85e3b700d513bd8add3618e293c
[]
no_license
peu-oliveira/pibiti
108057e196e7388a39916bf464d89d886d3e2cba
7acfa9d173c7d2bd4d4406e030a8510ced8a3add
refs/heads/main
2023-04-18T00:30:43.890808
2021-04-28T13:55:50
2021-04-28T13:55:50
306,166,539
1
0
null
2021-04-28T13:55:50
2020-10-21T22:54:45
C
UTF-8
C++
false
false
2,772
inl
/* * Copyright 2008-2013 NVIDIA 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 <thrust/detail/config.h> #include <thrust/system/detail/generic/adjacent_difference.h> #include <thrust/adjacent_difference.h> #include <thrust/functional.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/temporary_array.h> #include <thrust/transform.h> namespace thrust { namespace system { namespace detail { namespace generic { template<typename DerivedPolicy, typename InputIterator, typename OutputIterator> __host__ __device__ OutputIterator adjacent_difference(thrust::execution_policy<DerivedPolicy> &exec, InputIterator first, InputIterator last, OutputIterator result) { typedef typename thrust::iterator_traits<InputIterator>::value_type InputType; thrust::minus<InputType> binary_op; return thrust::adjacent_difference(exec, first, last, result, binary_op); } // end adjacent_difference() template<typename DerivedPolicy, typename InputIterator, typename OutputIterator, typename BinaryFunction> __host__ __device__ OutputIterator adjacent_difference(thrust::execution_policy<DerivedPolicy> &exec, InputIterator first, InputIterator last, OutputIterator result, BinaryFunction binary_op) { typedef typename thrust::iterator_traits<InputIterator>::value_type InputType; if(first == last) { // empty range, nothing to do return result; } else { // an in-place operation is requested, copy the input and call the entry point // XXX a special-purpose kernel would be faster here since // only block boundaries need to be copied thrust::detail::temporary_array<InputType, DerivedPolicy> input_copy(exec, first, last); *result = *first; thrust::transform(exec, input_copy.begin() + 1, input_copy.end(), input_copy.begin(), result + 1, binary_op); } return result + (last - first); } } // end namespace generic } // end namespace detail } // end namespace system } // end namespace thrust
[ "pepeuguimaraes@gmail.com" ]
pepeuguimaraes@gmail.com
5ce9790026e92cbaf7c23d98300795676e4bfeff
2dcb52ddd94443a81082c71627784f4a8089e860
/DVR/settings/dispset.cpp
a9490c1b177e90651fe2ad2e0098468d9b980d90
[]
no_license
jerryxiee/qt_code
d986ff7270ca582f59dc00257cb7368b7080f7ae
1cd8d63666a7aabcb9df3108dbaf3227dd5cb440
refs/heads/master
2022-12-31T23:00:21.370792
2020-10-21T08:00:43
2020-10-21T08:00:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,254
cpp
#include "dispset.h" #include <QDebug> #include <QRect> DispSet::DispSet(QObject *parent, const QString &filename) : QObject(parent),Config(filename) { } void DispSet::setConfig(int Chn,QString name,bool dispname,bool dispdate,bool dispweek,QString datetype,int value) { Config::setConfig(RootName+QString::number(Chn),ChnName,name); Config::setConfig(RootName+QString::number(Chn),DispName,dispname); Config::setConfig(RootName+QString::number(Chn),DispDate,dispdate); Config::setConfig(RootName+QString::number(Chn),DispWeek,dispweek); Config::setConfig(RootName+QString::number(Chn),DateType,datetype); Config::setConfig(RootName+QString::number(Chn),TimeType,value); preSetConfig(Chn,name, dispname, dispdate,dispweek, datetype, value); emit rgnOverlayShow(Chn); emit overlaySetPos(Chn); } void DispSet::setConfig(const QString &rootName,const QString &name,const QVariant &Value) { Config::setConfig(rootName,name,Value); } void DispSet::preSetConfig(int Chn, QString name, bool dispname, bool dispdate,bool dispweek, QString datetype, int value) { QString time; if(dispweek){ time = "ddd "; } if(dispdate){ time.append(datetype); if(value == 1){ time.append(" AP"); } } if(dispname){ qDebug()<<"name:"<<name; if(!name.isEmpty()){ qDebug()<<"emit overlayNameChange"; emit overlayNameChange(Chn, name); } } if(!time.isEmpty()) emit overlayTimeTypeChange(time); } void DispSet::enableTime(int Chn,bool enable) { Q_UNUSED(Chn); QString time; if(Config::getConfig(RootName+QString::number(0),DispWeek).toBool()){ time = "ddd "; } if(enable){ time.append(Config::getConfig(RootName+QString::number(0),DateType).toString()); } qDebug()<<"enableTime:"<<enable<<time; if(!time.isEmpty()) emit overlayTimeTypeChange(time); } void DispSet::enableWeek(int Chn, bool enable) { Q_UNUSED(Chn); QString time; if(enable){ time = "ddd "; } if(Config::getConfig(RootName+QString::number(0),DispDate).toBool()){ time.append(Config::getConfig(RootName+QString::number(0),DateType).toString()); } qDebug()<<"enableWeek:"<<enable<<time; if(!time.isEmpty()) emit overlayTimeTypeChange(time); } void DispSet::enableName(int Chn, bool enable) { } void DispSet::setNameRect(int Chn,QRect &rect) { Config::setConfig(RootName+QString::number(Chn),NamePos,rect); } QRect &DispSet::getNameRect(int Chn, QRect &rect) { rect = Config::getConfig(RootName+QString::number(Chn),NamePos).toRect(); return rect; } void DispSet::setTimeRect(int Chn, QRect &rect) { Config::setConfig(RootName+QString::number(Chn),TimePos,rect); } QRect &DispSet::getTimeRect(int Chn, QRect &rect) { rect = Config::getConfig(RootName+QString::number(Chn),TimePos).toRect(); return rect; } void DispSet::setTimeShowEnabled(int Chn, bool enable) { Config::setConfig(RootName+QString::number(Chn),DispDate,enable); } bool DispSet::getTimeShowEnabled(int Chn ) { return Config::getConfig(RootName+QString::number(Chn),DispDate).toBool(); } void DispSet::setNameShowEnabled(int Chn, bool enable) { Config::setConfig(RootName+QString::number(Chn),DispName,enable); } bool DispSet::getNameShowEnabled(int Chn) { return Config::getConfig(RootName+QString::number(Chn),DispName).toBool(); } void DispSet::setWeekShowEnabled(int Chn, bool enable) { Config::setConfig(RootName+QString::number(Chn),DispWeek,enable); } bool DispSet::getWeekShowEnabled(int Chn) { return Config::getConfig(RootName+QString::number(Chn),DispWeek).toBool(); } void DispSet::setTimeType(int Chn, QString &type) { Config::setConfig(RootName+QString::number(Chn),TimeType,type); } QString &DispSet::getTimeType(int Chn, QString &type) { type = Config::getConfig(RootName+QString::number(Chn),TimeType).toString(); return type; } void DispSet::setDateType(int Chn, int type) { Config::setConfig(RootName+QString::number(Chn),DateType,type); } int DispSet::getDateType(int Chn) { return Config::getConfig(RootName+QString::number(Chn),DateType).toInt(); }
[ "liuzhenwei2013@outlook.com" ]
liuzhenwei2013@outlook.com
bfcace272c844aedf8ec2237498fcd31c929ced1
6a9aa3949fc39f7694efbccbb1266d679713e106
/BOJ/Parametric Search - 1939.cpp
3520455735fa38515c267ed97d6ad4bd80226cf5
[]
no_license
kyeongyong1/Problem-Solving
4e2d2d314d49bef872576ecdd5e8b6d5ea0b65fb
058d9cf0ad67f433aec6fd2df43a7e865b5ec568
refs/heads/master
2021-01-21T04:47:03.713125
2016-07-13T10:38:13
2016-07-13T10:38:13
52,586,526
0
0
null
null
null
null
UHC
C++
false
false
1,680
cpp
/* 각각의 섬은 다리로 연결되어 있는데 그 다리는 중량제한이 있다. 이 때, 한 섬에서 다른 섬으로 갈때 운송 할 수 있는 최대값을 출력하는 문제 Parametric Search + BFS Parametric Search 값은 중량이고, 그 중량에 대한 가능의 여부를 판단하는 함수에는 BFS가 쓰였다. 해당 중량으로 시작 섬에서 도착 섬까지 갈 수 있으면 왼쪽반을 없애고, 아니라면 오른쪽반을 없앤다. */ #include <algorithm> #include <functional> #include <vector> #include <map> #include <cstdio> #include <queue> #include <climits> #include <stack> #include <set> #include <cmath> #include <cstring> #include <list> using namespace std; int n, m, a, b, c, s, t; vector<pair<int, int > > graph[100010]; bool visited[100010]; bool func(int mid) { queue<int> q; q.push(s); memset(visited, 0, sizeof(visited)); visited[s] = true; while (!q.empty()) { int here = q.front(); q.pop(); for (int i = 0; i < graph[here].size(); i++) { int there = graph[here][i].first; int cut = graph[here][i].second; if (cut >= mid && visited[there] == false) { if (there == t) return true; visited[there] = true; q.push(there); } } } return false; } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d%d%d", &a, &b, &c); graph[a].push_back(make_pair(b, c)); graph[b].push_back(make_pair(a, c)); } scanf("%d%d", &s, &t); int lo = 1, hi = 1000000001; int res = -1; for (int i = 0; i < 100; i++) { int mid = (lo + hi) / 2; if (func(mid)) { res = max(res, mid); lo = mid; } else hi = mid; } printf("%d\n", res); }
[ "kyeongyong1@naver.com" ]
kyeongyong1@naver.com
5504e68bb166e955eee890e4637fe7563ad9a9cb
f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d
/SDK/PVR_Shell_Base_parameters.hpp
164707f29589fc54061906e0cf25b22a78dd2162
[]
no_license
hinnie123/PavlovVRSDK
9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b
503f8d9a6770046cc23f935f2df1f1dede4022a8
refs/heads/master
2020-03-31T05:30:40.125042
2020-01-28T20:16:11
2020-01-28T20:16:11
151,949,019
5
2
null
null
null
null
UTF-8
C++
false
false
2,841
hpp
#pragma once // PavlovVR (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Shell_Base.Shell_Base_C.GetTorqueOffset struct AShell_Base_C_GetTorqueOffset_Params { struct FVector ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Shell_Base.Shell_Base_C.GetImpulseVector struct AShell_Base_C_GetImpulseVector_Params { struct FVector ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Shell_Base.Shell_Base_C.SetAsLive struct AShell_Base_C_SetAsLive_Params { }; // Function Shell_Base.Shell_Base_C.UserConstructionScript struct AShell_Base_C_UserConstructionScript_Params { }; // Function Shell_Base.Shell_Base_C.ReceiveBeginPlay struct AShell_Base_C_ReceiveBeginPlay_Params { }; // Function Shell_Base.Shell_Base_C.BndEvt__Mesh_K2Node_ComponentBoundEvent_1_ComponentHitSignature__DelegateSignature struct AShell_Base_C_BndEvt__Mesh_K2Node_ComponentBoundEvent_1_ComponentHitSignature__DelegateSignature_Params { class UPrimitiveComponent* HitComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) class AActor* OtherActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UPrimitiveComponent* OtherComp; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) struct FVector NormalImpulse; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FHitResult Hit; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData) }; // Function Shell_Base.Shell_Base_C.ExecuteUbergraph_Shell_Base struct AShell_Base_C_ExecuteUbergraph_Shell_Base_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "hsibma02@gmail.com" ]
hsibma02@gmail.com
0832f4d0cb0db3e83136823f54e6dc0342326311
d47f48e49782411383257ff4ecad0da9e07a9e00
/OnlineContest/TopCoder/SRM/651 Div 2/FoxAndSouvenirTheNext.cpp
eccc7aa9e32371a82034c9e3476760749b206700
[]
no_license
shuvokr/OnlineContest
1dc2c284f955bdb71e442cd16b7fda77b00bf8a3
40d32d6979c072d0f7e5c2aed1994aabed25f484
refs/heads/master
2021-01-09T20:23:06.653265
2016-12-04T15:55:24
2016-12-04T15:55:24
65,753,590
1
0
null
null
null
null
UTF-8
C++
false
false
6,891
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <string> #include <iostream> #include <sstream> #include <vector> #include <queue> #include <deque> #include <stack> #include <map> #include <list> #include <set> #include <algorithm> using namespace std; #define phl puts("Hello") #define sf scanf #define pf printf #define fo(i, n) for(i = 0; i < n; i++) #define of(i, n) for(i = n - 1; i >= 0; i--) #define CLR(n, v) memset(n, v, sizeof( n )) #define INF 1 << 30 #define pb push_back #define lim(v) v.begin(), v.end() #define sz(v) ((int)v,size()) #define equals(a, b) (fabs(a-b)<eps) #define white 0 #define black 1 const double PI = 2 * acos ( 0.0 ); const double eps = 1e-9; typedef long long lld; typedef unsigned long long llu; typedef pair<int, int> pi; typedef vector<int> vi; typedef vector<pi> vpi; template <class T> T jog(T a, T b) { return a + b; } template <class T> T bog(T a, T b) { return a - b; } template <class T> T gon(T a, T b) { return a * b; } template <class T> T sq(T x) {return x * x;} template <class T> T gcd( T a, T b ) { return b == 0 ? a : gcd(b, a % b); } template <class T> T lcm ( T a, T b ) { return ( a / gcd ( a, b ) ) * b; } template <class T> T power ( T a, T p ) { T res = 1, x = a; while ( p ) { if ( p & 1 ) res = res * x; x = x * x; p >>= 1; } return res;} template <class T> T cordinatlenth(T a, T b, T c, T d) { return sqrt( sq(a - c) + sq(b - d) ); } template<class T> string toString(T n){ostringstream oss;oss<<n;oss.flush();return oss.str();} int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;} lld bigmod ( lld a, lld p, lld mod ) { lld res = 1, x = a; while ( p ) { if ( p & 1 ) res = ( res * x ) % mod; x = ( x * x ) % mod; p >>= 1; } return res; } /* #define M 1000005 int phi[M]; void calculatePhi() { for (int i = 1; i < M; i++) phi[i] = i; for (int p = 2; p < M; p++) if (phi[p] == p) // p is a prime for (int k = p; k < M; k += p) phi[k] -= phi[k] / p; } */ /* const int pr = 500001; int prime[ 41539 ], ind; bool mark[ pr ]; void primelist() { for(int i = 4; i < pr; i += 2) mark[ i ] = false; for(int i = 3; i < pr; i += 2) mark[ i ] = true; mark[ 2 ] = true; for(int i = 3, sq = sqrt( pr ); i < sq; i += 2) if(mark[ i ]) for(int j = i * i; j < pr; j += i + i) mark[ j ] = false; prime[ 0 ] = 2; ind = 1; for(int i = 3; i < pr; i += 2) if(mark[ i ]) ind++; printf("%d\n", ind); } */ int diraction1[] = {-1, 0, 0, 1, 1, -1, -1, 1}; int diraction2[] = {0, -1, 1, 0, 1, -1, 1, -1}; int horsed1[] = {-2, -2, -1, 1, 2, 2, 1, -1}; int horsed2[] = {1, -1, -2, -2, -1, 1, 2, 2}; #define check(n, pos) (n & (1<<(pos))) #define biton(n, pos) (n | (1<<(pos))) #define bitoff(n, pos) (n & ~(1<<(pos))) struct FoxAndSouvenirTheNext { int len, sum, mamo[ 55 ][ 55 ][ 55 ], in[ 55 ]; bool mark; string ableToSplit(vector <int> value) { mark = false; string ret; sum = 0; len = value.size(); if(len % 2 != 0) ret = "Impossible"; else { for(int i = 0; i < len; i++) sum += value[ i ], in[ i ] = value[ i ]; if(sum % 2 != 0) ret = "Impossible"; else { sum = sum / 2; len = len / 2; //cout << sum << " " << len << endl; CLR(mamo, -1); int k = DP(0, 0, 0); if(k) ret = "Possible"; else ret = "Impossible"; } } return ret; } int DP(int pos, int su, int cou) { if(pos >= len * 2) { if(su == sum && cou == len) { mark = true; return 1; } return 0; } if(su == sum && cou == len) { mark = true; return 1; } int &ret = mamo[ pos ][ su ][ cou ]; if(ret != -1) return ret; ret = 0; if(su + in[ pos ] <= sum) ret = ret || DP(pos + 1, su + in[ pos ], cou + 1); ret = ret || DP(pos + 1, su, cou); return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {1,2,3,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Possible"; verify_case(0, Arg1, ableToSplit(Arg0)); } void test_case_1() { int Arr0[] = {1,1,1,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Impossible"; verify_case(1, Arg1, ableToSplit(Arg0)); } void test_case_2() { int Arr0[] = {1,1,2,3,5,8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Possible"; verify_case(2, Arg1, ableToSplit(Arg0)); } void test_case_3() { int Arr0[] = {2,3,5,7,11,13}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Impossible"; verify_case(3, Arg1, ableToSplit(Arg0)); } void test_case_4() { int Arr0[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Possible"; verify_case(4, Arg1, ableToSplit(Arg0)); } void test_case_5() { int Arr0[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Impossible"; verify_case(5, Arg1, ableToSplit(Arg0)); } // END CUT HERE }; void input(); /**************************Templet end*********************************/ // BEGIN CUT HERE int main() { FoxAndSouvenirTheNext ___test; ___test.run_test(-1); int gbase; #ifdef monkey //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif input(); return 0; } // END CUT HERE void input() { }
[ "Monkey 'sWorld" ]
Monkey 'sWorld
e316b96be5374d85f03b5bed85eecd9d35e609b6
f408ca85062066a3d8037fb79034d0e9bdf5dcb0
/Source/Foundation/bsfEngine/Private/RTTI/BsResourceMappingRTTI.h
91616cb95b73102313964e4c335d6856dafa55bb
[ "MIT" ]
permissive
xrjervis/bsf
ed1495f71d8b2ec292a8cb4badd293ec67ab0764
1794f0c70c2c53c7c98d87ad8f64acec8e47651c
refs/heads/master
2020-03-09T01:08:14.064455
2018-04-05T17:59:31
2018-04-05T17:59:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,025
h
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "BsPrerequisites.h" #include "Reflection/BsRTTIType.h" #include "Resources/BsGameResourceManager.h" namespace bs { /** @cond RTTI */ /** @addtogroup RTTI-Impl-Engine * @{ */ class BS_EXPORT ResourceMappingRTTI : public RTTIType<ResourceMapping, IReflectable, ResourceMappingRTTI> { private: BS_BEGIN_RTTI_MEMBERS BS_RTTI_MEMBER_PLAIN(mMapping, 0) BS_END_RTTI_MEMBERS public: ResourceMappingRTTI() :mInitMembers(this) { } const String& getRTTIName() override { static String name = "ResourceMapping"; return name; } UINT32 getRTTIId() override { return TID_ResourceMapping; } SPtr<IReflectable> newRTTIObject() override { return ResourceMapping::create(); } }; /** @} */ /** @endcond */ }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
0ee2e17e6e22d78faf3d07156119c59857af9c8c
7bc58e0e6a34f3d74c2da7b367ad348e1a8862d0
/tools/kactus2/kactus2-3.2.35/common/graphicsItems/expandableitem.cpp
58d0b85460d5df34474349820a68e7b509a4bd0f
[]
no_license
ouabache/fossi
3069e7440597b283b657eaee11fbc203909d54aa
e780307bff0bb702e6da36df5d15305354c95f42
refs/heads/master
2020-07-02T08:58:41.834354
2017-04-06T15:59:09
2017-04-06T15:59:09
67,724,364
4
1
null
null
null
null
UTF-8
C++
false
false
4,902
cpp
/* * Created on: 15.10.2012 * Author: Antti Kamppi * filename: expandableitem.cpp * Project: Kactus 2 */ #include "expandableitem.h" #include "graphicsexpandcollapseitem.h" //----------------------------------------------------------------------------- // Function: ExpandableItem::ExpandableItem() //----------------------------------------------------------------------------- ExpandableItem::ExpandableItem(QGraphicsItem* parent): VisualizerItem(parent), expandCollapseItem_(new GraphicsExpandCollapseItem(this)), expansionRect_(new QGraphicsRectItem(this)) { connect(expandCollapseItem_, SIGNAL(stateChanged(bool)), this, SLOT(onExpandStateChange(bool)), Qt::UniqueConnection); setShowExpandableItem(false); expandCollapseItem_->setZValue(1); expansionRect_->show(); } //----------------------------------------------------------------------------- // Function: ExpandableItem::~ExpandableItem() //----------------------------------------------------------------------------- ExpandableItem::~ExpandableItem() { } //----------------------------------------------------------------------------- // Function: ExpandableItem::onExpandStateChange() //----------------------------------------------------------------------------- void ExpandableItem::onExpandStateChange(bool expanded) { // if there are children QList<QGraphicsItem*> children = childItems(); foreach (QGraphicsItem* child, children) { Q_ASSERT(child); // if the item is visualizer item VisualizerItem* childItem = dynamic_cast<VisualizerItem*>(child); if (childItem) { childItem->setVisible(expanded); } } if (expanded) { reorganizeChildren(); } else { updateRectangle(); } emit expandStateChanged(); } //----------------------------------------------------------------------------- // Function: ExpandableItem::setShowExpandableItem() //----------------------------------------------------------------------------- void ExpandableItem::setShowExpandableItem( bool show ) { expandCollapseItem_->setVisible(show); } //----------------------------------------------------------------------------- // Function: ExpandableItem::isExpanded() //----------------------------------------------------------------------------- bool ExpandableItem::isExpanded() const { return expandCollapseItem_->isExpanded(); } //----------------------------------------------------------------------------- // Function: ExpandableItem::reorganizeChildren() //----------------------------------------------------------------------------- void ExpandableItem::reorganizeChildren() { updateRectangle(); VisualizerItem::reorganizeChildren(); } //----------------------------------------------------------------------------- // Function: ExpandableItem::setDefaultBrush() //----------------------------------------------------------------------------- void ExpandableItem::setDefaultBrush(QBrush brush) { VisualizerItem::setDefaultBrush(brush); setExpansionBrush(brush); } //----------------------------------------------------------------------------- // Function: ExpandableItem::setExpansionBrush() //----------------------------------------------------------------------------- void ExpandableItem::setExpansionBrush(QBrush const& brush) { expansionRect_->setBrush(brush); } //----------------------------------------------------------------------------- // Function: ExpandableItem::setExpansionPen() //----------------------------------------------------------------------------- void ExpandableItem::setExpansionPen(QPen const& pen) { expansionRect_->setPen(pen); } //----------------------------------------------------------------------------- // Function: ExpandableItem::setExpansionRectVisible() //----------------------------------------------------------------------------- void ExpandableItem::setExpansionRectVisible(bool visible) { expansionRect_->setVisible(visible); } //----------------------------------------------------------------------------- // Function: ExpandableItem::updateHeight() //----------------------------------------------------------------------------- void ExpandableItem::updateRectangle() { // the rectangle that contains this item and children QRectF totalRect = itemTotalRect(); // the rectangle is on the left side of the parent and children expansionRect_->setRect(-GraphicsExpandCollapseItem::SIDE, 0, GraphicsExpandCollapseItem::SIDE, totalRect.height()); // Set the position for the expand/collapse item with the icon. expandCollapseItem_->setPos(-GraphicsExpandCollapseItem::SIDE, GraphicsExpandCollapseItem::SIDE / 2 + VisualizerItem::CORNER_INDENTATION); }
[ "z3qmtr45@gmail.com" ]
z3qmtr45@gmail.com
ad5c5ef2c2ad706131ac904a499b038a823ed5c5
a4fbd22fec95beba17fa15026a1812d30426e839
/November long Challenge 3.11.17/Left Right Left/main.cpp
08e64e428348df0bd870a5471099180eace15f00
[]
no_license
codesniper99/Coding-Competitions
bb368fc051f60e02fea73e90d3056f0ffe6af6f3
6fcb6a90f46842274f7b700af5edf4f60ecbb4d9
refs/heads/master
2021-07-04T22:45:32.322362
2020-09-07T20:19:26
2020-09-07T20:19:26
171,656,734
1
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
// SOOOOOOOOOOOOOOOOOOOOOLVED #include <iostream> #include<bits/stdc++.h> #include<vector> #define ll long long int using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int t; scanf("%d",&t); while(t--) { ll n,r; scanf("%lld %lld",&n,&r); vector<long long int>a(n); for(ll i=0;i<n;i++) scanf("%lld",&a[i]); ll left,right; ll current; int flag=0; current = a[0]; left = -1000000001; right = 1000000001; if(a[n-1]!=r) { printf("NO\n"); continue; } for(ll i=1;i<n;i++) { if(a[i]<left||a[i]>right) { flag=1; printf("NO\n"); break; } if(a[i]>left&&a[i]<right) { if(a[i]<current) { right=current; current=a[i]; } else if(a[i]>current) { left=current; current=a[i]; } else ; } } if(flag==0) printf("YES\n"); } return 0; }
[ "akhilvaid21@gmail.com" ]
akhilvaid21@gmail.com
5480cf1465806639295c2c2724c07e65db8d65e8
1a5a3b9f8675000cf94b1a6797a909e1a0fcc40e
/src/common/CHotICON.h
9e26bb16d5dba12d548162d3b3de683492315302
[]
no_license
Davidixx/client
f57e0d82b4aeec75394b453aa4300e3dd022d5d7
4c0c1c0106c081ba9e0306c14607765372d6779c
refs/heads/main
2023-07-29T19:10:20.011837
2021-08-11T20:40:39
2021-08-11T20:40:39
403,916,993
0
0
null
2021-09-07T09:21:40
2021-09-07T09:21:39
null
UHC
C++
false
false
1,360
h
#ifndef __CHOTICON_H #define __CHOTICON_H #pragma warning (disable:4201) //------------------------------------------------------------------------------------------------- /// 최대 단축 아이콘 등록 가능 갯수 #ifdef _NEWUI #define MAX_ICONS_PAGES 6 // normal 4 + ext 2 #define MAX_ICONS_PAGES_NORMAL 4 #define MAX_ICONS_PAGES_EXT 2 #define HOT_ICONS_PER_PAGE 8 #define MAX_HOT_ICONS 48 #else #define MAX_ICONS_PAGES 4 #define MAX_ICONS_PAGES_NORMAL 4 #define HOT_ICONS_PER_PAGE 8 #define MAX_HOT_ICONS 32 #endif enum t_HotIconTYPE { INV_ICON = 1, COMMAND_ICON, SKILL_ICON, EMOTION_ICON, DIALOG_ICON, CLANSKILL_ICON, } ; #pragma pack (push, 1) union tagHotICON { struct { unsigned short m_cType : 5; // 0~31 unsigned short m_nSlotNo : 11; // 0~2047 } ; WORD m_wHotICON; } ; class CHotICONS { public : union { tagHotICON m_IconLIST[ MAX_HOT_ICONS ]; tagHotICON m_IconPAGE[ MAX_ICONS_PAGES ][ HOT_ICONS_PER_PAGE ]; } ; void Init (); bool RegHotICON (BYTE btListIDX, tagHotICON sHotICON); void DelHotICON (BYTE btListIDX); #ifndef __SERVER void UpdateHotICON(); #endif } ; #pragma pack (pop) //------------------------------------------------------------------------------------------------- #pragma warning (default:4201) #endif
[ "ralphminderhoud@gmail.com" ]
ralphminderhoud@gmail.com
89a9929ff7b26ac1e1595c0c6379f61d99ba6a0e
c643d601e8caaa904b86d46b97d3e81b23bdd7ea
/Smooth_Thermocouple/Smooth_Thermocouple.ino
039b631d765a9cbbfeacacbb13ac6c9831a99d25
[]
no_license
kipa200/Auto_Thermocouple
68ddc2f752c8d941956c6f1bcda5391b75b7117f
2766bbdf145de278da94b1e7e688f645398e13fa
refs/heads/master
2022-08-06T15:29:33.346516
2020-05-17T06:13:10
2020-05-17T06:13:10
264,355,095
5
0
null
null
null
null
UTF-8
C++
false
false
3,127
ino
#include "LiquidCrystal_I2C.h" #include <SPI.h> #include <Wire.h> #include <Thermocouple.h> #include <MAX6675_Thermocouple.h> #include <SmoothThermocouple.h> #include <SD.h> //#define Button_PIN 2 //thermal #define Thermal_SCK_PIN 3 #define Thermal_CS_PIN 4 #define Thermal_SO_PIN 5 #define READINGS_NUMBER 30 #define DELAY_TIME 10 #define SMOOTHING_FACTOR 5 Thermocouple* thermocouple_Smooth = NULL; //SD #define SD_CS_PIN 7 File myTemp; //LCD //#define LCD_SDA_PIN A4 //#define LCD_SCL_PIN A5 LiquidCrystal_I2C lcd(0x27, 16, 2);// 0x27 is the I2C bus address for an unmodified backpack void setup() { // put your setup code here, to run once: // pinMode(2,INPUT_PULLUP);//2号引脚接开关OUT,控制程序开始 // while(digitalRead(2)){ // Serial.print("WAITING"); // }//按下按键前,2为高电平,返回1,执行空死循环 //LCD Initialization lcd.init(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("HELLO"); delay(500); lcd.setCursor(0, 1); lcd.print("FROM HEU KIPA"); delay(500); //PC Initialization Serial.begin(9600); Serial.print("Initializing SD card..."); //SD Initialization pinMode(10,OUTPUT);//SS引脚(UNO=10),保持输出,SD卡工作 if (!SD.begin(SD_CS_PIN)) { Serial.println("Initialization failled!"); while (1);//初始化失败,执行空死循环,不进入loop循环 } Serial.println("Initialization done."); //SD_File Initialization 打开文件,且一次只能打开一个文件,若需打开另一文件,须先关闭当前文件 myTemp = SD.open("TempRec.txt", FILE_WRITE); // if the file opened okay, write to it: if (myTemp) { Serial.print("Writing to TempRec.txt..."); myTemp.println("Temperature records are about to begin."); // close the file: myTemp.close(); Serial.println("Temperature records are about to begin."); } else { // if the file didn't open, print an error: Serial.println("Error opening File in setup"); lcd.setCursor(0, 1); lcd.print("Setup File Error"); } //MAX6675 Initialization Serial.print("Read data from MAX6675: "); lcd.setCursor(0, 0); lcd.print("MAX6675 Rec"); thermocouple_Smooth = new SmoothThermocouple( new MAX6675_Thermocouple(Thermal_SCK_PIN, Thermal_CS_PIN, Thermal_SO_PIN), SMOOTHING_FACTOR ); } void loop() { // put your main code here, to run repeatedly: // Reads temperature const double Smooth_celsius = thermocouple_Smooth->readCelsius(); Serial.println("Read data and write data"); myTemp = SD.open("TempRec.txt", FILE_WRITE); if(myTemp){ myTemp.print(Smooth_celsius); myTemp.println(" "); Serial.println("File Writen"); myTemp.close(); } else{ Serial.println("Error opening File"); } lcd.clear(); lcd.setCursor(0, 0); lcd.print("MAX6675 Rec(C)"); lcd.setCursor(0, 1); lcd.print("Temp: "); lcd.print(Smooth_celsius); // Output of information PC Serial.print("Smooth_Temperature: "); Serial.print(Smooth_celsius); Serial.println(" C. "); delay(500); // optionally, only to delay the output of information in the example. }
[ "46548932+kipa200@users.noreply.github.com" ]
46548932+kipa200@users.noreply.github.com
a2fad5e63caa848cf9377ab7114efb5be5598d81
19ccfd6806c5054679dab3f275822302206b222f
/src/game/server/te_beampoints.cpp
00b23acba714f4dd080d27a4e61c1fe4a14420d5
[ "Apache-2.0" ]
permissive
BenLubar/SwarmDirector2
425441d5ac3fd120c998379ddc96072b2c375109
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
refs/heads/master
2021-01-17T22:14:37.146323
2015-07-09T19:18:03
2015-07-09T19:18:03
20,357,966
4
1
Apache-2.0
2018-08-30T13:37:22
2014-05-31T15:00:51
C++
WINDOWS-1252
C++
false
false
4,362
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basetempentity.h" #include "te_basebeam.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern int g_sModelIndexSmoke; // (in combatweapon.cpp) holds the index for the smoke cloud //----------------------------------------------------------------------------- // Purpose: Dispatches a beam ring between two entities //----------------------------------------------------------------------------- class CTEBeamPoints : public CTEBaseBeam { public: DECLARE_CLASS( CTEBeamPoints, CTEBaseBeam ); DECLARE_SERVERCLASS(); CTEBeamPoints( const char *name ); virtual ~CTEBeamPoints( void ); virtual void Test( const Vector& current_origin, const QAngle& current_angles ); public: CNetworkVector( m_vecStartPoint ); CNetworkVector( m_vecEndPoint ); }; //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- CTEBeamPoints::CTEBeamPoints( const char *name ) : CTEBaseBeam( name ) { m_vecStartPoint.Init(); m_vecEndPoint.Init(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTEBeamPoints::~CTEBeamPoints( void ) { } //----------------------------------------------------------------------------- // Purpose: // Input : *current_origin - // *current_angles - //----------------------------------------------------------------------------- void CTEBeamPoints::Test( const Vector& current_origin, const QAngle& current_angles ) { m_nModelIndex = g_sModelIndexSmoke; m_nStartFrame = 0; m_nFrameRate = 10; m_fLife = 2.0; m_fWidth = 1.0; m_fAmplitude = 1; r = 0; g = 63; b = 127; a = 150; m_nSpeed = 1; m_vecStartPoint = current_origin; Vector forward, right; m_vecStartPoint += Vector( 0, 0, 30 ); AngleVectors( current_angles, &forward, &right, 0 ); forward[2] = 0.0; VectorNormalize( forward ); VectorMA( m_vecStartPoint, 75.0, forward, m_vecStartPoint.GetForModify() ); VectorMA( m_vecStartPoint, 25.0, right, m_vecEndPoint.GetForModify() ); VectorMA( m_vecStartPoint, -25.0, right, m_vecStartPoint.GetForModify() ); CBroadcastRecipientFilter filter; Create( filter, 0.0 ); } IMPLEMENT_SERVERCLASS_ST( CTEBeamPoints, DT_TEBeamPoints) SendPropVector( SENDINFO(m_vecStartPoint), -1, SPROP_COORD ), SendPropVector( SENDINFO(m_vecEndPoint), -1, SPROP_COORD ), END_SEND_TABLE() // Singleton to fire TEBeamPoints objects static CTEBeamPoints g_TEBeamPoints( "BeamPoints" ); //----------------------------------------------------------------------------- // Purpose: // Input : msg_dest - // delay - // *origin - // *recipient - // *start - // *end - // modelindex - // startframe - // framerate - // msg_dest - // delay - // origin - // recipient - //----------------------------------------------------------------------------- void TE_BeamPoints( IRecipientFilter& filter, float delay, const Vector* start, const Vector* end, int modelindex, int haloindex, int startframe, int framerate, float life, float width, float endWidth, int fadeLength, float amplitude, int r, int g, int b, int a, int speed ) { g_TEBeamPoints.m_vecStartPoint = *start; g_TEBeamPoints.m_vecEndPoint = *end; g_TEBeamPoints.m_nModelIndex = modelindex; g_TEBeamPoints.m_nHaloIndex = haloindex; g_TEBeamPoints.m_nStartFrame = startframe; g_TEBeamPoints.m_nFrameRate = framerate; g_TEBeamPoints.m_fLife = life; g_TEBeamPoints.m_fWidth = width; g_TEBeamPoints.m_fEndWidth = endWidth; g_TEBeamPoints.m_nFadeLength = fadeLength; g_TEBeamPoints.m_fAmplitude = amplitude; g_TEBeamPoints.m_nSpeed = speed; g_TEBeamPoints.r = r; g_TEBeamPoints.g = g; g_TEBeamPoints.b = b; g_TEBeamPoints.a = a; // Send it over the wire g_TEBeamPoints.Create( filter, delay ); }
[ "ben.lubar@gmail.com" ]
ben.lubar@gmail.com
48ccbc8cdaeee9bf791907db0e49959638fa461a
01a8d4f2dd5de176287699b5e659b646011427a2
/FELICITY/Code_Generation/Matrix_Assembly/Unit_Test/Hdiv/RT1_Dim3/Scratch_Dir/Div_Matrix_Omega.cpp
44e0a7828d59924fe3f4c9a94939bf4c868a5c3a
[ "BSD-3-Clause", "MIT" ]
permissive
brianchowlab/BcLOV4-FEM
2bd2286011f5d09d01a9973c59023031612b63b2
27432974422d42b4fe3c8cc79bcdd5cb14a800a7
refs/heads/main
2023-04-16T08:27:57.927561
2022-05-27T15:26:46
2022-05-27T15:26:46
318,320,689
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
cpp
/***************************************************************************************/ /* Tabulate the tensor for the local element contribution */ void SpecificFEM::Tabulate_Tensor(const CLASS_geom_Omega_embedded_in_Omega_restricted_to_Omega& Mesh) { const unsigned int NQ = 10; // Compute element tensor using quadrature // Loop quadrature points for integral for (unsigned int j = 0; j < COL_NB; j++) { for (unsigned int i = 0; i < ROW_NB; i++) { double A0_value = 0.0; // initialize for (unsigned int qp = 0; qp < NQ; qp++) { const double integrand_0 = (*P1_phi_restricted_to_Omega->Func_f_Value)[j][qp].a*RT1_phi_restricted_to_Omega->Func_vv_Div[i][qp].a; A0_value += integrand_0 * Mesh.Map_Det_Jac_w_Weight[qp].a; } FE_Tensor_0[j*ROW_NB + i] = A0_value; } } } /***************************************************************************************/
[ "ikuznet1@users.noreply.github.com" ]
ikuznet1@users.noreply.github.com
22f9ecc4e8ea927fb4244773f4a7c63e6dd5b1ec
61a2098d994eeaf980bf6f18d9d0d8d6b6e4303f
/pro_sl/StdAfx.cpp
13f2514e65805156f1beaa839d4864ba0280d9e3
[]
no_license
abdullah38rcc/MFC-SaoLei
782729429197512914000eb47d87ce8e2b8827cd
2b84e7e4a7aba34a08e29771edabd1924b690ab3
refs/heads/master
2020-11-30T11:54:21.422634
2013-06-07T13:00:06
2013-06-07T13:00:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
// stdafx.cpp : source file that includes just the standard includes // pro_sl.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "zhh358@gmail.com" ]
zhh358@gmail.com
9bef98f859642e588e1e3f00564f0713faa7dbdf
1791461e6740f81c2dd6704ae6a899a6707ee6b1
/UESTC/2374-Block.cpp
62d5318dde8aafb62d5e39bedd046ed006d718ea
[ "MIT" ]
permissive
HeRaNO/OI-ICPC-Codes
b12569caa94828c4bedda99d88303eb6344f5d6e
4f542bb921914abd4e2ee7e17d8d93c1c91495e4
refs/heads/master
2023-08-06T10:46:32.714133
2023-07-26T08:10:44
2023-07-26T08:10:44
163,658,110
22
6
null
null
null
null
UTF-8
C++
false
false
1,434
cpp
#include <bits/stdc++.h> #define MAXN 2000005 #define MAXB 1420 using namespace std; const int INF=1e9; int T,n,m,b,l,k,pt,a[MAXN],pos[MAXN],mx[MAXB]; inline void clean(int x) { int l=(x-1)*b,r=x*b; for (int i=l;i<r&&i<n;i++) mx[x]=max(mx[x],a[i]); return ; } inline int getBlock(int x,int v) { int l=(x-1)*b,r=x*b; for (int i=l;i<r;i++) if (a[i]>=v) return i; assert(false); return -1; } inline int query(int l,int r,int v) { if (pos[l]==pos[r]) { for (int i=l;i<=r;i++) if (a[i]>=v) return i; return -1; } for (int i=l,p=pos[l]*b;i<p;i++) if (a[i]>=v) return i; for (int i=pos[l]+1;i<pos[r];i++) if (mx[i]>=v) return getBlock(i,v); for (int i=(pos[r]-1)*b;i<=r;i++) if (a[i]>=v) return i; return -1; } inline void modify(int x) { int l=(pos[x]-1)*b,r=pos[x]*b;a[x]=-INF; x=pos[x];mx[x]=-INF; for (int i=l;i<r&&i<n;i++) mx[x]=max(mx[x],a[i]); return ; } inline void read(int &x) { x=0;char ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return ; } int main() { read(n);b=sqrt(n);m=n/b; if (n%b) ++m; for (int i=0;i<n;i++) { read(a[i]); pos[i]=i/b+1; } for (int i=1;i<=m;i++) clean(i); read(T); for (int i=0;i<T;i++) { read(l);read(k);k-=i; pt=query(l,n-1,k); if (!~pt&&l) pt=query(0,l-1,k); if (!~pt) puts("-1"); else { l=pt-l+n;if (l>=n) l-=n; printf("%d\n",l); modify(pt); } } return 0; }
[ "heran55@126.com" ]
heran55@126.com
e6a9a1af0a8919a281130cee5322580a70637241
ad878f66367bcd5fc8cab83a004dad147b87e638
/duyetcaydanhsach.cpp
7477087294d5e18964e2ca2811d14911d5c27d0b
[]
no_license
Tamabcxyz/CodeCauTrucDuLieu
9338c61f87753d226440260488742d0863b76d53
3f3224c9bd06724ba0e25904b2a5682a32856998
refs/heads/master
2020-04-27T10:06:27.712090
2019-03-07T00:14:21
2019-03-07T00:14:21
174,240,334
0
0
null
null
null
null
UTF-8
C++
false
false
2,531
cpp
#include <stdio.h> #include <conio.h> #define MAX 30 #define NIL -1 typedef char datatype; typedef int node; typedef struct{ node parent[MAX];// luu tru nut cha int maxnode;// quan ly so luong nut that su cua cay datatype data[MAX];// luu tru nhan(giu lieu trong o) }tree; // tao cay rong ko co meo j het void makenull(tree &T){ T.maxnode=0; } // kiem tra xem cay co meo j chua int empty(tree T){ return T.maxnode==0; } // xac dinh nut cha cua nut tren cay node parent(tree T, node n){ if(empty(T)||n>T.maxnode-1)return NIL; else return T.parent[n]; } // xac dinh nhan cua nut n datatype lable_node(tree T, node n){ if(!empty(T)&&n<=T.maxnode-1)return T.data[n]; else printf("ko co nhan\n"); } // ham mac dinh nut goc trong cay int root(tree T){ if(!empty(T))return 0; else return NIL; } // ham xac dinh con trai nhat cua 1 nut node leftmost_child(tree T,node n){ node i=n+1; int find=0; if(n<0)return NIL; while(i<=T.maxnode-1&&find==0){ if(T.parent[i]==n) find=1; else i++; }if(find==1)return i; else return NIL; } // ham xac dinh ae ruot phai cua 1 nut node right_sibling(tree T, node n){ node i=n+1; int find=0; if(n<0)return NIL; while(i<=T.maxnode-1&&find==0){ if(T.parent[i]==T.parent[n]) find=1; else i++; }if(find==1)return i; else return NIL; } // duyet tien tu void preorder(tree T, node n){ node i; printf("%c",lable_node(T,n)); i=leftmost_child(T,n); while(i!=NIL){ preorder(T,i); i=right_sibling(T,i); } } // duyet trung tu void inorder(tree T, node n){ node i; i=leftmost_child(T,n); if(i!=NIL)inorder(T,i); printf("%c",lable_node(T,n)); i=right_sibling(T,i); while(i!=NIL){ inorder(T,i); i=right_sibling(T,i); } } // duyet hau tu void postorder(tree T, node n){ node i; i=leftmost_child(T,n); while(i!=NIL){ postorder(T,i); i=right_sibling(T,i); } printf("%c",lable_node(T,n)); } void readtree(tree &T){ makenull(T); node n; do{ printf("co bao nhieu phan tu\n"); scanf("%d",&T.maxnode); }while(T.maxnode<1||T.maxnode>MAX); printf("nhap nhan(gia tri cua nut 0)\n");fflush(stdin); scanf("%c",&T.data[0]); T.parent[0]=NIL; printf("\nnhap cac phan tu con lai\n"); for(int i=1;i<T.maxnode;i++){ printf("cha cua nut %d la ",i);fflush(stdin); scanf("%d",&T.parent[i]); printf("\n nhan cua nut la ");fflush(stdin); scanf("%c",&T.data[i]); } } int main(){ tree T; readtree(T); printf("duyet tien tu\n"); preorder(T,root(T)); printf("\nduyet trung tu\n"); inorder(T,root(T)); printf("\nduyet hau tu\n"); postorder(T,root(T)); }
[ "minhtam16071999@gmail.com" ]
minhtam16071999@gmail.com
06e06ef4426552d662023a900139d2f4fa15f4dc
38c10c01007624cd2056884f25e0d6ab85442194
/chrome/installer/util/work_item.h
a8c53769b9726ab77d1fa4d9f3b9da019efe6fc0
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
9,001
h
// Copyright (c) 2011 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. // // Base class for managing an action of a sequence of actions to be carried // out during install/update/uninstall. Supports rollback of actions if this // process fails. #ifndef CHROME_INSTALLER_UTIL_WORK_ITEM_H_ #define CHROME_INSTALLER_UTIL_WORK_ITEM_H_ #include <windows.h> #include <string> #include <vector> #include "base/basictypes.h" #include "base/callback_forward.h" class CallbackWorkItem; class CopyTreeWorkItem; class CreateDirWorkItem; class CreateRegKeyWorkItem; class DeleteTreeWorkItem; class DeleteRegKeyWorkItem; class DeleteRegValueWorkItem; class MoveTreeWorkItem; class SelfRegWorkItem; class SetRegValueWorkItem; class WorkItemList; namespace base { class FilePath; } // A base class that defines APIs to perform/rollback an action or a // sequence of actions during install/update/uninstall. class WorkItem { public: // A callback that returns the desired value based on the |existing_value|. // |existing_value| will be empty if the value didn't previously exist or // existed under a non-string type. using GetValueFromExistingCallback = base::Callback<std::wstring(const std::wstring& existing_value)>; // All registry operations can be instructed to operate on a specific view // of the registry by specifying a REGSAM value to the wow64_access parameter. // The wow64_access parameter can be one of: // KEY_WOW64_32KEY - Operate on the 32-bit view. // KEY_WOW64_64KEY - Operate on the 64-bit view. // kWow64Default - Operate on the default view (e.g. 32-bit on 32-bit // systems, and 64-bit on 64-bit systems). // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa384129.aspx static const REGSAM kWow64Default = 0; // Possible states enum CopyOverWriteOption { ALWAYS, // Always overwrite regardless of what existed before. NEVER, // Not used currently. IF_DIFFERENT, // Overwrite if different. Currently only applies to file. IF_NOT_PRESENT, // Copy only if file/directory do not exist already. NEW_NAME_IF_IN_USE // Copy to a new path if dest is in use(only files). }; // Options for the MoveTree work item. enum MoveTreeOption { ALWAYS_MOVE, // Always attempt to do a move operation. CHECK_DUPLICATES // Only move if the move target is different. }; // Abstract base class for the conditions used by ConditionWorkItemList. // TODO(robertshield): Move this out of WorkItem. class Condition { public: virtual ~Condition() {} virtual bool ShouldRun() const = 0; }; virtual ~WorkItem(); // Create a CallbackWorkItem that invokes a callback. static CallbackWorkItem* CreateCallbackWorkItem( base::Callback<bool(const CallbackWorkItem&)> callback); // Create a CopyTreeWorkItem that recursively copies a file system hierarchy // from source path to destination path. // * If overwrite_option is ALWAYS, the created CopyTreeWorkItem always // overwrites files. // * If overwrite_option is NEW_NAME_IF_IN_USE, file is copied with an // alternate name specified by alternative_path. static CopyTreeWorkItem* CreateCopyTreeWorkItem( const base::FilePath& source_path, const base::FilePath& dest_path, const base::FilePath& temp_dir, CopyOverWriteOption overwrite_option, const base::FilePath& alternative_path); // Create a CreateDirWorkItem that creates a directory at the given path. static CreateDirWorkItem* CreateCreateDirWorkItem(const base::FilePath& path); // Create a CreateRegKeyWorkItem that creates a registry key at the given // path. static CreateRegKeyWorkItem* CreateCreateRegKeyWorkItem( HKEY predefined_root, const std::wstring& path, REGSAM wow64_access); // Create a DeleteRegKeyWorkItem that deletes a registry key at the given // path. static DeleteRegKeyWorkItem* CreateDeleteRegKeyWorkItem( HKEY predefined_root, const std::wstring& path, REGSAM wow64_access); // Create a DeleteRegValueWorkItem that deletes a registry value static DeleteRegValueWorkItem* CreateDeleteRegValueWorkItem( HKEY predefined_root, const std::wstring& key_path, REGSAM wow64_access, const std::wstring& value_name); // Create a DeleteTreeWorkItem that recursively deletes a file system // hierarchy at the given root path. A key file can be optionally specified // by key_path. static DeleteTreeWorkItem* CreateDeleteTreeWorkItem( const base::FilePath& root_path, const base::FilePath& temp_path, const std::vector<base::FilePath>& key_paths); // Create a MoveTreeWorkItem that recursively moves a file system hierarchy // from source path to destination path. static MoveTreeWorkItem* CreateMoveTreeWorkItem( const base::FilePath& source_path, const base::FilePath& dest_path, const base::FilePath& temp_dir, MoveTreeOption duplicate_option); // Create a SetRegValueWorkItem that sets a registry value with REG_SZ type // at the key with specified path. static SetRegValueWorkItem* CreateSetRegValueWorkItem( HKEY predefined_root, const std::wstring& key_path, REGSAM wow64_access, const std::wstring& value_name, const std::wstring& value_data, bool overwrite); // Create a SetRegValueWorkItem that sets a registry value with REG_DWORD type // at the key with specified path. static SetRegValueWorkItem* CreateSetRegValueWorkItem( HKEY predefined_root, const std::wstring& key_path, REGSAM wow64_access, const std::wstring& value_name, DWORD value_data, bool overwrite); // Create a SetRegValueWorkItem that sets a registry value with REG_QWORD type // at the key with specified path. static SetRegValueWorkItem* CreateSetRegValueWorkItem( HKEY predefined_root, const std::wstring& key_path, REGSAM wow64_access, const std::wstring& value_name, int64 value_data, bool overwrite); // Create a SetRegValueWorkItem that sets a registry value based on the value // provided by |get_value_callback| given the existing value under // |key_path\value_name|. static SetRegValueWorkItem* CreateSetRegValueWorkItem( HKEY predefined_root, const std::wstring& key_path, REGSAM wow64_access, const std::wstring& value_name, const GetValueFromExistingCallback& get_value_callback); // Add a SelfRegWorkItem that registers or unregisters a DLL at the // specified path. static SelfRegWorkItem* CreateSelfRegWorkItem(const std::wstring& dll_path, bool do_register, bool user_level_registration); // Create an empty WorkItemList. A WorkItemList can recursively contains // a list of WorkItems. static WorkItemList* CreateWorkItemList(); // Create an empty WorkItemList that cannot be rolled back. // Such a work item list executes all items on a best effort basis and does // not abort execution if an item in the list fails. static WorkItemList* CreateNoRollbackWorkItemList(); // Create a conditional work item list that will execute only if // condition->ShouldRun() returns true. The WorkItemList instance // assumes ownership of condition. static WorkItemList* CreateConditionalWorkItemList(Condition* condition); // Perform the actions of WorkItem. Returns true if success, returns false // otherwise. // If the WorkItem is transactional, then Do() is done as a transaction. // If it returns false, there will be no change on the system. virtual bool Do() = 0; // Rollback any actions previously carried out by this WorkItem. If the // WorkItem is transactional, then the previous actions can be fully // rolled back. If the WorkItem is non-transactional, the rollback is a // best effort. virtual void Rollback() = 0; // If called with true, this WorkItem may return true from its Do() method // even on failure and Rollback will have no effect. void set_ignore_failure(bool ignore_failure) { ignore_failure_ = ignore_failure; } // Returns true if this WorkItem should ignore failures. bool ignore_failure() const { return ignore_failure_; } // Sets an optional log message that a work item may use to print additional // instance-specific information. void set_log_message(const std::string& log_message) { log_message_ = log_message; } // Retrieves the optional log message. The retrieved string may be empty. const std::string& log_message() const { return log_message_; } protected: WorkItem(); // Specifies whether this work item my fail to complete and yet still // return true from Do(). bool ignore_failure_; std::string log_message_; }; #endif // CHROME_INSTALLER_UTIL_WORK_ITEM_H_
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
1c929cb9dffe634814c25d581a8b9b5d59388b61
3677aebe1c05c91fb8eea8d97ca3748d7e510708
/include/Sylvester/Server/request.h
fcaff1f818f3dcba38737cd03e9534c134f87050
[]
no_license
njoubert/Sylvester
3b46eec015c554000dccf532bca8ed02d4e8a3a7
6e39ceb01a3d478fc5ee8529f8691b8ad0efb3a2
refs/heads/master
2021-01-13T02:06:26.183969
2011-01-29T00:16:03
2011-01-29T00:16:03
1,278,134
0
0
null
null
null
null
UTF-8
C++
false
false
399
h
// // request.h // // Created by Niels Joubert on 2011-01-21. // Copyright (c) 2011 Niels Joubert. All rights reserved. // #ifndef INCLUDE_SYLVESTER_SERVER_REQUEST_H_ #define INCLUDE_SYLVESTER_SERVER_REQUEST_H_ namespace Sylvester { namespace Server { class Request { public: private: }; } /* namespace Server */ } /* namespace Sylvester */ #endif // INCLUDE_SYLVESTER_SERVER_REQUEST_H_
[ "njoubert@gmail.com" ]
njoubert@gmail.com
44cab20cb5bc2a0d39fe25cde3fc56f680e72cd8
438e7e41206157a38e4318450a91e4cc1a5af564
/TP1/Ej5/main.cpp
2130f48dbcbacd7b8ce0544c759651e55d04d862
[]
no_license
gtessi/PDI2014-FICH
f793d8af457a673432ff3c79d1056122de550a00
dd9d4e2df2ff70a711a5cf747875abc3134f1e8b
refs/heads/master
2020-03-27T05:51:19.198022
2018-08-25T02:51:25
2018-08-25T02:51:25
146,057,455
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
#include <iostream> #include "CImg.h" using namespace cimg_library; using namespace std; int main(int argc, char** argv) { // Carga la imagen en filename const char* filename = cimg_option("-i","rmn.jpg","Image file\n"); CImg<unsigned char> img100(filename); // imagen // Dimensiones originales unsigned int alto=img100.height(); unsigned int ancho=img100.width(); // Aprovecha el pipeline, primero reduce la imagen y la vuelve a agrandar // como si se tratara de un objeto sobre otro (viola el encapsulamiento) // Escala la imagen original en un 50% CImg<unsigned char> img50=img100.get_resize(alto/2,ancho/2).get_resize(alto,ancho); // Escala la imagen original en un 25% CImg<unsigned char> img25=img100.get_resize(alto/4,ancho/4).get_resize(alto,ancho); // Escala la imagen original en un 12.5% CImg<unsigned char> img125=img100.get_resize(alto/8,ancho/8).get_resize(alto,ancho); // // Guarda las imagenes escaladas // img50.save("rmn50.jpg"); // 50% // img25.save("rmn25.jpg"); // 25% // img125.save("rmn125.jpg"); // 12.5% // no me deja guardar los archivos como jpg // Crea una lista donde muestra todas las imagenes CImgList<unsigned char> lista; lista.assign(img100,img50,img25,img125); lista.display("Lista de imagenes con diferente resolucion espacial"); cout<<"*********************************************************"<<endl<<endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
a98b4f16e72bf8f0c386384de529639502d11956
0ca8832a2818af66f1a584d7cf6c56abf0af8591
/src/thirdparty/boost/boost/mpl/or.hpp
3a76ed1049182b9996215089a3106d24e906ba15
[]
no_license
knobik/source-python
241e27d325d40fc8374fc9fb8f8311a146dc7e77
e57308a662c25110f1a1730199985a5f2cf11713
refs/heads/master
2021-01-10T08:28:55.402519
2013-09-12T04:00:12
2013-09-12T04:00:12
54,717,312
0
0
null
null
null
null
UTF-8
C++
false
false
1,740
hpp
#ifndef BOOST_MPL_OR_HPP_INCLUDED #define BOOST_MPL_OR_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: or.hpp 49239 2008-10-10 09:10:26Z agurtovoy $ // $Date: 2008-10-10 05:10:26 -0400 (Fri, 10 Oct 2008) $ // $Revision: 49239 $ #include <boost/mpl/aux_/config/use_preprocessed.hpp> #if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/bool.hpp> # include <boost/mpl/aux_/nested_type_wknd.hpp> # include <boost/mpl/aux_/na_spec.hpp> # include <boost/mpl/aux_/lambda_support.hpp> # include <boost/mpl/aux_/config/msvc.hpp> // agurt, 19/may/04: workaround a conflict with <iso646.h> header's // 'or' and 'and' macros, see http://tinyurl.com/3et69; 'defined(or)' // has to be checked in a separate condition, otherwise GCC complains // about 'or' being an alternative token #if defined(_MSC_VER) #ifndef __GCCXML__ #if defined(or) # pragma push_macro("or") # undef or # define or(x) #endif #endif #endif # define BOOST_MPL_PREPROCESSED_HEADER or.hpp # include <boost/mpl/aux_/include_preprocessed.hpp> #if defined(_MSC_VER) #ifndef __GCCXML__ #if defined(or) # pragma pop_macro("or") #endif #endif #endif #else # define AUX778076_OP_NAME or_ # define AUX778076_OP_VALUE1 true # define AUX778076_OP_VALUE2 false # include <boost/mpl/aux_/logical_op.hpp> #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // BOOST_MPL_OR_HPP_INCLUDED
[ "satoon101@gmail.com" ]
satoon101@gmail.com
69d53ede60d1825b86533280d1755759a1841f7c
c9b02ab1612c8b436c1de94069b139137657899b
/tradeWar/app/config/CommonConfig.h
33e5a3eac8d2ba94a183bf2749413ff4172b6534
[]
no_license
colinblack/game_server
a7ee95ec4e1def0220ab71f5f4501c9a26ab61ab
a7724f93e0be5c43e323972da30e738e5fbef54f
refs/heads/master
2020-03-21T19:25:02.879552
2020-03-01T08:57:07
2020-03-01T08:57:07
138,948,382
1
1
null
null
null
null
UTF-8
C++
false
false
499
h
/* * CommonConfig.h * * Created on: 2016年6月16日 * Author: asdf */ #ifndef CONFIG_COMMON_CONFIG_H_ #define CONFIG_COMMON_CONFIG_H_ using std::vector; using std::set; using std::pair; template<typename T> bool parseArray(const Json::Value &v, vector<T> &d) { if (v.isNull() || !v.isArray()) { return false; } for (size_t i = 0; i < v.size(); ++i) { unsigned item = 0; Json::GetUInt(v, i, item); d.push_back(item); } return true; } #endif /* CONFIG_COMMON_CONFIG_H_ */
[ "178370407@qq.com" ]
178370407@qq.com
6bf1040b680fb0c2a8a18ef74e40c09d2b8aa273
386a109ecc8ab5e57cf2181f81fa0302df0b4505
/Engine/RectF.cpp
9b367d1b3e9080f4c95aa37edc5dbe9493e9e989
[]
no_license
Games28/the-pong-wars
a93760e99fa95496e3321946c4d615b6a402b549
ace26bef80e541e96cedaf7c9931e7c465eb3731
refs/heads/master
2020-05-30T20:06:37.793797
2019-06-06T08:23:46
2019-06-06T08:23:46
189,940,528
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
cpp
#include "RectF.h" RectF::RectF(float left_in, float right_in, float top_in, float bottom_in) : left(left_in), right(right_in), top(top_in), bottom(bottom_in) { } RectF::RectF(const Vec2 & topLeft, const Vec2 & bottomRight) // this takes the individual corrdiantes of xy1 to xy 2 : RectF(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y) // 40, 100, 40, 60 { } RectF::RectF(const Vec2 & topLeft, float width, float height)// this takes in the topleft or first xy and just add width/height. : RectF(topLeft,topLeft +Vec2(width, height)) { } bool RectF::IsOverLappingWith(const RectF & other) const { return right > other.left && left < other.right && bottom >other.top && top < other.bottom; } RectF RectF::FromCenter(const Vec2 & center, float halfWidth, float halfHeight) { const Vec2 half(halfWidth, halfHeight); return RectF(center - half, center + half); } RectF RectF::GetExpended(float offset) const { return RectF(left - offset, right + offset, top - offset, bottom + offset);; }
[ "43530438+Games28@users.noreply.github.com" ]
43530438+Games28@users.noreply.github.com
49d8e124eef056adf1dc7c0454deca8446dcfaa7
04b9e5195b3069cc3c08052fc27d217fdc1b2a29
/gnc/navigator_perception/scan_the_code_detector.cc
334bcf0213aa583c48aee2377e16bd9331052fbc
[]
no_license
forrestv/Navigator
c6e68c90054a62a2eee4e87e1dd39f3d51165ff4
0a1467204f735320fb4390606e20bd5c5480bb68
refs/heads/master
2021-01-17T21:39:22.401426
2016-09-01T02:25:45
2016-09-01T02:25:45
68,004,079
0
0
null
2016-09-12T11:43:14
2016-09-12T11:43:14
null
UTF-8
C++
false
false
12,211
cc
#include <navigator_vision_lib/scan_the_code_detector.hpp> using namespace std; using namespace cv; /////////////////////////////////////////////////////////////////////////////////////////////////// // Class: ScanTheCodeDetector //////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// ScanTheCodeDetector::ScanTheCodeDetector() try : image_transport(nh), rviz("/scan_the_code/visualization/detection") { stringstream log_msg; init_ros(log_msg); log_msg << "\nInitializing ScanTheCodeDetector:\n"; int tab_sz = 4; PerceptionModel model = PerceptionModel(model_width, model_height); model_fitter = new StereoModelFitter(model, debug_image_pub); // Start main detector loop run_id = 0; boost::thread main_loop_thread(boost::bind(&ScanTheCodeDetector::run, this)); main_loop_thread.detach(); log_msg << setw(1 * tab_sz) << "" << "Running main detector loop in a background thread\n"; log_msg << "ScanTheCodeDetector Initialized\n"; ROS_INFO(log_msg.str().c_str()); } catch (const exception &e) { ROS_ERROR("Exception from within ScanTheCodeDetector constructor " "initializer list: "); ROS_ERROR(e.what()); } ScanTheCodeDetector::~ScanTheCodeDetector() { ROS_INFO("Killed Torpedo Board Detector"); } void ScanTheCodeDetector::validate_frame(Mat& current_image_left, Mat& current_image_right, Mat& processing_size_image_left, Mat& processing_size_image_right ){ // Prevent segfault if service is called before we get valid img_msg_ptr's if (model_fitter->left_most_recent.image_msg_ptr == NULL || model_fitter->right_most_recent.image_msg_ptr == NULL) { ROS_WARN("Torpedo Board Detector: Image Pointers are NULL."); throw "ROS ERROR"; } double sync_thresh = 0.5; // Get the most recent frames and camera info for both cameras cv_bridge::CvImagePtr input_bridge; try { left_mtx.lock(); right_mtx.lock(); Matx34d left_cam_mat = left_cam_model.fullProjectionMatrix(); // Left Camera input_bridge = cv_bridge::toCvCopy(model_fitter->left_most_recent.image_msg_ptr, sensor_msgs::image_encodings::BGR8); current_image_left = input_bridge->image; left_cam_model.fromCameraInfo(model_fitter->left_most_recent.info_msg_ptr); resize(current_image_left, processing_size_image_left, Size(0, 0), image_proc_scale, image_proc_scale); if (current_image_left.channels() != 3) { ROS_ERROR("The left image topic does not contain a color image."); throw "ROS ERROR"; } // Right Camera input_bridge = cv_bridge::toCvCopy(model_fitter->right_most_recent.image_msg_ptr, sensor_msgs::image_encodings::BGR8); current_image_right = input_bridge->image; right_cam_model.fromCameraInfo(model_fitter->right_most_recent.info_msg_ptr); resize(current_image_right, processing_size_image_right, Size(0, 0), image_proc_scale, image_proc_scale); if (current_image_right.channels() != 3) { ROS_ERROR("The right image topic does not contain a color image."); throw "ROS ERROR"; } left_mtx.unlock(); right_mtx.unlock(); } catch (const exception &ex) { ROS_ERROR("[scan_the_code] cv_bridge: Failed to convert images"); left_mtx.unlock(); right_mtx.unlock(); throw "ROS ERROR"; } // Enforce approximate image synchronization double left_stamp, right_stamp; left_stamp = model_fitter->left_most_recent.image_msg_ptr->header.stamp.toSec(); right_stamp = model_fitter->right_most_recent.image_msg_ptr->header.stamp.toSec(); double sync_error = fabs(left_stamp - right_stamp); stringstream sync_msg; sync_msg << "Left and right images were not sufficiently synchronized" << "\nsync error: " << sync_error << "s"; if (sync_error > sync_thresh) { ROS_WARN(sync_msg.str().c_str()); throw "Sync Error"; } } void ScanTheCodeDetector::init_ros(stringstream& log_msg){ using ros::param::param; int tab_sz = 4; // Default parameters string img_topic_left_default = "/stereo/left/image_rect_color/"; string img_topic_right_default = "/stereo/right/image_rect_color/"; string activation_default = "/scan_the_code/detection_activation_switch"; string dbg_topic_default = "/scan_the_code/dbg_imgs"; string pose_est_srv_default = "/scan_the_code/pose_est_srv"; float image_proc_scale_default = 0.5; int diffusion_time_default = 20; int max_features_default = 20; int feature_block_size_default = 11; float feature_min_distance_default = 15.0; bool generate_dbg_img_default = true; int frame_height_default = 644; int frame_width_default = 482; // Set image processing scale image_proc_scale = param<float>("/scan_the_code_vision/img_proc_scale", image_proc_scale_default); log_msg << setw(1 * tab_sz) << "" << "Image Processing Scale: \x1b[37m" << image_proc_scale << "\x1b[0m\n"; // Set diffusion duration in pseudotime diffusion_time = param<int>("/scan_the_code_vision/diffusion_time", diffusion_time_default); log_msg << setw(1 * tab_sz) << "" << "Anisotropic Diffusion Duration: \x1b[37m" << diffusion_time << "\x1b[0m\n"; // Set feature extraction parameters max_features = param<int>("/scan_the_code_vision/max_features", max_features_default); log_msg << setw(1 * tab_sz) << "" << "Maximum features: \x1b[37m" << max_features << "\x1b[0m\n"; feature_block_size = param<int>("/scan_the_code_vision/feature_block_size", feature_block_size_default); log_msg << setw(1 * tab_sz) << "" << "Feature Block Size: \x1b[37m" << feature_block_size << "\x1b[0m\n"; feature_min_distance = param<float>("/scan_the_code_vision/feature_min_distance", feature_min_distance_default); log_msg << setw(1 * tab_sz) << "" << "Feature Minimum Distance: \x1b[37m" << feature_min_distance << "\x1b[0m\n"; // Configure debug image generation generate_dbg_img = param<bool>("/scan_the_code_vision/generate_dbg_imgs", generate_dbg_img_default); // Subscribe to Cameras (image + camera_info) string left = param<string>("/scan_the_code_vision/input_left", img_topic_left_default); string right = param<string>("/scan_the_code_vision/input_right", img_topic_right_default); left_image_sub = image_transport.subscribeCamera( left, 10, &ScanTheCodeDetector::left_image_callback, this); right_image_sub = image_transport.subscribeCamera( right, 10, &ScanTheCodeDetector::right_image_callback, this); log_msg << setw(1 * tab_sz) << "" << "Camera Subscriptions:\x1b[37m\n" << setw(2 * tab_sz) << "" << "left = " << left << endl << setw(2 * tab_sz) << "" << "right = " << right << "\x1b[0m\n"; // Register Pose Estimation Service Client string pose_est_srv = param<string>("/scan_the_code_vision/pose_est_srv", pose_est_srv_default); pose_client = nh.serviceClient<sub8_msgs::TorpBoardPoseRequest>( pose_est_srv); log_msg << setw(1 * tab_sz) << "" << "Registered as client of the service:\n" << setw(2 * tab_sz) << "" << "\x1b[37m" << pose_est_srv << "\x1b[0m\n"; // Advertise debug image topic string dbg_topic = param<string>("/scan_the_code_vision/dbg_imgs", dbg_topic_default); debug_image_pub = image_transport.advertise(dbg_topic, 1, true); log_msg << setw(1 * tab_sz) << "" << "Advertised debug image topic:\n" << setw(2 * tab_sz) << "" << "\x1b[37m" << dbg_topic << "\x1b[0m\n"; // Setup debug image quadrants int frame_height = param<int>("/scan_the_code_vision/frame_height", frame_height_default); int frame_width = param<int>("/scan_the_code_vision/frame_width", frame_width_default); Size input_frame_size(frame_height, frame_width); // This needs to be changed if we ever change // the camera settings for frame size Size proc_size(cvRound(image_proc_scale * input_frame_size.width), cvRound(image_proc_scale * input_frame_size.height)); Size dbg_img_size(proc_size.width * 2, proc_size.height * 2); debug_image = Mat(dbg_img_size, CV_8UC3, Scalar(0, 0, 0)); upper_left = Rect(Point(0, 0), proc_size); upper_right = Rect(Point(proc_size.width, 0), proc_size); lower_left = Rect(Point(0, proc_size.height), proc_size); lower_right = Rect(Point(proc_size.width, proc_size.height), proc_size); // Advertise detection activation switch active = false; string activation = param<string>("/scan_the_code_vision/activation", activation_default); detection_switch = nh.advertiseService( activation, &ScanTheCodeDetector::detection_activation_switch, this); log_msg << setw(1 * tab_sz) << "" << "Advertised scan_the_code board detection switch:\n" << setw(2 * tab_sz) << "" << "\x1b[37m" << activation << "\x1b[0m\n"; } void ScanTheCodeDetector::run() { ros::Rate loop_rate(10); // process images 10 times per second while (ros::ok()) { if (true){ process_current_image(); } loop_rate.sleep(); } return; } void ScanTheCodeDetector::process_current_image(){ Eigen::Vector3d position; Mat current_image_left, current_image_right, processing_size_image_left, processing_size_image_right; try{ validate_frame(current_image_left, current_image_right, processing_size_image_left, processing_size_image_right); }catch(const char* msg){ return; } Matx34d left_cam_mat = this->left_cam_model.fullProjectionMatrix(); Matx34d right_cam_mat = right_cam_model.fullProjectionMatrix(); bool ret = model_fitter->determine_model_position(position, max_features, feature_block_size, feature_min_distance, image_proc_scale, diffusion_time, current_image_left, current_image_right, processing_size_image_left, processing_size_image_right, left_cam_mat, right_cam_mat); } bool ScanTheCodeDetector::detection_activation_switch( sub8_msgs::TBDetectionSwitch::Request &req, sub8_msgs::TBDetectionSwitch::Response &resp) { resp.success = false; stringstream ros_log; ros_log << "\x1b[1;31mSetting torpedo board detection to: \x1b[1;37m" << (req.detection_switch ? "on" : "off") << "\x1b[0m"; ROS_INFO(ros_log.str().c_str()); active = req.detection_switch; if (active == req.detection_switch) { resp.success = true; return true; } return false; } void ScanTheCodeDetector::left_image_callback( const sensor_msgs::ImageConstPtr &image_msg_ptr, const sensor_msgs::CameraInfoConstPtr &info_msg_ptr) { left_mtx.lock(); model_fitter->left_most_recent.image_msg_ptr = image_msg_ptr; model_fitter->left_most_recent.info_msg_ptr = info_msg_ptr; left_mtx.unlock(); } void ScanTheCodeDetector::right_image_callback( const sensor_msgs::ImageConstPtr &image_msg_ptr, const sensor_msgs::CameraInfoConstPtr &info_msg_ptr) { right_mtx.lock(); model_fitter->right_most_recent.image_msg_ptr = image_msg_ptr; model_fitter->right_most_recent.info_msg_ptr = info_msg_ptr; right_mtx.unlock(); } int main(int argc, char **argv) { ros::init(argc, argv, "scan_the_code_board_perception"); ROS_INFO("Initializing node /scan_the_code_board_perception"); ScanTheCodeDetector scan_the_code_detector; ros::spin(); }
[ "tesshbianchi@gmail.com" ]
tesshbianchi@gmail.com
3119699d2da8b32cdecf557de63b5e625f5b2020
1f63dde39fcc5f8be29f2acb947c41f1b6f1683e
/Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/audio_processing/aec3/echo_remover_metrics.cc
54d608f7fcb7117bf1509391cd60840666fcf346
[ "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webm", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
koobonil/Boss2D
09ca948823e0df5a5a53b64a10033c4f3665483a
e5eb355b57228a701495f2660f137bd05628c202
refs/heads/master
2022-10-20T09:02:51.341143
2019-07-18T02:13:44
2019-07-18T02:13:44
105,999,368
7
2
MIT
2022-10-04T23:31:12
2017-10-06T11:57:07
C++
UTF-8
C++
false
false
14,847
cc
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/aec3/echo_remover_metrics.h" #include <math.h> #include <algorithm> #include <numeric> #include BOSS_WEBRTC_U_rtc_base__numerics__safe_minmax_h //original-code:"rtc_base/numerics/safe_minmax.h" #include BOSS_WEBRTC_U_system_wrappers__include__metrics_h //original-code:"system_wrappers/include/metrics.h" namespace webrtc { namespace { constexpr float kOneByMetricsCollectionBlocks = 1.f / kMetricsCollectionBlocks; } // namespace EchoRemoverMetrics::DbMetric::DbMetric() : DbMetric(0.f, 0.f, 0.f) {} EchoRemoverMetrics::DbMetric::DbMetric(float sum_value, float floor_value, float ceil_value) : sum_value(sum_value), floor_value(floor_value), ceil_value(ceil_value) {} void EchoRemoverMetrics::DbMetric::Update(float value) { sum_value += value; floor_value = std::min(floor_value, value); ceil_value = std::max(ceil_value, value); } void EchoRemoverMetrics::DbMetric::UpdateInstant(float value) { sum_value = value; floor_value = std::min(floor_value, value); ceil_value = std::max(ceil_value, value); } EchoRemoverMetrics::EchoRemoverMetrics() { ResetMetrics(); } void EchoRemoverMetrics::ResetMetrics() { erl_.fill(DbMetric(0.f, 10000.f, 0.000f)); erl_time_domain_ = DbMetric(0.f, 10000.f, 0.000f); erle_.fill(DbMetric(0.f, 0.f, 1000.f)); erle_time_domain_ = DbMetric(0.f, 0.f, 1000.f); comfort_noise_.fill(DbMetric(0.f, 100000000.f, 0.f)); suppressor_gain_.fill(DbMetric(0.f, 1.f, 0.f)); active_render_count_ = 0; saturated_capture_ = false; } void EchoRemoverMetrics::Update( const AecState& aec_state, const std::array<float, kFftLengthBy2Plus1>& comfort_noise_spectrum, const std::array<float, kFftLengthBy2Plus1>& suppressor_gain) { metrics_reported_ = false; if (++block_counter_ <= kMetricsCollectionBlocks) { aec3::UpdateDbMetric(aec_state.Erl(), &erl_); erl_time_domain_.UpdateInstant(aec_state.ErlTimeDomain()); aec3::UpdateDbMetric(aec_state.Erle(), &erle_); erle_time_domain_.UpdateInstant(aec_state.ErleTimeDomainLog2()); aec3::UpdateDbMetric(comfort_noise_spectrum, &comfort_noise_); aec3::UpdateDbMetric(suppressor_gain, &suppressor_gain_); active_render_count_ += (aec_state.ActiveRender() ? 1 : 0); saturated_capture_ = saturated_capture_ || aec_state.SaturatedCapture(); } else { // Report the metrics over several frames in order to lower the impact of // the logarithms involved on the computational complexity. constexpr int kMetricsCollectionBlocksBy2 = kMetricsCollectionBlocks / 2; constexpr float kComfortNoiseScaling = 1.f / (kBlockSize * kBlockSize); switch (block_counter_) { case kMetricsCollectionBlocks + 1: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErleBand0.Average", aec3::TransformDbMetricForReporting(true, 0.f, 19.f, 0.f, kOneByMetricsCollectionBlocks, erle_[0].sum_value), 0, 19, 20); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErleBand0.Max", aec3::TransformDbMetricForReporting(true, 0.f, 19.f, 0.f, 1.f, erle_[0].ceil_value), 0, 19, 20); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErleBand0.Min", aec3::TransformDbMetricForReporting(true, 0.f, 19.f, 0.f, 1.f, erle_[0].floor_value), 0, 19, 20); break; case kMetricsCollectionBlocks + 2: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErleBand1.Average", aec3::TransformDbMetricForReporting(true, 0.f, 19.f, 0.f, kOneByMetricsCollectionBlocks, erle_[1].sum_value), 0, 19, 20); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErleBand1.Max", aec3::TransformDbMetricForReporting(true, 0.f, 19.f, 0.f, 1.f, erle_[1].ceil_value), 0, 19, 20); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErleBand1.Min", aec3::TransformDbMetricForReporting(true, 0.f, 19.f, 0.f, 1.f, erle_[1].floor_value), 0, 19, 20); break; case kMetricsCollectionBlocks + 3: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErlBand0.Average", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, kOneByMetricsCollectionBlocks, erl_[0].sum_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErlBand0.Max", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_[0].ceil_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErlBand0.Min", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_[0].floor_value), 0, 59, 30); break; case kMetricsCollectionBlocks + 4: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErlBand1.Average", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, kOneByMetricsCollectionBlocks, erl_[1].sum_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErlBand1.Max", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_[1].ceil_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ErlBand1.Min", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_[1].floor_value), 0, 59, 30); break; case kMetricsCollectionBlocks + 5: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ComfortNoiseBand0.Average", aec3::TransformDbMetricForReporting( true, 0.f, 89.f, -90.3f, kComfortNoiseScaling * kOneByMetricsCollectionBlocks, comfort_noise_[0].sum_value), 0, 89, 45); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ComfortNoiseBand0.Max", aec3::TransformDbMetricForReporting(true, 0.f, 89.f, -90.3f, kComfortNoiseScaling, comfort_noise_[0].ceil_value), 0, 89, 45); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ComfortNoiseBand0.Min", aec3::TransformDbMetricForReporting(true, 0.f, 89.f, -90.3f, kComfortNoiseScaling, comfort_noise_[0].floor_value), 0, 89, 45); break; case kMetricsCollectionBlocks + 6: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ComfortNoiseBand1.Average", aec3::TransformDbMetricForReporting( true, 0.f, 89.f, -90.3f, kComfortNoiseScaling * kOneByMetricsCollectionBlocks, comfort_noise_[1].sum_value), 0, 89, 45); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ComfortNoiseBand1.Max", aec3::TransformDbMetricForReporting(true, 0.f, 89.f, -90.3f, kComfortNoiseScaling, comfort_noise_[1].ceil_value), 0, 89, 45); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.ComfortNoiseBand1.Min", aec3::TransformDbMetricForReporting(true, 0.f, 89.f, -90.3f, kComfortNoiseScaling, comfort_noise_[1].floor_value), 0, 89, 45); break; case kMetricsCollectionBlocks + 7: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.SuppressorGainBand0.Average", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 0.f, kOneByMetricsCollectionBlocks, suppressor_gain_[0].sum_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.SuppressorGainBand0.Max", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 0.f, 1.f, suppressor_gain_[0].ceil_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.SuppressorGainBand0.Min", aec3::TransformDbMetricForReporting( true, 0.f, 59.f, 0.f, 1.f, suppressor_gain_[0].floor_value), 0, 59, 30); break; case kMetricsCollectionBlocks + 8: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.SuppressorGainBand1.Average", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 0.f, kOneByMetricsCollectionBlocks, suppressor_gain_[1].sum_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.SuppressorGainBand1.Max", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 0.f, 1.f, suppressor_gain_[1].ceil_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.SuppressorGainBand1.Min", aec3::TransformDbMetricForReporting( true, 0.f, 59.f, 0.f, 1.f, suppressor_gain_[1].floor_value), 0, 59, 30); break; case kMetricsCollectionBlocks + 9: RTC_HISTOGRAM_BOOLEAN( "WebRTC.Audio.EchoCanceller.UsableLinearEstimate", static_cast<int>(aec_state.UsableLinearEstimate() ? 1 : 0)); RTC_HISTOGRAM_BOOLEAN( "WebRTC.Audio.EchoCanceller.ActiveRender", static_cast<int>( active_render_count_ > kMetricsCollectionBlocksBy2 ? 1 : 0)); RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.Audio.EchoCanceller.FilterDelay", aec_state.FilterDelayBlocks(), 0, 30, 31); RTC_HISTOGRAM_BOOLEAN("WebRTC.Audio.EchoCanceller.CaptureSaturation", static_cast<int>(saturated_capture_ ? 1 : 0)); break; case kMetricsCollectionBlocks + 10: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.Erl.Value", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_time_domain_.sum_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.Erl.Max", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_time_domain_.ceil_value), 0, 59, 30); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.Erl.Min", aec3::TransformDbMetricForReporting(true, 0.f, 59.f, 30.f, 1.f, erl_time_domain_.floor_value), 0, 59, 30); break; case kMetricsCollectionBlocks + 11: RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.Erle.Value", aec3::TransformDbMetricForReporting(false, 0.f, 19.f, 0.f, 1.f, erle_time_domain_.sum_value), 0, 19, 20); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.Erle.Max", aec3::TransformDbMetricForReporting(false, 0.f, 19.f, 0.f, 1.f, erle_time_domain_.ceil_value), 0, 19, 20); RTC_HISTOGRAM_COUNTS_LINEAR( "WebRTC.Audio.EchoCanceller.Erle.Min", aec3::TransformDbMetricForReporting(false, 0.f, 19.f, 0.f, 1.f, erle_time_domain_.floor_value), 0, 19, 20); metrics_reported_ = true; RTC_DCHECK_EQ(kMetricsReportingIntervalBlocks, block_counter_); block_counter_ = 0; ResetMetrics(); break; default: RTC_NOTREACHED(); break; } } } namespace aec3 { void UpdateDbMetric(const std::array<float, kFftLengthBy2Plus1>& value, std::array<EchoRemoverMetrics::DbMetric, 2>* statistic) { RTC_DCHECK(statistic); // Truncation is intended in the band width computation. constexpr int kNumBands = 2; constexpr int kBandWidth = 65 / kNumBands; constexpr float kOneByBandWidth = 1.f / kBandWidth; RTC_DCHECK_EQ(kNumBands, statistic->size()); RTC_DCHECK_EQ(65, value.size()); for (size_t k = 0; k < statistic->size(); ++k) { float average_band = std::accumulate(value.begin() + kBandWidth * k, value.begin() + kBandWidth * (k + 1), 0.f) * kOneByBandWidth; (*statistic)[k].Update(average_band); } } int TransformDbMetricForReporting(bool negate, float min_value, float max_value, float offset, float scaling, float value) { float new_value = 10.f * log10(value * scaling + 1e-10f) + offset; if (negate) { new_value = -new_value; } return static_cast<int>(rtc::SafeClamp(new_value, min_value, max_value)); } } // namespace aec3 } // namespace webrtc
[ "slacealic@nate.com" ]
slacealic@nate.com
f1016dc0def2b3a8417cb79cadf150bfca861d83
9bdc01fddc660053e23eaf89302f9b8e5daaefdf
/src/planner/cspace/cspace_geometric_SO2RN.h
151b4c55a8150a9b7afe0ec1924c34ce2c8fea10
[]
no_license
hello-starry/MotionExplorer
51d4ca1a1325567968ac2119de7c96b0345e5b10
01472004a1bc1272ce32a433fe6bde81eb962775
refs/heads/master
2023-08-14T21:20:22.073477
2021-09-07T17:51:20
2021-09-07T17:51:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
483
h
#include "planner/cspace/cspace_geometric.h" class GeometricCSpaceOMPLSO2RN: public GeometricCSpaceOMPL { public: GeometricCSpaceOMPLSO2RN(RobotWorld *world_, int robot_idx); virtual void initSpace(); virtual void ConfigToOMPLState(const Config &q, ob::State *qompl) override; virtual Config OMPLStateToConfig(const ob::State *qompl) override; virtual void print(std::ostream& out = std::cout) const; virtual Vector3 getXYZ(const ob::State*) override; };
[ "andreas.orthey@gmx.de" ]
andreas.orthey@gmx.de
0f166947f51e98a385384e10143adcc23485ddbe
85b9ce4fb88972d9b86dce594ae4fb3acfcd0a4b
/build/Android/Preview/Global Pot/app/src/main/include/Fuse.Drawing.Batching.BatchVertexBuffer.h
02e092de20711965307a569c95fc802e98b9354b
[]
no_license
bgirr/Global-Pot_App
16431a99e26f1c60dc16223fb388d9fd525cb5fa
c96c5a8fb95acde66fc286bcd9a5cdf160ba8b1b
refs/heads/master
2021-01-09T06:29:18.255583
2017-02-21T23:27:47
2017-02-21T23:27:47
80,985,681
0
0
null
2017-02-21T23:27:48
2017-02-05T10:29:14
C++
UTF-8
C++
false
false
5,596
h
// This file was generated based on C:\Users\EliteBook-User\AppData\Local\Fusetools\Packages\Fuse.Drawing.Batching\0.44.1\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Drawing{namespace Batching{struct BatchVertexBuffer;}}}} namespace g{namespace Uno{namespace Graphics{struct VertexBuffer;}}} namespace g{namespace Uno{struct Buffer;}} namespace g{namespace Uno{struct Byte2;}} namespace g{namespace Uno{struct Byte4;}} namespace g{namespace Uno{struct Float2;}} namespace g{namespace Uno{struct Float3;}} namespace g{namespace Uno{struct Float4;}} namespace g{namespace Uno{struct Int2;}} namespace g{namespace Uno{struct Int3;}} namespace g{namespace Uno{struct Int4;}} namespace g{namespace Uno{struct SByte2;}} namespace g{namespace Uno{struct SByte4;}} namespace g{namespace Uno{struct Short2;}} namespace g{namespace Uno{struct Short4;}} namespace g{namespace Uno{struct UShort2;}} namespace g{namespace Uno{struct UShort4;}} namespace g{ namespace Fuse{ namespace Drawing{ namespace Batching{ // public sealed class BatchVertexBuffer :351 // { uType* BatchVertexBuffer_typeof(); void BatchVertexBuffer__ctor__fn(BatchVertexBuffer* __this, int* type, int* maxVertices1, bool* staticBatch); void BatchVertexBuffer__ctor_1_fn(BatchVertexBuffer* __this, int* type, ::g::Uno::Buffer* data); void BatchVertexBuffer__get_Buffer_fn(BatchVertexBuffer* __this, ::g::Uno::Buffer** __retval); void BatchVertexBuffer__get_DataType_fn(BatchVertexBuffer* __this, int* __retval); void BatchVertexBuffer__set_DataType_fn(BatchVertexBuffer* __this, int* value); void BatchVertexBuffer__Flush_fn(BatchVertexBuffer* __this); void BatchVertexBuffer__Invalidate_fn(BatchVertexBuffer* __this); void BatchVertexBuffer__New1_fn(int* type, int* maxVertices1, bool* staticBatch, BatchVertexBuffer** __retval); void BatchVertexBuffer__New2_fn(int* type, ::g::Uno::Buffer* data, BatchVertexBuffer** __retval); void BatchVertexBuffer__get_Position_fn(BatchVertexBuffer* __this, int* __retval); void BatchVertexBuffer__set_Position_fn(BatchVertexBuffer* __this, int* value); void BatchVertexBuffer__get_StrideInBytes_fn(BatchVertexBuffer* __this, int* __retval); void BatchVertexBuffer__get_VertexBuffer_fn(BatchVertexBuffer* __this, ::g::Uno::Graphics::VertexBuffer** __retval); void BatchVertexBuffer__Write_fn(BatchVertexBuffer* __this, uint8_t* value); void BatchVertexBuffer__Write1_fn(BatchVertexBuffer* __this, ::g::Uno::Byte2* value); void BatchVertexBuffer__Write2_fn(BatchVertexBuffer* __this, ::g::Uno::Byte4* value); void BatchVertexBuffer__Write3_fn(BatchVertexBuffer* __this, ::g::Uno::Float2* value); void BatchVertexBuffer__Write4_fn(BatchVertexBuffer* __this, ::g::Uno::Float3* value); void BatchVertexBuffer__Write5_fn(BatchVertexBuffer* __this, ::g::Uno::Float4* value); void BatchVertexBuffer__Write6_fn(BatchVertexBuffer* __this, int* value); void BatchVertexBuffer__Write7_fn(BatchVertexBuffer* __this, ::g::Uno::Int2* value); void BatchVertexBuffer__Write8_fn(BatchVertexBuffer* __this, ::g::Uno::Int3* value); void BatchVertexBuffer__Write9_fn(BatchVertexBuffer* __this, ::g::Uno::Int4* value); void BatchVertexBuffer__Write10_fn(BatchVertexBuffer* __this, int8_t* value); void BatchVertexBuffer__Write11_fn(BatchVertexBuffer* __this, ::g::Uno::SByte2* value); void BatchVertexBuffer__Write12_fn(BatchVertexBuffer* __this, ::g::Uno::SByte4* value); void BatchVertexBuffer__Write13_fn(BatchVertexBuffer* __this, int16_t* value); void BatchVertexBuffer__Write14_fn(BatchVertexBuffer* __this, ::g::Uno::Short2* value); void BatchVertexBuffer__Write15_fn(BatchVertexBuffer* __this, ::g::Uno::Short4* value); void BatchVertexBuffer__Write16_fn(BatchVertexBuffer* __this, uint32_t* value); void BatchVertexBuffer__Write17_fn(BatchVertexBuffer* __this, uint16_t* value); void BatchVertexBuffer__Write18_fn(BatchVertexBuffer* __this, ::g::Uno::UShort2* value); void BatchVertexBuffer__Write19_fn(BatchVertexBuffer* __this, ::g::Uno::UShort4* value); struct BatchVertexBuffer : uObject { int _position; uStrong< ::g::Uno::Buffer*> buf; int dataType; bool isDirty; int maxVertices; int usage; uStrong< ::g::Uno::Graphics::VertexBuffer*> vbo; void ctor_(int type, int maxVertices1, bool staticBatch); void ctor_1(int type, ::g::Uno::Buffer* data); ::g::Uno::Buffer* Buffer(); int DataType(); void DataType(int value); void Flush(); void Invalidate(); int Position(); void Position(int value); int StrideInBytes(); ::g::Uno::Graphics::VertexBuffer* VertexBuffer(); void Write(uint8_t value); void Write1(::g::Uno::Byte2 value); void Write2(::g::Uno::Byte4 value); void Write3(::g::Uno::Float2 value); void Write4(::g::Uno::Float3 value); void Write5(::g::Uno::Float4 value); void Write6(int value); void Write7(::g::Uno::Int2 value); void Write8(::g::Uno::Int3 value); void Write9(::g::Uno::Int4 value); void Write10(int8_t value); void Write11(::g::Uno::SByte2 value); void Write12(::g::Uno::SByte4 value); void Write13(int16_t value); void Write14(::g::Uno::Short2 value); void Write15(::g::Uno::Short4 value); void Write16(uint32_t value); void Write17(uint16_t value); void Write18(::g::Uno::UShort2 value); void Write19(::g::Uno::UShort4 value); static BatchVertexBuffer* New1(int type, int maxVertices1, bool staticBatch); static BatchVertexBuffer* New2(int type, ::g::Uno::Buffer* data); }; // } }}}} // ::g::Fuse::Drawing::Batching
[ "girr.benjamin@gmail.com" ]
girr.benjamin@gmail.com
c4b9e92bd69ee66c8cef7f618f0a3f40e6f4e800
4af4bc8e656e4a1e7719f97eff475b46b413b560
/Stack/Valid_Parentheses_n2Recurs.cpp
92a6194e2dc028278297dd0558a3408e558f311d
[]
no_license
ksaetern/AlgosDataStrcLeetCode
588bd0d55ee0f272a31a88489a7f8dc2bc72eb06
bea691603e84354127bb2efc954f097788cd8009
refs/heads/master
2020-05-25T20:20:52.433301
2019-06-08T03:16:36
2019-06-08T03:16:36
187,973,909
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
class Solution { public: bool isValid(string s) { //O(n2) recursive solution if(s.size() == 0) return true; //if "()" doesnt = string end pos if(s.find("()") != string::npos){ int index = s.find("()"); s.replace(index, 2, ""); return isValid(s); } else if(s.find("{}") != string::npos){ int index = s.find("{}"); s.replace(index, 2, ""); return isValid(s); } else if(s.find("[]") != string::npos){ int index = s.find("[]"); s.replace(index, 2, ""); return isValid(s); } else return false; } };
[ "ksaetern@e1z2r1p7.42.us.org" ]
ksaetern@e1z2r1p7.42.us.org
d0c988c4ed19cd85b54e8e6028f83fb0db29a536
407d144edf2882bd3edd2abcf32ce48a99ee2f6b
/CC3/include/DoubleHash.h
95fb3c93210deb5265bb38e7a22ec07a6162893c
[]
no_license
Fangcong-Yin/CSE-20312-DataStructures-Projects
3a9f72fe52a56675e65b2de817b15e2babfadfce
4f32f91a18bf92daf1b3a608ef970625d5ebf859
refs/heads/master
2022-12-25T02:36:51.580724
2020-10-04T20:42:25
2020-10-04T20:42:25
286,543,143
0
0
null
null
null
null
UTF-8
C++
false
false
2,746
h
//Author: Fangcong Yin //Email: fyin2@nd.edu //CC3: Double Hash Class #include "LinearProbe.h" #ifndef DOUBLEHASH #define DOUBLEHASH template<class Key, class Value> class DoubleHash: public HashTable<Key, Value> { private: //This is the HashFunction2(v) = 3-v%3 for integers long unsigned int HashFunc2( const int& keyToTranslate ) const{ long unsigned int v; if (keyToTranslate < 0){ v = (long unsigned int)(-1 * keyToTranslate); } else{ v = (long unsigned int) keyToTranslate; } return (3-(v%3)); } //This is the HashFunction2(v) = 3-v%3 for strings long unsigned int HashFunc2( const std::string& keyToTranslate ) const{ return (3-(keyToTranslate.size()%3)); } //The overridden findPos function long unsigned int findPos( const Key& theKey ) const{ long unsigned int currentPos; //iter starts from 1 instead of 0 long unsigned int iter = 1; do{ //this->HashFunc represents Hash1(v) =v currentPos = (this->HashFunc( theKey ) + iter*HashFunc2( theKey )) % ((this -> array).capacity()); ++iter; } while( (this -> array).at( currentPos ).state != EMPTY && (this -> array).at( currentPos ).state != DELETED && (this -> array).at( currentPos ).key != theKey && iter < (this -> array).capacity() ); // Return capacity if the current value isn't the key. For safety if((this -> array).at( currentPos ).state == ACTIVE && (this -> array).at( currentPos ).key != theKey ){ return (this -> array).capacity(); } return currentPos; } public: //The Double Hash constructor uses the constructor from HashTable class DoubleHash(const unsigned int size = 0) : HashTable<Key,Value>(size) { } //Destructor virtual ~DoubleHash(){} //Overriden ostream operator friend std::ostream& operator<<( std::ostream& output, const DoubleHash<Key, Value>& theTable ){ output << "Double Hash Results: " << std::endl; output << "Double Hash Table Size: " << theTable.array.size() << std::endl; output << "Hashed Elements: " << theTable.numHash << std::endl; for(unsigned int iter = 0; iter < theTable.array.size(); iter++){ output << "{" << iter << ": "; if( theTable.array[iter].state == ACTIVE ){ output << "ACTIVE, "; } else if( theTable.array[iter].state == DELETED ){ output << "DELETED, "; } else{ output << "EMPTY, "; } output << theTable.array[iter].key << ", "; output << theTable.array[iter].value << "}" << std::endl; } return output; } }; #endif
[ "fyin2@student00.cse.nd.edu" ]
fyin2@student00.cse.nd.edu
4ae596f8d74aa4ea4545692ceb3539874377cbcb
a66f43ebb6bebfe509f8aaeff3989c6153668de8
/LIGHTOJ/1238 - Power Puff Girls.cpp
b9534dd175c969a46ce40c0ee09abe4bd2ad8ecd
[]
no_license
ShikariSohan/Problems-Solving
e6cbeaaa9a8a091364aee12cc28cce06165cf84d
26809bddfcb357ca232be5e8016ef1e705a94f9a
refs/heads/master
2023-02-24T08:05:27.161840
2021-01-26T12:44:55
2021-01-26T12:44:55
283,302,951
2
0
null
null
null
null
UTF-8
C++
false
false
3,095
cpp
/* """Bismillahir Rahmanur Rahim""" */ #include<bits/stdc++.h> using namespace std; #define pi 2*acos(0.0) #define ll long long int #define pb push_back #define pf push_front const ll sz = 1000001; #define mp make_pair #define ses '\n' #define stm istringstream #define gcd __gcd ll lcm(ll x,ll y){return (x*y)/gcd(x,y);} #define tin ll T;cin>>T; for(ll o=1;o<=T;o++) #define tout cout<<"Case "<<o<<": "; ll dr[]={-1,0,1,0}; ll dc[]={0,1,0,-1}; ll valid(ll r,ll c,ll x,ll y) { if(r>=0 && r<x && c>=0 && c<y) return 1; else return 0; } ll ar[20][20]; int bfs(ll a,ll b,ll x,ll y) { ll dis[x][y]={},vis[x][y]={}; queue<pair<ll,ll> >q; q.push({a,b}); vis[a][b]=1; dis[a][b]=0; while(!q.empty()) { ll p,k; p=q.front().first; k=q.front().second; q.pop(); if(ar[p][k]==3) return dis[p][k]; for(int i=0;i<4;i++) { ll r=p+dr[i]; ll c=k+dc[i]; if(valid(r,c,x,y)) { if(vis[r][c]==0) { if(ar[r][c]==1 || ar[r][c]==3) { vis[r][c]=1; dis[r][c]=dis[p][k]+1; q.push({r,c}); } } } } } } int main() { // freopen ("input.txt","r",stdin); //freopen ("output.txt","w",stdout); tin { ll x,y,a,b,p1,p2,q1,q2,r1,r2; cin>>x>>y; char c; for(int i=0;i<x;i++) for(int j=0;j<y;j++) { cin>>c; if(c=='.') ar[i][j]=1; if(c=='#' || c=='m') ar[i][j]=2; if(c=='h') { ar[i][j]=3; a=i; b=j; } if(c=='a') { ar[i][j]=1; p1=i; p2=j; } if(c=='b') { ar[i][j]=1; q1=i; q2=j; } if(c=='c') { ar[i][j]=1; r1=i; r2=j; } } ll z=bfs(p1,p2,x,y); ll z1=bfs(q1,q2,x,y); ll z2=bfs(r1,r2,x,y); tout; cout<<max(z,max(z1,z2))<<ses; } return 0; } /* -------------------- | ~SOHAN~ | | ~Chandler68~ | -------------------- || VALAR MORGULIS||==|| ALL MEN MUST DIE || \\ Power Is Power// || I Can Do This All day || // We are on a Break \\ // How you doin'? \\ || Say My Name || ~~ || I Am The Who Knocks || // I Am Ted Mosby Architect \\ || It Is Legen --wait for it -- dary ,Legendary || \\ Penny - Penny - Penny // -- Bazinga */
[ "moksedur.rahman.sohan@gmail.com" ]
moksedur.rahman.sohan@gmail.com
ff899705c5fd9335de4b79c94d85e2058a853751
5442bd245de4bab02d88e669e8e35cb5de8338d8
/Assignment3/prog3_ComparisionComplex.cpp
15fbacedf10d3b0c960d74725343fc892d8c6b5a
[]
no_license
isha-singhal/OopsAssignment
cec4813582a34a3e06e2f77a0bd61e71a02663cd
01ee1c8e350dc9914b233fc9b676174eedc5e646
refs/heads/master
2023-01-07T12:35:05.980575
2020-11-09T14:50:58
2020-11-09T14:50:58
286,243,735
0
0
null
null
null
null
UTF-8
C++
false
false
973
cpp
#include<iostream> using namespace std; class Complex { public: Complex(int r=0 ,int i =0) { real = r; img = i; } void print() { cout<<real<<" +i"<<img<<"\n"; } Complex operator == (Complex const &obj) { if(real == obj.real) { if(img == obj.img) { cout<<"They are equal \n"; } } } Complex operator != (Complex const &obj) { if(real != obj.real) { if(img != obj.img) { cout<<"They are not equal \n"; } } } private: int real ,img ; }; int main() { Complex c1(5,5), c2(5,5); cout<<"The complex 1 is: "; c1.print(); cout<<"The complex 2 is: "; c2.print(); c1 == c2; Complex c3(10,15), c4(6,8); cout<<"The complex 3 is: "; c3.print(); cout<<"The complex 4 is: "; c4.print(); c3 != c4; return 0; }
[ "isinghal40@gmail.com" ]
isinghal40@gmail.com
074f214ba325cc87fbce779beb76da7bc1204f0c
19f6b6ae0b4ff04269c4c3067238a8094d4db992
/hoops/hoops_limits.cxx
c65b2548506bf90b5860081382e7defdcbe3ab6f
[]
no_license
Areustle/heacore
20fc58b1c9be75aa2e3ad0c72facdac9b1d5a598
4e7be354bdef2f84c37a6b49f60bad9e2827bcc5
refs/heads/master
2021-01-14T08:47:31.145648
2017-02-21T16:45:42
2017-02-21T16:45:42
81,976,859
1
0
null
null
null
null
UTF-8
C++
false
false
18,899
cxx
/****************************************************************************** * File name: * * * * Description: * * * * Language: C++ * * * * Author: James Peachey, for HEASARC/GSFC/NASA * * * * Change log: see CVS Change log at the end of the file. * ******************************************************************************/ //////////////////////////////////////////////////////////////////////////////// // Header files. //////////////////////////////////////////////////////////////////////////////// #include "hoops/hoops_limits.h" #include "hoops/hoops_numeric_limits.h" //////////////////////////////////////////////////////////////////////////////// namespace hoops { #ifdef HAVE_LIMITS using std::numeric_limits; #endif ////////////////////////////////////////////////////////////////////////////// // Constants. ////////////////////////////////////////////////////////////////////////////// // Lim<T>::code static initializations. ////////////////////////////////////////////////////////////////////////////// template <> PrimTypeCode_e Lim<bool>::code = P_BOOL; template <> PrimTypeCode_e Lim<char>::code = P_CHAR; template <> PrimTypeCode_e Lim<signed char>::code = P_SCHAR; template <> PrimTypeCode_e Lim<short>::code = P_SHORT; template <> PrimTypeCode_e Lim<int>::code = P_INT; template <> PrimTypeCode_e Lim<long>::code = P_LONG; template <> PrimTypeCode_e Lim<unsigned char>::code = P_UCHAR; template <> PrimTypeCode_e Lim<unsigned short>::code = P_USHORT; template <> PrimTypeCode_e Lim<unsigned int>::code = P_UINT; template <> PrimTypeCode_e Lim<unsigned long>::code = P_ULONG; template <> PrimTypeCode_e Lim<float>::code = P_FLOAT; template <> PrimTypeCode_e Lim<double>::code = P_DOUBLE; template <> PrimTypeCode_e Lim<long double>::code = P_LONGDOUBLE; ////////////////////////////////////////////////////////////////////////////// #ifdef OLD_LIMITS_IMPLEMENTATION // Lim<T>::digits10 static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const int Lim<bool>::digits10 = numeric_limits<bool>::digits10; template <> const int Lim<char>::digits10 = numeric_limits<char>::digits10; template <> const int Lim<signed char>::digits10 = numeric_limits<signed char>::digits10; template <> const int Lim<short>::digits10 = numeric_limits<short>::digits10; template <> const int Lim<int>::digits10 = numeric_limits<int>::digits10; template <> const int Lim<long>::digits10 = numeric_limits<long>::digits10; template <> const int Lim<unsigned char>::digits10 = numeric_limits<unsigned char>::digits10; template <> const int Lim<unsigned short>::digits10 = numeric_limits<unsigned short>::digits10; template <> const int Lim<unsigned int>::digits10 = numeric_limits<unsigned int>::digits10; template <> const int Lim<unsigned long>::digits10 = numeric_limits<unsigned long>::digits10; template <> const int Lim<float>::digits10 = numeric_limits<float>::digits10; template <> const int Lim<double>::digits10 = numeric_limits<double>::digits10; // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const int Lim<long double>::digits10 = numeric_limits<double>::digits10; ////////////////////////////////////////////////////////////////////////////// // Lim<T>::epsilon static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const bool Lim<bool>::epsilon = numeric_limits<bool>::epsilon(); template <> const char Lim<char>::epsilon = numeric_limits<char>::epsilon(); template <> const signed char Lim<signed char>::epsilon = numeric_limits<signed char>::epsilon(); template <> const short Lim<short>::epsilon = numeric_limits<short>::epsilon(); template <> const int Lim<int>::epsilon = numeric_limits<int>::epsilon(); template <> const long Lim<long>::epsilon = numeric_limits<long>::epsilon(); template <> const unsigned char Lim<unsigned char>::epsilon = numeric_limits<unsigned char>::epsilon(); template <> const unsigned short Lim<unsigned short>::epsilon = numeric_limits<unsigned short>::epsilon(); template <> const unsigned int Lim<unsigned int>::epsilon = numeric_limits<unsigned int>::epsilon(); template <> const unsigned long Lim<unsigned long>::epsilon = numeric_limits<unsigned long>::epsilon(); template <> const float Lim<float>::epsilon = numeric_limits<float>::epsilon(); template <> const double Lim<double>::epsilon = numeric_limits<double>::epsilon(); // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const long double Lim<long double>::epsilon = numeric_limits<double>::epsilon(); ////////////////////////////////////////////////////////////////////////////// // Lim<T>::is_integer static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const bool Lim<bool>::is_integer = numeric_limits<bool>::is_integer; template <> const bool Lim<char>::is_integer = numeric_limits<char>::is_integer; template <> const bool Lim<signed char>::is_integer = numeric_limits<signed char>::is_integer; template <> const bool Lim<short>::is_integer = numeric_limits<short>::is_integer; template <> const bool Lim<int>::is_integer = numeric_limits<int>::is_integer; template <> const bool Lim<long>::is_integer = numeric_limits<long>::is_integer; template <> const bool Lim<unsigned char>::is_integer = numeric_limits<unsigned char>::is_integer; template <> const bool Lim<unsigned short>::is_integer = numeric_limits<unsigned short>::is_integer; template <> const bool Lim<unsigned int>::is_integer = numeric_limits<unsigned int>::is_integer; template <> const bool Lim<unsigned long>::is_integer = numeric_limits<unsigned long>::is_integer; template <> const bool Lim<float>::is_integer = numeric_limits<float>::is_integer; template <> const bool Lim<double>::is_integer = numeric_limits<double>::is_integer; // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const bool Lim<long double>::is_integer = numeric_limits<double>::is_integer; ////////////////////////////////////////////////////////////////////////////// // Lim<T>::is_signed static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const bool Lim<bool>::is_signed = numeric_limits<bool>::is_signed; template <> const bool Lim<char>::is_signed = numeric_limits<char>::is_signed; template <> const bool Lim<signed char>::is_signed = numeric_limits<signed char>::is_signed; template <> const bool Lim<short>::is_signed = numeric_limits<short>::is_signed; template <> const bool Lim<int>::is_signed = numeric_limits<int>::is_signed; template <> const bool Lim<long>::is_signed = numeric_limits<long>::is_signed; template <> const bool Lim<unsigned char>::is_signed = numeric_limits<unsigned char>::is_signed; template <> const bool Lim<unsigned short>::is_signed = numeric_limits<unsigned short>::is_signed; template <> const bool Lim<unsigned int>::is_signed = numeric_limits<unsigned int>::is_signed; template <> const bool Lim<unsigned long>::is_signed = numeric_limits<unsigned long>::is_signed; template <> const bool Lim<float>::is_signed = numeric_limits<float>::is_signed; template <> const bool Lim<double>::is_signed = numeric_limits<double>::is_signed; // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const bool Lim<long double>::is_signed = numeric_limits<double>::is_signed; ////////////////////////////////////////////////////////////////////////////// // Lim<T>::round_error static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const bool Lim<bool>::round_error = numeric_limits<bool>::round_error(); template <> const char Lim<char>::round_error = numeric_limits<char>::round_error(); template <> const signed char Lim<signed char>::round_error = numeric_limits<signed char>::round_error(); template <> const short Lim<short>::round_error = numeric_limits<short>::round_error(); template <> const int Lim<int>::round_error = numeric_limits<int>::round_error(); template <> const long Lim<long>::round_error = numeric_limits<long>::round_error(); template <> const unsigned char Lim<unsigned char>::round_error = numeric_limits<unsigned char>::round_error(); template <> const unsigned short Lim<unsigned short>::round_error = numeric_limits<unsigned short>::round_error(); template <> const unsigned int Lim<unsigned int>::round_error = numeric_limits<unsigned int>::round_error(); template <> const unsigned long Lim<unsigned long>::round_error = numeric_limits<unsigned long>::round_error(); template <> const float Lim<float>::round_error = numeric_limits<float>::round_error(); template <> const double Lim<double>::round_error = numeric_limits<double>::round_error(); // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const long double Lim<long double>::round_error = numeric_limits<double>::round_error(); ////////////////////////////////////////////////////////////////////////////// // Lim<T>::max static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const bool Lim<bool>::max = numeric_limits<bool>::max(); template <> const char Lim<char>::max = numeric_limits<char>::max(); template <> const signed char Lim<signed char>::max = numeric_limits<signed char>::max(); template <> const short Lim<short>::max = numeric_limits<short>::max(); template <> const int Lim<int>::max = numeric_limits<int>::max(); template <> const long Lim<long>::max = numeric_limits<long>::max(); template <> const unsigned char Lim<unsigned char>::max = numeric_limits<unsigned char>::max(); template <> const unsigned short Lim<unsigned short>::max = numeric_limits<unsigned short>::max(); template <> const unsigned int Lim<unsigned int>::max = numeric_limits<unsigned int>::max(); template <> const unsigned long Lim<unsigned long>::max = numeric_limits<unsigned long>::max(); template <> const float Lim<float>::max = numeric_limits<float>::max(); template <> const double Lim<double>::max = numeric_limits<double>::max(); // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const long double Lim<long double>::max = numeric_limits<double>::max(); ////////////////////////////////////////////////////////////////////////////// // Lim<T>::min static initializations. ////////////////////////////////////////////////////////////////////////////// template <> const bool Lim<bool>::min = numeric_limits<bool>::min(); template <> const char Lim<char>::min = numeric_limits<char>::min(); template <> const signed char Lim<signed char>::min = numeric_limits<signed char>::min(); template <> const short Lim<short>::min = numeric_limits<short>::min(); template <> const int Lim<int>::min = numeric_limits<int>::min(); template <> const long Lim<long>::min = numeric_limits<long>::min(); template <> const unsigned char Lim<unsigned char>::min = numeric_limits<unsigned char>::min(); template <> const unsigned short Lim<unsigned short>::min = numeric_limits<unsigned short>::min(); template <> const unsigned int Lim<unsigned int>::min = numeric_limits<unsigned int>::min(); template <> const unsigned long Lim<unsigned long>::min = numeric_limits<unsigned long>::min(); // Note: for all floating points, min is -max, _not_ min in the // sense of numeric_limits::min(). template <> const float Lim<float>::min = -numeric_limits<float>::max(); template <> const double Lim<double>::min = -numeric_limits<double>::max(); // On *expletive* Solaris, numeric_limits<long double> causes the // compiler to exit with assertion failures. template <> const long double Lim<long double>::min = -numeric_limits<double>::max(); ////////////////////////////////////////////////////////////////////////////// // Support of all the above for long long. ////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_LONGLONG // Utility to determine maximum value for type long long. // On Solaris, numeric_limits does not contain meaningful // specializations for long long, so the maximum value is // computed. static long long LongLongMax() { long long max = numeric_limits<long long>::max(); if (0 == max) { long long bitmax = 1; // Find highest positive power of 2. while (0 < bitmax << 1) bitmax <<= 1; // Fill lower bits, always testing for overflow. while (0 < bitmax) { if (0 < max | bitmax) max |= bitmax; bitmax >>= 1; } } return max; } // Utility to determine minimum value for type long long. // On Solaris, numeric_limits does not contain meaningful // specializations for long long, so the minimum value is // computed using LongLongMax, and then taking the 2s complement. static long long LongLongMin() { static long long min = 0; if (0 == min) { min = numeric_limits<long long>::min(); if (0 == min) { // Assume 2s complement min = LongLongMax() + 1; } } return min; } // the following #endif is for HAVE_LONGLONG #endif // the following #endif is for OLD_LIMITS_IMPLEMENTATION #endif #ifdef HAVE_LONGLONG // Specializations of all static members of Lim for type long long. template <> PrimTypeCode_e Lim<long long>::code = P_LONGLONG; #ifdef OLD_LIMITS_IMPLEMENTATION template <> const long long Lim<long long>::epsilon = numeric_limits<long long>::epsilon(); template <> const bool Lim<long long>::is_signed = numeric_limits<long>::is_signed; template <> const bool Lim<long long>::is_integer = numeric_limits<long>::is_integer; template <> const long long Lim<long long>::max = LongLongMax(); template <> const long long Lim<long long>::min = LongLongMin(); #endif #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Static function declarations. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Type definitions. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Global variable definitions. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Static variable definitions. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Static function definitions. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Function definitions. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// } /****************************************************************************** * $Log: hoops_limits.cxx,v $ * Revision 1.4 2004/06/24 20:26:39 peachey * Correct a violation of ISO standard; static const int/enum types * must be initialized where they are declared. The Lim class's "code" * static member variable was therefore changed to be non-const. To * protect its value, it was made private and an accessor, GetCode() * was added. * * In addition, all Lim's other const static members which shadow * numeric_limits members were removed, and instead Lim derives * directly from std::numeric_limits (or hoops::numeric_limits if * std::numeric_limits is not available.) * * Revision 1.3 2003/12/02 14:39:44 peachey * To support compilers which do not have limits, such as g++ 2.95.x, * add round_error field to Lim class. This allows the test code to * be compiled without the limits header. * * Revision 1.2 2003/11/10 18:16:12 peachey * Moved header files into hoops subdirectory. * * Revision 1.1 2003/06/18 18:06:36 peachey * New source file to hold static initializers for Lim class support. * * Revision 1.4 2003/05/15 04:02:16 peachey * Use standard <limits> header only if HAVE_LIMITS is defined. Otherwise, * use hoops_limits.h. * * Revision 1.3 2003/05/14 15:28:00 peachey * Add strcasecmp for Windows. * * Revision 1.2 2003/05/14 15:17:06 peachey * Further encapsulate Prim class by hiding the templates in hoops_prim.cxx * and using a factory class. * * Revision 1.1 2003/04/11 19:20:38 peachey * New component HOOPS, an object oriented parameter interface. Low * level access currently uses PIL, but this can be changed. * ******************************************************************************/
[ "areustledev@gmail.com" ]
areustledev@gmail.com
37b3b6837ebfa91ee629c2fe30f435a291f28c97
348ef5a9fa75c629f2ae1bea2a48bd3eb5696eb0
/DPCDemo/ModelLoader.h
4bed7a4f149ae92ea5826bc2434ca00654b9e9ad
[]
no_license
GuMiner/DPC-experiments
3346174c7c1643bb4063bd82f969f19f07d3fa2a
2cdf05df6373bff9daa35401b4b01b005cd6b4f2
refs/heads/main
2023-02-27T06:03:57.456902
2021-02-03T06:53:45
2021-02-03T06:53:45
326,547,251
1
1
null
null
null
null
UTF-8
C++
false
false
139
h
#pragma once #include <string> #include "FanMesh.h" class ModelLoader { public: bool Load(std::string path, FanMesh* const fanMesh); };
[ "gus.gran@gmail.com" ]
gus.gran@gmail.com
5a757d190117382c0b198cadf2fdd2cc693407a8
4c2d1c669e16ba7c552d7ca30348b5d013a9fe51
/vtkm/worklet/testing/UnitTestThreshold.cxx
331db6be5be88f0bbd08ef58aa6a51f945615b5e
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
rushah05/VTKm_FP16
7423db6195d60974071565af9995905f45d7a6df
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
refs/heads/main
2023-04-13T12:10:03.420232
2021-02-10T21:34:31
2021-02-10T21:34:31
308,658,384
0
0
NOASSERTION
2021-02-10T21:34:33
2020-10-30T14:43:03
C++
UTF-8
C++
false
false
4,717
cxx
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/worklet/Threshold.h> #include <vtkm/cont/testing/MakeTestDataSet.h> #include <vtkm/cont/testing/Testing.h> #include <vtkm/cont/ArrayPortalToIterators.h> #include <algorithm> #include <iostream> #include <vector> namespace { class HasValue { public: VTKM_CONT HasValue(vtkm::Float32 value) : Value(value) { } template <typename ScalarType> VTKM_EXEC bool operator()(ScalarType value) const { return static_cast<vtkm::Float32>(value) == this->Value; } private: vtkm::Float32 Value; }; using vtkm::cont::testing::MakeTestDataSet; class TestingThreshold { public: void TestUniform2D() const { std::cout << "Testing threshold on 2D uniform dataset" << std::endl; using CellSetType = vtkm::cont::CellSetStructured<2>; using OutCellSetType = vtkm::cont::CellSetPermutation<CellSetType>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make2DUniformDataSet0(); CellSetType cellset; dataset.GetCellSet().CopyTo(cellset); vtkm::cont::ArrayHandle<vtkm::Float32> pointvar; dataset.GetField("pointvar").GetData().CopyTo(pointvar); vtkm::worklet::Threshold threshold; OutCellSetType outCellSet = threshold.Run(cellset, pointvar, vtkm::cont::Field::Association::POINTS, HasValue(60.1f)); VTKM_TEST_ASSERT(outCellSet.GetNumberOfCells() == 1, "Wrong number of cells"); vtkm::cont::ArrayHandle<vtkm::Float32> cellvar; dataset.GetField("cellvar").GetData().CopyTo(cellvar); vtkm::cont::ArrayHandle<vtkm::Float32> cellFieldArray = threshold.ProcessCellField(cellvar); VTKM_TEST_ASSERT(cellFieldArray.GetNumberOfValues() == 1 && cellFieldArray.ReadPortal().Get(0) == 200.1f, "Wrong cell field data"); } void TestUniform3D() const { std::cout << "Testing threshold on 3D uniform dataset" << std::endl; using CellSetType = vtkm::cont::CellSetStructured<3>; using OutCellSetType = vtkm::cont::CellSetPermutation<CellSetType>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet0(); CellSetType cellset; dataset.GetCellSet().CopyTo(cellset); vtkm::cont::ArrayHandle<vtkm::Float32> pointvar; dataset.GetField("pointvar").GetData().CopyTo(pointvar); vtkm::worklet::Threshold threshold; OutCellSetType outCellSet = threshold.Run(cellset, pointvar, vtkm::cont::Field::Association::POINTS, HasValue(20.1f)); VTKM_TEST_ASSERT(outCellSet.GetNumberOfCells() == 2, "Wrong number of cells"); vtkm::cont::ArrayHandle<vtkm::Float32> cellvar; dataset.GetField("cellvar").GetData().CopyTo(cellvar); vtkm::cont::ArrayHandle<vtkm::Float32> cellFieldArray = threshold.ProcessCellField(cellvar); VTKM_TEST_ASSERT(cellFieldArray.GetNumberOfValues() == 2 && cellFieldArray.ReadPortal().Get(0) == 100.1f && cellFieldArray.ReadPortal().Get(1) == 100.2f, "Wrong cell field data"); } void TestExplicit3D() const { std::cout << "Testing threshold on 3D explicit dataset" << std::endl; using CellSetType = vtkm::cont::CellSetExplicit<>; using OutCellSetType = vtkm::cont::CellSetPermutation<CellSetType>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet0(); CellSetType cellset; dataset.GetCellSet().CopyTo(cellset); vtkm::cont::ArrayHandle<vtkm::Float32> cellvar; dataset.GetField("cellvar").GetData().CopyTo(cellvar); vtkm::worklet::Threshold threshold; OutCellSetType outCellSet = threshold.Run(cellset, cellvar, vtkm::cont::Field::Association::CELL_SET, HasValue(100.1f)); VTKM_TEST_ASSERT(outCellSet.GetNumberOfCells() == 1, "Wrong number of cells"); vtkm::cont::ArrayHandle<vtkm::Float32> cellFieldArray = threshold.ProcessCellField(cellvar); VTKM_TEST_ASSERT(cellFieldArray.GetNumberOfValues() == 1 && cellFieldArray.ReadPortal().Get(0) == 100.1f, "Wrong cell field data"); } void operator()() const { this->TestUniform2D(); this->TestUniform3D(); this->TestExplicit3D(); } }; } int UnitTestThreshold(int argc, char* argv[]) { return vtkm::cont::testing::Testing::Run(TestingThreshold(), argc, argv); }
[ "46826537+rushah05@users.noreply.github.com" ]
46826537+rushah05@users.noreply.github.com
4b56e2f74484f53d2b33bf4faa983e1b23b0bf36
ddb3350cd249c1bc85bf191769660765ffe1e1d9
/testDLL1/stdafx.cpp
676a7fe4fcd51994367853f08607c83345b2ca10
[]
no_license
arturhgca/WPFDllImportTest
a488830aa4b6559a2f7d9b2ff847d88971974f37
907f08cbef7302a187864e5cfea823d552fb3c1e
refs/heads/master
2021-01-01T18:04:55.159955
2017-07-24T22:36:58
2017-07-24T22:36:58
98,239,750
0
0
null
null
null
null
UTF-8
C++
false
false
287
cpp
// stdafx.cpp : source file that includes just the standard includes // testDLL1.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "arturhgca@gmail.com" ]
arturhgca@gmail.com
c4d5f52c749eaa346491053f38c838b1fda9ace5
07a5787ae40f09ebe704e88814c502c189b49c72
/librssoft/lib/RR_Factorization.cpp
c000a34263d50319c1ba6b2d801446d847147a20
[]
no_license
xdcesc/rssoft
075c8427ec96b1712bf77a31909419bf71fc9175
493b7909eeff04583d02b0ced6157b47b1bdd36e
refs/heads/master
2021-03-12T22:43:45.461804
2013-09-18T21:56:31
2013-09-18T21:56:31
40,472,370
1
0
null
null
null
null
UTF-8
C++
false
false
6,689
cpp
/* Copyright 2013 Edouard Griffiths <f4exb at free dot fr> This file is part of RSSoft. A Reed-Solomon Soft Decoding library This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA Roth-Ruckenstein factorization class for soft decision decoding Optimized recursive strategy */ #include "RR_Factorization.h" #include "GFq.h" #include "GFq_Polynomial.h" #include "GFq_BivariatePolynomial.h" #include "RSSoft_Exception.h" #include "Debug.h" namespace rssoft { // ================================================================================================ RR_Node::RR_Node(RR_Node *_parent, const gf::GFq_BivariatePolynomial& _Q, const gf::GFq_Element& _coeff, unsigned int _id) : parent(_parent), Q(_Q), coeff(_coeff), id(_id) { if (_parent == 0) { degree = -1; } else { degree = _parent->get_degree()+1; } } // ================================================================================================ RR_Factorization::RR_Factorization(const gf::GFq& _gf, unsigned int _k) : gf(_gf), k(_k), t(0), verbosity(0) { } // ================================================================================================ RR_Factorization::~RR_Factorization() { } // ================================================================================================ void RR_Factorization::init() { t = 0; F.clear(); } // ================================================================================================ std::vector<gf::GFq_Polynomial>& RR_Factorization::run(const gf::GFq_BivariatePolynomial& polynomial) { if (!polynomial.is_valid()) { throw RSSoft_Exception("Invalid polynomial"); } else { const gf::GFq& gf = polynomial.get_leading_monomial().coeff().field(); RR_Node u(0, polynomial, gf::GFq_Element(gf,0), t); node_run(u); return F; } } // ================================================================================================ gf::GFq_Polynomial RR_Factorization::node_run(RR_Node& rr_node) { gf::GFq_BivariatePolynomial Qu = rr_node.getQ(); gf::GFq_Polynomial Qy = Qu.get_0_Y(); std::vector<rssoft::gf::GFq_Element> roots_y; Qy.rootChien(roots_y); std::vector<rssoft::gf::GFq_Element>::const_iterator ry_it = roots_y.begin(); DEBUG_OUT(verbosity > 0, "*** Node #" << rr_node.get_id() << ": " << rr_node.get_degree() << " " << rr_node.get_coeff() << std::endl); if (ry_it != roots_y.end()) { const gf::GFq& gf = ry_it->field(); gf::GFq_BivariatePolynomial X1Y0(Qu.get_weights()); X1Y0.init_x_pow(gf, 1); // X1Y0(X,Y) = X rssoft::gf::GFq_BivariateMonomial m_XY(rssoft::gf::GFq_Element(gf,1),1,1); // X*Y std::vector<gf::GFq_Element> poly_X1; poly_X1.push_back(gf::GFq_Element(gf,0)); poly_X1.push_back(gf::GFq_Element(gf,1)); gf::GFq_Polynomial X1(gf, poly_X1); // X1(X) = X for (; ry_it != roots_y.end(); ++ry_it) { if (!rr_node.is_in_ry_set(*ry_it)) { rr_node.add_ry(*ry_it); gf::GFq_BivariatePolynomial Yv(Qu.get_weights()); // Yv(X,Y) = X*Y + ry std::vector<rssoft::gf::GFq_BivariateMonomial> monos_Yv; rssoft::gf::GFq_BivariateMonomial m_ry(*ry_it,0,0); monos_Yv.push_back(m_ry); monos_Yv.push_back(m_XY); Yv.init(monos_Yv); gf::GFq_BivariatePolynomial Qv = star(Qu(X1Y0,Yv)); DEBUG_OUT(verbosity > 0, " ry = " << *ry_it << " : Qv = " << Qv << std::endl); // Optimization: anticipate behaviour at child node bool Qv_for_Y_eq_0_is_0 = (Qv.get_X_0().is_zero()); // Qv(Y=0) = 0 if (Qv_for_Y_eq_0_is_0) // Qv(Y=0) = 0 { if (rr_node.get_degree() < k-1) { // trace back this route from node v DEBUG_OUT(verbosity > 1, " -> trace back this route from node v: " << (rr_node.get_coeff()*(X1^rr_node.get_degree()))+(*ry_it*(X1^(rr_node.get_degree()+1))) << std::endl); return (rr_node.get_coeff()*(X1^rr_node.get_degree()))+(*ry_it*(X1^(rr_node.get_degree()+1))); } else { // trace back this route from node u DEBUG_OUT(verbosity > 1, " -> trace back this route from node u: " << rr_node.get_coeff()*(X1^rr_node.get_degree()) << std::endl); return rr_node.get_coeff()*(X1^rr_node.get_degree()); } } else if ((rr_node.get_degree() == k-1) && !Qv_for_Y_eq_0_is_0) { DEBUG_OUT(verbosity > 1, " -> invalidate the route by returning an invalid polynomial" << std::endl); return gf::GFq_Polynomial(gf); // invalidate the route by returning an invalid polynomial } else { // construct a child node t++; DEBUG_OUT(verbosity > 1, " child #" << t << std::endl); RR_Node child_node(&rr_node, Qv, *ry_it, t); gf::GFq_Polynomial part_Fv = node_run(child_node); // Recursive call if (rr_node.get_degree() == -1) // we are at the root node { DEBUG_OUT(verbosity > 0, " we are at root node" << std::endl); if (part_Fv.is_valid()) { DEBUG_OUT(verbosity > 0, " Fi = " << part_Fv << std::endl); F.push_back(part_Fv); // collect result } } else { if (!part_Fv.is_valid()) { DEBUG_OUT(verbosity > 1, " -> propagate invalid route" << std::endl); return part_Fv; } else { DEBUG_OUT(verbosity > 1, " -> return partial polynomial: " << ((rr_node.get_coeff()*(X1^rr_node.get_degree())) + part_Fv) << std::endl); return (rr_node.get_coeff()*(X1^rr_node.get_degree())) + part_Fv; } } } } } } return gf::GFq_Polynomial(gf); } } // namespace rssoft
[ "f4exb06@gmail.com" ]
f4exb06@gmail.com
246cc95b35032a7d505f2b282cd93991c22389e9
486b8e06d7d42b3761fe77b11f760b824de6fd89
/Refureku/Library/Include/TypeInfo/PropertyGroup.inl
5abf658de66b4223b5b11e3d9174013f117326a0
[ "MIT" ]
permissive
CrackerCat/Refureku
5183f8e20f1a1d90e698b33d88b067c349b75824
5b8047c023788dc42be6f8ce0c98edb76f5570ed
refs/heads/master
2022-10-07T01:49:10.849889
2020-06-05T19:31:29
2020-06-05T19:31:29
269,936,069
0
1
MIT
2020-06-06T09:45:12
2020-06-06T09:45:11
null
UTF-8
C++
false
false
680
inl
/** * Copyright (c) 2020 Julien SOYSOUVANH - All Rights Reserved * * This file is part of the Refureku library project which is released under the MIT License. * See the README.md file for full license details. */ inline bool PropertyGroup::hasProperty(std::string const& prop) const noexcept { return simpleProperties.find(prop) != simpleProperties.cend(); } inline bool PropertyGroup::hasProperty(std::string const& main, std::string const& sub) const noexcept { auto range = complexProperties.equal_range(main); return std::find_if(range.first, range.second, [sub](std::pair<std::string, std::string> pair) noexcept { return pair.second == sub; }) != range.second; }
[ "j.soysouvanh@student.isartdigital.com" ]
j.soysouvanh@student.isartdigital.com
8bac989cf1eb5a3dd5f72807321537e06d0ebdd2
5e3a29123e0a51a23f50fd01589e67c2c6175f5f
/windows/runner/main.cpp
be9121e6b2eba3d45d59578c9b7106c66b7eea64
[]
no_license
codetricity/flame_monster_spawn
039c79ac095e2d72e8a97e5ddc2b0cec6d7250ca
9dac338ee0d6cc8988886798f550df55d8183a8e
refs/heads/main
2023-07-13T04:19:18.420067
2021-08-20T13:27:12
2021-08-20T13:27:12
398,284,983
0
0
null
null
null
null
UTF-8
C++
false
false
1,274
cpp
#include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include "flutter_window.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); flutter::DartProject project(L"data"); std::vector<std::string> command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"alien_stomper2", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); ::MSG msg; while (::GetMessage(&msg, nullptr, 0, 0)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::CoUninitialize(); return EXIT_SUCCESS; }
[ "craig@oppkey.com" ]
craig@oppkey.com
d2e638e195274ae9a7f187fcd83d99dcf27049ac
cb304a53bd560c87b39da31e0446d1a0424012a5
/rtb_prototype/build/grpc_proto/rtb.grpc.pb.h
945d51b933799ecb08e3b0d895283047b4562591
[]
no_license
burgfilho/cpp_study
a090b09ca041655e2dcc87a426c35d86ac496e5e
0b4086c42508f306c0d0efa1e475e5a3bfe98bc8
refs/heads/master
2020-03-28T04:32:01.473033
2018-12-03T16:24:56
2018-12-03T16:24:56
147,720,673
0
0
null
null
null
null
UTF-8
C++
false
true
36,820
h
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: rtb.proto #ifndef GRPC_rtb_2eproto__INCLUDED #define GRPC_rtb_2eproto__INCLUDED #include "rtb.pb.h" #include <functional> #include <grpcpp/impl/codegen/async_generic_service.h> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/method_handler_impl.h> #include <grpcpp/impl/codegen/proto_utils.h> #include <grpcpp/impl/codegen/rpc_method.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/status.h> #include <grpcpp/impl/codegen/stub_options.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace grpc { class CompletionQueue; class Channel; class ServerCompletionQueue; class ServerContext; } // namespace grpc namespace sita { namespace rtb { class RTB final { public: static constexpr char const* service_full_name() { return "sita.rtb.RTB"; } class StubInterface { public: virtual ~StubInterface() {} virtual ::grpc::Status Help(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::sita::rtb::HelpReply* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::HelpReply>> AsyncHelp(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::HelpReply>>(AsyncHelpRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::HelpReply>> PrepareAsyncHelp(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::HelpReply>>(PrepareAsyncHelpRaw(context, request, cq)); } virtual ::grpc::Status Add(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::sita::rtb::AddReply* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::AddReply>> AsyncAdd(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::AddReply>>(AsyncAddRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::AddReply>> PrepareAsyncAdd(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::AddReply>>(PrepareAsyncAddRaw(context, request, cq)); } virtual ::grpc::Status Delete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::sita::rtb::DeleteReply* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DeleteReply>> AsyncDelete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DeleteReply>>(AsyncDeleteRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DeleteReply>> PrepareAsyncDelete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DeleteReply>>(PrepareAsyncDeleteRaw(context, request, cq)); } virtual ::grpc::Status Clear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::sita::rtb::ClearReply* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::ClearReply>> AsyncClear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::ClearReply>>(AsyncClearRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::ClearReply>> PrepareAsyncClear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::ClearReply>>(PrepareAsyncClearRaw(context, request, cq)); } virtual ::grpc::Status Display(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::sita::rtb::DisplayReply* response) = 0; std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DisplayReply>> AsyncDisplay(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DisplayReply>>(AsyncDisplayRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DisplayReply>> PrepareAsyncDisplay(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DisplayReply>>(PrepareAsyncDisplayRaw(context, request, cq)); } class experimental_async_interface { public: virtual ~experimental_async_interface() {} virtual void Help(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response, std::function<void(::grpc::Status)>) = 0; virtual void Add(::grpc::ClientContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response, std::function<void(::grpc::Status)>) = 0; virtual void Delete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response, std::function<void(::grpc::Status)>) = 0; virtual void Clear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response, std::function<void(::grpc::Status)>) = 0; virtual void Display(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response, std::function<void(::grpc::Status)>) = 0; }; virtual class experimental_async_interface* experimental_async() { return nullptr; } private: virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::HelpReply>* AsyncHelpRaw(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::HelpReply>* PrepareAsyncHelpRaw(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::AddReply>* AsyncAddRaw(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::AddReply>* PrepareAsyncAddRaw(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DeleteReply>* AsyncDeleteRaw(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DeleteReply>* PrepareAsyncDeleteRaw(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::ClearReply>* AsyncClearRaw(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::ClearReply>* PrepareAsyncClearRaw(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DisplayReply>* AsyncDisplayRaw(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) = 0; virtual ::grpc::ClientAsyncResponseReaderInterface< ::sita::rtb::DisplayReply>* PrepareAsyncDisplayRaw(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) = 0; }; class Stub final : public StubInterface { public: Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); ::grpc::Status Help(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::sita::rtb::HelpReply* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::HelpReply>> AsyncHelp(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::HelpReply>>(AsyncHelpRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::HelpReply>> PrepareAsyncHelp(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::HelpReply>>(PrepareAsyncHelpRaw(context, request, cq)); } ::grpc::Status Add(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::sita::rtb::AddReply* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::AddReply>> AsyncAdd(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::AddReply>>(AsyncAddRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::AddReply>> PrepareAsyncAdd(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::AddReply>>(PrepareAsyncAddRaw(context, request, cq)); } ::grpc::Status Delete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::sita::rtb::DeleteReply* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DeleteReply>> AsyncDelete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DeleteReply>>(AsyncDeleteRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DeleteReply>> PrepareAsyncDelete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DeleteReply>>(PrepareAsyncDeleteRaw(context, request, cq)); } ::grpc::Status Clear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::sita::rtb::ClearReply* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::ClearReply>> AsyncClear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::ClearReply>>(AsyncClearRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::ClearReply>> PrepareAsyncClear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::ClearReply>>(PrepareAsyncClearRaw(context, request, cq)); } ::grpc::Status Display(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::sita::rtb::DisplayReply* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DisplayReply>> AsyncDisplay(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DisplayReply>>(AsyncDisplayRaw(context, request, cq)); } std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DisplayReply>> PrepareAsyncDisplay(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::sita::rtb::DisplayReply>>(PrepareAsyncDisplayRaw(context, request, cq)); } class experimental_async final : public StubInterface::experimental_async_interface { public: void Help(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response, std::function<void(::grpc::Status)>) override; void Add(::grpc::ClientContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response, std::function<void(::grpc::Status)>) override; void Delete(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response, std::function<void(::grpc::Status)>) override; void Clear(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response, std::function<void(::grpc::Status)>) override; void Display(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response, std::function<void(::grpc::Status)>) override; private: friend class Stub; explicit experimental_async(Stub* stub): stub_(stub) { } Stub* stub() { return stub_; } Stub* stub_; }; class experimental_async_interface* experimental_async() override { return &async_stub_; } private: std::shared_ptr< ::grpc::ChannelInterface> channel_; class experimental_async async_stub_{this}; ::grpc::ClientAsyncResponseReader< ::sita::rtb::HelpReply>* AsyncHelpRaw(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::HelpReply>* PrepareAsyncHelpRaw(::grpc::ClientContext* context, const ::sita::rtb::HelpRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::AddReply>* AsyncAddRaw(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::AddReply>* PrepareAsyncAddRaw(::grpc::ClientContext* context, const ::sita::rtb::AddRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::DeleteReply>* AsyncDeleteRaw(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::DeleteReply>* PrepareAsyncDeleteRaw(::grpc::ClientContext* context, const ::sita::rtb::DeleteRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::ClearReply>* AsyncClearRaw(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::ClearReply>* PrepareAsyncClearRaw(::grpc::ClientContext* context, const ::sita::rtb::ClearRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::DisplayReply>* AsyncDisplayRaw(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) override; ::grpc::ClientAsyncResponseReader< ::sita::rtb::DisplayReply>* PrepareAsyncDisplayRaw(::grpc::ClientContext* context, const ::sita::rtb::DisplayRequest& request, ::grpc::CompletionQueue* cq) override; const ::grpc::internal::RpcMethod rpcmethod_Help_; const ::grpc::internal::RpcMethod rpcmethod_Add_; const ::grpc::internal::RpcMethod rpcmethod_Delete_; const ::grpc::internal::RpcMethod rpcmethod_Clear_; const ::grpc::internal::RpcMethod rpcmethod_Display_; }; static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); class Service : public ::grpc::Service { public: Service(); virtual ~Service(); virtual ::grpc::Status Help(::grpc::ServerContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response); virtual ::grpc::Status Add(::grpc::ServerContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response); virtual ::grpc::Status Delete(::grpc::ServerContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response); virtual ::grpc::Status Clear(::grpc::ServerContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response); virtual ::grpc::Status Display(::grpc::ServerContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response); }; template <class BaseClass> class WithAsyncMethod_Help : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Help() { ::grpc::Service::MarkMethodAsync(0); } ~WithAsyncMethod_Help() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Help(::grpc::ServerContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestHelp(::grpc::ServerContext* context, ::sita::rtb::HelpRequest* request, ::grpc::ServerAsyncResponseWriter< ::sita::rtb::HelpReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Add : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Add() { ::grpc::Service::MarkMethodAsync(1); } ~WithAsyncMethod_Add() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Add(::grpc::ServerContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestAdd(::grpc::ServerContext* context, ::sita::rtb::AddRequest* request, ::grpc::ServerAsyncResponseWriter< ::sita::rtb::AddReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Delete : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Delete() { ::grpc::Service::MarkMethodAsync(2); } ~WithAsyncMethod_Delete() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Delete(::grpc::ServerContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestDelete(::grpc::ServerContext* context, ::sita::rtb::DeleteRequest* request, ::grpc::ServerAsyncResponseWriter< ::sita::rtb::DeleteReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Clear : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Clear() { ::grpc::Service::MarkMethodAsync(3); } ~WithAsyncMethod_Clear() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Clear(::grpc::ServerContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestClear(::grpc::ServerContext* context, ::sita::rtb::ClearRequest* request, ::grpc::ServerAsyncResponseWriter< ::sita::rtb::ClearReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(3, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithAsyncMethod_Display : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithAsyncMethod_Display() { ::grpc::Service::MarkMethodAsync(4); } ~WithAsyncMethod_Display() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Display(::grpc::ServerContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestDisplay(::grpc::ServerContext* context, ::sita::rtb::DisplayRequest* request, ::grpc::ServerAsyncResponseWriter< ::sita::rtb::DisplayReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(4, context, request, response, new_call_cq, notification_cq, tag); } }; typedef WithAsyncMethod_Help<WithAsyncMethod_Add<WithAsyncMethod_Delete<WithAsyncMethod_Clear<WithAsyncMethod_Display<Service > > > > > AsyncService; template <class BaseClass> class WithGenericMethod_Help : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Help() { ::grpc::Service::MarkMethodGeneric(0); } ~WithGenericMethod_Help() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Help(::grpc::ServerContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Add : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Add() { ::grpc::Service::MarkMethodGeneric(1); } ~WithGenericMethod_Add() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Add(::grpc::ServerContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Delete : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Delete() { ::grpc::Service::MarkMethodGeneric(2); } ~WithGenericMethod_Delete() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Delete(::grpc::ServerContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Clear : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Clear() { ::grpc::Service::MarkMethodGeneric(3); } ~WithGenericMethod_Clear() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Clear(::grpc::ServerContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithGenericMethod_Display : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithGenericMethod_Display() { ::grpc::Service::MarkMethodGeneric(4); } ~WithGenericMethod_Display() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Display(::grpc::ServerContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } }; template <class BaseClass> class WithRawMethod_Help : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithRawMethod_Help() { ::grpc::Service::MarkMethodRaw(0); } ~WithRawMethod_Help() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Help(::grpc::ServerContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestHelp(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithRawMethod_Add : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithRawMethod_Add() { ::grpc::Service::MarkMethodRaw(1); } ~WithRawMethod_Add() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Add(::grpc::ServerContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestAdd(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithRawMethod_Delete : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithRawMethod_Delete() { ::grpc::Service::MarkMethodRaw(2); } ~WithRawMethod_Delete() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Delete(::grpc::ServerContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestDelete(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithRawMethod_Clear : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithRawMethod_Clear() { ::grpc::Service::MarkMethodRaw(3); } ~WithRawMethod_Clear() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Clear(::grpc::ServerContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestClear(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(3, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithRawMethod_Display : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithRawMethod_Display() { ::grpc::Service::MarkMethodRaw(4); } ~WithRawMethod_Display() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method ::grpc::Status Display(::grpc::ServerContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } void RequestDisplay(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { ::grpc::Service::RequestAsyncUnary(4, context, request, response, new_call_cq, notification_cq, tag); } }; template <class BaseClass> class WithStreamedUnaryMethod_Help : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Help() { ::grpc::Service::MarkMethodStreamed(0, new ::grpc::internal::StreamedUnaryHandler< ::sita::rtb::HelpRequest, ::sita::rtb::HelpReply>(std::bind(&WithStreamedUnaryMethod_Help<BaseClass>::StreamedHelp, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Help() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Help(::grpc::ServerContext* context, const ::sita::rtb::HelpRequest* request, ::sita::rtb::HelpReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedHelp(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::sita::rtb::HelpRequest,::sita::rtb::HelpReply>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Add : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Add() { ::grpc::Service::MarkMethodStreamed(1, new ::grpc::internal::StreamedUnaryHandler< ::sita::rtb::AddRequest, ::sita::rtb::AddReply>(std::bind(&WithStreamedUnaryMethod_Add<BaseClass>::StreamedAdd, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Add() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Add(::grpc::ServerContext* context, const ::sita::rtb::AddRequest* request, ::sita::rtb::AddReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedAdd(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::sita::rtb::AddRequest,::sita::rtb::AddReply>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Delete : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Delete() { ::grpc::Service::MarkMethodStreamed(2, new ::grpc::internal::StreamedUnaryHandler< ::sita::rtb::DeleteRequest, ::sita::rtb::DeleteReply>(std::bind(&WithStreamedUnaryMethod_Delete<BaseClass>::StreamedDelete, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Delete() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Delete(::grpc::ServerContext* context, const ::sita::rtb::DeleteRequest* request, ::sita::rtb::DeleteReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedDelete(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::sita::rtb::DeleteRequest,::sita::rtb::DeleteReply>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Clear : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Clear() { ::grpc::Service::MarkMethodStreamed(3, new ::grpc::internal::StreamedUnaryHandler< ::sita::rtb::ClearRequest, ::sita::rtb::ClearReply>(std::bind(&WithStreamedUnaryMethod_Clear<BaseClass>::StreamedClear, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Clear() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Clear(::grpc::ServerContext* context, const ::sita::rtb::ClearRequest* request, ::sita::rtb::ClearReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedClear(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::sita::rtb::ClearRequest,::sita::rtb::ClearReply>* server_unary_streamer) = 0; }; template <class BaseClass> class WithStreamedUnaryMethod_Display : public BaseClass { private: void BaseClassMustBeDerivedFromService(const Service *service) {} public: WithStreamedUnaryMethod_Display() { ::grpc::Service::MarkMethodStreamed(4, new ::grpc::internal::StreamedUnaryHandler< ::sita::rtb::DisplayRequest, ::sita::rtb::DisplayReply>(std::bind(&WithStreamedUnaryMethod_Display<BaseClass>::StreamedDisplay, this, std::placeholders::_1, std::placeholders::_2))); } ~WithStreamedUnaryMethod_Display() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method ::grpc::Status Display(::grpc::ServerContext* context, const ::sita::rtb::DisplayRequest* request, ::sita::rtb::DisplayReply* response) override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } // replace default version of method with streamed unary virtual ::grpc::Status StreamedDisplay(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::sita::rtb::DisplayRequest,::sita::rtb::DisplayReply>* server_unary_streamer) = 0; }; typedef WithStreamedUnaryMethod_Help<WithStreamedUnaryMethod_Add<WithStreamedUnaryMethod_Delete<WithStreamedUnaryMethod_Clear<WithStreamedUnaryMethod_Display<Service > > > > > StreamedUnaryService; typedef Service SplitStreamedService; typedef WithStreamedUnaryMethod_Help<WithStreamedUnaryMethod_Add<WithStreamedUnaryMethod_Delete<WithStreamedUnaryMethod_Clear<WithStreamedUnaryMethod_Display<Service > > > > > StreamedService; }; } // namespace rtb } // namespace sita #endif // GRPC_rtb_2eproto__INCLUDED
[ "burg@ostra.dom_qp.com.br" ]
burg@ostra.dom_qp.com.br
7e22ecbc86a7d6235fa6d750e2c3eca3657a8d84
561de3b7528ca1892bbde417888337512033bfe9
/Benchmarks/gbench/src/benchmark.cc
a086453a943a59ba1d650c03139d526b787dbf5c
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
marcoafo/OpenXLSX
e63aab94c0b6f571f36f57437bb71330d8520d2b
b80da42d1454f361c29117095ebe1989437db390
refs/heads/master
2022-08-27T09:35:17.214043
2022-07-03T11:43:24
2022-07-03T11:43:24
263,135,789
0
0
BSD-3-Clause
2020-05-11T19:18:47
2020-05-11T19:18:47
null
UTF-8
C++
false
false
22,175
cc
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/benchmark.h" #include "benchmark_api_internal.h" #include "benchmark_runner.h" #include "internal_macros.h" #ifndef BENCHMARK_OS_WINDOWS #ifndef BENCHMARK_OS_FUCHSIA #include <sys/resource.h> #endif #include <sys/time.h> #include <unistd.h> #endif #include <algorithm> #include <atomic> #include <condition_variable> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <limits> #include <map> #include <memory> #include <random> #include <string> #include <thread> #include <utility> #include "check.h" #include "colorprint.h" #include "commandlineflags.h" #include "complexity.h" #include "counter.h" #include "internal_macros.h" #include "log.h" #include "mutex.h" #include "perf_counters.h" #include "re.h" #include "statistics.h" #include "string_util.h" #include "thread_manager.h" #include "thread_timer.h" namespace benchmark { // Print a list of benchmarks. This option overrides all other options. BM_DEFINE_bool(benchmark_list_tests, false); // A regular expression that specifies the set of benchmarks to execute. If // this flag is empty, or if this flag is the string \"all\", all benchmarks // linked into the binary are run. BM_DEFINE_string(benchmark_filter, ""); // Minimum number of seconds we should run benchmark before results are // considered significant. For cpu-time based tests, this is the lower bound // on the total cpu time used by all threads that make up the test. For // real-time based tests, this is the lower bound on the elapsed time of the // benchmark execution, regardless of number of threads. BM_DEFINE_double(benchmark_min_time, 0.5); // The number of runs of each benchmark. If greater than 1, the mean and // standard deviation of the runs will be reported. BM_DEFINE_int32(benchmark_repetitions, 1); // If set, enable random interleaving of repetitions of all benchmarks. // See http://github.com/google/benchmark/issues/1051 for details. BM_DEFINE_bool(benchmark_enable_random_interleaving, false); // Report the result of each benchmark repetitions. When 'true' is specified // only the mean, standard deviation, and other statistics are reported for // repeated benchmarks. Affects all reporters. BM_DEFINE_bool(benchmark_report_aggregates_only, false); // Display the result of each benchmark repetitions. When 'true' is specified // only the mean, standard deviation, and other statistics are displayed for // repeated benchmarks. Unlike benchmark_report_aggregates_only, only affects // the display reporter, but *NOT* file reporter, which will still contain // all the output. BM_DEFINE_bool(benchmark_display_aggregates_only, false); // The format to use for console output. // Valid values are 'console', 'json', or 'csv'. BM_DEFINE_string(benchmark_format, "console"); // The format to use for file output. // Valid values are 'console', 'json', or 'csv'. BM_DEFINE_string(benchmark_out_format, "json"); // The file to write additional output to. BM_DEFINE_string(benchmark_out, ""); // Whether to use colors in the output. Valid values: // 'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use colors if // the output is being sent to a terminal and the TERM environment variable is // set to a terminal type that supports colors. BM_DEFINE_string(benchmark_color, "auto"); // Whether to use tabular format when printing user counters to the console. // Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false. BM_DEFINE_bool(benchmark_counters_tabular, false); // List of additional perf counters to collect, in libpfm format. For more // information about libpfm: https://man7.org/linux/man-pages/man3/libpfm.3.html BM_DEFINE_string(benchmark_perf_counters, ""); // Extra context to include in the output formatted as comma-separated key-value // pairs. Kept internal as it's only used for parsing from env/command line. BM_DEFINE_kvpairs(benchmark_context, {}); // The level of verbose logging to output BM_DEFINE_int32(v, 0); namespace internal { std::map<std::string, std::string>* global_context = nullptr; // FIXME: wouldn't LTO mess this up? void UseCharPointer(char const volatile*) {} } // namespace internal State::State(IterationCount max_iters, const std::vector<int64_t>& ranges, int thread_i, int n_threads, internal::ThreadTimer* timer, internal::ThreadManager* manager, internal::PerfCountersMeasurement* perf_counters_measurement) : total_iterations_(0), batch_leftover_(0), max_iterations(max_iters), started_(false), finished_(false), error_occurred_(false), range_(ranges), complexity_n_(0), counters(), thread_index_(thread_i), threads_(n_threads), timer_(timer), manager_(manager), perf_counters_measurement_(perf_counters_measurement) { BM_CHECK(max_iterations != 0) << "At least one iteration must be run"; BM_CHECK_LT(thread_index_, threads_) << "thread_index must be less than threads"; // Note: The use of offsetof below is technically undefined until C++17 // because State is not a standard layout type. However, all compilers // currently provide well-defined behavior as an extension (which is // demonstrated since constexpr evaluation must diagnose all undefined // behavior). However, GCC and Clang also warn about this use of offsetof, // which must be suppressed. #if defined(__INTEL_COMPILER) #pragma warning push #pragma warning(disable : 1875) #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winvalid-offsetof" #endif // Offset tests to ensure commonly accessed data is on the first cache line. const int cache_line_size = 64; static_assert(offsetof(State, error_occurred_) <= (cache_line_size - sizeof(error_occurred_)), ""); #if defined(__INTEL_COMPILER) #pragma warning pop #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif } void State::PauseTiming() { // Add in time accumulated so far BM_CHECK(started_ && !finished_ && !error_occurred_); timer_->StopTimer(); if (perf_counters_measurement_) { auto measurements = perf_counters_measurement_->StopAndGetMeasurements(); for (const auto& name_and_measurement : measurements) { auto name = name_and_measurement.first; auto measurement = name_and_measurement.second; BM_CHECK_EQ(counters[name], 0.0); counters[name] = Counter(measurement, Counter::kAvgIterations); } } } void State::ResumeTiming() { BM_CHECK(started_ && !finished_ && !error_occurred_); timer_->StartTimer(); if (perf_counters_measurement_) { perf_counters_measurement_->Start(); } } void State::SkipWithError(const char* msg) { BM_CHECK(msg); error_occurred_ = true; { MutexLock l(manager_->GetBenchmarkMutex()); if (manager_->results.has_error_ == false) { manager_->results.error_message_ = msg; manager_->results.has_error_ = true; } } total_iterations_ = 0; if (timer_->running()) timer_->StopTimer(); } void State::SetIterationTime(double seconds) { timer_->SetIterationTime(seconds); } void State::SetLabel(const char* label) { MutexLock l(manager_->GetBenchmarkMutex()); manager_->results.report_label_ = label; } void State::StartKeepRunning() { BM_CHECK(!started_ && !finished_); started_ = true; total_iterations_ = error_occurred_ ? 0 : max_iterations; manager_->StartStopBarrier(); if (!error_occurred_) ResumeTiming(); } void State::FinishKeepRunning() { BM_CHECK(started_ && (!finished_ || error_occurred_)); if (!error_occurred_) { PauseTiming(); } // Total iterations has now wrapped around past 0. Fix this. total_iterations_ = 0; finished_ = true; manager_->StartStopBarrier(); } namespace internal { namespace { // Flushes streams after invoking reporter methods that write to them. This // ensures users get timely updates even when streams are not line-buffered. void FlushStreams(BenchmarkReporter* reporter) { if (!reporter) return; std::flush(reporter->GetOutputStream()); std::flush(reporter->GetErrorStream()); } // Reports in both display and file reporters. void Report(BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter, const RunResults& run_results) { auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only, const RunResults& results) { assert(reporter); // If there are no aggregates, do output non-aggregates. aggregates_only &= !results.aggregates_only.empty(); if (!aggregates_only) reporter->ReportRuns(results.non_aggregates); if (!results.aggregates_only.empty()) reporter->ReportRuns(results.aggregates_only); }; report_one(display_reporter, run_results.display_report_aggregates_only, run_results); if (file_reporter) report_one(file_reporter, run_results.file_report_aggregates_only, run_results); FlushStreams(display_reporter); FlushStreams(file_reporter); } void RunBenchmarks(const std::vector<BenchmarkInstance>& benchmarks, BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter) { // Note the file_reporter can be null. BM_CHECK(display_reporter != nullptr); // Determine the width of the name field using a minimum width of 10. bool might_have_aggregates = FLAGS_benchmark_repetitions > 1; size_t name_field_width = 10; size_t stat_field_width = 0; for (const BenchmarkInstance& benchmark : benchmarks) { name_field_width = std::max<size_t>(name_field_width, benchmark.name().str().size()); might_have_aggregates |= benchmark.repetitions() > 1; for (const auto& Stat : benchmark.statistics()) stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size()); } if (might_have_aggregates) name_field_width += 1 + stat_field_width; // Print header here BenchmarkReporter::Context context; context.name_field_width = name_field_width; // Keep track of running times of all instances of each benchmark family. std::map<int /*family_index*/, BenchmarkReporter::PerFamilyRunReports> per_family_reports; if (display_reporter->ReportContext(context) && (!file_reporter || file_reporter->ReportContext(context))) { FlushStreams(display_reporter); FlushStreams(file_reporter); size_t num_repetitions_total = 0; std::vector<internal::BenchmarkRunner> runners; runners.reserve(benchmarks.size()); for (const BenchmarkInstance& benchmark : benchmarks) { BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr; if (benchmark.complexity() != oNone) reports_for_family = &per_family_reports[benchmark.family_index()]; runners.emplace_back(benchmark, reports_for_family); int num_repeats_of_this_instance = runners.back().GetNumRepeats(); num_repetitions_total += num_repeats_of_this_instance; if (reports_for_family) reports_for_family->num_runs_total += num_repeats_of_this_instance; } assert(runners.size() == benchmarks.size() && "Unexpected runner count."); std::vector<size_t> repetition_indices; repetition_indices.reserve(num_repetitions_total); for (size_t runner_index = 0, num_runners = runners.size(); runner_index != num_runners; ++runner_index) { const internal::BenchmarkRunner& runner = runners[runner_index]; std::fill_n(std::back_inserter(repetition_indices), runner.GetNumRepeats(), runner_index); } assert(repetition_indices.size() == num_repetitions_total && "Unexpected number of repetition indexes."); if (FLAGS_benchmark_enable_random_interleaving) { std::random_device rd; std::mt19937 g(rd()); std::shuffle(repetition_indices.begin(), repetition_indices.end(), g); } for (size_t repetition_index : repetition_indices) { internal::BenchmarkRunner& runner = runners[repetition_index]; runner.DoOneRepetition(); if (runner.HasRepeatsRemaining()) continue; // FIXME: report each repetition separately, not all of them in bulk. RunResults run_results = runner.GetResults(); // Maybe calculate complexity report if (const auto* reports_for_family = runner.GetReportsForFamily()) { if (reports_for_family->num_runs_done == reports_for_family->num_runs_total) { auto additional_run_stats = ComputeBigO(reports_for_family->Runs); run_results.aggregates_only.insert(run_results.aggregates_only.end(), additional_run_stats.begin(), additional_run_stats.end()); per_family_reports.erase( (int)reports_for_family->Runs.front().family_index); } } Report(display_reporter, file_reporter, run_results); } } display_reporter->Finalize(); if (file_reporter) file_reporter->Finalize(); FlushStreams(display_reporter); FlushStreams(file_reporter); } // Disable deprecated warnings temporarily because we need to reference // CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif std::unique_ptr<BenchmarkReporter> CreateReporter( std::string const& name, ConsoleReporter::OutputOptions output_opts) { typedef std::unique_ptr<BenchmarkReporter> PtrType; if (name == "console") { return PtrType(new ConsoleReporter(output_opts)); } else if (name == "json") { return PtrType(new JSONReporter); } else if (name == "csv") { return PtrType(new CSVReporter); } else { std::cerr << "Unexpected format: '" << name << "'\n"; std::exit(1); } } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif } // end namespace bool IsZero(double n) { return std::abs(n) < std::numeric_limits<double>::epsilon(); } ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { int output_opts = ConsoleReporter::OO_Defaults; auto is_benchmark_color = [force_no_color]() -> bool { if (force_no_color) { return false; } if (FLAGS_benchmark_color == "auto") { return IsColorTerminal(); } return IsTruthyFlagValue(FLAGS_benchmark_color); }; if (is_benchmark_color()) { output_opts |= ConsoleReporter::OO_Color; } else { output_opts &= ~ConsoleReporter::OO_Color; } if (FLAGS_benchmark_counters_tabular) { output_opts |= ConsoleReporter::OO_Tabular; } else { output_opts &= ~ConsoleReporter::OO_Tabular; } return static_cast<ConsoleReporter::OutputOptions>(output_opts); } } // end namespace internal size_t RunSpecifiedBenchmarks() { return RunSpecifiedBenchmarks(nullptr, nullptr); } size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) { return RunSpecifiedBenchmarks(display_reporter, nullptr); } size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter) { std::string spec = FLAGS_benchmark_filter; if (spec.empty() || spec == "all") spec = "."; // Regexp that matches all benchmarks // Setup the reporters std::ofstream output_file; std::unique_ptr<BenchmarkReporter> default_display_reporter; std::unique_ptr<BenchmarkReporter> default_file_reporter; if (!display_reporter) { default_display_reporter = internal::CreateReporter( FLAGS_benchmark_format, internal::GetOutputOptions()); display_reporter = default_display_reporter.get(); } auto& Out = display_reporter->GetOutputStream(); auto& Err = display_reporter->GetErrorStream(); std::string const& fname = FLAGS_benchmark_out; if (fname.empty() && file_reporter) { Err << "A custom file reporter was provided but " "--benchmark_out=<file> was not specified." << std::endl; std::exit(1); } if (!fname.empty()) { output_file.open(fname); if (!output_file.is_open()) { Err << "invalid file name: '" << fname << "'" << std::endl; std::exit(1); } if (!file_reporter) { default_file_reporter = internal::CreateReporter( FLAGS_benchmark_out_format, ConsoleReporter::OO_None); file_reporter = default_file_reporter.get(); } file_reporter->SetOutputStream(&output_file); file_reporter->SetErrorStream(&output_file); } std::vector<internal::BenchmarkInstance> benchmarks; if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0; if (benchmarks.empty()) { Err << "Failed to match any benchmarks against regex: " << spec << "\n"; return 0; } if (FLAGS_benchmark_list_tests) { for (auto const& benchmark : benchmarks) Out << benchmark.name().str() << "\n"; } else { internal::RunBenchmarks(benchmarks, display_reporter, file_reporter); } return benchmarks.size(); } void RegisterMemoryManager(MemoryManager* manager) { internal::memory_manager = manager; } void AddCustomContext(const std::string& key, const std::string& value) { if (internal::global_context == nullptr) { internal::global_context = new std::map<std::string, std::string>(); } if (!internal::global_context->emplace(key, value).second) { std::cerr << "Failed to add custom context \"" << key << "\" as it already " << "exists with value \"" << value << "\"\n"; } } namespace internal { void PrintUsageAndExit() { fprintf(stdout, "benchmark" " [--benchmark_list_tests={true|false}]\n" " [--benchmark_filter=<regex>]\n" " [--benchmark_min_time=<min_time>]\n" " [--benchmark_repetitions=<num_repetitions>]\n" " [--benchmark_enable_random_interleaving={true|false}]\n" " [--benchmark_report_aggregates_only={true|false}]\n" " [--benchmark_display_aggregates_only={true|false}]\n" " [--benchmark_format=<console|json|csv>]\n" " [--benchmark_out=<filename>]\n" " [--benchmark_out_format=<json|console|csv>]\n" " [--benchmark_color={auto|true|false}]\n" " [--benchmark_counters_tabular={true|false}]\n" " [--benchmark_perf_counters=<counter>,...]\n" " [--benchmark_context=<key>=<value>,...]\n" " [--v=<verbosity>]\n"); exit(0); } void ParseCommandLineFlags(int* argc, char** argv) { using namespace benchmark; BenchmarkReporter::Context::executable_name = (argc && *argc > 0) ? argv[0] : "unknown"; for (int i = 1; argc && i < *argc; ++i) { if (ParseBoolFlag(argv[i], "benchmark_list_tests", &FLAGS_benchmark_list_tests) || ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) || ParseDoubleFlag(argv[i], "benchmark_min_time", &FLAGS_benchmark_min_time) || ParseInt32Flag(argv[i], "benchmark_repetitions", &FLAGS_benchmark_repetitions) || ParseBoolFlag(argv[i], "benchmark_enable_random_interleaving", &FLAGS_benchmark_enable_random_interleaving) || ParseBoolFlag(argv[i], "benchmark_report_aggregates_only", &FLAGS_benchmark_report_aggregates_only) || ParseBoolFlag(argv[i], "benchmark_display_aggregates_only", &FLAGS_benchmark_display_aggregates_only) || ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) || ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) || ParseStringFlag(argv[i], "benchmark_out_format", &FLAGS_benchmark_out_format) || ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) || // "color_print" is the deprecated name for "benchmark_color". // TODO: Remove this. ParseStringFlag(argv[i], "color_print", &FLAGS_benchmark_color) || ParseBoolFlag(argv[i], "benchmark_counters_tabular", &FLAGS_benchmark_counters_tabular) || ParseStringFlag(argv[i], "benchmark_perf_counters", &FLAGS_benchmark_perf_counters) || ParseKeyValueFlag(argv[i], "benchmark_context", &FLAGS_benchmark_context) || ParseInt32Flag(argv[i], "v", &FLAGS_v)) { for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1]; --(*argc); --i; } else if (IsFlag(argv[i], "help")) { PrintUsageAndExit(); } } for (auto const* flag : {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) { if (*flag != "console" && *flag != "json" && *flag != "csv") { PrintUsageAndExit(); } } if (FLAGS_benchmark_color.empty()) { PrintUsageAndExit(); } for (const auto& kv : FLAGS_benchmark_context) { AddCustomContext(kv.first, kv.second); } } int InitializeStreams() { static std::ios_base::Init init; return 0; } } // end namespace internal void Initialize(int* argc, char** argv) { internal::ParseCommandLineFlags(argc, argv); internal::LogLevel() = FLAGS_v; } void Shutdown() { delete internal::global_context; } bool ReportUnrecognizedArguments(int argc, char** argv) { for (int i = 1; i < argc; ++i) { fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], argv[i]); } return argc > 1; } } // end namespace benchmark
[ "kenneth.balslev@gmail.com" ]
kenneth.balslev@gmail.com
ef4d6bfb8ba7edac0b2713695d0a640bc9e7892a
43dfcad293ba92d3d09f1dfa070402e1c5c38e99
/PPSUM.cpp
771ce9c101768b9a912f7001b01d264d7eb78f0b
[]
no_license
pavan-2001/codechef-solutions
e3f8530928bdb8d1658d5967ac842a86cf12ef51
5f1215ee9ada4e900d04d8934c431bf05b20c449
refs/heads/master
2022-12-03T11:05:44.221416
2020-08-16T06:51:43
2020-08-16T06:51:43
287,801,517
2
0
null
null
null
null
UTF-8
C++
false
false
348
cpp
#include <iostream> using namespace std; int main() { int a; cin>>a; while(a--) { int b,n,sum=0,sum1=0; cin>>b>>n; if(b==1) { sum=((n*(n+1))/2); n=sum; } else { while(b--) { sum=((n*(n+1))/2); n=sum; } } cout<<n<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
9f73483a951cefd51b6fab8c6ea4dc3e79c4763c
584dd17425bba4f8ac816f171f947a2660d75204
/Labs/misc/Other.cpp
bc0b98b65343e7e74627ddf4c822ee377551030c
[]
no_license
Unwrittend/CS60
8052f9a385508bd4cb22361dc330249082304fb8
c790802c3d40704038cc1283317b817702612d54
refs/heads/master
2020-04-29T01:04:50.141635
2019-03-15T00:10:06
2019-03-15T00:10:06
175,718,406
0
0
null
null
null
null
UTF-8
C++
false
false
3,015
cpp
#include <iostream> #include <string> using namespace std; //DEFINED structrure struct Time{//military time, no am/pm int hour; int minute; }; struct Carpool{ string names[5]; int num_people; Time arrival; }; Carpool combineCarpool (Carpool car1, Carpool car2);//declare the function. int main() { //VARIABLE DECLARATION int num1,num2,i; Carpool car1; Carpool car2; //CODE //get first car info cout<<"Enter the information of the first car: "<<endl; cout<<"Enter the number of people: "<<endl; cin>>car1.num_people; cin.get(); for(i=0;i<car1.num_people;i++){ cout<<"Enter the name of the passenger: "<<endl; getline(cin, car1.names[i]); } cout<<"Enter the arrival hour: "<<endl; cin>>car1.arrival.hour; cout<<"Enter the arrival minute: "<<endl; cin>>car1.arrival.minute; //get second car info cout<<"Enter the information of the second car: "<<endl; cout<<"Enter the number of people: "<<endl; cin>>car2.num_people; cin.get(); for(i=0;i<car2.num_people;i++){ cout<<"Enter the name of the passenger: "<<endl; getline(cin, car2.names[i]); } cout<<"Enter the arrival hour: "<<endl; cin>>car2.arrival.hour; cout<<"Enter the arrival minute: "<<endl; cin>>car2.arrival.minute; //combine info Carpool combined; combined = combineCarpool(car1, car2); //print info cout<<"The information for the new carpool: "<<endl; cout<<"The number of people: "<<combined.num_people<<endl; cout<<"Names of each passenger: "<<endl; for(int i=0;i<combined.num_people;i++){ cout<<combined.names[i]<<endl; } cout<<"The arrival hour: "<<combined.arrival.hour<<endl; cout<<"The arrival minute: "<<combined.arrival.minute<<endl; } //-------------------- //FUNCTION CODE //-------------------- Carpool combineCarpool (Carpool car1, Carpool car2){ Carpool newpool; //find earlier time if(car1.arrival.hour<car2.arrival.hour) { newpool.arrival.hour=car1.arrival.hour; newpool.arrival.minute=car1.arrival.minute; } else if(car1.arrival.hour>car2.arrival.hour) { newpool.arrival.hour=car2.arrival.hour; newpool.arrival.minute=car2.arrival.minute; } else if(car1.arrival.hour==car2.arrival.hour) { newpool.arrival.hour=car1.arrival.hour; if(car1.arrival.minute<car2.arrival.minute) newpool.arrival.minute=car1.arrival.minute; else newpool.arrival.minute=car2.arrival.minute; } //get total names and the num_people variable if (car1.num_people + car2.num_people > 5) { cout << "Too Many People" << endl; newpool.num_people = 0; } else { int dummy_counter = 0; for(int index = 0; index < car1.num_people; index++) { newpool.names[index] = car1.names[index]; dummy_counter++; } for(int index = 0; index < car2.num_people; index++) { newpool.names[index+dummy_counter] = car2.names[index]; } newpool.num_people = car1.num_people + car2.num_people; } return newpool; } //-------------------- //--------------------
[ "cmpitterlejunk@gmail.com" ]
cmpitterlejunk@gmail.com
fec0241242a07a23a379993e003c5048df9588ff
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_WoodElevatorTopSwitch_structs.hpp
07be9c474e27003b38f060a73e24e51f560f0d79
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
415
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Basic.hpp" #include "ARKSurvivalEvolved_StructureBaseBP_classes.hpp" #include "ARKSurvivalEvolved_ShooterGame_classes.hpp" #include "ARKSurvivalEvolved_CoreUObject_classes.hpp" #include "ARKSurvivalEvolved_Engine_classes.hpp" namespace sdk { } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
1c6a23f53e34d70f5b7a4c41ad182173be0bc7cf
c7a1bbfeb7aa82f6ff0f2004bef5144013da46c9
/storewindow.cpp
5bfb7f6219d74ed93b594122575304d911064e0a
[]
no_license
tagreff/test_task_client
2f2a145e2534f5b041417d343e193687ac7acc24
9163cfdef9430cda8a71cf8dfbed8c0e89c7cf0c
refs/heads/master
2020-06-16T19:48:19.717009
2019-07-07T22:01:27
2019-07-07T22:01:27
195,684,563
0
0
null
null
null
null
UTF-8
C++
false
false
7,219
cpp
#include "storewindow.h" #include "ui_storewindow.h" #include <QtXml> #include <QFile> #include <QFileDialog> #include <QMessageBox> #include <QtWidgets> #include <QtNetwork> #include <QString> StoreWindow::StoreWindow(QWidget *parent) : QDialog(parent), ui(new Ui::StoreWindow) { ui->setupUi(this); ui->sendRequestButton->setEnabled(false); ui->resetButton->setEnabled(false); fileLoadState = false; StoreWindow::getConnectionAttributes();// Получаем адрес и порт из xml файла tcpSocket = new QTcpSocket(); // создаем новый экземпляр сокета connect(tcpSocket, &QIODevice::readyRead, this, &StoreWindow::onReadyRead); //сигнал на получение сообщения от сервера connect(tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), //сигнал для обработки ошибки подключения this, &StoreWindow::displayError); } StoreWindow::~StoreWindow() { delete ui; } void StoreWindow::on_StoreWindow_rejected() // { emit storeWindowClosed(); } void StoreWindow::getConnectionAttributes() // Получаем адрес и порт из xml файла { QDomDocument attrsFile; QFile attrs(qApp->applicationDirPath() + "/attributes.xml"); //открываем файл с портом и адресом attrsFile.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""); // задаем инструкции для обработки attrs.open(QIODevice::ReadOnly); attrsFile.setContent(&attrs); QDomNodeList fileAttributes = attrsFile.elementsByTagName("attributes"); //получаем родительские элемент адреса и порта QDomNode attribute = fileAttributes.item(0); //задаем переменную QDomNode значением первого элемента address = attribute.firstChildElement("ip").text(); //получаем адрес port = attribute.firstChildElement("port").text().toUShort();//получаем порт connectionState = false; } void StoreWindow::on_fileOpenButton_clicked() { QString filename = QFileDialog::getOpenFileName( //открываем файловый диалог this, "Выберите файл с товарами", QDir::currentPath(), "XML files (*.xml)"); if( !filename.isNull() ) { QDomDocument itemsFile; QFile file(filename);//записываем имя выбранного файла itemsFile.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""); if (!file.open(QIODevice::ReadOnly )) //обрабатываем ошибку { QMessageBox Msgbox; Msgbox.setText("Ошибка при открытии файла!"); Msgbox.exec(); } itemsFile.setContent(&file); items = itemsFile.elementsByTagName("item"); QString out; ui->listWidget->clear(); StoreWindow::clearPickedItems(); for (int i = 0; i<items.size(); i++)//обрабатываем xml файл { QDomNode item = items.item(i); out = item.firstChildElement("name").text(); itemsList = new QListWidgetItem(out, ui->listWidget); itemsList->setFlags(itemsList->flags() | Qt::ItemIsUserCheckable); itemsList->setCheckState(Qt::Unchecked); } if(!fileLoadState) //костыль, но я не знаю, как по другому исправить эту ошибку { QObject::connect(ui->listWidget, SIGNAL(itemChanged(QListWidgetItem*)), //создаем connection для элементов списка this, SLOT(highlightChecked(QListWidgetItem*))); fileLoadState = true; } file.close(); ui->sendRequestButton->setEnabled(true); //разблокируем кнопки ui->resetButton->setEnabled(true); } } void StoreWindow::highlightChecked(QListWidgetItem *item){ if(item->checkState() == Qt::Checked) { pickedItems.append(item->text());// добавляем выбранные элементы в QList qDebug() << item->text(); } else{ pickedItems.removeOne(item->text()); } } void StoreWindow::onReadyRead() { QByteArray response = tcpSocket->readAll(); //считываем данные из сокета if(response == "true"){ QMessageBox::information(this, tr("Результат запроса"), tr("Запрос принят")); ui->resetButton->setEnabled(true); } else if(response == "false") { QMessageBox::information(this, tr("Результат запроса"), tr("Запрос отклонен")); ui->sendRequestButton->setEnabled(true); } else{ qDebug() << response; } } void StoreWindow::displayError(QAbstractSocket::SocketError socketError) //обрабатываем возможные исключения при подключении к серверу { switch (socketError) { case QAbstractSocket::RemoteHostClosedError: break; case QAbstractSocket::HostNotFoundError: QMessageBox::information(this, tr("Fortune Client"), tr("The host was not found. Please check the " "host name and port settings.")); break; case QAbstractSocket::ConnectionRefusedError: QMessageBox::information(this, tr("Fortune Client"), tr("The connection was refused by the peer. " "Make sure the fortune server is running, " "and check that the host name and port " "settings are correct.")); break; default: QMessageBox::information(this, tr("Fortune Client"), tr("The following error occurred: %1.") .arg(tcpSocket->errorString())); } } void StoreWindow::on_sendRequestButton_clicked() //отправляем запрос на сервер { if(!connectionState) { tcpSocket->connectToHost(QHostAddress(address), port); connectionState = true; } QByteArray output; int num = pickedItems.length(); for(int i =0; i< num; i++) { output.append(pickedItems.at(i) + ";"); } tcpSocket->write(QByteArray(output)); //записываем строку в QByteArray output.clear(); ui->sendRequestButton->setEnabled(false); ui->resetButton->setEnabled(false); } void StoreWindow::on_resetButton_clicked() //ресет списка и кнопок { ui->listWidget->clear(); StoreWindow::clearPickedItems(); ui->sendRequestButton->setEnabled(false); ui->resetButton->setEnabled(false); } void StoreWindow::clearPickedItems() { int num = pickedItems.length(); for(int i =0; i< num; i++) { pickedItems.removeAt(i); } pickedItems.clear(); }
[ "tagreff@yandex.ru" ]
tagreff@yandex.ru
0fa7ab2ea4637617d62e71577fb879a94394cf13
69a23980bdaa200920e8384aabdab5b603beeb64
/src/Graphics/Controls/ProgressBar.cpp
6fbf61ed0bb32ad6223c613b1b838f9ecdd96aff
[]
no_license
hhawley/Bengite
c28deb8f4320e5083aed779993949780231d3bfb
67a4510eb4d8833e9a0a7cd4dbc9ca0dd93305c8
refs/heads/master
2021-05-31T08:28:16.423982
2016-03-17T01:34:55
2016-03-17T01:34:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,247
cpp
#include "Graphics/Controls/ProgressBar.h" #include "Core/Math/BMath.h" #include "Core/Objects.h" using namespace bengite::core; using namespace bengite::graphics; ProgressBar::ProgressBar(const string& name, const float& max = 100.0f) : Control(name), _showNum(false), _maxNumber(max), _currentNumber(0), _topColor((Color){0, 255, 0, 255}) { _color = (Color){255, 0, 0, 255}; } void ProgressBar::Update(const GameTime& gameTime) { } void ProgressBar::Draw(const GameTime& gameTime, SpriteBatch& spriteBatch) { DrawRectangleRec(getSize(), _color); Rectangle topSize = (Rectangle){static_cast<int>(_position.x), static_cast<int>(_position.y), static_cast<int>((_currentNumber * _size.width) / _maxNumber), _size.height}; DrawRectangleRec(topSize, _topColor); if(_showNum) { _text = Math::ftostr(_currentNumber) + "/" + Math::ftostr(_maxNumber); int size_w = MeasureText(_text.c_str(), 10); size_w = (_size.width - size_w) / 2; int size_h = (_size.height - 10) / 2; DrawText(_text.c_str(), (int)_position.x + size_w, (int)_position.y + size_h, 10, WHITE); } } bool ProgressBar::isShowingNumber() const { return _showNum; } float ProgressBar::getMaxNumber() const { return _maxNumber; } float ProgressBar::getCurrentNumber() const { return _currentNumber; } Color ProgressBar::getTopColor() const { return _topColor; } void ProgressBar::setShowingNumber(const bool& value) { _showNum = value; } void ProgressBar::setMaxNumber(const float& num) { _maxNumber = num; } void ProgressBar::setCurrentNumber(const float& num) { _currentNumber = num > _maxNumber ? _maxNumber : num < 0 ? 0 : num; } void ProgressBar::setTopColor(const Color& color) { _topColor = color; } Json::Value ProgressBar::toJson(void) const { Json::Value controlJson; controlJson["name"] = this->_name; controlJson["text"] = this->_text; controlJson["position"] = raylibJson::vector2ToJson(this->_position); controlJson["color"] = raylibJson::colorToJson(this->_color); controlJson["size"] = raylibJson::rectangleToJson(this->_size); controlJson["enabled"] = this->_enabled; controlJson["visible"] = this->_visible; controlJson["showNum"] = this->_showNum; controlJson["maxNum"] = this->_maxNumber; controlJson["currentNum"] = this->_currentNumber; controlJson["topColor"] = raylibJson::colorToJson(this->_topColor); Json::Value finalJson; finalJson["progressBar"] = controlJson; return finalJson; } void ProgressBar::fromJson(Json::Value& value) { this->_name = value.get("name", "").asString(); this->_text = value.get("text", "").asString(); this->_enabled = value.get("enabled", true).asBool(); this->_visible = value.get("visible", true).asBool(); auto v = value.get("position", -1); this->_position = raylibJson::jsonToVec2(v); v = value.get("color", -1); this->_color = raylibJson::jsonToColor(v); v = value.get("size", -1); this->_size = raylibJson::jsonToRectangle(v); this->_showNum = value.get("showNum", false).asBool(); this->_maxNumber = value.get("maxNum", 100).asInt(); this->_currentNumber = value.get("currentNum", 100).asInt(); v = value.get("topColor", -1); this->_topColor = raylibJson::jsonToColor(v); }
[ "noturnbak@hotmail.com" ]
noturnbak@hotmail.com
c529291f6143ff66eb1b87fc2fd043cf413f2f7b
908fbab5d1c478b6453d2657d0d75b5fa752ec06
/DEMO/coordinate.cpp
a4c7183c4a3b628d00ce8e5e5366f92e55121a44
[]
no_license
zbl2018/draw_tool
bba7f273feef4e9ac32d40a80934094c00e88251
688962822fd4e4b7afea527b27012f42bd3a2c60
refs/heads/master
2020-03-16T20:58:32.487093
2018-05-17T04:07:07
2018-05-17T04:07:07
132,979,731
1
0
null
null
null
null
UTF-8
C++
false
false
1,657
cpp
#include "coordinate.h" QRectF coordinate::boundingRect() const{ qreal penWidth = 1; return QRectF(-300, -300, 600, 600); } void coordinate::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget) { int width = 300; Q_UNUSED(option); //标明该参数没有使用 Q_UNUSED(widget); QPen pen; //pen.setWidth(2); //设置宽度 //pen.setBrush(Qt::blue); //设置颜色 painter->setPen(pen); //选中画笔 painter->drawLine(0,width,0,-width); //绘制y轴 painter->drawLine(-width,0,width,0); //绘制x轴 int i; for(i = -width;i<width;i+=10)//x zhou { if(i%3==0){ painter->drawLine(i,0,i,-5); //绘制x轴上的点 painter->drawText(i-9,11,QString::number(i/3)); //绘制文本 } } for(i=-width;i<width;i+=10)//y zhou { if(i%3==0&&i!=0){ painter->drawLine(0,i,5,i); //绘制y轴上的点 painter->drawText(-20,i+5,QString::number(-(i/3))); //绘制文本 } } //painter->setBrush(Qt::red); //painter->drawRect(0,0,20,20); } //void coordinate::mousePressEvent(QMouseEvent *e)//鼠标单击 //{ //int x; //int y; //QPoint p; //坐标点 //p = e->pos(); //获取鼠标位置,保存在p中 //x = p.x(); //p的x坐标值 //y = p.y(); //p的y坐标值 //QString sx,sy; //字符串变量 //sx = QString::number(x); //x转换为字符串 //sy = QString::number(y); //y转换为字符串 ////qDebug("sx:%s,sy:%sy\n",sx,sy);// //qDebug()<<sx<<sy<<endl; ////ui->lineEdit->setText(sx); //文本框显示 x值 ////ui->lineEdit_2->setText(sy); //文本框显示 y值 //}
[ "191904554@qq.com" ]
191904554@qq.com
a78924a219a63dac894d5fa2c6ce29675f05dd5f
d3f45c0dcf6a555b7aa48ee8202ef82cc7263914
/src/version.cpp
6fd73f3954cfdfd844d777023057b5a7db22ad9c
[ "MIT" ]
permissive
raskul/GUINEA
084fd1b8bfc1121a4d80f7fa9fa47f6318348240
c1a9c11164f9da0a8c4463cec5e955cbca64e2dc
refs/heads/master
2020-04-07T19:18:37.588335
2014-07-10T01:09:20
2014-07-10T01:09:20
21,674,188
0
1
null
null
null
null
UTF-8
C++
false
false
2,673
cpp
// Copyright (c) 2014 The Guinea developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both Guinead and Guinea-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Guinea"); // Client version number #define CLIENT_VERSION_SUFFIX "-guinea" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE "May 18, 2014" # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
[ "StockPix@Russells-MacBook-Air.local" ]
StockPix@Russells-MacBook-Air.local
d1b1b99b73ea1ba5515cbc27eed5e4df0cd4c906
bc997f47b4cffef395f0ce85d72f113ceb1466e6
/POI/Potyczki/pa20_dag.cpp
025df3c1455ffbfb19f9c8c6d28db300b6ff7a21
[ "LicenseRef-scancode-public-domain" ]
permissive
koosaga/olympiad
1f069dd480004c9df033b73d87004b765d77d622
fcb87b58dc8b5715b3ae2fac788bd1b7cac9bffe
refs/heads/master
2023-09-01T07:37:45.168803
2023-08-31T14:18:03
2023-08-31T14:18:03
45,691,895
246
49
null
2020-10-20T16:52:45
2015-11-06T16:01:57
C++
UTF-8
C++
false
false
705
cpp
#include <bits/stdc++.h> using namespace std; using lint = long long; using pi = array<lint, 2>; #define sz(a) ((int)(a).size()) #define all(a) (a).begin(), (a).end() int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int k; cin >> k; vector<pi> ans(100, pi{-1, -1}); // 99 - 2i = 2^i for (int i = 97; i >= 41; i -= 2) { ans[i] = {i + 1, i + 2}; ans[i + 1] = {i + 2, -1}; } vector<int> v; ans[0] = {1, -1}; for (int i = 0; i < 30; i++) { if ((k >> i) & 1) { ans[i + 1] = {99 - 2 * i, i + 2}; } else { ans[i + 1] = {i + 2, -1}; } } cout << "100\n"; for (auto &[x, y] : ans) { if (x >= 0) x++; if (y >= 0) y++; cout << x << " " << y << "\n"; } }
[ "koosaga@gmail.com" ]
koosaga@gmail.com
d3a616bb472d18aa02ebc316607ca7c38f3b2aac
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/toolchain/riscv/Darwin/riscv64-unknown-elf/include/c++/10.2.0/ext/pb_ds/detail/splay_tree_/traits.hpp
57d85516150d5d520957bc6340968e80c0b165a8
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C++
false
false
3,351
hpp
// -*- C++ -*- // Copyright (C) 2005-2020 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, 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 // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/traits.hpp * Contains an implementation for splay_tree_. */ #ifndef PB_DS_SPLAY_TREE_NODE_AND_IT_TRAITS_HPP #define PB_DS_SPLAY_TREE_NODE_AND_IT_TRAITS_HPP #include <ext/pb_ds/detail/splay_tree_/node.hpp> namespace __gnu_pbds { namespace detail { /// Specialization. /// @ingroup traits template<typename Key, typename Mapped, typename Cmp_Fn, template<typename Node_CItr, typename Node_Itr, typename Cmp_Fn_, typename _Alloc_> class Node_Update, typename _Alloc> struct tree_traits<Key, Mapped, Cmp_Fn, Node_Update, splay_tree_tag, _Alloc> : public bin_search_tree_traits<Key, Mapped, Cmp_Fn, Node_Update, splay_tree_node_< typename types_traits<Key, Mapped, _Alloc, false>::value_type, typename tree_node_metadata_dispatch<Key, Mapped, Cmp_Fn, Node_Update, _Alloc>::type, _Alloc>, _Alloc> { }; /// Specialization. /// @ingroup traits template<typename Key, class Cmp_Fn, template<typename Node_CItr, class Node_Itr, class Cmp_Fn_, typename _Alloc_> class Node_Update, typename _Alloc> struct tree_traits<Key, null_type, Cmp_Fn, Node_Update, splay_tree_tag, _Alloc> : public bin_search_tree_traits<Key, null_type, Cmp_Fn, Node_Update, splay_tree_node_< typename types_traits<Key, null_type, _Alloc, false>::value_type, typename tree_node_metadata_dispatch<Key, null_type, Cmp_Fn, Node_Update, _Alloc>::type, _Alloc>, _Alloc> { }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_SPLAY_TREE_NODE_AND_IT_TRAITS_HPP
[ "jczhang@bouffalolab.com" ]
jczhang@bouffalolab.com
57880e5d36a6565e4e7f501222550f0ba749d7a5
a22ad1404a0393e9edb2d7bd4e84c35c1fe3255b
/patterns/InvertedHalfPyramid.cpp
af16b8a10146c29a3fdb283ad3a824f9cfad50bc
[]
no_license
jaimit25/NotesPrep
33398338c2c0e2195ec3f1cd4c6e40e532a9b2a1
f2ab2d9511481df2b584826f6d679a66a28f77a4
refs/heads/master
2023-04-09T16:48:24.637590
2021-04-16T05:12:04
2021-04-16T05:12:04
345,178,641
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
// ./helloworls on terminal to run the program manually //comman+shift +b //stop code control + alt + m macos #include<iostream> using namespace std; int main(){ int height; cout<<"Enter Height Of Pyramid"<<endl; cin>>height; int i,j; for(i=height;i>0;i--){ for(j=1;j<=i;j++){ cout<< " *"; } cout<<endl; } return 0; }
[ "jaimit.jp@gmail.com" ]
jaimit.jp@gmail.com
945108a364b55eaf7c763b813aee932768d8fdcb
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/admin/cys/servmgmt/auw/dll/wizchain/statsdlg.cpp
ae9e7da48b7948d6a3d6cfba61e25eeb9d270bb4
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
25,908
cpp
// StatsDlg.cpp : Implementation of CStatusDlg #include "stdafx.h" #include "WizChain.h" #include "StatsDlg.h" // This is the thread that displays the status dialog DWORD WINAPI DialogThreadProc( LPVOID lpv ) { HRESULT hr; CStatusDlg * pSD = (CStatusDlg *)lpv; // Increment the ref count so that the object does not disappear when the user releases it hr = pSD->AddRef(); if( SUCCEEDED(hr) && pSD ) { pSD->DoModal(NULL); } // Decrement the ref count pSD->Release(); return 0; } STDMETHODIMP CStatusDlg::AddComponent( BSTR bstrComponent, long * plIndex ) { HRESULT hr = S_OK; // If the dialog is already displayed // we are not accepting new components if( m_hThread ) return E_UNEXPECTED; // Validate the arguments if( NULL == bstrComponent || NULL == plIndex ) return E_INVALIDARG; // Get a new index long lNewIndex = m_mapComponents.size(); if( m_mapComponents.find(lNewIndex) == m_mapComponents.end() ) { // Add the new component BSTR bstrNewComponent = SysAllocString(bstrComponent); if( bstrNewComponent ) { m_mapComponents.insert(COMPONENTMAP::value_type(lNewIndex, bstrNewComponent)); } else { hr = E_OUTOFMEMORY; } } else { hr = E_UNEXPECTED; // This cannot happen! } if( SUCCEEDED(hr) ) { *plIndex = lNewIndex; } return hr; } STDMETHODIMP CStatusDlg::Initialize( BSTR bstrWindowTitle, BSTR bstrWindowText, VARIANT varFlags ) { HRESULT hr = S_OK; // If the dialog is already displayed // do not allow to reinitialize if( m_hThread ) return E_UNEXPECTED; if( !bstrWindowTitle || !bstrWindowText ) return E_INVALIDARG; if( VT_I2 != V_VT(&varFlags) && VT_I4 != V_VT(&varFlags) ) return E_INVALIDARG; if( VT_I2 == V_VT(&varFlags) ) { m_lFlags = (long) varFlags.iVal; } else { m_lFlags = varFlags.lVal; } if( SUCCEEDED(hr) ) { // Initialize the common control library INITCOMMONCONTROLSEX initCommonControlsEx; initCommonControlsEx.dwSize = sizeof(initCommonControlsEx); initCommonControlsEx.dwICC = ICC_PROGRESS_CLASS | ICC_LISTVIEW_CLASSES; if( !::InitCommonControlsEx(&initCommonControlsEx) ) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if( SUCCEEDED(hr) ) { if( bstrWindowTitle ) { m_strWindowTitle = bstrWindowTitle; // Status Dialog Title } if( bstrWindowText ) { m_strWindowText = bstrWindowText; // Status Dialog Text } } return hr; } STDMETHODIMP CStatusDlg::SetStatus(long lIndex, SD_STATUS lStatus) { HRESULT hr = S_OK; BOOL bToggleActive = FALSE; COMPONENTMAP::iterator compIterator; // Validate the arguments if( (SD_STATUS_NONE > lStatus) || (SD_STATUS_RUNNING < lStatus) ) { return E_INVALIDARG; } compIterator = m_mapComponents.find(lIndex); if( compIterator == m_mapComponents.end() ) { return E_INVALIDARG; // Cannot find the component } if( IsWindow() ) { if( m_pProgressList ) { CProgressItem * pPI; compIterator = m_mapComponents.begin(); // Make sure that no component has status "running" while( compIterator != m_mapComponents.end() ) { pPI = m_pProgressList->GetProgressItem(compIterator->first); if( pPI && pPI->m_bActive ) { m_pProgressList->ToggleActive(compIterator->first); } compIterator++; } if( SD_STATUS_RUNNING == lStatus ) { m_pProgressList->ToggleActive(lIndex); // New status is "running" } else { // Update the state of the component on the Listview m_pProgressList->SetItemState(lIndex, (ItemState) lStatus); // If the component's done, update the total progress if( (lStatus == SD_STATUS_SUCCEEDED) || (lStatus == SD_STATUS_FAILED) ) { // TO DO: No need to do this, just send a message to the dialog to do that PBRANGE range; SendDlgItemMessage(IDC_PROGRESS1, PBM_GETRANGE, FALSE, (LPARAM) &range); SendDlgItemMessage(IDC_PROGRESS1, PBM_SETPOS, range.iHigh, 0); InterlockedExchangeAdd(&m_lTotalProgress, range.iHigh); } } } else { hr = E_UNEXPECTED; } if( SUCCEEDED(hr) ) { SetupButtons( ); } } else { hr = E_UNEXPECTED; } return hr; } void CStatusDlg::SetupButtons( ) { HWND hWnd = NULL; HWND hWndOK = NULL; HWND hWndCancel = NULL; CString csText; BOOL bFailed = FALSE; BSTR bstrText = NULL; USES_CONVERSION; hWndOK = GetDlgItem(IDOK); hWndCancel = GetDlgItem(IDCANCEL); if( IsWindow() && hWndOK && hWndCancel ) { if( AreAllComponentsDone(bFailed) ) { // Enable OK button ::EnableWindow(hWndOK, TRUE); // Disable Cancel button ::EnableWindow(hWndCancel, FALSE); // Default button is the Close button ::SendMessage(m_hWnd, WM_NEXTDLGCTL, (WPARAM) hWndOK, 1); // // When all components are done we will hide the progress bars to give the user // a visual clue to realize that the wizard is done. I know, that sounds stupid. // hWnd = GetDlgItem(IDC_STATIC2); // Component progress text if (NULL != hWnd) { ::ShowWindow(hWnd, SW_HIDE); } hWnd = GetDlgItem(IDC_PROGRESS1); // Component progress text if (NULL != hWnd) { ::ShowWindow(hWnd, SW_HIDE); } hWnd = GetDlgItem(IDC_STATIC3); // Overall progress text if (NULL != hWnd) { ::ShowWindow(hWnd, SW_HIDE); } hWnd = GetDlgItem(IDC_PROGRESS2); // Overall progress if (NULL != hWnd) { ::ShowWindow(hWnd, SW_HIDE); } if (FALSE == bFailed) { if (csText.LoadString(IDS_STATUS_SUCCESS)) { bstrText = T2BSTR(csText); if (NULL != bstrText) { SetStatusText(bstrText); } } } else { if (csText.LoadString(IDS_STATUS_FAIL)) { bstrText = T2BSTR(csText); if (NULL != bstrText) { SetStatusText(bstrText); } } } if (NULL != bstrText) { ::SysFreeString(bstrText); } } else { // Disable OK button ::EnableWindow( hWndOK, FALSE ); if( m_lFlags & SD_BUTTON_CANCEL ) { ::EnableWindow( hWndCancel, TRUE ); } } } } STDMETHODIMP CStatusDlg::Display( BOOL bShow ) { HRESULT hr = S_OK; if( bShow ) { if( m_hThread != NULL ) { if( !IsWindowVisible() ) // We are already on { ShowWindow(SW_SHOW); } } else { // Create a new thread which will DoModal the status dialog m_hThread = CreateThread( NULL, 0, DialogThreadProc, (void *) this, 0, NULL ); if( NULL == m_hThread ) { hr = HRESULT_FROM_WIN32(GetLastError()); } else if( m_hDisplayedEvent ) // Wait till the dialog is displayed { if( WAIT_OBJECT_0 != WaitForSingleObject(m_hDisplayedEvent, INFINITE) ) { hr = E_UNEXPECTED; } } } } else { // Will close the dialog if( m_hThread != NULL ) { EndDialog(IDCANCEL); WaitForSingleObject(m_hThread, INFINITE); } } return hr; } // The wizard writer should call this function to wait on user response // If the user has already responded: clicked OK or Cancel // then this method will return immediately STDMETHODIMP CStatusDlg::WaitForUser( ) { if( m_hThread ) { WaitForSingleObject(m_hThread, INFINITE); } return S_OK; } STDMETHODIMP CStatusDlg::get_Cancelled( BOOL *pVal ) { if( NULL == pVal ) { return E_INVALIDARG; } if( m_lFlags & SD_BUTTON_CANCEL ) { if( m_iCancelled == 0 ) { *pVal = FALSE; } else { *pVal = TRUE; } } else { *pVal = FALSE; } return S_OK; } STDMETHODIMP CStatusDlg::get_ComponentProgress( IStatusProgress** pVal ) { HRESULT hr = S_OK; if( NULL == pVal ) { return E_INVALIDARG; } if( m_lFlags & SD_PROGRESS_COMPONENT ) { // Create component progress object if( m_pComponentProgress == NULL ) { hr = CComObject<CStatusProgress>::CreateInstance(&m_pComponentProgress); if( SUCCEEDED(hr) ) { hr = m_pComponentProgress->AddRef(); } if( SUCCEEDED(hr) && IsWindow() ) { // Initialize the component progress with the progress bar handle hr = m_pComponentProgress->Initialize(this, GetDlgItem(IDC_PROGRESS1), FALSE); } } if( SUCCEEDED(hr) ) { hr = (m_pComponentProgress->QueryInterface(IID_IStatusProgress, (void **) pVal)); } } return hr; } LRESULT CStatusDlg::OnInitDialog( UINT uint, WPARAM wparam, LPARAM lparam, BOOL& bbool ) { HWND hWndText = GetDlgItem(IDC_STATIC1); HWND hWndLV = GetDlgItem(IDC_LIST2); HWND hWndCompText = GetDlgItem(IDC_STATIC2); HWND hWndCompProgress = GetDlgItem(IDC_PROGRESS1); HWND hWndOverallText = GetDlgItem(IDC_STATIC3); HWND hWndOverallProgress = GetDlgItem(IDC_PROGRESS2); HWND hWndOK = GetDlgItem(IDOK); HWND hWndCancel = GetDlgItem(IDCANCEL); LOGFONT logFont; HIMAGELIST hILSmall; HBITMAP hBitmap; HDC hDC; TEXTMETRIC tm; RECT rect; CWindow wnd; int iResizeLV = 0; int iResize = 0; // Attach to the Listview wnd.Attach(hWndLV); wnd.GetWindowRect(&rect); hDC = GetDC(); GetTextMetrics(hDC, &tm); ReleaseDC(hDC); // Check if size of the list view is OK enough to hold all the components iResizeLV = rect.bottom - rect.top - ((tm.tmHeight + 2) * (m_mapComponents.size() + 1)); // Depending on the options selected, decide whether the stus dialog will shrink or expand if( (m_lFlags & SD_PROGRESS_COMPONENT) && !(m_lFlags & SD_PROGRESS_OVERALL) ) { iResize = GetWindowLength(hWndOverallText, hWndOverallProgress); } else if( !(m_lFlags & SD_PROGRESS_COMPONENT) && (m_lFlags & SD_PROGRESS_OVERALL) ) { iResize = GetWindowLength(hWndCompText, hWndCompProgress); } else if( !(m_lFlags & SD_PROGRESS_COMPONENT) && !(m_lFlags & SD_PROGRESS_OVERALL) ) { iResize = GetWindowLength(hWndCompText, hWndOverallProgress); } // Hide component progress if necessary if( !(m_lFlags & SD_PROGRESS_COMPONENT) ) { ::ShowWindow(hWndCompText, SW_HIDE); ::ShowWindow(hWndCompProgress, SW_HIDE); } // Hide overall progress if necessary if( !(m_lFlags & SD_PROGRESS_OVERALL) ) { ::ShowWindow(hWndOverallText, SW_HIDE); ::ShowWindow(hWndOverallProgress, SW_HIDE); } if ((!(m_lFlags & SD_PROGRESS_OVERALL)) || (!(m_lFlags & SD_PROGRESS_COMPONENT))) { // We need to get rid of the space between the progress bars iResize -= GetWindowLength(hWndCompText, hWndOverallProgress) - GetWindowLength(hWndOverallText, hWndOverallProgress) - GetWindowLength(hWndCompText, hWndOverallProgress) + 4; } // Well, we may need to make LV bigger, but the dialog length could stay the same // if the user does not want component and/or overall progress if( iResizeLV < 0 ) // Will need to make the LV bigger { iResize += iResizeLV; } else { iResizeLV = 0; // We will not touch the LV } if( iResizeLV != 0 || iResize != 0 ) // We will need to do some moving and resizing { VerticalResizeWindow(m_hWnd, iResize); VerticalMoveWindow(hWndOK, iResize); VerticalMoveWindow(hWndCancel, iResize); // Location of progress bars completely depend on the resizing of the LV VerticalMoveWindow(hWndOverallText, iResizeLV); VerticalMoveWindow(hWndOverallProgress, iResizeLV); VerticalMoveWindow(hWndCompText, iResizeLV); VerticalMoveWindow(hWndCompProgress, iResizeLV); // Last, but not the least, resize the LV VerticalResizeWindow(hWndLV, iResizeLV); } if( !(m_lFlags & SD_BUTTON_CANCEL) ) // We will only have an OK button { LONG_PTR dwStyle = ::GetWindowLongPtr( m_hWnd, GWL_STYLE ); if( 0 != dwStyle ) { // Get rid of the System Menu (Close X) as well dwStyle &= ~WS_SYSMENU; ::SetWindowLongPtr( m_hWnd, GWL_STYLE, dwStyle ); } ReplaceWindow(hWndCancel, hWndOK); } // if we only have overall progress, we need to move it up // so that it replaces the component progress if( (m_lFlags & SD_PROGRESS_OVERALL) && !(m_lFlags & SD_PROGRESS_COMPONENT) ) { ReplaceWindow(hWndCompText, hWndOverallText); ReplaceWindow(hWndCompProgress, hWndOverallProgress); } // Set some style for the LV ::SendMessage(hWndLV, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_SUBITEMIMAGES); ::SendMessage(hWndLV, LVM_SETBKCOLOR, 0, (LPARAM) CLR_NONE); ::SendMessage(hWndLV, LVM_SETTEXTBKCOLOR, 0, (LPARAM) CLR_NONE); LVCOLUMN col; ZeroMemory (&col, sizeof(col)); col.mask = LVCF_WIDTH; col.cx = 500; SendMessage( hWndLV, LVM_INSERTCOLUMN, 0, (LPARAM)&col ); // Thanks to Jeffzi m_pProgressList->Attach( hWndLV ); COMPONENTMAP::iterator compIterator; compIterator = m_mapComponents.begin(); while( compIterator != m_mapComponents.end() ) { // Add each component to the LV m_pProgressList->AddItem(compIterator->second); m_pProgressList->SetItemState(compIterator->first, IS_NONE, FALSE ); compIterator++; } if( m_pComponentProgress ) { // Initialize the component progress with the progress bar handle m_pComponentProgress->Initialize( this, hWndCompProgress, FALSE ); } if (m_pOverallProgress) { // Initialize the overall progress with the progress bar handle m_pOverallProgress->Initialize( this, hWndOverallProgress, TRUE ); } // Here comes the dialog title and text SetWindowText(m_strWindowTitle.c_str()); ::SetWindowText(hWndText, m_strWindowText.c_str()); SetupButtons(); // Center the window, no Jeff this works just right if you have 2 monitors CenterWindow(); if( m_hDisplayedEvent ) { SetEvent(m_hDisplayedEvent); } return TRUE; } BOOL CStatusDlg::VerticalMoveWindow( HWND hWnd, int iResize ) { BOOL bRet; CWindow wnd; RECT rect; wnd.Attach( hWnd ); // Returns void if(wnd.GetWindowRect(&rect) ) { rect.top -= iResize; rect.bottom -= iResize; // GetWindowRect fills in RECT relative to the desktop // We need to make it relative to the dialog // as MoveWindow works that way if( ScreenToClient(&rect) ) { bRet = wnd.MoveWindow(&rect); } else { bRet = FALSE; } } else { bRet = FALSE; } return bRet; } BOOL CStatusDlg::ReplaceWindow( HWND hWndOld, HWND hWndNew ) { BOOL bRet; CWindow wnd; RECT rect; wnd.Attach(hWndOld); // Get the coordinates of the old Window if( wnd.GetWindowRect(&rect) ) { // Hide it, we are trying to replace it wnd.ShowWindow(SW_HIDE); // Attach to the new one wnd.Attach(hWndNew); // Map the coordinates and move the window on top of the old one if( ScreenToClient(&rect) ) { bRet = wnd.MoveWindow(&rect); } else { bRet = FALSE; } } else { bRet = FALSE; } return bRet; } BOOL CStatusDlg::VerticalResizeWindow( HWND hWnd, int iResize ) { CWindow wnd; RECT rect; BOOL bRet = FALSE; if( iResize ) { // Attach to the window wnd.Attach(hWnd); // Get the coordinates if( wnd.GetWindowRect(&rect) ) { rect.bottom -= iResize; // Increase the bottom if( ScreenToClient(&rect) ) { bRet = wnd.MoveWindow(&rect); // Resize } else { bRet= FALSE; } } else { bRet = FALSE; } } return bRet; } int CStatusDlg::GetWindowLength( HWND hWndTop, HWND hWndBottom ) { CWindow wnd; RECT rect; int iTop; wnd.Attach(hWndTop); if( wnd.GetWindowRect(&rect) ) { iTop = rect.top; wnd.Attach(hWndBottom); if( wnd.GetWindowRect(&rect) ) { return rect.bottom - iTop; } } return 0; } STDMETHODIMP CStatusDlg::get_OverallProgress( IStatusProgress** pVal ) { HRESULT hr = S_OK; if( NULL == pVal ) { return E_INVALIDARG; } if( m_lFlags & SD_PROGRESS_OVERALL ) { // Create component progress object if( m_pOverallProgress == NULL ) { hr = CComObject<CStatusProgress>::CreateInstance(&m_pOverallProgress); if( SUCCEEDED(hr) ) { hr = m_pOverallProgress->AddRef(); } if( SUCCEEDED(hr) && IsWindow() ) { // Initialize the overall progress with the progress bar handle hr = m_pOverallProgress->Initialize(this, GetDlgItem(IDC_PROGRESS2), TRUE); } } hr = m_pOverallProgress->QueryInterface(IID_IStatusProgress, (void **) pVal); } return hr; } BOOL CStatusDlg::AreAllComponentsDone( BOOL& bFailedComponent ) { BOOL bComponentToRun = FALSE; COMPONENTMAP::iterator compIterator = m_mapComponents.begin(); if( m_pProgressList ) { // Look for a component that's not done while( m_pProgressList && !bComponentToRun && compIterator != m_mapComponents.end() ) { CProgressItem * pPI = m_pProgressList->GetProgressItem(compIterator->first); if( NULL != pPI ) { // Is the component done? if( IS_NONE == pPI->m_eState ) { bComponentToRun = TRUE; } else if( IS_FAILED == pPI->m_eState ) { bFailedComponent = TRUE; } } else { _ASSERT( pPI ); } compIterator++; } } return !bComponentToRun; } LRESULT CStatusDlg::OnCloseCmd( WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/ ) { EndDialog(wID); return 0; } LRESULT CStatusDlg::OnCancelCmd( WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/ ) { HWND hWnd = NULL; if( 0 == m_iCancelled ) { InterlockedIncrement((LONG *) &m_iCancelled); } // Disable the Cancel button hWnd = GetDlgItem(IDCANCEL); if( hWnd && ::IsWindow(hWnd) ) { ::EnableWindow( hWnd, FALSE ); } // EndDialog(wID); // Leaving it to the component to close the dialog return 0; } LRESULT CStatusDlg::OnDrawItem( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { if( wParam == IDC_LIST2 ) { if( m_pProgressList ) { m_pProgressList->OnDrawItem( lParam ); } } return 0; } LRESULT CStatusDlg::OnMeasureItem( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { if( wParam == IDC_LIST2) { if( m_pProgressList ) { m_pProgressList->OnMeasureItem( lParam ); } } return 0; } LRESULT CStatusDlg::OnClose( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { if( m_lFlags & SD_BUTTON_CANCEL ) // Cancel button? { if( ::IsWindowEnabled( GetDlgItem(IDCANCEL) ) ) // Is it enabled? { if( 0 == m_iCancelled ) { InterlockedIncrement( (LONG*)&m_iCancelled ); } EndDialog(0); } else if( ::IsWindowEnabled( GetDlgItem(IDOK) ) ) { // it could be OK button sending WM_CLOSE or the user // As long as OK button is enabled we need to close the dialog EndDialog(1); } } else if( ::IsWindowEnabled( GetDlgItem(IDOK) ) ) { EndDialog( 1 ); } return 0; } LRESULT CStatusDlg::OnTimerProgress( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { HRESULT hr; long lPosition; if( wParam && (m_lTimer == wParam) ) // Make sure that this is for our timer { lPosition = SendDlgItemMessage(IDC_PROGRESS1, PBM_GETPOS, 0, 0); if( lPosition < m_lMaxSteps ) // Do we still have room for progress? { SendDlgItemMessage(IDC_PROGRESS1, PBM_STEPIT, 0, 0); // Step 1 SendMessage(WM_UPDATEOVERALLPROGRESS, 0, 0); // Update the overall progress } else { // There's no room to progress, we've reached the max // Let's kill the timer SendMessage(WM_KILLTIMER, 0); } } return 0; } LRESULT CStatusDlg::OnUpdateOverallProgress( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { long lPosition = 0; if( m_lFlags & SD_PROGRESS_COMPONENT ) // Make sure that there's a component progress { lPosition = SendDlgItemMessage(IDC_PROGRESS1, PBM_GETPOS, 0, 0); // Update the overall progress SendDlgItemMessage(IDC_PROGRESS2, PBM_SETPOS, m_lTotalProgress + lPosition, 0); } return 0; } LRESULT CStatusDlg::OnStartTimer( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { if( !m_lTimer ) // There might be a timer already { m_lTimer = SetTimer(SD_TIMER_ID, wParam * 500); // Create a timer m_lMaxSteps = (long) lParam; // Max. not to exceed for the progress bar } return 0; } LRESULT CStatusDlg::OnKillTimer( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) { if( m_lTimer ) // Is there a timer? { KillTimer( m_lTimer ); // Kill it m_lTimer = 0; m_lMaxSteps = 0; } return 0; } STDMETHODIMP CStatusDlg::SetStatusText(BSTR bstrText) { if( !bstrText ) return E_POINTER; HRESULT hr = S_OK; HWND hWnd = GetDlgItem(IDC_STATIC1); if( hWnd && ::IsWindow(hWnd) ) { if( 0 == ::SetWindowText(hWnd, OLE2T(bstrText)) ) { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { hr = E_FAIL; } return hr; } STDMETHODIMP CStatusDlg::DisplayError(BSTR bstrError, BSTR bstrTitle, DWORD dwFlags, long * pRet) { if( !bstrError || !bstrTitle || !pRet ) return E_POINTER; HRESULT hr = S_OK; *pRet = MessageBox( bstrError, bstrTitle, dwFlags ); if( 0 == *pRet ) { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
478100c3ca955df5fbfabafe0fe0b25bf092ffbe
973182ff08776327adc6c70154fc935c19b8fff3
/junk/string/lcs.cpp
649e043fd803e29411bd635ba51c8742454829df
[]
no_license
arhuaco/junkcode
cecf067551b76d5d8471c2b7c788064d4705b923
4b5dd1560042ef21e7fa4b1b398de8b172693de7
refs/heads/master
2023-05-25T13:51:19.927997
2023-05-16T11:50:30
2023-05-16T11:50:30
3,691,986
7
3
null
2016-08-09T16:03:20
2012-03-12T04:05:34
C
UTF-8
C++
false
false
1,799
cpp
#include <iostream> #include <string> #include <map> // http://www.topcoder.com/tc?module=Static&d1=features&d2=040104 using namespace std; /* Naive version, this one is exponential! */ string LCS(string S, string T) { if (S.size() == 0 || T.size() == 0) return ""; if (S[0] == T[0]) return S[0] + LCS(S.substr(1, S.size() - 1), T.substr(1, T.size() - 1)); string s1 = LCS(S.substr(1, S.size() - 1), T); string s2 = LCS(S, T.substr(1, T.size() - 1)); if (s1.size() > s2.size()) return s1; return s2; } /* this use memoization */ string LCSMEMO(string S, string T, map < pair<string, string> , string > &memo) { string LCS2(string S, string T, map < pair<string, string> , string > &memo); if (S.size() == 0 || T.size() == 0) return ""; pair<string, string> idx = make_pair(S,T); map < pair<string, string> , string >::iterator it = memo.find(idx); if (it != memo.end()) return it->second; string ret = LCS2(S, T, memo); memo[idx] = ret; cerr << S << ", " << T << " => " << ret << endl; return ret; } string LCS2(string S, string T, map < pair<string, string> , string > &memo) { if (S.size() == 0 || T.size() == 0) return ""; if (S[0] == T[0]) return S[0] + LCSMEMO(S.substr(1, S.size() - 1), T.substr(1, T.size() - 1), memo); string s1 = LCSMEMO(S.substr(1, S.size() - 1), T, memo); string s2 = LCSMEMO(S, T.substr(1, T.size() - 1), memo); if (s1.size() > s2.size()) return s1; return s2; } string LCSMEMO_MAIN(string S, string T) { map < pair<string, string> , string > memo; return LCS2(S, T, memo); } int main(int argc, char *argv[]) { if (argc != 3) { cerr << "enter 2 strings" << endl; return 1; } cerr << "LCS:" << LCSMEMO_MAIN(argv[1], argv[2]) << endl; return 0; }
[ "nelsoneci@gmail.com" ]
nelsoneci@gmail.com
1b9254a0987003b3546b0639827ef62d01e15259
ff1d41ec27a33a43920243154021208cf1b27abe
/Homework/Assignment_3/Gaddis_8thEd_Chap4_Prob1_MinMaxNumber/main.cpp
08cdb63cc8543164302cebe7a736fb6d7541c0ac
[]
no_license
yhencay/CayShienne_CSC5_40107
5831c8f33ced6749abec818f7d8d85415bf7dc7e
40324827ac13cf9634b7a9b7eddec8dadd03a1c6
refs/heads/master
2021-01-13T13:04:43.065467
2017-02-12T02:18:27
2017-02-12T02:18:27
78,146,381
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
cpp
/* * File: main.cpp * Author: Shienne Cay * Created on January 12, 2017, 12:57 PM * Purpose: Homework identifying bigger/smaller number in two user input * Problem: Write a program that asks the user to enter two numbers. The * program should use the conditional operator to determine which number is the * smaller and which is the larger. */ //System Libraries #include <iostream> #include <iomanip> using namespace std; //User Libraries //Global Constants //Such as PI, Vc, -> Math/Science values //as well as conversions from one system of measurements //to another //Function Prototypes //Executable code begins here! Always begins in Main int main(int argc, char** argv) { //Declare Variables float num1, //Input first number num2; //Input second number //Input Values cout<<"Let's compare two different numbers and see which is "<<endl <<"smaller and bigger!"<<endl<<endl; cout<<"Input first number: "; cin>>num1; cout<<"Input second number: "; cin>>num2; cout<<endl<<fixed<<setprecision(2); //Process by mapping inputs to outputs //& Output Values if (num1>num2) cout<<num1<<" is larger than "<<num2<<endl <<num2<<" is smaller than "<<num1<<endl; else if(num2>num1) cout<<num2<<" is larger than "<<num1<<endl <<num1<<" is smaller than "<<num2<<endl; else if(num2==num1) cout<<num1<<" and "<<num2<<" are the same numbers!"<<endl; else cout<<"Do it again!"<<endl; //Exit stage right! - This is the 'return 0' call return 0; }
[ "yhencay@yahoo.com.ph" ]
yhencay@yahoo.com.ph
47e372d38129d1a93f815e692b9b27c1a5df3a25
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/orbsvcs/orbsvcs/Event/EC_ProxyConsumer.inl
fce2b690b8cf60ee3e35c758338563ed0a8302c6
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop", "Apache-2.0" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
1,579
inl
// -*- C++ -*- TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE CORBA::Boolean TAO_EC_ProxyPushConsumer::is_connected_i (void) const { return this->connected_; } ACE_INLINE CORBA::Boolean TAO_EC_ProxyPushConsumer::is_connected (void) const { ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, false); return this->is_connected_i (); } ACE_INLINE RtecEventComm::PushSupplier_ptr TAO_EC_ProxyPushConsumer::supplier (void) const { ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0); return RtecEventComm::PushSupplier::_duplicate (this->supplier_.in ()); } ACE_INLINE void TAO_EC_ProxyPushConsumer::supplier_i (RtecEventComm::PushSupplier_ptr supplier) { this->supplier_ = supplier; } ACE_INLINE void TAO_EC_ProxyPushConsumer::supplier (RtecEventComm::PushSupplier_ptr supplier) { ACE_GUARD (ACE_Lock, ace_mon, *this->lock_); this->supplier_i (supplier); } ACE_INLINE const RtecEventChannelAdmin::SupplierQOS& TAO_EC_ProxyPushConsumer::publications (void) const { // @@ TODO There should some way to signal errors here. ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, this->qos_); return this->qos_; } ACE_INLINE const RtecEventChannelAdmin::SupplierQOS& TAO_EC_ProxyPushConsumer::publications_i (void) const { return this->qos_; } ACE_INLINE TAO_EC_Supplier_Filter * TAO_EC_ProxyPushConsumer::filter_i (void) const { return this->filter_; } // **************************************************************** ACE_INLINE bool TAO_EC_ProxyPushConsumer_Guard::locked (void) const { return this->locked_; } TAO_END_VERSIONED_NAMESPACE_DECL
[ "lihuibin705@163.com" ]
lihuibin705@163.com
a5f0ee9ac326a8ccb517ed3d486942afa1efcb6d
866acbb0eed58ec6bbefa42b0e51c51de6c55d28
/Rocmop/External/mesquite_0_9_5/includeLinks/TerminationCriterion.hpp
91ed8be4d74e913f53cc40c701fbc8656b35fae2
[ "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
metorm/Rocstar
0a96499fda3e14d073b365d9fa90d000839eabd3
5075e33131faa50919c15e08d2808bbeb576350e
refs/heads/master
2020-04-11T09:44:37.728497
2019-04-02T16:30:58
2019-04-02T16:30:58
59,928,027
0
0
NOASSERTION
2019-05-08T02:55:57
2016-05-29T05:32:35
FORTRAN
UTF-8
C++
false
false
39
hpp
../src/Control/TerminationCriterion.hpp
[ "msafdari@illinoisrocstar.com" ]
msafdari@illinoisrocstar.com
2bfa55b49262e86096c07a40889b1c26e5999e15
f1c01a3b5b35b59887bf326b0e2b317510deef83
/SDK/SoT_BP_BountyRewardSkull_Legendary+_Desc_classes.hpp
34daaaf9db2b81cca53d6440beffc6b272c4da9e
[]
no_license
codahq/SoT-SDK
0e4711e78a01f33144acf638202d63f573fa78eb
0e6054dddb01a83c0c1f3ed3e6cdad5b34b9f094
refs/heads/master
2023-03-02T05:00:26.296260
2021-01-29T13:03:35
2021-01-29T13:03:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
812
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_BountyRewardSkull_Legendary+_Desc_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_BountyRewardSkull_Legendary+_Desc.BP_BountyRewardSkull_Legendary+_Desc_C // 0x0000 (0x0130 - 0x0130) class UBP_BountyRewardSkull_Legendary__Desc_C : public UBootyItemDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_BountyRewardSkull_Legendary+_Desc.BP_BountyRewardSkull_Legendary+_Desc_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
fbf077256d1e0c306aa183070f9abe70171fea6f
3bfe6ec77189501d994a3b3bde47a4333be0cd6b
/Insertion.cpp
65f266640bfb79f2aa710e8dc2fa94e219a593b4
[]
no_license
PorterDalton1/SortingAlgorithms
92b91be5f9472edf84b9be9711e07c9bfbb3eaff
211a5cebba49b6e8a8f95163d6284804490cd550
refs/heads/master
2020-12-01T03:53:38.925607
2020-01-01T04:02:11
2020-01-01T04:02:11
230,551,903
0
0
null
null
null
null
UTF-8
C++
false
false
776
cpp
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream myFile; string data; int lyst[100000]; int counter; int tmp; myFile.open("randomRepeat.txt"); counter = 0; while (myFile >> data) { lyst[counter] = stoi(data); counter += 1; } for (int i = 1; i < counter; i++) { for (int e = i; e > 0; e--) { if (lyst[e] < lyst[e - 1]) { tmp = lyst[e]; lyst[e] = lyst[e-1]; lyst[e-1] = tmp; } else { break; } } } for (int z = 0; z < counter; z++) { cout << lyst[z] << endl; } return 0; }
[ "porter.dalton2@gmail.com" ]
porter.dalton2@gmail.com
51a7860f26912f2ed5f4faaae0163468e71b8eaa
084454708583f973177dd8afc3ed1a3d87f42470
/2022 ACM-ICPC Vietnam Northern Provincial Programming Contest/D.cpp
8ba5406d1072ea11aa943a2b373819bf365a5484
[]
no_license
truongcongthanh2000/TrainACM-ICPC-OLP
53b0ac9de5c7f7794969bbf4f0849549357990cb
6f5ebc7ef65ca26a332c1f69e25989f2cbe379f4
refs/heads/master
2022-12-12T05:53:40.785634
2022-12-10T09:28:09
2022-12-10T09:28:09
233,577,493
62
26
null
null
null
null
UTF-8
C++
false
false
2,288
cpp
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; #define INP "input" #define OUT "output" /* some template */ template <typename T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& a) { out << (int)a.size() << '\n'; for (const auto& v : a) out << v << ' '; out << endl; return out; } template <typename T> std::ostream& operator<<(std::ostream& out, const std::vector<vector<T> >& a) { out << (int)a.size() << '\n'; for (const auto& v : a) { for (const auto& value : v) out << value << ' '; out << endl; } return out; } template <typename T> std::istream& operator>>(std::istream& is, std::vector<T>& v) { for (auto& x : v) is >> x; return is; } /* end template */ const long long INF_LL = 1e18; const int INF = 1e9 + 100; const long double EPS = 1e-6; const int BLOCK = 550; const int dx[4] = {-1, 0, 1, 0}; const int dy[4] = {0, 1, 0, -1}; void open_file() { #ifdef THEMIS freopen(INP ".txt", "r", stdin); freopen(OUT ".txt", "w", stdout); #endif // THEMIS } const int maxN = 1e6 + 100; const int MOD = 1e9 + 7; void sol() { int y; cin >> y; if (y == 1) { cout << 0; return; } vector<int> fact = []() { vector<int> fact(10, 1); for (int i = 1; i < 10; ++i) fact[i] = fact[i - 1] * i; return fact; }(); vector<int> cnt(10, 0); for (int i = 9; i >= 1; --i) { cnt[i] = y / fact[i]; y -= cnt[i] * fact[i]; } string res = ""; for (int i = 0; i < 10; ++i) { res += string(cnt[i], i + '0'); } if (cnt[0]) swap(res[0], res[cnt[0]]); cout << res << '\n'; } void solve() { clock_t start, end; start = clock(); int T = 1; // cin >> T; int TestCase = 0; while (T--) { TestCase += 1; cerr << "Processing test = " << TestCase << '\n'; // cout << "Case #" << TestCase << ": "; sol(); // if (T) cout << '\n'; } end = clock(); cerr << "Time = " << (double)(end - start) / (double)CLOCKS_PER_SEC << '\n'; } int main(int argc, char* argv[]) { // srand(time(nullptr)); ios_base::sync_with_stdio(0); cin.tie(nullptr); cout.tie(nullptr); open_file(); solve(); return 0; }
[ "truongcongthanh2000@gmail.com" ]
truongcongthanh2000@gmail.com
51ac84377acaa1d25af7f7e819fcf8eff8cbb1af
64d401b998d689d9c937988c5ad8badaffeb29ed
/services/identity/identity_service.h
b2fd9c796c6e7c4dfea42859103844c08f8a68bb
[ "BSD-3-Clause" ]
permissive
Snger/chromium
77c1ae991b5d92d830d83e2bbd6890673d98c963
23c9664fcc2ffd6bdcffbca5355ba4cd083f7060
refs/heads/master
2023-02-26T16:06:16.690161
2017-03-30T03:45:22
2017-03-30T03:45:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_IDENTITY_IDENTITY_SERVICE_H_ #define SERVICES_IDENTITY_IDENTITY_SERVICE_H_ #include "services/identity/public/interfaces/identity_manager.mojom.h" #include "services/service_manager/public/cpp/interface_factory.h" #include "services/service_manager/public/cpp/service.h" class SigninManagerBase; namespace identity { class IdentityService : public service_manager::Service, public service_manager::InterfaceFactory<mojom::IdentityManager> { public: IdentityService(SigninManagerBase* signin_manager); ~IdentityService() override; private: // |Service| override: void OnStart() override; bool OnConnect(const service_manager::ServiceInfo& remote_info, service_manager::InterfaceRegistry* registry) override; // InterfaceFactory<mojom::IdentityManager>: void Create(const service_manager::Identity& remote_identity, mojom::IdentityManagerRequest request) override; SigninManagerBase* signin_manager_; DISALLOW_COPY_AND_ASSIGN(IdentityService); }; } // namespace identity #endif // SERVICES_IDENTITY_IDENTITY_SERVICE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1e8026288b89a9b56d68666a523ea8edfd221a6f
09d9b50726c2e5cdc768c57930a84edc984d2a6e
/CODEFORCES/CONTEST PROBLEMS/codeforces_241_A.cpp
3eee884e1b84283a55afec49b6e892accd9aa661
[]
no_license
omar-sharif03/Competitive-Programming
86b4e99f16a6711131d503eb8e99889daa92b53d
c8bc015af372eeb328c572d16038d0d0aac6bb6a
refs/heads/master
2022-11-15T08:22:08.474648
2020-07-15T12:30:53
2020-07-15T12:30:53
279,789,803
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
cpp
#include<bits/stdc++.h> using namespace std; long high=2000000000; long low=-2000000000; int main() { string s,s1; long n,m,flag=0; cin>>m; while(m--){ cin>>s>>n>>s1; if(flag==0){ if(s==">"){ if(s1=="Y"&&low<n+1) low=n+1; else if(s1=="N"&&n<high) high=n; } else if(s=="<"){ if(s1=="Y"&&high>n-1) high=n-1; else if(s1=="N"&&n>low) low=n; } else if(s==">="){ if(s1=="Y"&&n>=low) low=n; else if (s1=="N"&&high>n) high=n-1; } else if(s=="<="){ if(s1=="Y"&&n<=high) high=n; else if(s1=="N"&&n>low) low=n+1; } } if(high<low) flag=1; // cout<<low<<' '<<high<<endl; } if(flag==1) cout<<"Impossible"<<endl; else cout<<high<<endl; }
[ "omar.sharif1303@gmail.com" ]
omar.sharif1303@gmail.com
2278216b9a2567063a46aab63718ae748582cb6c
c56012edcb3550317ace8943b01f4b5f46476d16
/no_cache/client.h
847017e452dbc4dbd88de8abf094ec85d1a1f8b3
[ "MIT" ]
permissive
cerww/cpp_discord_api
8d27dc94f03014a44db975f491d20759547bc8bf
3989b9e3fdcceb6823fb5df935ef38e3f7cb350e
refs/heads/master
2021-06-12T11:49:40.180426
2021-05-28T10:40:12
2021-05-28T10:40:12
128,608,135
7
0
null
null
null
null
UTF-8
C++
false
false
7,850
h
#pragma once #include "snowflake.h" #include "intents.h" #include <boost/asio.hpp> #include <variant> #include "internal_shard.h" #include "unavailable_guild.h" #include "guild_member_update.h" #include "events.h" namespace cacheless { enum class token_type { BOT, BEARER }; static constexpr auto nothing = [](auto&&...) {};//so i don't get std::bad_function struct client { explicit client(int = 1, intents = intent::ALL); explicit client(boost::asio::io_context&, intents = intent::ALL); client(client&&) = delete; client(const client&) = delete; client& operator=(client&&) = delete; client& operator=(const client&) = delete; virtual ~client() = default; virtual void run(); void set_token(std::string token, token_type type = token_type::BOT); //void set_up_request(boost::beast::http::request<boost::beast::http::string_body>& req) const; std::string_view token() const { return m_token; } std::string_view auth_token() const { return m_authToken; } size_t num_shards() const noexcept { return m_num_shards; } std::optional<std::function<void(events::guild_message_create, shard&)>> on_guild_text_msg; std::optional<std::function<void(events::dm_message_create, shard&)>> on_dm_msg; std::optional<std::function<void(events::text_channel_create, shard&)>> on_guild_text_channel_create; std::optional<std::function<void(events::channel_catagory_create, shard&)>> on_guild_channel_catagory_create; std::optional<std::function<void(events::voice_channel_create, shard&)>> on_guild_voice_channel_create; std::optional<std::function<void(events::dm_channel_create, shard&)>> on_dm_channel_create; std::optional<std::function<void(events::text_channel_update, shard&)>> on_guild_text_channel_update; std::optional<std::function<void(events::dm_channel_update, shard&)>> on_dm_channel_update; std::optional<std::function<void(events::voice_channel_update, shard&)>> on_guild_voice_channel_update; std::optional<std::function<void(events::channel_catagory_update, shard&)>> on_guild_channel_catagory_update; std::optional<std::function<void(events::text_channel_delete, shard&)>> on_guild_text_channel_delete; std::optional<std::function<void(events::dm_channel_delete, shard&)>> on_dm_channel_delete; std::optional<std::function<void(events::voice_channel_delete, shard&)>> on_guild_voice_channel_delete; std::optional<std::function<void(events::channel_catagory_delete, shard&)>> on_guild_channel_catagory_delete; std::optional<std::function<void(events::guild_member_add, shard&)>> on_guild_member_add; std::optional<std::function<void(events::guild_member_remove, shard&)>> on_guild_member_remove; std::optional<std::function<void(events::guild_member_update, shard&)>> on_guild_member_update; std::optional<std::function<void(events::guild_members_chunk, shard&)>> on_guild_member_chunk; std::optional<std::function<void(events::guild_update, shard&)>> on_guild_update; std::optional<std::function<void(events::guild_delete, shard&)>> on_guild_remove; std::optional<std::function<void(events::guild_ban_add, shard&)>> on_ban_add; std::optional<std::function<void(events::guild_ban_remove, shard&)>> on_ban_remove; std::optional<std::function<void(events::guild_role_create, shard&)>> on_role_create; std::optional<std::function<void(events::guild_role_update, shard&)>> on_role_update; std::optional<std::function<void(events::guild_role_delete, shard&)>> on_role_delete; std::optional<std::function<void(events::dm_message_update, shard&)>> on_dm_msg_update; std::optional<std::function<void(events::guild_message_update, shard&)>> on_guild_msg_update; std::optional<std::function<void(events::dm_message_delete, shard&)>> on_dm_msg_delete; std::optional<std::function<void(events::guild_message_delete, shard&)>> on_guild_msg_delete; std::optional<std::function<void(events::guild_typing_start, shard&)>> on_guild_typing_start; std::optional<std::function<void(events::dm_typing_start, shard&)>> on_dm_typing_start; std::optional<std::function<void(events::guild_message_reaction_add, shard&)>> on_guild_reaction_add; std::optional<std::function<void(events::dm_message_reaction_add, shard&)>> on_dm_reaction_add; std::optional<std::function<void(events::guild_message_reaction_remove, shard&)>> on_guild_reaction_remove; std::optional<std::function<void(events::dm_message_reaction_remove, shard&)>> on_dm_reaction_remove; std::optional<std::function<void(events::guild_message_reaction_remove_all, shard&)>> on_guild_reaction_remove_all; std::optional<std::function<void(events::dm_message_reaction_remove_all, shard&)>> on_dm_reaction_remove_all; std::optional<std::function<void(events::presence_update_event, shard&)>> on_presence_update; std::optional<std::function<void(events::guild_create, shard&)>> on_guild_ready; std::optional<std::function<void(events::guild_message_delete_bulk, shard&)>> on_message_bulk_delete; std::optional<std::function<void(events::dm_message_delete_bulk, shard&)>> on_dm_message_bulk_delete; std::optional<std::function<void(shard&)>> on_ready = nothing; std::optional<std::function<void(events::guild_emoji_update, shard&)>> on_emoji_update; void stop(); virtual void rate_limit_global(std::chrono::system_clock::time_point); boost::asio::io_context& context() { if (std::holds_alternative<boost::asio::io_context>(m_ioc)) { return std::get<boost::asio::io_context>(m_ioc); } else { return *std::get<boost::asio::io_context*>(m_ioc); } } virtual std::chrono::steady_clock::time_point get_time_point_for_identifying() { //use mutex or atomic? std::lock_guard lock(m_identify_mut); //5.1s to account for some random delay that might happen? m_last_identify = std::max(std::chrono::steady_clock::now(), m_last_identify + std::chrono::milliseconds(5100)); return m_last_identify; } virtual void queue_to_identify(internal_shard& s) { std::lock_guard lock(m_identify_mut); if (m_no_one_is_identifying) { m_no_one_is_identifying = false; auto timer = std::make_unique<boost::asio::steady_timer>(context()); timer->expires_at(m_last_identify + 5s); timer->async_wait([pin = std::move(timer), s_ = &s](auto ec) { if (ec) {} else { (void)s_->send_identity(); } }); } else { m_identifying_stack.push_back(&s); } } virtual void notify_identified() { std::lock_guard lock(m_identify_mut); m_last_identify = std::chrono::steady_clock::now(); if (!m_identifying_stack.empty()) { const auto next = m_identifying_stack.back(); m_identifying_stack.pop_back(); auto timer = std::make_unique<boost::asio::steady_timer>(context()); timer->expires_at(m_last_identify + 5s); timer->async_wait([pin = std::move(timer), s_ = next](auto ec) { if (ec) {} else { (void)s_->send_identity(); } }); } else { m_no_one_is_identifying = true; } } virtual void do_gateway_stuff(); client& set_shards(size_t s) { assert(s > 0); m_num_shards = s; return *this; } protected: void m_getGateway(); std::chrono::system_clock::time_point m_last_global_rate_limit = std::chrono::system_clock::now(); //1 identify every 5s, -6s is so we don't wait 5s for the first one std::chrono::steady_clock::time_point m_last_identify = std::chrono::steady_clock::now() - std::chrono::seconds(6); std::mutex m_identify_mut; bool m_no_one_is_identifying = true; std::vector<internal_shard*> m_identifying_stack; intents m_intents = {}; std::string m_endpoint; std::string m_authToken; std::string m_gateway = ""s; size_t m_num_shards = 0; std::string m_token = ""; // std::mutex m_global_rate_limit_mut; std::mutex m_shard_mut; std::vector<std::unique_ptr<internal_shard>> m_shards; std::vector<std::thread> m_threads; std::variant<boost::asio::io_context, boost::asio::io_context*> m_ioc{}; }; }
[ "calebtran1@hotmail.com" ]
calebtran1@hotmail.com
d2d3c06f0a8838d3695b7110d6d30c3462db2bd9
67f38a31a770e029209fd3a78ef093c885c270e7
/light/spotlight.hpp
8ecadada71682370b5614c54195c3c252489b31d
[]
no_license
Zackere/Sculptor
f95b6dfa56bcc51934fca8ff1efcc5f72c648e5e
ff699cce064b8d8ea2a2a6ace220d5e574a694b3
refs/heads/master
2020-12-08T07:43:07.045093
2020-03-02T12:09:32
2020-03-02T12:09:32
232,927,738
0
0
null
2020-01-26T02:40:58
2020-01-09T23:42:08
C++
UTF-8
C++
false
false
748
hpp
// Copyright 2020 Wojciech Replin. All rights reserved. #pragma once #include <glm/glm.hpp> #include "light_base.hpp" namespace Sculptor { class ShaderProgramBase; class Spotlight : public LightBase { public: Spotlight(glm::vec3 ambient, glm::vec3 diffuse, glm::vec3 specular, glm::vec3 position, glm::vec3 look_target, glm::vec2 cutoff_); ~Spotlight() override = default; void LoadIntoShader(ShaderProgramBase* shader) override; void LookAt(glm::vec3 target); void SetPosition(glm::vec3 pos) override; private: static constexpr auto kClassName = "SculptorSpotlight"; glm::vec3 position_; glm::vec3 look_target_; glm::vec2 cutoff_; }; } // namespace Sculptor
[ "wo1001@wp.pl" ]
wo1001@wp.pl
438ad6385e0640466f3f002f788aa3efa117e74a
3935ac1e3bd8958e987b44b366f3c17376d6c766
/camuso 1191 Distruttori (good bad)/src/bad.h
a4b3dfacb005102b0f344964901f748df26bbb2e
[]
no_license
mircocrit/Cpp-workspace-camuso
0f2dc9231fd52b63cea688fa9702084071993c61
fe1928a0f4718880d53b4acbf3bd832df2ae9713
refs/heads/master
2020-05-19T13:29:31.944404
2019-05-05T15:03:06
2019-05-05T15:03:06
185,040,544
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
#ifndef BAD_H_ #define BAD_H_ #include <iostream> #include <stdexcept> #include <memory> #include "solleva_eccezione.h" using namespace std; class bad { public: bad(){ cout << "costruttore bad\n"; system("pause"); a = new int[100000000]; system("pause"); b = new solleva_eccezione(); } ~bad() { cout << "distruttore bad\n"; system("pause"); delete a; } private: int * a; solleva_eccezione *b; }; #endif /* BAD_H_ */
[ "Mirco@DESKTOP-A55DTAV" ]
Mirco@DESKTOP-A55DTAV
b4da83b31b37c7a3543f6d588c2f01576dcb2ba5
ca905b1f22a3c06ae243230348813deeb7810b42
/src/bboy/base/errno.h
38699f9ad1c8a0e170eadd802300a06649571da2
[]
no_license
wqx081/bboy
e190a0b92266e5c1efcbdac42103476834bb203e
b8fe208754aff37767799c3d9be4c81f35b03987
refs/heads/master
2021-01-21T11:16:23.126136
2017-03-04T05:56:56
2017-03-04T05:56:56
83,547,463
0
0
null
null
null
null
UTF-8
C++
false
false
334
h
#ifndef BBOY_BASE_ERRNO_H_ #define BBOY_BASE_ERRNO_H_ #include <string> namespace bb { void ErrnoToCString(int err, char* buf, size_t buf_len); inline static std::string ErrnoToString(int err) { char buf[512]; ErrnoToCString(err, buf, sizeof(buf)); return std::string(buf); } } // namespace bb #endif // BBOY_BASE_ERRNO_H_
[ "wangqx@mpreader.com" ]
wangqx@mpreader.com
ca9402c3a2808fc08648cdb162469657806f7ad9
dc0b575c79487a0a6a2ec6cdb7d6708000287de2
/AnimatedSprite/AnimatedSprite/Game.cpp
3c95b2b769102854e1b321c356f9f8fdb55c824f
[]
no_license
FMock/SDL-OpenGL-Projects
cb1dd74473f8441c18cbe0cf36af51d5a3364d9d
ce070a4f940d1103de9510125da1a32229927fec
refs/heads/master
2020-05-01T12:35:01.607925
2019-05-03T02:23:51
2019-05-03T02:23:51
177,469,598
0
0
null
null
null
null
UTF-8
C++
false
false
5,165
cpp
#include "Game.h" Game::Game() :window(nullptr) , glContext(nullptr) , ticksCount(0) , mIsRunning(true) {} Game::~Game() { ptrAnimationInfo.reset(); } // Initialize the game bool Game::Initialize() { //Use OpenGL 3.1 core SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // Initialize SDL. if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Could not initialize SDL. ErrorCode=%s\n", SDL_GetError()); return 1; } // Create the window and OpenGL context. SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); //SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, //... //SDL_WINDOW_OPENGL); window = SDL_CreateWindow( "AnimatedSprite Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); if (!window) { fprintf(stderr, "Could not create window. ErrorCode=%s\n", SDL_GetError()); SDL_Quit(); return 1; //return false } // create openGL context glContext = SDL_GL_CreateContext(window); if (glContext == NULL) { // Display error message printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError()); return false; } // Initialize glew and make sure we have a recent version of OpenGL. GLenum glewError = glewInit(); if (glewError != GLEW_OK) { fprintf(stderr, "Could not initialize glew. ErrorCode=%s\n", glewGetErrorString(glewError)); SDL_Quit(); return 1; } if (GLEW_VERSION_2_0) { fprintf(stderr, "OpenGL 2.0 or greater supported: Version=%s\n", glGetString(GL_VERSION)); } else { fprintf(stderr, "OpenGL max supported version is too low.\n"); SDL_Quit(); return 1; } // Setup OpenGL state. glViewport(0, 0, 800, 600); glMatrixMode(GL_PROJECTION); glOrtho(0, 800, 600, 0, 0, 100); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Create AnimationInfo object MoveableSprites or AnimatedSprites can reference ptrAnimationInfo = std::make_shared<AnimationInfo>("config/.anim_config", "config/.animations"); /* Each level of game will create various amount and variety of sprites (game objects)*/ //sprite = MoveableSprite(glTexImageTGAFile("images/magikarp.tga"), 44, 55, 100.0f, 100.0f, "fish"); sprite = MoveableSprite(44, 55, 100.0f, 100.0f, ptrAnimationInfo, "fish"); //sprite3 = AnimatedSprite(40.0f, 400.0f, ptrAnimationInfo, "explosion"); //sprite3 = AnimatedSprite(40.0f, 400.0f, ptrAnimationInfo, "dwarf"); sprite3 = AnimatedSprite(100.0f, 10.0f, ptrAnimationInfo, "girl"); return true; } // Runs the game loop until the game is over void Game::RunLoop() { while (mIsRunning) { ProcessInput(); UpdateGame(); GenerateOutput(); } } // Below are helper functions for the game loop void Game::ProcessInput() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type){ // If we get an SDL_QUIT event, end loop case SDL_QUIT: mIsRunning = false; break; } } // Get state of keyboard const Uint8* state = SDL_GetKeyboardState(NULL); // If escape is pressed, also end loop if (state[SDL_SCANCODE_ESCAPE]) { mIsRunning = false; } else if (state[SDL_SCANCODE_LEFT]) { sprite.moveLeft(); } else if (state[SDL_SCANCODE_RIGHT]) { sprite.moveRight(); } else if (state[SDL_SCANCODE_UP]) { sprite.moveUp(); } else if (state[SDL_SCANCODE_DOWN]) { sprite.moveDown(); } else if (state[SDL_SCANCODE_D]) { sprite3.changeAnimation(5); sprite3.moveRight(); } else if (state[SDL_SCANCODE_A]) { sprite3.changeAnimation(4); sprite3.moveLeft(); } else if (state[SDL_SCANCODE_W]) { sprite3.changeAnimation(3); sprite3.moveUp(); } else if (state[SDL_SCANCODE_S]) { sprite3.changeAnimation(2); sprite3.moveDown(); } else { sprite.stop(); sprite3.stop(); sprite3.changeAnimation(1); } } void Game::UpdateGame() { // Compute delta time // Wait until 16ms has elapsed since last frame while (!SDL_TICKS_PASSED(SDL_GetTicks(), ticksCount + 16)) ; float deltaTime = (SDL_GetTicks() - ticksCount) / 1000.0f; if (deltaTime > 0.05f) { deltaTime = 0.05f; } ticksCount = SDL_GetTicks(); // Update the sprite sprite.update(deltaTime); // Continuously move sprite3 across the screen (and loop back around) sprite3.moveRight(); if (sprite3.box.x > 800) sprite3.setX(-200); sprite3.update(deltaTime); // Check for sprite to sprite intersections if (sprite.box.boxesIntersect(sprite3.box)) { sprite.sethasCollided(true); sprite3.sethasCollided(true); } else { sprite.sethasCollided(false); sprite3.sethasCollided(false); } } void Game::GenerateOutput() { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Game drawing goes here. sprite.draw(); //printf(sprite.to_string().c_str()); sprite3.draw(); printf(sprite3.to_string().c_str()); // Present the most recent frame. SDL_GL_SwapWindow(window); } // Shutdown the game void Game::Shutdown() { //Destroy window SDL_DestroyWindow(window); window = NULL; SDL_Quit(); }
[ "FMOCK@users.noreply.github.com" ]
FMOCK@users.noreply.github.com
e309f3d30aa634cbf5651d5bdc600a32d1fa2fbc
90d39aa2f36783b89a17e0687980b1139b6c71ce
/Codechef/snackdown/17/2/ANCESTOR.cc
dcd2c1e04ff81abdb6d66c476bcf0b7bdbd5fdc0
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,022
cc
#include <bits/stdc++.h> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",a) #define newline printf("\n") #define BE(a) a.begin(), a.end() using namespace std; int N; vector<int> neigh[2][500010]; int par[1000100][32]; int depth[1000100]; void dfs1(int idx, int par = -1){ for(int v: neigh[idx]){ if(v != par){ } } } int main(){ in_T{ in_I(N); for(int i = 0;i<=N;i++){ neigh[0][i].clear(); neigh[1][i].clear(); } for(int i = 0;i<N-1;i++){ int u, v; in_I(u); in_I(v); neigh[0][u].push_back(v); neigh[0][v].push_back(u); } for(int i = 0;i<N-1;i++){ int u, v; in_I(u); in_I(v); neigh[1][u].push_back(v); neigh[1][v].push_back(u); } depth[1] = 1; dfs1(1); } }
[ "nimeshghelani@gmail.com" ]
nimeshghelani@gmail.com
a6c7f0702510c18abf845118ebbcf5abbe380dcb
c68f791005359cfec81af712aae0276c70b512b0
/0-unclassified/jaw.cpp
e179eaf6e285e47e721694d59b905d79a37e8c0f
[]
no_license
luqmanarifin/cp
83b3435ba2fdd7e4a9db33ab47c409adb088eb90
08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f
refs/heads/master
2022-10-16T14:30:09.683632
2022-10-08T20:35:42
2022-10-08T20:35:42
51,346,488
106
46
null
2017-04-16T11:06:18
2016-02-09T04:26:58
C++
UTF-8
C++
false
false
2,035
cpp
#include <bits/stdc++.h> typedef long long LL; typedef double DB; #define sf scanf #define pf printf #define mp make_pair #define nl printf("\n") #define FOR(i,a,b) for(i = a; i <= b; ++i) #define FORD(i,a,b) for(i = a; i >= b; --i) #define FORS(i,n) for(i = 0; i < n; ++i) #define FORM(i,n) for(i = n - 1; i >= 0; --i) #define reset(i,n) memset(i, n, sizeof(i)) #define open freopen("input.txt","r",stdin); freopen("output.txt","w",stdout) #define close fclose(stdin); fclose(stdout) using namespace std; const LL mod = 1e9 + 7; const LL INF = 4e18; const int inf = 2e9; int gcd(int a, int b) { return b? gcd(b, a%b): a; } int lcm(int a, int b) { return a/ gcd(a, b)*b; } int s[30][30], pet[30][30], n, m; bool vis[30][30]; int dfs(int x, int y) { if(x < 1 || n < x || y < 1 || m < y) return 0; if(vis[x][y]) return 0; vis[x][y] = 1; int ret = 1; ret += (s[x][y + 1] == s[x][y]? dfs(x, y + 1) : 0); ret += (s[x][y - 1] == s[x][y]? dfs(x, y - 1) : 0); ret += (s[x + 1][y] == s[x][y]? dfs(x + 1, y) : 0); ret += (s[x - 1][y] == s[x][y]? dfs(x - 1, y) : 0); return ret; } void rusak(int x, int y) { if(x < 1 || n < x || y < 1 || m < y) return; if(vis[x][y]) return; vis[x][y] = 1; pet[x][y] = -99; if(s[x][y + 1] == s[x][y]) rusak(x, y + 1); if(s[x][y - 1] == s[x][y]) rusak(x, y - 1); if(s[x + 1][y] == s[x][y]) rusak(x + 1, y); if(s[x - 1][y] == s[x][y]) rusak(x - 1, y); } int main(void) { int i, j; sf("%d %d", &n, &m); FOR(i, 1, n) FOR(j, 1, m) { sf("%d", &s[i][j]); pet[i][j] = s[i][j]; } int x, y; int ans = 0; FOR(i, 1, n) FOR(j, 1, m) { int cur = dfs(i, j); if(cur > ans) { ans = cur; x = i; y = j; } } reset(vis, 0); rusak(x, y); FORD(i, n, 1) FOR(j, 1, m) { if(pet[i][j] == -99) { int ii = i; while(ii) { if(pet[ii][j] != -99) break; ii--; } if(ii) swap(pet[ii][j], pet[i][j]); } } FOR(i, 1, n) { pf("%c", (pet[i][1] == -99? '.' : pet[i][1] + '0')); FOR(j, 2, m) pf(" %c", (pet[i][j] == -99? '.' : pet[i][j] + '0')); nl; } return 0; }
[ "l.arifin.siswanto@gmail.com" ]
l.arifin.siswanto@gmail.com
27e5f013f27af914267acb126d8b2d8a5fa4bfa6
c12dc233139fc8aa95877e6081e671c4a972b091
/TEvtGen/EvtGenBase/EvtPto3PAmpFactory.cxx
62e7f363aff1b64f319abab5a152800b196e9ba6
[]
no_license
yanqicw/ORKA-ILCRoot
b4be984cb9f1991b0c174da7428366af4973ef84
6e66c4cbae6835586274a385bee9bed254a63976
refs/heads/master
2020-04-01T02:27:50.942859
2012-12-03T17:51:10
2012-12-03T17:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,785
cxx
//----------------------------------------------------------------------- // File and Version Information: // $Id: EvtPto3PAmpFactory.cc,v 1.22 2009/02/19 03:22:30 ryd Exp $ // // Environment: // This software is part of the EvtGen package developed jointly // for the BaBar and CLEO collaborations. If you use all or part // of it, please give an appropriate acknowledgement. // // Copyright Information: // Copyright (C) 1998 Caltech, UCSB // // Module creator: // Alexei Dvoretskii, Caltech, 2001-2002. //----------------------------------------------------------------------- #include "EvtGenBase/EvtPatches.hh" // AmpFactory for building a P -> 3P decay // (pseudoscalar to three pseudoscalars) #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "EvtGenBase/EvtId.hh" #include "EvtGenBase/EvtPDL.hh" #include "EvtGenBase/EvtConst.hh" #include "EvtGenBase/EvtComplex.hh" #include "EvtGenBase/EvtCyclic3.hh" #include "EvtGenBase/EvtSpinType.hh" #include "EvtGenBase/EvtPto3PAmp.hh" #include "EvtGenBase/EvtNonresonantAmp.hh" #include "EvtGenBase/EvtFlatAmp.hh" #include "EvtGenBase/EvtLASSAmp.hh" #include "EvtGenBase/EvtPto3PAmpFactory.hh" #include "EvtGenBase/EvtPropBreitWigner.hh" #include "EvtGenBase/EvtPropFlatte.hh" #include "EvtGenBase/EvtPropBreitWignerRel.hh" #include "EvtGenBase/EvtDalitzResPdf.hh" #include "EvtGenBase/EvtDalitzFlatPdf.hh" using namespace EvtCyclic3; #include <iostream> void EvtPto3PAmpFactory::processAmp(EvtComplex c, std::vector<std::string> vv, bool conj) { if(_verbose) { printf("Make %samplitude\n",conj ? "CP conjugate" : ""); unsigned i; for(i=0;i<vv.size();i++) printf("%s\n",vv[i].c_str()); printf("\n"); } EvtAmplitude<EvtDalitzPoint>* amp = 0; EvtPdf<EvtDalitzPoint>* pdf = 0; std::string name; Pair pairRes=AB; size_t i; /* Experimental amplitudes */ if(vv[0] == "PHASESPACE") { pdf = new EvtDalitzFlatPdf(_dp); amp = new EvtFlatAmp<EvtDalitzPoint>(); name = "NR"; } else if (!vv[0].find("NONRES")) { double alpha=0; EvtPto3PAmp::NumType typeNRes=EvtPto3PAmp::NONRES; if (vv[0]=="NONRES_LIN") { typeNRes=EvtPto3PAmp::NONRES_LIN; pairRes=strToPair(vv[1].c_str()); } else if (vv[0]=="NONRES_EXP") { typeNRes=EvtPto3PAmp::NONRES_EXP; pairRes = strToPair(vv[1].c_str()); alpha = strtod(vv[2].c_str(),0); } else assert(0); pdf = new EvtDalitzFlatPdf(_dp); amp = new EvtNonresonantAmp( &_dp, typeNRes, pairRes, alpha); } else if (vv[0]=="LASS") { pairRes = strToPair(vv[1].c_str()); double m0 = strtod(vv[2].c_str(),0); double g0 = strtod(vv[3].c_str(),0); double a = strtod(vv[4].c_str(),0); double r = strtod(vv[5].c_str(),0); double cutoff = strtod(vv[6].c_str(),0); pdf = new EvtDalitzResPdf(_dp,m0,g0,pairRes); amp = new EvtLASSAmp( &_dp, pairRes, m0, g0, a, r, cutoff); } /* Resonant amplitudes */ else if(vv[0] == "RESONANCE") { EvtPto3PAmp* partAmp = 0; // RESONANCE stanza pairRes = strToPair(vv[1].c_str()); EvtSpinType::spintype spinR; double mR, gR; name = vv[2]; EvtId resId = EvtPDL::getId(vv[2]); if(_verbose) printf("Particles %s form %sresonance %s\n", vv[1].c_str(),vv[2].c_str(), conj ? "(conj) " : ""); // If no valid particle name is given, assume that // it is the spin, the mass and the width of the particle. if(resId.getId() == -1) { switch(atoi(vv[2].c_str())) { case 0: { spinR = EvtSpinType::SCALAR; break; } case 1: { spinR = EvtSpinType::VECTOR; break; } case 2: { spinR = EvtSpinType::TENSOR; break; } case 3: { spinR = EvtSpinType::SPIN3; break; } case 4: { spinR = EvtSpinType::SPIN4; break; } default: { assert(0); break; } } mR = strtod(vv[3].c_str(),0); gR = strtod(vv[4].c_str(),0); i = 4; } else { // For a valid particle get spin, mass and width spinR = EvtPDL::getSpinType(resId); mR = EvtPDL::getMeanMass(resId); gR = EvtPDL::getWidth(resId); i = 2; // It's possible to specify mass and width of a particle // explicitly if(vv[3] != "ANGULAR") { if(_verbose) printf("Setting m(%s)=%s g(%s)=%s\n", vv[2].c_str(),vv[3].c_str(),vv[2].c_str(),vv[4].c_str()); mR = strtod(vv[3].c_str(),0); gR = strtod(vv[4].c_str(),0); i = 4; } } // ANGULAR stanza if(vv[++i] != "ANGULAR") { printf("%s instead of ANGULAR\n",vv[i].c_str()); exit(0); } Pair pairAng = strToPair(vv[++i].c_str()); if(_verbose) printf("Angle is measured between particles %s\n",vv[i].c_str()); // TYPE stanza assert(vv[++i] == "TYPE"); std::string type = vv[++i]; if(_verbose) printf("Propagator type %s\n",vv[i].c_str()); if(type == "NBW") { EvtPropBreitWigner prop(mR,gR); partAmp = new EvtPto3PAmp(_dp,pairAng,pairRes,spinR,prop,EvtPto3PAmp::NBW); } else if(type == "RBW_ZEMACH") { EvtPropBreitWignerRel prop(mR,gR); partAmp = new EvtPto3PAmp(_dp,pairAng,pairRes,spinR,prop,EvtPto3PAmp::RBW_ZEMACH); } else if(type == "RBW_KUEHN") { EvtPropBreitWignerRel prop(mR,gR); partAmp = new EvtPto3PAmp(_dp,pairAng,pairRes,spinR,prop,EvtPto3PAmp::RBW_KUEHN); } else if(type == "RBW_CLEO") { EvtPropBreitWignerRel prop(mR,gR); partAmp = new EvtPto3PAmp(_dp,pairAng,pairRes,spinR,prop,EvtPto3PAmp::RBW_CLEO); } else if(type == "FLATTE") { double m1a = _dp.m( first(pairRes) ); double m1b = _dp.m( second(pairRes) ); // 2nd channel double g2 = strtod(vv[++i].c_str(),0); double m2a = strtod(vv[++i].c_str(),0); double m2b = strtod(vv[++i].c_str(),0); EvtPropFlatte prop( mR, gR, m1a, m1b, g2, m2a, m2b ); partAmp = new EvtPto3PAmp(_dp,pairAng,pairRes,spinR,prop,EvtPto3PAmp::FLATTE); } else assert(0); // Optional DVFF, BVFF stanzas if(i < vv.size() - 1) { if(vv[i+1] == "DVFF") { i++; if(vv[++i] == "BLATTWEISSKOPF") { double R = strtod(vv[++i].c_str(),0); partAmp->set_fd(R); } else assert(0); } } if(i < vv.size() - 1) { if(vv[i+1] == "BVFF") { i++; if(vv[++i] == "BLATTWEISSKOPF") { if(_verbose) printf("BVFF=%s\n",vv[i].c_str()); double R = strtod(vv[++i].c_str(),0); partAmp->set_fb(R); } else assert(0); } } const int minwidths=5; //Optional resonance minimum and maximum if(i < vv.size() - 1) { if(vv[i+1] == "CUTOFF") { i++; if(vv[i+1] == "MIN") { i++; double min = strtod(vv[++i].c_str(),0); if(_verbose) std::cout<<"CUTOFF MIN = "<<min<<std::endl; //ensure against cutting off too close to the resonance assert( min<(mR-minwidths*gR) ); partAmp->setmin(min); } else if (vv[i+1] == "MAX") { i++; double max = strtod(vv[++i].c_str(),0); if(_verbose) std::cout<<"CUTOFF MAX = "<<max<<std::endl; //ensure against cutting off too close to the resonance assert( max>(mR+minwidths*gR) ); partAmp->setmax(max); } else assert(0); } } //2nd iteration in case min and max are both specified if(i < vv.size() - 1) { if(vv[i+1] == "CUTOFF") { i++; if(vv[i+1] == "MIN") { i++; double min = strtod(vv[++i].c_str(),0); if(_verbose) std::cout<<"CUTOFF MIN = "<<min<<std::endl; //ensure against cutting off too close to the resonance assert( min<(mR-minwidths*gR) ); partAmp->setmin(min); } else if (vv[i+1] == "MAX") { i++; double max = strtod(vv[++i].c_str(),0); if(_verbose) std::cout<<"CUTOFF MAX = "<<max<<std::endl; //ensure against cutting off too close to the resonance assert( max>(mR+minwidths*gR) ); partAmp->setmax(max); } else assert(0); } } i++; pdf = new EvtDalitzResPdf(_dp,mR,gR,pairRes); amp = partAmp; } assert(amp); assert(pdf); if(!conj) { _amp->addOwnedTerm(c,amp); } else { _ampConj->addOwnedTerm(c,amp); } double scale = matchIsobarCoef(_amp, pdf, pairRes); _pc->addOwnedTerm(abs2(c)*scale,pdf); _names.push_back(name); } double EvtPto3PAmpFactory::matchIsobarCoef(EvtAmplitude<EvtDalitzPoint>* amp, EvtPdf<EvtDalitzPoint>* pdf, EvtCyclic3::Pair ipair) { // account for differences in the definition of amplitudes by matching // Integral( c'*pdf ) = Integral( c*|A|^2 ) // to improve generation efficiency ... double Ipdf = pdf->compute_integral(10000).value(); double Iamp2 = 0; EvtCyclic3::Pair jpair = EvtCyclic3::next(ipair); EvtCyclic3::Pair kpair = EvtCyclic3::next(jpair); // Trapezoidal integral int N=10000; double di = (_dp.qAbsMax(ipair) - _dp.qAbsMin(ipair))/((double) N); double siMin = _dp.qAbsMin(ipair); double s[3]; // playing with fire for(int i=1; i<N; i++) { s[ipair] = siMin + di*i; s[jpair] = _dp.q(jpair, 0.9999, ipair, s[ipair]); s[kpair] = _dp.bigM()*_dp.bigM() - s[ipair] - s[jpair] + _dp.mA()*_dp.mA() + _dp.mB()*_dp.mB() + _dp.mC()*_dp.mC(); EvtDalitzPoint point( _dp.mA(), _dp.mB(), _dp.mC(), s[EvtCyclic3::AB], s[EvtCyclic3::BC], s[EvtCyclic3::CA]); if (!point.isValid()) continue; double p = point.p(other(ipair), ipair); double q = point.p(first(ipair), ipair); double itg = abs2( amp->evaluate(point) )*di*4*q*p; Iamp2 += itg; } if (_verbose) std::cout << "integral = " << Iamp2 << " pdf="<<Ipdf << std::endl; assert(Ipdf>0 && Iamp2>0); return Iamp2/Ipdf; }
[ "anna@fbb65c11-2394-7148-9363-1d506dd39c89" ]
anna@fbb65c11-2394-7148-9363-1d506dd39c89
e4a0be0babf62733b38423ff9775289cdb5802f6
7546536d704f667905a557397b9ac9b37cab8c38
/Material.cpp
555c0326cebbe70037cb465b3e417ed0b4f62906
[]
no_license
jambolo/Glx
8ea8c29cf6f923f16103206b3cce55db8771b381
cc16be2b6d7d77f65de1e36f0b9306417d575582
refs/heads/master
2021-01-13T16:00:38.041407
2019-07-06T06:13:25
2019-07-06T06:14:12
76,818,324
0
0
null
null
null
null
UTF-8
C++
false
false
5,535
cpp
/** @file *//******************************************************************************************************** Material.cpp Copyright 2003, John J. Bolton -------------------------------------------------------------------------------------------------------------- $Header: //depot/Libraries/Glx/Material.cpp#5 $ $NoKeywords: $ ********************************************************************************************************************/ #include "PrecompiledHeaders.h" #include "Material.h" #include "Texture.h" #include "Enable.h" namespace Glx { /********************************************************************************************************************/ /* */ /* */ /********************************************************************************************************************/ /// Constructs a Material with no texture. /// @param color Diffuse and ambient color /// @param specularColor Specular color /// @param shininess Specular power. Range is 0.f - 128.f /// @param emissiveColor Emissive color /// @param shading Shading type. Values accepted by @p glShadingModel are valid. Currently: /// - @p GL_FLAT /// - @p GL_SMOOTH (default) /// @param face Face this applies to. Values may be: /// - @p GL_FRONT /// - @p GL_BACK /// - @p GL_FRONT_AND_BACK (default) Material::Material( Rgba const & color /*= Rgba::WHITE*/, Rgba const & specularColor /*= Rgba::BLACK*/, GLfloat shininess /*= 0.f*/, Rgba const & emissiveColor /*= Rgba::BLACK*/, GLenum shading /*= GL_SMOOTH*/, GLenum face /*= GL_FRONT_AND_BACK*/ ) : m_Face( face ), m_Shading( shading ), m_Color( color ), m_pTexture( 0 ), m_TexEnvMode( GL_MODULATE ), m_SpecularColor( specularColor ), m_Shininess( shininess ), m_EmissiveColor( emissiveColor ) { assert_limits( 0.f, shininess, 128.f ); } /********************************************************************************************************************/ /* */ /* */ /********************************************************************************************************************/ /// Constructs a Material with a texture /// @param pTexture Texture /// @param texEnv Texture environment mode. If @a pTexture is @p NULL, this parameter is ignored. Values /// accepted by @p glTexEnvi are valid. Currently: /// - @p GL_MODULATE (default) /// - @p GL_DECAL /// - @p GL_BLEND /// - @p GL_REPLACE /// @param color Diffuse and ambient color /// @param specularColor Specular color /// @param shininess Specular power. Range is 0.f - 128.f /// @param emissiveColor Emissive color /// @param shading Shading type. Values accepted by @p glShadingModel are valid. Currently: /// - @p GL_FLAT /// - @p GL_SMOOTH (default) /// @param face Face this applies to. Values may be: /// - @p GL_FRONT /// - @p GL_BACK /// - @p GL_FRONT_AND_BACK (default) Material::Material( Texture * pTexture, GLenum texEnv /*= GL_MODULATE*/, Rgba const & color /*= Rgba::WHITE*/, Rgba const & specularColor /*= Rgba::BLACK*/, GLfloat shininess /*= 0.f*/, Rgba const & emissiveColor /*= Rgba::BLACK*/, GLenum shading /*= GL_SMOOTH*/, GLenum face /*= GL_FRONT_AND_BACK*/ ) : m_Face( face ), m_Shading( shading ), m_Color( color ), m_pTexture( pTexture ), m_TexEnvMode( texEnv ), m_SpecularColor( specularColor ), m_Shininess( shininess ), m_EmissiveColor( emissiveColor ) { assert_limits( 0.f, shininess, 128.f ); } /********************************************************************************************************************/ /* */ /* */ /********************************************************************************************************************/ Material::~Material() { } /********************************************************************************************************************/ /* */ /* */ /********************************************************************************************************************/ /// @note The following states are set by this function: /// - glShadeModel( ... ) /// - glMaterialfv( m_Face, GL_AMBIENT_AND_DIFFUSE, ... ) /// - glMaterialfv( m_Face, GL_SPECULAR, ... ) /// - glMaterialf( m_Face, GL_SHININESS, ... ) /// - glMaterialfv( m_Face, GL_EMISSION, ... ) /// - glEnable( GL_TEXTURE_2D ), if textured /// - glDisable( GL_TEXTURE_2D ), if not textured /// - glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, ... ) /// - glBindTexture( GL_TEXTURE_2D, ... ) void Material::Apply() const { glShadeModel( m_Shading ); glMaterialfv( m_Face, GL_AMBIENT_AND_DIFFUSE, m_Color.m_C ); glMaterialfv( m_Face, GL_SPECULAR, m_SpecularColor.m_C ); glMaterialf( m_Face, GL_SHININESS, m_Shininess ); glMaterialfv( m_Face, GL_EMISSION, m_EmissiveColor.m_C ); if ( m_pTexture ) { Glx::Enable( GL_TEXTURE_2D ); glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, m_TexEnvMode ); m_pTexture->Apply(); } else { Glx::Disable( GL_TEXTURE_2D ); } } } // namespace Glx
[ "odolvlobo-github@yahoo.com" ]
odolvlobo-github@yahoo.com
cdf517edfef882ea0e19909e73f43c7bda13b036
03211386b21ce1abbb2b1d3369df344cdd2a8d14
/Dynamic Programming/Non-Classical/043 SPOJ - ACODE.cpp
4ba553b0c4927014e21a5339e8c69c47305069a0
[]
no_license
bony2023/Competitive-Programming
a9e616957986ea09e6694ce3635eefd3e843a0d0
d33d919658327048bfdef702efd7cb5eab013c33
refs/heads/master
2021-03-12T19:21:18.758167
2015-04-19T19:26:29
2015-04-19T19:26:29
22,675,345
1
0
null
null
null
null
UTF-8
C++
false
false
2,172
cpp
// Author : Bony Roopchandani // ACODE // DP // INCLUDES #include <algorithm> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; // MACROS #define all(a) a.begin(), a.end() #define bg begin() #define en end() #define ff first #define ll long long #define mp make_pair #define nl printf("\n") #define pb push_back #define pf(a) printf("%d ",a) #define pfi(a) printf("%d\n",a) #define pfl(a) printf("%lld\n",(ll)a) #define pfs(a) printf("%s\n",a) #define rep(i, n) for(int i=0; i<n; i++) #define repd(i, a, b) for(int i=a; i>=b; i--) #define repl(i, n) for(ll i=0; i<n; i++) #define repld(i, a, b) for(ll i=a; i>=b; i--) #define replt(i, a, b) for(ll i=a; i<=b; i++) #define rept(i, a, b) for(int i=a; i<=b; i++) #define sfi(a) scanf("%d",&a) #define sfl(a) scanf("%lld",&a) #define sfs(a) scanf("%s",a) #define ss second #define sz size() // CONSTS const double EPS = (1e-11); const double PI = acos(-1.0); const int INF = 9999999; const int MOD = (1e9 + 7); // TYPEDEFS typedef list < int > LI; typedef list < ll > LLL; typedef map < int, bool > MIB; typedef map < int, int > MII; typedef map < int, ll > MIL; typedef map < ll, int > MLI; typedef pair < int, int > PII; typedef pair < int, PII > PIII; typedef pair < int, PIII > PIIII; typedef pair < int, ll > PIL; typedef pair < ll, int > PLI; typedef set < int > SI; typedef set < ll > SLL; typedef vector < int > VI; typedef vector < ll > VLL; typedef vector < string > VS; char A[5000+5]; int parse(int a, int b) { int x=(A[a]-'0')*10; return (x+(A[b]-'0')); } ll dp[5000+5]; ll f(int pos) { if(A[0]>='1' && A[0]<='9') dp[0]=1; else dp[0]=0; rept(i, 1, pos) { if(A[i]>='1' && A[i]<='9') dp[i]=dp[i-1]; int P=parse(i-1, i); if(P>9 && P<=26) { if((i-2)>=0) dp[i]+=dp[i-2]; else dp[i]+=dp[0]; } } return dp[pos]; } int main() { while(1) { memset(dp, 0, sizeof dp); sfs(A); if(strlen(A)==1 && A[0]=='0') break; pfl(f(strlen(A)-1)); } return (0); }
[ "" ]
21c1a29e9bb3c7cc136334792bea001f664d272e
9a3e97ea5b4b39e3b5316fe25fe1086cdcdbbd49
/Client.cpp
a4d4f4752749006094d2fa62f84c748eab873f1c
[]
no_license
Pushkar16/labwork
18de02569f9e7ce100a8931e5d4672188df89dc5
a77a166c50175e73ee39a80f070796993cae1572
refs/heads/master
2020-06-16T10:30:26.946047
2018-01-30T21:56:54
2018-01-30T21:56:54
94,143,367
0
0
null
null
null
null
UTF-8
C++
false
false
1,740
cpp
#include <iostream> #include <iostream> #include <iomanip> #include <stdio.h> #include <iostream> #include <omp.h> #include <cstdlib> #include <iostream> #include <fstream> #include <cstring> #include <string> #include <cmath> using namespace std; #include "CTFEstimate.h" int main() { float A; float lambda,g,cs; std::string gmag; float defocus; float alpha_g,alpha_ast; std::string line; std::ifstream myfile ("input.txt"); if (myfile.is_open()) { std::string delimiter = ":"; while ( getline (myfile,line) ) { std::string token = line.substr(0,line.find(delimiter)); std::string value = line.substr(line.find(delimiter)+1); if(token=="A") { A=atof(value.c_str()); } if(token=="lambda") { lambda=atof(value.c_str()); } if(token=="g") { gmag=value.c_str(); std::cout<<"\ngmag is ::"<<gmag; std::string delimiter2 = ","; std::string y=gmag.substr(gmag.find(delimiter2)+1); std::string x=gmag.substr(0,gmag.find(delimiter2)); float xcomp=strtof(x.c_str(),0); float ycomp=strtof(y.c_str(),0); g=pow(pow(xcomp,2)+pow(ycomp,2),0.5); } if(token=="CS") { cs=atof(value.c_str()); } if(token=="defocus") { defocus=atof(value.c_str()); } if(token=="alpha_g") { alpha_g=atof(value.c_str()); } if(token=="alpha_ast") { alpha_ast=atof(value.c_str()); } //std::cout << token << '\n'; } } //std::cout<<w1<<"\n"<<w2<<"\n"<<lambda<<"\n"<<g<<"\n"<<cs<<"\n"<<alpha_g<<"\n"<<alpha_ast; CTFEstimate ctf=CTFEstimate(A,lambda,g,cs,defocus,alpha_g,alpha_ast); }
[ "pushker16@gmail.com" ]
pushker16@gmail.com
2b9c79939ae6e9db6507ebd69cf10dd1d39c6424
151b1ed23a4d972582cdd26b21c49d8689c804bb
/eventlib/event_tra_immA.h
4fb966d656f5b2571260533cec1a87a54dd7420c
[]
no_license
Chuzzle/masters_thesis
63cf48996c35e6752f82e4ef169d6bace16e83eb
f785d0d6a4ddc45490f73c343fc23d7c686c631a
refs/heads/master
2020-05-21T19:10:22.282789
2017-08-12T18:01:28
2017-08-12T18:01:28
61,619,714
0
0
null
null
null
null
UTF-8
C++
false
false
306
h
#include "event.h" #ifndef EVENT_TRA_IMMA_H #define EVENT_TRA_IMMA_H class Event_tra_immA : public Event{ public: explicit Event_tra_immA(Population& pop_init) : Event(pop_init) {}; virtual std::string description(); virtual double update_prob(double t); virtual void execute_event(); }; #endif
[ "hanna_autio@hotmail.com" ]
hanna_autio@hotmail.com
0f07b5d535ef7fb214433fd8e03daf80720620ab
0d1eaeebbef203e83ccb058268c7c8ffaf9c98f9
/utils.h
ac46293bc006a9cc76fccdab647b92f29f0edc7d
[]
no_license
nagendra-y/RAKE
10fee445e1383b2f6291662d7846ba5e7ca546d4
2c685e54b1e153abf369fb4ff5abd7f2e2d45688
refs/heads/master
2021-03-25T18:28:35.171019
2015-03-12T18:41:14
2015-03-12T18:41:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
964
h
#ifndef UTILS_H #define UTILS_H #include <boost/algorithm/string.hpp> #include <boost/regex.hpp> #include <string> #include <vector> namespace rake{ inline std::vector<std::string> split(const std::string& text, const boost::regex& regex){ std::vector<std::string> results; boost::sregex_token_iterator i(text.begin(), text.end(), regex, -1); boost::sregex_token_iterator end; while(i != end){ std::string token(*i); boost::trim(token); if(token != "") results.push_back(token); i++; } return results; } inline std::string lower(const std::string str){ return boost::to_lower_copy(str); } inline std::string join(const std::vector<std::string>& v, std::string c=" "){ int s = v.size(); if(s == 0) return ""; std::string res = ""; for(int i=0; i<s; ++i){ res += v[i]; if(i != s-1) res += c; } return res; } } #endif // UTILS_H
[ "giorgos@gpc.fritz.box" ]
giorgos@gpc.fritz.box
9aeedd8db3e7b63878643cb8254cfaa462aae1a9
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_7644.cpp
0b1c4fc2e9ffddc2ff371f6a3f136709a97654ff
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
429
cpp
tag_val = get_tag(r->pool, in, tag, sizeof(tag), 0); if (*tag == '\0') { return 1; } else if (!strcmp(tag, "done")) { if (expr == NULL) { ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r->server, "missing expr in if statement: %s", r->filename); ap_rputs(error, r); return 1; } *printing = *conditional_status = parse_expr(r, expr, error);
[ "993273596@qq.com" ]
993273596@qq.com
dc5b320bd99d9ca3942a381a6c62acfc0ba08d30
ec8a204d9f078d12ed95f7975adbde4d51ad55ec
/10.SM/SMv1.0.00.1/source/CommonData.cpp
b545fbbe91ef021a88468c1e9d1c0955df0ab3fb
[]
no_license
yyd01245/bbcv_SM
77c2e0b3519ee064cce8a8764e46959265903b06
25bb6c622fd9a1d54cb3865daf0e259e56bbb352
refs/heads/master
2016-09-05T14:55:03.118908
2015-09-18T04:09:51
2015-09-18T04:09:51
42,697,679
1
1
null
null
null
null
GB18030
C++
false
false
1,463
cpp
char strAdverIP[128]; int iAdverPort; char strNavIP[128]; int iNavPort; char strVodIP[128]; int iVodPort; char strMsiIP[128]; int iMsiPort; char strMyServerIP[128]; int iMSIServerPort; char strVOD_KeyIP[128]; char dbip[128]; char dbname[128]; char dbuser[128]; char dbpass[128]; char hdadvname[128]; char hdadvip[128]; char hdadvport[64]; char advip[128]; int muladvport; char pauseurl[256]; char quiturl[256]; char strsdNavIP[128]; int isdNavPort; char hdrate[64]; char sdrate[64]; char navgoback[256]; char sdpauseurl[256]; char sdquiturl[256]; char sdnavgoback[256]; char sdadvname[128]; char sdadvip[128]; char sdadvport[64]; int iwaittime; int frequency; int pid; int advflag; //是否使用均衡切流器1:使用 0:不使用 char strblanIP[64]; int iBlanport; int iBaseport; int Istype = 1; //VGW的类型 0:ENRICH 1:SIHUA 2:VLC int VOD_play_clean = 1000*1000; //释放: 广告流 或者 导航流 或者 广告+CDN流 int VodStreamOver_clean = 1000*1000; //VodStreamOver (goback)调用 清掉:切流器,cdn的流 int BindOverTime_clean = 1000*1800; //BindOverTime 释放:导航流 int RecoverVodPlay_clean = 1000*1000; //RecoverVodPlay 释放:导航流 int InitStream_clean = 1000*1000; //InitStream 初始化释放所有流 int PauseVOD_clean = 1000*1000; //PauseVOD 释放掉一路广告流
[ "yydgame@163.com" ]
yydgame@163.com
994b519898365e3a1c5d0d92f5dee8d9ed900067
28c0fe23f98240d20f1da70ee6d03bf825149972
/1-İkiSayınınBölünmesi/IkiSayininBolunmesi.cpp
e6c8aa4238f0a9cb69536b4a7468e11e29138442
[ "MIT" ]
permissive
enurv/ProgrammingHandBook
b8e57594adbe0758ff0406520b0625ea7c20921c
3327389adcfa2aef0f2277331973a49072fa1510
refs/heads/master
2020-08-13T01:21:56.604420
2019-10-18T13:55:40
2019-10-18T13:55:40
214,880,914
0
1
null
2019-10-13T19:30:29
2019-10-13T19:30:29
null
UTF-8
C++
false
false
754
cpp
#include <iostream> using namespace std; int main() { // “a”, “b”, “c” tanımlanması int a, b, c; cout<< "a= "; // “a” ve “b”nin değerlerinin girilmesi cin >> a; cout << "b= "; cin >> b; // Büyük sayının tespit edilmesi. if (a < b) { // “a”nın değerinin “c”de saklanması c = a; // “b”nin değeri “a”ya atanması a = b; // “c”de Saklanan değerinin “b”ye aktarılması b = c; } // 0 ise “Tam Bolunebilir” yazdırılması if (a % b == 0) cout<<"Tam Bolunebilir"; // 0 değilse “Tam Bolunemez” yazdırılması else cout<<"Tam Bolunemez"; return 0; }
[ "45575570+asmaamirkhan@users.noreply.github.com" ]
45575570+asmaamirkhan@users.noreply.github.com
0a5eaee400abe0691890a7808e2628c1ed2d0ba5
559865817c91a275f4d53491a083ff2d249f230f
/Light OJ/LightOj 1214.cpp
d69bc6385886d5618e44b14162c42fa730f20874
[]
no_license
zarif98sjs/Competitive-Programming
5b9d80701417ab232800e1b81758d91af601dfca
bde0423f243b1b1ee7c9d4c5baf2a890f1ff15fb
refs/heads/master
2021-09-05T13:43:03.870815
2021-08-16T14:37:13
2021-08-16T14:37:13
152,996,444
1
0
null
2020-09-09T20:02:40
2018-10-14T16:47:09
C++
UTF-8
C++
false
false
1,673
cpp
/* Which of the favors of your Lord will you deny? */ #include<bits/stdc++.h> using namespace std; #define pi acos(-1) #define SI(n) scanf("%d",&n) #define SLL(n) scanf("%lld",&n) #define SULL(n) scanf("%llu",&n) #define SC(n) scanf("%c",&n) #define SD(n) scanf("%lf",&n) #define fr(i,a,b) for(int i=a ,_b=(b) ;i<= _b;i++) #define LL long long #define PUB push_back #define POB pop_back #define MP make_pair; #define PII pair<int,int> #define PLL pair<ll,ll> #define GCD __gcd #define DEBUG cout<<"aw"<<endl; int main() { //freopen("LOJ1214.txt","w",stdout); int tc; SI(tc); fr(j,1,tc) { char num[1000]; int div; scanf("%s",num); SI(div); LL now = num[0]-'0',i=0; if(num[0]=='-') i=1,now = num[1]-'0'; if(div<0) div = div*(-1); for( ; i<strlen(num); i++) { if(now/div!=0) { now = now%div; if(num[i+1]!='\0') { now = now*10+(num[i+1]-'0'); //cout<<"**"<<now<<endl; } //cout<<"##"<<now<<endl; } else // now/div=0 { //cout<<":)"<<num[i+1]<<endl; if(num[i+1]!='\0') { now = now*10 + (num[i+1]-'0'); //cout<<"@@@"<<now<<endl; } } } if(now==0) printf("Case %d: divisible\n",j); else printf("Case %d: not divisible\n",j); } return 0; }
[ "zarif98sjs@gmail.com" ]
zarif98sjs@gmail.com
8aa3389a4f21642b66dcf8b01bc6a9d50fa1387d
7a968d337839510b2623d8cbce0238cfed4babb0
/armcmx/tools/RFID/RFID_PN532_SPI/PN532.h
39a7697f5867292380b87eda1a62277224952ee5
[]
no_license
ADTL/ARMWork
637ab108346de001fcbc3b750ecff96abb88f2fd
85e959894cf5d200f70662a5deb4f2c432a61b83
refs/heads/master
2020-02-26T17:14:03.242368
2014-01-13T15:04:05
2014-01-13T15:04:05
16,342,797
2
0
null
null
null
null
UTF-8
C++
false
false
2,045
h
// PN532 library by adafruit/ladyada // MIT license // authenticateBlock, readMemoryBlock, writeMemoryBlock contributed // by Seeed Technology Inc (www.seeedstudio.com) #if ARDUINO >= 100 #include <Arduino.h> #else #include <WProgram.h> #endif #define PN532_PREAMBLE 0x00 #define PN532_STARTCODE1 0x00 #define PN532_STARTCODE2 0xFF #define PN532_POSTAMBLE 0x00 #define PN532_HOSTTOPN532 0xD4 #define PN532_FIRMWAREVERSION 0x02 #define PN532_GETGENERALSTATUS 0x04 #define PN532_SAMCONFIGURATION 0x14 #define PN532_INLISTPASSIVETARGET 0x4A #define PN532_INDATAEXCHANGE 0x40 #define PN532_MIFARE_READ 0x30 #define PN532_MIFARE_WRITE 0xA0 #define PN532_AUTH_WITH_KEYA 0x60 #define PN532_AUTH_WITH_KEYB 0x61 #define PN532_WAKEUP 0x55 #define PN532_SPI_STATREAD 0x02 #define PN532_SPI_DATAWRITE 0x01 #define PN532_SPI_DATAREAD 0x03 #define PN532_SPI_READY 0x01 #define PN532_MIFARE_ISO14443A 0x0 #define KEY_A 1 #define KEY_B 2 class PN532{ public: PN532(uint8_t cs, uint8_t clk, uint8_t mosi, uint8_t miso); void begin(void); boolean SAMConfig(void); uint32_t getFirmwareVersion(void); uint32_t readPassiveTargetID(uint8_t cardbaudrate); uint32_t authenticateBlock( uint8_t cardnumber /*1 or 2*/, uint32_t cid /*Card NUID*/, uint8_t blockaddress /*0 to 63*/, uint8_t authtype /*Either KEY_A or KEY_B */, uint8_t * keys); uint32_t readMemoryBlock(uint8_t cardnumber /*1 or 2*/,uint8_t blockaddress /*0 to 63*/, uint8_t * block); uint32_t writeMemoryBlock(uint8_t cardnumber /*1 or 2*/,uint8_t blockaddress /*0 to 63*/, uint8_t * block); boolean sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout = 1000); // private: uint8_t _ss, _clk, _mosi, _miso; boolean spi_readack(); uint8_t readspistatus(void); void readspidata(uint8_t* buff, uint8_t n); void spiwritecommand(uint8_t* cmd, uint8_t cmdlen); void spiwrite(uint8_t c); uint8_t spiread(void); };
[ "una.veritas@me.com" ]
una.veritas@me.com
c89e30e8fdbbe7cf8a60e7d1d386c99052cdac80
98c279b5d63d72222a53c5837f8fabfbfad1ed93
/examples/Network/OverSamplingHalfDuplexNoAcknowledge/Device1/Device1.ino
5d1fe4267bfa9a664a529085a8f9da2a952d8444
[ "Apache-2.0" ]
permissive
snowshow/PJON
5297c379523c804570d36d2d46315671b44808cb
0ff9245564507a525f54afae37decb18ccba6dc2
refs/heads/master
2021-01-19T12:32:56.655573
2017-02-14T15:01:13
2017-02-14T15:01:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
ino
#include <PJON.h> // Bus id definition uint8_t bus_id[] = {0, 0, 0, 1}; // PJON object PJON<OverSampling> bus(bus_id, 44); void setup() { pinMode(13, OUTPUT); digitalWrite(13, LOW); // Initialize LED 13 to be off bus.strategy.set_pins(11, 12); bus.set_synchronous_acknowledge(false); bus.set_receiver(receiver_function); bus.begin(); bus.send_repeatedly(45, "B", 1, 1000000); Serial.begin(115200); }; void receiver_function(uint8_t *payload, uint16_t length, const PJON_Packet_Info &packet_info) { Serial.print("Receiver bus id: "); Serial.print(packet_info.receiver_bus_id[0]); Serial.print(packet_info.receiver_bus_id[1]); Serial.print(packet_info.receiver_bus_id[2]); Serial.print(packet_info.receiver_bus_id[3]); Serial.print(" - device id: "); Serial.println(packet_info.receiver_id); Serial.print("Sender bus id: "); Serial.print(packet_info.sender_bus_id[0]); Serial.print(packet_info.sender_bus_id[1]); Serial.print(packet_info.sender_bus_id[2]); Serial.print(packet_info.sender_bus_id[3]); Serial.print(" - device id: "); Serial.println(packet_info.sender_id); if((char)payload[0] == 'B') { digitalWrite(13, HIGH); delay(5); digitalWrite(13, LOW); delay(5); } } void loop() { bus.receive(); bus.update(); };
[ "gioscarab@gmail.com" ]
gioscarab@gmail.com
ed6a7f7aec6048903ad034226397339ccad608da
b47bf18dfa4681e03af598a6cd21e8e0c9d51b0a
/src/caffe/layers/softmax_loss_layer.cpp
c0e0057ac630b7e4a411d31a661827605ad4db77
[ "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
peteflorence/caffe_FAST
a01c93ff7d53c88a7403abecfe6a009be7bafae7
1ea6c9eaadafcdb962196ec75e8437d91b7eb01a
refs/heads/master
2021-01-02T09:36:13.864715
2017-08-03T22:50:28
2017-08-03T22:50:28
99,259,444
3
0
null
null
null
null
UTF-8
C++
false
false
4,630
cpp
#include <algorithm> #include <cfloat> #include <vector> #include "caffe/layer.hpp" #include "caffe/layer_factory.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::LayerSetUp(bottom, top); LayerParameter softmax_param(this->layer_param_); softmax_param.set_type("Softmax"); softmax_layer_ = LayerRegistry<Dtype>::CreateLayer(softmax_param); softmax_bottom_vec_.clear(); softmax_bottom_vec_.push_back(bottom[0]); softmax_top_vec_.clear(); softmax_top_vec_.push_back(&prob_); softmax_layer_->SetUp(softmax_bottom_vec_, softmax_top_vec_); has_ignore_label_ = this->layer_param_.loss_param().has_ignore_label(); if (has_ignore_label_) { ignore_label_ = this->layer_param_.loss_param().ignore_label(); } normalize_ = this->layer_param_.loss_param().normalize(); } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); softmax_layer_->Reshape(softmax_bottom_vec_, softmax_top_vec_); softmax_axis_ = bottom[0]->CanonicalAxisIndex(this->layer_param_.softmax_param().axis()); outer_num_ = bottom[0]->count(0, softmax_axis_); inner_num_ = bottom[0]->count(softmax_axis_ + 1); CHECK_EQ(outer_num_ * inner_num_, bottom[1]->count()) << "Number of labels must match number of predictions; " << "e.g., if softmax axis == 1 and prediction shape is (N, C, H, W), " << "label count (number of labels) must be N*H*W, " << "with integer values in {0, 1, ..., C-1}."; if (top.size() >= 2) { // softmax output top[1]->ReshapeLike(*bottom[0]); } } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // The forward pass computes the softmax prob values. softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_); const Dtype* prob_data = prob_.cpu_data(); const Dtype* label = bottom[1]->cpu_data(); int dim = prob_.count() / outer_num_; int count = 0; Dtype loss = 0; for (int i = 0; i < outer_num_; ++i) { for (int j = 0; j < inner_num_; j++) { const int label_value = static_cast<int>(label[i * inner_num_ + j]); if (has_ignore_label_ && label_value == ignore_label_) { continue; } DCHECK_GE(label_value, 0); DCHECK_LT(label_value, prob_.shape(softmax_axis_)); loss -= log(std::max(prob_data[i * dim + label_value * inner_num_ + j], Dtype(FLT_MIN))); ++count; } } if (normalize_) { if (count > 0) { top[0]->mutable_cpu_data()[0] = loss / count; } else { top[0]->mutable_cpu_data()[0] = 0; } } else { top[0]->mutable_cpu_data()[0] = loss / outer_num_; } if (top.size() == 2) { top[1]->ShareData(prob_); } } template <typename Dtype> void SoftmaxWithLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* prob_data = prob_.cpu_data(); caffe_copy(prob_.count(), prob_data, bottom_diff); const Dtype* label = bottom[1]->cpu_data(); int dim = prob_.count() / outer_num_; int count = 0; for (int i = 0; i < outer_num_; ++i) { for (int j = 0; j < inner_num_; ++j) { const int label_value = static_cast<int>(label[i * inner_num_ + j]); if (has_ignore_label_ && label_value == ignore_label_) { for (int c = 0; c < bottom[0]->shape(softmax_axis_); ++c) { bottom_diff[i * dim + c * inner_num_ + j] = 0; } } else { bottom_diff[i * dim + label_value * inner_num_ + j] -= 1; ++count; } } } // Scale gradient const Dtype loss_weight = top[0]->cpu_diff()[0]; if (normalize_) { if (count > 0) { caffe_scal(prob_.count(), loss_weight / count, bottom_diff); } } else { caffe_scal(prob_.count(), loss_weight / outer_num_, bottom_diff); } } } #ifdef CPU_ONLY STUB_GPU(SoftmaxWithLossLayer); #endif INSTANTIATE_CLASS(SoftmaxWithLossLayer); REGISTER_LAYER_CLASS(SoftmaxWithLoss); } // namespace caffe
[ "pete.florence@gmail.com" ]
pete.florence@gmail.com