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
0a3ca601ce0b54efde7d014701b01a91881f2edd
468
hpp
C++
experimental/Pomdog.Experimental/Skeletal2D/AnimationTimeInterval.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Skeletal2D/AnimationTimeInterval.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Skeletal2D/AnimationTimeInterval.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_ANIMATIONTIMEINTERVAL_DEA1AD60_HPP #define POMDOG_ANIMATIONTIMEINTERVAL_DEA1AD60_HPP #include <chrono> namespace Pomdog { using AnimationTimeInterval = std::chrono::duration<float, std::ratio<1>>; static_assert(sizeof(AnimationTimeInterval) == sizeof(float), ""); } // namespace Pomdog #endif // POMDOG_ANIMATIONTIMEINTERVAL_DEA1AD60_HPP
26
74
0.794872
bis83
0a3e53f06aaac98c9ef4c85f5069a14b30c576fb
327
cpp
C++
Brickjoon_Src/Bronze2/17608.cpp
waixxt3213/Brickjoon
66b38d7026febb090d47db1c8c56793ff1e54617
[ "MIT" ]
null
null
null
Brickjoon_Src/Bronze2/17608.cpp
waixxt3213/Brickjoon
66b38d7026febb090d47db1c8c56793ff1e54617
[ "MIT" ]
null
null
null
Brickjoon_Src/Bronze2/17608.cpp
waixxt3213/Brickjoon
66b38d7026febb090d47db1c8c56793ff1e54617
[ "MIT" ]
1
2020-10-10T14:35:59.000Z
2020-10-10T14:35:59.000Z
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(nullptr); int n,max{},i,r{}; cin >> n; stack<int> num; while(n--) { cin >> i; num.push(i); } while(num.empty()!=1) { if (max < num.top()) { max = num.top(); r++; } num.pop(); } cout << r; } // solve
11.678571
30
0.519878
waixxt3213
0a3f1d8d0c88247761e9cade374036be2a17fa3a
4,762
cc
C++
servlib/prophet/Dictionary.cc
delay-tolerant-networking/DTN2
1c12a9dea32c5cbae8c46db105012a2031f4161e
[ "Apache-2.0" ]
14
2016-06-27T19:28:23.000Z
2021-06-28T20:41:17.000Z
servlib/prophet/Dictionary.cc
delay-tolerant-networking/DTN2
1c12a9dea32c5cbae8c46db105012a2031f4161e
[ "Apache-2.0" ]
null
null
null
servlib/prophet/Dictionary.cc
delay-tolerant-networking/DTN2
1c12a9dea32c5cbae8c46db105012a2031f4161e
[ "Apache-2.0" ]
5
2019-09-23T11:07:39.000Z
2021-06-28T20:41:24.000Z
/* * Copyright 2007 Baylor University * * 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 "Dictionary.h" namespace prophet { // Reserve 0xffff as in-band error report const u_int16_t Dictionary::INVALID_SID = 0xffff; const std::string Dictionary::NULL_STR; Dictionary::Dictionary(const std::string& sender, const std::string& receiver) : sender_(sender), receiver_(receiver) {} Dictionary::Dictionary(const Dictionary& d) : sender_(d.sender_), receiver_(d.receiver_), ribd_(d.ribd_), rribd_(d.rribd_) {} u_int16_t Dictionary::find(const std::string& dest_id) const { // weed out the oddball if (dest_id == "") return INVALID_SID; // answer the easy ones before troubling map::find if (dest_id == sender_) return 0; if (dest_id == receiver_) return 1; // OK, now we fall back to the Google ribd::const_iterator i = (ribd::const_iterator) ribd_.find(dest_id); if (i != ribd_.end()) return (*i).second; // you fail it! return INVALID_SID; } const std::string& Dictionary::find(u_int16_t id) const { // answer the easy ones first if (id == 0) return sender_; if (id == 1) return receiver_; // fall back to reverse RIBD const_iterator i = (const_iterator) rribd_.find(id); if (i != rribd_.end()) return (*i).second; // no dice return NULL_STR; } u_int16_t Dictionary::insert(const std::string& dest_id) { // weed out the oddball if (dest_id == "") return INVALID_SID; // only assign once if (find(dest_id) != INVALID_SID) return INVALID_SID; // our dirty little secret: just increment the internal // SID by skipping the first two (implicit sender & receiver) u_int16_t sid = ribd_.size() + 2; // somehow the dictionary filled up!? if (sid == INVALID_SID) return INVALID_SID; bool res = assign(dest_id,sid); while (res == false) { res = assign(dest_id,++sid); if (sid == INVALID_SID) // sad times ... ? return INVALID_SID; } return sid; } bool Dictionary::assign(const std::string& dest_id, u_int16_t sid) { // weed out the oddball if (dest_id == "") return false; // these shouldn't get out of sync if (ribd_.size() != rribd_.size()) return false; // enforce sender/receiver definitions if (sid == 0) { if (sender_ == "" && dest_id != "") { sender_.assign(dest_id); return true; } return false; } else if (sid == 1) { if (receiver_ == "" && dest_id != "") { receiver_.assign(dest_id); return true; } return false; } else if (sid == INVALID_SID) { // what were you thinking? return false; } // attempt to insert into forward lookup bool res = ribd_.insert(ribd::value_type(dest_id,sid)).second; if ( ! res ) return false; // move on to reverse lookup res = rribd_.insert(rribd::value_type(sid,dest_id)).second; if ( ! res ) ribd_.erase(dest_id); // complain if we get out of sync return res && (ribd_.size() == rribd_.size()); } size_t Dictionary::guess_ribd_size(size_t RASsz) const { size_t retval = 0; for (const_iterator i = rribd_.begin(); i != rribd_.end(); i++) { retval += FOUR_BYTE_ALIGN( RASsz + (*i).second.length() ); } return retval; } void Dictionary::clear() { // wipe out everything from the dictionary sender_.assign(""); receiver_.assign(""); ribd_.clear(); rribd_.clear(); } void Dictionary::dump(BundleCore* core,const char* file,u_int line) const { if (core == NULL) return; core->print_log("dictionary", BundleCore::LOG_DEBUG, "%s(%u): 0 -> %s", file, line, sender_.c_str()); core->print_log("dictionary", BundleCore::LOG_DEBUG, "%s(%u): 1 -> %s", file, line, receiver_.c_str()); for (const_iterator i = rribd_.begin(); i != rribd_.end(); i++) core->print_log("dictionary", BundleCore::LOG_DEBUG, "%s(%u): %u -> %s", file, line, (*i).first, (*i).second.c_str()); } }; // namespace prophet
26.752809
78
0.609198
delay-tolerant-networking
0a401f23e819ff14a8ea53f85dfc66cd5dcaba64
899
hpp
C++
framework/frontend/parser/packrat/packrat_parser.hpp
aamshukov/frontend
6be5fea43b7776691034f3b4f56d318d7cdf18f8
[ "MIT" ]
2
2018-12-21T17:08:55.000Z
2018-12-21T17:08:57.000Z
framework/frontend/parser/packrat/packrat_parser.hpp
aamshukov/frontend
6be5fea43b7776691034f3b4f56d318d7cdf18f8
[ "MIT" ]
null
null
null
framework/frontend/parser/packrat/packrat_parser.hpp
aamshukov/frontend
6be5fea43b7776691034f3b4f56d318d7cdf18f8
[ "MIT" ]
null
null
null
//.............................. // UI Lab Inc. Arthur Amshukov . //.............................. #ifndef __PACKRAT_PARSER_H__ #define __PACKRAT_PARSER_H__ #pragma once BEGIN_NAMESPACE(frontend) USINGNAMESPACE(core) template <typename Token, typename TreeTraits> class packrat_parser : private recursive_descent_parser<Token, TreeTraits> { //?? Memoization table --> key<position(my_ptr), rule(my_id)> value<tree> public: using token_type = typename parser<Token, TreeTraits>::token_type; using tree_traits_type = typename parser<Token, TreeTraits>::tree_traits_type; using lexical_analyzer_type = typename parser<token_type, tree_traits_type>::lexical_analyzer_type; public: packrat_parser(const lexical_analyzer_type& lexical_analyzer); ~packrat_parser(); }; END_NAMESPACE #endif // __PACKRAT_PARSER_H__
29.966667
107
0.675195
aamshukov
0a455562cf02c6bdcea96a96beb45063a758632d
2,417
cpp
C++
ProvinceMapper/Source/Localization/LocalizationMapper.cpp
Idhrendur/provinceMapper
909baf41926263be9d844c69c85da04af34b19b3
[ "MIT" ]
10
2018-12-22T03:59:24.000Z
2021-03-20T02:11:05.000Z
ProvinceMapper/Source/Localization/LocalizationMapper.cpp
cetvrtak/provinceMapper
9e05003c5b11c7d252aa74cb6ef4bf9a953dd13b
[ "MIT" ]
24
2018-12-04T04:43:32.000Z
2021-10-16T16:23:06.000Z
ProvinceMapper/Source/Localization/LocalizationMapper.cpp
cetvrtak/provinceMapper
9e05003c5b11c7d252aa74cb6ef4bf9a953dd13b
[ "MIT" ]
14
2019-01-09T06:00:09.000Z
2021-09-02T10:26:55.000Z
#include "LocalizationMapper.h" #include "CsvScraper.h" #include "OSCompatibilityLayer.h" #include "YmlScraper.h" #include <fstream> void LocalizationMapper::scrapeSourceDir(const std::string& dirPath) { std::string actualPath; // our dirpath is a path to the map folder. locs are elsewhere. if (commonItems::DoesFolderExist(dirPath + "/../localisation")) // ck2, eu4, vic2 actualPath = dirPath + "/../localisation"; if (commonItems::DoesFolderExist(dirPath + "/../localization/english")) // ck3, imp actualPath = dirPath + "/../localization/english"; if (actualPath.empty()) return; for (const auto& fileName: commonItems::GetAllFilesInFolderRecursive(actualPath)) scrapeFile(actualPath + "/" + fileName, LocType::SOURCE); } void LocalizationMapper::scrapeTargetDir(const std::string& dirPath) { std::string actualPath; if (commonItems::DoesFolderExist(dirPath + "/../localisation")) // ck2, eu4, vic2 actualPath = dirPath + "/../localisation"; if (commonItems::DoesFolderExist(dirPath + "/../localization/english")) // ck3, imp actualPath = dirPath + "/../localization/english"; if (actualPath.empty()) return; for (const auto& fileName: commonItems::GetAllFilesInFolderRecursive(actualPath)) scrapeFile(actualPath + "/" + fileName, LocType::TARGET); } void LocalizationMapper::scrapeFile(const std::string& filePath, LocType locType) { if (filePath.find(".csv") != std::string::npos) { const auto locs = CsvScraper(filePath).getLocalizations(); if (locType == LocType::SOURCE) sourceLocalizations.insert(locs.begin(), locs.end()); else targetLocalizations.insert(locs.begin(), locs.end()); } else if (filePath.find(".yml") != std::string::npos) { const auto locs = YmlScraper(filePath).getLocalizations(); if (locType == LocType::SOURCE) sourceLocalizations.insert(locs.begin(), locs.end()); else targetLocalizations.insert(locs.begin(), locs.end()); } } std::optional<std::string> LocalizationMapper::getLocForSourceKey(const std::string& key) const { if (const auto& keyItr = sourceLocalizations.find(key); keyItr != sourceLocalizations.end()) return keyItr->second; else return std::nullopt; } std::optional<std::string> LocalizationMapper::getLocForTargetKey(const std::string& key) const { if (const auto& keyItr = targetLocalizations.find(key); keyItr != targetLocalizations.end()) return keyItr->second; else return std::nullopt; }
34.528571
95
0.724452
Idhrendur
0a489e288698d1d9f1cd35d2b001d9a9930d9c41
322
cpp
C++
QEverCloud/EventLoopFinisher.cpp
mgsxx/QEverCloud
3b031507d1ef03c994f35ff9b1e52849caadc01f
[ "MIT" ]
10
2015-01-25T16:46:58.000Z
2022-01-29T19:46:45.000Z
QEverCloud/EventLoopFinisher.cpp
mgsxx/QEverCloud
3b031507d1ef03c994f35ff9b1e52849caadc01f
[ "MIT" ]
1
2015-08-31T18:24:01.000Z
2015-09-05T18:12:06.000Z
QEverCloud/EventLoopFinisher.cpp
mgsxx/QEverCloud
3b031507d1ef03c994f35ff9b1e52849caadc01f
[ "MIT" ]
null
null
null
#include "EventLoopFinisher.h" /** @cond HIDDEN_SYMBOLS */ qevercloud::EventLoopFinisher::EventLoopFinisher(QEventLoop* loop, int exitCode, QObject *parent) : QObject(parent), loop_(loop), exitCode_(exitCode) { } void qevercloud::EventLoopFinisher::stopEventLoop() { loop_->exit(exitCode_); } /** @endcond */
20.125
99
0.723602
mgsxx
aea72851e869f096646664dfaec92a39999596cf
1,479
cpp
C++
Engine/src/Common/Manager.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
1
2021-07-24T03:10:38.000Z
2021-07-24T03:10:38.000Z
Engine/src/Common/Manager.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
null
null
null
Engine/src/Common/Manager.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
2
2021-05-11T10:47:37.000Z
2021-07-24T03:10:39.000Z
#include "Manager.h" #include "Component.h" #include "Entity.h" Manager::Manager(ManID id) : _manId(id) { } Manager::~Manager() { destroyAllComponents(); } int Manager::getCompID(const std::string& s) { auto e = enum_map_.find(s); if (e != enum_map_.end()) return e->second; return -1; } const std::list<Component*>& Manager::getComponents() { return _compsList; } const std::list<Component*>& Manager::getComponents() const { return _compsList; } void Manager::destroyAllComponents() { for (auto it = _compsList.begin(); it != _compsList.end(); it = _compsList.begin()) { delete* it; (*it) = nullptr; _compsList.erase(it); } } bool Manager::destroyComponent(Entity* ent, int compId) { auto it = _compsList.begin(); for (; it != _compsList.end(); it++) { if ((*it)->getEntity() == ent) { delete *it; _compsList.erase(it); return true; } } return false; } int Manager::getId() { return (int)_manId; } int Manager::getId() const { return (int)_manId; } void Manager::registerComponent(const std::string& name, int id, std::function<Component * ()> compConst) { enum_map_[name] = id; compsRegistry_[id] = compConst; } Component* Manager::create(const std::string& name, Entity* ent) { Component* comp = nullptr; auto it = compsRegistry_.find(enum_map_[name]); if (it != compsRegistry_.end()) comp = it->second(); if (comp != nullptr) { _compsList.push_back(comp); comp->setEntity(ent); return comp; } return nullptr; }
19.460526
105
0.665314
Proyecto03
aeb397536b73870e71e8a1314c1503e197e0c49c
3,029
cpp
C++
RX64M/rx64m_DMAC_sample/main.cpp
hirakuni45/RX
3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0
[ "BSD-3-Clause" ]
56
2015-06-04T14:15:38.000Z
2022-03-01T22:58:49.000Z
RX64M/rx64m_DMAC_sample/main.cpp
hirakuni45/RX
3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0
[ "BSD-3-Clause" ]
30
2019-07-27T11:03:14.000Z
2021-12-14T09:59:57.000Z
RX64M/rx64m_DMAC_sample/main.cpp
hirakuni45/RX
3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0
[ "BSD-3-Clause" ]
15
2017-06-24T11:33:39.000Z
2021-12-07T07:26:58.000Z
//=====================================================================// /*! @file @brief RX64M DMAC サンプル @n ・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/sci_io.hpp" #include "common/cmt_mgr.hpp" #include "common/fixed_fifo.hpp" #include "common/format.hpp" #include "common/delay.hpp" #include "common/command.hpp" namespace { typedef device::PORT<device::PORT0, device::bitpos::B7> LED; typedef device::cmt_mgr<device::CMT0> CMT; CMT cmt_; typedef utils::fixed_fifo<char, 128> BUFFER; typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI; SCI sci_; utils::command<256> cmd_; /// DMAC 終了割り込み class dmac_task { uint32_t count_; public: dmac_task() : count_(0) { } void operator() () { ++count_; } uint32_t get_count() const { return count_; } }; typedef device::dmac_mgr<device::DMAC0, dmac_task> DMAC_MGR; DMAC_MGR dmac_mgr_; char tmp_[256]; } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } char sci_getch(void) { return sci_.getch(); } void sci_puts(const char *str) { sci_.puts(str); } uint16_t sci_length(void) { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::system_io<>::boost_master_clock(); { // タイマー設定(60Hz) uint8_t int_level = 4; cmt_.start(60, int_level); } { // SCI 設定 uint8_t int_level = 2; sci_.start(115200, int_level); } utils::format("RX64M DMAC sample start\n"); cmd_.set_prompt("# "); LED::DIR = 1; { uint8_t intr_level = 4; dmac_mgr_.start(intr_level); } // copy 機能の確認 std::memset(tmp_, 0, sizeof(tmp_)); std::strcpy(tmp_, "ASDFGHJKLQWERTYUZXCVBNMIOP"); uint32_t copy_len = 16; dmac_mgr_.copy(&tmp_[0], &tmp_[128], copy_len, true); utils::format("DMA Copy: %d\n") % copy_len; while(dmac_mgr_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("CPY(%d): '%s'\n") % std::strlen(&tmp_[128]) % &tmp_[128]; utils::format("DMAC task: %d\n") % dmac_mgr_.at_task().get_count(); dmac_mgr_.fill(&tmp_[0], 4, copy_len, true); utils::format("DMA fill: %d\n") % copy_len; while(dmac_mgr_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("DMAC task: %d\n") % dmac_mgr_.at_task().get_count(); uint8_t val = 'Z'; copy_len = 31; dmac_mgr_.memset(&tmp_[0], val, copy_len, true); utils::format("DMA memset: %d\n") % copy_len; while(dmac_mgr_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("DMAC task: %d\n") % dmac_mgr_.at_task().get_count(); uint32_t cnt = 0; while(1) { cmt_.sync(); if(cmd_.service()) { } ++cnt; if(cnt >= 30) { cnt = 0; } LED::P = (cnt < 10) ? 0 : 1; } }
20.193333
73
0.610432
hirakuni45
aeb5802c328f0b8dbad33a35390b174a120c77cd
8,450
cpp
C++
src/fonts/SkTestScalerContext.cpp
Crawping/skia_custom
a7fd773196f844c1345a876bd14847c5992d27a3
[ "BSD-3-Clause" ]
null
null
null
src/fonts/SkTestScalerContext.cpp
Crawping/skia_custom
a7fd773196f844c1345a876bd14847c5992d27a3
[ "BSD-3-Clause" ]
null
null
null
src/fonts/SkTestScalerContext.cpp
Crawping/skia_custom
a7fd773196f844c1345a876bd14847c5992d27a3
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmap.h" #include "SkCanvas.h" #include "SkDescriptor.h" #include "SkGlyph.h" #include "SkMask.h" // #include "SkOTUtils.h" #include "SkScalerContext.h" #include "SkTestScalerContext.h" #include "SkTypefaceCache.h" class SkTestTypeface : public SkTypeface { public: SkTestTypeface(SkPaint::FontMetrics (*funct)(SkTDArray<SkPath*>& , SkTDArray<SkFixed>& ), SkTypeface::Style style) : SkTypeface(style, SkTypefaceCache::NewFontID(), false) { fMetrics = (*funct)(fPaths, fWidths); } virtual ~SkTestTypeface() { fPaths.deleteAll(); } void getAdvance(SkGlyph* glyph) { glyph->fAdvanceX = fWidths[SkGlyph::ID2Code(glyph->fID)]; glyph->fAdvanceY = 0; } void getFontMetrics(SkPaint::FontMetrics* metrics) { *metrics = fMetrics; } void getMetrics(SkGlyph* glyph) { glyph->fAdvanceX = fWidths[SkGlyph::ID2Code(glyph->fID)]; glyph->fAdvanceY = 0; } void getPath(const SkGlyph& glyph, SkPath* path) { *path = *fPaths[SkGlyph::ID2Code(glyph.fID)]; } protected: virtual SkScalerContext* onCreateScalerContext(const SkDescriptor* desc) const SK_OVERRIDE; virtual void onFilterRec(SkScalerContextRec* rec) const SK_OVERRIDE { rec->setHinting(SkPaint::kNo_Hinting); rec->fMaskFormat = SkMask::kA8_Format; } virtual SkAdvancedTypefaceMetrics* onGetAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::PerGlyphInfo , const uint32_t* glyphIDs, uint32_t glyphIDsCount) const SK_OVERRIDE { // pdf only SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics; info->fEmSize = 0; info->fLastGlyphID = SkToU16(onCountGlyphs() - 1); info->fStyle = 0; info->fFontName.set("SkiaTest"); info->fType = SkAdvancedTypefaceMetrics::kOther_Font; info->fItalicAngle = 0; info->fAscent = 0; info->fDescent = 0; info->fStemV = 0; info->fCapHeight = 0; info->fBBox = SkIRect::MakeEmpty(); return info; } virtual SkStream* onOpenStream(int* ttcIndex) const SK_OVERRIDE { SkASSERT(0); // don't expect to get here return NULL; } virtual void onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const SK_OVERRIDE { SkASSERT(0); // don't expect to get here } virtual int onCharsToGlyphs(const void* chars, Encoding encoding, uint16_t glyphs[], int glyphCount) const SK_OVERRIDE { SkASSERT(encoding == kUTF8_Encoding); for (int index = 0; index < glyphCount; ++index) { int ch = ((unsigned char*) chars)[index]; SkASSERT(ch < 0x7F); if (ch < 0x20) { glyphs[index] = 0; } else { glyphs[index] = ch - 0x20; } } return glyphCount; } virtual int onCountGlyphs() const SK_OVERRIDE { return fPaths.count(); } virtual int onGetUPEM() const SK_OVERRIDE { SkASSERT(0); // don't expect to get here return 1; } virtual SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const SK_OVERRIDE { SkString familyName("SkiaTest"); SkString language("und"); //undetermined SkASSERT(0); // incomplete return NULL; // return new SkOTUtils::LocalizedStrings_SingleName(familyName, language); } virtual int onGetTableTags(SkFontTableTag tags[]) const SK_OVERRIDE { return 0; } virtual size_t onGetTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const SK_OVERRIDE { return 0; } private: SkTDArray<SkPath* > fPaths; SkTDArray<SkFixed> fWidths; SkPaint::FontMetrics fMetrics; friend class SkTestScalerContext; }; SkTypeface* CreateTestTypeface(SkPaint::FontMetrics (*funct)(SkTDArray<SkPath*>& pathArray, SkTDArray<SkFixed>& widthArray), SkTypeface::Style style) { SkTypeface* test = SkNEW_ARGS(SkTestTypeface, (funct, style)); return test; } class SkTestScalerContext : public SkScalerContext { public: SkTestScalerContext(SkTestTypeface* face, const SkDescriptor* desc) : SkScalerContext(face, desc) , fFace(face) { fRec.getSingleMatrix(&fMatrix); this->forceGenerateImageFromPath(); } virtual ~SkTestScalerContext() { } protected: virtual unsigned generateGlyphCount() SK_OVERRIDE { return fFace->onCountGlyphs(); } virtual uint16_t generateCharToGlyph(SkUnichar uni) SK_OVERRIDE { uint8_t ch = (uint8_t) uni; SkASSERT(ch < 0x7f); uint16_t glyph; (void) fFace->onCharsToGlyphs((const void *) &ch, SkTypeface::kUTF8_Encoding, &glyph, 1); return glyph; } virtual void generateAdvance(SkGlyph* glyph) SK_OVERRIDE { fFace->getAdvance(glyph); SkVector advance; fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY), &advance); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); } virtual void generateMetrics(SkGlyph* glyph) SK_OVERRIDE { fFace->getMetrics(glyph); SkVector advance; fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY), &advance); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); SkPath path; fFace->getPath(*glyph, &path); path.transform(fMatrix); SkRect storage; const SkPaint paint; const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(), &storage, SkPaint::kFill_Style); SkIRect ibounds; newBounds.roundOut(&ibounds); glyph->fLeft = ibounds.fLeft; glyph->fTop = ibounds.fTop; glyph->fWidth = ibounds.width(); glyph->fHeight = ibounds.height(); glyph->fMaskFormat = SkMask::kARGB32_Format; } virtual void generateImage(const SkGlyph& glyph) SK_OVERRIDE { SkPath path; fFace->getPath(glyph, &path); SkBitmap bm; bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight), glyph.fImage, glyph.rowBytes()); bm.eraseColor(0); SkCanvas canvas(bm); canvas.translate(-SkIntToScalar(glyph.fLeft), -SkIntToScalar(glyph.fTop)); canvas.concat(fMatrix); SkPaint paint; paint.setAntiAlias(true); canvas.drawPath(path, paint); } virtual void generatePath(const SkGlyph& glyph, SkPath* path) SK_OVERRIDE { fFace->getPath(glyph, path); path->transform(fMatrix); } virtual void generateFontMetrics(SkPaint::FontMetrics* , SkPaint::FontMetrics* metrics) SK_OVERRIDE { fFace->getFontMetrics(metrics); if (metrics) { SkScalar scale = fMatrix.getScaleY(); metrics->fTop = SkScalarMul(metrics->fTop, scale); metrics->fAscent = SkScalarMul(metrics->fAscent, scale); metrics->fDescent = SkScalarMul(metrics->fDescent, scale); metrics->fBottom = SkScalarMul(metrics->fBottom, scale); metrics->fLeading = SkScalarMul(metrics->fLeading, scale); metrics->fAvgCharWidth = SkScalarMul(metrics->fAvgCharWidth, scale); metrics->fXMin = SkScalarMul(metrics->fXMin, scale); metrics->fXMax = SkScalarMul(metrics->fXMax, scale); metrics->fXHeight = SkScalarMul(metrics->fXHeight, scale); } } private: SkTestTypeface* fFace; SkMatrix fMatrix; }; SkScalerContext* SkTestTypeface::onCreateScalerContext(const SkDescriptor* desc) const { return SkNEW_ARGS(SkTestScalerContext, (const_cast<SkTestTypeface*>(this), desc)); }
33.665339
97
0.612189
Crawping
aec07d963f89313f25e3aa77fc735d723287fffe
2,419
hh
C++
src/solvers/mg/SpectrumGS.hh
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/solvers/mg/SpectrumGS.hh
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/solvers/mg/SpectrumGS.hh
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*-----------------------------------// /** * @file SpectrumGS.hh * @brief SpectrumGS class definition * @note Copyright (C) 2013 Jeremy Roberts */ //----------------------------------------------------------------------------// #ifndef detran_SPECTRUMGS_HH_ #define detran_SPECTRUMGS_HH_ #include "SpectrumBase.hh" namespace detran { /** * @class SpectrumGS * @brief Use the dominant mode from the G-S eigenvalue problem as spectrum * * Adams and Morel developed a two energy grid method for accelerating * Gauss-Seidell upscatter interations. The basic idea is to solve a * one group diffusion problem for the error, using a special energy shape * function to map between the one group and multigroup specta. The shape * they use is the eigenvector corresponding to the spectral radius of * the Gauss-Seidel method for a homogeneous infinite medium, defined * by * @f[ * (\mathbf{T} - \mathbf{S}_L - \mathbf{S}_D)^{-1} * \mathbf{S}_U \xi = \rho \xi \, . * * @f] * Here, @f$ \xi @f$ is the shape function of interest and is computed for * each group. Whereas Adams and Morel (and later, Evans, Clarno, and * Morel) collapse to just one group, here, we use the shape function to * map between the fine mesh and any allowable coarse energy grid. */ class SpectrumGS: public SpectrumBase { public: //--------------------------------------------------------------------------// // TYPEDEFS //--------------------------------------------------------------------------// //--------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //--------------------------------------------------------------------------// SpectrumGS(SP_input input, SP_material material, SP_mesh mesh); virtual ~SpectrumGS(){} /// Produce the edit region-dependent spectra virtual vec2_dbl spectrum(double keff = 1.0); protected: //--------------------------------------------------------------------------// // DATA //--------------------------------------------------------------------------// }; } // end namespace detran #endif /* detran_SPECTRUMGS_HH_ */ //----------------------------------------------------------------------------// // end of file SpectrumGS.hh //----------------------------------------------------------------------------//
32.253333
80
0.465068
baklanovp
aec0f3682ad0636eb87525d8697add36b54f56d4
7,982
cpp
C++
d3d11/setup/src/demo.cpp
tocchan/sd3_samples
1dcb4d7917629c910e1e36dd6c99b836fa03c4f8
[ "MIT" ]
3
2017-01-09T20:27:07.000Z
2017-01-18T23:03:13.000Z
d3d11/setup/src/demo.cpp
tocchan/guildhall_samples
1dcb4d7917629c910e1e36dd6c99b836fa03c4f8
[ "MIT" ]
null
null
null
d3d11/setup/src/demo.cpp
tocchan/guildhall_samples
1dcb4d7917629c910e1e36dd6c99b836fa03c4f8
[ "MIT" ]
null
null
null
#include "demo.h" #include "window.h" // D3D Stuff //------------------------------------------------------------------------ // DEFINES //------------------------------------------------------------------------ #define WINDOW_TITLE "D3D11 SETUP" #define WINDOW_RES_X (1280) #define WINDOW_RES_Y (720) #define RENDER_DEBUG typedef unsigned int uint; //------------------------------------------------------------------------ // MACROS //------------------------------------------------------------------------ #define SAFE_DELETE(ptr) if ((ptr) != nullptr) { delete ptr; ptr = nullptr } //------------------------------------------------------------------------ // Declare functions this demo uses //------------------------------------------------------------------------ void WindowCreate(); void WindowDestroy(); void WindowStep(); bool WindowIsOpen(); bool D3D11Setup(HWND hwnd); // Creates required D3D Objects void D3D11Cleanup(); // Cleans up D3D11 Objects void DemoRender(); // Does rendering for this demo void DemoRun(); // Demo setup and update loop //------------------------------------------------------------------------ // Code not pertinant to the topic of this demo is moved here // // I will be swapping things in and out as I add/remove steps. //------------------------------------------------------------------------ #include "demo.inl" //------------------------------------------------------------------------ // WINDOW STUFF //------------------------------------------------------------------------ // WINDOWS static HWND gHWND = NULL; //------------------------------------------------------------------------ void WindowCreate() { int const left_position = 100; int const top_position = 100; gHWND = CreateTheWindow( WINDOW_TITLE, left_position, top_position, WINDOW_RES_X, WINDOW_RES_Y ); } //------------------------------------------------------------------------ void WindowDestroy() { ::DestroyWindow(gHWND); gHWND = NULL; } //------------------------------------------------------------------------ bool WindowIsOpen() { return ::IsWindow(gHWND) == TRUE; } //------------------------------------------------------------------------ void WindowStep() { ProcessWindowMessages(gHWND); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // D3D11 STUFF //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Required Headers #include <d3d11.h> #include <DXGI.h> // DEBUG STUFF #include <dxgidebug.h> // #pragma comment( lib, "dxguid.lib" ) #pragma comment( lib, "d3d11.lib" ) #pragma comment( lib, "DXGI.lib" ) #define DX_SAFE_RELEASE(dx_resource) if ((dx_resource) != nullptr) { dx_resource->Release(); dx_resource = nullptr; } ID3D11Device *gD3DDevice = nullptr; ID3D11DeviceContext *gD3DContext = nullptr; IDXGISwapChain *gD3DSwapChain = nullptr; //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- bool D3D11Setup( HWND hwnd ) { // Creation Flags // For options, see; // https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=device_flags+%7C%3D+D3D11_CREATE_DEVICE_DEBUG%3B uint device_flags = 0U; #if defined(RENDER_DEBUG) device_flags |= D3D11_CREATE_DEVICE_DEBUG; // This flag fails unless we' do 11.1 (which we're not), and we query that // the adapter support its (which we're not). Just here to let you know it exists. // device_flags |= D3D11_CREATE_DEVICE_DEBUGGABLE; #endif // Setup our Swap Chain // For options, see; // https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=DXGI_SWAP_CHAIN_DESC DXGI_SWAP_CHAIN_DESC swap_desc; memset( &swap_desc, 0, sizeof(swap_desc) ); // fill the swap chain description struct swap_desc.BufferCount = 2; // two buffers (one front, one back?) swap_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT // how swap chain is to be used | DXGI_USAGE_BACK_BUFFER; swap_desc.OutputWindow = hwnd; // the window to be copied to on present swap_desc.SampleDesc.Count = 1; // how many multisamples (1 means no multi sampling) // Default options. swap_desc.Windowed = TRUE; // windowed/full-screen mode swap_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color swap_desc.BufferDesc.Width = WINDOW_RES_X; swap_desc.BufferDesc.Height = WINDOW_RES_Y; // Actually Create HRESULT hr = ::D3D11CreateDeviceAndSwapChain( nullptr, // Adapter, if nullptr, will use adapter window is primarily on. D3D_DRIVER_TYPE_HARDWARE, // Driver Type - We want to use the GPU (HARDWARE) nullptr, // Software Module - DLL that implements software mode (we do not use) device_flags, // device creation options nullptr, // feature level (use default) 0U, // number of feature levels to attempt D3D11_SDK_VERSION, // SDK Version to use &swap_desc, // Description of our swap chain &gD3DSwapChain, // Swap Chain we're creating &gD3DDevice, // [out] The device created nullptr, // [out] Feature Level Acquired &gD3DContext ); // Context that can issue commands on this pipe. // SUCCEEDED & FAILED are macros provided by Windows to checking // the results. Almost every D3D call will return one - be sure to check it. return SUCCEEDED(hr); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void D3D11Cleanup() { DX_SAFE_RELEASE(gD3DSwapChain); DX_SAFE_RELEASE(gD3DContext); DX_SAFE_RELEASE(gD3DDevice); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void DemoRender() { // Get the back buffer ID3D11Texture2D *back_buffer = nullptr; gD3DSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&back_buffer); // Get a render target view of this // NOTE: This could be cached off and stored instead of creating // a new one each frame. It is fairly cheap to do though. ID3D11RenderTargetView *rtv = nullptr; gD3DDevice->CreateRenderTargetView( back_buffer, nullptr, &rtv ); DX_SAFE_RELEASE( back_buffer ); // I'm done using this - so release my hold on it (does not destroy it!) // Clear the buffer. float clear_color[4] = { 0.004f, 0.475f, 0.435f, 1.0f }; gD3DContext->ClearRenderTargetView( rtv, clear_color ); DX_SAFE_RELEASE( rtv ); // done with the view - can release it (if you save it frame to frame, skip this step) // We're done rendering, so tell the swap chain they can copy the back buffer to the front (desktop/window) buffer gD3DSwapChain->Present( 0, // Sync Interval, set to 1 for VSync 0 ); // Present flags, see; // https://msdn.microsoft.com/en-us/library/windows/desktop/bb509554(v=vs.85).aspx } //------------------------------------------------------------------------ // DEMO ENTRY POINT //------------------------------------------------------------------------ void DemoRun() { // Need a Window so I have something to render to. WindowCreate(); // Setup D3D11 - will crash if this fails (demo contains no error checking) D3D11Setup(gHWND); // While this window is open, process messages, and do other game processing while (WindowIsOpen()) { WindowStep(); // Do other stuff. DemoRender(); } // This is overkill - since it was destroyed before it got here // but just want it to match the create above (and more match what this looks // like when it becomes an class) D3D11Cleanup(); WindowDestroy(); }
36.78341
140
0.527311
tocchan
aec1b457b24fa103552f0d01402ddcb71222f4ad
11,427
cpp
C++
CodeGeneration/concrete/PackCPP/impl/SimpleMDGenerator.cpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
CodeGeneration/concrete/PackCPP/impl/SimpleMDGenerator.cpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
CodeGeneration/concrete/PackCPP/impl/SimpleMDGenerator.cpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
#include "SimpleMDGenerator.hpp" namespace dsg { namespace generator { SimpleMDGenerator::SimpleMDGenerator() { Source_R2 = CreateFile_R2; CreateFile_R2 = (CreateClassDescription << line_g(1) << CreateClassReference) [ent0, entN]; CreateClassDescription = str_g("# ") << UEntity_R2 << line_g(1) << ent_g(getEntityCommentHandler()); CreateClassReference = line_g(1) << str_g("# Référence") << CreateDefaultConstructorReference_R2 << CreateConstructorReference_R2 << CreateAttributeGetterReference_R2 << CreateAttributeRefGetterReference_R2 << CreateAttributeSetterReference_R2 << CreateAttributeIsNullReference_R2 << CreateAttributeEraseReference_R2 << CreateAttributeListEraseReference_R2 << CreateAttributeListInsertReference_R2 << CreateAttributeListAtReference_R2 << CreateAttributeListClearReference_R2 << CreateAttributeListEmptyReference_R2 << CreateAttributeListSize_R2; CreateDefaultConstructorReference_R2 = line_g(1) << str_g("## Constructeur ") << UEntity_R2 << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Description*" << line_g(1) << "* Crée une instance de la classe " << UEntity_R2 << "." << line_g(1) << "```" << line_g(1) << "var = new " << UEntity_R2 << "();" << line_g(1) << "```" << line_g(1); CreateConstructorReference_R2 = line_g(1) << str_g("## Constructeur ") << UEntity_R2 << line_g(1) << "*Paramètres*" << ListEntityParam_R2 ( line_g(1) << "* " << AttributeInterpreterTypeName_R2 << " : La valeur de la colonne " << LAttribute_R2 << "." ) << line_g(2) << "*Description*" << line_g(1) << "* Crée une instance de la classe " << UEntity_R2 << "." << line_g(1) << "```" << line_g(1) << "var = new " << UEntity_R2 << "(" << ListEntityParam_R2 ( LAttribute_R2 << ~-(str_g(", ")) ) << ");" << line_g(1) << "```" << line_g(1); CreateAttributeGetterReference_R2 = (line_g(1) << str_g("## Méthode ") << UAttribute_R2 << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* " << AttributeInterpreterTypeName_R2 << " : La colonne " << LAttribute_R2 << "." << line_g(2) << "*Description*" << line_g(1) << "* Retourne la colonne " << UAttribute_R2 << "." << line_g(1) << "```" << line_g(1) << "val = var." << UAttribute_R2 << ";" << line_g(1) << "```" << line_g(1)) [!If_IsREF_R2][attr0, attrN]; CreateAttributeRefGetterReference_R2 = (line_g(1) << str_g("## Méthode ") << UAttribute_R2 << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* " << AttributeInterpreterTypeName_R2 << " : La colonne " << LAttribute_R2 << "." << line_g(2) << "*Description*" << line_g(1) << "* Retourne la colonne " << UAttribute_R2 << "." << line_g(1) << "```" << line_g(1) << LAttribute_R2 << " = var." << UAttribute_R2 << ";" << line_g(1) << "```" << line_g(1)) [If_IsREF_R2][attr0, attrN]; CreateAttributeSetterReference_R2 = (line_g(1) << str_g("## Méthode ") << UAttribute_R2 << line_g(1) << "*Paramètres*" << line_g(1) << "* " << AttributeInterpreterTypeName_R2 << " : La valeur de la colonne " << LAttribute_R2 << "." << line_g(2) << "*Retour*" << line_g(1) << "* None." << line_g(2) << "*Description*" << line_g(1) << "* Définit la colonne " << LAttribute_R2 << "." << line_g(1) << "```" << line_g(1) << "var." << UAttribute_R2 << "(" << LAttribute_R2 << ");" << line_g(1) << "```" << line_g(1)) [If_IsWriteAttribute_R2] [attr0, attrN]; CreateAttributeIsNullReference_R2 = (line_g(1) << str_g("## Méthode Has") << UAttribute_R2 << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* Bool : Une valeur est définie pour la colonne " << LAttribute_R2 << "." << line_g(2) << "*Description*" << line_g(1) << "* Indique si la colonne " << UAttribute_R2 << " a une valeur définie." << line_g(1) << "```" << line_g(1) << "val = var.Has" << UAttribute_R2 << ";" << line_g(1) << "```" << line_g(1)) [If_IsREF_R2][attr0, attrN]; CreateAttributeEraseReference_R2 = (line_g(1) << str_g("## Méthode remove") << UAttribute_R2 << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* None." << line_g(2) << "*Description*" << line_g(1) << "* Supprime la valeur définie pour la colonne " << LAttribute_R2 << "." << line_g(1) << "```" << line_g(1) << "var." << UAttribute_R2 << " = null;" << line_g(1) << "```" << line_g(1)) [If_IsREF_R2][attr0, attrN]; CreateAttributeListEraseReference_R2 = ListRelationN_R2 ( line_g(1) << str_g("## Méthode remove") << URelationNName_R2 << "s" << line_g(1) << "*Paramètres*" << line_g(1) << "* Numeric : La position de l'élément à supprimer dans la liste." << line_g(2) << "*Retour*" << line_g(1) << "* None." << line_g(2) << "*Description*" << line_g(1) << "* Supprime l'élément à la position *n* dans la liste de " << URelationNName_R2 << "s." << line_g(1) << "```" << line_g(1) << "var." << URelationNName_R2 << "s(0) = null;" << line_g(1) << "```" << line_g(1) ); CreateAttributeListInsertReference_R2 = ListRelationN_R2 ( line_g(1) << str_g("## Méthode ") << URelationNName_R2 << "s" << line_g(1) << "*Paramètres*" << line_g(1) << "* Numeric : La position de l'élément à insérer dans la liste." << line_g(1) << "* " << URelationN_R2 << " : L'élément à insérer dans la liste." << line_g(2) << "*Retour*" << line_g(1) << "* None." << line_g(2) << "*Description*" << line_g(1) << "* Insère un élément à la position *n* dans la liste de " << URelationNName_R2 << "s." << line_g(1) << "```" << line_g(1) << "var." << URelationNName_R2 << "s(0) = " << LRelationNName_R2 << ";" << line_g(1) << "```" << line_g(1) ); CreateAttributeListAtReference_R2 = ListRelationN_R2 ( line_g(1) << str_g("## Méthode ") << URelationNName_R2 << "s" << line_g(1) << "*Paramètres*" << line_g(1) << "* Numeric : La position de l'élément dans la liste." << line_g(2) << "*Retour*" << line_g(1) << "* " << URelationN_R2 << " : L'élément dans la liste." << line_g(2) << "*Description*" << line_g(1) << "* Retourne l'élément à la position *n* dans la liste de " << URelationNName_R2 << "s." << line_g(1) << "```" << line_g(1) << "val = var." << URelationNName_R2 << "s(0);" << line_g(1) << "```" << line_g(1) ); CreateAttributeListClearReference_R2 = ListRelationN_R2 ( line_g(1) << str_g("## Méthode Clear") << URelationNName_R2 << "s" << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* None." << line_g(2) << "*Description*" << line_g(1) << "* Supprime tous les éléments de liste." << line_g(1) << "```" << line_g(1) << "var.Clear" << URelationNName_R2 << "s();" << line_g(1) << "```" << line_g(1) ); CreateAttributeListEmptyReference_R2 = ListRelationN_R2 ( line_g(1) << str_g("## Méthode Has") << URelationNName_R2 << "s" << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* Bool : True si la liste n'est pas vide, False sinon." << line_g(2) << "*Description*" << line_g(1) << "* Indique si la liste n'est pas vide." << line_g(1) << "```" << line_g(1) << "val = var.Has" << URelationNName_R2 << "s();" << line_g(1) << "```" << line_g(1) ); CreateAttributeListSize_R2 = ListRelationN_R2 ( line_g(1) << str_g("## Méthode ") << URelationNName_R2 << "sCount" << line_g(1) << "*Paramètres*" << line_g(1) << "* None." << line_g(2) << "*Retour*" << line_g(1) << "* Numeric : Le nombre d'éléments contenus dans la liste." << line_g(2) << "*Description*" << line_g(1) << "* Retourne le nombre d'élément contenus dans la liste." << line_g(1) << "```" << line_g(1) << "val = var." << URelationNName_R2 << "sCount();" << line_g(1) << "```" << line_g(1) ); } } }
47.6125
133
0.403693
tedi21
aed9c56612c4cfc6625a62898aa11cd4807e4ede
6,129
cpp
C++
Engine/dragwidget.cpp
vadkasevas/BAS
657f62794451c564c77d6f92b2afa9f5daf2f517
[ "MIT" ]
302
2016-05-20T12:55:23.000Z
2022-03-29T02:26:14.000Z
Engine/dragwidget.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
9
2016-07-21T09:04:50.000Z
2021-05-16T07:34:42.000Z
Engine/dragwidget.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
113
2016-05-18T07:48:37.000Z
2022-02-26T12:59:39.000Z
#if QT_VERSION >= 0x050000 #include <QtWidgets> #endif #include <QLabel> #include <QDragEnterEvent> #include <QPainter> #include <QMimeData> #include <QDrag> #include "every_cpp.h" #include <QScrollArea> #include "dragwidget.h" DragWidget::DragWidget(QWidget *parent) : QFrame(parent) { this->setContentsMargins(0,0,0,0); this->setMinimumHeight(100); QVBoxLayout *MainLayout = new QVBoxLayout(this); QScrollArea *ScrollArea = new QScrollArea(this); ScrollArea->setStyleSheet("QScrollArea{border: 1px solid gray; border-radius: 4px; padding: 1px;}"); MainLayout->addWidget(ScrollArea); MainLayout->setContentsMargins(0,0,0,0); ScrollArea->setContentsMargins(0,0,0,0); Data = new QWidget(ScrollArea); Layout = new QVBoxLayout(Data); Layout->setSizeConstraint(QLayout::SetMinAndMaxSize); Data->setLayout(Layout); ScrollArea->setWidget(Data); //setFrameStyle(QFrame::Sunken | QFrame::StyledPanel); setAcceptDrops(true); setMinimumWidth(280); SetData(QStringList()); } QStringList DragWidget::GetData() { QStringList res; int index = 0; while(index < Layout->count()) { QLayoutItem* item = Layout->itemAt(index); if(item) { if(item->widget()) { QLabel *label = qobject_cast<QLabel *>(item->widget()); if(label) { res.append(label->text()); } } } index++; } return res; } void DragWidget::SetData(const QStringList& list) { Clear(); foreach(QString item, list) { QLabel *label = new QLabel(Data); label->setText(item); label->show(); label->setMouseTracking(true); QFont font; font.setPointSize(9); label->setFont(font); label->setCursor(QCursor(Qt::OpenHandCursor)); label->setAttribute(Qt::WA_DeleteOnClose); Layout->addWidget(label); } Data->updateGeometry(); Data->update(); dynamic_cast<QBoxLayout *>(Layout)->addSpacerItem(new QSpacerItem(0,0,QSizePolicy::Expanding,QSizePolicy::Expanding)); } void DragWidget::Clear() { while(Layout->count()>0) { QLayoutItem* item = Layout->itemAt(0); if(item) { Layout->removeItem( item ); QWidget* widget = item->widget(); if(widget) { Layout->removeWidget(widget); delete widget; } delete item; } } } void DragWidget::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("application/x-dnditemdata")) { if (event->source() == this) { event->setDropAction(Qt::MoveAction); event->accept(); } else { event->acceptProposedAction(); } } else { event->ignore(); } } void DragWidget::dragMoveEvent(QDragMoveEvent *event) { if (event->mimeData()->hasFormat("application/x-dnditemdata")) { if (event->source() == this) { event->setDropAction(Qt::MoveAction); event->accept(); } else { event->acceptProposedAction(); } } else { event->ignore(); } } void DragWidget::dropEvent(QDropEvent *event) { if (event->mimeData()->hasFormat("application/x-dnditemdata")) { QByteArray itemData = event->mimeData()->data("application/x-dnditemdata"); QDataStream dataStream(&itemData, QIODevice::ReadOnly); QString text; QPoint offset; dataStream >> text >> offset; QLabel *newIcon = new QLabel(this); newIcon->setText(text); int index = 0; while(index < Layout->count()) { QLayoutItem* item = Layout->itemAt(index); if(item) { if(!item->widget()) { break; } if(!((event->pos() - offset).y() > item->widget()->pos().y())) { break; } } index++; } dynamic_cast<QBoxLayout *>(Layout)->insertWidget(index,newIcon); QFont font; font.setPointSize(9); newIcon->setFont(font); newIcon->show(); newIcon->setMouseTracking(true); newIcon->setCursor(QCursor(Qt::OpenHandCursor)); newIcon->setAttribute(Qt::WA_DeleteOnClose); if (event->source() == this) { event->setDropAction(Qt::MoveAction); event->accept(); } else { event->acceptProposedAction(); } emit ChangedDragWidget(); } else { event->ignore(); } } void DragWidget::mousePressEvent(QMouseEvent *event) { QLabel *child = dynamic_cast<QLabel*>(childAt(event->pos())); if (!child) return; QSize size = child->size(); QRegion region = QRegion(0,0,size.width(),size.height()); QPixmap pixmap(size); child->render(&pixmap, QPoint(),region ); QString text = qobject_cast<QLabel *>(child)->text(); QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); dataStream << text << QPoint(event->pos() - child->pos()); QMimeData *mimeData = new QMimeData; mimeData->setData("application/x-dnditemdata", itemData); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); drag->setPixmap(pixmap); drag->setHotSpot(QPoint(-10,-10)); QPixmap tempPixmap = pixmap; QPainter painter; painter.begin(&tempPixmap); painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127)); painter.end(); child->setPixmap(tempPixmap); Qt::DropAction action = drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction); switch(action) { case Qt::MoveAction: child->close(); break; case Qt::CopyAction: child->close(); break; case Qt::IgnoreAction: child->show(); child->setText(text); break; } }
24.225296
122
0.566161
vadkasevas
aedbb0e0fe99e4a60d0c5df59e4e10ba624b067b
2,172
cpp
C++
src/Video/LowLevelRenderer/OpenGL/OpenGLBuffer.cpp
Chainsawkitten/HymnToBeauty
b0c431869fee4314eca2aee65d93e78f7e707f10
[ "MIT" ]
10
2019-01-13T05:51:54.000Z
2022-02-02T14:34:47.000Z
src/Video/LowLevelRenderer/OpenGL/OpenGLBuffer.cpp
Chainsawkitten/HymnToBeauty
b0c431869fee4314eca2aee65d93e78f7e707f10
[ "MIT" ]
46
2016-12-30T11:14:25.000Z
2021-09-04T12:50:40.000Z
src/Video/LowLevelRenderer/OpenGL/OpenGLBuffer.cpp
Chainsawkitten/HymnToBeauty
b0c431869fee4314eca2aee65d93e78f7e707f10
[ "MIT" ]
4
2017-09-28T09:00:58.000Z
2019-10-22T05:28:32.000Z
#include "OpenGLBuffer.hpp" #include <assert.h> #include <cstddef> namespace Video { OpenGLBuffer::OpenGLBuffer(Buffer::BufferUsage bufferUsage, unsigned int size, const void* data) : Buffer(bufferUsage) { assert(size > 0); this->size = size; // Map high-level buffer usage to OpenGL buffer type and usage. GLenum usage; switch (bufferUsage) { case BufferUsage::VERTEX_BUFFER_STATIC: target = GL_ARRAY_BUFFER; usage = GL_STATIC_DRAW; break; case BufferUsage::VERTEX_BUFFER_DYNAMIC: target = GL_ARRAY_BUFFER; usage = GL_DYNAMIC_DRAW; break; case BufferUsage::INDEX_BUFFER_STATIC: target = GL_ELEMENT_ARRAY_BUFFER; usage = GL_STATIC_DRAW; break; case BufferUsage::INDEX_BUFFER_DYNAMIC: target = GL_ELEMENT_ARRAY_BUFFER; usage = GL_DYNAMIC_DRAW; break; case BufferUsage::UNIFORM_BUFFER: target = GL_UNIFORM_BUFFER; usage = GL_DYNAMIC_DRAW; break; case BufferUsage::STORAGE_BUFFER: target = GL_SHADER_STORAGE_BUFFER; usage = GL_DYNAMIC_DRAW; break; case BufferUsage::VERTEX_STORAGE_BUFFER: target = GL_SHADER_STORAGE_BUFFER; usage = GL_DYNAMIC_DRAW; break; } // Create buffer. glGenBuffers(1, &buffer); glBindBuffer(target, buffer); glBufferData(target, static_cast<GLsizeiptr>(size), (data != nullptr) ? data : NULL, usage); glBindBuffer(target, 0); } OpenGLBuffer::~OpenGLBuffer() { glDeleteBuffers(1, &buffer); } void OpenGLBuffer::Write(const void* data) { assert(data != nullptr); assert(GetBufferUsage() == BufferUsage::VERTEX_BUFFER_DYNAMIC || GetBufferUsage() == BufferUsage::INDEX_BUFFER_DYNAMIC || GetBufferUsage() == BufferUsage::UNIFORM_BUFFER || GetBufferUsage() == BufferUsage::STORAGE_BUFFER); glBindBuffer(target, buffer); glBufferSubData(target, 0, size, data); glBindBuffer(target, 0); } unsigned int OpenGLBuffer::GetSize() const { return size; } GLuint OpenGLBuffer::GetBufferID() const { return buffer; } GLenum OpenGLBuffer::GetTarget() const { return target; } }
27.15
226
0.677716
Chainsawkitten
aedc429bf82edd33067c4288ddd0c251b9e4a389
653
cpp
C++
Cpp/DSA-gfg/arrays/maxSumOfK-consectiveEle.cpp
uday256071/DataStructures-and-Algorithms
d5740a27a8e4141616307ec3771bc7ad95ff9f72
[ "MIT" ]
null
null
null
Cpp/DSA-gfg/arrays/maxSumOfK-consectiveEle.cpp
uday256071/DataStructures-and-Algorithms
d5740a27a8e4141616307ec3771bc7ad95ff9f72
[ "MIT" ]
null
null
null
Cpp/DSA-gfg/arrays/maxSumOfK-consectiveEle.cpp
uday256071/DataStructures-and-Algorithms
d5740a27a8e4141616307ec3771bc7ad95ff9f72
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; //Sliding window technique int maxSumKconsecutiveEle(vector<int> v,int k){ int p1,p2,maxSum=0,sum =0; int n= v.size(); if(n<k || k==0) return 0; for(int i=0;i<k;i++){ sum+= v.at(i); } for(int i=1;i<n-k;i++){ sum= sum +v.at(i+k-1)-v.at(i-1); maxSum = max(sum,maxSum); // cout << i << " -> "<<sum <<" "<<maxSum << endl; } return maxSum; } int main(){ // https://ide.geeksforgeeks.org/QSMe98qHhN vector<int> v = {5,-2,8,6,4,12,-8,3}; cout <<"Maximum sum of K consecutive element = "<< maxSumKconsecutiveEle(v,3); }
23.321429
82
0.548239
uday256071
aedcb6f7071bfbfd16a56143c004f9da3a479b6c
3,757
cpp
C++
src/atta/fileSystem/fileManager.cpp
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-06-18T00:48:13.000Z
2021-06-18T00:48:13.000Z
src/atta/fileSystem/fileManager.cpp
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
6
2021-03-11T21:01:27.000Z
2021-09-06T19:41:46.000Z
src/atta/fileSystem/fileManager.cpp
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-09-04T19:54:41.000Z
2021-09-04T19:54:41.000Z
//-------------------------------------------------- // Atta File System // fileManager.cpp // Date: 2021-09-05 // By Breno Cunha Queiroz //-------------------------------------------------- #include <atta/fileSystem/fileManager.h> #include <atta/fileSystem/watchers/nullFileWatcher.h> #include <atta/fileSystem/watchers/linuxFileWatcher.h> #include <atta/eventSystem/eventManager.h> #include <atta/eventSystem/events/projectOpenEvent.h> #include <atta/eventSystem/events/projectCloseEvent.h> #include <atta/componentSystem/componentManager.h> #include <atta/cmakeConfig.h> namespace atta { void FileManager::startUpImpl() { _project = nullptr; _projectSerializer = nullptr; #ifdef ATTA_OS_LINUX _fileWatcher = std::static_pointer_cast<FileWatcher>(std::make_shared<LinuxFileWatcher>()); #else _fileWatcher = std::static_pointer_cast<FileWatcher>(std::make_shared<NullFileWatcher>()); #endif } void FileManager::shutDownImpl() { } bool FileManager::openProjectImpl(fs::path projectFile, bool newProject) { // Check valid project file if(!newProject && !fs::exists(projectFile)) { LOG_WARN("FileManager", "Could not find file [w]$0[]", fs::absolute(projectFile)); return false; } if(projectFile.extension() != ".atta") { LOG_WARN("FileManager", "Project file must have .atta extension [w]$0[]", fs::absolute(projectFile)); return false; } // Close project if still open (save if not new project) // When opening a new project we save the changes only to the new project if(_project != nullptr) closeProjectImpl(!newProject); // Update project _project = std::make_shared<Project>(projectFile); _projectSerializer = std::make_shared<ProjectSerializer>(_project); if(!newProject) _projectSerializer->deserialize();// Deserialize already created project file else _projectSerializer->serialize();// Create new project file // Watch project directory file changes _fileWatcher->addWatch(_project->getDirectory()); ProjectOpenEvent e; EventManager::publish(e); return true; } bool FileManager::isProjectOpenImpl() const { return _project != nullptr; } void FileManager::closeProjectImpl(bool save) { if(save) { saveProjectImpl(); ComponentManager::clear(); } if(_project) _fileWatcher->removeWatch(_project->getDirectory()); _project.reset(); _projectSerializer.reset(); ProjectCloseEvent e; EventManager::publish(e); } void FileManager::saveProjectImpl() { if(_projectSerializer) _projectSerializer->serialize(); } void FileManager::saveNewProjectImpl(fs::path projectFile) { openProjectImpl(projectFile, true); } // TODO remove void FileManager::updateImpl() { _fileWatcher->update(); } fs::path FileManager::solveResourcePathImpl(fs::path relativePath) { if(_project != nullptr) return _project->solveResourcePath(relativePath); else { fs::path full = fs::path(ATTA_DIR)/"resources"/relativePath; if(fs::exists(full)) return full; else return fs::path(); } } std::vector<fs::path> FileManager::getResourcePathsImpl() const { if(_project != nullptr) return _project->getResourceRootPaths(); else return { fs::path(ATTA_DIR)/"resources" }; } }
28.037313
113
0.602875
Brenocq
aedecdbaf6d76b8b02e9d9444950b32f54717522
974
hpp
C++
include/DirectDrawSurfaceWriter.hpp
antenous/image
7743a31d87bae1b76efdd4023f21d0f861093057
[ "BSD-3-Clause" ]
null
null
null
include/DirectDrawSurfaceWriter.hpp
antenous/image
7743a31d87bae1b76efdd4023f21d0f861093057
[ "BSD-3-Clause" ]
null
null
null
include/DirectDrawSurfaceWriter.hpp
antenous/image
7743a31d87bae1b76efdd4023f21d0f861093057
[ "BSD-3-Clause" ]
null
null
null
/* * @file include/DirectDrawSurfaceWriter.hpp * DirectDrawSurfaceWriter.hpp * * Created on: Dec 17, 2017 * Author: Antero Nousiainen */ #ifndef DIRECTDRAWSURFACEWRITER_HPP_ #define DIRECTDRAWSURFACEWRITER_HPP_ #include <ostream> #include "DirectDrawSurface.hpp" namespace image { class DirectDrawSurfaceWriter { public: class BadFile; class InvalidType; /** Write the direct draw surface image to the stream @throw BadFile if unable to write to the stream @throw InvalidType if the image is not a valid direct draw surface image */ static void write(std::ostream & to, const DirectDrawSurface & dds); }; class DirectDrawSurfaceWriter::BadFile : public std::invalid_argument { public: BadFile(); }; class DirectDrawSurfaceWriter::InvalidType : public std::invalid_argument { public: InvalidType(); }; } #endif
19.48
84
0.654004
antenous
aee2d6ed45a3c7ca1f414163797a051feb912b59
255
cpp
C++
smile-clinic/src/enum/PessoaTipoEnum.cpp
hjCostaBR/hjcostabr_smile-clinic
bb74f77f5a4b6a8ad648dc8a752306351e5de01f
[ "MIT" ]
null
null
null
smile-clinic/src/enum/PessoaTipoEnum.cpp
hjCostaBR/hjcostabr_smile-clinic
bb74f77f5a4b6a8ad648dc8a752306351e5de01f
[ "MIT" ]
null
null
null
smile-clinic/src/enum/PessoaTipoEnum.cpp
hjCostaBR/hjcostabr_smile-clinic
bb74f77f5a4b6a8ad648dc8a752306351e5de01f
[ "MIT" ]
null
null
null
/** * File: PessoaTipoEnum.cpp * Enum: PessoaTipoEnum * Author: hjCostaBR * * Enum de tipos de pessoa, no sistema * Smile Clinic */ #ifndef PESSOA_TIPO_CPP #define PESSOA_TIPO_CPP enum PessoaTipoEnum { FUNCIONARIO = 0, PACIENTE }; #endif
15
38
0.698039
hjCostaBR
aee6f103908d0dc64aea3c668d6a5515358c484a
1,131
cpp
C++
3. Algorithms on Graphs/Programming assignment 2/acyclicity/acyclicity.cpp
theyashmhatre/coursera-ds-algorithms
99e08921c0c0271e66a9aea42e7d38b7df494007
[ "MIT" ]
58
2017-12-24T05:08:58.000Z
2022-01-09T01:00:30.000Z
3. Algorithms on Graphs/Programming assignment 2/acyclicity/acyclicity.cpp
theyashmhatre/coursera-ds-algorithms
99e08921c0c0271e66a9aea42e7d38b7df494007
[ "MIT" ]
null
null
null
3. Algorithms on Graphs/Programming assignment 2/acyclicity/acyclicity.cpp
theyashmhatre/coursera-ds-algorithms
99e08921c0c0271e66a9aea42e7d38b7df494007
[ "MIT" ]
49
2017-12-07T02:52:46.000Z
2022-02-08T02:49:09.000Z
#include <iostream> #include <vector> using namespace std; vector<bool> visited, rec_stack; bool _acyclic(vector<vector<int> > &adj, int i) { if (!visited[i]) { // put in recursive stack and mark visited visited[i] = true; rec_stack[i] = true; for (int j = 0; j < adj[i].size(); j++) { int w = adj[i][j]; if (!visited[w] && _acyclic(adj, w)) { return true; } else if (rec_stack[w]) { return true; } } } // remove this element from recursive stack and return false rec_stack[i] = false; return false; } bool acyclic(vector<vector<int> > &adj) { visited.resize(adj.size()); rec_stack.resize(adj.size()); for (int i = 0; i < adj.size(); i++) { if (_acyclic(adj, i)) return true; } return false; } int main() { size_t n, m; std::cin >> n >> m; vector<vector<int> > adj(n, vector<int>()); for (size_t i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].push_back(y - 1); } std::cout << acyclic(adj); }
22.62
64
0.50221
theyashmhatre
aeee0eb9c4675aa56be42fec6103e8c8688fc094
6,121
cpp
C++
src/m_user.cpp
DreamHacks/dd3d
4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9
[ "MIT" ]
null
null
null
src/m_user.cpp
DreamHacks/dd3d
4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9
[ "MIT" ]
null
null
null
src/m_user.cpp
DreamHacks/dd3d
4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9
[ "MIT" ]
5
2017-07-09T12:03:19.000Z
2022-02-09T09:37:36.000Z
#include "dd3d.h" #include "log.h" #include <time.h> #include "m_user.h" #include "utils.h" const char* TABLE_USER = "vip_user"; const char* TABLE_SESSION = "vip_session"; static mysqlpp::Connection* Conn; void m_user_init(void) { Conn = database_conn(); } void m_user_cleanup(void) { Conn = NULL; } bool m_user_get_login_info(LoginUserInfo* info, const char* email, const char* password) { bool rv = false; CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "SELECT `uid`, `expire_time`, `groupid`, `banned` FROM `" << TABLE_USER << "` WHERE (`email` = " << mysqlpp::quote << email << " OR `username` = " << mysqlpp::quote << email << ") AND (`password` = " << mysqlpp::quote << password << " OR `password` = MD5(" << mysqlpp::quote << password << ")) LIMIT 1"; mysqlpp::StoreQueryResult res = query.store(); if (res.num_rows()) { info->uid = res[0][0]; info->expire_time = res[0][1]; info->groupid = res[0][2]; info->banned = res[0][3]; rv = true; } ) return rv; } bool m_user_get_session_by_id(SessionInfo* info, const char session_id[33]) { bool rv = false; CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "SELECT `client_id`, `uid`, `alive_time`, `key`, `locale_id` FROM `" << TABLE_SESSION << "`" " WHERE `session_id` = " << mysqlpp::quote << session_id << " LIMIT 1"; mysqlpp::StoreQueryResult res = query.store(); if (res.num_rows()) { info->session_id = session_id; info->client_id = res[0][0]; info->uid = res[0][1]; info->alive_time = res[0][2]; info->key = res[0][3]; info->locale_id = res[0][4]; rv = true; } ) return rv; } bool m_user_get_session_key_by_id(const char session_id[33], uint8_t key[XXTEA_KEY_SIZE], bool check_logged_in) { bool rv = false; SessionInfo info; if (m_user_get_session_by_id(&info, session_id)) { if (!check_logged_in || (check_logged_in && info.uid > 0)) { memcpy(key, info.key.data(), XXTEA_KEY_SIZE); rv = true; } } return rv; } bool m_user_erase_session_by_id(const char session_id[33]) { bool rv = false; CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "DELETE FROM `" << TABLE_SESSION << "` WHERE `session_id` = " << mysqlpp::quote << session_id; if (query.exec()) rv = true; ) return rv; } bool m_user_erase_session_by_uid(uint32_t uid) { bool rv = false; CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "DELETE FROM `" << TABLE_SESSION << "` WHERE `uid` = " << uid; if (query.exec()) rv = true; ) return rv; } bool m_user_get_session_by_uid(SessionInfo* info, uint32_t uid) { bool rv = false; try { mysqlpp::Query query(Conn); query << "SELECT `session_id`, `client_id`, `alive_time`, `key`, `locale_id` FROM `" << TABLE_SESSION << "`" " WHERE `uid` = " << uid << " LIMIT 1"; mysqlpp::StoreQueryResult res = query.store(); if (res.num_rows()) { info->session_id = res[0][0].c_str(); info->client_id = res[0][1]; info->uid = uid; info->alive_time = res[0][2]; info->key = res[0][3]; info->locale_id = res[0][4]; rv = true; } } catch (const mysqlpp::Exception& e) { printf("exception: %s\n", e.what()); } return rv; } bool m_user_clear_timeout_sessions() { bool rv = false; CATCH_DB_EXCEPTION ( uint32_t now = time(NULL); mysqlpp::Query query(Conn); query << "DELETE FROM `" << TABLE_SESSION << "` WHERE `alive_time` < " << (now - SESSION_TIMEOUT); if (query.exec()) rv = true; ) return rv; } bool m_user_create_session(char session_id[33], const uint8_t key[16]) { bool rv = false; CATCH_DB_EXCEPTION ( uint32_t now = time(NULL); mysqlpp::Query query(Conn); uint8_t uuid[16]; utils_get_uuid(uuid); utils_bin2hex(uuid, 16, session_id, 33); std::string key_str; key_str.assign((char*)key, 16); query << "INSERT INTO `" << TABLE_SESSION << "` VALUES(" << mysqlpp::quote << session_id << "," << 0 << "," << 0 << "," << now << ",\"" << mysqlpp::escape << key_str << "\"" << "," << 0 << ")"; if (query.exec() && query.affected_rows() == 1) rv = true; ) return rv; } bool m_user_update_session_by_id(const char session_id[33], uint32_t client_id, uint32_t uid) { bool rv = false; CATCH_DB_EXCEPTION ( uint32_t now = time(NULL); mysqlpp::Query query(Conn); query << "UPDATE `" << TABLE_SESSION << "` SET `client_id` = " << client_id << ", uid = " << uid << ", alive_time = " << now << " WHERE `session_id` = " << mysqlpp::quote << session_id; if (query.exec() && query.affected_rows() == 1) rv = true; ) return rv; } bool m_user_update_session_client_id_by_uid(uint32_t uid, uint32_t client_id) { bool rv = false; CATCH_DB_EXCEPTION ( uint32_t now = time(NULL); mysqlpp::Query query(Conn); query << "UPDATE `" << TABLE_SESSION << "` SET `client_id` = " << client_id << ", alive_time = " << now << " WHERE `uid` = " << uid << " LIMIT 1"; if (query.exec() && query.affected_rows() == 1) rv = true; ) return rv; } bool m_user_alive_session_by_id(const char session_id[33]) { bool rv = false; uint32_t now = time(NULL); CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "UPDATE `" << TABLE_SESSION << "` SET `alive_time` = " << now << " WHERE `session_id` = " << mysqlpp::quote << session_id << " LIMIT 1"; if (query.exec() && query.affected_rows() == 1) rv = true; ) return rv; } bool m_user_alive_session_by_uid(uint32_t uid) { bool rv = false; uint32_t now = time(NULL); CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "UPDATE `" << TABLE_SESSION << "` SET `alive_time` = " << now << " WHERE `uid` = " << uid << " LIMIT 1"; if (query.exec() && query.affected_rows() == 1) rv = true; ) return rv; } bool m_user_update_locale_by_id(const char session_id[33], uint32_t locale_id) { bool rv = false; CATCH_DB_EXCEPTION ( mysqlpp::Query query(Conn); query << "UPDATE `" << TABLE_SESSION << "` SET `locale_id` = " << locale_id << " WHERE `session_id` = " << mysqlpp::quote << session_id << " LIMIT 1"; if (query.exec() && query.affected_rows() == 1) rv = true; ) return rv; }
28.602804
139
0.622937
DreamHacks
aef07315a50b644c549da3a9d299dd76c5d33cd0
4,496
cpp
C++
src/Platforms/OpenGL/GLStandardRenderer.cpp
merphous/LavaEngine
33fc8cab9b31a93426f5ad430ca355dd4456197a
[ "MIT" ]
1
2021-08-07T21:20:19.000Z
2021-08-07T21:20:19.000Z
src/Platforms/OpenGL/GLStandardRenderer.cpp
merphous/LavaEngine
33fc8cab9b31a93426f5ad430ca355dd4456197a
[ "MIT" ]
null
null
null
src/Platforms/OpenGL/GLStandardRenderer.cpp
merphous/LavaEngine
33fc8cab9b31a93426f5ad430ca355dd4456197a
[ "MIT" ]
1
2021-07-31T21:54:33.000Z
2021-07-31T21:54:33.000Z
#include "GLStandardRenderer.h" #include "GLShaderBank.h" namespace Lava { namespace OpenGL { GLStandardRenderer::GLStandardRenderer(Scene* scene, std::vector<GLShader*> shader_list) : EntityRenderer(scene) { m_bank = new GLShaderBank(); if (shader_list.empty()) LoadDefaultShader(shader_list); for (auto& shader : shader_list) m_bank->AddShader(shader); m_bank->Activate(); } GLStandardRenderer::~GLStandardRenderer() { delete m_bank; } void GLStandardRenderer::Configure(glm::mat4 viewMatrix, glm::mat4 projectionMatrix) { m_bank->Bind(); m_bank->GetShader(0)->SetMatrix4x4("View", viewMatrix); m_bank->GetShader(0)->SetMatrix4x4("Projection", projectionMatrix); } void GLStandardRenderer::CompleteRender() { m_bank->Unbind(); } void GLStandardRenderer::Update(Scene* scene) { Configure(scene->ActiveCamera->GetViewMatrix(), scene->ActiveCamera->GetProjectionMatrix()); SetLightInfo(scene); SetFogInfo(); Render(dummy_render_parameter,glm::vec4(0)); CompleteRender(); } void GLStandardRenderer::BindAttribute(int variableIndex, const char* variableName) { m_bank->AddVariable(variableIndex, variableName); } void GLStandardRenderer::SetLightInfo(Scene* scene) { m_bank->GetShader(1)->SetFloat1("AmbientLightIntensity", scene->scene_data->ambient_light_intensity); for (int i = 0; i < scene->scene_data->lights->size(); i++) { auto& light = scene->scene_data->lights->at(i); m_bank->GetShader(0)->SetFloat3(("LightPosition[" + std::to_string(i) + "]").c_str(), light->Position); m_bank->GetShader(1)->SetFloat3(("LightColor[" + std::to_string(i) + "]").c_str(), light->Color); m_bank->GetShader(1)->SetFloat3(("LightAttenuation[" + std::to_string(i) + "]").c_str(), light->Attenuation); m_bank->GetShader(1)->SetFloat1(("LightIntensity[" + std::to_string(i) + "]").c_str(), light->Intensity); } } void GLStandardRenderer::SetFogInfo() { m_bank->GetShader(0)->SetFloat1("FogDensity", m_scene->scene_data->fog_density); m_bank->GetShader(1)->SetFloat3("FogColor", m_scene->scene_data->fog_color); } void GLStandardRenderer::PushInstanceData(Entity* entityPtr) { auto model = entityPtr->transform->GetTransformationMatrix(); m_bank->GetShader(0)->SetMatrix4x4("Model", model); m_bank->GetShader(1)->SetFloat1("Shininess", entityPtr->material->shininess); m_bank->GetShader(1)->SetFloat1("GlossDamping", entityPtr->material->glossDamping); } void GLStandardRenderer::BindObjects(Entity* entityPtr) { GLRenderObject* renderObjectPtr = (GLRenderObject*)(entityPtr->GetMeshRenderer(Platform::OpenGL)->GetRenderObject()); renderObjectPtr->m_vao->Bind(); for (auto i = 0; i < entityPtr->mesh->m_bufferLayoutCount; i++) glEnableVertexAttribArray(i); if (renderObjectPtr->HasTexture()) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, entityPtr->material->m_mainTexture->texture_id); m_bank->GetShader(1)->SetInt1("textureSampler", 0); } m_bank->GetShader(1)->SetFloat3("Albedo",entityPtr->material->albedoColor); if (renderObjectPtr->HasNormalMap()) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, entityPtr->material->m_nrmTexture->texture_id); m_bank->GetShader(1)->SetInt1("normalMapSampler", 1); } } void GLStandardRenderer::UnBindObjects(Entity* entityPtr) { for (auto i = 0; i < entityPtr->mesh->m_bufferLayoutCount; i++) glDisableVertexAttribArray(i); GLRenderObject* renderObjectPtr = static_cast<GLRenderObject*>(entityPtr->GetMeshRenderer(Platform::OpenGL)->GetRenderObject()); renderObjectPtr->m_vao->Unbind(); } void GLStandardRenderer::Render(std::map<MeshRenderer*, std::vector<Entity*>*>& entities, glm::vec4 clipPlane) { glEnable(GL_CLIP_DISTANCE0); for (auto& render_element : m_renderlist) { BindObjects(render_element); PushInstanceData(render_element); m_bank->GetShader(0)->SetFloat4("ClipPlane", clipPlane); glDrawElements(GL_TRIANGLES, render_element->mesh->m_posCount, GL_UNSIGNED_INT, 0); UnBindObjects(render_element); } glDisable(GL_CLIP_DISTANCE0); } void GLStandardRenderer::LoadDefaultShader(std::vector<GLShader*>& list) { auto vert = new GLShader("Shaders/vertexShader.vp", ShaderType::Vertex, m_bank); auto frag = new GLShader("Shaders/fragmentShader.fp", ShaderType::Fragment, m_bank); list.push_back(vert); list.push_back(frag); } } }
34.852713
131
0.715525
merphous
aef1f4448cefe4926fecfce99b728f893ba5f66e
337
cpp
C++
src/modules/commands/power_command.cpp
molayab/bobot-car-iot
978a7ce279b894619f3b03ceb6d7675d8a414e2b
[ "MIT" ]
null
null
null
src/modules/commands/power_command.cpp
molayab/bobot-car-iot
978a7ce279b894619f3b03ceb6d7675d8a414e2b
[ "MIT" ]
null
null
null
src/modules/commands/power_command.cpp
molayab/bobot-car-iot
978a7ce279b894619f3b03ceb6d7675d8a414e2b
[ "MIT" ]
null
null
null
#include "modules/commands/power_command.h" PowerCommand::PowerCommand(Engine* engine, Engine::motor_descriptor_r motor, uint8_t power) { this->engine = engine; this->motor = motor; this->power = power; } void PowerCommand::execute() { engine->set_power(motor, power); }
25.923077
58
0.608309
molayab
aef93c965911a85823ced57d8213df001299ae21
636
cpp
C++
0187 Repeated DNA Sequences/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
1
2019-12-19T04:13:15.000Z
2019-12-19T04:13:15.000Z
0187 Repeated DNA Sequences/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
0187 Repeated DNA Sequences/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" using namespace std; class Solution { public: vector<string> findRepeatedDnaSequences(string s) { unordered_map<string, int> hash; vector<string> res; for (int i = 0; i + 10 <= s.size(); i ++) { string str = s.substr(i, 10); hash[str] ++; if (hash[str] == 2) res.push_back(str); } return res; } }; int main(){ string s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"; vector<string> res = Solution().findRepeatedDnaSequences(s); for (auto t : res) cout << t << " "; return 0; }
22.714286
64
0.518868
Aden-Tao
aef99b08d481b7a0b5c2709a4b6869d9effb9b2c
2,106
cpp
C++
bindings/python/crocoddyl/core/activations/smooth-2norm.cpp
spykspeigel/crocoddyl
0500e398861564b6986d99206a1e0ccec0d66a33
[ "BSD-3-Clause" ]
322
2019-06-04T12:04:00.000Z
2022-03-28T14:37:44.000Z
bindings/python/crocoddyl/core/activations/smooth-2norm.cpp
spykspeigel/crocoddyl
0500e398861564b6986d99206a1e0ccec0d66a33
[ "BSD-3-Clause" ]
954
2019-09-02T10:07:27.000Z
2022-03-31T16:14:25.000Z
bindings/python/crocoddyl/core/activations/smooth-2norm.cpp
spykspeigel/crocoddyl
0500e398861564b6986d99206a1e0ccec0d66a33
[ "BSD-3-Clause" ]
89
2019-08-13T13:37:52.000Z
2022-03-31T15:55:07.000Z
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2020-2021, LAAS-CNRS, University of Edinburgh // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "python/crocoddyl/core/core.hpp" #include "python/crocoddyl/core/activation-base.hpp" #include "crocoddyl/core/activations/smooth-2norm.hpp" namespace crocoddyl { namespace python { void exposeActivationSmooth2Norm() { boost::python::register_ptr_to_python<boost::shared_ptr<ActivationModelSmooth2Norm> >(); bp::class_<ActivationModelSmooth2Norm, bp::bases<ActivationModelAbstract> >( "ActivationModelSmooth2Norm", "Smooth-2Norm activation model.\n\n" "It describes a smooth representation of a 2-norm, i.e.\n" "sqrt{eps + sum^nr_{i=0} ||ri||^2}, where ri is the scalar residual for the i constraints,\n." "and nr is the dimension of the residual vector.", bp::init<int, bp::optional<double> >(bp::args("self", "nr", "eps"), "Initialize the activation model.\n\n" ":param nr: dimension of the residual vector\n" ":param eps: smoothing factor (default: 1.)")) .def("calc", &ActivationModelSmooth2Norm::calc, bp::args("self", "data", "r"), "Compute the smooth-2norm function.\n\n" ":param data: activation data\n" ":param r: residual vector") .def("calcDiff", &ActivationModelSmooth2Norm::calcDiff, bp::args("self", "data", "r"), "Compute the derivatives of a smooth-2norm function.\n\n" "It assumes that calc has been run first.\n" ":param data: activation data\n" ":param r: residual vector \n") .def("createData", &ActivationModelSmooth2Norm::createData, bp::args("self"), "Create the smooth-2norm activation data.\n\n"); } } // namespace python } // namespace crocoddyl
47.863636
100
0.58547
spykspeigel
aefa99702dd6d6210dbf98b0cab762d5201865c3
265
cpp
C++
C++/1_EntradaSalidaDeDatos/potenciaCuadrada.cpp
JoseVcode/learn-programming
829457010d3ec439a2a164efb0e69b64ec56eeb7
[ "MIT" ]
null
null
null
C++/1_EntradaSalidaDeDatos/potenciaCuadrada.cpp
JoseVcode/learn-programming
829457010d3ec439a2a164efb0e69b64ec56eeb7
[ "MIT" ]
null
null
null
C++/1_EntradaSalidaDeDatos/potenciaCuadrada.cpp
JoseVcode/learn-programming
829457010d3ec439a2a164efb0e69b64ec56eeb7
[ "MIT" ]
null
null
null
/* Programa que muestra la potencia cuadrada de un numero entero */ #include <iostream> int main() { int numero; std::cout << "Ingrese un numero: "; std::cin >> numero; std::cout << "La potencia es '" << numero*numero << "'" << std::endl; return 0; }
18.928571
71
0.611321
JoseVcode
4e0cfb5c9fb2f01ae170b6ff65dc3a6aca49d607
1,314
cpp
C++
Lab-7/Coin_Change_DP.cpp
Hitesh1309/DAA-Lab-Submissions
acaa495628ea3755a7602cf9d8ee35874bddbe88
[ "MIT" ]
1
2022-03-15T07:09:37.000Z
2022-03-15T07:09:37.000Z
Lab-7/Coin_Change_DP.cpp
Hitesh1309/DAA-Lab-Submissions
acaa495628ea3755a7602cf9d8ee35874bddbe88
[ "MIT" ]
null
null
null
Lab-7/Coin_Change_DP.cpp
Hitesh1309/DAA-Lab-Submissions
acaa495628ea3755a7602cf9d8ee35874bddbe88
[ "MIT" ]
1
2022-03-15T07:09:58.000Z
2022-03-15T07:09:58.000Z
#include<bits/stdc++.h> using namespace std; int main() { int n,t; cout<<"\nEnter no. of denominations (where 1 would be auto added): "; cin>>n; vector<int> change; //vector of denominations map<int,int> record; // map of amount - minimum number of denominations cout<<"\nInserted a base denomination 1\nEnter "<<n-1; cout<<" denominations:\n"; change.push_back(1); record[1] = 1; for(int i=1;i<n;i++) { cin>>t; change.push_back(t); record[t] = 1; // assign minimum value } record[0] = 0; //assign to 0 value int amount; A: cout<<"\nEnter total amount: "; cin>>amount; if(amount<0) { cout<<"\nEnter amount again..\n"; goto A; } int m; for(int i=1;i<=amount;i++) { if(record[i]!=0) continue; else { m = INT_MAX; for(int X:change) { if(i-X>0) // to check out of bounds { m = min(m,record[i-X]+1); // iteratively assigning min value } } record[i] = m; } } cout<<"\nMinimum number of denominations required for "<<amount<<" is: "<<record[amount]; cout<<"\n\n"; }
19.61194
93
0.479452
Hitesh1309
4e0f57b4d78d3f708bad3239aabc0957e7d874a9
2,956
cpp
C++
src/settingsdialog.cpp
jubnzv/qtask
f67c7034ff9576c123b885acbb942638bf85de48
[ "MIT" ]
11
2020-11-29T18:24:28.000Z
2022-03-19T17:34:08.000Z
src/settingsdialog.cpp
jubnzv/jtask
f67c7034ff9576c123b885acbb942638bf85de48
[ "MIT" ]
3
2020-11-29T18:26:36.000Z
2021-07-16T14:18:58.000Z
src/settingsdialog.cpp
jubnzv/jtask
f67c7034ff9576c123b885acbb942638bf85de48
[ "MIT" ]
1
2022-02-14T17:25:04.000Z
2022-02-14T17:25:04.000Z
#include "settingsdialog.hpp" #include <QAbstractButton> #include <QCoreApplication> #include <QDialog> #include <QDialogButtonBox> #include <QGridLayout> #include <QIcon> #include <QLabel> #include <QLineEdit> #include "configmanager.hpp" SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent) { initUI(); } SettingsDialog::~SettingsDialog() {} void SettingsDialog::initUI() { QGridLayout *main_layout = new QGridLayout(); main_layout->setContentsMargins(5, 5, 5, 5); setWindowTitle(QCoreApplication::applicationName() + " - Settings"); setWindowIcon(QIcon(":/icons/qtask.svg")); QLabel *task_bin_label = new QLabel("task executable:"); main_layout->addWidget(task_bin_label, 0, 0); m_task_bin_edit = new QLineEdit(); m_task_bin_edit->setText(ConfigManager::config()->getTaskBin()); main_layout->addWidget(m_task_bin_edit, 0, 1); QLabel *task_data_path_label = new QLabel("Path to task data:"); main_layout->addWidget(task_data_path_label, 1, 0); m_task_data_path_edit = new QLineEdit(); m_task_data_path_edit->setText(ConfigManager::config()->getTaskDataPath()); main_layout->addWidget(m_task_data_path_edit, 1, 1); m_hide_on_startup_cb = new QCheckBox(tr("Hide QTask window on startup")); m_hide_on_startup_cb->setChecked( ConfigManager::config()->getHideWindowOnStartup()); main_layout->addWidget(m_hide_on_startup_cb, 2, 0, 1, 2); m_save_filter_on_exit = new QCheckBox(tr("Save task filter on exit")); m_save_filter_on_exit->setChecked( ConfigManager::config()->getSaveFilterOnExit()); main_layout->addWidget(m_save_filter_on_exit, 3, 0, 1, 2); m_buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Close); connect(m_buttons, &QDialogButtonBox::clicked, this, &SettingsDialog::onButtonBoxClicked); main_layout->addWidget(m_buttons, 4, 0, 1, 2); setLayout(main_layout); } void SettingsDialog::applySettings() { auto task_data_path = m_task_data_path_edit->text(); if (ConfigManager::config()->getTaskDataPath() != task_data_path) ConfigManager::config()->setTaskDataPath(task_data_path); auto task_bin = m_task_bin_edit->text(); if (ConfigManager::config()->getTaskBin() != task_bin) ConfigManager::config()->setTaskBin(task_bin); ConfigManager::config()->setHideWindowOnStartup( m_hide_on_startup_cb->isChecked()); ConfigManager::config()->setSaveFilterOnExit( m_save_filter_on_exit->isChecked()); ConfigManager::config()->updateConfigFile(); } void SettingsDialog::onButtonBoxClicked(QAbstractButton *button) { switch (m_buttons->standardButton(button)) { case QDialogButtonBox::Apply: applySettings(); break; case QDialogButtonBox::Ok: applySettings(); close(); default: close(); } }
31.115789
79
0.701286
jubnzv
4e107da15c1367fa17e0ac049fba015a572b8cf1
2,869
hpp
C++
Renderers/OpenGL3/CubismOpenGL3.hpp
akoylasar/cubism
3e1e26ccc6de87dd574bab4c2be396650fd5af45
[ "MIT" ]
null
null
null
Renderers/OpenGL3/CubismOpenGL3.hpp
akoylasar/cubism
3e1e26ccc6de87dd574bab4c2be396650fd5af45
[ "MIT" ]
null
null
null
Renderers/OpenGL3/CubismOpenGL3.hpp
akoylasar/cubism
3e1e26ccc6de87dd574bab4c2be396650fd5af45
[ "MIT" ]
null
null
null
// This is a modified version of imgui_impl_opengl3.h found under https://github.com/ocornut/imgui/tree/master/examples /* The MIT License (MIT) Copyright (c) 2014-2020 Omar Cornut 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. */ // Copyright (c) Fouad Valadbeigi (akoylasar@gmail.com) #pragma once #include "Cubism.hpp" namespace Cubism { namespace Renderer { namespace OpenGL { bool init(const char* glslVersion); void shutdown(); void newFrame(); void render(); } } } // Specific OpenGL versions // #define CUBISM_RENDERER_OPENGL_ES2 // Auto-detected on Emscripten // #define CUBISM_RENDERER_OPENGL_ES3 // Auto-detected on iOS/Android // Desktop OpenGL: attempt to detect default GL loader based on available header files. // If auto-detection fails or doesn't select the same GL loader file as used by your application, // you are likely to get a crash in Cubism::Renderer::OpenGL::Init(). #if !defined(CUBISM_RENDERER_OPENGL_LOADER_GL3W) \ && !defined(CUBISM_RENDERER_OPENGL_LOADER_GLEW) \ && !defined(CUBISM_RENDERER_OPENGL_LOADER_GLAD) \ && !defined(CUBISM_RENDERER_OPENGL_LOADER_GLBINDING2) \ && !defined(CUBISM_RENDERER_OPENGL_LOADER_GLBINDING3) \ && !defined(CUBISM_RENDERER_OPENGL_LOADER_CUSTOM) #if defined(__has_include) #if __has_include(<GL/glew.h>) #define CUBISM_RENDERER_OPENGL_LOADER_GLEW #elif __has_include(<glad/glad.h>) #define CUBISM_RENDERER_OPENGL_LOADER_GLAD #elif __has_include(<GL/gl3w.h>) #define CUBISM_RENDERER_OPENGL_LOADER_GL3W #elif __has_include(<glbinding/glbinding.h>) #define CUBISM_RENDERER_OPENGL_LOADER_GLBINDING3 #elif __has_include(<glbinding/Binding.h>) #define CUBISM_RENDERER_OPENGL_LOADER_GLBINDING2 #else #error "Cannot detect OpenGL loader!" #endif #else #define CUBISM_RENDERER_OPENGL_LOADER_GL3W #endif #endif
37.25974
119
0.767863
akoylasar
4e197cf1898ba1c2f3807c803eaec70505207b66
265
cpp
C++
school1/3A/10Awk.cpp
momomeomo/School
d004bf6ed6fa3a5cec4fa067b61e5842acbaa3f6
[ "Unlicense" ]
null
null
null
school1/3A/10Awk.cpp
momomeomo/School
d004bf6ed6fa3a5cec4fa067b61e5842acbaa3f6
[ "Unlicense" ]
null
null
null
school1/3A/10Awk.cpp
momomeomo/School
d004bf6ed6fa3a5cec4fa067b61e5842acbaa3f6
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; void CountUp(int start, int stop, int step); int main() { CountUp(10,100,2); return 0; } void CountUp(int start, int stop, int step) { for (int x = start; x <= stop; x = x + step) cout << x << endl; }
15.588235
48
0.592453
momomeomo
4e1d29c1c2f74923230b0e38e85adb175853ae1c
355
hpp
C++
include/rxcpp/rx-fsm.hpp
i94matjo/rxcpp-fsm
4706b3111065c078d55a3fc0089110d0772f3427
[ "Apache-2.0" ]
1
2020-08-05T04:21:04.000Z
2020-08-05T04:21:04.000Z
include/rxcpp/rx-fsm.hpp
i94matjo/rxcpp-fsm
4706b3111065c078d55a3fc0089110d0772f3427
[ "Apache-2.0" ]
null
null
null
include/rxcpp/rx-fsm.hpp
i94matjo/rxcpp-fsm
4706b3111065c078d55a3fc0089110d0772f3427
[ "Apache-2.0" ]
1
2020-08-05T04:21:09.000Z
2020-08-05T04:21:09.000Z
/*! \file rx-fsm.hpp \copyright Copyright (c) 2019, emJay Software Consulting AB. All rights reserved. Use of this source code is governed by the Apache-2.0 license, that can be found in the LICENSE.md file. \author Mattias Johansson */ #pragma once #if !defined(RX_FSM_HPP) #define RX_FSM_HPP #include "fsm/rx-fsm-includes.hpp" #endif
23.666667
191
0.721127
i94matjo
4e1d48788690a4cedea6c37b5415d151b1bc3a6f
957
cpp
C++
solutions/number_of_coins.cpp
spythrone/gfg-solutions
7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2
[ "MIT" ]
null
null
null
solutions/number_of_coins.cpp
spythrone/gfg-solutions
7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2
[ "MIT" ]
null
null
null
solutions/number_of_coins.cpp
spythrone/gfg-solutions
7bb5198a1a8c7a06d7f81eea78dfa9451252c6b2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution{ public: int getsol(int coins[], int M, int V, vector<int> &v){ if(V==0) return 0; if(V<0) return INT_MAX; if(v[V]>0) return v[V]; int x = INT_MAX; for(int i=0; i<M; i++){ int t = getsol(coins, M, V-coins[i], v); if(t==INT_MAX) x = min(x, t); else x = min(x, t+1); } v[V] = x; return v[V]; } int minCoins(int coins[], int M, int V) { vector<int> v(V+1,0); int ans = getsol(coins, M, V, v); if(ans==INT_MAX) return -1; return ans; } }; int main() { int t; cin >> t; while (t--) { int v, m; cin >> v >> m; int coins[m]; for(int i = 0; i < m; i++) cin >> coins[i]; Solution ob; cout << ob.minCoins(coins, m, v) << "\n"; } return 0; }
15.95
55
0.416928
spythrone
4e1fd934435cc72a12d13cbe2f93077ad6e730a9
575
cpp
C++
math/fps/eulerian.cpp
neal2018/library
a19f3b29f3355e32f7e5f6768a7943db48fcdff7
[ "Unlicense" ]
127
2019-07-22T03:52:01.000Z
2022-03-11T07:20:21.000Z
math/fps/eulerian.cpp
neal2018/library
a19f3b29f3355e32f7e5f6768a7943db48fcdff7
[ "Unlicense" ]
39
2019-09-16T12:04:53.000Z
2022-03-29T15:43:35.000Z
math/fps/eulerian.cpp
neal2018/library
a19f3b29f3355e32f7e5f6768a7943db48fcdff7
[ "Unlicense" ]
29
2019-08-10T11:27:06.000Z
2022-03-11T07:02:43.000Z
/** * @brief Eulerian(オイラー数) */ template< template< typename > class FPS, typename Mint > FPS< Mint > eulerian(int N) { vector< Mint > fact(N + 2), rfact(N + 2); fact[0] = rfact[N + 1] = 1; for(int i = 1; i <= N + 1; i++) fact[i] = fact[i - 1] * Mint(i); rfact[N + 1] /= fact[N + 1]; for(int i = N; i >= 0; i--) rfact[i] = rfact[i + 1] * Mint(i + 1); FPS< Mint > A(N + 1), B(N + 1); for(int i = 0; i <= N; i++) { A[i] = fact[N + 1] * rfact[i] * rfact[N + 1 - i]; if(i & 1) A[i] *= -1; B[i] = Mint(i + 1).pow(N); } return (A * B).pre(N + 1); }
30.263158
68
0.462609
neal2018
4e1ff634ac99980cea3ed37b57505a8a3174df57
2,410
cpp
C++
MedicalCenterConsole/ConsoleMenu.cpp
vm2mv/bsuir_kp_okp_medical_center
0a555293d1e50506d7e9a4aff533a45c45e46117
[ "MIT" ]
8
2017-01-13T10:11:42.000Z
2022-03-15T18:27:14.000Z
MedicalCenterConsole/ConsoleMenu.cpp
vm2mv/bsuir_kp_okp_medical_center
0a555293d1e50506d7e9a4aff533a45c45e46117
[ "MIT" ]
null
null
null
MedicalCenterConsole/ConsoleMenu.cpp
vm2mv/bsuir_kp_okp_medical_center
0a555293d1e50506d7e9a4aff533a45c45e46117
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ConsoleMenu.h" #include "Console.h" #include "Language.h" ConsoleMenu::ConsoleMenu(Console& console, const Language& language) : m_language(language), m_console(console) { } ConsoleMenu::~ConsoleMenu() { } void ConsoleMenu::AddItem(const std::string& itemName, std::function<void()> action) { size_t menuItemNumer = m_items.size() + 1; m_items[menuItemNumer] = MenuItem{ itemName, action }; } void ConsoleMenu::AddMenu(const std::string& itemName, const ConsoleMenu menu) { std::function<void()> actionFunc = [itemName, menu]() { menu.StartMenuDialog(true, itemName); }; m_items[m_items.size() + 1] = MenuItem{ itemName, actionFunc }; } void ConsoleMenu::StartMenuAndWaitExit() const { StartMenuDialog(false, ""); } void ConsoleMenu::StartMenuDialog(bool childMenu, const std::string& itemName) const { while (true) { if (!DoMenuDialog(childMenu, itemName)) { break; } } } bool ConsoleMenu::DoMenuDialog(bool childMenu, const std::string& itemName) const { PrintMenu(childMenu, itemName); m_console.PrintWhite(GetLanguage().GetString(LanguageString::MenuSelectItem)); uint64_t selectedMenuItemNum = m_console.RequestInputInteger(); if (selectedMenuItemNum == 0) { return false; } auto it = m_items.find(selectedMenuItemNum); if (it == m_items.cend()) { m_console.PrintErrorWithNewLine(GetLanguage().GetString(LanguageString::IncorrectValue)); return true; } CallAction(it->second.action); return true; } void ConsoleMenu::PrintMenu(bool childMenu, const std::string& itemName) const { if (childMenu) { m_console.PrintWhite(u8"%s\r\n", itemName.c_str()); } for (const auto& i : m_items) { m_console.PrintInfo(u8"%zu. %s\r\n", i.first, i.second.name.c_str()); } if (childMenu) { m_console.PrintInfoWithNewLine(GetLanguage().GetString(LanguageString::MenuReturnToParent)); } else { m_console.PrintInfoWithNewLine(GetLanguage().GetString(LanguageString::MenuExit)); } } void ConsoleMenu::CallAction(const std::function<void()>& actionCallback) const { if (actionCallback == nullptr) { return; } try { actionCallback(); } catch (const std::exception& ex) { m_console.PrintErrorWithNewLine(GetLanguage().GetString(LanguageString::UnknowError)); m_console.PrintErrorWithNewLine("\t %s", ex.what()); } } const Language& ConsoleMenu::GetLanguage() const { return m_language; }
18.682171
94
0.720747
vm2mv
4e2026c498bea5332d4de04ee95f03eb040a1408
831
hpp
C++
include/h3api/H3GzWrapper.hpp
Patrulek/H3API
91f10de37c6b86f3160706c1fdf4792f927e9952
[ "MIT" ]
14
2020-09-07T21:49:26.000Z
2021-11-29T18:09:41.000Z
include/h3api/H3GzWrapper.hpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
2
2021-02-12T15:52:31.000Z
2021-02-12T16:21:24.000Z
include/h3api/H3GzWrapper.hpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
8
2021-02-12T15:52:41.000Z
2022-01-31T15:28:10.000Z
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created or last updated on: 2021-02-20 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #pragma once #include "h3api/H3GzWrapper/H3GzFile.hpp" #include "h3api/H3GzWrapper/H3GzInflateBuf.hpp" #include "h3api/H3GzWrapper/H3GzStream.hpp" #include "h3api/H3GzWrapper/H3ZStream.hpp"
48.882353
70
0.357401
Patrulek
4e236865b611e3c2ec1acedac0115ec2b1946382
7,130
hh
C++
src/callow/matrix/Matrix.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
null
null
null
src/callow/matrix/Matrix.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
null
null
null
src/callow/matrix/Matrix.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// /** * @file Matrix.hh * @author robertsj * @date Sep 13, 2012 * @brief Matrix class definition. */ //---------------------------------------------------------------------------// #ifndef callow_MATRIX_HH_ #define callow_MATRIX_HH_ #include "MatrixBase.hh" #include "Triplet.hh" #include <ostream> #include <vector> #include <string> namespace callow { /** * @class Matrix * @brief CRS matrix * * This is the base matrix class used within callow. It implements * a compressed row storage (CRS) matrix. An example of what this * means is as follows. * * Example: * * | 7 0 0 2 | * | 0 2 0 4 | * | 1 0 0 0 | * | 3 8 0 6 | * * value = [7 2 2 4 1 3 8 6] * column indices = [0 3 1 3 0 0 1 3] * row pointers = [0 2 4 5 8] * * We're keeping this simple to use. The use must specify * the number of nonzero entries per row, either via one * value applied to all rows or an array of values for * each row. The reason the row storage is needed rather * than say the total number of nonzero entries is to make * construction easier. During construction, the matrix * is stored (temporarily) in coordinate (COO) format, i.e. * a list of (i, j, value) triplets. If this were stored * in one monolithic array, the construction of the CSR * structure would require we sort all the triplets by * row and then by column (since we want explicit access * to L, D, and U). Initial testing proved that sorting * is just too time consuming, even with an n*log(n) method * like quicksort. * * Consequently, we do keep (i, j, value) triplets, but they * are stored by row, and to store by row, we need an initial * guess of how many entries there are. For now, the size * can not be increased, but that would not be too difficult. * * During the construction process, * a COO (row, column, value) format is used. * This allows the user to add entries * one at a time, a row at a time, a column at a time, or * several rcv triples at a time. At the construction process, * the storage is streamlined into CSR format, ensuring that * entries are stored by row and column and that a diagonal * entry exists. That latter is required for things like * the \ref Jacobi or \ref GaussSeidel solvers, along with * certain preconditioner types. * */ class CALLOW_EXPORT Matrix: public MatrixBase { public: //---------------------------------------------------------------------------// // ENUMERATIONS //---------------------------------------------------------------------------// enum insert_type { INSERT, ADD, END_INSERT_TYPE }; //---------------------------------------------------------------------------// // TYPEDEFS //---------------------------------------------------------------------------// typedef detran_utilities::SP<Matrix> SP_matrix; typedef triplet triplet_T; //---------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //---------------------------------------------------------------------------// // construction with deferred sizing and allocation Matrix(); // construction with sizing but deferred allocation Matrix(const int m, const int n); // construction with sizing and allocation Matrix(const int m, const int n, const int nnz); // copy constructor Matrix(Matrix &A); // destructor virtual ~Matrix(); // sp constructor static SP_matrix Create(const int m, const int n); static SP_matrix Create(const int m, const int n, const int nnz); //---------------------------------------------------------------------------// // PUBLIC FUNCTIONS //---------------------------------------------------------------------------// /// allocate using constant row size void preallocate(const int nnz_row); /// allocate using variable row size void preallocate(int *nnz_rows); /// add one value (return false if can't add) bool insert(int i, int j, double v, const int type = INSERT); /// add n values to a row (return false if can't add) bool insert(int i, int *j, double *v, int n, const int type = INSERT); /// add n values to a column (return false if can't add) bool insert(int *i, int j, double *v, int n, const int type = INSERT); /// add n triplets (return false if can't add) bool insert(int *i, int *j, double *v, int n, const int type = INSERT); /// starting index for a row int start(const int i) const; /// diagonal index for a row int diagonal(const int i) const; /// ending index for a row int end(const int i) const ; /// column index from cardinal index int column(const int p) const; /// value at a cardinal index double operator[](const int p) const; /// value at ij and returns 0 if not present double operator()(const int i, const int j) const; // get underlying storage and indexing. careful! double* values() {return d_values;} int* columns() {return d_columns;} int* rows() {return d_rows;} int* diagonals() {return d_diagonals;} /// number of nonzeros int number_nonzeros() const { return d_nnz; } /// is memory allocated? bool allocated() const {return d_allocated;} /// print (i, j, v) to ascii file with 1-based indexing for matlab void print_matlab(std::string filename = "matrix.out") const; //---------------------------------------------------------------------------// // ABSTRACT INTERFACE -- ALL MATRICES MUST IMPLEMENT //---------------------------------------------------------------------------// // postprocess storage void assemble(); // action y <-- A * x void multiply(const Vector &x, Vector &y); // action y <-- A' * x void multiply_transpose(const Vector &x, Vector &y); // pretty print to screen void display() const; protected: //---------------------------------------------------------------------------// // DATA //---------------------------------------------------------------------------// /// expose base members using MatrixBase::d_m; using MatrixBase::d_n; using MatrixBase::d_sizes_set; using MatrixBase::d_is_ready; #ifdef CALLOW_ENABLE_PETSC using MatrixBase::d_petsc_matrix; #endif /// matrix elements double* d_values; /// column indices int* d_columns; /// row pointers int* d_rows; /// pointer to diagonal index of each row int* d_diagonals; /// number of nonzeros int d_nnz; /// are we allocated? bool d_allocated; // temporaries [number of rows][nonzeros per row] std::vector<std::vector<triplet> > d_aij; // counts entries added per row detran_utilities::vec_int d_counter; //---------------------------------------------------------------------------// // IMPLEMENTATION //---------------------------------------------------------------------------// /// internal preallocation void preallocate(); }; CALLOW_TEMPLATE_EXPORT(detran_utilities::SP<Matrix>) } // end namespace callow // Inline members #include "Matrix.i.hh" #endif /* callow_MATRIX_HH_ */
32.262443
81
0.556522
RLReed
4e25206edc6a95ad9851b555064f6086d560e772
1,134
cpp
C++
src/core/threading.cpp
hrxcodes/cbftp
bf2784007dcc4cc42775a2d40157c51b80383f81
[ "MIT" ]
8
2019-04-30T00:37:00.000Z
2022-02-03T13:35:31.000Z
src/core/threading.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
2
2019-11-19T12:46:13.000Z
2019-12-20T22:13:57.000Z
src/core/threading.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
9
2020-01-15T02:38:36.000Z
2022-02-15T20:05:20.000Z
#include "threading.h" #include <cassert> #include "signal.h" namespace Core { namespace Threading { namespace { struct ThreadFunc { void (*func)(void*); void* arg; }; void* runDetached(void* vtf) { blockAllRegisteredSignals(); ThreadFunc* tf = reinterpret_cast<ThreadFunc*>(vtf); tf->func(tf->arg); delete tf; return nullptr; } } // namespace void setThreadName(pthread_t thread, const std::string& name) { assert(name.length() <= 15); #ifdef _ISOC95_SOURCE pthread_setname_np(thread, name.c_str()); #endif } void setCurrentThreadName(const std::string& name) { assert(name.length() <= 15); setThreadName(pthread_self(), name); } pthread_t createDetachedThread(void (*func)(void*), void* arg) { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); ThreadFunc* tf = new ThreadFunc(); tf->func = func; tf->arg = arg; pthread_create(&thread, &attr, runDetached, static_cast<void*>(tf)); return thread; } void blockSignalsInternal() { blockAllRegisteredSignals(); } } // namespace Threading } // namespace Core
20.25
70
0.710758
hrxcodes
89efe1429b0fbffeb40ee7ec06e0c30f04edc8db
33,897
cpp
C++
src/gdnative_text_server.cpp
bruvzg/gdnative_text_server_template
cdbc4eefef7ba7ebf472a608ceaba24deb807704
[ "MIT" ]
1
2021-11-08T02:49:46.000Z
2021-11-08T02:49:46.000Z
src/gdnative_text_server.cpp
bruvzg/gdnative_text_server_template
cdbc4eefef7ba7ebf472a608ceaba24deb807704
[ "MIT" ]
null
null
null
src/gdnative_text_server.cpp
bruvzg/gdnative_text_server_template
cdbc4eefef7ba7ebf472a608ceaba24deb807704
[ "MIT" ]
null
null
null
/*************************************************************************/ /* gdnative_text_server.cpp */ /*************************************************************************/ #include "gdnative_text_server.h" static int features = 0; void *godot_text_server_constructor(godot_object *p_data) { printf("GDN Dummy TS: TS(%p)\n", p_data); godot_text_server_data_struct *data = (godot_text_server_data_struct *)core_api->godot_alloc(sizeof(godot_text_server_data_struct)); data->sever = p_data; return data; } void godot_text_server_destructor(void *p_data) { printf("GDN Dummy TS: ~TS()\n"); if (p_data != nullptr) { core_api->godot_free(p_data); } } godot_string godot_text_server_get_name(const void *p_data) { printf("GDN Dummy TS: get_name()\n"); godot_string ret; core_api->godot_string_new(&ret); core_api->godot_string_parse_utf8(&ret, "Dummy"); return ret; } godot_bool godot_text_server_has_feature(const void *p_data, godot_int p_feature) { printf("GDN Dummy TS: has_feature(%lld)\n", p_feature); return (features & p_feature) == p_feature; } bool godot_text_server_load_support_data(void *p_data, const godot_string *p_filename) { godot_char_string cs = core_api->godot_string_utf8(p_filename); printf("GDN Dummy TS: load_support_data(\"%s\")\n", core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return true; } godot_string godot_text_server_get_support_data_filename(const void *p_data) { printf("GDN Dummy TS: get_support_data_filename()\n"); godot_string ret; core_api->godot_string_new(&ret); return ret; } godot_string godot_text_server_get_support_data_info(const void *p_data) { printf("GDN Dummy TS: get_support_data_info()\n"); godot_string ret; core_api->godot_string_new(&ret); core_api->godot_string_parse_utf8(&ret, "Not supported."); return ret; } bool godot_text_server_save_support_data(void *p_data, const godot_string *p_filename) { godot_char_string cs = core_api->godot_string_utf8(p_filename); printf("GDN Dummy TS: save_support_data(\"%s\")\n", core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return false; } bool godot_text_server_is_locale_right_to_left(void *p_data, const godot_string *p_locale) { godot_char_string cs = core_api->godot_string_utf8(p_locale); printf("GDN Dummy TS: is_locale_right_to_left(\"%s\")\n", core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return false; } void godot_text_server_free_rid(void *p_data, godot_rid *p_rid) { printf("GDN Dummy TS: free(%llu)\n", core_api->godot_rid_get_id(p_rid)); godot_text_server_data_struct* data = (godot_text_server_data_struct *)p_data; uint64_t id = *((uint64_t *)p_rid); if (data->fonts.count(id) > 0) { data->fonts.erase(id); } if (data->buffers.count(id) > 0) { data->buffers.erase(id); } } bool godot_text_server_has_rid(void *p_data, godot_rid *p_rid) { printf("GDN Dummy TS: has(%llu)\n", core_api->godot_rid_get_id(p_rid)); godot_text_server_data_struct* data = (godot_text_server_data_struct *)p_data; uint64_t id = *((uint64_t *)p_rid); return (data->fonts.count(id) > 0) || (data->buffers.count(id) > 0); } godot_rid godot_text_server_create_font_system(void *p_data, const godot_string *p_name, int p_base_size) { godot_char_string cs = core_api->godot_string_utf8(p_name); printf("GDN Dummy TS: create_font_system(\"%s\", %d)\n", core_api->godot_char_string_get_data(&cs), p_base_size); core_api->godot_char_string_destroy(&cs); godot_text_server_data_struct* data = (godot_text_server_data_struct *)p_data; godot_rid r; *((uint64_t *)&r) = data->last_id; data->fonts[data->last_id] = font_data(); data->last_id++; return r; } godot_rid godot_text_server_create_font_resource(void *p_data, const godot_string *p_filename, int p_base_size) { godot_char_string cs = core_api->godot_string_utf8(p_filename); printf("GDN Dummy TS: create_font_resource(\"%s\", %d)\n", core_api->godot_char_string_get_data(&cs), p_base_size); core_api->godot_char_string_destroy(&cs); godot_rid r; // Return null RID, not implemented. core_api->godot_rid_new(&r); return r; } godot_rid godot_text_server_create_font_memory(void *p_data, const uint8_t *p_membuffer, size_t p_size, godot_string *p_type, int p_base_size) { godot_char_string cs = core_api->godot_string_utf8(p_type); printf("GDN Dummy TS: create_font_memory(%p[%zu], \"%s\" %d)\n", p_membuffer, p_size, core_api->godot_char_string_get_data(&cs), p_base_size); core_api->godot_char_string_destroy(&cs); godot_rid r; // Return null RID, not implemented. core_api->godot_rid_new(&r); return r; } float godot_text_server_font_get_height(void *p_data, godot_rid *p_font, int p_size) { printf("GDN Dummy TS: font_get_height(%lld, %d)\n", core_api->godot_rid_get_id(p_font), p_size); return 0.f; } float godot_text_server_font_get_ascent(void *p_data, godot_rid *p_font, int p_size) { printf("GDN Dummy TS: font_get_ascent(%lld, %d)\n", core_api->godot_rid_get_id(p_font), p_size); return 0.f; } float godot_text_server_font_get_descent(void *p_data, godot_rid *p_font, int p_size) { printf("GDN Dummy TS: font_get_descent(%lld, %d)\n", core_api->godot_rid_get_id(p_font), p_size); return 0.f; } float godot_text_server_font_get_underline_position(void *p_data, godot_rid *p_font, int p_size) { printf("GDN Dummy TS: font_get_underline_position(%lld, %d)\n", core_api->godot_rid_get_id(p_font), p_size); return 0.f; } float godot_text_server_font_get_underline_thickness(void *p_data, godot_rid *p_font, int p_size) { printf("GDN Dummy TS: font_get_underline_thickness(%lld, %d)\n", core_api->godot_rid_get_id(p_font), p_size); return 0.f; } void godot_text_server_font_set_antialiased(void *p_data, godot_rid *p_font, bool p_enabled) { printf("GDN Dummy TS: font_set_antialiased(%lld, %s)\n", core_api->godot_rid_get_id(p_font), p_enabled ? "T" : "F"); } bool godot_text_server_font_get_antialiased(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_antialiased(%lld)\n", core_api->godot_rid_get_id(p_font)); return false; } godot_dictionary godot_text_server_font_get_feature_list(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_feature_list(%lld)\n", core_api->godot_rid_get_id(p_font)); godot_dictionary ret; core_api->godot_dictionary_new(&ret); return ret; } godot_dictionary godot_text_server_font_get_variation_list(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_variation_list(%lld)\n", core_api->godot_rid_get_id(p_font)); godot_dictionary ret; core_api->godot_dictionary_new(&ret); return ret; } void godot_text_server_font_set_variation(void *p_data, godot_rid *p_font, const godot_string *p_variation, double p_value) { godot_char_string cs = core_api->godot_string_utf8(p_variation); printf("GDN Dummy TS: font_set_variation(%lld, %s, %f)\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs), p_value); core_api->godot_char_string_destroy(&cs); } double godot_text_server_font_get_variation(void *p_data, godot_rid *p_font, const godot_string *p_variation) { godot_char_string cs = core_api->godot_string_utf8(p_variation); printf("GDN Dummy TS: font_get_variation(%lld, %s)\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return 0.f; } void godot_text_server_font_set_distance_field_hint(void *p_data, godot_rid *p_font, bool p_enabled) { printf("GDN Dummy TS: font_set_distance_field_hint(%lld, %s)\n", core_api->godot_rid_get_id(p_font), p_enabled ? "T" : "F"); } bool godot_text_server_font_get_distance_field_hint(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_distance_field_hint(%lld)\n", core_api->godot_rid_get_id(p_font)); return false; } void godot_text_server_font_set_hinting(void *p_data, godot_rid *p_font, godot_int p_hint) { printf("GDN Dummy TS: font_set_hinting(%lld, %lld)\n", core_api->godot_rid_get_id(p_font), p_hint); } godot_int godot_text_server_font_get_hinting(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_hinting(%lld)\n", core_api->godot_rid_get_id(p_font)); return 0; } void godot_text_server_font_set_force_autohinter(void *p_data, godot_rid *p_font, bool p_enabled) { printf("GDN Dummy TS: font_set_force_autohinter(%lld, %s)\n", core_api->godot_rid_get_id(p_font), p_enabled ? "T" : "F"); } bool godot_text_server_font_get_force_autohinter(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_force_autohinter(%lld)\n", core_api->godot_rid_get_id(p_font)); return false; } bool godot_text_server_font_has_char(void *p_data, godot_rid *p_font, char32_t p_char) { printf("GDN Dummy TS: font_has_char(%lld, %x)\n", core_api->godot_rid_get_id(p_font), p_char); return false; } godot_string godot_text_server_font_get_supported_chars(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_supported_chars%lld)\n", core_api->godot_rid_get_id(p_font)); godot_string ret; core_api->godot_string_new(&ret); return ret; } bool godot_text_server_font_has_outline(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_has_outline(%lld)\n", core_api->godot_rid_get_id(p_font)); return false; } int godot_text_server_font_get_base_size(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: get_base_size(%lld)\n", core_api->godot_rid_get_id(p_font)); return 16; } bool godot_text_server_font_is_language_supported(void *p_data, godot_rid *p_font, const godot_string *p_language) { godot_char_string cs = core_api->godot_string_utf8(p_language); printf("GDN Dummy TS: font_is_language_supported(%lld, \"%s\")\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return false; } void godot_text_server_font_set_language_support_override(void *p_data, godot_rid *p_font, const godot_string *p_language, bool p_supported) { godot_char_string cs = core_api->godot_string_utf8(p_language); printf("GDN Dummy TS: font_set_language_support_override(%lld, \"%s\", %s)\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs), p_supported? "T" : "F"); core_api->godot_char_string_destroy(&cs); } bool godot_text_server_font_get_language_support_override(void *p_data, godot_rid *p_font, const godot_string *p_language) { godot_char_string cs = core_api->godot_string_utf8(p_language); printf("GDN Dummy TS: font_get_language_support_override(%lld, \"%s\")\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return false; } void godot_text_server_font_remove_language_support_override(void *p_data, godot_rid *p_font, const godot_string *p_language) { godot_char_string cs = core_api->godot_string_utf8(p_language); printf("GDN Dummy TS: font_remove_language_support_override(%lld, \"%s\")\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); } godot_packed_string_array godot_text_server_font_get_language_support_overrides(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_language_support_overrides(%lld\n)", core_api->godot_rid_get_id(p_font)); godot_packed_string_array ret; core_api->godot_packed_string_array_new(&ret); return ret; } bool godot_text_server_font_is_script_supported(void *p_data, godot_rid *p_font, const godot_string *p_script) { godot_char_string cs = core_api->godot_string_utf8(p_script); printf("GDN Dummy TS: font_is_script_supported(%lld, \"%s\")\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return false; } void godot_text_server_font_set_script_support_override(void *p_data, godot_rid *p_font, const godot_string *p_script, bool p_supported) { godot_char_string cs = core_api->godot_string_utf8(p_script); printf("GDN Dummy TS: font_set_script_support_override(%lld, \"%s\", %s)\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs), p_supported? "T" : "F"); core_api->godot_char_string_destroy(&cs); } bool godot_text_server_font_get_script_support_override(void *p_data, godot_rid *p_font, const godot_string *p_script) { godot_char_string cs = core_api->godot_string_utf8(p_script); printf("GDN Dummy TS: font_get_script_support_override(%lld, \"%s\")\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); return false; } void godot_text_server_font_remove_script_support_override(void *p_data, godot_rid *p_font, const godot_string *p_script) { godot_char_string cs = core_api->godot_string_utf8(p_script); printf("GDN Dummy TS: font_remove_script_support_override(%lld, \"%s\")\n", core_api->godot_rid_get_id(p_font), core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); } godot_packed_string_array godot_text_server_font_get_script_support_overrides(void *p_data, godot_rid *p_font) { printf("GDN Dummy TS: font_get_script_support_overrides(%lld\n)", core_api->godot_rid_get_id(p_font)); godot_packed_string_array ret; core_api->godot_packed_string_array_new(&ret); return ret; } uint32_t godot_text_server_font_get_glyph_index(void * p_data, godot_rid *p_font, char32_t p_char, char32_t p_var_selector) { printf("GDN Dummy TS: font_get_glyph_index(%lld, %x %x\n)", core_api->godot_rid_get_id(p_font), p_char, p_var_selector); return 0; } godot_vector2 godot_text_server_font_get_glyph_advance(void *p_data, godot_rid *p_font, uint32_t p_char, int p_size) { printf("GDN Dummy TS: _font_get_glyph_advance(%lld, %x, %d)\n", core_api->godot_rid_get_id(p_font), p_char, p_size); godot_vector2 ret; core_api->godot_vector2_new(&ret, 0.f, 0.f); return ret; } godot_vector2 godot_text_server_font_get_glyph_kerning(void *p_data, godot_rid *p_font, uint32_t p_char_a, uint32_t p_char_b, int p_size) { printf("GDN Dummy TS: _font_get_glyph_kerning(%lld, %x, %x, %d)\n", core_api->godot_rid_get_id(p_font), p_char_a, p_char_b, p_size); godot_vector2 ret; core_api->godot_vector2_new(&ret, 0.f, 0.f); return ret; } godot_vector2 godot_text_server_font_draw_glyph(void *p_data, godot_rid *p_font, godot_rid *p_canvas, int p_size, const godot_vector2 *p_pos, uint32_t p_glyph, const godot_color *p_color) { printf("GDN Dummy TS: font_draw_glyph(%lld, %lld, %d, [x:%f y:%f], %u, [r:%f g:%f b:%f])\n", core_api->godot_rid_get_id(p_font), core_api->godot_rid_get_id(p_canvas), p_size, core_api->godot_vector2_get_x(p_pos), core_api->godot_vector2_get_y(p_pos), p_glyph, core_api->godot_color_get_r(p_color), core_api->godot_color_get_g(p_color), core_api->godot_color_get_b(p_color) ); godot_vector2 ret; core_api->godot_vector2_new(&ret, 0.f, 0.f); return ret; } godot_vector2 godot_text_server_font_draw_glyph_outline(void *p_data, godot_rid *p_font, godot_rid *p_canvas, int p_size, int p_outline_size, const godot_vector2 *p_pos, uint32_t p_glyph, const godot_color *p_color) { printf("GDN Dummy TS: font_draw_glyph_outline(%lld, %lld, %d %d, [x:%f y:%f], %u, [r:%f g:%f b:%f])\n", core_api->godot_rid_get_id(p_font), core_api->godot_rid_get_id(p_canvas), p_size, p_outline_size, core_api->godot_vector2_get_x(p_pos), core_api->godot_vector2_get_y(p_pos), p_glyph, core_api->godot_color_get_r(p_color), core_api->godot_color_get_g(p_color), core_api->godot_color_get_b(p_color) ); godot_vector2 ret; core_api->godot_vector2_new(&ret, 0.f, 0.f); return ret; } float godot_text_server_font_get_oversampling(void * p_data) { printf("GDN Dummy TS: font_get_oversampling()\n"); return 0.f; } void godot_text_server_font_set_oversampling(void *p_data, float p_oversampling) { printf("GDN Dummy TS: font_set_oversampling(%f)\n", p_oversampling); } godot_packed_string_array godot_text_server_get_system_fonts(void *p_data) { printf("GDN Dummy TS: godot_text_server_get_system_fonts()\n"); godot_packed_string_array ret; core_api->godot_packed_string_array_new(&ret); return ret; } godot_rid godot_text_server_create_shaped_text(void *p_data, godot_int p_direction, godot_int p_orientation) { printf("GDN Dummy TS: create_shaped_text(%lld, %lld)\n", p_direction, p_orientation); godot_text_server_data_struct *data = (godot_text_server_data_struct *)p_data; godot_rid r; *((uint64_t *)&r) = data->last_id; data->buffers[data->last_id] = text_buffer(); data->last_id++; return r; } void godot_text_server_shaped_text_clear(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_clear(%lld)\n", core_api->godot_rid_get_id(p_shaped)); godot_text_server_data_struct *data = (godot_text_server_data_struct *)p_data; uint64_t id = *((uint64_t *)p_shaped); if (data->fonts.count(id) == 0) { printf("Invalid RID\n"); } //... } void godot_text_server_shaped_text_set_direction(void *p_data, godot_rid *p_shaped, godot_int p_direction) { printf("GDN Dummy TS: shaped_text_set_direction(%lld, %lld)\n", core_api->godot_rid_get_id(p_shaped), p_direction); } godot_int godot_text_server_shaped_text_get_direction(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_direction(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return 0; } void godot_text_server_shaped_text_set_bidi_override(void *p_data, godot_rid *p_shaped, const godot_packed_vector2i_array *p_overrides) { printf("GDN Dummy TS: shaped_text_set_bidi_override(%lld, [...])\n", core_api->godot_rid_get_id(p_shaped)); } void godot_text_server_shaped_text_set_orientation(void *p_data, godot_rid *p_shaped, godot_int p_orientation) { printf("GDN Dummy TS: shaped_text_set_orientation(%lld, %lld)\n", core_api->godot_rid_get_id(p_shaped), p_orientation); } godot_int godot_text_server_shaped_text_get_orientation(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_orientation(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return 0; } void godot_text_server_shaped_text_set_preserve_invalid(void *p_data, godot_rid *p_shaped, bool p_enabled) { printf("GDN Dummy TS: shaped_text_set_preserve_invalid(%lld, %s)\n", core_api->godot_rid_get_id(p_shaped), p_enabled ? "T" : "F"); } bool godot_text_server_shaped_text_get_preserve_invalid(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_preserve_invalid(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return false; } void godot_text_server_shaped_text_set_preserve_control(void *p_data, godot_rid *p_shaped, bool p_enabled) { printf("GDN Dummy TS: shaped_text_set_preserve_control(%lld, %s)\n", core_api->godot_rid_get_id(p_shaped), p_enabled ? "T" : "F"); } bool godot_text_server_shaped_text_get_preserve_control(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_preserve_control(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return false; } bool godot_text_server_shaped_text_add_string(void *p_data, godot_rid *p_shaped, const godot_string *p_text, const godot_rid **p_fonts, int p_size, const godot_dictionary *p_ot_features, const godot_string *p_language) { godot_char_string cs_t = core_api->godot_string_utf8(p_text); printf("GDN Dummy TS: shaped_text_add_string(%lld, \"%s\", [ ", core_api->godot_rid_get_id(p_shaped), core_api->godot_char_string_get_data(&cs_t)); core_api->godot_char_string_destroy(&cs_t); const godot_rid *rid = p_fonts[0]; while (rid != nullptr) { printf("%lld ", core_api->godot_rid_get_id(rid)); rid++; } godot_char_string cs_l = core_api->godot_string_utf8(p_language); printf("], %d, \"%s\", [])\n", p_size, core_api->godot_char_string_get_data(&cs_l)); core_api->godot_char_string_destroy(&cs_l); return false; } bool godot_text_server_shaped_text_add_object(void *p_data, godot_rid *p_shaped, const godot_variant *p_id, const godot_vector2 *p_size, godot_int p_align) { printf("GDN Dummy TS: shaped_text_add_object(%lld, [%p], [x:%f y:%f], %lld)\n", core_api->godot_rid_get_id(p_shaped), p_id, core_api->godot_vector2_get_x(p_size), core_api->godot_vector2_get_y(p_size), p_align); return false; } bool godot_text_server_shaped_text_resize_object(void *p_data, godot_rid *p_shaped, const godot_variant *p_id, const godot_vector2 *p_size, godot_int p_align) { printf("GDN Dummy TS: shaped_text_resize_object(%lld, [%p], [x:%f y:%f], %lld)\n", core_api->godot_rid_get_id(p_shaped), p_id, core_api->godot_vector2_get_x(p_size), core_api->godot_vector2_get_y(p_size), p_align); return false; } godot_rid godot_text_server_shaped_text_substr(void *p_data, godot_rid *p_shaped, godot_int p_start, godot_int p_length) { printf("GDN Dummy TS: shaped_text_substr(%lld, %lld, %lld)\n", core_api->godot_rid_get_id(p_shaped), p_start, p_length); godot_rid r; *((uint64_t *)&r) = 10000 + *(uint64_t *)&p_shaped; return r; } godot_rid godot_text_server_shaped_text_get_parent(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_parent(%lld)\n", core_api->godot_rid_get_id(p_shaped)); godot_rid r; *((uint64_t *)&r) = *(uint64_t *)&p_shaped - 10000; return r; } float godot_text_server_shaped_text_fit_to_width(void *p_data, godot_rid *p_shaped, float p_width, uint8_t p_flags) { printf("GDN Dummy TS: shaped_text_fit_to_width(%lld, %f, %d)\n", core_api->godot_rid_get_id(p_shaped), p_width, p_flags); return 0.f; } float godot_text_server_shaped_text_tab_align(void *p_data, godot_rid *p_shaped, godot_packed_float32_array *p_tab_stops) { printf("GDN Dummy TS: shaped_text_tab_align(%lld, [ ", core_api->godot_rid_get_id(p_shaped)); for (int i = 0; i < core_api->godot_packed_float32_array_size(p_tab_stops); i++) { printf("%f ", core_api->godot_packed_float32_array_get(p_tab_stops, i)); } printf("])\n"); return 0.f; } bool godot_text_server_shaped_text_shape(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_shape(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return false; } bool godot_text_server_shaped_text_update_breaks(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_update_breaks(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return false; } bool godot_text_server_shaped_text_update_justification_ops(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_update_justification_ops(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return false; } bool godot_text_server_shaped_text_is_ready(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_is_ready(%lld)\n", core_api->godot_rid_get_id(p_shaped)); return false; } godot_packed_glyph_array godot_text_server_shaped_text_get_glyphs(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_glyphs(%lld)\n", core_api->godot_rid_get_id(p_shaped)); godot_packed_glyph_array ret; text_api->godot_packed_glyph_array_new(&ret); return ret; } godot_vector2i godot_text_server_shaped_text_get_range(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_range(%lld)\n", core_api->godot_rid_get_id(p_shaped)); godot_vector2i ret; core_api->godot_vector2i_new(&ret, 0, 0); return ret; } godot_packed_glyph_array godot_text_server_shaped_text_sort_logical(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_sort_logical(%lld)\n", core_api->godot_rid_get_id(p_shaped)); godot_packed_glyph_array ret; text_api->godot_packed_glyph_array_new(&ret); return ret; } godot_packed_vector2i_array godot_text_server_shaped_text_get_line_breaks_adv(void *p_data, godot_rid *p_shaped, godot_packed_float32_array *p_widths, int p_start, bool p_once, uint8_t p_flags) { printf("GDN Dummy TS: shaped_text_get_line_breaks_adv(%lld", core_api->godot_rid_get_id(p_shaped)); for (int i = 0; i < core_api->godot_packed_float32_array_size(p_widths); i++) { printf("%f ", core_api->godot_packed_float32_array_get(p_widths, i)); } printf(", %d, %s, %d)\n", p_start, p_once ? "T" : "F", p_flags); godot_packed_vector2i_array ret; core_api->godot_packed_vector2i_array_new(&ret); return ret; } godot_packed_vector2i_array godot_text_server_shaped_text_get_line_breaks(void *p_data, godot_rid *p_shaped, float p_width, int p_start, uint8_t p_flags) { printf("GDN Dummy TS: shaped_text_get_line_breaks(%lld, %f, %d, %d)", core_api->godot_rid_get_id(p_shaped), p_width, p_start, p_flags); godot_packed_vector2i_array ret; core_api->godot_packed_vector2i_array_new(&ret); return ret; } godot_packed_vector2i_array godot_text_server_shaped_text_get_word_breaks(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_word_breaks(%lld)", core_api->godot_rid_get_id(p_shaped)); godot_packed_vector2i_array ret; core_api->godot_packed_vector2i_array_new(&ret); return ret; } godot_array godot_text_server_shaped_text_get_objects(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_objects(%lld)", core_api->godot_rid_get_id(p_shaped)); godot_array ret; godot_array_new(&ret); return ret; } godot_rect2 godot_text_server_shaped_text_get_object_rect(void *p_data, godot_rid *p_shaped, const godot_variant *p_id) { printf("GDN Dummy TS: shaped_text_get_object_rect(%lld, [%p])", core_api->godot_rid_get_id(p_shaped), p_id); godot_rect2 ret; core_api->godot_rect2_new(&ret, 0.f, 0.f, 0.f, 0.f); return ret; } godot_vector2 godot_text_server_shaped_text_get_size(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_size(%lld)", core_api->godot_rid_get_id(p_shaped)); godot_vector2 ret; core_api->godot_vector2_new(&ret, 0.f, 0.f); return ret; } float godot_text_server_shaped_text_get_ascent(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_ascent(%lld)", core_api->godot_rid_get_id(p_shaped)); return 0.f; } float godot_text_server_shaped_text_get_descent(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_descent(%lld)", core_api->godot_rid_get_id(p_shaped)); return 0.f; } float godot_text_server_shaped_text_get_width(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_width(%lld)", core_api->godot_rid_get_id(p_shaped)); return 0.f; } float godot_text_server_shaped_text_get_underline_position(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_underline_position(%lld)", core_api->godot_rid_get_id(p_shaped)); return 0.f; } float godot_text_server_shaped_text_get_underline_thickness(void *p_data, godot_rid *p_shaped) { printf("GDN Dummy TS: shaped_text_get_underline_thickness(%lld)", core_api->godot_rid_get_id(p_shaped)); return 0.f; } godot_string godot_text_server_format_number(void *p_data, const godot_string *p_text, const godot_string *p_lang) { godot_char_string cs = core_api->godot_string_utf8(p_text); godot_char_string csl = core_api->godot_string_utf8(p_lang); printf("GDN Dummy TS: format_number(\"%s\", \"%s\")\n", core_api->godot_char_string_get_data(&cs), core_api->godot_char_string_get_data(&csl)); core_api->godot_char_string_destroy(&cs); core_api->godot_char_string_destroy(&csl); godot_string ret; godot_string_new_copy(&ret, p_text); return ret; } godot_string godot_text_server_parse_number(void *p_data, const godot_string *p_text, const godot_string *p_lang) { godot_char_string cs = core_api->godot_string_utf8(p_text); godot_char_string csl = core_api->godot_string_utf8(p_lang); printf("GDN Dummy TS: parse_number(\"%s\", \"%s\")\n", core_api->godot_char_string_get_data(&cs), core_api->godot_char_string_get_data(&csl)); core_api->godot_char_string_destroy(&cs); core_api->godot_char_string_destroy(&csl); godot_string ret; godot_string_new_copy(&ret, p_text); return ret; } godot_string godot_text_server_percent_sign(void *p_data, const godot_string *p_lang) { godot_char_string cs = core_api->godot_string_utf8(p_lang); printf("GDN Dummy TS: percent_sign(\"%s\")\n", core_api->godot_char_string_get_data(&cs)); core_api->godot_char_string_destroy(&cs); godot_string ret; core_api->godot_string_new(&ret); core_api->godot_string_parse_utf8(&ret, "%"); return ret; } const godot_text_interface_gdnative interface_struct = { GODOT_TEXT_API_MAJOR, GODOT_TEXT_API_MINOR, &godot_text_server_constructor, &godot_text_server_destructor, &godot_text_server_get_name, &godot_text_server_has_feature, &godot_text_server_load_support_data, &godot_text_server_get_support_data_filename, &godot_text_server_get_support_data_info, &godot_text_server_save_support_data, &godot_text_server_is_locale_right_to_left, &godot_text_server_free_rid, &godot_text_server_has_rid, &godot_text_server_create_font_system, &godot_text_server_create_font_resource, &godot_text_server_create_font_memory, &godot_text_server_font_get_height, &godot_text_server_font_get_ascent, &godot_text_server_font_get_descent, &godot_text_server_font_get_underline_position, &godot_text_server_font_get_underline_thickness, &godot_text_server_font_set_antialiased, &godot_text_server_font_get_antialiased, &godot_text_server_font_get_feature_list, &godot_text_server_font_get_variation_list, &godot_text_server_font_set_variation, &godot_text_server_font_get_variation, &godot_text_server_font_set_distance_field_hint, &godot_text_server_font_get_distance_field_hint, &godot_text_server_font_set_hinting, &godot_text_server_font_get_hinting, &godot_text_server_font_set_force_autohinter, &godot_text_server_font_get_force_autohinter, &godot_text_server_font_has_char, &godot_text_server_font_get_supported_chars, &godot_text_server_font_has_outline, &godot_text_server_font_get_base_size, &godot_text_server_font_is_language_supported, &godot_text_server_font_set_language_support_override, &godot_text_server_font_get_language_support_override, &godot_text_server_font_remove_language_support_override, &godot_text_server_font_get_language_support_overrides, &godot_text_server_font_is_script_supported, &godot_text_server_font_set_script_support_override, &godot_text_server_font_get_script_support_override, &godot_text_server_font_remove_script_support_override, &godot_text_server_font_get_script_support_overrides, &godot_text_server_font_get_glyph_index, &godot_text_server_font_get_glyph_advance, &godot_text_server_font_get_glyph_kerning, &godot_text_server_font_draw_glyph, &godot_text_server_font_draw_glyph_outline, &godot_text_server_font_get_oversampling, &godot_text_server_font_set_oversampling, &godot_text_server_get_system_fonts, &godot_text_server_create_shaped_text, &godot_text_server_shaped_text_clear, &godot_text_server_shaped_text_set_direction, &godot_text_server_shaped_text_get_direction, &godot_text_server_shaped_text_set_bidi_override, &godot_text_server_shaped_text_set_orientation, &godot_text_server_shaped_text_get_orientation, &godot_text_server_shaped_text_set_preserve_invalid, &godot_text_server_shaped_text_get_preserve_invalid, &godot_text_server_shaped_text_set_preserve_control, &godot_text_server_shaped_text_get_preserve_control, &godot_text_server_shaped_text_add_string, &godot_text_server_shaped_text_add_object, &godot_text_server_shaped_text_resize_object, &godot_text_server_shaped_text_substr, &godot_text_server_shaped_text_get_parent, &godot_text_server_shaped_text_fit_to_width, &godot_text_server_shaped_text_tab_align, &godot_text_server_shaped_text_shape, &godot_text_server_shaped_text_update_breaks, &godot_text_server_shaped_text_update_justification_ops, &godot_text_server_shaped_text_is_ready, &godot_text_server_shaped_text_get_glyphs, &godot_text_server_shaped_text_get_range, &godot_text_server_shaped_text_sort_logical, &godot_text_server_shaped_text_get_line_breaks_adv, &godot_text_server_shaped_text_get_line_breaks, &godot_text_server_shaped_text_get_word_breaks, &godot_text_server_shaped_text_get_objects, &godot_text_server_shaped_text_get_object_rect, &godot_text_server_shaped_text_get_size, &godot_text_server_shaped_text_get_ascent, &godot_text_server_shaped_text_get_descent, &godot_text_server_shaped_text_get_width, &godot_text_server_shaped_text_get_underline_position, &godot_text_server_shaped_text_get_underline_thickness, &godot_text_server_format_number, &godot_text_server_parse_number, &godot_text_server_percent_sign, }; /*************************************************************************/ void GDN_EXPORT godot_text_server_gdnative_init(godot_gdnative_init_options *p_options) { printf("GDN Dummy TS: GDN API init - "); core_api = p_options->api_struct; for (unsigned int i = 0; i < core_api->num_extensions; i++) { if (core_api->extensions[i]->type == GDNATIVE_EXT_TEXT) { text_api = reinterpret_cast<const godot_gdnative_ext_text_api_struct *>(core_api->extensions[i]); } } if (text_api != nullptr && core_api != nullptr) { printf("OK\n"); } else { printf("Failed\n"); } } void GDN_EXPORT godot_text_server_gdnative_terminate(godot_gdnative_terminate_options *p_options) { printf("GDN Dummy TS: GDN API terminated\n"); } void GDN_EXPORT godot_text_server_gdnative_singleton() { printf("GDN Dummy TS: Server register - "); if (text_api != nullptr && core_api != nullptr) { godot_string name; core_api->godot_string_new(&name); core_api->godot_string_parse_utf8(&name, "Dummy"); text_api->godot_text_register_interface(&interface_struct, &name, features); core_api->godot_string_destroy(&name); printf("OK\n"); } else { printf("Failed\n"); } } void GDN_EXPORT godot_text_server_nativescript_init(void *p_handle) { printf("GDN Dummy TS: NativeScript API init\n"); } void GDN_EXPORT godot_text_server_nativescript_terminate(void *p_handle) { printf("GDN Dummy TS: NativeScript API terminated\n"); }
42.37125
220
0.789244
bruvzg
89f402ef38b6778d425ba5d152b2d4114472b980
624
hpp
C++
src/Verde/audio/AudioSfx.hpp
Cannedfood/Verde2D
3a09e2ecc6b62281e5190183faef55c8f0447d27
[ "CC0-1.0" ]
null
null
null
src/Verde/audio/AudioSfx.hpp
Cannedfood/Verde2D
3a09e2ecc6b62281e5190183faef55c8f0447d27
[ "CC0-1.0" ]
null
null
null
src/Verde/audio/AudioSfx.hpp
Cannedfood/Verde2D
3a09e2ecc6b62281e5190183faef55c8f0447d27
[ "CC0-1.0" ]
null
null
null
#pragma once #include "AudioData.hpp" #include <glm/vec2.hpp> #include <memory> #include <vector> #include <mutex> class AudioSfx { struct Source { unsigned source; std::shared_ptr<AudioData> data; }; unsigned mNextSource; std::vector<Source> mSources; std::mutex mMutex; // Requires ownership of mMutex Source& getSource(); public: AudioSfx(size_t n_sources); ~AudioSfx(); void update(); void play(const std::shared_ptr<AudioData>& data, const glm::vec2& p, float gain = 1, float pitch = 1); void play(const std::shared_ptr<AudioData>& data, float gain = 1, float pitch = 1); };
19.5
104
0.68109
Cannedfood
89f777f0bd2de0b4f9a49ceaec83cc03e05e032f
2,995
hpp
C++
plugindev/exampleGuipluginSink.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
245
2020-10-24T16:27:13.000Z
2022-03-31T03:01:11.000Z
plugindev/exampleGuipluginSink.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
41
2021-01-13T11:30:42.000Z
2022-01-14T14:36:11.000Z
plugindev/exampleGuipluginSink.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
43
2020-12-11T15:28:19.000Z
2022-03-20T11:55:58.000Z
/*F*************************************************************************** * This file is part of openSMILE. * * Copyright (c) audEERING GmbH. All rights reserved. * See the file COPYING for details on license terms. ***************************************************************************E*/ /* openSMILE component: example dataSink: reads data from data memory and outputs it to console/logfile (via smileLogger) this component is also useful for debugging */ #ifndef __CEXAMPLEGUIPLUGINSINK_HPP #define __CEXAMPLEGUIPLUGINSINK_HPP #include <core/smileCommon.hpp> #include <core/dataSink.hpp> #include <wx/wx.h> #define COMPONENT_DESCRIPTION_CEXAMPLEGUIPLUGINSINK "This is an example of a cDataSink descendant. It reads data from the data memory and prints it to the console. This component is intended as a template for developers." #define COMPONENT_NAME_CEXAMPLEGUIPLUGINSINK "cExampleGuipluginSink" #undef class #include <wx/sizer.h> class wxImagePanel : public wxPanel { wxBitmap image; public: bool showImg; wxImagePanel(wxFrame* parent, wxString file, wxBitmapType format); void paintEvent(wxPaintEvent & evt); void paintNow(); void render(wxDC& dc); DECLARE_EVENT_TABLE() }; // the ID we'll use to identify our event const int VAD_UPDATE_ID = 100000; class MyFrame: public wxFrame { //wxBitmap bmp; wxImagePanel * drawPane; wxCheckBox *m_cb; public: MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); /* void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event);*/ // this is called when the event from the thread is received void onVadUpdate(wxCommandEvent& evt) { // get the number sent along the event and use it to update the GUI if (evt.GetInt()==1) { //m_cb->SetValue( true ); drawPane->showImg = true; drawPane->paintNow(); } else { //m_cb->SetValue( false ); drawPane->showImg = false; drawPane->paintNow(); } } DECLARE_EVENT_TABLE() }; class MyApp: public wxApp { virtual bool OnInit() override; public: MyFrame * mframe; }; class cExampleGuipluginSink : public cDataSink { private: const char *filename; FILE * fHandle; int lag; //wxCommandEvent &myevent; //( wxEVT_COMMAND_TEXT_UPDATED, VAD_UPDATE_ID ); int old; smileThread guiThr; //gcroot<openSmilePluginGUI::TestForm^> fo; protected: SMILECOMPONENT_STATIC_DECL_PR virtual void myFetchConfig() override; //virtual int myConfigureInstance() override; virtual int myFinaliseInstance() override; virtual eTickResult myTick(long long t) override; public: SMILECOMPONENT_STATIC_DECL MyApp* pApp; cExampleGuipluginSink(const char *_name); virtual ~cExampleGuipluginSink(); }; #endif // __CEXAMPLEGUIPLUGINSINK_HPP
22.350746
221
0.644741
elinjammal
89fd6fa89e947f387464f62ff992561bb592573a
1,660
cpp
C++
chapter18/purrForAllMammal13.cpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
2
2022-01-08T03:31:25.000Z
2022-03-09T01:21:54.000Z
chapter18/purrForAllMammal13.cpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
null
null
null
chapter18/purrForAllMammal13.cpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
1
2022-03-09T01:26:01.000Z
2022-03-09T01:26:01.000Z
/********************************************************* * * Answer to exercise 1 in chapter 18 * * Modified 18.5 Sams Teach Yourself C++ in 24 Hours by Rogers Cadenhead * and Jesse Liberty * * Somehow, the dynamic cast appears to work and purr() is called regardless * if the Mammal is actually a Cat. So it fails for Dog because Dogs are not * supposed to purr. * * Compiled with g++ (GCC) 11.1.0 * *********************************************************/ #include <iostream> using std::cout; using std::cin; class Mammal { public: Mammal():age(1) { cout << "Mammal constructor ...\n"; } virtual ~Mammal() { cout << "Mammal destructor ...\n"; } virtual void speak() const { cout << "Mammal speak ...\n"; } protected: int age; }; class Cat: public Mammal { public: Cat() { cout << "Cat constructor ...\n"; } ~Cat() { cout << "Cat destructor ...\n"; } void speak() const { cout << "Meow!\n"; } void purr() const { cout << "Rrrrrrrrrrr!\n"; } }; class Dog : public Mammal { public: Dog() { cout << "Dog contructor ...\n"; } ~Dog() { cout << "dog destructor ...\n"; } void speak() const { cout << "Whoof!\n"; } }; int main() { const int numberMammals = 3; Mammal* zoo[numberMammals]; Mammal *pMammal = 0; int choice, i; for (i = 0; i < numberMammals; i++) { cout << "(1) Dog (2) Cat: "; cin >> choice; if (choice == 1) pMammal = new Dog; else pMammal = new Cat; zoo[i] = pMammal; } cout << "\n"; for (i = 0; i < numberMammals; i++) { zoo[i]->speak(); Cat *pRealCat = dynamic_cast<Cat *> (zoo[i]); pRealCat->purr(); // Dog will purr delete zoo[i]; cout << "\n"; } return 0; }
19.761905
75
0.54759
not-sponsored
d600dea9b75219920534179fafb08bd200957a2a
859
cpp
C++
src/modules/lib/WindowPreferencesType.cpp
Thorsten-Geppert/Warehouse
b064e5b422d0b484ca702cc4433cbda90f40e009
[ "BSD-3-Clause" ]
null
null
null
src/modules/lib/WindowPreferencesType.cpp
Thorsten-Geppert/Warehouse
b064e5b422d0b484ca702cc4433cbda90f40e009
[ "BSD-3-Clause" ]
null
null
null
src/modules/lib/WindowPreferencesType.cpp
Thorsten-Geppert/Warehouse
b064e5b422d0b484ca702cc4433cbda90f40e009
[ "BSD-3-Clause" ]
null
null
null
#include "WindowPreferencesType.h" void WindowPreferencesType::SetSize(const wxSize &size) { this->size = size; } void WindowPreferencesType::SetSize(const int width, const int height) { this->size = wxSize(width, height); } wxSize WindowPreferencesType::GetSize() const { return size; } void WindowPreferencesType::GetSize(int *width, int *height) const { if(width) *width = GetSize().GetWidth(); if(height) *height = GetSize().GetHeight(); } void WindowPreferencesType::SetPosition(const wxPoint &position) { this->position = position; } void WindowPreferencesType::SetPosition(const int x, const int y) { this->position = wxPoint(x, y); } wxPoint WindowPreferencesType::GetPosition() const { return position; } void WindowPreferencesType::GetPosition(int *x, int *y) const { if(x) *x = GetPosition().x; if(y) *y = GetPosition().y; }
22.605263
72
0.724098
Thorsten-Geppert
d605ce279eafa590152236ce7bc86eaccd9f24a0
4,831
cpp
C++
Src/sound/SoundPlayerPool.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/sound/SoundPlayerPool.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/sound/SoundPlayerPool.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "Common.h" #include "SoundPlayerPool.h" #include <algorithm> #include <cjson/json.h> #include "HostBase.h" #include "Preferences.h" static SoundPlayerPool* s_instance = 0; static const int kMaxPooledPlayers = 0; static const int kMaxPlayers = 5; SoundPlayerPool* SoundPlayerPool::instance() { if (!s_instance) new SoundPlayerPool; return s_instance; } SoundPlayerPool::SoundPlayerPool() : m_purgeTimer(HostBase::instance()->masterTimer(), this, &SoundPlayerPool::purgeTimerFired) { s_instance = this; bool ret; LSError error; LSErrorInit(&error); ret = LSRegister(NULL, &m_lsHandle, &error); if (!ret) { g_warning("Failed to register handler: %s", error.message); LSErrorFree(&error); return; } ret = LSGmainAttach(m_lsHandle, HostBase::instance()->mainLoop(), &error); if (!ret) { g_warning("Failed to attach service to main loop: %s", error.message); LSErrorFree(&error); return; } } SoundPlayerPool::~SoundPlayerPool() { s_instance = 0; // no-op } sptr<SoundPlayer> SoundPlayerPool::play(const std::string& filePath, const std::string& streamClass, bool repeat, int duration) { sptr<SoundPlayer> player = getPooledPlayer(); if (!player.get()) { if (SoundPlayer::m_numInstances >= kMaxPlayers) { g_warning ("Exceeded maximum instances of sound players %d, ignoring request", kMaxPlayers); return 0; } player = new SoundPlayer; } // Add to list of active players m_activePlayers.push_back(player); player->play(filePath, streamClass, repeat, duration); return player; } void SoundPlayerPool::stop(sptr<SoundPlayer> player) { if (player.get()) player->stop(); // once the player is asynchronously closed, it will add // itself to the pool of dormant clients } void SoundPlayerPool::playFeedback(const std::string& name, const std::string& sinkName) { if (sinkName.empty() && !Preferences::instance()->playFeedbackSounds()) return; bool ret; LSError error; LSErrorInit(&error); if (!m_lsHandle) return; json_object* json = json_object_new_object(); json_object_object_add(json, "name", json_object_new_string(name.c_str())); if (!sinkName.empty()) json_object_object_add(json, "sink", json_object_new_string(sinkName.c_str())); ret = LSCall(m_lsHandle, "palm://com.palm.audio/systemsounds/playFeedback", json_object_to_json_string(json), NULL, NULL, NULL, &error); if (!ret) { g_warning("Failed in playFeedback call: %s", error.message); LSErrorFree(&error); } json_object_put(json); } void SoundPlayerPool::queueFinishedPlayer(sptr<SoundPlayer> player) { // Add to list of finished players bool foundInFinishedPlayers = false; for (PlayerList::const_iterator it = m_finishedPlayers.begin(); it != m_finishedPlayers.end(); ++it) { if (it->get() == player.get()) { foundInFinishedPlayers = true; break; } } if (!foundInFinishedPlayers) m_finishedPlayers.push_back(player); // Remove from list of active players for (PlayerList::iterator it = m_activePlayers.begin(); it != m_activePlayers.end(); ++it) { if (it->get() == player.get()) { m_activePlayers.erase(it); break; } } if (!m_purgeTimer.running()) m_purgeTimer.start(0); } bool SoundPlayerPool::purgeTimerFired() { PlayerList::iterator it; // First delete all dead players it = m_finishedPlayers.begin(); while (it != m_finishedPlayers.end()) { if ((*it)->dead()) it = m_finishedPlayers.erase(it); else ++it; } int count = m_finishedPlayers.size(); it = m_finishedPlayers.begin(); while (it != m_finishedPlayers.end()) { if (count <= kMaxPooledPlayers) break; it = m_finishedPlayers.erase(it); } return false; } sptr<SoundPlayer> SoundPlayerPool::getPooledPlayer() { /* PlayerList::iterator it = m_finishedPlayers.begin(); while (it != m_finishedPlayers.end()) { sptr<SoundPlayer> player = (*it); // explicitly remove from dormant set it = m_finishedPlayers.erase(it); if (player->dead()) continue; return player; } return 0; */ // No pooling: mediaserver cannot handle back to back playbacks // on the same client very well return 0; }
23.004762
95
0.700683
ericblade
d60a28e235d70c4e0ba79013915aed2e71dca6dc
3,077
cxx
C++
examples/particle_advection/ParticleAdvection.cxx
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
1
2021-07-21T07:15:44.000Z
2021-07-21T07:15:44.000Z
examples/particle_advection/ParticleAdvection.cxx
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
null
null
null
examples/particle_advection/ParticleAdvection.cxx
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
null
null
null
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/cont/DataSet.h> #include <vtkm/cont/Initialize.h> #include <vtkm/filter/Streamline.h> #include <vtkm/io/reader/VTKDataSetReader.h> #include <vtkm/io/writer/VTKDataSetWriter.h> // Example computing streamlines. // An example vector field is available in the vtk-m data directory: magField.vtk // Example usage: // this will advect 200 particles 50 steps using a step size of 0.01 // // Particle_Advection <path-to-data-dir>/magField.vtk vec 200 50 0.01 output.vtk // int main(int argc, char** argv) { auto opts = vtkm::cont::InitializeOptions::DefaultAnyDevice; auto config = vtkm::cont::Initialize(argc, argv, opts); if (argc < 8) { std::cerr << "Usage: " << argv[0] << "dataFile varName numSeeds numSteps stepSize outputFile [options]" << std::endl; std::cerr << "where options are: " << std::endl << config.Usage << std::endl; return -1; } std::string dataFile = argv[1]; std::string varName = argv[2]; vtkm::Id numSeeds = std::stoi(argv[3]); vtkm::Id numSteps = std::stoi(argv[4]); vtkm::FloatDefault stepSize = std::stof(argv[5]); std::string outputFile = argv[6]; vtkm::cont::DataSet ds; if (dataFile.find(".vtk") != std::string::npos) { vtkm::io::reader::VTKDataSetReader rdr(dataFile); ds = rdr.ReadDataSet(); } else { std::cerr << "Unsupported data file: " << dataFile << std::endl; return -1; } //create seeds randomly placed withing the bounding box of the data. vtkm::Bounds bounds = ds.GetCoordinateSystem().GetBounds(); std::vector<vtkm::Particle> seeds; for (vtkm::Id i = 0; i < numSeeds; i++) { vtkm::Particle p; vtkm::FloatDefault rx = (vtkm::FloatDefault)rand() / (vtkm::FloatDefault)RAND_MAX; vtkm::FloatDefault ry = (vtkm::FloatDefault)rand() / (vtkm::FloatDefault)RAND_MAX; vtkm::FloatDefault rz = (vtkm::FloatDefault)rand() / (vtkm::FloatDefault)RAND_MAX; p.Pos[0] = static_cast<vtkm::FloatDefault>(bounds.X.Min + rx * bounds.X.Length()); p.Pos[1] = static_cast<vtkm::FloatDefault>(bounds.Y.Min + ry * bounds.Y.Length()); p.Pos[2] = static_cast<vtkm::FloatDefault>(bounds.Z.Min + rz * bounds.Z.Length()); p.ID = i; seeds.push_back(p); } auto seedArray = vtkm::cont::make_ArrayHandle(seeds); //compute streamlines vtkm::filter::Streamline streamline; streamline.SetStepSize(stepSize); streamline.SetNumberOfSteps(numSteps); streamline.SetSeeds(seedArray); streamline.SetActiveField(varName); auto output = streamline.Execute(ds); vtkm::io::writer::VTKDataSetWriter wrt(outputFile); wrt.WriteDataSet(output); return 0; }
33.813187
97
0.648684
yisyuanliou
d611412ad071de87aa25b1aebe142691e723a33d
64
cpp
C++
src/cxxperfcounter/MetricRegistry.cpp
bigc2000/cxxperfcounter
827fbf87a5fb594c1b3f0dbc9bdde215e8627350
[ "MIT" ]
null
null
null
src/cxxperfcounter/MetricRegistry.cpp
bigc2000/cxxperfcounter
827fbf87a5fb594c1b3f0dbc9bdde215e8627350
[ "MIT" ]
null
null
null
src/cxxperfcounter/MetricRegistry.cpp
bigc2000/cxxperfcounter
827fbf87a5fb594c1b3f0dbc9bdde215e8627350
[ "MIT" ]
null
null
null
// // Created by wx on 18-8-11. // #include "MetricRegistry.h"
10.666667
28
0.625
bigc2000
d625f5723d65d8618f7c6e03d980b741ecdd84ea
9,344
cpp
C++
raytracer.cpp
ShadowMitia/raytracer-upsud
4ac6ee21959438b5ee84612777b97ec6b7749820
[ "MIT" ]
1
2022-01-19T07:03:05.000Z
2022-01-19T07:03:05.000Z
raytracer.cpp
ShadowMitia/raytracer-upsud
4ac6ee21959438b5ee84612777b97ec6b7749820
[ "MIT" ]
null
null
null
raytracer.cpp
ShadowMitia/raytracer-upsud
4ac6ee21959438b5ee84612777b97ec6b7749820
[ "MIT" ]
null
null
null
// // Framework for a raytracer // File: raytracer.cpp // // Created for the Computer Science course "Introduction Computer Graphics" // taught at the University of Groningen by Tobias Isenberg. // // Author: Maarten Everts // // This framework is inspired by and uses code of the raytracer framework of // Bert Freudenberg that can be found at // http://isgwww.cs.uni-magdeburg.de/graphik/lehre/cg2/projekt/rtprojekt.html // #include "raytracer.h" #include "object.h" #include "sphere.h" #include "plane.h" #include "triangle.h" #include "box.h" #include "material.h" #include "light.h" #include "camera.h" #include "image.h" #include "yaml/yaml.h" #include "model.h" #include <ctype.h> #include <fstream> #include <assert.h> // Functions to ease reading from YAML input void operator >> (const YAML::Node& node, Triple& t) { if(node.size()==3){ node[0] >> t.x; node[1] >> t.y; node[2] >> t.z; } else if(node.size()==2){ node[0] >> t.x; node[1] >> t.y; node[1] >> t.z; } } Triple parseTriple(const YAML::Node& node) { Triple t; node[0] >> t.x; node[1] >> t.y; node[2] >> t.z; return t; } Material* Raytracer::parseMaterial(const YAML::Node& node) { Material *m = new Material(); m->color = Color(0.0, 0.0, 0.0); if(node.FindValue("color")){ node["color"] >> m->color; } if(node.FindValue("texture")) { std::string texSrc = node["texture"]; if (texSrc == "UV") { m->showUV = true; } else { if (imageHandler.find(texSrc) == imageHandler.end()) { imageHandler[texSrc] = new Image(texSrc.c_str()); if (imageHandler[texSrc]->width() == 0) { std::cout << "!!! Impossible de lire l'image" << texSrc << "\n"; } else { std::cout << "Importation de : " << texSrc << "\n"; } } m->texture = imageHandler[texSrc]; } } else { m->texture = nullptr; } if (node.FindValue("bump")) { std::string texSrc = node["bump"]; if (imageHandler.find(texSrc) == imageHandler.end()) { imageHandler[texSrc] = new Image(texSrc.c_str()); if (imageHandler[texSrc]->width() == 0) { std::cout << "!!! Impossible de lire l'image" << texSrc << "\n"; } else { std::cout << "Importation de : " << texSrc << "\n"; } } m->bump = imageHandler[texSrc]; } node["ka"] >> m->ka; node["kd"] >> m->kd; node["ks"] >> m->ks; node["n"] >> m->n; return m; } Object* Raytracer::parseOBJ(const YAML::Node& node) { Point pos = Point(0, 0, 0); if (!node.FindValue("position")) { std::cout << "No position\n"; } node["position"] >> pos; if (!node.FindValue("modelPath")) { std::cout << "Can't find model file\n"; } std::string modelPath; if (!node.FindValue("modelPath")) { std::cout << "No model path\n"; } node["modelPath"] >> modelPath; std::string materialPath; if (node.FindValue("materialFile")) { node["materialFile"] >> materialPath; } Object* returnObject = new Model(pos, modelPath, materialPath); return returnObject; } Object* Raytracer::parseObject(const YAML::Node& node) { Object *returnObject = NULL; std::string objectType; node["type"] >> objectType; if (objectType == "model") { returnObject = parseOBJ(node); } else if (objectType == "sphere") { Point pos; node["position"] >> pos; double r; double angle = 0; Triple vec = Triple(0.0, 0.0, 1.0); if(node.FindValue("angle")){ node["angle"] >> angle; node["radius"][0] >> r; node["radius"][1] >> vec; }else{ node["radius"] >> r; } Sphere *sphere = new Sphere(pos,r,angle,vec); returnObject = sphere; } else if (objectType == "plane") { Point normal; node["normal"] >> normal; double to; node["distance"] >> to; Plane *plane = new Plane(normal,to); returnObject = plane; } else if (objectType == "triangle") { Point p1; node["p1"] >> p1; Point p2; node["p2"] >> p2; Point p3; node["p3"] >> p3; Triangle *triangle = new Triangle(p1,p2,p3); triangle->InitTriangle(); returnObject = triangle; } else if (objectType == "box") { Point position; node["position"] >> position; Point dimension; node["dimension"] >> dimension; Point rotation; node["rotation"] >> rotation; Box *box = new Box(position,dimension,rotation); box->InitBox(); returnObject = box; } if (returnObject) { // read the material and attach to object if (!node.FindValue("material") && objectType == "model") { } else { returnObject->material = parseMaterial(node["material"]); } } return returnObject; } Camera* Raytracer::parseCamera(const YAML::Node& node) { Point eye; node["eye"] >> eye; Point center; node["center"] >> center; Point up; node["up"] >> up; Point viewSize; node["viewSize"] >> viewSize; Camera *returnCamera = new Camera(eye, center, up, viewSize); return returnCamera; } Light* Raytracer::parseLight(const YAML::Node& node) { Point position; node["position"] >> position; Color color; node["color"] >> color; return new Light(position,color); } std::string Raytracer::parseRendering(const YAML::Node& node) { std::string renderMode; node >> renderMode; return renderMode; } double Raytracer::parseRecDepth(const YAML::Node& node) { double recDepth; node >> recDepth; return recDepth; } /* * Read a scene from file */ bool Raytracer::readScene(const std::string& inputFilename) { // Initialize a new scene scene = new Scene(); // Open file stream for reading and have the YAML module parse it std::ifstream fin(inputFilename.c_str()); if (!fin) { cerr << "Error: unable to open " << inputFilename << " for reading." << endl;; return false; } try { YAML::Parser parser(fin); if (parser) { YAML::Node doc; parser.GetNextDocument(doc); if (doc.FindValue("GoochParameters")) { scene->setGoochParameters( doc["GoochParameters"]["alpha"], doc["GoochParameters"]["beta"], doc["GoochParameters"]["b"], doc["GoochParameters"]["y"]); } if (doc.FindValue("SuperSampling")) { scene->setSuperSampling(doc["SuperSampling"]["factor"]); } if(doc.FindValue("MaxRecursionDepth")){ // Read and set recursion depth's value scene->setRecDepth(parseRecDepth(doc["MaxRecursionDepth"])); } if(doc.FindValue("RenderMode")){ // Read and set scene Rendering to RenderMode directive's value scene->setRendering(parseRendering(doc["RenderMode"])); } else{ // If no renderingMode directive found then set rendering to Phong by default const char* phong = "phong"; std::string str(phong); scene->setRendering(str); } if (doc.FindValue("Shadows")) { scene->renderShadows(doc["Shadows"]); } else { scene->renderShadows(false); } if(doc.FindValue("Camera")){ scene->setCamera(parseCamera(doc["Camera"])); scene->withCam = true; } if(doc.FindValue("Eye")){ scene->setEye(parseTriple(doc["Eye"])); scene->withEye = true; } // Read and parse the scene objects const YAML::Node& sceneObjects = doc["Objects"]; if (sceneObjects.GetType() != YAML::CT_SEQUENCE) { cerr << "Error: expected a sequence of objects." << endl; return false; } for(YAML::Iterator it=sceneObjects.begin();it!=sceneObjects.end();++it) { Object *obj = parseObject(*it); // Only add object if it is recognized if (obj) { scene->addObject(obj); } else { cerr << "Warning: found object of unknown type, ignored." << endl; } } // Read and parse light definitions const YAML::Node& sceneLights = doc["Lights"]; if (sceneObjects.GetType() != YAML::CT_SEQUENCE) { cerr << "Error: expected a sequence of lights." << endl; return false; } for(YAML::Iterator it=sceneLights.begin();it!=sceneLights.end();++it) { scene->addLight(parseLight(*it)); } } if (parser) { cerr << "Warning: unexpected YAML document, ignored." << endl; } } catch(YAML::ParserException& e) { std::cerr << "Error at line " << e.mark.line + 1 << ", col " << e.mark.column + 1 << ": " << e.msg << std::endl; return false; } cout << "YAML parsing results: " << scene->getNumObjects() << " objects read." << endl; return true; } void Raytracer::renderToFile(const std::string& outputFilename) { if(scene->withCam){ Image img(static_cast<int>(scene->getWidth()),static_cast<int>(scene->getHeight())); cout << "Tracing..." << endl; scene->render(img); cout << "Writing image to " << outputFilename << "..." << endl; img.write_png(outputFilename.c_str()); cout << "Done." << endl; }else{ Image img(400,400); cout << "Tracing..." << endl; scene->render(img); cout << "Writing image to " << outputFilename << "..." << endl; img.write_png(outputFilename.c_str()); cout << "Done." << endl; } }
25.955556
116
0.583369
ShadowMitia
d62ff8a071bd1e679752ca42bd679f9e57ec8a70
3,985
cpp
C++
Level.cpp
georgelam6/TinyRoguelike
ce7592851b8b39ae598799a7bad742e49bd8e125
[ "MIT" ]
null
null
null
Level.cpp
georgelam6/TinyRoguelike
ce7592851b8b39ae598799a7bad742e49bd8e125
[ "MIT" ]
null
null
null
Level.cpp
georgelam6/TinyRoguelike
ce7592851b8b39ae598799a7bad742e49bd8e125
[ "MIT" ]
null
null
null
#include "Level.h" #include "globals.h" #include <iostream> #include <ctime> #include <cstdlib> Level::Level() {} Level::Level(SDL_Texture* spritesheet) { this->CreateLevel(); this->image = spritesheet; this->wallSrcRect = { 16, 0, 8, 8 }; this->enemySrcRect = { 8, 0, 8, 8 }; this->stairSrcRect = { 25, 0, 8, 8 }; this->foodSrcRect = { 48, 0, 8, 8 }; this->doorSrcRect = { 32, 0, 8, 8 }; } int Level::Random(int min, int max) { return rand() % (max - min + 1) + min; } bool Level::LevelContains(int thing) { for (int row = 0; row < 16; row++) { for (int col = 0; col < 16; col++) { int type = this->currentLevel[row][col]; if (type == thing) { return true; } } } return false; } void Level::CreateLevel() { // Reset level for (int row = 0; row < 16; row++) { for (int col = 0; col < 16; col++) { this->currentLevel[row][col] = 0; } } this->enemies.clear(); foodx = foody = 0; int count = 0; for (int row = 0; row < 16; row++) { for (int col = 0; col < 16; col++) { this->currentLevel[row][col] = template00[row][col]; int type = template00[row][col]; //if (type == 2) //{ //count++; //Enemy e = Enemy(this->image, row, col, count); //this->enemies.push_back(e); //} // spawn enemies if (Random(1, 60) == 1 && currentLevel[row][col] == 0) { count++; Enemy e = Enemy(this->image, col, row, count); this->enemies.push_back(e); } // spawn walls if (Random(1, 50) == 1 && row != 2 && col != 2) { this->currentLevel[row][col] = 1; } // spawn the stairs if (Random(1, 30) == 1 && row != 2 && col != 0 && !LevelContains(3) && currentLevel[row][col] == 0) { this->currentLevel[row][col] = 3; endx = col; endy = row; } // spawn a food if (Random(1, 60) == 1 && row != 2 && col != 0 && !LevelContains(4) && currentLevel[row][col] == 0) { this->currentLevel[row][col] = 4; foodx = col; foody = row; } } } } void Level::Render(SDL_Renderer *renderer) { int type = 0; for (int row = 0; row < 16; row++) { for (int col = 0; col < 16; col++) { type = this->currentLevel[row][col]; if (type == 1) { SDL_Rect destRect = { col * Globals::GRID_CELL_SIZE, row * Globals::GRID_CELL_SIZE, Globals::GRID_CELL_SIZE ,Globals::GRID_CELL_SIZE }; SDL_RenderCopy(renderer, this->image, &this->wallSrcRect, &destRect); } else if (type == 3) { SDL_Rect destRect = { col * Globals::GRID_CELL_SIZE, row * Globals::GRID_CELL_SIZE, Globals::GRID_CELL_SIZE ,Globals::GRID_CELL_SIZE }; SDL_RenderCopy(renderer, this->image, &this->stairSrcRect, &destRect); } else if (type == 4) { SDL_Rect destRect = { col * Globals::GRID_CELL_SIZE, row * Globals::GRID_CELL_SIZE, Globals::GRID_CELL_SIZE ,Globals::GRID_CELL_SIZE }; SDL_RenderCopy(renderer, this->image, &this->foodSrcRect, &destRect); } else if (type == 5) { SDL_Rect destRect = { col * Globals::GRID_CELL_SIZE, row * Globals::GRID_CELL_SIZE, Globals::GRID_CELL_SIZE ,Globals::GRID_CELL_SIZE }; SDL_RenderCopy(renderer, this->image, &this->doorSrcRect, &destRect); } } } for (auto& e : this->enemies) { SDL_Rect destRect = { e.x * Globals::GRID_CELL_SIZE, e.y * Globals::GRID_CELL_SIZE, Globals::GRID_CELL_SIZE, Globals::GRID_CELL_SIZE }; SDL_RenderCopy(renderer, this->image, &enemySrcRect, &destRect); } } void Level::Update(int px, int py) { for (auto& e : this->enemies) { e.Update(px, py, this->currentLevel); } } void Level::RemoveEnemy(Enemy enemy) { std::vector<Enemy> tempList; for (auto& e : this->enemies) { if (enemy.id != e.id) { tempList.push_back(e); } else { std::cout << "You slayed the skeleton" << std::endl; } } this->enemies = tempList; } void Level::EatFood(int x, int y) { this->currentLevel[y][x] = 0; foodx = foody = 0; std::cout << "You ate some food. It tasted good for something that you found on the floor." << std::endl; }
22.26257
139
0.597742
georgelam6
d6304268ad92ff3b0d548318336ee52ef9d7b19e
18,011
cpp
C++
master/core/third/cxxtools/src/string.cpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/third/cxxtools/src/string.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/third/cxxtools/src/string.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
/* * Copyright (C) 2004-2007 Marc Boris Duerner * Copyright (C) 2011 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/string.h> #include <cxxtools/utf8codec.h> #include <iostream> #include <algorithm> namespace std { void basic_string<cxxtools::Char>::resize(size_t n, cxxtools::Char ch) { size_type size = this->size(); if(size < n) { this->append(n - size, ch); } else if(n < size) { this->erase(n); } } void basic_string<cxxtools::Char>::reserve(size_t n) { if (capacity() < n) { // since capacity is always at least shortStringCapacity, we need to use long string // to ensure the requested capacity if the current is not enough cxxtools::Char* p = _data.allocate(n + 1); size_type l = length(); const cxxtools::Char* oldData = privdata_ro(); traits_type::copy(p, oldData, l); if (isShortString()) markLongString(); else _data.deallocate(longStringData(), longStringCapacity() + 1); _data.u.ptr._begin = p; _data.u.ptr._end = p + l; _data.u.ptr._capacity = p + n; *_data.u.ptr._end = cxxtools::Char::null(); } } void basic_string<cxxtools::Char>::privreserve(size_t n) { if (capacity() < n) { size_type nn = 16; while (nn < n) nn += (nn >> 1); reserve(nn); } } void basic_string<cxxtools::Char>::swap(basic_string& str) { if (isShortString()) { if (str.isShortString()) { for (unsigned nn = 0; nn < _shortStringSize; ++nn) std::swap(shortStringData()[nn], str.shortStringData()[nn]); } else { Ptr p = str._data.u.ptr; for (unsigned nn = 0; nn < _shortStringSize; ++nn) str.shortStringData()[nn] = shortStringData()[nn]; markLongString(); _data.u.ptr = p; } } else { if (str.isShortString()) { Ptr p = _data.u.ptr; for (unsigned nn = 0; nn < _shortStringSize; ++nn) shortStringData()[nn] = str.shortStringData()[nn]; str.markLongString(); str._data.u.ptr = p; } else { std::swap(_data.u.ptr, str._data.u.ptr); } } } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::copy(cxxtools::Char* a, size_type n, size_type pos) const { if( pos > this->size() ) { throw out_of_range("basic_string::copy"); } if(n > this->size() - pos) { n = this->size() - pos; } traits_type::copy(a, privdata_ro() + pos, n); return n; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const basic_string<cxxtools::Char>& str) { // self-assignment check if (this == &str) { return *this; } privreserve(str.size()); cxxtools::Char* p = privdata_rw(); size_type l = str.length(); traits_type::copy(p, str.data(), l); setLength(l); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const std::string& str) { size_type len = str.length(); privreserve(len); cxxtools::Char* p = privdata_rw(); for (size_type n = 0; n < len; ++n) p[n] = cxxtools::Char( str[n] ); setLength(len); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const std::string& str, size_type pos, size_type len) { privreserve(len); cxxtools::Char* p = privdata_rw(); for (size_type n = 0; n < len; ++n) p[n] = cxxtools::Char( str[pos + n] ); setLength(len); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const wchar_t* str) { size_type length = 0; while (str[length]) ++length; assign(str, length); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const wchar_t* str, size_type length) { privreserve(length); cxxtools::Char* d = privdata_rw(); for (unsigned n = 0; n < length; ++n) { d[n] = str[n]; } setLength(length); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const char* str) { size_type length = 0; while (str[length]) ++length; assign(str, length); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const char* str, size_type length) { privreserve(length); cxxtools::Char* d = privdata_rw(); for (unsigned n = 0; n < length; ++n) { d[n] = cxxtools::Char(str[n]); } setLength(length); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(const cxxtools::Char* str, size_type length) { // self-assignment check if (str != privdata_ro()) { privreserve(length); traits_type::copy(privdata_rw(), str, length); } setLength(length); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::assign(size_type n, cxxtools::Char ch) { privreserve(n); cxxtools::Char* p = privdata_rw(); for (size_type nn = 0; nn < n; ++nn) p[nn] = ch; setLength(n); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::append(const cxxtools::Char* str, size_type n) { size_type l = length(); privreserve(l + n); traits_type::copy(privdata_rw() + l, str, n); setLength(l + n); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::append(size_type n, cxxtools::Char ch) { size_type l = length(); privreserve(l + n); cxxtools::Char* p = privdata_rw(); for (size_type nn = 0; nn < n; ++nn) p[l + nn] = ch; setLength(l + n); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::insert(size_type pos, const cxxtools::Char* str, size_type n) { size_type l = length(); privreserve(l + n); cxxtools::Char* p = privdata_rw(); traits_type::move(p + pos + n, p + pos, l - pos); traits_type::copy(p + pos, str, n); setLength(l + n); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::insert(size_type pos, size_type n, cxxtools::Char ch) { size_type l = length(); privreserve(l + n); cxxtools::Char* p = privdata_rw(); traits_type::move(p + pos + n, p + pos, l - pos); for (size_type nn = 0; nn < n; ++nn) p[pos + nn] = ch; setLength(l + n); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::erase(size_type pos, size_type n) { cxxtools::Char* p = privdata_rw(); size_type l = length(); if (n == npos || pos + n > l) n = l - pos; traits_type::move(p + pos, p + pos + n, l - pos - n); setLength(l - n); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::replace(size_type pos, size_type n, const cxxtools::Char* str, size_type n2) { cxxtools::Char* p; if (n != n2) { size_type l = length(); privreserve(l - n + n2); p = privdata_rw(); traits_type::move(p + pos + n2, p + pos + n, l - pos - n); setLength(l - n + n2); } else { p = privdata_rw(); } traits_type::copy(p + pos, str, n2); return *this; } basic_string<cxxtools::Char>& basic_string<cxxtools::Char>::replace(size_type pos, size_type n, size_type n2, cxxtools::Char ch) { cxxtools::Char* p; if (n != n2) { size_type l = length(); privreserve(l - n + n2); p = privdata_rw(); traits_type::move(p + pos + n2, p + pos + n, l - pos - n); setLength(l - n + n2); } else { p = privdata_rw(); } for (size_type nn = 0; nn < n2; ++nn) p[pos + nn] = ch; return *this; } int basic_string<cxxtools::Char>::compare(const basic_string& str) const { const size_type size = this->size(); const size_type osize = str.size(); size_type n = min(size , osize); const int result = traits_type::compare(privdata_ro(), str.privdata_ro(), n); // unlike real life, size only matters when the quality is equal if (result == 0) { return static_cast<int>(size - osize); } return result; } int basic_string<cxxtools::Char>::compare(const char* str) const { size_type size = length(); size_type n; const cxxtools::Char* p = privdata_ro(); for (n = 0; n < size && str[n]; ++n) { cxxtools::Char ch(str[n]); if (p[n] != ch) return p[n] > ch ? 1 : -1; } return n < size ? 1 : str[n] ? -1 : 0; } int basic_string<cxxtools::Char>::compare(const char* str, size_type len) const { size_type size = length(); size_type n; const cxxtools::Char* p = privdata_ro(); for (n = 0; n < size && n < len; ++n) { cxxtools::Char ch(str[n]); if (p[n] != ch) return p[n] > ch ? 1 : -1; } return n < size ? 1 : n < len ? -1 : 0; } int basic_string<cxxtools::Char>::compare(const cxxtools::Char* str, size_type osize) const { const size_type size = this->size(); size_type n = min(size , osize); const int result = traits_type::compare(privdata_ro(), str, n); // unlike real life, size only matters when the quality is equal if (result == 0) { return static_cast<int>(size - osize); } return result; } int basic_string<cxxtools::Char>::compare(const wchar_t* str) const { const cxxtools::Char* self = privdata_ro(); while(self->toWchar() != L'\0' && *str != L'\0') { if( *self != *str ) return *self < cxxtools::Char(*str) ? -1 : +1; ++self; ++str; } return static_cast<int>(self->value()) - static_cast<int>(*str); } int basic_string<cxxtools::Char>::compare(const wchar_t* str, size_type n) const { const cxxtools::Char* self = privdata_ro(); size_type nn; for (nn = 0; nn < n; ++nn) { if(*self != str[nn]) return *self < cxxtools::Char(str[nn]) ? -1 : +1; ++self; } return self->value() != 0 ? 1 : nn < n ? -1 : 0; } int basic_string<cxxtools::Char>::compare(size_type pos, size_type n, const cxxtools::Char* str, size_type n2) const { const size_type size = n; const size_type osize = n2; size_type len = min(size , osize); const int result = traits_type::compare(privdata_ro() + pos, str, len); // unlike real life, size only matters when the quality is equal if (result == 0) { return static_cast<int>(size - osize); } return result; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find(const cxxtools::Char* token, size_type pos, size_type n) const { const size_type size = this->size(); const cxxtools::Char* str = privdata_ro(); for( ; pos + n <= size; ++pos) { if( 0 == traits_type::compare( str + pos, token, n ) ) { return pos; } } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find(cxxtools::Char ch, size_type pos) const { const size_type size = this->size(); if(pos > size) { return npos; } const cxxtools::Char* str = privdata_ro(); const size_type n = size - pos; const cxxtools::Char* found = traits_type::find(str + pos, n, ch); if(found) { return found - str; } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::rfind(const cxxtools::Char* token, size_type pos, size_type n) const { // FIXME: check length const size_type size = this->size(); if (n > size) { return npos; } pos = min(size_type(size - n), pos); const cxxtools::Char* str = privdata_ro(); do { if (traits_type::compare(str + pos, token, n) == 0) return pos; } while (pos-- > 0); return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::rfind(cxxtools::Char ch, size_type pos) const { const cxxtools::Char* str = privdata_ro(); size_type size = this->size(); if(size == 0) return npos; if(--size > pos) size = pos; for(++size; size-- > 0; ) { if( traits_type::eq(str[size], ch) ) return size; } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find_first_of(const cxxtools::Char* s, size_type pos, size_type n) const { // check length os s against n const cxxtools::Char* str = privdata_ro(); const size_type size = this->size(); for (; n && pos < size; ++pos) { if( traits_type::find(s, n, str[pos]) ) return pos; } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find_last_of(const cxxtools::Char* s, size_type pos, size_type n) const { // check length os s against n size_type size = this->size(); const cxxtools::Char* str = privdata_ro(); if (size == 0 || n == 0) { return npos; } if (--size > pos) { size = pos; } do { if( traits_type::find(s, n, str[size]) ) return size; } while (size-- != 0); return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find_first_not_of(const cxxtools::Char* tok, size_type pos, size_type n) const { const cxxtools::Char* str = privdata_ro(); for (; pos < this->size(); ++pos) { if ( !traits_type::find(tok, n, str[pos]) ) return pos; } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find_first_not_of(const cxxtools::Char ch, size_type pos) const { const cxxtools::Char* str = privdata_ro(); for (; pos < this->size(); ++pos) { if ( !traits_type::eq(str[pos], ch) ) { return pos; } } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find_last_not_of(const cxxtools::Char* tok, size_type pos, size_type n) const { size_type size = this->size(); const cxxtools::Char* str = privdata_ro(); if(size) { if (--size > pos) size = pos; do { if ( !traits_type::find(tok, n, str[size]) ) { return size; } } while(size--); } return npos; } basic_string<cxxtools::Char>::size_type basic_string<cxxtools::Char>::find_last_not_of(cxxtools::Char ch, size_type pos) const { size_type size = this->size(); const cxxtools::Char* str = privdata_ro(); if (size) { if (--size > pos) size = pos; do { if( !traits_type::eq(str[size], ch) ) { return size; } } while (size--); } return npos; } std::string basic_string<cxxtools::Char>::narrow(char dfault) const { std::string ret; size_type len = this->length(); const cxxtools::Char* s = privdata_ro(); ret.reserve(len); for (size_type n = 0; n < len; ++n) ret.append( 1, s[n].narrow(dfault) ); return ret; } basic_string<cxxtools::Char> basic_string<cxxtools::Char>::widen(const char* str) { std::basic_string<cxxtools::Char> ret; size_type len = std::char_traits<char>::length(str); ret.privreserve(len); for (size_type n = 0; n < len; ++n) ret += cxxtools::Char( str[n] ); return ret; } basic_string<cxxtools::Char> basic_string<cxxtools::Char>::widen(const std::string& str) { std::basic_string<cxxtools::Char> ret; size_type len = str.length(); ret.privreserve(len); for (size_type n = 0; n < len; ++n) ret += cxxtools::Char( str[n] ); return ret; } ostream& operator<< (ostream& out, const basic_string<cxxtools::Char>& str) { cxxtools::Utf8Codec codec; char to[64]; cxxtools::MBState state; cxxtools::Utf8Codec::result r; const cxxtools::Char* from = str.data(); cxxtools::String::size_type size = str.size(); do{ const cxxtools::Char* from_next; char* to_next = to; r = codec.out(state, from, from + size, from_next, to, to + sizeof(to), to_next); if (r == cxxtools::Utf8Codec::error) { out.setstate(std::ios::failbit); break; } out.write(to, to_next - to); size -= (from_next - from); from = from_next; } while (out.good() && r == cxxtools::Utf8Codec::partial); return out; } }
23.855629
136
0.589251
importlib
d636df85302e5055264d14e6483465a79af74bb6
1,600
cpp
C++
02 Arrays and Vectors/Advanced/pairSum.cpp
akritisneh/OnAndOn
a14f964c14d6a7a5fbef43db99f61a357b1f52f8
[ "MIT" ]
13
2021-10-05T15:50:21.000Z
2022-03-04T19:43:18.000Z
02 Arrays and Vectors/Advanced/pairSum.cpp
akritisneh/OnAndOn
a14f964c14d6a7a5fbef43db99f61a357b1f52f8
[ "MIT" ]
18
2021-10-05T14:43:14.000Z
2021-10-21T04:19:34.000Z
02 Arrays and Vectors/Advanced/pairSum.cpp
akritisneh/OnAndOn
a14f964c14d6a7a5fbef43db99f61a357b1f52f8
[ "MIT" ]
21
2021-10-05T14:34:25.000Z
2021-10-17T09:07:46.000Z
/*Given an array containing N integers and a number S denoting a target sum. Find two distinct integers that can pair up to form target sum. Let us assume there will be only one such pair. Input: array = [10,5,2,3,-6,9,11] Output [10,-6] Approach 1 - Brute Force Comparing every digit from all other digits Time Complexity - O(n^2) Approach 2 - Search for element x = S-arr[i] Binary Search for the element O(log n) Traversing array - O(n) Total Time complexity - O(n log n) Approach 3 - Two pointer Using two pointers at start and end, check for sum in a sorted array. Sorting - O(nlog n) Two pointer traversing - O(n) Total timecomplexity - O(n log n) Approach 4 - Unordered Set Checking for element in set O(1) if present return else insert that elemnt into set. Time Complexity (most optimal) - O(n) */ #include<iostream> #include<vector> #include<unordered_set> using namespace std; vector<int> pairSum(vector<int> arr, int Sum){ unordered_set<int> s; vector<int> result; for(int i=0;i<arr.size();i++){ int x = Sum-arr[i]; if(s.find(x)!=s.end()){ result.push_back(x); result.push_back(arr[i]); return result; } //insert the curent no. inside set to avoid duplicates as in ques it's mentioned distinct numbers s.insert(arr[i]); } return {}; } int main(){ vector<int> arr; int n; cout<<"Enter size - "; cin>>n; cout<<"Enter elements - "; while(n--){ int num; cin>>num; arr.push_back(num); } int S; cout<<"Enter the sum value - "; cin>>S; auto p = pairSum(arr,S); if(p.size()==0){ cout<<"No such pair"; } else{ cout<<p[0]<<","<<p[1]<<endl; } }
23.529412
99
0.678125
akritisneh
d637eb51ebfb6c7e4cfab281c3819a07637f9fc8
3,361
cpp
C++
src/source/data structures/MeshStructures.cpp
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
src/source/data structures/MeshStructures.cpp
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
src/source/data structures/MeshStructures.cpp
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
#include "data structures\MeshStructures.h" #include <cstdlib> #include <typeinfo> #include <cmath> #include <GL\glew.h> #include <stdio.h> #include <ctime> Vertex::Vertex() { } Vertex::Vertex(GLfloat x, GLfloat y, GLfloat z) { pos[0] = x; pos[1] = y; pos[2] = z; } TexCoord::TexCoord() { } TexCoord::TexCoord(GLfloat x, GLfloat y) { pos[0] = x; pos[1] = y; } Face::Face() { for(int i=0; i<3; i++) { vertex[i] = NULL; normal[i] = NULL; texCoord[i] = NULL; avg[i] = 0; vertIndex[i] = 0; normalIndex[i] = 0; texCoordIndex[i] = 0; } brdfIndex = 0; } Face::~Face() { delete vertex[0]; delete vertex[1]; delete vertex[2]; delete normal[0]; delete normal[1]; delete normal[2]; delete texCoord[0]; delete texCoord[1]; delete texCoord[2]; } float Face::area() { float A[] = { vertex[0]->pos[0] - vertex[1]->pos[0], vertex[0]->pos[1] - vertex[1]->pos[1] , vertex[0]->pos[2] - vertex[1]->pos[2] }; float B[] = { vertex[0]->pos[0] - vertex[2]->pos[0], vertex[0]->pos[1] - vertex[2]->pos[1] , vertex[0]->pos[2] - vertex[2]->pos[2] }; float C[] = { vertex[1]->pos[0] - vertex[2]->pos[0], vertex[1]->pos[1] - vertex[2]->pos[1] , vertex[1]->pos[2] - vertex[2]->pos[2] }; float a = dotProduct(A, A); a = maximum(a, 0.0); float b = dotProduct(B, B); b = maximum(b, 0.0); float c = dotProduct(C, C); c = maximum(c, 0.0); a = sqrt(a); b = sqrt(b); c = sqrt(c); float s = (a + b + c) / 2.0; float ar = s*(s - a)*(s - b)*(s - c); ar = sqrt(ar); return ar; } float triangleArea(float* v1, float* v2, float* v3) { float A[] = { v1[0] - v2[0], v1[1] - v2[1] , v1[2] - v2[2] }; float B[] = { v1[0] - v3[0], v1[1] - v3[1] , v1[2] - v3[2] }; float C[] = { v2[0] - v3[0], v2[1] - v3[1] , v2[2] - v3[2] }; float a = dotProduct(A, A); a = maximum(a, 0.0); float b = dotProduct(B, B); b = maximum(b, 0.0); float c = dotProduct(C, C); c = maximum(c, 0.0); a = sqrt(a); b = sqrt(b); c = sqrt(c); float s = (a + b + c) / 2.0; float ar = s*(s - a)*(s - b)*(s - c); ar = maximum(ar, 0.0); ar = sqrt(ar); return ar; } void interpolateNormals(Face* face, float* position, float* normalResult) { float areaV1 = triangleArea(face->vertex[1]->pos, face->vertex[2]->pos, position); float areaV2 = triangleArea(face->vertex[0]->pos, face->vertex[2]->pos, position); float areaV3 = triangleArea(face->vertex[0]->pos, face->vertex[1]->pos, position); float totalArea = areaV1 + areaV2 + areaV3; areaV1 = areaV1 / totalArea; areaV2 = areaV2 / totalArea; areaV3 = areaV3 / totalArea; normalResult[0] = areaV1 * face->normal[0]->pos[0] + areaV2 * face->normal[1]->pos[0] + areaV3 * face->normal[2]->pos[0]; normalResult[1] = areaV1 * face->normal[0]->pos[1] + areaV2 * face->normal[1]->pos[1] + areaV3 * face->normal[2]->pos[1]; normalResult[2] = areaV1 * face->normal[0]->pos[2] + areaV2 * face->normal[1]->pos[2] + areaV3 * face->normal[2]->pos[2]; normalize(normalResult); } void listDelete(List *l, void *ptr) { if(ptr == NULL) return; for(int i=0; i<l->alloc; i++) { if(l->buf[i] == ptr) { for(int j=i; j<l->alloc; j++) { l->buf[j] = l->buf[j+1]; } l->alloc = l->alloc-1; } } return; } Array::~Array() { delete buf; n = 0; }
22.557047
135
0.545968
Gregjksmith
d6418fb95bc1813c5927848aa5e5a8c71a7d427e
313
hpp
C++
include/partition.hpp
justcppdev/rb_tree
353ab0c0e07043df8e90d7cd0ae45ff753a461e5
[ "MIT" ]
null
null
null
include/partition.hpp
justcppdev/rb_tree
353ab0c0e07043df8e90d7cd0ae45ff753a461e5
[ "MIT" ]
null
null
null
include/partition.hpp
justcppdev/rb_tree
353ab0c0e07043df8e90d7cd0ae45ff753a461e5
[ "MIT" ]
null
null
null
#ifndef PARTITION_HPP #define PARTITION_HPP template <typename _Iterator> struct range_t { _Iterator begin; typename _Iterator::difference_type size; }; template <typename _Iterator> struct parition_t { range_t<_Iterator> less; range_t<_Iterator> equal; range_t<_Iterator> great; }; #endif
15.65
45
0.747604
justcppdev
d643f59f5c8410069c11f0d38683a32959f60473
3,853
cpp
C++
src/Source Code/MO_Sound.cpp
MayKoder/TFG-Miquel_Suau_Gonzalez
c0d0a7a71a709ec3514c9ff20be272ac9e66d1e2
[ "Apache-2.0" ]
null
null
null
src/Source Code/MO_Sound.cpp
MayKoder/TFG-Miquel_Suau_Gonzalez
c0d0a7a71a709ec3514c9ff20be272ac9e66d1e2
[ "Apache-2.0" ]
null
null
null
src/Source Code/MO_Sound.cpp
MayKoder/TFG-Miquel_Suau_Gonzalez
c0d0a7a71a709ec3514c9ff20be272ac9e66d1e2
[ "Apache-2.0" ]
null
null
null
#include "MO_Sound.h" #include <stdlib.h> #include <assert.h> #include <inttypes.h> #include <limits.h> #include <stdio.h> #include "sndfile/include/sndfile.h" #include "OpenAL/include/AL/al.h" #include "OpenAL/include/AL/alc.h" #include "OpenAL/include/AL/alext.h" #include "alhelpers.h" #pragma comment (lib, "sndfile/lib/sndfile.lib") #pragma comment (lib, "OpenAL/libs/Win32/OpenAL32.lib") M_Sound::M_Sound(Application* app, bool start_enabled) : Module(app, start_enabled), buffer(0), source(0), offset(0.0f), state(0) { } M_Sound::~M_Sound() { } #pragma region Audio test // /* Play the sound until it finishes. */ // alSourcePlay(source); // do { // al_nssleep(10000000); // alGetSourcei(source, AL_SOURCE_STATE, &state); // /* Get the source offset. */ // alGetSourcef(source, AL_SEC_OFFSET, &offset); // printf("\rOffset: %f ", offset); // fflush(stdout); // } while (alGetError() == AL_NO_ERROR && state == AL_PLAYING); // printf("\n"); #pragma endregion ALuint M_Sound::LoadSound(const char* filename) { ALenum err, format; ALuint buffer; SNDFILE* sndfile; SF_INFO sfinfo; short* membuf; sf_count_t num_frames; ALsizei num_bytes; /* Open the audio file and check that it's usable. */ sndfile = sf_open(filename, SFM_READ, &sfinfo); if (!sndfile) { fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); return 0; } if (sfinfo.frames < 1 || sfinfo.frames >(sf_count_t)(INT_MAX / sizeof(short)) / sfinfo.channels) { fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); sf_close(sndfile); return 0; } /* Get the sound format, and figure out the OpenAL format */ format = AL_NONE; if (sfinfo.channels == 1) format = AL_FORMAT_MONO16; else if (sfinfo.channels == 2) format = AL_FORMAT_STEREO16; else if (sfinfo.channels == 3) { if (sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) format = AL_FORMAT_BFORMAT2D_16; } else if (sfinfo.channels == 4) { if (sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) format = AL_FORMAT_BFORMAT3D_16; } if (!format) { fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); sf_close(sndfile); return 0; } /* Decode the whole audio file to a buffer. */ membuf = (short*)malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short)); num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames); if (num_frames < 1) { free(membuf); sf_close(sndfile); fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); return 0; } num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short); /* Buffer the audio data into a new buffer object, then free the data and * close the file. */ buffer = 0; alGenBuffers(1, &buffer); alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); free(membuf); sf_close(sndfile); /* Check if an error occured, and clean up if so. */ err = alGetError(); if (err != AL_NO_ERROR) { fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); if (buffer && alIsBuffer(buffer)) alDeleteBuffers(1, &buffer); return 0; } return buffer; } bool M_Sound::Init() { /* Initialize OpenAL. */ if (InitAL() != 0) return false; /* Load the sound into a buffer. */ //buffer = LoadSound("test.wav"); //if (!buffer) //{ // CloseAL(); // return false; //} ///* Create the source to play the sound with. */ //alGenSources(1, &source); //alSourcei(source, AL_BUFFER, (ALint)buffer); //assert(alGetError() == AL_NO_ERROR && "Failed to setup sound source"); //alSourcePlay(source); return true; } bool M_Sound::CleanUp() { /* All done. Delete resources, and close down OpenAL. */ alDeleteSources(1, &source); alDeleteBuffers(1, &buffer); CloseAL(); return true; }
23.493902
129
0.680768
MayKoder
d644f2dee9d259e974a61dc08a263f55590836ea
1,633
cpp
C++
src/main.cpp
dniklaus/lights-on
329f003e2f7a1ef0f24468b63985bf7d4f1bb107
[ "MIT" ]
null
null
null
src/main.cpp
dniklaus/lights-on
329f003e2f7a1ef0f24468b63985bf7d4f1bb107
[ "MIT" ]
1
2021-03-11T23:41:51.000Z
2021-03-11T23:41:51.000Z
src/main.cpp
dniklaus/lights-on
329f003e2f7a1ef0f24468b63985bf7d4f1bb107
[ "MIT" ]
null
null
null
/* * main.cpp * * Created on: 19.01.2021 * Author: Dieter Niklaus */ #include <Arduino.h> // PlatformIO libraries #include <SerialCommand.h> // pio lib install 173, lib details see https://github.com/kroimon/Arduino-SerialCommand #include <SpinTimer.h> // pio lib install 11599, lib details see https://github.com/dniklaus/spin-timer // private libraries #include <ProductDebug.h> // local components (lib folder) #include <Indicator.h> #include <MyIndicatorAdapter.h> SerialCommand* sCmd = 0; // pointer to indicator object for built in LED Indicator* led = 0; // pointers to indicator objects for 4 lamps Indicator* lamp = 0; Indicator* pwrcycle = 0; Indicator* reset = 0; Indicator* relay4 = 0; void setup() { // setup basic debug environment (heap usage printer, trace ports & dbg cli) setupProdDebugEnv(); // indicator LED led = new Indicator("led", "Built in LED."); led->assignAdapter(new MyIndicatorAdapter()); // 4 Lamps lamp = new Indicator("lamp", "Relay 1 - Lamp."); lamp->clear(); lamp->assignAdapter(new MyIndicatorAdapter(1)); pwrcycle = new Indicator("pwrcycle", "Relay 2 - Power Cycle."); pwrcycle->clear(); pwrcycle->assignAdapter(new MyIndicatorAdapter(2)); reset = new Indicator("reset", "Relay 3 - Reset Button."); reset->clear(); reset->assignAdapter(new MyIndicatorAdapter(3)); relay4 = new Indicator("relay4", "Relay 4."); relay4->clear(); relay4->assignAdapter(new MyIndicatorAdapter(4)); } void loop() { if (0 != sCmd) { sCmd->readSerial(); // process serial commands } scheduleTimers(); // process Timers }
24.373134
116
0.679118
dniklaus
d64bfe1c0bba8db3668deffe4eb0586fea84229c
4,832
cpp
C++
src/daemon/security/ldapplugin/LdapGroup.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
90
2020-06-06T12:11:33.000Z
2022-01-04T11:30:24.000Z
src/daemon/security/ldapplugin/LdapGroup.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
80
2020-05-19T14:33:34.000Z
2022-03-25T08:00:54.000Z
src/daemon/security/ldapplugin/LdapGroup.cpp
HanixNicolas/app-mesh
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
[ "MIT" ]
14
2020-07-16T11:35:47.000Z
2022-01-04T03:10:44.000Z
#include <map> #include <memory> #include <mutex> #include <set> #include <string> #include <cpprest/json.h> #include "../../../common/Utility.h" #include "../Role.h" #include "LdapGroup.h" ////////////////////////////////////////////////////////////////////////// /// LDAP Group ////////////////////////////////////////////////////////////////////////// // serialize web::json::value LdapGroup::AsJson() const { web::json::value result = web::json::value::object(); result[JSON_KEY_USER_LDAP_bind_dn] = web::json::value::string(m_bindDN); auto roles = web::json::value::array(m_roles.size()); int i = 0; for (const auto &role : m_roles) { roles[i++] = web::json::value::string(role->getName()); } return result; }; // de-serialize std::shared_ptr<LdapGroup> LdapGroup::FromJson(const std::string &groupName, const web::json::value &obj, const std::shared_ptr<Roles> roles) noexcept(false) { std::shared_ptr<LdapGroup> result = std::make_shared<LdapGroup>(groupName); if (!obj.is_null()) { result->m_bindDN = GET_JSON_STR_VALUE(obj, JSON_KEY_USER_LDAP_bind_dn); if (HAS_JSON_FIELD(obj, JSON_KEY_USER_roles)) { auto arr = obj.at(JSON_KEY_USER_roles).as_array(); for (auto jsonRole : arr) result->m_roles.insert(roles->getRole(jsonRole.as_string())); } } return result; }; void LdapGroup::updateGroup(std::shared_ptr<LdapGroup> group) { std::lock_guard<std::recursive_mutex> guard(m_mutex); this->m_roles = group->m_roles; this->m_bindDN = group->m_bindDN; } ////////////////////////////////////////////////////////////////////////// /// LDAP Groups ////////////////////////////////////////////////////////////////////////// std::shared_ptr<LdapGroup> LdapGroups::getGroup(const std::string &name) { std::lock_guard<std::recursive_mutex> guard(m_mutex); auto group = m_groups.find(name); if (group != m_groups.end()) { return group->second; } else { throw std::invalid_argument(Utility::stringFormat("no such group <%s>", name.c_str())); } }; web::json::value LdapGroups::AsJson() const { std::lock_guard<std::recursive_mutex> guard(m_mutex); web::json::value result = web::json::value::object(); for (const auto &group : m_groups) { result[group.first] = group.second->AsJson(); } return result; }; const std::shared_ptr<LdapGroups> LdapGroups::FromJson(const web::json::value &obj, std::shared_ptr<Roles> roles) noexcept(false) { std::shared_ptr<LdapGroups> groups = std::make_shared<LdapGroups>(); auto jsonOj = obj.as_object(); for (const auto &group : jsonOj) { auto name = GET_STD_STRING(group.first); groups->m_groups[name] = LdapGroup::FromJson(name, group.second, roles); } return groups; }; std::shared_ptr<LdapGroup> LdapGroups::addGroup(const web::json::value &obj, std::string name, std::shared_ptr<Roles> roles) { std::lock_guard<std::recursive_mutex> guard(m_mutex); auto group = LdapGroup::FromJson(name, obj, roles); if (m_groups.count(name)) { // update m_groups[name]->updateGroup(group); } else { // insert m_groups[name] = group; } return group; }; void LdapGroups::delGroup(const std::string &name) { std::lock_guard<std::recursive_mutex> guard(m_mutex); if (m_groups.count(name)) { // delete m_groups.erase(m_groups.find(name)); } }; std::map<std::string, std::shared_ptr<LdapGroup>> LdapGroups::getGroups() const { std::lock_guard<std::recursive_mutex> guard(m_mutex); return m_groups; }; ////////////////////////////////////////////////////////////////////////// /// JsonLdap ////////////////////////////////////////////////////////////////////////// JsonLdap::JsonLdap() { m_roles = std::make_shared<Roles>(); m_groups = std::make_shared<LdapGroups>(); } std::shared_ptr<JsonLdap> JsonLdap::FromJson(const web::json::value &jsonValue) { auto security = std::make_shared<JsonLdap>(); security->m_ldapUri = GET_JSON_STR_VALUE(jsonValue, JSON_KEY_USER_LDAP_ldap_uri); // Roles if (HAS_JSON_FIELD(jsonValue, JSON_KEY_Roles)) security->m_roles = Roles::FromJson(jsonValue.at(JSON_KEY_Roles)); // Groups if (HAS_JSON_FIELD(jsonValue, JSON_KEY_Groups)) security->m_groups = LdapGroups::FromJson(jsonValue.at(JSON_KEY_Groups), security->m_roles); return security; } web::json::value JsonLdap::AsJson() const { auto result = web::json::value::object(); result[JSON_KEY_USER_LDAP_ldap_uri] = web::json::value::string(m_ldapUri); // Users result[JSON_KEY_JWT_Users] = m_groups->AsJson(); // Roles result[JSON_KEY_Roles] = m_roles->AsJson(); return result; }
31.376623
157
0.596854
HanixNicolas
d64c5872a5203290a2859dc01a6c7f3cbf771ad8
2,308
cpp
C++
Algorithm/TSP_problem.cpp
Kenshin-Y/competitive
9035b86d772e4a48973309dbe45c3355ac18dbcb
[ "MIT" ]
null
null
null
Algorithm/TSP_problem.cpp
Kenshin-Y/competitive
9035b86d772e4a48973309dbe45c3355ac18dbcb
[ "MIT" ]
null
null
null
Algorithm/TSP_problem.cpp
Kenshin-Y/competitive
9035b86d772e4a48973309dbe45c3355ac18dbcb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // あとで整備する #define ll long long #define ALL(a) (a).begin(),(a).end() #define rep(i,n) for(int i=0;i<(n);i++) #define rrep(i,n) for(int i=n-1;i>=0;i--) //有向グラフ上巡回セールスマン問題 //verified //どこから始めても一緒なので、今回は0から始める。 const ll INF=1e18; signed main(){ int n,m; cin >> n >> m; map<P,ll> mp; map<P,bool> ok; rep(i,m){ int s,t; ll d; cin >> s >> t >> d; //from s to t mp[{s,t}]=d; ok[{s,t}]=1; } //dp[S][j]:=Sを通ってラストがjの時の、残りの経路の最短 ans:=dp[0][j] for j in [0,n) ll dp[1<<n][n]; rep(i,1<<n){ rep(j,n){ dp[i][j]=INF; } } dp[(1<<n)-1][0]=0; rrep(i,(1<<n)){ rep(j,n){ rep(k,n){ if(!ok[{j,k}]) continue; if(i&(1<<k)) continue; chmin(dp[i][j],dp[i|(1<<k)][k]+mp[{j,k}]); } } } ll res=INF; chmin(res,dp[0][0]); cout << (res==INF ? -1 : res) << endl; } //最短経路の数え上げ含む 双子コン#1 struct edge{ int to; ll cost; ll time; }; ll dp[1<<20][20]; ll memo[1<<20][20]; vector<edge> G[20]; const ll INF = 1e18; signed main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); int n,m; cin >> n >> m; rep(i,m){ int s,t; ll d,ti; cin >> s >> t >> d >> ti; s--; t--; G[s].pb({t,d,ti}); G[t].pb({s,d,ti}); } rep(i,1<<n)rep(j,n) dp[i][j]=INF; for(auto u:G[0]){ if(u.cost<=u.time){ dp[1<<u.to][u.to]=u.cost; memo[1<<u.to][u.to]=1; } } rep(i,1<<n){ rep(j,n){ if((i&(1<<j))==0) continue; for(auto u:G[j]){ if(u.to==0&&(i|1)!=((1<<n)-1)) continue; if(i&(1<<u.to)||u.time<dp[i][j]+u.cost) continue; if(dp[i|(1<<u.to)][u.to]>dp[i][j]+u.cost){ dp[i|(1<<u.to)][u.to]=dp[i][j]+u.cost; memo[i|(1<<u.to)][u.to]=memo[i][j]; }else if(dp[i|(1<<u.to)][u.to]==dp[i][j]+u.cost){ memo[i|(1<<u.to)][u.to]+=memo[i][j]; } } } } if(dp[(1<<n)-1][0]==INF){ cout<<"IMPOSSIBLE"<<endl; }else{ cout<<dp[(1<<n)-1][0]<<" "<< memo[(1<<n)-1][0] << endl; } }
23.793814
67
0.40078
Kenshin-Y
d6503925dffc6637f7422b6c49203558f3cc464e
250
cpp
C++
c++/forRoop/breakTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/forRoop/breakTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/forRoop/breakTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
#include <iostream> int main() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < 10; ++j) { std::cout << "(i, j) = (" << i << ", " << j << ")" << std::endl; if (j >= 2) { break; } } } return 0; }
10.869565
68
0.32
taku-xhift
d650f71c471d525127c95fdadfe92418c66cdab0
925
cpp
C++
poj/2551/main.cpp
nimitz871016/acm
a59aba6333e48473f9ef3c3702965b5ba2c4d741
[ "MIT" ]
null
null
null
poj/2551/main.cpp
nimitz871016/acm
a59aba6333e48473f9ef3c3702965b5ba2c4d741
[ "MIT" ]
null
null
null
poj/2551/main.cpp
nimitz871016/acm
a59aba6333e48473f9ef3c3702965b5ba2c4d741
[ "MIT" ]
null
null
null
// // main.cpp // 2551 // 水题,找到规律就很简单啦。分解 11111 = 10*1111 + 1,递进搜索,避免高精度运算 // Created by Nimitz_007 on 16/7/31. // Copyright © 2016年 Fujian Ruijie Networks Co., Ltd. All rights reserved. // #include <iostream> #include <math.h> int digitOfNum(long num){ int count = 1; while(num >= pow(10.0,count)){ count++; } return count; } int mod10e(long num,int n){ return true; } int main(int argc, const char * argv[]) { int n; int count = 0; int pre; while(scanf("%d",&n)!=EOF){ count = digitOfNum(n); pre = 0; for(int i = 0; i < count; i++){ pre += pow(10.0,i); } while(true){ pre = ((10 % n)*pre)%n + 1; if( pre % n == 0){ break; }else{ count ++; continue; } } printf("%d\n",count + 1); } return 0; }
19.270833
75
0.460541
nimitz871016
d651a7d057fe78b9c18ef1ab0096efc59e9dd2e0
1,256
hpp
C++
program/program/dx.hpp
agehama/graphics_experiments
f79bc33d306017ab928d2c7bbcbcfc884f2b5f98
[ "Unlicense" ]
null
null
null
program/program/dx.hpp
agehama/graphics_experiments
f79bc33d306017ab928d2c7bbcbcfc884f2b5f98
[ "Unlicense" ]
null
null
null
program/program/dx.hpp
agehama/graphics_experiments
f79bc33d306017ab928d2c7bbcbcfc884f2b5f98
[ "Unlicense" ]
null
null
null
#pragma once #include <array> #include <optional> #include <Windows.h> #include <d3d12.h> #include <dxgi1_6.h> class Mesh; class ShaderPipeline; class Dx { public: static Dx& instance() { static Dx i; return i; } bool init(HWND hwnd, int width, int height); bool frameBegin(); bool frameEnd(); ID3D12Device* device() { return m_device; } void setPipeline(const ShaderPipeline& pipeline); void draw(const Mesh& mesh); private: Dx() = default; ID3D12Device* m_device = nullptr; IDXGISwapChain4* m_swapChain = nullptr; ID3D12CommandAllocator* m_commandAllocator = nullptr; ID3D12GraphicsCommandList* m_commandList = nullptr; ID3D12CommandQueue* m_commandQueue = nullptr; IDXGIFactory6* m_dxgiFactory = nullptr; std::array<ID3D12Resource*, 2> m_backBuffers; D3D12_DESCRIPTOR_HEAP_DESC m_backBufferHD = {}; D3D12_RESOURCE_BARRIER m_backBufferBD = {}; ID3D12DescriptorHeap* m_backBufferHeaps = nullptr; std::array<float, 4> m_clearColor = { 0.f,0.f,0.f,1.f }; D3D12_VIEWPORT m_windowViewport = {}; D3D12_RECT m_scissorRect = {}; D3D12_PRIMITIVE_TOPOLOGY m_primitiveTOpology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; };
18.470588
87
0.691083
agehama
d653c263a4664572df582d9ffb1d4e48452d346c
1,224
cpp
C++
Scription/src/Scription/Layer/LayerHandler.cpp
MJTodge/Scription
530e4055ca4689f0b0ff80356b377ef9008f5f7c
[ "Apache-2.0" ]
null
null
null
Scription/src/Scription/Layer/LayerHandler.cpp
MJTodge/Scription
530e4055ca4689f0b0ff80356b377ef9008f5f7c
[ "Apache-2.0" ]
null
null
null
Scription/src/Scription/Layer/LayerHandler.cpp
MJTodge/Scription
530e4055ca4689f0b0ff80356b377ef9008f5f7c
[ "Apache-2.0" ]
null
null
null
#include "scrpch.h" #include "Scription/Layer/LayerHandler.h" namespace SCR { LayerHandler::~LayerHandler() { for (auto layer : _Layers) delete layer; } void LayerHandler::AttachLayer(Layer* layer) { _Layers.emplace(_Layers.begin() + _Insert, layer); _Insert++; layer->OnAttach(); } void LayerHandler::DetachLayer(Layer* layer) { auto i = std::find(_Layers.begin(), _Layers.end(), layer); if (i != _Layers.end()) { _Layers.erase(i); _Insert--; layer->OnDetach(); } } void LayerHandler::AttachOverlay(Layer* overlay) { _Layers.emplace_back(overlay); overlay->OnAttach(); } void LayerHandler::DetachOverlay(Layer* overlay) { auto i = std::find(_Layers.begin(), _Layers.end(), overlay); if (i != _Layers.end()) { _Layers.erase(i); overlay->OnDetach(); } } void LayerHandler::DetachLayerAt(unsigned index) { if (index >= _Layers.size()) return; auto layer = _Layers.at(index); auto i = std::find(_Layers.begin(), _Layers.end(), layer); if (i != _Layers.end()) { _Layers.erase(i); if (index < _Insert) _Insert--; layer->OnDetach(); } } }
19.741935
64
0.591503
MJTodge
d65952e4209c3725add87b31272269e9f8cba3b7
3,943
cpp
C++
msj_archives/code/MSJApr97.src/Tips on Tooltips/TTDemo/TitleTip.cpp
sarangbaheti/misc-code
d47a8d1cc41f19701ce628c9f15976bb5baa239d
[ "Unlicense" ]
1
2020-10-22T12:58:55.000Z
2020-10-22T12:58:55.000Z
msj_archives/code/MSJApr97.src/Tips on Tooltips/TTDemo/TitleTip.cpp
sarangbaheti/misc-code
d47a8d1cc41f19701ce628c9f15976bb5baa239d
[ "Unlicense" ]
null
null
null
msj_archives/code/MSJApr97.src/Tips on Tooltips/TTDemo/TitleTip.cpp
sarangbaheti/misc-code
d47a8d1cc41f19701ce628c9f15976bb5baa239d
[ "Unlicense" ]
2
2020-10-19T23:36:26.000Z
2020-10-22T12:59:37.000Z
// TitleTip.cpp : implementation file // #include "stdafx.h" #include "TitleTip.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTitleTip LPCSTR CTitleTip::m_pszWndClass = NULL; CTitleTip::CTitleTip() :m_nNoIndex(-1) { // Register the window class if it has not already been registered by // previous instantiation of CTitleTip. if (m_pszWndClass == NULL) { m_pszWndClass = AfxRegisterWndClass( CS_SAVEBITS | CS_HREDRAW | CS_VREDRAW); } m_nItemIndex = m_nNoIndex; m_pListBox = NULL; } CTitleTip::~CTitleTip() { } BOOL CTitleTip::Create(CListBox* pParentWnd) { ASSERT_VALID(pParentWnd); m_pListBox = pParentWnd; // Don't add border to regular (non owner-draw) listboxes because // owner-draw item automatically adds border. DWORD dwStyle = WS_POPUP; if (!IsListBoxOwnerDraw()) { dwStyle |= WS_BORDER; } return CreateEx(0, m_pszWndClass, NULL, dwStyle, 0, 0, 0, 0, pParentWnd->GetSafeHwnd(), NULL, NULL); } BOOL CTitleTip::IsListBoxOwnerDraw() { ASSERT_VALID(m_pListBox); DWORD dwStyle = m_pListBox->GetStyle(); return (dwStyle & LBS_OWNERDRAWFIXED) || (dwStyle & LBS_OWNERDRAWVARIABLE); } void CTitleTip::Show(CRect DisplayRect, int nItemIndex) { ASSERT_VALID(m_pListBox); ASSERT(nItemIndex < m_pListBox->GetCount()); ASSERT(nItemIndex >= 0); ASSERT(::IsWindow(m_hWnd)); ASSERT(!DisplayRect.IsRectEmpty()); // Invalidate if new item. if (m_nItemIndex != nItemIndex) { m_nItemIndex = nItemIndex; InvalidateRect(NULL); } // Adjust window position and visibility. CRect WindowRect; GetWindowRect(WindowRect); int nSWPFlags = SWP_SHOWWINDOW | SWP_NOACTIVATE; if (WindowRect == DisplayRect) { nSWPFlags |= SWP_NOMOVE | SWP_NOSIZE; } VERIFY(SetWindowPos(&wndTopMost, DisplayRect.left, DisplayRect.top, DisplayRect.Width(), DisplayRect.Height(), nSWPFlags)); } void CTitleTip::Hide() { ASSERT(::IsWindow(m_hWnd)); ShowWindow(SW_HIDE); } BEGIN_MESSAGE_MAP(CTitleTip, CWnd) //{{AFX_MSG_MAP(CTitleTip) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTitleTip message handlers void CTitleTip::OnPaint() { ASSERT(m_nItemIndex != m_nNoIndex); CPaintDC DC(this); int nSavedDC = DC.SaveDC(); CRect ClientRect; GetClientRect(ClientRect); if (IsListBoxOwnerDraw()) { // Let the listbox do the real drawing. DRAWITEMSTRUCT DrawItemStruct; DrawItemStruct.CtlType = ODT_LISTBOX; DrawItemStruct.CtlID = m_pListBox->GetDlgCtrlID(); DrawItemStruct.itemID = m_nItemIndex; DrawItemStruct.itemAction = ODA_DRAWENTIRE; DrawItemStruct.hwndItem = m_pListBox->GetSafeHwnd(); DrawItemStruct.hDC = DC.GetSafeHdc(); DrawItemStruct.rcItem = ClientRect; DrawItemStruct.itemData = m_pListBox->GetItemData(m_nItemIndex); DrawItemStruct.itemState = (m_pListBox->GetSel(m_nItemIndex) > 0 ? ODS_SELECTED : 0); if (m_pListBox->GetStyle() & LBS_MULTIPLESEL) { if (m_pListBox->GetCaretIndex() == m_nItemIndex) { DrawItemStruct.itemState |= ODS_FOCUS; } } else { DrawItemStruct.itemState |= ODS_FOCUS; } m_pListBox->DrawItem(&DrawItemStruct); } else { // Do all of the drawing ourselves CFont* pFont = m_pListBox->GetFont(); ASSERT_VALID(pFont); DC.SelectObject(pFont); COLORREF clrBackground = RGB(255, 255, 255); if (m_pListBox->GetSel(m_nItemIndex) > 0) { DC.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT)); clrBackground = ::GetSysColor(COLOR_HIGHLIGHT); } // Draw background DC.FillSolidRect(ClientRect, clrBackground); // Draw text of item CString strItem; m_pListBox->GetText(m_nItemIndex, strItem); ASSERT(!strItem.IsEmpty()); DC.SetBkMode(TRANSPARENT); DC.TextOut(1, -1, strItem); } DC.RestoreDC(nSavedDC); // Do not call CWnd::OnPaint() for painting messages }
22.531429
87
0.696424
sarangbaheti
d65fa3f00bc8b2e83bc0944fe4881783ed59ccd7
109
cpp
C++
test/src/BreakIntoDebugger.test.cpp
AMS21/CppBase
a6ec5542682bcebf5958d54557af1e03752a132f
[ "CC0-1.0" ]
null
null
null
test/src/BreakIntoDebugger.test.cpp
AMS21/CppBase
a6ec5542682bcebf5958d54557af1e03752a132f
[ "CC0-1.0" ]
1
2020-05-12T19:48:20.000Z
2020-05-12T19:48:20.000Z
test/src/BreakIntoDebugger.test.cpp
AMS21/CppBase
a6ec5542682bcebf5958d54557af1e03752a132f
[ "CC0-1.0" ]
null
null
null
#include <cpp/BreakIntoDebugger.hpp> void BreakIntoDebuggerCompileTest() { CPP_BREAK_INTO_DEBUGGER(); }
15.571429
36
0.779817
AMS21
d6679901ea9a336fb3ff448834f30bc2ccc5ca13
2,355
cpp
C++
code/310.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
23
2020-03-30T05:44:56.000Z
2021-09-04T16:00:57.000Z
code/310.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
1
2020-05-10T15:04:05.000Z
2020-06-14T01:21:44.000Z
code/310.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
6
2020-03-30T05:45:04.000Z
2020-08-13T10:01:39.000Z
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } int to[100005], nxt[100005], at[50005], cnt; int d1[50005], d2[50005], dd[50005]; class Solution { public: void dfs1(int cur, int fa){ for(int i = at[cur]; i; i = nxt[i]){ if (fa == to[i]) continue; int v = to[i]; dfs1(v, cur); if (d1[v] + 1 > d1[cur]){ if (d2[v] + 1 > d1[cur]) d2[cur] = d2[v] + 1; else d2[cur] = d1[cur]; d1[cur] = d1[v] + 1; }else if (d1[v] + 1 == d1[cur]){ d2[cur] = d1[v] + 1; }else { if (d1[v] + 1 > d2[cur]) d2[cur] = d1[v] + 1; } } if (d1[cur] < 0) d1[cur] = 0; } void dfs2(int cur, int fa){ for(int i = at[cur]; i; i = nxt[i]){ if (fa == to[i]) continue; int v = to[i]; dd[v] = d1[v]; if (d1[v] + 1 == d1[cur]){ if (d1[v] + 1 == d2[cur]) dd[v] = max(dd[v], d1[cur] + 1); else { if (d2[cur] >= 0) dd[v] = max(dd[v], d2[cur] + 1); } } else dd[v] = max(d1[cur] + 1, dd[v]); if (dd[v] ) dfs2(v, cur); } } vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) { memset(at, 0, sizeof(at)); cnt = 0; for (auto& e: edges){ int u = e[0], v = e[1]; to[++cnt] = v, nxt[cnt] = at[u], at[u] = cnt; to[++cnt] = u, nxt[cnt] = at[v], at[v] = cnt; } memset(d1, 0x90, sizeof(d1)); memset(d2, 0x90, sizeof(d2)); dfs1(0, -1); dd[0] = d1[0]; dfs2(0, -1); int mini = n + 1; for (int i = 0; i < n; ++i) mini = min(mini, dd[i]); vector<int> ans; for (int i = 0; i < n; ++i) if(dd[i] == mini) ans.push_back(i); return ans; } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
27.705882
71
0.385563
Nightwish-cn
d66d864e74946714748d755613cdbab36218cd0f
59,264
cpp
C++
src/ff_eam_dmd.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
3
2018-06-06T05:43:36.000Z
2020-07-18T14:31:37.000Z
src/ff_eam_dmd.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
null
null
null
src/ff_eam_dmd.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
7
2018-01-16T03:21:20.000Z
2020-07-20T19:36:13.000Z
#include "ff_eam_dmd.h" #include <stdlib.h> #include "neighbor_dmd.h" #include "elements.h" #include "memory.h" #include "xmath.h" #include "atoms_dmd.h" #include "MAPP.h" #include "dynamic_dmd.h" #include "import_eam.h" #include <limits> #define PI_IN_SQ 0.564189583547756286948079451561 using namespace MAPP_NS; /*-------------------------------------------- constructor --------------------------------------------*/ ForceFieldEAMDMD:: ForceFieldEAMDMD(AtomsDMD* atoms, type0 __dr,type0 __drho,size_t __nr,size_t __nrho, type0(***&& __r_phi_arr)[4],type0(***&& __rho_arr)[4],type0(**&& __F_arr)[5], type0**&& __cut,type0*&& __r_crd,type0*&& __zeta): ForceFieldDMD(atoms), nr(__nr), nrho(__nrho), dr(__dr), drho(__drho), F_arr(__F_arr), r_phi_arr(__r_phi_arr), r_rho_arr(__rho_arr), dE_ptr(NULL), ddE_ptr(NULL), cv_ptr(NULL), vec0(NULL), vec1(NULL), vec2(NULL), vec3(NULL), rho_phi(NULL), drho_phi_dr(NULL), drho_phi_dalpha(NULL), ddrho_phi_drdr(NULL), ddrho_phi_drdalpha(NULL), ddrho_phi_dalphadalpha(NULL), max_pairs0(0), max_pairs1(0), N(atoms->N), M_IJ(NULL) { __r_phi_arr=NULL; __rho_arr=NULL; __F_arr=NULL; dr_inv=1.0/dr; drho_inv=1.0/drho; rho_max=static_cast<type0>(nrho)*drho; Memory::alloc(xi,N); Memory::alloc(wi_0,N); Memory::alloc(wi_1,N); Memory::alloc(zeta,nelems); Memory::alloc(c_1,nelems); memcpy(xi,atoms->xi,N*sizeof(type0)); memcpy(wi_0,atoms->wi,N*sizeof(type0)); for(int i=0;i<N;i++) wi_1[i]=wi_0[i]*xi[i]; for(elem_type elem_i=0;elem_i<nelems;elem_i++) { r_crd[elem_i]=__r_crd[elem_i]; zeta[elem_i]=__zeta[elem_i]; } Memory::dealloc(__r_crd); Memory::dealloc(__zeta); for(elem_type elem_i=0;elem_i<nelems;elem_i++) { for(size_t i=0;i<nr;i++) r_rho_arr[elem_i][0][i][0]*=static_cast<type0>(i)*dr; ImportEAM::interpolate(nr,dr,r_rho_arr[elem_i][0]); for(elem_type elem_j=1;elem_j<nelems;elem_j++) { if(r_rho_arr[elem_i][elem_j]!=r_rho_arr[elem_i][elem_j-1]) { for(size_t i=0;i<nr;i++) r_rho_arr[elem_i][elem_j][i][0]*=static_cast<type0>(i)*dr; ImportEAM::interpolate(nr,dr,r_rho_arr[elem_i][elem_j]); } } } type0 tmp; for(size_t i=0;i<nelems;i++) for(size_t j=0;j<i+1;j++) { cut[i][j]=cut[j][i]=__cut[i][j]; tmp=__cut[i][j]; cut_sq[i][j]=cut_sq[j][i]=tmp*tmp; } Memory::dealloc(__cut); } /*-------------------------------------------- destructor --------------------------------------------*/ ForceFieldEAMDMD::~ForceFieldEAMDMD() { Memory::dealloc(F_arr); Memory::dealloc(r_rho_arr); Memory::dealloc(r_phi_arr); Memory::dealloc(zeta); Memory::dealloc(c_1); Memory::dealloc(wi_1); Memory::dealloc(wi_0); Memory::dealloc(xi); } /*-------------------------------------------- force calculation --------------------------------------------*/ void ForceFieldEAMDMD::__force_calc() { if(max_pairs0<neighbor->no_pairs) { delete [] rho_phi; delete [] drho_phi_dr; delete [] drho_phi_dalpha; max_pairs0=neighbor->no_pairs; size_t no_0=max_pairs0*3; Memory::alloc(rho_phi,no_0); Memory::alloc(drho_phi_dr,no_0); Memory::alloc(drho_phi_dalpha,no_0); } for(size_t i=0;i<max_pairs0*3;i++) rho_phi[i]=drho_phi_dr[i]=drho_phi_dalpha[i]=0.0; type0 r,r_inv; size_t m; type0* coef; type0 tmp0,tmp1; type0 fpair,apair; type0 p,cv_i; type0 dx_ij[__dim__]; type0 const* c=atoms->c->begin(); type0* dE=dE_ptr->begin(); type0* mu_vec=f_c->begin(); type0* rho=E_ptr->begin(); const int n=atoms->natms_lcl*c_dim; for(int i=0;i<n;i++) rho[i]=0.0; elem_type const* elem_vec=atoms->elem->begin(); type0 alpha_ij,rsq; elem_type elem_i,elem_j; const type0* x=atoms->x->begin(); const type0* alpha=atoms->alpha->begin(); int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; size_t istart=0; for(int i=0;i<n;i++) { type0 c_i=c[i]; if(c_i<0.0) continue; elem_i=elem_vec[i]; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; elem_j=elem_vec[j]; rsq=Algebra::RSQ<__dim__>(x+(i/c_dim)*__dim__,x+(j/c_dim)*__dim__); r=sqrt(rsq); type0 alpha_ij_sq=alpha[i]*alpha[i]+alpha[j]*alpha[j]; alpha_ij=sqrt(alpha_ij_sq); if(r-alpha_ij*xi[N-1]>=cut[elem_i][elem_j]) continue; type0 upper=(r+cut[elem_i][elem_j])/alpha_ij; type0 lower=(r-cut[elem_i][elem_j])/alpha_ij; type0 __r,p,tmp0,xi2; type0* coef; type0 H[3][5]{DESIG2(3,5,0.0)}; for(int l=0;l<N;l++) { if(xi[l]<=lower && xi[l]>=upper) continue; xi2=xi[l]*xi[l]; __r=r-xi[l]*alpha_ij; p=fabs(__r)*dr_inv; m=static_cast<size_t>(p); m=MIN(m,nr-2); p-=m; p=MIN(p,1.0); coef=r_phi_arr[elem_i][elem_j][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; if(__r<0.0) tmp0*=-1.0; tmp0*=wi_0[l]; H[0][0]+=tmp0; H[0][1]+=tmp0*xi[l]; H[0][2]+=tmp0*xi2; coef=r_rho_arr[elem_i][elem_j][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; if(__r<0.0) tmp0*=-1.0; tmp0*=wi_0[l]; H[1][0]+=tmp0; H[1][1]+=tmp0*xi[l]; H[1][2]+=tmp0*xi2; coef=r_rho_arr[elem_j][elem_i][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; if(__r<0.0) tmp0*=-1.0; tmp0*=wi_0[l]; H[2][0]+=tmp0; H[2][1]+=tmp0*xi[l]; H[2][2]+=tmp0*xi2; } r_inv=1.0/r; type0 r2_inv=r_inv*r_inv; type0 alpha_inv=1.0/alpha_ij; type0 alpha2_inv=alpha_inv*alpha_inv; Algebra::Do<3>::func([&istart,&H,&r_inv,&r2_inv,&alpha2_inv,&alpha_inv,this] (int i) { rho_phi[istart+i]=PI_IN_SQ*r_inv*H[i][0]; drho_phi_dr[istart+i]=-r2_inv*(rho_phi[istart+i]+2.0*PI_IN_SQ*alpha_inv*H[i][1]); drho_phi_dalpha[istart+i]=-alpha2_inv*(rho_phi[istart+i]-2.0*PI_IN_SQ*r_inv*H[i][2]); }); rho[i]+=c[j]*rho_phi[istart+2]; if(j<n) { rho[j]+=c_i*rho_phi[istart+1]; __vec_lcl[0]+=c_i*c[j]*rho_phi[istart]; } else __vec_lcl[0]+=0.5*c_i*c[j]*rho_phi[istart]; } p=rho[i]*drho_inv; m=static_cast<size_t>(p); m=MIN(m,nrho-2); p-=m; p=MIN(p,1.0); coef=F_arr[elem_i][m]; tmp0=(((coef[4]*p+coef[3])*p+coef[2])*p+coef[1])*p+coef[0]; tmp1=(((4.0*coef[4]*p+3.0*coef[3])*p+2.0*coef[2])*p+coef[1])*drho_inv; if(rho[i]>rho_max) tmp0+=tmp1*(rho[i]-rho_max); rho[i]=tmp0; dE[i]=tmp1; mu_vec[i]=tmp0; __vec_lcl[0]+=c_i*(tmp0+mu_0[elem_i]-3.0*kBT*log(alpha[i])); __vec_lcl[1+__nvoigt__]+=calc_ent(c_i); } const int __natms=atoms->natms_lcl; for(int i=0;i<__natms;i++) { cv_i=1.0; for(int ic=0;ic<c_dim;ic++) if(c[i*c_dim+ic]>0.0) cv_i-=c[i*c_dim+ic]; __vec_lcl[1+__nvoigt__]+=calc_ent(cv_i); } __vec_lcl[0]+=kBT*__vec_lcl[1+__nvoigt__]; update(dE_ptr); type0* fvec=f->begin(); type0* f_alphavec=f_alpha->begin(); type0 f_i[__dim__]={DESIG(__dim__,0.0)}; type0 x_i[__dim__]; Algebra::zero<__dim__>(x_i); istart=0; for(int i=0;i<n;i++) { if(i%c_dim==0) { Algebra::zero<__dim__>(f_i); Algebra::V_eq<__dim__>(x+(i/c_dim)*__dim__,x_i); } type0 c_i=c[i]; type0 alpha_i=alpha[i]; type0 dE_i=dE[i]; type0 f_alpha_i=0.0; type0 mu_i=0.0; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; Algebra::DX<__dim__>(x_i,x+(j/c_dim)*__dim__,dx_ij); fpair=-(drho_phi_dr[istart+2]*dE_i+drho_phi_dr[istart+1]*dE[j]+drho_phi_dr[istart])*c_i*c[j]; apair=-(drho_phi_dalpha[istart+2]*dE_i+drho_phi_dalpha[istart+1]*dE[j]+drho_phi_dalpha[istart])*c_i*c[j]; mu_i+=c[j]*(rho_phi[istart]+rho_phi[istart+1]*dE[j]); if(j<n) mu_vec[j]+=c_i*(rho_phi[istart]+rho_phi[istart+2]*dE_i); Algebra::SCL_mul_V_add<__dim__>(fpair,dx_ij,f_i); f_alpha_i+=alpha_i*apair; if(j<n) { Algebra::SCL_mul_V_add<__dim__>(-fpair,dx_ij,fvec+(j/c_dim)*__dim__); f_alphavec[j]+=alpha[j]*apair; } else fpair*=0.5; Algebra::DyadicV<__dim__>(-fpair,dx_ij,&__vec_lcl[1]); } f_alpha_i+=3.0*kBT*c_i/alpha_i; f_alphavec[i]+=f_alpha_i; mu_vec[i]+=mu_i; if((i+1)%c_dim==0) Algebra::V_add_V<__dim__>(fvec+__dim__*(i/c_dim),f_i); } type0 norm_sq_lcl=0.0; for(int i=0;i<n;i++) norm_sq_lcl+=f_alphavec[i]*f_alphavec[i]; const int natms_lcl=atoms->natms_lcl; for(int i=0;i<natms_lcl;i++,fvec+=__dim__) norm_sq_lcl+=Algebra::RSQ<__dim__>(fvec,fvec); } /*-------------------------------------------- force calculation --------------------------------------------*/ void ForceFieldEAMDMD::__prepJ_n_res(Vec<type0>* fvec_ptr,Vec<type0>* f_alphavec_ptr) { if(max_pairs0<neighbor->no_pairs) { delete [] rho_phi; delete [] drho_phi_dr; delete [] drho_phi_dalpha; max_pairs0=neighbor->no_pairs; size_t no_0=max_pairs0*3; Memory::alloc(rho_phi,no_0); Memory::alloc(drho_phi_dr,no_0); Memory::alloc(drho_phi_dalpha,no_0); } if(max_pairs1<neighbor->no_pairs) { delete [] ddrho_phi_drdr; delete [] ddrho_phi_dalphadalpha; delete [] ddrho_phi_drdalpha; max_pairs1=neighbor->no_pairs; size_t no_0=max_pairs1*3; Memory::alloc(ddrho_phi_drdr,no_0); Memory::alloc(ddrho_phi_drdalpha,no_0); Memory::alloc(ddrho_phi_dalphadalpha,no_0); } for(size_t i=0;i<max_pairs0*3;i++) rho_phi[i]=drho_phi_dr[i]=drho_phi_dalpha[i]=0.0; for(size_t i=0;i<max_pairs1*3;i++) ddrho_phi_drdr[i]=ddrho_phi_dalphadalpha[i]=ddrho_phi_drdalpha[i]=0.0; type0 r,r_inv; size_t m; type0* coef; type0 p; const int n=atoms->natms_lcl*c_dim; const type0* c=atoms->c->begin(); const type0* x=atoms->x->begin(); const type0* alpha=atoms->alpha->begin(); type0* E=E_ptr->begin(); type0* dE=dE_ptr->begin(); type0* ddE=ddE_ptr->begin(); type0* rho=E; for(int i=0;i<n;i++) rho[i]=0.0; elem_type const* elem_vec=atoms->elem->begin(); type0 alpha_ij,alpha_ij_sq,rsq,__rho; elem_type elem_i,elem_j; int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; size_t istart=0; for(int i=0;i<n;i++) { type0 c_i=c[i]; if(c_i<0.0) continue; elem_i=elem_vec[i]; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; elem_j=elem_vec[j]; rsq=Algebra::RSQ<__dim__>(x+(i/c_dim)*__dim__,x+(j/c_dim)*__dim__); r=sqrt(rsq); alpha_ij_sq=alpha[i]*alpha[i]+alpha[j]*alpha[j]; alpha_ij=sqrt(alpha_ij_sq); if(r-alpha_ij*xi[N-1]>=cut[elem_i][elem_j]) continue; type0 upper=(r+cut[elem_i][elem_j])/alpha_ij; type0 lower=(r-cut[elem_i][elem_j])/alpha_ij; type0 __r,p,tmp0,xi2,xi3,xi4; type0* coef; type0 H[3][5]{DESIG2(3,5,0.0)}; for(int l=0;l<N;l++) { if(xi[l]<=lower && xi[l]>=upper) continue; xi2=xi[l]*xi[l]; xi3=xi[l]*xi2; xi4=xi2*xi2; __r=r-xi[l]*alpha_ij; p=fabs(__r)*dr_inv; m=static_cast<size_t>(p); m=MIN(m,nr-2); p-=m; p=MIN(p,1.0); coef=r_phi_arr[elem_i][elem_j][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; if(__r<0.0) tmp0*=-1.0; tmp0*=wi_0[l]; H[0][0]+=tmp0; H[0][1]+=tmp0*xi[l]; H[0][2]+=tmp0*xi2; H[0][3]+=tmp0*xi3; H[0][4]+=tmp0*xi4; coef=r_rho_arr[elem_i][elem_j][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; if(__r<0.0) tmp0*=-1.0; tmp0*=wi_0[l]; H[1][0]+=tmp0; H[1][1]+=tmp0*xi[l]; H[1][2]+=tmp0*xi2; H[1][3]+=tmp0*xi3; H[1][4]+=tmp0*xi4; coef=r_rho_arr[elem_j][elem_i][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; if(__r<0.0) tmp0*=-1.0; tmp0*=wi_0[l]; H[2][0]+=tmp0; H[2][1]+=tmp0*xi[l]; H[2][2]+=tmp0*xi2; H[2][3]+=tmp0*xi3; H[2][4]+=tmp0*xi4; } r_inv=1.0/r; type0 r2_inv=r_inv*r_inv; type0 alpha_inv=1.0/alpha_ij; type0 alpha2_inv=alpha_inv*alpha_inv; type0 alpha4_inv=alpha2_inv*alpha2_inv; type0 r2alpha2_inv=r2_inv*alpha2_inv; Algebra::Do<3>::func([&istart,&H,&r_inv,&r2_inv,&alpha2_inv,&r2alpha2_inv,&alpha_ij_sq,&alpha_inv,&rsq,&alpha4_inv,this] (int i) { rho_phi[istart+i]=PI_IN_SQ*r_inv*H[i][0]; drho_phi_dr[istart+i]=-r2_inv*(rho_phi[istart+i]+2.0*PI_IN_SQ*alpha_inv*H[i][1]); drho_phi_dalpha[istart+i]=-alpha2_inv*(rho_phi[istart+i]-2.0*PI_IN_SQ*r_inv*H[i][2]); ddrho_phi_drdr[istart+i]=-r2_inv*(3.0*drho_phi_dr[istart+i]-2.0*drho_phi_dalpha[istart+i]); ddrho_phi_drdalpha[istart+i]=-r2alpha2_inv*(3.0*rho_phi[istart+i]+3.0*rsq*drho_phi_dr[istart+i]+alpha_ij_sq*drho_phi_dalpha[istart+i]+4.0*PI_IN_SQ*alpha_inv*H[i][3]); ddrho_phi_dalphadalpha[istart+i]=-alpha4_inv*(3.0*rho_phi[istart+i]+6.0*alpha_ij_sq*drho_phi_dalpha[istart+i]-4.0*PI_IN_SQ*r_inv*H[i][4]); }); rho[i]+=c[j]*rho_phi[istart+2]; if(j<n) { rho[j]+=c_i*rho_phi[istart+1]; __vec_lcl[0]+=c_i*c[j]*rho_phi[istart]; } else __vec_lcl[0]+=0.5*c_i*c[j]*rho_phi[istart]; } __rho=rho[i]; p=__rho*drho_inv; m=static_cast<size_t>(p); m=MIN(m,nrho-2); p-=m; p=MIN(p,1.0); coef=F_arr[elem_i][m]; E[i]=(((coef[4]*p+coef[3])*p+coef[2])*p+coef[1])*p+coef[0]; dE[i]=(((4.0*coef[4]*p+3.0*coef[3])*p+2.0*coef[2])*p+coef[1])*drho_inv; if(__rho>rho_max) { E[i]+=dE[i]*(__rho-rho_max); ddE[i]=0.0; } else { ddE[i]=(((12.0*coef[4]*p+6.0*coef[3])*p+2.0*coef[2]))*drho_inv*drho_inv; } __vec_lcl[0]+=c_i*(E[i]+mu_0[elem_i]-3.0*kBT*log(alpha[i])); __vec_lcl[1+__nvoigt__]+=calc_ent(c_i); } const int __natms=atoms->natms_lcl; type0 cv_i; for(int i=0;i<__natms;i++) { cv_i=1.0; for(int ic=0;ic<c_dim;ic++) if(c[i*c_dim+ic]>0.0) cv_i-=c[i*c_dim+ic]; __vec_lcl[1+__nvoigt__]+=calc_ent(cv_i); } __vec_lcl[0]+=kBT*__vec_lcl[1+__nvoigt__]; update(dE_ptr); type0* f_coef=f_c->begin(); if(c_dim!=1) { type0 c_tot; for(int i=0;i<__natms;i++) { c_tot=0.0; for(int ic=0;ic<c_dim;ic++) if(c[i*c_dim+ic]>0.0) c_tot+=c[i*c_dim+ic]; if(c_tot==0.0) { for(int ic=0;ic<c_dim;ic++) { if(c[i*c_dim+ic]==0.0) f_coef[i*c_dim+ic]=1.0; else f_coef[i*c_dim+ic]=0.0; } } else { for(int ic=0;ic<c_dim;ic++) { if(c[i*c_dim+ic]>=0.0) f_coef[i*c_dim+ic]=c[i*c_dim+ic]/c_tot; else f_coef[i*c_dim+ic]=0.0; } } } } else { for(int i=0;i<n;i++) if(c[i]>=0.0) f_coef[i]=1.0; } const int natms_lcl=atoms->natms_lcl; dE=dE_ptr->begin(); type0* fvec=fvec_ptr->begin(); type0* f_alphavec=f_alphavec_ptr->begin(); for(int i=0;i<n;i++) f_alphavec[i]=0.0; for(int i=0;i<natms_lcl*__dim__;i++) fvec[i]=0.0; type0 f_i[__dim__]={DESIG(__dim__,0.0)}; type0 x_i[__dim__]; Algebra::zero<__dim__>(x_i); type0 dx_ij[__dim__]; type0 fpair,apair; istart=0; for(int i=0;i<n;i++) { if(i%c_dim==0) { Algebra::zero<__dim__>(f_i); Algebra::V_eq<__dim__>(x+(i/c_dim)*__dim__,x_i); } type0 c_i=c[i]; type0 alpha_i=alpha[i]; type0 dE_i=dE[i]; type0 f_alpha_i=0.0; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; Algebra::DX<__dim__>(x_i,x+(j/c_dim)*__dim__,dx_ij); fpair=(drho_phi_dr[istart+2]*dE_i+drho_phi_dr[istart+1]*dE[j]+drho_phi_dr[istart]); apair=(drho_phi_dalpha[istart+2]*dE_i+drho_phi_dalpha[istart+1]*dE[j]+drho_phi_dalpha[istart]); Algebra::SCL_mul_V_add<__dim__>(fpair*c[j]*f_coef[i],dx_ij,f_i); f_alpha_i+=alpha_i*apair*c[j]; if(j<n) { Algebra::SCL_mul_V_add<__dim__>(-fpair*c_i*f_coef[j],dx_ij,fvec+(j/c_dim)*__dim__); f_alphavec[j]+=alpha[j]*apair*c_i; } else fpair*=0.5; Algebra::DyadicV<__dim__>(fpair*c_i*c[j],dx_ij,&__vec_lcl[1]); } f_alpha_i-=3.0*kBT/alpha_i; f_alphavec[i]+=f_alpha_i; if((i+1)%c_dim==0) Algebra::V_add_V<__dim__>(fvec+__dim__*(i/c_dim),f_i); } } /*-------------------------------------------- --------------------------------------------*/ void ForceFieldEAMDMD::__J(Vec<type0>* dx_ptr,Vec<type0>* dalpha_ptr,Vec<type0>* Adx_ptr,Vec<type0>* Adalpha_ptr) { type0* deltadE=E_ptr->begin(); const int n=atoms->natms_lcl*c_dim; const int nn=atoms->natms_lcl*__dim__; type0 const* c=atoms->c->begin(); const type0* x=atoms->x->begin(); const type0* alpha=atoms->alpha->begin(); type0* ddE=ddE_ptr->begin(); type0* dE=dE_ptr->begin(); int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; type0* dx=dx_ptr->begin(); type0* dalpha=dalpha_ptr->begin(); type0* Adx=Adx_ptr->begin(); type0* Adalpha=Adalpha_ptr->begin(); type0* f_coef=f_c->begin(); type0 dx_ij[__dim__]; type0 ddx_ij[__dim__]; type0 x_i[__dim__]; Algebra::zero<__dim__>(x_i); type0 dx_i[__dim__]; Algebra::zero<__dim__>(dx_i); type0 Adx_i[__dim__]; Algebra::zero<__dim__>(Adx_i); type0 pair_alpha_0,pair_alpha_1,df_pair,f_pair,a,b,alpha_i,dalpha_i,Adalpha_i; for(int i=0;i<n;i++) Adalpha[i]=deltadE[i]=0.0; for(int i=0;i<nn;i++) Adx[i]=0.0; size_t istart=0; for(int i=0;i<n;i++) { if(i%c_dim==0) { Algebra::V_eq<__dim__>(x+(i/c_dim)*__dim__,x_i); Algebra::V_eq<__dim__>(dx+(i/c_dim)*__dim__,dx_i); Algebra::zero<__dim__>(Adx_i); } alpha_i=alpha[i]; dalpha_i=dalpha[i]; Adalpha_i=0.0; type0 c_i=c[i]; if(c_i<0.0) continue; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; Algebra::DX<__dim__>(x_i,x+(j/c_dim)*__dim__,dx_ij); Algebra::DX<__dim__>(dx_i,dx+(j/c_dim)*__dim__,ddx_ij); a=Algebra::V_mul_V<__dim__>(dx_ij,ddx_ij); b=alpha_i*dalpha_i+alpha[j]*dalpha[j]; pair_alpha_0=-( (ddrho_phi_drdalpha[istart]+ddrho_phi_drdalpha[istart+2]*dE[i]+ddrho_phi_drdalpha[istart+1]*dE[j])*a +(ddrho_phi_dalphadalpha[istart]+ddrho_phi_dalphadalpha[istart+2]*dE[i]+ddrho_phi_dalphadalpha[istart+1]*dE[j])*b); pair_alpha_1=-(drho_phi_dalpha[istart]+drho_phi_dalpha[istart+2]*dE[i]+drho_phi_dalpha[istart+1]*dE[j]); df_pair=-( (ddrho_phi_drdalpha[istart]+ddrho_phi_drdalpha[istart+2]*dE[i]+ddrho_phi_drdalpha[istart+1]*dE[j])*b +(ddrho_phi_drdr[istart]+ddrho_phi_drdr[istart+2]*dE[i]+ddrho_phi_drdr[istart+1]*dE[j])*a); f_pair=-(drho_phi_dr[istart]+drho_phi_dr[istart+2]*dE[i]+drho_phi_dr[istart+1]*dE[j]); deltadE[i]+=(a*drho_phi_dr[istart+2]+b*drho_phi_dalpha[istart+2])*ddE[i]*c[j]; Algebra::SCL_mul_V_add<__dim__>(df_pair*c[j]*f_coef[i],dx_ij,Adx_i); Algebra::SCL_mul_V_add<__dim__>(f_pair*c[j]*f_coef[i],ddx_ij,Adx_i); Adalpha_i+=c[j]*(pair_alpha_0*alpha_i+pair_alpha_1*dalpha_i); if(j<n) { deltadE[j]+=(a*drho_phi_dr[istart+1]+b*drho_phi_dalpha[istart+1])*ddE[j]*c[i]; Algebra::SCL_mul_V_add<__dim__>(-df_pair*c[i]*f_coef[j],dx_ij,Adx+(j/c_dim)*__dim__); Algebra::SCL_mul_V_add<__dim__>(-f_pair*c[i]*f_coef[j],ddx_ij,Adx+(j/c_dim)*__dim__); Adalpha[j]+=c[i]*(pair_alpha_0*alpha[j]+pair_alpha_1*dalpha[j]); } else { f_pair*=0.5; df_pair*=0.5; } Algebra::DyadicV<__dim__>(-df_pair*c_i*c[j],dx_ij,__vec_lcl); Algebra::DyadicV<__dim__>(-f_pair*c_i*c[j],ddx_ij,dx_ij,__vec_lcl); } Adalpha[i]+=Adalpha_i; if((i+1)%c_dim==0) Algebra::V_add_V<__dim__>(Adx+__dim__*(i/c_dim),Adx_i); } update(E_ptr); deltadE=E_ptr->begin(); istart=0; for(int i=0;i<n;i++) { if(i%c_dim==0) { Algebra::zero<__dim__>(Adx_i); Algebra::V_eq<__dim__>(x+(i/c_dim)*__dim__,x_i); } alpha_i=alpha[i]; dalpha_i=dalpha[i]; Adalpha_i=0.0; type0 c_i=c[i]; if(c_i<0.0) continue; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; Algebra::DX<__dim__>(x_i,x+(j/c_dim)*__dim__,dx_ij); df_pair=-(drho_phi_dr[istart+2]*deltadE[i]+drho_phi_dr[istart+1]*deltadE[j]); pair_alpha_0=-(drho_phi_dalpha[istart+2]*deltadE[i]+drho_phi_dalpha[istart+1]*deltadE[j]); Algebra::SCL_mul_V_add<__dim__>(df_pair*c[j]*f_coef[i],dx_ij,Adx_i); Adalpha_i+=alpha_i*pair_alpha_0*c[j]; if(j<n) { Algebra::SCL_mul_V_add<__dim__>(-df_pair*c_i*f_coef[j],dx_ij,Adx+(j/c_dim)*__dim__); Adalpha[j]+=alpha[j]*pair_alpha_0*c_i; } else df_pair*=0.5; Algebra::DyadicV<__dim__>(-df_pair*c_i*c[j],dx_ij,__vec_lcl); } Adalpha[i]+=Adalpha_i-3.0*kBT*dalpha_i/(alpha_i*alpha_i); if((i+1)%c_dim==0) Algebra::V_add_V<__dim__>(Adx+__dim__*(i/c_dim),Adx_i); } } /*-------------------------------------------- energy calculation --------------------------------------------*/ void ForceFieldEAMDMD::__energy_calc() { type0* rho=ddE_ptr->begin(); const int n=atoms->natms_lcl*c_dim; for(int i=0;i<n;i++) rho[i]=0.0; elem_type const* elem_vec=atoms->elem->begin(); type0 alpha_ij,rsq,r,r_inv,p,tmp0,tmp1; elem_type elem_i,elem_j; size_t m; const type0* x=atoms->x->begin(); const type0* alpha=atoms->alpha->begin(); int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; type0 const* c=atoms->c->begin(); type0 const* coef; size_t istart=0; for(int i=0;i<n;i++) { elem_i=elem_vec[i]; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; elem_j=elem_vec[j]; rsq=Algebra::RSQ<__dim__>(x+(i/c_dim)*__dim__,x+(j/c_dim)*__dim__); r=sqrt(rsq); alpha_ij=sqrt(alpha[i]*alpha[i]+alpha[j]*alpha[j]); if(r-alpha_ij*xi[N-1]>=cut[elem_i][elem_j]) continue; type0 upper=(r+cut[elem_i][elem_j])/alpha_ij; type0 lower=(r-cut[elem_i][elem_j])/alpha_ij; type0 __r,p,tmp0; type0* coef; r_inv=1.0/r; type0 __arr[3]{DESIG(3,0.0)}; for(int l=0;l<N;l++) { if(xi[l]<=lower && xi[l]>=upper) continue; __r=r-xi[l]*alpha_ij; p=fabs(__r)*dr_inv; m=static_cast<size_t>(p); m=MIN(m,nr-2); p-=m; p=MIN(p,1.0); coef=r_phi_arr[elem_i][elem_j][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; tmp1=((3.0*coef[3]*p+2.0*coef[2])*p+coef[1])*dr_inv; if(__r<0.0) tmp0*=-1.0; __arr[0]+=wi_0[l]*tmp0; coef=r_rho_arr[elem_i][elem_j][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; tmp1=((3.0*coef[3]*p+2.0*coef[2])*p+coef[1])*dr_inv; if(__r<0.0) tmp0*=-1.0; __arr[1]+=wi_0[l]*tmp0; coef=r_rho_arr[elem_j][elem_i][m]; tmp0=((coef[3]*p+coef[2])*p+coef[1])*p+coef[0]; tmp1=((3.0*coef[3]*p+2.0*coef[2])*p+coef[1])*dr_inv; if(__r<0.0) tmp0*=-1.0; __arr[2]+=wi_0[l]*tmp0; } tmp0=PI_IN_SQ*r_inv; Algebra::Do<3>::func([&__arr,&tmp0](int i) { __arr[i]*=tmp0; }); rho[i]+=c[j]*__arr[2]; if(j<n) { rho[j]+=c[i]*__arr[1]; __vec_lcl[0]+=c[i]*c[j]*__arr[0]; } else __vec_lcl[0]+=0.5*c[i]*c[j]*__arr[0]; } if(c[i]<0.0) continue; tmp0=rho[i]; p=tmp0*drho_inv; m=static_cast<size_t>(p); m=MIN(m,nrho-2); p-=m; p=MIN(p,1.0); coef=F_arr[elem_i][m]; tmp1=(((coef[4]*p+coef[3])*p+coef[2])*p+coef[1])*p+coef[0]; if(rho[i]>rho_max) tmp1+=(((4.0*coef[4]*p+3.0*coef[3])*p+2.0*coef[2])*p+coef[1])*drho_inv*(tmp0-rho_max); if(c[i]!=0.0) __vec_lcl[0]+=c[i]*(tmp1+mu_0[elem_i]-3.0*kBT*log(alpha[i])); __vec_lcl[1+__nvoigt__]+=calc_ent(c[i]); } const int __natms=atoms->natms_lcl; type0 cv_i; for(int i=0;i<__natms;i++) { cv_i=1.0; for(int ic=0;ic<c_dim;ic++) if(c[i*c_dim+ic]>0.0) cv_i-=c[i*c_dim+ic]; __vec_lcl[1+__nvoigt__]+=calc_ent(cv_i); } __vec_lcl[0]+=kBT*__vec_lcl[1+__nvoigt__]; } /*-------------------------------------------- init --------------------------------------------*/ void ForceFieldEAMDMD::init() { pre_init(); set_temp(); cv_ptr=new Vec<type0>(atoms,1); E_ptr=new Vec<type0>(atoms,c_dim); dE_ptr=new Vec<type0>(atoms,c_dim); ddE_ptr=new Vec<type0>(atoms,c_dim); } /*-------------------------------------------- fin --------------------------------------------*/ void ForceFieldEAMDMD::fin() { Memory::dealloc(rho_phi); Memory::dealloc(drho_phi_dr); Memory::dealloc(drho_phi_dalpha); Memory::dealloc(ddrho_phi_drdr); Memory::dealloc(ddrho_phi_dalphadalpha); Memory::dealloc(ddrho_phi_drdalpha); max_pairs0=max_pairs1=0; delete ddE_ptr; delete dE_ptr; delete E_ptr; delete cv_ptr; dE_ptr=ddE_ptr=cv_ptr=vec0=vec1=vec2=vec3=NULL; post_fin(); } /*-------------------------------------------- create the sparse matrices --------------------------------------------*/ void ForceFieldEAMDMD::init_static() { Memory::alloc(M_IJ,4*neighbor->no_pairs_2nd); vec0=new Vec<type0>(atoms,c_dim); vec1=new Vec<type0>(atoms,1); vec2=new Vec<type0>(atoms,c_dim); vec3=new Vec<type0>(atoms,c_dim); fcoef_ptr=new Vec<type0>(atoms,1); const int __natms_lcl=atoms->natms_lcl; type0* f_coef=fcoef_ptr->begin(); type0* c=atoms->c->begin(); if(c_dim!=1) { type0 c_tot; for(int i=0;i<__natms_lcl;i++) { c_tot=0.0; for(int ic=0;ic<c_dim;ic++) if(c[i*c_dim+ic]>0.0) c_tot+=c[i*c_dim+ic]; if(c_tot==0.0) { for(int ic=0;ic<c_dim;ic++) { if(c[i*c_dim+ic]==0.0) f_coef[i*c_dim+ic]=1.0; else f_coef[i*c_dim+ic]=0.0; } } else { for(int ic=0;ic<c_dim;ic++) { if(c[i*c_dim+ic]>=0.0) f_coef[i*c_dim+ic]=c[i*c_dim+ic]/c_tot; else f_coef[i*c_dim+ic]=0.0; } } } } else { const int n=__natms_lcl*c_dim; for(int i=0;i<n;i++) if(c[i]>=0.0) f_coef[i]=1.0; } } /*-------------------------------------------- create the sparse matrices --------------------------------------------*/ void ForceFieldEAMDMD::fin_static() { delete fcoef_ptr; delete vec3; delete vec2; delete vec1; delete vec0; Memory::dealloc(M_IJ); } /*-------------------------------------------- set the temperature in the simulation --------------------------------------------*/ void ForceFieldEAMDMD::set_temp() { for(size_t i=0;i<nelems;i++) c_1[i]=sqrt(0.5*kBT/atoms->elements.masses[i])/M_PI; } /*-------------------------------------------- calculate cv calculate mu external vecs atoms->alpha; atoms->c; atoms->elem; internal vecs cv_ptr; E_ptr; dE_ptr; mu_ptr; --------------------------------------------*/ void ForceFieldEAMDMD::calc_mu() { /*-------------------------------- 2 things are hapenning here: 0. calculate c_v for local atoms 1. calculate the non interacting part of energy --------------------------------*/ //external vecs const type0* alpha=atoms->alpha->begin(); type0 const* c=atoms->c->begin(); elem_type const* elem_vec=atoms->elem->begin(); //internal vecs type0* cv=cv_ptr->begin(); int natms_lcl=atoms->natms_lcl; type0 en=0.0; for(int i=0;i<natms_lcl;i++) { type0 cv_i=1.0; for(int j=0;j<c_dim;j++) if(c[i*c_dim+j]>0.0) { __vec_lcl[1+__nvoigt__]+=calc_ent(c[i*c_dim+j]); en+=c[i*c_dim+j]* (mu_0[elem_vec[i*c_dim+j]]-3.0*kBT*log(alpha[i*c_dim+j])); cv_i-=c[i*c_dim+j]; } cv[i]=cv_i; __vec_lcl[1+__nvoigt__]+=calc_ent(cv_i); } __vec_lcl[0]+=en; __vec_lcl[0]+=kBT*__vec_lcl[1+__nvoigt__]; /*-------------------------------- we will calculate the rest of c_v here --------------------------------*/ int nall=natms_lcl+atoms->natms_ph; for(int i=natms_lcl;i<nall;i++) { type0 cv_i=1.0; for(int j=0;j<c_dim;j++) if(c[i*c_dim+j]>0.0) cv_i-=c[i*c_dim+j]; cv[i]=cv_i; } /*-------------------------------- calculate the electron densities --------------------------------*/ //internal vecs type0* rho=E_ptr->begin(); type0* mu_vec=f_c->begin(); int n=atoms->natms_lcl*c_dim; for(int i=0;i<n;i++) mu_vec[i]=rho[i]=0.0; size_t m; type0 p,__E,__dE,__rho; type0* coef; //internal vecs type0* dE=dE_ptr->begin(); type0* ddE=ddE_ptr->begin(); int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; size_t istart=0; for(int i=0;i<n;i++) { if(c[i]<0.0) continue; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; rho[i]+=c[j]*rho_phi[istart+2]; if(j<n) rho[j]+=c[i]*rho_phi[istart+1]; } __rho=rho[i]; p=__rho*drho_inv; m=static_cast<size_t>(p); m=MIN(m,nrho-2); p-=m; p=MIN(p,1.0); coef=F_arr[elem_vec[i]][m]; __E=(((coef[4]*p+coef[3])*p+coef[2])*p+coef[1])*p+coef[0]; __dE=(((4.0*coef[4]*p+3.0*coef[3])*p+2.0*coef[2])*p+coef[1])*drho_inv; ddE[i]=(((12.0*coef[4]*p+6.0*coef[3])*p+2.0*coef[2]))*drho_inv*drho_inv; if(__rho>rho_max) __E+=__dE*(__rho-rho_max); __vec_lcl[0]+=c[i]*__E; rho[i]=__E; mu_vec[i]+=__E; dE[i]=__dE; } update(dE_ptr); type0* fcoef=fcoef_ptr->begin(); type0* falpha=f_alpha->begin(); type0* fvec=f->begin(); memset(falpha,0,sizeof(type0)*n); memset(fvec,0,sizeof(type0)*__dim__*atoms->natms_lcl); /* type0 pair_0,pair_1; istart=0; for(int i=0;i<n;i++) { const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; mu[i]+=c[j]*(rho_phi[istart]+rho_phi[istart+1]*dE[j]); pair_0=(drho_phi_dr[istart]+drho_phi_dr[istart+1]*dE[j]+drho_phi_dr[istart+2]*dE[i]); pair_1=(drho_phi_dalpha[istart]+drho_phi_dalpha[istart+1]*dE[j]+drho_phi_dalpha[istart+2]*dE[i]); if(j<n) { mu[j]+=c[i]*(rho_phi[istart]+rho_phi[istart+2]*dE[i]); __vec_lcl[0]+=c[i]*c[j]*rho_phi[istart]; } else __vec_lcl[0]+=0.5*c[i]*c[j]*rho_phi[istart]; } } dynamic->update(mu_ptr); */ type0* x=atoms->x->begin(); type0 f_i[__dim__]={DESIG(__dim__,0.0)}; type0 x_i[__dim__]; Algebra::zero<__dim__>(x_i); type0 dx_ij[__dim__]; type0 fpair,apair; istart=0; for(int i=0;i<n;i++) { if(i%c_dim==0) { Algebra::zero<__dim__>(f_i); Algebra::V_eq<__dim__>(x+(i/c_dim)*__dim__,x_i); } type0 c_i=c[i]; type0 alpha_i=alpha[i]; type0 dE_i=dE[i]; type0 f_alpha_i=0.0; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; mu_vec[i]+=c[j]*(rho_phi[istart]+rho_phi[istart+1]*dE[j]); Algebra::DX<__dim__>(x_i,x+(j/c_dim)*__dim__,dx_ij); fpair=(drho_phi_dr[istart+2]*dE_i+drho_phi_dr[istart+1]*dE[j]+drho_phi_dr[istart]); apair=(drho_phi_dalpha[istart+2]*dE_i+drho_phi_dalpha[istart+1]*dE[j]+drho_phi_dalpha[istart]); Algebra::SCL_mul_V_add<__dim__>(fpair*c[j]*fcoef[i],dx_ij,f_i); f_alpha_i+=alpha_i*apair*c[j]; if(j<n) { mu_vec[j]+=c[i]*(rho_phi[istart]+rho_phi[istart+2]*dE[i]); Algebra::SCL_mul_V_add<__dim__>(-fpair*c_i*fcoef[j],dx_ij,fvec+(j/c_dim)*__dim__); falpha[j]+=alpha[j]*apair*c_i; __vec_lcl[0]+=c[i]*c[j]*rho_phi[istart]; } else __vec_lcl[0]+=0.5*c[i]*c[j]*rho_phi[istart]; } f_alpha_i-=3.0*kBT/alpha_i; falpha[i]+=f_alpha_i; if((i+1)%c_dim==0) Algebra::V_add_V<__dim__>(fvec+__dim__*(i/c_dim),f_i); } update(f_c); } /*-------------------------------------------- force calculation --------------------------------------------*/ void ForceFieldEAMDMD::__force_calc_static() { int n=atoms->natms_lcl*c_dim; type0 const* E=E_ptr->begin(); type0 const* c=atoms->c->begin(); type0 const* cv=cv_ptr->begin(); type0 const* alpha=atoms->alpha->begin(); elem_type const* elem=atoms->elem->begin(); for(int i=0;i<n;i++) { if(i%c_dim==0) __vec_lcl[1+__nvoigt__]+=calc_ent(cv[i]); if(c[i]>=0.0) { __vec_lcl[0]+=c[i]*(E[i]+mu_0[elem[i]]-3.0*kBT*log(alpha[i])); __vec_lcl[1+__nvoigt__]+=calc_ent(c[i]); } } __vec_lcl[0]+=kBT*__vec_lcl[1+__nvoigt__]; type0 const* dE=dE_ptr->begin(); type0 const* x=atoms->x->begin(); type0 x_i[__dim__]; Algebra::zero<__dim__>(x_i); type0 dx_ij[__dim__]; type0 fpair; int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; size_t istart=0; for(int i=0;i<n;i++) { if(i%c_dim==0) Algebra::V_eq<__dim__>(x+(i/c_dim)*__dim__,x_i); type0 c_i=c[i]; type0 dE_i=dE[i]; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; Algebra::DX<__dim__>(x_i,x+(j/c_dim)*__dim__,dx_ij); fpair=-(drho_phi_dr[istart+2]*dE_i+drho_phi_dr[istart+1]*dE[j]+drho_phi_dr[istart])*c_i*c[j]; if(j<n) __vec_lcl[0]+=rho_phi[istart]*c_i*c[j]; else { fpair*=0.5; __vec_lcl[0]+=0.5*rho_phi[istart]*c_i*c[j]; } Algebra::DyadicV<__dim__>(-fpair,dx_ij,&__vec_lcl[1]); } } } /*-------------------------------------------- create the sparse matrices external vecs atoms->x; atoms->alpha; atoms->c; atoms->elem; atoms->c_d; internal vecs type0* mu=mu_ptr->begin(); type0* cv=cv_ptr->begin(); F=c-scalar*c_d(c)+a --------------------------------------------*/ void ForceFieldEAMDMD::__c_d_calc() { calc_mu(); //external vecs const type0* x=atoms->x->begin(); const type0* alpha=atoms->alpha->begin(); const type0* c=atoms->c->begin(); const elem_type* elem_vec=atoms->elem->begin(); type0* __c_d=c_d->begin(); //internal vecs type0* cv=cv_ptr->begin(); type0* mu_vec=f_c->begin(); type0 rsq,alpha_i,alpha_j,alpha_sq_i,alpha_sq_j,gamma_i,gamma_j,mu_i,mu_ji; type0 Q_i,gamma_ij_inv,theta_i,theta_j,d_i,d_j,coef0; type0 dc_ij,c_1_ielem,zeta_ielem; size_t istart=0; int** neighbor_list=neighbor->neighbor_list_2nd; int* neighbor_list_size=neighbor->neighbor_list_size_2nd; const int n=atoms->natms_lcl*c_dim; type0 c_d_norm_lcl=0.0; for(int i=0;i<n;i++) { if(c[i]<0.0) continue; alpha_i=alpha[i]; alpha_sq_i=alpha_i*alpha_i; mu_i=mu_vec[i]; c_1_ielem=c_1[elem_vec[i]]; zeta_ielem=zeta[elem_vec[i]]; const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=4) { j=neighbor_list[i][__j]; if(!dof_c_empty && !(atoms->c_dof->begin()[i] && atoms->c_dof->begin()[j])) { M_IJ[istart]=0.0; M_IJ[istart+1]=0.0; M_IJ[istart+2]=0.0; M_IJ[istart+3]=0.0; continue; } alpha_j=alpha[j]; alpha_sq_j=alpha_j*alpha_j; rsq=Algebra::RSQ<__dim__>(x+(i/c_dim)*__dim__,x+(j/c_dim)*__dim__); gamma_i=rsq/(zeta_ielem*alpha_sq_i); gamma_j=rsq/(zeta_ielem*alpha_sq_j); mu_ji=beta*(mu_vec[j]-mu_i); calc_Q(gamma_i,gamma_j,mu_ji,Q_i,gamma_ij_inv,theta_i); coef0=-c_1_ielem*rsq*gamma_ij_inv*exp(-Q_i+0.5*mu_ji); /* exp_mod_Q_i=exp(-Q_i); exp_mod_Q_j=exp(-Q_i+mu_ji); d_i=d_j=-c_1_ielem*rsq*gamma_ij_inv; d_i/=alpha_sq_i*alpha_i; d_j/=alpha_sq_j*alpha_j; d_i*=exp(-Q_i); d_j*=exp(-Q_i+mu_ji);; */ theta_j=theta_i+1.0; dc_ij=coef0*(c[i]*cv[j/c_dim]*exp(-0.5*mu_ji)/(alpha_sq_i*alpha_i)-c[j]*cv[i/c_dim]*exp(0.5*mu_ji)/(alpha_sq_j*alpha_j)); //M_IJ[istart]=beta*(c[i]*cv[j/c_dim]*d_i*theta_i-c[j]*cv[i/c_dim]*d_j*theta_j); //M_IJ[istart+1]=d_i; //M_IJ[istart+2]=d_j; d_i=exp(-0.5*mu_ji)/(alpha_sq_i*alpha_i); d_j=exp(0.5*mu_ji)/(alpha_sq_j*alpha_j); M_IJ[istart]=beta*(theta_i*c[i]*cv[j/c_dim]*d_i-theta_j*c[j]*cv[i/c_dim]*d_j); M_IJ[istart+1]=d_i; M_IJ[istart+2]=d_j; M_IJ[istart+3]=coef0; __c_d[i]+=dc_ij; if(j<n) __c_d[j]-=dc_ij; } c_d_norm_lcl=MAX(c_d_norm_lcl,fabs(__c_d[i])); } MPI_Allreduce(&c_d_norm_lcl,&c_d_norm,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world); } /*-------------------------------------------- create the sparse matrices external vecs atoms->c; internal vecs E_ptr; dE_ptr; vec0; vec1; cv_ptr; input vecs x_ptr; Ax_ptr; F_i=c_i-beta*(d c_i)/dt J_ij=d F_i/(d c_j) Ax_i=-J_ij*x_j; --------------------------------------------*/ void ForceFieldEAMDMD::__J(Vec<type0>* x_ptr,Vec<type0>* Ax_ptr) { update(x_ptr); //external vecs type0* c=atoms->c->begin(); //internal vecs type0* ddE=ddE_ptr->begin(); type0* dE=dE_ptr->begin(); type0* b0=vec0->begin(); //input vecs type0* x=x_ptr->begin(); type0* Ax=Ax_ptr->begin(); int** neighbor_list=neighbor->neighbor_list; int* neighbor_list_size=neighbor->neighbor_list_size; size_t istart=0; const int n=atoms->natms_lcl*c_dim; for(int i=0;i<n;i++) b0[i]=Ax[i]=0.0; for(int i=0;i<n;i++) { const int neigh_sz=neighbor_list_size[i]; type0 ci_dEEi=c[i]*ddE[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; Ax[i]+=ci_dEEi*rho_phi[istart+2]*x[j]; if(j<n) Ax[j]+=c[j]*ddE[j]*rho_phi[istart+1]*x[i]; } } update(Ax_ptr); type0 tmp0; istart=0; for(int i=0;i<n;i++) { const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=3) { j=neighbor_list[i][__j]; tmp0=rho_phi[istart]+dE[i]*rho_phi[istart+2]+dE[j]*rho_phi[istart+1]; b0[i]+=rho_phi[istart+1]*Ax[j]+tmp0*x[j]; if(j<n) b0[j]+=rho_phi[istart+2]*Ax[i]+tmp0*x[i]; } } update(vec0); //internal vecs type0* xv=vec1->begin(); type0* cv=cv_ptr->begin(); const int nall=atoms->natms_lcl+atoms->natms_ph; for(int i=0;i<nall;i++) { xv[i]=0.0; for(int j=0;j<c_dim;j++) if(c[i*c_dim+j]>=0.0) xv[i]+=x[i*c_dim+j]; } for(int i=0;i<n;i++) Ax[i]=0.0; neighbor_list=neighbor->neighbor_list_2nd; neighbor_list_size=neighbor->neighbor_list_size_2nd; istart=0; for(int i=0;i<n;i++) { const int neigh_sz=neighbor_list_size[i]; for(int j,__j=0;__j<neigh_sz;__j++,istart+=4) { j=neighbor_list[i][__j]; tmp0=M_IJ[istart]*(b0[j]-b0[i]); tmp0+=M_IJ[istart+1]*(cv[j/c_dim]*x[i]-c[i]*xv[j/c_dim]); tmp0-=M_IJ[istart+2]*(cv[i/c_dim]*x[j]-c[j]*xv[i/c_dim]); tmp0*=M_IJ[istart+3]; Ax[i]+=tmp0; if(j<n) Ax[j]-=tmp0; } } } /*-------------------------------------------- gamma_i = x_ij*x_ij/(alpha_i*alpha_i) gamma_j = x_ij*x_ij/(alpha_j*alpha_j) mu_ji = beta*(mu_j-mu_i) Q=beta*U alpha_Q_sq=alpha_U_sq/(x_ij*x_ij) --------------------------------------------*/ inline void ForceFieldEAMDMD:: calc_Q(type0& gamma_i,type0& gamma_j,type0& mu_ji ,type0& Q,type0& alpha_Q_sq) { type0 z0; type0 a=5.0*(gamma_i-gamma_j-6.0*mu_ji); type0 xi=-2.0*(gamma_i+gamma_j); type0 d=sqrt((xi-a)*(xi-a)-8.0*a*gamma_i); z0=-4.0*gamma_i/((xi-a)-d); /* if(z0<0.0 || z0>1.0) { Error::abort("could not find z0"); } */ Q=z0*z0*(1.0-z0)*(1.0-z0)*((1.0-z0)*gamma_i+z0*gamma_j); Q+=z0*z0*z0*(6.0*z0*z0-15.0*z0+10.0)*mu_ji; alpha_Q_sq=1.0/((1.0-z0)*gamma_i+z0*gamma_j); } /*-------------------------------------------- gamma_i = x_ij*x_ij/(alpha_i*alpha_i) gamma_j = x_ij*x_ij/(alpha_j*alpha_j) mu_ji = beta*(mu_j-mu_i) Q=beta*U dz0: derivative of z0 w.r.t. mu_ji dQ: derivative of Q w.r.t. mu_ji alpha_Q_sq=alpha_U_sq/(x_ij*x_ij) dalpha_Q_sq/dmu_ji --------------------------------------------*/ inline void ForceFieldEAMDMD:: calc_Q(type0& gamma_i,type0& gamma_j,type0& mu_ji ,type0& Q,type0& alpha_Q_sq,type0& theta) { type0 z0,dz0,dQ; type0 a=5.0*(gamma_i-gamma_j-6.0*mu_ji); type0 xi=-2.0*(gamma_i+gamma_j); type0 delta_sqrt=sqrt((xi-a)*(xi-a)-8.0*a*gamma_i); z0=-4.0*gamma_i/((xi-a)-delta_sqrt); dz0=30.0*z0*(1.0-z0)/delta_sqrt; /* here */ dQ=z0*z0*z0*(6.0*z0*z0-15.0*z0+10.0); Q=z0*z0*(1.0-z0)*(1.0-z0)*((1.0-z0)*gamma_i+z0*gamma_j); Q+=dQ*mu_ji; alpha_Q_sq=1.0/((1.0-z0)*gamma_i+z0*gamma_j); theta=alpha_Q_sq*(gamma_i-gamma_j)*dz0-dQ; } /*-------------------------------------------- python constructor --------------------------------------------*/ void ForceFieldEAMDMD::ml_new(PyMethodDef& method_0,PyMethodDef& method_1,PyMethodDef& method_2) { method_0.ml_flags=METH_VARARGS | METH_KEYWORDS; method_0.ml_name="ff_eam_funcfl"; method_0.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { AtomsDMD::Object* __self=reinterpret_cast<AtomsDMD::Object*>(self); FuncAPI<std::string*,type0*,type0*,std::string*> f("ff_eam_funcfl",{"funcfl_files","r_crd","C","elems"}); f.noptionals=1; f.logics<1>()[0]=VLogics("gt",0.0); f.logics<2>()[0]=VLogics("gt",0.0); const std::string* names=__self->atoms->elements.names; size_t nelems=__self->atoms->elements.nelems; if(f(args,kwds)) return NULL; if(f.remap<3,0,1,2>("elements present in system",names,nelems)) return NULL; size_t nr,nrho; type0 dr,drho; type0** r_c; type0(** F)[5]=NULL; type0(*** r_phi)[4]=NULL; type0(*** rho)[4]=NULL; try { ImportEAM::funcfl(nelems,f.val<0>(),dr,drho,nr,nrho,r_phi,rho,F,r_c); } catch(char* err_msg) { PyErr_SetString(PyExc_TypeError,err_msg); delete [] err_msg; return NULL; } for(size_t i=0;i<nelems;i++) if(f.v<1>()[i]>r_c[i][i]) { Memory::dealloc(r_c); Memory::dealloc(F); Memory::dealloc(r_phi); Memory::dealloc(rho); PyErr_Format(PyExc_TypeError,"r_crd[%zu] should be less than r_c[%zu][%zu]",i,i,i); return NULL; } delete __self->ff; __self->ff=new ForceFieldEAMDMD(__self->atoms,dr,drho,nr,nrho,std::move(r_phi),std::move(rho),std::move(F),std::move(r_c),f.mov<1>(),f.mov<2>()); Py_RETURN_NONE; }); method_0.ml_doc=(char*)R"---( ff_eam_funcfl(funcfl_files,r_crd,C,elems=None) Tabulated EAM force field given by FuncFL file/s Assigns EAM force field to system Parameters ---------- funcfl_files : string[nelems] list of relative paths to DYNAMO files with FuncFL format r_crd : double[nelems] cutoff radius for mass exchange C : double[nelems] dimensionless factor for each element, see :ref:`here <master-ref>` elems : string[nelems] mapping elements Returns ------- None Notes ----- This is tabulated form of Embedded Atom Method (EAM) potential Examples -------- Ni :: >>> from mapp import dmd >>> sim=dmd.cfg(5,"configs/Ni-DMD.cfg") >>> sim.ff_eam_funcfl("potentials/niu3.eam") )---"; method_1.ml_flags=METH_VARARGS | METH_KEYWORDS; method_1.ml_name="ff_eam_setfl"; method_1.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { AtomsDMD::Object* __self=reinterpret_cast<AtomsDMD::Object*>(self); FuncAPI<std::string,type0*,type0*,std::string*> f("ff_eam_setfl",{"setfl_file","r_crd","C","elems"}); f.noptionals=1; f.logics<1>()[0]=VLogics("gt",0.0); f.logics<2>()[0]=VLogics("gt",0.0); const std::string* names=__self->atoms->elements.names; size_t nelems=__self->atoms->elements.nelems; if(f(args,kwds)) return NULL; if(f.remap<3,2,1>("elements present in system",names,nelems)) return NULL; size_t nr,nrho; type0 dr,drho; type0** r_c; type0(** F)[5]=NULL; type0(*** r_phi)[4]=NULL; type0(*** rho)[4]=NULL; try { ImportEAM::setfl(nelems,__self->atoms->elements.names,f.val<0>(),dr,drho,nr,nrho,r_phi,rho,F,r_c); } catch(char* err_msg) { PyErr_SetString(PyExc_TypeError,err_msg); delete [] err_msg; return NULL; } for(size_t i=0;i<nelems;i++) if(f.v<1>()[i]>r_c[i][i]) { Memory::dealloc(r_c); Memory::dealloc(F); Memory::dealloc(r_phi); Memory::dealloc(rho); PyErr_Format(PyExc_TypeError,"r_crd[%zu] should be less than r_c[%zu][%zu]",i,i,i); return NULL; } delete __self->ff; __self->ff=new ForceFieldEAMDMD(__self->atoms,dr,drho,nr,nrho,std::move(r_phi),std::move(rho),std::move(F),std::move(r_c),f.mov<1>(),f.mov<2>()); Py_RETURN_NONE; }); method_1.ml_doc=(char*)R"---( ff_eam_setfl(setfl_file,r_crd,C,elems=None) Tabulated EAM force field given by a single SetFL file Assigns EAM force field to system Parameters ---------- setfl_file : string relative path to DYNAMO file with SetFL format r_crd : double[nelems] cutoff radius for mass exchange C : double[nelems] dimensionless factor for each element, see :ref:`here <master-ref>` elems : string[nelems] mapping elements Returns ------- None Notes ----- This is tabulated form of Embedded Atom Method (EAM) potential Examples -------- Cu :: >>> from mapp import dmd >>> sim=dmd.cfg(5,"configs/Cu-DMD.cfg") >>> sim.ff_eam_setfl("potentials/Cu_mishin.eam.alloy") )---"; method_2.ml_flags=METH_VARARGS | METH_KEYWORDS; method_2.ml_name="ff_eam_fs"; method_2.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { AtomsDMD::Object* __self=reinterpret_cast<AtomsDMD::Object*>(self); FuncAPI<std::string,type0*,type0*,std::string*> f("ff_eam_fs",{"fs_file","r_crd","C","elems"}); f.noptionals=1; f.logics<1>()[0]=VLogics("gt",0.0); f.logics<2>()[0]=VLogics("gt",0.0); const std::string* names=__self->atoms->elements.names; size_t nelems=__self->atoms->elements.nelems; if(f(args,kwds)) return NULL; if(f.remap<3,2,1>("elements present in system",names,nelems)) return NULL; size_t nr,nrho; type0 dr,drho; type0** r_c; type0(** F)[5]=NULL; type0(*** r_phi)[4]=NULL; type0(*** rho)[4]=NULL; try { ImportEAM::fs(nelems,__self->atoms->elements.names,f.val<0>(),dr,drho,nr,nrho,r_phi,rho,F,r_c); } catch(char* err_msg) { PyErr_SetString(PyExc_TypeError,err_msg); delete [] err_msg; return NULL; } for(size_t i=0;i<nelems;i++) if(f.v<1>()[i]>r_c[i][i]) { Memory::dealloc(r_c); Memory::dealloc(F); Memory::dealloc(r_phi); Memory::dealloc(rho); PyErr_Format(PyExc_TypeError,"r_crd[%zu] should be less than r_c[%zu][%zu]",i,i,i); return NULL; } delete __self->ff; __self->ff=new ForceFieldEAMDMD(__self->atoms,dr,drho,nr,nrho,std::move(r_phi),std::move(rho),std::move(F),std::move(r_c),f.mov<1>(),f.mov<2>()); Py_RETURN_NONE; }); method_2.ml_doc=(char*)R"---( ff_eam_fs(fs_file,r_crd,C,elems=None) Tabulated Finnis-Sinclair EAM Assigns Finnis-Sinclair EAM force field to system. For explanation of the parameter see the Notes section. Parameters ---------- fs_file : string relative path to DYNAMO file with fs format r_crd : double[nelems] cutoff radius for mass exchange C : double[nelems] dimensionless factor for each element, see :ref:`here <master-ref>` elems : string[nelems] mapping elements Returns ------- None Notes ----- This is tabulated form of Finnis-Sinclair Embedded Atom Method (EAM) potential Consider the general form of EAM potential: .. math:: U=\frac{1}{2}\sum_{i}\sum_{j\neq i}\phi_{\gamma \delta}{(x_{ij}) }+\sum_i E_\gamma \left(\sum_{j\neq i} \rho_{\delta\gamma}(x_{ij}) \right), From here on, greek superscipts/subscripts are used to refer to elements present the system; :math:`\gamma`, and :math:`\delta` denote type of atom :math:`i` and atom :math:`j`, repectively. :math:`E`, :math:`\rho`, and :math:`\phi` are embedding, electron density, and pair functions, respectively. Also :math:`x_{ij}` refers to distance between :math:`i` and :math:`j`. Now the multi component formulation of DMD free energy would be: .. math:: F=&\frac{1}{2}\sum_{i,\gamma,j\neq i,\delta}c_i^\gamma c_j^\delta \omega_{\gamma \delta}\left(x_{ij}\right)+\sum_{i,\gamma} c_i^\gamma E_\gamma \left(\sum_{j\neq i,\delta} c_j^{\delta}\psi_{\delta\gamma}\left(x_{ij}\right)\right)-3k_BT\sum_{i,\gamma} c_i^\gamma \log\left(\sqrt{\pi e}\alpha_i^\gamma/\Lambda_\gamma\right)\\ &+k_BT\sum_{i,\gamma} c_i^\gamma\log c_i^\gamma+k_BT\sum_{i}c_i^v\log (c_i^v), where .. math:: \Lambda_\gamma=\frac{h}{\sqrt{2\pi m_\gamma k_BT}}, \quad c_i^v=1-\sum_{\gamma}c_i^\gamma, .. math:: \omega_{\gamma\delta}(x_{ij})= \frac{1}{\left(\alpha^{\gamma\delta}_{ij}\sqrt{\pi}\right)^{3}}\int d^3\mathbf{x} \exp{\biggl[-\left(\frac{\mathbf{x}_{ij} -\mathbf{x}}{\alpha^{\gamma\delta}_{ij}}\right)^2\biggr]}\phi_{\gamma\delta}(|\mathbf{x}|) .. math:: \psi_{\gamma\delta}(x_{ij})=\frac{1}{\left(\alpha^{\gamma\delta}_{ij}\sqrt{\pi}\right)^{3}}\int d^3\mathbf{x} \exp{\biggl[-\left(\frac{\mathbf{x}_{ij} -\mathbf{x}}{\alpha^{\gamma\delta}_{ij}}\right)^2\biggr]}\rho_{\gamma\delta}(|\mathbf{x}|) .. math:: \alpha^{\gamma\delta}_{ij}=\sqrt{{\alpha_i^{\gamma}}^2+{\alpha_j^{\delta}}^2},\quad \mathbf{x}_{ji}=\mathbf{x}_j-\mathbf{x}_i The numerical evaluation of these integrals is discussed :ref:`here <integ-ref>`. Recalling that .. math:: \langle U \rangle &= \frac{\partial }{\partial \beta}\left(\beta F \right) the average potential energy is .. math:: \langle U \rangle = \frac{1}{2}\sum_{i,\gamma,j\neq i,\delta}c_i^\gamma c_j^\delta \omega_{\gamma \delta}\left(x_{ij}\right)+\sum_{i,\gamma} c_i^\gamma E_\gamma \left(\sum_{j\neq i,\delta} c_j^{\delta}\psi_{\delta\gamma}\left(x_{ij}\right)\right) -\frac{3}{2} k_B T Examples -------- Iron Hydrogrn mixture >>> from mapp import dmd >>> sim=dmd.cfg(5,"configs/FeH-DMD.cfg") >>> sim.ff_eam_fs("potentials/FeH.eam.fs") )---"; }
30.564208
440
0.507846
sinamoeini
699094516198e04a858eeb1077c196ac5ae92b09
251
cc
C++
BOJ/17175.cc
Yaminyam/Algorithm
fe49b37b4b310f03273864bcd193fe88139f1c01
[ "MIT" ]
1
2019-05-18T00:02:12.000Z
2019-05-18T00:02:12.000Z
BOJ/17175.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
BOJ/17175.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int t; int a; long long p[51]; p[0] = 1; p[1] = 1; for (int i = 2; i < 51; i++) { p[i] = p[i - 1] + p[i - 2] + 1; } scanf("%d", &a); printf("%d", p[a]%1000000007); }
13.210526
34
0.442231
Yaminyam
6991505e8b288b910acb427d5a3dab68419f9922
3,764
cpp
C++
src/tsp/symmetric/lagrangean.cpp
Alexander-Ignatyev/optimer
fc0fb8ffd35e6326f60d77c144cfe7635a6edaa7
[ "BSD-3-Clause" ]
null
null
null
src/tsp/symmetric/lagrangean.cpp
Alexander-Ignatyev/optimer
fc0fb8ffd35e6326f60d77c144cfe7635a6edaa7
[ "BSD-3-Clause" ]
null
null
null
src/tsp/symmetric/lagrangean.cpp
Alexander-Ignatyev/optimer
fc0fb8ffd35e6326f60d77c144cfe7635a6edaa7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013-2014 Alexander Ignatyev. All rights reserved. #include "lagrangean.h" #include <cstring> #include <cmath> #include <numeric> namespace stsp { std::pair<MSOneTree::Solution<value_type>, size_t> LagrangeanRelaxation::solve( const std::vector<value_type> &initial_matrix , size_t dimension , value_type upper_bound , value_type epsilon , size_t max_iter , const std::vector<std::pair<size_t, size_t> > &included_edges) { static const size_t TOUR_DEGREE = 2; static const value_type ALPHA_START_VALUE = 2; if (dimension * dimension > matrix_.size()) { matrix_.resize(dimension*dimension); } value_type *matrix = matrix_.data(); MSOneTree::Solution<value_type> solution; std::memcpy(matrix, initial_matrix.data() , sizeof(value_type)*dimension*dimension); std::vector<int> gradient(dimension); std::vector<value_type> lambda(dimension, value_type()); value_type alpha = ALPHA_START_VALUE; value_type alpha_reduce = (alpha-0.01) / max_iter; value_type included_edges_penalty = value_type(); for (size_t iter = 0; iter < max_iter; ++iter) { solution = MSOneTree::solve(matrix, dimension); solution.value += included_edges_penalty; std::fill(gradient.begin(), gradient.end(), 0); std::vector<std::pair<size_t, size_t> >::const_iterator pos , end = solution.edges.end(); for (pos = solution.edges.begin(); pos != end; ++pos) { ++gradient[pos->first]; ++gradient[pos->second]; } value_type lagrangean = included_edges_penalty; for (pos = solution.edges.begin(); pos != end; ++pos) { lagrangean += matrix[pos->first*dimension + pos->second]; } lagrangean -= 2*std::accumulate(lambda.begin() , lambda.end() , value_type()); solution.value = lagrangean; if (lagrangean+epsilon > upper_bound) { return std::make_pair(solution, iter+1); } bool isGradientsRightDegree = true; for (size_t i = 0; i < gradient.size(); ++i) { if (gradient[i] != TOUR_DEGREE) { isGradientsRightDegree = false; break; } } if (isGradientsRightDegree) { solution.value = lagrangean; return std::make_pair(solution, iter+1); } int sum_gradient = 0; for (size_t i = 0; i < gradient.size(); ++i) { int val = gradient[i] - TOUR_DEGREE; sum_gradient += val*val; } value_type step = alpha*(upper_bound - lagrangean)/sum_gradient; for (size_t i = 0; i < dimension; ++i) { lambda[i] += step*gradient[i]; } alpha -= alpha_reduce; for (size_t i = 0; i < dimension; ++i) { for (size_t j = 0; j < dimension; ++j) { if (i == j) { matrix[i*dimension+j] = M_VAL; } else { matrix[i*dimension+j] = initial_matrix[i*dimension+j] + (lambda[i] + lambda[j]); } } } included_edges_penalty = value_type(); for (size_t i = 0; i < included_edges.size(); ++i) { const std::pair<size_t, size_t> &edge = included_edges[i]; size_t index = edge.first*dimension+edge.second; included_edges_penalty += matrix[index]; matrix[index] = value_type(); matrix[edge.second*dimension+edge.first] = value_type(); } } return std::make_pair(solution, max_iter); } } // namespace stsp
33.607143
79
0.559511
Alexander-Ignatyev
6992f67ae9ef3036cb0c38773280ea32c27a75d3
1,236
cpp
C++
BOJ_solve/16026.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
BOJ_solve/16026.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
null
null
null
BOJ_solve/16026.cpp
python-programmer1512/Code_of_gunwookim
e72e6724fb9ee6ccf2e1064583956fa954ba0282
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const long long llINF = 1e18; long long mod = 1e9+7; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int n,m; ll d[2][100005]; struct Computer { int c,f,v; }a[4005]; bool cmp(Computer x,Computer y) { if(x.f == y.f) return x.c > y.c; return x.f > y.f; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 1;i <= n;i++) cin >> a[i].c >> a[i].f >> a[i].v, a[i].v *= -1; cin >> m; for(int i = n+1;i <= n+m;i++) cin >> a[i].c >> a[i].f >> a[i].v, a[i].c *= -1; sort(a+1,a+n+m+1,cmp); for(int i = 1;i <= 100000;i++) d[0][i] = d[1][i] = -llINF; for(int i = 1;i <= n+m;i++) { for(int j = 0;j <= 100000;j++) { d[i%2][j] = d[(i-1)%2][j]; if(j-a[i].c < 0||j-a[i].c > 100000) continue; d[i%2][j] = max(d[i%2][j],d[(i-1)%2][j-a[i].c]+a[i].v); } } ll ans = -INF; for(int j = 0;j <= 100000;j++) ans = max(ans,d[(n+m)%2][j]); cout << ans; }
25.22449
79
0.559871
python-programmer1512
6993ebffba140bb41fdcd09482cfa1b21db37b0e
484
cpp
C++
Ch 12/12.11.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 12/12.11.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 12/12.11.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
/*如果像下面这样调用process,会发生什么?*/ // 报错,当p被销毁时,p指向的内存会被第二次delete #include<iostream> #include<memory> using namespace std; void process(shared_ptr<int> ptr) { cout << "inside the process function: " << ptr.use_count() << endl; } int main() { shared_ptr<int> p(new int(42)); process(shared_ptr<int>(p.get())); // shared_ptr<int>(p.get())生成一个临时shared_ptr变量 // 并将其传入process函数,这个临时变量和q指向相同内存 // 但不是p的拷贝,即独立创建的。其引用计数为1。 // 在退出process时临时p指向的内存已经被释放 // 当main函数结束时释放p就会出错。 return 0; }
18.615385
68
0.714876
Felon03
69a1e7e66e16df70151ef057986ee0e05be7b6e7
2,454
hpp
C++
src/Main/Help/HelpPage.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/Main/Help/HelpPage.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/Main/Help/HelpPage.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * 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. */ #pragma once #include <QtCore/QMap> #include <QtCore/QSharedPointer> #include <QtCore/QString> namespace vx { namespace cmark { class Node; } namespace help { class HelpPageInfo { QString url_; QString title_; QString shortDescription_; QMap<QString, QString> metaInformation_; public: HelpPageInfo( const QString& url, const QString& title, const QString& shortDescription, const QMap<QString, QString>& metaInformation = QMap<QString, QString>()); ~HelpPageInfo(); const QString& url() const { return url_; } const QString& title() const { return title_; } const QString& shortDescription() const { return shortDescription_; } const QMap<QString, QString>& metaInformation() const { return metaInformation_; } }; // TODO: Should this contain a HelpPageInfo? class HelpPage { QSharedPointer<vx::cmark::Node> doc_; QString baseFileName_; QString title_; public: HelpPage(const QSharedPointer<vx::cmark::Node>& doc, const QString& baseFileName, const QString& title); ~HelpPage(); const QSharedPointer<vx::cmark::Node>& doc() const { return doc_; } const QString& baseFileName() const { return baseFileName_; } const QString& title() const { return title_; } QSharedPointer<vx::cmark::Node> docClone(); }; } // namespace help } // namespace vx
31.87013
80
0.734311
voxie-viewer
69a2c00ff1dbf9c1ba8e1a8486bd7d0df9989c6d
2,616
cpp
C++
gui/GUIWindowsComponents.cpp
grumat/urbackup_frontend_wx
a5d086f6c1a0544965ac7d9a3db94363ab2b936b
[ "RSA-MD" ]
65
2015-07-29T13:45:31.000Z
2022-03-30T15:42:33.000Z
gui/GUIWindowsComponents.cpp
grumat/urbackup_frontend_wx
a5d086f6c1a0544965ac7d9a3db94363ab2b936b
[ "RSA-MD" ]
7
2016-06-13T11:41:22.000Z
2020-07-11T14:21:21.000Z
gui/GUIWindowsComponents.cpp
grumat/urbackup_frontend_wx
a5d086f6c1a0544965ac7d9a3db94363ab2b936b
[ "RSA-MD" ]
39
2015-02-03T20:44:00.000Z
2022-03-30T15:42:34.000Z
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Jun 17 2015) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "GUIWindowsComponents.h" /////////////////////////////////////////////////////////////////////////// GUIWindowsComponents::GUIWindowsComponents( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style ) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); m_treeCtrl1 = new wxTreeCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE ); bSizer1->Add( m_treeCtrl1, 10, wxALL|wxEXPAND, 5 ); wxBoxSizer* bSizer2; bSizer2 = new wxBoxSizer( wxHORIZONTAL ); bSizer2->Add( 0, 0, 1, wxEXPAND, 5 ); m_button1 = new wxButton( this, wxID_ANY, _("Ok"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer2->Add( m_button1, 0, wxALL, 5 ); m_button2 = new wxButton( this, wxID_ANY, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer2->Add( m_button2, 0, wxALL, 5 ); bSizer1->Add( bSizer2, 1, wxEXPAND, 5 ); this->SetSizer( bSizer1 ); this->Layout(); this->Centre( wxBOTH ); // Connect Events m_treeCtrl1->Connect( wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, wxTreeEventHandler( GUIWindowsComponents::evtOnTreeItemGetTooltip ), NULL, this ); m_treeCtrl1->Connect( wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK, wxTreeEventHandler( GUIWindowsComponents::evtOnTreeStateImageClick ), NULL, this ); m_button1->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIWindowsComponents::onOkClick ), NULL, this ); m_button2->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIWindowsComponents::onCancel ), NULL, this ); } GUIWindowsComponents::~GUIWindowsComponents() { // Disconnect Events m_treeCtrl1->Disconnect( wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, wxTreeEventHandler( GUIWindowsComponents::evtOnTreeItemGetTooltip ), NULL, this ); m_treeCtrl1->Disconnect( wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK, wxTreeEventHandler( GUIWindowsComponents::evtOnTreeStateImageClick ), NULL, this ); m_button1->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIWindowsComponents::onOkClick ), NULL, this ); m_button2->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIWindowsComponents::onCancel ), NULL, this ); }
44.338983
203
0.686162
grumat
69afe8dba0ec5da8a79ec509ac76e4dfb9ee812e
2,305
hpp
C++
src/Environment.hpp
KipHamiltons/NUClear
1c6147b3fda26c3796f133881f0bf626261db574
[ "MIT" ]
6
2015-04-09T04:23:58.000Z
2020-12-10T04:35:13.000Z
src/Environment.hpp
KipHamiltons/NUClear
1c6147b3fda26c3796f133881f0bf626261db574
[ "MIT" ]
12
2015-01-21T16:42:43.000Z
2021-09-29T10:06:45.000Z
src/Environment.hpp
KipHamiltons/NUClear
1c6147b3fda26c3796f133881f0bf626261db574
[ "MIT" ]
15
2015-04-10T00:33:38.000Z
2021-09-24T23:42:55.000Z
/* * Copyright (C) 2013 Trent Houliston <trent@houliston.me>, Jake Woods <jake.f.woods@gmail.com> * 2014-2017 Trent Houliston <trent@houliston.me> * * 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 NUCLEAR_ENVIRONMENT_HPP #define NUCLEAR_ENVIRONMENT_HPP #include <string> #include "LogLevel.hpp" namespace NUClear { // Forward declare reactor and powerplant class Reactor; class PowerPlant; /** * @brief * Environment defines variables that are passed from the installing PowerPlant context * into a Reactor. * * @details * The Environment is used to provide information from the PowerPlant to Reactors. * Each Reactor owns it's own environment and can use it to access useful information. */ class Environment { public: Environment(PowerPlant& powerplant, std::string&& reactor_name, LogLevel log_level) : powerplant(powerplant), log_level(log_level), reactor_name(reactor_name) {} private: friend class PowerPlant; friend class Reactor; /// @brief The PowerPlant to use in this reactor PowerPlant& powerplant; /// @brief The log level for this reactor LogLevel log_level; /// @brief The name of the reactor std::string reactor_name; }; } // namespace NUClear #endif // NUCLEAR_ENVIRONMENT_HPP
37.786885
120
0.748373
KipHamiltons
69b5ebba04f8850e8349c058f453f4aea7dc685a
458
cpp
C++
regression/esbmc-cpp/vector/vector3/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/vector/vector3/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/vector/vector3/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
#include <iostream> #include <vector> using namespace std; int main() { vector<double> student_marks; double mark; char answer; cout << "Enter marks (y/n)? " << endl; cin >> answer; while (answer == 'y' || answer == 'Y') { cout << "Enter value: " << endl; cin >> mark; student_marks.push_back (mark); cout << "More students (y/n)? " << endl; cin >> answer; } return 0; }
16.962963
48
0.510917
shmarovfedor
69b67ca7d032f3175af516a931ae53a0258e218e
358
cpp
C++
projects/codility/max_profit/src/MaxProfit.cpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
2
2021-06-24T21:46:56.000Z
2021-09-24T07:51:04.000Z
projects/codility/max_profit/src/MaxProfit.cpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
null
null
null
projects/codility/max_profit/src/MaxProfit.cpp
antaljanosbenjamin/miscellaneous
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
[ "MIT" ]
null
null
null
#include "MaxProfit.hpp" #include <algorithm> namespace MaxProfit { int solution(std::vector<int> &A) { if (A.empty()) { return 0; } auto minValue = A[0]; auto maxProfit = 0; for (const auto &a: A) { maxProfit = std::max(maxProfit, a - minValue); minValue = std::min(minValue, a); } return maxProfit; } } // namespace MaxProfit
17.047619
50
0.622905
antaljanosbenjamin
69e193f1ab4a32437a72bde3ae316e8d27297faa
1,405
hpp
C++
check/core/matrix/dense/dense_vector/test.hpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
check/core/matrix/dense/dense_vector/test.hpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
check/core/matrix/dense/dense_vector/test.hpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
#pragma once #include <gtest/gtest.h> #include <mcnla/core/matrix.hpp> #include <mcnla/core/la.hpp> using MyTypes = testing::Types<float, double, std::complex<float>, std::complex<double>>; template <typename _Val, mcnla::index_t _len, mcnla::index_t _stride, mcnla::index_t _memsize, mcnla::index_t _offset> class DenseVectorTestBase : public testing::Test { protected: const mcnla::index_t len_ = _len; const mcnla::index_t stride_ = _stride; const mcnla::index_t memsize_ = _memsize; const mcnla::index_t capacity_ = _memsize-_offset; const mcnla::index_t offset_ = _offset; const _Val *valptr0_; mcnla::matrix::DenseVector<_Val> vec_; mcnla::index_t iseed[4] = {0, 0, 0, 1}; virtual void SetUp() { mcnla::matrix::Array<_Val> array(memsize_, offset_); vec_.reconstruct(len_, stride_, array); mcnla::la::larnv<3>(vec_, iseed); valptr0_ = array.get(); } virtual void TearDown() {} }; template <typename _Val> class DenseVectorTest : public testing::Test {}; TYPED_TEST_CASE(DenseVectorTest, MyTypes); template <typename _Val> class DenseVectorTest_Size8_Stride1 : public DenseVectorTestBase<_Val, 8, 1, 10, 2> {}; TYPED_TEST_CASE(DenseVectorTest_Size8_Stride1, MyTypes); template <typename _Val> class DenseVectorTest_Size8_Stride3 : public DenseVectorTestBase<_Val, 8, 3, 25, 3> {}; TYPED_TEST_CASE(DenseVectorTest_Size8_Stride3, MyTypes);
29.270833
118
0.733096
emfomy
69e5d04ca0261fa98c8b3a2a198fd81ea7ed0b87
6,524
cpp
C++
src/network/oni-network-peer.cpp
sina-/granite
95b873bc545cd4925b5cea8c632a82f2d815be6e
[ "MIT" ]
2
2019-08-01T09:18:49.000Z
2020-03-26T05:59:52.000Z
src/network/oni-network-peer.cpp
sina-/granite
95b873bc545cd4925b5cea8c632a82f2d815be6e
[ "MIT" ]
null
null
null
src/network/oni-network-peer.cpp
sina-/granite
95b873bc545cd4925b5cea8c632a82f2d815be6e
[ "MIT" ]
1
2020-03-26T05:59:53.000Z
2020-03-26T05:59:53.000Z
#include <oni-core/network/oni-network-peer.h> #include <enet/enet.h> namespace oni { Peer::Peer() = default; Peer::Peer(const Address *address, u8 peerCount, u8 channelLimit, u32 incomingBandwidth, u32 outgoingBandwidth) { auto result = enet_initialize(); if (result) { throw std::runtime_error("An error occurred while initializing server.\n"); } if (address) { auto enetAddress = ENetAddress{}; enet_address_set_host(&enetAddress, address->host.c_str()); enetAddress.port = address->port; mEnetHost = enet_host_create(&enetAddress, peerCount, channelLimit, incomingBandwidth, outgoingBandwidth); } else { mEnetHost = enet_host_create(nullptr, peerCount, channelLimit, incomingBandwidth, outgoingBandwidth); } assert(mEnetHost); // TODO: Compressor doesnt seem to reduce the bit-rate :/ // result = enet_host_compress_with_range_coder(mEnetHost); // assert(result >= 0); } Peer::~Peer() { enet_host_destroy(mEnetHost); enet_deinitialize(); } void Peer::flush() { enet_host_flush(mEnetHost); auto elapsed = mUploadTimer.elapsedInSeconds(); if (elapsed >= 1.0f) { mUploadBPS = mTotalUpload / elapsed; mTotalUpload = 0; mUploadTimer.restart(); } } void Peer::poll() { ENetEvent event; while (enet_host_service(mEnetHost, &event, 0) > 0) { char ip[16]; enet_address_get_host_ip(&event.peer->address, ip, 16); switch (event.type) { case ENET_EVENT_TYPE_CONNECT: { const auto &peedID = getPeerID(*event.peer); printf("A new client connected from %s:%u with client ID: %s.\n", ip, event.peer->address.port, peedID.c_str()); mPeers[peedID] = event.peer; postConnectHook(&event); break; } case ENET_EVENT_TYPE_RECEIVE: { // TODO: Need to gather stats on invalid packets and their sources! if (!event.packet->data) { return; } if (!event.packet->dataLength) { return; } mTotalDownload += event.packet->dataLength; auto data = event.packet->data; auto header = getHeader(data); auto dataHeadless = event.packet->dataLength - 1; data += 1; handle(event.peer, data, dataHeadless, header); enet_packet_destroy(event.packet); break; } case ENET_EVENT_TYPE_DISCONNECT: { const auto &peerID = getPeerID(*event.peer); printf("%s:%u disconnected. Client ID: %s \n", ip, event.peer->address.port, peerID.c_str()); postDisconnectHook(&event); mPeers.erase(peerID); event.peer->data = nullptr; enet_peer_reset(event.peer); break; } case ENET_EVENT_TYPE_NONE: { break; } } } auto elapsed = mDownloadTimer.elapsedInSeconds(); if (elapsed >= 1.0f) { mDownloadBPS = mTotalDownload / elapsed; mTotalDownload = 0; mDownloadTimer.restart(); } } PacketType Peer::getHeader(const u8 *data) const { if (!data) { return PacketType::UNKNOWN; } auto header = static_cast<PacketType>(*data); return header; } void Peer::send(const u8 *data, size size, ENetPeer *peer) { if (size < 1 || !data) { return; } ENetPacket *packetToServer = enet_packet_create(data, size, ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_NO_ALLOCATE); assert(packetToServer); auto success = enet_peer_send(peer, 0, packetToServer); assert(success == 0); mTotalUpload += size; } void Peer::send(PacketType type, std::string &data, ENetPeer *peer) { if (data.empty() && type != PacketType::SETUP_SESSION && type != PacketType::PING) { return; } data.insert(0, 1, static_cast<std::underlying_type<PacketType>::type>(type)); ENetPacket *packetToServer = enet_packet_create(data.c_str(), data.size(), ENET_PACKET_FLAG_RELIABLE); assert(packetToServer); auto success = enet_peer_send(peer, 0, packetToServer); assert(success == 0); mTotalUpload += data.size(); } void Peer::broadcast(PacketType type, std::string &&data) { // TODO: Might want to whitelist some packet types that have empty payload if (data.size() <= 1) { return; } data.insert(0, 1, static_cast<std::underlying_type<PacketType>::type>(type)); ENetPacket *packetToPeers = enet_packet_create(data.c_str(), data.size(), ENET_PACKET_FLAG_RELIABLE); assert(packetToPeers); enet_host_broadcast(mEnetHost, 0, packetToPeers); mTotalUpload += data.size(); } void Peer::registerPacketHandler(PacketType type, std::function< void(const std::string &, const std::string &)> &&handler) { assert(mPacketHandlers.find(type) == mPacketHandlers.end()); mPacketHandlers[type] = std::move(handler); } void Peer::registerPostDisconnectHook(std::function<void(const std::string &)> &&handler) { mPostDisconnectHook = std::move(handler); } std::string Peer::getPeerID(const ENetPeer &peer) const { return std::to_string(peer.connectID); } r32 Peer::getDownloadKBPS() const { return mDownloadBPS / (1000 * 1); } r32 Peer::getUploadKBPS() const { return mUploadBPS / (1000 * 1); } }
31.365385
115
0.520999
sina-
69e7f5d3e4fe2eed406a3c36d313894971371e64
631
hpp
C++
external/boost_1_60_0/qsboost/type_traits/add_lvalue_reference.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/type_traits/add_lvalue_reference.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/type_traits/add_lvalue_reference.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
// Copyright 2010 John Maddock // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef QSBOOST_TYPE_TRAITS_EXT_ADD_LVALUE_REFERENCE__HPP #define QSBOOST_TYPE_TRAITS_EXT_ADD_LVALUE_REFERENCE__HPP #include <qsboost/type_traits/add_reference.hpp> namespace qsboost{ template <class T> struct add_lvalue_reference { typedef typename qsboost::add_reference<T>::type type; }; #ifndef QSBOOST_NO_CXX11_RVALUE_REFERENCES template <class T> struct add_lvalue_reference<T&&> { typedef T& type; }; #endif } #endif // BOOST_TYPE_TRAITS_EXT_ADD_LVALUE_REFERENCE__HPP
22.535714
62
0.800317
wouterboomsma
69f69cddcb5faf4dfe3b61999f7a0dbe16902631
19,074
cpp
C++
source/UI/Automap.cpp
BodbDearg/phoenix_doom
9648b1cc742634d5aefc18cd3699cd7cb2c0e21c
[ "MIT" ]
29
2019-09-25T06:29:07.000Z
2022-02-20T23:52:36.000Z
source/UI/Automap.cpp
monyarm/phoenix_doom
78c75f985803b94b981469ac32764169ed56aee4
[ "MIT" ]
4
2019-09-25T03:24:31.000Z
2020-09-07T18:38:32.000Z
source/UI/Automap.cpp
monyarm/phoenix_doom
78c75f985803b94b981469ac32764169ed56aee4
[ "MIT" ]
4
2019-09-26T06:43:12.000Z
2020-09-05T16:25:03.000Z
#include "Automap.h" #include "Base/Tables.h" #include "Game/Controls.h" #include "Game/Data.h" #include "Game/Tick.h" #include "GFX/Blit.h" #include "GFX/Video.h" #include "Map/MapData.h" #include "Things/MapObj.h" static constexpr Fixed STEPVALUE = (2 << FRACBITS); // Speed to move around in the map (Fixed) For non-follow mode static constexpr Fixed MAXSCALES = 0x10000; // Maximum scale factor (Largest) static constexpr Fixed MINSCALES = 0x00800; // Minimum scale factor (Smallest) static constexpr float ZOOMIN = 1.02f; static constexpr float ZOOMOUT = 1 / 1.02f; // RGBA5551 colors static constexpr uint16_t COLOR_BROWN = 0x4102u; static constexpr uint16_t COLOR_BLUE = 0x001Eu; static constexpr uint16_t COLOR_RED = 0x6800u; static constexpr uint16_t COLOR_YELLOW = 0x7BC0u; static constexpr uint16_t COLOR_GREEN = 0x0380u; static constexpr uint16_t COLOR_LILAC = 0x6A9Eu; static constexpr uint16_t COLOR_LIGHTGREY = 0x6318u; bool gShowAllAutomapThings; bool gShowAllAutomapLines; // Used to restore the view if the screen goes blank static Fixed gOldPlayerX; // X coord of the player previously static Fixed gOldPlayerY; // Y coord of the player previously static Fixed gUnscaledOldScale; // Previous scale value (at original 320x200 resolution) static Fixed gUnscaledMapScale; // Scaling constant for the automap (at original 320x200 resolution) static Fixed gMapScale; // Scaling constant for the automap (for current screen resolution, i.e has scale factor applied) static uint32_t gMapPixelsW; // Width of the automap display (pixels) static uint32_t gMapPixelsH; // Height of the automap display (pixels) static int32_t gMapClipLx; // Line clip bounds: left x (inclusive) static int32_t gMapClipRx; // Line clip bounds: right x (inclusive) static int32_t gMapClipTy; // Line clip bounds: top y (inclusive) static int32_t gMapClipBy; // Line clip bounds: bottom y (inclusive) static constexpr Fixed NOSELENGTH = 0x200000; // Player's triangle static constexpr Fixed MOBJLENGTH = 0x100000; // Object's triangle //------------------------------------------------------------------------------------------------------------------------------------------ // Multiply a map coord and a fixed point scale value and return the INTEGER result. // I assume that the scale cannot exceed 1.0 and the map coord has no fractional part. // This way I can use a 16 by 16 mul with 32 bit result (Single mul) to speed up the code. //------------------------------------------------------------------------------------------------------------------------------------------ static inline int32_t MulByMapScale(const Fixed mapCoord) noexcept { return ((mapCoord >> FRACBITS) * gMapScale) >> FRACBITS; } //------------------------------------------------------------------------------------------------------------------------------------------ // Multiply two fixed point numbers but return an INTEGER result! //------------------------------------------------------------------------------------------------------------------------------------------ static inline int IMFixMulGetInt(const Fixed a, const Fixed b) noexcept { return fixed16Mul(a, b) >> FRACBITS; } static void updateMapScale() noexcept { gMapScale = fixed16Mul(gUnscaledOldScale, floatToFixed16(gScaleFactor)); } //------------------------------------------------------------------------------------------------------------------------------------------ // Init all the variables for the automap system Called during P_Start when the game is initally loaded. // If I need any permanent art, load it now. //------------------------------------------------------------------------------------------------------------------------------------------ void AM_Start() noexcept { gUnscaledMapScale = (FRACUNIT / 16); // Default map scale factor (0.00625) gUnscaledOldScale = gUnscaledMapScale; updateMapScale(); gMapPixelsW = std::min((uint32_t) std::ceil(320.0f * gScaleFactor), Video::gScreenWidth); gMapPixelsH = std::min((uint32_t) std::ceil(160.0f * gScaleFactor), Video::gScreenHeight); gMapClipLx = (int32_t) std::floor(-160.0f * gScaleFactor); gMapClipRx = (int32_t) std::ceil(160.0f * gScaleFactor); gMapClipTy = (int32_t) std::floor(-80.0f * gScaleFactor); gMapClipBy = (int32_t) std::ceil(80.0f * gScaleFactor); gShowAllAutomapThings = false; // Turn off the cheat gShowAllAutomapLines = false; // Turn off the cheat gPlayer.AutomapFlags &= ~AF_FREE_CAM; // Follow the player gPlayer.AutomapFlags &= ~AF_ACTIVE; // Automap off } //------------------------------------------------------------------------------------------------------------------------------------------ // Draw a pixel on the screen but clip it to the visible area. // I assume a coordinate system where 0,0 is at the upper left corner of the screen. //------------------------------------------------------------------------------------------------------------------------------------------ static void ClipPixel(const int32_t x, const int32_t y, const uint16_t color) noexcept { // Note: casting to uint32_t avoids the need for a '>= 0' check! if ((uint32_t) x < gMapPixelsW && (uint32_t) y < gMapPixelsH) { // On the screen? const uint32_t color32 = Video::rgba5551ToScreenCol(color); Video::gpFrameBuffer[(uint32_t) y * Video::gScreenWidth + (uint32_t) x] = color32; } } //------------------------------------------------------------------------------------------------------------------------------------------ // Draw a line in the automap, I use a classic Bresanhem line algorithm and call a routine to clip // to the visible bounds. All x and y's assume a coordinate system where 0,0 is the CENTER of the // visible screen! // // Even though all the variables are cast as unsigned, they are truly signed. I do this to test // for out of bounds with one compare (x>=0 && x<320) is now just (x<320). Neat eh? //------------------------------------------------------------------------------------------------------------------------------------------ static void DrawLine( const int32_t x1, const int32_t y1, const int32_t x2, const int32_t y2, const uint16_t color ) noexcept { // Coord adjustment: // (1) Move the x coords to the CENTER of the screen // (2) Vertically flip and then CENTER the y int32_t x = x1 + gMapClipRx; const int32_t xEnd = x2 + gMapClipRx; int32_t y = gMapClipBy - y1; const int32_t yEnd = gMapClipBy - y2; // Draw the initial pixel ClipPixel(x, y, color); // Get the distance to travel uint32_t deltaX = (uint32_t)(xEnd - x); uint32_t deltaY = (uint32_t)(yEnd - y); if (deltaX == 0 && deltaY == 0) { // No line here? return; // Exit now } int32_t xStep = 1; // Assume positive step int32_t yStep = 1; if (deltaX & 0x80000000) { // Going left? deltaX = (uint32_t) -(int32_t) deltaX; // Make positive xStep = -1; // Step to the left } if (deltaY & 0x80000000) { // Going up? deltaY = (uint32_t) -(int32_t) deltaY; // Make positive yStep = -1; // Step upwards } uint32_t delta = 0; // Init the fractional step if (deltaX < deltaY) { // Is the Y larger? (Step in Y) do { // Yes, make the Y step every pixel y += yStep; // Step the Y pixel delta += deltaX; // Add the X fraction if (delta >= deltaY) { // Time to step the X? x += xStep; // Step the X delta -= deltaY; // Adjust the fraction } ClipPixel(x, y, color); // Draw a pixel } while (y != yEnd); // At the bottom? return; // Exit } do { // Nope, make the X step every pixel x += xStep; // Step the X coord delta += deltaY; // Adjust the Y fraction if (delta >= deltaX) { // Time to step Y? y += yStep; // Step the Y coord delta -= deltaX; // Adjust the fraction } ClipPixel(x, y, color); // Draw a pixel } while (x != xEnd); // At the bottom? } //------------------------------------------------------------------------------------------------------------------------------------------ // Called by P_PlayerThink before any other player processing //------------------------------------------------------------------------------------------------------------------------------------------ void AM_Control(player_t& player) noexcept { if (GAME_ACTION_ENDED(AUTOMAP_TOGGLE)) { // Toggle event? if (!player.isOptionsMenuActive()) { // Can't toggle in option mode! player.AutomapFlags ^= AF_ACTIVE; // Swap the automap state if both held } } if (!player.isAutomapActive()) { // Is the automap is off? return; // Exit now! } if (player.isAutomapFollowModeActive()) { // Test here to make SURE I get called at least once mobj_t* const pMapObj = player.mo; player.automapx = pMapObj->x; // Mark the automap position player.automapy = pMapObj->y; } gOldPlayerX = player.automapx; // Mark the previous position gOldPlayerY = player.automapy; gUnscaledOldScale = gUnscaledMapScale; // And scale value // Enable/disable follow mode if (GAME_ACTION_ENDED(AUTOMAP_FREE_CAM_TOGGLE)) { player.AutomapFlags ^= AF_FREE_CAM; } // If follow mode if off, then I intercept the joypad motion to move the map anywhere on the screen. if (!player.isAutomapFollowModeActive()) { Fixed step = STEPVALUE; // Multiplier for joypad motion: mul by integer step = fixed16Div(step, gUnscaledMapScale); // Adjust for scale factor // Gather inputs (both analog and digital) float moveFracX = INPUT_AXIS(TURN_LEFT_RIGHT) + INPUT_AXIS(STRAFE_LEFT_RIGHT); float moveFracY = -INPUT_AXIS(MOVE_FORWARD_BACK); if (GAME_ACTION(TURN_RIGHT) || GAME_ACTION(STRAFE_RIGHT)) { moveFracX += 1.0f; } if (GAME_ACTION(TURN_LEFT) || GAME_ACTION(STRAFE_LEFT)) { moveFracX -= 1.0f; } if (GAME_ACTION(MOVE_FORWARD)) { moveFracY += 1.0f; } if (GAME_ACTION(MOVE_BACKWARD)) { moveFracY -= 1.0f; } moveFracX = std::max(moveFracX, -1.0f); moveFracX = std::min(moveFracX, +1.0f); moveFracY = std::max(moveFracY, -1.0f); moveFracY = std::min(moveFracY, +1.0f); // Do movement player.automapx += fixed16Mul(floatToFixed16(moveFracX), step); player.automapy += fixed16Mul(floatToFixed16(moveFracY), step); } // Do zoom in/out { float zoomFrac = -INPUT_AXIS(AUTOMAP_ZOOM_IN_OUT); if (GAME_ACTION(AUTOMAP_ZOOM_OUT)) { zoomFrac -= 1.0f; } if (GAME_ACTION(AUTOMAP_ZOOM_IN)) { zoomFrac += 1.0f; } zoomFrac = std::max(zoomFrac, -1.0f); zoomFrac = std::min(zoomFrac, +1.0f); // Do scaling if (zoomFrac < 0.0f) { const float zoomMulF = (1.0f + zoomFrac) - zoomFrac * ZOOMOUT; gUnscaledMapScale = fixed16Mul(gUnscaledMapScale, floatToFixed16(zoomMulF)); // Perform the scale if (gUnscaledMapScale < MINSCALES) { // Too small? gUnscaledMapScale = MINSCALES; // Set to smallest allowable updateMapScale(); } else { updateMapScale(); } } else { const float zoomMulF = (1.0f - zoomFrac) + zoomFrac * ZOOMIN; gUnscaledMapScale = fixed16Mul(gUnscaledMapScale, floatToFixed16(zoomMulF)); // Perform the scale if (gUnscaledMapScale >= MAXSCALES) { // Too large? gUnscaledMapScale = MAXSCALES; // Set to maximum updateMapScale(); } else { updateMapScale(); } } } } //------------------------------------------------------------------------------------------------------------------------------------------ // Draws the current frame to workingscreen //------------------------------------------------------------------------------------------------------------------------------------------ void AM_Drawer() noexcept { // Clear the screen: normally clear it black but if we are doing cheat confirm fx clear it white! float clearColor[3]; if (gPlayer.cheatFxTicksLeft > 0) { clearColor[0] = (float) gPlayer.cheatFxTicksLeft / 60.0f; clearColor[1] = (float) gPlayer.cheatFxTicksLeft / 60.0f; clearColor[2] = (float) gPlayer.cheatFxTicksLeft / 30.0f; } else { clearColor[0] = 0.0f; clearColor[1] = 0.0f; clearColor[2] = 0.0f; } Blit::blitRect( Video::gpFrameBuffer, Video::gScreenWidth, Video::gScreenHeight, Video::gScreenWidth, 0.0f, 0.0f, 320 * gScaleFactor, 160 * gScaleFactor, clearColor[0], clearColor[1], clearColor[2], 1.0f ); player_t* const pPlayer = &gPlayer; // Get pointer to the player Fixed ox = pPlayer->automapx; // Get the x and y to draw from Fixed oy = pPlayer->automapy; line_t* pLine = gpLines; // Init the list pointer to the line segment array uint32_t drawn = 0; // Init the count of drawn lines uint32_t i = gNumLines; // Init the line count do { if (gShowAllAutomapLines || // Cheat? pPlayer->powers[pw_allmap] || ( // Automap enabled? (pLine->flags & ML_MAPPED) && // If not mapped or don't draw !(pLine->flags & ML_DONTDRAW) ) ) { const int32_t x1 = MulByMapScale(pLine->v1.x - ox); // Source line coords: scale it const int32_t y1 = MulByMapScale(pLine->v1.y - oy); const int32_t x2 = MulByMapScale(pLine->v2.x - ox); // Dest line coords: scale it const int32_t y2 = MulByMapScale(pLine->v2.y - oy); // Is the line clipped? if ((y1 > gMapClipBy && y2 > gMapClipBy) || (y1 < gMapClipTy && y2 < gMapClipTy) || (x1 > gMapClipRx && x2 > gMapClipRx) || (x1 < gMapClipLx && x2 < gMapClipLx) ) { ++pLine; continue; } // Figure out color uint16_t color; if ((gShowAllAutomapLines || pPlayer->powers[pw_allmap]) && // If compmap && !Mapped yet (!(pLine->flags & ML_MAPPED)) ) { color = COLOR_LIGHTGREY; } else if (!(pLine->flags & ML_TWOSIDED)) { color = COLOR_RED; // One-sided line } else if (pLine->special == 97 || pLine->special == 39) { color = COLOR_GREEN; // Teleport line } else if (pLine->flags & ML_SECRET) { color = COLOR_RED; // Secret room? } else if (pLine->special) { color = COLOR_BLUE; // Special line } else if (pLine->frontsector->floorheight != pLine->backsector->floorheight) { color = COLOR_YELLOW; // Floor height change } else { color = COLOR_BROWN; // Other two sided line } DrawLine(x1, y1, x2, y2, color); // Draw the line ++drawn; // A line is drawn } ++pLine; } while (--i); // Draw the position of the player { // Get the size of the triangle into a cached local const Fixed noseScale = fixed16Mul(NOSELENGTH, gMapScale); mobj_t* const pMapObj = gPlayer.mo; int32_t x1 = MulByMapScale(pMapObj->x - ox); // Get the screen int32_t y1 = MulByMapScale(pMapObj->y - oy); // coords angle_t angle = pMapObj->angle >> ANGLETOFINESHIFT; // Get angle of view const int32_t nx3 = IMFixMulGetInt(gFineCosine[angle], noseScale) + x1; // Other points for the triangle const int32_t ny3 = IMFixMulGetInt(gFineSine[angle], noseScale) + y1; angle = (angle - ((ANG90 + ANG45) >> ANGLETOFINESHIFT)) & FINEMASK; const int32_t x2 = IMFixMulGetInt(gFineCosine[angle], noseScale) + x1; const int32_t y2 = IMFixMulGetInt(gFineSine[angle], noseScale) + y1; angle = (angle + (((ANG90 + ANG45) >> ANGLETOFINESHIFT) * 2)) & FINEMASK; x1 = IMFixMulGetInt(gFineCosine[angle], noseScale)+x1; y1 = IMFixMulGetInt(gFineSine[angle], noseScale)+y1; DrawLine(x1, y1, x2, y2, COLOR_GREEN); // Draw the triangle DrawLine(x2, y2, nx3, ny3, COLOR_GREEN); DrawLine(nx3, ny3, x1, y1, COLOR_GREEN); } // Show all map things (cheat) if (gShowAllAutomapThings) { const int32_t objScale = MulByMapScale(MOBJLENGTH); // Get the triangle size mobj_t* pMapObj = gMObjHead.next; const mobj_t* const pPlayerMapObj = pPlayer->mo; while (pMapObj != &gMObjHead) { // Wrapped around? if (pMapObj != pPlayerMapObj) { // Not the player? const int32_t x1 = MulByMapScale(pMapObj->x-ox); int32_t y1 = MulByMapScale(pMapObj->y-oy); const int32_t x2 = x1 - objScale; // Create the triangle const int32_t y2 = y1 + objScale; const int32_t nx3 = x1 + objScale; y1 = y1 - objScale; DrawLine(x1, y1, x2, y2, COLOR_LILAC); // Draw the triangle DrawLine(x2, y2, nx3, y2, COLOR_LILAC); DrawLine(nx3, y2, x1, y1, COLOR_LILAC); } pMapObj = pMapObj->next; // Next item? } } // If less than 5 lines drawn, move to last position! if (drawn < 5) { pPlayer->automapx = gOldPlayerX; // Restore the x,y pPlayer->automapy = gOldPlayerY; gUnscaledMapScale = gUnscaledOldScale; // Restore scale factor as well... updateMapScale(); } }
44.88
141
0.520185
BodbDearg
69f98c91379842f52a50ae79070751d206bcdc88
1,714
cpp
C++
tests/transpose.cpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
tests/transpose.cpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
tests/transpose.cpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
// Copyright 2020 Marcel Wagenländer #include "helper.hpp" #include "tensors.hpp" #include "catch2/catch.hpp" #include <string> int test_transpose(long rows, long columns, bool to_col_major) { std::string home = std::getenv("HOME"); std::string dir_path = home + "/gpu_memory_reduction/alzheimer/data"; std::string flickr_dir_path = dir_path + "/flickr"; std::string test_dir_path = dir_path + "/tests"; std::string path; Matrix<float> mat(rows, columns, true); mat.set_random_values(); if (!to_col_major) {// to_row_major mat.is_row_major_ = false; } path = test_dir_path + "/matrix.npy"; save_npy_matrix_no_trans(&mat, path); if (to_col_major) { to_column_major_inplace(&mat); } else { to_row_major_inplace(&mat); } path = test_dir_path + "/matrix_transposed.npy"; save_npy_matrix_no_trans(&mat, path); path = test_dir_path + "/to_col_major.npy"; if (to_col_major) { write_value(1, path); } else { write_value(0, path); } char command[] = "/home/ubuntu/gpu_memory_reduction/pytorch-venv/bin/python3 /home/ubuntu/gpu_memory_reduction/alzheimer/tests/transpose.py"; system(command); path = test_dir_path + "/value.npy"; return read_return_value(path); } TEST_CASE("Transpose to column-major", "[transpose][colmajor]") { CHECK(test_transpose(99999, 6584, true)); CHECK(test_transpose(85647, 6584, true)); CHECK(test_transpose(84634, 8573, true)); } TEST_CASE("Transpose to row-major", "[transpose][rowmajor]") { CHECK(test_transpose(99999, 6584, false)); CHECK(test_transpose(85647, 6584, false)); CHECK(test_transpose(84634, 8573, false)); }
29.050847
145
0.673862
marwage
69ffe1a6db4e8c4b33c3af64023f90e647acf975
2,248
hpp
C++
src/Conversion/KrnlToAffine/ConvertKrnlToAffine.hpp
redbopo/onnx-mlir
3305a13ddcdfa73ddd6c241b64c8d856e78b9455
[ "Apache-2.0" ]
null
null
null
src/Conversion/KrnlToAffine/ConvertKrnlToAffine.hpp
redbopo/onnx-mlir
3305a13ddcdfa73ddd6c241b64c8d856e78b9455
[ "Apache-2.0" ]
null
null
null
src/Conversion/KrnlToAffine/ConvertKrnlToAffine.hpp
redbopo/onnx-mlir
3305a13ddcdfa73ddd6c241b64c8d856e78b9455
[ "Apache-2.0" ]
null
null
null
/* * SPDX-License-Identifier: Apache-2.0 */ //====------ ConvertKrnlToAffine.hpp - Krnl Dialect Lowering --------------===// // // Copyright 2019-2022 The IBM Research Authors. // // ============================================================================= // // This file declares the lowering of Krnl operations to the affine dialect. // //===----------------------------------------------------------------------===// #pragma once #include "src/Dialect/Krnl/KrnlOps.hpp" #include "src/Pass/Passes.hpp" #include "src/Support/Common.hpp" namespace onnx_mlir { namespace krnl { // We use here a Affine builder that generates Krnl Load and Store ops instead // of the affine memory ops directly. This is because we can still generrate // Krnl Ops while lowring the dialect, and the big advantage of the Krnl memory // operations is that they distinguish themselves if they are affine or not. using AffineBuilderKrnlMem = GenericAffineBuilder<KrnlLoadOp, KrnlStoreOp>; // To assist unroll and jam using UnrollAndJamRecord = std::pair<AffineForOp, int64_t>; using UnrollAndJamList = SmallVector<UnrollAndJamRecord, 4>; using UnrollAndJamMap = std::map<Operation *, UnrollAndJamList *>; void populateKrnlToAffineConversion(LLVMTypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlCopyFromBufferOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlCopyToBufferOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlLoadOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlStoreOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlMatmultOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlMemsetOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); void populateLoweringKrnlTerminatorOpPattern(TypeConverter &typeConverter, RewritePatternSet &patterns, MLIRContext *ctx); } // namespace krnl } // namespace onnx_mlir
36.852459
80
0.733541
redbopo
0e0851bb50aa5cc6aa0046a0e2911c66c4e7b8bd
1,207
cpp
C++
src/htsettings.cpp
hualet/NeteaseMusicForLinux
f0662203658add8c48f474cc67a19da88fe12339
[ "MIT" ]
15
2015-04-19T13:43:11.000Z
2020-08-13T08:17:31.000Z
src/htsettings.cpp
hualet/NeteaseMusicForLinux
f0662203658add8c48f474cc67a19da88fe12339
[ "MIT" ]
3
2015-05-13T14:14:32.000Z
2018-08-29T10:17:24.000Z
src/htsettings.cpp
hualet/NeteaseMusicForLinux
f0662203658add8c48f474cc67a19da88fe12339
[ "MIT" ]
8
2015-04-27T14:20:17.000Z
2021-05-12T10:17:43.000Z
#include "htsettings.h" #include <QDebug> HTSettings::HTSettings(QObject *parent) : QSettings(parent) { } double HTSettings::volume() { return value("General/volume").toDouble(); } void HTSettings::setVolume(double volume) { setValue("General/volume", QVariant(volume)); } QString HTSettings::lastSong() const { return value("General/last_song").toString(); } void HTSettings::setLastSong(QString& lastSong) { setValue("General/last_song", QVariant(lastSong)); } QString HTSettings::userId() const { return value("General/user_id").toString(); } void HTSettings::setUserId(QString& userId) { setValue("General/user_id", QVariant(userId)); emit userIdChanged(); } QString HTSettings::userNickname() const { return value("General/user_nickname").toString(); } void HTSettings::setUserNickname(QString& nickname) { setValue("General/user_nickname", QVariant(nickname)); emit userNicknameChanged(); } QString HTSettings::userAvatarUrl() const { return value("General/user_avatar_url").toString(); } void HTSettings::setUserAvatarUrl(QString& avatarUrl) { setValue("General/user_avatar_url", QVariant(avatarUrl)); emit userAvatarUrlChanged(); }
19.786885
61
0.724938
hualet
0e1034acc2ba7bffa4a982ba7f1679b401540955
3,369
cpp
C++
common/actiongroup.cpp
pastillilabs/situations-symbian
909da8a2067ad33ab8d290a6420a9e8f0abd96e6
[ "Unlicense" ]
4
2016-06-04T20:56:27.000Z
2016-10-11T11:39:27.000Z
common/actiongroup.cpp
pastillilabs/situations-symbian
909da8a2067ad33ab8d290a6420a9e8f0abd96e6
[ "Unlicense" ]
null
null
null
common/actiongroup.cpp
pastillilabs/situations-symbian
909da8a2067ad33ab8d290a6420a9e8f0abd96e6
[ "Unlicense" ]
null
null
null
#include "actiongroup.h" #include "action.h" #include "identifiers.h" ActionGroup::ActionGroup(ActionPlugin& plugin, QObject* parent) : QAbstractListModel(parent) , mPlugin(plugin) , mRunning(false) { QHash<int, QByteArray> roles; roles[ActionRole] = "action"; setRoleNames(roles); } ActionGroup::~ActionGroup() { } void ActionGroup::operator<<(const QVariantMap& in) { const int id(in[Identifiers::keyId].toInt()); if(id == mPlugin.property(Identifiers::groupId)) { const QVariantList instances(in[Identifiers::keyInstances].toList()); foreach(const QVariant& data, instances) addAction(data.toMap()); } } void ActionGroup::operator>>(QVariantMap& out) const { QVariantList instances; foreach(const Action* action, mActions) { instances.append(action->data()); } out[Identifiers::keyId] = mPlugin.property(Identifiers::groupId).toInt(); out[Identifiers::keyInstances] = instances; } void ActionGroup::start() { mRunning = true; // Start all actions QList<Action*>::const_iterator i(mActions.begin()); while(i != mActions.end()) { (*i)->start(false); ++i; } } void ActionGroup::stop() { mRunning = false; // Stop all actions QList<Action*>::const_iterator i(mActions.begin()); while(i != mActions.end()) { (*i)->stop(false); ++i; } } Action* ActionGroup::addAction(const QVariantMap& data) { Action* action(mPlugin.createInstance(this)); addAction(*action); if(data.isEmpty()) action->initialize(); else action->setData(data); if(mRunning) action->start(true); return action; } void ActionGroup::rmvAction(const int action) { if(action >= 0 && action < mActions.count()) { beginRemoveRows(QModelIndex(), action, action); Action* c(mActions.takeAt(action)); if(mRunning) c->stop(true); delete c; endRemoveRows(); } } void ActionGroup::setActionData(const int action, const QVariantMap& data) { if(action >= 0 && action < mActions.count()) { Action* c(mActions.at(action)); c->setData(data); QModelIndex i(index(action)); emit dataChanged(i, i); } } const QVariantMap ActionGroup::getActionData(const int action) { if(action >= 0 && action < mActions.count()) { return mActions.at(action)->data(); } return QVariantMap(); } ActionPlugin& ActionGroup::plugin() const { return mPlugin; } const QVariant ActionGroup::property(const char* name) const { return mPlugin.property(name); } void ActionGroup::addAction(Action& action) { beginInsertRows(QModelIndex(), actions().count(), actions().count()); mActions.append(&action); endInsertRows(); } const QList<Action*>& ActionGroup::actions() const { return mActions; } int ActionGroup::rowCount(const QModelIndex& /*parent*/) const { return mActions.count(); } QVariant ActionGroup::data(const QModelIndex& index, int role) const { QVariant data; if(index.row() >= 0 && index.row() < mActions.size()) { switch(role) { case ActionRole: data = QVariant::fromValue(qobject_cast<QObject*>(mActions.at(index.row()))); break; default: Q_ASSERT(false); } } return data; }
21.458599
89
0.629267
pastillilabs
97bbc93df9b0d4d29fb4a3bd79c7ee98bfdc2078
2,087
cc
C++
tests/neuron_rng_uniform/neuron_rng_uniform_CODE/init.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-06-28T19:48:48.000Z
2020-06-28T19:48:48.000Z
tests/neuron_rng_uniform/neuron_rng_uniform_CODE/init.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-02-10T15:26:29.000Z
2020-02-10T15:26:29.000Z
tests/neuron_rng_uniform/neuron_rng_uniform_CODE/init.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-02-10T10:47:12.000Z
2020-02-10T10:47:12.000Z
#include "definitionsInternal.h" extern "C" const char* initProgramSrc = R"(typedef float scalar; #define fmodf fmod #define TIME_MIN 1.175494351e-38f #define TIME_MAX 3.402823466e+38f __kernel void initializeKernel(__global unsigned int* d_glbSpkCntPop, __global unsigned int* d_glbSpkPop, __global scalar* d_xPop, unsigned int deviceRNGSeed) { const size_t localId = get_local_id(0); const unsigned int id = get_global_id(0); // ------------------------------------------------------------------------ // Local neuron groups // Pop if(id < 1024) { // only do this for existing neurons if(id < 1000) { if(id == 0) { d_glbSpkCntPop[0] = 0; } d_glbSpkPop[id] = 0; { d_xPop[id] = (0.00000000000000000e+00f); } // current source variables } } // ------------------------------------------------------------------------ // Synapse groups with dense connectivity // ------------------------------------------------------------------------ // Synapse groups with sparse connectivity } )"; // Initialize the initialization kernel(s) void initProgramKernels() { initializeKernel = cl::Kernel(initProgram, "initializeKernel"); CHECK_OPENCL_ERRORS(initializeKernel.setArg(0, d_glbSpkCntPop)); CHECK_OPENCL_ERRORS(initializeKernel.setArg(1, d_glbSpkPop)); CHECK_OPENCL_ERRORS(initializeKernel.setArg(2, d_xPop)); } void initialize() { { unsigned int deviceRNGSeed = 0; CHECK_OPENCL_ERRORS(initializeKernel.setArg(3, deviceRNGSeed)); const cl::NDRange globalWorkSize(1024, 1); const cl::NDRange localWorkSize(32, 1); CHECK_OPENCL_ERRORS(commandQueue.enqueueNDRangeKernel(initializeKernel, cl::NullRange, globalWorkSize, localWorkSize)); CHECK_OPENCL_ERRORS(commandQueue.finish()); } } // Initialize all OpenCL elements void initializeSparse() { copyStateToDevice(true); copyConnectivityToDevice(true); }
31.621212
160
0.586488
9inpachi
97bfd6b1afa3c9b4e7424549c0c9a5b3504573fc
3,152
cpp
C++
Proj_Android/app/src/main/cpp/FAssetResolutionConfigurator.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
3
2019-10-10T19:25:42.000Z
2019-12-17T10:51:23.000Z
Framework/[C++ Core]/FAssetResolutionConfigurator.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
null
null
null
Framework/[C++ Core]/FAssetResolutionConfigurator.cpp
nraptis/Metal_OpenGL_MobileGameEngine
cc36682676a9797df8b3a7ee235b99be3ae2f666
[ "MIT" ]
1
2021-11-16T15:29:40.000Z
2021-11-16T15:29:40.000Z
// // FAssetResolutionConfigurator.cpp // Crazy Darts 2 Mac // // Created by Nicholas Raptis on 8/24/19. // Copyright © 2019 Froggy Studios. All rights reserved. // #include "FAssetResolutionConfigurator.hpp" #include "core_includes.h" FAssetResolutionConfigurator::FAssetResolutionConfigurator() { mAssetScale = 1; mPrevAssetScale = 0; mSpriteScale = 1; mPrevSpriteScale = 0; mAutoScale = true; } FAssetResolutionConfigurator::~FAssetResolutionConfigurator() { } void FAssetResolutionConfigurator::Invalidate() { mPrevAssetScale = 0; mPrevSpriteScale = 0; } bool FAssetResolutionConfigurator::ShouldReload() { if (mSpriteScale != mPrevSpriteScale) { return true; } if (mAssetScale != mPrevAssetScale) { return true; } return false; } void FAssetResolutionConfigurator::NotifyReload() { mPrevAssetScale = mAssetScale; mPrevSpriteScale = mSpriteScale; } void FAssetResolutionConfigurator::NotifyScreenPropertiesChanged() { float aScreenWidth = gVirtualDevWidth; //float aCutoff = gVirtualDevHeight * 0.75f; //if (aCutoff < aScreenWidth) { aScreenWidth = aCutoff; } if (aScreenWidth < 100.0f) { aScreenWidth = 100.0f; } //TODO: This will be the magic number that determines our scale... float aExampleImageWidth = 480.0f; //float aExampleImageWidth = 540.0f; float aFactor = (aScreenWidth - 640.0f) / (1412.0 - 640.0f); if (aFactor < 0.0f) { aFactor = 0.0f; } if (aFactor > 1.0f) { aFactor = 1.0f; } float aNumer = aScreenWidth + (aExampleImageWidth * 0.5f) + (aExampleImageWidth * 0.5f * aFactor); float aExpectScale = aNumer / (aExampleImageWidth); float aScale = RoundSpriteScale(aExpectScale); //Log("FAssetResolutionConfigurator::Expect Scale: %f (%f) VD(%f x %f)\n", aScale, aExpectScale, gVirtualDevWidth, gVirtualDevHeight); if (mAutoScale) { mSpriteScale = aScale; mAssetScale = os_getAssetScale(); int aThresholdScale = (int)(mSpriteScale + 0.5f); if (aThresholdScale < 1) { aThresholdScale = 1; } if (aThresholdScale > 4) { aThresholdScale = 4; } if (mAssetScale < aThresholdScale) { mAssetScale = aThresholdScale; } } } void FAssetResolutionConfigurator::SetAssetScale(int pScale) { mAssetScale = pScale; } void FAssetResolutionConfigurator::SetSpriteScale(float pScale) { mSpriteScale = RoundSpriteScale(pScale); } float FAssetResolutionConfigurator::RoundSpriteScale(float pScale) { float aScale = pScale; if (aScale < 2.0f) { if (aScale >= 1.5f) { aScale = 1.5f; } else { aScale = 1.0f; } } else if (aScale >= 2.0f && aScale < 3.0f) { if (aScale >= 2.5f) { aScale = 2.5f; } else { aScale = 2.0f; } } else if (aScale >= 3.0f && aScale < 4.0f) { if (aScale >= 3.5f) { aScale = 3.5f; } else { aScale = 3.0f; } } else { aScale = 4.0f; } return aScale; }
26.711864
138
0.618338
nraptis
97c00ffe046fd1a28516d261c40f835d364d2472
4,754
cpp
C++
lib/Transform/Mixed/DILoopRetriever.cpp
yukatan1701/tsar
a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8
[ "Apache-2.0" ]
14
2019-11-04T15:03:40.000Z
2021-09-07T17:29:40.000Z
lib/Transform/Mixed/DILoopRetriever.cpp
yukatan1701/tsar
a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8
[ "Apache-2.0" ]
11
2019-11-29T21:18:12.000Z
2021-12-22T21:36:40.000Z
lib/Transform/Mixed/DILoopRetriever.cpp
yukatan1701/tsar
a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8
[ "Apache-2.0" ]
17
2019-10-15T13:56:35.000Z
2021-10-20T17:21:14.000Z
//===- DILoopRetriever.cpp - Loop Debug Info Retriever ----------*- C++ -*-===// // // Traits Static Analyzer (SAPFOR) // // Copyright 2018 DVM System Group // // 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. // //===----------------------------------------------------------------------===// // // This file implements loop pass which retrieves some debug information for a // a loop if it is not presented in LLVM IR. // //===----------------------------------------------------------------------===// #include "tsar/Analysis/KnownFunctionTraits.h" #include "tsar/Analysis/Memory/Utils.h" #include "tsar/Transform/Mixed/Passes.h" #include <bcl/utility.h> #include <llvm/ADT/SmallVector.h> #include <llvm/Analysis/LoopInfo.h> #include <llvm/Analysis/LoopPass.h> #include <llvm/InitializePasses.h> #include <llvm/IR/DebugInfoMetadata.h> using namespace llvm; using namespace tsar; namespace { /// This retrieves some debug information for a loop if it is not presented /// in LLVM IR. class DILoopRetrieverPass : public LoopPass, private bcl::Uncopyable { public: /// Pass ID, replacement for typeid. static char ID; /// Constructor. DILoopRetrieverPass() : LoopPass(ID) { initializeDILoopRetrieverPassPass(*PassRegistry::getPassRegistry()); } /// Retrieves debug information for a specified loop. bool runOnLoop(Loop *L, LPPassManager &LPM) override; /// Specifies a list of analyzes that are necessary for this pass. void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<LoopInfoWrapperPass>(); AU.setPreservesAll(); } }; /// Returns first known location in a specified range. /// This function ignores debug and memory marker intrinsics. template<class ItrT> DebugLoc firstInRange(const ItrT &BeginItr, const ItrT &EndItr) { for (auto I = BeginItr; I != EndItr; ++I) { if (!I->getDebugLoc()) continue; if (auto II = dyn_cast<IntrinsicInst>(&*I)) if (isDbgInfoIntrinsic(II->getIntrinsicID()) || isMemoryMarkerIntrinsic(II->getIntrinsicID())) continue; return I->getDebugLoc(); } return DebugLoc(); } } char DILoopRetrieverPass::ID = 0; INITIALIZE_PASS_BEGIN(DILoopRetrieverPass, "loop-diretriever", "Loop Debug Info Retriever", true, false) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_END(DILoopRetrieverPass, "loop-diretriever", "Loop Debug Info Retriever", true, false) bool DILoopRetrieverPass::runOnLoop(Loop *L, LPPassManager &LPM) { auto LoopID = L->getLoopID(); // At this moment the first operand is not initialized, it will be replaced // with LoopID later. SmallVector<Metadata *, 3> MDs(1); if (LoopID) { for (unsigned I = 1, EI = LoopID->getNumOperands(); I < EI; ++I) { MDNode *Node = cast<MDNode>(LoopID->getOperand(I)); if (isa<DILocation>(Node)) return false; MDs.push_back(Node); } } auto Header = L->getHeader(); assert(Header && "Header of the loop must not be null!"); auto *F = Header->getParent(); assert(F && "Function which is owner of a loop must not be null!"); auto DISub = findMetadata(F); auto StabLoc = DISub ? DILocation::get(F->getContext(), 0, 0, DISub->getScope()) : nullptr; bool NeedStabLoc = true; if (auto PreBB = L->getLoopPredecessor()) if (auto Loc = firstInRange(PreBB->rbegin(), PreBB->rend())) { MDs.push_back(Loc.getAsMDNode()); NeedStabLoc = false; } if (NeedStabLoc) if (auto Loc = firstInRange(Header->begin(), Header->end())) { MDs.push_back(Loc.getAsMDNode()); NeedStabLoc = false; } if (auto Latch = L->getLoopLatch()) { auto TI = Latch->getTerminator(); assert(TI && "Basic block is not well formed!"); if (TI->getDebugLoc()) { if (NeedStabLoc && StabLoc) { MDs.push_back(StabLoc); MDs.push_back(TI->getDebugLoc().getAsMDNode()); } else if (!NeedStabLoc) { MDs.push_back(TI->getDebugLoc().getAsMDNode()); } } } LoopID = MDNode::get(L->getHeader()->getContext(), MDs); LoopID->replaceOperandWith(0, LoopID); L->setLoopID(LoopID); return true; } Pass * llvm::createDILoopRetrieverPass() { return new DILoopRetrieverPass(); }
35.214815
80
0.657131
yukatan1701
97c3f9f388f29a31d560c68312af51bfb687b671
1,632
cpp
C++
source/Libraries/AES/MyAES.cpp
febrihendra88/whatsapp-viewer
2b4e727dfba3ad7847a13588854364ca97e4725b
[ "MIT" ]
3
2018-12-21T14:46:32.000Z
2019-02-03T14:12:26.000Z
source/Libraries/AES/MyAES.cpp
febrihendra88/whatsapp-viewer
2b4e727dfba3ad7847a13588854364ca97e4725b
[ "MIT" ]
null
null
null
source/Libraries/AES/MyAES.cpp
febrihendra88/whatsapp-viewer
2b4e727dfba3ad7847a13588854364ca97e4725b
[ "MIT" ]
3
2018-10-27T13:28:29.000Z
2021-04-05T15:35:50.000Z
#include "mbedtls/aes.h" #include "mbedtls/gcm.h" #include "../../Exceptions/Exception.h" int aesBlocksize = 16; void decrypt_aes_cbc_192(const unsigned char *input, unsigned char *output, int length, const unsigned char *key, unsigned char *initVector) { mbedtls_aes_context context; mbedtls_aes_setkey_dec(&context, key, 192); if (mbedtls_aes_crypt_cbc(&context, MBEDTLS_AES_DECRYPT, length, initVector, input, output) != 0) { throw Exception("Could not decrypt block"); } mbedtls_aes_free(&context); } void decrypt_aes_cbc_256(const unsigned char *input, unsigned char *output, int length, const unsigned char *key, unsigned char *initVector) { mbedtls_aes_context context; mbedtls_aes_setkey_dec(&context, key, 256); int result = mbedtls_aes_crypt_cbc(&context, MBEDTLS_AES_DECRYPT, length, initVector, input, output); if (result != 0) { throw Exception("Could not decrypt block"); } mbedtls_aes_free(&context); } void decrypt_aes_gcm(const unsigned char *input, unsigned char *output, int length, const unsigned char *key, unsigned char *initVector) { mbedtls_gcm_context context; mbedtls_gcm_init(&context); if (mbedtls_gcm_setkey(&context, MBEDTLS_CIPHER_ID_AES, key, 256) != 0) { throw Exception("Could not decrypt (mbedtls_gcm_setkey)"); } if (mbedtls_gcm_starts(&context, MBEDTLS_GCM_DECRYPT, initVector, 16, NULL, 0) != 0) { throw Exception("Could not decrypt (mbedtls_gcm_starts)"); } if (mbedtls_gcm_update(&context, length, input, output) != 0) { throw Exception("Could not decrypt (mbedtls_gcm_update)"); } mbedtls_gcm_finish(&context, NULL, 0); mbedtls_gcm_free(&context); }
32.64
140
0.753676
febrihendra88
97c671b04ca89750abeaa38411289ce93a02a286
6,388
cpp
C++
kernel/pager.cpp
shockkolate/shockk-os
1cbe2e14be6a8dd4bbe808e199284b6979dacdff
[ "Apache-2.0" ]
2
2015-11-16T07:30:38.000Z
2016-03-26T21:14:42.000Z
kernel/pager.cpp
shockkolate/shockk-os
1cbe2e14be6a8dd4bbe808e199284b6979dacdff
[ "Apache-2.0" ]
null
null
null
kernel/pager.cpp
shockkolate/shockk-os
1cbe2e14be6a8dd4bbe808e199284b6979dacdff
[ "Apache-2.0" ]
null
null
null
#include <kernel/pager.h> //////////////////// // Pager::Context // //////////////////// Pager::Context::Context(Pager *parent, Directory *dir, bool copy_kernel_pages) : parent(parent), directory(dir) { // initialize directory for(unsigned int table = 0; table < 1024; ++table) { directory->tables[table].present = 0; directory->tables[table].writable = 1; directory->tables[table].unprivileged = 1; directory->tables[table].write_through = 0; directory->tables[table].disable_cache = 0; directory->tables[table].accessed = 0; directory->tables[table].page_size = 0; } // initialize 1:1 mapping for(unsigned int table = 0; table < LOW_MAP; ++table) { directory->tables[table].unprivileged = 0; // reserved for(unsigned int page = 0; page < 1024; ++page) { Map(table, page, (void *)((table * 1024 + page) * PAGE_ALLOCATOR_PAGE_SIZE)); } } // copy kernel pages if(copy_kernel_pages) { for(TableID table = KERNEL_RESERVE; table < 1024; ++table) { directory->tables[table].unprivileged = 0; // reserved Table *table_addr = (Table *)(parent->GetContext().directory->tables[table].address << 12); Make(table, table_addr, false); } } } bool Pager::Context::IsPresent(TableID table, PageID page) { if(!directory->tables[table].present) { return false; } Table *table_addr = (Table *)(directory->tables[table].address << 12); return table_addr->pages[page].present == 1; } void * Pager::Context::AllocAt(TableID table, PageID page) { return Map(table, page, page_allocator_alloc(parent->allocator)); } void * Pager::Context::AllocIn(TableID lower, TableID upper) { // lower bound has to be above low 1:1 mapping if(lower < LOW_MAP) { return NULL; } // attempt to allocate from existing page table for(unsigned int table = lower; table < upper; ++table) { if(directory->tables[table].present) { for(unsigned int page = 0; page < 1024; ++page) { Table *table_addr = (Table *)(directory->tables[table].address << 12); if(!table_addr->pages[page].present) { return AllocAt(table, page); } } } } // attempt to allocate from new page table for(unsigned int table = lower; table < upper; ++table) { if(!directory->tables[table].present) { return AllocAt(table, 0); } } // otherwise fail return NULL; } void Pager::Context::Make(TableID table, Table *table_addr, bool initialize) { directory->tables[table].address = (uint32_t)table_addr >> 12; // we set the present flag last to avoid page table caching issues directory->tables[table].present = 1; // initialize all pages to present=0 if(initialize) { Unmap(table); } } void Pager::Context::Make(TableID table, bool initialize) { Table *table_addr = static_cast<Table *>(page_allocator_reserve(parent->allocator)); Make(table, table_addr, initialize); } void * Pager::Context::Map(TableID table, PageID page, void *phys_addr) { if(!directory->tables[table].present) { Make(table); } Table *table_addr = (Table *)(directory->tables[table].address << 12); table_addr->pages[page].writable = 1; table_addr->pages[page].unprivileged = 1; table_addr->pages[page].write_through = 0; table_addr->pages[page].disable_cache = 0; table_addr->pages[page].accessed = 0; table_addr->pages[page].dirty = 0; table_addr->pages[page].reserved = 0; table_addr->pages[page].address = (uint32_t)phys_addr >> 12; // we set the present flag last to avoid page caching issues table_addr->pages[page].present = 1; return (void *)((table * 1024 + page) * PAGE_ALLOCATOR_PAGE_SIZE); } void Pager::Context::Unmap(TableID table) { if(!directory->tables[table].present) { Make(table); } Table *table_addr = (Table *)(directory->tables[table].address << 12); for(PageID page = 0; page < 1024; ++page) { table_addr->pages[page].present = 0; } } /////////// // Pager // /////////// Pager * Pager::Create(void) { struct PageAllocator *allocator = (struct PageAllocator *)0x100000; allocator->bitmap = (uint8_t *)0x200000; page_allocator_init(allocator, NULL, 4096, LOW_MAP * 1024); // reserve physical range NULL to 0x10000 for(size_t page = 0; page < 0x20; ++page) { page_allocator_alloc_at(allocator, page); } page_allocator_alloc_self(allocator); // reserve physical range 0x50000 to upper bound of 1:1 mapping for(size_t page = 0x50; page < LOW_MAP * 1024; ++page) { page_allocator_alloc_at(allocator, page); } Pager *pager = static_cast<Pager *>(page_allocator_reserve(allocator)); pager->allocator = allocator; auto context = pager->MakeContext(false); pager->Load(context); // reserve page for pager itself Pager *vPager = static_cast<Pager *>( context.Map((uintptr_t)pager / 4096 / 1024, (uintptr_t)pager / 4096 % 1024, pager) ); pager->Reload(); return vPager; } Pager::Context Pager::MakeContext(bool copy_kernel_pages) { Directory *dir = static_cast<Directory *>(page_allocator_reserve(allocator)); return Context(this, dir, copy_kernel_pages); } Pager::Context Pager::ForkContext(Context parent) { static unsigned char buf[PAGE_ALLOCATOR_PAGE_SIZE]; auto old_context = GetContext(); auto context = Pager::MakeContext(); __asm__ ("cli"); for(TableID table = LOW_MAP; table < KERNEL_RESERVE; ++table) { for(unsigned int page = 0; page < 1024; ++page) { if(parent.IsPresent(table, page)) { unsigned char *ptr = (unsigned char *)((table * 1024 + page) * PAGE_ALLOCATOR_PAGE_SIZE); Enable(parent); for(size_t off = 0; off < PAGE_ALLOCATOR_PAGE_SIZE; ++off) { buf[off] = ptr[off]; } context.AllocAt(table, page); Enable(context); for(size_t off = 0; off < PAGE_ALLOCATOR_PAGE_SIZE; ++off) { ptr[off] = buf[off]; } } } } Enable(old_context); __asm__ ("sti"); return context; } void Pager::Load(const Directory *dir) { __asm__ ("mov %0, %%cr3" : : "r" (dir)); } void Pager::Load(Context context) { this->context = context; Reload(); } void Pager::Enable(Context context) { Load(context); Enable(); } void Pager::Enable(void) { uint32_t cr0; __asm__ __volatile__ ("mov %%cr0, %0" : "=r" (cr0)); cr0 |= 0x80000000; /* set bit 31 (paging bit) in cr0 */ __asm__ ("mov %0, %%cr0" : : "r" (cr0)); } void Pager::Disable(void) { uint32_t cr0; __asm__ __volatile__ ("mov %%cr0, %0" : "=r" (cr0)); cr0 &= ~0x80000000; /* clear bit 31 (paging bit) in cr0 */ __asm__ ("mov %0, %%cr0" : : "r" (cr0)); }
28.391111
94
0.673294
shockkolate
97ca1c91bc78f5044677d73567326e1b39acfedc
507
cpp
C++
llistTests.cpp
iankronquist/llist
b04b2af49e5104426b457358bdae2c96540fa27c
[ "MIT" ]
1
2019-04-08T05:16:56.000Z
2019-04-08T05:16:56.000Z
llistTests.cpp
iankronquist/llist
b04b2af49e5104426b457358bdae2c96540fa27c
[ "MIT" ]
null
null
null
llistTests.cpp
iankronquist/llist
b04b2af49e5104426b457358bdae2c96540fa27c
[ "MIT" ]
null
null
null
#include "llist.hpp" #include <cstdio> #include <cassert> bool testllistCreationAndDestruction(); int main() { bool passed = true; passed = testllistCreationAndDestruction(); return 0; } bool testllistCreationAndDestruction() { int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; //struct llist* arr = llistCreate(); llist<int>* arrdanlist = new llist<int>(array, 10); printf("Testing the llistDestroy function\n"); //llistDestroy(arr); delete arrdanlist; printf("Test passed\n"); return 1; }
19.5
52
0.690335
iankronquist
97d94fea5abee56700846d38dcc06c4c5aeec400
3,751
cpp
C++
src/newuser.cpp
dmakian/FlashcardPro
0537e7483015cd0c0ec6bc01875f9d592a9f284d
[ "MIT" ]
null
null
null
src/newuser.cpp
dmakian/FlashcardPro
0537e7483015cd0c0ec6bc01875f9d592a9f284d
[ "MIT" ]
null
null
null
src/newuser.cpp
dmakian/FlashcardPro
0537e7483015cd0c0ec6bc01875f9d592a9f284d
[ "MIT" ]
null
null
null
#include "newuser.h" #include <QtWidgets> NewUser::NewUser(QStackedWidget* pages_in, LogIn* parent_in, UserSelect* select_parent) { QFrame(); pages = pages_in; parent = parent_in; select = select_parent; //qDebug() << "making new user "; QLabel* title = new QLabel("Create New User"); QFont naxa; QFontDatabase db; naxa = db.font("Nexa Light","Normal",64); title->setFont(naxa); QFont naxa2= db.font("Nexa Light", "Normal", 18); QFormLayout* form = new QFormLayout(); username = new QTextEdit(); QLabel *name = new QLabel(tr("Name:")); name->setFont(naxa2); form->addRow(name, username); username->setMaximumHeight(40); username->setFont(naxa2); QLabel *select = new QLabel(tr("Select a Save Directory:")); QHBoxLayout *direct_lay = new QHBoxLayout(); direct = new QTextEdit(); direct->setReadOnly(true); direct->setMaximumHeight(40); direct->setFont(naxa2); select->setFont(naxa2); QPushButton *browseButton = new QPushButton("Browse"); browseButton->setFont(naxa2); QPushButton *cancelButton = new QPushButton("Cancel"); QPushButton *submitButton = new QPushButton("Create User"); connect(browseButton, SIGNAL(clicked()), this, SLOT(browse())); connect(submitButton,SIGNAL(clicked()),this,SLOT(submit())); connect(cancelButton,SIGNAL(clicked()),this,SLOT(cancel())); direct_lay->addWidget(browseButton); direct_lay->addWidget(direct); browseButton->setMaximumWidth(150); form->addRow(select, direct_lay); //form->addRow(submitButton); submitButton->setFont(naxa2); submitButton->setMinimumWidth(150); cancelButton->setMinimumWidth(150); cancelButton->setFont(naxa2); QVBoxLayout* layout = new QVBoxLayout(); layout->addWidget(title, 0, Qt::AlignHCenter); layout->addSpacerItem(new QSpacerItem(this->width(), this->height()/4)); layout->addLayout(form); layout->addSpacerItem(new QSpacerItem(this->width(), this->height()/8)); layout->addWidget(submitButton, 0, Qt::AlignHCenter); layout->addWidget(cancelButton, 0, Qt::AlignHCenter); layout->addSpacerItem(new QSpacerItem(this->width(), this->height()/8)); this->setLayout(layout); } NewUser::~NewUser() { } void NewUser::browse() { for(int i=0; i < parent->curUsers->size(); i++){ if(parent->curUsers->at(i)->username == validName()){ showError("Please choose a unique name"); return; } } pathName = QFileDialog::getExistingDirectory(this,tr("Select a Save Directory"), QDir::homePath()); // QDir dir(pathName); direct->setText(pathName); } void NewUser::submit(){ if(anyEmpty()) { showError("Please fill in all fields."); return; } User* newUser = new User(validName(), pathName ); parent->addNewUser(newUser); if(select != NULL) select->updateUserSelect(); return; } void NewUser::cancel() { int index = pages->currentIndex(); pages->removeWidget(this); pages->setCurrentIndex(index - 1); } bool NewUser::anyEmpty() { if(username->toPlainText().isEmpty()) return true; return false; } bool NewUser::invalidUsername() { for(int i=0; i < parent->curUsers->size(); ++i) { if(parent->curUsers->at(i)->sameName(username->toPlainText())) return true; } return false; } bool NewUser::passwordMismatch() { return false; } QString NewUser::validName() { return username->toPlainText().replace(" ","_"); } void NewUser::showError(QString text) { QMessageBox msgBox; msgBox.critical(0,"Error",text); msgBox.setFixedSize(500,200); return; }
25.868966
103
0.642229
dmakian
97da700cc22468835e5f39229270fa1bf8071776
173
hpp
C++
events/teleport.hpp
ErikBehar/randballs
ae29c22ba46a22f6ee11902043f7fce37c600bcc
[ "MIT" ]
29
2018-05-17T14:08:16.000Z
2021-12-01T08:15:03.000Z
events/teleport.hpp
ErikBehar/randballs
ae29c22ba46a22f6ee11902043f7fce37c600bcc
[ "MIT" ]
4
2018-09-04T13:46:19.000Z
2020-05-15T16:05:35.000Z
events/teleport.hpp
ErikBehar/randballs
ae29c22ba46a22f6ee11902043f7fce37c600bcc
[ "MIT" ]
2
2020-03-30T05:19:37.000Z
2020-04-24T03:02:25.000Z
#pragma once namespace GameEvent { struct Teleport { Teleport(unsigned int who, unsigned int where) : who(who), where(where) { } unsigned int who, where; }; };
12.357143
73
0.66474
ErikBehar
97dcf41ab942e4beb8c620ced8ca785e6143dfcb
127
hpp
C++
source/color.hpp
Lucius-sama/programmiersprachen-aufgabenblatt-2
35c98e73aece7c490269db35d0bfd595086a473a
[ "MIT" ]
null
null
null
source/color.hpp
Lucius-sama/programmiersprachen-aufgabenblatt-2
35c98e73aece7c490269db35d0bfd595086a473a
[ "MIT" ]
null
null
null
source/color.hpp
Lucius-sama/programmiersprachen-aufgabenblatt-2
35c98e73aece7c490269db35d0bfd595086a473a
[ "MIT" ]
null
null
null
#ifndef COLOR_HPP #define COLOR_HPP struct Color { float r = 0.5f; float g = 0.5f; float b = 0.5f; }; #endif // !COLOR_HPP
11.545455
20
0.645669
Lucius-sama
97e24797d4aef427bd2d45913ac1933b8419f4e8
5,276
cpp
C++
Nacro/SDK/FN_ItemUIFunctionLibrary_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_ItemUIFunctionLibrary_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2021-08-11T18:40:26.000Z
2021-08-11T18:40:26.000Z
Nacro/SDK/FN_ItemUIFunctionLibrary_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.Truncate Integer Value // (Static, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // int Value (Parm, ZeroConstructor, IsPlainOldData) // int Min_Fractional_Digits (Parm, ZeroConstructor, IsPlainOldData) // int Max_Fractional_Digits (Parm, ZeroConstructor, IsPlainOldData) // class UObject* __WorldContext (Parm, ZeroConstructor, IsPlainOldData) // struct FText Formatted_Value (Parm, OutParm) void UItemUIFunctionLibrary_C::STATIC_Truncate_Integer_Value(int Value, int Min_Fractional_Digits, int Max_Fractional_Digits, class UObject* __WorldContext, struct FText* Formatted_Value) { static auto fn = UObject::FindObject<UFunction>("Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.Truncate Integer Value"); UItemUIFunctionLibrary_C_Truncate_Integer_Value_Params params; params.Value = Value; params.Min_Fractional_Digits = Min_Fractional_Digits; params.Max_Fractional_Digits = Max_Fractional_Digits; params.__WorldContext = __WorldContext; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Formatted_Value != nullptr) *Formatted_Value = params.Formatted_Value; } // Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.Convert Tier To Integer // (Static, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // TEnumAsByte<EFortItemTier> Tier (Parm, ZeroConstructor, IsPlainOldData) // class UObject* __WorldContext (Parm, ZeroConstructor, IsPlainOldData) // int Numeric_Tier (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UItemUIFunctionLibrary_C::STATIC_Convert_Tier_To_Integer(TEnumAsByte<EFortItemTier> Tier, class UObject* __WorldContext, int* Numeric_Tier) { static auto fn = UObject::FindObject<UFunction>("Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.Convert Tier To Integer"); UItemUIFunctionLibrary_C_Convert_Tier_To_Integer_Params params; params.Tier = Tier; params.__WorldContext = __WorldContext; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Numeric_Tier != nullptr) *Numeric_Tier = params.Numeric_Tier; } // Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.ParseLevelRequiredFromString // (Static, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FString inString (Parm, ZeroConstructor) // class UObject* __WorldContext (Parm, ZeroConstructor, IsPlainOldData) // int outInt (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UItemUIFunctionLibrary_C::STATIC_ParseLevelRequiredFromString(const struct FString& inString, class UObject* __WorldContext, int* outInt) { static auto fn = UObject::FindObject<UFunction>("Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.ParseLevelRequiredFromString"); UItemUIFunctionLibrary_C_ParseLevelRequiredFromString_Params params; params.inString = inString; params.__WorldContext = __WorldContext; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (outInt != nullptr) *outInt = params.outInt; } // Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.Add Alteration Widgets // (Static, Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UVerticalBox* Host_Widget (Parm, ZeroConstructor, IsPlainOldData) // class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData) // int PreviewLevel (Parm, ZeroConstructor, IsPlainOldData) // bool ShowInVaultDetails (Parm, ZeroConstructor, IsPlainOldData) // class UObject* __WorldContext (Parm, ZeroConstructor, IsPlainOldData) void UItemUIFunctionLibrary_C::STATIC_Add_Alteration_Widgets(class UVerticalBox* Host_Widget, class UFortItem* Item, int PreviewLevel, bool ShowInVaultDetails, class UObject* __WorldContext) { static auto fn = UObject::FindObject<UFunction>("Function ItemUIFunctionLibrary.ItemUIFunctionLibrary_C.Add Alteration Widgets"); UItemUIFunctionLibrary_C_Add_Alteration_Widgets_Params params; params.Host_Widget = Host_Widget; params.Item = Item; params.PreviewLevel = PreviewLevel; params.ShowInVaultDetails = ShowInVaultDetails; params.__WorldContext = __WorldContext; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
40.584615
190
0.692381
Milxnor
97f02180ee282f87987d33bfc3d249fcbc045da8
352
cpp
C++
tutorial/expl-19.cpp
qPCR4vir/sdsl-lite
3ae7ac30c3837553cf20243cc3df8ee658b9f00f
[ "BSD-3-Clause" ]
20
2017-12-26T16:04:18.000Z
2022-02-09T03:30:13.000Z
tutorial/expl-19.cpp
Irallia/sdsl-lite
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
[ "BSD-3-Clause" ]
6
2018-11-12T15:14:24.000Z
2021-04-29T14:07:13.000Z
tutorial/expl-19.cpp
Irallia/sdsl-lite
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
[ "BSD-3-Clause" ]
4
2018-11-12T14:36:34.000Z
2021-01-26T22:16:32.000Z
#include <sdsl/suffix_arrays.hpp> #include <iostream> #include <algorithm> using namespace std; using namespace sdsl; int main() { csa_wt<wt_int<rrr_vector<63>>> csa; construct_im(csa, "1 8 15 23 1 8 23 11 8", 'd'); cout << " i SA ISA PSI LF BWT T[SA[i]..SA[i]-1]" << endl; csXprintf(cout, "%2I %2S %3s %3P %2p %3B %:3T", csa); }
23.466667
63
0.613636
qPCR4vir
97f5a8bae7fb3e4b5b36b837b4d4ee34bd3a9fed
1,109
hpp
C++
library/include/darcel/reactors/none_reactor.hpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/include/darcel/reactors/none_reactor.hpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/include/darcel/reactors/none_reactor.hpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
1
2020-04-17T13:25:25.000Z
2020-04-17T13:25:25.000Z
#ifndef DARCEL_NONE_REACTOR_HPP #define DARCEL_NONE_REACTOR_HPP #include <memory> #include "darcel/reactors/reactor.hpp" #include "darcel/reactors/reactor_unavailable_exception.hpp" #include "darcel/reactors/reactors.hpp" namespace darcel { //! A reactor that never produces an evaluation. template<typename T> class NoneReactor final : public Reactor<T> { public: using Type = typename Reactor<T>::Type; //! Constructs a none reactor. NoneReactor() = default; BaseReactor::Update commit(int sequence) override; Type eval() const override; }; //! Makes a none reactor. template<typename T> auto make_none_reactor() { return std::make_shared<NoneReactor<T>>(); }; //! Makes a none reactor. template<typename T> auto none() { return make_none_reactor<T>(); } template<typename T> BaseReactor::Update NoneReactor<T>::commit(int sequence) { return BaseReactor::Update::COMPLETE_EMPTY; } template<typename T> typename NoneReactor<T>::Type NoneReactor<T>::eval() const { throw ReactorUnavailableException(); } } #endif
23.104167
62
0.704238
spiretrading
3f03a4c58a3b54235c29b6398a4a68ca05bf86de
5,580
cpp
C++
testogl.cpp
twareintor/Spaceship-simulator
9b960eebbf86d36bad908e822f481a87247424c1
[ "MIT" ]
null
null
null
testogl.cpp
twareintor/Spaceship-simulator
9b960eebbf86d36bad908e822f481a87247424c1
[ "MIT" ]
null
null
null
testogl.cpp
twareintor/Spaceship-simulator
9b960eebbf86d36bad908e822f481a87247424c1
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Copyright (c) 2007 - 2018 Claudiu Ciutacu "Twareintor" */ // copyright (c) 2007 - 2018 Claudiu Ciutacu "Twareintor" //---+----3----+----2----+----1----+---<>---+----1----+----2----+----3----+----4 // #include "globals.h" #include "testogl.h" #include "triangles.h" //---+----3----+----2----+----1----+---<>---+----1----+----2----+----3----+----4 float g_fAng; // no more in use! no more in use! no more in use! HBITMAP g_hBmp[24]; // handles to global bitmap images... float XUP[3] = {1,0,0}, XUN[3] = {-1, 0, 0}, YUP[3] = {0,1,0}, YUN[3] = { 0,-1, 0}, ZUP[3] = {0,0,1}, ZUN[3] = { 0, 0,-1}, ORG[3] = {0,0,0}; GLfloat viewangle = 0, tippangle = 0, vertangle = 0, traj[120][3]; GLfloat d[3] = {0.1, 0.1, 0.1}; GLfloat fL[] = {0.0, 0.0, 1.0, 25.0}; GLfloat fA[] = {0.0, 0.0, 0.0}; GLfloat fMovL = 1; GLfloat xAngle = 0.0, yAngle = 0.0, zAngle = 0.0; GLfloat zoomF = 1.0f; GLboolean booExit = false; VEC3 pos, rad; //---+----3----+----2----+----1----+---<>---+----1----+----2----+----3----+----4 //---+----3----+----2----+----1----+---<>---+----1----+----2----+----3----+----4 void Redraw(HDC hdc, BOOL bLight, CxCam* pCam, float* params) { // main function that draws all glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_SMOOTH); glShadeModel(GL_SMOOTH); glLoadIdentity(); gluLookAt(pCam->x, pCam->y, pCam->z, pCam->x0, pCam->y0, pCam->z0, pCam->xv, pCam->yv, pCam->zv); // // // // // // // Begin of: Drawing objects: // Triad (); TheSky(pCam); // RenderTriangles(); // BUG: Assertion fault message from MinGW!!! (pfnGlGenBuffers() unusual way) // TheSea(); glEnable(GL_LIGHT0); // TheStar(pCam); // shows the sun on the sky// long distance simulated by moving with the camera.. TheStar2(pCam); ThePlanet(pCam, params[0]); // shows the planet, relative to position of the cam, simulating a very long distance... TheAsteroid(pCam, 0, pos, rad); // /**************** begin of terrestrial objects: **************************/ // DrawCubes(8, 240); // cubes // CUBURI> Rows, Units // it was just for testing // StreetLights(60, 8.0); // lighting spheres // pairs, distance between // TheHall(); // CeilLightsOnHall(); // RestrictCamOnTheHall(pCam); // Scari(15); // Punte(); /**************** ~~end of terrestrial objects: **************************/ glDisable(GL_LIGHT0); // // // // // // // End of: Drawing objects SwapBuffers(hdc); } void Initializations(float fFovy, float fWidth, float fHeight) { // glClearColor(0.0, 0.0, 0.0, 0.0); // in space glMatrixMode(GL_PROJECTION); gluPerspective(45.0, 16.0/9.0, 0.1, 10120.0); glMatrixMode(GL_MODELVIEW); // srand(time(NULL)); pos.x = (float)(rand()%400); srand(time(NULL)); pos.y = (float)(rand()%400); srand(time(NULL)); pos.z = (float)(rand()%100); srand(time(NULL)); rad.x = (float)(rand()%100); // } void Finalizaitions() { // MessageBoxW(NULL, L"Finalization", L"Program terminated", MB_OK); } //---+----3----+----2----+----1----+---<>---+----1----+----2----+----3----+----4 //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || ////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// // || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || ////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// // || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || || ////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
46.115702
130
0.3
twareintor
3f04d3a1ab1a2e4a2d80d90cb77aae08ffd5f12c
28,768
cpp
C++
8 Puzzle/Main.cpp
CaiGwatkin/CPP_AI8Puzzle
8c98a48eb6aa75d8da8254d57297039101833122
[ "MIT" ]
null
null
null
8 Puzzle/Main.cpp
CaiGwatkin/CPP_AI8Puzzle
8c98a48eb6aa75d8da8254d57297039101833122
[ "MIT" ]
null
null
null
8 Puzzle/Main.cpp
CaiGwatkin/CPP_AI8Puzzle
8c98a48eb6aa75d8da8254d57297039101833122
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // 8-PUZZLE PROBLEM // // Start-up codes by n.h.reyes@massey.ac.nz // // Name(s): Cai Gwatkin - 15146508 // Date: // ////////////////////////////////////////////////////////////////////////// #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> //used by transform - to lower case #include <exception> #include "graphics.h" #include "algorithm.h" using namespace std; #define OUTPUT_LENGTH 2 /* Length of output string. */ const int HEIGHT = 400; /**< Height of board for rendering in pixels. */ const int WIDTH = 400; /**< Width of board for rendering in pixels. */ ////////////////////////////////////////////////////// // Function prototypes void update(int **board); void displayBoard(string const elements); void AnimateSolution(string const initialState, string const goalState, string path); ////////////////////////////////////////////////////// /** * Main function to kick off the game. */ int main( int argc, char* argv[] ) { string path; // Following commented code for testing only //~ cout << "=========<< SEARCH ALGORITHMS >>=========" << endl; if (argc < 5) // If not enough arguments program should be exited. { cout << "SYNTAX: main.exe <TYPE_OF_RUN = \"batch_run\" or \"single_run\"> ALGORITHM_NAME \"INITIAL STATE\" \"GOAL STATE\" " << endl; // Display error text to show what should have been passed to program. exit(1); // Close executable. } // Following commented code for testing only //~ cout << "Parameters supplied" << endl; //~ for (int i=1; i < argc; i++) //~ { //~ cout << setw(2) << i << ") " << argv[i] << endl; //~ } // Initialise variables. string typeOfRun(argv[1]); // Type of run, should be batch_run or single_run. string algorithmSelected(argv[2]); // The algorithm selected to be used to solve the puzzle. string initialState(argv[3]); // Initial state of the puzzle. string goalState(argv[4]); // Goal state for the puzzle. std::transform(typeOfRun.begin(), typeOfRun.end(), typeOfRun.begin(), ::tolower); // Ensure type of run is lower-case. std::transform(algorithmSelected.begin(), algorithmSelected.end(), algorithmSelected.begin(), ::tolower); // Ensure algorithm selected is lower-case. int pathLength = 0; // The path length of the solution. int depth = 0; // The depth of the solution. int numOfStateExpansions = 0; // The number of state expansions performed during run-time. int maxQLength = 0; // The max length that the queue was during run-time. int numOfDeletionsFromMiddleOfHeap = 0; // The number of deletions of elements from the middle of the heap. int numOfLocalLoopsAvoided = 0; // The number of local loops detected and avoided. int numOfAttemptedNodeReExpansions = 0; // The number of attempted expansions of nodes already expanded. float actualRunningTime = 0.0; // The time it took the algorithm to find the solution. // Following commented code for testing only //~ cout << "typeOfRun = " << typeOfRun << endl; //~ cout << "algorithmSelected = " << algorithmSelected << endl; try { if (typeOfRun == "single_run") cout << endl << "===========================================<< EXPERIMENT RESULTS >>===========================================" << endl; // Run algorithm. if (algorithmSelected == "breadth_first_search") // Check if algorithm selected is Breadth First Search. { path = breadthFirstSearch(initialState, goalState, numOfStateExpansions, maxQLength, actualRunningTime, numOfLocalLoopsAvoided); // Solve using Breadth First Search. } else if (algorithmSelected == "breadth_first_search_vlist") // Check if algorithm selected is Breadth First Search with Visited List. { path = breadthFirstSearch_with_VisitedList(initialState, goalState, numOfStateExpansions, maxQLength, actualRunningTime); // Solve using Breadth First Search with Visited List. } else if (algorithmSelected == "pds_no_vlist") // Check if algorithm selected is Progressive Deepenging Search. { path = progressiveDeepeningSearch_No_VisitedList(initialState, goalState, numOfStateExpansions, maxQLength, actualRunningTime, numOfLocalLoopsAvoided, 5000); // Solve using Progressive Deepenging Search. } else if (algorithmSelected == "pds_nonstrict_vlist") // Check if algorithm selected is Progressive Deepenging Search with Non-Strict Visited List. { path = progressiveDeepeningSearch_with_NonStrict_VisitedList(initialState, goalState, numOfStateExpansions, maxQLength, actualRunningTime, 5000); // Solve using Progressive Deepenging Search with Non-Strict Visited List. } else if (algorithmSelected == "astar_explist_misplacedtiles") // Check if algorithm selected is A* with Expanded List using Misplaced Tiles for heuristic values. { path = aStar_ExpandedList(initialState, goalState, numOfStateExpansions, maxQLength, actualRunningTime, numOfDeletionsFromMiddleOfHeap,numOfLocalLoopsAvoided ,numOfAttemptedNodeReExpansions, MISPLACED_TILES); // Solve using A* with Expanded List using Misplaced Tiles for heuristic values. } else if (algorithmSelected == "astar_explist_manhattan") // Check if algorithm selected is A* with Expanded List using Manhattan Distance for heuristic values. { path = aStar_ExpandedList(initialState, goalState, numOfStateExpansions, maxQLength, actualRunningTime, numOfDeletionsFromMiddleOfHeap,numOfLocalLoopsAvoided ,numOfAttemptedNodeReExpansions, MANHATTAN_DISTANCE); // Solve using A* with Expanded List using Manhattan Distance for heuristic values. } pathLength = path.size(); // Output results. if (algorithmSelected == "breadth_first_search") { cout << setw(31) << std::left << "1) breadth_first_search"; } else if (algorithmSelected == "breadth_first_search_vlist") { cout << setw(31) << std::left << "2) breadth_first_search_vlist"; } else if (algorithmSelected == "pds_no_vlist") { cout << setw(31) << std::left << "3) pds_no_vlist"; } else if (algorithmSelected == "pds_nonstrict_vlist") { cout << setw(31) << std::left << "4) pds_nonstrict_vlist"; } else if (algorithmSelected == "astar_explist_misplacedtiles") { cout << setw(31) << std::left << "5) astar_explist_misplacedtiles"; } else if (algorithmSelected == "astar_explist_manhattan") { cout << setw(31) << std::left << "6) astar_explist_manhattan"; } } catch (exception &e) // Ensure no exception when running algorithm. { cout << "Standard exception: " << e.what() << endl; } if (typeOfRun == "batch_run") // Check if a batch run is being performed and output results. { string reasonForNonCompletion = ""; if (pathLength == 0) // Path length of 0 means no solution was found by the algorthm. { reasonForNonCompletion = "no_solution"; } else if (path == "memory overload") // Memory overloaded and algorithm aborted. { reasonForNonCompletion = "RAM_overload"; path = ""; // Clear path so no solution animated. pathLength = 0; // Path length updated. } else if (path == "ultimate max depth reached") // PDS algorithm reached ultimate max depth and aborted. { reasonForNonCompletion = "max_depth_reached"; path = ""; // Clear path so no solution animated. pathLength = 0; // Path length updated. } cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(10) << pathLength; cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(10) << numOfStateExpansions; cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(19) << maxQLength; cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(15) << actualRunningTime; cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(15) << numOfDeletionsFromMiddleOfHeap; cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(15) << numOfAttemptedNodeReExpansions; cout << setprecision(6) << std::setfill(' ') << std::fixed << std::right << ' ' << setw(19) << reasonForNonCompletion << endl; } else if (typeOfRun == "single_run") // Check if a single run is being performed and output results. { if (pathLength == 0) { cout << "\n\n*---- NO SOLUTION found. (Q is empty!) ----*" << endl; // Path length of 0 means no solution was found by the algorthm. } else if (path == "memory overload") // Memory overloaded and algorithm aborted. { cout << "\n\n*---- NO SOLUTION found. (RAM overloaded!) ----*" << endl; path = ""; // Clear path so no solution animated. pathLength = 0; // Path length updated. } else if (path == "ultimate max depth reached") // PDS algorithm reached ultimate max depth and aborted. { cout << "\n\n*---- NO SOLUTION found. (Ultimate max depth reached!) ----*" << endl; path = ""; // Clear path so no solution animated. pathLength = 0; // Path length updated. } cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << endl << endl << "Initial State:" << std::fixed << ' ' << setw(12) << initialState << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << "Goal State:" << std::fixed << ' ' << setw(12) << goalState << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << endl << "Path Length:" << std::fixed << ' ' << setw(12) << pathLength << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << "Num Of State Expansions:" << std::fixed << ' ' << setw(12) << numOfStateExpansions << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << "Max Q Length:" << std::fixed << ' ' << setw(12) << maxQLength << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << "Actual Running Time:" << std::fixed << ' ' << setprecision(6) << setw(12) << actualRunningTime << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << "Num of Deletions from MiddleOfHeap:" << std::fixed << ' ' << setprecision(6) << setw(12) << numOfDeletionsFromMiddleOfHeap << endl; cout << setprecision(6) << setw(25) << std::setfill(' ') << std::right << "Num of Attempted Node ReExpansions:" << std::fixed << ' ' << setprecision(6) << setw(12) << numOfAttemptedNodeReExpansions << endl; cout << "===============================================================================================================" << endl << endl; if (path != "") AnimateSolution(initialState, goalState, path); // If a solution was found for single run then animation should be displayed. } // Show that we have exited without an error. return 0; } /* * Flicker-free implementation of the 8-puzzle board game using the BGI * graphics library for Windows. */ void AnimateSolution(string const initialState, string const goalState, string path) { cout << endl << "--------------------------------------------------------------------" << endl; if (path == "") // If no solution found then nothing to animate. { cout << endl << "Nothing to animate." << endl; return; } else // Otherwise animate the solution. { cout << endl << "Animating solution..." << endl; cout << "Plan of action = " << path << endl; } Puzzle *p = new Puzzle(initialState, goalState); // Create new puzzle object for the puzzle. Puzzle *nextState; // To be used to create the next state of the puzzle. string strState = p->toString(); // The state of the puzzle as a string to be displayed to user. displayBoard(strState); // Display the initial state of the puzzle. cout << "--------------------------------------------------------------------" << endl; for (unsigned int i = 0; i < path.length(); i++) // Itterate over steps in path to display path to user. { cout << endl << "Step #" << i + 1 << ") "; switch (path[i]) // Check the value of the character at the point in the path and display the corresponding word. { case 'L': nextState = p->move(-1, 0); cout << "[LEFT]" << endl; break; case 'U': nextState = p->move(0, -1); cout << "[UP]" << endl; break; case 'R': nextState = p->move(1, 0); cout << "[RIGHT]" << endl; break; case 'D': nextState = p->move(0, 1); cout << "[DOWN]" << endl; break; } delete p; // Free memory. p = nextState; // Make next puzzle state the current puzzle state. strState = p->toString(); // Update the string of current state of puzzle. displayBoard(strState); // Display current state. } delete p; // Free memory. cout << endl << "Animation done." << endl; // Done. cout << "--------------------------------------------------------------------" << endl; } /** * Update the board and draw it to the screen. This function displays the * board updates in a flicker-free way. * * @param board 3 x 3 array containing the current board state, * 0 indicates an empty space. */ void displayBoard(string const elements) { // Setting up the graphics. int board[3][3]; // 3x3 board. int n = 0; for (int i = 0; i < 3; i++) // Loop through rows of board. { for (int j = 0; j < 3; j++) // Loop through columns. { board[i][j] = elements.at(n) - '0'; // Sets the value of the element at that coordinate. n++; // Next element. } } static bool setup = false; // Setup initialised to false as setup has not occured. if (!setup) // If not setup then setup. { int graphDriver = 0; int graphMode = 0; initgraph(&graphDriver, &graphMode, "", WIDTH, HEIGHT); // Initialise the graph. settextstyle(TRIPLEX_FONT, HORIZ_DIR, 3); // Set text style for start message. settextjustify(CENTER_TEXT, CENTER_TEXT); // Set text to centred. outtextxy(getmaxx()/2,getmaxy()/2,"press any key to start."); // Output start message. cout << endl << endl << "press any key to start." << endl << endl; getch(); // Wait for user input. setup = true; // Setup now complete. } // Variables for the function. int xIncrement = (WIDTH - 40) / 3; // Grid's raster width. int yIncrement = ((HEIGHT - 6) - 40) / 3; // Grid's raster height. int x = 0; // Temporary x positions. int y = 0; // Temporary y positions. char outputString[OUTPUT_LENGTH]; // Holder for output strings in the GUI. static bool visual; // Indicator which visual page to draw to prevent flickers. // Initalising the variables. strncpy(outputString, "", OUTPUT_LENGTH); // Even though this is not necessary here the protected version of "strcpy" is used in this case. It should ALWAYS be used to prevent boundary overwrites! // Initialising the GUI. setactivepage(visual); // The current active page is set as visual, so that updates happen to a different screen before being shown. setbkcolor(BLACK); // Background colour is set to black. cleardevice(); // Clear the screen. setfillstyle(SOLID_FILL, WHITE); // Fill with text with white. settextstyle(GOTHIC_FONT, HORIZ_DIR, 6); // Set text style. settextjustify(CENTER_TEXT, CENTER_TEXT); // Make text centred. // Display different coloured squares for different numbers. y = 10; // Initialise y coordinate for first square. for (int i = 0; i < 3; i++) // Loop through each row to make 3 squares tall. { x = 10; // Initial x coordinate for square. for (int j = 0; j < 3; j++) // Loop through each column to make 3 squares wide. { if (board[i][j] != 0) // Colour all squares except top left. { setcolor(board[i][j]); // Set different colour for each square. bar(x, y, x + xIncrement, y + yIncrement); // Draw square. } x += xIncrement; // Make x coordinate edge of drawn square. x += 10; // Increment x to go to next square. } y += yIncrement; // Make y coordinate edge of drawn square. y += 10; // Increment y to go to next square. } /* Display the actual numbers. */ y = 8 * HEIGHT / 40; // Initialise y coordinate for first square. for (int i = 0; i < 3; i++) // Loop through each row of squares. { x = WIDTH / 6; // Initialise x coordinate for first square. for (int j = 0; j < 3; j++) // Loop through each column of squares. { setcolor(WHITE); // Use white for colour of text for the square's number. setbkcolor(board[i][j]); // Set the text's background colour to that of the square. if (board[i][j] != 0) // Number all squares except top left. { snprintf(outputString, OUTPUT_LENGTH, "%d", board[i][j]); // Create the string with the squares number as outputString. outtextxy(x, y, outputString); // Output the text in the square. moveto(0, 0); // Move back origin of outtextxy. } x += 2 * (WIDTH / 6); // Increment x to go to next column. } y += 13 * HEIGHT / 40; // Increment y to go to next row. } // Set the page to display. setvisualpage(visual); // Set the page to display. visual = !visual; // Make visual not previous visual so that updates are all finished before displayed. delay(100); // Wait 100 milliseconds. } /** * Update the board and draw it to the screen. This function displays the * board updates in a flicker-free way. * * @param board 3 x 3 array containing the current board state, * 0 indicates an empty space. */ /* void update(int **board) { // Setting up the graphics. static bool setup = false; // Not setup yet. if (!setup) // If not setup then setup. { int graphDriver = 0; int graphMode = 0; initgraph(&graphDriver, &graphMode, "", WIDTH, HEIGHT); // Initialise the graph. setup = true; // Setup complete. } // Variables for the function. int xIncrement = (WIDTH - 40) / 3; // Grid's raster width. int yIncrement = ((HEIGHT - 6) - 40) / 3; // Grid's raster height. int x = 0; // Temporary x positions. int y = 0; // Temporary y positions. char outputString[OUTPUT_LENGTH]; // Holder for output strings in the GUI. static bool visual; // Indicator which visual page to draw to to prevent flickers. // Initalising the variables. strncpy(outputString, "", OUTPUT_LENGTH); // Initialise outputString to blank string. // Initialising the GUI. setactivepage(visual); // The current active page is set as visual, so that updates happen to a different screen before being shown. setbkcolor(BLACK); // Background colour is set to black. cleardevice(); // Clear the screen. setfillstyle(SOLID_FILL, WHITE); // Fill with text with white. settextstyle(GOTHIC_FONT, HORIZ_DIR, 6); // Set text style. settextjustify(CENTER_TEXT, CENTER_TEXT); // Make text centred. // Display different coloured squares for different numbers. y = 10; // Initialise y coordinate for first square. for (int i = 0; i < 3; i++) // Loop through each row to make 3 squares tall. { x = 10; // Initial x coordinate for square. for (int j = 0; j < 3; j++) // Loop through each column to make 3 squares wide. { if (board[i][j] != 0) // Colour all squares except top left. { setcolor(board[i][j]); // Set different colour for each square. bar(x, y, x + xIncrement, y + yIncrement); // Draw square. } x += xIncrement; // Make x coordinate edge of drawn square. x += 10; // Increment x to go to next square. } y += yIncrement; // Make y coordinate edge of drawn square. y += 10; // Increment y to go to next square. } // Display the actual numbers. y = 8 * HEIGHT / 40; // Initialise y coordinate for first square. for (int i = 0; i < 3; i++) // Loop through each row of squares. { x = WIDTH / 6; // Initialise x coordinate for first square. for (int j = 0; j < 3; j++) // Loop through each column of squares. { setcolor(WHITE); // Use white for colour of text for the square's number. setbkcolor(board[i][j]); // Set the text's background colour to that of the square. if (board[i][j] != 0) // Number all squares except top left. { snprintf(outputString, OUTPUT_LENGTH, "%d", board[i][j]); // Create the string with the squares number as outputString. outtextxy(x, y, outputString); // Output the text in the square. moveto(0, 0); // Move back origin of outtextxy. } x += 2 * (WIDTH / 6); // Increment x to go to next column. } y += 13 * HEIGHT / 40; // Increment y to go to next row. } // Set the page to display. setvisualpage(visual); // Set the page to display. visual = !visual; // Make visual not previous visual so that updates are all finished before displayed. delay(100); // Wait 100 milliseconds. }*/
57.767068
308
0.459017
CaiGwatkin
3f053570b45d96020f9f006c691383e5311de321
12,093
cpp
C++
src/bkGL/texture/TextureCubeMap.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
4
2018-12-08T15:35:38.000Z
2021-08-06T03:23:06.000Z
src/bkGL/texture/TextureCubeMap.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
src/bkGL/texture/TextureCubeMap.cpp
BenKoehler/bk
53d9ce99cf54fe01dbb3b22ff2418cd102e20ee3
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <bkGL/texture/TextureCubeMap.h> #include <climits> #include <future> #include <string> #include <bk/Image> #include <bkGL/texture/Texture2D.h> #include <bk/Matrix> #include <bk/ThreadPool> namespace bk { //==================================================================================================== //===== MEMBERS //==================================================================================================== struct TextureCubeMap::Impl { GLenum texture_unit; Impl() : texture_unit(GL_TEXTURE0) { /* do nothing */ } Impl(const Impl&) = delete; Impl(Impl&&) noexcept = default; ~Impl() = default; [[maybe_unused]] Impl& operator=(const Impl&) = delete; [[maybe_unused]] Impl& operator=(Impl&&) noexcept = default; }; //==================================================================================================== //===== CONSTRUCTORS & DESTRUCTOR //==================================================================================================== /// @{ -------------------------------------------------- CTOR #ifndef BK_LIB_QT_AVAILABLE TextureCubeMap::TextureCubeMap() : base_type() #else TextureCubeMap::TextureCubeMap(bk::qt_gl_functions* gl) : base_type(gl) #endif { /* do nothing */ } TextureCubeMap::TextureCubeMap(self_type&&) noexcept = default; /// @} /// @{ -------------------------------------------------- DTOR TextureCubeMap::~TextureCubeMap() = default; /// @} //==================================================================================================== //===== GETTER //==================================================================================================== /// @{ -------------------------------------------------- GET TEXTURE UNIT GLenum TextureCubeMap::texture_unit() const { return _pdata->texture_unit; } /// @} //==================================================================================================== //===== SETTER //==================================================================================================== /// @{ -------------------------------------------------- OPERATOR = auto TextureCubeMap::operator=(self_type&& other) noexcept -> self_type& = default; /// @} /// @{ -------------------------------------------------- SET TEXTURE UNIT void TextureCubeMap::set_texture_unit(GLenum t) { if (t == GL_TEXTURE0 || t == GL_TEXTURE1 || t == GL_TEXTURE2 || t == GL_TEXTURE3 || t == GL_TEXTURE4 || t == GL_TEXTURE5 || t == GL_TEXTURE6 || t == GL_TEXTURE7 || t == GL_TEXTURE8 || t == GL_TEXTURE9 || t == GL_TEXTURE10 || t == GL_TEXTURE11 || t == GL_TEXTURE12 || t == GL_TEXTURE13 || t == GL_TEXTURE14 || t == GL_TEXTURE15 || t == GL_TEXTURE16 || t == GL_TEXTURE17 || t == GL_TEXTURE18 || t == GL_TEXTURE19 || t == GL_TEXTURE20 || t == GL_TEXTURE21 || t == GL_TEXTURE22 || t == GL_TEXTURE23 || t == GL_TEXTURE24 || t == GL_TEXTURE25 || t == GL_TEXTURE26 || t == GL_TEXTURE27 || t == GL_TEXTURE28 || t == GL_TEXTURE29 || t == GL_TEXTURE30 || t == GL_TEXTURE31) { _pdata->texture_unit = t; } } void TextureCubeMap::set_texture_unit_number(GLuint i) { switch (i) { default: [[fallthrough]] case 0: _pdata->texture_unit = GL_TEXTURE0; break; case 1: _pdata->texture_unit = GL_TEXTURE1; break; case 2: _pdata->texture_unit = GL_TEXTURE2; break; case 3: _pdata->texture_unit = GL_TEXTURE3; break; case 4: _pdata->texture_unit = GL_TEXTURE4; break; case 5: _pdata->texture_unit = GL_TEXTURE5; break; case 6: _pdata->texture_unit = GL_TEXTURE6; break; case 7: _pdata->texture_unit = GL_TEXTURE7; break; case 8: _pdata->texture_unit = GL_TEXTURE8; break; case 9: _pdata->texture_unit = GL_TEXTURE9; break; case 10: _pdata->texture_unit = GL_TEXTURE10; break; case 11: _pdata->texture_unit = GL_TEXTURE11; break; case 12: _pdata->texture_unit = GL_TEXTURE12; break; case 13: _pdata->texture_unit = GL_TEXTURE13; break; case 14: _pdata->texture_unit = GL_TEXTURE14; break; case 15: _pdata->texture_unit = GL_TEXTURE15; break; case 16: _pdata->texture_unit = GL_TEXTURE16; break; case 17: _pdata->texture_unit = GL_TEXTURE17; break; case 18: _pdata->texture_unit = GL_TEXTURE18; break; case 19: _pdata->texture_unit = GL_TEXTURE19; break; case 20: _pdata->texture_unit = GL_TEXTURE20; break; case 21: _pdata->texture_unit = GL_TEXTURE21; break; case 22: _pdata->texture_unit = GL_TEXTURE22; break; case 23: _pdata->texture_unit = GL_TEXTURE23; break; case 24: _pdata->texture_unit = GL_TEXTURE24; break; case 25: _pdata->texture_unit = GL_TEXTURE25; break; case 26: _pdata->texture_unit = GL_TEXTURE26; break; case 27: _pdata->texture_unit = GL_TEXTURE27; break; case 28: _pdata->texture_unit = GL_TEXTURE28; break; case 29: _pdata->texture_unit = GL_TEXTURE29; break; case 30: _pdata->texture_unit = GL_TEXTURE30; break; case 31: _pdata->texture_unit = GL_TEXTURE31; break; } } /// @} //==================================================================================================== //===== FUNCTIONS //==================================================================================================== /// @{ -------------------------------------------------- CLEAR void TextureCubeMap::clear_impl() { if (_id != 0) { BK_QT_GL glDeleteTextures(1, &_id); } } /// @} /// @{ -------------------------------------------------- INIT void TextureCubeMap::bind_impl() { BK_QT_GL glActiveTexture(_pdata->texture_unit); BK_QT_GL glEnable(GL_TEXTURE_CUBE_MAP); BK_QT_GL glBindTexture(GL_TEXTURE_CUBE_MAP, _id); } void TextureCubeMap::release_impl() { BK_QT_GL glActiveTexture(_pdata->texture_unit); BK_QT_GL glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } /// @} /// @{ -------------------------------------------------- VIRTUAL #ifdef BK_LIB_PNG_AVAILABLE std::vector<GLfloat> TextureCubeMap::_make_texture(std::string_view path) const { CartesianImage<Vec3d, 2> img; // temp image for png loading img.load_png(path); const GLuint width = img.geometry().size(0); const GLuint height = img.geometry().size(1); std::vector<GLfloat> tex_vals(width * height * 3, 0.0f); #pragma omp parallel for for (unsigned int y = 0; y < height; ++y) { unsigned int off = y * width * 3; for (unsigned int x = 0; x < width; ++x) { for (unsigned int v = 0; v < 3; ++v) { tex_vals[off++] = static_cast<GLfloat>(img(x, y)[v] / 255.0); } } } return tex_vals; } void TextureCubeMap::init_from_rgb_images(std::string_view x_pos_path, std::string_view x_neg_path, std::string_view y_pos_path, std::string_view y_neg_path, std::string_view z_pos_path, std::string_view z_neg_path) { this->clear(); std::future<std::vector<GLfloat>> fut_x_pos = bk_threadpool.enqueue([&](){ return _make_texture(x_pos_path); }); std::future<std::vector<GLfloat>> fut_x_neg = bk_threadpool.enqueue([&](){ return _make_texture(x_neg_path); }); std::future<std::vector<GLfloat>> fut_y_pos = bk_threadpool.enqueue([&](){ return _make_texture(y_pos_path); }); std::future<std::vector<GLfloat>> fut_y_neg = bk_threadpool.enqueue([&](){ return _make_texture(y_neg_path); }); std::future<std::vector<GLfloat>> fut_z_pos = bk_threadpool.enqueue([&](){ return _make_texture(z_pos_path); }); std::future<std::vector<GLfloat>> fut_z_neg = bk_threadpool.enqueue([&](){ return _make_texture(z_neg_path); }); CartesianImage<Vec3d, 2> img; // temp image for png loading img.load_png(x_pos_path); const GLuint width = img.geometry().size(0); const GLuint height = img.geometry().size(1); BK_QT_GL glGenTextures(1, &_id); bind(); std::vector<GLfloat> tex_vals_x_pos = fut_x_pos.get(); std::vector<GLfloat> tex_vals_x_neg = fut_x_neg.get(); std::vector<GLfloat> tex_vals_y_pos = fut_y_pos.get(); std::vector<GLfloat> tex_vals_y_neg = fut_y_neg.get(); std::vector<GLfloat> tex_vals_z_pos = fut_z_pos.get(); std::vector<GLfloat> tex_vals_z_neg = fut_z_neg.get(); BK_QT_GL glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, static_cast<const GLvoid*>(tex_vals_x_pos.data())); BK_QT_GL glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, static_cast<const GLvoid*>(tex_vals_x_neg.data())); BK_QT_GL glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, static_cast<const GLvoid*>(tex_vals_y_pos.data())); BK_QT_GL glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, static_cast<const GLvoid*>(tex_vals_y_neg.data())); BK_QT_GL glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, static_cast<const GLvoid*>(tex_vals_z_pos.data())); BK_QT_GL glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, static_cast<const GLvoid*>(tex_vals_z_neg.data())); /* * cube map texture parameters */ BK_QT_GL glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); BK_QT_GL glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); BK_QT_GL glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); BK_QT_GL glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); BK_QT_GL glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); release(); tex_vals_x_pos.clear(); tex_vals_x_pos.shrink_to_fit(); tex_vals_x_neg.clear(); tex_vals_x_neg.shrink_to_fit(); tex_vals_y_pos.clear(); tex_vals_y_pos.shrink_to_fit(); tex_vals_y_neg.clear(); tex_vals_y_neg.shrink_to_fit(); tex_vals_z_pos.clear(); tex_vals_z_pos.shrink_to_fit(); tex_vals_z_neg.clear(); tex_vals_z_neg.shrink_to_fit(); } #endif /// @} } // namespace bk
42.135889
669
0.563797
BenKoehler
3f0614fd6f1a11896a3da3d7a2b660f8d238fdaf
1,009
cpp
C++
xfa/fxfa/parser/cxfa_binditemsdata.cpp
jamespayor/pdfium
07b4727a34d2f4aff851f0dc420faf617caca220
[ "BSD-3-Clause" ]
1
2019-01-12T07:00:46.000Z
2019-01-12T07:00:46.000Z
xfa/fxfa/parser/cxfa_binditemsdata.cpp
jamespayor/pdfium
07b4727a34d2f4aff851f0dc420faf617caca220
[ "BSD-3-Clause" ]
null
null
null
xfa/fxfa/parser/cxfa_binditemsdata.cpp
jamespayor/pdfium
07b4727a34d2f4aff851f0dc420faf617caca220
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/parser/cxfa_binditemsdata.h" #include "xfa/fxfa/parser/cxfa_node.h" CXFA_BindItemsData::CXFA_BindItemsData(CXFA_Node* pNode) : CXFA_DataData(pNode) {} void CXFA_BindItemsData::GetLabelRef(WideString& wsLabelRef) { wsLabelRef = m_pNode->JSNode()->GetCData(XFA_Attribute::LabelRef); } void CXFA_BindItemsData::GetValueRef(WideString& wsValueRef) { wsValueRef = m_pNode->JSNode()->GetCData(XFA_Attribute::ValueRef); } void CXFA_BindItemsData::GetRef(WideString& wsRef) { wsRef = m_pNode->JSNode()->GetCData(XFA_Attribute::Ref); } bool CXFA_BindItemsData::SetConnection(const WideString& wsConnection) { return m_pNode->JSNode()->SetCData(XFA_Attribute::Connection, wsConnection, false, false); }
33.633333
80
0.74331
jamespayor
3f0a346f1e8c71b57165a44ba8b6bce9c754fabb
2,768
cc
C++
gcc-gcc-7_3_0-release/libvtv/testsuite/other-tests/so.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libvtv/testsuite/other-tests/so.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libvtv/testsuite/other-tests/so.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
#include <dlfcn.h> #include <assert.h> #include <unistd.h> #include <vtv_fail.h> extern "C" int printf(const char *, ...); extern "C" int sprintf(char *, const char*, ...); static int counter = 0; extern int failures; template <int i> struct base { virtual char * whoami() { static char sl[100]; sprintf(sl, "I am base %d", i); return sl; } virtual void inc() { counter += i; } }; template <int i> struct derived: base<i> { virtual char * whoami() { static char sl[100]; sprintf(sl, "I am derived %d", i); return sl; } virtual void inc() { counter += (10*i); } }; // We don't use this class. It is just here so that the // compiler does not devirtualize calls to derived::inc() template <int i> struct derived2: derived<i> { virtual void inc() { counter += (20*i); } }; static base<TPID> * bp = new base<TPID>(); static derived<TPID> * dp = new derived<TPID>(); static base<TPID> * dbp = new derived<TPID>(); // Given 2 pointers to C++ objects (non PODs), exchange the pointers to vtable static void exchange_vtptr(void * object1_ptr, void * object2_ptr) { void ** object1_vtptr_ptr = (void **)object1_ptr; void ** object2_vtptr_ptr = (void **)object2_ptr; void * object1_vtptr = *object1_vtptr_ptr; void * object2_vtptr = *object2_vtptr_ptr; *object1_vtptr_ptr = object2_vtptr; *object2_vtptr_ptr = object1_vtptr; } #define BUILD_NAME(NAME,ID) NAME##ID #define EXPAND(NAME,X) BUILD_NAME(NAME,X) extern "C" void EXPAND(so_entry_,TPID)(void) { int prev_counter; int prev_failures; counter = 0; bp->inc(); dp->inc(); dbp->inc(); assert(counter == (TPID + 10*TPID + 10*TPID)); prev_counter = counter; exchange_vtptr(bp, dp); bp->inc(); // This one should succeed but it is calling the wrong member if (counter != (prev_counter + 10*TPID)) { printf("TPID=%d whoami=%s wrong counter value prev_counter=%d counter=%d\n", TPID, bp->whoami(), prev_counter, counter); sleep(2); } assert(counter == (prev_counter + 10*TPID)); // printf("Pass first attack!\n"); // This one should fail verification!. So it should jump to __vtv_verify_fail above. prev_failures = failures; dp->inc(); // this code may be executed by multiple threads at the same time. So, just verify the number of failures has // increased as opposed to check for increase by 1. assert(failures > prev_failures); assert(counter == (prev_counter + 10*TPID + TPID)); // printf("TPDI=%d counter %d\n", TPID, counter); // printf("Pass second attack!\n"); // restore the vtable pointers to the original state. // This is very important. For some reason the dlclose is not "really" closing the library so when we reopen it we are // getting the old memory state. exchange_vtptr(bp, dp); }
29.446809
124
0.670882
best08618
3f0d1a425429c90e344871374fe4209ff80c2548
4,756
hpp
C++
game/game_objects/editor/object_selector.hpp
antonkanin/potatoengine
9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd
[ "MIT" ]
null
null
null
game/game_objects/editor/object_selector.hpp
antonkanin/potatoengine
9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd
[ "MIT" ]
null
null
null
game/game_objects/editor/object_selector.hpp
antonkanin/potatoengine
9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd
[ "MIT" ]
1
2020-01-29T10:18:23.000Z
2020-01-29T10:18:23.000Z
#include <engine.hpp> #include <game_object.hpp> #include <input_manager.hpp> #include <movable_object.hpp> #include "../space_ship.hpp" #include <SDL2/SDL_mouse.h> // TODO hide this in the engine #include <glm/gtc/matrix_transform.hpp> #include <ptm/glm_to_ptm.hpp> #include <ptm/math.hpp> #include <ptm/vec4.hpp> #include "../game/enemy.hpp" #include "../utils.hpp" class object_selector final : public pt::game_object { public: using pt::game_object::game_object; void update() override { handle_mouse_input(); draw_debug_line(); } void draw_debug_line() { get_engine().draw_line(line_from_, line_to_, { 1.0f, 0.0f, 0.0f }); // pt::log_line() << line_from_ << line_to_ << std::endl; } void handle_mouse_input() { if (get_engine().get_input_manager().get_key_down( pt::key_code::mouse_left)) { const auto [mouse_from, mouse_to] = get_mouse_ndc(); auto [mouse_world_from, mouse_world_to] = get_world_ray(get_engine(), mouse_from, mouse_to); line_from_ = { mouse_world_from.x, mouse_world_from.y, mouse_world_from.z }; line_to_ = { mouse_world_to.x, mouse_world_to.y, mouse_world_to.z }; line_to_ = line_from_ + 10 * ptm::normalize(line_to_ - line_from_); auto found_obj = find_collision(get_engine(), mouse_world_from, mouse_world_to); if (found_obj != nullptr) { selected_object_ = found_obj; } } } std::tuple<glm::vec4, glm::vec4> get_mouse_ndc() { // get NDC from and to const auto mouse_ndc = get_mouse_normalized(); const auto from_ndc = glm::vec4{ mouse_ndc.x, mouse_ndc.y, -1.f, 1.f }; const auto to_ndc = glm::vec4{ mouse_ndc.x, mouse_ndc.y, 1.f, 1.f }; return { from_ndc, to_ndc }; } static ptm::vec2 normalize_screen_coords(int x, int y, int width, int height) { auto x_f = static_cast<float>(x); auto y_f = static_cast<float>(y); auto width_f = static_cast<float>(width); auto height_f = static_cast<float>(height); auto result_x = 2.f * (x_f - (width_f / 2.f)) / width_f; auto result_y = 2.f * (y_f - (height_f / 2.f)) / height_f; return { result_x, -result_y }; } ptm::vec2 get_mouse_normalized() { auto window_size = get_engine().get_window_size(); int x, y; SDL_GetMouseState(&x, &y); auto mouse_pos = normalize_screen_coords(x, y, window_size.x, window_size.y); return { mouse_pos.x, mouse_pos.y }; } void on_gui() override { if (selected_object_ == nullptr) { return; } ImGui::SetNextWindowPos(ImVec2(140, 0), ImGuiCond_Appearing); ImGui::SetNextWindowSize(ImVec2(260, 150), ImGuiCond_Appearing); if (!ImGui::Begin("Object properties", nullptr, 0 /*ImGuiWindowFlags_NoTitleBar*/)) { ImGui::End(); return; } auto pos = selected_object_->get_position(); auto scale = selected_object_->get_scale(); ImGui::LabelText("Name", selected_object_->get_name().c_str()); ImGui::Text("Position"); ImGui::InputFloat("x##pos", &pos.x, 0.1f, 1.0f); ImGui::InputFloat("y##pos", &pos.y, 0.1f, 1.0f); ImGui::InputFloat("z##pos", &pos.z, 0.1f, 1.0f); ImGui::Text("Scale"); ImGui::InputFloat("x##scale", &scale.x, 0.1f, 1.0f); ImGui::InputFloat("y##scale", &scale.y, 0.1f, 1.0f); ImGui::InputFloat("z##scale", &scale.z, 0.1f, 1.0f); // ImGui::SliderFloat("x", &pos.x, -10.0f, 10.0f, "%.4f", 2.0f); // ImGui::SliderFloat("y", &pos.y, -10.0f, 10.0f, "%.4f", 2.0f); // ImGui::SliderFloat("z", &pos.z, -10.0f, 10.0f, "%.4f", 2.0f); // // ImGui::SliderFloat("scale x", &scale.x, -10.0f, 10.0f, // "%.4f", 1.0f); ImGui::SliderFloat("scale y", &scale.y, // -10.0f, 10.0f, "%.4f", 1.0f); ImGui::SliderFloat("scale z", // &scale.z, -10.0f, 10.0f, "%.4f", 1.0f); // ImGui::Checkbox("Auto-rotate", &selected_object_->is_auto_rotate_); selected_object_->set_position(pos); selected_object_->set_scale(scale); ImGui::End(); } private: // btVector3 bt_pos{ 0.f, 0.f, 0.f }; // btVector3 bt_dir{ 0.f, 0.f, 0.f }; ptm::vec3 line_from_; ptm::vec3 line_to_; game_object* selected_object_ = nullptr; };
30.101266
80
0.555929
antonkanin
3f10a9f03e514238269127ed9e390d21a12099a4
2,614
hpp
C++
src/Modules/EffectsModule/Entity/FreeFrameEffect.hpp
danielfilipealmeida/Orange
e0118a7d1391e74c15c707e64a2e0458d51d318f
[ "MIT" ]
null
null
null
src/Modules/EffectsModule/Entity/FreeFrameEffect.hpp
danielfilipealmeida/Orange
e0118a7d1391e74c15c707e64a2e0458d51d318f
[ "MIT" ]
null
null
null
src/Modules/EffectsModule/Entity/FreeFrameEffect.hpp
danielfilipealmeida/Orange
e0118a7d1391e74c15c707e64a2e0458d51d318f
[ "MIT" ]
null
null
null
// // FreeFrameEffect.hpp // orange // // Created by Daniel Almeida on 13/01/2019. // // IMPORTANT: // FreeFrame filters are currently considered incompatible with GLSL filters. // This is because FreeFrame filters require ArbTex to be disabled while // GLSL requires the oposite. // Also, the used ofxFreeFrame is tweaked to compile on OSX 10.14 and isn't // available, making this code not portable. // Because of this, FreeFrame filters have been removed from the Application. // The code maintains for reference #ifndef FreeFrameEffect_hpp #define FreeFrameEffect_hpp #include <stdio.h> #include "EffectBase.hpp" #include "ofxFFPlugin.h" #include "ofxFFHost.h" namespace Orange { namespace Effects { /*! Class that implement the listener of each parameter */ class FreeFrameEffectListener { unsigned int parameterNumber; ofxFFGLInstance *instance; public: FreeFrameEffectListener(ofxFFGLInstance *_instance, unsigned int _parameterNumber) { instance = _instance; parameterNumber = _parameterNumber; }; void update(float &value) { instance->setParameter(parameterNumber, value); }; }; class FreeFrameEffect : public EffectBase { ofxFFGLInstance *instance; ofxFFPlugin *plugin; vector<FreeFrameEffectListener *>listeners; /*! Cleans all the currently set listeners */ void clearListeners(); /*! Update all parameters and their listeners */ void updateParameters(); public: ofParameter<string> name; vector<ofParameter<float>> parameters; /*! Configures this FreeFrameEffect \param ofxFFPlugin *_plugin \param ofxFFGLInstance *_instance */ void setPluginAndInstance(ofxFFPlugin *_plugin, ofxFFGLInstance *_instance); /*! Process \param ofFbo& fbo */ void process(ofTexture &tex); void process(ofFbo &fbo) {}; /*! Apply a lambda to each parameter \param */ void forEachParameter(std::function<void (ofParameter<float>)> lambda); }; } } #endif /* FreeFrameEffect_hpp */
27.808511
96
0.555853
danielfilipealmeida
3f162437b1807c63d856305b661308be325dc922
20,620
cc
C++
libport-core/src/main/native/server/manager.cc
jerryz920/portlib
72c6534e8f064b5507a5c79766a13114478d3ffa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
libport-core/src/main/native/server/manager.cc
jerryz920/portlib
72c6534e8f064b5507a5c79766a13114478d3ffa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
libport-core/src/main/native/server/manager.cc
jerryz920/portlib
72c6534e8f064b5507a5c79766a13114478d3ffa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include <unordered_map> #include "proto/config.h" #include "proto/statement.pb.h" #include "proto/utils.h" #include "proto/traits.h" #include "manager.h" #include "pplx/threadpool.h" #include "pplx/pplxtasks.h" #include "metadata.h" #include "utils.h" #include <jutils/config/simple.h> #include "config.h" namespace latte { using proto::Response; using proto::Command; class LatteAttestationManager: public LatteDispatcher { public: typedef std::unordered_multimap<uint64_t, std::shared_ptr<proto::Principal>> PrincipalMap; LatteAttestationManager(const std::string &metadata_server): LatteAttestationManager(metadata_server,crossplat::threadpool::shared_instance() ) { } LatteAttestationManager(const std::string &metadata_server, crossplat::threadpool &pool): executor_(pool), metadata_service_(utils::make_unique<MetadataServiceClient>( metadata_server, latte::config::myid())) { init(); } LatteAttestationManager(MetadataServiceClient* service): LatteAttestationManager(service,crossplat::threadpool::shared_instance()) { } LatteAttestationManager(MetadataServiceClient* service, crossplat::threadpool &pool): executor_(pool), metadata_service_(service) { init(); } bool dispatch(std::shared_ptr<proto::Command> cmd, Writer w) override { auto handler = find_handler(cmd->type()); std::shared_ptr<Response> result; if (handler) { try { //// TODO: validate the speaker field if needed result = handler(cmd); } catch (const std::runtime_error &e) { std::string errmsg = "runtime error " + std::string(e.what()); log_err(errmsg.c_str()); result = proto::make_shared_status_response(false, errmsg); } catch (const web::json::json_exception &e) { std::string errmsg = "json error " + std::string(e.what()); log_err(errmsg.c_str()); result = proto::make_shared_status_response(false, errmsg); } catch(const web::http::http_exception &e) { std::string errmsg = "http error " + std::string(e.what()); log_err(errmsg.c_str()); result = proto::make_shared_status_response(false, errmsg); } } else { std::string typedesc = proto::Command::Type_Name(cmd->type()); result = proto::make_shared_status_response(false, "not handler found for type " + typedesc); } w(result); return true; } //// In fact we should separate these things out as a standalone Manager class, // while the dispatcher accepts registeration of handlers. So the separation // is cleaner. But I have no time for that kind of shit. private: typedef std::shared_ptr<Response> (LatteAttestationManager::*RawHandler) (std::shared_ptr<Command>); void register_handler(proto::Command::Type type, RawHandler h) { dispatch_table_[static_cast<uint32_t>(type)] = std::bind(h, this, std::placeholders::_1); } Handler find_handler(proto::Command::Type type) const { auto res = dispatch_table_.find(static_cast<uint32_t>(type)); if (res == dispatch_table_.end()) { return nullptr; } return res->second; } void init(uint64_t init_gn = 0) { gn_ = init_gn; register_handler(proto::Command::CREATE_PRINCIPAL, &LatteAttestationManager::create_principal); register_handler(proto::Command::DELETE_PRINCIPAL, &LatteAttestationManager::delete_principal); register_handler(proto::Command::GET_PRINCIPAL, &LatteAttestationManager::get_principal); register_handler(proto::Command::ENDORSE_PRINCIPAL, &LatteAttestationManager::endorse_principal); register_handler(proto::Command::REVOKE_PRINCIPAL_ENDORSEMENT, &LatteAttestationManager::revoke_principal); register_handler(proto::Command::ENDORSE, &LatteAttestationManager::endorse); register_handler(proto::Command::REVOKE, &LatteAttestationManager::revoke); register_handler(proto::Command::GET_LOCAL_PRINCIPAL, &LatteAttestationManager::get_local_principal); register_handler(proto::Command::GET_METADATA_CONFIG, &LatteAttestationManager::get_metadata_config); register_handler(proto::Command::POST_ACL, &LatteAttestationManager::post_acl); register_handler(proto::Command::ENDORSE_MEMBERSHIP, &LatteAttestationManager::endorse_membership); register_handler(proto::Command::ENDORSE_ATTESTER_IMAGE, &LatteAttestationManager::endorse_attester); register_handler(proto::Command::ENDORSE_BUILDER_IMAGE, &LatteAttestationManager::endorse_builder); register_handler(proto::Command::ENDORSE_SOURCE_IMAGE, &LatteAttestationManager::endorse_source); register_handler(proto::Command::CHECK_PROPERTY, &LatteAttestationManager::check_property); register_handler(proto::Command::CHECK_ATTESTATION, &LatteAttestationManager::check_attestation); register_handler(proto::Command::CHECK_ACCESS, &LatteAttestationManager::check_access); register_handler(proto::Command::CHECK_WORKER_ACCESS, &LatteAttestationManager::check_worker_access); register_handler(proto::Command::CHECK_IMAGE_PROPERTY, &LatteAttestationManager::check_image_property); register_handler(proto::Command::FREE_CALL, &LatteAttestationManager::free_call); register_handler(proto::Command::GUARD_CALL, &LatteAttestationManager::guard_call); register_handler(proto::Command::LINK_IMAGE, &LatteAttestationManager::link_image); } static inline std::string principal_name(const proto::Principal &p) { std::stringstream ss; ss << p.id() << "_" << p.gn(); return ss.str(); } std::shared_ptr<Response> free_call(std::shared_ptr<Command> cmd) { auto freecall = proto::CommandWrapper::extract_free_call(*cmd); auto proto_values = freecall->othervalues(); std::vector<std::string> other_values(proto_values.begin(), proto_values.end()); auto res = metadata_service_->free_call(cmd->auth(), freecall->cmd(), other_values); return proto::make_shared_status_response(res, ""); } std::shared_ptr<Response> guard_call(std::shared_ptr<Command> cmd) { auto guardcall = proto::CommandWrapper::extract_guard_call(*cmd); auto proto_values = guardcall->othervalues(); std::vector<std::string> other_values(proto_values.begin(), proto_values.end()); auto res = metadata_service_->guard_call(cmd->auth(), guardcall->cmd(), other_values); return proto::make_shared_status_response(res, ""); } std::shared_ptr<Response> link_image(std::shared_ptr<Command> cmd) { auto linkimage = proto::CommandWrapper::extract_link_image(*cmd); auto host = linkimage->host(); if (host.size() == 0) { host = cmd->auth(); } auto &image = linkimage->image(); auto res = metadata_service_->link_image(cmd->auth(), host, image); return proto::make_shared_status_response(res, ""); } std::shared_ptr<Response> create_principal(std::shared_ptr<Command> cmd) { auto p = proto::CommandWrapper::extract_principal(*cmd); if (!p) { return proto::make_shared_status_response(false, "principal not found or mal-formed"); } p->set_gn(gn()); auto image_store = p->code().image_store(); if (image_store.size() == 0) { image_store = cmd->auth(); } //auto res = metadata_service_->post_new_principal(cmd->auth(), principal_name(*p), // ip, p->auth().port_lo(), p->auth().port_hi(), // p->code().image(), p->code().config().at(LEGACY_CONFIG_KEY)); auto &confmap = p->code().config(); /// copy the stuff to make the interface clean from any protobuf dependency std::unordered_map<std::string, std::string> configs(confmap.begin(), confmap.end()); metadata_service_ -> create_instance(cmd->auth(), principal_name(*p), p->code().image(), p->auth().ip(), p->auth().port_lo(), p->auth().port_hi(), image_store, configs); p->set_speaker(cmd->pid()); add_principal(p->id(), p); return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> delete_principal(std::shared_ptr<Command> cmd) { auto p = proto::CommandWrapper::extract_principal(*cmd); if (!p) { return proto::make_shared_status_response(false, "principal not found or mal-formed"); } log("entering delete principal"); uint64_t maxgn = 0; std::shared_ptr<proto::Principal> latest = nullptr; plock_.lock(); auto matched = principals_.equal_range(p->id()); for (auto i = matched.first; i != matched.second; ++i) { log("find gn %d", i->second->gn()); if (maxgn <= i->second->gn()) { maxgn = i->second->gn(); latest = i->second; } } log("looking for latest principal, found: %d", maxgn); if (latest) { auto speaker = latest->speaker(); if ((speaker != cmd->pid() && cmd->uid() != 0)) { plock_.unlock(); return proto::make_shared_status_response(false, "privilege not matching"); } } principals_.erase(matched.first, matched.second); //// authenticate if deletion is allowed! /// deleting latest principal log("after erase the range"); if (latest) { //auto speaker = latest->speaker(); auto name = principal_name(*latest); //auto ip = latest->auth().ip(); //auto plo = latest->auth().port_lo(); //auto phi = latest->auth().port_hi(); //auto image = latest->code().image(); //auto config = latest->code().config().at(LEGACY_CONFIG_KEY); //log("deleting principal: id = %u, maxgn = %u, latest = %p, speaker = %u, pid = %u, uid = %u", // p->id(), maxgn, latest.get(), speaker, cmd->pid(), cmd->uid()); log("deleting principal %s", name.c_str()); plock_.unlock(); metadata_service_->delete_instance(cmd->auth(), name); //metadata_service_->remove_principal(cmd->auth(),name, ip, plo, phi, image, config); return proto::make_shared_status_response(true, ""); } else { plock_.unlock(); log("deleting %u, %u, latest principal not found", p->id(), p->gn()); return proto::make_shared_status_response(false, "latest principal not found"); } } std::shared_ptr<Response> get_principal(std::shared_ptr<Command> ) { /// not implemented yet return proto::not_implemented(); } std::shared_ptr<Response> endorse_principal(std::shared_ptr<Command> ) { /// not implemented yet return proto::not_implemented(); } std::shared_ptr<Response> revoke_principal(std::shared_ptr<Command> ) { /// not implemented yet return proto::not_implemented(); } std::shared_ptr<Response> endorse(std::shared_ptr<Command> cmd) { auto endorse = proto::CommandWrapper::extract_endorse(*cmd); if (endorse->endorsements_size() == 0) { return proto::make_shared_status_response(false, "must provide at least one property"); } auto &image = endorse->id(); auto &property = endorse->endorsements(0).property(); auto &value = endorse->endorsements(0).value(); //auto &config = endorse->config().at(LEGACY_CONFIG_KEY); metadata_service_->endorse(cmd->auth(), image, property, value); return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> revoke(std::shared_ptr<Command> ) { return proto::not_implemented(); } std::shared_ptr<Response> get_local_principal(std::shared_ptr<Command> cmd) { auto p = proto::CommandWrapper::extract_principal(*cmd); if (!p) { return proto::make_shared_status_response(false, "principal not found or mal-formed"); } uint64_t maxgn = 0; std::shared_ptr<proto::Principal> latest = nullptr; std::lock_guard<std::mutex> guard(plock_); auto matched = principals_.equal_range(p->id()); for (auto i = matched.first; i != matched.second; ++i) { if (maxgn <= i->second->gn()) { maxgn = i->second->gn(); latest = i->second; } } if (latest) { return proto::make_shared_principal_response(*latest); } else { return proto::make_shared_status_response(false, "not found"); } } std::shared_ptr<Response> get_metadata_config(std::shared_ptr<Command>) { proto::MetadataConfig config; config.set_ip(config::metadata_service_ip()); config.set_port(config::metadata_service_port()); return proto::make_shared_metadata_config_response(config); } ////////////////////Legacy APIs std::shared_ptr<Response> post_acl(std::shared_ptr<Command> cmd) { auto acl = proto::CommandWrapper::extract_post_acl(*cmd); /// we only use the first name if (acl->policies_size() == 0) { return proto::make_shared_status_response(false, "must provide one policy"); } metadata_service_->post_object_acl(cmd->auth(), acl->name(), acl->policies(0)); return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> endorse_membership(std::shared_ptr<Command> cmd) { auto endorse_p = proto::CommandWrapper::extract_endorse_principal(*cmd); if (endorse_p->endorsements_size() == 0) { return proto::make_shared_status_response(false, "must provide one endorsement"); } auto gn = endorse_p->principal().gn(); auto &target_ip = endorse_p->principal().auth().ip(); auto target_port = endorse_p->principal().auth().port_lo(); auto &target_config = endorse_p->principal().code().config().at(LEGACY_CONFIG_KEY); auto &statement = endorse_p->endorsements(0); metadata_service_->endorse_membership(cmd->auth(), target_ip, target_port, gn, statement.property(), target_config); return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> endorse_attester(std::shared_ptr<Command> cmd) { auto endorse = proto::CommandWrapper::extract_endorse(*cmd); auto id = endorse->id(); auto &config = endorse->config().at(LEGACY_CONFIG_KEY); if (endorse->type() == proto::Endorse::SOURCE) { /// metadata_service_->endorse_source(id, statement); metadata_service_->endorse_attester_on_source(cmd->auth(),id, config); } else { //// Need add a type metadata_service_->endorse_attester(cmd->auth(),id, config); } return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> endorse_builder(std::shared_ptr<Command> cmd) { auto endorse = proto::CommandWrapper::extract_endorse(*cmd); auto id = endorse->id(); if (endorse->endorsements_size() == 0) { return proto::make_shared_status_response(false, "must provide one endorsement"); } auto &config = endorse->config().at(LEGACY_CONFIG_KEY); if (endorse->type() == proto::Endorse::SOURCE) { /// metadata_service_->endorse_source(id, statement); metadata_service_->endorse_builder_on_source(cmd->auth(),id, config); } else { //// Need add a type metadata_service_->endorse_builder(cmd->auth(),id, config); } return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> endorse_source(std::shared_ptr<Command> cmd) { auto endorse = proto::CommandWrapper::extract_endorse(*cmd); auto id = endorse->id(); if (endorse->endorsements_size() == 0) { return proto::make_shared_status_response(false, "must provide one endorsement"); } auto &statement = endorse->endorsements(0); auto &config = endorse->config().at(LEGACY_CONFIG_KEY); if (endorse->type() == proto::Endorse::SOURCE) { /// metadata_service_->endorse_source(id, statement); return proto::make_shared_status_response(false, "source endorse this is image only"); } else { //// Need add a type metadata_service_->endorse_image(cmd->auth(), id, statement.property(), config); } return proto::make_shared_status_response(true, ""); } std::shared_ptr<Response> check_property(std::shared_ptr<Command> cmd) { auto check = proto::CommandWrapper::extract_check_property(*cmd); auto &ip = check->principal().auth().ip(); auto port = check->principal().auth().port_lo(); if (check->properties_size() == 0) { return proto::make_shared_status_response(false, "must provide one property"); } auto &prop = check->properties(0); return proto::make_shared_status_response( metadata_service_->has_property(cmd->auth(), ip, port, prop, ""), ""); } std::shared_ptr<Response> check_attestation(std::shared_ptr<Command> cmd) { auto attest = proto::CommandWrapper::extract_check_attestation(*cmd); auto &ip = attest->principal().auth().ip(); auto port = attest->principal().auth().port_lo(); proto::Attestation a; a.set_content(metadata_service_->attest(cmd->auth(), ip, port, "")); return proto::make_shared_attestation_response(a); } std::shared_ptr<Response> check_access(std::shared_ptr<Command> cmd) { auto check = proto::CommandWrapper::extract_check_access(*cmd); auto &ip = check->principal().auth().ip(); auto port = check->principal().auth().port_lo(); if (check->objects_size() == 0) { return proto::make_shared_status_response(false, "must provide one object"); } auto &object = check->objects(0); return proto::make_shared_status_response( metadata_service_->can_access(cmd->auth(),ip, port, object, ""), ""); } std::shared_ptr<Response> check_worker_access(std::shared_ptr<Command> cmd) { auto check = proto::CommandWrapper::extract_check_access(*cmd); auto &ip = check->principal().auth().ip(); auto port = check->principal().auth().port_lo(); if (check->objects_size() == 0) { return proto::make_shared_status_response(false, "must provide one object"); } auto &object = check->objects(0); return proto::make_shared_status_response( metadata_service_->can_worker_access(cmd->auth(),ip, port, object, ""), ""); } std::shared_ptr<Response> check_image_property(std::shared_ptr<Command> cmd) { auto check = proto::CommandWrapper::extract_check_image(*cmd); auto &image = check->image(); auto &confmap = check->config(); if (check->property_size() == 0) { return proto::make_shared_status_response(false, "must provide one property"); } auto &config = confmap.at(LEGACY_CONFIG_KEY); auto &property = check->property(0); return proto::make_shared_status_response( metadata_service_->image_has_property(cmd->auth(), image, config, property), ""); } void add_principal(uint64_t id, std::shared_ptr<proto::Principal> p) { std::lock_guard<std::mutex> guard(plock_); principals_.insert(std::make_pair(id, std::move(p))); } uint64_t gn() { return gn_++; } std::unordered_map<uint32_t, Handler> dispatch_table_; crossplat::threadpool & executor_; std::unique_ptr<MetadataServiceClient> metadata_service_; std::mutex plock_; PrincipalMap principals_; uint64_t gn_; /// maybe we could use image but not now I think. }; static std::shared_ptr<LatteAttestationManager> instance; void init_manager(const std::string &metadata_url) { instance = std::make_shared<LatteAttestationManager>(metadata_url); } void init_manager(const std::string &metadata_url, crossplat::threadpool &pool) { instance = std::make_shared<LatteAttestationManager>(metadata_url, pool); } void init_manager(MetadataServiceClient *client) { instance = std::make_shared<LatteAttestationManager>(client); } std::shared_ptr<LatteDispatcher> get_manager() { if (instance) { return instance; } /// Must init manager first to call it throw std::runtime_error("must initialize the latte manager first"); } }
40.273438
106
0.651164
jerryz920
3f16a85da2f2141d66168faf3a23dbc0a795b747
12,253
cpp
C++
src/seeds.gratitude.cpp
shakhruz/seeds-smart-contracts
14423aa5901379f7a273536db4a93bf1da996f21
[ "MIT" ]
13
2020-04-05T15:26:58.000Z
2022-03-24T07:29:45.000Z
src/seeds.gratitude.cpp
shakhruz/seeds-smart-contracts
14423aa5901379f7a273536db4a93bf1da996f21
[ "MIT" ]
318
2020-03-09T14:56:45.000Z
2022-03-29T18:26:24.000Z
src/seeds.gratitude.cpp
chuck-h/seeds-smart-contracts
98f8279c52c607e0e3f697f125fcf43980402f27
[ "MIT" ]
3
2021-04-03T04:44:55.000Z
2021-12-15T16:22:03.000Z
#include <seeds.gratitude.hpp> ACTION gratitude::reset () { require_auth(get_self()); auto bitr = balances.begin(); while (bitr != balances.end()) { bitr = balances.erase(bitr); } auto actr = acks.begin(); while (actr != acks.end()) { actr = acks.erase(actr); } auto sitr = sizes.begin(); while (sitr != sizes.end()) { sitr = sizes.erase(sitr); } auto stitr = stats.begin(); while (stitr != stats.end()) { stitr = stats.erase(stitr); } auto stitr2 = stats2.begin(); while (stitr2 != stats2.end()) { stitr2 = stats2.erase(stitr2); } // setup first round stats2.emplace(_self, [&](auto& item) { item.round_id = 1; item.num_transfers = 0; item.num_acks = 0; item.volume = asset(0, gratitude_symbol); item.round_pot = asset(0, seeds_symbol); }); } ACTION gratitude::migratestats() { require_auth(get_self()); auto sitr = stats.begin(); while(sitr != stats.end()) { stats2.emplace(get_self(), [&](auto& item) { item.round_id = sitr->round_id; item.num_transfers = sitr->num_transfers; item.volume = sitr->volume; // new values item.num_acks = 0; item.round_pot = asset(0, seeds_symbol); }); // Remove old one sitr = stats.erase(sitr); } } ACTION gratitude::give (name from, name to, asset quantity, string memo) { require_auth(from); check(from != to, "gratitude: cannot give to self"); check(is_account(to), "gratitude: to account does not exist"); check_user(to); check_asset(quantity); check(quantity.amount > 0, "gratitude: must give positive quantity"); // Should create balances if not there yet init_balances(to); init_balances(from); sub_gratitude(from, quantity); add_gratitude(to, quantity); update_stats(from, to, quantity); } ACTION gratitude::acknowledge (name from, name to, string memo) { require_auth(from); check(from != to, "gratitude: cannot give to self"); check(is_account(to), "gratitude: to account does not exist"); check_user(to); // Should create balances if not there yet init_balances(to); init_balances(from); auto actr = acks.find(from.value); if (actr == acks.end()) { acks.emplace(_self, [&](auto& item) { item.donor = from; item.receivers = vector{to}; }); } else { acks.modify(actr, get_self(), [&](auto &item) { item.receivers.push_back(to); }); } // Updates ack stats auto stitr = stats2.rbegin(); auto round_id = stitr->round_id; // Have to use find to get a modifiable operator auto stitr2 = stats2.find(round_id); auto oldacks = stitr2->num_acks; stats2.modify(stitr2, _self, [&](auto& item) { item.num_acks = oldacks + 1; }); } ACTION gratitude::testacks() { require_auth(get_self()); auto actr = acks.begin(); while (actr != acks.end()) { _calc_acks(actr->donor); actr = acks.erase(actr); } } ACTION gratitude::calcacks(uint64_t start) { require_auth(get_self()); auto actr = start == 0 ? acks.begin() : acks.find(start); if (actr != acks.end()) { _calc_acks(actr->donor); actr = acks.erase(actr); } // If there is still more, do recursion call if (actr != acks.end()) { action next_execution( permission_level{get_self(), "active"_n}, get_self(), "calcacks"_n, std::make_tuple(actr->donor.value) ); transaction tx; tx.actions.emplace_back(next_execution); tx.delay_sec = 1; tx.send(actr->donor.value, _self); } else { // Otherwise, starts recursive payout auto contract_balance = eosio::token::get_balance(contracts::token, get_self(), seeds_symbol.code()); float potkeep = config_get(gratz_potkp) / (float)100; uint64_t usable_amount = contract_balance.amount - (contract_balance.amount * potkeep); action( permission_level{get_self(), "active"_n}, get_self(), "payround"_n, std::make_tuple((uint64_t)0, usable_amount) ).send(); } } // Recursively pay accounts ACTION gratitude::payround(uint64_t start, uint64_t usable_bal) { require_auth(get_self()); auto bitr = start == 0 ? balances.begin() : balances.find(start); uint64_t current = 0; auto chunksize = config_get("batchsize"_n); while (current < chunksize) { if (bitr != balances.end()) { uint64_t volume = get_current_volume(); uint64_t my_received = bitr->received.amount; // reset gratitude for account reset_balances(bitr->account); float split_factor = my_received / (float)volume; uint64_t payout = usable_bal * split_factor; if (payout > 0) _transfer(bitr->account, asset(payout, seeds_symbol), "gratitude bonus"); bitr++; current++; } else break; } // if there's more if (bitr != balances.end()) { action next_execution( permission_level{get_self(), "active"_n}, get_self(), "payround"_n, std::make_tuple(bitr->account.value, usable_bal) ); transaction tx; tx.actions.emplace_back(next_execution); tx.delay_sec = 1; tx.send(bitr->account.value, _self); } // Else, after all payouts are complete else { // adds a new round auto stitr = stats2.rbegin(); auto cur_round_id = stitr->round_id; auto oldpot = stitr->round_pot; float potkeep = config_get(gratz_potkp) / (float)100; uint64_t newpot = oldpot.amount * potkeep; stats2.emplace(_self, [&](auto& item) { item.round_id = ++cur_round_id; item.num_transfers = 0; item.num_acks = 0; item.volume = asset(0, gratitude_symbol); item.round_pot = asset(newpot, seeds_symbol); }); } } ACTION gratitude::newround() { require_auth(get_self()); action( permission_level{get_self(), "active"_n}, get_self(), "calcacks"_n, std::make_tuple((uint64_t)0) ).send(); } // Receive incoming SEEDS ACTION gratitude::deposit (name from, name to, asset quantity, string memo) { require_auth(from); if (get_first_receiver() == contracts::token && // from SEEDS token account to == get_self() && // to here quantity.symbol == seeds_symbol) { // SEEDS symbol utils::check_asset(quantity); // Updates stats auto stitr = stats2.rbegin(); auto round_id = stitr->round_id; // Have to use find to get a modifiable operator auto stitr2 = stats2.find(round_id); auto oldpot = stitr2->round_pot.amount; stats2.modify(stitr2, _self, [&](auto& item) { item.round_pot = asset(oldpot + quantity.amount, seeds_symbol); }); } } /// ----------================ PRIVATE ================---------- void gratitude::check_user (name account) { auto uitr = users.find(account.value); check(uitr != users.end(), "gratitude: user not found"); } void gratitude::_calc_acks (name donor) { auto bitr = balances.find(donor.value); if (bitr == balances.end()) { init_balances(donor); bitr = balances.find(donor.value); } uint64_t remaining = bitr->remaining.amount; auto min_acks = config_get(gratz_acks); auto actr = acks.find(donor.value); if (actr != acks.end()) { std::map<name, uint64_t> unique_recs; for (std::size_t i = 0; i < actr->receivers.size(); i++) { unique_recs[actr->receivers[i]]++; } auto uritr = unique_recs.begin(); while (uritr != unique_recs.end()) { uint64_t received = 0; if (actr->receivers.size() < min_acks) { received = (remaining / min_acks) * uritr->second; } else { received = (remaining / actr->receivers.size()) * uritr->second; } sub_gratitude(donor, asset(received, gratitude_symbol)); add_gratitude(uritr->first, asset(received, gratitude_symbol)); update_stats(donor, uritr->first, asset(received, gratitude_symbol)); uritr++; } } } uint64_t gratitude::get_current_volume() { auto stitr = stats2.rbegin(); // Should always work because reset always creates first round return stitr->volume.amount; } void gratitude::update_stats(name from, name to, asset quantity) { // Updating the last stats item auto itr = stats2.rbegin(); auto round_id = itr->round_id; auto stitr = stats2.find(round_id); auto oldvolume = stitr->volume.amount; auto oldtransfers = stitr->num_transfers; stats2.modify(stitr, _self, [&](auto& item) { item.volume = asset(oldvolume + quantity.amount, gratitude_symbol); item.num_transfers = oldtransfers + 1; }); } void gratitude::init_balances (name account) { auto bitr = balances.find(account.value); uint64_t generated_gratz = 0; auto uitr = users.find(account.value); if (uitr != users.end()) { switch (uitr->status) { case "citizen"_n: generated_gratz = config_get(gratzgen_cit); break; case "resident"_n: generated_gratz = config_get(gratzgen_res); break; } } if (bitr == balances.end()) { balances.emplace(_self, [&](auto & item){ item.account = account; item.received = asset(0, gratitude_symbol); item.remaining = asset(generated_gratz, gratitude_symbol); }); size_change("balances.sz"_n, 1); } } void gratitude::reset_balances (name account) { auto bitr = balances.find(account.value); uint64_t generated_gratz = 0; auto uitr = users.find(account.value); if (uitr != users.end()) { switch (uitr->status) { case "citizen"_n: generated_gratz = config_get(gratzgen_cit); break; case "resident"_n: generated_gratz = config_get(gratzgen_res); break; } } if (bitr == balances.end()) { balances.emplace(_self, [&](auto & item){ item.account = account; item.received = asset(0, gratitude_symbol); item.remaining = asset(generated_gratz, gratitude_symbol); }); size_change("balances.sz"_n, 1); } else { balances.modify(bitr, _self, [&](auto& item) { item.received = asset(0, gratitude_symbol); item.remaining = asset(generated_gratz, gratitude_symbol); }); } } void gratitude::add_gratitude (name account, asset quantity) { check_asset(quantity); auto bitr = balances.find(account.value); if (bitr == balances.end()) { init_balances(account); bitr = balances.find(account.value); } balances.modify(bitr, _self, [&](auto & item){ item.received += quantity; }); } void gratitude::sub_gratitude (name account, asset quantity) { check_asset(quantity); auto bitr = balances.find(account.value); if (bitr == balances.end()) { init_balances(account); bitr = balances.find(account.value); } check(bitr -> remaining.amount >= quantity.amount, "gratitude: not enough gratitude to give"); balances.modify(bitr, _self, [&](auto & item){ item.remaining -= quantity; }); } void gratitude::size_change(name id, int delta) { auto sitr = sizes.find(id.value); if (sitr == sizes.end()) { sizes.emplace(_self, [&](auto& item) { item.id = id; item.size = delta; }); } else { uint64_t newsize = sitr->size + delta; if (delta < 0) { if (sitr->size < -delta) { newsize = 0; } } sizes.modify(sitr, _self, [&](auto& item) { item.size = newsize; }); } } void gratitude::size_set(name id, uint64_t newsize) { auto sitr = sizes.find(id.value); if (sitr == sizes.end()) { sizes.emplace(_self, [&](auto& item) { item.id = id; item.size = newsize; }); } else { sizes.modify(sitr, _self, [&](auto& item) { item.size = newsize; }); } } uint64_t gratitude::get_size(name id) { auto sitr = sizes.find(id.value); if (sitr == sizes.end()) { return 0; } else { return sitr->size; } } uint64_t gratitude::config_get(name key) { auto citr = config.find(key.value); if (citr == config.end()) { check(false, ("settings: the "+key.to_string()+" parameter has not been initialized").c_str()); } return citr->value; } // Transfers out stored SEEDS void gratitude::_transfer (name beneficiary, asset quantity, string memo) { utils::check_asset(quantity); token::transfer_action action{contracts::token, {contracts::gratitude, "active"_n}}; action.send(contracts::gratitude, beneficiary, quantity, memo); }
26.293991
105
0.635028
shakhruz