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
sequencelengths
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
sequencelengths
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
sequencelengths
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
35780e67403f1502578682eb387b94c80863e5cd
3,850
cpp
C++
src/libs/opengl/src/gl_buffers.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
2
2020-07-29T04:27:22.000Z
2021-10-11T01:27:43.000Z
src/libs/opengl/src/gl_buffers.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
null
null
null
src/libs/opengl/src/gl_buffers.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
2
2020-08-03T03:29:28.000Z
2020-08-03T08:01:14.000Z
/** * ================================================== * _____ * __|___ |__ __ __ _ ____ ____ _ * | ___| | _| |_ | |_| || \ | \ | | * | ___| ||_ _|| _ || \ | \| | * |______| __| |__| |__| |_||__|\__\|__/\____| * |_____| * * Game Engine * ================================================== * * @file gl_buffers.cpp * @author Nghia Lam <[email protected]> * * @brief * * @license Copyright 2020 Nghia Lam * * 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 "ethan/opengl/gl_buffers.h" #include "ethan/opengl/gl_assert.h" #include <glad/glad.h> namespace Ethan { static unsigned int BufferDataUsageToOpenGL(BufferDataUsage usage) { switch(usage) { case BufferDataUsage::STATIC: return GL_STATIC_DRAW; case BufferDataUsage::DYNAMIC: return GL_DYNAMIC_DRAW; } } /// --- GLVertexBuffer GLVertexBuffer::GLVertexBuffer(BufferDataUsage usage) : data_usage_(usage) { // TODO(Nghia Lam): Profile Here GLCALL(glGenBuffers(1, &vertexbufferID_)); } GLVertexBuffer::GLVertexBuffer(uint32_t size, BufferDataUsage usage) : data_usage_(usage) { // TODO(Nghia Lam): Profile Here GLCALL(glGenBuffers(1, &vertexbufferID_)); GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferData(GL_ARRAY_BUFFER, size, nullptr, BufferDataUsageToOpenGL(usage))); } GLVertexBuffer::GLVertexBuffer(const void* data, uint32_t size, BufferDataUsage usage) : data_usage_(usage) { // TODO(Nghia Lam): Profile here GLCALL(glGenBuffers(1, &vertexbufferID_)); GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferData(GL_ARRAY_BUFFER, size, data, BufferDataUsageToOpenGL(usage))); } GLVertexBuffer::~GLVertexBuffer() { GLCALL(glDeleteBuffers(1, &vertexbufferID_)); } void GLVertexBuffer::Bind() const { GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); } void GLVertexBuffer::UnBind() const { GLCALL(glBindBuffer(GL_ARRAY_BUFFER, 0)); } void GLVertexBuffer::SetData(const void* data, uint32_t size) { // NOTE(Nghia Lam): Bind Buffer to make sure we set data to the right vertex buffer // Will this impact the performace ? GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferData(GL_ARRAY_BUFFER, size, data, BufferDataUsageToOpenGL(data_usage_))); } void GLVertexBuffer::SetSubData(const void* data, uint32_t size, uint32_t offset) { GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_)); GLCALL(glBufferSubData(GL_ARRAY_BUFFER, offset, size, data)); } /// --- GLIndexBuffer GLIndexBuffer::GLIndexBuffer(uint32_t* indices, uint32_t &count) : count_(count) { GLCALL(glGenBuffers(1, &indexbufferID_)); GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbufferID_)); GLCALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint32_t), indices, GL_STATIC_DRAW)); } GLIndexBuffer::~GLIndexBuffer() { GLCALL(glDeleteBuffers(1, &indexbufferID_)); } void GLIndexBuffer::Bind() const { GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbufferID_)); } void GLIndexBuffer::UnBind() const { GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); } } // namespace Ethan
32.627119
101
0.670909
zZnghialamZz
357aacf63c7d9f507c2fc9dfb197f5d474f336a4
351
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise5.22.cpp // Ad // Rewrite the last example in this section using a loop. #include <iostream> using std::cin; using std::cout; using std::endl; int get_size(); int main() { int sz = get_size(); while (sz <= 0) { sz = get_size(); } // pause cin.get(); return 0; } int get_size() { return -1; }
12.535714
58
0.555556
alaxion
357f2fc5c895bbe88e01755584290087338ea20c
3,816
cpp
C++
src/armed/FilePickerDialog.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/armed/FilePickerDialog.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/armed/FilePickerDialog.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt #include "StdAfx.h" #include "FilePickerDialog.h" #include "QtUtil.h" #include "Project.h" #include "QtUtil.h" namespace Armed { ////////////////////////////////////////////////////////////////////////// FilePickerDialog::FilePickerDialog(QWidget* parent) : QDialog(parent) { m_Ui.setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); connect(m_Ui.OkButton, SIGNAL(clicked()), this, SLOT(accept())); connect(m_Ui.CancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(this, SIGNAL(finished(int)), this, SLOT(OnFinished())); connect(m_Ui.ProjectTree, SIGNAL(PathSelected(QString)), this, SLOT(OnPathSelected(QString))); connect(m_Ui.ProjectTree, SIGNAL(doubleClicked(QModelIndex)), m_Ui.OkButton, SLOT(click())); connect(m_Ui.FileName, SIGNAL(textChanged(QString)), this, SLOT(OnPathEdited(QString))); OnPathEdited(""); QSettings settings; settings.beginGroup("FilePickerDialog"); restoreGeometry(settings.value("Geometry").toByteArray()); m_Ui.MainSplitter->restoreState(settings.value("MainSplitter").toByteArray()); settings.endGroup(); } ////////////////////////////////////////////////////////////////////////// FilePickerDialog::~FilePickerDialog() { } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::OnFinished() { QSettings settings; settings.beginGroup("FilePickerDialog"); settings.setValue("Geometry", saveGeometry()); settings.setValue("MainSplitter", m_Ui.MainSplitter->saveState()); settings.endGroup(); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::OnPathSelected(const QString& path) { if (QtUtil::NormalizeFileName(path) != QtUtil::NormalizeFileName(m_Ui.FileName->text())) m_Ui.FileName->setText(QDir::toNativeSeparators(path)); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::OnPathEdited(const QString& path) { bool isValid = false; bool isFile = false; bool isAbs = false; if (!path.isEmpty()) { QString absPath = Project::GetInstance()->GetAbsoluteFileName(path.trimmed()); QFileInfo fileInfo(absPath); if (fileInfo.exists()) { m_Ui.ProjectTree->SetCurrentFile(Project::GetInstance()->GetRelativeFileName(absPath)); isValid = true; isFile = fileInfo.isFile() && m_FilterExtensions.contains(fileInfo.suffix().toLower()); isAbs = QDir::isAbsolutePath(path); } } m_Ui.OkButton->setEnabled(isFile); QPalette palette = m_Ui.FileName->palette(); QColor textColor = Qt::black; if (isValid) { if (isAbs) textColor = Qt::red; } else textColor = Qt::darkGray; palette.setColor(QPalette::Active, QPalette::Text, textColor); m_Ui.FileName->setPalette(palette); } ////////////////////////////////////////////////////////////////////////// QString FilePickerDialog::GetCurrentFile() const { return QDir::fromNativeSeparators(m_Ui.FileName->text().trimmed()); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::SetCurrentFile(const QString& fileName) { m_Ui.FileName->setText(QDir::fromNativeSeparators(fileName)); } ////////////////////////////////////////////////////////////////////////// void FilePickerDialog::SetFilterTypes(const QString& types) { m_FilterTypes = types.split(";", QString::SkipEmptyParts); QtUtil::FileTypeListToExtList(types, m_FilterExtensions); QStringList masks; qforeach (const QString& ext, m_FilterExtensions) { masks << "*." + ext; } m_Ui.ProjectTree->SetFilters(masks); } } // namespace Armed
30.774194
96
0.604036
retrowork
3585618ed34f4961ccc77b2e7dd5e0f6ecb06a89
885
cpp
C++
SPOJ/FENCE1 - Build a Fence.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
6
2018-11-26T02:38:07.000Z
2021-07-28T00:16:41.000Z
SPOJ/FENCE1 - Build a Fence.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
1
2021-05-30T09:25:53.000Z
2021-06-05T08:33:56.000Z
SPOJ/FENCE1 - Build a Fence.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
4
2020-04-16T07:15:01.000Z
2020-12-04T06:26:07.000Z
/*FENCE1 - Build a Fence #math There is a wall in your backyard. It is so long that you can’t see its endpoints. You want to build a fence of length L such that the area enclosed between the wall and the fence is maximized. The fence can be of arbitrary shape, but only its two endpoints may touch the wall. Input The input consists of several test cases. For every test case, there is only one integer L (1<=L<=100), indicating the length of the fence. The input ends with L=0. Output For each test case, output one line containing the largest area. Your answer should be rounded to 2 digits after the decimal point. Example Input: 1 0 Output: 0.16 */ #include <cmath> #include <iomanip> #include <iostream> int main() { for (int l; std::cin >> l && l !=0;) { std::cout << std::setprecision(2) << std::fixed << l*l / (std::atan(1) * 8) << std::endl; } }
23.918919
276
0.693785
ravirathee
358565336bad30a16789c0389cdf37d969dfd7d7
478
hpp
C++
include/SSVOpenHexagon/Data/PackData.hpp
mehlon/SSVOpenHexagon
a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Data/PackData.hpp
mehlon/SSVOpenHexagon
a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Data/PackData.hpp
mehlon/SSVOpenHexagon
a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2015 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef HG_PACKDATA #define HG_PACKDATA namespace hg { struct PackData { std::string id, name; float priority; PackData( const std::string& mId, const std::string& mName, float mPriority) : id{mId}, name{mName}, priority{mPriority} { } }; } #endif
20.782609
78
0.60251
mehlon
3586b02ccae01f85d6954123e95c028070b1f195
4,407
cpp
C++
MyThirthyHomeWork/for.1/for.1.cpp
pashak14/CppHomeWork
861bf1241800f2c6a0fb782738554d617de89599
[ "MIT" ]
null
null
null
MyThirthyHomeWork/for.1/for.1.cpp
pashak14/CppHomeWork
861bf1241800f2c6a0fb782738554d617de89599
[ "MIT" ]
null
null
null
MyThirthyHomeWork/for.1/for.1.cpp
pashak14/CppHomeWork
861bf1241800f2c6a0fb782738554d617de89599
[ "MIT" ]
1
2020-12-14T11:52:04.000Z
2020-12-14T11:52:04.000Z
#include <iostream> using namespace std; void variant1(), variant2(), variant3(), variant4(), variant5(), variant6(), variant7(), variant8(), variant9(), variant10(); int main() { int numEx; setlocale(0, ""); while (true) { cout << "\nВведите вариант узора (0 - 10): " << endl; cin >> numEx; switch (numEx) { case 1: variant1(); break; case 2: variant2(); break; case 3: variant3(); break; case 4: variant4(); break; case 5: variant5(); break; case 6: variant6(); break; case 7: variant7(); break; case 8: variant8(); break; case 9: variant9(); break; case 10: variant10(); break; } } } void variant1() { int i = 0, j = 0, k = 0, col = 10; while (0 < col) { i++; col -= 1; j = 0; while (j <= col) { j++; cout << " * "; } cout << endl; k = 0; while (k < i) { cout << " "; k++; } } } void variant2() { int i = 0, j, col = 10; while (i < col) { i++; j = 0; while (j < i) { j++; cout << " * "; } cout << endl; } } void variant3() { int i = 0, j, k, b, col = 10; while (0 <= col ) { i++; col -= 2; j = 0; while (j <= col) { j++; cout << " * "; } cout << endl; k = 0; while (k < i) { cout << " "; k++; } } } void variant4() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((!(i >= n) && !(i + n <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant5() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((!(i >= n) && !(i + n <= col)) || ((i >= n) && (i + n <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant7() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if (i <= n && (i + n ) <= col) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant6() { int n = 0, i = 0, col = 9; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((i <= n && (i + n - 1) <= col) || (i >= n && !(i + n <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant8() { int n = 0, i = 0, col = 10; n = 1; while (n <= col) { i = 1; while (i <= col) { if ((i >= n && !(i + n - 1 <= col))) { cout << " * "; } else { cout << " "; } i++; } cout << endl; n++; } } void variant10() { int i = 0, j = 0, k = 0, col = 10; while (0 < col) { i++; col -= 1; k = 0; while (k < i - 1) { k++; cout << " * "; } cout << endl; j = 0; while (j <= col) { cout << " "; j++; } } } void variant9() { int i = 0, j, k, col = 10; while (i < col) { i++; k = i; while (k <= col) { k++; cout << " * "; } cout << endl; } }
17.557769
81
0.256637
pashak14
3587c88b7d11dc508d9a24ec8758b390be867c65
20,157
cc
C++
src/core/rnn/CustomLayers.cc
arjun-k-r/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
34
2017-03-01T05:49:17.000Z
2022-01-01T15:30:06.000Z
src/core/rnn/CustomLayers.cc
arjun-k-r/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
1
2018-12-19T17:02:52.000Z
2018-12-19T17:02:52.000Z
src/core/rnn/CustomLayers.cc
junosan/Sibyl
ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb
[ "Apache-2.0" ]
24
2017-09-19T01:51:50.000Z
2022-02-04T19:53:16.000Z
/* Copyright 2017 Hosang Yoon 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 "CustomLayers.h" #include <string> namespace fractal { void AddLstmLayer_ForgetOneInit(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const bool selfLoop, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size); ConnParam connParam(CONN_IDENTITY); connParam.srcRangeFrom = 0; connParam.srcRangeTo = size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam); rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SQUASH", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SQUASH", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY); /* Bias */ ConnParam initParam(initWeightParam); initParam.dstRangeFrom = 0; initParam.dstRangeTo = size - 1; rnn.AddConnection(biasLayer, prefix + "INPUT", initParam); initParam.dstRangeFrom += size; initParam.dstRangeTo += size; rnn.AddConnection(biasLayer, prefix + "INPUT", initParam); InitWeightParamUniform oneInitParam; oneInitParam.a = 1.0; oneInitParam.b = 1.0; oneInitParam.isValid = true; ConnParam oneParam(oneInitParam); oneParam.dstRangeFrom = 2 * size; oneParam.dstRangeTo = 3 * size - 1; rnn.AddConnection(biasLayer, prefix + "INPUT", oneParam); initParam.dstRangeFrom += 2 * size; initParam.dstRangeTo += 2 * size; rnn.AddConnection(biasLayer, prefix + "INPUT", initParam); /* Peephole connections */ rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY); if(selfLoop == true) { rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } void AddResGateLayer(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long size) { // out = in_r * sig(k) + in_1 * (1 - sig(k)) // in_r : residual (output of layer just below) // in_1 : identity (input of layer just below) // assumes in_r.size == in_1.size const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT_R" , ACT_LINEAR , AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_1" , ACT_LINEAR , AGG_MULT, size); rnn.AddLayer(prefix + "SWITCH_R", ACT_SIGMOID , AGG_SUM , size); rnn.AddLayer(prefix + "SWITCH_1", ACT_ONE_MINUS_LINEAR, AGG_SUM , size); rnn.AddLayer(prefix + "OUTPUT" , ACT_LINEAR , AGG_SUM , size); InitWeightParamUniform minusOne; // biased towards identity initially minusOne.a = -1.0; minusOne.b = -1.0; minusOne.isValid = true; rnn.AddConnection(biasLayer , prefix + "SWITCH_R", minusOne); rnn.AddConnection(prefix + "SWITCH_R", prefix + "SWITCH_1", CONN_IDENTITY); rnn.AddConnection(prefix + "SWITCH_R", prefix + "INPUT_R", CONN_IDENTITY); rnn.AddConnection(prefix + "SWITCH_1", prefix + "INPUT_1", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_R", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_1", prefix + "OUTPUT", CONN_IDENTITY); } void AddLstmLayer_LearnInit(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_SUM, size); // mult -> sum rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_SUM, size); // mult -> sum // switch between init & prev states // reset = 1. (use init states) or 0. (use prev states) { rnn.AddLayer(prefix + "RESET", ACT_LINEAR , AGG_SUM, 1); rnn.AddLayer(prefix + "CARRY", ACT_ONE_MINUS_LINEAR, AGG_SUM, 1); rnn.AddConnection(prefix + "RESET", prefix + "CARRY", CONN_IDENTITY); rnn.AddLayer(prefix + "MEMORY_CELL_INIT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL_PREV", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_INIT" , ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_PREV" , ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(biasLayer, prefix + "MEMORY_CELL_INIT", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_INIT" , initWeightParam); rnn.AddConnection(prefix + "RESET", prefix + "MEMORY_CELL_INIT", CONN_BROADCAST); rnn.AddConnection(prefix + "CARRY", prefix + "MEMORY_CELL_PREV", CONN_BROADCAST); rnn.AddConnection(prefix + "RESET", prefix + "OUTPUT_INIT" , CONN_BROADCAST); rnn.AddConnection(prefix + "CARRY", prefix + "OUTPUT_PREV" , CONN_BROADCAST); rnn.AddConnection(prefix + "MEMORY_CELL_INIT", prefix + "MEMORY_CELL.DELAYED", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL_PREV", prefix + "MEMORY_CELL.DELAYED", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_INIT" , prefix + "OUTPUT.DELAYED" , CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_PREV" , prefix + "OUTPUT.DELAYED" , CONN_IDENTITY); } ConnParam connParam(CONN_IDENTITY); connParam.srcRangeFrom = 0; connParam.srcRangeTo = size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam); rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL_PREV", {CONN_IDENTITY, delayAmount}); // .DELAYED -> _PREV rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SQUASH", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SQUASH", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY); /* Bias */ rnn.AddConnection(biasLayer, prefix + "INPUT", initWeightParam); /* Peephole connections */ rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY); // selfLoop { rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT_PREV", {CONN_IDENTITY, delayAmount}); // .DELAYED -> _PREV rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } void AddLstmLayer_DSigmoidOut(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const bool selfLoop, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_SIGMOID", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_ONE_MINUS_SIGMOID", ACT_ONE_MINUS_LINEAR, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT_DSIGMOID", ACT_LINEAR, AGG_MULT, size); rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size); rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size); ConnParam connParam(CONN_IDENTITY); connParam.srcRangeFrom = 0; connParam.srcRangeTo = size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam); connParam.srcRangeFrom += size; connParam.srcRangeTo += size; rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam); rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SIGMOID", prefix + "OUTPUT_ONE_MINUS_SIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_SIGMOID", prefix + "OUTPUT_DSIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_ONE_MINUS_SIGMOID", prefix + "OUTPUT_DSIGMOID", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_DSIGMOID", prefix + "OUTPUT", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY); /* Bias */ rnn.AddConnection(biasLayer, prefix + "INPUT", initWeightParam); /* Peephole connections */ rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY); rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam); rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam); rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY); rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY); if(selfLoop == true) { rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } void AddOELstmLayer(Rnn &rnn, const std::string &name, const std::string &biasLayer, const unsigned long delayAmount, const unsigned long size, const bool selfLoop, const InitWeightParam &initWeightParam) { const std::string prefix = name + "."; verify(size % 2 == 0); rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size); // 1D weights (input bias & peephole) are added by the internal layers // 2D weights (below-to-input & feedback) are added outside basicLayers::AddFastLstmLayer(rnn, prefix + "OLSTM", biasLayer, 1, size / 2, false, initWeightParam); AddLstmLayer_DSigmoidOut (rnn, prefix + "ELSTM", biasLayer, 1, size / 2, false, initWeightParam); /* Connect "RESET" to * "OLSTM.MEMORY_CELL.DELAYED" and "ELSTM.MEMORY_CELL.DELAYED" directly * * Otherwise, cannot function with "RESET" removed for inference */ rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_SUM, size); ConnParam srcParam(CONN_IDENTITY); srcParam.srcRangeFrom = 0; srcParam.srcRangeTo = 2 * size - 1; rnn.AddConnection(prefix + "INPUT", prefix + "OLSTM.INPUT", srcParam); srcParam.srcRangeFrom += 2 * size; srcParam.srcRangeTo += 2 * size; rnn.AddConnection(prefix + "INPUT", prefix + "ELSTM.INPUT", srcParam); // // relay reset signal // rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_SUM, size); // // srcParam.srcRangeFrom = 0; // srcParam.srcRangeTo = size / 2 - 1; // rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", // prefix + "OLSTM.MEMORY_CELL.DELAYED", srcParam); // // srcParam.srcRangeFrom += size / 2; // srcParam.srcRangeTo += size / 2; // rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", // prefix + "ELSTM.MEMORY_CELL.DELAYED", srcParam); ConnParam dstParam(CONN_IDENTITY); dstParam.dstRangeFrom = 0; dstParam.dstRangeTo = size / 2 - 1; rnn.AddConnection(prefix + "OLSTM.OUTPUT", prefix + "OUTPUT", dstParam); dstParam.dstRangeFrom += size / 2; dstParam.dstRangeTo += size / 2; rnn.AddConnection(prefix + "ELSTM.OUTPUT", prefix + "OUTPUT", dstParam); if(selfLoop == true) { rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size); rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount}); rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam); } } }
49.283619
126
0.674406
arjun-k-r
358c3223168f206b6db3f4686d2072394f2d571e
648
cpp
C++
PAT/B1011.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/B1011.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/B1011.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
#include<stdio.h> using namespace std; long long A,B,C; bool check(){ if(A>0 && B>0 && C>0) return A>C-B; if(A<0 && B<0 && C<0) return A>C-B; if(A>0 && B>0 && C<0) return true; if(A<0 && B<0 && C>0) return false; return A+B>C; } int main(void) { // freopen("in.txt","r",stdin); int T; scanf("%d",&T); for(int I=1;I<=T;I++){ printf("Case #%d: ",I); scanf("%lld%lld%lld",&A,&B,&C); if(check()) puts("true"); else puts("false"); } return 0; } /* 4 1 2 3 2 3 4 2147483647 0 2147483646 0 -2147483648 -2147483647 Case #1: false Case #2: true Case #3: true Case #4: false */
16.615385
39
0.512346
iphelf
358d183c0e807d86a5d58dda48fdd53de75f73d3
11,928
cpp
C++
src/kernel.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/kernel.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
src/kernel.cpp
Unified-Projects/Unified-OS
89912adc1ed9ec35753fe0f4fa35f03d30ec66a2
[ "BSD-2-Clause" ]
null
null
null
#include <common/stdint.h> #include <boot/bootinfo.h> #include <pointers.h> #include <IO/APIC/apic.h> //COMMENT #include <smp/smp.h> //COMMENT #include <gdt/gdt.h> #include <gdt/tss.h> //COMMENT #include <paging/PageTableManager.h> #include <paging/PageFrameAllocator.h> #include <memory/memory.h> #include <memory/heap.h> #include <process/Scheduler/Scheduler.h> //Comment (INCLUDES PROCESSES) #include <interrupts/interrupts.h> #include <exceptions/exceptions.h> #include <interrupts/syscalls.h> //Comment #include <interrupts/timer/pit.h> #include <drivers/Driver.h> #include <drivers/Intel/AHCI/AHCI.h> #include <IO/DeviceManager/DeviceManager.h> //Comment #include <fs/VolumeManager.h> //Comment #include <drivers/Input/PS2KeyboardDriver.h> #include <drivers/Input/PS2MouseDriver.h> #include <common/stdio.h> #include <common/cstring.h> using namespace UnifiedOS; using namespace UnifiedOS::Boot; using namespace UnifiedOS::GlobalDescriptorTable; using namespace UnifiedOS::Paging; using namespace UnifiedOS::Memory; using namespace UnifiedOS::Processes; using namespace UnifiedOS::Interrupts; using namespace UnifiedOS::Exceptions; using namespace UnifiedOS::Interrupts::Syscalls; using namespace UnifiedOS::Interrupts::Timer; using namespace UnifiedOS::Drivers; using namespace UnifiedOS::Devices; using namespace UnifiedOS::FileSystem; //SOMETHING TO HAVE A LOOK INTO FOR MAXIMUM MEMORY EFFICIENCY //Look over code and make sure all needed * are kept but all un needed get removed // (delete pointer) // // // // #include <files/tga.h> #include <interrupts/syscall.h> void InitVolumes(DriverManager* driverM){ //NOTE //TRY TO SETUP WITH LOOKING TO SEE IF THE VOLUME //Locate Driver Driver* driver = driverM->FindDriver("ACPI 1.0 Driver"); //Ensure Driver Found if(driver != nullptr){ //Convert to AHCI if(driver->MainObject != nullptr){ Drivers::AHCI::AHCIDriver* AHCIdriver = (Drivers::AHCI::AHCIDriver*)(driver->MainObject); //Look at ports for(int p = 0; p < AHCIdriver->portCount; p++){ //Find Disks if(AHCIdriver->Ports[p]->portType == AHCI::AHCIPort::PortType::SATA){ //Mount __FS_VOLUME_MANAGER__->MountVolume(AHCIdriver->Ports[p]); } } } } } void DrawBootScreen(){ Clear(0x00); //Read the icon file GeneralFile* File = syscall(6, "B:/UnifiedIcon.tga"); //If the file is found displat the logo if(File->Found){ uint8_t* Buffer = (uint8_t*)Memory::malloc(__BOOT__BootContext__->framebuffer->BufferSize); File->Disk->Read((File->Sectors[0]*512), File->FileSize, Buffer); //Recode this! TGA_Image image = TGA().GetImage(Buffer); Memory::free(Buffer); //Work out system center uint64_t xoff = (__BOOT__BootContext__->framebuffer->Width / 2) - (image.header.width / 2); uint64_t xoffText = (__BOOT__BootContext__->framebuffer->Width / 2) - ((strlen("Loading System") * 16) / 4); uint64_t xoffText1 = (__BOOT__BootContext__->framebuffer->Width / 2) - ((strlen("Unified OS: Version 0.0.1") * 16) / 4); uint64_t yoff = (__BOOT__BootContext__->framebuffer->Height / 4) - (image.header.width / 2); uint64_t yoffText = ((__BOOT__BootContext__->framebuffer->Height / 2)) - 8; for(int y = image.header.height - 1; y >= 0; y--){ for(int x = image.header.width - 1; x >= 0; x--){ putPix(x + xoff, (image.header.height - 1) - y + yoff, image.Buffer[(y * image.header.width) + x]); } } //Print boot SetPosX(xoffText); SetPosY(yoffText); printf("Loading System\n"); SetPosX(xoffText1); printf("Unified OS: Version 0.0.1"); SetPosX(0); SetPosY(0); //Delete Image Data after delete image.Buffer; } } void KernelStage2(){ //Volumes InitVolumes(Pointers::Drivers::DriverManager); //GP FAULT CAUSED HERE... ^ on real hardware // PS2Init(); //Real hardware is to be imagined right now with how this works //Create Boot Screen DrawBootScreen(); // TestTGA(); //Load System Modules while (true) { /* code */ } } //For locking the memory at the kernel extern uint64_t _KernelStart; extern uint64_t _KernelEnd; void InitialisePaging(){ //Entries (Pages) uint64_t mMapEntries = __BOOT__BootContext__->mMapSize / __BOOT__BootContext__->DescriptorSize; //Load Memory To Page Frame Allocator __PAGING__PFA_GLOBAL = PageFrameAllocator(); __PAGING__PFA_GLOBAL.ReadEFIMemoryMap(__BOOT__BootContext__->mMap, __BOOT__BootContext__->mMapSize, __BOOT__BootContext__->DescriptorSize); uint64_t SizeOfKernel = (uint64_t)&_KernelEnd - (uint64_t)&_KernelStart; uint64_t PageCountOfKernel = (uint64_t)SizeOfKernel / 0x1000 + 1; //Lock memory pages at kernel positions __PAGING__PFA_GLOBAL.LockPages(&_KernelStart, PageCountOfKernel); //Get a Page for the Page Table Manager PageTable* PML4 = (PageTable*)__PAGING__PFA_GLOBAL.RequestPage(); //Fill it with zero to stop any issues with default memset(PML4, 0, 0x1000); //Setup the page table manager __PAGING__PTM_GLOBAL = PageTableManager(PML4); //Map memory addresses to default for(uint64_t t = 0; t < __PAGING__TotalMemorySize__; t+=0x1000){ //We do this in 4KiB Pages __PAGING__PTM_GLOBAL.MapMemory((void*)t, (void*)t); } //Lock Framebuffer Pages uint64_t FramebufferBase = (uint64_t)__BOOT__BootContext__->framebuffer->BaseAddress; uint64_t FramebufferSize = (uint64_t)__BOOT__BootContext__->framebuffer->BufferSize + 0x1000; //We add this is a padding __PAGING__PFA_GLOBAL.LockPages((void*)FramebufferBase, FramebufferSize / 0x1000 + 1); // +1 just incase not entire fit //Map the framebuffer address for(uint64_t t = FramebufferBase; t < FramebufferBase + FramebufferSize; t+=4096){ //We do this in 4KiB Pages __PAGING__PTM_GLOBAL.MapMemory((void*)t, (void*)t); } //Load the Page Table asm("mov %0, %%cr3" : : "r" (PML4)); } // inline void WaitSignal() { // IO::Port8Bit CommandPort(0x64); // int timeout = 10000; // while (timeout--) // if ((CommandPort.Read() & 0x2) != 0x2) // return; // } // // template <bool isMouse> inline void WaitData() { // IO::Port8Bit CommandPort(0x64); // int timeout = 10000; // while (timeout--) // if ((CommandPort.Read() & 0x21) == (isMouse ? 0x21 : 0x1)) // return; // } // // void PS2Init(){ // IO::Port8Bit DataPort(0x60); // IO::Port8Bit CommandPort(0x64); // IO::Port8Bit PITMaster(0x20); // // // Start by disabling both ports // WaitSignal(); // CommandPort.Write(0xAD); // WaitSignal(); // CommandPort.Write(0xA7); // // DataPort.Read(); // Discard any data // // WaitSignal(); // CommandPort.Write(0x20); // WaitData<false>(); // uint8_t status = PITMaster.Read(); // // WaitSignal(); // CommandPort.Write(0xAE); // WaitSignal(); // CommandPort.Write(0xA8); // // // Enable interrupts, enable keyboard and mouse clock // status = ((status & ~0x30) | 3); // WaitSignal(); // CommandPort.Write(0x60); // WaitSignal(); // CommandPort.Write(status); // WaitData<false>(); // DataPort.Read(); // } extern "C" void kernelMain(BootInfo* bootInfo) { __BOOT__BootContext__ = bootInfo; //Blank Screen Clear(0x00); //Detect SMP cores test //I Dont know why (I think a delay effect) but whenever I remove the prints //It stops working??? printf("SMP APIC: \n"); IO::APIC::ReadAPIC(); printf("Found "); printf(to_string((int64_t)IO::APIC::CoreCount)); printf(", IOAPIC "); printf(to_hstring(IO::APIC::IOAPIC_PTR)); printf(", LAPIC "); printf(to_hstring(IO::APIC::LAPIC_PTR)); printf(", Processor IDs: "); for(int i = 0; i < IO::APIC::CoreCount; i++){ printf(to_string((int64_t)IO::APIC::LAPIC_IDs[i])); printf(" "); } printf("\n"); //Memory InitialisePaging(); //GDT LoadGDT(&__GDTDesc); //Heap //We use a high address to not interrupt other addresses //Yes this can lead to issues such as what if we reach the heap and overwrite it //Im not sure how I can fix that its just how it is. Well I suppose the pages will be locked //So its not too much of an issue. InitialiseHeap((void*)0x0000100000000000, 0xFF); //Interrupts (Default) Pointers::Interrupts::Interrupts = new InterruptManager(); //Syscalls Pointers::Interrupts::Syscalls::Syscalls = new SyscallHandler(Pointers::Interrupts::Interrupts); //Intialise Exceptions Pointers::Exceptions::Exceptions = new ExceptionManager(Pointers::Interrupts::Interrupts); //Drivers Pointers::Drivers::DriverManager = new DriverManager(); //Devices Pointers::Devices::DeviceManager = new DeviceManager(Pointers::Drivers::DriverManager); // //Keyboard Driver MAKE USING new // PrintfKeyboardEventHandler KeyboardHandler; // PS2KeyboardDriver keyboard(Pointers::Interrupts::Interrupts, &KeyboardHandler); // Pointers::Drivers::DriverManager->AddDriver(&keyboard); // //Mouse Driver MAKE USING new // MouseToScreen MouseHandler; // PS2MouseDriver mouse(Pointers::Interrupts::Interrupts, &MouseHandler); // Pointers::Drivers::DriverManager->AddDriver(&mouse); //Activate Drivers //SETUP NOTE: Make it so when a driver is called to activate it check if already ative and ignores if active //To allow for more drivers to be loaded after this boot Pointers::Drivers::DriverManager->ActivateAll(); //PIT __TIMER__PIT__ = new PIT(Pointers::Interrupts::Interrupts); __TIMER__PIT__->SetFrequency(1000); //INACURRATE //ERRORS WITH PIT MAPPING ON MODERN HARDWARE //Dissable PIC Pointers::Interrupts::Interrupts->DissablePIC(); //APIC NOTE //Sometimes the interrupts do not register which is an issue (With PIT) //As this will cause the smp to fail to initialise //However this only seems to be with qemu not real hardware //APIC Inits //Spurious Interrupt IO::APIC::SpuriousInterrupHandler* SpuriousInterupts = new IO::APIC::SpuriousInterrupHandler(Pointers::Interrupts::Interrupts); IO::APIC::LApicInit(); IO::APIC::IntitateIO(); IO::APIC::MapLegacyIRQ(0x01); //PS2 Keyboard IO::APIC::MapLegacyIRQ(0x0C); //PS2 Mouse //Interrupts activation Pointers::Interrupts::Interrupts->Activate(); //SMP //Will now boot all the cpu's that are not booted. //64-Bit gets toggled with gdt //Interrupts are synced SMP::Intitialise(); printf("All "); printf(to_string((int64_t)SMP::ActiveCPUs)); printf(" Have Been Booted!\n\n"); //Issues here with real hardware: //Either SMP fails to exit (I presume TSS) //Or somthing wrong with the preparation of the SMP Trampoline just not working (well working but breaking everything else) //Scheduling has issues with process swapping and all of that swaps //Processes Scheduling::IntialiseScheduler(Pointers::Interrupts::Interrupts, (uint64_t)KernelStage2); //CAUSES ISSUES (REAL HARDWARE Div by zero Exception) // Process* proctest = Scheduling::__SCHEDULER__->NewProcess("TestProcess", (uint64_t)TaskA, 0); //All issues I thought are actually TSS issues //TYPES //User space (NEED TO IMPLEMENT) (https://wiki.osdev.org/Getting_to_Ring_3) // This will also need to link to system calls for userspace to reach //Kernel space (This) // KernelStage2(); while(true){ // printf("Task Kernel...\n"); // asm("hlt"); //Saves performance } }
31.0625
147
0.662726
Unified-Projects
358dd892ae6a47600fdf23472a3f1d53e967a577
2,008
cpp
C++
tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include <new> #include <cassert> #include "uiwayblock.h" #include <QListWidget> #include <QLineEdit> #include <QDoubleSpinBox> #include <QCheckBox> #include <QPushButton> gui::uiblocks::UIWayBlock::UIWayBlock() : lstWays(nullptr), txtWayName(nullptr), dsbWayTotalTime(nullptr), cbWayClosed(nullptr), btnWayAdd(nullptr), btnWayRemove(nullptr), lstWayPoints(nullptr), dsbWayPointX(nullptr), dsbWayPointY(nullptr), btnWayPointAdd(nullptr), btnWayPointRemove(nullptr), btnWayPointMoveBack(nullptr), btnWayPointMoveFront(nullptr) { } void gui::uiblocks::UIWayBlock::init(QWidget* w) { assert(w); this->lstWays = w->findChild<QListWidget*>("lstWays"); assert(this->lstWays); this->txtWayName = w->findChild<QLineEdit*>("txtWayName"); assert(this->txtWayName); this->dsbWayTotalTime = w->findChild<QDoubleSpinBox*>("dsbWayTotalTime"); assert(this->dsbWayTotalTime); this->cbWayClosed = w->findChild<QCheckBox*>("cbWayClosed"); assert(this->cbWayClosed); this->btnWayAdd = w->findChild<QPushButton*>("btnWayAdd"); assert(this->btnWayAdd); this->btnWayRemove = w->findChild<QPushButton*>("btnWayRemove"); assert(this->btnWayRemove); this->lstWayPoints = w->findChild<QListWidget*>("lstWayPoints"); assert(this->lstWayPoints); this->dsbWayPointX = w->findChild<QDoubleSpinBox*>("dsbWayPointX"); assert(this->dsbWayPointX); this->dsbWayPointY = w->findChild<QDoubleSpinBox*>("dsbWayPointY"); assert(this->dsbWayPointY); this->btnWayPointAdd = w->findChild<QPushButton*>("btnWayPointAdd"); assert(this->btnWayPointAdd); this->btnWayPointRemove = w->findChild<QPushButton*>("btnWayPointRemove"); assert(this->btnWayPointRemove); this->btnWayPointMoveBack = w->findChild<QPushButton*>("btnWayPointMoveBack"); assert(this->btnWayPointMoveBack); this->btnWayPointMoveFront = w->findChild<QPushButton*>("btnWayPointMoveFront"); assert(this->btnWayPointMoveFront); } gui::uiblocks::UIWayBlock::~UIWayBlock() { }
32.387097
84
0.731076
mamontov-cpp
358f0675afa1d80c560a1dec6fb0401f5642c3dc
3,833
cpp
C++
opengl/hello_3d.cpp
xiwan/opengl
1e30baf40debd00b55252fc14d0e6b909c94bfbd
[ "MIT" ]
1
2019-02-22T03:11:28.000Z
2019-02-22T03:11:28.000Z
opengl/hello_3d.cpp
xiwan/opengl
1e30baf40debd00b55252fc14d0e6b909c94bfbd
[ "MIT" ]
null
null
null
opengl/hello_3d.cpp
xiwan/opengl
1e30baf40debd00b55252fc14d0e6b909c94bfbd
[ "MIT" ]
null
null
null
#include "./headers/shader.h" #include "./headers/opengl_common.h" #define STB_IMAGE_IMPLEMENTATION_2 #include "./headers/stb_image.h" int hello_3d() { GLFWwindow* window = prepareWindow("hello_3d"); if (!window) { return -1; } Shader textureShader("./shaders/3d.shader.vs", "./shaders/3d.shader.fs"); float textureVertices[] = { // positions // colors // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; // Vertex input unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(textureVertices), textureVertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); unsigned int texture1, texture2; texture1 = loadTexture("./pics/container.jpg"); texture2 = loadTexture("./pics/awesomeface.png"); textureShader.use(); textureShader.setInt("texture1", 0); textureShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); textureShader.use(); float timeValue = glfwGetTime(); float sinValue = sin(timeValue); glm::mat4 trans = glm::mat4(1.0f); trans = glm::translate(trans, glm::vec3(sinValue, -0.5f, 0.0f)); trans = glm::rotate(trans, timeValue, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = glm::mat4(1.0f); glm::mat4 projection = glm::mat4(1.0f); //model = glm::translate(model, glm::vec3(sinValue, -0.5f, 0.0f)); model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f)); //model = glm::rotate(model, timeValue, glm::vec3(0.0f, 0.0f, 1.0f)); // note that we're translating the scene in the reverse direction of where we want to move // Note that in normalized device coordinates OpenGL actually uses a left-handed system view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f)); projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); //textureShader.setMatrix4("sinValue", &sinValue); textureShader.setMat4("model", model); textureShader.setMat4("view", view); textureShader.setMat4("projection", projection); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
32.760684
105
0.651448
xiwan
35969c7d3d5bf587b5c69a49b5535fe6a20368a1
4,970
hpp
C++
libraries/app/include/scorum/app/detail/advertising_api.hpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
libraries/app/include/scorum/app/detail/advertising_api.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
libraries/app/include/scorum/app/detail/advertising_api.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#pragma once #include <scorum/chain/services/advertising_property.hpp> #include <scorum/chain/services/account.hpp> #include <scorum/chain/services/budgets.hpp> #include <scorum/chain/services/dynamic_global_property.hpp> #include <scorum/app/scorum_api_objects.hpp> #include <scorum/app/advertising_api.hpp> #include <boost/range/algorithm/transform.hpp> #include <boost/range/algorithm/sort.hpp> namespace scorum { namespace app { class advertising_api::impl { public: impl(chain::database& db, chain::data_service_factory_i& services) : _db(db) , _services(services) , _adv_service(_services.advertising_property_service()) , _account_service(_services.account_service()) , _banner_budget_service(_services.banner_budget_service()) , _post_budget_service(_services.post_budget_service()) , _dyn_props_service(_services.dynamic_global_property_service()) { } fc::optional<account_api_obj> get_moderator() const { auto& adv_property_object = _adv_service.get(); if (adv_property_object.moderator == SCORUM_MISSING_MODERATOR_ACCOUNT) return {}; auto& moderator_account = _account_service.get_account(adv_property_object.moderator); return account_api_obj(moderator_account, _db); } std::vector<budget_api_obj> get_user_budgets(const std::string& user) const { auto post_budgets = _post_budget_service.get_budgets(user); auto banner_budgets = _banner_budget_service.get_budgets(user); std::vector<budget_api_obj> ret; ret.reserve(post_budgets.size() + banner_budgets.size()); boost::transform(post_budgets, std::back_inserter(ret), [](const post_budget_object& o) { return budget_api_obj(o); }); boost::transform(banner_budgets, std::back_inserter(ret), [](const banner_budget_object& o) { return budget_api_obj(o); }); boost::sort(ret, [](const budget_api_obj& l, const budget_api_obj& r) { return l.created > r.created; }); return ret; } fc::optional<budget_api_obj> get_budget(const uuid_type& uuid, budget_type type) const { switch (type) { case budget_type::post: return get_budget(_post_budget_service, uuid); case budget_type::banner: return get_budget(_banner_budget_service, uuid); } FC_THROW("unreachable"); } std::vector<budget_api_obj> get_current_winners(budget_type type) const { switch (type) { case budget_type::post: return get_current_winners(_post_budget_service); case budget_type::banner: return get_current_winners(_banner_budget_service); } FC_THROW("unreachable"); } std::vector<percent_type> get_auction_coefficients(budget_type type) const { switch (type) { case budget_type::post: return std::vector<percent_type>{ _adv_service.get().auction_post_coefficients.begin(), _adv_service.get().auction_post_coefficients.end() }; case budget_type::banner: return std::vector<percent_type>{ _adv_service.get().auction_banner_coefficients.begin(), _adv_service.get().auction_banner_coefficients.end() }; } FC_THROW("unreachable"); } private: template <budget_type budget_type_v> fc::optional<budget_api_obj> get_budget(const chain::adv_budget_service_i<budget_type_v>& budget_service, const uuid_type& uuid) const { fc::optional<budget_api_obj> ret; if (budget_service.is_exists(uuid)) ret = budget_service.get(uuid); return ret; } template <budget_type budget_type_v> std::vector<budget_api_obj> get_current_winners(const chain::adv_budget_service_i<budget_type_v>& budget_service) const { using object_type = chain::adv_budget_object<budget_type_v>; auto head_block_time = _dyn_props_service.get().time; const auto& auction_coeffs = _adv_service.get().get_auction_coefficients<budget_type_v>(); auto budgets = budget_service.get_top_budgets(head_block_time, auction_coeffs.size()); std::vector<budget_api_obj> ret; ret.reserve(auction_coeffs.size()); boost::transform(budgets, std::back_inserter(ret), [](const object_type& o) { return budget_api_obj(o); }); return ret; } public: chain::database& _db; chain::data_service_factory_i& _services; chain::advertising_property_service_i& _adv_service; chain::account_service_i& _account_service; chain::banner_budget_service_i& _banner_budget_service; chain::post_budget_service_i& _post_budget_service; chain::dynamic_global_property_service_i& _dyn_props_service; }; } }
34.275862
115
0.673441
scorum
359b6f223ae30af473858429465ad694eddf411e
6,256
cpp
C++
Day1/build/iOS/Preview/src/iOS.QuartzCore.g.cpp
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/src/iOS.QuartzCore.g.cpp
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/src/iOS.QuartzCore.g.cpp
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <iOS.QuartzCore.CATransform3D.h> #include <Uno.Double.h> namespace g{ namespace iOS{ namespace QuartzCore{ // ../../../../../../../usr/local/share/uno/Packages/Experimental.iOS/0.24.0/struct/$.uno(1471) // -------------------------------------------------------------------------------------------- // public extern struct CATransform3D :1471 // { uStructType* CATransform3D_typeof() { static uSStrong<uStructType*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 16; options.ValueSize = sizeof(CATransform3D); options.TypeSize = sizeof(uStructType); type = uStructType::New("iOS.QuartzCore.CATransform3D", options); type->SetFields(0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M11), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M12), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M13), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M14), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M21), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M22), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M23), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M24), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M31), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M32), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M33), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M34), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M41), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M42), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M43), 0, ::g::Uno::Double_typeof(), offsetof(::g::iOS::QuartzCore::CATransform3D, M44), 0); type->Reflection.SetFields(16, new uField("M11", 0), new uField("M12", 1), new uField("M13", 2), new uField("M14", 3), new uField("M21", 4), new uField("M22", 5), new uField("M23", 6), new uField("M24", 7), new uField("M31", 8), new uField("M32", 9), new uField("M33", 10), new uField("M34", 11), new uField("M41", 12), new uField("M42", 13), new uField("M43", 14), new uField("M44", 15)); type->Reflection.SetFunctions(1, new uFunction(".ctor", NULL, (void*)CATransform3D__New1_fn, 0, true, CATransform3D_typeof(), 16, ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof(), ::g::Uno::Double_typeof())); return type; } // public CATransform3D(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) :1473 void CATransform3D__ctor__fn(CATransform3D* __this, double* M111, double* M121, double* M131, double* M141, double* M211, double* M221, double* M231, double* M241, double* M311, double* M321, double* M331, double* M341, double* M411, double* M421, double* M431, double* M441) { __this->ctor_(*M111, *M121, *M131, *M141, *M211, *M221, *M231, *M241, *M311, *M321, *M331, *M341, *M411, *M421, *M431, *M441); } // public CATransform3D New(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) :1473 void CATransform3D__New1_fn(double* M111, double* M121, double* M131, double* M141, double* M211, double* M221, double* M231, double* M241, double* M311, double* M321, double* M331, double* M341, double* M411, double* M421, double* M431, double* M441, CATransform3D* __retval) { *__retval = CATransform3D__New1(*M111, *M121, *M131, *M141, *M211, *M221, *M231, *M241, *M311, *M321, *M331, *M341, *M411, *M421, *M431, *M441); } // public CATransform3D(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) [instance] :1473 void CATransform3D::ctor_(double M111, double M121, double M131, double M141, double M211, double M221, double M231, double M241, double M311, double M321, double M331, double M341, double M411, double M421, double M431, double M441) { uStackFrame __("iOS.QuartzCore.CATransform3D", ".ctor(double,double,double,double,double,double,double,double,double,double,double,double,double,double,double,double)"); M11 = M111; M12 = M121; M13 = M131; M14 = M141; M21 = M211; M22 = M221; M23 = M231; M24 = M241; M31 = M311; M32 = M321; M33 = M331; M34 = M341; M41 = M411; M42 = M421; M43 = M431; M44 = M441; } // public CATransform3D New(double M11, double M12, double M13, double M14, double M21, double M22, double M23, double M24, double M31, double M32, double M33, double M34, double M41, double M42, double M43, double M44) [static] :1473 CATransform3D CATransform3D__New1(double M111, double M121, double M131, double M141, double M211, double M221, double M231, double M241, double M311, double M321, double M331, double M341, double M411, double M421, double M431, double M441) { CATransform3D obj1; obj1.ctor_(M111, M121, M131, M141, M211, M221, M231, M241, M311, M321, M331, M341, M411, M421, M431, M441); return obj1; } // } }}} // ::g::iOS::QuartzCore
57.394495
538
0.646739
sauvikatinnofied
359d83a58dc46b4fa80fded4f093ab723cb9d5a4
1,516
cpp
C++
cplus/Day-Month-Year.cpp
chtld/Programming-and-Algorithm-Course
669f266fc97db9050013ffbb388517667de33433
[ "MIT" ]
2
2019-06-10T11:50:06.000Z
2019-10-14T08:00:41.000Z
cplus/Day-Month-Year.cpp
chtld/Programming-and-Algorithm-Course
669f266fc97db9050013ffbb388517667de33433
[ "MIT" ]
null
null
null
cplus/Day-Month-Year.cpp
chtld/Programming-and-Algorithm-Course
669f266fc97db9050013ffbb388517667de33433
[ "MIT" ]
null
null
null
#include<iostream> int days = 0; int getDayOfWeek(); int getYear(); int getMonth(bool isLeapYear); int main(){ int year = 0, month = 0, dayOfWeek = 0; bool isLeapYear = true; char week[7][10] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; while ((std::cin >> days) && days != -1) { dayOfWeek = getDayOfWeek(); year = getYear(); isLeapYear = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0); month = getMonth(isLeapYear); std::cout << year << "-" << month << "-" << ++days << " " << week[dayOfWeek] << std::endl; } return 0; } int getDayOfWeek(){ int dayOfWeek = 0; dayOfWeek = days % 7; return dayOfWeek; } int getYear(){ int i = 2000; bool isLeapYear = true; while (true) { isLeapYear = (i % 4 == 0 && i % 100 != 0 || i % 400 == 0); if (isLeapYear && days >= 366) { days -= 366; i++; } else if (!isLeapYear && days >= 365) { days -= 365; i++; } else { break; } } return i; } int getMonth(bool isLeapYear){ int pmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int rmonth[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int month = 0; while (true) { if (isLeapYear && days >= rmonth[month]) { days = days - rmonth[month]; month++; } else if (!isLeapYear && days >= pmonth[month]) { days = days - pmonth[month]; month++; } else { break; } } return ++month; }
23.323077
71
0.511214
chtld
359dc15ccb18eb076d57ac1e794a721ab27c673f
215,144
cpp
C++
libraries/wallet/wallet.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
1
2019-06-11T09:00:42.000Z
2019-06-11T09:00:42.000Z
libraries/wallet/wallet.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
null
null
null
libraries/wallet/wallet.cpp
LianshuOne/yoyow-core
fba1274b79f85110febd66aab428473ad75148a7
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <list> #include <boost/version.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm_ext/erase.hpp> #include <boost/range/algorithm/unique.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/random_access_index.hpp> #include <boost/multi_index/tag.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <fc/git_revision.hpp> #include <fc/io/fstream.hpp> #include <fc/io/json.hpp> #include <fc/io/stdio.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/cli.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/crypto/aes.hpp> #include <fc/crypto/hex.hpp> #include <fc/thread/mutex.hpp> #include <fc/thread/scoped_lock.hpp> #include <graphene/app/api.hpp> #include <graphene/chain/asset_object.hpp> #include <graphene/chain/account_object.hpp> #include <graphene/chain/config.hpp> #include <graphene/chain/protocol/fee_schedule.hpp> #include <graphene/utilities/git_revision.hpp> #include <graphene/utilities/key_conversion.hpp> #include <graphene/utilities/string_escape.hpp> #include <graphene/utilities/words.hpp> #include <graphene/wallet/wallet.hpp> #include <graphene/wallet/api_documentation.hpp> #include <graphene/wallet/reflect_util.hpp> #include <graphene/debug_witness/debug_api.hpp> #include <fc/smart_ref_impl.hpp> #ifndef WIN32 # include <sys/types.h> # include <sys/stat.h> #endif #define BRAIN_KEY_WORD_COUNT 16 namespace graphene { namespace wallet { namespace detail { struct operation_result_printer { public: explicit operation_result_printer( const wallet_api_impl& w ) : _wallet(w) {} const wallet_api_impl& _wallet; typedef std::string result_type; std::string operator()(const void_result& x) const; std::string operator()(const object_id_type& oid); std::string operator()(const asset& a); std::string operator()(const advertising_confirm_result& a); }; // BLOCK TRX OP VOP struct operation_printer { private: ostream& out; const wallet_api_impl& wallet; operation_result result; std::string fee(const asset& a) const; public: operation_printer( ostream& out, const wallet_api_impl& wallet, const operation_result& r = operation_result() ) : out(out), wallet(wallet), result(r) {} typedef std::string result_type; template<typename T> std::string operator()(const T& op)const; std::string operator()(const transfer_operation& op)const; std::string operator()(const override_transfer_operation& op)const; std::string operator()(const account_create_operation& op)const; std::string operator()(const asset_create_operation& op)const; }; template<class T> optional<T> maybe_id( const string& name_or_id ) { if( std::isdigit( name_or_id.front() ) ) { try { return fc::variant(name_or_id).as<T>( 1 ); } catch (const fc::exception&) { // not an ID } } return optional<T>(); } fc::ecc::private_key derive_private_key( const std::string& prefix_string, int sequence_number ) { std::string sequence_string = std::to_string(sequence_number); fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string); fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h)); return derived_key; } string normalize_brain_key( string s ) { size_t i = 0, n = s.length(); std::string result; char c; result.reserve( n ); bool preceded_by_whitespace = false; bool non_empty = false; while( i < n ) { c = s[i++]; switch( c ) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': preceded_by_whitespace = true; continue; case 'a': c = 'A'; break; case 'b': c = 'B'; break; case 'c': c = 'C'; break; case 'd': c = 'D'; break; case 'e': c = 'E'; break; case 'f': c = 'F'; break; case 'g': c = 'G'; break; case 'h': c = 'H'; break; case 'i': c = 'I'; break; case 'j': c = 'J'; break; case 'k': c = 'K'; break; case 'l': c = 'L'; break; case 'm': c = 'M'; break; case 'n': c = 'N'; break; case 'o': c = 'O'; break; case 'p': c = 'P'; break; case 'q': c = 'Q'; break; case 'r': c = 'R'; break; case 's': c = 'S'; break; case 't': c = 'T'; break; case 'u': c = 'U'; break; case 'v': c = 'V'; break; case 'w': c = 'W'; break; case 'x': c = 'X'; break; case 'y': c = 'Y'; break; case 'z': c = 'Z'; break; default: break; } if( preceded_by_whitespace && non_empty ) result.push_back(' '); result.push_back(c); preceded_by_whitespace = false; non_empty = true; } return result; } struct op_prototype_visitor { typedef void result_type; int t = 0; flat_map< std::string, operation >& name2op; op_prototype_visitor( int _t, flat_map< std::string, operation >& _prototype_ops ):t(_t), name2op(_prototype_ops) {} template<typename Type> result_type operator()( const Type& op )const { string name = fc::get_typename<Type>::name(); size_t p = name.rfind(':'); if( p != string::npos ) name = name.substr( p+1 ); name2op[ name ] = Type(); } }; class wallet_api_impl { public: api_documentation method_documentation; private: void claim_registered_account(const string& name) { auto it = _wallet.pending_account_registrations.find( name ); FC_ASSERT( it != _wallet.pending_account_registrations.end() ); for (const std::string& wif_key : it->second) if( !import_key( name, wif_key ) ) { // somebody else beat our pending registration, there is // nothing we can do except log it and move on elog( "account ${name} registered by someone else first!", ("name", name) ); // might as well remove it from pending regs, // because there is now no way this registration // can become valid (even in the extremely rare // possibility of migrating to a fork where the // name is available, the user can always // manually re-register) } _wallet.pending_account_registrations.erase( it ); } // after a witness registration succeeds, this saves the private key in the wallet permanently // void claim_registered_witness(const std::string& witness_name) { auto iter = _wallet.pending_witness_registrations.find(witness_name); FC_ASSERT(iter != _wallet.pending_witness_registrations.end()); std::string wif_key = iter->second; // get the list key id this key is registered with in the chain fc::optional<fc::ecc::private_key> witness_private_key = wif_to_key(wif_key); FC_ASSERT(witness_private_key); auto pub_key = witness_private_key->get_public_key(); _keys[pub_key] = wif_key; _wallet.pending_witness_registrations.erase(iter); } fc::mutex _resync_mutex; void resync() { fc::scoped_lock<fc::mutex> lock(_resync_mutex); // this method is used to update wallet_data annotations // e.g. wallet has been restarted and was not notified // of events while it was down // // everything that is done "incremental style" when a push // notification is received, should also be done here // "batch style" by querying the blockchain if( !_wallet.pending_account_registrations.empty() ) { // make a vector of the account names pending registration std::vector<string> pending_account_names = boost::copy_range<std::vector<string> >(boost::adaptors::keys(_wallet.pending_account_registrations)); for(string& name : pending_account_names ) { std::map<std::string,account_uid_type> n = _remote_db->lookup_accounts_by_name( name, 1 ); map<std::string, account_uid_type>::iterator it = n.find(name); if( it != n.end() ) { claim_registered_account(name); } } } if (!_wallet.pending_witness_registrations.empty()) { // make a vector of the owner accounts for witnesses pending registration std::vector<string> pending_witness_names = boost::copy_range<std::vector<string> >(boost::adaptors::keys(_wallet.pending_witness_registrations)); for(string& name : pending_witness_names ) { std::map<std::string,account_uid_type> w = _remote_db->lookup_accounts_by_name( name, 1 ); map<std::string, account_uid_type>::iterator it = w.find(name); if( it != w.end() ) { fc::optional<witness_object> witness_obj = _remote_db->get_witness_by_account(it->second); if (witness_obj) claim_registered_witness(name); } } } } void enable_umask_protection() { #ifdef __unix__ _old_umask = umask( S_IRWXG | S_IRWXO ); #endif } void disable_umask_protection() { #ifdef __unix__ umask( _old_umask ); #endif } void init_prototype_ops() { operation op; for( int t=0; t<op.count(); t++ ) { op.set_which( t ); op.visit( op_prototype_visitor(t, _prototype_ops) ); } return; } map<transaction_handle_type, signed_transaction> _builder_transactions; // if the user executes the same command twice in quick succession, // we might generate the same transaction id, and cause the second // transaction to be rejected. This can be avoided by altering the // second transaction slightly (bumping up the expiration time by // a second). Keep track of recent transaction ids we've generated // so we can know if we need to do this struct recently_generated_transaction_record { fc::time_point_sec generation_time; graphene::chain::transaction_id_type transaction_id; }; struct timestamp_index{}; typedef boost::multi_index_container<recently_generated_transaction_record, boost::multi_index::indexed_by<boost::multi_index::hashed_unique<boost::multi_index::member<recently_generated_transaction_record, graphene::chain::transaction_id_type, &recently_generated_transaction_record::transaction_id>, std::hash<graphene::chain::transaction_id_type> >, boost::multi_index::ordered_non_unique<boost::multi_index::tag<timestamp_index>, boost::multi_index::member<recently_generated_transaction_record, fc::time_point_sec, &recently_generated_transaction_record::generation_time> > > > recently_generated_transaction_set_type; recently_generated_transaction_set_type _recently_generated_transactions; public: wallet_api& self; wallet_api_impl( wallet_api& s, const wallet_data& initial_data, fc::api<login_api> rapi ) : self(s), _chain_id(initial_data.chain_id), _remote_api(rapi), _remote_db(rapi->database()), _remote_net_broadcast(rapi->network_broadcast()), _remote_hist(rapi->history()) { chain_id_type remote_chain_id = _remote_db->get_chain_id(); if( remote_chain_id != _chain_id ) { FC_THROW( "Remote server gave us an unexpected chain_id", ("remote_chain_id", remote_chain_id) ("chain_id", _chain_id) ); } init_prototype_ops(); _remote_db->set_block_applied_callback( [this](const variant& block_id ) { on_block_applied( block_id ); } ); _wallet.chain_id = _chain_id; _wallet.ws_server = initial_data.ws_server; _wallet.ws_user = initial_data.ws_user; _wallet.ws_password = initial_data.ws_password; } virtual ~wallet_api_impl() { try { _remote_db->cancel_all_subscriptions(); } catch (const fc::exception& e) { // Right now the wallet_api has no way of knowing if the connection to the // node has already disconnected (via the node exiting first). // If it has exited, cancel_all_subscriptsions() will throw and there's // nothing we can do about it. // dlog("Caught exception ${e} while canceling database subscriptions", ("e", e)); } } void encrypt_keys() { if( !is_locked() ) { plain_keys data; data.keys = _keys; data.checksum = _checksum; auto plain_txt = fc::raw::pack(data); _wallet.cipher_keys = fc::aes_encrypt( data.checksum, plain_txt ); } } void on_block_applied( const variant& block_id ) { fc::async([this]{resync();}, "Resync after block"); } bool copy_wallet_file( string destination_filename ) { fc::path src_path = get_wallet_filename(); if( !fc::exists( src_path ) ) return false; fc::path dest_path = destination_filename + _wallet_filename_extension; int suffix = 0; while( fc::exists(dest_path) ) { ++suffix; dest_path = destination_filename + "-" + to_string( suffix ) + _wallet_filename_extension; } wlog( "backing up wallet ${src} to ${dest}", ("src", src_path) ("dest", dest_path) ); fc::path dest_parent = fc::absolute(dest_path).parent_path(); try { enable_umask_protection(); if( !fc::exists( dest_parent ) ) fc::create_directories( dest_parent ); fc::copy( src_path, dest_path ); disable_umask_protection(); } catch(...) { disable_umask_protection(); throw; } return true; } bool is_locked()const { return _checksum == fc::sha512(); } template<typename T> T get_object(object_id<T::space_id, T::type_id, T> id)const { auto ob = _remote_db->get_objects({id}).front(); return ob.template as<T>( GRAPHENE_MAX_NESTED_OBJECTS ); } void set_operation_fees( signed_transaction& tx, const fee_schedule& s, bool csaf_fee ) { if (csaf_fee) { for (auto& op : tx.operations) s.set_fee_with_csaf(op); } else { for (auto& op : tx.operations) s.set_fee(op); } } variant info() const { auto chain_props = get_chain_properties(); auto global_props = get_global_properties(); auto dynamic_props = get_dynamic_global_properties(); fc::mutable_variant_object result; result["head_block_num"] = dynamic_props.head_block_number; result["head_block_id"] = fc::variant( dynamic_props.head_block_id, 1 ); result["head_block_time"] = dynamic_props.time; result["head_block_age"] = fc::get_approximate_relative_time_string(dynamic_props.time, time_point_sec(time_point::now()), " old"); //result["next_maintenance_time"] = fc::get_approximate_relative_time_string(dynamic_props.next_maintenance_time); result["last_irreversible_block_num"] = dynamic_props.last_irreversible_block_num; result["chain_id"] = chain_props.chain_id; result["participation"] = (100*dynamic_props.recent_slots_filled.popcount()) / 128.0; result["active_witnesses"] = fc::variant( global_props.active_witnesses, GRAPHENE_MAX_NESTED_OBJECTS ); result["active_committee_members"] = fc::variant( global_props.active_committee_members, GRAPHENE_MAX_NESTED_OBJECTS ); return result; } variant_object about() const { string client_version( graphene::utilities::git_revision_description ); const size_t pos = client_version.find( '/' ); if( pos != string::npos && client_version.size() > pos ) client_version = client_version.substr( pos + 1 ); fc::mutable_variant_object result; //result["blockchain_name"] = BLOCKCHAIN_NAME; //result["blockchain_description"] = BTS_BLOCKCHAIN_DESCRIPTION; result["client_version"] = client_version; result["graphene_revision"] = graphene::utilities::git_revision_sha; result["graphene_revision_age"] = fc::get_approximate_relative_time_string( fc::time_point_sec( graphene::utilities::git_revision_unix_timestamp ) ); result["fc_revision"] = fc::git_revision_sha; result["fc_revision_age"] = fc::get_approximate_relative_time_string( fc::time_point_sec( fc::git_revision_unix_timestamp ) ); result["compile_date"] = "compiled on " __DATE__ " at " __TIME__; result["boost_version"] = boost::replace_all_copy(std::string(BOOST_LIB_VERSION), "_", "."); result["openssl_version"] = OPENSSL_VERSION_TEXT; std::string bitness = boost::lexical_cast<std::string>(8 * sizeof(int*)) + "-bit"; #if defined(__APPLE__) std::string os = "osx"; #elif defined(__linux__) std::string os = "linux"; #elif defined(_MSC_VER) std::string os = "win32"; #else std::string os = "other"; #endif result["build"] = os + " " + bitness; return result; } chain_property_object get_chain_properties() const { return _remote_db->get_chain_properties(); } global_property_object get_global_properties() const { return _remote_db->get_global_properties(); } content_parameter_extension_type get_global_properties_extensions() const { return _remote_db->get_global_properties().parameters.get_award_params(); } dynamic_global_property_object get_dynamic_global_properties() const { return _remote_db->get_dynamic_global_properties(); } account_object get_account(account_uid_type uid) const { /* // TODO review. commented out to get around the caching issue const auto& idx = _wallet.my_accounts.get<by_uid>(); auto itr = idx.find(uid); if( itr != idx.end() ) return *itr; */ auto rec = _remote_db->get_accounts_by_uid({uid}).front(); FC_ASSERT( rec, "Can not find account ${uid}.", ("uid",uid) ); return *rec; } account_object get_account(string account_name_or_id) const { FC_ASSERT( account_name_or_id.size() > 0 ); if( graphene::utilities::is_number( account_name_or_id ) ) { // It's a UID return get_account( fc::variant( account_name_or_id ).as<account_uid_type>( 1 ) ); } else { // It's a name /* // TODO review. commented out to get around the caching issue if( _wallet.my_accounts.get<by_name>().count(account_name_or_id) ) { auto local_account = *_wallet.my_accounts.get<by_name>().find(account_name_or_id); auto blockchain_account = _remote_db->lookup_account_names({account_name_or_id}).front(); FC_ASSERT( blockchain_account ); if (local_account.uid != blockchain_account->uid) elog("my account uid ${uid} different from blockchain uid ${uid2}", ("uid", local_account.uid)("uid2", blockchain_account->uid)); if (local_account.name != blockchain_account->name) elog("my account name ${name} different from blockchain name ${name2}", ("name", local_account.name)("name2", blockchain_account->name)); return *_wallet.my_accounts.get<by_name>().find(account_name_or_id); } */ optional<account_object> rec = _remote_db->get_account_by_name( account_name_or_id ); FC_ASSERT( rec && rec->name == account_name_or_id, "Can not find account ${a}.", ("a",account_name_or_id) ); return *rec; } } account_uid_type get_account_uid(string account_name_or_id) const { return get_account(account_name_or_id).get_uid(); } account_id_type get_account_id(string account_name_or_id) const { return get_account(account_name_or_id).get_id(); } optional<asset_object_with_data> find_asset(asset_aid_type aid)const { auto rec = _remote_db->get_assets({aid}).front(); return rec; } optional<asset_object_with_data> find_asset(string asset_symbol_or_id)const { FC_ASSERT( asset_symbol_or_id.size() > 0 ); if(graphene::utilities::is_number(asset_symbol_or_id)) { asset_aid_type id = fc::variant( asset_symbol_or_id ).as_uint64(); return find_asset(id); } else if(auto id = maybe_id<asset_id_type>(asset_symbol_or_id)) { return get_object(*id); } else { auto rec = _remote_db->lookup_asset_symbols({asset_symbol_or_id}).front(); if( rec ) { if( rec->symbol != asset_symbol_or_id ) return optional<asset_object>(); } return rec; } } asset_object_with_data get_asset(asset_aid_type aid)const { auto opt = find_asset(aid); FC_ASSERT( opt, "Can not find asset ${a}", ("a", aid) ); return *opt; } asset_object_with_data get_asset(string asset_symbol_or_id)const { auto opt = find_asset(asset_symbol_or_id); FC_ASSERT( opt, "Can not find asset ${a}", ("a", asset_symbol_or_id) ); return *opt; } asset_aid_type get_asset_aid(string asset_symbol_or_id) const { FC_ASSERT( asset_symbol_or_id.size() > 0 ); auto opt_asset = find_asset( asset_symbol_or_id ); FC_ASSERT( opt_asset.valid(), "Can not find asset ${a}", ("a", asset_symbol_or_id) ); return opt_asset->asset_id; } string get_wallet_filename() const { return _wallet_filename; } fc::ecc::private_key get_private_key(const public_key_type& id)const { FC_ASSERT( !self.is_locked(), "The wallet must be unlocked to get the private key" ); auto it = _keys.find(id); FC_ASSERT( it != _keys.end(), "Can not find private key of ${pub} in the wallet", ("pub",id) ); fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); FC_ASSERT( privkey, "Can not find private key of ${pub} in the wallet", ("pub",id) ); return *privkey; } fc::ecc::private_key get_private_key_for_account(const account_object& account)const { vector<public_key_type> active_keys = account.active.get_keys(); if (active_keys.size() != 1) FC_THROW("Expecting a simple authority with one active key"); return get_private_key(active_keys.front()); } // imports the private key into the wallet, and associate it in some way (?) with the // given account name. // @returns true if the key matches a current active/owner/memo key for the named // account, false otherwise (but it is stored either way) bool import_key(string account_name_or_id, string wif_key) { fc::optional<fc::ecc::private_key> optional_private_key = wif_to_key(wif_key); if (!optional_private_key) FC_THROW("Invalid private key"); graphene::chain::public_key_type wif_pub_key = optional_private_key->get_public_key(); account_object account = get_account( account_name_or_id ); // make a list of all current public keys for the named account flat_set<public_key_type> all_keys_for_account; std::vector<public_key_type> secondary_keys = account.secondary.get_keys(); std::vector<public_key_type> active_keys = account.active.get_keys(); std::vector<public_key_type> owner_keys = account.owner.get_keys(); std::copy(secondary_keys.begin(), secondary_keys.end(), std::inserter(all_keys_for_account, all_keys_for_account.end())); std::copy(active_keys.begin(), active_keys.end(), std::inserter(all_keys_for_account, all_keys_for_account.end())); std::copy(owner_keys.begin(), owner_keys.end(), std::inserter(all_keys_for_account, all_keys_for_account.end())); all_keys_for_account.insert(account.memo_key); _keys[wif_pub_key] = wif_key; _wallet.update_account(account); _wallet.extra_keys[account.uid].insert(wif_pub_key); return all_keys_for_account.find(wif_pub_key) != all_keys_for_account.end(); } bool load_wallet_file(string wallet_filename = "") { if( !self.is_locked() ) self.lock(); // TODO: Merge imported wallet with existing wallet, // instead of replacing it if( wallet_filename == "" ) wallet_filename = _wallet_filename; if( ! fc::exists( wallet_filename ) ) return false; _wallet = fc::json::from_file( wallet_filename ).as< wallet_data >( 2 * GRAPHENE_MAX_NESTED_OBJECTS ); if( _wallet.chain_id != _chain_id ) FC_THROW( "Wallet chain ID does not match", ("wallet.chain_id", _wallet.chain_id) ("chain_id", _chain_id) ); size_t account_pagination = 100; vector< account_uid_type > account_uids_to_send; size_t n = _wallet.my_accounts.size(); account_uids_to_send.reserve( std::min( account_pagination, n ) ); auto it = _wallet.my_accounts.begin(); for( size_t start=0; start<n; start+=account_pagination ) { size_t end = std::min( start+account_pagination, n ); assert( end > start ); account_uids_to_send.clear(); std::vector< account_object > old_accounts; for( size_t i=start; i<end; i++ ) { assert( it != _wallet.my_accounts.end() ); old_accounts.push_back( *it ); account_uids_to_send.push_back( old_accounts.back().uid ); ++it; } std::vector< optional< account_object > > accounts = _remote_db->get_accounts_by_uid(account_uids_to_send); // server response should be same length as request FC_ASSERT( accounts.size() == account_uids_to_send.size(), "remote server error" ); size_t i = 0; for( const optional< account_object >& acct : accounts ) { account_object& old_acct = old_accounts[i]; if( !acct.valid() ) { elog( "Could not find account ${uid} : \"${name}\" does not exist on the chain!", ("uid", old_acct.uid)("name", old_acct.name) ); i++; continue; } // this check makes sure the server didn't send results // in a different order, or accounts we didn't request FC_ASSERT( acct->uid == old_acct.uid, "remote server error" ); if( fc::json::to_string(*acct) != fc::json::to_string(old_acct) ) { wlog( "Account ${uid} : \"${name}\" updated on chain", ("uid", acct->uid)("name", acct->name) ); } _wallet.update_account( *acct ); i++; } } return true; } void save_wallet_file(string wallet_filename = "") { // // Serialize in memory, then save to disk // // This approach lessens the risk of a partially written wallet // if exceptions are thrown in serialization // encrypt_keys(); if( wallet_filename == "" ) wallet_filename = _wallet_filename; wlog( "saving wallet to file ${fn}", ("fn", wallet_filename) ); string data = fc::json::to_pretty_string( _wallet ); try { enable_umask_protection(); // // Parentheses on the following declaration fails to compile, // due to the Most Vexing Parse. Thanks, C++ // // http://en.wikipedia.org/wiki/Most_vexing_parse // fc::ofstream outfile{ fc::path( wallet_filename ) }; outfile.write( data.c_str(), data.length() ); outfile.flush(); outfile.close(); disable_umask_protection(); } catch(...) { disable_umask_protection(); throw; } } transaction_handle_type begin_builder_transaction() { int trx_handle = _builder_transactions.empty()? 0 : (--_builder_transactions.end())->first + 1; _builder_transactions[trx_handle]; return trx_handle; } void add_operation_to_builder_transaction(transaction_handle_type transaction_handle, const operation& op) { FC_ASSERT(_builder_transactions.count(transaction_handle)); _builder_transactions[transaction_handle].operations.emplace_back(op); } void replace_operation_in_builder_transaction(transaction_handle_type handle, uint32_t operation_index, const operation& new_op) { FC_ASSERT(_builder_transactions.count(handle)); signed_transaction& trx = _builder_transactions[handle]; FC_ASSERT( operation_index < trx.operations.size()); trx.operations[operation_index] = new_op; } asset set_fees_on_builder_transaction(transaction_handle_type handle, string fee_asset = GRAPHENE_SYMBOL) { FC_ASSERT(_builder_transactions.count(handle)); auto fee_asset_obj = get_asset(fee_asset); asset total_fee = fee_asset_obj.amount(0); FC_ASSERT(fee_asset_obj.asset_id == GRAPHENE_CORE_ASSET_AID, "Must use core assets as a fee"); auto gprops = _remote_db->get_global_properties().parameters; for( auto& op : _builder_transactions[handle].operations ) total_fee += gprops.current_fees->set_fee( op ); return total_fee; } transaction preview_builder_transaction(transaction_handle_type handle) { FC_ASSERT(_builder_transactions.count(handle)); return _builder_transactions[handle]; } signed_transaction sign_builder_transaction(transaction_handle_type transaction_handle, bool broadcast = true) { FC_ASSERT(_builder_transactions.count(transaction_handle)); return _builder_transactions[transaction_handle] = sign_transaction(_builder_transactions[transaction_handle], broadcast); } signed_transaction propose_builder_transaction( transaction_handle_type handle, string account_name_or_id, time_point_sec expiration = time_point::now() + fc::minutes(1), uint32_t review_period_seconds = 0, bool broadcast = true) { FC_ASSERT(_builder_transactions.count(handle)); proposal_create_operation op; op.fee_paying_account = get_account(account_name_or_id).get_uid(); op.expiration_time = expiration; signed_transaction& trx = _builder_transactions[handle]; std::transform(trx.operations.begin(), trx.operations.end(), std::back_inserter(op.proposed_ops), [](const operation& op) -> op_wrapper { return op; }); if( review_period_seconds ) op.review_period_seconds = review_period_seconds; trx.operations = {op}; _remote_db->get_global_properties().parameters.current_fees->set_fee( trx.operations.front() ); return trx = sign_transaction(trx, broadcast); } void remove_builder_transaction(transaction_handle_type handle) { _builder_transactions.erase(handle); } signed_transaction register_account(string name, public_key_type owner, public_key_type active, string registrar_account, string referrer_account, uint32_t referrer_percent, uint32_t seed, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT( !self.is_locked() ); account_create_operation account_create_op; // #449 referrer_percent is on 0-100 scale, if user has larger // number it means their script is using GRAPHENE_100_PERCENT scale // instead of 0-100 scale. FC_ASSERT( referrer_percent <= 100 ); // TODO: process when pay_from_account is ID account_object registrar_account_object = this->get_account( registrar_account ); //FC_ASSERT( registrar_account_object.is_lifetime_member() ); account_object referrer_account_object = this->get_account(referrer_account); // TODO review /* account_id_type registrar_account_id = registrar_account_object.id; account_object referrer_account_object = this->get_account( referrer_account ); account_create_op.referrer = referrer_account_object.id; account_create_op.referrer_percent = uint16_t( referrer_percent * GRAPHENE_1_PERCENT ); account_create_op.registrar = registrar_account_id; */ account_create_op.name = name; account_create_op.owner = authority(1, owner, 1); account_create_op.active = authority(1, active, 1); account_create_op.secondary = authority(1, owner, 1); account_create_op.memo_key = active; account_create_op.uid = graphene::chain::calc_account_uid(seed); account_reg_info reg_info; reg_info.registrar = registrar_account_object.uid; reg_info.referrer = referrer_account_object.uid; account_create_op.reg_info = reg_info; signed_transaction tx; tx.operations.push_back( account_create_op ); auto current_fees = _remote_db->get_global_properties().parameters.current_fees; set_operation_fees( tx, current_fees, csaf_fee ); vector<public_key_type> paying_keys = registrar_account_object.active.get_keys(); auto dyn_props = get_dynamic_global_properties(); tx.set_reference_block( dyn_props.head_block_id ); tx.set_expiration( dyn_props.time + fc::seconds(30) ); tx.validate(); for( public_key_type& key : paying_keys ) { auto it = _keys.find(key); if( it != _keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); if( !privkey.valid() ) { FC_ASSERT( false, "Malformed private key in _keys" ); } tx.sign( *privkey, _chain_id ); } } if( broadcast ) _remote_net_broadcast->broadcast_transaction( tx ); return tx; } FC_CAPTURE_AND_RETHROW( (name)(owner)(active)(registrar_account)(referrer_account)(referrer_percent)(csaf_fee)(broadcast) ) } // This function generates derived keys starting with index 0 and keeps incrementing // the index until it finds a key that isn't registered in the block chain. To be // safer, it continues checking for a few more keys to make sure there wasn't a short gap // caused by a failed registration or the like. int find_first_unused_derived_key_index(const fc::ecc::private_key& parent_key) { int first_unused_index = 0; int number_of_consecutive_unused_keys = 0; for (int key_index = 0; ; ++key_index) { fc::ecc::private_key derived_private_key = derive_private_key(key_to_wif(parent_key), key_index); graphene::chain::public_key_type derived_public_key = derived_private_key.get_public_key(); if( _keys.find(derived_public_key) == _keys.end() ) { if (number_of_consecutive_unused_keys) { ++number_of_consecutive_unused_keys; if (number_of_consecutive_unused_keys > 5) return first_unused_index; } else { first_unused_index = key_index; number_of_consecutive_unused_keys = 1; } } else { // key_index is used first_unused_index = 0; number_of_consecutive_unused_keys = 0; } } } signed_transaction create_account_with_private_key(fc::ecc::private_key owner_privkey, string account_name, string registrar_account, string referrer_account, uint32_t seed, bool csaf_fee = true, bool broadcast = false, bool save_wallet = true) { try { int active_key_index = find_first_unused_derived_key_index(owner_privkey); fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), active_key_index); int memo_key_index = find_first_unused_derived_key_index(active_privkey); fc::ecc::private_key memo_privkey = derive_private_key( key_to_wif(active_privkey), memo_key_index); graphene::chain::public_key_type owner_pubkey = owner_privkey.get_public_key(); graphene::chain::public_key_type active_pubkey = active_privkey.get_public_key(); graphene::chain::public_key_type memo_pubkey = memo_privkey.get_public_key(); account_create_operation account_create_op; // TODO: process when pay_from_account is ID account_object registrar_account_object = get_account( registrar_account ); account_object referrer_account_object = get_account(referrer_account); // TODO: review /* account_id_type registrar_account_id = registrar_account_object.id; account_object referrer_account_object = get_account( referrer_account ); account_create_op.referrer = referrer_account_object.id; account_create_op.referrer_percent = referrer_account_object.referrer_rewards_percentage; account_create_op.registrar = registrar_account_id; */ account_create_op.name = account_name; account_create_op.owner = authority(1, owner_pubkey, 1); account_create_op.active = authority(1, active_pubkey, 1); account_create_op.secondary = authority(1, owner_pubkey, 1); account_create_op.uid = graphene::chain::calc_account_uid(seed); account_reg_info reg_info; reg_info.registrar = registrar_account_object.uid; reg_info.referrer = referrer_account_object.uid; account_create_op.reg_info = reg_info; account_create_op.memo_key = memo_pubkey; // current_fee_schedule() // find_account(pay_from_account) // account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule()); signed_transaction tx; tx.operations.push_back( account_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); vector<public_key_type> paying_keys = registrar_account_object.active.get_keys(); auto dyn_props = get_dynamic_global_properties(); tx.set_reference_block( dyn_props.head_block_id ); tx.set_expiration( dyn_props.time + fc::seconds(30) ); tx.validate(); for( public_key_type& key : paying_keys ) { auto it = _keys.find(key); if( it != _keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); FC_ASSERT( privkey.valid(), "Malformed private key in _keys" ); tx.sign( *privkey, _chain_id ); } } // we do not insert owner_privkey here because // it is intended to only be used for key recovery _wallet.pending_account_registrations[account_name].push_back(key_to_wif( active_privkey )); _wallet.pending_account_registrations[account_name].push_back(key_to_wif( memo_privkey )); if( save_wallet ) save_wallet_file(); if( broadcast ) _remote_net_broadcast->broadcast_transaction( tx ); return tx; } FC_CAPTURE_AND_RETHROW( (account_name)(registrar_account)(referrer_account)(csaf_fee)(broadcast) ) } signed_transaction create_account_with_brain_key(string brain_key, string account_name, string registrar_account, string referrer_account, uint32_t seed, bool csaf_fee = true, bool broadcast = false, bool save_wallet = true) { try { FC_ASSERT( !self.is_locked() ); string normalized_brain_key = normalize_brain_key( brain_key ); // TODO: scan blockchain for accounts that exist with same brain key fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 ); return create_account_with_private_key(owner_privkey, account_name, registrar_account, referrer_account, seed, csaf_fee, broadcast, save_wallet); } FC_CAPTURE_AND_RETHROW( (account_name)(registrar_account)(referrer_account) ) } signed_transaction create_asset(string issuer, string symbol, uint8_t precision, asset_options common, share_type initial_supply, bool csaf_fee, bool broadcast = false) { try { account_object issuer_account = get_account( issuer ); FC_ASSERT(!find_asset(symbol).valid(), "Asset with that symbol already exists!"); asset_create_operation create_op; create_op.issuer = issuer_account.uid; create_op.symbol = symbol; create_op.precision = precision; create_op.common_options = common; if( initial_supply != 0 ) { create_op.extensions = extension<asset_create_operation::ext>(); create_op.extensions->value.initial_supply = initial_supply; } signed_transaction tx; tx.operations.push_back( create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (issuer)(symbol)(precision)(common)(csaf_fee)(broadcast) ) } signed_transaction update_asset(string symbol, optional<uint8_t> new_precision, asset_options new_options, bool csaf_fee, bool broadcast /* = false */) { try { optional<asset_object_with_data> asset_to_update = find_asset(symbol); FC_ASSERT( asset_to_update.valid(), "Can not find asset ${a}", ("a", symbol) ); asset_update_operation update_op; update_op.issuer = asset_to_update->issuer; update_op.asset_to_update = asset_to_update->asset_id; update_op.new_precision = new_precision; update_op.new_options = new_options; signed_transaction tx; tx.operations.push_back( update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (symbol)(new_precision)(new_options)(csaf_fee)(broadcast) ) } signed_transaction reserve_asset(string from, string amount, string symbol, bool csaf_fee, bool broadcast /* = false */) { try { account_object from_account = get_account(from); optional<asset_object_with_data> asset_to_reserve = find_asset(symbol); FC_ASSERT( asset_to_reserve.valid(), "Can not find asset ${a}", ("a", symbol) ); asset_reserve_operation reserve_op; reserve_op.payer = from_account.uid; reserve_op.amount_to_reserve = asset_to_reserve->amount_from_string(amount); signed_transaction tx; tx.operations.push_back( reserve_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (from)(amount)(symbol)(csaf_fee)(broadcast) ) } signed_transaction whitelist_account(string authorizing_account, string account_to_list, account_whitelist_operation::account_listing new_listing_status, bool csaf_fee, bool broadcast /* = false */) { try { account_whitelist_operation whitelist_op; whitelist_op.authorizing_account = get_account_uid(authorizing_account); whitelist_op.account_to_list = get_account_uid(account_to_list); whitelist_op.new_listing = new_listing_status; signed_transaction tx; tx.operations.push_back( whitelist_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (authorizing_account)(account_to_list)(new_listing_status)(csaf_fee)(broadcast) ) } signed_transaction create_committee_member(string owner_account, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { try { account_object committee_member_account = get_account(owner_account); if( _remote_db->get_committee_member_by_account( committee_member_account.uid ) ) FC_THROW( "Account ${owner_account} is already a committee_member", ("owner_account", owner_account) ); fc::optional<asset_object_with_data> asset_obj = get_asset( pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", pledge_asset_symbol) ); committee_member_create_operation committee_member_create_op; committee_member_create_op.account = committee_member_account.uid; committee_member_create_op.pledge = asset_obj->amount_from_string( pledge_amount ); committee_member_create_op.url = url; signed_transaction tx; tx.operations.push_back( committee_member_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } witness_object get_witness(string owner_account) { try { fc::optional<witness_id_type> witness_id = maybe_id<witness_id_type>(owner_account); if (witness_id) { std::vector<object_id_type> ids_to_get; ids_to_get.push_back(*witness_id); fc::variants objects = _remote_db->get_objects( ids_to_get ); for( const variant& obj : objects ) { optional<witness_object> wo; from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS ); if( wo ) return *wo; } FC_THROW("No witness is registered for id ${id}", ("id", owner_account)); } else { // then maybe it's the owner account try { account_uid_type owner_account_uid = get_account_uid(owner_account); fc::optional<witness_object> witness = _remote_db->get_witness_by_account(owner_account_uid); if (witness) return *witness; else FC_THROW("No witness is registered for account ${account}", ("account", owner_account)); } catch (const fc::exception&) { FC_THROW("No account or witness named ${account}", ("account", owner_account)); } } } FC_CAPTURE_AND_RETHROW( (owner_account) ) } platform_object get_platform(string owner_account) { try { fc::optional<platform_id_type> platform_id = maybe_id<platform_id_type>(owner_account); if (platform_id) { std::vector<object_id_type> ids_to_get; ids_to_get.push_back(*platform_id); fc::variants objects = _remote_db->get_objects( ids_to_get ); for( const variant& obj : objects ) { optional<platform_object> wo; from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS ); if( wo ) return *wo; } FC_THROW("No platform is registered for id ${id}", ("id", owner_account)); } else { // then maybe it's the owner account try { account_uid_type owner_account_uid = get_account_uid(owner_account); fc::optional<platform_object> platform = _remote_db->get_platform_by_account(owner_account_uid); if (platform) return *platform; else FC_THROW("No platform is registered for account ${account}", ("account", owner_account)); } catch (const fc::exception&) { FC_THROW("No account or platform named ${account}", ("account", owner_account)); } } } FC_CAPTURE_AND_RETHROW( (owner_account) ) } committee_member_object get_committee_member(string owner_account) { try { fc::optional<committee_member_id_type> committee_member_id = maybe_id<committee_member_id_type>(owner_account); if (committee_member_id) { std::vector<object_id_type> ids_to_get; ids_to_get.push_back(*committee_member_id); fc::variants objects = _remote_db->get_objects( ids_to_get ); for( const variant& obj : objects ) { optional<committee_member_object> wo; from_variant( obj, wo, GRAPHENE_MAX_NESTED_OBJECTS ); if( wo ) return *wo; } FC_THROW("No committee_member is registered for id ${id}", ("id", owner_account)); } else { // then maybe it's the owner account try { account_uid_type owner_account_uid = get_account_uid(owner_account); fc::optional<committee_member_object> committee_member = _remote_db->get_committee_member_by_account(owner_account_uid); if (committee_member) return *committee_member; else FC_THROW("No committee_member is registered for account ${account}", ("account", owner_account)); } catch (const fc::exception&) { FC_THROW("No account or committee_member named ${account}", ("account", owner_account)); } } } FC_CAPTURE_AND_RETHROW( (owner_account) ) } signed_transaction create_witness_with_details(string owner_account, public_key_type block_signing_key, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { try { account_object witness_account = get_account(owner_account); if( _remote_db->get_witness_by_account( witness_account.uid ) ) FC_THROW( "Account ${owner_account} is already a witness", ("owner_account", owner_account) ); fc::optional<asset_object_with_data> asset_obj = get_asset( pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", pledge_asset_symbol) ); witness_create_operation witness_create_op; witness_create_op.account = witness_account.uid; witness_create_op.block_signing_key = block_signing_key; witness_create_op.pledge = asset_obj->amount_from_string( pledge_amount ); witness_create_op.url = url; signed_transaction tx; tx.operations.push_back( witness_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(block_signing_key)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction create_witness(string owner_account, string url, bool csaf_fee, bool broadcast /* = false */) { try { account_object witness_account = get_account(owner_account); fc::ecc::private_key active_private_key = get_private_key_for_account(witness_account); int witness_key_index = find_first_unused_derived_key_index(active_private_key); fc::ecc::private_key witness_private_key = derive_private_key(key_to_wif(active_private_key), witness_key_index); graphene::chain::public_key_type witness_public_key = witness_private_key.get_public_key(); witness_create_operation witness_create_op; witness_create_op.account = witness_account.uid; witness_create_op.block_signing_key = witness_public_key; witness_create_op.url = url; if (_remote_db->get_witness_by_account(witness_create_op.account)) FC_THROW("Account ${owner_account} is already a witness", ("owner_account", owner_account)); signed_transaction tx; tx.operations.push_back( witness_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); _wallet.pending_witness_registrations[owner_account] = key_to_wif(witness_private_key); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(csaf_fee)(broadcast) ) } signed_transaction create_platform(string owner_account, string name, string pledge_amount, string pledge_asset_symbol, string url, string extra_data, bool csaf_fee, bool broadcast ) { try { account_object platform_account = get_account( owner_account ); if( _remote_db->get_platform_by_account( platform_account.uid ) ) FC_THROW( "Account ${owner_account} is already a platform", ( "owner_account", owner_account ) ); fc::optional<asset_object_with_data> asset_obj = get_asset( pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ( "asset", pledge_asset_symbol ) ); platform_create_operation platform_create_op; platform_create_op.account = platform_account.uid; platform_create_op.name = name; platform_create_op.pledge = asset_obj->amount_from_string( pledge_amount ); platform_create_op.extra_data = extra_data; platform_create_op.url = url; signed_transaction tx; tx.operations.push_back( platform_create_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (owner_account)(name)(pledge_amount)(pledge_asset_symbol)(url)(extra_data)(csaf_fee)(broadcast) ) } signed_transaction update_platform(string platform_account, optional<string> name, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, optional<string> extra_data, bool csaf_fee, bool broadcast ) { try { FC_ASSERT( pledge_amount.valid() == pledge_asset_symbol.valid(), "Pledge amount and asset symbol should be both set or both not set" ); fc::optional<asset> pledge; if( pledge_amount.valid() ) { fc::optional<asset_object_with_data> asset_obj = get_asset( *pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ( "asset", *pledge_asset_symbol ) ); pledge = asset_obj->amount_from_string( *pledge_amount ); } platform_object platform = get_platform( platform_account ); account_object platform_owner = get_account( platform.owner ); platform_update_operation platform_update_op; platform_update_op.account = platform_owner.uid; platform_update_op.new_name = name; platform_update_op.new_pledge = pledge; platform_update_op.new_url = url; platform_update_op.new_extra_data = extra_data; signed_transaction tx; tx.operations.push_back( platform_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (platform_account)(name)(pledge_amount)(pledge_asset_symbol)(url)(extra_data)(csaf_fee)(broadcast) ) } signed_transaction account_auth_platform(string account, string platform_owner, string memo, string limit_for_platform = 0, uint32_t permission_flags = account_auth_platform_object::Platform_Permission_Forward | account_auth_platform_object::Platform_Permission_Liked | account_auth_platform_object::Platform_Permission_Buyout | account_auth_platform_object::Platform_Permission_Comment | account_auth_platform_object::Platform_Permission_Reward | account_auth_platform_object::Platform_Permission_Post | account_auth_platform_object::Platform_Permission_Content_Update, bool csaf_fee = true, bool broadcast = false) { try { fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_object user = get_account(account); account_object platform_account = get_account(platform_owner); auto pa = _remote_db->get_platform_by_account(platform_account.uid); FC_ASSERT(pa.valid(), "Account ${platform_owner} is not a platform", ("platform_owner", platform_owner)); account_auth_platform_operation op; op.uid = user.uid; op.platform = pa->owner; account_auth_platform_operation::extension_parameter ext; ext.limit_for_platform = asset_obj->amount_from_string(limit_for_platform).amount; ext.permission_flags = permission_flags; if (memo.size()) { ext.memo = memo_data(); ext.memo->from = user.memo_key; ext.memo->to = platform_account.memo_key; ext.memo->set_message(get_private_key(user.memo_key), platform_account.memo_key, memo); } op.extensions = extension<account_auth_platform_operation::extension_parameter>(); op.extensions->value = ext; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((account)(platform_owner)(limit_for_platform)(permission_flags)(csaf_fee)(broadcast)) } signed_transaction account_cancel_auth_platform(string account, string platform_owner, bool csaf_fee = true, bool broadcast = false) { try { account_object user = get_account( account ); account_object platform_account = get_account( platform_owner ); account_cancel_auth_platform_operation op; op.uid = user.uid; op.platform = platform_account.uid; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account)(platform_owner)(csaf_fee)(broadcast) ) } signed_transaction update_committee_member( string committee_member_account, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { try { FC_ASSERT( pledge_amount.valid() == pledge_asset_symbol.valid(), "Pledge amount and asset symbol should be both set or both not set" ); fc::optional<asset> pledge; if( pledge_amount.valid() ) { fc::optional<asset_object_with_data> asset_obj = get_asset( *pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", *pledge_asset_symbol) ); pledge = asset_obj->amount_from_string( *pledge_amount ); } committee_member_object committee_member = get_committee_member( committee_member_account ); account_object committee_member_account = get_account( committee_member.account ); committee_member_update_operation committee_member_update_op; committee_member_update_op.account = committee_member_account.uid; committee_member_update_op.new_pledge = pledge; committee_member_update_op.new_url = url; signed_transaction tx; tx.operations.push_back( committee_member_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (committee_member_account)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction update_witness_with_details( string witness_account, optional<public_key_type> block_signing_key, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { try { FC_ASSERT( pledge_amount.valid() == pledge_asset_symbol.valid(), "Pledge amount and asset symbol should be both set or both not set" ); fc::optional<asset> pledge; if( pledge_amount.valid() ) { fc::optional<asset_object_with_data> asset_obj = get_asset( *pledge_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", *pledge_asset_symbol) ); pledge = asset_obj->amount_from_string( *pledge_amount ); } witness_object witness = get_witness( witness_account ); account_object witness_account = get_account( witness.account ); witness_update_operation witness_update_op; witness_update_op.account = witness_account.uid; witness_update_op.new_signing_key = block_signing_key; witness_update_op.new_pledge = pledge; witness_update_op.new_url = url; signed_transaction tx; tx.operations.push_back( witness_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (witness_account)(block_signing_key)(pledge_amount)(pledge_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction update_witness(string witness_name, string url, string block_signing_key, bool csaf_fee, bool broadcast /* = false */) { try { witness_object witness = get_witness(witness_name); account_object witness_account = get_account( witness.account ); witness_update_operation witness_update_op; //witness_update_op.witness = witness.id; witness_update_op.account = witness_account.uid; if( url != "" ) witness_update_op.new_url = url; if( block_signing_key != "" ) witness_update_op.new_signing_key = public_key_type( block_signing_key ); signed_transaction tx; tx.operations.push_back( witness_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (witness_name)(url)(block_signing_key)(csaf_fee)(broadcast) ) } signed_transaction collect_witness_pay(string witness_account, string pay_amount, string pay_asset_symbol, bool csaf_fee, bool broadcast /* = false */) { try { witness_object witness = get_witness(witness_account); fc::optional<asset_object_with_data> asset_obj = get_asset( pay_asset_symbol ); FC_ASSERT( asset_obj, "Could not find asset matching ${asset}", ("asset", pay_asset_symbol) ); witness_collect_pay_operation witness_collect_pay_op; witness_collect_pay_op.account = witness.account; witness_collect_pay_op.pay = asset_obj->amount_from_string( pay_amount ); signed_transaction tx; tx.operations.push_back( witness_collect_pay_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (witness_account)(pay_amount)(pay_asset_symbol)(csaf_fee)(broadcast) ) } signed_transaction collect_csaf(string from, string to, string amount, string asset_symbol, time_point_sec time, bool csaf_fee, bool broadcast /* = false */) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object from_account = get_account(from); account_object to_account = get_account(to); csaf_collect_operation cc_op; cc_op.from = from_account.uid; cc_op.to = to_account.uid; cc_op.amount = asset_obj->amount_from_string(amount); cc_op.time = time; signed_transaction tx; tx.operations.push_back(cc_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW( (from)(to)(amount)(asset_symbol)(time)(csaf_fee)(broadcast) ) } signed_transaction update_witness_votes(string voting_account, flat_set<string> witnesses_to_add, flat_set<string> witnesses_to_remove, bool csaf_fee, bool broadcast /* = false */) { try { account_object voting_account_object = get_account(voting_account); flat_set<account_uid_type> uids_to_add; flat_set<account_uid_type> uids_to_remove; uids_to_add.reserve( witnesses_to_add.size() ); uids_to_remove.reserve( witnesses_to_remove.size() ); for( string wit : witnesses_to_add ) uids_to_add.insert( get_witness( wit ).account ); for( string wit : witnesses_to_remove ) uids_to_remove.insert( get_witness( wit ).account ); witness_vote_update_operation witness_vote_update_op; witness_vote_update_op.voter = voting_account_object.uid; witness_vote_update_op.witnesses_to_add = uids_to_add; witness_vote_update_op.witnesses_to_remove = uids_to_remove; signed_transaction tx; tx.operations.push_back( witness_vote_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (voting_account)(witnesses_to_add)(witnesses_to_remove)(csaf_fee)(broadcast) ) } signed_transaction update_platform_votes(string voting_account, flat_set<string> platforms_to_add, flat_set<string> platforms_to_remove, bool csaf_fee, bool broadcast ) { try { account_object voting_account_object = get_account( voting_account ); flat_set<account_uid_type> uids_to_add; flat_set<account_uid_type> uids_to_remove; uids_to_add.reserve( platforms_to_add.size() ); uids_to_remove.reserve( platforms_to_remove.size() ); for( string pla : platforms_to_add ) uids_to_add.insert( get_platform( pla ).owner ); for( string pla : platforms_to_remove ) uids_to_remove.insert( get_platform( pla ).owner ); platform_vote_update_operation platform_vote_update_op; platform_vote_update_op.voter = voting_account_object.uid; platform_vote_update_op.platform_to_add = uids_to_add; platform_vote_update_op.platform_to_remove = uids_to_remove; signed_transaction tx; tx.operations.push_back( platform_vote_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee ); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (voting_account)(platforms_to_add)(platforms_to_remove)(csaf_fee)(broadcast) ) } signed_transaction update_committee_member_votes(string voting_account, flat_set<string> committee_members_to_add, flat_set<string> committee_members_to_remove, bool csaf_fee, bool broadcast /* = false */) { try { account_object voting_account_object = get_account(voting_account); flat_set<account_uid_type> uids_to_add; flat_set<account_uid_type> uids_to_remove; uids_to_add.reserve( committee_members_to_add.size() ); uids_to_remove.reserve( committee_members_to_remove.size() ); for( string com : committee_members_to_add ) uids_to_add.insert( get_committee_member( com ).account ); for( string com : committee_members_to_remove ) uids_to_remove.insert( get_committee_member( com ).account ); committee_member_vote_update_operation committee_member_vote_update_op; committee_member_vote_update_op.voter = voting_account_object.uid; committee_member_vote_update_op.committee_members_to_add = uids_to_add; committee_member_vote_update_op.committee_members_to_remove = uids_to_remove; signed_transaction tx; tx.operations.push_back( committee_member_vote_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (voting_account)(committee_members_to_add)(committee_members_to_remove)(csaf_fee)(broadcast) ) } signed_transaction set_voting_proxy(string account_to_modify, optional<string> voting_account, bool csaf_fee, bool broadcast /* = false */) { try { account_update_proxy_operation account_update_op; account_update_op.voter = get_account_uid(account_to_modify); if (voting_account) account_update_op.proxy = get_account_uid(*voting_account); else account_update_op.proxy = GRAPHENE_PROXY_TO_SELF_ACCOUNT_UID; signed_transaction tx; tx.operations.push_back( account_update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account_to_modify)(voting_account)(csaf_fee)(broadcast) ) } signed_transaction enable_allowed_assets(string account, bool enable, bool csaf_fee, bool broadcast /* = false */) { try { account_enable_allowed_assets_operation op; op.account = get_account_uid( account ); op.enable = enable; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account)(enable)(csaf_fee)(broadcast) ) } signed_transaction update_allowed_assets(string account, flat_set<string> assets_to_add, flat_set<string> assets_to_remove, bool csaf_fee, bool broadcast /* = false */) { try { account_object account_obj = get_account( account ); flat_set<asset_aid_type> aids_to_add; flat_set<asset_aid_type> aids_to_remove; aids_to_add.reserve( assets_to_add.size() ); aids_to_remove.reserve( assets_to_remove.size() ); for( string a : assets_to_add ) aids_to_add.insert( get_asset( a ).asset_id ); for( string a : assets_to_remove ) aids_to_remove.insert( get_asset( a ).asset_id ); account_update_allowed_assets_operation op; op.account = get_account_uid( account ); op.assets_to_add = aids_to_add; op.assets_to_remove = aids_to_remove; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (account)(assets_to_add)(assets_to_remove)(csaf_fee)(broadcast) ) } signed_transaction sign_transaction( signed_transaction tx, bool broadcast = false ) { // get required keys to sign the trx const auto& result = _remote_db->get_required_signatures( tx, flat_set<public_key_type>() ); const auto& required_keys = result.first.second; // check whether it's possible to fullfil the authority requirement if( required_keys.find( public_key_type() ) == required_keys.end() ) { // get a subset of available keys flat_set<public_key_type> available_keys; flat_map<public_key_type,fc::ecc::private_key> available_keys_map; for( const auto& pub_key : required_keys ) { auto it = _keys.find( pub_key ); if( it != _keys.end() ) { fc::optional<fc::ecc::private_key> privkey = wif_to_key( it->second ); FC_ASSERT( privkey.valid(), "Malformed private key in _keys" ); available_keys.insert( pub_key ); available_keys_map[ pub_key ] = *privkey; } } // if we have the required key(s), preceed to sign if( !available_keys.empty() ) { // get a subset of required keys const auto& new_result = _remote_db->get_required_signatures( tx, available_keys ); const auto& required_keys_subset = new_result.first.first; //const auto& missed_keys = new_result.first.second; const auto& unused_signatures = new_result.second; // unused signatures can be removed safely for( const auto& sig : unused_signatures ) tx.signatures.erase( std::remove( tx.signatures.begin(), tx.signatures.end(), sig), tx.signatures.end() ); bool no_sig = tx.signatures.empty(); auto dyn_props = get_dynamic_global_properties(); // if no signature is included in the trx, reset the tapos data; otherwise keep the tapos data if( no_sig ) tx.set_reference_block( dyn_props.head_block_id ); // if no signature is included in the trx, reset expiration time; otherwise keep it if( no_sig ) { // first, some bookkeeping, expire old items from _recently_generated_transactions // since transactions include the head block id, we just need the index for keeping transactions unique // when there are multiple transactions in the same block. choose a time period that should be at // least one block long, even in the worst case. 5 minutes ought to be plenty. fc::time_point_sec oldest_transaction_ids_to_track(dyn_props.time - fc::minutes(5)); auto oldest_transaction_record_iter = _recently_generated_transactions.get<timestamp_index>().lower_bound(oldest_transaction_ids_to_track); auto begin_iter = _recently_generated_transactions.get<timestamp_index>().begin(); _recently_generated_transactions.get<timestamp_index>().erase(begin_iter, oldest_transaction_record_iter); } uint32_t expiration_time_offset = 0; for (;;) { if( no_sig ) { tx.set_expiration( dyn_props.time + fc::seconds(120 + expiration_time_offset) ); tx.signatures.clear(); } //idump((required_keys_subset)(available_keys)); // TODO: for better performance, sign after dupe check for( const auto& key : required_keys_subset ) { tx.sign( available_keys_map[key], _chain_id ); /// TODO: if transaction has enough signatures to be "valid" don't add any more, /// there are cases where the wallet may have more keys than strictly necessary and /// the transaction will be rejected if the transaction validates without requiring /// all signatures provided } graphene::chain::transaction_id_type this_transaction_id = tx.id(); auto iter = _recently_generated_transactions.find(this_transaction_id); if (iter == _recently_generated_transactions.end()) { // we haven't generated this transaction before, the usual case recently_generated_transaction_record this_transaction_record; this_transaction_record.generation_time = dyn_props.time; this_transaction_record.transaction_id = this_transaction_id; _recently_generated_transactions.insert(this_transaction_record); break; } // if there was a signature included in the trx, we can not update expiration field if( !no_sig ) break; // if we've generated a dupe, increment expiration time and re-sign it ++expiration_time_offset; } } } //wdump((tx)); if( broadcast ) { try { _remote_net_broadcast->broadcast_transaction( tx ); } catch (const fc::exception& e) { elog("Caught exception while broadcasting tx ${id}: ${e}", ("id", tx.id().str())("e", e.to_detail_string()) ); throw; } } return tx; } transaction_id_type broadcast_transaction( signed_transaction tx ) { try { _remote_net_broadcast->broadcast_transaction( tx ); } catch (const fc::exception& e) { elog("Caught exception while broadcasting tx ${id}: ${e}", ("id", tx.id().str())("e", e.to_detail_string()) ); throw; } return tx.id(); } signed_transaction transfer(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT( !self.is_locked(), "Should unlock first" ); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object from_account = get_account(from); account_object to_account = get_account(to); transfer_operation xfer_op; xfer_op.from = from_account.uid; xfer_op.to = to_account.uid; xfer_op.amount = asset_obj->amount_from_string(amount); if( memo.size() ) { xfer_op.memo = memo_data(); xfer_op.memo->from = from_account.memo_key; xfer_op.memo->to = to_account.memo_key; xfer_op.memo->set_message(get_private_key(from_account.memo_key), to_account.memo_key, memo); } //xfer_op.fee = fee_type(asset(_remote_db->get_required_fee_data({ xfer_op }).at(0).min_fee)); signed_transaction tx; tx.operations.push_back(xfer_op); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW( (from)(to)(amount)(asset_symbol)(memo)(csaf_fee)(broadcast) ) } signed_transaction transfer_extension(string from, string to, string amount, string asset_symbol, string memo, optional<string> sign_platform , bool isfrom_balance = true, bool isto_balance = true, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object from_account = get_account(from); account_object to_account = get_account(to); transfer_operation xfer_op; xfer_op.extensions = extension< transfer_operation::ext >(); if (isfrom_balance) xfer_op.extensions->value.from_balance = asset_obj->amount_from_string(amount); else xfer_op.extensions->value.from_prepaid = asset_obj->amount_from_string(amount); if (isto_balance) xfer_op.extensions->value.to_balance = asset_obj->amount_from_string(amount); else xfer_op.extensions->value.to_prepaid = asset_obj->amount_from_string(amount); if (sign_platform.valid()){ xfer_op.extensions->value.sign_platform = get_account_uid(*sign_platform); } xfer_op.from = from_account.uid; xfer_op.to = to_account.uid; xfer_op.amount = asset_obj->amount_from_string(amount); if (memo.size()) { xfer_op.memo = memo_data(); xfer_op.memo->from = from_account.memo_key; xfer_op.memo->to = to_account.memo_key; xfer_op.memo->set_message(get_private_key(from_account.memo_key), to_account.memo_key, memo); } signed_transaction tx; tx.operations.push_back(xfer_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from)(to)(amount)(asset_symbol)(memo)(isfrom_balance)(isto_balance)(csaf_fee)(broadcast)) } signed_transaction override_transfer(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT( !self.is_locked(), "Should unlock first" ); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); account_object issuer_account = get_account(asset_obj->issuer); account_object from_account = get_account(from); account_object to_account = get_account(to); override_transfer_operation xfer_op; xfer_op.issuer = issuer_account.uid; xfer_op.from = from_account.uid; xfer_op.to = to_account.uid; xfer_op.amount = asset_obj->amount_from_string(amount); if( memo.size() ) { xfer_op.memo = memo_data(); xfer_op.memo->from = issuer_account.memo_key; xfer_op.memo->to = to_account.memo_key; xfer_op.memo->set_message(get_private_key(issuer_account.memo_key), to_account.memo_key, memo); } signed_transaction tx; tx.operations.push_back(xfer_op); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW( (from)(to)(amount)(asset_symbol)(memo)(csaf_fee)(broadcast) ) } signed_transaction issue_asset(string to_account, string amount, string symbol, string memo, bool csaf_fee = true, bool broadcast = false) { auto asset_obj = get_asset(symbol); account_object to = get_account(to_account); account_object issuer = get_account(asset_obj.issuer); asset_issue_operation issue_op; issue_op.issuer = asset_obj.issuer; issue_op.asset_to_issue = asset_obj.amount_from_string(amount); issue_op.issue_to_account = to.uid; if( memo.size() ) { issue_op.memo = memo_data(); issue_op.memo->from = issuer.memo_key; issue_op.memo->to = to.memo_key; issue_op.memo->set_message(get_private_key(issuer.memo_key), to.memo_key, memo); } signed_transaction tx; tx.operations.push_back(issue_op); set_operation_fees(tx,_remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } std::map<string,std::function<string(fc::variant,const fc::variants&)>> get_result_formatters() const { std::map<string,std::function<string(fc::variant,const fc::variants&)> > m; m["help"] = [](variant result, const fc::variants& a) { return result.get_string(); }; m["gethelp"] = [](variant result, const fc::variants& a) { return result.get_string(); }; m["get_relative_account_history"] = [this](variant result, const fc::variants& a) { auto r = result.as<vector<operation_detail>>( GRAPHENE_MAX_NESTED_OBJECTS ); std::stringstream ss; ss << "#" << " "; ss << "block_num" << " "; ss << "time " << " "; ss << "description/fee_payer/fee/operation_result" << " "; ss << " \n"; for( operation_detail& d : r ) { operation_history_object& i = d.op; ss << d.sequence << " "; ss << i.block_num << " "; ss << i.block_timestamp.to_iso_string() << " "; i.op.visit(operation_printer(ss, *this, i.result)); ss << " \n"; } return ss.str(); }; m["list_account_balances"] = [this](variant result, const fc::variants& a) { auto r = result.as<vector<asset>>( GRAPHENE_MAX_NESTED_OBJECTS ); vector<asset_object_with_data> asset_recs; std::transform(r.begin(), r.end(), std::back_inserter(asset_recs), [this](const asset& a) { return get_asset(a.asset_id); }); std::stringstream ss; for( unsigned i = 0; i < asset_recs.size(); ++i ) ss << asset_recs[i].amount_to_pretty_string(r[i]) << "\n"; return ss.str(); }; return m; } signed_transaction committee_proposal_create( const string committee_member_account, const vector<committee_proposal_item_type> items, const uint32_t voting_closing_block_num, optional<voting_opinion_type> proposer_opinion, const uint32_t execution_block_num = 0, const uint32_t expiration_block_num = 0, bool csaf_fee = true, bool broadcast = false ) { try { committee_proposal_create_operation op; op.proposer = get_account_uid( committee_member_account ); op.items = items; op.voting_closing_block_num = voting_closing_block_num; op.proposer_opinion = proposer_opinion; op.execution_block_num = execution_block_num; op.expiration_block_num = expiration_block_num; signed_transaction tx; tx.operations.push_back( op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (committee_member_account)(items)(voting_closing_block_num)(proposer_opinion)(execution_block_num)(expiration_block_num)(csaf_fee)(broadcast) ) } signed_transaction committee_proposal_vote( const string committee_member_account, const uint64_t proposal_number, const voting_opinion_type opinion, bool csaf_fee = true, bool broadcast = false ) { try { committee_proposal_update_operation update_op; update_op.account = get_account_uid( committee_member_account ); update_op.proposal_number = proposal_number; update_op.opinion = opinion; signed_transaction tx; tx.operations.push_back( update_op ); set_operation_fees( tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction( tx, broadcast ); } FC_CAPTURE_AND_RETHROW( (committee_member_account)(proposal_number)(opinion)(csaf_fee)(broadcast) ) } signed_transaction proposal_create(const string fee_paying_account, const vector<op_wrapper> proposed_ops, time_point_sec expiration_time, uint32_t review_period_seconds, bool csaf_fee = true, bool broadcast = false ) { try { proposal_create_operation op; op.fee_paying_account = get_account_uid(fee_paying_account); op.proposed_ops = proposed_ops; op.expiration_time = expiration_time; op.review_period_seconds = review_period_seconds; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((fee_paying_account)(proposed_ops)(expiration_time)(review_period_seconds)(csaf_fee)(broadcast)) } signed_transaction proposal_update(const string fee_paying_account, proposal_id_type proposal, const flat_set<account_uid_type> secondary_approvals_to_add, const flat_set<account_uid_type> secondary_approvals_to_remove, const flat_set<account_uid_type> active_approvals_to_add, const flat_set<account_uid_type> active_approvals_to_remove, const flat_set<account_uid_type> owner_approvals_to_add, const flat_set<account_uid_type> owner_approvals_to_remove, const flat_set<public_key_type> key_approvals_to_add, const flat_set<public_key_type> key_approvals_to_remove, bool csaf_fee = true, bool broadcast = false ) { try { proposal_update_operation op; op.fee_paying_account = get_account_uid(fee_paying_account); op.proposal = proposal; op.secondary_approvals_to_add = secondary_approvals_to_add; op.secondary_approvals_to_remove = secondary_approvals_to_remove; op.active_approvals_to_add = active_approvals_to_add; op.active_approvals_to_remove = active_approvals_to_remove; op.owner_approvals_to_add = owner_approvals_to_add; op.owner_approvals_to_remove = owner_approvals_to_remove; op.key_approvals_to_add = key_approvals_to_add; op.key_approvals_to_remove = key_approvals_to_remove; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((fee_paying_account)(proposal)(secondary_approvals_to_add)(secondary_approvals_to_remove)(active_approvals_to_add)(active_approvals_to_remove) (owner_approvals_to_add)(owner_approvals_to_remove)(key_approvals_to_add)(key_approvals_to_remove)(csaf_fee)(broadcast)) } signed_transaction proposal_delete(const string fee_paying_account, proposal_id_type proposal, bool csaf_fee = true, bool broadcast = false ) { try { proposal_delete_operation op; op.fee_paying_account = get_account_uid(fee_paying_account); op.proposal = proposal; signed_transaction tx; tx.operations.push_back(op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((fee_paying_account)(proposal)(csaf_fee)(broadcast)) } signed_transaction score_a_post(string from_account, string platform, string poster, post_pid_type post_pid, int8_t score, string csaf, optional<string> sign_platform, bool csaf_fee = true, bool broadcast = false) { try { fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); score_create_operation create_op; create_op.from_account_uid = get_account_uid(from_account); create_op.platform = get_account_uid(platform); create_op.poster = get_account_uid(poster); create_op.post_pid = post_pid; create_op.score = score; create_op.csaf = asset_obj->amount_from_string(csaf).amount; if (sign_platform.valid()){ create_op.sign_platform = get_account_uid(*sign_platform); } signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(score)(csaf)(csaf_fee)(broadcast)) } signed_transaction reward_post(string from_account, string platform, string poster, post_pid_type post_pid, string amount, string asset_symbol, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(asset_symbol); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", asset_symbol)); reward_operation reward_op; reward_op.from_account_uid = get_account_uid(from_account); reward_op.platform = get_account_uid(platform); reward_op.poster = get_account_uid(poster); reward_op.post_pid = post_pid; reward_op.amount = asset_obj->amount_from_string(amount); signed_transaction tx; tx.operations.push_back(reward_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(amount)(asset_symbol)(csaf_fee)(broadcast)) } signed_transaction reward_post_proxy_by_platform(string from_account, string platform, string poster, post_pid_type post_pid, string amount, optional<string> sign_platform, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); reward_proxy_operation reward_op; reward_op.from_account_uid = get_account_uid(from_account); reward_op.platform = get_account_uid(platform); reward_op.poster = get_account_uid(poster); reward_op.post_pid = post_pid; reward_op.amount = asset_obj->amount_from_string(amount).amount; if (sign_platform.valid()){ reward_op.sign_platform = get_account_uid(*sign_platform); } signed_transaction tx; tx.operations.push_back(reward_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(amount)(csaf_fee)(broadcast)) } signed_transaction buyout_post(string from_account, string platform, string poster, post_pid_type post_pid, string receiptor_account, optional<string> sign_platform, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); buyout_operation buyout_op; buyout_op.from_account_uid = get_account_uid(from_account); buyout_op.platform = get_account_uid(platform); buyout_op.poster = get_account_uid(poster); buyout_op.post_pid = post_pid; buyout_op.receiptor_account_uid = get_account_uid(receiptor_account); if (sign_platform.valid()){ buyout_op.sign_platform = get_account_uid(*sign_platform); } signed_transaction tx; tx.operations.push_back(buyout_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((from_account)(platform)(poster)(post_pid)(receiptor_account)(csaf_fee)(broadcast)) } signed_transaction create_license(string platform, uint8_t license_type, string hash_value, string title, string body, string extra_data, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type platform_uid = get_account_uid(platform); fc::optional<platform_object> platform_obj = _remote_db->get_platform_by_account(platform_uid); FC_ASSERT(platform_obj.valid(), "platform doesn`t exsit. "); const account_statistics_object& plat_account_statistics = _remote_db->get_account_statistics_by_uid(platform_uid); license_create_operation create_op; create_op.license_lid = plat_account_statistics.last_license_sequence + 1; create_op.platform = platform_uid; create_op.type = license_type; create_op.hash_value = hash_value; create_op.extra_data = extra_data; create_op.title = title; create_op.body = body; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(license_type)(hash_value)(title)(body)(extra_data)(csaf_fee)(broadcast)) } signed_transaction create_post(string platform, string poster, string hash_value, string title, string body, string extra_data, string origin_platform = "", string origin_poster = "", string origin_post_pid = "", post_create_ext exts = post_create_ext(), bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_uid_type poster_uid = get_account_uid(poster); const account_statistics_object& poster_account_statistics = _remote_db->get_account_statistics_by_uid(poster_uid); post_operation create_op; create_op.post_pid = poster_account_statistics.last_post_sequence + 1; create_op.platform = get_account_uid(platform); create_op.poster = poster_uid; if (!origin_platform.empty()) create_op.origin_platform = get_account_uid(origin_platform); if (!origin_poster.empty()) create_op.origin_poster = get_account_uid(origin_poster); if (!origin_post_pid.empty()) create_op.origin_post_pid = fc::to_uint64(fc::string(origin_post_pid)); create_op.hash_value = hash_value; create_op.extra_data = extra_data; create_op.title = title; create_op.body = body; post_operation::ext extension_; if (exts.post_type) extension_.post_type = exts.post_type; if (exts.forward_price.valid()) extension_.forward_price = asset_obj->amount_from_string(*(exts.forward_price)).amount; if (exts.receiptors.valid()) { map<account_uid_type, Receiptor_Parameter> maps_receiptors; for (auto itor = (*exts.receiptors).begin(); itor != (*exts.receiptors).end(); itor++) { Receiptor_Parameter para; para.cur_ratio = uint16_t(itor->second.cur_ratio * GRAPHENE_1_PERCENT); para.to_buyout = itor->second.to_buyout; para.buyout_ratio = uint16_t(itor->second.buyout_ratio * GRAPHENE_1_PERCENT); para.buyout_price = asset_obj->amount_from_string(itor->second.buyout_price).amount; maps_receiptors.insert(std::make_pair(itor->first, para)); } extension_.receiptors = maps_receiptors; } if (exts.license_lid.valid()) extension_.license_lid = exts.license_lid; if (exts.permission_flags) extension_.permission_flags = exts.permission_flags; if (exts.sign_platform.valid()) extension_.sign_platform = get_account_uid(*(exts.sign_platform)); create_op.extensions = graphene::chain::extension<post_operation::ext>(); create_op.extensions->value = extension_; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(poster)(hash_value)(title)(body)(extra_data)(origin_platform)(origin_poster)(origin_post_pid)(exts)(csaf_fee)(broadcast)) } signed_transaction update_post(string platform, string poster, string post_pid, string hash_value, string title, string body, string extra_data, optional<post_update_ext> ext, bool csaf_fee = true, bool broadcast = false) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); post_update_operation update_op; update_op.post_pid = fc::to_uint64(fc::string(post_pid)); update_op.platform = get_account_uid(platform); update_op.poster = get_account_uid(poster); if (!hash_value.empty()) update_op.hash_value = hash_value; if (!extra_data.empty()) update_op.extra_data = extra_data; if (!title.empty()) update_op.title = title; if (!body.empty()) update_op.body = body; if (ext.valid()) { update_op.extensions = graphene::chain::extension<post_update_operation::ext>(); auto value = *ext; if (value.forward_price.valid()) update_op.extensions->value.forward_price = asset_obj->amount_from_string(*(value.forward_price)).amount; if (value.receiptor.valid()) update_op.extensions->value.receiptor = get_account_uid(*(value.receiptor)); if (value.to_buyout.valid()) update_op.extensions->value.to_buyout = value.to_buyout; if (value.buyout_ratio.valid()) update_op.extensions->value.buyout_ratio = uint16_t((*(value.buyout_ratio))* GRAPHENE_1_PERCENT); if (value.buyout_price.valid()) update_op.extensions->value.buyout_price = asset_obj->amount_from_string(*(value.buyout_price)).amount; if (value.buyout_expiration.valid()) update_op.extensions->value.buyout_expiration = time_point_sec(*(value.buyout_expiration)); if (value.license_lid.valid()) update_op.extensions->value.license_lid = value.license_lid; if (value.permission_flags.valid()) update_op.extensions->value.permission_flags = value.permission_flags; if (value.content_sign_platform.valid()) update_op.extensions->value.content_sign_platform = get_account_uid(*(value.content_sign_platform)); if (value.receiptor_sign_platform.valid()) update_op.extensions->value.receiptor_sign_platform = get_account_uid(*(value.receiptor_sign_platform)); } signed_transaction tx; tx.operations.push_back(update_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(poster)(post_pid)(hash_value)(title)(body)(extra_data)(ext)(csaf_fee)(broadcast)) } signed_transaction account_manage(string executor, string account, account_manage_operation::opt options, bool csaf_fee = true, bool broadcast = false ) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_manage_operation manage_op; manage_op.account = get_account_uid(account); manage_op.executor = get_account_uid(executor); manage_op.options.value = options; signed_transaction tx; tx.operations.push_back(manage_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((executor)(account)(options)(csaf_fee)(broadcast)) } signed_transaction buy_advertising(string account, string platform, advertising_aid_type advertising_aid, uint32_t start_time, uint32_t buy_number, string extra_data, string memo, bool csaf_fee = true, bool broadcast = false ) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type platform_uid = get_account_uid(platform); account_uid_type account_uid = get_account_uid(account); optional<advertising_object> ad_obj = _remote_db->get_advertising(platform_uid, advertising_aid); FC_ASSERT(ad_obj.valid(), "advertising_object doesn`t exsit. "); advertising_buy_operation buy_op; buy_op.from_account = account_uid; buy_op.platform = platform_uid; buy_op.advertising_aid = advertising_aid; buy_op.advertising_order_oid = ad_obj->last_order_sequence + 1; buy_op.start_time = time_point_sec(start_time); buy_op.buy_number = buy_number; buy_op.extra_data = extra_data; account_object user = get_account(account); account_object platform_account = get_account(platform); if (memo.size()) { buy_op.memo = memo_data(); buy_op.memo->from = user.memo_key; buy_op.memo->to = platform_account.memo_key; buy_op.memo->set_message(get_private_key(user.memo_key), platform_account.memo_key, memo); } signed_transaction tx; tx.operations.push_back(buy_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((account)(platform)(advertising_aid)(start_time)(buy_number)(extra_data)(memo)(csaf_fee)(broadcast)) } signed_transaction confirm_advertising(string platform, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool confirm, bool csaf_fee = true, bool broadcast = false ) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); advertising_confirm_operation confirm_op; confirm_op.platform = get_account_uid(platform); confirm_op.advertising_aid = advertising_aid; confirm_op.advertising_order_oid = advertising_order_oid; confirm_op.isconfirm = confirm; signed_transaction tx; tx.operations.push_back(confirm_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(advertising_aid)(advertising_order_oid)(confirm)(csaf_fee)(broadcast)) } post_object get_post(string platform_owner, string poster_uid, string post_pid) { try { post_pid_type postid = fc::to_uint64(fc::string(post_pid)); account_uid_type platform = get_account_uid(platform_owner); account_uid_type poster = get_account_uid(poster_uid); fc::optional<post_object> post = _remote_db->get_post(platform, poster, postid); if (post) return *post; else FC_THROW("poster: ${poster} don't publish post: ${post} in platform: ${platform}", ("poster", poster_uid)("post", post_pid)("platform", platform_owner)); } FC_CAPTURE_AND_RETHROW((platform_owner)(poster_uid)(post_pid)) } vector<post_object> get_posts_by_platform_poster(string platform_owner, optional<string> poster, time_point_sec begin_time_range, time_point_sec end_time_range, object_id_type lower_bound_post, uint32_t limit) { try { account_uid_type platform = get_account_uid(platform_owner); if (poster.valid()){ account_uid_type poster_uid = get_account_uid(*poster); return _remote_db->get_posts_by_platform_poster(platform, poster_uid, std::make_pair(begin_time_range, end_time_range), lower_bound_post, limit); } else{ return _remote_db->get_posts_by_platform_poster(platform, optional<account_uid_type>(), std::make_pair(begin_time_range, end_time_range), lower_bound_post, limit); } } FC_CAPTURE_AND_RETHROW((platform_owner)(poster)(begin_time_range)(end_time_range)(lower_bound_post)(limit)) } uint64_t get_posts_count(optional<string> platform, optional<string> poster) { try { if (platform.valid()) { account_uid_type platform_uid = get_account_uid(*platform); if (poster.valid()) { account_uid_type poster_uid = get_account_uid(*poster); return _remote_db->get_posts_count(platform_uid, poster_uid); } else return _remote_db->get_posts_count(platform_uid, optional<account_uid_type>()); } else { if (poster.valid()) FC_THROW("platform should be valid when poster is valid"); else return _remote_db->get_posts_count(optional<account_uid_type>(), optional<account_uid_type>()); } } FC_CAPTURE_AND_RETHROW((platform)(poster)) } score_object get_score(string platform, string poster_uid, string post_pid, string from_account) { try { post_pid_type postid = fc::to_uint64(fc::string(post_pid)); account_uid_type platform_uid = get_account_uid(platform); account_uid_type poster = get_account_uid(poster_uid); account_uid_type from_uid = get_account_uid(from_account); fc::optional<score_object> score = _remote_db->get_score(platform_uid, poster, postid, from_uid); if (score) return *score; else FC_THROW("score that form account ${from_account} for post ${post} created by poster ${poster} in platform ${platform} not found", ("from_account", from_account)("post", post_pid)("poster", poster_uid)("platform", platform)); } FC_CAPTURE_AND_RETHROW((platform)(poster_uid)(post_pid)(from_account)) } vector<score_object> get_scores_by_uid(string scorer, uint32_t period, object_id_type lower_bound_score, uint32_t limit) { try { account_uid_type scorer_uid = get_account_uid(scorer); return _remote_db->get_scores_by_uid(scorer_uid, period, lower_bound_score, limit); } FC_CAPTURE_AND_RETHROW((scorer)(period)(lower_bound_score)(limit)) } vector<score_object> list_scores(string platform, string poster_uid, string post_pid, object_id_type lower_bound_score, uint32_t limit, bool list_cur_period) { try { post_pid_type postid = fc::to_uint64(fc::string(post_pid)); account_uid_type platform_uid = get_account_uid(platform); account_uid_type poster = get_account_uid(poster_uid); return _remote_db->list_scores(platform_uid, poster, postid, lower_bound_score, limit, list_cur_period); } FC_CAPTURE_AND_RETHROW((platform)(poster_uid)(post_pid)(lower_bound_score)(limit)(list_cur_period)) } license_object get_license(string platform, string license_lid) { try { account_uid_type platform_uid = get_account_uid(platform); license_lid_type lid = fc::to_uint64(fc::string(license_lid)); fc::optional<license_object> license = _remote_db->get_license(platform_uid, lid); if (license) return *license; else FC_THROW("license: ${license} not found in platform: ${platform}", ("license", license_lid)("platform", platform)); } FC_CAPTURE_AND_RETHROW((platform)(license_lid)) } vector<license_object> list_licenses(string platform, object_id_type lower_bound_license, uint32_t limit) { try { account_uid_type platform_uid = get_account_uid(platform); return _remote_db->list_licenses(platform_uid, lower_bound_license, limit); } FC_CAPTURE_AND_RETHROW((platform)(lower_bound_license)(limit)) } vector<advertising_object> list_advertisings(string platform, string lower_bound_advertising, uint32_t limit) { try { account_uid_type platform_uid = get_account_uid(platform); advertising_aid_type lower_advertising_aid = fc::to_uint64(fc::string(lower_bound_advertising)); return _remote_db->list_advertisings(platform_uid, lower_advertising_aid, limit); } FC_CAPTURE_AND_RETHROW((platform)(lower_bound_advertising)(limit)) } vector<active_post_object> get_post_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, string poster, string post_pid) { try { FC_ASSERT(begin_period <= end_period, "begin_period should be less than end_period."); FC_ASSERT(end_period - begin_period <= 100); account_uid_type platform_uid = get_account_uid(platform); account_uid_type poster_uid = get_account_uid(poster); post_pid_type postid = fc::to_uint64(fc::string(post_pid)); return _remote_db->get_post_profits_detail(begin_period, end_period, platform_uid, poster_uid, postid); } FC_CAPTURE_AND_RETHROW((begin_period)(end_period)(platform)(poster)(post_pid)) } vector<Platform_Period_Profit_Detail> get_platform_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, uint32_t lower_bound_index, uint32_t limit) { try { FC_ASSERT(begin_period <= end_period, "begin_period should be less than end_period."); FC_ASSERT(end_period - begin_period <= 100); account_uid_type platform_uid = get_account_uid(platform); return _remote_db->get_platform_profits_detail(begin_period, end_period, platform_uid, lower_bound_index, limit); } FC_CAPTURE_AND_RETHROW((begin_period)(end_period)(platform)(lower_bound_index)(limit)) } vector<Poster_Period_Profit_Detail> get_poster_profits_detail(uint32_t begin_period, uint32_t end_period, string poster, uint32_t lower_bound_index, uint32_t limit) { try { FC_ASSERT(begin_period <= end_period, "begin_period should be less than end_period."); FC_ASSERT(end_period - begin_period <= 100); account_uid_type poster_uid = get_account_uid(poster); return _remote_db->get_poster_profits_detail(begin_period, end_period, poster_uid, lower_bound_index, limit); } FC_CAPTURE_AND_RETHROW((begin_period)(end_period)(poster)(lower_bound_index)(limit)) } share_type get_score_profit(string account, uint32_t period) { try { account_uid_type account_uid = get_account_uid(account); auto dynamic_props = _remote_db->get_dynamic_global_properties(); FC_ASSERT(period <= dynamic_props.current_active_post_sequence, "period does not exist"); return _remote_db->get_score_profit(account_uid, period); } FC_CAPTURE_AND_RETHROW((account)(period)) } account_statistics_object get_account_statistics(string account) { try { account_uid_type account_uid = get_account_uid(account); account_statistics_object plat_account_statistics = _remote_db->get_account_statistics_by_uid(account_uid); return plat_account_statistics; } FC_CAPTURE_AND_RETHROW((account)) } signed_transaction create_advertising(string platform, string description, string unit_price, uint32_t unit_time, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_uid_type platform_uid = get_account_uid(platform); fc::optional<platform_object> platform_obj = _remote_db->get_platform_by_account(platform_uid); FC_ASSERT(platform_obj.valid(), "platform doesn`t exsit. "); const account_statistics_object& plat_account_statistics = _remote_db->get_account_statistics_by_uid(platform_uid); advertising_create_operation create_op; create_op.platform = platform_uid; create_op.advertising_aid = plat_account_statistics.last_advertising_sequence + 1; create_op.description = description; create_op.unit_price = asset_obj->amount_from_string(unit_price).amount; create_op.unit_time = unit_time; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(description)(unit_price)(unit_time)(csaf_fee)(broadcast)) } signed_transaction update_advertising(string platform, advertising_aid_type advertising_aid, optional<string> description, optional<string> unit_price, optional<uint32_t> unit_time, optional<bool> on_sell, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); fc::optional<asset_object_with_data> asset_obj = get_asset(GRAPHENE_CORE_ASSET_AID); FC_ASSERT(asset_obj, "Could not find asset matching ${asset}", ("asset", GRAPHENE_CORE_ASSET_AID)); account_uid_type platform_uid = get_account_uid(platform); advertising_update_operation update_op; update_op.platform = platform_uid; update_op.advertising_aid = advertising_aid; if (description.valid()) update_op.description = *description; if (unit_price.valid()) update_op.unit_price = asset_obj->amount_from_string(*unit_price).amount; if (unit_time.valid()) update_op.unit_time = *unit_time; if (on_sell.valid()) update_op.on_sell = *on_sell; signed_transaction tx; tx.operations.push_back(update_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(advertising_aid)(description)(unit_price)(unit_time)(on_sell)(csaf_fee)(broadcast)) } signed_transaction ransom_advertising(string platform, string from_account, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type platform_uid = get_account_uid(platform); account_uid_type from_account_uid = get_account_uid(from_account); advertising_ransom_operation ransom_op; ransom_op.platform = platform_uid; ransom_op.from_account = from_account_uid; ransom_op.advertising_aid = advertising_aid; ransom_op.advertising_order_oid = advertising_order_oid; signed_transaction tx; tx.operations.push_back(ransom_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((platform)(from_account)(advertising_aid)(advertising_order_oid)(csaf_fee)(broadcast)) } signed_transaction create_custom_vote(string create_account, string title, string description, time_point_sec expired_time, asset_aid_type asset_id, share_type required_amount, uint8_t minimum_selected_items, uint8_t maximum_selected_items, vector<string> options, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type creater = get_account_uid(create_account); const account_statistics_object& creater_statistics = _remote_db->get_account_statistics_by_uid(creater); custom_vote_create_operation create_op; create_op.custom_vote_creater = creater; create_op.vote_vid = creater_statistics.last_custom_vote_sequence + 1; create_op.title = title; create_op.description = description; create_op.vote_expired_time = expired_time; create_op.vote_asset_id = asset_id; create_op.required_asset_amount = required_amount; create_op.minimum_selected_items = minimum_selected_items; create_op.maximum_selected_items = maximum_selected_items; create_op.options = options; signed_transaction tx; tx.operations.push_back(create_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((create_account)(title)(description)(expired_time)(asset_id) (required_amount)(minimum_selected_items)(maximum_selected_items)(options)(csaf_fee)(broadcast)) } signed_transaction cast_custom_vote(string voter, string custom_vote_creater, custom_vote_vid_type custom_vote_vid, set<uint8_t> vote_result, bool csaf_fee, bool broadcast) { try { FC_ASSERT(!self.is_locked(), "Should unlock first"); account_uid_type cast_voter = get_account_uid(voter); account_uid_type creater = get_account_uid(custom_vote_creater); custom_vote_cast_operation vote_op; vote_op.voter = cast_voter; vote_op.custom_vote_creater = creater; vote_op.custom_vote_vid = custom_vote_vid; vote_op.vote_result = vote_result; signed_transaction tx; tx.operations.push_back(vote_op); set_operation_fees(tx, _remote_db->get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } FC_CAPTURE_AND_RETHROW((voter)(custom_vote_creater)(custom_vote_vid)(vote_result)(csaf_fee)(broadcast)) } uint64_t get_account_auth_platform_count(string platform) { try { account_uid_type platform_uid = get_account_uid(platform); return _remote_db->get_account_auth_platform_count(platform_uid); } FC_CAPTURE_AND_RETHROW((platform)) } vector<account_auth_platform_object> list_account_auth_platform_by_platform(string platform, account_uid_type lower_bound_account, uint32_t limit) { try { account_uid_type platform_uid = get_account_uid(platform); return _remote_db->list_account_auth_platform_by_platform(platform_uid, lower_bound_account, limit); } FC_CAPTURE_AND_RETHROW((platform)(lower_bound_account)(limit)) } vector<account_auth_platform_object> list_account_auth_platform_by_account(string account, account_uid_type lower_bound_platform, uint32_t limit) { try { account_uid_type account_uid = get_account_uid(account); return _remote_db->list_account_auth_platform_by_account(account_uid, lower_bound_platform, limit); } FC_CAPTURE_AND_RETHROW((account)(lower_bound_platform)(limit)) } signed_transaction approve_proposal( const string& fee_paying_account, const string& proposal_id, const approval_delta& delta, bool csaf_fee = true, bool broadcast = false) { proposal_update_operation update_op; update_op.fee_paying_account = get_account(fee_paying_account).uid; update_op.proposal = fc::variant(proposal_id).as<proposal_id_type>( 1 ); // make sure the proposal exists get_object( update_op.proposal ); for( const std::string& name : delta.secondary_approvals_to_add ) update_op.secondary_approvals_to_add.insert( get_account( name ).uid ); for( const std::string& name : delta.secondary_approvals_to_remove ) update_op.secondary_approvals_to_remove.insert( get_account( name ).uid ); for( const std::string& name : delta.active_approvals_to_add ) update_op.active_approvals_to_add.insert( get_account( name ).uid ); for( const std::string& name : delta.active_approvals_to_remove ) update_op.active_approvals_to_remove.insert( get_account( name ).uid ); for( const std::string& name : delta.owner_approvals_to_add ) update_op.owner_approvals_to_add.insert( get_account( name ).uid ); for( const std::string& name : delta.owner_approvals_to_remove ) update_op.owner_approvals_to_remove.insert( get_account( name ).uid ); for( const std::string& k : delta.key_approvals_to_add ) update_op.key_approvals_to_add.insert( public_key_type( k ) ); for( const std::string& k : delta.key_approvals_to_remove ) update_op.key_approvals_to_remove.insert( public_key_type( k ) ); signed_transaction tx; tx.operations.push_back(update_op); set_operation_fees(tx, get_global_properties().parameters.current_fees, csaf_fee); tx.validate(); return sign_transaction(tx, broadcast); } void dbg_make_uia(string creator, string symbol) { asset_options opts; opts.flags &= ~(white_list); opts.issuer_permissions = opts.flags; create_asset(get_account(creator).name, symbol, 2, opts, {}, true); } void dbg_push_blocks( const std::string& src_filename, uint32_t count ) { use_debug_api(); (*_remote_debug)->debug_push_blocks( src_filename, count ); (*_remote_debug)->debug_stream_json_objects_flush(); } void dbg_generate_blocks( const std::string& debug_wif_key, uint32_t count ) { use_debug_api(); (*_remote_debug)->debug_generate_blocks( debug_wif_key, count ); (*_remote_debug)->debug_stream_json_objects_flush(); } void dbg_stream_json_objects( const std::string& filename ) { use_debug_api(); (*_remote_debug)->debug_stream_json_objects( filename ); (*_remote_debug)->debug_stream_json_objects_flush(); } void dbg_update_object( const fc::variant_object& update ) { use_debug_api(); (*_remote_debug)->debug_update_object( update ); (*_remote_debug)->debug_stream_json_objects_flush(); } void use_network_node_api() { if( _remote_net_node ) return; try { _remote_net_node = _remote_api->network_node(); } catch( const fc::exception& e ) { std::cerr << "\nCouldn't get network node API. You probably are not configured\n" "to access the network API on the yoyow_node you are\n" "connecting to. Please follow the instructions in README.md to set up an apiaccess file.\n" "\n"; throw(e); } } void use_debug_api() { if( _remote_debug ) return; try { _remote_debug = _remote_api->debug(); } catch( const fc::exception& e ) { std::cerr << "\nCouldn't get debug node API. You probably are not configured\n" "to access the debug API on the node you are connecting to.\n" "\n" "To fix this problem:\n" "- Please ensure you are running debug_node, not witness_node.\n" "- Please follow the instructions in README.md to set up an apiaccess file.\n" "\n"; } } void network_add_nodes( const vector<string>& nodes ) { use_network_node_api(); for( const string& node_address : nodes ) { (*_remote_net_node)->add_node( fc::ip::endpoint::from_string( node_address ) ); } } vector< variant > network_get_connected_peers() { use_network_node_api(); const auto peers = (*_remote_net_node)->get_connected_peers(); vector< variant > result; result.reserve( peers.size() ); for( const auto& peer : peers ) { variant v; fc::to_variant( peer, v, GRAPHENE_MAX_NESTED_OBJECTS ); result.push_back( v ); } return result; } void flood_network(string prefix, uint32_t number_of_transactions) { try { const account_object& master = *_wallet.my_accounts.get<by_name>().lower_bound("import"); int number_of_accounts = number_of_transactions / 3; number_of_transactions -= number_of_accounts; try { dbg_make_uia(master.name, "SHILL"); } catch(...) {/* Ignore; the asset probably already exists.*/} fc::time_point start = fc::time_point::now(); for( int i = 0; i < number_of_accounts; ++i ) { std::ostringstream brain_key; brain_key << "brain key for account " << prefix << i; signed_transaction trx = create_account_with_brain_key(brain_key.str(), prefix + fc::to_string(i), master.name, master.name, /* broadcast = */ true, /* save wallet = */ false); } fc::time_point end = fc::time_point::now(); ilog("Created ${n} accounts in ${time} milliseconds", ("n", number_of_accounts)("time", (end - start).count() / 1000)); start = fc::time_point::now(); for( int i = 0; i < number_of_accounts; ++i ) { signed_transaction trx = transfer(master.name, prefix + fc::to_string(i), "10", "CORE", "", true); trx = transfer(master.name, prefix + fc::to_string(i), "1", "CORE", "", true); } end = fc::time_point::now(); ilog("Transferred to ${n} accounts in ${time} milliseconds", ("n", number_of_accounts*2)("time", (end - start).count() / 1000)); start = fc::time_point::now(); for( int i = 0; i < number_of_accounts; ++i ) { signed_transaction trx = issue_asset(prefix + fc::to_string(i), "1000", "SHILL", "", true); } end = fc::time_point::now(); ilog("Issued to ${n} accounts in ${time} milliseconds", ("n", number_of_accounts)("time", (end - start).count() / 1000)); } catch (...) { throw; } } operation get_prototype_operation( string operation_name ) { auto it = _prototype_ops.find( operation_name ); if( it == _prototype_ops.end() ) FC_THROW("Unsupported operation: \"${operation_name}\"", ("operation_name", operation_name)); return it->second; } string _wallet_filename; wallet_data _wallet; map<public_key_type,string> _keys; fc::sha512 _checksum; chain_id_type _chain_id; fc::api<login_api> _remote_api; fc::api<database_api> _remote_db; fc::api<network_broadcast_api> _remote_net_broadcast; fc::api<history_api> _remote_hist; optional< fc::api<network_node_api> > _remote_net_node; optional< fc::api<graphene::debug_witness::debug_api> > _remote_debug; flat_map<string, operation> _prototype_ops; static_variant_map _operation_which_map = create_static_variant_map< operation >(); #ifdef __unix__ mode_t _old_umask; #endif const string _wallet_filename_extension = ".wallet"; }; std::string operation_printer::fee(const asset& a)const { out << " (Fee: " << wallet.get_asset(a.asset_id).amount_to_pretty_string(a) << ")"; return ""; } BOOST_TTI_HAS_MEMBER_DATA(fee) template<typename T> const asset get_operation_total_fee(const T& op, std::true_type) { return op.fee; } template<typename T> const asset get_operation_total_fee(const T& op, std::false_type) { return op.fee.total; } template<typename T> const asset get_operation_total_fee(const T& op) { const bool b = has_member_data_fee<T,asset>::value; return get_operation_total_fee( op, std::integral_constant<bool, b>() ); } template<typename T> std::string operation_printer::operator()(const T& op)const { //balance_accumulator acc; //op.get_balance_delta( acc, result ); asset op_fee = get_operation_total_fee(op); auto a = wallet.get_asset( op_fee.asset_id ); // TODO: review //auto payer = wallet.get_account( op.fee_payer() ); auto payer_uid = op.fee_payer_uid(); string op_name = fc::get_typename<T>::name(); if( op_name.find_last_of(':') != string::npos ) op_name.erase(0, op_name.find_last_of(':')+1); out << op_name <<" "; // out << "balance delta: " << fc::json::to_string(acc.balance) <<" "; //out << payer.name << " fee: " << a.amount_to_pretty_string( op.fee ); out << payer_uid << " fee: " << a.amount_to_pretty_string( op_fee ); operation_result_printer rprinter(wallet); std::string str_result = result.visit(rprinter); if( str_result != "" ) { out << " result: " << str_result; } return ""; } string operation_printer::operator()(const transfer_operation& op) const { out << "Transfer " << wallet.get_asset(op.amount.asset_id).amount_to_pretty_string(op.amount) << " from " << op.from << " to " << op.to; std::string memo; if( op.memo ) { if( wallet.is_locked() ) { out << " -- Unlock wallet to see memo."; } else { try { FC_ASSERT(wallet._keys.count(op.memo->to) || wallet._keys.count(op.memo->from), "Memo is encrypted to a key ${to} or ${from} not in this wallet.", ("to", op.memo->to)("from",op.memo->from)); if( wallet._keys.count(op.memo->to) ) { auto my_key = wif_to_key(wallet._keys.at(op.memo->to)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->from); out << " -- Memo: " << memo; } else { auto my_key = wif_to_key(wallet._keys.at(op.memo->from)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->to); out << " -- Memo: " << memo; } } catch (const fc::exception& e) { out << " -- could not decrypt memo"; //elog("Error when decrypting memo: ${e}", ("e", e.to_detail_string())); } } } fee(op.fee.total); return memo; } string operation_printer::operator()(const override_transfer_operation& op) const { out << "Override-transfer " << wallet.get_asset(op.amount.asset_id).amount_to_pretty_string(op.amount) << " from " << op.from << " to " << op.to; std::string memo; if( op.memo ) { if( wallet.is_locked() ) { out << " -- Unlock wallet to see memo."; } else { try { FC_ASSERT(wallet._keys.count(op.memo->to) || wallet._keys.count(op.memo->from), "Memo is encrypted to a key ${to} or ${from} not in this wallet.", ("to", op.memo->to)("from",op.memo->from)); if( wallet._keys.count(op.memo->to) ) { auto my_key = wif_to_key(wallet._keys.at(op.memo->to)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->from); out << " -- Memo: " << memo; } else { auto my_key = wif_to_key(wallet._keys.at(op.memo->from)); FC_ASSERT(my_key, "Unable to recover private key to decrypt memo. Wallet may be corrupted."); memo = op.memo->get_message(*my_key, op.memo->to); out << " -- Memo: " << memo; } } catch (const fc::exception& e) { out << " -- could not decrypt memo"; //elog("Error when decrypting memo: ${e}", ("e", e.to_detail_string())); } } } fee(op.fee.total); return memo; } std::string operation_printer::operator()(const account_create_operation& op) const { out << "Create Account '" << op.name << "'"; return fee(op.fee.total); } std::string operation_printer::operator()(const asset_create_operation& op) const { out << "Create "; out << "Asset "; out << "'" << op.symbol << "' with issuer " << wallet.get_account(op.issuer).name; return fee(op.fee.total); } std::string operation_result_printer::operator()(const void_result& x) const { return ""; } std::string operation_result_printer::operator()(const object_id_type& oid) { return std::string(oid); } std::string operation_result_printer::operator()(const asset& a) { return _wallet.get_asset(a.asset_id).amount_to_pretty_string(a); } std::string operation_result_printer::operator()(const advertising_confirm_result& a) { std::string str = "Return the deposit money: \n"; for (auto iter : a) { str += " account: " + to_string(iter.first) + " : " + to_string(iter.second.value) + "\n"; } return str; } }}} namespace graphene { namespace wallet { vector<brain_key_info> utility::derive_owner_keys_from_brain_key(string brain_key, int number_of_desired_keys) { // Safety-check FC_ASSERT( number_of_desired_keys >= 1 ); // Create as many derived owner keys as requested vector<brain_key_info> results; brain_key = graphene::wallet::detail::normalize_brain_key(brain_key); for (int i = 0; i < number_of_desired_keys; ++i) { fc::ecc::private_key priv_key = graphene::wallet::detail::derive_private_key( brain_key, i ); brain_key_info result; result.brain_priv_key = brain_key; result.wif_priv_key = key_to_wif( priv_key ); result.pub_key = priv_key.get_public_key(); results.push_back(result); } return results; } }} namespace graphene { namespace wallet { wallet_api::wallet_api(const wallet_data& initial_data, fc::api<login_api> rapi) : my(new detail::wallet_api_impl(*this, initial_data, rapi)) { } wallet_api::~wallet_api() { } bool wallet_api::copy_wallet_file(string destination_filename) { return my->copy_wallet_file(destination_filename); } optional<signed_block_with_info> wallet_api::get_block(uint32_t num) { return my->_remote_db->get_block(num); } uint64_t wallet_api::get_account_count() const { return my->_remote_db->get_account_count(); } vector<account_object> wallet_api::list_my_accounts_cached() { // TODO this implementation has caching issue. To get latest data, check the steps in `load_wallet_file()` return vector<account_object>(my->_wallet.my_accounts.begin(), my->_wallet.my_accounts.end()); } map<string,account_uid_type> wallet_api::list_accounts_by_name(const string& lowerbound, uint32_t limit) { return my->_remote_db->lookup_accounts_by_name(lowerbound, limit); } vector<asset> wallet_api::list_account_balances(const string& account) { return my->_remote_db->get_account_balances( get_account( account ).uid, flat_set<asset_aid_type>() ); } vector<asset_object_with_data> wallet_api::list_assets(const string& lowerbound, uint32_t limit)const { return my->_remote_db->list_assets( lowerbound, limit ); } vector<operation_detail> wallet_api::get_relative_account_history(string account, optional<uint16_t> op_type, uint32_t stop, int limit, uint32_t start)const { vector<operation_detail> result; account_uid_type uid = get_account( account ).uid; while( limit > 0 ) { vector <pair<uint32_t,operation_history_object>> current = my->_remote_hist->get_relative_account_history(uid, op_type, stop, std::min<uint32_t>(100, limit), start); for (auto &p : current) { auto &o = p.second; std::stringstream ss; auto memo = o.op.visit(detail::operation_printer(ss, *my, o.result)); result.push_back(operation_detail{memo, ss.str(), p.first, o}); } if (current.size() < std::min<uint32_t>(100, limit)) break; limit -= current.size(); start = result.back().sequence - 1; if( start == 0 || start < stop ) break; } return result; } uint64_t wallet_api::calculate_account_uid(uint64_t n)const { return calc_account_uid( n ); } brain_key_info wallet_api::suggest_brain_key()const { brain_key_info result; // create a private key for secure entropy fc::sha256 sha_entropy1 = fc::ecc::private_key::generate().get_secret(); fc::sha256 sha_entropy2 = fc::ecc::private_key::generate().get_secret(); fc::bigint entropy1( sha_entropy1.data(), sha_entropy1.data_size() ); fc::bigint entropy2( sha_entropy2.data(), sha_entropy2.data_size() ); fc::bigint entropy(entropy1); entropy <<= 8*sha_entropy1.data_size(); entropy += entropy2; string brain_key = ""; for( int i=0; i<BRAIN_KEY_WORD_COUNT; i++ ) { fc::bigint choice = entropy % graphene::words::word_list_size; entropy /= graphene::words::word_list_size; if( i > 0 ) brain_key += " "; brain_key += graphene::words::word_list[ choice.to_int64() ]; } brain_key = normalize_brain_key(brain_key); fc::ecc::private_key priv_key = derive_private_key( brain_key, 0 ); result.brain_priv_key = brain_key; result.wif_priv_key = key_to_wif( priv_key ); result.pub_key = priv_key.get_public_key(); return result; } vector<brain_key_info> wallet_api::derive_owner_keys_from_brain_key(string brain_key, int number_of_desired_keys) const { return graphene::wallet::utility::derive_owner_keys_from_brain_key(brain_key, number_of_desired_keys); } bool wallet_api::is_public_key_registered(string public_key) const { bool is_known = my->_remote_db->is_public_key_registered(public_key); return is_known; } string wallet_api::serialize_transaction( signed_transaction tx )const { return fc::to_hex(fc::raw::pack(tx)); } variant wallet_api::get_object( object_id_type id ) const { return my->_remote_db->get_objects({id}); } string wallet_api::get_wallet_filename() const { return my->get_wallet_filename(); } transaction_handle_type wallet_api::begin_builder_transaction() { return my->begin_builder_transaction(); } void wallet_api::add_operation_to_builder_transaction(transaction_handle_type transaction_handle, const operation& op) { my->add_operation_to_builder_transaction(transaction_handle, op); } void wallet_api::replace_operation_in_builder_transaction(transaction_handle_type handle, unsigned operation_index, const operation& new_op) { my->replace_operation_in_builder_transaction(handle, operation_index, new_op); } asset wallet_api::set_fees_on_builder_transaction(transaction_handle_type handle, string fee_asset) { return my->set_fees_on_builder_transaction(handle, fee_asset); } transaction wallet_api::preview_builder_transaction(transaction_handle_type handle) { return my->preview_builder_transaction(handle); } signed_transaction wallet_api::sign_builder_transaction(transaction_handle_type transaction_handle, bool broadcast) { return my->sign_builder_transaction(transaction_handle, broadcast); } signed_transaction wallet_api::propose_builder_transaction( transaction_handle_type handle, string account_name_or_id, time_point_sec expiration, uint32_t review_period_seconds, bool broadcast) { return my->propose_builder_transaction(handle, account_name_or_id, expiration, review_period_seconds, broadcast); } void wallet_api::remove_builder_transaction(transaction_handle_type handle) { return my->remove_builder_transaction(handle); } account_object wallet_api::get_account(string account_name_or_id) const { return my->get_account(account_name_or_id); } full_account wallet_api::get_full_account(string account_name_or_uid) const { account_uid_type uid = my->get_account_uid( account_name_or_uid ); vector<account_uid_type> uids( 1, uid ); full_account_query_options opt = { true, true, true, true, true, true, true, true, true, true, true, true, true }; const auto& results = my->_remote_db->get_full_accounts_by_uid( uids, opt ); return results.at( uid ); } asset_object_with_data wallet_api::get_asset(string asset_name_or_id) const { auto a = my->find_asset(asset_name_or_id); FC_ASSERT( a, "Can not find asset ${a}", ("a", asset_name_or_id) ); return *a; } asset_aid_type wallet_api::get_asset_aid(string asset_symbol_or_id) const { return my->get_asset_aid(asset_symbol_or_id); } bool wallet_api::import_key(string account_name_or_id, string wif_key) { FC_ASSERT(!is_locked(), "Should unlock first"); // backup wallet fc::optional<fc::ecc::private_key> optional_private_key = wif_to_key(wif_key); if (!optional_private_key) FC_THROW("Invalid private key"); //string shorthash = detail::address_to_shorthash(optional_private_key->get_public_key()); //copy_wallet_file( "before-import-key-" + shorthash ); bool result = my->import_key(account_name_or_id, wif_key); save_wallet_file(); //copy_wallet_file( "after-import-key-" + shorthash ); return result; } map<string, bool> wallet_api::import_accounts( string filename, string password ) { FC_ASSERT( !is_locked() ); FC_ASSERT( fc::exists( filename ) ); const auto imported_keys = fc::json::from_file<exported_keys>( filename ); const auto password_hash = fc::sha512::hash( password ); FC_ASSERT( fc::sha512::hash( password_hash ) == imported_keys.password_checksum ); map<string, bool> result; for( const auto& item : imported_keys.account_keys ) { const auto import_this_account = [ & ]() -> bool { try { const account_object account = get_account( item.account_name ); const auto& owner_keys = account.owner.get_keys(); const auto& active_keys = account.active.get_keys(); for( const auto& public_key : item.public_keys ) { if( std::find( owner_keys.begin(), owner_keys.end(), public_key ) != owner_keys.end() ) return true; if( std::find( active_keys.begin(), active_keys.end(), public_key ) != active_keys.end() ) return true; } } catch( ... ) { } return false; }; const auto should_proceed = import_this_account(); result[ item.account_name ] = should_proceed; if( should_proceed ) { uint32_t import_successes = 0; uint32_t import_failures = 0; // TODO: First check that all private keys match public keys for( const auto& encrypted_key : item.encrypted_private_keys ) { try { const auto plain_text = fc::aes_decrypt( password_hash, encrypted_key ); const auto private_key = fc::raw::unpack<private_key_type>( plain_text ); import_key( item.account_name, string( graphene::utilities::key_to_wif( private_key ) ) ); ++import_successes; } catch( const fc::exception& e ) { elog( "Couldn't import key due to exception ${e}", ("e", e.to_detail_string()) ); ++import_failures; } } ilog( "successfully imported ${n} keys for account ${name}", ("n", import_successes)("name", item.account_name) ); if( import_failures > 0 ) elog( "failed to import ${n} keys for account ${name}", ("n", import_failures)("name", item.account_name) ); } } return result; } bool wallet_api::import_account_keys( string filename, string password, string src_account_name, string dest_account_name ) { FC_ASSERT( !is_locked() ); FC_ASSERT( fc::exists( filename ) ); bool is_my_account = false; const auto accounts = list_my_accounts_cached(); for( const auto& account : accounts ) { if( account.name == dest_account_name ) { is_my_account = true; break; } } FC_ASSERT( is_my_account ); const auto imported_keys = fc::json::from_file<exported_keys>( filename ); const auto password_hash = fc::sha512::hash( password ); FC_ASSERT( fc::sha512::hash( password_hash ) == imported_keys.password_checksum ); bool found_account = false; for( const auto& item : imported_keys.account_keys ) { if( item.account_name != src_account_name ) continue; found_account = true; for( const auto& encrypted_key : item.encrypted_private_keys ) { const auto plain_text = fc::aes_decrypt( password_hash, encrypted_key ); const auto private_key = fc::raw::unpack<private_key_type>( plain_text ); my->import_key( dest_account_name, string( graphene::utilities::key_to_wif( private_key ) ) ); } return true; } save_wallet_file(); FC_ASSERT( found_account ); return false; } string wallet_api::normalize_brain_key(string s) const { return detail::normalize_brain_key( s ); } variant wallet_api::info() { return my->info(); } variant_object wallet_api::about() const { return my->about(); } fc::ecc::private_key wallet_api::derive_private_key(const std::string& prefix_string, int sequence_number) const { return detail::derive_private_key( prefix_string, sequence_number ); } signed_transaction wallet_api::register_account(string name, public_key_type owner_pubkey, public_key_type active_pubkey, string registrar_account, string referrer_account, uint32_t referrer_percent, uint32_t seed, bool csaf_fee, bool broadcast) { return my->register_account(name, owner_pubkey, active_pubkey, registrar_account, referrer_account, referrer_percent, seed, csaf_fee, broadcast); } signed_transaction wallet_api::create_account_with_brain_key(string brain_key, string account_name, string registrar_account, string referrer_account, uint32_t id, bool csaf_fee, bool broadcast /* = false */) { return my->create_account_with_brain_key( brain_key, account_name, registrar_account, referrer_account, id, csaf_fee, broadcast ); } signed_transaction wallet_api::issue_asset(string to_account, string amount, string symbol, string memo, bool csaf_fee, bool broadcast) { return my->issue_asset(to_account, amount, symbol, memo, csaf_fee, broadcast); } signed_transaction wallet_api::transfer_new(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee, bool broadcast /* = false */) { return my->transfer(from, to, amount, asset_symbol, memo, csaf_fee, broadcast); } signed_transaction wallet_api::transfer(string from, string to, string amount, string asset_symbol, string memo,bool broadcast /* = false */) { return my->transfer(from, to, amount, asset_symbol, memo, true, broadcast); } signed_transaction wallet_api::transfer_extension(string from, string to, string amount, string asset_symbol, string memo, optional<string> sign_platform, bool isfrom_balance, bool isto_balance, bool csaf_fee, bool broadcast) { return my->transfer_extension(from, to, amount, asset_symbol, memo, sign_platform, isfrom_balance, isto_balance, csaf_fee, broadcast); } signed_transaction wallet_api::override_transfer(string from, string to, string amount, string asset_symbol, string memo, bool csaf_fee, bool broadcast /* = false */) { return my->override_transfer(from, to, amount, asset_symbol, memo, csaf_fee, broadcast); } signed_transaction wallet_api::create_asset(string issuer, string symbol, uint8_t precision, asset_options common, share_type initial_supply, bool csaf_fee, bool broadcast) { return my->create_asset(issuer, symbol, precision, common, initial_supply, csaf_fee, broadcast); } signed_transaction wallet_api::update_asset(string symbol, optional<uint8_t> new_precision, asset_options new_options, bool csaf_fee, bool broadcast /* = false */) { return my->update_asset(symbol, new_precision, new_options, csaf_fee, broadcast); } signed_transaction wallet_api::reserve_asset(string from, string amount, string symbol, bool csaf_fee, bool broadcast /* = false */) { return my->reserve_asset(from, amount, symbol, csaf_fee, broadcast); } signed_transaction wallet_api::whitelist_account(string authorizing_account, string account_to_list, account_whitelist_operation::account_listing new_listing_status, bool csaf_fee, bool broadcast /* = false */) { return my->whitelist_account(authorizing_account, account_to_list, new_listing_status, csaf_fee, broadcast); } signed_transaction wallet_api::create_committee_member(string owner_account, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { return my->create_committee_member(owner_account, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); } vector<witness_object> wallet_api::list_witnesses(const account_uid_type lowerbound, uint32_t limit, data_sorting_type order_by) { return my->_remote_db->lookup_witnesses(lowerbound, limit, order_by); } vector<committee_member_object> wallet_api::list_committee_members(const account_uid_type lowerbound, uint32_t limit, data_sorting_type order_by) { return my->_remote_db->lookup_committee_members(lowerbound, limit, order_by); } vector<committee_proposal_object> wallet_api::list_committee_proposals() { return my->_remote_db->list_committee_proposals(); } witness_object wallet_api::get_witness(string owner_account) { return my->get_witness(owner_account); } platform_object wallet_api::get_platform(string owner_account) { return my->get_platform(owner_account); } vector<platform_object> wallet_api::list_platforms(const account_uid_type lowerbound, uint32_t limit, data_sorting_type order_by) { return my->_remote_db->lookup_platforms(lowerbound, limit, order_by); } uint64_t wallet_api::get_platform_count() { return my->_remote_db->get_platform_count(); } committee_member_object wallet_api::get_committee_member(string owner_account) { return my->get_committee_member(owner_account); } signed_transaction wallet_api::create_witness(string owner_account, public_key_type block_signing_key, string pledge_amount, string pledge_asset_symbol, string url, bool csaf_fee, bool broadcast /* = false */) { return my->create_witness_with_details(owner_account, block_signing_key, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); //return my->create_witness(owner_account, url, broadcast); } signed_transaction wallet_api::create_platform(string owner_account, string name, string pledge_amount, string pledge_asset_symbol, string url, string extra_data, bool csaf_fee, bool broadcast ) { return my->create_platform( owner_account, name, pledge_amount, pledge_asset_symbol, url, extra_data, csaf_fee, broadcast ); } signed_transaction wallet_api::update_platform(string platform_account, optional<string> name, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, optional<string> extra_data, bool csaf_fee, bool broadcast ) { return my->update_platform( platform_account, name, pledge_amount, pledge_asset_symbol, url, extra_data, csaf_fee, broadcast ); } signed_transaction wallet_api::update_platform_votes(string voting_account, flat_set<string> platforms_to_add, flat_set<string> platforms_to_remove, bool csaf_fee, bool broadcast ) { return my->update_platform_votes( voting_account, platforms_to_add, platforms_to_remove, csaf_fee, broadcast ); } signed_transaction wallet_api::account_auth_platform(string account, string platform_owner, string memo, string limit_for_platform, uint32_t permission_flags, bool csaf_fee, bool broadcast) { return my->account_auth_platform(account, platform_owner, memo, limit_for_platform, permission_flags, csaf_fee, broadcast); } signed_transaction wallet_api::account_cancel_auth_platform(string account, string platform_owner, bool csaf_fee, bool broadcast) { return my->account_cancel_auth_platform( account, platform_owner, csaf_fee, broadcast ); } signed_transaction wallet_api::update_committee_member( string committee_member_account, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { return my->update_committee_member(committee_member_account, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); } signed_transaction wallet_api::update_witness( string witness_account, optional<public_key_type> block_signing_key, optional<string> pledge_amount, optional<string> pledge_asset_symbol, optional<string> url, bool csaf_fee, bool broadcast /* = false */) { return my->update_witness_with_details(witness_account, block_signing_key, pledge_amount, pledge_asset_symbol, url, csaf_fee, broadcast); //return my->update_witness(witness_name, url, block_signing_key, broadcast); } signed_transaction wallet_api::collect_witness_pay(string witness_account, string pay_amount, string pay_asset_symbol, bool csaf_fee, bool broadcast /* = false */) { return my->collect_witness_pay(witness_account, pay_amount, pay_asset_symbol, csaf_fee, broadcast); } signed_transaction wallet_api::collect_csaf_new(string from, string to, string amount, string asset_symbol, bool csaf_fee, bool broadcast /* = false */) { time_point_sec time( time_point::now().sec_since_epoch() / 60 * 60 ); return my->collect_csaf(from, to, amount, asset_symbol, time, csaf_fee, broadcast); } signed_transaction wallet_api::collect_csaf(string from, string to, string amount, string asset_symbol, bool broadcast /* = false */) { time_point_sec time( time_point::now().sec_since_epoch() / 60 * 60 ); return my->collect_csaf(from, to, amount, asset_symbol, time, true, broadcast); } signed_transaction wallet_api::collect_csaf_with_time(string from, string to, string amount, string asset_symbol, time_point_sec time, bool csaf_fee, bool broadcast /* = false */) { return my->collect_csaf(from, to, amount, asset_symbol, time, csaf_fee, broadcast); } string wallet_api::compute_available_csaf(string account_name_or_uid) { account_uid_type uid = my->get_account_uid( account_name_or_uid ); vector<account_uid_type> uids( 1, uid ); full_account_query_options opt = { true, true, false, false, false, false, false, false, false, false, false, false, false }; const auto& results = my->_remote_db->get_full_accounts_by_uid( uids, opt ); auto& account = results.at( uid ); const auto& global_params = my->get_global_properties().parameters; auto csaf = account.statistics.compute_coin_seconds_earned( global_params.csaf_accumulate_window, time_point_sec(time_point::now()) ).first; auto ao = my->get_asset( GRAPHENE_CORE_ASSET_AID ); auto s1 = global_params.max_csaf_per_account - account.statistics.csaf; auto s2 = (csaf / global_params.csaf_rate).to_uint64(); return ao.amount_to_string(s1 > s2 ? s2 : s1); } signed_transaction wallet_api::update_witness_votes(string voting_account, flat_set<string> witnesses_to_add, flat_set<string> witnesses_to_remove, bool csaf_fee, bool broadcast /* = false */) { return my->update_witness_votes( voting_account, witnesses_to_add, witnesses_to_remove, csaf_fee, broadcast ); } signed_transaction wallet_api::update_committee_member_votes(string voting_account, flat_set<string> committee_members_to_add, flat_set<string> committee_members_to_remove, bool csaf_fee, bool broadcast /* = false */) { return my->update_committee_member_votes( voting_account, committee_members_to_add, committee_members_to_remove, csaf_fee, broadcast ); } signed_transaction wallet_api::set_voting_proxy(string account_to_modify, optional<string> voting_account, bool csaf_fee, bool broadcast /* = false */) { return my->set_voting_proxy(account_to_modify, voting_account, csaf_fee, broadcast); } signed_transaction wallet_api::enable_allowed_assets(string account, bool enable, bool csaf_fee, bool broadcast /* = false */) { return my->enable_allowed_assets( account, enable, csaf_fee, broadcast ); } signed_transaction wallet_api::update_allowed_assets(string account, flat_set<string> assets_to_add, flat_set<string> assets_to_remove, bool csaf_fee, bool broadcast /* = false */) { return my->update_allowed_assets( account, assets_to_add, assets_to_remove, csaf_fee, broadcast ); } void wallet_api::set_wallet_filename(string wallet_filename) { my->_wallet_filename = wallet_filename; } signed_transaction wallet_api::sign_transaction(signed_transaction tx, bool broadcast /* = false */) { try { return my->sign_transaction( tx, broadcast); } FC_CAPTURE_AND_RETHROW( (tx) ) } transaction_id_type wallet_api::broadcast_transaction(signed_transaction tx) { try { return my->broadcast_transaction( tx ); } FC_CAPTURE_AND_RETHROW( (tx) ) } operation wallet_api::get_prototype_operation(string operation_name) { return my->get_prototype_operation( operation_name ); } void wallet_api::dbg_make_uia(string creator, string symbol) { FC_ASSERT(!is_locked()); my->dbg_make_uia(creator, symbol); } void wallet_api::dbg_push_blocks( std::string src_filename, uint32_t count ) { my->dbg_push_blocks( src_filename, count ); } void wallet_api::dbg_generate_blocks( std::string debug_wif_key, uint32_t count ) { my->dbg_generate_blocks( debug_wif_key, count ); } void wallet_api::dbg_stream_json_objects( const std::string& filename ) { my->dbg_stream_json_objects( filename ); } void wallet_api::dbg_update_object( fc::variant_object update ) { my->dbg_update_object( update ); } void wallet_api::network_add_nodes( const vector<string>& nodes ) { my->network_add_nodes( nodes ); } vector< variant > wallet_api::network_get_connected_peers() { return my->network_get_connected_peers(); } void wallet_api::flood_network(string prefix, uint32_t number_of_transactions) { FC_ASSERT(!is_locked()); my->flood_network(prefix, number_of_transactions); } signed_transaction wallet_api::committee_proposal_create( const string committee_member_account, const vector<committee_proposal_item_type> items, const uint32_t voting_closing_block_num, optional<voting_opinion_type> proposer_opinion, const uint32_t execution_block_num, const uint32_t expiration_block_num, bool csaf_fee, bool broadcast ) { return my->committee_proposal_create( committee_member_account, items, voting_closing_block_num, proposer_opinion, execution_block_num, expiration_block_num, csaf_fee, broadcast ); } signed_transaction wallet_api::committee_proposal_vote( const string committee_member_account, const uint64_t proposal_number, const voting_opinion_type opinion, bool csaf_fee, bool broadcast /* = false */ ) { return my->committee_proposal_vote( committee_member_account, proposal_number, opinion, csaf_fee, broadcast ); } signed_transaction wallet_api::proposal_create(const string fee_paying_account, const vector<op_wrapper> proposed_ops, time_point_sec expiration_time, uint32_t review_period_seconds, bool csaf_fee, bool broadcast ) { return my->proposal_create(fee_paying_account, proposed_ops, expiration_time, review_period_seconds, csaf_fee, broadcast); } signed_transaction wallet_api::proposal_update(const string fee_paying_account, proposal_id_type proposal, const flat_set<account_uid_type> secondary_approvals_to_add, const flat_set<account_uid_type> secondary_approvals_to_remove, const flat_set<account_uid_type> active_approvals_to_add, const flat_set<account_uid_type> active_approvals_to_remove, const flat_set<account_uid_type> owner_approvals_to_add, const flat_set<account_uid_type> owner_approvals_to_remove, const flat_set<public_key_type> key_approvals_to_add, const flat_set<public_key_type> key_approvals_to_remove, bool csaf_fee, bool broadcast ) { return my->proposal_update(fee_paying_account, proposal, secondary_approvals_to_add, secondary_approvals_to_remove, active_approvals_to_add, active_approvals_to_remove, owner_approvals_to_add, owner_approvals_to_remove, key_approvals_to_add, key_approvals_to_remove, csaf_fee, broadcast); } signed_transaction wallet_api::proposal_delete(const string fee_paying_account, proposal_id_type proposal, bool csaf_fee, bool broadcast ) { return my->proposal_delete(fee_paying_account, proposal, csaf_fee, broadcast); } signed_transaction wallet_api::score_a_post(string from_account, string platform, string poster, post_pid_type post_pid, int8_t score, string csaf, optional<string> sign_platform, bool csaf_fee, bool broadcast) { return my->score_a_post(from_account, platform, poster, post_pid, score, csaf, sign_platform, csaf_fee, broadcast); } signed_transaction wallet_api::reward_post(string from_account, string platform, string poster, post_pid_type post_pid, string amount, string asset_symbol, bool csaf_fee, bool broadcast) { return my->reward_post(from_account, platform, poster, post_pid, amount, asset_symbol, csaf_fee, broadcast); } signed_transaction wallet_api::reward_post_proxy_by_platform(string from_account, string platform, string poster, post_pid_type post_pid, string amount, optional<string> sign_platform, bool csaf_fee, bool broadcast) { return my->reward_post_proxy_by_platform(from_account, platform, poster, post_pid, amount, sign_platform, csaf_fee, broadcast); } signed_transaction wallet_api::buyout_post(string from_account, string platform, string poster, post_pid_type post_pid, string receiptor_account, optional<string> sign_platform, bool csaf_fee, bool broadcast) { return my->buyout_post(from_account, platform, poster, post_pid, receiptor_account, sign_platform, csaf_fee, broadcast); } signed_transaction wallet_api::create_license(string platform, uint8_t license_type, string hash_value, string title, string body, string extra_data, bool csaf_fee, bool broadcast) { return my->create_license(platform, license_type, hash_value, title, body, extra_data, csaf_fee, broadcast); } signed_transaction wallet_api::create_post(string platform, string poster, string hash_value, string title, string body, string extra_data, string origin_platform, string origin_poster, string origin_post_pid, post_create_ext ext, bool csaf_fee, bool broadcast) { return my->create_post(platform, poster, hash_value, title, body, extra_data, origin_platform, origin_poster, origin_post_pid, ext, csaf_fee, broadcast); } signed_transaction wallet_api::update_post(string platform, string poster, string post_pid, string hash_value, string title, string body, string extra_data, optional<post_update_ext> ext, bool csaf_fee, bool broadcast) { return my->update_post(platform, poster, post_pid, hash_value, title, body, extra_data, ext, csaf_fee, broadcast); } signed_transaction wallet_api::account_manage(string executor, string account, account_manage_operation::opt options, bool csaf_fee, bool broadcast ) { return my->account_manage(executor,account, options, csaf_fee, broadcast); } signed_transaction wallet_api::buy_advertising(string account, string platform, advertising_aid_type advertising_aid, uint32_t start_time, uint32_t buy_number, string extra_data, string memo, bool csaf_fee, bool broadcast) { return my->buy_advertising(account, platform, advertising_aid, start_time, buy_number, extra_data, memo, csaf_fee, broadcast); } signed_transaction wallet_api::confirm_advertising(string platform, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool confirm, bool csaf_fee, bool broadcast) { return my->confirm_advertising(platform, advertising_aid, advertising_order_oid, confirm, csaf_fee, broadcast); } post_object wallet_api::get_post(string platform_owner, string poster_uid, string post_pid) { return my->get_post(platform_owner, poster_uid, post_pid); } vector<post_object> wallet_api::get_posts_by_platform_poster(string platform_owner, optional<string> poster, uint32_t begin_time_range, uint32_t end_time_range, object_id_type lower_bound_post, uint32_t limit) { time_point_sec begin_time(begin_time_range); time_point_sec end_time(end_time_range); return my->get_posts_by_platform_poster(platform_owner, poster, begin_time, end_time, lower_bound_post, limit); } uint64_t wallet_api::get_posts_count(optional<string> platform, optional<string> poster) { return my->get_posts_count(platform, poster); } score_object wallet_api::get_score(string platform, string poster_uid, string post_pid, string from_account) { return my->get_score(platform, poster_uid, post_pid, from_account); } vector<score_object> wallet_api::get_scores_by_uid(string scorer, uint32_t period, object_id_type lower_bound_score, uint32_t limit) { return my->get_scores_by_uid(scorer, period, lower_bound_score, limit); } vector<score_object> wallet_api::list_scores(string platform, string poster_uid, string post_pid, object_id_type lower_bound_score, uint32_t limit, bool list_cur_period) { return my->list_scores(platform, poster_uid, post_pid, lower_bound_score, limit, list_cur_period); } license_object wallet_api::get_license(string platform, string license_lid) { return my->get_license(platform, license_lid); } vector<license_object> wallet_api::list_licenses(string platform, object_id_type lower_bound_license, uint32_t limit) { return my->list_licenses(platform, lower_bound_license, limit); } vector<advertising_object> wallet_api::list_advertisings(string platform, string lower_bound_advertising, uint32_t limit) { return my->list_advertisings(platform, lower_bound_advertising, limit); } vector<active_post_object> wallet_api::get_post_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, string poster, string post_pid) { return my->get_post_profits_detail(begin_period, end_period, platform, poster, post_pid); } vector<Platform_Period_Profit_Detail> wallet_api::get_platform_profits_detail(uint32_t begin_period, uint32_t end_period, string platform, uint32_t lower_bound_index, uint32_t limit) { return my->get_platform_profits_detail(begin_period, end_period, platform, lower_bound_index, limit); } vector<Poster_Period_Profit_Detail> wallet_api::get_poster_profits_detail(uint32_t begin_period, uint32_t end_period, string poster, uint32_t lower_bound_index, uint32_t limit) { return my->get_poster_profits_detail(begin_period, end_period, poster, lower_bound_index, limit); } share_type wallet_api::get_score_profit(string account, uint32_t period) { return my->get_score_profit(account, period); } account_statistics_object wallet_api::get_account_statistics(string account) { return my->get_account_statistics(account); } signed_transaction wallet_api::create_advertising(string platform, string description, string unit_price, uint32_t unit_time, bool csaf_fee, bool broadcast) { return my->create_advertising(platform, description, unit_price, unit_time, csaf_fee, broadcast); } signed_transaction wallet_api::update_advertising(string platform, advertising_aid_type advertising_aid, optional<string> description, optional<string> unit_price, optional<uint32_t> unit_time, optional<bool> on_sell, bool csaf_fee, bool broadcast) { return my->update_advertising(platform, advertising_aid, description, unit_price, unit_time, on_sell, csaf_fee, broadcast); } signed_transaction wallet_api::ransom_advertising(string platform, string from_account, advertising_aid_type advertising_aid, advertising_order_oid_type advertising_order_oid, bool csaf_fee, bool broadcast) { return my->ransom_advertising(platform, from_account, advertising_aid, advertising_order_oid, csaf_fee, broadcast); } vector<advertising_order_object> wallet_api::list_advertising_orders_by_purchaser(string purchaser, object_id_type lower_bound_advertising_order, uint32_t limit) { account_uid_type account = my->get_account_uid(purchaser); return my->_remote_db->list_advertising_orders_by_purchaser(account, lower_bound_advertising_order, limit); } vector<advertising_order_object> wallet_api::list_advertising_orders_by_ads_aid(string platform, string advertising_aid, string lower_bound_advertising_order, uint32_t limit) { account_uid_type platform_uid = my->get_account_uid(platform); advertising_aid_type ad_aid = fc::to_uint64(fc::string(advertising_aid)); advertising_order_oid_type lower_order_oid = fc::to_uint64(fc::string(lower_bound_advertising_order)); return my->_remote_db->list_advertising_orders_by_ads_aid(platform_uid, ad_aid, lower_order_oid, limit); } signed_transaction wallet_api::create_custom_vote(string create_account, string title, string description, uint32_t expired_time, asset_aid_type asset_id, share_type required_amount, uint8_t minimum_selected_items, uint8_t maximum_selected_items, vector<string> options, bool csaf_fee, bool broadcast) { time_point_sec time = time_point_sec(expired_time); return my->create_custom_vote(create_account, title, description, time, asset_id, required_amount, minimum_selected_items, maximum_selected_items, options, csaf_fee, broadcast); } signed_transaction wallet_api::cast_custom_vote(string voter, string custom_vote_creater, custom_vote_vid_type custom_vote_vid, set<uint8_t> vote_result, bool csaf_fee, bool broadcast) { return my->cast_custom_vote(voter, custom_vote_creater, custom_vote_vid, vote_result, csaf_fee, broadcast); } vector<custom_vote_object> wallet_api::list_custom_votes(const account_uid_type lowerbound, uint32_t limit) { return my->_remote_db->list_custom_votes(lowerbound, limit); } vector<custom_vote_object> wallet_api::lookup_custom_votes(string creater, custom_vote_vid_type lower_bound_custom_vote, uint32_t limit) { account_uid_type account = my->get_account_uid(creater); return my->_remote_db->lookup_custom_votes(account, lower_bound_custom_vote, limit); } vector<cast_custom_vote_object> wallet_api::list_cast_custom_votes_by_id(const string creater, const custom_vote_vid_type vote_vid, const object_id_type lower_bound_cast_custom_vote, uint32_t limit) { account_uid_type creater_account = my->get_account_uid(creater); return my->_remote_db->list_cast_custom_votes_by_id(creater_account, vote_vid, lower_bound_cast_custom_vote, limit); } vector<cast_custom_vote_object> wallet_api::list_cast_custom_votes_by_voter(string voter, object_id_type lower_bound_cast_custom_vote, uint32_t limit) { account_uid_type account = my->get_account_uid(voter); return my->_remote_db->list_cast_custom_votes_by_voter(account, lower_bound_cast_custom_vote, limit); } uint64_t wallet_api::get_account_auth_platform_count(string platform) { return my->get_account_auth_platform_count(platform); } vector<account_auth_platform_object> wallet_api::list_account_auth_platform_by_platform(string platform, account_uid_type lower_bound_account, uint32_t limit) { return my->list_account_auth_platform_by_platform(platform, lower_bound_account, limit); } vector<account_auth_platform_object> wallet_api::list_account_auth_platform_by_account(string account, account_uid_type lower_bound_platform, uint32_t limit) { return my->list_account_auth_platform_by_account(account, lower_bound_platform, limit); } signed_transaction wallet_api::approve_proposal( const string& fee_paying_account, const string& proposal_id, const approval_delta& delta, bool csaf_fee, bool broadcast /* = false */ ) { return my->approve_proposal( fee_paying_account, proposal_id, delta, csaf_fee, broadcast ); } vector<proposal_object> wallet_api::list_proposals( string account_name_or_id ) { auto acc = my->get_account( account_name_or_id ); //return my->_remote_db->get_proposed_transactions( acc.uid ); return {}; } global_property_object wallet_api::get_global_properties() const { return my->get_global_properties(); } content_parameter_extension_type wallet_api::get_global_properties_extensions() const { return my->get_global_properties_extensions(); } dynamic_global_property_object wallet_api::get_dynamic_global_properties() const { return my->get_dynamic_global_properties(); } string wallet_api::help()const { std::vector<std::string> method_names = my->method_documentation.get_method_names(); std::stringstream ss; for (const std::string method_name : method_names) { try { ss << my->method_documentation.get_brief_description(method_name); } catch (const fc::key_not_found_exception&) { ss << method_name << " (no help available)\n"; } } return ss.str(); } string wallet_api::gethelp(const string& method)const { fc::api<wallet_api> tmp; std::stringstream ss; ss << "\n"; // doxygen help string first try { string brief_desc = my->method_documentation.get_brief_description(method); boost::trim( brief_desc ); ss << brief_desc << "\n\n"; std::string doxygenHelpString = my->method_documentation.get_detailed_description(method); if (!doxygenHelpString.empty()) ss << doxygenHelpString << "\n"; else ss << "No doxygen help defined for method " << method << "\n\n"; } catch (const fc::key_not_found_exception&) { ss << "No doxygen help defined for method " << method << "\n\n"; } if( method == "import_key" ) { ss << "usage: import_key ACCOUNT_NAME_OR_ID WIF_PRIVATE_KEY\n\n"; ss << "example: import_key \"1.3.11\" 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3\n"; ss << "example: import_key \"usera\" 5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3\n"; } else if( method == "transfer" ) { ss << "usage: transfer FROM TO AMOUNT SYMBOL \"memo\" BROADCAST\n\n"; ss << "example: transfer \"1.3.11\" \"1.3.4\" 1000.03 CORE \"memo\" true\n"; ss << "example: transfer \"usera\" \"userb\" 1000.123 CORE \"memo\" true\n"; } else if( method == "create_account_with_brain_key" ) { ss << "usage: create_account_with_brain_key BRAIN_KEY ACCOUNT_NAME REGISTRAR REFERRER BROADCAST\n\n"; ss << "example: create_account_with_brain_key \"my really long brain key\" \"newaccount\" \"1.3.11\" \"1.3.11\" true\n"; ss << "example: create_account_with_brain_key \"my really long brain key\" \"newaccount\" \"someaccount\" \"otheraccount\" true\n"; ss << "\n"; ss << "This method should be used if you would like the wallet to generate new keys derived from the brain key.\n"; ss << "The BRAIN_KEY will be used as the owner key, and the active key will be derived from the BRAIN_KEY. Use\n"; ss << "register_account if you already know the keys you know the public keys that you would like to register.\n"; } else if( method == "register_account" ) { ss << "usage: register_account ACCOUNT_NAME OWNER_PUBLIC_KEY ACTIVE_PUBLIC_KEY REGISTRAR REFERRER REFERRER_PERCENT BROADCAST\n\n"; ss << "example: register_account \"newaccount\" \"CORE6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV\" \"CORE6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV\" \"1.3.11\" \"1.3.11\" 50 true\n"; ss << "\n"; ss << "Use this method to register an account for which you do not know the private keys."; } else if( method == "create_asset" ) { ss << "usage: ISSUER SYMBOL PRECISION_DIGITS OPTIONS INITIAL_SUPPLY BROADCAST\n\n"; ss << "PRECISION_DIGITS: the number of digits after the decimal point\n\n"; ss << "Example value of OPTIONS: \n"; ss << fc::json::to_pretty_string( graphene::chain::asset_options() ); } else if( method == "committee_proposal_create" ) { ss << "usage: COMMITTEE_MEMBER_UID PROPOSED_ITEMS BLOCK_NUM PROPOSER_OPINION BLOCK_NUM BLOCK_NUM BROADCAST\n\n"; ss << "Example value of PROPOSED_ITEMS: \n"; ss << "item[0].new_priviledges:\n\n"; graphene::chain::committee_update_account_priviledge_item_type::account_priviledge_update_options apuo; apuo.can_vote = true; apuo.is_admin = true; apuo.is_registrar = true; apuo.takeover_registrar = 25638; ss << fc::json::to_pretty_string( apuo ); ss << "\n\nitem[1].parameters:\n\n"; ss << fc::json::to_pretty_string( fee_schedule::get_default().parameters ); ss << "\n\nitem[2]:\n\n"; ss << "see graphene::chain::committee_updatable_parameters or Calling \"get_global_properties\" to see"; ss << "\n\n"; ss << "[[0,{\"account\":28182,\"new_priviledges\": {\"can_vote\":true}}],[1,{\"parameters\": "; ss << "[[16,{\"fee\":10000,\"min_real_fee\":0,\"min_rf_percent\":0}]]}],[2,{\"governance_voting_expiration_blocks\":150000}]]"; ss << "\n\n"; } return ss.str(); } bool wallet_api::load_wallet_file( string wallet_filename ) { return my->load_wallet_file( wallet_filename ); } void wallet_api::save_wallet_file( string wallet_filename ) { my->save_wallet_file( wallet_filename ); } std::map<string,std::function<string(fc::variant,const fc::variants&)> > wallet_api::get_result_formatters() const { return my->get_result_formatters(); } bool wallet_api::is_locked()const { return my->is_locked(); } bool wallet_api::is_new()const { return my->_wallet.cipher_keys.size() == 0; } void wallet_api::encrypt_keys() { my->encrypt_keys(); } void wallet_api::lock() { try { if ( is_locked() ) return; encrypt_keys(); for( auto key : my->_keys ) key.second = key_to_wif(fc::ecc::private_key()); my->_keys.clear(); my->_checksum = fc::sha512(); my->self.lock_changed(true); } FC_CAPTURE_AND_RETHROW() } void wallet_api::unlock(string password) { try { FC_ASSERT( !is_new(), "Please use the set_password method to initialize a new wallet before continuing" ); FC_ASSERT( is_locked(), "The wallet is already unlocked" ); FC_ASSERT(password.size() > 0); auto pw = fc::sha512::hash(password.c_str(), password.size()); vector<char> decrypted = fc::aes_decrypt(pw, my->_wallet.cipher_keys); auto pk = fc::raw::unpack<plain_keys>(decrypted); FC_ASSERT(pk.checksum == pw); my->_keys = std::move(pk.keys); my->_checksum = pk.checksum; my->self.lock_changed(false); } FC_CAPTURE_AND_RETHROW() } void wallet_api::set_password( string password ) { if( !is_new() ) FC_ASSERT( !is_locked(), "The wallet must be unlocked before the password can be set" ); my->_checksum = fc::sha512::hash( password.c_str(), password.size() ); lock(); } map<public_key_type, string> wallet_api::dump_private_keys() { FC_ASSERT( !is_locked(), "Should unlock first" ); return my->_keys; } string wallet_api::get_key_label( public_key_type key )const { auto key_itr = my->_wallet.labeled_keys.get<by_key>().find(key); if( key_itr != my->_wallet.labeled_keys.get<by_key>().end() ) return key_itr->label; return string(); } string wallet_api::get_private_key( public_key_type pubkey )const { return key_to_wif( my->get_private_key( pubkey ) ); } public_key_type wallet_api::get_public_key( string label )const { try { return fc::variant(label).as<public_key_type>( 1 ); } catch ( ... ){} auto key_itr = my->_wallet.labeled_keys.get<by_label>().find(label); if( key_itr != my->_wallet.labeled_keys.get<by_label>().end() ) return key_itr->key; return public_key_type(); } bool wallet_api::set_key_label( public_key_type key, string label ) { auto result = my->_wallet.labeled_keys.insert( key_label{label,key} ); if( result.second ) return true; auto key_itr = my->_wallet.labeled_keys.get<by_key>().find(key); auto label_itr = my->_wallet.labeled_keys.get<by_label>().find(label); if( label_itr == my->_wallet.labeled_keys.get<by_label>().end() ) { if( key_itr != my->_wallet.labeled_keys.get<by_key>().end() ) return my->_wallet.labeled_keys.get<by_key>().modify( key_itr, [&]( key_label& obj ){ obj.label = label; } ); } return false; } } } // graphene::wallet namespace fc { void /*fc::*/to_variant(const account_multi_index_type& accts, fc::variant& vo, uint32_t max_depth) { to_variant( std::vector<account_object>(accts.begin(), accts.end()), vo, max_depth ); } void /*fc::*/from_variant(const fc::variant& var, account_multi_index_type& vo, uint32_t max_depth) { const std::vector<account_object>& v = var.as<std::vector<account_object>>( max_depth ); vo = account_multi_index_type(v.begin(), v.end()); } }
43.577881
299
0.600835
LianshuOne
35a7a08561f25f446421101cf82034e46321f4f9
503
cpp
C++
src/lpp_client.cpp
logpicker/prototype
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
[ "MIT" ]
null
null
null
src/lpp_client.cpp
logpicker/prototype
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
[ "MIT" ]
null
null
null
src/lpp_client.cpp
logpicker/prototype
0a25fccc24a8e298dee9bae240fcd73a4e5d185e
[ "MIT" ]
null
null
null
#include "logpicker_t.hpp" #include "types.hpp" #include "logpicker_t.hpp" #include "log.hpp" #include "cert.hpp" #include "utils.hpp" int main() { cert_t cert = read_cert_from_disk("/home/leen/Projects/TU_BS/misc/LogPicker/lpp/data/github/DER/github.com"); hash_t hash = hash_certificate(cert); std::cout << "Hash: " << hash << "\n"; std::vector<Log> logs = make_logs(1); log_pool_t pool; for(const auto& log : logs) { //pool.emplace_back(make_instance(log)); } }
26.473684
113
0.658052
logpicker
35a8f8a2e57d67bf9ee9fd02b644b79bf7480f8d
2,006
cpp
C++
src/AutoVersionTest.cpp
adamyg/libappupdater
a9dd531499cc87046347d9710574b459e5d541f3
[ "MIT" ]
1
2021-12-22T07:52:39.000Z
2021-12-22T07:52:39.000Z
src/AutoVersionTest.cpp
adamyg/libappupdater
a9dd531499cc87046347d9710574b459e5d541f3
[ "MIT" ]
null
null
null
src/AutoVersionTest.cpp
adamyg/libappupdater
a9dd531499cc87046347d9710574b459e5d541f3
[ "MIT" ]
null
null
null
// // // #include <gtest/gtest.h> #include "AutoVersion.h" TEST(AutoVersionTest, ParsesUpstreamOnly) { AutoVersion v("1"); EXPECT_EQ(0, v.Epoch()); EXPECT_STREQ("1", v.Upstream()); EXPECT_STREQ("0", v.Revision()); } TEST(AutoVersionTest, ParsesEpochs) { AutoVersion v("1:2.0.1"); EXPECT_EQ(1, v.Epoch()); EXPECT_STREQ("2.0.1", v.Upstream()); EXPECT_STREQ("0", v.Revision()); } TEST(AutoVersionTest, ParsesRevisions) { AutoVersion v("10:4.0.1~alpha-4-5"); EXPECT_EQ(10, v.Epoch()); EXPECT_STREQ("4.0.1~alpha-4", v.Upstream()); EXPECT_STREQ("5", v.Revision()); } TEST(AutoVersionTest, ComparesNumbers) { EXPECT_LT(AutoVersion("1"), AutoVersion("2")); EXPECT_EQ(AutoVersion("10"), AutoVersion("10")); EXPECT_LT(AutoVersion("9"), AutoVersion("10")); EXPECT_GT(AutoVersion("10"), AutoVersion("9")); } TEST(AutoVersionTest, ComparesEpochs) { EXPECT_GT(AutoVersion("2:1"), AutoVersion("1:2")); EXPECT_LT(AutoVersion("10"), AutoVersion("1:2")); } TEST(AutoVersionTest, ComparesAlphas) { EXPECT_LT(AutoVersion("alpha"), AutoVersion("beta")); EXPECT_LT(AutoVersion("alpha1"), AutoVersion("alpha2")); EXPECT_GT(AutoVersion("alpha10"), AutoVersion("alpha2")); } TEST(AutoVersionTest, ComparesTildes) { EXPECT_LT(AutoVersion("3.0~beta1"), AutoVersion("3.0")); EXPECT_GT(AutoVersion("3.0~beta"), AutoVersion("3.0~~prebeta")); EXPECT_LT(AutoVersion("3.0~beta4"), AutoVersion("3.0~rc1")); } TEST(AutoVersionTest, ComparesRevisions) { EXPECT_LT(AutoVersion("3.0-2"), AutoVersion("3.0-10")); } assert mycmp('1', '2') == -1 assert mycmp('2', '1') == 1 assert mycmp('1', '1') == 0 assert mycmp('1.0', '1') == 0 assert mycmp('1', '1.000') == 0 assert mycmp('12.01', '12.1') == 0 assert mycmp('13.0.1', '13.00.02') == -1 assert mycmp('1.1.1.1', '1.1.1.1') == 0 assert mycmp('1.1.1.2', '1.1.1.1') == 1 assert mycmp('1.1.3', '1.1.3.000') == 0 assert mycmp('3.1.1.0', '3.1.2.10') == -1 assert mycmp('1.1', '1.10') == -1
25.717949
68
0.631107
adamyg
35b4271fe40b17a31882ef7de3665b6288a65975
782
hpp
C++
src/main/include/Configuration.hpp
Apophis5006/Subsystem-Library
7537637a166a8f161b95d0cae3152f02c87d61de
[ "MIT" ]
1
2022-02-15T01:03:05.000Z
2022-02-15T01:03:05.000Z
src/main/include/Configuration.hpp
Apophis5006/Subsystem-Library
7537637a166a8f161b95d0cae3152f02c87d61de
[ "MIT" ]
null
null
null
src/main/include/Configuration.hpp
Apophis5006/Subsystem-Library
7537637a166a8f161b95d0cae3152f02c87d61de
[ "MIT" ]
null
null
null
//-------------------Joysticks---------------- #define DRIVE_STICK 0 #define STEER_STICK 1 //-------------------Drivetrain--------------- #define SWERVE_DISTANCE_FRONT 10 //distance between swerve drives from front to back (inches) #define SWERVE_DISTANCE_SIDE 10 //distance between swerve drives from side to side (inches) //Swerve CAN bus defines for steering motors #define FLS 4 #define FRS 1 #define BLS 2 #define BRS 3 //Swerve CAN bus defines for drive motors #define FLD 15 #define FRD 12 #define BLD 13 #define BRD 14 //Swerve Can bus defines for non drivetrain motors #define SHOOTER 11 #define Intake 8 #define Magazine 7 #define Trigger 5 #define Hood 6 //value multiplyers #define VELOCITY_MULTIPLIER 30 //add actual speed later #define pi 3.14 //aproximate fore pi
26.965517
93
0.713555
Apophis5006
35b549edc2bb88298d2a8d909de8118dade9ba15
3,156
hpp
C++
src/rolmodl/hpp/Tex.hpp
maximsmol/rolmodl
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
[ "MIT" ]
1
2022-02-19T21:34:42.000Z
2022-02-19T21:34:42.000Z
src/rolmodl/hpp/Tex.hpp
maximsmol/rolmodl
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
[ "MIT" ]
null
null
null
src/rolmodl/hpp/Tex.hpp
maximsmol/rolmodl
fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f
[ "MIT" ]
1
2021-12-07T09:33:42.000Z
2021-12-07T09:33:42.000Z
#pragma once #include "forwarddecl/Tex.hpp" #include "forwarddecl/Ren.hpp" #include "Base.hpp" #include "PixelFmt.hpp" #include "Geom.hpp" namespace rolmodl { enum class TextureType { Static, Lock, Ren }; namespace textureType::unsafe { constexpr TextureType fromSDLEnum(const int a) noexcept { if (a == SDL_TEXTUREACCESS_STATIC) return TextureType::Static; if (a == SDL_TEXTUREACCESS_STREAMING) return TextureType::Lock; // if (a == SDL_TEXTUREACCESS_TARGET) return TextureType::Ren; } constexpr int toSDLEnum(const TextureType a) noexcept { if (a == TextureType::Static) return SDL_TEXTUREACCESS_STATIC; if (a == TextureType::Lock) return SDL_TEXTUREACCESS_STREAMING; // if (a == TextureType::Ren) return SDL_TEXTUREACCESS_TARGET; } } struct TextureInfo { public: pixelfmt::Id fmt; TextureType type; geom::Size size; }; class Tex { public: ~Tex() noexcept; Tex(const Tex& that) = delete; Tex(Tex&& that) noexcept; Tex& operator=(const Tex& that) = delete; Tex& operator=(Tex&& that) noexcept; friend void swap(Tex& a, Tex& b) noexcept; BlendMode getBlendMode(); void setBlendMode(const BlendMode m); uint8_t getAlphaMod(); void setAlphaMod(const uint8_t i); RGB getRGBMod(); void setRGBMod(const RGB i); TextureInfo query(); SDL_Texture* unsafeRaw() noexcept; const SDL_Texture* unsafeRaw() const noexcept; protected: Tex() noexcept; Tex(Ren& r, const pixelfmt::Id fmt, const int access, const geom::Size s); SDL_Texture* h_; }; class StaticTex : public Tex { public: StaticTex(Ren& r, const pixelfmt::Id fmt, const geom::Size s); }; class LockTex : public Tex { public: LockTex(Ren& r, const pixelfmt::Id fmt, const geom::Size s); pixelfmt::Id format() const noexcept; private: LockTex() noexcept; pixelfmt::Id format_; }; class RenTex : public Tex { public: RenTex(Ren& r, const pixelfmt::Id fmt, const geom::Size s); }; class TexLock { public: explicit TexLock(LockTex& tex); TexLock(LockTex& tex, const geom::RectWH r); TexLock(LockTex& tex, const geom::RectXY r); ~TexLock() noexcept; TexLock(const TexLock& that) = delete; TexLock(TexLock&& that) noexcept; TexLock& operator=(const TexLock& that) = delete; TexLock& operator=(TexLock&& that) noexcept; friend void swap(TexLock& a, TexLock& b) noexcept; TexLock& drawPoint(const RGBA c, const geom::Pos p) noexcept; RGBA getPoint(const geom::Pos p) const noexcept; uint32_t& unsafePoint(const geom::Pos p) noexcept; const uint32_t& unsafePoint(const geom::Pos p) const noexcept; void* unsafeRaw() noexcept; const void* unsafeRaw() const noexcept; private: TexLock() noexcept; TexLock(LockTex& tex, const SDL_Rect* r); TexLock(LockTex& tex, const SDL_Rect r); LockTex* t_; void* h_; unsigned int pitch_; }; }
24.276923
80
0.631179
maximsmol
35b8397827a7b1f9700a9f9b2bba950c91fa569c
906
cpp
C++
10282.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
10282.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
10282.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; int x,y,len; map<string,string> idx; char msk[50]; string a,b; int main() { while(gets(msk)) { len=strlen(msk); if(!len) break; for(x=0;x<len;x++) if(msk[x]==' ') break; a.clear(),b.clear(); for(y=0;y<x;y++) a+=msk[y]; for(y=x+1;y<len;y++) b+=msk[y]; idx[b]=a; } while(scanf("%s",msk)!=EOF) if(idx.find(msk)==idx.end()) printf("eh\n"); else printf("%s\n",idx[msk].c_str()); return 0; }
18.12
85
0.610375
felikjunvianto
35bfa942cddd463f93d90460ef7b939aae562857
1,972
cpp
C++
soruce/main.cpp
juyuanmao/pick-ghost
c0e9713d63c1428a93e64dd33497cb97a37758c1
[ "Unlicense" ]
null
null
null
soruce/main.cpp
juyuanmao/pick-ghost
c0e9713d63c1428a93e64dd33497cb97a37758c1
[ "Unlicense" ]
null
null
null
soruce/main.cpp
juyuanmao/pick-ghost
c0e9713d63c1428a93e64dd33497cb97a37758c1
[ "Unlicense" ]
null
null
null
// // main.cpp // pick-ghost // // Created by Ju Yuanmao on 2017/7/15. // Copyleft // #include <iostream> #include <fstream> #include <algorithm> #include "randi.hpp" #include "cards.hpp" #include "player.hpp" using std::cin; using std::cout; using std::endl; int main(int argc, const char * argv[]) { std::ofstream out; switch (argc) { case 2: out.open(argv[1]); case 1: break; default: cout << "usage: ./pick-ghost.out [output_film]\n"; exit(1); break; } cards c; int t; unsigned long long n; cout << "How many people will join the game?\n"; cin >> t; cout << "How many times will the game be played?\n"; cin >> n; while (n--) { c.reset(); player *now = new player('a'); for (char i='b'; i<'a'+t; i++) { now->insert(i); now = now->next(); } now = now->next(); while (!c.empty()) { now->push(c.pop()); now = now->next(); } for (int i=0; i<t; i++) { if (now->last()->empty()) { now->last()->erase(); } now = now->next(); } int m = randi(0, t); while (m--) { now = now -> next(); } while (now->next() != now && now->last() != now) { now->push(now->next()->pop()); if (now->next()->empty()) { now->next()->erase(); } if (now->empty()) { now = now->next(); now->last()->erase(); continue; } now = now->next(); } if (out.is_open()) { out << now->name() << endl; } else { cout << now->name() << endl; } delete now; } if (out.is_open()) { out.close(); } return 0; }
21.911111
62
0.399594
juyuanmao
35c17388680166e4bd3c03c481724aa2ec6cba04
6,640
cpp
C++
src/unused/SceneData.cpp
rampart5555/ark
1399679feac89a84d3597e377992e90756e27dd0
[ "Apache-2.0" ]
null
null
null
src/unused/SceneData.cpp
rampart5555/ark
1399679feac89a84d3597e377992e90756e27dd0
[ "Apache-2.0" ]
null
null
null
src/unused/SceneData.cpp
rampart5555/ark
1399679feac89a84d3597e377992e90756e27dd0
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osg/io_utils> #include <osg/UserDataContainer> #include <osg/ValueObject> #include "SceneData.h" #include "AssetsManager.h" #include "Logging.h" static void build_scene_data(const char *osgt_file) { char buf[20]; osg::Group *root = new osg::Group(); for(int i=0;i<EPISODE_NR;i++) { std::string ep_name="Episode_"; osg::Group *episode = new osg::Group(); episode->setUserValue("ep_id",i); sprintf(buf,"%d",i+1); ep_name += buf; episode->setUserValue("ep_name",ep_name); episode->setUserValue("ep_unlocked",false); for(int j=0;j<SCENE_NR;j++) { osg::Group *level = new osg::Group(); level->setUserValue("lvl_id", j); if((i==0)&&(j==0)) level->setUserValue("lvl_unlocked", true ); else level->setUserValue("lvl_unlocked", false ); level->setUserValue("lvl_score", 0); std::string lvl_data = "levels/Level_"; sprintf(buf,"%02d",j+1); lvl_data += buf; lvl_data +=".lua"; level->setUserValue("lvl_data",lvl_data); episode->addChild(level); } root->addChild(episode); } AssetsManager::instance().writeNode(*root, "levels.osgt"); } static void dump_episode_info(EpisodeInfo ei) { printf("Episode\n"); printf("ei_id: %d\n",ei.ep_id); printf("ei_name: %s\n",ei.ep_name.c_str()); printf("ei_unlocked: %d\n",ei.ep_unlocked); } static void dump_level_info(LevelInfo li) { printf(" Level\n"); printf(" lvl_id: %d\n",li.lvl_id); printf(" lvl_unlocked: %d\n",li.lvl_unlocked); printf(" lvl_score: %d\n",li.lvl_score); printf(" lvl_data: %s\n",li.lvl_data.c_str()); } SceneLoader::SceneLoader() { m_osgtFile=AssetsManager::instance().getRootPath() + "models/levels.osgt"; m_epNr = 3; m_lvlNr = 15; //levels per episode if(m_rootGroup==NULL) { readSceneData(); } m_currentEp = -1; m_currentLvl = -1; //build_scene_data(m_osgtFile.c_str()); } SceneLoader::~SceneLoader() { } void SceneLoader::writeSceneData() { AssetsManager::instance().writeNode(*m_rootGroup, m_osgtFile.c_str()); } void SceneLoader::readSceneData() { LOG_INFO("SceneLoader::readSceneData=> %s\n",m_osgtFile.c_str()); osg::Object *obj = AssetsManager::instance().loadObject(m_osgtFile.c_str(),"osgt"); m_rootGroup = dynamic_cast<osg::Group*>(obj); } void SceneLoader::dumpSceneData() { unsigned int i,j; LevelInfo li; EpisodeInfo ei; bool ep_res,lvl_res; if(m_rootGroup!=NULL) { for(i=0;i<m_rootGroup->getNumChildren();i++) { osg::Group *ep_group = dynamic_cast<osg::Group*>(m_rootGroup->getChild(i)); ep_res = ep_group->getUserValue("ep_id",ei.ep_id); if(ep_res==true) { ep_group->getUserValue("ep_name", ei.ep_name); ep_group->getUserValue("ep_unlocked", ei.ep_unlocked); dump_episode_info(ei); } for(j=0;j<ep_group->getNumChildren();j++) { osg::Node *lvl_group = dynamic_cast<osg::Group*>(ep_group->getChild(j)); lvl_res = lvl_group->getUserValue("lvl_id",li.lvl_id); if(lvl_res==true) { lvl_group->getUserValue("lvl_unlocked",li.lvl_unlocked); lvl_group->getUserValue("lvl_score",li.lvl_score); lvl_group->getUserValue("lvl_data",li.lvl_data); dump_level_info(li); } } } } } bool SceneLoader::getLevelInfo(int ep_id, int lvl_id, LevelInfo& lvl_info) { if(m_rootGroup != NULL) { osg::Group *ep_group = NULL; osg::Group *lvl_group = NULL; ep_group = dynamic_cast<osg::Group*>(m_rootGroup->getChild(ep_id)); if(ep_group != NULL) lvl_group = dynamic_cast<osg::Group*>(ep_group->getChild(lvl_id)); if( (ep_group == NULL)||(lvl_group == NULL) ) { LOG_ERROR("Level info not found for ep_id:%d lvl_id:%d\n", ep_id, lvl_id); return false; } lvl_group->getUserValue("lvl_id", lvl_info.lvl_id); lvl_group->getUserValue("lvl_unlocked",lvl_info.lvl_unlocked); lvl_group->getUserValue("lvl_score",lvl_info.lvl_score); lvl_group->getUserValue("lvl_data",lvl_info.lvl_data); //set episode id for this level lvl_info.lvl_ep_id = ep_id; //printf("level info: ep_id: %d,lvl_id:%d\n",ep_id,lvl_id); dump_level_info(lvl_info); return true; } return false; } bool SceneLoader::getEpisodeInfo(int ep_id, EpisodeInfo& ep_info) { if(m_rootGroup != NULL) { osg::Group *ep_group = dynamic_cast<osg::Group*>(m_rootGroup->getChild(ep_id)); if(ep_group==NULL) { LOG_ERROR("Episode info not found for ep_id:%d \n", ep_id); return false; } ep_group->getUserValue("ep_id",ep_info.ep_id); ep_group->getUserValue("ep_name", ep_info.ep_name); ep_group->getUserValue("ep_unlocked", ep_info.ep_unlocked); return true; } return false; } void SceneLoader::getCurrentScene(int& ep_id, int& lvl_id) { ep_id = m_currentEp; lvl_id = m_currentLvl; } void SceneLoader::setCurrentScene(int ep_id, int lvl_id) { LOG_INFO("Set current scene episode: %d level: %d\n",ep_id,lvl_id); m_currentEp = ep_id ; m_currentLvl = lvl_id; } bool SceneLoader::unlockNextLevel() { LOG_INFO("Unlock next level, current scene episode: %d level: %d\n",m_currentEp,m_currentLvl); if(m_currentLvl < m_lvlNr) { osg::Group *ep_group = NULL; osg::Group *lvl_group = NULL; m_currentLvl++; ep_group = dynamic_cast<osg::Group*>(m_rootGroup->getChild(m_currentEp)); if(ep_group != NULL) lvl_group = dynamic_cast<osg::Group*>(ep_group->getChild(m_currentLvl)); if( (ep_group == NULL)||(lvl_group == NULL) ) { LOG_ERROR("Level info not found for ep_id:%d lvl_id:%d\n", m_currentEp, m_currentLvl); return false; } lvl_group->setUserValue("lvl_unlocked", true ); } return true; }
31.923077
106
0.578313
rampart5555
35db1fde2e1f3b753bde44f9c864d80b8bd50157
28,340
cpp
C++
src/CamMonitor/CamMonitor/LiveTab.cpp
infinicam/infinicam-samples
47c9c0dd79e1991d17fbcff91f49ab15a69c519a
[ "MIT" ]
null
null
null
src/CamMonitor/CamMonitor/LiveTab.cpp
infinicam/infinicam-samples
47c9c0dd79e1991d17fbcff91f49ab15a69c519a
[ "MIT" ]
null
null
null
src/CamMonitor/CamMonitor/LiveTab.cpp
infinicam/infinicam-samples
47c9c0dd79e1991d17fbcff91f49ab15a69c519a
[ "MIT" ]
1
2020-12-23T04:38:56.000Z
2020-12-23T04:38:56.000Z
#include "stdafx.h" #include "LiveTab.h" #include "resource.h" #include "AppDefine.h" #include "CamMonitor.h" #include "cih.h" #include "ChildView.h" #include "SelectCameraDialog.h" #include "SaveLiveDialog.h" #include "Util.h" IMPLEMENT_DYNAMIC(CLiveTab, CBaseTab) CLiveTab::CLiveTab(CWnd* pParent) : CBaseTab(CLiveTab::IDD, _T("LIVE"), pParent) , m_lockTextInfo(sizeof(TEXTINFO)) , m_lockRec(sizeof(BOOL)) , m_nRecFrameCount(0) , m_xvAcqMode(ACQUISITION_MODE_SINGLE) , m_xvSyncIn(PUC_SYNC_INTERNAL) , m_xvSyncOutSignal(PUC_SIGNAL_POSI) , m_xvSyncOutDelay(0) , m_xvSyncOutWidth(0) , m_xvLEDMode(FALSE) , m_xvFanState(FALSE) , m_xvExposeOn(0) , m_xvExposeOff(0) , m_csvFile(nullptr) { } CLiveTab::~CLiveTab() { } void CLiveTab::DoDataExchange(CDataExchange* pDX) { CBaseTab::DoDataExchange(pDX); DDX_Radio(pDX, IDC_ACQUISITION_SINGLE, m_xvAcqMode); DDX_Control(pDX, IDC_REC, m_buttonRec); DDX_Control(pDX, IDC_FRAMERATE, m_comboFramerate); DDX_Control(pDX, IDC_SHUTTERFPS, m_comboShutterFps); DDX_Control(pDX, IDC_RESOLUTION, m_comboReso); DDX_Radio(pDX, IDC_SYNC_IN_INTERNAL, m_xvSyncIn); DDX_Radio(pDX, IDC_SYNC_OUT_SIGNAL_POSI, m_xvSyncOutSignal); DDX_Text(pDX, IDC_SYNC_OUT_DELAY, m_xvSyncOutDelay); DDX_Text(pDX, IDC_SYNC_OUT_WIDTH, m_xvSyncOutWidth); DDX_Control(pDX, IDC_SYNC_OUT_MAGNIFICATION, m_comboSyncOutMag); DDX_Check(pDX, IDC_LED_MODE, m_xvLEDMode); DDX_Check(pDX, IDC_FAN_CTRL, m_xvFanState); DDX_Control(pDX, IDC_QUANTIZATION, m_comboQuantization); DDX_Text(pDX, IDC_EXPOSE_ON, m_xvExposeOn); DDX_Text(pDX, IDC_EXPOSE_OFF, m_xvExposeOff); DDX_Text(pDX, IDC_DECODE_POS_X, m_xvDecodePos.x); DDX_Text(pDX, IDC_DECODE_POS_Y, m_xvDecodePos.y); DDX_Text(pDX, IDC_DECODE_POS_W, m_xvDecodeSize.cx); DDX_Text(pDX, IDC_DECODE_POS_H, m_xvDecodeSize.cy); } BOOL CLiveTab::OpenCamera(UINT32 nDeviceNo, UINT32 nSingleXferTimeOut, UINT32 nContinuousXferTimeOut, UINT32 nRingBufCount) { CString msg; PUCRESULT result; result = m_camera.OpenDevice(nDeviceNo, nSingleXferTimeOut, nContinuousXferTimeOut, nRingBufCount); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("OpenDevice"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); return FALSE; } m_camera.SetCallbackSingle(_SingleProc, this); m_camera.SetCallbackContinuous(_ContinuousProc, this); return TRUE; } void CLiveTab::CloseCamera() { StopRec(); StopLive(); m_camera.CloseDevice(); } void CLiveTab::StartLive() { CString msg; PUCRESULT result; result = m_camera.StartLive(); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("StartLive"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } SetTimer(TIMER_ID_UPDATE_TEMP, UPDATE_TEMP_INTERVAL, NULL); } void CLiveTab::StopLive() { CString msg; PUCRESULT result; result = m_camera.StopLive(); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("StopLive"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } KillTimer(TIMER_ID_UPDATE_TEMP); } void CLiveTab::StartRec() { UpdateData(); // ***Lock*** BOOL* pRec = (BOOL*)m_lockRec.GetLockData(); *pRec = TRUE; m_nRecFrameCount = 0; CDefaultParams& df = ((CCamMonitorApp*)AfxGetApp())->GetDefaultParams(); if (df.cameraSaveFileType == SAVE_FILE_TYPE_RAW) { CString filepath; filepath.Format(_T("%s\\%s.mdat"), (LPCTSTR)df.cameraSaveFolderPath, (LPCTSTR)df.cameraSaveFileName); FILE* fp = NULL; errno_t error = _tfopen_s(&fp, filepath, _T("wbS")); if (!fp || error != 0) { TRACE(_T("fopen error\n")); } else { m_mdatFile = fp; } } if (df.cameraSaveFileType == SAVE_FILE_TYPE_CSV) { CString filepath; filepath.Format(_T("%s\\%s.csv"), (LPCTSTR)df.cameraSaveFolderPath, (LPCTSTR)df.cameraSaveFileName); FILE* fp = NULL; errno_t error = _tfopen_s(&fp, filepath, _T("w")); if (!fp || error != 0) { TRACE(_T("fopen error\n")); } else { _ftprintf(fp, _T("Frame No,Sequence No,Difference from previous frame,Drop\n")); m_csvFile = fp; } } m_lockRec.Unlock(); // ***Unlock*** } void CLiveTab::StopRec() { // ***Lock*** BOOL* pRec = (BOOL*)m_lockRec.GetLockData(); if (*pRec) { *pRec = FALSE; m_lockRec.Unlock(); CDefaultParams& df = ((CCamMonitorApp*)AfxGetApp())->GetDefaultParams(); if (df.cameraSaveFileType == SAVE_FILE_TYPE_RAW) { WriteCIH(); } if (m_csvFile) { fclose(m_csvFile); m_csvFile = nullptr; } if (m_mdatFile) { fclose(m_mdatFile); m_mdatFile = nullptr; } } else { m_lockRec.Unlock(); } // ***Unlock*** } void CLiveTab::WriteCIH() { CIH cih; CDefaultParams& df = ((CCamMonitorApp*)AfxGetApp())->GetDefaultParams(); PUC_GetFramerateShutter(m_camera.GetHandle(), &cih.m_framerate, &cih.m_shutterFps); PUC_GetExposeTime(m_camera.GetHandle(), &cih.m_exposeOn, &cih.m_exposeOff); PUC_GetResolution(m_camera.GetHandle(), &cih.m_width, &cih.m_height); PUC_GetXferDataSize(m_camera.GetHandle(), PUC_DATA_COMPRESSED, &cih.m_frameSize); cih.m_frameCount = m_nRecFrameCount; memcpy(cih.m_quantization, m_camera.GetQuantization(), sizeof(cih.m_quantization)); cih.m_filetype = df.cameraSaveFileType; PUC_GetColorType(m_camera.GetHandle(), &cih.m_colortype); CString filepath; static INT64 n = 0; filepath.Format(_T("%s\\%s.cih"), (LPCTSTR)df.cameraSaveFolderPath, (LPCTSTR)df.cameraSaveFileName); cih.Write(filepath); } void CLiveTab::DecodeImage(PUCHAR pBuffer) { // ***Lock*** CBitmapImage* pImage = (CBitmapImage*)m_lockImage.GetLockData(); pImage->FillBlack(); PUC_DecodeData( pImage->GetBuffer() + (m_xvDecodePos.y * pImage->GetLineByte() + m_xvDecodePos.x), m_xvDecodePos.x, m_xvDecodePos.y, m_xvDecodeSize.cx, m_xvDecodeSize.cy, pImage->GetLineByte(), pBuffer, m_camera.GetQuantization()); m_lockImage.Unlock(); // ***Unlock*** } void CLiveTab::_SingleProc(PPUC_XFER_DATA_INFO pInfo, void* pArg) { CLiveTab* pObj = (CLiveTab*)pArg; pObj->SingleProc(pInfo); } void CLiveTab::SingleProc(PPUC_XFER_DATA_INFO pInfo) { // Update Live View PTEXTINFO pTextInfo = (PTEXTINFO)m_lockTextInfo.GetLockData(); pTextInfo->nSeqNo = pInfo->nSequenceNo; m_lockTextInfo.Unlock(); DecodeImage(pInfo->pData); ::PostMessage(GetSafeHwnd(), WM_USER_UPDATE_VIEW, (WPARAM)0, (LPARAM)0); } void CLiveTab::_ContinuousProc(PPUC_XFER_DATA_INFO pInfo, void* pArg) { CLiveTab* pObj = (CLiveTab*)pArg; pObj->ContinuousProc(pInfo); } void CLiveTab::ContinuousProc(PPUC_XFER_DATA_INFO pInfo) { // Save BOOL* pRec = (BOOL*)m_lockRec.GetLockData(); if (*pRec) { CDefaultParams& df = ((CCamMonitorApp*)AfxGetApp())->GetDefaultParams(); FILE* fp = NULL; errno_t error; static INT32 nPreSeqNo = 0; if (df.cameraSaveFileType == SAVE_FILE_TYPE_RAW) { fp = m_mdatFile; if (fp) { fwrite(pInfo->pData, pInfo->nDataSize, 1, fp); m_nRecFrameCount++; } } else if (df.cameraSaveFileType == SAVE_FILE_TYPE_CSV) { fp = m_csvFile; if (fp) { if ((pInfo->nSequenceNo - nPreSeqNo) == 0 || (pInfo->nSequenceNo - nPreSeqNo) == 1) _ftprintf(fp, _T("%lld,%d,%d\n"), m_nRecFrameCount, pInfo->nSequenceNo, pInfo->nSequenceNo - nPreSeqNo); else _ftprintf(fp, _T("%lld,%d,%d,*\n"), m_nRecFrameCount, pInfo->nSequenceNo, pInfo->nSequenceNo - nPreSeqNo); m_nRecFrameCount++; } } nPreSeqNo = pInfo->nSequenceNo; } m_lockRec.Unlock(); } void CLiveTab::UpdateBuffer() { m_camera.UpdateBuffer(); UINT32 w, h; PUC_COLOR_TYPE colorType; PUC_GetResolution(m_camera.GetHandle(), &w, &h); PUC_GetColorType(m_camera.GetHandle(), &colorType); m_lockImage.SetWidth(w); m_lockImage.SetHeight(h); m_lockImage.SetColor(colorType != PUC_COLOR_MONO); m_lockImage.Create(); } void CLiveTab::UpdateControlState() { CString s; BOOL bOpened = m_camera.IsOpened(); BOOL bContinuous = m_xvAcqMode == ACQUISITION_MODE_CONTINUOUS; BOOL bExternal = m_xvSyncIn == PUC_SYNC_EXTERNAL; // ***Lock*** BOOL bRecording = *(BOOL*)m_lockRec.GetLockData(); m_lockRec.Unlock(); // ***Unlock*** GetDlgItem(IDC_OPENCAMERA)->EnableWindow(!bRecording); m_buttonRec.EnableWindow(bOpened && bContinuous && !bRecording); GetDlgItem(IDC_STOP)->EnableWindow(bRecording); GetDlgItem(IDC_ACQUISITION_SINGLE)->EnableWindow(bOpened && !bRecording); GetDlgItem(IDC_ACQUISITION_CONTINUOUS)->EnableWindow(bOpened && !bRecording); m_comboFramerate.EnableWindow(bOpened && !bContinuous); m_comboShutterFps.EnableWindow(bOpened && !bContinuous); m_comboReso.EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_IN_INTERNAL)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_IN_EXTERNAL)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_OUT_SIGNAL_POSI)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_OUT_SIGNAL_NEGA)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_OUT_DELAY)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_OUT_WIDTH)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SYNC_OUT_MAGNIFICATION)->EnableWindow(bOpened && !bContinuous && !bExternal); GetDlgItem(IDC_LED_MODE)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_FAN_CTRL)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_QUANTIZATION)->EnableWindow(FALSE); GetDlgItem(IDC_EXPOSE_ON)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_EXPOSE_OFF)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_DECODE_POS_X)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_DECODE_POS_Y)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_DECODE_POS_W)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_DECODE_POS_H)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SNAPSHOT)->EnableWindow(bOpened && !bContinuous); GetDlgItem(IDC_SAVE_TO)->EnableWindow(bOpened && !bContinuous); // Record button color if (bRecording) { m_buttonRec.SetFaceColor(RGB(242, 121, 8), true); m_buttonRec.SetTextColor(RGB(255, 255, 255)); s.LoadString(IDS_RECORDING); m_buttonRec.SetWindowText(s); } else { m_buttonRec.SetFaceColor(RGB(94, 124, 146), true); m_buttonRec.SetTextColor(RGB(255, 255, 255)); s.LoadString(IDS_REC); m_buttonRec.SetWindowText(s); } Invalidate(); } void CLiveTab::UpdateCameraSerialNo() { UINT32 nName = 0; UINT32 nType = 0; UINT32 nVer = 0; UINT64 nSerialNo = 0; CString s; PUC_GetDeviceName(m_camera.GetHandle(), &nName); PUC_GetDeviceType(m_camera.GetHandle(), &nType); PUC_GetDeviceVersion(m_camera.GetHandle(), &nVer); PUC_GetSerialNo(m_camera.GetHandle(), &nSerialNo); s.Format(_T("NAME:%x TYPE:%x Ver:%u Ser:%llx"), nName, nType, nVer, nSerialNo); GetDlgItem(IDC_STATIC_SERIAL)->SetWindowText(s); } void CLiveTab::UpdateFramerateComboBox() { CString s; UINT32 nFramerate, nShutterFps; UINT32 nTmp; m_comboFramerate.ResetContent(); if (!IsCameraOpened()) return; PUC_GetFramerateShutter(m_camera.GetHandle(), &nFramerate, &nShutterFps); for (int i = 0; i < MAX_FRAMERATE_COUNT; i++) { nTmp = FramerateShutterTable[i].nFramerate; s.Format(_T("%u fps"), nTmp); m_comboFramerate.AddString(s); m_comboFramerate.SetItemData(m_comboFramerate.GetCount() - 1, nTmp); if (nTmp == nFramerate) m_comboFramerate.SetCurSel(m_comboFramerate.GetCount() - 1); } } void CLiveTab::UpdateShutterFpsComboBox() { CString s; UINT32 nCurrentFps = 0; UINT32 nFramerate, nShutterFps; m_comboShutterFps.ResetContent(); if (!IsCameraOpened()) return; PUC_GetFramerateShutter(m_camera.GetHandle(), &nFramerate, &nShutterFps); nCurrentFps = m_comboFramerate.GetItemData(m_comboFramerate.GetCurSel()); for (int i = 0; i < MAX_FRAMERATE_COUNT; i++) { if (nCurrentFps != FramerateShutterTable[i].nFramerate) continue; for (int j = 0; j < FramerateShutterTable[i].itemList.nSize; j++) { s.Format(_T("1/%u fps"), FramerateShutterTable[i].itemList.items[j]); m_comboShutterFps.AddString(s); m_comboShutterFps.SetItemData(m_comboShutterFps.GetCount() - 1, FramerateShutterTable[i].itemList.items[j]); if (FramerateShutterTable[i].itemList.items[j] == nShutterFps) m_comboShutterFps.SetCurSel(m_comboShutterFps.GetCount() - 1); } } } void CLiveTab::UpdateResoComboBox() { CString s; UINT32 w, h, nCurMaxW, nCurMaxH, n; PUC_RESO_LIMIT_INFO info = { 0 }; m_comboReso.ResetContent(); if (!IsCameraOpened()) return; PUC_GetResolution(m_camera.GetHandle(), &w, &h); PUC_GetMaxResolution(m_camera.GetHandle(), &nCurMaxW, &nCurMaxH); PUC_GetResolutionLimit(m_camera.GetHandle(), &info); n = nCurMaxH; while (1) { s.Format(_T("%u x %u"), nCurMaxW, n); m_comboReso.AddString(s); m_comboReso.SetItemData(m_comboReso.GetCount() - 1, MAKE_RESO(nCurMaxW, n)); if (n == h) m_comboReso.SetCurSel(m_comboReso.GetCount() - 1); n -= info.nUnitHeight; if (n < info.nMinHeight) break; } } void CLiveTab::UpdateSyncOutSignalRadio() { if (!IsCameraOpened()) return; PUC_GetSyncInMode(m_camera.GetHandle(), (PUC_SYNC_MODE*)&m_xvSyncIn); UpdateData(FALSE); } void CLiveTab::UpdateSyncInRadio() { if (!IsCameraOpened()) return; PUC_GetSyncOutSignal(m_camera.GetHandle(), (PUC_SIGNAL*)& m_xvSyncOutSignal); UpdateData(FALSE); } void CLiveTab::UpdateSyncOutDelayEdit() { if (!IsCameraOpened()) return; PUC_GetSyncOutDelay(m_camera.GetHandle(), (UINT32*)&m_xvSyncOutDelay); UpdateData(FALSE); } void CLiveTab::UpdateSyncOutWidthEdit() { if (!IsCameraOpened()) return; PUC_GetSyncOutWidth(m_camera.GetHandle(), (UINT32*)&m_xvSyncOutWidth); UpdateData(FALSE); } void CLiveTab::UpdateSyncOutMagComboBox() { CString s; UINT32 nMag; m_comboSyncOutMag.ResetContent(); if (!IsCameraOpened()) return; PUC_GetSyncOutMagnification(m_camera.GetHandle(), &nMag); s.Format(_T("x 0.5")); m_comboSyncOutMag.AddString(s); m_comboSyncOutMag.SetItemData(m_comboSyncOutMag.GetCount() - 1, PUC_SYNC_OUT_MAGNIFICATION_0_5); if (nMag == PUC_SYNC_OUT_MAGNIFICATION_0_5) m_comboSyncOutMag.SetCurSel(m_comboSyncOutMag.GetCount() - 1); s.Format(_T("x 1")); m_comboSyncOutMag.AddString(s); m_comboSyncOutMag.SetItemData(m_comboSyncOutMag.GetCount() - 1, 1); if (nMag == 1) m_comboSyncOutMag.SetCurSel(m_comboSyncOutMag.GetCount() - 1); s.Format(_T("x 2")); m_comboSyncOutMag.AddString(s); m_comboSyncOutMag.SetItemData(m_comboSyncOutMag.GetCount() - 1, 2); if (nMag == 2) m_comboSyncOutMag.SetCurSel(m_comboSyncOutMag.GetCount() - 1); s.Format(_T("x 4")); m_comboSyncOutMag.AddString(s); m_comboSyncOutMag.SetItemData(m_comboSyncOutMag.GetCount() - 1, 4); if (nMag == 4) m_comboSyncOutMag.SetCurSel(m_comboSyncOutMag.GetCount() - 1); s.Format(_T("x 10")); m_comboSyncOutMag.AddString(s); m_comboSyncOutMag.SetItemData(m_comboSyncOutMag.GetCount() - 1, 10); if (nMag == 10) m_comboSyncOutMag.SetCurSel(m_comboSyncOutMag.GetCount() - 1); } void CLiveTab::UpdateLEDModeCheckBox() { if (!IsCameraOpened()) return; PUC_GetLEDMode(m_camera.GetHandle(), (PUC_MODE*)&m_xvLEDMode); UpdateData(FALSE); } void CLiveTab::UpdateFANCtrlCheckBox() { if (!IsCameraOpened()) return; PUC_GetFanState(m_camera.GetHandle(), (PUC_MODE*)&m_xvFanState); UpdateData(FALSE); } void CLiveTab::UpdateQuantization() { CString s; int nCurSel = m_comboQuantization.GetCurSel(); if (nCurSel == CB_ERR) nCurSel = 0; m_comboQuantization.ResetContent(); if (!IsCameraOpened()) return; s.LoadString(IDS_QUALITY_NORMAL); m_comboQuantization.AddString(s); m_comboQuantization.SetItemData(m_comboQuantization.GetCount() - 1, IMAGE_QUALITY_NORMAL); s.LoadString(IDS_QUALITY_LOW); m_comboQuantization.AddString(s); m_comboQuantization.SetItemData(m_comboQuantization.GetCount() - 1, IMAGE_QUALITY_LOW); s.LoadString(IDS_QUALITY_HIGH); m_comboQuantization.AddString(s); m_comboQuantization.SetItemData(m_comboQuantization.GetCount() - 1, IMAGE_QUALITY_HIGH); m_comboQuantization.SetCurSel(m_comboQuantization.GetCount() - 1); } void CLiveTab::UpdateExposeTime() { if (!IsCameraOpened()) return; PUC_GetExposeTime(m_camera.GetHandle(), (UINT32*)&m_xvExposeOn, (UINT32*)&m_xvExposeOff); UpdateData(FALSE); } void CLiveTab::ResetDecodePos() { if (!IsCameraOpened()) return; UINT32 w, h; PUC_GetResolution(m_camera.GetHandle(), &w, &h); m_xvDecodePos.x = m_xvDecodePosBK.x = 0; m_xvDecodePos.y = m_xvDecodePosBK.y = 0; m_xvDecodeSize.cx = m_xvDecodeSizeBK.cx = w; m_xvDecodeSize.cy = m_xvDecodeSizeBK.cy = h; UpdateData(FALSE); } void CLiveTab::ConfirmDecodePos() { if (!IsCameraOpened()) return; UINT32 w, h; PUC_GetResolution(m_camera.GetHandle(), &w, &h); BOOL bIllegal = FALSE; if (m_xvDecodePos.x != 0 && (m_xvDecodePos.x % 8) != 0) bIllegal = TRUE; if (m_xvDecodePos.y != 0 && (m_xvDecodePos.y % 8) != 0) bIllegal = TRUE; if (m_xvDecodeSize.cx == 0) bIllegal = TRUE; if (m_xvDecodeSize.cy == 0) bIllegal = TRUE; if ((m_xvDecodePos.x + m_xvDecodeSize.cx) > w) bIllegal = TRUE; if ((m_xvDecodePos.x + m_xvDecodeSize.cy) > h) bIllegal = TRUE; if (bIllegal) { m_xvDecodePos.x = m_xvDecodePosBK.x; m_xvDecodePos.y = m_xvDecodePosBK.y; m_xvDecodeSize.cx = m_xvDecodeSizeBK.cx; m_xvDecodeSize.cy = m_xvDecodeSizeBK.cy; } else { m_xvDecodePosBK.x = m_xvDecodePos.x; m_xvDecodePosBK.y = m_xvDecodePos.y; m_xvDecodeSizeBK.cx = m_xvDecodeSize.cx; m_xvDecodeSizeBK.cy = m_xvDecodeSize.cy; } UpdateData(FALSE); } BEGIN_MESSAGE_MAP(CLiveTab, CBaseTab) ON_MESSAGE(WM_INITDIALOG, OnInitDialog) ON_WM_SHOWWINDOW() ON_WM_DESTROY() ON_WM_TIMER() ON_BN_CLICKED(IDC_OPENCAMERA, &CLiveTab::OnBnClickedOpencamera) ON_BN_CLICKED(IDC_REC, &CLiveTab::OnBnClickedRec) ON_BN_CLICKED(IDC_ACQUISITION_SINGLE, &CLiveTab::OnBnClickedAcquisitionSingle) ON_BN_CLICKED(IDC_ACQUISITION_CONTINUOUS, &CLiveTab::OnBnClickedAcquisitionContinuous) ON_BN_CLICKED(IDC_STOP, &CLiveTab::OnBnClickedStop) ON_CBN_SELCHANGE(IDC_FRAMERATE, &CLiveTab::OnCbnSelchangeFramerate) ON_CBN_SELCHANGE(IDC_SHUTTERFPS, &CLiveTab::OnCbnSelchangeShutterFps) ON_CBN_SELCHANGE(IDC_RESOLUTION, &CLiveTab::OnCbnSelchangeResolution) ON_BN_CLICKED(IDC_SYNC_IN_INTERNAL, &CLiveTab::OnBnClickedSyncIn) ON_BN_CLICKED(IDC_SYNC_IN_EXTERNAL, &CLiveTab::OnBnClickedSyncIn) ON_BN_CLICKED(IDC_SYNC_OUT_SIGNAL_POSI, &CLiveTab::OnBnClickedSyncOutSignal) ON_BN_CLICKED(IDC_SYNC_OUT_SIGNAL_NEGA, &CLiveTab::OnBnClickedSyncOutSignal) ON_EN_KILLFOCUS(IDC_SYNC_OUT_DELAY, &CLiveTab::OnEnKillfocusSyncOutDelay) ON_EN_KILLFOCUS(IDC_SYNC_OUT_WIDTH, &CLiveTab::OnEnKillfocusSyncOutWidth) ON_CBN_SELCHANGE(IDC_SYNC_OUT_MAGNIFICATION, &CLiveTab::OnCbnSelchangeSyncOutMag) ON_BN_CLICKED(IDC_LED_MODE, &CLiveTab::OnBnClickedLEDMode) ON_BN_CLICKED(IDC_FAN_CTRL, &CLiveTab::OnBnClickedFANCtrl) ON_CBN_SELCHANGE(IDC_QUANTIZATION, &CLiveTab::OnCbnSelchangeQuantization) ON_EN_KILLFOCUS(IDC_EXPOSE_ON, &CLiveTab::OnEnKillfocusExposeOn) ON_EN_KILLFOCUS(IDC_EXPOSE_OFF, &CLiveTab::OnEnKillfocusExposeOff) ON_EN_KILLFOCUS(IDC_DECODE_POS_X, &CLiveTab::OnEnKillfocusDecodePos) ON_EN_KILLFOCUS(IDC_DECODE_POS_Y, &CLiveTab::OnEnKillfocusDecodePos) ON_EN_KILLFOCUS(IDC_DECODE_POS_W, &CLiveTab::OnEnKillfocusDecodePos) ON_EN_KILLFOCUS(IDC_DECODE_POS_H, &CLiveTab::OnEnKillfocusDecodePos) ON_BN_CLICKED(IDC_SNAPSHOT, &CLiveTab::OnBnClickedSnapshot) ON_BN_CLICKED(IDC_SAVE_TO, &CLiveTab::OnBnClickedSaveTo) END_MESSAGE_MAP() LRESULT CLiveTab::OnInitDialog(WPARAM wParam, LPARAM lParam) { LRESULT ret = CBaseTab::OnInitDialog(wParam, lParam); if (!ret) return ret; UpdateControlState(); OnBnClickedAcquisitionSingle(); return FALSE; } void CLiveTab::OnShowWindow(BOOL bShow, UINT nStatus) { if (bShow) { UpdateControlState(); StartLive(); } else { StopRec(); StopLive(); } } void CLiveTab::OnDestroy() { CloseCamera(); } void CLiveTab::OnTimer(UINT_PTR nIDEvent) { if (nIDEvent == TIMER_ID_UPDATE_TEMP) { if (m_camera.IsOpened() && m_camera.GetAcquisitionMode() != ACQUISITION_MODE_CONTINUOUS) { PTEXTINFO pTextInfo = (PTEXTINFO)m_lockTextInfo.GetLockData(); PUC_GetSensorTemperature(m_camera.GetHandle(), &pTextInfo->nTemp); m_lockTextInfo.Unlock(); } } CBaseTab::OnTimer(nIDEvent); } void CLiveTab::OnBnClickedOpencamera() { CSelectCameraDialog dlg; PUCRESULT result; CString msg; if (dlg.DoModal() != IDOK) goto EXIT_LABEL; StopRec(); StopLive(); if (!OpenCamera(dlg.GetDeviceNo(), dlg.GetSingleXferTimeOut(), dlg.GetContinuousXferTimeOut(), dlg.GetRingBufCount())) goto EXIT_LABEL; UpdateBuffer(); EXIT_LABEL: UpdateCameraSerialNo(); UpdateFramerateComboBox(); UpdateShutterFpsComboBox(); UpdateResoComboBox(); UpdateSyncInRadio(); UpdateSyncOutSignalRadio(); UpdateSyncOutDelayEdit(); UpdateSyncOutWidthEdit(); UpdateSyncOutMagComboBox(); UpdateLEDModeCheckBox(); UpdateFANCtrlCheckBox(); UpdateQuantization(); UpdateExposeTime(); ResetDecodePos(); UpdateControlState(); StartLive(); } void CLiveTab::OnBnClickedRec() { StartRec(); UpdateControlState(); } void CLiveTab::OnBnClickedStop() { StopRec(); UpdateControlState(); } void CLiveTab::OnBnClickedAcquisitionSingle() { StopLive(); m_xvAcqMode = ACQUISITION_MODE_SINGLE; UpdateData(FALSE); m_camera.SetAcquisitionMode((ACQUISITION_MODE)m_xvAcqMode); StartLive(); UpdateControlState(); } void CLiveTab::OnBnClickedAcquisitionContinuous() { StopLive(); m_xvAcqMode = ACQUISITION_MODE_CONTINUOUS; UpdateData(FALSE); m_camera.SetAcquisitionMode((ACQUISITION_MODE)m_xvAcqMode); StartLive(); UpdateControlState(); } void CLiveTab::OnCbnSelchangeFramerate() { UINT32 nFramerate = m_comboFramerate.GetItemData(m_comboFramerate.GetCurSel()); PUCRESULT result; CString msg; StopLive(); result = PUC_SetFramerateShutter(m_camera.GetHandle(), nFramerate, nFramerate); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetFramerateShutter"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateFramerateComboBox(); UpdateShutterFpsComboBox(); UpdateResoComboBox(); UpdateExposeTime(); UpdateSyncOutWidthEdit(); UpdateSyncOutMagComboBox(); UpdateBuffer(); ResetDecodePos(); StartLive(); UpdateControlState(); } void CLiveTab::OnCbnSelchangeShutterFps() { UINT32 nFramerate = m_comboFramerate.GetItemData(m_comboFramerate.GetCurSel()); UINT32 nShutterFps = m_comboShutterFps.GetItemData(m_comboShutterFps.GetCurSel()); PUCRESULT result; CString msg; StopLive(); result = PUC_SetFramerateShutter(m_camera.GetHandle(), nFramerate, nShutterFps); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetFramerateShutter"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateFramerateComboBox(); UpdateShutterFpsComboBox(); UpdateResoComboBox(); UpdateExposeTime(); UpdateSyncOutWidthEdit(); UpdateSyncOutMagComboBox(); StartLive(); UpdateControlState(); } void CLiveTab::OnCbnSelchangeResolution() { UINT32 nResolution = m_comboReso.GetItemData(m_comboReso.GetCurSel()); PUCRESULT result; CString msg; StopLive(); result = PUC_SetResolution(m_camera.GetHandle(), RESO_W(nResolution), RESO_H(nResolution)); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetResolution"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateResoComboBox(); UpdateBuffer(); ResetDecodePos(); StartLive(); UpdateControlState(); } void CLiveTab::OnBnClickedSyncIn() { PUCRESULT result; CString msg; StopLive(); UpdateData(TRUE); result = PUC_SetSyncInMode(m_camera.GetHandle(), (PUC_SYNC_MODE)m_xvSyncIn); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetSyncInMode"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateFramerateComboBox(); UpdateShutterFpsComboBox(); UpdateResoComboBox(); UpdateExposeTime(); UpdateSyncOutMagComboBox(); UpdateBuffer(); ResetDecodePos(); StartLive(); UpdateControlState(); } void CLiveTab::OnBnClickedSyncOutSignal() { PUCRESULT result; CString msg; StopLive(); UpdateData(TRUE); result = PUC_SetSyncOutSignal(m_camera.GetHandle(), (PUC_SIGNAL)m_xvSyncOutSignal); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetSyncOutSignal"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } StartLive(); UpdateControlState(); } void CLiveTab::OnEnKillfocusSyncOutDelay() { PUCRESULT result; CString msg; StopLive(); UpdateData(TRUE); result = PUC_SetSyncOutDelay(m_camera.GetHandle(), m_xvSyncOutDelay); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetSyncOutDelay"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } StartLive(); UpdateControlState(); } void CLiveTab::OnEnKillfocusSyncOutWidth() { PUCRESULT result; CString msg; StopLive(); UpdateData(TRUE); result = PUC_SetSyncOutWidth(m_camera.GetHandle(), m_xvSyncOutWidth); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetSyncOutWidth"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateSyncOutMagComboBox(); StartLive(); UpdateControlState(); } void CLiveTab::OnCbnSelchangeSyncOutMag() { UINT32 nMag = m_comboSyncOutMag.GetItemData(m_comboSyncOutMag.GetCurSel()); PUCRESULT result; CString msg; StopLive(); result = PUC_SetSyncOutMagnification(m_camera.GetHandle(), nMag); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetSyncOutMagnification"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateSyncOutWidthEdit(); StartLive(); UpdateControlState(); } void CLiveTab::OnBnClickedLEDMode() { PUCRESULT result; CString msg; StopLive(); UpdateData(TRUE); result = PUC_SetLEDMode(m_camera.GetHandle(), (PUC_MODE)m_xvLEDMode); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetLEDMode"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } StartLive(); UpdateControlState(); } void CLiveTab::OnBnClickedFANCtrl() { PUCRESULT result; CString msg; StopLive(); UpdateData(TRUE); result = PUC_SetFanState(m_camera.GetHandle(), (PUC_MODE)m_xvFanState); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetFanCtrl"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } StartLive(); UpdateControlState(); } void CLiveTab::OnCbnSelchangeQuantization() { QUANTIZATION_MODE q = (QUANTIZATION_MODE)m_comboQuantization.GetItemData(m_comboQuantization.GetCurSel()); PUCRESULT result; CString msg; StopLive(); result = m_camera.SetQuantization(q); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetQuantization"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } StartLive(); UpdateControlState(); } void CLiveTab::SetExposeTime() { PUCRESULT result; CString msg; StopLive(); result = PUC_SetExposeTime(m_camera.GetHandle(), m_xvExposeOn, m_xvExposeOff); if (PUC_CHK_FAILED(result)) { msg.FormatMessage(IDS_ERROR_CODE, _T("PUC_SetExposeTime"), result); AfxMessageBox(msg, MB_OK | MB_ICONERROR); } UpdateExposeTime(); UpdateResoComboBox(); UpdateSyncOutMagComboBox(); UpdateBuffer(); ResetDecodePos(); StartLive(); UpdateControlState(); } void CLiveTab::OnEnKillfocusExposeOn() { UpdateData(TRUE); SetExposeTime(); } void CLiveTab::OnEnKillfocusExposeOff() { UpdateData(TRUE); SetExposeTime(); } void CLiveTab::OnEnKillfocusDecodePos() { StopLive(); UpdateData(TRUE); ConfirmDecodePos(); StartLive(); } void CLiveTab::OnBnClickedSnapshot() { PUCRESULT result; CBitmapImage* pImage = NULL; CString filepath, sTmp; UINT64 nSerialNo; result = PUC_GetSerialNo(m_camera.GetHandle(), &nSerialNo); if (PUC_CHK_FAILED(result)) { AfxMessageBox(IDS_ERROR_SAVE, MB_OK | MB_ICONERROR); return; } sTmp.Format(_T("%llx"), nSerialNo); sTmp = MakeUpper(sTmp); pImage = m_camera.GetSingleImageStart(); if (!pImage) { m_camera.GetSingleImageEnd(); AfxMessageBox(IDS_ERROR_SAVE, MB_OK | MB_ICONERROR); return; } CDefaultParams& df = ((CCamMonitorApp*)AfxGetApp())->GetDefaultParams(); filepath.Format(_T("%s\\%s.bmp"), (LPCTSTR)df.cameraSaveFolderPath, (LPCTSTR)sTmp); if (!pImage->Save(filepath)) { m_camera.GetSingleImageEnd(); AfxMessageBox(IDS_ERROR_SAVE, MB_OK | MB_ICONERROR); return; } m_camera.GetSingleImageEnd(); AfxMessageBox(IDS_COMPLETED, MB_OK | MB_ICONINFORMATION); } void CLiveTab::OnBnClickedSaveTo() { CSaveLiveDialog dlg(this); if (dlg.DoModal() != IDOK) return; }
24.347079
123
0.749365
infinicam
e3028bc70fab84b4590d18f85286390ff3a83e29
1,797
hpp
C++
include/engine/utils/timing/Profiler.hpp
Ghabriel/CppGameArchitecture
1212cf1e140ba78d72f2aea2aff56ec8c3e23293
[ "Apache-2.0" ]
6
2018-08-05T21:45:23.000Z
2021-10-30T19:48:34.000Z
include/engine/utils/timing/Profiler.hpp
Ghabriel/CppGameArchitecture
1212cf1e140ba78d72f2aea2aff56ec8c3e23293
[ "Apache-2.0" ]
null
null
null
include/engine/utils/timing/Profiler.hpp
Ghabriel/CppGameArchitecture
1212cf1e140ba78d72f2aea2aff56ec8c3e23293
[ "Apache-2.0" ]
1
2021-11-01T20:15:38.000Z
2021-11-01T20:15:38.000Z
#ifndef UTILS_TIMING_PROFILER_HPP #define UTILS_TIMING_PROFILER_HPP #include <chrono> namespace engine::utils { /** * \brief Provides a simple way to profile arbitrary code. */ class Profiler { public: /** * \brief Starts a time measurement. */ void start() { startTime = std::chrono::steady_clock::now(); } /** * \brief Finishes a time measurement. The elapsed time can be obtained via * measure(), measureAsSeconds(), measureAsMilliseconds() or * measureAsMicroseconds(). */ void finish() { finishTime = std::chrono::steady_clock::now(); } /** * \brief Returns the elapsed time in an arbitrary time unit. */ template<typename T> intmax_t measure() const { return std::chrono::duration_cast<T>(finishTime - startTime).count(); } /** * \brief Returns the elapsed time in seconds, rounded down to * an integer. */ intmax_t measureAsSeconds() const { return measure<std::chrono::seconds>(); } /** * \brief Returns the elapsed time in milliseconds, rounded down to * an integer. */ intmax_t measureAsMilliseconds() const { return measure<std::chrono::milliseconds>(); } /** * \brief Returns the elapsed time in microseconds, rounded down to * an integer. */ intmax_t measureAsMicroseconds() const { return measure<std::chrono::microseconds>(); } private: std::chrono::steady_clock::time_point startTime; std::chrono::steady_clock::time_point finishTime; }; } #endif
26.820896
83
0.558152
Ghabriel
e309c1e95eee4987d9f7c0a8851787e62ea609c2
573
cpp
C++
AIPaddle.cpp
deviant-zairus/pong
ae76c13c5801212051749bfcc967d231c1821920
[ "Apache-2.0" ]
null
null
null
AIPaddle.cpp
deviant-zairus/pong
ae76c13c5801212051749bfcc967d231c1821920
[ "Apache-2.0" ]
null
null
null
AIPaddle.cpp
deviant-zairus/pong
ae76c13c5801212051749bfcc967d231c1821920
[ "Apache-2.0" ]
null
null
null
#include "AIPaddle.h" #include "Ball.h" AIPaddle::AIPaddle(Ball* ball) : Paddle(irr::core::vector3df(25.0f, 0.0f, 0.0f)) { this->_ball = ball; } AIPaddle::~AIPaddle() { } bool AIPaddle::Update(float deltaTime, InputHandler* ih) { irr::core::vector3df ballPos = this->_ball->GetPosition(); irr::core::vector3df myPos = this->_node->GetPosition(); if (ballPos.Y > myPos.Y) { this->_node->setPosition(myPos + (_velocity * deltaTime)); } else if (ballPos.Y < myPos.Y) { this->_nod->setPosition(myPos - (_velocity * deltaTime)); } Paddle::ValidatePosition(); }
21.222222
80
0.673647
deviant-zairus
e3114210a4b46d76da8a8768405a17bd976435f6
407
hpp
C++
fts/fts_share/fts_define.hpp
iihiro/FHE-Table-Search
a035cf9af311a8cb123a08d5d1378acd739df4a4
[ "Apache-2.0" ]
2
2020-07-19T15:54:42.000Z
2020-08-20T06:35:05.000Z
fts/fts_share/fts_define.hpp
yamanalab/FHE-Table-Search
0104ace6e91409730cc6a58481a0f8459892d6dc
[ "Apache-2.0" ]
2
2020-07-09T01:41:40.000Z
2020-08-18T03:24:38.000Z
fts/fts_share/fts_define.hpp
iihiro/FHE-Table-Search
a035cf9af311a8cb123a08d5d1378acd739df4a4
[ "Apache-2.0" ]
1
2020-01-21T05:16:28.000Z
2020-01-21T05:16:28.000Z
#ifndef FTS_DEFINE_HPP #define FTS_DEFINE_HPP #define FTS_TIMEOUT_SEC (60) #define FTS_RETRY_INTERVAL_USEC (2000000) #define FTS_DEFAULT_MAX_CONCURRENT_QUERIES 128 #define FTS_DEFAULT_MAX_RESULTS 128 #define FTS_DEFAULT_MAX_RESULT_LIFETIME_SEC 50000 #define FTS_LUTFILE_EXT "csv" #define FTS_LUT_POSSIBLE_INPUT_NUM_ONE (819200) #define FTS_LUT_POSSIBLE_INPUT_NUM_TWO (4096) #endif /* FTS_DEFINE_HPP */
23.941176
49
0.847666
iihiro
e31434cb7ae51ebbbc0295413f7cbdb6a0fda312
8,424
cpp
C++
src/argss/modules/akeys.cpp
cstrahan/argss
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
[ "BSD-2-Clause" ]
1
2015-02-12T01:24:04.000Z
2015-02-12T01:24:04.000Z
src/argss/modules/akeys.cpp
cstrahan/argss
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
[ "BSD-2-Clause" ]
null
null
null
src/argss/modules/akeys.cpp
cstrahan/argss
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
[ "BSD-2-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) // 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. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // Headers /////////////////////////////////////////////////////////// #include "argss/modules/akeys.h" /////////////////////////////////////////////////////////// // Global Variables /////////////////////////////////////////////////////////// VALUE ARGSS::AKeys::id; /////////////////////////////////////////////////////////// // ARGSS Keys initialize /////////////////////////////////////////////////////////// void ARGSS::AKeys::Init() { id = rb_define_module("Keys"); rb_define_const(id, "BACKSPACE", INT2FIX(1001)); rb_define_const(id, "TAB", INT2FIX(1002)); rb_define_const(id, "CLEAR", INT2FIX(1003)); rb_define_const(id, "RETURN", INT2FIX(1004)); rb_define_const(id, "PAUSE", INT2FIX(1005)); rb_define_const(id, "ESCAPE", INT2FIX(1006)); rb_define_const(id, "SPACE", INT2FIX(1007)); rb_define_const(id, "PGUP", INT2FIX(1008)); rb_define_const(id, "PGDN", INT2FIX(1009)); rb_define_const(id, "ENDS", INT2FIX(1010)); rb_define_const(id, "HOME", INT2FIX(1011)); rb_define_const(id, "LEFT", INT2FIX(1012)); rb_define_const(id, "UP", INT2FIX(1013)); rb_define_const(id, "RIGHT", INT2FIX(1014)); rb_define_const(id, "DOWN", INT2FIX(1015)); rb_define_const(id, "SNAPSHOT", INT2FIX(1016)); rb_define_const(id, "INSERT", INT2FIX(1017)); rb_define_const(id, "DEL", INT2FIX(1018)); rb_define_const(id, "SHIFT", INT2FIX(1019)); rb_define_const(id, "LSHIFT", INT2FIX(1020)); rb_define_const(id, "RSHIFT", INT2FIX(1021)); rb_define_const(id, "CTRL", INT2FIX(1022)); rb_define_const(id, "LCTRL", INT2FIX(1023)); rb_define_const(id, "RCTRL", INT2FIX(1024)); rb_define_const(id, "ALT", INT2FIX(1025)); rb_define_const(id, "LALT", INT2FIX(1026)); rb_define_const(id, "RALT", INT2FIX(1027)); rb_define_const(id, "N0", INT2FIX(1028)); rb_define_const(id, "N1", INT2FIX(1029)); rb_define_const(id, "N2", INT2FIX(1030)); rb_define_const(id, "N3", INT2FIX(1031)); rb_define_const(id, "N4", INT2FIX(1032)); rb_define_const(id, "N5", INT2FIX(1033)); rb_define_const(id, "N6", INT2FIX(1034)); rb_define_const(id, "N7", INT2FIX(1035)); rb_define_const(id, "N8", INT2FIX(1036)); rb_define_const(id, "N9", INT2FIX(1037)); rb_define_const(id, "A", INT2FIX(1038)); rb_define_const(id, "B", INT2FIX(1039)); rb_define_const(id, "C", INT2FIX(1040)); rb_define_const(id, "D", INT2FIX(1041)); rb_define_const(id, "E", INT2FIX(1042)); rb_define_const(id, "F", INT2FIX(1043)); rb_define_const(id, "G", INT2FIX(1044)); rb_define_const(id, "H", INT2FIX(1045)); rb_define_const(id, "I", INT2FIX(1046)); rb_define_const(id, "J", INT2FIX(1047)); rb_define_const(id, "K", INT2FIX(1048)); rb_define_const(id, "L", INT2FIX(1049)); rb_define_const(id, "M", INT2FIX(1050)); rb_define_const(id, "N", INT2FIX(1051)); rb_define_const(id, "O", INT2FIX(1052)); rb_define_const(id, "P", INT2FIX(1053)); rb_define_const(id, "Q", INT2FIX(1054)); rb_define_const(id, "R", INT2FIX(1055)); rb_define_const(id, "S", INT2FIX(1056)); rb_define_const(id, "T", INT2FIX(1057)); rb_define_const(id, "U", INT2FIX(1058)); rb_define_const(id, "V", INT2FIX(1059)); rb_define_const(id, "W", INT2FIX(1060)); rb_define_const(id, "X", INT2FIX(1061)); rb_define_const(id, "Y", INT2FIX(1062)); rb_define_const(id, "Z", INT2FIX(1063)); rb_define_const(id, "LOS", INT2FIX(1064)); rb_define_const(id, "ROS", INT2FIX(1065)); rb_define_const(id, "APPS", INT2FIX(1066)); rb_define_const(id, "KP0", INT2FIX(1067)); rb_define_const(id, "KP1", INT2FIX(1068)); rb_define_const(id, "KP2", INT2FIX(1069)); rb_define_const(id, "KP3", INT2FIX(1070)); rb_define_const(id, "KP4", INT2FIX(1071)); rb_define_const(id, "KP5", INT2FIX(1072)); rb_define_const(id, "KP6", INT2FIX(1073)); rb_define_const(id, "KP7", INT2FIX(1074)); rb_define_const(id, "KP8", INT2FIX(1075)); rb_define_const(id, "KP9", INT2FIX(1076)); rb_define_const(id, "MULTIPLY", INT2FIX(1077)); rb_define_const(id, "ADD", INT2FIX(1078)); rb_define_const(id, "SEPARATOR", INT2FIX(1079)); rb_define_const(id, "SUBTRACT", INT2FIX(1080)); rb_define_const(id, "DECIMAL", INT2FIX(1081)); rb_define_const(id, "DIVIDE", INT2FIX(1082)); rb_define_const(id, "F1", INT2FIX(1083)); rb_define_const(id, "F2", INT2FIX(1084)); rb_define_const(id, "F3", INT2FIX(1085)); rb_define_const(id, "F4", INT2FIX(1086)); rb_define_const(id, "F5", INT2FIX(1087)); rb_define_const(id, "F6", INT2FIX(1088)); rb_define_const(id, "F7", INT2FIX(1089)); rb_define_const(id, "F8", INT2FIX(1090)); rb_define_const(id, "F9", INT2FIX(1091)); rb_define_const(id, "F10", INT2FIX(1092)); rb_define_const(id, "F11", INT2FIX(1093)); rb_define_const(id, "F12", INT2FIX(1094)); rb_define_const(id, "CAPS_LOCK", INT2FIX(1095)); rb_define_const(id, "NUM_LOCK", INT2FIX(1096)); rb_define_const(id, "SCROLL_LOCK", INT2FIX(1097)); rb_define_const(id, "MOUSE_LEFT", INT2FIX(2001)); rb_define_const(id, "MOUSE_RIGHT", INT2FIX(2002)); rb_define_const(id, "MOUSE_MIDDLE", INT2FIX(2003)); rb_define_const(id, "MOUSE_XBUTTON1", INT2FIX(2004)); rb_define_const(id, "MOUSE_XBUTTON2", INT2FIX(2005)); rb_define_const(id, "JOY_1", INT2FIX(3001)); rb_define_const(id, "JOY_2", INT2FIX(3002)); rb_define_const(id, "JOY_3", INT2FIX(3003)); rb_define_const(id, "JOY_4", INT2FIX(3004)); rb_define_const(id, "JOY_5", INT2FIX(3005)); rb_define_const(id, "JOY_6", INT2FIX(3006)); rb_define_const(id, "JOY_7", INT2FIX(3007)); rb_define_const(id, "JOY_8", INT2FIX(3008)); rb_define_const(id, "JOY_9", INT2FIX(3009)); rb_define_const(id, "JOY_10", INT2FIX(3010)); rb_define_const(id, "JOY_11", INT2FIX(3011)); rb_define_const(id, "JOY_12", INT2FIX(3012)); rb_define_const(id, "JOY_13", INT2FIX(3013)); rb_define_const(id, "JOY_14", INT2FIX(3014)); rb_define_const(id, "JOY_15", INT2FIX(3015)); rb_define_const(id, "JOY_16", INT2FIX(3016)); rb_define_const(id, "JOY_17", INT2FIX(3017)); rb_define_const(id, "JOY_18", INT2FIX(3018)); rb_define_const(id, "JOY_19", INT2FIX(3019)); rb_define_const(id, "JOY_20", INT2FIX(3020)); rb_define_const(id, "JOY_21", INT2FIX(3021)); rb_define_const(id, "JOY_22", INT2FIX(3022)); rb_define_const(id, "JOY_23", INT2FIX(3023)); rb_define_const(id, "JOY_24", INT2FIX(3024)); rb_define_const(id, "JOY_25", INT2FIX(3025)); rb_define_const(id, "JOY_26", INT2FIX(3026)); rb_define_const(id, "JOY_27", INT2FIX(3027)); rb_define_const(id, "JOY_28", INT2FIX(3028)); rb_define_const(id, "JOY_29", INT2FIX(3029)); rb_define_const(id, "JOY_30", INT2FIX(3030)); rb_define_const(id, "JOY_31", INT2FIX(3031)); rb_define_const(id, "JOY_32", INT2FIX(3032)); }
47.061453
78
0.647317
cstrahan
e3150079d1432cceb4c51ea2bda9e1f9307372bf
520
hpp
C++
library/ATF/_pvp_order_view_end_zoclInfo.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/_pvp_order_view_end_zoclInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/_pvp_order_view_end_zoclInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_pvp_order_view_end_zocl.hpp> START_ATF_NAMESPACE namespace Info { using _pvp_order_view_end_zoclsize2_ptr = int (WINAPIV*)(struct _pvp_order_view_end_zocl*); using _pvp_order_view_end_zoclsize2_clbk = int (WINAPIV*)(struct _pvp_order_view_end_zocl*, _pvp_order_view_end_zoclsize2_ptr); }; // end namespace Info END_ATF_NAMESPACE
34.666667
135
0.776923
lemkova
e31570afb71316f7e4160f8369a6fe6a8f742191
1,457
cpp
C++
src/bullet.cpp
Harrand/Asteroids-Topaz
ce549802b0360f2554f4f6189d6ca0a486c4c928
[ "Apache-2.0" ]
null
null
null
src/bullet.cpp
Harrand/Asteroids-Topaz
ce549802b0360f2554f4f6189d6ca0a486c4c928
[ "Apache-2.0" ]
null
null
null
src/bullet.cpp
Harrand/Asteroids-Topaz
ce549802b0360f2554f4f6189d6ca0a486c4c928
[ "Apache-2.0" ]
null
null
null
// // Created by Harrand on 25/08/2018. // #include "bullet.hpp" #include "entity_manager.hpp" Bullet::Bullet(Vector2F position, Vector2F velocity, const Texture* bullet_texture, EntityManager& manager, DynamicSprite* shooter): DynamicSprite(1.0f, position, 0.0f, {Bullet::bullet_size, Bullet::bullet_size}, bullet_texture, velocity * Bullet::base_bullet_speed_multiplier), manager(manager), shooter(shooter) { if(this->shooter != nullptr) this->velocity += this->shooter->velocity; } void Bullet::on_collision(Asteroid& asteroid) { Player* player_component = dynamic_cast<Player*>(this->shooter); if(player_component != nullptr) { player_component->set_score(player_component->get_score() + Asteroid::get_score_on_kill(asteroid.get_type())); } this->manager.remove_sprite(*this); asteroid.explode(this->manager); Asteroid::play_explosion_sound(); } void Bullet::on_collision(Player& player) { // A player's own bullet cannot collide with itself. if(&player == this->shooter) return; std::cout << "bullet collided with player.\n"; } void Bullet::on_collision(PhysicsObject& other) { Asteroid* asteroid_component = dynamic_cast<Asteroid*>(&other); Player* player_component = dynamic_cast<Player*>(&other); if(asteroid_component != nullptr) this->on_collision(*asteroid_component); if(player_component != nullptr) this->on_collision(*player_component); }
34.690476
313
0.716541
Harrand
e319f162f2ac133c1961311e5cfbf7466a3f887a
8,669
cpp
C++
src/vertexcover.cpp
manighahrmani/PACE2017-min-fill
496fffc8b61b3507611ab118f211dc06457e0855
[ "MIT" ]
1
2020-05-29T15:47:16.000Z
2020-05-29T15:47:16.000Z
src/vertexcover.cpp
manighahrmani/PACE2017-min-fill
496fffc8b61b3507611ab118f211dc06457e0855
[ "MIT" ]
null
null
null
src/vertexcover.cpp
manighahrmani/PACE2017-min-fill
496fffc8b61b3507611ab118f211dc06457e0855
[ "MIT" ]
1
2020-05-29T15:47:21.000Z
2020-05-29T15:47:21.000Z
#include "vertexcover.hpp" #include "graph.hpp" #include "timer.hpp" #include "global.hpp" #include <vector> #include <queue> #include <cassert> #include <iostream> #include <cstring> #include <algorithm> #include <map> #define F first #define S second using namespace std; namespace VertexCover { int uu[maxN]; int u[maxN]; Timer VCtimer; int m1[maxN]; int m2[maxN]; int layer[2*maxN]; int bfs[2*maxN]; int z[2*maxN]; int v[2*maxN]; int dQ[maxN]; void findZ(const Graph& G, int x) { if (z[x]) return; z[x] = 1; assert(x%2 == 0); for (int nx : G.g[x/2]) { if (nx != m1[x/2]) { z[nx*2+1] = 1; if (m2[nx] != -1) findZ(G, m2[nx]*2); } } } int hkdfs(const Graph& G, int x) { int la = layer[x]; assert(la > 0); layer[x] = 0; assert(la%2 != x%2); if (x%2 == 1) { for (int nx : G.g[x/2]) { if (nx != m2[x/2] && layer[nx*2] == la-1) { int ff = hkdfs(G, nx*2); if (ff) { m2[x/2] = nx; m1[nx] = x/2; return 1; } } } return 0; } else { if (la == 1) { return 1; } if (m1[x/2] != -1 && layer[m1[x/2]*2+1] == la-1) { int ff = hkdfs(G, m1[x/2]*2+1); if (ff) return 1; } return 0; } } pair<int, vector<int> > LPVC(const Graph& G) { fill(m1, m1 + G.n, -1); fill(m2, m2 + G.n, -1); int iter = 0; while (1) { iter++; fill(layer, layer + G.n*2, 0); int bfsi1 = 0; int bfsi2 = 0; for (int i = 0; i < G.n; i++) { if (m1[i] == -1 && G.g[i].size() > 0) { layer[i*2] = 1; bfs[bfsi2++] = i*2; } } int f = 0; while (bfsi1 < bfsi2) { int x = bfs[bfsi1++]; if (x%2 == 1) { if (m2[x/2] == -1) { f = layer[x]; break; } else { if (layer[m2[x/2]*2] == 0) { layer[m2[x/2]*2] = layer[x]+1; bfs[bfsi2++] = m2[x/2]*2; } } } else { for (int nx : G.g[x/2]) { if (nx != m1[x/2] && layer[nx*2+1] == 0) { layer[nx*2+1] = layer[x]+1; bfs[bfsi2++] = nx*2+1; } } } } if (f == 0) break; assert(f>1); assert(f%2 == 0); int fo = 0; for (int i = 0; i < G.n; i++) { if (layer[i*2+1] == f && m2[i] == -1) { fo += hkdfs(G, i*2+1); } } assert(fo > 0); } assert(iter*iter <= 16*G.n); int val = 0; for (int i = 0; i < G.n; i++) { if (m1[i] != -1) val++; } fill(z, z + G.n*2, 0); for (int i = 0; i < G.n; i++) { if (m1[i] == -1) { findZ(G, i*2); } } fill(v, v + G.n*2, 0); for (int i = 0; i < 2*G.n; i++) { if (i%2 == 0) { if (!z[i]) { v[i] = 1; } } else { if (z[i]) { v[i] = 1; } } } int cval = 0; for (int i = 0; i < 2*G.n; i++) { cval += v[i]; if (v[i] == 0) { for (int nx : G.g[i/2]) { if (i%2 == 0) { assert(v[nx*2+1] == 1); } else { assert(v[nx*2] == 1); } } } } assert(cval == val); vector<int> ret; for (int i = 0; i < G.n; i++) { if (v[i*2] && v[i*2+1]) ret.push_back(i); } return {val, ret}; } int lowerBound2A(Graph G) { int bound = 0; queue<int> d1; for (int i = 0; i < G.n; i++) { assert(G.g[i].size() > 0); if (G.g[i].size() == 1) d1.push(i); } for (int i = 0; i < G.n; i++) { while (!d1.empty()) { int x = d1.front(); d1.pop(); if (G.g[x].size() == 0) continue; assert(G.g[x].size() == 1); int t = G.g[x][0]; bound++; for (int nx : G.g[t]) { if (G.g[nx].size() == 2) { d1.push(nx); } } G.remIncident(t); assert(G.g[x].size() == 0); assert(G.g[t].size() == 0); } if (G.g[i].size() == 0) continue; assert(G.g[i].size() > 1); int t = G.g[i][0]; for (int nx : G.g[i]) { if (G.g[nx].size() < G.g[t].size()) { t = nx; } } for (int nx : G.g[i]) { if (nx != t && G.g[nx].size() == 2) { d1.push(nx); } else if (nx != t && G.g[nx].size() == 3 && G.hasEdge(t, nx)) { d1.push(nx); } } for (int nx : G.g[t]) { if (nx != i && G.g[nx].size() == 2) { d1.push(nx); } } bound++; G.remIncident(t); G.remIncident(i); assert(G.g[t].size() == 0); assert(G.g[i].size() == 0); } return bound; } int dfs(const Graph& G, int x) { if (uu[x]) return 0; uu[x] = 1; int r = 1; for (int nx : G.g[x]) { r += dfs(G, nx); } return r; } void getCC(const Graph& G, int x, vector<pair<int, int> >& es) { if (u[x]) return; u[x] = 1; for (int nx : G.g[x]) { if (nx > x) es.push_back({x, nx}); getCC(G, nx, es); } } // find the best solution that is at most upperBound or report that it does not exist bool optSolve(Graph& G, int upperBound, vector<int>& sol) { if (upperBound < 0) return false; if (upperBound == 0 && G.m > 0) return false; if (G.m == 0) return true; assert(upperBound > 0); int dQ1 = 0; int dQ2 = 0; for (int i = 0; i < G.n; i++) { if (G.g[i].size() == 1) dQ[dQ2++] = G.g[i][0]; if ((int)G.g[i].size() > upperBound) dQ[dQ2++] = i; } bool fr = true; vector<pair<int, int> > remd; while (dQ1 < dQ2 || fr) { fr = false; while (dQ1 < dQ2) { while (dQ1 < dQ2) { int x = dQ[dQ1++]; if (G.g[x].size() == 0) continue; if (upperBound == 0) { G.addEdges(remd); return false; } sol.push_back(x); G.remIncident(x, remd); assert(G.g[x].size() == 0); upperBound--; } for (int i = 0; i < G.n; i++) { if (G.g[i].size() == 1) dQ[dQ2++] = G.g[i][0]; if ((int)G.g[i].size() > upperBound) dQ[dQ2++] = i; } } auto LPV = LPVC(G); if (LPV.F > 2*upperBound) { G.addEdges(remd); return false; } assert((int)LPV.S.size() <= upperBound); for (int x : LPV.S) { sol.push_back(x); assert(G.g[x].size() > 0); G.remIncident(x, remd); assert(G.g[x].size() == 0); upperBound--; } assert(upperBound >= 0); for (int i = 0; i < G.n; i++) { if (G.g[i].size() == 1) dQ[dQ2++] = G.g[i][0]; if ((int)G.g[i].size() > upperBound) dQ[dQ2++] = i; } } if (G.m == 0) { G.addEdges(remd); return true; } if (upperBound == 0) { G.addEdges(remd); return false; } assert(upperBound > 0); int maxD = 0; int maxDx = -1; int fo = 0; for (int i = 0; i < G.n; i++) { assert(G.g[i].size() != 1); if ((int)G.g[i].size() > maxD) { maxD = G.g[i].size(); maxDx = i; } if ((int)G.g[i].size() > 0) fo++; } assert(maxD <= upperBound); assert(maxD > 0); if (maxD == 2) { fill(uu, uu + G.n, 0); for (int i = 0; i < G.n; i++) { if (uu[i] == 0 && G.g[i].size() > 0) { int sz = dfs(G, i); assert(sz >= 3); upperBound -= (sz+1)/2; if (upperBound < 0) { G.addEdges(remd); return false; } } } for (int i = 0; i < G.n; i++) { if (uu[i] == 1) { assert(G.g[i].size() == 2); int sz = 0; int x = i; while (uu[x] == 1) { sz++; if (sz%2 == 1) { sol.push_back(x); } uu[x] = 2; for (int nx : G.g[x]) { if (uu[nx] == 1) { x = nx; break; } } } } } G.addEdges(remd); return true; } assert(maxD >= 3); vector<int> nb = G.g[maxDx]; vector<pair<int, int> > co1; memset(u, 0, sizeof(int)*G.n); for (int i = 0; i < G.n; i++) { if (G.g[i].size() > 0) { getCC(G, i, co1); assert(co1.size() > 0); break; } } assert((int)co1.size() <= G.m); if ((int)co1.size() < G.m || G.m*2 < G.n) { vector<vector<pair<int, int> > > cos = {co1}; for (int i = 0; i < G.n; i++) { if (G.g[i].size() > 0 && !u[i]) { cos.push_back(vector<pair<int, int> >()); getCC(G, i, cos.back()); assert(cos.back().size() > 0); } } G.addEdges(remd); vector<int> soltt; for (auto& co : cos) { Graph CC(co); vector<int> solt; bool s = optSolve(CC, upperBound - (int)soltt.size(), solt); if (!s) return false; solt = CC.mapBack(solt); soltt.insert(soltt.end(), solt.begin(), solt.end()); } sol.insert(sol.end(), soltt.begin(), soltt.end()); assert((int)soltt.size() <= upperBound); return true; } vector<int> sol1; G.remIncident(maxDx, remd); sol1.push_back(maxDx); bool s1 = optSolve(G, upperBound - (int)sol1.size(), sol1); if (s1) { assert((int)sol1.size() <= upperBound); upperBound = (int)sol1.size()-1; } vector<int> sol2; for (int x : nb) { sol2.push_back(x); G.remIncident(x, remd); } bool s2 = optSolve(G, upperBound - (int)sol2.size(), sol2); G.addEdges(remd); if (s2) { if (s1) assert(sol2.size() < sol1.size()); sol.insert(sol.end(), sol2.begin(), sol2.end()); return true; } else if (s1) { sol.insert(sol.end(), sol1.begin(), sol1.end()); return true; } else{ return false; } } vector<int> exactSol(const Graph& G) { if (G.m == 0) return {}; VCtimer.start(); vector<int> solv; Graph GG = G; bool ok = optSolve(GG, G.n-1, solv); assert(ok); VCtimer.stop(); return solv; } double getTimeUsed() { return VCtimer.getTime().count(); } }
20.160465
85
0.484139
manighahrmani
e3232cb7da6a0da1723a513c5499943d2cb043e1
1,277
hpp
C++
include/meevax/kernel/stack.hpp
yamacir-kit/meevax
ff9449a16380eac727c914a33449e9b3a7597b8e
[ "Apache-2.0" ]
13
2018-11-27T02:06:58.000Z
2022-01-01T16:07:12.000Z
include/meevax/kernel/stack.hpp
yamacir-kit/meevax
ff9449a16380eac727c914a33449e9b3a7597b8e
[ "Apache-2.0" ]
89
2017-11-24T23:58:06.000Z
2022-02-06T14:54:01.000Z
include/meevax/kernel/stack.hpp
yamacir-kit/meevax
ff9449a16380eac727c914a33449e9b3a7597b8e
[ "Apache-2.0" ]
4
2017-12-22T15:45:46.000Z
2020-01-12T19:50:45.000Z
/* Copyright 2018-2021 Tatsuya Yamasaki. 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. */ #ifndef INCLUDED_MEEVAX_KERNEL_STACK_HPP #define INCLUDED_MEEVAX_KERNEL_STACK_HPP #include <meevax/kernel/list.hpp> namespace meevax { inline namespace kernel { template <typename T, typename... Ts> auto push(T&& stack, Ts&&... xs) -> decltype(auto) { return stack = cons(std::forward<decltype(xs)>(xs)..., stack); } template <std::size_t N, typename T> auto pop(T&& stack) -> decltype(auto) { return stack = std::next(std::begin(stack), N); } template <typename T> auto pop(T&& stack) { let const x = car(stack); pop<1>(stack); return x; } } // namespace kernel } // namespace meevax #endif // INCLUDED_MEEVAX_KERNEL_STACK_HPP
26.061224
75
0.703994
yamacir-kit
e326c9f13c30636263244c06e30fc48f88dbb966
1,716
cpp
C++
dialog.cpp
mguludag/QtIFW_Frontend
1f670e4e633ed5fc92412d523a7365c6b16ade58
[ "BSL-1.0" ]
11
2020-12-28T13:53:16.000Z
2022-03-29T04:19:32.000Z
dialog.cpp
mguludag/QtIFW_Frontend
1f670e4e633ed5fc92412d523a7365c6b16ade58
[ "BSL-1.0" ]
null
null
null
dialog.cpp
mguludag/QtIFW_Frontend
1f670e4e633ed5fc92412d523a7365c6b16ade58
[ "BSL-1.0" ]
1
2020-12-28T13:53:24.000Z
2020-12-28T13:53:24.000Z
/***************************************************************************** * dialog.cpp * * Created: 12/20/2020 2020 by mguludag * * Copyright 2020 mguludag. All rights reserved. * * This file may be distributed under the terms of GNU Public License version * 3 (GPL v3) as defined by the Free Software Foundation (FSF). A copy of the * license should have been included with this file, or the project in which * this file belongs to. You may also find the details of GPL v3 at: * http://www.gnu.org/licenses/gpl-3.0.txt * * If you have any questions regarding the use of this file, feel free to * contact the author of this file, or the owner of the project in which * this file belongs to. *****************************************************************************/ #include "dialog.hpp" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); Settings::init(Settings::Format::iniFormat, "settings.ini"); ui->lineEdit_qtbinpath->setText( Settings::readSettings("Qt_IFW_Bins", "Path").toString()); ifw_path = ui->lineEdit_qtbinpath->text(); } Dialog::~Dialog() { delete ui; } void Dialog::on_buttonBox_accepted() { Settings::writeSettings("Qt_IFW_Bins", "Path", ui->lineEdit_qtbinpath->text()); } QString Dialog::getIfw_path() const { return ifw_path; } void Dialog::on_toolButton_qtifw_clicked() { ui->lineEdit_qtbinpath->setText(QFileDialog::getExistingDirectory( this, tr("Open Qt Bin Directory"), QDir::rootPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks)); ifw_path = ui->lineEdit_qtbinpath->text(); }
39
80
0.626457
mguludag
e327f8aaa69d6be9637dd6975423007026dd67e8
59
cpp
C++
src/base/shape.cpp
wzhhh123/SimpleRT
e2ff1a2773eecbc388568fdc2b5c20ead45d262d
[ "Apache-2.0" ]
null
null
null
src/base/shape.cpp
wzhhh123/SimpleRT
e2ff1a2773eecbc388568fdc2b5c20ead45d262d
[ "Apache-2.0" ]
null
null
null
src/base/shape.cpp
wzhhh123/SimpleRT
e2ff1a2773eecbc388568fdc2b5c20ead45d262d
[ "Apache-2.0" ]
null
null
null
#include "shape.h" FLOAT Shape::Area() { return 0; }
6.555556
33
0.576271
wzhhh123
e32921ab796018ed3107d779fbe74a96a7df96b3
5,673
cpp
C++
src/stream_transformer_payload_to_payload.cpp
luibass92/mqttraffic-warden
a421b04aff99927e92f0bda4c0543af91abef6c5
[ "MIT" ]
null
null
null
src/stream_transformer_payload_to_payload.cpp
luibass92/mqttraffic-warden
a421b04aff99927e92f0bda4c0543af91abef6c5
[ "MIT" ]
null
null
null
src/stream_transformer_payload_to_payload.cpp
luibass92/mqttraffic-warden
a421b04aff99927e92f0bda4c0543af91abef6c5
[ "MIT" ]
null
null
null
#include "stream_transformer_payload_to_payload.h" #include <iostream> #include "cast.h" #include "exceptions.h" #include "json_utilities.h" #include "spdlog/spdlog.h" #include "utilities.h" namespace tw { void StreamTransformerPayloadToPayload::setup(const nlohmann::json& p_json) { if (!is_valid_setup(p_json)) { spdlog::error("{} has an invalid setup", get_class_name()); throw StreamTransformerSetupException(); } // mandatory fields m_transformation.fromPayload = p_json[k_from].get<std::string>(); m_transformation.toPayload = p_json[k_to].get<std::string>(); // optional fields if (p_json.contains(k_as)) { if (k_typeNumber == p_json[k_as].get<std::string>()) { m_transformation.asType = JsonType::Number; } else if (k_typeString == p_json[k_as].get<std::string>()) { m_transformation.asType = JsonType::String; } else if (k_typeBoolean == p_json[k_as].get<std::string>()) { m_transformation.asType = JsonType::Boolean; } else { spdlog::error( "{} '{}' key must have one of the " "following values: {}", get_class_name(), k_as, fmt::join(k_types, ", ")); throw StreamTransformerSetupException(); } } else { m_transformation.asType = JsonType::JsonTypeUnknown; } if (p_json.contains(k_keep)) { m_transformation.keep = p_json[k_keep].get<bool>(); } else { m_transformation.keep = false; } } void StreamTransformerPayloadToPayload::execute( const std::string&, const nlohmann::json& p_inputPayload, std::string&, nlohmann::json& p_outputPayload) { if (m_transformation.asType == JsonType::JsonTypeUnknown) { // No type conversion p_outputPayload[m_transformation.toPayload] = p_inputPayload.at(m_transformation.fromPayload); } else { // Type conversion std::string l_inputPayloadStr = ""; if (p_inputPayload.at(m_transformation.fromPayload).is_string()) { l_inputPayloadStr = p_inputPayload.at(m_transformation.fromPayload); } else { l_inputPayloadStr = utilities::dump_json(p_inputPayload.at(m_transformation.fromPayload)); } switch (m_transformation.asType) { case JsonType::Number: if (utilities::isInt(l_inputPayloadStr)) { p_outputPayload[m_transformation.toPayload] = utilities::lexical_cast<long>(l_inputPayloadStr.c_str()); } else if (utilities::isFloat(l_inputPayloadStr)) { p_outputPayload[m_transformation.toPayload] = utilities::lexical_cast<float>(l_inputPayloadStr.c_str()); } else if (utilities::isDouble(l_inputPayloadStr)) { p_outputPayload[m_transformation.toPayload] = utilities::lexical_cast<double>(l_inputPayloadStr.c_str()); } else { spdlog::error( "The input payload is expected to be a number (integer or " "float), instead it is: '{}'", l_inputPayloadStr); throw StreamTransformerExecutionException(); } break; case JsonType::String: p_outputPayload[m_transformation.toPayload] = l_inputPayloadStr; break; case JsonType::Boolean: if (utilities::isBool(l_inputPayloadStr)) { p_outputPayload[m_transformation.toPayload] = utilities::lexical_cast<bool>(l_inputPayloadStr.c_str()); } else { spdlog::error( "The input payload is expected to be a boolean, instead it is: " "'{}'", l_inputPayloadStr); throw StreamTransformerExecutionException(); } break; default: spdlog::error("{} '{}' value must be one of the following: {}", get_class_name(), k_as, fmt::join(k_types, ", ")); throw StreamTransformerExecutionException(); break; } } if (!m_transformation.keep) { // If 'keep' is false, the original payload key-value pair must be deleted p_outputPayload.erase(m_transformation.fromPayload); } } bool StreamTransformerPayloadToPayload::is_valid_setup( const nlohmann::json& p_json) { if (!p_json.is_object()) { spdlog::error("{} is not a JSON object", get_class_name()); return false; } // mandatory fields else if (!p_json.contains(k_from)) { spdlog::error("{} must contain a '{}' key", get_class_name(), k_from); return false; } else if (!p_json[k_from].is_string()) { spdlog::error("{} '{}' value must be a string", get_class_name(), k_from); return false; } else if (!p_json.contains(k_to)) { spdlog::error("{} must contain a '{}' key", get_class_name(), k_to); return false; } else if (!p_json[k_to].is_string()) { spdlog::error("{} '{}' value must be a string", get_class_name(), k_to); return false; } // optional fields else if (p_json.contains(k_as)) { if (!p_json[k_as].is_string()) { spdlog::error("{} '{}' value must be a string", get_class_name(), k_as); return false; } else if (std::none_of(k_types.begin(), k_types.end(), [&p_json](std::string it_type) { return it_type == p_json.at(k_as).get<std::string>(); })) { spdlog::error( "{} '{}' key must have one of the " "following values: {}", get_class_name(), k_as, fmt::join(k_types, ", ")); return false; } } else if (p_json.contains(k_keep) && !p_json[k_keep].is_boolean()) { spdlog::error("{} '{}' value must be a boolean", get_class_name(), k_keep); return false; } return true; } } // namespace tw
36.365385
80
0.624008
luibass92
e32967d92a125756460bf2a3ea5989ca1e3dba94
285
cpp
C++
beaker/decl.cpp
thehexia/beaker2
ca6c563c51be4a08d78e4eda007967bc4ae812a2
[ "Apache-2.0" ]
null
null
null
beaker/decl.cpp
thehexia/beaker2
ca6c563c51be4a08d78e4eda007967bc4ae812a2
[ "Apache-2.0" ]
null
null
null
beaker/decl.cpp
thehexia/beaker2
ca6c563c51be4a08d78e4eda007967bc4ae812a2
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2015 Andrew Sutton // All rights reserved #include "decl.hpp" #include "type.hpp" Function_type const* Function_decl::type() const { return cast<Function_type>(Decl::type()); } Type const* Function_decl::return_type() const { return type()->return_type(); }
13.571429
43
0.705263
thehexia
e32d0195642344abdc5e1f7144acfba601f3fb66
8,475
cc
C++
src/ActProdXSecData.cc
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
1
2020-11-04T08:32:23.000Z
2020-11-04T08:32:23.000Z
src/ActProdXSecData.cc
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
null
null
null
src/ActProdXSecData.cc
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
1
2020-11-04T08:32:30.000Z
2020-11-04T08:32:30.000Z
// Class for defining the production cross-section data for // a specific target isotope. It stores a map of ActXSecGraphs // for the target isotope. #include "Activia/ActProdXSecData.hh" #include "Activia/ActBeamSpectrum.hh" #include "Activia/ActProdNuclideList.hh" #include "Activia/ActProdNuclide.hh" #include "Activia/ActNucleiData.hh" #include "Activia/ActAbsXSecAlgorithm.hh" #include "Activia/ActConstants.hh" #include "Activia/ActNuclideFactory.hh" #include "Activia/ActGraphPoint.hh" #include "Activia/ActAbsOutput.hh" #include "Activia/ActOutputSelection.hh" #include "Activia/ActTargetNuclide.hh" #include "Activia/ActAbsCalcStatus.hh" #include <vector> #include <iostream> using std::cout; using std::endl; ActProdXSecData::ActProdXSecData(ActTargetNuclide* targetIsotope, ActProdNuclideList* prodList, ActBeamSpectrum* inputBeam, ActAbsXSecAlgorithm* algorithm, ActAbsOutput* output) { // Constructor _targetIsotope = targetIsotope; _prodList = prodList; _inputBeam = inputBeam; _algorithm = algorithm; _xSecData.clear(); _output = output; } ActProdXSecData::~ActProdXSecData() { // Destructor _xSecData.clear(); } void ActProdXSecData::calculate() { // Calculate the target isotope - product cross-sections given the input beam // and calculation algorithm // Check for null pointers if (_prodList == 0 || _targetIsotope == 0) {return;} if (_inputBeam == 0 || _algorithm == 0) {return;} _xSecData.clear(); double EStart = _inputBeam->getEStart(); double dE = _inputBeam->getdE(); int nE = _inputBeam->getnE(); cout<<"E0 = "<<EStart<<", dE = "<<dE<<", nE = "<<nE<<endl; int nE1 = nE - 1; int nProducts = _prodList->getNProdNuclides(); int ip; // Create a nuclei data pointer that will store the beam, target and // product information, all in one object, that can be passed around // the various cross-section algorithm/models. ActNucleiData* data = new ActNucleiData(); ActNuclide* beamNuclide = _inputBeam->getNuclide(); data->setBeamData(beamNuclide); data->setTargetData(_targetIsotope); // Initialise the production rate normalisation factor double factor(0.0); double atgt = data->getat(); if (atgt > 1e-30) {factor = ActConstants::pps/atgt;} // Retrieve the abundance fraction for the selected target isotope. // This will be used to scale the production rate for all product isotopes. double fraction = data->getFraction(); // Load in any data tables for this target isotope // Use the list of product isotopes to store maps of // target-product tables. _algorithm->loadDataTables(_targetIsotope, _prodList); // Store energies in vector (same for all products) std::vector<double> energies; int iE; for (iE = 0; iE < nE; iE++) { double energy = iE*dE + EStart; energies.push_back(energy); } int levelOfDetail(0); bool outputEGraphs = false; if (_output != 0) { levelOfDetail = _output->getLevelOfDetail(); if (levelOfDetail > ActOutputSelection::Summary) {outputEGraphs = true;} } // Calculation status ActAbsCalcStatus* calcStatus = _output->getCalcStatus(); if (calcStatus != 0) {calcStatus->setNProductIsotopes(nProducts);} bool runCode(true); // calculation status can say "stop calculating" // Loop over products for (ip = 0; ip < nProducts; ip++) { cout<<"ActProdXSecData ip = "<<ip<<endl; // Set calculation status (if it exists) if (calcStatus != 0) { calcStatus->setProductIsotope(ip); calcStatus->xSecReport(); runCode = calcStatus->canRunCode(); } // Stop calculation if requested by the status if (runCode == false) {break;} ActProdNuclide* prodNuclide = _prodList->getProdNuclide(ip); double zNucl(0.0), aNucl(0.0), halfLife(0.0); int nSideBranches(0); if (prodNuclide != 0) { zNucl = prodNuclide->getfZ(); aNucl = prodNuclide->getA(); nSideBranches = prodNuclide->getNSideBranches(); halfLife = prodNuclide->getHalfLife(); } // Set the product data and check if we pass the selection criteria // for the beam, target and product set-up. data->setProductData(prodNuclide); if (_algorithm->passSelection(data) == false) { // We have failed the selection. // Continue to the next product within the (ip) loop. continue; } // Define the vector of graph points for the product nuclide. std::vector<ActGraphPoint> prodGraphPoints(nE); for (iE = 0; iE < nE; iE++) { prodGraphPoints[iE] = ActGraphPoint(energies[iE], 0.0, 0.0); } // Total sigma and production rate for the product (including side branches) double totalProdSigma(0.0), totalProdRate(0.0); // Loop over side branches, as well as the product isotope int iSB; for (iSB = 0; iSB < nSideBranches+1; iSB++) { // Total sigma and production rate for the individual side branches double totalSBSigma(0.0), totalSBProdRate(0.0); bool doCalc(true); bool sideBranch(false); double z(zNucl), a(aNucl), tHalf(halfLife); if (iSB != nSideBranches) { // We have a side-branch. ActNuclide* sbNuclide = prodNuclide->getSideBranch(iSB); if (sbNuclide != 0) { z = sbNuclide->getfZ(); a = sbNuclide->getA(); tHalf = 0.0; sideBranch = true; // Reset the product data to use the side-branch isotope. data->setProductData(sbNuclide); // Check whether the side-branch, together with the beam and target data, // passes the selection criteria. Set the doCalc flag using this check. doCalc = _algorithm->passSelection(data); } else { // sbNuclide pointer is null. Skip to the next in the loop. doCalc = false; } } else if (nSideBranches > 0) { // Reset the product data to the original product isotope data->setProductData(prodNuclide); } // Skip nuclide if earlier selections have failed if (doCalc == false) {continue;} // Also calculate the threshold energy and other quantities, since we now // have the target and product parameters data->setOtherQuantities(); // Set the nuclei data that the algorithm will use // Since the data is a pointer, this can be updated and the algorithm // will automatically know about the changes. _algorithm->setNucleiData(data); // Loop over the energy range, calculating the cross section value // and storing them in the graph. for (iE = 0; iE < nE; iE++) { double pfac(1.0); if (iE == 0 || iE == nE1) {pfac = 0.5;} double energy = energies[iE]; data->setEnergy(energy); bool passESelection = _algorithm->passESelection(data); if (passESelection == true) { // Calculate the cross-section based on the previously // given nuclei data pointer double sigma = _algorithm->calcCrossSection(); double dNdE = _inputBeam->fluxdE(energy); double prodRate = pfac*sigma*factor*fraction*dNdE*dE; totalSBSigma += sigma; totalSBProdRate += prodRate; totalProdSigma += sigma; totalProdRate += prodRate; // Also store the sigma and production rate vs energy // graph for the side branch/product isotope prodGraphPoints[iE].addYValues(sigma, prodRate); } // energy selection } // energy loop // Finished looping over all side branches. Store the side-branch summed // sigma/production rate vs energy for the product nuclide using graphs. ActNuclide* isotope = ActNuclideFactory::getInstance()->getNuclide((int) z, a, tHalf); // Only store the total sigma/production rate to save on RAM memory use! ActXSecGraph xSecGraph("xSecGraph"); if (sideBranch == true) { // Only store the total sigma/production rate xSecGraph.addPoint(0.0, totalSBSigma, totalSBProdRate); } else { // Store total sigma/production rate xSecGraph.addPoint(0.0, totalProdSigma, totalProdRate); // Print out sigma/production rate as function of energy to output class ActXSecGraph xSecEGraph("xSecEData"); xSecEGraph.addPoints(prodGraphPoints); if (outputEGraphs == true) { _output->outputGraph(*data, xSecEGraph); } } // Insert the graphs into the internal map for the given product nuclide //cout<<"Inserting cross-section and production rate vs energy graph into map"<<endl; _xSecData[isotope] = xSecGraph; } // side branch plus product loop } // product loop cout<<"Finished in ActProdXSecData"<<endl; delete data; }
30.706522
92
0.688732
UniversityofWarwick
e3326e1d70ba23df0af2595682eeb96335c58dd9
1,145
cpp
C++
tests/benchmark/src/main.cpp
typesAreSpaces/AXDInterpolator
e0759c806480ff54b7a4f878e007b534a71dad44
[ "MIT" ]
null
null
null
tests/benchmark/src/main.cpp
typesAreSpaces/AXDInterpolator
e0759c806480ff54b7a4f878e007b534a71dad44
[ "MIT" ]
1
2021-06-24T18:55:46.000Z
2021-06-24T18:55:46.000Z
tests/benchmark/src/main.cpp
typesAreSpaces/AXDInterpolator
e0759c806480ff54b7a4f878e007b534a71dad44
[ "MIT" ]
null
null
null
#include "UAutomizerFileReader.h" #include <sys/stat.h> inline bool exists_file (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } int main(int argc, char * argv[]){ if(argc != 6){ std::cerr << "Invalid number of inputs.\n"; return 0; } // argv[1] -> file path of smt file // argv[2] -> Solver Code // argv[3] -> file path of output file // argv[4] -> '0' -> test implementation // '1' -> test other interpolation engines char const * file = argv[1]; if(!exists_file(file)){ std::cout << argv[1] << std::endl; std::cerr << "File doesnt exists.\n"; return 0; } SMT_SOLVER curr_solver; switch(*argv[2]){ case '0': curr_solver = Z3; break; case '1': curr_solver = MATHSAT; break; case '2': curr_solver = SMTINTERPOL; break; default: curr_solver = MATHSAT; break; } UAutomizerFileReader reader( curr_solver, 500, argv[3], *argv[4] == '0', *argv[5] == '0'); #if SINGLE_FORMULA reader.processSingleFile(file); #else reader.process(file); #endif return 0; }
20.818182
67
0.583406
typesAreSpaces
e33317d73edf89d40fd046ce25f1f608f05a5438
2,754
cpp
C++
Board.cpp
ahmadabed1/messageboard-b
05b154801690250737f56a31b71359ae71c0cdbb
[ "MIT" ]
null
null
null
Board.cpp
ahmadabed1/messageboard-b
05b154801690250737f56a31b71359ae71c0cdbb
[ "MIT" ]
null
null
null
Board.cpp
ahmadabed1/messageboard-b
05b154801690250737f56a31b71359ae71c0cdbb
[ "MIT" ]
null
null
null
#include <iostream> #include "Board.hpp" using namespace std; using namespace ariel; const char defaultChar = '_'; namespace ariel { void Board::update(unsigned int row, unsigned int col, bool flag, unsigned int num){ if(this->maxR!=0 || this->minR!=INT32_MAX || this->maxC!=0 || this->minC!=INT32_MAX){ this->minC=min(this->minC, col); this->minR=min(this->minR, row); if(!flag){ this->maxC=max(this->maxC, col+1); this->maxR=max(this->maxR, row+num+1); } else{ this->maxC= max(this->maxC, col+num+1); this->maxR=max(this->maxR, row+1); } resizeBoard(this->maxR, this->maxC); } else{ if (!flag){ this->maxR=row+num; this->maxC=col+1; this->minR=row; this->minC=col; } else{ this->maxR=row+1; this->maxC=col+num; this->minR=row; this->minC=col; } resizeBoard(this->maxR, this->maxC); } } /* resize boeard */ void Board::resizeBoard(unsigned int row, unsigned int col){ this-> board.resize(row); for(unsigned int i=0; i < row; i++){ board.at(i).resize(col,defaultChar); } } /* write message to the board */ void Board::post(unsigned int row, unsigned int col, Direction d, string const &message){ unsigned int messageSize = message.length(); bool flag = (d == Direction::Horizontal); update(row,col,flag,messageSize); for (char ch: message){ board.at(row).at(col) = ch; flag? col++ : row++; } } /* read messages from board */ string Board::read(unsigned int row, unsigned int col, Direction d, unsigned int num){ string s; bool flag = (d == Direction::Horizontal); for(int i=0; i<num; i++){ try { s+=board.at(row).at(col); } catch(const std::exception& e) { s+="_"; } flag? col++ : row++; } return s; } /* print the board */ void Board::show(){ for (unsigned int i = this->minR; i < this->maxR; i++) { cout << i << ": "; for (unsigned int j = this->minC; j < this->maxC; j++) { cout << this->board[i][j]; } cout<< "\n"; } cout << "\n" << endl; } }
23.142857
93
0.439361
ahmadabed1
e3350eedf98cd11ade84d8706ee7ac6f3ac32187
346
cpp
C++
5659.删除字符串两端相同字符后的最短长度/minimumLength.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2019-10-21T14:40:39.000Z
2019-10-21T14:40:39.000Z
5659.删除字符串两端相同字符后的最短长度/minimumLength.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
null
null
null
5659.删除字符串两端相同字符后的最短长度/minimumLength.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2020-11-04T07:33:34.000Z
2020-11-04T07:33:34.000Z
class Solution { public: int minimumLength(string s) { int l = 0, r = s.size() - 1; while(l < r) { if(s[l]!=s[r]) break; while(l<r-1 && s[l+1]==s[r])l++; while(r>l+1 && s[r-1]==s[l])r--; if(r-l+1>=2&&l<s.size()-1){l++;r--;} } return r-l+1; } };
21.625
48
0.358382
YichengZhong
e337577a783f4092f5d786c771233083f63ddc04
1,316
hpp
C++
src/time_advance.hpp
ckendrick/asgard
ed4fc90d240466e9ca0473071e8f64f84ad14462
[ "MIT" ]
null
null
null
src/time_advance.hpp
ckendrick/asgard
ed4fc90d240466e9ca0473071e8f64f84ad14462
[ "MIT" ]
null
null
null
src/time_advance.hpp
ckendrick/asgard
ed4fc90d240466e9ca0473071e8f64f84ad14462
[ "MIT" ]
null
null
null
#pragma once #include "batch.hpp" #include "boundary_conditions.hpp" #include "distribution.hpp" #include "kronmult.hpp" #include "program_options.hpp" #include "tensors.hpp" #include "timer.hpp" #include <mutex> // this function executes a time step using the current solution // vector x (in host_space). // on exit, the next solution vector is stored in x. template<typename P> fk::vector<P> explicit_time_advance(PDE<P> const &pde, elements::table const &table, options const &program_opts, std::vector<fk::vector<P>> const &unscaled_sources, std::array<unscaled_bc_parts<P>, 2> const &unscaled_parts, fk::vector<P> const &x, distribution_plan const &plan, int const workspace_size_MB, P const time); template<typename P> fk::vector<P> implicit_time_advance(PDE<P> const &pde, elements::table const &table, std::vector<fk::vector<P>> const &unscaled_sources, std::array<unscaled_bc_parts<P>, 2> const &unscaled_parts, fk::vector<P> const &x, distribution_plan const &plan, P const time, solve_opts const solver = solve_opts::direct, bool const update_system = true);
41.125
80
0.6231
ckendrick
e3393fcf86a950ee192dfa381e4be20d3f3dfb74
55
hpp
C++
misc/tower.hpp
reubn/symfonisk
559ae842a159734ab5f1dc33b80a394577b3b576
[ "MIT" ]
1
2020-05-14T20:52:56.000Z
2020-05-14T20:52:56.000Z
misc/tower.hpp
reubn/symfonisk
559ae842a159734ab5f1dc33b80a394577b3b576
[ "MIT" ]
null
null
null
misc/tower.hpp
reubn/symfonisk
559ae842a159734ab5f1dc33b80a394577b3b576
[ "MIT" ]
null
null
null
extern void loopTower(ConfigurableSettings& settings);
27.5
54
0.854545
reubn
e34857efb9134554d767f7548f519dbb3a161ba2
8,179
cpp
C++
src/main.cpp
ak1211/m5stack-azure-iot
179a474acde159c689ab359dba804c886402794a
[ "MIT" ]
null
null
null
src/main.cpp
ak1211/m5stack-azure-iot
179a474acde159c689ab359dba804c886402794a
[ "MIT" ]
null
null
null
src/main.cpp
ak1211/m5stack-azure-iot
179a474acde159c689ab359dba804c886402794a
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Akihiro Yamamoto. // Licensed under the MIT License <https://spdx.org/licenses/MIT.html> // See LICENSE file in the project root for full license information. // #include "credentials.h" #include "iothub_client.hpp" #include "peripherals.hpp" #include <ArduinoOTA.h> #include <M5Core2.h> #include <Wifi.h> #include <ctime> #include <lwip/apps/sntp.h> #include <LovyanGFX.hpp> constexpr static const char *TAG = "MainModule"; // // globals // constexpr static uint8_t IOTHUB_PUSH_MESSAGE_EVERY_MINUTES = 1; // 1 mimutes static_assert(IOTHUB_PUSH_MESSAGE_EVERY_MINUTES < 60, "IOTHUB_PUSH_MESSAGE_EVERY_MINUTES is lesser than 60 minutes."); constexpr static uint8_t IOTHUB_PUSH_STATE_EVERY_MINUTES = 15; // 15 minutes static_assert(IOTHUB_PUSH_STATE_EVERY_MINUTES < 60, "IOTHUB_PUSH_STATE_EVERY_MINUTES is lesser than 60 minutes."); // // callbacks // // void btnAEvent(Event &e) { Peripherals &peri = Peripherals::getInstance(); peri.screen.prev(); peri.screen.update(peri.ticktack.time()); } // void btnBEvent(Event &e) { Peripherals &peri = Peripherals::getInstance(); peri.screen.home(); peri.screen.update(peri.ticktack.time()); } // void btnCEvent(Event &e) { Peripherals &peri = Peripherals::getInstance(); peri.screen.next(); peri.screen.update(peri.ticktack.time()); } // void releaseEvent(Event &e) { Peripherals &peri = Peripherals::getInstance(); peri.screen.releaseEvent(e); } // // // void setup() { // // initializing M5Stack and UART, I2C, Touch, RTC, etc. peripherals. // M5.begin(true, true, true, true); Peripherals::begin(Credentials.wifi_ssid, Credentials.wifi_password, Credentials.connection_string); Peripherals &peri = Peripherals::getInstance(); // // register the button hook // M5.BtnA.addHandler(btnAEvent, E_RELEASE); M5.BtnB.addHandler(btnBEvent, E_RELEASE); M5.BtnC.addHandler(btnCEvent, E_RELEASE); M5.background.addHandler(releaseEvent, E_RELEASE); // // start up // peri.screen.repaint(peri.ticktack.time()); } // // // struct MeasurementSets { std::time_t measured_at; Bme280 bme280; Sgp30 sgp30; Scd30 scd30; }; static struct MeasurementSets periodical_measurement_sets(std::time_t measured_at) { Peripherals &peri = Peripherals::getInstance(); if (peri.bme280.readyToRead(measured_at)) { peri.bme280.read(measured_at); } if (peri.sgp30.readyToRead(measured_at)) { peri.sgp30.read(measured_at); } if (peri.scd30.readyToRead(measured_at)) { peri.scd30.read(measured_at); } return {.measured_at = measured_at, .bme280 = peri.bme280.calculateSMA(measured_at), .sgp30 = peri.sgp30.calculateSMA(measured_at), .scd30 = peri.scd30.calculateSMA(measured_at)}; } // // // static std::string & absolute_sensor_id_from_SensorDescriptor(std::string &output, SensorDescriptor descriptor) { std::string strDescriptor; descriptor.toString(strDescriptor); // output = Credentials.device_id; output.push_back('-'); output += strDescriptor; return output; } // // // static void periodical_push_message(const MeasurementSets &m) { Peripherals &peri = Peripherals::getInstance(); // BME280 sensor values. // Temperature, Relative Humidity, Pressure if (m.bme280.good()) { TempHumiPres temp_humi_pres = m.bme280.get(); // // calculate the Aboslute Humidity from Temperature and Relative Humidity MilligramPerCubicMetre absolute_humidity = calculateAbsoluteHumidity( temp_humi_pres.temperature, temp_humi_pres.relative_humidity); ESP_LOGI(TAG, "absolute humidity: %d", absolute_humidity.value); // set "Absolute Humidity" to the SGP30 sensor. if (!peri.sgp30.setHumidity(absolute_humidity)) { ESP_LOGE(TAG, "setHumidity error."); } std::string sensor_id; absolute_sensor_id_from_SensorDescriptor(sensor_id, temp_humi_pres.sensor_descriptor); if (peri.iothub_client.pushTempHumiPres(sensor_id, temp_humi_pres)) { ESP_LOGD(TAG, "pushTempHumiPres() success."); } else { ESP_LOGE(TAG, "pushTempHumiPres() failure."); peri.iothub_client.check(false); } } // SGP30 sensor values. // eCo2, TVOC if (m.sgp30.good()) { TvocEco2 tvoc_eco2 = m.sgp30.get(); std::string sensor_id; absolute_sensor_id_from_SensorDescriptor(sensor_id, tvoc_eco2.sensor_descriptor); if (peri.iothub_client.pushTvocEco2(sensor_id, tvoc_eco2)) { ESP_LOGD(TAG, "pushTvocEco2() success."); } else { ESP_LOGE(TAG, "pushTvocEco2() failure."); peri.iothub_client.check(false); } } // SCD30 sensor values. // co2, Temperature, Relative Humidity if (m.scd30.good()) { Co2TempHumi co2_temp_humi = m.scd30.get(); std::string sensor_id; absolute_sensor_id_from_SensorDescriptor(sensor_id, co2_temp_humi.sensor_descriptor); if (peri.iothub_client.pushCo2TempHumi(sensor_id, co2_temp_humi)) { ESP_LOGD(TAG, "pushCo2TempHumi() success."); } else { ESP_LOGE(TAG, "pushCo2TempHumi() failure."); peri.iothub_client.check(false); } } } // // // static void periodical_push_state() { Peripherals &peri = Peripherals::getInstance(); if (peri.system_power.needToUpdate()) { peri.system_power.update(); } DynamicJsonDocument json(IotHubClient::MESSAGE_MAX_LEN); if (json.capacity() == 0) { ESP_LOGE(TAG, "memory allocation error."); return; } char buf[10] = {'\0'}; snprintf(buf, 10, "%d%%", static_cast<int>(peri.system_power.getBatteryPercentage())); json["batteryLevel"] = buf; uint32_t upseconds = peri.ticktack.uptimeSeconds(); json["uptime"] = upseconds; if (peri.iothub_client.pushState(json)) { ESP_LOGD(TAG, "pushState() success."); } else { ESP_LOGE(TAG, "pushState() failure."); peri.iothub_client.check(false); } } // // // static void periodical_send_to_iothub(const MeasurementSets &m) { struct tm utc; gmtime_r(&m.measured_at, &utc); // bool allowToPushMessage = utc.tm_sec == 0 && utc.tm_min % IOTHUB_PUSH_MESSAGE_EVERY_MINUTES == 0; bool allowToPushState = utc.tm_sec == 0 && utc.tm_min % IOTHUB_PUSH_STATE_EVERY_MINUTES == 0; Peripherals &peri = Peripherals::getInstance(); // if (peri.wifi_launcher.hasWifiConnection()) { // // send to IoT Hub // if (allowToPushMessage) { periodical_push_message(m); } if (allowToPushState) { periodical_push_state(); } } // if (allowToPushMessage) { // // insert to local logging file // if (m.bme280.good() && m.sgp30.good() && m.scd30.good()) { peri.data_logging_file.write_data_to_log_file( m.measured_at, m.bme280.get(), m.sgp30.get(), m.scd30.get()); } // // insert to local database // if (m.bme280.good()) { peri.local_database.insert(m.bme280.get()); } if (m.sgp30.good()) { peri.local_database.insert(m.sgp30.get()); } if (m.scd30.good()) { peri.local_database.insert(m.scd30.get()); } } } // // // void loop() { ArduinoOTA.handle(); delay(1); Peripherals &peri = Peripherals::getInstance(); if (peri.wifi_launcher.hasWifiConnection()) { peri.iothub_client.check(true); } static clock_t before_clock = 0; clock_t now_clock = clock(); if ((now_clock - before_clock) >= CLOCKS_PER_SEC) { peri.ticktack.update(); MeasurementSets m = periodical_measurement_sets(peri.ticktack.time()); peri.screen.update(m.measured_at); if (m.scd30.good()) { Ppm co2 = m.scd30.get().co2; peri.led_signal.showSignal(co2); } periodical_send_to_iothub(m); before_clock = now_clock; } M5.update(); }
28.106529
80
0.643477
ak1211
e358559a3caa8d098753bf701165bc2bc379231c
1,250
cpp
C++
BinarySearchTree/BinarySearchTree/BinarySearchTree.cpp
epoll31/DataStructuresCpp
bfd93bad226bb5175d6b74f8dd9beb60150bb055
[ "MIT" ]
null
null
null
BinarySearchTree/BinarySearchTree/BinarySearchTree.cpp
epoll31/DataStructuresCpp
bfd93bad226bb5175d6b74f8dd9beb60150bb055
[ "MIT" ]
null
null
null
BinarySearchTree/BinarySearchTree/BinarySearchTree.cpp
epoll31/DataStructuresCpp
bfd93bad226bb5175d6b74f8dd9beb60150bb055
[ "MIT" ]
null
null
null
#include <iostream> #include "BinarySearchTree.h" #include <vector> int main() { BinarySearchTree<int> tree; //tree.Add(4); //tree.Add(2); //tree.Add(6); //tree.Add(1); //tree.Add(3); //tree.Add(5); //tree.Add(7); tree.Add(25); tree.Add(15); tree.Add(50); tree.Add(10); tree.Add(22); tree.Add(35); tree.Add(70); tree.Add(4); tree.Add(12); tree.Add(18); tree.Add(24); tree.Add(31); tree.Add(44); tree.Add(66); tree.Add(90); std::vector<Node<int>*> preorder = tree.DepthFirstTraversalPreOrder(); for (auto i = preorder.begin(); i < preorder.end(); i++) { std::cout << (*i)->Value << " "; } std::cout << std::endl; std::vector<Node<int>*> inorder = tree.DepthFirstTraversalInOrder(); for (auto i = inorder.begin(); i < inorder.end(); i++) { std::cout << (*i)->Value << " "; } std::cout << std::endl; std::vector<Node<int>*> postorder = tree.DepthFirstTraversalPostOrder(); for (auto i = postorder.begin(); i < postorder.end(); i++) { std::cout << (*i)->Value << " "; } std::cout << std::endl; std::vector<Node<int>*> breadthfirst = tree.BreadthFirstTraversal(); for (auto i = breadthfirst.begin(); i < breadthfirst.end(); i++) { std::cout << (*i)->Value << " "; } std::cout << std::endl; }
19.230769
73
0.5936
epoll31
e3616c347f069bbae2093bca66d1b14e91cd1a34
565
cpp
C++
396.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
396.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
396.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
// // Created by pzz on 2022/4/22. // #include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { public: int maxRotateFunction(vector<int> &nums) { int n = nums.size(); int numSum = 0, f = 0; for (int i = 0; i < n; i++) { numSum += nums[i]; f += i * nums[i]; } int res = f; for (int i = 1; i < n; i++) { f += numSum - n * nums[n - i]; res = max(res, f); } return res; } }; int main() { return 0; }
17.121212
46
0.446018
pengzhezhe
e36299db653d094110285453e6f864c66fdce7fa
510
cpp
C++
usage/cl_11_array_no_exception_of_out_index.cpp
conncui/CProject
f2786e8cfad1b590154af9167cbc218332e4e71f
[ "Apache-2.0" ]
null
null
null
usage/cl_11_array_no_exception_of_out_index.cpp
conncui/CProject
f2786e8cfad1b590154af9167cbc218332e4e71f
[ "Apache-2.0" ]
null
null
null
usage/cl_11_array_no_exception_of_out_index.cpp
conncui/CProject
f2786e8cfad1b590154af9167cbc218332e4e71f
[ "Apache-2.0" ]
null
null
null
# include <iostream> using namespace std; void test_1(); void test_2(); int main() { // test_1(); test_2(); } void test_1(){ int a[2]; a[0] = 1; a[1] = 2; int i = 2; a[i] = 10; for (int i = 0; i <=2; i++){ cout << a[i] << " "; } cout << endl; for (int i = 0; i <=2; i++){ cout << &a[i] << " "; } } void test_2() { double d[3] = {0, 1, 2}; double dd = 9; int index = 3; d[index] = 0; std::cout << dd << std::endl; }
12.75
33
0.401961
conncui
e365db498c6099afa4cad6311ab653c85460ca15
239
cpp
C++
chapter3/Proj325.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
chapter3/Proj325.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
chapter3/Proj325.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
#include<vector> #include<iostream> using namespace::std; int main() { vector<unsigned> v(11,0); unsigned score; auto it = v.begin(); while(cin>>score) ++*(it + score/10); for(auto &w:v) cout<<w<<" "; cout<<endl; return 0; }
14.058824
26
0.610879
basstal
e36cf94d6f0dfa569ccdf34744f802dd5b933c03
4,572
cpp
C++
src/multimedia/AudioOutObject.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
1
2016-03-26T13:25:08.000Z
2016-03-26T13:25:08.000Z
src/multimedia/AudioOutObject.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
src/multimedia/AudioOutObject.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
#include "AudioOutObject.h" #include "AudioOutObject_p.h" namespace Magna{ namespace MultiMedia{ AudioOutObject & AudioOutObject::getAudioOutObject(){ static AudioOutObject o; return o; } AudioOutObject::AudioOutObject() :m_data( new PrivateData( *this ) ){ } AudioOutObject::~AudioOutObject(){ } void AudioOutObject::setMuted ( bool mute ){ if( !m_data.isNull() ){ m_data->m_outputDevice->setMuted( mute ); } } void AudioOutObject::setVolume ( double newVolume ){ if( !m_data.isNull() ){ m_data->m_outputDevice->setVolume( newVolume ); } } void AudioOutObject::setCurAt( uint32 at){ if( !m_data.isNull() ){ auto &_data = *m_data; if( at < _data.m_URLs.size() ){ if( at != _data.m_cur ){ _data.m_cur = at; auto &_current_URL = _data.m_URLs.at( _data.m_cur ); #ifdef _MSC_VER QString _URL = QString::fromUtf16( reinterpret_cast<const ushort *>( _current_URL.c_str() ), _current_URL.size() ); #else QString _URL = QString::fromStdWString( _current_URL ); #endif _data.m_manipulatorObject->setCurrentSource( _URL ); } } } } void AudioOutObject::setCurrentSourceURL( const String&url){ if( !m_data.isNull() ){ m_data->m_cur = m_data->m_URLs.size(); m_data->m_URLs .push_back( url ); #ifdef _MSC_VER QString _URL = QString::fromUtf16( reinterpret_cast<const ushort *>( url.c_str() ), url.size() ); #else QString _URL = QString::fromStdWString( url ); #endif m_data->m_manipulatorObject->setCurrentSource( _URL ); } } bool AudioOutObject::isMuted() const{ bool _ret_muted = false; if( !m_data.isNull() ){ _ret_muted = m_data->m_outputDevice->isMuted(); } return _ret_muted; } void AudioOutObject::appendNextSourceURL( const String& url){ if( !m_data.isNull() ){ m_data->m_URLs .push_back( url ); } } void AudioOutObject::play(){ if( !m_data.isNull() ){ auto &_data = *m_data; if( !_data.m_URLs.empty() ){ if( _data.m_cur < _data.m_URLs.size() ){ auto &_current_URL = _data.m_URLs.at( _data.m_cur ); #ifdef _MSC_VER QString _URL = QString::fromUtf16( reinterpret_cast<const ushort *>( _current_URL.c_str() ), _current_URL.size() ); #else QString _URL = QString::fromStdWString( _current_URL ); #endif _data.m_manipulatorObject->setCurrentSource( _URL ); _data.m_manipulatorObject->play(); } } } } void AudioOutObject::pause(){ if( !m_data.isNull() ){ auto &_data = *m_data; _data.m_manipulatorObject->pause(); } } void AudioOutObject::stop(){ if( !m_data.isNull() ){ auto &_data = *m_data; _data.m_manipulatorObject->stop(); } } void AudioOutObject::playPrevious(){ if( !m_data.isNull() ){ auto &_data = *m_data; if( !_data.m_URLs.empty() ){ if( _data.m_cur > 0 ){ --_data.m_cur; auto &_current_URL = _data.m_URLs.at( _data.m_cur ); #ifdef _MSC_VER QString _URL = QString::fromUtf16( reinterpret_cast<const ushort *>( _current_URL.c_str() ), _current_URL.size() ); #else QString _URL = QString::fromStdWString( _current_URL ); #endif _data.m_manipulatorObject->setCurrentSource( _URL ); _data.m_manipulatorObject->play(); } } } } void AudioOutObject::playNext(){ if( !m_data.isNull() ){ auto &_data = *m_data; if( !_data.m_URLs.empty() ){ if( _data.m_cur < (_data.m_URLs.size() - 1) ){ ++_data.m_cur; auto &_current_URL = _data.m_URLs.at( _data.m_cur ); #ifdef _MSC_VER QString _URL = QString::fromUtf16( reinterpret_cast<const ushort *>( _current_URL.c_str() ), _current_URL.size() ); #else QString _URL = QString::fromStdWString( _current_URL ); #endif _data.m_manipulatorObject->setCurrentSource( _URL ); _data.m_manipulatorObject->play(); } } } } }//namespace MultiMedia }//namespace Magna
27.709091
129
0.554243
0of
e3717fa7cf16cda5b6a3b951c2a5298affb407ec
5,617
cpp
C++
src/generic_cubic_gadget/generic_cubic_gadget.cpp
AntoineRondelet/libsnark-playground
a67e20379decf42ae4b6189900ff0001e3936fc9
[ "MIT" ]
8
2018-08-31T08:51:30.000Z
2021-05-10T17:30:34.000Z
src/generic_cubic_gadget/generic_cubic_gadget.cpp
AntoineRondelet/libsnark-playground
a67e20379decf42ae4b6189900ff0001e3936fc9
[ "MIT" ]
1
2018-09-03T20:57:49.000Z
2018-09-03T20:57:49.000Z
src/generic_cubic_gadget/generic_cubic_gadget.cpp
AntoineRondelet/libsnark-playground
a67e20379decf42ae4b6189900ff0001e3936fc9
[ "MIT" ]
4
2018-08-31T08:51:33.000Z
2021-04-04T01:56:33.000Z
/* * While the "cubic_gadget" aims to provide a circuit for the statement: * (E) x**3 + x + 5 = 35 * This gadget ("generic_cubic_gagdet") is more generic, and provides a circuit for the statement: * (E') A*x**3 + B*x**2 + C*x + D = E * where, A, B, C, D, and E are fields elements of the field we are working on (FieldT) * * As a consequence, to use this gadget, one has to provide the coefficients: * A, B, C, D, and E as public input (primary input) * The sol_x being the secret solution that is used to generate a valid witness * will still remain as a private input (auxiliary input). * * The set of constraints encoding (E') becomes: * x1 = A * x0 * x2 = x1 * x0 * x3 = x2 * x0 * x4 = B * x0 * x5 = x4 * x0 * x6 = C * x0 * x7 = x6 + D * x8 = x5 + x3 * x9 = x8 + x7 * x9 = E * **/ #include <libsnark/gadgetlib1/gadget.hpp> #include "utils.hpp" /* * This gadget is made to prove the knowledge of x such that: * A*x**3 + B*x**2 + C*x + D = E, where A, B, C, D, and E are given as primary input **/ template<typename FieldT> class generic_cubic_gadget : public libsnark::gadget<FieldT> { public: libsnark::protoboard<FieldT> &pb; const std::string annotation_prefix=""; // Solution x that satisfies: (E') A*x**3 + B*x**2 + C*x + D = E (auxiliary input) const libsnark::pb_variable<FieldT> &sol_x; // Array that contains the values of the coefficients of the polynomial (along with E) const libsnark::pb_variable_array<FieldT> &coefficients; // X = [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9] variables allocated on the protoboard libsnark::pb_variable_array<FieldT> vars; generic_cubic_gadget( libsnark::protoboard<FieldT> &in_pb, const libsnark::pb_variable_array<FieldT> &in_coefficients, const libsnark::pb_variable<FieldT> &in_sol_x, const std::string &in_annotation_prefix="" ): libsnark::gadget<FieldT>(in_pb, FMT(in_annotation_prefix, " generic_cubic_equation")), pb(in_pb), sol_x(in_sol_x), coefficients(in_coefficients), vars(), annotation_prefix(in_annotation_prefix) { vars.allocate(pb, 10, FMT(this->annotation_prefix, " vars")); // size(X) = 10 (10 variables) } // Creates all constraints on the libsnark::protoboard void generate_r1cs_constraints() { // A * x0 = x1 libsnark::r1cs_constraint<FieldT> constraint1 = libsnark::r1cs_constraint<FieldT>( coefficients[0], vars[0], vars[1] ); // x1 * x0 = x2 libsnark::r1cs_constraint<FieldT> constraint2 = libsnark::r1cs_constraint<FieldT>( vars[1], vars[0], vars[2] ); // x2 * x0 = x3 libsnark::r1cs_constraint<FieldT> constraint3 = libsnark::r1cs_constraint<FieldT>( vars[2], vars[0], vars[3] ); // B * x0 = x4 libsnark::r1cs_constraint<FieldT> constraint4 = libsnark::r1cs_constraint<FieldT>( coefficients[1], vars[0], vars[4] ); // x4 * x0 = x5 libsnark::r1cs_constraint<FieldT> constraint5 = libsnark::r1cs_constraint<FieldT>( vars[4], vars[0], vars[5] ); // C * x0 = x6 libsnark::r1cs_constraint<FieldT> constraint6 = libsnark::r1cs_constraint<FieldT>( coefficients[2], vars[0], vars[6] ); // x6 + D = x7 libsnark::r1cs_constraint<FieldT> constraint7 = libsnark::r1cs_constraint<FieldT>( vars[6] + coefficients[3], FieldT::one(), vars[7] ); // x5 + x3 = x8 libsnark::r1cs_constraint<FieldT> constraint8 = libsnark::r1cs_constraint<FieldT>( vars[5] + vars[3], FieldT::one(), vars[8] ); // x8 + x7 = x9 libsnark::r1cs_constraint<FieldT> constraint9 = libsnark::r1cs_constraint<FieldT>( vars[8] + vars[7], FieldT::one(), vars[9] ); // E = x9 (constraint on the value of the output) libsnark::r1cs_constraint<FieldT> constraint10 = libsnark::r1cs_constraint<FieldT>( vars[9], FieldT::one(), coefficients[4] ); pb.add_r1cs_constraint(constraint1); pb.add_r1cs_constraint(constraint2); pb.add_r1cs_constraint(constraint3); pb.add_r1cs_constraint(constraint4); pb.add_r1cs_constraint(constraint5); pb.add_r1cs_constraint(constraint6); pb.add_r1cs_constraint(constraint7); pb.add_r1cs_constraint(constraint8); pb.add_r1cs_constraint(constraint9); pb.add_r1cs_constraint(constraint10); } void generate_r1cs_witness() { pb.val(vars[0]) = pb.val(sol_x); // Input variable // Generate an assignment for all non-input variables // (internal wires of the circuit) pb.val(vars[1]) = pb.val(coefficients[0]) * pb.val(vars[0]); pb.val(vars[2]) = pb.val(vars[1]) * pb.val(vars[0]); pb.val(vars[3]) = pb.val(vars[2]) * pb.val(vars[0]); pb.val(vars[4]) = pb.val(coefficients[1]) * pb.val(vars[0]); pb.val(vars[5]) = pb.val(vars[4]) * pb.val(vars[0]); pb.val(vars[6]) = pb.val(coefficients[2]) * pb.val(vars[0]); pb.val(vars[7]) = pb.val(vars[6]) + pb.val(coefficients[3]); pb.val(vars[8]) = pb.val(vars[5]) + pb.val(vars[3]); pb.val(vars[9]) = pb.val(vars[8]) + pb.val(vars[7]); } };
34.460123
100
0.582339
AntoineRondelet
e3747249d8bc1d18aba1920d752546bc0aedd0ac
1,599
hpp
C++
components/scream/src/share/field/field_property_checks/field_upper_bound_check.hpp
ngam/scream
676f7469b9b33120cb0810c3ab8d9a214746286b
[ "BSD-3-Clause" ]
22
2018-12-12T17:44:55.000Z
2022-03-11T03:47:38.000Z
components/scream/src/share/field/field_property_checks/field_upper_bound_check.hpp
ngam/scream
676f7469b9b33120cb0810c3ab8d9a214746286b
[ "BSD-3-Clause" ]
1,440
2018-07-10T16:49:55.000Z
2022-03-31T22:41:25.000Z
components/scream/src/share/field/field_property_checks/field_upper_bound_check.hpp
ngam/scream
676f7469b9b33120cb0810c3ab8d9a214746286b
[ "BSD-3-Clause" ]
24
2018-11-12T15:43:53.000Z
2022-03-30T18:10:52.000Z
#ifndef SCREAM_FIELD_UPPER_BOUND_CHECK_HPP #define SCREAM_FIELD_UPPER_BOUND_CHECK_HPP #include "share/field/field_property_checks/field_within_interval_check.hpp" #include "ekat/util/ekat_math_utils.hpp" namespace scream { // This field property check returns true if all data in a given field are // bounded above by the given upper bound, and false if not. // It can repair a field that fails the check by clipping all unbounded values // to the upper bound. // Note: The upper bound check is a sub-class of the within interval check with // the upper bound set to the numeric limit. template<typename RealType> class FieldUpperBoundCheck: public FieldWithinIntervalCheck<RealType> { public: using const_RT = typename FieldPropertyCheck<RealType>::const_RT; // No default constructor -- we need an upper bound. FieldUpperBoundCheck () = delete; // Constructor with upper bound. By default, this property check // can repair fields that fail the check by overwriting nonpositive values // with the given upper bound. If can_repair is false, the check cannot // apply repairs to the field. explicit FieldUpperBoundCheck (const_RT upper_bound, bool can_repair = true) : FieldWithinIntervalCheck<RealType>(-std::numeric_limits<RealType>::max(), upper_bound, can_repair) { // Do Nothing } // Overrides. // The name of the field check std::string name () const override { return "Upper Bound Check of " + std::to_string(this->m_upper_bound); } }; } // namespace scream #endif // SCREAM_FIELD_UPPER_BOUND_CHECK_HPP
34.76087
110
0.74359
ngam
e37d586f11df6440712c0b38140276ac072d136c
3,799
cpp
C++
17_2_FEB17/MAKETRI.cpp
parthlathiya/Codechef_Submissions
d404129e4a59c4df10eace61541f48263c32480c
[ "MIT" ]
null
null
null
17_2_FEB17/MAKETRI.cpp
parthlathiya/Codechef_Submissions
d404129e4a59c4df10eace61541f48263c32480c
[ "MIT" ]
null
null
null
17_2_FEB17/MAKETRI.cpp
parthlathiya/Codechef_Submissions
d404129e4a59c4df10eace61541f48263c32480c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define forall(i,a,b) for(int i=a;i<b;i++) #define miN(a,b) ( (a) < (b) ? (a) : (b)) #define maX(a,b) ( (a) > (b) ? (a) : (b)) #define ll long long int #define llu long long unsigned #define mod 1000000007 struct inte { ll s; ll e; }; bool mf1(ll i,ll j){return i<j;} bool mf2(inte i,inte j){return i.s<j.s;} int main() { #ifndef ONLINE_JUDGE freopen("MAKETRI_in.txt","r",stdin); #endif ll N,L,R; cin>>N>>L>>R; ll i; ll a[N]; forall(i,0,N) cin >> a[i]; sort(a,a+N,mf1); // forall(i,0,N) // cout << a[i]; // ll startp[N-1]; // ll endp[N-1]; // ll magic=0; // forall(i,0,N-1) // { // sp=a[i+1]-a[i]+1; // ep=a[i+1]+a[i]-1; // if(i==0) // { // startp[magic]=sp; // endp[magic]=ep; // magic++; // } // else // { // if(sp<=startp[magic-1]) // { // startp[magic-1]=sp; // endp[magic-1]=ep; // } // else if(sp>startp[magic-1] && sp<endp[magic-1]) // endp[magic-1]=ep; // else // { // startp[magic]=sp; // endp[magic]=ep; // magic++; // } // } // // } // // ll ans=0; // forall(i,L,R+1) // { // forall(j,0,N-1) // { // if(i>=startp[j] && i<=endp[j]) // { // ans++; // break; // } // } // } // cout << ans << endl; inte inter[N-1]; forall(i,0,N-1) { inter[i].s=a[i+1]-a[i]+1; inter[i].e=a[i+1]+a[i]-1; } // forall(i,0,N-1) // cout << "d"<<inter[i].s<<"l "<<inter[i].e<< endl; sort(inter,inter+N-1,mf2); // forall(i,0,N-1) // cout << "d"<<inter[i].s<<"l "<<inter[i].e<< endl; stack<inte> ss; ss.push(inter[0]); forall(i,1,N-1) { if((ss.top()).e>=inter[i].s) { inte temp=ss.top(); temp.e=maX(temp.e,inter[i].e); ss.pop(); ss.push(temp); } else ss.push(inter[i]); } ll ans=0; while(!ss.empty()) { inte tt=ss.top(); // cout<<tt.s<<" "<<tt.e<<endl; // cout<<L<<" "<<R<<endl; // if(tt.s<=L) // { // // if(tt.e>=L && tt.e<=R) // ans+=tt.e-L+1; // else if(tt.e>R) // ans+=R-L+1; // } // else if(tt.s<=R) // { // // if(tt.e>=L && tt.e<=R) // ans+=tt.e-tt.s+1; // else if(tt.e>R) // ans+=R-tt.s+1; // } ll start=maX(tt.s,L); ll end=miN(tt.e,R); if(start<=end) ans+=end-start+1; ss.pop(); } // ll ans=0; // forall(i,L,R+1) // { // for(int j=N-1;j>=0;j--) // { // if(i>=startp[j] && i<=endp[j]) // { // //cout << endp[j] << i << endl; // // ans= ans + miN(endp[j],R) - i + 1; // i=miN(endp[j],R); // //cout << ans << i << endl; // break; // } // } // } cout << ans << endl; return 0; }
21.833333
65
0.304817
parthlathiya
be6b6527f236cafe21149bc0329c3881d6c0c9c2
864
cpp
C++
EasyCppTest/BsonSerializer.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
3
2018-02-06T05:12:41.000Z
2020-05-12T20:57:32.000Z
EasyCppTest/BsonSerializer.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
41
2016-07-11T12:19:10.000Z
2017-08-08T07:43:12.000Z
EasyCppTest/BsonSerializer.cpp
Thalhammer/EasyCpp
6b9886fecf0aa363eaf03741426fd3462306c211
[ "MIT" ]
2
2019-08-02T10:24:36.000Z
2020-09-11T01:45:12.000Z
#include <gtest/gtest.h> #include <Serialize/BsonSerializer.h> using namespace EasyCpp; namespace EasyCppTest { TEST(BsonSerializer, BuildDocument) { Bundle b; b.set("hello", "world"); Serialize::BsonSerializer bson; auto result = bson.serialize(b); ASSERT_EQ(result.size(), 22); ASSERT_EQ(result, std::string({ 0x16,0x00,0x00,0x00,0x02,'h','e','l','l','o',0x00,0x06,0x00,0x00,0x00,'w','o','r','l','d',0x00,0x00 })); } TEST(BsonSerializer, ReadDocument) { std::string doc({ 0x16,0x00,0x00,0x00,0x02,'h','e','l','l','o',0x00,0x06,0x00,0x00,0x00,'w','o','r','l','d',0x00,0x00 }); Serialize::BsonSerializer bson; auto b = bson.deserialize(doc).as<Bundle>(); ASSERT_FALSE(b.isEmpty()); ASSERT_TRUE(b.isSet("hello")); ASSERT_TRUE(b.get("hello").isType<std::string>()); ASSERT_EQ(b.get<std::string>("hello"), std::string("world")); } }
30.857143
138
0.662037
Thalhammer
be7344d2191bacb706b24cdc4ce662ada7cefe20
33,709
cc
C++
test/service_recorder_test.cc
epgdatacapbon/mirakc-arib
f50851ac1869599e95dcbefe115624b95e8274de
[ "Apache-2.0", "MIT" ]
null
null
null
test/service_recorder_test.cc
epgdatacapbon/mirakc-arib
f50851ac1869599e95dcbefe115624b95e8274de
[ "Apache-2.0", "MIT" ]
null
null
null
test/service_recorder_test.cc
epgdatacapbon/mirakc-arib
f50851ac1869599e95dcbefe115624b95e8274de
[ "Apache-2.0", "MIT" ]
null
null
null
#include <memory> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <tsduck/tsduck.h> #include "ring_file_sink.hh" #include "service_recorder.hh" #include "test_helper.hh" namespace { constexpr size_t kNumBuffers = 2; constexpr size_t kNumChunks = 2; constexpr size_t kChunkSize = RingFileSink::kBufferSize * kNumBuffers; constexpr uint64_t kRingSize = kChunkSize * kNumChunks; const ServiceRecorderOption kOption { "/dev/null", 3, kChunkSize, kNumChunks }; } TEST(ServiceRecorderTest, NoPacket) { ServiceRecorderOption option = kOption; MockSource src; auto file = std::make_unique<MockFile>(); auto json_sink = std::make_unique<MockJsonlSink>(); { testing::InSequence seq; EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } EXPECT_CALL(src, GetNextPacket).WillOnce(testing::Return(false)); // EOF auto ring = std::make_unique<RingFileSink>( std::move(file), option.chunk_size, option.num_chunks); auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); } TEST(ServiceRecorderTest, EventStart) { ServiceRecorderOption option = kOption; TableSource src; auto file = std::make_unique<MockFile>(); auto json_sink = std::make_unique<MockJsonlSink>(); // TDT tables are used for emulating PES and PCR packets. src.LoadXml(R"( <?xml version="1.0" encoding="utf-8"?> <tsduck> <PAT version="1" current="true" transport_stream_id="0x0002" test-pid="0x0000"> <service service_id="0x0003" program_map_PID="0x0101" /> </PAT> <PMT version="1" current="true" service_id="0x0003" PCR_PID="0x901" test-pid="0x0101"> <component elementary_PID="0x0301" stream_type="0x02" /> </PMT> <TOT UTC_time="2021-01-01 00:00:00" test-pid="0x0014" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="0" /> <EIT type="pf" version="1" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012"> <event event_id="4" start_time="2021-01-01 00:00:00" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="5" start_time="2021-01-01 00:00:01" duration="01:00:00" running_status="undefined" CA_mode="true" /> </EIT> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" /> </tsduck> )"); { testing::InSequence seq; EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } EXPECT_CALL(*file, Write).WillRepeatedly(testing::Return(RingFileSink::kBufferSize)); EXPECT_CALL(*file, Sync).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Trunc).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Seek).WillRepeatedly(testing::Return(0)); auto ring = std::make_unique<RingFileSink>( std::move(file), option.chunk_size, option.num_chunks); auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); EXPECT_TRUE(src.IsEmpty()); } TEST(ServiceRecorderTest, EventProgress) { ServiceRecorderOption option = kOption; TableSource src; auto ring_sink = std::make_unique<MockRingSink>(option.chunk_size, option.num_chunks); auto json_sink = std::make_unique<MockJsonlSink>(); // TDT tables are used for emulating PES and PCR packets. src.LoadXml(R"( <?xml version="1.0" encoding="utf-8"?> <tsduck> <PAT version="1" current="true" transport_stream_id="0x0002" test-pid="0x0000"> <service service_id="0x0003" program_map_PID="0x0101" /> </PAT> <PMT version="1" current="true" service_id="0x0003" PCR_PID="0x901" test-pid="0x0101"> <component elementary_PID="0x0301" stream_type="0x02" /> </PMT> <TOT UTC_time="2021-01-01 00:00:00" test-pid="0x0014" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="0" /> <EIT type="pf" version="1" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012"> <event event_id="4" start_time="2021-01-01 00:00:00" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="5" start_time="2021-01-01 00:00:01" duration="01:00:00" running_status="undefined" CA_mode="true" /> </EIT> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0FFD" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" /> </tsduck> )"); { testing::InSequence seq; EXPECT_CALL(*ring_sink, Start) .WillOnce(testing::Return(true)); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-update","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":16384)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":16384)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-update","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*ring_sink, End) .WillOnce(testing::Return(true)); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring_sink)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); EXPECT_TRUE(src.IsEmpty()); } TEST(ServiceRecorderTest, EventEnd) { ServiceRecorderOption option = kOption; TableSource src; auto file = std::make_unique<MockFile>(); auto json_sink = std::make_unique<MockJsonlSink>(); // TDT tables are used for emulating PES and PCR packets. src.LoadXml(R"( <?xml version="1.0" encoding="utf-8"?> <tsduck> <PAT version="1" current="true" transport_stream_id="0x0002" test-pid="0x0000"> <service service_id="0x0003" program_map_PID="0x0101" /> </PAT> <PMT version="1" current="true" service_id="0x0003" PCR_PID="0x901" test-pid="0x0101"> <component elementary_PID="0x0301" stream_type="0x02" /> </PMT> <TOT UTC_time="2021-01-01 00:00:00" test-pid="0x0014" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="0" /> <EIT type="pf" version="1" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012"> <event event_id="4" start_time="2021-01-01 00:00:00" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="5" start_time="2021-01-01 00:00:01" duration="00:00:01" running_status="undefined" CA_mode="true" /> </EIT> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="1" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="27000000" /> <EIT type="pf" version="2" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012" test-cc="1"> <event event_id="5" start_time="2021-01-01 00:00:01" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="6" start_time="2021-01-01 00:00:02" duration="00:00:01" running_status="undefined" CA_mode="true" /> </EIT> </tsduck> )"); { testing::InSequence seq; EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-end","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426801000,)" R"("pos":376)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":5,)" R"("startTime":1609426801000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426801000,)" R"("pos":376)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } EXPECT_CALL(*file, Write).WillRepeatedly(testing::Return(RingFileSink::kBufferSize)); EXPECT_CALL(*file, Sync).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Trunc).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Seek).WillRepeatedly(testing::Return(0)); auto ring = std::make_unique<RingFileSink>( std::move(file), option.chunk_size, option.num_chunks); auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); EXPECT_TRUE(src.IsEmpty()); } TEST(ServiceRecorderTest, EventStartBeforeEventEnd) { ServiceRecorderOption option = kOption; TableSource src; auto file = std::make_unique<MockFile>(); auto json_sink = std::make_unique<MockJsonlSink>(); // TDT tables are used for emulating PES and PCR packets. src.LoadXml(R"( <?xml version="1.0" encoding="utf-8"?> <tsduck> <PAT version="1" current="true" transport_stream_id="0x0002" test-pid="0x0000"> <service service_id="0x0003" program_map_PID="0x0101" /> </PAT> <PMT version="1" current="true" service_id="0x0003" PCR_PID="0x901" test-pid="0x0101"> <component elementary_PID="0x0301" stream_type="0x02" /> </PMT> <TOT UTC_time="2021-01-01 00:00:00" test-pid="0x0014" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="0" /> <EIT type="pf" version="1" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012"> <event event_id="4" start_time="2021-01-01 00:00:00" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="5" start_time="2021-01-01 00:00:01" duration="01:00:00" running_status="undefined" CA_mode="true" /> </EIT> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" /> <EIT type="pf" version="2" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012" test-cc="1"> <event event_id="6" start_time="2021-01-01 00:00:00" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="7" start_time="2021-01-01 00:00:01" duration="01:00:00" running_status="undefined" CA_mode="true" /> </EIT> </tsduck> )"); { testing::InSequence seq; EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-end","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":188)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":6,)" R"("startTime":1609426800000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":188)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } EXPECT_CALL(*file, Write).WillRepeatedly(testing::Return(RingFileSink::kBufferSize)); EXPECT_CALL(*file, Sync).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Trunc).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Seek).WillRepeatedly(testing::Return(0)); auto ring = std::make_unique<RingFileSink>( std::move(file), option.chunk_size, option.num_chunks); auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); EXPECT_TRUE(src.IsEmpty()); } TEST(ServiceRecorderTest, FirstEventAlreadyEnded) { ServiceRecorderOption option = kOption; TableSource src; auto file = std::make_unique<MockFile>(); auto json_sink = std::make_unique<MockJsonlSink>(); // TDT tables are used for emulating PES and PCR packets. src.LoadXml(R"( <?xml version="1.0" encoding="utf-8"?> <tsduck> <PAT version="1" current="true" transport_stream_id="0x0002" test-pid="0x0000"> <service service_id="0x0003" program_map_PID="0x0101" /> </PAT> <PMT version="1" current="true" service_id="0x0003" PCR_PID="0x901" test-pid="0x0101"> <component elementary_PID="0x0301" stream_type="0x02" /> </PMT> <TOT UTC_time="2021-01-01 00:00:01" test-pid="0x0014" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="0" /> <EIT type="pf" version="1" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012"> <event event_id="4" start_time="2021-01-01 00:00:00" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="5" start_time="2021-01-01 00:00:01" duration="00:00:01" running_status="undefined" CA_mode="true" /> </EIT> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" /> <EIT type="pf" version="2" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012" test-cc="1"> <event event_id="5" start_time="2021-01-01 00:00:01" duration="00:00:01" running_status="undefined" CA_mode="true" /> <event event_id="6" start_time="2021-01-01 00:00:02" duration="00:00:01" running_status="undefined" CA_mode="true" /> </EIT> </tsduck> )"); { testing::InSequence seq; EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426801000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":5,)" R"("startTime":1609426801000,)" R"("duration":1000,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426801000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } EXPECT_CALL(*file, Write).WillRepeatedly(testing::Return(RingFileSink::kBufferSize)); EXPECT_CALL(*file, Sync).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Trunc).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Seek).WillRepeatedly(testing::Return(0)); auto ring = std::make_unique<RingFileSink>( std::move(file), option.chunk_size, option.num_chunks); auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); EXPECT_TRUE(src.IsEmpty()); } TEST(ServiceRecorderTest, UnspecifiedEventEnd) { ServiceRecorderOption option = kOption; TableSource src; auto file = std::make_unique<MockFile>(); auto json_sink = std::make_unique<MockJsonlSink>(); // TDT tables are used for emulating PES and PCR packets. src.LoadXml(R"( <?xml version="1.0" encoding="utf-8"?> <tsduck> <PAT version="1" current="true" transport_stream_id="0x0002" test-pid="0x0000"> <service service_id="0x0003" program_map_PID="0x0101" /> </PAT> <PMT version="1" current="true" service_id="0x0003" PCR_PID="0x901" test-pid="0x0101"> <component elementary_PID="0x0301" stream_type="0x02" /> </PMT> <TOT UTC_time="2021-01-01 00:00:00" test-pid="0x0014" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="0" /> <EIT type="pf" version="1" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012"> <event event_id="4" start_time="2021-01-01 00:00:00" duration="00:00:00" running_status="undefined" CA_mode="true" /> <event event_id="5" start_time="2021-01-01 00:00:00" duration="00:00:00" running_status="undefined" CA_mode="true" /> </EIT> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0901" test-pcr="27000000" test-cc="1" /> <TOT UTC_time="2021-01-01 00:00:01" test-pid="0x0014" test-cc="1" /> <TDT UTC_time="1970-01-01 00:00:00" test-pid="0x0301" test-cc="1" /> <EIT type="pf" version="2" current="true" actual="true" service_id="0x0003" transport_stream_id="0x0002" original_network_id="0x0001" last_table_id="0x4E" test-pid="0x0012" test-cc="1"> <event event_id="5" start_time="2021-01-01 00:00:00" duration="00:00:00" running_status="undefined" CA_mode="true" /> <event event_id="6" start_time="2021-01-01 00:00:00" duration="00:00:00" running_status="undefined" CA_mode="true" /> </EIT> </tsduck> )"); { testing::InSequence seq; EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"start"})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"chunk","data":{"chunk":{)" R"("timestamp":1609426800000,"pos":0)" R"(}}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":0,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426800000,)" R"("pos":0)" R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-end","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":4,)" R"("startTime":1609426800000,)" R"("duration":0,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426801000,)" R"("pos":752)" // 188 * 4 R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"event-start","data":{)" R"("originalNetworkId":1,)" R"("transportStreamId":2,)" R"("serviceId":3,)" R"("event":{)" R"("eventId":5,)" R"("startTime":1609426800000,)" R"("duration":0,)" R"("scrambled":true,)" R"("descriptors":[])" R"(},)" R"("record":{)" R"("timestamp":1609426801000,)" R"("pos":752)" // 188 * 4 R"(})" R"(}})", MockJsonlSink::Stringify(doc)); return true; }); EXPECT_CALL(*json_sink, HandleDocument) .WillOnce([](const rapidjson::Document& doc) { EXPECT_EQ( R"({"type":"stop","data":{"reset":false}})", MockJsonlSink::Stringify(doc)); return true; }); } EXPECT_CALL(*file, Write).WillRepeatedly(testing::Return(RingFileSink::kBufferSize)); EXPECT_CALL(*file, Sync).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Trunc).WillRepeatedly(testing::Return(true)); EXPECT_CALL(*file, Seek).WillRepeatedly(testing::Return(0)); auto ring = std::make_unique<RingFileSink>( std::move(file), option.chunk_size, option.num_chunks); auto recorder = std::make_unique<ServiceRecorder>(kOption); recorder->ServiceRecorder::Connect(std::move(ring)); recorder->JsonlSource::Connect(std::move(json_sink)); src.Connect(std::move(recorder)); EXPECT_TRUE(src.FeedPackets()); EXPECT_TRUE(src.IsEmpty()); }
38.218821
88
0.531164
epgdatacapbon
be7c81fda2431801fa41313c1d4a8df4fecbe8bd
4,066
cpp
C++
dbms/src/Storages/MergeTree/SimpleMergeSelector.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
null
null
null
dbms/src/Storages/MergeTree/SimpleMergeSelector.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
null
null
null
dbms/src/Storages/MergeTree/SimpleMergeSelector.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
null
null
null
#include <DB/Storages/MergeTree/SimpleMergeSelector.h> #include <DB/Common/interpolate.h> #include <cmath> namespace DB { namespace { /** Estimates best set of parts to merge within passed alternatives. */ struct Estimator { using Iterator = SimpleMergeSelector::PartsInPartition::const_iterator; void consider(Iterator begin, Iterator end, size_t sum_size, size_t size_next_at_left, size_t size_next_at_right) { double current_score = score(end - begin, sum_size); if (size_next_at_left > sum_size * 0.9) { double difference = std::abs(log2(static_cast<double>(sum_size) / size_next_at_left)); if (difference < 0.5) current_score *= 0.75 + difference * 0.5; } if (size_next_at_right == 0) current_score *= 0.9; if (size_next_at_right > sum_size * 0.9) { double difference = std::abs(log2(static_cast<double>(sum_size) / size_next_at_right)); if (difference < 0.5) current_score *= 0.75 + difference * 0.5; } if (!min_score || current_score < min_score) { min_score = current_score; best_begin = begin; best_end = end; } } SimpleMergeSelector::PartsInPartition getBest() { return SimpleMergeSelector::PartsInPartition(best_begin, best_end); } static double score(double count, double sum_size) { /** Consider we have two alternative ranges of data parts to merge. * Assume time to merge a range is proportional to sum size of its parts. * * Cost of query execution is proportional to total number of data parts in a moment of time. * Let define our target: to minimize average (in time) total number of data parts. * * Let calculate integral of total number of parts, if we are going to do merge of one or another range. * It must be lower, and thus we decide, what range is better to merge. * * The integral is lower iff the following formula is lower: */ return sum_size / (count - 1); } double min_score = 0; Iterator best_begin; Iterator best_end; }; void selectWithinPartition( const SimpleMergeSelector::PartsInPartition & parts, const size_t max_total_size_to_merge, const time_t current_min_part_age, Estimator & estimator, const SimpleMergeSelector::Settings & settings) { size_t parts_count = parts.size(); if (parts_count <= 1) return; double actual_base = std::max(1.0, std::min( settings.base, std::min( interpolateLinear(settings.base, 1.0, (static_cast<double>(parts_count) - settings.lower_base_after_num_parts_start) / (settings.lower_base_after_num_parts_end - settings.lower_base_after_num_parts_start)), interpolateLinear(settings.base, 1.0, (static_cast<double>(current_min_part_age) - settings.lower_base_after_seconds_start) / (settings.lower_base_after_seconds_end - settings.lower_base_after_seconds_start))))); for (size_t begin = 0; begin < parts_count; ++begin) { size_t sum_size = parts[begin].size; size_t max_size = parts[begin].size; for (size_t end = begin + 2; end <= parts_count; ++end) { if (settings.max_parts_to_merge_at_once && end - begin > settings.max_parts_to_merge_at_once) break; sum_size += parts[end - 1].size; if (parts[end - 1].size > max_size) max_size = parts[end - 1].size; if (max_total_size_to_merge && sum_size > max_total_size_to_merge) break; if (static_cast<double>(sum_size) / max_size >= actual_base) estimator.consider( parts.begin() + begin, parts.begin() + end, sum_size, begin == 0 ? 0 : parts[begin - 1].size, end == parts_count ? 0 : parts[end].size); } } } } SimpleMergeSelector::PartsInPartition SimpleMergeSelector::select( const Partitions & partitions, const size_t max_total_size_to_merge) { time_t min_age = -1; for (const auto & partition : partitions) for (const auto & part : partition) if (min_age == -1 || part.age < min_age) min_age = part.age; Estimator estimator; for (const auto & partition : partitions) selectWithinPartition(partition, max_total_size_to_merge, min_age, estimator, settings); return estimator.getBest(); } }
28.236111
126
0.715691
rudneff
be7df6dd1c4e64c658312aab616f39e541c3669d
571
hpp
C++
libs/plugin/include/sge/plugin/declare_iterator.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/plugin/include/sge/plugin/declare_iterator.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/plugin/include/sge/plugin/declare_iterator.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_PLUGIN_DECLARE_ITERATOR_HPP_INCLUDED #define SGE_PLUGIN_DECLARE_ITERATOR_HPP_INCLUDED #include <sge/core/detail/export_class_declaration.hpp> #include <sge/plugin/iterator.hpp> #define SGE_PLUGIN_DECLARE_ITERATOR(plugin_type) \ extern template class SGE_CORE_DETAIL_EXPORT_CLASS_DECLARATION sge::plugin::iterator<plugin_type> #endif
35.6875
99
0.789842
cpreh
be8decd271b23fec17ea31015c559bfd90c1b25d
4,135
cc
C++
c++-stl/random-number-engines.cc
deyuan/coding-practice
82bdf719397507601e582ab6d5693e4e50e96a3a
[ "MIT" ]
null
null
null
c++-stl/random-number-engines.cc
deyuan/coding-practice
82bdf719397507601e582ab6d5693e4e50e96a3a
[ "MIT" ]
null
null
null
c++-stl/random-number-engines.cc
deyuan/coding-practice
82bdf719397507601e582ab6d5693e4e50e96a3a
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Deyuan Guo. All rights reserved. // This file is subject to the terms and conditions defined // in file 'LICENSE' in this source code package. #include <iostream> #include <random> // Engine: std::random_device // Algorithm: True-RNG if entropy() is non-zero, pseudo-RNG otherwise // Note: Non-deterministic. May throw an exception if not available void TestRandomDevice() { std::cout << "# RNG Engine Test: std::random_devide" << std::endl; std::random_device rd; std::cout << " Range: [" << rd.min() << ", " << rd.max() << "]" << std::endl; std::cout << " Entropy: " << rd.entropy() << (rd.entropy() ? " (True RNG)" : " (Pseudo RNG)") << std::endl; unsigned int randVal = rd(); std::cout << " Random Value: " << randVal << std::endl; std::cout << std::endl; } // Template for testing a pseudo random number engine template <class T> void TestPrngEngine(const std::string &name, unsigned int seed) { std::cout << "# RNG Engine Test: " << name << " (seed " << seed << ")\n"; T rng(seed); std::cout << " Range: [" << rng.min() << ", " << rng.max() << "]\n"; std::cout << " Random Values: "; std::cout << rng() << ", "; std::cout << rng() << ", "; std::cout << rng() << ", "; rng.seed(seed); // reset seed std::cout << "RESET-SEED\n"; std::cout << " Random Values: " << rng() << ", "; rng.discard(1); // discard 1 value std::cout << "DISCARDED, "; std::cout << rng() << "\n"; std::cout << std::endl; } void RandomNumberEngines() { // Note: RNG engines below generate uniformly-distributed unsigned int values // Note: Implementation-defined, true-RNG or pseudo-RNG, non-deterministic TestRandomDevice(); // Note: Implementation-defined, implemented as one PRNG engine below TestPrngEngine<std::default_random_engine>("std::default_random_engine", 0); //////////////////////////////////////////////////////////////////////////// // std::linear_congruential_engine // Algorithm: x = (a * x + c) mod m, period = m // // Engine Adaptors: // std::shuffle_order_engine: table_size k, shuffle k elements // minstd_rand: a = 48271 (prime), c = 0, m = 2^31 - 1, return uint_fast32_t TestPrngEngine<std::minstd_rand>("std::minstd_rand", 0); // minstd_rand0: a = 16807 (prime), c = 0, m = 2^31 - 1, return uint_fast32_t TestPrngEngine<std::minstd_rand0>("std::minstd_rand0", 0); // knuth_b: minstd_rand0 + shuffle_order_engine with k = 256, uint_fast32_t TestPrngEngine<std::knuth_b>("std::knuth_b", 0); //////////////////////////////////////////////////////////////////////////// // std::mersenne_twister_engine // Algorithm: word_size w, state_size n, shift_size m, mask_bits r // range = [0, 2^w - 1], period = 2^((n - 1) * w) - 1 // mt19937: (w, n, m, r) = (32, 624, 397, 31), return uint_fast32_t TestPrngEngine<std::mt19937>("std::mt19937", 0); // mt19937: (w, n, m, r) = (64, 312, 156, 31), return uint_fast64_t TestPrngEngine<std::mt19937_64>("std::mt19937_64", 0); //////////////////////////////////////////////////////////////////////////// // std::subtract_with_carry_engine // Algorithm: lagged fibonacci generator (LFG/LFib) // word_size w, short_lag s, long_lag r // // Engine Adaptors: // std::discard_block_engine: block_size p, used_block r // discard p - r elements // ranlux24_base: (w, s, r) = (24, 10, 24), return uint_fast32_t TestPrngEngine<std::ranlux24_base>("std::ranlux24_base", 0); // ranlux48_base: (w, s, r) = (48, 5, 12), return uint_fast64_t TestPrngEngine<std::ranlux48_base>("std::ranlux48_base", 0); // ranlux24_base + discard_block_engine (p, r) = (223, 23), uint_fast32_t TestPrngEngine<std::ranlux24>("std::ranlux24", 0); // ranlux48_base + discard_block_engine (p, r) = (389, 11), uint_fast64_t TestPrngEngine<std::ranlux48>("std::ranlux48", 0); //////////////////////////////////////////////////////////////////////////// // Engine Adaptors: // std::independent_bits_engine: work_size w, fixed w bits of each number } int main() { RandomNumberEngines(); return 0; }
40.539216
80
0.58549
deyuan
be9382e0028be1e8abf2be05a94625d75b012b59
1,972
cpp
C++
src/plugins/monocle/plugins/postrus/postrus.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/monocle/plugins/postrus/postrus.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/monocle/plugins/postrus/postrus.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 "postrus.h" #include <QIcon> #include <util/sys/mimedetector.h> #include <util/util.h> #include "redirector.h" namespace LC { namespace Monocle { namespace Postrus { void Plugin::Init (ICoreProxy_ptr) { Util::InstallTranslator ("monocle_postrus"); } void Plugin::SecondInit () { } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.Monocle.Postrus"; } void Plugin::Release () { } QString Plugin::GetName () const { return "Monocle Postrus"; } QString Plugin::GetInfo () const { return tr ("PostScript backend for Monocle."); } QIcon Plugin::GetIcon () const { return QIcon (); } QSet<QByteArray> Plugin::GetPluginClasses () const { QSet<QByteArray> result; result << "org.LeechCraft.Monocle.IBackendPlugin"; return result; } auto Plugin::CanLoadDocument (const QString& file) -> LoadCheckResult { const auto& mime = Util::MimeDetector {} (file); return mime == "application/postscript" ? LoadCheckResult::Redirect : LoadCheckResult::Cannot; } IDocument_ptr Plugin::LoadDocument (const QString&) { return {}; } IRedirectProxy_ptr Plugin::GetRedirection (const QString& filename) { return std::make_shared<Redirector> (filename); } QStringList Plugin::GetSupportedMimes () const { return { "application/postscript" }; } QList<IKnowFileExtensions::ExtInfo> Plugin::GetKnownFileExtensions () const { return { { tr ("PostScript files"), { "ps", "eps" } } }; } } } } LC_EXPORT_PLUGIN (leechcraft_monocle_postrus, LC::Monocle::Postrus::Plugin);
19.919192
83
0.646552
Maledictus
be9aea33c1dd3e5e41e625280ea311c225213135
752
cpp
C++
engine/calculators/source/RangedPhysicalDamageCalculator.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/calculators/source/RangedPhysicalDamageCalculator.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/calculators/source/RangedPhysicalDamageCalculator.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "RangedPhysicalDamageCalculator.hpp" RangedPhysicalDamageCalculator::RangedPhysicalDamageCalculator(const PhaseOfMoonType new_pom) : PhysicalDamageCalculator(AttackType::ATTACK_TYPE_RANGED, new_pom) { } int RangedPhysicalDamageCalculator::get_statistic_based_damage_modifier(CreaturePtr attacking_creature) { int modifier = 0; if (attacking_creature) { int current_dex = attacking_creature->get_dexterity().get_current(); if (current_dex > DAMAGE_STAT_BASELINE) { current_dex -= DAMAGE_STAT_BASELINE; modifier = current_dex / DAMAGE_STAT_DIVISOR; } } return modifier; } SkillType RangedPhysicalDamageCalculator::get_general_combat_skill() const { return SkillType::SKILL_GENERAL_ARCHERY; }
25.931034
103
0.785904
sidav
be9c5052b288578c0fc376c780e021103f05883e
285
hpp
C++
include/flexui/Layout/TextLayoutObject.hpp
mlomb/flexui
242790aa13b057e25b276b6a3df79a30735c2548
[ "MIT" ]
23
2020-12-20T01:41:56.000Z
2021-11-14T20:26:40.000Z
include/flexui/Layout/TextLayoutObject.hpp
mlomb/flexui
242790aa13b057e25b276b6a3df79a30735c2548
[ "MIT" ]
2
2020-12-23T16:29:55.000Z
2021-11-29T05:35:12.000Z
include/flexui/Layout/TextLayoutObject.hpp
mlomb/flexui
242790aa13b057e25b276b6a3df79a30735c2548
[ "MIT" ]
4
2020-12-23T16:02:25.000Z
2021-09-30T08:37:51.000Z
#pragma once #include "flexui/Layout/LayoutObject.hpp" namespace flexui { class Text; class TextLayoutObject : public LayoutObject { public: TextLayoutObject(Text* text); ~TextLayoutObject(); Text* getTextNode() const { return m_Text; } private: Text* m_Text; }; }
13.571429
47
0.708772
mlomb
bea22392664416aacba57e1ec2c161350ba0766a
2,751
hpp
C++
back/project2/include/ast_terminal.hpp
wht-github/CS323-Compilers
d49c8e61f17b18503504d11e0eca58b1f89997c4
[ "MIT" ]
null
null
null
back/project2/include/ast_terminal.hpp
wht-github/CS323-Compilers
d49c8e61f17b18503504d11e0eca58b1f89997c4
[ "MIT" ]
null
null
null
back/project2/include/ast_terminal.hpp
wht-github/CS323-Compilers
d49c8e61f17b18503504d11e0eca58b1f89997c4
[ "MIT" ]
null
null
null
#ifndef AST_TERMINAL_HPP #define AST_TERMINAL_HPP #include "ast.hpp" #include <string> #include <iostream> class Terminal : public Base { public: std::string symbol; Terminal(const std::string &_symbol) : symbol(_symbol) {} virtual void print(int idt = 0) const { for (int i = 0; i < idt; i++) std::cout << " "; std::cout << symbol << std::endl; } virtual void push(const Base *_base) const { std::cerr << "Can't call this function for terminal" << std::endl; (void)_base; } }; class ValInt : public Base { public: unsigned int val; ValInt(unsigned int _val) : val(_val) {} virtual void print(int idt = 0) const { for (int i = 0; i < idt; i++) std::cout << " "; std::cout << "INT: " << val << std::endl; } virtual void push(const Base *_base) const { std::cerr << "Can't call this function for int" << std::endl; (void)_base; } }; class ValFloat : public Base { public: float val; ValFloat(float _val) : val(_val) {} virtual void print(int idt = 0) const { for (int i = 0; i < idt; i++) std::cout << " "; std::cout << "FLOAT: " << val << std::endl; } virtual void push(const Base *_base) const { std::cerr << "Can't call this function for float" << std::endl; (void)_base; } }; class ValChar : public Base { public: std::string val; ValChar(std::string &_val) : val(_val) {} virtual void print(int idt = 0) const { for (int i = 0; i < idt; i++) std::cout << " "; std::cout << "CHAR: " << val << std::endl; } virtual void push(const Base *_base) const { std::cerr << "Can't call this function for char" << std::endl; (void)_base; } }; class ValType : public Base { public: std::string val; ValType(std::string &_val) : val(_val) {} virtual void print(int idt = 0) const { for (int i = 0; i < idt; i++) std::cout << " "; std::cout << "TYPE: " << val << std::endl; } virtual void push(const Base *_base) const { std::cerr << "Can't call this function for type" << std::endl; (void)_base; } }; class ValId : public Base { public: std::string val; ValId(std::string &_val) : val(_val) {} virtual void print(int idt = 0) const { for (int i = 0; i < idt; i++) std::cout << " "; std::cout << "ID: " << val << std::endl; } virtual void push(const Base *_base) const { std::cerr << "Can't call this function for identifier" << std::endl; (void)_base; } }; #endif
20.377778
76
0.519084
wht-github
bea5412932ae445664a243bc6db51fb808638852
616
hpp
C++
Code/Engine/Math/RigidBodyBucket.hpp
pronaypeddiraju/Engine
0ca9720a00f51340c6eb6bba07d70972489663e8
[ "Unlicense" ]
1
2021-01-25T23:53:44.000Z
2021-01-25T23:53:44.000Z
Code/Engine/Math/RigidBodyBucket.hpp
pronaypeddiraju/Engine
0ca9720a00f51340c6eb6bba07d70972489663e8
[ "Unlicense" ]
null
null
null
Code/Engine/Math/RigidBodyBucket.hpp
pronaypeddiraju/Engine
0ca9720a00f51340c6eb6bba07d70972489663e8
[ "Unlicense" ]
1
2021-01-25T23:53:46.000Z
2021-01-25T23:53:46.000Z
//------------------------------------------------------------------------------------------------------------------------------ #pragma once #include <vector> #include "Engine/Math/PhysicsTypes.hpp" //------------------------------------------------------------------------------------------------------------------------------ class Rigidbody2D; //------------------------------------------------------------------------------------------------------------------------------ class RigidBodyBucket { public: RigidBodyBucket(); ~RigidBodyBucket(); std::vector<Rigidbody2D*> m_RbBucket[NUM_SIMULATION_TYPES]; };
36.235294
128
0.287338
pronaypeddiraju
bea5eee63b0ceec1509be64925c74c24d88fb744
1,964
cpp
C++
toonz/sources/tnztools/inputstate.cpp
morevnaproject-org/opentoonz
3335715599092c3f173c2ffd015f09b1a0b3cb91
[ "BSD-3-Clause" ]
36
2020-05-18T22:26:35.000Z
2022-02-19T00:09:25.000Z
toonz/sources/tnztools/inputstate.cpp
morevnaproject-org/opentoonz
3335715599092c3f173c2ffd015f09b1a0b3cb91
[ "BSD-3-Clause" ]
16
2020-05-14T17:51:08.000Z
2022-02-11T01:49:38.000Z
toonz/sources/tnztools/inputstate.cpp
morevnaproject-org/opentoonz
3335715599092c3f173c2ffd015f09b1a0b3cb91
[ "BSD-3-Clause" ]
8
2020-06-12T17:01:20.000Z
2021-09-15T07:03:12.000Z
#include <tools/inputstate.h> //***************************************************************************************** // TKey static members //***************************************************************************************** const TKey TKey::shift(Qt::Key_Shift, true); const TKey TKey::control(Qt::Key_Control, true); const TKey TKey::alt(Qt::Key_Alt, true); const TKey TKey::meta(Qt::Key_Meta, true); Qt::Key TKey::mapKey(Qt::Key key) { switch (key) { case Qt::Key_AltGr: return Qt::Key_Alt; default: break; } return key; } bool TKey::isModifier(Qt::Key key) { key = mapKey(key); return key == Qt::Key_Shift || key == Qt::Key_Control || key == Qt::Key_Alt || key == Qt::Key_AltGr || key == Qt::Key_Meta; } bool TKey::isNumber(Qt::Key key) { key = mapKey(key); return key >= Qt::Key_0 && key <= Qt::Key_9; } //***************************************************************************************** // TInputState implementation //***************************************************************************************** TInputState::TInputState() : m_ticks(), m_keyHistory(new KeyHistory()) {} TInputState::~TInputState() {} void TInputState::touch(TTimerTicks ticks) { if (m_ticks < ticks) m_ticks = ticks; else ++m_ticks; } TInputState::ButtonHistory::Pointer TInputState::buttonHistory( DeviceId device) const { ButtonHistory::Pointer &history = m_buttonHistories[device]; if (!history) history = new ButtonHistory(); return history; } TInputState::ButtonState::Pointer TInputState::buttonFindAny( Button button, DeviceId &outDevice) { for (ButtonHistoryMap::const_iterator i = m_buttonHistories.begin(); i != m_buttonHistories.end(); ++i) { ButtonState::Pointer state = i->second->current()->find(button); if (state) { outDevice = i->first; return state; } } outDevice = DeviceId(); return ButtonState::Pointer(); }
28.057143
91
0.535642
morevnaproject-org
bea71ffa482ff76d6c4ef7897f0d4ce830dc5fa1
34,635
cc
C++
test/TestStratum.cc
vpashka/btcpool
dab18b2bc90b3db2fb30698fc04e7e21a06acd11
[ "MIT" ]
null
null
null
test/TestStratum.cc
vpashka/btcpool
dab18b2bc90b3db2fb30698fc04e7e21a06acd11
[ "MIT" ]
null
null
null
test/TestStratum.cc
vpashka/btcpool
dab18b2bc90b3db2fb30698fc04e7e21a06acd11
[ "MIT" ]
1
2021-11-05T08:36:28.000Z
2021-11-05T08:36:28.000Z
/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "gtest/gtest.h" #include "Common.h" #include "Utils.h" #include "Stratum.h" #include "bitcoin/BitcoinUtils.h" #include "bitcoin/StratumBitcoin.h" #include "rsk/RskWork.h" #include <chainparams.h> #include <hash.h> #include <script/script.h> #include <uint256.h> #include <util.h> #ifdef INCLUDE_BTC_KEY_IO_H #include <key_io.h> // IsValidDestinationString for bch is not in this file. #endif #include <stdint.h> TEST(Stratum, jobId2Time) { uint64_t jobId; // jobId: timestamp + gbtHash // ---------- ---------- // uint32_t uint32_t // const string jobIdStr = Strings::Format("%08x%s", (uint32_t)time(nullptr), // gbtHash.ToString().substr(0, // 8).c_str()); jobId = (1469002809ull << 32) | 0x00000000FFFFFFFFull; ASSERT_EQ(jobId2Time(jobId), 1469002809u); jobId = (1469002809ull << 32) | 0x0000000000000000ull; ASSERT_EQ(jobId2Time(jobId), 1469002809u); } TEST(Stratum, Share) { ShareBitcoin s; ASSERT_EQ(s.isValid(), false); ASSERT_EQ(s.score(), 0); ASSERT_EQ( s.toString(), "share(jobId: 0, ip: 0.0.0.0, userId: 0, workerId: 0, " "time: 0/1970-01-01 00:00:00, height: 0, blkBits: 00000000/inf, " "shareDiff: 0, status: 0/Share rejected)"); IpAddress ip; ip.fromIpv4Int(htonl(167772161)); s.set_ip(ip.toString()); // 167772161 : 10.0.0.1 ASSERT_EQ( s.toString(), "share(jobId: 0, ip: 10.0.0.1, userId: 0, workerId: 0, " "time: 0/1970-01-01 00:00:00, height: 0, blkBits: 00000000/inf, " "shareDiff: 0, status: 0/Share rejected)"); } TEST(Stratum, Share2) { ShareBitcoin s; s.set_blkbits(0x1d00ffffu); s.set_sharediff(1ll); ASSERT_EQ(s.score(), 1ll); s.set_blkbits(0x18050edcu); s.set_sharediff(UINT32_MAX); // double will be: 0.0197583 ASSERT_EQ(score2Str(s.score()), "0.0197582875516673"); } TEST(Stratum, StratumWorker) { StratumWorker w; uint64_t u; int64_t workerId; ASSERT_EQ(w.getUserName("abcd"), "abcd"); ASSERT_EQ( w.getUserName("abcdabcdabcdabcdabcdabcdabcd"), "abcdabcdabcdabcdabcdabcdabcd"); ASSERT_EQ(w.getUserName("abcd."), "abcd"); ASSERT_EQ(w.getUserName("abcd.123"), "abcd"); ASSERT_EQ(w.getUserName("abcd.123.456"), "abcd"); // // echo -n '123' |openssl dgst -sha256 -binary |openssl dgst -sha256 // w.setUserIDAndNames(INT32_MAX, "abcd.123"); ASSERT_EQ(w.fullName_, "abcd.123"); ASSERT_EQ(w.userId_, INT32_MAX); ASSERT_EQ(w.userName_, "abcd"); ASSERT_EQ(w.workerName_, "123"); // '123' dsha256 : // 5a77d1e9612d350b3734f6282259b7ff0a3f87d62cfef5f35e91a5604c0490a3 // uint256 : // a390044c60a5915ef3f5fe2cd6873f0affb7592228f634370b352d61e9d1775a u = strtoull("a390044c60a5915e", nullptr, 16); memcpy((uint8_t *)&workerId, (uint8_t *)&u, 8); ASSERT_EQ(w.workerHashId_, workerId); w.setUserIDAndNames(0, "abcdefg"); ASSERT_EQ(w.fullName_, "abcdefg.__default__"); ASSERT_EQ(w.userId_, 0); ASSERT_EQ(w.userName_, "abcdefg"); ASSERT_EQ(w.workerName_, "__default__"); // '__default__' dsha256 : // e00f302bc411fde77d954283be6904911742f2ac76c8e79abef5dff4e6a19770 // uint256 : 7097a1e6f4dff5be u = strtoull("7097a1e6f4dff5be", nullptr, 16); memcpy((uint8_t *)&workerId, (uint8_t *)&u, 8); ASSERT_EQ(w.workerHashId_, workerId); // check allow chars w.setUserIDAndNames(0, "abcdefg.azAZ09-._:|^/"); ASSERT_EQ(w.workerName_, "azAZ09-._:|^/"); ASSERT_EQ(w.fullName_, "abcdefg.azAZ09-._:|^/"); // some of them are bad chars w.setUserIDAndNames(0, "abcdefg.~!@#$%^&*()+={}|[]\\<>?,./"); ASSERT_EQ(w.workerName_, "^|./"); ASSERT_EQ(w.fullName_, "abcdefg.^|./"); // all bad chars w.setUserIDAndNames(0, "abcdefg.~!@#$%&*()+={}[]\\<>?,"); ASSERT_EQ(w.workerName_, "__default__"); ASSERT_EQ(w.fullName_, "abcdefg.__default__"); } TEST(JobMaker, BitcoinAddress) { // main net SelectParams(CBaseChainParams::MAIN); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "1A1zP1eP5QGefi2DMPPfTL5SLmv7DivfNa"), false); #ifdef CHAIN_TYPE_BTC ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bc1qw508c6qejxtdg4y5r3zarvary4c5xw7kv8f3t4"), false); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bc1qrp33g0q5c5txsp8arysrx4k6zdkfs4nde4xj0gdcccefvpysxf3qccfmv3"), false); #endif #ifdef CHAIN_TYPE_BCH ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bitcoincash:qp3wjpa3tjlj042z2wv7hahsldgwhwy0rq9sywjpyy"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bitcoincash:qp3wjpa3tjlj142z2wv7hahsldgwhwy0rq9sywjpyy"), false); #endif // test net SelectParams(CBaseChainParams::TESTNET); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "myxopLJB19oFtNBdrADD5Z34Aw6P8o9P8U"), false); #ifdef CHAIN_TYPE_BTC ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "tb1qw508d6qejxtdg6y5r3zarvary0c5xw7kxpjzsx"), false); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "tb1qrp33g0q5c5txsp9arysrx4k6zdkgs4nce4xj0gdcccefvpysxf3q0sl5k7"), false); #endif #ifdef CHAIN_TYPE_BCH ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bchtest:qr99vqygcra4umcz374pzzz7vslrgw50ts58trd220"), true); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "bchtest:qr99vqygcra5umcz374pzzz7vslrgw50ts58trd220"), false); #endif } TEST(Stratum, StratumJobBitcoin) { StratumJobBitcoin sjob; string poolCoinbaseInfo = "/BTC.COM/"; uint32_t blockVersion = 0; bool res; { string gbt; gbt += "{\"result\":{"; gbt += " \"capabilities\": ["; gbt += " \"proposal\""; gbt += " ],"; gbt += " \"version\": 536870912,"; gbt += " \"previousblockhash\": " "\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c34\","; gbt += " \"transactions\": ["; gbt += " {"; gbt += " \"data\": " "\"01000000010291939c5ae8191c2e7d4ce8eba7d6616a66482e3200037cb8b8c2d0af" "45b445000000006a47304402204df709d9e149804e358de4b082e41d8bb21b3c9d3472" "41b728b1362aafcb153602200d06d9b6f2eca899f43dcd62ec2efb2d9ce2e10adf0273" "8bb908420d7db93ede012103cae98ab925e20dd6ae1f76e767e9e99bc47b3844095c68" "600af9c775104fb36cffffffff0290f1770b000000001976a91400dc5fd62f6ee48eb8" "ecda749eaec6824a780fdd88aca08601000000000017a914eb65573e5dd52d3d950396" "ccbe1a47daf8f400338700000000\","; gbt += " \"hash\": " "\"bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca79ff\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 10000,"; gbt += " \"sigops\": 1"; gbt += " }"; gbt += " ],"; gbt += " \"coinbaseaux\": {"; gbt += " \"flags\": \"\""; gbt += " },"; gbt += " \"coinbasevalue\": 312659655,"; gbt += " \"longpollid\": " "\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c341911" "\","; gbt += " \"target\": " "\"000000000000018ae20000000000000000000000000000000000000000000000\","; gbt += " \"mintime\": 1469001544,"; gbt += " \"mutable\": ["; gbt += " \"time\","; gbt += " \"transactions\","; gbt += " \"prevblock\""; gbt += " ],"; gbt += " \"noncerange\": \"00000000ffffffff\","; gbt += " \"sigoplimit\": 20000,"; gbt += " \"sizelimit\": 1000000,"; gbt += " \"curtime\": 1469006933,"; gbt += " \"bits\": \"1a018ae2\","; gbt += " \"height\": 898487"; gbt += "}}"; blockVersion = 0; SelectParams(CBaseChainParams::TESTNET); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"), true); CTxDestination poolPayoutAddrTestnet = BitcoinUtils::DecodeDestination("myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"); res = sjob.initFromGbt( gbt.c_str(), poolCoinbaseInfo, poolPayoutAddrTestnet, blockVersion, "", RskWork(), 1, false); ASSERT_EQ(res, true); const string jsonStr = sjob.serializeToJson(); StratumJobBitcoin sjob2; res = sjob2.unserializeFromJson(jsonStr.c_str(), jsonStr.length()); ASSERT_EQ(res, true); ASSERT_EQ( sjob2.prevHash_, uint256S("000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979" "c34")); ASSERT_EQ( sjob2.prevHashBeStr_, "03979c349a31fd2dc3fe929586643caabb46c03b532b2e774f2ea23900000000"); ASSERT_EQ(sjob2.height_, 898487); // 46 bytes, 5 bytes (timestamp), 9 bytes (poolCoinbaseInfo) // 02000000010000000000000000000000000000000000000000000000000000000000000000ffffffff1e03b7b50d // 0402363d58 2f4254432e434f4d2f ASSERT_EQ( sjob2.coinbase1_.substr(0, 92), "0200000001000000000000000000000000000000000000000000000000000000000000" "0000ffffffff1e03b7b50d"); ASSERT_EQ(sjob2.coinbase1_.substr(102, 18), "2f4254432e434f4d2f"); // 0402363d58 -> 0x583d3602 = 1480406530 = 2016-11-29 16:02:10 uint32_t ts = (uint32_t)strtoull(sjob2.coinbase1_.substr(94, 8).c_str(), nullptr, 16); ts = HToBe(ts); ASSERT_EQ(ts == time(nullptr) || ts + 1 == time(nullptr), true); ASSERT_EQ( sjob2.coinbase2_, "ffffffff" // sequence "01" // 1 output // c7cea21200000000 -> 0000000012a2cec7 -> 312659655 "c7cea21200000000" // 0x19 -> 25 bytes "1976a914ca560088c0fb5e6f028faa11085e643e343a8f5c88ac" // lock_time "00000000"); ASSERT_EQ(sjob2.merkleBranch_.size(), 1U); ASSERT_EQ( sjob2.merkleBranch_[0], uint256S("bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca7" "9ff")); ASSERT_EQ(sjob2.nVersion_, 536870912); ASSERT_EQ(sjob2.nBits_, 436308706U); ASSERT_EQ(sjob2.nTime_, 1469006933U); ASSERT_EQ(sjob2.minTime_, 1469001544U); ASSERT_EQ(sjob2.coinbaseValue_, 312659655); ASSERT_GE(time(nullptr), jobId2Time(sjob2.jobId_)); } } #ifdef CHAIN_TYPE_BTC TEST(Stratum, StratumJobWithWitnessCommitment) { StratumJobBitcoin sjob; string poolCoinbaseInfo = "/BTC.COM/"; uint32_t blockVersion = 0; bool res; { string gbt; gbt += "{\"result\":"; gbt += "{"; gbt += " \"capabilities\": ["; gbt += " \"proposal\""; gbt += " ],"; gbt += " \"version\": 536870912,"; gbt += " \"rules\": ["; gbt += " \"csv\","; gbt += " \"!segwit\""; gbt += " ],"; gbt += " \"vbavailable\": {"; gbt += " },"; gbt += " \"vbrequired\": 0,"; gbt += " \"previousblockhash\": " "\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803772\","; gbt += " \"transactions\": ["; gbt += " {"; gbt += " \"data\": " "\"0100000002449f651247d5c09d3020c30616cb1807c268e2c2346d1de28442b89ef3" "4c976d000000006a47304402203eae3868946a312ba712f9c9a259738fee6e3163b05d" "206e0f5b6c7980"; gbt += "161756022017827f248432f7313769f120fb3b7a65137bf93496a1ae7d6a775879fbdf" "b8cd0121027d7b71dab3bb16582c97fc0ccedeacd8f75ebee62fa9c388290294ee3bc3" "e935feffffffcbc82a21497f8db"; gbt += "8d57d054fefea52aba502a074ed984efc81ec2ef211194aa6010000006a47304402207" "f5462295e52fb4213f1e63802d8fe9ec020ac8b760535800564694ea87566a802205ee" "01096fc9268eac483136ce08250"; gbt += "6ac951a7dbc9e4ae24dca07ca2a1fdf2f30121023b86e60ef66fe8ace403a0d77d27c8" "0ba9ba5404ee796c47c03c73748e59d125feffffff0286c35b00000000001976a914ab" "29f668d284fd2d65cec5f098432"; gbt += "c4ece01055488ac8093dc14000000001976a914ac19d3fd17710e6b9a331022fe92c69" "3fdf6659588ac8dd70f00\","; gbt += " \"txid\": " "\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\","; gbt += " \"hash\": " "\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 37400,"; gbt += " \"sigops\": 8,"; gbt += " \"weight\": 1488"; gbt += " },"; gbt += " {"; gbt += " \"data\": " "\"0100000001043f5e73755b5c6919b4e361f4cae84c8805452de3df265a6e2d3d71cb" "cb385501000000da0047304402202b14552521cd689556d2e44d914caf2195da37b80d" "e4f8cd0fad9adf"; gbt += "7ef768ef022026fcddd992f447c39c48c3ce50c5960e2f086ebad455159ffc3e36a562" "4af2f501483045022100f2b893e495f41b22cd83df6908c2fa4f917fd7bce9f8da14e6" "ab362042e11f7d022075bc2451e"; gbt += "1cf2ae2daec0f109a3aceb6558418863070f5e84c94526201850324014752210263217" "8d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951ec" "7d3a9da9de171617026442fcd30"; gbt += "f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9143e9a" "6b79be836762c8ef591cf16b76af1327ced58790dfdf8c0000000017a9148ce5408cfe" "addb7ccb2545ded41ef47810945"; gbt += "4848700000000\","; gbt += " \"txid\": " "\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\","; gbt += " \"hash\": " "\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 20000,"; gbt += " \"sigops\": 8,"; gbt += " \"weight\": 1332"; gbt += " },"; gbt += " {"; gbt += " \"data\": " "\"01000000013faf73481d6b96c2385b9a4300f8974b1b30c34be30000c7dcef11f686" "62de4501000000db00483045022100f9881f4c867b5545f6d7a730ae26f598107171d0" "f68b860bd973db"; gbt += "b855e073a002207b511ead1f8be8a55c542ce5d7e91acfb697c7fa2acd2f322b47f177" "875bffc901483045022100a37aa9998b9867633ab6484ad08b299de738a86ae997133d" "827717e7ed73d953022011e3f99"; gbt += "d1bd1856f6a7dc0bf611de6d1b2efb60c14fc5931ba09da01558757f60147522102632" "178d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951" "ec7d3a9da9de171617026442fcd"; gbt += "30f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9148d" "57003ecbaa310a365f8422602cc507a702197e87806868a90000000017a9148ce5408c" "feaddb7ccb2545ded41ef478109"; gbt += "454848700000000\","; gbt += " \"txid\": " "\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\","; gbt += " \"hash\": " "\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 20000,"; gbt += " \"sigops\": 8,"; gbt += " \"weight\": 1336"; gbt += " },"; gbt += " ],"; gbt += " \"coinbaseaux\": {"; gbt += " \"flags\": \"\""; gbt += " },"; gbt += " \"coinbasevalue\": 319367518,"; gbt += " \"longpollid\": " "\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e98037726045" "97\","; gbt += " \"target\": " "\"0000000000001714480000000000000000000000000000000000000000000000\","; gbt += " \"mintime\": 1480831053,"; gbt += " \"mutable\": ["; gbt += " \"time\","; gbt += " \"transactions\","; gbt += " \"prevblock\""; gbt += " ],"; gbt += " \"noncerange\": \"00000000ffffffff\","; gbt += " \"sigoplimit\": 80000,"; gbt += " \"sizelimit\": 4000000,"; gbt += " \"weightlimit\": 4000000,"; gbt += " \"curtime\": 1480834892,"; gbt += " \"bits\": \"1a171448\","; gbt += " \"height\": 1038222,"; gbt += " \"default_witness_commitment\": " "\"6a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6" "9ed22bf8\""; gbt += "}}"; blockVersion = 0; SelectParams(CBaseChainParams::TESTNET); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"), true); CTxDestination poolPayoutAddrTestnet = BitcoinUtils::DecodeDestination("myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"); res = sjob.initFromGbt( gbt.c_str(), poolCoinbaseInfo, poolPayoutAddrTestnet, blockVersion, "", RskWork(), 1, false); ASSERT_EQ(res, true); const string jsonStr = sjob.serializeToJson(); StratumJobBitcoin sjob2; res = sjob2.unserializeFromJson(jsonStr.c_str(), jsonStr.length()); ASSERT_EQ(res, true); ASSERT_EQ( sjob2.prevHash_, uint256S("0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803" "772")); ASSERT_EQ( sjob2.prevHashBeStr_, "e98037722f631f70eeb00c155d52e0f3407654b2e5bda1220000004700000000"); ASSERT_EQ(sjob2.height_, 1038222); ASSERT_EQ( sjob2.coinbase2_, "ffffffff" // sequence "02" // 2 outputs // 5e29091300000000 -> 000000001309295e -> 319367518 "5e29091300000000" // 0x19 -> 25 bytes "1976a914ca560088c0fb5e6f028faa11085e643e343a8f5c88ac" // "0000000000000000" // 0x26 -> 38 bytes "266a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6" "9ed22bf8" // lock_time "00000000"); ASSERT_EQ(sjob2.nVersion_, 536870912); ASSERT_EQ(sjob2.nBits_, 0x1a171448U); ASSERT_EQ(sjob2.nTime_, 1480834892U); ASSERT_EQ(sjob2.minTime_, 1480831053U); ASSERT_EQ(sjob2.coinbaseValue_, 319367518); ASSERT_GE(time(nullptr), jobId2Time(sjob2.jobId_)); } } #endif #ifdef CHAIN_TYPE_BTC TEST(Stratum, StratumJobWithSegwitPayoutAddr) { StratumJobBitcoin sjob; string poolCoinbaseInfo = "/BTC.COM/"; uint32_t blockVersion = 0; bool res; { string gbt; gbt += "{\"result\":"; gbt += "{"; gbt += " \"capabilities\": ["; gbt += " \"proposal\""; gbt += " ],"; gbt += " \"version\": 536870912,"; gbt += " \"rules\": ["; gbt += " \"csv\","; gbt += " \"!segwit\""; gbt += " ],"; gbt += " \"vbavailable\": {"; gbt += " },"; gbt += " \"vbrequired\": 0,"; gbt += " \"previousblockhash\": " "\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803772\","; gbt += " \"transactions\": ["; gbt += " {"; gbt += " \"data\": " "\"0100000002449f651247d5c09d3020c30616cb1807c268e2c2346d1de28442b89ef3" "4c976d000000006a47304402203eae3868946a312ba712f9c9a259738fee6e3163b05d" "206e0f5b6c7980"; gbt += "161756022017827f248432f7313769f120fb3b7a65137bf93496a1ae7d6a775879fbdf" "b8cd0121027d7b71dab3bb16582c97fc0ccedeacd8f75ebee62fa9c388290294ee3bc3" "e935feffffffcbc82a21497f8db"; gbt += "8d57d054fefea52aba502a074ed984efc81ec2ef211194aa6010000006a47304402207" "f5462295e52fb4213f1e63802d8fe9ec020ac8b760535800564694ea87566a802205ee" "01096fc9268eac483136ce08250"; gbt += "6ac951a7dbc9e4ae24dca07ca2a1fdf2f30121023b86e60ef66fe8ace403a0d77d27c8" "0ba9ba5404ee796c47c03c73748e59d125feffffff0286c35b00000000001976a914ab" "29f668d284fd2d65cec5f098432"; gbt += "c4ece01055488ac8093dc14000000001976a914ac19d3fd17710e6b9a331022fe92c69" "3fdf6659588ac8dd70f00\","; gbt += " \"txid\": " "\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\","; gbt += " \"hash\": " "\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 37400,"; gbt += " \"sigops\": 8,"; gbt += " \"weight\": 1488"; gbt += " },"; gbt += " {"; gbt += " \"data\": " "\"0100000001043f5e73755b5c6919b4e361f4cae84c8805452de3df265a6e2d3d71cb" "cb385501000000da0047304402202b14552521cd689556d2e44d914caf2195da37b80d" "e4f8cd0fad9adf"; gbt += "7ef768ef022026fcddd992f447c39c48c3ce50c5960e2f086ebad455159ffc3e36a562" "4af2f501483045022100f2b893e495f41b22cd83df6908c2fa4f917fd7bce9f8da14e6" "ab362042e11f7d022075bc2451e"; gbt += "1cf2ae2daec0f109a3aceb6558418863070f5e84c94526201850324014752210263217" "8d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951ec" "7d3a9da9de171617026442fcd30"; gbt += "f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9143e9a" "6b79be836762c8ef591cf16b76af1327ced58790dfdf8c0000000017a9148ce5408cfe" "addb7ccb2545ded41ef47810945"; gbt += "4848700000000\","; gbt += " \"txid\": " "\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\","; gbt += " \"hash\": " "\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 20000,"; gbt += " \"sigops\": 8,"; gbt += " \"weight\": 1332"; gbt += " },"; gbt += " {"; gbt += " \"data\": " "\"01000000013faf73481d6b96c2385b9a4300f8974b1b30c34be30000c7dcef11f686" "62de4501000000db00483045022100f9881f4c867b5545f6d7a730ae26f598107171d0" "f68b860bd973db"; gbt += "b855e073a002207b511ead1f8be8a55c542ce5d7e91acfb697c7fa2acd2f322b47f177" "875bffc901483045022100a37aa9998b9867633ab6484ad08b299de738a86ae997133d" "827717e7ed73d953022011e3f99"; gbt += "d1bd1856f6a7dc0bf611de6d1b2efb60c14fc5931ba09da01558757f60147522102632" "178d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951" "ec7d3a9da9de171617026442fcd"; gbt += "30f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9148d" "57003ecbaa310a365f8422602cc507a702197e87806868a90000000017a9148ce5408c" "feaddb7ccb2545ded41ef478109"; gbt += "454848700000000\","; gbt += " \"txid\": " "\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\","; gbt += " \"hash\": " "\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 20000,"; gbt += " \"sigops\": 8,"; gbt += " \"weight\": 1336"; gbt += " },"; gbt += " ],"; gbt += " \"coinbaseaux\": {"; gbt += " \"flags\": \"\""; gbt += " },"; gbt += " \"coinbasevalue\": 319367518,"; gbt += " \"longpollid\": " "\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e98037726045" "97\","; gbt += " \"target\": " "\"0000000000001714480000000000000000000000000000000000000000000000\","; gbt += " \"mintime\": 1480831053,"; gbt += " \"mutable\": ["; gbt += " \"time\","; gbt += " \"transactions\","; gbt += " \"prevblock\""; gbt += " ],"; gbt += " \"noncerange\": \"00000000ffffffff\","; gbt += " \"sigoplimit\": 80000,"; gbt += " \"sizelimit\": 4000000,"; gbt += " \"weightlimit\": 4000000,"; gbt += " \"curtime\": 1480834892,"; gbt += " \"bits\": \"1a171448\","; gbt += " \"height\": 1038222,"; gbt += " \"default_witness_commitment\": " "\"6a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6" "9ed22bf8\""; gbt += "}}"; blockVersion = 0; SelectParams(CBaseChainParams::TESTNET); ASSERT_EQ( BitcoinUtils::IsValidDestinationString( "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7"), true); CTxDestination poolPayoutAddrTestnet = BitcoinUtils::DecodeDestination( "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7"); res = sjob.initFromGbt( gbt.c_str(), poolCoinbaseInfo, poolPayoutAddrTestnet, blockVersion, "", RskWork(), 1, false); ASSERT_EQ(res, true); const string jsonStr = sjob.serializeToJson(); StratumJobBitcoin sjob2; res = sjob2.unserializeFromJson(jsonStr.c_str(), jsonStr.length()); ASSERT_EQ(res, true); ASSERT_EQ( sjob2.prevHash_, uint256S("0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803" "772")); ASSERT_EQ( sjob2.prevHashBeStr_, "e98037722f631f70eeb00c155d52e0f3407654b2e5bda1220000004700000000"); ASSERT_EQ(sjob2.height_, 1038222); ASSERT_EQ( sjob2.coinbase2_, "ffffffff" // sequence "02" // 2 outputs // 5e29091300000000 -> 000000001309295e -> 319367518 "5e29091300000000" // 0x22 -> 34 bytes "2200201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262" // "0000000000000000" // 0x26 -> 38 bytes "266a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6" "9ed22bf8" // lock_time "00000000"); ASSERT_EQ(sjob2.nVersion_, 536870912); ASSERT_EQ(sjob2.nBits_, 0x1a171448U); ASSERT_EQ(sjob2.nTime_, 1480834892U); ASSERT_EQ(sjob2.minTime_, 1480831053U); ASSERT_EQ(sjob2.coinbaseValue_, 319367518); ASSERT_GE(time(nullptr), jobId2Time(sjob2.jobId_)); } } #endif #ifdef CHAIN_TYPE_BTC TEST(Stratum, StratumJobWithRskWork) { StratumJobBitcoin sjob; RskWork rskWork; string poolCoinbaseInfo = "/BTC.COM/"; uint32_t blockVersion = 0; { string gbt; gbt += "{\"result\":{"; gbt += " \"capabilities\": ["; gbt += " \"proposal\""; gbt += " ],"; gbt += " \"version\": 536870912,"; gbt += " \"previousblockhash\": " "\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c34\","; gbt += " \"transactions\": ["; gbt += " {"; gbt += " \"data\": " "\"01000000010291939c5ae8191c2e7d4ce8eba7d6616a66482e3200037cb8b8c2d0af" "45b445000000006a47304402204df709d9e149804e358de4b082e41d8bb21b3c9d3472" "41b728b1362aafcb153602200d06d9b6f2eca899f43dcd62ec2efb2d9ce2e10adf0273" "8bb908420d7db93ede012103cae98ab925e20dd6ae1f76e767e9e99bc47b3844095c68" "600af9c775104fb36cffffffff0290f1770b000000001976a91400dc5fd62f6ee48eb8" "ecda749eaec6824a780fdd88aca08601000000000017a914eb65573e5dd52d3d950396" "ccbe1a47daf8f400338700000000\","; gbt += " \"hash\": " "\"bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca79ff\","; gbt += " \"depends\": ["; gbt += " ],"; gbt += " \"fee\": 10000,"; gbt += " \"sigops\": 1"; gbt += " }"; gbt += " ],"; gbt += " \"coinbaseaux\": {"; gbt += " \"flags\": \"\""; gbt += " },"; gbt += " \"coinbasevalue\": 312659655,"; gbt += " \"longpollid\": " "\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c341911" "\","; gbt += " \"target\": " "\"000000000000018ae20000000000000000000000000000000000000000000000\","; gbt += " \"mintime\": 1469001544,"; gbt += " \"mutable\": ["; gbt += " \"time\","; gbt += " \"transactions\","; gbt += " \"prevblock\""; gbt += " ],"; gbt += " \"noncerange\": \"00000000ffffffff\","; gbt += " \"sigoplimit\": 20000,"; gbt += " \"sizelimit\": 1000000,"; gbt += " \"curtime\": 1469006933,"; gbt += " \"bits\": \"1a018ae2\","; gbt += " \"height\": 898487"; gbt += "}}"; uint32_t creationTime = (uint32_t)time(nullptr); string rawgw; rawgw = Strings::Format( "{\"created_at_ts\": %u," "\"rskdRpcAddress\":\"http://10.0.2.2:4444\"," "\"rskdRpcUserPwd\":\"user:pass\"," "\"target\":" "\"0x5555555555555555555555555555555555555555555555555555555555555555\"" "," "\"parentBlockHash\":" "\"0x13532f616f89e3ac2e0a9ef7363be28e7f2ca39764684995fb30c0d96e664ae4\"" "," "\"blockHashForMergedMining\":" "\"0xe6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8364604e9f8a15d\"" "," "\"feesPaidToMiner\":\"0\"," "\"notify\":\"true\"}", creationTime); blockVersion = 0; SelectParams(CBaseChainParams::TESTNET); bool resInitRskWork = rskWork.initFromGw(rawgw); ASSERT_TRUE(resInitRskWork); ASSERT_EQ(rskWork.isInitialized(), true); ASSERT_EQ(rskWork.getCreatedAt(), creationTime); ASSERT_EQ( rskWork.getBlockHash(), "0xe6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8364604e9f8a15d"); ASSERT_EQ( rskWork.getTarget(), "0x5555555555555555555555555555555555555555555555555555555555555555"); ASSERT_EQ(rskWork.getFees(), "0"); ASSERT_EQ(rskWork.getRpcAddress(), "http://10.0.2.2:4444"); ASSERT_EQ(rskWork.getRpcUserPwd(), "user:pass"); ASSERT_EQ(rskWork.getNotifyFlag(), true); CTxDestination poolPayoutAddrTestnet = BitcoinUtils::DecodeDestination("myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"); sjob.initFromGbt( gbt.c_str(), poolCoinbaseInfo, poolPayoutAddrTestnet, blockVersion, "", rskWork, 1, true); // check rsk required data copied properly to the stratum job ASSERT_EQ( sjob.blockHashForMergedMining_, "0xe6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8364604e9f8a15d"); ASSERT_EQ( sjob.rskNetworkTarget_, uint256S("0x55555555555555555555555555555555555555555555555555555555555" "55555")); ASSERT_EQ(sjob.feesForMiner_, "0"); ASSERT_EQ(sjob.rskdRpcAddress_, "http://10.0.2.2:4444"); ASSERT_EQ(sjob.rskdRpcUserPwd_, "user:pass"); ASSERT_EQ(sjob.isMergedMiningCleanJob_, true); // check rsk merged mining tag present in the coinbase // Hex("RSKBLOCK:") = 0x52534b424c4f434b3a string rskTagHex = "52534b424c4f434b3ae6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae836" "4604e9f8a15d"; size_t rskTagPos = sjob.coinbase2_.find(rskTagHex); ASSERT_NE(rskTagPos, string::npos); ASSERT_EQ( sjob.prevHash_, uint256S("000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979" "c34")); ASSERT_EQ( sjob.prevHashBeStr_, "03979c349a31fd2dc3fe929586643caabb46c03b532b2e774f2ea23900000000"); ASSERT_EQ(sjob.height_, 898487); // 46 bytes, 5 bytes (timestamp), 9 bytes (poolCoinbaseInfo) // 02000000010000000000000000000000000000000000000000000000000000000000000000ffffffff1e03b7b50d // 0402363d58 2f4254432e434f4d2f ASSERT_EQ( sjob.coinbase1_.substr(0, 92), "0200000001000000000000000000000000000000000000000000000000000000000000" "0000ffffffff1e03b7b50d"); ASSERT_EQ(sjob.coinbase1_.substr(102, 18), "2f4254432e434f4d2f"); // 0402363d58 -> 0x583d3602 = 1480406530 = 2016-11-29 16:02:10 uint32_t ts = (uint32_t)strtoull(sjob.coinbase1_.substr(94, 8).c_str(), nullptr, 16); ts = HToBe(ts); ASSERT_EQ(ts == time(nullptr) || ts + 1 == time(nullptr), true); ASSERT_EQ( sjob.coinbase2_, "ffffffff" // sequence "02" // 2 outputs. Rsk tag is stored in an additional CTxOut besides the // cb's standard output // c7cea21200000000 -> 0000000012a2cec7 -> 312659655 "c7cea21200000000" // 0x19 -> 25 bytes of first output script "1976a914ca560088c0fb5e6f028faa11085e643e343a8f5c88ac" // rsk tx out value "0000000000000000" // 0x29 = 41 bytes of second output script containing the rsk merged // mining tag "2952534b424c4f434b3ae6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8" "364604e9f8a15d" // lock_time "00000000"); ASSERT_EQ(sjob.merkleBranch_.size(), 1U); ASSERT_EQ( sjob.merkleBranch_[0], uint256S("bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca7" "9ff")); ASSERT_EQ(sjob.nVersion_, 536870912); ASSERT_EQ(sjob.nBits_, 436308706U); ASSERT_EQ(sjob.nTime_, 1469006933U); ASSERT_EQ(sjob.minTime_, 1469001544U); ASSERT_EQ(sjob.coinbaseValue_, 312659655); ASSERT_GE(time(nullptr), jobId2Time(sjob.jobId_)); } } #endif
35.269857
99
0.640739
vpashka
beb0e6d6183bbf6bb8da617438c661f83e3ccafe
1,691
cpp
C++
BZOJ/4896.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
BZOJ/4896.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
BZOJ/4896.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> #include <vector> using namespace std; typedef long long lint; #define ni (next_num<int>()) #define nl (next_num<lint>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool flag=c=='-'; flag?(c=getchar()):0; while(i=i*10-'0'+c,isdigit(c=getchar())); return flag?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){ if(a<b){ a=b; } } template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){ if(a>b){ a=b; } } inline int abs(int x){ return x>=0?x:-x; } const int L=65,SIGMA=26,N=100010; char s[L]; struct Trie{ typedef Trie* node; int val; vector<int>q; node son[SIGMA]; Trie(){ memset(son,0,sizeof(son)); q.push_back(0); val=0; } inline void update(int id){ val++; if(val==q.size()){ q.push_back(id); assert(q[val]==id); } } inline node go(int c){ c-='a'; if(son[c]==0){ son[c]=new Trie(); } return son[c]; } inline void insert(char *s,int id){ for(node pt=this;pt->update(id),*s;pt=pt->go(*s),s++); } inline void del(char *s){ for(node pt=this;pt->val--,*s;pt=pt->son[(*s)-'a'],s++); } inline node find(char *s){ node pt=this; for(;*s;pt=pt->son[(*s)-'a'],s++); return pt; } }trie; inline int work(Trie *pt,int ans){ lint a=nl,b=nl,c=nl; lint x=(a*abs(ans)+b)%c+1; if(pt->q.size()<=x){ return -1; } return pt->q[x]; } int main(){ int ans=0; for(int i=1,n=ni;i<=n;i++){ int k=ni; scanf("%s",s); if(k==1){ trie.insert(s,i); }else if(k==2){ trie.del(s); }else{ assert(k==3); printf("%d\n",ans=work(trie.find(s),ans)); } } }
18.182796
64
0.583678
sshockwave
beb86b042dc547fbe7ac9c8cc6a4a39888c5251a
6,646
cpp
C++
Common/utils/iStyle/ASResource.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/utils/iStyle/ASResource.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/utils/iStyle/ASResource.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
// $Id: ASResource.cpp,v 1.2 2004/02/04 07:35:10 devsolar Exp $ // -------------------------------------------------------------------------- // // Copyright (c) 1998,1999,2000,2001,2002 Tal Davidson. All rights reserved. // // compiler_defines.h // by Tal Davidson ([email protected]) // // This file is a part of "Artistic Style" - an indentater and reformatter // of C, C++, C# and Java source files. // // -------------------------------------------------------------------------- // // 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // -------------------------------------------------------------------------- #include "compiler_defines.h" #include "astyle.h" #include <string> #ifdef USES_NAMESPACE using namespace std; namespace astyle { #endif const string ASResource::AS_IF = string("if"); const string ASResource::AS_ELSE = string ("else"); const string ASResource::AS_FOR = string("for"); const string ASResource::AS_WHILE = string("while"); const string ASResource::AS_SWITCH = string ("switch"); const string ASResource::AS_DEFAULT = string("default"); const string ASResource::PRO_CELLDEFINE = string("`celldefine"); const string ASResource::PRO_DEFAULT_NETTYPE = string("`default_nettype"); const string ASResource::PRO_DEFINE = string("`define"); const string ASResource::PRO_ELSE = string("`else"); const string ASResource::PRO_ENDCELLDEFINE = string("`endcelldefine"); const string ASResource::PRO_ENDIF = string("`endif"); const string ASResource::PRO_IFDEF = string("`ifdef"); const string ASResource::PRO_INCLUDE = string("`include"); const string ASResource::PRO_NOUNCONNECTED_DRIVE = string("`nounconnected_drive"); const string ASResource::PRO_RESETALL = string("`resetall"); const string ASResource::PRO_TIMESCALE = string("`timescale"); const string ASResource::PRO_UNCONNECTED_DRIVE = string("`unconnected_drive"); const string ASResource::PRO_UNDEF = string("`undef"); const string ASResource::PRO_IMPORT = string("import"); const string ASResource::AS_OPEN_BRACKET = string("{"); const string ASResource::AS_CLOSE_BRACKET = string("}"); const string ASResource::AS_OPEN_LINE_COMMENT = string("//"); const string ASResource::AS_OPEN_COMMENT = string("/*"); const string ASResource::AS_CLOSE_COMMENT = string("*/"); const string ASResource::AS_ASSIGN = string("="); const string ASResource::AS_LS_ASSIGN = string("<="); const string ASResource::AS_EQUAL = string("=="); const string ASResource::AS_NOT_EQUAL = string("!="); const string ASResource::AS_EQUAL_EQUAL = string("==="); const string ASResource::AS_NOT_EQUAL_EQUAL = string("!=="); const string ASResource::AS_BITNOT_AND = string("~&"); const string ASResource::AS_BITNOT_OR = string("~|"); const string ASResource::AS_BITNOT_XNOR = string("~^"); const string ASResource::AS_NOT_XNOR = string("^~"); const string ASResource::AS_GR_EQUAL = string(">="); const string ASResource::AS_GR_GR = string(">>"); const string ASResource::AS_LS_EQUAL = string("<="); const string ASResource::AS_LS_LS = string("<<"); const string ASResource::AS_AND = string("&&"); const string ASResource::AS_OR = string("||"); const string ASResource::AS_PAREN_PAREN = string("()"); const string ASResource::AS_BLPAREN_BLPAREN = string("[]"); const string ASResource::AS_PLUS = string("+"); const string ASResource::AS_MINUS = string("-"); const string ASResource::AS_MULT = string("*"); const string ASResource::AS_DIV = string("/"); const string ASResource::AS_MOD = string("%"); const string ASResource::AS_GR = string(">"); const string ASResource::AS_LS = string("<"); const string ASResource::AS_NOT = string("!"); const string ASResource::AS_BIT_OR = string("|"); const string ASResource::AS_BIT_AND = string("&"); const string ASResource::AS_BIT_NOT = string("~"); const string ASResource::AS_BIT_XOR = string("^"); const string ASResource::AS_QUESTION = string("?"); const string ASResource::AS_COLON = string(":"); const string ASResource::AS_COMMA = string(","); const string ASResource::AS_SEMICOLON = string(";"); const string ASResource::AS_INITIAL = string("initial"); const string ASResource::AS_FOREVER = string("forever"); const string ASResource::AS_ALWAYS = string("always"); const string ASResource::AS_REPEAT = string("repeat"); const string ASResource::AS_CASE = string("case" ); const string ASResource::AS_CASEX = string("casex" ); const string ASResource::AS_CASEZ = string("casez" ); const string ASResource::AS_FUNCTION = string("function" ); const string ASResource::AS_GENERATE = string("generate" ); const string ASResource::AS_FORK = string("fork" ); const string ASResource::AS_TABLE = string("table" ); const string ASResource::AS_TASK = string("task" ); const string ASResource::AS_SPECIFY = string("specify" ); const string ASResource::AS_PRIMITIVE = string("primitive"); //const string ASResource::AS_MODULE = string("module" ); const string ASResource::AS_BEGIN = string("begin" ); const string ASResource::AS_ENDCASE = string("endcase" ); const string ASResource::AS_ENDFUNCTION = string("endfunction" ); const string ASResource::AS_ENDGENERATE = string("endgenerate" ); const string ASResource::AS_JOIN = string("join" ); const string ASResource::AS_ENDTASK = string("endtask" ); const string ASResource::AS_ENDTABLE = string("endtable" ); const string ASResource::AS_ENDSPECIFY = string("endspecify" ); const string ASResource::AS_ENDPRIMITIVE = string("endprimitive" ); //const string ASResource::AS_ENDMODULE = string("endmodule" ); const string ASResource::AS_END = string("end" ); const char ASResource::PREPROCESSOR_CHAR ='`'; #ifdef USES_NAMESPACE } #endif
43.437908
84
0.671532
testdrive-profiling-master
beb879e76be433f8d05e2a88d7fabb47b17c7273
13,202
cpp
C++
example/FieldContainer/example_01.cpp
Sandia2014/intrepid
9a310ddc033da1dda162a09bf80cca6c2dde2d6b
[ "MIT" ]
null
null
null
example/FieldContainer/example_01.cpp
Sandia2014/intrepid
9a310ddc033da1dda162a09bf80cca6c2dde2d6b
[ "MIT" ]
null
null
null
example/FieldContainer/example_01.cpp
Sandia2014/intrepid
9a310ddc033da1dda162a09bf80cca6c2dde2d6b
[ "MIT" ]
null
null
null
// @HEADER // ************************************************************************ // // Intrepid Package // Copyright (2007) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Pavel Bochev ([email protected]) // Denis Ridzal ([email protected]), or // Kara Peterson ([email protected]) // // ************************************************************************ // @HEADER /** \file \brief Illustrates use of the FieldContainer class. \author Created by P. Bochev and D. Ridzal */ #include "Intrepid_FieldContainer.hpp" #include "Teuchos_Time.hpp" #include "Teuchos_GlobalMPISession.hpp" using namespace std; using namespace Intrepid; int main(int argc, char *argv[]) { Teuchos::GlobalMPISession mpiSession(&argc, &argv); std::cout \ << "===============================================================================\n" \ << "| |\n" \ << "| Example use of the FieldContainer class |\n" \ << "| |\n" \ << "| 1) Creating and filling FieldContainer objects |\n" \ << "| 2) Accessing elements in FieldContainer objects |\n" \ << "| |\n" \ << "| Questions? Contact Pavel Bochev ([email protected]) or |\n" \ << "| Denis Ridzal ([email protected]). |\n" \ << "| |\n" \ << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \ << "| Trilinos website: http://trilinos.sandia.gov |\n" \ << "| |\n" \ << "===============================================================================\n\n"; // Define variables to create and use FieldContainers Teuchos::Array<int> dimension; Teuchos::Array<int> multiIndex; std::cout \ << "===============================================================================\n"\ << "| EXAMPLE 1: rank 2 multi-index: {u(p,i) | 0 <= p < 5; 0 <= i < 3 } |\n"\ << "===============================================================================\n\n"; // This rank 2 multi-indexed value can be used to store values of 3D vector field // evaluated at 5 points, or values of gradient of scalar field evaluated at the points // Resize dimension and multiIndex for rank-2 multi-indexed value dimension.resize(2); multiIndex.resize(2); // Load upper ranges for the two indices in the multi-indexed value dimension[0] = 5; dimension[1] = 3; // Create FieldContainer that can hold the rank-2 multi-indexed value FieldContainer<double> myContainer(dimension); // Fill with some data: leftmost index changes last, rightmost index changes first! for(int p = 0; p < dimension[0]; p++){ multiIndex[0] = p; for(int i = 0; i < dimension[1]; i++){ multiIndex[1] = i; // Load value with multi-index {p,i} to container myContainer.setValue((double)(i+p), multiIndex); } } // Show container contents std::cout << myContainer; // Access by overloaded (), multiindex and []: multiIndex[0] = 3; multiIndex[1] = 1; int enumeration = myContainer.getEnumeration(multiIndex); std::cout << "Access by (): myContainer(" << 3 <<"," << 1 << ") = " << myContainer(3,1) << "\n"; std::cout << "Access by multi-index: myContainer{" << multiIndex[0] << multiIndex[1] << "} = "<< myContainer.getValue(multiIndex) <<"\n"; std::cout << "Access by enumeration: myContainer[" << enumeration << "] = " << myContainer[enumeration] <<"\n"; std::cout << "Assigning value by (): \n old value at (3,1) = " << myContainer(3,1) <<"\n"; myContainer(3,1) = 999.99; std::cout << " new value at (3,1) = " << myContainer(3,1) <<"\n"; std::cout << "\n" \ << "===============================================================================\n"\ << "| EXAMPLE 2: rank 3 multi-index: {u(p,i,j) | 0 <=p< 5; 0 <= i<2, 0<=j<3 |\n"\ << "===============================================================================\n\n"; // This rank-3 value can be used to store subset of second partial derivatives values // of a scalar function at p points. // Resize dimension and multiIndex for rank-3 multi-indexed value dimension.resize(3); multiIndex.resize(3); // Define upper ranges for the three indices in the multi-indexed value dimension[0] = 5; dimension[1] = 2; dimension[2] = 3; // Reset the existing container to accept rank-3 value with the specified index ranges myContainer.resize(dimension); // Fill with some data for(int p = 0; p < dimension[0]; p++){ multiIndex[0] = p; for(int i = 0; i < dimension[1]; i++){ multiIndex[1] = i; for(int j = 0; j < dimension[2]; j++){ multiIndex[2] = j; // Load value with multi-index {p,i} to container myContainer.setValue((double)(p+i+j), multiIndex); } } } // Display contents std::cout << myContainer; // Access by overloaded (), multiindex and []: multiIndex[0] = 3; multiIndex[1] = 1; multiIndex[2] = 2; enumeration = myContainer.getEnumeration(multiIndex); std::cout << "Access by (): myContainer(" << 3 <<"," << 1 << "," << 2 << ") = " << myContainer(3,1,2) << "\n"; std::cout << "Access by multi-index: myContainer{" << multiIndex[0] << multiIndex[1] << multiIndex[2] << "} = "<< myContainer.getValue(multiIndex) <<"\n"; std::cout << "Access by enumeration: myContainer[" << enumeration << "] = " << myContainer[enumeration] <<"\n"; std::cout << "Assigning value by (): \n old value at (3,1,2) = " << myContainer(3,1,2) <<"\n"; myContainer(3,1,2) = -999.999; std::cout << " new value at (3,1,2) = " << myContainer(3,1,2) <<"\n"; std::cout << "\n" \ << "===============================================================================\n"\ << "| EXAMPLE 4: making rank-5 FieldContainer from data array and index range array |\n"\ << "===============================================================================\n\n"; // Initialize dimension for rank-5 multi-index value dimension.resize(5); dimension[0] = 5; dimension[1] = 2; dimension[2] = 3; dimension[3] = 4; dimension[4] = 6; // Define Teuchos::Array to store values with dimension equal to the number of multi-indexed values Teuchos::Array<double> dataTeuchosArray(5*2*3*4*6); // Fill with data int counter = 0; for(int i=0; i < dimension[0]; i++){ for(int j=0; j < dimension[1]; j++){ for(int k=0; k < dimension[2]; k++){ for(int l = 0; l < dimension[3]; l++){ for(int m = 0; m < dimension[4]; m++){ dataTeuchosArray[counter] = (double)counter; counter++; } } } } } // Create FieldContainer from data array and index array and show it FieldContainer<double> myNewContainer(dimension, dataTeuchosArray); std::cout << myNewContainer; // Access by overloaded (), multiindex and []: multiIndex.resize(myNewContainer.rank()); multiIndex[0] = 3; multiIndex[1] = 1; multiIndex[2] = 2; multiIndex[3] = 2; multiIndex[4] = 5; enumeration = myNewContainer.getEnumeration(multiIndex); std::cout << "Access by (): myNewContainer(" << 3 <<"," << 1 << "," << 2 << "," << 2 << "," << 5 << ") = " << myNewContainer(3,1,2,2,5) << "\n"; std::cout << "Access by multi-index: myNewContainer{" << multiIndex[0] << multiIndex[1] << multiIndex[2] << multiIndex[3] << multiIndex[4] << "} = "<< myNewContainer.getValue(multiIndex) <<"\n"; std::cout << "Access by enumeration: myNewContainer[" << enumeration << "] = " << myNewContainer[enumeration] <<"\n"; std::cout << "Assigning value by (): \n old value at (3,1,2,2,5) = " << myNewContainer(3,1,2,2,5) <<"\n"; myNewContainer(3,1,2,2,5) = -888.888; std::cout << " new value at (3,1,2,2,5) = " << myNewContainer(3,1,2,2,5) <<"\n"; std::cout << "\n" \ << "===============================================================================\n"\ << "| EXAMPLE 5: making trivial FieldContainers and storing a single zero |\n"\ << "===============================================================================\n\n"; // Make trivial container by resetting the index range to zero rank (no indices) and then // using resize method dimension.resize(0); myContainer.resize(dimension); std::cout << myContainer; // Make trivial container by using clear method: myNewContainer.clear(); std::cout << myNewContainer; // Now use initialize() to reset the container to hold a single zero myNewContainer.initialize(); std::cout << myNewContainer; std::cout << "\n" \ << "===============================================================================\n"\ << "| EXAMPLE 6: Timing read and write operations using () and getValue |\n"\ << "===============================================================================\n\n"; // Initialize dimensions for rank-5 multi-index value int dim0 = 10; // number of cells int dim1 = 50; // number of points int dim2 = 27; // number of functions int dim3 = 3; // 1st space dim int dim4 = 3; // 2nd space dim FieldContainer<double> myTensorContainer(dim0, dim1, dim2, dim3, dim4); multiIndex.resize(myTensorContainer.rank()); double aValue; Teuchos::Time timerGetValue("Reading and writing from rank-5 container using getValue"); timerGetValue.start(); for(int i0 = 0; i0 < dim0; i0++){ multiIndex[0] = i0; for(int i1 = 0; i1 < dim1; i1++){ multiIndex[1] = i1; for(int i2 = 0; i2 < dim2; i2++) { multiIndex[2] = i2; for(int i3 = 0; i3 < dim3; i3++) { multiIndex[3] = i3; for(int i4 =0; i4 < dim4; i4++) { multiIndex[4] = i4; aValue = myTensorContainer.getValue(multiIndex); myTensorContainer.setValue(999.999,multiIndex); } } } } } timerGetValue.stop(); std::cout << " Time to read and write from container using getValue: " << timerGetValue.totalElapsedTime() <<"\n"; Teuchos::Time timerRound("Reading and writing from rank-5 container using ()"); timerRound.start(); for(int i0 = 0; i0 < dim0; i0++){ for(int i1 = 0; i1 < dim1; i1++) { for(int i2 = 0; i2 < dim2; i2++) { for(int i3 = 0; i3 < dim3; i3++) { for(int i4 =0; i4 < dim4; i4++) { aValue = myTensorContainer(i0,i1,i2,i3,i4); myTensorContainer(i0,i1,i2,i3,i4) = 999.999; } } } } } timerRound.stop(); std::cout << " Time to read and write from container using (): " << timerRound.totalElapsedTime() <<"\n"; std::cout << "\n" \ << "===============================================================================\n"\ << "| EXAMPLE 6: Specialized methods of FieldContainer |\n"\ << "===============================================================================\n\n"; return 0; }
41.127726
196
0.522269
Sandia2014
beba7f22985606f3d10d46aa8181f390f0d1d17c
6,940
hpp
C++
src/si_derived.hpp
DarthPigrum/TypeSI
3505cad5113c1c6c907c48b3bd71e24e9ddb32bc
[ "BSL-1.0" ]
null
null
null
src/si_derived.hpp
DarthPigrum/TypeSI
3505cad5113c1c6c907c48b3bd71e24e9ddb32bc
[ "BSL-1.0" ]
null
null
null
src/si_derived.hpp
DarthPigrum/TypeSI
3505cad5113c1c6c907c48b3bd71e24e9ddb32bc
[ "BSL-1.0" ]
null
null
null
#pragma once /// @file si_derived.hpp /// @brief Derived SI units #include "si_base.hpp" #include <utility> namespace Si { /// @brief Derived SI units namespace Derived { /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Hertz = decltype(std::declval<Internal::Dimensionless<T>>() / std::declval<Base::Second<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Newton = decltype( std::declval<Base::Kilogram<T>>() * std::declval<Base::Meter<T>>() / (std::declval<Base::Second<T>>() * std::declval<Base::Second<T>>())); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Pascal = decltype(std::declval<Newton<T>>() / (std::declval<Base::Meter<T>>() * std::declval<Base::Meter<T>>())); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Joule = decltype(std::declval<Base::Meter<T>>() * std::declval<Newton<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Watt = decltype(std::declval<Joule<T>>() / std::declval<Base::Second<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Coulomb = decltype(std::declval<Base::Second<T>>() * std::declval<Base::Ampere<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Volt = decltype(std::declval<Watt<T>>() / std::declval<Base::Ampere<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Farad = decltype(std::declval<Coulomb<T>>() / std::declval<Volt<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Ohm = decltype(std::declval<Volt<T>>() / std::declval<Base::Ampere<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Siemens = decltype(std::declval<Base::Ampere<T>>() / std::declval<Volt<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Weber = decltype(std::declval<Joule<T>>() / std::declval<Base::Ampere<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Tesla = decltype(std::declval<Newton<T>>() / (std::declval<Base::Ampere<T>>() * std::declval<Base::Meter<T>>())); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Henry = decltype(std::declval<Weber<T>>() / std::declval<Base::Ampere<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Lumen = Base::Candela<T>; /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Lux = decltype(std::declval<Lumen<T>>() / (std::declval<Base::Meter<T>>() * std::declval<Base::Meter<T>>())); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Becquerel = Hertz<T>; /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Gray = decltype(std::declval<Joule<T>>() / std::declval<Base::Kilogram<T>>()); /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Sievert = Gray<T>; /// @tparam T Any number type such as float, double or long double used as a /// container template <typename T> using Katal = decltype(std::declval<Base::Mole<T>>() / std::declval<Base::Second<T>>()); /// @brief Use this namespace to enable literals for base units namespace Literals { /// @brief _m long double literal for hertz Hertz<long double> operator"" _Hz(long double value) { return Hertz<long double>(value); } /// @brief _kg long double literal for newton Newton<long double> operator"" _N(long double value) { return Newton<long double>(value); } /// @brief _s long double literal for pascal Pascal<long double> operator"" _Pa(long double value) { return Pascal<long double>(value); } /// @brief _A long double literal for joule Joule<long double> operator"" _J(long double value) { return Joule<long double>(value); } /// @brief _K long double literal for watt Watt<long double> operator"" _W(long double value) { return Watt<long double>(value); } /// @brief _mol long double literal for coulomb Coulomb<long double> operator"" _C(long double value) { return Coulomb<long double>(value); } /// @brief _cd long double literal for volt Volt<long double> operator"" _V(long double value) { return Volt<long double>(value); } /// @brief _cd long double literal for farad Farad<long double> operator"" _F(long double value) { return Farad<long double>(value); } /// @brief _cd long double literal for ohm(not as defined by standard because of /// non-ASCII symbol) Ohm<long double> operator"" _Ohm(long double value) { return Ohm<long double>(value); } /// @brief _cd long double literal for siemens Siemens<long double> operator"" _S(long double value) { return Siemens<long double>(value); } /// @brief _cd long double literal for weber Weber<long double> operator"" _Wb(long double value) { return Weber<long double>(value); } /// @brief _cd long double literal for tesla Tesla<long double> operator"" _T(long double value) { return Tesla<long double>(value); } /// @brief _cd long double literal for henry Henry<long double> operator"" _H(long double value) { return Henry<long double>(value); } /// @brief _cd long double literal for lumen Lumen<long double> operator"" _lm(long double value) { return Lumen<long double>(value); } /// @brief _cd long double literal for lux Lux<long double> operator"" _lx(long double value) { return Lux<long double>(value); } /// @brief _cd long double literal for becquerel Becquerel<long double> operator"" _Bq(long double value) { return Becquerel<long double>(value); } /// @brief _cd long double literal for gray Gray<long double> operator"" _Gy(long double value) { return Gray<long double>(value); } /// @brief _cd long double literal for sievert Sievert<long double> operator"" _Sv(long double value) { return Sievert<long double>(value); } /// @brief _cd long double literal for katal Katal<long double> operator"" _kat(long double value) { return Katal<long double>(value); } } // namespace Literals } // namespace Derived } // namespace Si
38.131868
80
0.692507
DarthPigrum
bebcf0902de4b69fe2a506c8136d4c024ee247d5
3,274
cpp
C++
Source/Array-1-RemoveDups.cpp
KarateSnoopy/LeetCodeSubmissions
6da0c71e4104a43aea7a5029597685739b9f31b2
[ "MIT" ]
null
null
null
Source/Array-1-RemoveDups.cpp
KarateSnoopy/LeetCodeSubmissions
6da0c71e4104a43aea7a5029597685739b9f31b2
[ "MIT" ]
null
null
null
Source/Array-1-RemoveDups.cpp
KarateSnoopy/LeetCodeSubmissions
6da0c71e4104a43aea7a5029597685739b9f31b2
[ "MIT" ]
null
null
null
// LeetCode.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> //int x = input[inputSize - 1]; //for (int i = inputSize - 1; i > 0; i--) //{ // input[i] = input[i - 1]; //} //input[0] = x; //while (numsSize > 0) //{ // numsSize -= 1; //} // nums = { 2, 2, 3, 4 }. numSize = 4; int removeDuplicates(int* nums, int numsSize) { int x = 1; int y = 2; while( y < numsSize && x < numsSize ) { if (nums[x] == nums[y]) { y++; } else { nums[x] = nums[y]; x++; y++; } } int length = 0; return length; } // // //int removeDuplicates(int* nums, int numsSize) //{ // if (numsSize <= 1 || nums == NULL) // { // return numsSize; // } // // int oldLength = numsSize; // int* p1 = nums + 0; // int* p2 = nums + 0; // int newLength = 1; // // while (p2 < nums + numsSize) // p2 < nums[1] if numsSize == 2 // { // if (*p1 == *p2) // { // p2++; // } // else // { // p1++; // *p1 = *p2; // newLength++; // if (p2 == nums + numsSize - 1) // { // break; // } // p2++; // } // } // // return newLength; //} bool VerifyResult( std::vector<int> input, std::vector<int> expectedOutput ) { //std::cout << "Input: "; for (size_t i = 0; i < input.size(); i++) { std::cout << input[i] << ", "; } std::cout << std::endl; int newLength = removeDuplicates(input.data(), (int)input.size()); std::cout << "Output: "; for (int i = 0; i < newLength; i++) { std::cout << input[i] << ", "; } std::cout << std::endl; if( newLength != expectedOutput.size() ) { return false; } for (int i = 0; i < newLength; i++) { if( input[i] != expectedOutput[i] ) { return false; } } return true; } void TestArray1() { int nums[6] = { 7,1,5,3,9,4 }; int length = 6; int biggestIndexSoFar = 0; int smallestIndexSoFar = 0; for (int i = 1; i < length; i++) { if (nums[biggestIndexSoFar] < nums[i]) { biggestIndexSoFar = i; } if (nums[smallestIndexSoFar] > nums[i]) { smallestIndexSoFar = i; } } bool failed = false; if (!VerifyResult({ 2,2,3,4 }, { 2,3,4 })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ }, { })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ 1 }, { 1 })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ 10,10 }, { 10 })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ 1,1,1 }, { 1 })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ 2,5,9 }, { 2,5,9 })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ -10,-10,5,9 }, { -10,5,9 })) { std::cout << "Failed!"; failed = true; } //if (!VerifyResult({ 1,1,2,2,3,3,5,5 }, { 1,2,3,5 })) { std::cout << "Failed!"; failed = true; } if( !failed ) std::cout << "Success!"; }
21.682119
101
0.442578
KarateSnoopy
bec3cdfdc085fb7a2f2997c3cc209c5ba9794212
410
cc
C++
src/tools/hot_backup/sync_fault_state.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/tools/hot_backup/sync_fault_state.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/tools/hot_backup/sync_fault_state.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
#include "sync_fault_state.h" FaultState::FaultState(SyncStateManager* pSyncStateManager) : SyncStateBase() { m_pSyncStateManager = pSyncStateManager; } FaultState::~FaultState() { } void FaultState::Enter() { log_error("Here is ErrorState"); } void FaultState::Exit() { // do nothing } void FaultState::HandleEvent() { // 简单处理,程序结束 log_info("GoodBye hot_backup."); exit(0); }
14.137931
59
0.682927
jdisearch
bec528bdccaf409b043f71101ac596fdadec3888
1,431
hpp
C++
nd-coursework/books/cpp/C++MoveSemantics/basics/card.hpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/C++MoveSemantics/basics/card.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/C++MoveSemantics/basics/card.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2020 by Nicolai Josuttis. All rights reserved. // Licensed under the CCA-4.0 International License. See the LICENSE file in the project root for more information. // // Name: card.hpp // Author: crdrisko // Date: 08/08/2021-07:22:39 // Description: A class for the cards of a card game where each object is a valid card #ifndef CARD_HPP #define CARD_HPP #include <cassert> #include <iostream> #include <string> void assertValidCard(const std::string& val) { assert(val.find("seven") != std::string::npos || val.find("eight") != std::string::npos || val.find("nine") != std::string::npos || val.find("ten") != std::string::npos || val.find("jack") != std::string::npos || val.find("queen") != std::string::npos || val.find("king") != std::string::npos || val.find("ace") != std::string::npos); assert(val.find("clubs") != std::string::npos || val.find("spades") != std::string::npos || val.find("hearts") != std::string::npos || val.find("diamonds") != std::string::npos); } class Card { private: std::string value; // rank + "-of-" + suit public: Card(const std::string& val) : value {val} { assertValidCard(value); // ensure the value is always valid } // ... std::string getValue() const { return value; } friend std::ostream& operator<<(std::ostream& strm, const Card& c) { return strm << c.value; } }; #endif
31.8
115
0.621244
crdrisko
bec673d7073fe18807d852a87afb6c56bc84cb75
2,024
hpp
C++
code/source/util/parallel_buffer.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/util/parallel_buffer.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/util/parallel_buffer.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
#ifndef CLOVER_UTIL_PARALLEL_BUFFER_HPP #define CLOVER_UTIL_PARALLEL_BUFFER_HPP #include "build.hpp" #include "hardware/clstate.hpp" namespace clover { namespace visual { /// @todo Shouldn't be in util >:( class BaseVertexArrayObject; class Framebuffer; class Texture; } // visual namespace util { class ParallelQueue; /// @note Destroying/resetting can cause blocking if using kernel is running class ParallelBuffer { public: ParallelBuffer(); ParallelBuffer(ParallelBuffer&&); ParallelBuffer(const ParallelBuffer&)= delete; virtual ~ParallelBuffer(); ParallelBuffer& operator=(ParallelBuffer&&); ParallelBuffer& operator=(const ParallelBuffer&)= delete; template <typename T> void create(hardware::ClState::BufferFlag flags, T& first, uint32 element_count=1); /// @note After aliasing, modifying state of GL object through GL API is UB! void alias(hardware::ClState::BufferFlag flags, const visual::BaseVertexArrayObject& vao); void alias(hardware::ClState::BufferFlag flags, const visual::Framebuffer& fbo); void alias(hardware::ClState::BufferFlag flags, const visual::Texture& tex); void aliasTex(hardware::ClState::BufferFlag flags, uint32 tex_target, uint32 tex_id); void attachToQueue(util::ParallelQueue& q){ attachedQueue= &q; } /// Reads data back to elements specified in create(..) void read(); void acquire(); void release(); cl_mem getDId() const { return buffer.id; } void reset(); private: util::ParallelQueue* attachedQueue; hardware::ClState::Buffer buffer; void* hostData; SizeType hostDataSize; }; template <typename T> void ParallelBuffer::create(hardware::ClState::BufferFlag flags, T& first, uint32 element_count){ ensure(hardware::gClState); hostData= &first; hostDataSize= sizeof(T)*element_count; ensure(buffer.id == 0); buffer= hardware::gClState->createBuffer<T>( hardware::gClState->getDefaultContext(), (hardware::ClState::BufferFlag)flags, first, element_count); } } // util } // clover #endif // CLOVER_UTIL_PARALLEL_BUFFER_HPP
25.620253
97
0.755435
crafn
bede311bcd84c89fdf5538666aed61f014d642c4
5,855
cpp
C++
source/lib/memory/mmu_factory.cpp
olduf/gb-emu
37a2195fa67a2656cc11541eb75b1f7a548057b2
[ "Unlicense" ]
null
null
null
source/lib/memory/mmu_factory.cpp
olduf/gb-emu
37a2195fa67a2656cc11541eb75b1f7a548057b2
[ "Unlicense" ]
null
null
null
source/lib/memory/mmu_factory.cpp
olduf/gb-emu
37a2195fa67a2656cc11541eb75b1f7a548057b2
[ "Unlicense" ]
null
null
null
#include "lib/memory/mmu_factory.hpp" // Initial values come from the Gambatte source code // https://github.com/sinamas/gambatte/blob/master/libgambatte/src/initstate.cpp namespace gb_lib { MMU* MMUFactory::create(uint8_t* rom, uint32_t romSize, DMAMediator* dmaMediator, DMAMediator* hdmaMediator, MemorySpace* timerHandler, InterruptMediator* interruptMediator, bool isCGB) { MemorySpace* cartridge = this->cartridgeFactory.create(rom, romSize); MemorySpace* highRam = this->createHighRam(isCGB); MemorySpace* ioRegisters = this->createIORegisters(dmaMediator, hdmaMediator, timerHandler, interruptMediator, isCGB); MemorySpace* oam = new OAM(ioRegisters); MemorySpace* unusedMemoryFEA0_FEFF = nullptr; MemorySpace* videoRam = nullptr; MemorySpace* workingRam = nullptr; if (isCGB) { unusedMemoryFEA0_FEFF = new CGBUnusedMemoryFEA0_FEFF(); videoRam = new CGBVideoRam(ioRegisters); workingRam = new CGBWorkingRam(ioRegisters); } else { unusedMemoryFEA0_FEFF = new UnusedMemoryFEA0_FEFF(); videoRam = new VideoRam(ioRegisters); workingRam = new WorkingRam(); } return new MMU(cartridge, highRam, ioRegisters, oam, unusedMemoryFEA0_FEFF, videoRam, workingRam); } MemorySpace* MMUFactory::createHighRam(bool isCGB) { MemorySpace* highRam = new HighRam(); if (isCGB) { uint8_t initialValues[0x80] = { 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B, 0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E, 0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC, 0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x45, 0xEC, 0x42, 0xFA, 0x08, 0xB7, 0x07, 0x5D, 0x01, 0xF5, 0xC0, 0xFF, 0x08, 0xFC, 0x00, 0xE5, 0x0B, 0xF8, 0xC2, 0xCA, 0xF4, 0xF9, 0x0D, 0x7F, 0x44, 0x6D, 0x19, 0xFE, 0x46, 0x97, 0x33, 0x5E, 0x08, 0xFF, 0xD1, 0xFF, 0xC6, 0x8B, 0x24, 0x74, 0x12, 0xFC, 0x00, 0x9F, 0x94, 0xB7, 0x06, 0xD5, 0x40, 0x7A, 0x20, 0x9E, 0x04, 0x5F, 0x41, 0x2F, 0x3D, 0x77, 0x36, 0x75, 0x81, 0x8A, 0x70, 0x3A, 0x98, 0xD1, 0x71, 0x02, 0x4D, 0x01, 0xC1, 0xFF, 0x0D, 0x00, 0xD3, 0x05, 0xF9, 0x00, 0x0B, 0x00 }; for (uint16_t i = 0; i < 0x80; i++) { highRam->setByteInternal(0xFF80 + i, initialValues[i]); } } else { uint8_t initialValues[0x80] = { 0x2B, 0x0B, 0x64, 0x2F, 0xAF, 0x15, 0x60, 0x6D, 0x61, 0x4E, 0xAC, 0x45, 0x0F, 0xDA, 0x92, 0xF3, 0x83, 0x38, 0xE4, 0x4E, 0xA7, 0x6C, 0x38, 0x58, 0xBE, 0xEA, 0xE5, 0x81, 0xB4, 0xCB, 0xBF, 0x7B, 0x59, 0xAD, 0x50, 0x13, 0x5E, 0xF6, 0xB3, 0xC1, 0xDC, 0xDF, 0x9E, 0x68, 0xD7, 0x59, 0x26, 0xF3, 0x62, 0x54, 0xF8, 0x36, 0xB7, 0x78, 0x6A, 0x22, 0xA7, 0xDD, 0x88, 0x15, 0xCA, 0x96, 0x39, 0xD3, 0xE6, 0x55, 0x6E, 0xEA, 0x90, 0x76, 0xB8, 0xFF, 0x50, 0xCD, 0xB5, 0x1B, 0x1F, 0xA5, 0x4D, 0x2E, 0xB4, 0x09, 0x47, 0x8A, 0xC4, 0x5A, 0x8C, 0x4E, 0xE7, 0x29, 0x50, 0x88, 0xA8, 0x66, 0x85, 0x4B, 0xAA, 0x38, 0xE7, 0x6B, 0x45, 0x3E, 0x30, 0x37, 0xBA, 0xC5, 0x31, 0xF2, 0x71, 0xB4, 0xCF, 0x29, 0xBC, 0x7F, 0x7E, 0xD0, 0xC7, 0xC3, 0xBD, 0xCF, 0x59, 0xEA, 0x39, 0x01, 0x2E, 0x00, 0x69, 0x00 }; for (uint16_t i = 0; i < 0x80; i++) { highRam->setByteInternal(0xFF80 + i, initialValues[i]); } } return highRam; } MemorySpace* MMUFactory::createIORegisters(DMAMediator* dmaMediator, DMAMediator* hdmaMediator, MemorySpace* timerHandler, InterruptMediator* interruptMediator, bool isCGB) { MemorySpace* ioRegisters = new IORegisters(dmaMediator, hdmaMediator, timerHandler, interruptMediator, isCGB); ioRegisters->setByteInternal(0xFF05, 0x00); // TIMA ioRegisters->setByteInternal(0xFF06, 0x00); // TMA ioRegisters->setByteInternal(0xFF07, 0x00); // TAC ioRegisters->setByteInternal(0xFF10, 0x80); // NR10 ioRegisters->setByteInternal(0xFF11, 0xBF); // NR11 ioRegisters->setByteInternal(0xFF12, 0xF3); // NR12 ioRegisters->setByteInternal(0xFF14, 0xBF); // NR14 ioRegisters->setByteInternal(0xFF16, 0x3F); // NR21 ioRegisters->setByteInternal(0xFF17, 0x00); // NR22 ioRegisters->setByteInternal(0xFF19, 0xBF); // NR24 ioRegisters->setByteInternal(0xFF1A, 0x7F); // NR30 ioRegisters->setByteInternal(0xFF1B, 0xFF); // NR31 ioRegisters->setByteInternal(0xFF1C, 0x9F); // NR32 ioRegisters->setByteInternal(0xFF1E, 0xBF); // NR33 ioRegisters->setByteInternal(0xFF20, 0xFF); // NR41 ioRegisters->setByteInternal(0xFF21, 0x00); // NR42 ioRegisters->setByteInternal(0xFF22, 0x00); // NR43 ioRegisters->setByteInternal(0xFF23, 0xBF); // NR30 ioRegisters->setByteInternal(0xFF24, 0x77); // NR50 ioRegisters->setByteInternal(0xFF25, 0xF3); // NR51 ioRegisters->setByteInternal(0xFF26, 0xF1); // NR52 ioRegisters->setByteInternal(0xFF40, 0x91); // LCDC ioRegisters->setByteInternal(0xFF42, 0x00); // SCY ioRegisters->setByteInternal(0xFF43, 0x00); // SCX ioRegisters->setByteInternal(0xFF45, 0x00); // LYC ioRegisters->setByteInternal(0xFF47, 0xFC); // BGP ioRegisters->setByteInternal(0xFF48, 0xFF); // OBP0 ioRegisters->setByteInternal(0xFF49, 0xFF); // OBP1 ioRegisters->setByteInternal(0xFF4A, 0x00); // WY ioRegisters->setByteInternal(0xFF4B, 0x00); // WX if (isCGB) { // unsure, pandocs states it should be for SGB ioRegisters->setByteInternal(0xFF26, 0xF0); // NR52 } return ioRegisters; } }
42.122302
186
0.641674
olduf
bedf9bf367676509351f56af3d525586bf7520cd
1,210
cpp
C++
src/main.cpp
lukasz-pawlos/ukladV2
56d643d339160a891e5168fdaa576bab0a87f8a4
[ "MIT" ]
null
null
null
src/main.cpp
lukasz-pawlos/ukladV2
56d643d339160a891e5168fdaa576bab0a87f8a4
[ "MIT" ]
null
null
null
src/main.cpp
lukasz-pawlos/ukladV2
56d643d339160a891e5168fdaa576bab0a87f8a4
[ "MIT" ]
null
null
null
#include <iostream> #include "SWektor.hh" #include "Macierz.hh" #include "UkladRownan.hh" #include "rozmiar.h" #include "LZespolona.hh" using namespace std; int main() { char x; cin >> x; if (x == 'r') ///DLA DOUBLE { UkladRownanLiniowych<double, ROZMIAR> B; SWektor<double, ROZMIAR> C, D; cin >> B; C = B.obliczuklad(); //Obliczenie wektora wynikow B.wywtrans(); //Ztransponowanie macierzy cout << B; D = B.wekbl(C); //Obliczenie wektora bledu wyswrozw(C, D); // Wyswietlenie rozwiazan return 0; } else if (x == 'z') ///DLA ZESPOLONYCH { UkladRownanLiniowych<LZespolona, ROZMIAR> B; SWektor<LZespolona, ROZMIAR> C, D; cin >> B; C = B.obliczuklad(); //Obliczenie wektora wynikow B.wywtrans(); //Ztransponowanie macierzy cout << B; D = B.wekbl(C); //Obliczenie wektora bledu wyswrozw(C, D); // Wyswietlenie rozwiazan return 0; } else { cout << endl << "Nieprawidlowa opcja wywolania!" << endl; cout << "Dostepne opcje to: 'r'->(rzeczywiste) lub 'z'->(zespolone)" << endl; return 1; } }
20.166667
84
0.561157
lukasz-pawlos
bee1e1e4b5c5800a360b7a72a22951d90ac2ce30
4,666
cpp
C++
ch16-09-extruded-a/src/Utils.cpp
pulpobot/C-SFML-html5-animation
14154008b853d1235e8ca35a5b23b6a70366f914
[ "MIT" ]
73
2017-12-14T00:33:23.000Z
2022-02-09T12:04:52.000Z
ch17-03-extruded-a-light/src/Utils.cpp
threaderic/C-SFML-html5-animation
22f302cdf7c7c00247609da30e1bcf472d134583
[ "MIT" ]
null
null
null
ch17-03-extruded-a-light/src/Utils.cpp
threaderic/C-SFML-html5-animation
22f302cdf7c7c00247609da30e1bcf472d134583
[ "MIT" ]
5
2017-12-26T03:30:07.000Z
2020-07-05T04:58:24.000Z
#include <sstream> #include <iostream> #include "Utils.h" void Utils::Bezier::QuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments, std::vector<sf::Vector2f> &curvePoints, bool throughControlPoint) { //If there are any segments required if (segments <= 0) return; //Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2); curvePoints.clear(); float stepIncreasement = 1.0f / segments; float t = 0.0f; float px = 0.0f; float py = 0.0f; if (throughControlPoint) { p1.x = p1.x * 2 - (p0.x + p2.x) / 2; p1.y = p1.y * 2 - (p0.y + p2.y) / 2; } for (int i = 0; i <= segments; i++) { px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x); py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y); curvePoints.push_back(sf::Vector2f(px, py)); t += stepIncreasement; } } void Utils::Bezier::QuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments, std::vector<sf::Vertex> &curvePoints, sf::Color lineColor, bool throughControlPoint) { //If there are any segments required if (segments <= 0) return; //Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2); curvePoints.clear(); float stepIncreasement = 1.0f / segments; float t = 0; float px = 0; float py = 0; if (throughControlPoint) { p1.x = p1.x * 2 - (p0.x + p2.x) / 2; p1.y = p1.y * 2 - (p0.y + p2.y) / 2; } //Add points based on control point's position for (int i = 0; i <= segments; i++) { px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x); py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y); curvePoints.push_back(sf::Vertex(sf::Vector2f(px, py), lineColor)); t += stepIncreasement; } } ///Same as QuadraticBezierCurve, but it doesn't clear the array before pushing vertex void Utils::Bezier::AccumulativeQuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments, std::vector<sf::Vertex> &curvePoints, sf::Color lineColor, bool throughControlPoint) { //If there are any segments required if (segments <= 0) return; //Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2); float stepIncreasement = 1.0f / segments; float t = 0; float px = 0; float py = 0; if (throughControlPoint) { p1.x = p1.x * 2 - (p0.x + p2.x) / 2; p1.y = p1.y * 2 - (p0.y + p2.y) / 2; } //Add points based on control point's position for (int i = 0; i <= segments; i++) { px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x); py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y); curvePoints.push_back(sf::Vertex(sf::Vector2f(px, py), lineColor)); t += stepIncreasement; } } bool ::Utils::ContainsPoint(sf::FloatRect rect, float x, float y) { //SFML already has a "contains" function inside FloatRect class //return rect.contains(x,y); return !(x < rect.left || x > rect.left + rect.width || y < rect.top || y > rect.top + rect.height); } bool ::Utils::Intersects(sf::FloatRect rectA, sf::FloatRect rectB) { //SFML already has an "intersects" function inside FloatRect class //return rectA.intersects(rectB); return !(rectA.left + rectA.width < rectB.left || rectB.left + rectB.width < rectA.left || rectA.top + rectA.width < rectB.top || rectB.top + rectB.width < rectA.top ); } /// Input string examples: "#ffcccc" - "ffcccc" - "#ff" - "ffccccff" - "ffcccc" sf::Color Utils::HexColorToSFMLColor(std::string hexValue){ //remove # symbol if(hexValue.size() % 2 != 0) hexValue = hexValue.substr(1); unsigned int r = std::stoul(hexValue.substr(0,2), nullptr, 16); unsigned int g = (hexValue.size() > 2) ? std::stoul(hexValue.substr(2,2), nullptr, 16) : 0; unsigned int b = (hexValue.size() > 4) ? std::stoul(hexValue.substr(4,2), nullptr, 16) : 0; unsigned int a = (hexValue.size() > 6) ? std::stoul(hexValue.substr(6,2), nullptr, 16) : 255; return sf::Color(r,g,b,a); }
39.542373
114
0.536434
pulpobot
bee226083cad300103ba217fb6ad1b1e20152853
983
cpp
C++
tests/whole-program/structreturn.cpp
v8786339/NyuziProcessor
34854d333d91dbf69cd5625505fb81024ec4f785
[ "Apache-2.0" ]
1,388
2015-02-05T17:16:17.000Z
2022-03-31T07:17:08.000Z
tests/whole-program/structreturn.cpp
czvf/NyuziProcessor
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
[ "Apache-2.0" ]
176
2015-02-02T02:54:06.000Z
2022-02-01T06:00:21.000Z
tests/whole-program/structreturn.cpp
czvf/NyuziProcessor
31f74e43a785fa66d244f1e9744ca0ca9b8a1fad
[ "Apache-2.0" ]
271
2015-02-18T02:19:04.000Z
2022-03-28T13:30:25.000Z
// // Copyright 2011-2015 Jeff Bush // // 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 <stdio.h> // // Struct as return value // struct MyStruct { int a; int b; }; MyStruct __attribute__ ((noinline)) doIt(int a, int b) { MyStruct s1; s1.a = a; s1.b = b; return s1; } int main() { MyStruct s1 = doIt(0x37523482, 0x10458422); printf("s1a 0x%08x\n", s1.a); // CHECK: s1a 0x37523482 printf("s1b 0x%08x\n", s1.b); // CHECK: s1b 0x10458422 return 0; }
20.914894
75
0.693795
v8786339
bee879658e13c9e5d37bbf59ce9afb46702e32d4
1,406
cpp
C++
src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
null
null
null
src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
null
null
null
src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp
OpenCMISS-Dependencies/cube
bb425e6f75ee5dbdf665fa94b241b48deee11505
[ "Cube" ]
2
2016-09-19T00:16:05.000Z
2021-03-29T22:06:45.000Z
/**************************************************************************** ** CUBE http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2016 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** Copyright (c) 2009-2015 ** ** German Research School for Simulation Sciences GmbH, ** ** Laboratory for Parallel Programming ** ** ** ** This software may be modified and distributed under the terms of ** ** a BSD-style license. See the COPYING file in the package base ** ** directory for details. ** ****************************************************************************/ #ifndef __NULLARY_EVALUATION_CPP #define __NULLARY_EVALUATION_CPP 0 #include "CubeNullaryEvaluation.h" using namespace cube; NullaryEvaluation::NullaryEvaluation() : GeneralEvaluation() { }; NullaryEvaluation::~NullaryEvaluation() { } size_t NullaryEvaluation::getNumOfArguments() { return 0; } #endif
36.051282
77
0.396159
OpenCMISS-Dependencies
befdb4dc51f299c04b6b126655aa1748ff502e0f
629
cpp
C++
comsci-110/Chapter 5/consoleInput.cpp
colmentse/Cplusplus-class
0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050
[ "MIT" ]
null
null
null
comsci-110/Chapter 5/consoleInput.cpp
colmentse/Cplusplus-class
0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050
[ "MIT" ]
null
null
null
comsci-110/Chapter 5/consoleInput.cpp
colmentse/Cplusplus-class
0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050
[ "MIT" ]
null
null
null
/* Author : Colmen Tse Compsci : 120 5.6 consoleinput.cpp */ #include <string> #include <iostream> #include <cmath> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; cin.ignore(1000, 10); string name; cout << "Enter your name: "; getline(cin, name); double temp; cout << "Enter the temperature outside right now (degrees F): "; cin >> temp; cin.ignore(1000, 10); string location; cout << "What city are you in right now? "; getline(cin, location); cout << name << " is " << age << " years old." << endl; cout << "It's " << temp << " degrees F in " << location << endl; }
17.971429
65
0.613672
colmentse
befefa3a238c5a224d33a3c2e82fabedb5ecc0ad
67
cc
C++
fluid/src/framework/op_desc.cc
ImageMetrics/paddle-mobile
8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4
[ "MIT" ]
2
2018-07-17T10:55:48.000Z
2018-08-03T01:35:20.000Z
fluid/src/framework/op_desc.cc
ImageMetrics/paddle-mobile
8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4
[ "MIT" ]
null
null
null
fluid/src/framework/op_desc.cc
ImageMetrics/paddle-mobile
8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4
[ "MIT" ]
null
null
null
// // Created by liuRuiLong on 2018/4/23. // #include "op_desc.h"
11.166667
38
0.641791
ImageMetrics
8305a43c0016eb26e8d544d2c621426147818ff0
5,383
cpp
C++
tests/collection.cpp
dead1ock/algorithms-cpp
35b79b4cfe5db24e83ce157765fbcb221bc2ed38
[ "MIT" ]
null
null
null
tests/collection.cpp
dead1ock/algorithms-cpp
35b79b4cfe5db24e83ce157765fbcb221bc2ed38
[ "MIT" ]
null
null
null
tests/collection.cpp
dead1ock/algorithms-cpp
35b79b4cfe5db24e83ce157765fbcb221bc2ed38
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <collection/FixedArrayStack.h> #include <collection/FixedQueue.h> #include <collection/LinkedListStack.h> #include <collection/LinkedQueue.h> #include <collection/ResizableStack.h> #include <collection/ResizableQueue.h> TEST(LINKEDLISTSTACK, PushPopCount) { LinkedListStack<int> stack; stack.Push(100); stack.Push(200); stack.Push(300); EXPECT_EQ(3, stack.Count()); EXPECT_EQ(300, stack.Pop()); EXPECT_EQ(200, stack.Pop()); EXPECT_EQ(100, stack.Pop()); } TEST(LINKEDLISTSTACK, Push1000) { LinkedListStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(LINKEDLISTSTACK, Push100000) { LinkedListStack<int> stack; for (int x = 1; x <= 100000; x++) stack.Push(x); EXPECT_EQ(100000, stack.Count()); } TEST(LINKEDLISTSTACK, Push1000000) { LinkedListStack<int> stack; for (int x = 1; x <= 1000000; x++) stack.Push(x); EXPECT_EQ(1000000, stack.Count()); } // ===================================================== // // ===================================================== TEST(FixedArrayStack, PushPopCount) { FixedArrayStack<int> stack(3); stack.Push(100); stack.Push(200); stack.Push(300); EXPECT_EQ(3, stack.Count()); EXPECT_EQ(300, stack.Pop()); EXPECT_EQ(200, stack.Pop()); EXPECT_EQ(100, stack.Pop()); } TEST(FixedArrayStack, Push1000) { FixedArrayStack<int> stack(1000); for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(FixedArrayStack, Push100000) { FixedArrayStack<int> stack(100000); for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(FixedArrayStack, Push1000000) { FixedArrayStack<int> stack(1000000); for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } // ===================================================== // // ===================================================== TEST(ResizableStack, PushPopCount) { ResizableStack<int> stack; stack.Push(100); stack.Push(200); stack.Push(300); EXPECT_EQ(3, stack.Count()); EXPECT_EQ(300, stack.Pop()); EXPECT_EQ(200, stack.Pop()); EXPECT_EQ(100, stack.Pop()); } TEST(ResizableStack, Push1000) { ResizableStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(ResizableStack, Push100000) { ResizableStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } TEST(ResizableStack, Push1000000) { ResizableStack<int> stack; for (int x = 1; x <= 1000; x++) stack.Push(x); EXPECT_EQ(1000, stack.Count()); } // ===================================================== // // ===================================================== TEST(FixedQueue, EnqueueDequeueCount) { FixedQueue<int> queue(3); queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); EXPECT_EQ(3, queue.Count()); EXPECT_EQ(100, queue.Dequeue()); EXPECT_EQ(200, queue.Dequeue()); EXPECT_EQ(300, queue.Dequeue()); } TEST(FixedQueue, Enqueue1000) { FixedQueue<int> queue(1000); for (int x = 1; x <= 1000; x++) queue.Enqueue(x); EXPECT_EQ(1000, queue.Count()); } TEST(FixedQueue, Enqueue100000) { FixedQueue<int> queue(100000); for (int x = 1; x <= 100000; x++) queue.Enqueue(x); EXPECT_EQ(100000, queue.Count()); } TEST(FixedQueue, Enqueue1000000) { FixedQueue<int> queue(1000000); for (int x = 1; x <= 1000000; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); } TEST(FixedQueue, ProduceEnqueueOverflow) { FixedQueue<int> queue(1000000); for (int x = 1; x <= 1000001; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); } // ===================================================== // // ===================================================== TEST(LinkedQueue, EnqueueDequeueCount) { LinkedQueue<int> queue; queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); EXPECT_EQ(3, queue.Count()); EXPECT_EQ(100, queue.Dequeue()); EXPECT_EQ(200, queue.Dequeue()); EXPECT_EQ(300, queue.Dequeue()); } TEST(LinkedQueue, Enqueue1000) { LinkedQueue<int> queue; for (int x = 1; x <= 1000; x++) queue.Enqueue(x); EXPECT_EQ(1000, queue.Count()); } TEST(LinkedQueue, Enqueue100000) { LinkedQueue<int> queue; for (int x = 1; x <= 100000; x++) queue.Enqueue(x); EXPECT_EQ(100000, queue.Count()); } TEST(LinkedQueue, Enqueue1000000) { LinkedQueue<int> queue; for (int x = 1; x <= 1000000; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); } // ===================================================== // // ===================================================== TEST(ResizableQueue, EnqueueDequeueCount) { ResizableQueue<int> queue; queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); EXPECT_EQ(3, queue.Count()); EXPECT_EQ(100, queue.Dequeue()); EXPECT_EQ(200, queue.Dequeue()); EXPECT_EQ(300, queue.Dequeue()); } TEST(ResizableQueue, Enqueue1000) { ResizableQueue<int> queue; for (int x = 1; x <= 1000; x++) queue.Enqueue(x); EXPECT_EQ(1000, queue.Count()); } TEST(ResizableQueue, Enqueue100000) { ResizableQueue<int> queue; for (int x = 1; x <= 100000; x++) queue.Enqueue(x); EXPECT_EQ(100000, queue.Count()); } TEST(ResizableQueue, Enqueue1000000) { ResizableQueue<int> queue; for (int x = 1; x <= 1000000; x++) queue.Enqueue(x); EXPECT_EQ(1000000, queue.Count()); }
17.824503
56
0.602638
dead1ock
8306d502d0de3894cbff049ac4e1904b81fd428b
729
cpp
C++
test/examples_test/04_module_test/04_module_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206
e1fb506dbe4b068c01db307cd7626fd88b456a20
[ "MIT" ]
null
null
null
test/examples_test/04_module_test/04_module_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206
e1fb506dbe4b068c01db307cd7626fd88b456a20
[ "MIT" ]
1
2020-10-30T23:36:49.000Z
2020-11-06T19:33:56.000Z
test/examples_test/04_module_test/04_module_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206
e1fb506dbe4b068c01db307cd7626fd88b456a20
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("Verify sum of squares function") { REQUIRE(sum_of_squares(3)==14); REQUIRE(sum_of_squares(4)==30); REQUIRE(sum_of_squares(5)==55); } TEST_CASE("Verify sum numbers function") { REQUIRE(sum_numbers(4)==20); } TEST_CASE("Test get area with default parameters") { REQUIRE(get_area()==200); REQUIRE(get_area(5)==50); REQUIRE(get_area(20,20)==400); } TEST_CASE("Test value and reference parameters") { int num1=0, num2=0; pass_by_val_and_ref(num1, num2); REQUIRE(num1==0); REQUIRE(num2==50); }
20.828571
97
0.702332
acc-cosc-1337-fall-2020
8308730f7101ec449e3d4e3edfe2a179f4995b52
776
cpp
C++
Backtracking/ModularExpression.cpp
ssokjin/Interview-Bit
8714d3d627eb5875f49d205af779b59ca33ab4a3
[ "MIT" ]
513
2016-08-16T12:52:14.000Z
2022-03-30T19:32:10.000Z
Backtracking/ModularExpression.cpp
CodeOctal/Interview-Bit
88c021685d6cdef17906d077411ce34723363a08
[ "MIT" ]
25
2018-02-14T15:25:48.000Z
2022-03-23T11:52:08.000Z
Backtracking/ModularExpression.cpp
CodeOctal/Interview-Bit
88c021685d6cdef17906d077411ce34723363a08
[ "MIT" ]
505
2016-09-02T15:04:20.000Z
2022-03-25T06:36:31.000Z
// https://www.interviewbit.com/problems/modular-expression/ long long int calMod(int A, int B, int C){ if(B == 0){ return 1; } else if(B%2 == 0){ long long int y = calMod(A, B/2, C); return (y*y)%C; } else{ return ((A%C)*calMod(A,B-1,C))%C; } } int Solution::Mod(int A, int B, int C) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details if(A == 0){ return 0; } if(calMod(A, B, C) < 0){ return C+(int)calMod(A, B, C); } return (int)calMod(A, B, C); }
24.25
93
0.552835
ssokjin
830b9919832d3b721808454193278df544785653
570
cpp
C++
input/array.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/array.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/array.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; main(){ string name[5] = {"apple", "google", "microsoft", "ibm", "tesla"}; string arr[5] = {"ab", "bc", "cd", "de", "ff"}; string arr2[] = {"apappappapapap", "hghghdgahdgahsdghag"}; int num = sizeof(name[4]); int num2 = sizeof(arr[0]); int num3 = sizeof(arr2); cout << "The size of this array is "<< num; // The output will be 24 bcz of 3 pointers. cout << "The size of array 2 is "<< num2; // Each of size 8 bit. Thats why 8*3 = 24. cout << "The size of array 3 is "<< num3; return 0; }
38
91
0.578947
xdevkartik
83124097feb5012b57dc4f4fec5f0ab33adc840f
1,446
hpp
C++
code/aoce/Module/ModuleManager.hpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
71
2020-10-15T03:13:50.000Z
2022-03-30T02:04:28.000Z
code/aoce/Module/ModuleManager.hpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
9
2021-02-20T10:30:10.000Z
2022-03-04T07:59:58.000Z
code/aoce/Module/ModuleManager.hpp
msqljj/aoce
b15320acbb9454fb461501c8cf0c598d1b15c495
[ "MIT" ]
19
2021-01-01T12:03:02.000Z
2022-03-21T07:59:59.000Z
#pragma once #include <map> #include <memory> #include <string> #include <vector> #include "IModule.hpp" namespace aoce { typedef IModule* (*loadModuleAction)(); typedef std::function<IModule*(void)> loadModuleHandle; class ModuleInfo { public: void* handle = nullptr; IModule* module = nullptr; std::string name = ""; loadModuleHandle onLoadEvent = nullptr; bool load = false; public: ModuleInfo(/* args */){}; ~ModuleInfo(){}; }; class ACOE_EXPORT ModuleManager { public: static ModuleManager& Get(); ~ModuleManager(); protected: ModuleManager(); private: static ModuleManager* instance; std::map<std::string, ModuleInfo*> modules; private: ModuleManager(const ModuleManager&) = delete; ModuleManager& operator=(const ModuleManager&) = delete; /* data */ public: void registerModule(const char* name, loadModuleHandle handle = nullptr); void loadModule(const char* name); void unloadModule(const char* name); void regAndLoad(const char* name); public: bool checkLoadModel(const char* name); }; template <class module> class StaticLinkModule { public: StaticLinkModule(const std::string& name) { auto& fun = std::bind(&StaticLinkModule<module>::InitModeule, this); ModuleManager::Get().registerModule(name, fun); } public: IModule* InitModeule() { return new module(); } }; } // namespace aoce
22.246154
77
0.670124
msqljj
9b01091ed19e91701e87e18fd4691b40ac1c724e
856
cpp
C++
pico_src/conversion.cpp
Bambofy/pico
a26d853cca9e28170efa6ca694a9233f08f9b655
[ "MIT" ]
5
2020-03-03T16:02:28.000Z
2020-03-17T12:43:55.000Z
pico_src/conversion.cpp
Bambofy/pico
a26d853cca9e28170efa6ca694a9233f08f9b655
[ "MIT" ]
null
null
null
pico_src/conversion.cpp
Bambofy/pico
a26d853cca9e28170efa6ca694a9233f08f9b655
[ "MIT" ]
1
2020-03-04T12:16:05.000Z
2020-03-04T12:16:05.000Z
#include "../pico_inc/conversion.h" void Conversion_Uint_To_Char_Array(uint32_t inNumber, char * outDestinationPtrLocation, uint32_t outDestinationByteLength) { uintptr_t destPtr = reinterpret_cast<uintptr_t>(outDestinationPtrLocation); _Conversion_Uint_To_Char_Array(inNumber, destPtr, outDestinationByteLength); } void Conversion_Int_To_Char_Array(int32_t inNumber, char * outDestinationPtrLocation, uint32_t outDestinationByteLength) { uintptr_t destPtr = reinterpret_cast<uintptr_t>(outDestinationPtrLocation); _Conversion_Int_To_Char_Array(inNumber, destPtr, outDestinationByteLength); } int32_t Conversion_String_To_Int32(char * inCharArray, uint32_t inCharArrayPtrLength) { uintptr_t inCharArrayPtr = reinterpret_cast<uintptr_t>(inCharArray); return _Conversion_String_To_Int32(inCharArrayPtr, inCharArrayPtrLength); }
37.217391
122
0.83528
Bambofy
9b0a3563dab2a04ccc0e60408e3dab89439e70d4
3,269
cpp
C++
test/core/image_processing/hough_circle_transform.cpp
harsh-4/gil
6da59cc3351e5657275d3a536e0b6e7a1b6ac738
[ "BSL-1.0" ]
153
2015-02-03T06:03:54.000Z
2022-03-20T15:06:34.000Z
test/core/image_processing/hough_circle_transform.cpp
harsh-4/gil
6da59cc3351e5657275d3a536e0b6e7a1b6ac738
[ "BSL-1.0" ]
429
2015-03-22T09:49:04.000Z
2022-03-28T08:32:08.000Z
test/core/image_processing/hough_circle_transform.cpp
harsh-4/gil
6da59cc3351e5657275d3a536e0b6e7a1b6ac738
[ "BSL-1.0" ]
215
2015-03-15T09:20:51.000Z
2022-03-30T12:40:07.000Z
// Boost.GIL (Generic Image Library) - tests // // Copyright 2020 Olzhas Zhumabek <[email protected]> // // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/core/lightweight_test.hpp> #include <boost/gil/image.hpp> #include <boost/gil/image_processing/hough_transform.hpp> #include <boost/gil/image_view.hpp> #include <boost/gil/typedefs.hpp> #include <cstddef> #include <iostream> #include <limits> #include <vector> namespace gil = boost::gil; template <typename Rasterizer> void exact_fit_test(std::ptrdiff_t radius, gil::point_t offset, Rasterizer rasterizer) { std::vector<gil::point_t> circle_points(rasterizer.point_count(radius)); rasterizer(radius, offset, circle_points.begin()); // const std::ptrdiff_t diameter = radius * 2 - 1; const std::ptrdiff_t width = offset.x + radius + 1; const std::ptrdiff_t height = offset.y + radius + 1; gil::gray8_image_t image(width, height); auto input = gil::view(image); for (const auto& point : circle_points) { input(point) = std::numeric_limits<gil::uint8_t>::max(); } using param_t = gil::hough_parameter<std::ptrdiff_t>; const auto radius_parameter = param_t{radius, 0, 1}; // const auto x_parameter = param_t::from_step_count(offset.x, neighborhood, half_step_count); // const auto y_parameter = param_t::from_step_count(offset.y, neighborhood, half_step_count); const auto x_parameter = param_t{offset.x, 0, 1}; const auto y_parameter = param_t{offset.y, 0, 1}; std::vector<gil::gray16_image_t> output_images( radius_parameter.step_count, gil::gray16_image_t(x_parameter.step_count, y_parameter.step_count)); std::vector<gil::gray16_view_t> output_views(radius_parameter.step_count); std::transform(output_images.begin(), output_images.end(), output_views.begin(), [](gil::gray16_image_t& img) { return gil::view(img); }); gil::hough_circle_transform_brute(input, radius_parameter, x_parameter, y_parameter, output_views.begin(), rasterizer); if (output_views[0](0, 0) != rasterizer.point_count(radius)) { std::cout << "accumulated value: " << static_cast<int>(output_views[0](0, 0)) << " expected value: " << rasterizer.point_count(radius) << "\n\n"; } BOOST_TEST(output_views[0](0, 0) == rasterizer.point_count(radius)); } int main() { const int test_dim_length = 20; for (std::ptrdiff_t radius = 5; radius < test_dim_length; ++radius) { for (std::ptrdiff_t x_offset = radius; x_offset < radius + test_dim_length; ++x_offset) { for (std::ptrdiff_t y_offset = radius; y_offset < radius + test_dim_length; ++y_offset) { exact_fit_test(radius, {x_offset, y_offset}, gil::midpoint_circle_rasterizer{}); exact_fit_test(radius, {x_offset, y_offset}, gil::trigonometric_circle_rasterizer{}); } } } return boost::report_errors(); }
38.916667
99
0.657693
harsh-4
9b10a45f76002112ed294a14d916e6f2af835d83
2,704
cpp
C++
src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
null
null
null
src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
null
null
null
src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
1
2022-03-11T00:12:20.000Z
2022-03-11T00:12:20.000Z
#include <unistd.h> #include <iomanip> #include <torch/utils.h> #include "../utils/Ch_18_util.h" #include "../matplotlibcpp.h" namespace plt = matplotlibcpp; using torch::indexing::Slice; using torch::indexing::None; // Statistical bias torch::Tensor stat_bias(float true_theta, torch::Tensor est_theta) { return(torch::mean(est_theta) - true_theta); } // Mean squared error torch::Tensor mse(torch::Tensor data, float true_theta) { return(torch::mean(torch::square(data - true_theta))); } int main() { std::cout << "Current path is " << get_current_dir_name() << '\n'; // Device auto cuda_available = torch::cuda::is_available(); torch::Device device(cuda_available ? torch::kCUDA : torch::kCPU); std::cout << (cuda_available ? "CUDA available. Training on GPU." : "Training on CPU.") << '\n'; torch::manual_seed(8675309); auto torch_pi = torch::acos(torch::zeros(1)) * 2; // define pi in torch // Sample datapoints and create y coordinate float epsilon = 0.1; auto xs = torch::randn({300}); std::cout << xs.size(0) << '\n'; std::vector<float> ys; for(int i = 0; i < xs.size(0); i++) { auto yi = torch::sum(torch::exp(-1*torch::pow((xs.index({Slice(None, i)}) - xs[i]), 2) / (2 * epsilon*epsilon))) / torch::sqrt(2*torch_pi*epsilon*epsilon) / xs.size(0); ys.push_back(yi.data().item<float>()); } // Compute true density auto xd = torch::arange(torch::min(xs).data().item<float>(), torch::max(xs).data().item<float>(), 0.01); auto yd = torch::exp(-1*torch::pow(xd, 2)/2) / torch::sqrt(2 * torch_pi); std::vector<float> xx(xs.data_ptr<float>(), xs.data_ptr<float>() + xs.numel()); std::vector<float> xxd(xd.data_ptr<float>(), xd.data_ptr<float>() + xd.numel()); std::vector<float> yyd(yd.data_ptr<float>(), yd.data_ptr<float>() + yd.numel()); plt::figure_size(700, 500); plt::plot(xxd, yyd, "b-"); plt::scatter(xx, ys); plt::plot({0.0,0.0}, {0.0, 0.5}, {{"color", "purple"}, {"linestyle", "--"}, {"lw", "2"}}); plt::xlabel("x"); plt::ylabel("density"); plt::title("sample mean: " + std::to_string(xs.mean().data().item<float>())); plt::show(); plt::close(); float theta_true = 1.0; float sigma = 4.0; int sample_len = 10000; auto samples = torch::normal(theta_true, sigma, {sample_len, 1}); auto theta_est = torch::mean(samples); std::cout << "theta_est: " << theta_est << '\n'; std::cout << "mse(samples, theta_true): " << mse(samples, theta_true) << '\n'; // Next, we calculate Var(θ^n)+[bias(θ^n)]2 as below. auto bias = stat_bias(theta_true, theta_est); std::cout << "torch::square(samples.std(false)) + torch::square(bias): " << torch::square(samples.std(false)) + torch::square(bias) <<'\n'; std::cout << "Done!\n"; }
31.811765
114
0.637574
jiamny
9b11201d895aebd1c232215dd1a6d43437170e38
4,093
cpp
C++
src/gamelib/editor/ui/Overlay.cpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
1
2020-02-17T09:53:36.000Z
2020-02-17T09:53:36.000Z
src/gamelib/editor/ui/Overlay.cpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
null
null
null
src/gamelib/editor/ui/Overlay.cpp
mall0c/GameLib
df4116b53c39be7b178dd87f7eb0fe32a94d00d3
[ "MIT" ]
null
null
null
#include "gamelib/editor/ui/Overlay.hpp" #include "gamelib/editor/tools/ToolUtils.hpp" #include "gamelib/editor/EditorShared.hpp" #include "gamelib/core/ecs/Entity.hpp" #include "gamelib/core/geometry/flags.hpp" #include "gamelib/core/input/InputSystem.hpp" #include "gamelib/core/Game.hpp" #include "gamelib/core/rendering/CameraSystem.hpp" #include "gamelib/core/rendering/RenderSystem.hpp" #include "gamelib/components/geometry/Polygon.hpp" #include "gamelib/components/update/QPhysics.hpp" #include "imgui.h" namespace gamelib { Overlay::Overlay() : renderSolid(true), renderNormals(true), renderVel(true), showCoords(false), debugOverlay(true), debugOverlayMovable(true), renderCams(true) { } void Overlay::drawDebugOverlay() { if (debugOverlay) { if (!debugOverlayMovable) ImGui::SetNextWindowPos(ImVec2(0, 16)); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); if (ImGui::Begin("Stats overlay", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize)) { auto game = getSubsystem<Game>(); auto frametime = game->getFrametime(); ImGui::Text("FPS: %i", (int)(frametime != 0 ? 1.0 / frametime : 0)); ImGui::Text("Frametime: %i ms", (int)(frametime * 1000)); ImGui::Text("Real frametime: %i ms", (int)(game->getRealFrametime() * 1000)); ImGui::Text("Render time: %f ms", game->getRenderTime() * 1000); ImGui::Text("Update time: %f ms", game->getUpdateTime() * 1000); auto numrendered = getSubsystem<CameraSystem>()->getNumRendered(); if (!numrendered) numrendered = RenderSystem::getActive()->getNumObjectsRendered(); ImGui::Text("Objects rendered: %lu", numrendered); } ImGui::End(); ImGui::PopStyleColor(); } } void Overlay::drawGui() { auto input = getSubsystem<InputSystem>(); if (!input->isMouseConsumed() && showCoords) { auto mouse = EditorShared::isSnapEnabled() ? EditorShared::getMouseSnapped() : EditorShared::getMouse(); ImGui::BeginTooltip(); ImGui::SetTooltip("%i, %i", (int)mouse.x, (int)mouse.y); ImGui::EndTooltip(); } } void Overlay::render(sf::RenderTarget& target) { if (renderCams) { auto camsys = getSubsystem<CameraSystem>(); sf::Color col = sf::Color::Green; for (size_t i = 0; i < camsys->size(); ++i) { auto cam = camsys->get(i); const math::AABBf baserect(math::Point2f(), cam->getSize()); drawRectOutline(target, baserect, col, cam->getMatrix()); // if (!math::almostEquals(cam->getZoom(), 1.f)) // { // auto nozoomTransform = cam->getTransformation(); // nozoomTransform.scale.fill(1); // drawRectOutline(target, baserect, col, nozoomTransform.getMatrix()); // } } } const auto ent = EditorShared::getSelected(); if (!ent) return; if (renderSolid) drawCollisions(target, *ent, collision_solid); if (renderVel) { auto phys = ent->findByName<QPhysics>(); if (phys && !phys->vel.isZero()) { auto start = ent->getTransform().getBBox().getCenter(); auto end = start + phys->vel; drawArrow(target, start.x, start.y, end.x, end.y, sf::Color::Cyan); } } if (renderNormals) ent->findAllByName<PolygonCollider>([&](CompRef<PolygonCollider> pol) { if (pol->flags & collision_solid) drawNormals(target, pol->getGlobal()); return false; }); } }
36.221239
120
0.548986
mall0c
9b19915623890a71c6440137e1819b08795a6ab4
1,018
cpp
C++
engine/strings/source/RangedCombatTextKeys.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/strings/source/RangedCombatTextKeys.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/strings/source/RangedCombatTextKeys.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "RangedCombatTextKeys.hpp" using namespace std; // Ranged combat messages RangedCombatTextKeys::RangedCombatTextKeys() { } RangedCombatTextKeys::~RangedCombatTextKeys() { } const string RangedCombatTextKeys::RANGED_COMBAT_UNAVAILABLE_ON_WORLD_MAP = "RANGED_COMBAT_UNAVAILABLE_ON_WORLD_MAP"; const string RangedCombatTextKeys::RANGED_COMBAT_WEAPON_NOT_EQUIPPED = "RANGED_COMBAT_WEAPON_NOT_EQUIPPED"; const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_NOT_EQUIPPED = "RANGED_COMBAT_AMMUNITION_NOT_EQUIPPED"; const string RangedCombatTextKeys::RANGED_COMBAT_WEAPON_AMMUNITION_MISMATCH = "RANGED_COMBAT_WEAPON_AMMUNITION_MISMATCH"; const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_REQUIRES_RANGED_WEAPON = "RANGED_COMBAT_AMMUNITION_REQUIRES_RANGED_WEAPON"; const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_CURSED = "RANGED_COMBAT_AMMUNITION_CURSED"; const string RangedCombatTextKeys::RANGED_COMBAT_OVERBURDENED = "RANGED_COMBAT_OVERBURDENED";
50.9
135
0.852652
sidav
9b1d4f31caa5ccafbba94af952d5598e43d485ab
1,603
hpp
C++
rayt-cpp/utils.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
11
2020-07-04T13:35:10.000Z
2022-03-30T17:34:27.000Z
rayt-cpp/utils.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
null
null
null
rayt-cpp/utils.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
2
2021-03-02T06:31:43.000Z
2022-03-30T17:34:28.000Z
#ifndef UTILS_HPP #define UTILS_HPP //============================================================================== // Originally written in 2016 by Peter Shirley <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy (see file COPYING.txt) of the CC0 Public // Domain Dedication along with this software. If not, see // <http://creativecommons.org/publicdomain/zero/1.0/>. //============================================================================== #include <cmath> #include <cstdlib> #include <limits> #include <memory> #include <random> // Usings using std::make_shared; using std::shared_ptr; using std::sqrt; // Constants const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; // Utility Functions inline double degrees_to_radians(double degrees) { return degrees * pi / 180; } inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } inline double random_double(double min, double max) { return min + (max - min) * random_double(); } inline int random_int(int min, int max) { return static_cast<int>(random_double(min, max + 1)); } inline double clamp(double x, double min, double max) { if (x < min) { return min; } if (x > max) { return max; } return x; } #endif
27.169492
80
0.65315
gkmngrgn
9b1e120f3f985b6e526ca03ec3955e648466096f
5,202
hh
C++
kenlm/include/util/mmap.hh
pokey/w2ldecode
03f9995a48c5c1043be309fe5b20c6126851a9ff
[ "BSD-3-Clause" ]
114
2015-01-11T05:41:03.000Z
2021-08-31T03:47:12.000Z
Part 02/001_LM/ngram_lm_lab/kenlm/include/util/mmap.hh
Kabongosalomon/AMMI-NLP
00a0e47399926ad1951b84a11cd936598a9c7c3b
[ "MIT" ]
29
2015-01-09T01:00:09.000Z
2019-09-25T06:04:02.000Z
Part 02/001_LM/ngram_lm_lab/kenlm/include/util/mmap.hh
Kabongosalomon/AMMI-NLP
00a0e47399926ad1951b84a11cd936598a9c7c3b
[ "MIT" ]
50
2015-02-13T13:48:39.000Z
2019-08-07T09:45:11.000Z
#ifndef UTIL_MMAP_H #define UTIL_MMAP_H // Utilities for mmaped files. #include <cstddef> #include <limits> #include <stdint.h> #include <sys/types.h> namespace util { class scoped_fd; long SizePage(); // (void*)-1 is MAP_FAILED; this is done to avoid including the mmap header here. class scoped_mmap { public: scoped_mmap() : data_((void*)-1), size_(0) {} scoped_mmap(void *data, std::size_t size) : data_(data), size_(size) {} ~scoped_mmap(); void *get() const { return data_; } const uint8_t *begin() const { return reinterpret_cast<uint8_t*>(data_); } const uint8_t *end() const { return reinterpret_cast<uint8_t*>(data_) + size_; } std::size_t size() const { return size_; } void reset(void *data, std::size_t size) { scoped_mmap other(data_, size_); data_ = data; size_ = size; } void reset() { reset((void*)-1, 0); } private: void *data_; std::size_t size_; scoped_mmap(const scoped_mmap &); scoped_mmap &operator=(const scoped_mmap &); }; /* For when the memory might come from mmap, new char[], or malloc. Uses NULL * and 0 for blanks even though mmap signals errors with (void*)-1). The reset * function checks that blank for mmap. */ class scoped_memory { public: typedef enum {MMAP_ALLOCATED, ARRAY_ALLOCATED, MALLOC_ALLOCATED, NONE_ALLOCATED} Alloc; scoped_memory(void *data, std::size_t size, Alloc source) : data_(data), size_(size), source_(source) {} scoped_memory() : data_(NULL), size_(0), source_(NONE_ALLOCATED) {} ~scoped_memory() { reset(); } void *get() const { return data_; } const char *begin() const { return reinterpret_cast<char*>(data_); } const char *end() const { return reinterpret_cast<char*>(data_) + size_; } std::size_t size() const { return size_; } Alloc source() const { return source_; } void reset() { reset(NULL, 0, NONE_ALLOCATED); } void reset(void *data, std::size_t size, Alloc from); // realloc allows the current data to escape hence the need for this call // If realloc fails, destroys the original too and get() returns NULL. void call_realloc(std::size_t to); private: void *data_; std::size_t size_; Alloc source_; scoped_memory(const scoped_memory &); scoped_memory &operator=(const scoped_memory &); }; typedef enum { // mmap with no prepopulate LAZY, // On linux, pass MAP_POPULATE to mmap. POPULATE_OR_LAZY, // Populate on Linux. malloc and read on non-Linux. POPULATE_OR_READ, // malloc and read. READ, // malloc and read in parallel (recommended for Lustre) PARALLEL_READ, } LoadMethod; extern const int kFileFlags; // Wrapper around mmap to check it worked and hide some platform macros. void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset = 0); void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out); void MapAnonymous(std::size_t size, scoped_memory &to); // Open file name with mmap of size bytes, all of which are initially zero. void *MapZeroedWrite(int fd, std::size_t size); void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file); // msync wrapper void SyncOrThrow(void *start, size_t length); // Forward rolling memory map with no overlap. class Rolling { public: Rolling() {} explicit Rolling(void *data) { Init(data); } Rolling(const Rolling &copy_from, uint64_t increase = 0); Rolling &operator=(const Rolling &copy_from); // For an actual rolling mmap. explicit Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount); // For a static mapping void Init(void *data) { ptr_ = data; current_end_ = std::numeric_limits<uint64_t>::max(); current_begin_ = 0; // Mark as a pass-through. fd_ = -1; } void IncreaseBase(uint64_t by) { file_begin_ += by; ptr_ = static_cast<uint8_t*>(ptr_) + by; if (!IsPassthrough()) current_end_ = 0; } void DecreaseBase(uint64_t by) { file_begin_ -= by; ptr_ = static_cast<uint8_t*>(ptr_) - by; if (!IsPassthrough()) current_end_ = 0; } void *ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size); // Returns base pointer void *get() const { return ptr_; } // Returns base pointer. void *CheckedBase(uint64_t index) { if (index >= current_end_ || index < current_begin_) { Roll(index); } return ptr_; } // Returns indexed pointer. void *CheckedIndex(uint64_t index) { return static_cast<uint8_t*>(CheckedBase(index)) + index; } private: void Roll(uint64_t index); // True if this is just a thin wrapper on a pointer. bool IsPassthrough() const { return fd_ == -1; } void *ptr_; uint64_t current_begin_; uint64_t current_end_; scoped_memory mem_; int fd_; uint64_t file_begin_; uint64_t file_end_; bool for_write_; std::size_t block_; std::size_t read_bound_; }; } // namespace util #endif // UTIL_MMAP_H
26.953368
122
0.662438
pokey
9b1ef61068f354d7463caaa27ecf5b7deb9a80a4
501
hpp
C++
ffl/include/pipeline/FFL_PipelineNodeParser.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/include/pipeline/FFL_PipelineNodeParser.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/include/pipeline/FFL_PipelineNodeParser.hpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * FFL_PipelineNodeParser.hpp * Created by zhufeifei([email protected]) on 2018/02/11 * https://github.com/zhenfei2016/FFL-v2.git * * Pipelin系统中通过脚本创建node的parser * */ #ifndef _FFL_PIPELINENODE_PARSER_HPP_ #define _FFL_PIPELINENODE_PARSER_HPP_ namespace FFL{ class PipelineNodeParser { public: PipelineNodeParser(); virtual ~PipelineNodeParser(); }; } #endif
17.892857
57
0.740519
zhenfei2016
9b23a487cc1e235334005a4fd35d270a66e79f66
328
cpp
C++
chapter10/Proj1013.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
chapter10/Proj1013.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
chapter10/Proj1013.cpp
basstal/CPPPrimer
6366965657f873ac62003cf0a30a3fdb26c09351
[ "MIT" ]
null
null
null
#include"head.h" bool func(const string &s); int main(){ vector<string> words{"fox","jumps","over","quick","red","quick","blow","slow","the","turtle"}; auto iter = partition(words.begin(),words.end(),func); for(const auto &e:words) cout<<e<<" "; cout<<endl; return 0; } bool func(const string &s){ return s.size()>=5; }
23.428571
95
0.631098
basstal
9b25946d853b291db8676fcd613c862454f7ef3e
1,719
cpp
C++
firmware/Heat controller/lib/NTC/src/NTC.cpp
atoomnetmarc/IoT12
7706f69758a800da70bf8034a91a331206706824
[ "Apache-2.0" ]
null
null
null
firmware/Heat controller/lib/NTC/src/NTC.cpp
atoomnetmarc/IoT12
7706f69758a800da70bf8034a91a331206706824
[ "Apache-2.0" ]
null
null
null
firmware/Heat controller/lib/NTC/src/NTC.cpp
atoomnetmarc/IoT12
7706f69758a800da70bf8034a91a331206706824
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021-2022 Marc Ketel SPDX-License-Identifier: Apache-2.0 */ #include <math.h> #include "NTC.h" /* Class which is able to calculate the temperature of a NTC given the voltage of a resistor divider. Simple schematic: resistorDividerVoltage---[resistorDividerResistance]---[NTC]---GND */ NTC::NTC(void) { } /** @param resistorDividerVoltage Voltage of the resistor divider. @param resistorDividerResistance The fixed resistance of the resistor divider. @param thermistorResistance Resistance of the NTC at thermistorTemperature. @param thermistorTemperature Temperature in Kelvin of the NTC at thermistorResistance. @param thermistorBValue β-value of the NTC in Kelvin. */ void NTC::SetParameters( float resistorDividerVoltage, float resistorDividerResistance, float thermistorResistance, float thermistorTemperature, float thermistorBValue) { this->resistorDividerVoltage = resistorDividerVoltage; this->resistorDividerResistance = resistorDividerResistance; this->thermistorResistance = thermistorResistance; this->thermistorTemperature = thermistorTemperature; this->thermistorBValue = thermistorBValue; } /** @return Temperature in Kelvin */ float NTC::GetTemperature(float voltage) { //Current though NTC. float I = (this->resistorDividerVoltage - voltage) / this->resistorDividerResistance; //NTC resistance. float Rntc = (voltage / I); //Apply Steinhart–Hart equation: https://en.wikipedia.org/wiki/Thermistor#B_or_%CE%B2_parameter_equation float temperature = (1 / ((log(Rntc / this->resistorDividerResistance) / this->thermistorBValue) + (1 / this->thermistorTemperature))); return temperature; }
28.180328
139
0.753345
atoomnetmarc
9b2a0aeeed97f88621425a9a0b549c20a5d110d2
1,065
hpp
C++
src/elona/serialization/std/bitset.hpp
nanbansenji/ElonaFoobar
ddbd6639db8698e89f09b2512526e855d8016e46
[ "MIT" ]
84
2018-03-03T02:44:32.000Z
2019-07-14T16:16:24.000Z
src/elona/serialization/std/bitset.hpp
AFB111/elonafoobar
da7a3c86dd45e68e6e490fb260ead1d67c9fff5e
[ "MIT" ]
685
2018-02-27T04:31:17.000Z
2019-07-12T13:43:00.000Z
src/elona/serialization/std/bitset.hpp
nanbansenji/ElonaFoobar
ddbd6639db8698e89f09b2512526e855d8016e46
[ "MIT" ]
23
2019-07-26T08:52:38.000Z
2021-11-09T09:21:58.000Z
#pragma once #include <bitset> #include "../concepts.hpp" namespace elona::serialization { template <size_t N, typename Archive> void serialize(std::bitset<N>& value, Archive& ar) { if constexpr (concepts::is_iarchive_v<Archive>) { if constexpr (N <= 32) { uint32_t tmp; ar.scalar(tmp); value = tmp; } else if constexpr (N <= 64) { uint64_t tmp; ar.scalar(tmp); value = tmp; } else { std::string tmp; ar.str(tmp); value = std::bitset<N>(tmp); } } else { if constexpr (N <= 32) { uint32_t tmp = value.to_ulong(); ar.scalar(tmp); } else if constexpr (N <= 64) { uint64_t tmp = value.to_ulong(); ar.scalar(tmp); } else { std::string tmp = value.to_string(); ar.str(tmp); } } } } // namespace elona::serialization
18.684211
51
0.449765
nanbansenji
9b2b78b9110a940be1ce88a548c6fadf5e412df8
6,835
cpp
C++
modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp
lighthouse-os/hardware_libhardware
c6fa046a69d9b1adf474cf5de58318b677801e49
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * 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 "HidReport.h" #include "HidDefs.h" #include <cmath> #include <sstream> #include <iomanip> namespace HidUtil { HidReport::HidReport(uint32_t type, uint32_t data, const HidGlobal &global, const HidLocal &local) : mReportType(type), mFlag(data), mUsagePage(global.usagePage.get(0)), // default value 0 mUsage(local.getUsage(0)), mUsageVector(local.usage), mLogicalMin(global.logicalMin.get(0)), // default value 0 mLogicalMax(global.logicalMax.get(0)), mReportSize(global.reportSize), mReportCount(global.reportCount), mPhysicalMin(global.physicalMin), mPhysicalMax(global.physicalMax), mExponent(global.exponent), mUnit(global.unit), mReportId(global.reportId) { } std::string HidReport::getStringType() const { return reportTypeToString(mReportType); } std::string HidReport::reportTypeToString(int type) { using namespace HidDef::MainTag; switch(type) { case INPUT: return "INPUT"; case OUTPUT: return "OUTPUT"; case FEATURE: return "FEATURE"; default: return "<<UNKNOWN>>"; } } double HidReport::getExponentValue() const { if (!mExponent.isSet()) { return 1; } // default exponent is 0 int exponentInt = mExponent.get(0); if (exponentInt > 15 || exponentInt < 0) { return NAN; } return pow(10.0, static_cast<double>((exponentInt <= 7) ? exponentInt : exponentInt - 16)); } std::string HidReport::getExponentString() const { int exponentInt = mExponent.get(0); if (exponentInt > 15 || exponentInt < 0) { return "[error]"; } return std::string("x10^") + std::to_string((exponentInt <= 7) ? exponentInt : exponentInt - 16); } std::string HidReport::getUnitString() const { if (!mUnit.isSet()) { return "default"; } return "[not implemented]"; std::ostringstream ret; ret << std::hex << std::setfill('0') << std::setw(2) << mUnit.get(0); return ret.str(); } std::string HidReport::getFlagString() const { using namespace HidDef::ReportFlag; std::string ret; ret += (mFlag & DATA_CONST) ? "Const " : "Data "; ret += (mFlag & ARRAY_VARIABLE) ? "Variable " : "Array "; ret += (mFlag & WRAP) ? "Wrap " : ""; ret += (mFlag & NONLINEAR) ? "Nonlinear " : ""; ret += (mFlag & NO_PREFERRED) ? "NoPreferred " : ""; ret += (mFlag & NULL_STATE) ? "NullState " : ""; ret += (mFlag & VOLATILE) ? "Volatile " : ""; ret += (mFlag & BUFFERED_BYTES) ? "BufferedBytes " : ""; return ret; } // isArray() will return true for reports that may contains multiple values, e.g. keyboard scan // code, which can have multiple value, each denoting a key pressed down at the same time. It will // return false if repor represent a vector or matrix. // // This slightly deviates from HID's definition, it is more convenient this way as matrix/vector // input is treated similarly as variables. bool HidReport::isArray() const { using namespace HidDef::ReportFlag; return (mFlag & ARRAY_VARIABLE) == 0 && mIsCollapsed; } bool HidReport::isVariable() const { return !isArray(); } bool HidReport::isData() const { using namespace HidDef::ReportFlag; return (mFlag & DATA_CONST) == 0; } std::ostream& operator<<(std::ostream& os, const HidReport& h) { os << h.getStringType() << ", " << "usage: " << std::hex << h.getFullUsage() << std::dec << ", "; if (h.isData()) { auto range = h.getLogicalRange(); os << "logMin: " << range.first << ", " << "logMax: " << range.second << ", "; if (range == h.getPhysicalRange()) { os << "phy===log, "; } else { range = h.getPhysicalRange(); os << "phyMin: " << range.first << ", " << "phyMax: " << range.second << ", "; } if (h.isArray()) { os << "map: (" << std::hex; for (auto i : h.getUsageVector()) { os << i << ","; } os << "), " << std::dec; } os << "exponent: " << h.getExponentString() << ", " << "unit: " << h.getUnitString() << ", "; } else { os << "constant: "; } os << "size: " << h.getSize() << "bit x " << h.getCount() << ", " << "id: " << h.mReportId; return os; } std::pair<int64_t, int64_t> HidReport::getLogicalRange() const { int64_t a = mLogicalMin; int64_t b = mLogicalMax; if (a > b) { // might be unsigned a = a & ((static_cast<int64_t>(1) << getSize()) - 1); b = b & ((static_cast<int64_t>(1) << getSize()) - 1); if (a > b) { // bad hid descriptor return {0, 0}; } } return {a, b}; } std::pair<int64_t, int64_t> HidReport::getPhysicalRange() const { if (!(mPhysicalMin.isSet() && mPhysicalMax.isSet())) { // physical range undefined, use logical range return getLogicalRange(); } int64_t a = mPhysicalMin.get(0); int64_t b = mPhysicalMax.get(0); if (a > b) { a = a & ((static_cast<int64_t>(1) << getSize()) - 1); b = b & ((static_cast<int64_t>(1) << getSize()) - 1); if (a > b) { return {0, 0}; } } return {a, b}; } unsigned int HidReport::getFullUsage() const { return mUsage | (mUsagePage << 16); } size_t HidReport::getSize() const { return mReportSize; } size_t HidReport::getCount() const { return mReportCount; } unsigned int HidReport::getUnit() const { return mUnit.get(0); // default unit is 0 means default unit } unsigned HidReport::getReportId() const { // if report id is not specified, it defaults to zero return mReportId.get(0); } unsigned HidReport::getType() const { return mReportType; } void HidReport::setCollapsed(uint32_t fullUsage) { mUsage = fullUsage & 0xFFFF; mUsagePage = fullUsage >> 16; mIsCollapsed = true; } const std::vector<unsigned int>& HidReport::getUsageVector() const { return mUsageVector; } } // namespace HidUtil
29.717391
98
0.58654
lighthouse-os
9b2d7bdf8175e9af1324c8529f05ebc9298df440
4,713
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_DefineLazyClass.cpp // #include "smtc_DefineLazyClass.h" #include "smtc_ClassDefn.h" #include "smtc_ClassScope.h" #include "smtc_CreateLazyClass.h" #include "smtc_CreateLazyClassEntity.h" #include "smtc_CreateLazyClassScope.h" #include "smtc_CreateMbrInit.h" #include "smtc_CreateQualName.h" #include "smtc_CreateTmplLazyClass.h" #include "smtc_CreateTmplLazyClassEntity.h" #include "smtc_DeclareLazyClassObjParamSet.h" #include "smtc_FormTmplName.h" #include "smtc_GetNameLoc.h" #include "smtc_IsNameQual.h" #include "smtc_LazyBaseSpec.h" #include "smtc_LazyClass.h" #include "smtc_Message.h" #include "smtc_Ns.h" #include "smtc_NsScope.h" #include "smtc_ScopeVisitor.h" #include "smtc_TmplSpecScope.h" #include "smtc_TmplSpecToArgString.h" #define LZZ_INLINE inline namespace { using namespace smtc; } namespace { struct DefineLazyClass : ScopeVisitor { bool is_tmpl; TmplSpecPtrVector & tmpl_spec_set; gram::SpecSel const & spec_sel; ClassKey key; NamePtr const & name; bool is_dll_api; ParamPtrVector const & param_set; bool vararg; BaseSpecPtrVector const & base_spec_set; ScopePtr & res_scope; void visit (NsScope const & scope) const; void visit (ClassScope const & scope) const; void visit (TmplSpecScope const & scope) const; EntityPtr buildEntity (NamePtr const & encl_qual_name = NamePtr ()) const; public: explicit DefineLazyClass (bool is_tmpl, TmplSpecPtrVector & tmpl_spec_set, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set, ScopePtr & res_scope); ~ DefineLazyClass (); }; } namespace smtc { ScopePtr defineLazyClass (ScopePtr const & scope, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set) { ScopePtr res_scope; TmplSpecPtrVector tmpl_spec_set; scope->accept (DefineLazyClass (false, tmpl_spec_set, spec_sel, key, name, is_dll_api, param_set, vararg, base_spec_set, res_scope)); return res_scope; } } namespace { void DefineLazyClass::visit (NsScope const & scope) const { // build ns lazy class scope.getNs ()->addEntity (buildEntity ()); } } namespace { void DefineLazyClass::visit (ClassScope const & scope) const { // cannot be qualified if (isNameQual (name)) { msg::qualClassClassDefn (getNameLoc (name)); } // build mbr lazy class ClassDefnPtr const & class_defn = scope.getClassDefn (); class_defn->addEntity (buildEntity (class_defn->getQualName ())); } } namespace { void DefineLazyClass::visit (TmplSpecScope const & scope) const { // declare template class tmpl_spec_set.push_back (scope.getTmplSpec ()); scope.getParent ()->accept (DefineLazyClass (true, tmpl_spec_set, spec_sel, key, name, is_dll_api, param_set, vararg, base_spec_set, res_scope)); } } namespace { EntityPtr DefineLazyClass::buildEntity (NamePtr const & encl_qual_name) const { int flags = spec_sel.getFlags (); LazyClassPtr lazy_class = createLazyClass (flags, key, name, is_dll_api, param_set, vararg, base_spec_set); declareLazyClassObjParamSet (lazy_class, param_set, base_spec_set); // get qual name and entity NamePtr qual_name; EntityPtr entity; if (is_tmpl) { qual_name = formTmplName (name, tmplSpecToArgString (tmpl_spec_set.front ())); TmplLazyClassPtr tmpl_lazy_class = createTmplLazyClass (tmpl_spec_set, lazy_class); entity = createTmplLazyClassEntity (tmpl_lazy_class); } else { qual_name = name; entity = createLazyClassEntity (lazy_class); } if (encl_qual_name.isSet ()) { qual_name = createQualName (encl_qual_name, qual_name); } lazy_class->setQualName (qual_name); res_scope = createLazyClassScope (lazy_class); return entity; } } namespace { LZZ_INLINE DefineLazyClass::DefineLazyClass (bool is_tmpl, TmplSpecPtrVector & tmpl_spec_set, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set, ScopePtr & res_scope) : is_tmpl (is_tmpl), tmpl_spec_set (tmpl_spec_set), spec_sel (spec_sel), key (key), name (name), is_dll_api (is_dll_api), param_set (param_set), vararg (vararg), base_spec_set (base_spec_set), res_scope (res_scope) {} } namespace { DefineLazyClass::~ DefineLazyClass () {} } #undef LZZ_INLINE
34.152174
290
0.717165
SuperDizor
9b36bf4ac6c6a7f412d25e45df5084a4df3baa41
530
cc
C++
pathtracer/src/scene_elements/serialized/lights/SpotLight.cc
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
pathtracer/src/scene_elements/serialized/lights/SpotLight.cc
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
pathtracer/src/scene_elements/serialized/lights/SpotLight.cc
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
#include "SpotLight.hh" float SpotLight::getAngle() const { return angle_; } void SpotLight::setAngle(float angle) { SpotLight::angle_ = angle; } const Vector3D<float> &SpotLight::getDirection() const { return direction_; } void SpotLight::setDirection(const Vector3D<float> &direction) { SpotLight::direction_ = direction; } const Vector3D<float> &SpotLight::getPosition() const { return position_; } void SpotLight::setPosition(const Vector3D<float> &position) { SpotLight::position_ = position; }
20.384615
64
0.720755
bjorn-grape
9b375c34a28ab4aee9774fa54acb33fb2ebd7fa8
8,869
cpp
C++
code/utils/encoding.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
307
2015-04-10T13:27:32.000Z
2022-03-21T03:30:38.000Z
code/utils/encoding.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
2,231
2015-04-27T10:47:35.000Z
2022-03-31T19:22:37.000Z
code/utils/encoding.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
282
2015-01-05T12:16:57.000Z
2022-03-28T04:45:11.000Z
// // #include "utils/encoding.h" #include "mod_table/mod_table.h" namespace util { Encoding guess_encoding(const SCP_string& content, bool assume_utf8) { if (content.size()>= 3 && !strncmp(content.c_str(), "\xEF\xBB\xBF", 3)) { // UTF-8 return Encoding::UTF8; } if (content.size()>= 4 && !strncmp(content.c_str(), "\x00\x00\xFE\xFF", 4)) { // UTF-32 big-endian return Encoding::UTF32BE; } if (content.size()>= 4 && !strncmp(content.c_str(), "\xFF\xFE\x00\x00", 4)) { // UTF-32 little-endian return Encoding::UTF32LE; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFE\xFF", 2)) { // UTF-16 big-endian return Encoding::UTF16BE; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFF\xFE", 2)) { // UTF-16 little-endian return Encoding::UTF16LE; } return assume_utf8 ? Encoding::UTF8 : Encoding::ASCII; } bool has_bom(const SCP_string& content) { if (content.size()>= 3 && !strncmp(content.c_str(), "\xEF\xBB\xBF", 3)) { // UTF-8 return true; } if (content.size()>= 4 && !strncmp(content.c_str(), "\x00\x00\xFE\xFF", 4)) { // UTF-32 big-endian return true; } if (content.size()>= 4 && !strncmp(content.c_str(), "\xFF\xFE\x00\x00", 4)) { // UTF-32 little-endian return true; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFE\xFF", 2)) { // UTF-16 big-endian return true; } if (content.size()>= 2 && !strncmp(content.c_str(), "\xFF\xFE", 2)) { // UTF-16 little-endian return true; } return false; } int check_encoding_and_skip_bom(CFILE* file, const char* filename, int* start_offset) { cfseek(file, 0, CF_SEEK_SET); // Read up to 10 bytes from the file to check if there is a BOM SCP_string probe; auto probe_size = (size_t)std::min(10, cfilelength(file)); probe.resize(probe_size); cfread(&probe[0], 1, (int) probe_size, file); cfseek(file, 0, CF_SEEK_SET); auto filelength = cfilelength(file); if (start_offset) { *start_offset = 0; } // Determine encoding. Assume UTF-8 if we are in unicode text mode auto encoding = util::guess_encoding(probe, Unicode_text_mode); if (Unicode_text_mode) { if (encoding != util::Encoding::UTF8) { //This is probably fatal, so let's abort right here and now. Error(LOCATION, "%s is in an Unicode/UTF format that cannot be read by FreeSpace Open. Please convert it to UTF-8\n", filename); } if (util::has_bom(probe)) { // The encoding has to be UTF-8 here so we know that the BOM is 3 Bytes long // This makes sure that the first byte we read will be the first actual text byte. cfseek(file, 3, SEEK_SET); filelength -= 3; if (start_offset) { *start_offset = 3; } } } else { if (encoding != util::Encoding::ASCII) { //This is probably fatal, so let's abort right here and now. Error(LOCATION, "%s is in Unicode/UTF format and cannot be read by FreeSpace Open without turning on Unicode mode. Please convert it to ASCII/ANSI\n", filename); } } return filelength; } // The following code is adapted from the uchardet library, the original licence of the file has been kept /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <cstdio> #define UDF 0 // undefined #define OTH 1 //other #define ASC 2 // ascii capital letter #define ASS 3 // ascii small letter #define ACV 4 // accent capital vowel #define ACO 5 // accent capital other #define ASV 6 // accent small vowel #define ASO 7 // accent small other #define CLASS_NUM 8 // total classes #define FREQ_CAT_NUM 4 static const unsigned char Latin1_CharToClass[] = { OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 00 - 07 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 08 - 0F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 10 - 17 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 18 - 1F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 20 - 27 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 28 - 2F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 30 - 37 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 38 - 3F OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 40 - 47 ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 48 - 4F ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 50 - 57 ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, // 58 - 5F OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 60 - 67 ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 68 - 6F ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 70 - 77 ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, // 78 - 7F OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, // 80 - 87 OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, // 88 - 8F UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 90 - 97 OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, // 98 - 9F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A0 - A7 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A8 - AF OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B0 - B7 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B8 - BF ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, // C0 - C7 ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, // C8 - CF ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, // D0 - D7 ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, // D8 - DF ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, // E0 - E7 ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, // E8 - EF ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, // F0 - F7 ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, // F8 - FF }; /* 0 : illegal 1 : very unlikely 2 : normal 3 : very likely */ static const unsigned char Latin1ClassModel[] = { /* UDF OTH ASC ASS ACV ACO ASV ASO */ /*UDF*/ 0, 0, 0, 0, 0, 0, 0, 0, /*OTH*/ 0, 3, 3, 3, 3, 3, 3, 3, /*ASC*/ 0, 3, 3, 3, 3, 3, 3, 3, /*ASS*/ 0, 3, 3, 3, 1, 1, 3, 3, /*ACV*/ 0, 3, 3, 3, 1, 2, 1, 2, /*ACO*/ 0, 3, 3, 3, 3, 3, 3, 3, /*ASV*/ 0, 3, 1, 3, 1, 1, 1, 3, /*ASO*/ 0, 3, 1, 3, 1, 1, 3, 3, }; bool guessLatin1Encoding(const char* aBuf, size_t aLen) { char mLastCharClass = OTH; uint32_t mFreqCounter[FREQ_CAT_NUM]; for (int i = 0; i < FREQ_CAT_NUM; i++) { mFreqCounter[i] = 0; } unsigned char charClass; unsigned char freq; for (size_t i = 0; i < aLen; i++) { charClass = Latin1_CharToClass[(unsigned char) aBuf[i]]; freq = Latin1ClassModel[mLastCharClass * CLASS_NUM + charClass]; if (freq == 0) { return false; } mFreqCounter[freq]++; mLastCharClass = charClass; } float confidence; uint32_t total = 0; for (int32_t i = 0; i < FREQ_CAT_NUM; i++) { total += mFreqCounter[i]; } if (!total) { confidence = 0.0f; } else { confidence = mFreqCounter[3] * 1.0f / total; confidence -= mFreqCounter[1] * 20.0f / total; } if (confidence < 0.0f) { confidence = 0.0f; } return confidence > .5f; } }
35.906883
140
0.597023
trgswe
9b3addf69baf6396826baea1132848c4bea1126f
353
cpp
C++
Artemis/Source/Graphics/Artemis.Graphics.cpp
NoriyukiHiromoto/TinyGameEngine
ea683db3d498c1b8df91930a262a4c50a4e69b82
[ "MIT" ]
null
null
null
Artemis/Source/Graphics/Artemis.Graphics.cpp
NoriyukiHiromoto/TinyGameEngine
ea683db3d498c1b8df91930a262a4c50a4e69b82
[ "MIT" ]
null
null
null
Artemis/Source/Graphics/Artemis.Graphics.cpp
NoriyukiHiromoto/TinyGameEngine
ea683db3d498c1b8df91930a262a4c50a4e69b82
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- #include "Artemis.Local.hpp" #include "Artemis.Graphics.hpp" #if defined(ATS_API_DIRECTX11) #include "Platform/Artemis.Graphics.directx11.cpp" #endif//defined(ATS_API_DIRECTX11)
35.3
85
0.407932
NoriyukiHiromoto
9b3cc3cd55dd4d87adcbf4cab59dd62587a51248
3,360
cpp
C++
GraphAlgorithms/Monsters.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
2
2021-02-05T04:21:42.000Z
2021-02-10T14:24:38.000Z
GraphAlgorithms/Monsters.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
GraphAlgorithms/Monsters.cpp
su050300/CSES-Problemset-Solutions
292281f9ac3c57c21c8208b30087386c29238d17
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n,m; cin>>n>>m; vector<vector<char>>v(n,vector<char>(m)); vector<vector<int>>poss(n,vector<int>(m,-1)); queue<pair<int,int>>q; int xi,yi; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>v[i][j]; if(v[i][j]=='M') { q.push({i,j}); poss[i][j]=0; } if(v[i][j]=='A') { xi=i,yi=j; } } } vector<vector<int>>visited(n,vector<int>(m)); vector<pair<int,int>>pos={{1,0},{0,1},{-1,0},{0,-1}}; vector<char>pat={'D','R','U','L'}; while(!q.empty()) { pair<int,int>d=q.front(); q.pop(); for(int i=0;i<4;i++) { int x=pos[i].first+d.first; int y=pos[i].second+d.second; if(x>=0&&x<n&&y>=0&&y<m&&!visited[x][y]&&v[x][y]=='.') { visited[x][y]=1; q.push({x,y}); poss[x][y]=poss[d.first][d.second]+1; } // else if(x>=0&&x<n&&y>=0&&y<m&&v[x][y]=='.') // { // poss[x][y]=min(poss[x][y],poss[d.first][d.second]); // } } } q.push({xi,yi}); vector<vector<int>>vis(n,vector<int>(m)); vector<vector<int>>posss(n,vector<int>(m,-1)); vector<vector<char>>path(n,vector<char>(m)); posss[xi][yi]=0; vis[xi][yi]=1; if(poss[xi][yi]!=-1) { cout<<"NO"<<endl; return 0; } while(!q.empty()) { pair<int,int>d=q.front(); q.pop(); for(int i=0;i<4;i++) { int x=d.first+pos[i].first; int y=d.second+pos[i].second; if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&v[x][y]=='.') { vis[x][y]=1; if(poss[x][y]!=-1&&poss[x][y]<=posss[d.first][d.second]+1) { continue; } posss[x][y]=posss[d.first][d.second]+1; q.push({x,y}); path[x][y]=pat[i]; } } } int selx=-1,sely=-1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { // cout<<posss[i][j]<<" "; if(i==0||j==0||i==n-1||j==m-1) { if((v[i][j]=='.'||v[i][j]=='A')&&posss[i][j]!=-1) { selx=i,sely=j; break; } } } // cout<<endl; } if(selx==-1&&sely==-1) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; vector<char>res; path[xi][yi]='F'; while(path[selx][sely]!='F') { // cout<<selx<<" "<<sely<<endl; res.push_back(path[selx][sely]); if(path[selx][sely]=='L') { sely+=1; } else if(path[selx][sely]=='R') { sely-=1; } else if(path[selx][sely]=='U') { selx+=1; } else { selx-=1; } } reverse(res.begin(),res.end()); cout<<res.size()<<endl; for(char d:res) { cout<<d; } } return 0; }
24.347826
73
0.344048
su050300
9b3e2593d9ff36628dfe296383a498755d0df0e7
3,595
cpp
C++
src/main.cpp
shouxieai/kiwi-rknn
55c1a4ae2b664acf564b1218728b6ed85b9713aa
[ "MIT" ]
8
2022-03-02T08:51:21.000Z
2022-03-23T13:24:11.000Z
src/main.cpp
shouxieai/kiwi-rknn
55c1a4ae2b664acf564b1218728b6ed85b9713aa
[ "MIT" ]
3
2022-03-15T02:40:14.000Z
2022-03-29T03:25:17.000Z
src/main.cpp
shouxieai/kiwi-rknn
55c1a4ae2b664acf564b1218728b6ed85b9713aa
[ "MIT" ]
3
2022-03-03T07:46:21.000Z
2022-03-14T08:32:45.000Z
#include <stdio.h> #include <thread> #include <opencv2/opencv.hpp> #include "kiwi-logger.hpp" #include "kiwi-app-nanodet.hpp" #include "kiwi-app-scrfd.hpp" #include "kiwi-app-arcface.hpp" #include "kiwi-infer-rknn.hpp" using namespace cv; using namespace std; void test_pref(const char* model){ // 测试性能启用sync mode目的是尽可能的利用npu。实际使用如果无法掌握sync mode,尽量别用 // 你会发现sync mode的耗时会是非这个模式的80%左右,性能有提升,这与你实际推理时有区别,注意查看 auto infer = rknn::load_infer(model, true); infer->forward(); auto tic = kiwi::timestamp_now_float(); for(int i = 0; i < 100; ++i){ infer->forward(); } auto toc = kiwi::timestamp_now_float(); INFO("%s avg time: %f ms", model, (toc - tic) / 100); } void scrfd_demo(){ auto infer = scrfd::create_infer("scrfd_2.5g_bnkps.rknn", 0.4, 0.5); auto image = cv::imread("faces.jpg"); auto box_result = infer->commit(image).get(); auto tic = kiwi::timestamp_now_float(); for(int i = 0; i < 100; ++i){ infer->commit(image).get(); } auto toc = kiwi::timestamp_now_float(); INFO("scrfd time: %f ms", (toc - tic) / 100); for(auto& obj : box_result){ cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(0, 255, 0), 2); auto pl = obj.landmark; for(int i = 0; i < 5; ++i, pl += 2){ cv::circle(image, cv::Point(pl[0], pl[1]), 3, cv::Scalar(0, 0, 255), -1, 16); } } cv::imwrite("scrfd-result.jpg", image); } void nanodet_demo(){ auto infer = nanodet::create_infer("person_m416_plus_V15.rknn", 0.4, 0.5); auto image = cv::imread("faces.jpg"); auto box_result = infer->commit(image).get(); auto tic = kiwi::timestamp_now_float(); for(int i = 0; i < 100; ++i){ infer->commit(image).get(); } auto toc = kiwi::timestamp_now_float(); INFO("nanodet time: %f ms", (toc - tic) / 100); for(auto& obj : box_result){ cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(0, 255, 0), 2); } cv::imwrite("nanodet-result.jpg", image); } void arcface_demo(){ auto det = scrfd::create_infer("scrfd_2.5g_bnkps.rknn", 0.4, 0.5); auto ext = arcface::create_infer("w600k_r50_new.rknn"); auto a = cv::imread("library/2ys3.jpg"); auto b = cv::imread("library/male.jpg"); auto c = cv::imread("library/2ys5.jpg"); auto compute_sim = [](const cv::Mat& a, const cv::Mat& b){ auto c = cv::Mat(a * b.t()); return *c.ptr<float>(0); }; auto extract_feature = [&](const cv::Mat& image){ auto faces = det->commit(image).get(); if(faces.empty()){ INFOE("Can not detect any face"); return cv::Mat(); } auto max_face = std::max_element(faces.begin(), faces.end(), [](kiwi::Face& a, kiwi::Face& b){ return (a.right - a.left) * (a.bottom - a.top) > (b.right - b.left) * (b.bottom - b.top); }); auto out = arcface::face_alignment(image, max_face->landmark); return ext->commit(out, true).get(); }; auto fa = extract_feature(a); auto fb = extract_feature(b); auto fc = extract_feature(c); float ab = compute_sim(fa, fb); float ac = compute_sim(fa, fc); float bc = compute_sim(fb, fc); INFO("ab[differ] = %f, ac[same] = %f, bc[differ] = %f", ab, ac, bc); } int main(){ test_pref("person_m416_plus_V15.rknn"); test_pref("scrfd_2.5g_bnkps.rknn"); test_pref("w600k_r50_new.rknn"); // scrfd_demo(); // nanodet_demo(); arcface_demo(); return 0; }
30.726496
119
0.59249
shouxieai