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
5372cedf806e593384c41bcfca825a081f342a93
2,408
cpp
C++
Array/3Sum.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
Array/3Sum.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
null
null
null
Array/3Sum.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
5
2020-09-21T12:49:07.000Z
2020-09-29T16:13:09.000Z
class Solution { public: vector<vector<int>> threeSum(vector<int> &nums) { vector<vector<int>> ans; sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int l = i + 1; int r = n - 1; int tar = -nums[i]; while (l < r) { int sum = nums[l] + nums[r]; if (sum < tar) { l++; } else if (sum > tar) { r--; } else { vector<int> trip(3); trip[0] = nums[i]; trip[1] = nums[l]; trip[2] = nums[r]; ans.push_back(trip); while (l < r && nums[l] == trip[1]) { l++; } while (r > l && nums[r] == trip[2]) { r--; } } } } return ans; } }; class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> ans; for (int i = 0; i < int(nums.size()) - 2; i++) { if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { int sum = 0 - nums[i]; int low = i + 1; int high = nums.size() - 1; while (low < high) { if (nums[low] + nums[high] == sum) { ans.push_back(vector<int>{nums[i], nums[low], nums[high]}); while (low < high && nums[low] == nums[low + 1]) low++; while (low < high && nums[high] == nums[high - 1]) high--; low++; high--; } else if (nums[low] + nums[high] > sum) high--; else low++; } } } return ans; } };
27.678161
83
0.278654
harshallgarg
537700503cdd26d18fc2c5c38a1a6a27a8c41d17
1,404
cpp
C++
src/bits_of_matcha/engine/ops/SaveCsv.cpp
matcha-ai/matcha-engine
2ddc2a1dbe8b646176bf761b85720e94fc6b7cf9
[ "MIT" ]
null
null
null
src/bits_of_matcha/engine/ops/SaveCsv.cpp
matcha-ai/matcha-engine
2ddc2a1dbe8b646176bf761b85720e94fc6b7cf9
[ "MIT" ]
null
null
null
src/bits_of_matcha/engine/ops/SaveCsv.cpp
matcha-ai/matcha-engine
2ddc2a1dbe8b646176bf761b85720e94fc6b7cf9
[ "MIT" ]
1
2022-03-17T12:14:27.000Z
2022-03-17T12:14:27.000Z
#include "bits_of_matcha/engine/ops/SaveCsv.h" #include "bits_of_matcha/engine/tensor/iterations.h" #include <fstream> #include <iostream> #include <sstream> namespace matcha::engine::ops { SaveCsv::SaveCsv(Tensor* a, const std::string& file) : Op{a} , file_(file) {} void SaveCsv::run() { std::ofstream os(file_); dump(os); } void SaveCsv::dump(std::ostream& os) { dumpFrame(os); dumpData(os); } void SaveCsv::dumpFrame(std::ostream& os) { auto t = inputs[0]; if (t->dtype() != Float) os << "dtype," << t->dtype() << "\n"; if (t->rank() == 2) return; os << "shape"; for (unsigned dim: t->shape()) os << "," << dim; os << "\n"; } void SaveCsv::dumpData(std::ostream& os) { auto t = inputs[0]; auto f = t->buffer()->as<float*>(); if (t->rank() < 2) { float* end = f + t->size(); for (float* it = f; it != end; it++) { if (it != f) os << ","; os << *it; } os << "\n"; return; } MatrixStackIteration iter(t->shape()); float* tensorEnd = f + t->size(); for (float* matrix = f; matrix != tensorEnd ; matrix += iter.size) { float* matrixEnd = matrix + iter.size; for (float* row = matrix; row != matrixEnd; row += iter.cols) { float* rowEnd = row + iter.cols; for (float* col = row; col != rowEnd; col++) { if (col != row) os << ","; os << *col; } os << "\n"; } } } }
20.347826
70
0.538462
matcha-ai
537a0058e9af78f53b874b83272398e8b1b5cf87
3,344
hpp
C++
include/eepp/ui/uihelper.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
include/eepp/ui/uihelper.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
null
null
null
include/eepp/ui/uihelper.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#ifndef EE_UIHELPER_HPP #define EE_UIHELPER_HPP #include <eepp/graphics/font.hpp> #include <eepp/ui/base.hpp> using namespace EE::Graphics; namespace EE { namespace UI { #define UI_HALIGN_LEFT TEXT_ALIGN_LEFT #define UI_HALIGN_MASK TEXT_HALIGN_MASK #define UI_VALIGN_TOP TEXT_ALIGN_TOP #define UI_VALIGN_MASK TEXT_VALIGN_MASK enum UIFlag { UI_HALIGN_RIGHT = TEXT_ALIGN_RIGHT, UI_HALIGN_CENTER = TEXT_ALIGN_CENTER, UI_VALIGN_BOTTOM = TEXT_ALIGN_BOTTOM, UI_VALIGN_CENTER = TEXT_ALIGN_MIDDLE, UI_AUTO_SIZE = ( 1 << 4 ), UI_SKIN_KEEP_SIZE_ON_DRAW = ( 1 << 5 ), UI_FILL_BACKGROUND = ( 1 << 6 ), UI_FILL_FOREGROUND = ( 1 << 7 ), UI_BORDER = ( 1 << 8 ), UI_TAB_STOP = ( 1 << 9 ), UI_WORD_WRAP = ( 1 << 10 ), UI_MULTI_SELECT = ( 1 << 11 ), UI_AUTO_PADDING = ( 1 << 12 ), UI_DRAG_ENABLE = ( 1 << 13 ), UI_ANCHOR_TOP = ( 1 << 14 ), UI_ANCHOR_BOTTOM = ( 1 << 15 ), UI_ANCHOR_LEFT = ( 1 << 16 ), UI_ANCHOR_RIGHT = ( 1 << 17 ), UI_TOUCH_DRAG_ENABLED = ( 1 << 18 ), UI_TEXT_SELECTION_ENABLED = ( 1 << 19 ), UI_ATTRIBUTE_CHANGED = ( 1 << 20 ), UI_CHECKED = ( 1 << 21 ), UI_OWNS_CHILDS_POSITION = ( 1 << 22 ), UI_DRAG_VERTICAL = ( 1 << 23 ), UI_DRAG_HORIZONTAL = ( 1 << 24 ), UI_TAB_FOCUSABLE = ( 1 << 25 ) }; enum UINodeType { UI_TYPE_NODE = 0, UI_TYPE_UINODE, UI_TYPE_WIDGET, UI_TYPE_IMAGE, UI_TYPE_TEXTUREREGION, UI_TYPE_SPRITE, UI_TYPE_TEXTVIEW, UI_TYPE_TEXTINPUT, UI_TYPE_PUSHBUTTON, UI_TYPE_CHECKBOX, UI_TYPE_RADIOBUTTON, UI_TYPE_SLIDER, UI_TYPE_SPINBOX, UI_TYPE_SCROLLBAR, UI_TYPE_SCROLLVIEW, UI_TYPE_PROGRESSBAR, UI_TYPE_LISTBOX, UI_TYPE_LISTBOXITEM, UI_TYPE_DROPDOWNLIST, UI_TYPE_MENU_SEPARATOR, UI_TYPE_COMBOBOX, UI_TYPE_MENU, UI_TYPE_MENUITEM, UI_TYPE_MENUCHECKBOX, UI_TYPE_MENURADIOBUTTON, UI_TYPE_MENUSUBMENU, UI_TYPE_TEXTEDIT, UI_TYPE_TOOLTIP, UI_TYPE_WIDGETTABLE, UI_TYPE_WIDGETTABLEROW, UI_TYPE_WINDOW, UI_TYPE_MENUBAR, UI_TYPE_SELECTBUTTON, UI_TYPE_POPUPMENU, UI_TYPE_FILEDIALOG, UI_TYPE_TAB, UI_TYPE_TABWIDGET, UI_TYPE_LOADER, UI_TYPE_LINEAR_LAYOUT, UI_TYPE_RELATIVE_LAYOUT, UI_TYPE_TOUCH_DRAGGABLE_WIDGET, UI_TYPE_GRID_LAYOUT, UI_TYPE_LAYOUT, UI_TYPE_VIEWPAGER, UI_TYPE_ITEMCONTAINER, UI_TYPE_CODEEDITOR, UI_TYPE_SPLITTER, UI_TYPE_ABSTRACTVIEW, UI_TYPE_ABSTRACTTABLEVIEW, UI_TYPE_TREEVIEW, UI_TYPE_SCROLLABLEWIDGET, UI_TYPE_TREEVIEW_CELL, UI_TYPE_TABLEVIEW, UI_TYPE_TABLECELL, UI_TYPE_LISTVIEW, UI_TYPE_USER = 10000 }; enum class ScrollBarMode : Uint32 { Auto, AlwaysOn, AlwaysOff }; enum class UIOrientation : Uint32 { Vertical, Horizontal }; enum class SizePolicy : Uint32 { Fixed, MatchParent, WrapContent }; enum class PositionPolicy : Uint32 { None, LeftOf, RightOf, TopOf, BottomOf }; enum class UIScaleType : Uint32 { None, Expand, FitInside }; static const Uint32 UI_NODE_DEFAULT_ALIGN = UI_HALIGN_LEFT | UI_VALIGN_CENTER; static const Uint32 UI_NODE_ALIGN_CENTER = UI_HALIGN_CENTER | UI_VALIGN_CENTER; static const Uint32 UI_NODE_DEFAULT_ANCHOR = UI_ANCHOR_LEFT | UI_ANCHOR_TOP; static const Uint32 UI_NODE_DEFAULT_DRAG = UI_DRAG_VERTICAL | UI_DRAG_HORIZONTAL; static const Uint32 UI_NODE_DEFAULT_FLAGS = UI_NODE_DEFAULT_ANCHOR | UI_NODE_DEFAULT_ALIGN | UI_NODE_DEFAULT_DRAG; static const Uint32 UI_NODE_DEFAULT_FLAGS_CENTERED = UI_ANCHOR_LEFT | UI_ANCHOR_TOP | UI_HALIGN_CENTER | UI_VALIGN_CENTER; }} // namespace EE::UI #endif
25.526718
81
0.772727
jayrulez
537a5b183ea49888c3e68eb2d9aa545d3457a526
1,563
cpp
C++
src/terark/util/tmpfile.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
44
2020-12-21T05:14:38.000Z
2022-03-15T11:27:32.000Z
src/terark/util/tmpfile.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
2
2020-12-28T10:42:03.000Z
2021-05-21T07:22:47.000Z
src/terark/util/tmpfile.cpp
rockeet/terark-zip
3235373d04b7cf5d584259111b3a057c45cc1708
[ "BSD-3-Clause" ]
21
2020-12-22T09:40:16.000Z
2021-12-07T18:16:00.000Z
// created by leipeng at 2020-01-09 10:32 #include "tmpfile.hpp" #if _MSC_VER #include <io.h> #endif namespace terark { TempFileDeleteOnClose::~TempFileDeleteOnClose() { if (fp) this->close(); } void TempFileDeleteOnClose::open_temp() { if (!fstring(path).endsWith("XXXXXX")) { THROW_STD(invalid_argument, "ERROR: path = \"%s\", must ends with \"XXXXXX\"", path.c_str()); } #if _MSC_VER if (int err = _mktemp_s(&path[0], path.size() + 1)) { THROW_STD(invalid_argument, "ERROR: _mktemp_s(%s) = %s" , path.c_str(), strerror(err)); } this->open(); #else int fd = mkstemp(&path[0]); if (fd < 0) { int err = errno; THROW_STD(invalid_argument, "ERROR: mkstemp(%s) = %s", path.c_str(), strerror(err)); } this->dopen(fd); #endif } void TempFileDeleteOnClose::open(){ fp.open(path.c_str(), "wb+"); fp.disbuf(); writer.attach(&fp); } void TempFileDeleteOnClose::dopen(int fd) { fp.dopen(fd, "wb+"); fp.disbuf(); writer.attach(&fp); } void TempFileDeleteOnClose::close() { assert(nullptr != fp); writer.resetbuf(); fp.close(); ::remove(path.c_str()); } void TempFileDeleteOnClose::complete_write() { writer.flush_buffer(); fp.rewind(); } void AutoDeleteFile::Delete() { if (!fpath.empty()) { ::remove(fpath.c_str()); fpath.clear(); } } AutoDeleteFile::~AutoDeleteFile(){ if (!fpath.empty()) { ::remove(fpath.c_str()); } } } // namespace terark
21.410959
90
0.577095
rockeet
537d3047e1abd3ea85657f54eb428ea6f2ea5965
1,683
cpp
C++
UnitTests/bitarray_tests.cpp
jakubtyrcha/playground
d6be4387ffb2d9a2106f01b4c1b1a46ce78c1cef
[ "MIT" ]
null
null
null
UnitTests/bitarray_tests.cpp
jakubtyrcha/playground
d6be4387ffb2d9a2106f01b4c1b1a46ce78c1cef
[ "MIT" ]
null
null
null
UnitTests/bitarray_tests.cpp
jakubtyrcha/playground
d6be4387ffb2d9a2106f01b4c1b1a46ce78c1cef
[ "MIT" ]
null
null
null
#include "bitarray.h" #include "catch/catch.hpp" using namespace Playground; TEST_CASE("bitarray can store bits", "[bitarray]") { Bitarray b; b.Resize(1000); for (i32 i = 0; i < 1000; i++) { b.SetBit(i, (i % 3) == 0); } for (i32 i = 0; i < 1000; i++) { REQUIRE(b.GetBit(i) == ((i % 3) == 0)); } } TEST_CASE("bitarray can give next set bit", "[bitarray]") { Bitarray b; b.Resize(1000); REQUIRE(b.GetNextBitSet(0) == 1000); b.SetBit(0, true); b.SetBit(2, true); b.SetBit(3, true); b.SetBit(4, true); b.SetBit(63, true); b.SetBit(64, true); b.SetBit(65, true); b.SetBit(999, true); for (i32 i = 5; i < 63; i++) { REQUIRE(b.GetBit(i) == false); } REQUIRE(b.GetNextBitSet(0) == 0); REQUIRE(b.GetNextBitSet(1) == 2); REQUIRE(b.GetNextBitSet(2) == 2); REQUIRE(b.GetNextBitSet(3) == 3); REQUIRE(b.GetNextBitSet(4) == 4); REQUIRE(b.GetNextBitSet(5) == 63); REQUIRE(b.GetNextBitSet(63) == 63); REQUIRE(b.GetNextBitSet(64) == 64); REQUIRE(b.GetNextBitSet(65) == 65); REQUIRE(b.GetNextBitSet(66) == 999); REQUIRE(b.GetNextBitSet(999) == 999); } TEST_CASE("bitarray can test if any bit is set", "[bitarray]") { Bitarray b; b.Resize(63); REQUIRE(b.AnyBitSet() == false); b.SetBit(0, true); REQUIRE(b.AnyBitSet() == true); b.SetBit(0, false); REQUIRE(b.AnyBitSet() == false); b.SetBit(62, true); REQUIRE(b.AnyBitSet() == true); b.Resize(62); REQUIRE(b.AnyBitSet() == false); b.Resize(1000); REQUIRE(b.AnyBitSet() == false); b.SetBit(999, true); REQUIRE(b.AnyBitSet() == true); }
22.144737
62
0.56328
jakubtyrcha
537e55b26f570fac8b3a2e8a2495bdfa8101725c
758
cpp
C++
Medium/513_Find_Bottom_Left_Tree_Value.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Medium/513_Find_Bottom_Left_Tree_Value.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Medium/513_Find_Bottom_Left_Tree_Value.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { int key; queue<TreeNode*> q; q.push(root); while(!q.empty()) { int sz = q.size(); for(int i=0; i<sz; i++) { TreeNode* temp = q.front(); q.pop(); if(i==0) key = temp->val; if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } } return key; } };
24.451613
59
0.414248
ShehabMMohamed
53804e0fcc692cb73121e48bae12979f4f34173e
4,081
cc
C++
06-write-once-read-many/shared/src/worm.cc
timmerov/aggiornamento
d6af5c42d96522f6987c4b7c05a9421177504bcd
[ "Unlicense" ]
1
2016-09-21T19:15:20.000Z
2016-09-21T19:15:20.000Z
06-write-once-read-many/shared/src/worm.cc
timmerov/aggiornamento
d6af5c42d96522f6987c4b7c05a9421177504bcd
[ "Unlicense" ]
null
null
null
06-write-once-read-many/shared/src/worm.cc
timmerov/aggiornamento
d6af5c42d96522f6987c4b7c05a9421177504bcd
[ "Unlicense" ]
null
null
null
/* Copyright (C) 2012-2016 tim cotter. All rights reserved. */ /** write once-in-a-while read many example. worm implementation. assumes single writer, multiple simultaneous readers. assumes writer writes rarely. protecting the data in this case causes massive contention. so we don't. the data is constant the vast majority of the time. the strategy is to... - simply read the data. - detect the possibility of corrupt data. - retry if necessary. writer usage: char *ptr = getWriteBuffer(); memcpy(ptr, data, sizeof(data)); swap(); reader usage: int state; for(;;) { state = getStartState(); const char *ptr = getReadBuffer(state); memcpy(data, ptr, sizeof(data)); } while (checkState(state)); state is incremented every write. the low order bit identifies which buffer is which. the LOB is the index of the read buffer. 1-LOB is the index of the write buffer. use memory fences to ensure... - data is written to the buffer before the state is updated. - the start state is read before data is read from the buffer. - data is read from the buffer before the end state is read. **/ #include <aggiornamento/aggiornamento.h> #include <container/worm.h> #include <atomic> // use an anonymous namespace to avoid name collisions at link time. namespace { class WormImpl : public Worm { public: WormImpl() noexcept { data_[0] = nullptr; } WormImpl(const WormImpl &) = delete; virtual ~WormImpl() noexcept { delete[] data_[0]; } int size_ = 0; int volatile state_ = 0; char *data_[2]; }; } Worm::Worm() noexcept : agm::Container("WriteOnceReadMany") { } Worm::~Worm() { } /* master thread creates the worm. master thread deletes the worm. */ Worm *Worm::create( int size ) noexcept { auto impl = new(std::nothrow) WormImpl; auto stride = (size + 15) / 16 * 16; auto size2 = 2*stride; impl->size_ = size; impl->data_[0] = new(std::nothrow) char[size2]; impl->data_[1] = impl->data_[0] + stride; return impl; } /* returns the size of the buffer. */ int Worm::getSize() noexcept { auto impl = (WormImpl *) this; return impl->size_; } /* returns the write buffer. */ char *Worm::getWriteBuffer() noexcept { auto impl = (WormImpl *) this; // return the write buffer. auto idx = 1 - (impl->state_ & 1); auto ptr = impl->data_[idx]; return ptr; } /* swap the read/write buffers and update the state. */ void Worm::swap() noexcept { auto impl = (WormImpl *) this; /* a release fence forces completion of all pending reads and writes before the next write. in this case, the writer's new data is written before the state is changed. */ atomic_thread_fence(std::memory_order_release); ++impl->state_; } /* returns the state of the buffers. required to get the read buffer and to detect read failures. */ int Worm::getState() noexcept { auto impl = (WormImpl *) this; /* an acquire fence forces completion of all pending reads before the next read or write. in this case, the state is read before the the reader reads the data. */ auto state = impl->state_; atomic_thread_fence(std::memory_order_acquire); return state; } /* returns true if the current state is the same. returns false if the current state changed. */ bool Worm::checkState( int start_state ) noexcept { auto impl = (WormImpl *) this; /* an acquire fence forces completion of all pending reads before the next read or write. in this case, the reader's reads are completed before the state is re-read and tested. */ atomic_thread_fence(std::memory_order_acquire); auto end_state = impl->state_; return (start_state == end_state); } /* returns the read buffer. */ const char *Worm::getReadBuffer( int state ) noexcept { auto impl = (WormImpl *) this; // use the state passed to us to // determine the read buffer. auto idx = state & 1; auto ptr = impl->data_[idx]; return ptr; }
22.059459
68
0.664298
timmerov
53837e6b67db396214bce13e457e272dc8570deb
1,960
cpp
C++
src/algorithm_trivia/src/partition_algorithms.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
src/algorithm_trivia/src/partition_algorithms.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
src/algorithm_trivia/src/partition_algorithms.cpp
PeterSommerlad/CPPCourseIntroduction
9bc9cda460d504a3cf31bb059e858f9e8d5d3bf4
[ "MIT" ]
null
null
null
#include "partition_algorithms.h" #include "cute.h" #include "algorithm_replacements.h" #include <vector> #include <algorithm> #include <iterator> //Partition algorithms (hint): // * is_partitioned // * partition // * stable_partition // * partition_copy // * partition_point namespace { void test_algorithm_1() { std::vector<int> in1{2, 3, 5, 7, 1, 4, 6, 8, 9}; auto expected = std::begin(in1) + 4; auto res = std::xxx( std::begin(in1), std::end(in1), is_prime); ASSERT_EQUAL(expected, res); } void test_algorithm_2() { std::vector<int> in_out1{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> expected{2, 3, 5, 7, 1, 4, 6, 8, 9}; std::xxxxx( std::begin(in_out1), std::end(in_out1), is_prime); ASSERT_EQUAL(expected, in_out1); } void test_algorithm_3() { std::vector<int> in1{2, 3, 5, 7, 1, 4, 6, 8, 9}; bool res = std::xxxxx( std::begin(in1), std::end(in1), is_prime); ASSERT(res); } void test_algorithm_4() { std::vector<int> in1{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> out1{}; std::vector<int> out2{}; std::vector<int> expected1{2, 3, 5, 7}; std::vector<int> expected2{1, 4, 6, 8, 9}; std::xxxxx( std::begin(in1), std::end(in1), std::back_inserter(out1), std::back_inserter(out2), is_prime); ASSERT_EQUAL(std::tie(expected1, expected2), std::tie(out1, out2)); } void test_algorithm_5() { std::vector<int> in_out1{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> expected{7, 2, 3, 5, 4, 6, 1, 8, 9}; std::xxxxx( std::begin(in_out1), std::end(in_out1), is_prime); ASSERT_EQUAL(expected, in_out1); } } cute::suite make_suite_partition_algorithms() { cute::suite s { }; s.push_back(CUTE(test_algorithm_1)); s.push_back(CUTE(test_algorithm_2)); s.push_back(CUTE(test_algorithm_3)); s.push_back(CUTE(test_algorithm_4)); s.push_back(CUTE(test_algorithm_5)); return s; }
20.631579
69
0.611224
PeterSommerlad
53848f9f84d2f638958db5df18b39b5a9147a6a1
380
hpp
C++
src/behavior/singleagent/planning/stochastic/sparsesampling/sparse_sampling.hpp
MarkieMark/fastrl
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
[ "Apache-2.0" ]
4
2019-04-19T00:11:36.000Z
2020-04-08T09:50:37.000Z
src/behavior/singleagent/planning/stochastic/sparsesampling/sparse_sampling.hpp
MarkieMark/fastrl
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
[ "Apache-2.0" ]
null
null
null
src/behavior/singleagent/planning/stochastic/sparsesampling/sparse_sampling.hpp
MarkieMark/fastrl
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
[ "Apache-2.0" ]
null
null
null
/* * Mark Benjamin 6th March 2019 * Copyright (c) 2019 Mark Benjamin */ #ifndef FASTRL_BEHAVIOR_SINGLEAGENT_PLANNING_STOCHASTIC_SPARSESAMPLING_SPARSE_SAMPLING_HPP #define FASTRL_BEHAVIOR_SINGLEAGENT_PLANNING_STOCHASTIC_SPARSESAMPLING_SPARSE_SAMPLING_HPP class SparseSampling { }; #endif //FASTRL_BEHAVIOR_SINGLEAGENT_PLANNING_STOCHASTIC_SPARSESAMPLING_SPARSE_SAMPLING_HPP
25.333333
91
0.873684
MarkieMark
5384ff91a415c0595ee18f415cc464bb1ba72eff
615
cpp
C++
leetcode/1019. Next Greater Node In Linked List/s2.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/1019. Next Greater Node In Linked List/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/1019. Next Greater Node In Linked List/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/next-greater-node-in-linked-list/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(N) class Solution { public: vector<int> nextLargerNodes(ListNode* head) { vector<int> ans; stack<int> s; for (; head; head = head->next) ans.push_back(head->val); for (int i = 0; i < ans.size(); ++i) { while (s.size() && ans[s.top()] < ans[i]) { ans[s.top()] = ans[i]; s.pop(); } s.push(i); } for (; s.size(); s.pop()) ans[s.top()] = 0; return ans; } };
29.285714
70
0.476423
zhuohuwu0603
5387597aabae0bab71e06cbe6281d183159b0a76
1,684
cc
C++
net/grpc/gateway/codec/proto_encoder.cc
Atrasoftware/grpc-web
025b1d641b50b486bbae6921b5df4f9a515649a6
[ "BSD-3-Clause" ]
null
null
null
net/grpc/gateway/codec/proto_encoder.cc
Atrasoftware/grpc-web
025b1d641b50b486bbae6921b5df4f9a515649a6
[ "BSD-3-Clause" ]
null
null
null
net/grpc/gateway/codec/proto_encoder.cc
Atrasoftware/grpc-web
025b1d641b50b486bbae6921b5df4f9a515649a6
[ "BSD-3-Clause" ]
null
null
null
#include "net/grpc/gateway/codec/proto_encoder.h" #include <utility> #include <vector> #include "google/protobuf/any.pb.h" #include "net/grpc/gateway/protos/pair.pb.h" #include "net/grpc/gateway/protos/status.pb.h" #include "net/grpc/gateway/runtime/constants.h" #include "net/grpc/gateway/runtime/types.h" #include "third_party/grpc/include/grpc++/support/byte_buffer.h" #include "third_party/grpc/include/grpc++/support/slice.h" #include "third_party/grpc/include/grpc/slice.h" namespace grpc { namespace gateway { ProtoEncoder::ProtoEncoder() {} ProtoEncoder::~ProtoEncoder() {} void ProtoEncoder::Encode(grpc::ByteBuffer* input, std::vector<Slice>* result) { input->Dump(result); } void ProtoEncoder::EncodeStatus(const grpc::Status& status, const Trailers* trailers, std::vector<Slice>* result) { google::rpc::Status status_proto; status_proto.set_code(status.error_code()); status_proto.set_message(status.error_message()); if (trailers != nullptr) { for (auto& trailer : *trailers) { ::google::protobuf::Any* any = status_proto.add_details(); any->set_type_url(kTypeUrlPair); Pair pair; pair.set_first(trailer.first); pair.set_second(trailer.second.data(), trailer.second.length()); pair.SerializeToString(any->mutable_value()); } } grpc_slice status_slice = grpc_slice_malloc(status_proto.ByteSizeLong()); status_proto.SerializeToArray(GPR_SLICE_START_PTR(status_slice), GPR_SLICE_LENGTH(status_slice)); result->push_back(Slice(status_slice, Slice::STEAL_REF)); } } // namespace gateway } // namespace grpc
33.019608
80
0.697743
Atrasoftware
53927a879560d29f654a42b61be89ea80654aece
2,470
cpp
C++
OrionUO/TargetGump.cpp
shiryux/UOA-OrionUO
fd81d57db51efd39ecfaaa19fd0fb881bde8fef8
[ "MIT" ]
1
2019-04-13T09:30:27.000Z
2019-04-13T09:30:27.000Z
OrionUO/TargetGump.cpp
shiryux/UOA-OrionUO
fd81d57db51efd39ecfaaa19fd0fb881bde8fef8
[ "MIT" ]
null
null
null
OrionUO/TargetGump.cpp
shiryux/UOA-OrionUO
fd81d57db51efd39ecfaaa19fd0fb881bde8fef8
[ "MIT" ]
null
null
null
๏ปฟ// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /*********************************************************************************** ** ** TargetGump.cpp ** ** Copyright (C) August 2016 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "stdafx.h" //---------------------------------------------------------------------------------- CTargetGump g_TargetGump; CTargetGump g_AttackTargetGump; CNewTargetSystem g_NewTargetSystem; //---------------------------------------------------------------------------------- //-------------------------------------CTargetGump---------------------------------- //---------------------------------------------------------------------------------- CTargetGump::CTargetGump() { } //---------------------------------------------------------------------------------- CTargetGump::~CTargetGump() { } //---------------------------------------------------------------------------------- void CTargetGump::Draw() { WISPFUN_DEBUG("c210_f1"); if (m_Color != 0) { g_Orion.DrawGump(0x1068, m_Color, m_X, m_Y); if (m_Hits > 0) g_Orion.DrawGump(0x1069, m_HealthColor, m_X, m_Y, m_Hits, 0); } } //---------------------------------------------------------------------------------- //----------------------------------CNewTargetSystem-------------------------------- //---------------------------------------------------------------------------------- CNewTargetSystem::CNewTargetSystem() { } //---------------------------------------------------------------------------------- CNewTargetSystem::~CNewTargetSystem() { } //---------------------------------------------------------------------------------- void CNewTargetSystem::Draw() { WISPFUN_DEBUG("c211_f1"); if (!g_ConfigManager.DisableNewTargetSystem && m_ColorGump != 0) { CIndexObject &top = g_Orion.m_GumpDataIndex[m_GumpTop]; int x = m_X - (top.Width / 2); g_Orion.DrawGump(m_GumpTop, 0, x, m_TopY - top.Height); g_Orion.DrawGump(m_ColorGump, 0, x, m_TopY - top.Height); g_Orion.DrawGump(m_GumpBottom, 0, x, m_BottomY); if (m_Hits > 0) g_Orion.DrawGump(0x1069, m_HealthColor, m_X - 16, m_BottomY + 15, m_Hits, 0); } } //----------------------------------------------------------------------------------
36.323529
84
0.353846
shiryux
539b30aa9fa59ae61ab810ea85751d38a2075f99
2,736
hpp
C++
System/include/Switch/System/Net/WebSockets/WebSocketCloseStatus.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
4
2021-10-14T01:43:00.000Z
2022-03-13T02:16:08.000Z
src/Switch.System/include/Switch/System/Net/WebSockets/WebSocketCloseStatus.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
src/Switch.System/include/Switch/System/Net/WebSockets/WebSocketCloseStatus.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
/// @file /// @brief Contains Switch::System::Net::WebSockets::WebSocketCloseStatus enum. #pragma once #include <Switch/System/Enum.hpp> /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The System::Net namespace provides a simple programming interface for many of the protocols used on networks today. /// The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols. namespace Net { /// @brief The System::Net::WebSockets namespace provides a managed implementation of the WebSocket interface for developers. namespace WebSockets { /// @brief Represents well known WebSocket close codes as defined in section 11.7 of the WebSocket protocol spec. /// @par Library /// Switch.System enum class WebSocketCloseStatus { /// @brief No error specified. Empty = 0, /// @brief The connection will be closed by the server because of an error on the server. InternalServerError, /// @brief (1000) The connection has closed after the request was fulfilled. NormalClosure = 1000, /// @brief (1001) Indicates an endpoint is being removed. Either the server or client will become unavailable. EndpointUnavailable = 1001, /// @brief (1002) The client or server is terminating the connection because of a protocol error. ProtocolError = 1002, /// @brief (1003) The client or server is terminating the connection because it cannot accept the data type it received. InvalidMessageType = 1003, /// @brief (1004) Reserved for future use. MessageTooBig = 1004, /// @brief (1007) The client or server is terminating the connection because it has received data inconsistent with the message type. InvalidPayloadData = 1007, /// @brief (1008) The connection will be closed because an endpoint has received a message that violates its policy. PolicyViolation = 1008, /// @brief (1010) The client is terminating the connection because it expected the server to negotiate an extension. MandatoryExtension = 1010 }; } } } } using namespace Switch;
58.212766
281
0.702851
kkptm
53a6506a5dbc0c3bd9c6f7cc1743dd5b2ad9b42b
3,349
hpp
C++
openstudiocore/src/openstudio_lib/ScheduleDialog.hpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
1
2019-11-12T02:07:03.000Z
2019-11-12T02:07:03.000Z
openstudiocore/src/openstudio_lib/ScheduleDialog.hpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
1
2019-02-04T23:30:45.000Z
2019-02-04T23:30:45.000Z
openstudiocore/src/openstudio_lib/ScheduleDialog.hpp
hellok-coder/OS-Testing
e9e18ad9e99f709a3f992601ed8d2e0662175af4
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #ifndef OPENSTUDIO_SCHEDULEDIALOG_HPP #define OPENSTUDIO_SCHEDULEDIALOG_HPP #include "../model/Model.hpp" #include "../model/ScheduleTypeRegistry.hpp" #include "../model/ScheduleTypeLimits.hpp" #include "../shared_gui_components/OSDialog.hpp" #include <set> class QLabel; class QComboBox; namespace openstudio { class ScheduleDialog : public OSDialog { Q_OBJECT public: ScheduleDialog(bool isIP, const model::Model & model, QWidget * parent = nullptr); virtual ~ScheduleDialog() {} void setIsIP(bool isIP); private slots: void onCurrentIndexChanged(int index); private: virtual void createLayout() override; bool m_isIP; model::Model m_model; boost::optional<model::ScheduleTypeLimits> m_scheduleTypeLimits; QComboBox * m_scheduleTypeComboBox; QLabel * m_numericTypeLabel; QLabel * m_lowerLimitLabel; QLabel * m_upperLimitLabel; protected slots: virtual void on_okButton(bool checked) override; }; } // openstudio #endif // OPENSTUDIO_SCHEDULEDIALOG_HPP
36.402174
125
0.710958
hellok-coder
53a9d7ce1575074745b6bf922fd6f81c47f72a10
810
cpp
C++
src/Hitbox.cpp
cjmar/battleship
8fb895ebe7b89ddd1640f78b6607cfbbdb33cde9
[ "MIT" ]
null
null
null
src/Hitbox.cpp
cjmar/battleship
8fb895ebe7b89ddd1640f78b6607cfbbdb33cde9
[ "MIT" ]
null
null
null
src/Hitbox.cpp
cjmar/battleship
8fb895ebe7b89ddd1640f78b6607cfbbdb33cde9
[ "MIT" ]
null
null
null
#include "Hitbox.h" /* Aligned axis rectangle hitbox check */ bool Hitbox::rectCollide(SDL_Rect& r1, SDL_Rect& r2) { bool collide = false; if (r1.x < r2.x + r2.w && r1.x + r1.w > r2.x && r1.y < r2.y + r2.h && r1.y + r1.h > r2.y) collide = true; return collide; } /* Just calls rectCollide on the sprites destination rectangle */ bool Hitbox::spriteCollide(Sprite& s1, Sprite& s2) { return Hitbox::rectCollide(s1.destRect, s2.destRect);; } bool Hitbox::rectClickHit(int x, int y, SDL_Rect box, float scaling) { bool isxHit = false; bool isyHit = false; if (x >= box.x * scaling && x < box.x * scaling + box.w * scaling) isxHit = true; if (y >= box.y * scaling && y < box.y * scaling + box.h * scaling) isyHit = true; return (isxHit && isyHit); }
21.315789
83
0.608642
cjmar
53aa724e2bad3eef9e27207a2502fa1fa85cc4c2
2,687
hpp
C++
engine/src/ui/Units.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-01T20:22:41.000Z
2021-11-01T20:22:41.000Z
engine/src/ui/Units.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-02T12:45:20.000Z
2021-11-02T12:45:20.000Z
engine/src/ui/Units.hpp
Birdy2014/Birdy3d
96421f262ab6ba7448cae8381063aab32ac830fe
[ "MIT" ]
1
2021-11-02T12:28:58.000Z
2021-11-02T12:28:58.000Z
#pragma once #include "core/Base.hpp" namespace Birdy3d::ui { enum class Placement { TOP_LEFT, BOTTOM_LEFT, TOP_RIGHT, BOTTOM_RIGHT, CENTER_LEFT, CENTER_RIGHT, TOP_CENTER, BOTTOM_CENTER, CENTER }; class Unit { public: float pixels; float percent; Unit(float pixels, float percent = 0.0f); void operator=(float value); operator float(); float to_pixels(float parentSize = 0); bool operator==(const Unit& other) const; Unit operator+(const Unit& other); Unit& operator+=(const Unit& other); Unit operator-(); Unit operator-(const Unit& other); Unit& operator-=(const Unit& other); template <typename T, typename = std::enable_if<std::is_arithmetic<T>::value, T>> Unit operator+(const T& other) { return Unit(pixels + other, percent); } template <typename T, typename = std::enable_if<std::is_arithmetic<T>::value, T>> Unit& operator+=(const T& other) { pixels += other; return *this; } template <typename T, typename = std::enable_if<std::is_arithmetic<T>::value, T>> Unit operator-(const T& other) { return Unit(pixels - other, percent); } template <typename T, typename = std::enable_if<std::is_arithmetic<T>::value, T>> Unit& operator-=(const T& other) { pixels -= other; return *this; } }; class UIVector { public: Unit x; Unit y; UIVector(); UIVector(const UIVector& v); UIVector(const glm::vec2& v); UIVector(Unit x); UIVector(Unit x, Unit y); UIVector& operator=(const UIVector& other); bool operator==(const UIVector& other) const; UIVector operator+(const UIVector& other); UIVector operator+(const float other); UIVector operator-(); UIVector operator-(const UIVector& other); UIVector operator+=(const UIVector& other); UIVector operator+=(const float other); UIVector operator-=(const UIVector& other); glm::vec2 to_pixels(glm::vec2 parentSize = glm::vec2(0)); operator glm::vec2(); static glm::vec2 get_relative_position(UIVector pos, UIVector size, glm::vec2 parentSize, Placement placement); }; inline namespace literals { Unit operator"" _px(long double value); Unit operator"" _px(unsigned long long value); Unit operator"" _p(long double value); Unit operator"" _p(unsigned long long value); } }
29.206522
119
0.580945
Birdy2014
53ab62cc781d1097a93633ea732f123a93db1112
2,289
hpp
C++
include/qtm-calc/data.hpp
Andinoriel/qtm-calc
940d88c2db187f75d74086bf8feb8e11f4c566e8
[ "MIT" ]
3
2021-01-15T15:47:17.000Z
2021-02-22T12:24:43.000Z
include/qtm-calc/data.hpp
andinoriel/qtm-calc
940d88c2db187f75d74086bf8feb8e11f4c566e8
[ "MIT" ]
null
null
null
include/qtm-calc/data.hpp
andinoriel/qtm-calc
940d88c2db187f75d74086bf8feb8e11f4c566e8
[ "MIT" ]
null
null
null
#pragma once #ifndef __QTM_DATA_HPP__ #define __QTM_DATA_HPP__ #include <qtm-calc/core.hpp> namespace qtm { /** * Queueing system analysis class * * ... * * Implements calculation of special characteristics of the queuing system */ class qtm_data final : private boost::noncopyable { private: /** * Perform calculation the final states for a given instance of the queuing system * * @param[in] qtm Instance of qtm::qtm core class */ static void calc_fs_if_outdated(qtm &qtm); public: qtm_data(void) = delete; ~qtm_data(void) = delete; /** * Perform calculation of the average queue size for a given instance * of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_avg_queue(qtm &qtm); /** * Perform calculation of the ETE for a given instance * of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_ete(qtm &qtm); /** * Perform calculation of the average time in queue for a given instance * of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_avg_time_queue(qtm &qtm); /** * Perform calculation of the percent of served requests for a given instance * of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_perc_served_req(qtm &qtm); /** * Perform calculation of the average count of served requests for a given instance * of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_avg_count_served_req(qtm &qtm); /** * Perform calculation of the average count of requests for a given instance * of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_avg_count_req(qtm &qtm); /** * Perform calculation of the average count of unserved requests for a given * instance of the queuing system and get the result * * @param[in] qtm Instance of qtm::qtm core class */ static double calc_avg_count_unserved_req(qtm &qtm); }; }; // namespace qtm #endif // !__QTM_DATA_HPP__
27.578313
85
0.694626
Andinoriel
53ae80703ba2554577716223887a3ea7ddac7b92
1,422
cpp
C++
loops-1.8.cpp
dazmodel/cpp-study
169569b8e29eab209f15bec042c6aac014737356
[ "MIT" ]
null
null
null
loops-1.8.cpp
dazmodel/cpp-study
169569b8e29eab209f15bec042c6aac014737356
[ "MIT" ]
null
null
null
loops-1.8.cpp
dazmodel/cpp-study
169569b8e29eab209f15bec042c6aac014737356
[ "MIT" ]
null
null
null
#include <cmath> #include <stdio.h> #include <iostream> using namespace std; int main() { // ะ—ะฐะดะฐะตะผ ะฟะฐั€ะฐะผะตั‚ั€ั‹ ะพะบั€ัƒะถะฝะพัั‚ะธ int a, b, radius; cout << " Vvedite koordinaty centra kryga (a, b):" << endl; cin >> a >> b; cout << " Vvedite radius kryga:" << endl; cin >> radius; // --------- ะžะฑั€ะฐะฑะฐั‚ั‹ะฒะฐะตะผ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะน ะฒะฒะพะด ั‚ะพั‡ะตะบ --------- int numberOfPoints = 5; // ะœะฐััะธะฒ ะดะปั ัะพั…ั€ะฐะฝะตะฝะธั ะฝะฐะฑะพั€ะพะฒ ัั‚ะพั€ะพะฝ ั‚ั€ะตัƒะณะพะปัŒะฝะธะบะฐ // ะฒะฒะตะดะตะฝะฝั‹ั… ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะตะผ int userInput [numberOfPoints][2]; cout << " Vvedite " << numberOfPoints << " koordinat to4ek (x, y): " << endl; cout << endl; for (int i = 0; i < numberOfPoints; i++) { cout << " Vvedite nabor to4ek #" << i + 1 << " (x, y)" << endl; cin >> userInput[i][0] >> userInput[i][1]; } // ----------------------------------------------------- // ---------- ะ’ั‹ั‡ะธัะปัะตะผ ะฟะพะฟะฐะดะฐะฝะธะต ั‚ะพั‡ะบะธ ะฒ ะพะบั€ัƒะถะฝะพัั‚ัŒ for (int i = 0; i < numberOfPoints; i++) { bool bingo = (pow((userInput[i][0] - a), 2) + pow((userInput[i][1] - b), 2)) <= pow(radius, 2); if(bingo) { cout << " Tochka (" << userInput[i][0] << ", " << userInput[i][1] << ") popadaiet v okryshnost" << endl; } else { cout << " Tochka (" << userInput[i][0] << ", " << userInput[i][1] << ") NE popadaiet v okryshnost" << endl; } } // ----------------------------------------------------------------------- return 0; }
31.6
123
0.490155
dazmodel
53b05791e49c4e6ee4a4494df21f8f4a17c95b1e
1,378
hpp
C++
include/ttl/nn/bits/ops/hash.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
3
2018-10-23T18:46:39.000Z
2019-06-24T00:46:10.000Z
include/ttl/nn/bits/ops/hash.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
27
2018-11-10T14:19:16.000Z
2020-03-08T23:33:01.000Z
include/ttl/nn/bits/ops/hash.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
1
2018-11-05T06:17:12.000Z
2018-11-05T06:17:12.000Z
#pragma once #include <ttl/nn/bits/kernels/cpu/hash.hpp> #include <ttl/nn/common.hpp> namespace ttl::nn::ops { template <typename N> class basic_crc { N poly_; public: basic_crc(const N poly) : poly_(poly) {} template <rank_t r> shape<0> operator()(const shape<r> &) const { return shape<0>(); } template <typename R, rank_t r, typename D> void operator()(const tensor_ref<N, 0, D> &y, const tensor_view<R, r, D> &x) const { kernels::crc<D, N> kernel(poly_); // FIXME : cache kernel kernel(y, x); } }; template <typename N = uint32_t> class crc : basic_crc<N> { using P = basic_crc<N>; using P::P; public: using P::operator(); }; template <typename N, N seed> class standard_crc : basic_crc<N> { using P = basic_crc<N>; public: standard_crc() : P(seed) {} using P::operator(); }; struct crc_polynomials { static constexpr uint16_t usb = static_cast<uint16_t>(0xa001); static constexpr uint32_t ieee = static_cast<uint32_t>(0xedb88320); static constexpr uint64_t ecma = static_cast<uint64_t>(0xC96C5795D7870F42); }; using crc16_usb = standard_crc<uint16_t, crc_polynomials::usb>; using crc32_ieee = standard_crc<uint32_t, crc_polynomials::ieee>; using crc64_ecma = standard_crc<uint64_t, crc_polynomials::ecma>; } // namespace ttl::nn::ops
22.590164
79
0.654572
stdml
53b4181594c5800b84891baa78eebf96b1952ecc
312
hpp
C++
include/shacl/trait/RangeTraits.hpp
shacl/trait
c647510210ddec516d40ac17275cbd30a14c4fd8
[ "BSD-3-Clause" ]
null
null
null
include/shacl/trait/RangeTraits.hpp
shacl/trait
c647510210ddec516d40ac17275cbd30a14c4fd8
[ "BSD-3-Clause" ]
2
2021-02-26T02:40:51.000Z
2021-03-19T18:11:11.000Z
include/shacl/trait/RangeTraits.hpp
shacl/trait
c647510210ddec516d40ac17275cbd30a14c4fd8
[ "BSD-3-Clause" ]
null
null
null
template<typename T, std::enable_if_t< IsRange_v<T>, bool > = true > struct RangeTraits { using iterator_type = decltype( std::begin( std::declval<T>() ) ); using sentinel_type = decltype( std::end( std::declval<T>() ) ); using value_type = typename std::iterator_traits<iterator_type>::value_type; };
34.666667
78
0.698718
shacl
53b89903217bdf134b538786e04289513fa7a224
7,420
cpp
C++
ext/include/osgEarthDrivers/refresh/ReaderWriterRefresh.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
6
2015-09-26T15:33:41.000Z
2021-06-13T13:21:50.000Z
ext/include/osgEarthDrivers/refresh/ReaderWriterRefresh.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
null
null
null
ext/include/osgEarthDrivers/refresh/ReaderWriterRefresh.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
5
2015-05-04T09:02:23.000Z
2019-06-17T11:34:12.000Z
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth 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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <osgEarth/TileSource> #include <osgEarth/FileUtils> #include <osgEarth/ImageUtils> #include <osgEarth/Registry> #include <osg/Notify> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osg/ImageStream> #include <osg/ImageSequence> #include <sstream> #include <iomanip> #include <string.h> #include "RefreshOptions" using namespace osgEarth; using namespace osgEarth::Drivers; #define LC "[Refresh driver] " /* * LoadImageOperation is a simple operation that simply loads an image in a background thread */ class LoadImageOperation : public osg::Operation { public: LoadImageOperation(const std::string& filename): _filename(filename), _done(false) { } void operator()(osg::Object*) { //Try to load the image a few times. If you happen to be writing the file at the //same time as the plugin tries to load it it can fail. unsigned int maxTries = 5; for (unsigned int i = 0; i < maxTries; i++) { _image = osgDB::readImageFile( _filename ); if (_image.valid()) break; } _done = true; } bool _done; osg::ref_ptr< osg::Image > _image; std::string _filename; }; /* * RefreshImage is a special ImageStream that reloads an image from a filename and * updates it's internal image data. */ class RefreshImage : public osg::ImageStream { public: RefreshImage(const std::string& filename, double time): _filename(filename), _time(time), _lastUpdateTime(0), osg::ImageStream() { osg::ref_ptr< osg::Image > image = osgDB::readImageFile( filename ); if (image.valid()) copyImage( image.get() ); } /** * Tell OpenSceneGraph that we require an update call */ virtual bool requiresUpdateCall() const { return true; } ~RefreshImage() { } static osg::OperationsThread* getOperationsThread() { //Create an Operations Thread. This thread is static and is not deleted b/c //there are issues with calling cancel on static threads on Windows. The thread itself will die //cleanly, but the application will hang waiting for the cancel call in OpenThreads to return. //This is something that needs to be fixed in OpenThreads so we can maintain a static threadpool. static osg::OperationsThread* _thread = 0; static OpenThreads::Mutex _mutex; if (!_thread) { OpenThreads::ScopedLock< OpenThreads::Mutex > lock(_mutex); if (!_thread) { _thread = new osg::OperationsThread; _thread->start(); } } return _thread; } //If the loadImageOp is complete then update the contents of this image with the new pixels void updateImage() { if (_loadImageOp.valid() && _loadImageOp->_done) { osg::ref_ptr< osg::Image > image = _loadImageOp->_image.get(); if (image.valid()) { copyImage( image.get() ); } _lastUpdateTime = osg::Timer::instance()->time_s(); _loadImageOp = 0; } } /** * Copies the contents of the given image into this image. */ void copyImage( osg::Image* image) { if (image) { unsigned char* data = new unsigned char[ image->getTotalSizeInBytes() ]; memcpy(data, image->data(), image->getTotalSizeInBytes()); setImage(image->s(), image->t(), image->r(), image->getInternalTextureFormat(), image->getPixelFormat(), image->getDataType(), data, osg::Image::USE_NEW_DELETE, image->getPacking()); } } /** update method for osg::Image subclasses that update themselves during the update traversal.*/ virtual void update(osg::NodeVisitor* nv) { updateImage(); double time = osg::Timer::instance()->time_s(); osg::Timer_t ticks = osg::Timer::instance()->tick(); //If we've let enough time elapse and we're not waiting on an existing load image operation then add one to the queue if (!_loadImageOp.valid() && (time - _lastUpdateTime > _time)) { std::stringstream ss; std::string file = ss.str(); _loadImageOp = new LoadImageOperation(_filename); getOperationsThread()->add( _loadImageOp.get() ); } } std::string _filename; double _time; double _lastUpdateTime; osg::ref_ptr< LoadImageOperation > _loadImageOp; }; class RefreshSource : public TileSource { public: RefreshSource(const TileSourceOptions& options) : TileSource(options), _options(options) { } Status initialize(const osgDB::Options* dbOptions) { setProfile( osgEarth::Registry::instance()->getGlobalGeodeticProfile() ); return STATUS_OK; } osg::Image* createImage( const TileKey& key, ProgressCallback* progress ) { return new RefreshImage( _options.url()->full(), *_options.frequency()); } bool isDynamic() const { //Tell osgEarth that this is a dynamic image return true; } virtual int getPixelsPerTile() const { return 256; } virtual std::string getExtension() const { return osgDB::getFileExtension( _options.url()->full() ); } private: const RefreshOptions _options; }; class ReaderWriterRefresh : public TileSourceDriver { public: ReaderWriterRefresh() { supportsExtension( "osgearth_refresh", "Refresh" ); } virtual const char* className() { return "ReaderWriterRefresh"; } virtual ReadResult readObject(const std::string& file_name, const Options* options) const { if ( !acceptsExtension(osgDB::getLowerCaseFileExtension( file_name ))) return ReadResult::FILE_NOT_HANDLED; return new RefreshSource( getTileSourceOptions(options) ); } }; REGISTER_OSGPLUGIN(osgearth_refresh, ReaderWriterRefresh)
29.799197
224
0.600674
energonQuest
53be7545383671eb2243ae6081c1e851ccaa8d01
81,533
cpp
C++
s32v234_sdk/libs/io/sdi/src/sdi.cpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
null
null
null
s32v234_sdk/libs/io/sdi/src/sdi.cpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
null
null
null
s32v234_sdk/libs/io/sdi/src/sdi.cpp
intesight/Panorama4AIWAYS
46e1988e54a5155be3b3b47c486b3f722be00b5c
[ "WTFPL" ]
2
2021-01-21T02:06:16.000Z
2021-01-28T10:47:37.000Z
/****************************************************************************** * * Freescale Confidential Proprietary * * Copyright (c) 2016 Freescale Semiconductor; * Copyright (c) 2016-17 NXP; * All Rights Reserved * ***************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITEDl TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * \file sdi.cpp * \brief Sensor device interface functionality implementation. * \author Tomas Babinec * \version 0.1 * \date 16-September-2013 ****************************************************************************/ /*============================================================================= Revision History: Modification Tracking Author (core ID) Date D/M/Y Number Description of Changes Tomas Babinec 16-Sep-2013 Init version B51945 01-Nov-2017 VSDK-1455 Fix wrong implementation in sdi driver. =============================================================================*/ #ifdef SDI_ECLIPSE_DEF #define GBO_FILE "GBOpts_APEX2_Pseudo_FPGA_Valid.h" #endif #include "s32vs234.h" #include <unistd.h> #ifndef __STANDALONE__ #include <sys/mman.h> // #include <pthread.h> #include <sys/time.h> #endif // #ifndef __STANDALONE__ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include "sdi.hpp" #include "vdb_log.h" #include "oal.h" #include "oal_extras.h" #include "oal_process.h" #include "isp_fdma.h" #include "seq.h" #include "isp_seq.h" //**************************************************************************** // consts //**************************************************************************** //**************************************************************************** // macros //**************************************************************************** #define ALIGN2(_x) (((_x)/2 + (((_x)%2)?1:0)) * 2) #define UNUSED(_x) (void)(_x) // to suppress unused parameter warning //**************************************************************************** // local variables //**************************************************************************** #ifdef SDI_THRED_SAFE // process/thread safety under development static const char *scpSemInitName = "sdiSini"; static const char *scpMutSdiName = "sdiMut"; static const char *scpShmName = "sdiMem"; #endif // #ifdef SDI_THRED_SAFE static const uint32_t scSemWaitMax = 5000000; ///< maximum time to wait for semaphore #ifdef __STANDALONE__ extern "C" { unsigned long get_uptime_microS(void); } #endif // #ifdef __STANDALONE__ //**************************************************************************** // local functions declarations //**************************************************************************** #ifdef __STANDALONE__ void IspHwSramAccesAllow(void); #endif //**************************************************************************** // static members definition //**************************************************************************** bool sdi::mInitialized = false; uint32_t* sdi::mpSharedMemorySize = NULL; uint32_t* sdi::mpInitCounter = NULL; uint32_t sdi::mThreadCounter = 0; uint32_t* sdi::mpSensorCnt = NULL; //vector<sdi_process*> sdi::mProcesses(SDI_SENSOR_CNT); // initial number of processes == number of sensors uint32_t sdi::mNextProcessId = 1; OAL_SEMAPHORE sdi::mSdiMut = NULL; OAL_SEMAPHORE sdi::mInitSemaphore = NULL; OAL_SHARED_MEM sdi::mShm = NULL; void* sdi::mPramBase = NULL; // int32_t gEvent = 0; //**************************************************************************** // *** sdi_process implementation *** //**************************************************************************** sdi_process::sdi_process() : mpGraph(NULL), mpCramCache(NULL), mpKramCache(NULL) { // set defaults } // sdi_process::sdi_process() //**************************************************************************** LIB_RESULT sdi_process::Set(SEQ_Head_Ptr_t* apGraph, GraphMetadata_t* apGraphMetadata, const char* acpKmemSrec = kmem_srec, const char* acpSequencerSrec = sequencer_srec ) { LIB_RESULT lRet = LIB_SUCCESS; mpKramCache = SEQ_FwArrPreProc(acpKmemSrec, SEQ_FW_KERNEL); if(mpKramCache != NULL) { VDB_LOG_WARNING("KRAM is empty.\n"); // valid case } // if kram empty mpCramCache = SEQ_FwArrPreProc(acpSequencerSrec, SEQ_FW_CM0); if(mpCramCache == NULL) { VDB_LOG_ERROR("Sequencer FW srec is NULL.\n"); // no M0 FW not allowed lRet = LIB_FAILURE; } // if sequencer FW is NULL else { if(mpGraph != NULL) { VDB_LOG_WARNING("Graph set allready. Reset required.\n"); lRet = LIB_FAILURE; } // if graph set allready else { mpGraph = new sdi_graph(apGraph, apGraphMetadata) ; if((mpGraph == NULL)) { VDB_LOG_ERROR("Failed to preprocess the graph.\n"); lRet = LIB_FAILURE; } // if sdi_graph creation failed else { // all ok (nothing more to be done) VDB_LOG_NOTE("Process set successfully.\n"); } // else from if sdi_graph creation failed } // else from if graph set allready } // else from if sequencer FW is NULL return lRet; } // sdi_process::Set() //**************************************************************************** LIB_RESULT sdi_process::Reset() { LIB_RESULT lRet = LIB_SUCCESS; // destroy the graph if(mpGraph != NULL) { delete(mpGraph); mpGraph = NULL; } // if graph exists if(mpKramCache != NULL) { delete(mpKramCache); mpKramCache = NULL; } // if previous KRAM cache exists if(mpCramCache != NULL) { delete(mpCramCache); mpCramCache = NULL; } // if previous CRAM cache exists VDB_LOG_FCN_NOT_IMPLEMENTED(); return lRet; } // sdi_process::Reset() //**************************************************************************** LIB_RESULT sdi_process::Finalize() { LIB_RESULT lRet = LIB_SUCCESS; if(mpGraph != NULL) { if(mpGraph->Finalize() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to finalize the graph.\n"); lRet = LIB_FAILURE; } // if graph finalize failed } // if graph exists else { VDB_LOG_WARNING("There is no graph.\n"); } // else if grah exists return lRet; } // sdi_process::Finalize(void) //**************************************************************************** LIB_RESULT sdi_process::Free(void) { LIB_RESULT lRet = LIB_SUCCESS; if(mpGraph != NULL) { mpGraph->Free(); } // if graph exists else { VDB_LOG_WARNING("There is no graph.\n"); } // else if grah exists return lRet; } // Free(void) //**************************************************************************** LIB_RESULT sdi_process::Download() { LIB_RESULT lRet = LIB_SUCCESS; // *** M0 FW *** if(SEQ_FwArrDownload(mpCramCache, SEQ_FW_CM0) == LIB_SUCCESS) { // *** IPU kernels *** if(SEQ_FwArrDownload(mpKramCache, SEQ_FW_KERNEL) == LIB_SUCCESS) { //*** Graph *** if(mpGraph != NULL) { if(mpGraph->Download(0) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to download the graph.\n"); lRet = LIB_FAILURE; } // if graph finalize failed } // if graph exists else { VDB_LOG_WARNING("There is no graph.\n"); } // else if grah exists }// if IPU kernels ok else { lRet = LIB_FAILURE; } // else from if IPU kernels ok } // if FW download ok else { lRet = LIB_FAILURE; } // else from if FW download ok return lRet; } // sdi_process::Download(void) //**************************************************************************** SEQ_Buf_t** sdi_process::GraphFetch(SEQ_Head_Ptr_t** appGraph) { SEQ_Buf_t **lppBufferList = NULL; mpGraph->Fetch(appGraph, &lppBufferList); return lppBufferList; } // sdi_process::GraphFetch(SEQ_Head_Ptr_t** appGraph) //**************************************************************************** LIB_RESULT sdi_process::IOsGet(sdi_io *apIOs[]) { LIB_RESULT lRet = LIB_SUCCESS; // check input if(apIOs != NULL) { if(mpGraph != NULL) { for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { // get the IO indexes if( mpGraph->IoQuery((SEQ_Othr_ix_t) i) == LIB_SUCCESS) { // construct IO objects apIOs[i] = IOcreate((SEQ_Othr_ix_t) i); if ( apIOs[i] == NULL) { VDB_LOG_ERROR("Failed to generate %uth IO object.\n", i); apIOs[i] = NULL; lRet = LIB_FAILURE; } // if IOcreate failed } // if no such object } // for all possible IO objects } // if graph exists else { VDB_LOG_WARNING("There is no graph\n"); } // else from if graph exists } // if graph exists else { VDB_LOG_ERROR("Parameter is NULL.\n"); lRet = LIB_FAILURE; } // else from if graph exists return lRet; } // sdi_process::IOsGet(sdi_input *apIOs[]) //**************************************************************************** sdi_io* sdi_process::IOcreate(SEQ_Othr_ix_t aTypeIdx) { sdi_io *lpRetIO = NULL; switch(aTypeIdx) { case SEQ_OTHRIX_FDMA: { lpRetIO = (sdi_io*) new sdi_FdmaIO(mpGraph); } // case SEQ_OTHRIX_FDMA break; #ifndef __STANDALONE__ case SEQ_OTHRIX_H264ENC: { lpRetIO = (sdi_io*) new sdi_H264EncIO(mpGraph); } // case SEQ_OTHRIX_H264ENC break; #endif // #ifndef __STANDALONE__ case SEQ_OTHRIX_H264DEC: { lpRetIO = (sdi_io*) new sdi_H264DecIO(mpGraph); } // case SEQ_OTHRIX_H264DEC break; case SEQ_OTHRIX_JPEGDEC: { lpRetIO = (sdi_io*) new sdi_JpegDecIO(mpGraph); } // case SEQ_OTHRIX_JPEGDEC break; case SEQ_OTHRIX_MIPICSI0: { lpRetIO = (sdi_io*) new sdi_MipiCsiIO(mpGraph, CSI_IDX_0); } // case SEQ_OTHRIX_MIPICSI0/1 break; case SEQ_OTHRIX_MIPICSI1: { lpRetIO = (sdi_io*) new sdi_MipiCsiIO(mpGraph, CSI_IDX_1); } // case SEQ_OTHRIX_MIPICSI0/1 break; case SEQ_OTHRIX_VIU0: { lpRetIO = (sdi_io*) new sdi_ViuIO(mpGraph, VIU_IDX_0); } // case SEQ_OTHRIX_VIU0 break; case SEQ_OTHRIX_VIU1: { lpRetIO = (sdi_io*) new sdi_ViuIO(mpGraph, VIU_IDX_1); } // case SEQ_OTHRIX_VIU1 break; default: { VDB_LOG_ERROR("Unknown IO type index.\n"); } // default break; } // switch IO type index if( lpRetIO == NULL) { VDB_LOG_ERROR("Failed to create IO object with type index %u.\n", aTypeIdx); } // if no IO object created return lpRetIO; } // sdi_process::IOcreate(SEQ_Othr_ix_t aIdx) //**************************************************************************** LIB_RESULT sdi_process::SramBufferGet(const char *acpName, SEQ_Buf_t &arSramBuf) const { LIB_RESULT lRet = LIB_SUCCESS; if(mpGraph != NULL) { lRet = mpGraph->SramBufGet(acpName, arSramBuf); } // if graph set else { lRet = LIB_FAILURE; } // if no graph set return lRet; } // sdi_process::SramBufferGet(SEQ_Othr_ix_t aIoId) /***************************************************************************/ LIB_RESULT sdi_process::CsiSwap(int aEngIdx, int aEngIdxOther, sdi_io *apIOs[]) { LIB_RESULT lRet = mpGraph->CsiSwap(aEngIdx, aEngIdxOther); if(lRet == LIB_SUCCESS) { if(apIOs[aEngIdx] == NULL) { VDB_LOG_NOTE("Delete CSI_%d\n", aEngIdxOther - SEQ_OTHRIX_MIPICSI0); delete apIOs[aEngIdxOther]; apIOs[aEngIdxOther] = NULL; apIOs[aEngIdx] = IOcreate((SEQ_Othr_ix_t) aEngIdx); } // if(apIOs[aEngIdx] == NULL) else if(apIOs[aEngIdxOther] == NULL) { VDB_LOG_NOTE("Delete CSI_%d\n", aEngIdx - SEQ_OTHRIX_MIPICSI0); delete apIOs[aEngIdx]; apIOs[aEngIdx] = NULL; apIOs[aEngIdxOther] = IOcreate((SEQ_Othr_ix_t) aEngIdxOther); } // if(apIOs[aEngIdxOther] == NULL) else { VDB_LOG_NOTE("Recreate all\n"); delete apIOs[aEngIdx]; apIOs[aEngIdx] = IOcreate((SEQ_Othr_ix_t) aEngIdx); delete apIOs[aEngIdxOther]; apIOs[aEngIdxOther] = IOcreate((SEQ_Othr_ix_t) aEngIdxOther); } // else from if(apIOs[aEngIdxOther] == NULL) } // if lRet == LIB_SUCCESS return lRet; } // sdi_process::CsiSwap /***************************************************************************/ LIB_RESULT sdi_process::CsiSwapVc(uint32_t aVcS, uint32_t aVcD, uint32_t aPort) { LIB_RESULT lRet = mpGraph->CsiSwapVc(aVcS, aVcD, aPort); return lRet; } // sdi_process::CsiSwap //**************************************************************************** sdi_process::~sdi_process() { // reset processing setup if(Reset() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reset the sdi_process instance.\n"); } // if Reset failed VDB_LOG_FCN_NOT_IMPLEMENTED(); } // sdi_process::~sdi_process() //**************************************************************************** // *** sdi_grabberContext *** //**************************************************************************** sdi_grabberContext::sdi_grabberContext() : mProcess(NULL), mBufferArr(NULL), mBufCnt(0), mNextBuffIdx(0), mFramesToBeCaptured(1), mFramesCaptured(0), mCallBackParam(NULL), mCallBackFcn(NULL) { } // sdi_grabberContext::sdi_grabberContext() //**************************************************************************** // *** sdi_grabTask *** //**************************************************************************** sdi_grabTask::sdi_grabTask(sdi_grabber *apGrabber) : mpGrabber(apGrabber), mStatus(OFF), mResult(LIB_SUCCESS) { } // sdi_grabTask::sdi_grabTask() //**************************************************************************** sdi_grabTask::~sdi_grabTask() { mpGrabber = NULL; mStatus = OFF; mGC = sdi_grabberContext(); mResult = false; } // sdi_grabTask::~sdi_grabTask() //**************************************************************************** LIB_RESULT sdi_grabTask::TaskPrepare() { #ifndef __STANDALONE__ mResult = LIB_SUCCESS; if (mpGrabber != NULL) { // fetch grabber setup mGC = mpGrabber->mGC; if (mGC.mBufCnt != 0) { // make deep copy of buffer array mGC.mBufferArr = new (std::nothrow) uint8_t*[mGC.mBufCnt]; if (mGC.mBufferArr != NULL) { for (uint32_t i = 0; i < mGC.mBufCnt; ++i) { mGC.mBufferArr[i] = mpGrabber->mGC.mBufferArr[i]; } // for all buffers // check all is ready if ((mGC.mCallBackFcn != NULL) && (mGC.mProcess)) { mStatus = READY; mpGrabber->mGC.mFramesCaptured = 0; // leave index to buffer array as it is !!! // set grabbing state to on //mpGrabber->mGrabbingOn = true; } else { VDB_LOG_ERROR("Grabber not fully initialized.\n"); mResult = LIB_FAILURE; } // if all set prepared } else { VDB_LOG_ERROR("Buffer array could not be allocated. Grabbing will not start.\n"); mResult = LIB_FAILURE; } // else from if buffer array allocated } else { VDB_LOG_ERROR("Buffer array empty. Grabbing will not start.\n"); mResult = LIB_FAILURE; } // else from if buffer not empty } // if mGrabber exists #endif // #ifndef __STANDALONE__ return mResult; } // sdi_grabTask::TaskPrepare() //**************************************************************************** /*void sdi_grabTask::TaskOpen() { VDB_LOG_NOTE("Not needed now.\n"); } // sdi_grabTask::TaskOpen()*/ LIB_RESULT sdi_grabTask::AllDone(bool &arDone) { LIB_RESULT lRet = LIB_SUCCESS; #ifndef __STANDALONE__ // check grabbed cnt if (OAL_SemaphoreObtain(mpGrabber->mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex obtain failed.\n"); mResult = LIB_FAILURE; } // if mutex obtain failed else { if ((mGC.mFramesToBeCaptured > 0) && (mGC.mFramesCaptured >= mGC.mFramesToBeCaptured)) { arDone = true; } // if all frames captured else { arDone = false; } if (OAL_SemaphoreRelease(mpGrabber->mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex release failed.\n"); mResult = LIB_FAILURE; } // if semaphore release failed }// else from if mutex obtain failed #endif // #ifndef __STANDALONE__ return lRet; }// bool sdi_grabTask::AllDone(LIB_RESULT &lRet) //**************************************************************************** void sdi_grabTask::TaskService() { #ifndef __STANDALONE__ // test phase todo: remove sleep(1); VDB_LOG_NOTE("This is the grabber task service.\n"); sleep(1); // grab loop control variable bool run = false; bool done = false; if (OAL_SemaphoreObtain(mpGrabber->mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex obtain failed.\n"); mResult = LIB_FAILURE; } // if mutex obatin failed else { if(mStatus == READY) { mStatus = ON; run = true; } // if task is ready else { VDB_LOG_ERROR("Grabber task in not ready to execute."); mResult = LIB_FAILURE; } // else from if taks is ready if (OAL_SemaphoreRelease(mpGrabber->mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex release failed.\n"); mResult = LIB_FAILURE; } // if semaphore release failed }// else from if mutex obtain failed while (run) { // image grabbing sequence if(AllDone(done) != LIB_SUCCESS) { VDB_LOG_ERROR("Check for AllDone failed."); mResult = LIB_FAILURE; } // if AllDone() failed else { if(done) { run = false; break; } // if all frames have been captured //////// // // todo: do the image grabbing here // //////// // execute call-back function mGC.mCallBackFcn(mGC.mCallBackParam); // update grabber context ++mGC.mFramesCaptured; mGC.mNextBuffIdx = (mGC.mNextBuffIdx + 1) % mGC.mBufCnt; } // else from if AllDone() failed } // while(run) #endif // #ifndef __STANDALONE__ } // sdi_grabTask::TaskService() //**************************************************************************** void sdi_grabTask::TaskClose() { #ifndef __STANDALONE__ if (OAL_SemaphoreObtain(mpGrabber->mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex obtain failed.\n"); } // if mutex obtain failed else { // set grabbing state to off mStatus = OFF; // update frame counter and buffer index mpGrabber->mGC.mFramesCaptured += mGC.mFramesCaptured; mpGrabber->mGC.mNextBuffIdx += mGC.mNextBuffIdx; if (OAL_SemaphoreRelease(mpGrabber->mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex release failed.\n"); } // if semaphore release failed } // else from semaphore obtain failed // clean up if (mGC.mBufferArr != NULL) { delete[] (mGC.mBufferArr); } // mBufferArr not NULL #endif // #ifndef __STANDALONE__ } // sdi_grabTask::TaskClose() //**************************************************************************** // *** sdi_grabber *** //**************************************************************************** sdi_grabber::sdi_grabber() : modified(false),mGrabbingResult(LIB_SUCCESS), mGC(), mGrabTask(this) { mpSeqEventCb = NULL; mpCsiEventCb = NULL; mName = (int8_t*) ("grabtask"); mStatus = OFF; for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { mpIOs[i] = NULL; } // for all possible IO objects if (OAL_SemaphoreCreate(&mThreadMutex, "GrabberMutex", OAL_SEMAPHORE_MUTEX, 1) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex creation failed.\n"); mThreadMutex = NULL; } // if SemaphoreCreate failed } // sdi_grabber::sdi_grabber() //**************************************************************************** sdi_grabber::~sdi_grabber() { // *** clean up IO objects *** for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] != NULL) { delete(mpIOs[i]); } // if exists } // for all possible IO objects } // sdi_grabber::~sdi_grabber() //**************************************************************************** LIB_RESULT sdi_grabber::ProcessSet ( SEQ_Head_Ptr_t *apGraph, GraphMetadata_t *apGraphMetadata, const char* acpKmemSrec, const char* acpSequencerSrec ) { LIB_RESULT lRet = LIB_SUCCESS; if ((apGraph != NULL) && (apGraphMetadata != NULL)) { if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if semaphore not obtained else { if(mProcess.Set( apGraph, apGraphMetadata, acpKmemSrec, acpSequencerSrec ) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to setup a process.\n"); lRet = LIB_FAILURE; } // if setting a graph to process failed else { // remove all previous IO objects for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] != NULL) { delete(mpIOs[i]); mpIOs[i] = NULL; } // if IO set } // for all possible IO objects // get new IO grabber objects if(mProcess.IOsGet(mpIOs) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to get the IO objects from process.\n"); lRet = LIB_FAILURE; } // if IOsGet() failed } // else from if setting a graph to process failed if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if semaphore not obtained }// else from atribute pointers != NULL else { VDB_LOG_ERROR("NULL pointer given instead of valid sdi_process object.\n"); lRet = LIB_FAILURE; } // else from if attribute pointers != NULL return lRet; } // sdi_grabber::ProcessSet(SEQ_Head_t *apGraph[]) //**************************************************************************** SEQ_Buf_t** sdi_grabber::GraphFetch(SEQ_Head_Ptr_t** appGraph) { return mProcess.GraphFetch(appGraph); } // sdi_grabber::GraphFetch(SEQ_Head_Ptr_t** appGraph) //**************************************************************************** sdi_io* sdi_grabber::IoGet(SEQ_Othr_ix_t aIoId) const { sdi_io *lpRet = NULL; if(aIoId < SEQ_OTHRIX_LAST) { lpRet = mpIOs[aIoId]; } return lpRet; } // sdi_grabber::IoGet(SEQ_Othr_ix_t aIoId) //**************************************************************************** LIB_RESULT sdi_grabber::SramBufferGet(const char *acpName, SEQ_Buf_t &arSramBuf) const { return mProcess.SramBufferGet(acpName, arSramBuf); } // sdi_grabber::SramBufferGet() //**************************************************************************** LIB_RESULT sdi_grabber::FrameReadyCallBackInstall( void (*apFrameReadyCallBack)(void*), void* apFrameReadyCallBackParam) { LIB_RESULT lRet = LIB_SUCCESS; if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } else { if (apFrameReadyCallBack != NULL) { mGC.mCallBackFcn = apFrameReadyCallBack; mGC.mCallBackParam = apFrameReadyCallBackParam; } else { VDB_LOG_ERROR("CallBack function specified as NULL pointer.\n"); lRet = LIB_FAILURE; } // else from if callback fcn != NULL if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if semaphore obtain failed return lRet; } // FrameReadyCallBackInstall //**************************************************************************** LIB_RESULT sdi_grabber::SeqEventCallBackInstall( void (*apSeqEventCallBack)(uint32_t, void*), void* apSeqEventCallBackParam) { LIB_RESULT lRet = LIB_SUCCESS; if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } else { if (apSeqEventCallBack != NULL) { mpSeqEventCb = apSeqEventCallBack; mpSeqEventCbParam = apSeqEventCallBackParam; } else { VDB_LOG_ERROR("CallBack function specified as NULL pointer.\n"); lRet = LIB_FAILURE; } // else from if callback fcn != NULL if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if semaphore obtain failed return lRet; } // SeqEventCallBackInstall LIB_RESULT sdi_grabber::CsiEventCallBackInstall( void (*apCsiEventCallBack)(uint32_t, void*), void* apCsiEventCallBackParam) { LIB_RESULT lRet = LIB_SUCCESS; // TODO: check if graph has csi node if (!this->HasCsi()) { VDB_LOG_ERROR("There's no CSI node in graph.\n"); lRet = LIB_FAILURE; } else if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } else { if (apCsiEventCallBack != NULL) { mpCsiEventCb = apCsiEventCallBack; mpCsiEventCbParam = apCsiEventCallBackParam; } else { VDB_LOG_ERROR("CallBack function specified as NULL pointer.\n"); lRet = LIB_FAILURE; } // else from if callback fcn != NULL if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if semaphore obtain failed return lRet; } // CsiEventCallBackInstall //**************************************************************************** LIB_RESULT sdi_grabber::PreStart() { LIB_RESULT lRet = LIB_SUCCESS; // lock the grabber if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreObtain failed else { if(mStatus == OFF) { #ifdef __STANDALONE__ IspHwSramAccesAllow(); #endif // #ifdef __STANDALONE__ // *** reserve Sequencer access *** if(SEQ_Reserve() == SEQ_LIB_SUCCESS) { // set this grabber as current Sequencer event handler if(SEQ_EventHandlerSet((SEQ_EventHandlerClass*)this) == SEQ_LIB_SUCCESS) { // *** reserve IO objects *** if( IOsReserve() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reserve IO objects.\n"); lRet = LIB_FAILURE; } // if IOsReserve() failed else { // *** process finalize *** // allocates SRAM buffers & reserves TCs if(mProcess.Finalize() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to finalize process.\n"); lRet = LIB_FAILURE; } // if Process::Finalize() failed else { // *** apply IO objects parameters *** if(IOsSetup() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to setup IO objects.\n"); lRet = LIB_FAILURE; } // if IOsSetup() failed else { // *** download the Graph *** if(mProcess.Download() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to Download the process.\n"); lRet = LIB_FAILURE; } // if download failed else { // *** boot the Sequencer FW *** if(SEQ_Reset() != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reset sequencer.\n"); lRet = LIB_FAILURE; } // if seq reset failed else { if(SEQ_Boot() != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Failed to boot sequencer.\n"); lRet = LIB_FAILURE; } // if seq boot failed else { // set to ready status mStatus = READY; } // else from if seq boot failed } // else from if seq reser failed } // else from if download failed } // else from if IOsSetup() failed // release IOs if(lRet != LIB_SUCCESS) { if(IOsRelease() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reserve IO objects.\n"); lRet = LIB_FAILURE; } // if IOsRelease() } // if failure detected } // else from if Process::Finalize() failed if(lRet != LIB_SUCCESS) { // revert the Finalize action mProcess.Free(); } } // else from if IOsReserve() failed if(lRet != LIB_SUCCESS) { // attempt to reset the event handler if(SEQ_EventHandlerSet((SEQ_EventHandlerClass*)NULL) != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reset Sequencer event handler.\n"); lRet = LIB_FAILURE; } // if failed to reset event handler } } // if set handler ok else { VDB_LOG_ERROR("Failed to setup Sequencer event handler.\n"); lRet = LIB_FAILURE; } // else from if set handler ok if(lRet != LIB_SUCCESS) { // attempt to release the sequencer (void)SEQ_Release(); } } // if seq reserved ok else { VDB_LOG_ERROR("Sequencer reservation failed.\n"); lRet = LIB_FAILURE; } // else from if seq reserved ok } // if SRAM_PRO2HOST_OFF else { VDB_LOG_ERROR("Grabber is not OFF.\n"); lRet = LIB_FAILURE; } // else from if OFF // release the lock if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore release failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if Semaphore obtain failed return lRet; } // sdi_grabber::PreStart() //**************************************************************************** LIB_RESULT sdi_grabber::Release() { LIB_RESULT lRet = LIB_SUCCESS; // lock the grabber if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreObtain failed else { if(mStatus == READY) { // release IO objects if(IOsRelease() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to release IO objects.\n"); lRet = LIB_FAILURE; } // if IOsRelease() // revert the Finalize action mProcess.Free(); // attempt to reset the event handler if(SEQ_EventHandlerSet((SEQ_EventHandlerClass*)NULL) != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reset Sequencer event handler.\n"); lRet = LIB_FAILURE; } // if failed to reset event handler // reset the driver and ISP HW if(SEQ_Reset() != SEQ_LIB_SUCCESS) { lRet = LIB_FAILURE; } // if failed to reset // release Sequencer HW if(SEQ_Release() != SEQ_LIB_SUCCESS) { lRet = LIB_FAILURE; } // if failed to reset mStatus = OFF; } // if READY else { if(mStatus == ON) { VDB_LOG_ERROR("Failed to release. Sequencer still running.\n"); lRet = LIB_FAILURE; } // if still on } // else from if READY // release the lock if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore release failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if Semaphore obtain failed return lRet; } // sdi_grabber::PreStart(uint32_t) //**************************************************************************** LIB_RESULT sdi_grabber::Start(uint32_t aFrameCnt, uint32_t aInputLines) { LIB_RESULT lRet = LIB_SUCCESS; //TODO: remove unused parameter suppression UNUSED(aFrameCnt); // lock the grabber if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreObtain failed else { if(mStatus == READY) { mStatus = ON; // *** start up the graph *** if(SEQ_GraphStart(aFrameCnt, aInputLines) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to start the grabbing sequence.\n"); lRet = LIB_FAILURE; mStatus = READY; } // if Start failed else { // start IO objects if(IOsStart() != LIB_SUCCESS) { (void)SEQ_GraphStop(1); VDB_LOG_ERROR("Failed to start IO objects.\n"); lRet = LIB_FAILURE; mStatus = READY; } // if IOsStart() } } // if READY else { VDB_LOG_ERROR("Sequencer not READY.\n"); lRet = LIB_FAILURE; } // else from if READY // release the lock if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore release failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if Semaphore obtain failed return lRet; } // sdi_grabber::Start(uint32_t) //**************************************************************************** LIB_RESULT sdi_grabber::Stop(uint32_t) { LIB_RESULT lRet = LIB_SUCCESS; // lock the grabber if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreObtain failed else { if(mStatus == ON) { if(SEQ_GraphStop(1) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to stop the grabbing sequence.\n"); lRet = LIB_FAILURE; } // if Start failed { // start IO objects if(IOsStop() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to stop IO objects.\n"); lRet = LIB_FAILURE; mStatus = READY; } // if IOsStop() // *** reset the driver and ISP HW *** if(SEQ_Reset() != SEQ_LIB_SUCCESS) { lRet = LIB_FAILURE; } // if failed to reset mStatus = READY; } // else from if Start failed } // if ON else { VDB_LOG_WARNING("Sequencer not ON.\n"); } // else from if READY // release the lock if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore release failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if Semaphore obtain failed /*if (OAL_SemaphoreObtain(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } else { if( mGrabTask.mStatus == sdi_grabTask::ON) { // add requested frames to be captured then end grabbing mGrabTask.mGC.mFramesToBeCaptured = mGrabTask.mGC.mFramesCaptured + aFrameCnt; if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore obtain failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // if already running else { VDB_LOG_WARNING("Grabber is not running."); if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber semaphore release failed.\n"); lRet = LIB_FAILURE; } // if mutex release failed } // else from if not running now } // else from if semaphore obtain failed*/ return lRet; } // sdi_grabber::Stop(uint32_t) LIB_RESULT sdi_grabber::Restart(uint32_t) { LIB_RESULT lRet = LIB_SUCCESS; if(IOsStop() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to stop IOs.\n"); lRet = LIB_FAILURE; } // if grabber stop failed if(SEQ_Reset() != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reset sequencer.\n"); lRet = LIB_FAILURE; } // if failed to reset mStatus = READY; if (lRet != LIB_FAILURE) { if(IOsSetup() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to set up IOs.\n"); lRet = LIB_FAILURE; } // if setup IOs fail else { if(SEQ_Boot() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to boot sequencer.\n"); lRet = LIB_FAILURE; } // if boot sequencer fail else { if(Start() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to start the grabber.\n"); lRet = LIB_FAILURE; } // if grabber start failed } } } return lRet; } // sdi_grabber::Restart(uint32_t) //*************************************************************************** SDI_Frame sdi_grabber::FramePop(uint32_t aChnlIdx, uint32_t aTimeoutMs) { SDI_Frame lRet; LIB_RESULT lRes = LIB_SUCCESS; // by default sleep for 1s #ifndef __STANDALONE__ struct timespec lTimeToSleep = {aTimeoutMs/1000, (aTimeoutMs%1000)*1000000}; #else // #ifndef __STANDALONE__ uint64_t lTimeValStart; lTimeValStart = get_uptime_microS(); #endif // else from #ifndef __STANDALONE__ SEQ_FrmBufferInfo_t lBufferInfo; lBufferInfo.mStreamIdx = aChnlIdx; // try to pop new frame while(SEQ_FrmBufferPop(&lBufferInfo) != SEQ_LIB_SUCCESS) { if(aTimeoutMs > 0) { uint64_t lTimeSpent; #ifndef __STANDALONE__ lTimeSpent = aTimeoutMs - \ lTimeToSleep.tv_sec * 1000 - \ lTimeToSleep.tv_nsec / 1000000; #else // #ifndef __STANDALONE__ lTimeSpent = (get_uptime_microS() - lTimeValStart) / 1000; #endif // else from #ifndef __STANDALONE__ if(aTimeoutMs <= lTimeSpent) { lRes = LIB_FAILURE; VDB_LOG_ERROR("Frame wait timed out\n"); break; } // if timed-out } // if timeout required #ifndef __STANDALONE__ if(nanosleep(&lTimeToSleep, &lTimeToSleep) == 0) { lRes = LIB_FAILURE; break; } // if whole sleep ended uninterrupted #endif // else from #ifndef __STANDALONE__ } // while FrmBufferPop() failed if(lRes == LIB_SUCCESS) { ((sdi_FdmaIO*)mpIOs[SEQ_OTHRIX_FDMA])->DdrBufferQuery( aChnlIdx, lBufferInfo.mBufferIdx, lRet.mUMat); lRet.mChannelIdx = aChnlIdx; lRet.mBufferIdx = lBufferInfo.mBufferIdx; lRet.mFrmSeqNum = lBufferInfo.mFrmSeqNum; lRet.mCheckFrmErrs = lBufferInfo.mCheckFrmErrs; } // if did not fail return lRet; } // FramePop(uint32_t aChnlIdx, uint32_t aTimeoutMs) //*************************************************************************** SDI_Frame sdi_grabber::FramePopNonBlock(uint32_t aChnlIdx) { SDI_Frame lRet; SEQ_FrmBufferInfo_t lBufferInfo; lBufferInfo.mStreamIdx = aChnlIdx; // try to pop new frame if(SEQ_FrmBufferPop(&lBufferInfo) == SEQ_LIB_SUCCESS) { ((sdi_FdmaIO*)mpIOs[SEQ_OTHRIX_FDMA])->DdrBufferQuery(aChnlIdx, lBufferInfo.mBufferIdx, lRet.mUMat); lRet.mChannelIdx = aChnlIdx; lRet.mBufferIdx = lBufferInfo.mBufferIdx; } // if pop succeeded return lRet; } // FramePop(uint32_t aChnlIdx) //*************************************************************************** LIB_RESULT sdi_grabber::FramePush(SDI_Frame &arFrame) { LIB_RESULT lRet = LIB_SUCCESS; SEQ_FrmBufferInfo_t lBufferInfo; lBufferInfo.mStreamIdx = arFrame.mChannelIdx; lBufferInfo.mBufferIdx = arFrame.mBufferIdx; if(SEQ_FrmBufferPush(&lBufferInfo) != LIB_SUCCESS) { lRet = LIB_FAILURE; } // if frame push failed return lRet; } // FramePush(SDI_Frame &arFrame) //**************************************************************************** bool sdi_grabber::IsLive() { bool live = false; if (mThreadMutex != NULL) { if (OAL_SemaphoreObtain(mThreadMutex, scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex obtain failed.\n"); } else { live = mGrabTask.mStatus == sdi_grabTask::ON ? true: false; if (OAL_SemaphoreRelease(mThreadMutex) != LIB_SUCCESS) { VDB_LOG_ERROR("Grabber mutex release failed.\n"); } // if thread mutex release failed } // else from if thread mutex obtain failed } // if thread mutex initialized return live; } // sdi_grabber::IsLive() //**************************************************************************** LIB_RESULT sdi_grabber::IOsRelease() { LIB_RESULT lRet = LIB_SUCCESS; // release all prior reserved IOs for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] == NULL) { continue; } // if no IO if(mpIOs[i]->Release() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to release IO object %u.\n", i); lRet = LIB_FAILURE; } // if Release() failed if (this->HasCsi()) { if(CSI_EventHandlerSet((CSI_EventHandlerClass*)NULL) != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Fail to reset CSI event handler: %d", i - SEQ_OTHRIX_MIPICSI0); } } } // for all possible IOs return lRet; } // sdi_grabber::IOsRelease() //**************************************************************************** LIB_RESULT sdi_grabber::IOsReserve() { LIB_RESULT lRet = LIB_SUCCESS; for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] == NULL) { continue; } // if no IO if(mpIOs[i]->Reserve() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to reserve IO object %u.\n", i); lRet = LIB_FAILURE; // release all prior reserved IOs if(IOsRelease() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to release so far allocated IOs.\n"); } // if IOsRelease() failed break; } // if Reserve() failed } // for all IO objects return lRet; } // sdi_grabber::IOsReserve() //**************************************************************************** LIB_RESULT sdi_grabber::IOsSetup() { LIB_RESULT lRet = LIB_SUCCESS; for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] == NULL) { continue; } // if no IO if(mpIOs[i]->Setup() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to setup IO object %u.\n", i); lRet = LIB_FAILURE; break; } // if Setup() failed if (HasCsi()) { if(CSI_EventHandlerSet((CSI_EventHandlerClass*)this) != SEQ_LIB_SUCCESS) { VDB_LOG_ERROR("Fail to resgister CSI event handler: %d", i - SEQ_OTHRIX_MIPICSI0); } } } // for all IO objects return lRet; } // sdi_grabber::IOsSetup() //**************************************************************************** LIB_RESULT sdi_grabber::IOsStart() { LIB_RESULT lRet = LIB_SUCCESS; for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] == NULL) { continue; } // if no IO if(mpIOs[i]->Start() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to start IO object %u.\n", i); lRet = LIB_FAILURE; break; } // if Start() failed } // for all IO objects return lRet; } // sdi_grabber::IOsStart() //**************************************************************************** LIB_RESULT sdi_grabber::IOsStop() { LIB_RESULT lRet = LIB_SUCCESS; for(uint32_t i = 0; i < SEQ_OTHRIX_LAST; i++) { if(mpIOs[i] == NULL) { continue; } // if no IO if(mpIOs[i]->Stop() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to stop IO object %u.\n", i); lRet = LIB_FAILURE; break; } // if Stop() failed } // for all IO objects return lRet; } // sdi_grabber::IOsStop() //**************************************************************************** void sdi_grabber::SeqEventHandler(uint32_t aEventType) { VDB_LOG_NOTE("Grabber got Sequencer event number %u.\n", aEventType); if(mGC.mCallBackFcn != NULL) { mGC.mCallBackFcn(mGC.mCallBackParam); } // if callback set if(mpSeqEventCb != NULL) { mpSeqEventCb(aEventType, mpSeqEventCbParam); } // if Sequencer event callback installed if(aEventType == SEQ_MSG_TYPE_RAB) { VDB_LOG_NOTE("Sequencer Ready-after-boot message reached user application."); } if(aEventType == SEQ_MSG_TYPE_FRAMEDONE) { VDB_LOG_NOTE("Frame done.\n"); } // if FRAMEDONE if(aEventType == SEQ_MSG_TYPE_SEQDONE) { VDB_LOG_NOTE("Grabber status set to ready %u %u.\n", mStatus); mStatus = READY; } if(aEventType == SEQ_MSG_TYPE_OTHERERROR) { char lString[SEQ_PRAM_AUX_DATA_SIZE] = {0}; VDB_LOG_ERROR("*** Other error message received.\n"); VDB_LOG_ERROR("*** Sequencer error text:\n"); if(SEQ_MsgAuxDataGet(lString, SEQ_PRAM_AUX_DATA_SIZE) != SEQ_LIB_SUCCESS) { VDB_LOG_NOTE("Failed to get the auxiliary data from PRAM.\n"); } // if failed to read the error message else { VDB_LOG_ERROR(" %s\n", lString); } // else from if failed to read the error message } // if SEQ_MSG_TYPE_OTHERERROR } // EventHandler(uint32_t aEventType) LIB_RESULT sdi_grabber::CsiSwap(int aEngIdx, int aEngIdxOther) { LIB_RESULT lRet = LIB_SUCCESS; if(mStatus != OFF) { VDB_LOG_ERROR("Must call this function right after ProcessSet only.\n"); lRet = LIB_FAILURE; } // if state is not OFF else if((mpIOs[aEngIdx] == NULL) && (mpIOs[aEngIdxOther] == NULL)) { VDB_LOG_ERROR("One of 2 CSI port must be available.\n"); lRet = LIB_FAILURE; } // if both csi port is not available else { lRet = mProcess.CsiSwap(aEngIdx, aEngIdxOther, mpIOs); } // else from if both csi port is not available return lRet; } // sdi_grabber::CsiSwap LIB_RESULT sdi_grabber::CsiSwapVc(uint32_t aVcS, uint32_t aVcD, uint32_t aPort) { LIB_RESULT lRet = LIB_SUCCESS; if(mStatus != OFF) { VDB_LOG_ERROR("Must call this function right after ProcessSet only.\n"); lRet = LIB_FAILURE; } // if state is not OFF else if((aVcS >= 4)||(aVcD >= 4)) { VDB_LOG_ERROR("The VCs must be in range 0 - 3.\n"); lRet = LIB_FAILURE; } // if both csi port is not available else { lRet = mProcess.CsiSwapVc(aVcS, aVcD, aPort); } // else from if both csi port is not available return lRet; } // sdi_grabber::CsiSwap void sdi_grabber::CsiEventHandler(uint32_t aEventType) { VDB_LOG_NOTE("Grabber got Csi event number %u.\n", aEventType); if(mpCsiEventCb != NULL) { mpCsiEventCb(aEventType, mpCsiEventCbParam); } // if Csi event callback installed if ((aEventType & (CSI_IDX_0_PP_PHY_ERR || CSI_IDX_1_PP_PHY_ERR || CSI_IDX_0_LINE_CNT_ERR || CSI_IDX_1_LINE_CNT_ERR)) > 0) { this->Restart(); } } // CsiEventHandler(uint32_t aEventType) bool sdi_grabber::HasCsi(void) { return ((mpIOs[SEQ_OTHRIX_MIPICSI0] != NULL) || (mpIOs[SEQ_OTHRIX_MIPICSI1] != NULL)); } LIB_RESULT sdi_grabber::Roi(uint32_t aChnlIdx, uint32_t aBuffIn, uint32_t aBuffInChl, uint32_t aBuffOut, uint32_t aY, uint32_t aH) { LIB_RESULT lRet = LIB_SUCCESS; SEQ_RegList_t lRegList; SEQM_ipu_reg_t lpRegVal[3]; /*Change Line Start for FDMA*/ lpRegVal[0].mEngBase = (uint32_t)(uintptr_t)0;/*FDMA always is first in gpGraph*/ lpRegVal[0].mIndex = aChnlIdx; lpRegVal[0].mData = aY; lpRegVal[0].mType = SEQ_REG_FDMA_START; /*Change Line max of buffer*/ lpRegVal[1].mEngBase = (uint32_t)(uintptr_t)aBuffOut; lpRegVal[1].mIndex = 0; lpRegVal[1].mData = aH; lpRegVal[1].mType = SEQ_REG_BUFF_MAX; /*Change Line Skip for consumer0 of buffer*/ lpRegVal[2].mEngBase = (uint32_t)(uintptr_t)aBuffIn; lpRegVal[2].mIndex = aBuffInChl; lpRegVal[2].mData = aY; lpRegVal[2].mType = SEQ_REG_BUFF_LINE_SKIP; lRegList.mCnt = 3; lRegList.mDirection = IPU_REGLIST_WRITE; lRegList.mpData = lpRegVal; /*Set Register List in WRITE mode*/ SEQ_RegListSet(&lRegList); } //**************************************************************************** // *** sdi *** LIB_RESULT sdi::InitFirst() { LIB_RESULT lRet = LIB_SUCCESS; #ifndef __STANDALONE__ uint32_t sensor_cnt = 0; // when creating shm, there's no one to access the HW at the same time // this should be safe if( SensorCntGet(sensor_cnt) != LIB_SUCCESS) { VDB_LOG_ERROR("Query for available sensor count failed.\n"); lRet = LIB_FAILURE; // some failure = NOK }else { if(ShmConnect(sensor_cnt) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to connect shared memory variables.\n"); mShm = NULL; lRet = LIB_FAILURE; }else { // set shared variables to initial values *mpInitCounter = 1; *mpSensorCnt = sensor_cnt; mNextProcessId = 1; mThreadCounter = 1; // set all prepared process pointers to NULL //for (uint32_t i = 0; i < mProcesses.size(); ++i) //{ // mProcesses[i] = NULL; //} // for all processes if( HwInit() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to initialize HW.\n"); lRet = LIB_FAILURE; }else { if( OAL_SemaphoreRelease(mInitSemaphore) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to release init semaphore.\n"); lRet = LIB_FAILURE; }else { VDB_LOG_NOTE("First process & thread initialized successfully.\n"); } // else from if SemaphoreRelease() failed if(lRet == LIB_FAILURE) { if(HwClose() != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to close HW.\n"); }// if HwClose() failed mNextProcessId = 0; mThreadCounter = 0; } }// else from if HwInit() failed if( lRet == LIB_FAILURE) { if( ShmDisconnect(true) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to disconnect shared memory.\n"); } // if ShmDisconnect() failed } // if LIB_FAILURE } // else from if ShmConnect() failed } // else from if SensorCntGet() failed #endif // #ifndef __STANDALONE__ return lRet; } // sdi::InitFirst() //**************************************************************************** LIB_RESULT sdi::InitSubseq(bool arRepeat) { LIB_RESULT lRet = LIB_SUCCESS; #ifndef __STANDALONE__ if(ShmConnect(arRepeat) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to connect shared memory variables.\n"); mShm = NULL; lRet = LIB_FAILURE; }else { // check if another client allowed if((*mpInitCounter) > SDI_MAX_CLIENT_NUM) { VDB_LOG_ERROR("Maximum number of SDI clients reached already. Nothing done.\n"); lRet = LIB_FAILURE; }else{ ++(*mpInitCounter); mNextProcessId = 1; mThreadCounter = 1; // set all prepared process pointers to NULL //for (uint32_t i = 0; i < mProcesses.size(); ++i) //{ // mProcesses[i] = NULL; //} // for all processes if( OAL_SemaphoreRelease(mInitSemaphore) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to release init semaphore.\n"); --(*mpInitCounter); mNextProcessId = 0; mThreadCounter = 0; lRet = LIB_FAILURE; }else { VDB_LOG_NOTE("First thread in consecutive process initialized successfully.\n"); } // else from if SemaphoreRelease() failed } if( lRet == LIB_FAILURE) { if( ShmDisconnect(false) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to disconnect shared memory.\n"); } // if ShmDisconnect() failed } // if LIB_FAILURE } // else from if ShmConnect() failed #endif // #ifndef __STANDALONE__ return lRet; } // sdi::InitSubseq() //**************************************************************************** LIB_RESULT sdi::Initialize(uint32_t /*aTaskNum*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE // process/thread safety under development OAL_SEMAPHORE initSem = NULL; bool firstProcess = false; bool init_obtained = false; //TODO: remove unused parameter suppression UNUSED(aTaskNum); while(1) { // synchronize with init semaphore lRet = InitSemSynchronize(&initSem,&firstProcess, &init_obtained); // continue only if all ok so far if (lRet == LIB_SUCCESS) { // now init semaphore has been created/opened and obtained if(firstProcess) { // remember init semaphore mInitSemaphore = initSem; if( InitFirst() != LIB_SUCCESS) { VDB_LOG_ERROR("First process calling SDI initialization failed.\n"); mInitSemaphore = NULL; if(OAL_SemaphoreOwnershipSet(initSem, true) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore ownership set failed.\n"); } // SemaphoreOwnershipSet() failed if(OAL_SemaphoreDelete(initSem) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore delete failed.\n"); } // if init semaphore delete failed lRet = LIB_FAILURE; } // if InitFirst() Failed }else { //check if SDI initialized for this process already if( mInitSemaphore == NULL ) { // sdi has not been initialized for this process yet mInitSemaphore = initSem; bool repeat = false; if( InitSubseq(repeat) != LIB_SUCCESS) { VDB_LOG_ERROR("Subsequent call to SDI initialization failed. SDI probably de-initialized in between.\n"); if(OAL_SemaphoreRelease(initSem) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore release failed.\n"); lRet = LIB_FAILURE; } // if init semaphore release failed if(OAL_SemaphoreDelete(initSem) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore delete failed.\n"); lRet = LIB_FAILURE; } // if init semaphore delete failed mInitSemaphore = NULL; if(lRet == LIB_SUCCESS && repeat) { continue; } // if no other problem } // if InitSubseq() failed }else { bool max_reached = false; if((*mpInitCounter) >= SDI_MAX_CLIENT_NUM) { VDB_LOG_ERROR("Maximum number of SDI clients reached already. Nothing done.\n"); max_reached = true; lRet = LIB_FAILURE; }else { // increase counters ++(*mpInitCounter); ++mThreadCounter; } // else from if SDI_MAX_CLIENT_NUM reached // release SDI init semaphore if( OAL_SemaphoreRelease(initSem) != LIB_SUCCESS) { VDB_LOG_ERROR("Failed to release init semaphore.\n"); lRet = LIB_FAILURE; }else { /*if( OAL_SemaphoreDelete(initSem) != LIB_SUCCESS ) { VDB_LOG_ERROR("Failed to delete local init semaphore.\n"); lRet = LIB_FAILURE; } // if SemaphoreDelete() failed */ } // else from if SemaphoreRelease() failed if(lRet == LIB_FAILURE) { if(!max_reached) { --(*mpInitCounter); --mThreadCounter; } // if max_reached }else { VDB_LOG_NOTE("Ordinary thread initialized successfully.\n"); }// if LIB_FAILURE } // if all ok so far } // else from if first process } // if all ok so far break; } // repeat in case of SDI closed in between VDB_LOG_NOTE("%u Returning from INIT: overall cnt %u thread cnt %u\n", 0,0,0);//aTaskNum, *mpInitCounter, mThreadCounter); #endif // if 0 return lRet; } // Initialize() //**************************************************************************** LIB_RESULT sdi::InitSemSynchronize(OAL_SEMAPHORE */*apInitSem*/, bool */*apFirstProcess*/, bool */*apSemObtained*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE // process/thread safety under development *apFirstProcess = false; *apSemObtained = false; while (1) { lRet = OAL_SemaphoreCreate(apInitSem, scpSemInitName, OAL_SEMAPHORE_COUNTING, 0); if (lRet != LIB_SUCCESS) { if (lRet == LIB_FAILURE) { // semaphore probably exists - server is running already // open existing server semaphore lRet = OAL_SemaphoreGetByName(apInitSem, scpSemInitName); // check again if (lRet != LIB_SUCCESS) { if (lRet == OAL_ERR_SEM_EBADSEM) { // server probably ended in between try repeat sem_open O_CREAT VDB_LOG_WARNING("Sdi probably closed during client init. Repeating init procedure."); continue; } VDB_LOG_ERROR("Init semaphore get by name failed. Returning.\n"); lRet = LIB_FAILURE; *apInitSem = NULL; break; // leave the loop }else { LIB_RESULT tmpLres; // try to obtain init semaphore tmpLres = OAL_SemaphoreObtain(*apInitSem, scSemWaitMax); if( tmpLres != LIB_SUCCESS) { if( tmpLres == OAL_ERR_SEM_EBADSEM) { // server probably ended in between try repeat sem_open O_CREAT VDB_LOG_WARNING("Sdi probably closed during client init. Repeating init procedure."); continue; }else if( tmpLres == OAL_ERR_SEM_ETIMEOUT) { VDB_LOG_ERROR("Init semaphore obtain timedout. Returning.\n"); lRet = LIB_FAILURE; }else { VDB_LOG_ERROR("Init semaphore obtain failed. Returning.\n"); lRet = LIB_FAILURE; }// else from if sdi closed in between if(OAL_SemaphoreDelete(*apInitSem) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore delete failed. Returning.\n"); } *apInitSem = NULL; // break loop to return with previously set LIB_FAILURE break; }else { VDB_LOG_NOTE("Init semaphore opened and locked.\n"); *apSemObtained = true; break; } // if SemaphoreTimedWait failed }// if != LIB_SUCCESS } else { VDB_LOG_ERROR("Init semaphore open failed. Returning.\n"); lRet = LIB_FAILURE; // some failure = NOK break; // leave the loop } // else LIB_FAILURE } else { // this is first call to library - setup shared memmory *apFirstProcess = true; *apSemObtained = true; if( OAL_SemaphoreOwnershipSet(*apInitSem, false) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore ownership set failed.\n"); lRet = LIB_FAILURE; } // if Shared memory ownership set failed break; } // else SEM_FAILED } // while(1) #endif return lRet; } // sdi::InitSemSynchronize() //**************************************************************************** LIB_RESULT sdi::Close(uint32_t /*aTaskNum*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE // process/thread safety under development printf("SDI CLOSE %u\n", aTaskNum); VDB_LOG_NOTE("Sdi CLOSE here.\n"); // obtain Init semaphore if (OAL_SemaphoreObtain(mInitSemaphore,scSemWaitMax) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi init semaphore obtain failed.\n"); lRet = LIB_FAILURE; } else { VDB_LOG_NOTE("%u Close: overall cnt %u thread cnt %u\n", aTaskNum, *mpInitCounter, mThreadCounter); if(mpInitCounter != NULL) { if ((*mpInitCounter) > 0) { if(mThreadCounter == 1) { VDB_LOG_NOTE("%u Close: Last thread => destroy local sdi.\n",aTaskNum); if ((*mpInitCounter) == 1) { // this is the last sdi client overall if(OAL_SemaphoreOwnershipSet(mSdiMut,true) != LIB_SUCCESS) { VDB_LOG_ERROR("SDI mutex ownership set failed.\n"); lRet = LIB_FAILURE; } // if mutex ownership set failed if(OAL_SemaphoreOwnershipSet(mInitSemaphore,true) != LIB_SUCCESS) { VDB_LOG_ERROR("Init semaphore ownership set failed.\n"); lRet = LIB_FAILURE; } // if init semaphore ownership set failed if(OAL_SharedMemoryOwnershipSet(mShm,true) != LIB_SUCCESS) { VDB_LOG_ERROR("Shared memory ownership set failed.\n"); lRet = LIB_FAILURE; } // if shared memory ownership set failed VDB_LOG_NOTE("Close: Last process => destroy everything.\n"); // TODO: fix the two closes HwFdClose(); if(HwClose() != LIB_SUCCESS) { VDB_LOG_ERROR("Closing HW failed.\n"); } // if HwClose() failed // unmap PRAM if(mPramBase != NULL) { free(mPramBase); } // if PRAM mapped } // if last process // decrease counters --(*mpInitCounter); --mThreadCounter; // destroy sdi init semaphore if( OAL_SemaphoreDelete(mSdiMut) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi mutex semaphore delete failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreDelete() failed // destroy shared memory if(OAL_SharedMemoryDestroy(mShm) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi shared memory destruction failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreDelete() failed //try to release init semaphore if(OAL_SemaphoreRelease(mInitSemaphore) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi init semaphore release failed.\n"); lRet = LIB_FAILURE; } // SemaphoreRelease() failed // destroy sdi init semaphore if( OAL_SemaphoreDelete(mInitSemaphore) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi init semaphore delete failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreDelete() failed mInitSemaphore = NULL; }else { VDB_LOG_NOTE("%u Close: Ordinary thread => nothing destroyed.\n", aTaskNum); // decrease counters --(*mpInitCounter); --mThreadCounter; //try to release init semaphore if(OAL_SemaphoreRelease(mInitSemaphore) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi init semaphore release failed.\n"); lRet = LIB_FAILURE; } // SemaphoreRelease() failed }// else from if last thread in this process }else { VDB_LOG_ERROR("%u Sdi clients number already 0. Nothing done.\n", aTaskNum); lRet = LIB_FAILURE; //try to release init semaphore if(OAL_SemaphoreRelease(mInitSemaphore) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi init semaphore release failed.\n"); lRet = LIB_FAILURE; } // SemaphoreRelease() failed } // else from if max number of clients not reached yet } // if init counter pointer not NULL } // else from if init semaphore obtain failed #else // if 0 HwClose(); #endif // else from if 0 return lRet; } // sdi::Close() //**************************************************************************** /*LIB_RESULT sdi::ProcessReserve(sdi_process *&arpProcess) { LIB_RESULT lRet = LIB_SUCCESS; // must obtain mutex - will change sdi member if (OAL_SemaphoreObtain(mSdiMut) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi thread mutex obtain failed.\n"); lRet = LIB_FAILURE; } else { // create new process object sdi_process *tmpProcess = new (nothrow) sdi_process(); if (tmpProcess == NULL) { VDB_LOG_ERROR("Sdi thread mutex obtain failed.\n"); lRet = LIB_FAILURE; } else { bool found = false; //find slot for new sdi_process for (uint32_t i = 0; i < mProcesses.size(); ++i) { if (mProcesses[i] == NULL) { tmpProcess->mId = mNextProcessId; mProcesses[i] = tmpProcess; ++mNextProcessId; found = true; } // if process slot empty } // for all prepared process pointers if (!found) { if (mProcesses.size() < SDI_MAX_CLIENT_NUM) { mProcesses.push_back(tmpProcess); } else { VDB_LOG_ERROR("Maximum number of sdi clients reached already.\n"); lRet = LIB_FAILURE; } // else from if max client number reached } // if no empty slot found // reserving process done by filling pointer slot // no mutex needed arpProcess = tmpProcess; // todo: HW related reservation } // else from if sdi_process alloc failed if (OAL_SemaphoreRelease(mSdiMut) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi thread mutex release failed.\n"); lRet = LIB_FAILURE; } // if sdi mutex release failed } // else from if mutex obtain failed return lRet; } // sdi::ProcessReserve()*/ //**************************************************************************** /*LIB_RESULT sdi::ProcessRelease(sdi_process *&arpProcess) { LIB_RESULT lRet = LIB_SUCCESS; if( arpProcess == NULL) { VDB_LOG_ERROR("Null given instead of valid sdi_process pointer.\n"); lRet = LIB_FAILURE; } // if NULL pointer to Input given else { // must have mutex - will change sdi member if (OAL_SemaphoreObtain(mSdiMut) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi thread mutex obtain failed.\n"); lRet = LIB_FAILURE; } else { // create new process object if (arpProcess == NULL) { VDB_LOG_ERROR("NULL process pointer.\n"); lRet = LIB_FAILURE; } else { bool found = false; //find slot for new sdi_process for (uint32_t i = 0; i < mProcesses.size(); ++i) { if (mProcesses[i] == arpProcess) { mProcesses[i] = NULL; found = true; } // if process slot empty } // for all prepared process pointers if (!found) { VDB_LOG_ERROR("Bad process pointer.\n"); arpProcess->mId = (uint32_t) SDI_SENSOR_INVALID; lRet = LIB_FAILURE; } else { // todo: HW related releasing // delete process delete (arpProcess); } // else from if process not found } // else from if sdi_process alloc failed if (OAL_SemaphoreRelease(mSdiMut) != LIB_SUCCESS) { VDB_LOG_ERROR("Sdi thread mutex release failed.\n"); lRet = LIB_FAILURE; } // if sdi mutex release failed } // else from if mutex obtain failed } // else from if arpProcess == NULL return lRet; } // sdi::ProcessRelease()*/ //**************************************************************************** LIB_RESULT sdi::ShmConnect(uint32_t /*aSensorCnt*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE // process/thread safety under development uint8_t *pShm = NULL; // calculate required shared memory size = (shm size + init counter + // number of sensors + sdi_input * number of sensors) uint32_t sdi_shm_size = sizeof(uint32_t) * 3 + /*SEMAPHORE_STRUCT_SIZE + */sizeof(sdi_input) * aSensorCnt; // create general shared memory area if (OAL_SharedMemoryCreate(&mShm, scpShmName, sdi_shm_size) != LIB_SUCCESS) { VDB_LOG_ERROR("Shared memory creation failed.\n"); lRet = LIB_FAILURE; // some failure = NOK } else { VDB_LOG_NOTE("Shared memory object created and opened \n"); if(OAL_SharedMemoryGetPointer(((void**)&pShm), mShm) != LIB_SUCCESS) { VDB_LOG_ERROR("Getting pointer to shared memory failed.\n"); lRet = LIB_FAILURE; }else { // parcel the shared memory area mpSharedMemorySize = (uint32_t*)pShm; *mpSharedMemorySize = sdi_shm_size; // store the shared memory size pShm += sizeof(uint32_t); mpInitCounter = (uint32_t*)pShm; pShm += sizeof(uint32_t); mpSensorCnt = (uint32_t*)pShm; pShm += sizeof(uint32_t); if(OAL_SemaphoreCreate(&mSdiMut,scpMutSdiName,OAL_SEMAPHORE_COUNTING, 1)) { VDB_LOG_ERROR("Creating sdi semaphore failed.\n"); lRet = LIB_FAILURE; }else { if(OAL_SemaphoreOwnershipSet(mSdiMut,false) != LIB_SUCCESS) { VDB_LOG_ERROR("Mutex ownership set failed.\n"); lRet = LIB_FAILURE; }else { if(OAL_SharedMemoryOwnershipSet(mShm,false) != LIB_SUCCESS) { VDB_LOG_ERROR("Shared memory ownership set failed.\n"); lRet = LIB_FAILURE; } // if SharedMemoryOwnershipSet() failed else { // TODO: map PRAM if((mPramBase = malloc(PRAM_SIZE)) == NULL) { VDB_LOG_ERROR("Mapping of PRAM failed.\n"); lRet = LIB_FAILURE; // if(OAL_SemaphoreDelete(mSdiMut) != LIB_SUCCESS) // { // VDB_LOG_ERROR("Deleting shared mutex.\n"); // lRet = LIB_FAILURE; // }// if SemaphoreDelete() failed } // if PRAM mapping failed } // else from if SharedMemoryOwnershipSet() failed if( lRet == LIB_FAILURE) { if( OAL_SemaphoreOwnershipSet(mSdiMut, true) != LIB_SUCCESS)\ { VDB_LOG_NOTE("Shared mutex ownership set failed.\n"); } // if SemaphoreDelete() failed } // if LIB_FAILURE } // else if OwnershipSet() failed if( lRet == LIB_FAILURE) { if( OAL_SemaphoreDelete(mSdiMut) != LIB_SUCCESS)\ { VDB_LOG_NOTE("Shared mutex delete failed.\n"); } // if SemaphoreDelete() failed mpInitCounter = NULL; mpSensorCnt = NULL; } // if LIB_FAILURE } // else from if SemaphoreCreateInterprocessMutexOnAddress() failed } // else from if ShareMemoryCreate() failed if(lRet == LIB_FAILURE) { if(OAL_SharedMemoryDestroy(mShm) != LIB_SUCCESS) { VDB_LOG_ERROR("Destroying shared memory failed.\n"); } // OAL_SharedMemoryDestroy() failed } // if LIB_FAILURE } //else from if SharedMemoryCreate() failed #endif // #ifdef SDI_THRED_SAFE return lRet; } // sdi::ShmConnect(uint32_t) //**************************************************************************** LIB_RESULT ShmSizeGet(uint32_t */*apShmSize*/, const char* /*acpName*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE // process/thread safety under development OAL_SHARED_MEM shm; if (OAL_SharedMemoryGetByName(&shm, acpName, sizeof(uint32_t)) != LIB_SUCCESS) { VDB_LOG_NOTE("Shared memory open failed.\n"); lRet = LIB_FAILURE; } // if shm get by name failed else { uint32_t *pSize = NULL; *apShmSize = 0; if(OAL_SharedMemoryGetPointer(((void**)&pSize), shm) != LIB_SUCCESS) { VDB_LOG_ERROR("Getting pointer to shared memory failed.\n"); lRet = LIB_FAILURE; } // if shm get pointer failed else { *apShmSize = *pSize; pSize = NULL; } // else form if shm get pointer failed }// else from if shm get by name failed #endif //#if 0 return lRet; } // LIB_RESULT ShmOpen(OAL_SHARED_MEM* apSharedMem, const char* apName) //**************************************************************************** LIB_RESULT sdi::ExistingShmOpen(uint32_t */*apShmSize*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE if (OAL_SharedMemoryGetByName(&mShm, scpShmName, sizeof(uint32_t)) != LIB_SUCCESS) { VDB_LOG_NOTE("Shared memory open failed.\n"); lRet = LIB_FAILURE; } // if shm get by name failed else { uint32_t *pSize = NULL; *apShmSize = 0; if(OAL_SharedMemoryGetPointer(((void**)&pSize), mShm) != LIB_SUCCESS) { VDB_LOG_ERROR("Getting pointer to shared memory failed.\n"); lRet = LIB_FAILURE; } // if shm get pointer failed else { *apShmSize = *pSize; pSize = NULL; // TODO: map PRAM if((mPramBase = malloc(PRAM_SIZE)) == NULL) { VDB_LOG_ERROR("Mapping of PRAM failed.\n"); lRet = LIB_FAILURE; } // if PRAM mapping failed } // else form if shm get pointer failed if(lRet == LIB_FAILURE) { if(OAL_SharedMemoryDestroy(mShm) != LIB_SUCCESS) { VDB_LOG_ERROR("Destroying shared memory failed.\n"); lRet = LIB_FAILURE; }// if SemaphoreDelete() failed } // if failure detected }// else from if shm get by name failed #endif //#ifdef SDI_THRED_SAFE return lRet; } // LIB_RESULT ExistingShmOpen(OAL_SHARED_MEM* apSharedMem, const char* acpName, uint32_t *apShmSize) //**************************************************************************** LIB_RESULT sdi::ShmConnect(bool &/*arRepeat*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE uint8_t *pShm = NULL; arRepeat = false; uint32_t shmSize = 0; // first thread in consecutive process if (ExistingShmOpen(&shmSize) != LIB_SUCCESS) //if (OAL_SharedMemoryGetByName(&mShm, scpShmName,256) != LIB_SUCCESS) { VDB_LOG_NOTE("Shared memory open failed.\n"); arRepeat = true; lRet = LIB_FAILURE; }else { // get the pointer to full shared memory size if(OAL_SharedMemoryGetPointer(((void**)&pShm), mShm, shmSize) != LIB_SUCCESS) { VDB_LOG_ERROR("Getting pointer to shared memory failed.\n"); lRet = LIB_FAILURE; }else { // parcel the shared memory area mpSharedMemorySize = (uint32_t*)pShm; pShm += sizeof(uint32_t); mpInitCounter = (uint32_t*)pShm; pShm += sizeof(uint32_t); mpSensorCnt = (uint32_t*)pShm; pShm += sizeof(uint32_t); if(OAL_SemaphoreGetByName(&mSdiMut, scpMutSdiName) != LIB_SUCCESS) { VDB_LOG_ERROR("Getting sdi semaphore by name failed.\n"); mpSharedMemorySize = NULL; mpInitCounter = NULL; mpSensorCnt = NULL; lRet = LIB_FAILURE; } // if sdi semaphore get by name failed else { pShm += SEMAPHORE_STRUCT_SIZE; } // else from if SemaphoreGetFromMutexAddress)( failed } // else from if OAL_SharedMemoryGetPointer() if(lRet == LIB_FAILURE) { if(OAL_SharedMemoryDestroy(mShm) != LIB_SUCCESS) { VDB_LOG_ERROR("Destroying shared memory failed.\n"); } // SharedMemoryDestroy() failed } // if LIB_FAILURE }// else form if OAL_SharedMemoryGetByName() failed #endif // #ifdef SDI_THRED_SAFE return lRet; } // sdi::ShmConnect() //**************************************************************************** LIB_RESULT sdi::ShmDisconnect(bool /*aDelete*/) { LIB_RESULT lRet = LIB_SUCCESS; #ifdef SDI_THRED_SAFE if( aDelete) { if(OAL_SemaphoreOwnershipSet(mSdiMut,true) != LIB_SUCCESS) { VDB_LOG_ERROR("Shared mutex ownership set failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreOwnershipSet() failed if(OAL_SharedMemoryOwnershipSet(mShm,true) != LIB_SUCCESS) { VDB_LOG_ERROR("Shared memory ownership set failed.\n"); lRet = LIB_FAILURE; } // if SemaphoreOwnershipSet() failed } // if aMutDelete if(OAL_SemaphoreDelete(mSdiMut) != LIB_SUCCESS) { VDB_LOG_ERROR("Deleting shared mutex.\n"); lRet = LIB_FAILURE; }// if SemaphoreDelete() failed mpInitCounter = NULL; mpSensorCnt = NULL; #endif // #ifdef SDI_THRED_SAFE return lRet; } // sdi::ShmDisconnect() //**************************************************************************** LIB_RESULT sdi::SensorCntGet(uint32_t &raSensorCnt) { LIB_RESULT lRet = LIB_SUCCESS; // todo: query sequencer raSensorCnt = SDI_SENSOR_CNT; return lRet; } // sdi::SensorCntGet() //**************************************************************************** LIB_RESULT sdi::HwInit() { // TODO: initialize HW (open drivers...) VDB_LOG_FCN_NOT_IMPLEMENTED(); return LIB_SUCCESS; } // sdi::HwInit() //**************************************************************************** LIB_RESULT sdi::HwClose() { // TODO: release HW (close drivers...) VDB_LOG_FCN_NOT_IMPLEMENTED(); return LIB_SUCCESS; } // sdi::HwClose() //**************************************************************************** #ifdef __STANDALONE__ void IspHwSramAccesAllow(void) { *(uint32_t*)(0x40006000) = 0x00000000; *(uint32_t*)(0x40006004) = 0xffffffff; *(uint32_t*)(0x4000600c) = 0x80000000; *(uint32_t*)(0x40006020) = 0x00000000; *(uint32_t*)(0x40006024) = 0xffffffff; *(uint32_t*)(0x4000602c) = 0x80000000; *(uint32_t*)(0x40006040) = 0x00000000; *(uint32_t*)(0x40006044) = 0xffffffff; *(uint32_t*)(0x4000604c) = 0x80000000; *(uint32_t*)(0x40006060) = 0x00000000; *(uint32_t*)(0x40006064) = 0xffffffff; *(uint32_t*)(0x4000606c) = 0x80000000; *(uint32_t*)(0x40006080) = 0x00000000; *(uint32_t*)(0x40006084) = 0xffffffff; *(uint32_t*)(0x4000608c) = 0x80000000; *(uint32_t*)(0x400060a0) = 0x00000000; *(uint32_t*)(0x400060a4) = 0xffffffff; *(uint32_t*)(0x400060ac) = 0x80000000; *(uint32_t*)(0x400060c0) = 0x00000000; *(uint32_t*)(0x400060c4) = 0xffffffff; *(uint32_t*)(0x400060cc) = 0x80000000; *(uint32_t*)(0x400060e0) = 0x00000000; *(uint32_t*)(0x400060e4) = 0xffffffff; *(uint32_t*)(0x400060ec) = 0x80000000; *(uint32_t*)(0x40006100) = 0x00000000; *(uint32_t*)(0x40006104) = 0xffffffff; *(uint32_t*)(0x4000610c) = 0x80000000; *(uint32_t*)(0x40006120) = 0x00000000; *(uint32_t*)(0x40006124) = 0xffffffff; *(uint32_t*)(0x4000612c) = 0x80000000; *(uint32_t*)(0x40006140) = 0x00000000; *(uint32_t*)(0x40006144) = 0xffffffff; *(uint32_t*)(0x4000614c) = 0x80000000; *(uint32_t*)(0x40006160) = 0x00000000; *(uint32_t*)(0x40006164) = 0xffffffff; *(uint32_t*)(0x4000616c) = 0x80000000; *(uint32_t*)(0x40006180) = 0x00000000; *(uint32_t*)(0x40006184) = 0xffffffff; *(uint32_t*)(0x4000618c) = 0x80000000; *(uint32_t*)(0x400061a0) = 0x00000000; *(uint32_t*)(0x400061a4) = 0xffffffff; *(uint32_t*)(0x400061ac) = 0x80000000; *(uint32_t*)(0x400061c0) = 0x00000000; *(uint32_t*)(0x400061c4) = 0xffffffff; *(uint32_t*)(0x400061cc) = 0x80000000; *(uint32_t*)(0x400061e0) = 0x00000000; *(uint32_t*)(0x400061e4) = 0xffffffff; *(uint32_t*)(0x400061ec) = 0x80000000; *(uint32_t*)(0x40006200) = 0x00000000; *(uint32_t*)(0x40006204) = 0xffffffff; *(uint32_t*)(0x4000620c) = 0x80000000; *(uint32_t*)(0x40006220) = 0x00000000; *(uint32_t*)(0x40006224) = 0xffffffff; *(uint32_t*)(0x4000622c) = 0x80000000; *(uint32_t*)(0x40006240) = 0x00000000; *(uint32_t*)(0x40006244) = 0xffffffff; *(uint32_t*)(0x4000624c) = 0x80000000; *(uint32_t*)(0x40006260) = 0x00000000; *(uint32_t*)(0x40006264) = 0xffffffff; *(uint32_t*)(0x4000626c) = 0x80000000; } // IspHwSramAccesAllow() #endif //**************************************************************************** // *** EOF ***
29.648364
124
0.562656
intesight
53bfbeb381c50958f9b2d9ea6c9168e58abd5af3
567
cpp
C++
chapter-6/Program 6.20.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-6/Program 6.20.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-6/Program 6.20.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
/* program that inputs a number and checks whether it is a palindrome or not. a palindrome is a number that reads the same backwards as forwards such as 62526 and 4994 */ #include<iostream> using namespace std; main() { long int n, num, digit, rev=0; cout<<"Enter a positive number "; cin>>num; n=num; do { digit=num%10; rev=(rev*10)+digit; num=num/10; } while(num!=0); cout<<" the reverse of the number is "<<rev<<endl; if (n==rev) cout<<"the number is a Palindrome "; else cout<<"number is not Palindrome "; }
19.551724
60
0.634921
JahanzebNawaz
53c1c696aa3a43d0842e51aafd41d62ba5b8bbff
997
hpp
C++
include/_app_state_plan.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
1
2022-03-03T09:34:54.000Z
2022-03-03T09:34:54.000Z
include/_app_state_plan.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
null
null
null
include/_app_state_plan.hpp
zborffs/Delta
b2efa9fe1cc2138656f4d7964ccdbbbfcebba639
[ "MIT" ]
null
null
null
#ifndef DELTA__APP_STATE_PLAN_HPP #define DELTA__APP_STATE_PLAN_HPP /// third-party includes #include <spdlog/spdlog.h> /// project includes #include "app.hpp" #include "_app_state_shutdown.hpp" #include "_app_state_wait.hpp" /** * The AppStatePlan is responsible for coloring the Application's functionality when in the Plan state * - it transforms a ChessMove representing the best move into a series of coordinates in the world frame * - it is reached from the Engine state * - it makes use of the Plan component * - if successful, transitions to wait state */ class AppStatePlan : public AppState { ChessMove best_move_; public: explicit AppStatePlan(ChessMove best_move) : best_move_(best_move) { spdlog::get("delta_logger")->info("Created AppStatePlan (best_move: {})", best_move_.to_string()); } ~AppStatePlan() { spdlog::get("delta_logger")->info("Destroyed AppStatePlan"); } bool handle() override; }; #endif // DELTA__APP_STATE_PLAN_HPP
31.15625
106
0.735206
zborffs
53c8897bdc8ebe4c70ea469c6ca4eae7981b7202
732
cpp
C++
ch19/19_21.22.23.25/Test.cpp
WangLaban/CppPrime5th
b376f1a77dfb7cd9bbde7418006e016ce5b81550
[ "CC0-1.0" ]
null
null
null
ch19/19_21.22.23.25/Test.cpp
WangLaban/CppPrime5th
b376f1a77dfb7cd9bbde7418006e016ce5b81550
[ "CC0-1.0" ]
null
null
null
ch19/19_21.22.23.25/Test.cpp
WangLaban/CppPrime5th
b376f1a77dfb7cd9bbde7418006e016ce5b81550
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <string> #include "Token.h" using std::string; using std::cout; using std::endl; int main() { string s = "string"; Sales_data item("c++ primer 5", 12, 128.0); int i = 12; char c = 'c'; double d = 1.28; Token t; t = i; cout << t << endl; t = c; cout << t << endl; t = d; cout << t << endl; t = s; cout << t << endl; t = item; cout << t << endl; Token t2 = t; cout << t2 << endl; t2 = s; cout << t2 << endl; t2 = t; cout << t2 << endl; t2 = c; cout << t2 << endl; t = s; t2 = std::move(t); cout << t2 << endl; Token t3 = std::move(t2); cout << t3 << endl; t3 = t3; cout << t3 << endl; t3 = item; cout << t3 << endl; t2 = std::move(t3); cout << t2 << endl; return 0; }
15.574468
44
0.513661
WangLaban
53d556b3e690b8d41047402aeac7313570a6cd06
1,681
cpp
C++
Concurrency/2.Data_between_Threads/Avoiding_Data_Races/example_1.cpp
weihang-li/Cpp-Nano-Udacity
c7c1f30b1d56e9849519656ca5186a444bb0a77f
[ "MIT" ]
null
null
null
Concurrency/2.Data_between_Threads/Avoiding_Data_Races/example_1.cpp
weihang-li/Cpp-Nano-Udacity
c7c1f30b1d56e9849519656ca5186a444bb0a77f
[ "MIT" ]
null
null
null
Concurrency/2.Data_between_Threads/Avoiding_Data_Races/example_1.cpp
weihang-li/Cpp-Nano-Udacity
c7c1f30b1d56e9849519656ca5186a444bb0a77f
[ "MIT" ]
null
null
null
#include <iostream> #include <thread> #include <future> // In this example, one safe way of passing data to a thread would be to carefully synchronize // the two threads using either join() or the promise-future concept that can guarantee the availability // of a result. Data races are always to be avoided. Even if nothing bad seems to happen, // they are a bug and should always be treated as such. Another possible solution for the above example // would be to make a copy of the original argument and pass the copy to the thread, thereby preventing the data race. class Vehicle { public: //default constructor Vehicle() : _id(0) { std::cout << "Vehicle #" << _id << " Default constructor called" << std::endl; } //initializing constructor Vehicle(int id) : _id(id) { std::cout << "Vehicle #" << _id << " Initializing constructor called" << std::endl; } // setter and getter void setID(int id) { _id = id; } int getID() { return _id; } private: int _id; }; int main() { // create instances of class Vehicle Vehicle v0; // default constructor Vehicle v1(1); // initializing constructor // read and write name in different threads (which one of the above creates a data race?) /* an instance of the proprietary class Vehicle is created and passed to a thread by value, thus making a copy of it. */ std::future<void> ftr = std::async([](Vehicle v) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); // simulate work v.setID(2); }, v0); v0.setID(3); ftr.wait(); std::cout << "Vehicle #" << v0.getID() << std::endl; return 0; }
31.12963
118
0.652588
weihang-li
53d5e2ad4d6baec25ca80aa2c08eca2e068a6165
466
cpp
C++
codeforces/rounds/#359/watch.cpp
GinugaSaketh/Codes
e934aa5652dd86231a42e3f7f84b145eb35bf47d
[ "MIT" ]
null
null
null
codeforces/rounds/#359/watch.cpp
GinugaSaketh/Codes
e934aa5652dd86231a42e3f7f84b145eb35bf47d
[ "MIT" ]
null
null
null
codeforces/rounds/#359/watch.cpp
GinugaSaketh/Codes
e934aa5652dd86231a42e3f7f84b145eb35bf47d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int n,m; vector<int> a,b; int a[128]; int main(){ cin>>n>>m; if(n<m){ int t=n; n=m; m=t; } int k; for(k=0;k<10;k++){ dp[i][0][0]=0; dp[i][1][0]=0; dp[i][0][1]=0; dp[i][1][1]=0; } int p=n,q=n; while(p!=0){ a.push_back(p%7); p/=7; } while(q!=0){ b.push_back(q%7); q/=7; } if(a.size()+b.size()>7){ cout<<"0"<<endl; }else{ } } } return 0; }
6.213333
25
0.429185
GinugaSaketh
53dd68811cc91d55548fc2d80b80e1151362b896
1,186
hpp
C++
libzmq/ReceiptGenerator.hpp
murrekatt/zmq-samples
102a9543ba5c4fade15f5370aeb772ad48b0c3f4
[ "MIT" ]
1
2015-07-27T14:22:34.000Z
2015-07-27T14:22:34.000Z
libzmq/ReceiptGenerator.hpp
murrekatt/zmq-samples
102a9543ba5c4fade15f5370aeb772ad48b0c3f4
[ "MIT" ]
null
null
null
libzmq/ReceiptGenerator.hpp
murrekatt/zmq-samples
102a9543ba5c4fade15f5370aeb772ad48b0c3f4
[ "MIT" ]
null
null
null
#ifndef PROTO_RECEIPTGENERATOR_HPP #define PROTO_RECEIPTGENERATOR_HPP #include "Module.hpp" #include <zmq.h> #include <string> #include <cassert> #include <unistd.h> namespace proto { struct ReceiptGenerator : public Module { explicit ReceiptGenerator(int i) : Module() , socket_(nullptr) , id_("ReceiptGenerator" + std::to_string(i)) , interval_(i+1) { socket_ = zmq_socket(ctx_, ZMQ_DEALER); assert(socket_); setLinger(socket_); setIdentity(socket_, id_); int rc = zmq_connect(socket_, "tcp://127.0.0.1:5560"); assert(rc == 0); } virtual ~ReceiptGenerator() { int rc = zmq_close(socket_); assert(rc == 0); } virtual void run() { const char* content = "12345678ABCDEFGH12345678abcdefgh"; std::cout << id_ << ": Sending data." << std::endl; int rc = zmq_send(socket_, "", 0, ZMQ_SNDMORE); assert(rc == id_.size()); rc = zmq_send(socket_, content, 32, 0); sleep(interval_); } void* socket_; std::string id_; int interval_; }; } // namespace proto #endif // PROTO_RECEIPTGENERATOR_HPP
21.178571
65
0.596965
murrekatt
53e8dcc8d314722520672a285b7e97015e48a5c7
480
cpp
C++
13.TemplateLibrary/UserTemplateLibrary/3.Iterator/genitrtrtest.cpp
amitpingale92/PG-DAC-C-Plus-Plus
c36f8c3b426287e2c7a8825bb4acbca28d4abe5e
[ "MIT" ]
null
null
null
13.TemplateLibrary/UserTemplateLibrary/3.Iterator/genitrtrtest.cpp
amitpingale92/PG-DAC-C-Plus-Plus
c36f8c3b426287e2c7a8825bb4acbca28d4abe5e
[ "MIT" ]
null
null
null
13.TemplateLibrary/UserTemplateLibrary/3.Iterator/genitrtrtest.cpp
amitpingale92/PG-DAC-C-Plus-Plus
c36f8c3b426287e2c7a8825bb4acbca28d4abe5e
[ "MIT" ]
null
null
null
#include "simplelist.h" #include "interval.h" #include <iostream> using namespace Generic; using namespace std; int main(void) { SimpleList<Interval> store; store.AddElement(Interval(7, 31)); store.AddElement(Interval(4, 52)); store.AddElement(Interval(5, 43)); store.AddElement(Interval(3, 24)); store.AddElement(Interval(6, 35)); for(SimpleList<Interval>::Iterator i = store.Begin(); i != store.End(); ++i) cout << *i << "\t" << i->GetTime() << endl; }
15
77
0.664583
amitpingale92
53ec2d17b7d4bf274114cbf3546e7372aef3a710
1,162
cpp
C++
OwNetClient/helpers/listofstringpairs.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
2
2016-09-28T02:23:07.000Z
2019-07-13T15:53:47.000Z
OwNetClient/helpers/listofstringpairs.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
OwNetClient/helpers/listofstringpairs.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
#include "listofstringpairs.h" #include "jsondocument.h" ListOfStringPairs::ListOfStringPairs() : QList< QPair<QString, QString> >() { } void ListOfStringPairs::insert(const QString &key, const QString &value) { QPair<QString, QString> pair(key, value); append(pair); } void ListOfStringPairs::insertOrReplace(const QString &key, const QString &value) { for (int i = count() - 1; i >= 0; --i) if (QString::compare(at(i).first, key, Qt::CaseInsensitive) == 0) removeAt(i); insert(key, value); } void ListOfStringPairs::parse(const QVariantMap &variantMap) { foreach (QString key, variantMap.keys()) { insert(key, variantMap.value(key).toString()); } } QString ListOfStringPairs::toString() { QVariantMap map; for (int i = 0; i < count(); ++i) map.insert(at(i).first, at(i).second); return QString(JsonDocument::fromVariantMap(map).toJson()); } QString ListOfStringPairs::valueForKey(const QString &key) const { for (int i = 0; i < count(); i++){ if (QString::compare(at(i).first, key, Qt::CaseInsensitive) == 0) return at(i).second; } return ""; }
24.723404
81
0.640275
OwNet
53f1a82fa2a873cc76a28af5db285d63d669f847
32
cpp
C++
test/headers/error.cpp
Felspar/poll
432fc51e244fd3281695ad339cd2d09d3e33a36b
[ "BSL-1.0" ]
3
2022-02-21T03:01:09.000Z
2022-03-24T04:34:29.000Z
test/headers/error.cpp
Felspar/io
432fc51e244fd3281695ad339cd2d09d3e33a36b
[ "BSL-1.0" ]
null
null
null
test/headers/error.cpp
Felspar/io
432fc51e244fd3281695ad339cd2d09d3e33a36b
[ "BSL-1.0" ]
null
null
null
#include <felspar/io/error.hpp>
16
31
0.75
Felspar
53fbe519f54ac0793aeb26458b5c2805f7fc3237
18,131
hpp
C++
pulsar/math/MathSet.hpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
pulsar/math/MathSet.hpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
pulsar/math/MathSet.hpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
/* * File: MathSet.hpp * Original Author: Ryan Richard <ryanmrichard1@gmail.com> * * Created on January 22, 2016, 11:11 AM */ #pragma once #include "pulsar/exception/Assert.hpp" #include "pulsar/math/Universe.hpp" #include "pulsar/util/IterTools.hpp" #include <iterator> namespace pulsar{ template<typename T,typename U> class MathSet; /** An iterator to go with the MathSet class, returns actual objects * * The iterator only allows accessing the data, not modifying. That is, * this only behaves like a const_iterator */ template<typename T, typename U> class ConstSetItr : public std::iterator<std::input_iterator_tag, const T> { private: typedef ConstSetItr<T, U> My_t;///<Type of the iterator typedef Universe<T,U> Universe_t;///<Type of Universe in MathSet typedef std::set<size_t>::const_iterator Itr_t;///<Type of iterator to index Itr_t CurrIdx_;///<An iterator to the indices in the current MathSet const Universe_t* Set_;///<The Universe with the real data friend MathSet<T, U>; ///Only MathSet can make a working iterator ConstSetItr(Itr_t CurrIdx, const Universe_t* Set) : CurrIdx_(CurrIdx), Set_(Set) { } public: typedef T value_type;///<The type this iterator returns ConstSetItr(const ConstSetItr&) = default; ConstSetItr& operator=(const ConstSetItr&) = default; ConstSetItr(ConstSetItr&&) = default; ConstSetItr& operator=(ConstSetItr&&) = default; ~ConstSetItr() = default; ///Returns true if this iterator is equal to RHS bool operator==(const My_t& RHS)const { return (CurrIdx_ == RHS.CurrIdx_ &&Set_ == RHS.Set_); } ///Returns true if this iterator is not equal to RHS bool operator!=(const My_t& RHS)const{return !this->operator==(RHS);} ///Returns current element const T & operator*()const{return (*Set_)[*CurrIdx_];} ///Allows access to current element member functions const T * operator->()const{return &((*Set_)[*CurrIdx_]);} ///Increments and then returns this My_t& operator++(){++CurrIdx_;return *this;} ///Returns a copy of this and then increments My_t operator++(int){My_t ret(*this);++CurrIdx_;return ret;} }; /** \brief A class for performing set manipulations efficiently relative to * some universe. * * With the universe class all of the operations are deep copies or involve * copying the actual elements over. Now that we know what our universe is, * we can do these operations much more efficiently by mapping each element * to an integer in the range 0 to the size of our universe and performing * the operations on those integers. That's what this class does. It is * entirely possible to simply use the Universe class for set manipulations * (barring complement), it will just not be as efficient. * * * \par Hashing * The hash value of a MathSet is unique with respect to the values * of the universe (see the Universe class documentation) and * the values contained in this set. The hash will be * the same even if the pointers point to different locations. * * \param T The type of the object in the set \param U The type of the container holding the objects * */ template<typename T, typename U = std::vector<T>> class MathSet { private: typedef MathSet<T, U> My_t;///<This class's type public: typedef ConstSetItr<T, U> const_iterator;///<An iterator to this class typedef T value_type;///<The type of the elements typedef U store_type;///<The type of the container typedef Universe<T, U> Universe_t;///<Type of the universe in this class ///Type of a function capable of selecting elements typedef std::function<bool(const T &) > SelectorFunc; ///Type of a function capable of transforming elements typedef std::function<T(const T &)> TransformerFunc; /// \name Constructors, destructors, assignment ///@{ // constructs via shared pointer to universe and a given // set of elements MathSet(std::shared_ptr<const Universe_t> AUniverse, const std::set<size_t> & Elems) : Universe_(AUniverse) { this->Elems_ = Elems; } ///Makes a set in the universe and fills in all elements if fill==true explicit MathSet(std::shared_ptr<const Universe_t> AUniverse, bool fill) : Universe_(AUniverse) { for(size_t i : Range<0>(fill?AUniverse->size():0)) Elems_.insert(i); } MathSet(const My_t&) = default;///<copies indices, aliases universe ///Default, but compiler bug prevents using = default MathSet(My_t&& RHS) :Universe_(std::move(RHS.Universe_)),Elems_(std::move(RHS.Elems_)){} ///Copies universe and optionally fills it MathSet(const My_t& RHS,bool fill): MathSet(RHS.Universe_,fill) { } /*! \brief For serialization only * * \warning NOT FOR USE OUTSIDE OF SERIALIZATION * \todo Replace if cereal fixes this */ MathSet() {} // cannot be "=default" due to compiler bugs // (symbol may be missing when compiled in Debug mode) ///Deep copies elements, shallow copies Universe_ and (and Storage_) My_t & operator=(const My_t & RHS){//appears to also not work defaulted if(this==&RHS)return *this; Universe_=RHS.Universe_; Elems_=RHS.Elems_; return *this; } MathSet & operator=(My_t&& RHS){//Getting undefined reference when defaulted Universe_=std::move(RHS.Universe_); Elems_=std::move(RHS.Elems_); return *this; } ///Returns a deep copy of everything My_t clone()const { return My_t(std::make_shared<Universe_t>(*Universe_), this->Elems_); } /// Obtain the universe used by this set std::shared_ptr<const Universe_t> get_universe(void)const{return Universe_;} /*! \brief Obtain the contents of this MathSet as a new universe * * The new universe is not linked to this object in any way */ Universe_t as_universe()const{return Universe_t().insert(begin(),end());} ///@} ///@{ ///Basic accessors ///Clears Elems does not delete universe void clear(void){Elems_.clear();} ///Returns the number of elements in this set size_t size(void)const noexcept{return Elems_.size();} ///Returns a constant iterator to the start of this set const_iterator begin() const { return const_iterator(Elems_.begin(),Universe_.get()); } ///Returns a constant iterator just past the end of the this set const_iterator end() const { return const_iterator(Elems_.end(),Universe_.get()); } ///Returns true if this set has the element bool count(const T& Elem)const { return (Universe_->count(Elem) && count_idx(idx(Elem)) > 0); } ///Returns true if the index is in the set bool count_idx(size_t Idx)const { return Elems_.count(Idx); } ///Returns the index of \p Elem, throws if \p Elem is not in the Universe size_t idx(const T& Elem)const{return Universe_->idx(Elem);} ///Inserts the element into the set, throws if \p Elem is not in Universe My_t& insert(const T & Elem) { universe_contains(Elem); Elems_.insert(idx(Elem)); return *this; } ///Inserts the element with index \p Idx into this set My_t& insert_idx(size_t Idx) { universe_contains_idx(Idx); Elems_.insert(Idx); return *this; } ///@} /// \name Set operations ///@{ ///Makes this the union of this and \p RHS My_t& union_assign(const My_t & RHS) { if(!SameUniverse(RHS))throw PulsarException("Incompatible universes"); Elems_.insert(RHS.Elems_.begin(), RHS.Elems_.end()); return *this; } ///Returns the union of this and \p RHS My_t set_union(const My_t& RHS)const { return My_t(*this).union_assign(RHS); } ///Makes this the intersection of this and \p RHS My_t& intersection_assign(const My_t& RHS); ///Returns the intersection of this and \p RHS My_t intersection(const My_t & RHS) const { return My_t(*this).intersection_assign(RHS); } ///Returns the difference My_t& difference_assign(const My_t& RHS); ///Returns the difference of this and \p RHS My_t difference(const My_t& RHS) const { return My_t(*this).difference_assign(RHS); } ///Returns the complement of this set My_t complement()const { My_t Temp(Universe_,{}); for (const T& EI : *Universe_) { if(!this->count(EI))Temp.insert(EI); } return Temp; } /** \brief Returns true if this is a proper subset of other * * This is a proper subset of RHS if they have the same universe, * all elements in this are in RHS, and there is at least one * element in RHS that is not in this * * \param[in] RHS The set to comapre to * \return True if this is a proper subset of other * */ bool is_proper_subset_of(const My_t& RHS)const { return is_subset_of(RHS) && RHS.size() > this->size(); } /** \brief Returns true if this is a subset of other * * This is a subset of RHS if they have the same universe, * and all elements in this are in RHS * * \todo Avoid two equality checks (there's one in operator<) * * \param[in] RHS The set to comapre to * \return True if this is a subset of other * */ bool is_subset_of(const My_t& RHS)const { if(!SameUniverse(RHS)) return false; for(const auto & it : *this) if(!RHS.count(it)) return false; return true; } /** \brief Returns true if this is a proper superset of other * * This is a proper superset of other, iff other is a proper subset * of this. * * \param[in] RHS Set to compare to * \return True if this is a proper superset of other * */ bool is_proper_superset_of(const My_t& RHS)const { return RHS.is_proper_subset_of(*this); } /** \brief Returns true if this is a superset of other * * This is a superset of other iff other is a subset of this * * \param[in] RHS Set to compare to * \return true if this is a superset of other * */ bool is_superset_of(const My_t& RHS)const { return RHS.is_subset_of(*this); } ///@} ///@{ \brief Set comparison operators /** \brief Returns true if this set equals other * * Equality depends on two things the universe and which of the elements * from the universe are present in this set. For equality The universes * must contain the same elements (as determined by Universe::operator==) * and each set must contain the same elements * * \param[in] RHS The other MathSet to compare to * \return True if this set equals other */ bool operator==(const My_t& RHS)const { return ((Universe_==RHS.Universe_||*Universe_==*RHS.Universe_) && Elems_ == RHS.Elems_); } /** \brief Returns true if this does not equal other * * Literally just negates the result of operator==() * * \param[in] RHS The other MathSet * \return True if the sets are different * */ bool operator!=(const My_t& RHS)const { return !(*this == RHS); } ///@} /** \brief Applies a function to each element in this set * * This function takes a function of the signature: * \code * T transformer(const T& elem_in); * \endcode * which given some element, returns that elements new value. * * \param[in] transformer the function to apply * \return A new, non-aliased, trasformed version of this set */ My_t transform(TransformerFunc transformer)const { //! \todo better way to do this function? // This makes some assumptions about the ordering of elements std::shared_ptr<Universe_t> newuniverse(new Universe_t); for(size_t i = 0; i < Universe_->size(); ++i) { const auto & it = (*Universe_).at(i); if (Elems_.count(i) > 0) newuniverse->insert(transformer(it)); else newuniverse->insert(it); } return My_t(newuniverse, this->Elems_); } /** \brief Partitions the set in two based on some criteria * * This function creates a new set, with an aliased universe, that is * made up of elements for which the selector function returns true. The * selector function should have the signature: * \code * bool Selector(const T& elem_in); * \endcode * and should return true if the element it was given is to be in the new * set * * \param[in] selector the function used for selecting elements * \return The selected elements as a set */ My_t partition(SelectorFunc selector) const { std::set<size_t> newelems; for(const auto & idx : Elems_) { const auto & el = (*Universe_)[idx]; if(selector(el)) newelems.insert(idx); } return My_t(Universe_, newelems); } virtual std::string to_string()const { std::stringstream ss; for (const size_t& EI : Elems_) ss << (*Universe_)[EI] << " "; return ss.str(); } /*! \brief obtain a unique hash of this MathSet * * Hashes are the same if the Universes are equivalent * and if the elements are equivalent. The hashes will * be the same even if the two MathSets have different * Universes. */ bphash::HashValue my_hash(void) const { return bphash::make_hash(bphash::HashType::Hash128, *this); } private: ///The universe associated with this MathSet std::shared_ptr<const Universe_t> Universe_; ///Which elements of the universe are in the set std::set<size_t> Elems_; ///Does the universe contain the element void universe_contains(const T& Elem)const { if (!Universe_->count(Elem)) throw PulsarException("Requested element is not in the universe"); } ///Does the universe contain the index void universe_contains_idx(size_t Elem)const { if (Elem>=Universe_->size()) throw PulsarException("Requested element is not in the universe"); } /** \brief Determines if the universe of this and that of RHS are * compatible * * In order to use this set as the left side of a set operation like * union or intersection, the universe of this set must be the same as * that of \pRHS or every element in \pRHS must be in this's universe, * i.e. this's universe must be a superset of \pRHS's universe. */ bool SameUniverse(const My_t& RHS) const { return Universe_==RHS.Universe_ || Universe_->is_superset_of(*RHS.Universe_); //->is_superset_of(*RHS.Universe_); } //! \name Serialization and Hashing ///@{ DECLARE_SERIALIZATION_FRIENDS BPHASH_DECLARE_HASHING_FRIENDS /* We have to split load/save since the * the shared_ptr points to const data, and * cereal can't serialize to const data */ template<class Archive> void save(Archive & ar) const { ar(Universe_,Elems_); } template<class Archive> void load(Archive & ar) { std::shared_ptr<Universe_t> Newuniverse; ar(Newuniverse,Elems_); Universe_=std::move(Newuniverse); } void hash(bphash::Hasher & h) const { h(Universe_,Elems_); } ///@} }; /*********************** Implementations **************************************/ template<typename T,typename U> MathSet<T,U>& MathSet<T,U>::intersection_assign(const MathSet<T,U>& RHS) { if(!SameUniverse(RHS))throw PulsarException("Universes are incompatible"); if(&RHS==this)return *this; std::set<size_t> NewTemp; std::set_intersection(Elems_.begin(),Elems_.end(), RHS.Elems_.begin(), RHS.Elems_.end(), std::inserter<std::set<size_t>>( NewTemp, NewTemp.begin())); Elems_ = std::move(NewTemp); return *this; } template<typename T,typename U> MathSet<T,U>& MathSet<T,U>::difference_assign(const MathSet<T,U>& RHS) { if(!SameUniverse(RHS))throw PulsarException("Universes are incompatible"); if(&RHS==this){ Elems_=std::set<size_t>(); return *this; } std::set<size_t> NewTemp; std::set_difference(Elems_.begin(),Elems_.end(), RHS.Elems_.begin(), RHS.Elems_.end(), std::inserter<std::set < size_t >> ( NewTemp, NewTemp.begin())); Elems_ = std::move(NewTemp); return *this; } #define MATHSET_OP(op,name)\ template<typename T,typename U>\ MathSet<T,U> op(const MathSet<T,U>& LHS,const MathSet<T,U>& RHS) {\ return LHS.name(RHS);\ } #define MATHSET_OP2(op,name)\ template<typename T,typename U>\ MathSet<T,U>& op(MathSet<T,U>& LHS,const MathSet<T,U>& RHS) {\ return LHS.name(RHS);\ } #define MATHSET_COMP(op,name)\ template<typename T,typename U>\ bool op(const MathSet<T,U>& LHS,const MathSet<T,U>& RHS) {\ return LHS.name(RHS);\ } MATHSET_OP(operator+,set_union) MATHSET_OP2(operator+=,union_assign) MATHSET_OP(operator/,intersection) MATHSET_OP2(operator/=,intersection_assign) MATHSET_OP(operator-,difference) MATHSET_OP2(operator-=,difference_assign) MATHSET_COMP(operator<,is_proper_subset_of) MATHSET_COMP(operator<=,is_subset_of) MATHSET_COMP(operator>,is_proper_superset_of) MATHSET_COMP(operator>=,is_superset_of) #undef MATHSET_COMP #undef MATHSET_OP2 #undef MATHSET_OP }//End namespace pulsar
30.523569
82
0.629971
pulsar-chem
d87e4b15d8b21f7a60432634548d64bcee931bb2
607
cpp
C++
compiler/src/ast/ast_modbase_codegen.cpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
15
2017-08-15T20:46:44.000Z
2021-12-15T02:51:13.000Z
compiler/src/ast/ast_modbase_codegen.cpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
null
null
null
compiler/src/ast/ast_modbase_codegen.cpp
TuplexLanguage/tuplex
fc436c78224522663e40e09d36f83570fd76ba2d
[ "Apache-2.0" ]
1
2017-09-28T14:48:15.000Z
2017-09-28T14:48:15.000Z
#include "ast_modbase.hpp" #include "ast_entitydecls.hpp" #include "llvm_generator.hpp" using namespace llvm; void TxParsingUnitNode::code_gen( LlvmGenerationContext& context ) const { TRACE_CODEGEN( this, context ); this->module->code_gen( context ); } void TxModuleNode::code_gen( LlvmGenerationContext& context ) const { TRACE_CODEGEN( this, context ); if ( this->members ) { for ( auto mem : *this->members ) mem->code_gen( context ); } if ( this->subModules ) { for ( auto mod : *this->subModules ) mod->code_gen( context ); } }
24.28
74
0.642504
TuplexLanguage
d88482f0fa0f184a20781482b962aed57ce0bc23
1,961
cpp
C++
libraries/gloxor/src/graphics.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
4
2021-07-14T20:24:24.000Z
2021-07-16T06:49:48.000Z
libraries/gloxor/src/graphics.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
null
null
null
libraries/gloxor/src/graphics.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
null
null
null
#include "gloxor/graphics.hpp" #include <cstdint> const extern uint8_t fontBitmap[]; constexpr int scaleX = 2; constexpr int scaleY = 2; constexpr int fontWidth = 8 * scaleX; constexpr int fontHeight = 14 * scaleY; namespace glox { void framebuffer::putPixel(int x, int y, rgb_t color) { fbBeg[y * pitch + x] = color; } void framebuffer::writeCharAt(char ch, int x, int y, rgb_t fg, rgb_t bg) { int index = ((uint8_t)ch /* - 32 */) * 16; /* auto prescX = x*scale; auto prescY = y*scale; */ /* for (int i = 0; i < fontHeight; ++i) { for (int k = 0; k < fontWidth; ++k) { auto fontBit = 0b10000000 >> (k/scaleX); auto fontMask = fontBitmap[index + (i/scaleY)]; putPixel(x+k, y+i , fontMask & fontBit ? fg : bg); } } */ /* Magic code stolen from ted */ for (int i = 0, i1 = 0, i2 = 0; i2 < fontHeight; ++i, ++i2, (i == scaleY) ? (i = 0, i1++) : i) { for (int j = 0, j1 = 0, j2 = 0; j2 < fontWidth; ++j, ++j2, (j == scaleX) ? (j = 0, j1++) : j) { auto fontBit = 0b10000000 >> (j1); auto fontMask = fontBitmap[index + i1]; putPixel(x + j2, y + i2, fontMask & fontBit ? fg : bg); } } } void framebuffer::writeString(const char* str) { char c; while ((c = *str++) != 0) { writeCharAt(c, curX, curY, print_color, 0x0); // todo: modfify to work correctly with pitch values if (size_t tempX; (tempX = curX + fontWidth) < this->pitch) { curX = tempX; } else { curY += fontHeight; curX = 0; } } } void framebuffer::cls(rgb_t color) { //glox::drawRectangle(fbBeg,pitch,{0,0},{(rgb_t)width,(rgb_t)height},color); glox::setRange(fbBeg,fbEnd,color); } } // namespace glox
24.5125
102
0.501275
CarboSauce
d886b2c65a588eca9ee8f3305b8c28e15d15ddf4
1,389
hpp
C++
headers/Delegate.hpp
Asphox/SISL
fdfd532e7342336cf54a343f72812761eab5bf16
[ "MIT" ]
4
2017-06-29T12:49:51.000Z
2021-04-28T16:48:44.000Z
headers/Delegate.hpp
Asphox/SISL
fdfd532e7342336cf54a343f72812761eab5bf16
[ "MIT" ]
null
null
null
headers/Delegate.hpp
Asphox/SISL
fdfd532e7342336cf54a343f72812761eab5bf16
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////// // // SISL - An other SIgnals SLots library // Copyright (C) 2017-2018 SOTON "Asphox" Dylan (dylan.soton@telecom-sudparis.eu) // //////////////////////////////////////////////////////////// #ifndef SISL_DELEGATE_HPP #define SISL_DELEGATE_HPP #include <memory> #include <functional> #include <cstring> #include <type_traits> #include <typeinfo> #include "Generic_Delegate.hpp" namespace sisl { namespace priv { template< typename RET , typename... ARGS > class Delegate : public Generic_Delegate { private: template< typename OBJ > void init_with_member(OBJ* obj); void init_with_static(); public: Delegate() = default; Delegate(const Delegate&) = default; Delegate(Delegate&&) noexcept = default; explicit Delegate( const std::function<RET(ARGS...)>& functor ); template< typename OBJ > Delegate( OBJ* obj , RET(OBJ::*fp)(ARGS...)); explicit Delegate( RET(*fp)(ARGS...) ); template< typename... ARGS2 > void call(ARGS2... args); template< typename... ARGS2 > void operator()(ARGS2... args); }; } } #ifndef SISL_DELEGATE_TPP #define SISL_DELEGATE_TPP #include "../templates/Delegate.tpp" #endif //SISL_DELEGATE_TPP #endif //SISL_DELEGATE_HPP
21.369231
82
0.573794
Asphox
d888785845625b3e7120be72c7be451da56a0e33
8,769
cpp
C++
trie/trie.cpp
xmcy0011/cpp-dirtyfilter
2d2c9a69198b4676ab7a2897ea174b57effb9957
[ "MIT" ]
3
2022-01-21T04:09:49.000Z
2022-03-15T15:35:20.000Z
trie/trie.cpp
xmcy0011/cpp-dirtyfilter
2d2c9a69198b4676ab7a2897ea174b57effb9957
[ "MIT" ]
null
null
null
trie/trie.cpp
xmcy0011/cpp-dirtyfilter
2d2c9a69198b4676ab7a2897ea174b57effb9957
[ "MIT" ]
2
2021-10-09T15:18:23.000Z
2022-02-16T11:44:28.000Z
/** @file trie.h * @brief trieๆ ‘็ฎ—ๆณ•ๅฎž็Žฐ็š„ๆ•ๆ„Ÿ่ฏ่ฟ‡ๆปค * * Trie ๆ ‘ๅŽŸ็†ๅŠๅ…ถๆ•ๆ„Ÿ่ฏ่ฟ‡ๆปค็š„ๅฎž็Žฐ: https://www.jianshu.com/p/9919244dd7ad * wildfirechat: https://github.com/wildfirechat/server/blob/wildfirechat/broker/src/main/java/win/liyufan/im/SensitiveFilter.java * trie: https://github.com/r-lyeh-archived/trie/blob/master/trie.hpp * * Thinks [sensitivewd-filter](https://github.com/andyzty/sensitivewd-filter) * * @author teng.qing * @date 2021/6/10 */ #include "trie.h" #include <iostream> #include <fstream> const wchar_t kEndFlag = L'๏พฐ'; // unicode: FFB0 TrieNode::TrieNode() = default; TrieNode::~TrieNode() { for (auto i : subNodes_) { // std::cout << "delete" << i.first << std::endl; delete i.second; } subNodes_.clear(); } Trie::Trie() { root_ = new TrieNode(); } Trie::~Trie() { delete root_; root_ = nullptr; } void Trie::insert(const std::wstring &word) { TrieNode *curNode = root_; for (wchar_t code : word) { int unicode = SBCConvert::charConvert(code); TrieNode *subNode = curNode->getSubNode(unicode); // ๅฆ‚ๆžœๆฒกๆœ‰่ฟ™ไธช่Š‚็‚นๅˆ™ๆ–ฐๅปบ if (subNode == nullptr) { subNode = new TrieNode(); curNode->addSubNode(unicode, subNode); } // ๆŒ‡ๅ‘ๅญ่Š‚็‚น๏ผŒ่ฟ›ๅ…ฅไธ‹ไธ€ๅพช็Žฏ curNode = subNode; } // ่ฎพ็ฝฎ็ป“ๆŸๆ ‡่ฏ† int unicode = SBCConvert::charConvert(kEndFlag); curNode->addSubNode(unicode, new TrieNode()); } bool Trie::search(const std::wstring &word) { bool is_contain = false; for (int p2 = 0; p2 < word.length(); ++p2) { int wordLen = getSensitiveLength(word, p2); if (wordLen > 0) { is_contain = true; break; } } return is_contain; } bool Trie::startsWith(const std::wstring &prefix) { TrieNode *curNode = root_; for (wchar_t item : prefix) { int unicode = SBCConvert::charConvert(item); curNode = curNode->getSubNode(unicode); if (curNode == nullptr) return false; } return true; } std::set<SensitiveWord> Trie::getSensitive(const std::wstring &word) { std::set<SensitiveWord> sensitiveSet; for (int p2 = 0; p2 < word.length(); ++p2) { int wordLen = getSensitiveLength(word, p2); if (wordLen > 0) { std::wstring sensitiveWord = word.substr(p2, wordLen); SensitiveWord wordObj; wordObj.word = sensitiveWord; wordObj.startIndex = p2; wordObj.len = wordLen; sensitiveSet.insert(wordObj); p2 = p2 + wordLen - 1; } } return sensitiveSet; } int Trie::getSensitiveLength(std::wstring word, int startIndex) { TrieNode *p1 = root_; int wordLen = 0; bool endFlag = false; for (int p3 = startIndex; p3 < word.length(); ++p3) { int unicode = SBCConvert::charConvert(word[p3]); auto subNode = p1->getSubNode(unicode); if (subNode == nullptr) { // ๅฆ‚ๆžœๆ˜ฏๅœ้กฟ่ฏ๏ผŒ็›ดๆŽฅๅพ€ไธ‹็ปง็ปญๆŸฅๆ‰พ if (stop_words_.find(unicode) != stop_words_.end()) { ++wordLen; continue; } break; } else { ++wordLen; // ็›ดๅˆฐๆ‰พๅˆฐๅฐพๅทด็š„ไฝ็ฝฎ๏ผŒๆ‰่ฎคไธบๅฎŒๆ•ดๅŒ…ๅซๆ•ๆ„Ÿ่ฏ if (subNode->getSubNode(SBCConvert::charConvert(kEndFlag))) { endFlag = true; break; } else { p1 = subNode; } } } // ๆณจๆ„๏ผŒๅค„็†ไธ€ไธ‹ๆฒกๆ‰พๅˆฐๅฐพๅทด็š„ๆƒ…ๅ†ต if (!endFlag) { wordLen = 0; } return wordLen; } #if 0 /** @fn * @brief linuxไธ‹ไธ€ไธชไธญๆ–‡ๅ ็”จไธ‰ไธชๅญ—่Š‚,windowsๅ ไธคไธชๅญ—่Š‚ * ๅ‚่€ƒ๏ผšhttps://blog.csdn.net/taiyang1987912/article/details/49736349 * @param [in]str: ๅญ—็ฌฆไธฒ * @return */ std::string chinese_or_english_append(const std::string &str) { std::string replacement; //char chinese[4] = {0}; int chinese_len = 0; for (int i = 0; i < str.length(); i++) { unsigned char chr = str[i]; int ret = chr & 0x80; if (ret != 0) { // chinese: the top is 1 if (chr >= 0x80) { if (chr >= 0xFC && chr <= 0xFD) { chinese_len = 6; } else if (chr >= 0xF8) { chinese_len = 5; } else if (chr >= 0xF0) { chinese_len = 4; } else if (chr >= 0xE0) { chinese_len = 3; } else if (chr >= 0xC0) { chinese_len = 2; } else { throw std::exception(); } } // ่ทณ่ฟ‡ i += chinese_len - 1; //chinese[0] = str[i]; //chinese[1] = str[i + 1]; //chinese[2] = str[i + 2]; } else /** ascii **/ { } replacement.append("*"); } return replacement; } #endif std::wstring Trie::replaceSensitive(const std::wstring &word) { std::set<SensitiveWord> words = getSensitive(word); std::wstring ret = word; for (auto &item : words) { for (int i = item.startIndex; i < (item.startIndex + item.len); ++i) { ret[i] = L'*'; } } return ret; } void Trie::loadFromFile(const std::string &file_name) { std::ifstream ifs(file_name, std::ios_base::in); std::string str; int count = 0; while (getline(ifs, str)) { std::wstring utf8_str = SBCConvert::s2ws(str); insert(utf8_str); count++; } std::cout << "load " << count << " words" << std::endl; } void Trie::loadStopWordFromFile(const std::string &file_name) { std::ifstream ifs(file_name, std::ios_base::in); std::string str; int count = 0; while (getline(ifs, str)) { std::wstring utf8_str = SBCConvert::s2ws(str); if (utf8_str.length() == 1) { stop_words_.insert(utf8_str[0]); count++; } else if (utf8_str.empty()) { stop_words_.insert(L' '); count++; } } std::cout << "load " << count << " stop words" << std::endl; } void Trie::loadStopWordFromMemory(std::unordered_set<wchar_t> &words) { for (auto &str : words) { int unicode = SBCConvert::charConvert(str); stop_words_.emplace(unicode); } } void Trie::loadFromMemory(std::unordered_set<std::wstring> &words) { for (auto &item : words) { insert(item); } } #ifdef UNIT_TEST #include <thread> // performance void test_time(Trie &t) { auto t1 = std::chrono::steady_clock::now(); std::cout << "ไฝ ๅฅฝ๏ผŒๅŠ ไธ€ไธ‹ๅพฎไฟก18301231231:"; for (auto &&i : t.getSensitive(L"ไฝ ๅฅฝ๏ผŒๅŠ ไธ€ไธ‹ๅพฎไฟกVX18301231231")) { std::cout << SBCConvert::ws2s(i.word); } std::cout << std::endl; // run code auto t2 = std::chrono::steady_clock::now(); //ๆฏซ็ง’็บง double dr_ms = std::chrono::duration<double, std::milli>(t2 - t1).count(); std::cout << "่€—ๆ—ถ: " << dr_ms << std::endl; } void func(Trie &t) { std::cout << "ๆ•ๆ„Ÿ่ฏไธบ๏ผš"; std::wstring origin = L"ไฝ ไฝ ไฝ ไฝ ๆ˜ฏๅ‚ป้€ผๅ•Šไฝ ๏ผŒ่ฏดไฝ ๅ‘ข๏ผŒไฝ ไธชๅคง็ฌจ่›‹ใ€‚"; wchar_t dest[128] = {0}; origin.copy(dest, origin.length(), 0); for (auto &&i : t.getSensitive(origin)) { std::cout << "[index=" << i.startIndex << ",len=" << i.len << ",word=" << SBCConvert::ws2s(i.word) << "],"; // PS๏ผšๅฏนไบŽไธญๆ–‡ๆ•ๆ„Ÿ่ฏ๏ผŒๅ› ไธบไธ€่ˆฌๆฑ‰ๅญ—ๅ 3ไธชๅญ—่Š‚๏ผˆไนŸๆœ‰4ไธชๅญ—่Š‚๏ผ‰๏ผŒๆ‰€ไปฅ่ฟ™้‡Œโ€œ*โ€ๆ˜ฏๆญฃๅธธ็š„3ๅ€ใ€‚ // ้กน็›ฎ้‡Œ้œ€่ฆๆ˜ฏๅˆคๆ–ญๆ˜ฏๅŒ…ๅซ๏ผŒ่€Œไธๆ˜ฏๆ›ฟๆขใ€‚ // ๆ‰€ไปฅ๏ผŒๅฆ‚ๆžœๆœ‰่ฟ™็ง้œ€ๆฑ‚๏ผŒๅปบ่ฎฎๆ”นๆˆwstringๅ’Œwchat_tๆฅๅฎž็Žฐ for (int j = i.startIndex; j < (i.startIndex + i.len); ++j) { dest[j] = '*'; } } std::cout << " ๆ›ฟๆขๅŽ๏ผš" << dest << std::endl; std::cout << std::endl; } // thread safe void test_concurrent(Trie &t) { for (int i = 0; i < 20; i++) { std::thread thd([&]() { func(t); }); thd.join(); } std::this_thread::sleep_for(std::chrono::microseconds(3000)); } int testTrie() { Trie t; t.insert(L"apple"); assert(t.search(L"apple")); // ่ฟ”ๅ›ž true assert(t.search(L"app") == false); // ่ฟ”ๅ›ž false assert(t.startsWith(L"app")); // ่ฟ”ๅ›ž true t.insert(L"app"); assert(t.search(L"app")); // ่ฟ”ๅ›ž true assert(t.search(L"this is apple")); // ่ฟ”ๅ›ž true t.insert(L"ๅพฎไฟก"); t.insert(L"vx"); std::wstring origin = L"ไฝ ๅฅฝ๏ผŒ่ฏทๅŠ ๅพฎไฟก183023102312"; assert(t.replaceSensitive(origin) == L"ไฝ ๅฅฝ๏ผŒ่ฏทๅŠ **183023102312"); t.insert(L"ไฝ ๆ˜ฏๅ‚ป้€ผ"); t.insert(L"ไฝ ๆ˜ฏๅ‚ป้€ผๅ•Š"); t.insert(L"ไฝ ๆ˜ฏๅ่›‹"); t.insert(L"ไฝ ไธชๅคง็ฌจ่›‹"); t.insert(L"ๆˆ‘ๅŽปๅนดไนฐไบ†ไธช่กจ"); t.insert(L"shit"); origin = L"SHit๏ผŒไฝ ไฝ ไฝ ไฝ ๆ˜ฏๅ‚ป้€ผๅ•Šไฝ ๏ผŒ่ฏดไฝ ๅ‘ข๏ผŒไฝ ไธชๅคง็ฌจ่›‹ใ€‚"; assert(t.replaceSensitive(origin) == L"****๏ผŒไฝ ไฝ ไฝ ****ๅ•Šไฝ ๏ผŒ่ฏดไฝ ๅ‘ข๏ผŒ*****ใ€‚"); test_time(t); test_concurrent(t); // ๆต‹่ฏ•ๆฑ‰ๅญ—็š„ๅญ—่Š‚ๆ•ฐ // std::string str = "ไฝ ๅฅฝๅ•Š"; // std::string test = std::to_wstring(str); // for (int i = 0; i < test.length(); i++) { // std::cout << test[i] << std::endl; // } return 0; } #endif // UNIT_TEST
27.064815
131
0.538032
xmcy0011
d888e6cb56be33424389002bc67c3065148e0c16
14,460
cpp
C++
Blizzlike/Trinity/Scripts/Other/item_scripts.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Other/item_scripts.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Other/item_scripts.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Item_Scripts SD%Complete: 100 SDComment: Items for a range of different items. See content below (in script) SDCategory: Items EndScriptData */ /* ContentData item_nether_wraith_beacon(i31742) Summons creatures for quest Becoming a Spellfire Tailor (q10832) item_flying_machine(i34060, i34061) Engineering crafted flying machines item_gor_dreks_ointment(i30175) Protecting Our Own(q10488) item_only_for_flight Items which should only useable while flying EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "Spell.h" /*##### # item_only_for_flight #####*/ enum eOnlyForFlight { SPELL_ARCANE_CHARGES = 45072 }; class item_only_for_flight : public ItemScript { public: item_only_for_flight() : ItemScript("item_only_for_flight") { } bool OnUse(Player* player, Item* item, SpellCastTargets const& /*targets*/) { uint32 itemId = item->GetEntry(); bool disabled = false; //for special scripts switch (itemId) { case 24538: if (player->GetAreaId() != 3628) disabled = true; break; case 34489: if (player->GetZoneId() != 4080) disabled = true; break; case 34475: if (const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(SPELL_ARCANE_CHARGES)) Spell::SendCastResult(player, spellInfo, 1, SPELL_FAILED_NOT_ON_GROUND); break; } // allow use in flight only if (player->isInFlight() && !disabled) return false; // error player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); return true; } }; /*##### # item_nether_wraith_beacon #####*/ class item_nether_wraith_beacon : public ItemScript { public: item_nether_wraith_beacon() : ItemScript("item_nether_wraith_beacon") { } bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const& /*targets*/) { if (player->GetQuestStatus(10832) == QUEST_STATUS_INCOMPLETE) { if (Creature* nether = player->SummonCreature(22408, player->GetPositionX(), player->GetPositionY()+20, player->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 180000)) nether->AI()->AttackStart(player); if (Creature* nether = player->SummonCreature(22408, player->GetPositionX(), player->GetPositionY()-20, player->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 180000)) nether->AI()->AttackStart(player); } return false; } }; /*##### # item_gor_dreks_ointment #####*/ class item_gor_dreks_ointment : public ItemScript { public: item_gor_dreks_ointment() : ItemScript("item_gor_dreks_ointment") { } bool OnUse(Player* player, Item* item, SpellCastTargets const& targets) { if (targets.GetUnitTarget() && targets.GetUnitTarget()->GetTypeId() == TYPEID_UNIT && targets.GetUnitTarget()->GetEntry() == 20748 && !targets.GetUnitTarget()->HasAura(32578)) return false; player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); return true; } }; /*##### # item_incendiary_explosives #####*/ class item_incendiary_explosives : public ItemScript { public: item_incendiary_explosives() : ItemScript("item_incendiary_explosives") { } bool OnUse(Player* player, Item* item, SpellCastTargets const & /*targets*/) { if (player->FindNearestCreature(26248, 15) || player->FindNearestCreature(26249, 15)) return false; else { player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); return true; } } }; /*##### # item_mysterious_egg #####*/ class item_mysterious_egg : public ItemScript { public: item_mysterious_egg() : ItemScript("item_mysterious_egg") { } bool OnExpire(Player* player, ItemTemplate const* /*pItemProto*/) { ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 39883, 1); // Cracked Egg if (msg == EQUIP_ERR_OK) player->StoreNewItem(dest, 39883, true, Item::GenerateItemRandomPropertyId(39883)); return true; } }; /*##### # item_disgusting_jar #####*/ class item_disgusting_jar : public ItemScript { public: item_disgusting_jar() : ItemScript("item_disgusting_jar") {} bool OnExpire(Player* player, ItemTemplate const* /*pItemProto*/) { ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 44718, 1); // Ripe Disgusting Jar if (msg == EQUIP_ERR_OK) player->StoreNewItem(dest, 44718, true, Item::GenerateItemRandomPropertyId(44718)); return true; } }; /*##### # item_pile_fake_furs #####*/ enum ePileFakeFur { GO_CARIBOU_TRAP_1 = 187982, GO_CARIBOU_TRAP_2 = 187995, GO_CARIBOU_TRAP_3 = 187996, GO_CARIBOU_TRAP_4 = 187997, GO_CARIBOU_TRAP_5 = 187998, GO_CARIBOU_TRAP_6 = 187999, GO_CARIBOU_TRAP_7 = 188000, GO_CARIBOU_TRAP_8 = 188001, GO_CARIBOU_TRAP_9 = 188002, GO_CARIBOU_TRAP_10 = 188003, GO_CARIBOU_TRAP_11 = 188004, GO_CARIBOU_TRAP_12 = 188005, GO_CARIBOU_TRAP_13 = 188006, GO_CARIBOU_TRAP_14 = 188007, GO_CARIBOU_TRAP_15 = 188008, GO_HIGH_QUALITY_FUR = 187983, NPC_NESINGWARY_TRAPPER = 25835 }; #define CaribouTrapsNum 15 const uint32 CaribouTraps[CaribouTrapsNum] = { GO_CARIBOU_TRAP_1, GO_CARIBOU_TRAP_2, GO_CARIBOU_TRAP_3, GO_CARIBOU_TRAP_4, GO_CARIBOU_TRAP_5, GO_CARIBOU_TRAP_6, GO_CARIBOU_TRAP_7, GO_CARIBOU_TRAP_8, GO_CARIBOU_TRAP_9, GO_CARIBOU_TRAP_10, GO_CARIBOU_TRAP_11, GO_CARIBOU_TRAP_12, GO_CARIBOU_TRAP_13, GO_CARIBOU_TRAP_14, GO_CARIBOU_TRAP_15, }; class item_pile_fake_furs : public ItemScript { public: item_pile_fake_furs() : ItemScript("item_pile_fake_furs") { } bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const & /*targets*/) { GameObject* go = NULL; for (uint8 i = 0; i < CaribouTrapsNum; ++i) { go = player->FindNearestGameObject(CaribouTraps[i], 5.0f); if (go) break; } if (!go) return false; if (go->FindNearestCreature(NPC_NESINGWARY_TRAPPER, 10.0f, true) || go->FindNearestCreature(NPC_NESINGWARY_TRAPPER, 10.0f, false) || go->FindNearestGameObject(GO_HIGH_QUALITY_FUR, 2.0f)) return true; float x, y, z; go->GetClosePoint(x, y, z, go->GetObjectSize() / 3, 7.0f); go->SummonGameObject(GO_HIGH_QUALITY_FUR, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0, 0, 0, 0, 0, 1000); if (TempSummon* summon = player->SummonCreature(NPC_NESINGWARY_TRAPPER, x, y, z, go->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 1000)) { summon->SetVisible(false); summon->SetReactState(REACT_PASSIVE); summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); } return false; } }; /*##### # item_petrov_cluster_bombs #####*/ enum ePetrovClusterBombs { SPELL_PETROV_BOMB = 42406, AREA_ID_SHATTERED_STRAITS = 4064, ZONE_ID_HOWLING = 495 }; class item_petrov_cluster_bombs : public ItemScript { public: item_petrov_cluster_bombs() : ItemScript("item_petrov_cluster_bombs") { } bool OnUse(Player* player, Item* item, const SpellCastTargets & /*targets*/) { if (player->GetZoneId() != ZONE_ID_HOWLING) return false; if (!player->GetTransport() || player->GetAreaId() != AREA_ID_SHATTERED_STRAITS) { player->SendEquipError(EQUIP_ERR_NONE, item, NULL); if (const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(SPELL_PETROV_BOMB)) Spell::SendCastResult(player, spellInfo, 1, SPELL_FAILED_NOT_HERE); return true; } return false; } }; /*###### # item_dehta_trap_smasher # For quest 11876, Help Those That Cannot Help Themselves ######*/ enum eHelpThemselves { QUEST_CANNOT_HELP_THEMSELVES = 11876, NPC_TRAPPED_MAMMOTH_CALF = 25850, GO_MAMMOTH_TRAP_1 = 188022, GO_MAMMOTH_TRAP_2 = 188024, GO_MAMMOTH_TRAP_3 = 188025, GO_MAMMOTH_TRAP_4 = 188026, GO_MAMMOTH_TRAP_5 = 188027, GO_MAMMOTH_TRAP_6 = 188028, GO_MAMMOTH_TRAP_7 = 188029, GO_MAMMOTH_TRAP_8 = 188030, GO_MAMMOTH_TRAP_9 = 188031, GO_MAMMOTH_TRAP_10 = 188032, GO_MAMMOTH_TRAP_11 = 188033, GO_MAMMOTH_TRAP_12 = 188034, GO_MAMMOTH_TRAP_13 = 188035, GO_MAMMOTH_TRAP_14 = 188036, GO_MAMMOTH_TRAP_15 = 188037, GO_MAMMOTH_TRAP_16 = 188038, GO_MAMMOTH_TRAP_17 = 188039, GO_MAMMOTH_TRAP_18 = 188040, GO_MAMMOTH_TRAP_19 = 188041, GO_MAMMOTH_TRAP_20 = 188042, GO_MAMMOTH_TRAP_21 = 188043, GO_MAMMOTH_TRAP_22 = 188044, }; #define MammothTrapsNum 22 const uint32 MammothTraps[MammothTrapsNum] = { GO_MAMMOTH_TRAP_1, GO_MAMMOTH_TRAP_2, GO_MAMMOTH_TRAP_3, GO_MAMMOTH_TRAP_4, GO_MAMMOTH_TRAP_5, GO_MAMMOTH_TRAP_6, GO_MAMMOTH_TRAP_7, GO_MAMMOTH_TRAP_8, GO_MAMMOTH_TRAP_9, GO_MAMMOTH_TRAP_10, GO_MAMMOTH_TRAP_11, GO_MAMMOTH_TRAP_12, GO_MAMMOTH_TRAP_13, GO_MAMMOTH_TRAP_14, GO_MAMMOTH_TRAP_15, GO_MAMMOTH_TRAP_16, GO_MAMMOTH_TRAP_17, GO_MAMMOTH_TRAP_18, GO_MAMMOTH_TRAP_19, GO_MAMMOTH_TRAP_20, GO_MAMMOTH_TRAP_21, GO_MAMMOTH_TRAP_22 }; class item_dehta_trap_smasher : public ItemScript { public: item_dehta_trap_smasher() : ItemScript("item_dehta_trap_smasher") { } bool OnUse(Player* player, Item* /*item*/, const SpellCastTargets & /*targets*/) { if (player->GetQuestStatus(QUEST_CANNOT_HELP_THEMSELVES) != QUEST_STATUS_INCOMPLETE) return false; Creature* pMammoth = player->FindNearestCreature(NPC_TRAPPED_MAMMOTH_CALF, 5.0f); if (!pMammoth) return false; GameObject* pTrap = NULL; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = player->FindNearestGameObject(MammothTraps[i], 11.0f); if (pTrap) { pMammoth->AI()->DoAction(1); pTrap->SetGoState(GO_STATE_READY); player->KilledMonsterCredit(NPC_TRAPPED_MAMMOTH_CALF, 0); return true; } } return false; } }; enum TheEmissary { QUEST_THE_EMISSARY = 11626, NPC_LEVIROTH = 26452 }; class item_trident_of_nazjan : public ItemScript { public: item_trident_of_nazjan() : ItemScript("item_Trident_of_Nazjan") { } bool OnUse(Player* player, Item* item, const SpellCastTargets & /*targets*/) { if (player->GetQuestStatus(QUEST_THE_EMISSARY) == QUEST_STATUS_INCOMPLETE) { if (Creature* pLeviroth = player->FindNearestCreature(NPC_LEVIROTH, 10.0f)) // spell range { pLeviroth->AI()->AttackStart(player); return false; } else player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); } else player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); return true; } }; enum eCapturedFrog { QUEST_THE_PERFECT_SPIES = 25444, NPC_VANIRAS_SENTRY_TOTEM = 40187 }; class item_captured_frog : public ItemScript { public: item_captured_frog() : ItemScript("item_captured_frog") { } bool OnUse(Player* player, Item* item, SpellCastTargets const& /*targets*/) { if (player->GetQuestStatus(QUEST_THE_PERFECT_SPIES) == QUEST_STATUS_INCOMPLETE) { if (player->FindNearestCreature(NPC_VANIRAS_SENTRY_TOTEM, 10.0f)) return false; else player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); } else player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); return true; } }; void AddSC_item_scripts() { new item_only_for_flight(); new item_nether_wraith_beacon(); new item_gor_dreks_ointment(); new item_incendiary_explosives(); new item_mysterious_egg(); new item_disgusting_jar(); new item_pile_fake_furs(); new item_petrov_cluster_bombs(); new item_dehta_trap_smasher(); new item_trident_of_nazjan(); new item_captured_frog(); }
33.785047
194
0.605878
499453466
d89125ee5368c246f30467fdbabed969c6a2392a
3,816
cpp
C++
LibTDE/SignalData.cpp
ebragge/LibTDE
af3b16e7166cf66d5c96a5c9587cca2ba28c6a7d
[ "BSD-3-Clause" ]
6
2016-01-28T10:45:22.000Z
2022-02-22T07:19:40.000Z
LibTDE/SignalData.cpp
AlfonsoDR/LibTDE
af3b16e7166cf66d5c96a5c9587cca2ba28c6a7d
[ "BSD-3-Clause" ]
null
null
null
LibTDE/SignalData.cpp
AlfonsoDR/LibTDE
af3b16e7166cf66d5c96a5c9587cca2ba28c6a7d
[ "BSD-3-Clause" ]
3
2017-11-11T16:00:12.000Z
2021-06-19T21:10:24.000Z
#include "pch.h" #include "SignalData.h" using namespace TimeDelayEstimation; SignalData::SignalData(const std::vector<SignalType>* channel0, const std::vector<SignalType>* channel1, bool copyData) : m_copy(copyData), m_min(0), m_max(min(channel0->size(),channel1->size())), m_alignment(0) { if (copyData) { m_channel0 = new std::vector<SignalType>(*channel0); m_channel1 = new std::vector<SignalType>(*channel1); } else { m_channel0 = channel0; m_channel1 = channel1; } } SignalData::SignalData(const std::vector<SignalType>* channel0, const std::vector<SignalType>* channel1, std::size_t minPos, std::size_t maxPos, bool copyData) : m_copy(copyData), m_min(minPos), m_max(maxPos), m_alignment(0) { if (copyData) { m_channel0 = new std::vector<SignalType>(*channel0); m_channel1 = new std::vector<SignalType>(*channel1); } else { m_channel0 = channel0; m_channel1 = channel1; } if (minPos >= channel0->size() || minPos >= channel1->size()) m_min = min(channel0->size() - 1, channel1->size() - 1); if (maxPos >= channel0->size() || maxPos >= channel1->size()) m_max = min(channel0->size() - 1, channel1->size() - 1); } SignalData::~SignalData() { if (m_copy) { delete m_channel0; delete m_channel1; } } SignalValue SignalData::Value(size_t position) const { if (position < 0 || position >= m_channel0->size()) return SignalZero; return m_channel0->at(position).value; } UINT64 SignalData::Delta(UINT64 i0, UINT64 i1) const { return i0 > i1 ? i0 - i1 : i1 - i0; } bool SignalData::DataItem0(size_t position, AudioDataItem* item) const { if (position < 0 || position >= m_channel0->size()) return false; *item = m_channel0->at(position); return true; } bool SignalData::DataItem1(size_t position, AudioDataItem* item, UINT64 ts0) const { if (position < 0 || position >= m_channel1->size()) return false; if (ts0 == 0) { *item = m_channel1->at(position); return true; } UINT64 ts1 = m_channel1->at(position).timestamp; if (ts0 == ts1) { *item = m_channel1->at(position); return true; } if (ts0 < ts1) { size_t p = position; while (p > 0 && Delta(ts0, m_channel1->at(p - 1).timestamp) < Delta(ts0, m_channel1->at(p).timestamp)) { p--; } if (p < (m_channel1->size() - 1) && Delta(ts0, m_channel1->at(p).timestamp) >= Delta(ts0, m_channel1->at(p + 1).timestamp)) { p++; } *item = m_channel1->at(p); return true; } else { size_t p = position; size_t sz = m_channel1->size() - 1; while (p < sz && Delta(ts0, m_channel1->at(p + 1).timestamp) < Delta(ts0, m_channel1->at(p).timestamp)) { p++; } if (p > 0 && Delta(ts0, m_channel1->at(p).timestamp) >= Delta(ts0, m_channel1->at(p - 1).timestamp)) { p--; } *item = m_channel1->at(p); return true; } } bool SignalData::CalculateAlignment(size_t position, DelayType* alignment, UINT64* delta) { DelayType p = (DelayType)position; if (position >= m_channel0->size()) return false; if (position >= m_channel1->size()) return false; UINT64 ts0 = m_channel0->at(position).timestamp; UINT64 ts1 = m_channel1->at(position).timestamp; if (ts0 > ts1) { while (m_channel1->at(p).timestamp < ts0) { if (++p >= (DelayType)m_channel1->size()) return false; } if (p > 0 && ts0 - m_channel1->at(p - 1).timestamp > m_channel1->at(p).timestamp - ts0) { p--; } } else if (ts0 < ts1) { while (m_channel1->at(p).timestamp > ts0) { if (--p < 0) return false; } if (p < (DelayType)(m_channel1->size() - 1) && ts0 - m_channel1->at(p).timestamp > m_channel1->at(p + 1).timestamp - ts0) { p++; } } if (alignment != NULL) *alignment = p - (DelayType)position; if (delta != NULL) *delta = m_channel1->at(p).timestamp - ts0; return true; }
29.8125
135
0.635744
ebragge
d8922e71872378a1d278356e660dbc33a567c5e6
1,611
cpp
C++
intuit_09.cpp
gurleen-kaur1313/6Companies30Days
7e789173dfad08039ca908fbec18cab1a74b4d5f
[ "MIT" ]
null
null
null
intuit_09.cpp
gurleen-kaur1313/6Companies30Days
7e789173dfad08039ca908fbec18cab1a74b4d5f
[ "MIT" ]
null
null
null
intuit_09.cpp
gurleen-kaur1313/6Companies30Days
7e789173dfad08039ca908fbec18cab1a74b4d5f
[ "MIT" ]
null
null
null
/* problem link: https://leetcode.com/problems/pacific-atlantic-water-flow/ */ class Solution { public: bool isValid(int m , int n , int x, int y){ if(x<0||x>=m || y<0||y>=n)return false; return true; } void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited, int x ,int y){ int m = heights.size(); int n = heights[0].size(); visited[x][y] = true; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; for(int i = 0 ; i < 4; i++){ if(isValid(m, n , x + dx[i] , y + dy[i]) && !visited[x + dx[i]][y+dy[i]] && heights[x][y]<=heights[x + dx[i]][y + dy[i]]) { dfs(heights, visited, x + dx[i], y + dy[i]); } } } vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) { vector<vector<int>> ans; int m = heights.size(); int n = heights[0].size(); vector<vector<bool>> visPac(m , vector<bool>(n, false)); vector<vector<bool>> visAtl(m , vector<bool>(n, false)); for(int i = 0 ; i < m ; i++){ dfs(heights, visPac, i , 0); dfs(heights, visAtl, i , n-1); } for(int i = 0 ; i < n ; i++){ dfs(heights, visPac, 0 , i); dfs(heights, visAtl, m-1 , i); } for(int i = 0; i < m ; i++){ for(int j = 0; j < n ; j++){ if(visPac[i][j] && visAtl[i][j]){ ans.push_back({i, j}); } } } return ans; } };
25.571429
88
0.428305
gurleen-kaur1313
d896768a15992e731231d19fa221ba67e27adba5
507
hpp
C++
src/MenuController.hpp
adileo/rpg-game-cpp
f43f231b0bdb7f4618ece8174d08cf26ab3125c6
[ "MIT" ]
null
null
null
src/MenuController.hpp
adileo/rpg-game-cpp
f43f231b0bdb7f4618ece8174d08cf26ab3125c6
[ "MIT" ]
null
null
null
src/MenuController.hpp
adileo/rpg-game-cpp
f43f231b0bdb7f4618ece8174d08cf26ab3125c6
[ "MIT" ]
null
null
null
/* * MenuController.hpp * * Created on: 18 giu 2016 * Author: adileobarone * * Si occupa di instanziare il menรน di gioco iniziale utilizzabile trabite I/O * */ #ifndef MENUCONTROLLER_HPP_ #define MENUCONTROLLER_HPP_ #include <iostream> #include "GameManager.hpp" #include "lib/easylogging++.hpp" using namespace std; class MenuController{ GameManager* gm; public: MenuController(); void start(); private: void handleInput(string s); int inMenu; }; #endif /* MENUCONTROLLER_HPP_ */
15.363636
78
0.721893
adileo
d897ebeceeb9bc6dc3029a1b476a99bc2e053d0d
677
hpp
C++
project/include/Math/Vec4.hpp
smbss1/Foxecs
88b271b3614c4cefffa3f3bd7530d48698edea46
[ "MIT" ]
null
null
null
project/include/Math/Vec4.hpp
smbss1/Foxecs
88b271b3614c4cefffa3f3bd7530d48698edea46
[ "MIT" ]
null
null
null
project/include/Math/Vec4.hpp
smbss1/Foxecs
88b271b3614c4cefffa3f3bd7530d48698edea46
[ "MIT" ]
null
null
null
#pragma once class Vec4 { public: Vec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) {} Vec4(float x, float y, float z) : x(x), y(y), z(z), w(0.0f) {} Vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {} Vec4 operator+(Vec4 const& v) const { return Vec4( x + v.x, y + v.y, z + v.z, w + v.w); } Vec4 operator+=(Vec4 const& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } Vec4 operator-(Vec4 const& v) const { return Vec4( x - v.x, y - v.y, z - v.z, w - v.w); } Vec4 operator-=(Vec4 const& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } float x, y, z, w; };
11.283333
41
0.454948
smbss1
d89e487c8fd753bdbe29856a9658db08c740f766
4,146
cxx
C++
MITK/Modules/CoreIO/Internal/niftkLabelMapWriter.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Modules/CoreIO/Internal/niftkLabelMapWriter.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Modules/CoreIO/Internal/niftkLabelMapWriter.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "niftkLabelMapWriter.h" #include <fstream> #include <vtkSmartPointer.h> #include <mitkAbstractFileWriter.h> #include <mitkCustomMimeType.h> #include <mitkLogMacros.h> #include <mitkCommon.h> #include "niftkCoreIOMimeTypes.h" #include "niftkLookupTableContainer.h" namespace niftk { //----------------------------------------------------------------------------- LabelMapWriter::LabelMapWriter() : mitk::AbstractFileWriter(LookupTableContainer::GetStaticNameOfClass(), mitk::CustomMimeType(CoreIOMimeTypes::LABELMAP_MIMETYPE_NAME()), CoreIOMimeTypes::LABELMAP_MIMETYPE_DESCRIPTION()) { RegisterService(); } //----------------------------------------------------------------------------- LabelMapWriter::LabelMapWriter(const LabelMapWriter & other) : mitk::AbstractFileWriter(other) { } //----------------------------------------------------------------------------- LabelMapWriter::~LabelMapWriter() { } //----------------------------------------------------------------------------- LabelMapWriter * LabelMapWriter::Clone() const { return new LabelMapWriter(*this); } //----------------------------------------------------------------------------- void LabelMapWriter::Write() { std::ostream* out; std::ofstream outStream; if (this->GetOutputStream()) { out = this->GetOutputStream(); } else { outStream.open(this->GetOutputLocation().c_str()); out = &outStream; } if (!out->good()) { MITK_ERROR << "Unable to write to stream."; } std::string outputLocation; LookupTableContainer::ConstPointer lutContainer = dynamic_cast<const LookupTableContainer*>(this->GetInput()); try { const std::string& currLocale = setlocale( LC_ALL, NULL ); const std::string& locale = "C"; setlocale(LC_ALL, locale.c_str()); std::locale previousLocale(out->getloc()); std::locale I("C"); out->imbue(I); // const_cast here because vtk is stupid and vtkLookupTable->GetTableValue() is not a const function vtkLookupTable* unconstTable = const_cast<vtkLookupTable*> (lutContainer->GetLookupTable()); WriteLabelMap(lutContainer->GetLabels(), unconstTable); out->imbue( previousLocale ); setlocale(LC_ALL, currLocale.c_str()); } catch(const std::exception& e) { MITK_ERROR <<"Exception caught while writing file " <<outputLocation <<": " <<e.what(); mitkThrow() << e.what(); } } //----------------------------------------------------------------------------- void LabelMapWriter::WriteLabelMap( LabeledLookupTableProperty::LabelListType labels, vtkLookupTable* lookupTable) const { if (labels.empty() || lookupTable == NULL) { mitkThrow() << "Labels or LookupTable not set."; } std::ofstream outfile(this->GetOutputLocation().c_str(), std::ofstream::binary); for (unsigned int i = 0; i < labels.size(); i++) { int value = labels.at(i).first; QString name = labels.at(i).second; // in the slicer file format white space is used to denote space betweeen values, // replacing all white spaces/empty strings with a character to ensure proper IO. if (name.isEmpty()) { name = "*"; } else { name.replace(" ", "*"); } vtkIdType index = lookupTable->GetIndex(value); double* rgba = lookupTable->GetTableValue(index); int r = rgba[0] * 255; int g = rgba[1] * 255; int b = rgba[2] * 255; int a = rgba[3] * 255; outfile << value << " " << name.toStdString() << " "<< r << " " << g << " " << b << " " << a << "\n"; } outfile.flush(); outfile.close(); } }
26.240506
105
0.561264
NifTK
d89efcc780d96c773dca19db77824bd617e7a0c2
700
hpp
C++
bsengine/src/bstorm/path_const.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/path_const.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/path_const.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once namespace bstorm { constexpr wchar_t* FREE_PLAYER_DIR = L"script/player"; constexpr wchar_t* DEFAULT_SYSTEM_PATH = L"script/default_system/Default_System.txt"; constexpr wchar_t* DEFAULT_ITEM_DATA_PATH = L"resource/script/Default_ItemData.txt"; constexpr wchar_t* DEFAULT_PACKAGE_PATH = L"resource/script/Default_Package.txt"; constexpr wchar_t* DEFAULT_PACKAGE_ARGS_COMMON_DATA_AREA_NAME = L"__DEFAULT_PACKAGE_ARGS__"; constexpr wchar_t* SYSTEM_STG_DIGIT_IMG_PATH = L"resource/img/System_Stg_Digit.png"; constexpr wchar_t* SYSTEM_SINGLE_STAGE_PATH = L"resource/script/System_SingleStage.txt"; constexpr wchar_t* SYSTEM_PLURAL_STAGE_PATH = L"resource/script/System_PluralStage.txt"; }
46.666667
92
0.842857
At-sushi
d89f7872feeebeadef858584d43ab369b8ef7e38
3,331
cpp
C++
QScreenshot/SignInDialog.cpp
dbautsch/QScreenshot
80fc3113a342eb4498d8f24aa77230a0d8bbc170
[ "MIT" ]
2
2018-04-10T06:32:26.000Z
2021-04-23T14:50:04.000Z
QScreenshot/SignInDialog.cpp
dbautsch/QScreenshot
80fc3113a342eb4498d8f24aa77230a0d8bbc170
[ "MIT" ]
2
2016-06-10T12:55:45.000Z
2016-07-08T14:25:48.000Z
QScreenshot/SignInDialog.cpp
dbautsch/QScreenshot
80fc3113a342eb4498d8f24aa77230a0d8bbc170
[ "MIT" ]
1
2018-12-07T06:02:24.000Z
2018-12-07T06:02:24.000Z
/*! * Copyright (c) 2016 Dawid Bautsch dawid.bautsch@gmail.com * 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 "SignInDialog.h" #include "ui_SignInDialog.h" #include "ImageUploaders/ImageUploader.h" #include <QMessageBox> #include <QDebug> SignInDialog::SignInDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignInDialog) { ui->setupUi(this); ShowServiceCombo(false); } SignInDialog::~SignInDialog() { delete ui; } void SignInDialog::showEvent(QShowEvent *) { if (ui->serviceCombo->isVisible()) FillServicesCombo(); } void SignInDialog::closeEvent(QCloseEvent *) { ui->useLoginPasswordBox->setVisible(true); ui->loginEdit->setEnabled(true); ui->passwordEdit->setEnabled(true); ShowServiceCombo(false); strService.clear(); } void SignInDialog::ShowUseLoginPasswordBox(bool bShow) { ui->useLoginPasswordBox->setVisible(bShow); ui->loginEdit->setEnabled(!bShow); ui->passwordEdit->setEnabled(!bShow); } void SignInDialog::ShowServiceCombo(bool bShow) { //!< Show an extra control with the list of available services. //!< Used only when user want to add new service data to the list. ui->label_4->setVisible(bShow); ui->serviceCombo->setVisible(bShow); } void SignInDialog::SetServiceLogo(const QString & strResourcePath) { ui->logoWidget->setStyleSheet("QWidget{background-image: url(" + strResourcePath + "); background-repeat:none;}"); } void SignInDialog::on_saveButton_clicked() { //!< save login/password if (ui->loginEdit->text().trimmed().isEmpty() || ui->passwordEdit->text().trimmed().isEmpty()) { QMessageBox::information(this, tr("Save password"), tr("Please fill all requiered fields.")); return; } if (ui->serviceCombo->isVisible() && ui->serviceCombo->currentIndex() < 0) { QMessageBox::information(this, tr("Save password"), tr("Please select web service name.")); return; } close(); } QString SignInDialog::LoginInputBox() { //!< Get the login entered by user. return ui->loginEdit->text(); } QString SignInDialog::PasswordInputBox() { //!< Get the password entered by user. return ui->passwordEdit->text(); } QString SignInDialog::ServiceBox() { //!< Get the service choosen by user. return ui->serviceCombo->currentText(); } bool SignInDialog::UsePasswordsShelter() { return ui->usePasswordsShelterBox->isChecked(); } void SignInDialog::FillServicesCombo() { ServicesList services = ImageUploader::GetServices(); ui->serviceCombo->clear(); foreach (const QString & strService, services) { ui->serviceCombo->addItem(strService); } } void SignInDialog::SetLogin(const QString & strLogin) { ui->loginEdit->setText(strLogin); } void SignInDialog::SetService(const QString & strService) { this->strService = strService; }
23.624113
118
0.697688
dbautsch
d8acc3eb4c4dfbadbc2ad56f0803e151ed9ef77e
704
cpp
C++
employee/testadmin.cpp
AKoudounis/refactored-journey
81719c57104f14b141f0f7cd2aa805f9007ed79e
[ "MIT" ]
null
null
null
employee/testadmin.cpp
AKoudounis/refactored-journey
81719c57104f14b141f0f7cd2aa805f9007ed79e
[ "MIT" ]
null
null
null
employee/testadmin.cpp
AKoudounis/refactored-journey
81719c57104f14b141f0f7cd2aa805f9007ed79e
[ "MIT" ]
null
null
null
#include<iostream> #include โ€œadminstaff.hโ€ using namespace std; int main() { AdminStaff emp(45565, โ€œA.Bโ€, 500, 12.0); // input data emp.setAddress(โ€œ1455 Maisonneuve, Montrealโ€); emp.setPhone(โ€œ514-123-11111โ€); emp.setEmail(โ€œemp@concordia.caโ€); emp.print(); cout << emp.getAddress() << endl; cout << emp.getPhone() << endl; cout << emp.getEmail() << endl; cout << emp.getVacation() << endl; emp.setHoursWorked(450); // number of hours modified emp.setHourlyRate(15); // hourly rate modified emp.print(); // print salary of admin staff employee return 0; }
28.16
75
0.549716
AKoudounis
d8af92be630406d6381cf44c7200438822a7678d
18,233
cpp
C++
src/ContextAndroid.cpp
rekola/canvas
eabaaa7ae84548bf7d747152d64f4381c9277fee
[ "MIT" ]
28
2015-12-23T02:19:58.000Z
2022-01-22T00:52:11.000Z
src/ContextAndroid.cpp
modulesio/canvas
03c52b2301841083c9b70e91c572680cccd10522
[ "MIT" ]
89
2015-12-23T01:35:24.000Z
2019-02-18T20:24:16.000Z
src/ContextAndroid.cpp
avaer/canvas
03c52b2301841083c9b70e91c572680cccd10522
[ "MIT" ]
7
2016-11-11T04:46:10.000Z
2022-01-29T03:48:36.000Z
#include "ContextAndroid.h" #include <errno.h> #include <cassert> using namespace std; using namespace canvas; AndroidCache::AndroidCache(JNIEnv * myEnv, jobject _assetManager) { myEnv->GetJavaVM(&javaVM); assetManager = myEnv->NewGlobalRef(_assetManager); frameClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("com/sometrik/framework/FrameWork")); typefaceClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Typeface")); canvasClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Canvas")); assetManagerClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/content/res/AssetManager")); factoryClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/BitmapFactory")); bitmapClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Bitmap")); paintClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Paint")); pathClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Path")); paintStyleClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Paint$Style")); alignClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Paint$Align")); bitmapConfigClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Bitmap$Config")); field_argb_8888 = myEnv->GetStaticFieldID(bitmapConfigClass, "ARGB_8888", "Landroid/graphics/Bitmap$Config;"); // field_rgb_565 = myEnv->GetStaticFieldID(bitmapConfigClass, "RGB_565", "Landroid/graphics/Bitmap$Config;"); field_alpha_8 = myEnv->GetStaticFieldID(bitmapConfigClass, "ALPHA_8", "Landroid/graphics/Bitmap$Config;"); rectFClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/RectF")); rectClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Rect")); bitmapOptionsClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/BitmapFactory$Options")); fileClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/File")); fileInputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/FileInputStream")); stringClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/lang/String")); charsetString = (jstring) myEnv->NewGlobalRef(myEnv->NewStringUTF("UTF-8")); linearGradientClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/LinearGradient")); shaderTileModeClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/graphics/Shader$TileMode")); shaderTileModeMirrorField = myEnv->GetStaticFieldID(shaderTileModeClass, "MIRROR", "Landroid/graphics/Shader$TileMode;"); measureAscentMethod = myEnv->GetMethodID(paintClass, "ascent", "()F"); measureDescentMethod = myEnv->GetMethodID(paintClass, "descent", "()F"); measureTextMethod = myEnv->GetMethodID(paintClass, "measureText", "(Ljava/lang/String;)F"); setAlphaMethod = myEnv->GetMethodID(paintClass, "setAlpha", "(I)V"); setTypefaceMethod = myEnv->GetMethodID(paintClass, "setTypeface", "(Landroid/graphics/Typeface;)Landroid/graphics/Typeface;"); textAlignMethod = myEnv->GetMethodID(paintClass, "setTextAlign", "(Landroid/graphics/Paint$Align;)V"); paintSetColorMethod = myEnv->GetMethodID(paintClass, "setColor", "(I)V"); paintSetStyleMethod = myEnv->GetMethodID(paintClass, "setStyle", "(Landroid/graphics/Paint$Style;)V"); paintSetStrokeWidthMethod = myEnv->GetMethodID(paintClass, "setStrokeWidth", "(F)V"); paintSetStrokeJoinMethod = myEnv->GetMethodID(paintClass, "setStrokeJoin", "(Landroid/graphics/Paint$Join;)V"); paintConstructor = myEnv->GetMethodID(paintClass, "<init>", "()V"); paintSetAntiAliasMethod = myEnv->GetMethodID(paintClass, "setAntiAlias", "(Z)V"); textAlignMethod = myEnv->GetMethodID(paintClass, "setTextAlign", "(Landroid/graphics/Paint$Align;)V"); paintSetShaderMethod = myEnv->GetMethodID(paintClass, "setShader", "(Landroid/graphics/Shader;)Landroid/graphics/Shader;"); typefaceCreator = myEnv->GetStaticMethodID(typefaceClass, "create", "(Ljava/lang/String;I)Landroid/graphics/Typeface;"); managerOpenMethod = myEnv->GetMethodID(assetManagerClass, "open", "(Ljava/lang/String;)Ljava/io/InputStream;"); bitmapCreateMethod = myEnv->GetStaticMethodID(bitmapClass, "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;"); bitmapCreateMethod2 = myEnv->GetStaticMethodID(bitmapClass, "createBitmap", "([IIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;"); bitmapCreateScaledMethod = myEnv->GetStaticMethodID(bitmapClass, "createScaledBitmap", "(Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;"); canvasConstructor = myEnv->GetMethodID(canvasClass, "<init>", "(Landroid/graphics/Bitmap;)V"); factoryDecodeMethod = myEnv->GetStaticMethodID(factoryClass, "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Bitmap;"); factoryDecodeMethod2 = myEnv->GetStaticMethodID(factoryClass, "decodeStream", "(Ljava/io/InputStream;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); bitmapCopyMethod = myEnv->GetMethodID(bitmapClass, "copy", "(Landroid/graphics/Bitmap$Config;Z)Landroid/graphics/Bitmap;"); pathMoveToMethod = myEnv->GetMethodID(pathClass, "moveTo", "(FF)V"); pathConstructor = myEnv->GetMethodID(pathClass, "<init>", "()V"); canvasTextDrawMethod = myEnv->GetMethodID(canvasClass, "drawText", "(Ljava/lang/String;FFLandroid/graphics/Paint;)V"); pathLineToMethod = myEnv->GetMethodID(pathClass, "lineTo", "(FF)V"); pathCloseMethod = myEnv->GetMethodID(pathClass, "close", "()V"); pathArcToMethod = myEnv->GetMethodID(pathClass, "arcTo", "(Landroid/graphics/RectF;FF)V"); canvasPathDrawMethod = myEnv->GetMethodID(canvasClass, "drawPath", "(Landroid/graphics/Path;Landroid/graphics/Paint;)V"); rectFConstructor = myEnv->GetMethodID(rectFClass, "<init>", "(FFFF)V"); rectConstructor = myEnv->GetMethodID(rectClass, "<init>", "(IIII)V"); paintSetShadowMethod = myEnv->GetMethodID(paintClass, "setShadowLayer", "(FFFI)V"); paintSetTextSizeMethod = myEnv->GetMethodID(paintClass, "setTextSize", "(F)V"); canvasBitmapDrawMethod = myEnv->GetMethodID(canvasClass, "drawBitmap", "(Landroid/graphics/Bitmap;FFLandroid/graphics/Paint;)V"); canvasBitmapDrawMethod2 = myEnv->GetMethodID(canvasClass, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Rect;Landroid/graphics/RectF;Landroid/graphics/Paint;)V"); factoryDecodeByteMethod = myEnv->GetStaticMethodID(factoryClass, "decodeByteArray", "([BII)Landroid/graphics/Bitmap;"); bitmapGetWidthMethod = myEnv->GetMethodID(bitmapClass, "getWidth", "()I"); bitmapGetHeightMethod = myEnv->GetMethodID(bitmapClass, "getHeight", "()I"); bitmapOptionsConstructor = myEnv->GetMethodID(bitmapOptionsClass, "<init>", "()V"); fileConstructor = myEnv->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V"); fileInputStreamConstructor = myEnv->GetMethodID(fileInputStreamClass, "<init>", "(Ljava/io/File;)V"); stringConstructor = myEnv->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V"); stringGetBytesMethod = myEnv->GetMethodID(stringClass, "getBytes", "()[B"); stringConstructor2 = myEnv->GetMethodID(stringClass, "<init>", "()V"); stringByteConstructor = myEnv->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V"); linearGradientConstructor = myEnv->GetMethodID(linearGradientClass, "<init>", "(FFFFIILandroid/graphics/Shader$TileMode;)V"); optionsMutableField = myEnv->GetFieldID(bitmapOptionsClass, "inMutable", "Z"); alignEnumRight = myEnv->GetStaticFieldID(alignClass, "RIGHT", "Landroid/graphics/Paint$Align;"); alignEnumLeft = myEnv->GetStaticFieldID(alignClass, "LEFT", "Landroid/graphics/Paint$Align;"); alignEnumCenter = myEnv->GetStaticFieldID(alignClass, "CENTER", "Landroid/graphics/Paint$Align;"); factoryOptions = myEnv->NewGlobalRef(myEnv->NewObject(bitmapOptionsClass, bitmapOptionsConstructor)); myEnv->SetBooleanField(factoryOptions, optionsMutableField, JNI_TRUE); paintStyleEnumStroke = myEnv->GetStaticFieldID(myEnv->FindClass("android/graphics/Paint$Style"), "STROKE", "Landroid/graphics/Paint$Style;"); paintStyleEnumFill = myEnv->GetStaticFieldID(myEnv->FindClass("android/graphics/Paint$Style"), "FILL", "Landroid/graphics/Paint$Style;"); auto joinClass = (jclass) myEnv->FindClass("android/graphics/Paint$Join"); joinField_ROUND = myEnv->NewGlobalRef(myEnv->GetStaticObjectField(joinClass, myEnv->GetStaticFieldID(joinClass, "ROUND", "Landroid/graphics/Paint$Join;"))); myEnv->DeleteLocalRef(joinClass); } AndroidCache::~AndroidCache() { auto myEnv = getEnv(); myEnv->DeleteGlobalRef(factoryOptions); myEnv->DeleteGlobalRef(assetManager); myEnv->DeleteGlobalRef(typefaceClass); myEnv->DeleteGlobalRef(rectFClass); myEnv->DeleteGlobalRef(rectClass); myEnv->DeleteGlobalRef(canvasClass); myEnv->DeleteGlobalRef(paintClass); myEnv->DeleteGlobalRef(pathClass); myEnv->DeleteGlobalRef(bitmapClass); myEnv->DeleteGlobalRef(assetManagerClass); myEnv->DeleteGlobalRef(factoryClass); myEnv->DeleteGlobalRef(paintStyleClass); myEnv->DeleteGlobalRef(alignClass); myEnv->DeleteGlobalRef(bitmapConfigClass); myEnv->DeleteGlobalRef(bitmapOptionsClass); myEnv->DeleteGlobalRef(fileClass); myEnv->DeleteGlobalRef(fileInputStreamClass); myEnv->DeleteGlobalRef(stringClass); myEnv->DeleteGlobalRef(charsetString); myEnv->DeleteGlobalRef(linearGradientClass); myEnv->DeleteGlobalRef(joinField_ROUND); } AndroidSurface::AndroidSurface(AndroidCache * _cache, unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, unsigned int _num_channels) : Surface(_logical_width, _logical_height, _actual_width, _actual_height, _num_channels), cache(_cache), paint(_cache) { // creates an empty canvas if (_actual_width && _actual_height) { __android_log_print(ANDROID_LOG_INFO, "Sometrik", "AndroidSurface widthheight constructor called with width : height %u : %u", _actual_width, _actual_height); JNIEnv * env = cache->getEnv(); // set bitmap config according to internalformat jobject argbObject = createBitmapConfig(_num_channels); jobject localBitmap = env->CallStaticObjectMethod(cache->bitmapClass, cache->bitmapCreateMethod, _actual_width, _actual_height, argbObject); if (localBitmap) { bitmap = (jobject) env->NewGlobalRef(localBitmap); env->DeleteLocalRef(localBitmap); } else { bitmap = 0; } env->DeleteLocalRef(argbObject); } } AndroidSurface::AndroidSurface(AndroidCache * _cache, const ImageData & image) : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), image.getNumChannels() == 1 ? 1 : 4), cache(_cache), paint(_cache) { JNIEnv * env = cache->getEnv(); // creates a surface with width, height and contents from image jobject localBitmap = (jobject) env->NewGlobalRef(imageToBitmap(image)); if (localBitmap) { bitmap = (jobject) env->NewGlobalRef(localBitmap); env->DeleteLocalRef(localBitmap); } } AndroidSurface::AndroidSurface(AndroidCache * _cache, const std::string & filename) : Surface(0, 0, 0, 0, 0), cache(_cache), paint(_cache) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Surface filename constructor"); JNIEnv * env = cache->getEnv(); // Get inputStream from the picture(filename) jstring jfilename = env->NewStringUTF(filename.c_str()); jobject inputStream = env->CallObjectMethod(cache->getAssetManager(), cache->managerOpenMethod, jfilename); env->DeleteLocalRef(jfilename); // Create a bitmap from the inputStream jobject localBitmap = env->CallStaticObjectMethod(cache->factoryClass, cache->factoryDecodeMethod2, inputStream, NULL, cache->getFactoryOptions()); bitmap = (jobject) env->NewGlobalRef(localBitmap); env->DeleteLocalRef(localBitmap); int bitmapWidth = env->CallIntMethod(bitmap, cache->bitmapGetWidthMethod); int bitmapHeigth = env->CallIntMethod(bitmap, cache->bitmapGetHeightMethod); Surface::resize(bitmapWidth, bitmapHeigth, bitmapWidth, bitmapHeigth, 4); env->DeleteLocalRef(inputStream); } AndroidSurface::AndroidSurface(AndroidCache * _cache, const unsigned char * buffer, size_t size) : Surface(0, 0, 0, 0, 0), cache(_cache), paint(_cache) { JNIEnv * env = cache->getEnv(); int arraySize = size; jbyteArray array = env->NewByteArray(arraySize); env->SetByteArrayRegion(array, 0, arraySize, (const jbyte*) buffer); jobject firstBitmap = env->CallStaticObjectMethod(cache->factoryClass, cache->factoryDecodeByteMethod, array, 0, arraySize); // make this with factory options instead jobject argbObject = createBitmapConfig(4); jobject localBitmap = env->CallObjectMethod(firstBitmap, cache->bitmapCopyMethod, argbObject, JNI_TRUE); bitmap = (jobject) env->NewGlobalRef(localBitmap); env->DeleteLocalRef(localBitmap); int bitmapWidth = env->CallIntMethod(bitmap, cache->bitmapGetWidthMethod); int bitmapHeigth = env->CallIntMethod(bitmap, cache->bitmapGetHeightMethod); Surface::resize(bitmapWidth, bitmapHeigth, bitmapWidth, bitmapHeigth, 4); env->DeleteLocalRef(argbObject); env->DeleteLocalRef(firstBitmap); env->DeleteLocalRef(array); } jobject AndroidSurface::createBitmapConfig(unsigned int num_channels) { JNIEnv * env = cache->getEnv(); if (num_channels == 1) { return env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_alpha_8); } else { return env->GetStaticObjectField(cache->bitmapConfigClass, cache->field_argb_8888); } } jobject AndroidSurface::imageToBitmap(const ImageData & img) { JNIEnv * env = cache->getEnv(); unsigned int n = img.getWidth() * img.getHeight(); jintArray jarray = env->NewIntArray(n); if (img.getNumChannels() == 4) { env->SetIntArrayRegion(jarray, 0, n, (const jint*)img.getData()); } else { const unsigned char * input_data = img.getData(); unique_ptr<unsigned int[]> tmp(new unsigned int[n]); for (unsigned int i = 0; i < n; i++) { unsigned char r = *input_data++; unsigned char g = img.getNumChannels() >= 2 ? *input_data++ : r; unsigned char b = img.getNumChannels() >= 3 ? *input_data++ : g; unsigned char a = img.getNumChannels() >= 4 ? *input_data++ : 0xff; tmp[i] = (r) | (g << 8) | (b << 16) | (a << 24); } env->SetIntArrayRegion(jarray, 0, n, (const jint*)tmp.get()); } jobject argbObject = createBitmapConfig(4); jobject drawableBitmap = env->CallStaticObjectMethod(cache->bitmapClass, cache->bitmapCreateMethod2, jarray, img.getWidth(), img.getHeight(), argbObject); if (env->ExceptionCheck()) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "exception on imageToBitmap"); env->ExceptionClear(); } env->DeleteLocalRef(argbObject); env->DeleteLocalRef(jarray); return drawableBitmap; } static int android_read(void* cookie, char* buf, int size) { return AAsset_read((AAsset*)cookie, buf, size); } static int android_write(void* cookie, const char* buf, int size) { return EACCES; // can't provide write access to the apk } static fpos_t android_seek(void* cookie, fpos_t offset, int whence) { return AAsset_seek((AAsset*)cookie, offset, whence); } static int android_close(void* cookie) { AAsset_close((AAsset*)cookie); return 0; } class AndroidImage : public Image { public: AndroidImage(AAssetManager * _asset_manager, float _display_scale) : Image(_display_scale), asset_manager(_asset_manager) { } AndroidImage(AAssetManager * _asset_manager, const std::string & filename, float _display_scale) : Image(filename, _display_scale), asset_manager(_asset_manager) { } AndroidImage(AAssetManager * _asset_manager, const unsigned char * _data, unsigned int _width, unsigned int _height, unsigned int _num_channels, float _display_scale) : Image(_data, _width, _height, _num_channels, _display_scale), asset_manager(_asset_manager) { } protected: void loadFile() override { if (asset_manager) { AAsset * asset = AAssetManager_open(asset_manager, getFilename().c_str(), 0); if (asset) { FILE * in = funopen(asset, android_read, android_write, android_seek, android_close); basic_string<unsigned char> s; while (!feof(in)) { unsigned char b[256]; size_t n = fread(b, 1, 256, in); s += basic_string<unsigned char>(b, n); } fclose(in); __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "image %s loaded successfully: %d", getFilename().c_str(), int(s.size())); data = loadFromMemory(s.data(), s.size()); __android_log_print(ANDROID_LOG_INFO, "Sometrik", "Image Width = %u", data->getWidth()); __android_log_print(ANDROID_LOG_INFO, "Sometrik", "Image height = %u", data->getHeight()); } } if (!data.get()) { __android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "image %s loading FAILED", getFilename().c_str()); getFilename().clear(); } } private: AAssetManager * asset_manager; }; std::unique_ptr<Image> AndroidSurface::createImage(float display_scale) { std::unique_ptr<Image> image; unsigned char * buffer = (unsigned char *)lockMemory(false); assert(buffer); if (buffer) { image = std::unique_ptr<Image>(new AndroidImage(0, buffer, getActualWidth(), getActualHeight(), getNumChannels(), display_scale)); releaseMemory(); } return image; } std::shared_ptr<AndroidCache> AndroidContextFactory::cache; std::unique_ptr<Image> AndroidContextFactory::loadImage(const std::string & filename) { return std::unique_ptr<Image>(new AndroidImage(asset_manager, filename, getDisplayScale())); } std::unique_ptr<Image> AndroidContextFactory::createImage() { return std::unique_ptr<Image>(new AndroidImage(asset_manager, getDisplayScale())); } std::unique_ptr<Image> AndroidContextFactory::createImage(const unsigned char * _data, unsigned int _width, unsigned int _height, unsigned int _num_channels) { return std::unique_ptr<Image>(new AndroidImage(0, _data, _width, _height, _num_channels, getDisplayScale())); } void AndroidContextFactory::initialize(JNIEnv * env, jobject & manager) { cache = std::make_shared<AndroidCache>(env, manager); }
52.094286
266
0.744419
rekola
d8afecdce14cf72fd1e5f47692459a197de1ffa8
1,144
cpp
C++
Common/MapReduce_Customs/ii.cpp
luciolas/MapReduceCpp
aa47b1f4b3838ff26fb94583920c4aa9b9921828
[ "MIT" ]
1
2022-03-23T17:00:57.000Z
2022-03-23T17:00:57.000Z
Common/MapReduce_Customs/ii.cpp
luciolas/MapReduceCpp
aa47b1f4b3838ff26fb94583920c4aa9b9921828
[ "MIT" ]
null
null
null
Common/MapReduce_Customs/ii.cpp
luciolas/MapReduceCpp
aa47b1f4b3838ff26fb94583920c4aa9b9921828
[ "MIT" ]
null
null
null
#include "ii.h" #include <algorithm> #include <unordered_map> std::vector<KeyValue> iimapF(const std::string& doc, const std::string& bytes) { std::vector<std::string> words{}; std::vector<KeyValue> result{}; words.reserve(1 << 16); StringSplit(&words, bytes, isLetter); for (auto& word : words) { std::transform(word.begin(), word.end(), word.begin(), [](unsigned char c) { return std::tolower(c); }); result.emplace_back(KeyValue{word, doc}); } return result; } std::string iireduceF(const std::string& key, const std::vector<std::string>& values) { if (values.size()== 0) { return std::string{}; } std::unordered_map<std::string, int> word_doc{}; std::string result{}; result.reserve(values.capacity() + 2 * values.size()); if (word_doc[values[0]] != 1) { word_doc[values[0]] = 1; result += values[0]; } for (int i = 0; i < values.size() - 1; i++) { if (word_doc[values[i]] != 1) { word_doc[values[i]] = 1; result += ", " + values[i]; } } return std::to_string(values.size()) + ": " + result; }
23.833333
109
0.570804
luciolas
d8b75be022d51dd77a267b0b69961519d354f939
773
cpp
C++
source/TestMain.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/TestMain.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/TestMain.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ #include "cdstd.h" #include <fenv.h> #include <UnitTest++.h> #include <TestReporterStdout.h> #include "cddefines.h" #include "ran.h" int main () { ioQQQ = stdout; // disable FP exceptions, they would lead to spurious crashes in the tests fesetenv(FE_DFL_ENV); // initialize random number generator here since it is used in multiple units ran.init(0x0efae2bd7f0a3fddULL, cpu.i().nRANK()); // initialize search path for open_data() cpu.i().initPath(); // we do not want a backtrace since we are deliberately causing problems... cpu.i().disableBacktrace(); return UnitTest::RunAllTests(); }
33.608696
89
0.734799
cloudy-astrophysics
d8b8bd39320e6630117b0452f3954336e0f2108b
531
hpp
C++
include/hmm_h/shuttleFuns.hpp
stanley-rozell/hmm
21dc000961b960a5e1fbf66cb11e74c4e1532ad2
[ "Apache-2.0" ]
null
null
null
include/hmm_h/shuttleFuns.hpp
stanley-rozell/hmm
21dc000961b960a5e1fbf66cb11e74c4e1532ad2
[ "Apache-2.0" ]
12
2021-03-09T23:04:14.000Z
2021-05-17T16:02:29.000Z
include/hmm_h/shuttleFuns.hpp
stanley-rozell/hmm
21dc000961b960a5e1fbf66cb11e74c4e1532ad2
[ "Apache-2.0" ]
null
null
null
// // shuttleFuns.hpp // hmm // // Created by Adam Willats on 2/27/19. // Copyright ยฉ 2019 Adam Willats. All rights reserved. // #ifndef shuttleFuns_hpp #define shuttleFuns_hpp #include <stdio.h> #include "printFuns.hpp" //template <typename T> //std::vector<T> array2vec(T*,int); std::vector<int> array2vec(int*,int); std::vector<double> array2vec(double*,int); void vec2array(std::vector<double>, double *); //double * returnDub(void); void modDub(double*); void modDubVec(double *,int); #endif /* shuttleFuns_hpp */
18.310345
55
0.696798
stanley-rozell
d8befaff4f571818bd096824efe5ba4b31884149
32,455
cpp
C++
src/ofApp.cpp
ReillyGregorio/Tank
4754428f12536e6e67ae61ee48daaa83a821dc34
[ "MIT" ]
null
null
null
src/ofApp.cpp
ReillyGregorio/Tank
4754428f12536e6e67ae61ee48daaa83a821dc34
[ "MIT" ]
null
null
null
src/ofApp.cpp
ReillyGregorio/Tank
4754428f12536e6e67ae61ee48daaa83a821dc34
[ "MIT" ]
null
null
null
#include "ofApp.h" #include <vector> //-------------------------------------------------------------- void ofApp::setup(){ sun1.setPointLight(); sun.setRadius(90); sun2.setPointLight(); sun3.setRadius(90); bound.set(50,50,20); sky.setRadius(5000); skyimg.loadImage("bluecloud_up.jpg"); wallimg.loadImage("wall.jpg"); floorimg.loadImage("floor.jpg"); Tank1.setup(); TankGroup.add(Tank1.tankParam); Tank1.red = 255; Tank1.upk = 101; Tank1.downk = 100; Tank1.leftk = 115; Tank1.rightk = 102; Tank2.setup(); TankGroup.add(Tank2.tankParam); Tank2.green = 255; Tank2.upk = 357; Tank2.downk = 359; Tank2.leftk = 356; Tank2.rightk = 358; Tank3.setup(); TankGroup.add(Tank3.tankParam); Tank3.blue = 255; Tank3.upk = 105; Tank3.downk = 107; Tank3.leftk = 106; Tank3.rightk = 108; Bullet1.setup(); BulletGroup.add(Bullet1.bulletParam); Bullet1.shootk = 113; Bullet2.setup(); BulletGroup.add(Bullet2.bulletParam); Bullet2.shootk = 109; Bullet3.setup(); BulletGroup.add(Bullet3.bulletParam); Bullet3.shootk = 121; reset(); } void ofApp::reset(){ red = false; green = false; blue = false; Tank1.xPos = -ms/2 + wallw; Tank1.yPos = -ms/2 + wallw; Tank1.rotation = 0; Tank1.explode = false; Tank2.xPos = +ms/2 - wallw; Tank2.yPos = -ms/2 + wallw; Tank2.rotation = 0; Tank2.explode = false; Tank3.xPos = +ms/2 - wallw; Tank3.yPos = +ms/2 - wallw; Tank3.rotation = 0; Tank3.explode = false; Bullet1.bxPos = 9999; Bullet1.byPos = 9999; Bullet1.bTimer = 0; Bullet1.bullet.setPosition(999,999,999); Bullet2.bxPos = 9999; Bullet2.byPos = 9999; Bullet2.bTimer = 0; Bullet2.bullet.setPosition(999,999,999); Bullet3.bxPos = 9999; Bullet3.byPos = 9999; Bullet3.bTimer = 0; Bullet3.bullet.setPosition(999,999,999); std::cout << "Red: " << redScore << " Green: " << greenScore << " blue: " << blueScore << std::endl; ofSeedRandom(); for (int i=0; i<wallz; i++) { for (int j=0; j<wallz; j++) { distribution = ofRandom(1,3); if (distribution == 1) { MyWall var1; var1.x = i; var1.y = j; var1.vertical = false; var1.wall.set(ms/wallz,wallw,wallh); vec.push_back(var1); } } } for (int i=0; i<wallz; i++) { for (int j=0; j<wallz; j++) { distribution = ofRandom(1,3); if (distribution == 1) { MyWall var1; var1.x = i; var1.y = j; var1.vertical = true; var1.wall.set(wallw,ms/wallz,wallh); vec.push_back(var1); } } } floor.set(ms,ms,100,100,OF_PRIMITIVE_TRIANGLES); for (std::vector<MyWall>::iterator it = vec.begin() ; it != vec.end(); ++it) { if((*it).vertical == true){ (*it).x = (*it).x * (ms/wallz + wallh*2) + ms/wallz/2 - (wallw*2.777); (*it).y = (*it).y * ms/wallz + ms/wallz/2; }else{ (*it).x = (*it).x * ms/wallz + ms/wallz/2; (*it).y = (*it).y * ms/wallz + ms/wallz/2; } } } //-------------------------------------------------------------- void ofApp::update(){ Tank1.update(); Tank2.update(); Tank3.update(); Bullet1.update(); Bullet2.update(); Bullet3.update(); if(Bullet1.shoot == true && Tank1.explode == false){ if(Bullet1.bTimer <= 0){ Bullet1.bTimer = 10000; Bullet1.bTimerStart = ofGetElapsedTimef(); Bullet1.bxPos = Tank1.xPos+Tank1.xSpeed*15; Bullet1.byPos = Tank1.yPos+Tank1.ySpeed*15; Bullet1.brotation = Tank1.rotation; } } if(Bullet2.shoot == true && Tank2.explode == false){ if(Bullet2.bTimer <= 0){ Bullet2.bTimer = 10000; Bullet2.bTimerStart = ofGetElapsedTimef(); Bullet2.bxPos = Tank2.xPos+Tank2.xSpeed*15; Bullet2.byPos = Tank2.yPos+Tank2.ySpeed*15; Bullet2.brotation = Tank2.rotation; } } if(Bullet3.shoot == true && Tank3.explode == false){ if(Bullet3.bTimer <= 0){ Bullet3.bTimer = 10000; Bullet3.bTimerStart = ofGetElapsedTimef(); Bullet3.bxPos = Tank3.xPos+Tank3.xSpeed*15; Bullet3.byPos = Tank3.yPos+Tank3.ySpeed*15; Bullet3.brotation = Tank3.rotation; } } collide(); tankhit(); bulletCollide(); if(Tank1.explode == true && Tank2.explode == true){ reset(); blueScore += 1; }else if(Tank1.explode == true && Tank3.explode == true){ reset(); greenScore += 1; }else if(Tank2.explode == true && Tank3.explode == true){ reset(); redScore += 1; } bound.setPosition(Tank1.xPos,Tank1.yPos,Tank1.zPos); } void ofApp::tankhit(){ if(((Bullet1.bxPos+(ms/2) < Tank1.xPos +(ms/2) +25 && Bullet1.bxPos+(ms/2) > Tank1.xPos +(ms/2) -25) && (Bullet1.byPos+(ms/2) < Tank1.yPos +(ms/2) +25 && Bullet1.byPos+(ms/2) > Tank1.yPos +(ms/2) -25)) || ((Bullet2.bxPos+(ms/2) < Tank1.xPos +(ms/2) +25 && Bullet2.bxPos+(ms/2) > Tank1.xPos +(ms/2) -25) && (Bullet2.byPos+(ms/2) < Tank1.yPos +(ms/2) +25 && Bullet2.byPos+(ms/2) > Tank1.yPos +(ms/2) -25)) || ((Bullet3.bxPos+(ms/2) < Tank1.xPos +(ms/2) +25 && Bullet3.bxPos+(ms/2) > Tank1.xPos +(ms/2) -25) && (Bullet3.byPos+(ms/2) < Tank1.yPos +(ms/2) +25 && Bullet3.byPos+(ms/2) > Tank1.yPos +(ms/2) -25))){ Tank1.explode = true; std::cout << "iv been hit" << std::endl; } if(((Bullet1.bxPos+(ms/2) < Tank2.xPos +(ms/2) +25 && Bullet1.bxPos+(ms/2) > Tank2.xPos +(ms/2) -25) && (Bullet1.byPos+(ms/2) < Tank2.yPos +(ms/2) +25 && Bullet1.byPos+(ms/2) > Tank2.yPos +(ms/2) -25)) || ((Bullet2.bxPos+(ms/2) < Tank2.xPos +(ms/2) +25 && Bullet2.bxPos+(ms/2) > Tank2.xPos +(ms/2) -25) && (Bullet2.byPos+(ms/2) < Tank2.yPos +(ms/2) +25 && Bullet2.byPos+(ms/2) > Tank2.yPos +(ms/2) -25)) || ((Bullet3.bxPos+(ms/2) < Tank2.xPos +(ms/2) +25 && Bullet3.bxPos+(ms/2) > Tank2.xPos +(ms/2) -25) && (Bullet3.byPos+(ms/2) < Tank2.yPos +(ms/2) +25 && Bullet3.byPos+(ms/2) > Tank2.yPos +(ms/2) -25))){ Tank2.explode = true; std::cout << "iv been hit" << std::endl; } if(((Bullet1.bxPos+(ms/2) < Tank3.xPos +(ms/2) +25 && Bullet1.bxPos+(ms/2) > Tank3.xPos +(ms/2) -25) && (Bullet1.byPos+(ms/2) < Tank3.yPos +(ms/2) +25 && Bullet1.byPos+(ms/2) > Tank3.yPos +(ms/2) -25)) || ((Bullet2.bxPos+(ms/2) < Tank3.xPos +(ms/2) +25 && Bullet2.bxPos+(ms/2) > Tank3.xPos +(ms/2) -25) && (Bullet2.byPos+(ms/2) < Tank3.yPos +(ms/2) +25 && Bullet2.byPos+(ms/2) > Tank3.yPos +(ms/2) -25)) || ((Bullet3.bxPos+(ms/2) < Tank3.xPos +(ms/2) +25 && Bullet3.bxPos+(ms/2) > Tank3.xPos +(ms/2) -25) && (Bullet3.byPos+(ms/2) < Tank3.yPos +(ms/2) +25 && Bullet3.byPos+(ms/2) > Tank3.yPos +(ms/2) -25))){ Tank3.explode = true; std::cout << "iv been hit" << std::endl; } } void ofApp::bulletCollide(){ for (std::vector<MyWall>::iterator it = vec.begin() ; it != vec.end(); ++it) { if((*it).vertical == false){ if( ((((*it).x-((ms/wallz)/2) < (Bullet1.bxPos+(ms/2) + 6)) && ((Bullet1.bxPos+(ms/2) + 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet1.byPos+(ms/2) + 6)) && ((Bullet1.byPos+(ms/2) + 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet1.bxPos+(ms/2) - 6)) && ((Bullet1.bxPos+(ms/2) - 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet1.byPos+(ms/2) + 6)) && ((Bullet1.byPos+(ms/2) + 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet1.bxPos+(ms/2) + 6)) && ((Bullet1.bxPos+(ms/2) + 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet1.byPos+(ms/2) - 6)) && ((Bullet1.byPos+(ms/2) - 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet1.bxPos+(ms/2) - 6)) && ((Bullet1.bxPos+(ms/2) - 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet1.byPos+(ms/2) - 6)) && ((Bullet1.byPos+(ms/2) - 6) < (*it).y+(wallw/2)))) ){ Bullet1.brotation += 90; } }else{ if( ((((*it).y-((ms/wallz)/2) < (Bullet1.byPos+(ms/2) + 6)) && ((Bullet1.byPos+(ms/2) + 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet1.bxPos+(ms/2) + 6)) && ((Bullet1.bxPos+(ms/2) + 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet1.byPos+(ms/2) + 6)) && ((Bullet1.byPos+(ms/2) + 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet1.bxPos+(ms/2) - 6)) && ((Bullet1.bxPos+(ms/2) - 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet1.byPos+(ms/2) - 6)) && ((Bullet1.byPos+(ms/2) - 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet1.bxPos+(ms/2) + 6)) && ((Bullet1.bxPos+(ms/2) + 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet1.byPos+(ms/2) - 6)) && ((Bullet1.byPos+(ms/2) - 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet1.bxPos+(ms/2) - 6)) && ((Bullet1.bxPos+(ms/2) - 6) < (*it).x+(wallw/2)))) ){ Bullet1.brotation += 90; } } if((*it).vertical == false){ if( ((((*it).x-((ms/wallz)/2) < (Bullet2.bxPos+(ms/2) + 6)) && ((Bullet2.bxPos+(ms/2) + 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet2.byPos+(ms/2) + 6)) && ((Bullet2.byPos+(ms/2) + 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet2.bxPos+(ms/2) - 6)) && ((Bullet2.bxPos+(ms/2) - 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet2.byPos+(ms/2) + 6)) && ((Bullet2.byPos+(ms/2) + 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet2.bxPos+(ms/2) + 6)) && ((Bullet2.bxPos+(ms/2) + 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet2.byPos+(ms/2) - 6)) && ((Bullet2.byPos+(ms/2) - 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet2.bxPos+(ms/2) - 6)) && ((Bullet2.bxPos+(ms/2) - 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet2.byPos+(ms/2) - 6)) && ((Bullet2.byPos+(ms/2) - 6) < (*it).y+(wallw/2)))) ){ Bullet2.brotation += 90; } }else{ if( ((((*it).y-((ms/wallz)/2) < (Bullet2.byPos+(ms/2) + 6)) && ((Bullet2.byPos+(ms/2) + 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet2.bxPos+(ms/2) + 6)) && ((Bullet2.bxPos+(ms/2) + 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet2.byPos+(ms/2) + 6)) && ((Bullet2.byPos+(ms/2) + 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet2.bxPos+(ms/2) - 6)) && ((Bullet2.bxPos+(ms/2) - 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet2.byPos+(ms/2) - 6)) && ((Bullet2.byPos+(ms/2) - 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet2.bxPos+(ms/2) + 6)) && ((Bullet2.bxPos+(ms/2) + 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet2.byPos+(ms/2) - 6)) && ((Bullet2.byPos+(ms/2) - 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet2.bxPos+(ms/2) - 6)) && ((Bullet2.bxPos+(ms/2) - 6) < (*it).x+(wallw/2)))) ){ Bullet2.brotation += 90; } } if((*it).vertical == false){ if( ((((*it).x-((ms/wallz)/2) < (Bullet3.bxPos+(ms/2) + 6)) && ((Bullet3.bxPos+(ms/2) + 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet3.byPos+(ms/2) + 6)) && ((Bullet3.byPos+(ms/2) + 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet3.bxPos+(ms/2) - 6)) && ((Bullet3.bxPos+(ms/2) - 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet3.byPos+(ms/2) + 6)) && ((Bullet3.byPos+(ms/2) + 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet3.bxPos+(ms/2) + 6)) && ((Bullet3.bxPos+(ms/2) + 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet3.byPos+(ms/2) - 6)) && ((Bullet3.byPos+(ms/2) - 6) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Bullet3.bxPos+(ms/2) - 6)) && ((Bullet3.bxPos+(ms/2) - 6) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Bullet3.byPos+(ms/2) - 6)) && ((Bullet3.byPos+(ms/2) - 6) < (*it).y+(wallw/2)))) ){ Bullet3.brotation += 90; } }else{ if( ((((*it).y-((ms/wallz)/2) < (Bullet3.byPos+(ms/2) + 6)) && ((Bullet3.byPos+(ms/2) + 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet3.bxPos+(ms/2) + 6)) && ((Bullet3.bxPos+(ms/2) + 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet3.byPos+(ms/2) + 6)) && ((Bullet3.byPos+(ms/2) + 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet3.bxPos+(ms/2) - 6)) && ((Bullet3.bxPos+(ms/2) - 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet3.byPos+(ms/2) - 6)) && ((Bullet3.byPos+(ms/2) - 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet3.bxPos+(ms/2) + 6)) && ((Bullet3.bxPos+(ms/2) + 6) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Bullet3.byPos+(ms/2) - 6)) && ((Bullet3.byPos+(ms/2) - 6) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Bullet3.bxPos+(ms/2) - 6)) && ((Bullet3.bxPos+(ms/2) - 6) < (*it).x+(wallw/2)))) ){ Bullet3.brotation += 90; } } } Bullet1.oldx = Bullet1.bxPos; Bullet1.oldy = Bullet1.byPos; Bullet1.oldz = Bullet1.bzPos; Bullet2.oldx = Bullet2.bxPos; Bullet2.oldy = Bullet2.byPos; Bullet2.oldz = Bullet2.bzPos; Bullet3.oldx = Bullet3.bxPos; Bullet3.oldy = Bullet3.byPos; Bullet3.oldz = Bullet3.bzPos; } void ofApp::collide(){ for (std::vector<MyWall>::iterator it = vec.begin() ; it != vec.end(); ++it) { if((*it).vertical == false){ if( ((((*it).x-((ms/wallz)/2) < (Tank1.xPos+(ms/2) + 25)) && ((Tank1.xPos+(ms/2) + 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank1.yPos+(ms/2) + 25)) && ((Tank1.yPos+(ms/2) + 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank1.xPos+(ms/2) - 25)) && ((Tank1.xPos+(ms/2) - 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank1.yPos+(ms/2) + 25)) && ((Tank1.yPos+(ms/2) + 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank1.xPos+(ms/2) + 25)) && ((Tank1.xPos+(ms/2) + 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank1.yPos+(ms/2) - 25)) && ((Tank1.yPos+(ms/2) - 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank1.xPos+(ms/2) - 25)) && ((Tank1.xPos+(ms/2) - 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank1.yPos+(ms/2) - 25)) && ((Tank1.yPos+(ms/2) - 25) < (*it).y+(wallw/2)))) ){ Tank1.xPos = Tank1.oldx; Tank1.yPos = Tank1.oldy; Tank1.zPos = Tank1.oldz; } }else{ if( ((((*it).y-((ms/wallz)/2) < (Tank1.yPos+(ms/2) + 25)) && ((Tank1.yPos+(ms/2) + 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank1.xPos+(ms/2) + 25)) && ((Tank1.xPos+(ms/2) + 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank1.yPos+(ms/2) + 25)) && ((Tank1.yPos+(ms/2) + 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank1.xPos+(ms/2) - 25)) && ((Tank1.xPos+(ms/2) - 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank1.yPos+(ms/2) - 25)) && ((Tank1.yPos+(ms/2) - 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank1.xPos+(ms/2) + 25)) && ((Tank1.xPos+(ms/2) + 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank1.yPos+(ms/2) - 25)) && ((Tank1.yPos+(ms/2) - 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank1.xPos+(ms/2) - 25)) && ((Tank1.xPos+(ms/2) - 25) < (*it).x+(wallw/2)))) ){ Tank1.xPos = Tank1.oldx; Tank1.yPos = Tank1.oldy; Tank1.zPos = Tank1.oldz; } } if((*it).vertical == false){ if( ((((*it).x-((ms/wallz)/2) < (Tank2.xPos+(ms/2) + 25)) && ((Tank2.xPos+(ms/2) + 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank2.yPos+(ms/2) + 25)) && ((Tank2.yPos+(ms/2) + 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank2.xPos+(ms/2) - 25)) && ((Tank2.xPos+(ms/2) - 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank2.yPos+(ms/2) + 25)) && ((Tank2.yPos+(ms/2) + 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank2.xPos+(ms/2) + 25)) && ((Tank2.xPos+(ms/2) + 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank2.yPos+(ms/2) - 25)) && ((Tank2.yPos+(ms/2) - 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank2.xPos+(ms/2) - 25)) && ((Tank2.xPos+(ms/2) - 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank2.yPos+(ms/2) - 25)) && ((Tank2.yPos+(ms/2) - 25) < (*it).y+(wallw/2)))) ){ Tank2.xPos = Tank2.oldx; Tank2.yPos = Tank2.oldy; Tank2.zPos = Tank2.oldz; } }else{ if( ((((*it).y-((ms/wallz)/2) < (Tank2.yPos+(ms/2) + 25)) && ((Tank2.yPos+(ms/2) + 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank2.xPos+(ms/2) + 25)) && ((Tank2.xPos+(ms/2) + 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank2.yPos+(ms/2) + 25)) && ((Tank2.yPos+(ms/2) + 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank2.xPos+(ms/2) - 25)) && ((Tank2.xPos+(ms/2) - 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank2.yPos+(ms/2) - 25)) && ((Tank2.yPos+(ms/2) - 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank2.xPos+(ms/2) + 25)) && ((Tank2.xPos+(ms/2) + 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank2.yPos+(ms/2) - 25)) && ((Tank2.yPos+(ms/2) - 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank2.xPos+(ms/2) - 25)) && ((Tank2.xPos+(ms/2) - 25) < (*it).x+(wallw/2)))) ){ Tank2.xPos = Tank2.oldx; Tank2.yPos = Tank2.oldy; Tank2.zPos = Tank2.oldz; } } if((*it).vertical == false){ if( ((((*it).x-((ms/wallz)/2) < (Tank3.xPos+(ms/2) + 25)) && ((Tank3.xPos+(ms/2) + 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank3.yPos+(ms/2) + 25)) && ((Tank3.yPos+(ms/2) + 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank3.xPos+(ms/2) - 25)) && ((Tank3.xPos+(ms/2) - 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank3.yPos+(ms/2) + 25)) && ((Tank3.yPos+(ms/2) + 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank3.xPos+(ms/2) + 25)) && ((Tank3.xPos+(ms/2) + 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank3.yPos+(ms/2) - 25)) && ((Tank3.yPos+(ms/2) - 25) < (*it).y+(wallw/2)))) || ((((*it).x-((ms/wallz)/2) < (Tank3.xPos+(ms/2) - 25)) && ((Tank3.xPos+(ms/2) - 25) < (*it).x+((ms/wallz)/2))) && (((*it).y-(wallw/2) < (Tank3.yPos+(ms/2) - 25)) && ((Tank3.yPos+(ms/2) - 25) < (*it).y+(wallw/2)))) ){ Tank3.xPos = Tank3.oldx; Tank3.yPos = Tank3.oldy; Tank3.zPos = Tank3.oldz; } }else{ if( ((((*it).y-((ms/wallz)/2) < (Tank3.yPos+(ms/2) + 25)) && ((Tank3.yPos+(ms/2) + 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank3.xPos+(ms/2) + 25)) && ((Tank3.xPos+(ms/2) + 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank3.yPos+(ms/2) + 25)) && ((Tank3.yPos+(ms/2) + 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank3.xPos+(ms/2) - 25)) && ((Tank3.xPos+(ms/2) - 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank3.yPos+(ms/2) - 25)) && ((Tank3.yPos+(ms/2) - 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank3.xPos+(ms/2) + 25)) && ((Tank3.xPos+(ms/2) + 25) < (*it).x+(wallw/2)))) || ((((*it).y-((ms/wallz)/2) < (Tank3.yPos+(ms/2) - 25)) && ((Tank3.yPos+(ms/2) - 25) < (*it).y+((ms/wallz)/2))) && (((*it).x-(wallw/2) < (Tank3.xPos+(ms/2) - 25)) && ((Tank3.xPos+(ms/2) - 25) < (*it).x+(wallw/2)))) ){ Tank3.xPos = Tank3.oldx; Tank3.yPos = Tank3.oldy; Tank3.zPos = Tank3.oldz; } } } Tank1.oldx = Tank1.xPos; Tank1.oldy = Tank1.yPos; Tank1.oldz = Tank1.zPos; Tank2.oldx = Tank2.xPos; Tank2.oldy = Tank2.yPos; Tank2.oldz = Tank2.zPos; Tank3.oldx = Tank3.xPos; Tank3.oldy = Tank3.yPos; Tank3.oldz = Tank3.zPos; } //-------------------------------------------------------------- void ofApp::draw(){ ofEnableLighting(); ofSetSmoothLighting(true); glEnable (GL_DEPTH_TEST); ofColor centerColor = ofColor(255, 255, 255); ofColor edgeColor(250, 250, 250); ofBackgroundGradient(centerColor, edgeColor, OF_GRADIENT_CIRCULAR); camera.begin(); sun1.enable(); sun1.setPosition(300,0,5000); sun2.setPosition(300,0,5000); ofPushMatrix(); float tx = ofGetWidth() / 2; float ty = ofGetHeight() / 2; ofTranslate(tx, ty); ofPopMatrix(); ofPushStyle(); skyimg.bind(); ofSetColor(255,255,255); sky.draw(); ofPopStyle(); ofPushStyle(); floorimg.bind(); ofSetColor(255,255,255); floor.draw(); ofPopStyle(); sun1.disable(); sun2.enable(); Tank1.draw(); //bound.draw(); Tank2.draw(); Tank3.draw(); sun2.disable(); sun1.enable(); ofSetColor(0,0,0); Bullet1.draw(); Bullet2.draw(); Bullet3.draw(); ofPushStyle(); wallimg.bind(); ofSetColor(255,255,255); ofTranslate(-ms/2,-ms/2); for (std::vector<MyWall>::iterator it = vec.begin() ; it != vec.end(); ++it) { ofSetColor(ofColor::white); (*it).wall.setPosition((*it).x,(*it).y,wallh/2); (*it).wall.draw(); } ofTranslate(ms/2,ms/2); ofPopStyle(); sun1.disable(); camera.end(); ofDisableLighting(); ofSetSmoothLighting(false); glDisable (GL_DEPTH_TEST); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == Tank1.upk){ Tank1.up = true; } if(key == Tank1.downk){ Tank1.down = true; } if(key == Tank1.leftk){ Tank1.left = true; } if(key == Tank1.rightk){ Tank1.right = true; } if(key == Bullet1.shootk){ Bullet1.shoot = true; } if(key == Tank2.upk){ Tank2.up = true; } if(key == Tank2.downk){ Tank2.down = true; } if(key == Tank2.leftk){ Tank2.left = true; } if(key == Tank2.rightk){ Tank2.right = true; } if(key == Bullet2.shootk){ Bullet2.shoot = true; } if(key == Tank3.upk){ Tank3.up = true; } if(key == Tank3.downk){ Tank3.down = true; } if(key == Tank3.leftk){ Tank3.left = true; } if(key == Tank3.rightk){ Tank3.right = true; } if(key == Bullet3.shootk){ Bullet3.shoot = true; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ if(key == Tank1.upk){ Tank1.up = false; } if(key == Tank1.downk){ Tank1.down = false; } if(key == Tank1.leftk){ Tank1.left = false; } if(key == Tank1.rightk){ Tank1.right = false; } if(key == Bullet1.shootk){ Bullet1.shoot = false; } if(key == Tank2.upk){ Tank2.up = false; } if(key == Tank2.downk){ Tank2.down = false; } if(key == Tank2.leftk){ Tank2.left = false; } if(key == Tank2.rightk){ Tank2.right = false; } if(key == Bullet2.shootk){ Bullet2.shoot = false; } if(key == Tank3.upk){ Tank3.up = false; } if(key == Tank3.downk){ Tank3.down = false; } if(key == Tank3.leftk){ Tank3.left = false; } if(key == Tank3.rightk){ Tank3.right = false; } if(key == Bullet3.shootk){ Bullet3.shoot = false; } } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
31.663415
111
0.361547
ReillyGregorio
d8c3bd366edc0c5278a9f715ca0e9db36510bcc9
5,773
cpp
C++
source/TaskManagerPrefs.cpp
ocerman/TaskManager
7e0273c2eac2bd8670a1faec4dded8ba6ac19305
[ "Apache-2.0" ]
3
2015-07-29T03:16:00.000Z
2020-10-12T17:40:59.000Z
source/TaskManagerPrefs.cpp
radtek/TaskManager-1
4fd44eaa83d99e9314fe8f3ae10f1e9b99ea3291
[ "Apache-2.0" ]
5
2017-12-09T17:13:41.000Z
2020-03-12T18:07:33.000Z
source/TaskManagerPrefs.cpp
radtek/TaskManager-1
4fd44eaa83d99e9314fe8f3ae10f1e9b99ea3291
[ "Apache-2.0" ]
5
2017-11-30T06:07:35.000Z
2020-10-26T06:00:47.000Z
/* * Copyright 2000 by Thomas Krammer * * 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 "pch.h" #include "common.h" #include "TaskManagerPrefs.h" // ====== globals ====== const char * const PREF_MAIN_WINDOW_RECT = "MainWindowRect"; const char * const PREF_PULSE_RATE = "PulseRate"; const char * const PREF_SHOW_DESKBAR_REPLICANT = "ShowDeskbarRep"; const char * const PREF_COLUMN_WIDTH_PREFIX = "ColumnWidth_"; const char * const PREF_COLUMN_DISPLAY_ORDER = "ColumnDisplayOrder"; const char * const PREF_COLUMN_VISIBLE_PREFIX = "ColumnVisible_"; const char * const PREF_SORT_KEY_INFO = "SortKeyInfo"; const char * const PREF_SHOW_KILL_WARNING = "ShowKillWarning"; const char * const PREF_SHOW_SYSTEM_KILL_WARNING = "ShowSystemKillWarning"; const char * const PREF_HIDE_DESKBAR_REPLICANT_ON_CLOSE = "HideDeskbarRepOnClose"; const char * const PREF_HIDE_SYSTEM_TEAMS = "HideSystemTeams"; const char * const PREF_SHOW_IN_ALL_WORKSPACES = "ShowInAllWorkspaces"; const char * const PREF_ADD_PERFORMANCE_WINDOW_RECT = "AddPreformanceWindowRect"; const char * const PREF_PERFORMANCE_LEGEND_BAR_WIDTH = "PerfLegendBarWidth"; const char * const PREF_LANGUAGE = "Language"; const char * const PREF_SELECTED_TAB = "SelectedTab"; // ====== CTaskManagerPrefs ====== CTaskManagerPrefs::CTaskManagerPrefs() : CFilePreferences("TaskMgr_settings") { } BRect CTaskManagerPrefs::MainWindowRect() { BRect rect; Read(PREF_MAIN_WINDOW_RECT, rect, BRect(100,100, 400, 400)); return rect; } void CTaskManagerPrefs::SetMainWindowRect(BRect rect) { Write(PREF_MAIN_WINDOW_RECT, rect); } BRect CTaskManagerPrefs::AddPreformanceWindowRect(BRect defaultRect) { BRect rect; Read(PREF_ADD_PERFORMANCE_WINDOW_RECT, rect, defaultRect); return rect; } void CTaskManagerPrefs::SetAddPreformanceWindowRect(BRect rect) { Write(PREF_ADD_PERFORMANCE_WINDOW_RECT, rect); } bigtime_t CTaskManagerPrefs::PulseRate() { bigtime_t pulse; Read(PREF_PULSE_RATE, pulse, NORMAL_PULSE_RATE); return pulse; } void CTaskManagerPrefs::SetPulseRate(bigtime_t pulse) { Write(PREF_PULSE_RATE, pulse); } bool CTaskManagerPrefs::ShowDeskbarReplicant() { bool show; Read(PREF_SHOW_DESKBAR_REPLICANT, show); return show; } void CTaskManagerPrefs::SetShowDeskbarReplicant(bool show) { Write(PREF_SHOW_DESKBAR_REPLICANT, show); } float CTaskManagerPrefs::PerformanceLegendBarWidth(float defaultValue) { float value; Read(PREF_PERFORMANCE_LEGEND_BAR_WIDTH, value, defaultValue); return value; } void CTaskManagerPrefs::SetPerformanceLegendBarWidth(float width) { Write(PREF_PERFORMANCE_LEGEND_BAR_WIDTH, width); } bool CTaskManagerPrefs::ShowInAllWorkspaces() { bool show; Read(PREF_SHOW_IN_ALL_WORKSPACES, show, false); return show; } void CTaskManagerPrefs::SetShowInAllWorkspaces(bool show) { Write(PREF_SHOW_IN_ALL_WORKSPACES, show); } bool CTaskManagerPrefs::HideSystemTeams() { bool hideSystemTeams; Read(PREF_HIDE_SYSTEM_TEAMS, hideSystemTeams, false); return hideSystemTeams; } bool CTaskManagerPrefs::HideDeskbarReplicantOnClose() { bool hideDeskbarRep; Read(PREF_HIDE_DESKBAR_REPLICANT_ON_CLOSE, hideDeskbarRep, true); return hideDeskbarRep; } float CTaskManagerPrefs::ColumnWidth(int32 columnNum, float defaultValue) { char name[255]; sprintf(name, "%s%ld", PREF_COLUMN_WIDTH_PREFIX, columnNum); float width; Read(name, width, defaultValue); return width; } void CTaskManagerPrefs::SetColumnWidth(int32 columnNum, float width) { char name[255]; sprintf(name, "%s%ld", PREF_COLUMN_WIDTH_PREFIX, columnNum); Write(name, width); } bool CTaskManagerPrefs::ColumnVisible(int32 columnNum, bool defaultValue) { char name[255]; sprintf(name, "%s%ld", PREF_COLUMN_VISIBLE_PREFIX, columnNum); bool visible; Read(name, visible, defaultValue); return visible; } void CTaskManagerPrefs::SetColumnVisible(int32 columnNum, bool visible) { char name[255]; sprintf(name, "%s%ld", PREF_COLUMN_VISIBLE_PREFIX, columnNum); Write(name, visible); } sort_key_info *CTaskManagerPrefs::SortKeyInfo() { int32 num = SortKeyInfoCount(); sort_key_info *sortInfo = new sort_key_info [num]; Read(PREF_SORT_KEY_INFO, (void *)sortInfo, sizeof(sort_key_info), num); return sortInfo; } int32 CTaskManagerPrefs::SortKeyInfoCount() { return (int32)(DataSize(PREF_SORT_KEY_INFO) / sizeof(sort_key_info)); } void CTaskManagerPrefs::SetSortKeyInfo(sort_key_info *sortKeys, int32 num) { Write(PREF_SORT_KEY_INFO, (void *)sortKeys, sizeof(sort_key_info), num); } int32 *CTaskManagerPrefs::ColumnDisplayOrder(int32 numColumns) { int32 *dispOrder = new int32 [numColumns]; // initalize array for(int i=0 ; i<numColumns ; i++) dispOrder[i] = i; Read(PREF_COLUMN_DISPLAY_ORDER, (void *)dispOrder, sizeof(int32), numColumns); return dispOrder; } void CTaskManagerPrefs::SetColumnDisplayOrder(int32 *displayOrder, int32 numColumns) { Write(PREF_COLUMN_DISPLAY_ORDER, (void *)displayOrder, sizeof(int32), numColumns); } void CTaskManagerPrefs::SetLanguage(const char *language) { Write(PREF_LANGUAGE, language); } BString CTaskManagerPrefs::Language() { BString language; Read(PREF_LANGUAGE, language, "English"); return language; }
23.46748
84
0.764594
ocerman
d8c557e18bd9329e3c5204a9aec332a66e3f053c
5,189
hxx
C++
include/prevc/pipeline/AST/unary-operation.hxx
arazeiros/prevc
378f045f57b2e1c9460ac1699951291ac055c078
[ "MIT" ]
3
2018-10-30T20:33:45.000Z
2019-03-06T11:46:31.000Z
include/prevc/pipeline/AST/unary-operation.hxx
arazeiros/prevc
378f045f57b2e1c9460ac1699951291ac055c078
[ "MIT" ]
null
null
null
include/prevc/pipeline/AST/unary-operation.hxx
arazeiros/prevc
378f045f57b2e1c9460ac1699951291ac055c078
[ "MIT" ]
null
null
null
#ifndef PREVC_PIPELINE_AST_UNARYOPERATION_HXX #define PREVC_PIPELINE_AST_UNARYOPERATION_HXX #include <prevc/error.hxx> #include <prevc/pipeline/AST/expression.hxx> namespace prevc { namespace pipeline { namespace AST { /** * \brief Represent a unary operation node in the AST. * */ class UnaryOperation: public Expression { public: /** * \brief The enumeration of all possible unary operators. * */ enum class Operator { PLUS, MINUS, NOT, DEL, MEM, // $ (in C is &) VAL // @ (in C is *) }; /** * \brief Create an unary operation node. * \param pipeline The pipeline that owns this AST node. * \param location The location of the unary operation in the source code. * \param operator_ The operator applied on the sub-expression. * \param sub_expression The sub-expression on which the unary operation is executed. * */ UnaryOperation(Pipeline* pipeline, util::Location&& location, Operator operator_, Expression* sub_expression); /** * \brief Release the used resources. * */ virtual ~UnaryOperation(); /** * \brief Checks the semantics of the node. * \param pipeline The pipeline of the node. * */ virtual void check_semantics() override; /** * \brief Generate the IR code for this unary operation expression. * \param builder The builder of the IR block containing this unary operation expression. * \return The IR value representing this unary operation expression. * */ virtual llvm::Value* generate_IR(llvm::IRBuilder<>* builder) override; /** * \brief Evaluate the expression as an integer (if possible). * \return Returns the evaluated integer. * */ virtual std::optional<std::int64_t> evaluate_as_integer() const noexcept override; /** * \brief Tells if the expression is lvalue or not. * \return True if expression is lvalue, false otherwise. * */ virtual bool is_lvalue() const noexcept; /** * \brief Generate the IR code for this expression (returning the address of the expression). * \param builder The builder of the IR block containing this expression. * \return The IR address representing this expression. * * The expression must be lvalue, otherwise this function has unexpected behaviour. * */ virtual llvm::Value* generate_IR_address(llvm::IRBuilder<>* builder) override; /** * \brief Returns the semantic type of this expression. * \return The semantic type of this expression. * * Before this method can be called, the call to `check_semantics()` have to be done. * */ virtual const semantic_analysis::Type* get_semantic_type() override; /** * \brief Returns a string representation of this operation. * \return The representation in JSON format. * */ virtual util::String to_string() const noexcept override; private: /** * \brief The operator applied on the sub-expression. * */ Operator operator_; /** * \brief The sub-expression on which the unary operation is executed. * */ Expression* sub_expression; }; /** * \brief Returns the C-string representation of a specified operator. * \param operator_ The specified operator. * \return The C-string representation. * */ constexpr static const char* to_string(const UnaryOperation::Operator& operator_) { switch (operator_) { case UnaryOperation::Operator::PLUS: return "PLUS"; case UnaryOperation::Operator::MINUS: return "MINUS"; case UnaryOperation::Operator::NOT: return "NOT"; case UnaryOperation::Operator::DEL: return "DEL"; case UnaryOperation::Operator::MEM: return "MEM"; case UnaryOperation::Operator::VAL: return "VAL"; default: prevc::InternalError::raise("token not recognized"); } } } } } #endif
39.310606
126
0.505107
arazeiros
d8d79789d5b26abfa99c76e31536ddd37816d41c
2,232
cpp
C++
Competitive Coding/Tree/Minimum Spanning Tree/Kruskal/KruskalMST.cpp
Gareeb-coder/Algorithms
22f9c71a7554a3211978c910c086e23bf1ae4c7f
[ "MIT" ]
222
2016-07-17T17:28:19.000Z
2022-03-27T02:57:39.000Z
Competitive Coding/Tree/Minimum Spanning Tree/Kruskal/KruskalMST.cpp
Gareeb-coder/Algorithms
22f9c71a7554a3211978c910c086e23bf1ae4c7f
[ "MIT" ]
197
2016-10-24T16:47:42.000Z
2021-08-29T08:12:31.000Z
Competitive Coding/Tree/Minimum Spanning Tree/Kruskal/KruskalMST.cpp
Gareeb-coder/Algorithms
22f9c71a7554a3211978c910c086e23bf1ae4c7f
[ "MIT" ]
206
2016-05-18T17:08:14.000Z
2022-01-16T04:08:47.000Z
#include <bits/stdc++.h> using namespace std; #define lli long long int #define infinite numeric_limits<int>::max() #define Min(a,b) ((a)<(b)?(a):(b)) #define Max(a,b) ((a)>(b)?(a):(b)) #define fr(i,j,s) for(i = j ; i < s ; i++) #define ifr(i,j,s) for(i = j ; i >= s , i--) struct edge { lli wt; int src; int dest; }; struct Graph { int V; int E; struct edge* array; }; struct sub { int parent; int rank; }; bool comp(struct edge &a, struct edge &b) { return ((a.wt)<(b.wt)); } int find(struct sub subset[], int i) { if(subset[i].parent != i) { subset[i].parent = find(subset,subset[i].parent); } return subset[i].parent ; } void Union(struct sub subset[] , int x, int y) { int xfather = find(subset,x); int yfather = find(subset,y); if(subset[xfather].rank<subset[yfather].rank) subset[xfather].parent = yfather ; else if(subset[yfather].rank<subset[xfather].rank) subset[yfather].parent = xfather ; else { subset[yfather].parent = xfather; subset[xfather].rank++; } } struct Graph* createGraph(int V,int E) { int i ; struct Graph* G = (struct Graph *)malloc(sizeof(struct Graph)); G->V = V ; G->E = E ; G->array = (struct edge*)malloc(E*sizeof(struct edge)); return G ; } void KruskalMST(struct Graph *G) { int i ; int V = G->V ; int E = G->E ; lli sum = 0 ; struct sub subset[G->V]; fr(i,0,V) { subset[i].parent = i ; subset[i].rank = 0 ; } sort(G->array, (G->array)+G->E,comp); fr(i,0,E) { int x = find(subset,G->array[i].src); int y = find(subset,G->array[i].dest); if(x==y) continue; else { Union(subset,G->array[i].src,G->array[i].dest); sum+=G->array[i].wt; } } cout<<sum<<endl; } int main(void) { int test,v,e,a,b; lli wt; cin>>v>>e; struct Graph* G = createGraph(v,e); int ed = 0; int temp = e ; while(e--) { cin>>a>>b>>wt; G->array[ed].src=a-1; G->array[ed].dest=b-1; G->array[ed].wt=wt; ed++; } cin>>a; KruskalMST(G); return 0; }
20.666667
67
0.517025
Gareeb-coder
d8ddb2b2ebdd87ccd97a0f49fb58ba2dbaec8bc5
912
cpp
C++
gameSource/testFolderCache.cpp
Valaras/OneLife
0f83ffb8edf8362ff3bf0ca87a73bba21be20446
[ "Linux-OpenIB" ]
69
2018-10-05T23:29:10.000Z
2022-03-29T22:34:24.000Z
gameSource/testFolderCache.cpp
Valaras/OneLife
0f83ffb8edf8362ff3bf0ca87a73bba21be20446
[ "Linux-OpenIB" ]
62
2018-11-08T14:14:40.000Z
2022-03-01T20:38:01.000Z
gameSource/testFolderCache.cpp
Valaras/OneLife
0f83ffb8edf8362ff3bf0ca87a73bba21be20446
[ "Linux-OpenIB" ]
24
2018-10-11T09:20:27.000Z
2021-11-06T19:23:17.000Z
/* compile with g++ -g -I../.. -o testFolderCache testFolderCache.cpp folderCache.cpp \ ../../minorGems/io/file/linux/PathLinux.cpp \ ../../minorGems/formats/encodingUtils.cpp \ ../../minorGems/util/stringUtils.cpp \ ../../minorGems/system/unix/TimeUnix.cpp */ #include "folderCache.h" #include "minorGems/system/Time.h" int main() { double startTime = Time::getCurrentTime(); FolderCache c = initFolderCache( "objects" ); printf( "Init took %f seconds\n", Time::getCurrentTime() - startTime ); for( int i=0; i<c.numFiles; i++ ) { char *name = getFileName( c, i ); char *contents = getFileContents( c, i ); if( false )printf( "Cache reading file %s, length %d\n", name, strlen( contents ) ); delete [] name; delete [] contents; } freeFolderCache( c ); return 1; }
21.209302
71
0.575658
Valaras
d8f87c8a1317283817d20cb6db3452cb5e4cb753
2,853
cpp
C++
src/Kernel/Service/FirmwareUpdateService.cpp
ilesar/nodemcu_neopixel_mqtt
1e585eb9d1737c3f19b38126cc35b363006285b9
[ "MIT" ]
null
null
null
src/Kernel/Service/FirmwareUpdateService.cpp
ilesar/nodemcu_neopixel_mqtt
1e585eb9d1737c3f19b38126cc35b363006285b9
[ "MIT" ]
null
null
null
src/Kernel/Service/FirmwareUpdateService.cpp
ilesar/nodemcu_neopixel_mqtt
1e585eb9d1737c3f19b38126cc35b363006285b9
[ "MIT" ]
null
null
null
#include "../Interface/FirmwareUpdateService.h" FirmwareUpdateService::FirmwareUpdateService(char *password) { _password = password; } void FirmwareUpdateService::setup() { setAuthorization(_password); setExternalRoutes(); onStart(); onEnd(); onProgress(); onError(); ArduinoOTA.begin(); } void FirmwareUpdateService::loop() { if (_canUpdateFlag) { uint16_t timeStart = millis(); Serial.println("Can update for 15 seconds..."); while (_timeElapsed < 15000) { ArduinoOTA.handle(); _timeElapsed = millis() - timeStart; delay(10); } Serial.println("Update period ended"); _canUpdateFlag = false; } _server.handleClient(); } void FirmwareUpdateService::setAuthorization(char *password) { ArduinoOTA.setPassword("admin"); ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); } void FirmwareUpdateService::setExternalRoutes() { _server.on("/restart", [this]() { Serial.println("RESTART COMMAND"); _server.send(200, "text/plain", "Restarting..."); delay(1000); ESP.restart(); }); _server.on("/upload-firmware", [this]() { Serial.println("UPDATE COMMAND"); _canUpdateFlag = true; _server.send(200, "text/plain", "You have 15 seconds to upload your code..."); _timeElapsed = 0; }); _server.begin(); } void FirmwareUpdateService::onStart() { ArduinoOTA.onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) { type = "sketch"; } else { // U_SPIFFS type = "filesystem"; } // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }); } void FirmwareUpdateService::onEnd() { ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); } void FirmwareUpdateService::onProgress() { ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); } void FirmwareUpdateService::onError() { ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) { Serial.println("Auth Failed"); } else if (error == OTA_BEGIN_ERROR) { Serial.println("Begin Failed"); } else if (error == OTA_CONNECT_ERROR) { Serial.println("Connect Failed"); } else if (error == OTA_RECEIVE_ERROR) { Serial.println("Receive Failed"); } else if (error == OTA_END_ERROR) { Serial.println("End Failed"); } }); }
23.385246
96
0.575885
ilesar
2b020805d27794fe0042a32d0458f0f35bf36ca4
5,433
cpp
C++
src/utils/nts.cpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
16
2020-04-16T02:07:37.000Z
2020-07-23T10:48:27.000Z
src/utils/nts.cpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
8
2020-07-13T17:11:35.000Z
2020-08-03T16:46:31.000Z
src/utils/nts.cpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
9
2020-03-04T15:05:08.000Z
2020-07-30T06:18:18.000Z
// // This file is a part of UERANSIM open source project. // Copyright (c) 2021 ALฤฐ GรœNGร–R. // // The software and all associated files are licensed under GPL-3.0 // and subject to the terms and conditions defined in LICENSE file. // #include "nts.hpp" #include "common.hpp" #include <stdexcept> #define WAIT_TIME_IF_NO_TIMER 500 #define PAUSE_POLLING_PERIOD 20 static std::unique_ptr<NtsMessage> TimerExpiredMessage(TimerInfo *timerInfo) { return timerInfo ? std::make_unique<NmTimerExpired>(timerInfo->timerId) : nullptr; } void TimerBase::setTimerAbsolute(int timerId, int64_t timeMs) { auto *timerInfo = new TimerInfo(); timerInfo->start = utils::CurrentTimeMillis(); timerInfo->end = timeMs; timerInfo->timerId = timerId; timerQueue.push(timerInfo); } int64_t TimerBase::getNextWaitTime() { if (timerQueue.empty()) return WAIT_TIME_IF_NO_TIMER; auto delta = timerQueue.top()->end - utils::CurrentTimeMillis(); return delta < 0 ? 0 : delta; } TimerInfo *TimerBase::getAndRemoveExpiredTimer() { if (timerQueue.empty()) return nullptr; TimerInfo *timer = timerQueue.top(); if (timer->end < utils::CurrentTimeMillis()) { timerQueue.pop(); return timer; } return nullptr; } TimerBase::~TimerBase() { while (!timerQueue.empty()) { delete timerQueue.top(); timerQueue.pop(); } } bool NtsTask::push(std::unique_ptr<NtsMessage> &&msg) { if (isQuiting) return false; { std::unique_lock<std::mutex> lock(mutex); msgQueue.push_back(std::move(msg)); } cv.notify_one(); return true; } bool NtsTask::pushFront(std::unique_ptr<NtsMessage> &&msg) { if (isQuiting) return false; { std::unique_lock<std::mutex> lock(mutex); msgQueue.push_front(std::move(msg)); } cv.notify_one(); return true; } bool NtsTask::setTimer(int timerId, int64_t delayMs) { return setTimerAbsolute(timerId, utils::CurrentTimeMillis() + delayMs); } bool NtsTask::setTimerAbsolute(int timerId, int64_t timeMs) { if (isQuiting) return false; { std::unique_lock<std::mutex> lock(mutex); timerBase.setTimerAbsolute(timerId, timeMs); } cv.notify_one(); return true; } std::unique_ptr<NtsMessage> NtsTask::poll() { { std::unique_lock<std::mutex> lock(mutex); if (!msgQueue.empty()) { auto ret = std::move(msgQueue.front()); msgQueue.pop_front(); return ret; } } if (isQuiting) return nullptr; TimerInfo *expiredTimer; { std::unique_lock<std::mutex> lock(mutex); expiredTimer = timerBase.getAndRemoveExpiredTimer(); } if (expiredTimer != nullptr) { auto msg = TimerExpiredMessage(expiredTimer); delete expiredTimer; return msg; } return nullptr; } std::unique_ptr<NtsMessage> NtsTask::poll(int64_t timeout) { timeout = std::min(timeout, (int64_t)WAIT_TIME_IF_NO_TIMER); if (isQuiting) return nullptr; { std::unique_lock<std::mutex> lock(mutex); if (!msgQueue.empty()) { auto ret = std::move(msgQueue.front()); msgQueue.pop_front(); return ret; } cv.wait_for(lock, std::chrono::milliseconds(std::min(timerBase.getNextWaitTime(), timeout))); } if (isQuiting) return nullptr; { std::unique_lock<std::mutex> lock(mutex); if (!msgQueue.empty()) { auto ret = std::move(msgQueue.front()); msgQueue.pop_front(); return ret; } } TimerInfo *expiredTimer; { std::unique_lock<std::mutex> lock(mutex); expiredTimer = timerBase.getAndRemoveExpiredTimer(); } if (expiredTimer != nullptr) { auto msg = TimerExpiredMessage(expiredTimer); delete expiredTimer; return msg; } return nullptr; } std::unique_ptr<NtsMessage> NtsTask::take() { return poll(WAIT_TIME_IF_NO_TIMER); } void NtsTask::start() { onStart(); if (!isQuiting) { thread = std::thread{[this]() { while (true) { if (this->isQuiting) break; if (pauseReqCount > 0) { pauseConfirmed = true; utils::Sleep(PAUSE_POLLING_PERIOD); } else { pauseConfirmed = false; this->onLoop(); } } }}; } } void NtsTask::quit() { bool expected = false; while (!isQuiting.compare_exchange_weak(expected, true, std::memory_order_relaxed, std::memory_order_relaxed)) return; cv.notify_one(); if (thread.joinable()) thread.join(); { std::unique_lock<std::mutex> lock(mutex); while (!msgQueue.empty()) msgQueue.pop_front(); } onQuit(); } void NtsTask::requestPause() { if (++pauseReqCount < 0) throw std::runtime_error("NTS pause overflow"); if (!isQuiting) cv.notify_one(); } void NtsTask::requestUnpause() { if (--pauseReqCount < 0) throw std::runtime_error("NTS un-pause underflow"); } bool NtsTask::isPauseConfirmed() { return pauseConfirmed; }
20.976834
114
0.587521
aligungr
2b02e681e1e6cc628902aaa9d435cdaf5da17a3b
259
cpp
C++
chapter3/demo2.cpp
bw-y/cpt
0d9f12ab605066429e9e7f54405cc3aa935874a1
[ "MIT" ]
null
null
null
chapter3/demo2.cpp
bw-y/cpt
0d9f12ab605066429e9e7f54405cc3aa935874a1
[ "MIT" ]
null
null
null
chapter3/demo2.cpp
bw-y/cpt
0d9f12ab605066429e9e7f54405cc3aa935874a1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int res_row(int a){ int i; for (i = 1; i <= a; i++){ cout << i << "x" << a << "=" << i * a << "\t"; } cout << "\n"; } int main(){ int i, t; for (i = 0; i < 10; i++){ res_row(i); } return 0; }
13.631579
50
0.420849
bw-y
2b0a59b87451791edf614a068c171ecab3611594
3,800
cpp
C++
src/scene/ParticleToolModel.cpp
sophia-x/SophiaGL
be6733c0d4b6a38431db2a0e1e7dace3890a75be
[ "MIT" ]
null
null
null
src/scene/ParticleToolModel.cpp
sophia-x/SophiaGL
be6733c0d4b6a38431db2a0e1e7dace3890a75be
[ "MIT" ]
null
null
null
src/scene/ParticleToolModel.cpp
sophia-x/SophiaGL
be6733c0d4b6a38431db2a0e1e7dace3890a75be
[ "MIT" ]
null
null
null
#include <camera/Camera> #include <scene/Model> #include <scene/WindowManager> namespace gl { static bool life_compare_heap(const shared_ptr<ParticleSpirit>& a, const shared_ptr<ParticleSpirit>& b) { return a->getLife() > b->getLife(); } static bool dist_compare(const shared_ptr<ParticleSpirit>& a, const shared_ptr<ParticleSpirit>& b) { const Camera& camera = *WindowManager::getWindowManager().currentCamera(); const vec3& camera_pos = camera.getPosition(); return distance(camera_pos, a->getPos()) > distance(camera_pos, b->getPos()); } shared_ptr<ParticleToolModel> ParticleToolModel::initTool(const vec4& p_border, GLenum p_mode, const string& p_texture, const string &vertex_path, const string &fragment_path, const vector<string>& uniforms) { // Create GLObj shared_ptr<GLObj> obj_ptr = GLObj::getGLObj(); { // Add GLBuffer obj_ptr->addBuffer("Vertices", GLDataObj::getGLBuffer((void*)0, 0, 3, GL_STATIC_DRAW, 0)); obj_ptr->addBuffer("xyzs", GLStreamObj::getGLBuffer((void*)0, 0, 4, GL_STREAM_DRAW, 1)); obj_ptr->addBuffer("colors", GLStreamObj::getGLBuffer((void*)0, 0, 4, GL_STREAM_DRAW, 1)); obj_ptr->addDrawObj("Stream", GLInstanceDraw::getDrawObj(obj_ptr->getBuffer("Vertices"), p_mode)); obj_ptr->addTexture("Particle", p_texture); return shared_ptr<ParticleToolModel>(new ParticleToolModel(obj_ptr, GLShader::getShader(vertex_path, fragment_path, uniforms), p_border, vector<string> {"Vertices", "xyzs", "colors"}, "Stream")); } } void ParticleToolModel::sortByLife() { push_heap(spirits.begin(), spirits.end(), life_compare_heap); } void ParticleToolModel::update(float delta) { Model::update(delta); sortByLife(); while (!spirits.empty() && !spirits[0]->alive()) { pop_heap(spirits.begin(), spirits.end(), life_compare_heap); spirits.pop_back(); } vector<shared_ptr<ParticleSpirit>> vec = spirits; sort(vec.begin(), vec.end(), dist_compare); vector<GLfloat> positions(4 * spirits.size()); vector<GLfloat> colors(4 * spirits.size()); for (size_t i = 0; i < vec.size(); i ++) { const ParticleSpirit& sp = *vec[i]; positions[4 * i + 0] = sp.getPos().x; positions[4 * i + 1] = sp.getPos().y; positions[4 * i + 2] = sp.getPos().z; positions[4 * i + 3] = sp.getSize().x; colors[4 * i + 0] = sp.getColor().x; colors[4 * i + 1] = sp.getColor().y; colors[4 * i + 2] = sp.getColor().z; colors[4 * i + 3] = sp.getColor().w; } gl_obj->setData("xyzs", &positions[0], positions.size()); gl_obj->setData("colors", &colors[0], colors.size()); gl_obj->bufferData(vector<string> {"xyzs", "colors"}); const shared_ptr<GLInstanceDraw>& draw_ptr = (const shared_ptr<GLInstanceDraw>&)gl_obj->getDrawObj("Stream"); draw_ptr->setCount(spirits.size()); } void ParticleToolModel::draw() const { glViewport(border[0], border[1], border[2], border[3]); shader_ptr->useShader(); { setter->setup(); const Camera& camera = *WindowManager::getWindowManager().currentCamera(); const mat4 &projection_matrix = camera.getProjectionMatrix(); const mat4 &view_matrix = camera.getViewMatrix(); mat4 VP = projection_matrix * view_matrix; glUniform3f(shader_ptr->getUniform("camera_right_worldspace"), view_matrix[0][0], view_matrix[1][0], view_matrix[2][0]); glUniform3f(shader_ptr->getUniform("camera_up_worldspace"), view_matrix[0][1], view_matrix[1][1], view_matrix[2][1]); glUniformMatrix4fv(shader_ptr->getUniform("vp"), 1, GL_FALSE, &VP[0][0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, gl_obj->getTexture("Particle")); glUniform1i(shader_ptr->getUniform("texture_in"), 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); gl_obj->draw(draw_vec, draw_obj); glDisable(GL_BLEND); } shader_ptr->unuseShader(); } }
35.514019
133
0.702895
sophia-x
2b13ec00d138447d7a7e9091e69ccd73caa8581f
1,895
cpp
C++
args/args_parse.cpp
zhangguolian/cpp-framework
47bdf67a9dd917fa25f4c0c1b9e57ea437967497
[ "Apache-2.0" ]
8
2019-06-06T06:20:03.000Z
2022-03-13T23:44:20.000Z
args/args_parse.cpp
Guolian-Zhang/cpp-framework
47bdf67a9dd917fa25f4c0c1b9e57ea437967497
[ "Apache-2.0" ]
null
null
null
args/args_parse.cpp
Guolian-Zhang/cpp-framework
47bdf67a9dd917fa25f4c0c1b9e57ea437967497
[ "Apache-2.0" ]
3
2019-12-02T04:06:57.000Z
2021-08-11T14:01:51.000Z
/* * * Copyright 2018 Guolian Zhang. * * 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 <args/args_parse.h> #include <logs/logs.hpp> namespace args { ArgsParse::ArgsParse() { } ArgsParse::ArgsParse(const std::string& usage) : desc_(usage) { } ArgsParse::~ArgsParse() { } bool ArgsParse::Parse(int argc, char* argv[]) { try { store(parse_command_line(argc, argv, desc_), args_list_); } catch(error_with_no_option_name& ex) { LOG_ERROR("ArgsParse::Parse fail, error:%s.", ex.what()); return false; } // Save all parameters to args_list_ notify(args_list_); // Determine if a parameter with no value exists, // and if it exists, assign it to true for (auto iter = option_list_.begin(); iter != option_list_.end(); iter++) { if (args_list_.count(iter->first) > 0) { *iter->second = true; } } return true; } void ArgsParse::PrintfDescription() { std::cout << desc_ << std::endl; } std::shared_ptr<bool> ArgsParse::Get(const std::string& name, const std::string& description) { desc_.add_options()( name.c_str(), description.c_str() ); std::shared_ptr<bool> result; result.reset(new bool(false)); option_list_[name] = result; return result; } } // namespace args
24.934211
80
0.637467
zhangguolian
2b16122fc196ca05073fae94b55d9eea16d67650
325
cpp
C++
abc/abc161/d/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
3
2019-06-25T06:17:38.000Z
2019-07-13T15:18:51.000Z
abc/abc161/d/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
abc/abc161/d/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
#include "template.hpp" int main() { ll(K); queue<ll> q; repi(i, 9) { q.push(i); } ll ans; rep(_, K) { ans = q.front(); q.pop(); ll k = ans % 10; if (k >= 1) { q.push(10 * ans + k - 1); } q.push(10 * ans + k); if (k <= 8) { q.push(10 * ans + k + 1); } } out(ans); }
14.772727
31
0.393846
wotsushi
2b20bdfd870d939461e01b3615c2e1346878d459
26,548
cpp
C++
Darcy_Lights_W_ButtonsANDSOUNDPlayMem/AudioSampleBeat10.cpp
Drc3p0/InteractivePallette
d7180d43533850803a3f83d1f5f49e20e32509f5
[ "MIT" ]
1
2019-10-23T17:46:42.000Z
2019-10-23T17:46:42.000Z
Darcy_Lights_W_ButtonsANDSOUNDPlayMem/AudioSampleBeat10.cpp
Drc3p0/InteractivePallette
d7180d43533850803a3f83d1f5f49e20e32509f5
[ "MIT" ]
null
null
null
Darcy_Lights_W_ButtonsANDSOUNDPlayMem/AudioSampleBeat10.cpp
Drc3p0/InteractivePallette
d7180d43533850803a3f83d1f5f49e20e32509f5
[ "MIT" ]
null
null
null
// Audio data converted from WAV file by wav2sketch #include "AudioSampleBeat10.h" // Converted from 01.wav, using 44100 Hz, u-law encoding const unsigned int AudioSampleBeat10[2369] = { 0x01002500,0xACA69E92,0xB2B3B2B1,0xB3B1B1B1,0xBEBCB9B6,0xB3B8BCBE,0xB2ADABAF,0xC5C3C0B9, 0xC5C5C6C6,0xCBC9C7C6,0xC6C9CBCB,0xC6C4C3C4,0xCFCECCC9,0xCFCECECF,0xD4D3D2D0,0xD0D1D3D4, 0xC8C9CACC,0xCBCAC9C8,0xCECDCCCB,0xCDCECECE,0xCFCECDCD,0xCDCFD0D0,0xC8C8C9CB,0xCFCDCBC9, 0xCBCDCFD0,0xC6C6C6C8,0xCECDCAC8,0xCECFD0CF,0xCDCDCDCE,0xCCCCCDCD,0xC9C9CACB,0xC5C6C7C8, 0xC5C4C3C4,0xC6C7C7C6,0xC0C1C3C5,0xBBBDBEBE,0x9BAAB3B8,0x24221A03,0x21232425,0x1F1C1D20, 0x25252421,0x8F051822,0x2E1D8091,0x43423F37,0x333A4042,0x89021928,0x2C221382,0x33353432, 0x25282D31,0x24232323,0x29272524,0x3030302D,0x8316242B,0x09929895,0x30302A20,0xB7A61028, 0xCECBC7C2,0xD4D2D1D0,0xCCD2D4D4,0x2C0EB1C3,0xBEA61E2F,0xD7D4D0C8,0xDEDDDBD9,0xD9DBDCDD, 0xDBDAD8D8,0xDBDDDDDD,0xDBD9D9DA,0xE4E2E1DE,0xEAE8E7E5,0xECEDECEB,0xE3E5E8EA,0xE0E0E0E1, 0xE3E2E2E1,0xEAE8E7E5,0xECECECEB,0xEAEBECEC,0xD9E0E4E7,0xC5C9CED3,0x3F21B0C0,0x2C444A48, 0xD4D3CCB7,0x2CAAC5D0,0x373B3F3C,0x4B443C36,0x51525250,0x3640464C,0x362F2A30,0x4B494540, 0x3D404549,0x5F554B41,0x6A6A6864,0x65666869,0x5D616364,0x3C455057,0x3C3C3937,0x95092A37, 0x53483613,0x5E5F5E5A,0x4752575B,0xD5CBB431,0xC8D4D9D9,0x504D419B,0xC4A6394A,0xE0DAD5D0, 0xF0EDE8E3,0xF4F4F3F2,0xF3F3F3F4,0xF0F1F2F2,0xEEEEEFF0,0xEEEEEEEE,0xEFEFEEEE,0xECEEEFEF, 0xEDECEBEB,0xEEEFEFEE,0xE9E9EAEC,0xEBECEBEA,0xE4E5E7E9,0xE5E6E5E4,0xCAD6DFE3,0xABA8ADBB, 0x493A15A5,0x49515351,0x3E25243A,0x66625B50,0x5C626567,0x44434953,0x635E554C,0x6C6C6A67, 0x6E6D6D6D,0x66696C6D,0x65626263,0x6C6D6C68,0x60606468,0x706C6662,0x5A656C70,0x03A61746, 0x52504839,0x51525253,0xB52E454E,0xC1CDD0C9,0x4F50461F,0xD4CAA442,0x29C2D2D6,0x5858554B, 0x43485055,0x61574D44,0x71716E68,0x4B60686F,0xD4D2CBA7,0xD8D5D4D4,0xBCD1D8D9,0x6461563F, 0x515C6265,0xB0B6A239,0x5F554726,0x66666563,0x69696767,0x385B6568,0xF7F2E8D5,0xFAFBFBFA, 0xFAFAFAFA,0xF5F8F9FA,0xE9EDF1F3,0xCCD7E0E5,0xC7BBB5C0,0xE1DED9D2,0xEBE6E3E2,0xFAF8F4F0, 0xFBFCFCFC,0xF8F9F9FA,0xF3F5F6F7,0xF2F1F1F1,0xF0F2F3F2,0xD8E0E5EB,0xD2D3D3D4,0x23A7C2CD, 0xD3C39C29,0xE0E2E1DD,0xCBCCD2DA,0xE9E3DCD2,0xF2F1F1EE,0xF1F1F1F1,0xF0F1F1F1,0xEFEEEFF0, 0xF0F0F0F0,0xE6E9ECEF,0xE8E6E5E5,0xEAECECEA,0xE0E2E5E8,0xE8E4E1E0,0xF0F0EEEB,0xEBECEEEF, 0xECEBEBEB,0xEAEBECEC,0xE2E5E7E9,0xC0CCD6DE,0xC3C1B9B7,0x60501EBD,0x696E6E69,0xD4BF4860, 0x2EC0D2D7,0x5F59534A,0x74716B64,0x70737575,0x6665676B,0x6B6C6B69,0x67666769,0x7572706B, 0x79797877,0x77787979,0x73737576,0x71727272,0x385B676E,0xEAE6E0CF,0xEFEEEDEC,0xF0F1F1F0, 0xDCE3E9EE,0x0BBBC9D3,0x6B635745,0x636B706F,0x86B12E53,0x6A665E4A,0x52596368,0x6F675E53, 0x56677071,0xD1D9D5B1,0x635F5291,0x615F6062,0x74716C66,0x71737475,0x71717070,0x6E707171, 0x706F6E6D,0x61676C6F,0x47464E57,0x5655524D,0x5F5A5756,0x68676562,0x63656667,0x51595F62, 0xD7CEB33C,0xD5D9DBDB,0xD6D2D1D2,0xDADEDDDA,0x4311C4D3,0x3A494F4D,0xD0CBC19C,0xDCD7D4D2, 0xE4E5E3E0,0x2AC9DAE2,0x64625C51,0x64646565,0x63636464,0x61626263,0x63626262,0x60616263, 0x57585A5D,0x5F5C5957,0x61616160,0x60606161,0x60606060,0x5D5E5E5F,0x4B54595B,0xE1D5C031, 0xECEDECE7,0xC8D7E2E8,0xC6B29FB1,0xE0DFDAD3,0xE6E3E1E1,0xF3F1EEE9,0xF9F8F7F5,0xF4F7F9F9, 0xCCDBE6F0,0xB6B3B1BA,0x4D4222AF,0xE2CA364C,0xF9F8F5EF,0xF1F3F6F8,0xE7EAECEF,0xD0D5DDE3, 0xD8D5D1CE,0xDBD9D9D9,0xF1ECE6E0,0xEFF1F3F2,0xE4E4E6EA,0xD0DCE2E4,0x4B4F44A1,0xDFD6C233, 0xDBDEE1E1,0xE9E4E0DC,0xF4F3F1ED,0xFAF9F8F6,0xF5F7F9FA,0xF4F4F3F4,0xEDF1F3F4,0xD4D6DEE5, 0xE5E2DED8,0xE5E5E5E6,0xEFEDE9E6,0xE6EBEEF0,0xDCDBDEE2,0xDDE0E0DE,0xBCC8D2D8,0x453821A5, 0x5857534E,0x434E5357,0xB0A41033,0xB1B6B7B4,0x5B4F3890,0x72706B64,0x70717272,0x6A6B6C6E, 0x60646769,0x34414E57,0x38342F2C,0x47413D3B,0x615D5650,0x65656564,0x6A686665,0x6F70706E, 0x5260666C,0xC1BFA93A,0x1591AFBC,0xABAC9E0A,0x5F53400E,0x706F6B66,0x6F707070,0x686B6D6E, 0x63636466,0x6B696765,0x6E6D6D6C,0x7070706F,0x66696C6F,0x67656464,0x6A6A6A69,0x706D6B6A, 0x71717271,0x64676A6E,0x5A5E6062,0x3D444E54,0x554E443D,0x6865615C,0x706F6D6B,0x6F707070, 0x696B6D6E,0x5E606266,0x6A666260,0x7070706D,0x70706F70,0x71717171,0x70707070,0x71727171, 0x70707171,0x71717171,0x70707171,0x70707070,0x67696C6F,0x65656565,0x69676666,0x6C6C6B6A, 0x6365686A,0x63626162,0x5B606263,0x58565557,0x54585A5A,0x4943454D,0x615F5952,0x4C555B60, 0x403C3D43,0x13353F41,0xDCD3C8B5,0xEAE9E6E2,0xBAD7E3E8,0x65625A47,0x69686867,0x6B6C6B6A, 0x6A6A6A6B,0x6B6C6C6B,0x63646669,0x69676463,0x6366696A,0x615F5E60,0x6A696764,0x67676869, 0x6E6C6A68,0x6B6D6F6F,0x61636669,0x4250575D,0xCDC7B81A,0xB9C5CBCE,0x302E1EA3,0xC1B18726, 0xDAD5D1C9,0xE3E2E1DE,0xE5E5E5E4,0xE2E3E4E4,0xD7DCDFE1,0x84B8C8D2,0x393B3A31,0x433B3535, 0x4D504F4A,0x01223945,0x4A423318,0x38444A4D,0x37271C27,0x4D4C4842,0x52504E4D,0x5E5B5855, 0x66646260,0x63666868,0x4C525860,0x43454748,0xA01B323D,0xD8CFC2B4,0xEAE9E6E1,0xDDE1E5E9, 0xE7E3DFDC,0xE6E9EAEA,0xE2E1E2E4,0xE3E3E3E3,0xE7E5E4E3,0xE7E9EAE9,0xE4E2E3E5,0xE5E7E7E6, 0xC1CCD7E0,0xC2C4C0BC,0x52472BB4,0x2E475254,0xADBBBDAE,0x3F3D3519,0x43403D3D,0x504E4B47, 0x5B575452,0x5E60605E,0x5555575A,0x57585856,0xBF214652,0xD8D8D5CF,0xB0C3CFD4,0x37342E13, 0x5149423B,0x4E535554,0xB0A82141,0x413B27A0,0xC0A42F3F,0xD3D1D0CA,0xDEDAD7D4,0xE3E2E2E0, 0xE4E5E5E4,0xCAD6DFE2,0x212C1AB3,0xC5C2B8A2,0xCEC9C6C6,0xDDDBD7D2,0xD6DADCDE,0xC2C8CFD3, 0x94A4B1BA,0x483B2911,0x62605A53,0x51596062,0xCEC19640,0xE1DFDAD5,0xE1E2E3E3,0xD5D7DADE, 0xD7D7D6D5,0xCED2D5D7,0x83B0BEC6,0x43413A2D,0xBE843641,0xDEDBD5CE,0xDDDEDFDF,0xE0E0DEDD, 0xE0E1E1E1,0xDDDEDFE0,0xD8DADBDC,0xDDDBD9D8,0xE1E1E1E0,0xE0DFE0E0,0xE1E1E1E0,0xDFDFE0E0, 0xE0E0E0DF,0xCED4D9DE,0xC8C4C3C6,0xD3D3D1CE,0xCED0D1D2,0xC9CBCCCD,0xC8C8C8C8,0xBFC4C7C8, 0x23189BB2,0xB6AA8B1E,0xBABDBEBC,0xBEBAB7B8,0xC4C4C3C1,0xC4C2C3C3,0xCECCC9C6,0xC9CDCFCF, 0xBABDC1C5,0xC0BEBAB9,0xC2C3C3C2,0xBABBBEC1,0xC2C0BCBA,0xC6C6C5C4,0xC2C3C4C5,0xBFC0C0C1, 0xBDBDBEBE,0xABB3B8BB,0x2920069D,0x3A36332F,0x4946423F,0x5452504D,0x53555655,0x36414950, 0x362F292D,0x4242413D,0x3D3E4041,0x3C3C3C3C,0x4945413F,0x5553514E,0x5A585756,0x60605F5C, 0x595B5E60,0x58575757,0x56585959,0x4F505254,0x4E4D4C4D,0x53525150,0x54535353,0x615E5A56, 0x66666563,0x64646565,0x64646464,0x6A686665,0x6C6D6D6C,0x6667696B,0x66666666,0x65646465, 0x706C6966,0x70717271,0x67696C6F,0x6A686666,0x6D6E6E6C,0x6A6A6B6C,0x71706E6C,0x71717272, 0x73727171,0x73747574,0x6E6E7071,0x6E706F6E,0x6566696C,0x6E6B6865,0x71717170,0x73727171, 0x6F717273,0x6566686B,0x69686766,0x65666768,0x68666564,0x6A6B6B6A,0x68676768,0x73716F6B, 0x6F717373,0x6A69696B,0x6F6F6E6C,0x6D6C6D6E,0x7171706F,0x6D6E7071,0x6F6E6D6D,0x6C6C6E6F, 0x73716F6D,0x74757574,0x696C7072,0x62646567,0x60606061,0x5E606161,0x5E5B5A5C,0x68666461, 0x61646667,0x5256595E,0x43454A4F,0x4A494644,0xB4224047,0xCACECDC5,0xA2ABB8C3,0x94A6A8A3, 0x47433A25,0x1D374247,0x8EA6ABA0,0x3B393324,0x3537383A,0x2C303234,0x42372F2A,0x5A57534C, 0x5055595B,0x1D2B3A46,0x13151414,0x0682000B,0x26231E14,0x4339312A,0x5B57534C,0x595B5C5D, 0x57575657,0x51545657,0x3C40444A,0x363A3C3C,0x372C2A30,0x55524C43,0x4C515455,0x4E494748, 0x55545351,0x5F5B5856,0x64646361,0x68666565,0x6D6D6C6A,0x67696A6C,0x69686767,0x6A6A6A69, 0x6C6B6B6A,0x65686A6C,0x5B5B5F62,0x6663605D,0x6D6C6A68,0x6F6F6F6E,0x6E6F6F6F,0x6E6E6E6E, 0x6C6D6E6E,0x61636769,0x5C5B5B5E,0x6261605E,0x64636362,0x67676665,0x66666767,0x63636465, 0x61616262,0x60606060,0x5F5F5F60,0x60605F5F,0x5E5F5F60,0x5256595C,0x2537434C,0x2F1C060E, 0x4D48423A,0x53535250,0x484B5052,0x524E4846,0x56585755,0x494C5154,0x3F444647,0xB6AC0631, 0xA0A8B2B7,0xC8C1B4A5,0xC1C9CDCD,0x811A85B0,0xCFC8C0AD,0xD2D2D2D1,0xD5D4D3D2,0xD7D7D7D6, 0xD7D6D6D6,0xDADAD9D8,0xD3D6D8DA,0xCFCDCED0,0xDBD7D4D1,0xE3E2E0DE,0xE5E5E5E4,0xE4E5E5E5, 0xE1E2E3E4,0xD7D8DADE,0xE0DDDAD8,0xDADDE0E0,0xDDDAD8D8,0xE3E2E1E0,0xE6E4E3E3,0xEAEAE9E8, 0xE3E5E7E9,0xE6E4E3E2,0xECEBEAE8,0xEAEBECEC,0xEBEAE9EA,0xF0F0EFED,0xEBEEF0F0,0xEAE9E9EA, 0xF1F0EFED,0xF2F3F3F2,0xF1F1F1F2,0xF7F5F4F2,0xF6F7F8F8,0xF1F1F3F4,0xF3F3F2F1,0xF0F1F2F3, 0xEEEEEFF0,0xEBECEDEE,0xE9E9E9EA,0xECEBEAE9,0xF1F1F0EE,0xF3F3F2F2,0xF4F3F3F3,0xF6F6F5F4, 0xF5F5F6F6,0xF3F4F4F4,0xF2F2F2F3,0xF2F2F2F2,0xF2F2F2F2,0xF2F2F2F2,0xF2F2F2F2,0xF1F2F2F2, 0xF2F2F1F1,0xF2F2F2F2,0xF2F2F2F2,0xF1F1F1F2,0xF0F0F0F0,0xEDEFF0F0,0xE9E9EAEC,0xEDEBEAE9, 0xEBEDEDED,0xE6E7E8EA,0xE8E7E7E6,0xE5E6E7E7,0xE4E4E4E4,0xE7E7E6E5,0xE7E7E7E7,0xE6E6E6E6, 0xE7E6E6E6,0xE8E8E8E7,0xE5E6E7E7,0xE5E5E5E5,0xE2E3E4E5,0xE3E1E1E1,0xE9E8E6E4,0xECECEBEA, 0xECECECEC,0xEAEBEBEC,0xE9E9E9EA,0xE7E7E8E8,0xE8E8E8E7,0xE7E7E8E8,0xE6E6E6E6,0xECEAE8E7, 0xF0F0EFEE,0xEEEFEFF0,0xEFEFEEEE,0xEEEFEFEF,0xEDEDEDED,0xEEEEEDED,0xEEEEEEEE,0xECEDEDED, 0xEBECECEC,0xEBEBEBEB,0xECECECEB,0xE9EAEBEC,0xEAE9E9E9,0xECECEBEB,0xEBEBEBEC,0xEAEAEBEB, 0xE8E9E9EA,0xE9E8E8E8,0xE8E9E9E9,0xE4E5E6E7,0xE5E4E4E4,0xE6E6E6E6,0xE4E4E4E5,0xE6E5E5E4, 0xE6E6E7E7,0xE4E5E5E5,0xE4E4E4E4,0xE2E3E4E4,0xDFE0E0E1,0xDDDEDFDF,0xD8D9DADC,0xDCDBD9D8, 0xDADCDDDD,0xD9D8D7D8,0xDCDDDDDB,0xD1D4D7DA,0xCCCBCCCE,0xD2D1CFCD,0xD4D4D3D2,0xD3D4D4D4, 0xCDD0D1D2,0xCCCAC9CB,0xD6D4D2D0,0xD2D3D5D6,0xD2D1D1D1,0xD2D3D4D3,0xCECFD0D1,0xC7CACCCD, 0xC6C3C3C5,0xD0D0CDC9,0xC6C9CDD0,0xCAC8C6C5,0xC3C7CACB,0xB9B7B8BE,0xBEC1C0BE,0xA4A5B0B7, 0xC2BFB6AC,0xA2B4BEC2,0x84171C0C,0x1D909E9B,0x36393730,0x16152330,0x403B3325,0x40414242, 0x43434241,0x23323B41,0x84919008,0x07080B07,0x38302313,0x3B3F403E,0x41393637,0x51504C47, 0x4D4D4F50,0x50504F4D,0x504F4F50,0x57565351,0x52555758,0x52505051,0x55555553,0x54545455, 0x55555554,0x52535454,0x50505152,0x59565351,0x5D5E5E5C,0x5557595B,0x58575655,0x58585858, 0x58585858,0x53545557,0x59575553,0x5557595A,0x51505052,0x56565553,0x53535455,0x5D5A5754, 0x585B5E5E,0x474A4F53,0x514F4B48,0x50515353,0x4C4A4A4C,0x5152514F,0x45484C50,0x4E4B4745, 0x494D4F50,0x45434446,0x514F4B47,0x59585653,0x595A5B5B,0x56555657,0x5A595857,0x5A5A5A5A, 0x58595959,0x57565757,0x59595857,0x57575859,0x59585756,0x595A5A5A,0x5A595858,0x5B5C5B5B, 0x56565859,0x5A595756,0x5A5B5C5B,0x57575859,0x55565757,0x52525354,0x55545352,0x52535555, 0x53525151,0x53545454,0x474A4D51,0x4B494747,0x4D4E4E4D,0x4044484B,0x30303338,0x32343432, 0x060E202B,0x3B352A18,0x0630393E,0xB9BBB7AC,0x0F8DA5B3,0xB7AB960A,0xCBC8C4C0,0xCDCECECD, 0xC8C9CACC,0xC8C8C8C8,0xCAC8C8C8,0xD2D1D0CD,0xC6CBD0D1,0xC2C0C0C2,0xC9C8C6C4,0xCFCCCAC9, 0xD0D1D2D1,0xBFC2C6CC,0xC9C5C1BF,0xCACCCCCC,0xCAC8C8C9,0xD1D0CECC,0xD2D3D2D2,0xC4CACFD1, 0xA9AEB4BD,0xB3B1AEAA,0xB6B5B4B4,0xBBBAB9B7,0xC0BFBDBC,0xC5C4C3C2,0xC0C2C3C4,0xBFBFBFC0, 0xBBBDBEBF,0xAFB1B4B8,0xBAB4B0AD,0xC7C6C4C0,0xC7C7C7C7,0xD0CECCC9,0xC8CBCDCF,0xCAC8C6C6, 0xCCCDCDCD,0xCDCBCACA,0xD3D2D1D0,0xD4D3D3D2,0xDCDAD9D6,0xDCDCDCDC,0xDADBDBDB,0xD9D9D9DA, 0xDCDBDBDA,0xDDDCDCDC,0xE3E1E0DE,0xE1E2E3E3,0xE0E0DFE0,0xE3E3E3E1,0xDFE0E1E3,0xDDDDDDDE, 0xDADBDCDD,0xDDDCDADA,0xDEDFE0DF,0xD5D6D8DB,0xDAD9D7D6,0xD8DADBDB,0xD3D4D5D6,0xD4D4D3D3, 0xDAD8D6D5,0xDEDFDEDC,0xD6D8DBDD,0xD4D3D3D4,0xD7D7D6D5,0xD1D4D6D7,0xCCCBCBCE,0xD2D2D1CF, 0xCCCED0D2,0xD1CFCDCB,0xD4D4D4D2,0xD3D3D4D4,0xD5D4D4D4,0xD6D7D6D6,0xD1D2D4D5,0xD1D0CFD0, 0xD1D2D2D2,0xD1D1D0D1,0xD6D5D4D3,0xD4D4D5D6,0xD3D3D3D3,0xD3D3D3D3,0xD2D2D2D3,0xD5D4D3D3, 0xD6D6D6D5,0xD8D7D6D6,0xD9DAD9D9,0xD8D8D8D9,0xD9D9D9D8,0xD5D6D7D8,0xD6D5D5D4,0xD5D5D6D6, 0xD6D5D4D4,0xD7D8D7D7,0xDAD8D8D7,0xDEDEDDDB,0xDDDDDDDE,0xDBDBDCDC,0xDBDADADA,0xDCDCDCDB, 0xDEDDDCDC,0xE3E3E1E0,0xE0E1E2E3,0xE2E0E0DF,0xE3E4E4E3,0xDFE0E1E2,0xDFDFDFDF,0xDDDDDEDF, 0xE1E0DEDD,0xDFE0E1E1,0xD9D9DADC,0xDEDEDCDA,0xD8DADCDE,0xD5D5D5D6,0xD7D6D6D5,0xE0DFDCD9, 0xE0E1E2E1,0xD6D8DBDE,0xDAD8D6D6,0xDCDDDDDC,0xD0D3D7DA,0xCDC9C9CB,0xD5D5D3D0,0xD1D2D3D5, 0xD5D3D1D0,0xDADAD9D7,0xD7D8D9D9,0xD8D8D7D7,0xDBDBDAD9,0xDADADADA,0xE0DFDDDB,0xDEDFE0E0, 0xE1DFDEDD,0xE4E4E4E2,0xE0E1E2E4,0xE1E0DFDF,0xE2E2E2E1,0xE3E2E2E2,0xEAE8E6E5,0xEDEDEDEC, 0xEDEDEDED,0xEDEDEDED,0xEAEAEBEC,0xEAEAE9E9,0xE9EAEAEA,0xE9E9E9E9,0xE9E9E9E9,0xE7E7E8E8, 0xE8E8E8E7,0xE5E6E7E8,0xE4E4E4E5,0xE3E3E4E4,0xE2E2E2E3,0xE2E2E2E2,0xE1E1E2E2,0xE1E1E1E1, 0xE1E1E1E1,0xE0E0E0E0,0xE0E0E0E0,0xDFE0E0E0,0xDEDEDEDF,0xDBDCDDDE,0xDADADADB,0xDBDBDBDB, 0xD8D9DADA,0xD8D8D8D8,0xD7D7D8D8,0xD4D4D5D6,0xD4D4D4D4,0xD0D1D3D4,0xD0CFCFCF,0xD1D1D1D0, 0xCED0D0D1,0xCDCDCDCD,0xCBCCCDCD,0xC7C8C9CA,0xC7C7C6C6,0xC4C6C6C7,0xC1C2C2C3,0xC3C3C2C2, 0xBEC0C1C2,0xB9B9BABC,0xB9B9B9B9,0xB6B7B8B8,0xACB1B3B5,0x91969FA5,0xA9A29A93,0xA8ADAFAD, 0x0A0391A0,0x9E999002,0x27188799,0x32333230,0x38343231,0x4141403D,0x3D3E3F41,0x4342413F, 0x44454544,0x41434344,0x403D3E40,0x514D4742,0x58575654,0x56575758,0x50525355,0x514F4E4F, 0x54545352,0x53535354,0x5C595654,0x6161605F,0x61616161,0x61616161,0x60606161,0x60606060, 0x63626261,0x61626263,0x62616161,0x65656463,0x65656565,0x66666666,0x64646566,0x65646363, 0x67676665,0x68686868,0x69696969,0x68686869,0x69696968,0x67686969,0x66656667,0x68686766, 0x67686969,0x64646566,0x68676665,0x67686868,0x65656566,0x67676666,0x65666667,0x67666665, 0x65666667,0x64646464,0x67676665,0x64656667,0x62626363,0x61626262,0x61616161,0x64636362, 0x62626364,0x60606061,0x5F606060,0x5F5E5E5E,0x64636261,0x64646464,0x64646363,0x65656565, 0x66666565,0x68686867,0x69696969,0x67686868,0x65656566,0x68676665,0x6D6C6A69,0x6D6E6E6D, 0x6E6D6D6D,0x7170706F,0x6E707070,0x6E6D6D6E,0x6F6F6F6E,0x6F6F6F6F,0x70706F6F,0x71717171, 0x70717171,0x6F6F6F70,0x71707070,0x70707171,0x70707070,0x70707070,0x7070706F,0x70707070, 0x70707070,0x6F707070,0x6C6D6D6E,0x6D6D6D6C,0x6B6C6C6D,0x6A6A6A6B,0x6B6B6B6A,0x6B6B6C6B, 0x6B6B6B6B,0x6D6D6C6C,0x6C6C6D6D,0x6869696B,0x68686868,0x68686868,0x68686868,0x69696968, 0x6A6A6969,0x696A6A6A,0x65666768,0x65656565,0x65656565,0x64646464,0x64646464,0x63636364, 0x62626262,0x64646363,0x63636464,0x65646463,0x63646565,0x61616162,0x65646362,0x67666565, 0x6C6B6968,0x696B6C6C,0x66666768,0x69686766,0x68696969,0x66666667,0x6A696967,0x65666869, 0x64646364,0x66666665,0x66656565,0x67676766,0x64656566,0x63636464,0x60606162,0x62616160, 0x5D5F6161,0x5A59595A,0x5B5C5C5B,0x5858595A,0x5D5B5A59,0x5F5F5E5E,0x5D5E5F5F,0x58595B5C, 0x56565657,0x54545555,0x56555454,0x58595958,0x4D515456,0x46464649,0x4C4B4948,0x4E4D4D4C, 0x50504F4E,0x474A4D4F,0x40404244,0x42424140,0x27323A40,0x291F151B,0x3D3B3832,0x38393B3C, 0x2F343638,0x978E1124,0x03829096,0x9F9C9385,0x160E8C9A,0xB3A89210,0xA7B4B8B8,0x292C2402, 0xB6AD961B,0xB8BBBDBB,0x90A1ACB3,0x9F870B08,0xB7B6B3AB,0xB4B2B3B5,0xC6C3C0B9,0xBDC1C4C6, 0xC5C0BBBA,0xCFCFCDCA,0xC8C9CBCE,0xC7C7C7C7,0xC8C7C7C7,0xC9CACAC9,0xC4C4C5C7,0xD2CFCAC6, 0xD5D5D5D4,0xD3D3D4D5,0xD4D3D3D3,0xD1D2D3D3,0xCDCDCED0,0xD7D4D1CF,0xD6D8D9D9,0xD1D0D1D3, 0xDAD8D6D3,0xD5D7D9DA,0xD4D3D3D3,0xD4D4D5D4,0xD4D3D3D3,0xDCDAD8D6,0xDFDFDEDD,0xDADCDDDE, 0xD0D2D4D7,0xD4D3D1D0,0xD6D7D7D6,0xD7D6D6D6,0xD5D6D7D7,0xD2D1D2D3,0xDBD9D6D4,0xDBDCDCDC, 0xD9D9D9DA,0xD8D9D9D9,0xD6D6D6D7,0xD8D7D6D6,0xDBDAD9D9,0xDDDDDCDB,0xDDDDDEDE,0xD7D8DADC, 0xD6D5D5D5,0xDEDCDAD8,0xDFDFDFDE,0xDFDFDFDF,0xDDDDDEDF,0xDCDCDCDC,0xDBDCDCDC,0xDDDCDCDB, 0xDDDEDEDE,0xDADBDBDC,0xD8D9DADA,0xD4D5D5D7,0xD9D8D6D5,0xD5D7D8D9,0xD4D3D3D4,0xD9D8D6D5, 0xDBDBDADA,0xDCDCDCDC,0xDBDBDBDB,0xD9DADBDB,0xD3D4D6D8,0xD3D2D2D2,0xD7D6D6D5,0xD6D6D7D7, 0xD7D7D7D6,0xD6D6D7D7,0xD4D4D5D5,0xD5D4D4D4,0xD4D4D5D5,0xD3D3D3D3,0xD4D4D3D3,0xD2D3D4D4, 0xD1D1D1D2,0xD0D0D1D1,0xCFCFD0D0,0xD1D0D0D0,0xD0D0D1D1,0xD0D0D0D0,0xD1D1D1D1,0xD1D1D1D1, 0xD2D2D2D1,0xD0D1D1D2,0xCACBCDCF,0xC8C8C9C9,0xC8C8C9C9,0xC8C8C8C8,0xCDCCCBC9,0xCCCDCDCD, 0xCACBCBCC,0xC2C4C7C9,0xB5B6B9BE,0xC0BEBAB6,0xB9BDC0C1,0xB5B3B3B6,0xB7B9B9B7,0xACAEB1B4, 0xB5B3B1AD,0xAFB1B4B5,0xA5A7A8AB,0x148297A1,0x1F21211F,0x030F141A,0xA9A39A8D,0x1497A6AA, 0x2F323128,0x150C1725,0x433F3528,0x3C414445,0x30303236,0x8A1A272D,0xA3A7A7A1,0x9A93939B, 0x07A0A4A2,0x49443B2B,0x4A4B4C4C,0x48474748,0x43464748,0x3133383F,0x423D3632,0x48494846, 0x42434446,0x4A474543,0x4C4C4C4B,0x4F4E4D4C,0x50505050,0x504E4E4E,0x53535251,0x53535353, 0x55555453,0x51525455,0x504F4E4F,0x53535251,0x50505152,0x4E4F4F4F,0x4B4B4C4D,0x53514F4C, 0x56575755,0x50515254,0x53535251,0x50515353,0x4B4B4C4E,0x48494A4B,0x4C494847,0x53525150, 0x52535353,0x50505151,0x51504F4F,0x56555452,0x57575756,0x59595857,0x595A5A5A,0x56565758, 0x51535455,0x504F4F50,0x57555452,0x54555757,0x51515152,0x53535352,0x54545353,0x55565655, 0x4F505254,0x50504E4E,0x52515151,0x55545352,0x50525455,0x4243464B,0x46464442,0x43444546, 0x4A474543,0x5352504E,0x54545453,0x54545454,0x4E515253,0x4546484B,0x45464646,0x41414244, 0x4D494643,0x52515150,0x54535252,0x55555555,0x54545454,0x52535454,0x47494D50,0x42434546, 0x38383B3F,0x43413F3B,0x3B404243,0x36343436,0x393A3A38,0x38353537,0x4C48433E,0x4E505150, 0x383E4349,0x403D3937,0x29363D40,0x118F8F13,0x35353126,0x0A192731,0x31281C0D,0x38383735, 0x44413E3A,0x4B4B4A47,0x3F44474A,0x24293137,0x302D2925,0x22272C30,0x2A252120,0x23292D2D, 0x2C221C1E,0x35383733,0xA899192E,0x1696A7AC,0x2C303028,0x8D831423,0x1D1B1084,0xC1B4A00E, 0xD0D0CEC8,0xCCCACBCE,0xDAD7D4D0,0xD3D7DADB,0xC8C8CACF,0xC8CBCBCA,0xB3B6BDC3,0xC7C3BDB6, 0xCDCDCCCA,0xD0CFCECD,0xCCCECFD0,0xC8C8C9CA,0xCACAC9C9,0xCACACACA,0xC8C9C9C9,0xC4C5C7C8, 0xB7BABEC1,0xC4C0BAB7,0xCECECCC9,0xC6C8CACD,0xCAC8C7C6,0xCDCDCDCC,0xCCCBCBCC,0xD4D2D0CE, 0xDBD9D8D6,0xE1E0DFDD,0xE0E1E1E1,0xDADBDCDE,0xDCDCDBDA,0xD8D8DADB,0xDEDBD9D8,0xE1E1E1E0, 0xE3E2E1E1,0xE4E4E4E4,0xE2E3E3E4,0xE4E3E3E3,0xE2E3E3E4,0xE2E2E2E2,0xDFE0E1E1,0xDBDBDCDD, 0xDDDDDDDC,0xDBDBDCDD,0xDEDDDCDB,0xE2E1E0DF,0xE5E5E4E3,0xE1E3E4E5,0xE0DEDEE0,0xE2E2E1E0, 0xE2E2E2E2,0xE3E4E4E3,0xE1E1E2E3,0xE6E5E3E2,0xE4E5E6E6,0xE3E2E2E3,0xE3E4E4E3,0xE3E3E3E3, 0xE5E5E5E4,0xE5E5E5E5,0xE9E8E7E6,0xECEBEBEA,0xECECECEC,0xEAEAEBEB,0xE8E9E9E9,0xE7E7E8E8, 0xE7E7E6E6,0xEAEAE9E8,0xECEBEBEB,0xECECECEC,0xE9EAEBEC,0xE6E6E7E8,0xEAE9E7E6,0xE9EAEBEB, 0xE6E6E7E8,0xE8E8E7E7,0xEBEAE9E9,0xEEEEEDEC,0xEAEBECED,0xE9E9E9E9,0xEAEAEAEA,0xE9E9E9E9, 0xE9E9E9E9,0xEAEAEAEA,0xEEECEBEB,0xEFEFEFEF,0xEAEBEDEE,0xEAE9E9E9,0xEAEAEAEA,0xEBEBEAEA, 0xEBEBEBEB,0xECECEBEB,0xEEEEEEED,0xEAEBECED,0xEAEAE9E9,0xE8E9EAEA,0xE8E8E8E8,0xE8E8E9E8, 0xE4E5E6E7,0xE5E4E4E4,0xE5E5E5E5,0xE5E5E5E5,0xE4E4E5E5,0xE5E5E4E4,0xE7E7E7E6,0xE3E4E5E6, 0xE4E3E3E2,0xE3E4E4E4,0xE4E3E3E3,0xE5E5E5E5,0xE5E4E4E5,0xE6E6E6E5,0xE5E5E6E6,0xE5E5E5E5, 0xE4E4E4E5,0xE3E3E3E4,0xE0E1E2E3,0xE1E0E0E0,0xE2E2E2E1,0xE1E1E2E2,0xE1E1E1E1,0xDDDFE0E0, 0xD9D9DADC,0xDDDCDBDA,0xD9DADCDD,0xDBDAD9D9,0xDCDDDDDC,0xDBDBDBDB,0xDCDCDCDC,0xD8D9DADB, 0xD4D5D6D7,0xCDCFD1D3,0xCFCECDCD,0xD1D1D0D0,0xD5D5D4D2,0xD5D5D5D5,0xD9D8D7D6,0xD4D7D9D9, 0xCCCDD0D2,0xCBCCCCCC,0xCFCCCACA,0xD7D6D4D1,0xD6D6D7D8,0xD5D5D5D5,0xD1D2D4D5,0xCBCCCDCF, 0xC1C5C8CA,0xA1A7B1B9,0xBBB3ABA2,0xC3C4C3C1,0xB9BCC0C2,0xB5B7B7B8,0x2C15A0B0,0x1F2F3433, 0x9DA8A794,0x413C321A,0x24323B40,0x372D201A,0x41434240,0x222C343C,0x14131419,0x30261F17, 0x42403C36,0x41424343,0x45434241,0x46474746,0x29343D43,0x271D161D,0x2D32322F,0x91920621, 0x3731250E,0x34363839,0x45413A35,0x4C4C4B48,0x504E4C4C,0x52535352,0x50505051,0x51515150, 0x4D4D4F50,0x58555250,0x5F5E5D5B,0x62616160,0x63636363,0x61616162,0x5F606060,0x5D5C5D5E, 0x61605F5E,0x62626262,0x60606161,0x60606060,0x61616161,0x595C5F60,0x57555556,0x5B5B5A58, 0x5B5B5B5B,0x5C5C5C5B,0x5A5A5B5C,0x5A5A5959,0x5A5A5A5A,0x5E5D5C5B,0x605F5F5F,0x62616060, 0x63636363,0x62626263,0x62626262,0x61616161,0x63636262,0x61626363,0x62626161,0x63636362, 0x63636363,0x66666564,0x68686867,0x65656667,0x63636364,0x61626262,0x62616161,0x63636363, 0x5E5F6062,0x605F5E5E,0x61616161,0x62626161,0x61616262,0x62616161,0x63636362,0x60616263, 0x61606060,0x63636261,0x63636363,0x65656463,0x68686766,0x69696969,0x6A6A6A6A,0x68686969, 0x68676768,0x66676768,0x65656566,0x65656565,0x67666665,0x69686867,0x68696969,0x66676768, 0x65656566,0x65656464,0x67666665,0x67676767,0x68686767,0x6A6A6969,0x6969696A,0x67686869, 0x64656667,0x63636364,0x62636363,0x60606162,0x6160605F,0x63636261,0x61616262,0x61616060, 0x61616161,0x60616161,0x5E606060,0x5E5D5D5D,0x63626160,0x61616262,0x61606060,0x62626261, 0x65646363,0x67676666,0x65656667,0x62626364,0x62626262,0x61616262,0x61616060,0x62626262, 0x60606161,0x61616160,0x61616161,0x62626261,0x60616262,0x5E5E5E5F,0x5B5C5D5D,0x5859595A, 0x58585858,0x58585858,0x5A5A5A59,0x5959595A,0x59595959,0x54555658,0x5A575554,0x60605F5C, 0x5E5E5F60,0x5F5E5D5D,0x61606060,0x5E606060,0x5A5A5B5D,0x5D5D5C5B,0x5F5F5F5E,0x61616060, 0x60616161,0x5B5C5E5F,0x5356585A,0x4B4B4D50,0x50504E4C,0x4D4D4E50,0x5151504E,0x4B4E5051, 0x4949494A,0x3E434648,0x34323337,0x30343636,0x91910C23,0x302A1F05,0x1A242C30,0x32271A14, 0x4543413A,0x41424445,0x40403F40,0x3E404141,0x232C3339,0x1112151C,0x29201712,0x413E3932, 0x29343C40,0x3022171D,0x393E3D37,0xA69A1830,0x2C1B92A4,0x13283131,0xB4B2AC9C,0xB8B6B5B5, 0xC1C1BFBC,0xB1B7BDC0,0xA49EA1A8,0xC2BEB6AE,0xC8C7C6C5,0xD0CDCBC9,0xD2D2D2D1,0xD3D3D2D2, 0xD3D4D4D4,0xC8CBCED1,0xC8C7C6C7,0xC9C8C8C8,0xD3D1CECB,0xD5D5D6D5,0xD2D2D2D3,0xD1D2D2D2, 0xCCCED0D1,0xC9CACBCC,0xCAC9C8C8,0xD2D1D0CD,0xD5D4D3D3,0xD8D7D6D5,0xD6D7D7D8,0xD8D7D7D6, 0xD5D6D7D8,0xD6D5D4D5,0xD7D8D8D7,0xD5D5D5D6,0xDAD8D7D5,0xDCDCDBDB,0xDDDDDCDC,0xDEDEDEDE, 0xDBDBDCDD,0xDCDBDBDA,0xE0DFDFDE,0xE0E0E0E0,0xE1E1E1E1,0xE1E1E1E1,0xE2E2E2E2,0xE0E1E1E1, 0xE1E1E1E0,0xDFE0E1E1,0xE0DFDFDF,0xDFE0E0E0,0xE0DFDEDE,0xE3E2E2E1,0xE0E1E2E2,0xE0E0E0E0, 0xE0E0E0E0,0xE1E1E1E1,0xE0E0E1E1,0xE0E0E0E0,0xE3E3E2E1,0xE3E3E3E3,0xE4E3E3E3,0xE4E4E4E4, 0xE5E4E4E4,0xE8E7E7E6,0xE5E6E7E7,0xE5E5E5E5,0xE5E5E5E5,0xE4E4E4E5,0xE4E4E4E4,0xE5E4E4E3, 0xE8E8E7E6,0xE6E7E8E8,0xE4E4E4E5,0xE3E3E4E4,0xE3E3E3E3,0xE4E4E3E3,0xE3E3E4E4,0xE5E4E3E3, 0xE7E7E6E6,0xE4E4E5E6,0xE2E2E3E3,0xE1E1E1E2,0xE4E3E2E1,0xE3E4E4E4,0xE0E0E1E1,0xE4E3E2E1, 0xE5E5E5E4,0xE4E5E5E5,0xE3E4E4E4,0xE1E1E2E3,0xE1E1E0E1,0xE2E2E2E1,0xE3E3E2E2,0xE5E5E4E4, 0xE4E4E5E5,0xE2E3E3E4,0xDFE0E0E1,0xDFDFDFDF,0xDCDDDEDE,0xDDDDDCDC,0xDBDBDCDD,0xDFDDDBDB, 0xDEE0E0E0,0xD9D9DADC,0xDDDCDBDA,0xDADBDCDD,0xDADADADA,0xD6D7D8D9,0xDBD9D7D6,0xDEDFDEDD, 0xD8DADBDD,0xD4D5D6D7,0xD3D3D3D4,0xD5D5D4D4,0xD3D3D4D4,0xD7D6D5D4,0xD9D9D9D8,0xDBDAD9D9, 0xDCDCDCDC,0xDADADADB,0xDDDDDCDB,0xD9DBDCDD,0xD8D8D8D9,0xD3D5D6D7,0xD1D0D1D2,0xD3D3D3D2, 0xD2D2D2D3,0xD7D6D5D3,0xD6D7D8D8,0xD1D2D4D5,0xC9CCCED0,0xC2C3C5C7,0xC4C4C3C2,0xC1C2C3C4, 0xC0BFBEBF,0xC5C5C4C2,0xB7BCC1C3,0xB2B0B0B2,0xBEBBB8B5,0xC1C0C0BF,0xC2C1C1C1,0xC1C2C2C2, 0xC0C0C1C1,0xC4C3C2C1,0xC5C5C5C5,0xC3C3C4C4,0xBAC0C2C3,0xAEABAEB4,0xC2C0BAB4,0xC0C0C1C2, 0xCEC9C4C1,0xCFD1D2D1,0xC1C2C6CA,0xC5C5C4C2,0xACB7C0C3,0x14150998,0x8288830B,0x26241C10, 0x91112126,0x92A1A3A0,0x302D2412,0x1A232A2F,0x211C1514,0x1E222424,0x20191618,0x24262523, 0x211C1D21,0x39342F26,0x4141403E,0x363A3E40,0x2F303133,0x20262B2E,0x12060714,0x2B2B2620, 0x890B1E26,0x2C210D8A,0x32353532,0x332F2E30,0x44423F39,0x3E414445,0x2B2F3338,0x30302D2B, 0x2A2C2F30,0x34312D2A,0x36383837,0x2F2F3133,0x38363331,0x3F3D3B3A,0x48464441,0x48494949, 0x4A494948,0x4748494A,0x45454646,0x3F414344,0x3535373A,0x3B3A3836,0x3A3A3A3B,0x4442403D, 0x48484746,0x48484848,0x45464747,0x3C404143,0x38373739,0x3A3B3A39,0x37353638,0x4543403A, 0x47484847,0x44444546,0x42434444,0x43424141,0x49484745,0x47474849,0x46464646,0x44444545, 0x48474544,0x484A4A4A,0x42424446,0x45444242,0x49484847,0x4D4C4B4A,0x4C4C4D4D,0x49494A4B, 0x47484949,0x42434446,0x42414141,0x45444343,0x44454545,0x3C3F4143,0x3C3B3A3A,0x3E3E3E3D, 0x4341403F,0x44454544,0x42424243,0x49484644,0x43454748,0x3D3D3E40,0x4040403F,0x42414040, 0x44444443,0x40414344,0x43424040,0x46474645,0x44444545,0x44444444,0x40414243,0x41404040, 0x3F404141,0x3E3E3E3E,0x383B3D3E,0x34333436,0x3A3A3836,0x2F333739,0x25232428,0x3734302A, 0x38393938,0x3C3A3938,0x353A3D3D,0x94031F2D,0x8A919698,0x9B97918B,0x1185959B,0x2221201A, 0x312D2723,0x30333534,0x050D1B26,0x2321190F,0x8F0B1B22,0x979C9D99,0x06018791,0x1513100C, 0x810B1215,0x9A98948E,0xA3A09E9B,0xA4A6A6A5,0xA09EA0A2,0xA9A8A5A2,0xA4A6A8A9,0xADA9A6A4, 0xAEB0B0B0,0xA6A6A7AA,0xB4B1AEA9,0xB9B9B8B6,0xBCBBBBBA,0xBABBBCBC,0xB7B7B8B9,0xB7B7B7B6, 0xB7B7B7B7,0xBAB9B8B7,0xC0BEBDBB,0xC0C0C0C0,0xC0C0C0C0,0xC0C0C0C0,0xBEBFBFC0,0xBEBEBEBE, 0xBEBFBFBF,0xBCBCBDBE,0xBEBEBDBD,0xBFBFBFBE,0xC1C0C0BF,0xC1C2C2C2,0xC1C1C1C1,0xC2C2C1C1, 0xC2C2C2C2,0xC2C2C2C2,0xC4C3C2C2,0xC4C4C4C4,0xC3C3C3C4,0xC3C4C4C4,0xC0C1C2C3,0xC1C0BFBF, 0xC6C6C4C3,0xC7C7C7C7,0xC7C7C7C7,0xC7C7C7C8,0xC4C5C5C6,0xC0C1C2C3,0xC3C2C0C0,0xC4C4C5C4, 0xC1C1C2C3,0xC5C4C3C2,0xC6C6C6C5,0xC8C8C7C6,0xC7C8C8C8,0xC7C6C6C7,0xC7C7C7C7,0xC8C7C7C6, 0xC9C9C8C8,0xC9C8C8C9,0xC6C7C8C9,0xC1C1C3C5,0xC3C2C1C0,0xC7C7C6C5,0xC6C7C7C7,0xC4C5C5C6, 0xC2C3C3C4,0xC1C1C1C1,0xC3C3C2C1,0xC3C3C4C4,0xC5C4C4C3,0xC3C5C6C6,0xBBBCBFC1,0xC1C0BDBC, 0xC1C1C2C1,0xC1C1C1C1,0xBDBFC0C1,0xBBB9B9BA,0xC5C3C1BF,0xC7C7C6C6,0xC3C5C6C6,0xBDBEC0C2, 0xBFBEBDBC,0xBCBEBEBF,0xC1BFBDBC,0xC1C3C3C2,0xB9BABCC0,0xC1C0BDBA,0xBEC0C2C2,0xB5B5B7BA, 0xBBB9B8B6,0xBCBCBCBC,0xBCBCBCBC,0xBFBFBEBD,0xB6B9BCBE,0xADAEB0B3,0xB3B2B1AF,0xB1B1B2B3, 0xB1B0B0B0,0xB2B1B1B1,0xB6B6B5B3,0xA8AEB2B5,0xA9A5A3A5,0xACAFAFAD,0x9D9FA3A7,0xA1A1A09E, 0x828F979E,0x90850203,0xA4A29F98,0x98A0A3A5,0x17140B8A,0x9E930012,0x959EA2A2,0x05090587, 0x8D8F8B83,0x80008187,0x858A8884,0x1E181105,0x22212120,0x23242322,0x0D141C21,0x1B130A07, 0x28282622,0x26262627,0x312E2B28,0x34343332,0x32333333,0x31313232,0x2C2D2E30,0x35322F2D, 0x3E3D3B38,0x393B3C3D,0x38383838,0x3A3A3939,0x3E3C3B3B,0x4141403F,0x41424241,0x40404141, 0x3C3C3D3E,0x403F3E3D,0x3D3E3F40,0x41403E3D,0x43444343,0x42424243,0x45444443,0x47464645, 0x49494847,0x47474849,0x47474747,0x45464747,0x48464545,0x4B4B4A49,0x4747484A,0x4A494847, 0x494A4A4A,0x46464748,0x4B4A4847,0x4B4C4C4C,0x4647484A,0x44454545,0x41414243,0x44434241, 0x44454545,0x43434343,0x43434343,0x41424243,0x42424241,0x43434343,0x43434343,0x44434343, 0x43444444,0x44444343,0x48474645,0x48484848,0x47474747,0x45464646,0x45454545,0x45454645, 0x46454545,0x49484747,0x49494949,0x47484848,0x48474747,0x47474748,0x46464747,0x47474746, 0x48484848,0x48484848,0x4A494948,0x4B4B4B4B,0x4A4A4B4B,0x494A4A4A,0x49494949,0x4A4A4A4A, 0x4A4A4A4A,0x4A4A4A4A,0x48484949,0x4A494848,0x4B4B4B4A,0x4849494A,0x47474748,0x47474747, 0x46464647,0x47464645,0x48484848,0x45464647,0x45454545,0x44444545,0x40414243,0x3E3E3E3F, 0x40403F3F,0x41414141,0x40414141,0x3E3F4040,0x3D3D3D3D,0x3B3C3C3D,0x3B3B3A3B,0x3A3B3B3C, 0x34353638,0x35353434,0x35353535,0x38373635,0x39393939,0x36363738,0x37363636,0x37373737, 0x3A393837,0x3B3C3B3B,0x38383A3A,0x3A393838,0x3A3A3B3B,0x39393939,0x3A3B3A3A,0x3838393A, 0x3B3A3938,0x3A3B3B3B,0x37373738,0x3A393837,0x393A3B3B,0x37373838,0x39393837,0x3A3A3A3A, 0x39393939,0x39393939,0x38383939,0x37373838,0x34343536,0x34333333,0x36353535,0x34343535, 0x33343434,0x31313233,0x30303030,0x31313131,0x2E2E3030,0x2E2D2D2D,0x2E2F2F2E,0x2E2E2E2E, 0x2D2E2E2E,0x26292B2C,0x21222224,0x22222222,0x1D1F2122,0x201E1D1C,0x23232221,0x23242424, 0x1A1F2122,0x11111416,0x13121110,0x14141414,0x12131414,0x10101011,0x12111111,0x0A0C1010, 0x09090808,0x02050709,0x82838280,0x80000081,0x87858381,0x83858687,0x81818182,0x87868383, 0x8A8A8989,0x8B8A8B8A,0x8B8A8B8A,0x8E8C8C8B,0x8F908F8E,0x8E8F8E90,0x90908F8F,0x91919191, 0x90909090,0x92929191,0x92929292,0x93929292,0x93939393,0x92929393,0x92929291,0x94949493, 0x93949394,0x95949494,0x94949595,0x94949494,0x95959595,0x94949494,0x94949494,0x94949494, 0x94949494,0x94949494,0x93929393,0x93939392,0x92929393,0x91919191,0x91919192,0x90909091, 0x90909090,0x8D8E8E8F,0x8E8E8E8D,0x8C8D8D8E,0x8A8A8B8A,0x8889898A,0x85868687,0x84858586, 0x80818183, };
87.042623
88
0.897808
Drc3p0
2b285fd319effba571ce4dd865505c53fe3f1c35
2,058
cpp
C++
src/plugins/wkplugins/wkplugins.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/wkplugins/wkplugins.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/wkplugins/wkplugins.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "wkplugins.h" #include <QIcon> #include <xmlsettingsdialog/xmlsettingsdialog.h> #include <util/util.h> #include "staticplugin.h" #include "notificationsext.h" #include "spellcheckext.h" #include "xmlsettingsmanager.h" namespace LC { namespace WKPlugins { void Plugin::Init (ICoreProxy_ptr proxy) { Util::InstallTranslator ("wkplugins"); Proxy_ = proxy; XSD_ = std::make_shared<Util::XmlSettingsDialog> (); XSD_->RegisterObject (&XmlSettingsManager::Instance (), "wkpluginssettings.xml"); StaticPlugin::SetImpl (this); } void Plugin::SecondInit () { } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.WKPlugins"; } void Plugin::Release () { } QString Plugin::GetName () const { return "WKPlugins"; } QString Plugin::GetInfo () const { return tr ("Provides support for spellchecking and HTML5 notifications to WebKit."); } QIcon Plugin::GetIcon () const { return QIcon (); } Util::XmlSettingsDialog_ptr Plugin::GetSettingsDialog () const { return XSD_; } bool Plugin::supportsExtension (Extension ext) const { switch (ext) { case Extension::Notifications: case Extension::SpellChecker: return true; default: return false; } } QObject* Plugin::createExtension (Extension ext) const { QObject *extObj = nullptr; switch (ext) { case Extension::Notifications: extObj = new NotificationsExt { Proxy_ }; break; case Extension::SpellChecker: extObj = new SpellcheckerExt { Proxy_ }; break; default: break; } return extObj; } } } LC_EXPORT_PLUGIN (leechcraft_wkplugins, LC::WKPlugins::Plugin); Q_IMPORT_PLUGIN (StaticPlugin)
20.376238
86
0.661322
Maledictus
2b29533b0f93950d8a9423914191c7da88c487eb
6,002
hpp
C++
hpp/aligned_allocator.hpp
volcoma/hpp
c98a79c4b5593787789e0dffd670a1fdedc7308b
[ "BSD-2-Clause" ]
1
2019-05-26T19:50:41.000Z
2019-05-26T19:50:41.000Z
hpp/aligned_allocator.hpp
volcoma/hpp
c98a79c4b5593787789e0dffd670a1fdedc7308b
[ "BSD-2-Clause" ]
null
null
null
hpp/aligned_allocator.hpp
volcoma/hpp
c98a79c4b5593787789e0dffd670a1fdedc7308b
[ "BSD-2-Clause" ]
null
null
null
#ifndef ALLIGNED_ALLOCATOR_HPP #define ALLIGNED_ALLOCATOR_HPP #include <algorithm> #include <cstddef> #include <cstdlib> #include <memory> #include <cassert> namespace hpp { void* aligned_malloc(size_t size, size_t alignment); void aligned_free(void* ptr); /** * @class aligned_allocator * @brief Allocator for aligned memory * * The aligned_allocator class template is an allocator that * performs memory allocation aligned by the specified value. * * @tparam T type of objects to allocate. * @tparam Align alignment in bytes. */ template <class T, size_t Align = alignof(T)> class aligned_allocator { public: constexpr static bool is_power_of_2(size_t x) { return x > 0 && !(x & (x - 1)); } static_assert(Align > 0, "Alignment must be greater than 0"); static_assert(is_power_of_2(Align), "Alignment must be a power of 2"); using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using size_type = size_t; using difference_type = ptrdiff_t; template <class U> struct rebind { using other = aligned_allocator<U, Align>; }; aligned_allocator() noexcept; aligned_allocator(const aligned_allocator& rhs) noexcept; template <class U> aligned_allocator(const aligned_allocator<U, Align>& rhs) noexcept; ~aligned_allocator(); pointer allocate(size_type n, const void* hint = nullptr); void deallocate(pointer p, size_type n); size_type max_size() const noexcept; }; template <class T1, size_t Align1, class T2, size_t Align2> bool operator==(const aligned_allocator<T1, Align1>& lhs, const aligned_allocator<T2, Align2>& rhs) noexcept; template <class T1, size_t Align1, class T2, size_t Align2> bool operator!=(const aligned_allocator<T1, Align1>& lhs, const aligned_allocator<T2, Align2>& rhs) noexcept; /************************************ * aligned_allocator implementation * ************************************/ /** * Default constructor. */ template <class T, size_t A> inline aligned_allocator<T, A>::aligned_allocator() noexcept = default; /** * Copy constructor. */ template <class T, size_t A> inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator&) noexcept = default; /** * Extended copy constructor. */ template <class T, size_t A> template <class U> inline aligned_allocator<T, A>::aligned_allocator(const aligned_allocator<U, A>&) noexcept { } /** * Destructor. */ template <class T, size_t A> inline aligned_allocator<T, A>::~aligned_allocator() = default; /** * Allocates <tt>n * sizeof(T)</tt> bytes of uninitialized memory, aligned by \c A. * The alignment may require some extra memory allocation. * @param n the number of objects to allocate storage for. * @param hint unused parameter provided for standard compliance. * @return a pointer to the first byte of a memory block suitably aligned and sufficient to * hold an array of \c n objects of type \c T. */ template <class T, size_t A> inline auto aligned_allocator<T, A>::allocate(size_type n, const void*) -> pointer { auto res = reinterpret_cast<pointer>(aligned_malloc(sizeof(T) * n, A)); if(res == nullptr) throw std::bad_alloc(); return res; } /** * Deallocates the storage referenced by the pointer p, which must be a pointer obtained by * an earlier call to allocate(). The argument \c n must be equal to the first argument of the call * to allocate() that originally produced \c p; otherwise, the behavior is undefined. * @param p pointer obtained from allocate(). * @param n number of objects earlier passed to allocate(). */ template <class T, size_t A> inline void aligned_allocator<T, A>::deallocate(pointer p, size_type) { aligned_free(p); } /** * Returns the maximum theoretically possible value of \c n, for which the * call allocate(n, 0) could succeed. * @return the maximum supported allocated size. */ template <class T, size_t A> inline auto aligned_allocator<T, A>::max_size() const noexcept -> size_type { return size_type(-1) / sizeof(T); } /** * @defgroup allocator_comparison Comparison operators */ /** * @ingroup allocator_comparison * Compares two aligned memory allocator for equality. Since allocators * are stateless, return \c true iff <tt>A1 == A2</tt>. * @param lhs aligned_allocator to compare. * @param rhs aligned_allocator to compare. * @return true if the allocators have the same alignment. */ template <class T1, size_t A1, class T2, size_t A2> inline bool operator==(const aligned_allocator<T1, A1>& /*lhs*/, const aligned_allocator<T2, A2>& /*rhs*/) noexcept { return A1 == A2; } /** * @ingroup allocator_comparison * Compares two aligned memory allocator for inequality. Since allocators * are stateless, return \c true iff <tt>A1 != A2</tt>. * @param lhs aligned_allocator to compare. * @param rhs aligned_allocator to compare. * @return true if the allocators have different alignments. */ template <class T1, size_t A1, class T2, size_t A2> inline bool operator!=(const aligned_allocator<T1, A1>& lhs, const aligned_allocator<T2, A2>& rhs) noexcept { return !(lhs == rhs); } //**************************************** //* aligned malloc / free implementation * //**************************************** inline void* aligned_malloc(size_t required_bytes, size_t alignment) { void* res = nullptr; // we allocate extra bytes to keep the unaligned pointer there // so we can access it fast for when we need to free it. size_t offset = alignment - 1 + sizeof(void*); size_t malloc_size = required_bytes + offset; void* ptr = std::malloc(malloc_size); if(ptr != nullptr && alignment != 0) { res = reinterpret_cast<void*>((reinterpret_cast<size_t>(ptr) + offset)&~(size_t(alignment - 1))); *(reinterpret_cast<void**>(res) - 1) = ptr; } assert(uintptr_t(res) % alignment == 0); return res; } inline void aligned_free(void* ptr) { if(ptr != nullptr) { auto unaligned = *(reinterpret_cast<void**>(ptr) - 1); std::free(unaligned); } } } // namespace hpp #endif
29.135922
115
0.706265
volcoma
1a80e3edf85c632c20c987955b780476abf25be7
1,463
cc
C++
table/tests/index_composite_ut.cc
shampoo365/terarkdb
a05a42789b310e1a79f6b5bb2f98f78993f9fbb2
[ "Apache-2.0", "BSD-3-Clause" ]
1,658
2020-12-21T04:53:44.000Z
2022-03-30T16:16:07.000Z
table/tests/index_composite_ut.cc
shampoo365/terarkdb
a05a42789b310e1a79f6b5bb2f98f78993f9fbb2
[ "Apache-2.0", "BSD-3-Clause" ]
105
2020-12-21T09:09:55.000Z
2022-03-28T09:57:36.000Z
table/tests/index_composite_ut.cc
shampoo365/terarkdb
a05a42789b310e1a79f6b5bb2f98f78993f9fbb2
[ "Apache-2.0", "BSD-3-Clause" ]
151
2020-12-21T09:25:34.000Z
2022-03-13T08:58:37.000Z
#include <chrono> #include "index_composite_ut.h" int main_impl(int argc, char** argv) { printf("EXAGGERATE\n"); printf("/////////////// sorteduint test\n"); test_il256_il256_sorteduint(standard_ascend); test_il256_il256_sorteduint(standard_descend); test_allone_il256_sorteduint(standard_ascend); test_allone_il256_sorteduint(standard_descend); //test_fewzero_allzero_sorteduint(standard_ascend); //test_fewzero_allzero_sorteduint(standard_descend); test_allone_allzero_sorteduint(standard_allzero); test_data_seek_short_target_sorteduint(); printf("/////////////// uint test\n"); test_il256_il256_uint(standard_ascend); test_il256_il256_uint(standard_descend); test_allone_il256_uint(standard_ascend); test_allone_il256_uint(standard_descend); test_allone_allzero_uint(standard_allzero); test_data_seek_short_target_uint(); test_seek_cost_effective(); printf("///////////// str test\n"); test_il256_il256_str(standard_ascend); test_il256_il256_str(standard_descend); test_allone_il256_str(standard_ascend); test_allone_il256_str(standard_descend); test_allone_allzero_str(standard_allzero); test_data_seek_short_target_str(); return 0; } int main(int argc, char** argv) { //auto now = std::chrono::system_clock::now; //auto end = now() + std::chrono::minutes(2); //while (now() < end) { main_impl(argc, argv); //} return 0; }
25.224138
56
0.725906
shampoo365
1a82d232f38ef5ac63f6617c5da8ff7a7045a5cb
14,635
hpp
C++
include/qpoint_grid.hpp
sousaw/BTE-Barna
029ca43ef096c4b725d3aeb2955bc0df9ca544a9
[ "MIT", "BSD-3-Clause" ]
5
2022-02-07T03:36:38.000Z
2022-03-25T13:11:20.000Z
include/qpoint_grid.hpp
sousaw/BTE-Barna
029ca43ef096c4b725d3aeb2955bc0df9ca544a9
[ "MIT", "BSD-3-Clause" ]
null
null
null
include/qpoint_grid.hpp
sousaw/BTE-Barna
029ca43ef096c4b725d3aeb2955bc0df9ca544a9
[ "MIT", "BSD-3-Clause" ]
null
null
null
// Copyright 2015-2022 The ALMA Project Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #pragma once /// @file /// Classes and functions used to manipulate grids in reciprocal space. #include <boost/mpi.hpp> #include <structures.hpp> #include <dynamical_matrix.hpp> namespace alma { /// Convenient shorthand for an array of four indices. using Tetrahedron = std::array<std::size_t, 4>; /// Convenient shorthand for an array of three indices. using Triangle = std::array<std::size_t, 3>; /// Objects of this class represent a regular grid with the Gamma /// point in one corner. class Gamma_grid { public: /// Size of the grid along the first reciprocal axis. const int na; /// Size of the grid along the second reciprocal axis. const int nb; /// Size of the grid along the third reciprocal axis. const int nc; /// Total number of q points in the grid. const std::size_t nqpoints; /// Reciprocal lattice basis vectors. const Eigen::MatrixXd rlattvec; /// Side vectors of each element in reciprocal space. const Eigen::MatrixXd dq; /// Constructor: initialize all internal variables and compute /// the spectrum at each q point. Do not correct the dynamical /// matrix for the effect of long-range interactions. Gamma_grid(const Crystal_structure& poscar, const Symmetry_operations& symms, const Harmonic_ifcs& force_constants, int _na, int _nb, int _nc); /// Constructor: initialize all internal variables and compute /// the spectrum at each q point. Correct the dynamical /// matrix for the effect of long-range interactions. Gamma_grid(const Crystal_structure& poscar, const Symmetry_operations& symms, const Harmonic_ifcs& force_constants, const Dielectric_parameters& born, int _na, int _nb, int _nc); /// Set the three lowest frequencies at Gamma to zero. void enforce_asr() { this->spectrum[0].omega.head(3).fill(0.); } /// Return the index of a q point identified by its position /// along the three axes. /// /// Indices are interpreted modulo-{na, nb, nc}, so even /// negative values are accepted. /// @param[in] indices - positions of the q point /// along the three axes /// @return the index of the q point in this grid std::size_t three_to_one(const std::array<int, 3>& indices) const { auto ia = python_mod(indices[0], this->na); auto ib = python_mod(indices[1], this->nb); auto ic = python_mod(indices[2], this->nc); return ic + nc * (ib + nb * ia); } /// Return the coordinates of a q point identified by its /// index. /// /// @param[in] index - index of the q point /// @return - an array with the positions of the q point /// along the three axes. std::array<int, 3> one_to_three(std::size_t iq) const { std::array<int, 3> nruter; nruter[2] = iq % nc; iq /= nc; nruter[1] = iq % nb; nruter[0] = iq / nb; return nruter; } /// @return the number of q-point equivalence classes in the grid. std::size_t get_nequivalences() const { return this->equivalences.size(); } /// Access the harmonic properties at a point in the grid. /// /// The index is interpreted using modular arithmetic, /// so even negative values are accepted. /// @param[in] iq - index of the q point /// @return the harmonic properties at the q point. const Spectrum_at_point& get_spectrum_at_q(int iq) const { std::size_t index = python_mod(iq, this->nqpoints); return this->spectrum[index]; } /// Return the cardinal of an equivalence class. /// /// @param[in] ic - index of the equivalence class. /// @return the number of points in an equivalence class. std::size_t get_cardinal(std::size_t ic) const { if (ic > this->equivalences.size()) throw value_error("wrong equivalence class index"); return this->equivalences[ic].size(); } /// Return a representative of an equivalence class. /// /// The method is guaranteed to always return the same point. /// @param[in] ic - index of the equivalence class. /// @return a representative of the equivalence class. std::size_t get_representative(std::size_t ic) const { if (ic > this->equivalences.size()) throw value_error("wrong equivalence class index"); return this->equivalences[ic][0]; } /// Return the elements in an equivalence class. /// /// @param[in] ic - index of the equivalence class. /// @return a vector with the elements in the equivalence /// class. std::vector<std::size_t> get_equivalence(std::size_t ic) const { if (ic > this->equivalences.size()) throw value_error("wrong equivalence class index"); return this->equivalences[ic]; } /// Return the Cartesian coordinates of a q point. /// /// @param[in] iq - a q point index /// @return three Cartesian coordinates Eigen::VectorXd get_q(std::size_t iq) const { std::size_t index = python_mod(iq, this->nqpoints); return this->cpos.col(index); } /// Return the base broadening (without any prefactor) for a /// mode. /// /// @param[in] v - group velocity, or difference /// of group velocities in the case of three-phonon processes /// @return - the standard deviation of a Gaussian double base_sigma(const Eigen::VectorXd& v) const { return (v.transpose() * this->dq).norm() / std::sqrt(12.); } /// Very basic constructor that builds a stub object. Useful /// for deserialization or for obtaining an equivalences vector /// without computing the spectrum. Gamma_grid(const Crystal_structure& poscar, const Symmetry_operations& symms, int _na, int _nb, int _nc); /// Find the index of the polar opposite q point. /// /// @param[in] q - a q point /// @return the index of the polar opposite of q std::size_t polar_opposite(std::size_t q) { auto indices = this->one_to_three(q); return this->three_to_one({{-indices[0], -indices[1], -indices[2]}}); } /// Return the images of a q point through all the symmetry /// operations, including inversions. /// /// @param[in] q - a q point /// @return a vector of q point indices. Elements with even indices /// correspond to operations in the space group, /// while elements with odd indices compound them with time /// reversal. std::vector<size_t> equivalent_qpoints(std::size_t original) const { std::size_t index = python_mod(original, this->nqpoints); return this->symmetry_map[index]; } /// Find all q-point pairs equivalent to the input. /// /// Given a pair of indices, obtain all equivalent pairs /// after looking the up in the symmetry_map. /// @param[in] pair a pair of q point indices /// @return a vector of pairs, including the input std::vector<std::array<std::size_t, 2>> equivalent_qpairs( const std::array<std::size_t, 2>& original) const; /// Find all q-point triplets equivalent to the input. /// /// Given a triplet of indices, obtain all equivalent triplets /// after looking the up in the symmetry_map. /// @param[in] a triplet of q point indices /// @return a vector of triplets, including the input std::vector<std::array<std::size_t, 3>> equivalent_qtriplets( const std::array<std::size_t, 3>& original) const; /// Decompose the q-th microcell in five tetrahedra. /// /// @param[in] q - the index of the q point /// @return a vector of five Tetrahedron objects std::vector<Tetrahedron> get_tetrahedra(std::size_t q) const { // Find out the indices of the eight corners of the // microcell. std::size_t i000 = q; auto indices = this->one_to_three(i000); std::size_t i001 = this->three_to_one({{indices[0], indices[1], indices[2] + 1}}); std::size_t i010 = this->three_to_one({{indices[0], indices[1] + 1, indices[2]}}); std::size_t i011 = this->three_to_one({{indices[0], indices[1] + 1, indices[2] + 1}}); std::size_t i100 = this->three_to_one({{indices[0] + 1, indices[1], indices[2]}}); std::size_t i101 = this->three_to_one({{indices[0] + 1, indices[1], indices[2] + 1}}); std::size_t i110 = this->three_to_one({{indices[0] + 1, indices[1] + 1, indices[2]}}); std::size_t i111 = this->three_to_one( {{indices[0] + 1, indices[1] + 1, indices[2] + 1}}); // Build the four equivalent tetrahedra. std::vector<Tetrahedron> nruter; nruter.reserve(5); nruter.emplace_back(Tetrahedron({{i000, i001, i010, i100}})); nruter.emplace_back(Tetrahedron({{i110, i111, i100, i010}})); nruter.emplace_back(Tetrahedron({{i101, i100, i111, i001}})); nruter.emplace_back(Tetrahedron({{i011, i010, i001, i111}})); // And the central, inequivalent one. nruter.emplace_back(Tetrahedron({{i010, i100, i111, i001}})); return nruter; } /// @return a vector of triangle objects with each containing three /// indices std::vector<Triangle> get_triangles(std::size_t ia) const; /// @return the index of the representative of the equivalence /// class /// of the provided q-point std::size_t getParentIdx(std::size_t iq) const; /// @return the index of the symmetry operation that maps the /// provided q-point /// to the representative of the equivalence class to which it /// belongs std::size_t getSymIdxToParent(std::size_t iq) const; /// @return the grid's symmetry map std::vector<std::vector<std::size_t>> getSymmetryMap() { return this->symmetry_map; } /// Remove the component of a Cartesian vector which does transform as a /// q-point in the grid. /// /// @param[in] iq - index of the q point /// @param[in] symms - set of symmetry operations of the crystal /// @param[in] x - vector in Cartesian coordinates. Several vectors can /// be provided by making v a matrix and each vector a column /// @return the symmetrized version of x template <typename T> auto copy_symmetry(std::size_t iq, const Symmetry_operations& symms, const Eigen::MatrixBase<T>& x) const -> Eigen::Matrix<typename T::Scalar, Eigen::Dynamic, Eigen::Dynamic> { std::size_t index = python_mod(iq, this->nqpoints); std::size_t nops = symms.get_nsym(); typename T::PlainObject nruter(x); nruter.fill(0.); std::size_t nfound = 0; for (std::size_t iop = 0; iop < nops; ++iop) { if (this->symmetry_map[index][2 * iop] == index) { nruter += symms.rotate_v(x, iop, true); ++nfound; } } nruter /= nfound; return nruter; } private: friend void save_bulk_hdf5(const char* filename, const std::string& description, const Crystal_structure& cell, const Symmetry_operations& symmetries, const Gamma_grid& grid, const std::vector<Threeph_process>& processes, const boost::mpi::communicator& comm); friend std::tuple<std::string, std::unique_ptr<Crystal_structure>, std::unique_ptr<Symmetry_operations>, std::unique_ptr<Gamma_grid>, std::unique_ptr<std::vector<Threeph_process>>> load_bulk_hdf5(const char* filename, const boost::mpi::communicator& comm); /// Cartesian coordinates of each q point. Eigen::MatrixXd cpos; /// Harmonic properties at each q point. std::vector<Spectrum_at_point> spectrum; /// Vector of equivalence classes. Two q points in the same /// equivalence class are related by a symmetry operation. /// Note that both space group symmetries and time reversal /// symmetry are taken into account. std::vector<std::vector<std::size_t>> equivalences; /// Detailed map between q points through the symmetry /// operations. std::vector<std::vector<std::size_t>> symmetry_map; /// Initialize the Cartesian coordinates of the q points. /// @param[in] poscar - a description of the crystal structure void initialize_cpos(); /// Compute the spectrum at a subset of the q points. /// /// That subset is selected on the basis of this process' /// position in an MPI communicator. /// @param[in] factory - object in charge of building the /// dynamical matrix at each point. /// @param[in] symms - set of symmetry operations of the crystal /// @param[in] communicator - MPI communicator to use std::vector<Spectrum_at_point> compute_my_spectrum( const Dynamical_matrix_builder& factory, const Symmetry_operations& symms, const boost::mpi::communicator& communicator); /// Fill the equivalences vector. /// /// @param[in] symms - the set of symmetry operations to try. void fill_equivalences(const Symmetry_operations& symms); /// Parentlookup table: stores for each q-point the index of /// the representative of the equivalence class to which it /// belongs. std::vector<std::size_t> parentlookup; /// Fill the parentlookup table void fill_parentlookup(); /// Fill the symmetry_map vector. /// /// @param[in] symms - the set of symmetry operations to try. void fill_map(const Symmetry_operations& symms); }; } // namespace alma
37.14467
79
0.627195
sousaw
1a84f4d3ff3b8c68cfdeee86e3483282924f1f0b
3,024
cpp
C++
src/filters/eavlBoxMutator.cpp
jsmeredith/EAVL
114924a92aed4f1adfcf4f751151d9355c593944
[ "Apache-2.0", "BSD-2-Clause" ]
6
2016-12-11T21:40:00.000Z
2018-04-04T10:33:40.000Z
src/filters/eavlBoxMutator.cpp
jsmeredith/EAVL
114924a92aed4f1adfcf4f751151d9355c593944
[ "Apache-2.0", "BSD-2-Clause" ]
3
2015-02-11T20:55:01.000Z
2017-05-31T01:56:21.000Z
src/filters/eavlBoxMutator.cpp
jsmeredith/EAVL
114924a92aed4f1adfcf4f751151d9355c593944
[ "Apache-2.0", "BSD-2-Clause" ]
6
2015-05-24T06:27:45.000Z
2020-05-08T12:17:07.000Z
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information. #include "eavlBoxMutator.h" #include "eavlCellSetExplicit.h" #include "eavlException.h" eavlBoxMutator::eavlBoxMutator() { } eavlBoxMutator::~eavlBoxMutator() { } void eavlBoxMutator::Execute() { int inCellSetIndex = dataset->GetCellSetIndex(cellsetname); eavlCellSet *inCells = dataset->GetCellSet(cellsetname); vector<int> newcells; int in_ncells = inCells->GetNumCells(); eavlExplicitConnectivity conn; for (int i=0; i<in_ncells; i++) { eavlCell cell = inCells->GetCellNodes(i); bool match = true; for (int j=0; j<cell.numIndices; ++j) { if (dim >= 1) { double x = dataset->GetPoint(cell.indices[j], 0); if (x < xmin || x > xmax) { match = false; break; } } if (dim >= 2) { double y = dataset->GetPoint(cell.indices[j], 1); if (y < ymin || y > ymax) { match = false; break; } } if (dim >= 3) { double z = dataset->GetPoint(cell.indices[j], 2); if (z < zmin || z > zmax) { match = false; break; } } } if (match) { conn.AddElement(cell); newcells.push_back(i); } } unsigned int numnewcells = conn.GetNumElements(); eavlCellSetExplicit *subset = new eavlCellSetExplicit(string("box_of_")+inCells->GetName(), inCells->GetDimensionality()); subset->SetCellNodeConnectivity(conn); //int new_cellset_index = dataset->GetNumCellSets(); dataset->AddCellSet(subset); for (int i=0; i<dataset->GetNumFields(); i++) { eavlField *f = dataset->GetField(i); if (f->GetAssociation() == eavlField::ASSOC_CELL_SET && f->GetAssocCellSet() == dataset->GetCellSet(inCellSetIndex)->GetName()) { int numcomp = f->GetArray()->GetNumberOfComponents(); eavlFloatArray *a = new eavlFloatArray( string("subset_of_")+f->GetArray()->GetName(), numcomp, numnewcells); for (unsigned int j=0; j < numnewcells; j++) { int e = newcells[j]; for (int k=0; k<numcomp; ++k) a->SetComponentFromDouble(j,k, f->GetArray()->GetComponentAsDouble(e,k)); } eavlField *newfield = new eavlField(f->GetOrder(), a, eavlField::ASSOC_CELL_SET, subset->GetName()); dataset->AddField(newfield); } } }
30.545455
95
0.475198
jsmeredith
1a853c3b9608ecbfe41b742621f49ad2fc8c8069
1,084
cc
C++
type/slice.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
null
null
null
type/slice.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
null
null
null
type/slice.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
null
null
null
#include "type/slice.h" #include <algorithm> #include "absl/strings/str_format.h" #include "base/global.h" namespace type { static base::Global<absl::node_hash_set<Slice>> cache; Slice const *Slc(Type t) { ASSERT(t.valid() == true); auto const *p = &*cache.lock()->insert(Slice(t)).first; GlobalTypeSystem.insert(Type(p)); return p; } void Slice::WriteTo(std::string *result) const { result->append("[]"); data_type().get()->WriteTo(result); } core::Bytes Slice::bytes(core::Arch const &a) const { return core::FwdAlign(a.pointer().bytes(), a.pointer().alignment()) + core::Bytes::Get<length_t>(); } core::Alignment Slice::alignment(core::Arch const &a) const { return std::max(a.pointer().alignment(), core::Alignment::Get<length_t>()); } void Slice::ShowValue(std::ostream &os, ir::CompleteResultRef const &value) const { auto iter = value.raw().begin(); ir::addr_t addr = iter.read<ir::addr_t>(); length_t length = iter.read<length_t>(); absl::Format(&os, "slice(%p, %u)", addr, length); } } // namespace type
26.439024
77
0.648524
asoffer
1a8d107048738baf9ea10fea92ccc4ae2cf1eef6
1,658
cpp
C++
src/transport/backend/local/RangeServer.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
2
2020-11-25T17:45:58.000Z
2021-12-21T02:01:16.000Z
src/transport/backend/local/RangeServer.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
null
null
null
src/transport/backend/local/RangeServer.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
1
2021-10-11T19:54:05.000Z
2021-10-11T19:54:05.000Z
#include <cstdio> #include <cstdlib> #include <cstring> #include "hxhim/hxhim.hpp" #include "hxhim/private/accessors.hpp" #include "transport/backend/local/RangeServer.hpp" #include "utils/Blob.hpp" #include "utils/memory.hpp" namespace Transport { namespace local { Message::Response::Response *range_server(hxhim_t *hx, Message::Request::Request *req) { int rank = -1; hxhim::nocheck::GetMPI(hx, nullptr, &rank, nullptr); mlog(HXHIM_SERVER_INFO, "Rank %d Local RangeServer got a %s", rank, HXHIM_OP_STR[req->op]); Message::Response::Response *res = nullptr; // Call the appropriate function depending on the message type switch(req->op) { case hxhim_op_t::HXHIM_PUT: res = range_server<Message::Response::BPut>(hx, static_cast<Message::Request::BPut *>(req)); break; case hxhim_op_t::HXHIM_GET: res = range_server<Message::Response::BGet>(hx, static_cast<Message::Request::BGet *>(req)); break; case hxhim_op_t::HXHIM_GETOP: res = range_server<Message::Response::BGetOp>(hx, static_cast<Message::Request::BGetOp *>(req)); break; case hxhim_op_t::HXHIM_DELETE: res = range_server<Message::Response::BDelete>(hx, static_cast<Message::Request::BDelete *>(req)); break; case hxhim_op_t::HXHIM_HISTOGRAM: res = range_server<Message::Response::BHistogram>(hx, static_cast<Message::Request::BHistogram *>(req)); break; default: break; } mlog(HXHIM_SERVER_INFO, "Rank %d Local RangeServer done processing request", rank); return res; } } }
33.836735
116
0.6538
hpc
1a9278790b974344467865ea305ebfe1802f681a
2,272
hpp
C++
Includes/VanillaDNN/Math/Vector/Vector.hpp
jaegyeom/Vanilla-DNN
3a783bbbb7d827b82716516eca1ee9e7803804a7
[ "MIT" ]
4
2021-05-20T16:02:43.000Z
2021-10-02T02:37:06.000Z
Includes/VanillaDNN/Math/Vector/Vector.hpp
jaegyeom/Vanilla-DNN
3a783bbbb7d827b82716516eca1ee9e7803804a7
[ "MIT" ]
1
2021-05-14T18:13:28.000Z
2021-05-15T01:57:06.000Z
Includes/VanillaDNN/Math/Vector/Vector.hpp
jaegyeom/Vanilla-DNN
3a783bbbb7d827b82716516eca1ee9e7803804a7
[ "MIT" ]
2
2021-05-14T18:00:34.000Z
2021-10-31T08:23:35.000Z
#ifndef VANILLA_DNN_VECTOR_HPP #define VANILLA_DNN_VECTOR_HPP #include<vector> #include<stdexcept> #include<iostream> #include<vector> #include<cmath> #include <algorithm> #include <cstdlib> #include <ctime> template<typename T> class Matrix; template<typename T> class Vector { private: std::vector<T> vector; int size; public: Vector(); Vector(const int& _size, const T& _init); Vector(const Vector<T>& rhs); Vector(const Matrix<T>& rhs); explicit Vector(const std::vector<T>& rhs); virtual ~Vector(); //operator Vector<T> operator+(const Vector<T>& rhs); Vector<T> operator-(const Vector<T>& rhs); Vector<T> operator*(const Vector<T>& rhs); Vector<T>& operator+=(const Vector<T>& rhs); Vector<T>& operator-=(const Vector<T>& rhs); Vector<T>& operator*=(const Vector<T>& rhs); Vector<T>& operator=(const Vector<T>& rhs); Vector<T>& operator=(const Matrix<T>& rhs); //scalar Vector<T> operator+(const T& rhs); Vector<T> operator-(const T& rhs); Vector<T> operator*(const T& rhs); Vector<T> operator/(const T& rhs); Vector<T>& operator+=(const T& rhs); Vector<T>& operator-=(const T& rhs); Vector<T>& operator*=(const T& rhs); Vector<T>& operator/=(const T& rhs); bool operator==(const Vector<T>& rhs); // Matrix Matrix<T> transpose(); Matrix<T> dot(const Matrix<T>& rhs); T dot(const Vector<T>& rhs); T sum(); // sub Vector<T> square(); Vector<T> sqrt(); Vector<T> inv(); Vector<T> onehot(); Vector<T> clip(const T& _min, const T& _max); T& operator()(const int& idx); const T& operator()(const int& idx) const; T& operator()(const int& begin, const int& end); T& operator[](const int& idx); const T& operator[](const int& idx) const; //cout overloading template<typename U> friend std::ostream& operator << (std::ostream& out, const Vector<U>& v); int get_size() const; void push_back(T value); void setRandom(); void resize(const int& _size, const T& _init = 0); void clear(); float norm(); }; template<typename U> std::ostream& operator << (std::ostream& out, const Vector<U>& v) { int size = v.get_size(); out << "size : " << size << '\n'; for (int i = 0; i < size; i++) { out << v(i) << '\t'; } out << '\n'; return out; } #include <VanillaDNN/Math/Vector/Vector.cpp> #endif
21.638095
74
0.653609
jaegyeom
1a941c289d9d28fda0b6773eeb6a1fb77bb9135e
1,373
cpp
C++
04-linked-list/InsertANodeAtASpecificPositionInALinkedList/InsertANodeAtASpecificPositionInALinkedList.cpp
nalidzhik/data-structures-and-algorithms
fa69061913fd773b6f2ddac4feeace625b6b9baa
[ "Apache-2.0" ]
null
null
null
04-linked-list/InsertANodeAtASpecificPositionInALinkedList/InsertANodeAtASpecificPositionInALinkedList.cpp
nalidzhik/data-structures-and-algorithms
fa69061913fd773b6f2ddac4feeace625b6b9baa
[ "Apache-2.0" ]
null
null
null
04-linked-list/InsertANodeAtASpecificPositionInALinkedList/InsertANodeAtASpecificPositionInALinkedList.cpp
nalidzhik/data-structures-and-algorithms
fa69061913fd773b6f2ddac4feeace625b6b9baa
[ "Apache-2.0" ]
null
null
null
/* * Complete the 'insertNodeAtPosition' function below. * * The function is expected to return an INTEGER_SINGLY_LINKED_LIST. * The function accepts following parameters: * 1. INTEGER_SINGLY_LINKED_LIST llist * 2. INTEGER data * 3. INTEGER position */ /* * For your reference: * * SinglyLinkedListNode { * int data; * SinglyLinkedListNode* next; * }; * */ SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) { if (position == 0) { SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data); if (llist == nullptr) { llist = newNode; } else { SinglyLinkedListNode* temp = llist; newNode->next = temp; llist = newNode; } return llist; } else { SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data); SinglyLinkedListNode* traverse = llist; for (int i = 1; i < position; i++) { traverse = traverse->next; } // traverse points to (pos-1)th Node SinglyLinkedListNode* temp = traverse->next; // pos-th Node : traverse - newNode - temp traverse->next = newNode; newNode->next = temp; } return llist; }
24.517857
98
0.563729
nalidzhik
1a98d26b66436c5595f5bc806cbd5b2d786153fb
3,241
cpp
C++
src/lib/physics/2d/kernel_debrun_spiky.cpp
Fluci/GooBalls
4b68084303e66af368fd6bbf94aaec0950c9c6e3
[ "BSD-3-Clause" ]
null
null
null
src/lib/physics/2d/kernel_debrun_spiky.cpp
Fluci/GooBalls
4b68084303e66af368fd6bbf94aaec0950c9c6e3
[ "BSD-3-Clause" ]
null
null
null
src/lib/physics/2d/kernel_debrun_spiky.cpp
Fluci/GooBalls
4b68084303e66af368fd6bbf94aaec0950c9c6e3
[ "BSD-3-Clause" ]
null
null
null
#include "kernel_debrun_spiky.hpp" #include "generic/eigen.hpp" #include <iostream> namespace GooBalls { namespace d2 { namespace Physics { void DebrunSpiky::setH(Float h) { m_h = h; m_A1d = 2/std::pow(m_h, 4); m_A2d = 10.0/M_PI/std::pow(h, 5);; } void DebrunSpiky::compute1d( const Coordinates1d& r2, Coordinates1d* wResult, Coordinates1d* gradientResult, Coordinates1d* laplacianResult) const { Float h = m_h; Float A = m_A1d; assert(r2.maxCoeff() <= h*h*1.01); Coordinates1d r1 = r2.array().sqrt(); Coordinates1d diffH = h - r1.array(); Coordinates1d diffH2 = diffH.array() * diffH.array(); if(wResult != nullptr){ *wResult = A * diffH2.array()*diffH.array(); } if(gradientResult != nullptr){ *gradientResult = (-3*A) * diffH2; } if(laplacianResult != nullptr){ *laplacianResult = (6.0*A)*diffH; } } Float DebrunSpiky::scale2d() const { return m_A2d; } Float DebrunSpiky::computeValue(const TranslationVector rs) const { assert(false); // TODO return 0.0; } TranslationVector DebrunSpiky::computeGradient(const TranslationVector rs) const { Float h = m_h; Float A = m_A2d; Float epsilon = m_epsilon; auto r1 = rs.rowwise().norm().array(); return (-3*A) * (rs.array().colwise() *( (h - r1).pow(2.0) / (r1.array() + h*epsilon))); } Float DebrunSpiky::computeLaplacian(const TranslationVector rs) const { assert(false); // TODO return 0.0; } void DebrunSpiky::compute( const Coordinates2d& rs, Coordinates1d* wResult, Coordinates2d* gradientResult, Coordinates1d* laplacianResult) const { Float h = m_h; Float A = m_A2d; Float epsilon = m_epsilon; Coordinates1d r2 = rs.rowwise().squaredNorm(); int N = r2.rows(); assert(r2.maxCoeff() <= h*h*1.01); Coordinates1d r1 = r2.array().sqrt(); Coordinates1d diffH = h - r1.array(); Coordinates1d diffH2 = diffH.array() * diffH.array(); auto r1Inv = 1.0/(r1.array() + h*epsilon); if(wResult != nullptr){ minSize(*wResult, N); wResult->block(0,0,N,1) = A * diffH2.array()*diffH.array(); } if(gradientResult != nullptr){ auto comm = (-3*A) * diffH2; *gradientResult = rs.array().colwise() * r1Inv; *gradientResult = gradientResult->array().colwise() * comm.array(); /*auto comm = (-3*A) * diffH2.array() * r1Inv.array(); gradientResult->resize(rs.rows(), rs.cols()); gradientResult->col(0) = comm.array() * rs.col(0).array(); gradientResult->col(1) = comm.array() * rs.col(1).array(); *gradientResult = gradientResult->unaryExpr([](auto v){return std::isfinite(v) ? v : 0.0;}); */ } if(laplacianResult != nullptr){ Float h2 = h*h; *laplacianResult = -3*A * (h2 * r1Inv + 3.0 * r1.array() - 4 * h); /*laplacianResult->resize(rs.rows(), 1); *laplacianResult = (h*h * r1Inv) + (3.0*r1.array()) ; *laplacianResult = laplacianResult->unaryExpr([](auto v){return std::isfinite(v) ? v : 0.0;}); *laplacianResult = (-3.0*A)*(laplacianResult->array() - 4.0*h); */ } } } // Physics } // d2 } // GooBalls
30.28972
102
0.598889
Fluci
1a99488fb993c7f309991b8760b7db869f11f2dd
590
hpp
C++
Main course/Homework4/Problem2/Header files/Object.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework4/Problem2/Header files/Object.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework4/Problem2/Header files/Object.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
#pragma once #include "Comparable.hpp" #include "Debug.hpp" #include "Serializable.hpp" class Object : public Comparable, public Debug, public Serializable { public: Object(const std::string& name, const std::string& location, const std::string& extension); std::string get_name() const; std::string get_location() const; std::string get_extension() const; std::string get_fullpath() const; virtual Object* clone() const = 0; std::string to_string() const override; virtual ~Object() = default; protected: std::string name; std::string location; std::string extension; };
21.071429
92
0.730508
nia-flo
1a9e9fb5b9b93e87d24d49988b70f48f0121aad1
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/failtest/block_on_const_type_actually_const_0.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/block_on_const_type_actually_const_0.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/failtest/block_on_const_type_actually_const_0.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:b75858ed52d328dae0e5d29dcf258d42c226b61bc62c50bb344a90c40ea99884 size 262
32
75
0.882813
initialz
1aa7f939d8a193dba0485f19e68c9178d7dfc8e7
904
cpp
C++
897. Increasing Order Search Tree/main.cpp
dllexport/leetcode
a0cfd5d759daa36fec808b2dbe19c045d218ed76
[ "MIT" ]
null
null
null
897. Increasing Order Search Tree/main.cpp
dllexport/leetcode
a0cfd5d759daa36fec808b2dbe19c045d218ed76
[ "MIT" ]
null
null
null
897. Increasing Order Search Tree/main.cpp
dllexport/leetcode
a0cfd5d759daa36fec808b2dbe19c045d218ed76
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* increasingBST(TreeNode* root) { preOrderTraval(root); for(auto i : arr) { printf("%x ", i); } return makeTree(); } void preOrderTraval(TreeNode* root) { if(!root) return; preOrderTraval(root->left); arr.push_back(root->val); preOrderTraval(root->right); } TreeNode* makeTree(){ res = new TreeNode(arr[0]); auto p = res; for(int i = 1; i < arr.size(); i++){ auto node = new TreeNode(arr[i]); p->right = node; p = p->right; } return res; } private: std::vector<int> arr; TreeNode* res; };
22.04878
59
0.504425
dllexport
1aa981845b647597b54b8010a5db6cc4d9c366cd
13,935
cpp
C++
Ouroboros/Source/oGUI/msgbox.cpp
igHunterKiller/ouroboros
5e2cde7e6365341da297da10d8927b091ecf5559
[ "MIT" ]
null
null
null
Ouroboros/Source/oGUI/msgbox.cpp
igHunterKiller/ouroboros
5e2cde7e6365341da297da10d8927b091ecf5559
[ "MIT" ]
null
null
null
Ouroboros/Source/oGUI/msgbox.cpp
igHunterKiller/ouroboros
5e2cde7e6365341da297da10d8927b091ecf5559
[ "MIT" ]
null
null
null
// Copyright (c) 2016 Antony Arciuolo. See License.txt regarding use. #include <oCore/countof.h> #include <oGUI/msgbox.h> #include <oGUI/cursor.h> #include <oGUI/notification_area.h> #include <oGUI/Windows/oWinDialog.h> #include <oGUI/Windows/oWinRect.h> #include <oGUI/Windows/oWinWindowing.h> #include <oSystem/windows/win_error.h> // Secret function that is not normally exposed in headers. // Typically pass 0 for wLanguageId, and specify a timeout // for the dialog in milliseconds, returns MB_TIMEDOUT if // the timeout is reached. int MessageBoxTimeoutA(IN HWND hWnd, IN LPCSTR lpText, IN LPCSTR lpCaption, IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds); int MessageBoxTimeoutW(IN HWND hWnd, IN LPCWSTR lpText, IN LPCWSTR lpCaption, IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds); #ifdef UNICODE #define MessageBoxTimeout MessageBoxTimeoutW #else #define MessageBoxTimeout MessageBoxTimeoutA #endif #define MB_TIMEDOUT 32000 // Link to MessageBoxTimeout based on code from: // http://www.codeproject.com/KB/cpp/MessageBoxTimeout.aspx //Functions & other definitions required--> typedef int (__stdcall *MSGBOXAAPI)(IN HWND hWnd, IN LPCSTR lpText, IN LPCSTR lpCaption, IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds); typedef int (__stdcall *MSGBOXWAPI)(IN HWND hWnd, IN LPCWSTR lpText, IN LPCWSTR lpCaption, IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds); int MessageBoxTimeoutA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType, WORD wLanguageId, DWORD dwMilliseconds) { static MSGBOXAAPI MsgBoxTOA = nullptr; if (!MsgBoxTOA) { HMODULE hUser32 = GetModuleHandle("user32.dll"); if (hUser32) { MsgBoxTOA = (MSGBOXAAPI)GetProcAddress(hUser32, "MessageBoxTimeoutA"); //fall through to 'if (MsgBoxTOA)...' } else { //stuff happened, add code to handle it here //(possibly just call MessageBox()) return 0; } } if (MsgBoxTOA) { return MsgBoxTOA(hWnd, lpText, lpCaption, uType, wLanguageId, dwMilliseconds); } return 0; } int MessageBoxTimeoutW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType, WORD wLanguageId, DWORD dwMilliseconds) { static MSGBOXWAPI MsgBoxTOW = nullptr; if (!MsgBoxTOW) { HMODULE hUser32 = GetModuleHandle("user32.dll"); if (hUser32) { MsgBoxTOW = (MSGBOXWAPI)GetProcAddress(hUser32, "MessageBoxTimeoutW"); //fall through to 'if (MsgBoxTOW)...' } else { //stuff happened, add code to handle it here //(possibly just call MessageBox()) return 0; } } if (MsgBoxTOW) { return MsgBoxTOW(hWnd, lpText, lpCaption, uType, wLanguageId, dwMilliseconds); } return 0; } namespace ouro { static msg_result as_action(WORD _ID) { switch (_ID) { case IDCANCEL: return msg_result::abort; case IDRETRY: return msg_result::debug; default: case IDCONTINUE: return msg_result::ignore; case IDIGNORE: return msg_result::ignore_always; } } static UINT as_flags(msg_type type) { switch (type) { default: case msg_type::info: return MB_ICONINFORMATION|MB_OK; case msg_type::warn: return MB_ICONWARNING|MB_OK; case msg_type::yesno: return MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON1; case msg_type::error: return MB_ICONERROR|MB_OK|MB_TASKMODAL; case msg_type::debug: return MB_ICONERROR|MB_ABORTRETRYIGNORE; } } static msg_result get_result(int _MessageBoxResult) { switch (_MessageBoxResult) { default: case IDOK: return msg_result::yes; case IDABORT: return msg_result::abort; case IDIGNORE: return msg_result::ignore; case IDRETRY: return msg_result::debug; case IDYES: return msg_result::yes; case IDNO: return msg_result::no; } } static HICON load_icon(msg_type _Type) { static LPCSTR map[] = { IDI_INFORMATION, IDI_WARNING, IDI_QUESTION, IDI_ERROR, IDI_ERROR, IDI_INFORMATION, IDI_INFORMATION, IDI_WARNING, IDI_ERROR, }; match_array_e(map, msg_type); return LoadIconA(0, map[(int)_Type]); } #define IDMESSAGE 20 #define IDCOPYTOCLIPBOARD 21 #define IDICON 22 static VOID CALLBACK WndDialogTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { switch (idEvent) { case 1: EndDialog(hwnd, IDCANCEL); break; case 2: EnableWindow(GetDlgItem(hwnd, IDCONTINUE), TRUE); EnableWindow(GetDlgItem(hwnd, IDIGNORE), TRUE); KillTimer(hwnd, idEvent); break; } } struct DLGAssert { DLGAssert(HICON _hIcon, unsigned int _TimeoutMS, unsigned int _DisableTimeoutMS) : hIcon(_hIcon) , TimeoutMS(static_cast<UINT>(_TimeoutMS)) , DisableTimeoutMS(static_cast<UINT>(_DisableTimeoutMS)) , hBGBrush(nullptr/*CreateSolidBrush(RGB(255,255,255))*/) // I want to make the top part of the dialog white and bottom gray like in Win7, but I can't change the BG color of a read-only editbox since the WM_CTLCOLOREDIT doesn't get sent {} ~DLGAssert() { DeleteObject(hBGBrush); } oDECLARE_DLGPROC(, WndProc); oDECLARE_DLGPROC(static, StaticWndProc); HICON hIcon; UINT TimeoutMS; UINT DisableTimeoutMS; HBRUSH hBGBrush; }; oDEFINE_DLGPROC(DLGAssert, StaticWndProc); INT_PTR CALLBACK DLGAssert::WndProc(HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam) { //char desc[512]; //oGetWMDesc(desc, _hWnd, _uMsg, _wParam, _lParam); //oTrace("%s", desc); switch (_uMsg) { case WM_INITDIALOG: { if (TimeoutMS != ~0u) SetTimer(_hWnd, 1, TimeoutMS, WndDialogTimerProc); if (DisableTimeoutMS != 0 && DisableTimeoutMS != ~0u) SetTimer(_hWnd, 2, DisableTimeoutMS, WndDialogTimerProc); SendDlgItemMessage(_hWnd, IDICON, STM_SETICON, (WPARAM)hIcon, 0); return false; } case WM_SETCURSOR: while (ShowCursor(true) < 0) {} SetCursor(LoadCursor(nullptr, IDC_ARROW)); return true; case WM_COMMAND: switch (_wParam) { case IDCANCEL: case IDRETRY: case IDCONTINUE: case IDIGNORE: EndDialog(_hWnd, _wParam); return true; case IDCOPYTOCLIPBOARD: SendDlgItemMessage(_hWnd, IDMESSAGE, EM_SETSEL, 0, -1); SendDlgItemMessage(_hWnd, IDMESSAGE, WM_COPY, 0, 0); return true; default: break; } //case WM_CTLCOLORDLG: // return (INT_PTR)hBGBrush; //case WM_CTLCOLOREDIT: //{ // if (HWND(_lParam) == GetDlgItem(_hWnd, IDMESSAGE)) // { // SetBkMode((HDC)_wParam, TRANSPARENT); // return (INT_PTR)hBGBrush; // } // break; //} //case WM_CTLCOLORBTN: // break; //case WM_CTLCOLORSTATIC: // break; default: break; } return false; } static void calc_string_rect(RECT& rString, const char* string, LONG minW, LONG minH, LONG maxW, LONG maxH) { rString.left = 0; rString.top = 0; rString.right = 1; rString.bottom = 1; HDC hDC = CreateCompatibleDC(0); DrawTextA(hDC, string, -1, &rString, DT_CALCRECT|DT_LEFT|DT_NOPREFIX|DT_WORDBREAK); DeleteDC(hDC); // use a fudge-factor for the not-so-nice numbers that come out of DrawText rString.bottom = __min(maxH, __max(minH, rString.bottom * 3/4)); rString.right = __min(maxW, __max(minW, rString.right * 3/4)); if (rString.bottom == maxH) rString.right = maxW; } msg_result assert_dialog(msg_type _Type, const char* _Caption, const char* _String, unsigned int _DialogTimeoutMS, unsigned int _IgnoreDisableTimeoutMS) { const LONG FrameSpacingX = 5; const LONG FrameSpacingY = 6; const LONG BtnSpacingX = 3; const LONG BtnW = 42; const LONG BtnH = 13; const LONG BtnCopyW = 65; const LONG BtnPanelW = 4 * BtnW + 3 * BtnSpacingX; const LONG MinW = BtnCopyW + BtnSpacingX + BtnPanelW + 2 * FrameSpacingX; const LONG MinH = 50; const LONG MaxW = MinW + 150; const LONG MaxH = MinH + 150; RECT rString; std::vector<char> string(128 * 1024); replace(string.data(), string.size(), _String, "\n", "\r\n"); calc_string_rect(rString, string.data(), MinW, MinH, MaxW, MaxH); // Figure out where interface goes based on string RECT const LONG BtnPanelLeft = (rString.right - BtnPanelW) - FrameSpacingX; const LONG BtnPanelTop = rString.bottom; const LONG BtnPanelBottom = BtnPanelTop + BtnH; // Offset string box to make room for icon on left RECT rIcon = { FrameSpacingX, FrameSpacingY, rIcon.left + (GetSystemMetrics(SM_CXICON)/2), rIcon.top + (GetSystemMetrics(SM_CYICON)/2) }; rString.left += rIcon.right + FrameSpacingX + 2; rString.top += FrameSpacingY; rString.right -= FrameSpacingX; rString.bottom -= FrameSpacingY; // Assign the bounds for the rest of the dialog items // 4 main control options are right-aligned, but spaced evenly RECT rAbort = { BtnPanelLeft, BtnPanelTop, rAbort.left + BtnW, BtnPanelBottom }; RECT rBreak = { rAbort.right + BtnSpacingX, BtnPanelTop, rBreak.left + BtnW, BtnPanelBottom }; RECT rContinue = { rBreak.right + BtnSpacingX, BtnPanelTop, rContinue.left + BtnW, BtnPanelBottom }; RECT rIgnore = { rContinue.right + BtnSpacingX, BtnPanelTop, rIgnore.left + BtnW, BtnPanelBottom }; // copy to clipboard is left-aligned RECT rCopyToClipboard = { FrameSpacingX, BtnPanelTop, rCopyToClipboard.left + BtnCopyW, rCopyToClipboard.top + BtnH }; // Make the overall dialog RECT rDialog = { 0, 0, __max(rString.right, rIgnore.right + FrameSpacingX), __max(rString.bottom, rIgnore.bottom + FrameSpacingY) }; bool TimedoutControlledEnable = (_IgnoreDisableTimeoutMS == 0); const oWINDOWS_DIALOG_ITEM items[] = { { "&Abort", oDLG_BUTTON, IDCANCEL, rAbort, true, true, true }, { "&Break", oDLG_BUTTON, IDRETRY, rBreak, true, true, true }, { "&Continue", oDLG_BUTTON, IDCONTINUE, rContinue, TimedoutControlledEnable, true, true }, { "I&gnore", oDLG_BUTTON, IDIGNORE, rIgnore, TimedoutControlledEnable, true, true }, { "Copy &To Clipboard", oDLG_BUTTON, IDCOPYTOCLIPBOARD, rCopyToClipboard, true, true, true }, { string.data(), oDLG_LARGELABEL, IDMESSAGE, rString, true, true, true }, { "", oDLG_ICON, IDICON, rIcon, true, true, false }, }; oWINDOWS_DIALOG_DESC dlg; dlg.Font = "Tahoma"; dlg.Caption = _Caption; dlg.pItems = items; dlg.NumItems = countof(items); dlg.FontPointSize = 8; dlg.Rect = rDialog; dlg.Center = true; dlg.SetForeground = true; dlg.Enabled = true; dlg.Visible = true; dlg.AlwaysOnTop = true; LPDLGTEMPLATE lpDlgTemplate = oDlgNewTemplate(dlg); HICON hIcon = load_icon(_Type); DLGAssert Dialog(hIcon, _DialogTimeoutMS, _IgnoreDisableTimeoutMS); INT_PTR int_ptr = DialogBoxIndirectParam(GetModuleHandle(0), lpDlgTemplate, GetDesktopWindow(), DLGAssert::StaticWndProc, (LPARAM)&Dialog); oDlgDeleteTemplate(lpDlgTemplate); if (int_ptr == -1) { std::string msg = windows::category().message(GetLastError()); oTrace("DialogBoxIndirectParam failed. %s\n", msg.c_str()); __debugbreak(); // debug msgbox called from oASSERTs, so don't recurse into it } DeleteObject(hIcon); msg_result result = as_action(static_cast<WORD>(int_ptr)); return result; } namespace WFNWCV { static thread_local HWND hParent = nullptr; static thread_local WNDPROC OrigWndProc = nullptr; static thread_local HHOOK Hook = nullptr; LRESULT CALLBACK WndProc(HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam) { LRESULT result = CallWindowProc(OrigWndProc, _hWnd, _uMsg, _wParam, _lParam); switch (_uMsg) { case WM_ACTIVATE: { if (hParent) { RECT rParent, rChild; GetWindowRect(_hWnd, &rChild); GetWindowRect(hParent, &rParent); POINT p = {0,0}; ClientToScreen(hParent, &p); int2 MsgBoxPosition = int2(p.x, p.y) + (oWinRectSize(rParent) - oWinRectSize(rChild)) / 2; SetWindowPos(_hWnd, nullptr, MsgBoxPosition.x, MsgBoxPosition.y, 0, 0, SWP_NOZORDER|SWP_NOSIZE); } break; } case WM_SETCURSOR: { cursor::set(_hWnd, mouse_cursor::arrow); break; } case WM_NCDESTROY: { oVB(UnhookWindowsHookEx(Hook)); hParent = nullptr; Hook = nullptr; OrigWndProc = nullptr; break; } } return result; } LRESULT install(int _nCode, WPARAM _wParam, LPARAM _lParam) { CWPSTRUCT& cwp = *(CWPSTRUCT*)_lParam; if (_nCode == HC_ACTION && cwp.message == WM_INITDIALOG && !OrigWndProc) OrigWndProc = (WNDPROC)SetWindowLongPtr(cwp.hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); return CallNextHookEx(WFNWCV::Hook, _nCode, _wParam, _lParam); } } // WFNWCV void set_next_MessageBox_WndProc(HWND _hParent) { WFNWCV::hParent = _hParent; if (WFNWCV::hParent) WFNWCV::Hook = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)WFNWCV::install, nullptr, GetWindowThreadProcessId(_hParent, nullptr)); } msg_result msgboxv(msg_type _Type, ouro::window_handle _hParent, const char* _Title, const char* _Format, va_list _Args) { static const unsigned int _TimeoutMS = INFINITE; std::vector<char> msg(128 * 1024); vsnprintf(msg.data(), msg.size(), _Format, _Args); msg_result result = msg_result::yes; HICON hIcon = nullptr; std::thread::id ThreadID; HWND hWnd = (HWND)_hParent; try { if (!hWnd) oWinGetProcessTopWindowAndThread(this_process::get_id(), &hWnd, &ThreadID); } catch (std::exception&) { // continue on } switch (_Type) { case msg_type::debug: result = assert_dialog(_Type, _Title, msg.data(), _TimeoutMS, 0); break; case msg_type::notify_info: case msg_type::notify_warn: case msg_type::notify_error: hIcon = load_icon(_Type); // pass thru case msg_type::notify: notification_area::show_message((ouro::window_handle)hWnd, 0, (ouro::icon_handle)hIcon, __max(2000, _TimeoutMS), _Title, msg.data()); result = msg_result::ignore; break; default: { set_next_MessageBox_WndProc(hWnd); result = get_result(MessageBoxTimeout(hWnd, msg.data(), _Title, as_flags(_Type), 0, _TimeoutMS)); break; } } return result; } }
28.094758
238
0.700466
igHunterKiller
1aaba2ba17d8c32434fa58dae4a7a4dc3a9312ab
1,557
cpp
C++
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Naziaislam91
cc72163a5c49c144b06eb40e21462befa252721a
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Naziaislam91
cc72163a5c49c144b06eb40e21462befa252721a
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Naziaislam91
cc72163a5c49c144b06eb40e21462befa252721a
[ "MIT" ]
null
null
null
#include "tic_tac_toe_manager.h" #include "tic_tac_toe_3.h" #include "tic_tac_toe_data.h" #include "tic_tac_toe_4.h" #include "tic_tac_toe.h" #include<iostream> #include<string> //cpp /*TicTacToeManager::TicTacToeManager(TicTacToeData & data) { games = data.get_games(); //confused for (auto &game : games) { update_winner_count(game->get_winner()); } } */ TicTacToeManager::~TicTacToeManager() { TicTacToeData* saved_game; saved_game->save_pegs(games); } void TicTacToeManager::save_game(unique_ptr<TicTacToe> &game) { update_winner_count(game->get_winner()); games.push_back(std::move(game)); } void TicTacToeManager::update_winner_count(std::string winner) { if (winner == "X") { x_win++; } else if (winner == "O") { o_win++; } else { ties++; } } std::ostream & operator << (std::ostream & out, const TicTacToeManager & manager) { int x_win{ 0 }; int o_win{ 0 }; int ties{ 0 }; for (auto &game : manager.games) { out << *game; } //out << game; //game.get_winner(); out << "X wins: " << manager.x_win << "\n"; out << "O wins: " << manager.o_win << "\n"; out << "Tie: " << manager.ties << "\n"; /*if (game->get_winner() == "X") { x_win++; } else if (game->get_winner() == "O") { o_win++; } else if (game->get_winner() == "C") { ties++; }*/ return out; } /*void TicTacToeManager::get_winner_total(int & x, int& o, int& t) { std::cout << "X wins: " << x_win << "\n"; std::cout << "O wins: " << o_win << "\n"; std::cout << "Tie: " << ties << "\n"; }*/
15.887755
81
0.595376
acc-cosc-1337-spring-2020
1aad67a85aaee6f851f8b07db0eb9a0a02c20f18
5,630
cpp
C++
op_utilities/nodes/op_hmi_bridge/SocketServer.cpp
marcusvinicius178/core_planning
1e9f6c211d902dd5a9d99d0cbf9df4726a7c6739
[ "Apache-2.0" ]
1
2021-12-25T15:50:31.000Z
2021-12-25T15:50:31.000Z
op_utilities/nodes/op_hmi_bridge/SocketServer.cpp
marcusvinicius178/core_planning
1e9f6c211d902dd5a9d99d0cbf9df4726a7c6739
[ "Apache-2.0" ]
null
null
null
op_utilities/nodes/op_hmi_bridge/SocketServer.cpp
marcusvinicius178/core_planning
1e9f6c211d902dd5a9d99d0cbf9df4726a7c6739
[ "Apache-2.0" ]
null
null
null
/* * SocketServer.cpp * * Created on: Feb 13, 2017 * Author: user */ #include "SocketServer.h" #include <string.h> namespace HMI_BRIDGE_NS { HMISocketServer::HMISocketServer() { m_Socket_send = 0; m_Socket_receive = 0; sock_mutex_send = PTHREAD_MUTEX_INITIALIZER; sock_mutex_receive = PTHREAD_MUTEX_INITIALIZER; sock_thread_tid_send = 0; sock_thread_tid_receive = 0; m_bLatestMsg_send = false; m_bLatestMsg_receive = false; m_bExitMainLoop = false; } HMISocketServer::~HMISocketServer() { std::cout << " >> Call The Destructor !!!!! " << std::endl; HMISocketServer* pRet; m_bExitMainLoop = true; shutdown(m_Socket_receive, SHUT_RDWR); if(sock_thread_tid_receive>0) { pthread_join(sock_thread_tid_receive, (void**)&pRet); } close(m_Socket_receive); shutdown(m_Socket_send, SHUT_RDWR); if(sock_thread_tid_send>0) { pthread_join(sock_thread_tid_send, (void**)&pRet); } close(m_Socket_send); std::cout << " >> Destroy everything !!!!! " << std::endl; } int HMISocketServer::CreateSocket(int port, int& socket_id) { int err = -1; int reuse = 1; socket_id = socket(AF_INET, SOCK_STREAM, 0); if(socket_id == -1) { std::cout << "Error: Can't Create Socket." << std::endl; return -1; } err = setsockopt(socket_id, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); if(err == -1) { shutdown(socket_id, SHUT_RDWR); close(socket_id); std::cout << "Error: Can't Set Socket Options." << std::endl; return -1; } sockaddr_in addr; memset(&addr, 0, sizeof(sockaddr_in)); addr.sin_family = PF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; err = bind(socket_id, (struct sockaddr *)&addr, sizeof(addr)); if(err == -1) { shutdown(socket_id, SHUT_RDWR); close(socket_id); std::cout << "Error: Can't Bind Socket Address." << std::endl; return -1; } err = listen(socket_id, 5 /*maximum two clients can connect*/); if(err == -1) { std::cout << "Error: Can't Initialize Socket Listen Server." << std::endl; return -1; } return 1; } int HMISocketServer::InitSocket(int port_send, int port_receive) { if(CreateSocket(port_send, m_Socket_send) == -1) { return -1; } if(pthread_create(&sock_thread_tid_send, nullptr,&HMISocketServer::ThreadMainSend , this) != 0) { std::cout << "Error: Can't Create Thread for Sending Socket ." << std::endl; return -1; } if(CreateSocket(port_receive, m_Socket_receive) == -1) { return -1; } if(pthread_create(&sock_thread_tid_receive, nullptr,&HMISocketServer::ThreadMainReceive , this) != 0) { std::cout << "Error: Can't Create Thread for Receive Socket ." << std::endl; return -1; } return 1; } void* HMISocketServer::ThreadMainSend(void* pSock) { HMISocketServer* pS = (HMISocketServer*)pSock; while(!pS->m_bExitMainLoop) { int client_sock = 0; sockaddr_in client; socklen_t len = sizeof(client); client_sock = accept(pS->m_Socket_send, reinterpret_cast<sockaddr*>(&client), &len); if(client_sock == -1) { std::cout << "Can't Accept sending socket connection." << std::endl; usleep(100); continue; } bool bSkip = false; PlannerHNS::HMI_MSG msg; pthread_mutex_lock(&pS->sock_mutex_send); if(pS->m_bLatestMsg_send == false) // No Message to send , don't create any connections { bSkip = true; } else { msg = pS->m_msg_send; pS->m_bLatestMsg_send = false; } pthread_mutex_unlock(&pS->sock_mutex_send); if(!bSkip) { std::string cmd = msg.CreateStringMessage(); ssize_t n = write(client_sock, cmd.c_str(), cmd.size()); if(n < 0) { std::cout << "Can't Write message to socket." << std::endl; usleep(100); continue; } } shutdown(client_sock, SHUT_RDWR); if(close(client_sock) == -1) { std::cout << "Can't Close Send socket." << std::endl; usleep(100); continue; } } return 0; } void* HMISocketServer::ThreadMainReceive(void* pSock) { HMISocketServer* pS = (HMISocketServer*)pSock; while(!pS->m_bExitMainLoop) { int client_sock = 0; sockaddr_in client; socklen_t len = sizeof(client); client_sock = accept(pS->m_Socket_receive, reinterpret_cast<sockaddr*>(&client), &len); if(client_sock == -1) { std::cout << "Can't Accept receiving socket connection." << std::endl; usleep(100); continue; } char recvdata[1024]; std::string can_data(""); ssize_t nr = 0; while(true) { nr = recv(client_sock, recvdata, sizeof(recvdata), 0); if(nr<0) { std::cout << "Can't receive message from socket." << std::endl; can_data = ""; break; } else if(nr == 0) { break; } can_data.append(recvdata,nr); } shutdown(client_sock, SHUT_RDWR); if(close(client_sock)<0) { std::cout << "Can't Close receive socket." << std::endl; usleep(100); continue; } if(can_data.size() > 0) { pthread_mutex_lock(&pS->sock_mutex_receive); PlannerHNS::HMI_MSG msg_temp = PlannerHNS::HMI_MSG::FromString(can_data); if(msg_temp.type != PlannerHNS::UNKNOWN_MSG) { pS->m_bLatestMsg_receive = true; pS->m_msg_receive = msg_temp; } pthread_mutex_unlock(&pS->sock_mutex_receive); } } return 0; } void HMISocketServer::SendMSG(PlannerHNS::HMI_MSG msg) { pthread_mutex_lock(&sock_mutex_send); m_bLatestMsg_send = true; m_msg_send = msg; pthread_mutex_unlock(&sock_mutex_send); } int HMISocketServer::GetLatestMSG(PlannerHNS::HMI_MSG& msg) { int res = -1; pthread_mutex_lock(&sock_mutex_receive); if(m_bLatestMsg_receive == true) { msg = m_msg_receive; m_bLatestMsg_receive = false; res = 1; } pthread_mutex_unlock(&sock_mutex_receive); return res; } }
21.007463
102
0.673179
marcusvinicius178
1ab8b746a99a0407ae06a26db0a7e73da5ca0d66
12,635
cpp
C++
Code/PowerUp.cpp
ofaura/AndroDunos
98a8d54443df0bb3f9bd2b3ceb2017b3dafda489
[ "MIT" ]
2
2018-05-17T21:41:48.000Z
2018-12-27T21:46:00.000Z
Code/PowerUp.cpp
ofaura/AndroDunos
98a8d54443df0bb3f9bd2b3ceb2017b3dafda489
[ "MIT" ]
2
2018-05-15T19:03:18.000Z
2018-06-25T11:28:04.000Z
Code/PowerUp.cpp
ofaura/AndroDunos
98a8d54443df0bb3f9bd2b3ceb2017b3dafda489
[ "MIT" ]
null
null
null
#include "Application.h" #include "PowerUp.h" #include "ModuleCollision.h" #include "ModuleParticles.h" #include "ModuleEnemies.h" #include "ModulePlayer.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModuleShield.h" #include "ModuleShield_p2.h" #include "ModuleAudio.h" #include "ModulePlayer.h" #include "ModulePlayer2.h" #include "ModuleUserInterface.h" #include <cstdio> #include <cstdlib> #include <time.h> #include <iostream> #include <string> enum Stages { STILL_1 = 0, REFLECTION_1, CHANGE_1, STILL_2, REFLECTION_2, CHANGE_2 }; PowerUp::PowerUp(int x, int y) : Enemy(x, y) { srand(time(NULL)); // doesn't let me do time(NULL) type = POWER_UP; powerup_picked = App->audio->LoadFx("Assets/Audio/Sound FX/powerup_picked.wav"); graphics = App->textures->Load("Assets/Sprites/Enemies/enemies.png"); HP = -1; random = rand() % 4; if (random == 0) { S_B = true; fly_1.PushBack({ 10, 558, 16, 16 }); // still fly_1.loop = true; act[0] = &fly_1; fly_2.PushBack({ 29, 558, 16, 16 }); // reflection fly_2.PushBack({ 47, 558, 16, 16 }); fly_2.PushBack({ 65, 558, 16, 16 }); fly_2.PushBack({ 10, 558, 16, 16 }); fly_2.speed = 0.15f; fly_2.loop = false; act[1] = &fly_2; fly_3.PushBack({ 83, 558, 16, 16 }); // Change fly_3.PushBack({ 101, 558, 16, 16 }); fly_3.PushBack({ 101, 622, 16, 16 }); fly_3.PushBack({ 83, 540, 16, 16 }); fly_3.PushBack({ 101, 540, 16, 16 }); fly_3.PushBack({ 10, 540, 16, 16 }); fly_3.speed = 0.6f; fly_3.loop = false; act[2] = &fly_3; fly_4.PushBack({ 10, 540, 16, 16 }); // still fly_4.loop = true; act[3] = &fly_4; fly_5.PushBack({ 29, 540, 16, 16 }); // reflection fly_5.PushBack({ 47, 540, 16, 16 }); fly_5.PushBack({ 65, 540, 16, 16 }); fly_4.PushBack({ 10, 540, 16, 16 }); fly_5.speed = 0.15f; fly_5.loop = false; act[4] = &fly_5; fly_6.PushBack({ 83, 540, 16, 16 }); // Change fly_6.PushBack({ 101, 540, 16, 16 }); fly_6.PushBack({ 101, 622, 16, 16 }); // fly_6.PushBack({ 83, 558, 16, 16 }); fly_6.PushBack({ 101, 558, 16, 16 }); fly_6.PushBack({ 10, 558, 16, 16 }); fly_6.speed = 0.6f; fly_6.loop = false; act[5] = &fly_6; } else if (random == 1) { B_M = true; fly_1.PushBack({ 10, 540, 16, 16 }); // still fly_1.loop = true; act[0] = &fly_1; fly_2.PushBack({ 29, 540, 16, 16 }); // reflection fly_2.PushBack({ 47, 540, 16, 16 }); fly_2.PushBack({ 65, 540, 16, 16 }); fly_2.PushBack({ 10, 540, 16, 16 }); fly_2.speed = 0.15f; fly_2.loop = false; act[1] = &fly_2; fly_3.PushBack({ 83, 540, 16, 16 }); // Change fly_3.PushBack({ 101, 540, 16, 16 }); fly_3.PushBack({ 101, 622, 16, 16 }); /// fly_3.PushBack({ 83, 594, 16, 16 }); fly_3.PushBack({ 101, 594, 16, 16 }); fly_3.PushBack({ 10, 594, 16, 16 }); fly_3.speed = 0.6f; fly_3.loop = false; act[2] = &fly_3; fly_4.PushBack({ 10, 594, 16, 16 }); // still fly_4.loop = true; act[3] = &fly_4; fly_5.PushBack({ 29, 594, 16, 16 }); // reflection fly_5.PushBack({ 47, 594, 16, 16 }); fly_5.PushBack({ 65, 594, 16, 16 }); fly_5.PushBack({ 10, 594, 16, 16 }); fly_5.speed = 0.15f; fly_5.loop = false; act[4] = &fly_5; fly_6.PushBack({ 83, 594, 16, 16 }); // Change fly_6.PushBack({ 101, 594, 16, 16 }); fly_6.PushBack({ 101, 622, 16, 16 }); /// fly_6.PushBack({ 83, 540, 16, 16 }); fly_6.PushBack({ 101, 540, 16, 16 }); fly_6.PushBack({ 10, 540, 16, 16 }); fly_6.speed = 0.6f; fly_6.loop = false; act[5] = &fly_6; } else if (random == 2) { M_U = true; fly_1.PushBack({ 10, 594, 16, 16 }); // still fly_1.loop = true; act[0] = &fly_1; fly_2.PushBack({ 29, 594, 16, 16 }); // reflection fly_2.PushBack({ 47, 594, 16, 16 }); fly_2.PushBack({ 65, 594, 16, 16 }); fly_2.PushBack({ 10, 594, 16, 16 }); fly_2.speed = 0.15f; fly_2.loop = false; act[1] = &fly_2; fly_3.PushBack({ 83, 594, 16, 16 }); // Change fly_3.PushBack({ 101, 594, 16, 16 }); fly_3.PushBack({ 101, 622, 16, 16 }); /// fly_3.PushBack({ 101, 576, 16, 16 }); fly_3.PushBack({ 83, 576, 16, 16 }); fly_3.PushBack({ 10, 576, 16, 16 }); fly_3.speed = 0.6f; fly_3.loop = false; act[2] = &fly_3; fly_4.PushBack({ 10, 576, 16, 16 }); // still fly_4.loop = true; act[3] = &fly_4; fly_5.PushBack({ 29, 576, 16, 16 }); // reflection fly_5.PushBack({ 47, 576, 16, 16 }); fly_5.PushBack({ 65, 576, 16, 16 }); fly_5.PushBack({ 10, 576, 16, 16 }); fly_5.speed = 0.15f; fly_5.loop = false; act[4] = &fly_5; fly_6.PushBack({ 101, 576, 16, 16 }); // Change fly_6.PushBack({ 83, 576, 16, 16 }); fly_6.PushBack({ 101, 622, 16, 16 }); /// fly_6.PushBack({ 101, 594, 16, 16 }); fly_6.PushBack({ 83, 594, 16, 16 }); fly_6.PushBack({ 10, 594, 16, 16 }); fly_6.speed = 0.6f; fly_6.loop = false; act[5] = &fly_6; } else if (random == 3) { U_S = true; fly_1.PushBack({ 10, 576, 16, 16 }); // still fly_1.loop = true; act[0] = &fly_1; fly_2.PushBack({ 29, 576, 16, 16 }); // reflection fly_2.PushBack({ 47, 576, 16, 16 }); fly_2.PushBack({ 65, 576, 16, 16 }); fly_2.PushBack({ 10, 576, 16, 16 }); fly_2.speed = 0.15f; fly_2.loop = false; act[1] = &fly_2; fly_3.PushBack({ 101, 576, 16, 16 }); // Change fly_3.PushBack({ 83, 576, 16, 16 }); fly_3.PushBack({ 101, 622, 16, 16 }); /// fly_3.PushBack({ 83, 558, 16, 16 }); fly_3.PushBack({ 101, 558, 16, 16 }); fly_3.PushBack({ 10, 558, 16, 16 }); fly_3.speed = 0.6f; fly_3.loop = false; act[2] = &fly_3; fly_4.PushBack({ 10, 558, 16, 16 }); // still fly_4.loop = true; act[3] = &fly_4; fly_5.PushBack({ 29, 558, 16, 16 }); // reflection fly_5.PushBack({ 47, 558, 16, 16 }); fly_5.PushBack({ 65, 558, 16, 16 }); fly_5.PushBack({ 10, 558, 16, 16 }); fly_5.speed = 0.15f; fly_5.loop = false; act[4] = &fly_5; fly_6.PushBack({ 83, 558, 16, 16 }); // Change fly_6.PushBack({ 101, 558, 16, 16 }); fly_6.PushBack({ 101, 622, 16, 16 }); /// fly_6.PushBack({ 101, 576, 16, 16 }); fly_6.PushBack({ 83, 576, 16, 16 }); fly_6.PushBack({ 10, 576, 16, 16 }); fly_6.speed = 0.6f; fly_6.loop = false; act[5] = &fly_6; } collider = App->collision->AddCollider({ 0, 0, 16, 16 }, COLLIDER_TYPE::COLLIDER_POWER_UP, (Module*)App->enemies); original_y = y; } void PowerUp::Draw(SDL_Texture* sprites) { if (milliseconds >= 0 && milliseconds < 400) { if (milliseconds >= 200 && milliseconds < 225) { App->render->Blit(graphics, position.x, position.y, &(act[REFLECTION_1]->GetCurrentFrame())); } else { App->render->Blit(graphics, position.x, position.y, &(act[STILL_1]->GetCurrentFrame())); } } else if (milliseconds >= 400 && milliseconds < 425) { App->render->Blit(graphics, position.x, position.y, &(act[CHANGE_1]->GetCurrentFrame())); } else if (milliseconds >= 425 && milliseconds < 825) { if (milliseconds >= 625 && milliseconds < 650) { App->render->Blit(graphics, position.x, position.y, &(act[REFLECTION_2]->GetCurrentFrame())); } else { App->render->Blit(graphics, position.x, position.y, &(act[STILL_2]->GetCurrentFrame())); } } else if (milliseconds >= 825 && milliseconds < 850) { App->render->Blit(graphics, position.x, position.y, &(act[CHANGE_2]->GetCurrentFrame())); } else if (milliseconds >= 850) { for (int counter = 0; counter < CHANGE_2 + 1; counter++) { act[counter]->Reset(); } milliseconds = -1; } collider->SetPos(position.x, position.y); milliseconds++; } void PowerUp::Move() { //x lim if (position.x < abs(App->render->camera.x) / SCREEN_SIZE) { vel_x = -1 * vel_x; position.x = (App->render->camera.x / SCREEN_SIZE)+1; } else if (position.x >((abs(App->render->camera.x) / SCREEN_SIZE) + SCREEN_WIDTH - 16)) { vel_x = -1 * vel_x; position.x = (abs(App->render->camera.x) / SCREEN_SIZE) + SCREEN_WIDTH - 17; } //y lim if (position.y < abs(App->render->camera.y) / SCREEN_SIZE) { vel_y = -1 * vel_y; position.y = (abs(App->render->camera.y) / SCREEN_SIZE) + 1; } else if (position.y >(abs(App->render->camera.y) / SCREEN_SIZE) + SCREEN_HEIGHT - 16) { vel_y = -1 * vel_y; position.y = (abs(App->render->camera.y) / SCREEN_SIZE) + SCREEN_HEIGHT - 17; } position.y += vel_y; position.x += vel_x; // Perpetual Horizontal movement if (App->render->camera.x >= 0 && App->render->camera.x <= 8800 * SCREEN_SIZE) { position.x += 1; } } void PowerUp::OnCollision(Collider* collider) { if (S_B == true) { if (milliseconds < 412) { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); App->player->ShootPowerUpLevel++; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { App->audio->PlayFx(powerup_picked); App->player2->ShootPowerUpLevel++; App->user_interface->score2 += score; } } else { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); App->player->ShootPowerUpLevel_2++; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { App->audio->PlayFx(powerup_picked); App->player2->ShootPowerUpLevel_2++; App->user_interface->score2 += score; } } } else if (B_M == true) { if (milliseconds < 412) { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); App->player->ShootPowerUpLevel_2++; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { App->audio->PlayFx(powerup_picked); App->player2->ShootPowerUpLevel_2++; App->user_interface->score2 += score; } } else { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); App->shield->Enable(); App->player->HomingMissile++; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { App->audio->PlayFx(powerup_picked); App->shield_p2->Enable(); App->player2->HomingMissile++; App->user_interface->score2 += score; } } } if (M_U == true) { if (milliseconds < 412) { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); App->user_interface->score1 += score; App->player->HomingMissile++; // it's a homing missile, it ain't even started yet } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { App->audio->PlayFx(powerup_picked); App->user_interface->score2 += score; App->player2->HomingMissile++; // it's a homing missile, it ain't even started yet } } else { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); //App->shield->Enable(); App->player->Shield = 5; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { //App->shield_p2->Enable(); App->player2->Shield2 = 5; App->audio->PlayFx(powerup_picked); App->user_interface->score2 += score; } } } if (U_S == true) { if (milliseconds < 412) { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); //App->shield->Enable(); App->player->Shield = 5; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { //App->shield_p2->Enable(); App->player2->Shield2 = 5; App->audio->PlayFx(powerup_picked); App->user_interface->score2 += score; } } else { if ((collider->type == COLLIDER_PLAYER || collider->type == COLLIDER_NONE)) { App->audio->PlayFx(powerup_picked); App->player->ShootPowerUpLevel++; App->user_interface->score1 += score; } else if (collider->type == COLLIDER_PLAYER_2 || collider->type == COLLIDER_NONE_PLAYER_2) { App->audio->PlayFx(powerup_picked); App->player2->ShootPowerUpLevel++; App->user_interface->score2 += score; } } } } bool PowerUp::CleanUp() { LOG("Unloading Powerup"); App->textures->Unload(graphics); App->audio->UnLoadFx(powerup_picked); return true; }
24.726027
115
0.610922
ofaura
1ab9293575380b2e977369f68a61931f2a684789
988
hpp
C++
include/z8kSequencer.hpp
spectromas/RackPlugins
6c42eb5676b17acc201e625341655a37d413a8fe
[ "CC0-1.0" ]
1
2021-12-12T22:09:17.000Z
2021-12-12T22:09:17.000Z
include/z8kSequencer.hpp
spectromas/RackPlugins
6c42eb5676b17acc201e625341655a37d413a8fe
[ "CC0-1.0" ]
null
null
null
include/z8kSequencer.hpp
spectromas/RackPlugins
6c42eb5676b17acc201e625341655a37d413a8fe
[ "CC0-1.0" ]
1
2021-12-13T22:12:47.000Z
2021-12-13T22:12:47.000Z
#pragma once struct Z8K; struct z8kSequencer { public: void Init(Input *pRst, Input *pDir, Input *pClk, Output *pOut, Light *pLights, std::vector<Param> &params, std::vector<int> steps) { curStep = 0; pReset = pRst; pDirection = pDir; pClock = pClk; pOutput = pOut; numSteps = steps.size(); for(int k = 0; k < numSteps; k++) { sequence.push_back(&params[steps[k]]); leds.push_back(&pLights[steps[k]]); chain.push_back(steps[k]); } } inline void Reset() { curStep = 0; leds[0]->value = LED_ON; for(int k = 1; k < numSteps; k++) leds[k]->value =LED_OFF; } int Step(Z8K *pModule); z8kSequencer() { pReset = NULL; pDirection = NULL; pClock = NULL; pOutput = NULL; } private: dsp::SchmittTrigger clockTrigger; dsp::SchmittTrigger resetTrigger; Input *pReset; Input *pDirection; Input *pClock; Output *pOutput; std::vector<Param *> sequence; std::vector<Light *> leds; std::vector<int> chain; int curStep; int numSteps; };
18.296296
131
0.648785
spectromas
1ac2562fedab45e7f4af9023db33134979132aa1
11,979
cpp
C++
s3/s3fs/gnutls_auth.cpp
murlock/irods_resource_plugin_s3
5b7fa3f3cf373900828454147226a225791e97a5
[ "BSD-3-Clause" ]
null
null
null
s3/s3fs/gnutls_auth.cpp
murlock/irods_resource_plugin_s3
5b7fa3f3cf373900828454147226a225791e97a5
[ "BSD-3-Clause" ]
null
null
null
s3/s3fs/gnutls_auth.cpp
murlock/irods_resource_plugin_s3
5b7fa3f3cf373900828454147226a225791e97a5
[ "BSD-3-Clause" ]
null
null
null
/* * s3fs - FUSE-based file system backed by Amazon S3 * * Copyright(C) 2007 Randy Rizun <rrizun@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <pthread.h> #include <unistd.h> #include <syslog.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <gcrypt.h> #include <gnutls/gnutls.h> #include <gnutls/crypto.h> #ifdef USE_GNUTLS_NETTLE #include <nettle/md5.h> #include <nettle/sha1.h> #include <nettle/hmac.h> #endif #include <string> #include <map> #include "common.h" #include "s3fs_auth.h" #include <rodsLog.h> using namespace std; //------------------------------------------------------------------- // Utility Function for version //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE const char* s3fs_crypt_lib_name(void) { static const char version[] = "GnuTLS(nettle)"; return version; } #else // USE_GNUTLS_NETTLE const char* s3fs_crypt_lib_name(void) { static const char version[] = "GnuTLS(gcrypt)"; return version; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for global init //------------------------------------------------------------------- bool s3fs_init_global_ssl(void) { if(GNUTLS_E_SUCCESS != gnutls_global_init()){ return false; } #ifndef USE_GNUTLS_NETTLE if(NULL == gcry_check_version(NULL)){ return false; } #endif // USE_GNUTLS_NETTLE return true; } bool s3fs_destroy_global_ssl(void) { gnutls_global_deinit(); return true; } //------------------------------------------------------------------- // Utility Function for crypt lock //------------------------------------------------------------------- bool s3fs_init_crypt_mutex(void) { return true; } bool s3fs_destroy_crypt_mutex(void) { return true; } //------------------------------------------------------------------- // Utility Function for HMAC //------------------------------------------------------------------- #ifdef USE_GNUTLS_NETTLE bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || !data || !digest || !digestlen){ return false; } if(NULL == (*digest = reinterpret_cast<unsigned char*>(malloc(SHA1_DIGEST_SIZE)))){ return false; } struct hmac_sha1_ctx ctx_hmac; hmac_sha1_set_key(&ctx_hmac, keylen, reinterpret_cast<const uint8_t*>(key)); hmac_sha1_update(&ctx_hmac, datalen, reinterpret_cast<const uint8_t*>(data)); hmac_sha1_digest(&ctx_hmac, SHA1_DIGEST_SIZE, reinterpret_cast<uint8_t*>(*digest)); *digestlen = SHA1_DIGEST_SIZE; return true; } bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || !data || !digest || !digestlen){ return false; } if(NULL == (*digest = reinterpret_cast<unsigned char*>(malloc(SHA256_DIGEST_SIZE)))){ return false; } struct hmac_sha256_ctx ctx_hmac; hmac_sha256_set_key(&ctx_hmac, keylen, reinterpret_cast<const uint8_t*>(key)); hmac_sha256_update(&ctx_hmac, datalen, reinterpret_cast<const uint8_t*>(data)); hmac_sha256_digest(&ctx_hmac, SHA256_DIGEST_SIZE, reinterpret_cast<uint8_t*>(*digest)); *digestlen = SHA256_DIGEST_SIZE; return true; } #else // USE_GNUTLS_NETTLE bool s3fs_HMAC(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || !data || !digest || !digestlen){ return false; } if(0 == (*digestlen = gnutls_hmac_get_len(GNUTLS_MAC_SHA1))){ return false; } if(NULL == (*digest = reinterpret_cast<unsigned char*>(malloc(*digestlen + 1)))){ return false; } if(0 > gnutls_hmac_fast(GNUTLS_MAC_SHA1, key, keylen, data, datalen, *digest)){ free(*digest); *digest = NULL; return false; } return true; } bool s3fs_HMAC256(const void* key, size_t keylen, const unsigned char* data, size_t datalen, unsigned char** digest, unsigned int* digestlen) { if(!key || !data || !digest || !digestlen){ return false; } if(0 == (*digestlen = gnutls_hmac_get_len(GNUTLS_MAC_SHA256))){ return false; } if(NULL == (*digest = reinterpret_cast<unsigned char*>(malloc(*digestlen + 1)))){ return false; } if(0 > gnutls_hmac_fast(GNUTLS_MAC_SHA256, key, keylen, data, datalen, *digest)){ free(*digest); *digest = NULL; return false; } return true; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for MD5 //------------------------------------------------------------------- size_t get_md5_digest_length(void) { return 16; } #ifdef USE_GNUTLS_NETTLE unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size) { struct md5_ctx ctx_md5; unsigned char buf[512]; ssize_t bytes; unsigned char* result; // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); md5_init(&ctx_md5); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } md5_update(&ctx_md5, bytes, buf); memset(buf, 0, 512); } if(NULL == (result = reinterpret_cast<unsigned char*>(malloc(get_md5_digest_length())))){ return NULL; } md5_digest(&ctx_md5, get_md5_digest_length(), result); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #else // USE_GNUTLS_NETTLE unsigned char* s3fs_md5hexsum(int fd, off_t start, ssize_t size) { gcry_md_hd_t ctx_md5; gcry_error_t err; char buf[512]; ssize_t bytes; unsigned char* result; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast<ssize_t>(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); if(GPG_ERR_NO_ERROR != (err = gcry_md_open(&ctx_md5, GCRY_MD_MD5, 0))){ S3FS_PRN_ERR("MD5 context creation failure: %s/%s", gcry_strsource(err), gcry_strerror(err)); return NULL; } for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); gcry_md_close(ctx_md5); return NULL; } gcry_md_write(ctx_md5, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = reinterpret_cast<unsigned char*>(malloc(get_md5_digest_length())))){ gcry_md_close(ctx_md5); return NULL; } memcpy(result, gcry_md_read(ctx_md5, 0), get_md5_digest_length()); gcry_md_close(ctx_md5); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #endif // USE_GNUTLS_NETTLE //------------------------------------------------------------------- // Utility Function for SHA256 //------------------------------------------------------------------- size_t get_sha256_digest_length(void) { return 32; } #ifdef USE_GNUTLS_NETTLE bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen) { (*digestlen) = static_cast<unsigned int>(get_sha256_digest_length()); if(NULL == ((*digest) = reinterpret_cast<unsigned char*>(malloc(*digestlen)))){ return false; } struct sha256_ctx ctx_sha256; sha256_init(&ctx_sha256); sha256_update(&ctx_sha256, datalen, data); sha256_digest(&ctx_sha256, *digestlen, *digest); return true; } unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size) { struct sha256_ctx ctx_sha256; unsigned char buf[512]; ssize_t bytes; unsigned char* result; // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); sha256_init(&ctx_sha256); for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); return NULL; } sha256_update(&ctx_sha256, bytes, buf); memset(buf, 0, 512); } if(NULL == (result = reinterpret_cast<unsigned char*>(malloc(get_sha256_digest_length())))){ return NULL; } sha256_digest(&ctx_sha256, get_sha256_digest_length(), result); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #else // USE_GNUTLS_NETTLE bool s3fs_sha256(const unsigned char* data, unsigned int datalen, unsigned char** digest, unsigned int* digestlen) { (*digestlen) = static_cast<unsigned int>(get_sha256_digest_length()); if(NULL == ((*digest) = reinterpret_cast<unsigned char*>(malloc(*digestlen)))){ return false; } gcry_md_hd_t ctx_sha256; gcry_error_t err; if(GPG_ERR_NO_ERROR != (err = gcry_md_open(&ctx_sha256, GCRY_MD_SHA256, 0))){ S3FS_PRN_ERR("SHA256 context creation failure: %s/%s", gcry_strsource(err), gcry_strerror(err)); free(*digest); return false; } gcry_md_write(ctx_sha256, data, datalen); memcpy(*digest, gcry_md_read(ctx_sha256, 0), *digestlen); gcry_md_close(ctx_sha256); return true; } unsigned char* s3fs_sha256hexsum(int fd, off_t start, ssize_t size) { gcry_md_hd_t ctx_sha256; gcry_error_t err; char buf[512]; ssize_t bytes; unsigned char* result; if(-1 == size){ struct stat st; if(-1 == fstat(fd, &st)){ return NULL; } size = static_cast<ssize_t>(st.st_size); } // seek to top of file. if(-1 == lseek(fd, start, SEEK_SET)){ return NULL; } memset(buf, 0, 512); if(GPG_ERR_NO_ERROR != (err = gcry_md_open(&ctx_sha256, GCRY_MD_SHA256, 0))){ S3FS_PRN_ERR("SHA256 context creation failure: %s/%s", gcry_strsource(err), gcry_strerror(err)); return NULL; } for(ssize_t total = 0; total < size; total += bytes){ bytes = 512 < (size - total) ? 512 : (size - total); bytes = read(fd, buf, bytes); if(0 == bytes){ // end of file break; }else if(-1 == bytes){ // error S3FS_PRN_ERR("file read error(%d)", errno); gcry_md_close(ctx_sha256); return NULL; } gcry_md_write(ctx_sha256, buf, bytes); memset(buf, 0, 512); } if(NULL == (result = reinterpret_cast<unsigned char*>(malloc(get_sha256_digest_length())))){ gcry_md_close(ctx_sha256); return NULL; } memcpy(result, gcry_md_read(ctx_sha256, 0), get_sha256_digest_length()); gcry_md_close(ctx_sha256); if(-1 == lseek(fd, start, SEEK_SET)){ free(result); return NULL; } return result; } #endif // USE_GNUTLS_NETTLE /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
25.984816
141
0.623508
murlock
1ac3058d16b421793ec151c81009155a4c5af3db
3,635
cpp
C++
HelperFunctions/getVkViewport.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkViewport.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkViewport.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Douglas Kaip * * 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. */ /* * getVkViewport.cpp * * Created on: Oct 24, 2019 * Author: Douglas Kaip */ #include "JVulkanHelperFunctions.hh" #include "slf4j.hh" namespace jvulkan { void getVkViewport( JNIEnv *env, jobject jVkViewportObject, VkViewport *vkViewport, std::vector<void *> *memoryToFree) { jclass vkViewportClass = env->GetObjectClass(jVkViewportObject); if (env->ExceptionOccurred()) { return; } //////////////////////////////////////////////////////////////////////// jmethodID methodId = env->GetMethodID(vkViewportClass, "getX", "()F"); if (env->ExceptionOccurred()) { return; } jfloat x = env->CallFloatMethod(jVkViewportObject, methodId); if (env->ExceptionOccurred()) { return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkViewportClass, "getY", "()F"); if (env->ExceptionOccurred()) { return; } jfloat y = env->CallFloatMethod(jVkViewportObject, methodId); if (env->ExceptionOccurred()) { return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkViewportClass, "getWidth", "()F"); if (env->ExceptionOccurred()) { return; } jfloat width = env->CallFloatMethod(jVkViewportObject, methodId); if (env->ExceptionOccurred()) { return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkViewportClass, "getHeight", "()F"); if (env->ExceptionOccurred()) { return; } jfloat height = env->CallFloatMethod(jVkViewportObject, methodId); if (env->ExceptionOccurred()) { return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkViewportClass, "getMinDepth", "()F"); if (env->ExceptionOccurred()) { return; } jfloat minDepth = env->CallFloatMethod(jVkViewportObject, methodId); if (env->ExceptionOccurred()) { return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkViewportClass, "getMaxDepth", "()F"); if (env->ExceptionOccurred()) { return; } jfloat maxDepth = env->CallFloatMethod(jVkViewportObject, methodId); if (env->ExceptionOccurred()) { return; } vkViewport->x = x; vkViewport->y = y; vkViewport->width = width; vkViewport->height = height; vkViewport->minDepth = minDepth; vkViewport->maxDepth = maxDepth; } }
28.849206
80
0.49381
dkaip
1ac8de29fd47019c64532e6ad97c5ff09145ce35
2,758
cpp
C++
src/engine/ResourceManager.cpp
Streetwalrus/WalrusRPG
53d88ef36ca1b2c169b5755dd95ac2c5626b91f5
[ "MIT" ]
12
2015-06-30T19:38:06.000Z
2017-11-27T20:26:32.000Z
src/engine/ResourceManager.cpp
Pokespire/pokespire
53d88ef36ca1b2c169b5755dd95ac2c5626b91f5
[ "MIT" ]
18
2015-06-26T01:44:48.000Z
2016-07-01T16:26:17.000Z
src/engine/ResourceManager.cpp
Pokespire/pokespire
53d88ef36ca1b2c169b5755dd95ac2c5626b91f5
[ "MIT" ]
1
2016-12-12T05:15:46.000Z
2016-12-12T05:15:46.000Z
#include "ResourceManager.h" #include "Logger.h" #include "TINYSTL/unordered_map.h" using namespace WalrusRPG; /*::ResourceManager*/ using namespace WalrusRPG::Logger; using WalrusRPG::PIAF::Archive; using tinystl::unordered_map; ManagedArchive::ManagedArchive(const char *path) : path(path), arc(ResourceManager::require(path)) { log("Resource Manager : +Ref %s", path); } ManagedArchive::~ManagedArchive() { log("Resource Manager : -Ref %s", path); ResourceManager::release(path); } ManagedArchive::operator Archive *() const { return arc; } namespace { struct node { Archive *arc; uint16_t refcount; }; unordered_map<const char *, node> files; } void ResourceManager::init() { } void ResourceManager::deinit() { // Pruning unloaded files and unloading files which are still open. for (auto ptr = files.begin(), end = files.end(); ptr != end; ++ptr) { if (ptr->second.refcount == 0) log("Resource Manager : Prune Node : %s", ptr->first); else { log("Resource Manager : Delete Node : %s", ptr->first); delete ptr->second.arc; } } files.clear(); } Archive *ResourceManager::require(const char *path) { auto entry = files.find(path); // Not found? Open the file. if (entry == files.end()) { log("Resource Manager : New : %s", path); return files.insert({path, {new Archive(path), 1}}).first->second.arc; } // Previously closed? Re-open it. if (entry->second.refcount == 0) { log("Resource Manager : Reload : %s", path); entry->second.arc = new Archive(path); } ++entry->second.refcount; return entry->second.arc; } void ResourceManager::release(WalrusRPG::PIAF::Archive *arcs) { for (auto ptr = files.begin(), end = files.end(); ptr != end; ++ptr) { if (ptr->second.arc == arcs) { // Decreasing the refcount. Basic but effective. --ptr->second.refcount; if (ptr->second.refcount == 0) { log("Resource Manager : Free : %s", ptr->first); delete ptr->second.arc; ptr->second.refcount = 0; } return; } } } void ResourceManager::release(const char *path) { auto ptr = files.find(path); if (ptr == files.end()) return; // I actually enjoy the way this unordered_map is programmed. // I would just have loved is there would be an operator[] const. --ptr->second.refcount; if (ptr->second.refcount == 0) { log("Resource Manager : Free : %s", ptr->first); delete ptr->second.arc; ptr->second.refcount = 0; } return; }
24.846847
78
0.583394
Streetwalrus
1acbc5948aad29f5472ffbf503bd45f1ab1d0d8f
1,386
cpp
C++
test/DiGraph_Test.cpp
CalebCintary/pyplot_cpp
de33c3e921229e5efd72a7fc4fdb17212edc9aa9
[ "MIT" ]
1
2022-03-29T10:52:21.000Z
2022-03-29T10:52:21.000Z
test/DiGraph_Test.cpp
CalebCintary/pyplot_cpp
de33c3e921229e5efd72a7fc4fdb17212edc9aa9
[ "MIT" ]
1
2022-03-20T12:17:11.000Z
2022-03-20T17:50:12.000Z
test/DiGraph_Test.cpp
CalebCintary/pyplot_cpp
de33c3e921229e5efd72a7fc4fdb17212edc9aa9
[ "MIT" ]
1
2022-03-29T19:40:59.000Z
2022-03-29T19:40:59.000Z
// // Created by lavr4 on 3/24/2022. // #include <boost/test/unit_test.hpp> #include "pyplot_cpp/DiGraph.hpp" #include "pyplot_cpp/plt/Properties.hpp" BOOST_AUTO_TEST_SUITE(DiGraph_Test) BOOST_AUTO_TEST_CASE(DiGraph_EmptyShow_Test) { pyplot_cpp::DiGraph graph; graph.setTitle("Simple DiGraph"); graph.show(); } BOOST_AUTO_TEST_CASE(DiGraph_SimpleShow_Test) { pyplot_cpp::DiGraph graph; graph.addEdge("1", "2"); graph.setTitle("Simple DiGraph"); graph.show(); } BOOST_AUTO_TEST_CASE(DiGraph_SimpleSave_Test) { pyplot_cpp::DiGraph graph; graph.addEdge("1", "2"); graph.setTitle("Simple DiGraph"); graph.save("../../examples/DiGraph_Simple.png"); } BOOST_AUTO_TEST_CASE(DiGraph_Weighted_SimpleShow_Test) { pyplot_cpp::DiGraph graph; graph.addEdge("1", "2"); graph.addEdge("1", "3", "3"); graph.addEdge("2", "3", "5"); graph.setTitle("Simple DiGraph"); graph.show(); } BOOST_AUTO_TEST_CASE(DiGraph_Weighted_SimpleSave_Test) { pyplot_cpp::DiGraph graph; graph.addEdge("1", "2"); graph.addEdge("1", "3", "3"); graph.addEdge("2", "3", "5"); graph.setTitle("Simple DiGraph"); graph.save("../../examples/DiGraph_Weighted.png"); } BOOST_AUTO_TEST_SUITE_END()
25.2
60
0.616162
CalebCintary
1ad06d3ed55c91b0db13ee06513842e51f7b98e5
110
cpp
C++
src/intersim/rng_wrapper.cpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
src/intersim/rng_wrapper.cpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
src/intersim/rng_wrapper.cpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
#include "rng.hpp" #define main rng_main #include "rng.cpp" long ran_next( ) { return ran_arr_next( ); }
11
26
0.672727
beneslami
1adcb4ad1a2f42160dc3d3f7718d3c348b219861
1,122
cpp
C++
LeetCode Problem-Set/56. Merge Intervals (Medium)/Solution1.cpp
ankuralld5999/LeetCode-Problems
2f9a767a0effbb2a50672e102925fbbb65034083
[ "FSFAP" ]
2
2021-01-06T20:43:59.000Z
2021-01-11T15:42:59.000Z
LeetCode Problem-Set/56. Merge Intervals (Medium)/Solution1.cpp
ankuralld5999/LeetCode-Problems
2f9a767a0effbb2a50672e102925fbbb65034083
[ "FSFAP" ]
null
null
null
LeetCode Problem-Set/56. Merge Intervals (Medium)/Solution1.cpp
ankuralld5999/LeetCode-Problems
2f9a767a0effbb2a50672e102925fbbb65034083
[ "FSFAP" ]
null
null
null
// Problem: https://leetcode.com/problems/merge-intervals/ // Author: https://github.com/ankuralld5999 class Solution { public: vector<int> makeInterval(int intervalStart, int intervalEnd) { vector<int> interval(2); interval[0] = intervalStart; interval[1] = intervalEnd; return interval; } vector<vector<int>> merge(vector<vector<int>>& intervals) { vector<vector<int>> ans; if(intervals.empty()) return ans; sort(intervals.begin(), intervals.end()); int intervalStart = intervals[0][0], intervalEnd = intervals[0][1]; for(int i = 1; i < intervals.size(); i++) { if(intervals[i][0] >= intervalStart && intervals[i][0] <= intervalEnd) { intervalEnd = max(intervalEnd, intervals[i][1]); } else{ ans.push_back(makeInterval(intervalStart, intervalEnd)); intervalStart = intervals[i][0]; intervalEnd = intervals[i][1]; } } ans.push_back(makeInterval(intervalStart, intervalEnd)); return ans; } };
36.193548
84
0.579323
ankuralld5999
1addf6ac93a6f89a5e138fed5f8bdad2a478715f
1,354
cpp
C++
Strings/23. AnagramSearch.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
2
2021-05-21T17:10:02.000Z
2021-05-29T05:13:06.000Z
Strings/23. AnagramSearch.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
Strings/23. AnagramSearch.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; const int CHAR = 256; bool areAnagram(string &pat, string &txt, int i) { int count[CHAR] = {0}; for (int j = 0; j < pat.length(); j++) { count[pat[j]]++; count[txt[i + j]]--; } for (int j = 0; j < CHAR; j++) { if (count[j] != 0) return false; } return true; } bool isPresent(string &txt, string &pat) { int n = txt.length(); int m = pat.length(); for (int i = 0; i <= n - m; i++) { if (areAnagram(pat, txt, i)) return true; } return false; } bool areSame(int CT[], int CP[]) { for (int i = 0; i < CHAR; i++) if (CT[i] != CP[i]) return false; return true; } bool isPresentOP(string &txt, string &pat) { int CT[CHAR] = {0}, CP[CHAR] = {0}; for (int i = 0; i < pat.length(); i++) { CT[txt[i]]++; CP[pat[i]]++; } for (int i = pat.length(); i < txt.length(); i++) { if (areSame(CT, CP)) return true; // * Sliding Window Technique CT[txt[i]]++; CT[txt[i - pat.length()]]--; } return false; } int main() { string txt = "geeksforgeeks"; string pat = "frog"; cout << isPresent(txt, pat) << endl; cout << isPresentOP(txt, pat) << endl; return 0; }
19.623188
53
0.477105
sohamnandi77
1adfb03a9dbb41d74401b4f83a296f94ad9297ea
3,040
cpp
C++
temp-sensor.cpp
ThomasZehnder/low-noise-heating-arduino-2021
015e204b7e00fa49f123bd199dd9a256188788ce
[ "MIT" ]
null
null
null
temp-sensor.cpp
ThomasZehnder/low-noise-heating-arduino-2021
015e204b7e00fa49f123bd199dd9a256188788ce
[ "MIT" ]
3
2020-10-18T17:04:21.000Z
2020-10-18T17:08:19.000Z
temp-sensor.cpp
ThomasZehnder/low-noise-heating-arduino-2021
015e204b7e00fa49f123bd199dd9a256188788ce
[ "MIT" ]
null
null
null
// Include the libraries we need #include "Arduino.h" #include "temp-sensor.hpp" #include "Wire.h" #include "OneWire.h" #include "low-noise-heater-defines.hpp" OneWire ds(DS18B20_PIN); // maximum sensors on the bus #define M 4 // actual sensors detected byte m = 0; // addresses byte addr[M][8]; //temp for asynchronous reading float temp[M]; //local prototypes void show_id(byte m); void setup_tempsense() { m = 0; while (ds.search(addr[m])) { Serial.print("Found address "); Serial.print(m, DEC); Serial.print(": "); show_id(m); Serial.println(); if (OneWire::crc8(addr[m], 7) != addr[m][7]) { Serial.println("CRC is not valid!"); return; } if (addr[m][0] != 0x28) { Serial.println("Device is not a DS18B20 family device."); return; } m++; } Serial.println("No more addresses."); ds.reset_search(); } void show_id(byte m) { for (byte i = 6; i >= 1; i--) { Serial.print(addr[m][i] >> 4, HEX); Serial.print(addr[m][i] & 15, HEX); } } // asynchronous start conversion int start_conversion(byte i) { // The DallasTemperature library can do all this work for you! ds.reset(); ds.select(addr[i]); ds.write(0x44); // start conversion, with parasite power on at the end } // asynchronous read result int read_conversion_result(byte i) { byte present = ds.reset(); ds.select(addr[i]); ds.write(0xBE); // Read Scratchpad byte data[9]; for (byte i = 0; i < 9; i++) // we need 9 bytes { data[i] = ds.read(); } int temp = (data[1] << 8) | data[0]; // just want temperature return temp; } void tempSensorSetup(void) { // start serial port Serial.println("Dallas Temperature IC Control Library Demo"); setup_tempsense(); for (byte i = 0; i < M; i++) { temp[i] = 0.0; } } float getTemp(char index) { return temp[index]; } /* Main function, calls the temperatures in a loop. */ int counter = 0; int oldTime, actTime; bool tempSensorLoop(void) { //Call every 500ms actTime = millis(); if (actTime - oldTime > 0) { oldTime = actTime + 500; // read all the results for (byte i = 0; i < m; i++) { int t = read_conversion_result(i); float centigrade = ((float)t) * 0.0625; temp[i] = centigrade; } // start all the conversions for (byte i = 0; i < m; i++) { start_conversion(i); } return true; } return false; } void serialOutTemperatureDev(void) { counter++; Serial.println(counter); // read all the results for (byte i = 0; i < m; i++) { Serial.print("dev "); show_id(i); Serial.print(": "); Serial.print(temp[i]); Serial.println("ยฐC"); } Serial.println(); } void serialOutTemperatureCsv(void) { counter++; Serial.print(counter); Serial.print(";"); Serial.print(millis()/1000.0); // read all the results for (byte i = 0; i < m; i++) { Serial.print(";"); show_id(i); Serial.print(";"); Serial.print(temp[i]); } Serial.println(); }
16.888889
72
0.596053
ThomasZehnder
1ae1a653fc768b1331201778daa42c02471ea6c7
499
cpp
C++
CoreTests/Script/Test_ScriptScalarMath.cpp
azhirnov/GraphicsGenFramework-modular
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
12
2017-12-23T14:24:57.000Z
2020-10-02T19:52:12.000Z
CoreTests/Script/Test_ScriptScalarMath.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
CoreTests/Script/Test_ScriptScalarMath.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #include "CoreTests/Script/Common.h" static void TestScalar_Sin (ScriptEngine *se) { const char script[] = R"#( float main () { float f = Sin( 3.14f ); return f; } )#"; float res = 0; se->Run( script, "main", OUT res ); const float ref = Sin( 3.14_rad); TEST( res == ref ); } extern void Test_ScriptScalarMath () { ScriptEngine se; DefaultBindings::BindScalarMath( &se ); TestScalar_Sin( &se ); }
15.59375
72
0.643287
azhirnov
1ae32440010aab2a940f83ebcd7073fd7420d027
24,854
cpp
C++
Picfeature/Pic.cpp
akamoon/imageLab
7a15ec725b56da7e458805495695c12a95d717a1
[ "MIT" ]
null
null
null
Picfeature/Pic.cpp
akamoon/imageLab
7a15ec725b56da7e458805495695c12a95d717a1
[ "MIT" ]
null
null
null
Picfeature/Pic.cpp
akamoon/imageLab
7a15ec725b56da7e458805495695c12a95d717a1
[ "MIT" ]
null
null
null
๏ปฟ//#include <QCoreApplication> #include "include1\linear.h" #include "include1\pic.h" #include "direct.h" #include "include1\charactercut.h" #include "include1\imagecrop.h" #include "include1\backnotes.h" //-----------ๆš‚ๆ—ถไธ็Ÿฅ้“็”จๅค„็š„ๅ˜้‡ๅฎšไน‰๏ผŒๅ…ˆไฟ็•™ไธ้‡ๆž„--------------- unsigned char *image2; unsigned char *image3; unsigned char *image4; int *countlines(); int *m; unsigned short upActualSize[2] = {0}, downActualSize[2] = {0}; #pragma DATA_ALIGN (g_line_POINT1,4) //ๅ››ๅญ—่Š‚่พน็•Œๅฏน้ฝ๏ผŒไพฟไบŽๆ้ซ˜ๅค„็†ๆ•ˆ็އ POINT1 g_line_POINT1[8][2]={0}; //ไฟๅญ˜ไธŠไธ‹็ฎก็บธๅธไธŠใ€ไธ‹ใ€ๅทฆใ€ๅณ่พน็•Œ็บฟไธŠๅ„ๆ‰พๅ‡บ็š„2ไธช็‚น int k_up1; volatile unsigned int errorTag; unsigned short moneyLength; unsigned short moneyHeight; volatile int g_angle;//็บธๅธๅ่ฝฌ่ง’ๅบฆ //-----------ๆš‚ๆ—ถไธ็Ÿฅ้“็”จๅค„็š„ๅ˜้‡ๅฎšไน‰๏ผŒๅ…ˆไฟ็•™ไธ้‡ๆž„--------------- /* ๅทฒ้‡ๆž„๏ผš 1.image2,image3 ๅ˜้‡ๅ้‡ๆ–ฐๅฎšไน‰ไธบimage_input๏ผŒimageOutput 2.image123 ๅ˜้‡ๅ้‡ๆ–ฐๅฎšไน‰ไธบ๏ผšimageOriginal 3.gray_image1 ๅ˜้‡ๅ้‡ๆ–ฐๅฎšไน‰ไธบ๏ผšimage_gray 4.ๅ‡ฝๆ•ฐ่ฟ”ๅ›žๅ€ผไฝฟ็”จ funReuslt ็ปŸไธ€ๅญ˜ๅ‚จ 5.็ฐ้˜ถๅ›พ่ฝฌๆขๅ‡ฝๆ•ฐ 6.switch้ƒจๅˆ†็š„้‡ๆž„ 7.ๅฐ†ๅ†™ๅœจ็จ‹ๅบๆฎตๅ†…็š„ๅธธ้‡ๆๅ–ๅˆฐ็จ‹ๅบๆฎตๅผ€ๅคด */ //็”จไบŽ่ฏ†ๅˆซ็บธๅธๆ˜ฏๅคงๅคดๆˆ–่€…ๅฐๅคดๆ—ถ็š„ๅ‚ๆ•ฐ static const unsigned short PARAMETER_BIG_SMALL[4][4]= { {1200,7500,4500,6800} ,//T1 {1700, 2800, 7000, 9600}, {3200,6000,8000,8700}, {4000,6000,3000,8700}, }; //็”จไบŽ่ฏ†ๅˆซๅคงๅคด็บธๅธ้ขๅ€ผ็š„ๅ‚ๆ•ฐ static const unsigned short PARAMETER_BIG_DENOMI[12][4]= {//6900, 9100, 1100,1800 {3500, 5700, 800, 1400}, //T1ๅˆคๆ–ญๆ–ฐๆ—ง {1690, 2850, 7100, 9600}, //T2 {1700, 2860, 7100, 9600}, //ๆ—ง็‰ˆ10๏ผŒ20 {1900, 3100, 7050, 9550},//ๆ—ง็‰ˆ 100 {2000, 3250, 7200, 9600},//ๆ–ฐ็‰ˆ 100 {6000, 7200, 1100, 3700},//ๆ–ฐ็‰ˆ20 {1100,8800,4400,7200},//ๅคดๅƒ {1900, 2900, 6900, 9400}, //ๆ–ฐ็‰ˆ50 {1800, 2860, 7000, 9500}, //ๆ—ง็‰ˆ50 {1700, 2850, 7000, 9500}, //ๆ–ฐ็‰ˆ5 {1700, 2800, 7000, 9500}, //ๆ—ง็‰ˆ5 {6000, 7200, 1500, 3900}, //ๆ–ฐ็‰ˆ10 }; //็”จไบŽ่ฏ†ๅˆซๅฐๅคด็บธๅธ้ขๅ€ผ็š„ๅ‚ๆ•ฐ static const unsigned short PARAMETER_SMALL_DENOMI[5][4]= { {6000, 7100, 6300, 8600}, //ๅฐๅคด1็พŽๅ…ƒ {2550, 3750, 1610, 3900}, //ๅฐๅคด5็พŽๅ…ƒ {6100, 7300, 6300, 8600}, //ๅฐๅคด10็พŽๅ…ƒ {5800, 7000, 6100, 8400}, //ๅฐๅคด20็พŽๅ…ƒ {2400,8000,4000,6000} }; /***************************************************************** * ๅ‡ฝๆ•ฐๅ: ToGray * ๅŠŸ่ƒฝๆ่ฟฐ: ๅฐ†ๅŽŸๅ›พไธญ็š„ๅ›พๅƒ่ฝฌไธบ็ฐ้˜ถ๏ผŒๅนถๅฐ†ๅƒ็ด ็‚นๆ•ฐๆฎ่พ“ๅ‡บๅˆฐๆŒ‡ๅฎšๆ•ฐ็ป„ไธญ ๆ นๆฎ้œ€ๆฑ‚ๅฏน็ฐ้˜ถๅ›พๅƒ่ฟ›่กŒไฟๅญ˜ * ๅฝขๅผๅ‚ๆ•ฐ: Mat image_orignial๏ผš ไฝฟ็”จOpenCVๅฎนๆ˜“่ฏปๅ–็š„ๅŽŸๅ›พๆ•ฐๆฎ unsigned char* imagePixelStore๏ผš ๅญ˜ๅ‚จ็š„ๅ›พๅƒ็ฐ้˜ถๅƒ็ด ็š„ๆ•ฐ็ป„ int isSave: ๆ˜ฏๅฆไฟๅญ˜ๅ›พๅƒ char* fileName: ไฟๅญ˜ๅ›พๅƒ็š„ๆ–‡ไปถๅ * ่ฟ”ๅ›žๅ€ผ๏ผš ๆ—  *------------------------------------------------------------------ * V1.0 2018/05/07 FX ******************************************************************/ void ToGray(Mat imageOriginal, unsigned char* imagePixelStore, int isSave, char* fileName) { Mat imageGray;//openCVๅ›พๅƒๅฎนๅ™จ๏ผŒ็”จๆฅๅญ˜ๅ‚จ่ฝฌไธบ็ฐ้˜ถ็š„ๅ›พๅƒ cvtColor( imageOriginal, imageGray, CV_BGR2GRAY); if(isSave && fileName != NULL) imwrite(fileName, imageGray); int k=0; for(int i=0;i<400;i++) { for(int j=0;j<1440;j++) { imagePixelStore[k]=imageGray.at<uchar>(i,j); k++; } } } /***************************************************************** * ๅ‡ฝๆ•ฐๅ: recDenomination * ๅŠŸ่ƒฝๆ่ฟฐ: ๆˆชๅ–ๅ›พๅƒ็š„ๅธๅ€ผ็‰นๅพๅนถ่พ“ๅ‡บๆ˜ฏๅคšๅฐ‘้’ฑ * ๅฝขๅผๅ‚ๆ•ฐ: unsigned char *imageUpside ๏ผš ๅ›พๅƒๆญฃ้ขๅƒ็ด ๆ•ฐๆฎ unsigned char *imageDownside ๏ผš ๅ›พๅƒ่ƒŒ้ขๅƒ็ด ๆ•ฐๆฎ unsigned char *imageOutput ๏ผš ็”จไบŽๅญ˜ๅ‚จๆˆชๅ–ๅ›พๅƒๆ•ฐๆฎ็š„ๅญ˜ๅ‚จ็ฉบ้—ด int denomination ๏ผš ๅธๅ€ผๅคงๅฐ int paraIndex4New ๏ผš ๅฏนไบŽๆ–ฐ็‰ˆ้’ฑๅธๅบ”่ฏฅ้€‰ๅ–็š„ๅ‚ๆ•ฐๅบๅท int paraIndex4Old ๏ผš ๅฏนไบŽ่€ๆฟ้’ฑๅธๅบ”่ฏฅ้€‰ๅ–็š„ๅ‚ๆ•ฐๅบๅท int chan4New ๏ผš ๅฏนไบŽๆ–ฐ็‰ˆ้’ฑๅธๅฏนๅบ”ๅธๅ€ผๆˆชๅ–ๅ›พๅƒๆ—ถไฝฟ็”จ็š„ๆ ‡่ฏ† int chan4Old ๏ผš ๅฏนไบŽ่€็‰ˆ้’ฑๅธๅฏนๅบ”ๅธๅ€ผๆˆชๅ–ๅ›พๅƒๆ—ถไฝฟ็”จ็š„ๆ ‡่ฏ† * ่ฟ”ๅ›žๅ€ผ๏ผš ๆ—  *------------------------------------------------------------------ * V1.0 2018/05/07 FX ******************************************************************/ void recDenomination( unsigned char *imageUpside, unsigned char *imageDownside, unsigned char *imageOutput, int denomination, int paraIndex4New, int paraIndex4Old, int chan4New, int chan4Old) { int funReuslt = 0; funReuslt =LinearFitting(imageDownside,99.5,396,0); funReuslt=ImageCrop(imageDownside,PARAMETER_BIG_DENOMI[0],imageOutput,0,1); if(funReuslt>600) { funReuslt =LinearFitting(imageUpside,99.5,396,0); funReuslt=ImageCrop( imageUpside, PARAMETER_BIG_DENOMI[paraIndex4New], imageOutput, 0,chan4New); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ%d็พŽๅ…ƒ\n", denomination); } else { funReuslt =LinearFitting(imageUpside,99.5,396,0); funReuslt=ImageCrop(imageUpside, PARAMETER_BIG_DENOMI[paraIndex4Old], imageOutput, 0,chan4Old); printf("่ฟ™ๆ˜ฏ่€ๆฟ%d็พŽๅ…ƒ\n", denomination); } } /***************************************************************** * ๅ‡ฝๆ•ฐๅ: Pic * ๅŠŸ่ƒฝๆ่ฟฐ: ้€š่ฟ‡็‰นๅพ้€‰ๅ–๏ผŒๆˆชๅ–ๅ›พๅƒ็š„ๆ–นๅผๅˆคๆ–ญๅธๅ€ผ * ๅฝขๅผๅ‚ๆ•ฐ: chan๏ผš ๆ ‡่ฏ†่ฟ™ไธชๅ›พๅƒๆ—ถ็บธๅธ็š„ๆญฃ้ข่ฟ˜ๆ˜ฏๅ้ข * ่ฟ”ๅ›žๅ€ผ๏ผš intๅž‹ -1๏ผš ่ฏ†ๅˆซๅคฑ่ดฅ 0๏ผš ่ฏ†ๅˆซๆˆๅŠŸ *------------------------------------------------------------------ * V1.0 20??/??/?? ?? ******************************************************************/ int Pic(int chan) { _chdir(trainPath); //**001***ๅฎšไน‰ๅนถ็”ณ่ฏทๅ›พๅƒๅƒ็ด ็š„ๅญ˜ๅ‚จ็ฉบ้—ด********** unsigned char *imageInputUpside;//็”จไบŽไฟๅญ˜ไปŽๆ–‡ไปถ้‡Œ่ฏปๅ…ฅ็บธๅธๆญฃ้ข็š„ๅ›พๅƒ็š„ๅƒ็ด ็‚น unsigned char *imageInputDonwside;//็”จไบŽไฟๅญ˜ไปŽๆ–‡ไปถ้‡Œ่ฏปๅ…ฅ็š„็บธๅธ่ƒŒ้ข็š„ๅ›พๅƒ็š„ๅƒ็ด ็‚น unsigned char *imageOutput;//็”จไบŽๆŽฅๆ”ถimagecropๅ‡ฝๆ•ฐ็š„่พ“ๅ‡บ็š„ๅ›พๅƒ็š„ๅƒ็ด ็‚น imageInputUpside = new unsigned char[1440 * 400]; imageInputDonwside = new unsigned char[1440 * 400]; imageOutput = new unsigned char[1440 * 400]; //image2= new unsigned char [1440*400]; //image3= new unsigned char [1440*400]; //**001************************************** //***002***ๅฎšไน‰OpenCVๅ›พๅƒๅฎนๅ™จ********** //Mat image123; Mat imageOriginal;//openCVๅ›พๅƒๅฎนๅ™จ๏ผŒ็”จๆฅๆŽฅๆ”ถไปŽๆ–‡ไปถไธญ่ฏปๅ…ฅ็š„ๅ›พๅƒ //Mat gray_image1; //Mat imageGray;//openCVๅ›พๅƒๅฎนๅ™จ๏ผŒ็”จๆฅๅญ˜ๅ‚จ่ฝฌไธบ็ฐ้˜ถ็š„ๅ›พๅƒ //***002****************************** //Debug information //printf("................start\n"); //***003***ๅฐ†็บธๅธๅ›พๅƒ็š„ๆญฃ้ขๆ•ฐๆฎๅนถ่ฝฌไธบ็ฐ้˜ถ๏ผŒๅญ˜ๅ‚จ*************** imageOriginal = imread("currency_img.bmp",CV_LOAD_IMAGE_COLOR); //image123=imread("currency_img.bmp",CV_LOAD_IMAGE_COLOR); //unsigned char *image2;//**้‡ๅคไบ†ๅ‰้ข็š„image2 //image2= new unsigned char [1440*400]; /* //----005----็ฎ€ๅŒ–ไธบToGgrayๅ‡ฝๆ•ฐ--------------------- cvtColor( imageOriginal, imageGray, CV_BGR2GRAY); //cvtColor( image123, gray_image1, CV_BGR2GRAY ); imwrite("Gray_Image.bmp", imageGray); //imwrite("Gray_Image.bmp", gray_image1); //---2--ๆŠŠ็ฐ้˜ถๅ›พ็š„ๅƒ็ด ็‚น่ฏปๅ…ฅๆ•ฐ็ป„image_input------------------- int k=0; for(int i=0;i<400;i++) { for(int j=0;j<1440;j++) { imageInputUpside[k]=imageGray.at<uchar>(i,j); k++; } } //---2------------------------------------------------- //----005----็ฎ€ๅŒ–ไธบToGgrayๅ‡ฝๆ•ฐ--------------------- */ ToGray(imageOriginal, imageInputUpside, 0, 0); //***003************************************** int funReuslt = 0; //็”จๆฅๅญ˜ๅ‚จๅ‡ฝๆ•ฐ่ฟ”ๅ›ž็š„็ป“ๆžœ //----------ๆ‰ง่กŒๆœ€ๅผ€ๅง‹่ดงๅธๅคงๅฐๅคด็š„็‰นๅพ่ฃๅ‰ชๅ’Œ่ฏ†ๅˆซ--------6---- //int temp =LinearFitting(image_input,99.5,396,0); funReuslt = LinearFitting(imageInputUpside,99.5,396,0); /* unsigned short parameters_Dollar[4][4]= { {1200,7500,4500,6800} ,//T1 {1700, 2800, 7000, 9600}, {3200,6000,8000,8700}, {4000,6000,3000,8700}, }; */ //ๆ‰ง่กŒ่ดงๅธๅคงๅฐๅคด็š„่ฏ†ๅˆซ funReuslt = ImageCrop(imageInputUpside,PARAMETER_BIG_SMALL[2],imageOutput,0,0); //int temp5=ImageCrop(imageInputUpside,parameters_Dollar[2],imageOutput,0,0); //-----------------------------------------------------6--- //Debug Info //printf("\ntemp5=%d\n",temp5); // system("pause"); //if(temp5>1000) //ๅˆคๆ–ญ็บธๅธๆ˜ฏๅคงๅคด่ฟ˜ๆ˜ฏๅฐๅคด๏ผŒๅนถๆ นๆฎๅคงๅฐๅคด้€‰ๅ–ไธๅŒ็š„็‰นๅพๆˆชๅ–ๅ‚ๆ•ฐ if(funReuslt > 1000) { if(chan==0) { /* //----005----็ฎ€ๅŒ–ไธบToGgrayๅ‡ฝๆ•ฐ--------------------- //---3-้‡ๆ–ฐ่ฏปๅฆไธ€ๅผ ๅ›พcurrency_img1.bmp,็„ถๅŽ่ฝฌๆˆ็ฐ้˜ถ------ image123=imread("currency_img1.bmp",CV_LOAD_IMAGE_COLOR); unsigned char *image1; image1= new unsigned char [1440*400]; cvtColor( image123, gray_image1, CV_BGR2GRAY ); imwrite("Gray_Image1.bmp", gray_image1); int k=0; //---3-------------------------------------- //---4-ๆŠŠ็ฐ้˜ถๅ›พไผ ๅ…ฅimage1ๆ•ฐ็ป„------------------ for(int i=0;i<400;i++) { for(int j=0;j<1440;j++) { image1[k]=gray_image1.at<uchar>(i,j); k++; } } //---4-------------------------------------- //----005----็ฎ€ๅŒ–ไธบToGgrayๅ‡ฝๆ•ฐ--------------------- */ //่ฏปๅ–็บธๅธ็š„่ƒŒ้ขๆ•ฐๆฎ๏ผŒๅนถ่ฝฌไธบ็ฐ้˜ถ imageOriginal = imread("currency_img1.bmp",CV_LOAD_IMAGE_COLOR); ToGray(imageOriginal, imageInputDonwside, 0, 0); //int temp =LinearFitting(image2,99.5,396,0);//้‡ๅคๆ‰ง่กŒ /* unsigned short parameters_Dollar[12][4]= {//6900, 9100, 1100,1800 {3500, 5700, 800, 1400}, //T1ๅˆคๆ–ญๆ–ฐๆ—ง {1690, 2850, 7100, 9600}, //T2 {1700, 2860, 7100, 9600}, //ๆ—ง็‰ˆ10๏ผŒ20 {1900, 3100, 7050, 9550},//ๆ—ง็‰ˆ 100 {2000, 3250, 7200, 9600},//ๆ–ฐ็‰ˆ 100 {6000, 7200, 1100, 3700},//ๆ–ฐ็‰ˆ20 {1100,8800,4400,7200},//ๅคดๅƒ {1900, 2900, 6900, 9400}, //ๆ–ฐ็‰ˆ50 {1800, 2860, 7000, 9500}, //ๆ—ง็‰ˆ50 {1700, 2850, 7000, 9500}, //ๆ–ฐ็‰ˆ5 {1700, 2800, 7000, 9500}, //ๆ—ง็‰ˆ5 {6000, 7200, 1500, 3900}, //ๆ–ฐ็‰ˆ10 }; */ //ๆ นๆฎๅคงๅคด้’ฑๅธ็š„็‰นๅพๅ‚ๆ•ฐ๏ผŒๅˆคๆ–ญ่ฏฅๅคงๅคด้’ฑๅธ็š„ๅธๅ€ผ //int temp1=ImageCrop(image2,parameters_Dollar[6],image3,0,8); funReuslt = ImageCrop( imageInputUpside, PARAMETER_BIG_DENOMI[6], imageOutput, 0,8); //int temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9,temp10,temp11,temp12,temp13,temp14,temp15,temp16,temp17,temp18,temp19,temp20,temp21; //switch(temp1) //ๆ นๆฎไธๅŒ็š„็ป“ๆžœ่พ“ๅ‡บไธๅŒ็š„ๅธๅ€ผ๏ผŒๅนถไธ”ๆˆชๅ–ไธๅŒ็š„็‰นๅพ switch(funReuslt) { case 0: case 5: recDenomination( imageInputUpside, imageInputDonwside, imageOutput, 5, 9,10, 5,6); break; /* printf("่ฟ™ๆ˜ฏ5็พŽๅ…ƒ\n"); temp2 =LinearFitting(image1,99.5,396,0); temp3=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp3>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[9],image3,0,5); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ5็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[10],image3,0,6); printf("่ฟ™ๆ˜ฏ่€ๆฟ5็พŽๅ…ƒ\n"); } break; */ case 1: case 7: recDenomination( imageInputUpside, imageInputDonwside, imageOutput, 10, 11,2, 10,11); break; /* temp4 =LinearFitting(image1,99.5,396,0); temp5=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp5>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[11],image3,0,10); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ10็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[2],image3,0,11); printf("่ฟ™ๆ˜ฏ่€ๆฟ10็พŽๅ…ƒ\n"); } break; */ case 2: case 8: recDenomination( imageInputUpside, imageInputDonwside, imageOutput, 20, 5,2, 20,21); break; /* temp6 =LinearFitting(image1,99.5,396,0); temp7=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp7>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[5],image3,0,20); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ20็พŽๅ…ƒ\n"); } else { temp6 =LinearFitting(image2,99.5,396,0); temp7=ImageCrop(image2,parameters_Dollar[2],image3,0,21); printf("่ฟ™ๆ˜ฏ่€ๆฟ20็พŽๅ…ƒ\n"); } break; */ case 3: case 6: recDenomination( imageInputUpside, imageInputDonwside, imageOutput, 50, 7,8, 50,51); break; /* temp8 =LinearFitting(image1,99.5,396,0); temp9=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp9>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[7],image3,0,50); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ50็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[8],image3,0,51); printf("่ฟ™ๆ˜ฏ่€ๆฟ50็พŽๅ…ƒ\n"); } break; */ case 4: case 9: recDenomination( imageInputUpside, imageInputDonwside, imageOutput, 100, 4,3, 100,101); break; /* temp10 =LinearFitting(image1,99.5,396,0); temp11=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp11>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[4],image3,0,100); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ100็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[3],image3,0,101); printf("่ฟ™ๆ˜ฏ่€ๆฟ100็พŽๅ…ƒ\n"); } break; */ /*---------ๆŽฅไธ‹ๆฅ้‡ๅคไบ†----------------- case 5: temp12 =LinearFitting(image1,99.5,396,0); temp13=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp13>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[9],image3,0,5); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ5็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[10],image3,0,6); printf("่ฟ™ๆ˜ฏ่€ๆฟ5็พŽๅ…ƒ\n"); } break; case 6: temp14 =LinearFitting(image1,99.5,396,0); temp15=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp15>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[7],image3,0,50); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ50็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[8],image3,0,51); printf("่ฟ™ๆ˜ฏ่€ๆฟ50็พŽๅ…ƒ\n"); } break; case 7: temp16 =LinearFitting(image1,99.5,396,0); temp17=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp17>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[11],image3,0,10); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ10็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[2],image3,0,11); printf("่ฟ™ๆ˜ฏ่€ๆฟ10็พŽๅ…ƒ\n"); } break; case 8: temp18 =LinearFitting(image1,99.5,396,0); temp19=ImageCrop(image1,parameters_Dollar[0],image3,0,20); if(temp19>600) { temp6 =LinearFitting(image2,99.5,396,0); temp7=ImageCrop(image2,parameters_Dollar[5],image3,0,20); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ20็พŽๅ…ƒ\n"); } else { temp6 =LinearFitting(image2,99.5,396,0); temp7=ImageCrop(image2,parameters_Dollar[2],image3,0,21); printf("่ฟ™ๆ˜ฏ่€ๆฟ20็พŽๅ…ƒ\n"); } break; case 9: temp20 =LinearFitting(image1,99.5,396,0); temp21=ImageCrop(image1,parameters_Dollar[0],image3,0,1); if(temp21>600) { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[4],image3,0,100); printf("่ฟ™ๆ˜ฏๆ–ฐ็‰ˆ100็พŽๅ…ƒ\n"); } else { temp4 =LinearFitting(image2,99.5,396,0); temp5=ImageCrop(image2,parameters_Dollar[3],image3,0,101); printf("่ฟ™ๆ˜ฏ่€ๆฟ100็พŽๅ…ƒ\n"); } break; */ } } } else { funReuslt =LinearFitting(imageInputUpside,99.5,396,0); /* unsigned short parameters_Dollar[5][4]= { {6000, 7100, 6300, 8600}, //ๅฐๅคด1็พŽๅ…ƒ {2550, 3750, 1610, 3900}, //ๅฐๅคด5็พŽๅ…ƒ {6100, 7300, 6300, 8600}, //ๅฐๅคด10็พŽๅ…ƒ {5800, 7000, 6100, 8400}, //ๅฐๅคด20็พŽๅ…ƒ {2400,8000,4000,6000} }; */ funReuslt =ImageCrop(imageInputUpside,PARAMETER_SMALL_DENOMI[4],imageOutput,0,9); switch(funReuslt) { case 0: funReuslt = LinearFitting(imageInputUpside,99.5,396,0); funReuslt =ImageCrop(imageInputUpside,PARAMETER_SMALL_DENOMI[2],imageOutput,0,2); printf("่ฟ™ๆ˜ฏๅฐๅคด1ๅ—\n"); break; case 1: funReuslt = LinearFitting(imageInputUpside,99.5,396,0); funReuslt =ImageCrop(imageInputUpside,PARAMETER_SMALL_DENOMI[2],imageOutput,0,2); printf("่ฟ™ๆ˜ฏๅฐๅคด5ๅ—\n"); break; case 2: funReuslt = LinearFitting(imageInputUpside,99.5,396,0); funReuslt =ImageCrop(imageInputUpside,PARAMETER_SMALL_DENOMI[2],imageOutput,0,2); printf("่ฟ™ๆ˜ฏๅฐๅคด10ๅ—\n"); break; case 3: funReuslt = LinearFitting(imageInputUpside,99.5,396,0); funReuslt =ImageCrop(imageInputUpside,PARAMETER_SMALL_DENOMI[1],imageOutput,0,22); printf("่ฟ™ๆ˜ฏๅฐๅคด20ๅ—\n"); break; } } return 0; } //-----------ไน‹ๅŽ็š„ๅ‡ฝๆ•ฐๆฒกๆœ‰ๅ‘็Žฐๆœ‰ๅœจๅ…ถไป–ๅœฐๆ–น่ขซ่ฐƒ็”จ๏ผŒๆš‚ๆ—ถไธ่ฟ›่กŒ้‡ๆž„-------------- double *pick() { Mat image=imread("otsu1.bmp",CV_LOAD_IMAGE_COLOR); cvtColor(image, image, CV_BGR2GRAY ); printf("height: %d width: %d\n",image.rows,image.cols); int count=0; for(int i=15;i<image.cols;i++) { int *temp1= new int[2]; for(int j=15;j<image.rows;j++) { temp1[0]=0; temp1[1]=0; if(image.at<uchar>(j,i)==0) { printf("i=%d,j=%d\n",i,j); temp1=Charactercut(image,j,i,count); // printf("temp[0]=%d,temp[1]=%d\n",temp1[0],temp1[1]); // system("pause"); } if(temp1[0]!=0) { printf("temp[0]=%d,temp[1]=%d\n",temp1[0],temp1[1]); count++; i=temp1[1]; j=temp1[0]; if(j>image.rows-1) break; // system("pause"); } if( i>image.cols-1) break; } delete [] temp1; } // return 0; CHARACTER_Feature *head,*p1,*p2,*p3; /*head็”จๆฅๆ ‡่ฎฐ้“พ่กจ๏ผŒp1ๆ€ปๆ˜ฏ็”จๆฅๆŒ‡ๅ‘ๆ–ฐๅˆ†้…็š„ๅ†…ๅญ˜็ฉบ้—ด๏ผŒ p2ๆ€ปๆ˜ฏๆŒ‡ๅ‘ๅฐพ็ป“็‚น๏ผŒๅนถ้€š่ฟ‡p2ๆฅ้“พๅ…ฅๆ–ฐๅˆ†้…็š„็ป“็‚น*/ head=NULL; for(int i=0; i<11;i++) { p1=(CHARACTER_Feature*)malloc(sizeof(CHARACTER_Feature)); /*ๅŠจๆ€ๅˆ†้…ๅ†…ๅญ˜็ฉบ้—ด๏ผŒๅนถๆ•ฐๆฎ่ฝฌๆขไธบ(struct LNode)็ฑปๅž‹*/ // printf("่ฏท่พ“ๅ…ฅ้“พ่กจไธญ็š„็ฌฌ%dไธชๆ•ฐ๏ผš",i); // scanf("%d",&i); p1->label=i; if(head==NULL)/*ๆŒ‡ๅฎš้“พ่กจ็š„ๅคดๆŒ‡้’ˆ*/ { head=p1; p3=head; p2=p1; } else { p2->next=p1; p2=p1; } p2->next=NULL;/*ๅฐพ็ป“็‚น็š„ๅŽ็ปงๆŒ‡้’ˆไธบNULL(็ฉบ)*/ } while(head!=NULL) { Feature(head); head=head->next; } // int c=scaled(); // int b=onetoone(); double *kill= new double[11]; // kill=SVM(); for(int i=0;i<11;i++) { printf("%d",(int)kill[i]); } printf("\n"); return kill; } int scaled() { int i=0; int j=0; int *b=new int[2]; b= countlines(); double **a= new double*[b[1]]; cout<<b[0]<<" "<<b[1]<<endl; //b[0]ไธบๅˆ— for(i=0;i<b[1];i++) //b[1]ไธบ่กŒ { a[i]=new double[b[0]]; } for(i=0;i<b[1];i++) { for(j=0;j<b[0];j++) { a[i][j]=0; } } ifstream file; file.open("test.txt",ios::in); if (file.fail()) { cout<<"can't open"<<endl; return 0; } else { for(i=0;i<b[1];i++) for(j=0;j<b[0];j++) { file>>a[i][j]; } } for(i=0;i<b[1];i++) { for(j=0;j<b[0];j++) { cout<<a[i][j]<<' '; } cout<<endl; } double **c=new double * [2]; for(i=0;i<2;i++) { c[i]= new double [b[0]]; } for(i=0;i<2;i++) { for (j=0;j<b[0];j++) { c[i][j]=0; } } for(j=0;j<b[0];j++) { double max=0; double min=999; for(i=0;i<b[1];i++) { if(max<a[i][j]) { max=a[i][j]; } if(min>a[i][j]) { min=a[i][j]; } } c[0][j]=max; c[1][j]=min; cout<<"the "<<j; cout<<" lie min is "<<c[1][j]<<endl; //ๆ‰พๅ‡บๆœ€ๅฐๅ€ผ cout<<"the "<<j; cout<<" lie max is "<<c[0][j]<<endl; //ๆ‰พๅ‡บๆœ€ๅคงๅ€ผ } double **y =new double *[b[1]]; double upper=1; double lower=0; for(i=0;i<b[1];i++) { y[i]=new double [b[0]]; } for (i=0;i<b[1];i++) { for(j=0;j<b[0];j++) { y[i][j]=0; } } // ofstream writefile; // writefile.open("intput.txt",ios::trunc); for(j=0;j<b[0]-2;j++) { for(i=0;i<b[1];i++) { y[i][j]=lower+(upper-lower)*(a[i][j]-c[1][j])/(c[0][j]-c[1][j]); //ๅฝ’ไธ€ๅŒ–ๅ‡ฝๆ•ฐ a[i][j]=y[i][j]; } } FILE *fp; fp=fopen("input1.txt","a"); for(i=0;i<b[1];i++) { for(j=0;j<b[0];j++) // for(j=b[0]-1;j>=0;j--) { if(j==b[0]-1) fprintf(fp,"%lf",a[i][j]); else fprintf(fp,"%lf\t",a[i][j]); // if(j==b[0]-1) // fprintf(fp,"%lf ",a[i][j]); // else // fprintf(fp,"%d:%lf ",b[0]-j-1,a[i][j]); } fprintf(fp,"\n"); } fclose(fp); return 0; } int *countlines() { int n=0; int m=0; int min=0; int *p =new int[2]; char c; ifstream readfile; readfile.open("test.txt",ios::in); if(readfile.fail()) { cout<<"can't open the file"; p[0]=0; p[1]=0; } else { while(readfile.get(c)) { if (c=='\t') //่ฎก็ฎ—ๆ•ฐๆฎไน‹้—ด็š„็ฉบๆ ผ { n++; } if(c=='\n') { m++; min=n; n=1; } //่ฎก็ฎ—ๅ›ž่ฝฆไธชๆ•ฐ } p[0]=min; p[1]=m; cout<<"the m is "<<m<<" the n is "<<min<<endl; readfile.close(); } return p; }
29.378251
148
0.45039
akamoon
1af0593611ef5dd919c40973c2b4d568f64a280b
19,119
cpp
C++
LeapMotion/LeapMotionInputService/m+mLeapMotionInputListener.cpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
LeapMotion/LeapMotionInputService/m+mLeapMotionInputListener.cpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
LeapMotion/LeapMotionInputService/m+mLeapMotionInputListener.cpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------------------------------- // // File: m+mLeapMotionInputListener.cpp // // Project: m+m // // Contains: The class definition for a Leap Motion listener. // // Written by: Norman Jaffe // // Copyright: (c) 2014 by H Plus Technologies Ltd. and Simon Fraser University. // // All rights reserved. Redistribution and use in source and binary forms, with or // without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and / or // other materials provided with the distribution. // * Neither the name of the copyright holders nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // Created: 2014-09-16 // //-------------------------------------------------------------------------------------------------- #include "m+mLeapMotionInputListener.hpp" //#include <odlEnable.h> #include <odlInclude.h> #if defined(__APPLE__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunknown-pragmas" # pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #endif // defined(__APPLE__) /*! @file @brief The class definition for a %Leap Motion listener. */ #if defined(__APPLE__) # pragma clang diagnostic pop #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Namespace references #endif // defined(__APPLE__) using namespace MplusM; using namespace MplusM::Common; using namespace MplusM::LeapMotion; #if defined(__APPLE__) # pragma mark Private structures, constants and variables #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Global constants and variables #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Local functions #endif // defined(__APPLE__) /*! @brief Put the three coordinates of a %Vector in a dictionary with the given tag. @param[in,out] dictionary The dictionary to be added to. @param[in] tag The name to be associated with the value. @param[in] vectorToUse The %Vector containing the data to be added. */ static void putVectorInDictionary(yarp::os::Property & dictionary, const YarpString & tag, const Leap::Vector & vectorToUse) { yarp::os::Value stuff; yarp::os::Bottle * stuffList = stuff.asList(); if (stuffList) { stuffList->addDouble(vectorToUse.x); stuffList->addDouble(vectorToUse.y); stuffList->addDouble(vectorToUse.z); dictionary.put(tag, stuff); } } // putVectorInDictionary #if defined(__APPLE__) # pragma mark Class methods #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Constructors and Destructors #endif // defined(__APPLE__) LeapMotionInputListener::LeapMotionInputListener(GeneralChannel * outChannel) : inherited(), _outChannel(outChannel) { ODL_ENTER(); //#### ODL_P1("outChannel = ", outChannel); //#### ODL_EXIT_P(this); //#### } // LeapMotionInputListener::LeapMotionInputListener LeapMotionInputListener::~LeapMotionInputListener(void) { ODL_OBJENTER(); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::~LeapMotionInputListener #if defined(__APPLE__) # pragma mark Actions and Accessors #endif // defined(__APPLE__) void LeapMotionInputListener::clearOutputChannel(void) { ODL_OBJENTER(); //#### _outChannel = NULL; ODL_OBJEXIT(); //#### } // LeapMotionInputListener::clearOutputChannel void LeapMotionInputListener::onConnect(const Leap::Controller & theController) { ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### //theController.setPolicyFlags(Leap::Controller::POLICY_DEFAULT); theController.setPolicyFlags(Leap::Controller::POLICY_BACKGROUND_FRAMES); ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onConnect #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onDeviceChange(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onDeviceChange #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onDisconnect(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onDisconnect #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onExit(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onExit #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onFocusGained(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onFocusGained #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onFocusLost(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onFocusLost #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onFrame(const Leap::Controller & theController) { ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### Leap::Frame latestFrame(theController.frame()); if (latestFrame.isValid()) { Leap::HandList hands(latestFrame.hands()); Leap::ToolList tools(latestFrame.tools()); yarp::os::Bottle message; int handCount = hands.count(); int toolCount = tools.count(); yarp::os::Bottle & handStuff = message.addList(); yarp::os::Bottle & toolStuff = message.addList(); if (0 < (handCount + toolCount)) { for (Leap::HandList::const_iterator handWalker(hands.begin()); hands.end() != handWalker; ++handWalker) { Leap::Hand aHand(*handWalker); if (aHand.isValid()) { yarp::os::Property & handProps = handStuff.addDict(); handProps.put("id", aHand.id()); putVectorInDictionary(handProps, "palmposition", aHand.palmPosition()); putVectorInDictionary(handProps, "stabilizedpalmposition", aHand.stabilizedPalmPosition()); putVectorInDictionary(handProps, "palmnormal", aHand.palmNormal()); putVectorInDictionary(handProps, "palmvelocity", aHand.palmVelocity()); putVectorInDictionary(handProps, "direction", aHand.direction()); Leap::Arm anArm(aHand.arm()); if (anArm.isValid()) { yarp::os::Value armStuff; yarp::os::Bottle * armList = armStuff.asList(); if (armList) { yarp::os::Property & armDict = armList->addDict(); putVectorInDictionary(armDict, "direction", anArm.direction()); putVectorInDictionary(armDict, "elbowposition", anArm.elbowPosition()); handProps.put("arm", armStuff); } } putVectorInDictionary(handProps, "wristposition", aHand.wristPosition()); handProps.put("confidence", aHand.confidence()); if (aHand.isLeft()) { handProps.put("side", "left"); } else if (aHand.isRight()) { handProps.put("side", "right"); } else { handProps.put("side", "unknown"); } yarp::os::Value fingerSet; yarp::os::Bottle * fingerSetAsList = fingerSet.asList(); if (fingerSetAsList) { // fingers Leap::FingerList fingers(aHand.fingers()); for (Leap::FingerList::const_iterator fingerWalker(fingers.begin()); fingers.end() != fingerWalker; ++fingerWalker) { Leap::Finger aFinger(*fingerWalker); if (aFinger.isValid()) { yarp::os::Property & fingProps = fingerSetAsList->addDict(); fingProps.put("id", aFinger.id()); switch (aFinger.type()) { case Leap::Finger::TYPE_THUMB : fingProps.put("type", "thumb"); break; case Leap::Finger::TYPE_INDEX : fingProps.put("type", "index"); break; case Leap::Finger::TYPE_MIDDLE : fingProps.put("type", "middle"); break; case Leap::Finger::TYPE_RING : fingProps.put("type", "ring"); break; case Leap::Finger::TYPE_PINKY : fingProps.put("type", "pinky"); break; default : fingProps.put("type", "unknown"); break; } putVectorInDictionary(fingProps, "tipposition", aFinger.tipPosition()); putVectorInDictionary(fingProps, "stabilizedtipposition", aFinger.stabilizedTipPosition()); putVectorInDictionary(fingProps, "tipvelocity", aFinger.tipVelocity()); putVectorInDictionary(fingProps, "direction", aFinger.direction()); fingProps.put("length", aFinger.length()); if (aFinger.isExtended()) { fingProps.put("extended", "yes"); } else { fingProps.put("extended", "no"); } yarp::os::Value bonesStuff; yarp::os::Bottle * bonesAsList = bonesStuff.asList(); if (bonesAsList) { static const Leap::Bone::Type boneType[] = { Leap::Bone::TYPE_METACARPAL, Leap::Bone::TYPE_PROXIMAL, Leap::Bone::TYPE_INTERMEDIATE, Leap::Bone::TYPE_DISTAL }; static const size_t numBoneTypes = (sizeof(boneType) / sizeof(*boneType)); for (size_t ii = 0; numBoneTypes > ii; ++ii) { Leap::Bone::Type aType = boneType[ii]; Leap::Bone aBone = aFinger.bone(aType); if (aBone.isValid()) { yarp::os::Property & boneProps = bonesAsList->addDict(); putVectorInDictionary(boneProps, "proximal", aBone.prevJoint()); putVectorInDictionary(boneProps, "distal", aBone.nextJoint()); putVectorInDictionary(boneProps, "direction", aBone.direction()); boneProps.put("length", aBone.length()); } } fingProps.put("bones", bonesStuff); } } } handProps.put("fingers", fingerSet); } } } for (Leap::ToolList::const_iterator toolWalker(tools.begin()); tools.end() != toolWalker; ++toolWalker) { Leap::Tool aTool(*toolWalker); if (aTool.isValid()) { yarp::os::Property & toolProps = toolStuff.addDict(); toolProps.put("id", aTool.id()); putVectorInDictionary(toolProps, "tipposition", aTool.tipPosition()); putVectorInDictionary(toolProps, "tipvelocity", aTool.tipVelocity()); putVectorInDictionary(toolProps, "direction", aTool.direction()); toolProps.put("length", aTool.length()); } } } else { ODL_LOG("! (0 < (handCount + toolCount))"); //#### } if (_outChannel) { if (! _outChannel->write(message)) { ODL_LOG("(! _outChannel->write(message))"); //#### #if defined(MpM_StallOnSendProblem) Stall(); #endif // defined(MpM_StallOnSendProblem) } } } else { ODL_LOG("! (latestFrame.isValid())"); //#### } ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onFrame void LeapMotionInputListener::onInit(const Leap::Controller & theController) { ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### theController.setPolicyFlags(Leap::Controller::POLICY_BACKGROUND_FRAMES); ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onInit #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onServiceConnect(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onServiceConnect #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ #if (! MAC_OR_LINUX_) # pragma warning(push) # pragma warning(disable: 4100) #endif // ! MAC_OR_LINUX_ void LeapMotionInputListener::onServiceDisconnect(const Leap::Controller & theController) { #if (! defined(ODL_ENABLE_LOGGING_)) # if MAC_OR_LINUX_ # pragma unused(theController) # endif // MAC_OR_LINUX_ #endif // ! defined(ODL_ENABLE_LOGGING_) ODL_OBJENTER(); //#### ODL_P1("theController = ", &theController); //#### ODL_OBJEXIT(); //#### } // LeapMotionInputListener::onServiceDisconnect #if (! MAC_OR_LINUX_) # pragma warning(pop) #endif // ! MAC_OR_LINUX_ #if defined(__APPLE__) # pragma mark Global functions #endif // defined(__APPLE__)
38.314629
100
0.529996
opendragon
8c2473b193efca03afd512ebac1eb07c0733213e
659
hpp
C++
Microsoft.O365.Security.Native.ETW/Conversions.hpp
jdu2600/krabsetw
4ae6e5b01c1ae2d7621e942f7c76449a1b36a3b1
[ "MIT" ]
207
2016-10-26T22:53:49.000Z
2019-04-24T02:58:18.000Z
Microsoft.O365.Security.Native.ETW/Conversions.hpp
jdu2600/krabsetw
4ae6e5b01c1ae2d7621e942f7c76449a1b36a3b1
[ "MIT" ]
88
2019-06-06T23:50:21.000Z
2022-02-17T09:06:03.000Z
Microsoft.O365.Security.Native.ETW/Conversions.hpp
jdu2600/krabsetw
4ae6e5b01c1ae2d7621e942f7c76449a1b36a3b1
[ "MIT" ]
70
2019-05-15T04:56:26.000Z
2022-03-26T08:24:02.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include <type_traits> using namespace System; using namespace System::Runtime::InteropServices; namespace Microsoft::O365::Security::ETW { // Converts a CLR List<T> of arithmetic types to a corresponding std::vector<T> template <typename T, typename std::enable_if_t<std::is_arithmetic<T>::value, T> = 0> std::vector<T> to_vector(List<T>^ list) { std::vector<T> vector(list->Count); for each (auto item in list) { vector.push_back(item); } return vector; } }
24.407407
101
0.710167
jdu2600
8c2e12b5e0ea77f377267e9c5f550bd6e966ae3b
2,683
cpp
C++
src/plugins/legacy/itkINRDataImageWriter/itkINRDataImageWriter.cpp
dmargery/medInria-public
c232dbdf9353e14ec6e5184349ef1e523def0b76
[ "BSD-4-Clause" ]
61
2015-04-14T13:00:50.000Z
2022-03-09T22:22:18.000Z
src/plugins/legacy/itkINRDataImageWriter/itkINRDataImageWriter.cpp
dmargery/medInria-public
c232dbdf9353e14ec6e5184349ef1e523def0b76
[ "BSD-4-Clause" ]
510
2016-02-03T13:28:18.000Z
2022-03-23T10:23:44.000Z
src/plugins/legacy/itkINRDataImageWriter/itkINRDataImageWriter.cpp
mathildemerle/medInria-public
e8c517ef6263c1d98a62b79ca7aad30a21b61094
[ "BSD-4-Clause", "BSD-1-Clause" ]
36
2015-03-03T22:58:19.000Z
2021-12-28T18:19:23.000Z
/*========================================================================= medInria Copyright (c) INRIA 2013 All rights reserved. See LICENSE.txt for details in the root of the sources or: https://github.com/medInria/medInria-public/blob/master/LICENSE.txt This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "itkINRDataImageWriter.h" #include <medAbstractData.h> #include <medAbstractDataFactory.h> #include <medInrimageImageIO.h> // ///////////////////////////////////////////////////////////////// // itkINRDataImageWriter // ///////////////////////////////////////////////////////////////// static QString s_identifier() { return "itkINRDataImageWriter"; } static QStringList s_handled() { return QStringList() << "itkDataImageChar3" << "itkDataImageChar4" << "itkDataImageUChar3" << "itkDataImageUChar4" << "itkDataImageShort3" << "itkDataImageShort4" << "itkDataImageUShort3" << "itkDataImageUShort4" << "itkDataImageInt3" << "itkDataImageInt4" << "itkDataImageUInt3" << "itkDataImageUInt4" << "itkDataImageLong3" << "itkDataImageLong4" << "itkDataImageULong3" << "itkDataImageULong4" << "itkDataImageFloat3" << "itkDataImageFloat4" << "itkDataImageDouble3" << "itkDataImageDouble4" << "itkDataImageRGB3" << "itkDataImageRGBA3"; } itkINRDataImageWriter::itkINRDataImageWriter(void) : itkDataImageWriterBase() { this->io = InrimageImageIO::New(); } itkINRDataImageWriter::~itkINRDataImageWriter(void) { } bool itkINRDataImageWriter::registered(void) { return medAbstractDataFactory::instance()->registerDataWriterType(s_identifier(), s_handled(), create); } QString itkINRDataImageWriter::description(void) const { return "Inrimage image exporter"; } QStringList itkINRDataImageWriter::handled() const { return s_handled(); } QStringList itkINRDataImageWriter::supportedFileExtensions() const { return QStringList() << ".inr" << ".inr.gz"; } QString itkINRDataImageWriter::identifier() const { return s_identifier(); } // ///////////////////////////////////////////////////////////////// // Type instantiation // ///////////////////////////////////////////////////////////////// dtkAbstractDataWriter * itkINRDataImageWriter::create(void) { return new itkINRDataImageWriter; }
31.940476
107
0.565412
dmargery
8c2f2ff67065b7bd618ff08ef8915ea7bab7b2b3
2,851
hpp
C++
atomicpp/RateCoefficient.hpp
TBody/atomicpp
1c5fd4d280bfc0da9162babf7766943bd6611fc2
[ "MIT" ]
2
2017-09-27T11:07:42.000Z
2018-06-27T09:22:38.000Z
atomicpp/RateCoefficient.hpp
TBody/atomicpp
1c5fd4d280bfc0da9162babf7766943bd6611fc2
[ "MIT" ]
null
null
null
atomicpp/RateCoefficient.hpp
TBody/atomicpp
1c5fd4d280bfc0da9162babf7766943bd6611fc2
[ "MIT" ]
null
null
null
#ifndef RATECOEFFICIENT_H #define RATECOEFFICIENT_H #include <string> #include <vector> #include <array> #include "ExternalModules/json.hpp" using json = nlohmann::json; #include "Spline/BivariateBSpline.hpp" namespace atomicpp{ class RateCoefficient{ // # For storing the RateCoefficients encoded in an OpenADAS data file // # Intended to be called from the .makeRateCoefficients method of an ImpuritySpecies object // # // # Closely based on the cfe316/atomic/atomic_data.py/RateCoefficient class // # Attributes: // # atomic_number (int) : The element's Z. // # element (str) : Short element name like 'c' // # adf11_file (str) : The /full/filename it came from (link to .json, not .dat) // # log_temp : std::vector<double> of log10 of temperature values for building interpolation grid // # log_dens : std::vector<double> of log10 of density values for building interpolation grid // # log_rate : nested 3D std::vector<double> with shape (Z, temp, dens) // # The list has length Z and is interpolations of log_rate. public: /** * @brief RateCoefficient constructor * * @param filename JSON file from OpenADAS which supplies the rate coefficient data */ RateCoefficient(const std::string& filename); /** * @brief blank RateCoefficient constructor * @details Copies all characteristics except log_rate * * @param source_rc a smart pointer to a sample RateCoefficent object to source from */ RateCoefficient(const std::shared_ptr<RateCoefficient> source_rc); /** * @brief Returns the rate coefficient for a (scalar) Te and Ne supplied * @details Performs a simple bivariate (multicubic) interpolation to return the rate coefficient * at the supplied Te and Ne values. N.b. will throw a std::runtime_error if the supplied Te or Ne * value are not on the interpolating grid (otherwise you'll get a seg fault) * * @param k The charge state index process (actually k+=1 for charged-target processes, but we don't implement this here) * @param eval_Te electron temperature (Te) at a point (in eV) * @param eval_Ne electron density (Ne) at a point (in m^-3) * @return eval_coeff evaluated rate coefficient in m^3/s */ double call0D(const int k, const double eval_Te, const double eval_Ne); int get_atomic_number(); std::string get_element(); std::string get_adf11_file(); std::vector<BivariateBSpline> get_interpolator(); // std::vector<std::vector< std::vector<double> > > get_log_rate(); std::vector<double> get_log_temp(); std::vector<double> get_log_dens(); void zero_interpolator(); private: int atomic_number; std::string element; std::string adf11_file; std::vector<BivariateBSpline> interpolator; }; } #endif
41.926471
124
0.696247
TBody
8c3af866544f2075f558dc18b74b0b7bdaf7b566
412
hpp
C++
src/pilo/core/datetime/tickcount_simu_thread.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
1
2019-07-31T06:44:46.000Z
2019-07-31T06:44:46.000Z
src/pilo/core/datetime/tickcount_simu_thread.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
src/pilo/core/datetime/tickcount_simu_thread.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
#pragma once #include "core/coredefs.hpp" #ifndef WINDOWS extern volatile pilo::u64_t __glb_tick_count; extern volatile int __glb_tick_count_simulative_thread_started; pilo::u64_t __GetMillisecondTickCount(); #define PiloGetTickCount64() (__glb_tick_count_simulative_thread_started ? __glb_tick_count : __GetMillisecondTickCount()) #define PiloGetTickCount32() ((unsigned int) PiloGetTickCount64()) #endif
27.466667
123
0.830097
picofox
8c3f228752da10525d05e7bf23ebe8704b5daa26
6,866
cpp
C++
LiberoEngine/src/Libero/Components/SkyDomeRenderComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Components/SkyDomeRenderComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Components/SkyDomeRenderComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
#include "Liber_pch.h" #include "SkyDomeRenderComponent.h" #include "Libero/Graphics/Mesh.h" #include "Libero/Graphics/Skydome/SkyDome.h" #include "Libero/Graphics/GraphicsMaster.h" #include "Libero/Graphics/CameraMaster.h" #include "Libero/Components/CameraComponent.h" #include "Libero/Components/TransformComponent.h" namespace Libero { using namespace Math; SkyDomeRenderComponent::SkyDomeRenderComponent(const std::string& effectFile) : m_EffectPath{effectFile} { m_pSkyDome = new SkyDome(); Initialize(); } SkyDomeRenderComponent::~SkyDomeRenderComponent() { SafeRelease(m_pCameraPosition); SafeRelease(m_pApexColor); SafeRelease(m_pBaseColor); SafeRelease(m_pWVP); SafeRelease(m_pIndexBuffer); SafeRelease(m_pVertexBuffer); SafeRelease(m_pInputLayout); SafeRelease(m_pEffect); SafeDelete(m_pSkyDome); } void SkyDomeRenderComponent::UpdateEffectVariables() { TransformComponent* pTransform = CameraMasterLocator::Get()->GetActiveCamera()->GetOwner()->GetComponent<TransformComponent>(); m_CameraPosition = pTransform->GetPosition(); if (m_pCameraPosition) m_pCameraPosition->SetFloatVector(&m_CameraPosition.x); if (m_pApexColor) m_pApexColor->SetFloatVector(&m_pSkyDome->GetApexColor().r); if (m_pBaseColor) m_pBaseColor->SetFloatVector(&m_pSkyDome->GetBaseColor().r); XMFLOAT4X4 vp; DirectX::XMStoreFloat4x4(&vp, CameraMasterLocator::Get()->GetActiveCamera()->GetViewProjection()); if (m_pWVP) m_pWVP->SetMatrix(&vp.m[0][0]); } void SkyDomeRenderComponent::Initialize() { if (m_IsInitialized) return; InitEffect(); InitMeshData(); InitBuffer(); m_IsInitialized = true; } void SkyDomeRenderComponent::Render() { if (m_VertexBuffer.empty()) return; if (!m_pSkyDome) return; const GraphicsContext& grph = GraphicsLocator::Get()->GetGraphicsContext(); UpdateEffectVariables(); UINT offset = 0; UINT stride = sizeof(DomeVertex); grph.m_pDeviceContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset); grph.m_pDeviceContext->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); grph.m_pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); grph.m_pDeviceContext->IASetInputLayout(m_pInputLayout); D3DX11_TECHNIQUE_DESC techDesc; m_pTechnique->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { m_pTechnique->GetPassByIndex(p)->Apply(0, grph.m_pDeviceContext); grph.m_pDeviceContext->DrawIndexed((UINT)m_IndexBuffer.size(), 0, 0); } } void SkyDomeRenderComponent::InitMeshData() { m_VertexBuffer.clear(); m_IndexBuffer.clear(); Mesh* pMesh = m_pSkyDome->GetMesh(); // Setup indexbuffer for (size_t f{}; f < pMesh->GetMesh()->mNumFaces; ++f) { const aiFace* face = &pMesh->GetMesh()->mFaces[f]; for (size_t i{}; i < face->mNumIndices; ++i) m_IndexBuffer.push_back((uint32_t)face->mIndices[i]); } // Set up mesh data: (only positions) for (size_t i{}; i < pMesh->GetMesh()->mNumVertices; ++i) { aiVector3D pVertex = pMesh->GetMesh()->mVertices[i]; m_VertexBuffer.push_back({ pVertex.x, pVertex.y, pVertex.z }); } } void SkyDomeRenderComponent::InitBuffer() { // Vertexbuffer: if (m_pVertexBuffer) SafeRelease(m_pVertexBuffer); D3D11_BUFFER_DESC bufferDesc; bufferDesc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_VERTEX_BUFFER; bufferDesc.ByteWidth = sizeof(DomeVertex) * (UINT)m_VertexBuffer.size(); bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_FLAG::D3D11_CPU_ACCESS_WRITE; bufferDesc.Usage = D3D11_USAGE::D3D11_USAGE_DYNAMIC; bufferDesc.MiscFlags = 0; HRESULT res = GraphicsLocator::Get()->GetGraphicsContext().m_pDevice->CreateBuffer(&bufferDesc, nullptr, &m_pVertexBuffer); // Indexbuffer: if (m_pIndexBuffer) SafeRelease(m_pIndexBuffer); D3D11_BUFFER_DESC idxDesc; idxDesc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_INDEX_BUFFER; idxDesc.ByteWidth = sizeof(uint32_t) * (UINT)m_IndexBuffer.size(); idxDesc.CPUAccessFlags = D3D11_CPU_ACCESS_FLAG::D3D11_CPU_ACCESS_WRITE; idxDesc.Usage = D3D11_USAGE::D3D11_USAGE_DYNAMIC; idxDesc.MiscFlags = 0; GraphicsLocator::Get()->GetGraphicsContext().m_pDevice->CreateBuffer(&idxDesc, nullptr, &m_pIndexBuffer); res; // FILL IT UP WITH THE INITIAL DATA const GraphicsContext& grphContext = GraphicsLocator::Get()->GetGraphicsContext(); D3D11_MAPPED_SUBRESOURCE mappedR; grphContext.m_pDeviceContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedR); memcpy(mappedR.pData, m_VertexBuffer.data(), sizeof(DomeVertex) * m_VertexBuffer.size()); grphContext.m_pDeviceContext->Unmap(m_pVertexBuffer, 0); D3D11_MAPPED_SUBRESOURCE mappedRes; grphContext.m_pDeviceContext->Map(m_pIndexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedRes); memcpy(mappedRes.pData, m_IndexBuffer.data(), sizeof(uint32_t) * m_IndexBuffer.size()); grphContext.m_pDeviceContext->Unmap(m_pIndexBuffer, 0); } void SkyDomeRenderComponent::InitEffect() { // Load the effect: #pragma region LoadEffect const GraphicsContext& graphicsContext = GraphicsLocator::Get()->GetGraphicsContext(); HRESULT hr; ID3D10Blob* pErrBlob = nullptr; ID3DX11Effect* pEffect; DWORD shaderFlags = 0; hr = D3DX11CompileEffectFromFile(s2ws(m_EffectPath).c_str(), nullptr, nullptr, shaderFlags, 0, graphicsContext.m_pDevice, &pEffect, &pErrBlob); if (hr != S_OK) { std::string val = (char*)pErrBlob; val; } m_pEffect = pEffect; m_pTechnique = m_pEffect->GetTechniqueByIndex(0); D3D11_INPUT_ELEMENT_DESC layout [1] = { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; D3DX11_PASS_DESC passDesc; m_pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); const auto res = graphicsContext.m_pDevice->CreateInputLayout(layout, 1, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_pInputLayout); #pragma endregion // Load Effect Variables: #pragma region LoadVariables if (!m_pCameraPosition) m_pCameraPosition = m_pEffect->GetVariableByName("gCameraPosition")->AsVector(); if (!m_pBaseColor) m_pBaseColor = m_pEffect->GetVariableByName("gColorBase")->AsVector(); if (!m_pApexColor) m_pApexColor = m_pEffect->GetVariableByName("gColorApex")->AsVector(); if (!m_pWVP) m_pWVP = m_pEffect->GetVariableByName("gWVP")->AsMatrix(); #pragma endregion } #pragma region GettingSetting void SkyDomeRenderComponent::SetBaseColor(const ColorRGB& col) { m_pSkyDome->SetBaseColor(col); } void SkyDomeRenderComponent::SetApexColor(const ColorRGB& col) { m_pSkyDome->SetApexColor(col); } ColorRGB SkyDomeRenderComponent::GetBaseColor() const { return m_pSkyDome->GetBaseColor(); } ColorRGB SkyDomeRenderComponent::GetApexColor() const { return m_pSkyDome->GetApexColor(); } #pragma endregion }
29.852174
129
0.75284
Kair0z
8c401c23ef411ae5b046e99df0f43784f5c66d09
546
cpp
C++
BitMasking/IncredibleHulkProb.cpp
abhijay94/CompetitiveProgramming
ba1f05c189750a49ab9f69b10d2aafa60baa4310
[ "Apache-2.0" ]
null
null
null
BitMasking/IncredibleHulkProb.cpp
abhijay94/CompetitiveProgramming
ba1f05c189750a49ab9f69b10d2aafa60baa4310
[ "Apache-2.0" ]
null
null
null
BitMasking/IncredibleHulkProb.cpp
abhijay94/CompetitiveProgramming
ba1f05c189750a49ab9f69b10d2aafa60baa4310
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; void setBitsCount(int a) { int count = 0; while (a > 0) { count++; a = a & (a - 1); } cout << count << endl; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } for (int i = 0; i < n; i++) { setBitsCount(arr[i]); } }
16.058824
39
0.479853
abhijay94
8c461612d270fd140156c355d1b8e079b50f681e
5,038
cpp
C++
sabramov_task_3/func_sim/func_sim.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
1
2018-03-04T21:28:20.000Z
2018-03-04T21:28:20.000Z
sabramov_task_3/func_sim/func_sim.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
sabramov_task_3/func_sim/func_sim.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
/** * func_sim.cpp - simulator of MIPS CPU * @author Semyon Abramov <semyon.abramov.mipt@gmail.com> * 2014 - 2015 iLab project: MIPT - MIPS */ //Generic C++ #include<iostream> //Generic uArchSim modules #include"func_sim.h" /** * MIPS class methods */ MIPS::MIPS() { this->rf = new RF; } MIPS::~MIPS() { delete rf; } /* fetch instruction */ uint32 MIPS::fetch() const { return mem->read( PC); } /* read sources */ void MIPS::read_src( FuncInstr& instr) { instr.v_src1 = rf->read( static_cast< RegNum>( instr.get_src1_num_index())); instr.v_src2 = rf->read( static_cast< RegNum>( instr.get_src2_num_index())); instr.C = instr.getImm(); instr.CJump = instr.getJImm(); instr.Sh = instr.getShamt(); } /* load from Memory to Registers */ void MIPS::load(FuncInstr& instr) { if ( instr.pointer == &FuncInstr::lb) { rf->write( static_cast< RegNum>( instr.get_dst_num_index()), int8( mem->read( instr.mem_addr, 1))); instr.v_dst = rf->read( static_cast< RegNum>( instr.get_dst_num_index())); return; } if ( instr.pointer == &FuncInstr::lbu) { rf->write( static_cast< RegNum>( instr.get_dst_num_index()), uint8( mem->read( instr.mem_addr, 1))); instr.v_dst = rf->read( static_cast< RegNum>( instr.get_dst_num_index())); return; } if ( instr.pointer == &FuncInstr::lw) { rf->write( static_cast< RegNum>( instr.get_dst_num_index()), mem->read( instr.mem_addr, 4)); instr.v_dst = rf->read( static_cast< RegNum>( instr.get_dst_num_index())); return; } if ( instr.pointer == &FuncInstr::lh) { rf->write( static_cast< RegNum>( instr.get_dst_num_index()), int16( mem->read( instr.mem_addr, 2))); instr.v_dst = rf->read( static_cast< RegNum>( instr.get_dst_num_index())); return; } if ( instr.pointer == &FuncInstr::lhu) { rf->write( static_cast< RegNum>( instr.get_dst_num_index()), uint16( mem->read( instr.mem_addr, 2))); instr.v_dst = rf->read( static_cast< RegNum>( instr.get_dst_num_index())); return; } return; } /* store to Memory */ void MIPS::store( FuncInstr& instr) { instr.v_dst = rf->read( static_cast< RegNum>( instr.get_dst_num_index())); if ( instr.pointer == &FuncInstr::sb) { instr.v_dst = instr.v_dst & 0xff; mem->write( instr.v_dst, instr.mem_addr, 1); } if ( instr.pointer == &FuncInstr::sh) { instr.v_dst = instr.v_dst & 0xffff; mem->write( instr.v_dst, instr.mem_addr, 2); } if ( instr.pointer == &FuncInstr::sw) { mem->write( instr.v_dst, instr.mem_addr, 4); } } /* Memory Access */ void MIPS::ld_st(FuncInstr& instr) // calls load for loads, store for stores, nothing otherwise { if ( ( instr.pointer == &FuncInstr::lb) || ( instr.pointer == &FuncInstr::lw) || ( instr.pointer == &FuncInstr::lh) || ( instr.pointer == &FuncInstr::lhu) || ( instr.pointer == &FuncInstr::lbu)) { this->load( instr); return; } if ( ( instr.pointer == &FuncInstr::sb) || ( instr.pointer == &FuncInstr::sw) || ( instr.pointer == &FuncInstr::sh)) { this->store( instr); return; } return; } /* Writeback */ void MIPS::wb( FuncInstr& instr) { if ( instr.getWB() == 1) { rf->write( static_cast< RegNum>( instr.get_dst_num_index()), instr.v_dst); } instr.parseInstr(); // here parseInstr is called to prepare dump } uint32 MIPS::updatePC(const FuncInstr& instr) { this->PC = instr.new_PC; } /** * Implementation of RF class' methods */ /* Constructor of Register File */ RF::RF() { for ( int i = 0; i < MAX_REG; i++) { reset( static_cast< RegNum>( i)); } } RF::~RF() { } /* Read from Register File */ uint32 RF::read( RegNum index) const { if ( ( index != 0) && ( index < MAX_REG)) { return array[ index]; } else { return 0; } } /* Write to the Register File */ void RF::write( RegNum index, uint32 data) { if ( ( index != 0) && ( index < MAX_REG)) { array[ index] = data; return; } else { return; } } /* Clears Registers to 0 value */ void RF::reset( RegNum index) { { if ( static_cast< RegNum>( index) < MAX_REG) { array[ index] = 0; return; } } } /* this method starts process */ void MIPS::run( const string& tr, int instr_to_run) { /* load trace */ vector< ElfSection> sections_array; ElfSection::getAllElfSections( tr.c_str(), sections_array); FuncMemory func_mem( tr.c_str(), 32, 10, 12); this->mem = &func_mem; this->PC = mem->startPC(); /* loop that initializes the process */ for ( int i = 0; i < instr_to_run; ++i) { uint32 instr_bytes; instr_bytes = fetch(); // fetch FuncInstr instr( instr_bytes, this->PC); // decode read_src( instr); // read sources instr.execute(); // execution ld_st( instr); // memory access wb( instr); // writeback updatePC( instr); // update PC std::cout << instr << endl; // dump } }
21.347458
121
0.599444
MIPT-ILab
8c482faeeb7b4b8847e9badd3a6fc68cb5f33e94
3,608
hpp
C++
include/codegen/include/GlobalNamespace/SongPreviewPlayer.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/SongPreviewPlayer.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/SongPreviewPlayer.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: AudioSource class AudioSource; // Forward declaring type: AudioClip class AudioClip; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: SongPreviewPlayer class SongPreviewPlayer : public UnityEngine::MonoBehaviour { public: // private System.Int32 _channelsCount // Offset: 0x18 int channelsCount; // private UnityEngine.AudioSource _audioSourcePrefab // Offset: 0x20 UnityEngine::AudioSource* audioSourcePrefab; // private UnityEngine.AudioClip _defaultAudioClip // Offset: 0x28 UnityEngine::AudioClip* defaultAudioClip; // private System.Single _volume // Offset: 0x30 float volume; // private System.Single _ambientVolumeScale // Offset: 0x34 float ambientVolumeScale; // private System.Single _defaultCrossfadeSpeed // Offset: 0x38 float defaultCrossfadeSpeed; // private System.Single _defaultFadeOutSpeed // Offset: 0x3C float defaultFadeOutSpeed; // private UnityEngine.AudioSource[] _audioSources // Offset: 0x40 ::Array<UnityEngine::AudioSource*>* audioSources; // private System.Int32 _activeChannel // Offset: 0x48 int activeChannel; // private System.Single _timeToDefaultAudioTransition // Offset: 0x4C float timeToDefaultAudioTransition; // private System.Boolean _transitionAfterDelay // Offset: 0x50 bool transitionAfterDelay; // private System.Single _volumeScale // Offset: 0x54 float volumeScale; // private System.Single _fadeSpeed // Offset: 0x58 float fadeSpeed; // public System.Single get_volume() // Offset: 0xB9C4BC float get_volume(); // public System.Void set_volume(System.Single value) // Offset: 0xB9C4C4 void set_volume(float value); // protected System.Void OnEnable() // Offset: 0xB9C4CC void OnEnable(); // protected System.Void OnDisable() // Offset: 0xB9C8D0 void OnDisable(); // protected System.Void Update() // Offset: 0xB9C9FC void Update(); // public System.Void CrossfadeTo(UnityEngine.AudioClip audioClip, System.Single startTime, System.Single duration, System.Single volumeScale) // Offset: 0xB9C748 void CrossfadeTo(UnityEngine::AudioClip* audioClip, float startTime, float duration, float volumeScale); // public System.Void FadeOut() // Offset: 0xB9CBC8 void FadeOut(); // public System.Void CrossfadeToDefault() // Offset: 0xB9CBE0 void CrossfadeToDefault(); // public System.Void .ctor() // Offset: 0xB9CD40 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static SongPreviewPlayer* New_ctor(); }; // SongPreviewPlayer } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::SongPreviewPlayer*, "", "SongPreviewPlayer"); #pragma pack(pop)
35.372549
146
0.701774
Futuremappermydud
8c48e14482c3de8d8b8784711a637b2a1db29be1
5,220
cpp
C++
src/widgets/ImageButton.cpp
ndickson/UICommon
29a04e503e5e05594f5637f563b9f54417d4181e
[ "MIT" ]
null
null
null
src/widgets/ImageButton.cpp
ndickson/UICommon
29a04e503e5e05594f5637f563b9f54417d4181e
[ "MIT" ]
null
null
null
src/widgets/ImageButton.cpp
ndickson/UICommon
29a04e503e5e05594f5637f563b9f54417d4181e
[ "MIT" ]
null
null
null
#include "widgets/ImageButton.h" #include "MainWindow.h" #include <bmp/BMP.h> #include <bmp/sRGB.h> OUTER_NAMESPACE_BEGIN UICOMMON_LIBRARY_NAMESPACE_BEGIN const UIBoxClass ImageButton::staticType(ImageButton::initClass()); ImageButton::ImageButton( const char* upImageFilename, const char* hoverImageFilename, const char* downImageFilename, const char* disabledImageFilename ) : UIBox(&staticType), actionCallback(nullptr), callbackData(nullptr), isMouseInside(false), isMouseDown(false), isDisabled(false) { Array<uint32> pixelsSRGB; size_t width; size_t height; bool hasAlpha; if (upImageFilename != nullptr) { bool success = bmp::ReadBMPFile(upImageFilename, pixelsSRGB, width, height, hasAlpha); if (success) { assert(pixelsSRGB.size() == width*height); // Convert pixelsSRGB to linear in upImage upImage.setSize(width, height); Vec4f* pixels = upImage.pixels(); for (size_t i = 0, n = pixelsSRGB.size(); i < n; ++i) { pixels[i] = bmp::sRGBToLinear(pixelsSRGB[i]); } } } if (hoverImageFilename != nullptr) { bool success = bmp::ReadBMPFile(hoverImageFilename, pixelsSRGB, width, height, hasAlpha); if (success) { assert(pixelsSRGB.size() == width*height); // Convert pixelsSRGB to linear in hoverImage hoverImage.setSize(width, height); Vec4f* pixels = hoverImage.pixels(); for (size_t i = 0, n = pixelsSRGB.size(); i < n; ++i) { pixels[i] = bmp::sRGBToLinear(pixelsSRGB[i]); } } } if (downImageFilename != nullptr) { bool success = bmp::ReadBMPFile(downImageFilename, pixelsSRGB, width, height, hasAlpha); if (success) { assert(pixelsSRGB.size() == width*height); // Convert pixelsSRGB to linear in downImage downImage.setSize(width, height); Vec4f* pixels = downImage.pixels(); for (size_t i = 0, n = pixelsSRGB.size(); i < n; ++i) { pixels[i] = bmp::sRGBToLinear(pixelsSRGB[i]); } } } if (disabledImageFilename != nullptr) { bool success = bmp::ReadBMPFile(disabledImageFilename, pixelsSRGB, width, height, hasAlpha); if (success) { assert(pixelsSRGB.size() == width*height); // Convert pixelsSRGB to linear in disabledImage disabledImage.setSize(width, height); Vec4f* pixels = disabledImage.pixels(); for (size_t i = 0, n = pixelsSRGB.size(); i < n; ++i) { pixels[i] = bmp::sRGBToLinear(pixelsSRGB[i]); } } } // FIXME: set size based on maximum width and height!!! width = upImage.size()[0]; height= upImage.size()[1]; if (hoverImage.size()[0] > width) { width = hoverImage.size()[0]; } if (hoverImage.size()[1] > height) { width = hoverImage.size()[1]; } if (downImage.size()[0] > width) { width = downImage.size()[0]; } if (disabledImage.size()[1] > height) { width = disabledImage.size()[1]; } size = Vec2f(width, height); } UIBox* ImageButton::construct() { return new ImageButton(nullptr, nullptr, nullptr); } void ImageButton::destruct(UIBox* box) { assert(box->type != nullptr); ImageButton* imageButton = static_cast<ImageButton*>(box); imageButton->upImage.clear(); imageButton->hoverImage.clear(); imageButton->downImage.clear(); imageButton->disabledImage.clear(); } void ImageButton::onMouseDown(UIBox& box, size_t button, const MouseState& state) { assert(box.type != nullptr); ImageButton& imageButton = static_cast<ImageButton&>(box); imageButton.isMouseDown = true; setNeedRedraw(); } void ImageButton::onMouseUp(UIBox& box, size_t button, const MouseState& state) { assert(box.type != nullptr); ImageButton& imageButton = static_cast<ImageButton&>(box); imageButton.isMouseDown = false; if (imageButton.isMouseInside && imageButton.actionCallback != nullptr) { imageButton.actionCallback(imageButton); } setNeedRedraw(); } void ImageButton::onMouseEnter(UIBox& box, const MouseState& state) { assert(box.type != nullptr); ImageButton& imageButton = static_cast<ImageButton&>(box); imageButton.isMouseInside = true; setNeedRedraw(); } void ImageButton::onMouseExit(UIBox& box, const MouseState& state) { assert(box.type != nullptr); ImageButton& imageButton = static_cast<ImageButton&>(box); imageButton.isMouseInside = false; setNeedRedraw(); } void ImageButton::draw(const UIBox& box, const Box2f& clipRectangle, const Box2f& targetRectangle,Canvas& target) { const ImageButton& button = static_cast<const ImageButton&>(box); const Image* image; if (button.isDisabled && (button.disabledImage.pixels() != nullptr)) { image = &button.disabledImage; } else if (!button.isMouseInside && (!button.isMouseDown || (button.hoverImage.pixels() != nullptr))) { image = &button.upImage; } else if ((button.isMouseInside != button.isMouseDown) && (button.hoverImage.pixels() != nullptr)) { image = &button.hoverImage; } else { image = &button.downImage; } target.image.applyImage(targetRectangle, *image, clipRectangle); } UIBoxClass ImageButton::initClass() { UIBoxClass c; c.isContainer = false; c.typeName = "ImageButton"; c.construct = &construct; c.destruct = &destruct; c.onMouseDown = &onMouseDown; c.onMouseUp = &onMouseUp; c.onMouseEnter = &onMouseEnter; c.onMouseExit = &onMouseExit; c.draw = &draw; return c; } UICOMMON_LIBRARY_NAMESPACE_END OUTER_NAMESPACE_END
29
115
0.708429
ndickson
8c4b66bbf3dd8e66651020611f1a16697ae468d3
2,328
cpp
C++
1062.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
1062.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
1062.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <set> #include <algorithm> #include <map> using namespace std; int n, k; vector<string> list; //๊ฐ ๋‹จ์–ด์˜ ํ•„์š”ํ•œ ์•ŒํŒŒ๋ฒณ ๋ชจ์Œ set<char> alpha; //ํ•„์š”ํ•œ ์•ŒํŒŒ๋ฒณ๋“ค์˜ ์ด ๋ชจ์Œ int main() { cin.sync_with_stdio(0); cin.tie(0); cin >> n >> k; for(int i=0;i<n;i++) { set<char> s; string str, newstr; cin >> str; int strSize = str.size(); for(int j=0;j<strSize;j++) { //a, n, t, i, c๊ฐ€ ์•„๋‹ˆ๋ฉด set์— ๋„ฃ๋Š”๋‹ค. if(str[j]!='a' && str[j]!='n' && str[j]!='t' && str[j]!='i' && str[j]!='c') { s.insert(str[j]); alpha.insert(str[j]); } } set<char>::iterator iter; for(iter=s.begin();iter!=s.end();iter++) newstr+=*iter; list.push_back(newstr); //๊ฐ ๋‹จ์–ด์˜ ๋‹จ์–ด๋ชจ์Œ์„ ์ €์žฅ. } vector<char> alphav, n; set<char>::iterator iter; //์ด ์•ŒํŒŒ๋ฒณ ๋ชจ์Œ์„ set์—์„œ vector๋กœ ์˜ฎ๊น€ for(iter=alpha.begin();iter!=alpha.end();iter++) alphav.push_back(*iter); int alphavSize = alphav.size(); //์กฐํ•ฉ๋ฝ‘๊ธฐ ์‚ฌ์ „์ž‘์—… for(int i=0;i<alphavSize-k+5;i++) n.push_back('0'); for(int i=0;i<k-5;i++) n.push_back('1'); int maxcnt = 0, cnt, listSize = list.size(); do { //๋ชจ๋“  ์กฐํ•ฉ ๋ฝ‘๊ธฐ cnt = 0; map<char, bool> check; //๋ฐฐ์šด ๋‹จ์–ด ๋ชฉ๋ก for(int i=0;i<alphavSize;i++) if(n[i] == '1') check[alphav[i]] = true; //๋ฐฐ์šด๋‹จ์–ด๋Š” ์ „๋ถ€ ๋„ฃ์–ด์คŒ for(int i=0;i<listSize;i++) { //๊ฐ ๋‹จ์–ด์— ๋Œ€ํ•ด int j = list[i].size(); bool isGood = true; for(int k=0;k<j;k++) { //๋ฐฐ์šด๋‹จ์–ด๋กœ ํ•œ ๋‹จ์–ด๋ฅผ ๋ชจ๋‘ ๋ฐฐ์šธ ์ˆ˜ ์žˆ๋Š”์ง€ if(check.find(list[i][k]) == check.end()) { isGood = false; break; } } if(isGood) cnt++; } maxcnt = max(maxcnt, cnt); }while(next_permutation(n.begin(), n.end())); if(k<5) cout << 0; //k๊ฐ€ 5๊ฐœ ๋ฏธ๋งŒ์ด๋ฉด ๋ฌด์กฐ๊ฑด ๋ชป๋ฐฐ์šด๋‹ค. else cout << maxcnt; return 0; } /* ๋ชจ๋“  ๋‹จ์–ด๋Š” anta๋กœ ์‹œ์ž‘ํ•ด tica๋กœ ๋๋‚œ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ๊ธฐ๋ณธ์ ์œผ๋กœ a,n,t,i,c์˜ 5๊ฐœ์˜ ๊ธ€์ž๊ฐ€ ํ•„์š”ํ•˜๋‹ค. antarctica -> rc -> r antahellotica -> hello -> h,e,l,o antacartica -> car -> r set์— ์“ด ๋‹จ์–ด๋“ค์„ ๋ชจ๋‘ ๋ชจ์€๋‹ค. ๊ทธ๋ฆฌ๊ณ  k-5๊ฐœ์˜ ๋‹จ์–ด๋“ค์— ๋Œ€ํ•ด ์กฐํ•ฉ์„ ๋ฝ‘๋Š”๋‹ค. ๊ทธ ๋ชจ๋“  ์กฐํ•ฉ์— ๋Œ€ํ•ด ๋ช‡ ๊ธ€์ž๋ฅผ ์ฝ์„ ์ˆ˜ ์žˆ๋Š”์ง€ ์ฐพ๊ณ , ์ตœ๋Œ€๊ฐ’์„ ๊ตฌํ•œ๋‹ค. 26์—์„œ 5๊ฐœ๋ฅผ ๋นผ ์ตœ๋Œ€ 21๊ฐœ์—์„œ 11๊ฐœ๋ฅผ ๋ฝ‘์œผ๋ฉด, 35๋งŒ ๊ฒฝ์šฐ ์ •๋„. ์ถฉ๋ถ„ํ•˜๋‹ค. ์ƒ๊ฐ๋ณด๋‹ค ํ‘ธ๋Š”๋ฐ ๊ฝค ์˜ค๋ž˜ ๊ฑธ๋ฆฐ ๋ฌธ์ œ๋‹ค. ์‹œ๊ฐ„์ œํ•œ์ด 1์ดˆ์˜€๊ธฐ ๋•Œ๋ฌธ์—, ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ตœ๋Œ€ํ•œ ์‚ฌ์šฉํ•˜๋Š” ๋Œ€์‹  ์‹œ๊ฐ„์„ ๋งŽ์ด ์ค„์ด๋ ค๊ณ  ๋…ธ๋ ฅํ•˜์˜€๋‹ค -> AC */
30.233766
89
0.513316
jaemin2682