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 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7c0597aa563fb5f1065fc14f1813fe249d8a795c | 433 | cpp | C++ | W08/in_lab/Account.cpp | ariaav/OOP244 | bcfc52bfff86b68e4f464e85b8555eef541741a0 | [
"MIT"
] | null | null | null | W08/in_lab/Account.cpp | ariaav/OOP244 | bcfc52bfff86b68e4f464e85b8555eef541741a0 | [
"MIT"
] | null | null | null | W08/in_lab/Account.cpp | ariaav/OOP244 | bcfc52bfff86b68e4f464e85b8555eef541741a0 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Account.h"
namespace sict {
Account::Account(double bal) {
if (bal > 0)
bala = bal;
else
bala = 0;
}
bool Account::credit(double add) {
if (add > 0){
bala += add;
return true;
}
else
return false;
}
bool Account::debit(double sub) {
if (sub > 0) {
bala -= sub;
return true;
}
else
return false;
}
double Account::balance() const {
return bala;
}
} | 12.371429 | 35 | 0.577367 |
7c0fe5fd6a310e5dd2f79b822fe425d9cce77f87 | 851 | cpp | C++ | amara/amara_tweenBase.cpp | BigBossErndog/Amara | e534001dee88b7d66f7384ed167257ffac58aac3 | [
"MIT"
] | null | null | null | amara/amara_tweenBase.cpp | BigBossErndog/Amara | e534001dee88b7d66f7384ed167257ffac58aac3 | [
"MIT"
] | null | null | null | amara/amara_tweenBase.cpp | BigBossErndog/Amara | e534001dee88b7d66f7384ed167257ffac58aac3 | [
"MIT"
] | null | null | null | #ifndef AMARA_TWEENBASE
#define AMARA_TWEENBASE
#include "amara.h"
namespace Amara {
class Tweener;
class Tween: public Amara::StateManager {
public:
Amara::GameProperties* properties = nullptr;
bool finished = false;
bool deleteOnFinish = true;
double progress = 0;
float time = 0;
virtual void assign(Amara::Tweener* gTweener, Amara::GameProperties* gProperties) {
properties = gProperties;
}
virtual void run() {
progress += (time/properties->lps);
if (progress >= 1) {
finished = true;
progress = 1;
}
}
virtual void reset() {
progress = 0;
}
};
}
#endif | 23.638889 | 95 | 0.480611 |
7c11f304a4c71c599e3aa18728323cf90f51aaa3 | 2,138 | cc | C++ | 2021/5/main.cc | ey6es/aoc | c1e54534e5e6d4b52118ffd173834ab56a831102 | [
"MIT"
] | null | null | null | 2021/5/main.cc | ey6es/aoc | c1e54534e5e6d4b52118ffd173834ab56a831102 | [
"MIT"
] | null | null | null | 2021/5/main.cc | ey6es/aoc | c1e54534e5e6d4b52118ffd173834ab56a831102 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
std::tuple<int, int> parse_coord (const std::string& str) {
auto idx = str.find(',');
return std::make_tuple(
std::stoi(str.substr(0, idx)),
std::stoi(str.substr(idx + 1)));
}
std::ostream& operator<< (std::ostream& out, const std::tuple<int, int>& tuple) {
return out << std::get<0>(tuple) << " " << std::get<1>(tuple);
}
int main () {
std::ifstream in("input.txt");
std::map<std::tuple<int, int>, int> points;
while (in.good()) {
std::string line;
std::getline(in, line);
if (!in.good()) break;
auto start = parse_coord(line.substr(0, line.find(' ')));
auto end = parse_coord(line.substr(line.rfind(' ') + 1));
auto sx = std::get<0>(start);
auto sy = std::get<1>(start);
auto ex = std::get<0>(end);
auto ey = std::get<1>(end);
if (sx == ex) { // vertical line
auto x = sx;
auto minmax_y = std::minmax(sy, ey);
for (auto y = minmax_y.first; y <= minmax_y.second; y++) {
points[std::make_tuple(x, y)]++;
}
} else if (sy == ey) { // horizontal
auto y = sy;
auto minmax_x = std::minmax(sx, ex);
for (auto x = minmax_x.first; x <= minmax_x.second; x++) {
points[std::make_tuple(x, y)]++;
}
} else {
auto dx = ex - sx;
auto dy = ey - sy;
if (dx == dy) {
if (dx > 0) {
for (auto c = 0; c <= dx; c++) {
points[std::make_tuple(sx + c, sy + c)]++;
}
} else {
for (auto c = dx; c <= 0; c++) {
points[std::make_tuple(sx + c, sy + c)]++;
}
}
} else if (dx == -dy) {
if (dx > 0) {
for (auto c = 0; c <= dx; c++) {
points[std::make_tuple(sx + c, sy - c)]++;
}
} else {
for (auto c = dx; c <= 0; c++) {
points[std::make_tuple(sx + c, sy - c)]++;
}
}
}
}
}
int count = 0;
for (auto& pair : points) {
if (pair.second >= 2) count++;
}
std::cout << count << std::endl;
}
| 24.860465 | 81 | 0.481291 |
7c1885c5d71e72c411d50181d4b84e586de72b3f | 635 | cpp | C++ | 0014.cpp | excript/curso_cpp | 070d0bd1163c1252b7bf736fedb3370208c30811 | [
"CC0-1.0"
] | 1 | 2020-08-01T07:03:32.000Z | 2020-08-01T07:03:32.000Z | 0014.cpp | excript/curso_cpp | 070d0bd1163c1252b7bf736fedb3370208c30811 | [
"CC0-1.0"
] | 1 | 2020-08-01T07:04:27.000Z | 2020-08-01T07:04:27.000Z | 0014.cpp | excript/curso_cpp | 070d0bd1163c1252b7bf736fedb3370208c30811 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <iomanip>
/*====================================
* eXcript.com
* fb.com/eXcript
* ====================================*/
using namespace std;
int main() {
//obj cin3
//obj cout
cout << "Estudando a entrada e saida de dados." << endl;
// cout << setw(10) << 1 << endl;
// cout << setw(10) << 2 << endl;
// cout << setw(10) << 3 << endl;
// cout << setw(10) << 4 << endl;
cout << setw(10) << 1456;
cout << setw(10) << 25343543;
cout << setw(10) << 3456546;
cout << setw(10) << 44455;
system("pause");
return 0;
} | 19.84375 | 60 | 0.445669 |
7c1b5d88f091c7ddf7a60fc1969c757257d02a8d | 907 | hh | C++ | src/agents/pacman/pathfinding_pacman_agent.hh | emanuelssj/PacmanRL | 275715f7024e1ffab8a562c892a9852d4d7f16cb | [
"MIT"
] | 3 | 2019-01-07T10:15:21.000Z | 2019-03-25T15:36:39.000Z | src/agents/pacman/pathfinding_pacman_agent.hh | emanuelssj/Lunafreya-Pacman-Speedrun | 275715f7024e1ffab8a562c892a9852d4d7f16cb | [
"MIT"
] | null | null | null | src/agents/pacman/pathfinding_pacman_agent.hh | emanuelssj/Lunafreya-Pacman-Speedrun | 275715f7024e1ffab8a562c892a9852d4d7f16cb | [
"MIT"
] | 1 | 2019-05-26T07:48:21.000Z | 2019-05-26T07:48:21.000Z | #ifndef PATHFINDING_PACMAN_AGENT_HH
#define PATHFINDING_PACMAN_AGENT_HH
#include "../agent.hh"
#include "../../state/direction.hh"
#include "../../pathfinding/bfs.hh"
#include "../../pathfinding/wsp.hh"
#include <cmath>
class Pathfinding_Pacman_Agent: public Agent {
// In this case ghost_id can be ignored
inline Direction take_action(const State& s, uint ghost_id) {
if (s.distance_closest_harmful_ghost(s.pacman.pos) < 10) {
return wsp(s.pacman.pos,
[&s](const Position& pos) { return s.has_any_pill(pos); },
s,
[&s](const Position& pos) { return 10*pow(2, 10 - min(10,s.distance_closest_harmful_ghost(pos))); }
).dir;
}
else return bfs(s.pacman.pos,
[&s](const Position& pos) { return s.has_any_pill(pos); },
s).dir;
}
};
#endif
| 32.392857 | 122 | 0.582139 |
7c1f8355be92bc68e9e7eda8058f71239ef53cb8 | 4,614 | cpp | C++ | Stabilization/Stabilization.cpp | Ablaaaym/Satellite | 87c93cfbadcaae57767964957d81a98daff25bfe | [
"Apache-2.0"
] | null | null | null | Stabilization/Stabilization.cpp | Ablaaaym/Satellite | 87c93cfbadcaae57767964957d81a98daff25bfe | [
"Apache-2.0"
] | null | null | null | Stabilization/Stabilization.cpp | Ablaaaym/Satellite | 87c93cfbadcaae57767964957d81a98daff25bfe | [
"Apache-2.0"
] | null | null | null | #define PIN_ENA 9 //вывод управления скоростью вращения мотора №1
#define PIN_IN1 10 //вывод управления направлением вращения мотора №1
#define PIN_IN2 11 //вывод управления направлением вращения мотора №1
#define PIN_Left 7 //вход с расбери для скорости
#define PIN_Right 12 //вход с расбери для скорости
#define PIN_speed 4 //вход с расбери для скорости
#define PIN_return 13 //вход с расбери о прекращении работы алгоритма стабилизации
int detection = 0; //был ли обнаружен объект
int obgon = 0; //был обгон или отставание
uint8_t power = 105; //значение ШИМ (или скорости вращения)
void setup()
{
pinMode(PIN_ENA, OUTPUT); //установка всех управляющих пинов в режим выхода и входа
pinMode(PIN_IN1, OUTPUT);
pinMode(PIN_IN2, OUTPUT);
pinMode(PIN_Left, INPUT);
pinMode(PIN_Right, INPUT);
pinMode(PIN_speed, INPUT);
pinMode(PIN_return, INPUT);
digitalWrite(PIN_IN1, LOW); //команда остановки двум моторам
digitalWrite(PIN_IN2, LOW);
}
void loop()
{
int valLeft = digitalRead(PIN_Left);
int valRight = digitalRead(PIN_Right);
int valspeed = digitalRead(PIN_speed);
int runprog = digitalRead(PIN_return);
if (runprog == 1) //пришел сигнал о необходимости стабилизации
{
if((detection == 0) and ((valLeft == 1) or (valRight == 1) or (valspeed == 1))) //объект находится в зоне видимости
{
detection = 1;
}
if((valLeft == 1) or (valRight == 1) or (valspeed ==1)) //объект находится в зоне видимости
{
if ( (valLeft == 0) and (valRight == 0) and (valspeed == 1)) //догоняющая 1 скорость
{
analogWrite (PIN_ENA, 150);
digitalWrite(PIN_IN1, HIGH);
digitalWrite(PIN_IN2, LOW);
obgon = 1;
}
if ( (valLeft == 0) and (valRight == 1) and (valspeed == 0)) //догоняющая 2 скорость
{
analogWrite (PIN_ENA, 120);
digitalWrite(PIN_IN1, HIGH);
digitalWrite(PIN_IN2, LOW);
obgon = 1;
}
if ( (valLeft == 0) and (valRight == 1) and (valspeed == 1)) //догоняющая 3 скорость
{
analogWrite (PIN_ENA, 100);
digitalWrite(PIN_IN1, HIGH);
digitalWrite(PIN_IN2, LOW);
obgon = 1;
}
if ( (valLeft == 1) and (valRight == 0) and (valspeed == 1)) //нормальное состояние
{
analogWrite (PIN_ENA, 0);
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, LOW);
obgon = 0;
}
if ( (valLeft == 1) and (valRight == 0) and (valspeed == 0)) //обратная 3 скорость
{
analogWrite (PIN_ENA, 100);
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, HIGH);
obgon = 0;
}
if ( (valLeft == 1) and (valRight == 1) and (valspeed == 0)) //обратная 2 скорость
{
analogWrite (PIN_ENA, 120);
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, HIGH);
obgon = 0;
}
if ( (valLeft == 1) and (valRight == 1) and (valspeed == 1)) //обратная 1 скорость
{
analogWrite (PIN_ENA, 150);
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, HIGH);
obgon = 0;
}
}
if(detection==1) //если объект был обнаружен
{
if ((valLeft == 0) and (valRight == 0) and (valspeed == 0)) //объект не находится в зоне видимости
{
if( (obgon == 0)) //отстал
{
analogWrite(PIN_ENA, 200); //догоняющее движение со скоростью 200
digitalWrite(PIN_IN1, HIGH);
digitalWrite(PIN_IN2, LOW);
}
if((obgon == 1)) //обогнал
{
analogWrite(PIN_ENA, 200); //обратное движение со скоростью 200
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, HIGH);
}
}
}
}
if (runprog == 0) //отключение для будущего поиска новых объектов
{
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, LOW);
detection = 0;
}
}
| 35.767442 | 124 | 0.508669 |
7c21bfccc01efd7eb0c020508aee97d438dd283a | 3,971 | cpp | C++ | cpr/unit_test_for_huffman/unit_test_for_bit_string.cpp | Mooophy/Compression | 2d369956a83703f0283d36d438e76783e909957d | [
"MIT"
] | 14 | 2015-03-04T23:12:03.000Z | 2021-07-14T14:30:45.000Z | cpr/unit_test_for_huffman/unit_test_for_bit_string.cpp | Mooophy/Compression | 2d369956a83703f0283d36d438e76783e909957d | [
"MIT"
] | 7 | 2015-03-02T08:52:54.000Z | 2015-03-09T08:32:09.000Z | cpr/unit_test_for_huffman/unit_test_for_bit_string.cpp | Mooophy/Compression | 2d369956a83703f0283d36d438e76783e909957d | [
"MIT"
] | 7 | 2015-03-04T23:13:14.000Z | 2017-05-24T11:39:55.000Z | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../huffman/bit_string.hpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace unit_test_for_huffman
{
TEST_CLASS(unit_test_for_bit_string)
{
public:
TEST_METHOD(ctor)
{
cpr::huffman::BitString<char> bit_string;
}
TEST_METHOD(data)
{
cpr::huffman::BitString<char> bit_string;
Assert::AreEqual(0u, bit_string.str().size());
}
TEST_METHOD(bit_length)
{
cpr::huffman::BitString<char> bit_string;
Assert::AreEqual(1u, bit_string.bit_length(0x00));
Assert::AreEqual(7u, bit_string.bit_length(0x7f));
Assert::AreEqual(8u, bit_string.bit_length(-0x01));
Assert::AreEqual(8u, bit_string.bit_length(-0x7f));
Assert::AreEqual(8u, bit_string.bit_length(-0x80));
Assert::AreNotEqual(8u, bit_string.bit_length((char)-0x81));
}
TEST_METHOD(push_back_bits)
{
// case 1
cpr::huffman::BitString<char> bit_string;
bit_string.push_back_bits(0);
Assert::AreEqual((char)0, bit_string.str().front());
bit_string.push_back_bits((char)0xff);
std::string expected(1, 0);
expected += std::string(8, 1);
Assert::AreEqual(expected, bit_string.str());
Assert::AreEqual(9u, bit_string.str().size());
//case 2
cpr::huffman::BitString<char> bs_for_testing_minus_number;
bs_for_testing_minus_number.push_back_bits(char(-1));
Assert::AreEqual(8u, bs_for_testing_minus_number.str().size());
bs_for_testing_minus_number.push_back_bits(0);
Assert::AreEqual(9u, bs_for_testing_minus_number.str().size());
//case 3
cpr::huffman::BitString<char> case3;
case3.push_back_bits(0x07);
std::string expected_for_case3(3, 1);
Assert::AreEqual(expected_for_case3, case3.str());
}
// protocol :
// FrequencyTable|CompressedPart|Remainder|RemainderSize
TEST_METHOD(compress_case1)
{
cpr::huffman::BitString<char> bit_string;
bit_string.push_back_bits((char)0);
std::string compressed = bit_string.compress('|');
//note the compressed part is empty
Assert::AreEqual(4u, compressed.size());
std::string exprected{ '|', 0, '|', 1 };
Assert::AreEqual(exprected, compressed);
}
TEST_METHOD(compress_case2)
{
cpr::huffman::BitString<char> bit_string;
bit_string.push_back_bits((char)0xff);
std::string compressed = bit_string.compress('|');
Assert::AreEqual(5u, compressed.size());
std::string exprected{ (char)0xff, '|', 0, '|', 0 };
Assert::AreEqual(exprected, compressed);
}
TEST_METHOD(compress_case3)
{
cpr::huffman::BitString<char> bit_string;
bit_string.push_back_bits((char)0X00);
bit_string.push_back_bits((char)0Xff);
std::string compressed = bit_string.compress('|');
Assert::AreEqual(5u, compressed.size());
std::string exprected{ (char)0x7f, '|', 1, '|', 1 };
Assert::AreEqual(exprected, compressed);
}
TEST_METHOD(compress_case4)
{
cpr::huffman::BitString<char> bit_string;
bit_string.push_back_bits((char)0X00);
bit_string.push_back_bits((char)0Xff);
bit_string.push_back_bits((char)0Xff);
std::string compressed = bit_string.compress('|');
Assert::AreEqual(6u, compressed.size());
std::string exprected{ (char)0x7f, (char)0xff, '|', 1, '|', 1 };
Assert::AreEqual(exprected, compressed);
}
};
} | 33.940171 | 76 | 0.578444 |
7c283dc0e0c52f8c51f5f4a8f987d346aa6b947f | 2,624 | cpp | C++ | Utilities/MarbleAction/MarbleAction.cpp | mym2o/HavokDemos | 1235b96b93e256de50bc36c229439a334410fd77 | [
"MIT"
] | 1 | 2017-08-14T10:23:45.000Z | 2017-08-14T10:23:45.000Z | Utilities/MarbleAction/MarbleAction.cpp | mym2o/HavokDemos | 1235b96b93e256de50bc36c229439a334410fd77 | [
"MIT"
] | null | null | null | Utilities/MarbleAction/MarbleAction.cpp | mym2o/HavokDemos | 1235b96b93e256de50bc36c229439a334410fd77 | [
"MIT"
] | 2 | 2016-06-22T02:22:32.000Z | 2019-11-21T19:49:41.000Z | #include "MarbleAction.h"
MarbleAction::MarbleAction(hkpRigidBody* r, const hkVector4& forward, const hkVector4& resetPosition, hkReal impulseScale) : hkpUnaryAction(r), m_forward(forward), m_resetPosition(resetPosition), m_rotationIncrement(0.01f) {
m_forwardPressed = false;
m_backwardPressed = false;
m_leftPressed = false;
m_rightPressed = false;
m_jumpPressed = false;
m_brakePressed = false;
m_lastJump = 0.f;
m_impulseScale = impulseScale;
m_lasttimeCalled = 0.f;
m_currentAngle = 0.f;
}
void MarbleAction::applyAction(const hkStepInfo& stepInfo) {
hkpRigidBody* rb = getRigidBody();
//we need the delta time to record how long it's been since we last jumped
//(to avoid jumping while in the air!)
hkReal dt = stepInfo.m_deltaTime;
//get a "scale" to change the force of the impulse by, depending on both the mass of the body,
//an arbitrary "gain", eg 0.1
hkReal scale = rb->getMass() * m_impulseScale;
hkVector4 axis(0, 1, 0);
hkQuaternion q(axis, m_currentAngle);
hkVector4 f;
f.setRotatedDir(q, m_forward);
if (m_forwardPressed) {
hkVector4 imp;
imp.setMul4(scale, f);
rb->applyLinearImpulse(imp);
}
if (m_backwardPressed) {
hkVector4 imp;
imp.setMul4(-scale, f);
rb->applyLinearImpulse(imp);
}
if (m_rightPressed) {
m_currentAngle += 3.141592653f * 2 * m_rotationIncrement;
}
if (m_leftPressed) {
m_currentAngle -= 3.141592653f * 2 * m_rotationIncrement;
}
m_lasttimeCalled += dt;
//Jump (only if haven't jumped for at least 1 second)
if (m_jumpPressed && ((m_lasttimeCalled - m_lastJump) > 1.f)) {
m_lastJump = m_lasttimeCalled;
hkVector4 imp(0, rb->getMass() * 6, 0);
rb->applyLinearImpulse(imp);
setJumpPressed(false);
}
setJumpPressed(false);
//if brake pressed, zero all velocities
if (m_brakePressed) {
hkVector4 zero;
zero.setZero4();
rb->setLinearVelocity(zero);
rb->setAngularVelocity(zero);
setBrakePressed(false);
}
//draw current "facing" direction, usings "Debug" line. This gets pushed onto a global list,
//and gets dealt with by (perhaps) a drawDebugPointsAndLines() method from the mainline
start = rb->getPosition();
//end = start + 1.5 * "forward"
end = start;
f.mul4(1.5f);
end.add4(f);
//TODO: draw line from start to end
}
void MarbleAction::reset() {
hkpRigidBody* rb = getRigidBody();
//put marble back to the reset position defined on construction, and zero velocities
hkVector4 zero;
zero.setZero4();
rb->setPosition(m_resetPosition);
rb->setLinearVelocity(zero);
rb->setAngularVelocity(zero);
} | 28.835165 | 225 | 0.699695 |
7c28f9a0f641f5f618db137ee21ad79407c3aef8 | 13,626 | cc | C++ | src/ShaderCompiler/Private/GLSLangUtils.cc | PixPh/kaleido3d | 8a8356586f33a1746ebbb0cfe46b7889d0ae94e9 | [
"MIT"
] | 38 | 2019-01-10T03:10:12.000Z | 2021-01-27T03:14:47.000Z | src/ShaderCompiler/Private/GLSLangUtils.cc | fuqifacai/kaleido3d | ec77753b516949bed74e959738ef55a0bd670064 | [
"MIT"
] | null | null | null | src/ShaderCompiler/Private/GLSLangUtils.cc | fuqifacai/kaleido3d | ec77753b516949bed74e959738ef55a0bd670064 | [
"MIT"
] | 8 | 2019-04-16T07:56:27.000Z | 2020-11-19T02:38:37.000Z | #include <Kaleido3D.h>
#include "GLSLangUtils.h"
#include <glslang/MachineIndependent/gl_types.h>
using namespace ::glslang;
using namespace ::k3d;
void sInitializeGlSlang()
{
#if USE_GLSLANG
static bool sGlSlangIntialized = false;
if (!sGlSlangIntialized) {
glslang::InitializeProcess();
sGlSlangIntialized = true;
}
#endif
}
void sFinializeGlSlang()
{
#if USE_GLSLANG
static bool sGlSlangFinalized = false;
if (!sGlSlangFinalized) {
glslang::FinalizeProcess();
sGlSlangFinalized = true;
}
#endif
}
NGFXShaderDataType glTypeToRHIAttribType(int glType)
{
switch (glType)
{
case GL_FLOAT:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT;
case GL_FLOAT_VEC2:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2;
case GL_FLOAT_VEC3:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT3;
case GL_FLOAT_VEC4:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4;
case GL_INT:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT;
case GL_INT_VEC2:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT2;
case GL_INT_VEC3:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT3;
case GL_INT_VEC4:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT4;
case GL_UNSIGNED_INT:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT;
case GL_UNSIGNED_INT_VEC2:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT2;
case GL_UNSIGNED_INT_VEC3:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT3;
case GL_UNSIGNED_INT_VEC4:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT4;
}
return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
NGFXShaderDataType glTypeToRHIUniformType(int glType)
{
switch (glType)
{
case GL_FLOAT:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT;
case GL_FLOAT_VEC2:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2;
case GL_FLOAT_VEC3:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT3;
case GL_FLOAT_VEC4:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4;
case GL_INT:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT;
case GL_INT_VEC2:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT2;
case GL_INT_VEC3:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT3;
case GL_INT_VEC4:
return NGFXShaderDataType::NGFX_SHADER_VAR_INT4;
case GL_UNSIGNED_INT:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT;
case GL_UNSIGNED_INT_VEC2:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT2;
case GL_UNSIGNED_INT_VEC3:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT3;
case GL_UNSIGNED_INT_VEC4:
return NGFXShaderDataType::NGFX_SHADER_VAR_UINT4;
}
return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
NGFXShaderDataType glslangDataTypeToRHIDataType(const TType& type)
{
switch (type.getBasicType()) {
case EbtSampler:
{
switch (type.getQualifier().layoutFormat)
{
case ElfRgba32f:
return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4;
}
}
case EbtStruct:
case EbtBlock:
case EbtVoid:
return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
default:
break;
}
if (type.isVector()) {
int offset = type.getVectorSize() - 2;
switch (type.getBasicType()) {
case EbtFloat: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2 + offset);
//case EbtDouble: return GL_DOUBLE_VEC2 + offset;
#ifdef AMD_EXTENSIONS
//case EbtFloat16: return GL_FLOAT16_VEC2_NV + offset;
#endif
case EbtInt: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_INT2 + offset);
case EbtUint: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_UINT2 + offset);
//case EbtInt64: return GL_INT64_ARB + offset;
//case EbtUint64: return GL_UNSIGNED_INT64_ARB + offset;
case EbtBool: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_BOOL2 + offset);
//case EbtAtomicUint: return GL_UNSIGNED_INT_ATOMIC_COUNTER + offset;
default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
}
if (type.isMatrix())
{
switch (type.getBasicType())
{
case EbtFloat:
switch (type.getMatrixCols())
{
case 2:
switch (type.getMatrixRows())
{
case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2;
case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2X3;
case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2X4;
default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
case 3:
switch (type.getMatrixRows())
{
case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3X2;
case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3;
case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3X4;
default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
case 4:
switch (type.getMatrixRows())
{
case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4X2;
case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4X3;
case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4;
default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
}
}
}
if (type.getVectorSize() == 1) {
switch (type.getBasicType()) {
case EbtFloat: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT;
case EbtInt: return NGFXShaderDataType::NGFX_SHADER_VAR_INT;
case EbtUint: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT;
case EbtBool: return NGFXShaderDataType::NGFX_SHADER_VAR_BOOL;
default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
}
return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN;
}
NGFXShaderBindType glslangTypeToRHIType(const TBasicType& type)
{
switch (type)
{
case EbtSampler:
return NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLER;
case EbtStruct:
case EbtBlock:
return NGFXShaderBindType::NGFX_SHADER_BIND_BLOCK;
case EbtVoid:
return NGFXShaderBindType::NGFX_SHADER_BIND_UNDEFINED;
default:
break;
}
return NGFXShaderBindType::NGFX_SHADER_BIND_BLOCK;
}
void initResources(TBuiltInResource &resources)
{
resources.maxLights = 32;
resources.maxClipPlanes = 6;
resources.maxTextureUnits = 32;
resources.maxTextureCoords = 32;
resources.maxVertexAttribs = 64;
resources.maxVertexUniformComponents = 4096;
resources.maxVaryingFloats = 64;
resources.maxVertexTextureImageUnits = 32;
resources.maxCombinedTextureImageUnits = 80;
resources.maxTextureImageUnits = 32;
resources.maxFragmentUniformComponents = 4096;
resources.maxDrawBuffers = 32;
resources.maxVertexUniformVectors = 128;
resources.maxVaryingVectors = 8;
resources.maxFragmentUniformVectors = 16;
resources.maxVertexOutputVectors = 16;
resources.maxFragmentInputVectors = 15;
resources.minProgramTexelOffset = -8;
resources.maxProgramTexelOffset = 7;
resources.maxClipDistances = 8;
resources.maxComputeWorkGroupCountX = 65535;
resources.maxComputeWorkGroupCountY = 65535;
resources.maxComputeWorkGroupCountZ = 65535;
resources.maxComputeWorkGroupSizeX = 1024;
resources.maxComputeWorkGroupSizeY = 1024;
resources.maxComputeWorkGroupSizeZ = 64;
resources.maxComputeUniformComponents = 1024;
resources.maxComputeTextureImageUnits = 16;
resources.maxComputeImageUniforms = 8;
resources.maxComputeAtomicCounters = 8;
resources.maxComputeAtomicCounterBuffers = 1;
resources.maxVaryingComponents = 60;
resources.maxVertexOutputComponents = 64;
resources.maxGeometryInputComponents = 64;
resources.maxGeometryOutputComponents = 128;
resources.maxFragmentInputComponents = 128;
resources.maxImageUnits = 8;
resources.maxCombinedImageUnitsAndFragmentOutputs = 8;
resources.maxCombinedShaderOutputResources = 8;
resources.maxImageSamples = 0;
resources.maxVertexImageUniforms = 0;
resources.maxTessControlImageUniforms = 0;
resources.maxTessEvaluationImageUniforms = 0;
resources.maxGeometryImageUniforms = 0;
resources.maxFragmentImageUniforms = 8;
resources.maxCombinedImageUniforms = 8;
resources.maxGeometryTextureImageUnits = 16;
resources.maxGeometryOutputVertices = 256;
resources.maxGeometryTotalOutputComponents = 1024;
resources.maxGeometryUniformComponents = 1024;
resources.maxGeometryVaryingComponents = 64;
resources.maxTessControlInputComponents = 128;
resources.maxTessControlOutputComponents = 128;
resources.maxTessControlTextureImageUnits = 16;
resources.maxTessControlUniformComponents = 1024;
resources.maxTessControlTotalOutputComponents = 4096;
resources.maxTessEvaluationInputComponents = 128;
resources.maxTessEvaluationOutputComponents = 128;
resources.maxTessEvaluationTextureImageUnits = 16;
resources.maxTessEvaluationUniformComponents = 1024;
resources.maxTessPatchComponents = 120;
resources.maxPatchVertices = 32;
resources.maxTessGenLevel = 64;
resources.maxViewports = 16;
resources.maxVertexAtomicCounters = 0;
resources.maxTessControlAtomicCounters = 0;
resources.maxTessEvaluationAtomicCounters = 0;
resources.maxGeometryAtomicCounters = 0;
resources.maxFragmentAtomicCounters = 8;
resources.maxCombinedAtomicCounters = 8;
resources.maxAtomicCounterBindings = 1;
resources.maxVertexAtomicCounterBuffers = 0;
resources.maxTessControlAtomicCounterBuffers = 0;
resources.maxTessEvaluationAtomicCounterBuffers = 0;
resources.maxGeometryAtomicCounterBuffers = 0;
resources.maxFragmentAtomicCounterBuffers = 1;
resources.maxCombinedAtomicCounterBuffers = 1;
resources.maxAtomicCounterBufferSize = 16384;
resources.maxTransformFeedbackBuffers = 4;
resources.maxTransformFeedbackInterleavedComponents = 64;
resources.maxCullDistances = 8;
resources.maxCombinedClipAndCullDistances = 8;
resources.maxSamples = 4;
resources.limits.nonInductiveForLoops = 1;
resources.limits.whileLoops = 1;
resources.limits.doWhileLoops = 1;
resources.limits.generalUniformIndexing = 1;
resources.limits.generalAttributeMatrixVectorIndexing = 1;
resources.limits.generalVaryingIndexing = 1;
resources.limits.generalSamplerIndexing = 1;
resources.limits.generalVariableIndexing = 1;
resources.limits.generalConstantMatrixVectorIndexing = 1;
}
EShLanguage findLanguage(const NGFXShaderType shader_type)
{
switch (shader_type)
{
case NGFX_SHADER_TYPE_VERTEX:
return EShLangVertex;
case NGFX_SHADER_TYPE_HULL:
return EShLangTessControl;
case NGFX_SHADER_TYPE_DOMAIN:
return EShLangTessEvaluation;
case NGFX_SHADER_TYPE_GEOMETRY:
return EShLangGeometry;
case NGFX_SHADER_TYPE_FRAGMENT:
return EShLangFragment;
case NGFX_SHADER_TYPE_COMPUTE:
return EShLangCompute;
default:
return EShLangVertex;
}
}
void ExtractAttributeData(const TProgram& program, NGFXShaderAttributes& shAttributes)
{
auto numAttrs = program.getNumLiveAttributes();
if (numAttrs > 0)
{
for (uint32 i = 0; i < numAttrs; i++)
{
auto name = program.getAttributeName(i);
auto type = program.getAttributeType(i);
shAttributes.Append({name, NGFX_SEMANTIC_POSITION, glTypeToRHIAttribType(type), i, 0, 0});
}
}
}
void ExtractUniformData(NGFXShaderType const& stype, const TProgram& program, NGFXShaderBindingTable& outUniformLayout)
{
auto numUniforms = program.getNumLiveUniformVariables();
for (int i = 0; i < numUniforms; i++)
{
auto name = program.getUniformName(i);
auto index = program.getUniformIndex(name);
auto type = program.getUniformTType(index);
bool isImage = type->isImage();
auto baseType = type->getBasicType();
auto qualifier = type->getQualifier();
if (qualifier.hasBinding())
{
NGFXShaderBindType bind = glslangTypeToRHIType(baseType);
if (baseType == EbtSampler)
{
if (type->getSampler().isCombined())
{
bind = NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLER_IMAGE_COMBINE;
}
switch (type->getSampler().dim)
{
case Esd1D:
case Esd2D:
case Esd3D:
case EsdCube:
case EsdRect:
bind = NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLED_IMAGE;
break;
}
if (type->isImage())
{
switch (qualifier.storage)
{
case EvqUniform:
bind = NGFXShaderBindType::NGFX_SHADER_BIND_RWTEXEL_BUFFER;
break;
case EvqBuffer:
bind = NGFXShaderBindType::NGFX_SHADER_BIND_RWTEXEL_BUFFER;
break;
}
}
}
outUniformLayout.AddBinding({bind, name, stype, qualifier.layoutBinding});
}
if (qualifier.hasSet())
{
outUniformLayout.AddSet(qualifier.layoutSet);
}
if (baseType == EbtSampler)
{
auto sampler = type->getSampler();
if (!sampler.combined)
{
outUniformLayout.AddUniform({glslangDataTypeToRHIDataType(*type), name, qualifier.hasOffset() ? (uint32)qualifier.layoutOffset : 0, /*type->getArraySizes()*/});
}
}
else
{
outUniformLayout.AddUniform({glslangDataTypeToRHIDataType(*type), name, qualifier.hasOffset() ? (uint32)qualifier.layoutOffset : 0, /*type->getArraySizes()*/});
}
}
auto numUniformBlocks = program.getNumLiveUniformBlocks();
for (int i = 0; i < numUniformBlocks; i++)
{
auto block = program.getUniformBlockTType(i);
auto name = program.getUniformBlockName(i);
auto bindNum = program.getUniformBlockIndex(i);
auto bType = block->getBasicType();
auto qualifier = block->getQualifier();
if (qualifier.hasSet())
{
outUniformLayout.AddSet(qualifier.layoutSet);
}
if (qualifier.hasBinding())
{
outUniformLayout.AddBinding({glslangTypeToRHIType(bType), name, stype, (uint32)qualifier.layoutBinding});
}
switch (bType)
{
case EbtString:
break;
}
}
}
| 32.754808 | 168 | 0.754954 |
7c2b82eba95378926615f75703f463e29eb82ff6 | 3,288 | cpp | C++ | Project Mania/Source/Character/Chassis.cpp | larsolm/Archives | 18968c18b80777e589bc8a704b4375be2fff8eea | [
"MIT"
] | null | null | null | Project Mania/Source/Character/Chassis.cpp | larsolm/Archives | 18968c18b80777e589bc8a704b4375be2fff8eea | [
"MIT"
] | null | null | null | Project Mania/Source/Character/Chassis.cpp | larsolm/Archives | 18968c18b80777e589bc8a704b4375be2fff8eea | [
"MIT"
] | null | null | null | #include "Pch.h"
#include "Character/Character.h"
#include "Character/Chassis.h"
#include "Data/AugmentData.h"
#include "Data/CharacterData.h"
#include "Data/ComponentData.h"
#include "Data/ChassisData.h"
#include "Data/EquipmentData.h"
#include "Data/UpgradeData.h"
#include "Data/PartData.h"
#include "Parts/Item.h"
#include "Parts/Equipment.h"
#include "Parts/Weapon.h"
#include "Parts/Upgrade.h"
void Chassis::Initialize()
{
Skeleton = Data->Skeleton->CreateSkeleton();
Skeleton->Data = Data->Skeleton;
Skeleton->Character = Character;
Skeleton->Initialize();
for (auto& attachment : Data->Attachments)
{
auto part = AttachPart(attachment.Bone, *attachment.Part);
for (auto i = 0; i < attachment.Components.Count(); i++)
attachment.Components.Item(i)->Apply(*part, i);
for (auto augment : attachment.Augments)
augment->Apply(*part);
}
Character->Health = GetMaxHealth();
Character->Shield = GetMaxShield();
}
void Chassis::Update(float elapsed)
{
for (auto& equipment : Equipment)
equipment->Update(elapsed, false, false, false);
for (auto i = 0; i < Items.Count(); i++)
{
auto item = static_cast<Item*>(Items.Item(i).get());
auto active = Character->ActiveItemSlot == i;
auto primary = active && Character->Controller->ItemPrimary;
auto secondary = active && Character->Controller->ItemSecondary;
item->Update(elapsed, active, primary, secondary);
}
for (auto i = 0; i < Weapons.Count(); i++)
{
auto weapon = static_cast<Weapon*>(Weapons.Item(i).get());
auto active = Character->ActiveWeaponSlot == i;
auto primary = active && Character->Controller->WeaponPrimary;
auto secondary = active && Character->Controller->WeaponSecondary;
weapon->Update(elapsed, active, primary, secondary);
}
}
auto Chassis::AttachPart(StringView name, PartData& data) -> Part*
{
auto& bone = Skeleton->GetBone(name);
assert(bone.Data->AttachmentType == data.Bone.AttachmentType);
auto part = data.CreatePart();
part->Data = &data;
part->Character = Character;
part->Bone = &bone;
part->Initialize();
switch (data.Bone.AttachmentType)
{
case AttachmentType::Equipment: return Equipment.Add(std::move(part)).get();
case AttachmentType::Item: if (Items.IsEmpty()) Character->ActiveItemSlot = 0; return Items.Add(std::move(part)).get();
case AttachmentType::Weapon: if (Weapons.IsEmpty()) Character->ActiveWeaponSlot = 0; return Weapons.Add(std::move(part)).get();
}
return nullptr;
}
auto Chassis::GetMaxHealth() const -> float
{
auto health = Character->Data->Health;
for (auto& part : Equipment)
{
auto equipment = static_cast<class Equipment*>(part.get());
health += equipment->EquipmentData->Attributes.GetAttribute(equipment->Modifiers, EquipmentAttribute::Health);
}
return health;
}
auto Chassis::GetMaxShield() const -> float
{
auto shield = 0.0f;
for (auto& part : Equipment)
{
for (auto& upgrade : part->Upgrades)
shield += upgrade->Data->Attributes.GetAttribute(upgrade->Modifiers, UpgradeAttribute::Shield);
}
return shield;
}
auto Chassis::GetShieldRegen() const -> float
{
auto regen = 0.0f;
for (auto& part : Equipment)
{
for (auto& upgrade : part->Upgrades)
regen += upgrade->Data->Attributes.GetAttribute(upgrade->Modifiers, UpgradeAttribute::ShieldRegen);
}
return regen;
}
| 27.630252 | 129 | 0.708942 |
7c2e1ea6553fb140adf3f89f99d79cfaed04016d | 1,699 | cpp | C++ | libvast/src/format/ostream_writer.cpp | ngrodzitski/vast | 5d114f53d51db8558f673c7f873bd92ded630bf6 | [
"BSD-3-Clause"
] | null | null | null | libvast/src/format/ostream_writer.cpp | ngrodzitski/vast | 5d114f53d51db8558f673c7f873bd92ded630bf6 | [
"BSD-3-Clause"
] | null | null | null | libvast/src/format/ostream_writer.cpp | ngrodzitski/vast | 5d114f53d51db8558f673c7f873bd92ded630bf6 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/format/ostream_writer.hpp"
#include "vast/error.hpp"
namespace vast::format {
ostream_writer::ostream_writer(ostream_ptr out) : out_(std::move(out)) {
// nop
}
ostream_writer::~ostream_writer() {
// nop
}
caf::expected<void> ostream_writer::flush() {
if (out_ == nullptr)
return caf::make_error(ec::format_error, "no output stream available");
out_->flush();
if (!*out_)
return caf::make_error(ec::format_error, "failed to flush");
return caf::unit;
}
std::ostream& ostream_writer::out() {
VAST_ASSERT(out_ != nullptr);
return *out_;
}
void ostream_writer::write_buf() {
VAST_ASSERT(out_ != nullptr);
out_->write(buf_.data(), buf_.size());
buf_.clear();
}
} // namespace vast::format
| 34.673469 | 80 | 0.479105 |
7c2e99d071f669e6bf42911f05fdfe7e036dfa42 | 12,307 | cpp | C++ | Sources/Rosetta/Battlegrounds/Models/Battle.cpp | Hearthstonepp/Hearthstonepp | ee17ae6de1ee0078dab29d75c0fbe727a14e850e | [
"MIT"
] | 62 | 2017-08-21T14:11:00.000Z | 2018-04-23T16:09:02.000Z | Sources/Rosetta/Battlegrounds/Models/Battle.cpp | Hearthstonepp/Hearthstonepp | ee17ae6de1ee0078dab29d75c0fbe727a14e850e | [
"MIT"
] | 37 | 2017-08-21T11:13:07.000Z | 2018-04-30T08:58:41.000Z | Sources/Rosetta/Battlegrounds/Models/Battle.cpp | Hearthstonepp/Hearthstonepp | ee17ae6de1ee0078dab29d75c0fbe727a14e850e | [
"MIT"
] | 10 | 2017-08-21T03:44:12.000Z | 2018-01-10T22:29:10.000Z | // Copyright (c) 2017-2021 Chris Ohk
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Battlegrounds/Models/Battle.hpp>
#include <effolkronium/random.hpp>
using Random = effolkronium::random_static;
namespace RosettaStone::Battlegrounds
{
Battle::Battle(Player& player1, Player& player2)
: m_player1(player1),
m_player2(player2),
m_p1Field(m_player1.battleField),
m_p2Field(m_player2.battleField)
{
m_player1.battleField = m_player1.recruitField;
m_player2.battleField = m_player2.recruitField;
}
void Battle::Initialize()
{
// Determine the player attacks first
// NOTE: The player with the greater number of minions attacks first.
// If the number of minions is equal for both players, one of the players
// is randomly selected to attack first.
const int p1NumMinions = m_p1Field.GetCount();
const int p2NumMinions = m_p2Field.GetCount();
if (p1NumMinions > p2NumMinions)
{
m_turn = Turn::PLAYER1;
}
else if (p1NumMinions < p2NumMinions)
{
m_turn = Turn::PLAYER2;
}
else
{
m_turn = static_cast<Turn>(Random::get<std::size_t>(0, 1));
}
m_p1NextAttackerIdx = 0;
m_p2NextAttackerIdx = 0;
if (m_turn == Turn::PLAYER1)
{
m_p1Field.ForEach([&](MinionData& minion) {
minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player1);
});
m_p2Field.ForEach([&](MinionData& minion) {
minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player2);
});
}
else
{
m_p2Field.ForEach([&](MinionData& minion) {
minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player2);
});
m_p1Field.ForEach([&](MinionData& minion) {
minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player1);
});
}
ProcessDestroy(true);
}
void Battle::Run()
{
Initialize();
bool prevAttackSuccess = false;
while (!IsDone())
{
if (m_turn == Turn::PLAYER1)
{
m_p1Field.ForEachAlive([&](MinionData& owner) {
m_p1Field.ForEachAlive([&](MinionData& minion) {
{
owner.value().ActivateTrigger(TriggerType::TURN_START,
minion.value());
};
});
});
m_p2Field.ForEachAlive([&](MinionData& owner) {
m_p2Field.ForEachAlive([&](MinionData& minion) {
{
owner.value().ActivateTrigger(TriggerType::TURN_START,
minion.value());
};
});
});
}
else
{
m_p2Field.ForEachAlive([&](MinionData& owner) {
m_p2Field.ForEachAlive([&](MinionData& minion) {
{
owner.value().ActivateTrigger(TriggerType::TURN_START,
minion.value());
};
});
});
m_p1Field.ForEachAlive([&](MinionData& owner) {
m_p1Field.ForEachAlive([&](MinionData& minion) {
{
owner.value().ActivateTrigger(TriggerType::TURN_START,
minion.value());
};
});
});
}
const bool curAttackSuccess = Attack();
if (!prevAttackSuccess && !curAttackSuccess)
{
m_turn = Turn::DONE;
break;
}
prevAttackSuccess = curAttackSuccess;
}
ProcessResult();
const int damage = CalculateDamage();
if (m_result == BattleResult::PLAYER1_WIN)
{
m_player2.hero.TakeDamage(m_player2, damage);
}
else if (m_result == BattleResult::PLAYER2_WIN)
{
m_player1.hero.TakeDamage(m_player1, damage);
}
}
bool Battle::Attack()
{
const int attackerIdx = FindAttacker();
// No minions that can attack, switch players
if (attackerIdx == -1)
{
m_turn = (m_turn == Turn::PLAYER1) ? Turn::PLAYER2 : Turn::PLAYER1;
return false;
}
Minion& attacker = (m_turn == Turn::PLAYER1) ? m_p1Field[attackerIdx]
: m_p2Field[attackerIdx];
Minion& target = GetProperTarget(attacker);
target.TakeDamage(attacker);
attacker.TakeDamage(target);
ProcessDestroy(false);
m_turn = (m_turn == Turn::PLAYER1) ? Turn::PLAYER2 : Turn::PLAYER1;
return true;
}
int Battle::FindAttacker()
{
FieldZone& fieldZone = (m_turn == Turn::PLAYER1) ? m_p1Field : m_p2Field;
int nextAttackerIdx =
(m_turn == Turn::PLAYER1) ? m_p1NextAttackerIdx : m_p2NextAttackerIdx;
for (int i = 0; i < fieldZone.GetCount(); ++i)
{
if (fieldZone[nextAttackerIdx].GetAttack() > 0)
{
return nextAttackerIdx;
}
++nextAttackerIdx;
if (nextAttackerIdx == fieldZone.GetCount())
{
nextAttackerIdx = 0;
}
}
return -1;
}
Minion& Battle::GetProperTarget([[maybe_unused]] Minion& attacker)
{
auto& minions = (m_turn == Turn::PLAYER1) ? m_p2Field : m_p1Field;
std::vector<std::size_t> tauntMinions;
tauntMinions.reserve(MAX_FIELD_SIZE);
std::size_t minionIdx = 0;
minions.ForEach([&](const MinionData& minion) {
if (minion.value().HasTaunt())
{
tauntMinions.emplace_back(minionIdx);
}
++minionIdx;
});
if (!tauntMinions.empty())
{
const auto idx = Random::get<std::size_t>(0, tauntMinions.size() - 1);
return minions[tauntMinions[idx]];
}
const auto idx = Random::get<int>(0, minions.GetCount() - 1);
return minions[idx];
}
void Battle::ProcessDestroy(bool beforeAttack)
{
std::vector<std::tuple<int, Minion&>> deadMinions;
if (m_turn == Turn::PLAYER1)
{
m_p2Field.ForEach([&](MinionData& minion) {
if (minion.value().IsDestroyed())
{
deadMinions.emplace_back(
std::make_tuple(2, std::ref(minion.value())));
}
});
m_p1Field.ForEach([&](MinionData& minion) {
if (minion.value().IsDestroyed())
{
deadMinions.emplace_back(
std::make_tuple(1, std::ref(minion.value())));
}
});
}
else
{
m_p1Field.ForEach([&](MinionData& minion) {
if (minion.value().IsDestroyed())
{
deadMinions.emplace_back(
std::make_tuple(1, std::ref(minion.value())));
}
});
m_p2Field.ForEach([&](MinionData& minion) {
if (minion.value().IsDestroyed())
{
deadMinions.emplace_back(
std::make_tuple(2, std::ref(minion.value())));
}
});
}
// A variable to check a minion at the index of next attacker is destroyed
bool isAttackerDestroyed = false;
for (auto& deadMinion : deadMinions)
{
Minion& minion = std::get<1>(deadMinion);
Minion removedMinion;
if (std::get<0>(deadMinion) == 1)
{
if (!beforeAttack)
{
// If the zone position of minion that is destroyed is lower
// than nextAttackerIdx and greater than 0, decrease by 1
if (m_p1NextAttackerIdx < minion.GetZonePosition() &&
m_p1NextAttackerIdx > 0)
{
--m_p1NextAttackerIdx;
}
// If the turn is player 1 and the zone position of minion that
// is destroyed equals nextAttackerIdx, keep the value of it
else if (m_turn == Turn::PLAYER1 &&
m_p1NextAttackerIdx == minion.GetZonePosition())
{
isAttackerDestroyed = true;
}
}
m_p1Field.ForEachAlive([&](MinionData& aliveMinion) {
aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion);
});
m_p2Field.ForEachAlive([&](MinionData& aliveMinion) {
aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion);
});
minion.SetLastFieldPos(minion.GetZonePosition());
removedMinion = m_p1Field.Remove(minion);
}
else
{
if (!beforeAttack)
{
// If the zone position of minion that is destroyed is lower
// than nextAttackerIdx and greater than 0, decrease by 1
if (m_p2NextAttackerIdx < minion.GetZonePosition() &&
m_p2NextAttackerIdx > 0)
{
--m_p2NextAttackerIdx;
}
// If the turn is player 2 and the zone position of minion that
// is destroyed equals nextAttackerIdx, keep the value of it
else if (m_turn == Turn::PLAYER2 &&
m_p2NextAttackerIdx == minion.GetZonePosition())
{
isAttackerDestroyed = true;
}
}
m_p1Field.ForEachAlive([&](MinionData& aliveMinion) {
aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion);
});
m_p2Field.ForEachAlive([&](MinionData& aliveMinion) {
aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion);
});
minion.SetLastFieldPos(minion.GetZonePosition());
removedMinion = m_p2Field.Remove(minion);
}
// Process deathrattle tasks
if (removedMinion.HasDeathrattle())
{
removedMinion.ActivateTask(
PowerType::DEATHRATTLE,
std::get<0>(deadMinion) == 1 ? m_player1 : m_player2);
}
}
if (!beforeAttack)
{
// If the zone position of minion that is destroyed not equals
// nextAttackerIdx, increase by 1
if (!isAttackerDestroyed)
{
if (m_turn == Turn::PLAYER1)
{
++m_p1NextAttackerIdx;
}
else
{
++m_p2NextAttackerIdx;
}
}
// Check the boundaries of field zone
if (m_p1NextAttackerIdx == m_p1Field.GetCount())
{
m_p1NextAttackerIdx = 0;
}
if (m_p2NextAttackerIdx == m_p2Field.GetCount())
{
m_p2NextAttackerIdx = 0;
}
}
}
bool Battle::IsDone() const
{
return m_p1Field.IsEmpty() || m_p2Field.IsEmpty() || m_turn == Turn::DONE;
}
void Battle::ProcessResult()
{
if (m_p1Field.IsEmpty() && !m_p2Field.IsEmpty())
{
m_result = BattleResult::PLAYER2_WIN;
}
else if (!m_p1Field.IsEmpty() && m_p2Field.IsEmpty())
{
m_result = BattleResult::PLAYER1_WIN;
}
else
{
m_result = BattleResult::DRAW;
}
}
int Battle::CalculateDamage()
{
int totalDamage = 0;
if (m_result == BattleResult::PLAYER1_WIN)
{
m_p1Field.ForEach([&](const MinionData& minion) {
totalDamage += minion.value().GetTier();
});
totalDamage += m_player1.currentTier;
}
else
{
m_p2Field.ForEach([&](const MinionData& minion) {
totalDamage += minion.value().GetTier();
});
totalDamage += m_player2.currentTier;
}
return totalDamage;
}
const FieldZone& Battle::GetPlayer1Field() const
{
return m_p1Field;
}
const FieldZone& Battle::GetPlayer2Field() const
{
return m_p2Field;
}
int Battle::GetPlayer1NextAttacker() const
{
return m_p1NextAttackerIdx;
}
int Battle::GetPlayer2NextAttacker() const
{
return m_p2NextAttackerIdx;
}
BattleResult Battle::GetResult() const
{
return m_result;
}
} // namespace RosettaStone::Battlegrounds
| 28.291954 | 80 | 0.542781 |
7c320e8880a227a1bb2501c2bd6e7bd6ba233ea0 | 1,447 | hpp | C++ | include/clotho/fitness/linear_fitness_metric.hpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-06-16T21:27:57.000Z | 2022-01-25T23:26:54.000Z | include/clotho/fitness/linear_fitness_metric.hpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-06-16T21:12:42.000Z | 2015-06-23T12:41:00.000Z | include/clotho/fitness/linear_fitness_metric.hpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright 2015 Patrick Putnam
//
// 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 LINEAR_FITNESS_METRIC_HPP_
#define LINEAR_FITNESS_METRIC_HPP_
#include <vector>
#include "clotho/genetics/ifitness.hpp"
extern const std::string LINEAR_FIT_NAME;
class linear_fitness_metric : public ifitness {
public:
typedef double real_type;
typedef real_type result_type;
linear_fitness_metric( real_type a = 1., real_type b = 0. ) :
m_val( c ) {
}
result_type operator()() {
return m_B;
}
result_type operator()( real_type x ) {
return m_A * x + m_B;
}
result_type operator()( const std::vector< real_type > & multi_variate ) {
return m_B;
}
const std::string name() const;
void log( std::ostream & out ) const;
virtual ~linear_fitness_metric();
protected:
real_type m_A, m_B;
};
#endif // LINEAR_FITNESS_METRIC_HPP_
| 27.301887 | 78 | 0.68763 |
7c33935241f7c129d9af1d1003bd3b8c73346e36 | 21,839 | cpp | C++ | addons/ofxGuido/lib/guidolib-code/linux/src/GDeviceGtk.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 18 | 2015-01-18T22:34:22.000Z | 2020-09-06T20:30:30.000Z | addons/ofxGuido/lib/guidolib-code/linux/src/GDeviceGtk.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 2 | 2015-08-04T00:07:46.000Z | 2017-05-10T15:53:51.000Z | addons/ofxGuido/lib/guidolib-code/linux/src/GDeviceGtk.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 10 | 2015-01-18T23:46:10.000Z | 2019-08-25T12:10:04.000Z | /*
GUIDO Library
Copyright (C) 2004 Torben Hohn
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/////////////////////////////////////////////////////////////////
///
/// GTK implementation of VGDevice.
///
/////////////////////////////////////////////////////////////////
#include "GDeviceGtk.h"
#include "GFontGtk.h"
#include "GSystemGtk.h" // GUIDO HACK - REMOVE ASAP
// --------------------------------------------------------------
GDeviceGtk::GDeviceGtk( GdkDrawable * inDrawable, int inWidth, int inHeight )
: mCurrTextFont(NULL), mCurrMusicFont(NULL),
mRasterMode(kOpCopy),
mDPITag(72.0f), mBeginDrawCount(0), mDrawable( inDrawable )
{
// Default device init ---------------------------
// Default pen and brush colors must be pure black.
mPhysicalWidth = inWidth;
mPhysicalHeight = inHeight;
mPenStack.reserve( 16 );
mBrushStack.reserve( 16 );
SetFontAlign( kAlignLeft | kAlignBase );
// GTK -------------------------------------------
Init();
mPangoContext = gdk_pango_context_get();
gdk_pango_context_set_colormap( mPangoContext, gdk_rgb_get_colormap() );
if( mDrawable )
{
printf( "dc is OK\n" );
mGC = gdk_gc_new( mDrawable );
// TODO: get GdkGC...
// - Initial state of GDevice
SelectPen( VGColor( 0, 0, 0), 1 );
SelectFillColor( VGColor( 0, 0, 0) );
SetFontColor( VGColor(0,0,0) );
SetFontBackgroundColor( VGColor(255,255,255,ALPHA_TRANSPARENT) );
SetScale( 1, 1 );
SetOrigin( 0, 0 );
}
else
printf( "dc is NULL\n" );
// guigo hack - remove asap
mSys = new GSystemGtk(inDrawable, NULL);
}
// --------------------------------------------------------------
GDeviceGtk::~GDeviceGtk()
{
delete [] mPtArray;
}
// --------------------------------------------------------------
bool
GDeviceGtk::IsValid() const
{
if( mDrawable == NULL ) return false;
return true;
}
/////////////////////////////////////////////////////////////////
// - Drawing services -------------------------------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
bool
GDeviceGtk::BeginDraw()
{
// general device's state save - was VGDevice::SaveDC()
GState s;
s.pen = mPen;
s.fillColor = mFillColor;
s.textColor = mTextColor;
s.textBackColor = mTextBackColor;
s.scaleX = mScaleX;
s.scaleY = mScaleY;
s.originX = mOriginX;
s.originY = mOriginY;
s.textAlign = mTextAlign;
s.currTextFont = mCurrTextFont;
s.currMusicFont = mCurrMusicFont;
s.rasterMode = mRasterMode;
s.gtkUserScaleX = mGtkScaleX;
s.gtkUserScaleY = mGtkScaleY;
s.gtkOriginX = mGtkOriginX;
s.gtkOriginY = mGtkOriginY;
s.penPos = mCurrPenPos;
mStateStack.push_back( s );
// TODO : complete this code with correct
// platform-dependant implementation
return true;
}
// --------------------------------------------------------------
void
GDeviceGtk::EndDraw()
{
// Default device code ---------------------------
if( -- mBeginDrawCount == 0 )
{}
// general device's state restore - was RestoreDC()
GState & s = mStateStack.back();
mPen = s.pen;
mFillColor = s.fillColor;
mTextColor = s.textColor;
mTextBackColor = s.textBackColor;
mScaleX = s.scaleX;
mScaleY = s.scaleY;
mOriginX = s.originX;
mOriginY = s.originY;
mTextAlign = s.textAlign;
mCurrTextFont = s.currTextFont;
mCurrMusicFont = s.currMusicFont;
mRasterMode = s.rasterMode;
mGtkOriginX = s.gtkOriginX;
mGtkOriginY = s.gtkOriginY;
mGtkScaleX = s.gtkUserScaleX;
mGtkScaleY = s.gtkUserScaleY;
mCurrPenPos = s.penPos;
mStateStack.pop_back();
SetTextFont( s.currTextFont );
SetMusicFont( s.currMusicFont );
}
// --------------------------------------------------------------
void
GDeviceGtk::MoveTo( float x, float y )
{
printf( "moveto: %f, %f\n", x, y );
mCurrPenPos.x = lrintf (x * mGtkScaleX + mGtkOriginX);
mCurrPenPos.y = lrintf (y * mGtkScaleY + mGtkOriginY);
}
// --------------------------------------------------------------
void
GDeviceGtk::LineTo( float x, float y )
{
int gx = lrintf (x * mGtkScaleX + mGtkOriginX);
int gy = lrintf (y * mGtkScaleY + mGtkOriginY);
printf( "lineto: %f, %f -> (%d, %d)\n", x, y, gx, gy );
gdk_draw_line( mDrawable, mGC, mCurrPenPos.x, mCurrPenPos.y, gx, gy );
mCurrPenPos.x = gx;
mCurrPenPos.y = gy;
}
// --------------------------------------------------------------
void
GDeviceGtk::Line( float x1, float y1, float x2, float y2 )
{
MoveTo( x1, y1 );
LineTo( x2, y2 );
}
// --------------------------------------------------------------
void
GDeviceGtk::Frame( float left, float top, float right, float bottom )
{
MoveTo (left, top);
LineTo (right, top);
LineTo (right, bottom);
LineTo (left, bottom);
LineTo (left, top);
}
// --------------------------------------------------------------
void
GDeviceGtk::Arc( float left, float top, float right, float bottom,
float startX, float startY, float endX, float endY )
{
int x = (int) (left);
int y = (int) (top);
int width = (int) (right - left);
int height = (int) (bottom - top);
float midX = (left + right) * 0.5f;
float midY = (top + bottom) * 0.5f;
int angle1 = (int) (atan( (startX - midX)/(startY - midY) ) * 360 * 64 * 2 * M_PI);
int angle2 = (int) (atan( (endX - midX) /(endY - midY) ) * 360 * 64 * 2 * M_PI - angle1);
gdk_draw_arc( mDrawable, mGC, 0, x, y, width, height, angle1, angle2 );
}
// --------------------------------------------------------------
void
GDeviceGtk::Triangle( float x1, float y1, float x2, float y2, float x3, float y3 )
{
const float xCoords [] = { x1, x2, x3 };
const float yCoords [] = { y1, y2, y3 };
Polygon( xCoords, yCoords, 3 );
}
// --------------------------------------------------------------
void
GDeviceGtk::Polygon( const float * xCoords, const float * yCoords, int count )
{
if( count > mPtCount )
{
if( mPtArray )
delete [] mPtArray;
mPtArray = new GdkPoint [ count ];
if( mPtArray )
mPtCount = count;
}
for( int index = 0; index < count; index ++ )
{
mPtArray[ index ].x = (int) (xCoords[ index ] * mGtkScaleX + mGtkOriginX);
mPtArray[ index ].y = (int) (yCoords[ index ] * mGtkScaleY + mGtkOriginY);
}
gdk_draw_polygon( mDrawable, mGC, 0, mPtArray, count );
}
// --------------------------------------------------------------
void
GDeviceGtk::Rectangle( float left, float top, float right, float bottom )
{
int x = (int) (left * mGtkScaleX + mGtkOriginX);
int y = (int) (top * mGtkScaleY + mGtkOriginY);
int w = (int) ((left - right) * mGtkScaleX);
int h = (int) ((top - bottom ) * mGtkScaleY);
gdk_draw_rectangle( mDrawable, mGC, 0, x, y, w, h );
}
/////////////////////////////////////////////////////////////////
// - Font services ----------------------------------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
void
GDeviceGtk::SetMusicFont( const VGFont * font )
{
mCurrMusicFont = font;
GFontGtk* gtkFont = (GFontGtk*)mCurrMusicFont;
// printf( "select music font = %d\n", (PangoFontDescription *)font->GetNativeFont() );
pango_context_set_font_description( mPangoContext,
(PangoFontDescription*) gtkFont->GetNativeFont() );
}
// --------------------------------------------------------------
const VGFont *
GDeviceGtk::GetMusicFont() const
{
return mCurrMusicFont;
}
// --------------------------------------------------------------
void
GDeviceGtk::SetTextFont( const VGFont * font )
{
mCurrTextFont = font;
GFontGtk* gtkFont = (GFontGtk*)mCurrTextFont;
// printf( "select text font = %d\n", font->GetNativeFont() );
pango_context_set_font_description( mPangoContext,
(PangoFontDescription*) gtkFont->GetNativeFont() );
}
// --------------------------------------------------------------
const VGFont *
GDeviceGtk::GetTextFont() const
{
return mCurrTextFont;
}
/////////////////////////////////////////////////////////////////
// - Pen & brush services ---------------------------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
void
GDeviceGtk::SelectPen( const VGColor & inColor, float width )
{
mPen.Set( inColor, width );
GdkColor color = { 0, inColor.mRed, inColor.mGreen, inColor.mBlue };
GdkLineStyle style = (inColor.mAlpha >= ALPHA_TRANSPARENT) ? GDK_LINE_ON_OFF_DASH : GDK_LINE_SOLID ;
gdk_gc_set_rgb_fg_color( mGC, &color );
gdk_gc_set_line_attributes( mGC, lrintf(width * mGtkScaleX), style, GDK_CAP_ROUND, GDK_JOIN_MITER );
}
// --------------------------------------------------------------
void
GDeviceGtk::SelectFillColor( const VGColor & c )
{
mFillColor.Set( c );
GdkColor color = { 0, c.mRed, c.mGreen, c.mBlue };
gdk_gc_set_rgb_fg_color( mGC, &color );
}
// --------------------------------------------------------------
// Save the current pen, select the new one
void
GDeviceGtk::PushPen( const VGColor & inColor, float inWidth )
{
mPenStack.push_back( mPen );
SelectPen( inColor, inWidth );
// TODO : complete this code with correct
// platform-dependant implementation
}
// --------------------------------------------------------------
// Restore the previous pen from the stack
void
GDeviceGtk::PopPen()
{
VGPen & pen = mPenStack.back();
SelectPen( pen.mColor, pen.mWidth );
mPenStack.pop_back();
// TODO : complete this code with correct
// platform-dependant implementation
}
// --------------------------------------------------------------
// Save the current brush, select the new one
void
GDeviceGtk::PushFillColor( const VGColor & inColor )
{
mBrushStack.push_back( mFillColor );
if( inColor != mFillColor )
SelectFillColor( inColor );
// TODO : complete this code with correct
// platform-dependant implementation
}
// --------------------------------------------------------------
// Restore the previous brush from the stack
void
GDeviceGtk::PopFillColor()
{
VGColor & brush = mBrushStack.back();
SelectFillColor( brush );
mBrushStack.pop_back();
// TODO : complete this code with correct
// platform-dependant implementation
}
// --------------------------------------------------------------
void
GDeviceGtk::SetRasterOpMode( VRasterOpMode ROpMode )
{
mRasterMode = ROpMode;
}
/////////////////////////////////////////////////////////////////
// - Bitmap services (bit-block copy methods) -------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
bool
GDeviceGtk::CopyPixels( VGDevice* pSrcDC, float alpha )
{
return false;
// TODO : replace this code by correct
// platform-dependant implementation
}
// --------------------------------------------------------------
bool
GDeviceGtk::CopyPixels( int xDest, int yDest, VGDevice* pSrcDC,
int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, float alpha )
{
return false;
// TODO : replace this code by correct
// platform-dependant implementation
}
// --------------------------------------------------------------
bool
GDeviceGtk::CopyPixels( int xDest, int yDest,
int dstWidth, int dstHeight, VGDevice* pSrcDC, float alphas )
{
return false;
// TODO : replace this code by correct
// platform-dependant implementation
}
/////////////////////////////////////////////////////////////////
// - Coordinate services ----------------------------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
void
GDeviceGtk::SetScale( float x, float y )
{
const float prevX = mScaleX;
const float prevY = mScaleY;
mScaleX = mGtkScaleX = x;
mScaleY = mGtkScaleY = y;
// TODO : complete this code with correct
// platform-dependant implementation
// was DoSetScale( prevX, prevY, x, y );
printf( "set Scale %f, %f\n", x, y );
// mGtkScaleX = x;
// mGtkScaleY = y;
}
// --------------------------------------------------------------
// Called only by GRPage
void
GDeviceGtk::SetOrigin( float x, float y )
{
const float prevX = mOriginX;
const float prevY = mOriginY;
mOriginX = x;
mOriginY = y;
// TODO : complete this code with correct
// platform-dependant implementation
// was DoSetOrigin( prevX, prevY, x, y );
printf( "set Origin %f, %f\n", x, y );
mGtkOriginX += (int) ((x - prevX) * GetXScale());
mGtkOriginY += (int) ((y - prevY) * GetYScale());
}
// --------------------------------------------------------------
// Called by: GRPage, GRStaff, GRSystem
void
GDeviceGtk::OffsetOrigin( float x, float y )
{
const float prevX = mOriginX;
const float prevY = mOriginY;
mOriginX += x;
mOriginY += y;
// TODO : complete this code with correct
// platform-dependant implementation
// was DoSetOrigin( prevX, prevY, x, y );
printf( "set Origin %f, %f\n", x, y );
mGtkOriginX += (int) ((x - prevX) * GetXScale());
mGtkOriginY += (int) ((y - prevY) * GetYScale());
}
// --------------------------------------------------------------
// Called by:
// GRMusic::OnDraw
// GRPage::getPixelSize
void
GDeviceGtk::LogicalToDevice( float * x, float * y ) const
{
*x = (*x * mScaleX - mOriginX);
*y = (*y * mScaleY - mOriginY);
// TODO : complete this code with correct
// platform-dependant implementation
}
// --------------------------------------------------------------
// Called by:
// GRPage::DPtoLPRect
// GRPage::getVirtualSize
void
GDeviceGtk::DeviceToLogical( float * x, float * y ) const
{
*x = ( *x + mOriginX ) / mScaleX;
*y = ( *y + mOriginY ) / mScaleY;
// TODO : complete this code with correct
// platform-dependant implementation
}
// --------------------------------------------------------------
float
GDeviceGtk::GetXScale() const
{
return mScaleX;
}
// --------------------------------------------------------------
float
GDeviceGtk::GetYScale() const
{
return mScaleY;
}
// --------------------------------------------------------------
float
GDeviceGtk::GetXOrigin() const
{
return mOriginX;
}
// --------------------------------------------------------------
float
GDeviceGtk::GetYOrigin() const
{
return mOriginY;
}
// --------------------------------------------------------------
void
GDeviceGtk::NotifySize( int inWidth, int inHeight )
{
mPhysicalWidth = inWidth; mPhysicalHeight = inHeight;
}
// --------------------------------------------------------------
int
GDeviceGtk::GetWidth() const
{
return mPhysicalWidth;
}
// --------------------------------------------------------------
int
GDeviceGtk::GetHeight() const
{
return mPhysicalHeight;
}
/////////////////////////////////////////////////////////////////
// - Text and music symbols services ----------------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
void
GDeviceGtk::DrawMusicSymbol(float x, float y, unsigned int inSymbolID )
{
int gx = (int) (x * mGtkScaleX + mGtkOriginX);
int gy = (int) (y * mGtkScaleY + mGtkOriginY);
GFontGtk* gtkFont = (GFontGtk*)mCurrMusicFont;
// PangoFontDescription *mydescr = pango_font_description_copy( (PangoFontDescription *) mCurrFont->mNativeFont );
// pango_font_description_set_size( mydescr, mCurrFont->mHeight * PANGO_SCALE * mGtkScaleY );
PangoFontDescription *mydescr = pango_font_description_copy( (PangoFontDescription *) gtkFont->GetNativeFont() );
pango_font_description_set_size( mydescr, gtkFont->GetSize() * PANGO_SCALE * mGtkScaleY );
printf( "Draw Symbol %f, %f -> (%d,%d) size = %d \n", x,y, gx,gy, (int) (gtkFont->GetSize() * PANGO_SCALE * mGtkScaleY) );
// char theChar = mSymbolToChar[ inSymbolID ];
char theChar = gtkFont->Symbol( inSymbolID );
printf( "char = %c, %d\n", theChar, (int) theChar );
gsize newstringlen;
char *utf8string = g_convert( &theChar, 1, "LATIN1", "UTF8", NULL, &newstringlen, NULL );
PangoLayout *layout = pango_layout_new( mPangoContext );
PangoLanguage* pangoLanguage = pango_language_from_string( "en-us" );
PangoFontMetrics *metrics = pango_context_get_metrics( mPangoContext, mydescr, pangoLanguage );
pango_layout_set_font_description( layout, mydescr );
pango_layout_set_text( layout, utf8string, newstringlen );
const unsigned int textAlign = GetFontAlign();
if( textAlign != ( kAlignLeft | kAlignTop ))
{
int w = 0;
int h = 0;
int descent = (pango_font_metrics_get_descent( metrics ) / PANGO_SCALE) + 1;
//int descent = 0;
pango_layout_get_pixel_size( layout, &w, &h );
h--;
if( textAlign & kAlignBase )
gy -= ( h - descent );
else if( textAlign & kAlignBottom )
gy -= h; // depends on axis orientation ?
// - Perform horizontal text alignement
if( textAlign & kAlignRight )
gx -= w;
else if( textAlign & kAlignCenter )
gx -= (w * 0.5);
}
gdk_draw_layout( mDrawable, mGC, gx, gy, layout );
pango_font_description_free( mydescr );
g_free( utf8string );
g_object_unref( G_OBJECT( layout ) );
}
// --------------------------------------------------------------
void
GDeviceGtk::DrawString( float x, float y, const char * s, int inCharCount )
{
printf( "printAt( %f, %f ) scale = %f, origin = %d \n", x, y, mGtkScaleX, mGtkOriginX );
int gx = (int)( x * mGtkScaleX + mGtkOriginX );
int gy = (int)( y * mGtkScaleY + mGtkOriginY );
PangoLayout *layout = pango_layout_new( mPangoContext );
pango_layout_set_text( layout, s, inCharCount );
gdk_draw_layout( mDrawable, mGC, gx, gy, layout );
g_object_unref( G_OBJECT( layout ) );
}
// --------------------------------------------------------------
void
GDeviceGtk::SetFontColor( const VGColor & inColor )
{
mTextColor = inColor;
GdkColor color = { 0, inColor.mRed, inColor.mGreen, inColor.mBlue };
gdk_gc_set_rgb_bg_color( mGC, &color );
}
// --------------------------------------------------------------
VGColor
GDeviceGtk::GetFontColor() const
{
return mTextColor;
}
// --------------------------------------------------------------
void
GDeviceGtk::SetFontBackgroundColor( const VGColor & inColor )
{
mTextBackColor = inColor;
GdkColor color = { 0, inColor.mRed, inColor.mGreen, inColor.mBlue };
gdk_gc_set_rgb_bg_color( mGC, &color );
}
// --------------------------------------------------------------
VGColor
GDeviceGtk::GetFontBackgroundColor() const
{
return mTextBackColor;
}
// --------------------------------------------------------------
void
GDeviceGtk::SetFontAlign( unsigned int inAlign )
{
mTextAlign = inAlign;
}
// --------------------------------------------------------------
unsigned int
GDeviceGtk::GetFontAlign() const
{
return mTextAlign;
}
/////////////////////////////////////////////////////////////////
// - Printer informations services ------------------------------
/////////////////////////////////////////////////////////////////
// --------------------------------------------------------------
void
GDeviceGtk::SetDPITag( float inDPI )
{
mDPITag = inDPI;
}
// --------------------------------------------------------------
float
GDeviceGtk::GetDPITag() const
{
return mDPITag;
}
// --------------------------------------------------------------
VGSystem *
GDeviceGtk::getVGSystem() const
{
return mSys;
// TODO : replace this code by correct
// platform-dependant implementation
}
// --------------------------------------------------------------
void *
GDeviceGtk::GetNativeContext() const
{
return mGC;
}
// --------------------------------------------------------------
void
GDeviceGtk::Init()
{
mStateStack.reserve( 16 );
mGtkOriginX = 0;
mGtkOriginY = 0;
mCurrPenPos.x = 0;
mCurrPenPos.y = 0;
mPtArray = 0; // For polygon
mPtCount = 0; // For polygon
}
// --------------------------------------------------------------
#if 0
void
GDeviceGtk::AddWxAlignOffset( const wxString & inString, wxCoord * ioX, wxCoord * ioY ) const
{
const unsigned int textAlign = GetTextAlign();
if( textAlign != ( kAlignLeft | kAlignTop ))
{
wxCoord w = 0;
wxCoord h = 0;
wxCoord descent = 0;
mDC->GetTextExtent( inString, &w, &h, &descent );// <- crashes wxWindows if font is wrong.
if( textAlign & kAlignBase )
*ioY -= ( h - descent );
else if( textAlign & kAlignBottom )
*ioY -= h; // depends on axis orientation ?
// - Perform horizontal text alignement
if( textAlign & kAlignRight )
*ioX -= w;
else if( textAlign & kAlignCenter )
*ioX -= (w * 0.5);
}
}
#endif
// --------------------------------------------------------------
int
GDeviceGtk::MaxWidth() const
{
int width;
int height;
gdk_drawable_get_size( mDrawable, &width, &height );
return width;
}
// --------------------------------------------------------------
int
GDeviceGtk::MaxHeight() const
{
int width;
int height;
gdk_drawable_get_size( mDrawable, &width, &height );
return height;
}
| 27.367168 | 126 | 0.521223 |
7c36b071ee0da1c00b054d908090ba037591858e | 2,372 | cc | C++ | src/swganh/social/social_service.cc | JohnShandy/swganh | d20d22a8dca2e9220a35af0f45f7935ca2eda531 | [
"MIT"
] | 1 | 2015-03-25T16:02:17.000Z | 2015-03-25T16:02:17.000Z | src/swganh/social/social_service.cc | JohnShandy/swganh | d20d22a8dca2e9220a35af0f45f7935ca2eda531 | [
"MIT"
] | null | null | null | src/swganh/social/social_service.cc | JohnShandy/swganh | d20d22a8dca2e9220a35af0f45f7935ca2eda531 | [
"MIT"
] | null | null | null | // This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "swganh/social/social_service.h"
#include "anh/logger.h"
#include "anh/plugin/plugin_manager.h"
#include "anh/service/service_manager.h"
#include "anh/database/database_manager.h"
#include "swganh/app/swganh_kernel.h"
#include "swganh/connection/connection_service.h"
#include "swganh/character/character_provider_interface.h"
#include "swganh/object/player/player.h"
#include "swganh/object/object.h"
#include "swganh/object/object_controller.h"
#include "swganh/object/object_manager.h"
#include "swganh/messages/out_of_band.h"
using namespace anh::database;
using namespace anh::plugin;
using namespace std;
using namespace swganh::connection;
using namespace swganh::object;
using namespace swganh::object::player;
using namespace swganh::social;
using anh::app::KernelInterface;
using anh::service::ServiceDescription;
using swganh::app::SwganhKernel;
using swganh::character::CharacterProviderInterface;
SocialService::SocialService(SwganhKernel* kernel)
: kernel_(kernel)
{
character_provider_ = kernel->GetPluginManager()->CreateObject<CharacterProviderInterface>("Character::CharacterProvider");
}
SocialService::~SocialService()
{}
ServiceDescription SocialService::GetServiceDescription()
{
ServiceDescription service_description(
"SocialService",
"social",
"0.1",
"127.0.0.1",
0,
0,
0);
return service_description;
}
bool SocialService::AddFriend(const shared_ptr<Player>& player, const string& friend_name)
{
uint64_t friend_id = character_provider_->GetCharacterIdByName(friend_name);
/// If we found our friend, lets add them to our friends list (which will get updated by the player)
if (friend_id > 0)
{
player->AddFriend(friend_name, friend_id);
return true;
}
return false;
}
bool SocialService::AddIgnore(const shared_ptr<Player>& player, const string& player_name)
{
uint64_t player_id = character_provider_->GetCharacterIdByName(player_name);
/// If we found the player name, lets add them to our ignore list (which will get updated by the player)
if (player_id > 0)
{
player->IgnorePlayer(player_name, player_id);
return true;
}
return false;
}
| 28.238095 | 127 | 0.736931 |
7c3d1b998ba7e55703307ac573b0d4775b3151b5 | 388 | hpp | C++ | sdl2-sonic-drivers/src/utils/constants.hpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | 3 | 2021-10-31T14:24:00.000Z | 2022-03-16T08:15:31.000Z | sdl2-sonic-drivers/src/utils/constants.hpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | 48 | 2020-06-05T11:11:29.000Z | 2022-02-27T23:58:44.000Z | sdl2-sonic-drivers/src/utils/constants.hpp | Raffaello/sdl2-sonic-drivers | 20584f100ddd7c61f584deaee0b46c5228d8509d | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cmath>
namespace utils
{
// TODO remove M_PI and M_2PI replace them with PI and PI2
#ifdef M_PI
#undef M_PI
#endif // M_PI
constexpr double M_PI = 3.14159265358979323846;
#ifdef M_2PI
#undef M_2PI
#endif // M_2PI
constexpr double M_2PI = 2.0 * M_PI;
constexpr double PI = 3.141592653589793238462643;
constexpr double PI2 = PI * 2;
}
| 18.47619 | 62 | 0.688144 |
7c423f5a6c83d0ccfe3ff3d33914a241403fcc8e | 12,071 | cpp | C++ | Sourcecode/mxtest/core/PropertiesTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mxtest/core/PropertiesTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mxtest/core/PropertiesTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#include "mxtest/control/CompileControl.h"
#ifdef MX_COMPILE_CORE_TESTS
#include "cpul/cpulTestHarness.h"
#include "mxtest/core/HelperFunctions.h"
#include "mxtest/core/PropertiesTest.h"
#include "mxtest/core/EditorialGroupTest.h"
using namespace mx::core;
using namespace std;
using namespace mxtest;
TEST( Test01, Properties )
{
variant v = variant::one;
PropertiesPtr object = tgenProperties( v );
stringstream expected;
tgenPropertiesExpected( expected, 1, v );
stringstream actual;
// object->toStream( std::cout, 1 );
object->toStream( actual, 1 );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( ! object->hasContents() )
}
TEST( Test02, Properties )
{
variant v = variant::two;
PropertiesPtr object = tgenProperties( v );
stringstream expected;
tgenPropertiesExpected( expected, 1, v );
stringstream actual;
// object->toStream( std::cout, 1 );
object->toStream( actual, 1 );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
TEST( Test03, Properties )
{
variant v = variant::three;
PropertiesPtr object = tgenProperties( v );
stringstream expected;
tgenPropertiesExpected( expected, 1, v );
stringstream actual;
// object->toStream( std::cout, 1 );
object->toStream( actual, 1 );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
namespace mxtest
{
PropertiesPtr tgenProperties( variant v )
{
PropertiesPtr o = makeProperties();
switch ( v )
{
case variant::one:
{
}
break;
case variant::two:
{
o->setEditorialGroup( tgenEditorialGroup( v ) );
auto d = makeDivisions();
d->setValue( PositiveDivisionsValue( 120 ) );
o->setDivisions( d );
o->setHasDivisions( true );
auto k = makeKey();
k->getKeyChoice()->setChoice( KeyChoice::Choice::traditionalKey );
k->getKeyChoice()->getTraditionalKey()->getFifths()->setValue( FifthsValue( -2 ) );
k->getKeyChoice()->getTraditionalKey()->setHasCancel( true );
k->getKeyChoice()->getTraditionalKey()->getCancel()->setValue( FifthsValue ( 1 ) );
o->addKey( k );
auto t = makeTime();
t->getTimeChoice()->setChoice( TimeChoice::Choice::timeSignature );
auto timeSignature = makeTimeSignatureGroup();
timeSignature->getBeats()->setValue( XsString( "3" ) );
timeSignature->getBeatType()->setValue( XsString( "4" ) );
t->getTimeChoice()->addTimeSignatureGroup( timeSignature );
t->getTimeChoice()->removeTimeSignatureGroup( t->getTimeChoice()->getTimeSignatureGroupSet().cbegin() );
o->addTime( t );
o->setHasStaves( true );
o->getStaves()->setValue( NonNegativeInteger( 4 ) );
o->setHasPartSymbol( true );
o->getPartSymbol()->setValue( GroupSymbolValue::none );
o->setHasInstruments( true );
o->getInstruments()->setValue( NonNegativeInteger( 3 ) );
auto c = makeClef();
c->getSign()->setValue( ClefSign::g );
c->getLine()->setValue( StaffLine( 2 ) );
c->setHasLine( true );
o->addClef( c );
auto sd = makeStaffDetails();
sd->setHasStaffLines( true );
sd->getStaffLines()->setValue( NonNegativeInteger( 5 ) );
sd->setHasStaffType( true );
sd->getStaffType()->setValue( StaffTypeEnum::regular );
o->addStaffDetails( sd );
auto dir = makeDirective();
dir->setValue( XsString( "allegro" ) );
dir->getAttributes()->hasLang = true;
o->addDirective( dir );
auto ms = makeMeasureStyle();
ms->getMeasureStyleChoice()->setChoice( MeasureStyleChoice::Choice::slash );
ms->getMeasureStyleChoice()->getSlash()->getSlashType()->setValue( NoteTypeValue::eighth );
o->addMeasureStyle( ms );
}
break;
case variant::three:
{
o->setEditorialGroup( tgenEditorialGroup( v ) );
auto d = makeDivisions();
d->setValue( PositiveDivisionsValue( 99 ) );
o->setDivisions( d );
o->setHasDivisions( true );
auto k = makeKey();
k->getKeyChoice()->setChoice( KeyChoice::Choice::traditionalKey );
k->getKeyChoice()->getTraditionalKey()->getFifths()->setValue( FifthsValue( -2 ) );
k->getKeyChoice()->getTraditionalKey()->setHasCancel( true );
k->getKeyChoice()->getTraditionalKey()->getCancel()->setValue( FifthsValue ( 1 ) );
o->addKey( k );
auto t = makeTime();
t->getTimeChoice()->setChoice( TimeChoice::Choice::timeSignature );
auto timeSignature = makeTimeSignatureGroup();
timeSignature->getBeats()->setValue( XsString( "5" ) );
timeSignature->getBeatType()->setValue( XsString( "4" ) );
t->getTimeChoice()->addTimeSignatureGroup( timeSignature );
t->getTimeChoice()->removeTimeSignatureGroup( t->getTimeChoice()->getTimeSignatureGroupSet().cbegin() );
o->addTime( t );
o->setHasStaves( true );
o->getStaves()->setValue( NonNegativeInteger( 4 ) );
o->setHasPartSymbol( true );
o->getPartSymbol()->setValue( GroupSymbolValue::none );
o->setHasInstruments( true );
o->getInstruments()->setValue( NonNegativeInteger( 3 ) );
auto c = makeClef();
c->getSign()->setValue( ClefSign::g );
c->getLine()->setValue( StaffLine( 2 ) );
c->setHasLine( true );
o->addClef( c );
c = makeClef();
c->getSign()->setValue( ClefSign::c );
c->getLine()->setValue( StaffLine( 3 ) );
c->setHasLine( true );
o->addClef( c );
// auto sd = makeStaffDetails();
// sd->setHasStaffLines( true );
// sd->getStaffLines()->setValue( NonNegativeInteger( 5 ) );
// sd->setHasStaffType( true );
// sd->getStaffType()->setValue( StaffTypeEnum::regular );
// o->addStaffDetails( sd );
auto dir = makeDirective();
dir->setValue( XsString( "allegro" ) );
dir->getAttributes()->hasLang = true;
o->addDirective( dir );
auto ms = makeMeasureStyle();
ms->getMeasureStyleChoice()->setChoice( MeasureStyleChoice::Choice::slash );
ms->getMeasureStyleChoice()->getSlash()->getSlashType()->setValue( NoteTypeValue::eighth );
o->addMeasureStyle( ms );
}
break;
default:
break;
}
return o;
}
void tgenPropertiesExpected( std::ostream& os, int i, variant v )
{
switch ( v )
{
case variant::one:
{
streamLine( os, i, R"(<attributes/>)", false );
}
break;
case variant::two:
{
streamLine( os, i, R"(<attributes>)" );
tgenEditorialGroupExpected( os, i+1, v );
os << std::endl;
streamLine( os, i+1, R"(<divisions>120</divisions>)" );
streamLine( os, i+1, R"(<key>)" );
streamLine( os, i+2, R"(<cancel>1</cancel>)" );
streamLine( os, i+2, R"(<fifths>-2</fifths>)" );
streamLine( os, i+1, R"(</key>)" );
streamLine( os, i+1, R"(<time>)" );
streamLine( os, i+2, R"(<beats>3</beats>)" );
streamLine( os, i+2, R"(<beat-type>4</beat-type>)" );
streamLine( os, i+1, R"(</time>)" );
streamLine( os, i+1, R"(<staves>4</staves>)" );
streamLine( os, i+1, R"(<part-symbol>none</part-symbol>)" );
streamLine( os, i+1, R"(<instruments>3</instruments>)" );
streamLine( os, i+1, R"(<clef>)" );
streamLine( os, i+2, R"(<sign>G</sign>)" );
streamLine( os, i+2, R"(<line>2</line>)" );
streamLine( os, i+1, R"(</clef>)" );
streamLine( os, i+1, R"(<staff-details>)" );
streamLine( os, i+2, R"(<staff-type>regular</staff-type>)" );
streamLine( os, i+2, R"(<staff-lines>5</staff-lines>)" );
streamLine( os, i+1, R"(</staff-details>)" );
streamLine( os, i+1, R"(<directive xml:lang="it">allegro</directive>)" );
streamLine( os, i+1, R"(<measure-style>)" );
streamLine( os, i+2, R"(<slash type="start">)" );
streamLine( os, i+3, R"(<slash-type>eighth</slash-type>)" );
streamLine( os, i+2, R"(</slash>)" );
streamLine( os, i+1, R"(</measure-style>)" );
streamLine( os, i, R"(</attributes>)", false );
}
break;
case variant::three:
{
streamLine( os, i, R"(<attributes>)" );
tgenEditorialGroupExpected( os, i+1, v );
os << std::endl;
streamLine( os, i+1, R"(<divisions>99</divisions>)" );
streamLine( os, i+1, R"(<key>)" );
streamLine( os, i+2, R"(<cancel>1</cancel>)" );
streamLine( os, i+2, R"(<fifths>-2</fifths>)" );
streamLine( os, i+1, R"(</key>)" );
streamLine( os, i+1, R"(<time>)" );
streamLine( os, i+2, R"(<beats>5</beats>)" );
streamLine( os, i+2, R"(<beat-type>4</beat-type>)" );
streamLine( os, i+1, R"(</time>)" );
streamLine( os, i+1, R"(<staves>4</staves>)" );
streamLine( os, i+1, R"(<part-symbol>none</part-symbol>)" );
streamLine( os, i+1, R"(<instruments>3</instruments>)" );
streamLine( os, i+1, R"(<clef>)" );
streamLine( os, i+2, R"(<sign>G</sign>)" );
streamLine( os, i+2, R"(<line>2</line>)" );
streamLine( os, i+1, R"(</clef>)" );
streamLine( os, i+1, R"(<clef>)" );
streamLine( os, i+2, R"(<sign>C</sign>)" );
streamLine( os, i+2, R"(<line>3</line>)" );
streamLine( os, i+1, R"(</clef>)" );
// streamLine( os, i+1, R"(<staff-details>)" );
// streamLine( os, i+2, R"(<staff-type>regular</staff-type>)" );
// streamLine( os, i+2, R"(<staff-lines>5</staff-lines>)" );
// streamLine( os, i+1, R"(</staff-details>)" );
streamLine( os, i+1, R"(<directive xml:lang="it">allegro</directive>)" );
streamLine( os, i+1, R"(<measure-style>)" );
streamLine( os, i+2, R"(<slash type="start">)" );
streamLine( os, i+3, R"(<slash-type>eighth</slash-type>)" );
streamLine( os, i+2, R"(</slash>)" );
streamLine( os, i+1, R"(</measure-style>)" );
streamLine( os, i, R"(</attributes>)", false );
}
break;
default:
break;
}
}
}
#endif
| 44.873606 | 120 | 0.498385 |
7c45da4372eb53b9bbb2f92658006d7acf60e1c0 | 1,363 | cpp | C++ | Strings Problem/Valid Ip Addresses.cpp | theslytherin/Interview_Bit | da9973de33be2f12d6e051bea1e918004216b6ed | [
"MIT"
] | null | null | null | Strings Problem/Valid Ip Addresses.cpp | theslytherin/Interview_Bit | da9973de33be2f12d6e051bea1e918004216b6ed | [
"MIT"
] | null | null | null | Strings Problem/Valid Ip Addresses.cpp | theslytherin/Interview_Bit | da9973de33be2f12d6e051bea1e918004216b6ed | [
"MIT"
] | null | null | null | int stringnumber(string s){
int i=0;
int n=s.length();
int face=1;
int answer=0;
for(i=n-1;i>=0;i--){
answer+=(s[i]-'0')*face;
face*=10;
}
return answer;
}
bool isValid(string s){
int i,j;
int n=s.length();
int number;
int start=0;
string temp="";
while(start < n){
i=start;
temp="";
while(i<n && s[i]!='.')i++;
if(i-start >3 ||i-start==0)
return false;
for(j=start;j<i;j++)
temp+=s[j];
number=stringnumber(temp);
if(number > 255)
return false;
if(number == 0 && i-start >1)
return false;
if(i-start > 1 && s[start]=='0')
return false;
start=i+1;
}
return true;
}
string copyString(string s,int i,int j,int k){
string x;
for(int l=0;l<s.length();l++){
if(l==i)
x+='.';
if(l==j)
x+='.';
if(l==k)
x+='.';
x+=s[l];
}
return x;
}
vector<string> Solution::restoreIpAddresses(string A) {
vector <string> B;
int i,j,k;
string s;
int l=A.length();
for(i=0;i<l-1;i++)
for(j=i+1;j<l-1;j++)
for(k=j+1;k<l-1;k++){
s=copyString(A,i+1,j+1,k+1);
if(isValid(s))
B.push_back(s);
}
return B;
}
| 21.296875 | 55 | 0.432869 |
7c48357bb84762320f6d3c9346f67acfbca91d1c | 5,398 | cpp | C++ | src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp | test-bai-cpu/hdi_plan | 89684bb73832d7e40f3c669f284ffddb56a1e299 | [
"MIT"
] | 1 | 2021-07-31T12:34:11.000Z | 2021-07-31T12:34:11.000Z | src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp | test-bai-cpu/hdi_plan | 89684bb73832d7e40f3c669f284ffddb56a1e299 | [
"MIT"
] | null | null | null | src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp | test-bai-cpu/hdi_plan | 89684bb73832d7e40f3c669f284ffddb56a1e299 | [
"MIT"
] | 2 | 2021-05-08T13:27:31.000Z | 2021-09-24T07:59:04.000Z | #include "publish_trajectory/publish_trajectory_to_quadrotor.hpp"
namespace hdi_plan {
PublishTrajectory::PublishTrajectory(const ros::NodeHandle &nh, const ros::NodeHandle &pnh)
:nh_(nh),
pnh_(pnh){
arm_bridge_pub_ = nh_.advertise<std_msgs::Bool>("bridge/arm", 1);
start_pub_ = nh_.advertise<std_msgs::Empty>("autopilot/start", 1);
//go_to_pose_pub_ = nh_.advertise<geometry_msgs::PoseStamped>("autopilot/pose_command", 100);
trajectory_pub_ = nh_.advertise<quadrotor_msgs::Trajectory>("autopilot/trajectory", 1);
//max_velocity_pub_ = nh_.advertise<std_msgs::Float64>("autopilot/max_velocity", 1);
//trajectory_sub_ = nh_.subscribe("hdi_plan/full_trajectory", 1, &PublishTrajectory::trajectory_callback, this);
pub_solution_path_ = nh_.advertise<geometry_msgs::PoseStamped>("autopilot/pose_command", 1);
//get_new_path_sub_ = nh_.subscribe("hdi_plan/get_new_path", 1, &PublishTrajectory::get_new_path_callback, this);
//quadrotor_state_sub_ = nh_.subscribe("hdi_plan/quadrotor_state", 1, &PublishTrajectory::quadrotor_state_callback, this);
ros::Duration(9.0).sleep();
start_quadrotor_bridge();
ros::Duration(9.0).sleep();
ROS_INFO("Start to publish the trajectory!!!");
publish_trajectory();
}
PublishTrajectory::~PublishTrajectory() {}
void PublishTrajectory::quadrotor_state_callback(const nav_msgs::Odometry::ConstPtr &msg) {
quadrotor_state_(0) = msg->pose.pose.position.x;
quadrotor_state_(1) = msg->pose.pose.position.y;
quadrotor_state_(2) = msg->pose.pose.position.z;
}
void PublishTrajectory::start_quadrotor_bridge() {
ROS_INFO("###### Start the quadrotor bridge");
std_msgs::Bool arm_message;
arm_message.data = true;
this->arm_bridge_pub_.publish(arm_message);
std_msgs::Empty empty_message;
this->start_pub_.publish(empty_message);
ros::Duration(7.0).sleep();
ROS_INFO("Go to pose msg");
geometry_msgs::PoseStamped go_to_pose_msg;
go_to_pose_msg.pose.position.x = 0.0;
go_to_pose_msg.pose.position.y = 2.0;
go_to_pose_msg.pose.position.z = 2.0;
this->pub_solution_path_.publish(go_to_pose_msg);
}
void PublishTrajectory::get_new_path_callback(const std_msgs::Bool::ConstPtr &msg) {
this->if_get_new_path_ = msg->data;
}
/*
void PublishTrajectory::trajectory_callback(const hdi_plan::point_array::ConstPtr &msg) {
ROS_INFO("In the trajectory callback");
int trajectory_size = msg->points.size();
this->if_get_new_path_ = false;
quadrotor_msgs::Trajectory trajectory_msg;
trajectory_msg.header.stamp = ros::Time::now();
trajectory_msg.type = trajectory_msg.GENERAL;
for (int i = 0; i < trajectory_size; i++) {
quadrotor_msgs::TrajectoryPoint point;
geometry_msgs::Point point_msg;
point_msg.x = msg->points[i].x;
point_msg.y = msg->points[i].y;
point_msg.z = msg->points[i].z;
point.pose.position = point_msg;
trajectory_msg.points.push_back(point);
}
this->trajectory_pub_.publish(trajectory_msg);
}*/
void PublishTrajectory::publish_trajectory() {
ROS_INFO("check into publish trajectory");
std::vector<Eigen::Vector3d> optimized_trajectory;
for (int i = 1; i < 11; i++) {
Eigen::Vector3d point1(i, 2, 2);
optimized_trajectory.push_back(point1);
}
int trajectory_size = optimized_trajectory.size();
geometry_msgs::PoseStamped go_to_pose_msg;
for (int i = 0; i < trajectory_size; i++) {
Eigen::Vector3d point = optimized_trajectory.at(i);
go_to_pose_msg.pose.position.x = point(0);
go_to_pose_msg.pose.position.y = point(1);
go_to_pose_msg.pose.position.z = point(2);
this->pub_solution_path_.publish(go_to_pose_msg);
ros::Duration(0.7).sleep();
}
/*
std_msgs::Bool get_new_path_msg;
get_new_path_msg.data = true;
this->pub_get_new_path_.publish(get_new_path_msg);*/
}
}
/*
trajectory_pub_ = nh_.advertise<hdi_plan::point_array>("hdi_plan/full_trajectory", 1);
trigger_sub_ = nh_.subscribe("hdi_plan/trigger", 1, &PublishTrajectory::trigger_callback, this);
pub_get_new_path_ = nh_.advertise<std_msgs::Bool>("hdi_plan/get_new_path", 1);
void PublishTrajectory::trigger_callback(const std_msgs::Empty::ConstPtr &msg) {
this->publish_trajectory();
}
void PublishTrajectory::publish_another_trajectory() {
ROS_INFO("check into another publish trajectory");
quadrotor_common::Trajectory trajectory;
for (int i=0; i<10; i++) {
quadrotor_common::TrajectoryPoint point = quadrotor_common::TrajectoryPoint();
Eigen::Vector3d position(1,i+1,10);
point.position = position;
trajectory.points.push_back(point);
}
quadrotor_msgs::Trajectory msg = trajectory.toRosMessage();
this->trajectory_pub_.publish(msg);
}
void PublishTrajectory::publish_trajectory() {
ROS_INFO("check into publish trajectory");
std::vector<Eigen::Vector3d> optimized_trajectory;
for (int i = 0; i < 10; i++) {
Eigen::Vector3d point1(i, i+1, i+2);
optimized_trajectory.push_back(point1);
}
hdi_plan::point_array trajectory_msg;
int trajectory_size = optimized_trajectory.size();
geometry_msgs::Point trajectory_point;
for (int i = 0; i < trajectory_size; i++) {
Eigen::Vector3d point = optimized_trajectory.at(i);
trajectory_point.x = point(0);
trajectory_point.y = point(1);
trajectory_point.z = point(2);
trajectory_msg.points.push_back(trajectory_point);
}
std_msgs::Bool get_new_path_msg;
get_new_path_msg.data = true;
this->pub_get_new_path_.publish(get_new_path_msg);
this->trajectory_pub_.publish(trajectory_msg);
ROS_INFO("Finish publish trajectory");
}
*/ | 34.825806 | 123 | 0.757318 |
7c49087a00e33b089fb2609357398b4506781137 | 14,722 | cpp | C++ | src/moment_quantization.cpp | TobiasRp/mray | d59bb110c97c7f0a7263981ca0050132220f2688 | [
"MIT"
] | null | null | null | src/moment_quantization.cpp | TobiasRp/mray | d59bb110c97c7f0a7263981ca0050132220f2688 | [
"MIT"
] | 1 | 2021-11-29T14:03:20.000Z | 2021-11-29T14:03:20.000Z | src/moment_quantization.cpp | TobiasRp/mray | d59bb110c97c7f0a7263981ca0050132220f2688 | [
"MIT"
] | null | null | null | // Copyright (c) 2020, Tobias Rapp
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Karlsruhe Institute of Technology nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "moment_quantization.h"
#include "moment_prediction_coding.h"
#include <fstream>
namespace moment_quantization
{
static bool s_UseQuantizationTable = false;
static array<Byte, 255> s_QuantizationTable;
uint32_t quantize(float value, int numBits, float min, float max)
{
if (numBits == 32)
{
value = cut::clamp(value, min, max);
uint32_t uvalue;
std::memcpy(&uvalue, &value, sizeof(float));
return uvalue;
}
value = cut::clamp(value, min, max);
float norm = (value - min) / (max - min);
uint32_t bits = norm * ((1 << numBits) - 1);
uint32_t mask = 0xFFFFFFFF & ((1 << numBits) - 1);
return bits & mask;
}
float dequantize(uint32_t q, int numBits, float min, float max)
{
if (numBits == 32)
{
float fvalue;
std::memcpy(&fvalue, &q, sizeof(float));
return cut::clamp(fvalue, min, max);
}
float norm = q / static_cast<float>((1 << numBits) - 1);
return norm * (max - min) + min;
}
inline void pack_bits(vector<Byte> &out, const vector<uint32_t> &sparse_bits, int num_bits)
{
Byte buffer = 0;
int current_bit = 0;
for (size_t i = 0; i < sparse_bits.size(); ++i)
{
for (int b = 0; b < num_bits; ++b)
{
int bit = sparse_bits[i] & (1 << b);
if (bit)
buffer |= (1 << current_bit);
++current_bit;
if (current_bit == 8)
{
out.push_back(buffer);
buffer = 0;
current_bit = 0;
}
}
}
}
inline void pack_bits(vector<Byte> &out, const vector<uint32_t> &sparse_bits, const vector<Byte> &num_bits)
{
Byte buffer = 0;
int current_bit = 0;
for (size_t i = 0; i < sparse_bits.size(); ++i)
{
for (int b = 0; b < num_bits[i]; ++b)
{
int bit = sparse_bits[i] & (1 << b);
if (bit)
buffer |= (1 << current_bit);
++current_bit;
if (current_bit == 8)
{
out.push_back(buffer);
buffer = 0;
current_bit = 0;
}
}
}
}
inline void unpack_bits(vector<uint32_t> &sparse_bits, const vector<Byte> &in, int num_bits)
{
uint32_t buffer = 0;
int current_bit = 0;
for (size_t i = 0; i < in.size(); ++i)
{
for (int b = 0; b < 8; ++b)
{
int bit = in[i] & (1 << b);
if (bit)
buffer |= (1 << current_bit);
++current_bit;
if (current_bit == num_bits)
{
sparse_bits.push_back(buffer);
buffer = 0;
current_bit = 0;
}
}
}
}
inline void unpack_bits(vector<uint32_t> &sparse_bits, const vector<Byte> &in, const vector<Byte> &num_bits)
{
uint32_t buffer = 0;
int current_bit = 0;
int num_idx = 0;
for (size_t i = 0; i < in.size(); ++i)
{
for (int b = 0; b < 8; ++b)
{
int bit = in[i] & (1 << b);
if (bit)
buffer |= (1 << current_bit);
++current_bit;
if (current_bit == num_bits[num_idx])
{
sparse_bits.push_back(buffer);
buffer = 0;
current_bit = 0;
++num_idx;
}
}
}
}
bool uses_prediction_coding_quantization_table()
{
return s_UseQuantizationTable;
}
void load_prediction_coding_quantization_table(const string &file)
{
s_UseQuantizationTable = true;
std::ifstream in(file, std::ifstream::in);
string line;
int i = 0;
while (std::getline(in, line, ',') && i < 255)
{
s_QuantizationTable[i] = std::stoi(line);
++i;
}
}
vector<Byte> get_prediction_coding_quantization_table(int max_moments, int numBits)
{
vector<Byte> table(max_moments);
for (int m = 0; m < max_moments; ++m)
{
if (s_UseQuantizationTable)
table[m] = s_QuantizationTable[m];
else
{
if (m == 0)
table[m] = 16;
else
table[m] = numBits;
}
}
return table;
}
void set_prediction_coding_quantization_table(const vector<Byte> &table)
{
s_UseQuantizationTable = true;
for (size_t i = 0; i < table.size(); ++i)
s_QuantizationTable[i] = table[i];
}
vector<Byte> get_prediction_coding_quantization_table()
{
vector<Byte> table(255, 32);
if (s_UseQuantizationTable)
{
for (int i = 0; i < 255; ++i)
table[i] = s_QuantizationTable[i];
}
else
assert(false);
return table;
}
void write_prediction_coding_quantization_table_to_file(const string &filename)
{
std::fstream out(filename, std::fstream::out);
for (size_t i = 0; i < s_QuantizationTable.size(); ++i)
{
if (i != s_QuantizationTable.size() -1)
out << int(s_QuantizationTable[i]) << ", ";
else
out << int(s_QuantizationTable[i]);
}
out << "\n";
}
vector<Byte> quantize_prediction_coding(const MomentImageHost &mi, const vector<Byte> &quant_table)
{
assert(mi.prediction_code);
vector<uint32_t> words;
vector<Byte> num_bits;
for (int y = 0; y < mi.height; ++y)
{
for (int x = 0; x < mi.width; ++x)
{
auto num_moments = mi.get_num_moments(x, y);
auto idx = mi.get_idx(x, y);
if (num_moments == 0)
continue;
auto num_bits_0 = quant_table[0];
auto ql = quantize(mi.data[idx], num_bits_0, 0.0f, 1.0f);
words.push_back(ql);
num_bits.push_back(num_bits_0);
for (int l = 1; l < num_moments; ++l)
{
auto num_bits_l = quant_table[l];
auto u_l = mi.data[idx + l];
auto ql =
quantize(u_l, num_bits_l, PREDICTION_CODING_QUANTIZATION_MIN, PREDICTION_CODING_QUANTIZATION_MAX);
words.push_back(ql);
num_bits.push_back(num_bits_l);
}
}
}
vector<Byte> packed_bits;
pack_bits(packed_bits, words, num_bits);
return packed_bits;
}
vector<Byte> quantize_prediction_coding(const MomentImageHost &mi, int numBits)
{
auto table = get_prediction_coding_quantization_table(mi.num_moments, numBits);
return quantize_prediction_coding(mi, table);
}
void dequantize_prediction_coding(MomentImageHost &mi, const vector<Byte> &quant_table, const vector<Byte> &qs)
{
assert(mi.prediction_code);
vector<Byte> num_bits;
for (int y = 0; y < mi.height; ++y)
{
for (int x = 0; x < mi.width; ++x)
{
auto num_moments = mi.get_num_moments(x, y);
if (num_moments == 0)
continue;
for (int l = 0; l < num_moments; ++l)
num_bits.push_back(quant_table[l]);
}
}
vector<uint32_t> words;
unpack_bits(words, qs, num_bits);
size_t offset = 0;
for (int y = 0; y < mi.height; ++y)
{
for (int x = 0; x < mi.width; ++x)
{
auto num_moments = mi.get_num_moments(x, y);
auto idx = mi.get_idx(x, y);
if (num_moments == 0)
continue;
uint32_t qj = words[offset];
mi.data[idx] = dequantize(qj, num_bits[offset], 0.0, 1.0);
assert(!std::isnan(mi.data[idx]) && !std::isinf(mi.data[idx]));
++offset;
for (int l = 1; l < num_moments; ++l)
{
uint32_t qj = words[offset];
mi.data[idx + l] = dequantize(qj, num_bits[offset], PREDICTION_CODING_QUANTIZATION_MIN,
PREDICTION_CODING_QUANTIZATION_MAX);
assert(!std::isnan(mi.data[idx + l]) && !std::isinf(mi.data[idx + l]));
assert(mi.data[idx + l] >= -1.0f && mi.data[idx + l] <= 1.0f);
++offset;
}
}
}
}
void dequantize_prediction_coding(MomentImageHost &mi, int numBits, const vector<Byte> &qs)
{
auto table = get_prediction_coding_quantization_table(mi.num_moments, numBits);
return dequantize_prediction_coding(mi, table, qs);
}
vector<Byte> quantize(const MomentImageHost &mi, int numBits)
{
assert(!mi.prediction_code);
vector<uint32_t> qs;
for (int y = 0; y < mi.height; ++y)
{
for (int x = 0; x < mi.width; ++x)
{
auto num_moments = mi.get_num_moments(x, y);
auto idx = mi.get_idx(x, y);
if (num_moments == 0)
continue;
uint32_t q0 = quantize(mi.data[idx], numBits, 0.0f, 1.0f);
qs.push_back(q0);
for (int j = 1; j < num_moments; ++j)
{
float mj = mi.data[idx + j];
auto qm = quantize(mj, numBits, -1.0 / M_PI, 1.0 / M_PI);
qs.push_back(qm);
}
}
}
vector<Byte> packed_bits;
pack_bits(packed_bits, qs, numBits);
return packed_bits;
}
void dequantize(MomentImageHost &mi, int numBits, const vector<Byte> &qs)
{
assert(!mi.prediction_code);
vector<uint32_t> words;
unpack_bits(words, qs, numBits);
size_t offset = 0;
for (int y = 0; y < mi.height; ++y)
{
for (int x = 0; x < mi.width; ++x)
{
auto num_moments = mi.get_num_moments(x, y);
auto idx = mi.get_idx(x, y);
if (num_moments == 0)
continue;
auto m0 = words[offset]; // read_bytes(qs, b_offset, num_bytes);
++offset;
// b_offset += num_bytes;
mi.data[idx] = dequantize(m0, numBits, 0.0f, 1.0f);
assert(mi.data[idx] >= 0.0f / M_PI && mi.data[idx] <= 1.0f);
for (int l = 1; l < num_moments; ++l)
{
uint32_t qj = words[offset]; // read_bytes(qs, b_offset, num_bytes);
// b_offset += num_bytes;
++offset;
mi.data[idx + l] = dequantize(qj, numBits, -1.0 / M_PI, 1.0 / M_PI);
assert(mi.data[idx + l] >= -1.0f / M_PI && mi.data[idx + l] <= 1.0f / M_PI);
}
}
}
}
void append(vector<Byte> &qs, uint32_t q, int numBits)
{
int numBytes = (numBits + 7) / 8;
if (numBytes == 1)
qs.push_back(static_cast<Byte>(q));
else if (numBytes == 2)
{
qs.push_back(static_cast<Byte>(q & 0xFF));
qs.push_back(static_cast<Byte>((q >> 8) & 0xFF));
}
else if (numBytes == 3)
{
qs.push_back(static_cast<Byte>(q & 0xFF));
qs.push_back(static_cast<Byte>((q >> 8) & 0xFF));
qs.push_back(static_cast<Byte>((q >> 16) & 0xFF));
}
else
{
qs.push_back(static_cast<Byte>(q & 0xFF));
qs.push_back(static_cast<Byte>((q >> 8) & 0xFF));
qs.push_back(static_cast<Byte>((q >> 16) & 0xFF));
qs.push_back(static_cast<Byte>((q >> 24) & 0xFF));
}
}
uint32_t read_bits_at_idx(const vector<Byte> &qs, int idx, int numBits)
{
int numBytes = (numBits + 7) / 8;
if (numBytes == 1)
return qs[idx];
else if (numBytes == 2)
{
uint32_t res = qs[idx * numBytes];
res |= qs[idx * numBytes + 1] << 8;
return res;
}
else if (numBytes == 3)
{
uint32_t res = qs[idx * numBytes];
res |= qs[idx * numBytes + 1] << 8;
res |= qs[idx * numBytes + 2] << 16;
return res;
}
else
{
uint32_t res = qs[idx * numBytes];
res |= qs[idx * numBytes + 1] << 8;
res |= qs[idx * numBytes + 2] << 16;
res |= qs[idx * numBytes + 3] << 24;
return res;
}
}
vector<Byte> quantize(const vector<float> &moments, int numMoments, int numBits)
{
int numRays = moments.size() / numMoments;
vector<Byte> qs;
qs.reserve(numRays * numMoments * static_cast<int>((numBits + 7) / 8));
for (int i = 0; i < numRays; ++i)
{
float m0 = moments[i * numMoments];
uint32_t q0 = quantize(m0, numBits, 0.0f, 1.0f);
append(qs, q0, numBits);
for (int j = 1; j < numMoments; ++j)
{
float mj = moments[i * numMoments + j];
append(qs, quantize(mj, numBits, -1.0 / M_PI, 1.0 / M_PI), numBits);
}
}
return qs;
}
vector<float> dequantize(const vector<Byte> &qs, int numMoments, int numBits)
{
int numBytes = (numBits + 7) / 8;
int numRays = qs.size() / numMoments / numBytes;
vector<float> values;
values.reserve(numRays * numMoments);
for (int i = 0; i < numRays; ++i)
{
uint32_t q0 = read_bits_at_idx(qs, i * numMoments, numBits);
values.push_back(dequantize(q0, numBits, 0.0f, 1.0f));
for (int j = 1; j < numMoments; ++j)
{
uint32_t qj = read_bits_at_idx(qs, numMoments * i + j, numBits);
values.push_back(dequantize(qj, numBits, -1.0 / M_PI, 1.0 / M_PI));
}
}
return values;
}
} // namespace moment_quantization
| 28.866667 | 118 | 0.553118 |
7c49113f755566789ee39bf2b097dddcaf588764 | 774 | hpp | C++ | 03_Simple_2D_game/Asteroid/include/SFML-Book/Player.hpp | Krozark/SFML-book | 397dd3dc0c73b694d4b5c117e974c7ebdb885572 | [
"BSD-2-Clause"
] | 75 | 2015-01-18T21:29:03.000Z | 2022-02-09T14:11:05.000Z | 03_Simple_2D_game/Asteroid/include/SFML-Book/Player.hpp | Krozark/SFML-book | 397dd3dc0c73b694d4b5c117e974c7ebdb885572 | [
"BSD-2-Clause"
] | 7 | 2015-03-12T10:41:55.000Z | 2020-11-23T11:15:58.000Z | 03_Simple_2D_game/Asteroid/include/SFML-Book/Player.hpp | Krozark/SFML-book | 397dd3dc0c73b694d4b5c117e974c7ebdb885572 | [
"BSD-2-Clause"
] | 33 | 2015-12-01T07:34:46.000Z | 2022-03-23T03:37:42.000Z | #ifndef BOOK_PLAYER_HPP
#define BOOK_PLAYER_HPP
#include <SFML-Book/ActionTarget.hpp> //ActionTarget
#include <SFML-Book/Entity.hpp> //Entity
namespace book
{
class Player : public Entity , public ActionTarget<int>
{
public:
Player(const Player&) = delete;
Player& operator=(const Player&) = delete;
Player(World& world);
virtual bool isCollide(const Entity& other)const;
virtual void update(sf::Time deltaTime);
void processEvents();
void shoot();
void goToHyperspace();
virtual void onDestroy();
private:
bool _isMoving;
int _rotation;
sf::Time _timeSinceLastShoot;
};
}
#endif
| 20.918919 | 61 | 0.576227 |
7c4a20ef6c026977e9bb341654500cb624718f3f | 437 | hpp | C++ | src/utils/types.hpp | LukaszSelwa/min-cut | f11eec7d3c55b886112179d8893ef6ed9b3fc2d5 | [
"MIT"
] | null | null | null | src/utils/types.hpp | LukaszSelwa/min-cut | f11eec7d3c55b886112179d8893ef6ed9b3fc2d5 | [
"MIT"
] | null | null | null | src/utils/types.hpp | LukaszSelwa/min-cut | f11eec7d3c55b886112179d8893ef6ed9b3fc2d5 | [
"MIT"
] | null | null | null | #ifndef UTILS_TYPES_H
#define UTILS_TYPES_H
#include <memory>
#include <vector>
#include "../graphs/undirected_weighted_graph.hpp"
struct algo_result {
int minCutVal;
std::vector<bool> cut;
};
struct algo_input {
std::shared_ptr<graphs::weighted_graph> graph;
std::vector<bool> minCut;
int minCutVal;
};
bool validate_cuts(const std::vector<bool>& cutA, const std::vector<bool>& cutB);
#endif /* UTILS_TYPES_H */ | 20.809524 | 81 | 0.718535 |
7c4c0616aa4fa792076e6acee28793e04471ef6f | 422 | cpp | C++ | 机试/动态规划/leetcode300.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | 机试/动态规划/leetcode300.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | 机试/动态规划/leetcode300.cpp | codehuanglei/- | 933a55b5c5a49163f12e0c39b4edfa9c4f01678f | [
"MIT"
] | null | null | null | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, 1);
int res = dp[0];
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
if(nums[i] > nums[j]){
dp[i] = max(dp[j] + 1, dp[i]);
}
}
res = max(res, dp[i]);
}
return res;
}
}; | 24.823529 | 50 | 0.350711 |
7c4c60fc018b62608c46fe0ec12d9b8de69d27c3 | 2,802 | cpp | C++ | trunk/uidesigner/uidframe/src/Core/HoldItem.cpp | OhmPopy/MPFUI | eac88d66aeb88d342f16866a8d54858afe3b6909 | [
"MIT"
] | 59 | 2017-08-27T13:27:55.000Z | 2022-01-21T13:24:05.000Z | demos/uidesigner/uidframe/src/Core/HoldItem.cpp | BigPig0/MPFUI | 7042e0a5527ab323e16d2106d715db4f8ee93275 | [
"MIT"
] | 5 | 2017-11-26T05:40:23.000Z | 2019-04-02T08:58:21.000Z | demos/uidesigner/uidframe/src/Core/HoldItem.cpp | BigPig0/MPFUI | 7042e0a5527ab323e16d2106d715db4f8ee93275 | [
"MIT"
] | 49 | 2017-08-24T08:00:50.000Z | 2021-11-07T01:24:41.000Z | #include "stdafx.h"
#include <Core/HoldItem.h>
#include <Core/ResNode.h>
void HoldItem::InitNode(suic::IXamlNode* pNode)
{
pNode->Reset();
InitNode(this, pNode);
}
void HoldItem::Clear()
{
for (int i = 0; i < children.GetCount(); ++i)
{
Clear(children.GetItem(i));
}
attrs.Clear();
children.Clear();
}
String HoldItem::GetResXml(const String& offset)
{
String strChild = GetResXml(this, offset);
return strChild;
}
String HoldItem::GetChildResXml(const String& offset)
{
String strChild;
for (int j = 0; j < children.GetCount(); ++j)
{
HoldItem* pChild = children.GetItem(j);
strChild += GetResXml(pChild, offset);
}
return strChild;
}
void HoldItem::CloneTo(HoldItem* Other)
{
Other->Clear();
Other->name = name;
for (int i = 0; i < attrs.GetCount(); ++i)
{
Other->attrs.Add(attrs.GetItem(i));
}
for (int j = 0; j < children.GetCount(); ++j)
{
HoldItem* pChild = children.GetItem(j);
HoldItem* pOtherChild = new HoldItem();
Other->children.Add(pOtherChild);
pChild->CloneTo(pOtherChild);
}
}
void HoldItem::Clear(HoldItem* pHold)
{
for (int i = 0; i < pHold->children.GetCount(); ++i)
{
Clear(pHold->children.GetItem(i));
}
delete pHold;
}
void HoldItem::InitNode(HoldItem* pHold, suic::IXamlNode* pNode)
{
pHold->name = pNode->GetName();
suic::IXamlAttris* pAttris = pNode->GetAttris();
if (NULL != pAttris)
{
while (pAttris->HasNext())
{
StringPair pair(pAttris->GetName(), pAttris->GetValue());
pHold->attrs.Add(pair);
}
}
while (pNode->HasNext())
{
suic::IXamlNode* childNode = pNode->Current();
if (NULL != childNode)
{
HoldItem* pChildItem = new HoldItem();
pHold->children.Add(pChildItem);
InitNode(pChildItem, childNode);
}
}
}
String HoldItem::GetResXml(HoldItem* pHold, const String& offset)
{
String strXml;
strXml += offset + _U("<") + pHold->name;
for (int i = 0; i < pHold->attrs.GetCount(); ++i)
{
StringPair& pair = pHold->attrs.GetItem(i);
strXml += _U(" ") + pair.GetKey() + _U("=\"") + pair.GetValue() + _U("\"");
}
if (pHold->children.GetCount() > 0)
{
strXml += _U(">\n");
String strChild;
for (int j = 0; j < pHold->children.GetCount(); ++j)
{
HoldItem* pChildHold = pHold->children.GetItem(j);
strChild += GetResXml(pChildHold, offset + ResNode::OFFSET1);
}
strXml += strChild;
strXml += offset + _U("</") + pHold->name + _U(">\n");
}
else
{
strXml += _U(" />\n");
}
return strXml;
} | 22.416 | 83 | 0.552463 |
7c50c242e93c7ac923266b8307ed15728e6e63f1 | 3,708 | hpp | C++ | src/sqlite/db.hpp | wesselj1/mx3playground | 9b8c3e783f574a76cc17a9470b57e72a1b38be1a | [
"MIT"
] | 766 | 2015-01-01T17:33:40.000Z | 2022-02-23T08:20:20.000Z | src/sqlite/db.hpp | wesselj1/mx3playground | 9b8c3e783f574a76cc17a9470b57e72a1b38be1a | [
"MIT"
] | 43 | 2015-01-04T05:59:54.000Z | 2017-06-19T10:53:59.000Z | src/sqlite/db.hpp | wesselj1/mx3playground | 9b8c3e783f574a76cc17a9470b57e72a1b38be1a | [
"MIT"
] | 146 | 2015-01-09T19:38:23.000Z | 2021-09-30T08:39:44.000Z | #pragma once
#include <set>
#include <chrono>
#include "stl.hpp"
#include "stmt.hpp"
namespace mx3 { namespace sqlite {
// single param helpers for sqlite3_mprintf
string mprintf(const char * format, const string& data);
string mprintf(const char * format, int64_t data);
string libversion();
string sourceid();
int libversion_number();
string escape_column(const string& column);
enum class ChangeType {
INSERT,
UPDATE,
DELETE
};
enum class OpenFlag {
READONLY,
READWRITE,
CREATE,
URI,
MEMORY,
NOMUTEX,
FULLMUTEX,
SHAREDCACHE,
PRIVATECACHE
};
enum class Checkpoint {
PASSIVE,
FULL,
RESTART
};
enum class Affinity {
TEXT,
NUMERIC,
INTEGER,
REAL,
NONE
};
struct ColumnInfo final {
int64_t cid;
string name;
string type;
Affinity type_affinity() const;
bool notnull;
optional<string> dflt_value;
int32_t pk;
bool is_pk() const { return pk != 0; }
};
struct TableInfo final {
string name;
string sql;
int64_t rootpage;
vector<ColumnInfo> columns;
};
class Db final : public std::enable_shared_from_this<Db> {
public:
struct Change final {
ChangeType type;
string db_name;
string table_name;
int64_t rowid;
};
using UpdateHookFn = function<void(Change)>;
using CommitHookFn = function<bool()>;
using RollbackHookFn = function<void()>;
using WalHookFn = function<void(const string&, int)>;
// use this constructor if you want to simply open the database with default settings
static shared_ptr<Db> open(const string& path);
// use this constructor if you want to simply open an in memory database with the default flags
static shared_ptr<Db> open_memory();
// the most general Db constructor, directly mirrors sqlite3_open_v2
static shared_ptr<Db> open(const string& path, const std::set<OpenFlag>& flags, const optional<string>& vfs_name = nullopt);
// use this constructor if you want to do anything custom to set up your database
static shared_ptr<Db> inherit_db(sqlite3 * db);
~Db();
void update_hook(const UpdateHookFn& update_fn);
void commit_hook(const CommitHookFn& commit_fn);
void rollback_hook(const RollbackHookFn& rollback_fn);
void wal_hook(const WalHookFn& wal_fn);
std::pair<int, int> wal_checkpoint_v2(const optional<string>& db_name, Checkpoint mode);
string journal_mode();
int64_t last_insert_rowid();
int32_t schema_version();
void busy_timeout(nullopt_t);
void busy_timeout(std::chrono::system_clock::duration timeout);
vector<TableInfo> schema_info();
optional<TableInfo> table_info(const string& table_name);
vector<ColumnInfo> column_info(const string& table_name);
int32_t user_version();
void set_user_version(int32_t user_ver);
// give the ability to fetch the raw db pointer (in case you need to do anything special)
sqlite3 * borrow_db();
shared_ptr<Stmt> prepare(const string& sql);
void exec(const string& sql);
int64_t exec_scalar(const string& sql);
void enable_wal();
void close();
private:
struct Closer final {
void operator() (sqlite3 * db) const;
};
struct only_for_internal_make_shared_t;
public:
// make_shared constructor
Db(only_for_internal_make_shared_t flag, unique_ptr<sqlite3, Closer> db);
private:
unique_ptr<sqlite3, Closer> m_db;
// To ensure proper memory management, these hooks are owned by the database.
unique_ptr<UpdateHookFn> m_update_hook;
unique_ptr<CommitHookFn> m_commit_hook;
unique_ptr<RollbackHookFn> m_rollback_hook;
unique_ptr<WalHookFn> m_wal_hook;
};
} }
| 26.676259 | 128 | 0.699838 |
7c5115db2bd1096958da5285052bd6aa076b0e60 | 14,920 | inl | C++ | include/writer.inl | jpulidojr/VizAly-SNWPAC | ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd | [
"Unlicense",
"BSD-3-Clause"
] | 2 | 2020-03-19T07:14:54.000Z | 2022-03-11T19:29:33.000Z | include/writer.inl | jpulidojr/VizAly-SNWPAC | ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | include/writer.inl | jpulidojr/VizAly-SNWPAC | ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd | [
"Unlicense",
"BSD-3-Clause"
] | 2 | 2019-07-22T16:14:52.000Z | 2020-03-19T07:14:56.000Z |
#include "stdio.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string.h>
//#include <math.h>
#include <sstream>
//Use existing lossless compressors
#include "lz4.h"
/*static int * pfs1;
static int dimx1, dimy1, dimz1;
static int header_size1, scalar_fields1;
static double field_len1;*/
// These functions typically used by LZ4
static size_t write_uint16(FILE* fp, uint16_t i)
{
return fwrite(&i, sizeof(i), 1, fp);
}
static size_t write_bin(FILE* fp, const void* array, int arrayBytes)
{
return fwrite(array, 1, arrayBytes, fp);
}
template <typename T>
int arr_to_vti_3d_range_scale(T **** in, const char * filename,int xl,int xu, int yl,int yu, int zl, int zu, std::vector<std::string> names)
{
int sizeof_val = sizeof(in[0][0][0][0]);
//if(!readConfigw())
//{
// std::cout << "Error reading configuration file. Exiting..." << std::endl;
// return 0;
//}
//int *prefs = pfs1;
//std::string * field_names = fn1;
int dimx1 = (xu-xl)+1;//prefs[0];
int dimy1 = (yu-yl)+1;//prefs[1];
int dimz1 = (zu-zl)+1;//prefs[2];
//header_size1 = prefs[3];
int scalar_fields1 = names.size();//fld;//prefs[4];
//int num_blocks = prefs[5];
//std::cout << "Dimensions "<< dimx1 << " " << dimy1 << " " << dimz1 <<std::endl;
//std::cout << "Header " << header_size1 << " Fields " << scalar_fields1<<std::endl;
//std::cout << "Num Blocks " << num_blocks << std::endl;
//field_len = (double)((length-header_size) / scalar_fields);
size_t field_len1 = (double)dimx1*dimy1*dimz1*8;
//std::cout << "Length per field: " << field_len1 << std::endl;
// Skip the first bytes of the header
//f.seekg (header_size, std::ios::cur);
size_t len;
len = strlen(filename);
//std::string * part_filenames = new std::string[num_blocks+1];
int num_blocks=1;
// Define arrays for extent lengths
int ** ext_strt = new int*[num_blocks];
int ** ext_end = new int*[num_blocks];
for (int m = 0; m < num_blocks; ++m)
{
ext_strt[m] = new int[3];
ext_end[m] = new int[3];
}
// Define a size for 1 block of data
int * block_size=new int[3];
int blockID=0;
// Set the extents for the entire dataset
ext_strt[blockID][0]=xl;
ext_strt[blockID][1]=yl;
ext_strt[blockID][2]=zl;
ext_end[blockID][0]=xu;
ext_end[blockID][1]=yu;
ext_end[blockID][2]=zu;
// Set block size
block_size[0]=(xu-xl)+1;block_size[1]=(yu-yl)+1;block_size[2]=(zu-zl)+1;
// Start creating each individual block
//for(int g=0; g<num_blocks; g++)
//{
int g = 0;
std::ofstream out;
// Create the output file
printf("Creating %s\n", filename);
out.open(filename, std::ifstream::binary);
out.precision(20);
// Write VTK format header
out << "<VTKFile type=\"ImageData\" version=\"0.1\" byte_order=\"LittleEndian\">"<<std::endl;
out << " <ImageData WholeExtent=\""<<ext_strt[g][0]<<" "<<ext_end[g][0]<<" "<<ext_strt[g][1];
out << " "<<ext_end[g][1]<<" "<<ext_strt[g][2]<<" "<<ext_end[g][2]<<"\"";
out << " Origin=\"0 0 0\" Spacing=\"1 1 1\">"<<std::endl;
out << " <Piece Extent=\""<<ext_strt[g][0]<<" "<<ext_end[g][0]<<" "<<ext_strt[g][1];
out << " "<<ext_end[g][1]<<" "<<ext_strt[g][2]<<" "<<ext_end[g][2]<<"\">"<<std::endl;
out << " <PointData Scalars=\"density_scalars\">"<<std::endl;
int bin_offset = 0;
int * ghost = new int[3];
// Write the headers for each of the scalar fields (assuming they're doubles)
for(int i=0; i<scalar_fields1; i++)
{
// Factor in ghost data into the blocks
if(ext_strt[g][0]!=0){ghost[0]=0;}else{ghost[0]=0;}
if(ext_strt[g][1]!=0){ghost[1]=0;}else{ghost[1]=0;}
if(ext_strt[g][2]!=0){ghost[2]=0;}else{ghost[2]=0;}
//printf("%i %i %i\n", ghost[0], ghost[1], ghost[2]);
if( sizeof_val == 8 )
out << " <DataArray type=\"Float64\" Name=\""<<names[i]<<"\" format=\"appended\" offset=\""<< (double)(i*((double)(block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2])*8))+bin_offset <<"\"/>"<<std::endl;
else if( sizeof_val == 4)
out << " <DataArray type=\"Float32\" Name=\""<<names[i]<<"\" format=\"appended\" offset=\""<< (double)(i*((double)(block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2])*4))+bin_offset <<"\"/>"<<std::endl;
else
{
std::cout << "ERROR: Data size of " << sizeof_val << " bytes not supported for vti!" << std::endl;
return -1;
}
bin_offset += 4;
}
out << " </PointData>"<<std::endl;
out << " <CellData>" << std::endl;
out << " </CellData>" << std::endl;
out << " </Piece>"<<std::endl;
out << " </ImageData>"<<std::endl;
out << " <AppendedData encoding=\"raw\">"<<std::endl;
// Denote that you are about to write in binary
out << " _";
//char * bin_value= new char[sizeof_val];//[8];
//std::cout<< "[";
for(int sf=0; sf < scalar_fields1; sf++)
{
// As per the API, first encode a 32-bit unsigned integer value specifying
// the number of bytes in the block of data following it
unsigned int block_byte_size = ((block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2]))*8;
if(((double)block_size[0]*block_size[1]*block_size[2]*8) > 4294967296.0)
{
printf("Error: Scalar field size is too large. Choose a larger\n");
printf("number of blocks to segment by.\n");
return 0;
}
out.write( reinterpret_cast<char*>( &block_byte_size ), 4 );
int c=0;
for(int z=ext_strt[g][2]; z<=ext_end[g][2]; z++)
{
int b=0;
for(int y=ext_strt[g][1]; y<=ext_end[g][1]; y++)
{
int a=0;
for(int x=ext_strt[g][0]; x<=ext_end[g][0]; x++)
{
T dbl_val = (T)in[sf][a][b][c];
out.write(reinterpret_cast<char*>( &dbl_val ), sizeof_val);//sizeof(double));
a++;
}
b++;
}
c++;
}
//std::cout<<"] - "<<field_names[sf]<<" done!\n[";
}
//printf("Complete!");
//std::cout<<"]\n";
//Finish off the xml file
out << std::endl;
out << " </AppendedData>"<<std::endl;
out << "</VTKFile>";
//printf("%s Done!\n", part_filenames[g+1].c_str());
out.close();
//}
//std::cout<<"Done!"<<std::endl;
return 0;
}
template <typename T>
int save_coefficients(T * data, const char * filename, size_t total)
{
std::ofstream out;
// Create the output file
printf("Creating %s\n", filename);
out.open(filename, std::ifstream::binary);
out.precision(20);
for(int sz=0; sz < total; sz++)
{
T dbl_val = data[sz];
out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(T));
}
std::cout<<"Coefficient's saved\n";
out.close();
return 1;
}
template <typename T>
int save_coefficients_md(T * data, const char * filename, int * args)
{
std::ofstream out;
// Create the output file
printf("Creating %s\n", filename);
out.open(filename, std::ifstream::binary);
//out.precision(20);
short * tmp_s = new short[1]; char * tmp_c = new char[1];
int * tmp_i = new int[1];
// Write the header
tmp_s[0] = args[0]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short));
tmp_s[0] = args[1]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short));
tmp_c[0] = args[2]; out.write(reinterpret_cast<char*>( tmp_c ), sizeof(char));
tmp_s[0] = args[3]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short));
tmp_i[0] = args[4]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int));
tmp_i[0] = args[5]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int));
tmp_i[0] = args[6]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int));
tmp_i[0] = args[7]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int));
tmp_i[0] = args[8]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int));
tmp_i[0] = args[9]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int));
tmp_c[0] = args[10];out.write(reinterpret_cast<char*>( tmp_c ), sizeof(char));
delete [] tmp_s; delete [] tmp_c; delete [] tmp_i;
size_t total = (size_t)args[4]*(size_t)args[5]*(size_t)args[6];
// Check if we are using lz4 on coefficients
if (args[2] >= 118)
{
std::cout << "Beginning LZ4 Routines...";
// Optional: Perform floating point to integer requantization:
// No Requantization if args[2]=128
// When it's 125, it's 128-125 = 3. We divide by 1000
// When it's 131, it's 128-131 = -3. Multibly by 1000
double mod_bits = 1;
size_t oval_sz = sizeof(T);
if( args[2] > 128 ) // Multiply (for small dyn range data)
{
int cnt = args[2];
while (cnt != 128)
{
mod_bits *= 10.0;
cnt--;
}
oval_sz = sizeof(int);
std::cout << "requantizing coefficients: 1*10^" << args[2] - 128 << std::endl;
}
if(args[2] < 128 ) // Divide (for high dyn range data)
{
int cnt = args[2];
while (cnt != 128)
{
mod_bits /= 10.0;
cnt++;
}
oval_sz = sizeof(int);
std::cout << "requantizing coefficients: 1*10^-" << 128 - args[2] << std::endl;
}
// Target output variable (type)
T dbl_val;
//int dbl_val; // INT SUPPORT
const size_t totBytes = total * oval_sz;
size_t datBytes = totBytes;
// WARNING: LZ4_MAX_INPUT_SIZE is about 2MB so suggest using a sliding buffer
// Restriction inside of srcSize
if (totBytes > LZ4_MAX_INPUT_SIZE)
{
std::cout << "Warning: Data to write is larger than supported by Lz4. Use rolling buffer!!\n";
datBytes = LZ4_MAX_INPUT_SIZE;
}
LZ4_stream_t* lz4Stream = LZ4_createStream();
const size_t cmpBufBytes = LZ4_COMPRESSBOUND(datBytes); //messageMaxBytes
//Preallocate buffers
char * inBuf = new char[datBytes];
char * cmpBuf = new char[cmpBufBytes];
// Use a sliding window approach and reinterpert type cast to char * array.
// Use a ring buffer????
size_t max_vals = datBytes / oval_sz;
std::cout << " Encoding " << max_vals << " values.\n";
size_t sk = 0;
char * cval;
if (oval_sz == 4)
{
int dbl_val; // int for requantization
for (size_t sz = 0; sz < max_vals; sz++)
{
//dbl_val = data[sz]*100000; // INT SUPPORT
dbl_val = data[sz]*mod_bits; // INT SUPPORT
sk = sz * sizeof(dbl_val);
cval = reinterpret_cast<char*>(&dbl_val);
for (size_t id = 0; id < sizeof(dbl_val); id++)
{
inBuf[sk + id] = cval[id];
}
}
}
else if (oval_sz == 8)
{
T dbl_val; // No requant
for (size_t sz = 0; sz < max_vals; sz++)
{
dbl_val = data[sz];
sk = sz * sizeof(dbl_val);
cval = reinterpret_cast<char*>(&dbl_val);
for (size_t id = 0; id < sizeof(dbl_val); id++)
{
inBuf[sk + id] = cval[id];
}
//delete[] cval;
//inBuf[sk] = reinterpret_cast<char*>(&dbl_val), sizeof(dbl_val); //Insert T val into character buffer
//memcpy?
}
}
else
{
std::cout << "ERROR: Invalid byte size!" << std::endl; return -1;
}
//const int cmpBytes = LZ4_compress_fast_continue(lz4Stream, inBuf, cmpBuf, datBytes, cmpBufBytes, 1); /rolling
int cmpBytes = LZ4_compress_default(inBuf, cmpBuf, datBytes, cmpBufBytes);
//Write out the buffer size first
//write_uint16(FILE* fp, uint16_t i)
out.write(reinterpret_cast<char*>(&cmpBytes), sizeof(cmpBytes));
std::cout << "LZ4: Encoding " << cmpBytes << " bytes.." << std::endl;
// Write out bytestream
out.write(cmpBuf, cmpBytes);
delete[] inBuf;
delete[] cmpBuf;
LZ4_freeStream(lz4Stream);
std::cout << "..Done LZ4!\n";
}
// Check if we are encoding coefficients with RLE
else if(args[2] >= 64)
{
std::cout<<"Encoding enabled...";
//unsigned char signal = 0x24; //$ sign UTF-8
char signal = '$';
char signal2 = '@';
char signal3 = '#';
char signal4 = 'h';
//std::cout << "Size of char=" << sizeof(signal) << " value " << signal << std::endl;
unsigned short smax=0;
float wbytes=0;
int skips=0;
for(size_t sz=0; sz < total; sz++)
{
if (data[sz] == 0)
{
skips++;
int cont_block_cnt=0;
while (data[sz]==0 && sz < total)
{
sz++;
cont_block_cnt++; // DEBUG
}
// Encode the number of steps to skip
while(cont_block_cnt>65535) //Exceeded u_short_int
{
smax = 65535;
out.write(reinterpret_cast<char*>( &signal ), sizeof(signal));
out.write(reinterpret_cast<char*>( &signal2 ), sizeof(signal2));
out.write(reinterpret_cast<char*>( &signal3 ), sizeof(signal3));
out.write(reinterpret_cast<char*>( &signal4 ), sizeof(signal4));
out.write(reinterpret_cast<char*>( &smax ), sizeof(smax));
skips++;
cont_block_cnt-=65535;
wbytes+=sizeof(signal)*4+sizeof(smax);
}
smax = cont_block_cnt;
//std::cout << "\nSkipping at byte_loc: " << wbytes << " for " << smax << std::endl;
out.write(reinterpret_cast<char*>( &signal ), sizeof(signal));
out.write(reinterpret_cast<char*>( &signal2 ), sizeof(signal2));
out.write(reinterpret_cast<char*>( &signal3 ), sizeof(signal3));
out.write(reinterpret_cast<char*>( &signal4 ), sizeof(signal4));
out.write(reinterpret_cast<char*>( &smax ), sizeof(smax));
wbytes+=sizeof(signal)*4+sizeof(smax);
}
T dbl_val = data[sz];
out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(dbl_val));
wbytes+=sizeof(dbl_val);
}
std::cout<<"...Coefficient's saved\n";
std::cout<<"Bytes written (w header): " << wbytes+32 << std::endl;
std::cout << "Contiguous skips: " << skips << std::endl;
}
// Just write coefficients to storage with zeros intact
else
{
for(size_t sz=0; sz < total; sz++)
{
T dbl_val = data[sz];
out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(T));
}
std::cout<<"Coefficient's saved\n";
}
out.close();
return 1;
}
| 35.105882 | 235 | 0.552413 |
7c5976175e28b08a295516dc36fcc5cec67f35a8 | 1,263 | cpp | C++ | cpp-tower/Game.cpp | udupa-varun/coursera-cs400 | cf073e6fe816c0d1f8fe95cae10448e979fec2ce | [
"MIT"
] | 2 | 2021-05-19T02:49:55.000Z | 2021-05-20T03:14:24.000Z | cpp-tower/Game.cpp | udupa-varun/coursera-cs400 | cf073e6fe816c0d1f8fe95cae10448e979fec2ce | [
"MIT"
] | null | null | null | cpp-tower/Game.cpp | udupa-varun/coursera-cs400 | cf073e6fe816c0d1f8fe95cae10448e979fec2ce | [
"MIT"
] | null | null | null | /**
* C++ class for a game of the Tower of Hanoi puzzle.
*
* @author
* Wade Fagen-Ulmschneider <waf@illinois.edu>
*/
#include "Game.h"
#include "Stack.h"
#include "uiuc/Cube.h"
#include "uiuc/HSLAPixel.h"
#include <iostream>
using std::cout;
using std::endl;
// Solves the Tower of Hanoi puzzle.
// (Feel free to call "helper functions" to help you solve the puzzle.)
void Game::solve() {
// Prints out the state of the game:
cout << *this << endl;
// @TODO -- Finish solving the game!
}
// Default constructor to create the initial state:
Game::Game() {
// Create the three empty stacks:
for (int i = 0; i < 3; i++) {
Stack stackOfCubes;
stacks_.push_back( stackOfCubes );
}
// Create the four cubes, placing each on the [0]th stack:
Cube blue(4, uiuc::HSLAPixel::BLUE);
stacks_[0].push_back(blue);
Cube orange(3, uiuc::HSLAPixel::ORANGE);
stacks_[0].push_back(orange);
Cube purple(2, uiuc::HSLAPixel::PURPLE);
stacks_[0].push_back(purple);
Cube yellow(1, uiuc::HSLAPixel::YELLOW);
stacks_[0].push_back(yellow);
}
std::ostream& operator<<(std::ostream & os, const Game & game) {
for (unsigned i = 0; i < game.stacks_.size(); i++) {
os << "Stack[" << i << "]: " << game.stacks_[i];
}
return os;
}
| 23.388889 | 71 | 0.642914 |
7c5a6e0f32baf316ddb52f38114e81f0670d4510 | 21,740 | cpp | C++ | bin/Debugger.Sample/Debugger.Sample.cpp | igor-ribeiiro/ChakraCore-Debugger | ffbe00d82208ad3327482a6f0cb50c30035480bd | [
"MIT"
] | 16 | 2018-07-11T18:06:16.000Z | 2019-04-15T09:28:46.000Z | bin/Debugger.Sample/Debugger.Sample.cpp | igor-ribeiiro/ChakraCore-Debugger | ffbe00d82208ad3327482a6f0cb50c30035480bd | [
"MIT"
] | 28 | 2018-07-18T22:30:14.000Z | 2019-04-22T18:02:33.000Z | bin/Debugger.Sample/Debugger.Sample.cpp | igor-ribeiiro/ChakraCore-Debugger | ffbe00d82208ad3327482a6f0cb50c30035480bd | [
"MIT"
] | 12 | 2019-06-20T01:18:17.000Z | 2021-07-12T17:48:33.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "stdafx.h"
//
// Class to store information about command-line arguments to the host.
//
class CommandLineArguments
{
public:
bool breakOnNextLine;
bool enableDebugging;
bool help;
bool enableConsoleRedirect;
bool loadScriptUsingBuffer;
int port;
std::vector<std::wstring> scripts;
std::vector<std::wstring> scriptArgs;
CommandLineArguments()
: breakOnNextLine(false)
, enableDebugging(false)
, enableConsoleRedirect(true)
, help(false)
, loadScriptUsingBuffer(false)
, port(9229)
{
}
void ParseCommandLine(int argc, wchar_t* argv[])
{
bool foundScript = false;
for (int index = 1; index < argc; ++index)
{
std::wstring arg(argv[index]);
// Any flags before the script are considered host flags, anything else is passed to the script.
if (!foundScript && (arg.length() > 0) && (arg[0] == L'-'))
{
if (!arg.compare(L"--inspect"))
{
this->enableDebugging = true;
}
else if (!arg.compare(L"--inspect-brk"))
{
this->enableDebugging = true;
this->breakOnNextLine = true;
}
else if (!arg.compare(L"--port") || !arg.compare(L"-p"))
{
++index;
if (index < argc)
{
// This will return zero if no number was found.
this->port = std::stoi(std::wstring(argv[index]));
}
}
else if (!arg.compare(L"--script"))
{
++index;
if (index < argc)
{
std::wstring script(argv[index]);
this->scripts.emplace_back(std::move(script));
}
}
else if (!arg.compare(L"--buffer"))
{
this->loadScriptUsingBuffer = true;
}
else if (!arg.compare(L"--no-console-redirect"))
{
this->enableConsoleRedirect = false;
}
else
{
// Handle everything else including `-?` and `--help`
this->help = true;
}
}
else
{
foundScript = true;
// Collect any non-flag arguments
this->scriptArgs.emplace_back(std::move(arg));
}
}
if (this->port <= 0 || this->port > 65535 || this->scriptArgs.empty())
{
this->help = true;
}
}
void ShowHelp()
{
fwprintf(stderr,
L"\n"
L"Usage: ChakraCore.Debugger.Sample.exe [host-options] <script> [script-arguments]\n"
L"\n"
L"Options: \n"
L" --buffer Load script using JsCreateExternalArrayBuffer/JsRun\n"
L" -? --help Show this help info\n"
L" --inspect Enable debugging\n"
L" --inspect-brk Enable debugging and break\n"
L" --no-console-redirect Disable console redirection\n"
L" -p, --port <number> Specify the port number\n"
L" --script <script> Additional script to load\n"
L"\n");
}
};
class ScriptData
{
private:
std::string m_script;
public:
ScriptData(std::string const&& script)
{
m_script = std::move(script);
}
const char* c_str() const
{
return m_script.c_str();
}
size_t length() const
{
return m_script.length();
}
static std::unique_ptr<ScriptData> Create(std::string const&& script)
{
return std::make_unique<ScriptData>(std::move(script));
}
static void CALLBACK Finalize(void* callbackState)
{
auto instance = std::unique_ptr<ScriptData>(reinterpret_cast<ScriptData*>(callbackState));
}
};
std::wstring ConvertStringFromUtf8ToUtf16(const std::string& string)
{
std::vector<wchar_t> contents(string.length());
if (MultiByteToWideChar(CP_UTF8, 0, string.c_str(), static_cast<int>(string.length()), contents.data(), static_cast<int>(contents.size())) == 0)
{
const char* message = "chakrahost: unable to convert string from UTF-8 to UTF-16.";
fprintf(stderr, message);
fprintf(stderr, "\n");
throw new std::runtime_error(message);
}
return std::wstring(begin(contents), end(contents));
}
unsigned GetNextSourceContext()
{
static unsigned sourceContext = 0;
return sourceContext++;
}
//
// Helper to load a script from disk.
//
std::string LoadScriptUtf8(const wchar_t* filename)
{
std::ifstream ifs(filename, std::ifstream::in | std::ifstream::binary);
if (!ifs.good())
{
fwprintf(stderr, L"chakrahost: unable to open file: %s.\n", filename);
return std::string();
}
return std::string(
(std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
}
std::wstring LoadScriptUtf16(const wchar_t* filename)
{
std::string scriptUtf8 = LoadScriptUtf8(filename);
return ConvertStringFromUtf8ToUtf16(scriptUtf8);
}
JsErrorCode RunScript(bool loadScriptUsingBuffer, const wchar_t* filename, JsValueRef* result)
{
wchar_t fullPath[MAX_PATH];
DWORD pathLength = GetFullPathName(filename, MAX_PATH, fullPath, nullptr);
if (pathLength > MAX_PATH || pathLength == 0)
{
return JsErrorInvalidArgument;
}
if (loadScriptUsingBuffer)
{
JsValueRef sourceUrl = JS_INVALID_REFERENCE;
JsValueRef scriptValueRef = JS_INVALID_REFERENCE;
// Load script from the file
std::string script = LoadScriptUtf8(fullPath);
if (script.empty())
{
return JsErrorInvalidArgument;
}
auto scriptData = ScriptData::Create(std::move(script));
char* data = const_cast<char*>(scriptData->c_str());
unsigned int dataLength = static_cast<unsigned int>(scriptData->length());
JsFinalizeCallback callback = ScriptData::Finalize;
ScriptData* callbackState = scriptData.release();
IfFailRet(JsCreateExternalArrayBuffer(data, dataLength, callback, callbackState, &scriptValueRef));
IfFailRet(JsPointerToString(fullPath, wcslen(fullPath), &sourceUrl));
IfFailRet(JsRun(scriptValueRef, GetNextSourceContext(), sourceUrl, JsParseScriptAttributeNone, result));
}
else
{
std::wstring script = LoadScriptUtf16(fullPath);
if (script.empty())
{
return JsErrorInvalidArgument;
}
IfFailRet(JsRunScript(script.c_str(), GetNextSourceContext(), fullPath, result));
}
return JsNoError;
}
//
// Callback to echo something to the command-line.
//
JsValueRef CALLBACK HostEcho(
JsValueRef /*callee*/,
bool /*isConstructCall*/,
JsValueRef* arguments,
unsigned short argumentCount,
void* /*callbackState*/)
{
for (unsigned int index = 1; index < argumentCount; index++)
{
if (index > 1)
{
wprintf(L" ");
}
JsValueRef stringValue = JS_INVALID_REFERENCE;
IfFailThrowJsError(JsConvertValueToString(arguments[index], &stringValue), L"invalid argument");
const wchar_t* string;
size_t length;
IfFailThrowJsError(JsStringToPointer(stringValue, &string, &length), L"invalid argument");
wprintf(L"%s", string);
}
wprintf(L"\n");
return JS_INVALID_REFERENCE;
}
//
// Callback to test handling of exceptions thrown from native code. This isn't a realistic function for a host to
// implement, simply a sample function for testing purposes only.
//
JsValueRef CALLBACK HostThrow(
JsValueRef /*callee*/,
bool /*isConstructCall*/,
JsValueRef* arguments,
unsigned short argumentCount,
void* /*callbackState*/)
{
JsValueRef error = JS_INVALID_REFERENCE;
if (argumentCount >= 2)
{
// Attempt to use the provided object as the error to set.
error = arguments[1];
}
else
{
// By default create a sample error object with a message.
const std::string errStr("Sample error message");
JsValueRef errorMsg = JS_INVALID_REFERENCE;
JsCreateString(errStr.c_str(), errStr.length(), &errorMsg);
JsCreateError(errorMsg, &error);
}
JsSetException(error);
return JS_INVALID_REFERENCE;
}
//
// Callback to load a script and run it.
//
JsValueRef CALLBACK HostRunScript(
JsValueRef /*callee*/,
bool /*isConstructCall*/,
JsValueRef* arguments,
unsigned short argumentCount,
void* /*callbackState*/)
{
JsValueRef result = JS_INVALID_REFERENCE;
if (argumentCount < 2)
{
ThrowJsError(L"not enough arguments");
return result;
}
// Convert filename.
const wchar_t* filename = nullptr;
size_t length = 0;
IfFailThrowJsError(JsStringToPointer(arguments[1], &filename, &length), L"invalid filename argument");
IfFailThrowJsError(RunScript(false, filename, &result), L"failed to run script");
return result;
}
//
// Helper to define a host callback method on the global host object.
//
JsErrorCode DefineHostCallback(
JsValueRef globalObject,
const wchar_t* callbackName,
JsNativeFunction callback,
void* callbackState)
{
// Get property ID.
JsPropertyIdRef propertyId = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(callbackName, &propertyId));
// Create a function
JsValueRef function = JS_INVALID_REFERENCE;
IfFailRet(JsCreateFunction(callback, callbackState, &function));
// Set the property
IfFailRet(JsSetProperty(globalObject, propertyId, function, true));
return JsNoError;
}
JsErrorCode RedirectConsoleToDebugger(DebugProtocolHandler *handler)
{
// Get global.console object. If that is not defined just return, otherwise get the debugger.console and patch with global.console object
JsValueRef globalObject = JS_INVALID_REFERENCE;
IfFailRet(JsGetGlobalObject(&globalObject));
JsPropertyIdRef consolePropertyId = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(L"console", &consolePropertyId));
JsValueRef consoleObject = JS_INVALID_REFERENCE;
IfFailRet(JsGetProperty(globalObject, consolePropertyId, &consoleObject));
JsValueRef undefinedValue = JS_INVALID_REFERENCE;
IfFailRet(JsGetUndefinedValue(&undefinedValue));
if (consoleObject == JS_INVALID_REFERENCE || consoleObject == undefinedValue)
{
return JsNoError;
}
JsValueRef debuggerConsoleObject = JS_INVALID_REFERENCE;
IfFailRet(handler->GetConsoleObject(&debuggerConsoleObject));
const char* script =
"function patchConsoleObject$$1(global, console, debugConsole) {\n"
"var obj = {};\n"
"for (var fn in console) {\n"
"if (typeof console[fn] === \"function\") {\n"
"(function(name) {\n"
"obj[name] = function(...args) {\n"
"console[name](...args);\n"
"if (name in debugConsole && typeof debugConsole[name] === \"function\") {\n"
"debugConsole[name](...args);\n"
"}\n"
"}\n"
"})(fn);\n"
"}\n"
"}\n"
"global.console = obj;\n"
"}\n"
"patchConsoleObject$$1;\n";
JsValueRef patchFunction = JS_INVALID_REFERENCE;
JsValueRef scriptUrl = JS_INVALID_REFERENCE;
IfFailRet(JsCreateString("", 0, &scriptUrl));
JsValueRef scriptContentValue = JS_INVALID_REFERENCE;
IfFailRet(JsCreateString(script, strlen(script), &scriptContentValue));
IfFailRet(JsRun(scriptContentValue, JS_SOURCE_CONTEXT_NONE, scriptUrl, JsParseScriptAttributeLibraryCode, &patchFunction));
JsValueRef args[4] = { undefinedValue, globalObject, consoleObject, debuggerConsoleObject };
IfFailRet(JsCallFunction(patchFunction, args, _countof(args), nullptr /*no return value*/));
return JsNoError;
}
//
// Creates a host execution context and sets up the host object in it.
//
JsErrorCode CreateHostContext(JsRuntimeHandle runtime, std::vector<std::wstring>& scriptArgs, JsContextRef* context)
{
// Create the context.
IfFailRet(JsCreateContext(runtime, context));
// Now set the execution context as being the current one on this thread.
IfFailRet(JsSetCurrentContext(*context));
// Create the host object the script will use.
JsValueRef hostObject = JS_INVALID_REFERENCE;
IfFailRet(JsCreateObject(&hostObject));
// Get the global object
JsValueRef globalObject = JS_INVALID_REFERENCE;
IfFailRet(JsGetGlobalObject(&globalObject));
// Set the global object property name
JsPropertyIdRef globalPropertyId = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(L"global", &globalPropertyId));
IfFailRet(JsSetProperty(globalObject, globalPropertyId, globalObject, true));
JsValueRef consoleObject = JS_INVALID_REFERENCE;
IfFailRet(JsCreateObject(&consoleObject));
// Get the name of the property ("host") that we're going to set on the global object.
JsPropertyIdRef hostPropertyId = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(L"host", &hostPropertyId));
JsPropertyIdRef consolePropertyId = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(L"console", &consolePropertyId));
// Set the property.
IfFailRet(JsSetProperty(globalObject, hostPropertyId, hostObject, true));
IfFailRet(JsSetProperty(globalObject, consolePropertyId, consoleObject, true));
// Now create the host callbacks that we're going to expose to the script.
IfFailRet(DefineHostCallback(hostObject, L"echo", HostEcho, nullptr));
IfFailRet(DefineHostCallback(hostObject, L"runScript", HostRunScript, nullptr));
IfFailRet(DefineHostCallback(hostObject, L"throw", HostThrow, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"debug", HostEcho, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"error", HostEcho, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"info", HostEcho, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"log", HostEcho, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"warn", HostEcho, nullptr));
// Create an array for arguments.
JsValueRef arguments = JS_INVALID_REFERENCE;
unsigned int argCount = static_cast<unsigned int>(scriptArgs.size());
IfFailRet(JsCreateArray(argCount, &arguments));
for (unsigned int index = 0; index < argCount; index++)
{
// Create the argument value.
std::wstring& str = scriptArgs[index];
JsValueRef argument = JS_INVALID_REFERENCE;
IfFailRet(JsPointerToString(str.c_str(), str.length(), &argument));
// Create the index.
JsValueRef indexValue = JS_INVALID_REFERENCE;
IfFailRet(JsIntToNumber(index, &indexValue));
// Set the value.
IfFailRet(JsSetIndexedProperty(arguments, indexValue, argument));
}
// Get the name of the property that we're going to set on the host object.
JsPropertyIdRef argumentsPropertyId = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(L"arguments", &argumentsPropertyId));
// Set the arguments property.
IfFailRet(JsSetProperty(hostObject, argumentsPropertyId, arguments, true));
// Clean up the current execution context.
IfFailRet(JsSetCurrentContext(JS_INVALID_REFERENCE));
return JsNoError;
}
//
// Print out a script exception.
//
JsErrorCode PrintScriptException()
{
// Get script exception.
JsValueRef exception = JS_INVALID_REFERENCE;
IfFailRet(JsGetAndClearException(&exception));
// Get message.
JsPropertyIdRef messageName = JS_INVALID_REFERENCE;
IfFailRet(JsGetPropertyIdFromName(L"message", &messageName));
JsValueRef messageValue = JS_INVALID_REFERENCE;
IfFailRet(JsGetProperty(exception, messageName, &messageValue));
const wchar_t* message;
size_t length;
IfFailRet(JsStringToPointer(messageValue, &message, &length));
fwprintf(stderr, L"chakrahost: exception: %s\n", message);
return JsNoError;
}
JsErrorCode EnableDebugging(
JsRuntimeHandle runtime,
std::string const& runtimeName,
bool breakOnNextLine,
uint16_t port,
std::unique_ptr<DebugProtocolHandler>& debugProtocolHandler,
std::unique_ptr<DebugService>& debugService)
{
JsErrorCode result = JsNoError;
auto protocolHandler = std::make_unique<DebugProtocolHandler>(runtime);
auto service = std::make_unique<DebugService>();
result = service->RegisterHandler(runtimeName, *protocolHandler, breakOnNextLine);
if (result == JsNoError)
{
result = service->Listen(port);
std::cout << "Listening on ws://127.0.0.1:" << port << "/" << runtimeName << std::endl;
}
if (result == JsNoError)
{
debugProtocolHandler = std::move(protocolHandler);
debugService = std::move(service);
}
return result;
}
//
// The main entry point for the host.
//
int _cdecl wmain(int argc, wchar_t* argv[])
{
int returnValue = EXIT_FAILURE;
CommandLineArguments arguments;
arguments.ParseCommandLine(argc, argv);
if (arguments.help)
{
arguments.ShowHelp();
return returnValue;
}
try
{
JsRuntimeHandle runtime = JS_INVALID_RUNTIME_HANDLE;
JsContextRef context = JS_INVALID_REFERENCE;
std::unique_ptr<DebugProtocolHandler> debugProtocolHandler;
std::unique_ptr<DebugService> debugService;
std::string runtimeName("runtime1");
// Create the runtime. We're only going to use one runtime for this host.
IfFailError(
JsCreateRuntime(JsRuntimeAttributeDispatchSetExceptionsToDebugger, nullptr, &runtime),
L"failed to create runtime.");
if (arguments.enableDebugging)
{
IfFailError(
EnableDebugging(runtime, runtimeName, arguments.breakOnNextLine, static_cast<uint16_t>(arguments.port), debugProtocolHandler, debugService),
L"failed to enable debugging.");
}
// Similarly, create a single execution context. Note that we're putting it on the stack here,
// so it will stay alive through the entire run.
IfFailError(CreateHostContext(runtime, arguments.scriptArgs, &context), L"failed to create execution context.");
// Now set the execution context as being the current one on this thread.
IfFailError(JsSetCurrentContext(context), L"failed to set current context.");
if (arguments.enableConsoleRedirect && arguments.enableDebugging)
{
IfFailError(RedirectConsoleToDebugger(debugProtocolHandler.get()), L"Failed to redirect console to debugger.");
}
if (debugProtocolHandler && arguments.breakOnNextLine)
{
std::cout << "Waiting for debugger to connect..." << std::endl;
IfFailError(debugProtocolHandler->WaitForDebugger(), L"failed to wait for debugger");
std::cout << "Debugger connected" << std::endl;
}
if (arguments.scriptArgs.size() > 0)
{
arguments.scripts.emplace_back(arguments.scriptArgs[0]);
}
// for each script
for (unsigned int index = 0; index < arguments.scripts.size(); ++index)
{
// Run the script.
const std::wstring& script = arguments.scripts[index];
JsValueRef result = JS_INVALID_REFERENCE;
JsErrorCode errorCode = RunScript(arguments.loadScriptUsingBuffer, script.c_str(), &result);
if (errorCode == JsErrorScriptException)
{
IfFailError(PrintScriptException(), L"failed to print exception");
return EXIT_FAILURE;
}
else
{
IfFailError(errorCode, L"failed to run script.");
}
// Convert the return value.
JsValueRef numberResult = JS_INVALID_REFERENCE;
double doubleResult;
IfFailError(JsConvertValueToNumber(result, &numberResult), L"failed to convert return value.");
IfFailError(JsNumberToDouble(numberResult, &doubleResult), L"failed to convert return value.");
returnValue = (int) doubleResult;
std::cout << returnValue << std::endl;
}
// Clean up the current execution context.
IfFailError(JsSetCurrentContext(JS_INVALID_REFERENCE), L"failed to cleanup current context.");
context = JS_INVALID_REFERENCE;
if (debugService)
{
IfFailError(debugService->Close(), L"failed to close service");
IfFailError(debugService->UnregisterHandler(runtimeName), L"failed to unregister handler");
IfFailError(debugService->Destroy(), L"failed to destroy service");
}
if (debugProtocolHandler)
{
IfFailError(debugProtocolHandler->Destroy(), L"failed to destroy handler");
}
// Clean up the runtime.
IfFailError(JsDisposeRuntime(runtime), L"failed to cleanup runtime.");
}
catch (...)
{
fwprintf(stderr, L"chakrahost: fatal error: internal error.\n");
}
error:
return returnValue;
}
| 32.740964 | 156 | 0.638132 |
7c5ce1103a68b63e3fc9d600adfa560a410222c7 | 488 | hpp | C++ | src/eepp/window/backend/SDL2/wminfo.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | src/eepp/window/backend/SDL2/wminfo.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | null | null | null | src/eepp/window/backend/SDL2/wminfo.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #ifndef EE_BACKEND_SDL2_WMINFO_HPP
#define EE_BACKEND_SDL2_WMINFO_HPP
#include <eepp/window/backend/SDL2/base.hpp>
#include <eepp/window/windowhandle.hpp>
namespace EE { namespace Window { namespace Backend { namespace SDL2 {
class EE_API WMInfo {
public:
WMInfo( SDL_Window* win );
~WMInfo();
#if defined( EE_X11_PLATFORM )
X11Window getWindow();
#endif
eeWindowHandle getWindowHandler();
protected:
void* mWMInfo;
};
}}}} // namespace EE::Window::Backend::SDL2
#endif
| 17.428571 | 70 | 0.745902 |
7c5ed60bd233d69bcd3fec76f48a78d1253ad5bf | 2,664 | hpp | C++ | OptFrame/Experimental/Moves/MoveVVShiftk.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 2 | 2018-05-24T11:04:12.000Z | 2020-03-03T13:37:07.000Z | OptFrame/Experimental/Moves/MoveVVShiftk.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | null | null | null | OptFrame/Experimental/Moves/MoveVVShiftk.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 1 | 2019-06-06T16:57:49.000Z | 2019-06-06T16:57:49.000Z | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_MOVEVVSHIFTK_HPP_
#define OPTFRAME_MOVEVVSHIFTK_HPP_
// Framework includes
#include "../../Move.hpp"
#include "../NSVector.hpp"
using namespace std;
//============================================================================
// VVShiftk Move
//============================================================================
template<class T, class DS >
class MoveVVShiftk : public Move<vector<vector<T> >, DS >
{
public:
int k,v1,p1,v2,p2;
MoveVVShiftk(int k,int v1,int p1,int v2,int p2)
{
this->k = k;
this->v1 = v1;
this->p1 = p1;
this->v2 = v2;
this->p2 = p2;
}
virtual bool canBeApplied(const vector<vector<T> >&)
{
return true;
}
virtual Move<vector<vector<T> >, DS >& apply(vector<vector<T> >& rep)
{
pair<int,pair < pair<int,int> , pair<int,int> > > m;
m.first = k;
m.second.first.first = v1;
m.second.first.second = p1;
m.second.second.first = v2;
m.second.second.second = p2;
NSVector<T>::shiftk_apply(rep,m);
return * new MoveVVShiftk<T,DS >(k,v2,p2,v1,p1);
}
virtual Move<vector<vector<T> >, DS >& apply(DS& m, vector<vector<T> > & r)
{
if (!m.empty())
{
m[v1].first = m[v2].first = -1;
m[v1].second.first = p1;
m[v1].second.second = r[v1].size()-1;
m[v2].second.first = p2;
m[v2].second.second = r[v2].size()-1;
} else
{
//e->setMemory(new MemVRP(r.size(),make_pair(-1,make_pair(0,r.size()-1))));
m = MemVRPTW(r.size(),make_pair(-1,make_pair(0,r.size()-1)));
}
return apply(r);
}
virtual void print() const
{
cout << "Move Vector Vector Shiftk("<< k << " " << v1 << " " << p1 << " " << v2 << " " << p2 <<")"<<endl;
}
virtual bool operator==(const Move<vector<vector<T> >,DS >& m) const
{
return false; //TODO
}
};
#endif /*OPTFRAME_MOVEVVSHIFTK_HPP_*/
| 27.183673 | 107 | 0.613739 |
7c61d1f10673dfa4e36c148cfe5116240b21778a | 5,786 | cpp | C++ | src/core/taskmanager.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | 2 | 2019-06-22T23:29:44.000Z | 2019-07-07T18:34:04.000Z | src/core/taskmanager.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | src/core/taskmanager.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | /**
* @file taskmanager.cpp
* @brief Implementation of TaskManager.h
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2009-10-05
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/core/precompiled.h"
#include "o3d/core/taskmanager.h"
#include "o3d/core/debug.h"
#include <algorithm>
using namespace o3d;
TaskManager* TaskManager::m_instance = nullptr;
// Singleton instantiation
TaskManager* TaskManager::instance()
{
if (!m_instance)
m_instance = new TaskManager();
return m_instance;
}
// Singleton destruction
void TaskManager::destroy()
{
if (m_instance)
{
delete m_instance;
m_instance = nullptr;
}
}
// Default constructor
TaskManager::TaskManager() :
m_maxTask(5)
{
m_instance = (TaskManager*)this; // Used to avoid recursive call when the ctor call himself...
// connect himself to the delete task signal
onDeleteTask.connect(this, &TaskManager::deleteTask, EvtHandler::CONNECTION_ASYNCH);
onFinalizeTask.connect(this, &TaskManager::finalizeTask, EvtHandler::CONNECTION_ASYNCH);
}
// Destructor
TaskManager::~TaskManager()
{
m_mutex.lock();
// don't wait for any events, so disconnect from all
disconnect();
// delete pending task (we don't want they occur)
for (IT_TaskList it = m_pendingTasksList.begin(); it != m_pendingTasksList.end(); ++it)
{
deletePtr(*it);
}
m_pendingTasksList.clear();
// wait for the end of any running task
for (IT_TaskList it = m_runningTasksList.begin(); it != m_runningTasksList.end(); ++it)
{
(*it)->waitFinish();
// and finally delete it directly
deletePtr(*it);
}
m_runningTasksList.clear();
m_mutex.unlock();
}
// Add a task to process. A new task is started if tasks slots are available
void TaskManager::addTask(Task *task)
{
O3D_ASSERT(task);
if (!task) {
return;
} else {
RecurMutexLocker locker(m_mutex);
// to start the next pending task at finish, for finalize and next for auto deletion
task->onTaskFinished.connect(this, &TaskManager::taskFinished, EvtHandler::CONNECTION_ASYNCH);
// or when the task execution failed, call for its auto deletion without finalize
task->onTaskFailed.connect(this, &TaskManager::taskFailed, EvtHandler::CONNECTION_ASYNCH);
// process immediately by this thread
if (m_maxTask == 0) {
m_runningTasksList.push_back(task);
// process the task
task->start(False);
} else {
// empty slot ?
if (m_runningTasksList.size() < m_maxTask) {
m_runningTasksList.push_back(task);
// and start it
task->start(True);
} else {
// pending queue
m_pendingTasksList.push_back(task);
}
}
}
}
// Define the number of maximum simultaneous running tasks.
void TaskManager::setNumMaxTasks(UInt32 max)
{
RecurMutexLocker locker(m_mutex);
m_maxTask = max;
// start many others tasks as possible
while ((m_runningTasksList.size() < m_maxTask) && !m_pendingTasksList.empty()) {
Task *task = m_pendingTasksList.front();
m_pendingTasksList.pop_front();
m_runningTasksList.push_back(task);
// and start it
task->start(True);
}
}
// Get the current number of running tasks.
UInt32 TaskManager::getNumRunningTasks() const
{
RecurMutexLocker locker(const_cast<RecursiveMutex&>(m_mutex));
Int32 size = m_runningTasksList.size();
return size;
}
// Kills any running tasks.
void TaskManager::kill()
{
RecurMutexLocker locker(m_mutex);
for (IT_TaskList it = m_runningTasksList.begin(); it != m_runningTasksList.end(); ++it)
{
(*it)->kill();
deletePtr(*it);
}
m_runningTasksList.clear();
for (IT_TaskList it = m_pendingTasksList.begin(); it != m_pendingTasksList.end(); ++it)
{
deletePtr(*it);
}
m_pendingTasksList.clear();
}
// When a task execution is not a success it call for its deletion.
void TaskManager::taskFailed(Task* task)
{
O3D_ASSERT(task);
RecurMutexLocker locker(m_mutex);
if (task) {
IT_TaskList it = std::find(m_runningTasksList.begin(), m_runningTasksList.end(), task);
if (it != m_runningTasksList.end()) {
m_runningTasksList.erase(it);
onDeleteTask(task);
} else {
O3D_ERROR(E_InvalidParameter("Unknown running task"));
}
}
// start a new task if necessary
if (m_runningTasksList.size() < m_maxTask) {
if (!m_pendingTasksList.empty()) {
Task *task = m_pendingTasksList.front();
m_pendingTasksList.pop_front();
m_runningTasksList.push_back(task);
// and start it
task->start(True);
}
}
}
// When a task is finished to process it call for its finalize.
void TaskManager::taskFinished(Task* task)
{
O3D_ASSERT(task);
if (task) {
onFinalizeTask(task);
}
}
// When a task is finalized it call for its deletion.
void TaskManager::finalizeTask(Task* task)
{
O3D_ASSERT(task);
if (task) {
// finalize
task->synchronize();
RecurMutexLocker locker(m_mutex);
IT_TaskList it = std::find(m_runningTasksList.begin(), m_runningTasksList.end(), task);
if (it != m_runningTasksList.end()) {
m_runningTasksList.erase(it);
onDeleteTask(task);
} else {
O3D_ERROR(E_InvalidParameter("Unknown running task"));
}
}
// start a new task if necessary
if (m_runningTasksList.size() < m_maxTask) {
if (!m_pendingTasksList.empty()) {
Task *task = m_pendingTasksList.front();
m_pendingTasksList.pop_front();
m_runningTasksList.push_back(task);
// and start it
task->start(True);
}
}
}
// When delete a task.
void TaskManager::deleteTask(Task* task)
{
O3D_ASSERT(task);
if (task) {
o3d::deletePtr(task);
}
}
| 23.330645 | 102 | 0.674732 |
7c624d369f6c94c89b1b5af5419e758b6c894c1c | 4,325 | cpp | C++ | alert_db/src/get_images_from_bag.cpp | robotics-upo/siar_remote_packages | 09bbbc88fb656524cc523a95704e7d353e260876 | [
"MIT"
] | null | null | null | alert_db/src/get_images_from_bag.cpp | robotics-upo/siar_remote_packages | 09bbbc88fb656524cc523a95704e7d353e260876 | [
"MIT"
] | null | null | null | alert_db/src/get_images_from_bag.cpp | robotics-upo/siar_remote_packages | 09bbbc88fb656524cc523a95704e7d353e260876 | [
"MIT"
] | 1 | 2020-01-10T07:39:33.000Z | 2020-01-10T07:39:33.000Z | #include <rosbag/bag.h>
#include <rosbag/view.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <cv.h>
#include <boost/foreach.hpp>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
// #include <compressed_image_transport/codec.h>
#include <compressed_depth_image_transport/codec.h>
#include <compressed_depth_image_transport/compression_common.h>
#include "ros/ros.h"
#include <limits>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iomanip> // std::setfill, std::setwidth
#include <functions/functions.h>
using namespace std;
namespace enc = sensor_msgs::image_encodings;
using namespace cv;
double max_range = 10.0;
int main(int argc, char **argv)
{
rosbag::Bag bag;
std::string camera("/up");
if (argc < 3) {
cerr << "Usage: " << argv[0] << " <bag file> <input_file> [<skip first n images = 0>] \n";
return -1;
}
int ignore = -1;
if (argc > 3) {
ignore = atoi(argv[3]);
cout << "Ignoring ids with less than: " << ignore << endl;
}
std::string filename(argv[2]);
std::string bag_file(argv[1]);
std::vector<std::vector <double> > M;
functions::getMatrixFromFile(filename, M);
map<string, int> count_map;
try {
bag.open(string(argv[1]), rosbag::bagmode::Read);
std::vector<std::string> topics;
topics.push_back("/front/rgb/image_raw/compressed");
topics.push_back("/front_right/rgb/image_raw/compressed");
topics.push_back("/front_left/rgb/image_raw/compressed");
topics.push_back("/back/rgb/image_raw/compressed");
topics.push_back("/back_right/rgb/image_raw/compressed");
topics.push_back("/back_left/rgb/image_raw/compressed");
rosbag::View view(bag, rosbag::TopicQuery(topics));
bool initialized = false;
bool _positive = false;
bool ignoring = true;
unsigned int last_defect = 0;
unsigned long curr_msg = 0;
unsigned long view_size = view.size();
foreach(rosbag::MessageInstance const m, view)
{
sensor_msgs::CompressedImage::Ptr im = m.instantiate<sensor_msgs::CompressedImage>();
ROS_INFO("%d%%", (int) ((float)curr_msg/view_size*100.0));
printf("\033[1A"); // Move up X lines;
curr_msg++;
if (im != NULL) {
ros::Time t = im->header.stamp;
for (unsigned int i = last_defect; i < M.size(); i++) {
ros::Time t1(M[i][0], M[i][1]);
ros::Time t2(M[i][2], M[i][3]);
// if (t1 < t) {
// ROS_INFO("T1 < T");
//
// }
// if (t < t2) {
// ROS_INFO("T < T2");
// }
// if (t1.sec < t2.sec) {
// ROS_INFO("T1 < T2");
// }
if (t1 <= t && t2 >= t) {
ROS_INFO("Time: %f", t.toSec());
if (i != last_defect) {
count_map.clear();
last_defect = i;
ROS_INFO("Detected new defect. Number: %u", last_defect);
}
if ( count_map.find(m.getTopic()) == count_map.end() ) {
count_map[m.getTopic()] = 1;
} else {
count_map[m.getTopic()]++;
}
ostringstream filename_;
// filename_
filename_ << "defect_" << i << m.getTopic() << "_" << std::setfill ('0') << std::setw (4) << count_map[m.getTopic()] <<".jpg";
string s = filename_.str();
replace(s.begin(), s.end(), '/', '_');
Mat decompressed;
try
{
// Decode image data
decompressed = cv::imdecode(im->data, CV_LOAD_IMAGE_UNCHANGED);
if (m.getTopic() == topics[2] || m.getTopic() == topics[4]) {
// Front left and Back right should be flip
flip(decompressed, decompressed, -1);
}
if (imwrite (s, decompressed)) {
ROS_INFO("Exported file: %s", s.c_str());
} else {
ROS_ERROR("Could not export file: %s", s.c_str());
}
} catch (exception &e) {
}
}
}
}
}
bag.close();
} catch (exception &e) {
cerr << "Exception while manipulating the bag " << argv[1] << endl;
cerr << "Content " << e.what() << endl;
return -2;
}
printf("\n");
return 0;
}
| 26.863354 | 131 | 0.593988 |
7c663a8084f25481450e8d5dafdfba19424140e8 | 883 | cpp | C++ | lib/bencode/BInteger.cpp | ss16118/torrent-client-cpp | fdc6b37d45ba6c8e798216fd874523fac3eceeed | [
"MIT"
] | 24 | 2021-06-21T10:24:35.000Z | 2022-03-21T07:00:36.000Z | lib/bencode/BInteger.cpp | BaiXious/torrent-client-cpp | fdc6b37d45ba6c8e798216fd874523fac3eceeed | [
"MIT"
] | 2 | 2016-07-24T15:34:48.000Z | 2018-04-21T13:33:33.000Z | lib/bencode/BInteger.cpp | BaiXious/torrent-client-cpp | fdc6b37d45ba6c8e798216fd874523fac3eceeed | [
"MIT"
] | 10 | 2016-03-25T05:53:12.000Z | 2022-02-06T01:28:10.000Z | /**
* @file BInteger.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Implementation of the BInteger class.
*/
#include "BInteger.h"
#include "BItemVisitor.h"
namespace bencoding {
/**
* @brief Constructs the integer with the given @a value.
*/
BInteger::BInteger(ValueType value): _value(value) {}
/**
* @brief Creates and returns a new integer.
*/
std::unique_ptr<BInteger> BInteger::create(ValueType value) {
return std::unique_ptr<BInteger>(new BInteger(value));
}
/**
* @brief Returns the integer's value.
*/
auto BInteger::value() const -> ValueType {
return _value;
}
/**
* @brief Sets a new value.
*/
void BInteger::setValue(ValueType value) {
_value = value;
}
void BInteger::accept(BItemVisitor *visitor) {
visitor->visit(this);
}
} // namespace bencoding
| 19.622222 | 71 | 0.697622 |
7c6a02ae781b48453f543d541aa3efa1524e8e21 | 4,048 | cpp | C++ | UVA Online Judge/628_Passwords.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | 2 | 2020-09-10T15:48:02.000Z | 2020-09-12T00:05:35.000Z | UVA Online Judge/628_Passwords.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | null | null | null | UVA Online Judge/628_Passwords.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | 2 | 2020-09-09T17:01:05.000Z | 2020-09-09T17:02:27.000Z | /*Criado por Davi Augusto - BCC - UNESP Bauru*/
/*
Resolvido com Backtracking:
1 - "Escolhas"
2 - "Restrições"
3 - "Objetivo"
Escolhas: Colocar dígitos de 0 a 9 na senha com base nas "regras" (# e 0)
Restrições: Regras e o dígito (ex: #0). O '#' ficará a palavra e o dígito '0' os números de 0 a 9. Printar crescente.
Objetivos: Mostrar todo o conjunto de senha com as regras dadas
Critério de parada: dígito alcançar 9 (i <= 9); forem todas as palavras do vetor;
todos dígitos disponíveis
Padrão:
1) Ir até o final da regra;
2) Ver qual campo é:
-> Se for '#', mostrar a palavra atual
-> Se for '0', mostrar dígitos de 0 a 9; CONTUDO...
3) Necessário mostrar crescente...
Ciclo até fim do vector de palavras
*/
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
//Função para Mostrar todas as Palavras
void mostraPalavras(vector<string> dicio, vector<string> auxfinal){
for(int i = 0; i < dicio.size(); i++){
for(int j = 0; j < auxfinal.size(); j++){
cout << auxfinal[j];
}
cout << dicio[i] << endl;
}
}
//Função para Mostrar todos os Dígitos (0 a 9)
void mostraDigitos(vector<string> auxfinal){
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j < auxfinal.size(); j++)
{
cout << auxfinal[j];
}
cout << i << endl;
}
}
//Backtracking
void resolveSenha(vector<string> dicio, string regra,
int caracRegra, vector<string> auxfinal)
{
//Caso chegue no último, analisar
if(caracRegra == (regra.length()-1)){
//Verificar o caractere correspondente e printar
//Dígito
if (regra[caracRegra] == '0'){
mostraDigitos(auxfinal);
}
else if (regra[caracRegra] == '#'){ //Palavra
mostraPalavras(dicio, auxfinal);
}
return;
}
//Dígito
if(regra[caracRegra] == '0'){
for(int i = 0; i <= 9; i++){
//Copiar o dígito pra auxiliar
auxfinal.push_back(to_string(i));
//Executando a função novamente e avançando o dígito da regra
resolveSenha(dicio, regra, caracRegra + 1, auxfinal);
//Removendo o Último Elemento da Auxiliar
auxfinal.pop_back();
}
}
else if(regra[caracRegra] == '#'){ //Palavra
for(int j = 0; j < dicio.size(); j++){
//Copiar a palavra pra auxiliar
auxfinal.push_back(dicio[j]);
//Executando a função novamente e avançando o dígito da regra
resolveSenha(dicio, regra, caracRegra + 1, auxfinal);
//Removendo o Último Elemento da Auxiliar
auxfinal.pop_back();
}
}
}
int main(){
int numpalavras, numregras;
while(cin >> numpalavras){
//Vector contendo Dicionário
vector<string> dicionario;
dicionario.clear();
string dicioaux;
//Lendo cada palavra
for(int i = 0; i < numpalavras; i++){
cin >> dicioaux;
dicionario.push_back(dicioaux);
}
//Lendo Qtd de Regras
cin >> numregras;
//Vector contendo as regras
vector<string> regras;
regras.clear();
string regraux;
//Lendo cada regra
for(int i = 0; i < numregras; i++){
cin >> regraux;
regras.push_back(regraux);
}
//Mostrando resultado (Backtracking)
cout << "--" << endl;
//Passar cada regra
vector<string> auxfinal;
for(int i = 0; i < numregras; i++){
auxfinal.clear();
resolveSenha(dicionario, regras[i], 0, auxfinal);
}
}
return 0;
} | 28.70922 | 118 | 0.516304 |
7c6a4d9e5140b66d9f8a1a9d1f899b93076511af | 10,895 | cpp | C++ | Main/Libraries/Hunspell/HunspellExportFunctions.cpp | paulushub/SandAssists | ccd86a074e85b3588819253f241780fe9d9362e2 | [
"MS-PL"
] | 1 | 2018-12-13T19:41:01.000Z | 2018-12-13T19:41:01.000Z | Main/Libraries/Hunspell/HunspellExportFunctions.cpp | paulushub/SandAssists | ccd86a074e85b3588819253f241780fe9d9362e2 | [
"MS-PL"
] | null | null | null | Main/Libraries/Hunspell/HunspellExportFunctions.cpp | paulushub/SandAssists | ccd86a074e85b3588819253f241780fe9d9362e2 | [
"MS-PL"
] | null | null | null | #include "hunspell/hunspell.hxx"
#include <windows.h>
#include <locale.h>
#include <mbctype.h>
#include "NHunspellExtensions.h"
#include "EncodingToCodePage.h"
#define DLLEXPORT extern "C" __declspec( dllexport )
class NHunspell: public Hunspell
{
// The methods aren't multi threaded, reentrant or whatever so a encapsulated buffer can be used for performance reasons
void * marshalBuffer;
size_t marshalBufferSize;
void * wordBuffer;
size_t wordBufferSize;
void * word2Buffer;
size_t word2BufferSize;
void * affixBuffer;
size_t affixBufferSize;
public:
UINT CodePage;
inline NHunspell(const char *affpath, const char *dpath, const char * key = 0) : Hunspell(affpath,dpath,key)
{
marshalBuffer = 0;
marshalBufferSize = 0;
wordBuffer = 0;
wordBufferSize = 0;
word2Buffer = 0;
word2BufferSize = 0;
affixBuffer = 0;
affixBufferSize = 0;
char * encoding = get_dic_encoding();
CodePage = EncodingToCodePage( encoding );
}
inline ~NHunspell()
{
if( marshalBuffer != 0 )
free( marshalBuffer );
if( wordBuffer != 0 )
free( wordBuffer );
if( word2Buffer != 0 )
free( word2Buffer );
if( affixBuffer != 0 )
free( affixBuffer );
}
// Buffer for marshaling string lists back to .NET
void * GetMarshalBuffer(size_t size)
{
if(size < marshalBufferSize )
return marshalBuffer;
if( marshalBufferSize == 0 )
{
size += 128;
marshalBuffer = malloc( size );
}
else
{
size += 256;
marshalBuffer = realloc(marshalBuffer, size );
}
marshalBufferSize = size;
return marshalBuffer;
}
// Buffer for the mutibyte representation of a word
void * GetWordBuffer(size_t size)
{
if(size < wordBufferSize )
return wordBuffer;
if( wordBufferSize == 0 )
{
size += 32;
wordBuffer = malloc( size );
}
else
{
size += 64;
wordBuffer = realloc(wordBuffer, size );
}
wordBufferSize = size;
return wordBuffer;
}
// Buffer for the mutibyte representation of a word
void * GetWord2Buffer(size_t size)
{
if(size < word2BufferSize )
return word2Buffer;
if( word2BufferSize == 0 )
{
size += 32;
word2Buffer = malloc( size );
}
else
{
size += 64;
word2Buffer = realloc(wordBuffer, size );
}
word2BufferSize = size;
return word2Buffer;
}
inline char * GetWordBuffer( wchar_t * unicodeString )
{
int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0);
char * buffer = (char *) GetWordBuffer( buffersize );
WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0);
return buffer;
}
inline char * GetWord2Buffer( wchar_t * unicodeString )
{
int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0);
char * buffer = (char *) GetWord2Buffer( buffersize );
WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0);
return buffer;
}
// Buffer for the mutibyte representation of an affix
void * GetAffixBuffer(size_t size)
{
if(size < affixBufferSize )
return affixBuffer;
if( affixBufferSize == 0 )
{
size += 32;
affixBuffer = malloc( size );
}
else
{
size += 64;
affixBuffer = realloc(affixBuffer, size );
}
affixBufferSize = size;
return affixBuffer;
}
inline char * GetAffixBuffer( wchar_t * unicodeString )
{
int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0);
char * buffer = (char *) GetAffixBuffer( buffersize );
WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0);
return buffer;
}
};
inline char * AllocMultiByteBuffer( wchar_t * unicodeString )
{
int buffersize = WideCharToMultiByte(CP_UTF8,0,unicodeString,-1,0,0,0,0);
char * buffer = (char *) malloc( buffersize );
WideCharToMultiByte(CP_UTF8,0,unicodeString,-1,buffer,buffersize,0,0);
return buffer;
}
/************************* Export Functions **************************************************************/
DLLEXPORT NHunspell * HunspellInit(void * affixBuffer, size_t affixBufferSize, void * dictionaryBuffer, size_t dictionaryBufferSize, wchar_t * key)
{
char * key_buffer = 0;
if( key != 0 )
key_buffer = AllocMultiByteBuffer(key);
MemoryBufferInformation affixBufferInfo;
affixBufferInfo.magic = magicConstant;
affixBufferInfo.buffer = affixBuffer;
affixBufferInfo.bufferSize = affixBufferSize;
MemoryBufferInformation dictionaryBufferInfo;
dictionaryBufferInfo.magic = magicConstant;
dictionaryBufferInfo.buffer = dictionaryBuffer;
dictionaryBufferInfo.bufferSize = dictionaryBufferSize;
NHunspell * result = new NHunspell((const char *) &affixBufferInfo, (const char *) &dictionaryBufferInfo,key_buffer);
if( key_buffer != 0 )
free( key_buffer );
return result;
}
DLLEXPORT void HunspellFree(NHunspell * handle )
{
delete handle;
}
DLLEXPORT bool HunspellAdd(NHunspell * handle, wchar_t * word )
{
char * word_buffer = handle->GetWordBuffer(word);
int success = handle->add(word_buffer);
return success != 0;
}
DLLEXPORT bool HunspellAddWithAffix(NHunspell * handle, wchar_t * word, wchar_t * example )
{
char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word);
char * example_buffer = ((NHunspell *) handle)->GetWord2Buffer(example);
bool success = handle->add_with_affix(word_buffer,example_buffer) != 0;
return success;
}
DLLEXPORT bool HunspellSpell(NHunspell * handle, wchar_t * word )
{
char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word);
bool correct = ((NHunspell *) handle)->spell(word_buffer) != 0;
return correct;
}
DLLEXPORT void * HunspellSuggest(NHunspell * handle, wchar_t * word )
{
char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word);
char ** wordList;
int wordCount = ((NHunspell *) handle)->suggest(&wordList, word_buffer);
// Cacculation of the Marshalling Buffer.
// Layout: {Pointers- zero terminated}{Wide Strings - zero terminated}
size_t bufferSize = (wordCount + 1) * sizeof (wchar_t **);
for( int i = 0; i < wordCount; ++ i )
bufferSize += MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,0,0) * sizeof( wchar_t);
BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize );
wchar_t ** pointer = (wchar_t ** ) marshalBuffer;
wchar_t * buffer = (wchar_t * ) (marshalBuffer + (wordCount + 1) * sizeof (wchar_t **));
for( int i = 0; i < wordCount; ++ i )
{
*pointer = buffer;
size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,0,0);
MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,buffer,wcsSize);
// Prepare pointers for the next string
buffer += wcsSize;
++pointer;
}
// Zero terminate the pointer list
*pointer = 0;
((NHunspell *) handle)->free_list(&wordList, wordCount);
return marshalBuffer;
}
DLLEXPORT void * HunspellAnalyze(NHunspell * handle, wchar_t * word )
{
char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word);
char ** morphList;
int morphCount = ((NHunspell *) handle)->analyze(&morphList, word_buffer);
// Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated}
size_t bufferSize = (morphCount + 1) * sizeof (wchar_t **);
for( int i = 0; i < morphCount; ++ i )
bufferSize += MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,0,0) * sizeof( wchar_t);
BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize );
wchar_t ** pointer = (wchar_t ** ) marshalBuffer;
wchar_t * buffer = (wchar_t * ) (marshalBuffer + (morphCount + 1) * sizeof (wchar_t **));
for( int i = 0; i < morphCount; ++ i )
{
*pointer = buffer;
size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,0,0);
MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,buffer,wcsSize);
// Prepare pointers for the next string
buffer += wcsSize;
++pointer;
}
// Zero terminate the pointer list
*pointer = 0;
((NHunspell *) handle)->free_list(&morphList, morphCount);
return marshalBuffer;
}
DLLEXPORT void * HunspellStem(NHunspell * handle, wchar_t * word )
{
char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word);
char ** stemList;
int stemCount = ((NHunspell *) handle)->stem(&stemList, word_buffer);
// Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated}
size_t bufferSize = (stemCount + 1) * sizeof (wchar_t **);
for( int i = 0; i < stemCount; ++ i )
bufferSize += MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0) * sizeof( wchar_t);
BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize );
wchar_t ** pointer = (wchar_t ** ) marshalBuffer;
wchar_t * buffer = (wchar_t * ) (marshalBuffer + (stemCount + 1) * sizeof (wchar_t **));
for( int i = 0; i < stemCount; ++ i )
{
*pointer = buffer;
size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0);
MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,buffer,wcsSize);
// Prepare pointers for the next string
buffer += wcsSize;
++pointer;
}
// Zero terminate the pointer list
*pointer = 0;
((NHunspell *) handle)->free_list(&stemList, stemCount);
return marshalBuffer;
}
DLLEXPORT void * HunspellGenerate(NHunspell * handle, wchar_t * word, wchar_t * word2 )
{
char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word);
char * word2_buffer = ((NHunspell *) handle)->GetWord2Buffer(word2);
char ** stemList;
int stemCount = ((NHunspell *) handle)->generate(&stemList, word_buffer, word2_buffer);
// Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated}
size_t bufferSize = (stemCount + 1) * sizeof (wchar_t **);
for( int i = 0; i < stemCount; ++ i )
bufferSize += MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0) * sizeof( wchar_t);
BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize );
wchar_t ** pointer = (wchar_t ** ) marshalBuffer;
wchar_t * buffer = (wchar_t * ) (marshalBuffer + (stemCount + 1) * sizeof (wchar_t **));
for( int i = 0; i < stemCount; ++ i )
{
*pointer = buffer;
size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0);
MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,buffer,wcsSize);
// Prepare pointers for the next string
buffer += wcsSize;
++pointer;
}
// Zero terminate the pointer list
*pointer = 0;
((NHunspell *) handle)->free_list(&stemList, stemCount);
return marshalBuffer;
}
| 27.935897 | 148 | 0.663148 |
7c711c4ad895523c204c97b8febc668039d2a0b6 | 5,108 | cpp | C++ | snowman.cpp | Jewgah/Snowman-B | 58a67861bccdebdf2447ad3f5bd838dc65456791 | [
"MIT"
] | null | null | null | snowman.cpp | Jewgah/Snowman-B | 58a67861bccdebdf2447ad3f5bd838dc65456791 | [
"MIT"
] | null | null | null | snowman.cpp | Jewgah/Snowman-B | 58a67861bccdebdf2447ad3f5bd838dc65456791 | [
"MIT"
] | null | null | null | /**
* This file defines the "ariel" namespace for the assignment.
* the namespace contains a single function which returns a String representing a modular snowman print.
* each different input ([1-4], LENGTHgth = 8) returns a different snowman.
* each input of 8 numbers in [1-4] represents a sequence of compenents: HNLRXYTB
* (H = Hat, N = Nose, L = Left Eye, R = Right Eye, X = Left Arm, Y = Right Arm, T = Torso, B = TEN).
* Building the desired snowman is creating a string by the template:
* HHHHH
* HHHHH = H for Hat.
* X(LNR)Y = X for upper-left Arm, L for Left Eye, N for Nose, R for Right Eye, Y for upper-left Arm.
* X(TTT)Y = X for lower-right Arm, T for Torso, Y for lower-right Arm.
* (BBB) = B for TEN.
*
* For more information please visit: https://codegolf.stackexchange.com/questions/49671/do-you-want-to-code-a-snowman .
* */
/*
* To get the grade:
* dos2unix grade
* dos2unix grade_utils
* bash grade
*/
#include "snowman.hpp"
#include <array>
#include <string>
#include <exception>
#include <iostream> // added iostrem for the cout method in the main
using namespace std;
//TO DO: check the tidy warnings and fix them
namespace ariel
{
string snowman(int input)
{
// if input<11111111 or input>44444444 input not valid
if (input < MIN || input > MAX)
{
__throw_invalid_argument("Error! Not a valid input");
}
else
{
int *arr = new int[LENGTH];
//if input is between 11111111 and 44444444 we now have to check if each digit is between 1 and 4
for (int i = 0; i < LENGTH; i++)
{
if (input % TEN > MAX_DIGIT || input % TEN < MIN_DIGIT)
{
__throw_invalid_argument("Error! Not a valid input");
}
arr[FINAL_INDEX - i] = input % TEN;
input /= TEN;
}
//Creating strings arrays for easy access to each component needed in each scenario.
//hat[0] == straw hat, hat[1] == Mexican Hat, hat[2] == Fez, hat[3] == Russian Hat
const array<string, MAX_DIGIT> hat = {"_===_\n", " ___ \n .....\n", " _ \n /_\\ \n", " ___ \n (_*_)\n"};
//nose[0] == Normal, nose[1] == Dot, nose[2] == Line, nose[3] == None
const array<string, MAX_DIGIT> nose = {",", ".", "_", " "};
//lEye[0] == Dot, lEye[1] == Bigger Dot, lEye[2] == Biggest Dot, lEye[3] == Closed
const array<string, MAX_DIGIT> lEye = {".", "o", "O", "-"};
//rEye[0] == Dot, rEye[1] == Bigger Dot, rEye[2] == Biggest Dot, rEye[3] == Closed
const array<string, MAX_DIGIT> rEye = {".", "o", "O", "-"};
//highLA[0] == Normal Arm, highLA[1] == Upwards Arm, highLA[2] Downwards Arm, highLA[3] == None
const array<string, MAX_DIGIT> highLA = {" ", "\\", " ", " "};
//lowLA[0] == Normal Arm, lowLA[1] == Upwards Arm, lowLA[2] Downwards Arm, lowLA[3] == None
const array<string, MAX_DIGIT> lowLA = {"<", " ", "/", " "};
//highRA[0] == Normal Arm, highRA[1] == Upwards Arm, highRA[2] Downwards Arm, highRA[3] == None
const array<string, MAX_DIGIT> highRA = {" ","/", " ", " "};
//lowRA[0] == Normal Arm, lowRA[1] == Upwards Arm, lowRA[2] Downwards Arm, lowRA[3] == None
const array<string, MAX_DIGIT> lowRA = {">", " ", "\\", " "};
//torso[0] == Buttons, torso[1] == vest, torso[2] == Inwards Arms, torso[3] == None
const array<string, MAX_DIGIT> torso = {" : ", "] [", "> <", " "};
//base[0] == Buttons, base[1] == feet, Tbase[2] == Flat, base[3] == None
const array<string, MAX_DIGIT> base = {" : ", "\" \"", "___", " "};
//Building our Snowman:
string getHat = " " + hat[arr[FIRST_DIGIT_INPUT]-1];
string getHighLeftArm = highLA[arr[FIFTH_DIGIT_INPUT]-1];
string getLeftEye = "(" + lEye[arr[THIRD_DIGIT_INPUT]-1];
string getNose = nose[arr[SECOND_DIGIT_INPUT]-1];
string getRightEye = rEye[arr[FOURTH_DIGIT_INPUT]-1] + ")";
string getHighRightArm = highRA[arr[SIXTH_DIGIT_INPUT]-1] + "\n";
string getLowLeftArm = lowLA[arr[FIFTH_DIGIT_INPUT]-1] + "(";
string getTorso = torso[arr[SEVENTH_DIGIT_INPUT]-1] + ")";
string getLowRightArm = lowRA[arr[SIXTH_DIGIT_INPUT]-1] + "\n (";
string getBase = base[arr[EIGHTH_DIGIT_INPUT]-1] + ")";
string ans = getHat+getHighLeftArm+getLeftEye+getNose+getRightEye+getHighRightArm+getLowLeftArm+getTorso+getLowRightArm+getBase;
return ans;
}
}
}
// To run this main we need to only compile snowman.cpp by uncommenting the following main and by using the following commands:
// clang++-9 -std=c++2a snowman.cpp then ./a.out
// Because there is a conflict with the main in Demo.cpp and TestCounter.cpp
// int main()
// {
// std::cout << ariel::snowman(41322121) << endl;
// }
| 43.65812 | 140 | 0.563626 |
7c7271cd1bc6633e31eff5ad8cfbeb76ab576099 | 11,886 | hpp | C++ | libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | 1 | 2021-08-16T12:44:43.000Z | 2021-08-16T12:44:43.000Z | libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | null | null | null | libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | 2 | 2021-08-16T12:44:46.000Z | 2021-12-31T17:09:45.000Z | #pragma once
#include <deip/protocol/base.hpp>
#include <deip/protocol/block_header.hpp>
#include <deip/protocol/asset.hpp>
#include <deip/protocol/eci_diff.hpp>
#include <fc/utf8.hpp>
namespace deip {
namespace protocol {
struct fill_common_tokens_withdraw_operation : public virtual_operation
{
fill_common_tokens_withdraw_operation() {}
fill_common_tokens_withdraw_operation(const string& f, const string& t, const share_type& w, const share_type& d, const bool tr)
: from_account(f)
, to_account(t)
, withdrawn(w)
, deposited(d)
, transfer(tr)
{
}
account_name_type from_account;
account_name_type to_account;
share_type withdrawn;
share_type deposited;
bool transfer;
};
struct shutdown_witness_operation : public virtual_operation
{
shutdown_witness_operation() {}
shutdown_witness_operation(const string& o)
: owner(o)
{
}
account_name_type owner;
};
struct hardfork_operation : public virtual_operation
{
hardfork_operation() {}
hardfork_operation(uint32_t hf_id)
: hardfork_id(hf_id)
{
}
uint32_t hardfork_id = 0;
};
struct producer_reward_operation : public virtual_operation
{
producer_reward_operation() {}
producer_reward_operation(const string& p, const share_type c)
: producer(p)
, common_tokens_amount(c)
{
}
account_name_type producer;
share_type common_tokens_amount;
};
struct token_sale_contribution_to_history_operation : public virtual_operation
{
token_sale_contribution_to_history_operation() {}
token_sale_contribution_to_history_operation(const int64_t& research_id,
const external_id_type& research_external_id,
const int64_t& research_token_sale_id,
const external_id_type& research_token_sale_external_id,
const string& contributor,
const asset& amount)
: research_id(research_id)
, research_external_id(research_external_id)
, research_token_sale_id(research_token_sale_id)
, research_token_sale_external_id(research_token_sale_external_id)
, contributor(contributor)
, amount(amount)
{
}
int64_t research_id;
external_id_type research_external_id;
int64_t research_token_sale_id;
external_id_type research_token_sale_external_id;
account_name_type contributor;
asset amount;
};
struct research_content_reference_history_operation : public virtual_operation
{
research_content_reference_history_operation() {}
research_content_reference_history_operation(const int64_t& research_content_id,
const external_id_type& research_content_external_id,
const int64_t& research_id,
const external_id_type& research_external_id,
const std::string& content,
const int64_t& research_content_reference_id,
const external_id_type& research_content_reference_external_id,
const int64_t& research_reference_id,
const external_id_type& research_reference_external_id,
const std::string& content_reference)
: research_content_id(research_content_id)
, research_content_external_id(research_content_external_id)
, research_id(research_id)
, research_external_id(research_external_id)
, content(content)
, research_content_reference_id(research_content_reference_id)
, research_content_reference_external_id(research_content_reference_external_id)
, research_reference_id(research_reference_id)
, research_reference_external_id(research_reference_external_id)
, content_reference(content_reference)
{
}
int64_t research_content_id;
external_id_type research_content_external_id;
int64_t research_id;
external_id_type research_external_id;
std::string content;
int64_t research_content_reference_id;
external_id_type research_content_reference_external_id;
int64_t research_reference_id;
external_id_type research_reference_external_id;
std::string content_reference;
};
struct research_content_eci_history_operation : public virtual_operation
{
research_content_eci_history_operation() {}
research_content_eci_history_operation(const int64_t& research_content_id,
const int64_t& discipline_id,
const eci_diff& diff)
: research_content_id(research_content_id)
, discipline_id(discipline_id)
, diff(diff)
{
}
int64_t research_content_id;
int64_t discipline_id;
eci_diff diff;
};
struct research_eci_history_operation : public virtual_operation
{
research_eci_history_operation() {}
research_eci_history_operation(const int64_t& research_id,
const int64_t& discipline_id,
const eci_diff& diff)
: research_id(research_id)
, discipline_id(discipline_id)
, diff(diff)
{
}
int64_t research_id;
int64_t discipline_id;
eci_diff diff;
};
struct account_eci_history_operation : public virtual_operation
{
account_eci_history_operation() {}
account_eci_history_operation(const account_name_type& account,
const int64_t& discipline_id,
const uint16_t& recipient_type,
const eci_diff& diff)
: account(account)
, discipline_id(discipline_id)
, recipient_type(recipient_type)
, diff(diff)
{
}
account_name_type account;
int64_t discipline_id;
uint16_t recipient_type;
eci_diff diff;
};
struct disciplines_eci_history_operation : public virtual_operation
{
disciplines_eci_history_operation(){}
disciplines_eci_history_operation(const flat_map<int64_t, vector<eci_diff>>& contributions_map, const fc::time_point_sec& timestamp)
: timestamp(timestamp)
{
for (const auto& pair : contributions_map)
{
contributions.insert(pair);
}
}
flat_map<int64_t, vector<eci_diff>> contributions;
fc::time_point_sec timestamp;
};
struct account_revenue_income_history_operation : public virtual_operation
{
account_revenue_income_history_operation() {}
account_revenue_income_history_operation(const account_name_type& account,
const asset& security_token,
const asset& revenue,
const fc::time_point_sec& timestamp)
: account(account)
, security_token(security_token)
, revenue(revenue)
, timestamp(timestamp)
{
}
account_name_type account;
asset security_token;
asset revenue;
fc::time_point_sec timestamp;
};
struct proposal_status_changed_operation : public virtual_operation
{
proposal_status_changed_operation()
{
}
proposal_status_changed_operation(const external_id_type& external_id,
const uint8_t& status)
: external_id(external_id)
, status(status)
{
}
external_id_type external_id;
uint8_t status;
};
struct create_genesis_proposal_operation : public virtual_operation
{
create_genesis_proposal_operation()
{
}
create_genesis_proposal_operation(const external_id_type& external_id,
const account_name_type& proposer,
const string& serialized_proposed_transaction,
const time_point_sec& expiration_time,
const time_point_sec& created_at,
const optional<time_point_sec>& review_period,
const flat_set<account_name_type>& available_active_approvals,
const flat_set<account_name_type>& available_owner_approvals,
const flat_set<public_key_type>& available_key_approvals)
: external_id(external_id)
, proposer(proposer)
, serialized_proposed_transaction(serialized_proposed_transaction)
, expiration_time(expiration_time)
, created_at(created_at)
{
if (review_period.valid())
{
review_period_time = *review_period;
}
for (const auto& approver : available_active_approvals)
{
active_approvals.insert(approver);
}
for (const auto& approver : available_owner_approvals)
{
owner_approvals.insert(approver);
}
for (const auto& approver : key_approvals)
{
key_approvals.insert(approver);
}
}
external_id_type external_id;
uint8_t status;
account_name_type proposer;
string serialized_proposed_transaction;
time_point_sec expiration_time;
time_point_sec created_at;
optional<time_point_sec> review_period_time;
flat_set<account_name_type> active_approvals;
flat_set<account_name_type> owner_approvals;
flat_set<public_key_type> key_approvals;
};
struct create_genesis_account_operation : public virtual_operation
{
create_genesis_account_operation() {}
create_genesis_account_operation(const account_name_type& account)
: account(account)
{
}
account_name_type account;
};
}
} // deip::protocol
FC_REFLECT(deip::protocol::fill_common_tokens_withdraw_operation, (from_account)(to_account)(withdrawn)(deposited)(transfer))
FC_REFLECT(deip::protocol::shutdown_witness_operation, (owner))
FC_REFLECT(deip::protocol::hardfork_operation, (hardfork_id))
FC_REFLECT(deip::protocol::producer_reward_operation, (producer)(common_tokens_amount))
FC_REFLECT(deip::protocol::token_sale_contribution_to_history_operation, (research_id)(research_external_id)(research_token_sale_id)(research_token_sale_external_id)(contributor)(amount))
FC_REFLECT(deip::protocol::research_content_reference_history_operation, (research_content_id)(research_content_external_id)(research_id)(research_external_id)(content)(research_content_reference_id)(research_content_reference_external_id)(research_reference_id)(research_reference_external_id)(content_reference))
FC_REFLECT(deip::protocol::research_content_eci_history_operation, (research_content_id)(discipline_id)(diff))
FC_REFLECT(deip::protocol::research_eci_history_operation, (research_id)(discipline_id)(diff))
FC_REFLECT(deip::protocol::account_eci_history_operation, (account)(discipline_id)(recipient_type)(diff))
FC_REFLECT(deip::protocol::disciplines_eci_history_operation, (contributions)(timestamp))
FC_REFLECT(deip::protocol::account_revenue_income_history_operation, (account)(security_token)(revenue)(timestamp))
FC_REFLECT(deip::protocol::proposal_status_changed_operation, (external_id)(status))
FC_REFLECT(deip::protocol::create_genesis_proposal_operation, (external_id)(proposer)(serialized_proposed_transaction)(expiration_time)(created_at)(review_period_time)(active_approvals)(owner_approvals)(key_approvals))
FC_REFLECT(deip::protocol::create_genesis_account_operation, (account)) | 37.377358 | 314 | 0.673481 |
7c7333192b8c9fb7bf453a63ea77769f1c00283e | 128 | hpp | C++ | Blob_Lib/Include/glm/ext/matrix_uint2x4.hpp | antholuo/Blob_Traffic | 5d6acf88044e9abc63c0ff356714179eaa4b75bf | [
"MIT"
] | null | null | null | Blob_Lib/Include/glm/ext/matrix_uint2x4.hpp | antholuo/Blob_Traffic | 5d6acf88044e9abc63c0ff356714179eaa4b75bf | [
"MIT"
] | null | null | null | Blob_Lib/Include/glm/ext/matrix_uint2x4.hpp | antholuo/Blob_Traffic | 5d6acf88044e9abc63c0ff356714179eaa4b75bf | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:dc05769835c1662878111c8555c4d59f668a9a3a8ca31f2cb035da4016f33b2e
size 737
| 32 | 75 | 0.882813 |
7c75c42e66b58e3633067cab6b3d32cf091eb355 | 1,230 | hpp | C++ | Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp | Septus10/Fade-Engine | 285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6 | [
"MIT"
] | null | null | null | Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp | Septus10/Fade-Engine | 285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6 | [
"MIT"
] | null | null | null | Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp | Septus10/Fade-Engine | 285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <Core/CoreApi.hpp>
#include <Core/Containers/UniquePointer.hpp>
#define FADE_MAKE_PIMPL \
private: \
class CImpl; \
__pragma(warning(push)) \
__pragma(warning(disable : 4251)) \
TPimpl<CImpl> m_Impl; \
__pragma(warning(pop))
#define FADE_INIT_PIMPL(ClassName) \
m_Impl(MakeUnique<ClassName::CImpl>())
/* Brief:
* Creates pimpl object using a unique_ptr
*/
template <typename T>
class TPimpl
{
private:
Fade::TUniquePtr<T> m_Ptr;
public:
template <typename... Args>
TPimpl(Args&&... args) :
m_Ptr(std::forward<Args>(args)...)
{ }
// copy ctor & copy assignment
TPimpl(const TPimpl& rhs) = default;
TPimpl& operator=(const TPimpl& rhs) = default;
// move ctor & move assignment
TPimpl(TPimpl&& rhs) = default;
TPimpl& operator=(TPimpl&& rhs) = default;
// pointer operator
T& operator*() { return *m_Ptr; }
const T& operator*() const { return *m_Ptr; }
// arrow operator
T* operator->() { return m_Ptr.Get(); }
const T* operator->() const { return m_Ptr.Get(); }
// get() function
T* get() { return m_Ptr.Get(); }
const T* get() const { return m_Ptr.Get(); }
};
| 23.207547 | 52 | 0.621951 |
7c7b086b8a08cf99e589f533582f1c4b2692f5d6 | 11,108 | hpp | C++ | source/zisc/core/zisc/string/json_value_parser-inl.hpp | byzin/Zisc | c74f50c51f82c847f39a603607d73179004436bb | [
"MIT"
] | 2 | 2017-10-18T13:24:11.000Z | 2018-05-15T00:40:52.000Z | source/zisc/core/zisc/string/json_value_parser-inl.hpp | byzin/Zisc | c74f50c51f82c847f39a603607d73179004436bb | [
"MIT"
] | 9 | 2016-09-05T11:07:03.000Z | 2019-07-05T15:31:04.000Z | source/zisc/core/zisc/string/json_value_parser-inl.hpp | byzin/Zisc | c74f50c51f82c847f39a603607d73179004436bb | [
"MIT"
] | null | null | null | /*!
\file json_value_parser-inl.hpp
\author Sho Ikeda
\brief No brief description
\details
No detailed description.
\copyright
Copyright (c) 2015-2021 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#ifndef ZISC_JSON_VALUE_PARSER_INL_HPP
#define ZISC_JSON_VALUE_PARSER_INL_HPP
#include "json_value_parser.hpp"
// Standard C++ library
#include <cstddef>
#include <cstdlib>
#include <regex>
#include <string_view>
#include <type_traits>
#include <utility>
// Zisc
#include "constant_string.hpp"
#include "zisc/concepts.hpp"
#include "zisc/utility.hpp"
#include "zisc/zisc_config.hpp"
namespace zisc {
/*!
\details No detailed description
\return No description
*/
inline
constexpr auto JsonValueParser::truePattern() noexcept
{
auto pattern = toString(R"(true)");
return pattern;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr auto JsonValueParser::falsePattern() noexcept
{
auto pattern = toString(R"(false)");
return pattern;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr auto JsonValueParser::booleanPattern() noexcept
{
auto pattern = truePattern() + R"(|)" + falsePattern();
return pattern;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr auto JsonValueParser::integerPattern() noexcept
{
auto pattern = toString(R"(-?(?:[1-9][0-9]*|0))");
return pattern;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr auto JsonValueParser::floatPattern() noexcept
{
auto pattern = integerPattern() + R"((?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)";
return pattern;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr auto JsonValueParser::stringPattern() noexcept
{
auto character = toString(R"([^"\\[:cntrl:]])");
auto escaped = toString(R"(\\["\\bfnrt])");
auto pattern = R"("(?:)" + character + R"(|)" + escaped + R"()*")";
return pattern;
}
/*!
\details No detailed description
*/
inline
JsonValueParser::JsonValueParser() noexcept :
int_pattern_{integerPattern().toCStr(), regexInsOptions()},
float_pattern_{floatPattern().toCStr(), regexInsOptions()},
string_pattern_{stringPattern().toCStr(), regexInsOptions()}
{
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
std::size_t JsonValueParser::getCxxStringSize(const std::string_view json_value) noexcept
{
const std::size_t size = toCxxStringImpl(json_value, nullptr);
return size;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr std::regex::flag_type JsonValueParser::regexInsOptions() noexcept
{
constexpr std::regex::flag_type flag = std::regex_constants::nosubs |
std::regex_constants::optimize |
std::regex_constants::ECMAScript;
return flag;
}
/*!
\details No detailed description
\return No description
*/
inline
constexpr std::regex::flag_type JsonValueParser::regexTempOptions() noexcept
{
constexpr std::regex::flag_type flag = std::regex_constants::nosubs |
std::regex_constants::ECMAScript;
return flag;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::toCxxBool(const std::string_view json_value) noexcept
{
constexpr auto true_value = truePattern();
const bool result = true_value == json_value;
return result;
}
/*!
\details No detailed description
\tparam Float No description.
\param [in] json_value No description.
\return No description
*/
template <FloatingPoint Float> inline
Float JsonValueParser::toCxxFloat(const std::string_view json_value) noexcept
{
const Float result = toCxxFloatImpl<Float>(json_value);
return result;
}
/*!
\details No detailed description
\tparam Int No description.
\param [in] json_value No description.
\return No description
*/
template <Integer Int> inline
Int JsonValueParser::toCxxInteger(const std::string_view json_value) noexcept
{
const Int result = toCxxIntegerImpl<Int>(json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\param [out] value No description.
*/
inline
void JsonValueParser::toCxxString(const std::string_view json_value,
char* value) noexcept
{
toCxxStringImpl(json_value, value);
}
// For temporary use
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isBoolValue(const std::string_view json_value) noexcept
{
constexpr auto true_value = truePattern();
constexpr auto false_value = falsePattern();
const bool result = (true_value == json_value) || (false_value == json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isFloatValue(const std::string_view json_value) noexcept
{
const std::regex float_pattern{floatPattern().toCStr(), regexTempOptions()};
const bool result = isValueOf(float_pattern, json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isIntegerValue(const std::string_view json_value) noexcept
{
const std::regex int_pattern{integerPattern().toCStr(), regexTempOptions()};
const bool result = isValueOf(int_pattern, json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isStringValue(const std::string_view json_value) noexcept
{
const std::regex string_pattern{stringPattern().toCStr(), regexTempOptions()};
const bool result = isValueOf(string_pattern, json_value);
return result;
}
// For instance
/*!
\details No detailed description
\return No description
*/
inline
const std::regex& JsonValueParser::floatRegex() const noexcept
{
return float_pattern_;
}
/*!
\details No detailed description
\return No description
*/
inline
const std::regex& JsonValueParser::integerRegex() const noexcept
{
return int_pattern_;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isBool(const std::string_view json_value) const noexcept
{
const bool result = isBoolValue(json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isFloat(const std::string_view json_value) const noexcept
{
const bool result = isValueOf(floatRegex(), json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isInteger(const std::string_view json_value) const noexcept
{
const bool result = isValueOf(integerRegex(), json_value);
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isString(const std::string_view json_value) const noexcept
{
const bool result = isValueOf(stringRegex(), json_value);
return result;
}
/*!
\details No detailed description
\return No description
*/
inline
const std::regex& JsonValueParser::stringRegex() const noexcept
{
return string_pattern_;
}
/*!
\details No detailed description
\param [in] c No description.
\return No description
*/
inline
char JsonValueParser::getEscapedCharacter(const char c) noexcept
{
char result = '\0';
switch (c) {
case '\"':
result = '\"';
break;
case '\\':
result = '\\';
break;
case 'b':
result = '\b';
break;
case 'f':
result = '\f';
break;
case 'n':
result = '\n';
break;
case 'r':
result = '\r';
break;
case 't':
result = '\t';
break;
default:
break;
}
return result;
}
/*!
\details No detailed description
\param [in] pattern No description.
\param [in] json_value No description.
\return No description
*/
inline
bool JsonValueParser::isValueOf(const std::regex& pattern,
const std::string_view json_value) noexcept
{
const bool result = std::regex_match(json_value.begin(),
json_value.end(),
pattern);
return result;
}
/*!
\details No detailed description
\tparam Float No description.
\param [in] json_value No description.
\return No description
*/
template <FloatingPoint Float> inline
Float JsonValueParser::toCxxFloatImpl(const std::string_view json_value) noexcept
{
using FType = std::remove_cv_t<Float>;
Float result;
if constexpr (std::is_same_v<float, FType>)
result = std::strtof(json_value.data(), nullptr);
else if constexpr (std::is_same_v<double, FType>)
result = std::strtod(json_value.data(), nullptr);
else if constexpr (std::is_same_v<long double, FType>)
result = std::strtold(json_value.data(), nullptr);
return result;
}
/*!
\details No detailed description
\tparam Int No description.
\param [in] json_value No description.
\return No description
*/
template <SignedInteger Int> inline
Int JsonValueParser::toCxxIntegerImpl(const std::string_view json_value) noexcept
{
Int result = 0;
if constexpr (Integer64<Int>)
result = std::strtoll(json_value.data(), nullptr, 10);
else
result = cast<Int>(std::strtol(json_value.data(), nullptr, 10));
return result;
}
/*!
\details No detailed description
\tparam Int No description.
\param [in] json_value No description.
\return No description
*/
template <UnsignedInteger Int> inline
Int JsonValueParser::toCxxIntegerImpl(const std::string_view json_value) noexcept
{
Int result = 0;
if constexpr (Integer64<Int>)
result = std::strtoull(json_value.data(), nullptr, 10);
else
result = cast<Int>(std::strtoul(json_value.data(), nullptr, 10));
return result;
}
/*!
\details No detailed description
\param [in] json_value No description.
\param [out] value No description.
\return No description
*/
inline
std::size_t JsonValueParser::toCxxStringImpl(std::string_view json_value,
char* value) noexcept
{
// Remove prefix and suffix '"'
json_value.remove_prefix(1);
json_value.remove_suffix(1);
std::size_t size = 0;
for (auto i = json_value.begin(); i != json_value.end(); ++i) {
char c = *i;
if (c == '\\') {
++i;
c = getEscapedCharacter(*i);
}
if (value)
value[size] = c;
++size;
}
return size;
}
} // namespace zisc
#endif // _Z_JSON_VALUE_PARSER_INL_HPP__
| 22.039683 | 89 | 0.692384 |
75acb2eb9cd3d25bd94aacd1f8ba7c3e27ba8fda | 7,937 | cpp | C++ | lemon-based-parser/lemon-9-final/Value.cpp | PS-Group/compiler-theory-samples | c916af50eb42020024257ecd17f9be1580db7bf0 | [
"MIT"
] | null | null | null | lemon-based-parser/lemon-9-final/Value.cpp | PS-Group/compiler-theory-samples | c916af50eb42020024257ecd17f9be1580db7bf0 | [
"MIT"
] | null | null | null | lemon-based-parser/lemon-9-final/Value.cpp | PS-Group/compiler-theory-samples | c916af50eb42020024257ecd17f9be1580db7bf0 | [
"MIT"
] | null | null | null | #include "Value.h"
#include <stdexcept>
#include <boost/format.hpp>
#include <cmath>
namespace
{
bool FuzzyEquals(double left, double right)
{
return std::fabs(left - right) >= std::numeric_limits<double>::epsilon();
}
std::string ToPrettyString(double value)
{
std::string result = std::to_string(value);
// Преобразуем 2.00000 в 2.
while (!result.empty() && result.back() == '0')
{
result.pop_back();
}
if (!result.empty() && result.back() == '.')
{
result.pop_back();
}
return result;
}
std::string ToPrettyString(bool value)
{
return value ? "true" : "false";
}
// Конвертирует значение в Boolean (C++ bool).
struct BooleanConverter : boost::static_visitor<bool>
{
bool operator ()(double const& value) const { return FuzzyEquals(value, 0); }
bool operator ()(bool const& value) const { return value; }
bool operator ()(std::string const& value) const { return !value.empty(); }
bool operator ()(std::exception_ptr const&) { return false; }
};
// Конвертирует значение в String (C++ std::string).
struct StringConverter : boost::static_visitor<std::string>
{
std::string operator ()(double const& value) const { return ToPrettyString(value); }
std::string operator ()(bool const& value) const { return ToPrettyString(value); }
std::string operator ()(std::string const& value) const { return value; }
std::string operator ()(std::exception_ptr const& value) { std::rethrow_exception(value); }
};
struct TypeNameVisitor : boost::static_visitor<std::string>
{
std::string operator ()(double const&) const { return "Number"; }
std::string operator ()(bool const&) const { return "Boolean"; }
std::string operator ()(std::string const&) const { return "String"; }
std::string operator ()(std::exception_ptr const& value) { m_exception = value; return "Error"; }
std::exception_ptr m_exception;
};
} // anonymous namespace.
CValue CValue::FromError(const std::exception_ptr &value)
{
return Value(value);
}
CValue CValue::FromErrorMessage(const std::string &message)
{
return CValue::FromError(std::make_exception_ptr(std::runtime_error(message)));
}
CValue CValue::FromDouble(double value)
{
return Value(value);
}
CValue CValue::FromBoolean(bool value)
{
return Value(value);
}
CValue CValue::FromString(const std::string &value)
{
return Value(value);
}
CValue::operator bool() const
{
return ConvertToBool();
}
std::string CValue::ToString() const
{
return TryConvertToString();
}
void CValue::RethrowIfException() const
{
if (m_value.type() == typeid(std::exception_ptr))
{
std::rethrow_exception(boost::get<std::exception_ptr>(m_value));
}
}
bool CValue::AsBool() const
{
return boost::get<bool>(m_value);
}
const std::string &CValue::AsString() const
{
return boost::get<std::string>(m_value);
}
double CValue::AsDouble() const
{
return boost::get<double>(m_value);
}
CValue CValue::operator +() const
{
if (m_value.type() == typeid(double))
{
return *this;
}
return GenerateError(*this, "+");
}
CValue CValue::operator -() const
{
if (m_value.type() == typeid(double))
{
return Value(-AsDouble());
}
return GenerateError(*this, "-");
}
CValue CValue::operator !() const
{
if (m_value.type() == typeid(bool))
{
return Value(!AsBool());
}
return GenerateError(*this, "!");
}
CValue CValue::operator <(const CValue &other) const
{
if (AreBothValues<double>(*this, other))
{
return Value(AsDouble() < other.AsDouble());
}
if (AreBothValues<std::string>(*this, other))
{
return Value(AsString() < other.AsString());
}
return GenerateError(*this, other, "<");
}
CValue CValue::operator ==(const CValue &other) const
{
if (AreBothValues<double>(*this, other))
{
return Value(FuzzyEquals(AsDouble(), other.AsDouble()));
}
if (AreBothValues<std::string>(*this, other))
{
return Value(AsString() == other.AsString());
}
if (AreBothValues<bool>(*this, other))
{
return Value(AsBool() == other.AsBool());
}
return GenerateError(*this, other, "==");
}
CValue CValue::operator &&(const CValue &other) const
{
if (AreBothValues<bool>(*this, other))
{
return Value(AsBool() && other.AsBool());
}
return GenerateError(*this, other, "&&");
}
CValue CValue::operator ||(const CValue &other) const
{
if (AreBothValues<bool>(*this, other))
{
return Value(AsBool() || other.AsBool());
}
return GenerateError(*this, other, "||");
}
CValue CValue::operator +(const CValue &other) const
{
const auto &leftType = m_value.type();
const auto &rightType = other.m_value.type();
if (leftType == typeid(double))
{
if (rightType == typeid(double))
{
return Value(AsDouble() + other.AsDouble());
}
if (rightType == typeid(std::string))
{
return Value(::ToPrettyString(AsDouble()) + other.AsString());
}
}
if (leftType == typeid(std::string))
{
if (rightType == typeid(double))
{
return Value(AsString() + ::ToPrettyString(other.AsDouble()));
}
if (rightType == typeid(std::string))
{
return Value(AsString() + other.AsString());
}
}
return GenerateError(*this, other, "+");
}
CValue CValue::operator -(const CValue &other) const
{
if (AreBothValues<double>(*this, other))
{
return Value(AsDouble() - other.AsDouble());
}
return GenerateError(*this, other, "-");
}
CValue CValue::operator *(const CValue &other) const
{
if (AreBothValues<double>(*this, other))
{
return Value(AsDouble() * other.AsDouble());
}
return GenerateError(*this, other, "*");
}
CValue CValue::operator /(const CValue &other) const
{
if (AreBothValues<double>(*this, other))
{
return Value(AsDouble() / other.AsDouble());
}
return GenerateError(*this, other, "/");
}
CValue CValue::operator %(const CValue &other) const
{
if (AreBothValues<double>(*this, other))
{
return Value(fmod(AsDouble(), other.AsDouble()));
}
return GenerateError(*this, other, "%");
}
template<class TType>
bool CValue::AreBothValues(const CValue &left, const CValue &right)
{
return (left.m_value.type() == typeid(TType))
&& (right.m_value.type() == typeid(TType));
}
CValue CValue::GenerateError(const CValue &value, const char *description)
{
TypeNameVisitor visitor;
std::string valueType = value.m_value.apply_visitor(visitor);
// Прокидываем информацию об ошибке дальше.
if (visitor.m_exception)
{
return CValue::FromError(visitor.m_exception);
}
boost::format formatter("No such unary operation: %1%%2%");
formatter % description % valueType;
return CValue::FromErrorMessage(boost::str(formatter));
}
CValue CValue::GenerateError(const CValue &left, const CValue &right, const char *description)
{
TypeNameVisitor visitor;
std::string leftType = left.m_value.apply_visitor(visitor);
std::string rightType = right.m_value.apply_visitor(visitor);
// Прокидываем информацию об ошибке дальше.
if (visitor.m_exception)
{
return CValue::FromError(visitor.m_exception);
}
boost::format formatter("No such binary operation: %1% %2% %3%");
formatter % leftType % description % rightType;
return CValue::FromErrorMessage(boost::str(formatter));
}
CValue::CValue(const CValue::Value &value)
: m_value(value)
{
}
std::string CValue::TryConvertToString() const
{
StringConverter converter;
std::string value = m_value.apply_visitor(converter);
return value;
}
bool CValue::ConvertToBool() const
{
BooleanConverter converter;
return m_value.apply_visitor(converter);
}
| 24.649068 | 101 | 0.63815 |
75b5214b40cee70531bb1c2b785b7721472ba137 | 4,100 | cpp | C++ | src/TotalGeneralizedVariation.cpp | DanonOfficial/TGVDenoising | 20446d9c89d75cf43056f43ed42f37965b4e7b6e | [
"MIT"
] | 8 | 2019-04-06T06:13:53.000Z | 2021-04-30T09:49:18.000Z | src/TotalGeneralizedVariation.cpp | DanonOfficial/TGVDenoising | 20446d9c89d75cf43056f43ed42f37965b4e7b6e | [
"MIT"
] | 1 | 2021-06-22T15:26:13.000Z | 2021-06-23T05:45:21.000Z | src/TotalGeneralizedVariation.cpp | DanonOfficial/TGVDenoising | 20446d9c89d75cf43056f43ed42f37965b4e7b6e | [
"MIT"
] | 2 | 2020-07-13T09:05:51.000Z | 2021-02-01T04:15:58.000Z | //
// Created by roundedglint585 on 3/11/19.
//
#include "TotalGeneralizedVariation.hpp"
TotalGeneralizedVariation::TotalGeneralizedVariation(const std::vector<TotalGeneralizedVariation::Image> &images)
: m_images(images), m_result(m_images[0]), m_width(m_result[0].size()), m_height(m_result.size()) {
init();
initWs();
initStacked();
calculateHist();
}
TotalGeneralizedVariation::TotalGeneralizedVariation(std::vector<TotalGeneralizedVariation::Image> &&images) : m_images(
std::move(images)), m_result(m_images[0]), m_width(m_result[0].size()), m_height(m_result.size()) {
init();
initWs();
initStacked();
calculateHist();
}
void TotalGeneralizedVariation::init() {
v = mathRoutine::calculateGradient(m_result);
p = mathRoutine::calculateGradient(m_result);
q = mathRoutine::calculateEpsilon(v);
}
void TotalGeneralizedVariation::initWs() {
Ws.resize(m_images.size());
for (auto &ws: Ws) {
ws.resize(m_height);
for (auto &i : ws) {
i = std::vector<float>(m_width, 0.0f);
}
}
}
void TotalGeneralizedVariation::initStacked() {
stacked = std::vector(m_height,
std::vector<std::vector<float>>(m_width, std::vector<float>(Ws.size() + m_images.size(), 0)));
}
void TotalGeneralizedVariation::calculateHist() {
for (size_t histNum = 0; histNum < Ws.size(); histNum++) {
for (auto &image: m_images) {
for (size_t i = 0; i < m_height; i++) {
for (size_t j = 0; j < m_width; j++) {
if (m_images[histNum][i][j] > image[i][j]) {
Ws[histNum][i][j] += 1.f;
} else {
if (m_images[histNum][i][j] < image[i][j])
Ws[histNum][i][j] -= 1.f;
}
}
}
}
}
}
TotalGeneralizedVariation::Image
TotalGeneralizedVariation::prox(const TotalGeneralizedVariation::Image &image, float tau, float lambda_data) {
Image result = Image(m_height, std::vector<float>(m_width, 0));
//need to swap dimensions to calculate median
for (size_t i = 0; i < m_height; i++) {
for (size_t j = 0; j < m_width; j++) {
for (size_t k = 0; k < m_images.size(); k++) {
stacked[i][j][k] = m_images[k][i][j];
}
for (size_t k = 0; k < Ws.size(); k++) {
stacked[i][j][m_images.size() + k] = image[i][j] + tau * lambda_data * Ws[k][i][j];
}
}
}
for (size_t i = 0; i < m_height; i++) {
for (size_t j = 0; j < m_width; j++) {
std::stable_sort(stacked[i][j].begin(), stacked[i][j].end());
if (stacked[i][j].size() % 2 == 1) {
result[i][j] = stacked[i][j][stacked[i][j].size() / 2 + 1];
} else {
result[i][j] =
(stacked[i][j][stacked[i][j].size() / 2] + stacked[i][j][stacked[i][j].size() / 2 - 1]) / 2;
}
}
}
return result;
}
void TotalGeneralizedVariation::iteration(float tau, float lambda_tv,
float lambda_tgv, float lambda_data) {
using namespace mathRoutine;
float tau_u, tau_v, tau_p, tau_q;
tau_u = tau;
tau_v = tau;
tau_p = tau;
tau_q = tau;
Image un = prox(m_result + (-tau_u * lambda_tv) * (mathRoutine::calculateTranspondedGradient(p)), tau_u,
lambda_data);
Gradient vn = v + (-lambda_tgv * tau_v) * mathRoutine::calculateTranspondedEpsilon(q) + (tau_v * lambda_tv) * p;
Gradient pn = project(
p + (tau_p * lambda_tv) * (mathRoutine::calculateGradient((-1) * ((-2) * un + m_result)) + ((-2) * vn + v)),
lambda_tv);
Epsilon qn = project(q + (-tau_q * lambda_tgv) * mathRoutine::calculateEpsilon(-2 * vn + v), lambda_tgv);
m_result = std::move(un);
v = std::move(vn);
p = std::move(pn);
q = std::move(qn);
}
auto TotalGeneralizedVariation::getImage() const -> Image{
return m_result;
}
| 33.064516 | 120 | 0.54878 |
75b5a22f172625f6a8c744363d6f830d8f9313f2 | 2,254 | hpp | C++ | include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:45 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: Zenject.AddToCurrentGameObjectComponentProvider
#include "Zenject/AddToCurrentGameObjectComponentProvider.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: InjectContext
class InjectContext;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0
class AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0 : public ::Il2CppObject {
public:
// public Zenject.AddToCurrentGameObjectComponentProvider <>4__this
// Offset: 0x10
Zenject::AddToCurrentGameObjectComponentProvider* $$4__this;
// public System.Collections.Generic.List`1<Zenject.TypeValuePair> args
// Offset: 0x18
System::Collections::Generic::List_1<Zenject::TypeValuePair>* args;
// public System.Object instance
// Offset: 0x20
::Il2CppObject* instance;
// public Zenject.InjectContext context
// Offset: 0x28
Zenject::InjectContext* context;
// System.Void <GetAllInstancesWithInjectSplit>b__0()
// Offset: 0xD4F730
void $GetAllInstancesWithInjectSplit$b__0();
// public System.Void .ctor()
// Offset: 0xD4F728
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0* New_ctor();
}; // Zenject.AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0*, "Zenject", "AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0");
#pragma pack(pop)
| 40.25 | 173 | 0.741349 |
75b87972b857fbd84c695831f982b272ada18fa2 | 965 | hpp | C++ | common/include/bib/OrnsteinUhlenbeckNoise.hpp | matthieu637/ddrl | a454d09a3ac9be5db960ff180b3d075c2f9e4a70 | [
"MIT"
] | 27 | 2017-11-27T09:32:41.000Z | 2021-03-02T13:50:23.000Z | common/include/bib/OrnsteinUhlenbeckNoise.hpp | matthieu637/ddrl | a454d09a3ac9be5db960ff180b3d075c2f9e4a70 | [
"MIT"
] | 10 | 2018-10-09T14:39:14.000Z | 2020-11-10T15:01:00.000Z | common/include/bib/OrnsteinUhlenbeckNoise.hpp | matthieu637/ddrl | a454d09a3ac9be5db960ff180b3d075c2f9e4a70 | [
"MIT"
] | 3 | 2019-05-16T09:14:15.000Z | 2019-08-15T14:35:40.000Z | #ifndef ORNSTEINUHLENBECK_HPP
#define ORNSTEINUHLENBECK_HPP
#include <vector>
namespace bib {
template<typename Real>
class OrnsteinUhlenbeckNoise {
public:
OrnsteinUhlenbeckNoise(uint action_size, Real sigma_=.2, Real theta_=.15, Real dt_=0.01) : x_t (action_size, 0) {
sigma = sigma_;
theta = theta_;
dt = dt_;
}
void reset() {
for(uint i=0;i<x_t.size();i++)
x_t[i] = 0;
}
void step(std::vector<Real>& mu) {
std::normal_distribution<Real> dist(0, 1.);
for (uint i = 0; i < mu.size(); i++) {
Real normal = dist(*bib::Seed::random_engine());
Real x_tplus = x_t[i] - theta * dt * x_t[i] + sigma * sqrt(dt) * normal;
mu[i] += x_tplus;
if(mu[i] < (Real) -1.)
mu[i] = (Real) -1.;
else if (mu[i] > (Real) 1.)
mu[i] = (Real) 1.;
x_t[i] = x_tplus;
}
}
private:
std::vector<Real> x_t;
Real sigma;
Real theta;
Real dt;
};
}
#endif
| 19.693878 | 115 | 0.557513 |
75b90ec3f22c09aa37cd74b9beb9a071c2601b66 | 1,959 | cpp | C++ | Source/Driver/API/SQLSetConnectOption.cpp | yichenghuang/bigobject-odbc | c6d947ea3d18d79684adfbac1c492282a075d48d | [
"MIT"
] | null | null | null | Source/Driver/API/SQLSetConnectOption.cpp | yichenghuang/bigobject-odbc | c6d947ea3d18d79684adfbac1c492282a075d48d | [
"MIT"
] | null | null | null | Source/Driver/API/SQLSetConnectOption.cpp | yichenghuang/bigobject-odbc | c6d947ea3d18d79684adfbac1c492282a075d48d | [
"MIT"
] | null | null | null | /*
* ----------------------------------------------------------------------------
* Copyright (c) 2014-2015 BigObject Inc.
* All Rights Reserved.
*
* Use of, copying, modifications to, and distribution of this software
* and its documentation without BigObject's written permission can
* result in the violation of U.S., Taiwan and China Copyright and Patent laws.
* Violators will be prosecuted to the highest extent of the applicable laws.
*
* BIGOBJECT MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
* ----------------------------------------------------------------------------
*/
#include "Driver.hpp"
/*
https://msdn.microsoft.com/en-us/library/ms713564%28v=vs.85%29.aspx
https://msdn.microsoft.com/en-us/library/ms714008%28v=vs.85%29.aspx
WE DON'T EXPORT THIS API.
*/
SQLRETURN SQL_API SQLSetConnectOption(SQLHDBC hDrvDbc, UWORD nOption,
SQLULEN vParam)
{
HDRVDBC hDbc = (HDRVDBC)hDrvDbc;
LOG_DEBUG_F_FUNC(
TEXT("%s: hDrvDbc = 0x%08lX, nOption = %d, vParam = %d"),
LOG_FUNCTION_NAME,
(long)hDrvDbc, nOption, vParam);
API_HOOK_ENTRY(SQLSetConnectOption, hDrvDbc, nOption, vParam);
/* SANITY CHECKS */
if(hDbc == SQL_NULL_HDBC)
return SQL_INVALID_HANDLE;
switch(nOption)
{
case SQL_TRANSLATE_DLL:
case SQL_TRANSLATE_OPTION:
/* case SQL_CONNECT_OPT_DRVR_START: */
case SQL_ODBC_CURSORS:
case SQL_OPT_TRACE:
switch(vParam)
{
case SQL_OPT_TRACE_ON:
case SQL_OPT_TRACE_OFF:
default:
;
}
break;
case SQL_OPT_TRACEFILE:
case SQL_ACCESS_MODE:
case SQL_AUTOCOMMIT:
default:
;
}
LOG_WARN_F_FUNC(TEXT("%s: This function not supported."), LOG_FUNCTION_NAME);
LOG_DEBUG_F_FUNC(TEXT("%s: SQL_ERROR"), LOG_FUNCTION_NAME);
return SQL_ERROR;
}
| 27.208333 | 79 | 0.663604 |
75badf88c78b05b59ba0ffb444e53832a715d815 | 3,171 | cc | C++ | shill/dbus/chromeos_modem_simple_proxy.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | shill/dbus/chromeos_modem_simple_proxy.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | shill/dbus/chromeos_modem_simple_proxy.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shill/dbus/chromeos_modem_simple_proxy.h"
#include <base/bind.h>
#include "shill/cellular/cellular_error.h"
#include "shill/error.h"
#include "shill/logging.h"
using std::string;
namespace shill {
namespace Logging {
static auto kModuleLogScope = ScopeLogger::kDBus;
static string ObjectID(const dbus::ObjectPath* p) { return p->value(); }
}
ChromeosModemSimpleProxy::ChromeosModemSimpleProxy(
const scoped_refptr<dbus::Bus>& bus,
const string& path,
const string& service)
: proxy_(
new org::freedesktop::ModemManager::Modem::SimpleProxy(
bus, service, dbus::ObjectPath(path))) {}
ChromeosModemSimpleProxy::~ChromeosModemSimpleProxy() {}
void ChromeosModemSimpleProxy::GetModemStatus(
Error* error, const KeyValueStoreCallback& callback, int timeout) {
SLOG(&proxy_->GetObjectPath(), 2) << __func__;
proxy_->GetStatusAsync(
base::Bind(&ChromeosModemSimpleProxy::OnGetStatusSuccess,
weak_factory_.GetWeakPtr(),
callback),
base::Bind(&ChromeosModemSimpleProxy::OnGetStatusFailure,
weak_factory_.GetWeakPtr(),
callback),
timeout);
}
void ChromeosModemSimpleProxy::Connect(const KeyValueStore& properties,
Error* error,
const ResultCallback& callback,
int timeout) {
SLOG(&proxy_->GetObjectPath(), 2) << __func__;
brillo::VariantDictionary properties_dict;
KeyValueStore::ConvertToVariantDictionary(properties, &properties_dict);
proxy_->ConnectAsync(
properties_dict,
base::Bind(&ChromeosModemSimpleProxy::OnConnectSuccess,
weak_factory_.GetWeakPtr(),
callback),
base::Bind(&ChromeosModemSimpleProxy::OnConnectFailure,
weak_factory_.GetWeakPtr(),
callback),
timeout);
}
void ChromeosModemSimpleProxy::OnGetStatusSuccess(
const KeyValueStoreCallback& callback,
const brillo::VariantDictionary& props) {
SLOG(&proxy_->GetObjectPath(), 2) << __func__;
KeyValueStore props_store;
KeyValueStore::ConvertFromVariantDictionary(props, &props_store);
callback.Run(props_store, Error());
}
void ChromeosModemSimpleProxy::OnGetStatusFailure(
const KeyValueStoreCallback& callback, brillo::Error* dbus_error) {
SLOG(&proxy_->GetObjectPath(), 2) << __func__;
Error error;
CellularError::FromChromeosDBusError(dbus_error, &error);
callback.Run(KeyValueStore(), error);
}
void ChromeosModemSimpleProxy::OnConnectSuccess(
const ResultCallback& callback) {
SLOG(&proxy_->GetObjectPath(), 2) << __func__;
callback.Run(Error());
}
void ChromeosModemSimpleProxy::OnConnectFailure(
const ResultCallback& callback, brillo::Error* dbus_error) {
SLOG(&proxy_->GetObjectPath(), 2) << __func__;
Error error;
CellularError::FromChromeosDBusError(dbus_error, &error);
callback.Run(error);
}
} // namespace shill
| 33.378947 | 74 | 0.693157 |
75bb4de059be545230b138fcde43f895938c4a1e | 409 | cpp | C++ | week-02/practice/02.cpp | greenfox-zerda-sparta/zerda-syllabus | 5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c | [
"MIT"
] | null | null | null | week-02/practice/02.cpp | greenfox-zerda-sparta/zerda-syllabus | 5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c | [
"MIT"
] | null | null | null | week-02/practice/02.cpp | greenfox-zerda-sparta/zerda-syllabus | 5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
void draw_characters(int count, char c) {
for (int i = 0; i < count; ++i) {
cout << c;
}
}
void christmas_tree(char main_character, int times) {
for (int row = 1; row <= times; ++row) {
draw_characters(times - row, ' ');
draw_characters(row * 2 - 1, main_character);
cout << endl;
}
}
int main() {
christmas_tree('#', 8);
return 0;
}
| 16.36 | 53 | 0.594132 |
75bcef18d36e759fd1c49f900c6874c2ad77d7d0 | 55 | cpp | C++ | src-ui/tablemodel.cpp | ZhaohengLi/library-management | ffdd50e367f50354e07f5cd7aff9c826aac837b0 | [
"Apache-2.0"
] | 2 | 2021-09-06T17:13:19.000Z | 2022-03-02T06:47:31.000Z | tablemodel.cpp | borneq/userQtExamples | 2493a96e26293b3a842a998a09228de9834c1776 | [
"MIT"
] | null | null | null | tablemodel.cpp | borneq/userQtExamples | 2493a96e26293b3a842a998a09228de9834c1776 | [
"MIT"
] | null | null | null | #include "tablemodel.h"
TableModel::TableModel()
{
}
| 7.857143 | 24 | 0.690909 |
75bdac2cb35e35698d57780b633d79365809eb2e | 1,640 | cpp | C++ | code/SoulVania/AnimationFactoryReader.cpp | warzes/Soulvania | 83733b6a6aa38f8024109193893eb5b65b0e6294 | [
"MIT"
] | 1 | 2021-06-30T06:29:54.000Z | 2021-06-30T06:29:54.000Z | code/SoulVania/AnimationFactoryReader.cpp | warzes/Soulvania | 83733b6a6aa38f8024109193893eb5b65b0e6294 | [
"MIT"
] | null | null | null | code/SoulVania/AnimationFactoryReader.cpp | warzes/Soulvania | 83733b6a6aa38f8024109193893eb5b65b0e6294 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "AnimationFactoryReader.h"
#include "FileLogger.h"
#include "LoadContentException.h"
#include "ContentManager.h"
#include "pugixml/pugixml.hpp"
std::shared_ptr<AnimationFactory> AnimationFactoryReader::Read(std::string filePath, ContentManager& contentManager)
{
auto xmlDocument = pugi::xml_document{};
auto result = xmlDocument.load_file(filePath.c_str());
if (!result)
{
FileLogger::GetInstance().Error("{}() failed: {}. Path: {}", __FUNCTION__, result.description(), filePath);
throw LoadContentException(result.description());
}
auto rootNode = xmlDocument.child("GameContent");
auto atlasPath = rootNode.child("Animations").attribute("AtlasPath").as_string();
auto resolvedAtlasPath = contentManager.ResolvePath(Path{ filePath }.parent_path(), atlasPath);
auto spritesheet = contentManager.Load<Spritesheet>(resolvedAtlasPath);
auto animations = AnimationDict{};
for (auto animationNode : rootNode.child("Animations").children("Animation"))
{
auto name = animationNode.attribute("Name").as_string();
auto defaultAnimateTime = animationNode.attribute("DefaultTime").as_int();
auto isLooping = animationNode.attribute("IsLooping").as_bool();
auto animation = Animation{ name, defaultAnimateTime, isLooping };
for (auto frameNode : animationNode.children("Frame"))
{
auto name = frameNode.attribute("SpriteID").as_string();
auto time = frameNode.attribute("Time").as_int(); // equals to 0 if Time attribute not found
animation.Add(spritesheet->at(name), time);
}
animations.emplace(name, animation);
}
return std::make_shared<AnimationFactory>(animations);
} | 38.139535 | 116 | 0.75061 |
75c093ce0b68e30ec4281f3659b798d89fc0be6e | 929 | cpp | C++ | FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp | patridge/FlatRedBall | 01e0212afeb977a10244796494dcaf9c800a3770 | [
"MIT"
] | 110 | 2016-01-14T14:46:16.000Z | 2022-03-27T19:00:48.000Z | FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp | patridge/FlatRedBall | 01e0212afeb977a10244796494dcaf9c800a3770 | [
"MIT"
] | 471 | 2016-08-21T14:48:15.000Z | 2022-03-31T20:22:50.000Z | FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp | patridge/FlatRedBall | 01e0212afeb977a10244796494dcaf9c800a3770 | [
"MIT"
] | 33 | 2016-01-25T23:30:03.000Z | 2022-02-18T07:24:45.000Z | #include <windows.h>
#include "dynamic_funcs.h"
// Since this code requires Win2000 or later, we'll load it dynamically
static HMODULE dll_gdi32 = 0;
GetGlyphIndicesA_t fGetGlyphIndicesA = 0;
GetGlyphIndicesW_t fGetGlyphIndicesW = 0;
GetFontUnicodeRanges_t fGetFontUnicodeRanges = 0;
void Init()
{
#ifdef LOAD_GDI32
dll_gdi32 = LoadLibrary("gdi32.dll");
if( dll_gdi32 != 0 )
{
fGetGlyphIndicesA = (GetGlyphIndicesA_t)GetProcAddress(dll_gdi32, "GetGlyphIndicesA");
fGetGlyphIndicesW = (GetGlyphIndicesW_t)GetProcAddress(dll_gdi32, "GetGlyphIndicesW");
fGetFontUnicodeRanges = (GetFontUnicodeRanges_t)GetProcAddress(dll_gdi32, "GetFontUnicodeRanges");
}
#else
fGetGlyphIndicesA = GetGlyphIndicesA;
fGetGlyphIndicesW = GetGlyphIndicesW;
fGetFontUnicodeRanges = GetFontUnicodeRanges;
#endif
}
void Uninit()
{
#ifdef LOAD_GDI32
if( dll_gdi32 != 0 )
FreeLibrary(dll_gdi32);
#endif
} | 27.323529 | 100 | 0.759957 |
75c42169434068f566303a77e8c7e062f4d5bf0d | 201 | hpp | C++ | src/ColorSYMGS.hpp | hpcg-benchmark/KHPCG3.0 | 9591b148ea6552342a0471a932d2abf332e490e0 | [
"BSD-3-Clause"
] | 5 | 2015-07-10T16:35:08.000Z | 2021-09-13T03:29:37.000Z | src/ColorSYMGS.hpp | zabookey/Kokkos-HPCG | 7ca081e51a275c4fb6b21e8871788e88e8715dbc | [
"BSD-3-Clause"
] | null | null | null | src/ColorSYMGS.hpp | zabookey/Kokkos-HPCG | 7ca081e51a275c4fb6b21e8871788e88e8715dbc | [
"BSD-3-Clause"
] | 3 | 2019-03-05T16:46:25.000Z | 2021-12-22T03:49:00.000Z | #ifndef COLORSYMGS_HPP
#define COLORSYMGS_HPP
#include "SparseMatrix.hpp"
#include "Vector.hpp"
#include "KokkosSetup.hpp"
int ColorSYMGS(const SparseMatrix & A, const Vector & x, Vector & y);
#endif | 22.333333 | 69 | 0.766169 |
75c76b1272dc16e0e71395a36d1be066d448e549 | 26,695 | cpp | C++ | winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp | r2d2rigo/Win2D | 3f06d4f19b7d16b67859a1b30ac770215ef3e52d | [
"MIT"
] | 1,002 | 2015-01-09T19:40:01.000Z | 2019-05-04T12:05:09.000Z | winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp | r2d2rigo/Win2D | 3f06d4f19b7d16b67859a1b30ac770215ef3e52d | [
"MIT"
] | 667 | 2015-01-02T19:04:11.000Z | 2019-05-03T14:43:51.000Z | winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp | SunburstApps/Win2D.WinUI | 75a33f8f4c0c785c2d1b478589fd4d3a9c5b53df | [
"MIT"
] | 258 | 2015-01-06T07:44:49.000Z | 2019-05-01T15:50:59.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#include "pch.h"
TEST_CLASS(CanvasImageSourceUnitTests)
{
public:
TEST_METHOD_EX(CanvasImageSourceConstruction)
{
//
// On construction the CanvasImageSource is expected to:
//
// - create a SurfaceImageSource with the specified width/height and background mode
//
// - set this as the composable base (queryable by GetComposableBase())
//
// - call SetDevice on the SurfaceImageSourceNativeWith2D, passing it
// the d2d device associated with the CanvasDevice that was passed in
//
int expectedHeight = 123;
int expectedWidth = 456;
CanvasAlphaMode expectedAlphaMode = CanvasAlphaMode::Ignore;
auto mockD2DDevice = Make<MockD2DDevice>();
auto mockCanvasDevice = Make<MockCanvasDevice>();
auto mockSurfaceImageSourceFactory = Make<MockSurfaceImageSourceFactory>();
auto mockSurfaceImageSource = Make<MockSurfaceImageSource>();
//
// Verify that the SurfaceImageSourceFactory is asked to create a
// SurfaceImageSource with correct parameters.
//
// Note that actualOuter is a raw pointer - we don't want actualOuter to
// ever become the last thing referencing the CanvasImageSource (this
// could happen since the mock below is called during CanvasImageSource
// construction; if that fails then things can blow up since actualOuter
// exists outside normal exception cleanup)
//
bool mockCreateInstanceCalled = false;
IInspectable* actualOuter;
mockSurfaceImageSourceFactory->MockCreateInstanceWithDimensionsAndOpacity =
[&](int32_t actualWidth, int32_t actualHeight, bool isOpaque, IInspectable* outer)
{
Assert::IsFalse(mockCreateInstanceCalled);
Assert::AreEqual(expectedWidth, actualWidth);
Assert::AreEqual(expectedHeight, actualHeight);
auto actualAlphaMode = isOpaque ? CanvasAlphaMode::Ignore : CanvasAlphaMode::Premultiplied;
Assert::AreEqual(expectedAlphaMode, actualAlphaMode);
actualOuter = outer;
mockCreateInstanceCalled = true;
return mockSurfaceImageSource;
};
//
// Verify that SetDevice is called on the SurfaceImageSource with the
// correct D2D device
//
mockCanvasDevice->MockGetD2DDevice =
[&]
{
return mockD2DDevice;
};
mockCanvasDevice->Mockget_Device =
[&](ICanvasDevice** value)
{
ComPtr<ICanvasDevice> device(mockCanvasDevice.Get());
*value = device.Detach();
};
mockSurfaceImageSource->SetDeviceMethod.SetExpectedCalls(1,
[&](IUnknown* actualDevice)
{
ComPtr<IUnknown> expectedDevice;
ThrowIfFailed(mockD2DDevice.As(&expectedDevice));
Assert::AreEqual(expectedDevice.Get(), actualDevice);
return S_OK;
});
//
// Actually create the CanvasImageSource
//
auto canvasImageSource = Make<CanvasImageSource>(
mockCanvasDevice.Get(),
(float)expectedWidth,
(float)expectedHeight,
DEFAULT_DPI,
expectedAlphaMode,
mockSurfaceImageSourceFactory.Get(),
std::make_shared<MockCanvasImageSourceDrawingSessionFactory>());
Assert::IsTrue(mockCreateInstanceCalled);
//
// Verify the composition relationship between the CanvasImageSource and
// the base class, SurfaceImageSource.
//
ComPtr<IInspectable> expectedOuter;
ThrowIfFailed(canvasImageSource.As(&expectedOuter));
Assert::AreEqual(expectedOuter.Get(), actualOuter);
ComPtr<IInspectable> expectedComposableBase;
ThrowIfFailed(mockSurfaceImageSource.As(&expectedComposableBase));
Assert::AreEqual(canvasImageSource->GetComposableBase().Get(), expectedComposableBase.Get());
CanvasAlphaMode actualAlphaMode;
ThrowIfFailed(canvasImageSource->get_AlphaMode(&actualAlphaMode));
Assert::AreEqual(CanvasAlphaMode::Ignore, actualAlphaMode);
}
struct AlphaModeFixture
{
bool ExpectedIsOpaque;
AlphaModeFixture()
: ExpectedIsOpaque(false)
{}
void CreateImageSource(CanvasAlphaMode alphaMode)
{
auto factory = Make<MockSurfaceImageSourceFactory>();
bool createWasCalled = false;
factory->MockCreateInstanceWithDimensionsAndOpacity =
[&] (int32_t,int32_t,bool opaque,IInspectable*)
{
createWasCalled = true;
Assert::AreEqual(ExpectedIsOpaque, opaque);
return Make<StubSurfaceImageSource>();
};
Make<CanvasImageSource>(
As<ICanvasResourceCreator>(Make<StubCanvasDevice>()).Get(),
1.0f,
1.0f,
DEFAULT_DPI,
alphaMode,
factory.Get(),
std::make_shared<MockCanvasImageSourceDrawingSessionFactory>());
Assert::IsTrue(createWasCalled, L"SurfaceImageSourceFactory::Create was called");
}
};
TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModeIgnore_ThenUnderlyingImageSourceIsOpaque)
{
AlphaModeFixture f;
f.ExpectedIsOpaque = true;
f.CreateImageSource(CanvasAlphaMode::Ignore);
}
TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModePremultiplied_ThenUnderlyingImageSourceIsTransparent)
{
AlphaModeFixture f;
f.ExpectedIsOpaque = false;
f.CreateImageSource(CanvasAlphaMode::Premultiplied);
}
TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModeStraight_ThenFailsWithInvalidArg)
{
AlphaModeFixture f;
ExpectHResultException(E_INVALIDARG, [&] { f.CreateImageSource(CanvasAlphaMode::Straight); });
ValidateStoredErrorState(E_INVALIDARG, Strings::InvalidAlphaModeForImageSource);
}
TEST_METHOD_EX(CanvasImageSourceGetDevice)
{
ComPtr<ICanvasDevice> expectedCanvasDevice = Make<StubCanvasDevice>();
auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>();
auto canvasImageSource = Make<CanvasImageSource>(
static_cast<ICanvasResourceCreator*>(static_cast<StubCanvasDevice*>(expectedCanvasDevice.Get())),
1.0f,
1.0f,
DEFAULT_DPI,
CanvasAlphaMode::Premultiplied,
stubSurfaceImageSourceFactory.Get(),
std::make_shared<MockCanvasImageSourceDrawingSessionFactory>());
ComPtr<ICanvasDevice> actualCanvasDevice;
ThrowIfFailed(canvasImageSource->get_Device(&actualCanvasDevice));
Assert::AreEqual(expectedCanvasDevice.Get(), actualCanvasDevice.Get());
// Calling get_Device with a nullptr should fail appropriately
Assert::AreEqual(E_INVALIDARG, canvasImageSource->get_Device(nullptr));
}
struct RecreateFixture
{
ComPtr<StubCanvasDevice> FirstDevice;
ComPtr<MockSurfaceImageSource> SurfaceImageSource;
ComPtr<CanvasImageSource> ImageSource;
RecreateFixture()
: FirstDevice(Make<StubCanvasDevice>())
, SurfaceImageSource(Make<MockSurfaceImageSource>())
{
auto surfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(SurfaceImageSource.Get());
// On the initial make we know that this succeeds
SurfaceImageSource->SetDeviceMethod.AllowAnyCall();
ImageSource = Make<CanvasImageSource>(
FirstDevice.Get(),
1.0f,
1.0f,
DEFAULT_DPI,
CanvasAlphaMode::Premultiplied,
surfaceImageSourceFactory.Get(),
std::make_shared<MockCanvasImageSourceDrawingSessionFactory>());
}
void ExpectSetDeviceWithNullAndThen(ComPtr<IUnknown> expected)
{
SurfaceImageSource->SetDeviceMethod.SetExpectedCalls(2,
[=] (IUnknown* actualDevice)
{
if (this->SurfaceImageSource->SetDeviceMethod.GetCurrentCallCount() == 1)
{
Assert::IsNull(actualDevice);
}
else
{
Assert::IsTrue(IsSameInstance(actualDevice, expected.Get()));
}
return S_OK;
});
}
};
TEST_METHOD_EX(CanvasImageSource_Recreate_WhenPassedNull_ReturnsInvalidArg)
{
RecreateFixture f;
Assert::AreEqual(E_INVALIDARG, f.ImageSource->Recreate(nullptr));
}
TEST_METHOD_EX(CanvasImageSource_Recreate_WhenPassedNewDevice_SetsDevice)
{
RecreateFixture f;
auto secondDevice = Make<StubCanvasDevice>();
f.ExpectSetDeviceWithNullAndThen(secondDevice->GetD2DDevice());
ThrowIfFailed(f.ImageSource->Recreate(secondDevice.Get()));
ComPtr<ICanvasDevice> retrievedDevice;
ThrowIfFailed(f.ImageSource->get_Device(&retrievedDevice));
Assert::IsTrue(IsSameInstance(secondDevice.Get(), retrievedDevice.Get()));
}
TEST_METHOD_EX(CanvasImageSource_Recreated_WhenPassedOriginalDevice_SetsDevice)
{
RecreateFixture f;
f.ExpectSetDeviceWithNullAndThen(f.FirstDevice->GetD2DDevice());
ThrowIfFailed(f.ImageSource->Recreate(f.FirstDevice.Get()));
ComPtr<ICanvasDevice> retrievedDevice;
ThrowIfFailed(f.ImageSource->get_Device(&retrievedDevice));
Assert::IsTrue(IsSameInstance(f.FirstDevice.Get(), retrievedDevice.Get()));
}
TEST_METHOD_EX(CanvasImageSource_CreateFromCanvasControl)
{
auto canvasControlAdapter = std::make_shared<CanvasControlTestAdapter>();
auto canvasControl = Make<CanvasControl>(canvasControlAdapter);
// Get the control to a point where it has created the device.
canvasControlAdapter->CreateCanvasImageSourceMethod.AllowAnyCall();
auto userControl = static_cast<StubUserControl*>(As<IUserControl>(canvasControl).Get());
ThrowIfFailed(userControl->LoadedEventSource->InvokeAll(nullptr, nullptr));
canvasControlAdapter->RaiseCompositionRenderingEvent();
auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>();
auto canvasImageSource = Make<CanvasImageSource>(
canvasControl.Get(),
123.0f,
456.0f,
DEFAULT_DPI,
CanvasAlphaMode::Ignore,
stubSurfaceImageSourceFactory.Get(),
std::make_shared<MockCanvasImageSourceDrawingSessionFactory>());
//
// Verify that the image source and the control are compatible.
//
ComPtr<ICanvasDevice> controlDevice;
ThrowIfFailed(canvasControl->get_Device(&controlDevice));
ComPtr<ICanvasDevice> sisDevice;
ThrowIfFailed(canvasImageSource->get_Device(&sisDevice));
Assert::AreEqual(controlDevice.Get(), sisDevice.Get());
}
TEST_METHOD_EX(CanvasImageSource_CreateFromDrawingSession)
{
ComPtr<StubCanvasDevice> canvasDevice = Make<StubCanvasDevice>();
ComPtr<StubD2DDeviceContextWithGetFactory> d2dDeviceContext =
Make<StubD2DDeviceContextWithGetFactory>();
d2dDeviceContext->SetTextAntialiasModeMethod.SetExpectedCalls(1,
[](D2D1_TEXT_ANTIALIAS_MODE mode)
{
Assert::AreEqual(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE, mode);
});
ComPtr<CanvasDrawingSession> drawingSession = CanvasDrawingSession::CreateNew(
d2dDeviceContext.Get(),
std::make_shared<StubCanvasDrawingSessionAdapter>(),
canvasDevice.Get());
auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>();
auto canvasImageSource = Make<CanvasImageSource>(
drawingSession.Get(),
5.0f,
10.0f,
DEFAULT_DPI,
CanvasAlphaMode::Ignore,
stubSurfaceImageSourceFactory.Get(),
std::make_shared<MockCanvasImageSourceDrawingSessionFactory>());
//
// Verify that the image source and the drawing session are compatible.
//
ComPtr<ICanvasDevice> sisDevice;
ThrowIfFailed(canvasImageSource->get_Device(&sisDevice));
Assert::AreEqual(static_cast<ICanvasDevice*>(canvasDevice.Get()), sisDevice.Get());
}
TEST_METHOD_EX(CanvasImageSource_DpiProperties)
{
const float dpi = 144;
auto canvasDevice = Make<StubCanvasDevice>();
auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>();
auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get());
auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>();
auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>();
auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), 1.0f, 1.0f, dpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory);
float actualDpi = 0;
ThrowIfFailed(canvasImageSource->get_Dpi(&actualDpi));
Assert::AreEqual(dpi, actualDpi);
VerifyConvertDipsToPixels(dpi, canvasImageSource);
const float testValue = 100;
float dips = 0;
ThrowIfFailed(canvasImageSource->ConvertPixelsToDips((int)testValue, &dips));
Assert::AreEqual(testValue * DEFAULT_DPI / dpi, dips);
}
TEST_METHOD_EX(CanvasImageSource_PropagatesDpiToDrawingSession)
{
const float expectedDpi = 144;
auto canvasDevice = Make<StubCanvasDevice>();
auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>();
auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get());
auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>();
auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>();
auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), 1.0f, 1.0f, expectedDpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory);
mockDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const&, float dpi)
{
Assert::AreEqual(expectedDpi, dpi);
return nullptr;
});
ComPtr<ICanvasDrawingSession> drawingSession;
ThrowIfFailed(canvasImageSource->CreateDrawingSession(Color{}, &drawingSession));
}
TEST_METHOD_EX(CanvasImageSource_SizeProperties)
{
const float width = 123;
const float height = 456;
const float dpi = 144;
auto canvasDevice = Make<StubCanvasDevice>();
auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>();
auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get());
auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>();
auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>();
auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), width, height, dpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory);
Size size = { 0, 0 };
ThrowIfFailed(canvasImageSource->get_Size(&size));
Assert::AreEqual(width, size.Width);
Assert::AreEqual(height, size.Height);
BitmapSize bitmapSize = { 0, 0 };
ThrowIfFailed(canvasImageSource->get_SizeInPixels(&bitmapSize));
Assert::AreEqual(static_cast<uint32_t>(round(width * dpi / DEFAULT_DPI)), bitmapSize.Width);
Assert::AreEqual(static_cast<uint32_t>(round(height * dpi / DEFAULT_DPI)), bitmapSize.Height);
}
};
TEST_CLASS(CanvasImageSourceCreateDrawingSessionTests)
{
struct Fixture
{
ComPtr<StubCanvasDevice> m_canvasDevice;
ComPtr<MockSurfaceImageSource> m_surfaceImageSource;
ComPtr<StubSurfaceImageSourceFactory> m_surfaceImageSourceFactory;
std::shared_ptr<MockCanvasImageSourceDrawingSessionFactory> m_canvasImageSourceDrawingSessionFactory;
ComPtr<CanvasImageSource> m_canvasImageSource;
int m_imageWidth;
int m_imageHeight;
Color m_anyColor;
Fixture(float dpi = DEFAULT_DPI)
{
m_canvasDevice = Make<StubCanvasDevice>();
m_surfaceImageSource = Make<MockSurfaceImageSource>();
m_surfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(m_surfaceImageSource.Get());
m_canvasImageSourceDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>();
m_surfaceImageSource->SetDeviceMethod.AllowAnyCall();
m_imageWidth = 123;
m_imageHeight = 456;
m_canvasImageSource = Make<CanvasImageSource>(
m_canvasDevice.Get(),
(float)m_imageWidth,
(float)m_imageHeight,
dpi,
CanvasAlphaMode::Premultiplied,
m_surfaceImageSourceFactory.Get(),
m_canvasImageSourceDrawingSessionFactory);
m_surfaceImageSource->SetDeviceMethod.SetExpectedCalls(0);
m_anyColor = Color{ 1, 2, 3, 4 };
}
};
TEST_METHOD_EX(CanvasImageSource_CreateDrawingSession_PassesEntireImage)
{
Fixture f;
f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(1,
[&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const& updateRect, float)
{
Rect expectedRect{ 0, 0, static_cast<float>(f.m_imageWidth), static_cast<float>(f.m_imageHeight) };
Assert::AreEqual(expectedRect, updateRect);
return Make<MockCanvasDrawingSession>();
});
ComPtr<ICanvasDrawingSession> drawingSession;
ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSession(f.m_anyColor, &drawingSession));
Assert::IsTrue(drawingSession);
}
TEST_METHOD_EX(CanvasImageSource_CreateDrawingSessionWithUpdateRegion_PassesSpecifiedUpdateRegion)
{
Fixture f;
Rect expectedRect{ 1, 2, 3, 4 };
f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(1,
[&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const& updateRect, float)
{
Assert::AreEqual(expectedRect, updateRect);
return Make<MockCanvasDrawingSession>();
});
ComPtr<ICanvasDrawingSession> drawingSession;
ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSessionWithUpdateRectangle(f.m_anyColor, expectedRect, &drawingSession));
Assert::IsTrue(drawingSession);
}
TEST_METHOD_EX(CanvasImageSource_CreateDrawingSession_PassesClearColor)
{
Fixture f;
int32_t anyLeft = 1;
int32_t anyTop = 2;
int32_t anyWidth = 3;
int32_t anyHeight = 4;
Color expectedColor{ 1, 2, 3, 4 };
f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(2,
[&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const& clearColor, Rect const&, float)
{
Assert::AreEqual(expectedColor, clearColor);
return Make<MockCanvasDrawingSession>();
});
ComPtr<ICanvasDrawingSession> ignoredDrawingSession;
ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSession(expectedColor, &ignoredDrawingSession));
ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSessionWithUpdateRectangle(expectedColor, Rect{ (float)anyLeft, (float)anyTop, (float)anyWidth, (float)anyHeight }, &ignoredDrawingSession));
}
};
TEST_CLASS(CanvasImageSourceDrawingSessionFactoryTests)
{
public:
TEST_METHOD_EX(CanvasImageSourceDrawingSessionFactory_CallsBeginDrawWithCorrectUpdateRectangle)
{
auto drawingSessionFactory = std::make_shared<CanvasImageSourceDrawingSessionFactory>();
auto surfaceImageSource = Make<MockSurfaceImageSource>();
float dpi = 123.0f;
Rect updateRectangleInDips{ 10, 20, 30, 40 };
RECT expectedUpdateRectangle = ToRECT(updateRectangleInDips, dpi);
surfaceImageSource->BeginDrawMethod.SetExpectedCalls(1,
[&] (RECT const& updateRectangle, IID const& iid, void** updateObject, POINT*)
{
Assert::AreEqual(expectedUpdateRectangle, updateRectangle);
auto dc = Make<StubD2DDeviceContext>(nullptr);
dc->SetTransformMethod.AllowAnyCall();
return dc.CopyTo(iid, updateObject);
});
surfaceImageSource->EndDrawMethod.SetExpectedCalls(1);
Color anyClearColor{ 1,2,3,4 };
drawingSessionFactory->Create(
Make<MockCanvasDevice>().Get(),
As<ISurfaceImageSourceNativeWithD2D>(surfaceImageSource).Get(),
std::make_shared<bool>(),
anyClearColor,
updateRectangleInDips,
dpi);
}
};
TEST_CLASS(CanvasImageSourceDrawingSessionAdapterTests)
{
public:
TEST_METHOD_EX(CanvasImageSourceDrawingSessionAdapter_BeginEndDraw)
{
auto mockDeviceContext = Make<MockD2DDeviceContext>();
auto mockSurfaceImageSource = Make<MockSurfaceImageSource>();
RECT expectedUpdateRect{ 1, 2, 3, 4 };
POINT beginDrawOffset{ 5, 6 };
D2D1_COLOR_F expectedClearColor{ 7, 8, 9, 10 };
D2D1_POINT_2F expectedOffset{
static_cast<float>(beginDrawOffset.x - expectedUpdateRect.left),
static_cast<float>(beginDrawOffset.y - expectedUpdateRect.top) };
mockSurfaceImageSource->BeginDrawMethod.SetExpectedCalls(1,
[&](RECT const& updateRect, IID const& iid, void** updateObject, POINT* offset)
{
Assert::AreEqual(expectedUpdateRect, updateRect);
Assert::AreEqual(_uuidof(ID2D1DeviceContext), iid);
HRESULT hr = mockDeviceContext.CopyTo(iid, updateObject);
*offset = beginDrawOffset;
return hr;
});
mockDeviceContext->ClearMethod.SetExpectedCalls(1,
[&](D2D1_COLOR_F const* color)
{
Assert::AreEqual(expectedClearColor, *color);
});
mockDeviceContext->SetTransformMethod.SetExpectedCalls(1,
[&](const D2D1_MATRIX_3X2_F* m)
{
Assert::AreEqual(1.0f, m->_11);
Assert::AreEqual(0.0f, m->_12);
Assert::AreEqual(0.0f, m->_21);
Assert::AreEqual(1.0f, m->_22);
Assert::AreEqual(expectedOffset.x, m->_31);
Assert::AreEqual(expectedOffset.y, m->_32);
});
mockDeviceContext->SetDpiMethod.SetExpectedCalls(1,
[&](float dpiX, float dpiY)
{
Assert::AreEqual(DEFAULT_DPI, dpiX);
Assert::AreEqual(DEFAULT_DPI, dpiY);
});
ComPtr<ID2D1DeviceContext1> actualDeviceContext;
D2D1_POINT_2F actualOffset;
auto adapter = CanvasImageSourceDrawingSessionAdapter::Create(
mockSurfaceImageSource.Get(),
expectedClearColor,
expectedUpdateRect,
DEFAULT_DPI,
&actualDeviceContext,
&actualOffset);
Assert::AreEqual<ID2D1DeviceContext1*>(mockDeviceContext.Get(), actualDeviceContext.Get());
Assert::AreEqual(expectedOffset, actualOffset);
mockSurfaceImageSource->EndDrawMethod.SetExpectedCalls(1);
adapter->EndDraw(actualDeviceContext.Get());
}
struct DeviceContextWithRestrictedQI : public MockD2DDeviceContext
{
//
// Restrict this device context implementation so that it can only be
// QI'd for ID2D1DeviceContext.
//
STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppvObject)
{
if (riid == __uuidof(ID2D1DeviceContext))
return RuntimeClass::QueryInterface(riid, ppvObject);
return E_NOINTERFACE;
}
};
TEST_METHOD_EX(CanvasImageSourceDrawingSessionAdapter_When_SisNative_Gives_Unusuable_DeviceContext_Then_EndDraw_Called)
{
auto sis = Make<MockSurfaceImageSource>();
sis->BeginDrawMethod.SetExpectedCalls(1,
[&](RECT const&, IID const& iid, void** obj, POINT*)
{
auto deviceContext = Make<DeviceContextWithRestrictedQI>();
return deviceContext.CopyTo(iid, obj);
});
sis->EndDrawMethod.SetExpectedCalls(1);
//
// We expect creating the adapter to fail since our SurfaceImageSource
// implementation returns a device context that only implements
// ID2D1DeviceContext.
//
// If this happens we expect BeginDraw to have been called. Then, after
// the failure, we expect EndDraw to have been called in order to clean
// up properly.
//
ComPtr<ID2D1DeviceContext1> actualDeviceContext;
D2D1_POINT_2F actualOffset;
ExpectHResultException(E_NOINTERFACE,
[&]
{
CanvasImageSourceDrawingSessionAdapter::Create(
sis.Get(),
D2D1_COLOR_F{ 1, 2, 3, 4 },
RECT{ 1, 2, 3, 4 },
DEFAULT_DPI,
&actualDeviceContext,
&actualOffset);
});
}
};
| 39.548148 | 199 | 0.65132 |
75ca9fb4e04ff2b0e4d7b0b143bed3015cae2e6c | 595 | cc | C++ | src/Candle.cc | carolinavillam/Lucky-Monkey | 5ddbadf6c604ea00c3384cc42eda9033d6297e7e | [
"MIT"
] | null | null | null | src/Candle.cc | carolinavillam/Lucky-Monkey | 5ddbadf6c604ea00c3384cc42eda9033d6297e7e | [
"MIT"
] | null | null | null | src/Candle.cc | carolinavillam/Lucky-Monkey | 5ddbadf6c604ea00c3384cc42eda9033d6297e7e | [
"MIT"
] | null | null | null | #include "Candle.hh"
Candle::Candle(const char* textureUrl, sf::Vector2f position,
float scale, float width, float height, int col, int row,
sf::RenderWindow*& window, b2World*& world) :
GameObject(textureUrl, position, scale, width, height, col, row, b2BodyType::b2_staticBody, window, world)
{
animationsManager = new AnimationsManager();
animationsManager->AddAnimation("idle", new Animation("assets/animations/candle/idle2.anim", drawable));
}
Candle::~Candle()
{
}
void Candle::Update(float& deltaTime)
{
animationsManager->Update(deltaTime);
animationsManager->Play("idle");
} | 27.045455 | 106 | 0.744538 |
75cbdb9e5c961527d2241b0d02724dd87a66ba54 | 127 | cpp | C++ | Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp | dakitten2358/coopgame | 660293ce381d55025e4654ff448faf6a71a69bd2 | [
"Apache-2.0"
] | 1 | 2018-11-21T21:35:21.000Z | 2018-11-21T21:35:21.000Z | Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp | dakitten2358/coopgame | 660293ce381d55025e4654ff448faf6a71a69bd2 | [
"Apache-2.0"
] | 1 | 2017-05-13T12:21:22.000Z | 2017-05-13T12:24:39.000Z | Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp | dakitten2358/coopgame | 660293ce381d55025e4654ff448faf6a71a69bd2 | [
"Apache-2.0"
] | 1 | 2017-03-29T17:05:50.000Z | 2017-03-29T17:05:50.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "NativeEnemyPlayerStart.h"
| 15.875 | 79 | 0.732283 |
75cec848908939229603502e222c52e38afa93d2 | 475 | cpp | C++ | lectures/containers/code/list_example2.cpp | ahurta92/ams562-notes | e66baa1e50654e125902651f388d45cb32c81f00 | [
"MIT"
] | 1 | 2021-09-01T19:09:54.000Z | 2021-09-01T19:09:54.000Z | lectures/containers/code/list_example2.cpp | ahurta92/ams562-notes | e66baa1e50654e125902651f388d45cb32c81f00 | [
"MIT"
] | null | null | null | lectures/containers/code/list_example2.cpp | ahurta92/ams562-notes | e66baa1e50654e125902651f388d45cb32c81f00 | [
"MIT"
] | 1 | 2021-11-30T19:26:02.000Z | 2021-11-30T19:26:02.000Z | //
// Created by adrian on 11/6/21.
//
#include <list>
#include "examples.h"
int get_number(const string& s, const list<Entry>& phone_book)
{
for(auto p=phone_book.begin();p!=phone_book.end();++p)
if(p->name == s)
return p->number;
return 0; // number not found
}
int main()
{
list<Entry> contacts = {
{"Adrian Hurtado", 1234567}, {"Stella Salina", 1223442}, {"Johnny Z", 2323232}};
int num = get_number("Adrian Hurtado", contacts);
cout<<"my number: "<<num;
}
| 21.590909 | 82 | 0.646316 |
75d056890b4cd47c1a4666a5a68f2035ec6f7d31 | 2,757 | cpp | C++ | src/cli/argparse.cpp | NHollmann/CmdPathtracer | 6c6c0382948bb6ea547458f743937b70c090ca6c | [
"MIT"
] | null | null | null | src/cli/argparse.cpp | NHollmann/CmdPathtracer | 6c6c0382948bb6ea547458f743937b70c090ca6c | [
"MIT"
] | null | null | null | src/cli/argparse.cpp | NHollmann/CmdPathtracer | 6c6c0382948bb6ea547458f743937b70c090ca6c | [
"MIT"
] | null | null | null | #include "argparse.hpp"
#include <iostream>
#include "cxxopts.hpp"
namespace cli
{
RaytracerOptions parseArguments(int argc, char *argv[])
{
RaytracerOptions raytracerOptions;
cxxopts::Options options(argv[0], "A toy raytracer by Nicolas Hollmann.");
options.add_options("General")
("help", "Print help");
options.add_options("IO")
("o,output", "Output filename", cxxopts::value<std::string>()->default_value("out.ppm"), "file")
("f,format", "Output format", cxxopts::value<std::string>()->default_value("ppm"), "format");
options.add_options("Raytracer")
("w,width", "Width of the target image", cxxopts::value<int>()->default_value("200"), "width")
("h,height", "Height of the target image", cxxopts::value<int>()->default_value("100"), "height")
("s,samples", "Samples per pixel", cxxopts::value<int>()->default_value("100"), "samples")
("d,depth", "Max ray depth", cxxopts::value<int>()->default_value("50"), "depth");
options.add_options("Multithreading")
("p,parallel", "Enables multithreading")
("t,threads", "Sets the thread count, 0 for auto", cxxopts::value<unsigned int>()->default_value("0"), "threads")
("blocksize", "Sets the size of a thread block", cxxopts::value<unsigned int>()->default_value("16"), "size");
options.add_options("Scene")
("world", "The world to render", cxxopts::value<std::string>()->default_value("random"), "world");
try {
auto result = options.parse(argc, argv);
if (result.count("help"))
{
std::cout << options.help() << std::endl;
exit(0);
}
raytracerOptions.width = result["width"].as<int>();
raytracerOptions.height = result["height"].as<int>();
raytracerOptions.samples = result["samples"].as<int>();
raytracerOptions.depth = result["depth"].as<int>();
raytracerOptions.filename = result["output"].as<std::string>();
raytracerOptions.format = result["format"].as<std::string>();
raytracerOptions.multithreading = result.count("parallel") != 0;
raytracerOptions.threadCount = result["threads"].as<unsigned int>();
raytracerOptions.blockSize = result["blocksize"].as<unsigned int>();
raytracerOptions.world = result["world"].as<std::string>();
}
catch (const cxxopts::OptionException& e)
{
std::cerr << "Error parsing options: " << e.what() << std::endl;
exit(1);
}
return raytracerOptions;
}
}
| 41.149254 | 125 | 0.571999 |
75d319b0e4c0901e9010627776cd4a3d52708e83 | 1,638 | cpp | C++ | components/physics/scene_physics/tests/fall.cpp | untgames/funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 7 | 2016-03-30T17:00:39.000Z | 2017-03-27T16:04:04.000Z | components/physics/scene_physics/tests/fall.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2017-11-21T11:25:49.000Z | 2018-09-20T17:59:27.000Z | components/physics/scene_physics/tests/fall.cpp | untgames/Funner | c91614cda55fd00f5631d2bd11c4ab91f53573a3 | [
"MIT"
] | 4 | 2016-11-29T15:18:40.000Z | 2017-03-27T16:04:08.000Z | #include "shared.h"
using namespace scene_graph::controllers;
int main ()
{
printf ("Results of fall_test:\n");
try
{
PhysicsManager manager (DRIVER_NAME);
physics::Scene* scene (new physics::Scene (manager.CreateScene ()));
Shape sphere_shape (manager.CreateSphereShape (1.f));
RigidBody body (scene->CreateRigidBody (sphere_shape, 1));
Node::Pointer node (Node::Create ());
printf ("Initial state:\n");
dump_body_position (body);
dump_node_position (*node);
printf ("Simulating one second, attach controller\n");
scene->PerformSimulation (1.f);
SyncPhysicsToNode::Pointer controller (SyncPhysicsToNode::Create (*node, body));
dump_body_position (body);
dump_node_position (*node);
node->Update (TimeValue (0, 10));
printf ("Update node\n");
node->Update (TimeValue (1, 10));
dump_node_position (*node);
printf ("Simulating one second\n");
scene->PerformSimulation (1.f);
dump_body_position (body);
dump_node_position (*node);
printf ("Update node\n");
node->Update (TimeValue (2, 10));
dump_node_position (*node);
printf ("Update node\n");
node->Update (TimeValue (3, 10));
dump_node_position (*node);
printf ("Simulating one second, detach controller\n");
scene->PerformSimulation (1.f);
controller->Detach ();
dump_body_position (body);
dump_node_position (*node);
}
catch (std::exception& exception)
{
printf ("exception: %s\n", exception.what ());
}
return 0;
}
| 21.552632 | 85 | 0.614774 |
75d5469ea85f516ebf9dfddb8943c424e37f1606 | 351 | cc | C++ | src/kernel/core/class.cc | cmejj/How-to-Make-a-Computer-Operating-System | eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687 | [
"Apache-2.0"
] | 16,500 | 2015-01-01T00:47:42.000Z | 2022-03-31T17:12:02.000Z | src/kernel/core/class.cc | yongpingkan/How-to-Make-a-Computer-Operating-System | eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687 | [
"Apache-2.0"
] | 66 | 2015-01-08T15:22:11.000Z | 2021-12-16T09:04:37.000Z | src/kernel/core/class.cc | yongpingkan/How-to-Make-a-Computer-Operating-System | eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687 | [
"Apache-2.0"
] | 3,814 | 2015-01-01T12:42:31.000Z | 2022-03-31T14:26:50.000Z | #include <os.h>
/*
Static objects
*/
Io io; /* Input/Output interface */
Architecture arch; /* Cpu and architecture interface */
Vmm vmm; /* Virtual memory manager interface */
Filesystem fsm; /* Filesystem interface */
Module modm; /* Module manager */
Syscalls syscall; /* Syscalls manager */
System sys; /* System manager */
| 25.071429 | 57 | 0.660969 |
75d71582fb69f38016470062819df7410ac3b096 | 4,166 | cpp | C++ | test/Test1.cpp | LukasBanana/MercuriusLib | 0b80c49b52a166a4a5490f3044c64f4a8895d9ae | [
"BSD-3-Clause"
] | 1 | 2017-04-23T04:04:25.000Z | 2017-04-23T04:04:25.000Z | test/Test1.cpp | LukasBanana/MercuriusLib | 0b80c49b52a166a4a5490f3044c64f4a8895d9ae | [
"BSD-3-Clause"
] | null | null | null | test/Test1.cpp | LukasBanana/MercuriusLib | 0b80c49b52a166a4a5490f3044c64f4a8895d9ae | [
"BSD-3-Clause"
] | null | null | null | /*
* Test1.cpp
*
* This file is part of the "MercuriusLib" project (Copyright (c) 2017 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <Merc/Merc.h>
#include <iostream>
#include <cstdlib>
static void PrintHostAddresses(const std::string& hostName)
{
try
{
auto addresses = Mc::IPAddress::QueryAddressesFromHost(hostName);
std::cout << "addresses of host \"" << hostName << "\":" << std::endl;
if (!addresses.empty())
{
for (const auto& addr : addresses)
std::cout << " " << addr->ToString() << std::endl;
}
else
std::cout << " <none>" << std::endl;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
static void PrintNetworkAdapter(const Mc::NetworkAdapter& adapter, std::size_t idx)
{
std::cout << "network adapter " << (idx++) << ':' << std::endl;
std::cout << " type = " << Mc::ToString(adapter.type) << std::endl;
std::cout << " description = " << adapter.description << std::endl;
std::cout << " addressName = " << adapter.addressName << std::endl;
std::cout << " subnetMask = " << adapter.subnetMask << std::endl;
std::cout << " active = " << std::boolalpha << adapter.active << std::endl;
std::cout << " broadcast = " << adapter.BroadcastAddress()->ToString() << std::endl;
}
int main()
{
try
{
Mc::NetworkSystem net;
// Print network adapters
auto adapters = net.QueryAdapters();
std::size_t adaptersIdx = 0;
for (const auto& adapter : adapters)
PrintNetworkAdapter(adapter, adaptersIdx);
// Sort addresses
std::vector<std::unique_ptr<Mc::IPAddress>> address;
for (const auto& adapter : adapters)
address.emplace_back(Mc::IPAddress::MakeIPv4(0, adapter.addressName));
std::cout << "unsorted addresses:" << std::endl;
for (const auto& addr : address)
std::cout << " " << addr->ToString() << std::endl;
std::sort(
address.begin(), address.end(),
[](const std::unique_ptr<Mc::IPAddress>& lhs, const std::unique_ptr<Mc::IPAddress>& rhs)
{
return (*lhs > *rhs);
}
);
std::cout << "sorted addresses:" << std::endl;
for (const auto& addr : address)
std::cout << " " << addr->ToString() << std::endl;
// Print some IP addresses
auto addrLocalhost = Mc::IPAddress::MakeIPv4Localhost();
std::cout << "localhost = " << addrLocalhost->ToString() << std::endl;
//PrintHostAddresses("www.google.com");
PrintHostAddresses("www.google.de");
PrintHostAddresses("www.google.ch");
PrintHostAddresses("localhost");
PrintHostAddresses("www.facebook.com");
PrintHostAddresses("www.facebook.de");
// Send HTTP GET request to server
auto addrGoogle = Mc::IPAddress::QueryAddressesFromHost("www.google.com");
if (!addrGoogle.empty())
{
auto& addr = addrGoogle.front();
addr->Port(80);
auto sock = Mc::TCPSocket::Make(Mc::AddressFamily::IPv4);
sock->Connect(*addr);
std::string getRequest = "GET /index.html HTTP/1.1\r\nHost: www.google.com\r\n\r\n";
sock->Send(getRequest.c_str(), static_cast<int>(getRequest.size() + 1));
char getResponse[513];
while (true)
{
auto len = sock->Recv(getResponse, 512);
if (len > 0)
{
getResponse[len] = 0;
std::cout << getResponse;
}
else
{
std::cout << "\n\n";
break;
}
}
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
#ifdef _WIN32
system("pause");
#endif
return 0;
}
// ================================================================================
| 29.971223 | 100 | 0.512242 |
75d82e7e884119071ba9f0788cfc53d8daeb94c3 | 272 | cpp | C++ | deprecated_old_files/deprecated_workspace_pkgs/my_stage/src/run_stopper.cpp | Torreshan/TurtleBot | c6ae948364f82f505581dad2ee2dceb95fdcfba8 | [
"MIT"
] | 1 | 2019-01-31T13:13:03.000Z | 2019-01-31T13:13:03.000Z | deprecated_old_files/deprecated_workspace_pkgs/my_stage/src/run_stopper.cpp | Torreshan/TurtleBot | c6ae948364f82f505581dad2ee2dceb95fdcfba8 | [
"MIT"
] | null | null | null | deprecated_old_files/deprecated_workspace_pkgs/my_stage/src/run_stopper.cpp | Torreshan/TurtleBot | c6ae948364f82f505581dad2ee2dceb95fdcfba8 | [
"MIT"
] | 1 | 2019-01-14T16:24:05.000Z | 2019-01-14T16:24:05.000Z | #include <ros/ros.h>
#include "stopper.h"
int main(int argc, char **argv) {
// Initiate new ROS node named "stopper"
ros::init(argc, argv, "stopper");
// Create new stopper object
Stopper stopper;
// Start the movement
stopper.startMoving();
return 0;
}
| 17 | 42 | 0.661765 |
75da9c1ef3d420e1a32e810b0fe0b90c6f564e25 | 2,588 | hh | C++ | sdd/mem/cache_entry.hh | tic-toc/libsdd | 5c3deb43523d062929f169c3d7a301240f0fb811 | [
"BSD-2-Clause"
] | 6 | 2015-03-21T19:21:29.000Z | 2022-01-29T01:20:28.000Z | sdd/mem/cache_entry.hh | tic-toc/libsdd | 5c3deb43523d062929f169c3d7a301240f0fb811 | [
"BSD-2-Clause"
] | 1 | 2017-02-05T23:39:44.000Z | 2017-02-05T23:40:04.000Z | libsdd/sdd/mem/cache_entry.hh | kyouko-taiga/SwiftSDD | 9312160e0fac5fef6e605c9e74c543ded9708e54 | [
"MIT"
] | 3 | 2016-05-13T14:39:06.000Z | 2019-08-09T20:13:39.000Z | /// @file
/// @copyright The code is licensed under the BSD License
/// <http://opensource.org/licenses/BSD-2-Clause>,
/// Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once
#include <functional> // hash
#include <list>
#include <utility> // forward
#include "sdd/mem/hash_table.hh"
#include "sdd/mem/lru_list.hh"
#include "sdd/util/hash.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Associate an operation to its result into the cache.
///
/// The operation acts as a key and the associated result is the value counterpart.
template <typename Operation, typename Result>
struct cache_entry
{
// Can't copy a cache_entry.
cache_entry(const cache_entry&) = delete;
cache_entry& operator=(const cache_entry&) = delete;
/// @brief
mem::intrusive_member_hook<cache_entry> hook;
/// @brief The cached operation.
const Operation operation;
/// @brief The result of the evaluation of operation.
const Result result;
/// @brief Where this cache entry is stored in the LRU list.
typename lru_list<cache_entry>::const_iterator lru_cit_;
/// @brief Constructor.
template <typename... Args>
cache_entry(Operation&& op, Args&&... args)
: hook()
, operation(std::move(op))
, result(std::forward<Args>(args)...)
, lru_cit_()
{}
/// @brief Cache entries are only compared using their operations.
friend
bool
operator==(const cache_entry& lhs, const cache_entry& rhs)
noexcept
{
return lhs.operation == rhs.operation;
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
template <typename Operation, typename Result>
struct hash<sdd::mem::cache_entry<Operation, Result>>
{
std::size_t
operator()(const sdd::mem::cache_entry<Operation, Result>& x)
{
using namespace sdd::hash;
// A cache entry must have the same hash as its contained operation. Otherwise, cache::erase()
// and cache::insert_check()/cache::insert_commit() won't use the same position in buckets.
return seed(x.operation);
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
/*------------------------------------------------------------------------------------------------*/
| 28.755556 | 100 | 0.553323 |
75de7ce582992113a81de3160bf4152d196ac7d8 | 71,675 | cpp | C++ | tcs/sam_mw_gen_Type260.cpp | gjsoto/ssc | 70ef4fdafb9afe0418a9c552485a7116a1b3a743 | [
"BSD-3-Clause"
] | 61 | 2017-08-09T15:10:59.000Z | 2022-02-15T21:45:31.000Z | tcs/sam_mw_gen_Type260.cpp | gjsoto/ssc | 70ef4fdafb9afe0418a9c552485a7116a1b3a743 | [
"BSD-3-Clause"
] | 462 | 2017-07-31T21:26:46.000Z | 2022-03-30T22:53:50.000Z | tcs/sam_mw_gen_Type260.cpp | gjsoto/ssc | 70ef4fdafb9afe0418a9c552485a7116a1b3a743 | [
"BSD-3-Clause"
] | 73 | 2017-08-24T17:39:31.000Z | 2022-03-28T08:37:47.000Z | #define _TCSTYPEINTERFACE_
#include "tcstype.h"
//#include "htf_props.h"
#include "sam_csp_util.h"
#include <cmath>
using namespace std;
/*
************************************************************************
Object: Generic solar model
Simulation Studio Model: Type260
Author: Michael J. Wagner
Date: May 29, 2013
COPYRIGHT 2013 NATIONAL RENEWABLE ENERGY LABORATORY
*/
enum{
//parameters and inputs
P_LATITUDE,
P_LONGITUDE,
P_TIMEZONE,
P_THETA_STOW,
P_THETA_DEP,
P_INTERP_ARR,
P_RAD_TYPE,
P_SOLARM,
P_T_SFDES,
P_IRR_DES,
P_ETA_OPT_SOIL,
P_ETA_OPT_GEN,
P_F_SFHL_REF,
P_SFHLQ_COEFS,
P_SFHLT_COEFS,
P_SFHLV_COEFS,
P_QSF_DES,
P_W_DES,
P_ETA_DES,
P_F_WMAX,
P_F_WMIN,
P_F_STARTUP,
P_ETA_LHV,
P_ETAQ_COEFS,
P_ETAT_COEFS,
P_T_PCDES,
P_PC_T_CORR,
P_F_WPAR_FIXED,
P_F_WPAR_PROD,
P_WPAR_PRODQ_COEFS,
P_WPAR_PRODT_COEFS,
P_HRS_TES,
P_F_CHARGE,
P_F_DISCH,
P_F_ETES_0,
P_F_TESHL_REF,
P_TESHLX_COEFS,
P_TESHLT_COEFS,
P_NTOD,
//P_TOD_SCHED,
P_DISWS,
P_DISWOS,
P_QDISP,
P_FDISP,
P_ISTABLEUNSORTED,
P_OPTICALTABLE,
//P_OPTICALTABLEUNS,
I_IBN,
I_IBH,
I_ITOTH,
I_TDB,
I_TWB,
I_VWIND,
I_TOUPeriod,
O_IRR_USED,
O_HOUR_OF_DAY,
O_DAY_OF_YEAR,
O_DECLINATION,
O_SOLTIME,
O_HRANGLE,
O_SOLALT,
O_SOLAZ,
O_ETA_OPT_SF,
O_F_SFHL_QDNI,
O_F_SFHL_TAMB,
O_F_SFHL_VWIND,
O_Q_HL_SF,
O_Q_SF,
O_Q_INC,
O_PBMODE,
O_PBSTARTF,
O_Q_TO_PB,
O_Q_STARTUP,
O_Q_TO_TES,
O_Q_FROM_TES,
O_E_IN_TES,
O_Q_HL_TES,
O_Q_DUMP_TESFULL,
O_Q_DUMP_TESCHG,
O_Q_DUMP_UMIN,
O_Q_DUMP_TOT,
O_Q_FOSSIL,
O_Q_GAS,
O_F_EFFPC_QTPB,
O_F_EFFPC_TAMB,
O_ETA_CYCLE,
O_W_GR_SOLAR,
O_W_GR_FOSSIL,
O_W_GR,
O_W_PAR_FIXED,
O_W_PAR_PROD,
O_W_PAR_TOT,
O_W_PAR_ONLINE,
O_W_PAR_OFFLINE,
O_ENET,
//Include N_max
N_MAX
};
tcsvarinfo sam_mw_gen_type260_variables[] = {
{ TCS_PARAM, TCS_NUMBER, P_LATITUDE, "latitude", "Site latitude", "deg", "", "", "35" },
{ TCS_PARAM, TCS_NUMBER, P_LONGITUDE, "longitude", "Site longitude", "deg", "", "", "-117" },
{ TCS_PARAM, TCS_NUMBER, P_TIMEZONE, "timezone", "Site timezone", "hr", "", "", "-8" },
{ TCS_PARAM, TCS_NUMBER, P_THETA_STOW, "theta_stow", "Solar elevation angle at which the solar field stops operating", "deg", "", "", "170" },
{ TCS_PARAM, TCS_NUMBER, P_THETA_DEP, "theta_dep", "Solar elevation angle at which the solar field begins operating", "deg", "", "", "10" },
{ TCS_PARAM, TCS_NUMBER, P_INTERP_ARR, "interp_arr", "Interpolate the array or find nearest neighbor? (1=interp,2=no)", "none", "", "", "1" },
{ TCS_PARAM, TCS_NUMBER, P_RAD_TYPE, "rad_type", "Solar resource radiation type (1=DNI,2=horiz.beam,3=tot.horiz)", "none", "", "", "1" },
{ TCS_PARAM, TCS_NUMBER, P_SOLARM, "solarm", "Solar multiple", "none", "", "", "2" },
{ TCS_PARAM, TCS_NUMBER, P_T_SFDES, "T_sfdes", "Solar field design point temperature (dry bulb)", "C", "", "", "25" },
{ TCS_PARAM, TCS_NUMBER, P_IRR_DES, "irr_des", "Irradiation design point", "W/m2", "", "", "950" },
{ TCS_PARAM, TCS_NUMBER, P_ETA_OPT_SOIL, "eta_opt_soil", "Soiling optical derate factor", "none", "", "", "0.95" },
{ TCS_PARAM, TCS_NUMBER, P_ETA_OPT_GEN, "eta_opt_gen", "General/other optical derate", "none", "", "", "0.99" },
{ TCS_PARAM, TCS_NUMBER, P_F_SFHL_REF, "f_sfhl_ref", "Reference solar field thermal loss fraction", "MW/MWcap", "", "", "0.071591" },
{ TCS_PARAM, TCS_ARRAY, P_SFHLQ_COEFS, "sfhlQ_coefs", "Irr-based solar field thermal loss adjustment coefficients", "1/MWt", "", "", "1,-0.1,0,0" },
{ TCS_PARAM, TCS_ARRAY, P_SFHLT_COEFS, "sfhlT_coefs", "Temp.-based solar field thermal loss adjustment coefficients", "1/C", "", "", "1,0.005,0,0" },
{ TCS_PARAM, TCS_ARRAY, P_SFHLV_COEFS, "sfhlV_coefs", "Wind-based solar field thermal loss adjustment coefficients", "1/(m/s)", "", "", "1,0.01,0,0" },
{ TCS_PARAM, TCS_NUMBER, P_QSF_DES, "qsf_des", "Solar field thermal production at design", "MWt", "", "", "628" },
{ TCS_PARAM, TCS_NUMBER, P_W_DES, "w_des", "Design power cycle gross output", "MWe", "", "", "110" },
{ TCS_PARAM, TCS_NUMBER, P_ETA_DES, "eta_des", "Design power cycle gross efficiency", "none", "", "", "0.35" },
{ TCS_PARAM, TCS_NUMBER, P_F_WMAX, "f_wmax", "Maximum over-design power cycle operation fraction", "none", "", "", "1.05" },
{ TCS_PARAM, TCS_NUMBER, P_F_WMIN, "f_wmin", "Minimum part-load power cycle operation fraction", "none", "", "", "0.25" },
{ TCS_PARAM, TCS_NUMBER, P_F_STARTUP, "f_startup", "Equivalent full-load hours required for power system startup", "hours", "", "", "0.2" },
{ TCS_PARAM, TCS_NUMBER, P_ETA_LHV, "eta_lhv", "Fossil backup lower heating value efficiency", "none", "", "", "0.9" },
{ TCS_PARAM, TCS_ARRAY, P_ETAQ_COEFS, "etaQ_coefs", "Part-load power conversion efficiency adjustment coefficients", "1/MWt", "", "","0.9,0.1,0,0,0" },
{ TCS_PARAM, TCS_ARRAY, P_ETAT_COEFS, "etaT_coefs", "Temp.-based power conversion efficiency adjustment coefs.", "1/C", "", "","1,-0.002,0,0,0" },
{ TCS_PARAM, TCS_NUMBER, P_T_PCDES, "T_pcdes", "Power conversion reference temperature", "C", "", "", "21" },
{ TCS_PARAM, TCS_NUMBER, P_PC_T_CORR, "PC_T_corr", "Power conversion temperature correction mode (1=wetb, 2=dryb)", "none", "", "", "1" },
{ TCS_PARAM, TCS_NUMBER, P_F_WPAR_FIXED, "f_Wpar_fixed", "Fixed capacity-based parasitic loss fraction", "MWe/MWcap", "", "", "0.0055" },
{ TCS_PARAM, TCS_NUMBER, P_F_WPAR_PROD, "f_Wpar_prod", "Production-based parasitic loss fraction", "MWe/MWe", "", "", "0.08" },
{ TCS_PARAM, TCS_ARRAY, P_WPAR_PRODQ_COEFS, "Wpar_prodQ_coefs", "Part-load production parasitic adjustment coefs.", "1/MWe", "", "", "1,0,0,0" },
{ TCS_PARAM, TCS_ARRAY, P_WPAR_PRODT_COEFS, "Wpar_prodT_coefs", "Temp.-based production parasitic adjustment coefs.", "1/C", "", "", "1,0,0,0" },
{ TCS_PARAM, TCS_NUMBER, P_HRS_TES, "hrs_tes", "Equivalent full-load hours of storage", "hours", "", "", "6" },
{ TCS_PARAM, TCS_NUMBER, P_F_CHARGE, "f_charge", "Storage charging energy derate", "none", "", "", "0.98" },
{ TCS_PARAM, TCS_NUMBER, P_F_DISCH, "f_disch", "Storage discharging energy derate", "none", "", "", "0.98" },
{ TCS_PARAM, TCS_NUMBER, P_F_ETES_0, "f_etes_0", "Initial fractional charge level of thermal storage (0..1)", "none", "", "", "0.1" },
{ TCS_PARAM, TCS_NUMBER, P_F_TESHL_REF, "f_teshl_ref", "Reference heat loss from storage per max stored capacity","kWt/MWhr-stored", "", "", "0.35" },
{ TCS_PARAM, TCS_ARRAY, P_TESHLX_COEFS, "teshlX_coefs", "Charge-based thermal loss adjustment - constant coef.","1/MWhr-stored", "", "", "1,0,0,0" },
{ TCS_PARAM, TCS_ARRAY, P_TESHLT_COEFS, "teshlT_coefs", "Temp.-based thermal loss adjustment - constant coef.", "1/C", "", "", "1,0,0,0" },
{ TCS_PARAM, TCS_NUMBER, P_NTOD, "ntod", "Number of time-of-dispatch periods in the dispatch schedule", "none", "", "", "9" },
{ TCS_PARAM, TCS_ARRAY, P_DISWS, "disws", "Time-of-dispatch control for with-solar conditions", "none", "", "","0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1" },
{ TCS_PARAM, TCS_ARRAY, P_DISWOS, "diswos", "Time-of-dispatch control for without-solar conditions", "none", "", "","0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1" },
{ TCS_PARAM, TCS_ARRAY, P_QDISP, "qdisp", "TOD power output control factors", "none", "", "","1,1,1,1,1,1,1,1,1" },
{ TCS_PARAM, TCS_ARRAY, P_FDISP, "fdisp", "Fossil backup output control factors", "none", "", "","0,0,0,0,0,0,0,0,0" },
{ TCS_PARAM, TCS_NUMBER, P_ISTABLEUNSORTED, "istableunsorted", "Is optical table unsorted? (1=yes, 0=no)", "none", "", "", "0" },
{ TCS_PARAM, TCS_MATRIX, P_OPTICALTABLE, "OpticalTable", "Optical table", "none", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_IBN, "ibn", "Beam-normal (DNI) irradiation", "W/m2", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_IBH, "ibh", "Beam-horizontal irradiation", "W/m2", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_ITOTH, "itoth", "Total horizontal irradiation", "W/m2", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_TDB, "tdb", "Ambient dry-bulb temperature", "C", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_TWB, "twb", "Ambient wet-bulb temperature", "C", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_VWIND, "vwind", "Wind velocity", "m/s", "", "", "" },
{ TCS_INPUT, TCS_NUMBER, I_TOUPeriod, "TOUPeriod", "The time-of-use period", "", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_IRR_USED, "irr_used", "Irradiation value used in simulation", "W/m2", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_HOUR_OF_DAY, "hour_of_day", "Hour of the day", "hour", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_DAY_OF_YEAR, "day_of_year", "Day of the year", "day", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_DECLINATION, "declination", "Declination angle", "deg", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_SOLTIME, "soltime", "[hour] Solar time of the day", "hour", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_HRANGLE, "hrangle", "Hour angle", "deg", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_SOLALT, "solalt", "Solar elevation angle", "deg", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_SOLAZ, "solaz", "Solar azimuth angle (-180..180, 0deg=South)", "deg", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_ETA_OPT_SF, "eta_opt_sf", "Solar field optical efficiency", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_F_SFHL_QDNI, "f_sfhl_qdni", "Solar field load-based thermal loss correction", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_F_SFHL_TAMB, "f_sfhl_tamb", "Solar field temp.-based thermal loss correction", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_F_SFHL_VWIND, "f_sfhl_vwind", "Solar field wind-based thermal loss correction", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_HL_SF, "q_hl_sf", "Solar field thermal losses", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_SF, "q_sf", "Solar field delivered thermal power", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_INC, "q_inc", "Qdni - Solar incident energy, before all losses", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_PBMODE, "pbmode", "Power conversion mode", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_PBSTARTF, "pbstartf", "Flag indicating power system startup", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_TO_PB, "q_to_pb", "Thermal energy to the power conversion system", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_STARTUP, "q_startup", "Power conversion startup energy", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_TO_TES, "q_to_tes", "Thermal energy into storage", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_FROM_TES, "q_from_tes", "Thermal energy from storage", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_E_IN_TES, "e_in_tes", "Energy in storage", "MWt-hr", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_HL_TES, "q_hl_tes", "Thermal losses from storage", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_TESFULL, "q_dump_tesfull", "Dumped energy exceeding storage charge level max", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_TESCHG, "q_dump_teschg", "Dumped energy exceeding exceeding storage charge rate", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_UMIN, "q_dump_umin", "Dumped energy from falling below min. operation fraction", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_TOT, "q_dump_tot", "Total dumped energy", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_FOSSIL, "q_fossil", "thermal energy supplied from aux firing", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_Q_GAS, "q_gas", "Energy content of fuel required to supply Qfos", "MWt", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_F_EFFPC_QTPB, "f_effpc_qtpb", "Load-based conversion efficiency correction", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_F_EFFPC_TAMB, "f_effpc_tamb", "Temp-based conversion efficiency correction", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_ETA_CYCLE, "eta_cycle", "Adjusted power conversion efficiency", "none", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_GR_SOLAR, "w_gr_solar", "Power produced from the solar component", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_GR_FOSSIL, "w_gr_fossil", "Power produced from the fossil component", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_GR, "w_gr", "Total gross power production", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_PAR_FIXED, "w_par_fixed", "Fixed parasitic losses", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_PAR_PROD, "w_par_prod", "Production-based parasitic losses", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_PAR_TOT, "w_par_tot", "Total parasitic losses", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_PAR_ONLINE, "w_par_online", "Online parasitics", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_W_PAR_OFFLINE, "w_par_offline", "Offline parasitics", "MWe", "", "", "" },
{ TCS_OUTPUT, TCS_NUMBER, O_ENET, "enet", "Net electric output", "MWe", "", "", "" },
{ TCS_INVALID, TCS_INVALID, N_MAX, 0, 0, 0, 0, 0, 0 }
};
static const double zen_scale = 1.570781477;
static const double az_scale = 6.283125908;
class sam_mw_gen_type260 : public tcstypeinterface
{
private:
OpticalDataTable optical_table;
GaussMarkov *optical_table_uns;
//Constants for scaling GM table
double eff_scale; //defined later based on max value
double pi,Pi,d2r,r2d, g, mtoinch;
double latitude; //Site latitude
double longitude; //Site longitude
double timezone; //Site timezone
double theta_stow; //Solar elevation angle at which the solar field stops operating
double theta_dep; //Solar elevation angle at which the solar field begins operating
int interp_arr; //Interpolate the array or find nearest neighbor? (1=interp,2=no)
int rad_type; //Solar resource radiation type (1=DNI,2=horiz.beam,3=tot.horiz)
double solarm; //Solar multiple
double T_sfdes; //Solar field design point temperature (dry bulb)
double irr_des; //Irradiation design point
double eta_opt_soil; //Soiling optical derate factor
double eta_opt_gen; //General/other optical derate
double f_sfhl_ref; //Reference solar field thermal loss fraction
double* sfhlQ_coefs; //Irr-based solar field thermal loss adjustment coefficients
int nval_sfhlQ_coefs;
double* sfhlT_coefs; //Temp.-based solar field thermal loss adjustment coefficients
int nval_sfhlT_coefs;
double* sfhlV_coefs; //Wind-based solar field thermal loss adjustment coefficients
int nval_sfhlV_coefs;
double qsf_des; //Solar field thermal production at design
double w_des; //Design power cycle gross output
double eta_des; //Design power cycle gross efficiency
double f_wmax; //Maximum over-design power cycle operation fraction
double f_wmin; //Minimum part-load power cycle operation fraction
double f_startup; //Equivalent full-load hours required for power system startup
double eta_lhv; //Fossil backup lower heating value efficiency
double* etaQ_coefs; //Part-load power conversion efficiency adjustment coefficients
int nval_etaQ_coefs;
double* etaT_coefs; //Temp.-based power conversion efficiency adjustment coefs.
int nval_etaT_coefs;
double T_pcdes; //Power conversion reference temperature
double PC_T_corr; //Power conversion temperature correction mode (1=wetb, 2=dryb)
double f_Wpar_fixed; //Fixed capacity-based parasitic loss fraction
double f_Wpar_prod; //Production-based parasitic loss fraction
double* Wpar_prodQ_coefs; //Part-load production parasitic adjustment coefs.
int nval_Wpar_prodQ_coefs;
double* Wpar_prodT_coefs; //Temp.-based production parasitic adjustment coefs.
int nval_Wpar_prodT_coefs;
double hrs_tes; //Equivalent full-load hours of storage
double f_charge; //Storage charging energy derate
double f_disch; //Storage discharging energy derate
double f_etes_0; //Initial fractional charge level of thermal storage (0..1)
double f_teshl_ref; //Reference heat loss from storage per max stored capacity
double* teshlX_coefs; //Charge-based thermal loss adjustment - constant coef.
int nval_teshlX_coefs;
double* teshlT_coefs; //Temp.-based thermal loss adjustment - constant coef.
int nval_teshlT_coefs;
int ntod; //Number of time-of-dispatch periods in the dispatch schedule
//double* tod_sched; //Array of touperiod indices
int nval_tod_sched;
double* disws; //Time-of-dispatch control for with-solar conditions
int nval_disws;
double* diswos; //Time-of-dispatch control for without-solar conditions
int nval_diswos;
double* qdisp; //touperiod power output control factors
int nval_qdisp;
double* fdisp; //Fossil backup output control factors
int nval_fdisp;
bool istableunsorted;
double* OpticalTable_in; //Optical table
int nrow_OpticalTable, ncol_OpticalTable;
/*double* OpticalTableUns_in;
int nrow_OpticalTableUns, ncol_OpticalTableUns;*/
double ibn; //Beam-normal (DNI) irradiation
double ibh; //Beam-horizontal irradiation
double itoth; //Total horizontal irradiation
double tdb; //Ambient dry-bulb temperature
double twb; //Ambient wet-bulb temperature
double vwind; //Wind velocity
double irr_used; //Irradiation value used in simulation
double hour_of_day; //Hour of the day
double day_of_year; //Day of the year
double declination; //Declination angle
double soltime; //[hour] Solar time of the day
double hrangle; //Hour angle
double solalt; //Solar elevation angle
double solaz; //Solar azimuth angle (-180..180, 0deg=South)
double eta_opt_sf; //Solar field optical efficiency
double f_sfhl_qdni; //Solar field load-based thermal loss correction
double f_sfhl_tamb; //Solar field temp.-based thermal loss correction
double f_sfhl_vwind; //Solar field wind-based thermal loss correction
double q_hl_sf; //Solar field thermal losses
double q_sf; //Solar field delivered thermal power
double q_inc; //Qdni - Solar incident energy, before all losses
int pbmode; //Power conversion mode
int pbstartf; //Flag indicating power system startup
double q_to_pb; //Thermal energy to the power conversion system
double q_startup; //Power conversion startup energy
double q_to_tes; //Thermal energy into storage
double q_from_tes; //Thermal energy from storage
double e_in_tes; //Energy in storage
double q_hl_tes; //Thermal losses from storage
double q_dump_tesfull; //Dumped energy exceeding storage charge level max
double q_dump_teschg; //Dumped energy exceeding exceeding storage charge rate
double q_dump_umin; //Dumped energy from falling below min. operation fraction
double q_dump_tot; //Total dumped energy
double q_fossil; //thermal energy supplied from aux firing
double q_gas; //Energy content of fuel required to supply Qfos
double f_effpc_qtpb; //Load-based conversion efficiency correction
double f_effpc_tamb; //Temp-based conversion efficiency correction
double eta_cycle; //Adjusted power conversion efficiency
double w_gr_solar; //Power produced from the solar component
double w_gr_fossil; //Power produced from the fossil component
double w_gr; //Total gross power production
double w_par_fixed; //Fixed parasitic losses
double w_par_prod; //Production-based parasitic losses
double w_par_tot; //Total parasitic losses
double w_par_online; //Online parasitics
double w_par_offline; //Offline parasitics
double enet; //Net electric output
util::matrix_t<double> OpticalTable;
//util::matrix_t<double> OpticalTableUns;
//Declare variables that require storage from step to step
double dt, start_time, q_des, etesmax, omega, dec, eta_opt_ref, f_qsf, qttmin, qttmax, ptsmax, pfsmax;
double etes0, q_startup_remain, q_startup_used;
int pbmode0;
bool is_sf_init;
public:
sam_mw_gen_type260( tcscontext *cxt, tcstypeinfo *ti )
: tcstypeinterface(cxt, ti)
{
//Commonly used values, conversions, etc...
Pi = acos(-1.);
pi = Pi;
r2d = 180./pi;
d2r = pi/180.;
g = 9.81; //gravitation constant
mtoinch = 39.3700787; //[m] -> [in]
is_sf_init = false;
//Set all values to NaN or nonsense value to prevent misuse
latitude = std::numeric_limits<double>::quiet_NaN();
longitude = std::numeric_limits<double>::quiet_NaN();
timezone = std::numeric_limits<double>::quiet_NaN();
theta_stow = std::numeric_limits<double>::quiet_NaN();
theta_dep = std::numeric_limits<double>::quiet_NaN();
interp_arr = -1;
rad_type = -1;
solarm = std::numeric_limits<double>::quiet_NaN();
T_sfdes = std::numeric_limits<double>::quiet_NaN();
irr_des = std::numeric_limits<double>::quiet_NaN();
eta_opt_soil = std::numeric_limits<double>::quiet_NaN();
eta_opt_gen = std::numeric_limits<double>::quiet_NaN();
f_sfhl_ref = std::numeric_limits<double>::quiet_NaN();
sfhlQ_coefs = NULL;
nval_sfhlQ_coefs = -1;
sfhlT_coefs = NULL;
nval_sfhlT_coefs = -1;
sfhlV_coefs = NULL;
nval_sfhlV_coefs = -1;
qsf_des = std::numeric_limits<double>::quiet_NaN();
w_des = std::numeric_limits<double>::quiet_NaN();
eta_des = std::numeric_limits<double>::quiet_NaN();
f_wmax = std::numeric_limits<double>::quiet_NaN();
f_wmin = std::numeric_limits<double>::quiet_NaN();
f_startup = std::numeric_limits<double>::quiet_NaN();
eta_lhv = std::numeric_limits<double>::quiet_NaN();
etaQ_coefs = NULL;
nval_etaQ_coefs = -1;
etaT_coefs = NULL;
nval_etaT_coefs = -1;
T_pcdes = std::numeric_limits<double>::quiet_NaN();
PC_T_corr = std::numeric_limits<double>::quiet_NaN();
f_Wpar_fixed = std::numeric_limits<double>::quiet_NaN();
f_Wpar_prod = std::numeric_limits<double>::quiet_NaN();
Wpar_prodQ_coefs = NULL;
nval_Wpar_prodQ_coefs = -1;
Wpar_prodT_coefs = NULL;
nval_Wpar_prodT_coefs = -1;
hrs_tes = std::numeric_limits<double>::quiet_NaN();
f_charge = std::numeric_limits<double>::quiet_NaN();
f_disch = std::numeric_limits<double>::quiet_NaN();
f_etes_0 = std::numeric_limits<double>::quiet_NaN();
f_teshl_ref = std::numeric_limits<double>::quiet_NaN();
teshlX_coefs = NULL;
nval_teshlX_coefs = -1;
teshlT_coefs = NULL;
nval_teshlT_coefs = -1;
ntod = -1;
//tod_sched = NULL;
nval_tod_sched = -1;
disws = NULL;
nval_disws = -1;
diswos = NULL;
nval_diswos = -1;
qdisp = NULL;
nval_qdisp = -1;
fdisp = NULL;
nval_fdisp = -1;
OpticalTable_in = NULL;
nrow_OpticalTable = -1, ncol_OpticalTable = -1;
istableunsorted = false;
optical_table_uns = 0; //NULL
eff_scale = 1.; //Set here just in case
/*OpticalTableUns_in = NULL;
nrow_OpticalTableUns = -1, ncol_OpticalTableUns = -1;*/
ibn = std::numeric_limits<double>::quiet_NaN();
ibh = std::numeric_limits<double>::quiet_NaN();
itoth = std::numeric_limits<double>::quiet_NaN();
tdb = std::numeric_limits<double>::quiet_NaN();
twb = std::numeric_limits<double>::quiet_NaN();
vwind = std::numeric_limits<double>::quiet_NaN();
irr_used = std::numeric_limits<double>::quiet_NaN();
hour_of_day = std::numeric_limits<double>::quiet_NaN();
day_of_year = std::numeric_limits<double>::quiet_NaN();
declination = std::numeric_limits<double>::quiet_NaN();
soltime = std::numeric_limits<double>::quiet_NaN();
hrangle = std::numeric_limits<double>::quiet_NaN();
solalt = std::numeric_limits<double>::quiet_NaN();
solaz = std::numeric_limits<double>::quiet_NaN();
eta_opt_sf = std::numeric_limits<double>::quiet_NaN();
f_sfhl_qdni = std::numeric_limits<double>::quiet_NaN();
f_sfhl_tamb = std::numeric_limits<double>::quiet_NaN();
f_sfhl_vwind = std::numeric_limits<double>::quiet_NaN();
q_hl_sf = std::numeric_limits<double>::quiet_NaN();
q_sf = std::numeric_limits<double>::quiet_NaN();
q_inc = std::numeric_limits<double>::quiet_NaN();
pbmode = -1;
pbstartf = -1;
q_to_pb = std::numeric_limits<double>::quiet_NaN();
q_startup = std::numeric_limits<double>::quiet_NaN();
q_to_tes = std::numeric_limits<double>::quiet_NaN();
q_from_tes = std::numeric_limits<double>::quiet_NaN();
e_in_tes = std::numeric_limits<double>::quiet_NaN();
q_hl_tes = std::numeric_limits<double>::quiet_NaN();
q_dump_tesfull = std::numeric_limits<double>::quiet_NaN();
q_dump_teschg = std::numeric_limits<double>::quiet_NaN();
q_dump_umin = std::numeric_limits<double>::quiet_NaN();
q_dump_tot = std::numeric_limits<double>::quiet_NaN();
q_fossil = std::numeric_limits<double>::quiet_NaN();
q_gas = std::numeric_limits<double>::quiet_NaN();
f_effpc_qtpb = std::numeric_limits<double>::quiet_NaN();
f_effpc_tamb = std::numeric_limits<double>::quiet_NaN();
eta_cycle = std::numeric_limits<double>::quiet_NaN();
w_gr_solar = std::numeric_limits<double>::quiet_NaN();
w_gr_fossil = std::numeric_limits<double>::quiet_NaN();
w_gr = std::numeric_limits<double>::quiet_NaN();
w_par_fixed = std::numeric_limits<double>::quiet_NaN();
w_par_prod = std::numeric_limits<double>::quiet_NaN();
w_par_tot = std::numeric_limits<double>::quiet_NaN();
w_par_online = std::numeric_limits<double>::quiet_NaN();
w_par_offline = std::numeric_limits<double>::quiet_NaN();
enet = std::numeric_limits<double>::quiet_NaN();
}
virtual ~sam_mw_gen_type260(){
/* Clean up on simulation terminate */
if(optical_table_uns != 0)
delete optical_table_uns;
}
virtual int init(){
/*
--Initialization call--
Do any setup required here.
Get the values of the inputs and parameters
*/
dt = time_step()/3600.;
start_time = -1;
latitude = value(P_LATITUDE); //Site latitude [deg]
longitude = value(P_LONGITUDE); //Site longitude [deg]
timezone = value(P_TIMEZONE); //Site timezone [hr]
theta_stow = value(P_THETA_STOW); //Solar elevation angle at which the solar field stops operating [deg]
theta_dep = value(P_THETA_DEP); //Solar elevation angle at which the solar field begins operating [deg]
interp_arr = (int)value(P_INTERP_ARR); //Interpolate the array or find nearest neighbor? (1=interp,2=no) [none]
rad_type = (int)value(P_RAD_TYPE); //Solar resource radiation type (1=DNI,2=horiz.beam,3=tot.horiz) [none]
solarm = value(P_SOLARM); //Solar multiple [none]
T_sfdes = value(P_T_SFDES); //Solar field design point temperature (dry bulb) [C]
irr_des = value(P_IRR_DES); //Irradiation design point [W/m2]
eta_opt_soil = value(P_ETA_OPT_SOIL); //Soiling optical derate factor [none]
eta_opt_gen = value(P_ETA_OPT_GEN); //General/other optical derate [none]
f_sfhl_ref = value(P_F_SFHL_REF); //Reference solar field thermal loss fraction [MW/MWcap]
sfhlQ_coefs = value(P_SFHLQ_COEFS, &nval_sfhlQ_coefs); //Irr-based solar field thermal loss adjustment coefficients [1/MWt]
sfhlT_coefs = value(P_SFHLT_COEFS, &nval_sfhlT_coefs); //Temp.-based solar field thermal loss adjustment coefficients [1/C]
sfhlV_coefs = value(P_SFHLV_COEFS, &nval_sfhlV_coefs); //Wind-based solar field thermal loss adjustment coefficients [1/(m/s)]
qsf_des = value(P_QSF_DES); //Solar field thermal production at design [MWt]
w_des = value(P_W_DES); //Design power cycle gross output [MWe]
eta_des = value(P_ETA_DES); //Design power cycle gross efficiency [none]
f_wmax = value(P_F_WMAX); //Maximum over-design power cycle operation fraction [none]
f_wmin = value(P_F_WMIN); //Minimum part-load power cycle operation fraction [none]
f_startup = value(P_F_STARTUP); //Equivalent full-load hours required for power system startup [hours]
eta_lhv = value(P_ETA_LHV); //Fossil backup lower heating value efficiency [none]
etaQ_coefs = value(P_ETAQ_COEFS, &nval_etaQ_coefs); //Part-load power conversion efficiency adjustment coefficients [1/MWt]
etaT_coefs = value(P_ETAT_COEFS, &nval_etaT_coefs); //Temp.-based power conversion efficiency adjustment coefs. [1/C]
T_pcdes = value(P_T_PCDES); //Power conversion reference temperature [C]
PC_T_corr = value(P_PC_T_CORR); //Power conversion temperature correction mode (1=wetb, 2=dryb) [none]
f_Wpar_fixed = value(P_F_WPAR_FIXED); //Fixed capacity-based parasitic loss fraction [MWe/MWcap]
f_Wpar_prod = value(P_F_WPAR_PROD); //Production-based parasitic loss fraction [MWe/MWe]
Wpar_prodQ_coefs = value(P_WPAR_PRODQ_COEFS, &nval_Wpar_prodQ_coefs); //Part-load production parasitic adjustment coefs. [1/MWe]
Wpar_prodT_coefs = value(P_WPAR_PRODT_COEFS, &nval_Wpar_prodT_coefs); //Temp.-based production parasitic adjustment coefs. [1/C]
hrs_tes = value(P_HRS_TES); //Equivalent full-load hours of storage [hours]
f_charge = value(P_F_CHARGE); //Storage charging energy derate [none]
f_disch = value(P_F_DISCH); //Storage discharging energy derate [none]
f_etes_0 = value(P_F_ETES_0); //Initial fractional charge level of thermal storage (0..1) [none]
f_teshl_ref = value(P_F_TESHL_REF); //Reference heat loss from storage per max stored capacity [kWt/MWhr-stored]
teshlX_coefs = value(P_TESHLX_COEFS, &nval_teshlX_coefs); //Charge-based thermal loss adjustment - constant coef. [1/MWhr-stored]
teshlT_coefs = value(P_TESHLT_COEFS, &nval_teshlT_coefs); //Temp.-based thermal loss adjustment - constant coef. [1/C]
ntod = (int)value(P_NTOD); //Number of time-of-dispatch periods in the dispatch schedule [none]
//tod_sched = value(P_TOD_SCHED, &nval_tod_sched); //Array of touperiod indices [none]
disws = value(P_DISWS, &nval_disws); //Time-of-dispatch control for with-solar conditions [none]
diswos = value(P_DISWOS, &nval_diswos); //Time-of-dispatch control for without-solar conditions [none]
qdisp = value(P_QDISP, &nval_qdisp); //touperiod power output control factors [none]
fdisp = value(P_FDISP, &nval_fdisp); //Fossil backup output control factors [none]
OpticalTable_in = value(P_OPTICALTABLE, &nrow_OpticalTable, &ncol_OpticalTable); //Optical table [none]
istableunsorted = value(P_ISTABLEUNSORTED) == 1.;
//Rearrange the optical table into a more useful format
OpticalTable.assign(OpticalTable_in, nrow_OpticalTable, ncol_OpticalTable);
//Unit conversions
latitude *= d2r;
longitude *= d2r;
theta_stow *= d2r;
theta_dep *= d2r;
T_sfdes += 273.15;
T_pcdes += 273.15;
f_teshl_ref *= .001;
//Initial calculations
//Power block design power
q_des = w_des/eta_des; //[MWt]
//Maximum energy in storage
etesmax = hrs_tes*q_des; //[MW-hr]
//Express the dispatch values in dimensional terms
for(int i=0; i<ntod; i++){
disws[i] *= etesmax;
diswos[i] *= etesmax;
qdisp[i] *= q_des;
fdisp[i] *= q_des;
}
/*
Set up the optical table object..
The input should be defined as follows:
- Data of size nx, ny
- OpticalTable of size (nx+1)*(ny+1)
- First nx+1 values (row 1) are x-axis values, not data, starting at index 1
- First value of remaining ny rows are y-axis values, not data
- Data is contained in cells i,j : where i>1, j>1
A second option using an unstructured array is also possible. The data should be defined as:
- N rows
- 3 values per row
- Azimuth, Zenith, Efficiency point
If the OpticalTableUns is given data, it will be used by default.
*/
if( ! istableunsorted )
{
/*
Standard azimuth-elevation table
*/
//does the table look right?
if( (nrow_OpticalTable < 5 && ncol_OpticalTable > 3 ) || (ncol_OpticalTable == 3 && nrow_OpticalTable > 4) )
message(TCS_WARNING, "The optical efficiency table option flag may not match the specified table format. If running SSC, ensure \"IsTableUnsorted\""
" =0 if regularly-spaced azimuth-zenith matrix is used and =1 if azimuth,zenith,efficiency points are specified.");
if ( nrow_OpticalTable<=0 || ncol_OpticalTable<=0 ) // If these were not set correctly, it will create memory allocation crash not caught by error handling.
return -1;
double *xax = new double[ncol_OpticalTable-1];
double *yax = new double[nrow_OpticalTable-1];
double *data = new double[(ncol_OpticalTable -1) * (nrow_OpticalTable -1)];
//get the xaxis data values
for(int i=1; i<ncol_OpticalTable; i++){
xax[i-1] = OpticalTable.at(0, i)*d2r;
}
//get the yaxis data values
for(int j=1; j<nrow_OpticalTable; j++){
yax[j-1] = OpticalTable.at(j, 0)*d2r;
}
//Get the data values
for(int j=1; j<nrow_OpticalTable; j++){
for(int i=1; i<ncol_OpticalTable; i++){
data[ i-1 + (ncol_OpticalTable-1)*(j-1) ] = OpticalTable.at(j, i);
}
}
optical_table.AddXAxis(xax, ncol_OpticalTable-1);
optical_table.AddYAxis(yax, nrow_OpticalTable-1);
optical_table.AddData(data);
delete [] xax;
delete [] yax;
delete [] data;
}
else
{
/*
Use the unstructured data table
*/
/*
------------------------------------------------------------------------------
Create the regression fit on the efficiency map
------------------------------------------------------------------------------
*/
if(ncol_OpticalTable != 3){
message(TCS_ERROR, "The heliostat field efficiency file is not formatted correctly. Type expects 3 columns"
" (zenith angle, azimuth angle, efficiency value) and instead has %d cols.", ncol_OpticalTable);
return -1;
}
MatDoub sunpos;
vector<double> effs;
//read the data from the array into the local storage arrays
sunpos.resize(nrow_OpticalTable, VectDoub(2));
effs.resize(nrow_OpticalTable);
double eff_maxval = -9.e9;
for(int i=0; i<nrow_OpticalTable; i++){
sunpos.at(i).at(0) = TCS_MATRIX_INDEX( var( P_OPTICALTABLE ), i, 0 ) / az_scale * pi/180.;
sunpos.at(i).at(1) = TCS_MATRIX_INDEX( var( P_OPTICALTABLE ), i, 1 ) / zen_scale * pi/180.;
double eff = TCS_MATRIX_INDEX( var( P_OPTICALTABLE ), i, 2 );
effs.at(i) = eff;
if(eff > eff_maxval) eff_maxval = eff;
}
//scale values based on maximum. This helps the GM interpolation routine
eff_scale = eff_maxval;
for( int i=0; i<nrow_OpticalTable; i++)
effs.at(i) /= eff_scale;
//Create the field efficiency table
Powvargram vgram(sunpos, effs, 1.99, 0.);
optical_table_uns = new GaussMarkov(sunpos, effs, vgram);
//test how well the fit matches the data
double err_fit = 0.;
int npoints = (int)sunpos.size();
for(int i=0; i<npoints; i++){
double zref = effs.at(i);
double zfit = optical_table_uns->interp( sunpos.at(i) );
double dz = zref - zfit;
err_fit += dz * dz;
}
err_fit = sqrt(err_fit);
if( err_fit > 0.01 )
message(TCS_WARNING, "The heliostat field interpolation function fit is poor! (err_fit=%f RMS)", err_fit);
}
//Calculate min/max turbine operation rates
qttmin = q_des*f_wmin;
qttmax = q_des*f_wmax;
//Calculate max TES charging/discharging rates based on solar multiple
ptsmax = q_des * solarm;
pfsmax = ptsmax / f_disch*f_wmax;
//Set initial storage values
etes0 = f_etes_0*etesmax; //[MW-hr] Initial value in thermal storage. This keeps track of energy in thermal storage, or e_in_tes
pbmode0 = 0; //[-] initial value of power block operation mode pbmode
q_startup_remain = f_startup*q_des; //[MW-hr] Initial value of turbine startup energy q_startup_used
return true;
}
void init_sf()
{
//---- Calculate the "normalized" design-point thermal power.
//---Design point values---
//Calculate the design point efficiency based on the solar position at solstice noon, rather than maxval of the table
omega = 0.0; //solar noon
dec = 23.45*d2r; //declination at summer solstice
//Solar altitude at noon on the summer solstice
solalt = asin(sin(dec)*sin(latitude)+cos(latitude)*cos(dec)*cos(omega));
double opt_des;
if(istableunsorted)
{
// Use current solar position to interpolate field efficiency table and find solar field efficiency
vector<double> sunpos;
sunpos.push_back(0.);
sunpos.push_back((pi/2. - solalt)/zen_scale);
opt_des = optical_table_uns->interp( sunpos ) * eff_scale;
}
else
{
opt_des = interp_arr == 1 ?
optical_table.interpolate(0.0, max(pi/2.-solalt, 0.0)) :
optical_table.nearest(0.0, max(pi/2.-solalt, 0.0)) ;
}
eta_opt_ref = eta_opt_soil*eta_opt_gen*opt_des;
f_qsf = qsf_des/(irr_des*eta_opt_ref*(1.-f_sfhl_ref)); //[MWt/([W/m2] * [-] * [-])]
return;
}
virtual int call(double time, double step, int ncall){
/*
-- Standard timestep call --
*get inputs
*do calculations
*set outputs
*/
//record the start time
if(start_time < 0){ start_time = current_time(); }
//If the solar field design point hasn't yet been initialized, do so here.
if(! is_sf_init){
//Re-read the location info from the weather reader
latitude = value(P_LATITUDE)*d2r;
longitude = value(P_LONGITUDE)*d2r;
timezone = value(P_TIMEZONE);
init_sf();
is_sf_init = true;
}
//******************************************************************************************************************************
// Time-dependent conditions
//******************************************************************************************************************************
ibn = value(I_IBN); //Beam-normal (DNI) irradiation [W/m^2]
ibh = value(I_IBH); //Beam-horizontal irradiation [W/m^2]
itoth = value(I_ITOTH); //Total horizontal irradiation [W/m^2]
tdb = value(I_TDB); //Ambient dry-bulb temperature [C]
twb = value(I_TWB); //Ambient wet-bulb temperature [C]
vwind = value(I_VWIND); //Wind velocity [m/s]
double shift = longitude - timezone*15.*d2r;
//int touperiod = CSP::TOU_Reader(tod_sched, time, nval_tod_sched);
int touperiod = (int)value(I_TOUPeriod) - 1; // control value between 1 & 9, have to change to 0-8 for array index
//Unit conversions
tdb += 273.15;
twb += 273.15;
//Choose which irradiation source will be used
switch(rad_type)
{
case 1:
irr_used = ibn; //[W/m2]
break;
case 2:
irr_used = ibh; //[W/m2]
break;
case 3:
irr_used = itoth; //[W/m2]
break;
}
//Choose which dispatch set will be used
util::matrix_t<double> dispatch(ntod);
if(irr_used>0.){
for(int i=0; i<ntod; i++) dispatch.at(i) = disws[i];
}
else{
for(int i=0; i<ntod; i++) dispatch.at(i) = diswos[i];
}
//*********** End of input section *********************************************************************************************
//------------------------------------------------------------------------------------------------------------
// Solar field calculations
//------------------------------------------------------------------------------------------------------------
hour_of_day = fmod(time/3600., 24.); //hour_of_day of the day (1..24)
day_of_year = ceil(time/3600./24.); //Day of the year
// Duffie & Beckman 1.5.3b
double B = (day_of_year-1)*360.0/365.0*pi/180.0;
// Eqn of time in minutes
double EOT = 229.2 * (0.000075 + 0.001868 * cos(B) - 0.032077 * sin(B) - 0.014615 * cos(B*2.0) - 0.04089 * sin(B*2.0));
// Declination in radians (Duffie & Beckman 1.6.1)
dec = 23.45 * sin(360.0*(284.0+day_of_year)/365.0*pi/180.0) * pi/180.0;
// Solar Noon and time in hours
double SolarNoon = 12. - ((shift)*180.0/pi) / 15.0 - EOT / 60.0;
// 3.13.16 twn: 'TSnow' doesn't seem to be used anywhere, so commenting this out
/*double TSnow;
if ((hour_of_day - int(hour_of_day)) == 0.00){
TSnow = 1.0;
}
else{
TSnow = (hour_of_day - floor(hour_of_day))/dt + 1.;
}*/
// Deploy & stow times in hours
// Calculations modified by MJW 11/13/2009 to correct bug
theta_dep = max(theta_dep,1.e-6);
double DepHr1 = cos(latitude) / tan(theta_dep);
double DepHr2 = -tan(dec) * sin(latitude) / tan(theta_dep);
double DepHr3 = (tan(pi-theta_dep) < 0. ? -1. : 1.)*acos((DepHr1*DepHr2 + sqrt(DepHr1*DepHr1-DepHr2*DepHr2+1.0)) / (DepHr1 * DepHr1 + 1.0)) * 180.0 / pi / 15.0;
double DepTime = SolarNoon + DepHr3;
theta_stow = max(theta_stow,1.e-6);
double StwHr1 = cos(latitude) / tan(theta_stow);
double StwHr2 = -tan(dec) * sin(latitude) / tan(theta_stow);
double StwHr3 = (tan(pi-theta_stow) < 0. ? -1. : 1.)*acos((StwHr1*StwHr2 + sqrt(StwHr1*StwHr1-StwHr2*StwHr2+1.0)) / (StwHr1 * StwHr1 + 1.0)) * 180.0 / pi / 15.0;
double StwTime = SolarNoon + StwHr3;
// Ftrack is the fraction of the time period that the field is tracking. MidTrack is time at midpoint of operation
double HrA = hour_of_day-dt;
double HrB = hour_of_day;
// Solar field operates
double Ftrack, MidTrack;
if ((HrB > DepTime) && (HrA < StwTime)){
// solar field deploys during time period
if (HrA < DepTime){
Ftrack = (HrB - DepTime) *dt;
MidTrack = HrB - Ftrack * 0.5 *dt;
// Solar field stows during time period
}
else if (HrB > StwTime){
Ftrack = (StwTime - HrA) *dt;
MidTrack = HrA + Ftrack * 0.5 *dt;
}
// solar field operates during entire period
else{
Ftrack = 1.0;
MidTrack = HrA + 0.5 *dt;
}
}
// solar field doesn't operate
else{
Ftrack = 0.0;
MidTrack = HrA + 0.5 *dt;
}
double StdTime = MidTrack;
soltime = StdTime+((shift)*180.0/pi)/15.0+ EOT/60.0;
// hour_of_day angle (arc of sun) in radians
omega = (soltime - 12.0)*15.0*pi/180.0;
// B. Stine equation for Solar Altitude angle in radians
solalt = asin(sin(dec)*sin(latitude)+cos(latitude)*cos(dec)*cos(omega));
solaz = (omega < 0. ? -1. : 1.)*fabs(acos(min(1.0,(cos(pi/2.-solalt)*sin(latitude)-sin(dec))/(sin(pi/2.-solalt)*cos(latitude)))));
//Get the current optical efficiency
double opt_val;
if(istableunsorted)
{
// Use current solar position to interpolate field efficiency table and find solar field efficiency
vector<double> sunpos;
sunpos.push_back(solaz/az_scale);
sunpos.push_back((pi/2. - solalt)/zen_scale);
opt_val = optical_table_uns->interp( sunpos ) * eff_scale;
}
else
{
opt_val = interp_arr == 1 ?
optical_table.interpolate(solaz, max(pi/2.-solalt, 0.0)) :
optical_table.nearest(solaz, max(pi/2.-solalt, 0.0) );
}
double eta_arr = max(opt_val*Ftrack, 0.0); //mjw 7.25.11 limit zenith to <90, otherwise the interpolation error message gets called during night hours.
eta_opt_sf = eta_arr*eta_opt_soil*eta_opt_gen;
//Evaluate solar feild thermal efficiency derate
f_sfhl_qdni = 0.;
f_sfhl_tamb = 0.;
f_sfhl_vwind = 0.;
for(int i=0; i<nval_sfhlQ_coefs; i++)
f_sfhl_qdni += sfhlQ_coefs[i]*pow(irr_used/irr_des, i);
for(int i=0; i<nval_sfhlT_coefs; i++)
f_sfhl_tamb += sfhlT_coefs[i]*pow(tdb - T_sfdes, i);
for(int i=0; i<nval_sfhlV_coefs; i++)
f_sfhl_vwind += sfhlV_coefs[i]*pow(vwind, i);
double f_sfhl = 1.0 - f_sfhl_ref * f_sfhl_qdni * f_sfhl_tamb * f_sfhl_vwind; //This ratio indicates the sf thermal efficiency
q_hl_sf = f_qsf*irr_used*(1.-f_sfhl)*eta_opt_sf; //[MWt]
//Calculate the total solar field thermal output
q_sf = f_qsf * f_sfhl * eta_opt_sf * irr_used; //[MWt]
//------------------------------------------------------------------------------------------------------------
// Dispatch calculations
//------------------------------------------------------------------------------------------------------------
// initialize outputs to 0
q_to_tes = 0.; //| Energy to Thermal Storage
q_from_tes = 0.; //| Energy from Thermal Storage
e_in_tes = 0.; //| Energy in Thermal Storage
q_hl_tes = 0.; //| Energy losses from Thermal Storage
q_to_pb = 0.; //| Energy to the Power Block
q_dump_tesfull = 0.; //| Energy dumped because the thermal storage is full
q_dump_umin = 0.; //| Indicator of being below minimum operation level
q_dump_teschg = 0.; //| The amount of energy dumped (more than turbine and storage)
q_startup = 0.; //| The energy needed to startup the turbine
pbstartf = 0; //| is 1 during the period when powerblock starts up otherwise 0
q_startup_used = q_startup_remain; //| Turbine startup energy for this timestep is equal to the remaining previous energy
//--------Plant dispatch strategy--------------------
if (hrs_tes <= 0.){ // No Storage
if ((pbmode0==0)||(pbmode0==1)){ // if plant is not already operating in last timestep
if (q_sf>0){
if (q_sf>(q_startup_used/dt)){ // Starts plant as exceeds startup energy needed
q_to_pb = q_sf - q_startup_used/dt;
q_startup = q_startup_used/dt;
pbmode = 2; //Power block mode.. 2=starting up
pbstartf = 1; //Flag indicating whether the power block starts up in this time period
q_startup_used = 0.; //mjw 5-31-13 Reset to zero to handle cases where Qsf-TurSue leads to Qttb < Qttmin
}
else{ // Plant starting up but not enough energy to make it run - will probably finish in the next timestep
q_to_pb = 0.;
q_startup_used = q_startup_remain - q_sf*dt;
q_startup = q_sf;
pbmode = 1;
pbstartf = 0;
}
}
else{ // No solar field output so still need same amount of energy as before and nothing changes
q_startup_used = f_startup * q_des;
pbmode = 0;
pbstartf = 0;
}
}
else{ // if the powerblock mode is already 2 (running previous timestep)
if (q_sf>0){ // Plant operated last hour_of_day and this one
q_to_pb = q_sf; // all power goes from solar field to the powerblock
pbmode = 2; // powerblock continuing to operate
pbstartf = 0; // powerblock did not start during this timestep
}
else{ // Plant operated last hour_of_day but not this one
q_to_pb = 0.; // No energy to the powerblock
pbmode = 0; // turned off powrblock
pbstartf = 0; // it didn't start this timeperiod
q_startup_used = q_startup_remain;
}
}
// following happens no matter what state the powerblock was in previously
if (q_to_pb < qttmin){ // Energy to powerblock less than the minimum that the turbine can run at
q_dump_umin = q_to_pb; // The minimum energy (less than the minimum)
q_to_pb = 0; // Energy to PB is now 0
pbmode = 0; // PB turned off
}
if (q_to_pb > qttmax){ // Energy to powerblock greater than what the PB can handle (max)
q_dump_teschg = q_to_pb - qttmax; // The energy dumped
q_to_pb = qttmax; // the energy to the PB is exactly the maximum
}
}
else{ //With thermal storage
//--initialize values
q_startup = 0.0;
pbstartf = 0;
q_dump_teschg = 0.0;
q_from_tes = 0.0;
if (pbmode0 == 0){
//**********************************************************
//****** plant is not already operating *****
//**********************************************************
//---Start plant if any of the following conditions are met---
// 1.) Solar field output > 0
// a.) AND energy in TES exceeds w/ solar touperiod fraction
// b.) AND energy in TES plus solar field output exceeds turbine fraction
// OR
// 2.) Solar field is off
// a.) AND energy in TES exceeds w/o solar touperiod
// b.) AND energy in TES exceeds turbine fraction
// OR
// 3.) Solar field energy exceeds maximum TES charging rate
//------------------------------------------------------------
double EtesA = max(0.0, etes0 - dispatch.at(touperiod));
if ((q_sf + EtesA >= qdisp[touperiod]) || (q_sf > ptsmax)){
// Assumes Operator started plant during previous time period
// But TRNSYS cannot do this, so start-up energy is deducted during current timestep.
pbmode = 1;
q_startup = f_startup * q_des /dt;
q_to_pb = qdisp[touperiod]; // set the energy to powerblock equal to the load for this TOU period
if (q_sf>q_to_pb){ // if solar field output is greater than what the necessary load ?
q_to_tes = q_sf - q_to_pb; // the extra goes to thermal storage
q_from_tes = q_startup; // Use the energy from thermal storage to startup the power cycle
if (q_to_tes>ptsmax){ // if q to thermal storage exceeds thermal storage max rate Added 9-10-02
q_dump_teschg = q_to_tes - ptsmax; // then dump the excess for this period Added 9-10-02
q_to_tes = ptsmax;
}
}
else{ // q_sf less than the powerblock requirement
q_to_tes = 0.0;
q_from_tes = q_startup + (1 - q_sf / q_to_pb) * min(pfsmax, q_des);
if (q_from_tes>pfsmax) q_from_tes = pfsmax;
q_to_pb = q_sf + (1 - q_sf / q_to_pb) * min(pfsmax, q_des);
}
e_in_tes = etes0 - q_startup + (q_sf - q_to_pb) * dt; // thermal storage energy is initial + what was left
pbmode = 2; // powerblock is now running
pbstartf = 1; // the powerblock turns on during this timeperiod.
}
else{ //Store energy not enough stored to start plant
q_to_tes = q_sf; // everything goes to thermal storage
q_from_tes = 0; // nothing from thermal storage
e_in_tes = etes0 + q_to_tes * dt ;
q_to_pb = 0;
}
}
else{
//**********************************************************
//****** plant is already operating *****
//**********************************************************
if ((q_sf + max(0.0,etes0-dispatch.at(touperiod)) /dt) > qdisp[touperiod]){ // if there is sufficient energy to operate at dispatch target output
q_to_pb = qdisp[touperiod];
if (q_sf>q_to_pb){
q_to_tes = q_sf - q_to_pb; //extra from what is needed put in thermal storage
q_from_tes = 0.;
if (q_to_tes>ptsmax){ //check if max power rate to storage exceeded
q_dump_teschg = q_to_tes - ptsmax; // if so, dump extra
q_to_tes = ptsmax;
}
}
else{ // solar field outptu less than what powerblock needs
q_to_tes = 0.;
q_from_tes = (1. - q_sf / q_to_pb) * min(pfsmax, q_des);
if (q_from_tes>pfsmax) q_from_tes = min(pfsmax, q_des);
q_to_pb = q_from_tes + q_sf;
}
e_in_tes = etes0 + (q_sf - q_to_pb - q_dump_teschg) *dt; // energy of thermal storage is the extra
// Check to see if throwing away energy
if ( (e_in_tes>etesmax) && (q_to_pb<qttmax) ){ // qttmax (MWt) - power to turbine max
if ((e_in_tes - etesmax)/dt < (qttmax - q_to_pb) ){
q_to_pb = q_to_pb + (e_in_tes - etesmax) /dt;
e_in_tes = etesmax;
}
else{
e_in_tes = e_in_tes - (qttmax - q_to_pb) * dt; // should this be etes0 instead of e_in_tes on RHS ??
q_to_pb = qttmax;
}
q_to_tes = q_sf - q_to_pb;
}
}
else{ //Empties tes to dispatch level if above min load level
if ((q_sf + max(0.,etes0-dispatch.at(touperiod)) * dt) > qttmin){
q_from_tes = max(0.,etes0-dispatch.at(touperiod)) * dt;
q_to_pb = q_sf + q_from_tes;
q_to_tes = 0.;
e_in_tes = etes0 - q_from_tes;
}
else{
q_to_pb = 0.;
q_from_tes = 0.;
q_to_tes = q_sf;
e_in_tes = etes0 + q_to_tes * dt;
}
}
}
if (q_to_pb>0)
pbmode = 2;
else
pbmode = 0;
//---Calculate TES thermal losses ---
// First do the charge-based losses. Use the average charge over the timestep
double f_EtesAve = max((e_in_tes + etes0)/2./etesmax, 0.0);
double f_teshlX = 0., f_teshlT = 0.;
for(int i=0; i<nval_teshlX_coefs; i++)
f_teshlX += teshlX_coefs[i]*pow(f_EtesAve, i); //Charge adjustment factor
for(int i=0; i<nval_teshlT_coefs; i++)
f_teshlT += teshlT_coefs[i]*pow(T_sfdes - tdb, i);
//thermal storage heat losses adjusted by charge level and ambient temp.
q_hl_tes = f_teshl_ref*etesmax*f_teshlX*f_teshlT;
e_in_tes = max(e_in_tes - q_hl_tes*dt, 0.0); // Adjust the energy in thermal storage according to TES thermal losses
if (e_in_tes>etesmax){ // trying to put in more than storage can handle
q_dump_tesfull = (e_in_tes - etesmax)/dt; //this is the amount dumped when storage is completely full
e_in_tes = etesmax;
q_to_tes = q_to_tes - q_dump_tesfull;
}
else{
q_dump_tesfull = 0.; // nothing is dumped if not overfilled
}
// Check min and max on turbine
if (q_to_pb<qttmin){
q_dump_umin = q_to_pb;
q_to_pb = 0.;
pbmode = 0;
}
else{
q_dump_umin = 0;
}
pbmode0 = pbmode;
}
//------------------------------------------------------------------------------------------------------------
// Fossil backup
//------------------------------------------------------------------------------------------------------------
// 5.23.16 twn bug fix (see svn)
if( q_to_pb < fdisp[touperiod] )
{ // If the thermal power dispatched to the power cycle is less than the level in the fossil control
q_fossil = fdisp[touperiod] - q_to_pb; // then the fossil used is the fossil control value minus what's provided by the solar field
q_gas = q_fossil / eta_lhv; // Calculate the required fossil heat content based on the LHV efficiency
}
else
{
q_fossil = 0.0;
q_gas = 0.0;
}
//if (q_sf < fdisp[touperiod]){ // if the solar provided is less than the level stipulated in the fossil control
// q_fossil = fdisp[touperiod] - q_sf; // then the fossil used is the fossil control value minus what's provided by the solar field
// q_gas = q_fossil / eta_lhv; // Calculate the required fossil heat content based on the LHV efficiency
//}
//else{
// q_fossil = 0.;
// q_gas = 0.;
//}
//Adjust the power block energy based on additional fossil backup
q_to_pb = q_to_pb + q_fossil;
//------------------------------------------------------------------------------------------------------------
// Power block calculations
//------------------------------------------------------------------------------------------------------------
double qnorm = q_to_pb/q_des; //The normalized thermal energy flow
double tnorm;
if(PC_T_corr==1.) //Select the dry or wet bulb temperature as the driving difference
tnorm = twb - T_pcdes;
else
tnorm = tdb - T_pcdes;
//Calculate the load-based and temperature-based efficiency correction factors
f_effpc_qtpb = 0.;
f_effpc_tamb = 0.;
for(int i=0; i<nval_etaQ_coefs; i++)
f_effpc_qtpb += etaQ_coefs[i]*pow(qnorm, i);
for(int i=0; i<nval_etaT_coefs; i++)
f_effpc_tamb += etaT_coefs[i]*pow(tnorm, i);
eta_cycle = eta_des * f_effpc_qtpb * f_effpc_tamb; //Adjusted power conversion efficiency
if(q_to_pb <= 0.) eta_cycle = 0.0; //Set conversion efficiency to zero when the power block isn't operating
//Calculate the gross power
w_gr = q_to_pb * eta_cycle;
//Keep track of what portion is from solar
w_gr_solar = (q_to_pb - q_fossil)*eta_cycle;
//------------------------------------------------------------------------------------------------------------
// Parasitics
//------------------------------------------------------------------------------------------------------------
w_par_fixed = f_Wpar_fixed * w_des; //Fixed parasitic loss based on plant capacity
//Production-based parasitic loss
double wpar_prodq = 0., wpar_prodt = 0.;
for(int i=0; i<nval_Wpar_prodQ_coefs; i++)
wpar_prodq += Wpar_prodQ_coefs[i]*pow(qnorm, i); //Power block part-load correction factor
for(int i=0; i<nval_Wpar_prodT_coefs; i++)
wpar_prodt += Wpar_prodT_coefs[i]*pow(tnorm, i); //Temperature correction factor
w_par_prod = f_Wpar_prod * w_gr * wpar_prodq * wpar_prodt;
w_par_tot = w_par_fixed + w_par_prod; //Total parasitic loss
//Keep track of online/offline parasitics
if(w_gr > 0.){
w_par_online = w_par_tot;
w_par_offline = 0.;
}
else{
w_par_online = 0.;
w_par_offline = w_par_tot;
}
//---Calculate net energy output (enet<-->Wnet) ---
enet = w_gr - w_par_tot;
//Calculate final values
declination = dec*r2d; //[deg] Declination angle
hrangle = omega*r2d; //[deg] hour_of_day angle
solalt = max(solalt*r2d, 0.0); //[deg] Solar elevation angle
solaz = solaz*r2d; //[deg] Solar azimuth angle (-180..180, 0deg=South)
q_inc = f_qsf*irr_used; //[MWt] Qdni - Solar incident energy, before all losses
q_dump_tot = q_dump_tesfull + q_dump_teschg + q_dump_umin; //[MWt] Total dumped energy
w_gr_fossil = w_gr - w_gr_solar; //[MWe] Power produced from the fossil component
//Set outputs and return
value(O_IRR_USED, irr_used); //[W/m2] Irradiation value used in simulation
value(O_HOUR_OF_DAY, hour_of_day); //[hour_of_day] hour_of_day of the day
value(O_DAY_OF_YEAR, day_of_year); //[day] Day of the year
value(O_DECLINATION, declination); //[deg] Declination angle
value(O_SOLTIME, soltime); //[hour_of_day] [hour_of_day] Solar time of the day
value(O_HRANGLE, hrangle); //[deg] hour_of_day angle
value(O_SOLALT, solalt); //[deg] Solar elevation angle
value(O_SOLAZ, solaz); //[deg] Solar azimuth angle (-180..180, 0deg=South)
value(O_ETA_OPT_SF, eta_opt_sf); //[none] Solar field optical efficiency
value(O_F_SFHL_QDNI, f_sfhl_qdni); //[none] Solar field load-based thermal loss correction
value(O_F_SFHL_TAMB, f_sfhl_tamb); //[none] Solar field temp.-based thermal loss correction
value(O_F_SFHL_VWIND, f_sfhl_vwind); //[none] Solar field wind-based thermal loss correction
value(O_Q_HL_SF, q_hl_sf); //[MWt] Solar field thermal losses
value(O_Q_SF, q_sf); //[MWt] Solar field delivered thermal power
value(O_Q_INC, q_inc); //[MWt] Qdni - Solar incident energy, before all losses
value(O_PBMODE, pbmode); //[none] Power conversion mode
value(O_PBSTARTF, pbstartf); //[none] Flag indicating power system startup
value(O_Q_TO_PB, q_to_pb); //[MWt] Thermal energy to the power conversion system
value(O_Q_STARTUP, q_startup); //[MWt] Power conversion startup energy
value(O_Q_TO_TES, q_to_tes); //[MWt] Thermal energy into storage
value(O_Q_FROM_TES, q_from_tes); //[MWt] Thermal energy from storage
value(O_E_IN_TES, e_in_tes); //[MWt-hr] Energy in storage
value(O_Q_HL_TES, q_hl_tes); //[MWt] Thermal losses from storage
value(O_Q_DUMP_TESFULL, q_dump_tesfull); //[MWt] Dumped energy exceeding storage charge level max
value(O_Q_DUMP_TESCHG, q_dump_teschg); //[MWt] Dumped energy exceeding exceeding storage charge rate
value(O_Q_DUMP_UMIN, q_dump_umin); //[MWt] Dumped energy from falling below min. operation fraction
value(O_Q_DUMP_TOT, q_dump_tot); //[MWt] Total dumped energy
value(O_Q_FOSSIL, q_fossil); //[MWt] thermal energy supplied from aux firing
value(O_Q_GAS, q_gas); //[MWt] Energy content of fuel required to supply Qfos
value(O_F_EFFPC_QTPB, f_effpc_qtpb); //[none] Load-based conversion efficiency correction
value(O_F_EFFPC_TAMB, f_effpc_tamb); //[none] Temp-based conversion efficiency correction
value(O_ETA_CYCLE, eta_cycle); //[none] Adjusted power conversion efficiency
value(O_W_GR_SOLAR, w_gr_solar); //[MWe] Power produced from the solar component
value(O_W_GR_FOSSIL, w_gr_fossil); //[MWe] Power produced from the fossil component
value(O_W_GR, w_gr); //[MWe] Total gross power production
value(O_W_PAR_FIXED, w_par_fixed); //[MWe] Fixed parasitic losses
value(O_W_PAR_PROD, w_par_prod); //[MWe] Production-based parasitic losses
value(O_W_PAR_TOT, w_par_tot); //[MWe] Total parasitic losses
value(O_W_PAR_ONLINE, w_par_online); //[MWe] Online parasitics
value(O_W_PAR_OFFLINE, w_par_offline); //[MWe] Offline parasitics
value(O_ENET, enet); //[MWe] Net electric output
return 0;
}
virtual int converged(double time){
/*
-- Post-convergence call --
Update values that should be transferred to the next time step
*/
etes0 = e_in_tes;
pbmode0 = pbmode;
q_startup_remain = q_startup_used;
return 0;
}
};
TCS_IMPLEMENT_TYPE( sam_mw_gen_type260, "Generic Solar Model", "Mike Wagner", 1, sam_mw_gen_type260_variables, NULL, 1 );
| 53.729385 | 260 | 0.549997 |
75e5596aee746778f78381cffe406ad07ffb5f1a | 5,682 | cpp | C++ | src/ofApp.cpp | ryo-simon-mf/oF-Color-Boxes | 9ee208ec3c31d077c92860151c5a7df686ce579a | [
"MIT"
] | null | null | null | src/ofApp.cpp | ryo-simon-mf/oF-Color-Boxes | 9ee208ec3c31d077c92860151c5a7df686ce579a | [
"MIT"
] | null | null | null | src/ofApp.cpp | ryo-simon-mf/oF-Color-Boxes | 9ee208ec3c31d077c92860151c5a7df686ce579a | [
"MIT"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
cam.setDistance(2500);
gui.setup();
gui.add( toggle_0.setup("inside box",false));
gui.add( toggle_1.setup("outside box1",false));
gui.add( toggle_4.setup("outside box2",false));
gui.add( toggle_2.setup("Rotate Auto",false));
gui.add( toggle_3.setup("Rotate Mouse",false));
gui.add( xslider.setup("inside box x",180.0,0.0,360.0));
gui.add( yslider.setup("inside box y",180.0,0.0,360.0));
gui.add( zslider.setup("inside box z",180.0,0.0,360.0));
gui.add( xslider_1.setup("outside box1 x",180.0,0.0,360.0));
gui.add( yslider_1.setup("outside box1 y",180.0,0.0,360.0));
gui.add( zslider_1.setup("outside box1 z",180.0,0.0,360.0));
gui.add( xslider_2.setup("outside box2 x",180.0,0.0,360.0));
gui.add( yslider_2.setup("outside box2 y",180.0,0.0,360.0));
gui.add( zslider_2.setup("outside box2 z",180.0,0.0,360.0));
gui.add(color.setup("back ground color",
ofColor(0, 0, 0),
ofColor(0, 0),
ofColor(255, 255)));
gui.add( int_slider_0.setup("number of inside box ",100.0,1.0,1500.0));
gui.add( int_slider_1.setup("number of outside box ",100.0,1.0,1500.0));
gui.add( int_slider_2.setup("number of outside box ",100.0,1.0,1500.0));
bHide = false;
open = true;
open1 = true;
open2 =true;
open3=true;
open4=true;
on = false;
for(int i=0;i<int_slider_0;i++){
Box tmp= Box();
boxes.push_back(tmp);
}
for(int i=0;i<int_slider_1;i++){
Box2 tmp= Box2();
boxes2.push_back(tmp);
}
for(int i=0;i<int_slider_2;i++){
Box3 tmp= Box3();
boxes3.push_back(tmp);
}
rotate_x=0;
rotate_y=0;
rotate_z=0;
ofSetFrameRate(60);
ofGetFrameNum();
}
//--------------------------------------------------------------
void ofApp::update(){
for(int i=0;i< int_slider_0;i++){
boxes[i].update();
}
for(int i=0;i< int_slider_1;i++){
boxes2[i].update();
}
for(int i=0;i< int_slider_2;i++){
boxes3[i].update();
}
rotate_x += 0.3;
rotate_y += 0.3;
rotate_z += 0.3;
ofBackground(color);
}
//--------------------------------------------------------------
void ofApp::draw(){
cam.begin();
ofEnableDepthTest();
//rotate------------------------------
if(open2){
if(toggle_2 == true){
ofRotateX(rotate_x);
ofRotateY(rotate_y);
ofRotateZ(rotate_z);
}
}
//Rotate auto--------------------------
if(open3){
if(toggle_3 == true){
ofRotateX(ofGetMouseX());
ofRotateY(ofGetMouseY());
}
}
//inside box---------------------------
ofPushMatrix();
if(open){
ofRotate(100, xslider, yslider, zslider);
if( toggle_0 == true ){
for(int i=0; i < int_slider_0 ; i++){
boxes[i].draw();
Box tmp =Box();
boxes.push_back(tmp);
}
}
}
ofPopMatrix();
//outside box--------------------------
ofPushMatrix();
if(open1){
ofRotate(100, xslider_1, yslider_1, zslider_1);
if( toggle_1 == true ){
for(int i=0; i < int_slider_1 ; i++){
boxes2[i].draw();
Box2 tmp =Box2();
boxes2.push_back(tmp);
}
}
}
ofPopMatrix();
//outside box--------------------------
ofPushMatrix();
if(open4){
ofRotate(100, xslider_2, yslider_2, zslider_2);
if( toggle_4 == true ){
for(int i=0; i < int_slider_2 ; i++){
boxes3[i].draw();
Box3 tmp =Box3();
boxes3.push_back(tmp);
}
}
}
ofPopMatrix();
ofDisableDepthTest();
cam.end();
ofPopMatrix();
if(!bHide){
gui.draw();
}
ofPushMatrix();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if(key == 'h'){
bHide = !bHide;
}
if(key == 'f'){
ofToggleFullscreen();
}
if(key == '1'){
color = ofColor(255);
}
if(key == '2'){
color = ofColor(0);
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 23.774059 | 76 | 0.416579 |
75e84d7d6d90fe98b2bfa0f7278e9fe2c28f7805 | 7,971 | cpp | C++ | oldcode/lib_angle/tests/perf_tests/angle_perf_test_main.cpp | xriss/gamecake | 015e6d324761f46235ee61a61a71dbd9a49f6192 | [
"MIT"
] | 28 | 2017-04-20T06:21:26.000Z | 2021-12-10T15:22:51.000Z | oldcode/lib_angle/tests/perf_tests/angle_perf_test_main.cpp | sahwar/gamecake | 9abcb937c0edc22dee2940cb06ec9a84597e989c | [
"MIT"
] | 3 | 2017-04-05T00:41:45.000Z | 2020-04-04T00:44:24.000Z | oldcode/lib_angle/tests/perf_tests/angle_perf_test_main.cpp | sahwar/gamecake | 9abcb937c0edc22dee2940cb06ec9a84597e989c | [
"MIT"
] | 5 | 2016-11-26T14:44:55.000Z | 2021-07-29T04:25:53.000Z | //
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "SimpleBenchmark.h"
#include "BufferSubData.h"
#include "TexSubImage.h"
#include "PointSprites.h"
#include <iostream>
#include <rapidjson/document.h>
#include <rapidjson/filestream.h>
namespace
{
template <class T>
struct Optional
{
Optional()
: valid(false),
value(T())
{}
explicit Optional(T valueIn)
: valid(true),
value(valueIn)
{}
Optional(const Optional &other)
: valid(other.valid),
value(other.value)
{}
Optional &operator=(const Optional &other)
{
this.valid = other.valid;
this.value = otehr.value;
return *this;
}
static Optional None()
{
return Optional();
}
bool valid;
T value;
};
Optional<std::string> GetStringMember(const rapidjson::Document &document, const char *name)
{
auto typeIt = document.FindMember(name);
if (typeIt == document.MemberEnd() || !typeIt->value.IsString())
{
std::cerr << "JSON has missing or bad string member '" << name << "'" << std::endl;
return Optional<std::string>::None();
}
return Optional<std::string>(typeIt->value.GetString());
}
Optional<bool> GetBoolMember(const rapidjson::Document &document, const char *name)
{
auto typeIt = document.FindMember(name);
if (typeIt == document.MemberEnd() || !typeIt->value.IsBool())
{
std::cerr << "JSON has missing or bad bool member '" << name << "'" << std::endl;
return Optional<bool>::None();
}
return Optional<bool>(typeIt->value.GetBool());
}
Optional<int> GetIntMember(const rapidjson::Document &document, const char *name)
{
auto typeIt = document.FindMember(name);
if (typeIt == document.MemberEnd() || !typeIt->value.IsInt())
{
std::cerr << "JSON has missing or bad int member '" << name << "'" << std::endl;
return Optional<int>::None();
}
return Optional<int>(typeIt->value.GetInt());
}
Optional<unsigned int> GetUintMember(const rapidjson::Document &document, const char *name)
{
auto typeIt = document.FindMember(name);
if (typeIt == document.MemberEnd() || !typeIt->value.IsUint())
{
std::cerr << "JSON has missing or bad uint member '" << name << "'" << std::endl;
return Optional<unsigned int>::None();
}
return Optional<unsigned int>(typeIt->value.GetUint());
}
EGLint ParseRendererType(const std::string &value)
{
if (value == "d3d11")
{
return EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE;
}
else if (value == "d3d9")
{
return EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE;
}
else if (value == "warp")
{
// TODO(jmadill): other attributes for warp
return EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE;
}
else if (value == "default")
{
return EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE;
}
else
{
return EGL_NONE;
}
}
GLenum ParseAttribType(const std::string &value)
{
if (value == "float")
{
return GL_FLOAT;
}
else if (value == "int")
{
return GL_INT;
}
else if (value == "uint")
{
return GL_UNSIGNED_INT;
}
else if (value == "short")
{
return GL_SHORT;
}
else if (value == "ushort")
{
return GL_UNSIGNED_SHORT;
}
else if (value == "byte")
{
return GL_BYTE;
}
else if (value == "ubyte")
{
return GL_UNSIGNED_BYTE;
}
else
{
return GL_NONE;
}
}
bool ParseBenchmarkParams(const rapidjson::Document &document, BufferSubDataParams *params)
{
// Validate params
auto type = GetStringMember(document, "type");
auto components = GetUintMember(document, "components");
auto normalized = GetBoolMember(document, "normalized");
auto updateSize = GetUintMember(document, "update_size");
auto bufferSize = GetUintMember(document, "buffer_size");
auto iterations = GetUintMember(document, "iterations");
auto updateRate = GetUintMember(document, "update_rate");
if (!type.valid || !components.valid || !normalized.valid || !updateSize.valid ||
!bufferSize.valid || !iterations.valid || !updateRate.valid)
{
return false;
}
GLenum vertexType = ParseAttribType(type.value);
if (vertexType == GL_NONE)
{
std::cerr << "Invalid attribute type: " << type.value << std::endl;
return false;
}
if (components.value < 1 || components.value > 4)
{
std::cerr << "Invalid component count: " << components.value << std::endl;
return false;
}
if (normalized.value && vertexType == GL_FLOAT)
{
std::cerr << "Normalized float is not a valid vertex type." << std::endl;
return false;
}
if (bufferSize.value == 0)
{
std::cerr << "Zero buffer size is not valid." << std::endl;
return false;
}
if (iterations.value == 0)
{
std::cerr << "Zero iterations not valid." << std::endl;
return false;
}
params->vertexType = vertexType;
params->vertexComponentCount = components.value;
params->vertexNormalized = normalized.value;
params->updateSize = updateSize.value;
params->bufferSize = bufferSize.value;
params->iterations = iterations.value;
params->updateRate = updateRate.value;
return true;
}
bool ParseBenchmarkParams(const rapidjson::Document &document, TexSubImageParams *params)
{
// TODO(jmadill): Parse and validate parameters
params->imageWidth = 1024;
params->imageHeight = 1024;
params->subImageHeight = 64;
params->subImageWidth = 64;
params->iterations = 10;
return true;
}
bool ParseBenchmarkParams(const rapidjson::Document &document, PointSpritesParams *params)
{
// TODO(jmadill): Parse and validate parameters
params->iterations = 10;
params->count = 10;
params->size = 3.0f;
params->numVaryings = 3;
return true;
}
template <class BenchT>
int ParseAndRunBenchmark(EGLint rendererType, const rapidjson::Document &document)
{
BenchT::Params params;
if (!ParseBenchmarkParams(document, ¶ms))
{
// Parse or validation error
return 1;
}
params.requestedRenderer = rendererType;
BenchT benchmark(params);
// Run the benchmark
return benchmark.run();
}
}
int main(int argc, char **argv)
{
if (argc < 3)
{
std::cerr << "Must specify a renderer and source json file." << std::endl;
return 1;
}
EGLint rendererType = ParseRendererType(std::string(argv[1]));
if (rendererType == EGL_NONE)
{
std::cerr << "Invalid renderer type: " << argv[1] << std::endl;
return 1;
}
FILE *fp = fopen(argv[2], "rt");
if (fp == NULL)
{
std::cerr << "Cannot open " << argv[2] << std::endl;
return 1;
}
rapidjson::FileStream fileStream(fp);
rapidjson::Document document;
if (document.ParseStream(fileStream).HasParseError())
{
std::cerr << "JSON Parse error code " << document.GetParseError() << "." << std::endl;
return 1;
}
fclose(fp);
auto testName = GetStringMember(document, "test");
if (!testName.valid)
{
return 1;
}
if (testName.value == "BufferSubData")
{
return ParseAndRunBenchmark<BufferSubDataBenchmark>(rendererType, document);
}
else if (testName.value == "TexSubImage")
{
return ParseAndRunBenchmark<TexSubImageBenchmark>(rendererType, document);
}
else if (testName.value == "PointSprites")
{
return ParseAndRunBenchmark<PointSpritesBenchmark>(rendererType, document);
}
else
{
std::cerr << "Unknown test: " << testName.value << std::endl;
return 1;
}
}
| 24.601852 | 94 | 0.613474 |
75ec66a2cf5a8b24571f5449a2d43f2dc1b23e8f | 1,054 | cpp | C++ | 1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp | Jatin-Shihora/LeetCode-Solutions | 8e6fc84971ec96ec1263ba5ba2a8ae09e6404398 | [
"MIT"
] | 1 | 2022-01-02T10:29:32.000Z | 2022-01-02T10:29:32.000Z | 1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp | Jatin-Shihora/LeetCode-Solutions | 8e6fc84971ec96ec1263ba5ba2a8ae09e6404398 | [
"MIT"
] | null | null | null | 1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp | Jatin-Shihora/LeetCode-Solutions | 8e6fc84971ec96ec1263ba5ba2a8ae09e6404398 | [
"MIT"
] | 1 | 2022-03-04T12:44:14.000Z | 2022-03-04T12:44:14.000Z | class Solution {
public:
int minimumDeviation(vector<int>& nums) {
set <int> s;
// Storing all elements in sorted order
//insert even directly and odd with one time multiplication
//and it will become even
for(int i = 0; i<nums.size() ; ++i)
{
if(nums[i] % 2 == 0)
s.insert(nums[i]);
else
// Odd number are transformed
// using 2nd operation
s.insert(nums[i] * 2);
}
// maximum - minimun
int diff = *s.rbegin() - *s.begin();
//run the loop untill difference is minimized
while(*s.rbegin() % 2 == 0)
{
// Maximum element of the set
int x = *s.rbegin();
s.erase(x);
// remove begin element and inserted half of it for minimizing
s.insert(x/2);
diff = min(diff, *s.rbegin() - *s.begin());
}
return diff;
}
}; | 28.486486 | 74 | 0.446869 |
75ec9806e7f829e74e31082fb3e7c290a58961f6 | 4,810 | cpp | C++ | SVIEngine/jni/SVI/Render/Geometry/SVIPathPoly.cpp | Samsung/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | 27 | 2015-04-24T07:14:55.000Z | 2020-01-24T16:16:37.000Z | SVIEngine/jni/SVI/Render/Geometry/SVIPathPoly.cpp | Lousnote5/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | null | null | null | SVIEngine/jni/SVI/Render/Geometry/SVIPathPoly.cpp | Lousnote5/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | 15 | 2015-12-08T14:46:19.000Z | 2020-01-21T19:26:41.000Z | #include "../../SVICores.h"
#include "../../Slide/SVIBaseSlide.h"
#include "../../Slide/SVIProjectionSlide.h"
#include "../../Slide/SVIRenderPartManager.h"
#include "../SVITexture.h"
#include "../SVITextureManager.h"
#include "../SVIProgramManager.h"
#include "../SVIDebugRenderer.h"
#include "../SVIViewport.h"
#include "../SVIRenderer.h"
#include "../SVIRenderPatch.h"
#include "SVIPoly.h"
#include "SVIPathPoly.h"
namespace SVI {
const float cfTestDepth = 1.0f;
static const SVIBool DEBUG = SVIFALSE;
#define MAX_PATH_POINT 300
/****************************************************************************/
// real time path polygon
/****************************************************************************/
SVIPathPoly::SVIPathPoly(SVIGLSurface* surface):SVIPoly(surface){
mHasAdditionalRender = SVIFALSE;
mNeedTexcoords = SVITRUE;
mNeedIndices = SVITRUE;
mNeedNormals = SVIFALSE;
mIsAA = SVIFALSE;
mAACoord = NULL;
mWidth = 200.0f;
for (int n = 0; n < 1000; n++){
mWidthFactor.push_back( (float)(rand()%100 - 50) * 0.01f);
}
}
void SVIPathPoly::setup() {
//vertices for triangle strip
setPrimitiveType(SVI_POLY_TRI_STRIP);
}
SVIPathPoly::~SVIPathPoly() {
}
void SVIPathPoly::buildVertices() {
SVIFloat widthHalf = mWidth * 0.5f;
size_t pathCount = mPath.size();
float distancePath = 0.0f;
if (pathCount <= 1) {
return;
}
std::vector<SVIVector3> swapVertices;
swapVertices.reserve(0);
mPathVertices.swap(swapVertices);
mPathVertices.clear();
std::vector<SVIVector2> swapTexCoord;
swapTexCoord.reserve(0);
mPathTexCoord.swap(swapTexCoord);
mPathTexCoord.clear();
std::vector<SVIUShort> swapIndices;
swapIndices.reserve(0);
mPathIndices.swap(swapIndices);
mPathIndices.clear();
std::vector<SVIVector3> swapShadowVertices;
swapShadowVertices.reserve(0);
mShadowVertices.swap(swapShadowVertices);
mShadowVertices.clear();
SVISize size = mSVIGLSurface->getRenderPartManager()->getSize();
SVIUShort index = 0;
int width_index = 0;
for (size_t n = 0; n < pathCount-1; n++){
SVIVector3 direction = mPath[n+1] - mPath[n];
SVIVector3 up = SVIVector3(0,0,1.0f);
SVIVector3 side = up.Cross(direction);
side.normalize();
widthHalf = mPath[n].z * 0.5f;
SVIVector3 vertexA = mPath[n] - side * widthHalf;
SVIVector3 vertexB = mPath[n] + side * widthHalf;
mPathVertices.push_back(vertexA);
mPathVertices.push_back(vertexB);
float shadowWidth = mWidthFactor[width_index++];
width_index = width_index % 1000;
vertexA = mPath[n] - side * widthHalf * 1.1f;
vertexB = mPath[n] + side * widthHalf * 1.1f;
vertexA -= side * shadowWidth * mPath[n].z * 0.08f;
vertexB += side * shadowWidth * mPath[n].z * 0.08f;
mShadowVertices.push_back(vertexA);
mShadowVertices.push_back(vertexB);
mPathIndices.push_back(index);
mPathIndices.push_back(index+1);
index += 2;
//SVIDebugRenderer::drawPoint(vertexA, SVIVector4(1,1,1,1));
//SVIDebugRenderer::drawPoint(vertexB, SVIVector4(1,1,1,1));
}
mVerticeCount = mPathVertices.size();
mIndicesCount = mPathIndices.size();
for (int n = 0; n < mPathVertices.size(); n++) {
float u = (mPathVertices[n].x / (float)mOutpit->mSize.x);
float v = (mPathVertices[n].y / (float)mOutpit->mSize.y);
mPathTexCoord.push_back(SVIVector2(u, v));
}
mVertices = &mPathVertices[0];
mIndices = &mPathIndices[0];
mTextureCoords = &mPathTexCoord[0];
//2011-05-26 ignore z centering
//mVertices[SVI_QUAD_LEFT_TOP].x = fInverseXValue * fXDistance - width;
//mVertices[SVI_QUAD_LEFT_TOP].y = fInverseYValue * fYDistance - width;
}
void SVIPathPoly::addPath(float x, float y){
mPath.push_back(SVIVector3(x,y,0.0f));
mNeedToUpdate = SVITRUE;
}
void SVIPathPoly::clearPath(){
std::vector<SVIVector3> swapVertices;
swapVertices.reserve(0);
mPath.swap(swapVertices);
mPath.clear();
mNeedToUpdate = SVITRUE;
}
void SVIPathPoly::setWidth(SVIFloat width) {
mWidth = width;
mNeedToUpdate = SVITRUE;
}
void SVIPathPoly::setOutfit(SVISlideOutfit * pOutpit){
mOutpit = pOutpit;
clearPath();
if (!mOutpit->mPathPoints.empty()){
mPath.assign(mOutpit->mPathPoints.begin(),mOutpit->mPathPoints.end());
}
mNeedToUpdate = SVITRUE;
}
void SVIPathPoly::additionalRender(SVISlideTextureContainer * pContainer) {
}
SVIInt SVIPathPoly::generatePath() {
return 0;
}
void SVIPathPoly::buildTextureCoordinates() {
}
}
| 24.05 | 106 | 0.624116 |
75f00f39fe0f4a39addc90305154e7c6205e9604 | 1,415 | cpp | C++ | nowa/2018/c++/zad4_3.cpp | shilangyu/zadania-maturalne | faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c | [
"MIT"
] | 3 | 2019-04-15T14:16:53.000Z | 2019-04-26T09:37:19.000Z | nowa/2018/c++/zad4_3.cpp | shilangyu/zadania-maturalne | faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c | [
"MIT"
] | 1 | 2019-03-11T19:10:33.000Z | 2019-03-11T19:10:33.000Z | nowa/2018/c++/zad4_3.cpp | shilangyu/zadania-maturalne | faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c | [
"MIT"
] | 1 | 2019-04-26T09:38:04.000Z | 2019-04-26T09:38:04.000Z | #include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
string zad4_3()
{
string line;
vector<string> content;
fstream file("../dane/sygnaly.txt");
// wczytywanie danych z pliku do vectora
if (file.is_open())
{
while (getline(file, line))
content.push_back(line);
}
file.close();
// przypisanie zmiennym numerów odpowiadających za pierwszą literę alfabetu w tablicy ASCII (65)
// oraz za ostatnią (90)
int minAscii = 90;
int maxAscii = 65;
vector<char> word;
vector<string> answerVector;
for (int i = 0; i < content.size(); i++)
{
for (int j = 0; j < content[i].size(); j++)
{
word.push_back(content[i][j]);
}
for (int j = 0; j < word.size(); j++)
{
if (char(word[j]) < minAscii)
minAscii = char(word[j]);
if (char(word[j]) > maxAscii)
maxAscii = char(word[j]);
}
if (maxAscii - minAscii <= 10)
answerVector.push_back(content[i]);
word.clear();
minAscii = 90;
maxAscii = 65;
}
string answer = "\n";
for (int i = 0; i < answerVector.size(); i++)
answer += answerVector[i] + "\n";
return "4.3. Slowa, w ktorych litery sa maksymalnie oddalone od siebie o 10 znakow: " + answer;
}
| 23.583333 | 100 | 0.543463 |
75f13c1bb62cf1a362f9eea463a07f9b567cf933 | 3,690 | cpp | C++ | OpenGLProject/renderer.cpp | NikitaMagda/OpenGLProject | b1e13fbf64540ff36ac1026bc13d0c39edc08ddb | [
"MIT"
] | null | null | null | OpenGLProject/renderer.cpp | NikitaMagda/OpenGLProject | b1e13fbf64540ff36ac1026bc13d0c39edc08ddb | [
"MIT"
] | null | null | null | OpenGLProject/renderer.cpp | NikitaMagda/OpenGLProject | b1e13fbf64540ff36ac1026bc13d0c39edc08ddb | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "renderer.h"
const char* vertexShaderSource = "#version 330 core\n \
layout (location = 0) in vec3 inputPosition;\
layout (location = 1) in vec3 inputColor; \
out vec3 myColor; \
void main() \
{ \
gl_Position = vec4(inputPosition, 1.0f); \
myColor = inputColor; \
}";
const char* fragmentShaderSource = "#version 400 core\n \
in vec3 myColor; \
out vec4 color; \
void main() \
{ \
color = vec4(myColor, 1.0f); \
}";
Renderer::Renderer(OpenGLWrapper *openGLWrapper) : openGLWrapper_(openGLWrapper)
{
vertexShader_ = openGLWrapper_->glCreateShader(GL_VERTEX_SHADER);
fragmentShader_ = openGLWrapper_->glCreateShader(GL_FRAGMENT_SHADER);
openGLWrapper_->glShaderSource(vertexShader_, 1, &vertexShaderSource, NULL);
openGLWrapper_->glShaderSource(fragmentShader_, 1, &fragmentShaderSource, NULL);
openGLWrapper_->glCompileShader(vertexShader_);
openGLWrapper_->glCompileShader(fragmentShader_);
//GLint success;
//GLchar infoLog[512];
//openGLWrapper_->glGetShaderiv(vertexShader_, GL_COMPILE_STATUS, &success);
//if (!success)
//{
// openGLWrapper_->glGetShaderInfoLog(vertexShader_, 512, NULL, infoLog);
// MessageBoxA(0, infoLog, "ERROR::SHADER::VERTEX::COMPILATION_FAILED", MB_OK);
//}
shaderProgram_ = openGLWrapper_->glCreateProgram();
openGLWrapper_->glAttachShader(shaderProgram_, vertexShader_);
openGLWrapper_->glAttachShader(shaderProgram_, fragmentShader_);
openGLWrapper_->glBindAttribLocation(shaderProgram_, 0, "inputPosition");
openGLWrapper_->glBindAttribLocation(shaderProgram_, 1, "inputColor");
openGLWrapper_->glLinkProgram(shaderProgram_);
InitializeBuffers();
}
void Renderer::Render()
{
openGLWrapper_->Fill(0.2f, 0.4f, 0.1f, 1.0f);
RenderBuffers();
openGLWrapper_->Swap();
}
void Renderer::InitializeBuffers()
{
unsigned int m_vertexBufferId, m_indexBufferId;
// Set the number of vertices in the vertex array.
int m_vertexCount = 18;
// Set the number of indices in the index array.
int m_indexCount = 3;
GLfloat vertices[] = {
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};
// Create the index array.
GLuint indices[] = {
0,
1,
2
};
openGLWrapper_->glGenVertexArrays(1, &vertexArrayId_);
openGLWrapper_->glBindVertexArray(vertexArrayId_);
openGLWrapper_->glGenBuffers(1, &m_vertexBufferId);
openGLWrapper_->glGenBuffers(1, &m_indexBufferId);
openGLWrapper_->glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferId);
openGLWrapper_->glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
openGLWrapper_->glEnableVertexAttribArray(0); // Vertex position.
openGLWrapper_->glEnableVertexAttribArray(1); // Vertex color.
openGLWrapper_->glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferId);
openGLWrapper_->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
openGLWrapper_->glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferId);
openGLWrapper_->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*) + (3 * sizeof(GLfloat)));
openGLWrapper_->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferId);
openGLWrapper_->glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indexCount * sizeof(unsigned int), indices, GL_STATIC_DRAW);
}
void Renderer::RenderBuffers()
{
openGLWrapper_->glUseProgram(shaderProgram_);
openGLWrapper_->glBindVertexArray(vertexArrayId_);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
}
Renderer::~Renderer()
{
}
| 31.271186 | 124 | 0.716802 |
75f54a8a5cd7b7687c44b8069274ff56398e4f0e | 1,587 | cpp | C++ | src/034.STL_UniqueUnique_Copy/034.STL_UniqueUnique_Copy.cpp | ogycode/CPPFromZero | 9df9a9a19850642941ef92bdef9e59477baca202 | [
"Apache-2.0"
] | null | null | null | src/034.STL_UniqueUnique_Copy/034.STL_UniqueUnique_Copy.cpp | ogycode/CPPFromZero | 9df9a9a19850642941ef92bdef9e59477baca202 | [
"Apache-2.0"
] | null | null | null | src/034.STL_UniqueUnique_Copy/034.STL_UniqueUnique_Copy.cpp | ogycode/CPPFromZero | 9df9a9a19850642941ef92bdef9e59477baca202 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
using namespace std;
bool Pred(const int &i, const int &g)
{
return i == g;
}
int main()
{
system("color 70");
setlocale(0, "Russina");
SetConsoleTitle("034.STL_Unique Unique_Copy");
vector<int> vec{ 1,3,4,4,4,4,67,4,55,2,2,2,2,4,1,5 };
//отсортируем вектор дл¤ стабильной работы алгоритма unique
sort(vec.begin(), vec.end());
cout << "Vector befor unique:" << endl;
for (auto i : vec)
cout << i << " ";
cout << endl;
//коди ниже удал¤ет элементы в диапазоне которые повтор¤ютс¤ остав뤤 только первое вхождение
//этого элемента в коллекции, т.е. коллекци¤ не будет иметь одинаковых элементов
//так как алгоритм перезаписует некторые элементы и не измен¤ет размера коллекции
//то необходимо удалить неопределенные элементы методом erase
auto iter = unique(vec.begin(), vec.end(), Pred);
vec.erase(iter, vec.end());
cout << "Vector after unique:" << endl;
for (auto i : vec)
cout << i << " ";
cout << endl;
vector<int> vec2{ 4,55,11,11,11,34,5,6,6,3,32,2,22,4,66,66,6,5,5,3,3,5 };
//отсортируем вектор дл¤ стабильной работы алгоритма unique
sort(vec2.begin(), vec2.end());
vector<int> vec3;
cout << "Vector 2 befor unique_copy:" << endl;
for (auto i : vec2)
cout << i << " ";
cout << endl;
//unique_copy делает тоже самое, что и unique но при этом копирует
//элементы в новое расположение Ѕ≈« похожих элементов
unique_copy(vec2.begin(), vec2.end(), back_inserter(vec3), Pred);
cout << "New vector after unique_copy:" << endl;
for (auto i : vec3)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}
| 25.190476 | 94 | 0.661626 |
75f97aab1684f5ca3f646c331526fdf3ac9a8bfb | 4,639 | cpp | C++ | NarThumbnailProvider/zip_reader_open_IStream.cpp | Taromati2/nar-thumbnail-provider | 6b20d2896822754c9ac5e4c69999d0762b4f23df | [
"MIT"
] | null | null | null | NarThumbnailProvider/zip_reader_open_IStream.cpp | Taromati2/nar-thumbnail-provider | 6b20d2896822754c9ac5e4c69999d0762b4f23df | [
"MIT"
] | null | null | null | NarThumbnailProvider/zip_reader_open_IStream.cpp | Taromati2/nar-thumbnail-provider | 6b20d2896822754c9ac5e4c69999d0762b4f23df | [
"MIT"
] | null | null | null |
#include "windows.h"
#include "../minizip-ng/mz.h"
#include "../minizip-ng/mz_strm.h"
#include "../minizip-ng/mz_zip.h"
#include "../minizip-ng/mz_zip_rw.h"
typedef struct mz_zip_reader_s {
void *zip_handle;
void *file_stream;
void *buffered_stream;
void *split_stream;
void *mem_stream;
void *hash;
uint16_t hash_algorithm;
uint16_t hash_digest_size;
mz_zip_file *file_info;
const char *pattern;
uint8_t pattern_ignore_case;
const char *password;
void *overwrite_userdata;
mz_zip_reader_overwrite_cb
overwrite_cb;
void *password_userdata;
mz_zip_reader_password_cb
password_cb;
void *progress_userdata;
mz_zip_reader_progress_cb
progress_cb;
uint32_t progress_cb_interval_ms;
void *entry_userdata;
mz_zip_reader_entry_cb
entry_cb;
uint8_t raw;
uint8_t buffer[UINT16_MAX];
int32_t encoding;
uint8_t sign_required;
uint8_t cd_verified;
uint8_t cd_zipped;
uint8_t entry_verified;
uint8_t recover;
} mz_zip_reader;
/***************************************************************************/
typedef struct mz_stream_IStream_s {
mz_stream stream;
IStream *ps;
} mz_stream_IStream;
/***************************************************************************/
int32_t mz_stream_IStream_open(void *stream, const char *path, int32_t mode) {
mz_stream_IStream *mem = (mz_stream_IStream *)stream;
int32_t err = MZ_OK;
mem->ps = (IStream *)path;
return err;
}
int32_t mz_stream_IStream_is_open(void *stream) {
mz_stream_IStream *mem = (mz_stream_IStream *)stream;
if(mem->ps == NULL)
return MZ_OPEN_ERROR;
return MZ_OK;
}
int32_t mz_stream_IStream_read(void *stream, void *buf, int32_t size) {
mz_stream_IStream *mem = (mz_stream_IStream *)stream;
ULONG ret;
mem->ps->Read(buf,size,&ret);
return ret;
}
int32_t mz_stream_IStream_write(void *stream, const void *buf, int32_t size) {
return 0;
}
int64_t mz_stream_IStream_tell(void *stream) {
mz_stream_IStream *mem = (mz_stream_IStream *)stream;
ULARGE_INTEGER ret;
mem->ps->Seek({0}, STREAM_SEEK_CUR,&ret );
return ret.QuadPart;
}
int32_t mz_stream_IStream_seek(void *stream, int64_t offset, int32_t origin) {
mz_stream_IStream *mem = (mz_stream_IStream *)stream;
int64_t new_pos = 0;
int32_t err = MZ_OK;
LARGE_INTEGER offL = {};
offL.QuadPart = offset;
switch(origin) {
case MZ_SEEK_CUR:
mem->ps->Seek(offL, STREAM_SEEK_CUR, NULL);
break;
case MZ_SEEK_END:
mem->ps->Seek(offL, STREAM_SEEK_END, NULL);
break;
case MZ_SEEK_SET:
mem->ps->Seek(offL, STREAM_SEEK_SET, NULL);
break;
default:
return MZ_SEEK_ERROR;
}
return MZ_OK;
}
int32_t mz_stream_IStream_close(void *stream) {
/* We never return errors */
return MZ_OK;
}
int32_t mz_stream_IStream_error(void *stream) {
/* We never return errors */
return MZ_OK;
}
extern mz_stream_vtbl mz_stream_IStream_vtbl;
void *mz_stream_IStream_create(void **stream) {
mz_stream_IStream *mem = NULL;
mem = (mz_stream_IStream *)MZ_ALLOC(sizeof(mz_stream_IStream));
if(mem != NULL) {
memset(mem, 0, sizeof(mz_stream_IStream));
mem->stream.vtbl = &mz_stream_IStream_vtbl;
}
if(stream != NULL)
*stream = mem;
return mem;
}
void mz_stream_IStream_delete(void **stream) {
mz_stream_IStream *mem = NULL;
if(stream == NULL)
return;
mem = (mz_stream_IStream *)*stream;
if(mem != NULL) {
MZ_FREE(mem);
}
*stream = NULL;
}
/***************************************************************************/
static mz_stream_vtbl mz_stream_IStream_vtbl = {
mz_stream_IStream_open,
mz_stream_IStream_is_open,
mz_stream_IStream_read,
mz_stream_IStream_write,
mz_stream_IStream_tell,
mz_stream_IStream_seek,
mz_stream_IStream_close,
mz_stream_IStream_error,
mz_stream_IStream_create,
mz_stream_IStream_delete,
NULL,
NULL
};
//
int32_t mz_zip_reader_open_IStream(void *handle, IStream *ps) {
mz_zip_reader *reader = (mz_zip_reader *)handle;
int32_t err = MZ_OK;
mz_zip_reader_close(handle);
mz_stream_IStream_create(&reader->mem_stream);
mz_stream_IStream_open(reader->mem_stream, (char*)ps, MZ_OPEN_MODE_READ);
if(err == MZ_OK)
err = mz_zip_reader_open(handle, reader->mem_stream);
return err;
}
| 25.349727 | 79 | 0.632033 |
75fa3f0e258c665df7572f01b6807b4b5a79f358 | 1,549 | hpp | C++ | src/organization_model/Statistics.hpp | tomcreutz/knowledge-reasoning-moreorg | 545fa92eaf0fc8ccc4cc042bd994afc918d16f68 | [
"BSD-3-Clause"
] | null | null | null | src/organization_model/Statistics.hpp | tomcreutz/knowledge-reasoning-moreorg | 545fa92eaf0fc8ccc4cc042bd994afc918d16f68 | [
"BSD-3-Clause"
] | 1 | 2021-02-26T11:11:03.000Z | 2021-02-26T19:16:10.000Z | src/organization_model/Statistics.hpp | tomcreutz/knowledge-reasoning-moreorg | 545fa92eaf0fc8ccc4cc042bd994afc918d16f68 | [
"BSD-3-Clause"
] | 1 | 2021-05-17T13:02:49.000Z | 2021-05-17T13:02:49.000Z | #ifndef ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP
#define ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP
#include <stdint.h>
#include <base/Time.hpp>
#include <moreorg/organization_model/InterfaceConnection.hpp>
#include <moreorg/organization_model/ActorModelLink.hpp>
namespace owl = owlapi::model;
namespace moreorg {
namespace moreorg {
/**
* Statistic of the organization model engine
*/
struct Statistics
{
Statistics();
uint32_t upperCombinationBound;
uint32_t numberOfInferenceEpochs;
base::Time timeCompositeSystemGeneration;
base::Time timeRegisterCompositeSystems;
base::Time timeInference;
base::Time timeElapsed;
owl::IRIList interfaces;
uint32_t maxAllowedLinks;
InterfaceConnectionList links;
InterfaceCombinationList linkCombinations;
uint32_t constraintsChecked;
owl::IRIList actorsAtomic;
owl::IRIList actorsKnown;
owl::IRIList actorsInferred;
owl::IRIList actorsCompositePrevious;
//owl::IRIList actorsCompositePost;
uint32_t actorsCompositePost;
owl::IRIList actorsCompositeModelPrevious;
std::vector< std::vector<ActorModelLink> > actorsCompositeModelPost;
//uint32_t actorsCompositeModelPost;
std::string toString() const;
};
std::ostream& operator<<(std::ostream& os, const Statistics& statistics);
std::ostream& operator<<(std::ostream& os, const std::vector<Statistics>& statisticsList);
} // end namespace moreorg
} // end namespace moreorg
#endif // ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP
| 27.660714 | 90 | 0.775339 |
2f050085d7b99d79442a0c3e6e986aaace885244 | 365 | hpp | C++ | Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp | x-cessive/exile | c5d1f679879a183549e1c87d078d462cbba32c25 | [
"MIT"
] | 9 | 2017-03-30T15:37:09.000Z | 2022-02-06T22:44:17.000Z | Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp | x-cessive/exile | c5d1f679879a183549e1c87d078d462cbba32c25 | [
"MIT"
] | 1 | 2017-04-10T14:59:31.000Z | 2017-04-11T14:42:13.000Z | Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp | x-cessive/exile | c5d1f679879a183549e1c87d078d462cbba32c25 | [
"MIT"
] | 6 | 2017-02-25T00:19:40.000Z | 2022-02-16T19:54:45.000Z | class CfgRemoteExec
{
class Functions
{
mode = 2;
jip = 0;
class fnc_AdminReq { allowedTargets=2; };
class ExileServer_system_network_dispatchIncomingMessage { allowedTargets=2; };
class ExileExpansionServer_system_scavenge_spawnLoot { allowedTargets=0; };
};
class Commands
{
mode=0;
jip=0;
};
}; | 22.8125 | 83 | 0.632877 |
2f06c9830e77a368f7eb4bb675e6ad52232b7bcb | 1,535 | cpp | C++ | src/game-ui/in-game/game_ui_teleporter.cpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | 1 | 2020-09-23T11:17:35.000Z | 2020-09-23T11:17:35.000Z | src/game-ui/in-game/game_ui_teleporter.cpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | null | null | null | src/game-ui/in-game/game_ui_teleporter.cpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | null | null | null | #include "game_ui_teleporter.hpp"
#include "../ui_text_element.hpp"
#include "../ui_button.hpp"
#include "../game_ui_manager.hpp"
#include "../../game/items/teleporter.hpp"
#include "../../engine.hpp"
#include "../../game_session.hpp"
#include "../../game/character.hpp"
namespace space
{
void GameUITeleporter::init(GameUIManager &uiManager)
{
_text = uiManager.createElement<UITextElement>();
_uiManager = &uiManager;
_text->widthPercent(100);
_text->flexShrink(1.0f);
addChild(_text);
_actionButton = uiManager.createElement<UIButton>();
_actionButton->width(50);
_actionButton->text("Go");
addChild(_actionButton);
flexDirection(YGFlexDirectionRow);
_actionButton->onClick([this, &uiManager] (const sf::Event &e)
{
if (this->_teleporter.item == nullptr)
{
return UIEventResult::Triggered;
}
auto session = uiManager.engine().currentSession();
auto character = session->playerController().controllingCharacter();
auto placed = this->_teleporter.placed;
session->moveSpaceObject(static_cast<SpaceObject *>(character), placed->transform().position, placed->insideArea(), true);
return UIEventResult::Triggered;
});
}
void GameUITeleporter::teleporter(PlacedItemPair<Teleporter> teleporter)
{
_teleporter = teleporter;
_text->text(teleporter.item->name());
}
} // space | 30.098039 | 134 | 0.626059 |
2f08e1a5348a24f7626ef50ef47b2c68e4f380e0 | 5,059 | cc | C++ | L1Trigger/TrackFindingTracklet/src/Projection.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | L1Trigger/TrackFindingTracklet/src/Projection.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | L1Trigger/TrackFindingTracklet/src/Projection.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z |
#include "L1Trigger/TrackFindingTracklet/interface/Projection.h"
#include "L1Trigger/TrackFindingTracklet/interface/Settings.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <algorithm>
using namespace std;
using namespace trklet;
void Projection::init(Settings const& settings,
unsigned int layerdisk,
int iphiproj,
int irzproj,
int iphider,
int irzder,
double phiproj,
double rzproj,
double phiprojder,
double rzprojder,
double phiprojapprox,
double rzprojapprox,
double phiprojderapprox,
double rzprojderapprox,
bool isPSseed) {
assert(layerdisk < N_LAYER + N_DISK);
valid_ = true;
fpgaphiproj_.set(iphiproj, settings.nphibitsstub(layerdisk), true, __LINE__, __FILE__);
if (layerdisk < N_LAYER) {
fpgarzproj_.set(irzproj, settings.nzbitsstub(layerdisk), false, __LINE__, __FILE__);
} else {
fpgarzproj_.set(irzproj, settings.nrbitsstub(layerdisk), false, __LINE__, __FILE__);
}
if (layerdisk < N_LAYER) {
if (layerdisk < N_PSLAYER) {
fpgaphiprojder_.set(iphider, settings.nbitsphiprojderL123(), false, __LINE__, __FILE__);
fpgarzprojder_.set(irzder, settings.nbitszprojderL123(), false, __LINE__, __FILE__);
} else {
fpgaphiprojder_.set(iphider, settings.nbitsphiprojderL456(), false, __LINE__, __FILE__);
fpgarzprojder_.set(irzder, settings.nbitszprojderL456(), false, __LINE__, __FILE__);
}
} else {
fpgaphiprojder_.set(iphider, settings.nbitsphiprojderL123(), false, __LINE__, __FILE__);
fpgarzprojder_.set(irzder, settings.nrbitsprojderdisk(), false, __LINE__, __FILE__);
}
if (layerdisk < N_LAYER) {
////Separate the vm projections into zbins
////This determines the central bin:
////int zbin=4+(zproj.value()>>(zproj.nbits()-3));
////But we need some range (particularly for L5L6 seed projecting to L1-L3):
int offset = isPSseed ? 1 : 4;
int ztemp = fpgarzproj_.value() >> (fpgarzproj_.nbits() - settings.MEBinsBits() - NFINERZBITS);
unsigned int zbin1 = (1 << (settings.MEBinsBits() - 1)) + ((ztemp - offset) >> NFINERZBITS);
unsigned int zbin2 = (1 << (settings.MEBinsBits() - 1)) + ((ztemp + offset) >> NFINERZBITS);
if (zbin1 >= settings.MEBins()) {
zbin1 = 0; //note that zbin1 is unsigned
}
if (zbin2 >= settings.MEBins()) {
zbin2 = settings.MEBins() - 1;
}
assert(zbin1 <= zbin2);
assert(zbin2 - zbin1 <= 1);
fpgarzbin1projvm_.set(zbin1, settings.MEBinsBits(), true, __LINE__, __FILE__); // first z bin
int nextbin = zbin1 != zbin2;
fpgarzbin2projvm_.set(nextbin, 1, true, __LINE__, __FILE__); // need to check adjacent z bin?
//fine vm z bits. Use 4 bits for fine position. starting at zbin 1
int finez = ((1 << (settings.MEBinsBits() + NFINERZBITS - 1)) + ztemp) - (zbin1 << NFINERZBITS);
fpgafinerzvm_.set(finez, NFINERZBITS + 1, true, __LINE__, __FILE__); // fine z postions starting at zbin1
} else {
//TODO the -3 and +3 should be evaluated and efficiency for matching hits checked.
//This code should be migrated in the ProjectionRouter
double roffset = 3.0;
int rbin1 = 8.0 * (irzproj * settings.krprojshiftdisk() - roffset - settings.rmindiskvm()) /
(settings.rmaxdisk() - settings.rmindiskvm());
int rbin2 = 8.0 * (irzproj * settings.krprojshiftdisk() + roffset - settings.rmindiskvm()) /
(settings.rmaxdisk() - settings.rmindiskvm());
if (rbin1 < 0) {
rbin1 = 0;
}
rbin2 = clamp(rbin2, 0, 7);
assert(rbin1 <= rbin2);
assert(rbin2 - rbin1 <= 1);
int finer = 64 *
((irzproj * settings.krprojshiftdisk() - settings.rmindiskvm()) -
rbin1 * (settings.rmaxdisk() - settings.rmindiskvm()) / 8.0) /
(settings.rmaxdisk() - settings.rmindiskvm());
finer = clamp(finer, 0, 15);
int diff = rbin1 != rbin2;
if (irzder < 0)
rbin1 += 8;
fpgarzbin1projvm_.set(rbin1, 4, true, __LINE__, __FILE__); // first r bin
fpgarzbin2projvm_.set(diff, 1, true, __LINE__, __FILE__); // need to check adjacent r bin
fpgafinerzvm_.set(finer, 4, true, __LINE__, __FILE__); // fine r postions starting at rbin1
}
//fine phi bits
int projfinephi =
(fpgaphiproj_.value() >>
(fpgaphiproj_.nbits() - (settings.nbitsallstubs(layerdisk) + settings.nbitsvmme(layerdisk) + NFINEPHIBITS))) &
((1 << NFINEPHIBITS) - 1);
fpgafinephivm_.set(projfinephi, NFINEPHIBITS, true, __LINE__, __FILE__); // fine phi postions
phiproj_ = phiproj;
rzproj_ = rzproj;
phiprojder_ = phiprojder;
rzprojder_ = rzprojder;
phiprojapprox_ = phiprojapprox;
rzprojapprox_ = rzprojapprox;
phiprojderapprox_ = phiprojderapprox;
rzprojderapprox_ = rzprojderapprox;
}
| 38.037594 | 117 | 0.634908 |
2f0e58369426a872d6e60a0940741337c827f251 | 1,191 | cpp | C++ | quake_framebuffer/quake_framebuffer/net_none.cpp | WarlockD/quake-stm32 | 8414f407f6fc529bf9d5a371ed91c1ee1194679b | [
"BSD-2-Clause"
] | 4 | 2018-07-03T14:21:39.000Z | 2021-06-01T06:12:14.000Z | quake_framebuffer/quake_framebuffer/net_none.cpp | WarlockD/quake-stm32 | 8414f407f6fc529bf9d5a371ed91c1ee1194679b | [
"BSD-2-Clause"
] | null | null | null | quake_framebuffer/quake_framebuffer/net_none.cpp | WarlockD/quake-stm32 | 8414f407f6fc529bf9d5a371ed91c1ee1194679b | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (C) 1996-1997 Id Software, Inc.
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 "icommon.h"
#include "net_loop.h"
net_driver_t net_drivers[MAX_NET_DRIVERS] =
{
{
"Loopback",
false,
Loop_Init,
Loop_Listen,
Loop_SearchForHosts,
Loop_Connect,
Loop_CheckNewConnections,
Loop_GetMessage,
Loop_SendMessage,
Loop_SendUnreliableMessage,
Loop_CanSendMessage,
Loop_CanSendUnreliableMessage,
Loop_Close,
Loop_Shutdown
}
};
int net_numdrivers = 1;
net_landriver_t net_landrivers[MAX_NET_DRIVERS];
int net_numlandrivers = 0;
| 24.8125 | 75 | 0.786734 |
2f0fadc9f354656100b238a5d7fb9ab957259ea1 | 3,514 | cpp | C++ | source/code/utilities/program/wrappers/git/lib.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/utilities/program/wrappers/git/lib.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/utilities/program/wrappers/git/lib.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include <iostream>
#include "code/utilities/program/wrappers/git/lib.hpp"
#include "code/utilities/program/call/lib.hpp"
#include "code/utilities/filesystem/paths/lib.hpp"
#include "code/utilities/program/call/lib.hpp"
#include "code/utilities/random/lib.hpp"
#include "code/utilities/random/files/random_files.hpp"
#include "code/utilities/types/strings/observers/converting/lib.hpp"
#include "code/utilities/program/call/process_spawn/timed/timed_process_spawner.hpp"
std::string Download_Repo_To_Random_Name_In_Temp_Folder(std::string ssh_url)
{
auto dir = Random_Files::Random_Tmp_Directory();
std::string command = "git clone ";
command += ssh_url;
command += " ";
command += dir;
std::cout << command << std::endl;
auto spawn = Timed_Process_Spawner::Execute_And_Get_Back_Results(command);
if (spawn.results.return_code != 0){
std::cerr << spawn.results.stderr << std::endl;
exit(-1);
}
return dir;
}
std::string Download_Repo_To_Random_Name_In_Temp_Folder(std::string ssh_url, std::string branch)
{
auto dir = Random_Files::Random_Tmp_Directory();
std::string command = "git clone ";
command += "--branch ";
command += branch;
command += " ";
command += ssh_url;
command += " ";
command += dir;
auto spawn = Timed_Process_Spawner::Execute_And_Get_Back_Results(command);
if (spawn.results.return_code != 0){
std::cerr << spawn.results.stderr << std::endl;
exit(-1);
}
return dir;
}
bool Inside_Git_Repository(){
return Directory_Exists_In_Current_Directory_Or_Any_Parents(".git");
}
bool Git_Repo_Dirty(){
return Get_Return_Value_Of_Running("git diff-index --quiet HEAD --;");
}
bool Repo_Exists_On_Github(std::string const& user_name, std::string const& repo_name){
//return Successful_Run_Of_Command("wget -q --spider address https://github.com/" + user_name + "/" + repo_name);
return Successful_Run_Of_Command("curl -s --head https://github.com/" + user_name + "/" + repo_name + " | head -n 1 | grep \"HTTP/1.[01] [23]..\"");
}
void Create_Repo_On_Github(std::string const& user_name, std::string const& autorization, std::string const& project_name, std::string const& description){
exec_quietly("curl -u \"" + user_name + ":" + autorization + "\" https://api.github.com/user/repos -d '{\"name\": \"" + project_name + "\", " + "\"description\": \"" + description + "\"}'");
}
std::string Get_Path_Of_Directory_Starting_At_Git_Repo_Root(){
return Get_Path_Of_Directory_Starting_From_Root_Directory_Name(".git");
}
void Go_To_Git_Repo_Root(){
return Move_Back_Directories_Until_Directory_Exists(".git");
}
unsigned int Number_Of_Directories_Deep_In_Git_Repo(){
return Number_Of_Directories_Deep_In_Root_Directory_Name(".git");
}
std::string Get_Project_Name(){
return execute("basename `git rev-parse --show-toplevel`");
}
std::string Get_Project_URL(){
return execute("git ls-remote --get-url");
}
std::string Current_Git_Branch_Name(){
return execute("git rev-parse --abbrev-ref HEAD");
}
std::string Git_Username(){
return execute("git config --global user.name");
}
std::string Git_Hosted_User(){
auto str = exec("git config --get remote.origin.url");
std::string author;
//parse that url to get the author/organization name and repo name seperate
bool add_to_first = true;
if (!str.empty()) {
str.erase(0, 15);
for (auto const& it: str) {
if (it == '/') {add_to_first = false;}
else{
if (add_to_first) {author += it;}
}
}
}
return author;
}
int Number_Of_Commits()
{
return as_signed(execute("git rev-list --count HEAD"));
}
| 34.116505 | 190 | 0.72453 |
2f128127c60db93ca245e59efd2846ef5b44d83b | 3,553 | cpp | C++ | src/save/main.cpp | RobertLeahy/MCPP | 2b9223afa35ae215b9af7e5398ce8f7f6dd70377 | [
"Unlicense"
] | 19 | 2015-04-25T15:19:59.000Z | 2022-02-28T03:00:42.000Z | src/save/main.cpp | RobertLeahy/MCPP | 2b9223afa35ae215b9af7e5398ce8f7f6dd70377 | [
"Unlicense"
] | 1 | 2016-01-28T08:50:02.000Z | 2021-08-24T02:34:48.000Z | src/save/main.cpp | RobertLeahy/MCPP | 2b9223afa35ae215b9af7e5398ce8f7f6dd70377 | [
"Unlicense"
] | 7 | 2015-04-17T16:38:45.000Z | 2021-06-25T03:39:39.000Z | #include <save/save.hpp>
#include <server.hpp>
#include <singleton.hpp>
#include <thread_pool.hpp>
#include <exception>
#include <utility>
using namespace MCPP;
namespace MCPP {
static const Word priority=1;
static const String name("Save Manager");
static const String debug_key("save");
static const String save_complete("Save complete - took {0}ns");
static const String save_paused("Save loop paused, skipping");
static const String setting_key("save_frequency");
static const Word frequency_default=5*60*1000; // Every 5 minutes
bool SaveManager::is_verbose () {
return Server::Get().IsVerbose(debug_key);
}
void SaveManager::save () {
auto & server=Server::Get();
try {
Timer timer(Timer::CreateAndStart());
for (auto & callback : callbacks) callback();
auto elapsed=timer.ElapsedNanoseconds();
this->elapsed+=elapsed;
++count;
if (is_verbose()) server.WriteLog(
String::Format(
save_complete,
elapsed,
frequency
),
Service::LogType::Debug
);
} catch (...) {
try {
server.Panic(std::current_exception());
} catch (...) { }
throw;
}
}
void SaveManager::save_loop () {
auto & server=Server::Get();
if (
lock.Execute([&] () mutable {
if (paused) return true;
save();
return false;
}) &&
is_verbose()
) server.WriteLog(
save_paused,
Service::LogType::Debug
);
try {
server.Pool().Enqueue(
frequency,
[this] () mutable { save_loop(); }
);
} catch (...) {
try {
server.Panic(std::current_exception());
} catch (...) { }
throw;
}
}
static Singleton<SaveManager> singleton;
SaveManager & SaveManager::Get () noexcept {
return singleton.Get();
}
SaveManager::SaveManager () noexcept {
paused=false;
count=0;
elapsed=0;
}
Word SaveManager::Priority () const noexcept {
return priority;
}
const String & SaveManager::Name () const noexcept {
return name;
}
void SaveManager::Install () {
auto & server=Server::Get();
// On shutdown we must save everything
// one last time
server.OnShutdown.Add([this] () mutable {
save();
// Purge all callbacks held which
// may have originated from other
// modules
callbacks.Clear();
});
// Once the install phase is done, and
// all modules that wish to save have
// added their handlers, start the
// save loop
server.OnInstall.Add([this] (bool) mutable {
Server::Get().Pool().Enqueue(
frequency,
[this] () mutable { save_loop(); }
);
});
// Get the frequency with which saves
// should be performed from the backing store
frequency=server.Data().GetSetting(
setting_key,
frequency_default
);
}
void SaveManager::Add (std::function<void ()> callback) {
if (callback) callbacks.Add(std::move(callback));
}
void SaveManager::operator () () {
lock.Execute([&] () mutable { save(); });
}
void SaveManager::Pause () noexcept {
lock.Execute([&] () mutable { paused=true; });
}
void SaveManager::Resume () noexcept {
lock.Execute([&] () mutable { paused=false; });
}
SaveManagerInfo SaveManager::GetInfo () const noexcept {
return SaveManagerInfo{
frequency,
paused,
count,
elapsed
};
}
}
extern "C" {
Module * Load () {
return &(SaveManager::Get());
}
void Unload () {
singleton.Destroy();
}
}
| 14.384615 | 66 | 0.599775 |
2f14ea844e12e79dd8fd0b279551e50734feca17 | 4,250 | cpp | C++ | src/log.cpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 12 | 2015-03-04T15:07:00.000Z | 2019-09-13T16:31:06.000Z | src/log.cpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | null | null | null | src/log.cpp | blackberry/Wesnoth | 8b307689158db568ecc6cc3b537e8d382ccea449 | [
"Unlicense"
] | 5 | 2017-04-22T08:16:48.000Z | 2020-07-12T03:35:16.000Z | /* $Id: log.cpp 48725 2011-03-02 21:40:59Z mordante $ */
/*
Copyright (C) 2003 by David White <dave@whitevine.net>
2004 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
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.
See the COPYING file for more details.
*/
/**
* @file
* Standard logging facilities (implementation).
* See also the command line switches --logdomains and --log-@<level@>="domain".
*/
#include "global.hpp"
#include "SDL.h"
#include "log.hpp"
#include "foreach.hpp"
#include <map>
#include <sstream>
#include <ctime>
namespace {
class null_streambuf : public std::streambuf
{
virtual int overflow(int c) { return std::char_traits< char >::not_eof(c); }
public:
null_streambuf() {}
};
} // end anonymous namespace
static std::ostream null_ostream(new null_streambuf);
static int indent = 0;
static bool timestamp = true;
static std::ostream *output_stream = NULL;
static std::ostream& output()
{
if(output_stream) {
return *output_stream;
}
return std::cerr;
}
namespace lg {
tredirect_output_setter::tredirect_output_setter(std::ostream& stream)
: old_stream_(output_stream)
{
output_stream = &stream;
}
tredirect_output_setter::~tredirect_output_setter()
{
output_stream = old_stream_;
}
typedef std::map<std::string, int> domain_map;
static domain_map *domains;
void timestamps(bool t) { timestamp = t; }
logger err("error", 0), warn("warning", 1), info("info", 2), debug("debug", 3);
log_domain general("general");
log_domain::log_domain(char const *name)
: domain_(NULL)
{
// Indirection to prevent initialization depending on link order.
if (!domains) domains = new domain_map;
domain_ = &*domains->insert(logd(name, 1)).first;
}
bool set_log_domain_severity(std::string const &name, int severity)
{
std::string::size_type s = name.size();
if (name == "all") {
foreach (logd &l, *domains) {
l.second = severity;
}
} else if (s > 2 && name.compare(s - 2, 2, "/*") == 0) {
foreach (logd &l, *domains) {
if (l.first.compare(0, s - 1, name, 0, s - 1) == 0)
l.second = severity;
}
} else {
domain_map::iterator it = domains->find(name);
if (it == domains->end())
return false;
it->second = severity;
}
return true;
}
std::string list_logdomains(const std::string& filter)
{
std::ostringstream res;
foreach (logd &l, *domains) {
if(l.first.find(filter) != std::string::npos)
res << l.first << "\n";
}
return res.str();
}
std::string get_timestamp(const std::time_t& t, const std::string& format) {
char buf[100] = {0};
tm* lt = localtime(&t);
if (lt) {
strftime(buf, 100, format.c_str(), lt);
}
return buf;
}
std::ostream &logger::operator()(log_domain const &domain, bool show_names, bool do_indent) const
{
if (severity_ > domain.domain_->second)
return null_ostream;
else {
std::ostream& stream = output();
if(do_indent) {
for(int i = 0; i != indent; ++i)
stream << " ";
}
if (timestamp) {
stream << get_timestamp(time(NULL));
}
if (show_names) {
stream << name_ << ' ' << domain.domain_->first << ": ";
}
return stream;
}
}
void scope_logger::do_log_entry(log_domain const &domain, const std::string& str)
{
output_ = &debug(domain, false, true);
str_ = str;
ticks_ = SDL_GetTicks();
(*output_) << "{ BEGIN: " << str_ << "\n";
++indent;
}
void scope_logger::do_log_exit()
{
const int ticks = SDL_GetTicks() - ticks_;
--indent;
do_indent();
if (timestamp) (*output_) << get_timestamp(time(NULL));
(*output_) << "} END: " << str_ << " (took " << ticks << "ms)\n";
}
void scope_logger::do_indent() const
{
for(int i = 0; i != indent; ++i)
(*output_) << " ";
}
std::stringstream wml_error;
} // end namespace lg
| 24.285714 | 98 | 0.635529 |
2f1f2df1db8730ae3605308972354cd45da6ec14 | 2,679 | cc | C++ | leetcode/Trie/remove_sub_folders_from_the_filesystem.cc | LIZHICHAOUNICORN/Toolkits | db45dac4de14402a21be0c40ba8e87b4faeda1b6 | [
"Apache-2.0"
] | null | null | null | leetcode/Trie/remove_sub_folders_from_the_filesystem.cc | LIZHICHAOUNICORN/Toolkits | db45dac4de14402a21be0c40ba8e87b4faeda1b6 | [
"Apache-2.0"
] | null | null | null | leetcode/Trie/remove_sub_folders_from_the_filesystem.cc | LIZHICHAOUNICORN/Toolkits | db45dac4de14402a21be0c40ba8e87b4faeda1b6 | [
"Apache-2.0"
] | null | null | null | #include <map>
#include <string>
#include <vector>
#include "third_party/gflags/include/gflags.h"
#include "third_party/glog/include/logging.h"
// Problem:
// https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem/
// Solutions:
// https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem/solution/shi-yong-trie-dui-qian-zhui-bian-li-cha-1nb79/
using namespace std;
class Solution {
private:
class Trie {
struct TrieNode {
map<char, int> next;
bool isEnd;
};
vector<TrieNode> trie;
public:
Trie() { trie.push_back(TrieNode()); }
void Insert(int tree_id, string& word, int pos) {
if (pos == word.size()) {
trie[tree_id].isEnd = true;
return;
}
if (trie[tree_id].next.count(word[pos]) == 0) {
trie[tree_id].next[word[pos]] = trie.size();
trie.push_back(TrieNode());
}
Insert(trie[tree_id].next[word[pos]], word, pos + 1);
}
bool Search(int tree_id, string& word, int pos) {
if (pos == word.size()) {
return trie[tree_id].isEnd;
}
if (trie[tree_id].next.count(word[pos]) == 0) {
return false;
}
return Search(trie[tree_id].next[word[pos]], word, pos + 1);
}
bool StartWith(int tree_id, string& word, int pos) {
if (pos == word.size()) return true;
if (trie[tree_id].next.count(word[pos]) == 0) {
return false;
}
return StartWith(trie[tree_id].next[word[pos]], word, pos + 1);
}
};
public:
vector<string> removeSubfolders(vector<string>& folder) {
// 例如:["/c/d","/c/d/e","/c/f"],依次插入folder 建立trie.
Trie t;
for (auto& path : folder) {
t.Insert(0, path, 0);
}
vector<string> ret;
// 对所有路径进行遍历。
for (auto& path : folder) {
// 取每个路径的子路径查询,例如 ["/c/d","/c/d/e","/c/f"]
// 对 path="/c/d/e" 进行依次查询:"/c/d",
// "/c",如果存在("/c/d"),那么path是子路径
// 否则 它不是子路径。
int start = 0;
int last_pos = path.size();
bool found = false;
while (last_pos > 0) {
last_pos = path.substr(start, last_pos).find_last_of('/');
// 找不到就跳出
if (last_pos == std::string::npos) break;
string sub_str = path.substr(0, last_pos);
if (t.Search(0, sub_str, 0)) {
found = true;
break;
}
}
if (!found) ret.push_back(path);
}
return ret;
}
};
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
gflags::ParseCommandLineFlags(&argc, &argv, false);
vector<string> wordDict({"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"});
Solution solu;
auto ret = solu.removeSubfolders(wordDict);
return 0;
}
| 26.524752 | 130 | 0.571855 |
2f20ddb15c95e2defff68f8191a81f454eb9e14e | 4,154 | cpp | C++ | unit-test/common/test_lag.cpp | google/detectorgraph | d6c923f8e495a21137312b236e35c36a55d3a755 | [
"Apache-2.0"
] | 43 | 2018-05-17T07:13:18.000Z | 2022-02-02T01:54:06.000Z | unit-test/common/test_lag.cpp | google/detectorgraph | d6c923f8e495a21137312b236e35c36a55d3a755 | [
"Apache-2.0"
] | 4 | 2018-09-20T04:14:11.000Z | 2018-09-21T08:05:33.000Z | unit-test/common/test_lag.cpp | google/detectorgraph | d6c923f8e495a21137312b236e35c36a55d3a755 | [
"Apache-2.0"
] | 12 | 2018-05-17T09:03:31.000Z | 2020-10-13T16:38:15.000Z | // Copyright 2017 Nest Labs, Inc.
//
// 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 "nltest.h"
#include "errortype.hpp"
#include "test_lag.h"
#include "graph.hpp"
#include "lag.hpp"
#define SUITE_DECLARATION(name, test_ptr) { #name, test_ptr, setup_##name, teardown_##name }
using namespace DetectorGraph;
static int setup_lag(void *inContext)
{
return 0;
}
static int teardown_lag(void *inContext)
{
return 0;
}
namespace {
struct StartTopicState : public TopicState { StartTopicState(int aV = 0) : mV(aV) {}; int mV; };
struct LoopTopicState : public TopicState { LoopTopicState(int aV = 0) : mV(aV) {}; int mV; };
struct LoopTestDetector
: public Detector
, public SubscriberInterface<StartTopicState>
, public SubscriberInterface< Lagged<LoopTopicState> >
, public Publisher<LoopTopicState>
{
LoopTestDetector(Graph* graph) : Detector(graph), mState(0)
{
Subscribe<StartTopicState>(this);
Subscribe< Lagged<LoopTopicState> >(this);
SetupPublishing<LoopTopicState>(this);
}
virtual void Evaluate(const StartTopicState& aInData)
{
mState = LoopTopicState(1);
Publish(mState);
}
virtual void Evaluate(const Lagged<LoopTopicState>& aLoopData)
{
mState = aLoopData.data;
mState.mV++;
if (mState.mV < 5)
{
Publish(mState);
}
}
LoopTopicState mState;
};
}
static void Test_LaggedDataConstructor(nlTestSuite *inSuite, void *inContext)
{
Lagged<LoopTopicState> dummy;
NL_TEST_ASSERT(inSuite, dummy.data.mV == 0);
}
static void Test_FeedbackLoop(nlTestSuite *inSuite, void *inContext)
{
Graph graph;
graph.ResolveTopic<StartTopicState>();
Topic< Lagged<LoopTopicState> >* outputTopic = graph.ResolveTopic< Lagged<LoopTopicState> >();
LoopTestDetector detector(&graph);
graph.ResolveTopic<LoopTopicState>();
Lag<LoopTopicState> delayDetector(&graph);
graph.PushData<StartTopicState>(0);
NL_TEST_ASSERT(inSuite, detector.mState.mV == 0);
graph.EvaluateGraph();
NL_TEST_ASSERT(inSuite, detector.mState.mV == 1);
NL_TEST_ASSERT(inSuite, !outputTopic->HasNewValue());
graph.EvaluateGraph();
NL_TEST_ASSERT(inSuite, detector.mState.mV == 2);
NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue());
NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 1);
graph.EvaluateGraph();
NL_TEST_ASSERT(inSuite, detector.mState.mV == 3);
NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue());
NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 2);
graph.EvaluateGraph();
NL_TEST_ASSERT(inSuite, detector.mState.mV == 4);
NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue());
NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 3);
graph.EvaluateGraph();
NL_TEST_ASSERT(inSuite, detector.mState.mV == 5);
NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue());
NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 4);
graph.EvaluateGraph();
NL_TEST_ASSERT(inSuite, detector.mState.mV == 5);
NL_TEST_ASSERT(inSuite, !outputTopic->HasNewValue());
}
static const nlTest sTests[] = {
NL_TEST_DEF("Test_LaggedDataConstructor", Test_LaggedDataConstructor),
NL_TEST_DEF("Test_FeedbackLoop", Test_FeedbackLoop),
NL_TEST_SENTINEL()
};
extern "C"
int lag_testsuite(void)
{
nlTestSuite theSuite = SUITE_DECLARATION(lag, &sTests[0]);
nlTestRunner(&theSuite, NULL);
return nlTestRunnerStats(&theSuite);
}
| 30.544118 | 100 | 0.687771 |
2f267878a6ac98b051d235592254c2d275d238e9 | 2,366 | cpp | C++ | src/system.cpp | chrismusashi85/CppND-System-Monitor | 5855ed1e2e0279a16223176e9d476998c2695180 | [
"MIT"
] | null | null | null | src/system.cpp | chrismusashi85/CppND-System-Monitor | 5855ed1e2e0279a16223176e9d476998c2695180 | [
"MIT"
] | null | null | null | src/system.cpp | chrismusashi85/CppND-System-Monitor | 5855ed1e2e0279a16223176e9d476998c2695180 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <cstddef>
#include <set>
#include <string>
#include <vector>
#include "process.h"
#include "processor.h"
#include "system.h"
#include "linux_parser.h"
using std::set;
using std::size_t;
using std::string;
using std::vector;
using std::to_string;
/*You need to complete the mentioned TODOs in order to satisfy the rubric criteria "The student will be able to extract and display basic data about the system."
You need to properly format the uptime. Refer to the comments mentioned in format. cpp for formatting the uptime.*/
// Return the system's CPU
Processor& System::Cpu() { return cpu_; }
// ADD: compare processes with cpuutilization
bool Compare(const Process& a, const Process& b) {
return (a < b);
}
// Return a container composed of the system's processes -> DONE
vector<Process>& System::Processes() {
processes_.clear();
for (int pid : LinuxParser::Pids()) {
std::string user = LinuxParser::User(pid); // username of process
float cpuutilization = LinuxParser::CpuUtilization(pid); // cpu utilization of process
std::string ram = LinuxParser::Ram(pid); // memory utilization of process
long int uptime = LinuxParser::UpTime(pid); // uptime of process
std::string command = LinuxParser::Command(pid); // command which invokes process
processes_.emplace_back(Process(pid, user, command, cpuutilization, ram, uptime));
}
//if (processes_.size() > 0)
std::sort(processes_.begin(), processes_.end(), Compare);
return processes_;
}
// Return the system's kernel identifier (string) -> DONE
std::string System::Kernel() { return string(LinuxParser::Kernel()); }
// Return the system's memory utilization -> DONE
float System::MemoryUtilization() { return (LinuxParser::MemoryUtilization()); }
// Return the operating system name -> DONE
std::string System::OperatingSystem() { return string(LinuxParser::OperatingSystem()); }
// Return the number of processes actively running on the system -> DONE
int System::RunningProcesses() { return (LinuxParser::RunningProcesses()); }
// Return the total number of processes on the system -> DONE
int System::TotalProcesses() { return (LinuxParser::TotalProcesses()); }
// Return the number of seconds since the system started running -> DONE
long int System::UpTime() { return LinuxParser::UpTime(); }
| 37.555556 | 161 | 0.715976 |
2f2bdcf7447fd4ad54fdfd70d829770df30d3c37 | 980 | cpp | C++ | SnackDown Round 1A/BINFLIP.cpp | Jks08/CodeChef | a8aec8a563c441176a36b8581031764e99f09833 | [
"MIT"
] | 1 | 2021-09-17T13:10:04.000Z | 2021-09-17T13:10:04.000Z | SnackDown Round 1A/BINFLIP.cpp | Jks08/CodeChef | a8aec8a563c441176a36b8581031764e99f09833 | [
"MIT"
] | null | null | null | SnackDown Round 1A/BINFLIP.cpp | Jks08/CodeChef | a8aec8a563c441176a36b8581031764e99f09833 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define FAST1 ios_base::sync_with_stdio(false);
#define FAST2 cin.tie(NULL);
#define allsort(a) sort(a.begin(),a.end())
ll n,k;
void solve(){
cin>>n>>k;
if(k==0){
cout<<"Yes"<<endl;
cout<<0<<endl;
return;
}
if(k%2==0){
cout<<"No"<<endl;;
return;
}
ll sz=0;
for(ll i=31;i>=0;i--){
if(((1<<i)&k)!=0){
sz=i+1;
break;
}
}
k=(k+(1<<sz)-1)/2;
cout<<"Yes"<<endl;
cout<<sz<<endl;
int ans=1;
vector<int> a;
for(int i=sz-2;i>=0;i--){
if(((1<<i)&k)!=0){
a.push_back(ans);
ans+=(1<<i);
}
else{
ans-=(1<<i);
a.push_back(ans);
}
}
for(int i=sz-2;i>=0;i--)
cout<<a[i]<<endl;
cout<<ans<<endl;
}
int main(){
FAST1;
FAST2;
ll t;
cin>>t;
while(t--){
solve();
}
}
| 17.5 | 47 | 0.418367 |
2f315b9281397276f2339416be7e8d28f31ac034 | 887 | cc | C++ | leet_code/Longest_Increasing_Subsequence/dp_solution.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | 1 | 2020-04-11T22:04:23.000Z | 2020-04-11T22:04:23.000Z | leet_code/Longest_Increasing_Subsequence/dp_solution.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | leet_code/Longest_Increasing_Subsequence/dp_solution.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | class Solution {
private:
const int invalid = -1;
int getAnswer(vector<int>& answer, vector<int> &nums, int idx) {
int max = 0;
if (answer[idx] != invalid) {
return answer[idx];
}
for (int i = idx + 1; i < answer.size(); ++i) {
if (nums[idx] >= nums[i]) {
continue;
}
int ret = getAnswer(answer, nums, i);
if (max < ret) {
max = ret;
}
}
answer[idx] = max + 1;
return answer[idx];
}
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> answer(nums.size(), invalid);
int ans = 0;
for (int i = 0; i < answer.size(); ++i) {
int ret = getAnswer(answer, nums, i);
if (ans < ret) {
ans = ret;
}
}
return ans;
}
};
| 23.972973 | 68 | 0.421646 |
2f33385320806e4d297750693b873ce73938820c | 837 | cpp | C++ | program8/program8/driver.cpp | hurnhu/Academic-C-Code-Examples | 2dbab12888fc7f87b997daf7df4127a1ffd81b44 | [
"MIT"
] | null | null | null | program8/program8/driver.cpp | hurnhu/Academic-C-Code-Examples | 2dbab12888fc7f87b997daf7df4127a1ffd81b44 | [
"MIT"
] | null | null | null | program8/program8/driver.cpp | hurnhu/Academic-C-Code-Examples | 2dbab12888fc7f87b997daf7df4127a1ffd81b44 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "ProblemList.h"
/*
*********************
*MADE BY MICHAEL LApAN
*********************
*this program is a help desk mock up
*it proccesses helkp desk tickets,
*sorts and stores them. then shows top
*25 then bottem 25
*/
int main()
{
ProblemList problems("problems.txt");
ProblemList newProblems("newproblems.txt");
ProblemList solvedProblems("resolvedproblems.txt");
problems += newProblems;
problems -= solvedProblems;
//couldnt easily incorporate this into class
cout << "Priority Submitted By Description" << endl;
problems.writeTop(25);
system("pause");
//couldnt easily incorporate this into class
cout << "Priority Submitted By Description" << endl;
problems.writeBottom(25);
system("pause");
} | 23.25 | 65 | 0.67503 |
2f40127686b3e138bd6d4c51ffba3159a2b80c29 | 562 | cpp | C++ | CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp | QAQrz/ACM-Code | 7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7 | [
"Unlicense"
] | 2 | 2018-02-24T06:45:56.000Z | 2018-05-29T04:47:39.000Z | CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp | QAQrz/ACM-Code | 7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7 | [
"Unlicense"
] | null | null | null | CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp | QAQrz/ACM-Code | 7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7 | [
"Unlicense"
] | 2 | 2018-06-28T09:53:27.000Z | 2022-03-23T13:29:57.000Z | #include <bits/stdc++.h>
using namespace std;
#pragma comment(linker,"/stack:1024000000,1024000000")
#define db(x) cout<<(x)<<endl
#define pf(x) push_front(x)
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define ms(x,y) memset(x,y,sizeof x)
typedef long long LL;
const double pi=acos(-1),eps=1e-9;
const LL inf=0x3f3f3f3f,mod=1e9+7,maxn=1123456;
int n,a,x,vis[128],ans;
int main(){
ios::sync_with_stdio(0);
cin>>n>>x;
for(int i=0;i<n;i++){
cin>>a;
vis[a]=1;
}
for(int i=0;i<x;i++)
if(!vis[i])
ans++;
db(vis[x]?ans+1:ans);
return 0;
} | 22.48 | 54 | 0.649466 |
2f40bd39f42d58fecaad97ea17318d2cace2933c | 9,089 | cpp | C++ | src/Editor/TristeonEditor.cpp | HyperionDH/Tristeon | 8475df94b9dbd4e3b4cc82b89c6d4bab45acef29 | [
"MIT"
] | 38 | 2017-12-04T10:48:28.000Z | 2018-05-11T09:59:41.000Z | src/Editor/TristeonEditor.cpp | Tristeon/Tristeon3D | 8475df94b9dbd4e3b4cc82b89c6d4bab45acef29 | [
"MIT"
] | 9 | 2017-12-04T09:58:55.000Z | 2018-02-05T00:06:41.000Z | src/Editor/TristeonEditor.cpp | Tristeon/Tristeon3D | 8475df94b9dbd4e3b4cc82b89c6d4bab45acef29 | [
"MIT"
] | 3 | 2018-01-10T13:39:12.000Z | 2018-03-17T20:53:22.000Z | #include "Core/MessageBus.h"
#ifdef TRISTEON_EDITOR
#include "TristeonEditor.h"
#include <ImGUI/imgui_impl_glfw_vulkan.h>
#include "Core/Engine.h"
#include "Core/Rendering/Vulkan/HelperClasses/CommandBuffer.h"
#include "Core/Rendering/Vulkan/RenderManagerVulkan.h"
#include "Asset Browser/AssetBrowser.h"
#include "Scene editor/GameObjectHierarchy.h"
#include "Inspector/InspectorWindow.h"
#include "Scene editor/SceneWindow.h"
#include "Misc/Console.h"
#include "Misc/Hardware/Keyboard.h"
#include "EditorDragging.h"
namespace Tristeon
{
using namespace Editor;
TristeonEditor::TristeonEditor(Core::Engine* engine)
{
editorCamera = nullptr;
Core::VulkanBindingData *vkBinding = Core::VulkanBindingData::getInstance();
this->vkDevice = vkBinding->device;
this->engine = engine;
bindImGui(vkBinding);
initFontsImGui(vkBinding);
setupCallbacks();
createCommandBuffers();
//Set style
setStyle();
//Create editor windows
EditorWindow::editor = this;
windows.push_back(std::move(std::make_unique<AssetBrowser>()));
windows.push_back(std::move(std::make_unique<GameObjectHierarchy>()));
windows.push_back(std::move(std::make_unique<InspectorWindow>()));
windows.push_back(std::move(std::make_unique<SceneWindow>(this)));
}
TristeonEditor::~TristeonEditor()
{
Core::MessageBus::sendMessage(Core::Message(Core::MT_RENDERINGCOMPONENT_DEREGISTER, renderable));
delete renderable;
vkDevice.waitIdle();
ImGui_ImplGlfwVulkan_Shutdown();
}
void TristeonEditor::setStyle()
{
ImGuiStyle * style = &ImGui::GetStyle();
style->WindowPadding = ImVec2(15, 15);
style->WindowRounding = 5.0f;
style->FramePadding = ImVec2(5, 5);
style->FrameRounding = 4.0f;
style->ItemSpacing = ImVec2(12, 8);
style->ItemInnerSpacing = ImVec2(8, 6);
style->IndentSpacing = 25.0f;
style->ScrollbarSize = 15.0f;
style->ScrollbarRounding = 9.0f;
style->GrabMinSize = 5.0f;
style->GrabRounding = 3.0f;
style->Colors[ImGuiCol_Text] = ImVec4(0.80f, 0.80f, 0.83f, 1.00f);
style->Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style->Colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f);
style->Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f);
style->Colors[ImGuiCol_PopupBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f);
style->Colors[ImGuiCol_Border] = ImVec4(0.80f, 0.80f, 0.83f, 0.88f);
style->Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f);
style->Colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f);
style->Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style->Colors[ImGuiCol_FrameBgActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f);
style->Colors[ImGuiCol_TitleBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f);
style->Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f);
style->Colors[ImGuiCol_TitleBgActive] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f);
style->Colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f);
style->Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f);
style->Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f);
style->Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f);
style->Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f);
style->Colors[ImGuiCol_ComboBg] = ImVec4(0.19f, 0.18f, 0.21f, 1.00f);
style->Colors[ImGuiCol_CheckMark] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f);
style->Colors[ImGuiCol_SliderGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f);
style->Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f);
style->Colors[ImGuiCol_Button] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f);
style->Colors[ImGuiCol_ButtonHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style->Colors[ImGuiCol_ButtonActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f);
style->Colors[ImGuiCol_Header] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f);
style->Colors[ImGuiCol_HeaderActive] = ImVec4(0, 0, 0, 0);
style->Colors[ImGuiCol_HeaderHovered] = ImVec4(0.301f, 0.537f, .788f, 1);
style->Colors[ImGuiCol_Column] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f);
style->Colors[ImGuiCol_ColumnHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style->Colors[ImGuiCol_ColumnActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f);
style->Colors[ImGuiCol_ResizeGrip] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
style->Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f);
style->Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f);
style->Colors[ImGuiCol_CloseButton] = ImVec4(0.40f, 0.39f, 0.38f, 0.16f);
style->Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.40f, 0.39f, 0.38f, 0.39f);
style->Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.40f, 0.39f, 0.38f, 1.00f);
style->Colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f);
style->Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f);
style->Colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f);
style->Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f);
style->Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f);
style->Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(1.00f, 0.98f, 0.95f, 0.73f);
style->Colors[ImGuiCol_TSelectableActive] = ImVec4(1,1,1,1);
}
void TristeonEditor::onGui()
{
if (Misc::Keyboard::getKeyDown(Misc::KeyCode::SPACE))
{
inPlayMode = !inPlayMode;
Core::MessageBus::sendMessage(inPlayMode ? Core::MT_GAME_LOGIC_START : Core::MT_GAME_LOGIC_STOP);
}
//If playing the game it will go in fullscreen, thus the editor no longer needs to be rendered, will be subject to change
if (inPlayMode)
return;
ImGui_ImplGlfwVulkan_NewFrame();
//ImGuizmo::BeginFrame();
//Calling ongui functions of editorwindows
for (int i = 0; i < windows.size(); ++i)
{
windows[i]->onGui();
}
//Update dragging
if (ImGui::IsMouseReleased(0))
{
EditorDragging::reset();
}
}
void TristeonEditor::render()
{
if (inPlayMode)
return;
Core::Rendering::Vulkan::RenderData* d = dynamic_cast<Core::Rendering::Vulkan::RenderData*>(renderable->data);
vk::CommandBufferBeginInfo const begin = vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eRenderPassContinue, &d->inheritance);
cmd.begin(begin);
ImGui_ImplGlfwVulkan_Render(static_cast<VkCommandBuffer>(cmd));
cmd.end();
d->lastUsedSecondaryBuffer = cmd;
}
void TristeonEditor::bindImGui(Core::VulkanBindingData* vkBinding)
{
ImGui_ImplGlfwVulkan_Init_Data init_data;
init_data.allocator = nullptr;
init_data.gpu = static_cast<VkPhysicalDevice>(vkBinding->physicalDevice);
init_data.device = static_cast<VkDevice>(vkBinding->device);
init_data.render_pass = static_cast<VkRenderPass>(vkBinding->renderPass);
init_data.pipeline_cache = NULL;
init_data.descriptor_pool = static_cast<VkDescriptorPool>(vkBinding->descriptorPool);
init_data.check_vk_result = [](VkResult err) { Misc::Console::t_assert(err == VK_SUCCESS, "Editor vulkan error: " + err); };
ImGui_ImplGlfwVulkan_Init(vkBinding->window, true, &init_data);
}
void TristeonEditor::initFontsImGui(Core::VulkanBindingData* vkBinding)
{
VkResult err = vkResetCommandPool(
static_cast<VkDevice>(vkBinding->device),
static_cast<VkCommandPool>(vkBinding->commandPool),
0);
Misc::Console::t_assert(err == VK_SUCCESS, "Failed to reset command pool: " + to_string(static_cast<vk::Result>(err)));
VkCommandBuffer const cmd = static_cast<VkCommandBuffer>(Core::Rendering::Vulkan::CommandBuffer::begin(vkBinding->commandPool, vkBinding->device));
ImGui_ImplGlfwVulkan_CreateFontsTexture(cmd);
Core::Rendering::Vulkan::CommandBuffer::end(static_cast<vk::CommandBuffer>(cmd), vkBinding->graphicsQueue, vkBinding->device, vkBinding->commandPool);
vkBinding->device.waitIdle();
ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects();
}
void TristeonEditor::setupCallbacks()
{
//Subscribe to render callback
Core::MessageBus::subscribeToMessage(Core::MT_PRERENDER, std::bind(&TristeonEditor::onGui, this));
Core::MessageBus::subscribeToMessage(Core::MT_SHARE_DATA, [&](Core::Message msg)
{
Core::Rendering::Vulkan::EditorData* data = dynamic_cast<Core::Rendering::Vulkan::EditorData*>(msg.userData);
if (data != nullptr)
this->editorCamera = data;
});
renderable = new Core::Rendering::UIRenderable();
renderable->onRender += [&]() { render(); };
Core::MessageBus::sendMessage(Core::Message(Core::MT_RENDERINGCOMPONENT_REGISTER, renderable));
}
void TristeonEditor::createCommandBuffers()
{
Core::VulkanBindingData* binding = Core::VulkanBindingData::getInstance();
Misc::Console::t_assert(binding != nullptr, "Tristeon editor currently only supports vulkan!");
vk::CommandBufferAllocateInfo alloc = vk::CommandBufferAllocateInfo(binding->commandPool, vk::CommandBufferLevel::eSecondary, 1);
vk::Result const r = binding->device.allocateCommandBuffers(&alloc, &cmd);
Misc::Console::t_assert(r == vk::Result::eSuccess, "Failed to allocate command buffers: " + to_string(r));
}
}
#endif | 42.078704 | 152 | 0.728793 |
2f41e4c1d1f0071946aea4c61dff3941058b388f | 567 | cpp | C++ | chap13/Exer13_28_pointer.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 50 | 2016-01-08T14:28:53.000Z | 2022-01-21T12:55:00.000Z | chap13/Exer13_28_pointer.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 2 | 2017-06-05T16:45:20.000Z | 2021-04-17T13:39:24.000Z | chap13/Exer13_28_pointer.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 18 | 2016-08-17T15:23:51.000Z | 2022-03-26T18:08:43.000Z | #include <iostream>
#include "Exer13_28_BinStrTree_point.h"
using std::cout;
using std::endl;
int main()
{
TreeNode t1("t1");
TreeNode t2 = t1;
t1.read(cout) << endl;
t2.write("t2");
t2.read(cout) << endl;
{
TreeNode t3(t2);
t3.read(cout) << endl;
t3.write("t3");
t3.read(cout) << endl;;
}
TreeNode t4("t4");
TreeNode t5("t5");
t4.read(cout) << endl;;
t5.read(cout) << endl;
t4 = t4;
BinStrTree r1;
BinStrTree r2(r1);
BinStrTree r3;
r3 = r1;
r3 = r3;
return 0;
}
| 18.9 | 39 | 0.527337 |
2f46731513ee8207fa214c84ef6cf66b94654967 | 10,622 | cpp | C++ | Common/ScenarioTest/Document/ScenarioTest.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | Common/ScenarioTest/Document/ScenarioTest.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | Common/ScenarioTest/Document/ScenarioTest.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | //================================================================================
// Copyright (c) 2013 ~ 2020. HyungKi Jeong(clonextop@gmail.com)
// All rights reserved.
//
// The 3-Clause BSD License (https://opensource.org/licenses/BSD-3-Clause)
//
// Redistribution and use in source and binary forms,
// with or without modification, are permitted provided
// that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
//
// Title : Scenario test
// Rev. : 8/13/2020 Thu (clonextop@gmail.com)
//================================================================================
#include "ScenarioTest.h"
static CString __sScenarioPath;
static CString __sProgramPath;
REGISTER_LOCALED_DOCUMENT_EX(ScenarioTest)
{
CString sName(pDoc->DocumentTitle());
if(!sName.Compare(_T("Scenario Test"))) {
// default scenario path
pDoc->DocumentTitle(_L(DOCUMENT_TITLE));
__sScenarioPath = _T("%PROJECT%Program\\ScenarioTest");
__sProgramPath = _T("%PROJECT%Program");
return TRUE;
} else {
// user defined scenario path
int iPos = 0;
LPCTSTR sDelim = _T(":");
CString sTitle = sName.Tokenize(sDelim, iPos);
__sScenarioPath = (iPos > 0) ? sName.Tokenize(sDelim, iPos) : _T("%PROJECT%Program\\ScenarioTest");
__sProgramPath = (iPos > 0) ? sName.Tokenize(sDelim, iPos) : _T("%PROJECT%Program");
sName.Format(_T("%s(%s)"), _L(DOCUMENT_TITLE), (LPCTSTR)sTitle);
pDoc->DocumentTitle(sName);
return TRUE;
}
return TRUE;
}
LPCTSTR g_sTestStatus[TEST_STATUS_SIZE];
ScenarioTest::ScenarioTest(ITDDocument* pDoc)
{
m_bInitialized = FALSE;
m_pDoc = pDoc;
m_HtmlTable.Create(pDoc, _T("../media/tables.html"), 0, 0, 100, 100);
m_HtmlTable.SetManager(this);
m_pHtmlTable = &m_HtmlTable;
{
// initialize test status string
g_sTestStatus[TEST_STATUS_NOT_TESTED] = _L(TEST_STATUS_NOT_TESTED);
g_sTestStatus[TEST_STATUS_RUN_PASSED] = _L(TEST_STATUS_RUN_PASSED);
g_sTestStatus[TEST_STATUS_RUN_FAILED] = _L(TEST_STATUS_RUN_FAILED);
g_sTestStatus[TEST_STATUS_RUN_CRACHED] = _L(TEST_STATUS_RUN_CRACHED);
g_sTestStatus[TEST_STATUS_COMPILE_FAILED] = _L(TEST_STATUS_COMPILE_FAILED);
g_sTestStatus[TEST_STATUS_LINK_FAILED] = _L(TEST_STATUS_LINK_FAILED);
g_sTestStatus[TEST_STATUS_FILE_NOT_FOUND] = _L(TEST_STATUS_FILE_NOT_FOUND);
g_sTestStatus[TEST_STATUS_SYSTEM_IS_REQUIRED] = _L(TEST_STATUS_SYSTEM_IS_REQUIRED);
g_sTestStatus[TEST_STATUS_SCORE] = _L(TEST_STATUS_SCORE);
}
{
ITDPropertyData* pProperty;
pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_NAME_FILTER, _L(NAME_FILTER), (DWORD_PTR)((LPCTSTR)m_TestList.TestFilter()), _L(DESC_NAME_FILTER));
pProperty->UpdateConfigFile();
}
{
m_TimeToday = GetCurrentDayTime();
m_pDoc->SetTimer(COMMAND_ID_REFRESH_TABLE, 1000 * 60 * 60); // every 1 hour, refresh table when day changed
}
}
ScenarioTest::~ScenarioTest(void)
{
m_pDoc->KillTimer(COMMAND_ID_REFRESH_TABLE);
}
BOOL ScenarioTest::OnPropertyUpdate(ITDPropertyData* pProperty)
{
pProperty->UpdateData();
pProperty->UpdateConfigFile(FALSE);
switch(pProperty->GetID()) {
case PROPERTY_ID_NAME_FILTER:
if(m_pDoc->IsLocked()) {
g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING));
} else {
m_TestList.Clear();
m_TestList.Refresh();
g_pSystem->LogInfo(_L(LIST_REFRESH_IS_DONE));
}
break;
default:
break;
}
return TRUE;
}
void ScenarioTest::OnSize(int width, int height)
{
if(m_HtmlTable.Control()) {
ITDLayout* pLayout;
pLayout = m_HtmlTable.Control()->GetObject()->GetLayout();
pLayout->SetSize(width, height);
}
}
BOOL ScenarioTest::OnCommand(DWORD command, WPARAM wParam, LPARAM lParam)
{
switch(command) {
case COMMAND_ID_DO_TEST:
m_pDoc->KillTimer(command);
if(OnTest())
m_pDoc->SetTimer(command, 0);
break;
case COMMAND_ID_REFRESH_TABLE:
if(!m_pDoc->IsLocked() && (m_TimeToday != GetCurrentDayTime())) {
m_TestList.Refresh();
m_TimeToday = GetCurrentDayTime();
}
break;
default:
break;
}
return FALSE;
}
LPCTSTR ScenarioTest::OnHtmlBeforeNavigate(DWORD dwID, LPCTSTR lpszURL)
{
if(m_bInitialized) {
if(_tcsstr(lpszURL, _T("group:")) == lpszURL) {
int iGroupID;
_stscanf(&lpszURL[6], _T("%d"), &iGroupID);
StartTest(&lpszURL[6]);
} else if(_tcsstr(lpszURL, _T("test:")) == lpszURL) {
StartTest(&lpszURL[5], FALSE);
} else if(_tcsstr(lpszURL, _T("folder:")) == lpszURL) {
TestGroup* pGroup = m_TestList.FindGroup(&lpszURL[7]);
if(pGroup) pGroup->OpenFolder();
} else if(_tcsstr(lpszURL, _T("open:")) == lpszURL) {
Execute(&lpszURL[5], TRUE);
} else if(_tcsstr(lpszURL, _T("execute:")) == lpszURL) {
Execute(&lpszURL[8]);
} else if(_tcsstr(lpszURL, _T("quit:")) == lpszURL) {
g_pSystem->LogWarning(_L(FORCE_TO_QUIT_PROGRAM));
TestVector* pTestVector = TestVector::CurrentTestVecotr();
if(pTestVector) ForceToQuit(pTestVector->Group()->GetConfig(TG_DESC_PROGRAM));
} else if(_tcsstr(lpszURL, _T("refresh:")) == lpszURL) {
if(m_pDoc->IsLocked()) {
g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING));
} else {
m_TestList.Refresh();
g_pSystem->LogInfo(_L(LIST_REFRESH_IS_DONE));
}
} else if(_tcsstr(lpszURL, _T("testall:")) == lpszURL) {
if(m_pDoc->IsLocked()) {
g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING));
} else StartTest();
}
return NULL;
}
return lpszURL;
}
void ScenarioTest::SetLock(BOOL bLock)
{
if(bLock) {
m_HtmlTable.JScript(_T("SetTitle(\"<table class='null0'><tbody><td><button class='ShadowButton'>%s</button></td><td style='text-align:right'></td></tbody></table>\");"), _L(TEST_IN_PROGRESS));
} else {
m_HtmlTable.JScript(_T("SetTitle(\"<table class='null0'><tbody><td><a href='testall:'><button class='ShadowButton'>%s</button></a></td><td style='text-align:right'><a href='refresh:'><img class='MiniButton' src='refresh.png' title='%s'></a></td></tbody></table>\");"), _L(TEST_ALL), _L(RESCAN_ALL));
}
if(m_bInitialized) {
if(bLock) {
m_pDoc->Lock();
} else {
m_pDoc->UnLock();
}
}
}
void ScenarioTest::OnHtmlDocumentComplete(DWORD dwID, LPCTSTR lpszURL)
{
if(!m_bInitialized) {
m_TestList.Initialize(__sScenarioPath, __sProgramPath);
SetLock(FALSE);
m_bInitialized = TRUE;
}
}
void ScenarioTest::Execute(LPCTSTR sScript, BOOL bShell)
{
CString Script(sScript);
Script.Replace(_T("/"), _T("\\"));
Script.Replace(_T("%20"), _T(" "));
{
int iPos = 0;
LPCTSTR sDelim = _T("?");
CString sExecuteFile, sArg, sRunPath;
sExecuteFile = Script.Tokenize(sDelim, iPos);
if(iPos > 0)
sArg = Script.Tokenize(sDelim, iPos);
if(iPos > 0)
sRunPath = Script.Tokenize(sDelim, iPos);
if(sRunPath.IsEmpty()) sRunPath = _T("%PROJECT%Program");
sRunPath = g_pSystem->RetrieveFullPath(sRunPath);
sExecuteFile = g_pSystem->RetrieveFullPath(sExecuteFile);
if(bShell)
ShellExecute(NULL, NULL, sExecuteFile, sArg, NULL, SW_SHOW);
else
g_pSystem->ExecuteFile(sExecuteFile, sArg, TRUE, NULL, sRunPath,
_T("*E:"), -1,
_T("*I:"), 1,
NULL);
}
}
void ScenarioTest::StartTest(LPCTSTR sPath, BOOL bGroup)
{
if(!sPath) {
// add all
TestGroup* pGroup = m_TestList.GetNextGroup();
while(pGroup) {
TestVector* pVector = pGroup->GetNextVector();
while(pVector) {
m_Scenario.push_back(pVector);
pVector = pGroup->GetNextVector(pVector);
}
pGroup = m_TestList.GetNextGroup(pGroup);
}
} else if(bGroup) {
// add group
TestGroup* pGroup = m_TestList.FindGroup(sPath);
TestVector* pVector = NULL;
if(pGroup) pVector = pGroup->GetNextVector();
while(pVector) {
m_Scenario.push_back(pVector);
pVector = pGroup->GetNextVector(pVector);
}
} else {
// add vector
TestVector* pVector = m_TestList.FindVector(sPath);
if(pVector) m_Scenario.push_back(pVector);
}
if(m_Scenario.size() > 1) {
SetEnvironmentVariable(_T("SIM_WAVE_MODE"), _T("None"));
}
{
CString sSize;
sSize.Format(_T("%d"), m_Scenario.size());
SetEnvironmentVariable(_T("GROUP_TEST_SIZE"), (LPCTSTR)sSize);
}
if(!m_pDoc->IsLocked()) {
m_pDoc->SetTimer(COMMAND_ID_DO_TEST, 0);
} else {
g_pSystem->LogInfo(_L(ADD_TEST_LIST), sPath);
}
}
BOOL ScenarioTest::OnTest(void)
{
TestVector* pVector = m_Scenario.front();
if(pVector) {
SetLock();
m_Scenario.pop_front();
pVector->DoTest();
m_TestList.UpdateTable();
SetLock(FALSE);
}
if(!m_Scenario.size()) {
ITDDocument* pDoc = g_pSystem->GetDocument(_T("System"));
if(pDoc) pDoc->GetImplementation()->OnCommand(TD_EXTERNAL_COMMAND - 1);
g_pSystem->LogInfo(_L(TEST_IS_OVER));
return FALSE;
}
return TRUE;
}
#include <TlHelp32.h>
void ScenarioTest::ForceToQuit(LPCTSTR sFileName)
{
HANDLE hSnapShot;
PROCESSENTRY32 pEntry;
hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
if(hSnapShot == INVALID_HANDLE_VALUE) {
return;
}
pEntry.dwSize = sizeof(pEntry);
if(Process32First(hSnapShot, &pEntry)) {
do {
if(!_tcscmp(pEntry.szExeFile, sFileName)) {
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pEntry.th32ProcessID);
if(hProcess) {
if(TerminateProcess(hProcess, 0)) {
unsigned long nCode;
GetExitCodeProcess(hProcess, &nCode);
}
CloseHandle(hProcess);
}
break;
}
} while(Process32Next(hSnapShot, &pEntry));
}
}
| 28.785908 | 302 | 0.695914 |
2f4974d6d95586a9cbf61a1a1bf9c636ea7023a5 | 11,536 | cpp | C++ | src/probe_renderer/bruneton_probe_renderer.cpp | Hanggansta/Nimble | 291c1bae6308c49f4e86a7ecabc97e9fe8fce654 | [
"MIT"
] | null | null | null | src/probe_renderer/bruneton_probe_renderer.cpp | Hanggansta/Nimble | 291c1bae6308c49f4e86a7ecabc97e9fe8fce654 | [
"MIT"
] | null | null | null | src/probe_renderer/bruneton_probe_renderer.cpp | Hanggansta/Nimble | 291c1bae6308c49f4e86a7ecabc97e9fe8fce654 | [
"MIT"
] | 1 | 2021-05-09T12:51:18.000Z | 2021-05-09T12:51:18.000Z | #include "bruneton_probe_renderer.h"
#include "../renderer.h"
#include "../resource_manager.h"
#include "../logger.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <gtc/matrix_transform.hpp>
namespace nimble
{
// -----------------------------------------------------------------------------------------------------------------------------------
BrunetonProbeRenderer::BrunetonProbeRenderer()
{
}
// -----------------------------------------------------------------------------------------------------------------------------------
BrunetonProbeRenderer::~BrunetonProbeRenderer()
{
}
// -----------------------------------------------------------------------------------------------------------------------------------
bool BrunetonProbeRenderer::initialize(Renderer* renderer, ResourceManager* res_mgr)
{
register_float_parameter("Sun Radius", m_sun_angular_radius);
register_float_parameter("Exposure", m_exposure);
// Values from "Reference Solar Spectral Irradiance: ASTM G-173", ETR column
// (see http://rredc.nrel.gov/solar/spectra/am1.5/ASTMG173/ASTMG173.html),
// summed and averaged in each bin (e.g. the value for 360nm is the average
// of the ASTM G-173 values for all wavelengths between 360 and 370nm).
// Values in W.m^-2.
int lambda_min = 360;
int lambda_max = 830;
double kSolarIrradiance[] = {
1.11776, 1.14259, 1.01249, 1.14716, 1.72765, 1.73054, 1.6887, 1.61253, 1.91198, 2.03474, 2.02042, 2.02212, 1.93377, 1.95809, 1.91686, 1.8298, 1.8685, 1.8931, 1.85149, 1.8504, 1.8341, 1.8345, 1.8147, 1.78158, 1.7533, 1.6965, 1.68194, 1.64654, 1.6048, 1.52143, 1.55622, 1.5113, 1.474, 1.4482, 1.41018, 1.36775, 1.34188, 1.31429, 1.28303, 1.26758, 1.2367, 1.2082, 1.18737, 1.14683, 1.12362, 1.1058, 1.07124, 1.04992
};
// Values from http://www.iup.uni-bremen.de/gruppen/molspec/databases/
// referencespectra/o3spectra2011/index.html for 233K, summed and averaged in
// each bin (e.g. the value for 360nm is the average of the original values
// for all wavelengths between 360 and 370nm). Values in m^2.
double kOzoneCrossSection[] = {
1.18e-27, 2.182e-28, 2.818e-28, 6.636e-28, 1.527e-27, 2.763e-27, 5.52e-27, 8.451e-27, 1.582e-26, 2.316e-26, 3.669e-26, 4.924e-26, 7.752e-26, 9.016e-26, 1.48e-25, 1.602e-25, 2.139e-25, 2.755e-25, 3.091e-25, 3.5e-25, 4.266e-25, 4.672e-25, 4.398e-25, 4.701e-25, 5.019e-25, 4.305e-25, 3.74e-25, 3.215e-25, 2.662e-25, 2.238e-25, 1.852e-25, 1.473e-25, 1.209e-25, 9.423e-26, 7.455e-26, 6.566e-26, 5.105e-26, 4.15e-26, 4.228e-26, 3.237e-26, 2.451e-26, 2.801e-26, 2.534e-26, 1.624e-26, 1.465e-26, 2.078e-26, 1.383e-26, 7.105e-27
};
// From https://en.wikipedia.org/wiki/Dobson_unit, in molecules.m^-2.
double kDobsonUnit = 2.687e20;
// Maximum number density of ozone molecules, in m^-3 (computed so at to get
// 300 Dobson units of ozone - for this we divide 300 DU by the integral of
// the ozone density profile defined below, which is equal to 15km).
double kMaxOzoneNumberDensity = 300.0 * kDobsonUnit / 15000.0;
// Wavelength independent solar irradiance "spectrum" (not physically
// realistic, but was used in the original implementation).
double kConstantSolarIrradiance = 1.5;
double kTopRadius = 6420000.0;
double kRayleigh = 1.24062e-6;
double kRayleighScaleHeight = 8000.0;
double kMieScaleHeight = 1200.0;
double kMieAngstromAlpha = 0.0;
double kMieAngstromBeta = 5.328e-3;
double kMieSingleScatteringAlbedo = 0.9;
double kMiePhaseFunctionG = 0.8;
double kGroundAlbedo = 0.1;
double max_sun_zenith_angle = (m_use_half_precision ? 102.0 : 120.0) / 180.0 * M_PI;
DensityProfileLayer* rayleigh_layer = new DensityProfileLayer("rayleigh", 0.0, 1.0, -1.0 / kRayleighScaleHeight, 0.0, 0.0);
DensityProfileLayer* mie_layer = new DensityProfileLayer("mie", 0.0, 1.0, -1.0 / kMieScaleHeight, 0.0, 0.0);
// Density profile increasing linearly from 0 to 1 between 10 and 25km, and
// decreasing linearly from 1 to 0 between 25 and 40km. This is an approximate
// profile from http://www.kln.ac.lk/science/Chemistry/Teaching_Resources/
// Documents/Introduction%20to%20atmospheric%20chemistry.pdf (page 10).
std::vector<DensityProfileLayer*> ozone_density;
ozone_density.push_back(new DensityProfileLayer("absorption0", 25000.0, 0.0, 0.0, 1.0 / 15000.0, -2.0 / 3.0));
ozone_density.push_back(new DensityProfileLayer("absorption1", 0.0, 0.0, 0.0, -1.0 / 15000.0, 8.0 / 3.0));
std::vector<double> wavelengths;
std::vector<double> solar_irradiance;
std::vector<double> rayleigh_scattering;
std::vector<double> mie_scattering;
std::vector<double> mie_extinction;
std::vector<double> absorption_extinction;
std::vector<double> ground_albedo;
for (int l = lambda_min; l <= lambda_max; l += 10)
{
double lambda = l * 1e-3; // micro-meters
double mie = kMieAngstromBeta / kMieScaleHeight * pow(lambda, -kMieAngstromAlpha);
wavelengths.push_back(l);
if (m_use_constant_solar_spectrum)
solar_irradiance.push_back(kConstantSolarIrradiance);
else
solar_irradiance.push_back(kSolarIrradiance[(l - lambda_min) / 10]);
rayleigh_scattering.push_back(kRayleigh * pow(lambda, -4));
mie_scattering.push_back(mie * kMieSingleScatteringAlbedo);
mie_extinction.push_back(mie);
absorption_extinction.push_back(m_use_ozone ? kMaxOzoneNumberDensity * kOzoneCrossSection[(l - lambda_min) / 10] : 0.0);
ground_albedo.push_back(kGroundAlbedo);
}
m_sky_model.m_half_precision = m_use_half_precision;
m_sky_model.m_combine_scattering_textures = m_use_combined_textures;
m_sky_model.m_use_luminance = m_use_luminance;
m_sky_model.m_wave_lengths = wavelengths;
m_sky_model.m_solar_irradiance = solar_irradiance;
m_sky_model.m_sun_angular_radius = m_sun_angular_radius;
m_sky_model.m_bottom_radius = m_bottom_radius;
m_sky_model.m_top_radius = kTopRadius;
m_sky_model.m_rayleigh_density = rayleigh_layer;
m_sky_model.m_rayleigh_scattering = rayleigh_scattering;
m_sky_model.m_mie_density = mie_layer;
m_sky_model.m_mie_scattering = mie_scattering;
m_sky_model.m_mie_extinction = mie_extinction;
m_sky_model.m_mie_phase_function_g = kMiePhaseFunctionG;
m_sky_model.m_absorption_density = ozone_density;
m_sky_model.m_absorption_extinction = absorption_extinction;
m_sky_model.m_ground_albedo = ground_albedo;
m_sky_model.m_max_sun_zenith_angle = max_sun_zenith_angle;
m_sky_model.m_length_unit_in_meters = m_length_unit_in_meters;
int num_scattering_orders = 4;
bool status = m_sky_model.initialize(num_scattering_orders, renderer, res_mgr);
glm::mat4 capture_projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 10.0f);
glm::mat4 capture_views[] = {
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f))
};
for (int i = 0; i < 6; i++)
m_cubemap_views[i] = capture_projection * capture_views[i];
m_sun_dir = glm::vec3(0.0f);
std::vector<std::string> defines;
if (m_use_luminance == LUMINANCE::NONE)
defines.push_back("RADIANCE_API_ENABLED");
if (m_use_combined_textures)
defines.push_back("COMBINED_SCATTERING_TEXTURES");
m_env_map_vs = res_mgr->load_shader("shader/bruneton_sky_model/env_map_vs.glsl", GL_VERTEX_SHADER, defines);
m_env_map_fs = res_mgr->load_shader("shader/bruneton_sky_model/env_map_fs.glsl", GL_FRAGMENT_SHADER, defines);
if (m_env_map_vs && m_env_map_fs)
{
m_env_map_program = renderer->create_program(m_env_map_vs, m_env_map_fs);
if (!m_env_map_program)
{
NIMBLE_LOG_ERROR("Failed to create program");
return false;
}
}
else
{
NIMBLE_LOG_ERROR("Failed to load shaders");
return false;
}
return status;
}
// -----------------------------------------------------------------------------------------------------------------------------------
void BrunetonProbeRenderer::env_map(double delta, Renderer* renderer, Scene* scene)
{
uint32_t num_lights = scene->directional_light_count();
DirectionalLight* lights = scene->directional_lights();
if (num_lights > 0)
{
DirectionalLight& light = lights[0];
glm::vec3 sun_dir = light.transform.forward();
if (m_sun_dir != sun_dir)
{
m_sun_dir = sun_dir;
for (int i = 0; i < 6; i++)
m_cubemap_rtv[i] = RenderTargetView(i, 0, 0, scene->env_map());
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
m_env_map_program->use();
m_sky_model.bind_rendering_uniforms(m_env_map_program.get());
m_env_map_program->set_uniform("sun_size", glm::vec2(tan(m_sun_angular_radius), cos(m_sun_angular_radius)));
m_env_map_program->set_uniform("sun_direction", -light.transform.forward());
m_env_map_program->set_uniform("earth_center", glm::vec3(0.0f, -m_bottom_radius / m_length_unit_in_meters, 0.0f));
m_env_map_program->set_uniform("exposure", m_exposure);
for (int i = 0; i < 6; i++)
{
m_env_map_program->set_uniform("view_projection", m_cubemap_views[i]);
renderer->bind_render_targets(1, &m_cubemap_rtv[i], nullptr);
glViewport(0, 0, ENVIRONMENT_MAP_SIZE, ENVIRONMENT_MAP_SIZE);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
renderer->cube_vao()->bind();
glDrawArrays(GL_TRIANGLES, 0, 36);
}
}
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
void BrunetonProbeRenderer::diffuse(double delta, Renderer* renderer, Scene* scene)
{
}
// -----------------------------------------------------------------------------------------------------------------------------------
void BrunetonProbeRenderer::specular(double delta, Renderer* renderer, Scene* scene)
{
}
// -----------------------------------------------------------------------------------------------------------------------------------
std::string BrunetonProbeRenderer::probe_contribution_shader_path()
{
return "";
}
// -----------------------------------------------------------------------------------------------------------------------------------
} // namespace nimble | 46.704453 | 527 | 0.59492 |
2f49e24392da7f48d3dc992e0586a7843d6639a6 | 18,714 | cc | C++ | Translator_file/examples/step-26/step-26.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null | Translator_file/examples/step-26/step-26.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null | Translator_file/examples/step-26/step-26.cc | jiaqiwang969/deal.ii-course-practice | 0da5ad1537d8152549d8a0e4de5872efe7619c8a | [
"MIT"
] | null | null | null |
/* ---------------------------------------------------------------------
*
* Copyright (C) 2013 - 2021 by the deal.II authors
*
* This file is part of the deal.II library.
*
* The deal.II library is free software; you can use it, redistribute
* it, and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* The full text of the license can be found in the file LICENSE.md at
* the top level directory of deal.II.
*
* ---------------------------------------------------------------------
*
* Author: Wolfgang Bangerth, Texas A&M University, 2013
*/
// 程序以通常的包含文件开始,所有这些文件你现在应该都见过了。
#include <deal.II/base/utilities.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/function.h>
#include <deal.II/base/logstream.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/affine_constraints.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/error_estimator.h>
#include <deal.II/numerics/solution_transfer.h>
#include <deal.II/numerics/matrix_tools.h>
#include <fstream>
#include <iostream>
// 然后照例将这个程序的所有内容放入一个命名空间,并将deal.II命名空间导入到我们将要工作的命名空间中。
namespace Step26
{
using namespace dealii;
// @sect3{The <code>HeatEquation</code> class}
// 下一个部分是这个程序的主类的声明。它沿用了以前的例子中公认的路径。如果你看过 step-6 ,例如,这里唯一值得注意的是,我们需要建立两个矩阵(质量和拉普拉斯矩阵),并保存当前和前一个时间步骤的解。然后,我们还需要存储当前时间、时间步长和当前时间步长的编号。最后一个成员变量表示介绍中讨论的theta参数,它允许我们在一个程序中处理显式和隐式欧拉方法,以及Crank-Nicolson方法和其他通用方法。
// 就成员函数而言,唯一可能的惊喜是 <code>refine_mesh</code> 函数需要最小和最大的网格细化级别的参数。这样做的目的在介绍中已经讨论过了。
template <int dim>
class HeatEquation
{
public:
HeatEquation();
void run();
private:
void setup_system();
void solve_time_step();
void output_results() const;
void refine_mesh(const unsigned int min_grid_level,
const unsigned int max_grid_level);
Triangulation<dim> triangulation;
FE_Q<dim> fe;
DoFHandler<dim> dof_handler;
AffineConstraints<double> constraints;
SparsityPattern sparsity_pattern;
SparseMatrix<double> mass_matrix;
SparseMatrix<double> laplace_matrix;
SparseMatrix<double> system_matrix;
Vector<double> solution;
Vector<double> old_solution;
Vector<double> system_rhs;
double time;
double time_step;
unsigned int timestep_number;
const double theta;
};
// @sect3{Equation data}
// 在下面的类和函数中,我们实现了定义这个问题的各种数据(右手边和边界值),这些数据在这个程序中使用,我们需要函数对象。右手边的选择是在介绍的最后讨论的。对于边界值,我们选择零值,但这很容易在下面改变。
template <int dim>
class RightHandSide : public Function<dim>
{
public:
RightHandSide()
: Function<dim>()
, period(0.2)
{}
virtual double value(const Point<dim> & p,
const unsigned int component = 0) const override;
private:
const double period;
};
template <int dim>
double RightHandSide<dim>::value(const Point<dim> & p,
const unsigned int component) const
{
(void)component;
AssertIndexRange(component, 1);
Assert(dim == 2, ExcNotImplemented());
const double time = this->get_time();
const double point_within_period =
(time / period - std::floor(time / period));
if ((point_within_period >= 0.0) && (point_within_period <= 0.2))
{
if ((p[0] > 0.5) && (p[1] > -0.5))
return 1;
else
return 0;
}
else if ((point_within_period >= 0.5) && (point_within_period <= 0.7))
{
if ((p[0] > -0.5) && (p[1] > 0.5))
return 1;
else
return 0;
}
else
return 0;
}
template <int dim>
class BoundaryValues : public Function<dim>
{
public:
virtual double value(const Point<dim> & p,
const unsigned int component = 0) const override;
};
template <int dim>
double BoundaryValues<dim>::value(const Point<dim> & /*p*/,
const unsigned int component) const
{
(void)component;
Assert(component == 0, ExcIndexRange(component, 0, 1));
return 0;
}
// @sect3{The <code>HeatEquation</code> implementation}
// 现在是实现主类的时候了。让我们从构造函数开始,它选择了一个线性元素,一个时间步长为1/500的常数(记得上面把右边的源的一个周期设置为0.2,所以我们用100个时间步长来解决每个周期),并通过设置 $\theta=1/2$ 选择了Crank Nicolson方法.
template <int dim>
HeatEquation<dim>::HeatEquation()
: fe(1)
, dof_handler(triangulation)
, time_step(1. / 500)
, theta(0.5)
{}
// @sect4{<code>HeatEquation::setup_system</code>}
// 下一个函数是设置DoFHandler对象,计算约束,并将线性代数对象设置为正确的大小。我们还在这里通过简单地调用库中的两个函数来计算质量和拉普拉斯矩阵。
// 注意我们在组装矩阵时不考虑悬挂节点的约束(两个函数都有一个AffineConstraints参数,默认为一个空对象)。这是因为我们要在结合当前时间步长的矩阵后,在run()中浓缩约束。
template <int dim>
void HeatEquation<dim>::setup_system()
{
dof_handler.distribute_dofs(fe);
std::cout << std::endl
<< "===========================================" << std::endl
<< "Number of active cells: " << triangulation.n_active_cells()
<< std::endl
<< "Number of degrees of freedom: " << dof_handler.n_dofs()
<< std::endl
<< std::endl;
constraints.clear();
DoFTools::make_hanging_node_constraints(dof_handler, constraints);
constraints.close();
DynamicSparsityPattern dsp(dof_handler.n_dofs());
DoFTools::make_sparsity_pattern(dof_handler,
dsp,
constraints,
/*keep_constrained_dofs = */ true);
sparsity_pattern.copy_from(dsp);
mass_matrix.reinit(sparsity_pattern);
laplace_matrix.reinit(sparsity_pattern);
system_matrix.reinit(sparsity_pattern);
MatrixCreator::create_mass_matrix(dof_handler,
QGauss<dim>(fe.degree + 1),
mass_matrix);
MatrixCreator::create_laplace_matrix(dof_handler,
QGauss<dim>(fe.degree + 1),
laplace_matrix);
solution.reinit(dof_handler.n_dofs());
old_solution.reinit(dof_handler.n_dofs());
system_rhs.reinit(dof_handler.n_dofs());
}
// @sect4{<code>HeatEquation::solve_time_step</code>}
// 下一个函数是解决单个时间步骤的实际线性系统的函数。这里没有什么值得惊讶的。
template <int dim>
void HeatEquation<dim>::solve_time_step()
{
SolverControl solver_control(1000, 1e-8 * system_rhs.l2_norm());
SolverCG<Vector<double>> cg(solver_control);
PreconditionSSOR<SparseMatrix<double>> preconditioner;
preconditioner.initialize(system_matrix, 1.0);
cg.solve(system_matrix, solution, system_rhs, preconditioner);
constraints.distribute(solution);
std::cout << " " << solver_control.last_step() << " CG iterations."
<< std::endl;
}
// @sect4{<code>HeatEquation::output_results</code>}
// 在生成图形输出方面也没有什么新东西,只是我们告诉DataOut对象当前的时间和时间步长是多少,以便将其写入输出文件中。
template <int dim>
void HeatEquation<dim>::output_results() const
{
DataOut<dim> data_out;
data_out.attach_dof_handler(dof_handler);
data_out.add_data_vector(solution, "U");
data_out.build_patches();
data_out.set_flags(DataOutBase::VtkFlags(time, timestep_number));
const std::string filename =
"solution-" + Utilities::int_to_string(timestep_number, 3) + ".vtk";
std::ofstream output(filename);
data_out.write_vtk(output);
}
// @sect4{<code>HeatEquation::refine_mesh</code>}
// 这个函数是程序中最有趣的部分。它负责自适应网格细化的工作。这个函数执行的三个任务是:首先找出需要细化/粗化的单元,然后实际进行细化,最后在两个不同的网格之间传输解向量。第一个任务是通过使用成熟的凯利误差估计器来实现的。第二项任务是实际进行再细化。这也只涉及到基本的函数,例如 <code>refine_and_coarsen_fixed_fraction</code> ,它可以细化那些具有最大估计误差的单元,这些误差加起来占60%,并粗化那些具有最小误差的单元,这些单元加起来占40%的误差。请注意,对于像当前这样的问题,即有事发生的区域正在四处移动,我们希望积极地进行粗化,以便我们能够将单元格移动到有必要的地方。
// 正如在介绍中已经讨论过的,太小的网格会导致太小的时间步长,而太大的网格会导致太小的分辨率。因此,在前两个步骤之后,我们有两个循环,将细化和粗化限制在一个允许的单元范围内。
template <int dim>
void HeatEquation<dim>::refine_mesh(const unsigned int min_grid_level,
const unsigned int max_grid_level)
{
Vector<float> estimated_error_per_cell(triangulation.n_active_cells());
KellyErrorEstimator<dim>::estimate(
dof_handler,
QGauss<dim - 1>(fe.degree + 1),
std::map<types::boundary_id, const Function<dim> *>(),
solution,
estimated_error_per_cell);
GridRefinement::refine_and_coarsen_fixed_fraction(triangulation,
estimated_error_per_cell,
0.6,
0.4);
if (triangulation.n_levels() > max_grid_level)
for (const auto &cell :
triangulation.active_cell_iterators_on_level(max_grid_level))
cell->clear_refine_flag();
for (const auto &cell :
triangulation.active_cell_iterators_on_level(min_grid_level))
cell->clear_coarsen_flag();
// 上面这两个循环略有不同,但这很容易解释。在第一个循环中,我们没有调用 <code>triangulation.end()</code> ,而是调用 <code>triangulation.end_active(max_grid_level)</code> 。这两个调用应该产生相同的迭代器,因为迭代器是按级别排序的,不应该有任何级别高于 <code>max_grid_level</code> 的单元格。事实上,这段代码确保了这种情况的发生。
// 作为网格细化的一部分,我们需要将旧的网格中的解向量转移到新的网格中。为此,我们使用了SolutionTransfer类,我们必须准备好需要转移到新网格的解向量(一旦完成细化,我们将失去旧的网格,所以转移必须与细化同时发生)。在我们调用这个函数的时候,我们将刚刚计算出解决方案,所以我们不再需要old_solution变量(它将在网格被细化后被解决方案覆盖,也就是在时间步长结束时;见下文)。换句话说,我们只需要一个求解向量,并将其复制到一个临时对象中,当我们进一步向下调用 <code>setup_system()</code> 时,它就不会被重置。
// 因此,我们将一个SolutionTransfer对象附加到旧的DoF处理程序中,以初始化它。然后,我们准备好三角形和数据向量,以便进行细化(按照这个顺序)。
SolutionTransfer<dim> solution_trans(dof_handler);
Vector<double> previous_solution;
previous_solution = solution;
triangulation.prepare_coarsening_and_refinement();
solution_trans.prepare_for_coarsening_and_refinement(previous_solution);
// 现在一切都准备好了,所以进行细化并在新网格上重新创建DoF结构,最后在 <code>setup_system</code> 函数中初始化矩阵结构和新的向量。接下来,我们实际执行从旧网格到新网格的插值解。最后一步是对解向量应用悬空节点约束,即确保位于悬空节点上的自由度值,使解是连续的。这是必要的,因为SolutionTransfer只对单元格进行局部操作,不考虑邻域。
triangulation.execute_coarsening_and_refinement();
setup_system();
solution_trans.interpolate(previous_solution, solution);
constraints.distribute(solution);
}
// @sect4{<code>HeatEquation::run</code>}
// 这是程序的主要驱动,我们在这里循环所有的时间步骤。在函数的顶部,我们通过重复第一个时间步长,设置初始全局网格细化的数量和自适应网格细化的初始周期数量。然后,我们创建一个网格,初始化我们要处理的各种对象,设置一个标签,说明我们在重新运行第一个时间步长时应该从哪里开始,并将初始解插值到网格上(我们在这里选择了零函数,当然,我们可以用更简单的方法,直接将解向量设置为零)。我们还输出一次初始时间步长。
// @note 如果你是一个有经验的程序员,你可能会对我们在这段代码中使用 <code>goto</code> 语句感到吃惊 <code>goto</code> 语句现在已经不是特别受人欢迎了,因为计算机科学界的大师之一Edsgar Dijkstra在1968年写了一封信,叫做 "Go To Statement considered harmful"(见<a href="http:en.wikipedia.org/wiki/Considered_harmful">here</a>)。这段代码的作者全心全意地赞同这一观念。 <code>goto</code> 是难以理解的。事实上,deal.II几乎不包含任何出现的情况:不包括基本上是从书本上转录的代码,也不计算重复的代码片断,在写这篇笔记时,大约60万行代码中有3个位置;我们还在4个教程程序中使用它,其背景与这里完全相同。与其在这里试图证明这种情况的出现,不如先看看代码,我们在函数的最后再来讨论这个问题。
template <int dim>
void HeatEquation<dim>::run()
{
const unsigned int initial_global_refinement = 2;
const unsigned int n_adaptive_pre_refinement_steps = 4;
GridGenerator::hyper_L(triangulation);
triangulation.refine_global(initial_global_refinement);
setup_system();
unsigned int pre_refinement_step = 0;
Vector<double> tmp;
Vector<double> forcing_terms;
start_time_iteration:
time = 0.0;
timestep_number = 0;
tmp.reinit(solution.size());
forcing_terms.reinit(solution.size());
VectorTools::interpolate(dof_handler,
Functions::ZeroFunction<dim>(),
old_solution);
solution = old_solution;
output_results();
// 然后我们开始主循环,直到计算的时间超过我们的结束时间0.5。第一个任务是建立我们需要在每个时间步骤中解决的线性系统的右手边。回顾一下,它包含项 $MU^{n-1}-(1-\theta)k_n AU^{n-1}$ 。我们把这些项放到变量system_rhs中,借助于一个临时矢量。
while (time <= 0.5)
{
time += time_step;
++timestep_number;
std::cout << "Time step " << timestep_number << " at t=" << time
<< std::endl;
mass_matrix.vmult(system_rhs, old_solution);
laplace_matrix.vmult(tmp, old_solution);
system_rhs.add(-(1 - theta) * time_step, tmp);
// 第二块是计算源项的贡献。这与术语 $k_n \left[ (1-\theta)F^{n-1} + \theta F^n \right]$ 相对应。下面的代码调用 VectorTools::create_right_hand_side 来计算向量 $F$ ,在这里我们在评估之前设置了右侧(源)函数的时间。这一切的结果最终都在forcing_terms变量中。
RightHandSide<dim> rhs_function;
rhs_function.set_time(time);
VectorTools::create_right_hand_side(dof_handler,
QGauss<dim>(fe.degree + 1),
rhs_function,
tmp);
forcing_terms = tmp;
forcing_terms *= time_step * theta;
rhs_function.set_time(time - time_step);
VectorTools::create_right_hand_side(dof_handler,
QGauss<dim>(fe.degree + 1),
rhs_function,
tmp);
forcing_terms.add(time_step * (1 - theta), tmp);
// 接下来,我们将强迫项加入到来自时间步长的强迫项中,同时建立矩阵 $M+k_n\theta A$ ,我们必须在每个时间步长中进行反转。这些操作的最后一块是消除线性系统中悬挂的节点约束自由度。
system_rhs += forcing_terms;
system_matrix.copy_from(mass_matrix);
system_matrix.add(theta * time_step, laplace_matrix);
constraints.condense(system_matrix, system_rhs);
// 在解决这个问题之前,我们还需要做一个操作:边界值。为此,我们创建一个边界值对象,将适当的时间设置为当前时间步长的时间,并像以前多次那样对其进行评估。其结果也被用来在线性系统中设置正确的边界值。
{
BoundaryValues<dim> boundary_values_function;
boundary_values_function.set_time(time);
std::map<types::global_dof_index, double> boundary_values;
VectorTools::interpolate_boundary_values(dof_handler,
0,
boundary_values_function,
boundary_values);
MatrixTools::apply_boundary_values(boundary_values,
system_matrix,
solution,
system_rhs);
}
// 有了这些,我们要做的就是解决这个系统,生成图形数据,以及......
solve_time_step();
output_results();
// ...负责网格的细化。在这里,我们要做的是:(i)在求解过程的最开始,细化所要求的次数,之后我们跳到顶部重新开始时间迭代,(ii)之后每隔五步细化一次。
// 时间循环和程序的主要部分以开始进入下一个时间步骤结束,将old_solution设置为我们刚刚计算出的解决方案。
if ((timestep_number == 1) &&
(pre_refinement_step < n_adaptive_pre_refinement_steps))
{
refine_mesh(initial_global_refinement,
initial_global_refinement +
n_adaptive_pre_refinement_steps);
++pre_refinement_step;
tmp.reinit(solution.size());
forcing_terms.reinit(solution.size());
std::cout << std::endl;
goto start_time_iteration;
}
else if ((timestep_number > 0) && (timestep_number % 5 == 0))
{
refine_mesh(initial_global_refinement,
initial_global_refinement +
n_adaptive_pre_refinement_steps);
tmp.reinit(solution.size());
forcing_terms.reinit(solution.size());
}
old_solution = solution;
}
}
} // namespace Step26
// 现在你已经看到了这个函数的作用,让我们再来看看 <code>goto</code> 的问题。从本质上讲,代码所做的事情是这样的。
// @code
// void run ()
// {
// initialize;
// start_time_iteration:
// for (timestep=1...)
// {
// solve timestep;
// if (timestep==1 && not happy with the result)
// {
// adjust some data structures;
// goto start_time_iteration; simply try again
// }
// postprocess;
// }
// }
// @endcode
// 这里,"对结果满意 "的条件是我们想保留当前的网格,还是宁愿细化网格并在新网格上重新开始。我们当然可以用下面的方法来取代 <code>goto</code> 的使用。
// @code
// void run ()
// {
// initialize;
// while (true)
// {
// solve timestep;
// if (not happy with the result)
// adjust some data structures;
// else
// break;
// }
// postprocess;
// for (timestep=2...)
// {
// solve timestep;
// postprocess;
// }
// }
// @endcode
// 这样做的好处是摆脱了 <code>goto</code> ,但缺点是必须在两个不同的地方重复实现 "解算时间步长 "和 "后处理 "操作的代码。这可以通过将这些部分的代码(在上面的实际实现中是相当大的块)放到自己的函数中来解决,但是一个带有 <code>break</code> 语句的 <code>while(true)</code> 循环并不真的比 <code>goto</code> 容易阅读或理解。
// 最后,人们可能会简单地同意,<i>in general</i> 。
// <code>goto</code> 语句是个坏主意,但要务实地指出,在某些情况下,它们可以帮助避免代码重复和尴尬的控制流。这可能就是其中之一,它与Steve McConnell在他关于良好编程实践的优秀书籍 "Code Complete" @cite CodeComplete 中采取的立场一致(见 step-1 的介绍中提到的这本书),该书花了惊人的10页来讨论一般的 <code>goto</code> 问题。
// @sect3{The <code>main</code> function}
// 走到这一步,这个程序的主函数又没有什么好讨论的了:它看起来就像自 step-6 以来的所有此类函数一样。
int main()
{
try
{
using namespace Step26;
HeatEquation<2> heat_equation_solver;
heat_equation_solver.run();
}
catch (std::exception &exc)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
| 34.212066 | 439 | 0.610185 |
2f4c96320cf49fba14bc658832b4d561c921f50e | 480 | cpp | C++ | BASIC c++/inheritance/use _OF_protected.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/inheritance/use _OF_protected.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/inheritance/use _OF_protected.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
//base class
class shape{
protected:
int width;
int height;
public:
void setwidth(int w)
{
width=w;
}
void setheight(int h)
{
height=h;
}
};
//drived class
class rectangle:public shape
{
public:
int get_area(){
return (width*height);
}
};
int main()
{
rectangle rect;
rect.setwidth(5);
rect.setheight(7);
cout<<"total area :"<<rect.get_area()<<endl;
}
| 14.117647 | 48 | 0.572917 |
2f515c43df3d33da482c89eb87ec4ec7fecec030 | 1,405 | cpp | C++ | Kattis/ummcode.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | 3 | 2021-02-19T17:01:11.000Z | 2021-03-11T16:50:19.000Z | Kattis/ummcode.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | Kattis/ummcode.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | //
// https://open.kattis.com/problems/ummcode
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <cmath>
#include <map>
#include <utility>
#include <queue>
#include <iomanip>
#include <deque>
#include <set>
#define Forcase int __t;cin>>__t;for(int cases=1;cases<=__t;cases++)
#define For(i, n) for(int i=0;i<n;i++)
#define Fore(e, arr) for(auto e:arr)
#define INF 1e9
#define LINF 1e18
#define EPS 1e-9
using ull = unsigned long long;
using ll = long long;
using namespace std;
bool um(string& s) {
Fore (c, s) {
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) {
if (c != 'm' && c != 'u') return false;
}
}
return true;
}
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
string s, str;
getline(cin, s);
stringstream ss;
ss << s;
while (ss >> s) {
if (um(s)) {
str += s;
}
}
string real;
Fore (c, str) {
if (c == 'm' || c == 'u') real += c;
}
for (int i = 0; i < real.size(); i += 7) {
char c = 0;
for (int j = i; j < i + 7; j++) {
c *= 2;
if (real[j] == 'u') {
c++;
}
}
cout << c;
}
cout << '\n';
//cout << real << ' ' << str << '\n';
return 0;
} | 19.246575 | 68 | 0.472598 |
016ab541edfdb0fec8da16e434d4e8cfc51d05ba | 3,234 | cxx | C++ | src/libprocxx/io/file_descriptor.cxx | vencik/libprocxx | 9ed1672951c7c4ac452dd3843735fe0fe3ab33d2 | [
"BSD-3-Clause"
] | null | null | null | src/libprocxx/io/file_descriptor.cxx | vencik/libprocxx | 9ed1672951c7c4ac452dd3843735fe0fe3ab33d2 | [
"BSD-3-Clause"
] | null | null | null | src/libprocxx/io/file_descriptor.cxx | vencik/libprocxx | 9ed1672951c7c4ac452dd3843735fe0fe3ab33d2 | [
"BSD-3-Clause"
] | null | null | null | /**
* \file
* \brief File descriptor wrapper
*
* \date 2018/04/01
* \author Vaclav Krpec <vencik@razdva.cz>
*
*
* LEGAL NOTICE
*
* Copyright (c) 2017, Vaclav Krpec
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "file_descriptor.hxx"
#include <stdexcept>
extern "C" {
#include <unistd.h>
#include <fcntl.h>
}
namespace libprocxx {
namespace io {
file_descriptor::file_descriptor(const file_descriptor & orig) {
close();
m_fd = ::dup(orig.m_fd);
}
file_descriptor & file_descriptor::operator = (int fd) {
close();
m_fd = fd;
return *this;
}
int file_descriptor::status() const {
int flags = ::fcntl(m_fd, F_GETFL);
if (-1 == flags)
throw std::runtime_error(
"libprocxx::io::file_descriptor::status: "
"failed to get status flags");
return flags;
}
void file_descriptor::status(int flags) {
if (-1 == ::fcntl(m_fd, F_SETFL, flags))
throw std::runtime_error(
"libprocxx::io::file_descriptor::status: "
"failed to set status flags");
}
void file_descriptor::close() {
if (closed()) return;
::close(m_fd);
m_fd = -1;
}
std::tuple<size_t, int> file_descriptor::read(void * data, size_t size) {
const ssize_t rcnt = ::read(m_fd, data, size);
return -1 == rcnt
? std::tuple<size_t, int>(0, errno)
: std::tuple<size_t, int>((size_t)rcnt, 0);
}
std::tuple<size_t, int> file_descriptor::write(const void * data, size_t size) {
const ssize_t wcnt = ::write(m_fd, data, size);
return -1 == wcnt
? std::tuple<size_t, int>(0, errno)
: std::tuple<size_t, int>((size_t)wcnt, 0);
}
}} // end of namespace libprocxx::io
| 28.619469 | 80 | 0.679344 |
016d09b9894428db9518336c24de38bfe10ec957 | 611 | cpp | C++ | neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp | homembaixinho/codeforces | 9394eaf383afedacdfe86ca48609425b14f84bdb | [
"MIT"
] | null | null | null | neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp | homembaixinho/codeforces | 9394eaf383afedacdfe86ca48609425b14f84bdb | [
"MIT"
] | null | null | null | neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp | homembaixinho/codeforces | 9394eaf383afedacdfe86ca48609425b14f84bdb | [
"MIT"
] | null | null | null | // Soma de Casas
// https://neps.academy/lesson/173
#include <iostream>
using namespace std;
#define MAXN 100000
int N, K, casas[MAXN];
int busca(int x) {
int ini=0, fim=N-1, meio;
while (ini<=fim) {
meio = (ini+fim)/2;
if (casas[meio] > x) fim = meio-1;
if (casas[meio] < x) ini = meio+1;
if (casas[meio] == x) return true;
}
return false;
}
int main() {
cin >> N;
for (int i = 0; i < N; i++) cin >> casas[i];
cin >> K;
for (int i = 0; i < N; i++) {
if (busca(K-casas[i])) {
cout << casas[i] << ' ' << K-casas[i] << endl;
break;
}
}
return 0;
}
| 16.078947 | 52 | 0.513912 |
016ebe407f7707d1008e404dfdf8d8e80e371d03 | 2,808 | cpp | C++ | Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp | karenl7/stlhj | c3f35aefe81e2f6c721e4723ba4d07930b2661e7 | [
"MIT"
] | 6 | 2019-01-30T00:11:55.000Z | 2022-03-09T02:44:51.000Z | Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp | StanfordASL/stlhj | c3f35aefe81e2f6c721e4723ba4d07930b2661e7 | [
"MIT"
] | null | null | null | Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp | StanfordASL/stlhj | c3f35aefe81e2f6c721e4723ba4d07930b2661e7 | [
"MIT"
] | 4 | 2018-09-08T00:16:55.000Z | 2022-03-09T02:44:54.000Z | void add_lane_disturbance_v2(
beacls::FloatVec& lane,
const std::vector<size_t> shape,
beacls::FloatVec range,
beacls::FloatVec gmin,
beacls::FloatVec gmax,
FLOAT_TYPE vehicle_width,
FLOAT_TYPE fill_Value,
size_t dim){
FLOAT_TYPE x_unit = (static_cast<float>(shape[0])-1)/(gmax[0]-gmin[0]);
FLOAT_TYPE y_unit = (static_cast<float>(shape[1])-1)/(gmax[1]-gmin[1]);
FLOAT_TYPE b_unit = (static_cast<float>(shape[4])-1)/(gmax[4]-gmin[4]);
long unsigned int x1 = (long unsigned int)(x_unit*(range[0]-gmin[0])+0.5);
long unsigned int x2 = (long unsigned int)(x_unit*(range[1]-gmin[0])+0.5);
beacls::IntegerVec x_index{x1,x2};
long unsigned int y1 = (long unsigned int)(y_unit*(range[2]-gmin[1])+0.5);
long unsigned int y2 = (long unsigned int)(y_unit*(range[3]-gmin[1])+0.5);
beacls::IntegerVec y_index{y1,y2};
long unsigned int x_size, y_size, z_size, a_size, b_size, y, z, a, b, b2y, yz_unit;
FLOAT_TYPE y_add = (y_unit*vehicle_width);
FLOAT_TYPE x_add = (x_unit*vehicle_width);
beacls::IntegerVec n;
x_size = x2-x1+1;
y_size = y2-y1+1;
z_size = shape[2];
a_size = shape[3];
b_size = shape[4];
// printf("x_size: %lu\n", x_size);
// printf("y_size: %lu\n", y_size);
beacls::IntegerVec b2y_index;
beacls::IntegerVec y_addvec{0,0};
beacls::IntegerVec x_addvec{(long unsigned int)((static_cast<float>(x_size)-1.)/2.-x_add+0.5),(long unsigned int)((static_cast<float>(x_size)-1.)/2.+x_add+0.5)};
beacls::IntegerVec b_addvec{(long unsigned int)((range[2]-gmin[4])*b_unit+0.5),(long unsigned int)((range[3]-gmin[4])*b_unit+0.5)};
// printf("b_addvec: %lu\n", b_addvec[0]);
// printf("b_addvec: %lu\n", b_addvec[1]);
b_addvec[1] = b_addvec[1];
FLOAT_TYPE by_unit = 1.;//static_cast<float>(b_addvec[1]-b_addvec[0]+1)/y_size;
for (b = b_addvec[0]; b < b_addvec[1]+1; ++b) {
for (a = 0; a < a_size; ++a) {
for (z = 0; z < z_size; ++z) {
y_addvec[0] = (long unsigned int)((b-b_addvec[0])/by_unit-y_add+0.5);
y_addvec[1] = (long unsigned int)((b-b_addvec[0])/by_unit+y_add+0.5);
// printf("y_addvec: %lu\n", y_addvec[0]);
// printf("y_addvec: %lu\n", y_addvec[1]);
if (y_addvec[0]<0 || y_addvec[0]>1000){
y_addvec[0] = 0;
}
if (y_addvec[1]>y_size-1){
y_addvec[1] = y_size-1;
}
for (y = y_addvec[0]; y < y_addvec[1]+1; ++y){
n = {b*a_size*z_size*y_size*x_size + a*z_size*y_size*x_size + z*y_size*x_size + y*x_size + x_addvec[0], b*a_size*z_size*y_size*x_size + a*z_size*y_size*x_size + z*y_size*x_size + y*x_size + x_addvec[1]};
std::fill(lane.begin()+n[0],lane.begin()+n[1]+1,fill_Value);
}
}
}
}
}
| 40.114286 | 215 | 0.603276 |
0170c9fa6a328def88ae44587ce0c326d53f3be7 | 1,619 | cpp | C++ | src/log/log.cpp | kodo-pp/IVR | e904341d1850baf81e8aeecbf498691fbe8e50aa | [
"MIT"
] | null | null | null | src/log/log.cpp | kodo-pp/IVR | e904341d1850baf81e8aeecbf498691fbe8e50aa | [
"MIT"
] | 8 | 2018-05-26T19:27:53.000Z | 2018-10-28T19:31:33.000Z | src/log/log.cpp | kodo-pp/IVR | e904341d1850baf81e8aeecbf498691fbe8e50aa | [
"MIT"
] | 1 | 2019-05-07T15:32:38.000Z | 2019-05-07T15:32:38.000Z | #include <atomic>
#include <chrono>
#include <codecvt>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <locale>
#include <mutex>
#include <modbox/log/log.hpp>
static std::recursive_mutex lbfMutex;
std::recursive_mutex logMutex;
static std::wstring cachedLineBegin;
static std::atomic<time_t> prevTime(0);
// OK, too lazy to cope with references, so let's pray and hope that compiler
// will optimize it to move semantics
static LogStream logStream([]() -> std::wstring {
auto stl_now = std::chrono::system_clock::now();
time_t c_now = std::chrono::system_clock::to_time_t(stl_now);
if (c_now == prevTime) {
lbfMutex.lock();
std::wstring copied = cachedLineBegin;
lbfMutex.unlock();
return copied;
}
prevTime = c_now;
struct tm* tm_now = new struct tm;
localtime_r(&c_now, tm_now);
char* lineBegin;
// Current time
// Example:
// [LOG: 23.11.2039 16:44:37]
asprintf(&lineBegin,
"[LOG: %02d.%02d.%d %02d:%02d:%02d] T~%04u | ",
tm_now->tm_mday,
tm_now->tm_mon + 1,
tm_now->tm_year + 1900,
tm_now->tm_hour,
tm_now->tm_min,
tm_now->tm_sec,
(uint)pthread_self() % 10000);
std::wstring stlLineBegin(lineBegin, lineBegin + strlen(lineBegin));
free(lineBegin);
lbfMutex.lock();
cachedLineBegin = stlLineBegin;
lbfMutex.unlock();
delete tm_now;
return stlLineBegin;
});
static LogStream& logStreamLink = logStream;
LogStream& getLogStream()
{
return logStreamLink;
}
| 24.164179 | 77 | 0.632489 |
01711e943bc73ff5e41c51c8f7030c4bafda1b67 | 7,173 | cpp | C++ | src_legacy/2018/test/test_PlayFramesAction.cpp | gmoehler/ledpoi | d1294b172b7069f62119c310399d80500402d882 | [
"MIT"
] | null | null | null | src_legacy/2018/test/test_PlayFramesAction.cpp | gmoehler/ledpoi | d1294b172b7069f62119c310399d80500402d882 | [
"MIT"
] | 75 | 2017-05-28T23:39:33.000Z | 2019-05-09T06:18:44.000Z | src_legacy/2018/test/test_PlayFramesAction.cpp | gmoehler/ledpoi | d1294b172b7069f62119c310399d80500402d882 | [
"MIT"
] | null | null | null | #include "test.h"
#include "player/PlayFramesAction.h"
TEST(playFramesAction_tests, afterDeclaration){
PlayFramesAction playFramesAction;
playFramesAction.printInfo("pre:");
EXPECT_FALSE(playFramesAction.isActive());
}
TEST(playFramesAction_tests, afterInit){
PlayFramesAction playFramesAction;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 50, 3, 0, 100}};
PixelFrame sframe;
ActionOptions options;
playFramesAction.init(rawCmd0, &sframe, options);
EXPECT_TRUE(playFramesAction.isActive( ));
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
}
TEST(playFramesAction_tests, printStateForStaticFrame){
PlayFramesAction playFramesAction;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 10, 1, 0, 100}};
PixelFrame sframe;
ActionOptions options;
playFramesAction.init(rawCmd0, &sframe, options);
playFramesAction.printInfo("pre:");
EXPECT_TRUE(playFramesAction.isActive());
EXPECT_STREQ(playFramesAction.getActionName(), "Play Frame");
}
TEST(playFramesAction_tests, wrongAaction){
PlayFramesAction playFramesAction;
RawPoiCommand rawCmd0 = {{ANIMATE, 10, 50, 3, 0, 100}};
PixelFrame sframe;
ActionOptions options;
playFramesAction.init(rawCmd0, &sframe, options);
}
TEST(playFramesAction_tests, testNext){
PlayFramesAction playFramesAction;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 12, 3, 0, 100}};
PixelFrame sframe;
ActionOptions options;
playFramesAction.init(rawCmd0, &sframe, options);
EXPECT_FALSE(sframe.isLastFrame);
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
playFramesAction.next();
playFramesAction.printState();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 11);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 1);
}
TEST(playFramesAction_tests, testNextWithPixelFrame){
// 3 frames: red, blue, green
for (int p=0; p<N_PIXELS; p++){
imageCache.setPixel(0, p, RED);
}
for (int p=0; p<N_PIXELS; p++){
imageCache.setPixel(1, p, BLUE);
}
for (int p=0; p<N_PIXELS; p++){
imageCache.setPixel(2 ,p, GREEN);
}
PixelFrame sframe;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 0, 4, 3, 0, 100}};
PlayFramesAction playFramesAction;
ActionOptions options;
playFramesAction.init(rawCmd0, &sframe, options);
// test the first 3 frames
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 0);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
rgbVal rgb0 = sframe.pixel[0];
EXPECT_EQ(rgb0.r, 254);
EXPECT_EQ(rgb0.g, 0);
EXPECT_EQ(rgb0.b, 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 1);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
rgb0 = sframe.pixel[0];
EXPECT_EQ(rgb0.r, 0);
EXPECT_EQ(rgb0.g, 0);
EXPECT_EQ(rgb0.b, 254);
playFramesAction.setDimFactor(0.1);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 2);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
rgb0 = sframe.pixel[0];
EXPECT_EQ(rgb0.r, 0);
EXPECT_EQ(rgb0.g, 25); // 254/10
EXPECT_EQ(rgb0.b, 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 3);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
EXPECT_EQ(rgb0.r, 0);
}
TEST(playFramesAction_tests, testWithDimFactor){
// 3 frames: red, blue, green
for (int p=0; p<N_PIXELS; p++){
imageCache.setPixel(0, p, RED);
}
for (int p=0; p<N_PIXELS; p++){
imageCache.setPixel(1, p, BLUE);
}
for (int p=0; p<N_PIXELS; p++){
imageCache.setPixel(2 ,p, GREEN);
}
PixelFrame sframe;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 0, 4, 3, 0, 100}};
PlayFramesAction playFramesAction;
ActionOptions options;
options.dimFactor = 0.1;
playFramesAction.init(rawCmd0, &sframe, options);
playFramesAction.printInfo("");
// test the first 3 frames
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 0);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
rgbVal rgb0 = sframe.pixel[0];
EXPECT_EQ(rgb0.r, 25); // 254/10
EXPECT_EQ(rgb0.g, 0);
EXPECT_EQ(rgb0.b, 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 1);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
rgb0 = sframe.pixel[0];
EXPECT_EQ(rgb0.r, 0);
EXPECT_EQ(rgb0.g, 0);
EXPECT_EQ(rgb0.b, 25); // 254/10
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 2);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
rgb0 = sframe.pixel[0];
EXPECT_EQ(rgb0.r, 0);
EXPECT_EQ(rgb0.g, 25); // 254/10
EXPECT_EQ(rgb0.b, 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 3);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
EXPECT_EQ(rgb0.r, 0);
}
TEST(playFramesAction_tests, testFinishedAbstract){
PixelFrame sframe;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 12, 3, 0, 100}};
PlayFramesAction playFramesAction;
ActionOptions options;
playFramesAction.init(rawCmd0, &sframe, options);
AbstractAction *a = dynamic_cast<AbstractAction*>(&playFramesAction);
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
EXPECT_FALSE(sframe.isLastFrame);
for (int i=0; i<3*3-2; i++) {
a->next();
EXPECT_FALSE(sframe.isLastFrame);
}
// last iteration
a->next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2);
EXPECT_TRUE(playFramesAction.isActive());
EXPECT_FALSE(sframe.isLastFrame);
// finished
a->next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2);
EXPECT_FALSE(playFramesAction.isActive());
EXPECT_TRUE(sframe.isLastFrame);
}
TEST(playFramesAction_tests, testBackwardComplete){
PixelFrame sframe;
RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 12, 10, 3, 0, 100}};
PlayFramesAction playFramesAction;
ActionOptions options;
EXPECT_FALSE(playFramesAction.isActive());
playFramesAction.init(rawCmd0, &sframe, options);
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 11);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0);
EXPECT_FALSE(sframe.isLastFrame);
for (int i=0; i<3*3-3; i++) {
playFramesAction.next();
EXPECT_FALSE(sframe.isLastFrame);
}
// last iteration
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2);
EXPECT_TRUE(playFramesAction.isActive());
EXPECT_FALSE(sframe.isLastFrame);
// finished
playFramesAction.next();
EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10);
EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2);
EXPECT_FALSE(playFramesAction.isActive());
EXPECT_TRUE(sframe.isLastFrame);
}
| 29.763485 | 71 | 0.732748 |
017121b2618bd18b2603d506038026bf18a44dfb | 1,879 | cpp | C++ | ikloader.cpp | willsirius/Openrave_Painter | 2584722ee23f97baa54c56d7c9fffcbe895a3cc6 | [
"MIT"
] | null | null | null | ikloader.cpp | willsirius/Openrave_Painter | 2584722ee23f97baa54c56d7c9fffcbe895a3cc6 | [
"MIT"
] | null | null | null | ikloader.cpp | willsirius/Openrave_Painter | 2584722ee23f97baa54c56d7c9fffcbe895a3cc6 | [
"MIT"
] | null | null | null | #include <openrave-core.h>
#include <vector>
#include <cstring>
#include <sstream>
#include <stdio.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/format.hpp>
using namespace OpenRAVE;
using namespace std;
int main(int argc, char ** argv)
{
if( argc < 3 ) {
RAVELOG_INFO("ikloader robot iktype\n");
return 1;
}
string robotname = argv[1];
string iktype = argv[2];
RaveInitialize(true); // start openrave core
EnvironmentBasePtr penv = RaveCreateEnvironment(); // create the main environment
{
// lock the environment to prevent changes
EnvironmentMutex::scoped_lock lock(penv->GetMutex());
// load the scene
RobotBasePtr probot = penv->ReadRobotXMLFile(robotname);
if( !probot ) {
penv->Destroy();
return 2;
}
penv->Add(probot);
ModuleBasePtr pikfast = RaveCreateModule(penv,"ikfast");
penv->Add(pikfast,true,"");
stringstream ssin,ssout;
ssin << "LoadIKFastSolver " << probot->GetName() << " " << iktype;
// if necessary, add free inc for degrees of freedom
//ssin << " " << 0.04f;
// get the active manipulator
RobotBase::ManipulatorPtr pmanip = probot->GetActiveManipulator();
if( !pikfast->SendCommand(ssout,ssin) ) {
RAVELOG_ERROR("failed to load iksolver\n");
penv->Destroy();
return 1;
}
RAVELOG_INFO("testing random ik\n");
while(1) {
Transform trans;
trans.rot = quatFromAxisAngle(Vector(RaveRandomFloat()-0.5,RaveRandomFloat()-0.5,RaveRandomFloat()-0.5));
trans.trans = Vector(RaveRandomFloat()-0.5,RaveRandomFloat()-0.5,RaveRandomFloat()-0.5)*2;
vector<dReal> vsolution;
if( pmanip->FindIKSolution(IkParameterization(trans),vsolution,IKFO_CheckEnvCollisions) ) {
stringstream ss; ss << "solution is: ";
for(size_t i = 0; i < vsolution.size(); ++i) {
ss << vsolution[i] << " ";
}
ss << endl;
RAVELOG_INFO(ss.str());
}
else {
// could fail due to collisions, etc
}
}
}
RaveDestroy(); // destroy
return 0;
}
| 28.469697 | 105 | 0.723789 |
01715332cdd82763d0e23ef996bb901ffbd4d0c7 | 16,727 | cpp | C++ | jani/inspector/ui/BaseWindow.cpp | RodrigoHolztrattner/JANI | cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8 | [
"MIT"
] | null | null | null | jani/inspector/ui/BaseWindow.cpp | RodrigoHolztrattner/JANI | cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8 | [
"MIT"
] | null | null | null | jani/inspector/ui/BaseWindow.cpp | RodrigoHolztrattner/JANI | cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Filename: BaseWindow.cpp
////////////////////////////////////////////////////////////////////////////////
#include "BaseWindow.h"
#include "imgui.h"
#include "..\imgui_extension.h"
Jani::Inspector::BaseWindow::BaseWindow(InspectorManager& _inspector_manager, const std::string _window_type_name) : m_inspector_manager(_inspector_manager)
{
static WindowId unique_index_counter = 0;
m_unique_id = unique_index_counter++;
m_name = _window_type_name;
m_unique_name = _window_type_name + "###" + std::to_string(m_unique_id);
}
Jani::Inspector::BaseWindow::~BaseWindow()
{
RemoveAllInputWindowConnections(*this);
RemoveAllOutputWindowConnections(*this);
}
void Jani::Inspector::BaseWindow::PreUpdate()
{
m_updated = false;
}
void Jani::Inspector::BaseWindow::Update()
{
m_updated = true;
}
void Jani::Inspector::BaseWindow::Draw(
const CellsInfos& _cell_infos,
const WorkersInfos& _workers_infos)
{
}
void Jani::Inspector::BaseWindow::DrawConnections()
{
auto DrawConnection = [](ImVec2 _from, ImVec2 _to, ImColor _color) -> void
{
ImVec2 lenght = ImVec2(_to.x - _from.x, _to.y - _from.y);
float factor_from_points = std::sqrt(std::pow(lenght.x, 2) + std::pow(lenght.y, 2)) / 2.0f;
auto pos0 = _from;
auto cp0 = ImVec2(_from.x - factor_from_points, _from.y);
auto cp1 = ImVec2(_to.x + factor_from_points, _to.y);
auto pos1 = _to;
ImGui::GetForegroundDrawList()->AddBezierCurve(
pos0,
cp0,
cp1,
pos1,
_color,
2);
};
auto GetColorForDataType = [](WindowDataType _data_type) -> ImColor
{
switch (_data_type)
{
case WindowDataType::EntityData:
{
return ImColor(ImVec4(0.9f, 0.3f, 0.3f, 1.0f));
}
case WindowDataType::EntityId:
{
return ImColor(ImVec4(0.3f, 0.9f, 0.3f, 1.0f));
}
case WindowDataType::Constraint:
{
return ImColor(ImVec4(0.3f, 0.3f, 0.9f, 1.0f));
}
case WindowDataType::Position:
{
return ImColor(ImVec4(0.7f, 0.9f, 0.3f, 1.0f));
}
case WindowDataType::VisualizationSettings:
{
return ImColor(ImVec4(0.3f, 0.7f, 0.9f, 1.0f));
}
default:
{
return ImColor(ImVec4(0.9f, 0.9f, 0.9f, 1.0f));
}
}
};
for (int i = 0; i < m_output_connections.size(); i++)
{
auto& output_connection_info = m_output_connections[i];
for (auto& [window_id, window] : output_connection_info)
{
DrawConnection(m_outputs_position, window->GetConnectionInputPosition(), GetColorForDataType(magic_enum::enum_value<WindowDataType>(i)));
}
}
if (m_receiving_connection)
{
DrawConnection(m_receiving_connection->window->GetConnectionOutputPosition(), m_inputs_position, GetColorForDataType(m_receiving_connection->data_type));
}
if (m_creating_connection_payload)
{
DrawConnection(m_outputs_position, ImGui::GetMousePos(), GetColorForDataType(m_creating_connection_payload->data_type));
}
}
bool Jani::Inspector::BaseWindow::CanAcceptInputConnection(const WindowInputConnection& _connection)
{
return false;
}
std::optional<Jani::Inspector::WindowInputConnection> Jani::Inspector::BaseWindow::DrawOutputOptions(ImVec2 _button_size)
{
return std::nullopt;
}
Jani::Inspector::WindowDataType Jani::Inspector::BaseWindow::GetInputTypes() const
{
return WindowDataType::None;
}
Jani::Inspector::WindowDataType Jani::Inspector::BaseWindow::GetOutputTypes() const
{
return WindowDataType::None;
}
std::optional<std::unordered_map<Jani::EntityId, Jani::Inspector::EntityData>> Jani::Inspector::BaseWindow::GetOutputEntityData() const
{
return std::nullopt;
}
std::optional<std::vector<Jani::EntityId>> Jani::Inspector::BaseWindow::GetOutputEntityId() const
{
return std::nullopt;
}
std::optional<std::vector<std::shared_ptr<Jani::Inspector::Constraint>>> Jani::Inspector::BaseWindow::GetOutputConstraint() const
{
return std::nullopt;
}
std::optional<std::vector<Jani::WorldPosition>> Jani::Inspector::BaseWindow::GetOutputPosition() const
{
return std::nullopt;
}
std::optional<Jani::Inspector::VisualizationSettings> Jani::Inspector::BaseWindow::GetOutputVisualizationSettings() const
{
return std::nullopt;
}
void Jani::Inspector::BaseWindow::OnPositionChange(ImVec2 _current_pos, ImVec2 _new_pos, ImVec2 _delta)
{
/* stub */
}
void Jani::Inspector::BaseWindow::OnSizeChange(ImVec2 _current_size, ImVec2 _new_size, ImVec2 _delta)
{
/* stub */
}
Jani::Inspector::WindowId Jani::Inspector::BaseWindow::GetId() const
{
return m_unique_id;
}
bool Jani::Inspector::BaseWindow::WasUpdated() const
{
return m_updated;
}
ImVec2 Jani::Inspector::BaseWindow::GetWindowPos() const
{
return m_window_pos;
}
ImVec2 Jani::Inspector::BaseWindow::GetWindowSize() const
{
return m_is_visible ? m_window_size : ImVec2(m_window_size.x, m_header_height);
}
const std::string Jani::Inspector::BaseWindow::GetUniqueName() const
{
return m_unique_name;
}
bool Jani::Inspector::BaseWindow::IsVisible() const
{
return m_is_visible;
}
void Jani::Inspector::BaseWindow::DrawTitleBar(bool _edit_mode, std::optional<WindowInputConnection> _connection)
{
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.25f, 0.25f, 0.25f, 1.0f));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
if (ImGui::BeginChild("Title Bar", ImVec2(ImGui::GetWindowSize().x, m_header_height), false, ImGuiWindowFlags_NoDecoration))
{
if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered())
{
m_is_moving = true;
}
ImGui::AlignTextToFramePadding();
ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPos().x + 5.0f, ImGui::GetCursorPos().y));
if (ImGui::Button("#"))
{
m_is_visible = !m_is_visible;
}
ImGui::SameLine();
ImGui::Text(m_name.c_str());
ImGui::SameLine();
ImVec2 current_cursor_pos = ImGui::GetCursorPos();
float remaining_width = ImGui::GetWindowSize().x;
float options_button_size = ImGui::CalcTextSize("*").x + 20.0f;
float input_button_size = ImGui::CalcTextSize("+ INPUT").x + 5.0f;
float output_button_size = ImGui::CalcTextSize("- OUTPUT").x + 10.0f;
float input_button_begin = remaining_width - (options_button_size + input_button_size + output_button_size);
float output_button_begin = remaining_width - (options_button_size + output_button_size);
float options_button_begin = remaining_width - options_button_size;
if (_edit_mode)
{
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.3f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.5f, 0.5f, 0.5f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.4f, 0.4f, 0.4f, 1.0f));
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 2.0f);
ImGui::SetWindowFontScale(0.7f);
ImGui::SetCursorPos(ImVec2(input_button_begin, current_cursor_pos.y + 3.0f));
m_inputs_position = ImGui::GetCursorScreenPos();
if (_connection && (_connection->window == this || !CanAcceptInputConnection(_connection.value()))) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); }
ImGui::Button("+ INPUT");
if (_connection && (_connection->window == this || !CanAcceptInputConnection(_connection.value()))) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); }
if (ImGui::IsItemHovered() && ImGui::IsMouseReleased(0) && _connection && _connection->window != this && !ImGui::GetIO().KeyCtrl)
{
m_receiving_connection = _connection;
ImGui::OpenPopup("Input Popup");
}
if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl)
{
RemoveAllInputWindowConnections(*this);
}
m_inputs_position = m_inputs_position + ImVec2(ImGui::GetItemRectSize().x / 2.0f, ImGui::GetItemRectSize().y / 2.0f);
ImGui::SameLine();
ImGui::SetCursorPos(ImVec2(output_button_begin, current_cursor_pos.y + 3.0f));
m_outputs_position = ImGui::GetCursorScreenPos();
if (_connection) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); }
if (ImGui::Button("- OUTPUT"))
{
ImGui::OpenPopup("Output Popup");
}
if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl)
{
RemoveAllOutputWindowConnections(*this);
}
if (_connection) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); }
m_outputs_position = m_outputs_position + ImVec2(ImGui::GetItemRectSize().x / 2.0f, ImGui::GetItemRectSize().y / 2.0f);
ImGui::SetWindowFontScale(1.0f);
ImGui::PopStyleVar();
ImGui::PopStyleColor(3);
ImGui::SameLine();
}
ImGui::SetCursorPos(ImVec2(options_button_begin, current_cursor_pos.y));
if (ImGui::Button("*"))
{
}
ImGui::NewLine();
if (ImGui::BeginPopup("Input Popup") && m_receiving_connection)
{
if (CanAcceptInputConnection(m_receiving_connection.value()))
{
AddWindowConnection(*m_receiving_connection->window, *this, m_receiving_connection->data_type, m_receiving_connection->connection_type);
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
else
{
m_receiving_connection = std::nullopt;
}
if (ImGui::BeginPopup("Output Popup"))
{
auto creating_connection_payload = DrawOutputOptions(ImVec2(200.0f, 30.0f));
if (creating_connection_payload)
{
m_creating_connection_payload = creating_connection_payload;
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
} ImGui::EndChild();
ImGui::PopStyleVar();
ImGui::PopStyleColor();
if (!ImGui::IsMouseDown(0))
{
m_is_moving = false;
}
if (m_is_moving)
{
auto IO = ImGui::GetIO();
OnPositionChange(ImGui::GetWindowPos(), ImGui::GetWindowPos() + IO.MouseDelta, IO.MouseDelta);
m_window_pos = ImVec2(ImGui::GetWindowPos().x + IO.MouseDelta.x, ImGui::GetWindowPos().y + IO.MouseDelta.y);
}
}
void Jani::Inspector::BaseWindow::ProcessResize()
{
if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered())
{
float resize_bar_length = 10.0f;
auto mouse_position = ImGui::GetMousePos();
auto left_pos_diff = mouse_position.x - m_window_pos.x;
auto top_pos_diff = mouse_position.y - m_window_pos.y;
auto right_pos_diff = (m_window_pos.x + m_window_size.x) - mouse_position.x;
auto bottom_pos_diff = (m_window_pos.y + m_window_size.y) - mouse_position.y;
if (left_pos_diff > 0.f && left_pos_diff < resize_bar_length)
{
m_is_resizing[0] = true;
}
if (top_pos_diff > 0.f && top_pos_diff < resize_bar_length)
{
// m_is_resizing[1] = true;
}
if (right_pos_diff > 0.f && right_pos_diff < resize_bar_length)
{
m_is_resizing[2] = true;
}
if (bottom_pos_diff > 0.f && bottom_pos_diff < resize_bar_length)
{
m_is_resizing[3] = true;
}
}
if (!ImGui::IsMouseDown(0))
{
m_is_resizing[0] = false;
m_is_resizing[1] = false;
m_is_resizing[2] = false;
m_is_resizing[3] = false;
}
/*
if (m_is_resizing[0])
{
OnSizeChange(m_window_size, m_window_size - ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f), ImVec2(-ImGui::GetIO().MouseDelta.x, 0.0f));
m_window_pos.x += ImGui::GetIO().MouseDelta.x;
m_window_size.x -= ImGui::GetIO().MouseDelta.x;
}
*/
/*
if (m_is_resizing[1])
{
m_window_pos.y -= ImGui::GetIO().MouseDelta.y;
m_window_size.y += ImGui::GetIO().MouseDelta.y;
}
*/
if (m_is_resizing[2])
{
OnSizeChange(m_window_size, m_window_size + ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f), ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f));
m_window_size.x += ImGui::GetIO().MouseDelta.x;
}
if (m_is_resizing[3])
{
OnSizeChange(m_window_size, m_window_size + ImVec2(0.0f, ImGui::GetIO().MouseDelta.y), ImVec2(0.0f, ImGui::GetIO().MouseDelta.y));
m_window_size.y += ImGui::GetIO().MouseDelta.y;
}
}
ImVec2 Jani::Inspector::BaseWindow::GetConnectionInputPosition() const
{
return m_inputs_position;
}
ImVec2 Jani::Inspector::BaseWindow::GetConnectionOutputPosition() const
{
return m_outputs_position;
}
std::optional<Jani::Inspector::WindowInputConnection> Jani::Inspector::BaseWindow::GetCreatingConnectionPayload() const
{
return m_creating_connection_payload;
}
void Jani::Inspector::BaseWindow::ResetIsCreatingConnection()
{
m_creating_connection_payload = std::nullopt;
}
bool Jani::Inspector::BaseWindow::AddWindowConnection(BaseWindow& _from, BaseWindow& _to, WindowDataType _data_type, WindowConnectionType _connection_type)
{
auto data_enum_index = magic_enum::enum_index(_data_type);
if (!data_enum_index)
{
return false;
}
if (IsConnectedRecursively(_to, _from))
{
return false;
}
if (_to.m_input_connections[data_enum_index.value()] != std::nullopt
|| _from.m_output_connections[data_enum_index.value()].find(_to.GetId()) != _from.m_output_connections[data_enum_index.value()].end())
{
return false;
}
_to.m_input_connections[data_enum_index.value()] = { &_from, _data_type, _connection_type };
_from.m_output_connections[data_enum_index.value()].insert({ _to.GetId(),&_to });
return true;
}
bool Jani::Inspector::BaseWindow::IsConnectedRecursively(BaseWindow& _current_window, BaseWindow& _target)
{
for (auto& output_connections : _current_window.m_output_connections)
{
for (auto& [window_id, window] : output_connections)
{
if (window_id == _target.GetId())
{
return true;
}
if (IsConnectedRecursively(*window, _target))
{
return true;
}
}
}
return false;
}
bool Jani::Inspector::BaseWindow::RemoveWindowConnection(BaseWindow& _window, WindowDataType _data_type)
{
auto data_enum_index = magic_enum::enum_index(_data_type);
if (!data_enum_index)
{
return false;
}
if (_window.m_input_connections[data_enum_index.value()] == std::nullopt)
{
return false;
}
_window.m_input_connections[data_enum_index.value()].value().window->m_output_connections[data_enum_index.value()].erase(_window.GetId());
_window.m_input_connections[data_enum_index.value()] = std::nullopt;
return true;
}
void Jani::Inspector::BaseWindow::RemoveAllInputWindowConnections(BaseWindow& _window)
{
for (int i = 0; i < magic_enum::enum_count<WindowDataType>(); i++)
{
if (_window.m_input_connections[i].has_value())
{
RemoveWindowConnection(_window, magic_enum::enum_value<WindowDataType>(i));
}
}
}
void Jani::Inspector::BaseWindow::RemoveAllOutputWindowConnections(BaseWindow& _window)
{
for (auto& output_connection_info : _window.m_output_connections)
{
for (auto& [window_id, window] : output_connection_info)
{
for (int i = 0; i < window->m_input_connections.size(); i++)
{
auto& other_window_input_connection = window->m_input_connections[i];
if (other_window_input_connection && other_window_input_connection->window->GetId() == _window.GetId())
{
other_window_input_connection = std::nullopt;
}
}
}
output_connection_info.clear();
}
} | 32.99211 | 241 | 0.628505 |
0171b344cb1d582828969b7e099d9e2168cb09f5 | 5,000 | cpp | C++ | trunk/src/kernel/lbmemcheck.cpp | breezeewu/media-server | b7f6e7c24a1c849180ba31088250c0174b1112e0 | [
"MIT"
] | null | null | null | trunk/src/kernel/lbmemcheck.cpp | breezeewu/media-server | b7f6e7c24a1c849180ba31088250c0174b1112e0 | [
"MIT"
] | null | null | null | trunk/src/kernel/lbmemcheck.cpp | breezeewu/media-server | b7f6e7c24a1c849180ba31088250c0174b1112e0 | [
"MIT"
] | null | null | null | #include <lbmemcheck.hpp>
#include <srs_kernel_log.hpp>
#ifndef lbtrace
#define lbtrace srs_trace
#endif
#ifndef lberror
#define lberror srs_error
#endif
lbmemcheck_ctx* g_pmcc = NULL;
lbmemcheck_ctx* lbmemcheck_initialize()
{
lbmemcheck_ctx* pmcc = (lbmemcheck_ctx*)::calloc(1, sizeof(lbmemcheck_ctx));
pmcc->plist = lblist_create_context(__INT32_MAX__);
#ifdef ENABLE_PTHREAD_MUTEX_LOCK
pmcc->pmutex = (pthread_mutex_t*)::malloc(sizeof(pthread_mutex_t));
memset(pmcc->pmutex, 0, sizeof(pthread_mutex_t));
pthread_mutexattr_t attr;
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(pmcc->plist->pmutex, &attr);
#endif
lbtrace("pmcc:%p = lbmemcheck_initialize\n", pmcc);
return pmcc;
}
void lbmemcheck_finialize(lbmemcheck_ctx** ppmcc)
{
lbtrace("lbmemcheck_finialize, ppmcc:%p\n", ppmcc);
if(ppmcc && *ppmcc)
{
lbmemcheck_ctx* pmcc = *ppmcc;
lbtrace("lbmemcheck_finialize, pmcc:%p\n", pmcc);
#ifdef ENABLE_PTHREAD_MUTEX_LOCK
pthread_mutex_lock(pmcc->pmutex);
#endif
lbmem_blk* pmb = NULL;
lblist_node* pnode = NULL;
lbtrace("%d block of memory maybe leak\n", lblist_size(pmcc->plist));
while(lblist_size(pmcc->plist) > 0)//(pmb = (lbmem_blk*)lblist_pop(pmcc->plist))
{
pmb = (lbmem_blk*)lblist_pop(pmcc->plist);
lbtrace("leak memory [%s:%d %s] memory ptr:%p, size:%d\n", pmb->pfile_name, pmb->nfile_line, pmb->pfunc_name, pmb->pblock_ptr, pmb->nblock_size);
if(pmb->pfile_name)
{
::free(pmb->pfile_name);
pmb->pfile_name = NULL;
}
if(pmb->pfunc_name)
{
::free(pmb->pfunc_name);
pmb->pfunc_name = NULL;
}
::free(pmb);
}
lblist_close_context(&pmcc->plist);
#ifdef ENABLE_PTHREAD_MUTEX_LOCK
pthread_mutex_unlock(pmcc->pmutex);
pthread_mutex_destroy(pmcc->pmutex);
free(pmcc->pmutex);
#endif
::free(pmcc);
*ppmcc = pmcc = NULL;
}
}
int lbmemcheck_add_block(lbmemcheck_ctx* pmcc, void* ptr, int size, const char* pfile_name, const int nfile_line, const char* pfunc_name)
{
if(!pmcc || !ptr)
{
return -1;
}
//lbtrace("new T(pmcc:%p, ptr:%p, size:%d, pfile_name:%s, nfile_line:%d, pfunc_name:%s)\n", pmcc, ptr, size, pfile_name, nfile_line, pfunc_name);
assert(pmcc);
assert(ptr);
lbmem_blk* pmb = (lbmem_blk*)::calloc(1, sizeof(lbmem_blk));
if(NULL == pmb)
{
lberror("out of memory calloc lbmem_blk failed!\n");
assert(0);
return -1;
}
pmb->pblock_ptr = ptr;
pmb->nblock_size = size;
int len = strlen(pfile_name) + 1;
pmb->pfile_name = (char*)::calloc(len, sizeof(char));
if(NULL == pmb->pfile_name)
{
lberror("out of memory calloc pfile_name %s failed!\n", pfile_name);
assert(0);
return -1;
}
memcpy(pmb->pfile_name, pfile_name, len);
pmb->nfile_line = nfile_line;
len = strlen(pfunc_name);
pmb->pfunc_name = (char*)::calloc(len, sizeof(char));
if(NULL == pmb->pfunc_name)
{
lberror("out of memory calloc pfunc_name %s failed!\n", pfunc_name);
assert(0);
return -1;
}
memcpy(pmb->pfunc_name, pfunc_name, len);
return lblist_push(pmcc->plist, pmb);
}
int lbmemcheck_remove_block(lbmemcheck_ctx* pmcc, void* ptr)
{
/*assert(pmcc);
assert(ptr);*/
//lbtrace("pmcc:%p, delete ptr:%p", pmcc, ptr);
if(!pmcc || !ptr || !pmcc->plist)
{
return -1;
}
lbmem_blk* pmb = NULL;
for(lblist_node* pnode = pmcc->plist->head; pnode != NULL; pnode = pnode->pnext)
{
pmb = (lbmem_blk*)pnode->pitem;
//LBLIST_ENUM_BEGIN(lbmem_blk, pmcc->plist, pmb);
if(pmb && ptr == pmb->pblock_ptr)
{
if(pmb->pfile_name)
{
::free(pmb->pfile_name);
pmb->pfile_name = NULL;
}
if(pmb->pfunc_name)
{
::free(pmb->pfunc_name);
pmb->pfunc_name = NULL;
}
::free(pmb);
lblist_remove_node(pmcc->plist, pnode);
return 0;
}
}
//LBLIST_ENUM_END()
lberror("Invalid ptr:%p, not foud from alloc list!\n", ptr);
return -1;
}
#ifdef __cplusplus
template<class T>
inline T* lbmem_new(int count, const char* pfile_name, const int nfile_line, const char* pfunc_name)
{
T* ptr = NULL;
if(count > 1)
{
ptr = new T[count];
}
else
{
ptr = new T();
}
lbmemcheck_add_block(g_pmcc, ptr, sizeof(T) * count, pfile_name, nfile_line, pfunc_name);
return ptr;
}
template<class T>
inline void lbmem_delete(T* ptr, int isarray)
{
if(isarray)
{
delete[] ptr;
}
else
{
delete ptr;
}
lbmemcheck_remove_block(g_pmcc, ptr);
}
#endif
| 28.248588 | 157 | 0.5894 |