hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fe40c3dffbd1aeacdd475b9c54e41240e199297f
3,331
cpp
C++
cpp/src/io/device.cpp
quasiben/cucim
048d53e6f99c2129b9febd08e0ae6d1b37d74451
[ "Apache-2.0" ]
null
null
null
cpp/src/io/device.cpp
quasiben/cucim
048d53e6f99c2129b9febd08e0ae6d1b37d74451
[ "Apache-2.0" ]
null
null
null
cpp/src/io/device.cpp
quasiben/cucim
048d53e6f99c2129b9febd08e0ae6d1b37d74451
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020, 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 "cucim/macros/defines.h" #include "cucim/io/device.h" #include <regex> #include <string> #include <string_view> #include <fmt/format.h> namespace cucim::io { Device::Device() { // TODO: consider default case (how to handle -1 index?) } Device::Device(const Device& device) : type_(device.type_), index_(device.index_), shm_name_(device.shm_name_) { } Device::Device(const std::string& device_name) { // 'cuda', 'cuda:0', 'cpu[shm0]', 'cuda:0[cuda_shm0]' static const std::regex name_regex("([a-z]+)(?::(0|[1-9]\\d*))?(?:\\[([a-zA-Z0-9_\\-][a-zA-Z0-9_\\-\\.]*)\\])?"); std::smatch match; if (std::regex_match(device_name, match, name_regex)) { type_ = parse_type(match[1].str()); if (match[2].matched) { index_ = std::stoi(match[2].str()); } if (match[3].matched) { shm_name_ = match[3].str(); } } else { CUCIM_ERROR("Device name doesn't match!"); } validate_device(); } Device::Device(const char* device_name) : Device::Device(std::string(device_name)) { } Device::Device(DeviceType type, DeviceIndex index) { type_ = type; index_ = index; validate_device(); } Device::Device(DeviceType type, DeviceIndex index, const std::string& param) { type_ = type; index_ = index; shm_name_ = param; validate_device(); } DeviceType Device::parse_type(const std::string& device_name) { (void)device_name; // TODO: implement this return DeviceType::kCPU; } Device::operator std::string() const { static const std::unordered_map<DeviceType, std::string> device_type_map{ { DeviceType::kCPU, "cpu" }, { DeviceType::kPinned, "pinned" }, { DeviceType::kCPUShared, "cpu" }, { DeviceType::kCUDA, "cuda" }, { DeviceType::kCUDAShared, "cuda" }, }; if (index_ == -1 && shm_name_.empty()) { return fmt::format("{}", device_type_map.at(static_cast<DeviceType>(type_))); } else if (index_ != -1 && shm_name_.empty()) { return fmt::format("{}:{}", device_type_map.at(static_cast<DeviceType>(type_)), index_); } else { return fmt::format("{}:{}[{}]", device_type_map.at(static_cast<DeviceType>(type_)), index_, shm_name_); } } DeviceType Device::type() const { return type_; }; DeviceIndex Device::index() const { return index_; } const std::string& Device::shm_name() const { return shm_name_; } void Device::set_values(DeviceType type, DeviceIndex index, const std::string& param) { type_ = type; index_ = index; shm_name_ = param; } bool Device::validate_device() { // TODO: implement this return true; } } // namespace cucim::io
24.674074
117
0.636145
quasiben
fe43ad06492e326f2fa01ebb908c58ff93592581
5,589
cpp
C++
util/passwordanalyser.cpp
velezladonna/mwc-qt-wallet
bd241b91d28350e17e52a10208e663fcb992d7cc
[ "Apache-2.0" ]
1
2020-03-19T10:02:16.000Z
2020-03-19T10:02:16.000Z
util/passwordanalyser.cpp
velezladonna/mwc-qt-wallet
bd241b91d28350e17e52a10208e663fcb992d7cc
[ "Apache-2.0" ]
null
null
null
util/passwordanalyser.cpp
velezladonna/mwc-qt-wallet
bd241b91d28350e17e52a10208e663fcb992d7cc
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 The MWC Developers // // 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 "passwordanalyser.h" #include <QMap> #include <math.h> namespace util { PasswordAnalyser::PasswordAnalyser(QString _attentinColor, QString _happyColor ) : attentinColor(_attentinColor), happyColor(_happyColor), sequenceAnalyzer( dict::buldPasswordChackWordSequences() ) { Q_ASSERT(DICTS_NUM==4); dictionaries[0] = new dict::WordDictionary(":/resource/passwords-1k.dat"); dictionaryWeight[0] = 1.0; // 1 k include 10 & 100. Let's ban it to one symbol. In any case it is lett than 2 symbols dictionaries[1] = new dict::WordDictionary(":/resource/passwords-10k.dat"); dictionaryWeight[1] = 2.0; // 13.2 bits dictionaries[2] = new dict::WordDictionary(":/resource/passwords-100k.dat"); dictionaryWeight[2] = 2.5; // 16.6 bits (7 per char is ok) dictionaries[3] = new dict::WordDictionary(":/resource/passwords-1M.dat"); dictionaryWeight[3] = 3.0; // 20 bits } PasswordAnalyser::~PasswordAnalyser() { for ( auto d : dictionaries ) { delete d; } } // return String to print QPair<QString, bool> PasswordAnalyser::getPasswordQualityReport(const QString & pass, // in QVector<double> & weight, QStringList & seqWords, QStringList & dictWords) { // mwc713 password can't from '-', config parser doesn't handle that if (pass.startsWith("-")) { return QPair<QString, bool>("<font color="+attentinColor+">Password can't be started from '-' symbol.</font>", false); } // Check if all capital or lower case bool hasUpperCase = false; bool hasLowerCase = false; bool hasNumbers = false; bool hasSpecialSymbols = false; for (auto ch : pass) { if (ch.isLetter()) { if (ch.isUpper()) hasUpperCase = true; else hasLowerCase = true; continue; } if (ch.isNumber()) { hasNumbers = true; continue; } hasSpecialSymbols = true; } int alphabetSz = 1; if (hasUpperCase) alphabetSz += 32; if (hasLowerCase) alphabetSz += 32; if (hasNumbers) alphabetSz += 10; if (hasSpecialSymbols) alphabetSz += 32; // Minimum number of effective bits needed for the password to pass. double bitsMinSum = log2( 32.0 * 3 + 10 ) * 7; double singleCharBitWeight = log2(alphabetSz); // init all letters with a start weight weight.resize(pass.length()); for (auto & w : weight) w = singleCharBitWeight; seqWords.clear(); dictWords.clear(); if (pass.size()<PASS_MIN_LEN) return QPair<QString, bool>("<font color="+attentinColor+">Password must be at least "+ QString::number(PASS_MIN_LEN)+" symbols</font>", false); // Let's check for sequences. All sequence has a weight 1 for ( auto s : sequenceAnalyzer.detectSequences(pass, weight, singleCharBitWeight) ) if (s.length()>2) seqWords << s; // Let's check dictionary words for ( int t=0; t<DICTS_NUM; t++ ) { dictWords += dictionaries[t]->detectDictionaryWords(pass, weight, dictionaryWeight[t] * 7.0 ); // dictionary has the full alphabet - 7 bits } // Let's pack the dictionary words... for (int i=dictWords.size()-1; i>=0; i--) { bool included = false; for (int j = 0; j < dictWords.size(); j++) { if (i == j) continue; included = included || dictWords[j].contains(dictWords[i]); } if (included) dictWords.removeAt(i); } // Check if the password good enough double weightsSum = 0.0; for (auto w : weight) weightsSum += w; if (weightsSum+0.01 >= bitsMinSum) { // we are good to go! if ( seqWords.isEmpty() && dictWords.isEmpty() ) return QPair<QString, bool>("",true); // Great password QString respondStr = "<font color="+happyColor+">Your password is acceptable. But please note that it has:"; if (seqWords.size()>0) respondStr += "<br>Sequences: " + seqWords.join(", "); if (dictWords.size()>0) respondStr += "<br>Dictionary words: " + dictWords.join(", "); respondStr += "</font>"; return QPair<QString, bool>(respondStr, true); } // Here we are not good to go at all. if ( seqWords.isEmpty() && dictWords.isEmpty() ) { return QPair<QString, bool>("<font color="+attentinColor+">Please specify longer password or use more symbols variation.</font>", false); } QString respondStr = "<font color="+attentinColor+">Please specify longer password or don't use:"; if (seqWords.size()>0) respondStr += "<br>Sequences: " + seqWords.join(", "); if (dictWords.size()>0) respondStr += "<br>Dictionary words: " + dictWords.join(", "); respondStr += "</font>"; return QPair<QString, bool>(respondStr, false); } }
32.876471
147
0.61621
velezladonna
1cfb063105c3e5fc46dc00b661facfcacdec96ed
905
hpp
C++
src/n64/ROM.hpp
timschwartz/ultra64
9812cfb545f473ec3970dc65ba08ccb66acc4582
[ "BSD-3-Clause" ]
4
2019-01-24T04:13:09.000Z
2020-07-13T09:49:38.000Z
src/n64/ROM.hpp
timschwartz/ultra64
9812cfb545f473ec3970dc65ba08ccb66acc4582
[ "BSD-3-Clause" ]
null
null
null
src/n64/ROM.hpp
timschwartz/ultra64
9812cfb545f473ec3970dc65ba08ccb66acc4582
[ "BSD-3-Clause" ]
1
2020-08-17T04:34:04.000Z
2020-08-17T04:34:04.000Z
#pragma once #include <string> #include "N64.hpp" const uint32_t ROM_LOWHIGH = 0x80371240; const uint32_t ROM_HIGHLOW = 0x12408037; namespace ultra64 { typedef struct ROM_header { uint32_t signature; uint32_t clockrate; uint32_t pc; uint32_t release; uint32_t crc1; uint32_t crc2; uint64_t reserved_1; char name[20]; uint32_t reserved_2; uint32_t manufacturer_id; uint16_t cartridge_id; uint16_t country_code; } __attribute__((__packed__)) ROM_header; class ROM { public: ROM(); const ROM_header *header; const size_t size(); std::byte *get_pointer(); void Open(N64 *n64, std::string filename); std::byte *data = nullptr; private: std::string filename; size_t filesize = 0; void byte_swap(); }; }
21.547619
50
0.596685
timschwartz
e8019d1b05e2e4f47eec10b6ae326f753784dc88
473
cpp
C++
ted3d12/src/engine.cpp
Gibbeon/trace-engine
973d7803c92aa099bffa193513747fffadd93a94
[ "MIT" ]
null
null
null
ted3d12/src/engine.cpp
Gibbeon/trace-engine
973d7803c92aa099bffa193513747fffadd93a94
[ "MIT" ]
null
null
null
ted3d12/src/engine.cpp
Gibbeon/trace-engine
973d7803c92aa099bffa193513747fffadd93a94
[ "MIT" ]
null
null
null
/* #include "te/engine.h" #include "te/d3d12/renderingengine.h" using namespace te; extern bool_t te::_CreateRenderingEngineImpl(IRenderingEngine** pApp, ptr_t pInstance, string_t pszArg) { *pApp = new D3D12RenderingEngine(); return *pApp != nullptr; } */ #include "te/engine.h" #include "te/d3d12/gfxsystem.h" using namespace te; bool_t te::_CreateGfxSystemImpl(IGfxSystem** system, GfxSystemDesc& desc) { (*system) = new D3D12System(); return true; }
22.52381
103
0.72093
Gibbeon
e8050e5cefbe8ebb58aa70bd252541d45801c335
328
cpp
C++
ex3/expressions/Plus.cpp
ezenob8/HW3-TijnutMitkadem1-EzequielAndErez
ebb57d0bc1ef5570dc7799e10632dd63c98920b8
[ "Apache-2.0" ]
null
null
null
ex3/expressions/Plus.cpp
ezenob8/HW3-TijnutMitkadem1-EzequielAndErez
ebb57d0bc1ef5570dc7799e10632dd63c98920b8
[ "Apache-2.0" ]
null
null
null
ex3/expressions/Plus.cpp
ezenob8/HW3-TijnutMitkadem1-EzequielAndErez
ebb57d0bc1ef5570dc7799e10632dd63c98920b8
[ "Apache-2.0" ]
null
null
null
// // Created by erez on 07/11/2019. // #include "Plus.h" Plus::Plus(Expression *expression1, Expression *expression2) : BinaryOperator(expression1, expression2) { } double Plus::calculate() { return this->left->calculate() + this->right->calculate(); } Plus::~Plus() { delete this->right; delete this->left; }
17.263158
105
0.664634
ezenob8
e80f58282a4d866c625f9769147917de05ff484b
11,627
cpp
C++
src/cgame/cg_missionbriefing.cpp
jackeri/etjump
e17545b994b9edca8b2d11cba90fc311c9843bd8
[ "BSL-1.0", "MIT" ]
16
2019-09-07T18:08:08.000Z
2022-03-04T21:37:06.000Z
src/cgame/cg_missionbriefing.cpp
jackeri/etjump
e17545b994b9edca8b2d11cba90fc311c9843bd8
[ "BSL-1.0", "MIT" ]
121
2019-09-07T19:30:39.000Z
2022-01-31T20:59:48.000Z
src/cgame/cg_missionbriefing.cpp
jackeri/etjump
e17545b994b9edca8b2d11cba90fc311c9843bd8
[ "BSL-1.0", "MIT" ]
14
2019-09-07T17:20:40.000Z
2022-01-30T06:47:15.000Z
#include "cg_local.h" const char *CG_DescriptionForCampaign(void) { return cgs.campaignInfoLoaded ? cgs.campaignData.campaignDescription : NULL; } const char *CG_NameForCampaign(void) { return cgs.campaignInfoLoaded ? cgs.campaignData.campaignName : NULL; } qboolean CG_FindCampaignInFile(char *filename, const char *campaignShortName, cg_campaignInfo_t *info) { int handle; pc_token_t token; // char* dummy; qboolean campaignFound = qfalse; info->mapCount = 0; handle = trap_PC_LoadSource(filename); if (!handle) { trap_Print(va(S_COLOR_RED "file not found: %s\n", filename)); return qfalse; } if (!trap_PC_ReadToken(handle, &token)) { trap_PC_FreeSource(handle); return qfalse; } if (*token.string != '{') { trap_PC_FreeSource(handle); return qfalse; } while (trap_PC_ReadToken(handle, &token)) { if (*token.string == '}') { if (campaignFound) { trap_PC_FreeSource(handle); return qtrue; } if (!trap_PC_ReadToken(handle, &token)) { // eof trap_PC_FreeSource(handle); return qfalse; } if (*token.string != '{') { trap_Print(va(S_COLOR_RED "unexpected token '%s' inside: %s\n", token.string, filename)); trap_PC_FreeSource(handle); return qfalse; } info->mapCount = 0; } else if (!Q_stricmp(token.string, "shortname")) { if (!trap_PC_ReadToken(handle, &token)) // don't do a stringparse due to memory constraints { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } if (!Q_stricmp(token.string, campaignShortName)) { campaignFound = qtrue; } } else if (!Q_stricmp(token.string, "next") || !Q_stricmp(token.string, "image")) { //if( !PC_String_Parse( handle, &dummy ) ) { if (!trap_PC_ReadToken(handle, &token)) // don't do a stringparse due to memory constraints { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } } else if (!Q_stricmp(token.string, "description")) { if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } Q_strncpyz(info->campaignDescription, token.string, sizeof(info->campaignDescription)); } else if (!Q_stricmp(token.string, "name")) { if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } Q_strncpyz(info->campaignName, token.string, sizeof(info->campaignName)); } else if (!Q_stricmp(token.string, "maps")) { char *ptr, mapname[128], *mapnameptr; if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } ptr = token.string; while (*ptr) { mapnameptr = mapname; while (*ptr && *ptr != ';') { *mapnameptr++ = *ptr++; } if (*ptr) { ptr++; } *mapnameptr = '\0'; if (info->mapCount >= MAX_MAPS_PER_CAMPAIGN) { trap_Print(va(S_COLOR_RED "too many maps for a campaign inside: %s\n", filename)); trap_PC_FreeSource(handle); break; } Q_strncpyz(info->mapnames[info->mapCount++], mapname, MAX_QPATH); } } else if (!Q_stricmp(token.string, "maptc")) { if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } info->mapTC[0][0] = token.floatvalue; if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } info->mapTC[0][1] = token.floatvalue; info->mapTC[1][0] = 650 + info->mapTC[0][0]; info->mapTC[1][1] = 650 + info->mapTC[0][1]; } } trap_PC_FreeSource(handle); return qfalse; } qboolean CG_FindArenaInfo(char *filename, char *mapname, arenaInfo_t *info) { int handle; pc_token_t token; const char *dummy; qboolean found = qfalse; handle = trap_PC_LoadSource(filename); if (!handle) { trap_Print(va(S_COLOR_RED "file not found: %s\n", filename)); return qfalse; } if (!trap_PC_ReadToken(handle, &token)) { trap_PC_FreeSource(handle); return qfalse; } if (*token.string != '{') { trap_PC_FreeSource(handle); return qfalse; } while (trap_PC_ReadToken(handle, &token)) { if (*token.string == '}') { if (found) { // info->image = trap_R_RegisterShaderNoMip(va("levelshots/%s", mapname)); trap_PC_FreeSource(handle); return qtrue; } found = qfalse; if (!trap_PC_ReadToken(handle, &token)) { // eof trap_PC_FreeSource(handle); return qfalse; } if (*token.string != '{') { trap_Print(va(S_COLOR_RED "unexpected token '%s' inside: %s\n", token.string, filename)); trap_PC_FreeSource(handle); return qfalse; } } else if (!Q_stricmp(token.string, "objectives") || !Q_stricmp(token.string, "description") || !Q_stricmp(token.string, "type")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } } else if (!Q_stricmp(token.string, "longname")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } else { //char* p = info->longname; Q_strncpyz(info->longname, dummy, 128); // Gordon: removing cuz, er, no-one knows why it's here!... /* while(*p) { *p = toupper(*p); p++; }*/ } } else if (!Q_stricmp(token.string, "map")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } else { if (!Q_stricmp(dummy, mapname)) { found = qtrue; } } } else if (!Q_stricmp(token.string, "Timelimit") || !Q_stricmp(token.string, "AxisRespawnTime") || !Q_stricmp(token.string, "AlliedRespawnTime")) { if (!PC_Int_Parse(handle, (int *)&dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } } else if (!Q_stricmp(token.string, "lmsbriefing")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } else { Q_strncpyz(info->lmsdescription, dummy, sizeof(info->lmsdescription)); } } else if (!Q_stricmp(token.string, "briefing")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } else { Q_strncpyz(info->description, dummy, sizeof(info->description)); } } else if (!Q_stricmp(token.string, "alliedwintext")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } else { Q_strncpyz(info->alliedwintext, dummy, sizeof(info->description)); } } else if (!Q_stricmp(token.string, "axiswintext")) { if (!PC_String_Parse(handle, &dummy)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } else { Q_strncpyz(info->axiswintext, dummy, sizeof(info->description)); } } else if (!Q_stricmp(token.string, "mapposition_x")) { vec_t x; if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } x = token.floatvalue; info->mappos[0] = x; } else if (!Q_stricmp(token.string, "mapposition_y")) { vec_t y; if (!trap_PC_ReadToken(handle, &token)) { trap_Print(va(S_COLOR_RED "unexpected end of file inside: %s\n", filename)); trap_PC_FreeSource(handle); return qfalse; } y = token.floatvalue; info->mappos[1] = y; } } trap_PC_FreeSource(handle); return qfalse; } void CG_LocateCampaign(void) { /* int numdirs; char filename[MAX_QPATH]; char dirlist[1024]; char* dirptr; int i, dirlen; qboolean found = qfalse; // get all campaigns from .campaign files numdirs = trap_FS_GetFileList( "scripts", ".campaign", dirlist, 1024 ); dirptr = dirlist; for (i = 0; i < numdirs; i++, dirptr += dirlen+1) { dirlen = strlen(dirptr); strcpy(filename, "scripts/"); strcat(filename, dirptr); if(CG_FindCurrentCampaignInFile(filename, &cgs.campaignData)) { found = qtrue; break; } } if(!found) { return; } for(i = 0; i < cgs.campaignData.mapCount; i++ ) { Com_sprintf( filename, sizeof(filename), "scripts/%s.arena", cgs.campaignData.mapnames[i] ); // Gordon: horrible hack, but i dont plan to parse EVERY .arena to get a map briefing... if( !CG_FindArenaInfo( "scripts/wolfmp.arena", cgs.campaignData.mapnames[i], &cgs.campaignData.arenas[i] ) && !CG_FindArenaInfo( "scripts/wolfxp.arena", cgs.campaignData.mapnames[i], &cgs.campaignData.arenas[i] ) && !CG_FindArenaInfo( filename, cgs.campaignData.mapnames[i], &cgs.campaignData.arenas[i] )) { return; } } cgs.campaignInfoLoaded = qtrue;*/ int numdirs; char filename[MAX_QPATH]; char dirlist[1024]; char *dirptr; int i, dirlen; qboolean found = qfalse; // get all campaigns from .campaign files numdirs = trap_FS_GetFileList("scripts", ".campaign", dirlist, 1024); dirptr = dirlist; for (i = 0; i < numdirs; i++, dirptr += dirlen + 1) { dirlen = strlen(dirptr); Q_strncpyz(filename, "scripts/", MAX_QPATH); Q_strcat(filename, MAX_QPATH, dirptr); if (CG_FindCampaignInFile(filename, cgs.currentCampaign, &cgs.campaignData)) { found = qtrue; break; } } if (!found) { return; } for (i = 0; i < cgs.campaignData.mapCount; i++) { Com_sprintf(filename, sizeof(filename), "scripts/%s.arena", cgs.campaignData.mapnames[i]); // Gordon: horrible hack, but i dont plan to parse EVERY .arena to get a map briefing... if ( /*!CG_FindArenaInfo( "scripts/wolfmp.arena", cgs.campaignData.mapnames[i], &cgs.campaignData.arenas[i] ) && !CG_FindArenaInfo( "scripts/wolfxp.arena", cgs.campaignData.mapnames[i], &cgs.campaignData.arenas[i] ) &&*/ !CG_FindArenaInfo(filename, cgs.campaignData.mapnames[i], &cgs.campaignData.arenas[i])) { return; } } cgs.campaignInfoLoaded = qtrue; } void CG_LocateArena(void) { char filename[MAX_QPATH]; Com_sprintf(filename, sizeof(filename), "scripts/%s.arena", cgs.rawmapname); if ( /*!CG_FindArenaInfo( "scripts/wolfmp.arena", cgs.rawmapname, &cgs.arenaData ) && !CG_FindArenaInfo( "scripts/wolfxp.arena", cgs.rawmapname, &cgs.arenaData ) &&*/ !CG_FindArenaInfo(filename, cgs.rawmapname, &cgs.arenaData)) { return; } cgs.arenaInfoLoaded = qtrue; }
24.791045
145
0.640578
jackeri
e80f67d5e71858dac75aa5022028d5502649f30d
1,174
cpp
C++
src/gfx/extra/texture_composite.cpp
RedcraneStudio/redcrane-engine
4da8a7caedd6da5ffb7eda7da8c9a42396273bf6
[ "BSD-3-Clause" ]
5
2017-05-16T22:25:59.000Z
2020-02-10T20:19:35.000Z
src/gfx/extra/texture_composite.cpp
RedCraneStudio/redcrane-engine
4da8a7caedd6da5ffb7eda7da8c9a42396273bf6
[ "BSD-3-Clause" ]
1
2017-10-13T00:35:56.000Z
2017-10-13T00:35:56.000Z
src/gfx/extra/texture_composite.cpp
RedCraneStudio/redcrane-engine
4da8a7caedd6da5ffb7eda7da8c9a42396273bf6
[ "BSD-3-Clause" ]
2
2017-10-07T04:40:52.000Z
2021-09-27T05:59:05.000Z
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "texture_composite.h" namespace redc { Texture_Composite::Texture_Composite(Texture_Composite&& rhs) noexcept : ts_(std::move(rhs.ts_)) {} Texture_Composite& Texture_Composite:: operator=(Texture_Composite&& rhs) noexcept { ts_ = std::move(rhs.ts_); return *this; } void Texture_Composite::allocate_(Vec<int> const& extents, Image_Format form) noexcept { for(auto& ptr : ts_) { ptr->allocate(extents, form); } } void Texture_Composite:: blit_data_(Volume<int> const& vol, Color const* data) noexcept { for(auto& ptr : ts_) { ptr->blit_data(vol, data); } } void Texture_Composite::blit_data_(Volume<int> const& vol, float const* data) noexcept { for(auto& ptr : ts_) { ptr->blit_data(vol, data); } } void Texture_Composite::blit_data_(Volume<int> const& vol, Data_Type type, void const* data) noexcept { for(auto& ptr : ts_) { ptr->blit_data(vol, type, data); } } }
23.959184
76
0.584327
RedcraneStudio
e81214a188ef4146f02e7d3578625fe003c398c2
2,312
cpp
C++
src/states/CreditsState.cpp
CEDV-2016/mastermind
4cef7919a6dfa9f78887a25c409beea0448ca88e
[ "MIT" ]
null
null
null
src/states/CreditsState.cpp
CEDV-2016/mastermind
4cef7919a6dfa9f78887a25c409beea0448ca88e
[ "MIT" ]
null
null
null
src/states/CreditsState.cpp
CEDV-2016/mastermind
4cef7919a6dfa9f78887a25c409beea0448ca88e
[ "MIT" ]
null
null
null
#include "CreditsState.hpp" #include "SoundFXManager.hpp" template<> CreditsState* Ogre::Singleton<CreditsState>::msSingleton = 0; CreditsState::CreditsState() { _credits = NULL; } void CreditsState::enter () { _root = Ogre::Root::getSingletonPtr(); // Se recupera el gestor de escena y la cámara. _sceneMgr = _root->getSceneManager("SceneManager"); _camera = _sceneMgr->getCamera("MainCamera"); _viewport = _root->getAutoCreatedWindow()->getViewport(0); Ogre::Real tSpeed = 20.0; Ogre::Real deltaT = 0.1; Ogre::Vector3 vt(0, 0, 0); vt += Ogre::Vector3(2, 0, 0); _camera->moveRelative(vt * deltaT * tSpeed); createGUI(); SoundFXManager::getSingletonPtr()->load("paper.wav")->play(); _exitGame = false; } void CreditsState::exit () { _credits->hide(); Ogre::Real tSpeed = 20.0; Ogre::Real deltaT = 0.1; Ogre::Vector3 vt(0, 0, 0); vt += Ogre::Vector3(-2, 0, 0); _camera->moveRelative(vt * deltaT * tSpeed); } void CreditsState::pause () { } void CreditsState::resume () { } bool CreditsState::frameStarted (const Ogre::FrameEvent& evt) { return true; } bool CreditsState::frameEnded (const Ogre::FrameEvent& evt) { if (_exitGame) return false; return true; } void CreditsState::keyPressed (const OIS::KeyEvent &e) { } void CreditsState::keyReleased (const OIS::KeyEvent &e) { } void CreditsState::mouseMoved (const OIS::MouseEvent &e) { } void CreditsState::mousePressed (const OIS::MouseEvent &e, OIS::MouseButtonID id) { } void CreditsState::mouseReleased (const OIS::MouseEvent &e, OIS::MouseButtonID id) { } CreditsState* CreditsState::getSingletonPtr () { return msSingleton; } CreditsState& CreditsState::getSingleton () { assert(msSingleton); return *msSingleton; } void CreditsState::createGUI(){ if(_credits == NULL){ //Config Window _credits = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("credits.layout"); CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->addChild(_credits); CEGUI::Window* backButton = _credits->getChild("BackButton"); backButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CreditsState::back, this)); } else{ _credits->show(); } } bool CreditsState::back(const CEGUI::EventArgs &e) { popState(); return true; }
17.922481
117
0.699394
CEDV-2016
e815a9940b89d2f759dbe1e13bf36ef0bdd0aa33
13,380
cpp
C++
PolyhedronControl.cpp
getdunne/Voxvu
48d57a4eff7ca97f5562e79bce9d86e5e65a7d18
[ "MIT" ]
null
null
null
PolyhedronControl.cpp
getdunne/Voxvu
48d57a4eff7ca97f5562e79bce9d86e5e65a7d18
[ "MIT" ]
null
null
null
PolyhedronControl.cpp
getdunne/Voxvu
48d57a4eff7ca97f5562e79bce9d86e5e65a7d18
[ "MIT" ]
1
2021-04-09T08:24:03.000Z
2021-04-09T08:24:03.000Z
#include "stdafx.h" #include <math.h> #include "PolyhedronControl.h" //-------------------------------------------------------------- // Constructor //-------------------------------------------------------------- PolyhedronControl::PolyhedronControl () { m_pModel = NULL; m_zoomFactor = 1.0; m_panHoriz = 0.; m_panVert = 0.; m_pFaceSelectProc = NULL; m_bABVisible = TRUE; m_bTwoPass = FALSE; } //-------------------------------------------------------------- // Destructor //-------------------------------------------------------------- PolyhedronControl::~PolyhedronControl () { } //-------------------------------------------------------------- // SetPixelFormat must be called (after SetOwner!) to set up // embedded SuccessiveRefinementBuffer object //-------------------------------------------------------------- void PolyhedronControl::SetPixelFormat (int bytesPerPixel, int nColors, LPRGBQUAD lpQuadTable) { ASSERT(m_pOwner); m_srBuffer.SetOwner(m_pOwner); m_srBuffer.SetPixelFormat(bytesPerPixel,nColors,lpQuadTable); } //-------------------------------------------------------------- // GetViewMatrix: return transformation matrix mapping object to // screen coordinates. //-------------------------------------------------------------- Matrix4x4 PolyhedronControl::GetViewMatrix () { // origin offset matrix Matrix4x4 O; O.MakeTranslation(-m_origin.x, -m_origin.y, -m_origin.z); // rotation matrix Matrix4x4 R = m_orientQ.RotMatrix(); // scale factor: when m_zoomFactor=1.0, longest model diagonal // should be 95% of minimum display dimension double w = m_bbox.Width(); double h = m_bbox.Height(); double minWH = (w<h) ? w : h; double sf = (0.95*minWH*m_zoomFactor)/m_pModel->GetDiagonal(); Matrix4x4 S; S.MakeDilation(sf); // screen-plane translation Matrix4x4 T; T.MakeTranslation(w*0.5 + m_panHoriz, h*0.5 + m_panVert, 0.); return O*R*S*T; } //-------------------------------------------------------------- // GetInvViewMatrix: return transformation matrix mapping screen // to object coordinates (exact inverse of GetViewMatrix() above) //-------------------------------------------------------------- Matrix4x4 PolyhedronControl::GetInvViewMatrix () { // origin offset matrix Matrix4x4 O; O.MakeTranslation(m_origin.x, m_origin.y, m_origin.z); // rotation matrix Matrix4x4 R = (m_orientQ.RotMatrix()).Transpose(); // scale factor: when m_zoomFactor=1.0, longest model diagonal // should be 95% of minimum display dimension double w = m_bbox.Width(); double h = m_bbox.Height(); double minWH = (w<h) ? w : h; double sf = (0.95*minWH*m_zoomFactor)/m_pModel->GetDiagonal(); Matrix4x4 S; S.MakeDilation(1./sf); // screen-plane translation Matrix4x4 T; T.MakeTranslation(-(w*0.5 + m_panHoriz), -(h*0.5 + m_panVert), 0.); return T*S*R*O; } //-------------------------------------------------------------- // SetRenderingEnvironment: a wrapper for SetRenderer() to make // sure we get the right kind of renderer (a PolyhedronRenderer) // and set it up properly. //-------------------------------------------------------------- void PolyhedronControl::SetRenderingEnvironment ( PolyhedronRenderer* pr, VoxelArray* pVoxArray, Matrix4x4* pObjectToTexture) { m_srBuffer.SetRenderer(pr); m_pObjToTex = pObjectToTexture; pr->SetDrawBuffer(m_srBuffer.GetDrawBufferPtr()); pr->SetVoxelArray(pVoxArray); pr->SetPolyhedron(&m_spoly); pr->SetTransformation(GetInvViewMatrix()*(*pObjectToTexture)); // render once now m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // Set rotational orientation to given absolute //-------------------------------------------------------------- void PolyhedronControl::SetRotation (Quaternion& rotQ) { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_orientQ = rotQ; m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // As above but relative //-------------------------------------------------------------- void PolyhedronControl::Rotate (Quaternion& deltaQ) { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_orientQ = deltaQ * m_orientQ; m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // Set Zoom factor to given absolute //-------------------------------------------------------------- void PolyhedronControl::Zoom (double zoomFactor) { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_zoomFactor = zoomFactor; m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // Set horizontal panning factor to given absolute //-------------------------------------------------------------- void PolyhedronControl::PanHoriz (double panH) { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_panHoriz = panH; m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // Set vertical panning factor to given absolute //-------------------------------------------------------------- void PolyhedronControl::PanVert (double panV) { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_panVert = panV; m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // SelectFace : given a point in screen space, return the 0-based // index of the model face whose screen projection contains that // point, or -1 if there is none. //-------------------------------------------------------------- int PolyhedronControl::SelectFace (CPoint point) { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_pModel->SelectFace(-1); for (int i=0; i < m_spoly.GetFaceCount(); ++i) if (m_spoly.plane[i].n.z < 0. && m_spoly.poly[i].GetVertexCount() > 2 && m_spoly.poly[i].ContainsPoint2D(point)) { if (i > 5) m_pModel->SelectFace(i); else m_pModel->CloneFace(i); m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetPolyhedron(&m_spoly); return m_pModel->GetSelectedFace(); } return -1; } //-------------------------------------------------------------- // Model has been changed. Update screen representation. //-------------------------------------------------------------- void PolyhedronControl::ModelChanged () { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetPolyhedron(&m_spoly); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // Rendering conditions have changed. Update screen. //-------------------------------------------------------------- void PolyhedronControl::RenderingConditionsChanged () { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.InterruptSync(); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // StartBackgroundRendering : Use after calls to SetRotation, // Zoom, etc. Just a wrapper for SuccessiveRefinementBuffer::StartBestPass(). //-------------------------------------------------------------- void PolyhedronControl::StartBackgroundRendering () { ASSERT(m_srBuffer.m_pRenderer); m_srBuffer.StartBestPass(); } //-------------------------------------------------------------- // SetModel //-------------------------------------------------------------- void PolyhedronControl::SetModel (PolyhedronModel* pm) { m_pModel = pm; m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); } //-------------------------------------------------------------- // Draw : displays polyhedron outlines and arcball //-------------------------------------------------------------- inline CPoint ConvPt(const Vector3 &v) { return CPoint(int(v.x+0.5),int(v.y+0.5)); } void PolyhedronControl::Draw (CDC* pDC) { // first draw from our rendering buffer m_srBuffer.Draw(pDC); // set up for drawing in this control's bounding box only CRgn rgn; rgn.CreateRectRgnIndirect(m_bbox); pDC->SelectClipRgn(&rgn); pDC->OffsetViewportOrg(m_bbox.left,m_bbox.top); int selectedFace = m_pModel->GetSelectedFace(); // draw outlines of non-selected front faces of box in white HGDIOBJ pOldPen = pDC->SelectStockObject(WHITE_PEN); int side; for (side=0; side<m_spoly.GetFaceCount(); ++side) { if (m_spoly.poly[side].GetVertexCount() < 3) continue; if (m_spoly.plane[side].n.z > 0.) continue; if (side == selectedFace) continue; pDC->MoveTo(ConvPt(m_spoly.poly[side].v[0])); for (int vert=1; vert<m_spoly.poly[side].GetVertexCount(); ++vert) pDC->LineTo(ConvPt(m_spoly.poly[side].v[vert])); pDC->LineTo(ConvPt(m_spoly.poly[side].v[0])); } // outline selected face in red (if visible) CPen redPen(PS_SOLID,0,RGB(255,0,0)); pDC->SelectObject(&redPen); side = selectedFace; if (side >= 0 && m_spoly.poly[side].GetVertexCount() > 2 && m_spoly.plane[side].n.z < 0.) { pDC->MoveTo(ConvPt(m_spoly.poly[side].v[0])); for (int vert=1; vert<m_spoly.poly[side].GetVertexCount(); ++vert) pDC->LineTo(ConvPt(m_spoly.poly[side].v[vert])); pDC->LineTo(ConvPt(m_spoly.poly[side].v[0])); } // clean up pDC->SetViewportOrg(0,0); pDC->SelectObject(pOldPen); pDC->SelectClipRgn(NULL); rgn.DeleteObject(); // draw arcball circle if (m_bABVisible) ArcballControl::Draw(pDC); } //-------------------------------------------------------------- // SetBBox //-------------------------------------------------------------- void PolyhedronControl::SetBBox (const CRect& rect) { // resize arcball ArcballControl::SetBBox(rect); // resize embedded SuccessiveRefinementBuffer m_srBuffer.SetBBox(rect); // if we're ready, resize displayed polyhedron if (m_srBuffer.m_pRenderer) { m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); m_srBuffer.DoFirstPass(); } } //-------------------------------------------------------------- // Click //-------------------------------------------------------------- void PolyhedronControl::Click (UINT nFlags, CPoint point) { m_lastMouse = point; m_saveQ = m_orientQ; int selFace = m_pModel->GetSelectedFace(); m_bTiltingFace = (nFlags & MK_CONTROL) != 0 && (selFace >= 0); if (m_bTiltingFace) { m_saveFace = m_pModel->m_box.plane[selFace]; Plane p = m_saveFace.Transform(GetViewMatrix()); Vector3 pivot; pivot.x = point.x - m_bbox.left; pivot.y = point.y - m_bbox.top; pivot.z = p.ZfromXY(pivot.x,pivot.y); m_pivot = pivot.Aff(GetInvViewMatrix()); } } //-------------------------------------------------------------- // Drag //-------------------------------------------------------------- void PolyhedronControl::Drag (UINT nFlags, CPoint point) { Vector3 p0,p1; ArcballTrans(m_lastMouse,&p0); ArcballTrans(point,&p1); Quaternion q(p0.Cross(p1),p0.Dot(p1)); if (m_bTiltingFace) { int selFace = m_pModel->GetSelectedFace(); Matrix4x4 VR = m_saveQ.RotMatrix(); Matrix4x4 R = VR * q.RotMatrix() * (VR.Transpose()); m_pModel->m_box.plane[selFace].n = (m_saveFace.n).Lin(R); (m_pModel->m_box.plane[selFace].n).Normalize(); m_pModel->m_box.plane[selFace].d = (m_pModel->m_box.plane[selFace].n).Dot(m_pivot); m_pModel->RecomputePolygons(); ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetPolyhedron(&m_spoly); } else { m_orientQ = q * m_saveQ; ((PolyhedronRenderer*)m_srBuffer.m_pRenderer)-> SetTransformation(GetInvViewMatrix()*(*m_pObjToTex)); } m_pModel->m_box.Transform(GetViewMatrix(),&m_spoly); m_srBuffer.DoFirstPass(); Draw(m_pOwner->GetDC()); } //-------------------------------------------------------------- // Release //-------------------------------------------------------------- void PolyhedronControl::Release (UINT nFlags, CPoint point) { if (m_bTiltingFace && m_pFaceSelectProc) (*m_pFaceSelectProc)(m_pOwner,m_pModel->GetSelectedFace()); m_bTiltingFace = FALSE; m_srBuffer.StartBestPass(); } //-------------------------------------------------------------- // DoubleClick //-------------------------------------------------------------- void PolyhedronControl::DoubleClick (UINT nFlags, CPoint point) { m_srBuffer.InterruptSync(); point.Offset(-m_bbox.TopLeft()); int nFace = SelectFace(point); if (m_pFaceSelectProc) (*m_pFaceSelectProc)(m_pOwner,nFace); }
31.857143
85
0.577354
getdunne
e81ca5a63b2a5797737f9aad99a3912c833e5904
4,342
cpp
C++
etc/dp/p.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
3
2019-06-25T06:17:38.000Z
2019-07-13T15:18:51.000Z
etc/dp/p.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
etc/dp/p.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
#pragma region template 1.1 #pragma region def #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<ll> vi; typedef pair<ll, ll> ii; #define REP(i, n) for (ll i = 0; i < (n); ++i) #define REP1(i, n) for (ll i = 1; i <= (n); ++i) #define OUT(x) cout << (x) << endl; #define OUTA(a) \ REP(i, (a).size()) { cout << (a[i]) << (i == (a).size() - 1 ? "\n" : " "); } #define ALL(a) (a).begin(), (a).end() #define SORT(a) sort(ALL(a)) #define RSORT(a) \ SORT(a); \ reverse(ALL(a)) const ll INF = 1e18; const ll MOD = 1e9 + 7; #pragma endregion enddef #pragma region mint 1.0 struct mint { ll a; mint(ll x = 0) : a((x % MOD + MOD) % MOD) {} mint pow(ll rhs) { ll exp = rhs; mint res = mint(1); mint p = mint(a); while (exp) { if (exp & 1) { res *= p; } exp >>= 1; p *= p; } return res; } mint pow(mint rhs) { return pow(rhs.a); } mint &operator+=(ll rhs) { a += rhs; if (a >= MOD) { a -= MOD; } return *this; } mint &operator+=(mint rhs) { *this += rhs.a; return *this; } mint &operator-=(ll rhs) { if (a < rhs) { a += MOD; } a -= rhs; return *this; } mint &operator-=(mint rhs) { *this -= rhs.a; return *this; } mint &operator*=(ll rhs) { if (rhs < 0) { rhs += MOD; } a = a * rhs % MOD; return *this; } mint &operator*=(mint rhs) { *this *= rhs.a; return *this; } mint &operator/=(ll rhs) { *this *= mint(rhs).pow(MOD - 2); return *this; } mint &operator/=(const mint rhs) { *this /= rhs.a; return *this; } mint &operator++() { *this += 1; return *this; } mint &operator++(int) { *this += 1; return *this; } mint &operator--() { *this -= 1; return *this; } mint &operator--(int) { *this -= 1; return *this; } }; mint operator+(const mint &lhs, const mint &rhs) { return mint(lhs.a) += rhs; } mint operator+(const mint &lhs, const ll &rhs) { return mint(lhs.a) += rhs; } mint operator+(const ll &lhs, mint &rhs) { return mint(lhs) += rhs; } mint operator-(const mint &lhs, const mint &rhs) { return mint(lhs.a) -= rhs; } mint operator-(const mint &lhs, const ll &rhs) { return mint(lhs.a) -= rhs; } mint operator-(const ll &lhs, const mint &rhs) { return mint(lhs) -= rhs; } mint operator*(const mint &lhs, const mint &rhs) { return mint(lhs.a) *= rhs; } mint operator*(const mint &lhs, const ll &rhs) { return mint(lhs.a) *= rhs; } mint operator*(const ll &lhs, const mint &rhs) { return mint(lhs) *= rhs; } mint operator/(const mint &lhs, const mint &rhs) { return mint(lhs.a) /= rhs; } mint operator/(const mint &lhs, const ll &rhs) { return mint(lhs.a) /= rhs; } mint operator/(const ll &lhs, const mint &rhs) { return mint(lhs) /= rhs; } istream &operator>>(istream &is, mint &i) { is >> i.a; return is; } ostream &operator<<(ostream &os, const mint &i) { os << i.a; return os; } #pragma endregion mint vector<vi> G; vector<mint> dp; vector<bool> memo; mint f(ll i, ll p) { if (memo[i]) { return dp[i]; } mint w = 1; mint b = 1; REP(k, G[i].size()) { ll j = G[i][k]; if (j != p) { w *= f(j, i); REP(k2, G[j].size()) { ll j2 = G[j][k2]; if (j2 != i) { b *= f(j2, j); } } } } dp[i] = w + b; memo[i] = true; return dp[i]; } int main() { ll N; cin >> N; vi x(N - 1), y(N - 1); REP(i, N - 1) { cin >> x[i] >> y[i]; } G = vector<vi>(N + 1); REP(i, N - 1) { G[x[i]].push_back(y[i]); G[y[i]].push_back(x[i]); } dp = vector<mint>(N + 1); memo = vector<bool>(N + 1); mint ans = f(1, 0); OUT(ans); } #pragma endregion template
18.243697
80
0.447259
wotsushi
e81ca6ab5477464afe6677b98030ea343a4af254
2,706
cpp
C++
projects/atLib/source/Data/Interchange/atCSV.cpp
mbatc/atLib
7e3a69515f504a05a312d234291f02863e291631
[ "MIT" ]
1
2019-09-17T18:02:16.000Z
2019-09-17T18:02:16.000Z
projects/atLib/source/Data/Interchange/atCSV.cpp
mbatc/atLib
7e3a69515f504a05a312d234291f02863e291631
[ "MIT" ]
null
null
null
projects/atLib/source/Data/Interchange/atCSV.cpp
mbatc/atLib
7e3a69515f504a05a312d234291f02863e291631
[ "MIT" ]
null
null
null
#include "atCSV.h" #include "atScan.h" atCSV::atCSV(const atString &csv) { Parse(csv); } atCSV::atCSV(atCSV &&csv) { *this = std::move(csv); } atCSV::atCSV(const atCSV &csv) { *this = csv; } atCSV& atCSV::operator=(atCSV &&rhs) { std::swap(m_cells, rhs.m_cells); return *this; } atCSV& atCSV::operator=(const atCSV &rhs) { m_cells = rhs.m_cells; return *this; } bool atCSV::Parse(const atString &csv) { *this = atCSV(); if (csv.length() == 0) return false; atVector<atString> rows = csv.split("\r\n", true); for (const atString &row : rows) { atVector<atString> cols = row.split(',', false); m_cells.push_back(std::move(cols)); } return false; } int64_t atCSV::AsInt(const int64_t &row, const int64_t &column) const { const atString *pVal = TryGetValue(row, column); return pVal ? atScan::Int(*pVal) : 0; } bool atCSV::AsBool(const int64_t &row, const int64_t &column) const { const atString *pVal = TryGetValue(row, column); return pVal ? atScan::Bool(*pVal) : 0; } double atCSV::AsFloat(const int64_t &row, const int64_t &column) const { const atString *pVal = TryGetValue(row, column); return pVal ? atScan::Float(*pVal) : 0; } atString atCSV::AsString(const int64_t &row, const int64_t &column) const { const atString *pVal = TryGetValue(row, column); return pVal ? *pVal : ""; } void atCSV::SetValue(const atString &value, const int64_t &row, const int64_t &col) { atString *pCell = TryGetValue(row, col); if (pCell) *pCell = value; else AddValue(value, row, col); } bool atCSV::AddValue(const atString &value, const int64_t &row, const int64_t &col) { atString *pCell = TryGetValue(row, col); if (pCell && pCell->length() > 0) return false; if (!pCell) { m_cells.resize(atMax(m_cells.size(), row + 1)); m_cells[row].resize(atMax(m_cells[row].size(), col + 1)); pCell = TryGetValue(row, col); if (!pCell) return false; } *pCell = value; return true; } const atString* atCSV::TryGetValue(const int64_t &row, const int64_t &col) const { return col >= 0 && col < GetColCount(row) ? &m_cells[row][col] : nullptr; } atString* atCSV::TryGetValue(const int64_t &row, const int64_t &col) { return col >= 0 && col < GetColCount(row) ? &m_cells[row][col] : nullptr; } int64_t atCSV::GetRowCount() const { return m_cells.size(); } int64_t atCSV::GetColCount(const int64_t &row) const { return row >= 0 && row < GetRowCount() ? m_cells[row].size() : 0; } atString atToString(const atCSV &csv) { atVector<atString> joinedRows; for (const atVector<atString> &row : csv.m_cells) joinedRows.push_back(atString::join(row, ",", false)); return atString::join(joinedRows, "\n", false); }
26.529412
158
0.66371
mbatc
e81fd29d03dfac29e2fa3c41b7ca4b004c30b13c
922
hpp
C++
foundation/src/Win32/PluginManagerImpl.hpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
5
2018-08-16T00:55:33.000Z
2020-06-19T14:30:17.000Z
foundation/src/Win32/PluginManagerImpl.hpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
foundation/src/Win32/PluginManagerImpl.hpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
#pragma once #ifndef PLUGIN_MANAGER_IMPL_WIN32_HPP #define PLUGIN_MANAGER_IMPL_WIN32_HPP #include "CoreAPIs.hpp" #include <unordered_map> #include <string> #define WIN32_MEAN_AND_LEAN #include <windows.h> using plugin_handle = HMODULE; struct PluginManagerImpl { PluginManagerImpl(); void LoadPlugin(const char* fname); void UnloadPlugin(const char* fname); void* GetEngineAPI(uint32_t api_id); void LoadedPlugins(uint32_t * num_plugins, uint32_t * plugin_ids) const; Plugin_API* GetCoreAPI(uint32_t api_id); std::unordered_map<std::string, plugin_handle> plugins; std::unordered_map<std::string, uint32_t> pluginFilesToIDMap; // Each plugin should expose a Plugin_API* std::unordered_map<uint32_t, Plugin_API*> coreApiPointers; // The unique plugin APIs loaded are stored here std::unordered_map<uint32_t, void*> apiPointers; }; #endif //!PLUGIN_MANAGER_IMPL_WIN32_HPP
32.928571
76
0.765727
fuchstraumer
e8207a924f4e349426d534ea52098fe14715cec0
4,132
cpp
C++
character/character.cpp
Jorgee1/Turn-Battle-System
c4eb39dc89b58629f71e56c63d8b0d3c6a745b08
[ "MIT" ]
null
null
null
character/character.cpp
Jorgee1/Turn-Battle-System
c4eb39dc89b58629f71e56c63d8b0d3c6a745b08
[ "MIT" ]
null
null
null
character/character.cpp
Jorgee1/Turn-Battle-System
c4eb39dc89b58629f71e56c63d8b0d3c6a745b08
[ "MIT" ]
null
null
null
#include "Character.h" // Status Status::Status(string name, int value){ this->name = name; this->value = value; } string Status::get_name() const{ return name; } int Status::get_value() const{ return value; } void Status::set_value(int value) { this->value = value; } void Status::add_value(int value) { this->value+= value; } // Characters Character::Character(){ NAME = ""; character_stats.push_back(Status("HP", 1)); character_stats.push_back(Status("Max_HP", 1)); character_stats.push_back(Status("Attack", 1)); character_stats.push_back(Status("Defence", 1)); LEVEL = 1; } void Character::init(string name, int max_hp, int attack, int defense, int level){ NAME = name; character_stats[HP].set_value(max_hp); character_stats[MAX_HP].set_value(max_hp); character_stats[ATTACK].set_value(attack); character_stats[DEFFENCE].set_value(defense); LEVEL = level; } // Getters Status Character::get_hp() const { return character_stats[HP]; } Status Character::get_max_hp() const { return character_stats[MAX_HP]; } Status Character::get_attk() const { return character_stats[ATTACK]; } Status Character::get_def() const { return character_stats[DEFFENCE]; } string Character::get_name() const { return NAME; }; vector<Status> Character::get_stats() const{ return character_stats; } // Setters void Character::set_hp(int value){ if (value < 0){ character_stats[HP].set_value(0); }else if (value > character_stats[MAX_HP].get_value()){ character_stats[HP].set_value(character_stats[MAX_HP].get_value()); }else{ character_stats[HP].set_value(value); } } // Util string Character::repr() const{ return "<Character " + NAME + ": " + "[" + to_string(character_stats[HP].get_value()) + "/" + to_string(character_stats[MAX_HP].get_value()) + "] LVL " + to_string(LEVEL) + ">"; } // Hero Hero::Hero(){ character_stats.push_back(Status("Experience", 0)); character_stats.push_back(Status("Next Level", 10)); } Hero::Hero(string name, int max_hp, int attack, int defense, int level){ init(name, max_hp, attack, defense, level); } void Hero::init(string name, int max_hp, int attack, int defense, int level){ NAME = name; character_stats[HP].set_value(max_hp); character_stats[MAX_HP].set_value(max_hp); character_stats[ATTACK].set_value(attack); character_stats[DEFFENCE].set_value(defense); character_stats[EXPEREIENCE].set_value(0); character_stats[NEXT_LEVEL].set_value(10); LEVEL = level; } Status Hero::get_exp() const { return character_stats[EXPEREIENCE]; }; Status Hero::get_next_level_exp() const { return character_stats[NEXT_LEVEL]; }; void Hero::add_exp(int value){ while(value>0){ if(value >= character_stats[NEXT_LEVEL].get_value()-character_stats[EXPEREIENCE].get_value()){ value = value - (character_stats[NEXT_LEVEL].get_value()-character_stats[EXPEREIENCE].get_value()); level_up(); }else{ character_stats[EXPEREIENCE].add_value(value); value = 0; } } } void Hero::level_up(){ LEVEL += 1; character_stats[MAX_HP].add_value(5); character_stats[ATTACK].add_value(1); character_stats[DEFFENCE].add_value(1); character_stats[EXPEREIENCE].set_value(0); character_stats[NEXT_LEVEL].add_value(2); } string Hero::repr() const{ return "<Hero " + NAME + " : " + "[" + to_string(character_stats[HP].get_value()) + "/" + to_string(character_stats[MAX_HP].get_value()) + "] LVL " + to_string(LEVEL) + ">"; } // Monster Monster::Monster(){ EXP_REWARD = 0; } void Monster::init(string name, int max_hp, int attack, int defense, int level, int reward_exp){ NAME = name; character_stats[HP].set_value(max_hp); character_stats[MAX_HP].set_value(max_hp); character_stats[ATTACK].set_value(attack); character_stats[DEFFENCE].set_value(defense); character_stats.push_back(Status("Defence", defense)); LEVEL = level; EXP_REWARD = reward_exp; } int Monster::get_exp_reward() const{ return EXP_REWARD; }
32.031008
111
0.681994
Jorgee1
e823c94803c959d49297271277322777bb5b6ce4
123
cpp
C++
src/event.cpp
ricky26/netlib
f4d86475220ae32f0ab25e83fb8dc004f5f1af60
[ "BSD-2-Clause" ]
1
2020-07-04T01:11:38.000Z
2020-07-04T01:11:38.000Z
src/event.cpp
ricky26/netlib
f4d86475220ae32f0ab25e83fb8dc004f5f1af60
[ "BSD-2-Clause" ]
null
null
null
src/event.cpp
ricky26/netlib
f4d86475220ae32f0ab25e83fb8dc004f5f1af60
[ "BSD-2-Clause" ]
null
null
null
#include "netlib\event.h" namespace netlib { // // event // event::event(void *_sender) : mSender(_sender) { } }
8.785714
28
0.601626
ricky26
e826d9e5b358a2bfe554d168d0617f777b5aa6b9
666
hpp
C++
android-30/javax/xml/validation/Schema.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/javax/xml/validation/Schema.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/javax/xml/validation/Schema.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../../JObject.hpp" namespace javax::xml::validation { class Validator; } namespace javax::xml::validation { class ValidatorHandler; } namespace javax::xml::validation { class Schema : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit Schema(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} Schema(QJniObject obj); // Constructors // Methods javax::xml::validation::Validator newValidator() const; javax::xml::validation::ValidatorHandler newValidatorHandler() const; }; } // namespace javax::xml::validation
20.181818
147
0.696697
YJBeetle
e82b1886453ec3cfa36191e3b745a2cb4a841245
3,395
cpp
C++
src/Xenon/GPU/ShaderProgram.cpp
OutOfTheVoid/ProjectRed
801327283f5a302be130c90d593b39957c84cce5
[ "MIT" ]
1
2020-06-14T06:14:50.000Z
2020-06-14T06:14:50.000Z
src/Xenon/GPU/ShaderProgram.cpp
OutOfTheVoid/ProjectRed
801327283f5a302be130c90d593b39957c84cce5
[ "MIT" ]
null
null
null
src/Xenon/GPU/ShaderProgram.cpp
OutOfTheVoid/ProjectRed
801327283f5a302be130c90d593b39957c84cce5
[ "MIT" ]
null
null
null
#include <Xenon/GPU/ShaderProgram.h> #include <Xenon/GPU/Context.h> #include <stdlib.h> Xenon::GPU::ShaderProgram :: ShaderProgram ( const std :: string & Name ): RefCounted ( 0 ), Name ( Name ), Allocated ( false ), SHandle ( 0 ), LinkIteration ( - 1 ), InfoLog ( "" ) { } Xenon::GPU::ShaderProgram :: ~ShaderProgram () { } void Xenon::GPU::ShaderProgram :: GPUResourceAlloc () { if ( Allocated ) return; SHandle = glCreateProgram (); if ( SHandle != 0 ) Allocated = true; } void Xenon::GPU::ShaderProgram :: GPUResourceFree () { if ( ! Allocated ) return; glDeleteProgram ( SHandle ); Allocated = false; } void Xenon::GPU::ShaderProgram :: Bind () { if ( ! Allocated ) { GPUResourceAlloc (); if ( ! Allocated ) return; } if ( Context :: CurrentBoundContext -> CurrentBoundShader != this ) { glUseProgram ( SHandle ); Context :: CurrentBoundContext -> CurrentBoundShader = this; } } bool Xenon::GPU::ShaderProgram :: Link () { glLinkProgram ( SHandle ); GLint IsLinked = GL_FALSE; glGetProgramiv ( SHandle, GL_LINK_STATUS, & IsLinked ); if ( IsLinked ) { LinkIteration ++; return true; } return false; } const std :: string & Xenon::GPU::ShaderProgram :: GetInfoLog () { FreeInfoLog (); GLint MaxLength = 0; glGetProgramiv ( SHandle, GL_INFO_LOG_LENGTH, & MaxLength ); char * TempLogStore = reinterpret_cast <char *> ( malloc ( sizeof ( char ) * ( MaxLength + 1 ) ) ); if ( TempLogStore != NULL ) { glGetProgramInfoLog ( SHandle, MaxLength, & MaxLength, TempLogStore ); TempLogStore [ MaxLength ] = '\0'; InfoLog = TempLogStore; delete TempLogStore; } return InfoLog; } void Xenon::GPU::ShaderProgram :: FreeInfoLog () { InfoLog.clear (); InfoLog.shrink_to_fit (); } bool Xenon::GPU::ShaderProgram :: GPUResourceAllocated () { return Allocated; } void Xenon::GPU::ShaderProgram :: AddShader ( IShader & Shader ) { if ( ! Allocated ) { GPUResourceAlloc (); if ( ! Allocated ) { XENON_LOG_ERROR ( "Failed to allocate shader program \"%s\" for adding shader \"%s\"!\n", Name.c_str (), Shader.GetName ().c_str () ); return; } } glAttachShader ( SHandle, Shader.GetSHandle () ); } void Xenon::GPU::ShaderProgram :: RemoveShader ( IShader & Shader ) { if ( ! Allocated ) { XENON_LOG_ERROR ( "Attempted to remove a shader from non-allocated shader program \"%s\"!\n", Name.c_str () ); return; } Bind (); glDetachShader ( SHandle, Shader.GetSHandle () ); } GLint Xenon::GPU::ShaderProgram :: GetAttributeLocation ( const GLchar * Attribute ) { if ( ! Allocated ) { XENON_LOG_ERROR ( "Attempted to fetch attribute location from non-allocated shader program \"%s\"!\n", Name.c_str () ); return 0; } return glGetAttribLocation ( SHandle, Attribute ); } GLint Xenon::GPU::ShaderProgram :: GetUniformLocation ( const GLchar * Attribute ) { if ( ! Allocated ) { XENON_LOG_ERROR ( "Attempted to fetch attribute location from non-allocated shader program \"%s\"!\n", Name.c_str () ); return 0; } return glGetUniformLocation ( SHandle, Attribute ); } const std :: string & Xenon::GPU::ShaderProgram :: GetName () { return Name; } int64_t Xenon::GPU::ShaderProgram :: GetLinkIteration () { return LinkIteration; }
15.645161
137
0.635052
OutOfTheVoid
e82c5d03f37433e3f04e71e97dce7aed8374e849
2,329
hpp
C++
include/higra/structure/details/graph_concepts.hpp
deisemaia/Higra
82cb78b606a383f3961faa882457a9a987f802e0
[ "CECILL-B" ]
64
2019-08-18T19:23:23.000Z
2022-03-21T04:15:04.000Z
include/higra/structure/details/graph_concepts.hpp
deisemaia/Higra
82cb78b606a383f3961faa882457a9a987f802e0
[ "CECILL-B" ]
120
2019-08-16T09:10:35.000Z
2022-03-17T09:42:58.000Z
include/higra/structure/details/graph_concepts.hpp
deisemaia/Higra
82cb78b606a383f3961faa882457a9a987f802e0
[ "CECILL-B" ]
12
2019-10-04T07:35:55.000Z
2021-01-10T19:59:11.000Z
/*************************************************************************** * Copyright ESIEE Paris (2018) * * * * Contributor(s) : Benjamin Perret * * * * Distributed under the terms of the CECILL-B License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #pragma once #ifdef HG_USE_BOOST_GRAPH #include <boost/graph/graph_concepts.hpp> #endif namespace hg { namespace graph { #ifdef HG_USE_BOOST_GRAPH using directed_tag = boost::directed_tag; using undirected_tag = boost::undirected_tag; using bidirectional_tag = boost::bidirectional_tag; using incidence_graph_tag = boost::incidence_graph_tag; using adjacency_graph_tag = boost::adjacency_graph_tag; using bidirectional_graph_tag = boost::bidirectional_graph_tag; using vertex_list_graph_tag = boost::vertex_list_graph_tag; using edge_list_graph_tag = boost::edge_list_graph_tag; using adjacency_matrix_tag = boost::adjacency_matrix_tag; using allow_parallel_edge_tag = boost::allow_parallel_edge_tag; using disallow_parallel_edge_tag = boost::disallow_parallel_edge_tag; using graph_traits = boost::graph_traits; #else struct directed_tag { }; struct undirected_tag { }; struct bidirectional_tag : virtual public directed_tag { }; struct incidence_graph_tag { }; struct adjacency_graph_tag { }; struct bidirectional_graph_tag : virtual public incidence_graph_tag { }; struct vertex_list_graph_tag { }; struct edge_list_graph_tag { }; struct adjacency_matrix_tag { }; struct allow_parallel_edge_tag { }; struct disallow_parallel_edge_tag { }; template<typename T> struct graph_traits; #endif } using graph::graph_traits; }
32.802817
77
0.533705
deisemaia
e8305a88557e31a411d1f63e4050c1465e051604
2,593
cpp
C++
Backtracking/Rat_Maze.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Backtracking/Rat_Maze.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Backtracking/Rat_Maze.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//there is a rat in a maze.The maze is represented by a 2d matrix //with 1 and 0s . //1 means it is possible to go there ,0 means it can't be reached.Find // whether there is any path for the rat inside for reaching its //destination. //The rat can only move forward and down //The starting point is the upper left most cell and destination in //rightmost cell in the lowest row(bottom most right cell) /* We use backtracing just like the knight problem */ #include<iostream> #include<vector> using namespace std; //for printing the matrix void printSolution(vector< vector<int> > sol){ for(int i = 0; i<sol[0].size(); i++){ for(int j = 0; j<sol[0].size(); j++){ cout<<sol[i][j]<<" "; } cout<<endl; } } //for checking if the move is valid or not bool isValidMove(int move_x, int move_y, vector< vector<int> > &sol, vector< vector<int> > &maze){ return (move_x >= 0 && move_x < sol.size() && move_y >= 0 && move_y < sol.size() && sol[move_x][move_y] == 0 && maze[move_x][move_y] == 1); } //for finding if there is any path inside the maze for the rat to reach its dest or not bool findMazePath(int curr_x, int curr_y, vector< vector<int> > &sol, vector<int> x_coor, vector<int> y_coor, int n, vector< vector<int> > &maze){ //check if the dest is reached or not, //assuming the dest is always 1 if(curr_x == n-1 && curr_y == n-1){ sol[n-1][n-1] = 1; return true; } int x_move ; int y_move ; //it has two possible moves for (int i = 0; i < 2; ++i) { x_move = curr_x + x_coor[i]; y_move = curr_y + y_coor[i]; if(isValidMove(x_move, y_move, sol, maze)){ sol[curr_x][curr_y] = 1; if(findMazePath(x_move, y_move, sol, x_coor, y_coor, n, maze)) return true; else sol[curr_x][curr_y] = 0; } } return false; } //driver function for finding the path inside the maze void findMazePathDriver(vector< vector<int> > maze){ //sol contains the path for the rat to escape the maze vector < vector<int> > sol(maze[0].size(), vector<int>(maze[0].size(),0)); //valid set of moves ,rat can move forward and down only vector<int> x_coor = {0,1}; vector<int> y_coor = {1,0}; //mark the starting sol[0][0] = 1; int curr_x = 0; int curr_y = 0; //for finding the dest index int n = maze[0].size(); if(findMazePath(curr_x, curr_y, sol, x_coor, y_coor, n, maze)) printSolution(sol); else cout<<"No path is possible !"; } int main(){ vector< vector<int> > maze = { {1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}, {1, 1, 1, 1} }; findMazePathDriver(maze); }
26.459184
87
0.630929
susantabiswas
e831a77239d1f9ad9e4ee78f0adfb1262e088b0c
817
hpp
C++
library/ATF/Cmd.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/Cmd.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/Cmd.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE enum Cmd { _eRequestInitCandidate = 0x0, _eReqUpdateWinCount = 0x1, _eRequestCandidateList = 0x2, _eRegCandidate = 0x3, _eReg2ndCandidate = 0x4, _eMakeVotePaper = 0x5, _eSendVotePaper = 0x6, _eVote = 0x7, _eVoteScore = 0x8, _eReqQryFinalDecision = 0x9, _eReqQrySetWinner = 0xA, _eReqQryFinalApplyer = 0xB, _eRetQryFinalDecision = 0xC, _eReqNetFinalDecision = 0xD, _eQryAppoint = 0xE, _eReqAppoint = 0xF, _eRespAppoint = 0x10, _eReqDischarge = 0x11, _eReqPatriarchInform = 0x12, _eNon = 0x13, }; END_ATF_NAMESPACE
25.53125
108
0.659731
lemkova
e8387d0652ebe184db243405d675b35600aa9e44
9,449
cpp
C++
modules/fnxext/visibility_controller_2d.cpp
sergey-khrykov/godot
cbba0773b89da8291aea5f5e9a5f53321f723f20
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
2
2019-10-23T11:27:37.000Z
2021-12-06T12:02:31.000Z
modules/fnxext/visibility_controller_2d.cpp
sergey-khrykov/godot
cbba0773b89da8291aea5f5e9a5f53321f723f20
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
8
2020-03-03T13:35:53.000Z
2021-08-19T10:57:47.000Z
modules/fnxext/visibility_controller_2d.cpp
sergey-khrykov/godot
cbba0773b89da8291aea5f5e9a5f53321f723f20
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
2
2021-04-08T18:14:27.000Z
2022-02-28T10:52:34.000Z
#include "visibility_controller_2d.h" #include "core/engine.h" #ifdef TOOLS_ENABLED #include "canvas_layers_editor_plugin.h" #endif bool VisibilityController2D::_get(const String &p_name, Variant &r_ret) const { if (p_name == "editor/canvas_layer") { r_ret = "visibility_controller"; return true; } else { return false; } } NodePath VisibilityController2D::get_controlled_node() const { return controlled_node; } void VisibilityController2D::set_controlled_node(const NodePath &p_node) { controlled_node = p_node; #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) return; #endif setup_controlled_node(); } bool VisibilityController2D::should_control_visibility() const { return control_visibility; } void VisibilityController2D::set_control_visibility(bool p_value) { control_visibility = p_value; #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) return; #endif update_visibility(true); } bool VisibilityController2D::should_control_activity() const { return control_activity; } void VisibilityController2D::set_control_activity(bool p_value) { control_activity = p_value; #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) return; #endif update_visibility(true); } bool VisibilityController2D::should_mark_using_group() const { return mark_using_group; } void VisibilityController2D::set_mark_using_group(bool p_value) { mark_using_group = p_value; #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { _change_notify("mark_using_group"); _change_notify("group_name"); return; } #endif update_group_mark(); } String VisibilityController2D::get_group_name() const { return group_name; } void VisibilityController2D::set_group_name(const String &p_group_name) { if (mark_using_group && _node != NULL && _node->is_in_group(p_group_name)) { _node->remove_from_group(group_name); } group_name = p_group_name; update_group_mark(); } Rect2 VisibilityController2D::get_bounding_box(){ Vector2 size = get_size(); Transform2D tr = get_global_transform(); Rect2 gr = Rect2(tr.xform(Vector2()), Vector2()); gr = gr.expand(tr.xform(size * Vector2(1, 0))); gr = gr.expand(tr.xform(size * Vector2(0, 1))); gr = gr.expand(tr.xform(size)); return gr; } void VisibilityController2D::setup_controlled_node() { Node *parent = get_node(controlled_node); _node = Object::cast_to<CanvasItem>(parent); while (parent != NULL && Object::cast_to<ParallaxLayer>(parent) == NULL){ parent = parent->get_parent(); } if (parent != NULL){ layer = Object::cast_to<ParallaxLayer>(parent); } } void VisibilityController2D::update_visibility(bool force) { VisibilityType active_visibility = !is_inside_tree() ? VisibilityType::INVISIBLE : layer == NULL ? detect_visibility_outside_parallax() : detect_visibility_inside_parallax(); if (!force && active_visibility == visibility) return; bool visible = active_visibility == VisibilityType::VISIBLE; if (visibility != active_visibility) { emit_signal(visible ? "screen_entered" : "screen_exited"); visibility = active_visibility; } if (_node == NULL) return; if (control_visibility) VS::get_singleton()->canvas_item_set_visible(_node->get_canvas_item(), visible); if (control_activity) _node->set_branch_paused(!visible); if (mark_using_group) update_group_mark(); } void VisibilityController2D::update_group_mark() { if (_node == NULL) return; if (mark_using_group) { if (visibility == VISIBLE) { _node->add_to_group(group_name); } else if (_node->is_in_group(group_name)) { _node->remove_from_group(group_name); } } else if (_node->is_in_group(group_name)) { _node->remove_from_group(group_name); } } VisibilityController2D::VisibilityType VisibilityController2D::detect_visibility_outside_parallax() { Rect2 vp_rect = get_viewport_rect(); Rect2 global_rect = get_bounding_box(); return global_rect.intersects(vp_rect) ? VisibilityType::VISIBLE : VisibilityType::INVISIBLE; } VisibilityController2D::VisibilityType VisibilityController2D::detect_visibility_inside_parallax() { Rect2 vpr = get_viewport_rect(); Rect2 fr = get_bounding_box(); Vector2 num_parts = fr.size / vpr.size; num_parts.x = ceil(num_parts.x); num_parts.y = ceil(num_parts.y); Vector2 part_size = Vector2(fr.size.x/num_parts.x, fr.size.y/num_parts.y); Vector<Vector2> points; for (int xp=0; xp<num_parts.x; xp++){ for (int yp=0; yp<num_parts.y; yp++){ Vector2 base = Vector2(fr.position.x + xp*part_size.x, fr.position.y + yp*part_size.y); points.push_back(base); if (xp == num_parts.x-1){ points.push_back(base+Vector2(part_size.x,0)); } if (yp == num_parts.y-1){ points.push_back(base+Vector2(0, part_size.y)); } if (xp == num_parts.x-1 && yp == num_parts.y-1){ points.push_back(base+part_size); } } } Vector2 mo = layer == NULL ? Vector2() : layer->get_mirroring()*layer->get_global_scale(); VisibilityType active_visibility = VisibilityType::INVISIBLE; for (int i=0; i<points.size(); i++){ Vector2 gp = points[i]; while (mo.x && gp.x < 0) gp.x += mo.x; while (mo.x && gp.x > mo.x) gp.x -= mo.x; while (mo.y && gp.y < 0) gp.y += mo.y; while (mo.y && gp.y > mo.y) gp.y -= mo.y; if (vpr.has_point(gp)){ active_visibility = VisibilityType::VISIBLE; break; } } return active_visibility; } void VisibilityController2D::_notification(int p_what){ if (Engine::get_singleton()->is_editor_hint()) { #ifdef TOOLS_ENABLED if (p_what == NOTIFICATION_DRAW && CanvasLayersEditorPlugin::get_singleton()->is_layer_visible("visibility_controller")) { draw_rect(Rect2(Vector2(), get_rect().size), Color::html("3219f064"), true); } #endif return; } switch (p_what){ case NOTIFICATION_EXIT_TREE: { _node = NULL; visibility = UNKNOWN; } break; case NOTIFICATION_ENTER_TREE: { setup_controlled_node(); update_visibility(); set_notify_transform(true); } break; case NOTIFICATION_RESIZED: case NOTIFICATION_TRANSFORM_CHANGED: { update_visibility(); } break; } } void VisibilityController2D::_validate_property(PropertyInfo &prop) const { #ifdef TOOLS_ENABLED if (!Engine::get_singleton()->is_editor_hint()) return; if (prop.name == "group_name") { prop.usage = mark_using_group ? PROPERTY_USAGE_DEFAULT : PROPERTY_USAGE_NOEDITOR; } #endif } bool VisibilityController2D::is_visible_on_screen(){ return visibility; } void VisibilityController2D::_bind_methods(){ ClassDB::bind_method(D_METHOD("is_visible_on_screen"), &VisibilityController2D::is_visible_on_screen); ClassDB::bind_method(D_METHOD("get_bounding_box"), &VisibilityController2D::get_bounding_box); ClassDB::bind_method(D_METHOD("get_controlled_node"), &VisibilityController2D::get_controlled_node); ClassDB::bind_method(D_METHOD("set_controlled_node", "path"), &VisibilityController2D::set_controlled_node); ClassDB::bind_method(D_METHOD("should_control_visibility"), &VisibilityController2D::should_control_visibility); ClassDB::bind_method(D_METHOD("set_control_visibility", "value"), &VisibilityController2D::set_control_visibility); ClassDB::bind_method(D_METHOD("should_control_activity"), &VisibilityController2D::should_control_activity); ClassDB::bind_method(D_METHOD("set_control_activity", "value"), &VisibilityController2D::set_control_activity); ClassDB::bind_method(D_METHOD("should_mark_using_group"), &VisibilityController2D::should_mark_using_group); ClassDB::bind_method(D_METHOD("set_mark_using_group", "value"), &VisibilityController2D::set_mark_using_group); ClassDB::bind_method(D_METHOD("get_group_name"), &VisibilityController2D::get_group_name); ClassDB::bind_method(D_METHOD("set_group_name", "value"), &VisibilityController2D::set_group_name); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "controlled_node"), "set_controlled_node", "get_controlled_node"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "control_visibility"), "set_control_visibility", "should_control_visibility"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "control_activity"), "set_control_activity", "should_control_activity"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "mark_using_group"), "set_mark_using_group", "should_mark_using_group"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "group_name"), "set_group_name", "get_group_name"); ADD_SIGNAL(MethodInfo("screen_entered")); ADD_SIGNAL(MethodInfo("screen_exited")); } VisibilityController2D::VisibilityController2D(){ _node = NULL; controlled_node = NodePath(".."); control_visibility = true; control_activity = false; mark_using_group = false; group_name = "visible_on_screen"; set_mouse_filter(MOUSE_FILTER_IGNORE); layer = NULL; } VisibilityController2D::~VisibilityController2D(){ }
36.910156
130
0.698487
sergey-khrykov
e84121f99836fc7c226df1f4d76b83c3aa40b05a
344
hpp
C++
src/colour.hpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/colour.hpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
src/colour.hpp
zfccxt/calcium
9cc3a00904c05e675bdb5d35eef0f5356796e564
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> namespace cl { struct Colour { Colour() = default; Colour(float r, float g, float b, float a); Colour(uint32_t colour); uint32_t UintRGBA() const; uint32_t UintABGR() const; float r = 0.0f; float g = 0.0f; float b = 0.0f; float a = 1.0f; private: void SetColour(uint32_t colour); }; }
13.76
45
0.645349
zfccxt
e844050729f264123715536de2cef02f699f2622
2,953
cpp
C++
mpi-pingpong/pingpong.cpp
Zefiros-Software/SyncLib
087fa171b339bdbe16a974cd5f85ff4408b679bd
[ "MIT" ]
null
null
null
mpi-pingpong/pingpong.cpp
Zefiros-Software/SyncLib
087fa171b339bdbe16a974cd5f85ff4408b679bd
[ "MIT" ]
null
null
null
mpi-pingpong/pingpong.cpp
Zefiros-Software/SyncLib
087fa171b339bdbe16a974cd5f85ff4408b679bd
[ "MIT" ]
null
null
null
/** * @cond ___LICENSE___ * * Copyright (c) 2016-2018 Zefiros Software. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @endcond */ #include "sync/bench/mpiPingpong.h" #include "sync/bench/partitioning.h" #include "sync/util/time.h" #include "args/args.h" #include "fmt/format.h" #include "fs/fs.h" #include <armadillo> int main(int argc, char *argv[]) { SyncLib::MPI::Comm comm(argc, argv); uint32_t q = 0; std::string outputFile = "run"; if (comm.Rank() == 0) { Args args("bench", "MPI pingpong"); std::string timestamp = SyncLib::Util::GetTimeString(); args.AddOptions({ { { "q", "parts" }, "Number of parts for partitioning.", Option::U32(), "0", "0" }, { { "o", "output" }, "Output file for timings.", Option::String(), timestamp, timestamp } }); args.Parse(argc, argv); q = args.GetOption("parts"); outputFile = args.GetOption("output").Get<std::string>(); } comm.Broadcast(q, 0); SyncLib::Bench::MPIPingPongBenchmark bench(comm); bench.PingPong(); { std::ofstream out; if (comm.Rank() == 0) { const fs::path results("./results"); if (!fs::exists(results)) { fs::create_directory(results); } out.open(results / fmt::format("{}.json", outputFile)); } bench.Serialise(out); } auto G = std::get<0>(bench.ComputePairwise()); auto parts = SyncLib::Partitioning::MakeImprovedClusterInitialisedPartitioning(G, q); if (comm.Rank() == 0) { fmt::print("Original max: {}\n", G.max()); for (auto &part : parts) { arma::uvec slicer(part); fmt::print("Max in part of size {}: {}\n", slicer.size(), G(slicer, slicer).max()); } } // system("pause"); comm.Barrier(); return EXIT_SUCCESS; }
29.237624
109
0.626143
Zefiros-Software
e84e3c4954e66714c7bb1bd481c500485057c020
204
cpp
C++
codeforces/BITOBYT.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
codeforces/BITOBYT.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
codeforces/BITOBYT.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int t, a; for(scanf("%d", &t); t--; ){ scanf("%d", &a); a--; int c3 = 0, c2 = 2, c1 = 1; c3 = a / } }
17
35
0.387255
cosmicray001
e851c80c8ccfe018302e7ee5ada8bddac74a4057
653
cpp
C++
Qt/ChessSys/ui/logindialog.cpp
MagicYCC/ChessSys
2599b5196b8780f3e6cc3dcc3e19e7e23cf7b1d0
[ "MIT" ]
null
null
null
Qt/ChessSys/ui/logindialog.cpp
MagicYCC/ChessSys
2599b5196b8780f3e6cc3dcc3e19e7e23cf7b1d0
[ "MIT" ]
null
null
null
Qt/ChessSys/ui/logindialog.cpp
MagicYCC/ChessSys
2599b5196b8780f3e6cc3dcc3e19e7e23cf7b1d0
[ "MIT" ]
1
2019-05-07T17:31:26.000Z
2019-05-07T17:31:26.000Z
#include "logindialog.h" #include "ui_logindialog.h" #include <QMessageBox> LoginDialog::LoginDialog(ChessSysUser *user, QWidget *parent) : _user(user), QDialog(parent), ui(new Ui::LoginDialog) { ui->setupUi(this); ui->passwordEdit->setEchoMode(QLineEdit::Password); } LoginDialog::~LoginDialog() { delete ui; } void LoginDialog::on_loginButton_clicked() { _user->setName(ui->userEdit->text()); _user->setPassword(ui->passwordEdit->text()); if(_user->login() < 0){ QMessageBox::warning(this, "警告", "用户名或密码不正确!"); return; } // QMessageBox::information(this, "通知", "登录成功!"); close(); }
19.787879
63
0.644717
MagicYCC
e851c812920b9dba1285186166b72b38d296067f
681
cpp
C++
src/lib/JobManager.cpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
22
2020-05-18T02:37:09.000Z
2022-03-13T18:44:30.000Z
src/lib/JobManager.cpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
null
null
null
src/lib/JobManager.cpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
3
2020-12-21T01:21:03.000Z
2021-09-06T08:07:41.000Z
#include <JobManager.hpp> using namespace UniEngine; void JobManager::ResizePrimaryWorkers(int size) { GetInstance().m_primaryWorkers.FinishAll(true); GetInstance().m_primaryWorkers.Resize(size); } void JobManager::ResizeSecondaryWorkers(int size) { GetInstance().m_secondaryWorkers.FinishAll(true); GetInstance().m_secondaryWorkers.Resize(size); } ThreadPool &JobManager::PrimaryWorkers() { return GetInstance().m_primaryWorkers; } ThreadPool &JobManager::SecondaryWorkers() { return GetInstance().m_secondaryWorkers; } void JobManager::Init() { PrimaryWorkers().Resize(std::thread::hardware_concurrency() - 2); SecondaryWorkers().Resize(1); }
22.7
69
0.754772
edisonlee0212
e856527f18d52023a2fb02665b838a8016983ba2
2,136
cpp
C++
Washiwashi Engine/ModuleWindow.cpp
Ruizo/Washiwashi-engine
e1b5cdeea8bd80f647f1a0d556c48a441787ee01
[ "MIT" ]
null
null
null
Washiwashi Engine/ModuleWindow.cpp
Ruizo/Washiwashi-engine
e1b5cdeea8bd80f647f1a0d556c48a441787ee01
[ "MIT" ]
null
null
null
Washiwashi Engine/ModuleWindow.cpp
Ruizo/Washiwashi-engine
e1b5cdeea8bd80f647f1a0d556c48a441787ee01
[ "MIT" ]
1
2021-11-01T20:00:56.000Z
2021-11-01T20:00:56.000Z
#include "Globals.h" #include "Application.h" #include "ModuleWindow.h" ModuleWindow::ModuleWindow(Application* app, bool startEnabled) : Module(app, startEnabled) { window = NULL; screen_surface = NULL; } // Destructor ModuleWindow::~ModuleWindow() { } // Called before render is available bool ModuleWindow::Init() { WASHI_LOG("Init SDL window & surface"); bool ret = true; if(SDL_Init(SDL_INIT_VIDEO) < 0) { WASHI_LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { //Create window int width = App->width * SCREEN_SIZE; int height = App->height * SCREEN_SIZE; Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN; window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags); if(window == NULL) { WASHI_LOG("Window could not be created! SDL_Error: %s\n", SDL_GetError()); ret = false; } else { //Get window surface screen_surface = SDL_GetWindowSurface(window); } } return ret; } // Called before quitting bool ModuleWindow::CleanUp() { WASHI_LOG("Destroying SDL window and quitting all SDL systems"); //Destroy window if(window != NULL) { SDL_DestroyWindow(window); } //Quit SDL subsystems SDL_Quit(); return true; } void ModuleWindow::SetTitle(const char* title) { SDL_SetWindowTitle(window, title); } void ModuleWindow::SetFullscreen(bool fullscreen) { if (App->fullscreen) SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); if (App->fullscreenDesktop) SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP); if (App->borderless) SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP); else if (App->fullscreen == false && App->fullscreenDesktop == false && App->borderless == false) SDL_SetWindowFullscreen(window, 0); } void ModuleWindow::SetResizable(bool resizable) { //Uint32 flags = (resizable) ? SDL_WINDOW_RESIZABLE : 0; //SDL_SetWindowRes } void ModuleWindow::SetWindowSize() { SDL_SetWindowSize(window, (int)App->width, App->height); } void ModuleWindow::SetWindowBrightness() { SDL_SetWindowBrightness(window, App->brightness); }
22.484211
134
0.735487
Ruizo
e858adc1c9e29d674732bd528b8bf10dd6a84e18
152
hpp
C++
src/modules/enumerable.hpp
Zoxc/mirb
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
[ "BSD-3-Clause" ]
10
2016-10-06T06:22:20.000Z
2022-02-28T05:33:09.000Z
src/modules/enumerable.hpp
Zoxc/mirb
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
[ "BSD-3-Clause" ]
null
null
null
src/modules/enumerable.hpp
Zoxc/mirb
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
[ "BSD-3-Clause" ]
3
2018-01-08T03:34:34.000Z
2021-09-12T12:12:22.000Z
#pragma once #include "../value.hpp" namespace Mirb { namespace Enumerable { value_t any(value_t obj, value_t block); void initialize(); }; };
11.692308
42
0.677632
Zoxc
e85b09b24e7e1d316a1dac28accb32dfd181e067
10,557
cc
C++
pdb/src/cuda/source/PDBCUDAGPUInvoke.cc
yuxineverforever/plinycompute
c639d5307a438a850ad00f87880e7be4f17cbb2d
[ "Apache-2.0" ]
1
2020-02-21T06:11:13.000Z
2020-02-21T06:11:13.000Z
pdb/src/cuda/source/PDBCUDAGPUInvoke.cc
yuxineverforever/plinycompute
c639d5307a438a850ad00f87880e7be4f17cbb2d
[ "Apache-2.0" ]
null
null
null
pdb/src/cuda/source/PDBCUDAGPUInvoke.cc
yuxineverforever/plinycompute
c639d5307a438a850ad00f87880e7be4f17cbb2d
[ "Apache-2.0" ]
null
null
null
#include "PDBCUDAGPUInvoke.h" #include "storage/PDBRamPointer.h" /** SimpleTypeGPUInvoke deals with all the primitive types and invoke the gpu kernel for the input/output * `Out` vector should be reserved before passing as parameter * @tparam InvokerType - operator type (should be a derived type from PDBCUDAOp) * @tparam InputType - trivial copyable type for input params * @tparam OutputType - trivial copyable type for output params * @param f - operator * @param Out - output param * @param OutDim - output param dimension * @param In1 - input param 1 * @param In1Dim - input param 1 dimension * @param In2 - input param 2 * @param In2Dim - input param 2 dimension * @return bool - successful or not */ template<typename InvokerType, typename InputType, typename OutputType> typename std::enable_if_t< is_base_of<pdb::PDBCUDAInvoker, InvokerType>::value && std::is_trivially_copyable<OutputType>::value && std::is_trivially_copyable<InputType>::value, bool> SimpleTypeGPUInvoke(InvokerType &f, OutputType *Out, std::vector<size_t> &OutDim, InputType *In1, std::vector<size_t> &In1Dim, InputType *In2, std::vector<size_t> &In2Dim) { f.setInput(In1, In1Dim); f.setInput(In2, In2Dim); f.setOutput(Out, OutDim); bool res = f.invoke(); return res; } /** SimpleTypeGPUInvoke deals with all the primitive types and invoke the gpu kernel for the input/output * `Out` vector should be reserved before passing as parameter * @tparam InvokerType - operator type (should be a derived type from PDBCUDAOp) * @tparam InputType - trivial copyable type for input params * @tparam OutputType - trivial copyable type for output params * @param f - operator * @param Out - output param * @param OutDim - output param dimension * @param In1 - input param 1 * @param In1Dim - input param 1 dimension * @return bool - successful or not */ template<typename InvokerType, typename InputType, typename OutputType> typename std::enable_if_t< is_base_of<pdb::PDBCUDAInvoker, InvokerType>::value && std::is_trivially_copyable<OutputType>::value && std::is_trivially_copyable<InputType>::value, bool> SimpleTypeGPUInvoke(InvokerType &f, OutputType *Out, std::vector<size_t> &OutDim, InputType *In1, std::vector<size_t> &In1Dim) { f.setInput(In1, In1Dim); f.setOutput(Out, OutDim); bool res = f.invoke(); return res; } /** * GPUInvoke for handling the case that both input/output param is Handle<SimpleType> * @tparam InvokerType - operator type (should be a derived type from PDBCUDAOp) * @tparam InputType - trivial copyable type for input params * @tparam OutputType - trivial copyable type for output params * @param f - operator * @param Out - output param * @param In1 - input param 1 * @param In2 - input param 2 * @return bool - successful or not */ template<typename InvokerType, typename InputType, typename OutputType> typename std::enable_if_t<is_base_of<pdb::PDBCUDAInvoker, InvokerType>::value, bool> GPUInvoke(InvokerType &f, pdb::Handle<OutputType> Output, pdb::Handle<InputType> In1, pdb::Handle<InputType> In2) { auto In1Object = (In1.getTarget())->getObject(); std::vector<size_t> In1Dim{1}; auto In2Object = (In2.getTarget())->getObject(); std::vector<size_t> In2Dim{1}; auto OutputObject = (Output.getTarget())->getObject(); std::vector<size_t> OutDim{1}; return SimpleTypeGPUInvoke(f, OutputObject, OutDim, In1Object, In1Dim, In2Object, In2Dim); } /** * GPUInvoke for handling the case that dimensions for all the input/output params are 1 dimensional array * @tparam InvokerType - operator type (should be a derived type from PDBCUDAOp) * @tparam InputType - trivial copyable type for input params * @tparam OutputType - trivial copyable type for output params * @param f - operator * @param Out - output param * @param In1 - input param 1 * @param In2 - input param 2 * @return bool - successful or not */ template<typename InvokerType, typename InputType, typename OutputType> typename std::enable_if_t<is_base_of<pdb::PDBCUDAInvoker, InvokerType>::value, bool> GPUInvoke(InvokerType &f, pdb::Handle<pdb::Vector<OutputType>> Out, pdb::Handle<pdb::Vector<InputType>> In1, pdb::Handle<pdb::Vector<InputType>> In2) { auto In1Object = In1->c_ptr(); std::vector<size_t> In1Dim{In1->size()}; auto In2Object = In2->c_ptr(); std::vector<size_t> In2Dim{In2->size()}; auto OutObject = Out->c_ptr(); std::vector<size_t> OutDim{Out->size()}; return SimpleTypeGPUInvoke(f, OutObject, OutDim, In1Object, In1Dim, In2Object, In2Dim); } /** * GPUInvoke just allow trivial copyable types. Handle 1 input param case. * @tparam InvokerType - operator type (should be a derived type from PDBCUDAOp) * @tparam InputType - trivial copyable type for input params * @tparam OutputType - trivial copyable type for output params * @param f - operator * @param Out - output param * @param OutDim - output param dimension * @param In1 - input param 1 * @param In1Dim - input param 1 dimension * @return bool - successful or not * */ template<typename InvokerType, typename InputType, typename OutputType> typename std::enable_if_t<is_base_of<pdb::PDBCUDAInvoker, InvokerType>::value, bool> GPUInvoke(InvokerType &f, pdb::Handle<pdb::Vector<OutputType>> Out, std::vector<size_t> &OutDim, pdb::Handle<pdb::Vector<InputType>> In1, std::vector<size_t> &In1Dim) { auto In1Object = In1->c_ptr(); auto OutObject = Out->c_ptr(); return SimpleTypeGPUInvoke(f, OutObject, OutDim, In1Object, In1Dim); } /** * GPUInvoke just allow trivial copyable types. Handle 2 input param case. * @tparam InvokerType - operator type (should be a derived type from PDBCUDAOp) * @tparam InputType - trivial copyable type for input params * @tparam OutputType - trivial copyable type for output params * @param f - operator * @param Out - output param * @param OutDim - output param dimension * @param In1 - input param 1 * @param In1Dim - input param 1 dimension * @param In2 - input param 2 * @param In2Dim - input param 2 dimension * @return bool - successful or not */ template<typename InvokerType, typename InputType, typename OutputType> typename std::enable_if_t<is_base_of<pdb::PDBCUDAInvoker, InvokerType>::value, bool> GPUInvoke(InvokerType &f, pdb::Handle<pdb::Vector<OutputType>> Out, std::vector<size_t> &OutDim, pdb::Handle<pdb::Vector<InputType>> In1, std::vector<size_t> &In1Dim, pdb::Handle<pdb::Vector<InputType> > In2, std::vector<size_t> &In2Dim) { auto In1Object = In1->c_ptr(); auto In2Object = In2->c_ptr(); auto OutObject = Out->c_ptr(); return SimpleTypeGPUInvoke(f, OutObject, OutDim, In1Object, In1Dim, In2Object, In2Dim); } bool GPUInvoke(pdb::PDBCUDAMatrixMultipleInvoker &f, pdb::Handle<pdb::Vector<float>> Out, std::vector<size_t> &OutDim, pdb::Handle<pdb::Vector<float>> In1, std::vector<size_t> &In1Dim, pdb::Handle<pdb::Vector<float> > In2, std::vector<size_t> &In2Dim) { auto In1Object = In1->c_ptr(); auto In2Object = In2->c_ptr(); auto OutObject = Out->c_ptr(); return SimpleTypeGPUInvoke(f, OutObject, OutDim, In1Object, In1Dim, In2Object, In2Dim); } bool GPUInvoke(pdb::PDBCUDAVectorAddInvoker &f, pdb::Handle<pdb::Vector<float>> Out, std::vector<size_t> &OutDim, pdb::Handle<pdb::Vector<float>> In1, std::vector<size_t> &In1Dim) { auto In1Object = In1->c_ptr(); auto OutObject = Out->c_ptr(); return SimpleTypeGPUInvoke(f, OutObject, OutDim, In1Object, In1Dim); } //TODO: this should be added later /* std::shared_ptr<pdb::RamPointerBase> GPULazyAllocationHandler(pdb::PDBCUDAVectorAddInvoker &f, void* pointer, size_t size) { return f.LazyAllocationHandler(pointer, size); } */ /** By default, this GPUInvoke will handle the matrix multiple case for join. * @param op * @param Out * @param OutDim * @param In1 * @param In1Dim * @return */ //TODO: this should be added back later /* bool GPUInvoke(pdb::PDBCUDAOpType &op, pdb::Handle<pdb::Vector<float>> Out, std::vector<size_t> &OutDim, pdb::Handle<pdb::Vector<float>> In1, std::vector<size_t> &In1Dim) { if (op != pdb::PDBCUDAOpType::VectorAdd) { exit(-1); } pdb::PDBCUDAVectorAddInvoker vectorAddInvoker; auto OutPtr = Out->c_ptr(); auto OutCPUPtr = Out->cpu_ptr(); bool onGPU = Out->onGPU(); auto In1Ptr = In1->c_ptr(); // For handling the case of lazy allocation // In1Ptr == In1CPUPtr. // means the situation that pointer address in cpu ram is equal to pointer address in gpu/cpu ram. // This situation has two cases: 1. data should not on GPU. 2. data should on GPU but is lazy allocated. // We check the onGPU flag to see which case. if (OutCPUPtr == OutPtr && onGPU){ std::shared_ptr<pdb::RamPointerBase> NewRamPointer = GPULazyAllocationHandler(vectorAddInvoker, static_cast<void*>(OutCPUPtr), OutDim[0]); Out->setRamPointerReference(NewRamPointer); OutPtr = Out->c_ptr(); } assert(In1Ptr != nullptr); assert(OutPtr != nullptr); return SimpleTypeGPUInvoke(vectorAddInvoker, OutPtr, OutDim, In1Ptr, In1Dim); } */ /** By default, this GPUInvoke will handle the vector add case for aggregation. * @param op * @param Out * @param OutDim * @param In1 * @param In1Dim * @param In2 * @param In2Dim * @return */ bool GPUInvoke(pdb::PDBCUDAOpType &op, pdb::Handle<pdb::Vector<float>> Out, std::vector<size_t> &OutDim, pdb::Handle<pdb::Vector<float>> In1, std::vector<size_t> &In1Dim, pdb::Handle<pdb::Vector<float> > In2, std::vector<size_t> &In2Dim) { if (op != pdb::PDBCUDAOpType::MatrixMultiple) { exit(-1); } pdb::PDBCUDAMatrixMultipleInvoker matrixMultipleInvoker; auto In1Object = In1->c_ptr(); auto In2Object = In2->c_ptr(); auto OutObject = Out->c_ptr(); return SimpleTypeGPUInvoke(matrixMultipleInvoker, OutObject, OutDim, In1Object, In1Dim, In2Object, In2Dim); } bool GPUInvoke(pdb::PDBCUDAOpType& op, pdb::Handle<pdb::Vector<float>> Out, std::vector<size_t>& OutDim, pdb::Handle<pdb::Vector<float>> In1, std::vector<size_t>& In1Dim){ if (op!=pdb::PDBCUDAOpType::VectorAdd){ exit(-1); } pdb::PDBCUDAVectorAddInvoker vectorAddInvoker; auto In1Object = In1->c_ptr(); auto OutObject = Out->c_ptr(); return SimpleTypeGPUInvoke(vectorAddInvoker, OutObject, OutDim, In1Object, In1Dim); }
42.059761
171
0.704272
yuxineverforever
e85dbb25d476f5cc1bf8a85c4f56312ecef2b426
537
cpp
C++
linked-lists/insert-a-node-at-a-specific-position-in-a-linked-list.cpp
ritstar/Hackerrank-interview-preparation-kit-solutions
5eb5c975b101422902a2d49ec10677fd6a471d2c
[ "MIT" ]
53
2018-08-23T07:12:53.000Z
2021-04-23T09:38:46.000Z
linked-lists/insert-a-node-at-a-specific-position-in-a-linked-list.cpp
UndefeatedSunny/Hackerrank-interview-preparation-kit-solutions
9ae582e4f128652014bbae7c6a42a0ef9fde1a34
[ "MIT" ]
2
2019-02-14T13:58:51.000Z
2019-09-25T15:33:07.000Z
linked-lists/insert-a-node-at-a-specific-position-in-a-linked-list.cpp
UndefeatedSunny/Hackerrank-interview-preparation-kit-solutions
9ae582e4f128652014bbae7c6a42a0ef9fde1a34
[ "MIT" ]
25
2019-04-09T09:19:25.000Z
2021-09-05T11:36:14.000Z
// Hackerrank Insert node into linkedlist Solution // Runs in O(n) where n is length of linkedlist SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { SinglyLinkedListNode* n = (SinglyLinkedListNode*)malloc(sizeof(SinglyLinkedListNode)); n->data = data; if(head == NULL) return newNode; if(position == 0){ n->next = head; return n; } head->next = insertNodeAtPosition(head->next, data, position - 1); return head; }
25.571429
96
0.649907
ritstar
e85e36e7a852f723d6def9a9e73866cbf3223051
37,635
hpp
C++
include/nil/crypto3/zk/components/algebra/fields/element_fp4.hpp
skywinder/crypto3-blueprint
c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20
[ "MIT" ]
6
2021-05-27T04:52:42.000Z
2022-01-23T23:33:40.000Z
include/nil/crypto3/zk/components/algebra/fields/element_fp4.hpp
skywinder/crypto3-blueprint
c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20
[ "MIT" ]
12
2020-12-08T15:17:00.000Z
2022-03-17T22:19:43.000Z
include/nil/crypto3/zk/components/algebra/fields/element_fp4.hpp
skywinder/crypto3-blueprint
c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20
[ "MIT" ]
5
2021-05-20T20:02:17.000Z
2022-01-14T12:26:24.000Z
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation> // Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// // @file Declaration of interfaces for Fp4 components. // // The components verify field arithmetic in Fp4 = Fp2[V]/(V^2-U) where // Fp2 = Fp[U]/(U^2-non_residue) and non_residue is in Fp. //---------------------------------------------------------------------------// #ifndef CRYPTO3_ZK_BLUEPRINT_FP4_COMPONENTS_HPP #define CRYPTO3_ZK_BLUEPRINT_FP4_COMPONENTS_HPP #include <nil/crypto3/zk/components/component.hpp> #include <nil/crypto3/zk/components/algebra/fields/element_fp2.hpp> #include <nil/crypto3/zk/components/blueprint_variable.hpp> namespace nil { namespace crypto3 { namespace zk { namespace components { /******************************** element_fp4 ************************************/ /** * Component that represents an Fp4 element. */ template<typename Fp4T> struct element_fp4 : public component<typename Fp4T::base_field_type> { using field_type = Fp4T; using base_field_type = typename field_type::base_field_type; using underlying_field_type = typename field_type::underlying_field_type; using underlying_element_type = element_fp2<underlying_field_type>; using data_type = std::array<underlying_element_type, field_type::arity / underlying_field_type::arity>; data_type data; element_fp4(blueprint<base_field_type> &bp) : component<base_field_type>(bp), data({underlying_element_type(bp), underlying_element_type(bp)}) { } element_fp4(blueprint<base_field_type> &bp, const typename field_type::value_type &el) : component<base_field_type>(bp), data({underlying_element_type(bp, el.data[0]), underlying_element_type(bp, el.data[1])}) { } element_fp4(blueprint<base_field_type> &bp, const underlying_element_type &in_data0, const underlying_element_type &in_data1) : component<base_field_type>(bp), data({underlying_element_type(in_data0), underlying_element_type(in_data1)}) { } void generate_r1cs_equals_const_constraints(const typename field_type::value_type &el) { data[0].generate_r1cs_equals_const_constraints(el.data[0]); data[1].generate_r1cs_equals_const_constraints(el.data[1]); } void generate_r1cs_witness(const typename field_type::value_type &el) { data[0].generate_r1cs_witness(el.data[0]); data[1].generate_r1cs_witness(el.data[1]); } typename field_type::value_type get_element() { typename field_type::value_type el; el.data[0] = data[0].get_element(); el.data[1] = data[1].get_element(); return el; } element_fp4<field_type> Frobenius_map(const std::size_t power) const { blueprint_linear_combination<base_field_type> new_c0c0, new_c0c1, new_c1c0, new_c1c1; new_c0c0.assign(this->bp, data[0].data[0]); new_c0c1.assign(this->bp, data[0].data[1] * underlying_field_type::Frobenius_coeffs_c1[power % 2]); new_c1c0.assign(this->bp, data[1].data[0] * field_type::Frobenius_coeffs_c1[power % 4]); new_c1c1.assign(this->bp, data[1].data[1] * field_type::Frobenius_coeffs_c1[power % 4] * underlying_field_type::Frobenius_coeffs_c1[power % 2]); return element_fp4<field_type>(this->bp, underlying_element_type(this->bp, new_c0c0, new_c0c1), underlying_element_type(this->bp, new_c1c0, new_c1c1)); } void evaluate() const { data[0].evaluate(); data[1].evaluate(); } }; /******************************** element_fp4_tower_mul ************************************/ /** * Component that creates constraints for Fp4 multiplication (towering formulas). */ template<typename Fp4T> class element_fp4_tower_mul : public component<typename Fp4T::base_field_type> { public: using field_type = Fp4T; using base_field_type = typename field_type::base_field_type; using underlying_field_type = typename field_type::underlying_field_type; using underlying_element_type = element_fp2<underlying_field_type>; element_fp4<field_type> A; element_fp4<field_type> B; element_fp4<field_type> result; blueprint_linear_combination<base_field_type> v0_c0; blueprint_linear_combination<base_field_type> v0_c1; blueprint_linear_combination<base_field_type> Ac0_plus_Ac1_c0; blueprint_linear_combination<base_field_type> Ac0_plus_Ac1_c1; std::shared_ptr<underlying_element_type> Ac0_plus_Ac1; std::shared_ptr<underlying_element_type> v0; std::shared_ptr<underlying_element_type> v1; blueprint_linear_combination<base_field_type> Bc0_plus_Bc1_c0; blueprint_linear_combination<base_field_type> Bc0_plus_Bc1_c1; std::shared_ptr<underlying_element_type> Bc0_plus_Bc1; blueprint_linear_combination<base_field_type> result_c1_plus_v0_plus_v1_c0; blueprint_linear_combination<base_field_type> result_c1_plus_v0_plus_v1_c1; std::shared_ptr<underlying_element_type> result_c1_plus_v0_plus_v1; std::shared_ptr<element_fp2_mul<underlying_field_type>> compute_v0; std::shared_ptr<element_fp2_mul<underlying_field_type>> compute_v1; std::shared_ptr<element_fp2_mul<underlying_field_type>> compute_result_c1; element_fp4_tower_mul(blueprint<base_field_type> &bp, const element_fp4<field_type> &A, const element_fp4<field_type> &B, const element_fp4<field_type> &result) : component<base_field_type>(bp), A(A), B(B), result(result) { /* Karatsuba multiplication for Fp4 as a quadratic extension of Fp2: v0 = A.data[0] * B.data[0] v1 = A.data[1] * B.data[1] result.data[0] = v0 + non_residue * v1 result.data[1] = (A.data[0] + A.data[1]) * (B.data[0] + B.data[1]) - v0 - v1 where "non_residue * elem" := (non_residue * elt.data[1], elt.data[0]) Enforced with 3 element_fp2_mul's that ensure that: A.data[1] * B.data[1] = v1 A.data[0] * B.data[0] = v0 (A.data[0]+A.data[1])*(B.data[0]+B.data[1]) = result.data[1] + v0 + v1 Reference: "Multiplication and Squaring on Pairing-Friendly Fields" Devegili, OhEigeartaigh, Scott, Dahab */ v1.reset(new underlying_element_type(bp)); compute_v1.reset(new element_fp2_mul<underlying_field_type>(bp, A.data[1], B.data[1], *v1)); v0_c0.assign(bp, result.data[0].data[0] - field_type::value_type::non_residue * v1->data[1]); v0_c1.assign(bp, result.data[0].data[1] - v1->data[0]); v0.reset(new underlying_element_type(bp, v0_c0, v0_c1)); compute_v0.reset(new element_fp2_mul<underlying_field_type>(bp, A.data[0], B.data[0], *v0)); Ac0_plus_Ac1_c0.assign(bp, A.data[0].data[0] + A.data[1].data[0]); Ac0_plus_Ac1_c1.assign(bp, A.data[0].data[1] + A.data[1].data[1]); Ac0_plus_Ac1.reset(new underlying_element_type(bp, Ac0_plus_Ac1_c0, Ac0_plus_Ac1_c1)); Bc0_plus_Bc1_c0.assign(bp, B.data[0].data[0] + B.data[1].data[0]); Bc0_plus_Bc1_c1.assign(bp, B.data[0].data[1] + B.data[1].data[1]); Bc0_plus_Bc1.reset(new underlying_element_type(bp, Bc0_plus_Bc1_c0, Bc0_plus_Bc1_c1)); result_c1_plus_v0_plus_v1_c0.assign(bp, result.data[1].data[0] + v0->data[0] + v1->data[0]); result_c1_plus_v0_plus_v1_c1.assign(bp, result.data[1].data[1] + v0->data[1] + v1->data[1]); result_c1_plus_v0_plus_v1.reset(new underlying_element_type(bp, result_c1_plus_v0_plus_v1_c0, result_c1_plus_v0_plus_v1_c1)); compute_result_c1.reset(new element_fp2_mul<underlying_field_type>( bp, *Ac0_plus_Ac1, *Bc0_plus_Bc1, *result_c1_plus_v0_plus_v1)); } void generate_r1cs_constraints() { compute_v0->generate_r1cs_constraints(); compute_v1->generate_r1cs_constraints(); compute_result_c1->generate_r1cs_constraints(); } void generate_r1cs_witness() { compute_v0->generate_r1cs_witness(); compute_v1->generate_r1cs_witness(); Ac0_plus_Ac1_c0.evaluate(this->bp); Ac0_plus_Ac1_c1.evaluate(this->bp); Bc0_plus_Bc1_c0.evaluate(this->bp); Bc0_plus_Bc1_c1.evaluate(this->bp); compute_result_c1->generate_r1cs_witness(); const typename field_type::value_type Aval = A.get_element(); const typename field_type::value_type Bval = B.get_element(); const typename field_type::value_type Rval = Aval * Bval; result.generate_r1cs_witness(Rval); } }; /******************************** element_fp4_direct_mul ************************************/ /** * Component that creates constraints for Fp4 multiplication (direct formulas). */ template<typename Fp4T> class element_fp4_direct_mul : public component<typename Fp4T::base_field_type> { public: using field_type = Fp4T; using base_field_type = typename field_type::base_field_type; using underlying_field_type = typename field_type::underlying_field_type; using underlying_element_type = element_fp2<underlying_field_type>; using base_field_value_type = typename base_field_type::value_type; element_fp4<field_type> A; element_fp4<field_type> B; element_fp4<field_type> result; blueprint_variable<base_field_type> v1; blueprint_variable<base_field_type> v2; blueprint_variable<base_field_type> v6; element_fp4_direct_mul(blueprint<base_field_type> &bp, const element_fp4<field_type> &A, const element_fp4<field_type> &B, const element_fp4<field_type> &result) : component<base_field_type>(bp), A(A), B(B), result(result) { /* Tom-Cook-4x for Fp4 (beta is the quartic non-residue): v0 = a0*b0, v1 = (a0+a1+a2+a3)*(b0+b1+b2+b3), v2 = (a0-a1+a2-a3)*(b0-b1+b2-b3), v3 = (a0+2a1+4a2+8a3)*(b0+2b1+4b2+8b3), v4 = (a0-2a1+4a2-8a3)*(b0-2b1+4b2-8b3), v5 = (a0+3a1+9a2+27a3)*(b0+3b1+9b2+27b3), v6 = a3*b3 result.data[0] = v0+beta((1/4)v0-(1/6)(v1+v2)+(1/24)(v3+v4)-5v6), result.data[1] = -(1/3)v0+v1-(1/2)v2-(1/4)v3+(1/20)v4+(1/30)v5-12v6+beta(-(1/12)(v0-v1)+(1/24)(v2-v3)-(1/120)(v4-v5)-3v6), result.c2 = -(5/4)v0+(2/3)(v1+v2)-(1/24)(v3+v4)+4v6+beta v6, result.c3 = (1/12)(5v0-7v1)-(1/24)(v2-7v3+v4+v5)+15v6 Enforced with 7 constraints. Doing so requires some care, as we first compute three of the v_i explicitly, and then "inline" result.data[0]/c1/c2/c3 in computations of the remaining four v_i. Concretely, we first compute v1, v2 and v6 explicitly, via 3 constraints as above. v1 = (a0+a1+a2+a3)*(b0+b1+b2+b3), v2 = (a0-a1+a2-a3)*(b0-b1+b2-b3), v6 = a3*b3 Then we use the following 4 additional constraints: (1-beta) v0 = c0 + beta c2 - (beta v1)/2 - (beta v2)/ 2 - (-1 + beta) beta v6 (1-beta) v3 = -15 c0 - 30 c1 - 3 (4 + beta) c2 - 6 (4 + beta) c3 + (24 - (3 beta)/2) v1 + (-8 + beta/2) v2 + 3 (-16 + beta) (-1 + beta) v6 (1-beta) v4 = -15 c0 + 30 c1 - 3 (4 + beta) c2 + 6 (4 + beta) c3 + (-8 + beta/2) v1 + (24 - (3 beta)/2) v2 + 3 (-16 + beta) (-1 + beta) v6 (1-beta) v5 = -80 c0 - 240 c1 - 8 (9 + beta) c2 - 24 (9 + beta) c3 - 2 (-81 + beta) v1 + (-81 + beta) v2 + 8 (-81 + beta) (-1 + beta) v6 The isomorphism between the representation above and towering is: (a0, a1, a2, a3) <-> (a.data[0].data[0], a.data[1].data[0], a.data[0].data[1], a.data[1].data[1]) Reference: "Multiplication and Squaring on Pairing-Friendly Fields" Devegili, OhEigeartaigh, Scott, Dahab NOTE: the expressions above were cherry-picked from the Mathematica result of the following command: (# -> Solve[{c0 == v0+beta((1/4)v0-(1/6)(v1+v2)+(1/24)(v3+v4)-5v6), c1 == -(1/3)v0+v1-(1/2)v2-(1/4)v3+(1/20)v4+(1/30)v5-12v6+beta(-(1/12)(v0-v1)+(1/24)(v2-v3)-(1/120)(v4-v5)-3v6), c2 == -(5/4)v0+(2/3)(v1+v2)-(1/24)(v3+v4)+4v6+beta v6, c3 == (1/12)(5v0-7v1)-(1/24)(v2-7v3+v4+v5)+15v6}, #] // FullSimplify) & /@ Subsets[{v0, v1, v2, v3, v4, v5}, {4}] and simplified by multiplying the selected result by (1-beta) */ v1.allocate(bp); v2.allocate(bp); v6.allocate(bp); } void generate_r1cs_constraints() { const base_field_value_type beta = field_type::value_type::non_residue; const base_field_value_type u = (base_field_value_type::one() - beta).inversed(); const blueprint_linear_combination<base_field_type> &a0 = A.data[0].data[0], &a1 = A.data[1].data[0], &a2 = A.data[0].data[1], &a3 = A.data[1].data[1], &b0 = B.data[0].data[0], &b1 = B.data[1].data[0], &b2 = B.data[0].data[1], &b3 = B.data[1].data[1], &c0 = result.data[0].data[0], &c1 = result.data[1].data[0], &c2 = result.data[0].data[1], &c3 = result.data[1].data[1]; this->bp.add_r1cs_constraint( snark::r1cs_constraint<base_field_type>(a0 + a1 + a2 + a3, b0 + b1 + b2 + b3, v1)); this->bp.add_r1cs_constraint( snark::r1cs_constraint<base_field_type>(a0 - a1 + a2 - a3, b0 - b1 + b2 - b3, v2)); this->bp.add_r1cs_constraint(snark::r1cs_constraint<base_field_type>(a3, b3, v6)); this->bp.add_r1cs_constraint(snark::r1cs_constraint<base_field_type>( a0, b0, u * c0 + beta * u * c2 - beta * u * base_field_value_type(0x02).inversed() * v1 - beta * u * base_field_value_type(0x02).inversed() * v2 + beta * v6)); this->bp.add_r1cs_constraint(snark::r1cs_constraint<base_field_type>( a0 + base_field_value_type(0x02) * a1 + base_field_value_type(0x04) * a2 + base_field_value_type(0x08) * a3, b0 + base_field_value_type(0x02) * b1 + base_field_value_type(0x04) * b2 + base_field_value_type(0x08) * b3, -base_field_value_type(15) * u * c0 - base_field_value_type(30) * u * c1 - base_field_value_type(0x03) * (base_field_value_type(0x04) + beta) * u * c2 - base_field_value_type(6) * (base_field_value_type(0x04) + beta) * u * c3 + (base_field_value_type(24) - base_field_value_type(0x03) * beta * base_field_value_type(0x02).inversed()) * u * v1 + (-base_field_value_type(0x08) + beta * base_field_value_type(0x02).inversed()) * u * v2 - base_field_value_type(0x03) * (-base_field_value_type(16) + beta) * v6)); this->bp.add_r1cs_constraint(snark::r1cs_constraint<base_field_type>( a0 - base_field_value_type(0x02) * a1 + base_field_value_type(0x04) * a2 - base_field_value_type(0x08) * a3, b0 - base_field_value_type(0x02) * b1 + base_field_value_type(0x04) * b2 - base_field_value_type(0x08) * b3, -base_field_value_type(15) * u * c0 + base_field_value_type(30) * u * c1 - base_field_value_type(0x03) * (base_field_value_type(0x04) + beta) * u * c2 + base_field_value_type(6) * (base_field_value_type(0x04) + beta) * u * c3 + (base_field_value_type(24) - base_field_value_type(0x03) * beta * base_field_value_type(0x02).inversed()) * u * v2 + (-base_field_value_type(0x08) + beta * base_field_value_type(0x02).inversed()) * u * v1 - base_field_value_type(0x03) * (-base_field_value_type(16) + beta) * v6)); this->bp.add_r1cs_constraint(snark::r1cs_constraint<base_field_type>( a0 + base_field_value_type(0x03) * a1 + base_field_value_type(0x09) * a2 + base_field_value_type(27) * a3, b0 + base_field_value_type(0x03) * b1 + base_field_value_type(0x09) * b2 + base_field_value_type(27) * b3, -base_field_value_type(80) * u * c0 - base_field_value_type(240) * u * c1 - base_field_value_type(0x08) * (base_field_value_type(0x09) + beta) * u * c2 - base_field_value_type(24) * (base_field_value_type(0x09) + beta) * u * c3 - base_field_value_type(0x02) * (-base_field_value_type(81) + beta) * u * v1 + (-base_field_value_type(81) + beta) * u * v2 - base_field_value_type(0x08) * (-base_field_value_type(81) + beta) * v6)); } void generate_r1cs_witness() { const blueprint_linear_combination<base_field_type> &a0 = A.data[0].data[0], &a1 = A.data[1].data[0], &a2 = A.data[0].data[1], &a3 = A.data[1].data[1], &b0 = B.data[0].data[0], &b1 = B.data[1].data[0], &b2 = B.data[0].data[1], &b3 = B.data[1].data[1]; this->bp.val(v1) = ((this->bp.lc_val(a0) + this->bp.lc_val(a1) + this->bp.lc_val(a2) + this->bp.lc_val(a3)) * (this->bp.lc_val(b0) + this->bp.lc_val(b1) + this->bp.lc_val(b2) + this->bp.lc_val(b3))); this->bp.val(v2) = ((this->bp.lc_val(a0) - this->bp.lc_val(a1) + this->bp.lc_val(a2) - this->bp.lc_val(a3)) * (this->bp.lc_val(b0) - this->bp.lc_val(b1) + this->bp.lc_val(b2) - this->bp.lc_val(b3))); this->bp.val(v6) = this->bp.lc_val(a3) * this->bp.lc_val(b3); const typename field_type::value_type Aval = A.get_element(); const typename field_type::value_type Bval = B.get_element(); const typename field_type::value_type Rval = Aval * Bval; result.generate_r1cs_witness(Rval); } }; /** * Alias default multiplication component */ template<typename Fp4T> using element_fp4_mul = element_fp4_direct_mul<Fp4T>; /******************************** element_fp4_squared ************************************/ /** * Component that creates constraints for Fp4 squaring. */ template<typename Fp4T> class element_fp4_squared : public component<typename Fp4T::base_field_type> { public: using field_type = Fp4T; using base_field_type = typename field_type::base_field_type; using underlying_field_type = typename field_type::underlying_field_type; using underlying_element_type = element_fp2<underlying_field_type>; element_fp4<field_type> A; element_fp4<field_type> result; std::shared_ptr<underlying_element_type> v1; blueprint_linear_combination<base_field_type> v0_c0; blueprint_linear_combination<base_field_type> v0_c1; std::shared_ptr<underlying_element_type> v0; std::shared_ptr<element_fp2_squared<underlying_field_type>> compute_v0; std::shared_ptr<element_fp2_squared<underlying_field_type>> compute_v1; blueprint_linear_combination<base_field_type> Ac0_plus_Ac1_c0; blueprint_linear_combination<base_field_type> Ac0_plus_Ac1_c1; std::shared_ptr<underlying_element_type> Ac0_plus_Ac1; blueprint_linear_combination<base_field_type> result_c1_plus_v0_plus_v1_c0; blueprint_linear_combination<base_field_type> result_c1_plus_v0_plus_v1_c1; std::shared_ptr<underlying_element_type> result_c1_plus_v0_plus_v1; std::shared_ptr<element_fp2_squared<underlying_field_type>> compute_result_c1; element_fp4_squared(blueprint<base_field_type> &bp, const element_fp4<field_type> &A, const element_fp4<field_type> &result) : component<base_field_type>(bp), A(A), result(result) { /* Karatsuba squaring for Fp4 as a quadratic extension of Fp2: v0 = A.data[0]^2 v1 = A.data[1]^2 result.data[0] = v0 + non_residue * v1 result.data[1] = (A.data[0] + A.data[1])^2 - v0 - v1 where "non_residue * elem" := (non_residue * elt.data[1], elt.data[0]) Enforced with 3 element_fp2_squared's that ensure that: A.data[1]^2 = v1 A.data[0]^2 = v0 (A.data[0]+A.data[1])^2 = result.data[1] + v0 + v1 Reference: "Multiplication and Squaring on Pairing-Friendly Fields" Devegili, OhEigeartaigh, Scott, Dahab */ v1.reset(new underlying_element_type(bp)); compute_v1.reset(new element_fp2_squared<underlying_field_type>(bp, A.data[1], *v1)); v0_c0.assign(bp, result.data[0].data[0] - field_type::value_type::non_residue * v1->data[1]); v0_c1.assign(bp, result.data[0].data[1] - v1->data[0]); v0.reset(new underlying_element_type(bp, v0_c0, v0_c1)); compute_v0.reset(new element_fp2_squared<underlying_field_type>(bp, A.data[0], *v0)); Ac0_plus_Ac1_c0.assign(bp, A.data[0].data[0] + A.data[1].data[0]); Ac0_plus_Ac1_c1.assign(bp, A.data[0].data[1] + A.data[1].data[1]); Ac0_plus_Ac1.reset(new underlying_element_type(bp, Ac0_plus_Ac1_c0, Ac0_plus_Ac1_c1)); result_c1_plus_v0_plus_v1_c0.assign(bp, result.data[1].data[0] + v0->data[0] + v1->data[0]); result_c1_plus_v0_plus_v1_c1.assign(bp, result.data[1].data[1] + v0->data[1] + v1->data[1]); result_c1_plus_v0_plus_v1.reset(new underlying_element_type(bp, result_c1_plus_v0_plus_v1_c0, result_c1_plus_v0_plus_v1_c1)); compute_result_c1.reset(new element_fp2_squared<underlying_field_type>( bp, *Ac0_plus_Ac1, *result_c1_plus_v0_plus_v1)); } void generate_r1cs_constraints() { compute_v1->generate_r1cs_constraints(); compute_v0->generate_r1cs_constraints(); compute_result_c1->generate_r1cs_constraints(); } void generate_r1cs_witness() { compute_v1->generate_r1cs_witness(); v0_c0.evaluate(this->bp); v0_c1.evaluate(this->bp); compute_v0->generate_r1cs_witness(); Ac0_plus_Ac1_c0.evaluate(this->bp); Ac0_plus_Ac1_c1.evaluate(this->bp); compute_result_c1->generate_r1cs_witness(); const typename field_type::value_type Aval = A.get_element(); const typename field_type::value_type Rval = Aval.squared(); result.generate_r1cs_witness(Rval); } }; /******************************** element_fp4_cyclotomic_squared ************************************/ /** * Component that creates constraints for Fp4 cyclotomic squaring */ template<typename Fp4T> class element_fp4_cyclotomic_squared : public component<typename Fp4T::base_field_type> { public: using field_type = Fp4T; using base_field_type = typename field_type::base_field_type; using underlying_field_type = typename field_type::underlying_field_type; using underlying_element_type = element_fp2<underlying_field_type>; using base_field_value_type = typename base_field_type::value_type; element_fp4<field_type> A; element_fp4<field_type> result; blueprint_linear_combination<base_field_type> c0_expr_c0; blueprint_linear_combination<base_field_type> c0_expr_c1; std::shared_ptr<underlying_element_type> c0_expr; std::shared_ptr<element_fp2_squared<underlying_field_type>> compute_c0_expr; blueprint_linear_combination<base_field_type> A_c0_plus_A_c1_c0; blueprint_linear_combination<base_field_type> A_c0_plus_A_c1_c1; std::shared_ptr<underlying_element_type> A_c0_plus_A_c1; blueprint_linear_combination<base_field_type> c1_expr_c0; blueprint_linear_combination<base_field_type> c1_expr_c1; std::shared_ptr<underlying_element_type> c1_expr; std::shared_ptr<element_fp2_squared<underlying_field_type>> compute_c1_expr; element_fp4_cyclotomic_squared(blueprint<base_field_type> &bp, const element_fp4<field_type> &A, const element_fp4<field_type> &result) : component<base_field_type>(bp), A(A), result(result) { /* A = elt.data[1] ^ 2 B = elt.data[1] + elt.data[0]; C = B ^ 2 - A D = Fp2(A.data[1] * non_residue, A.data[0]) E = C - D F = D + D + Fp2::one() G = E - Fp2::one() return Fp4(F, G); Enforced with 2 element_fp2_squared's that ensure that: elt.data[1] ^ 2 = Fp2(result.data[0].data[1] / 2, (result.data[0].data[0] - 1) / (2 * non_residue)) = A (elt.data[1] + elt.data[0]) ^ 2 = A + result.data[1] + Fp2(A.data[1] * non_residue + 1, A.data[0]) (elt.data[1] + elt.data[0]) ^ 2 = Fp2(result.data[0].data[1] / 2 + result.data[1].data[0] + (result.data[0].data[0] - 1) / 2 + 1, (result.data[0].data[0] - 1) / (2 * non_residue) + result.data[1].data[1] + result.data[0].data[1] / 2) */ c0_expr_c0.assign(bp, result.data[0].data[1] * base_field_value_type(0x02).inversed()); c0_expr_c1.assign( bp, (result.data[0].data[0] - base_field_value_type(0x01)) * (base_field_value_type(0x02) * field_type::value_type::non_residue).inversed()); c0_expr.reset(new underlying_element_type(bp, c0_expr_c0, c0_expr_c1)); compute_c0_expr.reset(new element_fp2_squared<underlying_field_type>(bp, A.data[1], *c0_expr)); A_c0_plus_A_c1_c0.assign(bp, A.data[0].data[0] + A.data[1].data[0]); A_c0_plus_A_c1_c1.assign(bp, A.data[0].data[1] + A.data[1].data[1]); A_c0_plus_A_c1.reset(new underlying_element_type(bp, A_c0_plus_A_c1_c0, A_c0_plus_A_c1_c1)); c1_expr_c0.assign( bp, (result.data[0].data[1] + result.data[0].data[0] - base_field_value_type(0x01)) * base_field_value_type(0x02).inversed() + result.data[1].data[0] + base_field_value_type(0x01)); c1_expr_c1.assign( bp, (result.data[0].data[0] - base_field_value_type(0x01)) * (base_field_value_type(0x02) * field_type::value_type::non_residue).inversed() + result.data[1].data[1] + result.data[0].data[1] * base_field_value_type(0x02).inversed()); c1_expr.reset(new underlying_element_type(bp, c1_expr_c0, c1_expr_c1)); compute_c1_expr.reset( new element_fp2_squared<underlying_field_type>(bp, *A_c0_plus_A_c1, *c1_expr)); } void generate_r1cs_constraints() { compute_c0_expr->generate_r1cs_constraints(); compute_c1_expr->generate_r1cs_constraints(); } void generate_r1cs_witness() { compute_c0_expr->generate_r1cs_witness(); A_c0_plus_A_c1_c0.evaluate(this->bp); A_c0_plus_A_c1_c1.evaluate(this->bp); compute_c1_expr->generate_r1cs_witness(); const typename field_type::value_type Aval = A.get_element(); const typename field_type::value_type Rval = Aval.squared(); result.generate_r1cs_witness(Rval); } }; } // namespace components } // namespace zk } // namespace crypto3 } // namespace nil #endif // CRYPTO3_ZK_BLUEPRINT_FP4_COMPONENTS_HPP
58.078704
132
0.484576
skywinder
e867456fd369b12540666dbfec28c235d114f313
1,062
cpp
C++
C++/858. Mirror Reflection.cpp
josh-dp/LeetCode-Solutions
ef790260b8e390f207461e3ee1d79fd59d8b2258
[ "MIT" ]
263
2020-10-05T18:47:29.000Z
2022-03-31T19:44:46.000Z
C++/858. Mirror Reflection.cpp
josh-dp/LeetCode-Solutions
ef790260b8e390f207461e3ee1d79fd59d8b2258
[ "MIT" ]
1,264
2020-10-05T18:13:05.000Z
2022-03-31T23:16:35.000Z
C++/858. Mirror Reflection.cpp
josh-dp/LeetCode-Solutions
ef790260b8e390f207461e3ee1d79fd59d8b2258
[ "MIT" ]
760
2020-10-05T18:22:51.000Z
2022-03-29T06:06:20.000Z
// problem - 858. Mirror Reflection /* There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.) */ class Solution { public: int mirrorReflection(int p, int q) { int n = 1, m = 1; /* * if n == even then mirror 2 * else * if m is odd then mirror 1 * else mirror 0 **/ while(m * p != n * q) { n++; m = (n * q) / p; } if(n & 1) { if(m & 1) return 1; else return 0; } else return 2; } }; // Time Complexity = O(n) [where n is ((m*p)/q)] // Space Complexity = O(1)
27.230769
91
0.547081
josh-dp
e8674d58c543e2a4a55af9edfb445fe1c86f027a
359
hpp
C++
biblioteka/include/model/ClientType.hpp
aantczakpiotr/OOP-final-project
9559e797f4b98e88a6a97ef39ea6a8a4b67808b2
[ "MIT" ]
null
null
null
biblioteka/include/model/ClientType.hpp
aantczakpiotr/OOP-final-project
9559e797f4b98e88a6a97ef39ea6a8a4b67808b2
[ "MIT" ]
null
null
null
biblioteka/include/model/ClientType.hpp
aantczakpiotr/OOP-final-project
9559e797f4b98e88a6a97ef39ea6a8a4b67808b2
[ "MIT" ]
null
null
null
// // Created by student on 17.01.2020. // #ifndef SERWIS_SPRZETU_KOMPUTEROWEGO_CLIENTTYPE_HPP #define SERWIS_SPRZETU_KOMPUTEROWEGO_CLIENTTYPE_HPP class ClientType { public: virtual double discount(double totalValue, int totalRecentPurchase) = 0; ClientType(); virtual ~ClientType(); }; #endif //SERWIS_SPRZETU_KOMPUTEROWEGO_CLIENTTYPE_HPP
17.95
76
0.779944
aantczakpiotr
e86850152d81aaea49cb25e8b88e9b443d5739fb
1,645
hpp
C++
src/vector_ops.hpp
nr1040gh/ray-tracing
20500ba7875197b59ad20681d4309ea9d66d62e0
[ "MIT" ]
null
null
null
src/vector_ops.hpp
nr1040gh/ray-tracing
20500ba7875197b59ad20681d4309ea9d66d62e0
[ "MIT" ]
null
null
null
src/vector_ops.hpp
nr1040gh/ray-tracing
20500ba7875197b59ad20681d4309ea9d66d62e0
[ "MIT" ]
null
null
null
#ifndef VECTOR_OPS_HPP #define VECTOR_OPS_HPP #include <vector> #include "point.hpp" //http://www.math.uaa.alaska.edu/~afkjm/csce211/handouts/SeparateCompilation.pdf //http://www.cppforschool.com/tutorial/separate-header-and-implementation-files.html namespace vector_ops { //Templatize these below for any general container, not just vectors? /** * @brief Get dot product between two vectors. Vectors should be same length * * @param v1 vector1 same length as vector2 * @param v2 vector2 same length as vector1 * @return double Result of the dot product operation */ double dotProd(std::vector<double> v1, std::vector<double> v2); /** * @brief Get unit vector of a vector * * @param v1 vector1 * @return std::vector<double> New vector object representing unit vector */ std::vector<double> unitVec(std::vector<double> v1); /** * @brief Get cosine similarity between 2 vectors. Result is between -1 and 1, inclusive * * @param v1 vector1 same length as vector2 * @param v2 vector2 same length as vector1 * @return double Cosine similarity result [-1,1] */ double cosSimilarity(std::vector<double> v1, std::vector<double> v2); /** * @brief Get vector object representing vector from point 1 to point 2. * * @param p1 Point object representing "starting" point. Same dimensions as p2 * @param p2 Point object representing "ending" point. Same dimensions as p1 * @return std::vector<double> Vector object representing the vector from point 1 to point 2 */ std::vector<double> getVector(Point p1, Point p2); } #endif
30.462963
97
0.696049
nr1040gh
e86987752eafe07e4ae1cc0d9ce230b5b5af07aa
1,352
cpp
C++
src/modules/directx11/command_list.cpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
src/modules/directx11/command_list.cpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
91
2019-03-09T11:31:29.000Z
2022-02-27T13:06:06.000Z
src/modules/directx11/command_list.cpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
// mge - Modern Game Engine // Copyright (c) 2021 by Alexander Schroeder // All rights reserved. #include "command_list.hpp" #include "error.hpp" namespace mge::dx11 { command_list::command_list(render_context& context) : mge::command_list(context, true) , m_dx11_context(context) { ID3D11DeviceContext* deferred_context; auto hr = context.device()->CreateDeferredContext(0, &deferred_context); CHECK_HRESULT(hr, ID3D11Device, CreateDeferredContext); m_deferred_context.reset(deferred_context); } command_list::~command_list() {} void command_list::clear(const rgba_color& c) { float clearcolor[4] = {c.r, c.g, c.b, c.a}; m_deferred_context->ClearRenderTargetView( m_dx11_context.render_target_view(), clearcolor); } void command_list::execute() { if (!m_command_list) { ID3D11CommandList* command_list = nullptr; auto hr = m_deferred_context->FinishCommandList(FALSE, &command_list); CHECK_HRESULT(hr, ID3D11DeviceContext, FinishCommandList); m_command_list.reset(command_list); } m_dx11_context.device_context()->ExecuteCommandList( m_command_list.get(), FALSE); } } // namespace mge::dx11
30.727273
80
0.635355
mge-engine
e86d68c31d04bbf8659422670f67873c5fa04ce1
4,602
cpp
C++
minimgio/src/v4l2utils.cpp
SmartEngines/minimg_interfaces
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
[ "BSD-3-Clause" ]
4
2021-07-14T11:27:40.000Z
2021-12-16T12:58:36.000Z
minimgio/src/v4l2utils.cpp
SmartEngines/minimg_interfaces
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
[ "BSD-3-Clause" ]
null
null
null
minimgio/src/v4l2utils.cpp
SmartEngines/minimg_interfaces
b9276f4d800a7d4563c7e1aaa08ef927bbccb918
[ "BSD-3-Clause" ]
1
2021-12-20T10:18:39.000Z
2021-12-20T10:18:39.000Z
/* Copyright 2021 Smart Engines Service LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <minbase/minresult.h> #include <minutils/smartptr.h> #include "v4l2utils.h" #include <linux/videodev2.h> #include <dirent.h> #include <sys/stat.h> #include <fcntl.h> #include <vector> #include <cstring> #include <libv4l2.h> int InsistentIoctl(int dev_file, int request, const void* p_arg) { int res = -1; do { res = v4l2_ioctl(dev_file, request, p_arg); } while (-1 == res && (EINTR == errno || EAGAIN == errno || EIO == errno /*|| EBUSY == errno*/)); // if (-1 == res) { // int err_value = errno; // int for_break = err_value; // } return res; } typedef DIR* DirPtr; static MUSTINLINE void CloseDir(DirPtr* p_dirptr) { if (p_dirptr) closedir(*p_dirptr); } DEFINE_SCOPED_HANDLE(ScopedDIR, DirPtr, CloseDir) static MinResult ListDirectory( std::vector<std::string>& addr_list, const std::string& dir_path) { ScopedDIR dir_handle; dir_handle.reset(opendir(dir_path.c_str())); if (!dir_handle) return MR_ENV_ERROR; addr_list.clear(); dirent* p_entry; while ((p_entry = readdir(dir_handle))) { if (!::strcmp(p_entry->d_name, ".") || !::strcmp(p_entry->d_name, "..")) continue; addr_list.push_back(dir_path); addr_list.back() += p_entry->d_name; } return MR_SUCCESS; } ScopedV4L2File::ScopedV4L2File(const std::string& file_path) : file_path_(file_path), file_is_proper_(false), fd_(-1) { struct stat st; file_is_proper_ = (-1 < stat(file_path.c_str(), &st) && S_ISCHR(st.st_mode)); } ScopedV4L2File::~ScopedV4L2File() { Close(); } bool ScopedV4L2File::IsFileProper() const { return file_is_proper_; } int ScopedV4L2File::Open() { if (!IsFileProper()) return -1; if (fd_ < 0) fd_ = v4l2_open(file_path_.c_str(), O_RDWR | O_NONBLOCK, 0); return fd_; } void ScopedV4L2File::Close() { if (-1 < fd_) IGNORE_ERRORS(v4l2_close(fd_)); fd_ = -1; } ScopedV4L2File::operator const int&() const { return fd_; } static MinResult FillStreamingCaptureDeviceNameAddrMapByAddresses( std::map<std::string, std::string>& mp, const std::vector<std::string>& addr_list) { for (const auto& addr : addr_list) { ScopedV4L2File device_file(addr); if (-1 == device_file.Open()) return MR_ENV_ERROR; struct v4l2_capability cap; if (-1 == InsistentIoctl(device_file, VIDIOC_QUERYCAP, &cap)) return MR_INTERNAL_ERROR; if (cap.capabilities & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING)) mp[reinterpret_cast<char*>(cap.card)] = addr; } return MR_SUCCESS; } MinResult GetStreamingCaptureDeviceNameAddrMap( std::map<std::string, std::string>& name_addr_map) { constexpr char dev_addr_prefix[] = "/dev/v4l/by-id/"; std::vector<std::string> addr_list; MR_PROPAGATE_ERROR(ListDirectory(addr_list, dev_addr_prefix)); std::map<std::string, std::string> tmp_map; MR_PROPAGATE_ERROR(FillStreamingCaptureDeviceNameAddrMapByAddresses(tmp_map, addr_list)); std::swap(name_addr_map, tmp_map); return MR_SUCCESS; }
28.943396
94
0.706215
SmartEngines
e86d85eedb8114b719e914444c286ff2584b4a34
1,850
cc
C++
OJonline/compile_server.cc
Johnson5218/OJonline
d3146c53f0310050ae81e7ee0c8457ecf124f8b8
[ "Apache-2.0" ]
1
2019-08-31T00:39:21.000Z
2019-08-31T00:39:21.000Z
OJonline/compile_server.cc
Johnson5218/OJonline
d3146c53f0310050ae81e7ee0c8457ecf124f8b8
[ "Apache-2.0" ]
null
null
null
OJonline/compile_server.cc
Johnson5218/OJonline
d3146c53f0310050ae81e7ee0c8457ecf124f8b8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <unordered_map> #include <string> #include "httplib.h" #include "compile.hpp" #include <jsoncpp/json/json.h> /* 在线编译oj */ int main() { //写在里面好 using namespace httplib; Server server; //.Get 注册了一个回调函数,这个函数的调用时机 //处理 Get 方法的时候 //lambda 表达式?匿名函数 server.Post("/compile", [] (const Request& req, Response& resp) { //根据问题的具体场景 根据请求 计算出响应结果 //如何从req中获取到JSON的请求 //JSONcpp 第三方库 //以及JSON如何和HTTP协议结合 //需要的请求格式是JSON格式,而HTTP能够提供的格式是另外一种键值对的格式 //因此在这需要进行格式的转换 //这里有浏览器提供的一些特殊符号,这些特殊符号需要转义,浏览器帮我们完成了 //整理成为我们需要的JSON格式 //帮我们将body解析成为键值对 //键值对用哪个数据结构标识? 用unordered_map; //vector 数组 //list 链表 //map(key-value)/set(key) 二叉搜索树 //unordered_mapi(key-value)/unordered_set(key) 哈希表 //unordered 无序 std::unordered_map<std::string, std::string> body_kv; UrlUtil::ParseBody(req.body, body_kv); //在这里调用设定的compileAndRun Json::Value req_json; //从req对象中获取到 for (auto e : body_kv) { //键为first //值为second req_json[e.first] = e.second; } Json::Value resp_json; //从resp_json 放到响应中 Compiler::CompileAndRun(req_json, resp_json); //需要把 Json::value 对象序列化成一个字符串 才能返回 Json::FastWriter writer; resp.set_content(writer.write(resp_json), "text/plain"); }); //加上这个目录是为了让浏览器访问到一个静态页面 //静态页面:index.html 不会发生变化 //动态页面:编译结果会随着参数的不同发生变化 server.set_base_dir("./m"); server.listen("0.0.0.0", 9092); return 0; }
30.833333
72
0.526486
Johnson5218
e86e65d0d2752f9346244a94bb8e5470e68d4fdc
459
cpp
C++
Bootcamp/Practice/PaindromeString.cpp
sgpritam/DSAlgo
3e0e6b19d4f8978b2fc3be48195705a285dbdce8
[ "MIT" ]
1
2020-03-06T21:05:14.000Z
2020-03-06T21:05:14.000Z
Bootcamp/Practice/PaindromeString.cpp
sgpritam/DSAlgo
3e0e6b19d4f8978b2fc3be48195705a285dbdce8
[ "MIT" ]
2
2020-03-09T05:08:14.000Z
2020-03-09T05:14:09.000Z
Bootcamp/Practice/PaindromeString.cpp
sgpritam/DSAlgo
3e0e6b19d4f8978b2fc3be48195705a285dbdce8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool isPalindrome(char *a){ int i=0; int j=strlen(a)-1; while(i<j){ if(a[i]==a[j]){ i++; j--; } else{ return false; } } return true; } int main() { char a[1000]; cin.getline(a,1000); if(isPalindrome(a)){ cout<<"String is Palindrome"; } else{ cout<<"String is not palindromic"; } }
14.806452
42
0.455338
sgpritam
e87235339e8e0b74a623324cdf32a72f81a5fc04
3,102
cpp
C++
src/CpuOperations/NEG.cpp
PaulTrampert/GenieSys
637e7f764bc7faac8d0b5afcf22646e200562f6a
[ "MIT" ]
null
null
null
src/CpuOperations/NEG.cpp
PaulTrampert/GenieSys
637e7f764bc7faac8d0b5afcf22646e200562f6a
[ "MIT" ]
82
2020-12-17T04:03:10.000Z
2022-03-24T17:54:28.000Z
src/CpuOperations/NEG.cpp
PaulTrampert/GenieSys
637e7f764bc7faac8d0b5afcf22646e200562f6a
[ "MIT" ]
null
null
null
// // Created by pault on 10/6/2021. // #include <GenieSys/CpuOperations/NEG.h> #include <GenieSys/getPossibleOpcodes.h> #include <GenieSys/AddressingModes/AddressingMode.h> #include <GenieSys/getCcrFlags.h> #include <vector> #include <cmath> #include <sstream> #include <GenieSys/M68kCpu.h> #include <GenieSys/AddressingModes/DataRegisterDirectMode.h> #include <GenieSys/AddressingModes/AddressRegisterDirectMode.h> GenieSys::NEG::NEG(GenieSys::M68kCpu *cpu, GenieSys::Bus *bus) : GenieSys::CpuOperation(cpu, bus) { } uint8_t GenieSys::NEG::getSpecificity() { return sizeMask.getWidth() + eaModeMask.getWidth() + eaRegMask.getWidth(); } std::vector<uint16_t> GenieSys::NEG::getOpcodes() { return GenieSys::getPossibleOpcodes((uint16_t)0b0100010000000000, std::vector<GenieSys::BitMask<uint16_t>*> { &sizeMask, &eaModeMask, &eaRegMask }); } uint8_t GenieSys::NEG::execute(uint16_t opWord) { uint8_t size = sizeMask.apply(opWord); uint8_t eaModeId = eaModeMask.apply(opWord); uint8_t eaReg = eaRegMask.apply(opWord); auto eaMode = cpu->getAddressingMode(eaModeId); auto eaResult = eaMode->getData(eaReg, pow(2, size)); bool isRegisterEa = eaModeId == GenieSys::DataRegisterDirectMode::MODE_ID || eaModeId == GenieSys::AddressRegisterDirectMode::MODE_ID; uint8_t cycles = 4; uint8_t byteResult; uint16_t wordResult; uint32_t longResult; switch(size) { case 0: byteResult = -eaResult->getDataAsByte(); eaResult->write(byteResult); cpu->setCcrFlags(GenieSys::getSubtractionCcrFlags<uint8_t, int8_t>(byteResult, 0, -byteResult)); cycles = isRegisterEa ? 4 : (8 + eaResult->getCycles()); break; case 1: wordResult = -eaResult->getDataAsWord(); eaResult->write(wordResult); cpu->setCcrFlags(GenieSys::getSubtractionCcrFlags<uint16_t, int16_t>(wordResult, 0, -wordResult)); cycles = isRegisterEa ? 4 : (8 + eaResult->getCycles()); break; case 2: longResult = -eaResult->getDataAsLong(); eaResult->write(longResult); cpu->setCcrFlags(GenieSys::getSubtractionCcrFlags<uint32_t, int32_t>(longResult, 0, -longResult)); cycles = isRegisterEa ? 6 : (12 + eaResult->getCycles()); break; default: cpu->trap(GenieSys::TV_ILLEGAL_INSTR); } return cycles; } std::string GenieSys::NEG::disassemble(uint16_t opWord) { std::stringstream stream; uint8_t size = sizeMask.apply(opWord); uint8_t eaModeId = eaModeMask.apply(opWord); uint8_t eaReg = eaRegMask.apply(opWord); auto eaMode = cpu->getAddressingMode(eaModeId); stream << "NEG"; switch (size) { case 0: stream << ".b "; break; case 1: stream << ".w "; break; case 2: stream << ".l "; break; default: stream << " "; } stream << eaMode->disassemble(eaReg, pow(2, size)); return stream.str(); }
33.717391
138
0.636686
PaulTrampert
e8812041acfe973c2b36788cf1e1166b0a80a3b6
29,546
cxx
C++
HLT/MUON/OnlineAnalysis/AliHLTMUONMansoTrackerFSM.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1
2017-04-27T17:28:15.000Z
2017-04-27T17:28:15.000Z
HLT/MUON/OnlineAnalysis/AliHLTMUONMansoTrackerFSM.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
3
2017-07-13T10:54:50.000Z
2018-04-17T19:04:16.000Z
HLT/MUON/OnlineAnalysis/AliHLTMUONMansoTrackerFSM.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
5
2017-03-29T12:21:12.000Z
2018-01-15T15:52:24.000Z
/************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * All rights reserved. * * * * Primary Authors: * * Artur Szostak <artursz@iafrica.com> * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ /// /// @file AliHLTMUONMansoTrackerFSM.cxx /// @author Artur Szostak <artursz@iafrica.com> /// @date 29 May 2007 /// @brief Implementation of AliHLTMUONMansoTrackerFSM class. /// /// Implementation of AliHLTMUONMansoTrackerFSM class which implements the Manso /// tracking algorithm as a finite state machine, which partially reconstructs /// tracks in the muon spectrometer. #include "AliHLTMUONMansoTrackerFSM.h" #include "AliHLTMUONCalculations.h" #include "AliHLTMUONConstants.h" #include "AliHLTMUONUtils.h" #include "AliHLTMUONTriggerRecordsBlockStruct.h" #include "AliHLTMUONMansoTracksBlockStruct.h" #include "AliHLTMUONMansoCandidatesBlockStruct.h" #include <cmath> #ifdef DEBUG #include <ostream> namespace { std::ostream& operator << (std::ostream& os, AliHLTMUONMansoTrackerFSM::StatesSM4 state) { switch (state) { case AliHLTMUONMansoTrackerFSM::kSM4Idle: os << "kSM4Idle"; break; case AliHLTMUONMansoTrackerFSM::kWaitChamber8: os << "kWaitChamber8"; break; case AliHLTMUONMansoTrackerFSM::kWaitMoreChamber8: os << "kWaitMoreChamber8"; break; case AliHLTMUONMansoTrackerFSM::kWaitChamber7: os << "kWaitChamber7"; break; case AliHLTMUONMansoTrackerFSM::kWaitMoreChamber7: os << "kWaitMoreChamber7"; break; default: os << "FAULT!!"; } return os; } std::ostream& operator << (std::ostream& os, AliHLTMUONMansoTrackerFSM::StatesSM5 state) { switch (state) { case AliHLTMUONMansoTrackerFSM::kSM5Idle: os << "kSM5Idle"; break; case AliHLTMUONMansoTrackerFSM::kWaitChamber10: os << "kWaitChamber10"; break; case AliHLTMUONMansoTrackerFSM::kWaitMoreChamber10: os << "kWaitMoreChamber10"; break; case AliHLTMUONMansoTrackerFSM::kWaitChamber9: os << "kWaitChamber9"; break; case AliHLTMUONMansoTrackerFSM::kWaitMoreChamber9: os << "kWaitMoreChamber9"; break; case AliHLTMUONMansoTrackerFSM::kSM5Done: os << "kSM5Done"; break; default: os << "FAULT!!"; } return os; } } // end of namespace #endif // DEBUG // Deviate from the Manso implementation by allowing a and b // parameters per chamber and not just per station. // The default values are derived from the work done in // "A first algorithm for dimuon High Level Trigger" // Ref ID: ALICE-INT-2002-04 version 1.0 AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgA7 = 0.016f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgB7 = 2.0f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgA8 = 0.016f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgB8 = 2.0f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgA9 = 0.020f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgB9 = 3.0f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgA10 = 0.020f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgB10 = 3.0f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgZ7 = -1274.5f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgZ8 = -1305.5f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgZ9 = -1408.6f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgZ10 = -1439.6f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgZ11 = -1603.5f; AliHLTFloat32_t AliHLTMUONMansoTrackerFSM::fgZ13 = -1703.5f; void AliHLTMUONMansoTrackerFSM::AliRegionOfInterest::Create( AliHLTMUONRecHitStruct p, AliHLTFloat32_t a, AliHLTFloat32_t b ) { // Creates a region of interest specific to the Manso algorithm from a point and // two Manso specific parameters. fCentre = p; // Compute the radius Rp AliHLTFloat32_t rp = (AliHLTFloat32_t) sqrt( p.fX * p.fX + p.fY * p.fY ); // The radius Rs for the region of interest is computed from the // specification given in the document: // "A first algorithm for dimuon High Level Trigger" // Ref ID: ALICE-INT-2002-04 version 1.0 // equation: // Rs = a * Rp + b // given on page 3 section 4. fRs = a * rp + b; } bool AliHLTMUONMansoTrackerFSM::AliRegionOfInterest::Contains(AliHLTMUONRecHitStruct p) const { // Compute the distance between the centre of the region of interest and // the point p. This distance must be less than the radius of the region // of interest for p to be contained in the region of interest. register AliHLTFloat32_t lx = fCentre.fX - p.fX; register AliHLTFloat32_t ly = fCentre.fY - p.fY; register AliHLTFloat32_t r = (AliHLTFloat32_t) sqrt( lx * lx + ly * ly ); DebugTrace("\tAliRegionOfInterest::Contains : p = " << p << " , centre = " << fCentre << " , r = " << r << " , Rs = " << fRs ); return r <= fRs; } void AliHLTMUONMansoTrackerFSM::AliRegionOfInterest::GetBoundaryBox( AliHLTFloat32_t& left, AliHLTFloat32_t& right, AliHLTFloat32_t& bottom, AliHLTFloat32_t& top ) const { // Works out the smallest boundary box that will contain the region of interest. left = fCentre.fX - fRs; right = fCentre.fX + fRs; bottom = fCentre.fY - fRs; top = fCentre.fY + fRs; } AliHLTMUONMansoTrackerFSM::AliVertex::AliVertex( AliHLTFloat32_t x, AliHLTFloat32_t y, AliHLTFloat32_t z ) : fX(x), fY(y), fZ(z) { // Constructor for vertex. } AliHLTMUONMansoTrackerFSM::AliVertex::AliVertex(AliHLTMUONRecHitStruct xy, AliHLTFloat32_t z) : fX(xy.fX), fY(xy.fY), fZ(z) { // Construct vertex from a point on the XY plane and z coordinate. } AliHLTMUONMansoTrackerFSM::AliLine::AliLine( AliHLTFloat32_t ax, AliHLTFloat32_t ay, AliHLTFloat32_t az, AliHLTFloat32_t bx, AliHLTFloat32_t by, AliHLTFloat32_t bz ) : fMx(ax - bx), fMy(ay - by), fMz(az - bz), fCx(bx), fCy(by), fCz(bz) { // Construct a line defined by L = M*t + C = (A-B)*t + B // where M and C are 3D vectors and t is a free parameter. // A = (ax, ay, az) and B = (bx, by, bz) } AliHLTMUONMansoTrackerFSM::AliLine::AliLine(AliVertex a, AliVertex b) : fMx(a.X() - b.X()), fMy(a.Y() - b.Y()), fMz(a.Z() - b.Z()), fCx(b.X()), fCy(b.Y()), fCz(b.Z()) { // Contruct a line to go through two vertices a and b. } AliHLTMUONRecHitStruct AliHLTMUONMansoTrackerFSM::AliLine::FindIntersectWithXYPlain( AliHLTFloat32_t z ) const { // Find the point of intersection of the line and the XY plane at z. AliHLTFloat32_t t; if (fMz != 0) // Should not have a ray perpendicular to the beam axis. t = (z - fCz) / fMz; else t = 0; AliHLTMUONRecHitStruct p; p.fFlags = 0; p.fX = fMx*t + fCx; p.fY = fMy*t + fCy; p.fZ = z; return p; } AliHLTMUONMansoTrackerFSM::AliHLTMUONMansoTrackerFSM() : AliHLTLogging(), fCallback(NULL), fSm4state(kSM4Idle), fSm5state(kSM5Idle), fRequestsCompleted(0), fSt4chamber(kChamber1), fV1(), fMc1(), fSt5data(), fSt4points(), fSt5rec(), fFoundPoint(), fTriggerId(-1), fTrackId(0), fMakeCandidates(false), fCandidatesCount(0), fCandidatesSize(0), fCandidates(NULL) { // Default constructor } AliHLTMUONMansoTrackerFSM::~AliHLTMUONMansoTrackerFSM() { // Default destructor cleans up any allocated memory. if (fCandidates != NULL) delete [] fCandidates; } void AliHLTMUONMansoTrackerFSM::FindTrack(const AliHLTMUONTriggerRecordStruct& trigger) { // Tries to find the track from the trigger seed. DebugTrace("SM5 state = " << fSm5state << " , SM4 state = " << fSm4state); DebugTrace("Processing trigger with ID = " << trigger.fId); fTriggerId = trigger.fId; // Set Z coordinates of ideal point on trigger track to be nominal // chamber 11 and 13 positions. AliHLTMUONCalculations::IdealZ1(fgZ11); AliHLTMUONCalculations::IdealZ2(fgZ13); if (not AliHLTMUONCalculations::FitLineToTriggerRecord(trigger)) { NoTrackFound(); return; } fV1 = AliVertex( AliHLTMUONCalculations::IdealX1(), AliHLTMUONCalculations::IdealY1(), AliHLTMUONCalculations::IdealZ1() ); AliVertex v2 = AliVertex( AliHLTMUONCalculations::IdealX2(), AliHLTMUONCalculations::IdealY2(), AliHLTMUONCalculations::IdealZ2() ); DebugTrace("Using fV1 = {x = " << fV1.X() << ", y = " << fV1.Y() << ", " << fV1.Z() << "}"); DebugTrace("Using v2 = {x = " << v2.X() << ", y = " << v2.Y() << ", " << v2.Z() << "}"); // Form the vector line between the above two impact points and // find the crossing point of the line with chamber 10 (i.e. station 5). fMc1.fLine = AliLine(fV1, v2); AliHLTMUONRecHitStruct p10 = fMc1.fLine.FindIntersectWithXYPlain( fgZ10 ); // Build a region of interest for tracking station 5 (chamber 10). // Remember the parameters a and b are station specific. fMc1.fChamber = kChamber10; fMc1.fRoi.Create(p10, fgA10, fgB10); // Make SM5 state transition before the call to RequestClusters since // that method could call one of our methods again, so we need to be // in a consistant internal state. fSm5state = kWaitChamber10; if (fMakeCandidates) { fMc1.fCandidate = AddTrackCandidate(); if (fMc1.fCandidate != NULL) { *fMc1.fCandidate = AliHLTMUONConstants::NilMansoCandidateStruct(); fMc1.fCandidate->fTrack.fId = -1; fMc1.fCandidate->fTrack.fTrigRec = fTriggerId; fMc1.fCandidate->fTrack.fChi2 = -1; fMc1.fCandidate->fZmiddle = AliHLTMUONCalculations::Zf(); fMc1.fCandidate->fBl = AliHLTMUONCalculations::QBL(); fMc1.fCandidate->fRoI[3].fX = fMc1.fRoi.Centre().fX; fMc1.fCandidate->fRoI[3].fY = fMc1.fRoi.Centre().fY; fMc1.fCandidate->fRoI[3].fZ = fMc1.fRoi.Centre().fZ; fMc1.fCandidate->fRoI[3].fRadius = fMc1.fRoi.Radius(); } } AliHLTFloat32_t left, right, bottom, top; fMc1.fRoi.GetBoundaryBox(left, right, bottom, top); RequestClusters(left, right, bottom, top, kChamber10, &fMc1); } void AliHLTMUONMansoTrackerFSM::ReturnClusters( void* tag, const AliHLTMUONRecHitStruct* clusters, AliHLTUInt32_t count ) { // Implementation of AliHLTMUONMansoTrackerFSM::ReturnClusters. assert( count > 0 ); assert( clusters != NULL ); AliTagData* data = (AliTagData*)tag; DebugTrace("Got AliHLTMUONMansoTrackerFSM::ReturnClusters(tag = " << tag << ", chamber = " << data->fChamber << ", clusters = " << clusters << ", count = " << count << ")" ); DebugTrace("SM5 state = " << fSm5state << " , SM4 state = " << fSm4state); switch (data->fChamber) { case kChamber7: ReceiveClustersChamber7(clusters, count, data); break; case kChamber8: ReceiveClustersChamber8(clusters, count, data); break; case kChamber9: ReceiveClustersChamber9(clusters, count); break; case kChamber10: ReceiveClustersChamber10(clusters, count); break; default: // Error DebugTrace("ERROR: Got tag with an invalid value: " << data->fChamber); } } void AliHLTMUONMansoTrackerFSM::EndOfClusters(void* tag) { // Implementation of AliHLTMUONMansoTrackerFSM::EndOfClusters. AliTagData* data = (AliTagData*)tag; DebugTrace("Got AliHLTMUONMansoTrackerFSM::EndOfClusters(chamber = " << data->fChamber << ")"); DebugTrace("SM5 state = " << fSm5state << " , SM4 state = " << fSm4state); switch (data->fChamber) { case kChamber7: EndOfClustersChamber7(); break; case kChamber8: EndOfClustersChamber8(); break; case kChamber9: EndOfClustersChamber9(); break; case kChamber10: EndOfClustersChamber10(); break; default: // Error DebugTrace("ERROR: Got tag with an invalid value: " << data->fChamber); } } bool AliHLTMUONMansoTrackerFSM::FillTrackData(AliHLTMUONMansoTrackStruct& track) { // Implementation of AliHLTMUONMansoTrackerFSM::FillTrackData DebugTrace("FillTrack: st5 = " << fSt5rec->fClusterPoint << ", st4 = " << fFoundPoint->fClusterPoint); // Construct the track ID from the running counter fTrackId and the // bottom 8 bits of fTriggerId which will make this unique for an event. // 0x100 is forced for the Manso component. track.fId = (fTrackId << 10) | 0x100 | (fTriggerId & 0xFF); // Increment the track ID and warp it around at 0x1FFFFF since the // bottom 8 bits are copied from fTriggerId, bits 8 and 9 are forced to 01 // and the sign bit in track.fId must be positive. fTrackId = (fTrackId + 1) & 0x001FFFFF; track.fTrigRec = fTriggerId; AliHLTFloat32_t x1 = fFoundPoint->fClusterPoint.fX; AliHLTFloat32_t y1 = fFoundPoint->fClusterPoint.fY; AliHLTFloat32_t z1 = fFoundPoint->fClusterPoint.fZ; AliHLTFloat32_t y2 = fSt5rec->fClusterPoint.fY; AliHLTFloat32_t z2 = fSt5rec->fClusterPoint.fZ; bool calculated = AliHLTMUONCalculations::ComputeMomentum(x1, y1, y2, z1, z2); track.fPx = AliHLTMUONCalculations::Px(); track.fPy = AliHLTMUONCalculations::Py(); track.fPz = AliHLTMUONCalculations::Pz(); DebugTrace("Calculated Px = " << track.fPx << ", Py = " << track.fPy << ", Pz = " << track.fPx ); DebugTrace("\tusing x1 = " << x1 << " , y1 = " << y1 << " , y2 = " << y2 << " , z1 = " << z1 << " , z2 = " << z2 ); track.fChi2 = 0; bool hitset[4]; // Depending on which chamber we found reconstructed hits, fill the hit // in the appropriate location. This is done for station 4 then 5. if (fSt4chamber == kChamber8) { track.fHit[0] = AliHLTMUONConstants::NilRecHitStruct(); hitset[0] = false; track.fHit[1] = fFoundPoint->fClusterPoint; hitset[1] = true; } else { track.fHit[0] = fFoundPoint->fClusterPoint; hitset[0] = true; track.fHit[1] = AliHLTMUONConstants::NilRecHitStruct(); hitset[1] = false; } if (fMc1.fChamber == kChamber10) { track.fHit[2] = AliHLTMUONConstants::NilRecHitStruct(); hitset[2] = false; track.fHit[3] = fSt5rec->fClusterPoint; hitset[3] = true; } else { track.fHit[2] = fSt5rec->fClusterPoint; hitset[2] = true; track.fHit[3] = AliHLTMUONConstants::NilRecHitStruct(); hitset[3] = false; } track.fFlags = AliHLTMUONUtils::PackMansoTrackFlags( AliHLTMUONCalculations::Sign(), hitset ); if (fMakeCandidates) { AliHLTMUONMansoCandidateStruct* candidate = fSt5rec->fTag.fCandidate; if (candidate != NULL) { candidate->fTrack = track; } } return calculated; } void AliHLTMUONMansoTrackerFSM::Reset() { // Implementation of AliHLTMUONMansoTrackerFSM::Reset DebugTrace("SM5 state = " << fSm5state << " , SM4 state = " << fSm4state); fSt5data.Clear(); fSt4points.Clear(); fSm4state = kSM4Idle; fSm5state = kSM5Idle; fRequestsCompleted = 0; fTriggerId = -1; } // Note: In the following ReceiveClustersXXX and EndOfClustersXXX methods we make // the state machine transitions before calls to RequestClusters, FoundTrack, // NoTrackFound or EndOfClusterRequests. This is important since the callback // object will make recursive calls to the tracker's methods so we need to maintain // a consistant internal state. // The same would go for updating internal variables. // In general one should only call the callback methods at the end of any of the // following routines. void AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber7( const AliHLTMUONRecHitStruct* clusters, AliHLTUInt32_t count, const AliTagData* data ) { // State change method for Station 4 state machine. switch (fSm4state) { case kWaitChamber7: // We switch state below. case kWaitMoreChamber7: for (AliHLTUInt32_t j = 0; j < count; j++) { AliHLTMUONRecHitStruct cluster = clusters[j]; // Check that the cluster actually is in our region of interest on station 4. if ( data->fRoi.Contains(cluster) ) { // Go to next wait state only if we actually found anything in the RoI. fSm4state = kWaitMoreChamber7; DebugTrace("Adding cluster [" << cluster.fX << ", " << cluster.fY << "] from chamber 7."); AliStation4Data* newdata = fSt4points.Add(); newdata->fClusterPoint = cluster; newdata->fSt5tag = data; } } break; default: DebugTrace("ERROR: Unexpected state for SM4 in AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber7!"); } } void AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber8( const AliHLTMUONRecHitStruct* clusters, AliHLTUInt32_t count, const AliTagData* data ) { // State change method for Station 4 state machine. switch (fSm4state) { case kWaitChamber8: fSt4chamber = kChamber8; case kWaitMoreChamber8: for (AliHLTUInt32_t j = 0; j < count; j++) { AliHLTMUONRecHitStruct cluster = clusters[j]; // Check that the cluster actually is in our region of interest on station 4. if ( data->fRoi.Contains(cluster) ) { // Go to next wait state only if we actually found anything in the RoI. fSm4state = kWaitMoreChamber8; DebugTrace("Adding cluster [" << cluster.fX << ", " << cluster.fY << "] from chamber 8."); AliStation4Data* newdata = fSt4points.Add(); newdata->fClusterPoint = cluster; newdata->fSt5tag = data; } } break; default: DebugTrace("ERROR: Unexpected state for SM4 in AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber8!"); } } void AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber9( const AliHLTMUONRecHitStruct* clusters, AliHLTUInt32_t count ) { // State change method for Station 5 state machine. switch (fSm5state) { case kWaitChamber9: fSm4state = kWaitChamber8; // Start SM4. case kWaitMoreChamber9: for (AliHLTUInt32_t j = 0; j < count; j++) { AliHLTMUONRecHitStruct cluster = clusters[j]; // Check that the cluster actually is in our region of interest on station 5. if ( fMc1.fRoi.Contains(cluster) ) { // Go to next wait state only if we actually found anything in the RoI. fSm5state = kWaitMoreChamber9; DebugTrace("Adding cluster [" << cluster.fX << ", " << cluster.fY << "] from chamber 9."); AliStation5Data* data = fSt5data.Add(); data->fClusterPoint = cluster; ProjectToStation4(data, fgZ9, 2); // This adds a new request for station 4. } } break; default: DebugTrace("ERROR: Unexpected state for SM5 in AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber9!"); } } void AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber10( const AliHLTMUONRecHitStruct* clusters, AliHLTUInt32_t count ) { // State change method for Station 5 state machine. switch (fSm5state) { case kWaitChamber10: fSm4state = kWaitChamber8; // Start SM4. case kWaitMoreChamber10: for (AliHLTUInt32_t j = 0; j < count; j++) { AliHLTMUONRecHitStruct cluster = clusters[j]; // Check that the cluster actually is in our region of interest on station 5. if ( fMc1.fRoi.Contains(cluster) ) { // Go to next wait state only if we actually found anything in the RoI. fSm5state = kWaitMoreChamber10; DebugTrace("Adding cluster [" << cluster.fX << ", " << cluster.fY << "] from chamber 10."); AliStation5Data* data = fSt5data.Add(); data->fClusterPoint = cluster; ProjectToStation4(data, fgZ10, 3); // This adds a new request for station 4. } } break; default: DebugTrace("ERROR: Unexpected state for SM5 in AliHLTMUONMansoTrackerFSM::ReceiveClustersChamber10!"); } } void AliHLTMUONMansoTrackerFSM::EndOfClustersChamber7() { // State change method for Station 4 state machine. fRequestsCompleted++; // Increment the number of requests completed for station 4. DebugTrace("fRequestsCompleted = " << fRequestsCompleted ); switch (fSm4state) { case kWaitChamber7: // If all data from station 5 is received and no data found on // chambers 7 or 8 then we can not find a track. if (fSm5state == kSM5Done) NoTrackFound(); break; case kWaitMoreChamber7: if (fRequestsCompleted == fSt5data.Count() && fSm5state == kSM5Done) ProcessClusters(); break; default: DebugTrace("ERROR: Unexpected state for SM4 in AliHLTMUONMansoTrackerFSM::EndOfClustersChamber7!"); } } void AliHLTMUONMansoTrackerFSM::EndOfClustersChamber8() { // State change method for Station 4 state machine. fRequestsCompleted++; // Increment the number of requests completed for station 4. DebugTrace("fRequestsCompleted = " << fRequestsCompleted ); switch (fSm4state) { case kWaitChamber7: // Ignore. The requests for chamber 8 are already re-requested below. break; case kWaitChamber8: { fSm4state = kWaitChamber7; fSt4chamber = kChamber7; // We need to resend the requests for chamber 8, but change the request // to get data for chamber 7 instead: AliHLTUInt32_t reqlistsize = fSt5data.Count(); DebugTrace("Re-requesting clusters from chamber 7... reqlistsize = " << reqlistsize); Station5List::Iterator rec = fSt5data.First(); for (AliHLTUInt32_t i = 0; i < reqlistsize; i++, rec++) { // Need to create a new st5 data block for the request. AliStation5Data* data = fSt5data.Add(); data->fClusterPoint = rec->fClusterPoint; data->fTag.fLine = rec->fTag.fLine; data->fTag.fCandidate = rec->fTag.fCandidate; // Rebuild a region of interest for chamber 7. // Remember the parameters a and b are station specific. AliHLTMUONRecHitStruct p7 = data->fTag.fLine.FindIntersectWithXYPlain( fgZ7 ); data->fTag.fChamber = kChamber7; data->fTag.fRoi.Create(p7, fgA7, fgB7); if (fMakeCandidates and data->fTag.fCandidate != NULL) { data->fTag.fCandidate->fRoI[0].fX = data->fTag.fRoi.Centre().fX; data->fTag.fCandidate->fRoI[0].fY = data->fTag.fRoi.Centre().fY; data->fTag.fCandidate->fRoI[0].fZ = data->fTag.fRoi.Centre().fZ; data->fTag.fCandidate->fRoI[0].fRadius = data->fTag.fRoi.Radius(); } AliHLTFloat32_t left, right, bottom, top; data->fTag.fRoi.GetBoundaryBox(left, right, bottom, top); // Make request for chamber 7 data. RequestClusters(left, right, bottom, top, kChamber7, &data->fTag); } } break; case kWaitMoreChamber8: if (fRequestsCompleted == fSt5data.Count() && fSm5state == kSM5Done) ProcessClusters(); break; default: DebugTrace("ERROR: Unexpected state for SM4 in AliHLTMUONMansoTrackerFSM::EndOfClustersChamber8!"); } } void AliHLTMUONMansoTrackerFSM::EndOfClustersChamber9() { // State change method for Station 5 state machine. switch (fSm5state) { case kWaitChamber9: fSm5state = kSM5Done; EndOfClusterRequests(); NoTrackFound(); break; case kWaitMoreChamber9: fSm5state = kSM5Done; EndOfClusterRequests(); if (fRequestsCompleted == fSt5data.Count()) ProcessClusters(); break; default: DebugTrace("ERROR: Unexpected state for SM5 in AliHLTMUONMansoTrackerFSM::EndOfClustersChamber9!"); } } void AliHLTMUONMansoTrackerFSM::EndOfClustersChamber10() { // State change method for Station 5 state machine. switch (fSm5state) { case kWaitChamber10: { fSm5state = kWaitChamber9; // No clusters found on chamber 10 so we need to make a request for // clusters from chamber 9: AliHLTMUONRecHitStruct p9 = fMc1.fLine.FindIntersectWithXYPlain( fgZ9 ); // Build a region of interest for tracking station 5 (chamber 9). // Remember the parameters a and b are station specific. fMc1.fChamber = kChamber9; fMc1.fRoi.Create(p9, fgA9, fgB9); if (fMakeCandidates and fMc1.fCandidate != NULL) { fMc1.fCandidate->fRoI[2].fX = fMc1.fRoi.Centre().fX; fMc1.fCandidate->fRoI[2].fY = fMc1.fRoi.Centre().fY; fMc1.fCandidate->fRoI[2].fZ = fMc1.fRoi.Centre().fZ; fMc1.fCandidate->fRoI[2].fRadius = fMc1.fRoi.Radius(); } AliHLTFloat32_t left, right, bottom, top; fMc1.fRoi.GetBoundaryBox(left, right, bottom, top); RequestClusters(left, right, bottom, top, kChamber9, &fMc1); } break; case kWaitMoreChamber10: fSm5state = kSM5Done; EndOfClusterRequests(); if (fRequestsCompleted == fSt5data.Count()) ProcessClusters(); break; default: DebugTrace("ERROR: Unexpected state for SM5 in AliHLTMUONMansoTrackerFSM::EndOfClustersChamber10!"); } } void AliHLTMUONMansoTrackerFSM::ProjectToStation4( AliStation5Data* data, AliHLTFloat32_t station5z, AliHLTUInt32_t chamberSt5 ) { // Perform chamber specific operations: // Since certain states of SM4 means that it is fetching for Chamber8 // and other states are for fetching from Chamber7. We need to make // requests for the correct chamber. assert( fSm4state == kWaitChamber8 || fSm4state == kWaitMoreChamber8 || fSm4state == kWaitChamber7 || fSm4state == kWaitMoreChamber7 ); assert( chamberSt5 == 2 or chamberSt5 == 3 ); AliTagData* tag = &data->fTag; int chamber = 0; if (fSm4state == kWaitChamber8 || fSm4state == kWaitMoreChamber8) { // Form the vector line between trigger station 1 and tracking station 5, // and find the intersection point of the line with station 4 (chamber8). AliLine line51( AliVertex(data->fClusterPoint, station5z), fV1 ); AliHLTMUONRecHitStruct intercept = line51.FindIntersectWithXYPlain( fgZ8 ); tag->fLine = line51; // Build a region of interest for tracking station 4. tag->fChamber = kChamber8; tag->fRoi.Create(intercept, fgA8, fgB8); chamber = 1; } else { // Form the vector line between trigger station 1 and tracking station 5, // and find the intersection point of the line with station 4 (chamber7). AliLine line51( AliVertex(data->fClusterPoint, station5z), fV1 ); AliHLTMUONRecHitStruct intercept = line51.FindIntersectWithXYPlain( fgZ7 ); tag->fLine = line51; // Build a region of interest for tracking station 4. tag->fChamber = kChamber7; tag->fRoi.Create(intercept, fgA7, fgB7); chamber = 0; } if (fMakeCandidates) { // Make a copy of the track candidate if the exisiting track candidate // has already had its point on the given chamber filled. if (fMc1.fCandidate != NULL and fMc1.fCandidate->fTrack.fHit[chamberSt5] == AliHLTMUONConstants::NilRecHitStruct() ) { tag->fCandidate = fMc1.fCandidate; } else { tag->fCandidate = AddTrackCandidate(); if (tag->fCandidate != NULL and fMc1.fCandidate != NULL) *tag->fCandidate = *fMc1.fCandidate; } // Now fill the cluster point found on station 5 and RoI on station 4. if (tag->fCandidate != NULL) { tag->fCandidate->fTrack.fHit[chamberSt5] = data->fClusterPoint; tag->fCandidate->fRoI[chamber].fX = tag->fRoi.Centre().fX; tag->fCandidate->fRoI[chamber].fY = tag->fRoi.Centre().fY; tag->fCandidate->fRoI[chamber].fZ = tag->fRoi.Centre().fZ; tag->fCandidate->fRoI[chamber].fRadius = tag->fRoi.Radius(); } } // Make the request for clusters from station 4. AliHLTFloat32_t left, right, bottom, top; tag->fRoi.GetBoundaryBox(left, right, bottom, top); RequestClusters(left, right, bottom, top, tag->fChamber, tag); } void AliHLTMUONMansoTrackerFSM::ProcessClusters() { // Process clusters that have been received. // This is called once all clusters have been found. DebugTrace("ProcessClusters..."); // Check if the cluster point list on station 4 is empty. // If it is then we have not found any tracks. fFoundPoint = fSt4points.First(); if (fFoundPoint == fSt4points.End()) { NoTrackFound(); return; } fSt5rec = fSt5data.First(); if (fSt5rec != fSt5data.End()) { // Only look at station 5 data records that are for the found chamber number. // Note: either we only have chamber 8 data or we have chamber 7 data followed // by chamber 8 data. // Thus if we hit records that we are not interested in already then the list // contains no interesting data and we can signal no track found. if (fSt5rec->fTag.fChamber != fSt4chamber) { NoTrackFound(); return; } // For all combinations of cluster point pairs from station 4 and 5 // signal a found track: do { DebugTrace("\tfSt5rec->fTag.chamber = " << fSt5rec->fTag.fChamber << " , fSt4chamber = " << fSt4chamber ); for (fFoundPoint = fSt4points.First(); fFoundPoint != fSt4points.End(); fFoundPoint++) { if (fFoundPoint->fSt5tag == &fSt5rec->fTag) FoundTrack(); } fSt5rec++; // Get next station 5 cluster point. } while (fSt5rec != fSt5data.End() && fSt5rec->fTag.fChamber == fSt4chamber); } else NoTrackFound(); } AliHLTMUONMansoCandidateStruct* AliHLTMUONMansoTrackerFSM::AddTrackCandidate() { // Adds a new track candidate to the fCandidates list and returns a pointer // to the new structure. // First allocate or reallocate buffer if necessary. if (fCandidates == NULL) { try { fCandidates = new AliHLTMUONMansoCandidateStruct[1024]; } catch (...) { HLTError("Could not allocate buffer space for Manso track candidates."); return NULL; } fCandidatesSize = 1024; } else if (fCandidatesCount >= fCandidatesSize) { AliHLTMUONMansoCandidateStruct* newbuf = NULL; try { newbuf = new AliHLTMUONMansoCandidateStruct[fCandidatesSize*2]; } catch (...) { HLTError("Could not allocate more buffer space for Manso track candidates."); return NULL; } for (AliHLTUInt32_t i = 0; i < fCandidatesSize; ++i) newbuf[i] = fCandidates[i]; delete [] fCandidates; fCandidates = newbuf; fCandidatesSize = fCandidatesSize*2; } return &fCandidates[fCandidatesCount++]; }
31.101053
104
0.699113
AllaMaevskaya
e884601887984b9e0e3a0010c8ff81eb6242729a
5,827
cpp
C++
src/b_star_tree.cpp
harry830622/fixed-outline-floorplanning
8fc1fc91f0e3329c6369c8b1f863bcce31465430
[ "MIT" ]
4
2019-07-02T18:15:01.000Z
2021-12-22T06:09:35.000Z
src/b_star_tree.cpp
harry830622/fixed-outline-floorplanning
8fc1fc91f0e3329c6369c8b1f863bcce31465430
[ "MIT" ]
null
null
null
src/b_star_tree.cpp
harry830622/fixed-outline-floorplanning
8fc1fc91f0e3329c6369c8b1f863bcce31465430
[ "MIT" ]
1
2016-12-07T15:13:07.000Z
2016-12-07T15:13:07.000Z
#include "./b_star_tree.hpp" #include <stack> using namespace std; BStarTree::BStarTree(int num_macros) : root_id_(0), nodes_(num_macros, Node(-1, -1, -1)) { const int num_nodes = nodes_.size(); for (int i = 0; i < num_nodes - 1; ++i) { nodes_[i].left_child_id_ = i + 1; } for (int i = 1; i < num_nodes; ++i) { nodes_[i].parent_id_ = i - 1; } /* for (int i = 0; i < num_nodes / 2 + 1; ++i) { */ /* const int right_child_id = (i + 1) * 2; */ /* const int left_child_id = right_child_id - 1; */ /* if (left_child_id < num_nodes) { */ /* nodes_[i].left_child_id_ = left_child_id; */ /* } */ /* if (right_child_id < num_nodes) { */ /* nodes_[i].right_child_id_ = right_child_id; */ /* } */ /* } */ /* for (int i = 1; i < num_nodes; ++i) { */ /* nodes_[i].parent_id_ = (i - 1) / 2; */ /* } */ } void BStarTree::Print(ostream& os, int indent_level) const { const int indent_size = 2; os << string(indent_level * indent_size, ' ') << "BStarTree:" << endl; ++indent_level; os << string(indent_level * indent_size, ' ') << "root_id_:" << root_id_ << endl; os << string(indent_level * indent_size, ' ') << "nodes_:" << endl; ++indent_level; for (int i = 0; i < nodes_.size(); ++i) { const Node& node = nodes_[i]; os << string(indent_level * indent_size, ' ') << "Node: " << i << endl; ++indent_level; os << string(indent_level * indent_size, ' ') << "parent_id_: " << node.parent_id_ << endl; os << string(indent_level * indent_size, ' ') << "left_child_id_: " << node.left_child_id_ << endl; os << string(indent_level * indent_size, ' ') << "right_child_id_: " << node.right_child_id_ << endl; --indent_level; } } int BStarTree::num_nodes() const { return nodes_.size(); } int BStarTree::root_id() const { return root_id_; } int BStarTree::parent_id(int node_id) const { return node(node_id).parent_id_; } int BStarTree::left_child_id(int node_id) const { return node(node_id).left_child_id_; } int BStarTree::right_child_id(int node_id) const { return node(node_id).right_child_id_; } bool BStarTree::is_visited(int node_id) const { return node(node_id).is_visited_; } void BStarTree::Visit(int node_id) { node(node_id).is_visited_ = true; } void BStarTree::UnvisitAll() { for (Node& node : nodes_) { node.is_visited_ = false; } } void BStarTree::DeleteAndInsert(int deleted_node_id, int target_node_id, pair<int, int> inserted_positions) { Delete(deleted_node_id); Insert(deleted_node_id, target_node_id, inserted_positions); } // Private BStarTree::Node::Node(int parent_id, int left_child_id, int right_child_id) : parent_id_(parent_id), left_child_id_(left_child_id), right_child_id_(right_child_id), is_visited_(false) {} BStarTree::Node& BStarTree::node(int node_id) { return nodes_.at(node_id); } const BStarTree::Node& BStarTree::node(int node_id) const { return nodes_.at(node_id); } void BStarTree::Delete(int deleted_node_id) { Node& deleted_node = node(deleted_node_id); int child_id = -1; if (deleted_node.left_child_id_ != -1 && deleted_node.right_child_id_ != -1) { child_id = deleted_node.left_child_id_; int current_node_id = child_id; while (left_child_id(current_node_id) != -1 && right_child_id(current_node_id) != -1) { current_node_id = left_child_id(current_node_id); } if (right_child_id(current_node_id) != -1) { Node& current_node = node(current_node_id); current_node.left_child_id_ = current_node.right_child_id_; current_node.right_child_id_ = -1; } while (current_node_id != deleted_node_id) { Node& current_node = node(current_node_id); Node& current_parent = node(current_node.parent_id_); Node& current_parent_right_child = node(current_parent.right_child_id_); current_node.right_child_id_ = current_parent.right_child_id_; current_parent_right_child.parent_id_ = current_node_id; current_node_id = current_node.parent_id_; } } else if (deleted_node.left_child_id_ != -1) { child_id = deleted_node.left_child_id_; } else if (deleted_node.right_child_id_ != -1) { child_id = deleted_node.right_child_id_; } if (child_id != -1) { node(child_id).parent_id_ = deleted_node.parent_id_; } if (deleted_node.parent_id_ == -1) { root_id_ = child_id; } else { Node& parent = node(deleted_node.parent_id_); if (parent.left_child_id_ == deleted_node_id) { parent.left_child_id_ = child_id; } else { parent.right_child_id_ = child_id; } } deleted_node.parent_id_ = -1; deleted_node.left_child_id_ = -1; deleted_node.right_child_id_ = -1; } void BStarTree::Insert(int inserted_node_id, int target_node_id, pair<int, int> inserted_positions) { Node& inserted_node = node(inserted_node_id); Node& target_node = node(target_node_id); inserted_node.parent_id_ = target_node_id; if (inserted_positions.first % 2 == 0) { if (inserted_positions.second % 2 == 0) { inserted_node.left_child_id_ = target_node.left_child_id_; } else { inserted_node.right_child_id_ = target_node.left_child_id_; } if (target_node.left_child_id_ != -1) { node(target_node.left_child_id_).parent_id_ = inserted_node_id; } target_node.left_child_id_ = inserted_node_id; } else { if (inserted_positions.second % 2 == 0) { inserted_node.left_child_id_ = target_node.right_child_id_; } else { inserted_node.right_child_id_ = target_node.right_child_id_; } if (target_node.right_child_id_ != -1) { node(target_node.right_child_id_).parent_id_ = inserted_node_id; } target_node.right_child_id_ = inserted_node_id; } }
32.920904
80
0.665179
harry830622
e88ed1e4d2471b00c3465bfc83dfb065ad9c518c
1,614
cpp
C++
MonoNative.Tests/mscorlib/System/Collections/mscorlib_System_Collections_CollectionBase_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Collections/mscorlib_System_Collections_CollectionBase_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Collections/mscorlib_System_Collections_CollectionBase_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Collections // Name: CollectionBase // C++ Typed Name: mscorlib::System::Collections::CollectionBase #include <gtest/gtest.h> #include <mscorlib/System/Collections/mscorlib_System_Collections_CollectionBase.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { namespace Collections { //Public Methods Tests // Method GetEnumerator // Signature: TEST(mscorlib_System_Collections_CollectionBase_Fixture,GetEnumerator_Test) { } // Method Clear // Signature: TEST(mscorlib_System_Collections_CollectionBase_Fixture,Clear_Test) { } // Method RemoveAt // Signature: mscorlib::System::Int32 index TEST(mscorlib_System_Collections_CollectionBase_Fixture,RemoveAt_Test) { } //Public Properties Tests // Property Count // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Collections_CollectionBase_Fixture,get_Count_Test) { } // Property Capacity // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Collections_CollectionBase_Fixture,get_Capacity_Test) { } // Property Capacity // Return Type: mscorlib::System::Int32 // Property Set Method TEST(mscorlib_System_Collections_CollectionBase_Fixture,set_Capacity_Test) { } } } }
19.925926
88
0.707559
brunolauze
e890298d81106893bc5baae97f271530040ce03d
2,475
cpp
C++
tests/unit/test_app.cpp
dsiroky/backnocles
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
[ "MIT" ]
3
2017-10-22T17:57:10.000Z
2017-11-06T12:33:31.000Z
tests/unit/test_app.cpp
dsiroky/backnocles
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
[ "MIT" ]
null
null
null
tests/unit/test_app.cpp
dsiroky/backnocles
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
[ "MIT" ]
null
null
null
/// Test main app functions. /// /// @file #include <string> #include "backnocles/utils/disablewarnings.hpp" #include <gtest/gtest.h> #include <gmock/gmock.h> #include "backnocles/utils/enablewarnings.hpp" #include "backnocles/app.hpp" //========================================================================== namespace tests { //========================================================================== TEST(App, Request_UnknownCommand_OutputsUnknownCommand) { backnocles::App app{}; std::string output{}; bool quit_flag{false}; app.request("ndksfsldfjh", [&](const std::string_view& output_){ output = output_; }, [&](){ quit_flag = true; }); EXPECT_EQ(output, "unknown command: ndksfsldfjh"); EXPECT_FALSE(quit_flag); } //-------------------------------------------------------------------------- TEST(App, Request_Quit_OutputsByeAndCallsQuit) { backnocles::App app{}; std::string output{}; bool quit_flag{false}; app.request("quit", [&](const std::string_view& output_){ output = output_; }, [&](){ quit_flag = true; }); EXPECT_EQ(output, "bye"); EXPECT_TRUE(quit_flag); } //-------------------------------------------------------------------------- TEST(App, Request_AddHippo_OutputsAddedAndDoesNotQuit) { backnocles::App app{}; std::string output{}; bool quit_flag{false}; app.request("addanimal hippo", [&](const std::string_view& output_){ output = output_; }, [&](){ quit_flag = true; }); EXPECT_EQ(output, "hippo id:1 added"); EXPECT_FALSE(quit_flag); } //-------------------------------------------------------------------------- TEST(App, Request_AddMultipleAnimals_OutputsAddedWithDifferentIdsAndDoesNotQuit) { backnocles::App app{}; { std::string output{}; bool quit_flag{false}; app.request("addanimal hippo", [&](const std::string_view& output_){ output = output_; }, [&](){ quit_flag = true; }); EXPECT_EQ(output, "hippo id:1 added"); EXPECT_FALSE(quit_flag); } { std::string output{}; bool quit_flag{false}; app.request("addanimal turtle", [&](const std::string_view& output_){ output = output_; }, [&](){ quit_flag = true; }); EXPECT_EQ(output, "turtle id:2 added"); EXPECT_FALSE(quit_flag); } } //========================================================================== } // namespace
25
80
0.509495
dsiroky
e892ec7e37b29fa33e3f4df7abc7eff18936b3e1
2,500
cpp
C++
example/main.cpp
packetzero/vsqlite
5ac54389f1d1dfc91e34adf229eb20b6e6527d26
[ "MIT" ]
null
null
null
example/main.cpp
packetzero/vsqlite
5ac54389f1d1dfc91e34adf229eb20b6e6527d26
[ "MIT" ]
null
null
null
example/main.cpp
packetzero/vsqlite
5ac54389f1d1dfc91e34adf229eb20b6e6527d26
[ "MIT" ]
null
null
null
#include <vsqlite/vsqlite.h> #include "example_table.h" struct Function_power : public vsqlite::AppFunctionBase { Function_power() : vsqlite::AppFunctionBase("power", { TFLOAT64, TFLOAT64 }) {} DynVal func(const std::vector<DynVal> &args, std::string &errmsg) override { return pow((double)args[0], (double)args[1]); } }; struct Function_sqrt : public vsqlite::AppFunctionBase { Function_sqrt() : vsqlite::AppFunctionBase("sqrt", { TFLOAT64 }) {} DynVal func(const std::vector<DynVal> &args, std::string &errmsg) override { return sqrt((double)args[0]); } }; std::vector<vsqlite::SPAppFunction> gFunctions; std::vector<vsqlite::SPVirtualTable> gTables; static int usage(char *arg0) { printf("usage: %s \"<sql>\"\n", arg0); printf(" virtual tables:\n"); for (auto spTable : gTables) { printf(" %s\n", vsqlite::TableInfo(spTable).c_str()); } printf(" functions:\n"); for (auto spFunction : gFunctions) { printf(" %s\n", vsqlite::FunctionInfo(spFunction).c_str()); } printf("\n"); return 0; } int main(int argc, char *argv[]) { gFunctions.push_back(std::make_shared<Function_power>()); gFunctions.push_back(std::make_shared<Function_sqrt>()); gTables.push_back(newMyUsersTable()); if (argc < 2) { return usage(argv[0]); } vsqlite::SPVSQLite vsqlite = vsqlite::VSQLiteInstance(); vsqlite::SimpleQueryListener listener; for (auto spFunction : gFunctions) { int status = vsqlite->add(spFunction); if (status) { fprintf(stderr, "Failed to add function:'%s'\n", spFunction->name().c_str()); } } for (auto spTable : gTables) { int status = vsqlite->add(spTable); if (status) { fprintf(stderr, "Failed to add table:'%s'\n", spTable->getTableDef().schemaId->name.c_str()); } } std::string sql = argv[1]; int status = vsqlite->query(sql, listener); if (!listener.errmsgs.empty()) { fprintf(stderr, "Error:%s\n", listener.errmsgs[0].c_str()); } else if (listener.results.empty()) { if (status != 0) { printf("ERROR: %d\n", status); } else { printf("No results"); } } else { // print out results int i = 0; for (DynMap row : listener.results) { printf("[%02d] ", i++); for (auto it = row.begin(); it != row.end(); it++) { std::string value = (it->second.valid() ? it->second.as_s() : "null"); printf("'%s':'%s',", it->first->name.c_str(), value.c_str()); } puts(""); } } return 0; }
25.773196
99
0.6196
packetzero
e8945e67bfe429d0424bb8b7548cfbe6cb633c42
4,876
cpp
C++
inc/asmjit/Util.cpp
newcommerdontblame/ionlib
47ca829009e1529f62b2134aa6c0df8673864cf3
[ "MIT" ]
57
2016-05-15T20:17:16.000Z
2022-03-19T10:08:16.000Z
AsmJit/AsmJit/Util.cpp
DragonQuestHero/DarkMMap
c4fd125c8936334348b80804c4bfbd9952981d18
[ "MIT" ]
1
2016-11-04T16:45:23.000Z
2016-11-04T16:45:23.000Z
AsmJit/AsmJit/Util.cpp
DragonQuestHero/DarkMMap
c4fd125c8936334348b80804c4bfbd9952981d18
[ "MIT" ]
25
2016-05-31T19:12:10.000Z
2022-03-19T10:08:16.000Z
// [AsmJit] // Complete JIT Assembler for C++ Language. // // [License] // Zlib - See COPYING file in this package. // [Dependencies] #include "Build.h" #include "Util_p.h" // [Api-Begin] #include "ApiBegin.h" namespace AsmJit { // ============================================================================ // [AsmJit::Util] // ============================================================================ static const char letters[] = "0123456789ABCDEF"; char* Util::mycpy(char* dst, const char* src, sysuint_t len) ASMJIT_NOTHROW { if (src == NULL) return dst; if (len == (sysuint_t)-1) { while (*src) *dst++ = *src++; } else { memcpy(dst, src, len); dst += len; } return dst; } char* Util::myfill(char* dst, const int c, sysuint_t len) ASMJIT_NOTHROW { memset(dst, c, len); return dst + len; } char* Util::myhex(char* dst, const uint8_t* src, sysuint_t len) ASMJIT_NOTHROW { for (sysuint_t i = len; i; i--, dst += 2, src += 1) { dst[0] = letters[(src[0] >> 4) & 0xF]; dst[1] = letters[(src[0] ) & 0xF]; } return dst; } // Not too efficient, but this is mainly for debugging:) char* Util::myutoa(char* dst, sysuint_t i, sysuint_t base) ASMJIT_NOTHROW { ASMJIT_ASSERT(base <= 16); char buf[128]; char* p = buf + 128; do { sysint_t b = i % base; *--p = letters[b]; i /= base; } while (i); return Util::mycpy(dst, p, (sysuint_t)(buf + 128 - p)); } char* Util::myitoa(char* dst, sysint_t i, sysuint_t base) ASMJIT_NOTHROW { if (i < 0) { *dst++ = '-'; i = -i; } return Util::myutoa(dst, (sysuint_t)i, base); } // ============================================================================ // [AsmJit::Buffer] // ============================================================================ void Buffer::emitData(const void* dataPtr, sysuint_t dataLen) ASMJIT_NOTHROW { sysint_t max = getCapacity() - getOffset(); if ((sysuint_t)max < dataLen) { if (!realloc(getOffset() + dataLen)) return; } memcpy(_cur, dataPtr, dataLen); _cur += dataLen; } bool Buffer::realloc(sysint_t to) ASMJIT_NOTHROW { if (getCapacity() < to) { sysint_t len = getOffset(); uint8_t *newdata; if (_data) newdata = (uint8_t*)ASMJIT_REALLOC(_data, to); else newdata = (uint8_t*)ASMJIT_MALLOC(to); if (!newdata) return false; _data = newdata; _cur = newdata + len; _max = newdata + to; _max -= (to >= _growThreshold) ? _growThreshold : to; _capacity = to; } return true; } bool Buffer::grow() ASMJIT_NOTHROW { sysint_t to = _capacity; if (to < 512) to = 1024; else if (to > 65536) to += 65536; else to <<= 1; return realloc(to); } void Buffer::clear() ASMJIT_NOTHROW { _cur = _data; } void Buffer::free() ASMJIT_NOTHROW { if (!_data) return; ASMJIT_FREE(_data); _data = NULL; _cur = NULL; _max = NULL; _capacity = 0; } uint8_t* Buffer::take() ASMJIT_NOTHROW { uint8_t* data = _data; _data = NULL; _cur = NULL; _max = NULL; _capacity = 0; return data; } // ============================================================================ // [AsmJit::Zone] // ============================================================================ Zone::Zone(sysuint_t chunkSize) ASMJIT_NOTHROW { _chunks = NULL; _total = 0; _chunkSize = chunkSize; } Zone::~Zone() ASMJIT_NOTHROW { freeAll(); } void* Zone::zalloc(sysuint_t size) ASMJIT_NOTHROW { // Align to 4 or 8 bytes. size = (size + sizeof(sysint_t)-1) & ~(sizeof(sysint_t)-1); Chunk* cur = _chunks; if (!cur || cur->getRemainingBytes() < size) { sysuint_t chSize = _chunkSize; if (chSize < size) chSize = size; cur = (Chunk*)ASMJIT_MALLOC(sizeof(Chunk) - sizeof(void*) + chSize); if (!cur) return NULL; cur->prev = _chunks; cur->pos = 0; cur->size = _chunkSize; _chunks = cur; } uint8_t* p = cur->data + cur->pos; cur->pos += size; _total += size; return (void*)p; } char* Zone::zstrdup(const char* str) ASMJIT_NOTHROW { if (str == NULL) return NULL; sysuint_t len = strlen(str); if (len == 0) return NULL; // Include NULL terminator. len++; // Limit string length. if (len > 256) len = 256; char* m = reinterpret_cast<char*>(zalloc((len + 15) & ~15)); if (!m) return NULL; memcpy(m, str, len); m[len-1] = '\0'; return m; } void Zone::clear() ASMJIT_NOTHROW { Chunk* cur = _chunks; if (!cur) return; _chunks->pos = 0; _chunks->prev = NULL; _total = 0; cur = cur->prev; while (cur) { Chunk* prev = cur->prev; ASMJIT_FREE(cur); cur = prev; } } void Zone::freeAll() ASMJIT_NOTHROW { Chunk* cur = _chunks; _chunks = NULL; _total = 0; while (cur) { Chunk* prev = cur->prev; ASMJIT_FREE(cur); cur = prev; } } } // AsmJit namespace // [Api-End] #include "ApiEnd.h"
18.262172
79
0.541632
newcommerdontblame
e897b99959207dcdc88a8aed7fc5f98da1fcb5a4
2,263
cpp
C++
DSA/Trees/postorder-inorder.cpp
abhisheknaiidu/dsa
fe3f54df6802d2520142992b541602ce5ee24f26
[ "MIT" ]
54
2020-07-31T14:50:23.000Z
2022-03-14T11:03:02.000Z
DSA/Trees/postorder-inorder.cpp
abhisheknaiidu/NOOB
fe3f54df6802d2520142992b541602ce5ee24f26
[ "MIT" ]
null
null
null
DSA/Trees/postorder-inorder.cpp
abhisheknaiidu/NOOB
fe3f54df6802d2520142992b541602ce5ee24f26
[ "MIT" ]
30
2020-08-15T17:39:02.000Z
2022-03-10T06:50:18.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ // T-C => O(n^2) class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { int n = inorder.size(); int postInd = n-1; return helper(inorder, postorder, 0, n-1, postInd); } TreeNode* helper(vector<int>& inorder, vector<int>& postorder, int s, int e, int &postInd) { if(s > e) { cout << s << " " << e << endl; return NULL; } TreeNode* root = new TreeNode(postorder[postInd--]); cout << root->val << endl; int rootIndex = 0; for(int i=s; i<=e; i++) { if(inorder[i] == root->val) { rootIndex = i; break; } } cout << rootIndex << endl; root->right = helper(inorder, postorder, rootIndex+1, e, postInd); root->left = helper(inorder, postorder, s, rootIndex-1, postInd); return root; } }; // T.C => O(N) => using hash maps class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { int n = inorder.size(); unordered_map<int, int> inorderIndex; for(int i=0; i<n; i++) inorderIndex[inorder[i]] = i; int postInd = n-1; return helper(inorder, postorder, 0, n-1, postInd, inorderIndex); } TreeNode* helper(vector<int>& inorder, vector<int>& postorder, int s, int e, int &postInd, unordered_map<int, int> &inorderIndex) { if(s > e) { return NULL; } int nodeValue = postorder[postInd]; TreeNode* root = new TreeNode(nodeValue); postInd--; // if(s == e) return root; int rootIndex = inorderIndex[nodeValue]; root->right = helper(inorder, postorder, rootIndex+1, e, postInd, inorderIndex); root->left = helper(inorder, postorder, s, rootIndex-1, postInd, inorderIndex); return root; } };
31.873239
135
0.55369
abhisheknaiidu
e89a6d40285e06c8704aeb091ed5609211dbd338
821
hpp
C++
android-31/android/icu/text/CaseMap_Fold.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/icu/text/CaseMap_Fold.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/icu/text/CaseMap_Fold.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "./CaseMap.hpp" namespace android::icu::text { class CaseMap; } namespace android::icu::text { class Edits; } class JString; class JString; namespace android::icu::text { class CaseMap_Fold : public android::icu::text::CaseMap { public: // Fields // QJniObject forward template<typename ...Ts> explicit CaseMap_Fold(const char *className, const char *sig, Ts...agv) : android::icu::text::CaseMap(className, sig, std::forward<Ts>(agv)...) {} CaseMap_Fold(QJniObject obj); // Constructors // Methods JObject apply(JString arg0, JObject arg1, android::icu::text::Edits arg2) const; JString apply(JString arg0) const; android::icu::text::CaseMap_Fold omitUnchangedText() const; android::icu::text::CaseMap_Fold turkic() const; }; } // namespace android::icu::text
22.189189
173
0.704019
YJBeetle
e89ad71d380e8704a52fdb0833ec27ac6b42108c
951
hpp
C++
include/mockitopp/detail/util/horrible_cast.hpp
tpounds/mockitopp
775b151fa746c81c8762faea2de3429d6f3f46af
[ "MIT" ]
82
2015-03-19T06:28:00.000Z
2021-08-20T17:40:11.000Z
include/mockitopp/detail/util/horrible_cast.hpp
tpounds/mockitopp
775b151fa746c81c8762faea2de3429d6f3f46af
[ "MIT" ]
6
2015-03-19T08:46:46.000Z
2019-06-04T14:24:52.000Z
include/mockitopp/detail/util/horrible_cast.hpp
tpounds/mockitopp
775b151fa746c81c8762faea2de3429d6f3f46af
[ "MIT" ]
12
2015-03-19T08:15:32.000Z
2021-02-04T11:53:16.000Z
#ifndef __MOCKITOPP_HORRIBLE_CAST_HPP__ #define __MOCKITOPP_HORRIBLE_CAST_HPP__ #include <mockitopp/detail/util/cxx0x_static_assert.hpp> namespace mockitopp { namespace detail { /** * A potentially unsafe cast using a union of two possibly * incompatible data types that can be used to completely * subvert the compiler's cast system...USE WITH CAUTION! * * @author Trevor Pounds */ template <typename T, typename F> T horrible_cast(F from) { /** * Abort compilation to avoid casting potentially * incompatible types due obvious differences in size. */ //mockitopp_static_assert(sizeof(T) == sizeof(F)); union { F from; T to; } u; u.from = from; return u.to; } } // namespace detail } // namespace mockitopp #endif //__MOCKITOPP_HORRIBLE_CAST_HPP__
25.026316
64
0.605678
tpounds
e89fb588e859bdbf0987194d4a8f4eafbae64862
504
cpp
C++
c++/2 - Data Structures/Ordered Set.cpp
CarlosSalazar84/notebook
b2bb07daaf22d3eddfa09a2ea4484932bdaa75df
[ "MIT" ]
34
2016-03-07T16:43:38.000Z
2022-02-28T07:35:20.000Z
c++/2 - Data Structures/Ordered Set.cpp
CarlosSalazar84/notebook
b2bb07daaf22d3eddfa09a2ea4484932bdaa75df
[ "MIT" ]
72
2015-10-12T04:18:59.000Z
2021-03-17T02:00:12.000Z
c++/2 - Data Structures/Ordered Set.cpp
CarlosSalazar84/notebook
b2bb07daaf22d3eddfa09a2ea4484932bdaa75df
[ "MIT" ]
36
2016-08-12T16:46:56.000Z
2022-03-29T01:56:02.000Z
Estructura de datos basada en politicas. Funciona como un set<> pero es internamente indexado, cuenta con dos funciones adicionales. .find_by_order(k) -> Retorna un iterador al k-esimo elemento, si k >= size() retona .end() .order_of_key(x) -> Retorna cuantos elementos hay menores (<) que x #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
50.4
132
0.779762
CarlosSalazar84
e8a090e44d178debc32f6e978ce47515e1f56989
1,291
cpp
C++
Graphs/graph.cpp
hneralla/algorithms
73479196f4d0678b09bcfbc2b1f7e96669f9fea5
[ "Apache-2.0" ]
null
null
null
Graphs/graph.cpp
hneralla/algorithms
73479196f4d0678b09bcfbc2b1f7e96669f9fea5
[ "Apache-2.0" ]
null
null
null
Graphs/graph.cpp
hneralla/algorithms
73479196f4d0678b09bcfbc2b1f7e96669f9fea5
[ "Apache-2.0" ]
null
null
null
/** * @file graph.cpp * @author Harith Neralla * @date 7/8/2017 * @version 1.0 * * @brief Implementation of directed graphs. */ #include <stdio.h> #include <iostream> #include "graph.hpp" /** * @brief Default constructor for Graph. * * @param V is an int: number of vertices. * E is an int; number of edges. * * @return nothing */ Graph::Graph(int V, int E) { numOfVertices = V; numOfEdges = E; A = new Node[V]; } /** * @brief Prints graph contents to console. * * @param graph * @return nothing */ void Graph::writeGraph(Graph graph) { std::cout << std::endl << graph.getNumOfVertices() << " " << graph.getNumOfEdges() << std::endl; // Iterate through every vertex for (int i = 0; i < graph.getNumOfVertices(); i++) { std::cout << i + 1 << " :"; // Iterate through adjacency list for (long index = graph.A[i].adjacencyList.size()-1; index >= 0; index--) { std::cout << " (" << graph.A[i].adjacencyList[index].first + 1 // Adding 1 because index starts from 1 on console << " " << graph.A[i].adjacencyList[index].second << ")"; } std::cout << std::endl; } std::cout << std::endl; }
23.053571
129
0.538342
hneralla
e8a237f20432dcf73b2d5e0fb86c47308188460c
999
cpp
C++
MathTest/EllipseTest.cpp
PremiumGraphicsCodes/CGLib
eecd73c5af1a9e0c044e7d675318dbb496aec6b5
[ "MIT" ]
null
null
null
MathTest/EllipseTest.cpp
PremiumGraphicsCodes/CGLib
eecd73c5af1a9e0c044e7d675318dbb496aec6b5
[ "MIT" ]
null
null
null
MathTest/EllipseTest.cpp
PremiumGraphicsCodes/CGLib
eecd73c5af1a9e0c044e7d675318dbb496aec6b5
[ "MIT" ]
1
2022-02-03T08:09:03.000Z
2022-02-03T08:09:03.000Z
#include "gtest\gtest.h" #include "../Math/Ellipse.h" using namespace Crystal::Math; TEST(EllipseTest, TestGetPosition) { Ellipse<float> e(Vector2d<float>(1,0.5)); EXPECT_EQ(Vector2d<float>(1, 0), e.getPosition(Angle<float>(Degree<float>(0)))); EXPECT_EQ(Vector2d<float>(0, 0.5), e.getPosition(Angle<float>(Degree<float>(90)))); } TEST(EllipseTest, TestGetNormal) { Ellipse<float> e(Vector2d<float>(1, 0.5)); EXPECT_EQ(Vector2d<float>(1, 0), e.getNormal(Angle<float>(Degree<float>(0)))); EXPECT_EQ(Vector2d<float>(0, 1), e.getNormal(Angle<float>(Degree<float>(90)))); } TEST(EllipseTest, TestGetAngle) { Ellipse<float> e(Vector2d<float>(1, 0.5), Angle<float>(Degree<float>(90))); EXPECT_EQ(Angle<float>(Degree<float>(90)), e.getAngle()); } TEST(EllipseTest, TestRotate) { Ellipse<float> e(Vector2d<float>(1, 0.5), Angle<float>(Degree<float>(90))); e.rotate(Angle<float>(Degree<float>(90))); EXPECT_EQ(Angle<float>(Degree<float>(180)), e.getAngle()); }
31.21875
85
0.678679
PremiumGraphicsCodes
e8abcec3fd45ae2b49a62dc8bcabdaa2cc667883
10,933
cpp
C++
main.cpp
michalMilewski-8/baczek
67a54c50e85f2fea62fe4c5f23d0001e313c86af
[ "MIT" ]
null
null
null
main.cpp
michalMilewski-8/baczek
67a54c50e85f2fea62fe4c5f23d0001e313c86af
[ "MIT" ]
null
null
null
main.cpp
michalMilewski-8/baczek
67a54c50e85f2fea62fe4c5f23d0001e313c86af
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtc/quaternion.hpp> #include <glm/gtx/quaternion.hpp> #include <math.h> #define _USE_MATH_DEFINES #include <cmath> #include <vector> #include "Block.h" #include "Cursor.h" #include "Grid.h" #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include "Dependencies/include/rapidxml-1.13/rapidxml.hpp" #include "Dependencies/include/rapidxml-1.13/rapidxml_print.hpp" #include "Dependencies/include/rapidxml-1.13/rapidxml_utils.hpp" #include "./Dependencies/include/ImGuiFileDialog-Lib_Only/ImGuiFileDialog.h" #define DEFAULT_WIDTH 1280 #define DEFAULT_HEIGHT 720 #define EPS 0.1 #define PRECISION 1.0f using namespace rapidxml; using namespace std; glm::vec3 cameraPos, cameraFront, cameraUp, lookAt, moving_up; unsigned int width_, height_; int e = 0; glm::mat4 projection, view, model, mvp; glm::mat4 projection_i, view_i, model_i, mvp_i; glm::vec2 mousePosOld, angle; float start_angle = 45.0f; float angular_speed_ = 1.0f; float deltaTime = 0.0f; // Time between current frame and last frame float lastFrame = 0.0f; // Time of last frame float ipd = 0.01f; float d = 0.1f; float near = 0.01f; float far = 200.0f; bool animate = false; float T = 0.0f; float animation_time = 1.0f; int iteration_per_frame = 10; float distance_d = 1.0f; float speed = 0.2f; // speed of milling tool in milimeters per second; float size_x = 1; float size_y = 1; float size_z = 1; float denisity = 1; float timeSpeed = 1; int divisions_x = 400; int divisions_y = 400; glm::vec3 translation_s; glm::vec3 translation_e; glm::vec3 rot_euler_s; glm::vec3 rot_euler_e; glm::quat quaternion_s = { 0,0,0,1 }; glm::quat quaternion_e = { 0,0,0,1 }; bool draw_trajectory = false; Camera cam; Shader ourShader; std::unique_ptr<Grid> gridShader; GLFWwindow* window; GLFWwindow* window2; //std::unique_ptr<Cursor> cursor, center; std::vector<std::shared_ptr<Object>> objects_list = {}; std::unique_ptr<Block> block; std::unique_ptr<Cursor> cursor; std::unique_ptr<Line> trajectory; void draw_scene(); void draw_scene2(); void framebuffer_size_callback(GLFWwindow* window_1, int width, int height); void framebuffer_size_callback2(GLFWwindow* window_1, int width, int height); void processInput(GLFWwindow* window); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void create_gui(); int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "baczek 1", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } model = glm::mat4(1.0f); view = glm::mat4(1.0f); cameraPos = { 0,0,5 }; cameraFront = { 0,0,-1 }; lookAt = { 0,0,0 }; cameraUp = { 0,1,0 }; angle = { -90.0f, 0.0f }; width_ = DEFAULT_WIDTH; height_ = DEFAULT_HEIGHT; cam = Camera(cameraPos, cameraFront, cameraUp); cam.SetPerspective(glm::radians(45.0f), DEFAULT_WIDTH / (float)DEFAULT_HEIGHT, near, far); glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glViewport(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); const char* glsl_version = "#version 330"; // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(glsl_version); // build and compile our shader program // ------------------------------------ ourShader = Shader("shader.vs", "shader.fs"); // you can name your shader files however you like glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gridShader = std::make_unique<Grid>(); block = std::make_unique<Block>(size_x, size_y, size_z, divisions_x, divisions_y, ourShader); cursor = std::make_unique<Cursor>(ourShader); trajectory = std::make_unique<Line>(ourShader); { block->SetAngularSpeed(angular_speed_); float angle_rad = M_PI * start_angle / 180.0f; glm::quat q = glm::angleAxis(angle_rad, glm::vec3(0.0f, 0.0f, -1.0f)); block->RotateObject(q); block->SetDenisity(denisity); block->SetSize(size_x); } // render loop while (!glfwWindowShouldClose(window)) { glfwMakeContextCurrent(window); // cleaning frame glClearColor(0.2f, 0.2f, 0.2f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); projection = cam.GetProjectionMatrix(); projection_i = glm::inverse(projection); view = cam.GetViewMatrix(); view_i = glm::inverse(view); mvp = projection * view; float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; processInput(window); create_gui(); draw_scene(); // Render the grid gridShader->Draw(projection, view, projection_i, view_i); // Render dear imgui into screen ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // check and call events and swap the buffers glfwPollEvents(); glfwSwapBuffers(window); if (animate) { T += deltaTime / animation_time; } } // cleanup stuff ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); objects_list.clear(); ourShader.deleteShader(); return 0; } void draw_scene() { if (animate) { float delta = timeSpeed * deltaTime / iteration_per_frame; for (int i = 0; i < iteration_per_frame; i++) { block->CalculateFrame(delta); } block->DrawFrame(mvp); } else { block->DrawObject(mvp); } cursor->DrawObject(mvp); if (draw_trajectory) { trajectory->DrawObject(mvp); trajectory->AddPoint(block->GetPoint()); } else { trajectory->ClearPoints(); } } #pragma region boilerCodeOpenGL void framebuffer_size_callback(GLFWwindow* window_1, int width, int height) { glfwMakeContextCurrent(window_1); glViewport(0, 0, width, height); cam.SetPerspective(glm::radians(45.0f), width / (float)height, near, far); width_ = width; height_ = height; } void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (ImGui::GetIO().WantCaptureMouse) return; glm::vec2 mousePos = { xpos,ypos }; if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS) { glm::vec2 diff = (mousePosOld - mousePos) * PRECISION; float cameraSpeed = 5 * deltaTime; float radius; diff *= cameraSpeed; glm::vec3 right_movement = cam.GetRightVector() * -diff.x; glm::vec3 up_movement = cam.GetUpVector() * diff.y; glm::vec3 angle2 = lookAt - (cameraPos + right_movement + up_movement); auto rotation = Object::RotationBetweenVectors(lookAt - cameraPos, angle2); auto roation = glm::toMat4(rotation); angle += diff; if (angle.y > 90.0f) angle.y = 90.0f - EPS; if (angle.y < -90.0f) angle.y = -90.0f + EPS; if (angle.x > 180.0f) angle.x = -180.0f + EPS; if (angle.x < -180.0f) angle.x = 180.0f - EPS; radius = glm::length(cameraPos - lookAt); cameraPos.x = lookAt.x + radius * glm::cos(glm::radians(angle.y)) * glm::cos(glm::radians(angle.x)); cameraPos.z = lookAt.z + radius * -glm::cos(glm::radians(angle.y)) * glm::sin(glm::radians(angle.x)); cameraPos.y = lookAt.y + radius * glm::sin(glm::radians(-angle.y)); cameraFront = glm::normalize(lookAt - cameraPos); cam.LookAt(cameraPos, cameraFront, cameraUp); } if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) { glm::vec2 diff = (mousePosOld - mousePos) * PRECISION; float cameraSpeed = speed * deltaTime; glm::vec2 movement = diff * cameraSpeed; glm::vec3 right_movement = cam.GetRightVector() * movement.x; glm::vec3 up_movement = cam.GetUpVector() * -movement.y; cameraPos += right_movement + up_movement; lookAt += right_movement + up_movement; cam.LookAt(cameraPos, cameraFront, cameraUp); } mousePosOld = mousePos; } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { if (ImGui::GetIO().WantCaptureMouse) return; float precision = 0.01f; float movement = 1.0f - yoffset * precision; if (movement <= 0.0f) movement = 0.1f; cameraFront = glm::normalize(lookAt - cameraPos); float dist = glm::length(lookAt - cameraPos); cameraPos = lookAt - (cameraFront * dist * movement); cam.LookAt(cameraPos, cameraFront, cameraUp); } #pragma endregion void create_gui() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); //ImGui::ShowDemoWindow(); bool open; ImGuiWindowFlags flags = 0; //flags |= ImGuiWindowFlags_MenuBar; ImGui::Begin("Main Menu##uu", &open, flags); ImGui::SliderFloat("Time speed modifier", &timeSpeed,0.5f,20.0f); if (ImGui::InputFloat("Size of cube", &size_x)) block->SetSize(size_x); if (ImGui::InputFloat("Denisity of cube", &denisity)) block->SetDenisity(denisity); ImGui::InputInt("Max points on trajectory", &(trajectory->max_points)); if (ImGui::InputFloat("Starting angle", &start_angle)) { float angle_rad = M_PI * start_angle / 180.0f; glm::quat q = glm::angleAxis(angle_rad, glm::vec3(0.0f, 0.0f, -1.0f)); block->RotateObject(q); } if (ImGui::InputFloat("Starting angular speed", &angular_speed_)) { block->SetAngularSpeed(angular_speed_); } ImGui::Checkbox("Gravity", &(block->gravity)); ImGui::Checkbox("Draw cube", &(block->draw_cube)); ImGui::Checkbox("Draw diagonal", &(block->draw_diagonal)); ImGui::Checkbox("Draw trajectory", &draw_trajectory); ImGui::InputInt("Iterations per frame", &iteration_per_frame); if (ImGui::Button("Start Animation")) animate = true; if (ImGui::Button("Stop Animation")) animate = false; if (ImGui::Button("Restart Animation")) { float angle_rad = M_PI * start_angle / 180.0f; glm::quat q = glm::angleAxis(angle_rad, glm::vec3(0.0f, 0.0f, -1.0f)); block->RotateObject(q); block->SetAngularSpeed(angular_speed_); block->SetDenisity(denisity); block->SetSize(size_x); } ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); }
28.92328
123
0.719839
michalMilewski-8
e8b3a2ed7d3c78dfced440535027ab764a7d17fb
410
hh
C++
src/messages/filedescription.hh
cristalcho/VeloxMR
d726257d0a7e8c5153883991e26e6d36cee4d8dc
[ "Apache-2.0" ]
8
2016-11-29T11:08:16.000Z
2021-07-22T09:31:21.000Z
src/messages/filedescription.hh
cristalcho/VeloxMR
d726257d0a7e8c5153883991e26e6d36cee4d8dc
[ "Apache-2.0" ]
7
2016-11-29T06:22:37.000Z
2019-01-31T11:13:09.000Z
src/messages/filedescription.hh
cristalcho/VeloxMR
d726257d0a7e8c5153883991e26e6d36cee4d8dc
[ "Apache-2.0" ]
1
2019-01-15T05:16:59.000Z
2019-01-15T05:16:59.000Z
#pragma once #include "fileinfo.hh" #include <vector> namespace eclipse { namespace messages { struct FileDescription: public FileInfo { FileDescription() = default; ~FileDescription() = default; FileDescription& operator=(FileDescription&); std::string get_type() const override; std::vector<std::string> blocks; std::vector<uint32_t> hash_keys; std::vector<uint64_t> block_size; }; } }
16.4
47
0.72439
cristalcho
e8b5727419961ad3b4c08616410226958223fe66
5,632
cpp
C++
Engine/Source/Framework/ModuleManager.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
2
2022-01-11T21:15:31.000Z
2022-02-22T21:14:33.000Z
Engine/Source/Framework/ModuleManager.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
Engine/Source/Framework/ModuleManager.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
#include "ModuleManager.h" #include "Module.h" #include "Core/Log.h" #include "Framework/Application.h" #include "Utils/FileSystem.h" #include "Utils/VectorUtils.h" #include "Core/Profiling.h" void ModuleManager::LoadModule(const std::string& FullPath, const std::string& BaseSearchDirectory) { PROFILE_FUNC() //full path points to a .Module file if (IsModuleLoaded(File::GetFileNameFromPath(FullPath))) return; std::ifstream in; in.open(FullPath); if(in.is_open()) { Buffer FileBuf; File::ReadFile(FullPath, FileBuf); std::string stringValue = std::string(FileBuf.begin(), FileBuf.end()); Json::Reader reader; Json::Value value; reader.parse(stringValue, value); ModuleMetadata metadata; metadata.FromJson(value); for (auto& dep : metadata.Dependencies) { if(!IsModuleLoaded(dep.ModuleName)) LoadModuleFromName(dep.ModuleName, BaseSearchDirectory); } //finally load the actual module std::filesystem::path parent = std::filesystem::path(FullPath).parent_path(); std::string dllPath = parent.string() + "\\" + File::GetFileNameFromPath(FullPath) + ".dll"; LoadModuleDLL(dllPath, metadata); } else { LOG_ERROR("Failed to open " + FullPath); } } void ModuleManager::LoadModuleDLL(const std::string& ModuleDLLPath, const ModuleMetadata& metadata) { PROFILE_FUNC() //add the module dir (modules/myModule) as a dll path for external libs auto path = std::filesystem::path(ModuleDLLPath); SetDllDirectoryA(path.parent_path().string().c_str()); //load the dll auto TempInstance = LoadLibraryA(ModuleDLLPath.c_str()); ASSERT(TempInstance); auto func = (CreateModuleFunc)GetProcAddress(TempInstance, "CreateModule"); Module* mod = func(); //get the custom class module instance mod->m_Instance = TempInstance; //assign the module its instance m_LoadedModules.push_back(mod); //add to module array mod->m_ModuleManager = this; mod->m_App = m_App; mod->SetMetadata(metadata); mod->OnLoad(); EventModuleLoaded event; event.ModuleName = mod->GetThisModuleName(); m_EventDispatcher.Dispatch(event); } void ModuleManager::LoadModuleFromName(const std::string& ModuleName, const std::string& SearchPath) { PROFILE_FUNC() if (IsModuleLoaded(ModuleName)) return; for (const auto& file : std::filesystem::directory_iterator(SearchPath)) { std::string debug = file.path().filename().string(); if (file.is_directory() && file.path().filename().string() == ModuleName) { for (const auto& file : std::filesystem::directory_iterator(file.path())) { if (file.is_regular_file() && file.path().extension().string() == ".Module") { LoadModule(file.path().string(), SearchPath); return; } } } } LOG_ERROR("Module '{0}' Was not found", ModuleName); } bool ModuleManager::IsModuleLoaded(const std::string& ModuleName) { PROFILE_FUNC() for (auto it = m_LoadedModules.begin(); it != m_LoadedModules.end(); it++) { Module* mod = *it; if (mod->m_Name == ModuleName) { return true; } } return false; } void ModuleManager::LoadAllModules(const std::string& FolderPath) { PROFILE_FUNC() std::vector<std::string> ModuleNames; for (const auto& file : std::filesystem::directory_iterator(FolderPath)) { if (file.is_directory()) { ModuleNames.push_back(file.path().filename().string()); } } for (const auto& file : std::filesystem::recursive_directory_iterator(FolderPath)) { if (file.is_regular_file() && file.path().extension().string() == ".Module" && std::count(ModuleNames.begin(), ModuleNames.end(), File::GetFileNameFromPath(file.path().string())) > 0) { LoadModule(file.path().string(), FolderPath); } } } std::vector<std::string> ModuleManager::GetAllAvailableModuleNames(const std::string& FolderPath) const { std::vector<std::string> ModuleNames; for (const auto& file : std::filesystem::directory_iterator(FolderPath)) { if (file.is_directory()) { ModuleNames.push_back(file.path().filename().string()); } } return ModuleNames; } void ModuleManager::UnloadModule(const std::string& ModuleName) { PROFILE_FUNC() Module* ToUnload = nullptr; std::vector<Module*>::iterator ToUnloadIt; for (auto it = m_LoadedModules.begin(); it != m_LoadedModules.end(); it++) { Module* mod = *it; if (mod->m_Name == ModuleName) { ToUnload = *it; ToUnloadIt = it; break; } } if(!ToUnload) return; //no loaded module matches name //serach if other modules had this one as a dependency std::vector<std::string> ToUnloadChildren; for (auto it = m_LoadedModules.begin(); it != m_LoadedModules.end(); it++) { Module* mod = *it; for (auto& dep : mod->GetMetadata().Dependencies) { if(dep.ModuleName == ToUnload->GetThisModuleName()) ToUnloadChildren.push_back(mod->GetThisModuleName()); //recurisvly unload this module too } } //unload all children for (auto& mod : ToUnloadChildren) { UnloadModule(mod); } //finally unload the og module EventModuleUnloaded event; event.ModuleName = ToUnload->GetThisModuleName(); m_EventDispatcher.Dispatch(event); ToUnload->OnUnload(); delete ToUnload; m_LoadedModules.erase(ToUnloadIt); } void ModuleManager::UnloadAllModules() { PROFILE_FUNC() std::vector<std::string> AllModuleNames; for (auto& mod : m_LoadedModules) { AllModuleNames.push_back(mod->GetThisModuleName()); } for (size_t i = 0; i < AllModuleNames.size(); i++) { UnloadModule(AllModuleNames[i]); } m_LoadedModules.clear(); } void ModuleManager::Update(float DeltaTime) { PROFILE_FUNC() for (auto it = m_LoadedModules.begin(); it != m_LoadedModules.end(); it++) { (*it)->OnUpdate(DeltaTime); } }
25.031111
185
0.705433
wdrDarx
e8b5e0978cadf15618fec0ee3f655d2b21798ed3
4,108
cpp
C++
src/gdrive/revisions/RevisionsRevisionResource.cpp
Vadimatorik/googleQt
814ad6f695bb8e88d6a773e69fb8c188febaab00
[ "MIT" ]
24
2016-12-03T09:12:43.000Z
2022-03-29T19:51:48.000Z
src/gdrive/revisions/RevisionsRevisionResource.cpp
Vadimatorik/googleQt
814ad6f695bb8e88d6a773e69fb8c188febaab00
[ "MIT" ]
4
2016-12-03T09:14:42.000Z
2022-03-29T22:02:21.000Z
src/gdrive/revisions/RevisionsRevisionResource.cpp
Vadimatorik/googleQt
814ad6f695bb8e88d6a773e69fb8c188febaab00
[ "MIT" ]
7
2018-01-01T09:14:10.000Z
2022-03-29T21:50:11.000Z
/********************************************************** DO NOT EDIT This file was generated from stone specification "revisions" Part of "Ardi - the organizer" project. osoft4ardi@gmail.com www.prokarpaty.net ***********************************************************/ #include "gdrive/revisions/RevisionsRevisionResource.h" using namespace googleQt; namespace googleQt{ namespace revisions{ ///RevisionResource RevisionResource::operator QJsonObject()const{ QJsonObject js; this->toJson(js); return js; } void RevisionResource::toJson(QJsonObject& js)const{ if(!m_id.isEmpty()) js["id"] = QString(m_id); if(!m_kind.isEmpty()) js["kind"] = QString(m_kind); if(!m_mimeType.isEmpty()) js["mimeType"] = QString(m_mimeType); if(m_modifiedTime.isValid()) js["modifiedTime"] = m_modifiedTime.toString(Qt::ISODate); js["keepForever"] = m_keepForever; js["published"] = m_published; js["publishAuto"] = m_publishAuto; js["publishedOutsideDomain"] = m_publishedOutsideDomain; js["lastModifyingUser"] = (QJsonObject)m_lastModifyingUser; if(!m_originalFilename.isEmpty()) js["originalFilename"] = QString(m_originalFilename); if(!m_md5Checksum.isEmpty()) js["md5Checksum"] = QString(m_md5Checksum); js["size"] = QString("%1").arg(m_size); } void RevisionResource::fromJson(const QJsonObject& js){ m_id = js["id"].toString(); m_kind = js["kind"].toString(); m_mimeType = js["mimeType"].toString(); m_modifiedTime = QDateTime::fromString(js["modifiedTime"].toString(), Qt::ISODate); m_keepForever = js["keepForever"].toVariant().toBool(); m_published = js["published"].toVariant().toBool(); m_publishAuto = js["publishAuto"].toVariant().toBool(); m_publishedOutsideDomain = js["publishedOutsideDomain"].toVariant().toBool(); m_lastModifyingUser.fromJson(js["lastModifyingUser"].toObject()); m_originalFilename = js["originalFilename"].toString(); m_md5Checksum = js["md5Checksum"].toString(); m_size = js["size"].toVariant().toString().toULongLong(); } QString RevisionResource::toString(bool multiline)const { QJsonObject js; toJson(js); QJsonDocument doc(js); QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact)); return s; } std::unique_ptr<RevisionResource> RevisionResource::factory::create(const QByteArray& data) { QJsonDocument doc = QJsonDocument::fromJson(data); QJsonObject js = doc.object(); return create(js); } std::unique_ptr<RevisionResource> RevisionResource::factory::create(const QJsonObject& js) { std::unique_ptr<RevisionResource> rv; rv = std::unique_ptr<RevisionResource>(new RevisionResource); rv->fromJson(js); return rv; } #ifdef API_QT_AUTOTEST std::unique_ptr<RevisionResource> RevisionResource::EXAMPLE(int context_index, int parent_context_index){ Q_UNUSED(context_index); Q_UNUSED(parent_context_index); static int example_idx = 0; example_idx++; std::unique_ptr<RevisionResource> rv(new RevisionResource); rv->m_id = ApiAutotest::INSTANCE().getId("revisions::RevisionResource", example_idx); rv->m_kind = ApiAutotest::INSTANCE().getString("revisions::RevisionResource", "m_kind", QString("kind_%1").arg(example_idx)); rv->m_mimeType = ApiAutotest::INSTANCE().getString("revisions::RevisionResource", "m_mimeType", QString("mimeType_%1").arg(example_idx)); rv->m_modifiedTime = QDateTime::currentDateTime(); rv->m_lastModifyingUser = *(revisions::RevisionUser::EXAMPLE(0, context_index).get()); rv->m_originalFilename = ApiAutotest::INSTANCE().getString("revisions::RevisionResource", "m_originalFilename", QString("originalFilename_%1").arg(example_idx)); rv->m_md5Checksum = ApiAutotest::INSTANCE().getString("revisions::RevisionResource", "m_md5Checksum", QString("md5Checksum_%1").arg(example_idx)); rv->m_size = ApiAutotest::INSTANCE().getInt("revisions::RevisionResource", "m_size", 12 + example_idx); return rv; } #endif //API_QT_AUTOTEST }//revisions }//googleQt
37.688073
165
0.695716
Vadimatorik
e8b8337aa4e6fbe9dcddf8b6b2ef391ec484acb2
283
hh
C++
include/ScriptEngine/ScriptEngine.hh
kmc7468/ScriptEngine
5b9d19bc95a1d150cb63d285729249cf1afb1be6
[ "MIT" ]
1
2017-09-10T06:06:06.000Z
2017-09-10T06:06:06.000Z
include/ScriptEngine/ScriptEngine.hh
kmc7468/ScriptEngine
5b9d19bc95a1d150cb63d285729249cf1afb1be6
[ "MIT" ]
null
null
null
include/ScriptEngine/ScriptEngine.hh
kmc7468/ScriptEngine
5b9d19bc95a1d150cb63d285729249cf1afb1be6
[ "MIT" ]
null
null
null
#ifndef SCRIPTENGINE_HEADER_SCRIPTENGINE_HH # define SCRIPTENGINE_HEADER_SCRIPTENGINE_HH # include <ScriptEngine/Engine.hh> # include <ScriptEngine/LexerEngine.hh> # include <ScriptEngine/LexRule.hh> # include <ScriptEngine/ParserEngine.hh> # include <ScriptEngine/Token.hh> #endif
28.3
44
0.823322
kmc7468
e8bf37f03b6bd4932e1d0c3f2d72bd5c01627cef
846
cpp
C++
Linked List/141_Linked-List-Cycle.cpp
YunWGui/LeetCode
2587eca22195ec7d9263227554467ec4010cfe05
[ "MIT" ]
null
null
null
Linked List/141_Linked-List-Cycle.cpp
YunWGui/LeetCode
2587eca22195ec7d9263227554467ec4010cfe05
[ "MIT" ]
null
null
null
Linked List/141_Linked-List-Cycle.cpp
YunWGui/LeetCode
2587eca22195ec7d9263227554467ec4010cfe05
[ "MIT" ]
null
null
null
/* Title: 141. Linked List Cycle 141. 环形链表 Address: https://leetcode-cn.com/problems/linked-list-cycle/ Tips: 142. Linked List Cycle II https://leetcode-cn.com/problems/linked-list-cycle-ii/ */ #include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode( int x ) : val( x ), next( nullptr ) { }; }; // 方法一:双指针 - 快慢指针 class Solution { public: bool hasCycle(ListNode *head) { if ( head == nullptr ) return false; ListNode* fast = head; ListNode* slow = head; while ( fast != nullptr && fast->next != nullptr ) { slow = slow->next; fast = fast->next->next; if ( fast == slow ) return true; } return false; } }; int main() { return 0; }
18.391304
60
0.530733
YunWGui
e8c0a14bd6d043bc0575aa67fd915e187ebd4920
1,434
cpp
C++
UVA/11953.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/11953.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/11953.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
// Problem : 11953 - Battleships // Contest : UVa Online Judge // URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=3104 // Memory Limit : 32 MB // Time Limit : 1000 ms // Powered by CP Editor (https://github.com/cpeditor/cpeditor) #include<bits/stdc++.h> #define f first #define s second #define ll long long #define vi vector<int> #define pii pair<int, int> using namespace std; template<class T> using v=vector<T>; int dX[4]={-1, 1, 0, 0}; int dY[4]={0, 0, -1, 1}; int n; v<string> grid; bool isValid(int x, int y){ return x>=0 && x<n && y>=0 && y<n && (grid[x][y]=='@' || grid[x][y]=='x'); } void expand(int x, int y){ queue<pii> q; q.push({x, y}); grid[x][y]='*'; while(!q.empty()){ auto act=q.front(); q.pop(); int aX=act.f; int aY=act.s; for(int i=0; i<4; i++){ int nX=aX+dX[i]; int nY=aY+dY[i]; if(isValid(nX, nY)){ q.push({nX, nY}); grid[nX][nY]='*'; } } } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int cases; cin >> cases; for(int actCase=1; actCase<=cases; actCase++){ cin >> n; grid=v<string>(n); for(auto &row : grid) cin >> row; int ans=0; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(grid[i][j]=='x'){ expand(i, j); ans++; } } } cout << "Case " << actCase << ": " << ans << "\n"; } return 0; }
21.727273
117
0.543236
DT3264
e8c11a20605899b619b837b86dfa06e2d195f028
1,577
cpp
C++
src/page_02/task081.cpp
berlios/pe
5edd686481666c86a14804cfeae354a267d468be
[ "MIT" ]
null
null
null
src/page_02/task081.cpp
berlios/pe
5edd686481666c86a14804cfeae354a267d468be
[ "MIT" ]
null
null
null
src/page_02/task081.cpp
berlios/pe
5edd686481666c86a14804cfeae354a267d468be
[ "MIT" ]
null
null
null
#include <algorithm> #include <limits> #include <string> #include <vector> #include "base/common.h" #include "base/task.h" namespace { struct Node { Node(int new_weight) : weight(new_weight) {} int weight; int minimum_cost_to_end = std::numeric_limits<int>::max(); }; } TASK(81) { auto rows = Split(ReadFileIntoString("data/081_matrix.txt"), '\n', SkipEmpty()); const int n = rows.size(); std::vector<std::vector<Node>> matrix; for (const std::string& row : rows) { matrix.emplace_back(); for (const std::string& weight_string : Split(row, ',')) { matrix.back().emplace_back(stoi(weight_string)); } CHECK(matrix.back().size() == static_cast<size_t>(n)); } CHECK(matrix.size() == static_cast<size_t>(n)); matrix.back().back().minimum_cost_to_end = matrix.back().back().weight; for (int i = n - 2; i >= 0; --i) { matrix.back()[i].minimum_cost_to_end = matrix.back()[i].weight + matrix.back()[i + 1].minimum_cost_to_end; } for (int i = n - 2; i >= 0; --i) { matrix[i].back().minimum_cost_to_end = matrix[i].back().weight + matrix[i + 1].back().minimum_cost_to_end; } for (int sum = 2 * n - 3; sum >= 0; --sum) { for (int i = std::min(n - 2, sum); i >= 0; --i) { int j = sum - i; if (j > n - 2) { break; } matrix[i][j].minimum_cost_to_end = matrix[i][j].weight + std::min(matrix[i + 1][j].minimum_cost_to_end, matrix[i][j + 1].minimum_cost_to_end); } } return matrix[0][0].minimum_cost_to_end; }
27.666667
79
0.583386
berlios
e8c12db6343bcfdebbc9688465701f9bad399ea4
10,278
cpp
C++
Sail/src/Sail/entities/components/ParticleEmitterComponent.cpp
BTH-StoraSpel-DXR/SPLASH
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
12
2019-09-11T15:52:31.000Z
2021-11-14T20:33:35.000Z
Sail/src/Sail/entities/components/ParticleEmitterComponent.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
227
2019-09-11T08:40:24.000Z
2020-06-26T14:12:07.000Z
Sail/src/Sail/entities/components/ParticleEmitterComponent.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
2
2020-10-26T02:35:18.000Z
2020-10-26T02:36:01.000Z
#include "pch.h" #include "ParticleEmitterComponent.h" #include "Sail/Application.h" #include "Sail/graphics/shader/compute/ParticleComputeShader.h" #include "API/DX12/shader/DX12ConstantBuffer.h" #include "API/DX12/DX12Utils.h" #include "API/DX12/DX12VertexBuffer.h" #include "API/DX12/resources/DescriptorHeap.h" ParticleEmitterComponent::ParticleEmitterComponent() : m_hasBeenCreatedInSystem(false) { size = 0.2f; offset = { 0.f, 0.f, 0.f }; position = { 0.f, 0.f, 0.f }; spread = { 0.f, 0.f, 0.f }; constantVelocity = { 0.f, 0.f, 0.f }; velocity = { 0.f, 0.f, 0.f }; acceleration = { 0.f, 0.f, 0.f }; lifeTime = 1.0f; spawnRate = 0.1f; spawnTimer = 0.0f; atlasSize = glm::uvec2(1U, 1U); drag = 0.0f; maxNumberOfParticles = 300; isActive = false; init(); } ParticleEmitterComponent::~ParticleEmitterComponent() { delete[] m_cpuOutput; delete[] m_particleLife; } void ParticleEmitterComponent::init() { m_particleLife = SAIL_NEW std::vector<float>[DX12API::NUM_GPU_BUFFERS]; m_cpuOutput = SAIL_NEW CPUOutput[DX12API::NUM_GPU_BUFFERS]; for (unsigned int i = 0; i < DX12API::NUM_GPU_BUFFERS; i++) { m_cpuOutput[i].previousNrOfParticles = 0; m_cpuOutput[i].lastFrameTime = 0; } m_timer.startTimer(); m_startTime = m_timer.getStartTime(); m_gpuUpdates = 0; } void ParticleEmitterComponent::syncWithGPUUpdate(unsigned int swapBufferIndex, unsigned int outputVertexBufferSize) { // Remove unsigned int numToRemove = (unsigned int)m_cpuOutput[swapBufferIndex].toRemove.size(); for (unsigned int i = 0; i < numToRemove; i++) { unsigned int swapIndex = 0; if (m_cpuOutput[swapBufferIndex].toRemove[i] < m_cpuOutput[swapBufferIndex].previousNrOfParticles - numToRemove) { swapIndex = m_cpuOutput[swapBufferIndex].previousNrOfParticles - i - 1; int counter = 0; while (m_cpuOutput[swapBufferIndex].toRemove[numToRemove - counter - 1] >= swapIndex && counter < numToRemove - 1) { swapIndex--; counter++; } if (swapIndex > m_cpuOutput[swapBufferIndex].toRemove[i]) { m_particleLife[swapBufferIndex][m_cpuOutput[swapBufferIndex].toRemove[i]] = m_particleLife[swapBufferIndex][swapIndex]; } } } m_particleLife[swapBufferIndex].erase(m_particleLife[swapBufferIndex].begin() + m_cpuOutput[swapBufferIndex].previousNrOfParticles - numToRemove, m_particleLife[swapBufferIndex].end()); // Add unsigned int numToAdd = glm::min(glm::min((unsigned int)m_cpuOutput[swapBufferIndex].newParticles.size(), m_maxParticlesSpawnPerFrame), (unsigned int)(floor(outputVertexBufferSize / 6) - (m_cpuOutput[swapBufferIndex].previousNrOfParticles - numToRemove))); for (unsigned int i = 0; i < numToAdd; i++) { m_particleLife[swapBufferIndex].emplace_back(); m_particleLife[swapBufferIndex].back() = lifeTime - (m_cpuOutput[swapBufferIndex].lastFrameTime - m_cpuOutput[swapBufferIndex].newParticles[i].spawnTime); } } bool ParticleEmitterComponent::hasBeenCreatedInSystem() { return m_hasBeenCreatedInSystem; } void ParticleEmitterComponent::setAsCreatedInSystem(bool created) { m_hasBeenCreatedInSystem = created; } const std::string& ParticleEmitterComponent::getTextureName() const { return m_textureName; } void ParticleEmitterComponent::spawnParticles(int particlesToSpawn) { int maxCount = 0; for (unsigned int i = 0; i < DX12API::NUM_GPU_BUFFERS; i++) { if ((int) m_cpuOutput->newParticles.size() > maxCount) { maxCount = m_cpuOutput->newParticles.size(); } } particlesToSpawn = glm::min(particlesToSpawn, (int) (m_maxParticlesSpawnPerFrame - maxCount)); //Spawn particles for all swap buffers for (int j = 0; j < particlesToSpawn; j++) { //Get random spread glm::vec3 randVec = { (Utils::rnd() - 0.5f) * 2.0f, (Utils::rnd() - 0.5f) * 2.0f, (Utils::rnd() - 0.5f) * 2.0f }; //Get time float time = m_timer.getTimeSince<float>(m_startTime); //Add particle to spawn list for (unsigned int i = 0; i < DX12API::NUM_GPU_BUFFERS; i++) { m_cpuOutput[i].newParticles.emplace_back(); m_cpuOutput[i].newParticles.back().pos = position + (randVec + glm::vec3(0.0f, 1.0f, 0.0f)) * 0.02f ; m_cpuOutput[i].newParticles.back().spread = spread * randVec; m_cpuOutput[i].newParticles.back().spawnTime = time; } } } void ParticleEmitterComponent::updateTimers(float dt) { for (int i = 0; i < DX12API::NUM_GPU_BUFFERS; i++) { for (int j = 0; j < m_particleLife[i].size(); j++) { m_particleLife[i][j] -= dt; } } if (spawnTimer >= spawnRate && isActive) { //Spawn the correct number of particles int particlesToSpawn = (int)glm::floor(spawnTimer / glm::max(spawnRate, 0.0001f)); spawnParticles(particlesToSpawn); //Decrease timer spawnTimer -= glm::max(spawnRate, 0.0001f) * particlesToSpawn; } spawnTimer += dt; } void ParticleEmitterComponent::updateOnGPU(ID3D12GraphicsCommandList4* cmdList, const glm::vec3& cameraPos, EmitterData& data, ComputeShaderDispatcher& dispatcher) { auto* context = Application::getInstance()->getAPI<DX12API>(); if (m_gpuUpdates < (int)(DX12API::NUM_GPU_BUFFERS * 2)) { //Initialize timers the first two times the buffers are ran float elapsedTime = m_timer.getTimeSince<float>(m_startTime) - m_cpuOutput[context->getSwapIndex()].lastFrameTime; m_cpuOutput[context->getSwapIndex()].lastFrameTime += elapsedTime; m_gpuUpdates++; } else { data.outputVertexBuffer->init(cmdList); auto* settings = data.particleShader->getComputeSettings(); //----Compute shader constant buffer---- m_inputData.cameraPos = cameraPos; m_inputData.previousNrOfParticles = m_cpuOutput[context->getSwapIndex()].previousNrOfParticles; m_inputData.maxOutputVertices = data.outputVertexBufferSize; float elapsedTime = m_timer.getTimeSince<float>(m_startTime) - m_cpuOutput[context->getSwapIndex()].lastFrameTime; m_inputData.frameTime = elapsedTime; m_inputData.size = size; m_inputData.atlasSize = atlasSize; m_inputData.drag = drag; //Update timer for this buffer m_cpuOutput[context->getSwapIndex()].lastFrameTime += elapsedTime; //Gather particles to remove for (unsigned int i = 0; i < m_particleLife[context->getSwapIndex()].size(); i++) { if (m_particleLife[context->getSwapIndex()][i] < 0.0f && m_cpuOutput[context->getSwapIndex()].toRemove.size() < m_maxParticlesSpawnPerFrame - 1) { m_cpuOutput[context->getSwapIndex()].toRemove.emplace_back(); m_cpuOutput[context->getSwapIndex()].toRemove.back() = i; } } //Sort it so that the overlaps when swaping on the gpu can easily be found std::sort(m_cpuOutput[context->getSwapIndex()].toRemove.begin(), m_cpuOutput[context->getSwapIndex()].toRemove.end()); // Particles to remove unsigned int numPartRem = (unsigned int)m_cpuOutput[context->getSwapIndex()].toRemove.size(); m_inputData.numParticlesToRemove = numPartRem; for (unsigned int i = 0; i < numPartRem; i++) { m_inputData.particlesToRemove[i] = m_cpuOutput[context->getSwapIndex()].toRemove[i]; } // Particles to add unsigned int numPart = glm::min(glm::min((unsigned int)m_cpuOutput[context->getSwapIndex()].newParticles.size(), m_maxParticlesSpawnPerFrame), (unsigned int)(floor(data.outputVertexBufferSize / 6) - (m_cpuOutput[context->getSwapIndex()].previousNrOfParticles - numPartRem))); m_inputData.numParticles = numPart; for (unsigned int i = 0; i < numPart; i++) { const NewParticleInfo* newParticle_i = &m_cpuOutput[context->getSwapIndex()].newParticles[i]; m_inputData.particles[i].position = newParticle_i->pos; m_inputData.particles[i].velocity = velocity + newParticle_i->spread; m_inputData.particles[i].acceleration = acceleration; m_inputData.particles[i].spawnTime = m_cpuOutput[context->getSwapIndex()].lastFrameTime - newParticle_i->spawnTime; } data.inputConstantBuffer->updateData_new(&m_inputData, sizeof(ComputeInput), 0); data.inputConstantBuffer->bind_new(cmdList, 0, true); //-------------------------------------- auto& cdh = context->getComputeGPUDescriptorHeap()->getCurentCPUDescriptorHandle(); cdh.ptr += context->getComputeGPUDescriptorHeap()->getDescriptorIncrementSize() * 10; D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.Format = DXGI_FORMAT_UNKNOWN; uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = 0; uavDesc.Buffer.NumElements = data.outputVertexBufferSize; uavDesc.Buffer.StructureByteStride = 4 * 14; // TODO: replace with sizeof(Vertex) context->getDevice()->CreateUnorderedAccessView(data.outputVertexBuffer->getBuffer(), nullptr, &uavDesc, cdh); // Transition to UAV access DX12Utils::SetResourceTransitionBarrier(cmdList, data.outputVertexBuffer->getBuffer(), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); //----Compute shader physics buffer---- cdh.ptr += context->getComputeGPUDescriptorHeap()->getDescriptorIncrementSize(); uavDesc = {}; uavDesc.Format = DXGI_FORMAT_UNKNOWN; uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = 0; uavDesc.Buffer.NumElements = data.outputVertexBufferSize / 6; uavDesc.Buffer.StructureByteStride = data.particlePhysicsSize; context->getDevice()->CreateUnorderedAccessView(data.physicsBufferDefaultHeap[context->getSwapIndex()].Get(), nullptr, &uavDesc, cdh); //------------------------------------- dispatcher.dispatch(*data.particleShader, Shader::ComputeShaderInput(), cmdList); context->getComputeGPUDescriptorHeap()->getAndStepIndex(12); // Transition to Cbuffer usage DX12Utils::SetResourceTransitionBarrier(cmdList, data.outputVertexBuffer->getBuffer(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); //Sync cpu arrays with GPU syncWithGPUUpdate(context->getSwapIndex(), data.outputVertexBufferSize); // Update nr of particles in this buffer and erase added and removed emitters from the queues m_cpuOutput[context->getSwapIndex()].previousNrOfParticles = glm::min(m_cpuOutput[context->getSwapIndex()].previousNrOfParticles + numPart - numPartRem, data.outputVertexBufferSize / 6); m_cpuOutput[context->getSwapIndex()].newParticles.clear(); m_cpuOutput[context->getSwapIndex()].toRemove.clear(); } } void ParticleEmitterComponent::setTexture(const std::string& textureName) { m_textureName = textureName; }
41.95102
277
0.742946
BTH-StoraSpel-DXR
e8cc2c86ff27379c977fa7d504201da26dc887c9
24
cpp
C++
src/Reference.cpp
phiwen96/ph_image
282bdd835d721a561c4f3afcbb76af5f9bda87ba
[ "Apache-2.0" ]
null
null
null
src/Reference.cpp
phiwen96/ph_image
282bdd835d721a561c4f3afcbb76af5f9bda87ba
[ "Apache-2.0" ]
null
null
null
src/Reference.cpp
phiwen96/ph_image
282bdd835d721a561c4f3afcbb76af5f9bda87ba
[ "Apache-2.0" ]
null
null
null
#include "Reference.hpp"
24
24
0.791667
phiwen96
e8cc3daef0503ad49adf874198834ef3b8f9d8cf
1,279
cpp
C++
rubikdetectorcore/src/imagesaver/ImageSaver.cpp
rohithdsouza/RubikDetector-Android
3b6824d32e0034666d3f60375959b405cb58f0e0
[ "Apache-2.0" ]
42
2018-01-24T11:26:57.000Z
2022-02-27T17:04:00.000Z
rubikdetectorcore/src/imagesaver/ImageSaver.cpp
rohithdsouza/RubikDetector-Android
3b6824d32e0034666d3f60375959b405cb58f0e0
[ "Apache-2.0" ]
3
2017-11-18T08:00:30.000Z
2017-11-18T08:08:31.000Z
rubikdetectorcore/src/imagesaver/ImageSaver.cpp
rohithdsouza/RubikDetector-Android
3b6824d32e0034666d3f60375959b405cb58f0e0
[ "Apache-2.0" ]
9
2018-01-24T09:44:53.000Z
2022-02-21T19:53:16.000Z
// // Created by catalin on 31.07.2017. // #include <sstream> #include <opencv2/highgui/highgui.hpp> #include "../../include/rubikdetector/imagesaver/ImageSaver.hpp" #include "../../include/rubikdetector/utils/CrossLog.hpp" namespace rbdt { ImageSaver::ImageSaver(const std::string saveLocation) : path(saveLocation) {} ImageSaver::~ImageSaver() { if (debuggable) { LOG_DEBUG("RubikJniPart.cpp", "ImageSaver - destructor."); } } bool ImageSaver::saveImage(const cv::Mat &mat, const int frameNumber, const int regionId) { std::stringstream regionIdStringStream; regionIdStringStream << regionId; return saveImage(mat, frameNumber, regionIdStringStream.str()); } bool ImageSaver::saveImage(const cv::Mat &mat, const int frameNumber, const std::string regionName) { std::stringstream frameNrStringStream; frameNrStringStream << frameNumber; std::string store_path = path + "/pic_" + frameNrStringStream.str() + "_" + regionName + ".jpg"; return cv::imwrite(store_path, mat); } void ImageSaver::setDebuggable(const bool debuggable) { ImageSaver::debuggable = debuggable; } bool ImageSaver::isDebuggable() const { return ImageSaver::debuggable; } } //end namespace rbdt
29.744186
100
0.691165
rohithdsouza
e8d00320e93106dda9299a54c518d5bc553a01ba
23,174
hpp
C++
Solutions/Headers/Debug.hpp
kitegi/Edmonton
774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d
[ "Unlicense" ]
2
2021-07-16T13:30:10.000Z
2021-07-16T18:17:40.000Z
Solutions/Headers/Debug.hpp
kitegi/Edmonton
774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d
[ "Unlicense" ]
null
null
null
Solutions/Headers/Debug.hpp
kitegi/Edmonton
774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d
[ "Unlicense" ]
1
2021-04-16T22:56:07.000Z
2021-04-16T22:56:07.000Z
/***************************************************************************** dbg(...) macro License (MIT): Copyright (c) 2019 David Peter <mail@david-peter.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ #ifndef DBG_MACRO_DBG_H #define DBG_MACRO_DBG_H #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #define DBG_MACRO_UNIX #elif defined(_MSC_VER) #define DBG_MACRO_WINDOWS #endif #ifndef DBG_MACRO_NO_WARNING #pragma message("WARNING: the 'dbg.h' header is included in your code base") #endif // DBG_MACRO_NO_WARNING #include <algorithm> #include <chrono> #include <ctime> #include <iomanip> #include <ios> #include <iostream> #include <memory> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <vector> #ifdef DBG_MACRO_UNIX #include <unistd.h> #endif #if __cplusplus >= 201703L || defined(_MSC_VER) #define DBG_MACRO_CXX_STANDARD 17 #elif __cplusplus >= 201402L #define DBG_MACRO_CXX_STANDARD 14 #else #define DBG_MACRO_CXX_STANDARD 11 #endif #if DBG_MACRO_CXX_STANDARD >= 17 #include <optional> #include <variant> #endif namespace dbg { #ifdef DBG_MACRO_UNIX inline bool isColorizedOutputEnabled() { return isatty(fileno(stderr)); } #else inline bool isColorizedOutputEnabled() { return true; } #endif struct time {}; namespace pretty_function { // Compiler-agnostic version of __PRETTY_FUNCTION__ and constants to // extract the template argument in `type_name_impl` #if defined(__clang__) #define DBG_MACRO_PRETTY_FUNCTION __PRETTY_FUNCTION__ static constexpr size_t PREFIX_LENGTH = sizeof("const char *dbg::type_name_impl() [T = ") - 1; static constexpr size_t SUFFIX_LENGTH = sizeof("]") - 1; #elif defined(__GNUC__) && !defined(__clang__) #define DBG_MACRO_PRETTY_FUNCTION __PRETTY_FUNCTION__ static constexpr size_t PREFIX_LENGTH = sizeof("const char* dbg::type_name_impl() [with T = ") - 1; static constexpr size_t SUFFIX_LENGTH = sizeof("]") - 1; #elif defined(_MSC_VER) #define DBG_MACRO_PRETTY_FUNCTION __FUNCSIG__ static constexpr size_t PREFIX_LENGTH = sizeof("const char *__cdecl dbg::type_name_impl<") - 1; static constexpr size_t SUFFIX_LENGTH = sizeof(">(void)") - 1; #else #error "This compiler is currently not supported by dbg_macro." #endif } // namespace pretty_function // Formatting helpers template<typename T> struct print_formatted { static_assert(std::is_integral<T>::value, "Only integral types are supported."); print_formatted(T value, int numeric_base) : inner(value), base(numeric_base) {} operator T() const { return inner; } const char *prefix() const { switch(base) { case 8: return "0o"; case 16: return "0x"; case 2: return "0b"; default: return ""; } } T inner; int base; }; template<typename T> print_formatted<T> hex(T value) { return print_formatted<T>{value, 16}; } template<typename T> print_formatted<T> oct(T value) { return print_formatted<T>{value, 8}; } template<typename T> print_formatted<T> bin(T value) { return print_formatted<T>{value, 2}; } // Implementation of 'type_name<T>()' template<typename T> const char *type_name_impl() { return DBG_MACRO_PRETTY_FUNCTION; } template<typename T> struct type_tag {}; template<int &... ExplicitArgumentBarrier, typename T> std::string get_type_name(type_tag<T>) { namespace pf = pretty_function; std::string type = type_name_impl<T>(); return type.substr(pf::PREFIX_LENGTH, type.size() - pf::PREFIX_LENGTH - pf::SUFFIX_LENGTH); } template<typename T> std::string type_name() { if(std::is_volatile<T>::value) { if(std::is_pointer<T>::value) { return type_name<typename std::remove_volatile<T>::type>() + " volatile"; } else { return "volatile " + type_name<typename std::remove_volatile<T>::type>(); } } if(std::is_const<T>::value) { if(std::is_pointer<T>::value) { return type_name<typename std::remove_const<T>::type>() + " const"; } else { return "const " + type_name<typename std::remove_const<T>::type>(); } } if(std::is_pointer<T>::value) { return type_name<typename std::remove_pointer<T>::type>() + "*"; } if(std::is_lvalue_reference<T>::value) { return type_name<typename std::remove_reference<T>::type>() + "&"; } if(std::is_rvalue_reference<T>::value) { return type_name<typename std::remove_reference<T>::type>() + "&&"; } return get_type_name(type_tag<T>{}); } inline std::string get_type_name(type_tag<short>) { return "short"; } inline std::string get_type_name(type_tag<unsigned short>) { return "unsigned short"; } inline std::string get_type_name(type_tag<long>) { return "long"; } inline std::string get_type_name(type_tag<unsigned long>) { return "unsigned long"; } inline std::string get_type_name(type_tag<std::string>) { return "std::string"; } template<typename T> std::string get_type_name(type_tag<std::vector<T, std::allocator<T>>>) { return "std::vector<" + type_name<T>() + ">"; } template<typename T1, typename T2> std::string get_type_name(type_tag<std::pair<T1, T2>>) { return "std::pair<" + type_name<T1>() + ", " + type_name<T2>() + ">"; } template<typename... T> std::string type_list_to_string() { std::string result; auto unused = {(result += type_name<T>() + ", ", 0)..., 0}; static_cast<void>(unused); if(sizeof...(T) > 0) { result.pop_back(); result.pop_back(); } return result; } template<typename... T> std::string get_type_name(type_tag<std::tuple<T...>>) { return "std::tuple<" + type_list_to_string<T...>() + ">"; } template<typename T> inline std::string get_type_name(type_tag<print_formatted<T>>) { return type_name<T>(); } // Implementation of 'is_detected' to specialize for container-like types namespace detail_detector { struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const &) = delete; void operator=(nonesuch const &) = delete; }; template<typename...> using void_t = void; template<class Default, class AlwaysVoid, template<class...> class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template<class Default, template<class...> class Op, class... Args> struct detector<Default, void_t<Op<Args...>>, Op, Args...> { using value_t = std::true_type; using type = Op<Args...>; }; } // namespace detail_detector template<template<class...> class Op, class... Args> using is_detected = typename detail_detector:: detector<detail_detector::nonesuch, void, Op, Args...>::value_t; namespace detail { namespace { using std::begin; using std::end; #if DBG_MACRO_CXX_STANDARD < 17 template<typename T> constexpr auto size(const T &c) -> decltype(c.size()) { return c.size(); } template<typename T, std::size_t N> constexpr std::size_t size(const T (&)[N]) { return N; } #else using std::size; #endif } // namespace template<typename T> using detect_begin_t = decltype(detail::begin(std::declval<T>())); template<typename T> using detect_end_t = decltype(detail::end(std::declval<T>())); template<typename T> using detect_size_t = decltype(detail::size(std::declval<T>())); template<typename T> struct is_container { static constexpr bool value = is_detected<detect_begin_t, T>::value && is_detected<detect_end_t, T>::value && is_detected<detect_size_t, T>::value && !std::is_same<std::string, typename std::remove_cv< typename std::remove_reference<T>::type>::type>::value; }; template<typename T> using ostream_operator_t = decltype(std::declval<std::ostream &>() << std::declval<T>()); template<typename T> struct has_ostream_operator : is_detected<ostream_operator_t, T> {}; } // namespace detail // Helper to dbg(…)-print types template<typename T> struct print_type {}; template<typename T> print_type<T> type() { return print_type<T>{}; } // Specializations of "pretty_print" template<typename T> inline void pretty_print(std::ostream &stream, const T &value, std::true_type) { stream << value; } template<typename T> inline void pretty_print(std::ostream &, const T &, std::false_type) { static_assert(detail::has_ostream_operator<const T &>::value, "Type does not support the << ostream operator"); } template<typename T> inline typename std::enable_if<!detail::is_container<const T &>::value && !std::is_enum<T>::value, bool>::type pretty_print(std::ostream &stream, const T &value) { pretty_print(stream, value, typename detail::has_ostream_operator<const T &>::type{}); return true; } inline bool pretty_print(std::ostream &stream, const bool &value) { stream << std::boolalpha << value; return true; } inline bool pretty_print(std::ostream &stream, const char &value) { const bool printable = value >= 0x20 && value <= 0x7E; if(printable) { stream << "'" << value << "'"; } else { stream << "'\\x" << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << (0xFF & value) << "'"; } return true; } template<typename P> inline bool pretty_print(std::ostream &stream, P *const &value) { if(value == nullptr) { stream << "nullptr"; } else { stream << value; } return true; } template<typename T, typename Deleter> inline bool pretty_print(std::ostream &stream, std::unique_ptr<T, Deleter> &value) { pretty_print(stream, value.get()); return true; } template<typename T> inline bool pretty_print(std::ostream &stream, std::shared_ptr<T> &value) { pretty_print(stream, value.get()); stream << " (use_count = " << value.use_count() << ")"; return true; } template<size_t N> inline bool pretty_print(std::ostream &stream, const char (&value)[N]) { stream << value; return false; } template<> inline bool pretty_print(std::ostream &stream, const char *const &value) { stream << '"' << value << '"'; return true; } template<size_t Idx> struct pretty_print_tuple { template<typename... Ts> static void print(std::ostream &stream, const std::tuple<Ts...> &tuple) { pretty_print_tuple<Idx - 1>::print(stream, tuple); stream << ", "; pretty_print(stream, std::get<Idx>(tuple)); } }; template<> struct pretty_print_tuple<0> { template<typename... Ts> static void print(std::ostream &stream, const std::tuple<Ts...> &tuple) { pretty_print(stream, std::get<0>(tuple)); } }; template<typename... Ts> inline bool pretty_print(std::ostream &stream, const std::tuple<Ts...> &value) { stream << "{"; pretty_print_tuple<sizeof...(Ts) - 1>::print(stream, value); stream << "}"; return true; } template<> inline bool pretty_print(std::ostream &stream, const std::tuple<> &) { stream << "{}"; return true; } template<> inline bool pretty_print(std::ostream &stream, const time &) { using namespace std::chrono; const auto now = system_clock::now(); const auto us = duration_cast<microseconds>(now.time_since_epoch()).count() % 1000000; const auto hms = system_clock::to_time_t(now); const std::tm *tm = std::localtime(&hms); stream << "current time = " << std::put_time(tm, "%H:%M:%S") << '.' << std::setw(6) << std::setfill('0') << us; return false; } // Converts decimal integer to binary string template<typename T> std::string decimalToBinary(T n) { const size_t length = 8 * sizeof(T); std::string toRet; toRet.resize(length); for(size_t i = 0; i < length; ++i) { const auto bit_at_index_i = (n >> i) & 1; toRet[length - 1 - i] = bit_at_index_i + '0'; } return toRet; } template<typename T> inline bool pretty_print(std::ostream &stream, const print_formatted<T> &value) { if(value.inner < 0) { stream << "-"; } stream << value.prefix(); // Print using setbase if(value.base != 2) { stream << std::setw(sizeof(T)) << std::setfill('0') << std::setbase(value.base) << std::uppercase; if(value.inner >= 0) { // The '+' sign makes sure that a uint_8 is printed as a number stream << +value.inner; } else { using unsigned_type = typename std::make_unsigned<T>::type; stream << +(static_cast<unsigned_type>(-(value.inner + 1)) + 1); } } else { // Print for binary if(value.inner >= 0) { stream << decimalToBinary(value.inner); } else { using unsigned_type = typename std::make_unsigned<T>::type; stream << decimalToBinary<unsigned_type>( static_cast<unsigned_type>(-(value.inner + 1)) + 1); } } return true; } template<typename T> inline bool pretty_print(std::ostream &stream, const print_type<T> &) { stream << type_name<T>(); stream << " [sizeof: " << sizeof(T) << " byte, "; stream << "trivial: "; if(std::is_trivial<T>::value) { stream << "yes"; } else { stream << "no"; } stream << ", standard layout: "; if(std::is_standard_layout<T>::value) { stream << "yes"; } else { stream << "no"; } stream << "]"; return false; } template<typename Container> inline typename std::enable_if<detail::is_container<const Container &>::value, bool>::type pretty_print(std::ostream &stream, const Container &value) { stream << "{"; const size_t size = detail::size(value); const size_t n = std::min(size_t{10}, size); size_t i = 0; using std::begin; using std::end; for(auto it = begin(value); it != end(value) && i < n; ++it, ++i) { pretty_print(stream, *it); if(i != n - 1) { stream << ", "; } } if(size > n) { stream << ", ..."; stream << " size:" << size; } stream << "}"; return true; } template<typename Enum> inline typename std::enable_if<std::is_enum<Enum>::value, bool>::type pretty_print(std::ostream &stream, Enum const &value) { using UnderlyingType = typename std::underlying_type<Enum>::type; stream << static_cast<UnderlyingType>(value); return true; } inline bool pretty_print(std::ostream &stream, const std::string &value) { stream << '"' << value << '"'; return true; } template<typename T1, typename T2> inline bool pretty_print(std::ostream &stream, const std::pair<T1, T2> &value) { stream << "{"; pretty_print(stream, value.first); stream << ", "; pretty_print(stream, value.second); stream << "}"; return true; } #if DBG_MACRO_CXX_STANDARD >= 17 template<typename T> inline bool pretty_print(std::ostream &stream, const std::optional<T> &value) { if(value) { stream << '{'; pretty_print(stream, *value); stream << '}'; } else { stream << "nullopt"; } return true; } template<typename... Ts> inline bool pretty_print(std::ostream &stream, const std::variant<Ts...> &value) { stream << "{"; std::visit([&stream](auto &&arg) { pretty_print(stream, arg); }, value); stream << "}"; return true; } #endif template<typename T, typename... U> struct last { using type = typename last<U...>::type; }; template<typename T> struct last<T> { using type = T; }; template<typename... T> using last_t = typename last<T...>::type; class DebugOutput { public: // Helper alias to avoid obscure type `const char* const*` in signature. using expr_t = const char *; DebugOutput(const char *filepath, int line, const char *function_name) : m_use_colorized_output(isColorizedOutputEnabled()) { std::string path = filepath; const std::size_t path_length = path.length(); if(path_length > MAX_PATH_LENGTH) { path = ".." + path.substr(path_length - MAX_PATH_LENGTH, MAX_PATH_LENGTH); } std::stringstream ss; ss << ansi(ANSI_DEBUG) << "[" << path << ":" << line << " (" << function_name << ")] " << ansi(ANSI_RESET); m_location = ss.str(); } template<typename... T> auto print(std::initializer_list<expr_t> exprs, std::initializer_list<std::string> types, T &&... values) -> last_t<T...> { if(exprs.size() != sizeof...(values)) { std::cerr << m_location << ansi(ANSI_WARN) << "The number of arguments mismatch, please check unprotected comma" << ansi(ANSI_RESET) << std::endl; } return print_impl(exprs.begin(), types.begin(), std::forward<T>(values)...); } private: template<typename T> T &&print_impl(const expr_t *expr, const std::string *type, T &&value) { const T &ref = value; std::stringstream stream_value; const bool print_expr_and_type = pretty_print(stream_value, ref); std::stringstream output; output << m_location; if(print_expr_and_type) { output << ansi(ANSI_EXPRESSION) << *expr << ansi(ANSI_RESET) << " = "; } output << ansi(ANSI_VALUE) << stream_value.str() << ansi(ANSI_RESET); if(print_expr_and_type) { output << " (" << ansi(ANSI_TYPE) << *type << ansi(ANSI_RESET) << ")"; } output << std::endl; std::cerr << output.str(); return std::forward<T>(value); } template<typename T, typename... U> auto print_impl(const expr_t *exprs, const std::string *types, T &&value, U &&... rest) -> last_t<T, U...> { print_impl(exprs, types, std::forward<T>(value)); return print_impl(exprs + 1, types + 1, std::forward<U>(rest)...); } const char *ansi(const char *code) const { if(m_use_colorized_output) { return code; } else { return ANSI_EMPTY; } } const bool m_use_colorized_output; std::string m_location; static constexpr std::size_t MAX_PATH_LENGTH = 20; static constexpr const char *const ANSI_EMPTY = ""; static constexpr const char *const ANSI_DEBUG = "\x1b[02m"; static constexpr const char *const ANSI_WARN = "\x1b[33m"; static constexpr const char *const ANSI_EXPRESSION = "\x1b[36m"; static constexpr const char *const ANSI_VALUE = "\x1b[01m"; static constexpr const char *const ANSI_TYPE = "\x1b[32m"; static constexpr const char *const ANSI_RESET = "\x1b[0m"; }; // Identity function to suppress "-Wunused-value" warnings in DBG_MACRO_DISABLE // mode template<typename T> T &&identity(T &&t) { return std::forward<T>(t); } template<typename T, typename... U> auto identity(T &&, U &&... u) -> last_t<U...> { return identity(std::forward<U>(u)...); } } // namespace dbg #ifndef DBG_MACRO_DISABLE // Force expanding argument with commas for MSVC, ref: // https://stackoverflow.com/questions/35210637/macro-expansion-argument-with-commas // Note that "args" should be a tuple with parentheses, such as "(e1, e2, ...)". #define DBG_IDENTITY(x) x #define DBG_CALL(fn, args) DBG_IDENTITY(fn args) #define DBG_CAT_IMPL(_1, _2) _1##_2 #define DBG_CAT(_1, _2) DBG_CAT_IMPL(_1, _2) #define DBG_16TH_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, \ _14, _15, _16, ...) \ _16 #define DBG_16TH(args) DBG_CALL(DBG_16TH_IMPL, args) #define DBG_NARG(...) \ DBG_16TH((__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) // DBG_VARIADIC_CALL(fn, data, e1, e2, ...) => fn_N(data, (e1, e2, ...)) #define DBG_VARIADIC_CALL(fn, data, ...) \ DBG_CAT(fn##_, DBG_NARG(__VA_ARGS__)) \ (data, (__VA_ARGS__)) // (e1, e2, e3, ...) => e1 #define DBG_HEAD_IMPL(_1, ...) _1 #define DBG_HEAD(args) DBG_CALL(DBG_HEAD_IMPL, args) // (e1, e2, e3, ...) => (e2, e3, ...) #define DBG_TAIL_IMPL(_1, ...) (__VA_ARGS__) #define DBG_TAIL(args) DBG_CALL(DBG_TAIL_IMPL, args) #define DBG_MAP_1(fn, args) DBG_CALL(fn, args) #define DBG_MAP_2(fn, args) fn(DBG_HEAD(args)), DBG_MAP_1(fn, DBG_TAIL(args)) #define DBG_MAP_3(fn, args) fn(DBG_HEAD(args)), DBG_MAP_2(fn, DBG_TAIL(args)) #define DBG_MAP_4(fn, args) fn(DBG_HEAD(args)), DBG_MAP_3(fn, DBG_TAIL(args)) #define DBG_MAP_5(fn, args) fn(DBG_HEAD(args)), DBG_MAP_4(fn, DBG_TAIL(args)) #define DBG_MAP_6(fn, args) fn(DBG_HEAD(args)), DBG_MAP_5(fn, DBG_TAIL(args)) #define DBG_MAP_7(fn, args) fn(DBG_HEAD(args)), DBG_MAP_6(fn, DBG_TAIL(args)) #define DBG_MAP_8(fn, args) fn(DBG_HEAD(args)), DBG_MAP_7(fn, DBG_TAIL(args)) #define DBG_MAP_9(fn, args) fn(DBG_HEAD(args)), DBG_MAP_8(fn, DBG_TAIL(args)) #define DBG_MAP_10(fn, args) fn(DBG_HEAD(args)), DBG_MAP_9(fn, DBG_TAIL(args)) #define DBG_MAP_11(fn, args) fn(DBG_HEAD(args)), DBG_MAP_10(fn, DBG_TAIL(args)) #define DBG_MAP_12(fn, args) fn(DBG_HEAD(args)), DBG_MAP_11(fn, DBG_TAIL(args)) #define DBG_MAP_13(fn, args) fn(DBG_HEAD(args)), DBG_MAP_12(fn, DBG_TAIL(args)) #define DBG_MAP_14(fn, args) fn(DBG_HEAD(args)), DBG_MAP_13(fn, DBG_TAIL(args)) #define DBG_MAP_15(fn, args) fn(DBG_HEAD(args)), DBG_MAP_14(fn, DBG_TAIL(args)) #define DBG_MAP_16(fn, args) fn(DBG_HEAD(args)), DBG_MAP_15(fn, DBG_TAIL(args)) // DBG_MAP(fn, e1, e2, e3, ...) => fn(e1), fn(e2), fn(e3), ... #define DBG_MAP(fn, ...) DBG_VARIADIC_CALL(DBG_MAP, fn, __VA_ARGS__) #define DBG_STRINGIFY_IMPL(x) #x #define DBG_STRINGIFY(x) DBG_STRINGIFY_IMPL(x) #define DBG_TYPE_NAME(x) dbg::type_name<decltype(x)>() #define dbg(...) \ dbg::DebugOutput(__FILE__, __LINE__, __func__) \ .print({DBG_MAP(DBG_STRINGIFY, __VA_ARGS__)}, \ {DBG_MAP(DBG_TYPE_NAME, __VA_ARGS__)}, __VA_ARGS__) #else #define dbg(...) dbg::identity(__VA_ARGS__) #endif // DBG_MACRO_DISABLE #endif // DBG_MACRO_DBG_H
28.931336
85
0.636748
kitegi
e8d277b45218ef01e5feb0cd7077d8fd5a4f791c
5,010
cpp
C++
libace/model/HookAttribute.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
5
2016-06-14T17:56:47.000Z
2022-02-10T19:54:25.000Z
libace/model/HookAttribute.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
42
2016-06-21T20:48:22.000Z
2021-03-23T15:20:51.000Z
libace/model/HookAttribute.cpp
xguerin/ace
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
[ "MIT" ]
1
2016-10-02T02:58:49.000Z
2016-10-02T02:58:49.000Z
/** * Copyright (c) 2016 Xavier R. Guerin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without reexaction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <ace/model/Errors.h> #include <ace/model/HookAttribute.h> #include <ace/model/Model.h> namespace ace { namespace model { HookAttribute::HookAttribute(std::string const& n, bool o) : Attribute(n, o, false), m_hook() {} bool HookAttribute::checkModel(tree::Value const& t) const { if (t.type() != tree::Value::Type::Object) { ACE_LOG(Debug, t.isArray(), " ", t.isPrimitive()); ERROR(ERR_HOOK_INVALID_TYPE); return false; } auto const& o = static_cast<tree::Object const&>(t); if (not Hook::validate(o)) { return false; } return true; } void HookAttribute::loadModel(tree::Value const& t) { auto const& o = static_cast<tree::Object const&>(t); m_hook.load(o); } bool HookAttribute::checkInstance(tree::Object const& r, tree::Value const& v) const { return true; } bool HookAttribute::flattenInstance(tree::Object& r, tree::Value& v) { Model const& model = *static_cast<const Model*>(owner()); tree::Path const& p = hook().path(); if (not model.body().has(p)) { ERROR(ERR_INVALID_HOOK_SOURCE(p)); return false; } std::list<BasicType::Ref> lasso; model.body().get(p, lasso); for (auto& e : lasso) { if (not e->isEnumerated() and not e->isMapped()) { ERROR(ERR_HOOKED_VALUE_NOT_ENUMERATED); return false; } if (e->optional() and not optional()) { ERROR(ERR_HOOKED_VALUE_ARITY_MISMATCH(e->path())); return false; } } return true; } bool HookAttribute::resolveInstance(tree::Object const& r, tree::Value const& v) const { tree::Path const& p = hook().path(); if (not r.has(p)) { ERROR(ERR_NO_HOOKED_VALUE_IN_INSTANCE(hook().path())); return false; } std::set<std::string> mv, hv; v.each([&](tree::Value const& w) { if (w.type() == tree::Value::Type::Object) { tree::Object const& o = static_cast<tree::Object const&>(w); for (auto& e : o) { mv.insert(e.first); } } else { tree::Primitive const& p = static_cast<tree::Primitive const&>(w); mv.insert(p.value()); } }); r.get(p, [&](tree::Value const& val) { val.each([&](tree::Value const& w) { if (w.type() == tree::Value::Type::Object) { tree::Object const& o = static_cast<tree::Object const&>(w); for (auto& e : o) { hv.insert(e.first); } } else { tree::Primitive const& p = static_cast<tree::Primitive const&>(w); hv.insert(p.value()); } }); }); std::set<std::string> txv; for (auto& e : hv) { if (not hook().match(e)) { ERROR(ERR_EMPTY_HOOK_MATCH(name(), e)); return false; } std::string to; if (not hook().transform(e, to)) { ERROR(ERR_EMPTY_HOOK_MATCH(name(), e)); return false; } txv.insert(to); } for (auto& e : mv) { if (txv.find(e) == txv.end()) { ERROR(ERR_NO_HOOKED_VALUE_MATCH(e)); return false; } } if (m_hook.exact()) { for (auto& e : txv) { if (mv.count(e) == 0) { ERROR(ERR_MISSING_HOOKED_VALUE_MATCH(e)); return false; } } } return true; } void HookAttribute::load(Attribute const& a) { HookAttribute const& ra = static_cast<HookAttribute const&>(a); m_hook = ra.m_hook; } bool HookAttribute::merge(Attribute const& b) { if (not Attribute::merge(b)) { return false; } HookAttribute const& rb = static_cast<HookAttribute const&>(b); m_hook = rb.m_hook; return true; } HookAttribute::operator tree::Checker::Pattern() const { return tree::Checker::Pattern(tree::Value::Type::Object, true); } HookAttribute::operator std::string() const { std::ostringstream oss; oss << m_hook.path().toString(); return oss.str(); } Attribute::Ref HookAttribute::clone() const { return Attribute::Ref(new HookAttribute(*this)); } Hook const& HookAttribute::hook() const { return m_hook; } }}
26.09375
80
0.642116
xguerin
e8d6d80445ce9c6e527dc2690f3ce41e9380d1e8
985
cpp
C++
1.6/1.6/Source.cpp
albusshin/CTCI
0794c9f78cc881a60daf883ba2caa5d82bb8833d
[ "CC0-1.0" ]
2
2015-03-25T09:33:38.000Z
2016-05-23T06:57:31.000Z
1.6/1.6/Source.cpp
albusshin/CTCI
0794c9f78cc881a60daf883ba2caa5d82bb8833d
[ "CC0-1.0" ]
null
null
null
1.6/1.6/Source.cpp
albusshin/CTCI
0794c9f78cc881a60daf883ba2caa5d82bb8833d
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; void rotateClockwise90(char **arr, int n) { for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - i - 1; j++) { char tmp = arr[n-j-1][i]; arr[n-j-1][i] = arr[n-i-1][n-j-1]; arr[n-i-1][n-j-1] = arr[j][n-i-1]; arr[j][n-i-1] = arr[i][j]; arr[i][j] = tmp; } } } void printBoard(char **arr, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j]; } cout << endl; } cout << endl; } void test(char **arr, int n) { printBoard(arr, n); rotateClockwise90(arr, n); printBoard(arr, n); } int main() { char **arr = new char *[10]; for (int i = 0; i < 10; i++) arr[i] = new char[10]; strcpy(arr[0], "123456789"); strcpy(arr[1], "234567890"); strcpy(arr[2], "345678901"); strcpy(arr[3], "456789012"); strcpy(arr[4], "567890123"); strcpy(arr[5], "678901234"); strcpy(arr[6], "789012345"); strcpy(arr[7], "890123456"); strcpy(arr[8], "901234567"); test((char **)arr, 9); }
21.413043
52
0.53401
albusshin
e8db47d1e31ceef89f85ba475967a4ade84a0353
1,316
cpp
C++
Esami/Laboratorio20110912/ppm.cpp
eMDi94/EDM-ingmo
2b53194d862dea87a1f95305511c70c155dcc42c
[ "MIT" ]
2
2018-08-16T00:34:55.000Z
2019-02-10T00:59:05.000Z
Esami/Laboratorio20110912/ppm.cpp
eMDi94/EDM-ingmo
2b53194d862dea87a1f95305511c70c155dcc42c
[ "MIT" ]
null
null
null
Esami/Laboratorio20110912/ppm.cpp
eMDi94/EDM-ingmo
2b53194d862dea87a1f95305511c70c155dcc42c
[ "MIT" ]
null
null
null
#include "ppm.h" #include <string> using namespace std; using namespace core; using namespace ppm; bool ppm::load_ppm(istream& is, mat<vec3b>& img) { string magic; is >> magic; is.get(); if ((magic != "P3" && magic != "P6") || !is) return false; if (is.peek() == '#') { string comment; getline(is, comment); if (!is) return false; } size_t width, height; uint16_t val; is >> width >> height >> val; is.get(); if (!is) return false; img.resize(height, width); if (magic == "P6") is.read(reinterpret_cast<char*>(img.data()), height * width * 3); else for (auto& pixel : img) { uint32_t v; for (size_t i = 0; i < 3; ++i) { is >> v; pixel[i] = v; } } return true; } bool ppm::save_ppm(ostream& os, const mat<vec3b>& img, ppm_type type, string comment) { if (type == ppm_type::p6) os << "P6\n"; else os << "P3\n"; if (!comment.empty()) os << "# " << comment << "\n"; os << img.width() << " " << img.height() << "\n255\n"; if (type == ppm_type::p6) os.write(reinterpret_cast<const char*>(img.data()), img.height() * img.width() * 3); else for (const auto& pixel : img) os << uint32_t(pixel[0]) << " " << uint32_t(pixel[1]) << " " << uint32_t(pixel[2]) << " "; return os.good(); }
21.225806
94
0.540274
eMDi94
e8ddfafe0e9aa8bd809bc5f289ac5758d3953ae3
1,819
cpp
C++
core/MaterialData.cpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
core/MaterialData.cpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
core/MaterialData.cpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
#include "MaterialData.hpp" MaterialData::MaterialData() {} MaterialData::~MaterialData() { allDiffuseTex.clear(); allSpecularTex.clear(); allNormalsTex.clear(); } void MaterialData::clearDiffuseTex() { allDiffuseTex.clear(); } void MaterialData::clearSpecularTex() { allSpecularTex.clear(); } void MaterialData::clearNormalsTex() { allNormalsTex.clear(); } void MaterialData::addDiffuseTex(int texIndex) { allDiffuseTex.push_back(texIndex); } void MaterialData::addSpecularTex(int texIndex) { allSpecularTex.push_back(texIndex); } void MaterialData::addNormalsTex(int texIndex) { allNormalsTex.push_back(texIndex); } int MaterialData::getDiffuseTex(int index) { if (index >= 0 && index < allDiffuseTex.size()) { return allDiffuseTex.at(index); } else { return -1; } } int MaterialData::getSpecularTex(int index) { if (index >= 0 && index < allSpecularTex.size()) { return allSpecularTex.at(index); } else { return -1; } } int MaterialData::getNormalsTex(int index) { if (index >= 0 && index < allNormalsTex.size()) { return allNormalsTex.at(index); } else { return -1; } } int MaterialData::getDiffuseTexCnt() { return (int)allDiffuseTex.size(); } int MaterialData::getSpecularTexCnt() { return (int)allSpecularTex.size(); } int MaterialData::getNormalsTexCnt() { return (int)allNormalsTex.size(); } void MaterialData::setKd(glm::vec3 kd) { this->kd = kd; } void MaterialData::setKs(glm::vec3 ks) { this->ks = ks; } void MaterialData::setShininess(float shininess) { this->shininess = shininess; } void MaterialData::setName(string name) { this->name = name; } glm::vec3 MaterialData::getKd() { return kd; } glm::vec3 MaterialData::getKs() { return ks; } float MaterialData::getShininess() { return shininess; } string MaterialData::getName() { return name; }
19.55914
56
0.714129
jmppmj
e8e905b70542ebd850c1d1e06332d155d5059ff7
909
cc
C++
lambda_to_cfun/test.cc
dearoneesama/ctut
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
[ "BSL-1.0" ]
null
null
null
lambda_to_cfun/test.cc
dearoneesama/ctut
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
[ "BSL-1.0" ]
null
null
null
lambda_to_cfun/test.cc
dearoneesama/ctut
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
[ "BSL-1.0" ]
null
null
null
#include <iostream> #include "../queue/eventqueue.h" #include "l2cf.hh" using namespace oneesama; int main() { { auto yolo = l2cf{[i = 0] (bool &, int start) mutable { return start + i++; }}; // get pointers auto (*cb)(int, void *) -> int = yolo.get_cfnptr(); void *ctx = yolo.get_ctx(); for (int i = 0; i < 5; ++i) std::cout << cb(10, ctx) << std::endl; } const char *strings[] = {"hehe", "yolo", "hm"}; // C api EventQueue *eq = eventqueue_create(); { auto [cb, ctx, wr] = make_quick_cf_pair([&strings] (bool &free_me, EventQueue *) { free_me = true; std::cout << strings[1] << std::endl; }); wr.clean_up_on_destruct(false); eventqueue_emplace(eq, cb, ctx); } eventqueue_this_thread_run(eq); eventqueue_close(eq); // no memory leak }
25.25
90
0.522552
dearoneesama
e8ebc751759775703936891785c159098c4df36d
87
cpp
C++
examples/12_module/08_arrays_dyn_1/bank_account.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-TranBran
91728f8f8f324550c43bf056d11b63f75b4b2329
[ "MIT" ]
null
null
null
examples/12_module/08_arrays_dyn_1/bank_account.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-TranBran
91728f8f8f324550c43bf056d11b63f75b4b2329
[ "MIT" ]
null
null
null
examples/12_module/08_arrays_dyn_1/bank_account.cpp
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-TranBran
91728f8f8f324550c43bf056d11b63f75b4b2329
[ "MIT" ]
null
null
null
#include "bank_account.h // BankAccount::int get_balance()const { return balance; }
9.666667
35
0.724138
acc-cosc-1337-spring-2019
e8f1fd8c499b851dde52e7bcc3749119d92b82e8
590
cpp
C++
House Robber.cpp
liuslevis/leetcode
3447b338cd4efc7d817e35e182dda3a53899b8c2
[ "MIT" ]
null
null
null
House Robber.cpp
liuslevis/leetcode
3447b338cd4efc7d817e35e182dda3a53899b8c2
[ "MIT" ]
null
null
null
House Robber.cpp
liuslevis/leetcode
3447b338cd4efc7d817e35e182dda3a53899b8c2
[ "MIT" ]
null
null
null
// 5min 5 WA due to ... // Notice: usage of *max_element(v.begin(), v.begin()+1 + 1) class Solution { public: int rob(vector<int>& nums) { if (nums.size() == 0) return 0; if (nums.size() == 1) return nums[0]; if (nums.size() == 2) return max(nums[0], nums[1]); vector<int> f(nums.size(), 0); f[0] = nums[0]; f[1] = nums[1]; for (int i = 2; i < nums.size(); i++) { f[i] = nums[i] + *max_element(f.begin(), f.begin()+1+i-2); } return *max_element(f.begin(), f.end()); } };
28.095238
70
0.455932
liuslevis
e8f6838a18763b6bd876533014cf3f5ee27cddc6
4,832
cpp
C++
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.FontDialogMustExist/CPP/form1.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.FontDialogMustExist/CPP/form1.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.FontDialogMustExist/CPP/form1.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
#using <System.Drawing.dll> #using <System.dll> #using <System.Windows.Forms.dll> // The following code example demonstrates using the FontDialog.MinSize, // FontDialog.MaxSize, and FontDialog.ShowEffects members, and // handling of Apply event. using namespace System::Windows::Forms; public ref class Form1: public System::Windows::Forms::Form { public: Form1() : Form() { //This call is required by the Windows Form Designer. InitializeComponent(); //Add any initialization after the InitializeComponent() call } protected: ~Form1() { if ( components != nullptr ) { delete components; } } private: //Required by the Windows Form Designer System::ComponentModel::IContainer^ components; internal: //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. System::Windows::Forms::FontDialog^ FontDialog1; System::Windows::Forms::Button^ Button1; System::Windows::Forms::TextBox^ TextBox1; private: [System::Diagnostics::DebuggerStepThrough] void InitializeComponent() { this->FontDialog1 = gcnew System::Windows::Forms::FontDialog; this->Button1 = gcnew System::Windows::Forms::Button; this->TextBox1 = gcnew System::Windows::Forms::TextBox; this->SuspendLayout(); // //FontDialog1 // // //Button1 // this->Button1->Location = System::Drawing::Point( 72, 136 ); this->Button1->Name = "Button1"; this->Button1->Size = System::Drawing::Size( 144, 88 ); this->Button1->TabIndex = 0; this->Button1->Text = "Click for Font Dialog"; this->Button1->Click += gcnew System::EventHandler( this, &Form1::Button1_Click ); // //TextBox1 // this->TextBox1->Location = System::Drawing::Point( 72, 48 ); this->TextBox1->Name = "TextBox1"; this->TextBox1->Size = System::Drawing::Size( 152, 20 ); this->TextBox1->TabIndex = 1; this->TextBox1->Text = "Here is some text."; // //Form1 // this->ClientSize = System::Drawing::Size( 292, 266 ); this->Controls->Add( this->TextBox1 ); this->Controls->Add( this->Button1 ); this->Name = "Form1"; this->Text = "Form1"; this->ResumeLayout( false ); } //<snippet1> void Button1_Click( System::Object^ sender, System::EventArgs^ e ) { // Set FontMustExist to true, which causes message box error // if the user enters a font that does not exist. FontDialog1->FontMustExist = true; // Associate the method handling the Apply event with the event. FontDialog1->Apply += gcnew System::EventHandler( this, &Form1::FontDialog1_Apply ); // Set a minimum and maximum size to be // shown in the FontDialog. FontDialog1->MaxSize = 32; FontDialog1->MinSize = 18; // Show the Apply button in the dialog. FontDialog1->ShowApply = true; // Do not show effects such as Underline // and Bold. FontDialog1->ShowEffects = false; // Save the existing font. System::Drawing::Font^ oldFont = this->Font; //Show the dialog, and get the result System::Windows::Forms::DialogResult result = FontDialog1->ShowDialog(); // If the OK button in the Font dialog box is clicked, // set all the controls' fonts to the chosen font by calling // the FontDialog1_Apply method. if ( result == ::DialogResult::OK ) { FontDialog1_Apply( this->Button1, gcnew System::EventArgs ); } // If Cancel is clicked, set the font back to // the original font. else // If Cancel is clicked, set the font back to // the original font. if ( result == ::DialogResult::Cancel ) { this->Font = oldFont; System::Collections::IEnumerator^ myEnum = this->Controls->GetEnumerator(); while ( myEnum->MoveNext() ) { Control^ containedControl = safe_cast<Control^>(myEnum->Current); containedControl->Font = oldFont; } } } // Handle the Apply event by setting all controls' fonts to // the chosen font. void FontDialog1_Apply( Object^ sender, System::EventArgs^ e ) { this->Font = FontDialog1->Font; System::Collections::IEnumerator^ myEnum1 = this->Controls->GetEnumerator(); while ( myEnum1->MoveNext() ) { Control^ containedControl = safe_cast<Control^>(myEnum1->Current); containedControl->Font = FontDialog1->Font; } } //</snippet1> }; int main() { Application::Run( gcnew Form1 ); }
29.284848
90
0.614238
BohdanMosiyuk
e8f7c2472eb1df75faf5401d2bcfbd326698eb97
3,058
cc
C++
python/kratos_tb.cc
IanBoyanZhang/kratos
4865e71e657c770fdc86528fcd56918e6f2103a1
[ "BSD-2-Clause" ]
39
2019-10-07T16:42:00.000Z
2022-03-31T20:33:28.000Z
python/kratos_tb.cc
IanBoyanZhang/kratos
4865e71e657c770fdc86528fcd56918e6f2103a1
[ "BSD-2-Clause" ]
164
2019-06-29T03:43:19.000Z
2021-11-16T06:37:13.000Z
python/kratos_tb.cc
IanBoyanZhang/kratos
4865e71e657c770fdc86528fcd56918e6f2103a1
[ "BSD-2-Clause" ]
11
2019-07-13T19:24:30.000Z
2022-01-21T22:52:18.000Z
#include <pybind11/functional.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "../src/tb.hh" namespace py = pybind11; // test bench module void init_tb(py::module &m) { using namespace kratos; py::class_<TestBench>(m, "TestBench") .def(py::init<Context *, const std::string &>()) .def("var", py::overload_cast<const std::string &, uint32_t>(&TestBench::var), py::return_value_policy::reference) .def("var", py::overload_cast<const std::string &, uint32_t, uint32_t>(&TestBench::var), py::return_value_policy::reference) .def("var", py::overload_cast<const std::string &, uint32_t, uint32_t, bool>(&TestBench::var), py::return_value_policy::reference) .def("get_var", &TestBench::get_var) .def("initial", &TestBench::initial) .def("wire", py::overload_cast<const std::shared_ptr<Var> &, const std::shared_ptr<Port> &>( &TestBench::wire)) .def("wire", py::overload_cast<std::shared_ptr<Port> &, std::shared_ptr<Port> &>(&TestBench::wire)) .def("wire", py::overload_cast<const std::shared_ptr<Var> &, const std::shared_ptr<Var> &>( &TestBench::wire)) .def("add_child_generator", &TestBench::add_child_generator) .def("property", &TestBench::property) .def("codegen", &TestBench::codegen) .def("top", &TestBench::top); py::class_<AssertValueStmt, Stmt, std::shared_ptr<AssertValueStmt>>(m, "AssertValueStmt") .def(py::init<const std::shared_ptr<Var> &>()) .def(py::init<>()) .def("value", &AssertValueStmt::value); py::class_<AssertPropertyStmt, Stmt, std::shared_ptr<AssertPropertyStmt>>(m, "AssertPropertyStmt") .def(py::init<const std::shared_ptr<Property> &>()) .def("property", &AssertPropertyStmt::property); py::class_<Sequence, std::shared_ptr<Sequence>>(m, "Sequence") .def(py::init<const std::shared_ptr<Var> &>()) .def("imply", &Sequence::imply, py::return_value_policy::reference) .def("wait", py::overload_cast<uint32_t>(&Sequence::wait), py::return_value_policy::reference) .def("wait", py::overload_cast<uint32_t, uint32_t>(&Sequence::wait), py::return_value_policy::reference) .def("__repr__", &Sequence::to_string) .def("next", &Sequence::next, py::return_value_policy::reference); py::class_<Property, std::shared_ptr<Property>>(m, "Property") .def(py::init<std::string, std::shared_ptr<Sequence>>()) .def("property_name", &Property::property_name) .def("sequence", &Property::sequence) .def("edge", py::overload_cast<BlockEdgeType, const std::shared_ptr<Var> &>(&Property::edge)) .def("edge", [](const Property &property) { return property.edge(); }) .def_property("action", &Property::action, &Property::set_action); }
49.322581
100
0.603663
IanBoyanZhang
e8faeb1d4cbdbf1b0142e61b9d7abdff11ad1c76
11,088
cpp
C++
Examples/HexMap/HexLayer.cpp
Aaron-Berland/Nova
1b8587548c58adda27bd2b699bf4229e18f30e13
[ "Apache-2.0" ]
null
null
null
Examples/HexMap/HexLayer.cpp
Aaron-Berland/Nova
1b8587548c58adda27bd2b699bf4229e18f30e13
[ "Apache-2.0" ]
null
null
null
Examples/HexMap/HexLayer.cpp
Aaron-Berland/Nova
1b8587548c58adda27bd2b699bf4229e18f30e13
[ "Apache-2.0" ]
null
null
null
#include "HexLayer.h" #include <Nova/Renderer/RenderCommand.h> #include <Nova/Renderer/Renderer.h> #include <Nova/Input.h> #include <Nova/Window.h> #include <Nova/Application.h> #include <Nova/KeyCodes.h> #include <Nova/MouseButtonCodes.h> #include <initializer_list> #include <imgui.h> #include <functional> #include <Nova/Events/Event.h> #include <glm/gtc/type_ptr.hpp> #include <glad/glad.h> #include <Nova/Core/Benchmarking.h> #include <Nova/Platform/OpenGLShader.h> #include <Nova/Utility/Geometry.h> HexLayer::HexLayer() : m_currentTime(0.0f), m_camera(nullptr),m_hexMap(nullptr),m_hexShader(nullptr), m_clearColor(0.2f,0.2f,0.2f,1.0f), m_canElevationEdit(false), m_canColorEdit(true), m_canRiverEdit(false), m_canWaterEdit(false), m_currentColorIndex(0),m_currentElevation(0),m_currentWaterLevel(0), m_currentBrushSize(0), m_currentRiverEditingMode(0) { float tileRadius = 5.5f; unsigned int tileCount = 30; float mapMidPoint = tileRadius*glm::sqrt(3.0f)*0.5f * tileCount * CHUNK_SIZE; float cameraFOV = 60.0f; unsigned int maxElevation = 12; unsigned int maxBrushSize = CHUNK_SIZE; float elevationStep = 2.15f; float riverElevationOffset = -1.5f; float cameraDistance = mapMidPoint / glm::tan(glm::radians(cameraFOV) / 2.0f); float cameraMoveSpeed = 2*35.0f; float cameraRotationSpeed = 1.0f; float cameraZoomSpeed = 0.01f; float minDistance = maxElevation * elevationStep * 2.0f; float maxDistance = std::max(cameraDistance*1.0f, 2.0f*minDistance); float minAngle = 0.0f; float maxAngle = glm::radians(80.0f); float zoom = 0.0f; float rotation = 0.0f; const Nova::Window& window = Nova::Application::Get().GetWindow(); m_camera = Nova::CreateRef<Nova::PerspectiveCamera>( glm::vec3(mapMidPoint, (2.0f / 3.0f) * mapMidPoint, cameraDistance), glm::vec3(mapMidPoint, (2.0f / 3.0f) * mapMidPoint, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), cameraFOV, (float)window.GetWidth() / window.GetHeight()); m_camController = Nova::CreateScope<HexMapCameraController>( m_camera, cameraMoveSpeed, cameraRotationSpeed, cameraZoomSpeed, minDistance, maxDistance, minAngle, maxAngle, zoom, rotation); HexTileMetrics tileMetrics(tileRadius, 0.8f,elevationStep,riverElevationOffset); std::vector<glm::vec4>defaultColors = { (1 / 255.0f)*glm::vec4(0.9f*243.0f,0.9f*235.0f,0.9f*0.0f,255.0f), (1 / 255.0f)*glm::vec4(0.0f, 0.9f*219.0f, 0.9f*37.0f, 255.0f), (1 / 255.0f)*glm::vec4(0.9f*239.0f, 0.9f*239.0f, 0.9f*239.0f, 255.0f), (1 / 255.0f)*glm::vec4(0.9f*41.0f, 0.9f*98.0f, 0.9f*255.0f, 255.0f) }; m_brush = { { {defaultColors[0], "Yellow"}, {defaultColors[1], "Green" }, {defaultColors[2], "White"}, {defaultColors[3], "Blue"} }, maxElevation, maxBrushSize}; NoiseInfo noise(0.2f,1.0f, 1.0f); //std::vector<glm::vec4>defaultColors = { glm::vec4(0.8f,0.8f,0.8f,1.0f) }; HexMapMetrics mapMetrics(tileMetrics, noise, glm::vec3(0.0, 0.0, 0.0f),tileCount, tileCount,maxElevation, 2, defaultColors); m_hexMap = Nova::CreateScope<HexMap>(mapMetrics); m_hexShader = Nova::Shader::Create("HexMap-Assets/Shaders/hexVS.vs", "HexMap-Assets/Shaders/hexFS.fs"); m_hexRiverShader = Nova::Shader::Create("HexMap-Assets/Shaders/hexRiverVS.vs","HexMap-Assets/Shaders/hexRiverFS.fs"); m_hexWaterShader = Nova::Shader::Create("HexMap-Assets/Shaders/hexWaterVS.vs","HexMap-Assets/Shaders/hexWaterFS.fs"); m_hexShoreShader = Nova::Shader::Create("HexMap-Assets/Shaders/hexShoreVS.vs","HexMap-Assets/Shaders/hexShoreFS.fs"); m_hexEstuaryShader = Nova::Shader::Create("HexMap-Assets/Shaders/hexEstuaryVS.vs", "HexMap-Assets/Shaders/hexEstuaryFS.fs"); m_noiseTexture = Nova::Texture2D::Create("HexMap-Assets/Textures/noise.png"); m_noiseTexture->Bind(0); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexRiverShader)->Use(); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexRiverShader)->SetInt("u_noiseTexture", 0); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexWaterShader)->Use(); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexWaterShader)->SetInt("u_noiseTexture", 0); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexShoreShader)->Use(); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexShoreShader)->SetInt("u_noiseTexture", 0); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexEstuaryShader)->Use(); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexEstuaryShader)->SetInt("u_noiseTexture", 0); } void HexLayer::OnImGuiRender() { ImGui::Begin("HexMap"); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::ColorEdit3("Clear Color", glm::value_ptr(m_clearColor)); ImGui::End(); ImGui::Begin("HexMap Brush Settings"); ImGui::Text("General Settings"); if (ImGui::SliderInt("Brush Size", &m_currentBrushSize, 0, m_brush.GetMaxBrushSize())) { m_brush.SetCurrentBrushSize((unsigned int)m_currentBrushSize); } ImGui::Separator(); ImGui::Text("Color Editing Settings"); if (ImGui::Checkbox("Color Editing Enable", &m_canColorEdit)) { if (m_canColorEdit) m_brush.EnableColorEditing(); else m_brush.DisableColorEditing(); } for (decltype(m_brush.GetColorPalleteSize()) i = 0; i < m_brush.GetColorPalleteSize(); i++) { ImGui::RadioButton(m_brush.GetColorName(i).c_str(),&m_currentColorIndex, (int)i); ImGui::SameLine(100); const glm::vec4 &color = m_brush.GetColor(i); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(color.r, color.g, color.b, color.a)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(color.r, color.g, color.b, color.a)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(color.r, color.g, color.b, color.a)); ImGui::Button("", ImVec2(20.0f,20.0f)); ImGui::PopStyleColor(3); } ImGui::Separator(); ImGui::Text("Elevation Editing Settings"); if (ImGui::Checkbox("Elevation Editing Enable", &m_canElevationEdit)) { if (m_canElevationEdit) m_brush.EnableElevationEditing(); else m_brush.DisableElevationEditing(); } if (ImGui::SliderInt("Elevation Value", &m_currentElevation, 0, m_brush.GetMaxElevation())) { m_brush.SetCurrentElevation((unsigned int)m_currentElevation); } ImGui::Separator(); ImGui::Text("River Editing Settings"); if (ImGui::Checkbox("River Editing Enable", &m_canRiverEdit)) { if (m_canRiverEdit) m_brush.EnableRiverEditing(); else m_brush.DisableRiverEditing(); } ImGui::Text("River Editing Mode:"); ImGui::RadioButton("Removing Rivers", &m_currentRiverEditingMode, 0); ImGui::RadioButton("Adding Rivers", &m_currentRiverEditingMode, 1); ImGui::Separator(); ImGui::Text("Water Level Settings"); if (ImGui::Checkbox("Water Level Editing Enable", &m_canWaterEdit)) { if (m_canWaterEdit) m_brush.EnableWaterEditing(); else m_brush.DisableWaterEditing(); } if (ImGui::SliderInt("Water Level Value", &m_currentWaterLevel, 0, m_brush.GetMaxElevation())) { m_brush.SetCurrentWaterLevel((unsigned int)m_currentWaterLevel); } ImGui::Separator(); ImGui::Text("Current Tile Info"); ImGui::Text((std::string("Tile Index : ") + std::to_string(m_brush.GetCurrentTileIndex())).c_str()); const HexTile& tile = m_hexMap->GetTile(m_brush.GetCurrentTileIndex()); ImGui::Text((std::string("Elevation : ") + std::to_string(tile.elevation)).c_str()); ImGui::Text((std::string("Water Level : ") + std::to_string(tile.waterLevel)).c_str()); ImGui::Text("Color :"); ImGui::SameLine(50); const glm::vec4 &color = tile.color; ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(color.r, color.g, color.b, color.a)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(color.r, color.g, color.b, color.a)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(color.r, color.g, color.b, color.a)); ImGui::Button("", ImVec2(20.0f, 20.0f)); ImGui::PopStyleColor(3); if (tile.HasIncomingRiver()) ImGui::Text((std::string("Tile has Incoming river with direction : ") + std::to_string(tile.inComingRiver)).c_str()); if (tile.HasOutGoingRiver()) ImGui::Text((std::string("Tile has Outgoing river with direction : ") + std::to_string(tile.outGoingRiver)).c_str()); ImGui::End(); } void HexLayer::OnUpdate(Nova::Timestep ts) { UpdateScene(ts); RenderScene(); } void HexLayer::OnEvent(Nova::Event &e) { m_camController->OnEvent(e); } void HexLayer::UpdateScene(Nova::Timestep ts) { m_currentTime += ts; m_camController->OnUpdate(ts); if (Nova::Input::IsMouseButtonPressed(NOVA_MOUSE_BUTTON_1) && !(ImGui::GetIO().WantCaptureMouse)) { float x, y; Nova::Input::GetMousePosition(x, y); if (y < 0.0f) Nova::Input::GetMousePosition(x, y); const Nova::Window& window = Nova::Application::Get().GetWindow(); unsigned int width = window.GetWidth(); unsigned int height = window.GetHeight(); Nova::Ray cameraRay = m_camera->GetCameraRay(width, height, x, y); HexTileRayHitInfo tileHitInfo = m_hexMap->GetHexTileInfo(cameraRay); if (tileHitInfo.HasHitted()) { m_brush.SetCurrentTileIndex(tileHitInfo.hexIndex); m_hexMap->EditMap(m_brush); m_brush.SetDragging(true); //NOVA_TRACE("HexTile Index : {0}", ray.hexIndex); } else { m_brush.SetDragging(false); } } else { m_brush.SetDragging(false); } m_brush.SetCurrentColorIndex((decltype(m_brush.GetColorPalleteSize())) m_currentColorIndex); m_brush.SetCurrentRiverEditingMode(IntToRiverEditingMode(m_currentRiverEditingMode)); } void HexLayer::RenderScene() { Nova::RenderCommand::SetClearColor(m_clearColor); Nova::RenderCommand::Clear(); Nova::Renderer::BeginScene(*m_camera); Nova::Renderer::SetShaderData(*m_hexShader); unsigned int i = 0; for (auto it = m_hexMap->cTerrainVaoBegin(); it != m_hexMap->cTerrainVaoEnd(); it++, i++) Nova::Renderer::UnIndexedBasicSubmit(*(*it)); Nova::Renderer::SetShaderData(*m_hexShoreShader); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexShoreShader)->SetFloat("time", (float)m_currentTime); i = 0; for (auto it = m_hexMap->cShoreVaoBegin(); it != m_hexMap->cShoreVaoEnd(); it++, i++) Nova::Renderer::UnIndexedBasicSubmit(*(*it)); Nova::Renderer::SetShaderData(*m_hexWaterShader); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexWaterShader)->SetFloat("time", (float)m_currentTime); i = 0; for (auto it = m_hexMap->cWaterVaoBegin(); it != m_hexMap->cWaterVaoEnd(); it++, i++) Nova::Renderer::UnIndexedBasicSubmit(*(*it)); Nova::Renderer::SetShaderData(*m_hexRiverShader); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexRiverShader)->SetFloat("time", (float)m_currentTime); i = 0; for (auto it = m_hexMap->cRiverVaoBegin(); it != m_hexMap->cRiverVaoEnd(); it++, i++) Nova::Renderer::UnIndexedBasicSubmit(*(*it)); Nova::Renderer::SetShaderData(*m_hexEstuaryShader); std::dynamic_pointer_cast<Nova::OpenGLShader>(m_hexEstuaryShader)->SetFloat("time", (float)m_currentTime); i = 0; for (auto it = m_hexMap->cEstuaryVaoBegin(); it != m_hexMap->cEstuaryVaoEnd(); it++, i++) Nova::Renderer::UnIndexedBasicSubmit(*(*it)); Nova::Renderer::EndScene(); }
35.538462
125
0.718615
Aaron-Berland
33000ee98ac5341cc40e314692ae229b42952767
2,533
cpp
C++
options/slider.cpp
cpuwolf/opentrack
5541cfc68d87c2fc254eb2f2a5aad79831871a88
[ "ISC" ]
1
2018-02-06T08:36:39.000Z
2018-02-06T08:36:39.000Z
options/slider.cpp
cpuwolf/opentrack
5541cfc68d87c2fc254eb2f2a5aad79831871a88
[ "ISC" ]
null
null
null
options/slider.cpp
cpuwolf/opentrack
5541cfc68d87c2fc254eb2f2a5aad79831871a88
[ "ISC" ]
null
null
null
/* Copyright (c) 2015-2016, Stanislaw Halik <sthalik@misaki.pl> * Permission to use, copy, modify, and/or distribute this * software for any purpose with or without fee is hereby granted, * provided that the above copyright notice and this permission * notice appear in all copies. */ #include "slider.hpp" #include <cmath> namespace options { slider_value::slider_value(double cur, double min, double max) : cur_(cur), min_(min), max_(max) { if (min_ > max_) min_ = max_; if (cur_ > max_) cur_ = max; if (cur_ < min_) cur_ = min_; } slider_value::slider_value(const slider_value& v) : slider_value(v.cur(), v.min(), v.max()) { } slider_value::slider_value() : slider_value(0, 0, 0) { } slider_value& slider_value::operator=(const slider_value& v) { cur_ = v.cur_; min_ = v.min_; max_ = v.max_; return *this; } bool slider_value::operator==(const slider_value& v) const { using std::fabs; constexpr double eps = 2e-3; #if 1 return (fabs(v.cur_ - cur_) < eps && fabs(v.min_ - min_) < eps && fabs(v.max_ - max_) < eps); #else return (fabs(v.cur_ - cur_) < eps); #endif } slider_value slider_value::update_from_slider(int pos, int q_min, int q_max) const { slider_value v(*this); const int q_diff = q_max - q_min; const double sv_pos = q_diff == 0 ? 0 : (((pos - q_min) * (v.max() - v.min())) / q_diff + v.min()); if (sv_pos < v.min()) v = slider_value(v.min(), v.min(), v.max()); else if (sv_pos > v.max()) v = slider_value(v.max(), v.min(), v.max()); else v = slider_value(sv_pos, v.min(), v.max()); return v; } int slider_value::to_slider_pos(int q_min, int q_max) const { const int q_diff = q_max - q_min; const double div = max() - min(); if (std::fabs(div) < 1e-4) return q_min; else return int(std::round(((cur() - min()) * q_diff / div) + q_min)); } } // end ns options QT_BEGIN_NAMESPACE QDataStream& operator << (QDataStream& out, const options::slider_value& v) { out << v.cur() << v.min() << v.max(); return out; } QDebug operator << (QDebug dbg, const options::slider_value& val) { return dbg << val.cur(); } QDataStream& operator >> (QDataStream& in, options::slider_value& v) { double cur = 0, min = 0, max = 0; in >> cur >> min >> max; v = options::slider_value(cur, min, max); return in; } QT_END_NAMESPACE
22.026087
91
0.590209
cpuwolf
330295dd3fd02068e9af27ee0bc17a90037e451d
17,897
cpp
C++
SkeletonBasics-D2D_playbacktest/SkeletonBasics.cpp
drchangliu/KineticAnalytics
7fc906900ec44f286088c2b294a29b341e2bd7c0
[ "MIT" ]
3
2015-02-26T21:12:48.000Z
2015-03-26T21:45:40.000Z
SkeletonBasics-D2D_playbacktest/SkeletonBasics.cpp
drchangliu/KineticAnalytics
7fc906900ec44f286088c2b294a29b341e2bd7c0
[ "MIT" ]
1
2015-02-26T21:12:21.000Z
2015-02-26T21:12:21.000Z
SkeletonBasics-D2D_playbacktest/SkeletonBasics.cpp
drchangliu/KineticAnalytics
7fc906900ec44f286088c2b294a29b341e2bd7c0
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // <copyright file="SkeletonBasics.cpp" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ //#include <afxcoll.h> #include "stdafx.h" #include <strsafe.h> #include "SkeletonBasics.h" #include "resource.h" static const float g_JointThickness = 3.0f; static const float g_TrackedBoneThickness = 6.0f; static const float g_InferredBoneThickness = 1.0f; void CSkeletonBasics::Load_Data(std::string filename){ fin.open(filename.c_str()); while (!fin.eof()){ NUI_SKELETON_FRAME temp; for (int i = 0; i < NUI_SKELETON_POSITION_COUNT; i++){ fin >> temp.SkeletonData->SkeletonPositions[i].x; fin >> temp.SkeletonData->SkeletonPositions[i].y; fin >> temp.SkeletonData->SkeletonPositions[i].z; } Skeleton_Stack.push_back(temp); } } /// <summary> /// Entry point for the application /// </summary> /// <param name="hInstance">handle to the application instance</param> /// <param name="hPrevInstance">always 0</param> /// <param name="lpCmdLine">command line arguments</param> /// <param name="nCmdShow">whether to display minimized, maximized, or normally</param> /// <returns>status</returns> int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { CSkeletonBasics application; application.Run(hInstance, nCmdShow); } /// <summary> /// Constructor /// </summary> CSkeletonBasics::CSkeletonBasics() : m_pD2DFactory(NULL), m_hNextSkeletonEvent(INVALID_HANDLE_VALUE), m_pSkeletonStreamHandle(INVALID_HANDLE_VALUE), m_bSeatedMode(false), m_pRenderTarget(NULL), m_pBrushJointTracked(NULL), m_pBrushJointInferred(NULL), m_pBrushBoneTracked(NULL), m_pBrushBoneInferred(NULL), m_pNuiSensor(NULL) { ZeroMemory(m_Points,sizeof(m_Points)); Load_Data("playback_log_Sun_Feb_08_21_44_36_2015.txt"); S = 0; playing = true; } /// <summary> /// Destructor /// </summary> CSkeletonBasics::~CSkeletonBasics() { if (m_pNuiSensor) { m_pNuiSensor->NuiShutdown(); } if (m_hNextSkeletonEvent && (m_hNextSkeletonEvent != INVALID_HANDLE_VALUE)) { CloseHandle(m_hNextSkeletonEvent); } // clean up Direct2D objects DiscardDirect2DResources(); // clean up Direct2D SafeRelease(m_pD2DFactory); SafeRelease(m_pNuiSensor); } /// <summary> /// Creates the main window and begins processing /// </summary> /// <param name="hInstance">handle to the application instance</param> /// <param name="nCmdShow">whether to display minimized, maximized, or normally</param> int CSkeletonBasics::Run(HINSTANCE hInstance, int nCmdShow) { MSG msg = {0}; WNDCLASS wc = {0}; // Dialog custom window class wc.style = CS_HREDRAW | CS_VREDRAW; wc.cbWndExtra = DLGWINDOWEXTRA; wc.hInstance = hInstance; wc.hCursor = LoadCursorW(NULL, IDC_ARROW); wc.hIcon = LoadIconW(hInstance, MAKEINTRESOURCE(IDI_APP)); wc.lpfnWndProc = DefDlgProcW; wc.lpszClassName = L"SkeletonBasicsAppDlgWndClass"; if (!RegisterClassW(&wc)) { return 0; } // Create main application window HWND hWndApp = CreateDialogParamW( hInstance, MAKEINTRESOURCE(IDD_APP), NULL, (DLGPROC)CSkeletonBasics::MessageRouter, reinterpret_cast<LPARAM>(this)); // Show window ShowWindow(hWndApp, nCmdShow); //GetDlgItem(m_hWnd, IDC_SLIDER1); //Slider->SetRangeMin(0); //Slider->SetRangeMax(10); //const int eventCount = 1; //HANDLE hEvents[eventCount]; // Main message loop while (WM_QUIT != msg.message) { // hEvents[0] = m_hNextSkeletonEvent; // Check to see if we have either a message (by passing in QS_ALLEVENTS) // Or a Kinect event (hEvents) // Update() will check for Kinect events individually, in case more than one are signalled // DWORD dwEvent = MsgWaitForMultipleObjects(eventCount, hEvents, FALSE, INFINITE, QS_ALLINPUT); // Check if this is an event we're waiting on and not a timeout or message //if (WAIT_OBJECT_0 == dwEvent) //{ Update(); // } if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { // If a dialog message will be taken care of by the dialog proc if ((hWndApp != NULL) && IsDialogMessageW(hWndApp, &msg)) { continue; } TranslateMessage(&msg); DispatchMessageW(&msg); } } return static_cast<int>(msg.wParam); } /// <summary> /// Main processing function /// </summary> void CSkeletonBasics::Update() { Sleep(1000/30 ); ProcessSkeleton(); if (playing==true){ if (S < Skeleton_Stack.size() - 1){ S++; } } } /// <summary> /// Handles window messages, passes most to the class instance to handle /// </summary> /// <param name="hWnd">window message is for</param> /// <param name="uMsg">message</param> /// <param name="wParam">message data</param> /// <param name="lParam">additional message data</param> /// <returns>result of message processing</returns> LRESULT CALLBACK CSkeletonBasics::MessageRouter(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CSkeletonBasics* pThis = NULL; if (WM_INITDIALOG == uMsg) { pThis = reinterpret_cast<CSkeletonBasics*>(lParam); SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis)); } else { pThis = reinterpret_cast<CSkeletonBasics*>(::GetWindowLongPtr(hWnd, GWLP_USERDATA)); } if (pThis) { return pThis->DlgProc(hWnd, uMsg, wParam, lParam); } return 0; } /// <summary> /// Handle windows messages for the class instance /// </summary> /// <param name="hWnd">window message is for</param> /// <param name="uMsg">message</param> /// <param name="wParam">message data</param> /// <param name="lParam">additional message data</param> /// <returns>result of message processing</returns> LRESULT CALLBACK CSkeletonBasics::DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: { // Bind application window handle m_hWnd = hWnd; // Init Direct2D D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory); // Look for a connected Kinect, and create it if found CreateFirstConnected(); } break; // If the titlebar X is clicked, destroy app case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: // Quit the main message pump PostQuitMessage(0); break; // Handle button press case WM_COMMAND: // If it was for the near mode control and a clicked event, change near mode if (IDC_CHECK_SEATED == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam)) { // Toggle out internal state for near mode m_bSeatedMode = !m_bSeatedMode; if (NULL != m_pNuiSensor) { // Set near mode for sensor based on our internal state m_pNuiSensor->NuiSkeletonTrackingEnable(m_hNextSkeletonEvent, m_bSeatedMode ? NUI_SKELETON_TRACKING_FLAG_ENABLE_SEATED_SUPPORT : 0); } } if (IDC_BUTTON1 == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam)){ playing = true; } if (IDC_BUTTON2 == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam)){ playing = false; } if (IDC_BUTTON3 == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam)){ S=0; //Slider->SetRangeMin(30); } break; } return FALSE; } /// <summary> /// Create the first connected Kinect found /// </summary> /// <returns>indicates success or failure</returns> HRESULT CSkeletonBasics::CreateFirstConnected() { INuiSensor * pNuiSensor; int iSensorCount = 0; HRESULT hr = NuiGetSensorCount(&iSensorCount); if (FAILED(hr)) { return hr; } // Look at each Kinect sensor for (int i = 0; i < iSensorCount; ++i) { // Create the sensor so we can check status, if we can't create it, move on to the next hr = NuiCreateSensorByIndex(i, &pNuiSensor); if (FAILED(hr)) { continue; } // Get the status of the sensor, and if connected, then we can initialize it hr = pNuiSensor->NuiStatus(); if (S_OK == hr) { m_pNuiSensor = pNuiSensor; break; } // This sensor wasn't OK, so release it since we're not using it pNuiSensor->Release(); } if (NULL != m_pNuiSensor) { // Initialize the Kinect and specify that we'll be using skeleton hr = m_pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON); if (SUCCEEDED(hr)) { // Create an event that will be signaled when skeleton data is available m_hNextSkeletonEvent = CreateEventW(NULL, TRUE, FALSE, NULL); // Open a skeleton stream to receive skeleton data hr = m_pNuiSensor->NuiSkeletonTrackingEnable(m_hNextSkeletonEvent, 0); } } if (NULL == m_pNuiSensor || FAILED(hr)) { SetStatusMessage(L"No ready Kinect found!"); return E_FAIL; } return hr; } /// <summary> /// Handle new skeleton data /// </summary> void CSkeletonBasics::ProcessSkeleton() { NUI_SKELETON_FRAME skeletonFrame = {0}; HRESULT hr; // Endure Direct2D is ready to hr = EnsureDirect2DResources( ); if ( FAILED(hr) ) { return; } m_pRenderTarget->BeginDraw(); m_pRenderTarget->Clear( ); RECT rct; GetClientRect( GetDlgItem( m_hWnd, IDC_VIDEOVIEW ), &rct); int width = rct.right; int height = rct.bottom; //Sleep(16); for (int i = 0; i < NUI_SKELETON_COUNT; ++i) { DrawSkeleton(Skeleton_Stack[S].SkeletonData[i], width, height); } hr = m_pRenderTarget->EndDraw(); // Device lost, need to recreate the render target // We'll dispose it now and retry drawing if (D2DERR_RECREATE_TARGET == hr) { hr = S_OK; DiscardDirect2DResources(); } } /// <summary> /// Draws a skeleton /// </summary> /// <param name="skel">skeleton to draw</param> /// <param name="windowWidth">width (in pixels) of output buffer</param> /// <param name="windowHeight">height (in pixels) of output buffer</param> void CSkeletonBasics::DrawSkeleton(const NUI_SKELETON_DATA & skel, int windowWidth, int windowHeight) { int i; for (i = 0; i < NUI_SKELETON_POSITION_COUNT; ++i) { m_Points[i] = SkeletonToScreen(skel.SkeletonPositions[i], windowWidth, windowHeight); } // Render Torso DrawBone(skel, NUI_SKELETON_POSITION_HEAD, NUI_SKELETON_POSITION_SHOULDER_CENTER); DrawBone(skel, NUI_SKELETON_POSITION_SHOULDER_CENTER, NUI_SKELETON_POSITION_SHOULDER_LEFT); DrawBone(skel, NUI_SKELETON_POSITION_SHOULDER_CENTER, NUI_SKELETON_POSITION_SHOULDER_RIGHT); DrawBone(skel, NUI_SKELETON_POSITION_SHOULDER_CENTER, NUI_SKELETON_POSITION_SPINE); DrawBone(skel, NUI_SKELETON_POSITION_SPINE, NUI_SKELETON_POSITION_HIP_CENTER); DrawBone(skel, NUI_SKELETON_POSITION_HIP_CENTER, NUI_SKELETON_POSITION_HIP_LEFT); DrawBone(skel, NUI_SKELETON_POSITION_HIP_CENTER, NUI_SKELETON_POSITION_HIP_RIGHT); // Left Arm DrawBone(skel, NUI_SKELETON_POSITION_SHOULDER_LEFT, NUI_SKELETON_POSITION_ELBOW_LEFT); DrawBone(skel, NUI_SKELETON_POSITION_ELBOW_LEFT, NUI_SKELETON_POSITION_WRIST_LEFT); DrawBone(skel, NUI_SKELETON_POSITION_WRIST_LEFT, NUI_SKELETON_POSITION_HAND_LEFT); // Right Arm DrawBone(skel, NUI_SKELETON_POSITION_SHOULDER_RIGHT, NUI_SKELETON_POSITION_ELBOW_RIGHT); DrawBone(skel, NUI_SKELETON_POSITION_ELBOW_RIGHT, NUI_SKELETON_POSITION_WRIST_RIGHT); DrawBone(skel, NUI_SKELETON_POSITION_WRIST_RIGHT, NUI_SKELETON_POSITION_HAND_RIGHT); // Left Leg DrawBone(skel, NUI_SKELETON_POSITION_HIP_LEFT, NUI_SKELETON_POSITION_KNEE_LEFT); DrawBone(skel, NUI_SKELETON_POSITION_KNEE_LEFT, NUI_SKELETON_POSITION_ANKLE_LEFT); DrawBone(skel, NUI_SKELETON_POSITION_ANKLE_LEFT, NUI_SKELETON_POSITION_FOOT_LEFT); // Right Leg DrawBone(skel, NUI_SKELETON_POSITION_HIP_RIGHT, NUI_SKELETON_POSITION_KNEE_RIGHT); DrawBone(skel, NUI_SKELETON_POSITION_KNEE_RIGHT, NUI_SKELETON_POSITION_ANKLE_RIGHT); DrawBone(skel, NUI_SKELETON_POSITION_ANKLE_RIGHT, NUI_SKELETON_POSITION_FOOT_RIGHT); // Draw the joints in a different color for (i = 0; i < NUI_SKELETON_POSITION_COUNT; ++i) { D2D1_ELLIPSE ellipse = D2D1::Ellipse( m_Points[i], g_JointThickness, g_JointThickness ); if ( skel.eSkeletonPositionTrackingState[i] == NUI_SKELETON_POSITION_INFERRED ) { m_pRenderTarget->DrawEllipse(ellipse, m_pBrushJointInferred); } else if ( skel.eSkeletonPositionTrackingState[i] == NUI_SKELETON_POSITION_TRACKED ) { m_pRenderTarget->DrawEllipse(ellipse, m_pBrushJointTracked); } } } /// <summary> /// Draws a bone line between two joints /// </summary> /// <param name="skel">skeleton to draw bones from</param> /// <param name="joint0">joint to start drawing from</param> /// <param name="joint1">joint to end drawing at</param> void CSkeletonBasics::DrawBone(const NUI_SKELETON_DATA & skel, NUI_SKELETON_POSITION_INDEX joint0, NUI_SKELETON_POSITION_INDEX joint1) { NUI_SKELETON_POSITION_TRACKING_STATE joint0State = skel.eSkeletonPositionTrackingState[joint0]; NUI_SKELETON_POSITION_TRACKING_STATE joint1State = skel.eSkeletonPositionTrackingState[joint1]; // If we can't find either of these joints, exit if (joint0State == NUI_SKELETON_POSITION_NOT_TRACKED || joint1State == NUI_SKELETON_POSITION_NOT_TRACKED) { return; } // Don't draw if both points are inferred if (joint0State == NUI_SKELETON_POSITION_INFERRED && joint1State == NUI_SKELETON_POSITION_INFERRED) { return; } // We assume all drawn bones are inferred unless BOTH joints are tracked if (joint0State == NUI_SKELETON_POSITION_TRACKED && joint1State == NUI_SKELETON_POSITION_TRACKED) { m_pRenderTarget->DrawLine(m_Points[joint0], m_Points[joint1], m_pBrushBoneTracked, g_TrackedBoneThickness); } else { m_pRenderTarget->DrawLine(m_Points[joint0], m_Points[joint1], m_pBrushBoneInferred, g_InferredBoneThickness); } } /// <summary> /// Converts a skeleton point to screen space /// </summary> /// <param name="skeletonPoint">skeleton point to tranform</param> /// <param name="width">width (in pixels) of output buffer</param> /// <param name="height">height (in pixels) of output buffer</param> /// <returns>point in screen-space</returns> D2D1_POINT_2F CSkeletonBasics::SkeletonToScreen(Vector4 skeletonPoint, int width, int height) { LONG x, y; USHORT depth; // Calculate the skeleton's position on the screen // NuiTransformSkeletonToDepthImage returns coordinates in NUI_IMAGE_RESOLUTION_320x240 space NuiTransformSkeletonToDepthImage(skeletonPoint, &x, &y, &depth); float screenPointX = static_cast<float>(x * width) / cScreenWidth; float screenPointY = static_cast<float>(y * height) / cScreenHeight; return D2D1::Point2F(screenPointX, screenPointY); } /// <summary> /// Ensure necessary Direct2d resources are created /// </summary> /// <returns>S_OK if successful, otherwise an error code</returns> HRESULT CSkeletonBasics::EnsureDirect2DResources() { HRESULT hr = S_OK; // If there isn't currently a render target, we need to create one if (NULL == m_pRenderTarget) { RECT rc; GetWindowRect( GetDlgItem( m_hWnd, IDC_VIDEOVIEW ), &rc ); int width = rc.right - rc.left; int height = rc.bottom - rc.top; D2D1_SIZE_U size = D2D1::SizeU( width, height ); D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties(); rtProps.pixelFormat = D2D1::PixelFormat( DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE); rtProps.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE; // Create a Hwnd render target, in order to render to the window set in initialize hr = m_pD2DFactory->CreateHwndRenderTarget( rtProps, D2D1::HwndRenderTargetProperties(GetDlgItem( m_hWnd, IDC_VIDEOVIEW), size), &m_pRenderTarget ); if ( FAILED(hr) ) { SetStatusMessage(L"Couldn't create Direct2D render target!"); return hr; } //light green m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(0.27f, 0.75f, 0.27f), &m_pBrushJointTracked); m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 1.0f), &m_pBrushJointInferred); m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Green, 1.0f), &m_pBrushBoneTracked); m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Gray, 1.0f), &m_pBrushBoneInferred); } return hr; } /// <summary> /// Dispose Direct2d resources /// </summary> void CSkeletonBasics::DiscardDirect2DResources( ) { SafeRelease(m_pRenderTarget); SafeRelease(m_pBrushJointTracked); SafeRelease(m_pBrushJointInferred); SafeRelease(m_pBrushBoneTracked); SafeRelease(m_pBrushBoneInferred); } /// <summary> /// Set the status bar message /// </summary> /// <param name="szMessage">message to display</param> void CSkeletonBasics::SetStatusMessage(WCHAR * szMessage) { SendDlgItemMessageW(m_hWnd, IDC_STATUS, WM_SETTEXT, 0, (LPARAM)szMessage); } // //button1 int CSkeletonBasics::Button() { return 0; }
31.901961
148
0.673074
drchangliu
3305725f01103eac0b76ed109d2de9202346de3d
1,736
cpp
C++
voxblox-plusplus/global_segment_map_node/src/feature_ros_tools.cpp
Skywalker666666/visual_mapping
d28d1e2c800c08f0a3a2b32821e7cae09dfe744e
[ "MIT" ]
3
2021-05-17T10:55:40.000Z
2021-09-04T08:57:46.000Z
voxblox-plusplus/global_segment_map_node/src/feature_ros_tools.cpp
Skywalker666666/visual_mapping
d28d1e2c800c08f0a3a2b32821e7cae09dfe744e
[ "MIT" ]
null
null
null
voxblox-plusplus/global_segment_map_node/src/feature_ros_tools.cpp
Skywalker666666/visual_mapping
d28d1e2c800c08f0a3a2b32821e7cae09dfe744e
[ "MIT" ]
1
2021-06-09T13:38:19.000Z
2021-06-09T13:38:19.000Z
#include "voxblox_gsm/feature_ros_tools.h" namespace voxblox { namespace voxblox_gsm { std_msgs::ColorRGBA getColorFromBlockFeatures( const double max_number_of_features, const double number_of_features) { const double ratio = 2 * std::min(1.0, number_of_features / max_number_of_features); const double r = std::max(0.0, ratio - 1.0); const double b = std::max(0.0, 1.0 - ratio); std_msgs::ColorRGBA color_msg; color_msg.r = r; color_msg.g = 1.0 - b - r; color_msg.b = b; color_msg.a = 0.2; return color_msg; } void fromFeaturesMsgToFeature3D(const modelify_msgs::Features& features_msg, size_t* descriptor_size, std::string* camera_frame, ros::Time* timestamp, std::vector<Feature3D>* features_C) { CHECK_NOTNULL(camera_frame); CHECK_NOTNULL(timestamp); CHECK_NOTNULL(features_C); *descriptor_size = features_msg.descriptor_length; *camera_frame = features_msg.header.frame_id; *timestamp = features_msg.header.stamp; for (const modelify_msgs::Feature& msg : features_msg.features) { Feature3D feature; feature.keypoint << msg.x, msg.y, msg.z; feature.keypoint_scale = msg.scale; feature.keypoint_response = msg.response; feature.keypoint_angle = msg.angle; constexpr size_t kRows = 1; feature.descriptor = cv::Mat(kRows, *descriptor_size, CV_32FC1); memcpy(feature.descriptor.data, msg.descriptor.data(), msg.descriptor.size() * sizeof(float)); CHECK_EQ(feature.descriptor.cols, msg.descriptor.size()) << "Descriptor size is wrong!"; features_C->push_back(feature); } } } // namespace voxblox_gsm } // namespace voxblox
31
80
0.6803
Skywalker666666
330951916b0668d1849dd38abcc7077e13e99d12
3,210
cpp
C++
Source Code/Core/Time/ApplicationTimer.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Core/Time/ApplicationTimer.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Core/Time/ApplicationTimer.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Headers/ApplicationTimer.h" #include "Utility/Headers/Localization.h" #include "Core/Headers/StringHelper.h" namespace Divide::Time { namespace { // Time stamp at application initialization TimeValue g_startupTicks; // Previous frame's time stamp TimeValue g_frameDelay; std::atomic<U64> g_elapsedTimeUs; /// Benchmark reset frequency in milliseconds constexpr U64 g_benchmarkFrequencyUS = MillisecondsToMicroseconds<U64>(500); } ApplicationTimer::ApplicationTimer() noexcept { reset(); } void ApplicationTimer::reset() noexcept { std::atomic_init(&g_elapsedTimeUs, 0ULL); g_startupTicks = std::chrono::high_resolution_clock::now(); g_frameDelay = g_startupTicks; resetFPSCounter(); } void ApplicationTimer::update() { const TimeValue currentTicks = std::chrono::high_resolution_clock::now(); g_elapsedTimeUs = to_U64(std::chrono::duration_cast<USec>(currentTicks - g_startupTicks).count()); const U64 duration = to_U64(std::chrono::duration_cast<USec>(currentTicks - g_frameDelay).count()); g_frameDelay = currentTicks; _speedfactor = Time::MicrosecondsToSeconds<F32>(duration * _targetFrameRate); _frameRateHandler.tick(g_elapsedTimeUs); if (g_elapsedTimeUs - _lastBenchmarkTimeStamp > g_benchmarkFrequencyUS) { F32 fps = 0.f; F32 frameTime = 0.f; _frameRateHandler.frameRateAndTime(fps, frameTime); _lastBenchmarkTimeStamp = g_elapsedTimeUs; _benchmarkReport = Util::StringFormat(Locale::Get(_ID("FRAMERATE_FPS_OUTPUT")), fps, _frameRateHandler.averageFrameRate(), _frameRateHandler.maxFrameRate(), _frameRateHandler.minFrameRate(), frameTime); } } namespace Game { /// The following functions return the time updated in the main app loop only! U64 ElapsedNanoseconds() noexcept { return MicrosecondsToNanoseconds(ElapsedMicroseconds()); } U64 ElapsedMicroseconds() noexcept { return g_elapsedTimeUs; } D64 ElapsedMilliseconds() noexcept { return MicrosecondsToMilliseconds<D64, U64>(ElapsedMicroseconds()); } D64 ElapsedSeconds() noexcept { return MicrosecondsToSeconds(ElapsedMicroseconds()); } } namespace App { /// The following functions force a timer update (a call to query performance timer). U64 ElapsedNanoseconds() noexcept { return MicrosecondsToNanoseconds(ElapsedMicroseconds()); } U64 ElapsedMicroseconds() noexcept { return to_U64(std::chrono::duration_cast<USec>(std::chrono::high_resolution_clock::now() - g_startupTicks).count()); } D64 ElapsedMilliseconds() noexcept { return MicrosecondsToMilliseconds<D64, U64>(ElapsedMicroseconds()); } D64 ElapsedSeconds() noexcept { return MicrosecondsToSeconds(ElapsedMicroseconds()); } } } // namespace Divide::Time
34.891304
125
0.649221
IonutCava
330a2964df6a16524177ee6c4353632c7daa75e6
483
cpp
C++
Tga3D/Source/tga2dcore/tga2d/text/token.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
1
2022-03-10T11:43:24.000Z
2022-03-10T11:43:24.000Z
Tga3D/Source/tga2dcore/tga2d/text/token.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
Tga3D/Source/tga2dcore/tga2d/text/token.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <tga2d/text/Token.h> /////////////////////////////////////////////////////////////////////////////////////////// Token::Token(int tokenID, std::string tokenAsStr) : m_tokenID(tokenID), m_matchPos(0), m_tokenAsStr(tokenAsStr) { } /////////////////////////////////////////////////////////////////////////////////////////// Token::~Token() { } ///////////////////////////////////////////////////////////////////////////////////////////
30.1875
92
0.277433
sarisman84
330bb6979fae851a61c3d167ba7afe4b19d18d10
134
cpp
C++
code/Instructions/ZeroRegInstr/NoopInstr/NoopInstr.cpp
LLDevLab/LLDevCompiler
f73f13d38069ab5b571fb136e068eb06387caf4c
[ "BSD-3-Clause" ]
5
2019-10-22T18:37:43.000Z
2020-12-09T14:00:03.000Z
code/Instructions/ZeroRegInstr/NoopInstr/NoopInstr.cpp
LLDevLab/LLDevCompiler
f73f13d38069ab5b571fb136e068eb06387caf4c
[ "BSD-3-Clause" ]
1
2020-03-29T15:30:45.000Z
2020-03-29T15:30:45.000Z
code/Instructions/ZeroRegInstr/NoopInstr/NoopInstr.cpp
LLDevLab/LLDevCompiler
f73f13d38069ab5b571fb136e068eb06387caf4c
[ "BSD-3-Clause" ]
1
2019-12-23T06:51:45.000Z
2019-12-23T06:51:45.000Z
#include "NoopInstr.h" NoopInstr::NoopInstr(token_pos pos) : ZeroRegInstr(pos) { } uint32_t NoopInstr::GetOpcode() { return 0x00; }
13.4
55
0.731343
LLDevLab
330d73b306d40ea1ceacd0036723440fd25cf900
3,577
cpp
C++
BRDF_Sampler/main.cpp
Mr-Devin/GraphicAlgorithm
58877e6a8dba75ab171b0d89260defaffa22d047
[ "MIT" ]
1
2021-11-16T11:40:04.000Z
2021-11-16T11:40:04.000Z
BRDF_Sampler/main.cpp
younha169/GraphicAlgorithm
93287ae4d4171764e788371887c4fd1549304552
[ "MIT" ]
null
null
null
BRDF_Sampler/main.cpp
younha169/GraphicAlgorithm
93287ae4d4171764e788371887c4fd1549304552
[ "MIT" ]
null
null
null
#include <gli.hpp> #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> #include <map> #include <glm/glm.hpp> using namespace std; const float PI = 3.14159265358979323846264338327950288; float RadicalInverse_VdC(unsigned int bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; } glm::vec2 Hammersley(unsigned int i, unsigned int N) { return glm::vec2(float(i) / float(N), RadicalInverse_VdC(i)); } glm::vec3 ImportanceSampleGGX(glm::vec2 Xi, float roughness, glm::vec3 N) { float a = roughness * roughness; float phi = 2.0 * PI * Xi.x; float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y)); float sinTheta = sqrt(1.0 - cosTheta * cosTheta); // from spherical coordinates to cartesian coordinates glm::vec3 H; H.x = cos(phi) * sinTheta; H.y = sin(phi) * sinTheta; H.z = cosTheta; // from tangent-space vector to world-space sample vector glm::vec3 up = abs(N.z) < 0.999 ? glm::vec3(0.0, 0.0, 1.0) : glm::vec3(1.0, 0.0, 0.0); glm::vec3 tangent = normalize(cross(up, N)); glm::vec3 bitangent = cross(N, tangent); glm::vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; return normalize(sampleVec); } float GeometrySchlickGGX(float NdotV, float roughness) { float a = roughness; float k = (a * a) / 2.0; float nom = NdotV; float denom = NdotV * (1.0 - k) + k; return nom / denom; } float GeometrySmith(float roughness, float NoV, float NoL) { float ggx2 = GeometrySchlickGGX(NoV, roughness); float ggx1 = GeometrySchlickGGX(NoL, roughness); return ggx1 * ggx2; } glm::vec2 IntegrateBRDF(float NdotV, float roughness, unsigned int samples = 1024) { glm::vec3 V; V.x = sqrt(1.0 - NdotV * NdotV); V.y = 0.0; V.z = NdotV; float A = 0.0; float B = 0.0; glm::vec3 N = glm::vec3(0.0, 0.0, 1.0); for (unsigned int i = 0u; i < samples; ++i) { glm::vec2 Xi = Hammersley(i, samples); glm::vec3 H = ImportanceSampleGGX(Xi, roughness, N); glm::vec3 L = normalize(2.0f * dot(V, H) * H - V); float NoL = glm::max(L.z, 0.0f); float NoH = glm::max(H.z, 0.0f); float VoH = glm::max(dot(V, H), 0.0f); float NoV = glm::max(dot(N, V), 0.0f); if (NoL > 0.0) { float G = GeometrySmith(roughness, NoV, NoL); float G_Vis = (G * VoH) / (NoH * NoV) / NoL; float Fc = pow(1.0 - VoH, 5.0); A += (1.0 - Fc) * G_Vis; B += Fc * G_Vis; } } return glm::vec2(A / float(samples), B / float(samples)); } int main(int argc, char* argv[]) { int N = 512; gli::texture2d tex = gli::texture2d(gli::FORMAT_RG32_SFLOAT_PACK32, gli::extent2d(N, N), 1); for(int i = 0; i < N; i++) for (int j = 0; j < N; j++) { float NoV = (i + 0.5f) * (1.0f / N); float roughness = (j + 0.5f) * (1.0f / N); glm::vec2 eval = IntegrateBRDF(NoV, roughness); tex.store<glm::vec2>({ i, N - j - 1 }, 0, eval); } string outdir = "../Textures/BRDFLUT/"; string outfile = outdir + "BRDFLut.dds"; try { cout << "write rendered images: " << outfile << endl; gli::save(tex, outfile); } catch (std::exception e) { cout << "***** AN ERROR OCCURRED *****" << endl; cout << e.what() << endl; return 1; } std::cout << " [" << N << " x " << N << "] BRDF LUT generated using " << 1024 << " samples.\n"; std::cout << "Saved LUT to " << outfile << ".\n"; return 0; }
26.69403
97
0.604697
Mr-Devin
3310f07dafeb235799873103c6eb80c7294f2cb4
1,159
cpp
C++
src/nnfusion/core/operators/generic_op/generic_op_define/AddN.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/operators/generic_op/generic_op_define/AddN.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/operators/generic_op/generic_op_define/AddN.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "nnfusion/core/operators/generic_op/generic_op.hpp" REGISTER_OP(AddN).attr<nnfusion::op::OpConfig::any>("T").infershape( [](std::shared_ptr<graph::GNode> gnode) -> void { // enforce is like assert, but when thing goes wrong, it will print error message. NNFUSION_CHECK(gnode->get_input_size() >= 2) << "Inputs of AddN operator should not be less than 2."; auto& shape_0 = gnode->get_input_shape(0); for (int i = 1; i < gnode->get_input_size(); i++) { auto& shape_n = gnode->get_input_shape(i); NNFUSION_CHECK(shape_0.size() == shape_n.size()) << "Shape dimension size not match."; for (int j = 0; j < shape_0.size(); j++) { NNFUSION_CHECK(shape_0[j] == shape_n[j]) << "Dimension " << j << " in shapes must be equal."; } } nnfusion::Shape output_shape_0(shape_0); gnode->set_output_type_and_shape(0, gnode->get_input_element_type(0), output_shape_0); });
42.925926
98
0.577222
lynex
33175de52b19795adb6dd4367db1fcb5362c116f
9,009
cpp
C++
CUDA/session7.cpp
corsario/esat-multithreading
1adb947cbf5b7e4b6cc6e64973a03d558f041611
[ "MIT" ]
1
2015-04-23T07:09:11.000Z
2015-04-23T07:09:11.000Z
CUDA/session7.cpp
corsario/esat-multithreading
1adb947cbf5b7e4b6cc6e64973a03d558f041611
[ "MIT" ]
null
null
null
CUDA/session7.cpp
corsario/esat-multithreading
1adb947cbf5b7e4b6cc6e64973a03d558f041611
[ "MIT" ]
null
null
null
#define NOMINMAX #include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <string> #include "cuda_runtime.h" #include <mtUtils/Algorithms.hpp> #include "CUDAUtils.hpp" #include "SumIntVectors.cuh" namespace test_runtime_api { const size_t numElementsToPrint = 4; template<typename T> void printV(std::ostream& out, const T& a, size_t size, size_t initElement, size_t numElements) { unsigned int end = std::min(size, initElement + numElements); if (initElement == 0) out << "{ "; else out << " ... "; for (unsigned int i = initElement; i < end - 1; i++) { out << a[i] << ","; } out << a[end - 1]; if (end == size) std::cout << " } "; else std::cout << " ... "; } void test_cuda_simple1() { const int arraySize = 5; float a[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; float b[] = { 10, 20, 30, 40, 50 }; std::vector<float> c(arraySize); // Choose which GPU to run on, change this on a multi-GPU system. cuda::Device device(0); cudaError_t cudaStatus = addWithCuda(c.data(), a, b, arraySize); cuda::Check::CUDAError(cudaStatus, "addWithCuda failed!"); printV(std::cout, a, arraySize, 0, 5); std::cout << " + "; printV(std::cout, b, arraySize, 0, 5); std::cout << " = "; printV(std::cout, c, c.size(), 0, 5); std::cout << std::endl; } void test_cpu_simple2(const unsigned int arraySize, bool printResults = false) { std::vector<float> a(arraySize); std::vector<float> b(arraySize); std::vector<float> c(arraySize); for (unsigned int i = 0; i < arraySize; i++) { a[i] = static_cast<float>(sin(i)*sin(i)); b[i] = static_cast<float>(cos(i)*cos(i)); c[i] = a[i] + b[i]; } if (printResults) { printV(std::cout, a, a.size(), 0, numElementsToPrint); printV(std::cout, a, a.size(), arraySize - numElementsToPrint, 20); std::cout << " + "; printV(std::cout, b, b.size(), 0, numElementsToPrint); printV(std::cout, b, b.size(), arraySize - numElementsToPrint, 20); std::cout << " = "; printV(std::cout, c, c.size(), 0, numElementsToPrint); printV(std::cout, c, c.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << std::endl; } } void test_cuda_simple2(const int arraySize, bool printResults = false) { std::vector<float> a(arraySize); std::vector<float> b(arraySize); std::vector<float> c(arraySize); // Choose which GPU to run on, change this on a multi-GPU system. cuda::Device device(0); cudaError_t cudaStatus; float* a_ptr = a.data(); float* b_ptr = b.data(); float* c_ptr = c.data(); cudaStatus = fillWithCudaV2(a_ptr, b_ptr, arraySize); cuda::Check::CUDAError(cudaStatus, "fillWithCudaV2 failed!"); cudaStatus = addWithCudaV2(c_ptr, a_ptr, b_ptr, arraySize); cuda::Check::CUDAError(cudaStatus, "addWithCudaV2 failed!"); if (printResults) { printV(std::cout, a, a.size(), 0, numElementsToPrint); printV(std::cout, a, a.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << " + "; printV(std::cout, b, b.size(), 0, numElementsToPrint); printV(std::cout, b, b.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << " = "; printV(std::cout, c, c.size(), 0, numElementsToPrint); printV(std::cout, c, c.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << std::endl; } } void test_cuda_simple3(const int arraySize, bool printResults = false) { std::vector<float> a(arraySize); std::vector<float> b(arraySize); std::vector<float> c(arraySize); // Choose which GPU to run on, change this on a multi-GPU system. cuda::Device device(0); cudaError_t cudaStatus; float* a_ptr = a.data(); float* b_ptr = b.data(); float* c_ptr = c.data(); cudaStatus = fillThenAddWithCudaV2(c_ptr, a_ptr, b_ptr, arraySize); cuda::Check::CUDAError(cudaStatus, "fillAndAddWithCuda failed!"); if (printResults) { printV(std::cout, a, a.size(), 0, numElementsToPrint); printV(std::cout, a, a.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << " + "; printV(std::cout, b, b.size(), 0, numElementsToPrint); printV(std::cout, b, b.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << " = "; printV(std::cout, c, c.size(), 0, numElementsToPrint); printV(std::cout, c, c.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << std::endl; } } void test_cuda_simple4(const int arraySize, bool printResults = false) { std::vector<float> a(arraySize); std::vector<float> b(arraySize); std::vector<float> c(arraySize); // Choose which GPU to run on, change this on a multi-GPU system. cuda::Device device(0); cudaError_t cudaStatus; float* a_ptr = a.data(); float* b_ptr = b.data(); float* c_ptr = c.data(); cudaStatus = fillAndAddWithCudaV2(c_ptr, a_ptr, b_ptr, arraySize); cuda::Check::CUDAError(cudaStatus, "fillAndAddWithCudaV2 failed!"); if (printResults) { printV(std::cout, a, a.size(), 0, numElementsToPrint); printV(std::cout, a, a.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << " + "; printV(std::cout, b, b.size(), 0, numElementsToPrint); printV(std::cout, b, b.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << " = "; printV(std::cout, c, c.size(), 0, numElementsToPrint); printV(std::cout, c, c.size(), arraySize - numElementsToPrint, numElementsToPrint); std::cout << std::endl; } } } void pause() { std::cout << "Press any key to continue." << std::endl; std::cin.ignore(); } int main() { try { const unsigned int numTests = 10; const unsigned int iniMult = 1; const unsigned int maxMult = 10000; const bool printResults = false; std::cout << "Test CUDA simple 1" << std::endl; //std::cin.ignore(); test_runtime_api::test_cuda_simple1(); std::cout << "Test CPU simple 2, running ..." << std::endl; for (unsigned int mult = iniMult; mult <= maxMult; mult *= 10) { const int arraySize = 1024 * mult; std::cout << "Array size: " << arraySize << std::endl; ScopedTimer timer("time for CPU simple 2", numTests); for (unsigned int i = 0; i < numTests; i++) { test_runtime_api::test_cpu_simple2(arraySize, printResults); } } pause(); std::cout << "Test CUDA simple 2, running ..." << std::endl; for (unsigned int mult = iniMult; mult <= maxMult; mult *= 10) { const int arraySize = 1024 * mult; std::cout << "Array size: " << arraySize << std::endl; ScopedTimer timer("time for CUDA simple 2", numTests); for (unsigned int i = 0; i < numTests; i++) { test_runtime_api::test_cuda_simple2(arraySize, printResults); } } pause(); std::cout << "Test CUDA simple 3, running ..." << std::endl; for (unsigned int mult = iniMult; mult <= maxMult; mult *= 10) { const int arraySize = 1024 * mult; std::cout << "Array size: " << arraySize << std::endl; ScopedTimer timer("time for CUDA simple 3", numTests); for (unsigned int i = 0; i < numTests; i++) { test_runtime_api::test_cuda_simple3(arraySize, printResults); } } pause(); std::cout << "Test CUDA simple 4, running ..." << std::endl; for (unsigned int mult = iniMult; mult <= maxMult; mult *= 10) { const int arraySize = 1024 * mult; std::cout << "Array size: " << arraySize << std::endl; ScopedTimer timer("time for CUDA simple 4", numTests); for (unsigned int i = 0; i < numTests; i++) { test_runtime_api::test_cuda_simple4(arraySize, printResults); } } pause(); } catch (const cuda::cuda_exception& e) { std::cerr << "EXCEPTION:" << e.what() << std::endl; pause(); return -1; } return 0; }
34.517241
150
0.549562
corsario
331945be1668931eaad88d7a2f2dcd24316176c1
1,041
hpp
C++
iehl/src/scene/wavefront/load_material_properties.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
iehl/src/scene/wavefront/load_material_properties.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
iehl/src/scene/wavefront/load_material_properties.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
#pragma once #include <stb_image_resize.h> #include <stb_image.h> #include <tiny_obj_loader.h> #include <iostream> inline void load_material_properties( Scene& s, const tinyobj::ObjReader& wavefront) { std::cout << "--Loading material properties." << std::endl; auto& materials = wavefront.GetMaterials(); { // Material factors. s.materials.material_properties.resize(size(materials)); for(std::size_t i = 0; i < size(materials); ++i) { auto& m = materials[i]; auto& sm = s.materials.material_properties[i]; sm.color_factor = { m.diffuse[0], m.diffuse[1], m.diffuse[2], 1.f}; sm.emission_factor = { m.emission[0], m.emission[1], m.emission[2], 1.f}; sm.ao_roughness_metalness_fator = { m.specular[0], m.specular[1], m.specular[2], 1.f}; } } { gl::NamedBufferStorage(s.materials.material_properties_ssbo, std::span(s.materials.material_properties)); } }
29.742857
68
0.594621
the-last-willy
331e0de18eef3f1dde47f0d90d2a102213121d52
3,949
cpp
C++
owCore/GroupQuality.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owCore/GroupQuality.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owCore/GroupQuality.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
1
2020-05-11T13:32:49.000Z
2020-05-11T13:32:49.000Z
#include "stdafx.h" // General #include "GroupQuality.h" enum R_SamplerState2 // TODO DELETE ME!!! { SS_FILTER_BILINEAR = 0x0000, SS_FILTER_TRILINEAR = 0x0001, SS_FILTER_POINT = 0x0002, SS_ANISO1 = 0x0000, SS_ANISO2 = 0x0004, SS_ANISO4 = 0x0008, SS_ANISO8 = 0x0010, SS_ANISO16 = 0x0020, SS_ADDRU_CLAMP = 0x0000, SS_ADDRU_WRAP = 0x0040, SS_ADDRU_CLAMPCOL = 0x0080, SS_ADDRV_CLAMP = 0x0000, SS_ADDRV_WRAP = 0x0100, SS_ADDRV_CLAMPCOL = 0x0200, SS_ADDRW_CLAMP = 0x0000, SS_ADDRW_WRAP = 0x0400, SS_ADDRW_CLAMPCOL = 0x0800, SS_ADDR_CLAMP = SS_ADDRU_CLAMP | SS_ADDRV_CLAMP | SS_ADDRW_CLAMP, SS_ADDR_WRAP = SS_ADDRU_WRAP | SS_ADDRV_WRAP | SS_ADDRW_WRAP, SS_ADDR_CLAMPCOL = SS_ADDRU_CLAMPCOL | SS_ADDRV_CLAMPCOL | SS_ADDRW_CLAMPCOL, SS_COMP_LEQUAL = 0x1000 }; CGroupQuality::CGroupQuality() { _Bindings->RegisterInputListener(this); } CGroupQuality::~CGroupQuality() { _Bindings->UnregisterInputListener(this); } void CGroupQuality::InitDefault() { // Distances ADT_MCNK_Distance = C_ADT_MCNK_Distance; ADT_MCNK_HighRes_Distance = C_ADT_MCNK_HighRes_Distance; ADT_MDX_Distance = C_ADT_MDX_Distance; ADT_WMO_Distance = C_ADT_WMO_Distance; WMO_MODD_Distance = C_WMO_MODD_Distance; // Textures Texture_Sampler = R_SamplerState2::SS_ANISO16; // Drawing draw_map_mccv = true; WMO_MOCV = false; WMO_AmbColor = false; // Disables draw_mcnk = true; draw_mcnk_low = false; draw_map_wmo = true; draw_wmo_doodads = true; draw_map_m2 = true; draw_water = true; draw_wmo_water = true; drawfog = false; timeEnable = false; } void CGroupQuality::UpdateByFog(float _fogDist) { ADT_MCNK_Distance = (_fogDist < C_ADT_MCNK_Distance) ? _fogDist : /*C_ADT_MCNK_Distance*/ _fogDist; ADT_MCNK_HighRes_Distance = (_fogDist < C_ADT_MCNK_HighRes_Distance) ? _fogDist : C_ADT_MCNK_HighRes_Distance; ADT_MDX_Distance = (_fogDist < C_ADT_MDX_Distance) ? _fogDist : C_ADT_MDX_Distance; ADT_WMO_Distance = (_fogDist < C_ADT_WMO_Distance) ? _fogDist : C_ADT_WMO_Distance; WMO_MODD_Distance = (_fogDist < C_WMO_MODD_Distance) ? _fogDist : C_WMO_MODD_Distance; if (ADT_MDX_Distance > ADT_MCNK_Distance) { ADT_MDX_Distance = ADT_MCNK_Distance; } if (ADT_WMO_Distance > ADT_MCNK_Distance) { ADT_WMO_Distance = ADT_MCNK_Distance; } } bool CGroupQuality::OnKeyboardPressed(int _key, int _scancode, int _mods) { if (_key == OW_KEY_KP_1) { SwitchBool(draw_mcnk); return true; } if (_key == OW_KEY_KP_2) { SwitchBool(draw_map_wmo); return true; } if (_key == OW_KEY_KP_3) { SwitchBool(draw_wmo_doodads); return true; } if (_key == OW_KEY_KP_4) { SwitchBool(draw_map_m2); return true; } if (_key == OW_KEY_KP_5) { SwitchBool(draw_water); return true; } if (_key == OW_KEY_KP_9) { SwitchBool(draw_mcnk_low); return true; } if (_key == OW_KEY_F1) { Texture_Sampler = R_SamplerState2::SS_FILTER_POINT; return true; } if (_key == OW_KEY_F2) { Texture_Sampler = R_SamplerState2::SS_FILTER_BILINEAR; return true; } if (_key == OW_KEY_F3) { Texture_Sampler = R_SamplerState2::SS_FILTER_TRILINEAR; return true; } if (_key == OW_KEY_F6) { Texture_Sampler = R_SamplerState2::SS_ANISO1; return true; } if (_key == OW_KEY_F7) { Texture_Sampler = R_SamplerState2::SS_ANISO2; return true; } if (_key == OW_KEY_F8) { Texture_Sampler = R_SamplerState2::SS_ANISO4; return true; } if (_key == OW_KEY_F9) { Texture_Sampler = R_SamplerState2::SS_ANISO8; return true; } if (_key == OW_KEY_F10) { Texture_Sampler = R_SamplerState2::SS_ANISO16; return true; } if (_key == OW_KEY_C) { SwitchBool(WMO_MOCV); return true; } if (_key == OW_KEY_V) { SwitchBool(WMO_AmbColor); return true; } if (_key == OW_KEY_B) { SwitchBool(draw_map_mccv); return true; } if (_key == OW_KEY_F) { SwitchBool(drawfog); return true; } if (_key == OW_KEY_T) { SwitchBool(timeEnable); return true; } return false; }
18.453271
111
0.729552
adan830
331f4f6ee758e2124a5e8165ce9f8270dff91762
2,856
hpp
C++
PhysicsSandbox/Physics2dTCS/Components/PhysicsSpace2dTCS.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
PhysicsSandbox/Physics2dTCS/Components/PhysicsSpace2dTCS.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
PhysicsSandbox/Physics2dTCS/Components/PhysicsSpace2dTCS.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
#pragma once #include "Physics2dStandardTCS.hpp" #include "Components/Collider2dTCS.hpp" #include "Components/RigidBody2dTCS.hpp" #include "Physics2dTCS/Utilities/Physics2dQueues.hpp" #include "Physics2dCore/Queries/Collider2dCastResults.hpp" namespace Physics2dCore { class ComponentCreatedEvent; class CollisionLibrary; }//namespace Physics2dCore namespace Physics2dTCS { class Contact2dCache; //-------------------------------------------------------------------PhysicsSpace2dTCS class PhysicsSpace2dTCS : public Zero::Component { public: ZilchDeclareType(PhysicsSpace2dTCS, TypeCopyMode::ReferenceType); PhysicsSpace2dTCS(); ~PhysicsSpace2dTCS(); void Initialize(Zero::CogInitializer& initializer); void OnSystemLogicUpdate(Zero::UpdateEvent* updateEvent); void IterateTimestep(float dt); void UpdateQueues(float dt); void IntegrateBodiesVelocity(float dt); void DetectCollisions(); void Broadphase(Array<Physics2dCore::Collider2dPair>& possiblePairs); void NarrowPhase(Array<Physics2dCore::Collider2dPair>& possiblePairs); void ResolutionPhase(float dt); void IntegrateBodiesPosition(float dt); void Publish(); bool Cast(const Vector2& point); Physics2dCore::Collider2dCastResults CastResults(const Vector2& point); Physics2dCore::Collider2dCastResults CastResults(const Vector2& point, int maxCount); void CastResultsInternal(const Vector2& point, Physics2dCore::Collider2dCastResults& results); float Cast(const Ray2d& ray); Physics2dCore::Collider2dCastResults CastResults(const Ray2d& ray); Physics2dCore::Collider2dCastResults CastResults(const Ray2d& ray, int maxCount); void CastResultsInternal(const Ray2d& ray, Physics2dCore::Collider2dCastResults& results); void OnCollider2dCreated(Physics2dCore::ComponentCreatedEvent* e); void OnRigidBody2dCreated(Physics2dCore::ComponentCreatedEvent* e); void OnPhysics2dEffectCreated(Physics2dCore::ComponentCreatedEvent* e); void OnPhysics2dEffectDestroyed(Physics2dCore::ComponentCreatedEvent* e); void Add(RigidBody2dTCS* rigidBody); void Remove(RigidBody2dTCS* rigidBody); void Add(Collider2dTCS* collider); void Remove(Collider2dTCS* collider); void QueueMassUpdate(RigidBody2dTCS* rigidBody); void QueueBroadphaseUpdate(Collider2dTCS* collider); void DebugDrawContactManifold(const Physics2dCore::ContactManifold2d& manifold); BaseInList<RigidBody2dTCS, RigidBody2dTCS, &RigidBody2dTCS::mSpaceLink> mRigidBodies; BaseInList<Collider2dTCS, Collider2dTCS, &Collider2dTCS::mSpaceLink> mColliders; Array<Physics2dEffect*> mEffects; Physics2dQueues mQueues; Physics2dCore::IBroadphase2dManager* mBroadphaseManager = nullptr; Physics2dCore::CollisionLibrary* mCollisionLibrary = nullptr; IConstraint2dSolver* mConstraintSolver = nullptr; Contact2dCache* mContactCache = nullptr; }; }//namespace Physics2d
37.090909
96
0.794118
jodavis42
3321b476f8fcb0432578c36c2f4a4247caa07b5b
1,267
cpp
C++
engine/source/unit_tests/MessageBuffer_test.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/source/unit_tests/MessageBuffer_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/source/unit_tests/MessageBuffer_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "gtest/gtest.h" TEST(SW_Engine_MessageBuffer, insertion) { MessageBuffer mb(3); mb.add_message("a", Colour::COLOUR_RED); mb.add_message("b", Colour::COLOUR_GREEN); mb.add_message("c", Colour::COLOUR_BLUE); pair<string, Colour> exp_a = make_pair("a", Colour::COLOUR_RED); EXPECT_EQ(exp_a, mb.get_message(2)); mb.add_message("d", Colour::COLOUR_YELLOW); mb.add_message("e", Colour::COLOUR_CYAN); pair<string, Colour> exp_c = make_pair("c", Colour::COLOUR_BLUE); pair<string, Colour> exp_d = make_pair("d", Colour::COLOUR_YELLOW); pair<string, Colour> exp_e = make_pair("e", Colour::COLOUR_CYAN); // "a" and "b" should have been removed: EXPECT_EQ(exp_e, mb.get_message(0)); EXPECT_EQ(exp_d, mb.get_message(1)); EXPECT_EQ(exp_c, mb.get_message(2)); EXPECT_EQ(3, mb.capacity()); EXPECT_EQ(3, mb.size()); } TEST(SW_Engine_MessageBuffer, serialization_id) { MessageBuffer mb; EXPECT_EQ(ClassIdentifier::CLASS_ID_MESSAGE_BUFFER, mb.get_class_identifier()); } TEST(SW_Engine_MessageBuffer, saveload) { MessageBuffer mb; MessageBuffer mb2; ostringstream ss; mb.add_message("test", Colour::COLOUR_WHITE); mb.serialize(ss); istringstream iss(ss.str()); mb2.deserialize(iss); EXPECT_TRUE(mb == mb2); }
24.365385
81
0.713496
prolog
332838e067b9ef6458971fe8f50acc4dd9a61871
1,378
hpp
C++
examples/tt.hpp
superchessengine/libchess
a169b5efe61bb8ce53eab7edf5445a78997fec80
[ "MIT" ]
4
2021-05-27T01:40:06.000Z
2022-02-28T12:14:41.000Z
examples/tt.hpp
superchessengine/libchess
a169b5efe61bb8ce53eab7edf5445a78997fec80
[ "MIT" ]
4
2021-09-02T16:28:46.000Z
2022-03-29T13:35:41.000Z
examples/tt.hpp
superchessengine/libchess
a169b5efe61bb8ce53eab7edf5445a78997fec80
[ "MIT" ]
4
2021-09-07T17:04:04.000Z
2022-01-17T20:03:09.000Z
#ifndef TT_HPP #define TT_HPP #include <cstdint> #include <cstring> template <class T> class TT { public: TT(unsigned int mb) : filled_{0} { if (mb < 1) { mb = 1; } max_entries_ = (mb * 1024 * 1024) / sizeof(T); entries_ = new T[max_entries_]; } ~TT() { delete entries_; } [[nodiscard]] T poll(const std::uint64_t hash) const noexcept { const auto idx = index(hash); return entries_[idx]; } void add(const std::uint64_t hash, const T &t) noexcept { const auto idx = index(hash); filled_ += (entries_[idx].hash == 0 ? 1 : 0); entries_[idx] = t; } [[nodiscard]] std::size_t size() const noexcept { return max_entries_; } void clear() noexcept { filled_ = 0; std::memset(entries_, 0, max_entries_ * sizeof(T)); } [[nodiscard]] int hashfull() const noexcept { return 1000 * (static_cast<double>(filled_) / max_entries_); } void prefetch(const std::uint64_t hash) const noexcept { const auto idx = index(hash); __builtin_prefetch(&entries_[idx]); } private: [[nodiscard]] std::size_t index(const std::uint64_t hash) const noexcept { return hash % max_entries_; } std::size_t max_entries_; std::size_t filled_; T *entries_; }; #endif
22.225806
78
0.572569
superchessengine
3329c824d926136e637cf138d845565732fe2a5f
2,260
cpp
C++
leetcode/cpp/p208/p208.cpp
davidlunadeleon/leetcode
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
[ "Unlicense" ]
1
2020-08-20T23:27:13.000Z
2020-08-20T23:27:13.000Z
leetcode/cpp/p208/p208.cpp
davidlunadeleon/leetcode
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
[ "Unlicense" ]
null
null
null
leetcode/cpp/p208/p208.cpp
davidlunadeleon/leetcode
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
[ "Unlicense" ]
null
null
null
// Source: https://leetcode.com/problems/implement-trie-prefix-tree/ // Date: 05.08.2020 // Solution by: David Luna // Runtime: 208ms // Memory usage: 36.1 MB /* Note: This solution contains memory leaks that I plan to solve later. For the time being, I would not use it as a correct solution of the problem. */ #include <iostream> #include <unordered_map> #include <vector> using namespace std; // Leetcode solution starts class Trie { public: Trie() { trieMap = new unordered_map<char, Trie>(); } ~Trie() { delete trieMap; } void insert(string word) { word += '*'; unordered_map<char, Trie> *currMap = trieMap; for (uint64_t i = 0; i < word.size(); i++) { char c = word[i]; if ((*currMap).find(c) == (*currMap).end()) { (*currMap).insert(pair<char, Trie>(c, Trie())); } currMap = (*currMap)[c].getTrieMap(); } } bool search(string word) { word += '*'; return startsWith(word); } bool startsWith(string prefix) { unordered_map<char, Trie> *currMap = trieMap; for (uint64_t i = 0; i < prefix.size(); i++) { char c = prefix[i]; if ((*currMap).find(c) == (*currMap).end()) { return false; } currMap = (*currMap)[c].getTrieMap(); } return true; } protected: unordered_map<char, Trie> *getTrieMap() { return trieMap; } private: unordered_map<char, Trie> *trieMap; }; // Leetcode solution ends template <typename T> void makeVectorT(vector<T> &vect) { int numElements; cin >> numElements; for (int i = 0; i < numElements; i++) { T temp; cin >> temp; vect.push_back(temp); } } void makeTest() { Trie *trie; int numOperations; vector<bool> ans, correctAns; trie = new Trie(); cin >> numOperations; for (int i = 0; i < numOperations; i++) { char c; string s; cin >> c; switch (c) { case 'i': cin >> s; trie->insert(s); break; case 's': cin >> s; ans.push_back(trie->search(s)); break; case 'w': cin >> s; ans.push_back(trie->startsWith(s)); break; default: break; } } makeVectorT(correctAns); cout << (ans == correctAns ? "pass\n" : "fail\n"); delete trie; } int main() { int numTests; // Introduce the number of tests to make. cin >> numTests; for (int i = 0; i < numTests; i++) { makeTest(); } return 0; }
19.824561
70
0.615487
davidlunadeleon
06a27ff978a1b9f333372fe4831eaec775e1ebdd
648
cpp
C++
examples/dynamic/min-coin-change.cpp
priyanksingh02/ds-algo
d024f5e6313a1b7bf3fcbc9ad775cb7bdd986916
[ "CC0-1.0" ]
1
2021-06-21T18:09:31.000Z
2021-06-21T18:09:31.000Z
examples/dynamic/min-coin-change.cpp
priyanksingh02/ds-algo
d024f5e6313a1b7bf3fcbc9ad775cb7bdd986916
[ "CC0-1.0" ]
null
null
null
examples/dynamic/min-coin-change.cpp
priyanksingh02/ds-algo
d024f5e6313a1b7bf3fcbc9ad775cb7bdd986916
[ "CC0-1.0" ]
1
2021-03-12T11:35:37.000Z
2021-03-12T11:35:37.000Z
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int n; int coins[1000010]; bool ready[1000010]; int value[1000010]; const int INF = 100000010; int solve(int x) { if ( x < 0) return INF; if( x == 0) return 0; if (ready[x]) return value[x]; int best = INF; for(int i = 0; i < n; ++i) { best = min(best, solve(x - coins[i])+1); } ready[x] = true; value[x] = best; return best; } int main() { n = 3; coins[0] = 1; coins[1] = 3; coins[2] = 4; memset(ready, 0, sizeof(ready)); memset(value, 0, sizeof(value)); cout << solve(10) << endl; // 3 }
18
48
0.54784
priyanksingh02
06a44855774166dc68610b1c771bdcf508a9c04e
3,451
hpp
C++
Framework/EventFramework/EventDirector.hpp
SergeyIvanov87/TTL
321e38ff2885c231088846f6d37e8fe1d3faf104
[ "BSD-3-Clause" ]
5
2019-03-20T07:02:02.000Z
2020-05-09T18:16:27.000Z
Framework/EventFramework/EventDirector.hpp
SergeyIvanov87/TTL
321e38ff2885c231088846f6d37e8fe1d3faf104
[ "BSD-3-Clause" ]
null
null
null
Framework/EventFramework/EventDirector.hpp
SergeyIvanov87/TTL
321e38ff2885c231088846f6d37e8fe1d3faf104
[ "BSD-3-Clause" ]
null
null
null
#ifndef EVENT_DIRECTOR_HPP #define EVENT_DIRECTOR_HPP #include <tuple> #include <set> #include <array> #include <vector> #include <functional> #include <future> #include <type_traits> #include "EventDirector.h" #include "Interfaces/IEventConsumer.hpp" #include "Framework/Utils/CTimeUtils.h" template<class Consumer> template<class Producer, class Event> void ConsumersSetWrapper<Consumer>::produceEventForAllConsumers(Producer &producer, Event &event) { for( auto c : m_sameTypeConsumers) { if constexpr(std::is_same_v<Producer,EmptyProducer>) { (*c).onProcessEventDispatcher(event); } else { (*c).onProcessEventDispatcher(producer, event); } } } #define T_ARGS_DECL class Producer, class ...Consumers #define T_ARGS_DEF Producer, Consumers... template<T_ARGS_DECL> template<class Consumer> void IEventDirector<T_ARGS_DEF>::registerConsumer(Consumer consumerCandidate) { std::get<ConsumersSetWrapper<std::remove_pointer_t<Consumer>>>(m_consumers).m_sameTypeConsumers.insert(consumerCandidate); } template<T_ARGS_DECL> template<class Event> void SyncEventDirector<T_ARGS_DEF>::produceEvent(Producer &producer, Event &&event) { std::apply( [this, &producer, &event] (auto &...x) { bool dispatchingResult[] { (x.produceEventForAllConsumers(producer, event), true)... }; }, this->m_consumers); }; template<class Event> void eventOwner(Event &&event) { (void)event; } template<T_ARGS_DECL> template<class Event> typename AsyncEventDirector<T_ARGS_DEF>::AsyncTask AsyncEventDirector<T_ARGS_DEF>::produceEvent(Producer &producer, Event &&event) { /* own event a object - to avoid danging reference. * This callback should be called at chain finish, * to allow actual event processing callback finish its execution */ /* ret[0] = [holdedEvent = std::forward<Event>(event)]() -> void { (void)holdedEvent; }; */ /* ret.push_back([holdedEvent = std::move(event)]() mutable { eventOwner(std::move(holdedEvent)); }); */ using Processors = std::array<std::function<void(Event &)>, Base::ConsumersCount + 1>; Processors processors; CTimeUtils::for_each_in_tuple(this->m_consumers, [this, &producer, &event, &processors](size_t index, auto &dst) { //compare requested id and existed id typedef typename std::remove_reference<decltype(dst)>::type NonRefType; processors[index] = (std::bind(&NonRefType::template produceEventForAllConsumers<Producer, Event>, &dst, std::ref(producer), std::placeholders::_1)); }); /* std::apply( [this, &producer, &event, &ret] (auto &...x) { //typedef typename std::remove_reference<decltype(x)>::type NonRefType; size_t index = 0; bool dispatchingResult[] { (ret[index++] = std::bind( typename std::remove_reference<decltype(x)>::type::template produceEventForAllConsumers<Producer, Event>, &x, std::ref(producer), std::ref(event)))... }; }, m_consumers);*/ return AsyncTask(std::bind([](Event &ev, Processors &pr) { for(auto &p : pr) { p(ev); } }, std::move(event), std::move(processors))); } #undef T_ARGS_DEF #undef T_ARGS_DECL #endif
27.173228
190
0.644741
SergeyIvanov87
06a8a32811bafe27473d7e79e1802c523b33b62b
1,142
cpp
C++
utils/file_manager.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
1
2021-05-30T02:13:37.000Z
2021-05-30T02:13:37.000Z
utils/file_manager.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
null
null
null
utils/file_manager.cpp
GP-S/HOTS
85903015033184694e3b2b70af401a0ea5de11b7
[ "Unlicense", "MIT" ]
null
null
null
#include "file_manager.h" bool saveObject(char* file, void* Object, int SizeOfObject) { try { if (file == "") throw "wrong path"; std::ofstream outfile(file, std::ios::out | std::ios::app | std::ios::binary); if (!outfile) { std::cerr << "\a\n\nError while trying to open the file : " << *file <<"\n\n"; return 0; } outfile.write((char*) Object, SizeOfObject); outfile.close(); } catch (const char *exception) { std::cerr << "\n*** " << exception << " ***\n"; } catch (...) { std::cerr << "\n*** Wild ERROR appeared ***\n"; return 0; } return 1; } bool loadObject(char* file, void *Object, int SizeOfObject){ try { if (file == "") throw "wrong path"; std::ifstream infile(file, std::ios::binary); if (!infile) { std::cerr << "\a\n\nError while trying to read the file : " << *file << "\n\n"; std::cerr << "\a\n\nErri\n\n"; return 0; } infile.read((char*) Object, SizeOfObject); infile.close(); } catch (const char *exception) { std::cerr << "\n*** " << exception << " ***\n"; } catch (...) { std::cerr << "\n*** Wild ERROR appeared ***\n"; return 0; } return 1; }
20.392857
113
0.563047
GP-S
06a90e0c12c7844902c61e28488eec5cbc15861d
2,654
cpp
C++
convert.cpp
Laakeri/phylogeny-aaai
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
[ "MIT" ]
null
null
null
convert.cpp
Laakeri/phylogeny-aaai
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
[ "MIT" ]
null
null
null
convert.cpp
Laakeri/phylogeny-aaai
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(int argc, char** argv){ assert(argc == 2); if (string(argv[1]) == "tophy") { int n,m; cin>>n>>m; cout<<n<<" "<<m<<endl; vector<int> ss(m); for (int i=0;i<m;i++){ cin>>ss[i]; assert(ss[i]>0); } for (int i=0;i<n;i++){ for (int ii=0;ii<m;ii++){ int x; cin>>x; assert(x<ss[ii]); assert(x>=-1); if (x==-1){ cout<<"? "; } else{ cout<<x<<" "; } } cout<<endl; } } else if (string(argv[1]) == "toraw") { int n,m; cin>>n>>m; vector<vector<int>> mat(n); for (int i=0;i<n;i++){ mat[i].resize(m); for (int ii=0;ii<m;ii++){ string t; cin>>t; if (t=="?"){ mat[i][ii]=-1; }else{ mat[i][ii]=stoi(t); } } } vector<int> ss(m); for (int i=0;i<m;i++){ int f=0; map<int, int> mx; for (int ii=0;ii<n;ii++){ if (mat[ii][i]>=0){ if (!mx.count(mat[ii][i])){ mx[mat[ii][i]]=f++; } mat[ii][i]=mx[mat[ii][i]]; } } ss[i]=f; } int h=0; for (int i=0;i<m;i++){ if (ss[i]>0){ h++; } } assert(h>0); cout<<n<<endl<<h<<endl; for (int i=0;i<m;i++){ if (ss[i]>0){ cout<<ss[i]<<" "; } } cout<<endl; for (int i=0;i<n;i++){ for (int ii=0;ii<m;ii++){ if (ss[ii]>0){ cout<<mat[i][ii]<<" "; } } cout<<endl; } } else if(string(argv[1]) == "normal") { int n,m; cin>>n>>m; vector<vector<int>> mat(n); for (int i=0;i<n;i++){ mat[i].resize(m); for (int ii=0;ii<m;ii++){ string t; cin>>t; if (t=="?"){ mat[i][ii]=-1; }else{ mat[i][ii]=stoi(t); } } } vector<int> ss(m); for (int i=0;i<m;i++){ int f=0; map<int, int> mx; for (int ii=0;ii<n;ii++){ if (mat[ii][i]>=0){ if (!mx.count(mat[ii][i])){ mx[mat[ii][i]]=f++; } mat[ii][i]=mx[mat[ii][i]]; } } ss[i]=f; } int h=0; for (int i=0;i<m;i++){ if (ss[i]>1){ h++; } } assert(h>0); cout<<n<<" "<<h<<endl; for (int i=0;i<n;i++){ for (int ii=0;ii<m;ii++){ if (ss[ii]>1){ if (mat[i][ii]>=0) cout<<mat[i][ii]<<" "; else { assert(mat[i][ii]==-1); cout<<"? "; } } } cout<<endl; } } else { abort(); } }
19.659259
51
0.351168
Laakeri
06a9bd54f3179dbc37157bf8702a94f21acff596
975
cpp
C++
clover/src/shell.cpp
vas0x59/clover
513f4f419a6a2de476d2838db5c1c244de6b3e44
[ "MIT" ]
146
2020-05-04T10:11:43.000Z
2022-03-28T04:41:57.000Z
clover/src/shell.cpp
vas0x59/clover
513f4f419a6a2de476d2838db5c1c244de6b3e44
[ "MIT" ]
132
2017-07-23T11:49:11.000Z
2020-04-09T01:15:53.000Z
clover/src/shell.cpp
vas0x59/clover
513f4f419a6a2de476d2838db5c1c244de6b3e44
[ "MIT" ]
149
2020-04-28T07:45:25.000Z
2022-03-30T13:48:01.000Z
#include <ros/ros.h> #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> #include <std_msgs/String.h> #include <clover/Execute.h> ros::Duration timeout; // TODO: handle timeout bool handle(clover::Execute::Request& req, clover::Execute::Response& res) { ROS_INFO("Execute: %s", req.cmd.c_str()); std::array<char, 128> buffer; std::string result; FILE *fp = popen(req.cmd.c_str(), "r"); if (fp == NULL) { res.code = clover::Execute::Request::CODE_FAIL; res.output = "popen() failed"; return true; } while (fgets(buffer.data(), buffer.size(), fp) != nullptr) { res.output += buffer.data(); } res.code = pclose(fp); return true; } int main(int argc, char **argv) { ros::init(argc, argv, "shell"); ros::NodeHandle nh, nh_priv("~"); timeout = ros::Duration(nh_priv.param("timeout", 3.0)); auto gt_serv = nh.advertiseService("exec", &handle); ROS_INFO("shell: ready"); ros::spin(); }
19.117647
74
0.657436
vas0x59
06af9fc20013acf5648f333355257310b7be60f8
782
cpp
C++
code/cheonsa/cheonsa__types_triangle64.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa__types_triangle64.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
code/cheonsa/cheonsa__types_triangle64.cpp
Olaedaria/cheonsa
cf366a5869a4bf0872a0d8dc6a01a68118cfc92e
[ "Unlicense" ]
null
null
null
#include "cheonsa__types_triangle64.h" #include "cheonsa__ops_geometry.h" #include "cheonsa__ops_vector.h" namespace cheonsa { void_c triangle64_c::make_planes_from_points() { face_plane = ops::make_plane64_from_triangle( point_a, point_b, point_c ); edge_plane_ab = ops::make_plane64_from_normal_and_point( ops::normal_vector64x3( ops::cross_product_vector64x3( point_a - point_b, face_plane.get_normal() ) ), point_a ); edge_plane_bc = ops::make_plane64_from_normal_and_point( ops::normal_vector64x3( ops::cross_product_vector64x3( point_b - point_c, face_plane.get_normal() ) ), point_b ); edge_plane_ca = ops::make_plane64_from_normal_and_point( ops::normal_vector64x3( ops::cross_product_vector64x3( point_c - point_a, face_plane.get_normal() ) ), point_c ); } }
46
172
0.792839
Olaedaria
06b2741d92f67093de28a0285a27eb2c5a6b094a
1,751
cpp
C++
src/autonomy/compiler/translator_exceptions.cpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
2
2015-05-31T20:26:51.000Z
2022-02-19T16:11:14.000Z
src/autonomy/compiler/translator_exceptions.cpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
null
null
null
src/autonomy/compiler/translator_exceptions.cpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
null
null
null
//! \file translator_exceptions.cpp //! \brief Implementation of translator exception classes. #include <boost/lexical_cast.hpp> #include <autonomy/compiler/translator_exceptions.hpp> namespace autonomy { namespace compiler { //! \class translator_exception //! \brief Generic translator exception. translator_exception::translator_exception(std::string const& msg) : exception(), _msg(msg) { _msg = "Translator error: " + _msg; } const char* translator_exception::what() const throw () { return (_msg.c_str()); } //! \class corrupted_parse_tree //! \brief Exception for parse trees recognized as malformed. corrupted_parse_tree::corrupted_parse_tree(parser_id_t at_node, parser_id_t prev_node) : translator_exception((std::string( "corrupted parse tree [at parser = ") + boost::lexical_cast < std::string > (at_node) + ", previous parser = " + boost::lexical_cast < std::string > (prev_node) + "]")) {} //! \class undeclared_variable undeclared_variable::undeclared_variable(std::string const& symbol) : translator_exception("undefined reference to variable: " + symbol) {} //! \class undefined_command undefined_command::undefined_command(std::string const& symbol) : translator_exception("undefined reference to command: " + symbol) {} } }
35.734694
80
0.540263
medlefsen
06b50ca76d67925001340533dc8dd8dda96986bd
1,362
cpp
C++
src/titanic/controller/AbstractController.cpp
LaroyenneG/Fuzzy-Logic
0d2911c02b5bd4eedcca42925e7e35c5dd450bf8
[ "Apache-2.0" ]
null
null
null
src/titanic/controller/AbstractController.cpp
LaroyenneG/Fuzzy-Logic
0d2911c02b5bd4eedcca42925e7e35c5dd450bf8
[ "Apache-2.0" ]
null
null
null
src/titanic/controller/AbstractController.cpp
LaroyenneG/Fuzzy-Logic
0d2911c02b5bd4eedcca42925e7e35c5dd450bf8
[ "Apache-2.0" ]
null
null
null
#include "AbstractController.h" namespace controller { AbstractController::AbstractController(Model *_model, View *_view, Draftsman *_draftsman) : draftsman(_draftsman), model(_model), view(_view) { } void AbstractController::updateView() const { mutex.lock(); draftsman->draw(); auto rotationSpeed = model->getTitanic()->getMachinesRotationSpeed(); view->setMachinesSpeed(rotationSpeed[TITANIC_ALTERNATIVE_MACHINE_1_RANK], rotationSpeed[TITANIC_TURBINE_MACHINE_RANK], rotationSpeed[TITANIC_ALTERNATIVE_MACHINE_2_RANK]); view->setShipSpeed(model->getTitanic()->getSpeed()); view->setDistance(model->distance()); view->setCourse(model->getTitanic()->getOrientation()); if (view->automaticPilotIsEnable()) { draftsman->drawLaserSensor(&model->getTitanic()->getLasersSensors()); auto lasers = model->getTitanic()->getLasersSensors().getLasersValues(model->getElements()); view->setLasersValue(lasers[TITANIC_LASER_1_RANK], lasers[TITANIC_LASER_2_RANK], lasers[TITANIC_LASER_3_RANK]); } if (model->touching()) { view->stopTime(); view->touching(); } mutex.unlock(); } }
29.608696
104
0.616006
LaroyenneG
06b84fac02e1ec1dc1c4c1af6500c62a3c078af6
1,152
hpp
C++
examens/bruno_malenfant/final-2009/numero6/graphe.hpp
MFarradji/inf3105
93ffd6a237acbb67072d69fb5a8be02439f59a04
[ "MIT" ]
null
null
null
examens/bruno_malenfant/final-2009/numero6/graphe.hpp
MFarradji/inf3105
93ffd6a237acbb67072d69fb5a8be02439f59a04
[ "MIT" ]
null
null
null
examens/bruno_malenfant/final-2009/numero6/graphe.hpp
MFarradji/inf3105
93ffd6a237acbb67072d69fb5a8be02439f59a04
[ "MIT" ]
2
2020-10-01T14:16:56.000Z
2021-07-06T16:31:33.000Z
#include <string> #include <map> #include <vector> using namespace std; template <typename T> class Sommet { public: string identification; T information; }; template <typename T> class ListeAdjacence { private: vector< Sommet<T> > _liste; public: void ajouterElement(const Sommet<T>& a_sommet); bool appartient(const Sommet<T>& a_sommet) const; }; template <typename T> class Graphe { private: map< Sommet<T>, ListeAdjacence<T> > description; public: void ajouterArc(const Sommet<T>& a_sommet1, const Sommet<T>& a_sommet2); vector< Sommet<T> > voisins(const Sommet<T>& a_sommet) const; bool sontVoisins(const Sommet<T>& a_sommet1, const Sommet<T>& a_sommet2); }; template <typename T> bool ListeAdjacence<T>::appartient(const Sommet<T>& a_sommet) const { bool existe = false; for (int i = 0; i < _liste.size() && !existe; ++i) existe = _liste[i] == a_sommet; return existe; } template <typename T> bool Graphe<T>::sontVoisins(const Sommet<T>& a_sommet1, const Sommet<T>& a_sommet2) { return description[a_sommet1].appartient(a_sommet2) || description[a_sommet2].appartient(a_sommet1); }
25.6
102
0.702257
MFarradji
06b8e660c70f01c86587ba63911e2f8dfcf96771
556
cpp
C++
HW Peter/Zadacha 3.cpp
MihailTsvetogorov/SoftUni-Random-Dumb-Projects
c7eeedb4701a0b075ab0a86f91111a3875b29d45
[ "MIT" ]
null
null
null
HW Peter/Zadacha 3.cpp
MihailTsvetogorov/SoftUni-Random-Dumb-Projects
c7eeedb4701a0b075ab0a86f91111a3875b29d45
[ "MIT" ]
null
null
null
HW Peter/Zadacha 3.cpp
MihailTsvetogorov/SoftUni-Random-Dumb-Projects
c7eeedb4701a0b075ab0a86f91111a3875b29d45
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int a=1, c, A, B, b=1; cin>>A>>B; while (2+2==4) { c=a+b; a=b; b=c; if (c>=A&&c<=B)cout<<c<<" "; else if (c>B)break; } } /* C# using System; namespace Upr { class Zadacha3 { public static void Main() { int c; int A=int.Parse (Console.ReadLine()); int B=int.Parse (Console.ReadLine()); int b; while (true==true) { c=A+b; A=b; b=c; if (c<=B) Console.Write (c+ " "); else if (c>B) break; } } } }*/
13.9
41
0.471223
MihailTsvetogorov
06c086534fa771c6bb0d9e5798b5cd625686bb31
1,498
cpp
C++
kv/src/Signal.cpp
sobkulir/papyruskv
4802ec10121f5b8ce20fd7ab3c077d3d9ed0ccac
[ "BSD-3-Clause" ]
1
2018-05-13T02:29:05.000Z
2018-05-13T02:29:05.000Z
kv/src/Signal.cpp
sobkulir/papyruskv
4802ec10121f5b8ce20fd7ab3c077d3d9ed0ccac
[ "BSD-3-Clause" ]
null
null
null
kv/src/Signal.cpp
sobkulir/papyruskv
4802ec10121f5b8ce20fd7ab3c077d3d9ed0ccac
[ "BSD-3-Clause" ]
1
2021-12-10T19:31:37.000Z
2021-12-10T19:31:37.000Z
#include <papyrus/kv.h> #include "Signal.h" #include "Debug.h" #include "Platform.h" #include "Command.h" namespace papyruskv { Signal::Signal(Platform* platform) { dispatcher_ = platform->dispatcher(); pthread_mutex_init(&mutex_, NULL); } Signal::~Signal() { pthread_mutex_destroy(&mutex_); for (auto it = sems_.begin(); it != sems_.end(); ++it) { sem_destroy(it->second); delete it->second; } } int Signal::Notify(int signum, int* ranks, int count) { return dispatcher_->ExecuteSignal(signum, ranks, count); } int Signal::Wait(int signum, int* ranks, int count) { for (int i = 0; i < count; i++) { sem_t* sem = Semaphore(signum, ranks[i]); int ret = sem_wait(sem); if (ret != 0) { _error("ret[%d]", ret); return PAPYRUSKV_ERR; } } return PAPYRUSKV_OK; } int Signal::Action(int signum, int rank) { sem_t* sem = Semaphore(signum, rank); int ret = sem_post(sem); if (ret != 0) { _error("ret[%d]", ret); return PAPYRUSKV_ERR; } return PAPYRUSKV_OK; } sem_t* Signal::Semaphore(int signum, int rank) { sem_t* sem = NULL; unsigned long semid = (unsigned long) signum << 32 | rank; pthread_mutex_lock(&mutex_); if (sems_.count(semid) == 0) { sem = new sem_t; sem_init(sem, 0, 0); sems_[semid] = sem; } else sem = sems_[semid]; pthread_mutex_unlock(&mutex_); return sem; } } /* namespace papyruskv */
24.16129
62
0.594793
sobkulir
06c61a9941355b8855905b34b9fcbada41547848
1,885
cpp
C++
poly/staticpoly.cpp
ywen-cmd/C-Templates
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
[ "FSFAP" ]
11
2017-08-23T00:59:21.000Z
2021-02-20T20:36:09.000Z
poly/staticpoly.cpp
ywen-cmd/C-Templates
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
[ "FSFAP" ]
1
2017-03-15T15:17:16.000Z
2017-03-15T15:17:16.000Z
poly/staticpoly.cpp
ywen-cmd/C-Templates
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
[ "FSFAP" ]
8
2017-08-24T06:50:02.000Z
2021-02-20T20:36:12.000Z
/* The following code example is taken from the book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include "statichier.hpp" #include <vector> // draw any GeoObj template <typename GeoObj> void myDraw (GeoObj const& obj) { obj.draw(); // call draw() according to type of object } // process distance of center of gravity between two GeoObjs template <typename GeoObj1, typename GeoObj2> Coord distance (GeoObj1 const& x1, GeoObj2 const& x2) { Coord c = x1.center_of_gravity() - x2.center_of_gravity(); return c.abs(); // return coordinates as absolute values } // draw homogeneous collection of GeoObjs template <typename GeoObj> void drawElems (std::vector<GeoObj> const& elems) { for (unsigned i=0; i<elems.size(); ++i) { elems[i].draw(); // call draw() according to type of element } } int main() { Line l; Circle c, c1, c2; myDraw(l); // myDraw<Line>(GeoObj&) => Line::draw() myDraw(c); // myDraw<Circle>(GeoObj&) => Circle::draw() distance(c1,c2); // distance<Circle,Circle>(GeoObj1&,GeoObj2&) distance(l,c); // distance<Line,Circle>(GeoObj1&,GeoObj2&) // std::vector<GeoObj*> coll; // ERROR: no heterogeneous // collection possible std::vector<Line> coll; // OK: homogeneous collection possible coll.push_back(l); // insert line drawElems(coll); // draw all lines }
34.272727
72
0.645093
ywen-cmd
06c89660ac31418503bc8207c3c0be5b00604a41
3,520
cpp
C++
utils/process/deadline_killer_test.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
106
2015-01-20T14:49:12.000Z
2022-03-09T01:31:51.000Z
utils/process/deadline_killer_test.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
81
2015-02-23T23:23:41.000Z
2021-07-21T13:51:56.000Z
utils/process/deadline_killer_test.cpp
racktopsystems/kyua
1929dccc5cda71cddda71485094822d3c3862902
[ "BSD-3-Clause" ]
27
2015-09-30T20:33:34.000Z
2022-02-14T04:00:08.000Z
// Copyright 2015 The Kyua Authors. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "utils/process/deadline_killer.hpp" extern "C" { #include <signal.h> #include <unistd.h> } #include <cstdlib> #include <atf-c++.hpp> #include "utils/datetime.hpp" #include "utils/process/child.ipp" #include "utils/process/status.hpp" namespace datetime = utils::datetime; namespace process = utils::process; namespace { /// Body of a child process that sleeps and then exits. /// /// \tparam Seconds The delay the subprocess has to sleep for. template< int Seconds > static void child_sleep(void) { ::sleep(Seconds); std::exit(EXIT_SUCCESS); } } // anonymous namespace ATF_TEST_CASE_WITHOUT_HEAD(activation); ATF_TEST_CASE_BODY(activation) { std::auto_ptr< process::child > child = process::child::fork_capture( child_sleep< 60 >); datetime::timestamp start = datetime::timestamp::now(); process::deadline_killer killer(datetime::delta(1, 0), child->pid()); const process::status status = child->wait(); killer.unprogram(); datetime::timestamp end = datetime::timestamp::now(); ATF_REQUIRE(killer.fired()); ATF_REQUIRE(end - start <= datetime::delta(10, 0)); ATF_REQUIRE(status.signaled()); ATF_REQUIRE_EQ(SIGKILL, status.termsig()); } ATF_TEST_CASE_WITHOUT_HEAD(no_activation); ATF_TEST_CASE_BODY(no_activation) { std::auto_ptr< process::child > child = process::child::fork_capture( child_sleep< 1 >); datetime::timestamp start = datetime::timestamp::now(); process::deadline_killer killer(datetime::delta(60, 0), child->pid()); const process::status status = child->wait(); killer.unprogram(); datetime::timestamp end = datetime::timestamp::now(); ATF_REQUIRE(!killer.fired()); ATF_REQUIRE(end - start <= datetime::delta(10, 0)); ATF_REQUIRE(status.exited()); ATF_REQUIRE_EQ(EXIT_SUCCESS, status.exitstatus()); } ATF_INIT_TEST_CASES(tcs) { ATF_ADD_TEST_CASE(tcs, activation); ATF_ADD_TEST_CASE(tcs, no_activation); }
32.293578
74
0.731534
racktopsystems