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 int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e1c75968b3118e4a48c37dc4d7adce28e6325393 | 441 | hpp | C++ | include/dish2/debug/LogStackFrame.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 29 | 2019-02-04T02:39:52.000Z | 2022-01-28T10:06:26.000Z | include/dish2/debug/LogStackFrame.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 95 | 2020-02-22T19:48:14.000Z | 2021-09-14T19:17:53.000Z | include/dish2/debug/LogStackFrame.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 6 | 2019-11-19T10:13:09.000Z | 2021-03-25T17:35:32.000Z | #pragma once
#ifndef DISH2_DEBUG_LOGSTACKFRAME_HPP_INCLUDE
#define DISH2_DEBUG_LOGSTACKFRAME_HPP_INCLUDE
#include <string>
namespace dish2 {
struct LogStackFrame {
std::string name;
std::string detail;
LogStackFrame() = default;
LogStackFrame( const std::string& name_, const std::string& detail_="" )
: name( name_ ), detail( detail_ )
{}
};
} // namespace dish2
#endif // #ifndef DISH2_DEBUG_LOGSTACKFRAME_HPP_INCLUDE
| 17.64 | 74 | 0.741497 | mmore500 |
e1ca41216b08cfbd94905a4887abe5db86569af4 | 334 | hpp | C++ | src/ast/expr_ast.hpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | null | null | null | src/ast/expr_ast.hpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | 3 | 2021-07-24T23:06:37.000Z | 2021-08-21T03:24:58.000Z | src/ast/expr_ast.hpp | sethitow/stc | 28894bda001f00828613941d1a6da7cc3720dd52 | [
"MIT"
] | null | null | null | #ifndef EXPRAST_H
#define EXPRAST_H
#include <memory>
#include <string>
#include <vector>
#include "llvm/IR/Value.h"
#include "../code_gen_context.hpp"
/// ExprAST - Base class for all expression nodes.
class ExprAST
{
public:
virtual ~ExprAST() = default;
virtual llvm::Value *codegen(CodeGenContext &) = 0;
};
#endif | 15.904762 | 55 | 0.697605 | sethitow |
e1d0ef4bf77d0d0634e08785d22c90eb8cba720c | 1,491 | cc | C++ | tests/libtests/friction/data/FrictionModelData.cc | cehanagan/pylith | cf5c1c34040460a82f79b6eb54df894ed1b1ee93 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/friction/data/FrictionModelData.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/friction/data/FrictionModelData.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University at Buffalo
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2021 University of California, Davis
//
// See LICENSE.md for license information.
//
// ======================================================================
//
#include "FrictionModelData.hh"
// ----------------------------------------------------------------------
// Constructor
pylith::friction::FrictionModelData::FrictionModelData(void) :
numLocs(0),
numProperties(0),
numStateVars(0),
numDBProperties(0),
numDBStateVars(0),
numPropsVertex(0),
numVarsVertex(0),
numPropertyValues(0),
numStateVarValues(0),
dbPropertyValues(0),
dbStateVarValues(0),
dt(0.0),
dbProperties(0),
dbStateVars(0),
properties(0),
stateVars(0),
propertiesNondim(0),
stateVarsNondim(0),
friction(0),
frictionDeriv(0),
slip(0),
slipRate(0),
normalTraction(0),
stateVarsUpdated(0),
setLengthScale(0),
setTimeScale(0),
setPressureScale(0),
setDensityScale(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
// Destructor
pylith::friction::FrictionModelData::~FrictionModelData(void)
{ // destructor
} // destructor
// End of file
| 24.048387 | 73 | 0.56271 | cehanagan |
e1d14506beb052784912d088c0acb10381e183ec | 12,719 | cpp | C++ | src/airplane.cpp | RohanChacko/Jet-FIghter-3D | 3ad72ad71315f9e1f4e301d3e98385822de7c6e5 | [
"MIT"
] | 1 | 2022-03-27T12:31:25.000Z | 2022-03-27T12:31:25.000Z | src/airplane.cpp | RohanChacko/Jet-Fighter-3D | 3ad72ad71315f9e1f4e301d3e98385822de7c6e5 | [
"MIT"
] | null | null | null | src/airplane.cpp | RohanChacko/Jet-Fighter-3D | 3ad72ad71315f9e1f4e301d3e98385822de7c6e5 | [
"MIT"
] | null | null | null | #include "airplane.h"
#include "main.h"
Airplane::Airplane(float xs, float ys, float zs, color_t color) {
this->position = glm::vec3(xs, ys, 0);
this->rotation_x = 0;
this->rotation_z = 0;
this->rotation_y = 0;
this->fuel = 1000;
this->orc[0][0] = 1;
this->orc[0][1] = 0;
this->orc[0][2] = 0;
this->orc[1][0] = 0;
this->orc[1][1] = 1;
this->orc[1][2] = 0;
this->orc[2][0] = 0;
this->orc[2][1] = 0;
this->orc[2][2] = 1;
speed = 0.5;
this->score = 0;
this->health = 100;
static GLfloat g_vertex_buffer_data[100000];
int n = 0;
int ticker = 0;
orc *= speed;
float x1, y1, z, xy; // vertex position
float radius = 2.9; // vertex normal
float s, t; // vertex texCoord
float px, py, pz;
int i, j = 3, k = 3;
float incO = 2 * M_PI / 20;
float incA = M_PI / 20;
float scale_x = 0.3;
GLfloat x[30], y[30];
for(int i = 0; i < 30; ++i)
{
x[i] = scale_x*cos(2*3.14*i/10);
y[i] = scale_x*sin(2*3.14*i/10);
}
for(int i = 0; i < 10; ++i)
{
int j = 0;
g_vertex_buffer_data[18*i] = x[i+j];
g_vertex_buffer_data[18*i+1] = y[i+j];
g_vertex_buffer_data[18*i+2] = -2;
g_vertex_buffer_data[18*i+3] = x[(i+j+1)%30];
g_vertex_buffer_data[18*i+4] = y[(i+j+1)%30];
g_vertex_buffer_data[18*i+5] = -2;
g_vertex_buffer_data[18*i+6] = x[i+j];
g_vertex_buffer_data[18*i+7] = y[i+j];
g_vertex_buffer_data[18*i+8] = 3;
g_vertex_buffer_data[18*i+9] = x[i+j];
g_vertex_buffer_data[18*i+10] = y[i+j];
g_vertex_buffer_data[18*i+11] = 3;
g_vertex_buffer_data[18*i+12] = x[(i+j+1)%30];
g_vertex_buffer_data[18*i+13] = y[(i+j+1)%30];
g_vertex_buffer_data[18*i+14] = 3;
g_vertex_buffer_data[18*i+15] = x[(i+j+1)%30];
g_vertex_buffer_data[18*i+16] = y[(i+j+1)%30];
g_vertex_buffer_data[18*i+17] = -2;
}
for(int j = 0; j < 5; ++j)
{
for(int i = 0; i < 10; ++i)
{
g_vertex_buffer_data[18*i + 180* (j+1)] = x[j] * x[i]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 1] = x[j] * y[i]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 2] = 3 + y[j]/scale_x; //back
g_vertex_buffer_data[18*i + 180* (j+1) + 3] = x[j] *x[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 4] = x[j] *y[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 5] = 3 + y[j]/scale_x; //back
g_vertex_buffer_data[18*i + 180* (j+1) + 6] = x[j+1] *x[i]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 7] = x[j+1] *y[i]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 8] = 3 + y[j+1]/scale_x;//front
g_vertex_buffer_data[18*i + 180* (j+1) + 9] = x[j+1] * x[i]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 10] = x[j+1] * y[i]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 11] = 3 + y[j+1]/scale_x; //front
g_vertex_buffer_data[18*i + 180* (j+1) + 12] = x[j+1] *x[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 13] = x[j+1] *y[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 14] = 3 + y[j+1]/scale_x;//front
g_vertex_buffer_data[18*i + 180* (j+1) + 15] = x[j] *x[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 16] = x[j] *y[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 180* (j+1) + 17] = 3 + y[j]/scale_x;//back
}
}
for(int i = 0; i < 10; ++i)
{
int j = 0;
g_vertex_buffer_data[18*i + 1080] = x[j] * x[i]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 1] = x[j] * y[i]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 2] = -2 - y[j]/scale_x; //back
g_vertex_buffer_data[18*i + 1080 + 3] = x[j] *x[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 4] = x[j] *y[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 5] = -2 - y[j]/scale_x; //back
g_vertex_buffer_data[18*i + 1080 + 6] = x[j+1] *x[i]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 7] = x[j+1] *y[i]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 8] = -2 - y[j+1]/scale_x;//front
g_vertex_buffer_data[18*i + 1080 + 9] = x[j+1] * x[i]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 10] = x[j+1] * y[i]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 11] = -2 - y[j+1]/scale_x; //front
g_vertex_buffer_data[18*i + 1080 + 12] = x[j+1] *x[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 13] = x[j+1] *y[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 14] = -2 - y[j+1]/scale_x;//front
g_vertex_buffer_data[18*i + 1080 + 15] = x[j] *x[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 16] = x[j] *y[(i+1)%30]/scale_x;
g_vertex_buffer_data[18*i + 1080 + 17] = -2 - y[j]/scale_x;//back
}
//tail 1
g_vertex_buffer_data[1260] = 0;
g_vertex_buffer_data[1261] = scale_x;
g_vertex_buffer_data[1262] = -1;
g_vertex_buffer_data[1263] = 0;
g_vertex_buffer_data[1264] = 1.3;
g_vertex_buffer_data[1265] = -2.2;
g_vertex_buffer_data[1266] = 0;
g_vertex_buffer_data[1267] = scale_x;
g_vertex_buffer_data[1268] = -2;
//tail 2
g_vertex_buffer_data[1269] = 0;
g_vertex_buffer_data[1270] = 1.3;
g_vertex_buffer_data[1271] = -2.2;
g_vertex_buffer_data[1272] = 0;
g_vertex_buffer_data[1273] = scale_x;
g_vertex_buffer_data[1274] = -2;
g_vertex_buffer_data[1275] = 0;
g_vertex_buffer_data[1276] = 1.3;
g_vertex_buffer_data[1277] = -2.7;
//fins
g_vertex_buffer_data[1278] = 0;
g_vertex_buffer_data[1279] = -0.15;
g_vertex_buffer_data[1280] = -1;
g_vertex_buffer_data[1281] = 1.5f;
g_vertex_buffer_data[1282] = -0.15f;
g_vertex_buffer_data[1283] = -2;
g_vertex_buffer_data[1284] = -1.5;
g_vertex_buffer_data[1285] = -0.15;
g_vertex_buffer_data[1286] = -2;
g_vertex_buffer_data[1287] = 1.5f;
g_vertex_buffer_data[1288] = -0.15;
g_vertex_buffer_data[1289] = -2;
g_vertex_buffer_data[1290] = 1.5f;
g_vertex_buffer_data[1291] = -0.15;
g_vertex_buffer_data[1292] = -2.3;
g_vertex_buffer_data[1293] = -0.3;
g_vertex_buffer_data[1294] = -0.15;
g_vertex_buffer_data[1295] = -2;
g_vertex_buffer_data[1296] = -1.5f;
g_vertex_buffer_data[1297] = -0.15;
g_vertex_buffer_data[1298] = -2;
g_vertex_buffer_data[1299] = -1.5f;
g_vertex_buffer_data[1300] = -0.15;
g_vertex_buffer_data[1301] = -2.3;
g_vertex_buffer_data[1302] = 0.3;
g_vertex_buffer_data[1303] = -0.15;
g_vertex_buffer_data[1304] = -2;
g_vertex_buffer_data[1305] = 0;
g_vertex_buffer_data[1306] = -0.15;
g_vertex_buffer_data[1307] = 1.5;
g_vertex_buffer_data[1308] = 3.5;
g_vertex_buffer_data[1309] = -0.15f;
g_vertex_buffer_data[1310] = -0.5;
g_vertex_buffer_data[1311] = 0;
g_vertex_buffer_data[1312] = -0.15;
g_vertex_buffer_data[1313] = 0.5;
g_vertex_buffer_data[1314] = 0;
g_vertex_buffer_data[1315] = -0.15;
g_vertex_buffer_data[1316] = 1.5;
g_vertex_buffer_data[1317] = -3.5;
g_vertex_buffer_data[1318] = -0.15f;
g_vertex_buffer_data[1319] = -0.5;
g_vertex_buffer_data[1320] = 0;
g_vertex_buffer_data[1321] = -0.15;
g_vertex_buffer_data[1322] = 0.5;
g_vertex_buffer_data[1323] = 0;
g_vertex_buffer_data[1324] = -0.15;
g_vertex_buffer_data[1325] = 1.5;
g_vertex_buffer_data[1326] = 1.5f;
g_vertex_buffer_data[1327] = -0.15f;
g_vertex_buffer_data[1328] = 0.1;
g_vertex_buffer_data[1329] = -1.5;
g_vertex_buffer_data[1330] = -0.15;
g_vertex_buffer_data[1331] = 0.1;
for(int i = 2;i<1332;i+=3)
{
g_vertex_buffer_data[i]*=-1;
}
this->object = create3DObject(GL_TRIANGLES, 420 + 12 + 12, g_vertex_buffer_data, COLOR_GOLD, GL_FILL);
}
void Airplane::draw(glm::mat4 VP, glm::vec3& cam_position, glm::vec3& target_position) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 temp = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
// glm::mat4 pitch = glm::rotate((float) (this->rotation_x * M_PI / 180.0f), glm::vec3(1,0,0));
// glm::mat4 yaw = glm::rotate((float) (this->rotation_z * M_PI / 180.0f), glm::vec3(0,0,1));
// glm::mat4 roll = glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0));
glm::mat4 pitch = glm::rotate((float) (this->rotation_x * M_PI / 180.0f), glm::vec3(1,0,0));
glm::mat4 yaw = glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0));
glm::mat4 roll = glm::rotate((float) (this->rotation_z * M_PI / 180.0f), glm::vec3(0,0,1));
// No need as coords centered at 0, 0, 0 of cube arouund which we want to rotate
// rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
// Matrices.model *= initial;
Matrices.model *= (translate * yaw*pitch*roll);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object);
}
void Airplane::set_position(float x, float y, float z) {
this->position = glm::vec3(x, y, z);
}
int Airplane::barrel_roll()
{
this->rotation_z += (5*1.0);
this->position.z -= speed*cosf(this->rotation_y * M_PI/180.0);
if(this->rotation_z >= 360)
{
this->rotation_z -= 360;
return 1;
}
return 0;
}
void Airplane::tick(int move, glm::vec3& cam_position, glm::vec3& target_position) {
// this->rotation += speed;
ticker++;
// std::cout<<ticker<<"\n";
// this->position.y -= speed;
if(move == 1){
if(this->rotation_x < 30)
this->rotation_x += (1*1.0);
this->position.y+=speed*sinf(this->rotation_x * M_PI/180.0);
// cam_position.y+=speed*sinf(this->rotation_x * M_PI/180.0);
// target_position.y+=speed*sinf(this->rotation_x * M_PI/180.0);
}
else
{
if(this->rotation_x >- 30)
this->rotation_x -= (1* 1.0);
if(this->position.y >=1){
this->position.y+=speed*sinf(this->rotation_x * M_PI/180.0);
if(this->position.y < 10)
this->position.y = 10;
if(this->position.x > 500 && this->position.y < 24)
this->position.y = 24;
// cam_position.y+=speed*sinf(this->rotation_x * M_PI/180.0);
// target_position.y+=speed*sinf(this->rotation_x * M_PI/180.0);
}
}
if(move == 2)
{
// std::cout<<"first "<<this->rotation_z<<"\n";
if(this->rotation_z < 30)
{
this->rotation_z += (1*1.0);
}
}
else if(move == -2)
{
// std::cout<<"second "<<this->rotation_z<<"\n";
if(this->rotation_z >- 30)
{
this->rotation_z -= (1*1.0);
}
// this->position.x -= speed*sinf(this->rotation_z * M_PI/180.0);
}
if(move == 3)
{
this->rotation_y += (-1*1.0);
orc *= glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0));
}
else if(move == -3)
{
this->rotation_y -= (-1*1.0);
orc *= glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0));
}
// int i,j;
// for(i = 0;i<3;++i)
// {
// for(j = 0;j<3;++j)
// std::cout<<orc[i][j]<<" ";
// std::cout<<orc[i][j]<<"\n\n\n";
// }
// this->position.x += orc[0][0];
//this->position.y += orc[1][1];
// this->position.z += orc[2][2];
this->position.x -= speed*sinf(this->rotation_y * M_PI/180.0);
this->position.x -= speed*sinf(this->rotation_z * M_PI/180.0);
this->position.z -= speed*cosf(this->rotation_y * M_PI/180.0);
// std::cout<<move<<" "<<this->position.y<<"\n";
// cam_position.x -= speed*sinf(this->rotation_y * M_PI/180.0);
// cam_position.x -= speed*sinf(this->rotation_z * M_PI/180.0);
// cam_position.z -= speed*cosf(this->rotation_y * M_PI/180.0);
//
// target_position.x -= speed*sinf(this->rotation_y * M_PI/180.0);
// target_position.x -= speed*sinf(this->rotation_z * M_PI/180.0);
// target_position.z -= speed*cosf(this->rotation_y * M_PI/180.0);
}
| 35.627451 | 108 | 0.553345 | RohanChacko |
e1d1d4ac8fd09177ce45c72413a2342d012587d4 | 3,524 | hpp | C++ | src/concepts.hpp | Aertalon/optimizer | 32afad1dc5c1640cd2869a7575f43584ad6390bd | [
"MIT"
] | 1 | 2022-01-27T16:57:10.000Z | 2022-01-27T16:57:10.000Z | src/concepts.hpp | Aertalon/optimizer | 32afad1dc5c1640cd2869a7575f43584ad6390bd | [
"MIT"
] | 27 | 2022-01-27T17:46:56.000Z | 2022-02-15T22:37:43.000Z | src/concepts.hpp | Aertalon/optimizer | 32afad1dc5c1640cd2869a7575f43584ad6390bd | [
"MIT"
] | 1 | 2022-02-05T09:36:56.000Z | 2022-02-05T09:36:56.000Z | #pragma once
#include <concepts>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace opt {
// clang-format off
template <class T, class U = T, class R = T>
concept Addable =
requires (T a, U b) { { a + b } -> std::same_as<R>; };
template <class T, class U = T, class R = T>
concept Subtractible =
requires (T a, U b) { { a - b } -> std::same_as<R>; };
template <class T, class U = T, class R = T>
concept Multipliable =
requires (T a, U b) { { a * b } -> std::same_as<R>; };
template <class T, class U = T, class R = T>
concept Divisible =
requires (T a, U b) { { a / b } -> std::same_as<R>; };
template <class T>
concept Negatable =
requires (T a) { { -a } -> std::same_as<T>; };
template <class T, class U = T>
concept CompoundAddable =
requires (T& a, U b) { { a += b } -> std::same_as<T&>; };
template <class T, class U = T>
concept CompoundSubtractible =
requires (T& a, U b) { { a -= b } -> std::same_as<T&>; };
template <class T, class U = T>
concept CompoundMultipliable =
requires (T& a, U b) { { a *= b } -> std::same_as<T&>; };
template <class T, class U = T>
concept CompoundDivisible =
requires (T& a, U b) { { a /= b } -> std::same_as<T&>; };
template <class T>
concept Arithmetic =
std::regular<T> &&
Addable<T> &&
Subtractible<T> &&
Multipliable<T> &&
Divisible<T> &&
Negatable<T> &&
CompoundAddable<T> &&
CompoundSubtractible<T> &&
CompoundMultipliable<T> &&
CompoundDivisible<T> &&
requires(T a) {
T{0}; // additive identity
T{1}; // multiplicative identity
};
namespace detail {
template <class T>
concept is_lvalue_ref = std::is_lvalue_reference_v<T>;
template <class T>
concept is_const_lvalue_ref =
std::is_lvalue_reference_v<T> &&
std::is_const_v<std::remove_reference_t<T>>;
} // namespace detail
template <class T, class U = std::size_t>
concept Indexable =
requires(T& a, const T& b, U n) {
{ a[n] } -> detail::is_lvalue_ref;
{ b[n] } -> detail::is_const_lvalue_ref;
};
template <class T>
concept TupleSizable =
requires {
{ std::tuple_size<T>::value } -> std::same_as<const std::size_t&>;
};
template <Indexable T>
using scalar_t = std::remove_cvref_t<decltype(std::declval<T&>()[0])>;
template <class T, class U = scalar_t<T>>
concept Vector =
Arithmetic<U> &&
std::regular<T> &&
TupleSizable<T> &&
Indexable<T> &&
Addable<T> &&
Subtractible<T> &&
Negatable<T> &&
Multipliable<U, const T&, T>;
template <class T>
concept Diffable =
requires (T a, T b) { a - b; };
template <Diffable T>
using distance_t =
std::remove_cvref_t<decltype(std::declval<const T&>() - std::declval<const T&>())>;
template <class T, class U = distance_t<T>>
concept Point =
Vector<U> &&
std::regular<T> &&
TupleSizable<T> &&
(std::tuple_size<T>::value == std::tuple_size<U>::value) &&
Indexable<T> &&
Addable<const T&, const U&, T> &&
Addable<const U&, const T&, T> &&
Subtractible<const T&, const T&, U> &&
Subtractible<const T&, const U&, T>;
template <Arithmetic, std::size_t>
struct point;
namespace impl {
template <Arithmetic>
struct dual;
}
// TODO replace total ordering requirement with partial ordering
template <class T, class P>
concept Cost =
Point<P> &&
std::regular_invocable<const T&, const P&> &&
std::regular_invocable<const T&,
const opt::point<impl::dual<scalar_t<P>>, std::tuple_size<P>::value>&> &&
std::totally_ordered<std::invoke_result_t<const T&, const P&>>;
// clang-format on
} // namespace opt
| 24.643357 | 98 | 0.630533 | Aertalon |
e1d2c21af6c478b9b48be555acbc7f568826d3c3 | 3,316 | cpp | C++ | PlayerInfo/Dolby/DolbyOutput.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 7 | 2020-03-24T15:26:23.000Z | 2021-12-21T21:42:38.000Z | PlayerInfo/Dolby/DolbyOutput.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 224 | 2020-03-05T17:40:39.000Z | 2022-03-23T13:18:56.000Z | PlayerInfo/Dolby/DolbyOutput.cpp | Michal-Bugno/ThunderNanoServices | 9b328519a363c602823f9d1f101d47f0a2482a23 | [
"BSD-2-Clause"
] | 52 | 2020-03-05T17:24:05.000Z | 2022-03-31T02:13:40.000Z | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 Metrological
*
* 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 "../../Module.h"
#include "Dolby.h"
namespace WPEFramework
{
namespace Plugin
{
class DolbyOutputImplementation : public Exchange::Dolby::IOutput
{
public:
uint32_t Register(Exchange::Dolby::IOutput::INotification* notification) override
{
_adminLock.Lock();
// Make sure a sink is not registered multiple times.
ASSERT(std::find(_observers.begin(), _observers.end(), notification) == _observers.end());
_observers.push_back(notification);
notification->AddRef();
_adminLock.Unlock();
return (Core::ERROR_NONE);
}
uint32_t Unregister(Exchange::Dolby::IOutput::INotification* notification) override
{
_adminLock.Lock();
std::list<Exchange::Dolby::IOutput::INotification*>::iterator index(std::find(_observers.begin(), _observers.end(), notification));
// Make sure you do not unregister something you did not register !!!
ASSERT(index != _observers.end());
if (index != _observers.end()) {
(*index)->Release();
_observers.erase(index);
}
_adminLock.Unlock();
return (Core::ERROR_NONE);
}
uint32_t AtmosMetadata(bool& supported) const override
{
return (Core::ERROR_UNAVAILABLE);
}
uint32_t SoundMode(Exchange::Dolby::IOutput::SoundModes& mode) const override
{
return (Core::ERROR_UNAVAILABLE);
}
uint32_t EnableAtmosOutput(const bool& enable) override
{
return (Core::ERROR_UNAVAILABLE);
}
uint32_t Mode(const Exchange::Dolby::IOutput::Type& mode) override
{
return set_audio_output_type(mode);
}
uint32_t Mode(Exchange::Dolby::IOutput::Type& mode) const override
{
return get_audio_output_type(&mode);
}
BEGIN_INTERFACE_MAP(DolbyOutputImplementation)
INTERFACE_ENTRY(Exchange::Dolby::IOutput)
END_INTERFACE_MAP
private:
std::list<Exchange::Dolby::IOutput::INotification*> _observers;
mutable Core::CriticalSection _adminLock;
};
SERVICE_REGISTRATION(DolbyOutputImplementation, 1, 0);
} // namespace Plugin
} // namespace WPEFramework
| 32.509804 | 147 | 0.59228 | Michal-Bugno |
e1d5168d3aa19f1f78a5dd2ca476f5e488922a01 | 2,154 | cpp | C++ | OpenRPG/Components/SoundComponent.cpp | OpenRPGs/OpenRPG | 0baed49c1d7e6f871457c441aa0209ec4280265a | [
"MIT"
] | 28 | 2019-08-09T04:07:04.000Z | 2022-01-16T05:56:22.000Z | OpenRPG/Components/SoundComponent.cpp | OpenRPGs/OpenRPG | 0baed49c1d7e6f871457c441aa0209ec4280265a | [
"MIT"
] | 29 | 2019-08-09T04:02:59.000Z | 2019-09-16T05:01:33.000Z | OpenRPG/Components/SoundComponent.cpp | OpenRPGs/OpenRPG | 0baed49c1d7e6f871457c441aa0209ec4280265a | [
"MIT"
] | 18 | 2019-08-09T02:42:09.000Z | 2022-01-16T06:03:32.000Z | #include "stdafx.h"
#include "SoundComponent.h"
bool SoundComponent::isSame(sf::SoundBuffer& buffer) {
return &buffer == this->sound->getBuffer();
}
bool SoundComponent::Loaded() {
return this->sound != NULL;
}
#pragma region Play, Pause, Stop
SoundComponent* SoundComponent::play() {
if (this->sound == NULL)
return this;
this->sound->play();
return this;
}
SoundComponent* SoundComponent::pause() {
if (this->sound == NULL)
return this;
this->sound->pause();
return this;
}
SoundComponent* SoundComponent::stop() {
if (this->sound == NULL)
return this;
this->sound->stop();
return this;
}
#pragma endregion
bool SoundComponent::isPlaying() {
if (this->sound == NULL)
return false;
return this->sound->getStatus() == sf::Sound::Status::Playing;
}
#pragma region Volume
SoundComponent* SoundComponent::setVolume(float volume) {
if (this->sound == NULL)
return this;
this->sound->setVolume(volume);
return this;
}
float SoundComponent::getVolume() {
if (this->sound == NULL)
return -1;
return this->sound->getVolume();
}
#pragma endregion
#pragma region Offset
SoundComponent* SoundComponent::setOffset(int msec) {
if (this->sound == NULL)
return this;
this->sound->setPlayingOffset(sf::milliseconds(msec));
return this;
}
int SoundComponent::getOffset() {
if (this->sound == NULL)
return -1;
return this->sound->getPlayingOffset().asMilliseconds();
}
#pragma endregion
#pragma region Loop
SoundComponent* SoundComponent::setLoop(bool loop) {
if (this->sound == NULL)
return this;
this->sound->setLoop(loop);
return this;
}
bool SoundComponent::getLoop() {
if (this->sound == NULL)
return false;
return this->sound->getLoop();
}
#pragma endregion
SoundComponent::SoundComponent(sf::SoundBuffer& buffer) {
this->sound = new sf::Sound(buffer);
}
SoundComponent::~SoundComponent() {
if (this->sound != NULL) {
delete this->sound;
this->sound = NULL;
}
}
SoundComponent* SoundComponent::reset(sf::SoundBuffer& buffer) {
if (this->sound == NULL)
return this;
this->sound->stop();
this->sound->setBuffer(buffer);
this->sound->setPlayingOffset(sf::milliseconds(0));
return this;
}
| 19.944444 | 64 | 0.697307 | OpenRPGs |
e1d85a375708100cbe46b34ba007e78a9792128a | 877 | hpp | C++ | HiLo/Game.hpp | JankoDedic/Hi-Lo | b9d73b7a50deb76b6282c5541d496335d749a0f5 | [
"MIT"
] | 1 | 2019-09-18T01:32:23.000Z | 2019-09-18T01:32:23.000Z | HiLo/Game.hpp | JankoDedic/Hi-Lo | b9d73b7a50deb76b6282c5541d496335d749a0f5 | [
"MIT"
] | null | null | null | HiLo/Game.hpp | JankoDedic/Hi-Lo | b9d73b7a50deb76b6282c5541d496335d749a0f5 | [
"MIT"
] | null | null | null | #pragma once
#include "CreditsView.hpp"
#include "GameScene.hpp"
#include "MenuSceneView.hpp"
namespace HiLo {
class Game
: public Observer<MenuSceneView>
, public Observer<GameScene>
, public Observer<CreditsView> {
public:
auto receiveEvent(MenuSceneView*, MenuSceneView::Event const&) noexcept
-> void override;
auto receiveEvent(GameScene*, GameScene::Event const&) noexcept -> void
override;
auto receiveEvent(CreditsView*, CreditsView::Event const&) noexcept
-> void override;
Game() noexcept;
auto handleEvent(SDL_Event const&) noexcept -> void;
auto draw() const noexcept -> void;
private:
enum class Scene {
Menu, Game, Credits
};
Scene mActiveScene{Scene::Menu};
MenuSceneView mMenuSceneView;
GameScene mGameScene;
CreditsView mCreditsView;
};
} // namespace HiLo
| 21.390244 | 75 | 0.686431 | JankoDedic |
e1d96168d8b9d6714174e84c3b866df100f59f73 | 1,044 | cpp | C++ | src/mettle/run_test_files.cpp | jimporter/mettle | c65aa75b04a08b550b3572f4c080c68e26ad86fa | [
"BSD-3-Clause"
] | 82 | 2015-01-05T10:06:44.000Z | 2022-03-07T01:41:28.000Z | src/mettle/run_test_files.cpp | JohnGalbraith/mettle | 38b70fe1dc0f30e98b768a37108196328182b5f4 | [
"BSD-3-Clause"
] | 44 | 2015-01-08T08:40:54.000Z | 2021-10-29T23:28:56.000Z | src/mettle/run_test_files.cpp | jimporter/mettle | c65aa75b04a08b550b3572f4c080c68e26ad86fa | [
"BSD-3-Clause"
] | 13 | 2015-06-23T07:41:54.000Z | 2020-02-14T15:35:07.000Z | #include "run_test_files.hpp"
#include "log_pipe.hpp"
#ifndef _WIN32
# include "posix/run_test_file.hpp"
namespace platform = mettle::posix;
#else
# include "windows/run_test_file.hpp"
namespace platform = mettle::windows;
#endif
namespace mettle {
void run_test_files(
const std::vector<test_command> &commands, log::file_logger &logger,
const std::vector<std::string> &args
) {
using namespace platform;
logger.started_run();
detail::file_uid_maker uid;
for(const auto &command : commands) {
test_file file = {command, uid.make_file_uid()};
logger.started_file(file);
std::vector<std::string> final_args = command.args();
final_args.insert(final_args.end(), args.begin(), args.end());
auto result = run_test_file(std::move(final_args),
log::pipe(logger, file.id));
if(result.passed)
logger.ended_file(file);
else
logger.failed_file(file, result.message);
}
logger.ended_run();
}
} // namespace mettle
| 24.857143 | 72 | 0.65613 | jimporter |
e1d9f6248ede03dddee6e14ead9b6d6f3fa8e193 | 3,989 | cc | C++ | tests/unit/termination/test_termination_action_callable.extended.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 26 | 2019-11-26T08:36:15.000Z | 2022-02-15T17:13:21.000Z | tests/unit/termination/test_termination_action_callable.extended.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | tests/unit/termination/test_termination_action_callable.extended.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 12 | 2019-09-08T00:03:05.000Z | 2022-02-23T21:28:35.000Z | /*
//@HEADER
// *****************************************************************************
//
// test_termination_action_callable.extended.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright 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 OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#include "test_termination_action_common.h"
#if !defined INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H
#define INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H
namespace vt { namespace tests { namespace unit { namespace channel {
// set channel counting ranks
vt::NodeType root = vt::uninitialized_destination;
vt::NodeType node = vt::uninitialized_destination;
vt::NodeType all = vt::uninitialized_destination;
std::unordered_map<vt::EpochType,Data> data;
bool ok = false;
}}}} /* end namespace vt::tests::unit::channel */
namespace vt { namespace tests { namespace unit {
static bool finished[2] = {false, false};
static int num = 0;
// no need for a parameterized fixture
struct TestTermCallable : action::SimpleFixture {
void verify(int cur) {
int const nxt = (cur + 1) % 2;
EXPECT_FALSE(finished[cur]);
EXPECT_TRUE(not finished[nxt] or num == 1);
finished[cur] = true;
num++;
}
};
TEST_F(TestTermCallable, test_add_action_unique) /*NOLINT*/{
finished[0] = finished[1] = false;
num = 0;
vt::theCollective()->barrier();
// create an epoch and a related termination flag
auto epoch = ::vt::theTerm()->makeEpochCollective();
// assign an arbitrary action to be triggered at
// the end of the epoch and toggle the previous flag.
::vt::theTerm()->addActionEpoch(epoch, [=]{
vt_debug_print(
normal, term,
"current epoch:{:x} finished\n",
epoch
);
verify(0);
});
// assign a callable to be triggered after
// the action submitted for the given epoch.
::vt::theTerm()->addActionUnique(epoch, [=]{
vt_debug_print(
normal, term,
"trigger callable for epoch:{:x}\n",
epoch
);
verify(1);
});
if (channel::node == channel::root) {
action::compute(epoch);
}
::vt::theTerm()->finishedEpoch(epoch);
}
}}} // namespace vt::tests::unit::action
#endif /*INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H*/
| 33.521008 | 81 | 0.686388 | rbuch |
e1da9319c9add4892f817be61434d71d464f15b8 | 745 | cpp | C++ | Shape Information/DNAshapeR-2nd-order/src/map.cpp | felixekn/MuANN | 06bf80e2901e46faf77632b6240bde18199a21ab | [
"MIT"
] | 1 | 2017-12-04T06:12:23.000Z | 2017-12-04T06:12:23.000Z | Shape Information/DNAshapeR-2nd-order/src/map.cpp | felixekn/MuANN | 06bf80e2901e46faf77632b6240bde18199a21ab | [
"MIT"
] | 3 | 2017-05-03T17:27:35.000Z | 2018-05-17T05:10:53.000Z | Shape Information/DNAshapeR-2nd-order/src/map.cpp | felixekn/MuANN | 06bf80e2901e46faf77632b6240bde18199a21ab | [
"MIT"
] | null | null | null | #include "map.h"
#include "utilities.h"
void build_unique_pentamers(DNA_to_properties& pentamers){
std::string alphabet[4]={"A","T","G","C"};
pentamers.clear();
std::string t="";
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
for (int k=0;k<4;k++)
for (int l=0;l<4;l++)
for (int m=0;m<4;m++){
t=alphabet[i]+alphabet[j]+alphabet[k]+alphabet[l]+alphabet[m];
if ((!found_str_in_map(t,pentamers)) && (!found_str_in_map(opposite_strand(t),pentamers))){
properties p=properties();
pentamers[t]=p;
}
}
}
bool found_str_in_map(std::string str, DNA_to_properties &onemap){
DNA_to_properties::const_iterator end=onemap.end();
if (onemap.find(str)!=end)
return true;
else
return false;
}
| 26.607143 | 96 | 0.62953 | felixekn |
e1dad46882ae8f68205a619dbdea20c4bdf66f40 | 5,152 | cc | C++ | cc/aead/kms_envelope_aead.cc | BearerPipelineTest/tink | cb814f1e1b69caf6211046bee083a730625a3cf9 | [
"Apache-2.0"
] | null | null | null | cc/aead/kms_envelope_aead.cc | BearerPipelineTest/tink | cb814f1e1b69caf6211046bee083a730625a3cf9 | [
"Apache-2.0"
] | null | null | null | cc/aead/kms_envelope_aead.cc | BearerPipelineTest/tink | cb814f1e1b69caf6211046bee083a730625a3cf9 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
//
// 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 "tink/aead/kms_envelope_aead.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/base/internal/endian.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tink/aead.h"
#include "tink/registry.h"
#include "tink/util/errors.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "proto/tink.pb.h"
namespace crypto {
namespace tink {
namespace {
const int kEncryptedDekPrefixSize = 4;
const char* kEmptyAssociatedData = "";
// Constructs a ciphertext of KMS envelope encryption.
// The format of the ciphertext is the following:
// 4-byte-prefix | encrypted_dek | encrypted_plaintext
// where 4-byte-prefix is the length of encrypted_dek in big-endian format
// (for compatibility with Java)
std::string GetEnvelopeCiphertext(absl::string_view encrypted_dek,
absl::string_view encrypted_plaintext) {
uint8_t enc_dek_size[kEncryptedDekPrefixSize];
absl::big_endian::Store32(enc_dek_size, encrypted_dek.size());
return absl::StrCat(std::string(reinterpret_cast<const char*>(enc_dek_size),
kEncryptedDekPrefixSize),
encrypted_dek, encrypted_plaintext);
}
} // namespace
// static
util::StatusOr<std::unique_ptr<Aead>> KmsEnvelopeAead::New(
const google::crypto::tink::KeyTemplate& dek_template,
std::unique_ptr<Aead> remote_aead) {
if (remote_aead == nullptr) {
return util::Status(absl::StatusCode::kInvalidArgument,
"remote_aead must be non-null");
}
auto km_result = Registry::get_key_manager<Aead>(dek_template.type_url());
if (!km_result.ok()) return km_result.status();
std::unique_ptr<Aead> envelope_aead(
new KmsEnvelopeAead(dek_template, std::move(remote_aead)));
return std::move(envelope_aead);
}
util::StatusOr<std::string> KmsEnvelopeAead::Encrypt(
absl::string_view plaintext, absl::string_view associated_data) const {
// Generate DEK.
auto dek_result = Registry::NewKeyData(dek_template_);
if (!dek_result.ok()) return dek_result.status();
auto dek = std::move(dek_result.value());
// Wrap DEK key values with remote.
auto dek_encrypt_result =
remote_aead_->Encrypt(dek->value(), kEmptyAssociatedData);
if (!dek_encrypt_result.ok()) return dek_encrypt_result.status();
// Encrypt plaintext using DEK.
auto aead_result = Registry::GetPrimitive<Aead>(*dek);
if (!aead_result.ok()) return aead_result.status();
auto aead = std::move(aead_result.value());
auto encrypt_result = aead->Encrypt(plaintext, associated_data);
if (!encrypt_result.ok()) return encrypt_result.status();
// Build and return ciphertext.
return GetEnvelopeCiphertext(dek_encrypt_result.value(),
encrypt_result.value());
}
util::StatusOr<std::string> KmsEnvelopeAead::Decrypt(
absl::string_view ciphertext, absl::string_view associated_data) const {
// Parse the ciphertext.
if (ciphertext.size() < kEncryptedDekPrefixSize) {
return util::Status(absl::StatusCode::kInvalidArgument,
"ciphertext too short");
}
auto enc_dek_size = absl::big_endian::Load32(
reinterpret_cast<const uint8_t*>(ciphertext.data()));
if (enc_dek_size > ciphertext.size() - kEncryptedDekPrefixSize ||
enc_dek_size < 0) {
return util::Status(absl::StatusCode::kInvalidArgument,
"invalid ciphertext");
}
// Decrypt the DEK with remote.
auto dek_decrypt_result = remote_aead_->Decrypt(
ciphertext.substr(kEncryptedDekPrefixSize, enc_dek_size),
kEmptyAssociatedData);
if (!dek_decrypt_result.ok()) {
return util::Status(absl::StatusCode::kInvalidArgument,
absl::StrCat("invalid ciphertext: ",
dek_decrypt_result.status().message()));
}
// Create AEAD from DEK.
google::crypto::tink::KeyData dek;
dek.set_type_url(dek_template_.type_url());
dek.set_value(dek_decrypt_result.value());
dek.set_key_material_type(google::crypto::tink::KeyData::SYMMETRIC);
// Encrypt plaintext using DEK.
auto aead_result = Registry::GetPrimitive<Aead>(dek);
if (!aead_result.ok()) return aead_result.status();
auto aead = std::move(aead_result.value());
return aead->Decrypt(
ciphertext.substr(kEncryptedDekPrefixSize + enc_dek_size),
associated_data);
}
} // namespace tink
} // namespace crypto
| 37.333333 | 79 | 0.693711 | BearerPipelineTest |
e1db765306c8fd4c768e4e067f6a786bb72a6504 | 6,932 | cxx | C++ | Testing/Code/Libraries/Old/TestStringMsg_General.cxx | NifTK/NiftyLink | b8b794afb682ffcdcf5181661fcf167989369a5d | [
"BSD-3-Clause"
] | 5 | 2015-05-10T14:09:34.000Z | 2021-02-23T03:35:51.000Z | Testing/Code/Libraries/Old/TestStringMsg_General.cxx | NifTK/NiftyLink | b8b794afb682ffcdcf5181661fcf167989369a5d | [
"BSD-3-Clause"
] | null | null | null | Testing/Code/Libraries/Old/TestStringMsg_General.cxx | NifTK/NiftyLink | b8b794afb682ffcdcf5181661fcf167989369a5d | [
"BSD-3-Clause"
] | 1 | 2021-02-23T03:35:52.000Z | 2021-02-23T03:35:52.000Z | /*=============================================================================
NiftyLink: A software library to facilitate communication over OpenIGTLink.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "stdlib.h"
#include <QDebug>
#include <QSettings>
#include <QDateTime>
#include "TestStringMsg_General.h"
#include <cmath>
TestStringMsg_General::TestStringMsg_General(void)
{
m_TestCounter = 0;
m_SuccessCounter = 0;
}
TestStringMsg_General::~TestStringMsg_General(void)
{
std::cerr << "Test class destructor";
}
void TestStringMsg_General::SetupTest()
{
//Nothing to do right now
}
void TestStringMsg_General::PerformTest()
{
//Create image message and initialize with test data
std::cout << ++m_TestCounter << ". Creating string message..";
NiftyLinkStringMessage::Pointer stringMsg;
stringMsg.reset();
stringMsg = (NiftyLinkStringMessage::Pointer(new NiftyLinkStringMessage()));
if (stringMsg.operator != (NULL))
{
std::cout << " OK\n";
m_SuccessCounter++;
}
else
{
std::cout << " FAILED\n";
}
//***********************************************
std::cout << ++m_TestCounter << ". Initializing with test data..";
stringMsg->InitializeWithTestData();
if (stringMsg->GetString() == QString("This is a test string"))
{
std::cout << " OK\n";
m_SuccessCounter++;
}
else
{
std::cout << " FAILED\n";
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting string..";
stringMsg->SetString("This is a random string which meant to crash the NiftyLink lib");
if (stringMsg->GetString() != QString("This is a random string which meant to crash the NiftyLink lib"))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting encoding..";
stringMsg->SetEncoding(3);
if (stringMsg->GetEncoding() != 3)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting timestamp and sender ID..";
stringMsg->Update(GetLocalHostAddress());
if (stringMsg->GetHostName().isEmpty() || stringMsg->GetTimeCreated().IsNull())
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting message type tag..";
stringMsg->ChangeMessageType("Something");
if (stringMsg->GetMessageType() != QString("Something"))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting port number..";
stringMsg->SetPort(100);
if (stringMsg->GetPort() != 100)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Setting receive timestamp..";
igtl::TimeStamp::Pointer tsr = igtl::TimeStamp::New();
igtl::TimeStamp::Pointer tss = igtl::TimeStamp::New();
tsr->Update();
stringMsg->SetTimeReceived(tsr);
tss = stringMsg->GetTimeReceived();
if (tsr->GetTimeInNanoSeconds() != tss->GetTimeInNanoSeconds())
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Checking create timestamp and id..";
igtl::TimeStamp::Pointer tsc = igtl::TimeStamp::New();
igtlUint64 id = 0;
tsc = stringMsg->GetTimeCreated();
id = stringMsg->GetId();
if (tsr->GetTimeInNanoSeconds() < tsc->GetTimeInNanoSeconds() || id <= 0)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Checking Update function and hostname..";
stringMsg->Update("Something");
QString hname = stringMsg->GetHostName();
stringMsg->ChangeHostName("Anything");
QString hname2 = stringMsg->GetHostName();
if (hname2 != QString("Anything") || hname != QString("Something"))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Checking message pointer get / set..";
igtl::MessageBase::Pointer mp = igtl::MessageBase::New();
igtl::MessageBase::Pointer mp3;
stringMsg->SetMessagePointer(mp);
stringMsg->GetMessagePointer(mp3);
if (mp != mp3)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Set resolution settings..";
NiftyLinkMessage::Pointer sttString;
sttString.reset();
NiftyLinkStringMessage::Create_STT(sttString);
sttString->SetResolution(100);
igtlUint64 res = 0;
sttString->GetResolution(res);
if (res != 100)
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
std::cout << ++m_TestCounter << ". Deleting messages..";
stringMsg.reset();
stringMsg.operator = (NULL);
sttString.reset();
sttString.operator = (NULL);
if (sttString.operator != (NULL) || stringMsg.operator != (NULL))
{
std::cout << " FAILED\n";
}
else
{
std::cout << " OK\n";
m_SuccessCounter++;
}
//***********************************************
QuitTest();
}
void TestStringMsg_General::QuitTest()
{
emit Done();
if (m_TestCounter > m_SuccessCounter)
{
std::cout << "\n\n\n";
std::cout << "****************************************************\n";
std::cout << "**************** TESTING FINISHED: *****************\n";
std::cout << "***************** " << (m_TestCounter - m_SuccessCounter) << " TEST(S) FAILED *****************\n";
std::cout << "****************************************************\n";
exit(-1);
}
else
{
std::cout << "\n\n\n";
std::cout << "****************************************************\n";
std::cout << "**************** TESTING FINISHED: *****************\n";
std::cout << "********* ALL TESTS COMPLETED SUCCESSFULLY *********\n";
std::cout << "****************************************************\n";
exit(0);
}
}
| 25.207273 | 117 | 0.515436 | NifTK |
e1dbf5f086f8b244c45ebe419a1c02834a7f6330 | 11,583 | cpp | C++ | src/Gaffer/Loop.cpp | sebaDesmet/gaffer | 47b2d093c40452bd77947e3b5bd0722a366c8d59 | [
"BSD-3-Clause"
] | null | null | null | src/Gaffer/Loop.cpp | sebaDesmet/gaffer | 47b2d093c40452bd77947e3b5bd0722a366c8d59 | [
"BSD-3-Clause"
] | null | null | null | src/Gaffer/Loop.cpp | sebaDesmet/gaffer | 47b2d093c40452bd77947e3b5bd0722a366c8d59 | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "Gaffer/Loop.h"
#include "Gaffer/ContextAlgo.h"
#include "Gaffer/MetadataAlgo.h"
#include "boost/bind.hpp"
namespace Gaffer
{
IE_CORE_DEFINERUNTIMETYPED( Loop );
Loop::Loop( const std::string &name )
: ComputeNode( name ), m_inPlugIndex( 0 ), m_outPlugIndex( 0 ), m_firstPlugIndex( 0 )
{
// Connect to `childAddedSignal()` so we can set ourselves up later when the
// appropriate plugs are added manually.
/// \todo Remove this and do all the work in `setup()`.
childAddedSignal().connect( boost::bind( &Loop::childAdded, this ) );
}
Loop::~Loop()
{
}
void Loop::setup( const ValuePlug *plug )
{
if( inPlug() )
{
throw IECore::Exception( "Loop already has an \"in\" plug." );
}
if( outPlug() )
{
throw IECore::Exception( "Loop already has an \"out\" plug." );
}
PlugPtr in = plug->createCounterpart( "in", Plug::In );
MetadataAlgo::copyColors( plug , in.get() , /* overwrite = */ false );
in->setFlags( Plug::Serialisable, true );
addChild( in );
PlugPtr out = plug->createCounterpart( "out", Plug::Out );
MetadataAlgo::copyColors( plug , out.get() , /* overwrite = */ false );
addChild( out );
}
ValuePlug *Loop::inPlug()
{
return m_inPlugIndex ? getChild<ValuePlug>( m_inPlugIndex ) : nullptr;
}
const ValuePlug *Loop::inPlug() const
{
return m_inPlugIndex ? getChild<ValuePlug>( m_inPlugIndex ) : nullptr;
}
ValuePlug *Loop::outPlug()
{
return m_outPlugIndex ? getChild<ValuePlug>( m_outPlugIndex ) : nullptr;
}
const ValuePlug *Loop::outPlug() const
{
return m_outPlugIndex ? getChild<ValuePlug>( m_outPlugIndex ) : nullptr;
}
ValuePlug *Loop::nextPlug()
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex ) : nullptr;
}
const ValuePlug *Loop::nextPlug() const
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex ) : nullptr;
}
ValuePlug *Loop::previousPlug()
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex + 1 ) : nullptr;
}
const ValuePlug *Loop::previousPlug() const
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex + 1 ) : nullptr;
}
IntPlug *Loop::iterationsPlug()
{
return m_firstPlugIndex ? getChild<IntPlug>( m_firstPlugIndex + 2 ) : nullptr;
}
const IntPlug *Loop::iterationsPlug() const
{
return m_firstPlugIndex ? getChild<IntPlug>( m_firstPlugIndex + 2 ) : nullptr;
}
StringPlug *Loop::indexVariablePlug()
{
return m_firstPlugIndex ? getChild<StringPlug>( m_firstPlugIndex + 3 ) : nullptr;
}
const StringPlug *Loop::indexVariablePlug() const
{
return m_firstPlugIndex ? getChild<StringPlug>( m_firstPlugIndex + 3 ) : nullptr;
}
Gaffer::BoolPlug *Loop::enabledPlug()
{
return m_firstPlugIndex ? getChild<BoolPlug>( m_firstPlugIndex + 4 ) : nullptr;
}
const Gaffer::BoolPlug *Loop::enabledPlug() const
{
return m_firstPlugIndex ? getChild<BoolPlug>( m_firstPlugIndex + 4 ) : nullptr;
}
Gaffer::Plug *Loop::correspondingInput( const Gaffer::Plug *output )
{
return output == outPlug() ? inPlug() : nullptr;
}
const Gaffer::Plug *Loop::correspondingInput( const Gaffer::Plug *output ) const
{
return output == outPlug() ? inPlug() : nullptr;
}
void Loop::affects( const Plug *input, DependencyNode::AffectedPlugsContainer &outputs ) const
{
ComputeNode::affects( input, outputs );
if( input == iterationsPlug() )
{
addAffectedPlug( outPlug(), outputs );
}
else if(
input == indexVariablePlug() ||
input == enabledPlug()
)
{
addAffectedPlug( outPlug(), outputs );
addAffectedPlug( previousPlug(), outputs );
}
else if( const ValuePlug *inputValuePlug = IECore::runTimeCast<const ValuePlug>( input ) )
{
std::vector<IECore::InternedString> relativeName;
const ValuePlug *ancestor = ancestorPlug( inputValuePlug, relativeName );
if( ancestor == inPlug() || ancestor == nextPlug() )
{
outputs.push_back( descendantPlug( outPlug(), relativeName ) );
outputs.push_back( descendantPlug( previousPlug(), relativeName ) );
}
}
}
void Loop::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const
{
int index = -1;
IECore::InternedString indexVariable;
if( const ValuePlug *plug = sourcePlug( output, context, index, indexVariable ) )
{
Context::EditableScope tmpContext( context );
if( index >= 0 )
{
tmpContext.set<int>( indexVariable, index );
}
else
{
tmpContext.remove( indexVariable );
}
h = plug->hash();
return;
}
ComputeNode::hash( output, context, h );
}
void Loop::compute( ValuePlug *output, const Context *context ) const
{
int index = -1;
IECore::InternedString indexVariable;
if( const ValuePlug *plug = sourcePlug( output, context, index, indexVariable ) )
{
Context::EditableScope tmpContext( context );
if( index >= 0 )
{
tmpContext.set<int>( indexVariable, index );
}
else
{
tmpContext.remove( indexVariable );
}
output->setFrom( plug );
return;
}
ComputeNode::compute( output, context );
}
void Loop::childAdded()
{
setupPlugs();
}
bool Loop::setupPlugs()
{
const ValuePlug *in = getChild<ValuePlug>( "in" );
const ValuePlug *out = getChild<ValuePlug>( "out" );
if( !in || !out )
{
return false;
}
childAddedSignal().disconnect( boost::bind( &Loop::childAdded, this ) );
m_inPlugIndex = std::find( children().begin(), children().end(), in ) - children().begin();
m_outPlugIndex = std::find( children().begin(), children().end(), out ) - children().begin();
const size_t firstPlugIndex = children().size();
addChild( in->createCounterpart( "next", Plug::In ) );
addChild( out->createCounterpart( "previous", Plug::Out ) );
addChild( new IntPlug( "iterations", Gaffer::Plug::In, 10, 0 ) );
addChild( new StringPlug( "indexVariable", Gaffer::Plug::In, "loop:index" ) );
addChild( new BoolPlug( "enabled", Gaffer::Plug::In, true ) );
// Only assign after adding all plugs, because our plug accessors
// use a non-zero value to indicate that all plugs are now available.
m_firstPlugIndex = firstPlugIndex;
// The in/out plugs might be dynamic in the case of
// LoopComputeNode, but because we create the next/previous
// plugs ourselves in response, they don't need to be dynamic.
nextPlug()->setFlags( Plug::Dynamic, false );
previousPlug()->setFlags( Plug::Dynamic, false );
// Copy styling over from main plugs.
/// \todo We shouldn't really need to do this, because plug colours are
/// expected to be registered against plug type, so our plugs will get
/// the right colour automatically (and `copyColors()` will do nothing
/// because of the `overwrite = false` argument). We are keeping it for
/// now to accommodate proprietary extensions which are using custom colours
/// instead of introducing their own plug types, but some day we should
/// just remove this entirely. Note that the same applies for the Dot,
/// ContextProcessor, ArrayPlug and Switch nodes. See
/// https://github.com/GafferHQ/gaffer/pull/2953 for further discussion.
MetadataAlgo::copyColors( inPlug(), nextPlug() , /* overwrite = */ false );
MetadataAlgo::copyColors( inPlug(), previousPlug() , /* overwrite = */ false );
// Because we're a loop, our affects() implementation specifies a cycle
// between nextPlug() and previousPlug(), so we must ask nicely for leniency
// during dirty propagation. The cycles aren't an issue when it comes to
// hash()/compute() because each iteration changes the context and we bottom
// out after the specified number of iterations.
previousPlug()->setFlags( Plug::AcceptsDependencyCycles, true );
for( Gaffer::RecursivePlugIterator it( previousPlug() ); !it.done(); ++it )
{
(*it)->setFlags( Plug::AcceptsDependencyCycles, true );
}
return true;
}
void Loop::addAffectedPlug( const ValuePlug *output, DependencyNode::AffectedPlugsContainer &outputs ) const
{
if( output->children().size() )
{
for( RecursiveOutputPlugIterator it( output ); !it.done(); ++it )
{
if( !(*it)->children().size() )
{
outputs.push_back( it->get() );
}
}
}
else
{
outputs.push_back( output );
}
}
const ValuePlug *Loop::ancestorPlug( const ValuePlug *plug, std::vector<IECore::InternedString> &relativeName ) const
{
while( plug )
{
const GraphComponent *plugParent = plug->parent();
if( plugParent == this )
{
return plug;
}
else
{
relativeName.push_back( plug->getName() );
plug = static_cast<const ValuePlug *>( plugParent );
}
}
return nullptr;
}
const ValuePlug *Loop::descendantPlug( const ValuePlug *plug, const std::vector<IECore::InternedString> &relativeName ) const
{
for( std::vector<IECore::InternedString>::const_reverse_iterator it = relativeName.rbegin(), eIt = relativeName.rend(); it != eIt; ++it )
{
plug = plug->getChild<ValuePlug>( *it );
}
return plug;
}
const ValuePlug *Loop::sourcePlug( const ValuePlug *output, const Context *context, int &sourceLoopIndex, IECore::InternedString &indexVariable ) const
{
sourceLoopIndex = -1;
ContextAlgo::GlobalScope globalScope( context, inPlug() );
indexVariable = indexVariablePlug()->getValue();
std::vector<IECore::InternedString> relativeName;
const ValuePlug *ancestor = ancestorPlug( output, relativeName );
if( ancestor == previousPlug() )
{
const int index = context->get<int>( indexVariable, 0 );
if( index >= 1 && enabledPlug()->getValue() )
{
sourceLoopIndex = index - 1;
return descendantPlug( nextPlug(), relativeName );
}
else
{
return descendantPlug( inPlug(), relativeName );
}
}
else if( ancestor == outPlug() )
{
const int iterations = iterationsPlug()->getValue();
if( iterations > 0 && enabledPlug()->getValue() )
{
sourceLoopIndex = iterations - 1;
return descendantPlug( nextPlug(), relativeName );
}
else
{
return descendantPlug( inPlug(), relativeName );
}
}
return nullptr;
}
} // namespace Gaffer
| 30.085714 | 151 | 0.693085 | sebaDesmet |
e1e44441baa81a3b81111f8dafa04a4ce0840b82 | 18 | cpp | C++ | tools/datadic_template_tail.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 15 | 2016-01-28T16:54:57.000Z | 2021-04-16T08:28:21.000Z | tools/datadic_template_tail.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | null | null | null | tools/datadic_template_tail.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 3 | 2016-07-16T05:22:11.000Z | 2020-04-03T08:59:26.000Z |
}
}
}
#endif
| 1.8 | 6 | 0.277778 | mariusherzog |
e1e4b1ff626da2248eafe06ab928efcd07af6081 | 1,507 | cpp | C++ | mpid/nt2unix/tests/test_threads_2.cpp | RWTH-OS/MP-MPICH | f2ae296477bb9d812fda587221b3419c09f85b4a | [
"mpich2"
] | null | null | null | mpid/nt2unix/tests/test_threads_2.cpp | RWTH-OS/MP-MPICH | f2ae296477bb9d812fda587221b3419c09f85b4a | [
"mpich2"
] | null | null | null | mpid/nt2unix/tests/test_threads_2.cpp | RWTH-OS/MP-MPICH | f2ae296477bb9d812fda587221b3419c09f85b4a | [
"mpich2"
] | 1 | 2021-01-23T11:01:01.000Z | 2021-01-23T11:01:01.000Z | /* $id$ */
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define Size 8192
LPVOID Address;
volatile unsigned long counter;
DWORD __stdcall threadFunc(void *) {
fprintf(stderr, "Thread start \n");
getc(stdin);
return 0;
}
LONG MemoryExceptionFilter(_EXCEPTION_POINTERS *ExceptionInfo) { // address of exception info
DWORD OldProtection;
EXCEPTION_RECORD *ExRec=ExceptionInfo->ExceptionRecord;
if(ExRec->ExceptionCode!=EXCEPTION_ACCESS_VIOLATION) {
return EXCEPTION_CONTINUE_SEARCH;
}
fprintf(stderr, "Counter == %d\n", counter);
cerr << (ExRec->ExceptionInformation[0]?"Write":"Read")<<"-violation at "<<(void*)ExRec->ExceptionInformation[1]<<endl;
if(ExRec->ExceptionInformation[1] == 0)
return EXCEPTION_CONTINUE_SEARCH;
if(++counter<100)
return EXCEPTION_CONTINUE_EXECUTION;
else {
VirtualProtect((void*)ExRec->ExceptionInformation[1],4096,PAGE_READWRITE,&OldProtection);
return EXCEPTION_CONTINUE_EXECUTION;
}
}
int main() {
volatile char a = '\0';
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)MemoryExceptionFilter);
counter=0;
Address=VirtualAlloc(0,Size,MEM_COMMIT,PAGE_NOACCESS);
if(!Address) {
cerr<<"VirtualAllocFailed!!!\n";
return 0;
}
DWORD id;
CreateThread(0, 0, threadFunc, 0, 0, &id);
//__try {
((char*)Address)[4096]=0;
counter=0;
a = *((char*)Address);
//} __except(MemoryExceptionFilter(GetExceptionInformation())){};
return 0;
}
| 20.643836 | 120 | 0.707366 | RWTH-OS |
e1e586520cdaecdacf771e0c7269c75e3eaad61c | 3,940 | cpp | C++ | src/MetricsUploader/CaptureMetric.cpp | hrkrx/orbit | 47621f2ea6e5bba055861e1111addcb1d913a440 | [
"BSD-2-Clause"
] | 2 | 2020-07-31T08:18:58.000Z | 2021-12-26T06:43:07.000Z | src/MetricsUploader/CaptureMetric.cpp | hrkrx/orbit | 47621f2ea6e5bba055861e1111addcb1d913a440 | [
"BSD-2-Clause"
] | null | null | null | src/MetricsUploader/CaptureMetric.cpp | hrkrx/orbit | 47621f2ea6e5bba055861e1111addcb1d913a440 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2021 The Orbit 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 "MetricsUploader/CaptureMetric.h"
#include <chrono>
#include <cstdint>
#include <filesystem>
#include "OrbitBase/File.h"
#include "OrbitBase/Logging.h"
#include "orbit_log_event.pb.h"
namespace orbit_metrics_uploader {
CaptureMetric::CaptureMetric(MetricsUploader* uploader, const CaptureStartData& start_data)
: uploader_(uploader), start_(std::chrono::steady_clock::now()) {
CHECK(uploader_ != nullptr);
capture_data_.set_number_of_instrumented_functions(start_data.number_of_instrumented_functions);
capture_data_.set_number_of_frame_tracks(start_data.number_of_frame_tracks);
capture_data_.set_thread_states(start_data.thread_states);
capture_data_.set_memory_information_sampling_period_ms(
start_data.memory_information_sampling_period_ms);
capture_data_.set_lib_orbit_vulkan_layer(start_data.lib_orbit_vulkan_layer);
capture_data_.set_local_marker_depth_per_command_buffer(
start_data.local_marker_depth_per_command_buffer);
capture_data_.set_max_local_marker_depth_per_command_buffer(
start_data.max_local_marker_depth_per_command_buffer);
}
void CaptureMetric::SetCaptureCompleteData(const CaptureCompleteData& complete_data) {
capture_data_.set_number_of_instrumented_function_timers(
complete_data.number_of_instrumented_function_timers);
capture_data_.set_number_of_gpu_activity_timers(complete_data.number_of_gpu_activity_timers);
capture_data_.set_number_of_vulkan_layer_gpu_command_buffer_timers(
complete_data.number_of_vulkan_layer_gpu_command_buffer_timers);
capture_data_.set_number_of_vulkan_layer_gpu_debug_marker_timers(
complete_data.number_of_vulkan_layer_gpu_debug_marker_timers);
capture_data_.set_number_of_manual_start_timers(complete_data.number_of_manual_start_timers);
capture_data_.set_number_of_manual_stop_timers(complete_data.number_of_manual_stop_timers);
capture_data_.set_number_of_manual_start_async_timers(
complete_data.number_of_manual_start_async_timers);
capture_data_.set_number_of_manual_stop_async_timers(
complete_data.number_of_manual_stop_async_timers);
capture_data_.set_number_of_manual_tracked_value_timers(
complete_data.number_of_manual_tracked_value_timers);
file_path_ = complete_data.file_path;
}
bool CaptureMetric::SendCaptureFailed() {
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_);
capture_data_.set_duration_in_milliseconds(duration.count());
status_code_ = OrbitLogEvent_StatusCode_INTERNAL_ERROR;
return uploader_->SendCaptureEvent(capture_data_, status_code_);
}
bool CaptureMetric::SendCaptureCancelled() {
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_);
capture_data_.set_duration_in_milliseconds(duration.count());
status_code_ = OrbitLogEvent_StatusCode_CANCELLED;
return uploader_->SendCaptureEvent(capture_data_, status_code_);
}
bool CaptureMetric::SendCaptureSucceeded(std::chrono::milliseconds duration_in_milliseconds) {
capture_data_.set_duration_in_milliseconds(duration_in_milliseconds.count());
status_code_ = OrbitLogEvent_StatusCode_SUCCESS;
if (file_path_.empty()) {
ERROR("Unable to determine capture file size for metrics. File path is empty");
} else {
ErrorMessageOr<uint64_t> file_size = orbit_base::FileSize(file_path_);
if (file_size.has_error()) {
ERROR("Unable to determine capture file size for metrics. File: \"%s\"; error: %s",
file_path_.string(), file_size.error().message());
} else {
capture_data_.set_file_size(file_size.value());
}
}
return uploader_->SendCaptureEvent(capture_data_, status_code_);
}
} // namespace orbit_metrics_uploader | 45.813953 | 98 | 0.816497 | hrkrx |
e1e669e49acbe07063387bad419876c82e6f925c | 1,354 | hpp | C++ | include/kobuki_core/modules/sound.hpp | kobuki-base/kobuki_core | 5fb88169d010c3a23f24ff0ba7e9cb45b46b24e8 | [
"BSD-3-Clause"
] | 10 | 2020-06-01T05:05:27.000Z | 2022-01-18T13:19:58.000Z | include/kobuki_core/modules/sound.hpp | clalancette/kobuki_core | e5bef97d3c1db24441508673e08c67be599faa84 | [
"BSD-3-Clause"
] | 28 | 2020-01-10T14:42:54.000Z | 2021-07-28T08:01:44.000Z | include/kobuki_core/modules/sound.hpp | clalancette/kobuki_core | e5bef97d3c1db24441508673e08c67be599faa84 | [
"BSD-3-Clause"
] | 8 | 2020-02-04T09:59:18.000Z | 2021-08-29T01:59:38.000Z | /**
* @file /kobuki_core/include/kobuki_core/modules/sound.hpp
*
* @brief Flags and id's for commanding sound sequences.
*
* License: BSD
* https://raw.githubusercontent.com/kobuki-base/kobuki_core/license/LICENSE
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef KOBUKI_CORE_SOUND_HPP_
#define KOBUKI_CORE_SOUND_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace kobuki {
/*****************************************************************************
** Enums
*****************************************************************************/
enum SoundSequences
{
On = 0x0, /**< Turn on **/
Off = 0x1, /**< Turn off **/
Recharge = 0x2, /**< Recharging starting **/
Button = 0x3, /**< Button pressed **/
Error = 0x4, /**< Error sound **/
CleaningStart = 0x5, /**< Cleaning started **/
CleaningEnd = 0x6, /**< Cleaning ended **/
};
} // namespace kobuki
#endif /* KOBUKI_CORE_SOUND_HPP_ */
| 30.772727 | 78 | 0.350812 | kobuki-base |
e1e6ace46bd157efc2be7f99b06c0770221c0e2b | 8,282 | hh | C++ | grasp/run_trials.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 70 | 2018-10-17T17:37:22.000Z | 2022-02-28T15:19:47.000Z | grasp/run_trials.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 3 | 2020-12-08T13:02:17.000Z | 2022-02-22T11:59:00.000Z | grasp/run_trials.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 17 | 2018-10-29T04:09:45.000Z | 2022-03-19T11:34:55.000Z | /*!
\file grasp/run_trials.hh
\brief Performs grasp trials
Run full dynamic simulated grasp trials in Gazebo
\author João Borrego : jsbruglie
*/
#ifndef _RUN_TRIALS_HH_
#define _RUN_TRIALS_HH_
// Gazebo
#include <gazebo/gazebo_client.hh>
#include <gazebo/gazebo_config.h>
#include <gazebo/transport/transport.hh>
#include <gazebo/msgs/msgs.hh>
// I/O streams
#include <iostream>
// Threads
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
// Open YAML config files
#include "yaml-cpp/yaml.h"
// Custom messages
#include "MessageTypes.hh"
// Grasp representation
#include "Grasp.hh"
// Rest pose utils
#include "RestPose.hh"
// Interface for hand plugin
#include "Interface.hh"
// Tools
#include "object_utils.hh"
// Debug streams
#include "debug.hh"
// Randomiser class
#include "Randomiser.hh"
// GAP
// Custom messages
#include "dr_request.pb.h"
// Domain randomization plugin interface
#include "DRInterface.hh"
/// Config dictionary
typedef std::map<std::string,std::string> Config;
// Topics
/// Topic monitored by hand plugin for incoming requests
#define HAND_REQ_TOPIC "~/hand"
/// Topic for hand plugin responses
#define HAND_RES_TOPIC "~/hand/response"
/// Topic monitored by target plugin for incoming requests
#define TARGET_REQ_TOPIC "~/grasp/target"
/// Topic for target plugin responses
#define TARGET_RES_TOPIC "~/grasp/target/response"
/// Topic monitored by contacts plugin for incoming requests
#define CONTACT_REQ_TOPIC "~/grasp/contact"
/// Topic for contacts plugin responses
#define CONTACT_RES_TOPIC "~/grasp/contact/response"
/// Topic monitored by camera plugin for incoming requests
#define CAMERA_REQ_TOPIC "~/grasp/rgbd"
/// Topic for camera plugin responses
#define CAMERA_RES_TOPIC "~/grasp/rgbd/response"
/// Topic for Gazebo factory utility
#define FACTORY_TOPIC "~/factory"
/// Topic for generic Gazebo requests
#define REQUEST_TOPIC "~/request"
// Type enums
// Target Plugin
/// Get pose request
#define REQ_GET_POSE grasp::msgs::TargetRequest::GET_POSE
/// Set pose request
#define REQ_SET_POSE grasp::msgs::TargetRequest::SET_POSE
/// Update rest pose request
#define REQ_REST_POSE grasp::msgs::TargetRequest::GET_REST_POSE
/// Reset request
#define REQ_RESET grasp::msgs::TargetRequest::RESET
/// Current pose response
#define RES_POSE grasp::msgs::TargetResponse::POSE
/// Updated rest pose response
#define RES_REST_POSE grasp::msgs::TargetResponse::REST_POSE
// Camera plugin
/// Request to capture frame
#define REQ_CAPTURE grasp::msgs::CameraRequest::CAPTURE
// Hand plugin
/// Position control
#define POSITION grasp::msgs::Target::POSITION
/// Velocity control
#define VELOCITY grasp::msgs::Target::VELOCITY
/// Invalid grasp flag
#define INVALID_GRASP -1.0
// Message type definitions
/// Declaration for hand message type
typedef grasp::msgs::Hand HandMsg;
/// Shared pointer declaration for hand message type
typedef const boost::shared_ptr<const grasp::msgs::Hand>
HandMsgPtr;
/// Declaration for request message type
typedef grasp::msgs::TargetRequest TargetRequest;
/// Shared pointer declaration for request message type
typedef const boost::shared_ptr<const grasp::msgs::TargetRequest>
TargetRequestPtr;
/// Declaration for response message type
typedef grasp::msgs::TargetResponse TargetResponse;
/// Shared pointer declaration for response message type
typedef const boost::shared_ptr<const grasp::msgs::TargetResponse>
TargetResponsePtr;
/// Declaration for request aux message type
typedef grasp::msgs::CollisionRequest CollisionRequest;
/// Declaration for request message type
typedef grasp::msgs::ContactRequest ContactRequest;
/// Shared pointer declaration for request message type
typedef const boost::shared_ptr<const grasp::msgs::ContactRequest>
ContactRequestPtr;
/// Declaration for response message type
typedef grasp::msgs::ContactResponse ContactResponse;
/// Shared pointer declaration for response message type
typedef const boost::shared_ptr<const grasp::msgs::ContactResponse>
ContactResponsePtr;
/// Declaration for request message type
typedef grasp::msgs::CameraRequest CameraRequest;
/// Shared pointer declaration for request message type
typedef const boost::shared_ptr<const grasp::msgs::CameraRequest>
CameraRequestPtr;
/// Declaration for response message type
typedef grasp::msgs::CameraResponse CameraResponse;
/// Shared pointer declaration for response message type
typedef const boost::shared_ptr<const grasp::msgs::CameraResponse>
CameraResponsePtr;
//
// Argument parsing and setup
//
/// \brief Obtains usage string
/// \param argv_0 Name of the executable
/// \return String with command-line usage
const std::string getUsage(const char* argv_0);
/// \brief Parses command-line arguments
/// \param argc Argument count
/// \param argv Arguments
/// \param config Configuration YAML node
void parseArgs(
int argc,
char** argv,
Config & config);
/// \brief Sets up gazebo communication pubs/subs
/// \param node Gazebo communication node pointer
/// \param pubs Resulting map of publishers
/// \param subs Resulting map of subscribers
void setupCommunications(
gazebo::transport::NodePtr & node,
std::map<std::string, gazebo::transport::PublisherPtr> & pubs,
std::map<std::string, gazebo::transport::SubscriberPtr> & subs);
//
// File I/O
//
/// \brief Obtain list of models' names in dataset yml
/// \param targets Output list of model names
/// \param file_name Input dataset config yml
void obtainTargets(std::vector<std::string> & targets,
const std::string & file_name);
/// \brief Obtain list of grasps in yml files
/// \param grasp_cfg_dir Directory for grasp files
/// \param robot Target robot
/// \param object_name Target object name
/// \param grasps Output imported grasps
/// \returns Whether import was successful
bool importGrasps(const std::string & grasp_cfg_dir,
const std::string & robot,
const std::string & object_name,
std::vector<Grasp> & grasps);
/// \brief Export set of metrics to file
/// \param trials_out_dir Output directory
/// \param robot Target robot name
/// \param object_name Target object name
/// \param grasps Set of grasps to export to file
void exportGraspMetrics(const std::string & trials_out_dir,
const std::string & robot,
const std::string & object_name,
const std::vector<Grasp> & grasps);
//
// Gazebo plugin interaction
//
/// \brief Sets hand pose
/// \param pub Publisher to hand's topic
/// \param pose New hand pose
void setPose(gazebo::transport::PublisherPtr pub,
ignition::math::Pose3d pose,
double timeout=-1);
/// \brief Requests collisions in the world
/// \param pub Publisher to contact topic
/// \param target The target object name
/// \param hand The hand model name
void checkHandCollisions(gazebo::transport::PublisherPtr pub,
const std::string & hand,
std::vector<std::string> & targets);
/// \brief Closes manipulator fingers
/// \param pub Publisher to hand topic
/// \param timeout Timeout in seconds
/// \warning Applies force directly
void closeFingers(gazebo::transport::PublisherPtr pub,
double timeout=-1);
/// \brief Lifts robotic manipulator along positive z axis
/// \param pub Publisher to hand topic
/// \param timeout Timeout in seconds
void liftHand(gazebo::transport::PublisherPtr pub,
double timeout=-1);
/// \brief Resets target object to rest pose
/// \param pub Publisher to target's topic
void resetTarget(gazebo::transport::PublisherPtr pub);
/// \brief Attempts to grasp object
/// \param grasp The grasp configuration
/// \param pubs Map of publishers
/// \param model_name Target object model name
/// \return Grasp outcome metric
double tryGrasp(
Grasp & grasp,
Interface & interface,
std::map<std::string, gazebo::transport::PublisherPtr> & pubs,
const std::string & model_name);
// Synchronisation
/// \brief Waits for condition variable
/// \param timeout Timeout value in milliseconds
void waitForTrigger(int timeout=-1);
// Callback functions
/// TODO
void onHandResponse(HandMsgPtr & _msg);
/// TODO
void onTargetResponse(TargetResponsePtr & _msg);
/// TODO
void onContactResponse(ContactResponsePtr & _msg);
#endif
| 30.226277 | 68 | 0.746921 | el-cangrejo |
e1e6c3c90222d21e2cd1183d7dbcbe9a2f00091f | 504 | cpp | C++ | applications/image-viewer/main.cpp | harsh-kakasaniya55/skift | 79ccaf5398cfb7921599105607ad6688ece452d8 | [
"MIT"
] | 2 | 2021-08-14T16:03:48.000Z | 2021-11-09T10:29:36.000Z | applications/image-viewer/main.cpp | harsh-kakasaniya55/skift | 79ccaf5398cfb7921599105607ad6688ece452d8 | [
"MIT"
] | null | null | null | applications/image-viewer/main.cpp | harsh-kakasaniya55/skift | 79ccaf5398cfb7921599105607ad6688ece452d8 | [
"MIT"
] | 2 | 2020-10-13T14:25:30.000Z | 2020-10-13T14:39:40.000Z | #include <libwidget/Application.h>
#include <libwidget/Widgets.h>
int main(int argc, char **argv)
{
if (argc == 1)
return -1;
if (application_initialize(argc, argv) != SUCCESS)
return -1;
Window *window = new Window(WINDOW_RESIZABLE);
window->icon(Icon::get("image"));
window->title("Image Viewer");
window->size(Vec2i(700, 500));
new Image(window->root(), Bitmap::load_from_or_placeholder(argv[1]));
window->show();
return application_run();
}
| 21 | 73 | 0.634921 | harsh-kakasaniya55 |
e1ebe397a5498ffb928acb3bcdcba8ff0e5b1ec0 | 435 | cpp | C++ | src/logic/wire_get_inputs.cpp | nanolith/homesim | 693cd77c9ecd0fb8bbaf1848609a63eb56fa4b86 | [
"MIT"
] | null | null | null | src/logic/wire_get_inputs.cpp | nanolith/homesim | 693cd77c9ecd0fb8bbaf1848609a63eb56fa4b86 | [
"MIT"
] | null | null | null | src/logic/wire_get_inputs.cpp | nanolith/homesim | 693cd77c9ecd0fb8bbaf1848609a63eb56fa4b86 | [
"MIT"
] | null | null | null | /**
* \file logic/wire_get_inputs.cpp
*
* \brief Get the number of input connections on this wire.
*
* \copyright Copyright 2020 Justin Handville. All rights reserved.
*/
#include <homesim/wire.h>
using namespace homesim;
using namespace std;
/**
* \brief Get the number of input connections associated with this wire.
*
* \brief return the number of inputs.
*/
int homesim::wire::get_inputs() const
{
return inputs;
}
| 19.772727 | 72 | 0.710345 | nanolith |
e1ec110d998274f5a5c52cc4d6f51dad04dfb176 | 999 | cpp | C++ | ojcpp/leetcode/200/231_e_poweroftwo.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | 3 | 2019-05-04T03:26:02.000Z | 2019-08-29T01:20:44.000Z | ojcpp/leetcode/200/231_e_poweroftwo.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | ojcpp/leetcode/200/231_e_poweroftwo.cpp | softarts/oj | 2f51f360a7a6c49e865461755aec2f3a7e721b9e | [
"Apache-2.0"
] | null | null | null | //
// Created by Rui Zhou on 30/3/18.
//
/*
* https://leetcode.com/problems/power-of-two/description/
*
*/
#include <codech/codech_def.h>
using namespace std;
//这题目好像不对
//namespace yt {
// int Count(const vector<int>& nums)
// {
// int count = 0;
// for (int i = 0;i < nums.size();i++) {
// int sum = nums[i];
// if (sum>=7 && (sum % 7 ==0))
// count++;
// for (int j = i+1;j<nums.size();j++) {
// sum += nums[j];
// if (sum >= 7 && (sum % 7 ==0)) {
// count++;
// }
// }
// }
// return count;
// }
//}
// 判断一个数是不是2的幂
// 最高位是1,后面都是0
namespace {
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n&(n-1))==0;
}
};
}
DEFINE_CODE_TEST(231_poweroftwo)
{
Solution obj;
{
VERIFY_CASE(obj.isPowerOfTwo(1),true);
VERIFY_CASE(obj.isPowerOfTwo(2),true);
}
}
| 17.839286 | 58 | 0.443443 | softarts |
e1f0eabc86e95178e3bf794c4208cdec17c6d142 | 1,540 | cpp | C++ | source files/StringTest.cpp | SABERGLOW/String_Class | 407ca5d7640417e756eeb5e0742a447c035df9fb | [
"MIT"
] | 4 | 2020-07-28T16:57:11.000Z | 2020-08-26T16:33:43.000Z | source files/StringTest.cpp | SABERGLOW/String_Class | 407ca5d7640417e756eeb5e0742a447c035df9fb | [
"MIT"
] | null | null | null | source files/StringTest.cpp | SABERGLOW/String_Class | 407ca5d7640417e756eeb5e0742a447c035df9fb | [
"MIT"
] | null | null | null | #include <iostream>
#include "String.h"
#include "String.cpp"
using namespace std;
using namespace HomeMadeString;
int main()
{
// Test the default constructor
String s1;
// Test the conversion constructor
String s2="Hello, hello!";
// Let's see the results
cout<<endl<<"TESTING s1: "<<endl;
s1.print(cout);
cout<<endl;
cout<<endl<<"TESTING s2: "<<endl;
s2.print(cout);
cout<<endl<<endl;
// Test the copy function
String::copy(s1,s2);
cout<<endl<<"COPY FUNCTION TESTING: "<<endl;
s1.print(cout);
cout<<endl;
s2.print(cout);
cout<<endl;
// Test the compare function
cout<<endl<<"COMPARE FUNCTION TESTING: "<<endl;
if(String::compare(s1,s2))
cout<<"s1 and s2 are the same!"<<endl;
// Test the special constructor with two parameters
String s3('-',15);
cout<<endl<<"SPECIAL CONSTRUCTOR TESTING: "<<endl;
s3.print(cout);
cout<<endl;
// Test the concatenate function and the copy constructor
cout<<endl<<"CONCATENATE FUNCTION TESTING: "<<endl;
String s4=String::concatenate(s2,s3);
s4.print(cout);
cout<<endl;
// Test the GetChar function
cout<<endl<<"get Char TESTING: "<<endl;
for(int i=0; i<s4.getLength();i++)
{
cout<<s4.getChar(i);
}
cout<<endl;
// Test the getStr function
char* pStr=new char[s4.getLength()+1]; // Reserving memory for string and terminating character
s4.getStr(pStr);
cout<<pStr<<endl; // cout can work with strings
delete[] pStr; // delete the buffer and release the allocated memory
return 0;
}
| 23.692308 | 97 | 0.657143 | SABERGLOW |
e1f6799a75aa244a8dce78e19b3602a504d02528 | 307 | cpp | C++ | aql/benchmark/lib_7/class_4.cpp | menify/sandbox | 32166c71044f0d5b414335b2b6559adc571f568c | [
"MIT"
] | null | null | null | aql/benchmark/lib_7/class_4.cpp | menify/sandbox | 32166c71044f0d5b414335b2b6559adc571f568c | [
"MIT"
] | null | null | null | aql/benchmark/lib_7/class_4.cpp | menify/sandbox | 32166c71044f0d5b414335b2b6559adc571f568c | [
"MIT"
] | null | null | null | #include "class_4.h"
#include "class_6.h"
#include "class_1.h"
#include "class_0.h"
#include "class_3.h"
#include "class_4.h"
#include <lib_6/class_6.h>
#include <lib_5/class_9.h>
#include <lib_6/class_2.h>
#include <lib_3/class_1.h>
#include <lib_3/class_7.h>
class_4::class_4() {}
class_4::~class_4() {}
| 20.466667 | 26 | 0.710098 | menify |
e1f7492f415d27eb623bdbd87f7ec7406853a1ad | 2,747 | hpp | C++ | OcularEditor/include/Widgets/Standard/LineEdit.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 8 | 2017-01-27T01:06:06.000Z | 2020-11-05T20:23:19.000Z | OcularEditor/include/Widgets/Standard/LineEdit.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 39 | 2016-06-03T02:00:36.000Z | 2017-03-19T17:47:39.000Z | OcularEditor/include/Widgets/Standard/LineEdit.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 4 | 2019-05-22T09:13:36.000Z | 2020-12-01T03:17:45.000Z | /**
* Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef __H__OCULAR_EDITOR_LINE_EDIT__H__
#define __H__OCULAR_EDITOR_LINE_EDIT__H__
#include <QtWidgets/qlineedit.h>
//------------------------------------------------------------------------------------------
/**
* \addtogroup Ocular
* @{
*/
namespace Ocular
{
/**
* \addtogroup Editor
* @{
*/
namespace Editor
{
enum class LineType
{
String = 0,
Int8,
UInt8,
Int16,
UInt16,
Int32,
UInt32,
Float,
Double
};
/**
* \class LineEdit
*
* Helper class that automatically handles input mask, etc. setup based
* on the specified LineType.
*/
class LineEdit : public QLineEdit
{
Q_OBJECT
public:
LineEdit(LineType type, QWidget* parent = nullptr);
virtual ~LineEdit();
/**
* \param[in] reset If TRUE, then the edited flag is reset back to FALSE.
* \return TRUE if the user has modifed this edit (return key was pressed).
*/
bool wasEdited(bool reset = true);
/**
*
*/
void setInvalid(bool invalid);
/**
*
*/
int32_t asInt() const;
/**
*
*/
uint32_t asUint() const;
/**
*
*/
float asFloat() const;
template<typename T>
T as() const { return OcularString->fromString<T>(text().toStdString()); }
protected:
private slots:
void contentsChanged(QString const& text);
void userEdited(QString const& text);
private:
LineType m_Type;
bool m_WasEdited;
};
}
/**
* @} End of Doxygen Groups
*/
}
/**
* @} End of Doxygen Groups
*/
//------------------------------------------------------------------------------------------
#endif | 23.478632 | 92 | 0.488533 | ssell |
e1f81cb8a2e4ced1b30a218e97e87951e1d3ad0b | 10,511 | hh | C++ | Include/OpenMesh/Tools/Decimater/ModNormalDeviationT.hh | 565353780/peeling-art | 7427321c8cbf076361c8de2281a0f0cde7fd38bb | [
"MIT"
] | null | null | null | Include/OpenMesh/Tools/Decimater/ModNormalDeviationT.hh | 565353780/peeling-art | 7427321c8cbf076361c8de2281a0f0cde7fd38bb | [
"MIT"
] | null | null | null | Include/OpenMesh/Tools/Decimater/ModNormalDeviationT.hh | 565353780/peeling-art | 7427321c8cbf076361c8de2281a0f0cde7fd38bb | [
"MIT"
] | null | null | null | /* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* 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. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file ModNormalDeviationT.hh
*/
//=============================================================================
//
// CLASS ModNormalDeviationT
//
//=============================================================================
#ifndef OPENMESH_DECIMATER_MODNORMALDEVIATIONT_HH
#define OPENMESH_DECIMATER_MODNORMALDEVIATIONT_HH
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/ModBaseT.hh>
#include <OpenMesh/Core/Utils/Property.hh>
#include <OpenMesh/Core/Geometry/NormalConeT.hh>
//== NAMESPACES ===============================================================
namespace OpenMesh {
namespace Decimater {
//== CLASS DEFINITION =========================================================
/** \brief Use Normal deviation to control decimation
*
* The module tracks the normals while decimating
* a normal cone consisting of all normals of the
* faces collapsed together is computed and if
* a collapse would increase the size of
* the cone to a value greater than the given value
* the collapse will be illegal.
*
* In binary and mode, the collapse is legal if:
* - The normal deviation after the collapse is lower than the given value
*
* In continuous mode the maximal deviation is returned
*/
template <class MeshT>
class ModNormalDeviationT : public ModBaseT< MeshT >
{
public:
DECIMATING_MODULE( ModNormalDeviationT, MeshT, NormalDeviation );
typedef typename Mesh::Scalar Scalar;
typedef typename Mesh::Point Point;
typedef typename Mesh::Normal Normal;
typedef typename Mesh::VertexHandle VertexHandle;
typedef typename Mesh::FaceHandle FaceHandle;
typedef typename Mesh::EdgeHandle EdgeHandle;
typedef NormalConeT<Scalar> NormalCone;
public:
/// Constructor
ModNormalDeviationT(MeshT& _mesh, float _max_dev = 180.0)
: Base(_mesh, true), mesh_(Base::mesh())
{
set_normal_deviation(_max_dev);
mesh_.add_property(normal_cones_);
const bool mesh_has_normals = _mesh.has_face_normals();
_mesh.request_face_normals();
if (!mesh_has_normals)
{
omerr() << "Mesh has no face normals. Compute them automatically." << std::endl;
_mesh.update_face_normals();
}
}
/// Destructor
~ModNormalDeviationT() {
mesh_.remove_property(normal_cones_);
mesh_.release_face_normals();
}
/// Get normal deviation ( 0 .. 360 )
Scalar normal_deviation() const {
return normal_deviation_ / M_PI * 180.0;
}
/// Set normal deviation ( 0 .. 360 )
void set_normal_deviation(Scalar _s) {
normal_deviation_ = _s / static_cast<Scalar>(180.0) * static_cast<Scalar>(M_PI);
}
/// Allocate and init normal cones
void initialize() {
if (!normal_cones_.is_valid())
mesh_.add_property(normal_cones_);
typename Mesh::FaceIter f_it = mesh_.faces_begin(),
f_end = mesh_.faces_end();
for (; f_it != f_end; ++f_it)
mesh_.property(normal_cones_, *f_it) = NormalCone(mesh_.normal(*f_it));
}
/** \brief Control normals when Decimating
*
* Binary and Cont. mode.
*
* The module tracks the normals while decimating
* a normal cone consisting of all normals of the
* faces collapsed together is computed and if
* a collapse would increase the size of
* the cone to a value greater than the given value
* the collapse will be illegal.
*
* @param _ci Collapse info data
* @return Half of the normal cones size (radius in radians)
*/
float collapse_priority(const CollapseInfo& _ci) {
// simulate collapse
mesh_.set_point(_ci.v0, _ci.p1);
typename Mesh::Scalar max_angle(0.0);
typename Mesh::ConstVertexFaceIter vf_it(mesh_, _ci.v0);
typename Mesh::FaceHandle fh, fhl, fhr;
if (_ci.v0vl.is_valid()) fhl = mesh_.face_handle(_ci.v0vl);
if (_ci.vrv0.is_valid()) fhr = mesh_.face_handle(_ci.vrv0);
for (; vf_it.is_valid(); ++vf_it) {
fh = *vf_it;
if (fh != _ci.fl && fh != _ci.fr) {
NormalCone nc = mesh_.property(normal_cones_, fh);
nc.merge(NormalCone(mesh_.calc_face_normal(fh)));
if (fh == fhl) nc.merge(mesh_.property(normal_cones_, _ci.fl));
if (fh == fhr) nc.merge(mesh_.property(normal_cones_, _ci.fr));
if (nc.angle() > max_angle) {
max_angle = nc.angle();
if (max_angle > 0.5 * normal_deviation_)
break;
}
}
}
// undo simulation changes
mesh_.set_point(_ci.v0, _ci.p0);
return (max_angle < 0.5 * normal_deviation_ ? max_angle : float( Base::ILLEGAL_COLLAPSE ));
}
/// set the percentage of normal deviation
void set_error_tolerance_factor(double _factor) {
if (_factor >= 0.0 && _factor <= 1.0) {
// the smaller the factor, the smaller normal_deviation_ gets
// thus creating a stricter constraint
// division by error_tolerance_factor_ is for normalization
Scalar normal_deviation = (normal_deviation_ * static_cast<Scalar>(180.0)/static_cast<Scalar>(M_PI) ) * _factor / this->error_tolerance_factor_;
set_normal_deviation(normal_deviation);
this->error_tolerance_factor_ = _factor;
}
}
void postprocess_collapse(const CollapseInfo& _ci) {
// account for changed normals
typename Mesh::VertexFaceIter vf_it(mesh_, _ci.v1);
for (; vf_it.is_valid(); ++vf_it)
mesh_.property(normal_cones_, *vf_it).
merge(NormalCone(mesh_.normal(*vf_it)));
// normal cones of deleted triangles
typename Mesh::FaceHandle fh;
if (_ci.vlv1.is_valid()) {
fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(_ci.vlv1));
if (fh.is_valid())
mesh_.property(normal_cones_, fh).
merge(mesh_.property(normal_cones_, _ci.fl));
}
if (_ci.v1vr.is_valid()) {
fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(_ci.v1vr));
if (fh.is_valid())
mesh_.property(normal_cones_, fh).
merge(mesh_.property(normal_cones_, _ci.fr));
}
}
private:
Mesh& mesh_;
Scalar normal_deviation_;
OpenMesh::FPropHandleT<NormalCone> normal_cones_;
};
//=============================================================================
} // END_NS_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
#endif // OPENMESH_DECIMATER_MODNORMALDEVIATIONT_HH defined
//=============================================================================
| 39.367041 | 151 | 0.508229 | 565353780 |
e1fa970b57e33dfee8949461c014256eba122678 | 7,196 | cc | C++ | server.cc | ctiller/ced-1 | 8aa0bb3431988c7f13a0e5a40f378e8e9fa0066b | [
"Apache-2.0"
] | null | null | null | server.cc | ctiller/ced-1 | 8aa0bb3431988c7f13a0e5a40f378e8e9fa0066b | [
"Apache-2.0"
] | null | null | null | server.cc | ctiller/ced-1 | 8aa0bb3431988c7f13a0e5a40f378e8e9fa0066b | [
"Apache-2.0"
] | 1 | 2021-11-29T13:02:11.000Z | 2021-11-29T13:02:11.000Z | // Copyright 2017 Google LLC
//
// 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
//
// https://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 "server.h"
#include <grpc++/security/server_credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <map>
#include "absl/synchronization/mutex.h"
#include "application.h"
#include "buffer.h"
#include "log.h"
#include "proto/project_service.grpc.pb.h"
#include "run.h"
#include "src_hash.h"
class ProjectServer : public Application, public ProjectService::Service {
public:
ProjectServer(int argc, char** argv)
: project_(PathFromArgs(argc, argv), false),
active_requests_(0),
last_activity_(absl::Now()),
quit_requested_(false) {
if (PathFromArgs(argc, argv) !=
project_.aspect<ProjectRoot>()->LocalAddressPath()) {
throw std::runtime_error(absl::StrCat(
"Project path misalignment: ", PathFromArgs(argc, argv).string(), " ",
project_.aspect<ProjectRoot>()->LocalAddressPath().string()));
}
server_ =
grpc::ServerBuilder()
.RegisterService(this)
.AddListeningPort(project_.aspect<ProjectRoot>()->LocalAddress(),
grpc::InsecureServerCredentials())
.BuildAndStart();
Log() << "Created server " << server_.get() << " @ "
<< project_.aspect<ProjectRoot>()->LocalAddress();
}
int Run() override {
auto done = [this]() {
mu_.AssertHeld();
return active_requests_ == 0 &&
(quit_requested_ ||
(absl::Now() - last_activity_ > absl::Hours(1)));
};
{
absl::MutexLock lock(&mu_);
while (!mu_.AwaitWithTimeout(absl::Condition(&done),
absl::Duration(absl::Minutes(1))))
;
}
server_->Shutdown();
return 0;
}
grpc::Status ConnectionHello(grpc::ServerContext* context,
const ConnectionHelloRequest* req,
ConnectionHelloResponse* rsp) override {
rsp->set_src_hash(ced_src_hash);
return grpc::Status::OK;
}
grpc::Status Quit(grpc::ServerContext* context, const Empty* req,
Empty* rsp) override {
absl::MutexLock lock(&mu_);
quit_requested_ = true;
return grpc::Status::OK;
}
grpc::Status Edit(
grpc::ServerContext* context,
grpc::ServerReaderWriter<EditMessage, EditMessage>* stream) override {
ScopedRequest scoped_request(this);
EditMessage msg;
if (!stream->Read(&msg)) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"Stream closed with no greeting");
}
if (msg.type_case() != EditMessage::kClientHello) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"First message from client must be ClientHello");
}
Buffer* buffer = GetBuffer(msg.client_hello().buffer_name());
if (!buffer) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"Unable to access requested buffer");
}
Site site;
auto listener = buffer->Listen(
[stream, &site](const AnnotatedString& initial) {
EditMessage out;
auto body = out.mutable_server_hello();
body->set_site_id(site.site_id());
*body->mutable_current_state() = initial.AsProto();
stream->Write(out);
},
[stream](const CommandSet* commands) {
EditMessage out;
*out.mutable_commands() = *commands;
stream->Write(out);
});
while (stream->Read(&msg)) {
if (msg.type_case() != EditMessage::kCommands) {
return grpc::Status(grpc::INVALID_ARGUMENT,
"Expected commands after greetings");
}
buffer->PushChanges(&msg.commands(), true);
}
CommandSet cleanup_commands;
buffer->ContentSnapshot().MakeDeleteAttributesBySite(&cleanup_commands,
site);
buffer->PushChanges(&msg.commands(), false);
return grpc::Status::OK;
}
private:
Project project_;
std::unique_ptr<grpc::Server> server_;
absl::Mutex mu_;
int active_requests_ GUARDED_BY(mu_);
absl::Time last_activity_ GUARDED_BY(mu_);
std::map<boost::filesystem::path, std::unique_ptr<Buffer>> buffers_
GUARDED_BY(mu_);
bool quit_requested_ GUARDED_BY(mu_);
static bool IsChildOf(boost::filesystem::path needle,
boost::filesystem::path haystack) {
needle = boost::filesystem::absolute(needle);
haystack = boost::filesystem::absolute(haystack);
if (haystack.filename() == ".") {
haystack.remove_filename();
}
if (!needle.has_filename()) return false;
needle.remove_filename();
std::string needle_str = needle.string();
std::string haystack_str = haystack.string();
if (needle_str.length() > haystack_str.length()) return false;
return std::equal(haystack_str.begin(), haystack_str.end(),
needle_str.begin());
}
Buffer* GetBuffer(boost::filesystem::path path) {
path = boost::filesystem::absolute(path);
if (!IsChildOf(path, project_.aspect<ProjectRoot>()->Path())) {
Log() << "Attempt to access outside of project sandbox: " << path
<< " in project root " << project_.aspect<ProjectRoot>()->Path();
return nullptr;
}
absl::MutexLock lock(&mu_);
auto it = buffers_.find(path);
if (it != buffers_.end()) {
return it->second.get();
}
return buffers_
.emplace(
path,
Buffer::Builder().SetFilename(path).SetProject(&project_).Make())
.first->second.get();
}
class ScopedRequest {
public:
explicit ScopedRequest(ProjectServer* p) : p_(p) {
absl::MutexLock lock(&p_->mu_);
p_->active_requests_++;
p_->last_activity_ = absl::Now();
}
~ScopedRequest() {
absl::MutexLock lock(&p_->mu_);
p_->active_requests_--;
p_->last_activity_ = absl::Now();
}
private:
ProjectServer* const p_;
};
static boost::filesystem::path PathFromArgs(int argc, char** argv) {
if (argc != 2) throw std::runtime_error("Expected path");
return argv[1];
}
};
REGISTER_APPLICATION(ProjectServer);
void SpawnServer(const boost::filesystem::path& ced_bin,
const Project& project) {
run_daemon(
ced_bin,
{
"-mode",
"ProjectServer",
"-logfile",
(project.aspect<ProjectRoot>()->LocalAddressPath().parent_path() /
absl::StrCat(".cedlog.server.", ced_src_hash))
.string(),
project.aspect<ProjectRoot>()->LocalAddressPath().string(),
});
}
| 33.16129 | 80 | 0.61159 | ctiller |
e1fbbb0c416b02c0f612fd77c7f33b56e69190bc | 1,723 | cpp | C++ | src/Translater/PassManager.cpp | elite-lang/Elite | f65998863bb13c247c27c781b0cdb4cfc6ba8ae3 | [
"MIT"
] | 48 | 2015-12-28T01:42:57.000Z | 2022-03-11T02:59:17.000Z | src/Translater/PassManager.cpp | elite-lang/Elite | f65998863bb13c247c27c781b0cdb4cfc6ba8ae3 | [
"MIT"
] | 17 | 2015-12-16T07:43:52.000Z | 2016-04-17T12:30:48.000Z | src/Translater/PassManager.cpp | elite-lang/Elite | f65998863bb13c247c27c781b0cdb4cfc6ba8ae3 | [
"MIT"
] | 14 | 2015-12-22T06:54:14.000Z | 2020-12-02T06:39:45.000Z |
#include "Elite/Translater/PassManager.h"
#include "Elite/CodeGen/ICodeGenContext.h"
PassManager::PassManager () {
}
PassManager::~PassManager () {
}
void PassManager::NewPassList(const string& name, const vector<Pass*>& vec) {
NewPassList(name, list<Pass*>(vec.begin(), vec.end()));
}
void PassManager::NewPassList(const string& name, const list<Pass*>& lst) {
pass_lists[name] = lst;
}
list<Pass*>* PassManager::getPassList(const string& name) {
auto idx = pass_lists.find(name);
if (idx != pass_lists.end()) return &(idx->second);
return NULL;
}
void PassManager::RunPassList(const string& name, Node* node, ICodeGenContext* ctx) {
auto idx = pass_lists.find(name);
if (idx != pass_lists.end()) {
for (auto i : idx->second) {
// 设置i为活动pass
ctx->setNowPass(i);
ctx->MacroMake(node);
}
}
}
void PassManager::RunPassListWithSet(const string& name, set<Node*>& nodes, ICodeGenContext* ctx) {
auto idx = pass_lists.find(name);
if (idx != pass_lists.end()) {
for (auto i : idx->second) {
// 设置i为活动pass
ctx->setNowPass(i);
for (auto node : nodes)
ctx->MacroMake(node);
}
}
}
extern const FuncReg macro_funcs[];
extern const FuncReg macro_classes[];
extern const FuncReg macro_prescan[];
extern const FuncReg macro_pretype[];
extern const FuncReg macro_defmacro[];
void PassManager::LoadDefaultLists() {
list<Pass*> prescan = { new Pass(macro_defmacro), new Pass(macro_prescan), new Pass(macro_pretype) };
list<Pass*> main = { new Pass(macro_funcs, macro_classes) };
NewPassList("prescan", prescan);
NewPassList("main", main);
}
| 24.971014 | 105 | 0.641323 | elite-lang |
e1fce58e5800d269900e1bbac7ce48afad5b300b | 437 | cpp | C++ | hal/src/driver/null/eplibrary_null.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | hal/src/driver/null/eplibrary_null.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | hal/src/driver/null/eplibrary_null.cpp | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | #include "driver.h"
#if EPSYSTEM_DRIVER == EPDRIVER_NULL
#include "hal/library.h"
bool epLibrary_Open(epLibrary *pLibrary, const char *filename)
{
return false;
}
bool epLibrary_Close(epLibrary library)
{
return false;
}
void *epLibrary_GetFunction(epLibrary library, const char *funcName)
{
return nullptr;
}
char *epLibrary_GetLastError()
{
return nullptr;
}
#else
EPEMPTYFILE
#endif // EPSYSTEM_DRIVER == EPDRIVER_NULL
| 14.566667 | 68 | 0.75286 | Euclideon |
e1fdf3d085af806f32cd1bd4beaa15f487a45f64 | 2,975 | cpp | C++ | src/process_start.cpp | ValentinSidorov/DeLorean_Team | 921eb12d96d202c4c19fded3cf190abcbd075af0 | [
"MIT"
] | null | null | null | src/process_start.cpp | ValentinSidorov/DeLorean_Team | 921eb12d96d202c4c19fded3cf190abcbd075af0 | [
"MIT"
] | 20 | 2022-01-29T13:13:09.000Z | 2022-02-23T09:52:55.000Z | src/process_start.cpp | ValentinSidorov/DeLorean_Team | 921eb12d96d202c4c19fded3cf190abcbd075af0 | [
"MIT"
] | 1 | 2022-02-01T20:43:35.000Z | 2022-02-01T20:43:35.000Z | #include "process_start.h"
pid_t start_process(set_prog_start &program) {
pid_t process_pid;
// create new process
process_pid = fork();
if (process_pid == -1) {
// error of creation process
LOG("Error in process_start. Function fork(), couldn't do fork, for "
"program_name: " +
program.name,
ERROR);
return 0;
} else if (process_pid != 0) {
// parent process
// return child pid
return process_pid;
} else {
// child process
// number of process arguments(first - program name, last - NULL)
int argc = program.cmd_arguments.size() + 2;
// pointer to process arguments
char **argv = new char *[argc];
// first argument - program name
int word_length = 0;
word_length = program.name.length() + 1;
argv[0] = new char[word_length];
// copy program name to arguments array
strncpy(argv[0], program.name.c_str(), word_length);
// copy all arguments to arguments array
for (int i = 1; i < argc - 1; i++) {
word_length = program.cmd_arguments[i - 1].length() + 1;
argv[i] = new char[word_length];
strncpy(argv[i], program.cmd_arguments[i - 1].c_str(), word_length);
}
// last arguments - NULL
argv[argc - 1] = nullptr;
// check if we need to redirect programm's stdout
if (program.stdout_config_file.size() != 0) {
// change file mode depending of stdout_mode config
char file_mode = 0;
if (program.stdout_config_truncate) {
// true - truncate
file_mode = 'w';
} else {
// false - append
file_mode = 'a';
}
// open a log file
if (!freopen(program.stdout_config_file.c_str(), &file_mode, stdout)) {
// it doesn't open
// close stdout
fclose(stdout);
LOG("Error in process_start. Function freopen(), couldn't open stdout "
"config "
"file: " +
program.stdout_config_file,
ERROR);
}
}
// change run program status
program.pid = getpid();
// start new process(change current process to new)
if (execv(program.executable_path.c_str(), argv) == -1) {
// error occurred, program isn't executed
//!!! stdout stream doesn't work here(redirected to file)
// change run program status
program.pid = 0;
// delete argv array
for (int i = 0; i < argc; i++) {
delete[] argv[i];
}
delete[] argv;
argv = nullptr;
// add error info
std::string error_message("Error in proscess_start. Function execv()\n");
error_message += "Couldn't start program: " + program.name + "\n";
error_message +=
"Executable path = " + program.executable_path + "\nError info: ";
error_message.append(strerror(errno));
LOG(error_message, ERROR);
exit(1);
}
// these line is never reached(things below just for cppchecker)
delete[] argv;
return -1;
}
} | 33.806818 | 79 | 0.594286 | ValentinSidorov |
c006290aa4aef27a1aea1ab0b9a1e1cd5939ffed | 827 | cpp | C++ | old_solutions/maximising_xor.cpp | DSC-JSS-NOIDA/competitive | aa8807db24df389e52ba66dd0c5847e60237930b | [
"Apache-2.0"
] | null | null | null | old_solutions/maximising_xor.cpp | DSC-JSS-NOIDA/competitive | aa8807db24df389e52ba66dd0c5847e60237930b | [
"Apache-2.0"
] | null | null | null | old_solutions/maximising_xor.cpp | DSC-JSS-NOIDA/competitive | aa8807db24df389e52ba66dd0c5847e60237930b | [
"Apache-2.0"
] | 7 | 2018-10-25T12:13:25.000Z | 2020-10-01T18:09:05.000Z | #include <bits/stdc++.h>
using namespace std;
// Complete the maximizingXor function below.
int maximizingXor(int l, int r) {
// get xor of limits
int LXR = L ^ R;
// loop to get msb position of L^R
int msbPos = 0;
while (LXR)
{
msbPos++;
LXR >>= 1;
}
// construct result by adding 1,
// msbPos times
int maxXOR = 0;
int two = 1;
while (msbPos--)
{
maxXOR += two;
two <<= 1;
}
return maxXOR;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int l;
cin >> l;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int r;
cin >> r;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int result = maximizingXor(l, r);
fout << result << "\n";
fout.close();
return 0;
}
| 15.603774 | 56 | 0.523579 | DSC-JSS-NOIDA |
c008cb026c37e421c9857f545fa8321eb5b33ec0 | 6,641 | cxx | C++ | Rendering/OpenGL2/vtkToneMappingPass.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkToneMappingPass.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | Rendering/OpenGL2/vtkToneMappingPass.cxx | fluentgcc/VTK | dcbfc0df70212ef9f01cbc2a68387b2d44dce808 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkToneMappingPass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkToneMappingPass.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLFramebufferObject.h"
#include "vtkOpenGLQuadHelper.h"
#include "vtkOpenGLRenderUtilities.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLState.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkShaderProgram.h"
#include "vtkTextureObject.h"
vtkStandardNewMacro(vtkToneMappingPass);
// ----------------------------------------------------------------------------
vtkToneMappingPass::~vtkToneMappingPass()
{
if (this->FrameBufferObject)
{
vtkErrorMacro("FrameBufferObject should have been deleted in ReleaseGraphicsResources().");
}
if (this->ColorTexture)
{
vtkErrorMacro("ColorTexture should have been deleted in ReleaseGraphicsResources().");
}
if (this->QuadHelper)
{
vtkErrorMacro("QuadHelper should have been deleted in ReleaseGraphicsResources().");
}
}
// ----------------------------------------------------------------------------
void vtkToneMappingPass::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "FrameBufferObject:";
if(this->FrameBufferObject!=nullptr)
{
this->FrameBufferObject->PrintSelf(os,indent);
}
else
{
os << "(none)" <<endl;
}
os << indent << "ColorTexture:";
if(this->ColorTexture!=nullptr)
{
this->ColorTexture->PrintSelf(os,indent);
}
else
{
os << "(none)" <<endl;
}
}
// ----------------------------------------------------------------------------
void vtkToneMappingPass::Render(const vtkRenderState* s)
{
vtkOpenGLClearErrorMacro();
this->NumberOfRenderedProps = 0;
vtkRenderer* r = s->GetRenderer();
vtkOpenGLRenderWindow* renWin = static_cast<vtkOpenGLRenderWindow*>(r->GetRenderWindow());
vtkOpenGLState* ostate = renWin->GetState();
vtkOpenGLState::ScopedglEnableDisable bsaver(ostate, GL_BLEND);
vtkOpenGLState::ScopedglEnableDisable dsaver(ostate, GL_DEPTH_TEST);
if (this->DelegatePass == nullptr)
{
vtkWarningMacro("no delegate in vtkToneMappingPass.");
return;
}
// create FBO and texture
int x, y, w, h;
r->GetTiledSizeAndOrigin(&w, &h, &x, &y);
if (this->ColorTexture == nullptr)
{
this->ColorTexture = vtkTextureObject::New();
this->ColorTexture->SetContext(renWin);
this->ColorTexture->SetMinificationFilter(vtkTextureObject::Linear);
this->ColorTexture->SetMagnificationFilter(vtkTextureObject::Linear);
this->ColorTexture->Allocate2D(w, h, 4, VTK_FLOAT);
}
this->ColorTexture->Resize(w, h);
if (this->FrameBufferObject == nullptr)
{
this->FrameBufferObject = vtkOpenGLFramebufferObject::New();
this->FrameBufferObject->SetContext(renWin);
}
renWin->GetState()->PushFramebufferBindings();
this->RenderDelegate(s, w, h, w, h, this->FrameBufferObject, this->ColorTexture);
renWin->GetState()->PopFramebufferBindings();
if (this->QuadHelper &&
static_cast<unsigned int>(this->ToneMappingType) != this->QuadHelper->ShaderChangeValue)
{
delete this->QuadHelper;
this->QuadHelper = nullptr;
}
if (!this->QuadHelper)
{
std::string FSSource = vtkOpenGLRenderUtilities::GetFullScreenQuadFragmentShaderTemplate();
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Decl",
"uniform sampler2D source;\n"
"//VTK::FSQ::Decl");
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"vec4 pixel = texture2D(source, texCoord);\n"
" float Y = 0.2126 * pixel.r + 0.7152 * pixel.g + 0.0722 * pixel.b;\n"
" //VTK::FSQ::Impl");
switch (this->ToneMappingType)
{
case Clamp:
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"float scale = min(Y, 1.0) / Y;\n"
" //VTK::FSQ::Impl");
break;
case Reinhard:
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"float scale = 1.0 / (Y + 1.0);\n"
" //VTK::FSQ::Impl");
break;
case Exponential:
vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Decl", "uniform float exposure;\n");
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"float scale = (1.0 - exp(-Y*exposure)) / Y;\n"
" //VTK::FSQ::Impl");
break;
}
vtkShaderProgram::Substitute(FSSource,
"//VTK::FSQ::Impl",
"gl_FragData[0] = vec4(pixel.rgb * scale, pixel.a);");
this->QuadHelper = new vtkOpenGLQuadHelper(renWin,
vtkOpenGLRenderUtilities::GetFullScreenQuadVertexShader().c_str(),
FSSource.c_str(),
"");
this->QuadHelper->ShaderChangeValue = this->ToneMappingType;
}
else
{
renWin->GetShaderCache()->ReadyShaderProgram(this->QuadHelper->Program);
}
if (!this->QuadHelper->Program || !this->QuadHelper->Program->GetCompiled())
{
vtkErrorMacro("Couldn't build the shader program.");
return;
}
this->ColorTexture->Activate();
this->QuadHelper->Program->SetUniformi("source", this->ColorTexture->GetTextureUnit());
if (this->ToneMappingType == Exponential)
{
this->QuadHelper->Program->SetUniformf("exposure", this->Exposure);
}
ostate->vtkglDisable(GL_BLEND);
ostate->vtkglDisable(GL_DEPTH_TEST);
ostate->vtkglViewport(x, y, w, h);
ostate->vtkglScissor(x, y, w, h);
this->QuadHelper->Render();
this->ColorTexture->Deactivate();
vtkOpenGLCheckErrorMacro("failed after Render");
}
// ----------------------------------------------------------------------------
void vtkToneMappingPass::ReleaseGraphicsResources(vtkWindow* w)
{
this->Superclass::ReleaseGraphicsResources(w);
if (this->QuadHelper)
{
delete this->QuadHelper;
this->QuadHelper = nullptr;
}
if (this->FrameBufferObject)
{
this->FrameBufferObject->Delete();
this->FrameBufferObject = nullptr;
}
if (this->ColorTexture)
{
this->ColorTexture->Delete();
this->ColorTexture = nullptr;
}
}
| 29.127193 | 96 | 0.630778 | fluentgcc |
c00c3d39850e3716f921bc54dd0b9ab7d3e5b388 | 3,179 | cc | C++ | trng/yarn4.cc | sthagen/rabauke-trng4 | 5ef09d7e4ac149ad4e1c0a3817e5dace7eb12d55 | [
"BSD-3-Clause"
] | null | null | null | trng/yarn4.cc | sthagen/rabauke-trng4 | 5ef09d7e4ac149ad4e1c0a3817e5dace7eb12d55 | [
"BSD-3-Clause"
] | null | null | null | trng/yarn4.cc | sthagen/rabauke-trng4 | 5ef09d7e4ac149ad4e1c0a3817e5dace7eb12d55 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2000-2022, Heiko Bauke
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of the copyright 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 HOLDERS 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 "yarn4.hpp"
namespace trng {
// Uniform random number generator concept
// Parameter and status classes
const yarn4::parameter_type yarn4::LEcuyer1 =
parameter_type(2001982722, 1412284257, 1155380217, 1668339922);
const yarn4::parameter_type yarn4::LEcuyer2 = parameter_type(64886, 0, 0, 64322);
// Random number engine concept
yarn4::yarn4(yarn4::parameter_type P) : P{P} {}
yarn4::yarn4(unsigned long s, yarn4::parameter_type P) : P{P} { seed(s); }
void yarn4::seed() { (*this) = yarn4(); }
void yarn4::seed(unsigned long s) {
int64_t t(s);
t %= modulus;
if (t < 0)
t += modulus;
S.r[0] = static_cast<result_type>(t);
S.r[1] = 1;
S.r[2] = 1;
S.r[3] = 1;
}
void yarn4::seed(yarn4::result_type s1, yarn4::result_type s2, yarn4::result_type s3,
yarn4::result_type s4) {
S.r[0] = s1 % modulus;
if (S.r[0] < 0)
S.r[0] += modulus;
S.r[1] = s2 % modulus;
if (S.r[1] < 0)
S.r[1] += modulus;
S.r[2] = s3 % modulus;
if (S.r[2] < 0)
S.r[2] += modulus;
S.r[3] = s4 % modulus;
if (S.r[3] < 0)
S.r[3] += modulus;
}
// Equality comparable concept
bool operator==(const yarn4 &R1, const yarn4 &R2) { return R1.P == R2.P and R1.S == R2.S; }
bool operator!=(const yarn4 &R1, const yarn4 &R2) { return not(R1 == R2); }
// other useful methods
const char *const yarn4::name_str = "yarn4";
const char *yarn4::name() { return name_str; }
const int_math::power<yarn4::modulus, yarn4::gen> yarn4::g;
} // namespace trng
| 34.934066 | 93 | 0.674426 | sthagen |
c00c44b3e79aee6709158d4e5a40ec54b0ace1fc | 401 | hh | C++ | PacDisplay/PacDispCyl.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDisplay/PacDispCyl.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | PacDisplay/PacDispCyl.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | #ifndef PacDispCyl_HH
#define PacDispCyl_HH
#include <stdio.h>
#include <Rtypes.h>
#define STRINGSIZE 100
struct PacDispCyl {
virtual ~PacDispCyl() {;}
Double_t radius,thickness,lowZ,hiZ;
Int_t imat;
PacDispCyl():radius(-1.0),thickness(-1.0),lowZ(-1.0),hiZ(1.0){}
static const char* rootnames() {
return "radius/D:thick/D:lowZ/D:hiZ/D:imat/I";
}
ClassDef(PacDispCyl,1)
};
#endif
| 19.095238 | 65 | 0.690773 | brownd1978 |
84fed91bc7e65bdaacb76e5e3d29b1e08aa706d0 | 3,592 | cpp | C++ | GitCommit.cpp | simoc/wyag | e94edb6e9ef2aa650d88b59c428a667ef7fe3d59 | [
"MIT"
] | null | null | null | GitCommit.cpp | simoc/wyag | e94edb6e9ef2aa650d88b59c428a667ef7fe3d59 | [
"MIT"
] | null | null | null | GitCommit.cpp | simoc/wyag | e94edb6e9ef2aa650d88b59c428a667ef7fe3d59 | [
"MIT"
] | null | null | null | #include <algorithm>
#include "GitCommit.h"
GitCommit::GitCommit(GitRepository *repo) :
GitObject(repo, "commit")
{
}
GitCommit::GitCommit(GitRepository *repo, const std::string &fmt) :
GitObject(repo, fmt)
{
}
std::vector<unsigned char>
GitCommit::serialize()
{
return kvlm_serialize();
}
void
GitCommit::deserialize(const std::vector<unsigned char> &data)
{
m_dct.clear();
kvlm_parse(data, 0, m_dct);
}
std::vector<std::string>
GitCommit::get_value(const std::string &key)
{
auto it = m_dct.find(key);
if (it == m_dct.end())
return std::vector<std::string>();
return it->second;
}
std::string
GitCommit::replace_all(const std::string &s,
const std::string &before, const std::string &after)
{
std::string s2 = s;
size_t idx = s2.find(before);
while (idx != std::string::npos)
{
s2.replace(idx, before.size(), after);
idx = s2.find(before, idx + after.size());
}
return s2;
}
void
GitCommit::kvlm_parse(const std::vector<unsigned char> &raw, size_t start,
std::map<std::string, std::vector<std::string> > &dct)
{
// We search for the next space and the next newline.
int spc = -1;
int nl = -1;
const char space = ' ';
const char newline = '\n';
auto it1 = std::find(raw.begin() + start, raw.end(), space);
if (it1 != raw.end())
{
spc = it1 - raw.begin();
}
auto it2 = std::find(raw.begin() + start, raw.end(), newline);
if (it2 != raw.end())
{
nl = it2 - raw.begin();
}
// If space appears before newline, we have a keyword.
// Base case
// =========
// If newline appears first (or there's no space at all, in which
// case find returns -1), we assume a blank line. A blank line
// means the remainder of the data is the message.
if ((spc < 0) || (nl < spc))
{
std::string value;
value.append(raw.begin() + start + 1, raw.end());
std::vector values{value};
dct.insert({std::string(), values});
return;
}
// Recursive case
// ==============
// we read a key-value pair and recurse for the next.
std::string key;
key.append(raw.begin() + start, raw.begin() + spc);
// Find the end of the value. Continuation lines begin with a
// space, so we loop until we find a '\n' not followed by a space.
size_t ending = start;
while (true)
{
auto it3 = std::find(raw.begin() + ending + 1,
raw.end(), newline);
if (it3 == raw.end())
break;
ending = it3 - raw.begin();
if (*(it3 + 1) != space)
{
break;
}
}
// Grab the value
// Also, drop the leading space on continuation lines
std::string value;
value.append(raw.begin() + spc + 1, raw.begin() + ending);
value = replace_all(value, "\n ", "\n");
// Don't overwrite existing data contents
auto it4 = dct.find(key);
if (it4 != dct.end())
{
it4->second.push_back(value);
}
else
{
std::vector values{value};
dct.insert({key, values});
}
kvlm_parse(raw, ending + 1, dct);
}
std::vector<unsigned char>
GitCommit::kvlm_serialize()
{
std::vector<unsigned char> ret;
std::vector<std::string> message;
for (auto it = m_dct.begin(); it != m_dct.end(); it++)
{
std::string key = it->first;
if (key.empty())
{
// Skip the message itself
message = it->second;
continue;
}
std::vector<std::string> val = it->second;
for (const std::string &v : val)
{
for (const char &c : key)
{
ret.push_back(c);
}
ret.push_back(' ');
std::string v2 = replace_all(v, "\n", "\n ");
for (const char &c : v2)
{
ret.push_back(c);
}
}
}
// Append message
ret.push_back('\n');
for (const std::string &v : message)
{
for (const char &c : v)
{
ret.push_back(c);
}
}
return ret;
}
| 20.525714 | 74 | 0.618875 | simoc |
84feeddd9fc64f33ff581e2c95eadc893772466f | 6,128 | cpp | C++ | src/Extensions/Sampler/SamplerPanel.cpp | Freaxed/xrs-haiku | 74617bc5740fc15b165686a14894d4382096fad3 | [
"BSD-3-Clause"
] | 1 | 2022-03-25T15:40:45.000Z | 2022-03-25T15:40:45.000Z | src/Extensions/Sampler/SamplerPanel.cpp | Freaxed/xrs-haiku | 74617bc5740fc15b165686a14894d4382096fad3 | [
"BSD-3-Clause"
] | null | null | null | src/Extensions/Sampler/SamplerPanel.cpp | Freaxed/xrs-haiku | 74617bc5740fc15b165686a14894d4382096fad3 | [
"BSD-3-Clause"
] | null | null | null | /*
*
* Copyright 2006-2022, Andrea Anzani.
* Distributed under the terms of the MIT License.
*
* Authors:
* Andrea Anzani <andrea.anzani@gmail.com>
*/
#include "SamplerPanel.h"
#include "Sample.h"
#include "SamplerTrackBoost.h"
#include "GlobalDef.h"
#include "GfxMsg.h"
#include "SamplerTrack.h"
#include "Xed_Utils.h"
#include "sampler_locale.h"
#include "XDigit.h"
#include "XHost.h"
#define REMOVE 'remv'
#define REMOVEALL 'rema'
#define LOADEXT 'loae'
#define REL_MSG 'note'
#define REV_ON 'reo'
#define PIT_ON 'pio'
#define BOOST_ON 'boo'
#define MOD 'mod'
#define LOOP_ON 'loop'
SamplerPanel::SamplerPanel(SamplerTrackBoost* sb):
PlugPanel(), sampTrack(NULL), booster(sb)
{
BBox *sam_box= new BBox(BRect(10,150+17,171,210+17) ,"toolbar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP,
B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP, B_FANCY_BORDER);
BBox *sampler= new BBox(BRect(8,18,172,50) ,"toolbar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP,
B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP, B_FANCY_BORDER);
menu=new BMenu(" ");
menu->AddItem(booster->getMenu());
menu->AddItem(new BMenuItem(T_SAMPLER_LOAD,new BMessage(LOADEXT)));
menu->AddItem(new BMenuItem(T_SAMPLER_REMOVE,new BMessage(REMOVE)));
menu->AddItem(new BMenuItem(T_SAMPLER_REMOVE_ALL,new BMessage(REMOVEALL)));
BRect r(sampler->Bounds());
r.InsetBy(4,4);
field=new BMenuField(r,""," ",menu);
pit_box= new BBox(BRect(8,70-13,172,102-13), "");
r=(pit_box->Bounds());
r.InsetBy(4,4);
r.right-=50;
r.top+=2;
pit_box->AddChild(pit_ck=new BCheckBox(r,"",T_SAMPLER_STRECH,new BMessage(PIT_ON)));
pit_ck->SetValue(0);
pit_ck->SetFontSize(12);
pit_box->AddChild(shift=new XDigit(BRect(120,5,120+36,5+21), VID_EMPTY, "sampler_shift_xdigit", new BMessage(MOD),1,32));
r=(pit_box->Frame());
r.OffsetBy(0,38);
AddChild(pit_box);
pit_box= new BBox(r, "2");
r=(pit_box->Bounds());
r.InsetBy(4,4);
r.right-=50;
r.top+=2;
pit_box->AddChild(boost_ck=new BCheckBox(r,"",T_SAMPLER_BOOST,new BMessage(BOOST_ON)));
boost_ck->SetValue(0);
boost_ck->SetFontSize(12);
pit_box->AddChild(depth=new XDigit(BRect(120,5,120+36,5+21), VID_EMPTY, "sampler_boost", new BMessage(REL_MSG),1,4));
r=(pit_box->Frame());
r.OffsetBy(0,38);
AddChild(pit_box);
pit_box= new BBox(r, "3");
r=(pit_box->Bounds());
r.InsetBy(4,4);
r.right -= 75;
r.top += 2;
pit_box->AddChild(rev = new BCheckBox(r,"rev_check",T_SAMPLER_REVERSE,new BMessage(TRACK_REV)));
rev->SetValue(0);
rev->SetFontSize(12);
rev->ResizeToPreferred();
r.OffsetBy(r.Width(), 0);
pit_box->AddChild(loop_ck = new BCheckBox(r,"loop_check","Loop", new BMessage(LOOP_ON)));
loop_ck->SetValue(0);
loop_ck->SetFontSize(12);
loop_ck->ResizeToPreferred();
AddChild(pit_box);
sw=new SampleView(BRect(1,1,159,58), XUtils::GetBitmap(18));
sam_box->AddChild(sw);
sampler->AddChild(field);
AddChild(sampler);
AddChild(sam_box);
my_sample=NULL;
rev->SetValue(false);
menu->Superitem()->SetLabel(T_SAMPLER_NOSELECTED);
}
void
SamplerPanel::ResetToTrack(Track* trk)
{
//qui magari un bel check dell'ID ??
PlugPanel::ResetToTrack(trk);
SetTrack((SamplerTrack*)trk);
}
void
SamplerPanel::AttachedToWindow()
{
PlugPanel::AttachedToWindow();
depth->SetTarget(this);
shift->SetTarget((BView*)this);
pit_ck->SetTarget(this);
rev->SetTarget(this);
menu->SetTargetForItems(this);
boost_ck->SetTarget(this);
loop_ck->SetTarget(this);
field->SetDivider(0);
}
void
SamplerPanel::SetTrack(SamplerTrack *tr)
{
if(!Window()) return;
sampTrack = tr;
if(Window()->Lock()){
if(tr == NULL || tr->getSample() == NULL)
{
sw->Init(NULL, false, false);
shift->UpdateValue(16, true);
pit_ck->SetValue(false);
boost_ck->SetValue(false);
loop_ck->SetValue(false);
menu->Superitem()->SetLabel(T_SAMPLER_NOSELECTED);
depth->UpdateValue(1, true);
}
else
{
SetTitle(tr->getName());
my_sample=tr->getSample();
sw->Init(my_sample, tr->isReversed(), 1.0f);
menu->Superitem()->SetLabel(my_sample->GetName());
shift->UpdateValue(tr->getResample(), true);
pit_ck->SetValue(tr->isResampleEnable());
boost_ck->SetValue(tr->isBoostEnable());
loop_ck->SetValue(tr->IsLoopEnable());
rev->SetValue(tr->isReversed());
depth->UpdateValue((int32)tr->amp, true);
sw->SetBoost(tr->amp);
}
Window()->Unlock();
}
}
void
SamplerPanel::MessageReceived(BMessage* message)
{
switch(message->what)
{
case LOOP_ON:
if(sampTrack == NULL) return;
sampTrack->SetLoopEnable((bool)loop_ck->Value());
break;
case BOOST_ON:
if(sampTrack==NULL) return;
sampTrack->setBoostEnable((bool)boost_ck->Value());
if(!boost_ck->Value())
{
sampTrack->amp=1.0;
sw->SetBoost(sampTrack->amp);
return;
}
//else continue (without break!)
case REL_MSG:
if(sampTrack==NULL) return;
if(!sampTrack->isBoostEnable()) return;
sampTrack->amp=(float)depth->GetValue();
sw->SetBoost(sampTrack->amp);
break;
case TRACK_SAMP_EXT:
booster->ChangeSample(message->FindInt16("sample"));//ok
break;
case MOD:
if(sampTrack==NULL) return;
XHost::Get()->SendMessage(X_LockSem,NULL);
sampTrack->setResample(shift->GetValue());
XHost::Get()->SendMessage(X_UnLockSem,NULL);
break;
case PIT_ON:
if(sampTrack==NULL) return;
XHost::Get()->SendMessage(X_LockSem,NULL);
sampTrack->setResampleEnable((bool)pit_ck->Value());
XHost::Get()->SendMessage(X_UnLockSem,NULL);
break;
case TRACK_REV:
if(sampTrack==NULL) return;
sampTrack->setReversed(rev->Value());
sw->SetReversed(rev->Value());
break;
case LOADEXT:
booster->LoadSample();
break;
case REMOVEALL:
booster->RemoveAll();
break;
case REMOVE:
booster->RemoveSample(((SamplerTrack*)sampTrack)->getSample());
break;
case B_REFS_RECEIVED: //ok
{
entry_ref ref;
if(message->FindRef("refs",&ref)==B_OK)
{
booster->RefReceived(ref,sampTrack);
booster->RefreshSelected();
}
}
break;
default:
PlugPanel::MessageReceived(message);
break;
}
}
| 23.212121 | 122 | 0.678362 | Freaxed |
1701a6d200d0577106576d73da7ab1b6306ca2fa | 700 | cpp | C++ | src/urls/resolver.cpp | YuriyLisovskiy/xalwart | ee50f0ff991f76192291e9f8f16928ab1428632e | [
"Apache-2.0"
] | null | null | null | src/urls/resolver.cpp | YuriyLisovskiy/xalwart | ee50f0ff991f76192291e9f8f16928ab1428632e | [
"Apache-2.0"
] | null | null | null | src/urls/resolver.cpp | YuriyLisovskiy/xalwart | ee50f0ff991f76192291e9f8f16928ab1428632e | [
"Apache-2.0"
] | null | null | null | /**
* urls/resolver.cpp
*
* Copyright (c) 2019-2021 Yuriy Lisovskiy
*/
#include "./resolver.h"
__URLS_BEGIN__
std::function<std::unique_ptr<http::IResponse>(http::IRequest*, conf::Settings*)> resolve(
const std::string& path, const std::vector<std::shared_ptr<IPattern>>& urlpatterns
)
{
std::function<std::unique_ptr<http::IResponse>(http::IRequest*, conf::Settings*)> fn = nullptr;
for (const auto& url_pattern : urlpatterns)
{
if (url_pattern->match(path))
{
fn = [url_pattern](
http::IRequest* request, conf::Settings* settings
) -> std::unique_ptr<http::IResponse> {
return url_pattern->apply(request, settings);
};
break;
}
}
return fn;
}
__URLS_END__
| 20.588235 | 96 | 0.678571 | YuriyLisovskiy |
1701ffe8d4f5942086414b702aa67bf7d6bd5d51 | 6,580 | cpp | C++ | srrg2_solver/tests/test_se2_icp.cpp | daoran/srrg2_solver | 244fd8f260dfc62b145c9a4e6494775dfe5a8caa | [
"BSD-3-Clause"
] | 124 | 2020-02-26T14:40:45.000Z | 2022-03-29T11:11:48.000Z | srrg2_solver/tests/test_se2_icp.cpp | daoran/srrg2_solver | 244fd8f260dfc62b145c9a4e6494775dfe5a8caa | [
"BSD-3-Clause"
] | null | null | null | srrg2_solver/tests/test_se2_icp.cpp | daoran/srrg2_solver | 244fd8f260dfc62b145c9a4e6494775dfe5a8caa | [
"BSD-3-Clause"
] | 16 | 2020-03-03T00:57:43.000Z | 2022-03-15T00:50:12.000Z | #include <gtest/gtest.h>
#include <srrg_system_utils/parse_command_line.h>
#include <srrg_system_utils/shell_colors.h>
#include "srrg_solver/solver_core/instances.h"
#include "srrg_solver/solver_core/internals/linear_solvers/instances.h"
#include "srrg_solver/solver_core/solver.h"
#include "srrg_solver/variables_and_factors/types_2d/instances.h"
const std::string exe_name = "test_se2_icp";
#define LOG std::cerr << exe_name + "|"
using namespace srrg2_core;
using namespace srrg2_solver;
const size_t n_meas = 1000;
const size_t n_iterations = 10;
int main(int argc, char** argv) {
variables_and_factors_2d_registerTypes();
solver_registerTypes();
linear_solver_registerTypes();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
TEST(DUMMY_DATA, SE2Point2PointErrorFactor) {
using VariableType = VariableSE2Right;
using VariablePtrType = std::shared_ptr<VariableType>;
using FactorType = SE2Point2PointErrorFactorCorrespondenceDriven;
using FactorPtrType = std::shared_ptr<FactorType>;
const Vector3f t = 10 * Vector3f::Random();
Isometry2f T = geometry2d::v2t(t);
const Isometry2f inv_T = T.inverse();
// declare a multi_solver
Solver solver;
// declare a graph,
FactorGraphPtr graph(new FactorGraph);
// create a variable, set an id and add it to the graph
VariablePtrType pose(new VariableType);
pose->setGraphId(0);
graph->addVariable(pose);
graph->bindFactors();
solver.setGraph(graph);
// ia create two cloud that we want to align, and a vector of correspondences
Point2fVectorCloud fixed_cloud;
Point2fVectorCloud moving_cloud;
CorrespondenceVector correspondences;
fixed_cloud.reserve(n_meas);
moving_cloud.reserve(n_meas);
correspondences.reserve(n_meas);
for (size_t i = 0; i < n_meas; ++i) {
// ia create dummy measurements
Point2f fixed_point, moving_point;
fixed_point.coordinates().setRandom();
moving_point.coordinates() = inv_T * fixed_point.coordinates();
fixed_cloud.emplace_back(fixed_point);
moving_cloud.emplace_back(moving_point);
correspondences.emplace_back(Correspondence(i, i));
}
// create an ICP factor, correspondence driven, set the var index, and add it to the graph
FactorPtrType factor(new FactorType);
factor->setVariableId(0, 0);
graph->addFactor(factor);
// setup the factor;
factor->setFixed(fixed_cloud);
factor->setMoving(moving_cloud);
factor->setCorrespondences(correspondences);
factor->setInformationMatrix(Matrix2f::Identity());
solver.param_max_iterations.pushBack(n_iterations);
solver.param_termination_criteria.setValue(nullptr);
ASSERT_EQ(graph->factors().size(), static_cast<size_t>(1));
pose->setEstimate(Isometry2f::Identity());
solver.compute();
const auto& stats = solver.iterationStats();
const auto& final_chi2 = stats.back().chi_inliers;
// ia assert performed iterations are the effectively n_iterations
ASSERT_EQ(stats.size(), n_iterations);
// ia assert chi2 is good
ASSERT_LT(final_chi2, 1e-6);
// ia assert that relative error is good
const auto& estimated_T = pose->estimate();
const Isometry2f diff_T = estimated_T.inverse() * T;
const Vector3f diff_vector = geometry2d::t2v(diff_T);
LOG << stats << std::endl;
ASSERT_LT(diff_vector.x(), 1e-5);
ASSERT_LT(diff_vector.y(), 1e-5);
ASSERT_LT(diff_vector.z(), 1e-5);
}
TEST(DUMMY_DATA, SE2Point2PointWithSensorErrorFactor) {
using VariableType = VariableSE2Right;
using VariablePtrType = std::shared_ptr<VariableType>;
using FactorType = SE2Point2PointWithSensorErrorFactorCorrespondenceDriven;
using FactorPtrType = std::shared_ptr<FactorType>;
const Vector3f t = 10 * Vector3f::Random();
Vector3f sensor_in_robot_v = Vector3f(0.1, 0.2, 0.5);
Isometry2f sensor_in_robot = geometry2d::v2t(sensor_in_robot_v);
Isometry2f ground_truth_T = geometry2d::v2t(t);
Isometry2f T = ground_truth_T * sensor_in_robot;
const Isometry2f inv_T = T.inverse();
// declare a multi_solver
Solver solver;
// declare a graph,
FactorGraphPtr graph(new FactorGraph);
// create a variable, set an id and add it to the graph
VariablePtrType pose(new VariableType);
pose->setGraphId(0);
pose->setEstimate(Isometry2f::Identity());
graph->addVariable(pose);
graph->bindFactors();
solver.setGraph(graph);
// ia create two cloud that we want to align, and a vector of correspondences
Point2fVectorCloud fixed_cloud;
Point2fVectorCloud moving_cloud;
CorrespondenceVector correspondences;
fixed_cloud.reserve(n_meas);
moving_cloud.reserve(n_meas);
correspondences.reserve(n_meas);
for (size_t i = 0; i < n_meas; ++i) {
// ia create dummy measurements
Point2f fixed_point, moving_point;
moving_point.coordinates().setRandom();
fixed_point.coordinates() = inv_T * moving_point.coordinates();
fixed_cloud.emplace_back(fixed_point);
moving_cloud.emplace_back(moving_point);
correspondences.emplace_back(Correspondence(i, i));
}
// create an ICP factor, correspondence driven, set the var index, and add it to the graph
FactorPtrType factor(new FactorType);
factor->setVariableId(0, 0);
graph->addFactor(factor);
// setup the factor;
factor->setFixed(fixed_cloud);
factor->setMoving(moving_cloud);
factor->setCorrespondences(correspondences);
factor->setInformationMatrix(Matrix2f::Identity());
factor->setSensorInRobot(sensor_in_robot);
solver.param_max_iterations.pushBack(n_iterations);
solver.param_termination_criteria.setValue(nullptr);
ASSERT_EQ(graph->factors().size(), static_cast<size_t>(1));
solver.compute();
const auto& stats = solver.iterationStats();
const auto& final_chi2 = stats.back().chi_inliers;
// ia assert performed iterations are the effectively n_iterations
ASSERT_EQ(stats.size(), n_iterations);
// ia assert chi2 is good
ASSERT_LT(final_chi2, 1e-6);
// ia assert that relative error is good
const auto& estimated_T = pose->estimate();
const Isometry2f diff_T = estimated_T * ground_truth_T;
const Vector3f diff_vector = geometry2d::t2v(diff_T);
LOG << stats << std::endl;
LOG << "sensor T : " << geometry2d::t2v(T).transpose() << std::endl;
LOG << "estim T : " << geometry2d::t2v(estimated_T.inverse()).transpose() << std::endl;
LOG << "GT : " << geometry2d::t2v(ground_truth_T).transpose() << std::endl;
ASSERT_LT(diff_vector.x(), 1e-5);
ASSERT_LT(diff_vector.y(), 1e-5);
ASSERT_LT(diff_vector.z(), 1e-5);
}
| 35.187166 | 92 | 0.730395 | daoran |
17043eba8eec97e5fcf6e4937bcf362c0a06dea8 | 26,955 | cc | C++ | Geometry/TrackerCommonData/plugins/DDTECModuleAlgo.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | Geometry/TrackerCommonData/plugins/DDTECModuleAlgo.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | Geometry/TrackerCommonData/plugins/DDTECModuleAlgo.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | ///////////////////////////////////////////////////////////////////////////////
// File: DDTECModuleAlgo .cc
// Description: Creation of a TEC Test
///////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <string>
#include <utility>
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DetectorDescription/Core/interface/DDLogicalPart.h"
#include "DetectorDescription/Core/interface/DDSolid.h"
#include "DetectorDescription/Core/interface/DDMaterial.h"
#include "DetectorDescription/Core/interface/DDCurrentNamespace.h"
#include "DetectorDescription/Core/interface/DDSplit.h"
#include "Geometry/TrackerCommonData/plugins/DDTECModuleAlgo.h"
#include "CLHEP/Units/GlobalPhysicalConstants.h"
#include "CLHEP/Units/GlobalSystemOfUnits.h"
DDTECModuleAlgo::DDTECModuleAlgo() {
LogDebug("TECGeom") << "DDTECModuleAlgo info: Creating an instance";
}
DDTECModuleAlgo::~DDTECModuleAlgo() {}
void DDTECModuleAlgo::initialize(const DDNumericArguments & nArgs,
const DDVectorArguments & vArgs,
const DDMapArguments & ,
const DDStringArguments & sArgs,
const DDStringVectorArguments & vsArgs) {
idNameSpace = DDCurrentNamespace::ns();
genMat = sArgs["GeneralMaterial"];
DDName parentName = parent().name();
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Parent " << parentName
<< " NameSpace " << idNameSpace << " General Material "
<< genMat;
ringNo = (int)nArgs["RingNo"];
moduleThick = nArgs["ModuleThick"];
detTilt = nArgs["DetTilt"];
fullHeight = nArgs["FullHeight"];
dlTop = nArgs["DlTop"];
dlBottom = nArgs["DlBottom"];
dlHybrid = nArgs["DlHybrid"];
rPos = nArgs["RPos"];
standardRot = sArgs["StandardRotation"];
isRing6 = (ringNo == 6);
LogDebug("TECGeom") << "DDTECModuleAlgo debug: ModuleThick " << moduleThick
<< " Detector Tilt " << detTilt/CLHEP::deg << " Height "
<< fullHeight << " dl(Top) " << dlTop << " dl(Bottom) "
<< dlBottom << " dl(Hybrid) " << dlHybrid
<< " rPos " << rPos << " standrad rotation "
<< standardRot;
frameWidth = nArgs["FrameWidth"];
frameThick = nArgs["FrameThick"];
frameOver = nArgs["FrameOver"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Frame Width " << frameWidth
<< " Thickness " << frameThick << " Overlap "
<< frameOver;
topFrameMat = sArgs["TopFrameMaterial"];
topFrameHeight = nArgs["TopFrameHeight"];
topFrameTopWidth= nArgs["TopFrameTopWidth"];
topFrameBotWidth= nArgs["TopFrameBotWidth"];
topFrameThick = nArgs["TopFrameThick"];
topFrameZ = nArgs["TopFrameZ"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Top Frame Material "
<< topFrameMat << " Height " << topFrameHeight
<< " Top Width " << topFrameTopWidth << " Bottom Width "
<< topFrameTopWidth
<< " Thickness " << topFrameThick <<" positioned at"
<< topFrameZ;
double resizeH =0.96;
sideFrameMat = sArgs["SideFrameMaterial"];
sideFrameThick = nArgs["SideFrameThick"];
sideFrameLWidth = nArgs["SideFrameLWidth"];
sideFrameLHeight = resizeH*nArgs["SideFrameLHeight"];
sideFrameLtheta = nArgs["SideFrameLtheta"];
sideFrameRWidth = nArgs["SideFrameRWidth"];
sideFrameRHeight = resizeH*nArgs["SideFrameRHeight"];
sideFrameRtheta = nArgs["SideFrameRtheta"];
siFrSuppBoxWidth = vArgs["SiFrSuppBoxWidth"];
siFrSuppBoxHeight = vArgs["SiFrSuppBoxHeight"];
siFrSuppBoxYPos = vArgs["SiFrSuppBoxYPos"];
siFrSuppBoxThick = nArgs["SiFrSuppBoxThick"];
siFrSuppBoxMat = sArgs["SiFrSuppBoxMaterial"];
sideFrameZ = nArgs["SideFrameZ"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug : Side Frame Material "
<< sideFrameMat << " Thickness " << sideFrameThick
<< " left Leg's Width: " << sideFrameLWidth
<< " left Leg's Height: " << sideFrameLHeight
<< " left Leg's tilt(theta): " << sideFrameLtheta
<< " right Leg's Width: " << sideFrameRWidth
<< " right Leg's Height: " << sideFrameRHeight
<< " right Leg's tilt(theta): " << sideFrameRtheta
<< "Supplies Box's Material: " << siFrSuppBoxMat
<< " positioned at" << sideFrameZ;
for (int i= 0; i < (int)(siFrSuppBoxWidth.size());i++){
LogDebug("TECGeom") << " Supplies Box" << i << "'s Width: "
<< siFrSuppBoxWidth[i] << " Supplies Box" << i
<<"'s Height: " << siFrSuppBoxHeight[i]
<< " Supplies Box" << i << "'s y Position: "
<< siFrSuppBoxYPos[i];
}
waferMat = sArgs["WaferMaterial"];
sideWidthTop = nArgs["SideWidthTop"];
sideWidthBottom= nArgs["SideWidthBottom"];
waferRot = sArgs["WaferRotation"];
waferPosition = nArgs["WaferPosition"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Wafer Material "
<< waferMat << " Side Width Top" << sideWidthTop
<< " Side Width Bottom" << sideWidthBottom
<< " and positioned at "<<waferPosition
<< " positioned with rotation" << " matrix:"
<< waferRot;
activeMat = sArgs["ActiveMaterial"];
activeHeight = nArgs["ActiveHeight"];
waferThick = nArgs["WaferThick"];
activeRot = sArgs["ActiveRotation"];
activeZ = nArgs["ActiveZ"];
backplaneThick = nArgs["BackPlaneThick"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Active Material "
<< activeMat << " Height " << activeHeight
<< " rotated by " << activeRot
<< " translated by (0,0," << -0.5 * backplaneThick << ")"
<< " Thickness/Z"
<< waferThick-backplaneThick << "/" << activeZ;
hybridMat = sArgs["HybridMaterial"];
hybridHeight = nArgs["HybridHeight"];
hybridWidth = nArgs["HybridWidth"];
hybridThick = nArgs["HybridThick"];
hybridZ = nArgs["HybridZ"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Hybrid Material "
<< hybridMat << " Height " << hybridHeight
<< " Width " << hybridWidth << " Thickness "
<< hybridThick << " Z" << hybridZ;
pitchMat = sArgs["PitchMaterial"];
pitchHeight = nArgs["PitchHeight"];
pitchThick = nArgs["PitchThick"];
pitchWidth = nArgs["PitchWidth"];
pitchZ = nArgs["PitchZ"];
pitchRot = sArgs["PitchRotation"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Pitch Adapter Material "
<< pitchMat << " Height " << pitchHeight
<< " Thickness " << pitchThick << " position with "
<< " rotation " << pitchRot << " at Z" << pitchZ;
bridgeMat = sArgs["BridgeMaterial"];
bridgeWidth = nArgs["BridgeWidth"];
bridgeThick = nArgs["BridgeThick"];
bridgeHeight = nArgs["BridgeHeight"];
bridgeSep = nArgs["BridgeSeparation"];
LogDebug("TECGeom") << "DDTECModuleAlgo debug: Bridge Material "
<< bridgeMat << " Width " << bridgeWidth
<< " Thickness " << bridgeThick << " Height "
<< bridgeHeight << " Separation "<< bridgeSep;
siReenforceWidth = vArgs["SiReenforcementWidth"];
siReenforceHeight = vArgs["SiReenforcementHeight"];
siReenforceYPos = vArgs["SiReenforcementPosY"];
siReenforceThick = nArgs["SiReenforcementThick"];
siReenforceMat = sArgs["SiReenforcementMaterial"];
LogDebug("TECGeom") << "FALTBOOT DDTECModuleAlgo debug : Si-Reenforcement Material "
<< sideFrameMat << " Thickness " << siReenforceThick;
for (int i= 0; i < (int)(siReenforceWidth.size());i++){
LogDebug("TECGeom") << " SiReenforcement" << i << "'s Width: "
<< siReenforceWidth[i] << " SiReenforcement" << i
<< "'s Height: " << siReenforceHeight[i]
<< " SiReenforcement" << i << "'s y Position: "
<<siReenforceYPos[i];
}
inactiveDy = 0;
inactivePos = 0;
if(ringNo > 3){
inactiveDy = nArgs["InactiveDy"];
inactivePos = nArgs["InactivePos"];
inactiveMat = sArgs["InactiveMaterial"];
}
noOverlapShift = nArgs["NoOverlapShift"];
//Everything that is normal/stereo specific comes here
isStereo = (int)nArgs["isStereo"] == 1;
if(!isStereo){
LogDebug("TECGeom") << "This is a normal module, in ring "<<ringNo<<"!";
} else {
LogDebug("TECGeom") << "This is a stereo module, in ring "<<ringNo<<"!";
posCorrectionPhi= nArgs["PosCorrectionPhi"];
topFrame2LHeight = nArgs["TopFrame2LHeight"];
topFrame2RHeight = nArgs["TopFrame2RHeight"];
topFrame2Width = nArgs["TopFrame2Width"];
LogDebug("TECGeom") << "Phi Position corrected by " << posCorrectionPhi << "*rad";
LogDebug("TECGeom") << "DDTECModuleAlgo debug: stereo Top Frame 2nd Part left Heigt "
<< topFrame2LHeight << " right Height " << topFrame2RHeight
<< " Width " << topFrame2Width ;
sideFrameLWidthLow = nArgs["SideFrameLWidthLow"];
sideFrameRWidthLow = nArgs["SideFrameRWidthLow"];
LogDebug("TECGeom") << " left Leg's lower Width: " << sideFrameLWidthLow
<< " right Leg's lower Width: " << sideFrameRWidthLow;
// posCorrectionR = nArgs["PosCorrectionR"];
//LogDebug("TECGeom") << "Stereo Module Position Correction with R = " << posCorrectionR;
}
}
void DDTECModuleAlgo::doPos(const DDLogicalPart& toPos, const DDLogicalPart& mother,
int copyNr, double x, double y, double z,
const std::string& rotName, DDCompactView& cpv) {
DDTranslation tran(z, x, y);
DDRotation rot;
std::string rotstr = DDSplit(rotName).first;
std::string rotns;
if (rotstr != "NULL") {
rotns = DDSplit(rotName).second;
rot = DDRotation(DDName(rotstr, rotns));
} else {
rot = DDRotation();
}
cpv.position(toPos, mother, copyNr, tran, rot);
LogDebug("TECGeom") << "DDTECModuleAlgo test: " << toPos.name()
<< " positioned in "<< mother.name()
<< " at " << tran << " with " << rot;
}
void DDTECModuleAlgo::doPos(DDLogicalPart toPos, double x, double y, double z,
std::string rotName, DDCompactView& cpv) {
int copyNr = 1;
if (isStereo) copyNr = 2;
// This has to be done so that the Mother coordinate System of a Tub resembles
// the coordinate System of a Trap or Box.
z += rPos;
if(isStereo){
// z is x , x is y
//z+= rPos*sin(posCorrectionPhi); <<- this is already corrected with the r position!
x+= rPos*sin(posCorrectionPhi);
}
if (rotName == "NULL") rotName = standardRot;
doPos(std::move(toPos),parent(),copyNr,x,y,z,rotName, cpv);
}
void DDTECModuleAlgo::execute(DDCompactView& cpv) {
LogDebug("TECGeom") << "==>> Constructing DDTECModuleAlgo...";
//declarations
double tmp;
double dxdif, dzdif;
double dxbot, dxtop; // topfr;
//positions
double xpos, ypos, zpos;
//dimensons
double bl1, bl2;
double h1;
double dx, dy, dz;
double thet;
//names
std::string idName;
std::string name;
std::string tag("Rphi");
if (isStereo) tag = "Stereo";
//usefull constants
const double topFrameEndZ = 0.5 * (-waferPosition + fullHeight) + pitchHeight + hybridHeight - topFrameHeight;
DDName parentName = parent().name();
idName = parentName.name();
LogDebug("TECGeom") << "==>> " << idName << " parent " << parentName << " namespace " << idNameSpace;
DDSolid solid;
//set global parameters
DDName matname(DDSplit(genMat).first, DDSplit(genMat).second);
DDMaterial matter(matname);
dzdif = fullHeight + topFrameHeight;
if(isStereo) dzdif += 0.5*(topFrame2LHeight+topFrame2RHeight);
dxbot = 0.5*dlBottom + frameWidth - frameOver;
dxtop = 0.5*dlHybrid + frameWidth - frameOver;
// topfr = 0.5*dlBottom * sin(detTilt);
if (isRing6) {
dxbot = dxtop;
dxtop = 0.5*dlTop + frameWidth - frameOver;
// topfr = 0.5*dlTop * sin(detTilt);
}
dxdif = dxtop - dxbot;
//Frame Sides
// left Frame
name = idName + "SideFrameLeft";
matname = DDName(DDSplit(sideFrameMat).first, DDSplit(sideFrameMat).second);
matter = DDMaterial(matname);
h1 = 0.5 * sideFrameThick;
dz = 0.5 * sideFrameLHeight;
bl1 = bl2 = 0.5 * sideFrameLWidth;
thet = sideFrameLtheta;
//for stereo modules
if(isStereo) bl1 = 0.5 * sideFrameLWidthLow;
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1, bl1,
bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", "<<thet<<", 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
DDLogicalPart sideFrameLeft(solid.ddname(), matter, solid);
//translate
xpos = - 0.5*topFrameBotWidth +bl2+ tan(fabs(thet)) * dz;
ypos = sideFrameZ;
zpos = topFrameEndZ -dz;
//flip ring 6
if (isRing6){
zpos *= -1;
xpos -= 2*tan(fabs(thet)) * dz; // because of the flip the tan(..) to be in the other direction
}
//the stereo modules are on the back of the normal ones...
if(isStereo) {
xpos = - 0.5*topFrameBotWidth + bl2*cos(detTilt) + dz*sin(fabs(thet)+detTilt)/cos(fabs(thet));
xpos = -xpos;
zpos = topFrameEndZ -topFrame2LHeight- 0.5*sin(detTilt)*(topFrameBotWidth - topFrame2Width)-dz*cos(detTilt+fabs(thet))/cos(fabs(thet))+bl2*sin(detTilt)-0.1*CLHEP::mm;
}
//position
doPos(sideFrameLeft,xpos,ypos,zpos,waferRot, cpv);
//right Frame
name = idName + "SideFrameRight";
matname = DDName(DDSplit(sideFrameMat).first, DDSplit(sideFrameMat).second);
matter = DDMaterial(matname);
h1 = 0.5 * sideFrameThick;
dz = 0.5 * sideFrameRHeight;
bl1 = bl2 = 0.5 * sideFrameRWidth;
thet = sideFrameRtheta;
if(isStereo) bl1 = 0.5 * sideFrameRWidthLow;
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1, bl1,
bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", "<<thet<<", 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
DDLogicalPart sideFrameRight(solid.ddname(), matter, solid);
//translate
xpos = 0.5*topFrameBotWidth -bl2- tan(fabs(thet)) * dz;
ypos = sideFrameZ;
zpos = topFrameEndZ -dz ;
if (isRing6){
zpos *= -1;
xpos += 2*tan(fabs(thet)) * dz; // because of the flip the tan(..) has to be in the other direction
}
if(isStereo){
xpos = 0.5*topFrameBotWidth - bl2*cos(detTilt) - dz*sin(fabs(detTilt-fabs(thet)))/cos(fabs(thet));
xpos = -xpos;
zpos = topFrameEndZ -topFrame2RHeight+ 0.5*sin(detTilt)*(topFrameBotWidth - topFrame2Width)-dz*cos(detTilt-fabs(thet))/cos(fabs(thet))-bl2*sin(detTilt)-0.1*CLHEP::mm;
}
//position it
doPos(sideFrameRight,xpos,ypos,zpos,waferRot, cpv);
//Supplies Box(es)
for (int i= 0; i < (int)(siFrSuppBoxWidth.size());i++){
name = idName + "SuppliesBox" + std::to_string(i);
matname = DDName(DDSplit(siFrSuppBoxMat).first, DDSplit(siFrSuppBoxMat).second);
matter = DDMaterial(matname);
h1 = 0.5 * siFrSuppBoxThick;
dz = 0.5 * siFrSuppBoxHeight[i];
bl1 = bl2 = 0.5 * siFrSuppBoxWidth[i];
thet = sideFrameRtheta;
if(isStereo) thet = -atan(fabs(sideFrameRWidthLow-sideFrameRWidth)/(2*sideFrameRHeight)-tan(fabs(thet)));
// ^-- this calculates the lower left angel of the tipped trapezoid, which is the SideFframe...
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet,0, h1, bl1,
bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
DDLogicalPart siFrSuppBox(solid.ddname(), matter, solid);
//translate
xpos = 0.5*topFrameBotWidth -sideFrameRWidth - bl1-siFrSuppBoxYPos[i]*tan(fabs(thet));
ypos = sideFrameZ*(0.5+(siFrSuppBoxThick/sideFrameThick)); //via * so I do not have to worry about the sign of sideFrameZ
zpos = topFrameEndZ - siFrSuppBoxYPos[i];
if (isRing6){
xpos += 2*fabs(tan(thet))* siFrSuppBoxYPos[i]; // the flipped issue again
zpos *= -1;
}
if(isStereo){
xpos = 0.5*topFrameBotWidth - (sideFrameRWidth+bl1)*cos(detTilt) -sin(fabs(detTilt-fabs(thet)))*(siFrSuppBoxYPos[i]+dz*(1/cos(thet)- cos(detTilt))+bl1*sin(detTilt));
xpos =-xpos;
zpos = topFrameEndZ - topFrame2RHeight - 0.5*sin(detTilt)*(topFrameBotWidth - topFrame2Width) - siFrSuppBoxYPos[i]-sin(detTilt)*sideFrameRWidth;
}
//position it;
doPos(siFrSuppBox,xpos,ypos,zpos,waferRot,cpv);
}
//The Hybrid
name = idName + "Hybrid";
matname = DDName(DDSplit(hybridMat).first, DDSplit(hybridMat).second);
matter = DDMaterial(matname);
dx = 0.5 * hybridWidth;
dy = 0.5 * hybridThick;
dz = 0.5 * hybridHeight;
solid = DDSolidFactory::box(DDName(name, idNameSpace), dx, dy, dz);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Box made of " << matname << " of dimensions "
<< dx << ", " << dy << ", " << dz;
DDLogicalPart hybrid(solid.ddname(), matter, solid);
ypos = hybridZ;
zpos = 0.5 * (-waferPosition + fullHeight + hybridHeight)+pitchHeight;
if (isRing6) zpos *=-1;
//position it
doPos(hybrid,0,ypos,zpos,"NULL", cpv);
// Wafer
name = idName + tag +"Wafer";
matname = DDName(DDSplit(waferMat).first, DDSplit(waferMat).second);
matter = DDMaterial(matname);
bl1 = 0.5 * dlBottom;
bl2 = 0.5 * dlTop;
h1 = 0.5 * waferThick;
dz = 0.5 * fullHeight;
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1,
bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", "
<< bl2 << ", 0";
DDLogicalPart wafer(solid.ddname(), matter, solid);
ypos = activeZ;
zpos =-0.5 * waferPosition;// former and incorrect topFrameHeight;
if (isRing6) zpos *= -1;
doPos(wafer,0,ypos,zpos,waferRot,cpv);
// Active
name = idName + tag +"Active";
matname = DDName(DDSplit(activeMat).first, DDSplit(activeMat).second);
matter = DDMaterial(matname);
bl1 -= sideWidthBottom;
bl2 -= sideWidthTop;
dz = 0.5 * (waferThick-backplaneThick); // inactive backplane
h1 = 0.5 * activeHeight;
if (isRing6) { //switch bl1 <->bl2
tmp = bl2; bl2 =bl1; bl1 = tmp;
}
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl2,
bl1, 0, h1, bl2, bl1, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl2 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", "
<< bl1 << ", 0";
DDLogicalPart active(solid.ddname(), matter, solid);
doPos(active, wafer, 1, -0.5 * backplaneThick,0,0, activeRot, cpv); // from the definition of the wafer local axes and doPos() routine
//inactive part in rings > 3
if(ringNo > 3){
inactivePos -= fullHeight-activeHeight; //inactivePos is measured from the beginning of the _wafer_
name = idName + tag +"Inactive";
matname = DDName(DDSplit(inactiveMat).first, DDSplit(inactiveMat).second);
matter = DDMaterial(matname);
bl1 = 0.5*dlBottom-sideWidthBottom
+ ((0.5*dlTop-sideWidthTop-0.5*dlBottom+sideWidthBottom)/activeHeight)
*(activeHeight-inactivePos-inactiveDy);
bl2 = 0.5*dlBottom-sideWidthBottom
+ ((0.5*dlTop-sideWidthTop-0.5*dlBottom+sideWidthBottom)/activeHeight)
*(activeHeight-inactivePos+inactiveDy);
dz = 0.5 * (waferThick-backplaneThick); // inactive backplane
h1 = inactiveDy;
if (isRing6) { //switch bl1 <->bl2
tmp = bl2; bl2 =bl1; bl1 = tmp;
}
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl2,
bl1, 0, h1, bl2, bl1, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl2 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", "
<< bl1 << ", 0";
DDLogicalPart inactive(solid.ddname(), matter, solid);
ypos = inactivePos - 0.5*activeHeight;
doPos(inactive,active, 1, ypos,0,0, "NULL", cpv); // from the definition of the wafer local axes and doPos() routine
}
//Pitch Adapter
name = idName + "PA";
matname = DDName(DDSplit(pitchMat).first, DDSplit(pitchMat).second);
matter = DDMaterial(matname);
if (!isStereo) {
dx = 0.5 * pitchWidth;
dy = 0.5 * pitchThick;
dz = 0.5 * pitchHeight;
solid = DDSolidFactory::box(DDName(name, idNameSpace), dx, dy, dz);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Box made of " << matname <<" of dimensions "
<< dx << ", " << dy << ", " << dz;
} else {
dz = 0.5 * pitchWidth;
h1 = 0.5 * pitchThick;
bl1 = 0.5 * pitchHeight + 0.5 * dz * sin(detTilt);
bl2 = 0.5 * pitchHeight - 0.5 * dz * sin(detTilt);
double thet = atan((bl1-bl2)/(2.*dz));
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1,
bl1, bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname
<< " of dimensions " << dz << ", " << thet/CLHEP::deg
<< ", 0, " << h1 << ", " << bl1 << ", " << bl1
<< ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
}
xpos = 0;
ypos = pitchZ;
zpos = 0.5 * (-waferPosition + fullHeight + pitchHeight);
if (isRing6) zpos *= -1;
if(isStereo) xpos = 0.5 * fullHeight * sin(detTilt);
DDLogicalPart pa(solid.ddname(), matter, solid);
if(isStereo)doPos(pa, xpos, ypos,zpos, pitchRot, cpv);
else doPos(pa, xpos, ypos,zpos, "NULL", cpv);
//Top of the frame
name = idName + "TopFrame";
matname = DDName(DDSplit(topFrameMat).first, DDSplit(topFrameMat).second);
matter = DDMaterial(matname);
h1 = 0.5 * topFrameThick;
dz = 0.5 * topFrameHeight;
bl1 = 0.5 * topFrameBotWidth;
bl2 = 0.5 * topFrameTopWidth;
if (isRing6) { // ring 6 faces the other way!
bl1 = 0.5 * topFrameTopWidth;
bl2 = 0.5 * topFrameBotWidth;
}
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1,
bl1,0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
DDLogicalPart topFrame(solid.ddname(), matter, solid);
if(isStereo){
name = idName + "TopFrame2";
//additional object to build the not trapzoid geometry of the stereo topframes
dz = 0.5 * topFrame2Width;
h1 = 0.5 * topFrameThick;
bl1 = 0.5 * topFrame2LHeight;
bl2 = 0.5 * topFrame2RHeight;
double thet = atan((bl1-bl2)/(2.*dz));
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1,
bl1, bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", " << thet/CLHEP::deg << ", 0, " << h1
<< ", " << bl1 << ", " << bl1 << ", 0, " << h1
<< ", " << bl2 << ", " << bl2 << ", 0";
}
// Position the topframe
ypos = topFrameZ;
zpos = 0.5 * (-waferPosition + fullHeight - topFrameHeight)+ pitchHeight + hybridHeight;
if(isRing6){
zpos *=-1;
}
doPos(topFrame, 0,ypos,zpos,"NULL", cpv);
if(isStereo){
//create
DDLogicalPart topFrame2(solid.ddname(), matter, solid);
zpos -= 0.5*(topFrameHeight + 0.5*(topFrame2LHeight+topFrame2RHeight));
doPos(topFrame2, 0,ypos,zpos,pitchRot, cpv);
}
//Si - Reencorcement
for (int i= 0; i < (int)(siReenforceWidth.size());i++){
name = idName + "SiReenforce" + std::to_string(i);
matname = DDName(DDSplit(siReenforceMat).first, DDSplit(siReenforceMat).second);
matter = DDMaterial(matname);
h1 = 0.5 * siReenforceThick;
dz = 0.5 * siReenforceHeight[i];
bl1 = bl2 = 0.5 * siReenforceWidth[i];
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1,
bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
DDLogicalPart siReenforce(solid.ddname(), matter, solid);
//translate
xpos =0 ;
ypos = sideFrameZ;
zpos = topFrameEndZ -dz -siReenforceYPos[i];
if (isRing6) zpos *= -1;
if(isStereo){
xpos = (-siReenforceYPos[i]+0.5*fullHeight)*sin(detTilt);
// thet = detTilt;
// if(topFrame2RHeight > topFrame2LHeight) thet *= -1;
// zpos -= topFrame2RHeight + sin(thet)*(sideFrameRWidth + 0.5*dlTop);
zpos -= topFrame2RHeight + sin (fabs(detTilt))* 0.5*topFrame2Width;
}
doPos(siReenforce,xpos,ypos,zpos,waferRot, cpv);
}
//Bridge
if (bridgeMat != "None") {
name = idName + "Bridge";
matname = DDName(DDSplit(bridgeMat).first, DDSplit(bridgeMat).second);
matter = DDMaterial(matname);
bl2 = 0.5*bridgeSep + bridgeWidth;
bl1 = bl2 - bridgeHeight * dxdif / dzdif;
h1 = 0.5 * bridgeThick;
dz = 0.5 * bridgeHeight;
solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1,
bl1, 0, h1, bl2, bl2, 0);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Trap made of " << matname << " of dimensions "
<< dz << ", 0, 0, " << h1 << ", " << bl1 << ", "
<< bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2
<< ", 0";
DDLogicalPart bridge(solid.ddname(), matter, solid);
name = idName + "BridgeGap";
matname = DDName(DDSplit(genMat).first, DDSplit(genMat).second);
matter = DDMaterial(matname);
bl1 = 0.5*bridgeSep;
solid = DDSolidFactory::box(DDName(name,idNameSpace), bl1, h1, dz);
LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name()
<< " Box made of " << matname << " of dimensions "
<< bl1 << ", " << h1 << ", " << dz;
DDLogicalPart bridgeGap(solid.ddname(), matter, solid);
cpv.position(bridgeGap, bridge, 1, DDTranslation(0.0, 0.0, 0.0), DDRotation());
LogDebug("TECGeom") << "DDTECModuleAlgo test: " << bridgeGap.name()
<< " number 1 positioned in " << bridge.name()
<< " at (0,0,0) with no rotation";
}
LogDebug("TECGeom") << "<<== End of DDTECModuleAlgo construction ...";
}
| 40.533835 | 171 | 0.604044 | nistefan |
17087a984bfb322409d3626a78449479d9737aef | 1,328 | cpp | C++ | test/unit/DeviceConfigParserTest.cpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 8 | 2019-06-10T19:44:48.000Z | 2021-06-10T23:03:24.000Z | test/unit/DeviceConfigParserTest.cpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 10 | 2019-05-15T21:01:54.000Z | 2021-01-16T23:08:53.000Z | test/unit/DeviceConfigParserTest.cpp | aetas/RoomHub | 9661c5a04a572ae99a812492db7091da07cf5789 | [
"MIT"
] | 2 | 2021-09-17T08:20:07.000Z | 2022-03-29T01:17:07.000Z | #include "../main/catch.hpp"
#include "config/device/DeviceConfigParser.hpp"
#include <typeinfo>
#include <iostream>
#include <string.h>
using namespace std;
TEST_CASE("DeviceConfigParser")
{
DeviceConfigParser parser;
SECTION("should parse semicolon-separated-values to DeviceConfig") {
// given:
// version;id;name;type_int;port;wire_color_int;debounce
const char* line = "1.0;103;test device name;2;16;4;100;45";
// when
DeviceConfig* device = parser.parse(line);
// then
REQUIRE(device != nullptr);
REQUIRE(device->getId() == 103);
REQUIRE(strcmp(device->getName(), "test device name") == 0);
REQUIRE(device->getDeviceType() == DeviceType::DIGITAL_OUTPUT);
REQUIRE(device->getPortNumber() == 16);
REQUIRE(device->getWireColor() == WireColor::BLUE);
REQUIRE(device->getDebounceMs() == 100);
REQUIRE(device->getPjonId() == 45);
}
SECTION("should return null if version is not supported (1.0 for now)") {
// given:
// version;id;name;type_int;port;wire_color_int;debounce
const char* line = "2.0;103;test device name;2;16;4;100;44";
// when
DeviceConfig* device = parser.parse(line);
// then
REQUIRE(device == nullptr);
}
} | 30.883721 | 77 | 0.61747 | aetas |
1708b690b4c5e013ba67090bdc435196a1e047cf | 4,795 | hh | C++ | optixrap/OGeo.hh | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | 1 | 2020-05-13T06:55:49.000Z | 2020-05-13T06:55:49.000Z | optixrap/OGeo.hh | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | optixrap/OGeo.hh | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <vector>
#include "OXPPNS.hh"
#include <optixu/optixu_math_namespace.h>
#include <optixu/optixu_aabb_namespace.h>
#include "plog/Severity.h"
class RayTraceConfig ;
class Opticks ;
class OContext ;
//class GGeo ;
//class GGeoBase ;
class GGeoLib ;
class GMergedMesh ;
class GBuffer ;
template <typename S> class NPY ;
// used by OEngine::initGeometry
/**
OGeo
=====
Canonical OGeo instance resides in OScene and is
instanciated and has its *convert* called from OScene::init.
OScene::convert loops over the GMergedMesh within GGeo
converting them into OptiX geometry groups. The first
GMergedMesh is assumed to be non-instanced, the remainder
are expected to be instanced with appropriate
transform and identity buffers.
Details of geometry tree are documented with the OGeo::convert method.
**/
#include "OGeoStat.hh"
struct OGeometry ;
#include "OXRAP_API_EXPORT.hh"
class OXRAP_API OGeo
{
public:
/*
struct OGeometry
{
optix::Geometry g ;
#if OPTIX_VERSION >= 60000
optix::GeometryTriangles gt ;
#endif
bool isGeometry() const ;
bool isGeometryTriangles() const ;
};
*/
static const plog::Severity LEVEL ;
static const char* ACCEL ;
OGeo(OContext* ocontext, Opticks* ok, GGeoLib* geolib );
void setTopGroup(optix::Group top);
void setVerbose(bool verbose=true);
std::string description() const ;
public:
void convert();
private:
void init();
void convertMergedMesh(unsigned i);
void dumpStats(const char* msg="OGeo::dumpStats");
public:
template <typename T> static optix::Buffer CreateInputUserBuffer(optix::Context& ctx, NPY<T>* src, unsigned elementSize, const char* name, const char* ctxname_informational, unsigned verbosity);
public:
template <typename T> optix::Buffer createInputBuffer(GBuffer* buf, RTformat format, unsigned int fold, const char* name, bool reuse=false);
template <typename T, typename S> optix::Buffer createInputBuffer(NPY<S>* buf, RTformat format, unsigned int fold, const char* name, bool reuse=false);
template <typename T> optix::Buffer createInputUserBuffer(NPY<T>* src, unsigned elementSize, const char* name);
public:
optix::GeometryGroup makeGlobalGeometryGroup(GMergedMesh* mm);
optix::Group makeRepeatedAssembly(GMergedMesh* mm, bool lod );
private:
void setTransformMatrix(optix::Transform& xform, const float* tdata ) ;
optix::Acceleration makeAcceleration(const char* accel, bool accel_props=false);
optix::Material makeMaterial();
OGeometry* makeOGeometry(GMergedMesh* mergedmesh, unsigned lod);
optix::GeometryInstance makeGeometryInstance(OGeometry* geometry, optix::Material material, unsigned instance_index);
optix::GeometryGroup makeGeometryGroup(optix::GeometryInstance gi, optix::Acceleration accel );
private:
optix::Geometry makeAnalyticGeometry(GMergedMesh* mergedmesh, unsigned lod);
optix::Geometry makeTriangulatedGeometry(GMergedMesh* mergedmesh, unsigned lod);
#if OPTIX_VERSION >= 60000
optix::GeometryTriangles makeGeometryTriangles(GMergedMesh* mm, unsigned lod);
#endif
private:
void dump(const char* msg, const float* m);
private:
// input references
OContext* m_ocontext ;
optix::Context m_context ;
optix::Group m_top ;
Opticks* m_ok ;
int m_gltf ;
GGeoLib* m_geolib ;
unsigned m_verbosity ;
private:
// for giving "context names" to GPU buffer uploads
const char* getContextName() const ;
unsigned m_mmidx ;
unsigned m_lodidx ;
const char* m_top_accel ;
const char* m_ggg_accel ;
const char* m_assembly_accel ;
const char* m_instance_accel ;
private:
// locals
RayTraceConfig* m_cfg ;
std::vector<OGeoStat> m_stats ;
};
| 30.935484 | 202 | 0.682586 | seriksen |
17090b5cda62448df1a289b222a3d91e1f151305 | 3,740 | cpp | C++ | mod/xlib/xlib.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 45 | 2018-08-24T12:57:38.000Z | 2021-11-12T11:21:49.000Z | mod/xlib/xlib.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | null | null | null | mod/xlib/xlib.cpp | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 4 | 2019-09-16T02:48:42.000Z | 2020-07-10T03:50:31.000Z | #include <L/src/engine/Engine.h>
#include <L/src/rendering/Renderer.h>
#include <L/src/system/System.h>
#include <L/src/system/Window.h>
#include <L/src/text/String.h>
#include "xlib.h"
static class XWindow* instance(nullptr);
L::Symbol xlib_window_type("xlib");
class XWindow : public L::Window {
protected:
::Display* _xdisplay;
::Window _xwindow;
public:
XWindow() {
L::String tmp;
L::System::call("xdpyinfo | grep 'dimensions:' | grep -o '[[:digit:]]\\+'", tmp);
L::Array<L::String> res(tmp.explode('\n'));
if(res.size() >= 2) {
_screen_width = L::ston<10, uint32_t>(res[0]);
_screen_height = L::ston<10, uint32_t>(res[1]);
}
}
void update() {
L_SCOPE_MARKER("Window update");
XEvent xev;
XWindowAttributes gwa;
while(opened() && XPending(_xdisplay)) {
XNextEvent(_xdisplay, &xev);
Window::Event e {};
switch(xev.type) {
case Expose:
XGetWindowAttributes(_xdisplay, _xwindow, &gwa);
if(_width != uint32_t(gwa.width) || _height != uint32_t(gwa.height)) {
e.type = Event::Type::Resize;
_width = e.coords.x = gwa.width;
_height = e.coords.y = gwa.height;
}
break;
case MotionNotify:
_cursor_x = xev.xmotion.x;
_cursor_y = xev.xmotion.y;
break;
case ClientMessage: // It's the close operation
close();
break;
}
if(e.type!=Event::Type::None) {
_events.push(e);
}
}
}
void open(const char* title, uint32_t width, uint32_t height, uint32_t flags) override {
L_SCOPE_MARKER("XWindow::open");
if(opened()) {
L::error("xlib: Trying to reopen window");
}
_width = width;
_height = height;
_flags = flags;
if((_xdisplay = XOpenDisplay(nullptr)) == nullptr) {
L::error("Cannot open X server display.");
}
{ // Create window
::Window root = DefaultRootWindow(_xdisplay);
int scr = DefaultScreen(_xdisplay);
int depth = DefaultDepth(_xdisplay, scr);
Visual* visual = DefaultVisual(_xdisplay, scr);
XSetWindowAttributes swa {};
swa.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;
_xwindow = XCreateWindow(_xdisplay, root, 0, 0, width, height, 0, depth, InputOutput, visual, CWColormap | CWEventMask, &swa);
}
{ // Activate window close events
Atom wm_delete_window(XInternAtom(_xdisplay, "WM_DELETE_WINDOW", 0));
XSetWMProtocols(_xdisplay, _xwindow, &wm_delete_window, 1);
}
XMapWindow(_xdisplay, _xwindow);
XStoreName(_xdisplay, _xwindow, title);
if(flags & nocursor) {
const char pixmap_data(0);
Pixmap pixmap(XCreateBitmapFromData(_xdisplay, _xwindow, &pixmap_data, 1, 1));
XColor color;
Cursor cursor(XCreatePixmapCursor(_xdisplay, pixmap, pixmap, &color, &color, 0, 0));
XDefineCursor(_xdisplay, _xwindow, cursor);
}
_opened = true;
XlibWindowData window_data;
window_data.type = xlib_window_type;
window_data.display = _xdisplay;
window_data.window = _xwindow;
L::Renderer::get()->init(&window_data);
}
void close() override {
L_ASSERT(_opened);
XDestroyWindow(_xdisplay, _xwindow);
XCloseDisplay(_xdisplay);
_opened = false;
}
void title(const char*) override {
L::warning("Setting window title is unsupported for X windows");
}
void resize(uint32_t, uint32_t) override {
L::warning("Resizing window is unsupported for X windows");
}
};
void xlib_module_init() {
instance = L::Memory::new_type<XWindow>();
L::Engine::add_parallel_update([]() {
instance->update();
});
}
| 29.92 | 132 | 0.632353 | Lyatus |
170ae6ad1523f514c387578f4e59dad41166fc9f | 5,620 | cpp | C++ | SpaceShooter/src/Game/Entities/EShipControllable.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/Entities/EShipControllable.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/Entities/EShipControllable.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | #include "../../Engine/Input/InputEvent.h"
#include "../../Engine/Input/InputManager.h"
#include "../Components/CWeapon.h"
#include "../../Engine/Math.h"
#include "../UI/WLifebar.h"
#include "../Components/HeadersComponents.h"
#include "../../Engine/Audio/Audiosource.h"
#include "../../Engine/Input/Controller.h"
#include "EShipControllable.h"
Ptr<EShipControllable> EShipControllable::Create()
{
Ptr<EShipControllable> p = new EShipControllable();
p->mThis = p.UpCast<Entity>();
return p;
}
Ptr<EShipControllable> EShipControllable::Create(const Transform2D& Tranform2D, float MaxLinearAcceleration, float MaxAngularAcceleration, float LinearInertiaSec, float AngularInertiaSec)
{
Ptr<EShipControllable> p = new EShipControllable(Tranform2D, MaxLinearAcceleration, MaxAngularAcceleration, LinearInertiaSec, AngularInertiaSec);
p->mThis = p.UpCast<Entity>();
return p;
}
EShipControllable::EShipControllable(const Transform2D& Tranform2D, float MaxLinearAcceleration, float MaxAngularAcceleration, float LinearInertiaSec, float AngularInertiaSec)
{
mType = EntityType::ENTITY_SHIPCONTROLLABLE;
SetTransform(Tranform2D);
SetTickMovement(true);
SetMaxLinearAcc(MaxLinearAcceleration);
SetMaxAngularAcc(MaxAngularAcceleration);
SetLinearInertia(LinearInertiaSec);
SetAngularInertia(AngularInertiaSec);
mInputActivated = true;
ActivateMovementController();
}
void EShipControllable::Init()
{
EShip::Init();
// All the inputs events that a controllable ship should observe
std::vector<InputEvent::TEvent> EventsToObserve;
EventsToObserve.push_back(InputEvent::EVENT_KEY_UP_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_UP_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_RIGHT_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_RIGHT_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_LEFT_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_LEFT_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_SPACE_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_SPACE_RELEASED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_TAB_PRESSED);
EventsToObserve.push_back(InputEvent::EVENT_KEY_TAB_RELEASED);
// Pass these events to the InputMananger
IInputManagerObserver::Instance()->AddObserver((mThis.DownCast<EShipControllable>()).UpCast<IIMObserver>(), EventsToObserve);
}
void EShipControllable::Update(float elapsed)
{
EShip::Update(elapsed);
}
void EShipControllable::Render()
{
EShip::Render();
}
void EShipControllable::ManageEvent(const InputEvent& Event)
{
// How to manage the input event
if (mInputActivated)
{
InputEvent::TEvent TypeEvent = Event.GetTEvent();
switch (TypeEvent)
{
case InputEvent::EVENT_NONE:
{
break;
}
case InputEvent::EVENT_MOUSE_RIGHT_CLICK:
{
break;
}
case InputEvent::EVENT_MOUSE_LEFT_CLICK:
{
break;
}
case InputEvent::EVENT_KEY_SPACE_PRESSED:
{
if (IsPrimaryWeaponActive())
{
GetPrimaryWeaponComp()->Fire(GetProjectileSpawnPos(), GetRotation());
SetPrimaryWeaponActive(false);
}
break;
}
case InputEvent::EVENT_KEY_SPACE_RELEASED:
{
SetPrimaryWeaponActive(true);
break;
}
case InputEvent::EVENT_KEY_TAB_PRESSED:
{
if (IsSecondaryWeaponActive())
{
GetSecondaryWeaponComp()->Fire(GetProjectileSpawnPos(), GetRotation());
SetSecondaryWeaponActive(false);
}
break;
}
case InputEvent::EVENT_KEY_TAB_RELEASED:
{
SetSecondaryWeaponActive(true);
break;
}
case InputEvent::EVENT_KEY_UP_PRESSED:
{
if(IsMovementControllerActivated())
{
DeactivateLinearInertia();
SetLinearSteering(vec2(GetForwardVector().x * GetMaxLinearAcc(), GetForwardVector().y* GetMaxLinearAcc()));
}
break;
}
case InputEvent::EVENT_KEY_UP_RELEASED:
{
if (IsMovementControllerActivated())
{
ActivateLinearInertia();
}
break;
}
case InputEvent::EVENT_KEY_DOWN_PRESSED:
{
break;
}
case InputEvent::EVENT_KEY_RIGHT_PRESSED:
{
if (IsMovementControllerActivated())
{
DeactivateAngularInertia();
SetAngularSteering(-GetMaxAngularAcc());
SetTurnDirection(-1);
}
break;
}
case InputEvent::EVENT_KEY_RIGHT_RELEASED:
{
if (IsMovementControllerActivated())
{
ActivateAngularInertia();
}
break;
}
case InputEvent::EVENT_KEY_LEFT_PRESSED:
{
if (IsMovementControllerActivated())
{
DeactivateAngularInertia();
SetAngularSteering(GetMaxAngularAcc());
SetTurnDirection(1);
}
break;
}
case InputEvent::EVENT_KEY_LEFT_RELEASED:
{
if (IsMovementControllerActivated())
{
ActivateAngularInertia();
}
break;
}
default:
break;
}
}
} | 31.222222 | 187 | 0.625089 | tomasmartinsantos |
170dbe21f8030fd7cf7f65fe085eded46ed9565b | 330 | cpp | C++ | Code full house/buoi20 nguyen dinh trung duc/newbie/prob C.cpp | ducyb2001/CbyTrungDuc | 0e93394dce600876a098b90ae969575bac3788e1 | [
"Apache-2.0"
] | null | null | null | Code full house/buoi20 nguyen dinh trung duc/newbie/prob C.cpp | ducyb2001/CbyTrungDuc | 0e93394dce600876a098b90ae969575bac3788e1 | [
"Apache-2.0"
] | null | null | null | Code full house/buoi20 nguyen dinh trung duc/newbie/prob C.cpp | ducyb2001/CbyTrungDuc | 0e93394dce600876a098b90ae969575bac3788e1 | [
"Apache-2.0"
] | null | null | null | /*problem C*/
#include<stdio.h>
#include<string.h>
int main(){
int n;
scanf("%d",&n);
int a[n];
int sum=0;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
sum+=a[i];
}
float tbc=(float)sum/n;
int kq=0;
for(int i=0;i<n;i++){
if(a[i]>tbc){
kq+=a[i];
}
}
if(kq==0){
printf("-1");
return 0;
}
printf("%d",kq);
}
| 12.222222 | 24 | 0.490909 | ducyb2001 |
170e458b5971a4e0bb7b0a3db6b5436c1aa66c5c | 702 | hpp | C++ | src/renderer/pipelines/events/BIND.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 2 | 2021-03-18T16:25:04.000Z | 2021-11-13T00:29:27.000Z | src/renderer/pipelines/events/BIND.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | null | null | null | src/renderer/pipelines/events/BIND.hpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 1 | 2021-11-13T00:29:30.000Z | 2021-11-13T00:29:30.000Z | /**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#ifndef ZEN_RENDERER_PIPELINES_EVENTS_BIND_HPP
#define ZEN_RENDERER_PIPELINES_EVENTS_BIND_HPP
#include <string>
namespace Zen {
namespace Events {
/**
* The Pipeline Bind Event.
*
* This event is dispatched by a Pipeline when it is bound by the PipelineManager.
*
* @since 0.0.0
*
* @param pipeline Pointer to the pipeline that was bound.
* @param currentShader Pointer to the shader that was set as being current.
*/
const std::string PIPELINE_BIND = "pipelinebind";
} // namespace Events
} // namespace Zen
#endif
| 21.9375 | 82 | 0.730769 | hexoctal |
170e4c2736749d042c444e034419918e75733a7a | 226 | cpp | C++ | MegamanX3/MegamanX3/main.cpp | quangnghiauit/game | 3c0537f96342c6fcb89cf5f3541acfef75b558f1 | [
"MIT"
] | null | null | null | MegamanX3/MegamanX3/main.cpp | quangnghiauit/game | 3c0537f96342c6fcb89cf5f3541acfef75b558f1 | [
"MIT"
] | null | null | null | MegamanX3/MegamanX3/main.cpp | quangnghiauit/game | 3c0537f96342c6fcb89cf5f3541acfef75b558f1 | [
"MIT"
] | null | null | null | #include<Windows.h>
#include"MyGame.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MyGame *game = new MyGame(nCmdShow);
game->InitGame();
game->GameRun();
return 0;
} | 20.545455 | 95 | 0.738938 | quangnghiauit |
170fbf11cedf367fac4916f8ecb202f04eec0a67 | 7,724 | cpp | C++ | dynamorio/clients/drcachesim/tools/view.cpp | andre-motta/Project3Compilers | fa366d93ec8d49768fbc86f0c1431391822baf12 | [
"MIT"
] | null | null | null | dynamorio/clients/drcachesim/tools/view.cpp | andre-motta/Project3Compilers | fa366d93ec8d49768fbc86f0c1431391822baf12 | [
"MIT"
] | null | null | null | dynamorio/clients/drcachesim/tools/view.cpp | andre-motta/Project3Compilers | fa366d93ec8d49768fbc86f0c1431391822baf12 | [
"MIT"
] | null | null | null | /* **********************************************************
* Copyright (c) 2017-2020 Google, Inc. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Google, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. 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.
*/
/* This trace analyzer requires access to the modules.log file and the
* libraries and binary from the traced execution in order to obtain further
* information about each instruction than was stored in the trace.
* It does not support online use, only offline.
*/
#include "dr_api.h"
#include "view.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
const std::string view_t::TOOL_NAME = "View tool";
analysis_tool_t *
view_tool_create(const std::string &module_file_path, uint64_t skip_refs,
uint64_t sim_refs, const std::string &syntax, unsigned int verbose,
const std::string &alt_module_dir)
{
return new view_t(module_file_path, skip_refs, sim_refs, syntax, verbose,
alt_module_dir);
}
view_t::view_t(const std::string &module_file_path, uint64_t skip_refs, uint64_t sim_refs,
const std::string &syntax, unsigned int verbose,
const std::string &alt_module_dir)
: module_file_path_(module_file_path)
, knob_verbose_(verbose)
, instr_count_(0)
, knob_skip_refs_(skip_refs)
, knob_sim_refs_(sim_refs)
, knob_syntax_(syntax)
, knob_alt_module_dir_(alt_module_dir)
, num_disasm_instrs_(0)
{
}
std::string
view_t::initialize()
{
if (module_file_path_.empty())
return "Module file path is missing";
dcontext_.dcontext = dr_standalone_init();
std::string error = directory_.initialize_module_file(module_file_path_);
if (!error.empty())
return "Failed to initialize directory: " + error;
module_mapper_ =
module_mapper_t::create(directory_.modfile_bytes_, nullptr, nullptr, nullptr,
nullptr, knob_verbose_, knob_alt_module_dir_);
module_mapper_->get_loaded_modules();
error = module_mapper_->get_last_error();
if (!error.empty())
return "Failed to load binaries: " + error;
dr_disasm_flags_t flags = DR_DISASM_ATT;
if (knob_syntax_ == "intel") {
flags = DR_DISASM_INTEL;
} else if (knob_syntax_ == "dr") {
flags = DR_DISASM_DR;
} else if (knob_syntax_ == "arm") {
flags = DR_DISASM_ARM;
}
disassemble_set_syntax(flags);
return "";
}
bool
view_t::process_memref(const memref_t &memref)
{
if (instr_count_ < knob_skip_refs_ ||
instr_count_ >= (knob_skip_refs_ + knob_sim_refs_)) {
if (type_is_instr(memref.instr.type) ||
memref.data.type == TRACE_TYPE_INSTR_NO_FETCH)
++instr_count_;
return true;
}
if (memref.marker.type == TRACE_TYPE_MARKER) {
switch (memref.marker.marker_type) {
case TRACE_MARKER_TYPE_FILETYPE:
if (TESTANY(OFFLINE_FILE_TYPE_ARCH_ALL, memref.marker.marker_value) &&
!TESTANY(build_target_arch_type(), memref.marker.marker_value)) {
error_string_ = std::string("Architecture mismatch: trace recorded on ") +
trace_arch_string(static_cast<offline_file_type_t>(
memref.marker.marker_value)) +
" but tool built for " + trace_arch_string(build_target_arch_type());
return false;
}
break;
case TRACE_MARKER_TYPE_TIMESTAMP:
std::cerr << "<marker: timestamp " << memref.marker.marker_value << ">\n";
break;
case TRACE_MARKER_TYPE_CPU_ID:
// We include the thread ID here under the assumption that we will always
// see a cpuid marker on a thread switch. To avoid that assumption
// we would want to track the prior tid and print out a thread switch
// message whenever it changes.
std::cerr << "<marker: tid " << memref.marker.tid << " on core "
<< memref.marker.marker_value << ">\n";
break;
case TRACE_MARKER_TYPE_KERNEL_EVENT:
std::cerr << "<marker: kernel xfer to handler>\n";
break;
case TRACE_MARKER_TYPE_KERNEL_XFER:
std::cerr << "<marker: syscall xfer>\n";
break;
default:
// We ignore other markers such as call/ret profiling for now.
break;
}
return true;
}
if (!type_is_instr(memref.instr.type) &&
memref.data.type != TRACE_TYPE_INSTR_NO_FETCH)
return true;
++instr_count_;
app_pc mapped_pc;
app_pc orig_pc = (app_pc)memref.instr.addr;
mapped_pc = module_mapper_->find_mapped_trace_address(orig_pc);
if (!module_mapper_->get_last_error().empty()) {
error_string_ = "Failed to find mapped address for " +
to_hex_string(memref.instr.addr) + ": " + module_mapper_->get_last_error();
return false;
}
std::string disasm;
auto cached_disasm = disasm_cache_.find(mapped_pc);
if (cached_disasm != disasm_cache_.end()) {
disasm = cached_disasm->second;
} else {
// MAX_INSTR_DIS_SZ is set to 196 in core/ir/disassemble.h but is not
// exported so we just use the same value here.
char buf[196];
byte *next_pc = disassemble_to_buffer(
dcontext_.dcontext, mapped_pc, orig_pc, /*show_pc=*/true,
/*show_bytes=*/true, buf, BUFFER_SIZE_ELEMENTS(buf),
/*printed=*/nullptr);
if (next_pc == nullptr) {
error_string_ = "Failed to disassemble " + to_hex_string(memref.instr.addr);
return false;
}
disasm = buf;
disasm_cache_.insert({ mapped_pc, disasm });
}
// XXX: For now we print the disassembly of instructions only. We should extend
// this tool to annotate load/store operations with the entries recorded in
// the offline trace.
std::cerr << disasm;
++num_disasm_instrs_;
return true;
}
bool
view_t::print_results()
{
std::cerr << TOOL_NAME << " results:\n";
std::cerr << std::setw(15) << num_disasm_instrs_
<< " : total disassembled instructions\n";
return true;
}
| 39.408163 | 90 | 0.648628 | andre-motta |
171167a943cfbfe20cfdc4ddf432f82a95d7d6a9 | 140 | cpp | C++ | darknet-master/build/modules/imgproc/color_hsv.sse4_1.cpp | mcyy23633/ship_YOLOv4 | 2eb53e578546fce663a2f3fa153481ce4f82c588 | [
"MIT"
] | null | null | null | darknet-master/build/modules/imgproc/color_hsv.sse4_1.cpp | mcyy23633/ship_YOLOv4 | 2eb53e578546fce663a2f3fa153481ce4f82c588 | [
"MIT"
] | null | null | null | darknet-master/build/modules/imgproc/color_hsv.sse4_1.cpp | mcyy23633/ship_YOLOv4 | 2eb53e578546fce663a2f3fa153481ce4f82c588 | [
"MIT"
] | null | null | null |
#include "C:/opencv/opencv-4.5.1/modules/imgproc/src/precomp.hpp"
#include "C:/opencv/opencv-4.5.1/modules/imgproc/src/color_hsv.simd.hpp"
| 35 | 72 | 0.757143 | mcyy23633 |
1718aea0480f5a310eed75e199d928d4e108e9a3 | 1,212 | cpp | C++ | AdvancedDataStructures/rp_heap_testing_ec504/rp_heap_testbench.cpp | pdvnny/DataStructures-Algorithms | 9c1adbb77126011274129715c1ba589317d4479c | [
"Apache-2.0"
] | null | null | null | AdvancedDataStructures/rp_heap_testing_ec504/rp_heap_testbench.cpp | pdvnny/DataStructures-Algorithms | 9c1adbb77126011274129715c1ba589317d4479c | [
"Apache-2.0"
] | null | null | null | AdvancedDataStructures/rp_heap_testing_ec504/rp_heap_testbench.cpp | pdvnny/DataStructures-Algorithms | 9c1adbb77126011274129715c1ba589317d4479c | [
"Apache-2.0"
] | null | null | null | /**********************************************
Parker Dunn (pgdunn@bu.edu)
EC 504 Final Project
Testbench for my first version of rp_heap.h
***********************************************/
#include <iostream>
#include "rp_heap.h"
using namespace std;
int main() {
rp_heap* myHeap = new rp_heap();
int size = 10;
int heap_extract;
/// creating a bunch of things to push
int elements[size][2];
for (int i = 1; i < (size+1); i++) {
elements[i-1][0] = i; // KEY
elements[i-1][1] = i*10; // DATA
}
for (int j = 0; j < size; j++)
myHeap->push(elements[j][1], elements[j][0]);
cout << "\nThe size of myHeap is " << myHeap->size() << "\n" << endl;
cout << "\nExtracting 4 Nodes now..." << endl;
for (int j = 0; j < 4; j++) {
heap_extract = myHeap->extract_min();
cout << "Extraction #" << (j+1) << ": " << heap_extract << endl;
}
cout << "\nTime to decrease some keys..." << endl;
myHeap->decreaseKey(10, 5);
myHeap->decreaseKey(9, 8);
cout << "\n";
for (int j = 4; j < size; j++) {
heap_extract = myHeap->extract_min();
cout << "Extraction #" << (j+1) << ": " << heap_extract << endl;
}
return 0;
} | 20.896552 | 73 | 0.499175 | pdvnny |
1718bcb3e0909a56d7df2cb1c57df98a0b461be0 | 7,616 | cc | C++ | release/src-rt-6.x.4708/router/mysql/sql/sql_error.cc | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src-rt-6.x.4708/router/mysql/sql/sql_error.cc | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src-rt-6.x.4708/router/mysql/sql/sql_error.cc | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /*
Copyright (c) 2002-2008 MySQL AB, 2008, 2009 Sun Microsystems, Inc.
Use is subject to license terms.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**********************************************************************
This file contains the implementation of error and warnings related
- Whenever an error or warning occurred, it pushes it to a warning list
that the user can retrieve with SHOW WARNINGS or SHOW ERRORS.
- For each statement, we return the number of warnings generated from this
command. Note that this can be different from @@warning_count as
we reset the warning list only for questions that uses a table.
This is done to allow on to do:
INSERT ...;
SELECT @@warning_count;
SHOW WARNINGS;
(If we would reset after each command, we could not retrieve the number
of warnings)
- When client requests the information using SHOW command, then
server processes from this list and returns back in the form of
resultset.
Supported syntaxes:
SHOW [COUNT(*)] ERRORS [LIMIT [offset,] rows]
SHOW [COUNT(*)] WARNINGS [LIMIT [offset,] rows]
SELECT @@warning_count, @@error_count;
***********************************************************************/
#include "mysql_priv.h"
#include "sp_rcontext.h"
/*
Store a new message in an error object
This is used to in group_concat() to register how many warnings we actually
got after the query has been executed.
*/
void MYSQL_ERROR::set_msg(THD *thd, const char *msg_arg)
{
msg= strdup_root(&thd->warn_root, msg_arg);
}
/*
Reset all warnings for the thread
SYNOPSIS
mysql_reset_errors()
thd Thread handle
force Reset warnings even if it has been done before
IMPLEMENTATION
Don't reset warnings if this has already been called for this query.
This may happen if one gets a warning during the parsing stage,
in which case push_warnings() has already called this function.
*/
void mysql_reset_errors(THD *thd, bool force)
{
DBUG_ENTER("mysql_reset_errors");
if (thd->query_id != thd->warn_id || force)
{
thd->warn_id= thd->query_id;
free_root(&thd->warn_root,MYF(0));
bzero((char*) thd->warn_count, sizeof(thd->warn_count));
if (force)
thd->total_warn_count= 0;
thd->warn_list.empty();
thd->row_count= 1; // by default point to row 1
}
DBUG_VOID_RETURN;
}
/*
Push the warning/error to error list if there is still room in the list
SYNOPSIS
push_warning()
thd Thread handle
level Severity of warning (note, warning, error ...)
code Error number
msg Clear error message
RETURN
pointer on MYSQL_ERROR object
*/
MYSQL_ERROR *push_warning(THD *thd, MYSQL_ERROR::enum_warning_level level,
uint code, const char *msg)
{
MYSQL_ERROR *err= 0;
DBUG_ENTER("push_warning");
DBUG_PRINT("enter", ("code: %d, msg: %s", code, msg));
DBUG_ASSERT(code != 0);
DBUG_ASSERT(msg != NULL);
if (level == MYSQL_ERROR::WARN_LEVEL_NOTE &&
!(thd->options & OPTION_SQL_NOTES))
DBUG_RETURN(0);
if (thd->query_id != thd->warn_id && !thd->spcont)
mysql_reset_errors(thd, 0);
thd->got_warning= 1;
/* Abort if we are using strict mode and we are not using IGNORE */
if ((int) level >= (int) MYSQL_ERROR::WARN_LEVEL_WARN &&
thd->really_abort_on_warning())
{
/* Avoid my_message() calling push_warning */
bool no_warnings_for_error= thd->no_warnings_for_error;
sp_rcontext *spcont= thd->spcont;
thd->no_warnings_for_error= 1;
thd->spcont= NULL;
thd->killed= THD::KILL_BAD_DATA;
my_message(code, msg, MYF(0));
thd->spcont= spcont;
thd->no_warnings_for_error= no_warnings_for_error;
/* Store error in error list (as my_message() didn't do it) */
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
}
if (thd->handle_error(code, msg, level))
DBUG_RETURN(NULL);
if (thd->spcont &&
thd->spcont->handle_error(code, level, thd))
{
DBUG_RETURN(NULL);
}
query_cache_abort(&thd->net);
if (thd->warn_list.elements < thd->variables.max_error_count)
{
/* We have to use warn_root, as mem_root is freed after each query */
if ((err= new (&thd->warn_root) MYSQL_ERROR(thd, code, level, msg)))
thd->warn_list.push_back(err, &thd->warn_root);
}
thd->warn_count[(uint) level]++;
thd->total_warn_count++;
DBUG_RETURN(err);
}
/*
Push the warning/error to error list if there is still room in the list
SYNOPSIS
push_warning_printf()
thd Thread handle
level Severity of warning (note, warning, error ...)
code Error number
msg Clear error message
*/
void push_warning_printf(THD *thd, MYSQL_ERROR::enum_warning_level level,
uint code, const char *format, ...)
{
va_list args;
char warning[MYSQL_ERRMSG_SIZE];
DBUG_ENTER("push_warning_printf");
DBUG_PRINT("enter",("warning: %u", code));
DBUG_ASSERT(code != 0);
DBUG_ASSERT(format != NULL);
va_start(args,format);
my_vsnprintf(warning, sizeof(warning), format, args);
va_end(args);
push_warning(thd, level, code, warning);
DBUG_VOID_RETURN;
}
/*
Send all notes, errors or warnings to the client in a result set
SYNOPSIS
mysqld_show_warnings()
thd Thread handler
levels_to_show Bitmap for which levels to show
DESCRIPTION
Takes into account the current LIMIT
RETURN VALUES
FALSE ok
TRUE Error sending data to client
*/
const LEX_STRING warning_level_names[]=
{
{ C_STRING_WITH_LEN("Note") },
{ C_STRING_WITH_LEN("Warning") },
{ C_STRING_WITH_LEN("Error") },
{ C_STRING_WITH_LEN("?") }
};
bool mysqld_show_warnings(THD *thd, ulong levels_to_show)
{
List<Item> field_list;
DBUG_ENTER("mysqld_show_warnings");
field_list.push_back(new Item_empty_string("Level", 7));
field_list.push_back(new Item_return_int("Code",4, MYSQL_TYPE_LONG));
field_list.push_back(new Item_empty_string("Message",MYSQL_ERRMSG_SIZE));
if (thd->protocol->send_fields(&field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
DBUG_RETURN(TRUE);
MYSQL_ERROR *err;
SELECT_LEX *sel= &thd->lex->select_lex;
SELECT_LEX_UNIT *unit= &thd->lex->unit;
ha_rows idx= 0;
Protocol *protocol=thd->protocol;
unit->set_limit(sel);
List_iterator_fast<MYSQL_ERROR> it(thd->warn_list);
while ((err= it++))
{
/* Skip levels that the user is not interested in */
if (!(levels_to_show & ((ulong) 1 << err->level)))
continue;
if (++idx <= unit->offset_limit_cnt)
continue;
if (idx > unit->select_limit_cnt)
break;
protocol->prepare_for_resend();
protocol->store(warning_level_names[err->level].str,
warning_level_names[err->level].length, system_charset_info);
protocol->store((uint32) err->code);
protocol->store(err->msg, (uint) strlen(err->msg), system_charset_info);
if (protocol->write())
DBUG_RETURN(TRUE);
}
my_eof(thd);
DBUG_RETURN(FALSE);
}
| 28.848485 | 79 | 0.675945 | afeng11 |
17192f89651302fb794b091406686f43367251a8 | 4,124 | cpp | C++ | src/+cv/fisheyeStereoCalibrate.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 571 | 2015-01-04T06:23:19.000Z | 2022-03-31T07:37:19.000Z | src/+cv/fisheyeStereoCalibrate.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 362 | 2015-01-06T14:20:46.000Z | 2022-01-20T08:10:46.000Z | src/+cv/fisheyeStereoCalibrate.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 300 | 2015-01-20T03:21:27.000Z | 2022-03-31T07:36:37.000Z | /**
* @file fisheyeStereoCalibrate.cpp
* @brief mex interface for cv::fisheye::stereoCalibrate
* @ingroup calib3d
* @author Amro
* @date 2017
*/
#include "mexopencv.hpp"
#include "opencv2/calib3d.hpp"
using namespace std;
using namespace cv;
namespace {
/** Create a new MxArray from stereo calibration results.
* @param K1 First camera matrix.
* @param D1 Distortion coefficients of first camera.
* @param K2 Second camera matrix.
* @param D2 Distortion coefficients of second camera.
* @param R Rotation matrix between the cameras coordinate systems.
* @param T Translation vector between the cameras coordinate systems.
* @param rms Re-projection error.
* @return output MxArray struct object.
*/
MxArray toStruct(const Mat& K1, const Mat& D1, const Mat& K2, const Mat& D2,
const Mat& R, const Mat& T, double rms)
{
const char* fieldnames[] = {"cameraMatrix1", "distCoeffs1",
"cameraMatrix2", "distCoeffs2", "R", "T", "reprojErr"};
MxArray s = MxArray::Struct(fieldnames, 7);
s.set("cameraMatrix1", K1);
s.set("distCoeffs1", D1);
s.set("cameraMatrix2", K2);
s.set("distCoeffs2", D2);
s.set("R", R);
s.set("T", T);
s.set("reprojErr", rms);
return s;
}
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
// Option processing
Mat K1, D1, K2, D2;
int flags = cv::CALIB_FIX_INTRINSIC;
TermCriteria criteria(TermCriteria::COUNT+TermCriteria::EPS, 100, DBL_EPSILON);
for (int i=4; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "CameraMatrix1")
K1 = rhs[i+1].toMat(CV_64F);
else if (key == "DistCoeffs1")
D1 = rhs[i+1].toMat(CV_64F);
else if (key == "CameraMatrix2")
K2 = rhs[i+1].toMat(CV_64F);
else if (key == "DistCoeffs2")
D2 = rhs[i+1].toMat(CV_64F);
else if (key == "UseIntrinsicGuess")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_USE_INTRINSIC_GUESS);
else if (key == "RecomputeExtrinsic")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC);
else if (key == "CheckCond")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_CHECK_COND);
else if (key == "FixSkew")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_SKEW);
else if (key == "FixK1")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K1);
else if (key == "FixK2")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K2);
else if (key == "FixK3")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K3);
else if (key == "FixK4")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K4);
else if (key == "FixIntrinsic")
UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_INTRINSIC);
else if (key == "Criteria")
criteria = rhs[i+1].toTermCriteria();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
// Process
vector<vector<Point3d> > objectPoints(MxArrayToVectorVectorPoint3<double>(rhs[0]));
vector<vector<Point2d> > imagePoints1(MxArrayToVectorVectorPoint<double>(rhs[1]));
vector<vector<Point2d> > imagePoints2(MxArrayToVectorVectorPoint<double>(rhs[2]));
Size imageSize(rhs[3].toSize());
Mat R, T;
double rms = fisheye::stereoCalibrate(objectPoints, imagePoints1, imagePoints2,
K1, D1, K2, D2, imageSize, R, T, flags, criteria);
plhs[0] = toStruct(K1, D1, K2, D2, R, T, rms);
}
| 39.27619 | 90 | 0.626819 | 1123852253 |
171bf164f43b1e782f78ad5548fe47fd9cb27cdb | 11,359 | cpp | C++ | src/turtlecoin-crypto-js.cpp | CASH2-js/cash2-crypto | 1b1386253d5c032ac5a0d619481bff7931c979e9 | [
"BSD-3-Clause"
] | null | null | null | src/turtlecoin-crypto-js.cpp | CASH2-js/cash2-crypto | 1b1386253d5c032ac5a0d619481bff7931c979e9 | [
"BSD-3-Clause"
] | null | null | null | src/turtlecoin-crypto-js.cpp | CASH2-js/cash2-crypto | 1b1386253d5c032ac5a0d619481bff7931c979e9 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2018-2020, The TurtleCoin Developers
//
// Please see the included LICENSE file for more information.
#include <emscripten/bind.h>
#include <stdio.h>
#include <stdlib.h>
#include <turtlecoin-crypto.h>
using namespace emscripten;
struct Keys
{
std::string publicKey;
std::string secretKey;
};
struct PreparedSignatures
{
std::vector<std::string> signatures;
std::string key;
};
/* Most of the redefintions below are the result of the methods returning a bool instead
of the value we need or issues with method signatures having a uint64_t */
std::string cn_soft_shell_slow_hash_v0(const std::string data, const int height)
{
return Core::Cryptography::cn_soft_shell_slow_hash_v0(data, height);
}
std::string cn_soft_shell_slow_hash_v1(const std::string data, const int height)
{
return Core::Cryptography::cn_soft_shell_slow_hash_v1(data, height);
}
std::string cn_soft_shell_slow_hash_v2(const std::string data, const int height)
{
return Core::Cryptography::cn_soft_shell_slow_hash_v2(data, height);
}
std::vector<std::string> generateRingSignatures(
const std::string prefixHash,
const std::string keyImage,
const std::vector<std::string> publicKeys,
const std::string transactionSecretKey,
const int realOutputIndex)
{
std::vector<std::string> signatures;
bool success = Core::Cryptography::generateRingSignatures(
prefixHash, keyImage, publicKeys, transactionSecretKey, realOutputIndex, signatures);
return signatures;
}
PreparedSignatures prepareRingSignatures(
const std::string prefixHash,
const std::string keyImage,
const std::vector<std::string> publicKeys,
const int realOutputIndex)
{
std::vector<std::string> signatures;
std::string k;
bool success =
Core::Cryptography::prepareRingSignatures(prefixHash, keyImage, publicKeys, realOutputIndex, signatures, k);
PreparedSignatures result;
result.signatures = signatures;
result.key = k;
return result;
}
PreparedSignatures prepareRingSignaturesK(
const std::string prefixHash,
const std::string keyImage,
const std::vector<std::string> publicKeys,
const int realOutputIndex,
const std::string k)
{
std::vector<std::string> signatures;
bool success =
Core::Cryptography::prepareRingSignatures(prefixHash, keyImage, publicKeys, realOutputIndex, k, signatures);
PreparedSignatures result;
result.signatures = signatures;
result.key = k;
return result;
}
Keys generateViewKeysFromPrivateSpendKey(const std::string secretKey)
{
std::string viewSecretKey;
std::string viewPublicKey;
Core::Cryptography::generateViewKeysFromPrivateSpendKey(secretKey, viewSecretKey, viewPublicKey);
Keys keys;
keys.publicKey = viewPublicKey;
keys.secretKey = viewSecretKey;
return keys;
}
Keys generateKeys()
{
std::string secretKey;
std::string publicKey;
Core::Cryptography::generateKeys(secretKey, publicKey);
Keys keys;
keys.publicKey = publicKey;
keys.secretKey = secretKey;
return keys;
}
Keys generateDeterministicSubwalletKeys(const std::string basePrivateKey, const size_t walletIndex)
{
std::string newPrivateKey;
std::string newPublicKey;
Keys keys;
Core::Cryptography::generateDeterministicSubwalletKeys(basePrivateKey, walletIndex, keys.secretKey, keys.publicKey);
return keys;
}
std::string secretKeyToPublicKey(const std::string secretKey)
{
std::string publicKey;
bool success = Core::Cryptography::secretKeyToPublicKey(secretKey, publicKey);
return publicKey;
}
std::string generateKeyDerivation(const std::string publicKey, const std::string secretKey)
{
std::string derivation;
bool success = Core::Cryptography::generateKeyDerivation(publicKey, secretKey, derivation);
return derivation;
}
std::string generateKeyDerivationScalar(const std::string publicKey, const std::string secretKey, size_t outputIndex)
{
return Core::Cryptography::generateKeyDerivationScalar(publicKey, secretKey, outputIndex);
}
std::string derivationToScalar(const std::string derivation, size_t outputIndex)
{
return Core::Cryptography::derivationToScalar(derivation, outputIndex);
}
std::string derivePublicKey(const std::string derivation, const size_t outputIndex, const std::string publicKey)
{
std::string derivedKey;
bool success = Core::Cryptography::derivePublicKey(derivation, outputIndex, publicKey, derivedKey);
return derivedKey;
}
std::string scalarDerivePublicKey(const std::string derivationScalar, const std::string publicKey)
{
std::string derivedKey;
bool success = Core::Cryptography::derivePublicKey(derivationScalar, publicKey, derivedKey);
return derivedKey;
}
std::string deriveSecretKey(const std::string derivation, const size_t outputIndex, const std::string secretKey)
{
return Core::Cryptography::deriveSecretKey(derivation, outputIndex, secretKey);
}
std::string scalarDeriveSecretKey(const std::string derivationScalar, const std::string secretKey)
{
return Core::Cryptography::deriveSecretKey(derivationScalar, secretKey);
}
std::string underivePublicKey(const std::string derivation, const size_t outputIndex, const std::string derivedKey)
{
std::string publicKey;
bool success = Core::Cryptography::underivePublicKey(derivation, outputIndex, derivedKey, publicKey);
return publicKey;
}
std::vector<std::string> completeRingSignatures(
const std::string transactionSecretKey,
const int realOutputIndex,
const std::string k,
const std::vector<std::string> signatures)
{
std::vector<std::string> completeSignatures;
for (auto sig : signatures)
{
completeSignatures.push_back(sig);
}
bool success =
Core::Cryptography::completeRingSignatures(transactionSecretKey, realOutputIndex, k, completeSignatures);
return completeSignatures;
}
std::vector<std::string> restoreRingSignatures(
const std::string derivation,
const size_t output_index,
const std::vector<std::string> partialSigningKeys,
const int realOutput,
const std::string k,
const std::vector<std::string> signatures)
{
std::vector<std::string> completeSignatures;
for (auto sig : signatures)
{
completeSignatures.push_back(sig);
}
bool success = Core::Cryptography::restoreRingSignatures(
derivation, output_index, partialSigningKeys, realOutput, k, completeSignatures);
return completeSignatures;
}
EMSCRIPTEN_BINDINGS(signatures)
{
function("cn_fast_hash", &Core::Cryptography::cn_fast_hash);
function("cn_slow_hash_v0", &Core::Cryptography::cn_slow_hash_v0);
function("cn_slow_hash_v1", &Core::Cryptography::cn_slow_hash_v1);
function("cn_slow_hash_v2", &Core::Cryptography::cn_slow_hash_v2);
function("cn_lite_slow_hash_v0", &Core::Cryptography::cn_lite_slow_hash_v0);
function("cn_lite_slow_hash_v1", &Core::Cryptography::cn_lite_slow_hash_v1);
function("cn_lite_slow_hash_v2", &Core::Cryptography::cn_lite_slow_hash_v2);
function("cn_dark_slow_hash_v0", &Core::Cryptography::cn_dark_slow_hash_v0);
function("cn_dark_slow_hash_v1", &Core::Cryptography::cn_dark_slow_hash_v1);
function("cn_dark_slow_hash_v2", &Core::Cryptography::cn_dark_slow_hash_v2);
function("cn_dark_lite_slow_hash_v0", &Core::Cryptography::cn_dark_lite_slow_hash_v0);
function("cn_dark_lite_slow_hash_v1", &Core::Cryptography::cn_dark_lite_slow_hash_v1);
function("cn_dark_lite_slow_hash_v2", &Core::Cryptography::cn_dark_lite_slow_hash_v2);
function("cn_turtle_slow_hash_v0", &Core::Cryptography::cn_turtle_slow_hash_v0);
function("cn_turtle_slow_hash_v1", &Core::Cryptography::cn_turtle_slow_hash_v1);
function("cn_turtle_slow_hash_v2", &Core::Cryptography::cn_turtle_slow_hash_v2);
function("cn_turtle_lite_slow_hash_v0", &Core::Cryptography::cn_turtle_lite_slow_hash_v0);
function("cn_turtle_lite_slow_hash_v1", &Core::Cryptography::cn_turtle_lite_slow_hash_v1);
function("cn_turtle_lite_slow_hash_v2", &Core::Cryptography::cn_turtle_lite_slow_hash_v2);
function("cn_soft_shell_slow_hash_v0", &cn_soft_shell_slow_hash_v0);
function("cn_soft_shell_slow_hash_v1", &cn_soft_shell_slow_hash_v1);
function("cn_soft_shell_slow_hash_v2", &cn_soft_shell_slow_hash_v2);
function("chukwa_slow_hash", &Core::Cryptography::chukwa_slow_hash);
function("tree_depth", &Core::Cryptography::tree_depth);
function("tree_hash", &Core::Cryptography::tree_hash);
function("tree_branch", &Core::Cryptography::tree_branch);
function("tree_hash_from_branch", &Core::Cryptography::tree_hash_from_branch);
function("generateRingSignatures", &generateRingSignatures);
function("prepareRingSignatures", &prepareRingSignatures);
function("prepareRingSignaturesK", &prepareRingSignaturesK);
function("completeRingSignatures", &completeRingSignatures);
function("checkRingSignature", &Core::Cryptography::checkRingSignature);
function(
"generatePrivateViewKeyFromPrivateSpendKey", &Core::Cryptography::generatePrivateViewKeyFromPrivateSpendKey);
function("generateViewKeysFromPrivateSpendKey", &generateViewKeysFromPrivateSpendKey);
function("generateKeys", &generateKeys);
function("generateDeterministicSubwalletKeys", &generateDeterministicSubwalletKeys);
function("checkKey", &Core::Cryptography::checkKey);
function("secretKeyToPublicKey", &secretKeyToPublicKey);
function("generateKeyDerivation", &generateKeyDerivation);
function("generateKeyDerivationScalar", &generateKeyDerivationScalar);
function("derivationToScalar", &derivationToScalar);
function("derivePublicKey", &derivePublicKey);
function("deriveSecretKey", &deriveSecretKey);
function("scalarDerivePublicKey", &scalarDerivePublicKey);
function("scalarDeriveSecretKey", &scalarDeriveSecretKey);
function("underivePublicKey", &underivePublicKey);
function("generateSignature", &Core::Cryptography::generateSignature);
function("checkSignature", &Core::Cryptography::checkSignature);
function("generateKeyImage", &Core::Cryptography::generateKeyImage);
function("scalarmultKey", &Core::Cryptography::scalarmultKey);
function("hashToEllipticCurve", &Core::Cryptography::hashToEllipticCurve);
function("scReduce32", &Core::Cryptography::scReduce32);
function("hashToScalar", &Core::Cryptography::hashToScalar);
/* Multisig Methods */
function("calculateMultisigPrivateKeys", &Core::Cryptography::calculateMultisigPrivateKeys);
function("calculateSharedPrivateKey", &Core::Cryptography::calculateSharedPrivateKey);
function("calculateSharedPublicKey", &Core::Cryptography::calculateSharedPublicKey);
function("generatePartialSigningKey", &Core::Cryptography::generatePartialSigningKey);
function("restoreKeyImage", &Core::Cryptography::restoreKeyImage);
function("restoreRingSignatures", &restoreRingSignatures);
register_vector<std::string>("VectorString");
value_object<Keys>("Keys").field("secretKey", &Keys::secretKey).field("publicKey", &Keys::publicKey);
value_object<PreparedSignatures>("Keys")
.field("signatures", &PreparedSignatures::signatures)
.field("key", &PreparedSignatures::key);
}
| 33.907463 | 120 | 0.758341 | CASH2-js |
171c90f5c8adf93ca64d2d238b50c87cc49cb239 | 724 | cpp | C++ | cpp/G3M/GPUAttributeValueVec1Float.cpp | glob3mobile/g3m | 2b2c6422f05d13e0855b1dbe4e0afed241184193 | [
"BSD-2-Clause"
] | 70 | 2015-02-06T14:39:14.000Z | 2022-01-07T08:32:48.000Z | cpp/G3M/GPUAttributeValueVec1Float.cpp | glob3mobile/g3m | 2b2c6422f05d13e0855b1dbe4e0afed241184193 | [
"BSD-2-Clause"
] | 118 | 2015-01-21T10:18:00.000Z | 2018-10-16T15:00:57.000Z | cpp/G3M/GPUAttributeValueVec1Float.cpp | glob3mobile/g3m | 2b2c6422f05d13e0855b1dbe4e0afed241184193 | [
"BSD-2-Clause"
] | 41 | 2015-01-10T22:29:27.000Z | 2021-06-08T11:56:16.000Z | //
// GPUAttributeValueVec1Float.cpp
// G3M
//
// Created by DIEGO RAMIRO GOMEZ-DECK on 1/4/19.
//
#include "GPUAttributeValueVec1Float.hpp"
GPUAttributeValueVec1Float::GPUAttributeValueVec1Float(IFloatBuffer* buffer,
int arrayElementSize,
int index,
int stride,
bool normalized) :
GPUAttributeValueVecFloat(buffer,
1,
arrayElementSize,
index,
stride,
normalized)
{
}
| 30.166667 | 76 | 0.403315 | glob3mobile |
17240c96ec8014dce5c349c2c2097b70997aa4e5 | 2,465 | cpp | C++ | vpnor/test/create_read_window_size.cpp | ibm-openbmc/hiomapd | 8cef63e3a3652b25f6a310800c1e0bf09aeed4c6 | [
"Apache-2.0"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | vpnor/test/create_read_window_size.cpp | ibm-openbmc/hiomapd | 8cef63e3a3652b25f6a310800c1e0bf09aeed4c6 | [
"Apache-2.0"
] | 17 | 2018-09-20T02:29:41.000Z | 2019-04-05T04:43:11.000Z | vpnor/test/create_read_window_size.cpp | ibm-openbmc/hiomapd | 8cef63e3a3652b25f6a310800c1e0bf09aeed4c6 | [
"Apache-2.0"
] | 9 | 2017-02-14T03:05:09.000Z | 2019-01-07T20:39:42.000Z | // SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2018 IBM Corp.
#include "config.h"
extern "C" {
#include "test/mbox.h"
#include "test/system.h"
}
#include "vpnor/test/tmpd.hpp"
#include <cassert>
#include <experimental/filesystem>
#include "vpnor/backend.h"
static const auto BLOCK_SIZE = 4096;
static const auto ERASE_SIZE = BLOCK_SIZE;
static const auto WINDOW_SIZE = 2 * BLOCK_SIZE;
static const auto MEM_SIZE = WINDOW_SIZE;
static const auto N_WINDOWS = 1;
static const auto PNOR_SIZE = 4 * BLOCK_SIZE;
const std::string toc[] = {
"partition01=ONE,00001000,00002000,80,ECC,READONLY",
"partition02=TWO,00002000,00004000,80,ECC,READONLY",
};
static const uint8_t get_info[] = {0x02, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
static const uint8_t request_one[] = {0x04, 0x01, 0x01, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
static const uint8_t response_one[] = {0x04, 0x01, 0xfe, 0xff, 0x01,
0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01};
static const uint8_t request_two[] = {0x04, 0x02, 0x02, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00};
static const uint8_t response_two[] = {0x04, 0x02, 0xfe, 0xff, 0x02,
0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01};
namespace test = openpower::virtual_pnor::test;
int main()
{
struct mbox_context* ctx;
system_set_reserved_size(MEM_SIZE);
system_set_mtd_sizes(PNOR_SIZE, ERASE_SIZE);
ctx = mbox_create_frontend_context(N_WINDOWS, WINDOW_SIZE);
test::VpnorRoot root(&ctx->backend, toc, BLOCK_SIZE);
int rc = mbox_command_dispatch(ctx, get_info, sizeof(get_info));
assert(rc == 1);
rc = mbox_command_dispatch(ctx, request_one, sizeof(request_one));
assert(rc == 1);
rc = mbox_cmp(ctx, response_one, sizeof(response_one));
assert(rc == 0);
rc = mbox_command_dispatch(ctx, request_two, sizeof(request_two));
assert(rc == 1);
rc = mbox_cmp(ctx, response_two, sizeof(response_two));
assert(rc == 0);
return rc;
}
| 31.202532 | 73 | 0.593509 | ibm-openbmc |
172628daaa456b00c9286a0db48929d1559a021f | 958 | hpp | C++ | include/ygp/rng.hpp | qaqwqaqwq-0/YGP | 928d53aff1c8ca1327b0cf7ad6e6836d44c3447f | [
"MIT"
] | 5 | 2020-12-07T08:58:24.000Z | 2021-03-22T08:21:16.000Z | include/ygp/rng.hpp | qaqwqaqwq-0/YGP | 928d53aff1c8ca1327b0cf7ad6e6836d44c3447f | [
"MIT"
] | null | null | null | include/ygp/rng.hpp | qaqwqaqwq-0/YGP | 928d53aff1c8ca1327b0cf7ad6e6836d44c3447f | [
"MIT"
] | 2 | 2021-01-26T07:45:52.000Z | 2021-02-14T15:54:54.000Z | #ifndef _YGP_RNG_HPP_
#define _YGP_RNG_HPP_
#include"configure.hpp"
#include<cstdint>
BEGIN_NAMESPACE_YGP
template<typename _Tp>
class rng/*range*/
{
public:
using t=_Tp;
struct iterator
{
t tc,td;
iterator(t B,t D):tc{B},td{D}{}
t operator++(){return tc+=td;}
t operator--(){return tc-=td;}
const t& operator*()const{return tc;}
bool operator==(const iterator& an)const{return tc==an.tc;}
bool operator!=(const iterator& an)const{return tc!=an.tc;}
};
t b,e,d;
explicit rng(t E)
{
b=0,e=E,d=1;
}
explicit rng(t B,t E,t D=1):b{B},e{E},d{D}{}
iterator begin()const
{
return iterator{b,d};
}
iterator end()const
{
return iterator{e,d};
}
};
/*Usage: for(auto i:rng(begin,end))//[begin,end)*/
END_NAMESPACE_YGP
#endif | 25.210526 | 71 | 0.515658 | qaqwqaqwq-0 |
17273c77358e8d22cf1f6a9964f5eed94c1b3785 | 2,327 | cpp | C++ | libmarch/tests/core_types.cpp | j8xixo12/solvcon | a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a | [
"BSD-3-Clause"
] | 16 | 2015-12-09T02:54:42.000Z | 2021-04-20T11:26:39.000Z | libmarch/tests/core_types.cpp | j8xixo12/solvcon | a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a | [
"BSD-3-Clause"
] | 95 | 2015-12-09T00:49:40.000Z | 2022-02-14T13:34:55.000Z | libmarch/tests/core_types.cpp | j8xixo12/solvcon | a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a | [
"BSD-3-Clause"
] | 13 | 2015-05-08T04:16:42.000Z | 2021-01-15T09:28:06.000Z | /*
* Copyright (c) 2016, Yung-Yu Chen <yyc@solvcon.net>
* BSD 3-Clause License, see LICENSE.txt
*/
#include <cstdint>
#include <type_traits>
#include <gtest/gtest.h>
#include "march/core/types.hpp"
using namespace march;
TEST(typesTest, TypeId) {
DataTypeId val;
val = type_to<bool>::id;
EXPECT_EQ(val, MH_BOOL);
val = type_to<int8_t>::id;
EXPECT_EQ(val, MH_INT8);
val = type_to<uint8_t>::id;
EXPECT_EQ(val, MH_UINT8);
val = type_to<int16_t>::id;
EXPECT_EQ(val, MH_INT16);
val = type_to<uint16_t>::id;
EXPECT_EQ(val, MH_UINT16);
val = type_to<int32_t>::id;
EXPECT_EQ(val, MH_INT32);
val = type_to<uint32_t>::id;
EXPECT_EQ(val, MH_UINT32);
val = type_to<int64_t>::id;
EXPECT_EQ(val, MH_INT64);
val = type_to<uint64_t>::id;
EXPECT_EQ(val, MH_UINT64);
val = type_to<float>::id;
EXPECT_EQ(val, MH_FLOAT);
val = type_to<double>::id;
EXPECT_EQ(val, MH_DOUBLE);
val = type_to<std::complex<float>>::id;
EXPECT_EQ(val, MH_CFLOAT);
val = type_to<std::complex<double>>::id;
EXPECT_EQ(val, MH_CDOUBLE);
}
TEST(typesTest, cpptype) {
static_assert(std::is_same<id_to<MH_BOOL>::type, bool>::value, "bad bool");
static_assert(std::is_same<id_to<MH_INT8>::type, int8_t>::value, "bad int8");
static_assert(std::is_same<id_to<MH_UINT8>::type, uint8_t>::value, "bad uint8");
static_assert(std::is_same<id_to<MH_INT16>::type, int16_t>::value, "bad int16");
static_assert(std::is_same<id_to<MH_UINT16>::type, uint16_t>::value, "bad uint16");
static_assert(std::is_same<id_to<MH_INT32>::type, int32_t>::value, "bad int32");
static_assert(std::is_same<id_to<MH_UINT32>::type, uint32_t>::value, "bad uint32");
static_assert(std::is_same<id_to<MH_INT64>::type, int64_t>::value, "bad int64");
static_assert(std::is_same<id_to<MH_UINT64>::type, uint64_t>::value, "bad uint64");
static_assert(std::is_same<id_to<MH_FLOAT>::type, float>::value, "bad float");
static_assert(std::is_same<id_to<MH_DOUBLE>::type, double>::value, "bad double");
static_assert(std::is_same<id_to<MH_CFLOAT>::type, std::complex<float>>::value, "bad cfloat");
static_assert(std::is_same<id_to<MH_CDOUBLE>::type, std::complex<double>>::value, "bad cdouble");
}
// vim: set ff=unix fenc=utf8 nobomb et sw=4 ts=4:
| 37.532258 | 101 | 0.676407 | j8xixo12 |
172aba938345b6741eb65fd95c87a4fcacf42f84 | 1,913 | cpp | C++ | src/device/controllerNvidia.cpp | ISilence/delirium_cl | d54499af2556511eb47ae90b2420788ca914d314 | [
"MIT"
] | 2 | 2017-06-02T08:08:47.000Z | 2017-08-24T06:43:40.000Z | src/device/controllerNvidia.cpp | ISilence/delirium_cl | d54499af2556511eb47ae90b2420788ca914d314 | [
"MIT"
] | 9 | 2016-11-17T18:46:30.000Z | 2017-05-13T20:16:50.000Z | src/device/controllerNvidia.cpp | ISilence/delirium_cl | d54499af2556511eb47ae90b2420788ca914d314 | [
"MIT"
] | null | null | null | #if !defined(DLM_CL_SKIP_VENDOR_NVIDIA)
#include "dlm/env/macro.h"
DLM_CMODULE_START
#include "cl/cl_ext_nvidia.h"
DLM_CMODULE_END
#include "dlm/cl/device.hpp"
#include "dlm/cl/controllers.hpp"
using namespace dlmcl;
static void getPCITopology(DeviceInfo &info, cl_device_id device) noexcept
{
// undocumented Nvidia API
#define CL_DEVICE_PCI_BUS_ID_NV 0x4008
#define CL_DEVICE_PCI_SLOT_ID_NV 0x4009
cl_int bus = -1;
cl_int slot = -1;
cl_int err = clGetDeviceInfo (device, CL_DEVICE_PCI_BUS_ID_NV, sizeof(bus), &bus, NULL);
if (err != CL_SUCCESS)
return;
err = clGetDeviceInfo(device, CL_DEVICE_PCI_SLOT_ID_NV, sizeof(slot), &slot, NULL);
if (err != CL_SUCCESS)
return;
info.topology.bus = bus;
info.topology.dev = (slot >> 3) & 0xff;
info.topology.fn = slot & 0x7;
}
static void getMemoryArchitecture(DeviceInfo &info, cl_device_id device) noexcept
{
cl_bool isSMA;
const cl_int err = clGetDeviceInfo(device, CL_DEVICE_INTEGRATED_MEMORY_NV, sizeof(isSMA), &isSMA, NULL);
if (err == CL_SUCCESS)
info.memory.isSMA = (isSMA != 0);
}
static void getMemoryCaps(DeviceInfo &info, cl_device_id device) noexcept
{
cl_uint warp;
const cl_int err = clGetDeviceInfo(device, CL_DEVICE_WARP_SIZE_NV, sizeof(warp), &warp, NULL);
if (err == CL_SUCCESS)
info.compute.warp = warp;
}
DeviceInfo NvidiaController::getInfo(cl_device_id device) noexcept
{
DeviceInfo info = GenericController::getInfo(device);
getPCITopology(info, device);
getMemoryArchitecture(info, device);
getMemoryCaps(info, device);
return info;
}
const char* NvidiaController::getCompilationOptions(cl_device_id device, enum OPTIMIZATION_LEVEL level) noexcept
{
static const char opts[] = "-cl-fast-relaxed-math -cl-no-signed-zeros -cl-mad-enable -D DLM_NVIDIA";
return opts;
}
#endif // DLM_CL_SKIP_VENDOR_NVIDIA
| 28.984848 | 112 | 0.721903 | ISilence |
172b56c34f9c16feadc8d7e7a2301c7e8af139fa | 2,051 | cpp | C++ | Development/nmos/node_resource.cpp | EwoutH/nmos-cpp | e8cf0e2322bb4ae343f10638abf6035206620fe6 | [
"Apache-2.0"
] | null | null | null | Development/nmos/node_resource.cpp | EwoutH/nmos-cpp | e8cf0e2322bb4ae343f10638abf6035206620fe6 | [
"Apache-2.0"
] | null | null | null | Development/nmos/node_resource.cpp | EwoutH/nmos-cpp | e8cf0e2322bb4ae343f10638abf6035206620fe6 | [
"Apache-2.0"
] | null | null | null | #include "nmos/node_resource.h"
#include "cpprest/host_utils.h"
#include "cpprest/uri_builder.h"
#include "nmos/is04_versions.h"
#include "nmos/resource.h"
namespace nmos
{
// See https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/schemas/node.json
nmos::resource make_node(const nmos::id& id, const nmos::settings& settings)
{
using web::json::value;
using web::json::value_from_elements;
using web::json::value_of;
const auto hostname = !nmos::fields::host_name(settings).empty() ? nmos::fields::host_name(settings) : web::http::experimental::host_name();
auto data = details::make_resource_core(id, settings);
auto uri = web::uri_builder()
.set_scheme(U("http"))
.set_host(nmos::fields::host_address(settings))
.set_port(nmos::fields::node_port(settings))
.to_uri();
data[U("href")] = value::string(uri.to_string());
data[U("hostname")] = value::string(hostname);
data[U("api")][U("versions")] = value_from_elements(nmos::is04_versions::from_settings(settings) | boost::adaptors::transformed(make_api_version));
const auto at_least_one_host_address = value_of({ value::string(nmos::fields::host_address(settings)) });
const auto& host_addresses = settings.has_field(nmos::fields::host_addresses) ? nmos::fields::host_addresses(settings) : at_least_one_host_address.as_array();
for (const auto& host_address : host_addresses)
{
value endpoint;
endpoint[U("host")] = host_address;
endpoint[U("port")] = uri.port();
endpoint[U("protocol")] = value::string(uri.scheme());
web::json::push_back(data[U("api")][U("endpoints")], endpoint);
}
data[U("caps")] = value::object();
data[U("services")] = value::array();
data[U("clocks")] = value::array();
data[U("interfaces")] = value::array();
return{ is04_versions::v1_3, types::node, data, false };
}
}
| 37.981481 | 166 | 0.627986 | EwoutH |
172db5a9f7c0bc205531e64a301ba183d7857f33 | 1,187 | cpp | C++ | cpp/leetcode/FindCommonCharacters.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/FindCommonCharacters.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/FindCommonCharacters.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 1002 Find Common Characters
//Solution written by Xuqiang Fang on 5 Mar, 2019
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution{
public:
vector<string> commonChars(vector<string>& A){
const int n = A.size();
auto ans = helper(A[0]);
for(int i=1; i<n; ++i){
auto tmp = helper(A[i]);
for(int j=0; j<26; ++j){
ans[j] = min(ans[j], tmp[j]);
}
}
vector<string> ret;
for(int i=0; i<26; ++i){
while(ans[i] > 0){
string s;
char c = (char)('a'+i);
s.push_back(c);
ret.push_back(s);
ans[i]--;
}
}
return ret;
}
private:
vector<int> helper(string& a){
vector<int> ans(26, 0);
for(auto& c : a)
ans[c-'a']++;
return ans;
}
};
int main(){
Solution s;
vector<string> A {"bella", "label", "roller"};
auto ans = s.commonChars(A);
for(auto& a : ans){
cout << a << " ";
}
cout << endl;
A = {"cool", "lock", "cook"};
ans = s.commonChars(A);
for(auto& a : ans){
cout << a << " ";
}
cout << endl;
return 0;
}
| 19.145161 | 49 | 0.557709 | danyfang |
172edd1de0d19cdafc6ec5825400f61a8e4f2035 | 2,268 | cpp | C++ | MMVII/src/RamImages/cIm2d.cpp | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 8 | 2019-05-08T21:43:53.000Z | 2021-07-27T20:01:46.000Z | MMVII/src/RamImages/cIm2d.cpp | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 2 | 2019-05-24T17:11:33.000Z | 2019-06-30T17:55:28.000Z | MMVII/src/RamImages/cIm2d.cpp | dronemapper-io/micmac | d15d33de48a76575b6555399bc3bf9d89e31baa2 | [
"CECILL-B"
] | 2 | 2020-08-01T00:27:16.000Z | 2022-02-04T10:24:54.000Z | #include "include/MMVII_all.h"
namespace MMVII
{
/* ========================== */
/* cDataIm2D */
/* ========================== */
template <class Type> cDataIm2D<Type>::cDataIm2D(const cPt2di & aP0,const cPt2di & aP1,Type * aRawDataLin,eModeInitImage aModeInit) :
cDataTypedIm<Type,2> (aP0,aP1,aRawDataLin,aModeInit)
{
mRawData2D = cMemManager::Alloc<tVal*>(cRectObj<2>::Sz().y()) -Y0();
for (int aY=Y0() ; aY<Y1() ; aY++)
mRawData2D[aY] = tBI::mRawDataLin + (aY-Y0()) * SzX() - X0();
}
template <class Type> cDataIm2D<Type>::~cDataIm2D()
{
cMemManager::Free(mRawData2D+Y0());
}
template <class Type> int cDataIm2D<Type>::VI_GetV(const cPt2di& aP) const
{
return GetV(aP);
}
template <class Type> double cDataIm2D<Type>::VD_GetV(const cPt2di& aP) const
{
return GetV(aP);
}
template <class Type> void cDataIm2D<Type>::VI_SetV(const cPt2di& aP,const int & aV)
{
SetVTrunc(aP,aV);
}
template <class Type> void cDataIm2D<Type>::VD_SetV(const cPt2di& aP,const double & aV)
{
SetVTrunc(aP,aV);
}
/* ========================== */
/* cIm2D */
/* ========================== */
template <class Type> cIm2D<Type>::cIm2D(const cPt2di & aP0,const cPt2di & aP1,Type * aRawDataLin,eModeInitImage aModeInit) :
mSPtr(new cDataIm2D<Type>(aP0,aP1,aRawDataLin,aModeInit)),
mPIm (mSPtr.get())
{
}
template <class Type> cIm2D<Type>::cIm2D(const cPt2di & aSz,Type * aRawDataLin,eModeInitImage aModeInit) :
cIm2D<Type> (cPt2di(0,0),aSz,aRawDataLin,aModeInit)
{
}
template <class Type> cIm2D<Type> cIm2D<Type>::FromFile(const std::string & aName)
{
cDataFileIm2D aFileIm = cDataFileIm2D::Create(aName);
cIm2D<Type> aRes(aFileIm.Sz());
aRes.Read(aFileIm,cPt2di(0,0));
return aRes;
}
template <class Type> cIm2D<Type> cIm2D<Type>::Dup() const
{
cIm2D<Type> aRes(DIm().P0(),DIm().P1());
DIm().DupIn(aRes.DIm());
return aRes;
}
#define INSTANTIATE_IM2D(Type)\
template class cIm2D<Type>;\
template class cDataIm2D<Type>;
INSTANTIATE_IM2D(tINT1)
INSTANTIATE_IM2D(tINT2)
INSTANTIATE_IM2D(tINT4)
INSTANTIATE_IM2D(tU_INT1)
INSTANTIATE_IM2D(tU_INT2)
INSTANTIATE_IM2D(tU_INT4)
INSTANTIATE_IM2D(tREAL4)
INSTANTIATE_IM2D(tREAL8)
INSTANTIATE_IM2D(tREAL16)
};
| 23.381443 | 135 | 0.645944 | dronemapper-io |
173146c0cba0fa47527e4d530ca230027e9051f4 | 1,944 | cpp | C++ | source/directinput/CapabilitiesDI.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/directinput/CapabilitiesDI.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/directinput/CapabilitiesDI.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <dinput.h>
#include "CapabilitiesDI.h"
#include "Guids.h"
#include "DeviceSubType.h"
using namespace System;
namespace SlimDX
{
namespace DirectInput
{
Capabilities::Capabilities( const DIDEVCAPS &caps )
{
axesCount = caps.dwAxes;
buttonCount = caps.dwButtons;
povCount = caps.dwPOVs;
ffSamplePeriod = caps.dwFFSamplePeriod;
ffMinTimeResolution = caps.dwFFMinTimeResolution;
ffDriverVersion = caps.dwFFDriverVersion;
firmwareRevision = caps.dwFirmwareRevision;
hardwareRevision = caps.dwHardwareRevision;
flags = static_cast<DeviceFlags>( caps.dwFlags );
type = static_cast<DeviceType>( caps.dwDevType );
subType = caps.dwDevType >> 8;
if( ( caps.dwDevType & DIDEVTYPE_HID ) != 0 )
hid = true;
else
hid = false;
}
}
} | 35.345455 | 80 | 0.736626 | HeavenWu |
17330f1c438b9f64ae39ac15d8a76615d4e8c423 | 1,031 | cpp | C++ | tests/circuit_test/circuittest.cpp | Ignotus/circuitmod | 6e2b0c949df9c40e77d56f5fc0e890a54e1c7a17 | [
"BSD-2-Clause"
] | null | null | null | tests/circuit_test/circuittest.cpp | Ignotus/circuitmod | 6e2b0c949df9c40e77d56f5fc0e890a54e1c7a17 | [
"BSD-2-Clause"
] | null | null | null | tests/circuit_test/circuittest.cpp | Ignotus/circuitmod | 6e2b0c949df9c40e77d56f5fc0e890a54e1c7a17 | [
"BSD-2-Clause"
] | null | null | null | #include <QtTest>
#include <circuits/nand2.h>
#include <circuits/nor2.h>
#include <circuits/or2.h>
#include "circuittest.h"
#define TEST_ELEMENT(CLASS_NAME, FUNCTION) \
CLASS_NAME circuit;\
const bool i[] = {true, true, false, false};\
const bool j[] = {true, false, true, false};\
\
const QList<QString>& output = circuit.outputs();\
const QList<QString>& input = circuit.inputs();\
const QString& firstPortName = input[0];\
const QString& secondPortName = input[1];\
const QString& outputPortName = output[0];\
\
for (int k = 0; k != sizeof(i) / sizeof(bool); ++k)\
{\
circuit.setSignal(firstPortName, i[k]);\
circuit.setSignal(secondPortName, j[k]);\
QCOMPARE(FUNCTION, circuit.state(outputPortName));\
}
void CircuitTest::nand2Test()
{
TEST_ELEMENT(NAnd2, !(i[k] && j[k]));
}
void CircuitTest::nor2Test()
{
TEST_ELEMENT(NOr2, !(i[k] || j[k]));
}
void CircuitTest::or2Test()
{
TEST_ELEMENT(Or2, i[k] || j[k]);
}
QTEST_MAIN(CircuitTest) | 25.775 | 59 | 0.631426 | Ignotus |
173323212ed343e557833be6bf3d775b3bb0da62 | 4,503 | hpp | C++ | src/libraries/core/finiteVolume/fvc/fvcSmooth/smoothDataI.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/finiteVolume/fvc/fvcSmooth/smoothDataI.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/finiteVolume/fvc/fvcSmooth/smoothDataI.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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 3 of the License, or
(at your option) any later version.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
template<class TrackingData>
inline bool CML::smoothData::update
(
const smoothData& svf,
const scalar scale,
const scalar tol,
TrackingData& td
)
{
if (!valid(td) || (value_ < VSMALL))
{
// My value not set - take over neighbour
value_ = svf.value()/scale;
// Something changed - let caller know
return true;
}
else if (svf.value() > (1 + tol)*scale*value_)
{
// Neighbour is too big for me - Up my value
value_ = svf.value()/scale;
// Something changed - let caller know
return true;
}
else
{
// Neighbour is not too big for me or change is too small
// Nothing changed
return false;
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
inline CML::smoothData::smoothData()
:
value_(-GREAT)
{}
inline CML::smoothData::smoothData(const scalar value)
:
value_(value)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class TrackingData>
inline bool CML::smoothData::valid(TrackingData& td) const
{
return value_ > -SMALL;
}
template<class TrackingData>
inline bool CML::smoothData::sameGeometry
(
const polyMesh&,
const smoothData&,
const scalar,
TrackingData& td
) const
{
return true;
}
template<class TrackingData>
inline void CML::smoothData::leaveDomain
(
const polyMesh&,
const polyPatch&,
const label,
const point&,
TrackingData& td
)
{}
template<class TrackingData>
inline void CML::smoothData::transform
(
const polyMesh&,
const tensor&,
TrackingData& td
)
{}
template<class TrackingData>
inline void CML::smoothData::enterDomain
(
const polyMesh&,
const polyPatch&,
const label,
const point&,
TrackingData& td
)
{}
template<class TrackingData>
inline bool CML::smoothData::updateCell
(
const polyMesh&,
const label,
const label,
const smoothData& svf,
const scalar tol,
TrackingData& td
)
{
// Take over info from face if more than deltaRatio larger
return update(svf, td.maxRatio, tol, td);
}
template<class TrackingData>
inline bool CML::smoothData::updateFace
(
const polyMesh&,
const label,
const label,
const smoothData& svf,
const scalar tol,
TrackingData& td
)
{
// Take over information from cell without any scaling (scale = 1.0)
return update(svf, 1.0, tol, td);
}
// Update this (face) with coupled face information.
template<class TrackingData>
inline bool CML::smoothData::updateFace
(
const polyMesh&,
const label,
const smoothData& svf,
const scalar tol,
TrackingData& td
)
{
// Take over information from coupled face without any scaling (scale = 1.0)
return update(svf, 1.0, tol, td);
}
template <class TrackingData>
inline bool CML::smoothData::equal
(
const smoothData& rhs,
TrackingData& td
) const
{
return operator==(rhs);
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
inline void CML::smoothData::operator=
(
const scalar value
)
{
value_ = value;
}
inline bool CML::smoothData::operator==
(
const smoothData& rhs
) const
{
return value_ == rhs.value();
}
inline bool CML::smoothData::operator!=
(
const smoothData& rhs
) const
{
return !(*this == rhs);
}
// ************************************************************************* //
| 20.751152 | 80 | 0.585165 | MrAwesomeRocks |
1734742849aac8e69573038dbb7818081164c22c | 816 | cc | C++ | adlik_serving/framework/manager/boarding_loop.cc | zhaohainan666/Adlik | 51e8c798720d1b9139fc9660a4fa40aa644ac451 | [
"Apache-2.0"
] | 1 | 2019-09-27T00:49:30.000Z | 2019-09-27T00:49:30.000Z | adlik_serving/framework/manager/boarding_loop.cc | zhaohainan666/Adlik | 51e8c798720d1b9139fc9660a4fa40aa644ac451 | [
"Apache-2.0"
] | null | null | null | adlik_serving/framework/manager/boarding_loop.cc | zhaohainan666/Adlik | 51e8c798720d1b9139fc9660a4fa40aa644ac451 | [
"Apache-2.0"
] | null | null | null | #include "adlik_serving/framework/manager/boarding_loop.h"
#include "adlik_serving/framework/manager/boarding_functor.h"
#include "cub/env/concurrent/auto_lock.h"
namespace adlik {
namespace serving {
BoardingLoop::BoardingLoop() {
// auto action = [this] { this->poll(); };
// loop.reset(new cub::LoopThread(action, 10 * 1000 /* ms */));
}
void BoardingLoop::poll() {
auto action = [this] {
cub::AutoLock lock(this->mu);
BoardingFunctor f(this->ROLE(ManagedStore));
f(streams);
};
loop.reset(new cub::LoopThread(action, 10 * 1000 /* ms */));
// cub::AutoLock lock(mu);
// BoardingFunctor f(ROLE(ManagedStore));
// f(streams);
}
void BoardingLoop::update(ModelStream& stream) {
cub::AutoLock lock(mu);
streams.push_back(stream);
}
} // namespace serving
} // namespace adlik
| 24 | 65 | 0.678922 | zhaohainan666 |
1734cd367bde7adaa4ca92a36bd65474366fffd3 | 3,564 | cpp | C++ | src/hdk/ui/hdCheckbox.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | 2 | 2016-06-15T17:47:50.000Z | 2019-07-29T10:33:05.000Z | src/hdk/ui/hdCheckbox.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | null | null | null | src/hdk/ui/hdCheckbox.cpp | cdave1/hdk | 7c00dcbb255a48ab4a77d808cda0096c7e0a0fa6 | [
"Zlib"
] | null | null | null | /*
* Copyright (c) 2014 Hackdirt Ltd.
* Author: David Petrie (david@davidpetrie.com)
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the
* use of this software. Permission is granted to anyone to use this software for
* any purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim
* that you wrote the original software. If you use this software in a product, an
* acknowledgment in the product documentation would be appreciated but is not
* required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "hdCheckbox.h"
hdCheckbox::hdCheckbox(const char *textureOnNormal,
const char *textureOnOver,
const char *textureOffNormal,
const char *textureOffOver,
hdGameWorld* gameWorld) : hdReceiver(gameWorld, true)
{
// create two buttons
m_onButton = new hdButton(textureOnNormal,
textureOnOver,
textureOnOver);
m_offButton = new hdButton(textureOffNormal,
textureOffOver,
textureOffOver);
m_activeButton = m_onButton;
m_callbackObject = NULL;
m_valueChangedCallback = NULL;
}
hdCheckbox::~hdCheckbox()
{
if (m_onButton)
delete m_onButton;
if (m_offButton)
delete m_offButton;
}
void hdCheckbox::SetAs2DBox(const float& x, const float& y, const float& w, const float& h)
{
m_onButton->SetAs2DBox(x, y, w, h);
m_offButton->SetAs2DBox(x, y, w, h);
}
void hdCheckbox::AddValueChangedListener(void *obj, void (*func)(void *, void *))
{
m_callbackObject = obj;
m_valueChangedCallback = func;
}
bool hdCheckbox::MouseDown(float x, float y)
{
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
return m_activeButton->MouseDown(x, y);
}
bool hdCheckbox::MouseOver(float x, float y)
{
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
return m_activeButton->MouseOver(x, y);
}
bool hdCheckbox::MouseUp(float x, float y)
{
bool res;
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
res = m_activeButton->MouseUp(x, y);
if (res)
{
Toggle();
if (m_callbackObject != NULL && m_valueChangedCallback != NULL)
{
(*m_valueChangedCallback)(m_callbackObject, this);
}
}
return res;
}
bool hdCheckbox::MouseDoubleClick(float x, float y)
{
if (!this->isEnabled()) return false;
if (this->IsHidden()) return false;
return m_activeButton->MouseDoubleClick(x, y);
}
void hdCheckbox::Toggle()
{
if (m_activeButton == m_onButton)
m_activeButton = m_offButton;
else
m_activeButton = m_onButton;
}
void hdCheckbox::SetOn()
{
hdAssert(m_onButton != NULL);
m_activeButton = m_onButton;
}
void hdCheckbox::SetOff()
{
hdAssert(m_offButton != NULL);
m_activeButton = m_offButton;
}
void hdCheckbox::Draw() const
{
m_activeButton->Draw();
}
bool hdCheckbox::IsOn() const
{
return (m_activeButton == m_onButton);
}
| 24.081081 | 91 | 0.650954 | cdave1 |
17355ed0de9e9dcea7114cf843555260fdaff62f | 1,005 | cpp | C++ | XiaomiOJ/013.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | XiaomiOJ/013.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | XiaomiOJ/013.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | //Author:LanceYu
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cctype>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<iostream>
#include<string>
#include<queue>
#include<set>
#include<algorithm>
#include<complex>
#include<stack>
#include<bitset>
#include<iomanip>
#define ll long long
using namespace std;
const double clf=1e-8;
const int MMAX=0x7fffffff;
const int INF=0xfffffff;
const int mod=1e9+7;
struct node{
int hz=0,ori;
}x[10001];
bool cmp(const node a,const node b)
{
return a.hz>b.hz;
}
int main()
{
ios::sync_with_stdio(false);
//freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin);
//freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout);
string s;
cin>>s;
int i=0,n,t;
for(int i=0;i<10001;i++)
x[i].ori=i;
for(int i=0;i<s.length();i++)
if(s[i]==',')
s[i]=' ';
istringstream ss(s);
while(ss>>t)
x[t].hz++;
sort(x,x+10001,cmp);
cin>>t;
for(int i=0;i<t;i++)
{
if(i==0)cout<<x[i].ori;
else cout<<","<<x[i].ori;
}
return 0;
}
| 17.631579 | 61 | 0.648756 | windcry1 |
173b921fda55206dbe026d881b58c7644dc57173 | 3,519 | cc | C++ | src/uDepot/rwlock-pagefault-trt.cc | nik-io/uDepot | 06b94b7f2438b38b46572ede28072e24997e40c6 | [
"BSD-3-Clause"
] | null | null | null | src/uDepot/rwlock-pagefault-trt.cc | nik-io/uDepot | 06b94b7f2438b38b46572ede28072e24997e40c6 | [
"BSD-3-Clause"
] | null | null | null | src/uDepot/rwlock-pagefault-trt.cc | nik-io/uDepot | 06b94b7f2438b38b46572ede28072e24997e40c6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 International Business Machines
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Authors: Nikolas Ioannou (nio@zurich.ibm.com),
* Kornilios Kourtis (kou@zurich.ibm.com, kornilios@gmail.com)
*
*/
#include <stdio.h>
#include <signal.h>
#include "util/debug.h"
#include "uDepot/rwlock-pagefault-trt.hh"
#include "trt/uapi/trt.hh"
namespace udepot {
static struct sigaction oldact_g;
static void
sigsegv_handler(int sig, siginfo_t *siginfo, void *uctx)
{
UDEPOT_DBG("Got SIGSEGV!\n");
trt::Task *t = &trt::T::self();
if (t->rwpf_rb_set != 1) {
//trt_err("SIGSEGV without rollback set. Calling old handler\n");
return (oldact_g.sa_sigaction(sig, siginfo, uctx));
}
/* MAYBE TODO: register and check address for faults */
//siglongjmp(t->rwpf_rb_jmp, 1);
longjmp(t->rwpf_rb_jmp, 1);
}
rwlock_pagefault_trt::rwlock_pagefault_trt() : rwpf_trt_ao_(nullptr) {
pthread_spin_init(&rwpf_trt_lock_, 0);
}
rwlock_pagefault_trt::~rwlock_pagefault_trt() {}
int
rwlock_pagefault_trt::init()
{
struct sigaction sa = {0};
sa.sa_sigaction = sigsegv_handler;
sa.sa_flags = SA_SIGINFO;
if (sigaction(SIGSEGV, &sa, &oldact_g) == -1) {
perror("sigaction");
return errno;
}
return 0;
}
// the read_lock() part
void
rwlock_pagefault_trt::rd_enter()
{
for (;;) {
bool ok = rwlock_pagefault_base::rd_try_lock();
if (ok) {
return;
}
// failed: there is a resize in-progress: sleep
trt::Waitset ws;
trt::Future future;
// use a move constructor under the lock for getting the async object
// reference. If there no reference exists, retry. The future will
// subscribe to the async objet under the lock, so we are sure that it's
// not getting away.
bool retry = false;
pthread_spin_lock(&rwpf_trt_lock_);
if (rwpf_trt_ao_ == nullptr)
retry = true;
else
future = trt::Future(rwpf_trt_ao_, &ws, nullptr);
pthread_spin_unlock(&rwpf_trt_lock_);
if (retry)
continue;
// wait
trt::Future *f__ __attribute__((unused)) = ws.wait_();
assert(f__ == &future);
assert(future.get_val() == 0xbeef);
future.drop_ref();
}
}
void
rwlock_pagefault_trt::rd_exit()
{
rwlock_pagefault_base::rd_unlock();
}
void
rwlock_pagefault_trt::write_enter()
{
// before we start draining readers, we need a few things first.
// first, we should be the only writer -- other writers are assumed to be
// excluded externally.
assert(rwpf_trt_ao_ == nullptr);
// Allocate an async object. It will be deallocated when it's reference
// count reaches zero.
//
// Since readers are not blocked yet, the lock is probably not needed.
// But, I take it anyway since we are already on the slow path.
pthread_spin_lock(&rwpf_trt_lock_);
rwpf_trt_ao_ = trt::AsyncObj::allocate();
if (rwpf_trt_ao_ == nullptr) {
perror("malloc");
abort();
}
pthread_spin_unlock(&rwpf_trt_lock_);
// start draining readers
rwlock_pagefault_base::wr_enter();
}
void
rwlock_pagefault_trt::write_wait_readers()
{
while (!rwlock_pagefault_base::wr_ready())
trt::T::yield();
}
void
rwlock_pagefault_trt::write_exit()
{
trt::AsyncObj *old_ao = nullptr;
// remove the AsyncObj reference under the lock
pthread_spin_lock(&rwpf_trt_lock_);
std::swap(old_ao, rwpf_trt_ao_);
pthread_spin_unlock(&rwpf_trt_lock_);
// let readers pass
rwlock_pagefault_base::wr_exit();
// notify readers sleeping
assert(old_ao != nullptr);
trt::T::notify(old_ao, 0xbeef, trt::NotifyPolicy::LastTaskScheduler);
}
} // end namespace udepot
| 23.46 | 74 | 0.709577 | nik-io |
173c520dcab7811eaf918e0861331b720bcedaa9 | 517 | hpp | C++ | src/include/vuh/core/core.hpp | wangqiang1588/vuh | 20450436022b5386a0da3a82062bd49813993180 | [
"MIT"
] | null | null | null | src/include/vuh/core/core.hpp | wangqiang1588/vuh | 20450436022b5386a0da3a82062bd49813993180 | [
"MIT"
] | null | null | null | src/include/vuh/core/core.hpp | wangqiang1588/vuh | 20450436022b5386a0da3a82062bd49813993180 | [
"MIT"
] | null | null | null | #pragma once
#include "vnh.hpp"
namespace vuh {
class core {
public:
core() : _res(vhn::Result::eSuccess) { }
explicit core(vhn::Result res) : _res(res) { }
public:
virtual vhn::Result error() const { return _res; };
virtual bool success() const { return vhn::Result::eSuccess == _res; }
virtual std::string error_to_string() const { return vhn::to_string(_res); };
protected:
vhn::Result _res; ///< result of vulkan's api
};
}
| 23.5 | 85 | 0.572534 | wangqiang1588 |
173f67545228c863bfb4dfd4f32544c6a47b7beb | 848 | cpp | C++ | world/source/Currency.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | world/source/Currency.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | world/source/Currency.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | #include "Currency.hpp"
using namespace std;
Currency::Currency()
{
type = ItemType::ITEM_TYPE_CURRENCY;
symbol = '$';
status = ItemStatus::ITEM_STATUS_UNCURSED;
status_identified = true;
}
Currency::~Currency()
{
}
// Currency is always generated uncursed and shouldn't ever be set to another
// status.
void Currency::set_status(const ItemStatus status_to_ignore)
{
}
void Currency::set_status_identified(const bool new_status_identified)
{
}
bool Currency::additional_item_attributes_match(ItemPtr item) const
{
return true;
}
bool Currency::get_type_always_stacks() const
{
return true;
}
Item* Currency::clone()
{
return new Currency(*this);
}
ClassIdentifier Currency::internal_class_identifier() const
{
return ClassIdentifier::CLASS_ID_CURRENCY;
}
#ifdef UNIT_TESTS
#include "unit_tests/Currency_test.cpp"
#endif
| 16.627451 | 77 | 0.760613 | sidav |
174181d9ea03e20a47edfd7776d7362926c81837 | 6,617 | cpp | C++ | SdkCore/SdkCore/Environment/EnvironmentWindowsMsvc/Implementation/Atom.cpp | DexterDreeeam/DxtSdk2021 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | 1 | 2021-11-18T03:57:54.000Z | 2021-11-18T03:57:54.000Z | SdkCore/SdkCore/Environment/EnvironmentWindowsMsvc/Implementation/Atom.cpp | DexterDreeeam/P9 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | null | null | null | SdkCore/SdkCore/Environment/EnvironmentWindowsMsvc/Implementation/Atom.cpp | DexterDreeeam/P9 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | null | null | null |
#include "../../_Interface.hpp"
#include "../EnvironmentHeader.hpp"
template<typename Ty>
class shadow_class
{
public:
using DataType = volatile Ty;
DataType _data;
};
atom<s64>::atom()
{
assert(_mem_sz >= sizeof(shadow_class<s64>));
new (_mem) volatile s64(0);
}
atom<s64>::atom(const atom<s64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<s64>*);
shadow_self._data = shadow_rhs._data;
}
atom<s64>::atom(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
shadow_self._data = v;
}
atom<s64>::~atom()
{
}
s64 atom<s64>::get() const
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
return shadow_self._data;
}
void atom<s64>::set(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
shadow_self._data = v;
}
atom<s64>& atom<s64>::operator =(const atom<s64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<s64>*);
shadow_self._data = shadow_rhs._data;
return *this;
}
atom<s64>& atom<s64>::operator =(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
shadow_self._data = v;
return *this;
}
s64 atom<s64>::operator ++()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedIncrement(reinterpret_cast<volatile u64*>(&shadow_self._data));
return (s64)ret;
}
s64 atom<s64>::operator ++(int)
{
s64 ret = operator ++();
return ret - 1;
}
s64 atom<s64>::operator --()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedDecrement(reinterpret_cast<volatile u64*>(&shadow_self._data));
return (s64)ret;
}
s64 atom<s64>::operator --(int)
{
s64 ret = operator --();
return ret + 1;
}
s64 atom<s64>::weak_add(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
return shadow_self._data += v;
}
s64 atom<s64>::exchange(s64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedExchange(reinterpret_cast<volatile u64*>(&shadow_self._data), (u64)replace);
return (s64)ret;
}
s64 atom<s64>::compare_exchange(s64 expected, s64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedCompareExchange(reinterpret_cast<volatile u64*>(&shadow_self._data), (u64)replace, (u64)expected);
return (s64)ret;
}
atom<u64>::atom()
{
assert(_mem_sz >= sizeof(shadow_class<u64>));
new (_mem) volatile u64(0);
}
atom<u64>::atom(const atom<u64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<u64>*);
shadow_self._data = shadow_rhs._data;
}
atom<u64>::atom(u64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
shadow_self._data = v;
}
atom<u64>::~atom()
{
}
u64 atom<u64>::get() const
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
return shadow_self._data;
}
void atom<u64>::set(u64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
shadow_self._data = v;
}
atom<u64>& atom<u64>::operator =(const atom<u64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<u64>*);
shadow_self._data = shadow_rhs._data;
return *this;
}
atom<u64>& atom<u64>::operator =(u64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
shadow_self._data = v;
return *this;
}
u64 atom<u64>::operator ++()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedIncrement(&shadow_self._data);
return ret;
}
u64 atom<u64>::operator ++(int)
{
u64 ret = operator ++();
return ret - 1;
}
u64 atom<u64>::operator --()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedDecrement(&shadow_self._data);
return ret;
}
u64 atom<u64>::operator --(int)
{
u64 ret = operator --();
return ret + 1;
}
u64 atom<u64>::weak_add(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
return shadow_self._data += v;
}
u64 atom<u64>::exchange(u64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedExchange(&shadow_self._data, replace);
return ret;
}
u64 atom<u64>::compare_exchange(u64 expected, u64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedCompareExchange(&shadow_self._data, replace, expected);
return ret;
}
atom<void*>::atom()
{
assert(_mem_sz >= sizeof(shadow_class<void*>));
new (_mem) volatile void*(nullptr);
}
atom<void*>::atom(const atom<void*>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<void*>*);
shadow_self._data = shadow_rhs._data;
}
atom<void*>::atom(void* v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
shadow_self._data = v;
}
atom<void*>::~atom()
{
}
void* atom<void*>::get() const
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
return shadow_self._data;
}
void atom<void*>::set(void* v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
shadow_self._data = v;
}
atom<void*>& atom<void*>::operator =(const atom<void*>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<void*>*);
shadow_self._data = shadow_rhs._data;
return *this;
}
atom<void*>& atom<void*>::operator =(void* v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
shadow_self._data = v;
return *this;
}
void* atom<void*>::exchange(void* replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
void* ret = InterlockedExchangePointer(&shadow_self._data, replace);
return (void*)ret;
}
void* atom<void*>::compare_exchange(void* expected, void* replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
void* ret = InterlockedCompareExchangePointer(&shadow_self._data, replace, expected);
return (void*)ret;
}
| 22.130435 | 123 | 0.664652 | DexterDreeeam |
1743046c5a4b7ffe2ae6dac0b5741976c495f261 | 4,200 | cpp | C++ | proxygen/lib/http/codec/compress/HPACKDecodeBuffer.cpp | autoantwort/proxygen | 1cedfc101966163f647241b8c2564d55e4f31454 | [
"BSD-3-Clause"
] | 5,852 | 2015-01-01T06:12:49.000Z | 2022-03-31T07:28:30.000Z | proxygen/lib/http/codec/compress/HPACKDecodeBuffer.cpp | autoantwort/proxygen | 1cedfc101966163f647241b8c2564d55e4f31454 | [
"BSD-3-Clause"
] | 345 | 2015-01-02T22:15:43.000Z | 2022-03-28T23:33:28.000Z | proxygen/lib/http/codec/compress/HPACKDecodeBuffer.cpp | autoantwort/proxygen | 1cedfc101966163f647241b8c2564d55e4f31454 | [
"BSD-3-Clause"
] | 1,485 | 2015-01-04T14:39:26.000Z | 2022-03-22T02:32:08.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <proxygen/lib/http/codec/compress/HPACKDecodeBuffer.h>
#include <limits>
#include <memory>
#include <proxygen/lib/http/codec/compress/Huffman.h>
using folly::IOBuf;
using proxygen::HPACK::DecodeError;
using std::unique_ptr;
namespace proxygen {
void HPACKDecodeBuffer::EOB_LOG(std::string msg, DecodeError code) const {
if (endOfBufferIsError_ || code != DecodeError::BUFFER_UNDERFLOW) {
LOG(ERROR) << msg;
} else {
VLOG(4) << msg;
}
}
bool HPACKDecodeBuffer::empty() {
return remainingBytes_ == 0;
}
uint8_t HPACKDecodeBuffer::next() {
CHECK_GT(remainingBytes_, 0);
// in case we are the end of an IOBuf, peek() will move to the next one
uint8_t byte = peek();
cursor_.skip(1);
remainingBytes_--;
return byte;
}
uint8_t HPACKDecodeBuffer::peek() {
CHECK_GT(remainingBytes_, 0);
if (cursor_.length() == 0) {
cursor_.peek();
}
return *cursor_.data();
}
DecodeError HPACKDecodeBuffer::decodeLiteral(folly::fbstring& literal) {
return decodeLiteral(7, literal);
}
DecodeError HPACKDecodeBuffer::decodeLiteral(uint8_t nbit,
folly::fbstring& literal) {
literal.clear();
if (remainingBytes_ == 0) {
EOB_LOG("remainingBytes_ == 0");
return DecodeError::BUFFER_UNDERFLOW;
}
auto byte = peek();
uint8_t huffmanCheck = uint8_t(1 << nbit);
bool huffman = byte & huffmanCheck;
// extract the size
uint64_t size;
DecodeError result = decodeInteger(nbit, size);
if (result != DecodeError::NONE) {
EOB_LOG("Could not decode literal size", result);
return result;
}
if (size > remainingBytes_) {
EOB_LOG(folly::to<std::string>(
"size(", size, ") > remainingBytes_(", remainingBytes_, ")"));
return DecodeError::BUFFER_UNDERFLOW;
}
if (size > maxLiteralSize_) {
LOG(ERROR) << "Literal too large, size=" << size;
return DecodeError::LITERAL_TOO_LARGE;
}
const uint8_t* data;
unique_ptr<IOBuf> tmpbuf;
// handle the case where the buffer spans multiple buffers
if (cursor_.length() >= size) {
data = cursor_.data();
cursor_.skip(size);
} else {
// temporary buffer to pull the chunks together
tmpbuf = IOBuf::create(size);
// pull() will move the cursor
cursor_.pull(tmpbuf->writableData(), size);
data = tmpbuf->data();
}
if (huffman) {
static auto& huffmanTree = huffman::huffTree();
huffmanTree.decode(data, size, literal);
} else {
literal.append((const char*)data, size);
}
remainingBytes_ -= size;
return DecodeError::NONE;
}
DecodeError HPACKDecodeBuffer::decodeInteger(uint64_t& integer) {
return decodeInteger(8, integer);
}
DecodeError HPACKDecodeBuffer::decodeInteger(uint8_t nbit, uint64_t& integer) {
if (remainingBytes_ == 0) {
EOB_LOG("remainingBytes_ == 0");
return DecodeError::BUFFER_UNDERFLOW;
}
uint8_t byte = next();
uint8_t mask = HPACK::NBIT_MASKS[nbit];
// remove the first (8 - nbit) bits
byte = byte & mask;
integer = byte;
if (byte != mask) {
// the value fit in one byte
return DecodeError::NONE;
}
uint64_t f = 1;
uint32_t fexp = 0;
do {
if (remainingBytes_ == 0) {
EOB_LOG("remainingBytes_ == 0");
return DecodeError::BUFFER_UNDERFLOW;
}
byte = next();
if (fexp > 64) {
// overflow in factorizer, f > 2^64
LOG(ERROR) << "overflow fexp=" << fexp;
return DecodeError::INTEGER_OVERFLOW;
}
uint64_t add = (byte & 127) * f;
if (std::numeric_limits<uint64_t>::max() - integer <= add) {
// overflow detected - we disallow uint64_t max.
LOG(ERROR) << "overflow integer=" << integer << " add=" << add;
return DecodeError::INTEGER_OVERFLOW;
}
integer += add;
f = f << 7;
fexp += 7;
} while (byte & 128);
return DecodeError::NONE;
}
namespace HPACK {
std::ostream& operator<<(std::ostream& os, DecodeError err) {
return os << static_cast<uint32_t>(err);
}
} // namespace HPACK
} // namespace proxygen
| 27.45098 | 79 | 0.65619 | autoantwort |
1743bd2d1a4b7ffc0f888302fc11f462591f5f0d | 3,489 | cc | C++ | 3rdparty/pytorch/caffe2/operators/experimental/c10/cpu/concat_cpu.cc | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | 3rdparty/pytorch/caffe2/operators/experimental/c10/cpu/concat_cpu.cc | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | 3rdparty/pytorch/caffe2/operators/experimental/c10/cpu/concat_cpu.cc | WoodoLee/TorchCraft | 999f68aab9e7d50ed3ae138297226dc95fefc458 | [
"MIT"
] | null | null | null | #include <c10/core/dispatch/KernelRegistration.h>
#include "caffe2/operators/experimental/c10/schemas/concat.h"
#include "caffe2/utils/math.h"
#include "caffe2/core/tensor.h"
using caffe2::BaseContext;
using caffe2::CPUContext;
using caffe2::Tensor;
using caffe2::TensorCPU;
using std::vector;
namespace caffe2 {
namespace {
template <class DataType, class Context>
void concat_op_cpu_impl(
at::ArrayRef<C10Tensor> inputs,
const C10Tensor& output_,
const C10Tensor& split_,
int axis,
int add_axis) {
Tensor output(output_);
Tensor split(split_);
CPUContext context;
split.Resize(vector<int64_t>(1, inputs.size()));
int* axis_data = split.template mutable_data<int>();
int adj_size = Tensor(inputs[0]).dim() + (add_axis ? 1 : 0);
int canonical_axis = caffe2::canonical_axis_index_(axis, adj_size);
CAFFE_ENFORCE_LT(canonical_axis, adj_size, "Axis not in input ndim range.");
for (int i = 1; i < inputs.size(); ++i) {
CAFFE_ENFORCE(
Tensor(inputs[i]).dtype() == Tensor(inputs[0]).dtype(),
"All inputs must have the same type, expected: ",
Tensor(inputs[0]).dtype().name(),
" but got: ",
Tensor(inputs[i]).dtype().name(),
" for input: ",
i);
}
int before = 1, after = 1;
vector<int64_t> output_dims(Tensor(inputs[0]).sizes().vec());
for (int i = 0; i < Tensor(inputs[0]).dim(); ++i) {
if (i == canonical_axis && !add_axis) {
continue;
}
int dim = Tensor(inputs[0]).dim32(i);
if (i < canonical_axis) {
before *= dim;
} else { // i > canonical_axis || i == canonical_axis && add_axis
after *= dim;
}
// check the input dims are compatible.
for (int j = 1; j < inputs.size(); ++j) {
int dim_j = Tensor(inputs[j]).dim32(i);
CAFFE_ENFORCE(
dim == dim_j,
"Expect dimension = ",
dim,
" got ",
dim_j,
" at axis = ",
i,
" for input: ",
j,
". The input tensors can only have different dimensions "
"when arg 'add_axis' = 0 and along the axis = ",
canonical_axis,
" <",
Tensor(inputs[0]).sizes(),
"> vs <",
Tensor(inputs[j]).sizes(),
">.");
}
}
int output_channels = 0;
for (int i = 0; i < inputs.size(); ++i) {
axis_data[i] = add_axis ? 1 : Tensor(inputs[i]).dim32(canonical_axis);
output_channels += axis_data[i];
}
if (add_axis) {
output_dims.insert(output_dims.begin() + canonical_axis, output_channels);
} else {
output_dims[canonical_axis] = output_channels;
}
output.Resize(output_dims);
size_t output_offset = 0;
for (int i = 0; i < inputs.size(); ++i) {
Tensor input(inputs[i]);
auto axis_dim = add_axis ? 1 : input.dim32(canonical_axis);
caffe2::math::CopyMatrix<Context>(
input.itemsize(),
before,
axis_dim * after,
input.raw_data(),
axis_dim * after,
static_cast<char*>(output.raw_mutable_data(Tensor(inputs[0]).dtype())) +
output_offset,
output_channels * after,
static_cast<Context*>(&context),
Tensor(inputs[0]).dtype().copy());
output_offset += axis_dim * after * input.itemsize();
}
}
} // namespace
} // namespace caffe2
namespace c10 {
C10_REGISTER_KERNEL(caffe2::ops::Concat)
.kernel(&caffe2::concat_op_cpu_impl<float, CPUContext>)
.dispatchKey(c10::DeviceTypeId::CPU);
} // namespace c10
| 30.605263 | 80 | 0.602752 | WoodoLee |
174900a72e262fd0c8609f175b386fa1246d7392 | 5,335 | cpp | C++ | CxxProfiler/SyntaxHighlighter.cpp | mmozeiko/CxxProfiler | 5836f2a948cf97ad87bef0e357fd39c95d07189f | [
"Unlicense"
] | 110 | 2016-05-06T09:17:55.000Z | 2022-03-30T02:34:41.000Z | CxxProfiler/SyntaxHighlighter.cpp | mmozeiko/CxxProfiler | 5836f2a948cf97ad87bef0e357fd39c95d07189f | [
"Unlicense"
] | null | null | null | CxxProfiler/SyntaxHighlighter.cpp | mmozeiko/CxxProfiler | 5836f2a948cf97ad87bef0e357fd39c95d07189f | [
"Unlicense"
] | 5 | 2017-10-27T10:59:53.000Z | 2022-01-10T02:24:41.000Z | #include "SyntaxHighlighter.h"
// TODO http://www.kate-editor.org/syntax/3.9/isocpp.xml
SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
{
QTextCharFormat quotationFormat;
quotationFormat.setForeground(Qt::darkRed);
rule.pattern = QRegExp("\".*\"");
rule.pattern.setMinimal(true);
rule.format = quotationFormat;
mRules.append(rule);
rule.pattern = QRegExp("'.*'");
rule.pattern.setMinimal(true);
rule.format = quotationFormat;
mRules.append(rule);
rule.pattern = QRegExp("<[^\\s<]+>");
rule.format = quotationFormat;
mRules.append(rule);
}
mKeywordFormat.setForeground(Qt::blue);
static const char* keywords[] = {
"__abstract", "__alignof", "__asm", "__assume", "__based", "__box",
"__cdecl", "__declspec", "__delegate", "__event", "__fastcall",
"__forceinline", "__gc", "__hook", "__identifier", "__if_exists",
"__if_not_exists", "__inline", "__int16", "__int32", "__int64",
"__int8", "__interface", "__leave", "__m128", "__m128d", "__m128i",
"__m256", "__m256d", "__m256i", "__m64", "__multiple_inheritance",
"__nogc", "__noop", "__pin", "__property", "__raise", "__sealed",
"__single_inheritance", "__stdcall", "__super", "__thiscall",
"__try_cast", "__unaligned", "__unhook", "__uuidof", "__value",
"__vectorcall", "__virtual_inheritance", "__w64", "__wchar_t",
"abstract", "array", "auto", "bool", "break", "case", "catch",
"char", "class", "const", "const_cast", "continue", "decltype",
"default", "delegate", "delete", "deprecated", "dllexport",
"dllimport", "do", "double", "dynamic_cast", "each", "else", "event",
"explicit", "extern", "false", "finally", "float", "for", "friend",
"friend_as", "gcnew", "generic", "goto", "if", "in", "initonly",
"inline", "int", "interface", "interior_ptr", "literal", "long",
"mutable", "naked", "namespace", "new", "noinline", "noreturn",
"nothrow", "novtable", "nullptr", "operator", "private", "property",
"protected", "public", "ref", "register", "reinterpret_cast",
"return", "safecast", "sealed", "selectany", "short", "signed",
"sizeof", "static", "static_assert", "static_cast", "struct",
"switch", "template", "this", "thread", "throw", "true", "try",
"typedef", "typename", "union", "unsigned", "using", "uuid", "value",
"virtual", "void", "volatile", "wchar_t", "while"
};
for (const char* keyword : keywords)
{
QString pattern = QString("\\b%1\\b").arg(keyword);
rule.pattern = QRegExp(pattern);
rule.format = mKeywordFormat;
mRules.append(rule);
}
static const char* preprocKeywords[] = {
"#define", "#error", "#import", "#undef", "#elif", "#if", "#include",
"#using", "#else", "#ifdef", "#line", "#endif", "#ifndef", "#pragma"
};
for (const char* preprocKeyword : preprocKeywords)
{
QString pattern = QString("(\\b|^)%1\\b").arg(preprocKeyword);
rule.pattern = QRegExp(pattern);
rule.format = mKeywordFormat;
mRules.append(rule);
}
{
QTextCharFormat numberFormat;
numberFormat.setForeground(Qt::red);
rule.pattern = QRegExp("\\b[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?f?\\b");
rule.format = numberFormat;
mRules.append(rule);
rule.pattern = QRegExp("\\b0x[0-9a-fA-F]+U?L?L?\\b");
rule.format = numberFormat;
mRules.append(rule);
rule.pattern = QRegExp("\\b[0-9]+\\b");
rule.format = numberFormat;
mRules.append(rule);
}
{
QTextCharFormat singleLineCommentFormat;
singleLineCommentFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
mRules.append(rule);
}
mMultiLineCommentFormat.setForeground(Qt::darkGreen);
mCommentStart = QRegExp("/\\*");
mCommentEnd = QRegExp("\\*/");
}
SyntaxHighlighter::~SyntaxHighlighter()
{
}
void SyntaxHighlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule& rule : mRules)
{
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0)
{
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
{
startIndex = mCommentStart.indexIn(text);
}
while (startIndex >= 0)
{
int endIndex = mCommentEnd.indexIn(text, startIndex);
int commentLength;
if (endIndex == -1)
{
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
}
else
{
commentLength = endIndex - startIndex + mCommentEnd.matchedLength();
}
setFormat(startIndex, commentLength, mMultiLineCommentFormat);
startIndex = mCommentStart.indexIn(text, startIndex + commentLength);
}
} | 34.869281 | 80 | 0.582193 | mmozeiko |
174b7f091a9b143d165e798c5b75ccf3a04ed8ec | 3,908 | cpp | C++ | PyQt6-6.0.0/qpy/QtCore/qpycore_init.cpp | sonerkcardak/python-detailed-assistant | 161b82289c5ae7149fe638ba6a5192b6aa6833d8 | [
"Apache-2.0"
] | null | null | null | PyQt6-6.0.0/qpy/QtCore/qpycore_init.cpp | sonerkcardak/python-detailed-assistant | 161b82289c5ae7149fe638ba6a5192b6aa6833d8 | [
"Apache-2.0"
] | null | null | null | PyQt6-6.0.0/qpy/QtCore/qpycore_init.cpp | sonerkcardak/python-detailed-assistant | 161b82289c5ae7149fe638ba6a5192b6aa6833d8 | [
"Apache-2.0"
] | null | null | null | // This is the initialisation support code for the QtCore module.
//
// Copyright (c) 2021 Riverbank Computing Limited <info@riverbankcomputing.com>
//
// This file is part of PyQt6.
//
// This file may be used under the terms of the GNU General Public License
// version 3.0 as published by the Free Software Foundation and appearing in
// the file LICENSE included in the packaging of this file. Please review the
// following information to ensure the GNU General Public License version 3.0
// requirements will be met: http://www.gnu.org/copyleft/gpl.html.
//
// If you do not wish to use this file under the terms of the GPL version 3.0
// then you may purchase a commercial license. For more information contact
// info@riverbankcomputing.com.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#include <Python.h>
#include "qpycore_api.h"
#include "qpycore_public_api.h"
#include "qpycore_pyqtslotproxy.h"
#include "qpycore_qobject_helpers.h"
#include "sipAPIQtCore.h"
#include <QCoreApplication>
// Set if any QCoreApplication (or sub-class) instance was created from Python.
bool qpycore_created_qapp;
// This is called to clean up on exit. It is done in case the QCoreApplication
// dealloc code hasn't been called.
static PyObject *cleanup_on_exit(PyObject *, PyObject *)
{
pyqt6_cleanup_qobjects();
// Never destroy a QCoreApplication if we didn't create it (eg. if we are
// embedded in a C++ application).
if (qpycore_created_qapp)
{
QCoreApplication *app = QCoreApplication::instance();
if (app)
{
Py_BEGIN_ALLOW_THREADS
delete app;
Py_END_ALLOW_THREADS
}
}
Py_INCREF(Py_None);
return Py_None;
}
// Perform any required initialisation.
void qpycore_init()
{
// We haven't created a QCoreApplication instance.
qpycore_created_qapp = false;
// Export the private helpers, ie. those that should not be used by
// external handwritten code.
sipExportSymbol("qtcore_qt_metaobject",
(void *)qpycore_qobject_metaobject);
sipExportSymbol("qtcore_qt_metacall", (void *)qpycore_qobject_qt_metacall);
sipExportSymbol("qtcore_qt_metacast", (void *)qpycore_qobject_qt_metacast);
sipExportSymbol("qtcore_qobject_sender",
(void *)PyQtSlotProxy::lastSender);
// Export the public API.
sipExportSymbol("pyqt6_cleanup_qobjects", (void *)pyqt6_cleanup_qobjects);
sipExportSymbol("pyqt6_err_print", (void *)pyqt6_err_print);
sipExportSymbol("pyqt6_from_argv_list", (void *)pyqt6_from_argv_list);
sipExportSymbol("pyqt6_from_qvariant_by_type",
(void *)pyqt6_from_qvariant_by_type);
sipExportSymbol("pyqt6_get_connection_parts",
(void *)pyqt6_get_connection_parts);
sipExportSymbol("pyqt6_get_pyqtsignal_parts",
(void *)pyqt6_get_pyqtsignal_parts);
sipExportSymbol("pyqt6_get_pyqtslot_parts",
(void *)pyqt6_get_pyqtslot_parts);
sipExportSymbol("pyqt6_get_qmetaobject", (void *)pyqt6_get_qmetaobject);
sipExportSymbol("pyqt6_get_signal_signature",
(void *)pyqt6_get_signal_signature);
sipExportSymbol("pyqt6_register_from_qvariant_convertor",
(void *)pyqt6_register_from_qvariant_convertor);
sipExportSymbol("pyqt6_register_to_qvariant_convertor",
(void *)pyqt6_register_to_qvariant_convertor);
sipExportSymbol("pyqt6_register_to_qvariant_data_convertor",
(void *)pyqt6_register_to_qvariant_data_convertor);
sipExportSymbol("pyqt6_update_argv_list", (void *)pyqt6_update_argv_list);
// Register the cleanup function.
static PyMethodDef cleanup_md = {
"_qtcore_cleanup", cleanup_on_exit, METH_NOARGS, SIP_NULLPTR
};
sipRegisterExitNotifier(&cleanup_md);
}
| 36.523364 | 79 | 0.730297 | sonerkcardak |
174c9629aab8e0ea818e6c47f1e9614bb651452a | 3,457 | hpp | C++ | src/contrib/mlir/runtime/cpu/cpu_runtime.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/runtime/cpu/cpu_runtime.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/runtime/cpu/cpu_runtime.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
// NOTE: This file follows nGraph format style.
// Follows nGraph naming convention for public APIs only, else MLIR naming
// convention.
#pragma once
#include <memory>
#include <mlir/ExecutionEngine/ExecutionEngine.h>
#include <mlir/IR/Builders.h>
#include <mlir/IR/Module.h>
#include <mlir/IR/Types.h>
#include "contrib/mlir/backend/backend.hpp"
#include "contrib/mlir/runtime/runtime.hpp"
namespace ngraph
{
namespace runtime
{
namespace ngmlir
{
struct StaticMemRef
{
void* allocatedPtr;
void* alignedPtr;
int64_t offset;
int64_t shapeAndStrides[];
};
struct UnrankedMemRef
{
int64_t rank;
StaticMemRef* memRefDescPtr;
};
/// A CPU Runtime is an MLIR runtime that owns an MLIR context and a module
/// The module should be in LLVM dialect and ready to be lowered via an MLIR
/// ExecutionEngine. The runtime owns the context and must out-live any MLIR
/// code Compilation and execution.
class MLIRCPURuntime : public MLIRRuntime
{
public:
/// Executes a pre-compiled subgraph
void run(const std::vector<MemRefArg>& args, bool firstIteration) override;
private:
void run_internal(const std::vector<MemRefArg>& args, bool firstIteration);
// Bind external tensors to MLIR module entry point
void bindArguments(const std::vector<MemRefArg>& args);
// Invokes an MLIR module entry point with bound arguments
void execute(bool firstIteration);
// Cleans up allocated args
void cleanup();
/// Helper to create memref arguments for MLIR function signature
llvm::SmallVector<void*, 8> allocateMemrefArgs();
/// Helper to allocate a default MemRef descriptor for LLVM. Handles static
/// shapes
/// only for now.
StaticMemRef* allocateDefaultMemrefDescriptor(size_t);
private:
// Pointers to externally allocated memory for sub-graph's input and output
// tensors.
const std::vector<MemRefArg>* m_externalTensors;
// Arguments for the MLIR function generated for the nGraph sub-graph.
llvm::SmallVector<void*, 8> m_invokeArgs;
std::unique_ptr<::mlir::ExecutionEngine> m_engine;
std::vector<size_t> m_ranks;
};
}
}
}
| 38.411111 | 91 | 0.581429 | pqLee |
174dd2d6948632aafc858872c8c037ac8ba992be | 10,164 | cpp | C++ | spindash/spindash.cpp | Kazade/Spindash | 45ccbafe1941d65823a67880270c165d3888de21 | [
"BSD-2-Clause-FreeBSD"
] | 3 | 2015-12-20T20:59:29.000Z | 2019-02-24T00:54:28.000Z | spindash/spindash.cpp | Kazade/Spindash | 45ccbafe1941d65823a67880270c165d3888de21 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | spindash/spindash.cpp | Kazade/Spindash | 45ccbafe1941d65823a67880270c165d3888de21 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "kazbase/logging.h"
#include "spindash.h"
#include "character.h"
#include "world.h"
void sdCharacterLeftPressed(SDuint character) {
Character* c = Character::get(character);
c->move_left();
}
void sdCharacterRightPressed(SDuint character) {
Character* c = Character::get(character);
c->move_right();
}
void sdCharacterUpPressed(SDuint character) {
Character* c = Character::get(character);
c->move_up();
}
void sdCharacterDownPressed(SDuint character) {
Character* c = Character::get(character);
c->move_down();
}
void sdCharacterJumpPressed(SDuint character) {
Character* c = Character::get(character);
c->jump();
}
SDDirection sdCharacterFacingDirection(SDuint character) {
Character* c = Character::get(character);
return c->facing();
}
SDAnimationState sdCharacterAnimationState(SDuint character) {
Character* c = Character::get(character);
return c->animation_state();
}
SDfloat sdCharacterGetWidth(SDuint character) {
Character* c = Character::get(character);
return c->width();
}
SDbool sdCharacterIsGrounded(SDuint character) {
Character* c = Character::get(character);
return c->is_grounded();
}
SDbool sdObjectIsCharacter(SDuint object) {
Character* c = Character::get(object);
return (c) ? true: false;
}
void sdCharacterSetGroundSpeed(SDuint character, SDfloat value) {
Character* c = Character::get(character);
c->set_ground_speed(value);
}
SDfloat sdCharacterGetGroundSpeed(SDuint character) {
Character* c = Character::get(character);
return c->ground_speed();
}
void sdCharacterEnableSkill(SDuint character, sdSkill skill) {
Character* c = Character::get(character);
c->enable_skill(skill);
}
void sdCharacterDisableSkill(SDuint character, sdSkill skill) {
Character* c = Character::get(character);
c->disable_skill(skill);
}
SDbool sdCharacterSkillEnabled(SDuint character, sdSkill skill) {
Character* c = Character::get(character);
return c->skill_enabled(skill);
}
SDfloat sdCharacterGetSpindashCharge(SDuint character) {
Character* c = Character::get(character);
return c->spindash_charge();
}
void sdCharacterOverrideSetting(const char* setting, float value) {
Character::override_setting(setting, value);
}
void sdObjectDestroy(SDuint entity) {
Object* obj = Object::get(entity);
if(!obj) {
L_WARN("sdObjectDestroy: No such object");
return;
}
obj->world()->destroy_object(entity);
}
void sdObjectSetPosition(SDuint object, SDfloat x, SDfloat y) {
Object* obj = Object::get(object);
obj->set_position(x, y);
}
void sdObjectGetPosition(SDuint object, SDfloat* x, SDfloat* y) {
Object* obj = Object::get(object);
*x = obj->position().x;
*y = obj->position().y;
}
SDfloat sdObjectGetPositionX(SDuint object) {
Object* obj = Object::get(object);
return obj->position().x;
}
SDfloat sdObjectGetPositionY(SDuint object) {
Object* obj = Object::get(object);
return obj->position().y;
}
SDfloat sdObjectGetSpeedX(SDuint object) {
Object* obj = Object::get(object);
return obj->velocity().x;
}
SDfloat sdObjectGetSpeedY(SDuint object) {
Object* obj = Object::get(object);
return obj->velocity().y;
}
void sdObjectSetSpeedX(SDuint object, SDfloat x) {
Object* obj = Object::get(object);
obj->set_velocity(x, obj->velocity().y);
}
void sdObjectSetSpeedY(SDuint object, SDfloat y) {
Object* obj = Object::get(object);
obj->set_velocity(obj->velocity().x, y);
}
void sdObjectSetFixed(SDuint object, SDbool value) {
Object* obj = Object::get(object);
obj->set_fixed(value);
}
SDfloat sdObjectGetRotation(SDuint object) {
Object* obj = Object::get(object);
return obj->rotation();
}
SDuint sdBoxCreate(SDuint world_id, SDfloat width, SDfloat height) {
World* world = World::get(world_id);
return world->new_box(width, height);
}
SDuint sdSpringCreate(SDuint world_id, SDfloat angle, SDfloat power) {
World* world = World::get(world_id);
return world->new_spring(power, angle);
}
/**
@brief Creates a new physical world
This function creates an empty world ready to start accepting
new entities and polygons.
*/
SDuint sdWorldCreate() {
return World::create();
}
/** \brief Destroys a world
*
* \param world - The world to destroy
*
* Destroys a world and its contents (polygons, entities etc.)
*/
void sdWorldDestroy(SDuint world) {
World::destroy(world);
}
void sdWorldAddTriangle(SDuint world_id, kmVec2* points) {
World* world = World::get(world_id);
if(!world) {
//Log error
return;
}
world->add_triangle(points[0], points[1], points[2]);
}
void sdWorldAddBox(SDuint world_id, kmVec2* points) {
World* world = World::get(world_id);
if(!world) {
//Log error
return;
}
world->add_box(points[0], points[1], points[2], points[3]);
}
void sdWorldAddMesh(SDuint world_id, SDuint num_triangles, kmVec2* points) {
for(SDuint i = 0; i < num_triangles; ++i) {
kmVec2 tri[3];
kmVec2Assign(&tri[0], &points[i * 3]);
kmVec2Assign(&tri[1], &points[(i * 3) + 1]);
kmVec2Assign(&tri[2], &points[(i * 3) + 2]);
sdWorldAddTriangle(world_id, tri);
}
}
void sdWorldRemoveTriangles(SDuint world_id) {
World* world = World::get(world_id);
assert(world);
world->remove_all_triangles();
}
void sdWorldStep(SDuint world_id, SDfloat dt) {
World* world = World::get(world_id);
if(!world) {
//Log error
return;
}
world->update(dt);
}
SDuint64 sdWorldGetStepCounter(SDuint world_id) {
World* world = World::get(world_id);
return world->step_counter();
}
/**
* Mainly for testing, constructs a loop out of triangles
*/
void sdWorldConstructLoop(SDuint world, SDfloat left, SDfloat top,
SDfloat width) {
SDfloat thickness = width * 0.1;
SDfloat height = width;
SDfloat radius = (width - (thickness * 2)) / 2.0;
kmVec2 tmp;
const SDuint slices = 40;
//Generate the points of a circle
std::vector<kmVec2> circle_points;
for(SDuint i = 0; i < slices; ++i) {
SDfloat a = kmDegreesToRadians((360.0 / SDfloat(slices)) * (SDfloat)i);
kmVec2Fill(&tmp, radius * cos(a), radius * sin(a));
tmp.x += (left + radius) + thickness;
tmp.y += (top - radius) - thickness;
circle_points.push_back(tmp);
}
//Now, build the surrounding triangles
kmVec2 points[3];
/*kmVec2Fill(&points[0], left, top - height); //Bottom left of loop
kmVec2Fill(&points[1], left + width, top - height); //Bottom right of loop
kmVec2Fill(&points[2], circle_points[0].x, circle_points[0].y);
sdWorldAddTriangle(world, points);*/
for(SDuint i = 0; i < slices / 4; ++i) {
kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y);
kmVec2Fill(&points[1], left + width, top); //Top right of loop
kmVec2Fill(&points[2], circle_points[i + 1].x, circle_points[i + 1].y);
sdWorldAddTriangle(world, points);
}
for(SDuint i = slices / 4; i < ((slices / 4) * 2); ++i) {
kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y);
kmVec2Fill(&points[1], left, top); //Top left of loop
kmVec2Fill(&points[2], circle_points[i+1].x, circle_points[i+1].y);
sdWorldAddTriangle(world, points);
}
/*
for(SDuint i = (slices / 4) * 2; i < ((slices / 4) * 3); ++i) {
kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y);
kmVec2Fill(&points[1], left, top - height); //Bottom right of the loop
kmVec2Fill(&points[2], circle_points[i+1].x, circle_points[i+1].y);
sdWorldAddTriangle(world, points);
}*/
for(SDuint i = (slices / 4) * 3; i < slices ; ++i) {
kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y);
kmVec2Fill(&points[1], left + width, top - height); //Bottom right of the loop
if(i < slices -1 ) {
kmVec2Fill(&points[2], circle_points[i+1].x, circle_points[i+1].y);
} else {
kmVec2Fill(&points[2], circle_points[0].x, circle_points[0].y);
}
sdWorldAddTriangle(world, points);
}
}
void sdWorldSetCompileGeometryCallback(SDuint world_id, SDCompileGeometryCallback callback, void* data) {
World* world = World::get(world_id);
world->set_compile_callback(callback, data);
}
void sdWorldSetRenderGeometryCallback(SDuint world_id, SDRenderGeometryCallback callback, void* data) {
World* world = World::get(world_id);
world->set_render_callback(callback, data);
}
void sdWorldRender(SDuint world_id) {
World* world = World::get(world_id);
return world->render();
}
void sdWorldDebugEnable(SDuint world_id) {
World* world = World::get(world_id);
return world->enable_debug_mode();
}
void sdWorldDebugStep(SDuint world_id, double step) {
World* world = World::get(world_id);
return world->debug_step(step);
}
void sdWorldDebugDisable(SDuint world_id) {
World* world = World::get(world_id);
return world->disable_debug_mode();
}
SDbool sdWorldDebugIsEnabled(SDuint world_id) {
World* world = World::get(world_id);
return world->debug_mode_enabled();
}
void sdWorldCameraTarget(SDuint world_id, SDuint object) {
World* world = World::get(world_id);
world->set_camera_target(object);
}
void sdWorldCameraGetPosition(SDuint world_id, SDfloat* x, SDfloat* y) {
World* world = World::get(world_id);
const kmVec2& pos = world->camera_position();
*x = pos.x;
*y = pos.y;
}
void sdWorldSetObjectCollisionCallback(SDuint world_id, ObjectCollisionCallback callback, void* user_data) {
/*
* Sets the callback which is called when a collision is detected between two objects.
*
* We bind the user data to the callback here so we don't have to worry about it later.
*/
World* world = World::get(world_id);
using namespace std::placeholders;
InternalObjectCollisionCallback cb = std::bind(callback, _1, _2, _3, _4, user_data);
world->set_object_collision_callback(cb);
}
| 27.923077 | 108 | 0.66647 | Kazade |
174e28567b7f8f09e81209419631ecd072a5b649 | 1,523 | cpp | C++ | src/TaskManager/src/system2.cpp | RemiMattheyDoret/TaskManager | bea51ba9fcdf7390b57148bfa8adba75f25dddaa | [
"MIT"
] | null | null | null | src/TaskManager/src/system2.cpp | RemiMattheyDoret/TaskManager | bea51ba9fcdf7390b57148bfa8adba75f25dddaa | [
"MIT"
] | null | null | null | src/TaskManager/src/system2.cpp | RemiMattheyDoret/TaskManager | bea51ba9fcdf7390b57148bfa8adba75f25dddaa | [
"MIT"
] | null | null | null |
/*
system2 runs a shell command in the background and return the PID.
I stole this piece of code from https://stackoverflow.com/questions/22802902/how-to-get-pid-of-process-executed-with-system-command-in-c and modified it a little bit to fit my needs
system2() does not pauses like system(). It is therefore easier to get the PID from the submitted process.
*/
#include "TypeDefinitions.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include "system2.h"
PID_t system2(const char * command)
{
//std::cout << command << "\n";
int p_stdin[2];
int p_stdout[2];
PID_t pid;
if (pipe(p_stdin) == -1)
return -1;
if (pipe(p_stdout) == -1) {
close(p_stdin[0]);
close(p_stdin[1]);
return -1;
}
pid = fork();
if (pid < 0) {
close(p_stdin[0]);
close(p_stdin[1]);
close(p_stdout[0]);
close(p_stdout[1]);
return pid;
} else if (pid == 0) {
close(p_stdin[1]);
dup2(p_stdin[0], 0);
close(p_stdout[0]);
dup2(p_stdout[1], 1);
dup2(::open("/dev/null", O_RDONLY), 2);
/// Close all other descriptors for the safety sake.
for (int i = 3; i < 4096; ++i)
::close(i);
setsid();
execl("/bin/sh", "sh", "-c", command, NULL);
_exit(1);
}
close(p_stdin[0]);
close(p_stdout[1]);
//std::cout << "pid = " << pid << std::endl;
return pid;
}
| 22.397059 | 185 | 0.560079 | RemiMattheyDoret |
17562622d3119f56a683652e446b6d9e8af2cb2f | 13,271 | cpp | C++ | src/3ds/Graphics.cpp | mysterypaint/Hmm2 | 61e7b6566c1bf3590dde055a7107d486db03b077 | [
"MIT"
] | null | null | null | src/3ds/Graphics.cpp | mysterypaint/Hmm2 | 61e7b6566c1bf3590dde055a7107d486db03b077 | [
"MIT"
] | null | null | null | src/3ds/Graphics.cpp | mysterypaint/Hmm2 | 61e7b6566c1bf3590dde055a7107d486db03b077 | [
"MIT"
] | null | null | null | #include "Graphics.hpp"
#include "../PHL.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../Resources.hpp"
PHL_Surface db = {0};
PHL_Surface backBuffer = {0};
PHL_Surface dbAlt = {0};
PHL_Surface backBufferAlt = {0};
const int cWidth = 320;
const int cHeight = 240;
Screen scrnTop = {
GFX_TOP,
GFX_LEFT,
400,
240
};
Screen scrnBottom = {
GFX_BOTTOM,
GFX_LEFT,
cWidth,
cHeight
};
Screen* activeScreen = nullptr; // Where graphics get rendered to
#ifdef _3DS
Screen* debugScreen = nullptr; // Bottom screen console, for debugging (or swapping screen locations)
#endif
PHL_Rect offset;
void PHL_GraphicsInit() {
gfxInitDefault();
//Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
//gfxSet3D(false);
//consoleDebugInit(debugDevice_CONSOLE);
activeScreen = &scrnBottom;
debugScreen = &scrnTop;
PHL_ResetDrawbuffer();
//Create background image
backBuffer = PHL_NewSurface(cWidth * 2, cHeight * 2);
dbAlt = PHL_NewSurface(cWidth * 2, cHeight * 2);
backBufferAlt = PHL_NewSurface(cWidth * 2, cHeight * 2);
}
void PHL_GraphicsExit() {
gfxExit();
}
void PHL_StartDrawing() {
PHL_ResetDrawbuffer();
gfxFlushBuffers();
}
void PHL_EndDrawing() {
PHL_DrawOtherScreen();
gfxSwapBuffers();
gspWaitForVBlank();
}
void PHL_SetDrawbuffer(PHL_Surface surf) {
db = surf;
offset.w = db.width;
offset.h = db.height;
offset.x = 0;
offset.y = 0;
}
void PHL_ResetDrawbuffer() {
db.width = activeScreen->width;
db.height = activeScreen->height;
db.pxdata = gfxGetFramebuffer(activeScreen->screen, activeScreen->side, NULL, NULL);
offset.w = cWidth;
offset.h = cHeight;
offset.x = (activeScreen->width - offset.w) / 2;
offset.y = (activeScreen->height - offset.h) / 2;
}
PHL_RGB PHL_NewRGB(uint8_t r, uint8_t g, uint8_t b) {
PHL_RGB c = { r, g, b };
return c;
}
void PHL_SetColorKey(PHL_Surface surf, uint8_t r, uint8_t g, uint8_t b) {
PHL_RGB key = { r, g, b };
surf.colorKey = key;
}
PHL_Surface PHL_NewSurface(uint16_t w, uint16_t h) {
PHL_Surface surf;
surf.width = w / 2;
surf.height = h / 2;
surf.pxdata = (uint8_t *) malloc(surf.width * surf.height * 3 * sizeof(uint8_t));
surf.colorKey = PHL_NewRGB(0xFF, 0x00, 0xFF);
return surf;
}
void PHL_FreeSurface(PHL_Surface surf) {
if (surf.pxdata != NULL) {
free(surf.pxdata);
surf.pxdata = NULL;
}
}
PHL_Surface PHL_LoadTexture(int _img_index) {
PHL_Surface surf;
std::string _f_in = "romfs:/graphics/";
int fileSize = 77880; // The default filesize, in bytes (because nearly all the graphics in the game are this size)
switch(_img_index) {
case sprPlayer:
_f_in += "test_player.bmp";
fileSize = 12342;
break;
case sprTile0:
_f_in += "tile0.bmp";
fileSize = 1142;
break;
case sprProt1:
_f_in += "prot1.bmp";
break;
case sprTitle:
_f_in += "title.bmp";
break;
case sprMapG00:
_f_in += "mapg00.bmp";
break;
case sprMapG01:
_f_in += "mapg01.bmp";
break;
case sprMapG02:
_f_in += "mapg02.bmp";
break;
case sprMapG03:
_f_in += "mapg03.bmp";
break;
case sprMapG04:
_f_in += "mapg04.bmp";
break;
case sprMapG05:
_f_in += "mapg05.bmp";
break;
case sprMapG06:
_f_in += "mapg06.bmp";
break;
case sprMapG07:
_f_in += "mapg07.bmp";
break;
case sprMapG08:
_f_in += "mapg08.bmp";
break;
case sprMapG09:
_f_in += "mapg09.bmp";
break;
case sprMapG10:
_f_in += "mapg10.bmp";
break;
case sprMapG11:
_f_in += "mapg11.bmp";
break;
case sprMapG12:
_f_in += "mapg12.bmp";
break;
case sprMapG13:
_f_in += "mapg13.bmp";
break;
case sprMapG14:
_f_in += "mapg14.bmp";
break;
case sprMapG15:
_f_in += "mapg15.bmp";
break;
case sprMapG16:
_f_in += "mapg16.bmp";
break;
case sprMapG17:
_f_in += "mapg17.bmp";
break;
case sprMapG18:
_f_in += "mapg18.bmp";
break;
case sprMapG19:
_f_in += "mapg19.bmp";
break;
case sprMapG20:
_f_in += "mapg20.bmp";
break;
case sprMapG21:
_f_in += "mapg21.bmp";
break;
case sprMapG22:
_f_in += "mapg22.bmp";
break;
case sprMapG31:
_f_in += "mapg31.bmp";
break;
case sprMapG32:
_f_in += "mapg32.bmp";
break;
default:
fileSize = 77880;
}
FILE * f;
if ((f = fopen(_f_in.c_str(), "rb"))) {
//Save bmp data
uint8_t* bmpFile = (uint8_t*) malloc(fileSize * sizeof(uint8_t));
fread(bmpFile, fileSize, 1, f);
fclose(f);
//Create surface
uint16_t w, h;
memcpy(&w, &bmpFile[18], 2);
memcpy(&h, &bmpFile[22], 2);
surf = PHL_NewSurface(w * 2, h * 2);
//Load Palette
PHL_RGB palette[20][18];
int count = 0;
for (int dx = 0; dx < 20; dx++) {
for (int dy = 0; dy < 16; dy++) {
palette[dx][dy].b = bmpFile[54 + count];
palette[dx][dy].g = bmpFile[54 + count + 1];
palette[dx][dy].r = bmpFile[54 + count + 2];
count += 4;
}
}
//Fill pixels
count = 0;
for (int dx = w; dx > 0; dx--) {
for (int dy = 0; dy < h; dy++) {
int pix = w - dx + w * dy;
int px = bmpFile[1078 + pix] / 16;
int py = bmpFile[1078 + pix] % 16;
//Get transparency from first palette color
if (dx == w &&dy == 0)
surf.colorKey = palette[0][0];
PHL_RGB c = palette[px][py];
surf.pxdata[count] = c.b;
surf.pxdata[count+1] = c.g;
surf.pxdata[count+2] = c.r;
count += 3;
}
}
//Cleanup
free(bmpFile);
}
return surf;
}
void PHL_DrawRect(int16_t x, int16_t y, uint16_t w, uint16_t h, PHL_RGB col) {
// Everything is stored in memory at 2x size; Halve it for the 3ds port
if (x < 0 || y < 0 || x+w > db.width || y+h > db.height)
return;
//Shrink values for small 3ds screen
//x /= 2;
//y /= 2;
x += offset.x;
y += offset.y;
//w /= 2;
//h /= 2;
s16 x2 = x + w;
s16 y2 = y + h;
//Keep drawing within screen
if (x < offset.x) { x = offset.x; }
if (y < offset.y) { y = offset.y; }
if (x2 > offset.x + offset.w) { x2 = offset.x + offset.w; }
if (y2 > offset.y + offset.h) { y2 = offset.y + offset.h; }
w = x2 - x;
h = y2 - y;
u32 p = ((db.height - h - y) + (x * db.height)) * 3;
for (int i = 0; i < w; i++)
{
for (int a = 0; a < h; a++)
{
db.pxdata[p] = col.b;
db.pxdata[p+1] = col.g;
db.pxdata[p+2] = col.r;
p += 3;
}
p += (db.height - h) * 3;
}
}
void PHL_DrawSurface(int16_t x, int16_t y, PHL_Surface surf) {
PHL_DrawSurfacePart(x, y, 0, 0, surf.width * 2, surf.height * 2, surf);
}
void PHL_DrawSurfacePart(int16_t x, int16_t y, int16_t cropx, int16_t cropy, int16_t cropw, int16_t croph, PHL_Surface surf) {
if (surf.pxdata != NULL) {
/*
// Everything is stored in memory at 2x size; Halve it for the 3ds port
x = (int) x / 2;
y = (int) y / 2;
cropx = cropx / 2;
cropy = cropy / 2;
cropw /= 2;
croph /= 2;
*/
if (x > offset.w || y > offset.h || x + cropw < 0 || y + croph < 0) {
//image is outside of screen, so don't bother drawing
} else {
//Crop pixels that are outside of screen
if (x < 0) {
cropx += -(x);
cropw -= -(x);
x = 0;
}
if (y < 0) {
cropy += -(y);
croph -= -(y);
y = 0;
}
//3DS exclusive optimization
/*
//if (roomDarkness == 1) {
//if (1) {
int cornerX = 0;// (herox / 2) - 80;
int cornerY = 0;// (heroy / 2) + 10 - 80;
if (x < cornerX) {
cropx += cornerX - x;
cropw -= cornerX - x;
x = cornerX;
}
if (y < cornerY) {
cropy += cornerY - y;
croph -= cornerY - y;
y = cornerY;
}
if (x + cropw > cornerX + 160) {
cropw -= (x + cropw) - (cornerX + 160);
}
if (y + croph > cornerY + 160) {
croph -= (y + croph) - (cornerY + 160);
}
//}*/
if (x + cropw > offset.w)
cropw -= (x + cropw) - (offset.w);
if (y + croph > offset.h)
croph -= (y + croph) - (offset.h);
// Adjust the canvas' position based on the new offsets
x += offset.x;
y += offset.y;
// Find the first color and pixel that we're dealing with before we update the rest of the canvas
uint32_t p = ((offset.h - croph - y) + (x * offset.h)) * 3;
uint32_t c = ((surf.height - cropy - croph) + surf.height * cropx) * 3;
// Loop through every single pixel (draw columns from left to right, top to bottom) of the final output canvas and store the correct color at each pixel
for (int i = 0; i < cropw; i++) {
for (int a = 0; a < croph; a++) {
if (surf.colorKey.r != surf.pxdata[c + 2] ||
surf.colorKey.g != surf.pxdata[c + 1] ||
surf.colorKey.b != surf.pxdata[c]) {
// Only update this pixel's color if necessary
db.pxdata[p] = surf.pxdata[c];
db.pxdata[p + 1] = surf.pxdata[c + 1];
db.pxdata[p + 2] = surf.pxdata[c + 2];
}
c += 3;
p += 3;
}
// Skip drawing for all of the columns of pixels that we've cropped out (one pixel = 3 bytes of data {r,g,b})
p += (offset.h - croph) * 3;
c += (surf.height - croph) * 3;
}
}
}
}
void PHL_DrawBackground(PHL_Background back, PHL_Background fore) {
PHL_DrawSurface(0, 0, backBuffer);
}
void PHL_UpdateBackground(PHL_Background back, PHL_Background fore) {
PHL_SetDrawbuffer(backBuffer);
/*
int xx, yy;
for (yy = 0; yy < 12; yy++) {
for (xx = 0; xx < 16; xx++) {
//Draw Background tiles
PHL_DrawSurfacePart(xx * 40, yy * 40, back.tileX[xx][yy] * 40, back.tileY[xx][yy] * 40, 40, 40, images[imgTiles]);
//Only draw foreground tile if not a blank tile
if (fore.tileX[xx][yy] != 0 || fore.tileY[xx][yy] != 0) {
PHL_DrawSurfacePart(xx * 40, yy * 40, fore.tileX[xx][yy] * 40, fore.tileY[xx][yy] * 40, 40, 40, images[imgTiles]);
}
}
}
*/
PHL_ResetDrawbuffer();
}
//3DS exclusive. Changes which screen to draw on
void swapScreen(gfxScreen_t screen, gfx3dSide_t side) {
//Clear old screen
PHL_StartDrawing();
PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0));
PHL_EndDrawing();
PHL_StartDrawing();
PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0));
PHL_EndDrawing();
if (screen == GFX_TOP) {
activeScreen = &scrnTop;
debugScreen = &scrnBottom;
} else {
activeScreen = &scrnBottom;
debugScreen = &scrnTop;
}
PHL_ResetDrawbuffer();
}
void PHL_DrawOtherScreen() {
PHL_ResetAltDrawbuffer();
//printf(":wagu: :nodding: :nodding2: :slownod: :hypernodding: :wagu2: :oj100: :revolving_hearts: ");
}
void PHL_ResetAltDrawbuffer() {
dbAlt.width = debugScreen->width;
dbAlt.height = debugScreen->height;
dbAlt.pxdata = gfxGetFramebuffer(debugScreen->screen, debugScreen->side, NULL, NULL);
offset.w = cWidth;
offset.h = cHeight;
offset.x = (debugScreen->width - offset.w) / 2;
offset.y = (debugScreen->height - offset.h) / 2;
} | 28.057082 | 164 | 0.490619 | mysterypaint |
1757288b370f17004e7f385e0f07db58febb9e40 | 289 | cpp | C++ | Decorator/Decorator/Color.cpp | jayavardhanravi/DesignPatterns | aa6a37790f447c7caf69c6a1a9c6107074309a03 | [
"BSD-2-Clause"
] | 8 | 2020-01-23T23:20:40.000Z | 2022-01-08T13:04:08.000Z | Decorator/Decorator/Color.cpp | jayavardhanravi/DesignPatterns | aa6a37790f447c7caf69c6a1a9c6107074309a03 | [
"BSD-2-Clause"
] | null | null | null | Decorator/Decorator/Color.cpp | jayavardhanravi/DesignPatterns | aa6a37790f447c7caf69c6a1a9c6107074309a03 | [
"BSD-2-Clause"
] | 1 | 2020-01-28T14:27:54.000Z | 2020-01-28T14:27:54.000Z | #include "Color.h"
Color::Color(Mesh *mesh): MeshDecorator(mesh)
{
}
Color::~Color()
{
}
void Color::AddMeshProperties()
{
MeshDecorator::AddMeshProperties();
ColorFeatures();
}
void Color::ColorFeatures()
{
std::cout << "Added the Color Features" << std::endl;
} | 14.45 | 55 | 0.636678 | jayavardhanravi |
175c2174517af83e300abaeefe37cb2a15311bbe | 1,988 | cpp | C++ | BeakJoon/c++/solved/1000/1260.cpp | heeboy007/PS-MyAnswers | e5e02972ab64279d96eb43e85941a46b82315fbd | [
"MIT"
] | null | null | null | BeakJoon/c++/solved/1000/1260.cpp | heeboy007/PS-MyAnswers | e5e02972ab64279d96eb43e85941a46b82315fbd | [
"MIT"
] | null | null | null | BeakJoon/c++/solved/1000/1260.cpp | heeboy007/PS-MyAnswers | e5e02972ab64279d96eb43e85941a46b82315fbd | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
int dots, cons, start;
bool is_visited[1001];
int matrix[1001][1001];
/*
const int MAX = 1000 + 1;
int N, M, V;
int adjacent[MAX][MAX];
bool visited[MAX];
queue<int> q;
void DFS(int idx)
{
cout << idx << " ";
for(int i=1; i<=N; i++)
if (adjacent[idx][i] && !visited[i])
{
visited[i] = 1;
DFS(i);
}
}
*/
void dfs(int now){
cout << now << ' ';
for(int i = 1; i <= dots; i++){
if(matrix[now][i] && !is_visited[i]){ //never visited
is_visited[i] = true;
dfs(i);
}
}
}
/*
void BFS(int idx)
{
q.push(idx);
visited[idx] = 1;
while (!q.empty())
{
idx = q.front();
q.pop();
cout << idx << " ";
for(int i=1; i<=N; i++)
if (adjacent[idx][i] && !visited[i])
{
visited[i] = 1;
q.push(i);
}
}
}
*/
void bfs(int idx){
queue<int> q;
q.push(idx);
is_visited[idx] = true;
while(!q.empty()){
idx = q.front();
q.pop();
cout << idx << ' ';
for(int i = 1; i <= dots; i++){
if(matrix[idx][i] && !is_visited[i]){ //never visited
is_visited[i] = true;
q.push(i);
}
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> dots >> cons >> start;
for(int i = 0; i < cons; i++){
int from, to;
cin >> from >> to;
matrix[from][to] = 1;
matrix[to][from] = 1;
}
is_visited[start] = true;
dfs(start);
cout << endl;
memset(is_visited, false, sizeof(bool) * 1005);
bfs(start);
cout << endl;
return 0;
}
| 18.579439 | 65 | 0.41499 | heeboy007 |
1760a377c4ee0615e42f6597479223048a9c81cd | 26,783 | cpp | C++ | code/steps/source/model/wtg_models/wt_turbine_model/wt_turbine_model_test.cpp | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 29 | 2019-10-30T07:04:10.000Z | 2022-02-22T06:34:32.000Z | code/steps/source/model/wtg_models/wt_turbine_model/wt_turbine_model_test.cpp | cuihantao/steps | 60327bf42299cb7117ed5907a931583d7cdf590d | [
"MIT"
] | 1 | 2021-09-25T15:29:59.000Z | 2022-01-05T14:04:18.000Z | code/steps/source/model/wtg_models/wt_turbine_model/wt_turbine_model_test.cpp | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 8 | 2019-12-20T16:13:46.000Z | 2022-03-20T14:58:23.000Z | #include "header/basic/test_macro.h"
#include "header/model/wtg_models/wt_turbine_model/wt_turbine_model_test.h"
#include "header/basic/utility.h"
#include "header/steps_namespace.h"
#include "header/model/wtg_models/wt_generator_model/wt3g0.h"
#include "header/model/wtg_models/wt_aerodynamic_model/aerd0.h"
#include <cstdlib>
#include <cstring>
#include <istream>
#include <iostream>
#include <cstdio>
#include <cmath>
#ifdef ENABLE_STEPS_TEST
using namespace std;
WT_TURBINE_MODEL_TEST::WT_TURBINE_MODEL_TEST()
{
TEST_ADD(WT_TURBINE_MODEL_TEST::test_get_model_type);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_set_get_damping);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_get_standard_psse_string);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode);
TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode);
}
void WT_TURBINE_MODEL_TEST::setup()
{
WTG_MODEL_TEST::setup();
DYNAMIC_MODEL_DATABASE& dmdb = default_toolkit.get_dynamic_model_database();
WT_GENERATOR* wt_gen = get_test_wt_generator();
wt_gen->set_p_generation_in_MW(28.0);
wt_gen->set_rated_power_per_wt_generator_in_MW(1.5);
wt_gen->set_number_of_lumped_wt_generators(20);
WT3G0 genmodel(default_toolkit);
genmodel.set_device_id(wt_gen->get_device_id());
genmodel.set_converter_activer_current_command_T_in_s(0.2);
genmodel.set_converter_reactiver_voltage_command_T_in_s(0.2);
genmodel.set_KPLL(20.0);
genmodel.set_KIPLL(10.0);
genmodel.set_PLLmax(0.1);
LVPL lvpl;
lvpl.set_low_voltage_in_pu(0.5);
lvpl.set_high_voltage_in_pu(0.8);
lvpl.set_gain_at_high_voltage(20.0);
genmodel.set_LVPL(lvpl);
genmodel.set_HVRC_voltage_in_pu(0.8);
genmodel.set_HVRC_current_in_pu(20.0);
genmodel.set_LVPL_max_rate_of_active_current_change(0.2);
genmodel.set_LVPL_voltage_sensor_T_in_s(0.1);
dmdb.add_model(&genmodel);
AERD0 aeromodel(default_toolkit);
aeromodel.set_device_id(wt_gen->get_device_id());
aeromodel.set_number_of_pole_pairs(2);
aeromodel.set_generator_to_turbine_gear_ratio(100.0);
aeromodel.set_gear_efficiency(1.0);
aeromodel.set_turbine_blade_radius_in_m(25.0);
aeromodel.set_nominal_wind_speed_in_mps(13.0);
aeromodel.set_nominal_air_density_in_kgpm3(1.25);
aeromodel.set_air_density_in_kgpm3(1.25);
aeromodel.set_turbine_speed_mode(WT_UNDERSPEED_MODE);
aeromodel.set_C1(0.22);
aeromodel.set_C2(116.0);
aeromodel.set_C3(0.4);
aeromodel.set_C4(5.0);
aeromodel.set_C5(12.5);
aeromodel.set_C6(0.0);
aeromodel.set_C1(0.5176);
aeromodel.set_C2(116.0);
aeromodel.set_C3(0.4);
aeromodel.set_C4(5.0);
aeromodel.set_C5(21.0);
aeromodel.set_C6(0.0068);
dmdb.add_model(&aeromodel);
}
void WT_TURBINE_MODEL_TEST::tear_down()
{
WTG_MODEL_TEST::tear_down();
}
void WT_TURBINE_MODEL_TEST::test_get_model_type()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
TEST_ASSERT(model->get_model_type()=="WT TURBINE");
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_set_get_damping()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
model->set_damping_in_pu(0.0);
TEST_ASSERT(fabs(model->get_damping_in_pu()-0.0)<FLOAT_EPSILON);
model->set_damping_in_pu(1.0);
TEST_ASSERT(fabs(model->get_damping_in_pu()-1.0)<FLOAT_EPSILON);
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_get_standard_psse_string()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
model->get_standard_psse_string();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt");
run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode();
default_toolkit.close_log_file();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt");
run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode();
default_toolkit.close_log_file();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt");
run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode();
default_toolkit.close_log_file();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt");
run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode();
default_toolkit.close_log_file();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt");
run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode();
default_toolkit.close_log_file();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode()
{
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
if(model!=NULL)
{
show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST");
default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt");
run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode();
default_toolkit.close_log_file();
}
else
TEST_ASSERT(false);
}
void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode()
{
ostringstream osstream;
double delt = 0.001;
default_toolkit.set_dynamic_simulation_time_step_in_s(delt);
WT_GENERATOR* genptr = get_test_wt_generator();
if(genptr==NULL)
cout<<"Fatal error. No WT_GENERATOR is found in "<<__FUNCTION__<<endl;
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
if(genmodel==NULL)
cout<<"Fatal error. No WT_GENERATOR_MODEL is found in "<<__FUNCTION__<<endl;
genmodel->initialize();
WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model();
aeromodel->set_turbine_speed_mode(WT_UNDERSPEED_MODE);
WT_TURBINE_MODEL*model = get_test_wt_turbine_model();
osstream<<"Model:"<<model->get_standard_psse_string()<<endl;
default_toolkit.show_information_with_leading_time_stamp(osstream);
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt);
double generator_speed;
model->initialize();
generator_speed = model->get_generator_speed_in_pu();
export_meter_title();
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
model->run(UPDATE_MODE);
export_meter_values();
}
apply_1deg_pitch_angle_increase();
model->run(UPDATE_MODE);
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
model->run(UPDATE_MODE);
export_meter_values();
}
}
void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode()
{
ostringstream osstream;
double delt = 0.001;
default_toolkit.set_dynamic_simulation_time_step_in_s(delt);
WT_GENERATOR* genptr = get_test_wt_generator();
if(genptr==NULL)
cout<<"Fatal error. No WT_GENERATOR is found in "<<__FUNCTION__<<endl;
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
if(genmodel==NULL)
cout<<"Fatal error. No WT_GENERATOR_MODEL is found in "<<__FUNCTION__<<endl;
genmodel->initialize();
WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model();
aeromodel->set_turbine_speed_mode(WT_MPPT_MODE);
WT_TURBINE_MODEL*model = get_test_wt_turbine_model();
osstream<<"Model:"<<model->get_standard_psse_string()<<endl;
default_toolkit.show_information_with_leading_time_stamp(osstream);
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt);
double generator_speed;
model->initialize();
generator_speed = model->get_generator_speed_in_pu();
export_meter_title();
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
model->run(UPDATE_MODE);
export_meter_values();
}
apply_1deg_pitch_angle_increase();
model->run(UPDATE_MODE);
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
model->run(UPDATE_MODE);
export_meter_values();
}
}
void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode()
{
ostringstream osstream;
double delt = 0.001;
default_toolkit.set_dynamic_simulation_time_step_in_s(delt);
WT_GENERATOR* genptr = get_test_wt_generator();
if(genptr==NULL)
cout<<"Fatal error. No WT_GENERATOR is found in "<<__FUNCTION__<<endl;
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
if(genmodel==NULL)
cout<<"Fatal error. No WT_GENERATOR_MODEL is found in "<<__FUNCTION__<<endl;
genmodel->initialize();
WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model();
aeromodel->set_turbine_speed_mode(WT_OVERSPEED_MODE);
WT_TURBINE_MODEL*model = get_test_wt_turbine_model();
osstream<<"Model:"<<model->get_standard_psse_string()<<endl;
default_toolkit.show_information_with_leading_time_stamp(osstream);
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt);
double generator_speed;
model->initialize();
generator_speed = model->get_generator_speed_in_pu();
export_meter_title();
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
model->run(UPDATE_MODE);
export_meter_values();
}
apply_1deg_pitch_angle_increase();
model->run(UPDATE_MODE);
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
model->run(UPDATE_MODE);
export_meter_values();
}
}
void WT_TURBINE_MODEL_TEST::apply_1deg_pitch_angle_increase()
{
WT_AERODYNAMIC_MODEL* aero_model = get_test_wt_aerodynamic_model();
if (aero_model != NULL)
aero_model->set_initial_pitch_angle_in_deg(aero_model->get_initial_pitch_angle_in_deg() + 1.0);
else
{
cout << "Fatal error. No WT_AERODYNAMIC_MODEL is found in " << __FUNCTION__ << endl;
return;
}
}
void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode()
{
ostringstream osstream;
double delt = 0.001;
default_toolkit.set_dynamic_simulation_time_step_in_s(delt);
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
genmodel->initialize();
WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model();
aeromodel->set_turbine_speed_mode(WT_UNDERSPEED_MODE);
WT_TURBINE_MODEL*model = get_test_wt_turbine_model();
osstream<<"Model:"<<model->get_standard_psse_string()<<endl;
default_toolkit.show_information_with_leading_time_stamp(osstream);
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt);
double generator_speed;
model->initialize();
generator_speed = model->get_generator_speed_in_pu();
export_meter_title();
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
genmodel->run(INTEGRATE_MODE);
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
}
apply_10_percent_power_order_drop();
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
genmodel->run(INTEGRATE_MODE);
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
}
}
void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode()
{
ostringstream osstream;
double delt = 0.001;
default_toolkit.set_dynamic_simulation_time_step_in_s(delt);
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
genmodel->initialize();
WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model();
aeromodel->set_turbine_speed_mode(WT_MPPT_MODE);
WT_TURBINE_MODEL*model = get_test_wt_turbine_model();
osstream<<"Model:"<<model->get_standard_psse_string()<<endl;
default_toolkit.show_information_with_leading_time_stamp(osstream);
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt);
double generator_speed;
model->initialize();
generator_speed = model->get_generator_speed_in_pu();
export_meter_title();
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
genmodel->run(INTEGRATE_MODE);
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
}
apply_10_percent_power_order_drop();
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
genmodel->run(INTEGRATE_MODE);
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
}
}
void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode()
{
ostringstream osstream;
double delt = 0.001;
default_toolkit.set_dynamic_simulation_time_step_in_s(delt);
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
genmodel->initialize();
WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model();
aeromodel->set_turbine_speed_mode(WT_OVERSPEED_MODE);
WT_TURBINE_MODEL*model = get_test_wt_turbine_model();
osstream<<"Model:"<<model->get_standard_psse_string()<<endl;
default_toolkit.show_information_with_leading_time_stamp(osstream);
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt);
double generator_speed;
model->initialize();
generator_speed = model->get_generator_speed_in_pu();
export_meter_title();
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
genmodel->run(INTEGRATE_MODE);
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
}
apply_10_percent_power_order_drop();
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
while(true)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt);
if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON)
{
default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt);
break;
}
generator_speed = model->get_generator_speed_in_pu();
while(true)
{
genmodel->run(INTEGRATE_MODE);
model->run(INTEGRATE_MODE);
if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6)
generator_speed = model->get_generator_speed_in_pu();
else
break;
}
genmodel->run(UPDATE_MODE);
model->run(UPDATE_MODE);
export_meter_values();
}
}
void WT_TURBINE_MODEL_TEST::apply_10_percent_power_order_drop()
{
WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model();
double ipcmd = genmodel->get_initial_active_current_command_in_pu_based_on_mbase();
genmodel->set_initial_active_current_command_in_pu_based_on_mbase(ipcmd*0.9);
}
void WT_TURBINE_MODEL_TEST::export_meter_title()
{
ostringstream osstream;
osstream<<"TIME\tPELEC\tPMECH\tTSPEED\tGSPEED\tANGLE";
default_toolkit.show_information_with_leading_time_stamp(osstream);
}
void WT_TURBINE_MODEL_TEST::export_meter_values()
{
ostringstream osstream;
WT_TURBINE_MODEL* model = get_test_wt_turbine_model();
osstream<<setw(10)<<setprecision(6)<<fixed<<default_toolkit.get_dynamic_simulation_time_in_s()<<"\t"
<<setw(10)<<setprecision(6)<<fixed<<model->get_wt_generator_active_power_generation_in_MW()<<"\t"
<<setw(10)<<setprecision(6)<<fixed<<model->get_mechanical_power_in_pu_from_wt_aerodynamic_model()*model->get_mbase_in_MVA()<<"\t"
<<setw(10)<<setprecision(6)<<fixed<<model->get_turbine_speed_in_pu()<<"\t"
<<setw(10)<<setprecision(6)<<fixed<<model->get_generator_speed_in_pu()<<"\t"
<<setw(10)<<setprecision(6)<<fixed<<model->get_rotor_angle_in_deg();
default_toolkit.show_information_with_leading_time_stamp(osstream);
}
#endif
| 35.28722 | 140 | 0.720569 | changgang |
1760bcc6a7f257e9b16278992d6d2f2c8143bad0 | 56 | hpp | C++ | src/boost_spirit_home_qi_auxiliary_attr_cast.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_spirit_home_qi_auxiliary_attr_cast.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_spirit_home_qi_auxiliary_attr_cast.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/spirit/home/qi/auxiliary/attr_cast.hpp>
| 28 | 55 | 0.803571 | miathedev |
1764e3714e86b52ebefaf7fab17b045c75f3c7fe | 9,153 | cpp | C++ | src/services/http.cpp | devinsmith/tfstool | bccd7dc97a769a87fb576c1feae32290cf6bd8c3 | [
"MIT"
] | null | null | null | src/services/http.cpp | devinsmith/tfstool | bccd7dc97a769a87fb576c1feae32290cf6bd8c3 | [
"MIT"
] | null | null | null | src/services/http.cpp | devinsmith/tfstool | bccd7dc97a769a87fb576c1feae32290cf6bd8c3 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2012-2019 Devin Smith <devin@devinsmith.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <curl/curl.h>
#include <curl/easy.h>
#include <cstring>
#include <cstdlib>
#include <string>
#include "services/http.h"
#include "utils/logging.h"
namespace http {
/* HTTP Services version 1.102 (06-17-2019) */
struct http_context {
HttpRequest *req;
HttpResponse *resp;
};
/* Modern Chrome on Windows 10 */
static const char *chrome_win10_ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36";
#ifdef _WIN32
#define WAITMS(x) Sleep(x)
#else
/* Portable sleep for platforms other than Windows. */
#define WAITMS(x) \
struct timeval wait { 0, (x) * 1000 }; \
(void)select(0, NULL, NULL, NULL, &wait);
#endif
void
http_lib_startup(void)
{
curl_global_init(CURL_GLOBAL_ALL);
}
void
http_lib_shutdown(void)
{
}
HttpExecutor::HttpExecutor()
{
m_multi_handle = curl_multi_init();
}
HttpExecutor::~HttpExecutor()
{
curl_multi_cleanup(m_multi_handle);
}
/* Private generic response reading function */
static size_t
dk_httpread(char *ptr, size_t size, size_t nmemb, HttpResponse *hr)
{
size_t totalsz = size * nmemb;
if (strstr(ptr, "HTTP/1.1 100 Continue"))
return totalsz;
hr->body.append((char *)ptr, totalsz);
return totalsz;
}
const char *
http_get_error_str(int error_code)
{
return curl_easy_strerror((CURLcode)error_code);
}
static int
curl_debug_func(CURL *hnd, curl_infotype info, char *data, size_t len,
http_context *ctx)
{
std::string hdr;
std::string::size_type n;
switch (info) {
case CURLINFO_HEADER_OUT:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, "H>: %s", verb.c_str());
}
ctx->req->req_hdrs.append(data, len);
break;
case CURLINFO_TEXT:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, "T: %s", verb.c_str());
}
break;
case CURLINFO_HEADER_IN:
hdr = std::string(data, len);
if (ctx->req->verbose()) {
log_msgraw(0, "H<: %s", hdr.c_str());
}
n = hdr.find('\r');
if (n != std::string::npos) {
hdr.erase(n);
}
n = hdr.find('\n');
if (n != std::string::npos) {
hdr.erase(n);
}
ctx->resp->headers.push_back(hdr);
break;
case CURLINFO_DATA_IN:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, "<: %s", verb.c_str());
}
break;
case CURLINFO_DATA_OUT:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, ">: %s", verb.c_str());
}
break;
default:
break;
}
return 0;
}
static CURLcode
easy_perform(CURLM *mhnd, CURL *hnd)
{
CURLcode result = CURLE_OK;
CURLMcode mcode = CURLM_OK;
int done = 0; /* bool */
if (curl_multi_add_handle(mhnd, hnd)) {
return CURLE_FAILED_INIT;
}
while (!done && mcode == 0) {
int still_running = 0;
int rc;
mcode = curl_multi_wait(mhnd, NULL, 0, 1000, &rc);
if (mcode == 0) {
if (rc == 0) {
long sleep_ms;
/* If it returns without any file descriptor instantly, we need to
* avoid busy looping during periods where it has nothing particular
* to wait for. */
curl_multi_timeout(mhnd, &sleep_ms);
if (sleep_ms) {
if (sleep_ms > 1000)
sleep_ms = 1000;
WAITMS(sleep_ms);
}
}
mcode = curl_multi_perform(mhnd, &still_running);
}
/* Only read still-running if curl_multi_perform returns ok */
if (!mcode && still_running == 0) {
CURLMsg *msg = curl_multi_info_read(mhnd, &rc);
if (msg) {
result = msg->data.result;
done = 1;
}
}
}
if (mcode != 0) {
if ((int)mcode == CURLM_OUT_OF_MEMORY)
result = CURLE_OUT_OF_MEMORY;
else
result = CURLE_BAD_FUNCTION_ARGUMENT;
}
curl_multi_remove_handle(mhnd, hnd);
return result;
}
void HttpRequest::set_content(const char *content_type)
{
std::string ctype_hdr = "Content-Type: ";
ctype_hdr.append(content_type);
m_headers = curl_slist_append(m_headers, ctype_hdr.c_str());
}
HttpResponse HttpRequest::exec(const char *method, const char *data,
HttpExecutor& executor)
{
struct http_context ctx;
HttpResponse resp;
if (strcmp(method, "GET") == 0) {
curl_easy_setopt(m_handle, CURLOPT_HTTPGET, 1);
} else if (strcmp(method, "POST") == 0) {
curl_easy_setopt(m_handle, CURLOPT_POST, 1);
} else {
curl_easy_setopt(m_handle, CURLOPT_CUSTOMREQUEST, method);
}
if (data != NULL) {
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, (long)strlen(data));
} else {
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, 0);
}
curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str());
curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers);
curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_user_agent.c_str());
ctx.resp = &resp;
ctx.req = this;
curl_easy_setopt(m_handle, CURLOPT_DEBUGFUNCTION, curl_debug_func);
curl_easy_setopt(m_handle, CURLOPT_DEBUGDATA, &ctx);
curl_easy_setopt(m_handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, 0);
/* Verification of SSL is disabled on Windows. This is a limitation of
* curl */
curl_easy_setopt(m_handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(m_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, &resp);
curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, dk_httpread);
CURLcode res = easy_perform(executor.handle(), m_handle);
if (res != CURLE_OK) {
log_tmsg(0, "Failure performing request");
}
curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &resp.status_code);
curl_easy_getinfo(m_handle, CURLINFO_TOTAL_TIME, &elapsed);
resp.elapsed = elapsed;
return resp;
}
static size_t
write_file(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
bool
HttpRequest::get_file(const char *file)
{
FILE *fp;
fp = fopen(file, "w");
if (fp == NULL) {
return false;
}
bool ret = get_file_fp(fp);
fclose(fp);
return ret;
}
bool
HttpRequest::get_file_fp(FILE *fp)
{
long status_code;
curl_easy_setopt(m_handle, CURLOPT_HTTPGET, 1);
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, 0);
curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str());
curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers);
curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_user_agent.c_str());
curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, 0);
curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, write_file);
curl_easy_setopt(m_handle, CURLOPT_FOLLOWLOCATION, 1L);
CURLcode res = easy_perform(HttpExecutor::default_instance().handle(), m_handle);
if (res != CURLE_OK) {
log_tmsg(0, "Failure performing request");
}
curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &status_code);
curl_easy_getinfo(m_handle, CURLINFO_TOTAL_TIME, &elapsed);
return true;
}
HttpRequest::HttpRequest(const std::string &url, bool verbose) :
m_headers(NULL), m_url(url), m_verbose(verbose), m_user_agent(chrome_win10_ua)
{
m_handle = curl_easy_init();
}
void
HttpRequest::set_cert(const std::string &cert, const std::string &key)
{
curl_easy_setopt(m_handle, CURLOPT_SSLCERT, cert.c_str());
curl_easy_setopt(m_handle, CURLOPT_SSLKEY, key.c_str());
}
void
HttpRequest::set_basic_auth(const std::string &user, const std::string &pass)
{
curl_easy_setopt(m_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(m_handle, CURLOPT_USERNAME, user.c_str());
curl_easy_setopt(m_handle, CURLOPT_PASSWORD, pass.c_str());
}
void HttpRequest::set_ntlm(const std::string &username, const std::string& password)
{
curl_easy_setopt(m_handle, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_easy_setopt(m_handle, CURLOPT_USERNAME, username.c_str());
curl_easy_setopt(m_handle, CURLOPT_PASSWORD, password.c_str());
}
void
HttpRequest::add_header(const char *key, const char *value)
{
char maxheader[2048];
snprintf(maxheader, sizeof(maxheader), "%s: %s", key, value);
m_headers = curl_slist_append(m_headers, maxheader);
}
HttpRequest::~HttpRequest()
{
curl_easy_cleanup(m_handle);
curl_slist_free_all(m_headers);
}
} // namespace http
| 25.783099 | 154 | 0.694417 | devinsmith |
17671c04293be639f9cf311ef66f46b0a86d035b | 6,620 | cpp | C++ | engine/engine/core/math/tests/so3.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | null | null | null | engine/engine/core/math/tests/so3.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | null | null | null | engine/engine/core/math/tests/so3.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2022-01-28T16:37:51.000Z | 2022-01-28T16:37:51.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include "engine/core/math/so3.hpp"
#include <vector>
#include "engine/core/constants.hpp"
#include "engine/core/math/quaternion.hpp"
#include "engine/core/math/types.hpp"
#include "engine/gems/math/test_utils.hpp"
#include "gtest/gtest.h"
namespace isaac {
TEST(SO3, composition) {
SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 1.0, 3.0));
SO3d rot2 = SO3d::FromAngleAxis(1.7, Vector3d(1.0, 1.0, 3.0));
SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(1.0, 1.0, 3.0));
SO3d rot4 = SO3d::FromAngleAxis(0.535, Vector3d(1.0, 1.0, 3.0));
EXPECT_NEAR((rot1 * rot2 * rot3 * rot4).angle(),
SO3d::FromAngleAxis(rot1.angle() + rot2.angle() + rot3.angle() + rot4.angle(),
Vector3d(1.0, 1.0, 3.0)).angle(), 1e-7);
}
TEST(SO3, angle) {
SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 0.0, 0.0));
SO3d rot2 = SO3d::FromAngleAxis(-1.7, Vector3d(0.0, 1.0, 0.0));
SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(0.0, 0.0, 1.0));
SO3d rot4 = SO3d::FromAngleAxis(-0.535, Vector3d(1.0, 1.0, 1.0));
EXPECT_NEAR(rot1.angle(), 1.1, 1e-7);
EXPECT_NEAR(rot2.angle(), 1.7, 1e-7);
EXPECT_NEAR(rot3.angle(), 2.5, 1e-7);
EXPECT_NEAR(rot4.angle(), 0.535, 1e-7);
}
TEST(SO3, inverse) {
SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 0.0, 0.0));
SO3d rot2 = SO3d::FromAngleAxis(1.7, Vector3d(0.0, 1.0, 0.0));
SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(0.0, 0.0, 1.0));
SO3d rot4 = SO3d::FromAngleAxis(0.535, Vector3d(1.0, 1.0, 1.0));
EXPECT_NEAR(rot1.inverse().angle(), rot1.angle(), 1e-7);
EXPECT_NEAR(rot2.inverse().angle(), rot2.angle(), 1e-7);
EXPECT_NEAR(rot3.inverse().angle(), rot3.angle(), 1e-7);
EXPECT_NEAR(rot4.inverse().angle(), rot4.angle(), 1e-7);
EXPECT_NEAR((rot1.inverse().axis()+rot1.axis()).norm(), 0.0, 1e-7)
<< rot1.axis() << " vs " << rot1.inverse().axis();
EXPECT_NEAR((rot2.inverse().axis()+rot2.axis()).norm(), 0.0, 1e-7)
<< rot2.axis() << " vs " << rot2.inverse().axis();
EXPECT_NEAR((rot3.inverse().axis()+rot3.axis()).norm(), 0.0, 1e-7)
<< rot3.axis() << " vs " << rot3.inverse().axis();
EXPECT_NEAR((rot4.inverse().axis()+rot4.axis()).norm(), 0.0, 1e-7)
<< rot4.axis() << " vs " << rot4.inverse().axis();
}
TEST(SO3, vector) {
Vector3d vec1 = SO3d::FromAngleAxis(Pi<double>/2, Vector3d(0.0, 0.0, 1.0)) * Vector3d(1.0, 2.0, 3.0);
EXPECT_NEAR(vec1.x(), -2.0, 1e-7);
EXPECT_NEAR(vec1.y(), 1.0, 1e-7);
EXPECT_NEAR(vec1.z(), 3.0, 1e-7);
}
TEST(SO3, euler_angles) {
enum EulerAngles {
kRoll = 0,
kPitch = 1,
kYaw = 2
};
constexpr double roll = 1.1;
constexpr double pitch = 1.7;
constexpr double yaw = 2.5;
SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0));
SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0));
SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0));
SO3d rot4 = rot1 * rot2 *rot3;
Vector3d rot1_euler = rot1.eulerAnglesRPY();
Vector3d rot2_euler = rot2.eulerAnglesRPY();
Vector3d rot3_euler = rot3.eulerAnglesRPY();
Vector3d rot4_euler = rot4.eulerAnglesRPY();
EXPECT_NEAR(rot1_euler[kRoll], roll, 1e-7);
EXPECT_NEAR(rot1_euler[kPitch], 0.0, 1e-7);
EXPECT_NEAR(rot1_euler[kYaw], 0.0, 1e-7);
EXPECT_NEAR(rot2_euler[kRoll], 0.0, 1e-7);
EXPECT_NEAR(rot2_euler[kPitch], pitch, 1e-7);
EXPECT_NEAR(rot2_euler[kYaw], 0.0, 1e-7);
EXPECT_NEAR(rot3_euler[kRoll], 0.0, 1e-7);
EXPECT_NEAR(rot3_euler[kPitch], 0.0, 1e-7);
EXPECT_NEAR(rot3_euler[kYaw], yaw, 1e-7);
EXPECT_NEAR(rot4_euler[kRoll], roll, 1e-7);
EXPECT_NEAR(rot4_euler[kPitch], pitch, 1e-7);
EXPECT_NEAR(rot4_euler[kYaw], yaw, 1e-7);
}
TEST(SO3, euler_angles_close_zero) {
enum EulerAngles {
kRoll = 0,
kPitch = 1,
kYaw = 2
};
for (double roll = -Pi<double> * 0.25; roll < Pi<double> * 0.25; roll += Pi<double> * 0.05) {
for (double pitch = -Pi<double> * 0.25; pitch < Pi<double> * 0.25; pitch += Pi<double> * 0.05) {
for (double yaw = -Pi<double> * 0.25; yaw < Pi<double> * 0.25; yaw += Pi<double> * 0.05) {
const SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0));
const SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0));
const SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0));
const SO3d rot4 = rot1 * rot2 *rot3;
const Vector3d rot4_euler = rot4.eulerAnglesRPY();
EXPECT_NEAR(rot4_euler[kRoll], roll, 1e-7);
EXPECT_NEAR(rot4_euler[kPitch], pitch, 1e-7);
EXPECT_NEAR(rot4_euler[kYaw], yaw, 1e-7);
}
}
}
}
TEST(SO3, euler_angles_conversion) {
enum EulerAngles {
kRoll = 0,
kPitch = 1,
kYaw = 2
};
constexpr double roll = 1.1;
constexpr double pitch = 1.7;
constexpr double yaw = 2.5;
const SO3d so3 = SO3d::FromEulerAnglesRPY(roll, pitch, yaw);
const Vector3d euler_angles = so3.eulerAnglesRPY();
EXPECT_NEAR(euler_angles[kRoll], roll, 1e-7);
EXPECT_NEAR(euler_angles[kPitch], pitch, 1e-7);
EXPECT_NEAR(euler_angles[kYaw], yaw, 1e-7);
}
TEST(SO3, rotation_jacobian) {
Vector3d v = Vector3d::Random();
for (double roll = -Pi<double> * 0.25; roll < Pi<double> * 0.25; roll += Pi<double> * 0.05) {
for (double pitch = -Pi<double> * 0.25; pitch < Pi<double> * 0.25; pitch += Pi<double> * 0.05) {
for (double yaw = -Pi<double> * 0.25; yaw < Pi<double> * 0.25; yaw += Pi<double> * 0.05) {
const SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0));
const SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0));
// const SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0));
const SO3d rot4 = rot1 * rot2;
Matrix<double, 3, 4> result_a = rot4.vectorRotationJacobian(v);
Matrix<double, 3, 4> result_b = rot1.matrix() * rot2.vectorRotationJacobian(v);
Matrix<double, 3, 4> result_c =
(QuaternionProductMatrixLeft(rot1.quaternion())
* result_b.transpose()).transpose();
for (int j = 0; j < result_a.cols(); j++) {
ISAAC_EXPECT_VEC_NEAR(result_a.col(j), result_c.col(j), 1e-3);
}
}
}
}
}
} // namespace isaac
| 38.045977 | 103 | 0.629154 | ddr95070 |
176af815ab84f5cfde7a5eaea80f8cccbfcb108d | 8,354 | cc | C++ | orb_slam3/Examples/ROS/ORB_SLAM3/src/mono_imu_tcw.cc | zhouyong1234/ORB-SLAM3 | 796fa6d8562c88355b78411f9f6915e287a14f5a | [
"Apache-2.0"
] | null | null | null | orb_slam3/Examples/ROS/ORB_SLAM3/src/mono_imu_tcw.cc | zhouyong1234/ORB-SLAM3 | 796fa6d8562c88355b78411f9f6915e287a14f5a | [
"Apache-2.0"
] | null | null | null | orb_slam3/Examples/ROS/ORB_SLAM3/src/mono_imu_tcw.cc | zhouyong1234/ORB-SLAM3 | 796fa6d8562c88355b78411f9f6915e287a14f5a | [
"Apache-2.0"
] | null | null | null | /**
* This file is part of ORB-SLAM3
*
* Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
* Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
*
* ORB-SLAM3 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 3 of the License, or
* (at your option) any later version.
*
* ORB-SLAM3 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 ORB-SLAM3.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include<iostream>
#include<algorithm>
#include<fstream>
#include<chrono>
#include<vector>
#include<queue>
#include<thread>
#include<mutex>
#include<ros/ros.h>
#include<cv_bridge/cv_bridge.h>
#include<sensor_msgs/Imu.h>
#include<opencv2/core/core.hpp>
#include"../../../include/System.h"
#include"../include/ImuTypes.h"
#include <geometry_msgs/PoseStamped.h>
using namespace std;
class ImuGrabber
{
public:
ImuGrabber(){};
void GrabImu(const sensor_msgs::ImuConstPtr &imu_msg);
queue<sensor_msgs::ImuConstPtr> imuBuf;
std::mutex mBufMutex;
};
class ImageGrabber
{
ros::NodeHandle nh; //定义句柄初始化
ros::Publisher pub1,pub_tcw; //定义发布者
public:
ImageGrabber(ORB_SLAM3::System* pSLAM, ImuGrabber *pImuGb, const bool bClahe): mpSLAM(pSLAM), mpImuGb(pImuGb), mbClahe(bClahe),nh("~")
{
pub_tcw= nh.advertise<geometry_msgs::PoseStamped> ("CameraPose", 10);
}
void GrabImage(const sensor_msgs::ImageConstPtr& msg);
cv::Mat GetImage(const sensor_msgs::ImageConstPtr &img_msg);
void SyncWithImu();
queue<sensor_msgs::ImageConstPtr> img0Buf;
std::mutex mBufMutex;
ORB_SLAM3::System* mpSLAM;
ImuGrabber *mpImuGb;
const bool mbClahe;
cv::Ptr<cv::CLAHE> mClahe = cv::createCLAHE(3.0, cv::Size(8, 8));
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "Mono_Inertial");
ros::NodeHandle n("~");
ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Info);
bool bEqual = false;
if(argc < 1 || argc > 2)
{
cerr << endl << "Usage: rosrun ORB_SLAM3 Mono_Inertial path_to_vocabulary path_to_settings [do_equalize]" << endl;
ros::shutdown();
return 1;
}
if(argc==1)
{
std::string sbEqual(argv[3]);
if(sbEqual == "true")
bEqual = true;
}
string ORBvoc_path = "/home/lin/code/ORB_SLAM3/Vocabulary/ORBvoc.txt";
string config_path = "/home/lin/code/ORB_SLAM3/Examples/ROS/ORB_SLAM3/src/cam_inertial.yaml";
// Create SLAM system. It initializes all system threads and gets ready to process frames.
ORB_SLAM3::System SLAM(ORBvoc_path,config_path,ORB_SLAM3::System::IMU_MONOCULAR,true);
ImuGrabber imugb;
ImageGrabber igb(&SLAM,&imugb,bEqual); // TODO
// Maximum delay, 5 seconds
ros::Subscriber sub_imu = n.subscribe("/android/imu", 1000, &ImuGrabber::GrabImu, &imugb);
ros::Subscriber sub_img0 = n.subscribe("/usb_cam/image_raw", 100, &ImageGrabber::GrabImage,&igb);
std::thread sync_thread(&ImageGrabber::SyncWithImu,&igb);
ros::spin();
return 0;
}
void ImageGrabber::GrabImage(const sensor_msgs::ImageConstPtr &img_msg)
{
mBufMutex.lock();
if (!img0Buf.empty())
img0Buf.pop();
img0Buf.push(img_msg);
mBufMutex.unlock();
}
cv::Mat ImageGrabber::GetImage(const sensor_msgs::ImageConstPtr &img_msg)
{
// Copy the ros image message to cv::Mat.
cv_bridge::CvImageConstPtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvShare(img_msg, sensor_msgs::image_encodings::MONO8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
}
if(cv_ptr->image.type()==0)
{
return cv_ptr->image.clone();
}
else
{
std::cout << "Error type" << std::endl;
return cv_ptr->image.clone();
}
}
void ImageGrabber::SyncWithImu()
{
while(1)
{
cv::Mat im;
double tIm = 0;
if (!img0Buf.empty()&&!mpImuGb->imuBuf.empty())
{
tIm = img0Buf.front()->header.stamp.toSec();
if(tIm>mpImuGb->imuBuf.back()->header.stamp.toSec())
continue;
{
this->mBufMutex.lock();
im = GetImage(img0Buf.front());
img0Buf.pop();
this->mBufMutex.unlock();
}
vector<ORB_SLAM3::IMU::Point> vImuMeas;
mpImuGb->mBufMutex.lock();
// if(!mpImuGb->imuBuf.empty())
// {
// // Load imu measurements from buffer
// vImuMeas.clear();
// while(!mpImuGb->imuBuf.empty() && mpImuGb->imuBuf.front()->header.stamp.toSec()<=tIm)
// {
// double t = mpImuGb->imuBuf.front()->header.stamp.toSec();
// cv::Point3f acc(mpImuGb->imuBuf.front()->linear_acceleration.x, mpImuGb->imuBuf.front()->linear_acceleration.y, mpImuGb->imuBuf.front()->linear_acceleration.z);
// cv::Point3f gyr(mpImuGb->imuBuf.front()->angular_velocity.x, mpImuGb->imuBuf.front()->angular_velocity.y, mpImuGb->imuBuf.front()->angular_velocity.z);
// vImuMeas.push_back(ORB_SLAM3::IMU::Point(acc,gyr,t));
// mpImuGb->imuBuf.pop();
// }
// }
// 时间对齐
if(!mpImuGb->imuBuf.empty())
{
// Load imu measurements from buffer
vImuMeas.clear();
static bool time_flag = true;
static auto TIME_OFFSET = 0.0;
if(time_flag){
TIME_OFFSET = mpImuGb->imuBuf.front()->header.stamp.toSec()-tIm;
time_flag = false;
}
cout<<"imu_time: "<<setprecision(11)<<mpImuGb->imuBuf.front()->header.stamp.toSec()-TIME_OFFSET<<endl;
cout<<"image_time: "<<setprecision(11)<<tIm<<endl;
cout<<"---------------"<<endl;
while(!mpImuGb->imuBuf.empty() && mpImuGb->imuBuf.front()->header.stamp.toSec()-TIME_OFFSET<=tIm)
{
double t = mpImuGb->imuBuf.front()->header.stamp.toSec() - TIME_OFFSET;
cv::Point3f acc(mpImuGb->imuBuf.front()->linear_acceleration.x, mpImuGb->imuBuf.front()->linear_acceleration.y, mpImuGb->imuBuf.front()->linear_acceleration.z);
cv::Point3f gyr(mpImuGb->imuBuf.front()->angular_velocity.x, mpImuGb->imuBuf.front()->angular_velocity.y, mpImuGb->imuBuf.front()->angular_velocity.z);
cout<<"imudata: "<< t<<" "<<acc.x<<" "<<acc.y<<" "<<acc.z<<" "<<gyr.x<<" "<<gyr.y<<" "<<gyr.z<<endl;
vImuMeas.push_back(ORB_SLAM3::IMU::Point(acc,gyr,t));
mpImuGb->imuBuf.pop();
}
}
mpImuGb->mBufMutex.unlock();
if(mbClahe)
mClahe->apply(im,im);
cv::resize(im,im,cv::Size(640,480));
// if(cv::waitKey(10)=='q')
// break;
cv::Mat Tcw;
Tcw = mpSLAM->TrackMonocular(im,tIm,vImuMeas);
if(!Tcw.empty())
{
cv::Mat Twc =Tcw.inv();
cv::Mat RWC= Twc.rowRange(0,3).colRange(0,3);
cv::Mat tWC= Twc.rowRange(0,3).col(3);
Eigen::Matrix<double,3,3> eigMat ;
eigMat <<RWC.at<float>(0,0),RWC.at<float>(0,1),RWC.at<float>(0,2),
RWC.at<float>(1,0),RWC.at<float>(1,1),RWC.at<float>(1,2),
RWC.at<float>(2,0),RWC.at<float>(2,1),RWC.at<float>(2,2);
Eigen::Quaterniond q(eigMat);
geometry_msgs::PoseStamped tcw_msg;
tcw_msg.pose.position.x=tWC.at<float>(0);
tcw_msg.pose.position.y=tWC.at<float>(1);
tcw_msg.pose.position.z=tWC.at<float>(2);
tcw_msg.pose.orientation.x=q.x();
tcw_msg.pose.orientation.y=q.y();
tcw_msg.pose.orientation.z=q.z();
tcw_msg.pose.orientation.w=q.w();
pub_tcw.publish(tcw_msg);
}
else
{
cout<<"Twc is empty ..."<<endl;
}
}
std::chrono::milliseconds tSleep(1);
std::this_thread::sleep_for(tSleep);
}
}
void ImuGrabber::GrabImu(const sensor_msgs::ImuConstPtr &imu_msg)
{
mBufMutex.lock();
imuBuf.push(imu_msg);
mBufMutex.unlock();
return;
}
| 31.055762 | 180 | 0.625569 | zhouyong1234 |
176c14c56d38352d4afa91612a7dbf8873219b46 | 131 | cpp | C++ | src/core/DataStreamException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | null | null | null | src/core/DataStreamException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | 26 | 2017-12-13T12:45:32.000Z | 2018-02-06T11:08:04.000Z | src/core/DataStreamException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | null | null | null | #include "DataStreamException.h"
DataStreamException::DataStreamException(const char * message) :
BaseException(message)
{
}
| 16.375 | 64 | 0.770992 | Neomer |
176c3bf77b5fc36853944665f09088ba141836ad | 2,346 | hpp | C++ | static_control_flow/code/impl/static_for_state.hpp | SuperV1234/cppnow2016 | a4f6bd093378d88930d2564b84d8fdd14236a736 | [
"AFL-3.0"
] | 49 | 2016-05-10T20:25:27.000Z | 2021-08-18T23:46:43.000Z | static_control_flow/code/impl/static_for_state.hpp | SuperV1234/cppnow2016 | a4f6bd093378d88930d2564b84d8fdd14236a736 | [
"AFL-3.0"
] | null | null | null | static_control_flow/code/impl/static_for_state.hpp | SuperV1234/cppnow2016 | a4f6bd093378d88930d2564b84d8fdd14236a736 | [
"AFL-3.0"
] | 2 | 2016-05-23T15:14:38.000Z | 2016-09-01T19:38:52.000Z | // Copyright (c) 2016 Vittorio Romeo
// License: AFL 3.0 | https://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com
#pragma once
#include "./static_if.hpp"
namespace impl
{
namespace action
{
struct a_continue
{
};
struct a_break
{
};
}
template <typename TItr, typename TAcc, typename TAction>
struct state
{
constexpr auto iteration() const noexcept
{
return TItr{};
}
constexpr auto accumulator() const noexcept
{
return TAcc{};
}
constexpr auto next_action() const noexcept
{
return TAction{};
}
template <typename TNewAcc>
constexpr auto continue_(TNewAcc) const noexcept;
constexpr auto continue_() const noexcept;
template <typename TNewAcc>
constexpr auto break_(TNewAcc) const noexcept;
constexpr auto break_() const noexcept;
};
template <typename TItr, typename TAcc, typename TAction>
constexpr auto make_state(TItr, TAcc, TAction)
{
return state<TItr, TAcc, TAction>{};
}
template <typename TState, typename TAcc, typename TAction>
constexpr auto advance_state(TState s, TAcc a, TAction na)
{
return make_state(sz_v<s.iteration() + 1>, a, na);
}
template <typename TItr, typename TAcc, typename TAction>
template <typename TNewAcc>
constexpr auto state<TItr, TAcc, TAction>::continue_( // .
TNewAcc new_acc) const noexcept
{
return advance_state(*this, new_acc, action::a_continue{});
}
template <typename TItr, typename TAcc, typename TAction>
constexpr auto state<TItr, TAcc, TAction>::continue_( // .
) const noexcept
{
return continue_(accumulator());
}
template <typename TItr, typename TAcc, typename TAction>
template <typename TNewAcc>
constexpr auto state<TItr, TAcc, TAction>::break_( // .
TNewAcc new_acc) const noexcept
{
return advance_state(*this, new_acc, action::a_break{});
}
template <typename TItr, typename TAcc, typename TAction>
constexpr auto state<TItr, TAcc, TAction>::break_( // .
) const noexcept
{
return break_(accumulator());
}
} | 25.5 | 67 | 0.617647 | SuperV1234 |
176d4e9093f4dd271a1818cb111d883b50d8c17c | 2,924 | cpp | C++ | manager.cpp | kwarehit/runtestcases | fe7b68a90b7d5051277e383c50a1e90fbeab8c73 | [
"BSL-1.0"
] | null | null | null | manager.cpp | kwarehit/runtestcases | fe7b68a90b7d5051277e383c50a1e90fbeab8c73 | [
"BSL-1.0"
] | null | null | null | manager.cpp | kwarehit/runtestcases | fe7b68a90b7d5051277e383c50a1e90fbeab8c73 | [
"BSL-1.0"
] | null | null | null | #include "manager.h"
#include "commonhdr.h"
#include "log.h"
#include "caseinfomodel.h"
#include "monitor.h"
#include "iocontextwrapper.h"
#include "datamanager.h"
#include "logtext.h"
#include "caseinfomodel.h"
Manager::Manager(QObject *parent)
: QObject(parent)
{
dataMgr_ = std::make_shared<DataManager>();
logText_ = std::make_shared<LogText>();
iocWrapper_ = std::make_shared<IOContextWrapper>();
monitor_ = std::make_shared<Monitor>(*iocWrapper_);
thread_ = std::make_shared<MonitorThread>(*iocWrapper_, *monitor_, dataMgr_, this);
dataMgr_->setMonitorThread(thread_);
connect(logText_.get(), &LogText::addLog, this, &Manager::onAddLogText);
connect(monitor_.get(), &Monitor::addText, this, &Manager::onAddMonitorText);
connect(thread_.get(), &MonitorThread::enableRunButton, this, &Manager::onEnabledRunButton);
connect(thread_.get(), &MonitorThread::enableStopButton, this, &Manager::onEnabledStopButton);
connect(this, &Manager::stopProcess, thread_.get(), &MonitorThread::onStopProcess);
}
Manager::~Manager()
{
}
void Manager::setDataMgr(CaseInfoModel* pModel)
{
model_ = pModel;
pModel->setDataManger(dataMgr_);
}
void Manager::onAddMonitorText(const QString& s)
{
Q_EMIT addMonitorText(s);
}
void Manager::onEnabledRunButton(bool b)
{
Q_EMIT setEnabledRunButton(b);
}
void Manager::onEnabledStopButton(bool b)
{
Q_EMIT setEnabledStopButton(b);
}
void Manager::onAddLogText(const QString& s)
{
Q_EMIT addLogText(s);
}
QString Manager::getRootDir()
{
try
{
return QString::fromStdString(dataMgr_->getRootDir());
}
catch (std::exception& e)
{
BOOST_LOG(processLog::get()) << e.what() << std::endl;
return "";
}
}
void Manager::setRootDir(const QString& rootDir)
{
try
{
dataMgr_->setRootDir(rootDir.toStdString());
}
catch (std::exception& e)
{
BOOST_LOG(processLog::get()) << e.what() << std::endl;
}
}
QString Manager::getCases()
{
try
{
return QString::fromStdString(dataMgr_->getCases());
}
catch (std::exception& e)
{
BOOST_LOG(processLog::get()) << e.what() << std::endl;
}
return {};
}
void Manager::onCaseTextChanged(const QString& text)
{
try
{
auto listStr = text.split('\n', QString::SkipEmptyParts);
std::set<std::string> cases;
for(auto i = 0; i<listStr.size(); ++i)
{
QString s = listStr[i].trimmed();
cases.insert(s.toStdString());
}
dataMgr_->clearCases();
dataMgr_->refine(cases);
if(model_)
{
model_->updateData();
}
}
catch (std::exception& ec)
{
BOOST_LOG(processLog::get()) << ec.what() << std::endl;
}
}
void Manager::start()
{
thread_->start();
}
void Manager::stop()
{
Q_EMIT stopProcess();
}
| 20.305556 | 98 | 0.626197 | kwarehit |
176daafdf6db7ff44f02abd6569e391438281f3a | 2,211 | cc | C++ | Diagnostic/mdsd/mdsd/Constants.cc | shridpant/azure-linux-extensions | 4b5e66f33d5b93b15b427a9438931f0414f12a6e | [
"Apache-2.0"
] | 266 | 2015-01-05T04:13:15.000Z | 2022-03-24T17:52:51.000Z | Diagnostic/mdsd/mdsd/Constants.cc | shridpant/azure-linux-extensions | 4b5e66f33d5b93b15b427a9438931f0414f12a6e | [
"Apache-2.0"
] | 703 | 2015-01-27T07:16:57.000Z | 2022-03-29T09:01:23.000Z | Diagnostic/mdsd/mdsd/Constants.cc | shridpant/azure-linux-extensions | 4b5e66f33d5b93b15b427a9438931f0414f12a6e | [
"Apache-2.0"
] | 276 | 2015-01-20T11:11:15.000Z | 2022-03-24T12:40:49.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "Constants.hh"
#include <fstream>
#include <string>
#define DEFINE_STRING(name, value) const std::string name { value }; const std::wstring name ## W { L ## value };
uint64_t Constants::_UniqueId { 0 };
namespace Constants {
const std::string TIMESTAMP { "TIMESTAMP" };
const std::string PreciseTimeStamp { "PreciseTimeStamp" };
namespace Compression {
const std::string lz4hc { "lz4hc" };
} // namespace Compression
namespace EventCategory {
const std::string Counter { "counter" };
const std::string Trace { "trace" };
} // namespace EventCategory
namespace AzurePropertyNames {
DEFINE_STRING(Namespace, "namespace")
DEFINE_STRING(EventName, "eventname")
DEFINE_STRING(EventVersion, "eventversion")
DEFINE_STRING(EventCategory, "eventcategory")
DEFINE_STRING(BlobVersion, "version")
DEFINE_STRING(BlobFormat, "format")
DEFINE_STRING(DataSize, "datasizeinbytes")
DEFINE_STRING(BlobSize, "blobsizeinbytes")
DEFINE_STRING(MonAgentVersion, "monagentversion")
DEFINE_STRING(CompressionType, "compressiontype")
DEFINE_STRING(MinLevel, "minlevel")
DEFINE_STRING(AccountMoniker, "accountmoniker")
DEFINE_STRING(Endpoint, "endpoint")
DEFINE_STRING(OnbehalfFields, "onbehalffields")
DEFINE_STRING(OnbehalfServiceId, "onbehalfid")
DEFINE_STRING(OnbehalfAnnotations, "onbehalfannotations")
} // namespace AzurePropertyNames
uint64_t
UniqueId()
{
static std::string digits { "0123456789ABCDEFabcdef" };
if (!Constants::_UniqueId) {
std::ifstream bootid("/proc/sys/kernel/random/boot_id", std::ifstream::in);
if (bootid.is_open()) {
uint64_t id = 0;
int nybbles = 16;
while (nybbles && bootid.good()) {
char c = bootid.get();
size_t pos = digits.find(c);
if (pos != std::string::npos) {
if (pos > 15) {
pos -= 6;
}
id <<= 4;
id += pos;
nybbles--;
}
}
if (id == 0) {
id = 1; // Backstop in case something got weird
}
Constants::_UniqueId = id;
} else {
Constants::_UniqueId = 1; // Backstop in case something got weird
}
}
return Constants::_UniqueId;
}
} // namespace Constants
// vim: se sw=8 :
| 26.638554 | 113 | 0.703302 | shridpant |
176e929ba649f73a9bb54d48b92cfc75971ffce0 | 967 | cpp | C++ | BookSamples/Capitolo7/Ritardo_BufferLineare/Ritardo_BufferLineare/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | BookSamples/Capitolo7/Ritardo_BufferLineare/Ritardo_BufferLineare/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | BookSamples/Capitolo7/Ritardo_BufferLineare/Ritardo_BufferLineare/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | #include <iostream>
#define SAMPLE_RATE 44100
using namespace std;
/* Buffer Lineare ---------------------------------------------------------- */
float D_LinBuffer(float *buffer, int D, float x)
{
int i;
for(i = D-1; i >= 1; i--)
buffer[i] = buffer[i-1];
buffer[0] = x;
return buffer[D-1];
}
int main()
{
int i, D;
const int N = 2000;
float rit = 0.005, *buffer, *y, x[N];
for (i = 0; i < N; i++)
x[i] = 2 * ((float)rand() / (float)RAND_MAX) - 1;
D = (int)(rit*SAMPLE_RATE);
buffer = (float *)calloc(D, sizeof(float));
y = (float *)calloc(N, sizeof(float));
for (i = 0; i < D; i++)
buffer[i] = 0;
for (i = 0; i < N; i++)
y[i] = D_LinBuffer(buffer, D, x[i]);
cout << "Posizione x y: " << endl << endl;
for (i = 0; i < N; i++)
cout << i + 1 << ": " << x[i] << " " << y[i] << endl;
return 0;
}
| 21.021739 | 80 | 0.416753 | mscarpiniti |
176f15fa2f0fe766ba00bdeec96e1621b8ce07d3 | 2,910 | ipp | C++ | boost/test/utils/runtime/cla/dual_name_parameter.ipp | UnPourTous/boost-159-for-rn | 47e2c37fcbd5e1b25561e5a4fc81bc4f31d2cbf4 | [
"BSL-1.0"
] | 2 | 2021-08-08T02:06:56.000Z | 2021-12-20T02:16:44.000Z | include/boost/test/utils/runtime/cla/dual_name_parameter.ipp | Acidburn0zzz/PopcornTorrent-1 | c12a30ef9e971059dae5f7ce24a8c37fef83c0c4 | [
"MIT"
] | null | null | null | include/boost/test/utils/runtime/cla/dual_name_parameter.ipp | Acidburn0zzz/PopcornTorrent-1 | c12a30ef9e971059dae5f7ce24a8c37fef83c0c4 | [
"MIT"
] | 1 | 2017-04-09T17:04:14.000Z | 2017-04-09T17:04:14.000Z | // (C) Copyright Gennadiy Rozental 2005-2014.
// Use, modification, and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : implements model of generic parameter with dual naming
// ***************************************************************************
#ifndef BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
#define BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>
#include <boost/test/utils/runtime/validation.hpp>
#include <boost/test/utils/runtime/cla/dual_name_parameter.hpp>
namespace boost {
namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE {
namespace cla {
// ************************************************************************** //
// ************** dual_name_policy ************** //
// ************************************************************************** //
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE
dual_name_policy::dual_name_policy()
{
m_primary.accept_modifier( prefix = BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "--" ) );
m_secondary.accept_modifier( prefix = BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "-" ) );
}
//____________________________________________________________________________//
namespace {
template<typename K>
inline void
split( string_name_policy& snp, char_name_policy& cnp, cstring src, K const& k )
{
cstring::iterator sep = std::find( src.begin(), src.end(), BOOST_TEST_UTILS_RUNTIME_PARAM_LITERAL( '|' ) );
if( sep != src.begin() )
snp.accept_modifier( k = cstring( src.begin(), sep ) );
if( sep != src.end() )
cnp.accept_modifier( k = cstring( sep+1, src.end() ) );
}
} // local namespace
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void
dual_name_policy::set_prefix( cstring src )
{
split( m_primary, m_secondary, src, prefix );
}
//____________________________________________________________________________//
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void
dual_name_policy::set_name( cstring src )
{
split( m_primary, m_secondary, src, name );
}
//____________________________________________________________________________//
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void
dual_name_policy::set_separator( cstring src )
{
split( m_primary, m_secondary, src, separator );
}
//____________________________________________________________________________//
} // namespace cla
} // namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE
} // namespace boost
#endif // BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
| 31.978022 | 112 | 0.669416 | UnPourTous |
1771c5a32dfefdf6a35b913d0f935a71a823278f | 3,236 | cpp | C++ | src/MeteringSDK/MCORE/MSynchronizer.cpp | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 9 | 2016-09-02T17:24:58.000Z | 2021-12-14T19:43:48.000Z | src/MeteringSDK/MCORE/MSynchronizer.cpp | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 1 | 2018-09-06T21:48:42.000Z | 2018-09-06T21:48:42.000Z | src/MeteringSDK/MCORE/MSynchronizer.cpp | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 4 | 2016-09-06T16:54:36.000Z | 2021-12-16T16:15:24.000Z | // File MCORE/MSynchronizer.cpp
#include "MCOREExtern.h"
#include "MSynchronizer.h"
#include "MException.h"
#if !M_NO_MULTITHREADING
MSynchronizer::Locker::Locker(const MSynchronizer& s)
:
m_synchronizer(const_cast<MSynchronizer&>(s)),
m_locked(false)
{
m_synchronizer.Lock();
m_locked = true;
}
MSynchronizer::Locker::Locker(const MSynchronizer& s, long timeout)
:
m_synchronizer(const_cast<MSynchronizer&>(s)),
m_locked(false)
{
m_locked = m_synchronizer.LockWithTimeout(timeout);
}
MSynchronizer::Locker::~Locker() M_NO_THROW
{
if ( m_locked )
m_synchronizer.Unlock();
}
MSynchronizer::~MSynchronizer() M_NO_THROW
{
#if (M_OS & M_OS_WIN32)
if ( m_handle != 0 )
CloseHandle(m_handle);
#elif (M_OS & M_OS_POSIX)
// In Pthreads there are pthread_mutex_t and pthread_cond_t types for synchronization objects, they are destroyed in the derived classes
#else
#error "No implementation of semaphore exists for this OS"
#endif
}
#if (M_OS & M_OS_WIN32)
bool MSynchronizer::LockWithTimeout(long timeout)
{
M_ASSERT(m_handle != 0);
switch( ::WaitForSingleObject(m_handle, timeout < 0 ? INFINITE : timeout) )
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
break;
default:
M_ASSERT(0); // An unknown code was returned once. Throw error in this case.
case WAIT_FAILED:
MESystemError::ThrowLastSystemError();
M_ENSURED_ASSERT(0);
}
return false;
}
#endif
#if (M_OS & M_OS_WIN32)
bool MSynchronizer::DoWaitForMany(long timeout, unsigned* which, MSynchronizer* p1, MSynchronizer* p2, MSynchronizer* p3, MSynchronizer* p4, MSynchronizer* p5)
{
M_ASSERT(p1 != NULL && p2 != NULL);
HANDLE handles [ 5 ];
handles[0] = p1->m_handle;
handles[1] = p2->m_handle;
DWORD handlesCount;
if ( p3 != NULL )
{
handles[2] = p3->m_handle;
if ( p4 != NULL )
{
handles[3] = p4->m_handle;
if ( p5 != NULL )
{
handles[4] = p5->m_handle;
handlesCount = 5;
}
else
handlesCount = 4;
}
else
{
M_ASSERT(p5 == NULL);
handlesCount = 3;
}
}
else
{
M_ASSERT(p4 == NULL && p5 == NULL);
handlesCount = 2;
}
DWORD ret = ::WaitForMultipleObjects(handlesCount, handles, ((which == NULL) ? TRUE : FALSE), timeout < 0 ? INFINITE : static_cast<DWORD>(timeout));
M_COMPILED_ASSERT(WAIT_OBJECT_0 == 0); // below code depends on it
if ( ret <= (WAIT_OBJECT_0 + 5) )
{
if ( which != NULL )
*which = ret;
return true;
}
if ( ret != WAIT_TIMEOUT )
{
M_ASSERT(ret == WAIT_FAILED); // WAIT_ABANDONED_x is not supported
MESystemError::ThrowLastSystemError();
M_ENSURED_ASSERT(0);
}
return false;
}
#endif
#endif
| 26.308943 | 162 | 0.554079 | beroset |
1775c6d75e541e4eece58a3bba86b1f417a43a94 | 13,250 | cpp | C++ | src/dawn/tests/unittests/ResultTests.cpp | Antidote/dawn-cmake | b8c6d669fa3c0087aa86653a4078386ffb42f199 | [
"BSD-3-Clause"
] | 1 | 2021-12-06T14:21:54.000Z | 2021-12-06T14:21:54.000Z | src/dawn/tests/unittests/ResultTests.cpp | AartOdding/dawn | f2556ab35c0eecdfd93c02f7c226a5c94316d143 | [
"BSD-3-Clause"
] | null | null | null | src/dawn/tests/unittests/ResultTests.cpp | AartOdding/dawn | f2556ab35c0eecdfd93c02f7c226a5c94316d143 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Dawn Authors
//
// 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 <gtest/gtest.h>
#include "dawn/common/RefCounted.h"
#include "dawn/common/Result.h"
namespace {
template <typename T, typename E>
void TestError(Result<T, E>* result, E expectedError) {
EXPECT_TRUE(result->IsError());
EXPECT_FALSE(result->IsSuccess());
std::unique_ptr<E> storedError = result->AcquireError();
EXPECT_EQ(*storedError, expectedError);
}
template <typename T, typename E>
void TestSuccess(Result<T, E>* result, T expectedSuccess) {
EXPECT_FALSE(result->IsError());
EXPECT_TRUE(result->IsSuccess());
const T storedSuccess = result->AcquireSuccess();
EXPECT_EQ(storedSuccess, expectedSuccess);
// Once the success is acquired, result has an empty
// payload and is neither in the success nor error state.
EXPECT_FALSE(result->IsError());
EXPECT_FALSE(result->IsSuccess());
}
static int dummyError = 0xbeef;
static float dummySuccess = 42.0f;
static const float dummyConstSuccess = 42.0f;
class AClass : public RefCounted {
public:
int a = 0;
};
// Tests using the following overload of TestSuccess make
// local Ref instances to dummySuccessObj. Tests should
// ensure any local Ref objects made along the way continue
// to point to dummySuccessObj.
template <typename T, typename E>
void TestSuccess(Result<Ref<T>, E>* result, T* expectedSuccess) {
EXPECT_FALSE(result->IsError());
EXPECT_TRUE(result->IsSuccess());
// AClass starts with a reference count of 1 and stored
// on the stack in the caller. The result parameter should
// hold the only other reference to the object.
EXPECT_EQ(expectedSuccess->GetRefCountForTesting(), 2u);
const Ref<T> storedSuccess = result->AcquireSuccess();
EXPECT_EQ(storedSuccess.Get(), expectedSuccess);
// Once the success is acquired, result has an empty
// payload and is neither in the success nor error state.
EXPECT_FALSE(result->IsError());
EXPECT_FALSE(result->IsSuccess());
// Once we call AcquireSuccess, result no longer stores
// the object. storedSuccess should contain the only other
// reference to the object.
EXPECT_EQ(storedSuccess->GetRefCountForTesting(), 2u);
}
// Result<void, E*>
// Test constructing an error Result<void, E>
TEST(ResultOnlyPointerError, ConstructingError) {
Result<void, int> result(std::make_unique<int>(dummyError));
TestError(&result, dummyError);
}
// Test moving an error Result<void, E>
TEST(ResultOnlyPointerError, MovingError) {
Result<void, int> result(std::make_unique<int>(dummyError));
Result<void, int> movedResult(std::move(result));
TestError(&movedResult, dummyError);
}
// Test returning an error Result<void, E>
TEST(ResultOnlyPointerError, ReturningError) {
auto CreateError = []() -> Result<void, int> {
return {std::make_unique<int>(dummyError)};
};
Result<void, int> result = CreateError();
TestError(&result, dummyError);
}
// Test constructing a success Result<void, E>
TEST(ResultOnlyPointerError, ConstructingSuccess) {
Result<void, int> result;
EXPECT_TRUE(result.IsSuccess());
EXPECT_FALSE(result.IsError());
}
// Test moving a success Result<void, E>
TEST(ResultOnlyPointerError, MovingSuccess) {
Result<void, int> result;
Result<void, int> movedResult(std::move(result));
EXPECT_TRUE(movedResult.IsSuccess());
EXPECT_FALSE(movedResult.IsError());
}
// Test returning a success Result<void, E>
TEST(ResultOnlyPointerError, ReturningSuccess) {
auto CreateError = []() -> Result<void, int> { return {}; };
Result<void, int> result = CreateError();
EXPECT_TRUE(result.IsSuccess());
EXPECT_FALSE(result.IsError());
}
// Result<T*, E*>
// Test constructing an error Result<T*, E>
TEST(ResultBothPointer, ConstructingError) {
Result<float*, int> result(std::make_unique<int>(dummyError));
TestError(&result, dummyError);
}
// Test moving an error Result<T*, E>
TEST(ResultBothPointer, MovingError) {
Result<float*, int> result(std::make_unique<int>(dummyError));
Result<float*, int> movedResult(std::move(result));
TestError(&movedResult, dummyError);
}
// Test returning an error Result<T*, E>
TEST(ResultBothPointer, ReturningError) {
auto CreateError = []() -> Result<float*, int> {
return {std::make_unique<int>(dummyError)};
};
Result<float*, int> result = CreateError();
TestError(&result, dummyError);
}
// Test constructing a success Result<T*, E>
TEST(ResultBothPointer, ConstructingSuccess) {
Result<float*, int> result(&dummySuccess);
TestSuccess(&result, &dummySuccess);
}
// Test moving a success Result<T*, E>
TEST(ResultBothPointer, MovingSuccess) {
Result<float*, int> result(&dummySuccess);
Result<float*, int> movedResult(std::move(result));
TestSuccess(&movedResult, &dummySuccess);
}
// Test returning a success Result<T*, E>
TEST(ResultBothPointer, ReturningSuccess) {
auto CreateSuccess = []() -> Result<float*, int*> { return {&dummySuccess}; };
Result<float*, int*> result = CreateSuccess();
TestSuccess(&result, &dummySuccess);
}
// Tests converting from a Result<TChild*, E>
TEST(ResultBothPointer, ConversionFromChildClass) {
struct T {
int a;
};
struct TChild : T {};
TChild child;
T* childAsT = &child;
{
Result<T*, int> result(&child);
TestSuccess(&result, childAsT);
}
{
Result<TChild*, int> resultChild(&child);
Result<T*, int> result(std::move(resultChild));
TestSuccess(&result, childAsT);
}
{
Result<TChild*, int> resultChild(&child);
Result<T*, int> result = std::move(resultChild);
TestSuccess(&result, childAsT);
}
}
// Result<const T*, E>
// Test constructing an error Result<const T*, E>
TEST(ResultBothPointerWithConstResult, ConstructingError) {
Result<const float*, int> result(std::make_unique<int>(dummyError));
TestError(&result, dummyError);
}
// Test moving an error Result<const T*, E>
TEST(ResultBothPointerWithConstResult, MovingError) {
Result<const float*, int> result(std::make_unique<int>(dummyError));
Result<const float*, int> movedResult(std::move(result));
TestError(&movedResult, dummyError);
}
// Test returning an error Result<const T*, E*>
TEST(ResultBothPointerWithConstResult, ReturningError) {
auto CreateError = []() -> Result<const float*, int> {
return {std::make_unique<int>(dummyError)};
};
Result<const float*, int> result = CreateError();
TestError(&result, dummyError);
}
// Test constructing a success Result<const T*, E*>
TEST(ResultBothPointerWithConstResult, ConstructingSuccess) {
Result<const float*, int> result(&dummyConstSuccess);
TestSuccess(&result, &dummyConstSuccess);
}
// Test moving a success Result<const T*, E*>
TEST(ResultBothPointerWithConstResult, MovingSuccess) {
Result<const float*, int> result(&dummyConstSuccess);
Result<const float*, int> movedResult(std::move(result));
TestSuccess(&movedResult, &dummyConstSuccess);
}
// Test returning a success Result<const T*, E*>
TEST(ResultBothPointerWithConstResult, ReturningSuccess) {
auto CreateSuccess = []() -> Result<const float*, int> { return {&dummyConstSuccess}; };
Result<const float*, int> result = CreateSuccess();
TestSuccess(&result, &dummyConstSuccess);
}
// Result<Ref<T>, E>
// Test constructing an error Result<Ref<T>, E>
TEST(ResultRefT, ConstructingError) {
Result<Ref<AClass>, int> result(std::make_unique<int>(dummyError));
TestError(&result, dummyError);
}
// Test moving an error Result<Ref<T>, E>
TEST(ResultRefT, MovingError) {
Result<Ref<AClass>, int> result(std::make_unique<int>(dummyError));
Result<Ref<AClass>, int> movedResult(std::move(result));
TestError(&movedResult, dummyError);
}
// Test returning an error Result<Ref<T>, E>
TEST(ResultRefT, ReturningError) {
auto CreateError = []() -> Result<Ref<AClass>, int> {
return {std::make_unique<int>(dummyError)};
};
Result<Ref<AClass>, int> result = CreateError();
TestError(&result, dummyError);
}
// Test constructing a success Result<Ref<T>, E>
TEST(ResultRefT, ConstructingSuccess) {
AClass success;
Ref<AClass> refObj(&success);
Result<Ref<AClass>, int> result(std::move(refObj));
TestSuccess(&result, &success);
}
// Test moving a success Result<Ref<T>, E>
TEST(ResultRefT, MovingSuccess) {
AClass success;
Ref<AClass> refObj(&success);
Result<Ref<AClass>, int> result(std::move(refObj));
Result<Ref<AClass>, int> movedResult(std::move(result));
TestSuccess(&movedResult, &success);
}
// Test returning a success Result<Ref<T>, E>
TEST(ResultRefT, ReturningSuccess) {
AClass success;
auto CreateSuccess = [&success]() -> Result<Ref<AClass>, int> {
return Ref<AClass>(&success);
};
Result<Ref<AClass>, int> result = CreateSuccess();
TestSuccess(&result, &success);
}
class OtherClass {
public:
int a = 0;
};
class Base : public RefCounted {};
class Child : public OtherClass, public Base {};
// Test constructing a Result<Ref<TChild>, E>
TEST(ResultRefT, ConversionFromChildConstructor) {
Child child;
Ref<Child> refChild(&child);
Result<Ref<Base>, int> result(std::move(refChild));
TestSuccess<Base>(&result, &child);
}
// Test copy constructing Result<Ref<TChild>, E>
TEST(ResultRefT, ConversionFromChildCopyConstructor) {
Child child;
Ref<Child> refChild(&child);
Result<Ref<Child>, int> resultChild(std::move(refChild));
Result<Ref<Base>, int> result(std::move(resultChild));
TestSuccess<Base>(&result, &child);
}
// Test assignment operator for Result<Ref<TChild>, E>
TEST(ResultRefT, ConversionFromChildAssignmentOperator) {
Child child;
Ref<Child> refChild(&child);
Result<Ref<Child>, int> resultChild(std::move(refChild));
Result<Ref<Base>, int> result = std::move(resultChild);
TestSuccess<Base>(&result, &child);
}
// Result<T, E>
// Test constructing an error Result<T, E>
TEST(ResultGeneric, ConstructingError) {
Result<std::vector<float>, int> result(std::make_unique<int>(dummyError));
TestError(&result, dummyError);
}
// Test moving an error Result<T, E>
TEST(ResultGeneric, MovingError) {
Result<std::vector<float>, int> result(std::make_unique<int>(dummyError));
Result<std::vector<float>, int> movedResult(std::move(result));
TestError(&movedResult, dummyError);
}
// Test returning an error Result<T, E>
TEST(ResultGeneric, ReturningError) {
auto CreateError = []() -> Result<std::vector<float>, int> {
return {std::make_unique<int>(dummyError)};
};
Result<std::vector<float>, int> result = CreateError();
TestError(&result, dummyError);
}
// Test constructing a success Result<T, E>
TEST(ResultGeneric, ConstructingSuccess) {
Result<std::vector<float>, int> result({1.0f});
TestSuccess(&result, {1.0f});
}
// Test moving a success Result<T, E>
TEST(ResultGeneric, MovingSuccess) {
Result<std::vector<float>, int> result({1.0f});
Result<std::vector<float>, int> movedResult(std::move(result));
TestSuccess(&movedResult, {1.0f});
}
// Test returning a success Result<T, E>
TEST(ResultGeneric, ReturningSuccess) {
auto CreateSuccess = []() -> Result<std::vector<float>, int> { return {{1.0f}}; };
Result<std::vector<float>, int> result = CreateSuccess();
TestSuccess(&result, {1.0f});
}
} // anonymous namespace
| 34.326425 | 96 | 0.631245 | Antidote |
1776a2192a86edd7a26a00d7695fe7c2cbca732a | 88 | cpp | C++ | meditation_app/model/statsmodel.cpp | mikkac/meditation_app | 26c592e0c91fd2661ab91c2f7ce020293962aa99 | [
"MIT"
] | null | null | null | meditation_app/model/statsmodel.cpp | mikkac/meditation_app | 26c592e0c91fd2661ab91c2f7ce020293962aa99 | [
"MIT"
] | null | null | null | meditation_app/model/statsmodel.cpp | mikkac/meditation_app | 26c592e0c91fd2661ab91c2f7ce020293962aa99 | [
"MIT"
] | null | null | null | #include "statsmodel.h"
StatsModel::StatsModel(QObject *parent) : QObject(parent)
{
}
| 12.571429 | 57 | 0.727273 | mikkac |
1777a8696a8ad310a7a1be3f061812d49034972b | 14,880 | cpp | C++ | examples/tsne/responsive_tsne/responsive_tsne.cpp | e-/ANN | dd485320d1eb55e821027ad09013eb10ae07db93 | [
"BSD-2-Clause"
] | 19 | 2017-08-01T05:19:55.000Z | 2022-02-02T15:13:41.000Z | examples/tsne/responsive_tsne/responsive_tsne.cpp | e-/ANN | dd485320d1eb55e821027ad09013eb10ae07db93 | [
"BSD-2-Clause"
] | 4 | 2021-06-02T00:52:37.000Z | 2022-03-12T00:15:07.000Z | examples/tsne/responsive_tsne/responsive_tsne.cpp | e-/ANN | dd485320d1eb55e821027ad09013eb10ae07db93 | [
"BSD-2-Clause"
] | 5 | 2018-09-24T17:21:05.000Z | 2021-03-02T09:59:35.000Z | #include <cfloat>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <map>
#include <algorithm>
#include <random>
#include <chrono>
#if defined _MSC_VER
#include <direct.h>
#elif defined __GNUC__
#include <sys/types.h>
#include <sys/stat.h>
#endif
#include "../lib/config.h"
#include "../lib/vptree.h"
#include "../lib/sptree.h"
#include "responsive_tsne.h"
using namespace std;
using namespace panene;
double getEEFactor(int iter, const Config& config) {
if (config.use_ee) {
if (config.use_periodic) {
if (iter % config.periodic_cycle < config.periodic_duration) return config.ee_factor;
return 1.0;
}
if (iter < config.ee_iter) return config.ee_factor;
}
return 1.0;
}
// Perform Responsive t-SNE with Progressive KDTree
void ResponsiveTSNE::run(double* X, size_t N, size_t D, double* Y, size_t no_dims, double perplexity, double theta, int rand_seed,
bool skip_random_init, size_t max_iter, size_t stop_lying_iter, size_t mom_switch_iter, Config& config) {
// Set random seed
if (skip_random_init != true) {
if (rand_seed >= 0) {
printf("Using random seed: %d\n", rand_seed);
srand((unsigned int)rand_seed);
}
else {
printf("Using current time as random seed...\n");
srand((unsigned int)time(NULL));
}
}
// Determine whether we are using an exact algorithm
if (N - 1 < 3 * perplexity) { printf("Perplexity too large for the number of data points!\n"); exit(1); }
printf("Using no_dims = %d, perplexity = %f, and theta = %f\n", no_dims, perplexity, theta);
if (theta == .0) {
printf("Exact TSNE is not supported!");
exit(-1);
}
// Set learning parameters
float total_time = .0;
clock_t start, end;
double momentum = config.momentum, final_momentum = .8;
double eta = config.eta;
double* dY = (double*)malloc(N * no_dims * sizeof(double));
if (dY == NULL) { printf("Memory allocation failed!\n"); exit(1); }
// Allocate some memory
double* uY = (double*)malloc(N * no_dims * sizeof(double));
double* gains = (double*)malloc(N * no_dims * sizeof(double));
if (uY == NULL || gains == NULL) { printf("Memory allocation failed!\n"); exit(1); }
for (int i = 0; i < N * no_dims; i++) uY[i] = .0;
for (int i = 0; i < N * no_dims; i++) gains[i] = 1.0;
start = clock();
// Initialize data source
Source source((size_t)N, (size_t)D, X);
// Initialize KNN table
size_t K = (size_t)(perplexity * 3);
Sink sink(N, K + 1);
ProgressiveKNNTable<ProgressiveKDTreeIndex<Source>, Sink> table(
&source,
&sink,
K + 1,
IndexParams(config.num_trees),
SearchParams(config.num_checks, 0, 0, config.cores),
TreeWeight(config.add_point_weight, config.update_index_weight),
TableWeight(config.tree_weight, config.table_weight));
// Normalize input data (to prevent numerical problems)
zeroMean(X, N, D);
double max_X = .0;
for (int i = 0; i < N * D; i++) {
if (fabs(X[i]) > max_X) max_X = fabs(X[i]);
}
for (int i = 0; i < N * D; i++) X[i] /= max_X;
// Initialize solution (randomly)
if (skip_random_init != true) {
srand(0);
for (int i = 0; i < N * no_dims; i++) Y[i] = randn() * .0001;
}
end = clock();
total_time += (float)(end - start) / CLOCKS_PER_SEC;
printf("took %f for setup\n", total_time);
config.event_log("initialization", total_time);
// Perform main training loop
size_t ops = config.ops;
vector<map<size_t, double>> neighbors(N); // neighbors[i] has exact K items
vector<map<size_t, double>> similarities(N); // may have more due to asymmetricity of neighborhoodship
printf("training start\n");
float old_ee_factor = 1.0f;
start = clock();
for (int iter = 0; iter < max_iter; iter++) {
float start_perplex = 0, end_perplex = 0;
float table_time = 0;
float ee_factor = getEEFactor(iter, config);
if (old_ee_factor != ee_factor) {
float ratio = ee_factor / old_ee_factor;
printf("EE changed, ratio = %3f\n", ratio);
for (auto &sim : similarities) {
for (auto &kv : sim) {
kv.second *= ratio;
}
}
}
old_ee_factor = ee_factor;
if (table.getSize() < N) {
start_perplex = clock();
updateSimilarity(&table, neighbors, similarities, Y, no_dims, perplexity, K, ops, ee_factor);
end_perplex = clock();
}
int n = table.getSize();
computeGradient(similarities, Y, n, no_dims, dY, theta, ee_factor);
// Update gains
for (int i = 0; i < n * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8);
for (int i = 0; i < n * no_dims; i++) if (gains[i] < .01) gains[i] = .01;
// Perform gradient update (with momentum and gains)
for (int i = 0; i < n * no_dims; i++) uY[i] = momentum * uY[i] - eta * gains[i] * dY[i];
for (int i = 0; i < n * no_dims; i++) Y[i] = Y[i] + uY[i];
double grad_sum = 0;
for (int i = 0; i < n * no_dims; i++) {
grad_sum += dY[i] * dY[i];
}
// Make solution zero-mean
zeroMean(Y, n, no_dims);
if(iter == mom_switch_iter) momentum = final_momentum;
// Print out progress
if (iter > 0 && (iter % config.log_per == 0 || iter == max_iter - 1)) {
end = clock();
double C = .0;
C = evaluateError(similarities, Y, N, no_dims, theta, ee_factor); // doing approximate computation here!
printf("Iteration %d: error is %f (total=%4.2f seconds, perplex=%4.2f seconds, tree=%4.2f seconds, ee_factor=%2.1f) grad_sum is %4.6f\n", iter, C, (float)(end - start) / CLOCKS_PER_SEC, (end_perplex - start_perplex) / CLOCKS_PER_SEC, table_time, ee_factor, grad_sum);
total_time += (float)(end - start) / CLOCKS_PER_SEC;
config.event_log("iter", iter, C, total_time);
config.save_embedding(iter, Y);
start = clock();
}
}
// Clean up memory
free(dY);
free(uY);
free(gains);
printf("Fitting performed in %4.2f seconds.\n", total_time);
}
void ResponsiveTSNE::updateSimilarity(Table *table,
vector<map<size_t, double>>& neighbors,
vector<map<size_t, double>>& similarities,
double* Y,
size_t no_dims,
double perplexity,
size_t K,
size_t ops,
float ee_factor) {
if (perplexity > K) printf("Perplexity should be lower than K!\n");
// Update the KNNTable
clock_t start = clock();
UpdateResult ar = table->run(ops);
clock_t end = clock();
float table_time = (end - start) / CLOCKS_PER_SEC;
/*
We need to compute val_P for points that are
1) newly inserted (points in ar.addPointResult)
2) updated (points in ar.updatePointResult)
ar.updatedIds has the ids of the updated points.
The ids of the newly added points can be computed by comparing table.getSize() and ar.addPointResult
*/
// collect all ids that need to be updated
vector<size_t> updated;
vector<double> p(K);
map<size_t, map<size_t, double>> old;
for (size_t i = table->getSize() - ar.addPointResult; i < table->getSize(); ++i) {
// point i has been newly inserted.
ar.updatedIds.insert(i);
// for newly added points, we set its initial position to the mean of its neighbors
std::vector<size_t> indices(K + 1);
table->getNeighbors(i, indices);
for (size_t j = i * no_dims; j < (i + 1) * no_dims; ++j) {
Y[j] = 0;
}
for (size_t k = 0; k < K; ++k) {
for (size_t j = 0; j < no_dims; ++j) {
Y[i * no_dims + j] += Y[indices[k + 1] * no_dims + j] / K;
}
}
}
for (size_t uid : ar.updatedIds) {
// the neighbors of uid has been updated
std::vector<size_t> indices(K + 1);
std::vector<double> distances(K + 1);
table->getNeighbors(uid, indices);
table->getDistances(uid, distances);
bool found = false;
double beta = 1.0;
double min_beta = -DBL_MAX;
double max_beta = DBL_MAX;
double tol = 1e-5;
int iter = 0;
double sum_P;
// Iterate until we found a good perplexity
while (!found && iter < 200) {
// Compute Gaussian kernel row
for (int m = 0; m < K; m++) p[m] = exp(-beta * distances[m + 1] * distances[m + 1]);
// Compute entropy of current row
sum_P = DBL_MIN;
for (int m = 0; m < K; m++) sum_P += p[m];
double H = .0;
for (int m = 0; m < K; m++) H += beta * (distances[m + 1] * distances[m + 1] * p[m]);
H = (H / sum_P) + log(sum_P);
// Evaluate whether the entropy is within the tolerance level
double Hdiff = H - log(perplexity);
if (Hdiff < tol && -Hdiff < tol) {
found = true;
}
else {
if (Hdiff > 0) {
min_beta = beta;
if (max_beta == DBL_MAX || max_beta == -DBL_MAX)
beta *= 2.0;
else
beta = (beta + max_beta) / 2.0;
}
else {
max_beta = beta;
if (min_beta == -DBL_MAX || min_beta == DBL_MAX)
beta /= 2.0;
else
beta = (beta + min_beta) / 2.0;
}
}
// Update iteration counter
iter++;
}
for (unsigned int m = 0; m < K; m++) p[m] /= sum_P;
old[uid] = neighbors[uid];
neighbors[uid].clear();
for (unsigned int m = 0; m < K; m++) {
neighbors[uid][indices[m + 1]] = p[m] * ee_factor;
}
}
for (size_t Aid : ar.updatedIds) { // point A
// neighbors changed, we need to keep the similarities symmetric
// the neighbors of uid has been updated
for (auto &it : neighbors[Aid]) { // point B
size_t Bid = it.first;
double sAB = it.second;
double sBA = 0;
if (neighbors[Bid].count(Aid) > 0)
sBA = neighbors[Bid][Aid];
similarities[Aid][Bid] = (sAB + sBA) / 2;
similarities[Bid][Aid] = (sAB + sBA) / 2;
}
for (auto &it : old[Aid]) {
size_t oldBid = it.first;
if (neighbors[Aid].count(oldBid) > 0) continue;
// exit points
double sAB = 0;
double sBA = 0;
if (neighbors[oldBid].count(Aid) > 0)
sBA = neighbors[oldBid][Aid];
if (sBA == 0) {
similarities[Aid].erase(oldBid);
similarities[oldBid].erase(Aid);
}
else {
similarities[Aid][oldBid] = (sAB + sBA) / 2;
similarities[oldBid][Aid] = (sAB + sBA) / 2;
}
}
}
//for(auto &it: similarities[0]) {
//printf("[%d] %lf\n", it.first, it.second);
//}
}
// Compute gradient of the t-SNE cost function (using Barnes-Hut algorithm)
void ResponsiveTSNE::computeGradient(vector<map<size_t, double>>& similarities, double* Y, size_t N, size_t D, double* dC, double theta, float ee_factor)
{
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
double* pos_f = (double*)calloc(N * D, sizeof(double));
double* neg_f = (double*)calloc(N * D, sizeof(double));
if (pos_f == NULL || neg_f == NULL) { printf("Memory allocation failed!\n"); exit(1); }
tree->computeEdgeForces(similarities, N, pos_f, ee_factor);
for (int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, neg_f + n * D, &sum_Q);
// Compute final t-SNE gradient
for (int i = 0; i < N * D; i++) {
dC[i] = pos_f[i] - (neg_f[i] / sum_Q);
}
free(pos_f);
free(neg_f);
delete tree;
}
// Evaluate t-SNE cost function (approximately)
double ResponsiveTSNE::evaluateError(vector<map<size_t, double>>& similarities,
double *Y, size_t N, size_t D, double theta, float ee_factor)
{
// Get estimate of normalization term
SPTree* tree = new SPTree(D, Y, N);
double* buff = (double*)calloc(D, sizeof(double));
double sum_Q = .0;
for (int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, buff, &sum_Q);
// Loop over all edges to compute t-SNE error
int ind1 = 0, ind2;
double C = .0, Q;
double sum_P = .0;
int j = 0;
for (auto &p : similarities) {
if (j >= N) break;
j++;
for (auto &it : p) {
sum_P += it.second;
}
}
sum_P /= ee_factor;
j = 0;
for (auto &p : similarities) {
if (j >= N) break;
for (auto &it : p) {
Q = .0;
ind2 = it.first * D;
for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d];
for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d];
for (int d = 0; d < D; d++) Q += buff[d] * buff[d];
Q = (1.0 / (1.0 + Q)) / sum_Q;
C += it.second / sum_P * log((it.second / sum_P + FLT_MIN) / (Q + FLT_MIN));
}
ind1 += D;
j++;
}
// Clean up memory
free(buff);
delete tree;
return C;
}
// Makes data zero-mean
void ResponsiveTSNE::zeroMean(double* X, size_t N, size_t D) {
// Compute data mean
double* mean = (double*)calloc(D, sizeof(double));
if (mean == NULL) { printf("Memory allocation failed!\n"); exit(1); }
int nD = 0;
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
mean[d] += X[nD + d];
}
nD += D;
}
for (int d = 0; d < D; d++) {
mean[d] /= (double)N;
}
// Subtract data mean
nD = 0;
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
X[nD + d] -= mean[d];
}
nD += D;
}
free(mean); mean = NULL;
}
// Generates a Gaussian random number
double ResponsiveTSNE::randn() {
double x, y, radius;
do {
x = 2 * (rand() / ((double)RAND_MAX + 1)) - 1;
y = 2 * (rand() / ((double)RAND_MAX + 1)) - 1;
radius = (x * x) + (y * y);
} while ((radius >= 1.0) || (radius == 0.0));
radius = sqrt(-2 * log(radius) / radius);
x *= radius;
y *= radius;
return x;
} | 31.194969 | 279 | 0.533199 | e- |
1777f8f85eabfe60aa7c8b3c5359577484e4340b | 3,239 | cpp | C++ | lib/Backends/CPU/CPUFunction.cpp | dendisuhubdy/glow | 14da7854a0b4de11776ba1aa6da4de8c43f67f19 | [
"Apache-2.0"
] | null | null | null | lib/Backends/CPU/CPUFunction.cpp | dendisuhubdy/glow | 14da7854a0b4de11776ba1aa6da4de8c43f67f19 | [
"Apache-2.0"
] | null | null | null | lib/Backends/CPU/CPUFunction.cpp | dendisuhubdy/glow | 14da7854a0b4de11776ba1aa6da4de8c43f67f19 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, 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 "CPUFunction.h"
#include "glow/Graph/Context.h"
#include "glow/Support/Compiler.h"
#include "glow/Support/Memory.h"
using namespace glow;
CPUFunction::CPUFunction(std::unique_ptr<llvm::orc::GlowJIT> JIT,
const runtime::RuntimeBundle &runtimeBundle)
: JIT_(std::move(JIT)), runtimeBundle_(runtimeBundle) {}
CPUFunction::~CPUFunction() { alignedFree(runtimeBundle_.constants); }
void CPUFunction::allocateMutableBuffersOnDevice() {
baseActivationsAddress_ = (uint8_t *)alignedAlloc(
runtimeBundle_.activationsMemSize, TensorAlignment);
baseMutableWeightVarsAddress_ = (uint8_t *)alignedAlloc(
runtimeBundle_.mutableWeightVarsMemSize, TensorAlignment);
}
void CPUFunction::copyInputsToDevice(Context &ctx) {
// Copy Placeholders into allocated memory.
for (auto PH : ctx.pairs()) {
auto payload = PH.second->getUnsafePtr();
auto symbolInfo =
runtimeBundle_.symbolTable.find(std::string(PH.first->getName()));
assert(symbolInfo != runtimeBundle_.symbolTable.end() &&
"Symbol not found");
auto addr = symbolInfo->second.offset;
auto numBytes = symbolInfo->second.size;
// copy PH to allocated memory.
memcpy(baseMutableWeightVarsAddress_ + addr, payload, numBytes);
}
}
void CPUFunction::copyOutputsFromDevice(Context &ctx) {
// Copy placeholders from device back into context.
for (auto PH : ctx.pairs()) {
auto symbolInfo =
runtimeBundle_.symbolTable.find(std::string(PH.first->getName()));
auto payload = baseMutableWeightVarsAddress_ + symbolInfo->second.offset;
auto numBytes = symbolInfo->second.size;
auto addr = PH.second->getUnsafePtr();
// copy PH from allocated memory.
memcpy(addr, payload, numBytes);
}
}
void CPUFunction::freeAllocations() {
alignedFree(baseMutableWeightVarsAddress_);
alignedFree(baseActivationsAddress_);
}
void CPUFunction::execute(Context &ctx) {
copyFunctionToDevice();
copyConstantsToDevice();
allocateMutableBuffersOnDevice();
copyInputsToDevice(ctx);
auto sym = JIT_->findSymbol("jitmain");
assert(sym && "Unable to JIT the code!");
using JitFuncType =
void (*)(uint8_t * constantWeightVars, uint8_t * mutableWeightVars,
uint8_t * activations);
auto address = sym.getAddress();
if (address) {
JitFuncType funcPtr = reinterpret_cast<JitFuncType>(address.get());
funcPtr(runtimeBundle_.constants, baseMutableWeightVarsAddress_,
baseActivationsAddress_);
copyOutputsFromDevice(ctx);
} else {
GLOW_ASSERT(false && "Error getting address.");
}
freeAllocations();
}
| 34.827957 | 77 | 0.719975 | dendisuhubdy |
17799c7bc5a2165217b53d8904404910a77fff2a | 10,622 | cpp | C++ | libs/spirit/example/x3/calc6.cpp | Abce/boost | 2d7491a27211aa5defab113f8e2d657c3d85ca93 | [
"BSL-1.0"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | libs/boost/libs/spirit/example/x3/calc6.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/boost/libs/spirit/example/x3/calc6.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | /*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
// Yet another calculator example! This time, we will compile to a simple
// virtual machine. This is actually one of the very first Spirit example
// circa 2000. Now, it's ported to Spirit2 (and X3).
//
// [ JDG Sometime 2000 ] pre-boost
// [ JDG September 18, 2002 ] spirit1
// [ JDG April 8, 2007 ] spirit2
// [ JDG February 18, 2011 ] Pure attributes. No semantic actions.
// [ JDG April 9, 2014 ] Spirit X3 (from qi calc6)
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Uncomment this if you want to enable debugging
//#define BOOST_SPIRIT_X3_DEBUG
#if defined(_MSC_VER)
# pragma warning(disable: 4345)
#endif
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include <string>
#include <list>
#include <numeric>
namespace x3 = boost::spirit::x3;
namespace client { namespace ast
{
///////////////////////////////////////////////////////////////////////////
// The AST
///////////////////////////////////////////////////////////////////////////
struct nil {};
struct signed_;
struct expression;
struct operand : x3::variant<
nil
, unsigned int
, x3::forward_ast<signed_>
, x3::forward_ast<expression>
>
{
using base_type::base_type;
using base_type::operator=;
};
struct signed_
{
char sign;
operand operand_;
};
struct operation
{
char operator_;
operand operand_;
};
struct expression
{
operand first;
std::list<operation> rest;
};
// print function for debugging
inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; }
}}
BOOST_FUSION_ADAPT_STRUCT(
client::ast::signed_,
(char, sign)
(client::ast::operand, operand_)
)
BOOST_FUSION_ADAPT_STRUCT(
client::ast::operation,
(char, operator_)
(client::ast::operand, operand_)
)
BOOST_FUSION_ADAPT_STRUCT(
client::ast::expression,
(client::ast::operand, first)
(std::list<client::ast::operation>, rest)
)
namespace client
{
///////////////////////////////////////////////////////////////////////////
// The Virtual Machine
///////////////////////////////////////////////////////////////////////////
enum byte_code
{
op_neg, // negate the top stack entry
op_add, // add top two stack entries
op_sub, // subtract top two stack entries
op_mul, // multiply top two stack entries
op_div, // divide top two stack entries
op_int, // push constant integer into the stack
};
class vmachine
{
public:
vmachine(unsigned stackSize = 4096)
: stack(stackSize)
, stack_ptr(stack.begin())
{
}
int top() const { return stack_ptr[-1]; };
void execute(std::vector<int> const& code);
private:
std::vector<int> stack;
std::vector<int>::iterator stack_ptr;
};
void vmachine::execute(std::vector<int> const& code)
{
std::vector<int>::const_iterator pc = code.begin();
stack_ptr = stack.begin();
while (pc != code.end())
{
switch (*pc++)
{
case op_neg:
stack_ptr[-1] = -stack_ptr[-1];
break;
case op_add:
--stack_ptr;
stack_ptr[-1] += stack_ptr[0];
break;
case op_sub:
--stack_ptr;
stack_ptr[-1] -= stack_ptr[0];
break;
case op_mul:
--stack_ptr;
stack_ptr[-1] *= stack_ptr[0];
break;
case op_div:
--stack_ptr;
stack_ptr[-1] /= stack_ptr[0];
break;
case op_int:
*stack_ptr++ = *pc++;
break;
}
}
}
///////////////////////////////////////////////////////////////////////////
// The Compiler
///////////////////////////////////////////////////////////////////////////
struct compiler
{
typedef void result_type;
std::vector<int>& code;
compiler(std::vector<int>& code)
: code(code) {}
void operator()(ast::nil) const { BOOST_ASSERT(0); }
void operator()(unsigned int n) const
{
code.push_back(op_int);
code.push_back(n);
}
void operator()(ast::operation const& x) const
{
boost::apply_visitor(*this, x.operand_);
switch (x.operator_)
{
case '+': code.push_back(op_add); break;
case '-': code.push_back(op_sub); break;
case '*': code.push_back(op_mul); break;
case '/': code.push_back(op_div); break;
default: BOOST_ASSERT(0); break;
}
}
void operator()(ast::signed_ const& x) const
{
boost::apply_visitor(*this, x.operand_);
switch (x.sign)
{
case '-': code.push_back(op_neg); break;
case '+': break;
default: BOOST_ASSERT(0); break;
}
}
void operator()(ast::expression const& x) const
{
boost::apply_visitor(*this, x.first);
for (ast::operation const& oper : x.rest)
{
(*this)(oper);
}
}
};
///////////////////////////////////////////////////////////////////////////////
// The calculator grammar
///////////////////////////////////////////////////////////////////////////////
namespace calculator_grammar
{
using x3::uint_;
using x3::char_;
struct expression_class;
struct term_class;
struct factor_class;
x3::rule<expression_class, ast::expression> const expression("expression");
x3::rule<term_class, ast::expression> const term("term");
x3::rule<factor_class, ast::operand> const factor("factor");
auto const expression_def =
term
>> *( (char_('+') > term)
| (char_('-') > term)
)
;
auto const term_def =
factor
>> *( (char_('*') > factor)
| (char_('/') > factor)
)
;
auto const factor_def =
uint_
| '(' > expression > ')'
| (char_('-') > factor)
| (char_('+') > factor)
;
BOOST_SPIRIT_DEFINE(
expression = expression_def
, term = term_def
, factor = factor_def
);
struct expression_class
{
// Our error handler
template <typename Iterator, typename Exception, typename Context>
x3::error_handler_result
on_error(Iterator&, Iterator const& last, Exception const& x, Context const& context)
{
std::cout
<< "Error! Expecting: "
<< x.which()
<< " here: \""
<< std::string(x.where(), last)
<< "\""
<< std::endl
;
return x3::error_handler_result::fail;
}
};
auto calculator = expression;
}
using calculator_grammar::calculator;
}
///////////////////////////////////////////////////////////////////////////////
// Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Expression parser...\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Type an expression...or [q or Q] to quit\n\n";
typedef std::string::const_iterator iterator_type;
typedef client::ast::expression ast_expression;
typedef client::compiler compiler;
std::string str;
while (std::getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
client::vmachine mach; // Our virtual machine
std::vector<int> code; // Our VM code
auto& calc = client::calculator; // Our grammar
ast_expression expression; // Our program (AST)
compiler compile(code); // Compiles the program
std::string::const_iterator iter = str.begin();
std::string::const_iterator end = str.end();
boost::spirit::x3::ascii::space_type space;
bool r = phrase_parse(iter, end, calc, space, expression);
if (r && iter == end)
{
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
compile(expression);
mach.execute(code);
std::cout << "\nResult: " << mach.top() << std::endl;
std::cout << "-------------------------\n";
}
else
{
std::string rest(iter, end);
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "-------------------------\n";
}
}
std::cout << "Bye... :-) \n\n";
return 0;
}
| 30.522989 | 98 | 0.419036 | Abce |
177c1a8537d1eaa642928e64cf949a250d44e614 | 10,313 | cpp | C++ | cpp/src/grammar.cpp | sapphire-lang/emerald | 5cb7209f918e8ebdb36bb0455f58d3e941fc6e52 | [
"MIT"
] | null | null | null | cpp/src/grammar.cpp | sapphire-lang/emerald | 5cb7209f918e8ebdb36bb0455f58d3e941fc6e52 | [
"MIT"
] | null | null | null | cpp/src/grammar.cpp | sapphire-lang/emerald | 5cb7209f918e8ebdb36bb0455f58d3e941fc6e52 | [
"MIT"
] | null | null | null | #include <string>
#include <regex>
#include <iostream>
#include "grammar.hpp"
// [START] Include nodes
#include "nodes/node.hpp"
#include "nodes/node_list.hpp"
#include "nodes/boolean.hpp"
#include "nodes/scope_fn.hpp"
#include "nodes/scope.hpp"
#include "nodes/line.hpp"
#include "nodes/value_list.hpp"
#include "nodes/literal_new_line.hpp"
#include "nodes/attribute.hpp"
#include "nodes/attributes.hpp"
#include "nodes/tag_statement.hpp"
#include "nodes/text_literal_content.hpp"
#include "nodes/escaped.hpp"
#include "nodes/comment.hpp"
#include "nodes/scoped_key_value_pairs.hpp"
#include "nodes/key_value_pair.hpp"
#include "nodes/unary_expr.hpp"
#include "nodes/binary_expr.hpp"
#include "nodes/each.hpp"
#include "nodes/with.hpp"
#include "nodes/conditional.hpp"
#include "nodes/variable_name.hpp"
#include "nodes/variable.hpp"
#include "nodes/scope.hpp"
// [END] Include nodes
namespace {
// Helper function to turn a maybe rule (one element, made optional with a ?) into its value or a default
template<typename T>
std::function<T(const peg::SemanticValues&)> optional(T default_value) {
return [=](const peg::SemanticValues &sv) -> T {
if (sv.size() > 0) {
return sv[0].get<T>();
} else {
return default_value;
}
};
}
// Helper to turn plural rules (one element, repeated with + or *) into a vector of a given type
template<typename T>
std::function<std::vector<T>(const peg::SemanticValues&)> repeated() {
return [](const peg::SemanticValues& sv) -> std::vector<T> {
std::vector<T> contents;
for (unsigned int n = 0; n < sv.size(); n++) {
contents.push_back(sv[n].get<T>());
}
return contents;
};
}
}
Grammar::Grammar() : emerald_parser(syntax) {
emerald_parser["ROOT"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs nodes = sv[0].get<NodePtrs>();
return NodePtr(new NodeList(nodes, "\n"));
};
emerald_parser["line"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr line = sv[0].get<NodePtr>();
return NodePtr(new Line(line));
};
emerald_parser["value_list"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr keyword = sv[0].get<NodePtr>();
NodePtrs literals = sv[1].get<NodePtrs>();
return NodePtr(new ValueList(keyword, literals));
};
emerald_parser["literal_new_line"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr inline_lit_str = sv[0].get<NodePtr>();
return NodePtr(new LiteralNewLine(inline_lit_str));
};
emerald_parser["pair_list"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs nodes;
std::string base_keyword = sv[0].get<std::string>();
std::vector<const peg::SemanticValues> semantic_values = sv[1].get<std::vector<const peg::SemanticValues>>();
std::transform(semantic_values.begin(), semantic_values.end(), nodes.begin(),
[=](const peg::SemanticValues& svs) {
NodePtrs pairs = svs[0].get<NodePtrs>();
return NodePtr(new ScopedKeyValuePairs(base_keyword, pairs));
});
return NodePtr(new NodeList(nodes, "\n"));
};
emerald_parser["scoped_key_value_pairs"] = repeated<const peg::SemanticValues>();
emerald_parser["scoped_key_value_pair"] =
[](const peg::SemanticValues& sv) -> const peg::SemanticValues {
return sv;
};
emerald_parser["key_value_pair"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string key = sv[0].get<std::string>();
NodePtr value = sv[1].get<NodePtr>();
return NodePtr(new KeyValuePair(key, value));
};
emerald_parser["comment"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr text_content = sv[0].get<NodePtr>();
return NodePtr(new Comment(text_content));
};
emerald_parser["maybe_id_name"] = optional<std::string>("");
emerald_parser["class_names"] = repeated<std::string>();
emerald_parser["tag_statement"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string tag_name = sv[0].get<std::string>();
std::string id_name = sv[1].get<std::string>();
std::vector<std::string> class_names = sv[2].get<std::vector<std::string>>();
NodePtr body = sv[3].get<NodePtr>();
NodePtr attributes = sv[4].get<NodePtr>();
NodePtr nested = sv[5].get<NodePtr>();
return NodePtr(
new TagStatement(tag_name, id_name, class_names, body, attributes, nested));
};
emerald_parser["attr_list"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs nodes = sv[0].get<NodePtrs>();
return NodePtr(new Attributes(nodes));
};
emerald_parser["attribute"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string key = sv[0].get<std::string>();
NodePtr value = sv[1].get<NodePtr>();
return NodePtr(new Attribute(key, value));
};
emerald_parser["escaped"] =
[](const peg::SemanticValues& sv) -> NodePtr {
return NodePtr(new Escaped(sv.str()));
};
emerald_parser["maybe_negation"] = optional<bool>(false);
emerald_parser["negation"] =
[](const peg::SemanticValues& sv) -> bool {
return true;
};
emerald_parser["unary_expr"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
bool negated = sv[0].get<bool>();
BooleanPtr expr = sv[1].get<BooleanPtr>();
return BooleanPtr(new UnaryExpr(negated, expr));
};
emerald_parser["binary_expr"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
BooleanPtr lhs = sv[0].get<BooleanPtr>();
std::string op_str = sv[1].get<peg::SemanticValues>().str();
BooleanPtr rhs = sv[2].get<BooleanPtr>();
BinaryExpr::Operator op;
if (op_str == BinaryExpr::OR_STR) {
op = BinaryExpr::Operator::OR;
} else if (op_str == BinaryExpr::AND_STR) {
op = BinaryExpr::Operator::AND;
} else {
throw "Invalid operator: " + op_str;
}
return BooleanPtr(new BinaryExpr(lhs, op, rhs));
};
emerald_parser["boolean_expr"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
return sv[0].get<BooleanPtr>();
};
emerald_parser["maybe_key_name"] = optional<std::string>("");
emerald_parser["each"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
std::string collection_name = sv[0].get<std::string>();
std::string val_name = sv[1].get<std::string>();
std::string key_name = sv[2].get<std::string>();
return ScopeFnPtr(new Each(collection_name, val_name, key_name));
};
emerald_parser["with"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
std::string var_name = sv[0].get<std::string>();
return ScopeFnPtr(new With(var_name));
};
emerald_parser["given"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
BooleanPtr condition = sv[0].get<BooleanPtr>();
return ScopeFnPtr(new Conditional(true, condition));
};
emerald_parser["unless"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
BooleanPtr condition = sv[0].get<BooleanPtr>();
return ScopeFnPtr(new Conditional(false, condition));
};
emerald_parser["scope_fn"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
return sv[0].get<ScopeFnPtr>();
};
emerald_parser["variable_name"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
std::string name = sv.str();
return BooleanPtr(new VariableName(name));
};
emerald_parser["variable"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string name = sv.token(0);
return NodePtr(new Variable(name));
};
emerald_parser["scope"] =
[](const peg::SemanticValues& sv) -> NodePtr {
ScopeFnPtr scope_fn = sv[0].get<ScopeFnPtr>();
NodePtr body = sv[1].get<NodePtr>();
return NodePtr(new Scope(scope_fn, body));
};
// Repeated Nodes
const std::vector<std::string> repeated_nodes = {
"statements", "literal_new_lines", "key_value_pairs", "ml_lit_str_quoteds",
"ml_templess_lit_str_qs", "inline_literals", "il_lit_str_quoteds", "attributes"
};
for (std::string repeated_node : repeated_nodes) {
emerald_parser[repeated_node.c_str()] = repeated<NodePtr>();
}
// Wrapper Nodes
const std::vector<std::string> wrapper_nodes = {
"statement", "text_content", "ml_lit_str_quoted", "ml_templess_lit_str_q",
"inline_literal", "il_lit_str_quoted", "nested_tag"
};
for (std::string wrapper_node : wrapper_nodes) {
emerald_parser[wrapper_node.c_str()] =
[](const peg::SemanticValues& sv) -> NodePtr {
return sv[0].get<NodePtr>();
};
}
// Literals
const std::vector<std::string> literals = {
"multiline_literal", "inline_lit_str", "inline_literals_node"
};
for (std::string string_rule : literals) {
emerald_parser[string_rule.c_str()] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs body = sv[0].get<NodePtrs>();
return NodePtr(new NodeList(body, ""));
};
}
// Literal Contents
const std::vector<std::string> literal_contents = {
"ml_lit_content", "il_lit_content", "il_lit_str_content"
};
for (std::string string_rule_content : literal_contents) {
emerald_parser[string_rule_content.c_str()] =
[](const peg::SemanticValues& sv) -> NodePtr {
return NodePtr(new TextLiteralContent(sv.str()));
};
}
const std::vector<std::string> optional_nodes = {
"maybe_text_content", "maybe_nested_tag", "maybe_attr_list"
};
for (std::string rule_name : optional_nodes) {
emerald_parser[rule_name.c_str()] = optional<NodePtr>(NodePtr());
}
// Terminals
const std::vector<std::string> terminals = {
"attr", "tag", "class_name", "id_name", "key_name"
};
for (std::string rule_name : terminals) {
emerald_parser[rule_name.c_str()] =
[](const peg::SemanticValues& sv) -> std::string {
return sv.str();
};
}
emerald_parser.enable_packrat_parsing();
}
Grammar& Grammar::get_instance() {
static Grammar instance;
return instance;
}
peg::parser Grammar::get_parser() {
return emerald_parser;
}
bool Grammar::valid(const std::string &input) {
std::string output;
emerald_parser.parse(input.c_str(), output);
return output.length() == input.length();
}
| 30.332353 | 115 | 0.641617 | sapphire-lang |
177d8fec35d876499f29631cb9b8e062cd919d16 | 1,400 | cpp | C++ | src/exr.cpp | Fadis/hermit | 1b378fb94165e0348d11d8065d3259d14c49977b | [
"BSD-2-Clause"
] | 1 | 2015-03-09T05:54:01.000Z | 2015-03-09T05:54:01.000Z | src/exr.cpp | Fadis/hermit | 1b378fb94165e0348d11d8065d3259d14c49977b | [
"BSD-2-Clause"
] | null | null | null | src/exr.cpp | Fadis/hermit | 1b378fb94165e0348d11d8065d3259d14c49977b | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
//#include <boost/gil/gil_all.hpp>
#include <OpenEXR/ImfRgbaFile.h>
#include <OpenEXR/ImfArray.h>
/*
template <typename View>
void apply(const View& view) {
Imf::RgbaInputFile file ( "sample.exr" );
Imath::Box2i dw = file.dataWindow();
int width = dw.max.x - dw.min.x + 1;
int height = dw.max.y - dw.min.y + 1;
std::cout << width << "x" << height << std::endl;
Imf::Array2D<Imf::Rgba> pixels;
pixels.resizeErase (height, width);
file.setFrameBuffer( &pixels[0][0] - dw.min.x - dw.min.y * width, 1, width );
file.readPixels (dw.min.y, dw.max.y);
std::vector<pixel<bits8,layout<typename color_space_type<View>::type> > > row(view.width());
JSAMPLE* row_address=(JSAMPLE*)&row.front();
for(int y=0;y<view.height();++y) {
io_error_if(jpeg_read_scanlines(&_cinfo,(JSAMPARRAY)&row_address,1)!=1,
"jpeg_reader::apply(): fail to read JPEG file");
std::copy(row.begin(),row.end(),view.row_begin(y));
}
}
*/
int main() {
Imf::RgbaInputFile file ( "sample.exr" );
Imath::Box2i dw = file.dataWindow();
int width = dw.max.x - dw.min.x + 1;
int height = dw.max.y - dw.min.y + 1;
std::cout << width << "x" << height << std::endl;
Imf::Array2D<Imf::Rgba> pixels;
pixels.resizeErase (height, width);
file.setFrameBuffer( &pixels[0][0] - dw.min.x - dw.min.y * width, 1, width );
file.readPixels (dw.min.y, dw.max.y);
}
| 35 | 94 | 0.634286 | Fadis |
6aff1cbc36c117388cfe32f298a60e47dd492307 | 15,353 | cc | C++ | content/browser/media/capture/aura_window_capture_machine.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | content/browser/media/capture/aura_window_capture_machine.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | content/browser/media/capture/aura_window_capture_machine.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium 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 "content/browser/media/capture/aura_window_capture_machine.h"
#include <algorithm>
#include <utility>
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "cc/output/copy_output_request.h"
#include "cc/output/copy_output_result.h"
#include "components/display_compositor/gl_helper.h"
#include "content/browser/compositor/image_transport_factory.h"
#include "content/browser/media/capture/desktop_capture_device_uma_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/power_save_blocker.h"
#include "media/base/video_capture_types.h"
#include "media/base/video_util.h"
#include "media/capture/content/thread_safe_capture_oracle.h"
#include "media/capture/content/video_capture_oracle.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/cursor/cursors_aura.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/dip_util.h"
#include "ui/compositor/layer.h"
#include "ui/wm/public/activation_client.h"
namespace content {
AuraWindowCaptureMachine::AuraWindowCaptureMachine()
: desktop_window_(NULL),
screen_capture_(false),
weak_factory_(this) {}
AuraWindowCaptureMachine::~AuraWindowCaptureMachine() {}
void AuraWindowCaptureMachine::Start(
const scoped_refptr<media::ThreadSafeCaptureOracle>& oracle_proxy,
const media::VideoCaptureParams& params,
const base::Callback<void(bool)> callback) {
// Starts the capture machine asynchronously.
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI,
FROM_HERE,
base::Bind(&AuraWindowCaptureMachine::InternalStart,
base::Unretained(this),
oracle_proxy,
params),
callback);
}
bool AuraWindowCaptureMachine::InternalStart(
const scoped_refptr<media::ThreadSafeCaptureOracle>& oracle_proxy,
const media::VideoCaptureParams& params) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// The window might be destroyed between SetWindow() and Start().
if (!desktop_window_)
return false;
// If the associated layer is already destroyed then return failure.
ui::Layer* layer = desktop_window_->layer();
if (!layer)
return false;
DCHECK(oracle_proxy);
oracle_proxy_ = oracle_proxy;
capture_params_ = params;
// Update capture size.
UpdateCaptureSize();
// Start observing compositor updates.
aura::WindowTreeHost* const host = desktop_window_->GetHost();
ui::Compositor* const compositor = host ? host->compositor() : nullptr;
if (!compositor)
return false;
compositor->AddAnimationObserver(this);
power_save_blocker_.reset(
PowerSaveBlocker::Create(
PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
PowerSaveBlocker::kReasonOther,
"DesktopCaptureDevice is running").release());
return true;
}
void AuraWindowCaptureMachine::Stop(const base::Closure& callback) {
// Stops the capture machine asynchronously.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::Bind(
&AuraWindowCaptureMachine::InternalStop,
base::Unretained(this),
callback));
}
void AuraWindowCaptureMachine::InternalStop(const base::Closure& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Cancel any and all outstanding callbacks owned by external modules.
weak_factory_.InvalidateWeakPtrs();
power_save_blocker_.reset();
// Stop observing compositor and window events.
if (desktop_window_) {
if (aura::WindowTreeHost* host = desktop_window_->GetHost()) {
if (ui::Compositor* compositor = host->compositor())
compositor->RemoveAnimationObserver(this);
}
desktop_window_->RemoveObserver(this);
desktop_window_ = NULL;
cursor_renderer_.reset();
}
callback.Run();
}
void AuraWindowCaptureMachine::MaybeCaptureForRefresh() {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&AuraWindowCaptureMachine::Capture,
// Use of Unretained() is safe here since this task must run
// before InternalStop().
base::Unretained(this),
base::TimeTicks()));
}
void AuraWindowCaptureMachine::SetWindow(aura::Window* window) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!desktop_window_);
desktop_window_ = window;
cursor_renderer_.reset(new CursorRendererAura(window, kCursorAlwaysEnabled));
// Start observing window events.
desktop_window_->AddObserver(this);
// We must store this for the UMA reporting in DidCopyOutput() as
// desktop_window_ might be destroyed at that point.
screen_capture_ = window->IsRootWindow();
IncrementDesktopCaptureCounter(screen_capture_ ? SCREEN_CAPTURER_CREATED
: WINDOW_CAPTURER_CREATED);
}
void AuraWindowCaptureMachine::UpdateCaptureSize() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (oracle_proxy_ && desktop_window_) {
ui::Layer* layer = desktop_window_->layer();
oracle_proxy_->UpdateCaptureSize(ui::ConvertSizeToPixel(
layer, layer->bounds().size()));
}
cursor_renderer_->Clear();
}
void AuraWindowCaptureMachine::Capture(base::TimeTicks event_time) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Do not capture if the desktop window is already destroyed.
if (!desktop_window_)
return;
scoped_refptr<media::VideoFrame> frame;
media::ThreadSafeCaptureOracle::CaptureFrameCallback capture_frame_cb;
// TODO(miu): Need to fix this so the compositor is providing the presentation
// timestamps and damage regions, to leverage the frame timestamp rewriting
// logic. http://crbug.com/492839
const base::TimeTicks start_time = base::TimeTicks::Now();
media::VideoCaptureOracle::Event event;
if (event_time.is_null()) {
event = media::VideoCaptureOracle::kActiveRefreshRequest;
event_time = start_time;
} else {
event = media::VideoCaptureOracle::kCompositorUpdate;
}
if (oracle_proxy_->ObserveEventAndDecideCapture(
event, gfx::Rect(), event_time, &frame, &capture_frame_cb)) {
std::unique_ptr<cc::CopyOutputRequest> request =
cc::CopyOutputRequest::CreateRequest(base::Bind(
&AuraWindowCaptureMachine::DidCopyOutput,
weak_factory_.GetWeakPtr(), frame, event_time, start_time,
capture_frame_cb));
gfx::Rect window_rect = gfx::Rect(desktop_window_->bounds().width(),
desktop_window_->bounds().height());
request->set_area(window_rect);
desktop_window_->layer()->RequestCopyOfOutput(std::move(request));
}
}
void AuraWindowCaptureMachine::DidCopyOutput(
scoped_refptr<media::VideoFrame> video_frame,
base::TimeTicks event_time,
base::TimeTicks start_time,
const CaptureFrameCallback& capture_frame_cb,
std::unique_ptr<cc::CopyOutputResult> result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
static bool first_call = true;
const bool succeeded = ProcessCopyOutputResponse(
video_frame, event_time, capture_frame_cb, std::move(result));
const base::TimeDelta capture_time = base::TimeTicks::Now() - start_time;
// The two UMA_ blocks must be put in its own scope since it creates a static
// variable which expected constant histogram name.
if (screen_capture_) {
UMA_HISTOGRAM_TIMES(kUmaScreenCaptureTime, capture_time);
} else {
UMA_HISTOGRAM_TIMES(kUmaWindowCaptureTime, capture_time);
}
if (first_call) {
first_call = false;
if (screen_capture_) {
IncrementDesktopCaptureCounter(succeeded ? FIRST_SCREEN_CAPTURE_SUCCEEDED
: FIRST_SCREEN_CAPTURE_FAILED);
} else {
IncrementDesktopCaptureCounter(succeeded
? FIRST_WINDOW_CAPTURE_SUCCEEDED
: FIRST_WINDOW_CAPTURE_FAILED);
}
}
// If ProcessCopyOutputResponse() failed, it will not run |capture_frame_cb|,
// so do that now.
if (!succeeded)
capture_frame_cb.Run(video_frame, event_time, false);
}
bool AuraWindowCaptureMachine::ProcessCopyOutputResponse(
scoped_refptr<media::VideoFrame> video_frame,
base::TimeTicks event_time,
const CaptureFrameCallback& capture_frame_cb,
std::unique_ptr<cc::CopyOutputResult> result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!desktop_window_) {
VLOG(1) << "Ignoring CopyOutputResult: Capture target has gone away.";
return false;
}
if (result->IsEmpty()) {
VLOG(1) << "CopyOutputRequest failed: No texture or bitmap in result.";
return false;
}
if (result->size().IsEmpty()) {
VLOG(1) << "CopyOutputRequest failed: Zero-area texture/bitmap result.";
return false;
}
DCHECK(video_frame);
// Compute the dest size we want after the letterboxing resize. Make the
// coordinates and sizes even because we letterbox in YUV space
// (see CopyRGBToVideoFrame). They need to be even for the UV samples to
// line up correctly.
// The video frame's visible_rect() and the result's size() are both physical
// pixels.
gfx::Rect region_in_frame = media::ComputeLetterboxRegion(
video_frame->visible_rect(), result->size());
region_in_frame = gfx::Rect(region_in_frame.x() & ~1,
region_in_frame.y() & ~1,
region_in_frame.width() & ~1,
region_in_frame.height() & ~1);
if (region_in_frame.IsEmpty()) {
VLOG(1) << "Aborting capture: Computed empty letterboxed content region.";
return false;
}
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
display_compositor::GLHelper* gl_helper = factory->GetGLHelper();
if (!gl_helper) {
VLOG(1) << "Aborting capture: No GLHelper available for YUV readback.";
return false;
}
cc::TextureMailbox texture_mailbox;
std::unique_ptr<cc::SingleReleaseCallback> release_callback;
result->TakeTexture(&texture_mailbox, &release_callback);
DCHECK(texture_mailbox.IsTexture());
if (!texture_mailbox.IsTexture()) {
VLOG(1) << "Aborting capture: Failed to take texture from mailbox.";
return false;
}
gfx::Rect result_rect(result->size());
if (!yuv_readback_pipeline_ ||
yuv_readback_pipeline_->scaler()->SrcSize() != result_rect.size() ||
yuv_readback_pipeline_->scaler()->SrcSubrect() != result_rect ||
yuv_readback_pipeline_->scaler()->DstSize() != region_in_frame.size()) {
yuv_readback_pipeline_.reset(gl_helper->CreateReadbackPipelineYUV(
display_compositor::GLHelper::SCALER_QUALITY_FAST, result_rect.size(),
result_rect, region_in_frame.size(), true, true));
}
cursor_renderer_->SnapshotCursorState(region_in_frame);
yuv_readback_pipeline_->ReadbackYUV(
texture_mailbox.mailbox(), texture_mailbox.sync_token(),
video_frame->visible_rect(),
video_frame->stride(media::VideoFrame::kYPlane),
video_frame->data(media::VideoFrame::kYPlane),
video_frame->stride(media::VideoFrame::kUPlane),
video_frame->data(media::VideoFrame::kUPlane),
video_frame->stride(media::VideoFrame::kVPlane),
video_frame->data(media::VideoFrame::kVPlane), region_in_frame.origin(),
base::Bind(&CopyOutputFinishedForVideo, weak_factory_.GetWeakPtr(),
event_time, capture_frame_cb, video_frame,
base::Passed(&release_callback)));
media::LetterboxYUV(video_frame.get(), region_in_frame);
return true;
}
using CaptureFrameCallback =
media::ThreadSafeCaptureOracle::CaptureFrameCallback;
void AuraWindowCaptureMachine::CopyOutputFinishedForVideo(
base::WeakPtr<AuraWindowCaptureMachine> machine,
base::TimeTicks event_time,
const CaptureFrameCallback& capture_frame_cb,
const scoped_refptr<media::VideoFrame>& target,
std::unique_ptr<cc::SingleReleaseCallback> release_callback,
bool result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
release_callback->Run(gpu::SyncToken(), false);
// Render the cursor and deliver the captured frame if the
// AuraWindowCaptureMachine has not been stopped (i.e., the WeakPtr is
// still valid).
if (machine) {
if (machine->cursor_renderer_ && result)
machine->cursor_renderer_->RenderOnVideoFrame(target);
} else {
VLOG(1) << "Aborting capture: AuraWindowCaptureMachine has gone away.";
result = false;
}
capture_frame_cb.Run(target, event_time, result);
}
void AuraWindowCaptureMachine::OnWindowBoundsChanged(
aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(desktop_window_ && window == desktop_window_);
// Post a task to update capture size after first returning to the event loop.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
&AuraWindowCaptureMachine::UpdateCaptureSize,
weak_factory_.GetWeakPtr()));
}
void AuraWindowCaptureMachine::OnWindowDestroying(aura::Window* window) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
InternalStop(base::Bind(&base::DoNothing));
oracle_proxy_->ReportError(FROM_HERE, "OnWindowDestroying()");
}
void AuraWindowCaptureMachine::OnWindowAddedToRootWindow(
aura::Window* window) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(window == desktop_window_);
if (aura::WindowTreeHost* host = window->GetHost()) {
if (ui::Compositor* compositor = host->compositor())
compositor->AddAnimationObserver(this);
}
}
void AuraWindowCaptureMachine::OnWindowRemovingFromRootWindow(
aura::Window* window,
aura::Window* new_root) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(window == desktop_window_);
if (aura::WindowTreeHost* host = window->GetHost()) {
if (ui::Compositor* compositor = host->compositor())
compositor->RemoveAnimationObserver(this);
}
}
void AuraWindowCaptureMachine::OnAnimationStep(base::TimeTicks timestamp) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!timestamp.is_null());
// HACK: The compositor invokes this observer method to step layer animation
// forward. Scheduling frame capture was not the intention, and so invoking
// this method does not actually indicate the content has changed. However,
// this is the only reliable way to ensure all screen changes are captured, as
// of this writing.
// http://crbug.com/600031
//
// TODO(miu): Need a better observer callback interface from the compositor
// for this use case. The solution here will always capture frames at the
// maximum framerate, which means CPU/GPU is being wasted on redundant
// captures and quality/smoothness of animating content will suffer
// significantly.
// http://crbug.com/492839
Capture(timestamp);
}
void AuraWindowCaptureMachine::OnCompositingShuttingDown(
ui::Compositor* compositor) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
compositor->RemoveAnimationObserver(this);
}
} // namespace content
| 36.467933 | 80 | 0.72038 | maidiHaitai |