hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cd86441438ba4a0fa1de75ba9e52fa19e1718bb | 572 | inl | C++ | Native/Framework/source/Library.Shared/Transform.inl | btrowbridge/DirectX.2D.Bespoke.Games | 382728f7c9d50597f9fc84e222efd468c33716a5 | [
"MS-PL"
] | null | null | null | Native/Framework/source/Library.Shared/Transform.inl | btrowbridge/DirectX.2D.Bespoke.Games | 382728f7c9d50597f9fc84e222efd468c33716a5 | [
"MS-PL"
] | null | null | null | Native/Framework/source/Library.Shared/Transform.inl | btrowbridge/DirectX.2D.Bespoke.Games | 382728f7c9d50597f9fc84e222efd468c33716a5 | [
"MS-PL"
] | null | null | null | #pragma once
namespace Library
{
inline const DirectX::XMFLOAT3& Transform::Position() const
{
return mPosition;
}
inline void Transform::SetPosition(const DirectX::XMFLOAT3& position)
{
mPosition = position;
}
inline const Quaternion& Transform::Rotation() const
{
return mRotation;
}
inline void Transform::SetRotation(const Quaternion& rotation)
{
mRotation = rotation;
}
inline const DirectX::XMFLOAT3& Transform::Scale() const
{
return mScale;
}
inline void Transform::SetScale(const DirectX::XMFLOAT3& scale)
{
mScale = scale;
}
} | 16.823529 | 70 | 0.72028 | [
"transform"
] |
0cd878893a13855d1a1655da460aebe991f003a4 | 653 | hpp | C++ | src/tree/block/statements.hpp | Azer0s/Hephaistos | 7258cc5ceb2fa56dfecd0ee481768544fa3f276b | [
"MIT"
] | 1 | 2019-05-22T11:04:16.000Z | 2019-05-22T11:04:16.000Z | src/tree/block/statements.hpp | Azer0s/Hephaistos | 7258cc5ceb2fa56dfecd0ee481768544fa3f276b | [
"MIT"
] | null | null | null | src/tree/block/statements.hpp | Azer0s/Hephaistos | 7258cc5ceb2fa56dfecd0ee481768544fa3f276b | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <memory>
#include "../nodes.hpp"
namespace hephaistos {
class Statements : public SyntaxTree{
public:
Statements(SyntaxTree* c_tree, SyntaxTree* c_subtree){
tree = c_tree;
subtree = c_subtree;
};
virtual ~Statements(){
delete tree;
delete subtree;
};
virtual std::string toCode() const{
return tree->toCode() + ";\n" + subtree->toCode();
};
private:
SyntaxTree* tree;
SyntaxTree* subtree;
};
} | 25.115385 | 66 | 0.499234 | [
"vector"
] |
0ce872498fad11027c4e1896cf5d8721b1095f93 | 34,702 | cpp | C++ | Source/modules/eb/MFP_eb_divergence.cpp | darylbond/cerberus | a1b99f6b50ba6876d4705f26e6be98ed6e1c5c6a | [
"MIT"
] | 5 | 2021-05-10T01:21:52.000Z | 2022-03-10T17:26:41.000Z | Source/modules/eb/MFP_eb_divergence.cpp | darylbond/cerberus | a1b99f6b50ba6876d4705f26e6be98ed6e1c5c6a | [
"MIT"
] | 3 | 2021-05-26T01:12:12.000Z | 2021-12-14T00:34:06.000Z | Source/modules/eb/MFP_eb_divergence.cpp | darylbond/cerberus | a1b99f6b50ba6876d4705f26e6be98ed6e1c5c6a | [
"MIT"
] | 3 | 2021-05-11T02:45:27.000Z | 2021-09-06T12:08:23.000Z | #ifdef AMREX_USE_EB
#include "MFP_eb_divergence.H"
#include <AMReX_YAFluxRegister.H>
using CellType = YAFluxRegister::CellType;
#include "MFP_state.H"
#include "MFP_global.H"
#include "sol.hpp"
#ifdef PYTHON
#include "matplotlibcpp.h"
#include "MFP_diagnostics.H"
namespace plt = matplotlibcpp;
#endif
using GD = GlobalData;
DivergenceEB::DivergenceEB()
{
}
DivergenceEB::~DivergenceEB()
{
}
void DivergenceEB::calc_eb_divergence(const Box& box,
const FArrayBox &cons,
Array<FArrayBox, AMREX_SPACEDIM> &fluxes,
Array<FArrayBox, AMREX_SPACEDIM> &wall_fluxes,
FArrayBox& du,
const EBCellFlagFab& flag,
const FArrayBox& vfrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &afrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &fcent,
int as_crse,
int as_fine,
const IArrayBox *rrflag_as_crse,
const IArrayBox &levmsk,
FArrayBox *rr_drho_crse,
FArrayBox &dm_as_fine,
const Real *dx,
const Real dt) const
{
// do nothing
}
void DivergenceEB::merge_cells(const Box& box,
FArrayBox &cons,
FArrayBox& du,
const EBCellFlagFab& flag,
const FArrayBox& vfrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &afrac,
int as_fine,
FArrayBox &dm_as_fine,
const IArrayBox& levmsk) const
{
// do nothing
}
bool DivergenceEB::is_inside(const int i,const int j, const int k, const Dim3 &lo, const Dim3 &hi)
{
return i >= lo.x && i <= hi.x &&
j >= lo.y && j <= hi.y &&
k >= lo.z && k <= hi.z;
}
PhysicsFactory<DivergenceEB>& GetDivergenceEBBuilder()
{
static PhysicsFactory<DivergenceEB> F;
return F;
}
//=============================================================================
std::string RedistributeEB::tag = "redistribute";
bool RedistributeEB::registered = GetDivergenceEBBuilder().Register(RedistributeEB::tag, DivergenceEBBuilder<RedistributeEB>);
Vector<std::string> RedistributeEB::options = {"uniform", "volume", "density", "energy"};
RedistributeEB::RedistributeEB()
{
}
RedistributeEB::RedistributeEB(const sol::table &def)
{
global_idx = def["global_idx"];
// get the redistribution strategy
const sol::table &div_def = def["eb_divergence"];
std::string redist = div_def.get_or<std::string>("strategy", "volume");
const auto found = findInVector(options,redist);
if (found.first) {
redistribution_strategy = (RedistributionEB)found.second;
} else {
Abort("Invalid redistribution option '"+redist+"', valid options are "+vec2str(options));
}
if (redist == "density") {
State &istate = GD::get_state(global_idx);
if (istate.get_cons_density_idx() < 0)
Abort("Invalid redistribution option '"+redist+"' for state "+istate.name+" as it does not have a density");
}
// get the reredistribution threshold
reredistribution_threshold = div_def.get_or("reredistribution_threshold", 1.0e-14);
}
RedistributeEB::~RedistributeEB()
{
}
void RedistributeEB::calc_eb_divergence(const Box& box,
const FArrayBox &cons,
Array<FArrayBox, AMREX_SPACEDIM> &fluxes,
Array<FArrayBox, AMREX_SPACEDIM> &wall_fluxes,
FArrayBox& du,
const EBCellFlagFab& flag,
const FArrayBox& vfrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &afrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &fcent,
int as_crse, int as_fine,
const IArrayBox *rrflag_as_crse,
const IArrayBox &levmsk,
FArrayBox *rr_drho_crse,
FArrayBox &dm_as_fine,
const Real *dx,
const Real dt) const
{
BL_PROFILE("RedistributeEB::calc_eb_divergence");
State &istate = GD::get_state(global_idx);
// make sure arrays are empty
du.setVal(0.0);
dm_as_fine.setVal(0.0);
int nc = istate.n_cons();
Vector<Real> U(nc);
const Dim3 lo = amrex::lbound(box);
const Dim3 hi = amrex::ubound(box);
Array<int,3> index = {0,0,0};
Array4<const Real> const& cons4 = cons.array();
Array4<Real> const& du4 = du.array();
Array4<const int> const& rr_flag_crse4 = rrflag_as_crse->array();
Array4<const int> const& levmsk4 = levmsk.array();
Array4<Real> const& rr_drho_crse4 = rr_drho_crse->array();
Array4<Real> const& dm_as_fine4 = dm_as_fine.array();
Array<Array4<Real>,AMREX_SPACEDIM> flux4, wflux4;
Array4<const EBCellFlag> const& flag4 = flag.array();
Array4<const Real> const& vfrac4 = vfrac.array();
Array<Array4<const Real>,AMREX_SPACEDIM> afrac4;
Array<Array4<const Real>,AMREX_SPACEDIM> fcent4;
for (int d=0; d<AMREX_SPACEDIM; ++d) {
flux4[d] = fluxes[d].array();
wflux4[d] = wall_fluxes[d].array();
afrac4[d] = afrac[d]->array();
fcent4[d] = fcent[d]->array();
}
FArrayBox divc(grow(box,2),nc); // check size
Array4<Real> const& divc4 = divc.array();
FArrayBox rediswgt(grow(box,2)); // check size
Array4<Real> const& rediswgt4 = rediswgt.array();
Real dxinv[AMREX_SPACEDIM] = {AMREX_D_DECL(dt/dx[0],dt/dx[1],dt/dx[2])};
std::vector<std::array<int,3>> grab;
multi_dim_index({-1,AMREX_D_PICK(0,-1,-1),AMREX_D_PICK(0,0,-1)},
{1,AMREX_D_PICK(0, 1, 1),AMREX_D_PICK(0,0, 1)},
grab, false);
for (int k = lo.z-AMREX_D_PICK(0,0,2); k <= hi.z+AMREX_D_PICK(0,0,2); ++k) {
for (int j = lo.y-AMREX_D_PICK(0,2,2); j <= hi.y+AMREX_D_PICK(0,2,2); ++j) {
AMREX_PRAGMA_SIMD
for (int i = lo.x-2; i <= hi.x+2; ++i) {
const EBCellFlag &cflag = flag4(i,j,k);
Real vf = vfrac4(i,j,k);
if (vf <= 0.0) {
for (int n=0; n<nc; ++n) {
divc4(i,j,k,n) = 0.0;
}
} else if (vf >= 1.0) {
for (int n=0; n<nc; ++n) {
Real div = 0.0;
for (int d=0; d<AMREX_SPACEDIM; ++d) {
index[d] = 1;
div += dxinv[d]*(flux4[d](i,j,k,n) - flux4[d](i+index[0], j+index[1], k+index[2], n));
index[d] = 0;
}
divc4(i,j,k,n) = div;
}
} else {
// contribution from the standard fluxes
for (int n=0; n<nc; ++n) {
/* Use a weighted combination of fluxes from the surrounding faces
* to calculate the flux for this face, rather than just use the
* area-fraction of the flux.
* e.g. in 3D, for face (i,j) that has a cut in the top right we use a combination
* of the fluxes on faces to the left (i-1,j), below-left (i-1,j-1), and
* below (i,j-1)
*
* -------- -------
* | | \**|
* | i-1,j | i,j \*|
* | | |
* -------- -------
* | | |
* |i-1,j-1 | i,j-1 |
* | | |
* -------- -------
*/
Array<Array<Real,2>,AMREX_SPACEDIM> flux;
for (int lh=0; lh<2; ++lh) {
#if AMREX_SPACEDIM == 2
// x
if (fcent4[0](i+lh,j,k,0) <= 0.0) {
Real fracy = -fcent4[0](i+lh,j,k,0)*cflag.isConnected(0, -1, 0);
flux[0][lh] = fracy*flux4[0](i+lh,j-1,k,n) + (1.0-fracy)*flux4[0](i+lh,j,k,n);
} else {
Real fracy = fcent4[0](i+lh,j,k,0)*cflag.isConnected(0, 1, 0);
flux[0][lh] = fracy*flux4[0](i+lh,j+1,k,n) + (1.0-fracy)*flux4[0](i+lh,j,k,n);
}
// y
if (fcent4[1](i,j+lh,k,0) <= 0.0) {
Real fracx = -fcent4[1](i,j+lh,k,0)*cflag.isConnected(-1, 0, 0);
flux[1][lh] = fracx*flux4[1](i-1,j+lh,k,n) + (1.0-fracx)*flux4[1](i,j+lh,k,n);
} else {
Real fracx = fcent4[1](i,j+lh,k,0)*cflag.isConnected(1, 0, 0);
flux[1][lh] = fracx*flux4[1](i+1,j+lh,k,n) + (1.0-fracx)*flux4[1](i,j+lh,k,n);
}
#elif AMREX_SPACEDIM == 3
// x
if (fcent4[0](i+lh,j,k,0) <= 0.0) {
Real fracy = -fcent4[0](i+lh,j,k,0)*cflag.isConnected(0, -1, 0);
if (fcent4[0](i+lh,j,k,1) <= 0.0) {
Real fracz = -fcent4[0](i+lh,j,k,1)*cflag.isConnected(0, 0, -1);
flux[0][lh] = (1.0-fracz)*(fracy*flux4[0](i+lh,j-1,k ,n) + (1.0-fracy)*flux4[0](i+lh,j ,k ,n)) +
fracz *(fracy*flux4[0](i+lh,j-1,k-1,n) + (1.0-fracy)*flux4[0](i+lh,j ,k-1,n));
} else {
Real fracz = fcent4[0](i+lh,j,k,1)*cflag.isConnected(0, 0, 1);
flux[0][lh] = (1.0-fracz)*(fracy*flux4[0](i+lh,j-1,k ,n) + (1.0-fracy)*flux4[0](i+lh,j ,k ,n)) +
fracz *(fracy*flux4[0](i+lh,j-1,k+1,n) + (1.0-fracy)*flux4[0](i+lh,j ,k+1,n));
}
} else {
Real fracy = fcent4[0](i+lh,j,k,0)*cflag.isConnected(0, 1, 0);
if (fcent4[0](i+lh,j,k,1) <= 0.0) {
Real fracz = -fcent4[0](i+lh,j,k,1)*cflag.isConnected(0, 0, -1);
flux[0][lh] = (1.0-fracz)*(fracy*flux4[0](i+lh,j+1,k ,n) + (1.0-fracy)*flux4[0](i+lh,j ,k ,n)) +
fracz *(fracy*flux4[0](i+lh,j+1,k-1,n) + (1.0-fracy)*flux4[0](i+lh,j ,k-1,n));
} else {
Real fracz = fcent4[0](i+lh,j,k,1)*cflag.isConnected(0, 0, 1);
flux[0][lh] = (1.0-fracz)*(fracy*flux4[0](i+lh,j+1,k ,n) + (1.0-fracy)*flux4[0](i+lh,j ,k ,n)) +
fracz *(fracy*flux4[0](i+lh,j+1,k+1,n) + (1.0-fracy)*flux4[0](i+lh,j ,k+1,n));
}
}
// y
if (fcent4[1](i,j+lh,k,0) <= 0.0) {
Real fracx = -fcent4[1](i,j+lh,k,0)*cflag.isConnected(-1, 0, 0);
if (fcent4[1](i,j+lh,k,1) <= 0.0) {
Real fracz = -fcent4[1](i,j+lh,k,1)*cflag.isConnected(0, 0, -1);
flux[1][lh] = (1.0-fracz)*(fracx*flux4[1](i-1,j+lh,k ,n) + (1.0-fracx)*flux4[1](i,j+lh,k ,n)) +
fracz *(fracx*flux4[1](i-1,j+lh,k-1,n) + (1.0-fracx)*flux4[1](i,j+lh,k-1,n));
} else {
Real fracz = fcent4[1](i,j+lh,k,1)*cflag.isConnected(0, 0, 1);
flux[1][lh] = (1.0-fracz)*(fracx*flux4[1](i-1,j+lh,k ,n) + (1.0-fracx)*flux4[1](i,j+lh,k ,n)) +
fracz *(fracx*flux4[1](i-1,j+lh,k+1,n) + (1.0-fracx)*flux4[1](i,j+lh,k+1,n));
}
} else {
Real fracx = fcent4[1](i,j+lh,k,0)*cflag.isConnected(1, 0, 0);
if (fcent4[1](i,j+lh,k,1) <= 0.0) {
Real fracz = -fcent4[1](i,j+lh,k,1)*cflag.isConnected(0, 0, -1);
flux[1][lh] = (1.0-fracz)*(fracx*flux4[1](i+1,j+lh,k ,n) + (1.0-fracx)*flux4[1](i,j+lh,k ,n)) +
fracz *(fracx*flux4[1](i+1,j+lh,k-1,n) + (1.0-fracx)*flux4[1](i,j+lh,k-1,n));
} else {
Real fracz = fcent4[1](i,j+lh,k,1)*cflag.isConnected(0, 0, 1);
flux[1][lh] = (1.0-fracz)*(fracx*flux4[1](i+1,j+lh,k ,n) + (1.0-fracx)*flux4[1](i,j+lh,k ,n)) +
fracz *(fracx*flux4[1](i+1,j+lh,k+1,n) + (1.0-fracx)*flux4[1](i,j+lh,k+1,n));
}
}
// z
if (fcent4[2](i,j,k+lh,0) <= 0.0) {
Real fracx = -fcent4[2](i,j,k+lh,0)*cflag.isConnected(-1, 0, 0);
if (fcent4[2](i,j,k+lh,1) <= 0.0) {
Real fracy = -fcent4[2](i,j,k+lh,1)*cflag.isConnected(0, -1, 0);
flux[2][lh] = (1.0-fracy)*(fracx*flux4[2](i-1,j ,k+lh,n) + (1.0-fracx)*flux4[2](i,j, k+lh,n)) +
fracy *(fracx*flux4[2](i-1,j-1,k+lh,n) + (1.0-fracx)*flux4[2](i,j-1,k+lh,n));
} else {
Real fracy = fcent4[2](i,j,k+lh,1)*cflag.isConnected(0, 1, 0);
flux[2][lh] = (1.0-fracy)*(fracx*flux4[2](i-1,j ,k+lh,n) + (1.0-fracx)*flux4[2](i,j ,k ,n)) +
fracy *(fracx*flux4[2](i-1,j+1,k+lh,n) + (1.0-fracx)*flux4[2](i,j+1,k+lh,n));
}
} else {
Real fracx = fcent4[2](i,j,k+lh,0)*cflag.isConnected(1, 0, 0);
if (fcent4[2](i,j,k+lh,1) <= 0.0) {
Real fracy = -fcent4[2](i,j,k+lh,1)*cflag.isConnected(0, -1, 0);
flux[2][lh] = (1.0-fracy)*(fracx*flux4[2](i+1,j ,k+lh,n) + (1.0-fracx)*flux4[2](i,j, k+lh,n)) +
fracy *(fracx*flux4[2](i+1,j-1,k+lh,n) + (1.0-fracx)*flux4[2](i,j-1,k+lh,n));
} else {
Real fracy = fcent4[2](i,j,k+lh,1)*cflag.isConnected(0, 1, 0);
flux[2][lh] = (1.0-fracy)*(fracx*flux4[2](i+1,j ,k+lh,n) + (1.0-fracx)*flux4[2](i,j ,k ,n)) +
fracy *(fracx*flux4[2](i+1,j+1,k+lh,n) + (1.0-fracx)*flux4[2](i,j+1,k+lh,n));
}
}
#endif
}
divc4(i,j,k,n) = 0.0;
for (int d=0; d < AMREX_SPACEDIM; ++d) {
index[d] = 1;
const Real& alpha_lo = afrac4[d](i, j, k);
const Real& flux_lo = flux[d][0];
const Real& alpha_hi = afrac4[d](i+index[0], j+index[1], k+index[2]);
const Real& flux_hi = flux[d][1];
const Real& wflux = wflux4[d](i,j,k,n);
divc4(i,j,k,n) -= (alpha_hi*flux_hi - alpha_lo*flux_lo)*dxinv[d]; // standard flux
divc4(i,j,k,n) -= (alpha_lo - alpha_hi)*wflux*dxinv[d]; // wall flux
index[d] = 0;
}
divc4(i,j,k,n) /= vfrac4(i,j,k);
}
}
// get the redistribution weights
switch (redistribution_strategy) {
case RedistributionEB::Uniform :
rediswgt4(i,j,k) = 1.0;
break;
case RedistributionEB::VolumeFraction :
rediswgt4(i,j,k) = vfrac4(i,j,k);
break;
case RedistributionEB::Density :
rediswgt4(i,j,k) = cons4(i,j,k,istate.get_cons_density_idx());
break;
case RedistributionEB::Energy :
State::get_state_vector(cons,i,j,k,U);
rediswgt4(i,j,k) = istate.get_energy_from_cons(U);
break;
}
}
}
}
FArrayBox optmp(grow(box,2));
Array4<Real> const& optmp4 = optmp.array();
FArrayBox delm(grow(box,1));
Array4<Real> const& delm4 = delm.array();
for (int n=0; n<nc; ++n) {
//
// compute mass loss from non-conservative flux
//
optmp.setVal(0.0);
delm.setVal(0.0);
Real vtot, divnc;
for (int k = lo.z-AMREX_D_PICK(0,0,1); k <= hi.z+AMREX_D_PICK(0,0,1); ++k) {
for (int j = lo.y-AMREX_D_PICK(0,1,1); j <= hi.y+AMREX_D_PICK(0,1,1); ++j) {
AMREX_PRAGMA_SIMD
for (int i = lo.x-1; i <= hi.x+1; ++i) {
const EBCellFlag &cflag = flag4(i,j,k);
Real vf = vfrac4(i,j,k);
if ((vf > 0.0) && (vf < 1.0)) {
vtot = 0.0;
divnc = 0.0;
// compute divergence over cell as if there is no cut
divnc = 0.0;
for (int d=0; d<AMREX_SPACEDIM; ++d) {
index[d] = 1;
divnc += dxinv[d]*(flux4[d](i,j,k,n) - flux4[d](i+index[0], j+index[1], k+index[2], n));
index[d] = 0;
}
optmp4(i,j,k) = (1-vfrac4(i,j,k))*(divnc-divc4(i,j,k,n));
delm4(i,j,k) = -vfrac4(i,j,k)*optmp4(i,j,k);
}
}
}
}
//
// redistribute
//
Real wtot;
for (int k = lo.z-AMREX_D_PICK(0,0,1); k <= hi.z+AMREX_D_PICK(0,0,1); ++k) {
for (int j = lo.y-AMREX_D_PICK(0,1,1); j <= hi.y+AMREX_D_PICK(0,1,1); ++j) {
AMREX_PRAGMA_SIMD
for (int i = lo.x-1; i <= hi.x+1; ++i) {
const EBCellFlag &cflag = flag4(i,j,k);
Real vf = vfrac4(i,j,k);
if ((vf > 0.0) && (vf < 1.0)) {
wtot = 0.0;
for (const auto& g : grab) {
if (cflag.isConnected(g[0], g[1], g[2])) {
wtot += vfrac4(i+g[0],j+g[1],k+g[2])*rediswgt4(i+g[0],j+g[1],k+g[2]);
}
}
wtot = 1.0/(wtot + 1.e-80);
bool as_crse_crse_cell = false;
bool as_crse_covered_cell = false;
if (as_crse) {
as_crse_crse_cell = is_inside(i,j,k,lo,hi) && rr_flag_crse4(i,j,k) == CellType::crse_fine_boundary_cell;
as_crse_covered_cell = rr_flag_crse4(i,j,k) == CellType::fine_cell;
}
bool as_fine_valid_cell = false; // valid cells near box boundary
bool as_fine_ghost_cell = false; // ghost cells just outside valid region
if (as_fine) {
as_fine_valid_cell = is_inside(i,j,k,lo,hi);
as_fine_ghost_cell = levmsk4(i,j,k) == LevelMask::NotCovered; // not covered by other grids
}
for (const auto& g : grab) {
if (cflag.isConnected(g[0], g[1], g[2])) {
const int iii = i + g[0];
const int jjj = j + g[1];
const int kkk = k + g[2];
Real drho = delm4(i,j,k)*wtot*rediswgt4(iii,jjj,kkk);
optmp4(iii,jjj,kkk) += drho;
bool valid_dst_cell = is_inside(iii,jjj,kkk,lo,hi);
if (as_crse_crse_cell) {
if (rr_flag_crse4(iii,jjj,kkk) == CellType::fine_cell && vfrac4(i,j,k) > reredistribution_threshold) {
rr_drho_crse4(i,j,k,n) += drho*(vfrac4(iii,jjj,kkk)/vfrac4(i,j,k));
}
}
if (as_crse_covered_cell) {
if (valid_dst_cell) {
if (rr_flag_crse4(iii,jjj,kkk) == CellType::crse_fine_boundary_cell && vfrac4(iii,jjj,kkk) > reredistribution_threshold) {
// the recipient is a crse/fine boundary cell
rr_drho_crse4(iii,jjj,kkk,n) -= drho;
}
}
}
if (as_fine_valid_cell) {
if (!valid_dst_cell) {
dm_as_fine4(iii,jjj,kkk,n) += drho*vfrac4(iii,jjj,kkk);
}
}
if (as_fine_ghost_cell) {
if (valid_dst_cell) {
dm_as_fine4(i,j,k,n) -= drho*vfrac4(iii,jjj,kkk);
}
}
}
}
}
}
}
}
//
// push to output array
//
for (int k = lo.z; k <= hi.z; ++k) {
for (int j = lo.y; j <= hi.y; ++j) {
AMREX_PRAGMA_SIMD
for (int i = lo.x; i <= hi.x; ++i) {
du4(i,j,k,n) = divc4(i,j,k,n) + optmp4(i,j,k);
}
}
}
}
return;
}
std::string RedistributeEB::str() const
{
std::stringstream msg;
msg << get_tag() << "(";
msg << "strategy=" << options[+redistribution_strategy];
msg << ", reredistribution_threshold=" << reredistribution_threshold << ")";
return msg.str();
}
//=============================================================================
std::string MergeEB::tag = "merge";
bool MergeEB::registered = GetDivergenceEBBuilder().Register(MergeEB::tag, DivergenceEBBuilder<MergeEB>);
MergeEB::MergeEB()
{
}
MergeEB::MergeEB(const sol::table &def)
{
global_idx = def["global_idx"];
const sol::table &div_def = def["eb_divergence"];
// get the merge threshold
merge_threshold = div_def.get_or("merge_threshold", 0.5);
}
MergeEB::~MergeEB()
{
}
void MergeEB::calc_eb_divergence(const Box& box,
const FArrayBox &cons,
Array<FArrayBox, AMREX_SPACEDIM> &fluxes,
Array<FArrayBox, AMREX_SPACEDIM> &wall_fluxes,
FArrayBox& du,
const EBCellFlagFab& flag,
const FArrayBox& vfrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &afrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &fcent,
int as_crse,
int as_fine,
const IArrayBox *rrflag_as_crse,
const IArrayBox &levmsk, FArrayBox *rr_drho_crse,
FArrayBox &dm_as_fine,
const Real *dx,
const Real dt) const
{
BL_PROFILE("MergeEB::calc_eb_divergence");
// make sure du is empty
du.setVal(0.0);
int N = du.nComp();
const Dim3 lo = amrex::lbound(du.box());
const Dim3 hi = amrex::ubound(du.box());
Array<int,3> index = {0,0,0};
Array4<Real> const& du4 = du.array();
Real dxinv;
Array4<const EBCellFlag> const& flag4 = flag.array();
Array4<const Real> const& vfrac4 = vfrac.array();
Array<Array4<const Real>,AMREX_SPACEDIM> wflux4;
Array<Array4<const Real>,AMREX_SPACEDIM> flux4;
Array<Array4<const Real>,AMREX_SPACEDIM> afrac4;
for (int d=0; d<AMREX_SPACEDIM; ++d) {
flux4[d] = fluxes[d].array();
wflux4[d] = wall_fluxes[d].array();
afrac4[d] = afrac[d]->array();
}
Real wflux, vf;
for (int n=0; n<N; ++n) {
for (int k = lo.z; k <= hi.z; ++k) {
for (int j = lo.y; j <= hi.y; ++j) {
AMREX_PRAGMA_SIMD
for (int i = lo.x; i <= hi.x; ++i) {
const EBCellFlag &cflag = flag4(i,j,k);
vf = vfrac4(i,j,k);
if (vf <= 0.0) continue;
wflux = 0.0;
// cycle over dimensions
for (int d=0; d<AMREX_SPACEDIM; ++d) {
index[d] = 1;
dxinv = dt/dx[d];
if (cflag.isSingleValued()) {
wflux = wflux4[d](i,j,k,n);
}
Real flux_lo = flux4[d](i,j,k,n);
const Real alpha_lo = afrac4[d](i,j,k);
Real flux_hi = flux4[d](i+index[0], j+index[1], k+index[2], n);
const Real alpha_hi = afrac4[d](i+index[0], j+index[1], k+index[2]);
flux_lo *= alpha_lo;
flux_hi *= alpha_hi;
wflux *= (alpha_hi - alpha_lo);
du4(i,j,k,n) += dxinv*(flux_lo - flux_hi + wflux)/vf;
index[d] = 0;
}
}
}
}
}
return;
}
void MergeEB::merge_cells(const Box& box,
FArrayBox &cons,
FArrayBox& du,
const EBCellFlagFab& flag,
const FArrayBox& vfrac,
const Array<const FArrayBox *, AMREX_SPACEDIM> &afrac,
int as_fine,
FArrayBox &dm_as_fine,
const IArrayBox& levmsk) const
{
BL_PROFILE("MergeEB::merge_cells");
int nc = du.nComp();
Array<int,3> index = {0,0,0};
Array4<Real> const& cons4 = cons.array();
Array4<Real> const& du4 = du.array();
Array4<const EBCellFlag> const& flag4 = flag.array();
Array4<const Real> const& vfrac4 = vfrac.array();
Array4<Real> const& dm_as_fine4 = dm_as_fine.array();
Array4<const int> const& levmsk4 = levmsk.array();
Array<Array4<const Real>,AMREX_SPACEDIM> afrac4;
for (int d=0; d<AMREX_SPACEDIM; ++d) {
afrac4[d] = afrac[d]->array();
}
Real vf;
// the sets of cells that are to be merged
Vector<Vector<Array<int,3>>> merge;
// a container for all of the unique cells that are part of the problem and
// the super-cell that they are a part of
std::map<Array<int,3>,int> cells;
int ii, jj, kk;
int mi, mj, mk;
Real side_alpha, side_alpha_max;
Box halo = grow(box,2);
const Dim3 halo_lo = amrex::lbound(halo);
const Dim3 halo_hi = amrex::ubound(halo);
// expand zone over which we work so that each block sees the same modifications
// to du without having to do inter-block communication
Box calc = grow(box,1);
const Dim3 lo = amrex::lbound(calc);
const Dim3 hi = amrex::ubound(calc);
for (int k = lo.z; k <= hi.z; ++k) {
for (int j = lo.y; j <= hi.y; ++j) {
AMREX_PRAGMA_SIMD
for (int i = lo.x; i <= hi.x; ++i) {
const EBCellFlag &cflag = flag4(i,j,k);
vf = vfrac4(i,j,k);
if (vf <= 0.0) continue;
if (vf < merge_threshold) {
ii = i;
jj = j;
kk = k;
Array<int,3> cell_idx = {ii, jj, kk};
// check that this cell isn't already part of another super-cell
if (cells.find(cell_idx) != cells.end())
continue;
Vector<Array<int,3>> super_cell = {cell_idx};
bool new_super_cell = true;
while (vf < merge_threshold) {
// get the fluid fraction of each of the sides
// scaled by if it is a viable candidate
side_alpha_max = 0.0;
for (int d=0; d<AMREX_SPACEDIM; ++d) {
index[d] = 1;
// lo side
if (is_inside(ii-index[0], jj-index[1], kk-index[2], halo_lo, halo_hi)) {
side_alpha = afrac4[d](ii,jj,kk);
if (side_alpha > side_alpha_max) {
side_alpha_max = side_alpha;
mi = ii-index[0];
mj = jj-index[1];
mk = kk-index[2];
}
}
// hi side
if (is_inside(ii+index[0], jj+index[1], kk+index[2], halo_lo, halo_hi)) {
side_alpha = afrac4[d](ii+index[0], jj+index[1], kk+index[2]);
if (side_alpha > side_alpha_max) {
side_alpha_max = side_alpha;
mi = ii+index[0];
mj = jj+index[1];
mk = kk+index[2];
}
}
index[d] = 0;
}
ii = mi;
jj = mj;
kk = mk;
Array<int,3> cell_idx = {ii, jj, kk};
// check if this cell is part of another super cell
if (cells.find(cell_idx) == cells.end()) {
vf += vfrac4(ii,jj,kk);
super_cell.push_back(cell_idx);
} else {
int si = cells[cell_idx];
// register the cells with a super cell
for (const auto &cell : super_cell) {
merge[si].push_back(cell);
cells[cell] = si;
}
new_super_cell = false;
break;
}
}
// add the merged cell to the list
if (new_super_cell) {
for (const auto &cell : super_cell) {
cells[cell] = merge.size();
}
merge.push_back(super_cell);
}
} else if (cflag.isSingleValued() && as_fine) {
for (int n=0; n<nc; ++n) {
dm_as_fine4(i,j,k,n) = 0.0;
}
}
}
}
}
int nsuper = merge.size();
// do update
for (int n=0; n<nc; ++n) {
for (int mi=0; mi<nsuper; ++mi) {
const auto& mc = merge[mi];
// compute the sums
Real vf_sum = 0.0;
Real sum_cons = 0.0;
Real sum_du = 0.0;
for (const auto& cell_idx : mc) {
vf = vfrac4(cell_idx[0],cell_idx[1], cell_idx[2]);
vf_sum += vf;
sum_cons += cons4(cell_idx[0],cell_idx[1], cell_idx[2],n)*vf;
sum_du += du4(cell_idx[0],cell_idx[1], cell_idx[2],n)*vf;
}
sum_cons /= vf_sum;
sum_du /= vf_sum;
for (const auto& cell_idx : mc) {
const int i = cell_idx[0];
const int j = cell_idx[1];
const int k = cell_idx[2];
const Real u_orig = cons4(i,j,k,n);
const Real u_final = sum_cons + sum_du;
const Real du_merge = u_final - u_orig;
du4(i,j,k,n) = du_merge;
// tell other grids how du has changed
if (as_fine && (levmsk4(i,j,k) == LevelMask::NotCovered)) {
dm_as_fine4(i,j,k,n) = du_merge - du4(cell_idx[0],cell_idx[1], cell_idx[2],n);
}
}
}
}
}
std::string MergeEB::str() const
{
std::stringstream msg;
msg << get_tag() << "(";
msg << "merge_threshold=" << merge_threshold << ")";
return msg.str();
}
#endif
| 39.750286 | 162 | 0.404818 | [
"vector",
"3d"
] |
0cea3419b3ef7cbb37701a371998f14f4d21705b | 822 | cpp | C++ | mine/438-find_all_anagrams_in_a_string.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | mine/438-find_all_anagrams_in_a_string.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | mine/438-find_all_anagrams_in_a_string.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | class Solution {
public:
bool check(unordered_map<char, int>& hash){
bool flag = true;
for(const auto& p: hash){
if(p.second > 0){
flag = false;
break;
}
}
return flag;
}
vector<int> findAnagrams(string s, string p) {
int ns = s.size(), np = p.size();
unordered_map<char, int> hash;
vector<int> indices;
for(const char& c: p) ++hash[c];
for(int i = 0; i < ns; ++i) {
if(hash.count(s[i]))
--hash[s[i]];
if(i >= np && hash.count(s[i - np]))
++hash[s[i - np]];
if(i >= np - 1 && check(hash))
indices.emplace_back(i - np + 1);
}
return indices;
}
}; | 27.4 | 51 | 0.406326 | [
"vector"
] |
0cf38c9a8c4a6f7bfa8326162e2774e5b1c76401 | 1,782 | cpp | C++ | c-plus-plus-yellow-belt/week_4/iterator_usage/demographic_data/demographic_data/functions.cpp | codearchive/coursera-c-plus-plus-specialization | c599126e510182e5e6a8c5f29a31f1eecda8b8a5 | [
"Apache-2.0"
] | null | null | null | c-plus-plus-yellow-belt/week_4/iterator_usage/demographic_data/demographic_data/functions.cpp | codearchive/coursera-c-plus-plus-specialization | c599126e510182e5e6a8c5f29a31f1eecda8b8a5 | [
"Apache-2.0"
] | null | null | null | c-plus-plus-yellow-belt/week_4/iterator_usage/demographic_data/demographic_data/functions.cpp | codearchive/coursera-c-plus-plus-specialization | c599126e510182e5e6a8c5f29a31f1eecda8b8a5 | [
"Apache-2.0"
] | null | null | null | #include "functions.h"
template <typename InputIt>
int ComputeMedianAge(InputIt range_begin, InputIt range_end) {
if (range_begin == range_end) {
return 0;
}
std::vector<typename InputIt::value_type> range_copy(range_begin, range_end);
auto middle = begin(range_copy) + range_copy.size() / 2;
nth_element(
begin(range_copy), middle, end(range_copy),
[](const Person& lhs, const Person& rhs) {
return lhs.age < rhs.age;
}
);
return middle->age;
}
void PrintStats(std::vector<Person> persons) {
std::cout << "Median age = " << ComputeMedianAge(begin(persons), end(persons)) << std::endl;;
auto it_gender = partition(begin(persons), end(persons), [](Person p) {
return p.gender == Gender::FEMALE;
});
std::cout << "Median age for females = " << ComputeMedianAge(begin(persons), it_gender) << std::endl;
std::cout << "Median age for males = " << ComputeMedianAge(it_gender, end(persons)) << std::endl;
auto it_female_employment = partition(begin(persons), it_gender, [](Person p) {
return p.gender == Gender::FEMALE && p.is_employed;
});
std::cout << "Median age for employed females = " << ComputeMedianAge(begin(persons), it_female_employment) << std::endl;
std::cout << "Median age for unemployed females = " << ComputeMedianAge(it_female_employment, it_gender) << std::endl;
auto it_male_employment = partition(it_gender, end(persons), [](Person p) {
return p.gender == Gender::MALE && p.is_employed;
});
std::cout << "Median age for employed males = " << ComputeMedianAge(it_gender, it_male_employment) << std::endl;
std::cout << "Median age for unemployed males = " << ComputeMedianAge(it_male_employment, end(persons)) << std::endl;
} | 45.692308 | 125 | 0.659371 | [
"vector"
] |
0cfe0d93475a898691cd2ff33fe3d81b39051344 | 494 | cpp | C++ | c++/leetcode/1685-Sum_of_Absolute_Differences_in_a_Sorted_Array-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/1685-Sum_of_Absolute_Differences_in_a_Sorted_Array-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/1685-Sum_of_Absolute_Differences_in_a_Sorted_Array-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
const int n = nums.size();
vector<int> sums(nums);
for (int i = 1; i < n; ++i) {
sums[i] += sums[i - 1];
}
vector<int> res(n);
for (int i = 0; i < n; ++i) {
const int lsum = sums[i];
const int rsum = sums[n - 1] - sums[i];
res[i] = (2*i + 2 - n) * nums[i] - lsum + rsum;
}
return res;
}
};
| 27.444444 | 62 | 0.437247 | [
"vector"
] |
0cff8c77294b9a8e2b0ceac8ec1bb4a0060f4924 | 1,076 | cpp | C++ | ProjectEuler/euler008.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | ProjectEuler/euler008.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | ProjectEuler/euler008.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int t, k, n, i, j;
unsigned long long int current, maxProduct;
string s;
vector<unsigned long long int> factors (0);
cin >> t;
while(t--) {
cin >> n >> k;
cin >> s;
current = 1ULL;
for(i=0; i<k; i++) {
factors.push_back((unsigned long long int)(s[i]-'0'));
current *= (unsigned long long int)(s[i]-'0');
}
maxProduct = current;
for(i=k; i<n; i++) {
factors.erase(factors.begin());
factors.push_back((unsigned long long int)(s[i]-'0'));
current = 1ULL;
for(j=0; j<k; j++)
current *= factors[j];
maxProduct = max(maxProduct, current);
}
cout << maxProduct << endl;
factors.clear();
}
return 0;
}
// https://www.hackerrank.com/contests/projecteuler/challenges/euler008/problem | 25.023256 | 79 | 0.498141 | [
"vector"
] |
490ed6ab25a175ffaac99231b5a3d071fb2a3d8c | 1,468 | cpp | C++ | programming/dataStructure_Algorithm/exercises/SpecificProblems/sorting/mergeSort/mergeSortKSortedArray_List/Array/O_NlogK/mergeKSortedArray_NlogK.cpp | ljyang100/dataScience | ad2b243673c570c18d83ab1a0cd1bb4694c17eac | [
"MIT"
] | 2 | 2020-12-10T02:05:29.000Z | 2021-05-30T15:23:56.000Z | programming/dataStructure_Algorithm/exercises/SpecificProblems/sorting/mergeSort/mergeSortKSortedArray_List/Array/O_NlogK/mergeKSortedArray_NlogK.cpp | ljyang100/dataScience | ad2b243673c570c18d83ab1a0cd1bb4694c17eac | [
"MIT"
] | null | null | null | programming/dataStructure_Algorithm/exercises/SpecificProblems/sorting/mergeSort/mergeSortKSortedArray_List/Array/O_NlogK/mergeKSortedArray_NlogK.cpp | ljyang100/dataScience | ad2b243673c570c18d83ab1a0cd1bb4694c17eac | [
"MIT"
] | 1 | 2020-04-21T11:18:18.000Z | 2020-04-21T11:18:18.000Z | #include<iostream>
#include<queue> //For priority_queue
#include<vector>
class Compare {
public:
bool operator()(std::vector<int>::iterator a, std::vector<int>::iterator b)
{
return (*a) > (*b); //default is normally < sign. So the > sign definition is necessary.
}
};
std::vector<int> mergeKSortedArrays(std::vector<std::vector<int>> &vec) //don't forget pass by reference.
{
std::priority_queue<std::vector<int>::iterator, std::vector<std::vector<int>::iterator>, Compare> pq;
for (int i = 0; i < vec.size(); i++)
pq.push(vec[i].begin());
std::vector<int> resultVector;
while (!pq.empty()) {
std::vector<int>::iterator top = pq.top();
pq.pop();
auto next = std::next(top); //Here std::next does not advance top iterator.
if ((*next) != INT_MIN) //
pq.push(next);
if ((*top) != INT_MIN) resultVector.push_back((*top));
}
return resultVector;
}
// Driver program to test above
int main()
{
//Even with STL containers, we can always use pointer-like iterator.
std::vector<std::vector<int>> vec;
std::vector<int> vec1 = { 1, 3, 5, INT_MIN }, vec2 = { 2, 6, 8, INT_MIN }, vec3 = { 0, 9, 10, INT_MIN }, vec4 = { 4, 7, INT_MIN };
//**** because I cannot if (top.next != NULL), or even cannot use vec.end(). I put some indicators in the end of array.
vec.push_back(vec1); vec.push_back(vec2); vec.push_back(vec3); vec.push_back(vec4);
//merge the k sorted vectors.
std::vector<int> result = mergeKSortedArrays(vec);
return 0;
}
| 31.234043 | 131 | 0.656676 | [
"vector"
] |
49105c3801167a0de1371d0a1b1d1f8a80b9481d | 7,103 | cpp | C++ | Programs/ResourceEditor/Classes/Qt/Tools/AddSwitchEntityDialog/AddSwitchEntityDialog.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Programs/ResourceEditor/Classes/Qt/Tools/AddSwitchEntityDialog/AddSwitchEntityDialog.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Programs/ResourceEditor/Classes/Qt/Tools/AddSwitchEntityDialog/AddSwitchEntityDialog.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "Classes/Qt/Tools/AddSwitchEntityDialog/AddSwitchEntityDialog.h"
#include "Classes/Qt/Tools/AddSwitchEntityDialog/SwitchEntityCreator.h"
#include "Classes/Qt/Tools/SelectPathWidget/SelectEntityPathWidget.h"
#include <REPlatform/Commands/EntityAddCommand.h>
#include <REPlatform/Commands/EntityRemoveCommand.h>
#include <REPlatform/DataNodes/ProjectManagerData.h>
#include <REPlatform/DataNodes/SceneData.h>
#include "ui_BaseAddEntityDialog.h"
#include <QtTools/ConsoleWidget/PointerSerializer.h>
#include <TArc/Core/Deprecated.h>
#include <TArc/DataProcessing/DataContext.h>
#include <Scene3D/Components/MotionComponent.h>
#include <Scene3D/Components/SkeletonComponent.h>
#include <QPushButton>
namespace AddSwitchEntityDialogDetails
{
DAVA::SceneEditor2* GetActiveScene()
{
DAVA::SceneData* data = DAVA::Deprecated::GetActiveDataNode<DAVA::SceneData>();
if (data != nullptr)
{
return data->GetScene().Get();
}
return nullptr;
}
}
AddSwitchEntityDialog::AddSwitchEntityDialog(QWidget* parent)
: BaseAddEntityDialog(parent, QDialogButtonBox::Ok | QDialogButtonBox::Cancel)
{
setAcceptDrops(true);
setAttribute(Qt::WA_DeleteOnClose, true);
DAVA::ProjectManagerData* data = DAVA::Deprecated::GetDataNode<DAVA::ProjectManagerData>();
DVASSERT(data != nullptr);
DAVA::FilePath defaultPath(data->GetDataSource3DPath());
DAVA::SceneEditor2* scene = AddSwitchEntityDialogDetails::GetActiveScene();
if (scene != nullptr)
{
const DAVA::FilePath& scenePath = scene->GetScenePath();
if (scenePath.Exists())
{
defaultPath = scenePath.GetDirectory();
}
}
SelectEntityPathWidget* firstWidget = new SelectEntityPathWidget(parent, scene, defaultPath.GetAbsolutePathname(), "");
SelectEntityPathWidget* secondWidget = new SelectEntityPathWidget(parent, scene, defaultPath.GetAbsolutePathname(), "");
SelectEntityPathWidget* thirdWidget = new SelectEntityPathWidget(parent, scene, defaultPath.GetAbsolutePathname(), "");
connect(firstWidget, &SelectEntityPathWidget::PathSelected, this, &AddSwitchEntityDialog::OnPathChanged);
connect(secondWidget, &SelectEntityPathWidget::PathSelected, this, &AddSwitchEntityDialog::OnPathChanged);
connect(thirdWidget, &SelectEntityPathWidget::PathSelected, this, &AddSwitchEntityDialog::OnPathChanged);
AddControlToUserContainer(firstWidget, "First Entity:");
AddControlToUserContainer(secondWidget, "Second Entity:");
AddControlToUserContainer(thirdWidget, "Third Entity:");
pathWidgets.push_back(firstWidget);
pathWidgets.push_back(secondWidget);
pathWidgets.push_back(thirdWidget);
propEditor->setVisible(false);
propEditor->setMinimumHeight(0);
propEditor->setMaximumSize(propEditor->maximumWidth(), 0);
OnPathChanged();
}
AddSwitchEntityDialog::~AddSwitchEntityDialog()
{
RemoveAllControlsFromUserContainer();
}
void AddSwitchEntityDialog::OnPathChanged()
{
QPushButton* okButton = ui->buttonBox->button(QDialogButtonBox::Ok);
DVASSERT(okButton != nullptr);
bool hasAtLeastOnePathSet = std::any_of(pathWidgets.begin(), pathWidgets.end(), [](SelectEntityPathWidget* w) { return w->getText().empty() == false; });
okButton->setEnabled(hasAtLeastOnePathSet);
}
void AddSwitchEntityDialog::CleanupPathWidgets()
{
for (SelectEntityPathWidget* widget : pathWidgets)
{
widget->EraseWidget();
}
}
DAVA::Vector<DAVA::RefPtr<DAVA::Entity>> AddSwitchEntityDialog::GetPathEntities()
{
DAVA::Vector<DAVA::RefPtr<DAVA::Entity>> entities;
for (SelectEntityPathWidget* widget : pathWidgets)
{
DAVA::RefPtr<DAVA::Entity> entity = widget->GetOutputEntity();
if (entity)
{
entities.push_back(entity);
}
}
return entities;
}
void AddSwitchEntityDialog::accept()
{
using namespace DAVA;
SceneEditor2* scene = AddSwitchEntityDialogDetails::GetActiveScene();
if (scene == nullptr)
{
CleanupPathWidgets();
return;
}
Vector<RefPtr<Entity>> pathEntities = GetPathEntities();
Vector<Entity*> sourceEntities(pathEntities.size());
std::transform(pathEntities.begin(), pathEntities.end(), sourceEntities.begin(), [](const RefPtr<Entity>& r) { return r.Get(); });
CleanupPathWidgets();
SwitchEntityCreator creator;
bool simpleSwitchMode = true; // simple switch mode is when each source entity contains exact one render object
size_t simpleSkinnedMeshObjectsCount = 0;
size_t simpleSkeletonComponentsCount = 0;
size_t simpleMotionComponentsCount = 0;
for (Entity* sourceEntity : sourceEntities)
{
if (creator.HasSwitchComponentsRecursive(sourceEntity))
{
Logger::Error("Can't create switch over switch: %s", sourceEntity->GetName().c_str());
return;
}
size_t meshesCount = creator.GetRenderObjectsCountRecursive(sourceEntity, RenderObject::TYPE_MESH);
size_t skinnedMeshesCount = creator.GetRenderObjectsCountRecursive(sourceEntity, RenderObject::TYPE_SKINNED_MESH);
size_t overallMeshesCount = meshesCount + skinnedMeshesCount;
if (overallMeshesCount == 0)
{
Logger::Error("Entity '%s' hasn't mesh / skinned mesh render objects", sourceEntity->GetName().c_str());
return;
}
if (overallMeshesCount > 1)
{
simpleSwitchMode = false;
}
if (simpleSwitchMode)
{
if (skinnedMeshesCount > 0)
{
DVASSERT(skinnedMeshesCount == 1);
++simpleSkinnedMeshObjectsCount;
}
simpleSkeletonComponentsCount += sourceEntity->GetComponentCount<SkeletonComponent>();
simpleMotionComponentsCount += sourceEntity->GetComponentCount<MotionComponent>();
}
}
if (simpleSwitchMode)
{
if (simpleSkinnedMeshObjectsCount > 1)
{
Logger::Error("Can't create switch with multiple skinned mesh render objects");
return;
}
else if (simpleSkeletonComponentsCount > 1)
{
Logger::Error("Can't create switch with skinned mesh and multiple skeleton components");
return;
}
else if (simpleMotionComponentsCount > 1)
{
Logger::Error("Can't create switch with skinned mesh and multiple motion components");
return;
}
}
scene->BeginBatch("Unite entities into switch entity", static_cast<uint32>(sourceEntities.size()) + 1u);
for (Entity* sourceEntity : sourceEntities)
{
scene->Exec(std::unique_ptr<Command>(new EntityRemoveCommand(sourceEntity)));
}
RefPtr<Entity> switchEntity = creator.CreateSwitchEntity(sourceEntities);
scene->Exec(std::unique_ptr<DAVA::Command>(new DAVA::EntityAddCommand(switchEntity.Get(), scene)));
scene->EndBatch();
BaseAddEntityDialog::accept();
}
void AddSwitchEntityDialog::reject()
{
CleanupPathWidgets();
BaseAddEntityDialog::reject();
}
| 33.985646 | 157 | 0.697874 | [
"mesh",
"render",
"object",
"vector",
"transform"
] |
4913fc1252cf2dacfc72e447e1f30e5fe403c84e | 406 | hpp | C++ | production/include/executor/os_proxy.hpp | ratelware/logreader | 6ca96c49a342dcaef59221dd3497563f54b63ae7 | [
"MIT"
] | null | null | null | production/include/executor/os_proxy.hpp | ratelware/logreader | 6ca96c49a342dcaef59221dd3497563f54b63ae7 | [
"MIT"
] | 3 | 2017-11-21T22:16:51.000Z | 2017-11-21T23:34:31.000Z | production/include/executor/os_proxy.hpp | ratelware/logreader | 6ca96c49a342dcaef59221dd3497563f54b63ae7 | [
"MIT"
] | null | null | null | #ifndef OS_PROXY_H_mnfiowef3489feksdmkjwqndu238f43iokfnedsldwlqkdmnwfuiergh34f4kfmdfc
#define OS_PROXY_H_mnfiowef3489feksdmkjwqndu238f43iokfnedsldwlqkdmnwfuiergh34f4kfmdfc
#include <string>
#include <vector>
namespace executor
{
class os_proxy
{
public:
int call(const std::string& application, const std::vector<std::string>& arguments);
std::string get_current_working_directory();
};
}
#endif | 23.882353 | 86 | 0.825123 | [
"vector"
] |
4915616127aa1561ba333f3c26606dd6fce006fa | 13,289 | cpp | C++ | Samples/GLEncoding/FireCube.cpp | GPUOpen-LibrariesAndSDKs/RapidFire_SDK | b600e1e4eb29c7aabe16afcf35cb1ff2c996de5d | [
"MIT"
] | 35 | 2016-11-01T23:23:26.000Z | 2022-02-25T12:03:03.000Z | Samples/GLEncoding/FireCube.cpp | GPUOpen-LibrariesAndSDKs/RapidFire_SDK | b600e1e4eb29c7aabe16afcf35cb1ff2c996de5d | [
"MIT"
] | 10 | 2016-10-12T13:56:21.000Z | 2021-10-01T15:31:58.000Z | Samples/GLEncoding/FireCube.cpp | GPUOpen-LibrariesAndSDKs/RapidFire_SDK | b600e1e4eb29c7aabe16afcf35cb1ff2c996de5d | [
"MIT"
] | 14 | 2016-12-12T23:21:33.000Z | 2021-07-29T21:57:16.000Z | //
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
//
// 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 <GL/glew.h>
#include <Windows.h>
#include "FireCube.h"
#define MULTI_STRING(a) #a
extern char* readRGBimage(int &xsize, int &ysize, int &channels, const char* fname);
namespace
{
struct VERTEX_ELEMENT
{
float position[3];
float normal[3];
float texcoord[2];
};
struct LIGHT_DATA
{
float LightDirection[4];
float DiffuseColor[4];
float AmbientColor[4];
float SpecularColor[4];
};
}
FireCube::FireCube()
: m_uiVertexBuffer(0)
, m_uiElementBuffer(0)
, m_uiVertexArray(0)
, m_uiTexture(0)
, m_nSampler(0)
, m_uiLightBuffer(0)
{}
FireCube::~FireCube()
{
if (m_uiVertexBuffer)
{
glDeleteBuffers(1, &m_uiVertexBuffer);
}
if (m_uiElementBuffer)
{
glDeleteBuffers(1, &m_uiElementBuffer);
}
if (m_uiLightBuffer)
{
glDeleteBuffers(1, &m_uiLightBuffer);
}
if (m_uiVertexArray)
{
glDeleteVertexArrays(1, &m_uiVertexArray);
}
if (m_uiTexture)
{
glDeleteTextures(1, &m_uiTexture);
}
}
bool FireCube::initProgram()
{
const char* pVShader = MULTI_STRING( #version 420 compatibility \n
layout(location = 0) in vec4 inVertex;
layout(location = 1) in vec4 inNormal;
layout(location = 2) in vec2 inTexCoord;
out vec3 vNormal;
out vec3 vPosition;
out vec2 vTextureCoord;
void main()
{
// transform vertex position into eye space
vPosition = (gl_ModelViewMatrix * inVertex).xyz;
// Transform normal into eye space
vNormal = (gl_ModelViewMatrix * vec4(inNormal.x, inNormal.y, inNormal.z, 0.0f)).xyz;
vTextureCoord = inTexCoord;
gl_Position = gl_ModelViewProjectionMatrix * inVertex;
}
);
const char* pFShader = MULTI_STRING( #version 420 compatibility \n
layout(shared, binding = 1) uniform LightColor
{
vec4 LightDir;
vec4 DiffuseColor;
vec4 AmbientColor;
vec4 SpecularColor;
};
layout(binding = 1) uniform sampler2D BaseMap;
in vec2 vTextureCoord;
in vec3 vNormal;
in vec3 vPosition;
void main()
{
vec4 vTexColor = texture2D(BaseMap, vTextureCoord);
vec4 vBaseColor = mix(vec4(0.4f, 0.4f, 0.4f, 1.0f), vTexColor, vTexColor.a);
vec3 vN = normalize(vNormal);
float NdotL = max(dot(vN, -LightDir.xyz), 0.0);
vec3 vR = reflect(LightDir.xyz, vN);
float Spec = pow(max(dot(normalize(vR), normalize(-vPosition)), 0.0), 6.0);
gl_FragColor = vBaseColor * DiffuseColor * NdotL + vBaseColor * AmbientColor + Spec * SpecularColor;
}
);
if (!m_GLShader.createVertexShaderFromString(pVShader))
{
return false;
}
if (!m_GLShader.createFragmentShaderFromString(pFShader))
{
return false;
}
if (!m_GLShader.buildProgram())
{
return false;
}
return true;
}
bool FireCube::initTexture(const char* pFileName)
{
int nTexWidth = 0;
int nTexHeight = 0;
int nTexChannels = 0;
char* pPixels = readRGBimage(nTexWidth, nTexHeight, nTexChannels, pFileName);
if (!pPixels)
{
return false;
}
glGenTextures(1, &m_uiTexture);
glBindTexture(GL_TEXTURE_2D, m_uiTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, nTexWidth, nTexHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pPixels);
glBindTexture(GL_TEXTURE_2D, 0);
delete[] pPixels;
return true;
}
bool FireCube::initBuffer()
{
const VERTEX_ELEMENT vertexBuffer[] = { -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Front Tris 0,1,2 0,2,3
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Right Tris 4,5,6 4,6,7
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f, // Back Tris 8,9,10 8,10,11
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,-1.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f,-1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f,-1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Left Tris 12,13,14 12,14,15
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, // Top Tris 16,17,18 16,18,19
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f,-1.0f, 0.0f, 0.0f, 0.0f, // Bottom Tris 20,21,22 20,22,23
0.5f, -0.5f, -0.5f, 0.0f,-1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f,-1.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f,-1.0f, 0.0f, 0.0f, 1.0f };
const GLushort indexBuffer[] = { 0, 1, 2, 0, 2, 3, // Front
4, 5, 6, 4, 6, 7, // Right
8, 9, 10, 8, 10, 11, // Back
12, 13, 14, 12, 14, 15, // Left
16, 17, 18, 16, 18, 19, // Top
20, 21, 22, 20, 22, 23 }; // Bottom
// Create vertex buffer
glGenBuffers(1, &m_uiVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_uiVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(VERTEX_ELEMENT), vertexBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Create element buffer
glGenBuffers(1, &m_uiElementBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_uiElementBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 36 * sizeof(GLushort), indexBuffer, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// Create UBO for light data
glGenBuffers(1, &m_uiLightBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, m_uiLightBuffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(LIGHT_DATA), nullptr, GL_DYNAMIC_DRAW);
LIGHT_DATA* ptr = static_cast<LIGHT_DATA*>(glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(LIGHT_DATA), GL_MAP_WRITE_BIT));
if (!ptr)
{
return false;
}
ptr->LightDirection[0] = 0.0f;
ptr->LightDirection[1] = -0.707107f;
ptr->LightDirection[2] = -0.707107f;
ptr->LightDirection[3] = 0.0f;
ptr->AmbientColor[0] = 0.2f;
ptr->AmbientColor[1] = 0.2f;
ptr->AmbientColor[2] = 0.2f;
ptr->AmbientColor[3] = 1.0f;
ptr->DiffuseColor[0] = 1.0f;
ptr->DiffuseColor[1] = 1.0f;
ptr->DiffuseColor[2] = 1.0f;
ptr->DiffuseColor[3] = 1.0f;
ptr->SpecularColor[0] = 1.0f;
ptr->SpecularColor[1] = 1.0f;
ptr->SpecularColor[2] = 1.0f;
ptr->SpecularColor[3] = 1.0f;
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
return true;
}
bool FireCube::initVertexArray()
{
// Create vertex arrays
glGenVertexArrays(1, &m_uiVertexArray);
glBindVertexArray(m_uiVertexArray);
glBindBuffer(GL_ARRAY_BUFFER, m_uiVertexBuffer);
// Enable vertex array to pass vertex data to the shader.
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VERTEX_ELEMENT), nullptr);
// Enable vertex array to pass normal data to the shader.
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, sizeof(VERTEX_ELEMENT), reinterpret_cast<void*>(3 * sizeof(float)));
// Enable vertex array to pass texture data to the shader.
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VERTEX_ELEMENT), reinterpret_cast<void*>(6 * sizeof(float)));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_uiElementBuffer);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return true;
}
bool FireCube::init()
{
glClearColor(0.3f, 0.3f, 0.5f, 1.0f);
glEnable(GL_DEPTH_TEST);
if (!initTexture("AMD_FirePro.rgb"))
{
return false;
}
if (!initProgram())
{
return false;
}
if (!initBuffer())
{
return false;
}
if (!initVertexArray())
{
return false;
}
return true;
}
void FireCube::draw() const
{
m_GLShader.bind();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_uiTexture);
glBindVertexArray(m_uiVertexArray);
// Bind UBO containing light data to binding point 1
glBindBufferBase(GL_UNIFORM_BUFFER, 1, m_uiLightBuffer);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, NULL);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
m_GLShader.unbind();
} | 34.971053 | 147 | 0.488449 | [
"transform"
] |
491993201a63b23de8ef2947303e83da9503e92b | 2,422 | cpp | C++ | algos/c8-MULTQ3-original.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | algos/c8-MULTQ3-original.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | algos/c8-MULTQ3-original.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | #include<bits/stdc++.h>
#define REP(i,n) for (int i = 1; i <= n; i++)
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define lli long long int
#define INF 1000000000
#define endl '\n'
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
using namespace std;
struct node{
int ar[3];
};
node st[400004];
int lazy[400004];
void build(int si , int ss, int se)
{
if(ss == se)
{
st[si].ar[0] = 1;
st[si].ar[1] = 0;
st[si].ar[2] = 0;
return;
}
int mid = (ss + se) / 2;
build(2*si , ss , mid);
build(2*si+1 , mid+1 , se);
st[si].ar[0] = st[2*si].ar[0] + st[2*si+1].ar[0];
st[si].ar[1] = st[2*si].ar[1] + st[2*si+1].ar[1];
st[si].ar[2] = st[2*si].ar[2] + st[2*si+1].ar[2];
}
void shift(int si)
{
int a = st[si].ar[2];
st[si].ar[2] = st[si].ar[1];
st[si].ar[1] = st[si].ar[0];
st[si].ar[0] = a;
}
void update(int si , int ss , int se , int qs , int qe)
{
if(lazy[si] != 0)
{
int add = lazy[si];
lazy[si] = 0;
if(ss != se)
{
lazy[2*si] += add;
lazy[2*si+1] += add;
}
add %= 3;
for(int i=0;i<add;i++)
{
shift(si);
}
}
if(ss > qe || se < qs) return;
if(ss >= qs && se <= qe)
{
shift(si);
if(ss != se)
{
lazy[2*si]++;
lazy[2*si+1]++;
}
return;
}
int mid = (ss + se) / 2;
update(2*si , ss , mid , qs , qe);
update(2*si+1 , mid+1 , se , qs , qe);
st[si].ar[0] = st[2*si].ar[0] + st[2*si+1].ar[0];
st[si].ar[1] = st[2*si].ar[1] + st[2*si+1].ar[1];
st[si].ar[2] = st[2*si].ar[2] + st[2*si+1].ar[2];
}
int query(int si , int ss , int se , int qs , int qe)
{
if(lazy[si] != 0)
{
int add = lazy[si];
lazy[si] = 0;
if(ss != se)
{
lazy[2*si] += add;
lazy[2*si+1] += add;
}
add %= 3;
for(int i=0;i<add;i++)
{
shift(si);
}
}
if(ss > qe || se < qs) {
return 0;
}
if(ss >= qs && se <= qe)
{
return st[si].ar[0];
}
int mid = (ss + se) / 2;
int l = query(2*si , ss , mid , qs , qe);
int r = query(2*si+1 , mid+1 , se , qs , qe);
return l + r;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n , q , A , B , code;
cin>>n>>q;
build(1 , 1 , n);
while(q--)
{
cin>>code>>A>>B;
if(code == 0)
{
update(1 , 1 , n , A+1 , B+1);
}
else
{
cout<<query(1 , 1 , n , A+1 , B+1)<<endl;
}
}
} | 16.703448 | 55 | 0.508671 | [
"vector"
] |
492d3e115475f8eea8fd6fc62d1ef778da93b821 | 3,609 | hxx | C++ | source/AsteroidShooter/include/Game.hxx | selmentdev/recr-game-native-cxx-shooter | c924477cb2adb1500bed2a2958aaf4f1ee96391b | [
"Apache-2.0"
] | null | null | null | source/AsteroidShooter/include/Game.hxx | selmentdev/recr-game-native-cxx-shooter | c924477cb2adb1500bed2a2958aaf4f1ee96391b | [
"Apache-2.0"
] | null | null | null | source/AsteroidShooter/include/Game.hxx | selmentdev/recr-game-native-cxx-shooter | c924477cb2adb1500bed2a2958aaf4f1ee96391b | [
"Apache-2.0"
] | null | null | null | #ifndef INCLUDED_GAME_HXX
#define INCLUDED_GAME_HXX
//
// Copyright (C) Selmentdev, 2017
//
// See LICENSE file in the project root for full license information.
//
#include <Core/CoreEventHandler.hxx>
#include <Core/CoreWindow.hxx>
#include <Core.World/Scene.hxx>
#include <Core.World/Physics.hxx>
#include <Core.Rendering/CommandList.hxx>
#include <Core.Rendering/RenderSystem.hxx>
#include <Core.Rendering/MaterialRenderer.hxx>
#include <Core.Rendering/MeshRenderer.hxx>
#include <Core.World/Camera.hxx>
#include <SpaceShip.hxx>
#include <Meteorite.hxx>
#include <random>
namespace GameProject
{
using namespace Core;
class Game : public CoreEventHandler
{
public:
static Game* Current;
private:
CoreWindowRef m_Window;
Rendering::ViewportRef m_Viewport;
World::SceneRef m_Scene;
Rendering::OcclusionQueryRef m_Query;
Rendering::MaterialRendererRef m_SpaceShipMaterial;
Rendering::MeshRendererRef m_SpaceShipMesh;
Rendering::MaterialRendererRef m_BulletMaterial;
Rendering::MeshRendererRef m_BulletMesh;
Rendering::MaterialRendererRef m_MeteoriteMaterial;
Rendering::MeshRendererRef m_MeteoriteMesh;
SpaceShipRef m_SpaceShip;
float m_MoveLeftVelocity;
float m_MoveRightVelocity;
bool m_FireDown;
bool m_IsPaused;
public:
static constexpr const auto VisibleRangeExtent = 20.0F;
private:
std::mt19937 m_RandomEngine;
float m_SpawnTimeout;
float m_SpawnInterval;
uint32_t m_FrameCount;
float m_FrameCounterTimeout;
bool m_IsRestarting;
uint32_t m_MeteoritesShotDown;
public:
Game() noexcept;
virtual ~Game() noexcept;
public:
virtual void OnWindowClose(CoreWindow* window) noexcept override final;
virtual bool OnKeyDown(uint32_t keyCode, char32_t character, bool isRepeat) noexcept override final;
virtual bool OnKeyUp(uint32_t keyCode, char32_t character, bool isRepeat) noexcept override final;
virtual bool OnWindowSizeChanged(CoreWindow* window, int32_t width, int32_t height, bool wasMinimized) noexcept override final;
virtual bool OnWindowActivated(CoreWindow* window, CoreWindowActivation activationType) noexcept override final;
virtual bool OnApplicationActivated(bool isActive) noexcept override final;
virtual bool OnWindowEnterSizeMove(CoreWindow* window) noexcept override final;
virtual void OnWindowExitSizeMove(CoreWindow* window) noexcept override final;
virtual void Tick(float deltaTime) noexcept;
virtual void Render(float deltaTime) noexcept;
public:
void Restart() noexcept;
void NotifyMeteoriteShotDown() noexcept;
private:
void DoRestart() noexcept;
void RecomputeInterval() noexcept;
public:
virtual void Initialize() noexcept;
virtual void Shutdown() noexcept;
private:
DirectX::XMVECTOR XM_CALLCONV RandomVector2D() noexcept;
DirectX::XMVECTOR XM_CALLCONV RandomVector3D() noexcept;
DirectX::XMVECTOR XM_CALLCONV RandomVector3D(DirectX::FXMVECTOR min, DirectX::FXMVECTOR max) noexcept;
DirectX::XMVECTOR XM_CALLCONV RandomUnitVector() noexcept;
DirectX::XMVECTOR XM_CALLCONV RandomQuaternion() noexcept;
DirectX::XMVECTOR XM_CALLCONV RandomAngularVelocity(float max) noexcept;
float RandomScalar(float min, float max) noexcept;
void SpawnMeteorite() noexcept;
};
}
#endif // INCLUDED_GAME_HXX | 31.657895 | 135 | 0.718482 | [
"render"
] |
492e7f39d8581f1ee3be2b38117e897d0df85f16 | 17,326 | cpp | C++ | src/library/tools/ktest/step.cpp | JishinMaster/clBLAS | 3711b9788b5fd71d5e2f1cae3431753cdcd2ed76 | [
"Apache-2.0"
] | 615 | 2015-01-05T13:24:44.000Z | 2022-03-31T14:58:04.000Z | src/library/tools/ktest/step.cpp | JishinMaster/clBLAS | 3711b9788b5fd71d5e2f1cae3431753cdcd2ed76 | [
"Apache-2.0"
] | 223 | 2015-01-12T21:07:18.000Z | 2021-11-24T17:00:44.000Z | src/library/tools/ktest/step.cpp | JishinMaster/clBLAS | 3711b9788b5fd71d5e2f1cae3431753cdcd2ed76 | [
"Apache-2.0"
] | 250 | 2015-01-05T06:39:43.000Z | 2022-03-23T09:13:00.000Z | /* ************************************************************************
* Copyright 2013 Advanced Micro Devices, 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 <boost/lexical_cast.hpp>
#include <assert.h>
#include <kerngen.h>
#include <clblas-internal.h>
#include <matrix_dims.h>
#include <solution_seq.h>
#include "step.h"
using namespace clMath;
// This enum reflects CLBlasKargs structure, declared in clblas-internal.h
typedef enum StepKarg {
KARG_NONE = 0,
// kernType
// dtype
KARG_ORDER,
KARG_SIDE,
KARG_UPLO,
KARG_TRANS_A,
KARG_TRANS_B,
KARG_DIAG,
KARG_M,
KARG_N,
KARG_K,
KARG_ALPHA,
KARG_A,
KARG_LDA,
KARG_B,
KARG_LDB,
KARG_BETA,
KARG_C,
KARG_LDC,
// addrBits
KARG_OFFSET_M,
KARG_OFFSET_N,
KARG_OFFSET_K,
KARG_SCIMAGE_0,
KARG_SCIMAGE_1,
KARG_OFF_A,
KARG_OFF_BX,
KARG_OFF_CY
} StepKarg;
Step::Step(
BlasFunctionID funcID,
cl_device_id device) :
naiveCall_(""), compareCall_(""), postRandomCall_(""), kernelName_("")
{
memset(&step_, 0, sizeof(step_));
memset(&kextra_, 0, sizeof(kextra_));
step_.funcID = funcID;
step_.device.id = device;
identifyDevice(&step_.device);
step_.args.A = (cl_mem)BUFFER_A;
step_.args.B = (cl_mem)BUFFER_B;
step_.args.C = (cl_mem)BUFFER_C;
if (blasFunctionID() == CLBLAS_SYR2K) {
kextra_.flags = static_cast<KernelExtraFlags>
(kextra_.flags | KEXTRA_SYRK_2K_RANK);
step_.extraFlags = kextra_.flags;
}
}
Step::Step(ListNode *node) :
naiveCall_(""), compareCall_(""), postRandomCall_(""), kernelName_("")
{
SolutionStep *stepNode;
memset(&kextra_, 0, sizeof(kextra_));
stepNode = container_of(node, node, SolutionStep);
memcpy(&step_, stepNode, sizeof(step_));
kextra_.dtype = step_.args.dtype;
kextra_.flags = step_.extraFlags;
kextra_.kernType = CLBLAS_COMPUTING_KERNEL;
}
Step::~Step()
{
for (ArrayVarList::iterator it = arrays_.begin(); it != arrays_.end(); ++it) {
delete (*it);
}
for (VarList::iterator it = vars_.begin(); it != vars_.end(); ++it) {
delete (*it);
}
vars_.clear();
arrays_.clear();
buffers_.clear();
kargMap_.clear();
}
BlasFunctionID
Step::getStepNodeFuncID(ListNode *node)
{
SolutionStep *stepNode;
stepNode = container_of(node, node, SolutionStep);
return stepNode->funcID;
}
void
Step::completeDecompositionSingle()
{
cl_int err;
kextra_.dtype = kargs().dtype;
kextra_.kernType = CLBLAS_COMPUTING_KERNEL;
kextra_.flags = (KernelExtraFlags)(kextra_.flags |
clblasArgsToKextraFlags(&step_.args, blasFunctionID()));
if (deviceVendor(device()) == "Advanced Micro Devices, Inc.") {
kextra_.flags = static_cast<KernelExtraFlags>
(kextra_.flags | KEXTRA_VENDOR_AMD | KEXTRA_ENABLE_MAD);
}
step_.pgran.wfSize = deviceWavefront(device(), &err);
step_.extraFlags = kextra_.flags;
step_.patternID = selectPattern(&step_, 0);
pattern_ = &clblasSolvers[step_.funcID].memPatterns[step_.patternID];
if (0 == step_.subdims[0].bwidth
&& 0 == step_.subdims[0].bwidth
&& 0 == step_.subdims[0].bwidth) {
getStepGranulation(&step_);
}
else if (pattern_->sops->checkCalcDecomp) {
pattern_->sops->checkCalcDecomp(&step_.pgran, step_.subdims, 2,
kextra_.dtype, PGRAN_CALC);
}
else {
size_t wgX, wgY;
size_t x0, y0;
SolverFlags sflags;
// Set up granulation for given dimensions
wgY = step_.subdims[0].y/ step_.subdims[1].y;
wgX = step_.subdims[0].x/ step_.subdims[1].x;
x0 = step_.subdims[0].x;
y0 = step_.subdims[0].y;
if (funcBlasLevel(blasFunctionID()) == 2) {
/* Level 2 decomposition size for vectors (dims[0].x) is 1.
* We have to "restore" it to proceed.
*/
size_t xBlocks;
xBlocks = step_.subdims[0].bwidth / step_.subdims[1].bwidth;
x0 = step_.subdims[1].x * xBlocks;
}
/*
* adjust local size if a subproblem is not divisible
* between all local threads
*/
for (; (wgY > 1) && (y0 < wgY); wgY /= 2) { }
for (; (wgX > 1) && (x0 < wgX); wgX /= 2) { }
sflags = pattern_->sops->getFlags();
if (sflags & SF_WSPACE_2D) {
step_.pgran.wgDim = 2;
step_.pgran.wgSize[0] = (unsigned int)wgY;
step_.pgran.wgSize[1] = (unsigned int)wgX;
}
else {
step_.pgran.wgDim = 1;
step_.pgran.wgSize[0] = (unsigned int)(wgX * wgY);
step_.pgran.wgSize[1] = 1;
}
// fixup work group size in respect with desired work dispatch order
if ((step_.pgran.wgDim == 2) && pattern_->sops->innerDecompositionAxis) {
if (pattern_->sops->innerDecompositionAxis(&step_.args) == DECOMP_AXIS_X) {
unsigned int u;
u = step_.pgran.wgSize[0];
step_.pgran.wgSize[0] = step_.pgran.wgSize[1];
step_.pgran.wgSize[1] = u;
}
}
/* Check that dimensions are bigger than whole problem size */
if (dimensionsExceedProblemSize(&step_)) {
getMinimalStepGranulation(&step_);
}
}
detectProblemTails(&step_);
kextra_.flags = step_.extraFlags;
if (pattern_->sops->fixupArgs) {
pattern_->sops->fixupArgs(&step_.args, &step_.subdims[0], &kextra_);
}
step_.extraFlags = kextra_.flags;
detectOffsets(&step_);
kextra_.flags = step_.extraFlags;
selectVectorization(&step_, &kextra_);
}
void
Step::makeSolutionSequence(ListHead *seq, cl_platform_id platform)
{
SolutionStep *newStep;
(void)platform;
step_.args.A = (cl_mem)BUFFER_A;
step_.args.B = (cl_mem)BUFFER_B;
step_.args.C = (cl_mem)BUFFER_C;
newStep = (SolutionStep*)malloc(sizeof(SolutionStep));
memcpy(newStep, &step_, sizeof(SolutionStep));
listAddToTail(seq, &newStep->node);
decomposeProblemStep(newStep);
}
void
Step::freeSolutionSequence(ListHead *seq)
{
freeSolutionSeq(seq);
}
std::string
Step::generate()
{
ssize_t size;
char *buf;
std::stringstream ss;
if ((pattern_->sops == NULL) || (pattern_->sops->genKernel == NULL)) {
return "";
}
ss << "/*" << std::endl;
for (int i = 0; i < MAX_SUBDIMS; i++) {
ss << "SubproblemDim[" << i << "]" << std::endl;
ss << dumpSubdim(step_.subdims + i) << std::endl;
}
ss << "PGranularity" << std::endl;
ss << dumpPgran() << std::endl;
ss << "CLBLASKernExtra" << std::endl;
ss << dumpKextra() << std::endl;
ss << "MemoryPattern" << std::endl;
ss << dumpMemoryPattern();
ss << "*/" << std::endl << std::endl;
size = pattern_->sops->genKernel(NULL, 0, step_.subdims, &step_.pgran,
static_cast<void*>(&kextra_));
if (size <= 0) {
return 0;
}
buf = new char[size + 1];
if (pattern_->sops->genKernel(buf, size, step_.subdims, &step_.pgran,
static_cast<void*>(&kextra_)) != size) {
delete[] buf;
return "";
}
ss << buf;
delete[] buf;
return ss.str();
}
void
Step::setKargs(const CLBlasKargs& kargs)
{
step_.args = kargs;
}
const char*
Step::getBlasFunctionName()
{
switch (blasFunctionID()) {
case CLBLAS_GEMV:
return "gemv";
case CLBLAS_SYMV:
return "symv";
case CLBLAS_GEMM:
return "gemm";
case CLBLAS_TRMM:
return "trmm";
case CLBLAS_TRSM:
return "trsm";
case CLBLAS_SYRK:
return "syrk";
case CLBLAS_SYR2K:
return "syr2k";
default:
return "";
}
}
void
Step::setDecomposition(
const SubproblemDim *subdims)
{
for (size_t i = 0; i < MAX_SUBDIMS; i++) {
step_.subdims[i] = subdims[i];
}
}
Variable*
Step::addVar(
const std::string& name,
const std::string& type,
const std::string& defaultValue)
{
Variable *var = new Variable(name, type, defaultValue);
vars_.push_back(var);
return var;
}
Variable*
Step::addConst(
const std::string& name,
const std::string& type,
const std::string& defaultValue)
{
Variable *var = addVar(name, type, defaultValue);
var->setConstant(true);
return var;
}
Variable*
Step::addVar(
const std::string& name,
const std::string& type,
size_t value)
{
return addVar(name, type, boost::lexical_cast<std::string>(value));
}
Variable*
Step::addConst(
const std::string& name,
const std::string& type,
size_t value)
{
return addConst(name, type, boost::lexical_cast<std::string>(value));
}
Variable*
Step::addVar(
const std::string& name,
const std::string& type,
int value)
{
return addVar(name, type, boost::lexical_cast<std::string>(value));
}
Variable*
Step::addConst(
const std::string& name,
const std::string& type,
int value)
{
return addConst(name, type, boost::lexical_cast<std::string>(value));
}
MatrixVariable*
Step::addMatrix(
const std::string& name,
const std::string& type,
Variable *rows,
Variable *columns,
Variable *ld,
Variable *off)
{
MatrixVariable *var = new MatrixVariable(name, type, "NULL");
var->setMatrixSize(rows, columns, ld, off);
arrays_.push_back(var);
return var;
}
VectorVariable*
Step::addVector(
const std::string& name,
const std::string& type,
Variable *N,
Variable *inc,
Variable *off)
{
VectorVariable *var = new VectorVariable(name, type, "NULL");
var->setVectorSize(N, inc, off);
arrays_.push_back(var);
return var;
}
Variable*
Step::addBuffer(
BufferID bufID,
const std::string& name,
const std::string& type,
cl_mem_flags flags,
ArrayVariableInterface* hostPtr)
{
Variable *var = addVar(name, type, "NULL");
var->setIsBuffer(true);
var->setFlags(flags);
var->setHostPtr(hostPtr);
var->setBufferID(bufID);
buffers_.push_back(var);
return var;
}
Variable*
Step::getBuffer(BufferID bufID)
{
for (VarList::iterator it = buffers_.begin(); it != buffers_.end(); ++it) {
if ((*it)->getBufID() == bufID) {
return (*it);
}
}
return NULL;
}
void
Step::setKernelArg(
unsigned int index,
const Variable *var)
{
kargMap_[index] = var;
}
std::string
Step::matrixSize(MatrixVariable *matrix)
{
std::stringstream size;
if ((matrix->rows() == NULL) || (matrix->columns() == NULL)) {
return "";
}
if (matrix->off() != NULL) {
size << matrix->off()->name() << " + ";
}
if (matrix->ld() != NULL) {
size << matrix->ld()->name() << " * ";
}
if (step_.args.order == clblasColumnMajor) {
size << matrix->columns()->name();
}
else {
size << matrix->rows()->name();
}
return size.str();
}
std::string
Step::vectorSize(VectorVariable *vector)
{
std::stringstream size;
if (vector->nElems() == NULL) {
return "";
}
if (vector->off() != NULL) {
size << vector->off()->name() << " + ";
}
if (vector->inc() == NULL) {
size << vector->nElems()->name();
}
else {
size << "1 + (" << vector->nElems()->name() << " - 1) * abs("
<< vector->inc()->name() << ")";
}
return size.str();
}
void
Step::assignKargs(const StepKargs& map)
{
CLBlasKargs args;
KernelArg kargsList[MAX_KERNEL_ARGS];
Variable *v;
if ((pattern_->sops == NULL) || (pattern_->sops->assignKargs == NULL)) {
return;
}
memset(&kargsList, KARG_NONE, sizeof(kargsList));
args.kernType = CLBLAS_COMPUTING_KERNEL;
args.dtype = TYPE_COMPLEX_DOUBLE;
args.addrBits = 0;
args.order = static_cast<clblasOrder>(KARG_ORDER);
args.side = static_cast<clblasSide>(KARG_SIDE);
args.uplo = static_cast<clblasUplo>(KARG_UPLO);
args.transA = static_cast<clblasTranspose>(KARG_TRANS_A);
args.transB = static_cast<clblasTranspose>(KARG_TRANS_B);
args.diag = static_cast<clblasDiag>(KARG_DIAG);
args.M = KARG_M;
args.N = KARG_N;
args.K = KARG_K;
args.lda.matrix = KARG_LDA;
args.ldb.matrix = KARG_LDB;
args.ldc.matrix = KARG_LDC;
args.offsetM = KARG_OFFSET_M;
args.offsetN = KARG_OFFSET_N;
args.offsetK = KARG_OFFSET_K;
args.offA = KARG_OFF_A;
args.offBX = KARG_OFF_BX;
args.offCY = KARG_OFF_CY;
args.A = reinterpret_cast<cl_mem>(KARG_A);
args.B = reinterpret_cast<cl_mem>(KARG_B);
args.C = reinterpret_cast<cl_mem>(KARG_C);
memset(&args.alpha, KARG_ALPHA, sizeof(args.alpha));
memset(&args.beta, KARG_BETA, sizeof(args.beta));
args.scimage[0] = reinterpret_cast<cl_mem>(KARG_SCIMAGE_0);
args.scimage[1] = reinterpret_cast<cl_mem>(KARG_SCIMAGE_1);
pattern_->sops->assignKargs(kargsList, static_cast<void*>(&args), &kextra_);
for (unsigned int i = 0; (i < MAX_KERNEL_ARGS) && (kargsList[i].typeSize != 0); i++) {
switch (static_cast<StepKarg>(kargsList[i].arg.data[0])) {
case KARG_M:
v = map.M;
break;
case KARG_N:
v = map.N;
break;
case KARG_K:
v = map.K;
break;
case KARG_ALPHA:
v = map.alpha;
break;
case KARG_A:
v = map.A;
break;
case KARG_LDA:
v = map.lda;
break;
case KARG_B:
v = map.B;
break;
case KARG_LDB:
v = map.ldb;
break;
case KARG_BETA:
v = map.beta;
break;
case KARG_C:
v = map.C;
break;
case KARG_LDC:
v = map.ldc;
break;
case KARG_OFFSET_M:
v = map.offsetM;
break;
case KARG_OFFSET_N:
v = map.offsetN;
break;
case KARG_OFFSET_K:
v = map.offsetK;
break;
case KARG_SCIMAGE_0:
v = map.scimage0;
break;
case KARG_SCIMAGE_1:
v = map.scimage1;
break;
case KARG_OFF_A:
v = map.offA;
break;
case KARG_OFF_BX:
v = map.offBX;
break;
case KARG_OFF_CY:
v = map.offCY;
break;
default:
// KARG_ORDER, KARG_SIDE, KARG_UPLO, KARG_TRANS_A, KARG_TRANS_B,
// KARG_DIAG
v = NULL;
break;
}
if (v != NULL) {
setKernelArg(i, v);
}
}
}
std::string
Step::globalWorkSize()
{
size_t globalWorkSize[MAX_WORK_DIM] = { 0, 0, 0 };
std::stringstream ss;
SubproblemDim dims[MAX_SUBDIMS];
memcpy(dims, step_.subdims, sizeof(dims));
if (pattern_->sops->calcThreads) {
pattern_->sops->calcThreads(globalWorkSize, step_.subdims,
&step_.pgran, &step_.args, &kextra_);
}
else {
SubproblemDim globDim;
const PGranularity *pg;
pg = (pattern_->nrLevels == 1) ? NULL : &step_.pgran;
kargsToProbDims(&globDim, blasFunctionID(), &step_.args, false);
// fixup dimensions in respect with desired work dispatch order
if ((pgran().wgDim == 2) && pattern_->sops->innerDecompositionAxis) {
if (pattern_->sops->innerDecompositionAxis(&step_.args) ==
DECOMP_AXIS_X) {
/*
* these dimensions will not be used more anywhere, so we can
* just swap them
*/
swapDimXY(&dims[0]);
swapDimXY(&dims[1]);
swapDimXY(&globDim);
}
}
calcGlobalThreads(globalWorkSize, dims, pg, globDim.y, globDim.x);
}
for (unsigned int i = 0; i < pgran().wgDim; i++) {
if (i != 0) {
ss << ", ";
}
ss << globalWorkSize[i];
}
return ss.str();
}
void
Step::setKernelName(std::string name)
{
kernelName_ = name;
}
std::string
Step::deviceVendor(cl_device_id device)
{
cl_int err;
size_t len;
char *str;
std::string vendor = "";
err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, 0, NULL, &len);
if (err != CL_SUCCESS) {
return "";
}
str = new char[len + 1];
err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, len, str, NULL);
if (err == CL_SUCCESS) {
vendor = str;
}
delete[] str;
return vendor;
}
| 25.037572 | 90 | 0.576128 | [
"vector"
] |
49547fdd12c54b9d6e38df9d36ffb5afd20f3266 | 13,195 | cpp | C++ | Sources/Elastos/LibCore/src/elastosx/crypto/CMac.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/src/elastosx/crypto/CMac.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/src/elastosx/crypto/CMac.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "Elastos.CoreLibrary.Security.h"
#include "CMac.h"
#include "MacSpi.h"
#include "CSecurity.h"
#include "AutoLock.h"
#include "org/apache/harmony/security/fortress/CEngine.h"
#include <elastos/utility/logging/Logger.h>
using Elastos::Core::AutoLock;
using Elastos::Security::CSecurity;
using Elastos::Security::ISecurity;
using Elastos::Utility::IIterator;
using Org::Apache::Harmony::Security::Fortress::CEngine;
using Elastos::Utility::Logging::Logger;
namespace Elastosx {
namespace Crypto {
static AutoPtr<IEngine> InitEngine()
{
AutoPtr<CEngine> e;
CEngine::NewByFriend(String("Mac")/*SERVICE*/, (CEngine**)&e);
return e;
}
CAR_OBJECT_IMPL(CMac)
CAR_INTERFACE_IMPL(CMac, Object, IMac)
String CMac::SERVICE("Mac");
AutoPtr<IEngine> CMac::ENGINE = InitEngine();
CMac::CMac()
: mAlgorithm(String(NULL))
, mIsInitMac(FALSE)
{
}
ECode CMac::constructor(
/* [in] */ IMacSpi* macSpi,
/* [in] */ IProvider* provider,
/* [in] */ const String& algorithm)
{
mSpecifiedProvider = provider;
mAlgorithm = algorithm;
mSpiImpl = macSpi;
mIsInitMac = FALSE;
return NOERROR;
}
ECode CMac::GetAlgorithm(
/* [out] */ String * name)
{
VALIDATE_NOT_NULL(name)
*name = mAlgorithm;
return NOERROR;
}
ECode CMac::GetProvider(
/* [out] */ IProvider ** provider)
{
VALIDATE_NOT_NULL(provider)
*provider = mProvider;
REFCOUNT_ADD(*provider)
return NOERROR;
}
ECode CMac::GetMacLength(
/* [out] */ Int32 * len)
{
VALIDATE_NOT_NULL(len)
*len = 0;
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
return spi->EngineGetMacLength(len);
}
ECode CMac::Init(
/* [in] */ IKey * key,
/* [in] */ IAlgorithmParameterSpec* spec)
{
if (key == NULL) {
// throw new InvalidKeyException("key == NULL");
Logger::E("CMac", "Init 2 key == NULL");
return E_INVALID_KEY_EXCEPTION;
}
AutoPtr<IMacSpi> spi;
GetSpi(key, (IMacSpi**)&spi);
spi->EngineInit(key, spec);
mIsInitMac = TRUE;
return NOERROR;
}
ECode CMac::Init(
/* [in] */ IKey * key)
{
if (key == NULL) {
// throw new InvalidKeyException("key == NULL");
Logger::E("CMac", "Init 1 key == NULL");
return E_INVALID_KEY_EXCEPTION;
}
// try {
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
spi->EngineInit(key, NULL);
mIsInitMac = TRUE;
// } catch (InvalidAlgorithmParameterException e) {
// throw new RuntimeException(e);
// }
return NOERROR;
}
ECode CMac::Update(
/* [in] */ Byte input)
{
if (!mIsInitMac) {
// throw new IllegalStateException();
return E_ILLEGAL_STATE_EXCEPTION;
}
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
return spi->EngineUpdate(input);
}
ECode CMac::Update(
/* [in] */ ArrayOf<Byte> * input,
/* [in] */ Int32 offset,
/* [in] */ Int32 len)
{
if (!mIsInitMac) {
// throw new IllegalStateException();
return E_ILLEGAL_STATE_EXCEPTION;
}
if (input == NULL) {
return NOERROR;
}
if ((offset < 0) || (len < 0) || ((offset + len) > input->GetLength())) {
// throw new IllegalArgumentException("Incorrect arguments."
// + " input.length=" + input.length
// + " offset=" + offset + ", len=" + len);
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
return spi->EngineUpdate(input, offset, len);
}
ECode CMac::Update(
/* [in] */ ArrayOf<Byte> * input)
{
if (!mIsInitMac) {
// throw new IllegalStateException();
return E_ILLEGAL_STATE_EXCEPTION;
}
if (input != NULL) {
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
spi->EngineUpdate(input, 0, input->GetLength());
}
return NOERROR;
}
ECode CMac::Update(
/* [in] */ IByteBuffer * input)
{
if (!mIsInitMac) {
// throw new IllegalStateException();
return E_ILLEGAL_STATE_EXCEPTION;
}
if (input != NULL) {
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
((MacSpi*)spi.Get())->EngineUpdate(input);
} else {
// throw new IllegalArgumentException("input == NULL");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
return NOERROR;
}
ECode CMac::DoFinal(
/* [out, callee] */ ArrayOf<Byte> ** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
if (!mIsInitMac) {
// throw new IllegalStateException();
return E_ILLEGAL_STATE_EXCEPTION;
}
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
return spi->EngineDoFinal(result);
}
ECode CMac::DoFinal(
/* [in] */ ArrayOf<Byte> * output,
/* [in] */ Int32 outOffset)
{
if (!mIsInitMac) {
// throw new IllegalStateException();
return E_ILLEGAL_STATE_EXCEPTION;
}
if (output == NULL) {
// throw new ShortBufferException("output == NULL");
return E_SHORT_BUFFER_EXCEPTION;
}
if ((outOffset < 0) || (outOffset >= output->GetLength())) {
// throw new ShortBufferException("Incorrect outOffset: " + outOffset);
return E_SHORT_BUFFER_EXCEPTION;
}
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
Int32 t;
spi->EngineGetMacLength(&t);
if (t > (output->GetLength() - outOffset)) {
// throw new ShortBufferException("Output buffer is short. Needed " + t + " bytes.");
return E_SHORT_BUFFER_EXCEPTION;
}
AutoPtr<ArrayOf<Byte> > result;
spi->EngineDoFinal((ArrayOf<Byte>**)&result);
// System.arraycopy(result, 0, output, outOffset, result->GetLength());
output->Copy(outOffset, result, 0, result->GetLength());
return NOERROR;
}
ECode CMac::DoFinal(
/* [in] */ ArrayOf<Byte> * input,
/* [out, callee] */ ArrayOf<Byte> ** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
if (!mIsInitMac) {
// throw new IllegalStateException();
Logger::E("CMac", "DoFinal IllegalStateException, mIsInitMac");
return E_ILLEGAL_STATE_EXCEPTION;
}
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
if (input != NULL) {
spi->EngineUpdate(input, 0, input->GetLength());
}
return spi->EngineDoFinal(result);
}
ECode CMac::Reset()
{
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
return spi->EngineReset();
}
ECode CMac::GetInstance(
/* [in] */ const String& algorithm,
/* [out] */ IMac ** mac)
{
VALIDATE_NOT_NULL(mac)
*mac = NULL;
return GetMac(algorithm, NULL, mac);
}
ECode CMac::GetInstance(
/* [in] */ const String& algorithm,
/* [in] */ const String& provider,
/* [out] */ IMac ** mac)
{
VALIDATE_NOT_NULL(mac)
*mac = NULL;
if (provider == NULL || provider.IsEmpty()) {
// throw new IllegalArgumentException("Provider is NULL or empty");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<IProvider> impProvider;
AutoPtr<ISecurity> security;
CSecurity::AcquireSingleton((ISecurity**)&security);
security->GetProvider(provider, (IProvider**)&impProvider);
if (impProvider == NULL) {
// throw new NoSuchProviderException(provider);
return E_NO_SUCH_PROVIDER_EXCEPTION;
}
return GetMac(algorithm, impProvider, mac);
}
ECode CMac::GetInstance(
/* [in] */ const String& algorithm,
/* [in] */ IProvider * provider,
/* [out] */ IMac ** mac)
{
VALIDATE_NOT_NULL(mac)
*mac = NULL;
if (provider == NULL) {
// throw new IllegalArgumentException("provider == NULL");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
return GetMac(algorithm, provider, mac);
}
ECode CMac::Clone(
/* [out] */ IInterface** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
AutoPtr<IMacSpi> newSpiImpl;
AutoPtr<IMacSpi> spi;
GetSpi((IMacSpi**)&spi);
if (spi != NULL) {
AutoPtr<IInterface> clone;
ICloneable::Probe(spi)->Clone((IInterface**)&clone);
newSpiImpl = IMacSpi::Probe(clone);
}
AutoPtr<CMac> mac;
CMac::NewByFriend(newSpiImpl, mProvider, mAlgorithm, (CMac**)&mac);
mac->mIsInitMac = mIsInitMac;
*result = TO_IINTERFACE(mac);
REFCOUNT_ADD(*result)
return NOERROR;
}
ECode CMac::GetMac(
/* [in] */ const String& algorithm,
/* [in] */ IProvider * provider,
/* [out] */ IMac ** mac)
{
VALIDATE_NOT_NULL(mac)
*mac = NULL;
if (algorithm == NULL) {
// throw new NullPointerException("algorithm == NULL");
return E_NULL_POINTER_EXCEPTION;
}
if (TryAlgorithm(NULL, provider, algorithm) == NULL) {
if (provider == NULL) {
// throw new NoSuchAlgorithmException("No provider found for " + algorithm);
return E_NO_SUCH_ALGORITHM_EXCEPTION;
} else {
// throw new NoSuchAlgorithmException("Provider " + provider.getName()
// + " does not provide " + algorithm);
return E_NO_SUCH_ALGORITHM_EXCEPTION;
}
}
return CMac::New(NULL, provider, algorithm, mac);
}
AutoPtr<ISpiAndProvider> CMac::TryAlgorithm(
/* [in] */ IKey * key,
/* [in] */ IProvider * provider,
/* [in] */ const String& algorithm)
{
if (provider != NULL) {
AutoPtr<IProviderService> service;
provider->GetService(SERVICE, algorithm, (IProviderService**)&service);
if (service == NULL) {
return NULL;
}
return TryAlgorithmWithProvider(key, service);
}
AutoPtr<IArrayList/*<Provider.Service*/> services;
ENGINE->GetServices(algorithm, (IArrayList**)&services);
if (services == NULL) {
return NULL;
}
AutoPtr<IIterator> it;
services->GetIterator((IIterator**)&it);
Boolean has = FALSE;
while(it->HasNext(&has), has) {
AutoPtr<IInterface> service;
it->GetNext((IInterface**)&service);
AutoPtr<ISpiAndProvider> sap = TryAlgorithmWithProvider(key, IProviderService::Probe(service));
if (sap != NULL) {
return sap;
}
}
return NULL;
}
AutoPtr<ISpiAndProvider> CMac::TryAlgorithmWithProvider(
/* [in] */ IKey * key,
/* [in] */ IProviderService* service)
{
// try {
if (key != NULL) {
Boolean tmp = FALSE;
if (FAILED(service->SupportsParameter(key, &tmp))) {
return NULL;
}
if (!tmp) {
return NULL;
}
}
AutoPtr<ISpiAndProvider> sap;
if (FAILED(ENGINE->GetInstance(service, String(NULL), (ISpiAndProvider**)&sap))) {
return NULL;
}
AutoPtr<IInterface> spi;
sap->GetSpi((IInterface**)&spi);
AutoPtr<IProvider> provider;
if (spi.Get() == NULL || (sap->GetProvider((IProvider**)&provider), provider.Get()) == NULL) {
return NULL;
}
if (IMacSpi::Probe(spi) == NULL) {
return NULL;
}
return sap;
// } catch (NoSuchAlgorithmException ignored) {
// }
// return NULL;
}
/**
* Makes sure a MacSpi that matches this type is selected.
*/
ECode CMac::GetSpi(
/* [in] */ IKey* key,
/* [out] */ IMacSpi** spi)
{
VALIDATE_NOT_NULL(spi)
*spi = NULL;
{ AutoLock syncLock(mInitLock);
if (mSpiImpl != NULL && mProvider != NULL && key == NULL) {
*spi = mSpiImpl;
REFCOUNT_ADD(*spi)
return NOERROR;
}
if (mAlgorithm == NULL) {
*spi = NULL;
return NOERROR;
}
AutoPtr<ISpiAndProvider> sap = TryAlgorithm(key, mSpecifiedProvider, mAlgorithm);
if (sap == NULL) {
// throw new ProviderException("No provider for " + getAlgorithm());
return E_PROVIDER_EXCEPTION;
}
/*
* Set our Spi if we've never been initialized or if we have the Spi
* specified and have a NULL provider.
*/
if (mSpiImpl == NULL || mProvider != NULL) {
AutoPtr<IInterface> spi;
sap->GetSpi((IInterface**)&spi);
mSpiImpl = IMacSpi::Probe(spi);
}
sap->GetProvider((IProvider**)&mProvider);
*spi = mSpiImpl;
REFCOUNT_ADD(*spi)
return NOERROR;
}
return NOERROR;
}
/**
* Convenience call when the Key is not available.
*/
ECode CMac::GetSpi(
/* [out] */ IMacSpi** spi)
{
return GetSpi(NULL, spi);
}
} // Crypto
} // Elastosx
| 27.262397 | 103 | 0.592725 | [
"object"
] |
4959b03d062ab7b72dd83031a7212fbe7ba31f61 | 23,716 | cpp | C++ | Sources/Elastos/Packages/Apps/Dialer/src/elastos/droid/dialer/list/SwipeHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Packages/Apps/Dialer/src/elastos/droid/dialer/list/SwipeHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Packages/Apps/Dialer/src/elastos/droid/dialer/list/SwipeHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/dialer/list/SwipeHelper.h"
#include <elastos/core/Math.h>
#include <elastos/utility/logging/Logger.h>
#include "R.h"
using Elastos::Droid::Animation::ITimeInterpolator;
using Elastos::Droid::Animation::IAnimator;
using Elastos::Droid::Animation::IValueAnimator;
using Elastos::Droid::Animation::IObjectAnimatorHelper;
using Elastos::Droid::Animation::CObjectAnimatorHelper;
using Elastos::Droid::Animation::IAnimatorListener;
using Elastos::Droid::Animation::EIID_IAnimatorUpdateListener;
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Graphics::CRectF;
using Elastos::Droid::Graphics::IMatrix;
using Elastos::Droid::View::IViewParent;
using Elastos::Droid::View::IVelocityTrackerHelper;
using Elastos::Droid::View::CVelocityTrackerHelper;
using Elastos::Droid::View::Animation::CLinearInterpolator;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Dialer {
namespace List {
//=================================================================
// SwipeHelper::DismissAnimatorListenerAdapter
//=================================================================
SwipeHelper::DismissAnimatorListenerAdapter::DismissAnimatorListenerAdapter(
/* [in] */ SwipeHelper* host,
/* [in] */ IView* view,
/* [in] */ IView* animView)
: mHost(host)
, mView(view)
, mAnimView(animView)
{}
ECode SwipeHelper::DismissAnimatorListenerAdapter::OnAnimationEnd(
/* [in] */ IAnimator* animation)
{
mHost->mCallback->OnChildDismissed(mView);
mAnimView->SetLayerType(IView::LAYER_TYPE_NONE, NULL);
return NOERROR;
}
//=================================================================
// SwipeHelper::DismissAnimatorUpdateListener
//=================================================================
CAR_INTERFACE_IMPL(SwipeHelper::DismissAnimatorUpdateListener, Object, IAnimatorUpdateListener)
SwipeHelper::DismissAnimatorUpdateListener::DismissAnimatorUpdateListener(
/* [in] */ SwipeHelper* host,
/* [in] */ Boolean canBeDismissed,
/* [in] */ IView* animView)
: mHost(host)
, mCanBeDismissed(canBeDismissed)
, mAnimView(animView)
{}
ECode SwipeHelper::DismissAnimatorUpdateListener::OnAnimationUpdate(
/* [in] */ IValueAnimator* animation)
{
if (FADE_OUT_DURING_SWIPE && mCanBeDismissed) {
mAnimView->SetAlpha(mHost->GetAlphaForOffset(mAnimView));
}
mHost->InvalidateGlobalRegion(mAnimView);
return NOERROR;
}
//=================================================================
// SwipeHelper::SnapAnimatorUpdateListener
//=================================================================
CAR_INTERFACE_IMPL(SwipeHelper::SnapAnimatorUpdateListener, Object, IAnimatorUpdateListener)
SwipeHelper::SnapAnimatorUpdateListener::SnapAnimatorUpdateListener(
/* [in] */ SwipeHelper* host,
/* [in] */ Boolean canBeDismissed,
/* [in] */ IView* animView)
: mHost(host)
, mCanBeDismissed(canBeDismissed)
, mAnimView(animView)
{}
ECode SwipeHelper::SnapAnimatorUpdateListener::OnAnimationUpdate(
/* [in] */ IValueAnimator* animation)
{
if (FADE_OUT_DURING_SWIPE && mCanBeDismissed) {
mAnimView->SetAlpha(mHost->GetAlphaForOffset(mAnimView));
}
mHost->InvalidateGlobalRegion(mAnimView);
return NOERROR;
}
//=================================================================
// SwipeHelper::SnapAnimatorListenerAdapter
//=================================================================
SwipeHelper::SnapAnimatorListenerAdapter::SnapAnimatorListenerAdapter(
/* [in] */ SwipeHelper* host,
/* [in] */ IView* animView)
: mHost(host)
, mAnimView(animView)
{}
ECode SwipeHelper::SnapAnimatorListenerAdapter::OnAnimationEnd(
/* [in] */ IAnimator* animation)
{
mAnimView->SetAlpha(mHost->mStartAlpha);
mHost->mCallback->OnDragCancelled(mHost->mCurrView);
return NOERROR;
}
//=================================================================
// SwipeHelper
//=================================================================
const Int32 SwipeHelper::IS_SWIPEABLE_TAG = Elastos::Droid::Dialer::R::id::is_swipeable_tag;
const AutoPtr<Object> SwipeHelper::IS_SWIPEABLE = new Object();
const Int32 SwipeHelper::X;
const Int32 SwipeHelper::Y;
const Float SwipeHelper::ALPHA_FADE_START;
const String SwipeHelper::TAG("SwipeHelper");
const Boolean SwipeHelper::DEBUG_INVALIDATE;
const Boolean SwipeHelper::CONSTRAIN_SWIPE;
const Boolean SwipeHelper::FADE_OUT_DURING_SWIPE;
const Boolean SwipeHelper::DISMISS_IF_SWIPED_FAR_ENOUGH;
const Boolean SwipeHelper::LOG_SWIPE_DISMISS_VELOCITY;
static AutoPtr<ILinearInterpolator> InitInterpolator()
{
AutoPtr<ILinearInterpolator> interpolator;
CLinearInterpolator::New((ILinearInterpolator**)&interpolator);
return interpolator;
}
AutoPtr<ILinearInterpolator> SwipeHelper::sLinearInterpolator = InitInterpolator();
Int32 SwipeHelper::SWIPE_ESCAPE_VELOCITY = -1;
Int32 SwipeHelper::DEFAULT_ESCAPE_ANIMATION_DURATION = 0;
Int32 SwipeHelper::MAX_ESCAPE_ANIMATION_DURATION = 0;
Int32 SwipeHelper::MAX_DISMISS_VELOCITY = 0;
Int32 SwipeHelper::SNAP_ANIM_LEN = 0;
Int32 SwipeHelper::SWIPE_SCROLL_SLOP = 0;
Float SwipeHelper::MIN_SWIPE = 0;
Float SwipeHelper::MIN_VERT = 0;
Float SwipeHelper::MIN_LOCK = 0;
const Float SwipeHelper::ALPHA_FADE_END;
const Float SwipeHelper::FACTOR;
const Int32 SwipeHelper::PROTECTION_PADDING;
SwipeHelper::SwipeHelper(
/* [in] */ IContext* context,
/* [in] */ Int32 swipeDirection,
/* [in] */ ISwipeHelperCallback* callback,
/* [in] */ Float densityScale,
/* [in] */ Float pagingTouchSlop)
: mMinAlpha(0.3)
, mPagingTouchSlop(0.0)
, mSwipeDirection(0)
, mInitialTouchPosX(0.0)
, mDragging(FALSE)
, mCanCurrViewBeDimissed(FALSE)
, mDensityScale(0.0)
, mLastY(0.0)
, mInitialTouchPosY(0.0)
, mStartAlpha(0.0)
, mProtected(FALSE)
, mChildSwipedFarEnoughFactor(0.4)
, mChildSwipedFastEnoughFactor(0.05)
{
mCallback = callback;
mSwipeDirection = swipeDirection;
AutoPtr<IVelocityTrackerHelper> helper;
CVelocityTrackerHelper::AcquireSingleton((IVelocityTrackerHelper**)&helper);
helper->Obtain((IVelocityTracker**)&mVelocityTracker);
mDensityScale = densityScale;
mPagingTouchSlop = pagingTouchSlop;
if (SWIPE_ESCAPE_VELOCITY == -1) {
AutoPtr<IResources> res;
context->GetResources((IResources**)&res);
res->GetInteger(Elastos::Droid::Dialer::R::integer::swipe_escape_velocity, &SWIPE_ESCAPE_VELOCITY);
res->GetInteger(Elastos::Droid::Dialer::R::integer::escape_animation_duration, &DEFAULT_ESCAPE_ANIMATION_DURATION);
res->GetInteger(Elastos::Droid::Dialer::R::integer::max_escape_animation_duration, &MAX_ESCAPE_ANIMATION_DURATION);
res->GetInteger(Elastos::Droid::Dialer::R::integer::max_dismiss_velocity, &MAX_DISMISS_VELOCITY);
res->GetInteger(Elastos::Droid::Dialer::R::integer::snap_animation_duration, &SNAP_ANIM_LEN);
res->GetInteger(Elastos::Droid::Dialer::R::integer::swipe_scroll_slop, &SWIPE_SCROLL_SLOP);
res->GetDimension(Elastos::Droid::Dialer::R::dimen::min_swipe, &MIN_SWIPE);
res->GetDimension(Elastos::Droid::Dialer::R::dimen::min_vert, &MIN_VERT);
res->GetDimension(Elastos::Droid::Dialer::R::dimen::min_lock, &MIN_LOCK);
}
}
void SwipeHelper::SetDensityScale(
/* [in] */ Float densityScale)
{
mDensityScale = densityScale;
}
void SwipeHelper::SetPagingTouchSlop(
/* [in] */ Float pagingTouchSlop)
{
mPagingTouchSlop = pagingTouchSlop;
}
void SwipeHelper::SetChildSwipedFarEnoughFactor(
/* [in] */ Float factor)
{
mChildSwipedFarEnoughFactor = factor;
}
void SwipeHelper::SetChildSwipedFastEnoughFactor(
/* [in] */ Float factor)
{
mChildSwipedFastEnoughFactor = factor;
}
Float SwipeHelper::GetVelocity(
/* [in] */ IVelocityTracker* vt)
{
Float velocity;
mSwipeDirection == X ? vt->GetXVelocity(&velocity) : vt->GetYVelocity(&velocity);
return velocity;
}
AutoPtr<IObjectAnimator> SwipeHelper::CreateTranslationAnimation(
/* [in] */ IView* v,
/* [in] */ Float newPos)
{
AutoPtr<IObjectAnimatorHelper> helper;
CObjectAnimatorHelper::AcquireSingleton((IObjectAnimatorHelper**)&helper);
AutoPtr<ArrayOf<Float> > attrs = ArrayOf<Float>::Alloc(1);
(*attrs)[0] = newPos;
AutoPtr<IObjectAnimator> anim;
helper->OfFloat(v,
mSwipeDirection == X ? String("translationX") : String("translationY"),
attrs, (IObjectAnimator**)&anim);
return anim;
}
AutoPtr<IObjectAnimator> SwipeHelper::CreateDismissAnimation(
/* [in] */ IView* v,
/* [in] */ Float newPos,
/* [in] */ Int32 duration)
{
AutoPtr<IObjectAnimator> anim = CreateTranslationAnimation(v, newPos);
AutoPtr<IAnimator> a = IAnimator::Probe(anim);
a->SetInterpolator(ITimeInterpolator::Probe(sLinearInterpolator));
a->SetDuration(duration);
return anim;
}
Float SwipeHelper::GetPerpendicularVelocity(
/* [in] */ IVelocityTracker* vt)
{
Float velocity;
mSwipeDirection == X ? vt->GetYVelocity(&velocity) : vt->GetXVelocity(&velocity);
return velocity;
}
void SwipeHelper::SetTranslation(
/* [in] */ IView* v,
/* [in] */ Float translate)
{
if (mSwipeDirection == X) {
v->SetTranslationX(translate);
}
else {
v->SetTranslationY(translate);
}
}
Float SwipeHelper::GetSize(
/* [in] */ IView* v)
{
Int32 size;
mSwipeDirection == X ? v->GetMeasuredWidth(&size) : v->GetMeasuredHeight(&size);
return (Float)size;
}
void SwipeHelper::SetMinAlpha(
/* [in] */ Float minAlpha)
{
mMinAlpha = minAlpha;
}
Float SwipeHelper::GetAlphaForOffset(
/* [in] */ IView* view)
{
Float viewSize = GetSize(view);
Float fadeSize = ALPHA_FADE_END * viewSize;
Float result = mStartAlpha;
Float pos;
view->GetTranslationX(&pos);
if (pos >= viewSize * ALPHA_FADE_START) {
result = mStartAlpha - (pos - viewSize * ALPHA_FADE_START) / fadeSize;
}
else if (pos < viewSize * (mStartAlpha - ALPHA_FADE_START)) {
result = mStartAlpha + (viewSize * ALPHA_FADE_START + pos) / fadeSize;
}
return Elastos::Core::Math::Max(mMinAlpha, result);
}
void SwipeHelper::InvalidateGlobalRegion(
/* [in] */ IView* view)
{
Int32 left, top, right, bottom;
view->GetLeft(&left);
view->GetTop(&top);
view->GetRight(&right);
view->GetBottom(&bottom);
AutoPtr<IRectF> rectF;
CRectF::New(left, top, right, bottom, (IRectF**)&rectF);
InvalidateGlobalRegion(view, rectF);
}
void SwipeHelper::InvalidateGlobalRegion(
/* [in] */ IView* view,
/* [in] */ IRectF* childBounds)
{
// childBounds.offset(view.getTranslationX(), view.getTranslationY());
if (DEBUG_INVALIDATE)
Logger::V(TAG, "-------------");
AutoPtr<IViewParent> parent;
view->GetParent((IViewParent**)&parent);
while (parent != NULL && IView::Probe(parent) != NULL) {
view = IView::Probe(parent);
AutoPtr<IMatrix> matrix;
view->GetMatrix((IMatrix**)&matrix);
Boolean result;
matrix->MapRect(childBounds, &result);
Float left, top, right, bottom;
childBounds->GetLeft(&left);
childBounds->GetTop(&top);
childBounds->GetRight(&right);
childBounds->GetBottom(&bottom);
view->Invalidate((Int32)Elastos::Core::Math::Floor(left), (Int32)Elastos::Core::Math::Floor(top),
(Int32)Elastos::Core::Math::Ceil(right), (Int32)Elastos::Core::Math::Ceil(bottom));
if (DEBUG_INVALIDATE) {
Logger::V(TAG, "INVALIDATE(%d,%d,%d,%d", (Int32)Elastos::Core::Math::Floor(left),
(Int32)Elastos::Core::Math::Floor(top), (Int32)Elastos::Core::Math::Ceil(right),
(Int32)Elastos::Core::Math::Ceil(bottom));
}
}
}
Boolean SwipeHelper::OnInterceptTouchEvent(
/* [in] */ IMotionEvent* ev)
{
Int32 action;
ev->GetAction(&action);
switch (action) {
case IMotionEvent::ACTION_DOWN: {
ev->GetY(&mLastY);
mDragging = FALSE;
AutoPtr<IView> temp;
mCallback->GetChildAtPosition(ev, (IView**)&temp);
mCurrView = temp;
mVelocityTracker->Clear();
if (mCurrView != NULL) {
AutoPtr<IView> temp1;
mCallback->GetChildContentView(mCurrView, (IView**)&temp1);
mCurrAnimView = temp1;
mCurrAnimView->GetAlpha(&mStartAlpha);
mCallback->CanChildBeDismissed(mCurrView, &mCanCurrViewBeDimissed);
mVelocityTracker->AddMovement(ev);
ev->GetX(&mInitialTouchPosX);
ev->GetY(&mInitialTouchPosY);
}
break;
}
case IMotionEvent::ACTION_MOVE: {
if (mCurrView != NULL) {
// Check the movement direction.
if (mLastY >= 0 && !mDragging) {
Float currY;
ev->GetY(&currY);
Float currX;
ev->GetX(&currX);
Float deltaY = Elastos::Core::Math::Abs(currY - mInitialTouchPosY);
Float deltaX = Elastos::Core::Math::Abs(currX - mInitialTouchPosX);
if (deltaY > SWIPE_SCROLL_SLOP && deltaY > (FACTOR * deltaX)) {
ev->GetY(&mLastY);
mCallback->OnScroll();
return FALSE;
}
}
mVelocityTracker->AddMovement(ev);
Float pos;
ev->GetX(&pos);
Float delta = pos - mInitialTouchPosX;
if (Elastos::Core::Math::Abs(delta) > mPagingTouchSlop) {
AutoPtr<IView> view;
mCallback->GetChildContentView(mCurrView, (IView**)&view);
mCallback->OnBeginDrag(view);
mDragging = TRUE;
Float x;
ev->GetX(&x);
Float tx;
mCurrAnimView->GetTranslationX(&tx);
mInitialTouchPosX = x - tx;
ev->GetY(&mInitialTouchPosY);
}
}
ev->GetY(&mLastY);
break;
}
case IMotionEvent::ACTION_UP:
case IMotionEvent::ACTION_CANCEL:
mDragging = FALSE;
mCurrView = NULL;
mCurrAnimView = NULL;
mLastY = -1;
break;
}
return mDragging;
}
void SwipeHelper::DismissChild(
/* [in] */ IView* view,
/* [in] */ Float velocity)
{
AutoPtr<IView> animView;
mCallback->GetChildContentView(view, (IView**)&animView);
Boolean canAnimViewBeDismissed;
mCallback->CanChildBeDismissed(view, &canAnimViewBeDismissed);
Float newPos = DeterminePos(animView, velocity);
Int32 duration = DetermineDuration(animView, newPos, velocity);
animView->SetLayerType(IView::LAYER_TYPE_HARDWARE, NULL);
AutoPtr<IObjectAnimator> anim = CreateDismissAnimation(animView, newPos, duration);
AutoPtr<IAnimatorListener> listener = (IAnimatorListener*)new DismissAnimatorListenerAdapter(this, view, animView);
IAnimator::Probe(anim)->AddListener(listener);
AutoPtr<IAnimatorUpdateListener> updateListener =
(IAnimatorUpdateListener*)new DismissAnimatorUpdateListener(this, canAnimViewBeDismissed, animView);
IValueAnimator::Probe(anim)->AddUpdateListener(updateListener);
IAnimator::Probe(anim)->Start();
}
Int32 SwipeHelper::DetermineDuration(
/* [in] */ IView* animView,
/* [in] */ Float newPos,
/* [in] */ Float velocity)
{
Int32 duration = MAX_ESCAPE_ANIMATION_DURATION;
if (velocity != 0) {
Float x;
animView->GetTranslationX(&x);
duration = Elastos::Core::Math::Min(duration,
(Int32)(Elastos::Core::Math::Abs(newPos - x) * 1000.0f / Elastos::Core::Math::Abs(velocity)));
}
else {
duration = DEFAULT_ESCAPE_ANIMATION_DURATION;
}
return duration;
}
Float SwipeHelper::DeterminePos(
/* [in] */ IView* animView,
/* [in] */ Float velocity)
{
Float newPos = 0;
Float x;
if (velocity < 0 || (velocity == 0 && (animView->GetTranslationX(&x), x < 0))
// if we use the Menu to dismiss an item in landscape, animate up
|| (velocity == 0 && (animView->GetTranslationX(&x), x == 0) && mSwipeDirection == Y)) {
newPos = -GetSize(animView);
}
else {
newPos = GetSize(animView);
}
return newPos;
}
void SwipeHelper::SnapChild(
/* [in] */ IView* view,
/* [in] */ Float velocity)
{
AutoPtr<IView> animView;
mCallback->GetChildContentView(view, (IView**)&animView);
Boolean canAnimViewBeDismissed;
mCallback->CanChildBeDismissed(view, &canAnimViewBeDismissed);
AutoPtr<IObjectAnimator> anim = CreateTranslationAnimation(animView, 0);
Int32 duration = SNAP_ANIM_LEN;
AutoPtr<IAnimator> a = IAnimator::Probe(anim);
a->SetDuration(duration);
AutoPtr<IAnimatorUpdateListener> updateListener = new SnapAnimatorUpdateListener(this, canAnimViewBeDismissed, animView);
IValueAnimator::Probe(anim)->AddUpdateListener(updateListener);
AutoPtr<IAnimatorListener> snapListener = new SnapAnimatorListenerAdapter(this, animView);
a->AddListener(snapListener);
a->Start();
}
Boolean SwipeHelper::OnTouchEvent(
/* [in] */ IMotionEvent* ev)
{
if (!mDragging || mProtected) {
return FALSE;
}
mVelocityTracker->AddMovement(ev);
Int32 action;
ev->GetAction(&action);
switch (action) {
case IMotionEvent::ACTION_OUTSIDE:
case IMotionEvent::ACTION_MOVE:
if (mCurrView != NULL) {
Float x, y;
ev->GetX(&x);
ev->GetY(&y);
Float deltaX = x - mInitialTouchPosX;
Float deltaY = Elastos::Core::Math::Abs(y - mInitialTouchPosY);
// If the user has gone vertical and not gone horizontalish AT
// LEAST minBeforeLock, switch to scroll. Otherwise, cancel
// the swipe.
if (!mDragging && deltaY > MIN_VERT && (Elastos::Core::Math::Abs(deltaX)) < MIN_LOCK
&& deltaY > (FACTOR * Elastos::Core::Math::Abs(deltaX))) {
mCallback->OnScroll();
return FALSE;
}
Float minDistance = MIN_SWIPE;
if (Elastos::Core::Math::Abs(deltaX) < minDistance) {
// Don't start the drag until at least X distance has
// occurred.
return TRUE;
}
// don't let items that can't be dismissed be dragged more
// than maxScrollDistance
Boolean canChildBeDismissed;
if (CONSTRAIN_SWIPE &&
(mCallback->CanChildBeDismissed(mCurrView, &canChildBeDismissed), !canChildBeDismissed)) {
Float size = GetSize(mCurrAnimView);
Float maxScrollDistance = 0.15f * size;
if (Elastos::Core::Math::Abs(deltaX) >= size) {
deltaX = deltaX > 0 ? maxScrollDistance : -maxScrollDistance;
}
else {
deltaX = maxScrollDistance
* (Float) Elastos::Core::Math::Sin((deltaX / size) * (Elastos::Core::Math::PI / 2));
}
}
SetTranslation(mCurrAnimView, deltaX);
if (FADE_OUT_DURING_SWIPE && mCanCurrViewBeDimissed) {
mCurrAnimView->SetAlpha(GetAlphaForOffset(mCurrAnimView));
}
AutoPtr<IView> view;
mCallback->GetChildContentView(mCurrView, (IView**)&view);
InvalidateGlobalRegion(view);
}
break;
case IMotionEvent::ACTION_UP:
case IMotionEvent::ACTION_CANCEL:
if (mCurrView != NULL) {
Float maxVelocity = MAX_DISMISS_VELOCITY * mDensityScale;
mVelocityTracker->ComputeCurrentVelocity(1000 /* px/sec */, maxVelocity);
Float escapeVelocity = SWIPE_ESCAPE_VELOCITY * mDensityScale;
Float velocity = GetVelocity(mVelocityTracker);
Float perpendicularVelocity = GetPerpendicularVelocity(mVelocityTracker);
// Decide whether to dismiss the current view
// Tweak constants below as required to prevent erroneous
// swipe/dismiss
Float x;
mCurrAnimView->GetTranslationX(&x);
Float translation = Elastos::Core::Math::Abs(x);
Float currAnimViewSize = GetSize(mCurrAnimView);
// Long swipe = translation of {@link #mChildSwipedFarEnoughFactor} * width
Boolean childSwipedFarEnough = DISMISS_IF_SWIPED_FAR_ENOUGH
&& translation > mChildSwipedFarEnoughFactor * currAnimViewSize;
// Fast swipe = > escapeVelocity and translation of
// {@link #mChildSwipedFastEnoughFactor} * width
Boolean childSwipedFastEnough = (Elastos::Core::Math::Abs(velocity) > escapeVelocity)
&& (Elastos::Core::Math::Abs(velocity) > Elastos::Core::Math::Abs(perpendicularVelocity))
&& (velocity > 0) == ((mCurrAnimView->GetTranslationX(&x), x > 0))
&& translation > mChildSwipedFastEnoughFactor * currAnimViewSize;
if (LOG_SWIPE_DISMISS_VELOCITY) {
Logger::V(TAG, "Swipe/Dismiss: %f/%f/%f, x: %f/%f", velocity, escapeVelocity,
perpendicularVelocity, translation, currAnimViewSize);
}
Boolean canChildBeDismissed;
mCallback->CanChildBeDismissed(mCurrView, &canChildBeDismissed);
Boolean dismissChild = canChildBeDismissed && (childSwipedFastEnough || childSwipedFarEnough);
if (dismissChild) {
DismissChild(mCurrView, childSwipedFastEnough ? velocity : 0.0f);
}
else {
SnapChild(mCurrView, velocity);
}
}
break;
}
return TRUE;
}
void SwipeHelper::SetSwipeable(
/* [in] */ IView* view,
/* [in] */ Boolean swipeable)
{
view->SetTag(IS_SWIPEABLE_TAG, swipeable ? (IObject*)IS_SWIPEABLE.Get() : NULL);
}
Boolean SwipeHelper::IsSwipeable(
/* [in] */ IView* view)
{
AutoPtr<IInterface> tag;
view->GetTag(IS_SWIPEABLE_TAG, (IInterface**)&tag);
return Object::Equals(tag, IS_SWIPEABLE);
}
} // List
} // Dialer
} // Droid
} // Elastos
| 37.230769 | 125 | 0.612034 | [
"object"
] |
496773f2e810b227ee3f9d4814ace735c594fe09 | 1,115 | cc | C++ | src/var_slices.cc | yuntaolu/jittor | 80135d4ef525561a687015e0d27f6570e0dfaca0 | [
"Apache-2.0"
] | 1 | 2021-02-10T16:30:05.000Z | 2021-02-10T16:30:05.000Z | src/var_slices.cc | hexieshenghuo/jittor | 5b8d2fe13c549921c977d96a73acf7a246186022 | [
"Apache-2.0"
] | null | null | null | src/var_slices.cc | hexieshenghuo/jittor | 5b8d2fe13c549921c977d96a73acf7a246186022 | [
"Apache-2.0"
] | null | null | null | // ***************************************************************
// Copyright (c) 2021 Jittor. All Rights Reserved.
// Maintainers: Dun Liang <randonlang@gmail.com>.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include "var_slices.h"
#include "var.h"
namespace jittor {
std::ostream& operator<<(std::ostream& os, const VarSlices& vs) {
os << '[';
for (int i=0; i<vs.n; i++)
os << vs.slices[i] << ",";
return os << ']';
}
std::ostream& operator<<(std::ostream& os, const VarSlice& s) {
if (s.is_var()) return os << s.var->dtype() << s.var->shape;
if (s.is_ellipsis()) return os << "...";
if (s.is_slice()) return os << s.slice;
if (s.is_int()) return os << s.i;
return os << "-";
}
std::ostream& operator<<(std::ostream& os, const Slice& s) {
if (!(s.mask & 1)) os << s.start;
os << ':';
if (!(s.mask & 2)) os << s.stop;
os << ':';
if (!(s.mask & 4)) os << s.step;
return os;
}
} // jittor
| 30.135135 | 66 | 0.495964 | [
"shape"
] |
496860ccfa50ce87a0f1d083a19f8fd3745af400 | 4,301 | cc | C++ | chrome/browser/ui/views/autofill/new_credit_card_bubble_views.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2017-03-21T23:19:25.000Z | 2019-02-03T05:32:47.000Z | chrome/browser/ui/views/autofill/new_credit_card_bubble_views.cc | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/autofill/new_credit_card_bubble_views.cc | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-07-31T19:09:52.000Z | 2019-01-04T18:48:50.000Z | // 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 "chrome/browser/ui/views/autofill/new_credit_card_bubble_views.h"
#include "chrome/browser/ui/autofill/new_credit_card_bubble_controller.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "ui/gfx/insets.h"
#include "ui/gfx/size.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/link.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace autofill {
namespace {
// Get the view this bubble will be anchored to via |controller|.
views::View* GetAnchor(NewCreditCardBubbleController* controller) {
Browser* browser = chrome::FindTabbedBrowser(controller->profile(), false,
chrome::GetActiveDesktop());
if (!browser)
return NULL;
BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
return browser_view->GetToolbarView()->app_menu();
}
} // namespace
NewCreditCardBubbleViews::~NewCreditCardBubbleViews() {
controller_->OnBubbleDestroyed();
}
void NewCreditCardBubbleViews::Show() {
// TODO(dbeam): investigate why this steals focus from the web contents.
views::BubbleDelegateView::CreateBubble(this)->Show();
// This bubble doesn't render correctly on Windows without calling
// |SizeToContents()|. This must be called after showing the widget.
SizeToContents();
}
void NewCreditCardBubbleViews::Hide() {
GetWidget()->Close();
}
gfx::Size NewCreditCardBubbleViews::GetPreferredSize() {
return gfx::Size(
NewCreditCardBubbleView::kContentsWidth,
GetHeightForWidth(NewCreditCardBubbleView::kContentsWidth));
}
void NewCreditCardBubbleViews::Init() {
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical, 0, 0,
views::kRelatedControlVerticalSpacing));
views::View* card_container = new views::View();
card_container->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 10));
views::View* card_desc_view = new views::View();
card_desc_view->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 10));
views::ImageView* card_icon = new views::ImageView();
const CreditCardDescription& card_desc = controller_->CardDescription();
card_icon->SetImage(card_desc.icon.AsImageSkia());
card_desc_view->AddChildView(card_icon);
views::Label* card_name = new views::Label(card_desc.name);
card_name->SetHorizontalAlignment(gfx::ALIGN_LEFT);
card_desc_view->AddChildView(card_name);
card_container->AddChildView(card_desc_view);
views::Label* desc = new views::Label(card_desc.description);
desc->SetHorizontalAlignment(gfx::ALIGN_LEFT);
desc->SetMultiLine(true);
card_container->AddChildView(desc);
AddChildView(card_container);
views::Link* link = new views::Link(controller_->LinkText());
link->SetHorizontalAlignment(gfx::ALIGN_LEFT);
link->set_listener(this);
AddChildView(link);
}
base::string16 NewCreditCardBubbleViews::GetWindowTitle() const {
return controller_->TitleText();
}
void NewCreditCardBubbleViews::LinkClicked(views::Link* source,
int event_flags) {
controller_->OnLinkClicked();
}
// static
base::WeakPtr<NewCreditCardBubbleView> NewCreditCardBubbleView::Create(
NewCreditCardBubbleController* controller) {
NewCreditCardBubbleViews* bubble = new NewCreditCardBubbleViews(controller);
return bubble->weak_ptr_factory_.GetWeakPtr();
}
NewCreditCardBubbleViews::NewCreditCardBubbleViews(
NewCreditCardBubbleController* controller)
: BubbleDelegateView(GetAnchor(controller), views::BubbleBorder::TOP_RIGHT),
controller_(controller),
weak_ptr_factory_(this) {
gfx::Insets insets = views::BubbleFrameView::GetTitleInsets();
set_margins(gfx::Insets(0, insets.left(), insets.top(), insets.left()));
}
} // namespace autofill
| 35.254098 | 80 | 0.741455 | [
"render"
] |
4974c6160465ddb15cc8c63ea5f5c416f0729f28 | 51,557 | cpp | C++ | source/compression/brhashmap.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/compression/brhashmap.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/compression/brhashmap.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
HashMap template for mapping a key to data
Inspired by an implementation found in gameswf by Thatcher Ulrich
<tu@tulrich.com>
Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brhashmap.h"
#include "brsdbmhash.h"
#include "brdjb2hash.h"
#include "brglobalmemorymanager.h"
#include "brstringfunctions.h"
#include "brstring.h"
/*! ************************************
\brief SDBM (Service Data Base Management) hash callback for HashMapShared
Invoke the SDBM (Service Data Base Management) hashing algorithm on the contents of a class
using the default seed value.
\param pData Pointer to a data chunk to hash
\param uDataSize Size of the data chunk in bytes
\return 32 bit wide hash of the class
\sa SDBMHashCaseFunctor(), HashMapShared or SDBMHash()
***************************************/
uintptr_t BURGER_API Burger::SDBMHashFunctor(const void *pData,uintptr_t uDataSize)
{
return SDBMHash(pData,uDataSize);
}
/*! ************************************
\brief Case insensitive SDBM (Service Data Base Management) hash callback for HashMapShared
Invoke the SDBM (Service Data Base Management) hashing algorithm on the contents of a class
using the default seed value and convert all upper case characters into lower case.
\param pData Pointer to a data chunk to hash
\param uDataSize Size of the data chunk in bytes
\return 32 bit wide hash of the class
\sa SDBMHashFunctor(), HashMapShared or SDBMHashCase()
***************************************/
uintptr_t BURGER_API Burger::SDBMHashCaseFunctor(const void *pData,uintptr_t uDataSize)
{
return SDBMHashCase(pData,uDataSize);
}
/*! ************************************
\brief DJB2 Additive hash callback for HashMapShared
Invoke the DJB2 Additive hashing algorithm on the contents of a class
using the default seed value.
\param pData Pointer to a data chunk to hash
\param uDataSize Size of the data chunk in bytes
\return 32 bit wide hash of the class
\sa DJB2HashAddCaseFunctor(), HashMapShared or DJB2HashAdd()
***************************************/
uintptr_t BURGER_API Burger::DJB2HashAddFunctor(const void *pData,uintptr_t uDataSize)
{
return DJB2HashAdd(pData,uDataSize);
}
/*! ************************************
\brief Case insensitive DJB2 Additive hash callback for HashMapShared
Invoke the DJB2 Additive hashing algorithm on the contents of a class
using the default seed value and convert all upper case characters into lower case.
\param pData Pointer to a data chunk to hash
\param uDataSize Size of the data chunk in bytes
\return 32 bit wide hash of the class
\sa DJB2HashAddFunctor(), HashMapShared or DJB2HashAddCase()
***************************************/
uintptr_t BURGER_API Burger::DJB2HashAddCaseFunctor(const void *pData,uintptr_t uDataSize)
{
return DJB2HashAddCase(pData,uDataSize);
}
/*! ************************************
\brief DJB2 Exclusive Or hash callback for HashMapShared
Invoke the DJB2 Exclusive Or hashing algorithm on the contents of a class
using the default seed value.
\param pData Pointer to a data chunk to hash
\param uDataSize Size of the data chunk in bytes
\return 32 bit wide hash of the class
\sa DJB2HashXorCaseFunctor(), HashMapShared or DJB2HashXor()
***************************************/
uintptr_t BURGER_API Burger::DJB2HashXorFunctor(const void *pData,uintptr_t uDataSize)
{
return DJB2HashXor(pData,uDataSize);
}
/*! ************************************
\brief DJB2 Exclusive Or hash callback for HashMapShared
Invoke the DJB2 Exclusive Or hashing algorithm on the contents of a class
using the default seed value.
\param pData Pointer to a data chunk to hash
\param uDataSize Size of the data chunk in bytes
\return 32 bit wide hash of the class
\sa DJB2HashXorFunctor(), HashMapShared or DJB2HashXorCase()
***************************************/
uintptr_t BURGER_API Burger::DJB2HashXorCaseFunctor(const void *pData,uintptr_t uDataSize)
{
return DJB2HashXorCase(pData,uDataSize);
}
/*! ************************************
\brief DJB2 Exclusive Or hash callback for HashMapString
Invoke the DJB2 Exclusive Or hashing algorithm on the contents of
a \ref String class using the default seed value.
\param pData Pointer to a \ref String to hash
\param uDataSize Size of the data chunk in bytes (Not used)
\return 32 bit wide hash of the class
\sa DJB2StringHashXorCaseFunctor(), HashMapString or DJB2HashXor()
***************************************/
uintptr_t BURGER_API Burger::DJB2StringHashXorFunctor(const void *pData,uintptr_t /* uDataSize */)
{
return DJB2HashXor(static_cast<const String *>(pData)->GetPtr(),static_cast<const String *>(pData)->GetLength());
}
/*! ************************************
\brief Case insensitive DJB2 Exclusive Or hash callback for HashMapStringCase
Invoke the case insensitive DJB2 Exclusive Or hashing algorithm on the contents of
a \ref String class using the default seed value.
\param pData Pointer to a \ref String to hash with case insensitivity
\param uDataSize Size of the data chunk in bytes (Not used)
\return 32 bit wide hash of the class
\sa DJB2StringHashXorFunctor(), HashMapStringCase or DJB2HashXorCase()
***************************************/
uintptr_t BURGER_API Burger::DJB2StringHashXorCaseFunctor(const void *pData,uintptr_t /*uDataSize */)
{
return DJB2HashXorCase(static_cast<const String *>(pData)->GetPtr(),static_cast<const String *>(pData)->GetLength());
}
/*! ************************************
\class Burger::HashMapShared::Entry
\brief Base data entry for HashMap
This is the base class for each data entry
used by the HashMap / HashMapShared hash
manager. These entries are used for managing
the linked list for multiple hash items
The derived class will append the key / value
pairs to this class.
An entry is considered initialized if the hash
value is not \ref INVALID_HASH
An entry is considered "dormant", that is, part
of a linked list, yet must be skipped when
the entry is not \ref EMPTY_RECORD and the hash is
\ref INVALID_HASH.
This is to support erasing entries during the
use of an iterator without complicating the iterator
code.
\sa HashMap, HashMap::Entry or HashMapShared
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::Entry::IsEmpty(void) const
\brief Is the Entry an empty record.
If the Entry is not used at all, it will return \ref TRUE.
Otherwise, it returns \ref FALSE. It's possible the entry
is invalid, however it can be still part of a linked list.
\return \ref TRUE if this Entry is not used at all.
\sa IsEndOfChain(void) const or IsHashInvalid(void) const
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::Entry::IsEndOfChain(void) const
\brief Is the Entry the last Entry of a linked list.
If the Entry is the last link of the linked list, it will return \ref TRUE.
Otherwise, it returns \ref FALSE.
\return \ref TRUE if this Entry is the last entry of a valid linked list.
\sa IsEmpty(void) const or IsHashInvalid(void) const
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::Entry::IsHashInvalid(void) const
\brief Is the Entry uninitialized?
If the Entry doesn't contain valid data, it will return \ref TRUE.
Otherwise, it returns \ref FALSE.
\return \ref TRUE if this Entry not initialized.
\sa IsEndOfChain(void) const or IsEmpty(void) const
***************************************/
/*! ************************************
\class Burger::HashMapShared
\brief Base class for HashMap
HashMap is a template class to quickly look up data chunks using
a key value. To cut down on compile time and
reduce code bloat, a majority of the runtime
it contained in this class and the template
creates a front end with only the minimum amount
of code to support the class.
From a users point of view, HashMap is a 100% template
based class, from a code point of view, HashMap
is a dispatcher to HashMapShared.
\note This class is not intended to be directly used,
it's intended to be derived to allow its functionality
to be shared with different HashMap template types
\sa HashMap
***************************************/
/*! ************************************
\fn Burger::HashMapShared::HashMapShared(uintptr_t uEntrySize,uintptr_t uFirstSize,uintptr_t uSecondOffset,
TestProc pTestFunction,EntryConstructProc pEntryConstructFunction,
EntryCopyProc pEntryCopyFunction,EntryInvalidateProc pEntryInvalidationFunction,HashProc pHashFunction)
\brief Default constructor
A HashMapShared needs values to properly support the derived class, notably
the byte size of each data entry and a function to perform
the hash calculation. This constructor is called by derived classes,
it's not meant to be used by an application.
\param uEntrySize Size of each Entry in bytes
\param uFirstSize Size in bytes for the key class, usually sizeof(T)
\param uSecondOffset Offset in bytes for the data value in Entry
\param pTestFunction Function that returns \ref TRUE if the keys match
\param pEntryConstructFunction Function that invokes the default constructors for the Entry
\param pEntryCopyFunction Function that invokes the copy constructors for the Entry
\param pEntryInvalidationFunction Function that invokes the destructors for the Entry
\param pHashFunction Function that hashes the key value
\sa HashMap
***************************************/
/*! ************************************
\brief Locate an entry in the hash
Hash the key and use the hash to look up the data in
the entry table. If found, an entry index is returned. If not,
\ref INVALID_INDEX is returned.
\param pKey Pointer to the key value
\return A valid index or \ref INVALID_INDEX if not found.
\sa FindFirst(void) const or ComputeHash(const void*) const
***************************************/
uintptr_t BURGER_API Burger::HashMapShared::FindIndex(const void *pKey) const
{
// Assume failure
uintptr_t uResult = INVALID_INDEX;
const Entry *pEntry = static_cast<const Entry *>(m_pEntries);
// No data in the hash?
if (pEntry) {
// Get the hash to look up
uintptr_t uHash = ComputeHash(pKey);
// Mask to the size of the array
uintptr_t uIndex = uHash & m_uSizeMask;
// Get the initial index
pEntry = reinterpret_cast<const Entry *>(reinterpret_cast<const uint8_t *>(pEntry) + (uIndex*m_uEntrySize));
if (!pEntry->IsEmpty()) {
// Is this entry occupied by a ROOT linked list entry?
if (pEntry->IsHashInvalid() || ((pEntry->m_uHashValue & m_uSizeMask) == uIndex)) {
// Since this is a valid root entry, begin the scan!
for (;;) {
// Test the hash first, then the key to ensure there isn't a hash collision
// Note, pEntry+1 is used because the key is the data that
// follows the base Entry class.
if ((pEntry->m_uHashValue == uHash) && m_pTestFunction(pEntry+1,pKey)) {
// Found it.
uResult = uIndex;
break;
}
// Keys are equal, but hash differs!
// Can occur if the == operator allows equality for incomplete data
BURGER_ASSERT(pEntry->IsHashInvalid() || !m_pTestFunction(pEntry+1,pKey));
// Keep looking through the chain.
uIndex = pEntry->m_uNextInChain;
if (uIndex == END_OF_CHAIN) {
break; // No more data! Exit with failure
}
BURGER_ASSERT(uIndex <= m_uSizeMask);
pEntry = GetEntry(uIndex);
BURGER_ASSERT((!pEntry->IsEmpty() || pEntry->IsHashInvalid()) &&
((pEntry->m_uHashValue & m_uSizeMask) == (uHash & m_uSizeMask)));
}
}
}
}
return uResult;
}
/*! ************************************
\brief Create a buffer to store all of the data entries
This helper function assumes that there is no data already
allocated by the HashMapShared class. It will allocate a
buffer and then mark each entry as empty and initialize
all of the internal variables.
\param uCount Number of entries to allocate (Must be a power of 2)
\param uEntrySize Size in bytes of each Entry record
\sa Clear(void)
***************************************/
void BURGER_API Burger::HashMapShared::CreateBuffer(uintptr_t uCount,uintptr_t uEntrySize)
{
Entry *pEntry = static_cast<Entry*>(Alloc(uEntrySize * uCount));
BURGER_ASSERT(pEntry);
// Update the pointer
m_pEntries = pEntry;
m_uEntrySize = uEntrySize;
m_uSizeMask = uCount-1;
m_uEntryCount = 0;
// Initialize the base Entry records
// However, do NOT initialize the derived data
do {
pEntry->m_uNextInChain = EMPTY_RECORD;
pEntry->m_uHashValue = INVALID_HASH;
pEntry = reinterpret_cast<Entry*>(reinterpret_cast<uint8_t *>(pEntry)+uEntrySize);
} while (--uCount);
}
/*! ************************************
\brief Function to change the size of the buffer
Dynamically resize the buffer and retain all data within
by reentering every entry into the newly resized hash table
If uNewSize is zero, delete all data in the hash
\note If the data buffer is already a comparable size, no action will be performed.
\param uNewSize Number of entries to allocate (Will be rounded up to a power of 2)
\sa CreateBuffer(uintptr_t,uintptr_t) or Clear(void)
***************************************/
void BURGER_API Burger::HashMapShared::CreateHashBuffer(uintptr_t uNewSize)
{
// Handle data purging
if (!uNewSize) {
Clear();
} else {
// Force new_size to be a power of two.
uintptr_t uRoundedUp = PowerOf2(uNewSize);
BURGER_ASSERT(uRoundedUp >= uNewSize);
uNewSize = uRoundedUp;
// Assume a minimum size to give the hash a good chance
// to avoid collisions
if (uNewSize < 16) {
uNewSize = 16;
}
// Already the same size?
if (!m_uSizeMask || (uNewSize != (m_uSizeMask + 1))) {
// Detach the current array of data
Entry *pOldEntries = static_cast<Entry *>(m_pEntries);
uintptr_t uCount = m_uSizeMask+1;
uintptr_t uEntrySize = m_uEntrySize;
// Create the new buffer
CreateBuffer(uNewSize,uEntrySize);
// Copy the previous data to the new hash
if (pOldEntries) {
Entry *pTempEntry = pOldEntries;
do {
// Every entry with a valid hash will be added to the new hash
if (!pTempEntry->IsHashInvalid()) {
Add(pTempEntry+1,reinterpret_cast<const uint8_t *>(pTempEntry)+m_uSecondOffset);
// Call a disposal function?
if (m_pEntryInvalidationFunction) {
m_pEntryInvalidationFunction(pTempEntry);
}
}
pTempEntry = reinterpret_cast<Entry*>(reinterpret_cast<uint8_t *>(pTempEntry)+uEntrySize);
} while (--uCount);
// Delete our old data buffer.
Free(pOldEntries);
}
}
}
}
/*! ************************************
\brief Erase a specific hash entry
Assuming a data entry is initialized, this function
will remove it from the linked list and call the
invalidation function.
If the entry being erased is part of a linked list chain,
it will be destroyed, but the linked list will be retained.
This is to allow iterators to continue to function without
error.
\param uIndex Index into the hash for the entry to erase.
\sa Erase(const void *)
***************************************/
void BURGER_API Burger::HashMapShared::Erase(uintptr_t uIndex)
{
BURGER_ASSERT(m_pEntries && (uIndex <= m_uSizeMask));
Entry *pEntryToErase = GetEntry(uIndex);
// Get the root index entry
uintptr_t uTestIndex = pEntryToErase->m_uHashValue & m_uSizeMask;
// Not a root?
if (uIndex != uTestIndex) {
// Iterate from the root until the desired entry
// is found so it can be spliced in
Entry* pEntry = GetEntry(uTestIndex);
while (pEntry->m_uNextInChain != uIndex) {
BURGER_ASSERT(!pEntry->IsEndOfChain());
pEntry = GetEntry(pEntry->m_uNextInChain);
}
// pEntry has the parent entry, unlink from the chain
pEntry->m_uNextInChain = pEntryToErase->m_uNextInChain;
// This entry is totally free!
pEntryToErase->m_uNextInChain = EMPTY_RECORD;
} else if (pEntryToErase->IsEndOfChain()) {
// We are the head of a single entry chain
pEntryToErase->m_uNextInChain = EMPTY_RECORD;
}
// In the final case, it's a root object with a link.
// Do an in place disposal and retain the link, since
// moving entries is not supported in the hash
// else {}
// Dispose of the derived data
if (m_pEntryInvalidationFunction) {
m_pEntryInvalidationFunction(pEntryToErase);
}
// Mark as uninitialized
pEntryToErase->m_uHashValue = INVALID_HASH;
// Reduce the valid count
--m_uEntryCount;
}
/*! ************************************
\brief Erase a hash entry by searching for it
Search the hash for a key and dispose of the Entry if
one is found.
\param pKey Pointer to the key value
\sa Erase(uintptr_t)
***************************************/
void BURGER_API Burger::HashMapShared::Erase(const void *pKey)
{
// Find the entry
uintptr_t uIndex = FindIndex(pKey);
// Valid?
if (uIndex!=INVALID_INDEX) {
// Dispose of it
Erase(uIndex);
}
}
/*! ************************************
\brief Find the index for the first valid entry
Iterate over the hash data and find the index to the first
entry that contains valid data. This is used by HashMap::begin() and
HashMap::begin() const
\return Index to the first valid entry or \ref INVALID_INDEX if no entries are valid.
\sa FindIndex(const void *) const
***************************************/
uintptr_t BURGER_API Burger::HashMapShared::FindFirst(void) const
{
// Assume failure
uintptr_t uIndex = INVALID_INDEX;
Entry *pEntry = static_cast<Entry *>(m_pEntries);
if (pEntry) {
// Scan until we hit the first valid entry.
uintptr_t uCount = m_uSizeMask+1;
uintptr_t uEntrySize = m_uEntrySize;
do {
if (!pEntry->IsHashInvalid()) {
uIndex = (m_uSizeMask+1)-uCount;
break;
}
pEntry = reinterpret_cast<Entry*>(reinterpret_cast<uint8_t *>(pEntry)+uEntrySize);
} while (--uCount);
}
return uIndex;
}
/*! ************************************
\brief Calculate the hash for a key
Given a pointer to a key and the length in bytes of the key,
call the hash algorithm using the stored function pointer. If
it the very rare case that a hash matches \ref INVALID_HASH,
it will be changed to \ref INVALID_HASH -0x8000 to "validate"
the hash.
\param pKey Pointer to the key value
\return A valid hash value for the key
\sa HashProc
***************************************/
uintptr_t BURGER_API Burger::HashMapShared::ComputeHash(const void*pKey) const
{
// Create the hash
uintptr_t uHash = m_pHashFunction(pKey,m_uFirstSize);
// Collision with special hash?
if (uHash == INVALID_HASH) {
// Likely, this value will work in the rare case
uHash = (INVALID_HASH-0x8000);
}
return uHash;
}
/*! ************************************
\brief Replace the contents of this hash with a copy of another
Clear out all the data in this hash and copy the entries
from another hash into this one.
\param pInput Pointer to the HashMap to copy data from
\sa Clear() and EntryInvalidateProc
***************************************/
void BURGER_API Burger::HashMapShared::Copy(const HashMapShared *pInput)
{
Clear();
m_uFirstSize = pInput->m_uFirstSize;
m_uSecondOffset = pInput->m_uSecondOffset;
m_pHashFunction = pInput->m_pHashFunction;
m_pTestFunction = pInput->m_pTestFunction;
m_pEntryConstructFunction = pInput->m_pEntryConstructFunction;
m_pEntryCopyFunction = pInput->m_pEntryCopyFunction;
m_pEntryInvalidationFunction = pInput->m_pEntryInvalidationFunction;
uintptr_t uEntrySize = pInput->m_uEntrySize;
m_uEntrySize = uEntrySize;
uintptr_t uCount = pInput->m_uEntryCount;
if (uCount) {
HashMapShared::CreateHashBuffer((uCount * 3) / 2);
const Entry *pEntry = static_cast<const Entry *>(pInput->m_pEntries);
uCount = pInput->m_uSizeMask+1;
do {
// Every entry with a valid hash will be added to the new hash
if (!pEntry->IsHashInvalid()) {
Add(pEntry+1,reinterpret_cast<const uint8_t *>(pEntry)+m_uSecondOffset);
}
pEntry = reinterpret_cast<const Entry*>(reinterpret_cast<const uint8_t *>(pEntry)+uEntrySize);
} while (--uCount);
}
}
/*! ************************************
\brief Add a new key data pair into the hash
Expand the size of the hash if needed, and then insert
a new key data pair into the hash. This function should now
be called if a key should be replaced if present. Use
the HashMap::Set() function for that.
\param pT Pointer to the key to add
\param pU Pointer to the data to add
\sa HashMap::Set()
***************************************/
void BURGER_API Burger::HashMapShared::Add(const void *pT,const void *pU)
{
BURGER_ASSERT(FindIndex(pT) == INVALID_INDEX);
if (!m_pEntries) {
// Initial creation of table. Make a minimum-sized table.
CreateHashBuffer(16);
} else if ((m_uEntryCount * 3) > ((m_uSizeMask + 1) * 2)) {
// Table is more than 2/3rds full. Expand.
CreateHashBuffer((m_uSizeMask + 1) * 2);
}
BURGER_ASSERT(m_pEntries);
++m_uEntryCount;
uintptr_t uHash = ComputeHash(pT);
uintptr_t uIndex = uHash & m_uSizeMask;
Entry *pEntry = GetEntry(uIndex);
// If the key is empty, this is simplicity itself
if (pEntry->IsEmpty()) {
// Put the new entry in.
pEntry->m_uNextInChain = END_OF_CHAIN;
pEntry->m_uHashValue = uHash;
m_pEntryCopyFunction(pEntry,pT,pU);
} else if (pEntry->IsHashInvalid()) {
// This is a "Marker" entry. Invalid data, but a valid link.
// Make the data valid and retain the link
//pEntry->m_uNextInChain = pEntry->m_uNextInChain;
pEntry->m_uHashValue = uHash;
m_pEntryCopyFunction(pEntry,pT,pU);
} else {
// Find a blank spot and link it in
// Only entries with the EMPTY_RECORD index can be used for insertions
uintptr_t uBlankIndex = uIndex;
Entry *pNewEntry;
do {
uBlankIndex = (uBlankIndex + 1) & m_uSizeMask;
pNewEntry = GetEntry(uBlankIndex);
} while (!pNewEntry->IsEmpty());
if ((pEntry->m_uHashValue & m_uSizeMask) == uIndex) {
// Copy the parent entry into the newly found entry
// to "insert" the new hash entry to the top
// of the linked list.
pNewEntry->m_uHashValue = pEntry->m_uHashValue;
pNewEntry->m_uNextInChain = pEntry->m_uNextInChain;
m_pEntryCopyFunction(pNewEntry,pEntry+1,reinterpret_cast<const uint8_t *>(pEntry)+m_uSecondOffset);
// Make the new entry the new parent
pEntry->m_uNextInChain = uBlankIndex;
} else {
// Heavy sigh, the parent doesn't event belong here.
// Move it into this empty slot and find out
// which entry is pointing to this one (Very rare case)
// Start with the parent of the collided entry
uintptr_t uCollisionIndex = pEntry->m_uHashValue & m_uSizeMask;
for (;;) {
Entry *pCollisionEntry = GetEntry(uCollisionIndex);
// Found the parent?
if (pCollisionEntry->m_uNextInChain == uIndex) {
// Copy the collided entry into the new entry
pNewEntry->m_uHashValue = pEntry->m_uHashValue;
pNewEntry->m_uNextInChain = pEntry->m_uNextInChain;
m_pEntryCopyFunction(pNewEntry,pEntry+1,reinterpret_cast<const uint8_t *>(pEntry)+m_uSecondOffset);
// Fix up the linked list
pCollisionEntry->m_uNextInChain = uBlankIndex;
break;
}
uCollisionIndex = pCollisionEntry->m_uNextInChain;
BURGER_ASSERT(uCollisionIndex <= m_uSizeMask);
}
pEntry->m_uNextInChain = END_OF_CHAIN;
}
// Set up the new starting entry
pEntry->m_uHashValue = uHash;
if (m_pEntryInvalidationFunction) {
m_pEntryInvalidationFunction(pEntry);
}
m_pEntryCopyFunction(pEntry,pT,pU);
}
}
/*! ************************************
\brief Get the pointer to the data index by a key
Given a pointer to a key, scan for it using FindIndex(const void *)
and if found, return the pointer to the data pointed by
the Entry pointer added with m_uSecondOffset.
\param pT Pointer to the key look for
\return \ref NULL if the record wasn't found or a pointer to
the data attached to the key.
\sa HashMap::GetData(const T&) const
***************************************/
const void * Burger::HashMapShared::GetData(const void *pT) const
{
uintptr_t uIndex = FindIndex(pT);
const void *pResult = NULL;
if (uIndex!=INVALID_INDEX) {
pResult = reinterpret_cast<const uint8_t *>(GetEntry(uIndex))+m_uSecondOffset;
}
return pResult;
}
/*! ************************************
\fn Burger::HashMapShared::Entry *Burger::HashMapShared::GetEntry(uintptr_t uIndex)
\brief Return the pointer to an Entry
Since the Entry class is of a runtime decided size, this function
manually performs the indexing into the array.
\param uIndex Valid index into the array.
\return Pointer to a specific Entry into the array.
\sa GetEntry(uintptr_t) const
***************************************/
/*! ************************************
\fn const Burger::HashMapShared::Entry *Burger::HashMapShared::GetEntry(uintptr_t uIndex) const
\brief Return a constant pointer to an Entry
Since the Entry class is of a runtime decided size, this function
manually performs the indexing into the array.
\param uIndex Valid index into the array.
\return Constant pointer to a specific Entry into the array.
\sa GetEntry(uintptr_t)
***************************************/
/*! ************************************
\class Burger::HashMapShared::const_iterator
\brief STL compatible iterator base class
This class is the base class for iteration over a hash
table using standard STL algorithms. It's not meant to be
used by applications. A HashMap will derive from this
class to inherit the common functionality and then provide
access to the specialized key and data pairs.
\sa HashMap::const_iterator or HashMap::iterator
***************************************/
/*! ************************************
\fn Burger::HashMapShared::const_iterator::const_iterator(const HashMapShared *pParent,uintptr_t uIndex)
\brief Base class constructor
This class is initialized with a pointer to the parent class and
an index to start iteration. If uIndex is set to \ref INVALID_INDEX, it's
assumed to be an HashMap::end() marker.
\param pParent Pointer to the parent class
\param uIndex Index to start iteration from (Must an index to a valid entry or \ref INVALID_INDEX)
\sa HashMap::const_iterator or HashMap::iterator
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::const_iterator::IsEnd(void) const
\brief Is the iterator at the end of the array?
\return \ref TRUE if the iterator is not pointing to a valid entry.
\sa GetPtr(void) const
***************************************/
/*! ************************************
\fn const Burger::HashMapShared::Entry *Burger::HashMapShared::const_iterator::GetPtr(void) const
\brief Get the Entry pointer
Given an iterator that's pointing to a valid object, return a pointer
to the Entry. This function returns the base class which the derived HashMap
will up cast to the true data type.
\return Pointer to the specific entry the iterator is pointing to.
\sa IsEnd()
***************************************/
/*! ************************************
\fn const Burger::HashMapShared::Entry &Burger::HashMapShared::const_iterator::operator*() const
\brief Get the Entry reference
Given an iterator that's pointing to a valid object, return a reference
to the Entry. This function returns the base class which the derived HashMap
will up cast to the true data type.
\return Reference to the specific entry the iterator is pointing to.
\sa GetPtr() const
***************************************/
/*! ************************************
\fn const Burger::HashMapShared::Entry *Burger::HashMapShared::const_iterator::operator->() const
\brief Get the Entry pointer
Given an iterator that's pointing to a valid object, return a pointer
to the Entry. This function returns the base class which the derived HashMap
will up cast to the true data type.
\return Pointer to the specific entry the iterator is pointing to.
\sa GetPtr() const
***************************************/
/*! ************************************
\brief Increment the iterator to the next valid entry
Step the iterator to the next valid entry in the hash
table. If the end of the table is reached, the index will be set
to \ref INVALID_INDEX
\sa HashMap::begin() const or HashMap::end() const
***************************************/
void BURGER_API Burger::HashMapShared::const_iterator::operator++()
{
uintptr_t uIndex = m_uIndex;
if (uIndex!=INVALID_INDEX) {
const HashMapShared *pParent = m_pParent;
BURGER_ASSERT(pParent);
uintptr_t uEndMask = pParent->GetSizeMask();
// Get the starting pointer
const Entry *pEntry = pParent->GetEntry(uIndex);
uintptr_t uEntrySize = pParent->GetEntrySize();
do {
// End of the array?
if (++uIndex > uEndMask) {
// Force to invalid
uIndex = INVALID_INDEX;
break;
}
// Increment the pointer
pEntry = reinterpret_cast<const Entry*>(reinterpret_cast<const uint8_t *>(pEntry)+uEntrySize);
// Exit if valid
} while (pEntry->IsHashInvalid());
// Update the iterator
m_uIndex = uIndex;
}
}
/*! ************************************
\fn uint_t Burger::HashMapShared::const_iterator::operator==(const const_iterator& it) const
\brief Test for equality between iterators
If two iterators point to the same index, return \ref TRUE
\param it Reference to iterator to test against this one
\return \ref TRUE if the iterators match, \ref FALSE if not.
\sa operator!=(const const_iterator&) const
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::const_iterator::operator!=(const const_iterator& it) const
\brief Test for inequality between iterators
If two iterators point different indexes, return \ref TRUE
\param it Reference to iterator to test against this one
\return \ref TRUE if the iterators do not match, \ref FALSE if they do.
\sa operator==(const const_iterator&) const
***************************************/
/*! ************************************
\brief Purge all allocated data
Iterate over all of the initialized entries and destroy
any entry that has valid data using a function that
will handle the derived class disposal.
If the invalidation function is \ref NULL, the main buffer
is discarded immediately.
\sa CreateBuffer(uintptr_t,uintptr_t)
***************************************/
void BURGER_API Burger::HashMapShared::Clear(void)
{
if (m_pEntryInvalidationFunction) {
Entry *pEntry = static_cast<Entry *>(m_pEntries);
if (pEntry) {
uintptr_t uCount = m_uSizeMask+1;
uintptr_t uEntrySize = m_uEntrySize;
do {
if (!pEntry->IsHashInvalid()) {
m_pEntryInvalidationFunction(pEntry);
}
pEntry = reinterpret_cast<Entry*>(reinterpret_cast<uint8_t *>(pEntry)+uEntrySize);
} while (--uCount);
}
}
Free(m_pEntries);
m_pEntries = NULL;
m_uSizeMask = 0;
m_uEntryCount = 0;
}
/*! ************************************
\brief Sets a specific capacity to the hash
A non-destructive function to resize the hash to
a specific size.
\param uNewSize Number of entries for the new hash buffer
\sa SetCapacity(uintptr_t)
***************************************/
void BURGER_API Burger::HashMapShared::Resize(uintptr_t uNewSize)
{
if (uNewSize < m_uEntryCount) {
uNewSize = m_uEntryCount;
}
CreateHashBuffer(uNewSize);
}
/*! ************************************
\brief Sets a comfortable capacity of the hash
A non-destructive function to resize the hash to a size
that has padding for new entries to be added with minimal
memory allocations.
\param uNewSize Minimum number of entries to size the cache
\sa Resize(uintptr_t)
***************************************/
void BURGER_API Burger::HashMapShared::SetCapacity(uintptr_t uNewSize)
{
// Don't delete entries!
if (uNewSize < m_uEntryCount) {
uNewSize = m_uEntryCount;
}
// Mul by 1.5
CreateHashBuffer((uNewSize * 3U) >> 1U);
}
/*! ************************************
\fn uintptr_t Burger::HashMapShared::GetEntryCount(void) const
\brief Returns the number of valid entries in the hash
\return The number of valid entries in the hash.
\sa IsEmpty(void) const or GetSizeMask(void) const
***************************************/
/*! ************************************
\fn uintptr_t Burger::HashMapShared::GetSizeMask(void) const
\brief Returns the mask used by the hash for rounding.
When the hash buffer is created, it's set to a size that's
a power of two and that value is stored as (size-1) to
use as a wrap around mask. To get the hash size, take this
value and add one to it.
\code
HashMap<int,int> foo;
DoStuffToAddEntriesToTheHash(&foo);
printf("Maximum entries in the hash %u\n",foo.GetSizeMask()+1);
\endcode
\return Zero if hash hasn't been used, or the entry count - 1
\sa GetEntryCount(void) const or IsEmpty(void) const
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::IsEmpty(void) const
\brief Returns \ref TRUE if the hash is empty
\return \ref TRUE if the hash is empty, \ref FALSE if not
\sa GetEntryCount(void) const or GetSizeMask(void) const
***************************************/
/*! ************************************
\fn uint_t Burger::HashMapShared::GetEntrySize(void) const
\brief Returns the size of each entry in bytes
\return The number of bytes each Entry occupies in the hash array.
\sa GetEntryCount(void) const or GetSizeMask(void) const
***************************************/
/*! ************************************
\class Burger::HashMap
\brief Key / data pair hash for quick lookup and retrieval
HashMap is a template class to quickly look up data chunks using
a key value. To cut down on compile time and
reduce code bloat, a majority of the runtime
it contained in a parent class HashMapShared and the template
creates a front end with only the minimum amount
of code to support the class.
From a users point of view, HashMap is a 100% template
based class, from a code point of view, HashMap
is a dispatcher to HashMapShared.
\sa HashMapShared
***************************************/
/*! ************************************
\class Burger::HashMap::Entry
\brief Key / data pair for HashMap
Entry records have some extra data for connecting
to the hash and also data for a copy of the key
and data. This is declared in the template
so it adjusts depending on the data needed
\sa HashMapShared
***************************************/
/*! ************************************
\class Burger::HashMap::const_iterator
\brief STL compatible constant iterator for HashMap
To allow STL functionality, this class allow iteration
over the entire hash.
\note The const_iterator can only be created by a call to HashMap::begin() or
HashMap::end()
\sa iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\fn Burger::HashMap::const_iterator::const_iterator(const HashMapShared *pParent,uintptr_t uIndex)
\brief Standard constructor
This private function is used to create the const_iterator for returning to
applications.
\note The const_iterator can only be created by a call to HashMap::begin() or
HashMap::end()
\sa iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\fn const Burger::HashMap::Entry & Burger::HashMap::const_iterator::operator*() const
\brief Get a reference to the Entry indexed by the const_iterator
\note Function will fail if the iterator is at the end of the array.
\return Reference to the Entry record pointed by the const_iterator
\sa iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\fn const Burger::HashMap::Entry *Burger::HashMap::const_iterator::operator->() const
\brief Get a pointer to the Entry indexed by the const_iterator
\note Function will fail if the iterator is at the end of the array.
\return Pointer to the Entry record pointed by the const_iterator
\sa iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\class Burger::HashMap::iterator
\brief STL compatible iterator for HashMap
To allow STL functionality, this class allow iteration
over the entire hash.
\note The iterator can only be created by a call to HashMap::begin() or
HashMap::end()
\sa const_iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\fn Burger::HashMap::Entry & Burger::HashMap::iterator::operator*() const
\brief Get a reference to the Entry indexed by the iterator
\note Function will fail if the iterator is at the end of the array.
\return Reference to the Entry record pointed by the iterator
\sa const_iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\fn Burger::HashMap::Entry *Burger::HashMap::iterator::operator->() const
\brief Get a pointer to the Entry indexed by the const_iterator
\note Function will fail if the iterator is at the end of the array.
\return Pointer to the Entry record pointed by the iterator
\sa const_iterator and HashMapShared::const_iterator
***************************************/
/*! ************************************
\fn void Burger::HashMap::Construct(HashMapShared::Entry *pEntry)
\brief Default constructor for an Entry
Callback function to default initialize the template Entry structure
\param pEntry Pointer to an uninitialized Entry record
\sa EntryConstructProc. Copy(HashMapShared::Entry *,const void *,const void *) or Invalidate(HashMapShared::Entry *)
***************************************/
/*! ************************************
\fn void Burger::HashMap::Copy(HashMapShared::Entry *pEntry,const void *pT,const void *pU)
\brief Default copy constructor for an Entry
Callback function to copy construct an uninitialized template Entry structure
\param pEntry Pointer to an uninitialized Entry record
\param pT Pointer to a key record to copy
\param pU Pointer to a data record to copy
\sa EntryCopyProc, Construct(HashMapShared::Entry *) or Invalidate(HashMapShared::Entry *)
***************************************/
/*! ************************************
\fn void Burger::HashMap::Invalidate(HashMapShared::Entry *pEntry)
\brief Destructor for an Entry
Callback function to destroy an initialized template Entry structure
\param pEntry Pointer to an initialized Entry record
\sa EntryInvalidateProc, Copy(HashMapShared::Entry *,const void *,const void *) or Construct(HashMapShared::Entry *)
***************************************/
/*! ************************************
\fn uint_t Burger::HashMap::EqualsTest(const void *pA,const void *pB)
\brief Key comparison function.
Callback function to test two keys and return \ref TRUE if equal.
\param pA Pointer to the first key to test
\param pB Pointer to the second key to test
\sa TestProc
***************************************/
/*! ************************************
\fn Burger::HashMap::HashMap(HashProc pHashFunction)
\brief Default constructor
Create an empty hash and select a hash algorithm.
\param pHashFunction Pointer to a hash function
\sa HashMap(HashProc,uintptr_t) or HashMap(const HashMap &)
***************************************/
/*! ************************************
\fn Burger::HashMap::HashMap(HashProc pHashFunction,TestProc pTestProc)
\brief Default constructor with hash and equality function declarations
Create an empty hash and select a hash algorithm and
an Entry test function.
\param pHashFunction Pointer to a hash function
\param pTestProc Pointer to an Entry equality test
\sa HashMap(HashProc,uintptr_t) or HashMap(const HashMap &)
***************************************/
/*! ************************************
\fn Burger::HashMap::HashMap(HashProc pHashFunction,uintptr_t uDefault)
\brief Default constructor with a set number of preallocated entries
Construct the hash with a minimum number of entries so they don't
need to be allocated as data is inserted into the hash during runtime.
\param pHashFunction Pointer to a hash function
\param uDefault Number of entries to allocate (Will be rounded up to a power of 2)
\sa HashMap(HashProc) or HashMap(const HashMap &)
***************************************/
/*! ************************************
\fn Burger::HashMap::HashMap(const HashMap &rHashMap)
\brief Copy constructor
Make a copy of a hash.
\param rHashMap Reference to a hash to copy
\sa HashMap(HashProc) or HashMap(HashProc,uintptr_t)
***************************************/
/*! ************************************
\fn Burger::HashMap::~HashMap()
\brief Destructor
Dispose of all data in the hash
\sa Clear(), HashMap(HashProc), HashMap(HashProc,uintptr_t) or HashMap(const HashMap &)
***************************************/
/*! ************************************
\fn Burger::HashMap &Burger::HashMap::operator=(const HashMap &rHashMap)
\brief Copy operator
Delete all of the data and make a copy of another hash and
place it in this class.
\param rHashMap Reference to a hash to copy
\return *this
\sa HashMap(const HashMap &rHashMap)
***************************************/
/*! ************************************
\fn U & Burger::HashMap::operator[](const T &rKey)
\brief Index operator
Using a key, look up the item in the hash and if present,
return a reference to the data. If the entry didn't exist,
create it with a default constructor for the data.
\param rKey Reference to the key to look up
\return Reference to the data found or created.
\sa GetData(const T&)const or GetData(const T&,U*) const
***************************************/
/*! ************************************
\fn void Burger::HashMap::Set(const T &rKey,const U &rValue)
\brief Set a key/data pair in the hash
Using a key, look up the item in the hash and if present,
replace the data with the a copy of the data passed. If the entry didn't exist,
create it with a copy of the passed data.
\param rKey Reference to the key to look up
\param rValue Reference to the data to copy
\return Reference to the data found or created.
\sa GetData(const T&)const or GetData(const T&,U*) const
***************************************/
/*! ************************************
\fn void Burger::HashMap::add(const T &rKey,const U &rValue)
\brief Add a key/data pair to the hash
Using a key / data pair, add the entry into the hash. This function
is a helper, it will fail if the key was already present in the hash.
\param rKey Reference to the key to look up
\param rValue Reference to the data to copy
\return Reference to the data found or created.
\sa Set(const T&,const U&)
***************************************/
/*! ************************************
\fn U* Burger::HashMap::GetData(const T &rKey)
\brief Get data by looking it up by a hash key
Scan the hash for data indexed by the key. If found, return a
pointer to the data or \ref NULL if the data wasn't found.
\param rKey Reference to the key to look up
\return \ref NULL if the key wasn't in the hash or a valid pointer to the data if so.
\sa GetData(const T &,U *) const
***************************************/
/*! ************************************
\fn const U* Burger::HashMap::GetData(const T &rKey) const
\brief Get data by looking it up by a hash key
Scan the hash for data indexed by the key. If found, return a
pointer to the data or \ref NULL if the data wasn't found.
\param rKey Reference to the key to look up
\return \ref NULL if the key wasn't in the hash or a valid pointer to the data if so.
\sa GetData(const T &,U *) const
***************************************/
/*! ************************************
\fn uint_t Burger::HashMap::GetData(const T &rKey,U *pOutput) const
\brief Get a copy of data by looking it up by a hash key
Scan the hash for data indexed by the key. If found, copy the
data and return \ref TRUE. Return \ref FALSE on failure.
\param rKey Reference to the key to look up
\param pOutput Pointer to a buffer to receive a copy of the data
\return \ref TRUE if the data was found, \ref FALSE if not.
\sa GetData(const T &) const
***************************************/
/*! ************************************
\fn Burger::HashMap::iterator Burger::HashMap::begin(void)
\brief Set an iterator to the start of the hash
Return an STL compatible iterator pointing to the first entry
in the hash table. The iterator can be set to end() if there
is no data in the hash.
\return iterator preset to the beginning of the hash
\sa end(void)
***************************************/
/*! ************************************
\fn Burger::HashMap::const_iterator Burger::HashMap::begin(void) const
\brief Set an const_iterator to the start of the hash
Return an STL compatible const_iterator pointing to the first entry
in the hash table. The const_iterator can be set to end() const if there
is no data in the hash.
\return const_iterator preset to the beginning of the hash
\sa end(void) const
***************************************/
/*! ************************************
\fn Burger::HashMap::iterator Burger::HashMap::end(void)
\brief Set an iterator to the end of the hash
Return an STL compatible iterator pointing to the terminating entry
in the hash table. This is the value to test to determine
if the end of the iterations has been reached.
\return iterator preset to the terminator of the hash
\sa begin(void)
***************************************/
/*! ************************************
\fn Burger::HashMap::const_iterator Burger::HashMap::end(void) const
\brief Set an const_iterator to the end of the hash
Return an STL compatible const_iterator pointing to the first entry
in the hash table. This is the value to test to determine
if the end of the iterations has been reached.
\return const_iterator preset to the terminator of the hash
\sa begin(void) const
***************************************/
/*! ************************************
\fn Burger::HashMap::iterator Burger::HashMap::find(const T &rKey)
\brief Set an iterator to a specific entry in the hash
Return an STL compatible iterator pointing to the requested entry
in the hash table or end() in case the entry was not found.
\param rKey Reference to the key to look up
\return iterator preset to the terminator of the hash or the requested entry
\sa find(const T&rKey) const
***************************************/
/*! ************************************
\fn Burger::HashMap::const_iterator Burger::HashMap::find(const T &rKey) const
\brief Set an iterator to a specific entry in the hash
Return an STL compatible const_iterator pointing to the requested entry
in the hash table or end() const in case the entry was not found.
\param rKey Reference to the key to look up
\return const_iterator preset to the terminator of the hash or the requested entry
\sa find(const T&rKey)
***************************************/
/*! ************************************
\fn void Burger::HashMap::erase(const iterator &it)
\brief Erase a specific entry in the hash indexed by an iterator
Using an iterator to look up an entry in the hash, delete the entry.
\param it Reference to the iterator pointing to the entry to delete
\sa erase(const T&)
***************************************/
/*! ************************************
\fn void Burger::HashMap::erase(const T&rKey)
\brief Erase a specific entry in the hash
Using a key to look up an entry in the hash, if it's found, delete it.
\param rKey Reference to the key to look up
\sa erase(const iterator &it)
***************************************/
/*! ************************************
\class Burger::HashMapString
\brief String key / data pair hash for quick lookup and retrieval
HashMapString is a template class to quickly look up
data chunks using a String as a key value.
Unlike the standard HashMap which applies a hash to the class
contents, this HashMap will use the string contained
in the String class as the key data.
From a users point of view, HashMapString is a 100% template
based class, from a code point of view, HashMapString
is a dispatcher to HashMapShared.
\note String hashing is case sensitive. For case insensitive
hashing, use HashMapStringCase
\sa DJB2StringHashXorFunctor, HashMapShared, HashMap or HashMapStringCase
***************************************/
/*! ************************************
\fn Burger::HashMapString::HashMapString()
\brief Default constructor.
Create an empty hash and select to a case sensitive String hash algorithm.
\note String hashing is case sensitive. For case insensitive
hashing, use HashMapStringCase
\sa DJB2StringHashXorFunctor or HashMapStringCase
***************************************/
/*! ************************************
\brief Case insensitive string test for HashMapStringCase
This internal function performs a case insensitive string comparison
between two String classes.
\param pA Pointer to the first String to test
\param pB Pointer to the second String to test
\return \ref TRUE if the strings match, \ref FALSE if not.
\sa HashMapStringCase
***************************************/
uint_t BURGER_API Burger::HashMapStringCaseTest(const void *pA,const void *pB)
{
return StringCaseCompare(static_cast<const String *>(pA)->GetPtr(),static_cast<const String *>(pB)->GetPtr())==0;
}
/*! ************************************
\class Burger::HashMapStringCase
\brief String key / data pair hash for quick lookup and retrieval
HashMapStringCase is a template class to quickly look up
data chunks using a String as a key value.
Unlike the standard HashMap which applies a hash to the class
contents, this HashMap will use the string contained
in the String class as the key data.
From a users point of view, HashMapStringCase is a 100% template
based class, from a code point of view, HashMapStringCase
is a dispatcher to HashMapShared.
\note String hashing is case insensitive. For case sensitive
hashing, use HashMapString
\sa DJB2StringHashXorCaseFunctor, HashMapStringCaseTest(const void *,const void *),
HashMapShared, HashMap or HashMapString
***************************************/
/*! ************************************
\fn Burger::HashMapStringCase::HashMapStringCase()
\brief Default constructor.
Create an empty hash and select to a case insensitive String hash algorithm.
\note String hashing is case insensitive. For case sensitive
hashing, use HashMapString
\sa DJB2StringHashXorCaseFunctor or HashMapString
***************************************/
| 31.533333 | 118 | 0.654499 | [
"object"
] |
4976f1e575cae288fec403bb6fd2ceabdbefb5d0 | 1,730 | cpp | C++ | src/base/ThreadPool.cpp | larrystd/streamingserver | b3467964dc6478d5b2de71f8595de2d60b68ed49 | [
"Apache-2.0"
] | null | null | null | src/base/ThreadPool.cpp | larrystd/streamingserver | b3467964dc6478d5b2de71f8595de2d60b68ed49 | [
"Apache-2.0"
] | null | null | null | src/base/ThreadPool.cpp | larrystd/streamingserver | b3467964dc6478d5b2de71f8595de2d60b68ed49 | [
"Apache-2.0"
] | null | null | null | #include "base/ThreadPool.h"
#include "base/Logging.h"
#include "base/New.h"
ThreadPool* ThreadPool::createNew(int num)
{
//return new ThreadPool(num);
return New<ThreadPool>::allocate(num);
}
ThreadPool::ThreadPool(int num) :
mThreads(num),
mQuit(false)
{
mMutex = Mutex::createNew();
mCondition = Condition::createNew();
createThreads();
}
ThreadPool::~ThreadPool()
{
cancelThreads();
//delete mMutex;
//delete mCondition;
Delete::release(mMutex);
Delete::release(mCondition);
}
void ThreadPool::addTask(ThreadPool::Task& task)
{
MutexLockGuard mutexLockGuard(mMutex);
mTaskQueue.push(task);
mCondition->signal();
}
void ThreadPool::handleTask()
{
while(mQuit != true)
{
Task task;
{
MutexLockGuard mutexLockGuard(mMutex);
if(mTaskQueue.empty())
mCondition->wait(mMutex);
if(mQuit == true)
break;
if(mTaskQueue.empty())
continue;
task = mTaskQueue.front();
mTaskQueue.pop();
}
task.handle();
}
}
void ThreadPool::createThreads()
{
MutexLockGuard mutexLockGuard(mMutex);
for(std::vector<MThread>::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
(*it).start(this);
}
void ThreadPool::cancelThreads()
{
MutexLockGuard mutexLockGuard(mMutex);
mQuit = true;
mCondition->broadcast();
for(std::vector<MThread>::iterator it = mThreads.begin(); it != mThreads.end(); ++it)
(*it).join();
mThreads.clear();
}
void ThreadPool::MThread::run(void* arg)
{
ThreadPool* threadPool = (ThreadPool*)arg;
threadPool->handleTask();
} | 20.116279 | 89 | 0.600578 | [
"vector"
] |
497a4fccb64f3272024c0b82eb4fc181d9d5487d | 34,050 | hpp | C++ | include/graph/directed_adjacency_vector.hpp | pratzl/graph | 4bb50e92ab77bb1e672285340acf221ae5ae75af | [
"BSL-1.0"
] | 12 | 2020-01-09T22:15:00.000Z | 2022-03-15T21:36:21.000Z | include/graph/directed_adjacency_vector.hpp | pratzl/graph | 4bb50e92ab77bb1e672285340acf221ae5ae75af | [
"BSL-1.0"
] | 2 | 2021-05-05T16:34:29.000Z | 2021-09-19T20:14:58.000Z | include/graph/directed_adjacency_vector.hpp | pratzl/graph | 4bb50e92ab77bb1e672285340acf221ae5ae75af | [
"BSL-1.0"
] | 3 | 2020-01-30T21:41:55.000Z | 2021-05-05T10:48:04.000Z | //
// Author: J. Phillip Ratzloff
//
#include "graph_utility.hpp"
#include "ordered_pair.hpp"
#include <vector>
#include <cassert>
#ifndef DIRECTED_ADJ_ARRAY_HPP
# define DIRECTED_ADJ_ARRAY_HPP
namespace std {
///-------------------------------------------------------------------------------------
/// directed_adjacency_vector forward declarations
///
/// All vertices are kept in a single random-access container with an index for the
/// first outward edge in the edges container.
///
/// All edges are kept in a single random-access container in the graph. Outgoing edges
/// for a vertex are stored contiguously. Edges for vertex v must come after the
/// previous vertex's edges. An edge holds the index for its outward vertex in the
/// vertices container, plus any user-defined values.
///
/// A vector is used as the default container though any random-access container with
/// <T,A> (type, allocator) template parameters can be used.
///
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_vertex;
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_edge;
// clang-format off
template <typename VV = empty_value,
typename EV = empty_value,
typename GV = empty_value,
integral KeyT = uint32_t,
template <typename V, typename A> class VContainer = vector,
template <typename E, typename A> class EContainer = vector,
typename Alloc = allocator<char>>
class directed_adjacency_vector;
// clang-format on
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_const_vertex_vertex_iterator;
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_vertex_vertex_iterator;
///-------------------------------------------------------------------------------------
/// dav_edge
///
/// @tparam VV Vertex Value type. default = empty_value.
/// @tparam EV Edge Value type. default = empty_value.
/// @tparam GV Graph Value type. default = empty_value.
/// @tparam KeyT The type used for the vertex key, and index into edge container
/// @tparam A Allocator. default = std::allocator
///
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_edge : public conditional_t<graph_value_needs_wrap<EV>::value, graph_value_wrapper<EV>, EV> {
public:
using base_type = conditional_t<graph_value_needs_wrap<EV>::value, graph_value_wrapper<EV>, EV>;
using graph_type = directed_adjacency_vector<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_type = dav_vertex<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_value_type = VV;
using vertex_key_type = KeyT;
using vertex_index_type = KeyT;
using vertex_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<vertex_type>;
using vertex_set = VContainer<vertex_type, vertex_allocator_type>;
using vertex_iterator = typename vertex_set::iterator;
using const_vertex_iterator = typename vertex_set::const_iterator;
using vertex_size_type = typename vertex_set::size_type;
using vertex_difference_type = typename vertex_set::difference_type;
using edge_type = dav_edge<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using edge_value_type = EV;
using edge_key_type = ordered_pair<vertex_key_type, vertex_key_type>; // <from,to>
using edge_index_type = KeyT;
using edge_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<edge_type>;
using edge_set = EContainer<edge_type, edge_allocator_type>;
public:
dav_edge() = default;
dav_edge(const dav_edge&) = default;
dav_edge(dav_edge&&) noexcept = default;
~dav_edge() noexcept = default;
dav_edge& operator=(dav_edge&) = default;
dav_edge& operator=(dav_edge&&) = default;
dav_edge(vertex_key_type source_vertex_key, vertex_key_type target_vertex_key);
dav_edge(vertex_key_type source_vertex_key, vertex_key_type target_vertex_key, const edge_value_type&);
dav_edge(vertex_key_type source_vertex_key, vertex_key_type target_vertex_key, edge_value_type&&);
vertex_iterator source_vertex(graph_type&);
const_vertex_iterator source_vertex(const graph_type&) const;
vertex_key_type source_vertex_key() const noexcept;
vertex_iterator target_vertex(graph_type&);
const_vertex_iterator target_vertex(const graph_type&) const;
vertex_key_type target_vertex_key() const noexcept;
edge_key_type edge_key() const noexcept;
private:
vertex_key_type source_vertex_;
vertex_key_type target_vertex_;
};
///-------------------------------------------------------------------------------------
/// dav_vertex
///
/// @tparam VV Vertex Value type. default = empty_value.
/// @tparam EV Edge Value type. default = empty_value.
/// @tparam GV Graph Value type. default = empty_value.
/// @tparam KeyT The type used for the vertex key, and index into edge container
/// @tparam A Allocator. default = std::allocator
///
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_vertex : public conditional_t<graph_value_needs_wrap<VV>::value, graph_value_wrapper<VV>, VV> {
public:
using graph_type = directed_adjacency_vector<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using base_type = conditional_t<graph_value_needs_wrap<VV>::value, graph_value_wrapper<VV>, VV>;
using vertex_type = dav_vertex<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_value_type = VV;
using vertex_key_type = KeyT;
using vertex_index_type = KeyT;
using vertex_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<vertex_type>;
using vertex_set = VContainer<vertex_type, vertex_allocator_type>;
using vertex_iterator = typename vertex_set::iterator;
using const_vertex_iterator = typename vertex_set::const_iterator;
using vertex_size_type = typename vertex_set::size_type;
using vertex_difference_type = typename vertex_set::difference_type;
using edge_type = dav_edge<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using edge_value_type = EV;
using edge_key_type = ordered_pair<vertex_key_type, vertex_key_type>; // <from,to>
using edge_index_type = KeyT;
using edge_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<edge_type>;
using edge_set = EContainer<edge_type, edge_allocator_type>;
using edge_range = edge_set&;
using const_edge_range = const edge_set&;
using edge_iterator = ranges::iterator_t<edge_range>;
using const_edge_iterator = ranges::iterator_t<const_edge_range>;
using edge_size_type = ranges::range_size_t<edge_range>;
using edge_difference_type = ranges::range_difference_t<edge_range>;
public:
dav_vertex() noexcept = default;
dav_vertex(const dav_vertex&) = default;
dav_vertex(dav_vertex&&) noexcept = default;
~dav_vertex() noexcept = default;
dav_vertex& operator=(const dav_vertex&) = default;
dav_vertex& operator=(dav_vertex&&) = default;
dav_vertex(vertex_set& vertices, vertex_index_type index);
dav_vertex(vertex_set& vertices, vertex_index_type index, const vertex_value_type&);
dav_vertex(vertex_set& vertices, vertex_index_type index, vertex_value_type&&);
void set_edge_begin(graph_type&, edge_iterator);
void set_edge_begin(edge_index_type);
edge_index_type edge_begin_index() const;
private:
edge_index_type first_edge_ = numeric_limits<edge_index_type>::max();
};
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_const_vertex_vertex_iterator {
public:
using this_t = dav_const_vertex_vertex_iterator<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using graph_type = directed_adjacency_vector<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_type = dav_vertex<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_value_type = VV;
using vertex_key_type = KeyT;
using vertex_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<vertex_type>;
using vertex_set = VContainer<vertex_type, vertex_allocator_type>;
using vertex_iterator = typename vertex_set::iterator;
using const_vertex_iterator = typename vertex_set::const_iterator;
using edge_type = dav_edge<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using edge_value_type = typename edge_type::edge_value_type;
using edge_key_type = typename edge_type::edge_key_type; // <from,to>
using edge_set = typename edge_type::edge_set;
using vertex_edge_iterator = typename edge_set::iterator;
using const_vertex_edge_iterator = typename edge_set::const_iterator;
using iterator_category = random_access_iterator_tag;
using value_type = vertex_type;
using size_type = typename edge_set::size_type;
using difference_type = typename edge_set::difference_type;
using pointer = const value_type*;
using reference = const value_type&;
public:
constexpr dav_const_vertex_vertex_iterator(graph_type& g, vertex_edge_iterator uv);
constexpr dav_const_vertex_vertex_iterator() = default;
constexpr dav_const_vertex_vertex_iterator(const dav_const_vertex_vertex_iterator&) = default;
constexpr dav_const_vertex_vertex_iterator(dav_const_vertex_vertex_iterator&&) = default;
~dav_const_vertex_vertex_iterator() = default;
constexpr dav_const_vertex_vertex_iterator& operator=(const dav_const_vertex_vertex_iterator&) = default;
constexpr dav_const_vertex_vertex_iterator& operator=(dav_const_vertex_vertex_iterator&&) = default;
public:
constexpr const_vertex_iterator target_vertex(graph_type const&) const;
constexpr vertex_key_type target_vertex_key() const;
constexpr reference operator*() const noexcept;
constexpr pointer operator->() const noexcept;
constexpr dav_const_vertex_vertex_iterator& operator++() noexcept;
constexpr dav_const_vertex_vertex_iterator operator++(int) noexcept;
constexpr dav_const_vertex_vertex_iterator& operator+=(const difference_type distance) noexcept;
constexpr dav_const_vertex_vertex_iterator operator+(const difference_type distance) const noexcept;
constexpr dav_const_vertex_vertex_iterator& operator--() noexcept;
constexpr dav_const_vertex_vertex_iterator operator--(int) noexcept;
constexpr dav_const_vertex_vertex_iterator& operator-=(const difference_type distance) noexcept;
constexpr dav_const_vertex_vertex_iterator operator-(const difference_type distance) const noexcept;
reference operator[](const difference_type distance) const noexcept { return *uv_[distance].target_vertex(*g_); }
constexpr bool operator==(const dav_const_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator!=(const dav_const_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator>(const dav_const_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator<=(const dav_const_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator<(const dav_const_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator>=(const dav_const_vertex_vertex_iterator& rhs) const noexcept;
friend void swap(dav_const_vertex_vertex_iterator& lhs, dav_const_vertex_vertex_iterator& rhs) {
swap(lhs.g_, rhs.g_);
swap(lhs.uv_, rhs.uv_);
}
protected:
graph_type* g_ = nullptr;
vertex_edge_iterator uv_;
};
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A>
class VContainer,
template <typename E, typename A>
class EContainer,
typename Alloc>
class dav_vertex_vertex_iterator
: public dav_const_vertex_vertex_iterator<VV, EV, GV, KeyT, VContainer, EContainer, Alloc> {
public:
using this_t = dav_vertex_vertex_iterator<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using base_t = dav_const_vertex_vertex_iterator<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using graph_type = typename base_t::graph_type;
using vertex_type = typename base_t::vertex_type;
using vertex_edge_iterator = typename base_t::vertex_edge_iterator;
using vertex_iterator = typename base_t::vertex_iterator;
using edge_type = typename base_t::edge_type;
using iterator_category = typename base_t::iterator_category;
using value_type = typename base_t::value_type;
using size_type = typename base_t::size_type;
using difference_type = typename base_t::difference_type;
using pointer = value_type*;
using reference = value_type&;
protected:
using base_t::g_;
using base_t::uv_;
public:
constexpr dav_vertex_vertex_iterator(graph_type& g, vertex_edge_iterator uv);
constexpr dav_vertex_vertex_iterator() = default;
constexpr dav_vertex_vertex_iterator(const dav_vertex_vertex_iterator&) = default;
constexpr dav_vertex_vertex_iterator(dav_vertex_vertex_iterator&&) = default;
~dav_vertex_vertex_iterator() = default;
constexpr dav_vertex_vertex_iterator& operator=(const dav_vertex_vertex_iterator&) = default;
constexpr dav_vertex_vertex_iterator& operator=(dav_vertex_vertex_iterator&&) = default;
public:
constexpr vertex_iterator target_vertex(graph_type&);
constexpr reference operator*() const;
constexpr pointer operator->() const;
constexpr dav_vertex_vertex_iterator& operator++();
constexpr dav_vertex_vertex_iterator operator++(int);
constexpr dav_vertex_vertex_iterator& operator+=(const difference_type distance) noexcept;
constexpr dav_vertex_vertex_iterator operator+(const difference_type distance) const noexcept;
constexpr dav_vertex_vertex_iterator& operator--() noexcept;
constexpr dav_vertex_vertex_iterator operator--(int) noexcept;
constexpr dav_vertex_vertex_iterator& operator-=(const difference_type distance) noexcept;
constexpr dav_vertex_vertex_iterator operator-(const difference_type distance) const noexcept;
reference operator[](const difference_type distance) const noexcept;
constexpr bool operator==(const dav_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator!=(const dav_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator>(const dav_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator<=(const dav_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator<(const dav_vertex_vertex_iterator& rhs) const noexcept;
constexpr bool operator>=(const dav_vertex_vertex_iterator& rhs) const noexcept;
friend void swap(dav_vertex_vertex_iterator& lhs, dav_vertex_vertex_iterator& rhs) {
swap(lhs.g_, rhs.g_);
swap(lhs.uv_, rhs.uv_);
}
};
/// A simple semi-mutable graph emphasizing performance and space.
///
/// directed_adjacency_vector is a compressed adjacency array graph with the following characteristics:
/// 1. a forward-only directed graph
/// 2. user-defined value types for vertices, edges and the graph.
/// 3. iterating over vertices occurs in O(V) and over edges in O(E) time.
/// 4. minimum vertex size is sizeof(size_t) when empty_value is used for the value type
/// 5. minimum edge size is sizeof(size_t)*2 when empty_value is used for the value type
/// 6. vertices and edges are stored in separate vectors (2 total).
/// 7. After the graph is constructed, vertices and edges cannot be added or removed.
/// Properties may be modified.
///
/// The time to construct the graph is O(V) + 2*O(E). The edges are scanned twice, the first
/// time to identify the largest vertex index referenced (so the internal vertex container is
/// allocated only once), and the second time to build the internal edges container.
///
/// When constructing the directed_adjacency_vector, vertices are identified by their index in the vertex
/// container passed. Edges refer to their in/out vertices using the vertex index. If more
/// vertices are referred to in the edges container in the constructor, then the internal
/// vertex container will be sized to accomodate the largest vertex index used by the edges.
///
/// constructors accept a variety of containers, depending on the template parameters.
/// vertices accept containers with 2 template parameters, like vector<T,A> and deque<T,A>
/// Different constructors exist to accomoate edges in different container types, also based
/// on the number of template parameters. This accomodates both common std containers and
/// non-std containers.
///
/// Constructors are the only public functions that should be used directly. Use the
/// templatized graph free functions to work with the graph otherwise. While public member functions
/// (besides constructors) may work, there is no guarantee they will work on all implementations.
///
/// @tparam VV Vertex Value type. default = empty_value.
/// @tparam EV Edge Value type. default = empty_value.
/// @tparam GV Graph Value type. default = empty_value.
/// @tparam KeyT The type used for the vertex key, and index into edge container
/// @tparam VContainer<V,A> Random-access container type used to store vertices (V) with allocator (A).
/// @tparam EContainer<E,A> Random-access Container type used to store edges (E) with allocator (A).
/// @tparam Alloc Allocator. default = std::allocator
//
// clang-format off
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A> class VContainer,
template <typename E, typename A> class EContainer,
typename Alloc>
class directed_adjacency_vector
: public conditional_t<graph_value_needs_wrap<GV>::value, graph_value_wrapper<GV>, GV>
// clang-format on
{
public:
using base_type = conditional_t<graph_value_needs_wrap<GV>::value, graph_value_wrapper<GV>, GV>;
using graph_type = directed_adjacency_vector<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using graph_value_type = GV;
using allocator_type = Alloc;
using vertex_type = dav_vertex<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_value_type = VV;
using vertex_key_type = KeyT;
using vertex_index_type = KeyT;
using vertex_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<vertex_type>;
using vertex_set = VContainer<vertex_type, vertex_allocator_type>;
using vertex_range = vertex_set&;
using const_vertex_range = const vertex_set&;
using vertex_iterator = typename vertex_set::iterator;
using const_vertex_iterator = typename vertex_set::const_iterator;
using vertex_size_type = ranges::range_size_t<vertex_range>;
using vertex_difference_type = ranges::range_difference_t<vertex_range>;
using vertex_subrange = decltype(detail::make_subrange(declval<vertex_set&>()));
using edge_type = dav_edge<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using edge_value_type = EV;
using edge_key_type = ordered_pair<vertex_key_type, vertex_key_type>; // <from,to>
using edge_index_type = KeyT;
using edge_allocator_type = typename allocator_traits<Alloc>::template rebind_alloc<edge_type>;
using edge_set = EContainer<edge_type, edge_allocator_type>;
using edge_range = edge_set&;
using const_edge_range = const edge_set&;
using edge_iterator = ranges::iterator_t<edge_range>;
using const_edge_iterator = ranges::iterator_t<const_edge_range>;
using edge_size_type = ranges::range_size_t<edge_range>;
using edge_difference_type = ranges::range_difference_t<edge_range>;
using vertex_outward_size_type = edge_size_type;
using vertex_outward_difference_type = edge_difference_type;
using vertex_outward_edge_range = ranges::subrange<edge_iterator, edge_iterator, ranges::subrange_kind::sized>;
using const_vertex_outward_edge_range =
ranges::subrange<const_edge_iterator, const_edge_iterator, ranges::subrange_kind::sized>;
using vertex_outward_edge_iterator = edge_iterator;
using const_vertex_outward_edge_iterator = const_edge_iterator;
using vertex_outward_vertex_iterator = dav_vertex_vertex_iterator<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using const_vertex_outward_vertex_iterator =
dav_const_vertex_vertex_iterator<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using vertex_outward_vertex_range =
ranges::subrange<vertex_outward_vertex_iterator, vertex_outward_vertex_iterator, ranges::subrange_kind::sized>;
using const_vertex_outward_vertex_range = ranges::subrange<const_vertex_outward_vertex_iterator,
const_vertex_outward_vertex_iterator,
ranges::subrange_kind::sized>;
using vertex_edge_range = vertex_outward_edge_range;
using const_vertex_edge_range = const_vertex_outward_edge_range;
using vertex_edge_iterator = vertex_outward_edge_iterator;
using const_vertex_edge_iterator = const_vertex_outward_edge_iterator;
public:
directed_adjacency_vector() = default;
directed_adjacency_vector(directed_adjacency_vector&& rhs) noexcept = default;
directed_adjacency_vector(const directed_adjacency_vector&) = default;
// clang-format off
directed_adjacency_vector(const allocator_type& alloc);
directed_adjacency_vector(const graph_value_type&,
const allocator_type& alloc = allocator_type());
directed_adjacency_vector(graph_value_type&&,
const allocator_type& alloc = allocator_type());
// clang-format on
// The following constructors will load edges (and vertices) into the graph
//
// The number of vertices is guaranteed to match the highest vertex key in
// the edges. Edges are scanned first to determine the highest number and
// the vertices are resized to match the number.
//
// Accessor functions are used to return the edge_key_type and
// vertex_value_type.
//
// The order visited in the vertices determines their index
// (and key/identity) in the internal vertices container. The edge keys use
// those values and are also expected to be ordered by their first (in)
// vertex key and an exception is thrown if they aren't in
// order. For these reasons, unordered (hash) containers won't work.
//
/// Constructor that takes edge & vertex ranges to create the graph.
///
/// @tparam ERng The edge data range.
/// @tparam EKeyFnc Function object to return edge_key_type of the
/// ERng::value_type.
/// @tparam EValueFnc Function object to return the edge_value_type, or
/// a type that edge_value_type is constructible
/// from. If the return type is void or empty_value the
/// edge_value_type default constructor will be used
/// to initialize the value.
/// @tparam VRng The vertex data range.
/// @tparam VValueFnc Function object to return the vertex_value_type,
/// or a type that vertex_value_type is constructible
/// from. If the return type is void or empty_value the
/// vertex_value_type default constructor will be
/// used to initialize the value.
///
/// @param erng The container of edge data.
/// @param vrng The container of vertex data.
/// @param ekey_fnc The edge key extractor functor:
/// ekey_fnc(ERng::value_type) -> directed_adjacency_vector::edge_key_type
/// @param evalue_fnc The edge value extractor functor:
/// evalue_fnc(ERng::value_type) -> edge_value_t<G>.
/// @param vvalue_fnc The vertex value extractor functor:
/// vvalue_fnc(VRng::value_type) -> vertex_value_t<G>.
/// @param alloc The allocator to use for internal containers for
/// vertices & edges.
///
// clang-format off
template <typename ERng,
typename EKeyFnc,
typename EValueFnc,
typename VRng,
typename VValueFnc>
requires edge_value_extractor<ERng, EKeyFnc, EValueFnc>
&& vertex_value_extractor<VRng, VValueFnc>
directed_adjacency_vector(const ERng& erng,
const VRng& vrng,
const EKeyFnc& ekey_fnc,
const EValueFnc& evalue_fnc,
const VValueFnc& vvalue_fnc,
const GV& gv = GV(),
const Alloc& alloc = Alloc());
// clang-format on
/// Constructor that takes edge & vertex ranges to create the graph.
///
/// @tparam ERng The edge data range.
/// @tparam EKeyFnc Function object to return edge_key_type of the
/// ERng::value_type.
/// @tparam EValueFnc Function object to return the edge_value_type, or
/// a type that edge_value_type is constructible
/// from. If the return type is void or empty_value the
/// edge_value_type default constructor will be used
/// to initialize the value.
///
/// @param erng The container of edge data.
/// @param ekey_fnc The edge key extractor functor:
/// ekey_fnc(ERng::value_type) -> directed_adjacency_vector::edge_key_type
/// @param evalue_fnc The edge value extractor functor:
/// evalue_fnc(ERng::value_type) -> edge_value_t<G>.
/// @param alloc The allocator to use for internal containers for
/// vertices & edges.
///
// clang-format off
template <typename ERng, typename EKeyFnc, typename EValueFnc>
requires edge_value_extractor<ERng, EKeyFnc, EValueFnc>
directed_adjacency_vector(const ERng& rng,
const EKeyFnc& ekey_fnc,
const EValueFnc& evalue_fnc,
const GV& gv = GV(),
const Alloc& alloc = Alloc());
// clang-format on
/// Constructor for easy creation of a graph that takes an initializer
/// list with a tuple with 3 edge elements: source_vertex_key,
/// target_vertex_key and edge_value.
///
/// @param ilist Initializer list of tuples with source_vertex_key,
/// target_vertex_key and the edge value.
/// @param alloc Allocator.
///
// clang-format off
directed_adjacency_vector(
const initializer_list<
tuple<vertex_key_type, vertex_key_type, edge_value_type>>& ilist,
const Alloc& alloc = Alloc());
// clang-format on
/// Constructor for easy creation of a graph that takes an initializer
/// list with a tuple with 2 edge elements.
///
/// @param ilist Initializer list of tuples with source_vertex_key and
/// target_vertex_key.
/// @param alloc Allocator.
///
// clang-format off
directed_adjacency_vector(
const initializer_list<tuple<vertex_key_type, vertex_key_type>>& ilist,
const Alloc& alloc = Alloc());
// clang-format on
~directed_adjacency_vector() = default;
directed_adjacency_vector& operator=(const directed_adjacency_vector&) = default;
directed_adjacency_vector& operator=(directed_adjacency_vector&&) = default;
public:
constexpr vertex_set& vertices();
constexpr const vertex_set& vertices() const;
constexpr vertex_iterator begin();
constexpr const_vertex_iterator begin() const;
constexpr const_vertex_iterator cbegin() const;
constexpr vertex_iterator end();
constexpr const_vertex_iterator end() const;
constexpr const_vertex_iterator cend() const;
constexpr edge_set& edges();
constexpr const edge_set& edges() const;
vertex_iterator find_vertex(vertex_key_type);
const_vertex_iterator find_vertex(vertex_key_type) const;
constexpr vertex_edge_range outward_edges(vertex_iterator u);
constexpr const_vertex_edge_range outward_edges(const_vertex_iterator u) const;
constexpr vertex_outward_vertex_range outward_vertices(vertex_iterator u);
constexpr const_vertex_outward_vertex_range outward_vertices(const_vertex_iterator u) const;
constexpr allocator_type allocator() const;
protected:
void reserve_vertices(vertex_size_type);
void resize_vertices(vertex_size_type);
void resize_vertices(vertex_size_type, const vertex_value_type&);
vertex_iterator create_vertex();
vertex_iterator create_vertex(vertex_value_type&&);
template <class VV2>
vertex_iterator create_vertex(const VV2&); // vertex_value_type must be constructable from VV2
protected:
void reserve_edges(edge_size_type);
edge_iterator create_edge(vertex_key_type, vertex_key_type);
edge_iterator create_edge(vertex_key_type, vertex_key_type, edge_value_type&&);
template <class EV2>
edge_iterator create_edge(vertex_key_type,
vertex_key_type,
const EV2&); // EV2 must be accepted by vertex_value_type constructor
public:
void clear();
void swap(directed_adjacency_vector&);
protected:
vertex_iterator finalize_outward_edges(vertex_subrange);
void throw_unordered_edges() const;
private:
vertex_set vertices_;
edge_set edges_;
allocator_type alloc_;
};
// clang-format off
template <typename VV,
typename EV,
typename GV,
integral KeyT,
template <typename V, typename A> class VContainer,
template <typename E, typename A> class EContainer,
typename Alloc>
struct graph_traits<
directed_adjacency_vector<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>>
// clang-format on
{
using graph_type = directed_adjacency_vector<VV, EV, GV, KeyT, VContainer, EContainer, Alloc>;
using graph_value_type = typename graph_type::graph_value_type;
using allocator_type = typename graph_type::allocator_type;
using vertex_type = typename graph_type::vertex_type;
using vertex_key_type = typename graph_type::vertex_key_type;
using vertex_value_type = typename graph_type::vertex_value_type;
using edge_type = typename graph_type::edge_type;
using edge_key_type = ordered_pair<vertex_key_type, vertex_key_type>;
using edge_value_type = typename graph_type::edge_value_type;
using vertex_range = typename graph_type::vertex_range;
using const_vertex_range = typename graph_type::const_vertex_range;
using edge_range = typename graph_type::edge_range;
using const_edge_range = typename graph_type::const_edge_range;
using vertex_outward_edge_range = typename graph_type::vertex_outward_edge_range;
using const_vertex_outward_edge_range = typename graph_type::const_vertex_outward_edge_range;
using vertex_outward_vertex_range = typename graph_type::vertex_outward_vertex_range;
using const_vertex_outward_vertex_range = typename graph_type::const_vertex_outward_vertex_range;
using vertex_edge_range = vertex_outward_edge_range;
using const_vertex_edge_range = const_vertex_outward_edge_range;
using vertex_vertex_range = vertex_outward_vertex_range;
using const_vertex_vertex_range = const_vertex_outward_vertex_range;
};
} // namespace std
#endif // DIRECTED_ADJ_ARRAY_HPP
#include "detail/directed_adjacency_vector_api.hpp"
#include "detail/directed_adjacency_vector_impl.hpp"
| 45.643432 | 119 | 0.694332 | [
"object",
"vector"
] |
497e073d2d1fe4153157426f4f6fb0b51e0e322c | 1,569 | cpp | C++ | src/splitter.cpp | peppergeist/zigzag | e6e73c5c59ea80a98ec632e176fd5f4b1c1a91b5 | [
"MIT"
] | null | null | null | src/splitter.cpp | peppergeist/zigzag | e6e73c5c59ea80a98ec632e176fd5f4b1c1a91b5 | [
"MIT"
] | null | null | null | src/splitter.cpp | peppergeist/zigzag | e6e73c5c59ea80a98ec632e176fd5f4b1c1a91b5 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <iostream>
#include "input.hpp"
std::vector<std::string> split_text_into_zigzag_rows(input inp)
{
std::vector<std::string> output(inp.height, "");
int row = (inp.reverse ? inp.height - 1 : 0);
bool going_down = !inp.reverse;
for (int i = 0; i < inp.text.size(); ++i)
{
if (inp.text[i] == '\n')
{
inp.text = inp.text.substr(i + 1, std::string::npos);
std::vector<std::string> remaining = split_text_into_zigzag_rows(inp);
output.insert(output.end(), remaining.begin(), remaining.end());
return output;
}
for (int r = 0; r < output.size(); ++r)
{
if (r == row && inp.text[i] != '\t')
{
output[r].push_back(inp.text[i]);
}
else
{
output[r].push_back(' ');
}
}
if (going_down)
{
if (row < inp.height - 1)
{
++row;
}
else
{
if (row > 0)
{
--row;
}
going_down = !going_down;
}
}
else
{
if (row > 0)
{
--row;
}
else
{
if (row < inp.height - 1)
{
++row;
}
going_down = !going_down;
}
}
}
return output;
}
| 22.414286 | 82 | 0.372849 | [
"vector"
] |
21a71f3a503c528d916d61f25dcfde53d9a8fee8 | 3,781 | cpp | C++ | libstark/src/protocols/Fri/common/common.cpp | MukkuMayc/libSTARK | 2f1836a7e8299698f807cc75a3631a4ced540150 | [
"MIT"
] | null | null | null | libstark/src/protocols/Fri/common/common.cpp | MukkuMayc/libSTARK | 2f1836a7e8299698f807cc75a3631a4ced540150 | [
"MIT"
] | null | null | null | libstark/src/protocols/Fri/common/common.cpp | MukkuMayc/libSTARK | 2f1836a7e8299698f807cc75a3631a4ced540150 | [
"MIT"
] | 1 | 2019-12-02T13:27:16.000Z | 2019-12-02T13:27:16.000Z | #include "common.hpp"
#include <algebraLib/SubspacePolynomial.hpp>
#include "serialize_funfunc.hpp"
#include "../../Ali/common_details/serialization_fun.h"
namespace libstark{
namespace Protocols{
namespace Fri{
namespace common{
using std::vector;
using Algebra::FieldElement;
using Algebra::zero;
using Algebra::elementsSet_t;
using Algebra::SubspacePolynomial;
;
vector<FieldElement> getL0Basis(const vector<FieldElement>& BasisL, const bool L0isMSB){
if(L0isMSB){
return vector<FieldElement>(BasisL.end() - SoundnessParameters::dimReduction, BasisL.end());
}
return vector<FieldElement>(BasisL.begin(), BasisL.begin() + SoundnessParameters::dimReduction);
}
vector<FieldElement> getL1Basis(const vector<FieldElement>& BasisL, const bool L0isMSB){
if(L0isMSB){
return vector<FieldElement>(BasisL.begin(), BasisL.end() - SoundnessParameters::dimReduction);
}
return vector<FieldElement>(BasisL.begin() + SoundnessParameters::dimReduction, BasisL.end());
}
uint64_t getBasisLIndex_byL0L1indices(const vector<FieldElement>& BasisL, const uint64_t idxL0, const uint64_t idxL1, const bool L0isMSB){
if(L0isMSB){
const uint64_t BasisL1_size = BasisL.size() - SoundnessParameters::dimReduction;
return idxL1 | (idxL0<<BasisL1_size);
}
return idxL0 | (idxL1<<SoundnessParameters::dimReduction);
}
vector<FieldElement> getColumnBasis(const vector<FieldElement>& L, const bool L0isMSB){
const vector<FieldElement> L0Basis = getL0Basis(L, L0isMSB);
const elementsSet_t rowsBasis(L0Basis.begin(), L0Basis.end());
vector<FieldElement> basisForColumn(getL1Basis(L, L0isMSB));
{
const SubspacePolynomial q(rowsBasis);
const FieldElement q_on_ZERO = q.eval(zero());
for(FieldElement& e : basisForColumn){
e = q.eval(e + q_on_ZERO);
}
}
return basisForColumn;
}
template<typename T>
nlohmann::json state_t<T>::serialize() {
nlohmann::json data = {
{"localState", ddSetToStr(localState)}
};
std::for_each(subproofs.begin(), subproofs.end(), [&data] (std::pair<const Algebra::FieldElement, libstark::Protocols::Fri::common::state_t<rawQuery_t>> &element) {
nlohmann::json tmp{
{"first", nlohmann::json::parse(element.first.asString())},
{"second", element.second.serialize()}
};
data["subproofs"].push_back(tmp);
});
return data;
};
template<typename T>
nlohmann::json state_t<T>::serialize1() {
nlohmann::json data = {
{"localState", VecOfBufferToStr(localState)}
};
std::for_each(subproofs.begin(), subproofs.end(), [&data] (std::pair<const Algebra::FieldElement, libstark::Protocols::Fri::common::state_t<rawResult_t>> &element) {
nlohmann::json tmp{
{"first", nlohmann::json::parse(element.first.asString())},
{"second", element.second.serialize1()}
};
data["subproofs"].push_back(tmp);
});
return data;
};
nlohmann::json verifierRequest_t::serialization1() {
nlohmann::json result = {
{"proofConstructionQueries", ddVecOfVecOfALFEToStr(proofConstructionQueries)},
{"dataQueries", dataQueries.serialize()}
};
return result;
};
nlohmann::json proverResponce_t::serialization1() {
nlohmann::json result = {
{"proofConstructionComitments", VecOfBufferToStr(proofConstructionComitments)},
{"dataResults", dataResults.serialize1()}
};
return result;
};
unsigned short dimOfColumn(const unsigned short dimOfL){
return dimOfL - SoundnessParameters::dimReduction;
}
} //namespace common
} //nmasepace Fri
} //namespace Protocols
} //namespace libstark
| 33.166667 | 173 | 0.675747 | [
"vector"
] |
21a951ed4a7ec444404ceb3e157d0f06d37dc717 | 3,291 | cpp | C++ | apps/vaporgui/guis/TransformDelegate.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/guis/TransformDelegate.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/guis/TransformDelegate.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | //
// $Id$
//
// File: TransformDelegate.cpp
//
// Author: Kenny Gruchalla
// National Renewable Energy Laboratory
//
// Description: Delegate for inline editing of transform model
//
//
#include "TransformDelegate.h"
#include "TransformWidget.h"
#include "ModelParams.h"
#include "vizwinmgr.h"
#include "session.h"
#include "panelcommand.h"
#include <QtGui>
using namespace std;
using namespace VAPoR;
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
TransformDelegate::TransformDelegate(QObject *parent)
: QItemDelegate(parent)
{
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
QWidget *TransformDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem&,
const QModelIndex &index) const
{
return new TransformWidget(parent);
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
void TransformDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QStringList data = index.model()->data(index, Qt::EditRole).toString().split(" ");
TransformWidget *widget = static_cast<TransformWidget*>(editor);
widget->setLabel(data[0]);
widget->setX(data[1].toDouble());
widget->setY(data[2].toDouble());
widget->setZ(data[3].toDouble());
if (data.size() == 5)
{
widget->setTheta(data[4].toDouble());
}
widget->show();
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
void TransformDelegate::setModelData(QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index) const
{
QString text;
TransformWidget *widget = static_cast<TransformWidget*>(editor);
widget->interpretText();
text = widget->label();
text += QString(" %1 %2 %3").arg(widget->x()).arg(widget->y()).arg(widget->z());
if (widget->label() == "Rotate")
{
text += QString(" %1").arg(widget->theta());
}
QString data = index.model()->data(index, Qt::EditRole).toString();
if (data != text)
{
QString cmdtext = "edit " + widget->label() + " item";
ModelParams* modelParams = (ModelParams*) VizWinMgr::getActiveParams(ModelParams::_modelParamsTag);
PanelCommand* cmd = PanelCommand::captureStart(modelParams, cmdtext.toAscii().data());
model->setData(index, QVariant(text));
emit(transformChanged());
PanelCommand::captureEnd(cmd, modelParams);
}
}
//----------------------------------------------------------------------------
//
//----------------------------------------------------------------------------
void TransformDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
| 29.648649 | 105 | 0.477059 | [
"model",
"transform"
] |
21a996ee6ef569c6acc60170aa0a51ec43d163ab | 467 | cpp | C++ | client/src/main/game/entities/object.cpp | JulianBiancardi/Wolfenstein-Taller1 | 28e72ce8438264919586785aa09ce9b0a5de222b | [
"MIT"
] | 1 | 2021-04-23T19:57:40.000Z | 2021-04-23T19:57:40.000Z | client/src/main/game/entities/object.cpp | JulianBiancardi/Wolfenstein-Taller1 | 28e72ce8438264919586785aa09ce9b0a5de222b | [
"MIT"
] | null | null | null | client/src/main/game/entities/object.cpp | JulianBiancardi/Wolfenstein-Taller1 | 28e72ce8438264919586785aa09ce9b0a5de222b | [
"MIT"
] | null | null | null | #include "object.h"
#include "../../../../../common/src/main/ids/map_ids.h"
Object::Object(const Ray& position, unsigned int resource_id)
: position(position), resource_id(resource_id) {}
Object::~Object() {}
Point Object::get_position() const { return position.get_origin(); }
double Object::get_angle() const { return position.get_angle(); }
Image* Object::get_image(ResourceManager& resource_manager) {
return resource_manager.get_image(resource_id);
} | 29.1875 | 68 | 0.72591 | [
"object"
] |
21c3c2d8b8fedd501d476e27d95e829e1389a3fe | 3,757 | cpp | C++ | src/setup/SimpleObjLoader.cpp | QichenW/ComputerAnimations | 1da509763eb330d99a6dd5f40535abca09b2a87f | [
"MIT"
] | null | null | null | src/setup/SimpleObjLoader.cpp | QichenW/ComputerAnimations | 1da509763eb330d99a6dd5f40535abca09b2a87f | [
"MIT"
] | null | null | null | src/setup/SimpleObjLoader.cpp | QichenW/ComputerAnimations | 1da509763eb330d99a6dd5f40535abca09b2a87f | [
"MIT"
] | null | null | null | //
// Created by Qichen on 9/21/16.
//
#include "SimpleObjLoader.h"
#include <iostream>
using namespace std;
FILE *filePointer;
char firstWord[16];
vector<GLfloat> vx, vy,vz;
/****
* The machanism to load an object file is to first while reading throught the .obj file,
* store the coordinates of vertices and the identifiers of them.
* Then read through the file again to look for faces (triangles represented by identifiers of vertices),
* and use the information got from the first round, to create the opengl instructions to draw triangles,
* and save these instructions in a list, to be later called in main.cpp, when it is ready to plot the object.
* @param fileName
* @return identifier of the object
*/
GLuint SimpleObjLoader::loadObj(char *fileName) {
GLfloat x, y, z;
GLuint object;
object = glGenLists(1);
filePointer = fopen(fileName, "r");
if (!filePointer) {
printf("can't open file %s\n", fileName);
exit(1);
}
while (1) {
// read the first word of the line
if (fscanf(filePointer, "%s", firstWord) == EOF) {
break;
}
if (strcmp(firstWord, "v") == 0) {
fscanf(filePointer, "%f %f %f", &x, &y, &z);
// glVertex3f(x, y, z);
vx.push_back(x);
vy.push_back(y);
vz.push_back(z);
}
}
fclose(filePointer);
filePointer = fopen(fileName, "r");
glNewList(object, GL_COMPILE);
glLineWidth(1.0);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// record the polygons of an object in a
//if is a file without only vt, like in elephant.obj
//recordObjectAsTrianglesWithNoVt();
//if is a file without vt and vn, like in teddy.obj
recordObjectAsTrianglesWithNoVtNoVn();
glEndList();
fclose(filePointer);
return object;
}
/****
* This function can load a obj file with no texture vector and describing the object in triangles
*/
void SimpleObjLoader::recordObjectAsTrianglesWithNoVt() {
char dump1, dump2;
unsigned long vIndex1, vIndex2, vIndex3, vnIndex;
glBegin(GL_TRIANGLES);
while (true) {
// %s ignores /r /0 /n in between lines
if (fscanf(filePointer, "%s", firstWord) == EOF) {
break;
}
if (strcmp(firstWord, "f") == 0) {
fscanf(filePointer, "%lu %c %c %lu", &vIndex1, &dump1, &dump2, &vnIndex);
fscanf(filePointer, "%lu %c %c %lu", &vIndex2, &dump1, &dump2, &vnIndex);
fscanf(filePointer, "%lu %c %c %lu", &vIndex3, &dump1, &dump2, &vnIndex);
glVertex3f(vx.at(vIndex1 - 1), vy.at(vIndex1 - 1), vz.at(vIndex1 - 1));
glVertex3f(vx.at(vIndex2 - 1), vy.at(vIndex2 - 1), vz.at(vIndex2 - 1));
glVertex3f(vx.at(vIndex3 - 1), vy.at(vIndex3 - 1), vz.at(vIndex3 - 1));
}
}
glEnd();
}
/****
* This function can load a obj file with no texture vector, no normal vector and describing the object in triangles
*/
void SimpleObjLoader::recordObjectAsTrianglesWithNoVtNoVn() {
unsigned long vIndex1, vIndex2, vIndex3;
glBegin(GL_TRIANGLES);
while (true) {
// %s ignores /r /0 /n in between lines
if (fscanf(filePointer, "%s", firstWord) == EOF) {
break;
}
if (strcmp(firstWord, "f") == 0) {
fscanf(filePointer, "%lu %lu %lu", &vIndex1, &vIndex2, &vIndex3);
glVertex3f(vx.at(vIndex1 - 1), vy.at(vIndex1 - 1), vz.at(vIndex1 - 1));
glVertex3f(vx.at(vIndex2 - 1), vy.at(vIndex2 - 1), vz.at(vIndex2 - 1));
glVertex3f(vx.at(vIndex3 - 1), vy.at(vIndex3 - 1), vz.at(vIndex3 - 1));
}
}
glEnd();
}
| 33.846847 | 116 | 0.592494 | [
"object",
"vector"
] |
21c4fc9f4cee549a2db1d9acda37dd1b5b65e909 | 577 | cpp | C++ | LeetCode/0303. Range Sum Query - Immutable/solution.cpp | InnoFang/oh-my-algorithms | f559dba371ce725a926725ad28d5e1c2facd0ab2 | [
"Apache-2.0"
] | 19 | 2018-08-26T03:10:58.000Z | 2022-03-07T18:12:52.000Z | LeetCode/0303. Range Sum Query - Immutable/solution.cpp | InnoFang/Algorithm-Library | 1896b9d8b1fa4cd73879aaecf97bc32d13ae0169 | [
"Apache-2.0"
] | null | null | null | LeetCode/0303. Range Sum Query - Immutable/solution.cpp | InnoFang/Algorithm-Library | 1896b9d8b1fa4cd73879aaecf97bc32d13ae0169 | [
"Apache-2.0"
] | 6 | 2020-03-16T23:00:06.000Z | 2022-01-13T07:02:08.000Z | /**
* 16 / 16 test cases passed.
* Runtime: 24 ms
* Memory Usage: 16.8 MB
*/
class NumArray {
public:
NumArray(vector<int>& nums) {
prefixSum.push_back(0);
for (int i = 0; i < nums.size(); ++ i) {
prefixSum.push_back(prefixSum[i] + nums[i]);
}
}
int sumRange(int i, int j) {
return prefixSum[j + 1] - prefixSum[i];
}
private:
vector<int> prefixSum;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
| 20.607143 | 64 | 0.566724 | [
"object",
"vector"
] |
21c80b2d742d22bac7c66e390de896c46df8afcb | 2,245 | cpp | C++ | Cracking Fenwick Tree to the root V1/Solutions/luismo/F/F - Gravel.cpp | gmeligio/axon_training | 657f181b732265856c71e97697bfde2062744e5a | [
"MIT"
] | null | null | null | Cracking Fenwick Tree to the root V1/Solutions/luismo/F/F - Gravel.cpp | gmeligio/axon_training | 657f181b732265856c71e97697bfde2062744e5a | [
"MIT"
] | 5 | 2019-04-30T22:31:36.000Z | 2019-05-07T00:15:23.000Z | Cracking Fenwick Tree to the root V1/Solutions/luismo/F/F - Gravel.cpp | gmeligio/axon_training | 657f181b732265856c71e97697bfde2062744e5a | [
"MIT"
] | 5 | 2019-05-01T05:08:43.000Z | 2019-05-07T18:13:18.000Z | /*
Author: Luis Manuel Díaz Barón (LUISMO)
Problem:
Online Judge:
Idea:
*/
#include<bits/stdc++.h>
// Types
#define ll long long
#define ull unsigned long long
// IO
#define sf scanf
#define pf printf
#define mkp make_pair
#define fi first
#define se second
#define endl "\n"
using namespace std;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const ll inf = 1e16 + 3;
const int mod = 1e9 + 7;
const int lim = 2e5 + 2;
class FenwickTree
{
private:
vector<ll> tree;
inline int lowBit(int i) {return i&-i;}
public:
FenwickTree(){}
FenwickTree(int len)
{
tree.resize(len, 0);
}
FenwickTree(int len, int v)
{
tree.resize(len, v);
}
void update(int idx, ll upd)
{
for(int i = idx; i < tree.size(); i+= lowBit(i))
tree[i]+= upd;
}
ll retrieve(int idx)
{
ll sum = 0;
for(int i = idx; i > 0; i-= lowBit(i))
sum += tree[i];
return sum;
}
ll retrieve(int a, int b)
{
if(a > b)
return 0;
return retrieve(b) - retrieve(a - 1);
}
};
FenwickTree * ft;
int n, m, c, u , v, k, p;
char cc;
void solve()
{
cin >> n >> m >> c;
FenwickTree * ft = new FenwickTree(n + 3);
for(int i = 1; i <= n; i++)
ft->update(i, c), ft->update(i+1, -c);
for(int i = 0; i < m; i++)
{
cin >> cc;
if(cc == 'S')
{
cin >> u >> v >> k;
ft->update(u, k);
ft->update(v + 1, -k);
}
else
{
cin >> p;
ll answ = ft->retrieve(p);
cout << answ << endl;
}
}
}
void fastIO()
{
cin.sync_with_stdio(false);
cin.tie(0);
}
void IO()
{
if(fopen("d:\\lmo.in","r") != NULL)
{
freopen("d:\\lmo.in","r",stdin);
}
else if(fopen("/media/luismo/Beijing/lmo.in","r") != NULL)
{
freopen("/media/luismo/Beijing/lmo.in", "r", stdin);
}
}
int main()
{
IO();
fastIO();
solve();
}
| 17.269231 | 61 | 0.437416 | [
"vector"
] |
21cad99746f3426d273998da84247da215483e95 | 12,353 | cpp | C++ | CsPlugin/Source/CsCore/Public/Managers/FX/CsTypes_FX.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsPlugin/Source/CsCore/Public/Managers/FX/CsTypes_FX.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsPlugin/Source/CsCore/Public/Managers/FX/CsTypes_FX.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Managers/FX/CsTypes_FX.h"
#include "CsCore.h"
// Library
#include "Managers/FX/CsLibrary_FX.h"
// Settings
#include "Settings/CsDeveloperSettings.h"
// Param
#include "Managers/FX/Params/CsParams_FX.h"
// FX
#pragma region
namespace NCsFX
{
void PopulateEnumMapFromSettings(const FString& Context, UObject* ContextRoot)
{
if (UCsDeveloperSettings* Settings = GetMutableDefault<UCsDeveloperSettings>())
{
EMCsFX::Get().ClearUserDefinedEnums();
// Enum Settings
if (Settings->ECsFX_PopulateEnumMapMethod == ECsPopulateEnumMapMethod::EnumSettings)
{
const TArray<FCsSettings_Enum>& Enums = Settings->GetSettingsEnum<FECsFX>();
const FString& EnumSettingsPath = Settings->GetSettingsEnumPath<FECsFX>();
if (Enums.Num() > CS_EMPTY)
{
for (const FCsSettings_Enum& Enum : Enums)
{
const FString& Name = Enum.Name;
const FString& DisplayName = Enum.DisplayName;
if (Name.IsEmpty())
{
UE_LOG(LogCs, Warning, TEXT("%s: Empty Enum listed in %s."), *Context, *EnumSettingsPath);
return;
}
checkf(!EMCsFX::Get().IsValidEnum(Name), TEXT("%s: FX (Name): %s already exists (declared in native)."), *Context, *Name);
if (!Enum.DisplayName.IsEmpty())
{
checkf(!EMCsFX::Get().IsValidEnumByDisplayName(DisplayName), TEXT("%s: FX (DisplayName): %s already exists (declared in native)."), *Context, *DisplayName);
EMCsFX::Get().Create(Name, DisplayName, true);
}
else
{
EMCsFX::Get().Create(Name, true);
}
}
}
else
{
UE_LOG(LogCs, Warning, TEXT("%s: Enum Setting @ %s is empty."), *Context, *EnumSettingsPath);
}
}
// DataTable
if (Settings->ECsFX_PopulateEnumMapMethod == ECsPopulateEnumMapMethod::DataTable)
{
for (TSoftObjectPtr<UDataTable>& SoftObjectPtr : Settings->FXs)
{
// Check DataTable of Projectiles
TSoftObjectPtr<UDataTable> DT_SoftObject = SoftObjectPtr;
if (UDataTable* DT = DT_SoftObject.LoadSynchronous())
{
const UScriptStruct* RowStruct = DT->GetRowStruct();
const TMap<FName, uint8*>& RowMap = DT->GetRowMap();
{
// Set if the Row Struct has the properties Name and DisplayName
FStrProperty* NameProperty = CastField<FStrProperty>(RowStruct->FindPropertyByName(FName("Name")));
NameProperty = NameProperty ? NameProperty : CastField<FStrProperty>(RowStruct->CustomFindProperty(FName("Name")));
FStrProperty* DisplayNameProperty = CastField<FStrProperty>(RowStruct->FindPropertyByName(FName("DisplayName")));
DisplayNameProperty = DisplayNameProperty ? DisplayNameProperty: CastField<FStrProperty>(RowStruct->CustomFindProperty(FName("DisplayName")));
if (NameProperty &&
DisplayNameProperty)
{
for (const TPair<FName, uint8*>& Pair : RowMap)
{
const FName& RowName = Pair.Key;
const uint8* RowPtr = Pair.Value;
const FString& Name = NameProperty->GetPropertyValue_InContainer(RowPtr);
const FString& DisplayName = DisplayNameProperty->GetPropertyValue_InContainer(RowPtr);
checkf(Name.Compare(RowName.ToString(), ESearchCase::IgnoreCase) == 0, TEXT("%s: Row Name != FX Name (%s != %s)."), *Context, *(RowName.ToString()), *Name);
checkf(!EMCsFX::Get().IsValidEnum(Name), TEXT("%s: FX (Name): %s already exists (declared in native)."), *Context, *Name);
if (!DisplayName.IsEmpty())
{
checkf(!EMCsFX::Get().IsValidEnumByDisplayName(DisplayName), TEXT("%s: FX (DisplayName): %s already exists (declared in native)."), *Context, *DisplayName);
EMCsFX::Get().Create(Name, DisplayName, true);
}
else
{
EMCsFX::Get().Create(Name, true);
}
}
}
else
{
UE_LOG(LogCs, Warning, TEXT("%s: Failed to find properties with name: Name and Display for struct: %s."), *Context, *(RowStruct->GetName()));
}
}
}
else
{
UE_LOG(LogCs, Warning, TEXT("%s: Failed to Load DataTable @ %s."), *Context, *(DT_SoftObject.ToSoftObjectPath().ToString()));
}
}
}
}
}
}
#pragma endregion FX
// FXPriority
#pragma region
namespace NCsFXPriority
{
namespace Ref
{
typedef EMCsFXPriority EnumMapType;
CSCORE_API CS_ADD_TO_ENUM_MAP(Low);
CSCORE_API CS_ADD_TO_ENUM_MAP(Medium);
CSCORE_API CS_ADD_TO_ENUM_MAP(High);
CSCORE_API CS_ADD_TO_ENUM_MAP_CUSTOM(ECsFXPriority_MAX, "MAX");
}
CSCORE_API const uint8 MAX = (uint8)Type::ECsFXPriority_MAX;
}
#pragma endregion FXPriority
// FXDeallocateMethod
#pragma region
namespace NCsFXDeallocateMethod
{
namespace Ref
{
typedef EMCsFXDeallocateMethod EnumMapType;
CSCORE_API CS_ADD_TO_ENUM_MAP(LifeTime);
CSCORE_API CS_ADD_TO_ENUM_MAP(Complete);
CSCORE_API CS_ADD_TO_ENUM_MAP_CUSTOM(ECsFXDeallocateMethod_MAX, "MAX");
}
CSCORE_API const uint8 MAX = (uint8)Type::ECsFXDeallocateMethod_MAX;
}
namespace NCsFX
{
namespace NDeallocateMethod
{
namespace Ref
{
typedef EMDeallocateMethod EnumMapType;
CSCORE_API CS_ADD_TO_ENUM_MAP(LifeTime);
CSCORE_API CS_ADD_TO_ENUM_MAP(Complete);
}
}
}
#pragma endregion FXDeallocateMethod
// FXAttachPoint
#pragma region
namespace NCsFXAttachPoint
{
namespace Ref
{
typedef EMCsFXAttachPoint EnumMapType;
CSCORE_API CS_ADD_TO_ENUM_MAP(None);
CSCORE_API CS_ADD_TO_ENUM_MAP(Bone);
CSCORE_API CS_ADD_TO_ENUM_MAP(Socket);
CSCORE_API CS_ADD_TO_ENUM_MAP_CUSTOM(ECsFXAttachPoint_MAX, "MAX");
}
CSCORE_API const uint8 MAX = (uint8)Type::ECsFXAttachPoint_MAX;
}
#pragma endregion FXAttachPoint
// FXParameterValue
#pragma region
namespace NCsFXParameterValue
{
namespace Ref
{
typedef EMCsFXParameterValue EnumMapType;
CSCORE_API CS_ADD_TO_ENUM_MAP(Int);
CSCORE_API CS_ADD_TO_ENUM_MAP(Float);
CSCORE_API CS_ADD_TO_ENUM_MAP(Vector);
CSCORE_API CS_ADD_TO_ENUM_MAP_CUSTOM(ECsFXParameterValue_MAX, "MAX");
}
CSCORE_API const uint8 MAX = (uint8)Type::ECsFXParameterValue_MAX;
}
#pragma endregion FXParameterValue
// FCsFXParameterInt
#pragma region
#define ParameterType NCsFX::NParameter::NInt::FIntType
void FCsFXParameterInt::CopyToParams(ParameterType* Params)
{
Params->SetName(&Name);
Params->SetValue(&Value);
}
void FCsFXParameterInt::CopyToParamsAsValue(ParameterType* Params) const
{
Params->SetName(Name);
Params->SetValue(Value);
}
#undef ParameterType
bool FCsFXParameterInt::IsValid(const FString& Context, void(*Log)(const FString&) /*=&FCsLog::Warning*/) const
{
if (Name == NAME_None)
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: Name: None is NOT Valid."), *Context));
return false;
}
return true;
}
#pragma endregion FCsFXParameterInt
// FCsFXParameterFloat
#pragma region
#define ParameterType NCsFX::NParameter::NFloat::FFloatType
void FCsFXParameterFloat::CopyToParams(ParameterType* Params)
{
Params->SetName(&Name);
Params->SetValue(&Value);
}
void FCsFXParameterFloat::CopyToParamsAsValue(ParameterType* Params) const
{
Params->SetName(Name);
Params->SetValue(Value);
}
#undef ParameterType
bool FCsFXParameterFloat::IsValid(const FString& Context, void(*Log)(const FString&) /*=&FCsLog::Warning*/) const
{
if (Name == NAME_None)
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: Name: None is NOT Valid."), *Context));
return false;
}
return true;
}
#pragma endregion FCsFXParameterFloat
// FCsFXParameterVector
#pragma region
#define ParameterType NCsFX::NParameter::NVector::FVectorType
void FCsFXParameterVector::CopyToParams(ParameterType* Params)
{
Params->SetName(&Name);
Params->SetValue(&Value);
}
void FCsFXParameterVector::CopyToParamsAsValue(ParameterType* Params) const
{
Params->SetName(Name);
Params->SetValue(Value);
}
#undef ParameterType
bool FCsFXParameterVector::IsValid(const FString& Context, void(*Log)(const FString&) /*=&FCsLog::Warning*/) const
{
if (Name == NAME_None)
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: Name: None is NOT Valid."), *Context));
return false;
}
return true;
}
#pragma endregion FCsFXParameterVector
// FCsFX
#pragma region
const FCsFX FCsFX::Invalid;
bool FCsFX::IsValidChecked(const FString& Context) const
{
// Check FX is Valid.
check(GetChecked(Context));
// Check Type is Valid
check(EMCsFX::Get().IsValidEnumChecked(Context, Type));
if (!Transform.Equals(FTransform::Identity))
{
checkf(TransformRules != 0, TEXT("%s: No TransformRules set for Transform: %s."), *Context, *(Transform.ToString()));
}
// Character Parameters are Valid.
typedef NCsFX::FLibrary FXLibrary;
typedef NCsFX::NParameter::EValue ParameterValueType;
// Int
for (const FCsFXParameterInt& Param : IntParameters)
{
check(FXLibrary::HasVariableNameChecked(Context, FX_Internal, Param.Name, ParameterValueType::Int));
}
// Float
for (const FCsFXParameterFloat& Param : FloatParameters)
{
check(FXLibrary::HasVariableNameChecked(Context, FX_Internal, Param.Name, ParameterValueType::Float));
}
// Vector
for (const FCsFXParameterVector& Param : VectorParameters)
{
check(FXLibrary::HasVariableNameChecked(Context, FX_Internal, Param.Name, ParameterValueType::Vector));
}
return true;
}
bool FCsFX::IsValid(const FString& Context, void(*Log)(const FString&) /*=&FCsLog::Warning*/) const
{
// Check FX Path is Valid.
if (!FX.ToSoftObjectPath().IsValid())
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: FX is NULL."), *Context));
return false;
}
// Check FX is Valid.
if (!FX_Internal)
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: FX has NOT been loaded from Path @ %s."), *Context, *(FX.ToSoftObjectPath().ToString())));
return false;
}
// Check Type is Valid.
if (!EMCsFX::Get().IsValidEnum(Type))
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s Type: %s is NOT Valid."), *Context, Type.ToChar()));
return false;
}
if (!Transform.Equals(FTransform::Identity) &&
TransformRules == 0)
{
CS_CONDITIONAL_LOG(FString::Printf(TEXT("%s: No TransformRules set for Transform: %s."), *Context, *(Transform.ToString())));
return false;
}
// Character Parameters are Valid.
typedef NCsFX::FLibrary FXLibrary;
typedef NCsFX::NParameter::EValue ParameterValueType;
// Int
for (const FCsFXParameterInt& Param : IntParameters)
{
if (!FXLibrary::SafeHasVariableName(Context, FX_Internal, Param.Name, ParameterValueType::Int, Log))
return false;
}
// Float
for (const FCsFXParameterFloat& Param : FloatParameters)
{
if (!FXLibrary::SafeHasVariableName(Context, FX_Internal, Param.Name, ParameterValueType::Float, Log))
return false;
}
// Vector
for (const FCsFXParameterVector& Param : VectorParameters)
{
if (!FXLibrary::SafeHasVariableName(Context, FX_Internal, Param.Name, ParameterValueType::Vector, Log))
return false;
}
return true;
}
void FCsFX::Reset()
{
FX = nullptr;
FX_LoadFlags = 0;
FX_Internal= nullptr;
Type = EMCsFX::Get().GetMAX();
DeallocateMethod = ECsFXDeallocateMethod::Complete;
DeallocateMethod_Internal = (NCsFX::EDeallocateMethod*)&DeallocateMethod;
LifeTime = 0.0f;
AttachmentTransformRules = ECsAttachmentTransformRules::SnapToTargetNotIncludingScale;
Bone = NAME_None;
TransformRules =7; // NCsTransformRules::All
Transform = FTransform::Identity;
IntParameters.Reset(IntParameters.Max());
FloatParameters.Reset(FloatParameters.Max());
VectorParameters.Reset(VectorParameters.Max());
}
#pragma endregion FCsFX
// FXPayloadChange
#pragma region
namespace NCsFXPayloadChange
{
namespace Ref
{
typedef EMCsFXPayloadChange EnumMapType;
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP_CUSTOM(FXSystem, "FX System");
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP_CUSTOM(KeepRelativeTransform, "Keep Relative Transform");
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP_CUSTOM(KeepWorldTransform, "Keep World Transform");
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP_CUSTOM(SnapToTargetNotIncludingScale, "Snap to Target not Including Scale");
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP_CUSTOM(SnapToTargetIncludingScale, "Snap to Target Including Scale");
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP(Transform);
CSCORE_API CS_ADD_TO_ENUM_FLAG_MAP(Parameter);
}
CSCORE_API const int32 None = 0;
CSCORE_API const int32 All = 127; // 1 + 2 + 4 + 8 + 16 + 32 + 64
}
#pragma endregion FXPayloadChange | 27.759551 | 166 | 0.720473 | [
"vector",
"transform"
] |
21daca4d9f1be8349c913eb7b299b8b1e989a8b1 | 1,230 | hpp | C++ | src/com/cyosp/mpa/core/User.hpp | cyosp/MPA | f640435c483dcbf7bfe7ff7887a25e6c76612528 | [
"BSD-3-Clause"
] | null | null | null | src/com/cyosp/mpa/core/User.hpp | cyosp/MPA | f640435c483dcbf7bfe7ff7887a25e6c76612528 | [
"BSD-3-Clause"
] | null | null | null | src/com/cyosp/mpa/core/User.hpp | cyosp/MPA | f640435c483dcbf7bfe7ff7887a25e6c76612528 | [
"BSD-3-Clause"
] | null | null | null | /*
* User.hpp
*
* Created on: 2017-05-23
* Author: CYOSP
*/
#ifndef COM_CYOSP_MPA_CORE_USER_HPP_
#define COM_CYOSP_MPA_CORE_USER_HPP_
#include <vector>
#include <string>
#include "MPA.hpp"
#include "litesql.hpp"
#include "com/cyosp/mpa/po/MPAPO.hpp"
// no name collisions expected
using namespace litesql;
using namespace mpapo;
using std::vector;
using std::string;
namespace mpa
{
class User
{
public:
// Get administrator user
static vector<mpapo::User> getAdminUsers();
// Get users
static vector<mpapo::User> getUsers();
// Get user by login
static mpapo::User getUser(string login);
// Get user by id
static mpapo::User getUser(int id);
// Del an user
static bool delUser(int id, int version);
// Check if user exist by login
static bool existUser(string login);
// Add a user
static mpapo::User & addUser(bool isAdmin, string login, string password, string locale);
static bool isSecurePwd(const string pwd);
static bool isAdminRegistered();
virtual ~User();
};
}
#endif
| 21.578947 | 101 | 0.595122 | [
"vector"
] |
21defd8492e0934ca10bf32d2138cf7d08b3dae7 | 791 | hpp | C++ | app/model/StudentCourseModel.hpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | null | null | null | app/model/StudentCourseModel.hpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | null | null | null | app/model/StudentCourseModel.hpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | null | null | null | /*\
| ------------------------------------------------------
| @file : StudentCourseModel.hpp
| @author : Fabien Beaujean, Luc Lorentz
| @description : modèle gestion des cours par les élèves
| ------------------------------------------------------
\*/
#ifndef STUDENTCOURSEMODEL_HPP_INCLUDED
#define STUDENTCOURSEMODEL_HPP_INCLUDED
#include "../include.hpp"
namespace app
{
class StudentCourseModel : core::Model
{
public :
StudentCourseModel(core::Config &config, core::Database &database, core::Request &request);
entity::Student getStudentById(std::string id);
std::vector<entity::Course> getCoursesByStudent(entity::Student student);
};
}
#endif // STUDENTCOURSEMODEL_HPP_INCLUDED
| 30.423077 | 107 | 0.563843 | [
"vector",
"model"
] |
21df0f5364d9edbbda91e4dc36c9278f9902bd0b | 3,787 | hpp | C++ | Component.hpp | phisko/kengine | c30f98cc8e79cce6574b5f61088b511f29bbe8eb | [
"MIT"
] | 259 | 2018-11-01T05:12:37.000Z | 2022-03-28T11:15:27.000Z | Component.hpp | raptoravis/kengine | 619151c20e9db86584faf04937bed3d084e3bc21 | [
"MIT"
] | 2 | 2018-11-30T13:58:44.000Z | 2018-12-17T11:58:42.000Z | Component.hpp | raptoravis/kengine | 619151c20e9db86584faf04937bed3d084e3bc21 | [
"MIT"
] | 16 | 2018-12-01T13:38:18.000Z | 2021-12-04T21:31:55.000Z | #pragma once
#ifndef KENGINE_COMPONENT_CHUNK_SIZE
# define KENGINE_COMPONENT_CHUNK_SIZE 64
#endif
#ifndef KENGINE_NDEBUG
#include <iostream>
#endif
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <fstream>
#include <cstddef>
#include <unordered_map>
#include <memory>
#include <vector>
#include "meta/type.hpp"
#include "reflection.hpp"
#include "string.hpp"
#include "vector.hpp"
#include "termcolor.hpp"
namespace kengine {
namespace detail {
using Mutex = std::shared_mutex;
using ReadLock = std::shared_lock<Mutex>;
using WriteLock = std::lock_guard<Mutex>;
}
namespace detail {
static constexpr size_t INVALID = (size_t)-1;
struct MetadataBase {
size_t id = detail::INVALID;
size_t typeEntityID = detail::INVALID;
virtual ~MetadataBase() = default;
};
struct GlobalCompMap {
std::unordered_map<putils::meta::type_index, std::unique_ptr<MetadataBase>> map;
detail::Mutex mutex;
};
extern GlobalCompMap * components;
}
template<typename Comp>
class Component {
private:
using Chunk = std::vector<Comp>;
struct Metadata : detail::MetadataBase {
std::vector<Chunk> chunks;
mutable detail::Mutex _mutex;
};
public:
static Comp & get(size_t id) {
if constexpr (std::is_empty<Comp>()) {
static Comp ret;
return ret;
}
else {
static auto & meta = metadata();
detail::ReadLock r(meta._mutex);
if (id >= meta.chunks.size() * KENGINE_COMPONENT_CHUNK_SIZE) {
r.unlock(); { // Unlock read so we can get write
detail::WriteLock l(meta._mutex);
while (id >= meta.chunks.size() * KENGINE_COMPONENT_CHUNK_SIZE)
meta.chunks.emplace_back();
// Only populate the chunk we need
meta.chunks.back().resize(KENGINE_COMPONENT_CHUNK_SIZE);
} r.lock(); // Re-lock read
}
auto & currentChunk = meta.chunks[id / KENGINE_COMPONENT_CHUNK_SIZE];
if (currentChunk.empty()) {
r.unlock(); {
detail::WriteLock l(meta._mutex);
currentChunk.resize(KENGINE_COMPONENT_CHUNK_SIZE);
} r.lock();
}
return currentChunk[id % KENGINE_COMPONENT_CHUNK_SIZE];
}
}
static size_t id() {
static const size_t ret = metadata().id;
return ret;
}
template<typename Func>
static size_t initTypeEntityID(Func && createEntity) {
auto & meta = metadata();
detail::ReadLock l(meta._mutex);
if (meta.typeEntityID == detail::INVALID) {
l.unlock();
detail::WriteLock l2(meta._mutex);
if (meta.typeEntityID == detail::INVALID) // Might have been set by another thread between unlock() and lock()
meta.typeEntityID = createEntity();
}
return meta.typeEntityID;
}
template<typename Func>
static size_t typeEntityID(Func && createEntity) {
static size_t ret = initTypeEntityID(createEntity);
return ret;
}
static void setTypeEntityID(size_t id) {
metadata().typeEntityID = id;
}
private:
static inline Metadata & metadata() {
static Metadata * ret = [] {
const auto typeIndex = putils::meta::type<Comp>::index;
{
detail::ReadLock l(detail::components->mutex);
const auto it = detail::components->map.find(typeIndex);
if (it != detail::components->map.end())
return static_cast<Metadata *>(it->second.get());
}
auto tmp = std::make_unique<Metadata>();
auto ptr = static_cast<Metadata *>(tmp.get());
{
detail::WriteLock l(detail::components->mutex);
detail::components->map[typeIndex] = std::move(tmp);
ptr->id = detail::components->map.size() - 1;
}
#ifndef KENGINE_NDEBUG
std::cout << putils::termcolor::green << ptr->id << ' ' << putils::termcolor::cyan << putils::reflection::get_class_name<Comp>() << '\n' << putils::termcolor::reset;
#endif
return ptr;
}();
return *ret;
}
};
}
| 25.587838 | 169 | 0.668867 | [
"vector"
] |
21e64a79f31b05969d5c58d9856ccf2e391666d2 | 12,187 | cpp | C++ | QHTML_Static/qhtm/tablelayout.cpp | karolbe/DSS | 5a834561fbe7345d0be36f41ed8620ebbdb2f222 | [
"BSD-3-Clause"
] | null | null | null | QHTML_Static/qhtm/tablelayout.cpp | karolbe/DSS | 5a834561fbe7345d0be36f41ed8620ebbdb2f222 | [
"BSD-3-Clause"
] | null | null | null | QHTML_Static/qhtm/tablelayout.cpp | karolbe/DSS | 5a834561fbe7345d0be36f41ed8620ebbdb2f222 | [
"BSD-3-Clause"
] | 1 | 2020-06-28T19:21:22.000Z | 2020-06-28T19:21:22.000Z | /*----------------------------------------------------------------------
Copyright (c) 1998 Gipsysoft. All Rights Reserved.
Please see the file "licence.txt" for licencing details.
File: tablelayout.cpp
Owner: russf@gipsysoft.com
Author: rich@woodbridgeinternalmed.com
Purpose: Lays out the cells of a table
----------------------------------------------------------------------*/
#include "stdafx.h"
#include <math.h>
#include "DebugHlp/DebugHlp.h"
#include "Defaults.h"
#include "HTMLSectionCreator.h"
#include "HTMLSection.h"
#include "tablelayout.h"
//#define HIGH_DETAIL
#ifdef HIGH_DETAIL
#define DETAIL_TRACE TRACE
#else
#if _MSC_VER >= 1300
#define DETAIL_TRACE __noop
#else
#define DETAIL_TRACE 1 ? (void)0 : (void)0
#endif // _MSC_VER >= 1300
#endif
CHTMLTableLayout::CHTMLTableLayout( CHTMLTable* ptab, CHTMLSectionCreator *psc )
: m_pTab(ptab)
, m_nMaxWidth( psc->GetDefaultRightMargin() - psc->GetDefaultLeftMargin() )
, m_dc( psc->GetDC() )
, m_nCols( ptab->GetRowsCols().cy )
, m_nRows( ptab->GetRowsCols().cx )
, m_nZoomLevel( psc->GetZoomLevel() )
, m_pscParent( psc )
{
// Ensure that CHTMLTable is properly initialized...
if (!m_pTab->m_bCellsMeasured)
{
//
// The code herin relies upon these being set, so if this is the second time we have been through this
// (due to zoom level changing) then we need to reset them.
m_pTab->m_arrDesiredWidth.SetSize( 0 );
m_pTab->m_arrMinimumWidth.SetSize( 0 );
m_pTab->m_arrMaximumWidth.SetSize( 0 );
m_pTab->m_arrLayoutWidth.SetSize( 0 );
m_pTab->m_arrNoWrap.SetSize( 0 );
m_pTab->m_arrDesiredWidth.SetSize( m_nCols );
m_pTab->m_arrMinimumWidth.SetSize( m_nCols );
m_pTab->m_arrMaximumWidth.SetSize( m_nCols );
m_pTab->m_arrLayoutWidth.SetSize( m_nCols );
m_pTab->m_arrNoWrap.SetSize( m_nCols );
}
Layout();
}
WinHelper::CSize CHTMLTableLayout::MeasureDocument(CHTMLDocument* pdoc, int nWidth)
{
// We'll use an HTMLSection, since it will destroy the temporary sections
// for us.
CHTMLSection TempSection( &g_defaults );
CHTMLSectionCreator htCreate( &TempSection, m_dc, 0, 0, nWidth, COLORREF(0), true, m_nZoomLevel, NULL, m_pscParent );
htCreate.AddDocument( pdoc );
return htCreate.GetSize();
}
// Determine the extrema for the given cell, and return the values.
void CHTMLTableLayout::MeasureCell(CHTMLTableCell* pCell, size_t nCol)
{
const int nDesiredWidth = pCell->m_nWidth;
bool bNoWrap = pCell->m_bNoWrap;
if (bNoWrap)
m_pTab->m_arrNoWrap[nCol] = true;
// Start with minimum width:
if (!m_pTab->m_bCellsMeasured)
{
int testWidth;
// NOWRAP takes precedence, so look there first
if ( bNoWrap )
testWidth = knFindMaximumWidth;
else
testWidth = 1; // small enough to get smallest object
WinHelper::CSize size( MeasureDocument( pCell, testWidth ));
size.cx /= pCell->m_nColSpan;
m_pTab->m_arrMinimumWidth[nCol] = max(m_pTab->m_arrMinimumWidth[nCol], size.cx);
}
// We need maximum width only if the table width was not specified!
// If a percentage is specified for a nested tables width, then the
// maximum width for that document is difficult to determine.
// In fact, the maximu should be limited based on the maxWidth, rather
// than on the artificial value of 32000.
if( m_pTab->m_nWidth == 0 )
{
if (m_pTab->m_arrNoWrap[nCol])
{
m_pTab->m_arrMaximumWidth[ nCol ] = m_pTab->m_arrMinimumWidth[ nCol ];
}
else
{
// We use nMaxWidth here, which changes on a resize, but the
// cells are not recalculated if they are relative!
int nTestWidth = 0;
if( nDesiredWidth > 0 )
{
nTestWidth = nDesiredWidth;
}
else if( nDesiredWidth == -100 )
{
nTestWidth = m_nMaxWidth;
}
else if( nDesiredWidth == 0 )
{
nTestWidth = knFindMaximumWidth;
}
else
{
nTestWidth = m_nMaxWidth * abs(nDesiredWidth) / 100;
}
const WinHelper::CSize size( MeasureDocument( pCell, nTestWidth ) );
m_pTab->m_arrMaximumWidth[ nCol ] = max(m_pTab->m_arrMaximumWidth[ nCol ], size.cx);
}
}
else
m_pTab->m_arrMaximumWidth[ nCol ] = m_pTab->m_arrMinimumWidth[ nCol ];
DETAIL_TRACE( _T("\t\tCol %d has width of %d and colspan of %d, minimumWidth %d \n"), nCol, m_pTab->m_arrMaximumWidth[ nCol ], pCell->m_nColSpan, m_pTab->m_arrMinimumWidth[ nCol ] );
}
void CHTMLTableLayout::MeasureCells()
{
// Zero the max widths, because they are recalculated
m_pTab->m_arrMaximumWidth.SetSize( m_nCols );
// Iterate all of the cells
for (int nRow = 0; nRow < m_nRows; nRow++)
{
DETAIL_TRACE( _T("\tMeasuring row %d\n"), nRow );
CHTMLTable::CHTMLTableRow *pRow = m_pTab->m_arrRows[ nRow ];
const size_t nCols = pRow->m_arrCells.GetSize();
for( size_t nCol = 0; nCol < nCols; nCol++ )
{
CHTMLTableCell *pCell = pRow->m_arrCells[ nCol ];
MeasureCell( pCell, nCol );
//
// If the cell has colspan then we need to skip that many columns when assigning our measurements
if( pCell->m_nColSpan )
{
nCol += pCell->m_nColSpan - 1;
}
}
}
m_pTab->m_bCellsMeasured = true;
#ifdef DETAIL_TRACE
DETAIL_TRACE( _T("Table (%d, %d)\n"), m_nRows, m_nCols);
DETAIL_TRACE( _T(" Measurements:\n") );
for (int zz =0; zz < m_nCols; ++zz)
{
DETAIL_TRACE( _T(" Column: %d desired: %d Min: %d Max: %d\n"), zz, m_pTab->m_arrDesiredWidth[ zz ], m_pTab->m_arrMinimumWidth[zz], m_pTab->m_arrMaximumWidth[zz]);
}
#endif
// Be sure to include border and padding space.
int nDeadSpace = (2 * m_pTab->m_nBorder) + ((m_nCols + 1) * m_pTab->m_nCellSpacing) + (m_nCols * 2 * m_pTab->m_nCellPadding);
nDeadSpace = m_dc.ScaleX(nDeadSpace);
if (m_pTab->m_nBorder)
nDeadSpace += m_dc.ScaleX(2 * m_nCols);
// Calculate the extrema of table width
m_nMaxTableWidth = m_nMinTableWidth = nDeadSpace;
for (int i = 0; i < m_nCols; ++i)
{
m_nMinTableWidth += m_pTab->m_arrMinimumWidth[i];
m_nMaxTableWidth += max(0, m_pTab->m_arrMaximumWidth[i]); // ignore negatives!
}
}
bool CHTMLTableLayout::LayoutMaximum()
{
if (m_pTab->m_nWidth == 0 && m_nMaxTableWidth <= m_nMaxWidth)
{
m_nTableWidth = m_nMaxTableWidth;
for (int i = 0; i < m_nCols; ++i)
m_pTab->m_arrLayoutWidth[i] = m_pTab->m_arrMaximumWidth[i];
return true;
}
else
return false;
}
void CHTMLTableLayout::GetDesiredWidths()
{
// Now that we know the size of the table, we can calculate desired widths
for (int nRow = 0; nRow < m_nRows; nRow++)
{
CHTMLTable::CHTMLTableRow *pRow = m_pTab->m_arrRows[ nRow ];
for( UINT nCol = 0; nCol < pRow->m_arrCells.GetSize(); nCol++ )
{
const int nDesiredWidth = pRow->m_arrCells[ nCol ]->m_nWidth;
int nWidth = 0;
if (nDesiredWidth != 0)
{
if( nDesiredWidth < 0 )
{
if( nDesiredWidth == -100 )
{
nWidth = m_nTableWidth;
}
else
{
nWidth = min( int( (float( m_nTableWidth ) / 100 ) * abs( nDesiredWidth ) ), m_nTableWidth );
}
}
else
{
nWidth = min( m_dc.ScaleX(nDesiredWidth), m_nTableWidth );
}
nWidth = max(m_pTab->m_arrMinimumWidth[nCol], nWidth);
DETAIL_TRACE( _T("Cell( %d, %d ).DesiredWidth = %d\n"), nCol, nRow, nWidth );
m_pTab->m_arrDesiredWidth[nCol] = max(m_pTab->m_arrDesiredWidth[nCol], nWidth);
DETAIL_TRACE( _T("Col( %d ).DesiredWidth = %d\n"), nCol, m_pTab->m_arrDesiredWidth[nCol] );
}
}
}
}
int CHTMLTableLayout::CalculateTableSize()
{
if( m_pTab->m_nWidth < 0 )
{
if( m_pTab->m_nWidth == -100 )
{
m_nTableWidth = m_nMaxWidth;
}
else
{
m_nTableWidth = min( int( (float( m_nMaxWidth ) / 100 ) * abs( m_pTab->m_nWidth ) ), m_nMaxWidth );
}
}
else if( m_pTab->m_nWidth > 0 )
{
m_nTableWidth = m_dc.ScaleX(m_pTab->m_nWidth);
// m_nTableWidth = min( m_pTab->m_nWidth, m_nMaxWidth );
}
else
{
m_nTableWidth = m_nMaxWidth;
}
// Adjust the table width to at least as wide as the minimum required
m_nTableWidth = max(m_nTableWidth, m_nMinTableWidth);
DETAIL_TRACE( _T("CalculateTableSize=%d\n"), m_nTableWidth );
return m_nTableWidth;
}
int CHTMLTableLayout::GetSpaceNeeded()
{
// Calculate the need for space...
int nSpaceNeeded = 0;
for (int i = 0; i <m_nCols; ++i)
if (m_pTab->m_arrDesiredWidth[i] != 0)
nSpaceNeeded += m_pTab->m_arrDesiredWidth[i] - m_pTab->m_arrMinimumWidth[i];
return nSpaceNeeded;
}
// Allow for tables wider than the available space if the table width or
// Sum of cell widths indicate that it should be. Otherwise, squeeze it in!
// For this to work properly, we need to be able to determine the width of cell
// Contents for cells that have no predetermined width....
//
// Experimenation has revealed the following:
// NoWrap cells will not wrap under any cicumstamnces!
// A Cell will always be at least as wide as it's smallest element
// i.e. image or word, or paragraph if NOWRAP
// A tables width will not exceed the width of the page unless
// the table width is specified, or the sum of the minimum
// widths is wider than the page.
// Cells with a specified width CAN shrink to maintain the
// size of NOWRAP cells. This shrinking will occur until
// it is illegal to do so any further.
void CHTMLTableLayout::LayoutAllSpace(int nSpaceAvailable, int nSpaceNeeded)
{
// Readjust the cells that require space to their
// desired widths.
m_pTab->m_arrLayoutWidth = m_pTab->m_arrMinimumWidth;
for (int i = 0; i < m_nCols; ++i)
{
if (m_pTab->m_arrDesiredWidth[i] != 0)
m_pTab->m_arrLayoutWidth[i] = m_pTab->m_arrDesiredWidth[i];
}
nSpaceAvailable -= nSpaceNeeded;
// If there is some space left, see if any of the cells
// that did not require it, can use it
if (nSpaceAvailable > 0)
{
int nNoSpecCount = 0;
for (int i = 0; i < m_nCols; ++i)
{
if (m_pTab->m_arrDesiredWidth[i] == 0)
{
nNoSpecCount++;
}
}
int nSpacePerCell = 0;
if (nNoSpecCount)
{
// assign space to those cells
nSpacePerCell = max(nSpaceAvailable / nNoSpecCount, 1);
for (int i = 0; i < m_nCols; ++i)
{
if (m_pTab->m_arrDesiredWidth[i] == 0)
{
m_pTab->m_arrLayoutWidth[i] += nSpacePerCell;
}
}
}
else
{
// This might seem wrong, but remember thatthe case where all cells
// fit on the page has already been handled.
// assign space to all cells!
nSpacePerCell = max(nSpaceAvailable / m_nCols, 1);
for (int i = 0; i < m_nCols; ++i)
{
m_pTab->m_arrLayoutWidth[i] += nSpacePerCell;
}
nNoSpecCount = m_nCols;
}
if( nNoSpecCount * nSpacePerCell < nSpaceAvailable )
{
int nLeftOver = nSpaceAvailable % nNoSpecCount;
for (int i = 0; i < m_nCols && nLeftOver; ++i, nLeftOver--)
{
m_pTab->m_arrLayoutWidth[i] += 1;
}
}
}
}
void CHTMLTableLayout::LayoutSpaceProportional(int nSpaceAvailable, int nSpaceNeeded)
{
// Assign remaining space proportional to need
m_pTab->m_arrLayoutWidth = m_pTab->m_arrMinimumWidth;
int nTotalSpaceAdded = 0;
for (int i = 0; i < m_nCols; ++i)
{
if (m_pTab->m_arrDesiredWidth[i] != 0)
{
int nCellSpaceNeeded = m_pTab->m_arrDesiredWidth[i] - m_pTab->m_arrMinimumWidth[i];
int nSpaceAdded = (nSpaceAvailable * nCellSpaceNeeded) / nSpaceNeeded;
m_pTab->m_arrLayoutWidth[i] += nSpaceAdded;
nTotalSpaceAdded += nSpaceAdded;
}
}
}
void CHTMLTableLayout::Layout()
{
DETAIL_TRACE( _T("Detail trace start\n") );
// If we are detemining the maximum size, and the table's width is relative,
// there is no resonable value to return. So set the size
// to -1. The cells will still be measured, but may be subject to the same
// constraint.
MeasureCells();
if (m_nMaxWidth == knFindMaximumWidth && m_pTab->m_nWidth < 0 )
{
m_nTableWidth = -1;
return;
}
// Simple case - If table width not specified, and the nMaxTableWidth is
// small enough to fit, use those widths.
if (!LayoutMaximum())
{
CalculateTableSize();
GetDesiredWidths();
// Calculate the need for space...
int nSpaceNeeded = GetSpaceNeeded();
int nSpaceAvailable = m_nTableWidth - m_nMinTableWidth;
if (nSpaceAvailable >= nSpaceNeeded)
{
LayoutAllSpace( nSpaceAvailable, nSpaceNeeded );
}
else
{
LayoutSpaceProportional( nSpaceAvailable, nSpaceNeeded );
}
}
DETAIL_TRACE( _T("Detail trace end\n\n\n") );
}
| 28.607981 | 183 | 0.677607 | [
"object"
] |
21f742861e6381e279f5d1456ed1b685616b0599 | 798 | cpp | C++ | 3. Структуры данных/2. Полоска #884/[OK]228836.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 19 | 2018-05-19T16:37:14.000Z | 2022-03-23T20:13:43.000Z | 3. Структуры данных/2. Полоска #884/[OK]228836.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 6 | 2020-05-07T21:06:48.000Z | 2020-06-05T17:52:57.000Z | 3. Структуры данных/2. Полоска #884/[OK]228836.cpp | godnoTA/acm.bsu.by | 3e1cf1c545c691de82b5e1d2e0768b41ea581734 | [
"Unlicense"
] | 31 | 2019-03-01T21:41:38.000Z | 2022-03-27T17:56:39.000Z | #include <iostream>
#include <fstream>
#include <stack>
#include <math.h>
#include <vector>
using namespace std;
void flop(stack<int>& a, stack<int>&b) {
while (!b.empty()) {
a.push(b.top());
b.pop();
}
}
int main()
{
ifstream fin("in.txt");
ofstream fout("out.txt");
int n;
fin >> n;
long long size = pow(2, n);
vector<stack<int>> mas(size);
vector<int> ans(size);
for (int i = 0; i < size; i++) {
mas[i].push(i);
}
while (size) {
for (int i = 0; i < size / 2; i++) {
flop(mas[i], mas[size - i - 1]);
}
size /= 2;
}
int j = pow(2, n);
while (!mas[0].empty()) {
ans[mas[0].top()] = j;
mas[0].pop();
j--;
}
for (int i = 0; i < pow(2, n)-1; i++)
fout << ans[i] << " ";
fout << ans[pow(2, n) - 1];
return 0;
} | 17.347826 | 41 | 0.489975 | [
"vector"
] |
21fe5635614e69d136cee4b5938d0d75aca40162 | 519 | cpp | C++ | cpp-prime/c3/ex3-23.cpp | XiaochenCui/cpp-study | b18a2deb3961b095e67243a8df09e50b740701a9 | [
"BSD-2-Clause"
] | null | null | null | cpp-prime/c3/ex3-23.cpp | XiaochenCui/cpp-study | b18a2deb3961b095e67243a8df09e50b740701a9 | [
"BSD-2-Clause"
] | null | null | null | cpp-prime/c3/ex3-23.cpp | XiaochenCui/cpp-study | b18a2deb3961b095e67243a8df09e50b740701a9 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by 崔晓晨 on 2019-07-13.
//
#include <vector>
#include <iostream>
using namespace::std;
void print_vector_int(vector<int> v) {
for (auto it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
int main() {
vector<int> v(10);
int i = 0;
for (auto it = v.begin(); it != v.end(); it++) {
*it = i;
i++;
}
print_vector_int(v);
for (auto it = v.begin(); it != v.end(); it++) {
*it *= 2;
}
print_vector_int(v);
}
| 16.741935 | 52 | 0.472062 | [
"vector"
] |
1d04f6b7da8597949e079e208b0a7207e225869e | 2,919 | hpp | C++ | deps/memkind/src/test/allocator_perf_tool/CommandLine.hpp | steamboatid/keydb | 7aa9296f1bd9773ce47c46ab3ac3800bf870f8fe | [
"BSD-3-Clause"
] | 4,587 | 2019-02-26T06:59:21.000Z | 2021-03-02T20:54:42.000Z | deps/memkind/src/test/allocator_perf_tool/CommandLine.hpp | steamboatid/keydb | 7aa9296f1bd9773ce47c46ab3ac3800bf870f8fe | [
"BSD-3-Clause"
] | 269 | 2019-02-27T19:20:05.000Z | 2021-03-02T06:06:40.000Z | deps/memkind/src/test/allocator_perf_tool/CommandLine.hpp | steamboatid/keydb | 7aa9296f1bd9773ce47c46ab3ac3800bf870f8fe | [
"BSD-3-Clause"
] | 297 | 2019-02-26T22:37:53.000Z | 2021-02-24T03:06:13.000Z | /*
* Copyright (C) 2015 - 2018 Intel Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) 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.
*/
#pragma once
#include <map>
#include <vector>
#include <string>
class CommandLine
{
public:
//Parse and write to val when option exist and strtol(...) > 0, otherwise val is not changed.
//T should be an integer type.
template<class T>
void parse_with_strtol(const std::string &option, T &val)
{
if(args.count(option)) {
T tmp = static_cast<T>(strtol(args[option].c_str(), NULL, 10));
if(tmp > 0)
val = tmp;
else
printf("Warning! Option '%s' may not be set.\n", option.c_str());
} else {
//Do not modify val.
printf("Warning! Option '%s' is not present.\n", option.c_str());
}
}
bool is_option_present(const std::string &option) const
{
return args.count(option);
}
bool is_option_set(const std::string option, std::string val)
{
if(is_option_present(option))
return (args[option] == val);
return false;
}
const std::string &get_option_value(const std::string &option)
{
return args[option];
}
CommandLine(int argc, char *argv[])
{
for (int i=0; i<argc; i++) {
std::string arg(argv[i]);
size_t found = arg.find("=");
if(found != std::string::npos) {
std::string option = arg.substr(0, found);
std::string val = arg.substr(found+1, arg.length());
args[option] = val;
}
}
}
private:
std::map<std::string, std::string> args;
};
| 33.94186 | 97 | 0.644056 | [
"vector"
] |
1d097404ccdb0d482c03eb2860250bd15f9aa774 | 5,655 | cpp | C++ | src/cpp/helper.cpp | Krombik/keysender | 8f22fd4bff1dbef57538d6db0bcb78bc97002d6b | [
"MIT"
] | 12 | 2020-05-13T18:37:39.000Z | 2022-01-08T11:39:28.000Z | src/cpp/helper.cpp | Krombik/keysender | 8f22fd4bff1dbef57538d6db0bcb78bc97002d6b | [
"MIT"
] | 3 | 2020-11-07T20:27:57.000Z | 2021-11-29T01:36:19.000Z | src/cpp/helper.cpp | Krombik/keysender | 8f22fd4bff1dbef57538d6db0bcb78bc97002d6b | [
"MIT"
] | null | null | null | #include "helper.hpp"
BOOL CALLBACK Helper::EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
if (!IsWindowVisible(hWnd) || !IsWindowEnabled(hWnd) || GetWindowTextLengthA(hWnd) == 0)
return TRUE;
WindowInfo *windowInfo = (WindowInfo *)lParam;
if (!windowInfo->className.empty() && classNameGetter(hWnd).compare(windowInfo->className) != 0)
return TRUE;
if (!windowInfo->title.empty() && titleGetter(hWnd).compare(windowInfo->title) != 0)
return TRUE;
windowInfo->hWnd = hWnd;
return FALSE;
}
BOOL CALLBACK Helper::EnumAllWindowsProc(HWND hWnd, LPARAM lParam)
{
if (!IsWindowVisible(hWnd) || !IsWindowEnabled(hWnd) || GetWindowTextLengthA(hWnd) == 0)
return TRUE;
(*reinterpret_cast<std::vector<HWND> *>(lParam)).push_back(hWnd);
return TRUE;
}
BOOL CALLBACK Helper::EnumChildrenProc(HWND hWnd, LPARAM lParam)
{
if (!IsWindowVisible(hWnd) || !IsWindowEnabled(hWnd))
return TRUE;
(*reinterpret_cast<std::vector<HWND> *>(lParam)).push_back(hWnd);
return TRUE;
}
std::wstring Helper::bufferToWstring(Napi::Value val)
{
Napi::Buffer<wchar_t> buffer = val.As<Napi::Buffer<wchar_t>>();
std::wstring wstr;
for (size_t i = 0; i < buffer.ByteLength(); i += 2)
wstr.push_back(wchar_t(buffer.Get(i).As<Napi::Number>().Int32Value() | (buffer.Get(i + 1).As<Napi::Number>().Int32Value() << 8)));
return wstr;
}
std::wstring Helper::classNameGetter(HWND hWnd)
{
std::wstring className;
className.resize(256);
GetClassNameW(hWnd, &className[0], className.size());
className.resize(std::distance(className.begin(), std::search_n(className.begin(), className.end(), 2, 0)));
className.shrink_to_fit();
return className;
}
std::wstring Helper::titleGetter(HWND hWnd)
{
std::wstring title;
title.resize(GetWindowTextLengthA(hWnd) + 1);
GetWindowTextW(hWnd, &title[0], title.size());
title.pop_back();
return title;
}
Napi::Object Helper::windowGetter(HWND hWnd, Napi::Env env)
{
Napi::Object window = Napi::Object::New(env);
window["handle"] = HandleToLong(hWnd);
window["title"] = Napi::Buffer<wchar_t>::New(env, 0);
window["className"] = Napi::Buffer<wchar_t>::New(env, 0);
if (hWnd != NULL)
{
uint8_t titleLength = GetWindowTextLengthA(hWnd);
if (titleLength > 0)
{
std::wstring title = titleGetter(hWnd);
window["title"] = Napi::Buffer<wchar_t>::Copy(env, title.data(), title.size());
}
std::wstring className = classNameGetter(hWnd);
window["className"] = Napi::Buffer<wchar_t>::Copy(env, className.data(), className.size());
}
return window;
}
bool Helper::getKeyCode(Napi::Value key, UINT *keyCode)
{
if (key.IsNumber())
*keyCode = key.As<Napi::Number>();
else
{
const std::string keyName = key.As<Napi::String>();
if (keysDef.count(keyName) == 0)
return false;
*keyCode = keysDef.at(keyName);
}
return true;
}
const std::map<std::string, UINT> Helper::keysDef = {
{"backspace", VK_BACK},
{"tab", VK_TAB},
{"enter", VK_RETURN},
{"shift", VK_SHIFT},
{"ctrl", VK_CONTROL},
{"alt", VK_MENU},
{"pause", VK_PAUSE},
{"capslock", VK_CAPITAL},
{"escape", VK_ESCAPE},
{"space", VK_SPACE},
{"pageup", VK_PRIOR},
{"pagedown", VK_NEXT},
{"end", VK_END},
{"home", VK_HOME},
{"left", VK_LEFT},
{"up", VK_UP},
{"right", VK_RIGHT},
{"down", VK_DOWN},
{"prntscrn", VK_SNAPSHOT},
{"insert", VK_INSERT},
{"delete", VK_DELETE},
{"0", 0x30},
{"1", 0x31},
{"2", 0x32},
{"3", 0x33},
{"4", 0x34},
{"5", 0x35},
{"6", 0x36},
{"7", 0x37},
{"8", 0x38},
{"9", 0x39},
{"a", 0x41},
{"b", 0x42},
{"c", 0x43},
{"d", 0x44},
{"e", 0x45},
{"f", 0x46},
{"g", 0x47},
{"h", 0x48},
{"i", 0x49},
{"j", 0x4a},
{"k", 0x4b},
{"l", 0x4c},
{"m", 0x4d},
{"n", 0x4e},
{"o", 0x4f},
{"p", 0x50},
{"q", 0x51},
{"r", 0x52},
{"s", 0x53},
{"t", 0x54},
{"u", 0x55},
{"v", 0x56},
{"w", 0x57},
{"x", 0x58},
{"y", 0x59},
{"z", 0x5a},
{"lwin", VK_LWIN},
{"rwin", VK_RWIN},
{"num0", VK_NUMPAD0},
{"num0", VK_NUMPAD0},
{"num1", VK_NUMPAD1},
{"num2", VK_NUMPAD2},
{"num3", VK_NUMPAD3},
{"num4", VK_NUMPAD4},
{"num5", VK_NUMPAD5},
{"num6", VK_NUMPAD6},
{"num7", VK_NUMPAD7},
{"num8", VK_NUMPAD8},
{"num9", VK_NUMPAD9},
{"num*", VK_MULTIPLY},
{"num+", VK_ADD},
{"num,", VK_SEPARATOR},
{"num-", VK_SUBTRACT},
{"num.", VK_DECIMAL},
{"num/", VK_DIVIDE},
{"f1", VK_F1},
{"f2", VK_F2},
{"f3", VK_F3},
{"f4", VK_F4},
{"f5", VK_F5},
{"f6", VK_F6},
{"f7", VK_F7},
{"f8", VK_F8},
{"f9", VK_F9},
{"f10", VK_F10},
{"f11", VK_F11},
{"f12", VK_F12},
{"f13", VK_F13},
{"f14", VK_F14},
{"f15", VK_F15},
{"f16", VK_F16},
{"f17", VK_F17},
{"f18", VK_F18},
{"f19", VK_F19},
{"f20", VK_F20},
{"f21", VK_F21},
{"f22", VK_F22},
{"f23", VK_F23},
{"f24", VK_F24},
{"numlock", VK_NUMLOCK},
{"scrolllock", VK_SCROLL},
{"lshift", VK_LSHIFT},
{"rshift", VK_RSHIFT},
{"lctrl", VK_LCONTROL},
{"rctrl", VK_RCONTROL},
{"lalt", VK_LMENU},
{"ralt", VK_RMENU},
{";", VK_OEM_1},
{"=", VK_OEM_PLUS},
{",", VK_OEM_COMMA},
{"-", VK_OEM_MINUS},
{".", VK_OEM_PERIOD},
{"/", VK_OEM_2},
{"~", VK_OEM_3},
{"[", VK_OEM_4},
{"|", VK_OEM_5},
{"]", VK_OEM_6},
{"'", VK_OEM_7}}; | 26.549296 | 138 | 0.550309 | [
"object",
"vector"
] |
1d0db709eaf04207d4248350f31f20036d02993b | 1,198 | cpp | C++ | coder_strike_r2_2014/B/main.cpp | tamimcsedu19/codeforces | 8e61025b99bc0a5b32cb03f736123b39dcc23f61 | [
"Apache-2.0"
] | null | null | null | coder_strike_r2_2014/B/main.cpp | tamimcsedu19/codeforces | 8e61025b99bc0a5b32cb03f736123b39dcc23f61 | [
"Apache-2.0"
] | null | null | null | coder_strike_r2_2014/B/main.cpp | tamimcsedu19/codeforces | 8e61025b99bc0a5b32cb03f736123b39dcc23f61 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <queue>
#define white 1
#define gray 2
#define black 3
using namespace std;
vector<int> G[1005];
int x[1005],y[1005],val[1005];
bool vis[1005];
int dfs(int u)
{
vis[u] = true;
int cost = val[u];
for(int i=0;i<G[u].size();++i)
{
int v = G[u][i];
if(!vis[v])
cost+=dfs(v);
}
return cost;
}
int main()
{
int n;
while(cin>>n && n)
{
for(int i=1;i<=n;++i)
{
cin>>x[i]>>y[i]>>val[i];
G[i].clear();
vis[i] = 0;
}
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n;++j)
{
if(i!=j){
int dist = ceil(sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j])));
if(dist<=30)
{
G[i].push_back(j);
G[j].push_back(i);
}
}
}
int maxv = -1,idx = 0;
for(int i=1;i<=n;++i)
if(!vis[i])
{
int tot = dfs(i);
if(tot>maxv)
{
maxv = tot;
idx = i;
}
}
cout<<idx<<" "<<maxv<<endl;
}
}
| 15.763158 | 85 | 0.384808 | [
"vector"
] |
1d0e653447a95c16cb02bc99a79cf807f1bbe19f | 20,789 | cpp | C++ | src/urGovernor_node.cpp | uproot-robotics/urGovernor | f952ee9f78b551073210fe62874abbd2be44c4d3 | [
"BSD-3-Clause"
] | null | null | null | src/urGovernor_node.cpp | uproot-robotics/urGovernor | f952ee9f78b551073210fe62874abbd2be44c4d3 | [
"BSD-3-Clause"
] | null | null | null | src/urGovernor_node.cpp | uproot-robotics/urGovernor | f952ee9f78b551073210fe62874abbd2be44c4d3 | [
"BSD-3-Clause"
] | 1 | 2020-03-23T17:58:38.000Z | 2020-03-23T17:58:38.000Z | #include <ros/ros.h>
// Shared lib
#include "SerialPacket.h"
// For kinematics
#include "deltaRobot.h"
// Srv and msg types
#include <urGovernor/FetchWeed.h>
#include <urGovernor/MarkUprooted.h>
#include <urGovernor/RemoveWeed.h>
#include <urVision/weedDataArray.h>
#include <urGovernor/SerialWrite.h>
#include <urGovernor/SerialRead.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Vector3.h>
// Parameters to read from configs
std::string fetchWeedServiceName;
std::string markUprootedServiceName;
std::string rmWeedServiceName;
float overallRate;
std::string serialServiceWriteName;
std::string serialServiceReadName;
std::string velocityPublisherName;
int restAngle1, restAngle2, restAngle3;
float cartesianLimitXMax, cartesianLimitXMin, cartesianLimitYMax, cartesianLimitYMin;
float angleLimit;
float initSleepTime;
float actuationTimeOverride;
int minUpdateAngle;
int maxUpdateAngle;
const int relativeAngleFlag = false;
float toolOffset;
float soilOffset;
float targetYGain;
float curYVel;
// Time to actuate end-effector
double endEffectorTime = 0;
bool endEffectorRunning = true;
bool armDown = false;
float stayDownDist = 0;
// Connections to Serial interface services
ros::ServiceClient serialWriteClient;
ros::ServiceClient serialReadClient;
ros::ServiceClient fetchWeedClient;
ros::ServiceClient markUprootedClient;
ros::ServiceClient rmWeedClient;
const int logFetchWeedInterval = 5;
int serialTimeoutMs;
int commandTimeoutSec;
int motorSpeedDegS;
int motorAccelDegSS;
// General parameters for this node
bool readGeneralParameters(ros::NodeHandle nodeHandle)
{
if (!nodeHandle.getParam("fetch_weed_service", fetchWeedServiceName)) return false;
if (!nodeHandle.getParam("mark_uprooted_service", markUprootedServiceName)) return false;
if (!nodeHandle.getParam("remove_weed_service", rmWeedServiceName)) return false;
if (!nodeHandle.getParam("velocity_publisher", velocityPublisherName)) return false;
if (!nodeHandle.getParam("controller_overall_rate", overallRate)) return false;
if (!nodeHandle.getParam("init_sleep_time", initSleepTime)) return false;
if (!nodeHandle.getParam("max_actuation_time_override", actuationTimeOverride)) return false;
if (!nodeHandle.getParam("min_update_angle", minUpdateAngle)) return false;
if (!nodeHandle.getParam("max_update_angle", maxUpdateAngle)) return false;
if (!nodeHandle.getParam("rest_angle_1", restAngle1)) return false;
if (!nodeHandle.getParam("rest_angle_2", restAngle2)) return false;
if (!nodeHandle.getParam("rest_angle_3", restAngle3)) return false;
if (!nodeHandle.getParam("cartesian_limit_x_max", cartesianLimitXMax)) return false;
if (!nodeHandle.getParam("cartesian_limit_x_min", cartesianLimitXMin)) return false;
if (!nodeHandle.getParam("cartesian_limit_y_max", cartesianLimitYMax)) return false;
if (!nodeHandle.getParam("cartesian_limit_y_min", cartesianLimitYMin)) return false;
if (!nodeHandle.getParam("angle_limit", angleLimit)) return false;
if (!nodeHandle.getParam("end_effector_time_s", endEffectorTime)) return false;
if (!nodeHandle.getParam("stay_down_dist_cm", stayDownDist)) return false;
if (!nodeHandle.getParam("tool_offset", toolOffset)) return false;
if (!nodeHandle.getParam("soil_offset", soilOffset)) return false;
if (!nodeHandle.getParam("target_y_gain", targetYGain)) return false;
if (!nodeHandle.getParam("serial_output_service", serialServiceWriteName)) return false;
if (!nodeHandle.getParam("serial_input_service", serialServiceReadName)) return false;
if (!nodeHandle.getParam("serial_timeout_ms", serialTimeoutMs)) return false;
if (!nodeHandle.getParam("command_timeout_sec", commandTimeoutSec)) return false;
if (!nodeHandle.getParam("motor_speed_deg_s", motorSpeedDegS)) return false;
if (!nodeHandle.getParam("motor_accel_deg_s_s", motorAccelDegSS)) return false;
return true;
}
// Send CmdMsg over serial
bool sendCmd(SerialUtils::CmdMsg msg)
{
urGovernor::SerialWrite serialWrite;
// Pack message
std::vector<char> buff;
SerialUtils::pack(buff, msg);
serialWrite.request.command = std::string(buff.begin(), buff.end());
// Send angles to HAL (via calling the serial WRITE client)
return serialWriteClient.call(serialWrite);
}
// Check for callback from motors
bool checkSuccess(SerialUtils::CmdMsg exp_msg)
{
urGovernor::SerialRead serialRead;
SerialUtils::CmdMsg msg;
// Try to read on serial
if (serialReadClient.call(serialRead))
{
std::vector<char> v(serialRead.response.command.begin(), serialRead.response.command.end());
msg.cmd_success = 0;
// Unpack response from read
SerialUtils::unpack(v, msg);
// Check if we are done
if (msg == exp_msg && msg.cmd_success)
{
return true;
}
}
return false;
}
// Wait for success
bool waitSuccess(SerialUtils::CmdMsg exp_msg)
{
urGovernor::SerialRead serialRead;
SerialUtils::CmdMsg msg;
ros::Rate loopRate( 1.0 / (serialTimeoutMs / 1000.0));
ros::WallTime start_time = ros::WallTime::now();
double timeout = commandTimeoutSec;
while (ros::ok() && (ros::WallTime::now()- start_time).toSec() < timeout)
{
// Wait for arm done
// This is done by calling the serial READ client
// This should block until we get a CmdMsg FROM the serial line
if (checkSuccess(exp_msg)) {
ROS_DEBUG("Teensy callback received.");
return true;
}
if (serialReadClient.call(serialRead))
{
std::vector<char> v(serialRead.response.command.begin(), serialRead.response.command.end());
msg.cmd_success = 0;
// Unpack response from read
SerialUtils::unpack(v, msg);
// This should indicate that we are done
if (msg == exp_msg && msg.cmd_success)
{
ROS_DEBUG("Teensy callback received.");
return true;
}
}
else
{
ROS_DEBUG("No response from Teensy ... retrying ...");
}
loopRate.sleep();
}
ROS_ERROR("Timed out waiting for response from Teensy");
return false;
}
// Configure speed and acceleration in degrees/second -- value of 0 is discarded
bool configMotors(int speedDegS, int accelDegSS)
{
SerialUtils::CmdMsg msg = { .cmd_type = SerialUtils::CMDTYPE_CONFIG };
msg.mtr_speed_deg_s = speedDegS;
msg.mtr_accel_deg_s_s = accelDegSS;
sendCmd(msg);
if(!waitSuccess(msg)) {
ROS_ERROR("Unable to configure motors");
return false;
}
return true;
}
// Single set point, updates only, returns immediately
bool sendArmAngles(int angle1Deg, int angle2Deg, int angle3Deg, SerialUtils::CmdMsg* p_msg = NULL)
{
if (angle1Deg == 10)
angle1Deg = 11;
if (angle2Deg == 10)
angle2Deg = 11;
if (angle3Deg == 10)
angle3Deg = 11;
if (angle1Deg < restAngle1 &&
angle2Deg < restAngle2 &&
angle3Deg < restAngle3)
armDown = false;
else
armDown = true;
urGovernor::SerialWrite serialWrite;
// Pack message
SerialUtils::CmdMsg msg = {
.cmd_type = SerialUtils::CMDTYPE_MTRS,
.is_relative = relativeAngleFlag,
.mtr_angles = {(uint32_t)angle1Deg, (uint32_t)angle2Deg, (uint32_t)angle3Deg},
};
// Send angles to HAL (via calling the serial WRITE client)
if (sendCmd(msg))
{
*p_msg = msg;
return true;
}
else
{
ROS_ERROR("Serial write to set motors was NOT successful.");
return false;
}
}
// Single set point, blocks until it has been reached
bool actuateArmAngles(int angle1Deg, int angle2Deg, int angle3Deg, bool calibrate=false)
{
bool sent = false;
SerialUtils::CmdMsg msg;
if (calibrate) {
msg.cmd_type = SerialUtils::CMDTYPE_CAL;
sent = sendCmd(msg);
} else {
sent = sendArmAngles(angle1Deg, angle2Deg, angle3Deg, &msg);
}
if (sent)
{
return waitSuccess(msg);
}
}
// Starts the end effector actuation
bool startEndEffector()
{
if (endEffectorRunning)
return true;
ROS_INFO("START end effector.");
endEffectorRunning = true;
SerialUtils::CmdMsg msg = { .cmd_type = SerialUtils::CMDTYPE_ENDEFF_ON };
sendCmd(msg);
if (!waitSuccess(msg)) {
ROS_ERROR("Unable to start end effector.");
return false;
}
return true;
}
// Stops the end effector actuation
bool stopEndEffector()
{
if (!endEffectorRunning)
return true;
ROS_INFO("STOP end effector.");
endEffectorRunning = false;
SerialUtils::CmdMsg msg = { .cmd_type = SerialUtils::CMDTYPE_ENDEFF_OFF };
sendCmd(msg);
if (!waitSuccess(msg)) {
ROS_ERROR("Unable to stop end effector.");
return false;
}
return true;
}
/* This function performs the function of 'uprooting' a weed
* This function polls the tracker to update the location of the weed
*/
void doConstantTrackingUproot(urGovernor::FetchWeed &fetchWeedSrv)
{
// Continually update these angles
int oldAngle1 = 0,oldAngle2 = 0,oldAngle3 = 0;
// Save the current tracking ID
int currentTrackingID = fetchWeedSrv.response.tracking_id;
// Now we only want to query for this one
fetchWeedSrv.request.request_id = currentTrackingID;
static int lastIDOutOfRange = -1;
// Time this whole operation
ros::WallTime startActuation, startUproot;
double timeDelta = 0;
bool weedReached = false;
// Set start time
startActuation = ros::WallTime::now();
bool keepGoing = true;
// Do a continual update on the weeds location
ros::Rate loopRate(overallRate);
SerialUtils::CmdMsg last_msg;
bool command_sent = false;
// Main Loop for constant tracking
while (ros::ok() && keepGoing)
{
// Get the most recent coordinates
if (!fetchWeedClient.call(fetchWeedSrv))
{
keepGoing = false;
}
else
{
//// Process the current coordinates
float targetX = fetchWeedSrv.response.weed.point.x;
// Add offset here to compensate for motion
float targetY = fetchWeedSrv.response.weed.point.y + targetYGain*curYVel;
float targetZ = fetchWeedSrv.response.weed.point.z;
float targetSize = fetchWeedSrv.response.weed.size_cm;
// IF cartesian coordinate are out of range
if (targetX > cartesianLimitXMax ||
targetX < cartesianLimitXMin ||
targetY > cartesianLimitYMax ||
targetY < cartesianLimitYMin )
{
if (targetY < cartesianLimitYMin)
{
keepGoing = false;
urGovernor::RemoveWeed rmWeedSrv;
rmWeedSrv.request.tracking_id = currentTrackingID;
rmWeedClient.call(rmWeedSrv);
}
if (fetchWeedSrv.request.request_id != lastIDOutOfRange)
{
lastIDOutOfRange = fetchWeedSrv.request.request_id;
ROS_INFO("COORDS OUT OF RANGE of delta arm [(x,y,size)=(%.1f,%.1f,%.1f)]",targetX,targetY,targetSize);
}
// We are out of range!
keepGoing = false;
}
else
{
/* Create coordinates in the Delta Arm Reference
* This conversion requires a 'rotation matrix'
* to be applied to comply with Delta library coordinates.
* x' = x*cos(theta) - y*sin(theta)
* y' = x*sin(theta) + y*cos(theta)
* Based on our setup, theta = +60 degrees AND X and Y coordinates are switched
*/
float x_coord = (float)(targetY*(0.5) - (targetX)*(0.866));
float y_coord = (float)(targetY*(0.866) + (targetX)*(0.5));
float z_coord = (float)targetZ + soilOffset; // z = 0 IS AT THE GROUND (z = is always positive)
/* Calculate angles for Delta arm */
robot_position(x_coord, y_coord, z_coord);
// Get the resulting angles from kinematics
int angle1Deg, angle2Deg, angle3Deg;
getArmAngles(&angle1Deg, &angle2Deg, &angle3Deg);
if (angle1Deg < 0)
angle1Deg = 0;
if (angle2Deg < 0)
angle2Deg = 0;
if (angle3Deg < 0)
angle3Deg = 0;
// IF calculated angles are out of range
if (angle1Deg > angleLimit ||
angle2Deg > angleLimit ||
angle3Deg > angleLimit ||
angle1Deg < 0 ||
angle2Deg < 0 ||
angle3Deg < 0 )
{
ROS_INFO("ANGLES OUT OF RANGE of delta arm [(a1,a2,a3)=(%i,%i,%i)]",angle1Deg,angle2Deg,angle3Deg);
keepGoing = false;
}
// ELSE if any of the angles have changed, make call to update the arm angles
else if(abs(angle1Deg - oldAngle1) > minUpdateAngle ||
abs(angle2Deg - oldAngle2) > minUpdateAngle ||
abs(angle3Deg - oldAngle3) > minUpdateAngle)
{
// If we've already sent an arm angle and this
if(command_sent && (
abs(angle1Deg - oldAngle1) > maxUpdateAngle ||
abs(angle2Deg - oldAngle2) > maxUpdateAngle ||
abs(angle3Deg - oldAngle3) > maxUpdateAngle
))
{
ROS_ERROR("Angle update is too large... skipping ...");
}
else
{
oldAngle1 = angle1Deg;
oldAngle2 = angle2Deg;
oldAngle3 = angle3Deg;
ROS_INFO("UPDATE weed @ (%.1f,%.1f,%.1f) [cm] -> (%i,%i,%i) [degrees]",
targetX, targetY, targetZ,
angle1Deg, angle2Deg, angle3Deg);
startEndEffector();
// Update the arm angles
if (!sendArmAngles(angle1Deg, angle2Deg, angle3Deg, &last_msg))
{
// This is a Fatal issue ...
ROS_ERROR("Could not actuate motors to specified arm angles");
ros::requestShutdown();
keepGoing = false;
} else {
command_sent = true;
}
}
}
}
}
// IF weed has been reached by the arm
if(weedReached)
{
timeDelta = (ros::WallTime::now() - startUproot).toSec();
if (timeDelta >= endEffectorTime)
{
keepGoing = false;
}
}
// ELSE if we haven't set our flag but the motors are done their current motion
else if (!weedReached && command_sent && checkSuccess(last_msg))
{
weedReached = true;
startUproot = ros::WallTime::now();
}
// ELSE
else
{
timeDelta = (ros::WallTime::now() - startActuation).toSec();
// Override if we've hit our actuation time override
if (timeDelta >= actuationTimeOverride)
{
weedReached = true;
startUproot = ros::WallTime::now();
}
}
// After send the arm angle update, sleep for the loop rate
loopRate.sleep();
}
// IF not weedReached
if (!weedReached)
{
// Check if we should mark it as uprooted anyways
timeDelta = (ros::WallTime::now() - startActuation).toSec();
// Override if we've hit our actuation time override
if (timeDelta >= actuationTimeOverride)
{
weedReached = true;
}
}
urGovernor::MarkUprooted markUprootedSrv;
// weedReached indicates the success of this call
markUprootedSrv.request.success = command_sent;
// Mark this weed as uprooted (or back to ready if not successful)
markUprootedSrv.request.tracking_id = currentTrackingID;
if (!markUprootedClient.call(markUprootedSrv))
{
ROS_INFO("Governor -- Error calling markUprooted Srv (call to tracker_node).");
}
return;
}
// velocity callback from tracker
void updateVelocity(const geometry_msgs::Vector3::ConstPtr& msg){
curYVel = msg->y;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "urGovernor_node");
ros::NodeHandle nh;
ros::NodeHandle nodeHandle("~");
int fetchWeedLogs = 0;
if (!readGeneralParameters(nodeHandle))
{
ROS_ERROR("Could not read general parameters for urGovernor_node.");
ros::requestShutdown();
}
serialWriteClient = nh.serviceClient<urGovernor::SerialWrite>(serialServiceWriteName);
ros::service::waitForService(serialServiceWriteName);
serialReadClient = nh.serviceClient<urGovernor::SerialRead>(serialServiceReadName);
ros::service::waitForService(serialServiceReadName);
// Subscribe to service from tracker
fetchWeedClient = nh.serviceClient<urGovernor::FetchWeed>(fetchWeedServiceName);
ros::service::waitForService(fetchWeedServiceName);
urGovernor::FetchWeed fetchWeedSrv;
urGovernor::FetchWeed fetchWeedSrvLast;
// Subscribe to second service from tracker
markUprootedClient = nh.serviceClient<urGovernor::MarkUprooted>(markUprootedServiceName);
ros::service::waitForService(markUprootedServiceName);
rmWeedClient = nh.serviceClient<urGovernor::RemoveWeed>(rmWeedServiceName);
ros::service::waitForService(rmWeedServiceName);
// Subscribe to velocity updates from tracker
curYVel = 0;
ros::Subscriber velocitySub = nodeHandle.subscribe(
velocityPublisherName,
1,
updateVelocity
);
/* Initializing Kinematics */
// Set tool offset (tool id == 0, x, y, z )
robot_tool_offset(0, 0, 0, -(toolOffset));
// Default deltarobot setup
deltarobot_setup();
stopEndEffector();
// CALIBRATE arms
if (!actuateArmAngles(restAngle1, restAngle2, restAngle3, true))
{
ROS_ERROR("Could not Initialize arm positions.");
ros::requestShutdown();
}
// CONFIGURE motors
if (!configMotors(motorSpeedDegS, motorAccelDegSS))
{
ROS_ERROR("Unable to configure motors... continuing with default speed & accel");
}
// Sleep for startup to ensure we get our camera stream
ros::Duration(initSleepTime).sleep();
/*
* Main loop for urGovernor
*/
auto putArmsUp = [&] {
if (::armDown) {
if (!actuateArmAngles(restAngle1, restAngle2, restAngle3))
{
ROS_ERROR("Could not Reset arm positions.");
ros::requestShutdown();
}
}
stopEndEffector();
};
auto pointDist = [] (geometry_msgs::Point p1, geometry_msgs::Point p2) -> float {
float dx = p1.x - p2.x;
float dy = p1.y - p2.y;
float dz = p1.z - p2.z;
float dist = sqrt( dx*dx + dy*dy + dz*dz );
ROS_DEBUG("Got distance: %f", dist);
return dist;
};
ros::Rate loopRate(overallRate);
while (ros::ok())
{
fetchWeedSrv.request.caller = 1;
// Set to -1 to indicate we just want the top valid
fetchWeedSrv.request.request_id = -1;
// IF we do get a new weed
if (fetchWeedClient.call(fetchWeedSrv))
{
// stay down if the weeds are close
if (pointDist(fetchWeedSrv.response.weed.point,
fetchWeedSrvLast.response.weed.point) > stayDownDist)
putArmsUp();
doConstantTrackingUproot(fetchWeedSrv);
fetchWeedSrvLast = fetchWeedSrv;
}
else
{
putArmsUp();
if (fetchWeedLogs % logFetchWeedInterval == 1)
{
ROS_INFO("Governor -- no weeds are current.");
}
fetchWeedLogs++;
}
ros::spinOnce();
loopRate.sleep();
}
return 0;
}
| 32.790221 | 122 | 0.60633 | [
"vector"
] |
1d13c2ed994a93aff432de78c0784f1b499f474b | 12,866 | cpp | C++ | flash-graph/libgraph-algs/betweenness_centrality.cpp | kjhyun824/uncertain-graph-engine | 17aa1b8b5d03b03200583797ab0cfb4a42ff8845 | [
"Apache-2.0"
] | 140 | 2015-01-02T21:28:55.000Z | 2015-12-22T01:25:03.000Z | flash-graph/libgraph-algs/betweenness_centrality.cpp | kjhyun824/uncertain-graph-engine | 17aa1b8b5d03b03200583797ab0cfb4a42ff8845 | [
"Apache-2.0"
] | 160 | 2016-11-07T18:37:33.000Z | 2020-03-10T22:57:07.000Z | flash-graph/libgraph-algs/betweenness_centrality.cpp | kjhyun824/uncertain-graph-engine | 17aa1b8b5d03b03200583797ab0cfb4a42ff8845 | [
"Apache-2.0"
] | 25 | 2016-11-14T04:31:29.000Z | 2020-07-28T04:58:44.000Z | /**
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Disa Mhembere (disa@jhu.edu)
*
* This file is part of FlashGraph.
*
* 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.
*/
#ifdef PROFILER
#include <gperftools/profiler.h>
#endif
#include <vector>
#include "thread.h"
#include "io_interface.h"
#include "container.h"
#include "concurrency.h"
#include "vertex_index.h"
#include "graph_engine.h"
#include "graph_config.h"
#include "FGlib.h"
#include "save_result.h"
using namespace fg;
namespace {
short bfs_max_dist;
/* `update` phase is where BC is updated */
vertex_id_t g_source_vertex;
enum btwn_phase_t
{
bfs,
back_prop,
bc_summation,
};
btwn_phase_t g_alg_phase = bfs;
class betweenness_vertex: public compute_directed_vertex
{
float btwn_cent; // per-vertex btwn_cent
float delta;
int sigma;
short dist;
bool bfs_visited;
public:
betweenness_vertex(vertex_id_t id): compute_directed_vertex(id) {
btwn_cent = 0;
delta = 0;
sigma = 0 ;
dist = -1;
bfs_visited = false;
}
void init(int sigma, short dist) {
this->sigma = sigma;
this->dist = dist;
this->delta = 0;
this->bfs_visited = false;
}
// Used for save_query join
float get_result() const {
return btwn_cent;
}
short get_dist() const {
return dist;
}
void set_dist(short dist) {
this->dist = dist;
}
void set_sigma(int sigma) {
this->sigma = sigma;
}
bool is_bfs_visited() const {
return bfs_visited;
}
void set_visited(bool visited) {
this->bfs_visited = visited;
}
void run(vertex_program &prog);
void run(vertex_program &prog, const page_vertex &vertex);
void run_on_message(vertex_program &, const vertex_message &msg1);
};
typedef std::shared_ptr<std::vector<vertex_id_t> > vertex_set_ptr;
// Store activated vertex IDs per iteration in the bfs phase
typedef std::map<int, std::vector<vertex_set_ptr> > vertex_map_t;
class bfs_vertex_program: public vertex_program_impl<betweenness_vertex>
{
std::vector<vertex_set_ptr> bfs_visited_vertices; // Vertex set visited from this thread
short max_dist; // Keep track of max dist so we can activate greatest when bp-ing
public:
bfs_vertex_program() {
max_dist = 0;
}
typedef std::shared_ptr<bfs_vertex_program> ptr;
static ptr cast2(vertex_program::ptr prog) {
return std::static_pointer_cast<bfs_vertex_program, vertex_program>(prog);
}
void add_visited_bfs(vertex_id_t vid) {
max_dist = get_graph().get_curr_level();
// BOOST_LOG_TRIVIAL(info) << "The current per thread max_dist is " << max_dist << "\n";
assert(max_dist == ((short)bfs_visited_vertices.size()) - 1);
bfs_visited_vertices.back()->push_back(vid);
}
virtual void run_on_engine_start() {
bfs_visited_vertices.push_back(vertex_set_ptr(
new std::vector<vertex_id_t>()));
}
virtual void run_on_iteration_end() {
bfs_visited_vertices.push_back(vertex_set_ptr(
new std::vector<vertex_id_t>()));
}
void collect_vertices(vertex_map_t &vertices) {
vertex_map_t::const_iterator it = vertices.find(get_partition_id());
if (it != vertices.end())
BOOST_LOG_TRIVIAL(info) << "part" << it->first << "already exists";
assert(it == vertices.end());
vertices.insert(vertex_map_t::value_type(get_partition_id(),
bfs_visited_vertices));
}
short get_max_dist() const {
return max_dist;
}
};
class bp_vertex_program: public vertex_program_impl<betweenness_vertex>
{
std::shared_ptr<vertex_map_t> all_vertices;
std::vector<vertex_set_ptr> bfs_visited_vertices;
public:
bp_vertex_program(std::shared_ptr<vertex_map_t> vertices) {
this->all_vertices = vertices;
}
virtual void run_on_engine_start() {
vertex_map_t::const_iterator it = all_vertices->find(get_partition_id());
assert(it != all_vertices->end());
bfs_visited_vertices = it->second;
// Drop the empty set added at the end of the last iteration in bfs.
assert(bfs_visited_vertices.back()->empty());
bfs_visited_vertices.pop_back();
// Drop the last set of visited vertices because we have already activated them.
while ((short)bfs_visited_vertices.size() > bfs_max_dist) {
bfs_visited_vertices.pop_back();
}
assert((short)bfs_visited_vertices.size() == bfs_max_dist);
}
virtual void run_on_iteration_end() {
if (!bfs_visited_vertices.empty()) {
vertex_set_ptr vertices = bfs_visited_vertices.back();
activate_vertices(vertices->data(), vertices->size());
bfs_visited_vertices.pop_back();
}
}
};
class bfs_vertex_program_creater: public vertex_program_creater
{
public:
vertex_program::ptr create() const {
return vertex_program::ptr(new bfs_vertex_program());
}
};
class bp_vertex_program_creater: public vertex_program_creater
{
std::shared_ptr<vertex_map_t> all_vertices;
public:
bp_vertex_program_creater() {
all_vertices = std::shared_ptr<vertex_map_t>(new vertex_map_t());
}
vertex_map_t &get_vertex_map() {
return *all_vertices;
}
vertex_program::ptr create() const {
return vertex_program::ptr(new bp_vertex_program(all_vertices));
}
};
class bfs_message: public vertex_message
{
vertex_id_t sender_id;
short parent_dist;
int parent_sigma;
public:
bfs_message(vertex_id_t id, short sender_dist, int sigma):
vertex_message(sizeof(bfs_message), true) {
sender_id = id;
parent_dist = sender_dist;
parent_sigma = sigma;
}
const vertex_id_t get_sender_id() const {
return sender_id;
}
const short get_parent_dist() const {
return parent_dist;
}
const int get_parent_sigma() const {
return parent_sigma;
}
};
/** Back propagate message */
class bp_message: public vertex_message
{
float delta;
int sigma;
short dist;
public:
bp_message(short dist, float delta, int sigma):
vertex_message(sizeof(bp_message), false) {
this->delta = delta;
this->sigma = sigma;
this->dist = dist;
}
const float get_sender_delta() const {
return delta;
}
const int get_sender_sigma() const {
return sigma;
}
const short get_sender_dist() const {
return dist;
}
};
void betweenness_vertex::run(vertex_program &prog) {
switch (g_alg_phase) {
case btwn_phase_t::bfs:
{
if (is_bfs_visited())
return;
directed_vertex_request req(prog.get_vertex_id(*this), edge_type::OUT_EDGE);
request_partial_vertices(&req, 1);
((bfs_vertex_program&)prog).
add_visited_bfs(prog.get_vertex_id(*this));
break;
}
case btwn_phase_t::back_prop:
{
directed_vertex_request req(prog.get_vertex_id(*this), edge_type::IN_EDGE);
request_partial_vertices(&req, 1);
break;
}
case btwn_phase_t::bc_summation:
{
if (prog.get_vertex_id(*this) != g_source_vertex)
btwn_cent += delta;
break;
}
default:
assert(0);
}
}
void betweenness_vertex::run(vertex_program &prog, const page_vertex &vertex)
{
switch (g_alg_phase) {
case btwn_phase_t::bfs :
{
bfs_visited = true;
int num_dests = vertex.get_num_edges(OUT_EDGE);
if (num_dests == 0) return;
edge_seq_iterator it = vertex.get_neigh_seq_it(OUT_EDGE, 0, num_dests);
bfs_message msg(vertex.get_id(), this->dist, this->sigma);
prog.multicast_msg(it, msg);
break;
}
case btwn_phase_t::back_prop :
{
/* NOTE: Sending to all in_neighs instead of only P's ... */
int num_dests = vertex.get_num_edges(IN_EDGE);
edge_seq_iterator it = vertex.get_neigh_seq_it(IN_EDGE, 0, num_dests);
bp_message msg(this->dist, this->delta, this->sigma);
prog.multicast_msg(it, msg);
break;
}
default:
assert(0);
}
}
void betweenness_vertex::run_on_message(vertex_program &prog, const vertex_message &msg1) {
switch (g_alg_phase) {
case btwn_phase_t::bfs:
{
const bfs_message &msg = (const bfs_message &) msg1;
if (this->dist < 0) {
this->dist = msg.get_parent_dist() + 1;
}
if (this->dist == msg.get_parent_dist() + 1) {
this->sigma = this->sigma + msg.get_parent_sigma();
}
break;
}
case btwn_phase_t::back_prop:
{
const bp_message &msg = (const bp_message &) msg1;
// Ignore this message if you're not a parent on the path
if (this->dist != msg.get_sender_dist() - 1) {
return;
}
// Now we know it's only parents
if (msg.get_sender_sigma() != 0) { // If msg.get_sender_sigma() == 0 do nothing
delta = delta + (((float)sigma/msg.get_sender_sigma())
* (1 + msg.get_sender_delta()));
}
break;
}
default:
assert(0);
}
}
class btwn_initializer: public vertex_initializer
{
compute_vertex* source_vertex;
public:
btwn_initializer(compute_vertex *v) {
source_vertex = v;
}
virtual void init(compute_vertex &v) {
betweenness_vertex &bv = (betweenness_vertex &) v;
&v == source_vertex ? bv.init(1,0) : bv.init(0,-1); // sigma, dist
}
};
/** For back prop phase where we activate vertices
with only dist = max_dist. Also resets the bfs bit
to unvisited.
*/
class activate_by_dist_filter: public vertex_filter {
short dist;
public:
activate_by_dist_filter (short dist) {
this->dist = dist;
}
bool keep(vertex_program &prog, compute_vertex &v) {
betweenness_vertex &bv = (betweenness_vertex &) v;
bool is_max_v = bv.get_dist() == dist;
return is_max_v;
}
};
}
namespace fg
{
fm::vector::ptr compute_betweenness_centrality(FG_graph::ptr fg,
const std::vector<vertex_id_t>& ids)
{
bool directed = fg->get_graph_header().is_directed_graph();
if (!directed) {
BOOST_LOG_TRIVIAL(error)
<< "This algorithm currently works on a directed graph";
return fm::vector::ptr();
}
graph_index::ptr index = NUMA_graph_index<betweenness_vertex>::create(
fg->get_graph_header());
graph_engine::ptr graph = fg->create_engine(index);
BOOST_LOG_TRIVIAL(info) << "Starting Betweenness Centrality ...";
BOOST_LOG_TRIVIAL(info) << "prof_file: " << graph_conf.get_prof_file().c_str();
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStart(graph_conf.get_prof_file().c_str());
#endif
struct timeval start, end;
gettimeofday(&start, NULL);
BOOST_FOREACH (vertex_id_t id , ids) {
if (!graph->get_num_edges(id))
continue;
g_source_vertex = id;
bfs_max_dist = 0; // Must reset bfs dist for each vertex
// BFS phase. Inintialize start vert(ex)(ices)
g_alg_phase = btwn_phase_t::bfs;
BOOST_LOG_TRIVIAL(info) << "Starting BFS for vertex: " << g_source_vertex;
graph->init_all_vertices(vertex_initializer::ptr(
new btwn_initializer(&(graph->get_vertex(g_source_vertex)))));
graph->start(&g_source_vertex, 1, vertex_initializer::ptr(),
vertex_program_creater::ptr(new bfs_vertex_program_creater()));
graph->wait4complete();
std::vector<vertex_program::ptr> programs;
graph->get_vertex_programs(programs);
bp_vertex_program_creater *bp_prog_creater_ptr = new bp_vertex_program_creater();
vertex_program_creater::ptr bp_prog_creater
= vertex_program_creater::ptr(bp_prog_creater_ptr);
BOOST_FOREACH(vertex_program::ptr prog, programs) {
bfs_vertex_program::cast2(prog)->collect_vertices(
bp_prog_creater_ptr->get_vertex_map());
bfs_max_dist = std::max(bfs_max_dist,
bfs_vertex_program::cast2(prog)->get_max_dist());
}
BOOST_LOG_TRIVIAL(info) << "Max dist for bfs is: " << bfs_max_dist << "...";
if (bfs_max_dist > 0) {
// Back propagation phase
BOOST_LOG_TRIVIAL(info) << "Starting back_prop phase for vertex: "
<< g_source_vertex << "...";
g_alg_phase = btwn_phase_t::back_prop;
std::shared_ptr<vertex_filter> filter =
std::shared_ptr<vertex_filter>(new activate_by_dist_filter(bfs_max_dist));
graph->start(filter, std::move(bp_prog_creater));
graph->wait4complete();
BOOST_LOG_TRIVIAL(info) << "BC summation step";
g_alg_phase = bc_summation;
graph->start_all();
graph->wait4complete();
}
}
gettimeofday(&end, NULL);
fm::detail::mem_vec_store::ptr res_store = fm::detail::mem_vec_store::create(
fg->get_num_vertices(), safs::params.get_num_nodes(),
fm::get_scalar_type<float>());
graph->query_on_all(vertex_query::ptr(
new save_query<float, betweenness_vertex>(res_store)));
#if 0
BOOST_LOG_TRIVIAL(info) << "Printing betweenness vector:";
ret->print();
#endif
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStop();
#endif
BOOST_LOG_TRIVIAL(info) << boost::format("It takes %1% seconds")
% time_diff(start, end);
return fm::vector::create(res_store);
}
}
| 26.257143 | 91 | 0.713897 | [
"vector"
] |
1d16b830cc77c9e167155a9ceace5167d9279881 | 6,126 | hpp | C++ | include/map.hpp | SrinidhiSreenath/ENPM808X-Midterm-InformedRRTStar | 01e092b4795e3267cb6b0e37321cd103afdbc90b | [
"MIT"
] | 4 | 2018-10-10T00:42:05.000Z | 2020-07-09T07:46:38.000Z | include/map.hpp | SrinidhiSreenath/ENPM808X-Midterm-InformedRRTStar | 01e092b4795e3267cb6b0e37321cd103afdbc90b | [
"MIT"
] | 8 | 2018-10-24T04:28:31.000Z | 2018-11-06T21:07:27.000Z | include/map.hpp | SrinidhiSreenath/ENPM808X-Midterm-InformedRRTStar | 01e092b4795e3267cb6b0e37321cd103afdbc90b | [
"MIT"
] | 1 | 2019-10-13T01:12:37.000Z | 2019-10-13T01:12:37.000Z | /****************************************************************************
* MIT License
* Copyright (c) 2018 Srinidhi Sreenath
*
* 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.
******************************************************************************/
/**
* @file map.hpp
* @author Srinidhi Sreenath (SrinidhiSreenath)
* @date 10/7/2018
* @version 1.0
*
* @brief Map class declaration
*
* @section DESCRIPTION
*
* Header file for class Map.
*
*/
#ifndef INCLUDE_MAP_HPP_
#define INCLUDE_MAP_HPP_
// CPP Headers
#include <utility>
#include <vector>
/**
* @brief Class Map
* The following class Map aids in storing the layout of the environment
*/
class Map {
public:
std::vector<std::vector<double>>
obstacleList; ///< Variable to hold list of obstacles. Each obstacle is
///< defined as a vector of points in the order [x1, y1,
///< x2, y2 ... xN, yN]
std::vector<std::pair<double, double>>
workspaceBoundary; ///< Variable to hold workspace boundary as a vector
///< of paired points [x,y]
std::vector<double> boundaryXlimits; ///< Variable to hold min and max limits
///< of the workspace boundary on x axis
std::vector<double> boundaryYlimits; ///< Variable to hold min and max limits
///< of the workspace boundary on y axis
/**
* @brief Default constructor for Map
*
* @param none
* @return void
*/
Map();
/**
* @brief Destructor for Map
*
* @param none
* @return void
*/
~Map();
/**
* @brief setter function to set workspace boundary
*
* @param boundary is a vector of paired points [x,y] defining the boundary
* vertices
* @return void
*/
void setWorkspaceBoundary(
const std::vector<std::pair<double, double>> &boundary);
/**
* @brief function to add obstacle to a Map
*
* @param obstacle is a vector of double points [x1,y1,x2,y2...xN,yN]
* defining the boundary vertices of an obstacle
* @return void
*/
void addObstacle(const std::vector<double> &obstacle);
/**
* @brief checks if the second point lies on the line segment connecting
* first point and third point.
*
* @param firstPoint, secondPoint and thirdPoint are each pair of double
* [x,y] points in workspace
* @return true if second point lies on the line segment, false if it
* doesn't
*/
bool onSegment(const std::pair<double, double> &firstPoint,
const std::pair<double, double> &secondPoint,
const std::pair<double, double> &thirdPoint);
/**
* @brief determines the oreintation i.e clockwise, anti-clockwise or
* collinearity of three ordered points.
*
* @param firstPoint, secondPoint and thirdPoint are each pair of
* double [x,y] points in workspace
* @return 0 if collinear, 1 if clockwise, 2 if anti-clockwise orientation
* as integer
*/
int getOrientation(const std::pair<double, double> &firstPoint,
const std::pair<double, double> &secondPoint,
const std::pair<double, double> &thirdPoint);
/**
* @brief determines if the line segments of tree node and new node, and
* first vertex and second vertex intersect
*
* @param treeNode is the node in the tree as pair of double points [x,y]
* newNode is the node in the workspace as pair of double points
* [x,y]
* firstVertex, secondVertex are the vertices of an edge of an
* obstacle as pair of double points [x,y] each
* @return true if the line segments intersect, false if they don't
*/
bool isIntersect(const std::pair<double, double> &treeNode,
const std::pair<double, double> &newNode,
const std::pair<double, double> &firstVertex,
const std::pair<double, double> &secondVertex);
/**
* @brief determines if the given node is out of map bounds
*
* @param node is the point [x,y] in workspace as pair of double
* @return true if node is out of boundary, false otherwise
*/
bool isOutofMap(const std::pair<double, double> &node);
/**
* @brief determines if the given node can be added to the existing tree in
* the workspace without any conflicts
*
* @param treeNode is the node in the tree as pair of double points [x,y]
* newNode is the node in the workspace as pair of double points
* [x,y]
* @return true if the treeNode can be added to the tree, false otherwise
*/
bool isValidNode(const std::pair<double, double> &treeNode,
const std::pair<double, double> &newNode);
/**
* @brief function to reset the map by clearing the member variables
*
* @param none
* @return void
*/
void resetMap();
};
#endif // INCLUDE_MAP_HPP_
| 36.035294 | 80 | 0.617532 | [
"vector"
] |
1d19d47ee995cb46ff6c6b52f31963a4b4130ef0 | 309 | cpp | C++ | LeetCode/cpp/1018.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 279 | 2019-02-19T16:00:32.000Z | 2022-03-23T12:16:30.000Z | LeetCode/cpp/1018.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 2 | 2019-03-31T08:03:06.000Z | 2021-03-07T04:54:32.000Z | LeetCode/cpp/1018.cpp | ZintrulCre/LeetCode_Crawler | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 12 | 2019-01-29T11:45:32.000Z | 2019-02-04T16:31:46.000Z | class Solution {
public:
vector<bool> prefixesDivBy5(vector<int> &A) {
int sum = 0;
vector<bool> ret(A.size(), false);
for (int i = 0; i < A.size(); ++i) {
sum = (sum * 2 + A[i]) % 5;
ret[i] = sum == 0 ? true : false;
}
return ret;
}
};
| 23.769231 | 49 | 0.433657 | [
"vector"
] |
9192d80227cc096833879657d411082fd21f35ee | 12,366 | cpp | C++ | main.cpp | GaZ3ll3/kifmm3d | 31fa5bb208e6d257041f49f461edac8358ae3c1e | [
"MIT"
] | 1 | 2016-10-11T01:25:52.000Z | 2016-10-11T01:25:52.000Z | main.cpp | GaZ3ll3/kifmm3d | 31fa5bb208e6d257041f49f461edac8358ae3c1e | [
"MIT"
] | 2 | 2016-10-27T05:01:46.000Z | 2016-10-31T23:30:36.000Z | main.cpp | GaZ3ll3/bbfmm3d | 31fa5bb208e6d257041f49f461edac8358ae3c1e | [
"MIT"
] | null | null | null | /*
* main.cpp
*
* Created on: Oct 9, 2016
* Author: Yimin Zhong
*/
#include <iostream>
#include "kernel.h"
#include "bicgstab.h"
#include "gmres.h"
#include "molecule.h"
#include "singular.h"
int main() {
#ifdef RUN_OMP
omp_set_num_threads(omp_get_max_threads());
#endif
/*
* allocating source, target locations and weights
*/
vector<point> coarseSource;
vector<point> coarseTarget;
vector<point> coarseTriangle;
vector<double> coarseWeight;
vector<double> coarseNormalX;
vector<double> coarseNormalY;
vector<double> coarseNormalZ;
/*
* cube radius and sphere radius
*/
double cRadius = 2.0;
/*
* slice x slice grid on each face.
*/
int slice = 32;
vector<point> centers;
vector<double> radius;
centers.push_back(point(0., 0., 0.));
centers.push_back(point(1.0, 0., 0.));
centers.push_back(point(1., 1., 0.));
centers.push_back(point(0.0, 1., 0.));
radius.push_back(1.0);
radius.push_back(1.0);
radius.push_back(1.0);
radius.push_back(1.0);
moleculeProjection(centers, radius, coarseSource, coarseWeight, coarseNormalX, coarseNormalY, coarseNormalZ,
coarseTriangle,
cRadius, slice);
coarseTarget = coarseSource;
std::cout << "source point: " << coarseSource.size() << std::endl;
int np = 4;
int maxPoint = 160;
int maxLevel = 10;
double k = 0.03;
double dE = 80.0;
double dI = 2.0;
/*
* not necessary to handle singularity in function
*/
auto eval_G0 = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return 1.0 / 4 / M_PI / r;
};
auto eval_Gk = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return exp(-k * r) / 4 / M_PI / r;
};
auto eval_pG0x = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return -(a.x - b.x) / 4 / M_PI / r / d;
};
auto eval_pG0y = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return -(a.y - b.y) / 4 / M_PI / r / d;
};
auto eval_pG0z = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return -(a.z - b.z) / 4 / M_PI / r / d;
};
auto eval_pGkx = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return -(a.x - b.x) * exp(-k * r) * (k * r + 1) / 4 / M_PI / r / d;
};
auto eval_pGky = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return -(a.y - b.y) * exp(-k * r) * (k * r + 1) / 4 / M_PI / r / d;
};
auto eval_pGkz = [&](point &a, point &b) {
double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
double r = sqrt(d);
return -(a.z - b.z) * exp(-k * r) * (k * r + 1) / 4 / M_PI / r / d;
};
auto Mapping = [&](vector<point> &source, vector<point> &target, vector<point> triangle, vector<double> &weight,
vector<double> &normalX, vector<double> &normalY, vector<double> &normalZ, VectorXd &phi) {
int N = (int) source.size();
assert(phi.rows() == 2 * N);
kernel G0, Gk, pG0x, pG0y, pG0z, pGkx, pGky, pGkz;
G0.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_G0);
else return eval_G0(a, b);
};
Gk.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_Gk);
else return eval_Gk(a, b);
};
pG0x.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pG0x);
else return eval_pG0x(a, b);
};
pG0y.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pG0y);
else return eval_pG0y(a, b);
};
pG0z.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pG0z);
else return eval_pG0z(a, b);
};
pGkx.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pGkx);
else return eval_pGkx(a, b);
};
pGky.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pGky);
else return eval_pGky(a, b);
};
pGkz.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pGkz);
else return eval_pGkz(a, b);
};
// f = partial phi/partial n
// g = phi
// Phi = g | f
VectorXd f(N);
VectorXd gX(N), gY(N), gZ(N);
for (int i = 0; i < N; ++i) {
f(i) = phi(i + N) * weight[i];
gX(i) = phi(i) * normalX[i] * weight[i];
gY(i) = phi(i) * normalY[i] * weight[i];
gZ(i) = phi(i) * normalZ[i] * weight[i];
}
G0.initialize(np, source, target, f, N, N, maxPoint, maxLevel);
pG0x.initialize(np, source, target, gX, N, N, maxPoint, maxLevel);
pG0y.initialize(np, source, target, gY, N, N, maxPoint, maxLevel);
pG0z.initialize(np, source, target, gZ, N, N, maxPoint, maxLevel);
Gk.initialize(np, source, target, f, N, N, maxPoint, maxLevel);
pGkx.initialize(np, source, target, gX, N, N, maxPoint, maxLevel);
pGky.initialize(np, source, target, gY, N, N, maxPoint, maxLevel);
pGkz.initialize(np, source, target, gZ, N, N, maxPoint, maxLevel);
VectorXd retG0(N), retGk(N), retpG0X(N), retpG0Y(N), retpG0Z(N), retpGkX(N), retpGkY(N), retpGkZ(N);
G0.run(retG0);
Gk.run(retGk);
pG0x.run(retpG0X);
pG0y.run(retpG0Y);
pG0z.run(retpG0Z);
pGkx.run(retpGkX);
pGky.run(retpGkY);
pG0z.run(retpGkZ);
VectorXd ret(2 * N);
ret.segment(0, N) = 0.5 * phi.segment(0, N) + retpG0X + retpG0Y + retpG0Z - retG0;
ret.segment(N, N) = 0.5 * phi.segment(0, N) - retpGkX - retpGkY - retpGkZ + dI / dE * retGk;
return ret;
};
int N = (int) coarseSource.size();
auto coarseMap = [&](VectorXd &phi) {
return Mapping(coarseSource, coarseTarget, coarseTriangle, coarseWeight, coarseNormalX, coarseNormalY,
coarseNormalZ, phi);
};
VectorXd input(2 * N);
VectorXd start(2 * N);
for (int i = 0; i < N; ++i) {
input(i) = 1.0 / dE / 4.0 / M_PI / radius[0] / (1 + k * radius[0]);
input(i + N) = -1.0 / dI / 4.0 / M_PI / radius[0] / radius[0];
}
//
// start = input;
start.setZero();
VectorXd output(2 * N);
output.setZero();
for (int i = 0; i < N; ++i) {
for (int j = 0; j < centers.size(); ++j) {
double d = norm(centers[j].x - coarseSource[i].x, centers[j].y - coarseSource[i].y, centers[j].z -
coarseSource[i].z);
output(i) += 1.0 / dI / 4.0 / M_PI / d;
}
}
gmres(coarseMap, output, start, 200, 40, sqrt(1e-5));
// std::cout << "coarse error :" << (start - 2 * input).norm() /2/ input.norm() << std::endl;
auto RXN = [&](vector<point> &source, vector<point> &target, vector<point> triangle, vector<double> &weight,
vector<double> &normalX, vector<double> &normalY, vector<double> &normalZ, VectorXd &phi) {
int N = (int) source.size();
int M = (int) target.size();
assert(phi.rows() == 2 * N);
kernel G0, Gk, pG0x, pG0y, pG0z, pGkx, pGky, pGkz;
G0.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_G0);
else return eval_G0(a, b);
};
Gk.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_Gk);
else return eval_Gk(a, b);
};
pG0x.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pG0x);
else return eval_pG0x(a, b);
};
pG0y.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pG0y);
else return eval_pG0y(a, b);
};
pG0z.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pG0z);
else return eval_pG0z(a, b);
};
pGkx.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pGkx);
else return eval_pGkx(a, b);
};
pGky.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pGky);
else return eval_pGky(a, b);
};
pGkz.eval = [&](point &a, point &b) {
if (a == b) return singularIntegral(a, triangle, radius[a.ballId], centers, eval_pGkz);
else return eval_pGkz(a, b);
};
// f = partial phi/partial n
// g = phi
// Phi = g | f
VectorXd f(N);
VectorXd gX(N), gY(N), gZ(N);
for (int i = 0; i < N; ++i) {
f(i) = phi(i + N) * weight[i];
gX(i) = phi(i) * normalX[i] * weight[i];
gY(i) = phi(i) * normalY[i] * weight[i];
gZ(i) = phi(i) * normalZ[i] * weight[i];
}
G0.initialize(np, source, target, f, N, M, maxPoint, maxLevel);
pG0x.initialize(np, source, target, gX, N, M, maxPoint, maxLevel);
pG0y.initialize(np, source, target, gY, N, M, maxPoint, maxLevel);
pG0z.initialize(np, source, target, gZ, N, M, maxPoint, maxLevel);
Gk.initialize(np, source, target, f, N, M, maxPoint, maxLevel);
pGkx.initialize(np, source, target, gX, N, M, maxPoint, maxLevel);
pGky.initialize(np, source, target, gY, N, M, maxPoint, maxLevel);
pGkz.initialize(np, source, target, gZ, N, M, maxPoint, maxLevel);
VectorXd retG0(M), retGk(M), retpG0X(M), retpG0Y(M), retpG0Z(M), retpGkX(M), retpGkY(M), retpGkZ(M);
G0.run(retG0);
Gk.run(retGk);
pG0x.run(retpG0X);
pG0y.run(retpG0Y);
pG0z.run(retpG0Z);
pGkx.run(retpGkX);
pGky.run(retpGkY);
pG0z.run(retpGkZ);
VectorXd ret(M);
ret = 0.5 * (dE / dI * (retpGkX + retpGkY + retpGkZ) - (retpG0X + retpG0Y + retpG0Z) + retG0 - retGk);
return ret;
};
vector<point> rxnTarget = centers;
VectorXd result = RXN(coarseSource, rxnTarget, coarseTriangle,
coarseWeight, coarseNormalX, coarseNormalY,
coarseNormalZ, start);
for (int i = 0; i < centers.size(); ++i) {
std::cout << "energy of atom " << i << " : " << result(i) << std::endl;
}
// double rxn_ret = 1.0 / 8. / M_PI / radius[0] * (1.0 / dE / (1 + k) - 1.0 / dI);
//
// std::cout << "rxn energy error: " << (RXN(coarseSource, rxnTarget, coarseTriangle, coarseWeight, coarseNormalX,
// coarseNormalY,
// coarseNormalZ,
// start)(0) - rxn_ret) / rxn_ret << std::endl;
}
| 36.913433 | 117 | 0.506227 | [
"vector"
] |
9198539846e89721b6e8ab356a01552e3fd44837 | 6,500 | cpp | C++ | src/ModelSelection/ModelSelection.cpp | andreas-hjortgaard/master_thesis | bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb | [
"MIT"
] | null | null | null | src/ModelSelection/ModelSelection.cpp | andreas-hjortgaard/master_thesis | bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb | [
"MIT"
] | null | null | null | src/ModelSelection/ModelSelection.cpp | andreas-hjortgaard/master_thesis | bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb | [
"MIT"
] | 1 | 2018-10-20T00:43:36.000Z | 2018-10-20T00:43:36.000Z | /* Conditional Random Fields for Object Localization
* Master thesis source code
*
* Authors:
* Andreas Christian Eilschou (jwb226@alumni.ku.dk)
* Andreas Hjortgaard Danielsen (gxn961@alumni.ku.dk)
*
* Department of Computer Science
* University of Copenhagen
* Denmark
*
* Date: 27-08-2012
*/
// functions for doing model selection using either a validation set or by using
// cross validation
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include "DataManager.h"
#include "ConditionalRandomField.h"
#include "Measures/LossMeasures.h"
#include "ObjectiveFunctions/ObjectiveFunction.h"
#include "ObjectiveFunctions/Gradient.h"
#include "ObjectiveFunctions/StochasticGradient.h"
#include "Learning/GradientDescent.h"
#include "Learning/StochasticGradientDescent.h"
#include "Types.h"
using namespace std;
RecallOverlap modelSelection(Weights &wNew,
double lambda,
Weights &initial,
DataManager &trainingSet,
DataManager &validationSet,
ConditionalRandomField &crf,
ObjectiveFunction &objective,
Gradient &gradient,
GradientDescent &learningAlg) {
// set lambda
objective.setLambda(lambda);
gradient.setLambda(lambda);
cout << "Trying lambda = " << lambda << endl;
wNew = learningAlg.learnWeights(initial);
validationSet.setWeights(wNew);
// check loss on validation set
SearchIx indices;
RecallOverlap recallOverlap;
recallOverlap = computeRecallOverlap(validationSet, indices, crf.getStepSize());
return recallOverlap;
}
// perform model selection on validation set
// min and max determines the power of 2 to be used such that the range of
// parameter values is [2^min, 2^max]
double modelSelection(DataManager &trainingSet,
DataManager &validationSet,
ConditionalRandomField &crf,
ObjectiveFunction &objective,
Gradient &gradient,
GradientDescent &learningAlg,
int min,
int max) {
// outline:
// - train with lambda = 2^min on training set
// - check loss on validation set
// - repeat until lambda = 2^max
double lambda, bestLambda;
double bestRecallOverlap = -9999999999.;
int weightDim = crf.getWeightDim();
Weights w(weightDim, 0.1);
Weights wNew(weightDim, 0.0);
RecallOverlap recallOverlap;
// test different lambda values
for (int p=min; p<=max; p++) {
lambda = pow((double)10, p);
recallOverlap = modelSelection(wNew, lambda, w, trainingSet, validationSet, crf, objective, gradient, learningAlg);
// update best lambda
if (recallOverlap.AUC > bestRecallOverlap) {
bestRecallOverlap = recallOverlap.AUC;
bestLambda = lambda;
}
}
return bestLambda;
}
// perform model selection on validation set
// min and max determines the power of 2 to be used such that the range of
// parameter values is [2^min, 2^max]
double modelSelectionStochastic(DataManager &trainingSet,
DataManager &validationSet,
ConditionalRandomField &crf,
ObjectiveFunction &objective,
StochasticGradient &gradient,
StochasticGradientDescent &learningAlg,
int min,
int max) {
// outline:
// - train with lambda = 2^min on training set
// - check loss on validation set
// - repeat until lambda = 2^max
double lambda, bestLambda;
double bestRecallOverlap = -9999999999.;
int weightDim = crf.getWeightDim();
Weights w(weightDim, 0.1);
Weights wNew(weightDim, 0.0);
// test different lambda values
for (int p=min; p<=max; p++) {
// set lambda
lambda = pow((double)10, p);
objective.setLambda(lambda);
gradient.setLambda(lambda);
cout << "Trying lambda = " << lambda << endl;
learningAlg.initializeLearningRate(w, 0.1, 0, false);
wNew = learningAlg.learnWeights(w);
//crf.setWeights(wNew);
validationSet.setWeights(wNew);
// check loss on validation set
SearchIx indices;
RecallOverlap recallOverlap;
recallOverlap = computeRecallOverlap(validationSet, indices, crf.getStepSize());
// save learned weights in file
ostringstream os;
os << "lambda_" << lambda << ".txt";
ofstream weightFile(os.str().c_str());
if (!weightFile) {
cerr << "Could not open file..." << endl;
}
// store result in file
for (int i=0; i<weightDim; i++) {
weightFile << wNew[i] << endl;
}
weightFile.close();
// update best lambda
if (recallOverlap.AUC > bestRecallOverlap) {
bestRecallOverlap = recallOverlap.AUC;
bestLambda = lambda;
}
}
return bestLambda;
}
// perform model selection by cross-validation
// min and max determines the power of 2 to be used such that the range of
// parameter values is [2^min, 2^max]
/*double crossValidation(DataManager &trainingSet,
DataManager &validationSet,
ConditionalRandomField &crf,
ObjectiveFunction &objective,
Gradient &gradient,
GradientDescent &learningAlg,
int folds,
int min,
int max) {
// outline:
// - divide training set into k equally large subsets
// - train with lambda = 2^min on k-1 subsets
// - compute loss on the k'th subset
// - repeat for all subsets
// - compute average loss
// - repeat until lambda = 2^max
int numImages, numSubsets;
Images train;
SearchIx subsetTrain, subsetVal;
// set up objective functions
PseudoLikelihood pseudolik(trainingSet, crf);
PseudoLikelihoodGradient pseudolikgrad(trainingSet, crf);
LBFGS lbfgs(pseudolik, pseudolikgrad);
// retrieve images
numImages = trainingSet.getNumImages();
train = trainingSet.getImages();
// divide training set into k subsets
srand(time(NULL)); // seed for randomizer
random_shuffle(train.begin(), train.end());
for (int i=0; i<k; i++) {
// create subsets
subsetTrain =
// train model
// compute loss
// accumulate average loss
}
return 2.0;
}*/
| 27.896996 | 119 | 0.631385 | [
"object",
"model"
] |
91a2992e2af79a2f246617cb13d8b347f34b85f8 | 36,805 | cpp | C++ | src/xtf/xtf.cpp | WPI-ARC/xtf | 526b8a31a36f7bd9745267bb3e21646eb4dbb7bc | [
"BSD-2-Clause"
] | 4 | 2015-10-11T03:30:13.000Z | 2022-03-19T08:21:20.000Z | src/xtf/xtf.cpp | WPI-ARC/xtf | 526b8a31a36f7bd9745267bb3e21646eb4dbb7bc | [
"BSD-2-Clause"
] | null | null | null | src/xtf/xtf.cpp | WPI-ARC/xtf | 526b8a31a36f7bd9745267bb3e21646eb4dbb7bc | [
"BSD-2-Clause"
] | 2 | 2015-10-11T03:30:13.000Z | 2016-11-07T01:18:11.000Z | #include "stdlib.h"
#include "stdio.h"
#include <vector>
#include <string>
#include <sstream>
#include "string.h"
#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <typeinfo>
#include <libxml++/libxml++.h>
#include <arc_utilities/pretty_print.hpp>
#include "xtf/xtf.hpp"
using namespace XTF;
KeyValue::KeyValue(bool value)
{
Zero();
type_ = KV_BOOLEAN;
bool_val_ = value;
}
KeyValue::KeyValue(long value)
{
Zero();
type_ = KV_INTEGER;
int_val_ = value;
}
KeyValue::KeyValue(double value)
{
Zero();
type_ = KV_DOUBLE;
flt_val_ = value;
}
KeyValue::KeyValue(std::string value)
{
Zero();
type_ = KV_STRING;
str_val_ = value;
}
KeyValue::KeyValue(std::vector<bool> value)
{
Zero();
type_ = KV_BOOLEANLIST;
bool_list_ = value;
}
KeyValue::KeyValue(std::vector<long> value)
{
Zero();
type_ = KV_INTEGERLIST;
int_list_ = value;
}
KeyValue::KeyValue(std::vector<double> value)
{
Zero();
type_ = KV_DOUBLELIST;
flt_list_ = value;
}
KeyValue::KeyValue(std::vector<std::string> value)
{
Zero();
type_ = KV_STRINGLIST;
str_list_ = value;
}
void KeyValue::Zero()
{
bool_val_ = false;
flt_val_ = 0.0;
int_val_ = 0;
str_val_.clear();
bool_list_.clear();
flt_list_.clear();
int_list_.clear();
str_list_.clear();
}
KeyValue::TYPES KeyValue::Type()
{
return type_;
}
void KeyValue::SetValue(bool value)
{
Zero();
type_ = KV_BOOLEAN;
bool_val_ = value;
}
void KeyValue::SetValue(long value)
{
Zero();
type_ = KV_INTEGER;
int_val_ = value;
}
void KeyValue::SetValue(double value)
{
Zero();
type_ = KV_DOUBLE;
flt_val_ = value;
}
void KeyValue::SetValue(std::string value)
{
Zero();
type_ = KV_STRING;
str_val_ = value;
}
void KeyValue::SetValue(std::vector<bool> value)
{
Zero();
type_ = KV_BOOLEANLIST;
bool_list_ = value;
}
void KeyValue::SetValue(std::vector<long> value)
{
Zero();
type_ = KV_INTEGERLIST;
int_list_ = value;
}
void KeyValue::SetValue(std::vector<double> value)
{
Zero();
type_ = KV_DOUBLELIST;
flt_list_ = value;
}
void KeyValue::SetValue(std::vector<std::string> value)
{
Zero();
type_ = KV_STRINGLIST;
str_list_ = value;
}
bool KeyValue::BoolValue()
{
if (type_ == KV_BOOLEAN)
{
return bool_val_;
}
else
{
throw std::invalid_argument("KeyValue is not a BOOLEAN type");
}
}
long KeyValue::IntegerValue()
{
if (type_ == KV_INTEGER)
{
return int_val_;
}
else
{
throw std::invalid_argument("KeyValue is not an INTEGER type");
}
}
double KeyValue::DoubleValue()
{
if (type_ == KV_DOUBLE)
{
return flt_val_;
}
else
{
throw std::invalid_argument("KeyValue is not a DOUBLE type");
}
}
std::string KeyValue::StringValue()
{
if (type_ == KV_STRING)
{
return str_val_;
}
else
{
throw std::invalid_argument("KeyValue is not a STRING type");
}
}
std::vector<bool> KeyValue::BoolListValue()
{
if (type_ == KV_BOOLEANLIST)
{
return bool_list_;
}
else
{
throw std::invalid_argument("KeyValue is not a BOOLEANLIST type");
}
}
std::vector<long> KeyValue::IntegerListValue()
{
if (type_ == KV_INTEGERLIST)
{
return int_list_;
}
else
{
throw std::invalid_argument("KeyValue is not an INTEGERLIST type");
}
}
std::vector<double> KeyValue::DoubleListValue()
{
if (type_ == KV_DOUBLELIST)
{
return flt_list_;
}
else
{
throw std::invalid_argument("KeyValue is not a DOUBLELIST type");
}
}
std::vector<std::string> KeyValue::StringListValue()
{
if (type_ == KV_STRINGLIST)
{
return str_list_;
}
else
{
throw std::invalid_argument("KeyValue is not a STRINGLIST type");
}
}
std::string KeyValue::GetValueString()
{
std::ostringstream strm;
if (type_ == KV_BOOLEAN)
{
strm << PrettyPrint::PrettyPrint(bool_val_);
}
else if (type_ == KV_INTEGER)
{
strm << int_val_;
}
else if (type_ == KV_DOUBLE)
{
strm << flt_val_;
}
else if (type_ == KV_STRING)
{
strm << str_val_;
}
else if (type_ == KV_BOOLEANLIST)
{
strm << PrettyPrint::PrettyPrint(bool_list_);
}
else if (type_ == KV_INTEGERLIST)
{
strm << PrettyPrint::PrettyPrint(int_list_);
}
else if (type_ == KV_DOUBLELIST)
{
strm << PrettyPrint::PrettyPrint(flt_list_);
}
else if (type_ == KV_STRINGLIST)
{
strm << PrettyPrint::PrettyPrint(str_list_);
}
return strm.str();
}
std::string KeyValue::GetTypeString()
{
if (type_ == KV_BOOLEAN)
{
return std::string("boolean");
}
else if (type_ == KV_INTEGER)
{
return std::string("integer");
}
else if (type_ == KV_DOUBLE)
{
return std::string("double");
}
else if (type_ == KV_STRING)
{
return std::string("string");
}
else if (type_ == KV_BOOLEANLIST)
{
return std::string("booleanlist");
}
else if (type_ == KV_INTEGERLIST)
{
return std::string("integerlist");
}
else if (type_ == KV_DOUBLELIST)
{
return std::string("doublelist");
}
else if (type_ == KV_STRINGLIST)
{
return std::string("stringlist");
}
else
{
throw std::invalid_argument("Invalid KeyValue type ID");
}
}
std::ostream& operator<<(std::ostream& strm, KeyValue& keyvalue)
{
strm << "type: " << keyvalue.GetTypeString() << " value: " << keyvalue.GetValueString();
return strm;
}
void State::VerifySize(std::vector<double> element)
{
if (data_length_ == 0 && element.size() != 0)
{
data_length_ = element.size();
}
else if (element.size() != 0)
{
if (data_length_ != element.size())
{
throw std::invalid_argument("Inconsistent trajectory state fields");
}
}
}
State::State(std::vector<double> desiredP, std::vector<double> desiredV, std::vector<double> desiredA, std::vector<double> actualP, std::vector<double> actualV, std::vector<double> actualA, int sequence, timespec timing)
{
data_length_ = 0;
VerifySize(desiredP);
position_desired_ = desiredP;
VerifySize(desiredV);
velocity_desired_ = desiredV;
VerifySize(desiredA);
acceleration_desired_ = desiredA;
VerifySize(actualP);
position_actual_ = actualP;
VerifySize(actualV);
velocity_actual_ = actualV;
VerifySize(actualA);
acceleration_actual_ = actualA;
sequence_ = sequence;
timing_ = timing;
}
std::vector<std::string> State::ListExtras()
{
std::vector<std::string> keys;
std::map<std::string, KeyValue>::iterator itr;
for(itr = extras_.begin(); itr != extras_.end(); ++itr)
{
std::ostringstream key_stream;
key_stream << itr->first;
keys.push_back(key_stream.str());
}
return keys;
}
std::ostream& operator<<(std::ostream& strm, State& state)
{
strm << "State #" << state.sequence_ << " at:\nsecs: " << state.timing_.tv_sec << "\nnsecs: " << state.timing_.tv_nsec << "\ndesired:\nposition:";
for (unsigned int i = 0; i < state.position_desired_.size(); i++)
{
strm << " " << state.position_desired_[i];
}
strm << "\nvelocity:";
for (unsigned int i = 0; i < state.velocity_desired_.size(); i++)
{
strm << " " << state.velocity_desired_[i];
}
strm << "\nacceleration:";
for (unsigned int i = 0; i < state.acceleration_desired_.size(); i++)
{
strm << " " << state.acceleration_desired_[i];
}
strm << "\nactual:\nposition:";
for (unsigned int i = 0; i < state.position_actual_.size(); i++)
{
strm << " " << state.position_actual_[i];
}
strm << "\nvelocity:";
for (unsigned int i = 0; i < state.velocity_actual_.size(); i++)
{
strm << " " << state.velocity_actual_[i];
}
strm << "\nacceleration:";
for (unsigned int i = 0; i < state.acceleration_actual_.size(); i++)
{
strm << " " << state.acceleration_actual_[i];
}
strm << "\nextras:";
std::map<std::string, KeyValue>::iterator itr;
for(itr = state.extras_.begin(); itr != state.extras_.end(); ++itr)
{
strm << "\nkey: " << itr->first << " " << itr->second;
}
return strm;
}
Trajectory::Trajectory(std::string uid, TRAJTYPES traj_type, TIMINGS timing, std::string robot, std::string generator, std::string root_frame, std::string target_frame, std::vector<State> trajectory_data, std::vector<std::string> tags)
{
robot_ = robot;
uid_ = uid;
generator_ = generator;
root_frame_ = root_frame;
target_frame_ = target_frame;
tags_ = tags;
data_type_ = Trajectory::POSE;
traj_type_ = traj_type;
timing_ = timing;
trajectory_ = trajectory_data;
for (size_t index = 0; index < trajectory_.size(); index++)
{
if (trajectory_[index].data_length_ != 7)
{
throw std::invalid_argument("Pose data is not 7 doubles [X,Y,Z,X,Y,Z,W]");
}
}
}
Trajectory::Trajectory(std::string uid, TRAJTYPES traj_type, TIMINGS timing, std::string robot, std::string generator, std::vector<std::string> joint_names, std::vector<State> trajectory_data, std::vector<std::string> tags)
{
robot_ = robot;
uid_ = uid;
generator_ = generator;
joint_names_ = joint_names;
tags_ = tags;
data_type_ = Trajectory::JOINT;
traj_type_ = traj_type;
timing_ = timing;
trajectory_ = trajectory_data;
for (size_t index = 0; index < trajectory_.size(); index++)
{
if (trajectory_[index].data_length_ != joint_names_.size())
{
throw std::invalid_argument("Inconsistent joint names and joint data");
}
}
}
Trajectory::Trajectory(std::string uid, TRAJTYPES traj_type, TIMINGS timing, std::string robot, std::string generator, std::string root_frame, std::string target_frame, std::vector<std::string> tags)
{
robot_ = robot;
uid_ = uid;
generator_ = generator;
root_frame_ = root_frame;
target_frame_ = target_frame;
tags_ = tags;
data_type_ = Trajectory::POSE;
traj_type_ = traj_type;
timing_ = timing;
}
Trajectory::Trajectory(std::string uid, TRAJTYPES traj_type, TIMINGS timing, std::string robot, std::string generator, std::vector<std::string> joint_names, std::vector<std::string> tags)
{
robot_ = robot;
uid_ = uid;
generator_ = generator;
joint_names_ = joint_names;
tags_ = tags;
data_type_ = Trajectory::JOINT;
traj_type_ = traj_type;
timing_ = timing;
}
size_t Trajectory::size()
{
return trajectory_.size();
}
void Trajectory::push_back(State& val)
{
if (data_type_ == Trajectory::JOINT && (val.data_length_ != joint_names_.size()))
{
throw std::invalid_argument("Inconsistent joint names and joint data");
}
else if (data_type_ == Trajectory::POSE && (val.data_length_ != 7))
{
throw std::invalid_argument("Pose data is not 7 doubles [X,Y,Z,X,Y,Z,W]");
}
else
{
trajectory_.push_back(val);
}
}
State& Trajectory::at(size_t idx)
{
if (idx < trajectory_.size())
{
return trajectory_[idx];
}
else
{
std::ostringstream error_stream;
error_stream << "Index " << idx << " is out of range";
throw std::out_of_range(error_stream.str());
}
}
State& Trajectory::operator[](size_t idx)
{
if (idx < trajectory_.size())
{
return trajectory_[idx];
}
else
{
std::ostringstream error_stream;
error_stream << "Index " << idx << " is out of range";
throw std::out_of_range(error_stream.str());
}
}
std::ostream& operator<<(std::ostream& strm, Trajectory& traj)
{
if (traj.traj_type_ == traj.GENERATED)
{
strm << "Generated ";
}
else if (traj.traj_type_ == traj.RECORDED)
{
strm << "Recorded ";
}
if (traj.data_type_ == traj.JOINT)
{
strm << "Joint ";
}
else if (traj.data_type_ == traj.POSE)
{
strm << "Pose ";
}
strm << "Trajectory:\nUID: " << traj.uid_;
if (traj.data_type_ == traj.JOINT)
{
strm << "\nJoint names:";
for (unsigned int i = 0; i < traj.joint_names_.size(); i++)
{
strm << " " << traj.joint_names_[i];
}
}
else if (traj.data_type_ == traj.POSE)
{
strm << "\nRoot frame: " << traj.root_frame_;
strm << "\nTarget frame: " << traj.target_frame_;
}
strm << "\nRobot: " << traj.robot_ << "\nGenerator: " << traj.generator_;
if (traj.timing_ == traj.TIMED)
{
strm << "\nTiming: timed";
}
else if (traj.timing_ == traj.UNTIMED)
{
strm << "\nTiming: untimed";
}
strm << "\nTags:";
for (unsigned int i = 0; i < traj.tags_.size(); i++)
{
strm << " " << traj.tags_[i];
}
strm << "\nTrajectory data:";
for (unsigned int i = 0; i < traj.trajectory_.size(); i++)
{
strm << "\n---\n" << traj.trajectory_[i];
}
return strm;
}
Trajectory Parser::ParseTraj(std::string filename)
{
try
{
xmlpp::DomParser parser;
parser.set_substitute_entities();
parser.parse_file(filename);
if (parser)
{
const xmlpp::Node* root = parser.get_document()->get_root_node();
/* Read the header data */
// Get the header nodes
xmlpp::Node::NodeList info = root->get_children("info");
xmlpp::Node* infoEL = info.front();
xmlpp::Node::NodeList type = infoEL->get_children("type");
xmlpp::Node* typeEL = type.front();
xmlpp::Node::NodeList tgs = infoEL->get_children("tags");
xmlpp::Node* tagsEL = tgs.front();
xmlpp::Node::NodeList rf = typeEL->get_children("root_frame");
xmlpp::Node* rfEL = rf.front();
xmlpp::Node::NodeList tf = typeEL->get_children("target_frame");
xmlpp::Node* tfEL = tf.front();
xmlpp::Node::NodeList jn = typeEL->get_children("joint_names");
xmlpp::Node* jnEL = jn.front();
// Get the trajectory uid
const xmlpp::Element* rootEL = dynamic_cast<const xmlpp::Element*>(root);
xmlpp::Attribute* uidAttrib = rootEL->get_attribute("uid");
std::string uid;
if (uidAttrib)
{
uid = CleanString(uidAttrib->get_value());
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted");
}
// Get the info attributes
xmlpp::Element* infoAttribs = dynamic_cast<xmlpp::Element*>(infoEL);
xmlpp::Attribute* robotAttrib = infoAttribs->get_attribute("robot");
xmlpp::Attribute* generatorAttrib = infoAttribs->get_attribute("generator");
std::string robot;
std::string generator;
if (robotAttrib && generatorAttrib)
{
robot = CleanString(robotAttrib->get_value());
generator = CleanString(generatorAttrib->get_value());
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted");
}
// Get the type attributes
xmlpp::Element* typeAttribs = dynamic_cast<xmlpp::Element*>(typeEL);
xmlpp::Attribute* timingAttrib = typeAttribs->get_attribute("timing");
xmlpp::Attribute* trajtypeAttrib = typeAttribs->get_attribute("traj_type");
xmlpp::Attribute* datatypeAttrib = typeAttribs->get_attribute("data_type");
Trajectory::TIMINGS timing;
Trajectory::TRAJTYPES traj_type;
Trajectory::DATATYPES data_type;
if (timingAttrib && trajtypeAttrib && datatypeAttrib)
{
std::string timingstr = CleanString(timingAttrib->get_value());
std::string trajtypestr = CleanString(trajtypeAttrib->get_value());
std::string datatypestr = CleanString(datatypeAttrib->get_value());
if (timingstr.compare("timed") == 0)
{
timing = Trajectory::TIMED;
}
else if (timingstr.compare("untimed") == 0)
{
timing = Trajectory::UNTIMED;
}
else
{
throw std::invalid_argument("Invalid timing type");
}
if (trajtypestr.compare("generated") == 0)
{
traj_type = Trajectory::GENERATED;
}
else if (trajtypestr.compare("recorded") == 0)
{
traj_type = Trajectory::RECORDED;
}
else
{
throw std::invalid_argument("Invalid trajectory type");
}
if (datatypestr.compare("joint") == 0)
{
data_type = Trajectory::JOINT;
}
else if (datatypestr.compare("pose") == 0)
{
data_type = Trajectory::POSE;
}
else
{
throw std::invalid_argument("Invalid trajectory data type");
}
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted");
}
// Get the type data
std::string root_frame;
std::string target_frame;
std::vector<std::string> joint_names;
if (data_type == Trajectory::JOINT)
{
xmlpp::ContentNode* jointnamesText = dynamic_cast<xmlpp::ContentNode*>(jnEL->get_children().front());
if (jointnamesText && !jointnamesText->is_white_space())
{
joint_names = ReadStrings(jointnamesText->get_content());
}
else
{
throw std::invalid_argument("Type fields do not match type attribute");
}
}
else if (data_type == Trajectory::POSE)
{
xmlpp::ContentNode* rootframeText = dynamic_cast<xmlpp::ContentNode*>(rfEL->get_children().front());
xmlpp::ContentNode* targetframeText = dynamic_cast<xmlpp::ContentNode*>(tfEL->get_children().front());
if (rootframeText && targetframeText && !rootframeText->is_white_space() && !targetframeText->is_white_space())
{
root_frame = CleanString(rootframeText->get_content());
target_frame = CleanString(targetframeText->get_content());
}
else
{
throw std::invalid_argument("Type fields do not match type attribute");
}
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted");
}
// Get the tags
std::vector<std::string> tags;
// First, we need to check that current file actually has tags
xmlpp::Node* tagN = tagsEL->get_children().front();
if (tagN != NULL && (tagsEL->get_children().size() > 0))
{
xmlpp::ContentNode* tagsText = dynamic_cast<xmlpp::ContentNode*>(tagN);
if (tagsText != NULL && !tagsText->is_white_space())
{
tags = ReadStrings(tagsText->get_content());
}
else
{
//throw std::invalid_argument("XTF file is malformed or otherwise corrupted");
}
}
////////////////////////////////////////////////////////////////////////////////
/* Read the trajectory data */
// Get the state nodes
xmlpp::Node::NodeList states = root->get_children("states");
xmlpp::Node* statesEL = states.front();
xmlpp::Node::NodeList statelist = statesEL->get_children("state");
// Run through the state nodes
std::vector<State> trajectory_data;
for (xmlpp::Node::NodeList::iterator iter = statelist.begin(); iter != statelist.end(); ++iter)
{
// Get the desired data
xmlpp::Node::NodeList desired = ((xmlpp::Node*)*iter)->get_children("desired");
xmlpp::Node* desiredEL = desired.front();
std::vector< std::vector<double> > desiredData = ReadStateFields(desiredEL);
// Get the actual data
xmlpp::Node::NodeList actual = ((xmlpp::Node*)*iter)->get_children("actual");
xmlpp::Node* actualEL = actual.front();
std::vector< std::vector<double> > actualData = ReadStateFields(actualEL);
// Get the extras
std::map<std::string, KeyValue> extras;
xmlpp::Node::NodeList extralist = ((xmlpp::Node*)*iter)->get_children("extra");
for (xmlpp::Node::NodeList::iterator xiter = extralist.begin(); xiter != extralist.end(); ++xiter)
{
xmlpp::Element* extraElement = dynamic_cast<xmlpp::Element*>(*xiter);
xmlpp::Attribute* nameAttrib = extraElement->get_attribute("name");
xmlpp::Attribute* typeAttrib = extraElement->get_attribute("type");
xmlpp::Attribute* valueAttrib = extraElement->get_attribute("value");
if (nameAttrib && typeAttrib && valueAttrib)
{
std::string real_type(typeAttrib->get_value());
if (real_type.compare("BOOLEAN") == 0 || real_type.compare("boolean") == 0)
{
bool value = false;
std::string value_string(valueAttrib->get_value());
if (value_string.compare("TRUE") == 0 || value_string.compare("true") == 0 || value_string.compare("1") == 0)
{
value = true;
}
KeyValue extra(value);
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("INTEGER") == 0 || real_type.compare("integer") == 0)
{
KeyValue extra(atol(valueAttrib->get_value().c_str()));
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("DOUBLE") == 0 || real_type.compare("double") == 0)
{
KeyValue extra(atof(valueAttrib->get_value().c_str()));
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("STRING") == 0 || real_type.compare("string") == 0)
{
KeyValue extra(std::string(valueAttrib->get_value()));
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("BOOLEANLIST") == 0 || real_type.compare("booleanlist") == 0)
{
std::vector<bool> bools = ReadBools(std::string(valueAttrib->get_value()));
KeyValue extra(bools);
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("INTEGERLIST") == 0 || real_type.compare("integerlist") == 0)
{
std::vector<long> longs = ReadLongs(std::string(valueAttrib->get_value()));
KeyValue extra(longs);
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("DOUBLELIST") == 0 || real_type.compare("doublelist") == 0)
{
std::vector<double> doubles = ReadDoubles(std::string(valueAttrib->get_value()));
KeyValue extra(doubles);
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else if (real_type.compare("STRINGLIST") == 0 || real_type.compare("stringlist") == 0)
{
std::vector<std::string> strings = ReadStrings(std::string(valueAttrib->get_value()));
KeyValue extra(strings);
extras.insert(std::pair<std::string, KeyValue>(std::string(nameAttrib->get_value()), extra));
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted - a state contains invalid extra type");
}
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted - a state contains invalid extras");
}
}
// Get the state header data
xmlpp::Element* nodeElement = dynamic_cast<xmlpp::Element*>(*iter);
xmlpp::Attribute* sequenceAttrib = nodeElement->get_attribute("sequence");
xmlpp::Attribute* secsAttrib = nodeElement->get_attribute("secs");
xmlpp::Attribute* nsecsAttrib = nodeElement->get_attribute("nsecs");
if (sequenceAttrib && secsAttrib && nsecsAttrib)
{
int sequence = atoi(sequenceAttrib->get_value().c_str());
unsigned long secs = atoi(secsAttrib->get_value().c_str());
unsigned long nsecs = atoi(nsecsAttrib->get_value().c_str());
timespec timing;
timing.tv_sec = secs;
timing.tv_nsec = nsecs;
State new_state(desiredData[0], desiredData[1], desiredData[2], actualData[0], actualData[1], actualData[2], sequence, timing);
new_state.extras_ = extras;
trajectory_data.push_back(new_state);
}
else
{
throw std::invalid_argument("XTF file is malformed or otherwise corrupted - one of the states is invalid");
}
}
// Assemble the trajectory
if (data_type == Trajectory::JOINT)
{
Trajectory new_traj(uid, traj_type, timing, robot, generator, joint_names, trajectory_data, tags);
return new_traj;
}
else if (data_type == Trajectory::POSE)
{
Trajectory new_traj(uid, traj_type, timing, robot, generator, root_frame, target_frame, trajectory_data, tags);
return new_traj;
}
else
{
std::string error_str("Unable to read XTF file: " + filename);
throw std::invalid_argument(error_str.c_str());
}
}
else
{
std::string error_str("Unable to read XTF file: " + filename);
throw std::invalid_argument(error_str.c_str());
}
}
catch (xmlpp::internal_error e)
{
std::string error_str("Unable to read XTF file (file may not exist): " + filename);
throw std::invalid_argument(error_str.c_str());
}
}
bool Parser::ExportTraj(Trajectory trajectory, std::string filename, bool compact)
{
xmlpp::Document trajXTF;
// Make root
xmlpp::Element* root = trajXTF.create_root_node("trajectory");
root->set_attribute("uid", trajectory.uid_);
// - Make info block
xmlpp::Element* info = root->add_child("info");
info->set_attribute("robot", trajectory.robot_);
info->set_attribute("generator", trajectory.generator_);
// -- Make type block
xmlpp::Element* type = info->add_child("type");
if (trajectory.traj_type_ == Trajectory::GENERATED)
{
type->set_attribute("traj_type", "generated");
}
else if (trajectory.traj_type_ == Trajectory::RECORDED)
{
type->set_attribute("traj_type", "recorded");
}
else
{
throw std::invalid_argument("Trajectory is invalid/inconsistent");
}
if (trajectory.timing_ == Trajectory::TIMED)
{
type->set_attribute("timing", "timed");
}
else if (trajectory.timing_ == Trajectory::UNTIMED)
{
type->set_attribute("timing", "untimed");
}
else
{
throw std::invalid_argument("Trajectory is invalid/inconsistent");
}
// --- Make type fields
if (trajectory.data_type_ == Trajectory::JOINT)
{
type->set_attribute("data_type", "joint");
xmlpp::Element* joint_names = type->add_child("joint_names");
joint_names->set_child_text(PrettyPrint::PrettyPrint(trajectory.joint_names_));
}
else if (trajectory.data_type_ == Trajectory::POSE)
{
type->set_attribute("data_type", "pose");
xmlpp::Element* root_frame = type->add_child("root_frame");
root_frame->set_child_text(trajectory.root_frame_);
xmlpp::Element* target_frame = type->add_child("target_frame");
target_frame->set_child_text(trajectory.target_frame_);
}
else
{
throw std::invalid_argument("Trajectory is invalid/inconsistent");
}
// -- Make tag block
xmlpp::Element* tags = info->add_child("tags");
tags->set_child_text(PrettyPrint::PrettyPrint(trajectory.tags_));
// - Make state block
xmlpp::Element* states = root->add_child("states");
states->set_attribute("length", PrettyPrint::PrettyPrint(trajectory.trajectory_.size()));
// -- Make states
for (unsigned int i = 0; i < trajectory.trajectory_.size(); i++)
{
State current = trajectory.trajectory_[i];
xmlpp::Element* state = states->add_child("state");
state->set_attribute("sequence", PrettyPrint::PrettyPrint(current.sequence_));
state->set_attribute("secs", PrettyPrint::PrettyPrint(current.timing_.tv_sec));
state->set_attribute("nsecs", PrettyPrint::PrettyPrint(current.timing_.tv_nsec));
// --- Make state fields
xmlpp::Element* desired = state->add_child("desired");
xmlpp::Element* actual = state->add_child("actual");
// ---- Fill in the state fields
xmlpp::Element* dp = desired->add_child("position");
dp->set_child_text(PrettyPrint::PrettyPrint(current.position_desired_));
xmlpp::Element* dv = desired->add_child("velocity");
dv->set_child_text(PrettyPrint::PrettyPrint(current.velocity_desired_));
xmlpp::Element* da = desired->add_child("acceleration");
da->set_child_text(PrettyPrint::PrettyPrint(current.acceleration_desired_));
xmlpp::Element* ap = actual->add_child("position");
ap->set_child_text(PrettyPrint::PrettyPrint(current.position_actual_));
xmlpp::Element* av = actual->add_child("velocity");
av->set_child_text(PrettyPrint::PrettyPrint(current.velocity_actual_));
xmlpp::Element* aa = actual->add_child("acceleration");
aa->set_child_text(PrettyPrint::PrettyPrint(current.acceleration_actual_));
std::map<std::string, KeyValue>::iterator itr;
for(itr = current.extras_.begin(); itr != current.extras_.end(); ++itr)
{
xmlpp::Element* extra = state->add_child("extra");
extra->set_attribute("name", itr->first);
extra->set_attribute("type", itr->second.GetTypeString());
extra->set_attribute("value", itr->second.GetValueString());
}
}
// Write the xml document to file
if (compact)
{
trajXTF.write_to_file(filename, "utf-8");
}
else
{
trajXTF.write_to_file_formatted(filename, "utf-8");
}
return true;
}
std::vector<bool> Parser::ReadBools(std::string strtovec)
{
std::vector<std::string> elements = Parser::ReadStrings(strtovec);
std::vector<bool> bools;
for (unsigned int i = 0; i < elements.size(); i++)
{
bool temp = false;
if (elements[i].compare("TRUE") == 0 || elements[i].compare("true") == 0 || elements[i].compare("1") == 0)
{
temp = true;
}
bools.push_back(temp);
}
return bools;
}
std::vector<long> Parser::ReadLongs(std::string strtovec)
{
std::vector<std::string> elements = Parser::ReadStrings(strtovec);
std::vector<long> longs;
for (unsigned int i = 0; i < elements.size(); i++)
{
long temp = atol(elements[i].c_str());
longs.push_back(temp);
}
return longs;
}
std::vector<double> Parser::ReadDoubles(std::string strtovec)
{
std::vector<std::string> elements = Parser::ReadStrings(strtovec);
std::vector<double> doubles;
for (unsigned int i = 0; i < elements.size(); i++)
{
double temp = atof(elements[i].c_str());
doubles.push_back(temp);
}
return doubles;
}
std::vector<std::string> Parser::ReadStrings(std::string strtovec)
{
std::string temp = CleanString(strtovec);
std::vector<std::string> elements;
std::stringstream ss(temp);
std::string item;
char delim = ',';
while (std::getline(ss, item, delim))
{
std::string cleaned = CleanString(item);
elements.push_back(cleaned);
}
return elements;
}
std::vector< std::vector<double> > Parser::ReadStateFields(xmlpp::Node* field_parent)
{
// Get the basic nodes
xmlpp::Node::NodeList position = field_parent->get_children("position");
xmlpp::Node* positionEL = position.front();
xmlpp::Node::NodeList velocity = field_parent->get_children("velocity");
xmlpp::Node* velocityEL = velocity.front();
xmlpp::Node::NodeList acceleration = field_parent->get_children("acceleration");
xmlpp::Node* accelerationEL = acceleration.front();
// Intermediate step
xmlpp::Node* posN = positionEL->get_children().front();
xmlpp::Node* velN = velocityEL->get_children().front();
xmlpp::Node* accelN = accelerationEL->get_children().front();
// Make the storage containers
std::vector<double> position_data;
std::vector<double> velocity_data;
std::vector<double> acceleration_data;
// Attempt to populate - NOTE: we check both if the node is NULL and if it came from an empty container because libxml++ does not necessarily return NULL from empty NodeLists!
if (posN != NULL && (positionEL->get_children().size() > 0))
{
xmlpp::ContentNode* positionText = dynamic_cast<xmlpp::ContentNode*>(posN);
if (positionText != NULL && !positionText->is_white_space())
{
position_data = ReadDoubles(positionText->get_content());
}
}
if (velN != NULL && (velocityEL->get_children().size() > 0))
{
xmlpp::ContentNode* velocityText = dynamic_cast<xmlpp::ContentNode*>(velN);
if (velocityText != NULL && !velocityText->is_white_space())
{
velocity_data = ReadDoubles(velocityText->get_content());
}
}
if (accelN != NULL && (accelerationEL->get_children().size() > 0))
{
xmlpp::ContentNode* accelerationText = dynamic_cast<xmlpp::ContentNode*>(accelN);
if (accelerationText != NULL && !accelerationText->is_white_space())
{
acceleration_data = ReadDoubles(accelerationText->get_content());
}
}
// Pack everything together for return
std::vector< std::vector<double> > data;
data.push_back(position_data);
data.push_back(velocity_data);
data.push_back(acceleration_data);
return data;
}
| 33.735105 | 235 | 0.565874 | [
"vector"
] |
91b38e20914e5031fd9ad4b86c3c4f6d3891f746 | 6,562 | cpp | C++ | Triple_1.2weighted/readgrammar.cpp | amanzour/SCFGEntropy | ce3ae09d930a5f4eb2902eac539f265571bf9d03 | [
"FSFAP"
] | null | null | null | Triple_1.2weighted/readgrammar.cpp | amanzour/SCFGEntropy | ce3ae09d930a5f4eb2902eac539f265571bf9d03 | [
"FSFAP"
] | null | null | null | Triple_1.2weighted/readgrammar.cpp | amanzour/SCFGEntropy | ce3ae09d930a5f4eb2902eac539f265571bf9d03 | [
"FSFAP"
] | null | null | null | #include "readgrammar.h"
readgrammar::readgrammar(string filename)
{
gfilename = filename;
nonterm = "<Start>";
map_alpha.push_back(line);
map_beta.push_back(line);
grammar.resize(0);
}
readgrammar::~readgrammar(void)
{
}
void readgrammar::readtext(void)
{
string str_line="";
f_g.open(gfilename.c_str(), ios::in);
if (!f_g.is_open())
{
cerr<<"grammar file can't be open"<<endl;
exit(1);
}
while (!f_g.eof())
{
getline(f_g, str_line);
if (str_line == "")
continue;
if (str_line[0] == '#')
break;
handlerule(str_line);
}
f_g.close();
/* int i, j;
cout<<"alpha size: "<<map_alpha.size()<<endl;
for (i=0; i<map_alpha.size(); i++)
{
cout<<map_alpha.at(i).size()<<":";
for (j=0; j<map_alpha.at(i).size(); j++)
cout<<map_alpha.at(i).at(j)<<", ";
cout<<endl;
}
cout<<endl;
cout<<"beta size: "<<map_beta.size()<<endl;
for (i=0; i<map_beta.size(); i++)
{
cout<<map_beta.at(i).size()<<":";
for (j=0; j<map_beta.at(i).size(); j++)
cout<<map_beta.at(i).at(j)<<", ";
cout<<endl;
}
cout<<endl;
cout<<"grammar size: "<<grammar.size()<<endl;
for (i=0; i<grammar.size(); i++)
{
cout<<grammar.at(i).leftnon<<", ";
cout<<grammar.at(i).non1<<", ";
cout<<grammar.at(i).non2<<", ";
cout<<grammar.at(i).ruletype<<", ";
cout<<grammar.at(i).prob<<endl;
}*/
// cout<<map_alpha.at(1).at(1)<<endl;
// cout<<map_alpha.at(1).at(2)<<endl;
// cout<<map_alpha.at(0).at(3)<<endl;
//cout<<map_beta.at(0).size()<<endl;
}
double readgrammar::getvalue(string numstr)
{
double theValue;
istringstream istr;
istr.str(numstr);
istr>>theValue;
return theValue;
}
int readgrammar::nonterminalid(string therule, int non_beg,
int non_end)
{
int oriposi, curposi;
string currule;
currule = therule;
oriposi = nonterm.find(currule.substr(non_beg,non_end-non_beg+1));
if (oriposi == (int)string::npos)
{
nonterm += currule.substr(non_beg,non_end-non_beg+1);
curposi = accout_char(nonterm, "<")-1;
// for mapping_alpha
map_alpha.push_back(line);
// for mapping_beta
map_beta.push_back(line);
}else
curposi = accout_char(nonterm.substr(0, oriposi+1), "<")-1;
return curposi;
}
void readgrammar::parserule(string therule)
{
//int firstposi; //verify whether the first symbol is terminal
string currule;
int colon_posi=-100, brac_posi=-100;
//string nonlist="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // list of all possible non-terminal
//initialization
currule = therule;
colon_posi = currule.find(":");
if (colon_posi == (int)string::npos)
errorreport(2);
if (currule.at(colon_posi+1) == '<' )
{
brac_posi = currule.find("<", colon_posi+2);
if (brac_posi == (int)string::npos)
rule.ruletype = 5; //<X>:<H>a
else
rule.ruletype = 6; //<X>:<H>a<Y>b
}
else
identify_type(currule, colon_posi);
record_non(currule, colon_posi);
update_map_alpha();// update map_alpha
if (rule.ruletype >=2)
update_map_beta(); // update map_beta
}
void readgrammar::update_map_alpha(void)
{
map_alpha.at(rule.leftnon).push_back(grammar.size());// the current rule has not been stored in grammar
}
void readgrammar::update_map_beta(void)
{
map_beta.at(rule.non1).push_back(grammar.size()); // the current rule has not been stored in grammar
if ((rule.ruletype == 4)&&(rule.non1 != rule.non2)) // avoid X:aHbH
map_beta.at(rule.non2).push_back(grammar.size());
if ((rule.ruletype == 6)&&(rule.non1 != rule.non2)) // avoid X:HaHb
map_beta.at(rule.non2).push_back(grammar.size());
}
void readgrammar::handlerule(string rulestr)
{
int posi_space;
posi_space = rulestr.find(" ");
if ((posi_space == (int) string::npos)||(posi_space == (int)(rulestr.length()-1)))
errorreport(2); //rule format error
// probability
rule.prob = getvalue(rulestr.substr(posi_space, rulestr.length() - posi_space));
// parse rule
parserule(rulestr.substr(0, posi_space));
//store in grammar
grammar.push_back(rule);
}
int readgrammar::getnonterminalnum(void)
{
int num;
//we return # of chars are as same as that of non-termals.
num = accout_char(nonterm, "<");
//cout<<"# of nonterminal: "<<num<<endl;
return num;
}
vector< ruleinfo > readgrammar::getgrammar(void)
{
return grammar;
}
vector< vector< int > > readgrammar::get_alpha(void)
{
return map_alpha;
}
vector< vector< int > > readgrammar::get_beta(void)
{
return map_beta;
}
void readgrammar::errorreport(int errorid)
{
if (errorid ==2)
cerr<<"rule should be like <X>:a<H>b<Y> 0.25"<<endl;
if (errorid>=1000)
cerr<<"unknown error!!!"<<endl;
exit(1);
}
void readgrammar::identify_type(string therule, int colon_posi)
//identify rule type 1, 2, 3, 4
{
int brac_posi;
string str_rule;
str_rule = therule;
if ((int)str_rule.length() == colon_posi+2)
rule.ruletype = 1; //<X>:a
else
if (str_rule.at(str_rule.length()-1) != '>')
rule.ruletype = 3; // <X>:a<H>b
else
{
brac_posi = str_rule.find("<", colon_posi+3);
if (brac_posi == (int)string::npos)
rule.ruletype = 2; // <X>:a<H>
else
rule.ruletype = 4; // <X>:a<H>b<Y>
}
}
void readgrammar::record_non(string therule, int colon_posi)
// record all non-terminals
{
int beg_posi, end_posi;
string currule;
rule.leftnon = -1;
rule.non1 = -1;
rule.non2 = -1;
currule = therule;
rule.leftnon = nonterminalid(currule, 0, colon_posi-1);
if ((rule.ruletype >= 2)&&(rule.ruletype <= 4))
{
beg_posi = currule.find("<", colon_posi+1);
end_posi = currule.find(">", colon_posi+1);
rule.non1 = nonterminalid(currule, beg_posi, end_posi);
}
if (rule.ruletype == 4)
{
beg_posi = currule.find("<", beg_posi+1);
end_posi = currule.find(">", end_posi+1);
rule.non2 = nonterminalid(currule, beg_posi, end_posi);
}
if ((rule.ruletype == 5) || (rule.ruletype == 6))
{
beg_posi = currule.find("<", colon_posi+1);
end_posi = currule.find(">", colon_posi+1);
rule.non1 = nonterminalid(currule, beg_posi, end_posi);
}
if (rule.ruletype == 6)
{
beg_posi = currule.find("<", beg_posi+1);
end_posi = currule.find(">", end_posi+1);
rule.non2 = nonterminalid(currule, beg_posi, end_posi);
}
}
int readgrammar::accout_char(string target_str, string search_str)
{
int num = 0, posi;
posi = target_str.find(search_str);
while (posi != (int) string::npos)
{
num++;
posi = target_str.find(search_str, posi+1);
}
return num;
}
| 24.125 | 105 | 0.629686 | [
"vector"
] |
91b95435e263acac346fd8e95fc4831dec7b39ec | 42,097 | cpp | C++ | main/shape2ps.cpp | fmidev/smartmet-shapetools | 8ca25d3a007af8582c2553c9f608ec18482ea0d4 | [
"MIT"
] | null | null | null | main/shape2ps.cpp | fmidev/smartmet-shapetools | 8ca25d3a007af8582c2553c9f608ec18482ea0d4 | [
"MIT"
] | null | null | null | main/shape2ps.cpp | fmidev/smartmet-shapetools | 8ca25d3a007af8582c2553c9f608ec18482ea0d4 | [
"MIT"
] | null | null | null | // ======================================================================
/*!
* \file shape2ps.cpp
* \brief A program to render shapefiles into PostScript
*/
// ======================================================================
/*!
* \page shape2ps shape2ps
*
* shape2ps takes as input a single filename containing rendering
* directives. All rendering directive lines are by default considered
* to be plain PostScript, and are output as is. A few special tokens
* will read and output shapefile data, set projections and so on.
* Note that the special tokens must be the first ones on the line,
* otherwise they won't be recognized.
*
* A very simple example file would be
*
* \code
* projection stereographic,20,90,60:6,51.3,49,70.2:400,400
* body
* 3 setlinewidth
* 1 1 0 setrgbcolor
* shape moveto lineto closepath suomi stroke
* subshape moveto lineto closepath field=value suomi stroke
* gshhs moveto lineto closepath gshhs_f.c stroke
* \endcode
*
* Atleast one of coordinate ranges given in the projection is expected to
* differ from 0-1. If only one differs, the other is calculated to be 0-X,
* where X is calculated so that aspect ratio is preserved in the set
* projection.
*
* To render querydata contours one can use code like
* \code
* area 10 NFmiLatLonArea ...
* body
* querydata /data/pal/querydata/pal/skandinavia/pinta
* parameter Temperature
* level 750
* timemode utc
* time +1 12
* newpath
* bezier approximate 10
* contourcommands moveto lineto curveto closepath
* labelcommand show
* contourline 10 stroke
* contourline 15 stroke
* contourline 20 stroke
* contourline 25 stroke
* contourline 30 stroke
* contourfill -10 10 fill
* contourlabels 10 30 5
* \endcode
*
* The list of special commands is
* - projection ... to set the projection
* - area ... to set the projection as an object
* - projectioncenter <lon> <lat> <scale>
* - boundingbox to generate the path for the bounding box
* - body to indicate the start of the PostScript body
* - shape <moveto> <lineto> <closepath> <shapefile> to render a shapefile
* - gshhs <moveto> <lineto> <closepath> <gshhsfile> to render a shoreline
* - graticule <moveto> <lineto> <lon1> <lon2> <dx> <lat1> <lat2> <dy> to render
* a graticule
* - {moveto} {lineto} exec <shapefile> to execute given commands for vertices
* - {} qdexec <querydata> to execute given commands for grid points
* - project <x> <y> to output projected x and y
* - location <place> to output projected x and y
* - system .... to execute the remaining line in the shell
* - querydata <name> Set the active querydata
* - parameter <name> Set the active querydata parameter
* - level <levelvalue> Set the active querydata level
* - timemode <local|utc>
* - time <days> <hour>
* - smoother <name> <factor> <radius>
* - contourcommands <moveto> <lineto> <curveto> <closepath>
* - contourline <value>
* - contourfill <lolimit> <hilimit>
* - bezier none
* - bezier cardinal <0-1>
* - bezier approximate <maxerror>
* - bezier tight <maxerror>
*/
// ======================================================================
#include "Polyline.h"
#include <gis/CoordinateMatrix.h>
#include <imagine/NFmiApproximateBezierFit.h>
#include <imagine/NFmiCardinalBezierFit.h>
#include <imagine/NFmiContourTree.h>
#include <imagine/NFmiGeoShape.h>
#include <imagine/NFmiGshhsTools.h>
#include <imagine/NFmiPath.h>
#include <imagine/NFmiTightBezierFit.h>
#include <newbase/NFmiArea.h>
#include <newbase/NFmiAreaFactory.h>
#include <newbase/NFmiAreaTools.h>
#include <newbase/NFmiCmdLine.h>
#include <newbase/NFmiEnumConverter.h>
#include <newbase/NFmiFileSystem.h>
#include <newbase/NFmiLocationFinder.h>
#include <newbase/NFmiParameterName.h>
#include <newbase/NFmiPreProcessor.h>
#include <newbase/NFmiSaveBaseFactory.h>
#include <newbase/NFmiSettings.h>
#include <newbase/NFmiSmoother.h>
#include <newbase/NFmiStreamQueryData.h>
#include <newbase/NFmiValueString.h>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;
using namespace std;
// Clamp PostScript path elements to within this range
const double clamp_limit = 10000;
struct BezierSettings
{
BezierSettings(const string &theName,
const string theMode,
double theSmoothness,
double theMaxError)
: name(theName), mode(theMode), smoothness(theSmoothness), maxerror(theMaxError)
{
}
bool operator==(const BezierSettings &theOther) const
{
return (mode == theOther.mode && smoothness == theOther.smoothness &&
maxerror == theOther.maxerror);
}
bool operator<(const BezierSettings &theOther) const
{
if (mode != theOther.mode)
return (mode < theOther.mode);
if (smoothness != theOther.smoothness)
return (smoothness < theOther.smoothness);
return (maxerror < theOther.maxerror);
}
string name;
string mode;
double smoothness;
double maxerror;
};
// ----------------------------------------------------------------------
/*!
* \brief Global replace within a string
*
* \param theString The string in which to replace
* \param theMatch The original string
* \param theReplacement The replacement string
*/
// ----------------------------------------------------------------------
void replace(string &theString, const string &theMatch, const string &theReplacement)
{
string::size_type pos;
while ((pos = theString.find(theMatch)) != string::npos)
{
theString.replace(pos, theMatch.size(), theReplacement);
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create unique name for a contour
*
* \param theIndex The unique ordinal of the contour
* \return The unique name
*/
// ----------------------------------------------------------------------
string ContourName(unsigned long theIndex)
{
return ("% shape2ps: path " + lexical_cast<string>(theIndex) + " place holder");
}
// ----------------------------------------------------------------------
/*!
* \brief Convert local time to UTC time using current TZ
*
* \param theLocalTime The local time
* \return The UTC time
*
* \note This was stolen from textgen library TimeTools namespace
*/
// ----------------------------------------------------------------------
NFmiTime toutctime(const NFmiTime &theLocalTime)
{
::tm tlocal;
tlocal.tm_sec = theLocalTime.GetSec();
tlocal.tm_min = theLocalTime.GetMin();
tlocal.tm_hour = theLocalTime.GetHour();
tlocal.tm_mday = theLocalTime.GetDay();
tlocal.tm_mon = theLocalTime.GetMonth() - 1;
tlocal.tm_year = theLocalTime.GetYear() - 1900;
tlocal.tm_wday = -1;
tlocal.tm_yday = -1;
tlocal.tm_isdst = -1;
::time_t tsec = mktime(&tlocal);
::tm *tutc = ::gmtime(&tsec);
NFmiTime out(tutc->tm_year + 1900,
tutc->tm_mon + 1,
tutc->tm_mday,
tutc->tm_hour,
tutc->tm_min,
tutc->tm_sec);
return out;
}
// ----------------------------------------------------------------------
/*!
* \brief Convert path to PostScript path
*/
// ----------------------------------------------------------------------
string pathtostring(const Imagine::NFmiPath &thePath,
const NFmiArea &theArea,
double theClipMargin,
const string &theMoveto,
const string &theLineto,
const string &theClosepath = "")
{
const Imagine::NFmiPathData::const_iterator begin = thePath.Elements().begin();
const Imagine::NFmiPathData::const_iterator end = thePath.Elements().end();
string out;
Polyline polyline;
for (Imagine::NFmiPathData::const_iterator iter = begin; iter != end;)
{
double X = (*iter).X();
double Y = theArea.Bottom() - ((*iter).Y() - theArea.Top());
X = std::min(X, clamp_limit);
Y = std::min(Y, clamp_limit);
X = std::max(X, -clamp_limit);
Y = std::max(Y, -clamp_limit);
if ((*iter).Oper() == Imagine::kFmiMoveTo || (*iter).Oper() == Imagine::kFmiLineTo ||
(*iter).Oper() == Imagine::kFmiGhostLineTo)
polyline.add(X, Y);
else
throw runtime_error("Only moveto and lineto commands are supported in paths");
// Advance to next point. If end or moveto, flush previous polyline out
++iter;
if (!polyline.empty() && (iter == end || (*iter).Oper() == Imagine::kFmiMoveTo))
{
polyline.clip(
theArea.Left(), theArea.Top(), theArea.Right(), theArea.Bottom(), theClipMargin);
if (!polyline.empty())
out += polyline.path(theMoveto, theLineto, theClosepath);
polyline.clear();
}
}
return out;
}
// ----------------------------------------------------------------------
/*!
* \brief Convert path to PostScript path
*/
// ----------------------------------------------------------------------
string pathtostring(const Imagine::NFmiPath &thePath,
const NFmiArea &theArea,
double theClipMargin,
const string &theMoveto,
const string &theLineto,
const string &theCurveto,
const string &theClosepath)
{
Imagine::NFmiPath path =
thePath.Clip(theArea.Left(), theArea.Top(), theArea.Right(), theArea.Bottom(), theClipMargin);
const Imagine::NFmiPathData::const_iterator begin = path.Elements().begin();
const Imagine::NFmiPathData::const_iterator end = path.Elements().end();
ostringstream out;
unsigned int cubic_count = 0;
for (Imagine::NFmiPathData::const_iterator iter = begin; iter != end; ++iter)
{
double X = iter->X();
double Y = theArea.Bottom() - (iter->Y() - theArea.Top());
X = std::min(X, clamp_limit);
Y = std::min(Y, clamp_limit);
X = std::max(X, -clamp_limit);
Y = std::max(Y, -clamp_limit);
out << X << ' ' << Y << ' ';
switch (iter->Oper())
{
case Imagine::kFmiMoveTo:
out << theMoveto << endl;
cubic_count = 0;
break;
case Imagine::kFmiLineTo:
case Imagine::kFmiGhostLineTo:
out << theLineto << endl;
cubic_count = 0;
break;
case Imagine::kFmiCubicTo:
++cubic_count;
if (cubic_count % 3 == 0)
out << theCurveto << endl;
break;
case Imagine::kFmiConicTo:
throw runtime_error("Conic segments not supported");
}
}
return out.str();
}
// ----------------------------------------------------------------------
/*!
* \brief Set queryinfo level
*
* A negative level value implies the first level in the data
*
* \param theInfo The queryinfo
* \param theLevel The level value
*/
// ----------------------------------------------------------------------
void set_level(NFmiFastQueryInfo &theInfo, int theLevel)
{
if (theLevel < 0)
theInfo.FirstLevel();
else
{
for (theInfo.ResetLevel(); theInfo.NextLevel();)
if (theInfo.Level()->LevelValue() == static_cast<unsigned int>(theLevel))
return;
throw runtime_error("Level value " + NFmiStringTools::Convert(theLevel) + " is not available");
}
}
// ----------------------------------------------------------------------
// The main driver
// ----------------------------------------------------------------------
int domain(int argc, const char *argv[])
{
bool verbose = false;
NFmiCmdLine cmdline(argc, argv, "v");
if (cmdline.NumberofParameters() != 1)
throw runtime_error("Usage: shape2ps [options] <filename>");
if (cmdline.Status().IsError())
throw runtime_error(cmdline.Status().ErrorLog().CharPtr());
if (cmdline.isOption('v'))
verbose = true;
string scriptfile = cmdline.Parameter(1);
// Open the script file
const bool strip_pound = false;
NFmiPreProcessor processor(strip_pound);
processor.SetIncluding("include", "", "");
processor.SetDefine("#define");
if (!processor.ReadAndStripFile(scriptfile))
throw runtime_error("Error: " + processor.GetMessage());
string text = processor.GetString();
istringstream script(text);
// The area specification is not given yet
boost::shared_ptr<NFmiArea> theArea;
// The querydata is not given yet
string theQueryDataName;
NFmiStreamQueryData theQueryData;
// The querydata parameter is not given yet
string theParameterName;
FmiParameterName theParameter = kFmiBadParameter;
// The level is not given yet - use first level
int theLevel = -1;
// The time mode is by default local time
bool theLocalTimeMode = true;
// The time offset has not been given yet
string theTimeOrigin = "now";
int theDay = -1;
int theHour = -1;
// Contouring movement command names
string theMovetoCommand = "moveto";
string theLinetoCommand = "lineto";
string theCurvetoCommand = "curveto";
string theClosepathCommand = "closepath";
// Bezier smoothing
string theBezierMode = "none";
double theBezierSmoothness = 0.5;
double theBezierMaxError = 1.0;
// Smoothing
string theSmoother = "None";
double theSmootherRadius = 10;
int theSmootherFactor = 5;
// The calculated contours before Bezier fitting, and set of all
// different combinatins of Bezier parameters used in the script
typedef list<pair<BezierSettings, Imagine::NFmiPath>> Contours;
Contours theContours;
set<BezierSettings> theContourSettings;
// No clipping margin given yet
double theClipMargin = 0.0;
// Not in the body yet
bool body = false;
// Prepare the location finder for "location" token
string coordfile = NFmiSettings::Optional<string>("qdpoint::coordinates_file", "default.txt");
string coordpath = NFmiSettings::Optional<string>("qdpoint::coordinates_path", ".");
NFmiLocationFinder locfinder;
locfinder.AddFile(NFmiFileSystem::FileComplete(coordfile, coordpath), false);
// We try to cache the matrices for best speed.
// Some tokens will invalidate the matrices
unique_ptr<NFmiDataMatrix<float>> values;
unique_ptr<Fmi::CoordinateMatrix> coords;
// Do the deed
string token;
ostringstream buffer;
while (script >> token)
{
// ------------------------------------------------------------
// Handle script comments
// ------------------------------------------------------------
if (token == "#")
script.ignore(1000000, '\n');
// ------------------------------------------------------------
// Handle PostScript comments
// ------------------------------------------------------------
else if (token == "%")
{
getline(script, token);
buffer << '%' << token << endl;
}
// ------------------------------------------------------------
// Handle the clipmargin command
// ------------------------------------------------------------
else if (token == "clipmargin")
script >> theClipMargin;
// ------------------------------------------------------------
// Handle the area command
// ------------------------------------------------------------
else if (token == "area")
{
cerr << "Warning: The area command is deprecated, use projection command "
"instead"
<< endl;
// Invalidate coordinate matrix
coords.reset(0);
if (theArea.get())
throw runtime_error("Area given twice");
unsigned long classID;
string className;
script >> classID >> className;
theArea.reset(static_cast<NFmiArea *>(CreateSaveBase(classID)));
if (!theArea.get())
throw runtime_error("Unrecognized area in the script");
script >> *theArea;
// Now handle XY limits
double x1 = theArea->Left();
double x2 = theArea->Right();
double y1 = theArea->Top();
double y2 = theArea->Bottom();
if (x2 - x1 == 1 && y2 - y1 == 1)
throw runtime_error("Error: No decent XY-area given in projection");
// Recalculate x-range from y-range if necessary
if (x2 - x1 == 1)
{
x1 = 0;
x2 = (y2 - y1) * theArea->WorldXYAspectRatio();
theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));
}
// Recalculate y-range from x-range if necessary
if (y2 - y1 == 1)
{
y1 = 0;
y2 = (x2 - x1) / theArea->WorldXYAspectRatio();
theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));
}
}
// ------------------------------------------------------------
// Handle the projectioncenter command
// ------------------------------------------------------------
else if (token == "projectioncenter")
{
cerr << "Warning: The projectioncenter command is deprecated, use "
"projection command instead"
<< endl;
coords.reset(0);
if (!theArea.get())
throw runtime_error(
"projectioncenter must be used after a projection "
"has been specified");
float lon, lat, scale;
script >> lon >> lat >> scale;
NFmiPoint center(lon, lat);
double x1 = theArea->Left();
double x2 = theArea->Right();
double y1 = theArea->Top();
double y2 = theArea->Bottom();
// Projektiolaskuja varten
theArea.reset(theArea->NewArea(center, center));
NFmiPoint c = theArea->LatLonToWorldXY(center);
NFmiPoint bl(c.X() - scale * 1000 * (x2 - x1), c.Y() - scale * 1000 * (y2 - y1));
NFmiPoint tr(c.X() + scale * 1000 * (x2 - x1), c.Y() + scale * 1000 * (y2 - y1));
NFmiPoint bottomleft = theArea->WorldXYToLatLon(bl);
NFmiPoint topright = theArea->WorldXYToLatLon(tr);
theArea.reset(theArea->NewArea(bottomleft, topright));
if (verbose)
{
cerr << "Calculated new area to be" << endl << *theArea << endl;
}
}
// ------------------------------------------------------------
// Handle the projection command
// ------------------------------------------------------------
else if (token == "projection")
{
// Invalidate coordinate matrix
coords.reset(0);
if (theArea.get())
throw runtime_error("Projection given twice");
string specs;
script >> specs;
theArea = NFmiAreaFactory::Create(specs);
// Now handle XY limits
double x1 = theArea->Left();
double x2 = theArea->Right();
double y1 = theArea->Top();
double y2 = theArea->Bottom();
if (x2 - x1 == 1 && y2 - y1 == 1)
throw runtime_error("Error: No decent XY-area given in projection");
// Recalculate x-range from y-range if necessary
if (x2 - x1 == 1)
{
x1 = 0;
x2 = (y2 - y1) * theArea->WorldXYAspectRatio();
theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));
}
// Recalculate y-range from x-range if necessary
if (y2 - y1 == 1)
{
y1 = 0;
y2 = (x2 - x1) / theArea->WorldXYAspectRatio();
theArea->SetXYArea(NFmiRect(x1, y2, x2, y1));
}
if (verbose)
{
cerr << "The new projection is" << endl << *theArea << endl;
}
}
// ------------------------------------------------------------
// Handle the body command
// ------------------------------------------------------------
else if (token == "body")
{
if (body)
throw runtime_error("body command given twice in script");
if (!theArea.get())
throw runtime_error("No area specified before body");
body = true;
// Output the header, then the buffer, then the beginning of body
string tmp = buffer.str();
buffer.str("");
buffer << "%!PS-Adobe-3.0 EPSF-3.0" << endl
<< "%%Creator: shape2ps" << endl
<< "%%Pages: 1" << endl
<< "%%BoundingBox: " << static_cast<int>(theArea->Left()) << " "
<< static_cast<int>(theArea->Top()) << " " << static_cast<int>(theArea->Right()) << " "
<< static_cast<int>(theArea->Bottom()) << endl
<< "%%EndComments" << endl
<< "%%BeginProcSet: shape2ps" << endl
<< "save /mysave exch def" << endl
<< "/mydict 1000 dict def" << endl
<< "mydict begin" << endl
<< "/e2{2 index exec}def" << endl
<< "/e3{3 index exec}def" << endl
<< tmp << endl
<< "end" << endl
<< "%%EndProcSet" << endl
<< "%%EndProlog" << endl
<< "%%Page: 1 1" << endl
<< "%%BeginPageSetup" << endl
<< "mydict begin" << endl
<< "%%EndPageSetup" << endl
<< "gsave " << static_cast<int>(theArea->Left()) << " "
<< static_cast<int>(theArea->Top()) << " " << static_cast<int>(theArea->Right()) << " "
<< static_cast<int>(theArea->Bottom()) << " rectclip newpath" << endl;
}
// ----------------------------------------------------------------------
// Handle a boundingbox command
// ----------------------------------------------------------------------
else if (token == "boundingbox")
{
if (!theArea.get())
throw runtime_error("Using boundingbox before area");
buffer << static_cast<int>(theArea->Left()) << " " << static_cast<int>(theArea->Bottom())
<< " moveto " << static_cast<int>(theArea->Left()) << " "
<< static_cast<int>(theArea->Top()) << " lineto " << static_cast<int>(theArea->Right())
<< " " << static_cast<int>(theArea->Top()) << " lineto "
<< static_cast<int>(theArea->Right()) << " " << static_cast<int>(theArea->Bottom())
<< " lineto closepath" << endl;
}
// ------------------------------------------------------------
// Handle a project command
// ------------------------------------------------------------
else if (token == "project")
{
if (!theArea.get())
throw runtime_error("Using project before area");
double x, y;
script >> x >> y;
NFmiPoint pt = theArea->ToXY(NFmiPoint(x, y));
buffer << static_cast<char *>(NFmiValueString(pt.X())) << ' '
<< static_cast<char *>(NFmiValueString(theArea->Bottom() - (pt.Y() - theArea->Top())))
<< ' ';
}
// ------------------------------------------------------------
// Handle a location command
// ------------------------------------------------------------
else if (token == "location")
{
if (!theArea.get())
throw runtime_error("Using location before area");
string placename;
script >> placename;
NFmiPoint lonlat = locfinder.Find(placename);
if (locfinder.LastSearchFailed())
throw runtime_error("Location " + placename + " is not in the database");
NFmiPoint pt = theArea->ToXY(lonlat);
buffer << static_cast<char *>(NFmiValueString(pt.X())) << ' '
<< static_cast<char *>(NFmiValueString(theArea->Bottom() - (pt.Y() - theArea->Top())))
<< ' ';
}
// ------------------------------------------------------------
// Handle a system command
// ------------------------------------------------------------
else if (token == "system")
{
if (!body)
throw runtime_error("system command does not work in the header");
getline(script, token);
buffer << "% " << token << endl;
::system(token.c_str());
}
// ------------------------------------------------------------
// Handle the shape and exec commands
// ------------------------------------------------------------
else if (token == "shape" || token == "subshape" || token == "exec")
{
if (!body)
throw runtime_error("Cannot have " + token + " command in header");
string moveto, lineto, closepath;
if (token == "shape" || token == "subshape")
script >> moveto >> lineto >> closepath;
string shapefile, condition;
if (token == "subshape")
script >> condition;
script >> shapefile;
buffer << "% ";
buffer << token;
buffer << ' ';
buffer << shapefile;
buffer << endl;
// Read the shape, project and get as path
try
{
Imagine::NFmiGeoShape geo(shapefile, Imagine::kFmiGeoShapeEsri, condition);
// geo.ProjectXY(*theArea);
#ifdef WGS84
Imagine::NFmiPath path = geo.Path();
#else
Imagine::NFmiPath path = geo.Path().PacificView(theArea->PacificView());
#endif
path.Project(theArea.get());
if (token == "shape" || token == "subshape")
buffer << pathtostring(path, *theArea, theClipMargin, moveto, lineto, closepath);
else
buffer << pathtostring(path, *theArea, theClipMargin, "e3", "e2");
if (token == "exec")
buffer << "pop pop" << endl;
}
catch (std::exception &e)
{
if (token != "shape")
throw e;
string msg = "Failed at command shape ";
msg += moveto + ' ';
msg += lineto + ' ';
msg += closepath + ' ';
msg += shapefile;
msg += " : ";
msg += e.what();
throw runtime_error(msg);
}
}
// ------------------------------------------------------------
// Handle the qdexec command
// ------------------------------------------------------------
else if (token == "qdexec")
{
if (!body)
throw runtime_error("Cannot have " + token + " command in header");
if (!theArea.get())
throw runtime_error("Using qdexec before projection specified");
string queryfile;
script >> queryfile;
buffer << "% " << token << ' ' << queryfile << endl;
NFmiStreamQueryData qd;
qd.SafeReadLatestData(queryfile);
NFmiFastQueryInfo *qi = qd.QueryInfoIter();
qi->First();
for (qi->ResetLocation(); qi->NextLocation();)
{
const NFmiPoint lonlat = qi->LatLon();
const NFmiPoint pt = theArea->ToXY(lonlat);
buffer << static_cast<char *>(NFmiValueString(pt.X())) << ' '
<< static_cast<char *>(
NFmiValueString(theArea->Bottom() - (pt.Y() - theArea->Top())))
<< " e2" << endl;
}
buffer << "pop" << endl;
}
// ------------------------------------------------------------
// Handle the gshhs command
// ------------------------------------------------------------
else if (token == "gshhs")
{
if (!body)
throw runtime_error("Cannot have " + token + " command in header");
string moveto, lineto, closepath;
script >> moveto >> lineto >> closepath;
string gshhsfile;
script >> gshhsfile;
buffer << "% " << token << ' ' << gshhsfile << endl;
// Read the gshhs, project and get as path
try
{
double minlon, minlat, maxlon, maxlat;
NFmiAreaTools::LatLonBoundingBox(*theArea, minlon, minlat, maxlon, maxlat);
Imagine::NFmiPath path =
Imagine::NFmiGshhsTools::ReadPath(gshhsfile, minlon, minlat, maxlon, maxlat);
path.Project(theArea.get());
buffer << pathtostring(path, *theArea, theClipMargin, moveto, lineto, closepath);
}
catch (std::exception &e)
{
string msg = "Failed at command gshhs ";
msg += moveto + ' ';
msg += lineto + ' ';
msg += closepath + ' ';
msg += gshhsfile;
msg += " due to ";
msg += e.what();
throw runtime_error(e.what());
}
}
// ------------------------------------------------------------
// Handle the graticule <moveto> <lineto> <lon1> <lon2> <dx> <lat1> <lat2>
// <dy> command
// ------------------------------------------------------------
else if (token == "graticule")
{
if (!body)
throw runtime_error("Cannot have " + token + " command in header");
string moveto, lineto;
script >> moveto >> lineto;
double lon1, lon2, dx, lat1, lat2, dy;
script >> lon1 >> lon2 >> dx >> lat1 >> lat2 >> dy;
if (lon1 > lon2)
throw runtime_error("Graticule lon1>lon2");
if (lat1 > lat2)
throw runtime_error("Graticule lat1>lat2");
if (dx <= 0)
throw runtime_error("Graticule dx<=0");
if (dy <= 0)
throw runtime_error("Graticule dy<=0");
buffer << "% graticule " << lon1 << ' ' << lon2 << ' ' << dx << ' ' << lat1 << ' ' << lat2
<< ' ' << dy << endl;
Imagine::NFmiPath path;
for (double x = lon1; x <= lon2; x += dx)
for (double y = lat1; y <= lat2; y += dy)
{
if (y == lat1)
path.MoveTo(x, y);
else
path.LineTo(x, y);
}
for (double y = lat1; y <= lat2; y += dy)
for (double x = lon1; x <= lon2; x += dx)
{
if (x == lon1)
path.MoveTo(x, y);
else
path.LineTo(x, y);
}
path.Project(theArea.get());
buffer << pathtostring(path, *theArea, theClipMargin, moveto, lineto, "closepath");
}
// ------------------------------------------------------------
// Handle the querydata <filename> command
// ------------------------------------------------------------
else if (token == "querydata")
{
coords.reset(0);
values.reset(0);
script >> theQueryDataName;
if (!theQueryData.SafeReadLatestData(theQueryDataName))
throw runtime_error("Failed to read querydata from " + theQueryDataName);
}
// ------------------------------------------------------------
// Handle the parameter <name> command
// ----------------------------------------------------------------------
else if (token == "parameter")
{
values.reset(0);
script >> theParameterName;
NFmiEnumConverter converter;
theParameter = FmiParameterName(converter.ToEnum(theParameterName));
if (theParameter == kFmiBadParameter)
throw runtime_error("Parameter name " + theParameterName + " is not recognized by newbase");
}
// ------------------------------------------------------------
// Handle the level <levelvalue> command
// ----------------------------------------------------------------------
else if (token == "level")
{
values.reset(0);
script >> theLevel;
}
// ------------------------------------------------------------
// Handle the timemode <local|utc> command
// ------------------------------------------------------------
else if (token == "timemode")
{
values.reset(0);
string name;
script >> name;
if (name == "local")
theLocalTimeMode = true;
else if (name == "utc")
theLocalTimeMode = false;
else
throw runtime_error("Unrecognized time mode " + name +
", the name must be 'local' or 'utc'");
}
// ------------------------------------------------------------
// Handle the time <day> <hour> command
// ------------------------------------------------------------
else if (token == "time")
{
values.reset(0);
script >> theTimeOrigin >> theDay >> theHour;
if (theTimeOrigin != "now" && theTimeOrigin != "origintime" && theTimeOrigin != "firsttime")
throw runtime_error("Time mode " + theTimeOrigin + " is not recognized");
if (theDay < 0)
throw runtime_error("First argument of time-command must be nonnegative");
if (theHour < 0 || theHour > 24)
throw runtime_error("Second argument of time-command must be in range 0-23");
}
// ------------------------------------------------------------
// Handle the bezier command
// ------------------------------------------------------------
else if (token == "bezier")
{
script >> theBezierMode;
if (theBezierMode == "none")
;
else if (theBezierMode == "cardinal")
script >> theBezierSmoothness;
else if (theBezierMode == "approximate")
script >> theBezierMaxError;
else if (theBezierMode == "tight")
script >> theBezierMaxError;
else
throw runtime_error("Bezier mode " + theBezierMode + " is not recognized");
}
// ------------------------------------------------------------
// Handle the smoother command
// ------------------------------------------------------------
else if (token == "smoother")
{
values.reset(0);
script >> theSmoother;
if (theSmoother != "None")
script >> theSmootherFactor >> theSmootherRadius;
if (NFmiSmoother::SmootherValue(theSmoother) == NFmiSmoother::kFmiSmootherMissing)
throw runtime_error("Smoother mode " + theSmoother + " is not recognized");
}
// ------------------------------------------------------------
// Handle the contourcommands <moveto> <lineto> <curveto> <closepath>
// command
// ------------------------------------------------------------
else if (token == "contourcommands")
{
script >> theMovetoCommand >> theLinetoCommand >> theCurvetoCommand >> theClosepathCommand;
}
// ----------------------------------------------------------------------
// Handle the windarrows <dx> <dy> command
// ----------------------------------------------------------------------
else if (token == "windarrows")
{
if (!body)
throw runtime_error(token + " command is not allowed in the header");
int dx, dy;
script >> dx >> dy;
NFmiFastQueryInfo *q = theQueryData.QueryInfoIter();
if (q == 0)
throw runtime_error("querydata must be specified before using any windarrows commands");
if (!q->Param(kFmiWindDirection))
throw runtime_error("parameter WindDirection is not available in " + theQueryDataName);
if (theDay < 0 || theHour < 0)
throw runtime_error("time must be specified before using any contouring commands");
// Try to set the proper level on
set_level(*q, theLevel);
// Try to set the proper time on
NFmiTime t;
t.SetMin(0);
t.SetSec(0);
if (theTimeOrigin == "now")
{
t.ChangeByDays(theDay);
t.SetHour(theHour);
}
if (theTimeOrigin == "origintime")
{
t = q->OriginTime();
t.ChangeByDays(theDay);
t.ChangeByHours(theHour);
}
else if (theTimeOrigin == "firsttime")
{
q->FirstTime();
t = q->ValidTime();
t.ChangeByDays(theDay);
t.ChangeByHours(theHour);
}
// Get the data to be contoured
if (coords.get() == 0)
coords.reset(new Fmi::CoordinateMatrix(q->LocationsXY(*theArea)));
values.reset(new NFmiDataMatrix<float>(q->Values(t)));
// Loop through the data and render arrows
for (unsigned int j = 0; j < values->NY(); j += dy)
for (unsigned int i = 0; i < values->NX(); i += dx)
{
float wdir = (*values)[i][j];
NFmiPoint xy = (*coords)(i, j);
double x = xy.X();
double y = theArea->Bottom() - (xy.Y() - theArea->Top());
if ((x > theArea->Left() && x < theArea->Right()) ||
(y > theArea->Top() && y < theArea->Bottom()))
{
buffer << wdir << ' ' << x << ' ' << y << ' ' << " windarrow" << endl;
}
}
}
// ------------------------------------------------------------
// Handle the contourline <value> command
// Handle the contourfill <lolimit> <hilimit> command
// ------------------------------------------------------------
else if (token == "contourline" || token == "contourfill")
{
if (!body)
throw runtime_error(token + " command is not allowed in the header");
NFmiFastQueryInfo *q = theQueryData.QueryInfoIter();
if (q == 0)
throw runtime_error("querydata must be specified before using any contouring commands");
if (theParameter == kFmiBadParameter)
throw runtime_error("parameter must be specified before using any contouring commands");
if (!q->Param(theParameter))
throw runtime_error("parameter " + theParameterName + " is not available in " +
theQueryDataName);
// Try to set the proper level on
set_level(*q, theLevel);
if (theDay < 0 || theHour < 0)
throw runtime_error("time must be specified before using any contouring commands");
// Try to set the proper time on
NFmiTime t;
t.SetMin(0);
t.SetSec(0);
if (theTimeOrigin == "now")
{
t.ChangeByDays(theDay);
t.SetHour(theHour);
}
if (theTimeOrigin == "origintime")
{
t = q->OriginTime();
t.ChangeByDays(theDay);
t.ChangeByHours(theHour);
}
else if (theTimeOrigin == "firsttime")
{
q->FirstTime();
t = q->ValidTime();
t.ChangeByDays(theDay);
t.ChangeByHours(theHour);
}
if (theLocalTimeMode)
t = toutctime(t);
cerr << "Time = " << t << endl;
float lolimit, hilimit;
if (token == "contourline")
{
script >> lolimit;
hilimit = kFloatMissing;
}
else
{
script >> lolimit >> hilimit;
if (lolimit != kFloatMissing && hilimit != kFloatMissing && lolimit >= hilimit)
throw runtime_error(
"contourfill first argument must be smaller than "
"second argument");
}
// Get the data to be contoured
if (coords.get() == 0)
{
coords.reset(new Fmi::CoordinateMatrix(q->LocationsXY(*theArea)));
}
if (values.get() == 0)
{
values.reset(new NFmiDataMatrix<float>(q->Values(t)));
if (theSmoother != "None")
{
NFmiSmoother smoother(theSmoother, theSmootherFactor, theSmootherRadius);
*values = smoother.Smoothen(*coords, *values);
}
}
Imagine::NFmiContourTree tree(lolimit, hilimit);
if (token == "contourline")
tree.LinesOnly(true);
tree.Contour(*coords, *values, Imagine::NFmiContourTree::kFmiContourLinear);
Imagine::NFmiPath path = tree.Path();
// We don't bother to store non-smoothed contours at all
if (theBezierMode == "none")
{
buffer << pathtostring(path,
*theArea,
theClipMargin,
theMovetoCommand,
theLinetoCommand,
theCurvetoCommand,
theClosepathCommand);
}
else
{
const string name = ContourName(theContours.size() + 1);
BezierSettings bset(name, theBezierMode, theBezierSmoothness, theBezierMaxError);
theContourSettings.insert(bset);
theContours.push_back(make_pair(bset, path));
buffer << name << endl;
}
}
// ------------------------------------------------------------
// Handle a regular PostScript token line
// ------------------------------------------------------------
else
{
buffer << token;
getline(script, token);
buffer << token << endl;
}
}
// The script finished
if (!body)
{
cerr << "Error: There was no body in the script" << endl;
return 1;
}
// End the clipping
buffer << "grestore" << endl;
// Fill in the contours
string output = buffer.str();
if (!theContours.empty())
{
for (set<BezierSettings>::const_iterator sit = theContourSettings.begin();
sit != theContourSettings.end();
++sit)
{
list<string> names;
Imagine::NFmiBezierTools::NFmiPaths paths;
for (Contours::const_iterator it = theContours.begin(); it != theContours.end(); ++it)
{
if (*sit == it->first)
{
paths.push_back(it->second);
names.push_back(it->first.name);
}
}
Imagine::NFmiBezierTools::NFmiPaths outpaths;
if (sit->mode == "cardinal")
outpaths = Imagine::NFmiCardinalBezierFit::Fit(paths, sit->smoothness);
else if (sit->mode == "approximate")
outpaths = Imagine::NFmiApproximateBezierFit::Fit(paths, sit->maxerror);
else if (sit->mode == "tight")
outpaths = Imagine::NFmiTightBezierFit::Fit(paths, sit->maxerror);
else
throw runtime_error("Unknown Bezier mode " + sit->mode + " while fitting contours");
list<string>::const_iterator nit = names.begin();
Imagine::NFmiBezierTools::NFmiPaths::const_iterator it = outpaths.begin();
for (; nit != names.end() && it != outpaths.end(); ++nit, ++it)
{
const string name = *nit;
const string path = pathtostring(*it,
*theArea,
theClipMargin,
theMovetoCommand,
theLinetoCommand,
theCurvetoCommand,
theClosepathCommand);
replace(output, name, path);
}
}
}
cout << output << "end" << endl
<< "%%Trailer" << endl
<< "mysave restore" << endl
<< "%%EOF" << endl;
return 0;
}
// ----------------------------------------------------------------------
// Main program.
// ----------------------------------------------------------------------
int main(int argc, const char *argv[])
{
try
{
return domain(argc, argv);
}
catch (runtime_error &e)
{
cerr << "Error: shape2ps failed due to" << endl << "--> " << e.what() << endl;
return 1;
}
catch (...)
{
cerr << "Error: shape2ps failed due to an unknown exception" << endl;
return 1;
}
}
// ======================================================================
| 31.392245 | 100 | 0.518208 | [
"render",
"object",
"shape"
] |
91c809b916a5d2480541b01079e8dbe0a9d70714 | 48,778 | cpp | C++ | src/GUI/MediumSet.cpp | ArashMassoudieh/GIFMod_ | 1fa9eda21fab870fc3baf56462f79eb800d5154f | [
"MIT"
] | 5 | 2017-11-20T19:32:27.000Z | 2018-08-28T06:08:45.000Z | src/GUI/MediumSet.cpp | ArashMassoudieh/GIFMod_ | 1fa9eda21fab870fc3baf56462f79eb800d5154f | [
"MIT"
] | 1 | 2017-07-04T05:40:30.000Z | 2017-07-04T05:43:37.000Z | src/GUI/MediumSet.cpp | ArashMassoudieh/GIFMod_ | 1fa9eda21fab870fc3baf56462f79eb800d5154f | [
"MIT"
] | 2 | 2017-11-09T22:00:45.000Z | 2018-08-30T10:56:08.000Z | #ifdef GIFMOD
#include "MediumSet.h"
using namespace std;
CMediumSet::CMediumSet()
{
#ifdef Debug_API
showmessages = true;
#endif // Debug_API
set_default();
show_message("CMediumSet Created!");
#ifndef QT_version
showmessages = true;
#else
showmessages = false;
#endif
}
void CMediumSet::SetDefaultSolverParameters()
{
#ifdef Debug_API
show_message("Setting default solver parameters");
#endif // Debug_API
SP.dt = 0.01;
SP.epoch_limit = 1e6;
SP.mass_balance_check = false;
SP.maximum_run_time = 1e6;
SP.minimum_acceptable_negative_conc = -1e-13;
SP.negative_concentration_allowed = false;
SP.pos_def_limit = false;
SP.steady_state_hydro = false;
SP.tol = 1e-3;
SP.w = 0;
SP.solution_method="Partial Inverse Jacobian Evaluation";
SP.max_dt = 1;
SP.nr_iteration_treshold_max = 20;
SP.nr_iteration_treshold_min = 10;
SP.dt_change_rate = 0.75;
SP.dt_change_failure = 0.1;
SP.nr_failure_criteria = 100;
SP.max_J_interval = 100;
FI.write_interval = 1;
FI.write_details = false;
SP.wiggle_tolerance = 0.02;
FI.uniformoutput = true;
SP.mass_balance_check = false;
SP.forward = false;
SP.colloid_transport = false;
SP.constituent_transport = false;
SP.epoch_limit = 500000;
SP.avg_dt_limit = 1e-5;
SP.restore_interval = 20;
}
CMediumSet::~CMediumSet()
{
ANS_colloids.clear();
ANS_constituents.clear();
ANS_colloids.clear();
ANS_control.clear();
ANS_obs.clear();
ANS_hyd.clear();
gw = NULL;
}
CMediumSet::CMediumSet(string filename)
{
CLIDconfig lid(filename);
vector<string> names = lid.get_experiment_names();
if (lid.lookupkeyword("n_experiments") != -1)
Medium.resize(atoi(lid.value[lid.lookupkeyword("n_experiments")].c_str()));
else if (names.size()>0)
Medium.resize(names.size());
else
Medium.resize(1);
for (unsigned int i = 0; i < Medium.size(); i++)
{
if (names.size() == 0)
Medium[i].name = numbertostring(i);
else
Medium[i].name = names[i];
}
set_default();
f_get_environmental_params(lid);
f_get_params(lid);
f_get_observed(lid);
f_get_particle_types(lid);
f_get_constituents(lid);
f_get_reactions(lid);
f_get_buildup(lid);
f_get_external_flux(lid);
f_get_evaporation_model(lid);
vector<CLIDconfig> L = lid.extract_subsets();
for (unsigned int i = 0; i < Medium.size(); i++)
Medium[i].create(L[i], this);
}
CMediumSet::CMediumSet(const CMediumSet &M)
{
failed = M.failed;
Medium = M.Medium;
Solid_phase = M.Solid_phase;
parameters = M.parameters;
SP = M.SP;
std = M.std;
FI = M.FI;
PE_info_filename = M.PE_info_filename;
formulas = M.formulas;
RXN = M.RXN;
for (unsigned int i = 0; i < Medium.size(); i++)
Medium[i].parent = this;
set_features = M.set_features;
measured_quan = M.measured_quan;
measured_data = M.measured_data;
buildup = M.buildup;
externalflux = M.externalflux;
evaporation_model = M.evaporation_model;
ANS_obs = M.ANS_obs;
for (unsigned int i = 0; i < Medium.size(); i++)
{
ANS_hyd.push_back(&Medium[i].Results.ANS);
ANS_colloids.push_back(&Medium[i].Results.ANS_colloids);
ANS_constituents.push_back(&Medium[i].Results.ANS_constituents);
ANS_control.push_back(&Medium[i].Results.ANS_control);
}
Control = M.Control;
ID = M.ID;
MSE_obs = M.MSE_obs;
}
CMediumSet& CMediumSet::operator=(const CMediumSet &M)
{
failed = M.failed;
Medium = M.Medium;
Solid_phase = M.Solid_phase;
parameters = M.parameters;
std = M.std;
SP = M.SP;
FI = M.FI;
PE_info_filename = M.PE_info_filename;
formulas = M.formulas;
RXN = M.RXN;
for (unsigned int i = 0; i < Medium.size(); i++)
Medium[i].parent = this;
set_features = M.set_features;
measured_quan = M.measured_quan;
measured_data = M.measured_data;
buildup = M.buildup;
externalflux = M.externalflux;
evaporation_model = M.evaporation_model;
ANS_hyd.clear();
ANS_colloids.clear();
ANS_constituents.clear();
ANS_control.clear();
for (unsigned int i = 0; i < Medium.size(); i++)
{
ANS_hyd.push_back(&Medium[i].Results.ANS);
ANS_colloids.push_back(&Medium[i].Results.ANS_colloids);
ANS_constituents.push_back(&Medium[i].Results.ANS_constituents);
ANS_control.push_back(&Medium[i].Results.ANS_constituents);
}
ANS_obs = M.ANS_obs;
Control = M.Control;
ID = M.ID;
MSE_obs = M.MSE_obs;
return *this;
}
void CMediumSet::set_formulas()
{
show_message(string("Setting formulas..."));
formulas.formulasH.resize(10);
formulas.formulasH[Soil] = "_frs[(f[5]+f[6]-(((1/f[53])*(((_max(_min(f[9]:1):0.001)^(f[54]/(1-f[54])))-1)^(1/f[54])))*((1-_min(f[9]:1))/(0.01+1-_min(f[9]:1))))+(_mon((f[9]-1):0.05)*(_pos(f[9]-1)*f[51]/f[57])))]";
formulas.formulasH[Darcy] = "f[6]+f[5]+((f[10]-f[51])/f[57])";
formulas.formulasH[Storage] = "f[5]+(_pos(f[4])/(f[2]*f[51]))+(_mon((f[9]-1):0.01)*(f[9]-1)*f[51]/f[57])-(f[65]/((f[9]+0.0000001)^f[66]))";
formulas.formulasH[Pond] = "f[5]+(f[4]/f[2])";
formulas.formulasH[Catchment] = "f[5]+(f[4]/f[2])";
formulas.formulasH[Stream] = "f[5]+(f[4]/f[2])";
formulas.formulasH[Manhole] = "f[5]+(f[4]/f[2])";
formulas.formulasH[Plant] = "f[5]-((1/f[53])*((_min(_max(f[9]:0.00001):1)^(-f[54]))-1))+(_pos(f[9]-1)*f[51]/f[57])";
formulas.formulas.resize(10);
formulas.formulasQ.resize(10);
formulas.formulasA.resize(10);
formulas.const_area.resize(10);
for (unsigned int i = 0; i < formulas.formulasQ.size(); i++) formulas.formulasQ[i].resize(10);
for (unsigned int i = 0; i < formulas.formulasA.size(); i++)
{
formulas.formulasA[i].resize(10);
for (unsigned int j = 0; j < formulas.formulasA[i].size(); j++) formulas.formulasA[i][j] = "(s[2]+e[2])/2";
}
for (unsigned int i = 0; i < formulas.const_area.size(); i++) {
formulas.const_area[i].resize(10); for (unsigned int j = 0; j < formulas.const_area[i].size(); j++) formulas.const_area[i][j] = true;
}
formulas.vaporTransport.resize(10);
for (unsigned int i = 0; i < formulas.vaporTransport.size(); i++) formulas.vaporTransport[i].resize(10);
formulas.settling.resize(10);
for (unsigned int i = 0; i <formulas.settling.size(); i++) formulas.settling[i].resize(10);
formulas.vaporTransport[Soil][Soil] = 1;
formulas.vaporTransport[Soil][Pond] = 1;
formulas.vaporTransport[Soil][Storage] = 1;
formulas.vaporTransport[Soil][Darcy] = 1;
formulas.vaporTransport[Soil][Stream] = 1;
formulas.vaporTransport[Soil][Catchment] = 1;
formulas.vaporTransport[Pond][Soil] = 1;
formulas.vaporTransport[Storage][Soil] = 1;
formulas.vaporTransport[Darcy][Soil] = 1;
formulas.vaporTransport[Stream][Soil] = 1;
formulas.vaporTransport[Catchment][Soil] = 1;
formulas.settling[Storage][Storage] = 1;
formulas.settling[Pond][Soil] = 1;
formulas.settling[Soil][Pond] = 1;
formulas.settling[Stream][Darcy] = 1;
formulas.settling[Darcy][Stream] = 1;
formulas.settling[Pond][Darcy] = 1;
formulas.settling[Darcy][Pond] = 1;
formulas.air_phase.resize(10);
formulas.air_phase[Soil] = 1;
formulas.formulasQ2 = formulas.formulasQ;
formulas.formulasA[Catchment][Catchment] = "0.5*f[85]*((s[1]-s[5])+(e[1]-e[5]))";
formulas.formulasA[Catchment][Pond] = "f[85]*(s[1]-s[5])";
formulas.formulasA[Pond][Catchment] = "f[85]*(e[1]-e[5])";
formulas.formulasA[Catchment][Stream] = "f[85]*(s[1]-s[5])";
formulas.formulasA[Stream][Catchment] = "f[85]*(e[1]-e[5])";
formulas.formulasA[Stream][Stream] = "0.5*f[85] * (_pos(s[1] - _max(s[5]:f[60])) + _pos(e[1] - _max(e[5]:f[60])))";
formulas.formulasA[Stream][Pond] = "f[85]*_pos(s[1]-_max(s[5]:f[60]))";
formulas.formulasA[Pond][Pond] = "0.5*f[85]*(_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))";
formulas.formulasA[Storage][Storage] = "0.5*f[85]*((s[4]/(s[2]*s[51]))+(e[4]/(e[2]*e[51])))";
formulas.const_area[Catchment][Catchment] = false;
formulas.const_area[Catchment][Pond] = false;
formulas.const_area[Pond][Catchment] = false;
formulas.const_area[Catchment][Stream] = false;
formulas.const_area[Stream][Catchment] = false;
formulas.const_area[Stream][Stream] = false;
formulas.const_area[Stream][Pond] = false;
formulas.const_area[Pond][Pond] = false;
formulas.const_area[Storage][Storage] = false;
formulas.formulasQ[Soil][Storage] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(_pos(s[1]-_max(e[1]:s[5]))-_pos(e[1]-s[1]))/f[6]*f[2])";
formulas.formulasQ[Soil][Soil] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ[Soil][Pond] = "0.5*(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]+(f[50]))*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Soil][Darcy] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^s[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/s[55])))^s[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ[Soil][Catchment] = "(_frs[(s[50]*(_max(_min(s[9]:1):0)^s[56])*((1-((1-(_max(_min(s[9]:1):0)^(1/s[55])))^s[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ[Soil][Plant] = "f[3]*f[50]*(s[1]-e[1])";
formulas.formulasQ2[Soil][Soil] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ2[Soil][Storage] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ2[Soil][Pond] = "0.5*(_frs[(-f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]-(f[50]))*(e[1]-s[1])/f[6]*f[2]";// *(_mon((e[4] / e[2]) : 0.001))";
formulas.formulasQ2[Soil][Darcy] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^s[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/s[55])))^s[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
//formulas.formulasQ2[Soil][Catchment] = "_frs[((-f[50])*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(e[1]-s[1])/f[6]*f[2]*(_mon((s[4]/s[2]):0.001))";
formulas.formulasQ2[Soil][Catchment] = "-(f[50]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ2[Soil][Plant] = "f[3]*f[50]*(s[1]-e[1])";
formulas.formulasQ[Pond][Pond] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60])-s[62])+_pos(e[1]-_max(e[5]:f[60])-s[62]))/2)^1.66667)";
formulas.formulasQ2[Pond][Pond] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60])-s[62])+_pos(e[1]-_max(e[5]:f[60])-s[62]))/2)^1.66667)";
formulas.formulasQ[Pond][Soil] = "0.5*(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]+(f[50]))*(s[1]-e[1])/f[6]*f[2]";// *(_mon((s[4] / s[2]) : 0.001))";
formulas.formulasQ[Pond][Storage] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Pond][Darcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Pond][Stream] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))/2)^1.66667)";
formulas.formulasQ[Pond][Catchment] = "0";
formulas.formulasQ2[Pond][Stream] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))/2)^1.66667)";
formulas.formulasQ2[Pond][Darcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Pond][Storage] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Pond][Soil] = "0.5*(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]+(f[50]))*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Pond][Catchment] = "(-f[85])/f[56]*_sqs((e[1]-s[1])/f[6])*_mon((_abs(e[1]-s[1])/f[6]):0.0001)*((_pos(e[1]-e[5]-e[62])^(1+f[58]))";
formulas.formulasQ[Stream][Stream] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))/2)^1.66667)";
formulas.formulasQ[Stream][Darcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Stream][Stream] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))/2)^1.66667)";
formulas.formulasQ2[Stream][Pond] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))/2)^1.66667)";
formulas.formulasQ[Storage][Soil] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ[Storage][Storage] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Storage][Pond] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Storage][Catchment] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Storage][Catchment] = "0";
formulas.formulasQ2[Storage][Storage] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Storage][Pond] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Storage][Catchment] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Storage][Soil] = "(_frs[((-f[50])*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(_pos(e[1]-_max(s[1]:e[5]))-_pos(s[1]-e[1]))/f[6]*f[2])";
formulas.formulasQ[Darcy][Darcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Darcy][Pond] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Darcy][Catchment] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Darcy][Soil] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^e[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/e[55])))^e[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ2[Darcy][Stream] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Darcy][Pond] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Darcy][Catchment] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Darcy][Soil] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^e[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/e[55])))^e[55]))^2))]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ[Catchment][Storage] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Catchment][Darcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ[Catchment][Catchment] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-s[5]):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-e[5]):0.01)))*(((_hsd(s[1]-e[1])*_pos(s[1]-s[5]-s[62]))+(_hsd(e[1]-s[1])*_pos(e[1]-e[5]-s[62])))^(1+f[58]))";
formulas.formulasQ[Catchment][Pond] = "f[85]/f[56]*_sqs((s[1]-e[1])/f[6])*_mon((_abs(s[1]-e[1])/f[6]):0.0001)*((_pos(s[1]-s[5]-s[62])^(1+f[58]))";
formulas.formulasQ[Catchment][Stream] = "f[85]/f[56]*_sqs((s[1]-e[1])/f[6])*_mon((_abs(s[1]-e[1])/f[6]):0.0001)*((_pos(s[1]-s[5]-s[62])^(1+f[58]))";
//formulas.formulasQ[Catchment][Storage] = "f[55]/f[56]*_sqs((s[1]-e[1])/f[6])*_mon(_abs(s[1]-e[1])/f[6]:0.001)*((_pos(s[1]-s[5]-s[12])^(1+f[58]))";
//formulas.formulasQ[Catchment][Soil] = "(_frs[(f[50]*(_max(_min(f[9]:1):0)^f[56])*((1-((1-(_max(_min(f[9]:1):0)^(1/f[55])))^f[55]))^2))]*(s[1]-e[1])/f[6]*f[2]*(_mon((e[4]/e[2]):0.001)))";
formulas.formulasQ[Catchment][Soil] = "(f[50]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ2[Catchment][Storage] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Catchment][Darcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulasQ2[Catchment][Catchment] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-s[5]):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-e[5]):0.01)))*(((_hsd(s[1]-e[1])*_pos(s[1]-s[5]-s[12]))+(_hsd(e[1]-s[1])*_pos(e[1]-e[5]-s[12])))^(1+f[58]))";
formulas.formulasQ2[Catchment][Pond] = "0";
formulas.formulasQ2[Catchment][Stream] = "0";
formulas.formulasQ2[Catchment][Storage] = "0";
formulas.formulasQ2[Catchment][Soil] = "(f[50]*(s[1]-e[1])/f[6]*f[2])";
formulas.formulasQ[Stream][Pond] = "f[85]/f[56]*((_sq2(_pos((s[1]-e[1])/f[6]):0.001)*_mon((s[1]-_max(s[5]:f[60])):0.01))-(_sq2(_pos((e[1]-s[1])/f[6]):0.001)*_mon((e[1]-_max(e[5]:f[60])):0.01)))*(((_pos(s[1]-_max(s[5]:f[60]))+_pos(e[1]-_max(e[5]:f[60])))/2)^1.66667)";
formulas.formulasQ[Stream][Catchment] = "0";
formulas.formulasQ2[Stream][Catchment] = "(-f[85])/f[56]*_sqs((e[1]-s[1])/f[6])*_mon((_abs(s[1]-e[1])/f[6]):0.0001)*((_pos(e[1]-e[5]-e[62])^(1+f[58]))";
formulas.formulasQ[Plant][Soil] = "f[3]*f[50]*(s[1]-e[1])*(_max(_min(f[9]:0)^s[54])*f[2]*s[3]";
formulas.formulasQ2[Soil][Plant] = "f[3]*f[50]*(s[1]-e[1])*(_max(_min(f[9]:0)^e[54])*f[2]*e[3]";
//formulas.formulasQ2[Storage][Catchment] = "(-f[55])/f[56]*_sqs((e[1]-s[1])/f[6])*_mon(_abs(s[1]-e[1])/f[6]:0.001)*((_pos(e[1]-e[5]-e[12])^(1+f[58]))";
formulas.formulas[Normal] = "f[85]/f[56]*((_sq2(_pos((s[5]-e[5])/f[6]):0.001)*_mon((s[1]-s[5]):0.01))-(_sq2(_pos((e[5]-s[5])/f[6]):0.001)*_mon((e[1]-e[5]):0.01)))*(((_pos(s[1]-s[5])+_pos(e[1]-e[5]))/2)^(1+f[58])";
formulas.formulas[QDarcy] = "f[50]*(s[1]-e[1])/f[6]*f[2]";
formulas.formulas[Vapor] = "(((e[13]+s[13])/2*(s[10]-e[10])/f[6]*f[2]*(_pos(s[51]-s[10])+_pos(e[51]-e[10]))/2))";
formulas.formulas[Pipe1] = "(f[52]^2.63)*23760*f[67]*((_pos(s[1]-f[61])/f[6])^0.54)*_hsd(s[1]-f[60])";
formulas.formulas[Pipe2] = "(f[52]^2.63)*23760*f[67]*_ply(_max(((e[1]-f[61])/f[52]):((s[1]-f[60])/f[52])))*_mo1(((((_pos(s[1]-_max(e[1]:f[61]))/f[6])^0.54))-(((_pos(e[1]-_max(s[1]:f[60]))/f[6])^0.54))):0.001)"; //Q in m3/d
formulas.formulas[Rating_curve] = "(_hsd(s[1]-e[1])*f[62]*(_pos(s[1]-f[64])^f[63]))-(_hsd(e[1]-s[1])*f[62]*(_pos(e[1]-f[64])^f[63]))";
set_features.formulas = true;
}
void CMediumSet::solve()
{
failed = false;
if (FI.write_details)
{
FILE *FILEBTC = fopen((FI.outputpathname + "Solution_details_" + ID + ".txt").c_str(), "w");
fclose(FILEBTC);
}
failed = false;
ANS_hyd.clear();
ANS_colloids.clear();
ANS_constituents.clear();
ANS_control.clear();
for (unsigned int i = 0; i < Medium.size(); i++)
{
Medium[i].solve();
failed = failed || Medium[i].Solution_State.failed;
ANS_hyd.push_back(&Medium[i].Results.ANS);
ANS_colloids.push_back(&Medium[i].Results.ANS_colloids);
ANS_constituents.push_back(&Medium[i].Results.ANS_constituents);
ANS_control.push_back(&Medium[i].Results.ANS_control);
}
ANS_obs = CBTCSet(measured_quan.size());
for (unsigned int i = 0; i < measured_quan.size(); i++)
{
if (lookup_medium(measured_quan[i].experiment) != -1)
{
ANS_obs.BTC[i] = Medium[lookup_medium(measured_quan[i].experiment)].Results.ANS_obs.BTC[i];
ANS_obs.setname(i, measured_quan[i].name);
calc_MSE(i);
}
}
CVector(MSE_obs).writetofile(FI.outputpathname + "MSE" + ID + ".txt");
}
void CMediumSet::set_default()
{
SetDefaultSolverParameters();
#ifdef Debug_API
show_message("Setting formulas");
#endif // Debug_API
if (!get_formulas_from_file("formulas.txt"))
{
#ifdef Debug_API
show_message("Setting hardcoded formulas");
#endif // Debug_API
set_formulas();
}
}
void CMediumSet::f_get_environmental_params(CLIDconfig &lid_config)
{
SP.pos_def_limit = true;
SP.negative_concentration_allowed = false;
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "path") FI.pathname = lid_config.value[i].c_str();
if (tolower(lid_config.keyword[i]) == "outputpath") FI.outputpathname = lid_config.value[i].c_str();
if (tolower(lid_config.keyword[i]) == "forward") SP.forward = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "solution_method") SP.solution_method = lid_config.value[i];
if (tolower(lid_config.keyword[i]) == "wiggle_tolerance") SP.wiggle_tolerance = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "max_j_update_interval") SP.max_J_interval = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "dt") SP.dt = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "w") SP.w = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "tol") SP.tol = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "max_dt") SP.max_dt = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "uniformoutput") FI.uniformoutput = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "nr_iteration_treshold_max") SP.nr_iteration_treshold_max = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "nr_iteration_treshold_min") SP.nr_iteration_treshold_min = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "dt_change_rate") SP.dt_change_rate = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "dt_change_failure") SP.dt_change_failure = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "nr_failure_criteria") SP.nr_failure_criteria = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "write_details") FI.write_details = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "mass_balance_check") SP.mass_balance_check = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "colloid_transport") SP.colloid_transport = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "water_quality") SP.constituent_transport = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "epoch_limit") SP.epoch_limit = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "avg_dt_limit") SP.avg_dt_limit = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "restore_interval") SP.restore_interval = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "log_file") FI.log_file_name = FI.outputpathname + lid_config.value[i];
if (tolower(lid_config.keyword[i]) == "pe_info_filename") PE_info_filename = lid_config.value[i];
if (tolower(lid_config.keyword[i]) == "writeinterval") FI.write_interval = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "pos_def_limit") SP.pos_def_limit = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "negative_concentration_allowed") SP.negative_concentration_allowed = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "minimum_acceptable_negative_conc") SP.minimum_acceptable_negative_conc = atof(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "steady_state_hydro") SP.steady_state_hydro = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "check_oscillation") SP.check_oscillation = atoi(lid_config.value[i].c_str());
if (tolower(lid_config.keyword[i]) == "detout_obs_filename")
{
vector<string> names = split_curly_semicolon(lid_config.value[i]);
for (unsigned int ii = 0; ii<names.size(); ii++)
FI.detoutfilename_obs = names[ii];
}
}
if (SP.constituent_transport) SP.colloid_transport = true;
set_features.environmental_vars = true;
}
void CMediumSet::f_get_params(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "parameter")
{
param_range P;
P.low = 0;
P.high = 0;
P.fixed = false;
P.log = false;
P.applytoall = true;
P.tempcorr = 1;
P.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
if (tolower(lid_config.param_names[i][j]) == "low") P.low = atof(lid_config.param_vals[i][j].c_str()); //low range
if (tolower(lid_config.param_names[i][j]) == "high") P.high = atof(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "temp_corr") P.tempcorr = atof(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "fixed") P.fixed = atoi(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "applytoall") P.applytoall = atoi(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "log") P.log = atoi(lid_config.param_vals[i][j].c_str());
}
parameters.push_back(P);
if (P.log == 0)
P.value = 0.5*(P.low + P.high);
else
P.value = P.low / fabs(P.low)*sqrt(P.low*P.high);
}
}
set_features.parameters = true;
}
void CMediumSet::f_get_observed(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "observed")
{
measured_chrc M;
M.error_structure = 0;
M.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
if (tolower(lid_config.param_names[i][j]) == "id") M.id = split(lid_config.param_vals[i][j], '+'); //location id
if (tolower(lid_config.param_names[i][j]) == "loc_type") {if (tolower(lid_config.param_vals[i][j]) == "b") M.loc_type = 0; else if (tolower(lid_config.param_vals[i][j]) == "c") M.loc_type = 1;}
if (tolower(lid_config.param_names[i][j]) == "quan") M.quan = lid_config.param_vals[i][j].c_str();
if (tolower(lid_config.param_names[i][j]) == "std_no") M.std_no = atoi(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "error_structure") M.error_structure = atoi(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "experiment") M.experiment = lid_config.param_vals[i][j].c_str();
}
measured_quan.push_back(M);
}
if (tolower(lid_config.keyword[i]) == "observed_data")
{
measured_data = CBTCSet(FI.pathname + lid_config.value[i], 1);
if (measured_data.names.size() == 0)
writetolog("observed data lacks name field");
}
}
vector<int> stds;
for (unsigned int i = 0; i<measured_quan.size(); i++)
{
if (lookup(stds, measured_quan[i].std_no) == -1)
{
stds.push_back(measured_quan[i].std_no);
measured_quan[i].std_to_param = int(parameters.size());
param_range P;
P.fixed = false;
P.log = true;
P.applytoall = true;
P.tempcorr = 1;
P.name = "std_" + numbertostring(i);
P.low = exp(-4); P.high = exp(4);
P.value = sqrt(P.high*P.low);
parameters.push_back(P);
}
}
std.resize(stds.size());
set_features.observed = true;
}
void CMediumSet::f_get_sensors(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i < lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "sensor")
{
CSensor M;
M.error_structure = 0;
M.name = lid_config.value[i];
for (unsigned int j = 0; j < lid_config.param_names[i].size(); j++)
{
if (tolower(lid_config.param_names[i][j]) == "id") M.id = lid_config.param_vals[i][j]; //location id
if (tolower(lid_config.param_names[i][j]) == "loc_type") {if (tolower(lid_config.param_vals[i][j]) == "b") M.loc_type = 0; else if (tolower(lid_config.param_vals[i][j]) == "c") M.loc_type = 1;}
if (tolower(lid_config.param_names[i][j]) == "quan") M.quan = CStringOP(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "error_std") M.error_std = atof(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "error_structure") M.error_structure = atoi(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "interval") M.interval = atof(lid_config.param_vals[i][j].c_str());
}
Control.Sensors.push_back(M);
}
}
}
void CMediumSet::f_get_controller(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i < lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "controller")
{
CController M;
M.name = lid_config.value[i];
for (unsigned int j = 0; j < lid_config.param_names[i].size(); j++)
{
M.set_val(lid_config.param_names[i][j], atof(lid_config.param_vals[i][j].c_str()));
if (tolower(lid_config.param_names[i][j]) == "interval") M.interval = atof(lid_config.param_vals[i][j].c_str());
}
Control.Controllers.push_back(M);
}
}
}
void CMediumSet::writetolog(string S)
{
fstream file(FI.outputpathname + FI.log_file_name);
file << S << std::endl;
file.close();
}
void CMediumSet::f_get_particle_types(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if ((tolower(lid_config.keyword[i]) == "particulate_phase") || (tolower(lid_config.keyword[i]) == "solid_phase") || (tolower(lid_config.keyword[i]) == "particle"))
{
CSolid_Phase S(lid_config.param_vals[i][lookup(lid_config.param_names[i], "model")]);
S.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
S.set_val(lid_config.param_names[i][j], atof(lid_config.param_vals[i][j].c_str()));
}
Solid_phase.push_back(S);
}
}
set_features.solids = true;
}
void CMediumSet::f_get_constituents(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "constituent")
{
CConstituent S;
S.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
vector<char> del2; del2.push_back('['); del2.push_back(']'); del2.push_back(':');
if (tolower(split(lid_config.param_names[i][j], del2)[0]) == "kd")
{
S.capacity.push_back(atof(lid_config.param_vals[i][j].c_str()));
S.capacity_ptr.push_back(split(lid_config.param_names[i][j], del2)[1]);
}
if (tolower(split(lid_config.param_names[i][j], del2)[0]) == "rate")
{
S.rate_exchange.push_back(atof(lid_config.param_vals[i][j].c_str()));
S.rate_exchange_ptr.push_back(split(lid_config.param_names[i][j], del2)[1]);
}
if (tolower(lid_config.param_names[i][j]) == "diffusion")
{
S.diffusion = atof(lid_config.param_vals[i][j].c_str());
}
if (tolower(lid_config.param_names[i][j]) == "exchange_rate_factor")
{
S.exchange_rate_scale_factor = CStringOP(lid_config.param_vals[i][j]);
}
if (tolower(lid_config.param_names[i][j]) == "exchange_rate_param")
{
S.exchange_params.push_back(atof(lid_config.param_vals[i][j].c_str()));
}
if (tolower(lid_config.param_names[i][j]) == "vs")
{
S.vs = atof(lid_config.param_vals[i][j].c_str());
}
}
RXN.cons.push_back(S);
for (unsigned int ii = 0; ii<lid_config.est_param[i].size(); ii++)
{
if (lookup_parameters(lid_config.est_param[i][ii]) != -1)
{
parameters[lookup_parameters(lid_config.est_param[i][ii])].location.push_back(RXN.cons.size() - 1);
parameters[lookup_parameters(lid_config.est_param[i][ii])].quan.push_back(lid_config.param_names[i][ii]);
parameters[lookup_parameters(lid_config.est_param[i][ii])].location_type.push_back(4);
parameters[lookup_parameters(lid_config.est_param[i][ii])].experiment_id.push_back("");
}
}
}
}
set_features.constituents = true;
}
int CMediumSet::lookup_parameters(string S)
{
int out = -1;
for (unsigned int i = 0; i < parameters.size(); i++)
if (tolower(S) == tolower(parameters[i].name))
return i;
return out;
}
int CMediumSet::lookup_controllers(string S)
{
int out = -1;
for (unsigned int i = 0; i < Control.Controllers.size(); i++)
if (tolower(S) == tolower(Control.Controllers[i].name))
return i;
return out;
}
int CMediumSet::lookup_observation(string S) const
{
int out = -1;
for (unsigned int i = 0; i < measured_quan.size(); i++)
if (tolower(S) == tolower(measured_quan[i].name))
return i;
return out;
}
void CMediumSet::f_get_reactions(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i < lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "reaction_parameter")
{
rxparam rxparameter;
rxparameter.tempcorr = 1;
rxparameter.name = lid_config.value[i];
for (unsigned int j = 0; j < lid_config.param_names[i].size(); j++)
{
if (tolower(lid_config.param_names[i][j]) == "value") rxparameter.value = atof(lid_config.param_vals[i][j].c_str());
if (tolower(lid_config.param_names[i][j]) == "temperature_correction") { rxparameter.tempcorr = atof(lid_config.param_vals[i][j].c_str()); }
}
RXN.parameters.push_back(rxparameter);
for (unsigned int ii = 0; ii < lid_config.est_param[i].size(); ii++)
{
if (lookup_parameters(lid_config.est_param[i][ii]) != -1)
{
parameters[lookup_parameters(lid_config.est_param[i][ii])].location.push_back(RXN.parameters.size() - 1);
parameters[lookup_parameters(lid_config.est_param[i][ii])].quan.push_back(lid_config.value[i]);
parameters[lookup_parameters(lid_config.est_param[i][ii])].location_type.push_back(3);
parameters[lookup_parameters(lid_config.est_param[i][ii])].experiment_id.push_back("");
}
}
}
}
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if (tolower(lid_config.keyword[i]) == "reaction")
{
CReaction Rx;
Rx.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
vector<char> del2; del2.push_back('['); del2.push_back(']'); del2.push_back(':');
if (tolower(split(lid_config.param_names[i][j], del2)[0]) == "rate") Rx.rate = CStringOP(lid_config.param_vals[i][j], &RXN);
if (tolower(split(lid_config.param_names[i][j], del2)[0]) == "product")
{
Rx.products.push_back(RXN.look_up_constituent_no(split(lid_config.param_names[i][j], del2)[1])); Rx.prodrates.push_back(CStringOP(lid_config.param_vals[i][j], &RXN));
if (split(lid_config.param_names[i][j], del2).size()>2)
Rx.product_p_type.push_back(atoi(split(lid_config.param_names[i][j], del2)[2].c_str()));
else
Rx.product_p_type.push_back(-2);
if (split(lid_config.param_names[i][j], del2).size()>3)
Rx.product_phase.push_back(atoi(split(lid_config.param_names[i][j], del2)[3].c_str()));
else
Rx.product_phase.push_back(0);
}
}
RXN.Rxts.push_back(Rx);
}
}
set_features.reactions = true;
}
void CMediumSet::f_get_buildup(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if ((tolower(lid_config.keyword[i]) == "build_up") || (tolower(lid_config.keyword[i]) == "buildup"))
{
CBuildup S(lid_config.param_vals[i][lookup(lid_config.param_names[i], "model")]);
S.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
if (lid_config.param_names[i][j] == "constituent") S.constituent = lid_config.param_vals[i][j];
if (lid_config.param_names[i][j] == "solid") S.solid = lid_config.param_vals[i][j];
S.set_val(lid_config.param_names[i][j], atof(lid_config.param_vals[i][j].c_str()));
}
if ((S.constituent == "") && (S.solid != "") && (S.phase == "")) S.phase = "attached";
if ((S.solid == "") && (S.constituent != "") && (S.phase == "")) S.phase = "sorbed";
buildup.push_back(S);
for (unsigned int ii = 0; ii<lid_config.est_param[i].size(); ii++)
{
if (lookup_parameters(lid_config.est_param[i][ii]) != -1)
{
parameters[lookup_parameters(lid_config.est_param[i][ii])].location.push_back(externalflux.size() - 1);
parameters[lookup_parameters(lid_config.est_param[i][ii])].quan.push_back(lid_config.param_names[i][ii]);
parameters[lookup_parameters(lid_config.est_param[i][ii])].location_type.push_back(5);
parameters[lookup_parameters(lid_config.est_param[i][ii])].experiment_id.push_back("");
}
}
}
}
set_features.buildup = true;
}
void CMediumSet::f_get_external_flux(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if ((tolower(lid_config.keyword[i]) == "external_flux") || (tolower(lid_config.keyword[i]) == "externalflux"))
{
CEnvExchange S(lid_config.param_vals[i][lookup(lid_config.param_names[i], "model")]);
S.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
if (lid_config.param_names[i][j] == "constituent") S.constituent = lid_config.param_vals[i][j];
if (lid_config.param_names[i][j] == "solid") S.solid = lid_config.param_vals[i][j];
S.set_val(lid_config.param_names[i][j], atof(lid_config.param_vals[i][j].c_str()));
if (lid_config.param_names[i][j] == "expression") S.expression = lid_config.param_vals[i][j];
}
externalflux.push_back(S);
for (unsigned int ii = 0; ii<lid_config.est_param[i].size(); ii++)
{
if (lookup_parameters(lid_config.est_param[i][ii]) != -1)
{
parameters[lookup_parameters(lid_config.est_param[i][ii])].location.push_back(externalflux.size() - 1);
parameters[lookup_parameters(lid_config.est_param[i][ii])].quan.push_back(lid_config.param_names[i][ii]);
parameters[lookup_parameters(lid_config.est_param[i][ii])].location_type.push_back(6);
parameters[lookup_parameters(lid_config.est_param[i][ii])].experiment_id.push_back("");
}
}
}
}
set_features.external_flux = true;
}
void CMediumSet::f_get_evaporation_model(CLIDconfig &lid_config)
{
for (unsigned int i = 0; i<lid_config.keyword.size(); i++)
{
if ((tolower(lid_config.keyword[i]) == "evaporation_model"))
{
CEvaporation S(lid_config.param_vals[i][lookup(lid_config.param_names[i], "model")]);
S.name = lid_config.value[i];
for (unsigned int j = 0; j<lid_config.param_names[i].size(); j++)
{
if (lid_config.param_names[i][j] == "expression") S.expression = lid_config.param_vals[i][j];
S.set_val(lid_config.param_names[i][j], atof(lid_config.param_vals[i][j].c_str()));
if (lid_config.param_names[i][j] == "time_series") S.evaporation_filename = lid_config.param_vals[i][j];
if (lid_config.param_names[i][j] == "FAO-56 single crop coefficient time-series") S.single_crop_coefficient_filename = lid_config.param_vals[i][j];
if (lid_config.param_names[i][j] == "uptake_constituents") S.uptake = atoi(lid_config.param_vals[i][j].c_str());
}
evaporation_model.push_back(S);
for (unsigned int ii = 0; ii<lid_config.est_param[i].size(); ii++)
{
if (lookup_parameters(lid_config.est_param[i][ii]) != -1)
{
parameters[lookup_parameters(lid_config.est_param[i][ii])].location.push_back(evaporation_model.size() - 1);
parameters[lookup_parameters(lid_config.est_param[i][ii])].quan.push_back(lid_config.param_names[i][ii]);
parameters[lookup_parameters(lid_config.est_param[i][ii])].location_type.push_back(7);
parameters[lookup_parameters(lid_config.est_param[i][ii])].experiment_id.push_back("");
}
}
}
}
set_features.evaporation = true;
}
void CMediumSet::set_param(int param_no, double _value)
{
for (unsigned int i = 0; i<parameters[param_no].location.size(); i++)
{
double value;
if (parameters[param_no].conversion_factor.size())
value = _value*parameters[param_no].conversion_factor[i];
else
value = _value;
if ((parameters[param_no].location_type[i] == 2) || (parameters[param_no].location_type[i] == 1) || (parameters[param_no].location_type[i] == 0))
{
for (unsigned int j = 0; j < Medium.size(); j++)
if (parameters[param_no].experiment_id[i] == Medium[j].name)
Medium[j].set_param(param_no, value);
}
else if (parameters[param_no].location_type[i] == 3)
RXN.parameters[RXN.look_up_rxn_parameters(parameters[param_no].quan[i])].value = value;
else if (parameters[param_no].location_type[i] == 4)
RXN.cons[parameters[param_no].location[i]].set_val(parameters[param_no].quan[i], value);
else if (parameters[param_no].location_type[i] == 5)
buildup[parameters[param_no].location[i]].set_val(parameters[param_no].quan[i], value);
else if (parameters[param_no].location_type[i] == 6)
externalflux[parameters[param_no].location[i]].set_val(parameters[param_no].quan[i], value);
else if (parameters[param_no].location_type[i] == 7)
evaporation_model[parameters[param_no].location[i]].set_val(parameters[param_no].quan[i], value);
}
for (unsigned int i = 0; i<measured_quan.size(); i++)
if (measured_quan[i].std_to_param == param_no)
std[measured_quan[i].std_no] = _value;
}
void CMediumSet::set_control_param(int controller_no, int experiment_id)
{
for (unsigned int i = 0; i<Control.Controllers[controller_no].application_spec.location.size(); i++)
{
/*double value;
if (Control.Controllers[controller_no].application_spec.conversion_factor.size())
value = Control.Controllers[controller_no].value*Control.Controllers[controller_no].application_spec.conversion_factor[i];
else
value = Control.Controllers[controller_no].value;
*/
if ((Control.Controllers[controller_no].application_spec.location_type[i] == 2) || (Control.Controllers[controller_no].application_spec.location_type[i] == 1) || (Control.Controllers[controller_no].application_spec.location_type[i] == 0))
{
if (Control.Controllers[controller_no].application_spec.experiment_id[i] == Medium[experiment_id].name)
Medium[experiment_id].set_control_params(controller_no);
}
else if (Control.Controllers[controller_no].application_spec.location_type[i] == 3)
RXN.parameters[RXN.look_up_rxn_parameters(Control.Controllers[controller_no].application_spec.quan[i])].value = Control.Controllers[controller_no].value;
else if (Control.Controllers[controller_no].application_spec.location_type[i] == 4)
RXN.cons[Control.Controllers[controller_no].application_spec.location[i]].set_val(Control.Controllers[controller_no].application_spec.quan[i], Control.Controllers[controller_no].value);
else if (Control.Controllers[controller_no].application_spec.location_type[i] == 5)
buildup[Control.Controllers[controller_no].application_spec.location[i]].set_val(Control.Controllers[controller_no].application_spec.quan[i], Control.Controllers[controller_no].value);
else if (Control.Controllers[controller_no].application_spec.location_type[i] == 6)
externalflux[Control.Controllers[controller_no].application_spec.location[i]].set_val(Control.Controllers[controller_no].application_spec.quan[i], Control.Controllers[controller_no].value);
else if (Control.Controllers[controller_no].application_spec.location_type[i] == 7)
evaporation_model[Control.Controllers[controller_no].application_spec.location[i]].set_val(Control.Controllers[controller_no].application_spec.quan[i], Control.Controllers[controller_no].value);
}
}
int CMediumSet::lookup_medium(string S)
{
int j = -1;
for (unsigned int i = 0; i < Medium.size(); i++)
if (Medium[i].name == S) return i;
return j;
}
double CMediumSet::calc_log_likelihood() //calculate sum log likelihood for time series data ts
{
double sum = 0;
MSE_obs.clear();
solve();
if (failed == true) return -1e30;
for (unsigned int i = 0; i<measured_quan.size(); i++)
sum += calc_log_likelihood(i);
return sum;
}
double CMediumSet::calc_log_likelihood(int i) //calculate sum log likelihood for observed quantity i
{
double sum = 0;
int k = measured_data.lookup(measured_quan[i].name);
if (k != -1)
{
double MSE;
if (measured_quan[i].error_structure == 0)
{
int k = measured_data.lookup(measured_quan[i].name);
if (k != -1)
{
//qDebug() << "Calculating standard error" << QString::fromStdString(measured_quan[i].name);
MSE = diff(ANS_obs.BTC[i], measured_data.BTC[k]);
sum -= MSE / (2 * std[measured_quan[i].std_no] * std[measured_quan[i].std_no]);
//qDebug() << "Calculating standard error" << QString::fromStdString(measured_quan[i].name) << " Done!";
}
}
if (measured_quan[i].error_structure == 1)
{
int k = measured_data.lookup(measured_quan[i].name);
if (k != -1)
{
MSE = diff(ANS_obs.BTC[i].Log(1e-4), measured_data.BTC[k].Log(1e-4));
sum -= MSE / (2 * std[measured_quan[i].std_no] * std[measured_quan[i].std_no]);
}
}
MSE_obs.push_back(MSE);
sum -= measured_data.BTC[k].n*log(std[measured_quan[i].std_no]);
}
return sum;
}
double CMediumSet::calc_MSE(int i)
{
int k = measured_data.lookup(measured_quan[i].name);
double MSE;
if (k != -1)
{
if (measured_quan[i].error_structure == 0)
{
int k = measured_data.lookup(measured_quan[i].name);
if (k != -1) MSE = diff(ANS_obs.BTC[i], measured_data.BTC[k]);
}
if (measured_quan[i].error_structure == 1)
{
int k = measured_data.lookup(measured_quan[i].name);
if (k!=-1) MSE = diff(ANS_obs.BTC[i].Log(1e-4), measured_data.BTC[k].Log(1e-4));
}
MSE_obs.push_back(MSE);
}
return MSE;
}
void CMediumSet::finalize_set_param()
{
for (unsigned int i = 0; i < Medium.size(); i++)
Medium[i].finalize_set_param();
}
int CMediumSet::epoch_count()
{
int out = 0;
for (unsigned int i = 0; i < Medium.size(); i++) out += Medium[i].Solution_State.epoch_count;
return out;
}
void CMediumSet::clear()
{
ANS_colloids.clear();
ANS_constituents.clear();
ANS_control.clear();
ANS_hyd.clear();
ANS_obs.clear();
ANS_obs_noise.clear();
measured_data.clear();
Medium.clear();
}
int CMediumSet::get_block_type(string s)
{
if (tolower(trim(s)) == "soil") return Block_types::Soil;
if (tolower(trim(s)) == "darcy") return Block_types::Darcy;
if (tolower(trim(s)) == "pond") return Block_types::Pond;
if (tolower(trim(s)) == "stream") return Block_types::Stream;
if (tolower(trim(s)) == "plant") return Block_types::Plant;
if (tolower(trim(s)) == "catchment") return Block_types::Catchment;
if (tolower(trim(s)) == "storage") return Block_types::Storage;
if (tolower(trim(s)) == "normal") return Normal;
if (tolower(trim(s)) == "qdarcy") return QDarcy;
if (tolower(trim(s)) == "vapor") return Vapor;
if (tolower(trim(s)) == "pipe1") return Pipe1;
if (tolower(trim(s)) == "pipe2") return Pipe2;
if (tolower(trim(s)) == "rating_curve") return Rating_curve;
return -1;
}
bool CMediumSet::get_formulas_from_file(string filename)
{
show_message("Attempting to load formulas from file...");
formulas.formulasH.resize(10);
formulas.formulas.resize(10);
formulas.formulasQ.resize(10);
formulas.formulasA.resize(10);
formulas.const_area.resize(10);
for (unsigned int i = 0; i < formulas.formulasQ.size(); i++) formulas.formulasQ[i].resize(10);
for (unsigned int i = 0; i < formulas.formulasA.size(); i++)
{
formulas.formulasA[i].resize(10);
for (unsigned int j = 0; j < formulas.formulasA[i].size(); j++) formulas.formulasA[i][j] = "(s[2]+e[2])/2";
}
for (unsigned int i = 0; i < formulas.const_area.size(); i++) {
formulas.const_area[i].resize(10); for (unsigned int j = 0; j < formulas.const_area[i].size(); j++) formulas.const_area[i][j] = true;}
formulas.vaporTransport.resize(10);
for (unsigned int i = 0; i < formulas.vaporTransport.size(); i++) formulas.vaporTransport[i].resize(10);
formulas.settling.resize(10);
for (unsigned int i = 0; i <formulas.settling.size(); i++) formulas.settling[i].resize(10);
formulas.air_phase.resize(10);
formulas.air_phase[Soil] = 1;
formulas.formulasQ2 = formulas.formulasQ;
ifstream file(filename, std::ifstream::in);
if (!file.good())
{
show_message("File not found! ");
return false;
}
show_message("Reading formulas from file...");
while (!file.eof())
{
vector<string> s = getline(file);
if (s.size() > 2)
{
show_message(s[0]);
if (s[0].substr(0, 2) != "\\" && s[0].substr(0, 2) != "//")
{
if (trim(tolower(s[0])) == "h-s" && s.size()>=3)
formulas.formulasH[get_block_type(s[1])] = s[2];
if (trim(tolower(s[0])) == "vapor" && s.size()>=4)
formulas.vaporTransport[get_block_type(s[1])][get_block_type(s[2])] = atoi(s[3].c_str());
if (trim(tolower(s[0])) == "settling" && s.size() >= 4)
formulas.settling[get_block_type(s[1])][get_block_type(s[2])] = atoi(s[3].c_str());
if (trim(tolower(s[0])) == "area" && s.size() >= 4)
formulas.formulasA[get_block_type(s[1])][get_block_type(s[2])] = s[3];
if (trim(tolower(s[0])) == "const_area" && s.size() >= 4)
formulas.const_area[get_block_type(s[1])][get_block_type(s[2])] = atoi(s[3].c_str());
if (trim(tolower(s[0])) == "flow" && s.size() >= 4)
formulas.formulasQ[get_block_type(s[1])][get_block_type(s[2])] = s[3];
if (trim(tolower(s[0])) == "flow2" && s.size() >= 4)
formulas.formulasQ2[get_block_type(s[1])][get_block_type(s[2])] = s[3];
if (trim(tolower(s[0])) == "connector" && s.size() >= 3)
formulas.formulas[get_block_type(s[1])] = s[2];
}
}
}
set_features.formulas = true;
show_message("Done!");
return true;
}
void CMediumSet::show_message(string s)
{
if (showmessages)
{
std::cout<< string("ModelSet:") + s << std::endl;
}
}
#endif
| 41.513191 | 279 | 0.650724 | [
"vector",
"model",
"solid"
] |
91c9d14d3bf5eaf6d5918a8763f2800dfce5dbab | 11,220 | cpp | C++ | src/menu.cpp | kiavash-at-home/impedance-transform-matching-smith-chart | b58f94b327a6b56f6e1203df527f00c2b97e1d79 | [
"Apache-2.0"
] | 1 | 2021-01-08T13:03:08.000Z | 2021-01-08T13:03:08.000Z | src/menu.cpp | kiavash-at-home/impedance-transform-matching-smith-chart | b58f94b327a6b56f6e1203df527f00c2b97e1d79 | [
"Apache-2.0"
] | 1 | 2020-08-16T01:10:00.000Z | 2020-08-16T01:16:59.000Z | src/menu.cpp | kiavash-at-home/impedance-transform-matching-smith-chart | b58f94b327a6b56f6e1203df527f00c2b97e1d79 | [
"Apache-2.0"
] | null | null | null | /* Copyright note regarding the ported section of the code:
Copyright 2011 by Kiavash
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 "../third_party/sdl-bgi/graphics.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <ctype.h>
#include <math.h>
extern void *ptr;
extern unsigned size;
/*----------------------*/
int menu(void);
void make_bar(void);
int getkey(void);
void highlight(int num);
void lowlight(int num);
void gotolr(int *i, int key);
void make_down(int i);
void clean_down(int i);
void pull_up(int *i, int *j, int key);
int gotodu(int *i, int *j, int key);
void highdown(int i, int j, int flag);
int select_func(int i, int j);
void store_s(int x1, int y1, int x2, int y2);
void restore_s(int x, int y);
/*-----------------------------*/
int menu(void)
{
int i, j, ch;
i = j = ch = 1;
int temp;
make_bar();
for (;;)
{
ch = getkey();
for (; ch != 13;) // ENTER Key
{
gotolr(&i, ch);
ch = getkey();
}
make_down(i);
ch = getkey();
for (;
(ch == 77) // Right Arrow Key
|| (ch == 75);) // Left Arrow Key
{
pull_up(&i, &j, ch);
ch = getkey();
}
if (ch == 27) // ESC Key
gotodu(&i, &j, ch);
else
{
temp = gotodu(&i, &j, ch);
if (temp != 0) return temp;
do {
ch = getkey();
temp = gotodu(&i, &j, ch);
if (temp != 0)
return temp;
pull_up(&i, &j, ch);
} while (ch != 27); // ESC Key
}
}
}
/********************/
void make_bar(void)
{
char *m_bar[] = { " PUBLIC ",
" L PARAM. ",
" Lmin,max ",
" Z INPUT ",
" 1 STUB ",
" 2 STUB ",
" 3 STUB " };
char *m_ba[] = { "P",
"L",
"L",
"Z",
"1",
"2",
"3" };
int i;
//void *buf;
setcolor(MAGENTA);
setfillstyle(SOLID_FILL, getmaxcolor());
bar(2, 2, getmaxx() - 2, 24);
bar(2, 458, getmaxx() - 2, 478);
setcolor(BLACK);
rectangle(1, 459, getmaxx() - 3, 477);
line(100, 458, 100, 478);
setcolor(RED);
outtextxy(20, 464, (char*)
"COMMENT");
setcolor(BLACK);
outtextxy(120, 464, (char*)
"IMPEDANCE TRANSFORM AND MATCHING BY SMIT CHART");
setcolor(DARKGRAY);
for (i = 0; i < 7; i++) outtextxy(10 + i *79, 10, m_bar[i]);
setcolor(RED);
for (i = 0; i < 7; i++) outtextxy(19 + i *79, 10, m_ba[i]);
setcolor(DARKGRAY);
for (i = 0; i < 7; i++)
{
rectangle(4 + i *79, 4, 4 + (i + 1) *79, 23);
rectangle(3 + i *79, 3, 3 + (i + 1) *79, 24);
}
}
/*******
* Original getkey() used INT13H to return BIOS scan code
* replaced it with getch() implementation and converted
* ASCII to BIOS scan code
******/
int getkey(void)
{
int bios_scan_code;
int pressed_key_ascii = getch();
switch(pressed_key_ascii)
{
case KEY_ESC:
bios_scan_code = 27;
break;
case KEY_RIGHT:
bios_scan_code = 77;
break;
case KEY_LEFT:
bios_scan_code = 75;
break;
case KEY_UP:
bios_scan_code = 72;
break;
case KEY_DOWN:
bios_scan_code = 80;
break;
case SDLK_RETURN:
bios_scan_code = 13;
break;
default:
bios_scan_code = pressed_key_ascii;
}
return bios_scan_code;
}
void highlight(int num)
{
int temp = num;
setcolor(BLUE);
rectangle(5 + (temp - 1) *79, 5, 4 + temp *79, 21);
rectangle(3 + (temp - 1) *79, 3, 2 + temp *79, 23);
setcolor(GREEN);
rectangle(6 + (temp - 1) *79, 6, 5 + temp *79, 20);
rectangle(4 + (temp - 1) *79, 4, 3 + temp *79, 22);
}
/****************************/
void lowlight(int num)
{
int temp = num;
setcolor(DARKGRAY);
rectangle(5 + (temp - 1) *79, 5, 4 + temp *79, 21);
rectangle(3 + (temp - 1) *79, 3, 2 + temp *79, 23);
setcolor(WHITE);
rectangle(6 + (temp - 1) *79, 6, 5 + temp *79, 20);
rectangle(4 + (temp - 1) *79, 4, 3 + temp *79, 22);
}
/*******************/
void gotolr(int *i, int key)
{
int t;
t = *i;
switch (key)
{
case 25:
t = 1;
highlight(t);
break;
case 38:
t = 2;
highlight(t);
break;
case 44:
t = 4;
highlight(t);
break;
case 120:
t = 5;
highlight(t);
break;
case 121:
t = 6;
highlight(t);
break;
case 122:
t = 7;
highlight(t);
break;
case 27:
lowlight(t);
break;
case 77:
if (t < 7)
{
t = t + 1;
lowlight(t - 1);
highlight(t);
}
break;
case 75:
if (t > 1)
{
t = t - 1;
lowlight(t + 1);
highlight(t);
}
break;
case 13:
break;
}
*i = t;
}
/***************************/
void make_down(int i)
{
char *abar[] = { " SMIT CHART ",
" DEMO ",
" EXIT " };
char *bbar[] = { " LOAD IMP. ",
" VSWR ",
" GAMA " };
char *cbar[] = { " LOAD IMP. ",
" Z max,min ",
" V max,min " };
char *dbar[] = { " LOAD IMP. ",
" LOAD LINE ",
" Z INPUT " };
char *ebar[] = { " LOAD IMP. ",
" Ls &Lt ",
" SCH. GRAPH " };
char *fbar[] = { " LOAD IMP. ",
" Ld,Lt, Lt1 ",
" SCH. GRAPH " };
char *gbar[] = { " LOAD IMP. ",
" Ld,t,t1,t2 ",
" SCH. GRAPH " };
int j;
setfillstyle(SOLID_FILL, getmaxcolor());
setcolor(DARKGRAY);
switch (i)
{
case 1:
store_s(4, 25, 120, 104);
bar(4, 25, 120, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(17, 10 + j *25, abar[j - 1]);
rectangle(6, 2 + j *25, 118, 27 + j *25);
rectangle(7, 3 + j *25, 117, 26 + j *25);
}
break;
case 2:
store_s(74, 25, 190, 104);
bar(74, 25, 190, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(90, 10 + j *25, bbar[j - 1]);
rectangle(76, 2 + j *25, 188, 27 + j *25);
rectangle(77, 3 + j *25, 187, 26 + j *25);
}
break;
case 3:
store_s(156, 25, 269, 104);
bar(156, 25, 269, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(169, 10 + j *25, cbar[j - 1]);
rectangle(155, 2 + j *25, 267, 27 + j *25);
rectangle(156, 3 + j *25, 266, 26 + j *25);
}
break;
case 4:
store_s(235, 25, 348, 104);
bar(235, 25, 348, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(248, 10 + j *25, dbar[j - 1]);
rectangle(234, 2 + j *25, 346, 27 + j *25);
rectangle(235, 3 + j *25, 345, 26 + j *25);
}
break;
case 5:
store_s(314, 25, 427, 104);
bar(314, 25, 427, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(327, 10 + j *25, ebar[j - 1]);
rectangle(313, 2 + j *25, 425, 27 + j *25);
rectangle(314, 3 + j *25, 424, 26 + j *25);
}
break;
case 6:
store_s(393, 25, 506, 104);
bar(393, 25, 506, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(406, 10 + j *25, fbar[j - 1]);
rectangle(392, 2 + j *25, 504, 27 + j *25);
rectangle(393, 3 + j *25, 503, 26 + j *25);
}
break;
case 7:
store_s(472, 25, 585, 104);
bar(472, 25, 585, 104);
for (j = 1; j <= 3; j++)
{
outtextxy(485, 10 + j *25, gbar[j - 1]);
rectangle(471, 2 + j *25, 583, 27 + j *25);
rectangle(472, 3 + j *25, 582, 26 + j *25);
}
break;
}
highlight(i);
highdown(i, 1, 1);
}
/***************************/
void clean_down(int i)
{
switch (i)
{
case 1:
restore_s(4, 25);
break;
case 2:
restore_s(74, 25);
break;
case 3:
restore_s(156, 25);
break;
case 4:
restore_s(235, 25);
break;
case 5:
restore_s(314, 25);
break;
case 6:
restore_s(393, 25);
break;
case 7:
restore_s(472, 25);
break;
}
}
/***************************/
void pull_up(int *i, int *j, int key)
{
switch (key)
{
case 77:
if (*i < 7)
{
*i = *i + 1;
clean_down(*i - 1);
lowlight(*i - 1);
highlight(*i);
make_down(*i);
*j = 1;
}
break;
case 75:
if (*i > 1)
{
*i = *i - 1;
clean_down(*i + 1);
lowlight(*i + 1);
highlight(*i);
make_down(*i);
*j = 1;
}
break;
}
}
/****************************/
int gotodu(int *i, int *j, int key)
{
switch (key)
{
case 27:
clean_down(*i);
break;
case 13:
return select_func(*i, *j);
case 80:
if (*j < 3)
{
*j = *j + 1;
highdown(*i, *j - 1, 0);
highdown(*i, *j, 1);
}
break;
case 72:
if (*j > 1)
{
*j = *j - 1;
highdown(*i, *j + 1, 0);
highdown(*i, *j, 1);
}
break;
}
return 0;
}
/*********************************/
void highdown(int i, int j, int flag)
{
int ip, jp;
ip = i;
jp = j;
if (flag == 0) setcolor(WHITE);
else setcolor(GREEN);
switch (ip)
{
case 1:
rectangle(10, 6 + jp *25, 114, 23 + jp *25);
rectangle(11, 7 + jp *25, 113, 22 + jp *25);
rectangle(8, 4 + jp *25, 116, 25 + jp *25);
rectangle(9, 5 + jp *25, 115, 24 + jp *25);
break;
case 2:
rectangle(80, 6 + jp *25, 184, 23 + jp *25);
rectangle(81, 7 + jp *25, 183, 22 + jp *25);
rectangle(78, 4 + jp *25, 186, 25 + jp *25);
rectangle(79, 5 + jp *25, 185, 24 + jp *25);
break;
case 3:
rectangle(159, 6 + jp *25, 267, 23 + jp *25);
rectangle(160, 7 + jp *25, 266, 22 + jp *25);
rectangle(157, 4 + jp *25, 265, 25 + jp *25);
rectangle(158, 5 + jp *25, 264, 24 + jp *25);
break;
case 4:
rectangle(238, 6 + jp *25, 342, 23 + jp *25);
rectangle(239, 7 + jp *25, 341, 22 + jp *25);
rectangle(236, 4 + jp *25, 344, 25 + jp *25);
rectangle(237, 5 + jp *25, 343, 24 + jp *25);
break;
case 5:
rectangle(317, 6 + jp *25, 421, 23 + jp *25);
rectangle(318, 7 + jp *25, 420, 22 + jp *25);
rectangle(315, 4 + jp *25, 423, 25 + jp *25);
rectangle(316, 5 + jp *25, 422, 24 + jp *25);
break;
case 6:
rectangle(396, 6 + jp *25, 500, 23 + jp *25);
rectangle(397, 7 + jp *25, 499, 22 + jp *25);
rectangle(394, 4 + jp *25, 502, 25 + jp *25);
rectangle(395, 5 + jp *25, 501, 24 + jp *25);
break;
case 7:
rectangle(475, 6 + jp *25, 579, 23 + jp *25);
rectangle(476, 7 + jp *25, 578, 22 + jp *25);
rectangle(473, 4 + jp *25, 581, 25 + jp *25);
rectangle(474, 5 + jp *25, 580, 24 + jp *25);
break;
}
}
/*********************************/
int select_func(int i, int j)
{
int temp = 0;
switch (i)
{
case 1:
temp = j;
break;
case 2:
temp = j + 3;
break;
case 3:
temp = j + 6;
break;
case 4:
temp = j + 9;
break;
case 5:
temp = j + 12;
break;
case 6:
temp = j + 15;
break;
case 7:
temp = j + 18;
break;
}
clean_down(i);
return temp;
}
/***************************/
| 20.511883 | 73 | 0.481194 | [
"transform"
] |
91d48c8d2ed66e03f88290bcdc3ee1420b009f6d | 3,260 | cpp | C++ | src/core/YGraphics.cpp | j-tetteroo/kobu | 99486ee457c047a3392549bc73935d20bdbdaf93 | [
"Apache-2.0"
] | null | null | null | src/core/YGraphics.cpp | j-tetteroo/kobu | 99486ee457c047a3392549bc73935d20bdbdaf93 | [
"Apache-2.0"
] | null | null | null | src/core/YGraphics.cpp | j-tetteroo/kobu | 99486ee457c047a3392549bc73935d20bdbdaf93 | [
"Apache-2.0"
] | null | null | null |
#include <string>
#include "SkCanvas.h"
#include "SkRect.h"
#include "SkRRect.h"
#include "core/YGraphics.h"
#include "util/YTypes.h"
kobu::YGraphics::YGraphics(SkCanvas *c) : canvas_(c) {
}
kobu::YGraphics::~YGraphics(void) {
}
void kobu::YGraphics::DrawRect(uint32_t color, float x, float y, float w, float h, float lineWidth) {
SkPaint paint;
SkRect rect = SkRect::MakeXYWH(x, y, w, h);
paint.setColor(color);
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(lineWidth);
//canvas_->save();
//canvas_->translate(r.x, r.y);
canvas_->drawRect(rect, paint);
//canvas_->restore();
}
void kobu::YGraphics::DrawRect(uint32_t color, YRect r, float lineWidth) {
DrawRect(color, r.x, r.y, r.w, r.h, lineWidth);
}
void kobu::YGraphics::FillRect(uint32_t color, float x, float y, float w, float h) {
SkPaint paint;
SkRect rect = SkRect::MakeXYWH(x, y, w, h);
paint.setColor(color);
paint.setAntiAlias(true);
canvas_->drawRect(rect, paint);
}
void kobu::YGraphics::FillRect(uint32_t color, YRect r) {
FillRect(color, r.x, r.y, r.w, r.h);
}
void kobu::YGraphics::DrawRoundRect(uint32_t color, float x, float y, float w, float h, float radius, float lineWidth) {
SkPaint paint;
SkRect rect = SkRect::MakeXYWH(x, y, w, h);
paint.setColor(color);
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(lineWidth);
SkRRect rrect;
rrect.setRectXY(rect, radius, radius);
canvas_->drawRRect(rrect, paint);
}
;
void kobu::YGraphics::DrawRoundRect(uint32_t color, YRect r, float radius, float lineWidth) {
DrawRoundRect(color, r.x, r.y, r.w, r.h, radius, lineWidth);
}
void kobu::YGraphics::FillRoundRect(uint32_t color, float x, float y, float w, float h, float radius) {
SkPaint paint;
SkRect rect = SkRect::MakeXYWH(x, y, w, h);
paint.setColor(color);
paint.setAntiAlias(true);
SkRRect rrect;
rrect.setRectXY(rect, radius, radius);
canvas_->drawRRect(rrect, paint);
}
void kobu::YGraphics::FillRoundRect(uint32_t color, YRect r, float radius) {
FillRoundRect(color, r.x, r.y, r.w, r.h, radius);
}
void kobu::YGraphics::DrawLine(uint32_t color, float x0, float y0, float x1, float y1, float lineWidth) {
SkPaint paint;
paint.setColor(color);
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(lineWidth);
canvas_->drawLine (x0, y0, x1, y1, paint);
}
void kobu::YGraphics::DrawText(uint32_t color, const char *text, float x, float y) {
// Render with Skia
// TODO: add harfbuzz support
SkPaint paint;
canvas_->save();
paint.setAntiAlias(true);
paint.setColor(color);
canvas_->translate(x, y);
canvas_->drawText(text, strlen(text), SkIntToScalar(0),
SkIntToScalar(0), paint);
canvas_->restore();
}
void kobu::YGraphics::SetCanvas(SkCanvas *c) {
canvas_ = c;
}
void kobu::YGraphics::Push() {
canvas_->save();
}
void kobu::YGraphics::Pop() {
canvas_->restore();
}
void kobu::YGraphics::Translate(float x, float y) {
canvas_->translate(x, y);
}
| 24.511278 | 120 | 0.655828 | [
"render"
] |
91d72838430c10b6be099009ce809d2e4e409bef | 2,590 | cpp | C++ | cpp-mmgraph/graph.cpp | andelf/codeplay | de148cc48f5c1d436978b14876ee1c871e692e11 | [
"MIT"
] | 2 | 2016-10-10T04:01:10.000Z | 2017-01-10T08:31:17.000Z | cpp-mmgraph/graph.cpp | andelf/codeplay | de148cc48f5c1d436978b14876ee1c871e692e11 | [
"MIT"
] | null | null | null | cpp-mmgraph/graph.cpp | andelf/codeplay | de148cc48f5c1d436978b14876ee1c871e692e11 | [
"MIT"
] | null | null | null | // Copyright (c) 2016 Copyright Holder All Rights Reserved.
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <memory>
#include <numeric>
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>
#include <boost/graph/prim_minimum_spanning_tree.hpp>
using namespace boost;
typedef adjacency_list<vecS, vecS, directedS, no_property,
property<edge_weight_t, int64_t>>
Graph;
typedef graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef graph_traits<Graph>::edge_descriptor edge_descriptor;
int main(int argc, char const *argv[]) {
std::ifstream fin("../priv/edges.txt");
int num_of_nodes, num_of_edges;
fin >> num_of_nodes >> num_of_edges;
std::cout << "Nodes " << num_of_nodes << " Edges " << num_of_edges
<< std::endl;
Graph g(num_of_nodes);
// std::vector<int64_t> weights(num_of_nodes);
for (auto i = 0; i < num_of_edges; ++i) {
int u, v;
int64_t weight;
fin >> u >> v >> weight;
// std::cout << u << " -> " << v <<std::endl;
add_edge(u, v, weight, g);
}
// this use dijskura, don't allow negative edge weights
// std::vector<vertex_descriptor> p(num_vertices(g));
// prim_minimum_spanning_tree(g, &p[0]);
std::vector<edge_descriptor> spanning_tree;
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
for (auto it = spanning_tree.begin(); it != spanning_tree.end(); ++it) {
std::cout << source(*it, g) << " -- " << target(*it, g) << ";" << std::endl;
// std::cout << get(edge_weight, g, *it) << std::endl;
}
int64_t mst_weights = std::accumulate(
spanning_tree.begin(), spanning_tree.end(), 0,
[g](int64_t acc, auto b) { return acc + get(edge_weight, g, b); });
std::cout << "MST weights: " << mst_weights << std::endl;
/*for (std::size_t i = 0; i != p.size(); ++i)
if (p[i] != i)
std::cout << "parent[" << i << "] = " << p[i] << std::endl;
else
std::cout << "parent[" << i << "] = no parent" << std::endl;
*/
// write_graphviz(std::cout, g);
/*
graph_traits<Graph>::edge_iterator ei, eend;
for (boost::tie(ei, eend) = edges(g); ei != eend; ++ei) {
std::cout << "E: " << *ei << " " << std::endl;
}*/
/*graph_traits<Graph>::vertex_iterator vi, vend;
for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi) {
std::cout << "V: " << *vi << std::endl;
}*/
// std::cout << num_edges(g) << std::endl;
return 0;
}
| 31.204819 | 80 | 0.615444 | [
"vector"
] |
91dd31a5d8bf014afa306a0ab9f6caa7544af777 | 29,372 | cpp | C++ | src/Library/main.cpp | Gegel85/TouhouUNLDiscordIntegration | 266b4dca6915bf70073fff8aa93da06841c39a94 | [
"MIT"
] | 5 | 2020-11-02T05:31:05.000Z | 2021-03-03T06:50:15.000Z | src/Library/main.cpp | Gegel85/TouhouUNLDiscordIntegration | 266b4dca6915bf70073fff8aa93da06841c39a94 | [
"MIT"
] | 3 | 2020-11-18T05:51:09.000Z | 2021-02-16T16:41:24.000Z | src/Library/main.cpp | Gegel85/TouhouUNLDiscordIntegration | 266b4dca6915bf70073fff8aa93da06841c39a94 | [
"MIT"
] | 1 | 2020-11-24T21:40:46.000Z | 2020-11-24T21:40:46.000Z | //
// Created by Gegel85 on 31/10/2020
//
#include <thread>
#include <ctime>
#include <string>
#include <array>
#include <discord.h>
#include <shlwapi.h>
#include <SokuLib.hpp>
#include "logger.hpp"
#include "Exceptions.hpp"
#include "Network/getPublicIp.hpp"
#include "ShiftJISDecoder.hpp"
static bool enabled;
static char smallImg[32];
static bool showWR = false;
static bool experimentalSpec;
static std::pair<unsigned, unsigned> won;
static std::pair<unsigned, unsigned> score;
static time_t gameTimestamp;
static time_t hostTimestamp;
static time_t totalTimestamp;
static time_t refreshRate;
static discord::Core *core;
static unsigned long long clientId;
static int currentScene;
static std::string roomIp = "";
const std::vector<const char *> discordResultToString{
"Ok",
"ServiceUnavailable",
"InvalidVersion",
"LockFailed",
"InternalError",
"InvalidPayload",
"InvalidCommand",
"InvalidPermissions",
"NotFetched",
"NotFound",
"Conflict",
"InvalidSecret",
"InvalidJoinSecret",
"NoEligibleActivity",
"InvalidInvite",
"NotAuthenticated",
"InvalidAccessToken",
"ApplicationMismatch",
"InvalidDataUrl",
"InvalidBase64",
"NotFiltered",
"LobbyFull",
"InvalidLobbySecret",
"InvalidFilename",
"InvalidFileSize",
"InvalidEntitlement",
"NotInstalled",
"NotRunning",
"InsufficientBuffer",
"PurchaseCanceled",
"InvalidGuild",
"InvalidEvent",
"InvalidChannel",
"InvalidOrigin",
"RateLimited",
"OAuth2Error",
"SelectChannelTimeout",
"GetGuildTimeout",
"SelectVoiceForceRequired",
"CaptureShortcutAlreadyListening",
"UnauthorizedForAchievement",
"InvalidGiftCode",
"PurchaseError",
"TransactionAborted",
};
std::vector<std::string> charactersImg{
"reimu",
"marisa",
"sakuya",
"alice",
"patchouli",
"youmu",
"remilia",
"yuyuko",
"yukari",
"suika",
"reisen",
"aya",
"komachi",
"iku",
"tenshi",
"sanae",
"cirno",
"meiling",
"okuu",
"suwako",
"random_select"
};
void genericScreen()
{
logMessagef("Generic menu on scene %i\n", currentScene);
discord::Activity activity{};
auto &assets = activity.GetAssets();
if (!roomIp.empty())
logMessage("No longer hosting/connecting.\n");
roomIp = "";
score = {0, 0};
totalTimestamp = time(nullptr);
hostTimestamp = time(nullptr);
logMessage("Get scene name\n");
activity.SetState(SokuLib::sceneNames[currentScene].c_str());
logMessage("Done\n");
assets.SetLargeImage("cover");
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void showHost()
{
logMessagef("Showing host... Internal ip is %s\n", roomIp.c_str());
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto *menuObj = SokuLib::getMenuObj();
auto &timeStamp = activity.GetTimestamps();
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
if (roomIp.empty()) {
try {
roomIp = getMyIp() + std::string(":") + std::to_string(menuObj->port);
logMessagef("Hosting. Room ip is %s. Spectator are %sallowed\n", roomIp.c_str(), menuObj->spectate ? "" : "not ");
party.SetId(roomIp.c_str());
secrets.SetJoin(("join" + roomIp).c_str());
if (menuObj->spectate)
secrets.SetSpectate(("spec" + roomIp).c_str());
} catch (...) {}
} else {
party.SetId(roomIp.c_str());
secrets.SetJoin(("join" + roomIp).c_str());
if (menuObj->spectate)
secrets.SetSpectate(("spec" + roomIp).c_str());
}
party.GetSize().SetCurrentSize(1);
party.GetSize().SetMaxSize(2);
timeStamp.SetStart(hostTimestamp);
activity.SetDetails(SokuLib::sceneNames[currentScene].c_str());
activity.SetState("Hosting...");
assets.SetLargeImage("cover");
assets.SetSmallImage(smallImg);
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void connectingToRemote()
{
logMessage("Connecting to remote\n");
auto *menuObj = SokuLib::getMenuObj();
logMessagef("Menu object is at %#X\n", menuObj);
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
if (roomIp.empty())
roomIp = menuObj->IPString + (":" + std::to_string(menuObj->port));
logMessagef("The new room ip is %s\n", roomIp.c_str());
totalTimestamp = time(nullptr);
assets.SetLargeImage("cover");
activity.SetDetails("Joining room...");
activity.SetState("Playing multiplayer (Online)");
party.SetId(roomIp.c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
secrets.SetJoin(("join" + roomIp).c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void connectedToRemoteLoadingCharSelect()
{
logMessagef("Connected and waiting to load. Internal ip is %s\n", roomIp.c_str());
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
logMessagef("Room ip is %s\n", roomIp.c_str());
totalTimestamp = time(nullptr);
assets.SetLargeImage("cover");
activity.SetState("Loading character select...");
activity.SetDetails("Playing multiplayer (Online)");
party.SetId(roomIp.c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
secrets.SetJoin(("join" + roomIp).c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void titleScreen()
{
logMessage("On title screen\n");
auto *menuObj = SokuLib::getMenuObj();
if (!IN_MENU || *reinterpret_cast<char *>(menuObj)) {
logMessage("We are not in a proper submenu, falling back to generic screen\n");
return genericScreen();
}
logMessagef("Menu object is at %#X\n", menuObj);
if (
menuObj->choice >= SokuLib::MenuConnect::CHOICE_ASSIGN_IP_CONNECT &&
menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE &&
menuObj->subchoice == 3
)
connectingToRemote();
else if (
menuObj->choice >= SokuLib::MenuConnect::CHOICE_HOST &&
menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE &&
menuObj->subchoice == 255
)
connectedToRemoteLoadingCharSelect();
else if (
menuObj->choice == SokuLib::MenuConnect::CHOICE_HOST &&
menuObj->subchoice == 2
)
showHost();
else
genericScreen();
logMessage("Title screen callback end\n");
}
void localBattle()
{
logMessage("Playing a local game\n");
unsigned stage = SokuLib::flattenStageId(SokuLib::getStageId());
logMessagef("We are on stage %u\n", stage);
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
std::string profile1 = convertShiftJisToUTF8(SokuLib::player1Profile());
std::string profile2 = convertShiftJisToUTF8(SokuLib::player2Profile());
logMessagef("The 2 profiles are %s %s\n", profile1.c_str(), profile2.c_str());
timeStamp.SetStart(gameTimestamp);
if (SokuLib::getSubMode() == SokuLib::BATTLE_SUBMODE_REPLAY) {
logMessage("This is a replay\n");
assets.SetLargeImage(("stage_" + std::to_string(stage + 1)).c_str());
assets.SetLargeText(SokuLib::stagesName[stage].c_str());
activity.SetDetails(SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()].c_str());
activity.SetState(std::string(SokuLib::charactersName[SokuLib::getLeftChar()] + " vs " + SokuLib::charactersName[SokuLib::getRightChar()]).c_str());
} else {
logMessage("This is not a replay\n");
logMessagef("Stage: %i, Main: %i, Sub: %i, Left: %i, Right: %i\n", stage, SokuLib::getMainMode(), SokuLib::getSubMode(), SokuLib::getLeftChar(), SokuLib::getRightChar());
assets.SetLargeImage(charactersImg[SokuLib::getLeftChar()].c_str());
logMessage("Left\n");
assets.SetLargeText(SokuLib::charactersName[SokuLib::getLeftChar()].c_str());
logMessage("Left\n");
assets.SetSmallImage(("stage_" + std::to_string(stage + 1)).c_str());
assets.SetSmallText(SokuLib::stagesName[stage].c_str());
logMessage("Stage\n");
activity.SetDetails((SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" + profile1 + ")").c_str());
logMessage("Modes\n");
if (SokuLib::getMainMode() == SokuLib::BATTLE_MODE_VSPLAYER)
activity.SetState((std::string("Against ") + profile2 + " as " + SokuLib::charactersName[SokuLib::getRightChar()]).c_str());
else
activity.SetState(("Against " + SokuLib::charactersName[SokuLib::getRightChar()]).c_str());
logMessage("Right\n");
}
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void loadMatch()
{
logMessage("Loading local match\n");
unsigned stage = SokuLib::flattenStageId(SokuLib::getStageId());
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
std::string profile1 = convertShiftJisToUTF8(SokuLib::player1Profile());
logMessagef("profile is %s\n", profile1.c_str());
gameTimestamp = time(nullptr);
timeStamp.SetStart(totalTimestamp);
assets.SetLargeImage(charactersImg[SokuLib::getLeftChar()].c_str());
assets.SetLargeText(SokuLib::charactersName[SokuLib::getLeftChar()].c_str());
if (SokuLib::getSubMode() == SokuLib::BATTLE_SUBMODE_REPLAY) {
assets.SetSmallImage(charactersImg[SokuLib::getRightChar()].c_str());
assets.SetSmallText(SokuLib::charactersName[SokuLib::getRightChar()].c_str());
activity.SetDetails(SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()].c_str());
} else {
assets.SetSmallImage(("stage_" + std::to_string(stage + 1)).c_str());
assets.SetSmallText(SokuLib::stagesName[stage].c_str());
activity.SetDetails((SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" + profile1 + ")").c_str());
}
activity.SetState("Loading...");
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void charSelect()
{
logMessage("Choosing character\n");
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
std::string profile1 = convertShiftJisToUTF8(SokuLib::player1Profile());
logMessagef("Profile name is %s\n", profile1.c_str());
timeStamp.SetStart(totalTimestamp);
assets.SetSmallImage(charactersImg[SokuLib::getRightChar()].c_str());
assets.SetSmallText(SokuLib::charactersName[SokuLib::getRightChar()].c_str());
assets.SetLargeImage(charactersImg[SokuLib::getLeftChar()].c_str());
assets.SetLargeText(SokuLib::charactersName[SokuLib::getLeftChar()].c_str());
activity.SetDetails((SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" + profile1 + ")").c_str());
activity.SetState("Character select...");
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void onlineBattle()
{
logMessagef("In online battle. Internal ip is %s\n", roomIp.c_str());
unsigned stage = SokuLib::flattenStageId(SokuLib::getStageId());
logMessagef("We are on stage %u\n", stage);
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
std::string profile1 = convertShiftJisToUTF8(SokuLib::player1Profile());
char myChar;
char opChar;
std::string opName;
SokuLib::NetObject *infos = SokuLib::getNetObject();
logMessagef("Infos ptr is %#X\n", infos);
char *battle_manager = reinterpret_cast<char *>(SokuLib::getBattleMgr());
logMessagef("BattleMgr is at %#X\n", battle_manager);
char *server_manager = *(char**)(battle_manager + 0x0C);
logMessagef("Server manager is at %#X\n", server_manager);
char *client_manager = *(char**)(battle_manager + 0x10);
logMessagef("Client manager is at %#X\n", client_manager);
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
if (SokuLib::getMainMode() == SokuLib::BATTLE_MODE_VSCLIENT) {
opName = convertShiftJisToUTF8(infos->profile2name);
myChar = SokuLib::getLeftChar();
opChar = SokuLib::getRightChar();
logMessagef("Won serv is %u\n", *(server_manager + 0x573));
logMessagef("Won client is %u\n", *(client_manager + 0x573));
won.first = *(server_manager + 0x573);
won.second = *(client_manager + 0x573);
} else {
opName = convertShiftJisToUTF8(infos->profile1name);
myChar = SokuLib::getRightChar();
opChar = SokuLib::getLeftChar();
logMessagef("Won client is %u\n", *(client_manager + 0x573));
logMessagef("Won serv is %u\n", *(server_manager + 0x573));
won.first = *(client_manager + 0x573);
won.second = *(server_manager + 0x573);
}
logMessagef("Opponent name is %s\n", opName.c_str());
logMessagef("My character is %u\n", myChar);
logMessagef("Opponent character is %u\n", opChar);
party.SetId(roomIp.c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
timeStamp.SetStart(gameTimestamp);
assets.SetSmallImage(("stage_" + std::to_string(stage + 1)).c_str());
assets.SetSmallText(SokuLib::stagesName[stage].c_str());
assets.SetLargeImage(charactersImg[myChar].c_str());
assets.SetLargeText(SokuLib::charactersName[myChar].c_str());
activity.SetDetails((SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" + profile1 + ")").c_str());
if (showWR)
activity.SetState((
std::string("Against ") + opName + " as " + SokuLib::charactersName[opChar] +
" (" + std::to_string(won.first) + " - " + std::to_string(won.second) + ")"
).c_str());
else
activity.SetState((std::string("Against ") + opName + " as " + SokuLib::charactersName[opChar]).c_str());
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void onlineBattleSpec()
{
logMessagef("Watching online game. Internal ip is %s\n", roomIp.c_str());
unsigned stage = SokuLib::flattenStageId(SokuLib::getStageId());
logMessagef("We are on stage %u\n", stage);
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
SokuLib::NetObject *infos = SokuLib::getNetObject();
logMessagef("Infos ptr is %#X\n", infos);
char *battle_manager = reinterpret_cast<char *>(SokuLib::getBattleMgr());
logMessagef("BattleMgr is at %#X\n", battle_manager);
char *server_manager = *(char**)(battle_manager + 0x0C);
logMessagef("Server manager is at %#X\n", server_manager);
char *client_manager = *(char**)(battle_manager + 0x10);
logMessagef("Client manager is at %#X\n", client_manager);
timeStamp.SetStart(gameTimestamp);
won.first = *(server_manager + 0x573);
won.second = *(client_manager + 0x573);
party.SetId(roomIp.c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
assets.SetLargeImage(("stage_" + std::to_string(stage + 1)).c_str());
assets.SetLargeText(SokuLib::stagesName[stage].c_str());
activity.SetDetails((
SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" +
convertShiftJisToUTF8(infos->profile1name) + " vs " +
convertShiftJisToUTF8(infos->profile2name) + ")"
).c_str());
activity.SetState((
SokuLib::charactersName[SokuLib::getLeftChar()] + " vs " +
SokuLib::charactersName[SokuLib::getRightChar()] +
" (" + std::to_string(won.first) + " - " + std::to_string(won.second) + ")"
).c_str());
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void loadOnlineMatch()
{
logMessagef("Loading online match. Internal ip is %s\n", roomIp.c_str());
unsigned stage = SokuLib::flattenStageId(SokuLib::getStageId());
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
std::string profile1 = convertShiftJisToUTF8(SokuLib::player1Profile());
char myChar;
logMessagef("profile is %s\n", profile1.c_str());
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
if (SokuLib::getMainMode() == SokuLib::BATTLE_MODE_VSCLIENT)
myChar = SokuLib::getLeftChar();
else
myChar = SokuLib::getRightChar();
logMessagef("My character is %u\n", myChar);
party.SetId(roomIp.c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
gameTimestamp = time(nullptr);
timeStamp.SetStart(totalTimestamp);
assets.SetSmallImage(("stage_" + std::to_string(stage + 1)).c_str());
assets.SetSmallText(SokuLib::stagesName[stage].c_str());
assets.SetLargeImage(charactersImg[myChar].c_str());
assets.SetLargeText(SokuLib::charactersName[myChar].c_str());
activity.SetDetails((SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" + profile1 + ")").c_str());
activity.SetState("Loading...");
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void loadOnlineMatchSpec()
{
if (!experimentalSpec)
return genericScreen();
logMessagef("Loading online match as spectator. Internal ip is %s\n", roomIp.c_str());
unsigned stage = SokuLib::flattenStageId(SokuLib::getStageId());
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
SokuLib::NetObject *infos = SokuLib::getNetObject();
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
party.SetId(roomIp.c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
logMessagef("Infos ptr is %#X\n", infos);
gameTimestamp = time(nullptr);
timeStamp.SetStart(totalTimestamp);
assets.SetLargeImage(charactersImg[SokuLib::getLeftChar()].c_str());
assets.SetLargeText(SokuLib::charactersName[SokuLib::getLeftChar()].c_str());
assets.SetSmallImage(charactersImg[SokuLib::getRightChar()].c_str());
assets.SetSmallText(SokuLib::charactersName[SokuLib::getRightChar()].c_str());
activity.SetDetails((
SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" +
convertShiftJisToUTF8(infos->profile1name) + " vs " +
convertShiftJisToUTF8(infos->profile2name) + ")"
).c_str());
activity.SetState("Loading...");
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
logMessage("Callback end\n");
}
void onlineCharSelect()
{
logMessagef("Online character select. Internal ip is %s\n", roomIp.c_str());
SokuLib::NetObject *infos = SokuLib::getNetObject();
logMessagef("Infos ptr is %#X\n", infos);
discord::Activity activity{};
auto &assets = activity.GetAssets();
auto &timeStamp = activity.GetTimestamps();
std::string profile1 = convertShiftJisToUTF8(SokuLib::player1Profile());
char myChar;
char opChar;
std::string opName;
auto &party = activity.GetParty();
auto &secrets = activity.GetSecrets();
logMessagef("profile is %s\n", profile1.c_str());
if (SokuLib::getMainMode() == SokuLib::BATTLE_MODE_VSCLIENT) {
opName = convertShiftJisToUTF8(infos->profile2name);
myChar = SokuLib::getLeftChar();
opChar = SokuLib::getRightChar();
} else {
opName = convertShiftJisToUTF8(infos->profile1name);
myChar = SokuLib::getRightChar();
opChar = SokuLib::getLeftChar();
}
logMessagef("Opponent name is %s\n", opName.c_str());
logMessagef("My character is %u\n", myChar);
logMessagef("Opponent character is %u\n", opChar);
party.SetId(roomIp.c_str());
secrets.SetSpectate(("spec" + roomIp).c_str());
party.GetSize().SetCurrentSize(2);
party.GetSize().SetMaxSize(2);
score.first += won.first > won.second && won.first;
score.second += won.second > won.first && won.second;
logMessagef("Win %i:%i/Score %i:%i\n", won.first, won.second, score.first, score.second);
won = {0, 0};
timeStamp.SetStart(totalTimestamp);
assets.SetSmallImage(charactersImg[opChar].c_str());
assets.SetSmallText(SokuLib::charactersName[opChar].c_str());
assets.SetLargeImage(charactersImg[myChar].c_str());
assets.SetLargeText(SokuLib::charactersName[myChar].c_str());
activity.SetDetails((SokuLib::modeNames[SokuLib::getMainMode()][SokuLib::getSubMode()] + " (" + profile1 + ")").c_str());
if (showWR)
activity.SetState((
"Character select... (vs " + std::string(opName) + " " +
std::to_string(score.first) + "w " +
std::to_string(score.second) + "l " +
(score.first + score.second ? std::to_string(score.first * 100 / (score.first + score.second)) : "N/A") +
"% wr)"
).c_str());
else
activity.SetState(("Character select... (vs " + std::string(opName) + ")").c_str());
core->ActivityManager().UpdateActivity(activity, [](discord::Result result) {
auto code = static_cast<unsigned>(result);
if (code)
logMessagef("Error updating presence: %s\n", discordResultToString[code]);
});
}
std::vector<std::function<void()>> sceneCallbacks{
genericScreen, //SWRSSCENE_LOGO = 0,
genericScreen, //SWRSSCENE_OPENING = 1,
titleScreen, //SWRSSCENE_TITLE = 2,
charSelect, //SWRSSCENE_SELECT = 3,
genericScreen, //??? = 4,
localBattle, //SWRSSCENE_BATTLE = 5,
loadMatch, //SWRSSCENE_LOADING = 6,
genericScreen, //??? = 7,
onlineCharSelect, //SWRSSCENE_SELECTSV = 8,
onlineCharSelect, //SWRSSCENE_SELECTCL = 9,
loadOnlineMatch, //SWRSSCENE_LOADINGSV = 10,
loadOnlineMatch, //SWRSSCENE_LOADINGCL = 11,
loadOnlineMatchSpec, //SWRSSCENE_LOADINGWATCH = 12,
onlineBattle, //SWRSSCENE_BATTLESV = 13,
onlineBattle, //SWRSSCENE_BATTLECL = 14,
onlineBattleSpec, //SWRSSCENE_BATTLEWATCH = 15,
genericScreen, //SWRSSCENE_SELECTSENARIO= 16,
genericScreen, //??? = 17,
genericScreen, //??? = 18,
genericScreen, //??? = 19,
genericScreen, //SWRSSCENE_ENDING = 20,
};
enum MenuEnum {
MENU_NONE,
MENU_CONNECT,
MENU_REPLAY,
MENU_MUSICROOM,
MENU_RESULT,
MENU_PROFILE,
MENU_CONFIG,
MENU_COUNT
};
void onActivityJoin(const char *sec)
{
logMessagef("Got activity join with payload %s\n", sec);
auto menuObj = SokuLib::getMenuObj();
std::string secret = sec;
auto ip = secret.substr(4, secret.find_last_of(':') - 4);
unsigned short port = std::stol(secret.substr(secret.find_last_of(':') + 1));
bool isSpec = secret.substr(0, 4) == "spec";
if (!IN_MENU || *reinterpret_cast<char *>(menuObj)) {
logMessage("Warping to connect screen.\n");
SokuLib::moveToConnectScreen();
menuObj = SokuLib::getMenuObj();
logMessage("Done.\n");
} else
logMessage("Already in connect screen\n");
if (
menuObj->choice >= SokuLib::MenuConnect::CHOICE_ASSIGN_IP_CONNECT &&
menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE &&
menuObj->subchoice == 3
)
return;
if (
menuObj->choice >= SokuLib::MenuConnect::CHOICE_HOST &&
menuObj->choice < SokuLib::MenuConnect::CHOICE_SELECT_PROFILE &&
menuObj->subchoice == 255
)
return;
if (
menuObj->choice == SokuLib::MenuConnect::CHOICE_HOST &&
menuObj->subchoice == 2
)
return;
logMessagef("Connecting to %s:%u as %s\n", ip.c_str(), port, isSpec ? "spectator" : "player");
SokuLib::joinHost(
ip.c_str(),
port,
isSpec
);
roomIp = ip + ":" + std::to_string(port);
}
class MyThread : public std::thread {
private:
bool _done;
int _connectTimeout = 1;
public:
bool isDone() const { return this->_done; }
template<typename ...Args>
MyThread() : std::thread() {};
~MyThread() {
this->_done = true;
if (this->joinable())
this->join();
}
void start() {
std::thread::operator=(std::thread([this] {
logMessage("Connecting to discord client...\n");
discord::Result result;
do {
result = discord::Core::Create(clientId, DiscordCreateFlags_NoRequireDiscord, &core);
if (result != discord::Result::Ok) {
logMessagef("Error connecting to discord: %s\n", discordResultToString[static_cast<unsigned>(result)]);
logMessagef("Retrying in %i seconds\n", this->_connectTimeout);
std::this_thread::sleep_for(std::chrono::seconds(this->_connectTimeout));
if (this->_connectTimeout < 64)
this->_connectTimeout *= 2;
}
} while (result != discord::Result::Ok);
logMessage("Connected !\n");
core->ActivityManager().OnActivityJoin.Connect(onActivityJoin);
logMessage("Entering loop\n");
while (!this->isDone()) {
currentScene = SokuLib::sceneId();
auto newScene = SokuLib::sceneIdNew();
logMessagef("Current scene is %i vs new scene %i\n", currentScene, newScene);
if (currentScene >= 0 && currentScene < sceneCallbacks.size() && currentScene == newScene) {
logMessagef("Calling callback %u\n", currentScene);
sceneCallbacks[currentScene]();
logMessage("Callback returned\n");
} else if (currentScene == SokuLib::SCENE_TITLE && (newScene == SokuLib::SCENE_SELECTSV || newScene == SokuLib::SCENE_SELECTCL))
connectedToRemoteLoadingCharSelect();
else
logMessage("No callback call\n");
logMessage("Running discord callbacks\n");
core->RunCallbacks();
logMessagef("Waiting for next cycle (%llu ms)\n", refreshRate);
std::this_thread::sleep_for(std::chrono::milliseconds(refreshRate));
}
logMessage("Exit game\n");
}));
}
};
static MyThread updateThread;
// �ݒ胍�[�h
void LoadSettings(LPCSTR profilePath)
{
char buffer[64];
logMessage("Loading settings...\n");
// �����V���b�g�_�E��
enabled = GetPrivateProfileInt("DiscordIntegration", "Enabled", 1, profilePath) != 0;
showWR = GetPrivateProfileInt("DiscordIntegration", "ShowWR", 0, profilePath) != 0;
experimentalSpec = GetPrivateProfileInt("DiscordIntegration", "ExperimentalSpectator", 0, profilePath) != 0;
refreshRate = GetPrivateProfileInt("DiscordIntegration", "RefreshTime", 1000, profilePath);
GetPrivateProfileString("DiscordIntegration", "HostImg", "", smallImg, sizeof(smallImg), profilePath);
GetPrivateProfileString("DiscordIntegration", "ClientID", ClientID, buffer, sizeof(buffer), profilePath);
clientId = atoll(buffer);
GetPrivateProfileString("DiscordIntegration", "InviteIp", "", buffer, sizeof(buffer), profilePath);
if (inet_addr(buffer) != -1)
myIp = strdup(buffer);
logMessagef("Enabled: %s\nClientID: %llu\nShowWR: %s\nHostImg: %s\nInviteIp: %s\n", enabled ? "true" : "false", clientId, showWR ? "true" : "false", smallImg, myIp);
}
extern "C"
__declspec(dllexport) bool CheckVersion(const BYTE hash[16])
{
return true;
}
extern "C"
__declspec(dllexport) bool Initialize(HMODULE hMyModule, HMODULE hParentModule)
{
bool &_en = enabled;
char profilePath[1024 + MAX_PATH];
initLogger();
logMessage("Initializing...\n");
GetModuleFileName(hMyModule, profilePath, 1024);
PathRemoveFileSpec(profilePath);
PathAppend(profilePath, "DiscordIntegration.ini");
LoadSettings(profilePath);
//DWORD old;
//::VirtualProtect((PVOID)rdata_Offset, rdata_Size, PAGE_EXECUTE_WRITECOPY, &old);
//s_origCLogo_OnProcess = TamperDword(vtbl_CLogo + 4, (DWORD)CLogo_OnProcess);
//s_origCBattle_OnProcess = TamperDword(vtbl_CBattle + 4, (DWORD)CBattle_OnProcess);
//s_origCBattleSV_OnProcess = TamperDword(vtbl_CBattleSV + 4, (DWORD)CBattleSV_OnProcess);
//s_origCBattleCL_OnProcess = TamperDword(vtbl_CBattleCL + 4, (DWORD)CBattleCL_OnProcess);
//s_origCTitle_OnProcess = TamperDword(vtbl_CTitle + 4, (DWORD)CTitle_OnProcess);
//s_origCSelect_OnProcess = TamperDword(vtbl_CSelect + 4, (DWORD)CSelect_OnProcess);
//::VirtualProtect((PVOID)rdata_Offset, rdata_Size, old, &old);
//::FlushInstructionCache(GetCurrentProcess(), nullptr, 0);
if (enabled)
updateThread.start();
else
logMessage("Disabled ;(\n");
logMessage("Done...\n");
return true;
}
extern "C"
int APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved)
{
return TRUE;
} | 34.636792 | 172 | 0.704923 | [
"object",
"vector"
] |
91dd829cc3e8993047e9d824c3e6adf0339b9982 | 3,148 | cpp | C++ | AsteroidShooter/Map.cpp | htmlboss/OpenGL-2D-Game-Engine | 1908e5a6ab781585381bcb7bcae6a595506354b2 | [
"MIT"
] | 1 | 2017-06-27T18:45:39.000Z | 2017-06-27T18:45:39.000Z | AsteroidShooter/Map.cpp | htmlboss/OpenGL-2D-Game-Engine | 1908e5a6ab781585381bcb7bcae6a595506354b2 | [
"MIT"
] | null | null | null | AsteroidShooter/Map.cpp | htmlboss/OpenGL-2D-Game-Engine | 1908e5a6ab781585381bcb7bcae6a595506354b2 | [
"MIT"
] | null | null | null | #include "includes/Map.h"
#include <ErrorSuite.h>
#include <ResourceManager.h>
#include <fstream>
#include <iostream>
Map::Map(const std::string& mapDataPath) : m_uvRect(0.0f, 0.0f, 1.0f, 1.0f){
std::ifstream file;
file.open(mapDataPath);
if (file.fail()) {
Engine::fatalError("Failed to open " + mapDataPath);
}
//Get number of asteroids
std::string temp;
file >> temp >> m_numAsteroids;
//store file lines in map vector
while (std::getline(file, temp)) {
m_mapData.push_back(temp);
}
/*//Print out map in console
#ifdef _DEBUG
for (unsigned int i = 0; i < m_mapData.size(); i++) {
std::cout << m_mapData[i] << std::endl;
}
#endif // _DEBUG
*/
glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
//Render tiles
for (unsigned int y = 0; y < m_mapData.size(); y++) {
for (unsigned int x = 0; x < m_mapData[y].size(); x++) {
//Grab tile
char tile = m_mapData[y][x];
//Parse tile
switch (tile) {
//Planet 1 (Earth-like)
case '1':
m_planet1 = glm::vec4(x * TILE_WIDTH, y * TILE_WIDTH, TILE_WIDTH * 15, TILE_WIDTH * 15);
break;
//Planet 2 (Moon)
case '2':
m_planet2 = glm::vec4(x * TILE_WIDTH, y * TILE_WIDTH, TILE_WIDTH * 5, TILE_WIDTH * 5);
break;
//Planet 3 (Gas Giant)
case '3':
m_planet3 = glm::vec4(x * TILE_WIDTH, y * TILE_WIDTH, TILE_WIDTH * 25, TILE_WIDTH * 25);
break;
//Sun
case 'S':
m_sun = glm::vec4(x * TILE_WIDTH, y * TILE_WIDTH, TILE_WIDTH * 45, TILE_WIDTH * 45);
break;
//Player
case '@':
m_playerStartPos.x = x * TILE_WIDTH;
m_playerStartPos.y = y * TILE_WIDTH;
m_mapData[y][x] = '.'; //Don't collide with start position
break;
//Asteroids
case 'A':
m_asteroidPositions.push_back(glm::vec2(x * TILE_WIDTH, y * TILE_WIDTH));
break;
//Map Boundaries
case '-':
break;
//Ignore periods
case '.':
break;
default:
std::printf("\nUnexpected Symbol %c at (%d,%d)", tile, x, y);
break;
}
}
}
}
Map::~Map() {
}
void Map::DrawMap() {
m_spriteBatch.renderbatch();
}
void Map::DrawPlanets() {
m_spriteBatch.initBatch();
m_spriteBatch.Begin();
//Planet 1 (Earth-like)
m_spriteBatch.Draw(m_planet1,
m_uvRect,
Engine::ResourceManager::GetTexture("Data/textures/planets/planet_46.png", 500, 500, 32, 4).id,
0.0f,
Engine::ColorRGBA8(255, 255, 255, 255)
);
//Planet 2 (Moon)
m_spriteBatch.Draw(m_planet2,
m_uvRect,
Engine::ResourceManager::GetTexture("Data/textures/planets/planet_37.png", 500, 500, 32, 4).id,
0.0f,
Engine::ColorRGBA8(255, 255, 255, 255)
);
//Planet 3 (Gas Giant)
m_spriteBatch.Draw(m_planet3,
m_uvRect,
Engine::ResourceManager::GetTexture("Data/textures/planets/planet_48.png", 500, 500, 32, 4).id,
0.0f,
Engine::ColorRGBA8(255, 255, 255, 255)
);
m_spriteBatch.End();
m_spriteBatch.renderbatch();
}
void Map::DrawSun() {
m_spriteBatch.initBatch();
m_spriteBatch.Begin();
m_spriteBatch.Draw(m_sun,
m_uvRect,
Engine::ResourceManager::GetTexture("Data/textures/planets/Sun.png", 521, 522, 32, 4).id,
0.0f,
Engine::ColorRGBA8(255, 255, 255, 255)
);
m_spriteBatch.End();
m_spriteBatch.renderbatch();
}
| 21.127517 | 97 | 0.640407 | [
"render",
"vector"
] |
91e0a29260e446ca76735d9dda9c6c20457a0348 | 1,226 | cpp | C++ | projects/SURFKeypointMatching/SURFKeypointMatching.cpp | trevstanhope/scratch-Cpp | f6a0db5a7aeb388a852180dc0be749c1e7c2e318 | [
"MIT"
] | null | null | null | projects/SURFKeypointMatching/SURFKeypointMatching.cpp | trevstanhope/scratch-Cpp | f6a0db5a7aeb388a852180dc0be749c1e7c2e318 | [
"MIT"
] | null | null | null | projects/SURFKeypointMatching/SURFKeypointMatching.cpp | trevstanhope/scratch-Cpp | f6a0db5a7aeb388a852180dc0be749c1e7c2e318 | [
"MIT"
] | null | null | null | #include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <stdio.h>
using namespace cv;
int main( int argc, char** argv )
{
if(argc != 3)
{
return -1;
}
Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
if(img1.empty() || img2.empty())
{
printf("Can't read one of the imagesn");
return -1;
}
// detecting keypoints
SurfFeatureDetector detector(400);
vector<KeyPoint> keypoints1, keypoints2;
detector.detect(img1, keypoints1);
detector.detect(img2, keypoints2);
// computing descriptors
SurfDescriptorExtractor extractor;
Mat descriptors1, descriptors2;
extractor.compute(img1, keypoints1, descriptors1);
extractor.compute(img2, keypoints2, descriptors2);
// matching descriptors
BFMatcher matcher(NORM_L2);
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
// drawing the results
namedWindow("matches", 1);
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
imshow("matches", img_matches);
waitKey(0);
return 0;
}
| 24.52 | 72 | 0.721044 | [
"vector"
] |
91f53118ae69781668aee5472a39c217a2f17ea4 | 1,198 | hpp | C++ | Deitel/Chapter13/exercises/13.17/BasePlusCommissionEmployee.hpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 19 | 2019-09-15T12:23:51.000Z | 2020-06-18T08:31:26.000Z | Deitel/Chapter13/exercises/13.17/BasePlusCommissionEmployee.hpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | Deitel/Chapter13/exercises/13.17/BasePlusCommissionEmployee.hpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | /*
* =====================================================================================
*
* Filename: BasePlusCommissionEmployee.hpp
*
* Description: Fig. 13.15: BasePlusCommissionEmployee class derived from
* CommissionEmployee.
*
* Version: 1.0
* Created: 12/08/16 20:05:29
* Revision: none
* Compiler: gcc
*
* Author: Siidney Watson - siidney.watson.work@gmail.com
* Organization: LolaDog Studio
*
* =====================================================================================
*/
#pragma once
#include "CommissionEmployee.hpp"
class BasePlusCommissionEmployee : public CommissionEmployee {
public:
BasePlusCommissionEmployee(const std::string&, const std::string&,
const std::string&, double = 0.0f, double = 0.0f,
double = 0.0f);
void setBaseSalary(double);
double getBaseSalary() const;
// keyword virtual signals intent to override
virtual double earnings() const; // calculate earnings
virtual void print() const; // print BasePlusCommissionEmployee object
private:
double baseSalary;
};
| 30.717949 | 88 | 0.53172 | [
"object"
] |
91f86bfc74b6779a5b8bdfd69adf969495622915 | 12,119 | cpp | C++ | StrSTUN-synthesizer/strstunlib0/src/GoalGraphManager.cpp | HALOCORE/SynGuar | 8f7f9ba52e83091ad3def501169fd60d20b28321 | [
"MIT"
] | 1 | 2021-06-23T05:10:36.000Z | 2021-06-23T05:10:36.000Z | StrSTUN-synthesizer/strstunlib0/src/GoalGraphManager.cpp | HALOCORE/SynGuar | 8f7f9ba52e83091ad3def501169fd60d20b28321 | [
"MIT"
] | null | null | null | StrSTUN-synthesizer/strstunlib0/src/GoalGraphManager.cpp | HALOCORE/SynGuar | 8f7f9ba52e83091ad3def501169fd60d20b28321 | [
"MIT"
] | null | null | null | #include "GoalGraphManager.hpp"
#include "visitorbase.hpp"
#include "VisitorPretty.hpp"
#include "ValueVector.hpp"
GoalGraphManager::GoalGraphManager(bool isFullMatch) : goalRoot(), unionGoalsHash(131072) {
//this->pAllGoals.push_back(&goalRoot);
this->createProgram1stParam = nullptr;
this->pCreateProgram = nullptr;
if(isFullMatch) this->firstN = -1;
else this->firstN = 0;
}
GoalGraphManager::~GoalGraphManager() {
std::cerr << "# GoalGraphManager deleted.\n";
for(GoalUnion* p : this->unionGoals) {
delete p;
}
for(GoalConcrete* p : this->concreteGoals) {
delete p;
}
for(GoalConcrete* p : this->concreteCondGoals) {
delete p;
}
}
void GoalGraphManager::setProgramCreator(
ObjBase* createProgram1stParam,
Program* (*pCreateProgram)(ObjBase* createProgram1stParam, std::string mComponentId, std::vector<Program*> mInputPrograms)) {
this->createProgram1stParam = createProgram1stParam;
this->pCreateProgram = pCreateProgram;
}
///////////// this is the static branchProgramCreate used by Goal
Program* GoalGraphManager::branchProgramCreate(ObjBase* callObj, ValType vt, Program* condProg, Program* thenProg, Program* elseProg) {
GoalGraphManager* ggm = reinterpret_cast<GoalGraphManager*>(callObj);
std::string compId = ComponentIfThenElse::componentIdByValType[vt];
std::vector<Program*> inputPrograms;
inputPrograms.push_back(condProg);
inputPrograms.push_back(thenProg);
inputPrograms.push_back(elseProg);
Program* resultProg = ggm->pCreateProgram(ggm->createProgram1stParam, compId, inputPrograms);
assert(resultProg != nullptr);
return resultProg;
}
void GoalGraphManager::buildBottomValueGoals(std::vector<std::tuple<ValueVector*, std::vector<Program*>*>>* valueVecMapping) {
std::cerr << "# GoalGraphManager::buildBottomValueGoals.\n";
mpz_class total_value_term = 0;
int assert_appended_p = 0;
for(auto p : *valueVecMapping) {
//check all value vectors against target values
//maintain a vector of concrete goals
auto valvec = std::get<0>(p);
std::vector<int> matchingVec = ValueVector::getConcreteMatchingVector(this->targetValues, *valvec, this->firstN);
//VisitorPretty::common->visit(valvec);
bool anyMatchingGoal = false;
for(auto & g : this->concreteGoals) {
assert(g->isConcrete);
if(g->isBooleanVecEqual(matchingVec)) {
anyMatchingGoal = true;
g->addMatchingValVecNoCheck(p);
assert_appended_p++;
break;
}
}
if(!anyMatchingGoal) {
//all concrete goals are solved
GoalConcrete* newGoal = new GoalConcrete(matchingVec, p);
assert_appended_p++;
this->concreteGoals.push_back(newGoal);
this->updateAnyMatchVector(matchingVec);
}
}
assert(assert_appended_p == valueVecMapping->size());
for(auto& g : this->concreteGoals) total_value_term += g->solutionCount;
this->term_count_upper = total_value_term;
std::cerr << "# GoalGraphManager::buildBottomValueGoals done: #concrete=" << this->concreteGoals.size() << " totalTerm=" << total_value_term << "\n";
VisitorPretty::common->printIntVec(this->anyMatchVector);
}
void GoalGraphManager::buildBottomCondGoals(std::vector<std::tuple<ValueVector*, std::vector<Program*>*>>* condValueVecMapping) {
std::cerr << "# GoalGraphManager::buildBottomCondGoals.\n";
mpz_class total_cond = 0;
for(auto p : *condValueVecMapping) {
//check all cond vectors
//maintain a vector of concrete cond goals
auto condvec = ValueVector::convertToMatchingVector(*std::get<0>(p), this->firstN);
bool anyMatchingGoal = false;
for(auto & g : this->concreteCondGoals) {
assert(g->isConcrete);
if(g->isBooleanVecEqual(condvec)) {
anyMatchingGoal = true;
g->addMatchingValVecNoCheck(p);
break;
}
}
if(!anyMatchingGoal) {
GoalConcrete* newGoal = new GoalConcrete(condvec, p);
this->concreteCondGoals.push_back(newGoal);
}
}
for(auto& g : this->concreteCondGoals) total_cond += g->solutionCount;
this->cond_count_upper = total_cond;
std::cerr << "# GoalGraphManager::buildBottomCondGoals done: #concrete=" << this->concreteCondGoals.size() << " totalCond=" << total_cond << "\n";
}
void GoalGraphManager::buildCondGraph(int goalDepth) {
//TODO
std::cerr << "# GoalGraphManager::buildCondGraph. Fill root concrete...\n";
for(auto& cg : this->concreteGoals) {
if(cg->isGoodWithExpectedVec(this->goalRoot->boolMathingVec)) {
EVENT_COUNT("GRootDirect");
this->goalRoot->addConcreteGoalNoCheck(cg);
}
}
assert(goalDepth > 0);
std::cerr << "# GoalGraphManager::buildCondGraph. Expanding root...\n";
std::vector<GoalUnion*> toExpand;
for(auto& cg : this->concreteCondGoals) {
auto p = this->goalRoot->getTEGoalsForConcreteCond(cg);
std::vector<int>& thenEx = std::get<0>(p);
std::vector<int>& elseEx = std::get<1>(p);
if(thenEx.size() == 0) {
//this condition cannot use.
assert(elseEx.size() == 0);
continue;
}
GoalUnion* thenGoal = this->getOrCreateUnionGoals(thenEx);
if(thenGoal->concreteGoals.size() == 0) {
//then union goal don't have concrete implementation.
EVENT_COUNT("ThSk");
continue;
}
GoalUnion* elseGoal = this->getOrCreateUnionGoals(elseEx);
this->goalRoot->addBranchGoalsNoCheck(cg, thenGoal, elseGoal);
EVENT_COUNT("GRSpt");
toExpand.push_back(elseGoal);
}
this->goalRoot->isExpanded = true;
if(goalDepth > 1) {
assert(goalDepth == 2);
std::cerr << "# GoalGraphManager::buildCondGraph. Expanding second level...\n";
for(auto& xd : toExpand) {
if(!xd->isExpanded) {
for(auto& cg : this->concreteCondGoals) {
auto p = xd->getTEGoalsForConcreteCond(cg);
std::vector<int>& thenEx = std::get<0>(p);
std::vector<int>& elseEx = std::get<1>(p);
if(thenEx.size() == 0) {
//this condition cannot use.
assert(elseEx.size() == 0);
continue;
}
GoalUnion* thenGoal = this->getOrCreateUnionGoals(thenEx);
if(thenGoal->concreteGoals.size() == 0) {
//then union goal don't have concrete implementation.
EVENT_COUNT("ThSk");
continue;
}
GoalUnion* elseGoal = this->getOrCreateUnionGoals(elseEx);
xd->addBranchGoalsNoCheck(cg, thenGoal, elseGoal);
EVENT_COUNT("GRSpt");
}
xd->isExpanded = true;
}
}
}
this->calcHSizeUpperBound(goalDepth);
std::cerr << "# GoalGraphManager::buildCondGraph. Upper bound of H: " << this->prog_count_upper << "\n";
std::cerr << "# GoalGraphManager::buildCondGraph. Expanding first expand [skipped]\n";
std::cerr << "# GoalGraphManager::buildCondGraph. Count level 0...\n";
for(auto & ug : this->unionGoals) {
ug->checkAndCountByLevel(0);
}
std::cerr << "# GoalGraphManager::buildCondGraph. Count level 1...\n";
for(auto & ug : this->unionGoals) {
ug->checkAndCountByLevel(1);
}
if(goalDepth > 1) {
assert(goalDepth == 2);
std::cerr << "# GoalGraphManager::buildCondGraph. Count level 2...\n";
for(auto & ug : this->unionGoals) {
ug->checkAndCountByLevel(2);
}
}
this->goalRoot->ensureResultProgram(this, GoalGraphManager::branchProgramCreate);
std::cerr << "# GoalGraphManager::buildCondGraph. RootGoal Solution Count:\n";
this->goalRoot->debugPrint();
std::cerr << "\n";
this->prog_count_aftersynth = this->goalRoot->getTotalSolutionCount();
std::cerr << "# GoalGraphManager::buildCondGraph. Upper bound of H after synth: " << this->prog_count_aftersynth << "\n\n";
}
mpz_class GoalGraphManager::calcHSizeUpperBound(int maxCond) {
mpz_class totalH = 1;
for(int i = 0; i < maxCond; i++) {
totalH *= this->cond_count_upper - i;
totalH *= this->term_count_upper;
}
totalH *= this->term_count_upper;
this->prog_count_upper = totalH;
return totalH;
}
GoalUnion* GoalGraphManager::getOrCreateUnionGoals(std::vector<int>& expectedMatchVec){
//#define GU_VECTOR_DEDUP
#define GU_HASHMAP_DEDUP
#ifdef GU_VECTOR_DEDUP
for(auto ug : this->unionGoals) {
if(ug->isBooleanVecEqual(expectedMatchVec)) {
return ug;
}
}
#else
#ifdef GU_HASHMAP_DEDUP
IntVecP vp; vp.intvecp = &expectedMatchVec;
if(this->unionGoalsHash.find(vp) != this->unionGoalsHash.end()) {
return this->unionGoalsHash.at(vp);
}
#else
GoalUnion* gu1 = nullptr;
GoalUnion* gu2 = nullptr;
for(auto ug : this->unionGoals) {
if(ug->isBooleanVecEqual(expectedMatchVec)) {
gu1 = ug;
}
}
if(this->unionGoalsHash.find(expectedMatchVec) != this->unionGoalsHash.end()) {
gu2 = this->unionGoalsHash.at(expectedMatchVec);
}
assert(gu1 == gu2);
if(gu1 != nullptr) return gu1;
#endif
#endif
//otherwize, create new union goal, from concrete.
GoalUnion* newGU = new GoalUnion(expectedMatchVec);
for(auto& cg : this->concreteGoals) {
if(cg->isGoodWithExpectedVec(expectedMatchVec)) {
newGU->addConcreteGoalNoCheck(cg);
}
}
this->unionGoals.push_back(newGU);
IntVecP vp2; vp2.intvecp = new std::vector<int>(expectedMatchVec);
this->unionGoalsHash.insert(std::make_pair(vp2, newGU));
//std::cerr << "N";
return newGU;
}
void GoalGraphManager::clearAndResetGoal(ValueVector targetValues) {
std::cerr << "GoalGraphManager::clearAndResetGoal\n";
this->targetValues = targetValues;
this->anyMatchVector.clear();
this->anyMatchCount = 0;
std::vector<int> vec;
for(int i = 0; i < targetValues.values.size(); i++) {
this->anyMatchVector.push_back(0);
vec.push_back(1);
}
assert(vec.size() > 0);
if(this->firstN == 0) this->firstN = vec.size();
this->goalRoot = new GoalUnion(vec);
this->concreteGoals.clear();
this->concreteCondGoals.clear();
this->unionGoals.clear();
this->unionGoalsHash.clear();
this->unionGoals.push_back(this->goalRoot); //root goal is union goal.
IntVecP vp; vp.intvecp = new std::vector<int>(this->goalRoot->boolMathingVec);
this->unionGoalsHash.insert(std::make_pair(vp, this->goalRoot));
this->cond_count_upper = 0;
this->term_count_upper = 0;
this->prog_count_upper = 0;
assert(!this->getIsGoalRootSolved());
}
bool GoalGraphManager::getIsGoalRootSolved() {
Program* result = this->goalRoot->resultProgram;
if(result == nullptr) return false;
return true;
}
Program* GoalGraphManager::getGoalRootResultProgram() {
Program* result = this->goalRoot->resultProgram;
return result;
}
int GoalGraphManager::updateAnyMatchVector(std::vector<int>& boolMatchVec) {
int updatedMatchCount = 0;
for(int i = 0; i < boolMatchVec.size(); i++) {
if(boolMatchVec[i] == 1) {
anyMatchVector[i] += 1;
updatedMatchCount += 1;
} else {
assert(boolMatchVec[i] == 0);
if(anyMatchVector[i] > 0){
updatedMatchCount += 1;
}
}
}
this->anyMatchCount = updatedMatchCount;
return updatedMatchCount;
}
void GoalGraphManager::accept(Visitor* visitor) {
//visitor->visit(&this->goalRoot);
std::cerr << "GoalGraphManager::accept not implemented.\n";
} | 38.473016 | 153 | 0.622741 | [
"vector"
] |
91f93411814db4c28d64a260c139ea14ba1e9f8b | 7,023 | hpp | C++ | kernel/bb/Brick11/exe/fb11ademod_config.hpp | Bhaskers-Blu-Org2/Sora | 6aa5411db71199e56d5cb24265b01a89f49b40f4 | [
"BSD-2-Clause"
] | 270 | 2015-07-17T15:43:43.000Z | 2019-04-21T12:13:58.000Z | kernel/bb/Brick11/exe/fb11ademod_config.hpp | JamesLinus/Sora | 6aa5411db71199e56d5cb24265b01a89f49b40f4 | [
"BSD-2-Clause"
] | null | null | null | kernel/bb/Brick11/exe/fb11ademod_config.hpp | JamesLinus/Sora | 6aa5411db71199e56d5cb24265b01a89f49b40f4 | [
"BSD-2-Clause"
] | 106 | 2015-07-20T10:40:34.000Z | 2019-04-25T10:02:26.000Z | #pragma once
#include "ieee80211facade.hpp"
#include "depuncturer.hpp"
typedef struct _tagBB11aDemodContext :
LOCAL_CONTEXT(TDropAny)
, LOCAL_CONTEXT(TBB11aFrameSink)
, LOCAL_CONTEXT(T11aViterbi)
, LOCAL_CONTEXT(T11aPLCPParser)
, LOCAL_CONTEXT(T11aDemap)
, LOCAL_CONTEXT(TPilotTrack)
, LOCAL_CONTEXT(TChannelEqualization)
, LOCAL_CONTEXT(T11aLTSymbol)
, LOCAL_CONTEXT(TChannelEst)
, LOCAL_CONTEXT(TCCA11a)
, LOCAL_CONTEXT(TPhaseCompensate)
, LOCAL_CONTEXT(TFFT64)
, LOCAL_CONTEXT(TFreqCompensation)
, LOCAL_CONTEXT(TDCRemove)
, LOCAL_CONTEXT(TMemSamples)
, LOCAL_CONTEXT(TBB11aRxRateSel)
, LOCAL_CONTEXT(T11aLTS)
{
void Reset () {
// Reset all CFacade data in the context
// CF_Error
CF_Error::error_code() = E_ERROR_SUCCESS;
// CF_11CCA
CF_11CCA::Reset();
// CF_Channel_11a
CF_Channel_11a::Reset ();
// CF_11aRxVector
CF_11aRxVector::Reset ();
// CF_FreqOffsetComp
CF_FreqCompensate::Reset ();
// Phase
CF_PhaseCompensate::Reset ();
// CF_PilotTrack
CF_PilotTrack::Reset ();
// CF_11aSymSel
CF_11aSymState::Reset();
// CF_CFOffset
CF_CFOffset::Reset ();
// CF_11RxPLCPSwitch
CF_11RxPLCPSwitch::Reset();
// CF_11aRxVector
CF_11aRxVector::Reset();
}
void Init ( COMPLEX16* input, uint in_size, UCHAR* output, uint out_size )
{
// CF_11CCA
CF_11CCA::cca_pwr_threshold() = 1000*1000; // set energy threshold
// CF_MemSamples
CF_MemSamples::Init ( input, in_size );
// CF_VecDC
CF_VecDC::Reset ();
/* for (int i=0; i<4; i++) {
CF_VecDC::direct_current()[i].re = 1458;
CF_VecDC::direct_current()[i].im = -573;
}
*/
// CF_RxFrameBuffer
CF_RxFrameBuffer::Init (output, out_size);
Reset ();
}
void CCA_OnPowerDetected () {
// printf ( "CCA ::=> Power detected at %d\n", CF_MemSamples::mem_sample_index() );
}
void CCA_OnCCADone () {
printf ( "CCA ::=> CCA done at %d\n", CF_MemSamples::mem_sample_index() );
}
}BB11aDemodContext;
BB11aDemodContext BB11aDemodCtx;
struct sym_selector {
FINL
int operator()(BB11aDemodContext& ctx) {
if ( ctx.CF_11aSymState::symbol_type() == CF_11aSymState::SYMBOL_TRAINING ) {
return PORT_0;
} else {
return PORT_1;
}
}
};
typedef TGDemux<2, COMPLEX16, 4, sym_selector> T11aSymSelEx;
//
// Define the selector object for the plcp switch
//
struct plcp_selector {
FINL
int operator()(BB11aDemodContext& ctx) {
if ( ctx.CF_11RxPLCPSwitch::plcp_state() == CF_11RxPLCPSwitch::plcp_header ) {
return PORT_0;
} else {
return PORT_1;
}
}
};
/*************************************************************************
Processing graph
src-> downsample -> rxswt -> dc_removedc -> BB11aCCA -> estimate_dc
|-> symsel -> LTSSymbol -> ch_est -> fine_cfo -> drop
|-> dataSym -> FFT -> Equalization -> phase_comp ..->
..-> pilot -> plcpswt -> plcp_demap -> plcp_deinter -> plcp_viterbi -> plcp_parser
| -> 6M_demap -> 6M_deinter -> thread_sep -> viterbi -> desc -> frame_sink
*************************************************************************/
// Note: use "static inline" instead of "inline" to prevent silent function confliction during linking.
// Otherwise, it will introduce wrong linking result because these inline function share the same name,
// and indeed not inlined.
// ref: http://stackoverflow.com/questions/2217628/multiple-definition-of-inline-functions-when-linking-static-libs
static inline
void CreateDemodGraph11a (ISource*& src1, ISource*& src2)
{
CREATE_BRICK_SINK (drop, TDropAny, BB11aDemodCtx );
CREATE_BRICK_SINK (err , TFrameError, BB11aDemodCtx );
CREATE_BRICK_SINK (fsink, TBB11aFrameSink, BB11aDemodCtx );
CREATE_BRICK_FILTER (desc, T11aDesc, BB11aDemodCtx, fsink );
typedef T11aViterbi<5000*8, 48, 24> T11aViterbi6M;
typedef T11aViterbi<5000*8, 48*2, 24*8> T11aViterbi24M;
typedef T11aViterbi<5000*8, 48*6*4/3, 192> T11aViterbi48M;
CREATE_BRICK_FILTER (viterbi, T11aViterbi6M::Filter, BB11aDemodCtx, desc );
CREATE_BRICK_FILTER (vit1, TThreadSeparator<128>::Filter, BB11aDemodCtx, viterbi);
CREATE_BRICK_FILTER (vit0, TNoInline, BB11aDemodCtx, vit1);
// CREATE_BRICK_FILTER (vit0, TNoInline, BB11aDemodCtx, viterbi);
// CREATE_BRICK_SINK (vit0, TDropAny, BB11aDemodCtx );
// 6M
CREATE_BRICK_FILTER (di6, T11aDeinterleaveBPSK, BB11aDemodCtx, vit0 );
CREATE_BRICK_FILTER (dm6, T11aDemapBPSK::Filter, BB11aDemodCtx, di6 );
#if 0
// 12M
CREATE_BRICK_FILTER (di12, T11aDeinterleaveQPSK, BB11aDemodCtx, vit0 );
CREATE_BRICK_FILTER (dm12, T11aDemapQPSK, BB11aDemodCtx, di12 );
#endif
// 24M
CREATE_BRICK_FILTER (di24, T11aDeinterleaveQAM16, BB11aDemodCtx, vit1 );
CREATE_BRICK_FILTER (dm24, T11aDemapQAM16::Filter, BB11aDemodCtx, di24 );
// 48M
CREATE_BRICK_FILTER (di48, T11aDeinterleaveQAM64, BB11aDemodCtx, vit0 );
CREATE_BRICK_FILTER (dm48, T11aDemapQAM64::Filter, BB11aDemodCtx, di48 );
// PLCP
CREATE_BRICK_SINK (plcp, T11aPLCPParser, BB11aDemodCtx );
CREATE_BRICK_FILTER (sviterbik, T11aViterbiSig, BB11aDemodCtx, plcp );
CREATE_BRICK_FILTER (dibpsk, T11aDeinterleaveBPSK, BB11aDemodCtx, sviterbik );
CREATE_BRICK_FILTER (dmplcp, T11aDemapBPSK::Filter, BB11aDemodCtx, dibpsk );
CREATE_BRICK_DEMUX5 ( sigsel, TBB11aRxRateSel, BB11aDemodCtx,
dmplcp, dm6, err, dm24, dm48 );
// CREATE_BRICK_FILTER ( sigsel0, TNoInline, BB11aDemodCtx, sigsel );
CREATE_BRICK_FILTER (pilot, TPilotTrack, BB11aDemodCtx, sigsel );
CREATE_BRICK_FILTER (pcomp, TPhaseCompensate, BB11aDemodCtx, pilot );
CREATE_BRICK_FILTER (chequ, TChannelEqualization, BB11aDemodCtx, pcomp );
CREATE_BRICK_FILTER (fft, TFFT64, BB11aDemodCtx, chequ );
CREATE_BRICK_FILTER (fcomp, TFreqCompensation, BB11aDemodCtx, fft );
CREATE_BRICK_FILTER (dsym, T11aDataSymbol, BB11aDemodCtx, fcomp );
CREATE_BRICK_FILTER (dsym0, TNoInline, BB11aDemodCtx, dsym );
// LTS path
// CREATE_BRICK_FILTER (fcfo, TFineCFOEst, BB11aDemodCtx, drop );
// CREATE_BRICK_FILTER (chest, TChannelEst, BB11aDemodCtx, fcfo );
// CREATE_BRICK_FILTER (lsym, T11aLTSymbol, BB11aDemodCtx, chest );
CREATE_BRICK_SINK (lsym, T11aLTS, BB11aDemodCtx );
CREATE_BRICK_DEMUX2 (symsel, T11aSymSelEx::Filter, BB11aDemodCtx,
lsym, dsym0 );
CREATE_BRICK_FILTER (dcest, TDCEstimator, BB11aDemodCtx, drop );
CREATE_BRICK_FILTER (cca, TCCA11a, BB11aDemodCtx, dcest );
CREATE_BRICK_FILTER (dc, TDCRemoveEx<4>::Filter, BB11aDemodCtx, cca );
CREATE_BRICK_DEMUX2 (rxswt, TBB11bRxSwitch, BB11aDemodCtx,
dc, symsel);
CREATE_BRICK_FILTER (ds2, TDownSample2, BB11aDemodCtx, rxswt );
CREATE_BRICK_SOURCE (fsrc, TMemSamples, BB11aDemodCtx, ds2 );
src1 = fsrc;
src2 = vit1;
// src2 = fsrc;
}
| 31.352679 | 115 | 0.679624 | [
"object"
] |
6209b20aaebde0012dda2bc520d7d8f3edd86a0d | 3,494 | cpp | C++ | src/PokemonBLL/Jogo.cpp | mpeschke/OOP-PROJ1 | a0cb356a9b504ef49d3b1f2df12ade674628e482 | [
"MIT"
] | null | null | null | src/PokemonBLL/Jogo.cpp | mpeschke/OOP-PROJ1 | a0cb356a9b504ef49d3b1f2df12ade674628e482 | [
"MIT"
] | null | null | null | src/PokemonBLL/Jogo.cpp | mpeschke/OOP-PROJ1 | a0cb356a9b504ef49d3b1f2df12ade674628e482 | [
"MIT"
] | null | null | null | /**
Jogo.cpp
Purpose: classe do jogo
@author Matheus Peschke
@version 1.0.0 2021-05-09
*/
#include "Jogo.hpp"
#include "Pokemon.hpp"
#include "Pokemonrodada.hpp"
#include "Pokemoncardgenerator.hpp"
#include "Exceptions.hpp"
namespace BLL {
Jogo::Jogo()
: m_rodadas(0U), m_numero_cartas_pras_rodadas(0U)
{}
Jogo::Jogo(const bool computadorjoga, const unsigned int numero_cartas_pras_rodadas)
: m_computadorjoga(computadorjoga), m_numero_cartas_pras_rodadas(numero_cartas_pras_rodadas)
{}
std::vector<Pokemonrodada>& Jogo::get_rodadas()
{return this->m_rodadas;}
const bool Jogo::get_computadorjoga() const
{return this->m_computadorjoga;}
void Jogo::set_rodadas(const std::vector<Pokemonrodada>& rodadas)
{this->m_rodadas = rodadas;}
void Jogo::set_computadorjoga(const bool computadorjoga)
{this->m_computadorjoga = computadorjoga;}
// Usando stl count_if, com um predicado, para validar a regra fornecida no enunciado:
// "Vence o jogador que ainda tem (pelo menos) 1 pokemon ativo." Isso induz que,
// se o adversário ainda tem um pokemon ativo, ele ainda pode jogar.
// Conclusão: um dos jogadores tem que ter pelo menos 1 ativo, e o outro jogador nenhum.
bool Jogo::tem_vencedor(const std::vector<Pokemon>& maojogador1, const std::vector<Pokemon>& maojogador2) const
{
bool jogador1venceu = (
(std::count_if(maojogador1.begin(), maojogador1.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) >= 1U) &&
(std::count_if(maojogador2.begin(), maojogador2.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) == 0U)
);
bool jogador2venceu = (
(std::count_if(maojogador2.begin(), maojogador2.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) >= 1U) &&
(std::count_if(maojogador1.begin(), maojogador1.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) == 0U)
);
return jogador1venceu || jogador2venceu;
}
// A lógica aqui é semelhante à da função Jogo::tem_vencedor.
BLL::tstring Jogo::get_vencedor(const std::vector<Pokemon>& maojogador1, const std::vector<Pokemon>& maojogador2) const
{
bool jogador1venceu = (
(std::count_if(maojogador1.begin(), maojogador1.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) >= 1U) &&
(std::count_if(maojogador2.begin(), maojogador2.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) == 0U)
);
bool jogador2venceu = (
(std::count_if(maojogador2.begin(), maojogador2.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) >= 1U) &&
(std::count_if(maojogador1.begin(), maojogador1.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) == 0U)
);
if(jogador1venceu && !jogador2venceu)
return maojogador1[0].get_jogador();
else if(jogador2venceu && !jogador1venceu)
return maojogador2[0].get_jogador();
return "";
}
// A lógica aqui é semelhante à da função Jogo::tem_vencedor.
bool Jogo::continuarjogando(const std::vector<Pokemon>& maojogador1, const std::vector<Pokemon>& maojogador2) const
{
// Se um dos jogadores não tem nenhum pokemon ativo, o jogo está finalizado.
return !(
(std::count_if(maojogador1.begin(), maojogador1.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) == 0U) ||
(std::count_if(maojogador2.begin(), maojogador2.end(),[](Pokemon pk){return pk.get_status() == Status::Ativo;}) == 0U)
);
}
Jogo::~Jogo()
{}
} /* namespace BLL */
| 38.822222 | 129 | 0.688323 | [
"vector"
] |
620b14486643e637dbdcc5a34612fca1dcd07341 | 23,591 | cpp | C++ | src/sweepers/moc/tests/test_Ray.cpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 11 | 2016-03-31T17:46:15.000Z | 2022-02-14T01:07:56.000Z | src/sweepers/moc/tests/test_Ray.cpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 3 | 2016-04-04T16:40:47.000Z | 2019-10-16T22:22:54.000Z | src/sweepers/moc/tests/test_Ray.cpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 3 | 2019-10-16T22:20:15.000Z | 2019-11-28T11:59:03.000Z | /*
Copyright 2016 Mitchell Young
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 "UnitTest++/UnitTest++.h"
#include <cassert>
#include <string>
#include "pugixml.hpp"
#include "util/global_config.hpp"
#include "core/angular_quadrature.hpp"
#include "core/constants.hpp"
#include "core/core_mesh.hpp"
#include "moc/ray_data.hpp"
using namespace mocc;
using namespace mocc::moc;
TEST(big_ray)
{
pugi::xml_document geom_xml;
geom_xml.load_file("large.xml");
mocc::CoreMesh mesh(geom_xml);
Ray ray(Point2(64.050000000000011, 0.0),
Point2(64.260000000000019, 0.024230769230770152), {{0, 0}}, 0,
mesh);
CHECK_EQUAL(1, ray.cm_data().size());
return;
}
TEST(simple_ray)
{
pugi::xml_document geom_xml;
pugi::xml_parse_result result = geom_xml.load_file("6x5.xml");
REQUIRE CHECK(result);
mocc::CoreMesh mesh(geom_xml);
{
// Test a few rays that starts on a corner, ends on a corner and crosses
// a bunch of corners
{
Ray ray(Point2(0.0, 1.0), Point2(4.0, 5.0), {{0, 0}}, 0, mesh);
CHECK_EQUAL(ray.cm_surf_fw(), 37);
CHECK_EQUAL(ray.cm_cell_fw(), 6);
CHECK_EQUAL(ray.cm_surf_bw(), 88);
CHECK_EQUAL(ray.cm_cell_bw(), 27);
CHECK_EQUAL(ray.nseg(), 12);
CHECK_EQUAL(ray.ncseg(), 8);
// all of the segment lengths should be the same. I'm not testing
// this too much in the general sense, since the tests for the pin
// meshes should find most of these types of issues.
real_t t = 1.0 / 3.0 * sqrt(2);
for (auto v : ray.seg_len()) {
CHECK_CLOSE(v, t, 0.00001);
}
std::vector<Surface> fw_surf = {
Surface::EAST, Surface::NORTH, Surface::EAST, Surface::NORTH,
Surface::EAST, Surface::NORTH, Surface::EAST, Surface::NORTH};
std::vector<Surface> bw_surf = {
Surface::WEST, Surface::SOUTH, Surface::WEST, Surface::SOUTH,
Surface::WEST, Surface::SOUTH, Surface::SOUTH, Surface::WEST};
VecI nseg = {3, 0, 3, 0, 3, 0, 3, 0};
for (int i = 0; i < ray.ncseg(); i++) {
auto rcd = ray.cm_data()[i];
CHECK_EQUAL(rcd.fw, fw_surf[i]);
CHECK_EQUAL(rcd.bw, bw_surf[i]);
CHECK_EQUAL(rcd.nseg_fw, nseg[i]);
CHECK_EQUAL(rcd.nseg_bw, nseg[i]);
}
}
{
Ray ray(Point2(4.0, 0.0), Point2(6.0, 2.0), {{0, 0}}, 0, mesh);
CHECK_EQUAL(ray.cm_surf_fw(), 89);
CHECK_EQUAL(ray.cm_cell_fw(), 4);
CHECK_EQUAL(ray.cm_surf_bw(), 43);
CHECK_EQUAL(ray.cm_cell_bw(), 11);
CHECK_EQUAL(ray.nseg(), 6);
CHECK_EQUAL(ray.ncseg(), 4);
}
{
Ray ray(Point2(2.0, 0.0), Point2(0.0, 2.0), {{0, 0}}, 0, mesh);
}
{
Ray ray(Point2(6.0, 3.0), Point2(4.0, 5.0), {{0, 0}}, 0, mesh);
}
{
Ray ray(Point2(0.0, 0.5), Point2(6.0, 3.25), {{0, 0}}, 0, mesh);
}
}
}
TEST(nasty_ray)
{
pugi::xml_document geom_xml;
pugi::xml_parse_result result = geom_xml.load_file("square.xml");
mocc::CoreMesh mesh(geom_xml);
pugi::xml_document angquad_xml;
result = angquad_xml.load_string("<ang_quad type=\"ls\" order=\"4\" />");
// Make a nasty ray to exercise the coarse indexing
{
Ray ray(Point2(1.26, 0.0), Point2(3.78, 2.52), {{0, 0}}, 0, mesh);
}
{
Ray ray(Point2(1.26, 0.0), Point2(0.0, 1.26), {{0, 0}}, 0, mesh);
}
{
Ray ray(Point2(0.0, 1.26), Point2(2.52, 3.78), {{0, 0}}, 0, mesh);
}
{
Ray ray(Point2(3.78, 2.52), Point2(2.52, 3.78), {{0, 0}}, 0, mesh);
}
}
TEST(weird_ray)
{
std::string test_xml =
"<mesh id=\"1\" type=\"rect\" pitch=\"10\">"
" <sub_x>80</sub_x>"
" <sub_y>80</sub_y>"
"</mesh>"
"<pin id=\"1\" mesh=\"1\">"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
"</pin>"
""
"<lattice id=\"1\" nx=\"1\" ny=\"1\">"
" 1"
"</lattice>"
""
"<assembly id=\"1\" np=\"1\" hz=\"1.0\">"
" <lattices>1</lattices>"
"</assembly>"
""
"<core nx=\"1\" ny=\"1\""
" north=\"reflect\""
" south=\"reflect\""
" top=\"reflect\""
" bottom=\"reflect\""
" west=\"prescribed\""
" east=\"prescribed\">"
" 1"
"</core>"
""
"<material_lib path=\"c5g7.xsl\">"
" <material id=\"1\" name=\"UO2-3.3\" />"
"</material_lib>"
"<parallel num_threads=\"1\" />"
"";
pugi::xml_document xml;
xml.load_string(test_xml.c_str());
auto result = xml.load_string(test_xml.c_str());
REQUIRE CHECK(result);
CoreMesh core_mesh(xml);
// convert from pin-local to core-local
// {x = 3.750000000000004, y = 0, ok = true}
// {x = 0, y = 0.75757575757575779, ok = true}
Point2 p1(-1.249999999999996+5.0, -5.0+5.0);
Point2 p2(-5+5.0, -4.2424242424242422+5.0);
std::array<int,2> bc={106,7};
Ray ray(p1, p2, bc, 0, core_mesh);
std::cout << ray << std::endl;
// CHECK
VecI seg_index_expect = {
29, 28, 27, 26, 25, 105,
104, 103, 102, 101, 100, 180,
179, 178, 177, 176, 175, 255,
254, 253, 252, 251, 250, 330,
329, 328, 327, 326, 325, 405,
404, 403, 402, 401, 400, 480};
VecF seg_len_expect = {
0.12752525252525659, 0.12752525252525249, 0.12752525252525249,
0.12752525252525268, 0.12114898989898612, 0.0063762626262663788,
0.12752525252525249, 0.12752525252525249, 0.12752525252525249,
0.12752525252525249, 0.11477272727272445, 0.012752525252528228,
0.12752525252525249, 0.12752525252525249, 0.12752525252525249,
0.12752525252525249, 0.10839646464646216, 0.01912878787879034,
0.12752525252525268, 0.12752525252525249, 0.12752525252525249,
0.12752525252525249, 0.10202020202019987, 0.025505050505052623,
0.12752525252525268, 0.12752525252525249, 0.12752525252525249,
0.12752525252525249, 0.095643939393937588, 0.031881313131314912,
0.12752525252525249, 0.12752525252525249, 0.12752525252525268,
0.12752525252525249, 0.089267676767675302, 0.038257575757577197};
REQUIRE CHECK_EQUAL(36, ray.nseg());
CHECK_ARRAY_EQUAL(seg_index_expect, ray.seg_index(), 36);
CHECK_ARRAY_CLOSE(seg_len_expect, ray.seg_len(), 36, 0.000000000000001);
}
int main()
{
return UnitTest::RunAllTests();
}
| 75.612179 | 196 | 0.444195 | [
"mesh",
"vector"
] |
620e4ed9fb0acebb1d9e7d48df8abbf859291279 | 4,937 | cc | C++ | components/autofill/core/browser/payments/payments_util_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | components/autofill/core/browser/payments/payments_util_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/autofill/core/browser/payments/payments_util_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 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 "components/autofill/core/browser/payments/payments_util.h"
#include <string>
#include "base/guid.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/payments/payments_customer_data.h"
#include "components/autofill/core/browser/test_personal_data_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace autofill {
namespace payments {
class PaymentsUtilTest : public testing::Test {
public:
PaymentsUtilTest() {}
~PaymentsUtilTest() override {}
protected:
TestPersonalDataManager personal_data_manager_;
private:
DISALLOW_COPY_AND_ASSIGN(PaymentsUtilTest);
};
TEST_F(PaymentsUtilTest, GetBillingCustomerId_PaymentsCustomerData_Normal) {
personal_data_manager_.SetPaymentsCustomerData(
std::make_unique<PaymentsCustomerData>(/*customer_id=*/"123456"));
EXPECT_EQ(123456, GetBillingCustomerId(&personal_data_manager_));
}
TEST_F(PaymentsUtilTest, GetBillingCustomerId_PaymentsCustomerData_Garbage) {
personal_data_manager_.SetPaymentsCustomerData(
std::make_unique<PaymentsCustomerData>(/*customer_id=*/"garbage"));
EXPECT_EQ(0, GetBillingCustomerId(&personal_data_manager_));
}
TEST_F(PaymentsUtilTest, GetBillingCustomerId_PaymentsCustomerData_NoData) {
// Explictly do not set PaymentsCustomerData. Nothing crashes and the returned
// customer ID is 0.
EXPECT_EQ(0, GetBillingCustomerId(&personal_data_manager_));
}
TEST_F(PaymentsUtilTest, HasGooglePaymentsAccount_Normal) {
personal_data_manager_.SetPaymentsCustomerData(
std::make_unique<PaymentsCustomerData>(/*customer_id=*/"123456"));
EXPECT_TRUE(HasGooglePaymentsAccount(&personal_data_manager_));
}
TEST_F(PaymentsUtilTest, HasGooglePaymentsAccount_NoData) {
// Explicitly do not set Prefs data. Nothing crashes and returns false.
EXPECT_FALSE(HasGooglePaymentsAccount(&personal_data_manager_));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_EmptyBin) {
// Create empty supported card bin ranges.
std::vector<std::pair<int, int>> supported_card_bin_ranges;
std::u16string card_number = u"4111111111111111";
// Card number is not supported since the supported bin range is empty.
EXPECT_FALSE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_SameStartAndEnd) {
std::vector<std::pair<int, int>> supported_card_bin_ranges{
std::make_pair(411111, 411111)};
std::u16string card_number = u"4111111111111111";
// Card number is supported since it is within the range of the same start and
// end.
EXPECT_TRUE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_InsideRange) {
std::vector<std::pair<int, int>> supported_card_bin_ranges{
std::make_pair(411110, 411112)};
std::u16string card_number = u"4111111111111111";
// Card number is supported since it is inside the range.
EXPECT_TRUE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_StartBoundary) {
std::vector<std::pair<int, int>> supported_card_bin_ranges{
std::make_pair(411111, 422222)};
std::u16string card_number = u"4111111111111111";
// Card number is supported since it is at the start boundary.
EXPECT_TRUE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_EndBoundary) {
std::vector<std::pair<int, int>> supported_card_bin_ranges{
std::make_pair(410000, 411111)};
std::u16string card_number = u"4111111111111111";
// Card number is supported since it is at the end boundary.
EXPECT_TRUE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_OutOfRange) {
std::vector<std::pair<int, int>> supported_card_bin_ranges{
std::make_pair(2111, 2111), std::make_pair(412, 413),
std::make_pair(300, 305)};
std::u16string card_number = u"4111111111111111";
// Card number is not supported since it is out of any range.
EXPECT_FALSE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
TEST_F(PaymentsUtilTest, IsCreditCardNumberSupported_SeparatorStripped) {
std::vector<std::pair<int, int>> supported_card_bin_ranges{
std::make_pair(4111, 4111)};
std::u16string card_number = u"4111-1111-1111-1111";
// The separators are correctly stripped and the card number is supported.
EXPECT_TRUE(
IsCreditCardNumberSupported(card_number, supported_card_bin_ranges));
}
} // namespace payments
} // namespace autofill
| 37.976923 | 80 | 0.785497 | [
"vector"
] |
621774c3ff4b4f1c9251c73e23ccd9ae920c732f | 1,297 | cpp | C++ | c&c++/vpm.cpp | VanirLab/Vanir-API | e3fed71c3c5b74550e5ae8d0afdbf124edcc036f | [
"MIT"
] | 1 | 2020-07-23T11:59:46.000Z | 2020-07-23T11:59:46.000Z | c&c++/vpm.cpp | VanirLab/Vanir-API | e3fed71c3c5b74550e5ae8d0afdbf124edcc036f | [
"MIT"
] | null | null | null | c&c++/vpm.cpp | VanirLab/Vanir-API | e3fed71c3c5b74550e5ae8d0afdbf124edcc036f | [
"MIT"
] | null | null | null | //VANIR CORE MANAGER FOR API
#include "vdefines.h"
#include <vector>
#include <string>
class V_CORE_API PlugInstance
{
public:
explicit PlugInstance(const std::string&name);
~PlugInstance();
bool Load();
bool Unload();
bool IsLoaded();
bool Lock();
bool IsLocked();
bool Verify();
bool IsVerified();
std::string GetFileName();
std::string GetDisplayName();
std::string GetPackageName();
std::string GetByteByByte();
std::string GetCodeVersion();
std::string GetNameByTime();
private:
PlugInstance(const PlugInstance &);
const PlugInstance &operator=(const PlugInstance &);
class Impl;
Impl *mlmpl;
};
class V_CORE_API PluginManager
{
public:
static PluginManager &GetInstance();
bool LoadAll();
bool Load(const std::string &name);
bool UnloadAll();
bool Inject();
bool Unload(const std::string &name);
std::vector<PlugInstance*>GetAllPlugins();
private:
PluginManager();
~PluginManager();
PluginManager(const PluginManager &);
const PluginManager &operator=(const PlugInstance &);
std::vector<PluginManager*>mPlugins;
};
class VpatchString : public vString
{
public:
VpathString();
~VpathString();
vString GetNameByTime();
vString GetAllPlugins();
vString GetCodeVersion();
};
| 19.073529 | 54 | 0.687741 | [
"vector"
] |
621c5017caf69adaa63a60a329a95718779859f8 | 2,723 | cc | C++ | Calibration/Tools/src/BlockSolver.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Calibration/Tools/src/BlockSolver.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Calibration/Tools/src/BlockSolver.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | /**
*/
#include "Calibration/Tools/interface/BlockSolver.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
int BlockSolver::operator()(const CLHEP::HepMatrix& matrix, const CLHEP::HepVector& vector, CLHEP::HepVector& result) {
double threshold = matrix.trace() / static_cast<double>(matrix.num_row());
std::vector<int> holes;
// loop over the matrix rows
for (int row = 0; row < matrix.num_row(); ++row) {
double sumAbs = 0.;
for (int col = 0; col < matrix.num_col(); ++col)
sumAbs += fabs(matrix[row][col]);
if (sumAbs < threshold)
holes.push_back(row);
} // loop over the matrix rows
int dim = matrix.num_col() - holes.size();
if (holes.empty()) //PG exceptional case!
{
for (int i = 0; i < result.num_row(); ++i)
result[i] = 1.;
} else if (dim > 0) {
CLHEP::HepMatrix solution(dim, dim, 0);
CLHEP::HepVector input(dim, 0);
shrink(matrix, solution, vector, input, holes);
CLHEP::HepVector output = solve(solution, input);
pour(result, output, holes);
}
return holes.size();
}
// ------------------------------------------------------------
void BlockSolver::shrink(const CLHEP::HepMatrix& matrix,
CLHEP::HepMatrix& solution,
const CLHEP::HepVector& result,
CLHEP::HepVector& input,
const std::vector<int>& where) {
int offsetRow = 0;
std::vector<int>::const_iterator whereRows = where.begin();
// loop over rows
for (int row = 0; row < matrix.num_row(); ++row) {
if (row == *whereRows) {
// std::cerr << " DEBUG shr hole found " << std::endl ;
++offsetRow;
++whereRows;
continue;
}
input[row - offsetRow] = result[row];
int offsetCol = 0;
std::vector<int>::const_iterator whereCols = where.begin();
// loop over columns
for (int col = 0; col < matrix.num_col(); ++col) {
if (col == *whereCols) {
++offsetCol;
++whereCols;
continue;
}
solution[row - offsetRow][col - offsetCol] = matrix[row][col];
}
} // loop over rows
return;
}
// ------------------------------------------------------------
void BlockSolver::pour(CLHEP::HepVector& result, const CLHEP::HepVector& output, const std::vector<int>& where) {
std::vector<int>::const_iterator whereCols = where.begin();
int readingIndex = 0;
//PG loop over the output crystals
for (int xtal = 0; xtal < result.num_row(); ++xtal) {
if (xtal == *whereCols) {
result[xtal] = 1.;
++whereCols;
} else {
result[xtal] = output[readingIndex];
++readingIndex;
}
} //PG loop over the output crystals
return;
}
| 32.035294 | 119 | 0.565185 | [
"vector"
] |
6220d1db718a5b648a948923e0f1fa5a15660142 | 2,720 | hpp | C++ | coding/arithmetic_codec.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-01-11T05:02:05.000Z | 2019-01-11T05:02:05.000Z | coding/arithmetic_codec.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | null | null | null | coding/arithmetic_codec.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:21:09.000Z | 2019-08-09T21:21:09.000Z | // Author: Artyom.
// Arithmetic Encoder/Decoder.
// See http://en.wikipedia.org/wiki/Arithmetic_coding
// Usage:
// // Compute freqs table by counting number of occurancies of each symbol.
// // Freqs table should have size equal to number of symbols in the alphabet.
// // Convert freqs table to distr table.
// vector<uint32_t> distrTable = FreqsToDistrTable(freqs);
// ArithmeticEncoder arith_enc(distrTable);
// // Encode any number of symbols.
// arith_enc.Encode(10); arith_enc.Encode(17); arith_enc.Encode(0); arith_enc.Encode(4);
// // Get encoded bytes.
// vector<uint8_t> encoded_data = arith_enc.Finalize();
// // Decode encoded bytes. Number of symbols should be provided outside.
// MemReader reader(encoded_data.data(), encoded_data.size());
// ArithmeticDecoder arith_dec(&reader, distrTable);
// uint32_t sym1 = arith_dec.Decode(); uint32_t sym2 = arith_dec.Decode();
// uint32_t sym3 = arith_dec.Decode(); uint32_t sym4 = arith_dec.Decode();
#pragma once
#include "std/cstdint.hpp"
#include "std/vector.hpp"
// Forward declarations.
class Reader;
// Default shift of distribution table, i.e. all distribution table frequencies are
// normalized by this shift, i.e. distr table upper bound equals (1 << DISTR_SHIFT).
uint32_t const DISTR_SHIFT = 16;
// Converts symbols frequencies table to distribution table, used in Arithmetic codecs.
vector<uint32_t> FreqsToDistrTable(vector<uint32_t> const & freqs);
class ArithmeticEncoder
{
public:
// Provided distribution table.
ArithmeticEncoder(vector<uint32_t> const & distrTable);
// Encode symbol using given distribution table and add that symbol to output.
void Encode(uint32_t symbol);
// Finalize encoding, flushes remaining bytes from the buffer to output.
// Returns output vector of encoded bytes.
vector<uint8_t> Finalize();
private:
// Propagates carry in case of overflow.
void PropagateCarry();
private:
uint32_t m_begin;
uint32_t m_size;
vector<uint8_t> m_output;
vector<uint32_t> const & m_distrTable;
};
class ArithmeticDecoder
{
public:
// Decoder is given a reader to read input bytes,
// distrTable - distribution table to decode symbols.
ArithmeticDecoder(Reader & reader, vector<uint32_t> const & distrTable);
// Decode next symbol from the encoded stream.
uint32_t Decode();
private:
// Read next code byte from encoded stream.
uint8_t ReadCodeByte();
private:
// Current most significant part of code value.
uint32_t m_codeValue;
// Current interval size.
uint32_t m_size;
// Reader and two bounds of encoded data within this Reader.
Reader & m_reader;
uint64_t m_serialCur;
uint64_t m_serialEnd;
vector<uint32_t> const & m_distrTable;
};
| 35.324675 | 90 | 0.740074 | [
"vector"
] |
6224eff3b3d21c888a6e1fc2328055cfbd1f0cc6 | 8,235 | cpp | C++ | libinendi/tests/correlation.cpp | inendi-inspector/inspector | 9b9a00222d8a73cb0817ca56790ee9155db61cc4 | [
"MIT"
] | null | null | null | libinendi/tests/correlation.cpp | inendi-inspector/inspector | 9b9a00222d8a73cb0817ca56790ee9155db61cc4 | [
"MIT"
] | null | null | null | libinendi/tests/correlation.cpp | inendi-inspector/inspector | 9b9a00222d8a73cb0817ca56790ee9155db61cc4 | [
"MIT"
] | null | null | null | //
// MIT License
//
// © ESI Group, 2015
//
// 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 <inendi/PVLayerFilter.h>
#include <pvkernel/core/inendi_assert.h>
#include <pvkernel/core/PVEnumType.h>
#include <pvkernel/core/PVOriginalAxisIndexType.h>
#include <pvkernel/core/PVPlainTextType.h>
#include "common.h"
static constexpr const char* csv_file1 = TEST_FOLDER "/sources/proxy_sample1.log";
static constexpr const char* csv_file2 = TEST_FOLDER "/sources/proxy_sample2.log";
static constexpr const char* csv_file_format =
TEST_FOLDER "/formats/proxy_sample_correlation.format";
#ifdef INSPECTOR_BENCH
static constexpr unsigned int dupl = 100;
#else
static constexpr unsigned int dupl = 1;
#endif
void run_multiplesearch_filter(Inendi::PVView* view1, PVCore::PVOriginalAxisIndexType ait, const PVCore::PVPlainTextType& text_values)
{
constexpr char plugin_name[] = "search-multiple";
Inendi::PVLayerFilter::p_type filter_org =
LIB_CLASS(Inendi::PVLayerFilter)::get().get_class_by_name(plugin_name);
Inendi::PVLayerFilter::p_type plugin = filter_org->clone<Inendi::PVLayerFilter>();
PVCore::PVArgumentList& args = view1->get_last_args_filter(plugin_name);
Inendi::PVLayer& out = view1->get_post_filter_layer();
out.reset_to_empty_and_default_color();
Inendi::PVLayer& in = view1->get_layer_stack_output_layer();
args["axis"].setValue(ait);
args["exps"].setValue(text_values);
plugin->set_view(view1);
plugin->set_output(&out);
plugin->set_args(args);
plugin->operator()(in);
view1->set_selection_view(view1->get_post_filter_layer().get_selection());
}
int main()
{
pvtest::TestEnv env(csv_file1, csv_file_format, dupl);
env.add_source(csv_file2, csv_file_format, dupl);
env.compute_mappings();
env.compute_plottings();
env.compute_views();
auto views = env.root.get_children<Inendi::PVView>();
PV_VALID(views.size(), 2UL);
/**
* Add correlation between source IP columns
*/
Inendi::PVView* view1 = views.front();
Inendi::PVView* view2 = views.back();
Inendi::PVCorrelation correlation{view1, PVCol(2), view2, PVCol(2)};
PV_ASSERT_VALID(not env.root.correlations().exists(view1, PVCol(2)));
PV_ASSERT_VALID(not env.root.correlations().exists(correlation));
PV_ASSERT_VALID(env.root.correlations().correlation(view1) == nullptr);
env.root.correlations().add(correlation);
PV_ASSERT_VALID(env.root.correlations().exists(view1, PVCol(2)));
PV_ASSERT_VALID(
env.root.correlations().exists(Inendi::PVCorrelation{view1, PVCol(2), view2, PVCol(2)}));
PV_ASSERT_VALID(env.root.correlations().correlation(view1) != nullptr);
/**
* Filter values using multiple-search plugin
*/
auto start = std::chrono::system_clock::now();
run_multiplesearch_filter(
view1,
PVCore::PVOriginalAxisIndexType(PVCol(4) /* HTTP status */),
PVCore::PVPlainTextType("503")
);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << diff.count();
#ifndef INSPECTOR_BENCH
const Inendi::PVSelection& sel1 = view1->get_post_filter_layer().get_selection();
size_t count1 = sel1.bit_count();
const Inendi::PVSelection& sel2 = view2->get_post_filter_layer().get_selection();
size_t count2 = sel2.bit_count();
PV_VALID(count1, 11UL);
PV_VALID(count2, 84UL);
std::vector<size_t> v1(
{1332, 1485, 1540, 1875, 1877, 1966, 3156, 3159, 3199, 5689, 5762, 5764, 5767, 5791,
5843, 6003, 6009, 6177, 6205, 6213, 6221, 6252, 6260, 6293, 6294, 6295, 6297, 6298,
6299, 6300, 6301, 6305, 6306, 6307, 6308, 6309, 6311, 6313, 6314, 6315, 6317, 6319,
6320, 6321, 6323, 6324, 6325, 6329, 6332, 6333, 6335, 6337, 6340, 6341, 6343, 6344,
6346, 6349, 6350, 6354, 6356, 6357, 6358, 6359, 6362, 6365, 6366, 6370, 6374, 6383,
6384, 6385, 6410, 6411, 6414, 6420, 9703, 9704, 9747, 9969, 9970, 9974, 9998, 9999});
std::vector<size_t> v2;
sel2.visit_selected_lines([&](PVRow const row) { v2.push_back(row); });
PV_ASSERT_VALID(std::equal(v1.begin(), v1.end(), v2.begin()));
/**
* Add reciprocal correlation
*/
Inendi::PVCorrelation reciprocal_correlation{view2, correlation.col2, view1, correlation.col1};
env.root.correlations().add(reciprocal_correlation);
PV_ASSERT_VALID(env.root.correlations().exists(reciprocal_correlation));
PV_ASSERT_VALID(env.root.correlations().exists(correlation));
/**
* Remove all correlations (by removing view2 in both ways)
*/
env.root.correlations().remove(correlation.view2, true);
PV_ASSERT_VALID(not env.root.correlations().exists(view1, correlation.col1));
PV_ASSERT_VALID(not env.root.correlations().exists(view2, reciprocal_correlation.col1));
PV_ASSERT_VALID(not env.root.correlations().exists(correlation));
PV_ASSERT_VALID(not env.root.correlations().exists(reciprocal_correlation));
PV_ASSERT_VALID(env.root.correlations().correlation(view1) == nullptr);
PV_ASSERT_VALID(env.root.correlations().correlation(view2) == nullptr);
/**
* Re-add correlation
*/
env.root.correlations().add(correlation);
PV_ASSERT_VALID(env.root.correlations().exists(view1, PVCol(2)));
PV_ASSERT_VALID(
env.root.correlations().exists(Inendi::PVCorrelation{view1, PVCol(2), view2, PVCol(2)}));
PV_ASSERT_VALID(env.root.correlations().correlation(view1) != nullptr);
/**
* Re-remove correlation on view1
*/
env.root.correlations().remove(correlation.view1);
PV_ASSERT_VALID(not env.root.correlations().exists(view1, PVCol(2)));
PV_ASSERT_VALID(not env.root.correlations().exists(correlation));
PV_ASSERT_VALID(env.root.correlations().correlation(view1) == nullptr);
/**
* Replace correlation
*/
Inendi::PVCorrelation new_correlation{view1, PVCol(13), view2, PVCol(13)};
env.root.correlations().add(correlation);
env.root.correlations().add(new_correlation);
PV_ASSERT_VALID(not env.root.correlations().exists(correlation));
PV_ASSERT_VALID(env.root.correlations().exists(new_correlation));
/**
* Check that range correlation is properly working
*/
{
env.root.correlations().remove(correlation.view2, true);
Inendi::PVCorrelation range_correlation{view1, PVCol(5), view2, PVCol(5), Inendi::PVCorrelationType::RANGE};
env.root.correlations().add(range_correlation);
run_multiplesearch_filter(
view1,
PVCore::PVOriginalAxisIndexType(PVCol(5) /* Total bytes */),
PVCore::PVPlainTextType("0\n999")
);
const Inendi::PVSelection& sel1 = view1->get_post_filter_layer().get_selection();
size_t count1 = sel1.bit_count();
const Inendi::PVSelection& sel2 = view2->get_post_filter_layer().get_selection();
size_t count2 = sel2.bit_count();
PV_VALID(count1, 138UL);
PV_VALID(count2, 3990UL);
}
/**
* Check that removing view1 remove all correlations
*/
view1->get_parent().remove_child(*view1);
PV_ASSERT_VALID(not env.root.correlations().exists(view1, correlation.col1));
PV_ASSERT_VALID(not env.root.correlations().exists(view2, reciprocal_correlation.col1));
PV_ASSERT_VALID(not env.root.correlations().exists(correlation));
PV_ASSERT_VALID(not env.root.correlations().exists(reciprocal_correlation));
PV_ASSERT_VALID(env.root.correlations().correlation(view1) == nullptr);
PV_ASSERT_VALID(env.root.correlations().correlation(view2) == nullptr);
#endif
return 0;
}
| 38.125 | 134 | 0.746084 | [
"vector"
] |
622665f5ca7f5c295a81d99a8a38f6defecb7bf6 | 1,077 | cpp | C++ | Suffix Automata/suffix-automata.cpp | Kavaliro98/competitive-programming-codes | af9c4c58d8abbba7e8bcaf707da2cabc2a941eeb | [
"MIT"
] | null | null | null | Suffix Automata/suffix-automata.cpp | Kavaliro98/competitive-programming-codes | af9c4c58d8abbba7e8bcaf707da2cabc2a941eeb | [
"MIT"
] | null | null | null | Suffix Automata/suffix-automata.cpp | Kavaliro98/competitive-programming-codes | af9c4c58d8abbba7e8bcaf707da2cabc2a941eeb | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct SuffixAutomata {
#define state(x) tie(len[x], lnk[x], org[x], nxt[x])
vector<int> len, lnk, org;
vector<map<char,int>> nxt;
int sz, last;
SuffixAutomata(int n) {
sz = last = 0;
len = lnk = org = vector<int>(n<<1);
nxt.resize(n<<1);
state(0) = tuple(0, -1, 0, map<char,int>());
sz++;
}
int extend(int c) {
int cur = sz++;
state(cur) = tuple(len[last]+1, 0, 1, map<char,int>());
int p = last;
for( ; p!=-1 && !nxt[p].count(c) ; p=lnk[p]) nxt[p][c]=cur;
if(p == -1) lnk[cur] = 0;
else {
int q = nxt[p][c];
if(len[p]+1 == len[q]) lnk[cur] = q;
else {
int cpy = sz++;
state(cpy) = tuple(len[p]+1, lnk[q], 0, nxt[q]);
for( ; p!=-1 && nxt[p][c]==q ; p=lnk[p]) nxt[p][c]=cpy;
lnk[q] = lnk[cur] = cpy;
}
}
return last = cur;
}
};
int main() {
string s = "banana";
SuffixAutomata sa(s.size());
for(auto c:s) {
sa.extend(c);
}
}
| 23.413043 | 67 | 0.456825 | [
"vector"
] |
622b1bea09ae6428111e17b94d8c5a68c3f2e2dd | 2,879 | cpp | C++ | Practice/2019.5.18/LOJ3046.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2019.5.18/LOJ3046.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2019.5.18/LOJ3046.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
#define pb push_back
const int maxN=203000;
const int Bit=20;
class SegmentData
{
public:
int ls,rs,cnt,sum,l,r;
};
int n,m,Lg[maxN];
vector<int> T[maxN];
vector<int> Del[maxN];
int dfncnt,dfn[maxN],ST[Bit][maxN],Fa[maxN],D[maxN];
int scnt=0,rt[maxN];
SegmentData S[maxN*80];
long long Ans;
void dfs1(int u);
void dfs2(int u);
int LCA(int u,int v);
bool cmp(int a,int b);
void Update(int x);
void Modify(int &x,int l,int r,int p,int key);
int Merge(int u,int v,int l,int r);
int main()
{
for (int i=2; i<maxN; i++) Lg[i]=Lg[i>>1]+1;
scanf("%d%d",&n,&m);
for (int i=1; i<n; i++) {
int u,v;
scanf("%d%d",&u,&v);
T[u].pb(v);
T[v].pb(u);
}
dfs1(1);
for (int i=1; i<Bit; i++) for (int j=1; j+(1<<i)-1<=dfncnt; j++) ST[i][j]=min(ST[i-1][j],ST[i-1][j+(1<<(i-1))],cmp);
for (int i=1; i<=m; i++) {
int x,y;
scanf("%d%d",&x,&y);
if (x==y) continue;
int lca=LCA(x,y),fa=Fa[lca];
Modify(rt[x],1,dfncnt,x,1);
Modify(rt[x],1,dfncnt,y,1);
Modify(rt[y],1,dfncnt,x,1);
Modify(rt[y],1,dfncnt,y,1);
Del[fa].pb(x);
Del[fa].pb(y);
}
dfs2(1);
printf("%lld\n",Ans/2);
return 0;
}
void dfs1(int u)
{
ST[0][dfn[u]=++dfncnt]=u;
for (int i=0,sz=T[u].size(); i<sz; i++) if (T[u][i]!=Fa[u]) Fa[T[u][i]]=u,D[T[u][i]]=D[u]+1,dfs1(T[u][i]),ST[0][++dfncnt]=u;
return;
}
void dfs2(int u)
{
for (int i=0,sz=T[u].size(); i<sz; i++) if (T[u][i]!=Fa[u]) dfs2(T[u][i]),rt[u]=Merge(rt[u],rt[T[u][i]],1,dfncnt);
for (int i=0,sz=Del[u].size(); i<sz; i++) Modify(rt[u],1,dfncnt,Del[u][i],-2);
if (S[rt[u]].l&&S[rt[u]].r)
Ans=Ans+S[rt[u]].sum-D[LCA(S[rt[u]].l,S[rt[u]].r)];
return;
}
int LCA(int u,int v)
{
if (!u||!v) return 0;
if (dfn[u]>dfn[v]) swap(u,v);
int lg=Lg[dfn[v]-dfn[u]+1];
return min(ST[lg][dfn[u]],ST[lg][dfn[v]-(1<<lg)+1],cmp);
}
bool cmp(int a,int b)
{
return D[a]<D[b];
}
void Update(int x)
{
S[x].l=S[S[x].ls].l?S[S[x].ls].l:S[S[x].rs].l;
S[x].r=S[S[x].rs].r?S[S[x].rs].r:S[S[x].ls].r;
S[x].sum=S[S[x].ls].sum+S[S[x].rs].sum;
if (S[S[x].ls].r&&S[S[x].rs].l) S[x].sum=S[x].sum-D[LCA(S[S[x].ls].r,S[S[x].rs].l)];
return;
}
void Modify(int &x,int l,int r,int p,int key)
{
S[++scnt]=S[x];
x=scnt;
if (l==r) {
S[x].cnt+=key;
if (S[x].cnt) S[x].l=S[x].r=p,S[x].sum=D[p];
else S[x].l=S[x].r=S[x].sum=0;
return;
}
int mid=(l+r)>>1;
if (dfn[p]<=mid) Modify(S[x].ls,l,mid,p,key);
else Modify(S[x].rs,mid+1,r,p,key);
Update(x);
return;
}
int Merge(int u,int v,int l,int r)
{
if (!u||!v) return u+v;
int id=++scnt;
if (l==r) {
S[id].cnt=S[u].cnt+S[v].cnt;
if (S[id].cnt) S[id].l=S[id].r=ST[0][l],S[id].sum=D[ST[0][l]];
else S[id].l=S[id].r=S[id].sum=0;
return id;
}
int mid=(l+r)>>1;
S[id].ls=Merge(S[u].ls,S[v].ls,l,mid);
S[id].rs=Merge(S[u].rs,S[v].rs,mid+1,r);
Update(id);
return id;
}
| 22.669291 | 125 | 0.549496 | [
"vector"
] |
622c81c4730025a3bbf98114a787734906157136 | 13,890 | cpp | C++ | SOURCES/falclib/falcent.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/falclib/falcent.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/falclib/falcent.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include <string.h>
#include "f4vu.h"
#include "ClassTbl.h"
#include "sim/include/simbase.h"
#include "sim/include/aircrft.h"
#include "campbase.h"
#include "falcmesg.h"
#include "FalcSess.h"
#include "FalcEnt.h"
#include "Find.h"
#include "Campaign.h"
#include "MsgInc/CampDirtyDataMsg.h"
#include "MsgInc/SimDirtyDataMsg.h"
#include "package.h"
#include "gndunit.h"
#include "team.h"
#include "InvalidBufferException.h"
using namespace std;
// ==================================
// Falcon Entity functions
// ==================================
FalconEntity::FalconEntity(ushort type, VU_ID_NUMBER eid) : VuEntity(type, eid){
InitLocalData();
}
FalconEntity::FalconEntity(VU_BYTE** stream, long *rem) : VuEntity (stream, rem) {
InitLocalData();
memcpychk(&falconType, stream, sizeof (falconType), rem);
if (gCampDataVersion >= 32) {
memcpychk(&falconFlags, stream, sizeof (uchar), rem);
}
}
FalconEntity::FalconEntity(FILE* filePtr) : VuEntity (filePtr) {
InitLocalData();
fread (&falconType, sizeof (falconType), 1, filePtr);
if (gCampDataVersion >= 32){
fread (&falconFlags, sizeof (uchar), 1, filePtr);
}
}
FalconEntity::~FalconEntity(void) {
CleanupLocalData();
}
void FalconEntity::InitData(){
InitLocalData();
}
void FalconEntity::InitLocalData(){
falconType = 0;
falconFlags = 0;
dirty_falcent = 0;
dirty_classes = 0;
dirty_score = 0;
feLocalFlags = 0;
}
void FalconEntity::CleanupData(){
CleanupLocalData();
}
void FalconEntity::CleanupLocalData(){
// nothing to do here
}
int FalconEntity::Save(VU_BYTE** stream) {
int saveSize = VuEntity::Save (stream);
memcpy (*stream, &falconType, sizeof (falconType)); *stream += sizeof (falconType); saveSize += sizeof (falconType);
memcpy (*stream, &falconFlags, sizeof (uchar)); *stream += sizeof (uchar); saveSize += sizeof (uchar);
return (saveSize);
}
int FalconEntity::Save(FILE* filePtr) {
int saveSize = VuEntity::Save (filePtr);
fwrite (&falconType, sizeof (falconType), 1, filePtr); saveSize += sizeof (falconType);
fwrite (&falconFlags, sizeof (uchar), 1, filePtr); saveSize += sizeof (uchar);
return (saveSize);
}
int FalconEntity::SaveSize(void) {
return VuEntity::SaveSize() + sizeof (falconType) + sizeof (uchar);
// return VuEntity::SaveSize();
}
uchar FalconEntity::GetDomain (void) {
return Falcon4ClassTable[Type()-VU_LAST_ENTITY_TYPE].vuClassData.classInfo_[VU_DOMAIN];
}
uchar* FalconEntity::GetDamageModifiers (void) {
return DefaultDamageMods;
}
void FalconEntity::GetLocation (GridIndex* x, GridIndex* y) const {
::vector v;
v.x = XPos();
v.y = YPos();
v.z = 0.0F;
ConvertSimToGrid(&v,x,y);
}
void FalconEntity::SetOwner (FalconSessionEntity* session) {
// Set the owner to session
share_.ownerId_ = session->OwnerId();
}
void FalconEntity::SetOwner (VU_ID sessionId) {
// Set the owner to session
share_.ownerId_ = sessionId;
}
void FalconEntity::DoFullUpdate (void) {
VuEvent *event = new VuFullUpdateEvent(this, FalconLocalGame);
event->RequestReliableTransmit ();
VuMessageQueue::PostVuMessage(event);
}
int FalconEntity::calc_dirty_bucket(int dirty_score) {
int ds = dirty_score; //just for debugging
if (dirty_score == 0) {
return -1;
}
// sfr : new
int bin = 0;
while ((dirty_score & 0x1) == 0){ ++bin; dirty_score >>= 4; }
return bin;
#if 0
// sfr: old
else if (dirty_score <= SEND_EVENTUALLY) {
return 1;
}
else if (dirty_score <= SEND_SOMETIME) {
return 2;
}
else if (dirty_score <= SEND_LATER) {
return 3;
}
else if (dirty_score <= SEND_SOON) {
return 4;
}
else if (dirty_score <= SEND_NOW) {
return 5;
}
else if (dirty_score <= SEND_RELIABLE) {
return 6;
}
else if (dirty_score <= SEND_OOB) {
return 7;
}
else if (dirty_score > SEND_OOB) {
return 8;
}
else {
ShiAssert("This can't happen at all...");
return 0;
}
#endif
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FalconEntity::ClearDirty (void){
// dodirtydata removes it from lists nows
dirty_classes = 0;
dirty_score = 0;
#if 0
//sfr: old
int bin;
VuEnterCriticalSection ();
bin = calc_dirty_bucket ();
assert((bin >= 0) && (bin < MAX_DIRTY_BUCKETS));
dirty_classes = 0;
dirty_score = 0;
DirtyBucket[bin]->Remove(this);
VuExitCriticalSection();
#endif
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FalconEntity::MakeDirty (Dirty_Class bits, Dirtyness score) {
dirty_classes |= bits;
// sfr: for player entities, always send reliable and immediatelly
if (IsPlayer()){
score = SEND_RELIABLEANDOOB;
}
// send only local units which are active (in DB) and if the unit is more dirty than currently is
if (
(!IsLocal()) ||
(VuState() != VU_MEM_ACTIVE) ||
(score <= dirty_score) ||
!(TheCampaign.Flags & CAMP_LOADED)
){
return;
}
dirty_score = score;
int bin = calc_dirty_bucket(score);
if (IsSimBase()){
F4ScopeLock lock(simDirtyMutexes[bin]);
#if USE_VU_COLL_FOR_DIRTY
simDirtyBuckets[bin]->ForcedInsert(this);
#else
simDirtyBuckets[bin]->push_back(FalconEntityBin(this));
#endif
}
else {
F4ScopeLock lock(campDirtyMutexes[bin]);
#if USE_VU_COLL_FOR_DIRTY
campDirtyBuckets[bin]->ForcedInsert(this);
#else
campDirtyBuckets[bin]->push_back(FalconEntityBin(this));
#endif
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int FalconEntity::EncodeDirty (unsigned char **stream) {
uchar *start;
start = *stream;
// MonoPrint ("SendDirty %08x%08x %08x\n", Id(), dirty_classes);
*(short*)*stream = (short)dirty_classes;
*stream += sizeof (short);
if (dirty_classes & DIRTY_FALCON_ENTITY) {
*(uchar *)(*stream) = falconFlags;
*stream += sizeof (uchar);
}
if (dirty_classes & DIRTY_CAMPAIGN_BASE) {
((CampBaseClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_OBJECTIVE) {
((ObjectiveClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_UNIT) {
((UnitClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_PACKAGE) {
((PackageClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_SQUADRON) {
((SquadronClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_FLIGHT) {
((FlightClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_GROUND_UNIT) {
((GroundUnitClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_BATTALION) {
((BattalionClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_TEAM) {
((TeamClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_SIM_BASE) {
((SimBaseClass*)this)->WriteDirty (stream);
}
if (dirty_classes & DIRTY_AIRCRAFT){
((AircraftClass*)this)->WriteDirty(stream);
}
return *stream - start;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//sfr: changed this function prototype, see falcent.h
//changed body too
void FalconEntity::DecodeDirty (unsigned char **stream, long *rem){
short bits;
//read bits and update count
memcpychk(&bits, stream, sizeof(short), rem);
if (bits & DIRTY_FALCON_ENTITY) {
memcpychk(&falconFlags, stream, sizeof(uchar), rem);
}
if (bits & DIRTY_CAMPAIGN_BASE) {
((CampBaseClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_OBJECTIVE) {
((ObjectiveClass*)this)->ReadDirty(stream, rem);
}
if (bits & DIRTY_UNIT) {
((UnitClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_PACKAGE) {
((PackageClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_SQUADRON) {
((SquadronClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_FLIGHT) {
((FlightClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_GROUND_UNIT) {
((GroundUnitClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_BATTALION) {
((BattalionClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_TEAM) {
((TeamClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_SIM_BASE) {
((SimBaseClass*)this)->ReadDirty (stream, rem);
}
if (bits & DIRTY_AIRCRAFT){
((AircraftClass*)this)->ReadDirty(stream, rem);
}
}
//sfr: changed identation and calls to DecodeDirty
void FalconEntity::DoCampaignDirtyData(VU_TIME realTime) {
static VU_TIME lastSent = 0;
if (!(TheCampaign.Flags & CAMP_LOADED) || ((realTime - lastSent) < SIMDIRTYDATA_INTERVAL)){
return;
}
lastSent = realTime;
//a buffer for encoding decoding stuff, usually small, but theres a big one > 512
unsigned char buffer[1024];
//pointers to the buffer above
unsigned char *bufptr;
// max number of sends to do on this run
int toSend = 16;
// run all buckets
for (int bucket = MAX_DIRTY_BUCKETS - 1; (bucket >= 0); --bucket){
// send at least one from each bucket
bool sent = false;
F4ScopeLock lock(campDirtyMutexes[bucket]);
#if USE_VU_COLL_FOR_DIRTY
FalconEntity *current;
while ((current = static_cast<FalconEntity*>(campDirtyBuckets[bucket]->PopHead())) != NULL)
#else
while (!campDirtyBuckets[bucket]->empty())
#endif
{
//bucket 7 and 8 are OOB(out of band), the others must respect bw
if ((bucket < 7) && (toSend < 0) && (sent)){
break;
}
#if !USE_VU_COLL_FOR_DIRTY
FalconEntityBin current(campDirtyBuckets[bucket]->front());
campDirtyBuckets[bucket]->pop_front();
#endif
// can happen if inserted multiple times
if ((current->dirty_classes == 0) || (current->GetDirty() == 0)){
continue;
}
// encode and clear dirty to send message
bufptr = buffer;
long bufSize = static_cast<long>(current->EncodeDirty(&bufptr));
CampDirtyData *campDirtyMsg;
campDirtyMsg = new CampDirtyData (current->Id(), FalconLocalGame, FALSE);
campDirtyMsg->dataBlock.size = static_cast<int>(bufSize);
campDirtyMsg->dataBlock.data = new VU_BYTE[bufSize];
memcpy(campDirtyMsg->dataBlock.data, buffer, bufSize);
if (bucket >= 7){ campDirtyMsg->RequestOutOfBandTransmit(); }
FalconSendMessage(campDirtyMsg, bucket >= 6);
current->ClearDirty();
--toSend;
sent = true;
}
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void FalconEntity::DoSimDirtyData(VU_TIME realTime) {
// only do if initialized
if (!(TheCampaign.Flags & CAMP_LOADED) || (simDirtyBuckets == NULL)){
return;
}
// last time we sent sim dirty data
static VU_TIME lastSent = 0;
if ((realTime - lastSent) < SIMDIRTYDATA_INTERVAL){
return;
}
lastSent = realTime;
//a buffer for encoding decoding stuff (biggest I seen was around 32)
unsigned char buffer[128];
//pointer to the buffer above
unsigned char *bufptr;
// max number of sends to do
// but we send at least one on each bucket
int toSend = 30;
//now we go through all buckets while can send. Send at least one per bucket
for (int bucket = MAX_DIRTY_BUCKETS - 1; (bucket >= 0); bucket --){
bool sent = false;
F4ScopeLock lock(simDirtyMutexes[bucket]);
#if USE_VU_COLL_FOR_DIRTY
FalconEntity *current;
while ((current = static_cast<FalconEntity*>(simDirtyBuckets[bucket]->PopHead())) != NULL)
#else
while (!simDirtyBuckets[bucket]->empty())
#endif
{
//bucket 7 and 8 are OOB (out of band), others must respect limit
if ((bucket < 7) && (toSend < 0) && (sent)){
break;
}
#if !USE_VU_COLL_FOR_DIRTY
// get the entity in FIFO fashion
FalconEntityBin current(simDirtyBuckets[bucket]->front());
simDirtyBuckets[bucket]->pop_front();
#endif
// discard non dirty entities, can happen if it was inserted more than once
if ((current->dirty_classes == 0) || (current->GetDirty() == 0)){
continue;
}
//point to the buffer
bufptr = buffer;
// encode and clear dirtyness to send dirty message
long bufSize = static_cast<long>(current->EncodeDirty(&bufptr));
SimDirtyData *simDirtyData;
simDirtyData = new SimDirtyData(current->Id(), FalconLocalGame, FALSE);
simDirtyData->dataBlock.size = static_cast<int>(bufSize);
simDirtyData->dataBlock.data = new VU_BYTE[bufSize];
memcpy(simDirtyData->dataBlock.data, buffer, bufSize);
if (bucket >= 7){
simDirtyData->RequestOutOfBandTransmit();
}
//send the message
FalconSendMessage(simDirtyData, bucket >= 6);
current->ClearDirty();
toSend--;
sent = true;
}
}
}
int FalconEntity::GetRadarType(void) {
return RDR_NO_RADAR;
}
void FalconEntity::MakeFlagsDirty (void) {
//MakeFalconEntityDirty (DIRTY_FALCON_FLAGS, DDP[148].priority);
MakeFalconEntityDirty (DIRTY_FALCON_FLAGS, SEND_RELIABLEANDOOB);
}
void FalconEntity::MakeFalconEntityDirty (Dirty_Falcon_Entity bits, Dirtyness score) {
if ((!IsLocal()) || (VuState() != VU_MEM_ACTIVE)){
return;
}
dirty_falcent |= bits;
MakeDirty (DIRTY_FALCON_ENTITY, score);
}
#if NEW_REMOVAL_CALLBACK
VU_ERRCODE FalconEntity::RemovalCallback(){
//CleanupData();
return VU_SUCCESS;
}
#endif
/////////////////
// SPOT ENTITY //
/////////////////
SpotEntity::SpotEntity (ushort type) : FalconEntity(type, GetIdFromNamespace(VolatileNS)){
// spotentities are sent oob
SetSendCreate(VuEntity::VU_SC_SEND_OOB);
SetYPRDelta(0,0, 0);
}
SpotEntity::SpotEntity (VU_BYTE ** data, long *rem) : FalconEntity(data, rem){
SetYPRDelta(0,0,0);
}
| 26.158192 | 120 | 0.631246 | [
"vector"
] |
62322d9af7a19b21046639e3a2c18d560f92d901 | 51,735 | cpp | C++ | runtime/device/device.cpp | JustinTArthur/ROCm-OpenCL-Runtime | 3c0e33b125b13cc0b33e935d4ebf610bc3e3a677 | [
"MIT"
] | 1 | 2021-11-11T04:11:32.000Z | 2021-11-11T04:11:32.000Z | runtime/device/device.cpp | JustinTArthur/ROCm-OpenCL-Runtime | 3c0e33b125b13cc0b33e935d4ebf610bc3e3a677 | [
"MIT"
] | null | null | null | runtime/device/device.cpp | JustinTArthur/ROCm-OpenCL-Runtime | 3c0e33b125b13cc0b33e935d4ebf610bc3e3a677 | [
"MIT"
] | 1 | 2021-11-11T04:11:26.000Z | 2021-11-11T04:11:26.000Z | //
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#include "device/device.hpp"
#include "thread/atomic.hpp"
#include "thread/monitor.hpp"
#if defined(WITH_HSA_DEVICE)
#include "device/rocm/rocdevice.hpp"
extern amd::AppProfile* rocCreateAppProfile();
#endif
#if defined(WITH_CPU_DEVICE)
#include "device/cpu/cpudevice.hpp"
#endif // WITH_CPU_DEVICE
#if defined(WITH_PAL_DEVICE)
// namespace pal {
extern bool PalDeviceLoad();
extern void PalDeviceUnload();
//}
#endif // WITH_PAL_DEVICE
#if defined(WITH_GPU_DEVICE)
extern bool DeviceLoad();
extern void DeviceUnload();
#endif // WITH_GPU_DEVICE
#include "platform/runtime.hpp"
#include "platform/program.hpp"
#include "thread/monitor.hpp"
#include "amdocl/cl_common.hpp"
#include "utils/options.hpp"
#include "utils/versions.hpp" // AMD_PLATFORM_INFO
#if defined(HAVE_BLOWFISH_H)
#include "blowfish/oclcrypt.hpp"
#endif
#include "utils/bif_section_labels.hpp"
#include "utils/libUtils.h"
#include "spirv/spirvUtils.h"
#include <vector>
#include <string>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <fstream>
#include <set>
#include <algorithm>
#include <numeric>
namespace device {
extern const char* BlitSourceCode;
}
namespace amd {
std::vector<Device*>* Device::devices_ = NULL;
AppProfile Device::appProfile_;
amd::Monitor SvmManager::AllocatedLock_("Guards SVM allocation list");
std::map<uintptr_t, amd::Memory*> SvmManager::svmBufferMap_;
size_t SvmManager::size() {
amd::ScopedLock lock(AllocatedLock_);
return svmBufferMap_.size();
}
void SvmManager::AddSvmBuffer(const void* k, amd::Memory* v) {
amd::ScopedLock lock(AllocatedLock_);
svmBufferMap_.insert(std::pair<uintptr_t, amd::Memory*>(reinterpret_cast<uintptr_t>(k), v));
}
void SvmManager::RemoveSvmBuffer(const void* k) {
amd::ScopedLock lock(AllocatedLock_);
svmBufferMap_.erase(reinterpret_cast<uintptr_t>(k));
}
amd::Memory* SvmManager::FindSvmBuffer(const void* k) {
amd::ScopedLock lock(AllocatedLock_);
uintptr_t key = reinterpret_cast<uintptr_t>(k);
std::map<uintptr_t, amd::Memory*>::iterator it = svmBufferMap_.upper_bound(key);
if (it == svmBufferMap_.begin()) {
return NULL;
}
--it;
amd::Memory* mem = it->second;
if (key >= it->first && key < (it->first + mem->getSize())) {
// the k is in the range
return mem;
} else {
return NULL;
}
}
Device::BlitProgram::~BlitProgram() {
if (program_ != NULL) {
program_->release();
}
}
bool Device::BlitProgram::create(amd::Device* device, const char* extraKernels,
const char* extraOptions) {
std::vector<amd::Device*> devices;
devices.push_back(device);
std::string kernels(device::BlitSourceCode);
if (extraKernels != NULL) {
kernels += extraKernels;
}
// Create a program with all blit kernels
program_ = new Program(*context_, kernels.c_str());
if (program_ == NULL) {
return false;
}
// Build all kernels
std::string opt =
"-cl-internal-kernel "
#if !defined(WITH_LIGHTNING_COMPILER)
"-Wf,--force_disable_spir -fno-lib-no-inline "
"-fno-sc-keep-calls "
#endif // !defined(WITH_LIGHTNING_COMPILER)
;
if (extraOptions != NULL) {
opt += extraOptions;
}
if (!GPU_DUMP_BLIT_KERNELS) {
opt += " -fno-enable-dump";
}
if (CL_SUCCESS != program_->build(devices, opt.c_str(), NULL, NULL, GPU_DUMP_BLIT_KERNELS)) {
return false;
}
return true;
}
bool Device::init() {
assert(!Runtime::initialized() && "initialize only once");
bool ret = false;
devices_ = NULL;
appProfile_.init();
// IMPORTANT: Note that we are initialiing HSA stack first and then
// GPU stack. The order of initialization is signiicant and if changed
// amd::Device::registerDevice() must be accordingly modified.
#if defined(WITH_HSA_DEVICE)
// Return value of roc::Device::init()
// If returned false, error initializing HSA stack.
// If returned true, either HSA not installed or HSA stack
// successfully initialized.
if (!roc::Device::init()) {
// abort() commentted because this is the only indication
// that KFD is not installed.
// Ignore the failure and assume KFD is not installed.
// abort();
}
ret |= roc::NullDevice::init();
#endif // WITH_HSA_DEVICE
#if defined(WITH_GPU_DEVICE)
if (GPU_ENABLE_PAL != 1) {
ret |= DeviceLoad();
}
#endif // WITH_GPU_DEVICE
#if defined(WITH_PAL_DEVICE)
if (GPU_ENABLE_PAL != 0) {
ret |= PalDeviceLoad();
}
#endif // WITH_PAL_DEVICE
#if defined(WITH_CPU_DEVICE)
ret |= cpu::Device::init();
#endif // WITH_CPU_DEVICE
return ret;
}
void Device::tearDown() {
if (devices_ != NULL) {
for (uint i = 0; i < devices_->size(); ++i) {
delete devices_->at(i);
}
devices_->clear();
delete devices_;
}
#if defined(WITH_HSA_DEVICE)
roc::Device::tearDown();
#endif // WITH_HSA_DEVICE
#if defined(WITH_GPU_DEVICE)
if (GPU_ENABLE_PAL != 1) {
DeviceUnload();
}
#endif // WITH_GPU_DEVICE
#if defined(WITH_PAL_DEVICE)
if (GPU_ENABLE_PAL != 0) {
PalDeviceUnload();
}
#endif // WITH_PAL_DEVICE
#if defined(WITH_CPU_DEVICE)
cpu::Device::tearDown();
#endif // WITH_CPU_DEVICE
}
Device::Device(Device* parent)
: settings_(NULL),
online_(true),
blitProgram_(NULL),
hwDebugMgr_(NULL),
parent_(parent),
vaCacheAccess_(nullptr),
vaCacheMap_(nullptr) {
memset(&info_, '\0', sizeof(info_));
if (parent_ != NULL) {
parent_->retain();
}
}
Device::~Device() {
CondLog((vaCacheMap_ != nullptr) && (vaCacheMap_->size() != 0),
"Application didn't unmap all host memory!");
delete vaCacheMap_;
delete vaCacheAccess_;
// Destroy device settings
if (settings_ != NULL) {
delete settings_;
}
if (parent_ != NULL) {
parent_->release();
} else {
if (info_.extensions_ != NULL) {
delete[] info_.extensions_;
}
}
if (info_.partitionCreateInfo_.type_.byCounts_ &&
info_.partitionCreateInfo_.byCounts_.countsList_ != NULL) {
delete[] info_.partitionCreateInfo_.byCounts_.countsList_;
}
}
bool Device::create() {
vaCacheAccess_ = new amd::Monitor("VA Cache Ops Lock", true);
if (NULL == vaCacheAccess_) {
return false;
}
vaCacheMap_ = new std::map<uintptr_t, device::Memory*>();
if (NULL == vaCacheMap_) {
return false;
}
return true;
}
bool Device::isAncestor(const Device* sub) const {
for (const Device* d = sub->parent_; d != NULL; d = d->parent_) {
if (d == this) {
return true;
}
}
return false;
}
void Device::registerDevice() {
assert(Runtime::singleThreaded() && "this is not thread-safe");
static bool defaultIsAssigned = false;
if (devices_ == NULL) {
devices_ = new std::vector<Device*>;
}
if (info_.available_) {
if (!defaultIsAssigned) {
defaultIsAssigned = true;
info_.type_ |= CL_DEVICE_TYPE_DEFAULT;
}
}
devices_->push_back(this);
}
void Device::addVACache(device::Memory* memory) const {
// Make sure system memory has direct access
if (memory->isHostMemDirectAccess()) {
// VA cache access must be serialised
amd::ScopedLock lk(*vaCacheAccess_);
void* start = memory->owner()->getHostMem();
size_t offset;
device::Memory* doubleMap = findMemoryFromVA(start, &offset);
if (doubleMap == nullptr) {
// Insert the new entry
vaCacheMap_->insert(
std::pair<uintptr_t, device::Memory*>(reinterpret_cast<uintptr_t>(start), memory));
} else {
LogError("Unexpected double map() call from the app!");
}
}
}
void Device::removeVACache(const device::Memory* memory) const {
// Make sure system memory has direct access
if (memory->isHostMemDirectAccess() && memory->owner()) {
// VA cache access must be serialised
amd::ScopedLock lk(*vaCacheAccess_);
void* start = memory->owner()->getHostMem();
vaCacheMap_->erase(reinterpret_cast<uintptr_t>(start));
}
}
device::Memory* Device::findMemoryFromVA(const void* ptr, size_t* offset) const {
// VA cache access must be serialised
amd::ScopedLock lk(*vaCacheAccess_);
uintptr_t key = reinterpret_cast<uintptr_t>(ptr);
std::map<uintptr_t, device::Memory*>::iterator it =
vaCacheMap_->upper_bound(reinterpret_cast<uintptr_t>(ptr));
if (it == vaCacheMap_->begin()) {
return nullptr;
}
--it;
device::Memory* mem = it->second;
if (key >= it->first && key < (it->first + mem->size())) {
// ptr is in the range
*offset = key - it->first;
return mem;
}
return nullptr;
}
bool Device::IsTypeMatching(cl_device_type type, bool offlineDevices) {
if (!(isOnline() || offlineDevices)) {
return false;
}
return (info_.type_ & type) != 0;
}
std::vector<Device*> Device::getDevices(cl_device_type type, bool offlineDevices) {
std::vector<Device*> result;
if (devices_ == NULL) {
return result;
}
// Create the list of available devices
for (device_iterator it = devices_->begin(); it != devices_->end(); ++it) {
// Check if the device type is matched
if ((*it)->IsTypeMatching(type, offlineDevices)) {
result.push_back(*it);
}
}
return result;
}
size_t Device::numDevices(cl_device_type type, bool offlineDevices) {
size_t result = 0;
if (devices_ == NULL) {
return 0;
}
for (device_iterator it = devices_->begin(); it != devices_->end(); ++it) {
// Check if the device type is matched
if ((*it)->IsTypeMatching(type, offlineDevices)) {
++result;
}
}
return result;
}
bool Device::getDeviceIDs(cl_device_type deviceType, cl_uint numEntries, cl_device_id* devices,
cl_uint* numDevices, bool offlineDevices) {
if (numDevices != NULL && devices == NULL) {
*numDevices = (cl_uint)amd::Device::numDevices(deviceType, offlineDevices);
return (*numDevices > 0) ? true : false;
}
assert(devices != NULL && "check the code above");
std::vector<amd::Device*> ret = amd::Device::getDevices(deviceType, offlineDevices);
if (ret.size() == 0) {
*not_null(numDevices) = 0;
return false;
}
std::vector<amd::Device*>::iterator it = ret.begin();
cl_uint count = std::min(numEntries, (cl_uint)ret.size());
while (count--) {
*devices++ = as_cl(*it++);
--numEntries;
}
while (numEntries--) {
*devices++ = (cl_device_id)0;
}
*not_null(numDevices) = (cl_uint)ret.size();
return true;
}
char* Device::getExtensionString() {
std::stringstream extStream;
size_t size;
char* result = NULL;
// Generate the extension string
for (uint i = 0; i < ClExtTotal; ++i) {
if (settings().checkExtension(i)) {
extStream << OclExtensionsString[i];
}
}
size = extStream.str().size() + 1;
// Create a single string with all extensions
result = new char[size];
if (result != NULL) {
memcpy(result, extStream.str().data(), (size - 1));
result[size - 1] = 0;
}
return result;
}
void* Device::allocMapTarget(amd::Memory& mem, const amd::Coord3D& origin,
const amd::Coord3D& region, uint mapFlags, size_t* rowPitch,
size_t* slicePitch) {
// Translate memory references
device::Memory* devMem = mem.getDeviceMemory(*this);
if (devMem == NULL) {
LogError("allocMapTarget failed. Can't allocate video memory");
return NULL;
}
// Pass request over to memory
return devMem->allocMapTarget(origin, region, mapFlags, rowPitch, slicePitch);
}
#if defined(WITH_LIGHTNING_COMPILER)
CacheCompilation::CacheCompilation(std::string targetStr, std::string postfix, bool enableCache,
bool resetCache)
: codeCache_(targetStr, 0, AMD_PLATFORM_BUILD_NUMBER, postfix),
isCodeCacheEnabled_(enableCache) {
if (resetCache) {
// clean up the cached data of the target device
StringCache emptyCache(targetStr, 0, 0, postfix);
}
}
bool CacheCompilation::linkLLVMBitcode(amd::opencl_driver::Compiler* C,
std::vector<amd::opencl_driver::Data*>& inputs,
amd::opencl_driver::Buffer* output,
std::vector<std::string>& options, std::string& buildLog) {
std::string cacheOpt;
cacheOpt = std::accumulate(begin(options), end(options), cacheOpt);
bool ret = false;
bool cachedCodeExist = false;
std::vector<StringCache::CachedData> bcSet;
if (isCodeCacheEnabled_) {
using namespace amd::opencl_driver;
for (auto& input : inputs) {
assert(input->Type() == DT_LLVM_BC);
BufferReference* bc = reinterpret_cast<BufferReference*>(input);
StringCache::CachedData cachedData = {bc->Ptr(), bc->Size()};
bcSet.push_back(cachedData);
}
std::string dstData = "";
if (codeCache_.getCacheEntry(isCodeCacheEnabled_, bcSet.data(), bcSet.size(), cacheOpt, dstData,
"Link LLVM Bitcodes")) {
std::copy(dstData.begin(), dstData.end(), std::back_inserter(output->Buf()));
cachedCodeExist = true;
}
}
if (!cachedCodeExist) {
if (!C->LinkLLVMBitcode(inputs, output, options)) {
return false;
}
if (isCodeCacheEnabled_) {
std::string dstData(output->Buf().data(), output->Buf().size());
if (!codeCache_.makeCacheEntry(bcSet.data(), bcSet.size(), cacheOpt, dstData)) {
buildLog += "Warning: Failed to caching codes.\n";
LogWarning("Caching codes failed!");
}
}
}
return true;
}
bool CacheCompilation::compileToLLVMBitcode(amd::opencl_driver::Compiler* C,
std::vector<amd::opencl_driver::Data*>& inputs,
amd::opencl_driver::Buffer* output,
std::vector<std::string>& options,
std::string& buildLog) {
std::string cacheOpt;
for (uint i = 0; i < options.size(); i++) {
// skip the header file option, which is associated with the -cl-std=<CLstd> option
if (options[i].compare("-include-pch") == 0) {
i++;
continue;
}
cacheOpt += options[i];
}
bool ret = false;
bool cachedCodeExist = false;
std::vector<StringCache::CachedData> bcSet;
if (isCodeCacheEnabled_) {
using namespace amd::opencl_driver;
bool checkCache = true;
for (auto& input : inputs) {
if (input->Type() == DT_CL) {
BufferReference* bc = reinterpret_cast<BufferReference*>(input);
StringCache::CachedData cachedData = {bc->Ptr(), bc->Size()};
bcSet.push_back(cachedData);
} else if (input->Type() == DT_CL_HEADER) {
FileReference* bcFile = reinterpret_cast<FileReference*>(input);
std::string bc;
bcFile->ReadToString(bc);
StringCache::CachedData cachedData = {bc.c_str(), bc.size()};
bcSet.push_back(cachedData);
} else {
buildLog += "Error: unsupported bitcode type for checking cache.\n";
checkCache = false;
break;
}
}
std::string dstData = "";
if (checkCache &&
codeCache_.getCacheEntry(isCodeCacheEnabled_, bcSet.data(), bcSet.size(), cacheOpt, dstData,
"Compile to LLVM Bitcodes")) {
std::copy(dstData.begin(), dstData.end(), std::back_inserter(output->Buf()));
cachedCodeExist = true;
}
}
if (!cachedCodeExist) {
if (!C->CompileToLLVMBitcode(inputs, output, options)) {
return false;
}
if (isCodeCacheEnabled_) {
std::string dstData(output->Buf().data(), output->Buf().size());
if (!codeCache_.makeCacheEntry(bcSet.data(), bcSet.size(), cacheOpt, dstData)) {
buildLog += "Warning: Failed to caching codes.\n";
LogWarning("Caching codes failed!");
}
}
}
return true;
}
bool CacheCompilation::compileAndLinkExecutable(amd::opencl_driver::Compiler* C,
std::vector<amd::opencl_driver::Data*>& inputs,
amd::opencl_driver::Buffer* output,
std::vector<std::string>& options,
std::string& buildLog) {
std::string cacheOpt;
cacheOpt = std::accumulate(begin(options), end(options), cacheOpt);
bool ret = false;
bool cachedCodeExist = false;
std::vector<StringCache::CachedData> bcSet;
if (isCodeCacheEnabled_) {
for (auto& input : inputs) {
assert(input->Type() == amd::opencl_driver::DT_LLVM_BC);
amd::opencl_driver::Buffer* bc = (amd::opencl_driver::Buffer*)input;
StringCache::CachedData cachedData = {bc->Buf().data(), bc->Size()};
bcSet.push_back(cachedData);
}
std::string dstData = "";
if (codeCache_.getCacheEntry(isCodeCacheEnabled_, bcSet.data(), bcSet.size(), cacheOpt, dstData,
"Compile and Link Executable")) {
std::copy(dstData.begin(), dstData.end(), std::back_inserter(output->Buf()));
cachedCodeExist = true;
}
}
if (!cachedCodeExist) {
if (!C->CompileAndLinkExecutable(inputs, output, options)) {
return false;
}
if (isCodeCacheEnabled_) {
std::string dstData(output->Buf().data(), output->Buf().size());
if (!codeCache_.makeCacheEntry(bcSet.data(), bcSet.size(), cacheOpt, dstData)) {
buildLog += "Warning: Failed to caching codes.\n";
LogWarning("Caching codes failed!");
}
}
}
return true;
}
#endif
} // namespace amd
namespace device {
Settings::Settings() {
assert((ClExtTotal < (8 * sizeof(extensions_))) && "Too many extensions!");
extensions_ = 0;
partialDispatch_ = false;
supportRA_ = true;
customHostAllocator_ = false;
waitCommand_ = AMD_OCL_WAIT_COMMAND;
supportDepthsRGB_ = false;
enableHwDebug_ = false;
commandQueues_ = 200; //!< Field value set to maximum number
//!< concurrent Virtual GPUs for default
}
bool Kernel::createSignature(const parameters_t& params) {
std::stringstream attribs;
if (workGroupInfo_.compileSize_[0] != 0) {
attribs << "reqd_work_group_size(";
for (size_t i = 0; i < 3; ++i) {
if (i != 0) {
attribs << ",";
}
attribs << workGroupInfo_.compileSize_[i];
}
attribs << ")";
}
if (workGroupInfo_.compileSizeHint_[0] != 0) {
attribs << " work_group_size_hint(";
for (size_t i = 0; i < 3; ++i) {
if (i != 0) {
attribs << ",";
}
attribs << workGroupInfo_.compileSizeHint_[i];
}
attribs << ")";
}
if (!workGroupInfo_.compileVecTypeHint_.empty()) {
attribs << " vec_type_hint(" << workGroupInfo_.compileVecTypeHint_ << ")";
}
// Destroy old signature if it was allocated before
// (offline devices path)
delete signature_;
signature_ = new amd::KernelSignature(params, attribs.str());
if (NULL != signature_) {
return true;
}
return false;
}
Kernel::~Kernel() { delete signature_; }
std::string Kernel::openclMangledName(const std::string& name) {
const oclBIFSymbolStruct* bifSym = findBIF30SymStruct(symOpenclKernel);
assert(bifSym && "symbol not found");
return std::string("&") + bifSym->str[bif::PRE] + name + bifSym->str[bif::POST];
}
void Memory::saveMapInfo(const void* mapAddress, const amd::Coord3D origin,
const amd::Coord3D region, uint mapFlags, bool entire,
amd::Image* baseMip) {
// Map/Unmap must be serialized.
amd::ScopedLock lock(owner()->lockMemoryOps());
WriteMapInfo info = {};
WriteMapInfo* pInfo = &info;
auto it = writeMapInfo_.find(mapAddress);
if (it != writeMapInfo_.end()) {
LogWarning("Double map of the same or overlapped region!");
pInfo = &it->second;
}
if (mapFlags & (CL_MAP_WRITE | CL_MAP_WRITE_INVALIDATE_REGION)) {
pInfo->origin_ = origin;
pInfo->region_ = region;
pInfo->entire_ = entire;
pInfo->unmapWrite_ = true;
}
if (mapFlags & CL_MAP_READ) {
pInfo->unmapRead_ = true;
}
pInfo->baseMip_ = baseMip;
// Insert into the map if it's the first region
if (++pInfo->count_ == 1) {
writeMapInfo_.insert(std::pair<const void*, WriteMapInfo>(mapAddress, info));
}
}
Program::Program(amd::Device& device)
: device_(device),
type_(TYPE_NONE),
clBinary_(NULL),
llvmBinary_(),
elfSectionType_(amd::OclElf::LLVMIR),
compileOptions_(),
linkOptions_(),
lastBuildOptionsArg_(),
buildStatus_(CL_BUILD_NONE),
buildError_(CL_SUCCESS),
globalVariableTotalSize_(0),
programOptions(NULL) {}
Program::~Program() { clear(); }
void Program::clear() {
// Destroy all device kernels
kernels_t::const_iterator it;
for (it = kernels_.begin(); it != kernels_.end(); ++it) {
delete it->second;
}
kernels_.clear();
}
bool Program::initBuild(amd::option::Options* options) {
programOptions = options;
if (options->oVariables->DumpFlags > 0) {
static amd::Atomic<unsigned> build_num = 0;
options->setBuildNo(build_num++);
}
buildLog_.clear();
if (!initClBinary()) {
return false;
}
return true;
}
bool Program::finiBuild(bool isBuildGood) { return true; }
cl_int Program::compile(const std::string& sourceCode,
const std::vector<const std::string*>& headers,
const char** headerIncludeNames, const char* origOptions,
amd::option::Options* options) {
uint64_t start_time = 0;
if (options->oVariables->EnableBuildTiming) {
buildLog_ = "\nStart timing major build components.....\n\n";
start_time = amd::Os::timeNanos();
}
lastBuildOptionsArg_ = origOptions ? origOptions : "";
if (options) {
compileOptions_ = options->origOptionStr;
}
buildStatus_ = CL_BUILD_IN_PROGRESS;
if (!initBuild(options)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation init failed.";
}
}
if (options->oVariables->FP32RoundDivideSqrt &&
!(device().info().singleFPConfig_ & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT)) {
buildStatus_ = CL_BUILD_ERROR;
buildLog_ +=
"Error: -cl-fp32-correctly-rounded-divide-sqrt "
"specified without device support";
}
// Compile the source code if any
if ((buildStatus_ == CL_BUILD_IN_PROGRESS) && !sourceCode.empty() &&
!compileImpl(sourceCode, headers, headerIncludeNames, options)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation failed.";
}
}
setType(TYPE_COMPILED);
if ((buildStatus_ == CL_BUILD_IN_PROGRESS) && !createBinary(options)) {
buildLog_ += "Internal Error: creating OpenCL binary failed!\n";
}
if (!finiBuild(buildStatus_ == CL_BUILD_IN_PROGRESS)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation fini failed.";
}
}
if (buildStatus_ == CL_BUILD_IN_PROGRESS) {
buildStatus_ = CL_BUILD_SUCCESS;
} else {
buildError_ = CL_COMPILE_PROGRAM_FAILURE;
}
if (options->oVariables->EnableBuildTiming) {
std::stringstream tmp_ss;
tmp_ss << "\nTotal Compile Time: " << (amd::Os::timeNanos() - start_time) / 1000ULL << " us\n";
buildLog_ += tmp_ss.str();
}
if (options->oVariables->BuildLog && !buildLog_.empty()) {
if (strcmp(options->oVariables->BuildLog, "stderr") == 0) {
fprintf(stderr, "%s\n", options->optionsLog().c_str());
fprintf(stderr, "%s\n", buildLog_.c_str());
} else if (strcmp(options->oVariables->BuildLog, "stdout") == 0) {
printf("%s\n", options->optionsLog().c_str());
printf("%s\n", buildLog_.c_str());
} else {
std::fstream f;
std::stringstream tmp_ss;
std::string logs = options->optionsLog() + buildLog_;
tmp_ss << options->oVariables->BuildLog << "." << options->getBuildNo();
f.open(tmp_ss.str().c_str(), (std::fstream::out | std::fstream::binary));
f.write(logs.data(), logs.size());
f.close();
}
LogError(buildLog_.c_str());
}
return buildError();
}
cl_int Program::link(const std::vector<Program*>& inputPrograms, const char* origLinkOptions,
amd::option::Options* linkOptions) {
lastBuildOptionsArg_ = origLinkOptions ? origLinkOptions : "";
if (linkOptions) {
linkOptions_ = linkOptions->origOptionStr;
}
buildStatus_ = CL_BUILD_IN_PROGRESS;
amd::option::Options options;
if (!getCompileOptionsAtLinking(inputPrograms, linkOptions)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ += "Internal error: Get compile options failed.";
}
} else {
if (!amd::option::parseAllOptions(compileOptions_, options)) {
buildStatus_ = CL_BUILD_ERROR;
buildLog_ += options.optionsLog();
LogError("Parsing compile options failed.");
}
}
uint64_t start_time = 0;
if (options.oVariables->EnableBuildTiming) {
buildLog_ = "\nStart timing major build components.....\n\n";
start_time = amd::Os::timeNanos();
}
// initBuild() will clear buildLog_, so store it in a temporary variable
std::string tmpBuildLog = buildLog_;
if ((buildStatus_ == CL_BUILD_IN_PROGRESS) && !initBuild(&options)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ += "Internal error: Compilation init failed.";
}
}
buildLog_ += tmpBuildLog;
if (options.oVariables->FP32RoundDivideSqrt &&
!(device().info().singleFPConfig_ & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT)) {
buildStatus_ = CL_BUILD_ERROR;
buildLog_ +=
"Error: -cl-fp32-correctly-rounded-divide-sqrt "
"specified without device support";
}
bool createLibrary = linkOptions ? linkOptions->oVariables->clCreateLibrary : false;
if ((buildStatus_ == CL_BUILD_IN_PROGRESS) && !linkImpl(inputPrograms, &options, createLibrary)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ += "Internal error: Link failed.\n";
buildLog_ += "Make sure the system setup is correct.";
}
}
if (!finiBuild(buildStatus_ == CL_BUILD_IN_PROGRESS)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation fini failed.";
}
}
if (buildStatus_ == CL_BUILD_IN_PROGRESS) {
buildStatus_ = CL_BUILD_SUCCESS;
} else {
buildError_ = CL_LINK_PROGRAM_FAILURE;
}
if (options.oVariables->EnableBuildTiming) {
std::stringstream tmp_ss;
tmp_ss << "\nTotal Link Time: " << (amd::Os::timeNanos() - start_time) / 1000ULL << " us\n";
buildLog_ += tmp_ss.str();
}
if (options.oVariables->BuildLog && !buildLog_.empty()) {
if (strcmp(options.oVariables->BuildLog, "stderr") == 0) {
fprintf(stderr, "%s\n", options.optionsLog().c_str());
fprintf(stderr, "%s\n", buildLog_.c_str());
} else if (strcmp(options.oVariables->BuildLog, "stdout") == 0) {
printf("%s\n", options.optionsLog().c_str());
printf("%s\n", buildLog_.c_str());
} else {
std::fstream f;
std::stringstream tmp_ss;
std::string logs = options.optionsLog() + buildLog_;
tmp_ss << options.oVariables->BuildLog << "." << options.getBuildNo();
f.open(tmp_ss.str().c_str(), (std::fstream::out | std::fstream::binary));
f.write(logs.data(), logs.size());
f.close();
}
}
if (!buildLog_.empty()) {
LogError(buildLog_.c_str());
}
return buildError();
}
cl_int Program::build(const std::string& sourceCode, const char* origOptions,
amd::option::Options* options) {
uint64_t start_time = 0;
if (options->oVariables->EnableBuildTiming) {
buildLog_ = "\nStart timing major build components.....\n\n";
start_time = amd::Os::timeNanos();
}
lastBuildOptionsArg_ = origOptions ? origOptions : "";
if (options) {
compileOptions_ = options->origOptionStr;
}
buildStatus_ = CL_BUILD_IN_PROGRESS;
if (!initBuild(options)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation init failed.";
}
}
if (options->oVariables->FP32RoundDivideSqrt &&
!(device().info().singleFPConfig_ & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT)) {
buildStatus_ = CL_BUILD_ERROR;
buildLog_ +=
"Error: -cl-fp32-correctly-rounded-divide-sqrt "
"specified without device support";
}
// Compile the source code if any
std::vector<const std::string*> headers;
if ((buildStatus_ == CL_BUILD_IN_PROGRESS) && !sourceCode.empty() &&
!compileImpl(sourceCode, headers, NULL, options)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation failed.";
}
}
if ((buildStatus_ == CL_BUILD_IN_PROGRESS) && !linkImpl(options)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ += "Internal error: Link failed.\n";
buildLog_ += "Make sure the system setup is correct.";
}
}
if (!finiBuild(buildStatus_ == CL_BUILD_IN_PROGRESS)) {
buildStatus_ = CL_BUILD_ERROR;
if (buildLog_.empty()) {
buildLog_ = "Internal error: Compilation fini failed.";
}
}
if (buildStatus_ == CL_BUILD_IN_PROGRESS) {
buildStatus_ = CL_BUILD_SUCCESS;
} else {
buildError_ = CL_BUILD_PROGRAM_FAILURE;
}
if (options->oVariables->EnableBuildTiming) {
std::stringstream tmp_ss;
tmp_ss << "\nTotal Build Time: " << (amd::Os::timeNanos() - start_time) / 1000ULL << " us\n";
buildLog_ += tmp_ss.str();
}
if (options->oVariables->BuildLog && !buildLog_.empty()) {
if (strcmp(options->oVariables->BuildLog, "stderr") == 0) {
fprintf(stderr, "%s\n", options->optionsLog().c_str());
fprintf(stderr, "%s\n", buildLog_.c_str());
} else if (strcmp(options->oVariables->BuildLog, "stdout") == 0) {
printf("%s\n", options->optionsLog().c_str());
printf("%s\n", buildLog_.c_str());
} else {
std::fstream f;
std::stringstream tmp_ss;
std::string logs = options->optionsLog() + buildLog_;
tmp_ss << options->oVariables->BuildLog << "." << options->getBuildNo();
f.open(tmp_ss.str().c_str(), (std::fstream::out | std::fstream::binary));
f.write(logs.data(), logs.size());
f.close();
}
}
if (!buildLog_.empty()) {
LogError(buildLog_.c_str());
}
return buildError();
}
bool Program::getCompileOptionsAtLinking(const std::vector<Program*>& inputPrograms,
const amd::option::Options* linkOptions) {
amd::option::Options compileOptions;
std::vector<device::Program*>::const_iterator it = inputPrograms.begin();
std::vector<device::Program*>::const_iterator itEnd = inputPrograms.end();
for (size_t i = 0; it != itEnd; ++it, ++i) {
Program* program = *it;
amd::option::Options compileOptions2;
amd::option::Options* thisCompileOptions = i == 0 ? &compileOptions : &compileOptions2;
if (!amd::option::parseAllOptions(program->compileOptions_, *thisCompileOptions)) {
buildLog_ += thisCompileOptions->optionsLog();
LogError("Parsing compile options failed.");
return false;
}
if (i == 0) compileOptions_ = program->compileOptions_;
// if we are linking a program executable, and if "program" is a
// compiled module or a library created with "-enable-link-options",
// we can overwrite "program"'s compile options with linking options
if (!linkOptions_.empty() && !linkOptions->oVariables->clCreateLibrary) {
bool linkOptsCanOverwrite = false;
if (program->type() != TYPE_LIBRARY) {
linkOptsCanOverwrite = true;
} else {
amd::option::Options thisLinkOptions;
if (!amd::option::parseLinkOptions(program->linkOptions_, thisLinkOptions)) {
buildLog_ += thisLinkOptions.optionsLog();
LogError("Parsing link options failed.");
return false;
}
if (thisLinkOptions.oVariables->clEnableLinkOptions) linkOptsCanOverwrite = true;
}
if (linkOptsCanOverwrite) {
if (!thisCompileOptions->setOptionVariablesAs(*linkOptions)) {
buildLog_ += thisCompileOptions->optionsLog();
LogError("Setting link options failed.");
return false;
}
}
if (i == 0) compileOptions_ += " " + linkOptions_;
}
// warn if input modules have inconsistent compile options
if (i > 0) {
if (!compileOptions.equals(*thisCompileOptions, true /*ignore clc options*/)) {
buildLog_ +=
"Warning: Input OpenCL binaries has inconsistent"
" compile options. Using compile options from"
" the first input binary!\n";
}
}
}
return true;
}
bool Program::initClBinary(char* binaryIn, size_t size) {
if (!initClBinary()) {
return false;
}
// Save the original binary that isn't owned by ClBinary
clBinary()->saveOrigBinary(binaryIn, size);
char* bin = binaryIn;
size_t sz = size;
// unencrypted
int encryptCode = 0;
char* decryptedBin = NULL;
#if !defined(WITH_LIGHTNING_COMPILER)
bool isSPIRV = isSPIRVMagic(binaryIn, size);
if (isSPIRV || isBcMagic(binaryIn)) {
acl_error err = ACL_SUCCESS;
aclBinaryOptions binOpts = {0};
binOpts.struct_size = sizeof(binOpts);
binOpts.elfclass =
(info().arch_id == aclX64 || info().arch_id == aclAMDIL64 || info().arch_id == aclHSAIL64)
? ELFCLASS64
: ELFCLASS32;
binOpts.bitness = ELFDATA2LSB;
binOpts.alloc = &::malloc;
binOpts.dealloc = &::free;
aclBinary* aclbin_v30 = aclBinaryInit(sizeof(aclBinary), &info(), &binOpts, &err);
if (err != ACL_SUCCESS) {
LogWarning("aclBinaryInit failed");
aclBinaryFini(aclbin_v30);
return false;
}
err = aclInsertSection(device().compiler(), aclbin_v30, binaryIn, size,
isSPIRV ? aclSPIRV : aclSPIR);
if (ACL_SUCCESS != err) {
LogWarning("aclInsertSection failed");
aclBinaryFini(aclbin_v30);
return false;
}
if (info().arch_id == aclHSAIL || info().arch_id == aclHSAIL64) {
err = aclWriteToMem(aclbin_v30, reinterpret_cast<void**>(&bin), &sz);
if (err != ACL_SUCCESS) {
LogWarning("aclWriteToMem failed");
aclBinaryFini(aclbin_v30);
return false;
}
aclBinaryFini(aclbin_v30);
} else {
aclBinary* aclbin_v21 = aclCreateFromBinary(aclbin_v30, aclBIFVersion21);
err = aclWriteToMem(aclbin_v21, reinterpret_cast<void**>(&bin), &sz);
if (err != ACL_SUCCESS) {
LogWarning("aclWriteToMem failed");
aclBinaryFini(aclbin_v30);
aclBinaryFini(aclbin_v21);
return false;
}
aclBinaryFini(aclbin_v30);
aclBinaryFini(aclbin_v21);
}
} else
#endif // defined(WITH_LIGHTNING_COMPILER)
{
size_t decryptedSize;
if (!clBinary()->decryptElf(binaryIn, size, &decryptedBin, &decryptedSize, &encryptCode)) {
return false;
}
if (decryptedBin != NULL) {
// It is decrypted binary.
bin = decryptedBin;
sz = decryptedSize;
}
if (!isElf(bin)) {
// Invalid binary.
if (decryptedBin != NULL) {
delete[] decryptedBin;
}
return false;
}
}
clBinary()->setFlags(encryptCode);
return clBinary()->setBinary(bin, sz, (decryptedBin != NULL));
}
bool Program::setBinary(char* binaryIn, size_t size) {
if (!initClBinary(binaryIn, size)) {
return false;
}
#if defined(WITH_LIGHTNING_COMPILER)
if (!clBinary()->setElfIn(ELFCLASS64)) {
#else // !defined(WITH_LIGHTNING_COMPILER)
if (!clBinary()->setElfIn(ELFCLASS32)) {
#endif // !defined(WITH_LIGHTNING_COMPILER)
LogError("Setting input OCL binary failed");
return false;
}
uint16_t type;
if (!clBinary()->elfIn()->getType(type)) {
LogError("Bad OCL Binary: error loading ELF type!");
return false;
}
switch (type) {
case ET_NONE: {
setType(TYPE_NONE);
break;
}
case ET_REL: {
if (clBinary()->isSPIR() || clBinary()->isSPIRV()) {
setType(TYPE_INTERMEDIATE);
} else {
setType(TYPE_COMPILED);
}
break;
}
case ET_DYN: {
setType(TYPE_LIBRARY);
break;
}
case ET_EXEC: {
setType(TYPE_EXECUTABLE);
break;
}
default:
LogError("Bad OCL Binary: bad ELF type!");
return false;
}
clBinary()->loadCompileOptions(compileOptions_);
clBinary()->loadLinkOptions(linkOptions_);
#if defined(WITH_LIGHTNING_COMPILER)
// TODO: Remove this once BIF is no longer used as we should have a machinasm in
// place to get the binary type correctly from above.
// It is a workaround for executable build from the library. The code object
// binary does not have the type information.
char* sect = NULL;
size_t sz = 0;
if (clBinary()->elfIn()->getSection(amd::OclElf::TEXT, §, &sz) && sect && sz > 0) {
setType(TYPE_EXECUTABLE);
}
sect = NULL;
sz = 0;
if (type != ET_DYN && // binary is not a library
(clBinary()->elfIn()->getSection(amd::OclElf::LLVMIR, §, &sz) && sect && sz > 0)) {
setType(TYPE_COMPILED);
}
#endif
clBinary()->resetElfIn();
return true;
}
bool Program::createBIFBinary(aclBinary* bin) {
#if defined(WITH_LIGHTNING_COMPILER)
assert(!"createBIFBinary() should not be called when using LC");
return false;
#else // defined(WITH_LIGHTNING_COMPILER)
acl_error err;
char* binaryIn = NULL;
size_t size;
err = aclWriteToMem(bin, reinterpret_cast<void**>(&binaryIn), &size);
if (err != ACL_SUCCESS) {
LogWarning("aclWriteToMem failed");
return false;
}
clBinary()->saveBIFBinary(binaryIn, size);
aclFreeMem(bin, binaryIn);
return true;
#endif // defined(WITH_LIGHTNING_COMPILER)
}
ClBinary::ClBinary(const amd::Device& dev, BinaryImageFormat bifVer)
: dev_(dev),
binary_(NULL),
size_(0),
flags_(0),
origBinary_(NULL),
origSize_(0),
encryptCode_(0),
elfIn_(NULL),
elfOut_(NULL),
format_(bifVer) {}
ClBinary::~ClBinary() {
release();
if (elfIn_) {
delete elfIn_;
}
if (elfOut_) {
delete elfOut_;
}
}
std::string ClBinary::getBIFSymbol(unsigned int symbolID) const {
size_t nSymbols = 0;
// Due to PRE & POST defines in bif_section_labels.hpp conflict with
// PRE & POST struct members in sp3-si-chip-registers.h
// unable to include bif_section_labels.hpp in device.hpp
//! @todo: resolve conflict by renaming defines,
// then include bif_section_labels.hpp in device.hpp &
// use oclBIFSymbolID instead of unsigned int as a parameter
const oclBIFSymbolID symID = static_cast<oclBIFSymbolID>(symbolID);
switch (format_) {
case BIF_VERSION2: {
nSymbols = sizeof(BIF20) / sizeof(oclBIFSymbolStruct);
const oclBIFSymbolStruct* symb = findBIFSymbolStruct(BIF20, nSymbols, symID);
assert(symb && "BIF20 symbol with symbolID not found");
if (symb) {
return std::string(symb->str[bif::PRE]) + std::string(symb->str[bif::POST]);
}
break;
}
case BIF_VERSION3: {
nSymbols = sizeof(BIF30) / sizeof(oclBIFSymbolStruct);
const oclBIFSymbolStruct* symb = findBIFSymbolStruct(BIF30, nSymbols, symID);
assert(symb && "BIF30 symbol with symbolID not found");
if (symb) {
return std::string(symb->str[bif::PRE]) + std::string(symb->str[bif::POST]);
}
break;
}
default:
assert(0 && "unexpected BIF type");
return "";
}
return "";
}
void ClBinary::init(amd::option::Options* optionsObj, bool amdilRequired) {
// option has higher priority than environment variable.
if ((flags_ & BinarySourceMask) != BinaryRemoveSource) {
// set to zero
flags_ = (flags_ & (~BinarySourceMask));
flags_ |= (optionsObj->oVariables->BinSOURCE ? BinarySaveSource : BinaryNoSaveSource);
}
if ((flags_ & BinaryLlvmirMask) != BinaryRemoveLlvmir) {
// set to zero
flags_ = (flags_ & (~BinaryLlvmirMask));
flags_ |= (optionsObj->oVariables->BinLLVMIR ? BinarySaveLlvmir : BinaryNoSaveLlvmir);
}
// If amdilRequired is true, force to save AMDIL (for correctness)
if ((flags_ & BinaryAmdilMask) != BinaryRemoveAmdil || amdilRequired) {
// set to zero
flags_ = (flags_ & (~BinaryAmdilMask));
flags_ |=
((optionsObj->oVariables->BinAMDIL || amdilRequired) ? BinarySaveAmdil : BinaryNoSaveAmdil);
}
if ((flags_ & BinaryIsaMask) != BinaryRemoveIsa) {
// set to zero
flags_ = (flags_ & (~BinaryIsaMask));
flags_ |= ((optionsObj->oVariables->BinEXE) ? BinarySaveIsa : BinaryNoSaveIsa);
}
if ((flags_ & BinaryASMask) != BinaryRemoveAS) {
// set to zero
flags_ = (flags_ & (~BinaryASMask));
flags_ |= ((optionsObj->oVariables->BinAS) ? BinarySaveAS : BinaryNoSaveAS);
}
}
bool ClBinary::isRecompilable(std::string& llvmBinary, amd::OclElf::oclElfPlatform thePlatform) {
/* It is recompilable if there is llvmir that was generated for
the same platform (CPU or GPU) and with the same bitness.
Note: the bitness has been checked in initClBinary(), no need
to check it here.
*/
if (llvmBinary.empty()) {
return false;
}
uint16_t elf_target;
amd::OclElf::oclElfPlatform platform;
if (elfIn()->getTarget(elf_target, platform)) {
if (platform == thePlatform) {
return true;
}
if ((platform == amd::OclElf::COMPLIB_PLATFORM) &&
(((thePlatform == amd::OclElf::CAL_PLATFORM) &&
((elf_target == (uint16_t)EM_AMDIL) || (elf_target == (uint16_t)EM_HSAIL) ||
(elf_target == (uint16_t)EM_HSAIL_64))) ||
((thePlatform == amd::OclElf::CPU_PLATFORM) &&
((elf_target == (uint16_t)EM_386) || (elf_target == (uint16_t)EM_X86_64))))) {
return true;
}
}
return false;
}
void ClBinary::release() {
if (isBinaryAllocated() && (binary_ != NULL)) {
delete[] binary_;
binary_ = NULL;
flags_ &= ~BinaryAllocated;
}
}
void ClBinary::saveBIFBinary(char* binaryIn, size_t size) {
char* image = new char[size];
memcpy(image, binaryIn, size);
setBinary(image, size, true);
return;
}
bool ClBinary::createElfBinary(bool doencrypt, Program::type_t type) {
#if 0
if (!saveISA() && !saveAMDIL() && !saveLLVMIR() && !saveSOURCE()) {
return true;
}
#endif
release();
size_t imageSize;
char* image;
assert(elfOut_ && "elfOut_ should be initialized in ClBinary::data()");
// Insert Version string that builds this binary into .comment section
const device::Info& devInfo = dev_.info();
std::string buildVerInfo("@(#) ");
if (devInfo.version_ != NULL) {
buildVerInfo.append(devInfo.version_);
buildVerInfo.append(". Driver version: ");
buildVerInfo.append(devInfo.driverVersion_);
} else {
// char OpenCLVersion[256];
// size_t sz;
// cl_int ret= clGetPlatformInfo(AMD_PLATFORM, CL_PLATFORM_VERSION, 256, OpenCLVersion, &sz);
// if (ret == CL_SUCCESS) {
// buildVerInfo.append(OpenCLVersion, sz);
// }
// If CAL is unavailable, just hard-code the OpenCL driver version
buildVerInfo.append("OpenCL 1.1" AMD_PLATFORM_INFO);
}
elfOut_->addSection(amd::OclElf::COMMENT, buildVerInfo.data(), buildVerInfo.size());
switch (type) {
case Program::TYPE_NONE: {
elfOut_->setType(ET_NONE);
break;
}
case Program::TYPE_COMPILED: {
elfOut_->setType(ET_REL);
break;
}
case Program::TYPE_LIBRARY: {
elfOut_->setType(ET_DYN);
break;
}
case Program::TYPE_EXECUTABLE: {
elfOut_->setType(ET_EXEC);
break;
}
default:
assert(0 && "unexpected elf type");
}
if (!elfOut_->dumpImage(&image, &imageSize)) {
return false;
}
#if defined(HAVE_BLOWFISH_H)
if (doencrypt) {
// Increase the size by 64 to accomodate extra headers
int outBufSize = (int)(imageSize + 64);
char* outBuf = new char[outBufSize];
if (outBuf == NULL) {
return false;
}
memset(outBuf, '\0', outBufSize);
int outBytes = 0;
bool success = amd::oclEncrypt(0, image, imageSize, outBuf, outBufSize, &outBytes);
delete[] image;
if (!success) {
delete[] outBuf;
return false;
}
image = outBuf;
imageSize = outBytes;
}
#endif
setBinary(image, imageSize, true);
return true;
}
Program::binary_t ClBinary::data() const { return std::make_pair(binary_, size_); }
bool ClBinary::setBinary(char* theBinary, size_t theBinarySize, bool allocated) {
release();
size_ = theBinarySize;
binary_ = theBinary;
if (allocated) {
flags_ |= BinaryAllocated;
}
return true;
}
void ClBinary::setFlags(int encryptCode) {
encryptCode_ = encryptCode;
if (encryptCode != 0) {
flags_ =
(flags_ &
(~(BinarySourceMask | BinaryLlvmirMask | BinaryAmdilMask | BinaryIsaMask | BinaryASMask)));
flags_ |= (BinaryRemoveSource | BinaryRemoveLlvmir | BinaryRemoveAmdil | BinarySaveIsa |
BinaryRemoveAS);
}
}
bool ClBinary::decryptElf(char* binaryIn, size_t size, char** decryptBin, size_t* decryptSize,
int* encryptCode) {
*decryptBin = NULL;
#if defined(HAVE_BLOWFISH_H)
int outBufSize = 0;
if (amd::isEncryptedBIF(binaryIn, (int)size, &outBufSize)) {
char* outBuf = new (std::nothrow) char[outBufSize];
if (outBuf == NULL) {
return false;
}
// Decrypt
int outDataSize = 0;
if (!amd::oclDecrypt(binaryIn, (int)size, outBuf, outBufSize, &outDataSize)) {
delete[] outBuf;
return false;
}
*decryptBin = reinterpret_cast<char*>(outBuf);
*decryptSize = outDataSize;
*encryptCode = 1;
}
#endif
return true;
}
bool ClBinary::setElfIn(unsigned char eclass) {
if (elfIn_) return true;
if (binary_ == NULL) {
return false;
}
elfIn_ = new amd::OclElf(eclass, binary_, size_, NULL, ELF_C_READ);
if ((elfIn_ == NULL) || elfIn_->hasError()) {
if (elfIn_) {
delete elfIn_;
elfIn_ = NULL;
}
LogError("Creating input ELF object failed");
return false;
}
return true;
}
void ClBinary::resetElfIn() {
if (elfIn_) {
delete elfIn_;
elfIn_ = NULL;
}
}
bool ClBinary::setElfOut(unsigned char eclass, const char* outFile) {
elfOut_ = new amd::OclElf(eclass, NULL, 0, outFile, ELF_C_WRITE);
if ((elfOut_ == NULL) || elfOut_->hasError()) {
if (elfOut_) {
delete elfOut_;
elfOut_ = NULL;
}
LogError("Creating ouput ELF object failed");
return false;
}
return setElfTarget();
}
void ClBinary::resetElfOut() {
if (elfOut_) {
delete elfOut_;
elfOut_ = NULL;
}
}
bool ClBinary::loadLlvmBinary(std::string& llvmBinary,
amd::OclElf::oclElfSections& elfSectionType) const {
// Check if current binary already has LLVMIR
char* section = NULL;
size_t sz = 0;
const amd::OclElf::oclElfSections SectionTypes[] = {amd::OclElf::LLVMIR, amd::OclElf::SPIR,
amd::OclElf::SPIRV};
for (int i = 0; i < 3; ++i) {
if (elfIn_->getSection(SectionTypes[i], §ion, &sz) && section && sz > 0) {
llvmBinary.append(section, sz);
elfSectionType = SectionTypes[i];
return true;
}
}
return false;
}
bool ClBinary::loadCompileOptions(std::string& compileOptions) const {
char* options = NULL;
size_t sz;
compileOptions.clear();
if (elfIn_->getSymbol(amd::OclElf::COMMENT, getBIFSymbol(symOpenclCompilerOptions).c_str(),
&options, &sz)) {
if (sz > 0) {
compileOptions.append(options, sz);
}
return true;
}
return false;
}
bool ClBinary::loadLinkOptions(std::string& linkOptions) const {
char* options = NULL;
size_t sz;
linkOptions.clear();
if (elfIn_->getSymbol(amd::OclElf::COMMENT, getBIFSymbol(symOpenclLinkerOptions).c_str(),
&options, &sz)) {
if (sz > 0) {
linkOptions.append(options, sz);
}
return true;
}
return false;
}
void ClBinary::storeCompileOptions(const std::string& compileOptions) {
elfOut()->addSymbol(amd::OclElf::COMMENT, getBIFSymbol(symOpenclCompilerOptions).c_str(),
compileOptions.c_str(), compileOptions.length());
}
void ClBinary::storeLinkOptions(const std::string& linkOptions) {
elfOut()->addSymbol(amd::OclElf::COMMENT, getBIFSymbol(symOpenclLinkerOptions).c_str(),
linkOptions.c_str(), linkOptions.length());
}
bool ClBinary::isSPIR() const {
char* section = NULL;
size_t sz = 0;
if (elfIn_->getSection(amd::OclElf::LLVMIR, §ion, &sz) && section && sz > 0) return false;
if (elfIn_->getSection(amd::OclElf::SPIR, §ion, &sz) && section && sz > 0) return true;
return false;
}
bool ClBinary::isSPIRV() const {
char* section = NULL;
size_t sz = 0;
if (elfIn_->getSection(amd::OclElf::SPIRV, §ion, &sz) && section && sz > 0) {
return true;
}
return false;
}
cl_device_partition_property PartitionType::toCL() const {
static cl_device_partition_property conv[] = {CL_DEVICE_PARTITION_EQUALLY,
CL_DEVICE_PARTITION_BY_COUNTS,
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN};
return conv[amd::leastBitSet(value_)];
}
size_t PartitionType::toCL(cl_device_partition_property* types) const {
size_t i = 0;
if (equally_) {
types[i++] = CL_DEVICE_PARTITION_EQUALLY;
}
if (byCounts_) {
types[i++] = CL_DEVICE_PARTITION_BY_COUNTS;
}
if (byAffinityDomain_) {
types[i++] = CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN;
}
return i;
}
cl_device_affinity_domain AffinityDomain::toCL() const { return (cl_device_affinity_domain)value_; }
#ifdef cl_ext_device_fission
cl_device_partition_property_ext PartitionType::toCLExt() const {
static cl_device_partition_property_ext conv[] = {CL_DEVICE_PARTITION_EQUALLY_EXT,
CL_DEVICE_PARTITION_BY_COUNTS_EXT,
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT};
return conv[amd::leastBitSet(value_)];
}
size_t PartitionType::toCLExt(cl_device_partition_property_ext* types) const {
size_t i = 0;
if (equally_) {
types[i++] = CL_DEVICE_PARTITION_EQUALLY_EXT;
}
if (byCounts_) {
types[i++] = CL_DEVICE_PARTITION_BY_COUNTS_EXT;
}
if (byAffinityDomain_) {
types[i++] = CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT;
}
return i;
}
cl_device_partition_property_ext AffinityDomain::toCLExt() const {
static cl_device_partition_property_ext conv[] = {
CL_AFFINITY_DOMAIN_NUMA_EXT, CL_AFFINITY_DOMAIN_L4_CACHE_EXT,
CL_AFFINITY_DOMAIN_L3_CACHE_EXT, CL_AFFINITY_DOMAIN_L2_CACHE_EXT,
CL_AFFINITY_DOMAIN_L1_CACHE_EXT, CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT};
return conv[amd::leastBitSet(value_)];
}
size_t AffinityDomain::toCLExt(cl_device_partition_property_ext* affinities) const {
size_t i = 0;
if (numa_) {
affinities[i++] = CL_AFFINITY_DOMAIN_NUMA_EXT;
}
if (cacheL4_) {
affinities[i++] = CL_AFFINITY_DOMAIN_L4_CACHE_EXT;
}
if (cacheL3_) {
affinities[i++] = CL_AFFINITY_DOMAIN_L3_CACHE_EXT;
}
if (cacheL2_) {
affinities[i++] = CL_AFFINITY_DOMAIN_L2_CACHE_EXT;
}
if (cacheL1_) {
affinities[i++] = CL_AFFINITY_DOMAIN_L1_CACHE_EXT;
}
if (next_) {
affinities[i++] = CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT;
}
return i;
}
#endif // cl_ext_device_fission
} // namespace device
| 29.613623 | 100 | 0.640959 | [
"object",
"vector"
] |
6233b35a1910af15cfbfc0ad8c77a740a086ccf8 | 8,505 | cpp | C++ | src/autowiring/test/ContextEnumeratorTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | src/autowiring/test/ContextEnumeratorTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | src/autowiring/test/ContextEnumeratorTest.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | // Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/ContextEnumerator.h>
#include <algorithm>
#include <random>
#include MEMORY_HEADER
#include STL_UNORDERED_SET
class ContextEnumeratorTest:
public testing::Test
{};
TEST_F(ContextEnumeratorTest, DegenerateEnumeration) {
size_t ct = 0;
for(const auto& cur : ContextEnumerator(std::shared_ptr<CoreContext>(nullptr))) {
ASSERT_TRUE(!!cur) << "Context enumerator incorrectly enumerated a null context pointer";
ct++;
}
ASSERT_EQ(0UL, ct) << "An empty enumerator unexpectedly enumerated one or more entries";
}
TEST_F(ContextEnumeratorTest, TrivialEnumeration) {
size_t ct = 0;
for(const auto& cur : ContextEnumerator(AutoCurrentContext())) {
(void) cur;
ct++;
}
ASSERT_EQ(1UL, ct) << "Context enumerator failed to enumerate a context with no children";
}
TEST_F(ContextEnumeratorTest, TwoContextEnumerationTest) {
AutoCreateContext ctxt1;
AutoCreateContext ctxt2;
size_t ct = 0;
for(const auto& cur : ContextEnumerator(ctxt1)) {
(void) cur;
ct++;
}
ASSERT_EQ(1UL, ct) << "An attempt to enumerate a context with a sibling did not correctly enumerate one context";
}
TEST_F(ContextEnumeratorTest, VerifySimpleEnumeration) {
// Create a pair of descendant contexts, verify we don't accidentally hit these when enumerating children
AutoCreateContext outer;
AutoCreateContext inner;
CurrentContextPusher pshr(inner);
// Add a few children to the current context:
AutoCreateContext c1;
AutoCreateContext c2;
AutoCreateContext c3;
AutoCreateContext c4;
std::unordered_set<std::shared_ptr<CoreContext>> allCtxts;
allCtxts.insert(AutoCurrentContext());
allCtxts.insert(c1);
allCtxts.insert(c2);
allCtxts.insert(c3);
allCtxts.insert(c4);
// Create the enumerator, verify we get the expected count:
size_t nContexts = 0;
for(const std::shared_ptr<CoreContext>& cur : CurrentContextEnumerator()) {
ASSERT_TRUE(!!allCtxts.count(cur)) << "Context enumerator accidentally enumerated a context not rooted in the specified parent";
allCtxts.erase(cur);
nContexts++;
}
ASSERT_EQ(5UL, nContexts) << "Context enumerator did not encounter the number of expected children";
ASSERT_TRUE(allCtxts.empty()) << "Context enumerator did not encounter all children as expected";
}
struct NamedContext {};
TEST_F(ContextEnumeratorTest, VerifyComplexEnumeration) {
std::shared_ptr<CoreContext> firstNamed, secondNamed;
AutoCreateContext firstContext;
{
CurrentContextPusher pshr(firstContext);
AutoCreateContextT<NamedContext> named;
firstNamed = named;
}
AutoCreateContext secondContext;
{
CurrentContextPusher pshr(secondContext);
AutoCreateContextT<NamedContext> named;
secondNamed = named;
}
// Verify there is only one context under the first context
int firstCount = 0;
for(const auto& ctxt : ContextEnumeratorT<NamedContext>(firstContext)) {
firstCount++;
ASSERT_EQ(ctxt, firstNamed);
ASSERT_EQ(ctxt->GetParentContext(), firstContext);
}
ASSERT_EQ(firstCount, 1) << "Expected exactly one context in the parent context, found " << firstCount;
// Verify there is only one context under the second context
int secondCount = 0;
for(const auto& ctxt : ContextEnumeratorT<NamedContext>(secondContext)) {
secondCount++;
ASSERT_EQ(ctxt, secondNamed);
ASSERT_EQ(ctxt->GetParentContext(), secondContext);
}
ASSERT_EQ(secondCount, 1) << "Expected exactly one context in the parent context, found " << secondCount;
// Verify global context structure
auto enumerator = ContextEnumeratorT<NamedContext>(AutoGlobalContext());
size_t globalCount = std::distance(enumerator.begin(), enumerator.end());
ASSERT_EQ(globalCount, 2UL) << "Expected exactly one context in the parent context, found " << globalCount;
}
TEST_F(ContextEnumeratorTest, SimpleRemovalInterference) {
static const size_t nChildren = 5;
// Create a few contexts which we intend to destroy as we go along:
std::unordered_set<std::shared_ptr<CoreContext>> contexts;
for(size_t i = nChildren; i--;)
contexts.insert(AutoCreateContext());
// Also add ourselves:
contexts.insert(AutoCurrentContext());
// Enumerate contexts, and remove them from the set:
size_t nRemoved = 0;
for(const auto& cur : CurrentContextEnumerator()) {
ASSERT_TRUE(!!contexts.count(cur)) << "Failed to find a context enumerated by the context enumerator";
contexts.erase(cur);
nRemoved++;
}
// Verify we got the number removed we expected:
ASSERT_EQ(nChildren + 1UL, nRemoved) << "Context enumerator did not remove the expected number of children";
}
TEST_F(ContextEnumeratorTest, ComplexRemovalInterference) {
static const size_t nChildren = 50;
// This time we use a vector, and we pop from the back of the vector unpredictably:
std::vector<std::shared_ptr<CoreContext>> children(nChildren);
for(size_t i = nChildren; i--;)
children.push_back(AutoCreateContext());
// Shuffle the collection to prevent the order here from being equivalent to the order in the context
std::random_device rd;
std::mt19937 gen(rd());
std::shuffle(children.begin(), children.end(), gen);
// These are the elements actually encountered in the enumeration, held here to prevent expiration in the
// event that we enumerate a context which should have already been evicted
std::unordered_set<std::shared_ptr<CoreContext>> enumerated;
// These are the elements eliminated from the vector. By the time we're done the should all be expired.
std::vector<std::weak_ptr<CoreContext>> eliminated;
// Go through the enumeration, the totals should line up by the time we're done:
for(const auto& cur : CurrentContextEnumerator()) {
enumerated.insert(cur);
// Pull off the last element:
auto removed = children.back();
children.pop_back();
// If we haven't enumerated this element already, we want to mark it as eliminated-before-enumerated
if(!enumerated.count(removed))
eliminated.push_back(removed);
}
// Now verify that nothing we eliminated was enumerated:
for(const auto& cur : eliminated)
ASSERT_TRUE(cur.expired()) << "Found an element that was iterated after it should have been unreachable";
}
TEST_F(ContextEnumeratorTest, Unique) {
AutoCreateContextT<NamedContext> named;
ASSERT_EQ(named, ContextEnumeratorT<NamedContext>().unique()) <<
"Expected the unique context to be equal to the specifically named child context";
}
TEST_F(ContextEnumeratorTest, BadUnique0) {
// Intentionally create 0 contexts with the NamedContext sigil.
ASSERT_THROW(ContextEnumeratorT<NamedContext>().unique(), autowiring_error) <<
"An attempt to obtain a unique context from an enumerator providing none should throw an exception";
}
TEST_F(ContextEnumeratorTest, BadUnique2) {
AutoCreateContextT<NamedContext> named1;
AutoCreateContextT<NamedContext> named2;
ASSERT_THROW(ContextEnumeratorT<NamedContext>().unique(), autowiring_error) <<
"An attempt to obtain a unique context from an enumerator providing more than one should throw an exception";
}
TEST_F(ContextEnumeratorTest, ForwardIteratorCheck) {
static_assert(std::is_default_constructible<ContextEnumerator::iterator>::value, "ForwardIterator constraint requires iterators to be default-constructable");
static_assert(
std::is_same<
std::iterator_traits<ContextEnumerator::iterator>::iterator_category,
std::forward_iterator_tag
>::value,
"ContextEnumerator iterator not recognized as a forward iterator"
);
AutoCreateContext ctxt1;
AutoCreateContext ctxt2;
AutoCreateContext ctxt2_0(ctxt2);
AutoCreateContext ctxt2_1(ctxt2);
AutoCreateContext ctxt2_1_0(ctxt2_1);
AutoCreateContext ctxt3;
ContextEnumerator e;
auto a = e.begin();
auto b = e.begin();
ASSERT_EQ(a++, b++) << "Incrementation equivalence was not satisfied";
ASSERT_EQ(a, b) << "Iterators not equivalent after incrementation";
auto prior = *b;
a++;
ASSERT_EQ(prior, *b) << "Incrementation of an unrelated iterator invalidated a copy of that iterator";
++b;
ASSERT_EQ(a, b) << "Postfix and prefix incrementation are not equivalently implemented";
a++;
ASSERT_EQ(a, std::next(b)) << "std::next did not correctly return the next iterator after the specified iterator";
b++;
std::advance(a, 1);
b++;
ASSERT_EQ(a, b) << "std::advance did not actually advance an iterator";
}
| 35.886076 | 160 | 0.742152 | [
"vector"
] |
9a8e5faf2f17495d359080c6bf3544bca2005413 | 2,837 | cxx | C++ | main/xmloff/source/style/SinglePropertySetInfoCache.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/xmloff/source/style/SinglePropertySetInfoCache.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/xmloff/source/style/SinglePropertySetInfoCache.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <cppuhelper/weakref.hxx>
#ifndef _XMLOFF_SINGLEPROPERTYSETINFOCACHE_HXX
#include <xmloff/SinglePropertySetInfoCache.hxx>
#endif
using namespace ::com::sun::star::uno;
using ::com::sun::star::lang::XTypeProvider;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::beans::XPropertySetInfo;
sal_Bool SinglePropertySetInfoCache::hasProperty(
const Reference< XPropertySet >& rPropSet,
Reference< XPropertySetInfo >& rPropSetInfo )
{
if( !rPropSetInfo.is() )
rPropSetInfo = rPropSet->getPropertySetInfo();
sal_Bool bRet = sal_False, bValid = sal_False;
Reference < XTypeProvider > xTypeProv( rPropSet, UNO_QUERY );
Sequence< sal_Int8 > aImplId;
if( xTypeProv.is() )
{
aImplId = xTypeProv->getImplementationId();
if( aImplId.getLength() == 16 )
{
// The key must not be created outside this block, because it
// keeps a reference to the property set info.
PropertySetInfoKey aKey( rPropSetInfo, aImplId );
iterator aIter = find( aKey );
if( aIter != end() )
{
bRet = (*aIter).second;
bValid = sal_True;
}
}
}
if( !bValid )
{
bRet = rPropSetInfo->hasPropertyByName( sName );
if( xTypeProv.is() && aImplId.getLength() == 16 )
{
// Check whether the property set info is destroyed if it is
// assigned to a weak reference only. If it is destroyed, then
// every instance of getPropertySetInfo returns a new object.
// Such property set infos must not be cached.
WeakReference < XPropertySetInfo > xWeakInfo( rPropSetInfo );
rPropSetInfo = 0;
rPropSetInfo = xWeakInfo;
if( rPropSetInfo.is() )
{
PropertySetInfoKey aKey( rPropSetInfo, aImplId );
value_type aValue( aKey, bRet );
insert( aValue );
}
}
}
return bRet;
}
| 32.988372 | 70 | 0.685231 | [
"object"
] |
9a992e835d004f1d712afb787b675997fa607843 | 9,175 | cpp | C++ | Task1/BayerPattern.cpp | AlexeyZhuravlev/ABBYY-ImageProcessing | 3f07642eab194b66fa271795be06c2b29f1aa8de | [
"MIT"
] | null | null | null | Task1/BayerPattern.cpp | AlexeyZhuravlev/ABBYY-ImageProcessing | 3f07642eab194b66fa271795be06c2b29f1aa8de | [
"MIT"
] | null | null | null | Task1/BayerPattern.cpp | AlexeyZhuravlev/ABBYY-ImageProcessing | 3f07642eab194b66fa271795be06c2b29f1aa8de | [
"MIT"
] | null | null | null | #include <windows.h>
#include <gdiplus.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <vector>
#include <tuple>
#include <array>
using namespace Gdiplus;
typedef std::vector<BYTE> CRow;
typedef std::vector<CRow> CMatrix;
enum TChannelName {
CN_Blue = 0,
CN_Green = 1,
CN_Red = 2,
CN_Count
};
CMatrix getPaddedGrayMatrix( const BitmapData& pData, int padding, int fillValue )
{
int matrixHeight = pData.Height + padding * 2;
int matrixWidth = pData.Width + padding * 2;
CMatrix matrix( matrixHeight, CRow( matrixWidth, fillValue ) );
BYTE *pBuffer = (BYTE *)pData.Scan0;
int baseAdr = 0;
for( unsigned int y = 0; y < pData.Height; y++ ) {
int pixelAdr = baseAdr;
for( unsigned int x = 0; x < pData.Width; x++ ) {
int B = pBuffer[pixelAdr]; // blue
int G = pBuffer[pixelAdr + 1]; // green
int R = pBuffer[pixelAdr + 2]; // red
matrix[y + padding][x + padding] = ( B + G + R ) / 3;
pixelAdr += 3;
}
baseAdr += pData.Stride;
}
return matrix;
}
TChannelName getCurrentBayerChannel( int x, int y )
{
if( ( x + y ) % 2 != 0 ) {
return CN_Green;
}
if( y % 2 == 0 ) {
return CN_Red;
} else {
return CN_Blue;
}
}
bool isNorth( int dx, int dy )
{
return dy < 0 && abs(dx) <= 1;
}
bool isSouth( int dx, int dy )
{
return dy > 0 && abs( dx ) <= 1;
}
bool isWest( int dx, int dy )
{
return dx < 0 && abs( dy ) <= 1;
}
bool isEast( int dx, int dy )
{
return dx > 0 && abs( dy ) <= 1;
}
bool isNorthWest( int dx, int dy )
{
return dx <= 0 && dy <= 0 && abs( dx - dy ) <= 1;
}
bool isNorthEast( int dx, int dy )
{
return dx >= 0 && dy <= 0 && abs( dx + dy ) <= 1;
}
bool isSouthWest( int dx, int dy )
{
return dx <= 0 && dy >= 0 && abs( dx + dy ) <= 1;
}
bool isSouthEast( int dx, int dy )
{
return dx >= 0 && dy >= 0 && abs( dx - dy ) <= 1;
}
typedef bool( *DeltaCheckFunction )( int dx, int dy );
std::pair<int, int> findNearestSameColor( int x, int y, int dx, int dy )
{
int resultX = x + dx;
int resultY = y + dy;
while( getCurrentBayerChannel( x, y ) != getCurrentBayerChannel( resultX, resultY ) ) {
resultX += dx;
resultY += dy;
}
return std::make_pair( resultX, resultY );
}
int calcDirectionGradient( const CMatrix& m, int sourceX, int sourceY, int grayPadding, DeltaCheckFunction directionCheck,
int deltaX, int deltaY )
{
const int radius = 2;
int gradient = 0;
TChannelName channel = getCurrentBayerChannel( sourceX, sourceY );
for( int dx = -radius; dx <= radius; dx++ ) {
for( int dy = -radius; dy <= radius; dy++ ) {
if( !directionCheck( dx, dy ) ) {
continue;
}
int newX, newY;
std::tie(newX, newY) = findNearestSameColor( sourceX + dx, sourceY + dy, -deltaX, -deltaY );
if( abs( newX - sourceX ) + abs( newY - sourceY ) >= 3 ) {
continue;
}
int gradientValue = abs( m[sourceY + dy + grayPadding][sourceX + dx + grayPadding] - m[newY + grayPadding][newX + grayPadding] );
if( ( channel != CN_Green || abs( deltaX ) != abs( deltaY ) )
&& dx * deltaY - dy * deltaX != 0 )
{
gradientValue /= 2;
}
gradient += gradientValue;
}
}
return gradient;
}
std::tuple<int, int, int> calcEstimation( const CMatrix& m, int sourceX, int sourceY,
int pad, int dx, int dy )
{
int tX = sourceX + dx;
int tY = sourceY + dy;
std::array<int, CN_Count> colorValues;
colorValues.fill( 0 );
for( TChannelName channel : { CN_Blue, CN_Green, CN_Red } ) {
if( getCurrentBayerChannel( tX, tY ) == channel ) {
colorValues[channel] = m[tY + pad][tX + pad];
} else if( getCurrentBayerChannel( tX + dx, tY + dy ) == channel ) {
colorValues[channel] = (m[sourceY + pad][sourceX + pad] + m[tY + dy + pad][tX + dx + pad]) / 2;
} else {
int sum = 0;
int cnt = 0;
for( int deltaX = -1; deltaX <= 1; deltaX++ ) {
for( int deltaY = -1; deltaY <= 1; deltaY++ ) {
if( getCurrentBayerChannel( tX + deltaX, tY + deltaY ) == channel ) {
sum += m[tY + deltaY + pad][tX + deltaX + pad];
cnt++;
}
}
}
colorValues[channel] = sum / cnt;
}
}
return std::make_tuple( colorValues[CN_Blue], colorValues[CN_Green], colorValues[CN_Red] );
}
std::tuple<int, int, int> computeVngInterpolation( const CMatrix& m, int sourceX, int sourceY,
int grayPadding, float k1 = 1.5f, float k2 = 0.5f )
{
TChannelName currentChannel = getCurrentBayerChannel( sourceX, sourceY );
int x = sourceX + grayPadding;
int y = sourceY + grayPadding;
const int nGradients = 8;
const DeltaCheckFunction checkFunctions[nGradients] = {
isNorth,
isEast,
isSouth,
isWest,
isNorthEast,
isSouthEast,
isNorthWest,
isSouthWest
};
const std::pair<int, int> directions[nGradients] = {
{0, -1},
{1, 0},
{0, 1},
{-1, 0},
{1, -1},
{1, 1},
{-1, -1},
{-1, 1}
};
std::array<int, nGradients> gradients;
for( int i = 0; i < nGradients; i++ ) {
int dx = directions[i].first;
int dy = directions[i].second;
if( currentChannel == CN_Green ) {
dx *= 2;
dy *= 2;
}
gradients[i] = calcDirectionGradient( m, sourceX, sourceY, grayPadding,
checkFunctions[i], dx, dy );
}
int min = *std::min_element( gradients.begin(), gradients.end() );
int max = *std::max_element( gradients.begin(), gradients.end() );
int treshold = static_cast<int>( k1 * min + k2 * ( max - min ) );
int sumR = 0;
int sumB = 0;
int sumG = 0;
int nGoodGradients = 0;
for( int i = 0; i < nGradients; i++ ) {
if( gradients[i] <= treshold ) {
int db, dg, dr;
std::tie(db, dg, dr) = calcEstimation( m, sourceX, sourceY, grayPadding,
directions[i].first, directions[i].second );
sumR += dr;
sumB += db;
sumG += dg;
nGoodGradients++;
}
}
int currentIntensity = m[y][x];
int B = currentIntensity;
int R = currentIntensity;
int G = currentIntensity;
switch( currentChannel ) {
case CN_Red:
B += (sumB - sumR) / nGoodGradients;
G += (sumG - sumR) / nGoodGradients;
break;
case CN_Green:
R += (sumR - sumG) / nGoodGradients;
B += (sumB - sumG) / nGoodGradients;
break;
case CN_Blue:
R += (sumR - sumB) / nGoodGradients;
G += (sumG - sumB) / nGoodGradients;
break;
}
return std::make_tuple( B, G, R );
}
void process( BitmapData& pData )
{
const int w = pData.Width;
const int h = pData.Height;
const int bpr = pData.Stride;
const int bpp = 3; // BGR24
BYTE *pBuffer = (BYTE *)pData.Scan0;
time_t start = clock();
const int grayPadding = 3;
CMatrix paddedGraySource = getPaddedGrayMatrix( pData, grayPadding, 0 );
int baseAdr = 0;
for( int y = 0; y < h; y++ )
{
int pixelAdr = baseAdr;
for( int x = 0; x < w; x++ )
{
int B = 0;
int G = 0;
int R = 0;
std::tie( B, G, R ) = computeVngInterpolation( paddedGraySource, x,
y, grayPadding );
pBuffer[pixelAdr] = static_cast<BYTE>( max( 0, min( 255, B ) ) );
pBuffer[pixelAdr + 1] = static_cast<BYTE>( max( 0, min( 255, G ) ) );
pBuffer[pixelAdr + 2] = static_cast<BYTE>( max( 0, min( 255, R ) ) );
pixelAdr += bpp;
}
baseAdr += bpr;
}
time_t end = clock();
_tprintf( _T("Time: %.3f\n"), static_cast<double>( end - start ) / CLOCKS_PER_SEC );
}
int GetEncoderClsid( const WCHAR* format, CLSID* pClsid )
{
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
ImageCodecInfo* pImageCodecInfo = NULL;
GetImageEncodersSize( &num, &size );
if( size == 0 )
return -1; // Failure
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
if( pImageCodecInfo == NULL )
return -1; // Failure
GetImageEncoders( num, size, pImageCodecInfo );
for( UINT j = 0; j < num; j++ )
{
if( wcscmp( pImageCodecInfo[j].MimeType, format ) == 0 )
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free( pImageCodecInfo );
return -1; // Failure
}
int _tmain(int argc, _TCHAR* argv[])
{
if( argc != 3 )
{
_tprintf( _T("Usage: BayerPattern <inputFile.bmp> <outputFile.bmp>\n") );
return 0;
}
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );
{
Bitmap GDIBitmap( argv[1] );
int w = GDIBitmap.GetWidth();
int h = GDIBitmap.GetHeight();
BitmapData bmpData;
Rect rc( 0, 0, w, h ); // whole image
if( Ok != GDIBitmap.LockBits( &rc, ImageLockModeRead | ImageLockModeWrite, PixelFormat24bppRGB, &bmpData ) )
_tprintf( _T("Failed to lock image: %s\n"), argv[1] );
else
_tprintf( _T("File: %s\n"), argv[1] );
process( bmpData );
GDIBitmap.UnlockBits( &bmpData );
// Save result
CLSID clsId;
GetEncoderClsid( _T("image/bmp"), &clsId );
GDIBitmap.Save( argv[2], &clsId, NULL );
}
GdiplusShutdown( gdiplusToken );
return 0;
}
| 25.068306 | 133 | 0.58703 | [
"vector"
] |
9a9ddbbfe446e433e3272c599ae538019ba37311 | 18,593 | cc | C++ | chrome/browser/web_resource/notification_promo.cc | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 7 | 2015-05-20T22:41:35.000Z | 2021-11-18T19:07:59.000Z | chrome/browser/web_resource/notification_promo.cc | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 1 | 2015-02-02T06:55:08.000Z | 2016-01-20T06:11:59.000Z | chrome/browser/web_resource/notification_promo.cc | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 2 | 2015-12-08T00:37:41.000Z | 2017-04-06T05:34:05.000Z | // Copyright (c) 2012 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 "chrome/browser/web_resource/notification_promo.h"
#include <cmath>
#include <vector>
#include "base/bind.h"
#include "base/rand_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile_impl.h"
#include "chrome/browser/web_resource/promo_resource_service.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/net/url_util.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/user_metrics.h"
#include "googleurl/src/gurl.h"
#if defined(OS_ANDROID)
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#endif // defined(OS_ANDROID)
using content::UserMetricsAction;
namespace {
const int kDefaultGroupSize = 100;
const char promo_server_url[] = "https://clients3.google.com/crsignal/client";
const char kPrefPromoObject[] = "promo";
const char kPrefPromoText[] = "text";
#if defined(OS_ANDROID)
const char kPrefPromoTextLong[] = "text_long";
const char kPrefPromoActionType[] = "action_type";
const char kPrefPromoActionArgs[] = "action_args";
#endif
const char kPrefPromoStart[] = "start";
const char kPrefPromoEnd[] = "end";
const char kPrefPromoNumGroups[] = "num_groups";
const char kPrefPromoSegment[] = "segment";
const char kPrefPromoIncrement[] = "increment";
const char kPrefPromoIncrementFrequency[] = "increment_frequency";
const char kPrefPromoIncrementMax[] = "increment_max";
const char kPrefPromoMaxViews[] = "max_views";
const char kPrefPromoGroup[] = "group";
const char kPrefPromoViews[] = "views";
const char kPrefPromoClosed[] = "closed";
const char kPrefPromoGPlusRequired[] = "gplus_required";
#if defined(OS_ANDROID)
const int kCurrentMobilePayloadFormatVersion = 3;
#endif // defined(OS_ANDROID)
// Returns a string suitable for the Promo Server URL 'osname' value.
std::string PlatformString() {
#if defined(OS_WIN)
return "win";
#elif defined(OS_IOS)
// TODO(noyau): add iOS-specific implementation
const bool isTablet = false;
return std::string("ios-") + (isTablet ? "tablet" : "phone");
#elif defined(OS_MACOSX)
return "mac";
#elif defined(OS_CHROMEOS)
return "chromeos";
#elif defined(OS_LINUX)
return "linux";
#elif defined(OS_ANDROID)
const bool isTablet =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kTabletUI);
return std::string("android-") + (isTablet ? "tablet" : "phone");
#else
return "none";
#endif
}
// Returns a string suitable for the Promo Server URL 'dist' value.
const char* ChannelString() {
#if defined (OS_WIN)
// GetChannel hits the registry on Windows. See http://crbug.com/70898.
// TODO(achuith): Move NotificationPromo::PromoServerURL to the blocking pool.
base::ThreadRestrictions::ScopedAllowIO allow_io;
#endif
const chrome::VersionInfo::Channel channel =
chrome::VersionInfo::GetChannel();
switch (channel) {
case chrome::VersionInfo::CHANNEL_CANARY:
return "canary";
case chrome::VersionInfo::CHANNEL_DEV:
return "dev";
case chrome::VersionInfo::CHANNEL_BETA:
return "beta";
case chrome::VersionInfo::CHANNEL_STABLE:
return "stable";
default:
return "none";
}
}
struct PromoMapEntry {
NotificationPromo::PromoType promo_type;
const char* promo_type_str;
};
const PromoMapEntry kPromoMap[] = {
{ NotificationPromo::NO_PROMO, "" },
{ NotificationPromo::NTP_NOTIFICATION_PROMO, "ntp_notification_promo" },
{ NotificationPromo::BUBBLE_PROMO, "bubble_promo" },
{ NotificationPromo::MOBILE_NTP_SYNC_PROMO, "mobile_ntp_sync_promo" },
};
// Convert PromoType to appropriate string.
const char* PromoTypeToString(NotificationPromo::PromoType promo_type) {
for (size_t i = 0; i < arraysize(kPromoMap); ++i) {
if (kPromoMap[i].promo_type == promo_type)
return kPromoMap[i].promo_type_str;
}
NOTREACHED();
return "";
}
// TODO(achuith): remove this in m23.
void ClearDeprecatedPrefs(PrefService* prefs) {
prefs->RegisterStringPref(prefs::kNtpPromoLine,
std::string(),
PrefService::UNSYNCABLE_PREF);
prefs->ClearPref(prefs::kNtpPromoLine);
#if defined(OS_ANDROID)
prefs->RegisterStringPref(prefs::kNtpPromoLineLong,
std::string(),
PrefService::UNSYNCABLE_PREF);
prefs->RegisterStringPref(prefs::kNtpPromoActionType,
std::string(),
PrefService::UNSYNCABLE_PREF);
prefs->RegisterListPref(prefs::kNtpPromoActionArgs,
new base::ListValue,
PrefService::UNSYNCABLE_PREF);
prefs->ClearPref(prefs::kNtpPromoLineLong);
prefs->ClearPref(prefs::kNtpPromoActionType);
prefs->ClearPref(prefs::kNtpPromoActionArgs);
#endif // defined(OS_ANDROID)
prefs->RegisterDoublePref(prefs::kNtpPromoStart,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterDoublePref(prefs::kNtpPromoEnd,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoNumGroups,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoInitialSegment,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoIncrement,
1,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoGroupTimeSlice,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoGroupMax,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoViewsMax,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoGroup,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterIntegerPref(prefs::kNtpPromoViews,
0,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterBooleanPref(prefs::kNtpPromoClosed,
false,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterBooleanPref(prefs::kNtpPromoGplusRequired,
false,
PrefService::UNSYNCABLE_PREF);
prefs->ClearPref(prefs::kNtpPromoStart);
prefs->ClearPref(prefs::kNtpPromoEnd);
prefs->ClearPref(prefs::kNtpPromoNumGroups);
prefs->ClearPref(prefs::kNtpPromoInitialSegment);
prefs->ClearPref(prefs::kNtpPromoIncrement);
prefs->ClearPref(prefs::kNtpPromoGroupTimeSlice);
prefs->ClearPref(prefs::kNtpPromoGroupMax);
prefs->ClearPref(prefs::kNtpPromoViewsMax);
prefs->ClearPref(prefs::kNtpPromoGroup);
prefs->ClearPref(prefs::kNtpPromoViews);
prefs->ClearPref(prefs::kNtpPromoClosed);
prefs->ClearPref(prefs::kNtpPromoGplusRequired);
}
} // namespace
NotificationPromo::NotificationPromo(Profile* profile)
: profile_(profile),
prefs_(profile_->GetPrefs()),
promo_type_(NO_PROMO),
#if defined(OS_ANDROID)
promo_action_args_(new base::ListValue),
#endif
start_(0.0),
end_(0.0),
num_groups_(kDefaultGroupSize),
initial_segment_(0),
increment_(1),
time_slice_(0),
max_group_(0),
max_views_(0),
group_(0),
views_(0),
closed_(false),
gplus_required_(false),
new_notification_(false) {
DCHECK(profile);
DCHECK(prefs_);
}
NotificationPromo::~NotificationPromo() {}
void NotificationPromo::InitFromJson(const DictionaryValue& json,
PromoType promo_type) {
promo_type_ = promo_type;
const ListValue* promo_list = NULL;
if (!json.GetList(PromoTypeToString(promo_type_), &promo_list)) {
LOG(ERROR) << "Malformed JSON: not " << PromoTypeToString(promo_type_);
return;
}
// No support for multiple promos yet. Only consider the first one.
const DictionaryValue* promo = NULL;
if (!promo_list->GetDictionary(0, &promo))
return;
// Strings. Assume the first one is the promo text.
const DictionaryValue* strings = NULL;
if (promo->GetDictionary("strings", &strings)) {
#if !defined(OS_ANDROID)
DictionaryValue::Iterator iter(*strings);
iter.value().GetAsString(&promo_text_);
DVLOG(1) << "promo_text_=" << promo_text_;
#endif // defined(OS_ANDROID)
}
// Date.
const ListValue* date_list = NULL;
if (promo->GetList("date", &date_list)) {
const DictionaryValue* date;
if (date_list->GetDictionary(0, &date)) {
std::string time_str;
base::Time time;
if (date->GetString("start", &time_str) &&
base::Time::FromString(time_str.c_str(), &time)) {
start_ = time.ToDoubleT();
DVLOG(1) << "start str=" << time_str
<< ", start_="<< base::DoubleToString(start_);
}
if (date->GetString("end", &time_str) &&
base::Time::FromString(time_str.c_str(), &time)) {
end_ = time.ToDoubleT();
DVLOG(1) << "end str =" << time_str
<< ", end_=" << base::DoubleToString(end_);
}
}
}
// Grouping.
const DictionaryValue* grouping = NULL;
if (promo->GetDictionary("grouping", &grouping)) {
grouping->GetInteger("buckets", &num_groups_);
grouping->GetInteger("segment", &initial_segment_);
grouping->GetInteger("increment", &increment_);
grouping->GetInteger("increment_frequency", &time_slice_);
grouping->GetInteger("increment_max", &max_group_);
DVLOG(1) << "num_groups_ = " << num_groups_
<< ", initial_segment_ = " << initial_segment_
<< ", increment_ = " << increment_
<< ", time_slice_ = " << time_slice_
<< ", max_group_ = " << max_group_;
}
// Payload.
const DictionaryValue* payload = NULL;
if (promo->GetDictionary("payload", &payload)) {
payload->GetBoolean("gplus_required", &gplus_required_);
DVLOG(1) << "gplus_required_ = " << gplus_required_;
}
promo->GetInteger("max_views", &max_views_);
DVLOG(1) << "max_views_ " << max_views_;
#if defined(OS_ANDROID)
int payload_version = 0;
if (!payload) {
LOG(ERROR) << "Malformed JSON: no payload";
return;
}
if (!strings) {
LOG(ERROR) << "Malformed JSON: no strings";
return;
}
if (!payload->GetInteger("payload_format_version", &payload_version) ||
payload_version != kCurrentMobilePayloadFormatVersion) {
LOG(ERROR) << "Unsupported promo payload_format_version " << payload_version
<< "; expected " << kCurrentMobilePayloadFormatVersion;
return;
}
std::string promo_key_short;
std::string promo_key_long;
if (!payload->GetString("promo_message_short", &promo_key_short) ||
!payload->GetString("promo_message_long", &promo_key_long) ||
!strings->GetString(promo_key_short, &promo_text_) ||
!strings->GetString(promo_key_long, &promo_text_long_)) {
LOG(ERROR) << "Malformed JSON: no promo_message_short or _long";
return;
}
payload->GetString("promo_action_type", &promo_action_type_);
// We need to be idempotent as the tests call us more than once.
promo_action_args_.reset(new base::ListValue);
const ListValue* args;
if (payload->GetList("promo_action_args", &args)) {
// JSON format for args: "promo_action_args" : [ "<arg1>", "<arg2>"... ]
// Every value comes from "strings" dictionary, either directly or not.
// Every arg is either directly a key into "strings" dictionary,
// or a key into "payload" dictionary with the value that is a key into
// "strings" dictionary.
for (std::size_t i = 0; i < args->GetSize(); ++i) {
std::string name, key, value;
if (!args->GetString(i, &name) ||
!(strings->GetString(name, &value) ||
(payload->GetString(name, &key) &&
strings->GetString(key, &value)))) {
LOG(ERROR) << "Malformed JSON: failed to parse promo_action_args";
return;
}
promo_action_args_->Append(base::Value::CreateStringValue(value));
}
}
#endif // defined(OS_ANDROID)
CheckForNewNotification();
}
void NotificationPromo::CheckForNewNotification() {
NotificationPromo old_promo(profile_);
old_promo.InitFromPrefs(promo_type_);
const double old_start = old_promo.start_;
const double old_end = old_promo.end_;
const std::string old_promo_text = old_promo.promo_text_;
new_notification_ =
old_start != start_ || old_end != end_ || old_promo_text != promo_text_;
if (new_notification_)
OnNewNotification();
}
void NotificationPromo::OnNewNotification() {
DVLOG(1) << "OnNewNotification";
// Create a new promo group.
group_ = base::RandInt(0, num_groups_ - 1);
WritePrefs();
}
// static
void NotificationPromo::RegisterUserPrefs(PrefService* prefs) {
ClearDeprecatedPrefs(prefs);
prefs->RegisterDictionaryPref("promo",
new base::DictionaryValue,
PrefService::UNSYNCABLE_PREF);
}
void NotificationPromo::WritePrefs() {
DVLOG(1) << "WritePrefs";
base::DictionaryValue* ntp_promo = new base::DictionaryValue;
ntp_promo->SetString(kPrefPromoText, promo_text_);
#if defined(OS_ANDROID)
ntp_promo->SetString(kPrefPromoTextLong, promo_text_long_);
ntp_promo->SetString(kPrefPromoActionType, promo_action_type_);
DCHECK(promo_action_args_.get());
ntp_promo->Set(kPrefPromoActionArgs, promo_action_args_->DeepCopy());
#endif // defined(OS_ANDROID)
ntp_promo->SetDouble(kPrefPromoStart, start_);
ntp_promo->SetDouble(kPrefPromoEnd, end_);
ntp_promo->SetInteger(kPrefPromoNumGroups, num_groups_);
ntp_promo->SetInteger(kPrefPromoSegment, initial_segment_);
ntp_promo->SetInteger(kPrefPromoIncrement, increment_);
ntp_promo->SetInteger(kPrefPromoIncrementFrequency, time_slice_);
ntp_promo->SetInteger(kPrefPromoIncrementMax, max_group_);
ntp_promo->SetInteger(kPrefPromoMaxViews, max_views_);
ntp_promo->SetInteger(kPrefPromoGroup, group_);
ntp_promo->SetInteger(kPrefPromoViews, views_);
ntp_promo->SetBoolean(kPrefPromoClosed, closed_);
ntp_promo->SetBoolean(kPrefPromoGPlusRequired, gplus_required_);
base::ListValue* promo_list = new base::ListValue;
promo_list->Set(0, ntp_promo); // Only support 1 promo for now.
base::DictionaryValue promo_dict;
promo_dict.Set(PromoTypeToString(promo_type_), promo_list);
prefs_->Set(kPrefPromoObject, promo_dict);
}
void NotificationPromo::InitFromPrefs(PromoType promo_type) {
promo_type_ = promo_type;
const base::DictionaryValue* promo_dict =
prefs_->GetDictionary(kPrefPromoObject);
if (!promo_dict)
return;
const base::ListValue* promo_list(NULL);
promo_dict->GetList(PromoTypeToString(promo_type_), &promo_list);
if (!promo_list)
return;
const base::DictionaryValue* ntp_promo(NULL);
promo_list->GetDictionary(0, &ntp_promo);
if (!ntp_promo)
return;
ntp_promo->GetString(kPrefPromoText, &promo_text_);
#if defined(OS_ANDROID)
ntp_promo->GetString(kPrefPromoTextLong, &promo_text_long_);
ntp_promo->GetString(kPrefPromoActionType, &promo_action_type_);
const base::ListValue* lv(NULL);
ntp_promo->GetList(kPrefPromoActionArgs, &lv);
DCHECK(lv != NULL);
promo_action_args_.reset(lv->DeepCopy());
#endif // defined(OS_ANDROID)
ntp_promo->GetDouble(kPrefPromoStart, &start_);
ntp_promo->GetDouble(kPrefPromoEnd, &end_);
ntp_promo->GetInteger(kPrefPromoNumGroups, &num_groups_);
ntp_promo->GetInteger(kPrefPromoSegment, &initial_segment_);
ntp_promo->GetInteger(kPrefPromoIncrement, &increment_);
ntp_promo->GetInteger(kPrefPromoIncrementFrequency, &time_slice_);
ntp_promo->GetInteger(kPrefPromoIncrementMax, &max_group_);
ntp_promo->GetInteger(kPrefPromoMaxViews, &max_views_);
ntp_promo->GetInteger(kPrefPromoGroup, &group_);
ntp_promo->GetInteger(kPrefPromoViews, &views_);
ntp_promo->GetBoolean(kPrefPromoClosed, &closed_);
ntp_promo->GetBoolean(kPrefPromoGPlusRequired, &gplus_required_);
}
bool NotificationPromo::CanShow() const {
return !closed_ &&
!promo_text_.empty() &&
!ExceedsMaxGroup() &&
!ExceedsMaxViews() &&
base::Time::FromDoubleT(StartTimeForGroup()) < base::Time::Now() &&
base::Time::FromDoubleT(EndTime()) > base::Time::Now() &&
IsGPlusRequired();
}
// static
void NotificationPromo::HandleClosed(Profile* profile, PromoType promo_type) {
content::RecordAction(UserMetricsAction("NTPPromoClosed"));
NotificationPromo promo(profile);
promo.InitFromPrefs(promo_type);
if (!promo.closed_) {
promo.closed_ = true;
promo.WritePrefs();
}
}
// static
bool NotificationPromo::HandleViewed(Profile* profile, PromoType promo_type) {
content::RecordAction(UserMetricsAction("NTPPromoShown"));
NotificationPromo promo(profile);
promo.InitFromPrefs(promo_type);
++promo.views_;
promo.WritePrefs();
return promo.ExceedsMaxViews();
}
bool NotificationPromo::ExceedsMaxGroup() const {
return (max_group_ == 0) ? false : group_ >= max_group_;
}
bool NotificationPromo::ExceedsMaxViews() const {
return (max_views_ == 0) ? false : views_ >= max_views_;
}
bool NotificationPromo::IsGPlusRequired() const {
return !gplus_required_ || prefs_->GetBoolean(prefs::kIsGooglePlusUser);
}
// static
GURL NotificationPromo::PromoServerURL() {
GURL url(promo_server_url);
url = chrome_common_net::AppendQueryParameter(
url, "dist", ChannelString());
url = chrome_common_net::AppendQueryParameter(
url, "osname", PlatformString());
url = chrome_common_net::AppendQueryParameter(
url, "branding", chrome::VersionInfo().Version());
DVLOG(1) << "PromoServerURL=" << url.spec();
// Note that locale param is added by WebResourceService.
return url;
}
double NotificationPromo::StartTimeForGroup() const {
if (group_ < initial_segment_)
return start_;
return start_ +
std::ceil(static_cast<float>(group_ - initial_segment_ + 1) / increment_)
* time_slice_;
}
double NotificationPromo::EndTime() const {
return end_;
}
| 34.753271 | 80 | 0.683053 | [
"vector"
] |
9aa4e6d9310a461c39923d3347e247fdaea86999 | 1,100 | cpp | C++ | leetcode.com/0457 Circular Array Loop/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/0457 Circular Array Loop/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/0457 Circular Array Loop/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <iostream>
#include <vector>
using namespace std;
// ref:
// https://leetcode.com/problems/circular-array-loop/discuss/94148/Java-SlowFast-Pointer-Solution
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
#define Next(i) ((i + n + nums[i] % n) % n)
for (int i = 0; i < n; ++i) {
if (nums[i] == 0) continue; // visited
bool right = nums[i] > 0;
int slow = i, fast = Next(i);
while (nums[i] * nums[fast] > 0 && nums[i] * nums[Next(fast)] > 0) {
if (slow == fast) {
if (slow == Next(slow)) {
break;
}
return true;
}
slow = Next(slow);
fast = Next(Next(fast));
}
for (int j = i; nums[j] * nums[i] > 0;) {
int tmp = Next(j);
nums[j] = 0;
j = tmp;
}
}
return false;
}
};
int main(int argc, char const* argv[]) {
Solution s;
vector<int> nums = {2, 2, 2, 2, 2, 4, 7};
// nums = {-2, 1, -1, -2, -2};
nums = {2, -1, 1, 2, 2};
cout << s.circularArrayLoop(nums) << endl;
return 0;
}
| 24.444444 | 97 | 0.495455 | [
"vector"
] |
9aa8ba0d07ad96997a973b1f3f8cb32686ca5b57 | 1,313 | cpp | C++ | src/sword_to_offer/sword_q15.cpp | jielyu/leetcode | ce5327f5e5ceaa867ea2ddd58a93bfb02b427810 | [
"MIT"
] | 9 | 2020-04-09T12:37:50.000Z | 2021-04-01T14:01:14.000Z | src/sword_to_offer/sword_q15.cpp | jielyu/leetcode | ce5327f5e5ceaa867ea2ddd58a93bfb02b427810 | [
"MIT"
] | 3 | 2020-05-05T02:43:54.000Z | 2020-05-20T11:12:16.000Z | src/sword_to_offer/sword_q15.cpp | jielyu/leetcode | ce5327f5e5ceaa867ea2ddd58a93bfb02b427810 | [
"MIT"
] | 5 | 2020-04-17T02:32:10.000Z | 2020-05-20T10:12:26.000Z |
/*
#剑指Offer# Q15 链表中的倒数第k个节点
输入一个链表,输出链表中的倒数第k个节点。从1开始计数,比如倒数第1个就是最后一个节点。
*/
#include "leetcode.h"
namespace sword_q15
{
template<typename T>
bool run_testcases() {
T slt;
{
vector<int> arr {1,2,3,4,5,6};
auto head = create_list(arr);
auto ret = slt.lastKNode(head, 3);
delete_list(head);
CHECK_RET(4 == ret);
}
{
vector<int> arr {1,2,3,4,5,6};
auto head = create_list(arr);
auto ret = slt.lastKNode(head, 1);
delete_list(head);
CHECK_RET(6 == ret);
}
{
vector<int> arr {1,2,3,4,5,6};
auto head = create_list(arr);
auto ret = slt.lastKNode(head, 7);
delete_list(head);
CHECK_RET(-1 == ret);
}
return true;
}
class Solution {
public:
int lastKNode(ListNode * head, int k) {
if (!head) {return -1;}
ListNode * low = head, * high = head;
// 先走k步长度不够则返回-1,注意条件是走k-1步
for (int i = 0; i < k - 1; ++i) {
if (high->next) {high = high->next;}
else {return -1;}
}
while (high->next != 0) {
low = low->next;
high = high->next;
}
return low->val;
}
};
TEST(SwordQ15, Solution) {EXPECT_TRUE(run_testcases<Solution>());}
} // namespace sword_q15
| 21.177419 | 66 | 0.522468 | [
"vector"
] |
9aafbc09f1113720d2fbe819977fc01f8024eedd | 2,551 | cc | C++ | integrations/tensorflow/compiler/dialect/tf_strings/conversion/convert_flow_to_hal.cc | rise-lang/iree | 46ad3fe392d38ce3df6eff7826cc1ab331a40b72 | [
"Apache-2.0"
] | 2 | 2021-01-03T04:45:05.000Z | 2021-01-03T04:45:08.000Z | integrations/tensorflow/compiler/dialect/tf_strings/conversion/convert_flow_to_hal.cc | BernhardRiemann/iree | 471349762b316f7d6b83eb5f9089255d78052758 | [
"Apache-2.0"
] | null | null | null | integrations/tensorflow/compiler/dialect/tf_strings/conversion/convert_flow_to_hal.cc | BernhardRiemann/iree | 471349762b316f7d6b83eb5f9089255d78052758 | [
"Apache-2.0"
] | 1 | 2021-01-29T09:30:09.000Z | 2021-01-29T09:30:09.000Z | // Copyright 2020 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 "integrations/tensorflow/compiler/dialect/tf_strings/conversion/convert_flow_to_hal.h"
#include "integrations/tensorflow/compiler/dialect/tf_strings/ir/ops.h"
#include "integrations/tensorflow/compiler/dialect/tf_strings/ir/types.h"
#include "iree/compiler/Dialect/HAL/Conversion/ConversionTarget.h"
#include "iree/compiler/Dialect/IREE/IR/IREEDialect.h"
#include "iree/compiler/Dialect/IREE/IR/IREEOps.h"
#include "iree/compiler/Dialect/IREE/IR/IREETypes.h"
#include "iree/compiler/Dialect/Modules/Strings/IR/Dialect.h"
#include "iree/compiler/Dialect/Modules/Strings/IR/Ops.h"
#include "iree/compiler/Dialect/VM/Conversion/ConversionDialectInterface.h"
namespace mlir {
namespace iree_compiler {
namespace tf_strings {
void populateTFStringsToHALPatterns(MLIRContext *context,
OwningRewritePatternList &patterns,
TypeConverter &typeConverter) {
// We can use the HAL conversion handler for this tensor->buffer conversion
// as we just want the simple form. If we wanted to perform additional
// verification or have a specific use case (such as a place where only the
// buffer is required and the shape is not) we could add our own.
patterns.insert<HALOpConversion<tf_strings::PrintOp, IREE::Strings::PrintOp>>(
context, typeConverter);
patterns.insert<HALOpConversion<tf_strings::ToStringTensorOp,
IREE::Strings::ToStringTensorOp>>(
context, typeConverter);
patterns.insert<HALOpConversion<tf_strings::StringTensorToStringOp,
IREE::Strings::StringTensorToStringOp>>(
context, typeConverter);
// TODO(suderman): This should be able to handle generic IREE values.
patterns.insert<
HALOpConversion<tf_strings::ToStringOp, IREE::Strings::I32ToStringOp>>(
context, typeConverter);
}
} // namespace tf_strings
} // namespace iree_compiler
} // namespace mlir
| 46.381818 | 95 | 0.73383 | [
"shape"
] |
9ab4aa7e896f2cc591ab821998c7db192c9b61c4 | 1,330 | hpp | C++ | lizy1.kurisu/include/lizy1/impl/kurisu/forward_std.hpp | li-zhong-yuan/lizy1.kurisu | dba9136bfc966e2e81bee2b469ae4cc3a8157ca4 | [
"MIT"
] | null | null | null | lizy1.kurisu/include/lizy1/impl/kurisu/forward_std.hpp | li-zhong-yuan/lizy1.kurisu | dba9136bfc966e2e81bee2b469ae4cc3a8157ca4 | [
"MIT"
] | null | null | null | lizy1.kurisu/include/lizy1/impl/kurisu/forward_std.hpp | li-zhong-yuan/lizy1.kurisu | dba9136bfc966e2e81bee2b469ae4cc3a8157ca4 | [
"MIT"
] | null | null | null | /// <exception>
namespace std {
class exception;
}
/// <memory>
namespace std {
template<class T> class allocator;
}
/// <variant>
namespace std {
template<class... Ts> class variant;
template<class T> struct variant_size;
}
/// <string>
namespace std {
template<class charT> struct char_traits;
template<> struct char_traits<char>;
template<class CharT, class Traits, class Allocator> class basic_string;
}
/// <array>
namespace std {
template<class T, std::size_t N> class array;
}
/// <vector>
namespace std {
template<class T, class Allocator> class vector;
}
/// <deque>
namespace std {
template<class T, class Allocator> class deque;
}
/// <forward_list>
namespace std {
template<class T, class Allocator> class forward_list;
}
/// <list>
namespace std {
template<class T, class Allocator> class list;
}
/// <map>
namespace std {
template<class Key, class T, class Compare, class Allocator> class map;
}
/// <set>
namespace std {
template<class Key, class Compare, class Allocator> class set;
}
/// <unordered_map>
namespace std {
template<class Key, class T, class Hash, class Pred, class Alloc> class unordered_map;
}
/// <unordered_set>
namespace std {
template<class Key, class Hash, class Pred, class Alloc> class unordered_set;
}
| 16.625 | 90 | 0.678195 | [
"vector"
] |
9abae6415715814fc4b4021107ef9553f6db2f68 | 14,734 | cpp | C++ | amgcl.cpp | ddemidov/fortran_amg_omp_ocl | 9213b93ac4bb303826a5900bb356cede6b282104 | [
"MIT"
] | 9 | 2017-10-22T11:56:49.000Z | 2019-12-19T10:17:02.000Z | amgcl.cpp | ddemidov/fortran_amg_omp_ocl | 9213b93ac4bb303826a5900bb356cede6b282104 | [
"MIT"
] | null | null | null | amgcl.cpp | ddemidov/fortran_amg_omp_ocl | 9213b93ac4bb303826a5900bb356cede6b282104 | [
"MIT"
] | null | null | null | /*
The MIT License
Copyright (c) 2017-2019 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <functional>
#include <boost/core/ignore_unused.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/variant.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/filesystem.hpp>
#include <amgcl/backend/builtin.hpp>
#include <amgcl/backend/vexcl.hpp>
#include <amgcl/coarsening/runtime.hpp>
#include <amgcl/relaxation/runtime.hpp>
#include <amgcl/solver/runtime.hpp>
#include <amgcl/preconditioner/runtime.hpp>
#include <amgcl/preconditioner/schur_pressure_correction.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/profiler.hpp>
#ifdef AMGCL_DEBUG
# include <amgcl/io/mm.hpp>
#endif
#include "amgcl.h"
#ifdef WIN32
# include <windows.h>
# include <delayimp.h>
#endif
//---------------------------------------------------------------------------
typedef boost::property_tree::ptree Params;
//---------------------------------------------------------------------------
amgclHandle STDCALL amgcl_profile_create() {
return static_cast<amgclHandle>( new amgcl::profiler<>() );
}
//---------------------------------------------------------------------------
void STDCALL amgcl_profile_tic(amgclHandle p, const char *name) {
static_cast<amgcl::profiler<>*>(p)->tic(name);
}
//---------------------------------------------------------------------------
void STDCALL amgcl_profile_toc(amgclHandle p, const char *name) {
static_cast<amgcl::profiler<>*>(p)->toc(name);
}
//---------------------------------------------------------------------------
void STDCALL amgcl_profile_report(amgclHandle p) {
std::cout << *static_cast<amgcl::profiler<>*>(p) << std::endl;
}
//---------------------------------------------------------------------------
void STDCALL amgcl_profile_destroy(amgclHandle p) {
delete static_cast<amgcl::profiler<>*>(p);
}
//---------------------------------------------------------------------------
amgclHandle STDCALL amgcl_params_create() {
return static_cast<amgclHandle>( new Params() );
}
//---------------------------------------------------------------------------
void STDCALL amgcl_params_seti(amgclHandle prm, const char *name, int value) {
static_cast<Params*>(prm)->put(name, value);
}
//---------------------------------------------------------------------------
void STDCALL amgcl_params_setf(amgclHandle prm, const char *name, float value) {
static_cast<Params*>(prm)->put(name, value);
}
//---------------------------------------------------------------------------
void STDCALL amgcl_params_sets(amgclHandle prm, const char *name, const char *value) {
static_cast<Params*>(prm)->put(name, value);
}
//---------------------------------------------------------------------------
void STDCALL amgcl_params_read_json(amgclHandle prm, const char *fname) {
try {
read_json(fname, *static_cast<Params*>(prm));
} catch(const std::exception &e) {
std::cout
<< "Failed to read \"" << fname << "\"" << std::endl
<< " Reason: " << e.what() << std::endl;
}
}
//---------------------------------------------------------------------------
void STDCALL amgcl_params_destroy(amgclHandle prm) {
delete static_cast<Params*>(prm);
}
//---------------------------------------------------------------------------
bool opencl_available() {
#ifdef WIN32
__try {
if (FAILED(__HrLoadAllImportsForDll("OpenCL.dll")))
return false;
}
__except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
#endif
return true;
}
//---------------------------------------------------------------------------
vex::Context& ctx(int devnum = 0) {
static vex::Context c(vex::Filter::DoublePrecision && vex::Filter::Position(devnum));
static bool once = [](){ std::cout << c << std::endl; return true; }();
boost::ignore_unused(once);
return c;
}
//---------------------------------------------------------------------------
typedef amgcl::backend::builtin<double> openmp;
typedef amgcl::backend::vexcl<double> opencl;
template <class Backend>
using amg_solver =
amgcl::make_solver<
amgcl::runtime::preconditioner<Backend>,
amgcl::runtime::solver::wrapper<Backend>
>;
template <class Backend>
struct solver_type;
template <> struct solver_type<openmp> : amg_solver<openmp>
{
typedef amg_solver<openmp> Base;
using Base::Base;
};
template <> struct solver_type<opencl> : amg_solver<opencl>
{
typedef amg_solver<opencl> Base;
typedef Base::params params;
typedef opencl::params backend_params;
mutable vex::vector<double> X, F;
template <class Matrix>
solver_type(
const Matrix &A,
const params &prm = params(),
const backend_params &bprm = backend_params()
)
: Base(A, prm, bprm),
X(bprm.q, amgcl::backend::rows(A)),
F(bprm.q, amgcl::backend::rows(A))
{}
};
typedef boost::variant<
solver_type<openmp>*,
solver_type<opencl>*
> solver;
//---------------------------------------------------------------------------
amgclHandle STDCALL amgcl_solver_create(
int n,
const int *ptr,
const int *col,
const double *val,
int device,
amgclHandle prm
)
{
const int nnz = ptr[n] - 1;
auto ptr_rng = boost::make_iterator_range(ptr, ptr + n+1);
auto col_rng = boost::make_iterator_range(col, col + nnz);
auto val_rng = boost::make_iterator_range(val, val + nnz);
auto A = std::make_tuple(n,
ptr_rng | boost::adaptors::transformed([](int i){ return i - 1; }),
col_rng | boost::adaptors::transformed([](int i){ return i - 1; }),
val_rng
);
Params p;
if (prm) p = *static_cast<Params*>(prm);
if (boost::filesystem::exists("libamgcl.json")) {
read_json("libamgcl.json", p);
}
#ifdef AMGCL_DEBUG
if (boost::filesystem::exists("libamgcl-device.txt")) {
std::ifstream f("libamgcl-device.txt");
f >> device;
}
if (boost::filesystem::exists("libamgcl-debug.json")) {
Params dbg;
read_json("libamgcl-debug.json", dbg);
std::string matrix = "A.mtx", params = "p.json";
dbg.get("matrix", matrix);
dbg.get("params", params);
amgcl::io::mm_write(matrix, A);
std::ofstream pfile(params);
write_json(pfile, p);
}
#endif
if (device < 0) {
return static_cast<amgclHandle>(new solver(new solver_type<openmp>(A, p)));
} else {
amgcl::precondition(opencl_available(), "OpenCL.dll not found!");
opencl::params bp;
bp.q = ctx(device);
return static_cast<amgclHandle>(new solver(new solver_type<opencl>(A, p, bp)));
}
}
//---------------------------------------------------------------------------
struct solver_report : boost::static_visitor<> {
template <class S>
void operator()(const S *s) const {
std::cout << s->precond() << std::endl;
}
};
//---------------------------------------------------------------------------
void STDCALL amgcl_solver_report(amgclHandle handle) {
const solver *s = static_cast<const solver*>(handle);
boost::apply_visitor(solver_report(), *s);
}
//---------------------------------------------------------------------------
struct solver_destroy : boost::static_visitor<> {
template <class S>
void operator()(const S *s) const {
delete s;
}
};
//---------------------------------------------------------------------------
void STDCALL amgcl_solver_destroy(amgclHandle handle) {
const solver *s = static_cast<const solver*>(handle);
boost::apply_visitor(solver_destroy(), *s);
delete s;
}
//---------------------------------------------------------------------------
struct solver_solve : boost::static_visitor<> {
const double *rhs;
double *x;
mutable conv_info conv;
solver_solve(const double *rhs, double *x) : rhs(rhs), x(x) {}
template <template <class> class S>
void operator()(const S<openmp> *s) const {
size_t n = s->size();
auto X = boost::make_iterator_range(x, x + n);
auto F = boost::make_iterator_range(rhs, rhs + n);
std::tie(conv.iterations, conv.residual) = (*s)(F, X);
}
template <template <class> class S>
void operator()(const S<opencl> *s) const {
size_t n = s->size();
vex::copy(x, x + n, s->X.begin());
vex::copy(rhs, rhs + n, s->F.begin());
std::tie(conv.iterations, conv.residual) = (*s)(s->F, s->X);
vex::copy(s->X.begin(), s->X.end(), x);
}
};
//---------------------------------------------------------------------------
conv_info STDCALL amgcl_solver_solve(
amgclHandle handle,
const double *rhs,
double *x
)
{
const solver *s = static_cast<const solver*>(handle);
solver_solve solve(rhs, x);
boost::apply_visitor(solve, *s);
return solve.conv;
}
//---------------------------------------------------------------------------
template <class Backend>
using schur_solver =
amgcl::make_solver<
amgcl::preconditioner::schur_pressure_correction<
amgcl::make_solver<
amgcl::relaxation::as_preconditioner<
Backend,
amgcl::runtime::relaxation::wrapper
>,
amgcl::runtime::solver::wrapper<Backend>
>,
amgcl::make_solver<
amgcl::amg<
Backend,
amgcl::runtime::coarsening::wrapper,
amgcl::runtime::relaxation::wrapper
>,
amgcl::runtime::solver::wrapper<Backend>
>
>,
amgcl::runtime::solver::wrapper<Backend>
>;
template <class Backend>
struct spc_solver_type;
template <> struct spc_solver_type<openmp> : schur_solver<openmp>
{
typedef schur_solver<openmp> Base;
using Base::Base;
};
template <> struct spc_solver_type<opencl> : schur_solver<opencl>
{
typedef schur_solver<opencl> Base;
typedef Base::params params;
typedef opencl::params backend_params;
mutable vex::vector<double> X, F;
template <class Matrix>
spc_solver_type(
const Matrix &A,
const params &prm = params(),
const backend_params &bprm = backend_params()
)
: Base(A, prm, bprm),
X(bprm.q, amgcl::backend::rows(A)),
F(bprm.q, amgcl::backend::rows(A))
{}
};
typedef boost::variant<
spc_solver_type<openmp>*,
spc_solver_type<opencl>*
> spc_solver;
//---------------------------------------------------------------------------
amgclHandle STDCALL amgcl_schur_pc_create(
int n,
const int *ptr,
const int *col,
const double *val,
int pvars,
int device,
amgclHandle prm
)
{
const int nnz = ptr[n] - 1;
auto ptr_rng = boost::make_iterator_range(ptr, ptr + n+1);
auto col_rng = boost::make_iterator_range(col, col + nnz);
auto val_rng = boost::make_iterator_range(val, val + nnz);
auto A = std::make_tuple(n,
ptr_rng | boost::adaptors::transformed([](int i){ return i - 1; }),
col_rng | boost::adaptors::transformed([](int i){ return i - 1; }),
val_rng
);
Params p;
if (prm) p = *static_cast<Params*>(prm);
if (boost::filesystem::exists("libamgcl.json")) {
read_json("libamgcl.json", p);
}
p.put("precond.pmask_size", n);
p.put("precond.pmask_pattern", std::string("<") + std::to_string(pvars));
#ifdef AMGCL_DEBUG
if (boost::filesystem::exists("libamgcl-device.txt")) {
std::ifstream f("libamgcl-device.txt");
f >> device;
}
if (boost::filesystem::exists("libamgcl-debug.json")) {
Params dbg;
read_json("libamgcl-debug.json", dbg);
std::string matrix = "A.mtx", params = "p.json";
dbg.get("matrix", matrix);
dbg.get("params", params);
amgcl::io::mm_write(matrix, A);
std::ofstream pfile(params);
write_json(pfile, p);
}
#endif
if (device < 0) {
return static_cast<amgclHandle>(new spc_solver(new spc_solver_type<openmp>(A, p)));
} else {
amgcl::precondition(opencl_available(), "OpenCL.dll not found!");
opencl::params bp;
bp.q = ctx(device);
return static_cast<amgclHandle>(new spc_solver(new spc_solver_type<opencl>(A, p, bp)));
}
}
//---------------------------------------------------------------------------
void STDCALL amgcl_schur_pc_report(amgclHandle handle) {
const spc_solver *s = static_cast<const spc_solver*>(handle);
boost::apply_visitor(solver_report(), *s);
}
//---------------------------------------------------------------------------
conv_info STDCALL amgcl_schur_pc_solve(
amgclHandle handle,
double const * rhs,
double * x
)
{
const spc_solver *s = static_cast<const spc_solver*>(handle);
solver_solve solve(rhs, x);
boost::apply_visitor(solve, *s);
return solve.conv;
}
//---------------------------------------------------------------------------
void STDCALL amgcl_schur_pc_destroy(amgclHandle handle) {
const spc_solver *s = static_cast<const spc_solver*>(handle);
boost::apply_visitor(solver_destroy(), *s);
delete s;
}
| 31.084388 | 95 | 0.541808 | [
"vector"
] |
9abc2966e630afd5e40cc01157ee343a69f0d322 | 5,522 | cpp | C++ | LizardGraphics/LRectangleShape.cpp | GercogKaban/lizardgraphics | 7d161c42b04529aea43c6afac6cce31e12537a7e | [
"MIT"
] | 2 | 2020-05-04T11:38:39.000Z | 2020-05-04T11:43:31.000Z | LizardGraphics/LRectangleShape.cpp | GercogKaban/lizardgraphics | 7d161c42b04529aea43c6afac6cce31e12537a7e | [
"MIT"
] | 45 | 2020-05-15T19:13:07.000Z | 2021-10-31T21:10:39.000Z | LizardGraphics/LRectangleShape.cpp | GercogKaban/lizardgraphics | 7d161c42b04529aea43c6afac6cce31e12537a7e | [
"MIT"
] | null | null | null | #include "pch.h"
#include "LRectangleShape.h"
#include "LRectangleBuffer.h"
#include "Lshaders.h"
#include "LApp.h"
#include "LLogger.h"
namespace LGraphics
{
LRectangleShape::LRectangleShape(LApp* app, const char* path, bool isInterfaceObj)
:LShape(app,path)
{
init(app, isInterfaceObj);
shader = app->getLightningShader().get();
projection = app->getProjectionMatrix();
app->toCreate.push(this);
}
//#ifdef OPENGL
// LRectangleShape::LRectangleShape(LApp* app, const unsigned char * bytes, size_t size, bool isInterfaceObj)
// :LShape(app,bytes,size)
// {
// init(app, isInterfaceObj);
// }
//#endif
float LRectangleShape::calculateWidgetLength()
{
return xGlCoordToScreenCoord(app->getWindowSize(), getTopRightCorner().x) - xGlCoordToScreenCoord(app->getWindowSize(), getTopLeftCorner().x);
}
glm::vec3 LRectangleShape::getTopLeftCorner() const
{
return ((LRectangleBuffer*)buffer)->getTopLeftCorner() * scale_ + move_;
}
glm::vec3 LRectangleShape::getTopRightCorner() const
{
return ((LRectangleBuffer*)buffer)->getTopRightCorner() * scale_ + move_;
}
glm::vec3 LRectangleShape::getBottomLeftCorner() const
{
return ((LRectangleBuffer*)buffer)->getBottomLeftCorner() * scale_ + move_;
}
glm::vec3 LRectangleShape::getBottomRightCorner() const
{
return ((LRectangleBuffer*)buffer)->getBottomRightCorner() * scale_ + move_;
}
void LRectangleShape::init(LApp* app, bool isInterfaceObj)
{
LOG_CALL
this->app = app;
buffer = app->standartRectBuffer;
if (app->info.api == L_OPENGL)
shader = app->openGLLightShader.get();
else if (app->info.api == L_VULKAN)
shader = app->lightShader.get();
}
bool LRectangleShape::mouseOnIt()
{
//float x_[4], y_[4];
//float* vbo = buffer->getVertices();
//// getting rectangle coordinates
//for (size_t i = 0; i < buffer->getVerticesCount(); ++i)
//{
// x_[i] = vbo[i * 3] * getScale().x + getMove().x;
// y_[i] = vbo[i * 3 + 1] * getScale().y + getMove().y;
//}
//double mouse_x, mouse_y;
//glfwGetCursorPos(app->getWindowHandler(), &mouse_x, &mouse_y);
//return isPointInPolygon((int)buffer->getVerticesCount(), x_, y_, pointOnScreenToGlCoords(app->getWindowSize(), { (float)mouse_x ,(float)mouse_y }));
return false;
}
#ifdef OPENGL
void LRectangleShape::draw()
{
auto shader = (LShaders::OpenGLShader*)getShader();
shader->use();
if (isTextureTurnedOn())
glUniform1i(glGetUniformLocation(shader->getShaderProgram(), "sampleTexture"), 1);
else
glUniform1i(glGetUniformLocation(shader->getShaderProgram(), "sampleTexture"), 0);
glBindTexture(GL_TEXTURE_2D, *(GLuint*)getTexture());
glUniform3f(glGetUniformLocation(shader->getShaderProgram(), "move"), move_.x, move_.y, move_.z);
glUniform3f(glGetUniformLocation(shader->getShaderProgram(), "scale"), scale_.x, scale_.y, scale_.z);
glUniform4f(glGetUniformLocation(shader->getShaderProgram(), "color_"), color_.x, color_.y, color_.z, transparency_);
//glUniformMatrix4fv(glGetUniformLocation(shader->getShaderProgram(), "rotate"), 1, GL_FALSE, glm::value_ptr(rotate_));
glBindVertexArray(buffer->getVaoNum());
glDrawElements(GL_TRIANGLES, buffer->getIndCount(), GL_UNSIGNED_INT, 0);
//glBindVertexArray(0);
//if (label.text.size())
// LLine::display(label);
/*if (innerWidgets)
for (auto& i : *innerWidgets)
i->draw();*/
}
#endif OPENGL
//LRectangleShape::LRectangleShape(LApp* app)
// :LShape()
//{
// init(app);
//}
void LRectangleShape::draw(VkCommandBuffer commandBuffer, uint32_t frameIndex, size_t objectNum)
{
#ifdef VULKAN1
auto shader = getShader();
auto model = dynamic_cast<LWRectangle*>(this)->
app->updateUniformBuffer(frameIndex, this);
uint32_t dynamicOffset = objectNum * static_cast<uint32_t>(app->dynamicAlignment);
LApp::TransformData data{
{color_.x,color_.y,color_.z, transparency_}
,{move_.x, move_.y, move_.z}
, {scale_.x, scale_.y, scale_.z } };
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, shader->getGraphicsPipeline());
VkBuffer vertexBuffers[] = { buffer->getVertBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(commandBuffer, buffer->getIndBuffer(), 0, VK_INDEX_TYPE_UINT16);
vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
getShader()->getPipelineLayout(), 0, 1, &app->descriptorSets[objectNum*2 + frameIndex], 1, &dynamicOffset);
vkCmdPushConstants(commandBuffer, shader->getPipelineLayout(),
VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(LApp::TransformData), &data);
vkCmdDrawIndexed(commandBuffer, static_cast<uint32_t>(buffer->getIndCount()), 1, 0, 0, 0);
//if (innerWidgets)
// for (auto& i : *innerWidgets)
// i->draw(commandBuffer, frameIndex);
#endif
}
//LRectangleShape::LRectangleShape(LApp* app)
// :LShape()
//{
// init(app);
//}
}
| 36.328947 | 158 | 0.632923 | [
"model"
] |
9ac44d6bc3f26a5520fe06bb952abbf3bf217c56 | 14,776 | cpp | C++ | contracts/wawaka/common/contract/attestation.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | contracts/wawaka/common/contract/attestation.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | contracts/wawaka/common/contract/attestation.cpp | marcelamelara/private-data-objects | be6841715865d4733b6555f416c56dde8839849e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 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.
*/
#include <stddef.h>
#include <stdint.h>
#include "Types.h"
#include "Dispatch.h"
#include "Attestation.h"
#include "Cryptography.h"
#include "Environment.h"
#include "KeyValue.h"
#include "Message.h"
#include "Response.h"
#include "Util.h"
#include "Value.h"
#include "WasmExtensions.h"
#include "contract/base.h"
#include "contract/attestation.h"
static KeyValueStore contract_attestation_store("meta");
static KeyValueStore contract_endpoint_store("endpoint");
const std::string code_hash_key("code-hash");
const std::string ledger_key("ledger-key");
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// NAME: initialize
//
// Method to call during contract initialization to incorporate
// the methods necessary for the attestation functions.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
bool ww::contract::attestation::initialize_contract(const Environment& env)
{
if (! set_ledger_key(""))
{
CONTRACT_SAFE_LOG(3, "failed to initialize the meta store");
return false;
}
ww::types::ByteArray code_hash;
if (! set_code_hash(code_hash))
{
CONTRACT_SAFE_LOG(3, "failed to initialize the meta store");
return false;
}
return true;
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// NAME: set_ledger_key
//
// Contract method to set the ledger key that will serve as the root
// of trust for verifying contract object attestations.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
bool ww::contract::attestation::set_ledger_key(
const Message& msg,
const Environment& env,
Response& rsp)
{
ASSERT_SENDER_IS_CREATOR(env, rsp);
ASSERT_SUCCESS(rsp, msg.validate_schema(SET_LEDGER_KEY_PARAM_SCHEMA),
"invalid request, missing required parameters");
const std::string ledger_verifying_key(msg.get_string("ledger_verifying_key"));
if (! set_ledger_key(ledger_verifying_key))
return rsp.error("failed to save the ledger verifying key");
return rsp.success(true);
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// NAME: get_ledger_key
//
// Contract method to get the ledger key that has been set as the
// contract object root of trust. Note that this is available to
// anyone. Could be wrapped with additional policy checks.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
bool ww::contract::attestation::get_ledger_key(
const Message& msg,
const Environment& env,
Response& rsp)
{
std::string ledger_verifying_key;
if (! get_ledger_key(ledger_verifying_key))
return rsp.error("failed to get the ledger verifying key");
ww::value::String result(ledger_verifying_key.c_str());
return rsp.value(result, false);
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// NAME: get_contract_metadata
//
// Contract method to get encryption and verifying key associated
// with the contract. Anyone can retrieve this information, it is
// always available in the ledger.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
bool ww::contract::attestation::get_contract_metadata(
const Message& msg,
const Environment& env,
Response& rsp)
{
std::string verifying_key;
if (! KeyValueStore::privileged_get("ContractKeys.Verifying", verifying_key))
return rsp.error("failed to retreive privileged value for ContractKeys.Verifying");
std::string encryption_key;
if (! KeyValueStore::privileged_get("ContractKeys.Encryption", encryption_key))
return rsp.error("failed to retreive privileged value for ContractKeys.Encryption");
ww::value::Structure result(CONTRACT_METADATA_SCHEMA);
result.set_string("verifying_key", verifying_key.c_str());
result.set_string("encryption_key", encryption_key.c_str());
return rsp.value(result, false);
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// NAME: get_contract_code_metadata
//
// Contract method to get the code metadata associated with the
// contract. Note that only the creator can get this information.
// It may expose information about the details of the contract that
// should not be public.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
bool ww::contract::attestation::get_contract_code_metadata(
const Message& msg,
const Environment& env,
Response& rsp)
{
ASSERT_SENDER_IS_CREATOR(env, rsp);
// returning all the information for now though only the nonce
// should be necessary for the attestation test
std::string code_nonce;
ASSERT_SUCCESS(rsp, KeyValueStore::privileged_get("ContractCode.Nonce", code_nonce),
"unexpected error: failed to retreive code nonce");
ww::types::ByteArray code_hash;
ASSERT_SUCCESS(rsp, ww::contract::attestation::compute_code_hash(code_hash),
"unexpected error: failed to retrieve code hash");
std::string encoded_code_hash;
ASSERT_SUCCESS(rsp, ww::crypto::b64_encode(code_hash, encoded_code_hash),
"unexpected error: failed to encode code hash");
ww::value::Structure result(CONTRACT_CODE_METADATA_SCHEMA);
result.set_string("code_nonce", code_nonce.c_str());
result.set_string("code_hash", encoded_code_hash.c_str());
return rsp.value(result, false);
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// NAME: add_endpoint
//
// Contract method to verify the attestation of a contract object
// and add it to the set of "trusted endpoints". Note that this
// implementation of the method is open to all. It can be wrapped
// with additional policy checks when included in the contract.
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
bool ww::contract::attestation::add_endpoint(
const Message& msg,
const Environment& env,
Response& rsp)
{
// to add an endpoint we do need the ledger key
std::string ledger_key;
if (! get_ledger_key(ledger_key) && ledger_key.length() > 0)
return rsp.error("contract has not been initialized");
// extract the parameters
ASSERT_SUCCESS(rsp, msg.validate_schema(ADD_ENDPOINT_PARAM_SCHEMA),
"invalid request, missing required parameters");
const std::string contract_id(msg.get_string("contract_id"));
const std::string ledger_code_hash(msg.get_string("ledger_attestation.contract_code_hash"));
const std::string ledger_meta_hash(msg.get_string("ledger_attestation.metadata_hash"));
const std::string ledger_signature(msg.get_string("ledger_attestation.signature"));
const std::string verifying_key(msg.get_string("contract_metadata.verifying_key"));
const std::string encryption_key(msg.get_string("contract_metadata.encryption_key"));
const std::string code_nonce(msg.get_string("contract_code_metadata.code_nonce"));
// we are going to assume that the invoker of this method is the creator
// of the contract being added so the creator id will come from the environment
const std::string creator(env.originator_id_);
// verify the ledger's signature on the metadata_hash and code_hash
{
ww::types::ByteArray buffer;
std::copy(contract_id.begin(), contract_id.end(), std::back_inserter(buffer));
std::copy(creator.begin(), creator.end(), std::back_inserter(buffer));
std::copy(ledger_code_hash.begin(), ledger_code_hash.end(), std::back_inserter(buffer));
std::copy(ledger_meta_hash.begin(), ledger_meta_hash.end(), std::back_inserter(buffer));
ww::types::ByteArray signature;
if (! ww::crypto::b64_decode(ledger_signature, signature))
return rsp.error("failed to decode ledger signature");
if (! ww::crypto::ecdsa::verify_signature(buffer, ledger_key, signature))
return rsp.error("failed to verify ledger signature");
}
// verify that the code hash matches the code hash in the ledger
{
// we compute the merkle root using the hash of our own code
// so we know the hash of the other if it matches
ww::types::ByteArray decoded_code_hash;
if (! get_code_hash(decoded_code_hash))
return rsp.error("failed to retrieve code hash");
ww::types::ByteArray nonce(code_nonce.begin(), code_nonce.end());
ww::types::ByteArray decoded_nonce_hash;
if (! ww::crypto::crypto_hash(nonce, decoded_nonce_hash))
return rsp.error("failed to hash code nonce");
ww::types::ByteArray buffer;
std::copy(decoded_code_hash.begin(), decoded_code_hash.end(), std::back_inserter(buffer));
std::copy(decoded_nonce_hash.begin(), decoded_nonce_hash.end(), std::back_inserter(buffer));
ww::types::ByteArray decoded_code_hash_root;
if (! ww::crypto::crypto_hash(buffer, decoded_code_hash_root))
return rsp.error("failed to create the code hash root");
ww::types::ByteArray decoded_ledger_code_hash;
if (! ww::crypto::b64_decode(ledger_code_hash, decoded_ledger_code_hash))
return rsp.error("failed to decoded ledger code hash");
if (decoded_ledger_code_hash != decoded_code_hash_root)
return rsp.error("attestation of code hash failed");
}
// verify that the metadata hash matches the metadata hash in the ledger
{
ww::types::ByteArray idhash;
if (! ww::crypto::b64_decode(contract_id, idhash))
return rsp.error("failed to decode the contract id");
ww::types::ByteArray buffer;
std::copy(idhash.begin(), idhash.end(), std::back_inserter(buffer));
std::copy(verifying_key.begin(), verifying_key.end(), std::back_inserter(buffer));
std::copy(encryption_key.begin(), encryption_key.end(), std::back_inserter(buffer));
ww::types::ByteArray computed_hash;
if (! ww::crypto::crypto_hash(buffer, computed_hash))
return rsp.error("failed to compute the hash for metadata comparison");
ww::types::ByteArray decoded_ledger_meta_hash;
if (! ww::crypto::b64_decode(ledger_meta_hash, decoded_ledger_meta_hash))
return rsp.error("failed to decoded ledger code hash");
if (computed_hash != decoded_ledger_meta_hash)
return rsp.error("computed metadata hash not the same as the stored hash");
}
// now store the information about the endpoint
if (! add_endpoint(contract_id, verifying_key, encryption_key))
return rsp.error("unexpected error, failed to store endpoint information");
return rsp.success(true);
}
// -----------------------------------------------------------------
// Some functions for managing the ledger key
// -----------------------------------------------------------------
bool ww::contract::attestation::set_ledger_key(const std::string& ledger_verifying_key)
{
return contract_attestation_store.set(ledger_key, ledger_verifying_key);
}
bool ww::contract::attestation::get_ledger_key(std::string& ledger_verifying_key)
{
return contract_attestation_store.get(ledger_key, ledger_verifying_key);
}
// -----------------------------------------------------------------
// Some functions for managing the code hash
// -----------------------------------------------------------------
bool ww::contract::attestation::set_code_hash(const ww::types::ByteArray& code_hash)
{
return contract_attestation_store.set(code_hash_key, code_hash);
}
bool ww::contract::attestation::get_code_hash(ww::types::ByteArray& code_hash)
{
return contract_attestation_store.get(code_hash_key, code_hash);
}
bool ww::contract::attestation::compute_code_hash(ww::types::ByteArray& code_hash)
{
ww::types::ByteArray code_buffer;
if (! KeyValueStore::privileged_get("ContractCode.Code", code_buffer))
return false;
ww::types::ByteArray name;
if (! KeyValueStore::privileged_get("ContractCode.Name", name))
return false;
std::copy(name.begin(), name.end(), std::back_inserter(code_buffer));
if (! ww::crypto::crypto_hash(code_buffer, code_hash))
return false;
return true;
}
// -----------------------------------------------------------------
// Some functions for managing the endpoint registry
// -----------------------------------------------------------------
static const std::string ep_verifying_key("verifying_key");
static const std::string ep_encryption_key("encryption_key");
bool ww::contract::attestation::add_endpoint(
const std::string& contract_id,
const std::string& verifying_key,
const std::string& encryption_key)
{
// now store the information about the endpoint
ww::value::Object endpoint_information;
endpoint_information.set_string("verifying_key", verifying_key.c_str());
endpoint_information.set_string("encryption_key", encryption_key.c_str());
std::string serialized_endpoint_information;
if (! endpoint_information.serialize(serialized_endpoint_information))
{
CONTRACT_SAFE_LOG(3, "failed to serialize endpoint information");
return false;
}
if (! contract_endpoint_store.set(contract_id, serialized_endpoint_information))
{
CONTRACT_SAFE_LOG(3, "failed to save the endpoint information");
return false;
}
return true;
}
bool ww::contract::attestation::get_endpoint(
const std::string& contract_id,
std::string& verifying_key,
std::string& encryption_key)
{
std::string serialized_endpoint_information;
if (! contract_endpoint_store.get(contract_id, serialized_endpoint_information))
{
CONTRACT_SAFE_LOG(1, "endpoint not registered");
return false;
}
ww::value::Object endpoint_information;
if (! endpoint_information.deserialize(serialized_endpoint_information.c_str()))
{
CONTRACT_SAFE_LOG(3, "unexpected error, failed to deserialize endpoint information");
return false;
}
verifying_key = endpoint_information.get_string(ep_verifying_key.c_str());
encryption_key = endpoint_information.get_string(ep_encryption_key.c_str());
return true;
}
| 39.402667 | 100 | 0.709529 | [
"object"
] |
9ac71f3e982258375c2d8c96b582ac3731bcab94 | 8,130 | cpp | C++ | tree_detection/src/TreeDetector.cpp | leggedrobotics/tree_detection | eaec3a5909ba95743854cb1b7a31c748a161a8fe | [
"BSD-3-Clause"
] | 24 | 2021-08-31T08:22:14.000Z | 2022-03-31T15:53:43.000Z | tree_detection/src/TreeDetector.cpp | leggedrobotics/tree_detection | eaec3a5909ba95743854cb1b7a31c748a161a8fe | [
"BSD-3-Clause"
] | 3 | 2022-02-07T15:23:00.000Z | 2022-02-23T14:45:54.000Z | tree_detection/src/TreeDetector.cpp | leggedrobotics/tree_detection | eaec3a5909ba95743854cb1b7a31c748a161a8fe | [
"BSD-3-Clause"
] | 7 | 2021-11-27T06:43:45.000Z | 2022-03-27T12:44:58.000Z | #include "tree_detection/TreeDetector.hpp"
#include <pcl/common/common.h>
#include <pcl/common/pca.h>
#include <pcl/filters/crop_box.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/segmentation/extract_clusters.h>
namespace tree_detection {
void TreeDetector::setTreeDetectionParameters(const TreeDetectionParameters &p) {
treeDetectionParam_ = p;
}
const TreeDetectionParameters& TreeDetector::getParameters() const {
return treeDetectionParam_;
}
void TreeDetector::setInputPointCloudPtr(PointCloud::Ptr inputCloud) {
inputCloud_.reset();
inputCloud_ = inputCloud;
}
void TreeDetector::setInputPointCloud(const PointCloud &inputCloud) {
inputCloud_.reset(new PointCloud());
*inputCloud_ = inputCloud;
}
void TreeDetector::detectTrees() {
const auto startTime = std::chrono::steady_clock::now();
detectedTreeClusters_.clear();
//safety check
if (inputCloud_->empty()) {
std::cout << "[TreeDetector] inputCloud is empty. Returning. \n";
return;
}
PointIndices setsOfClusterIndices = extractClusterIndices(inputCloud_);
auto validClusters = extractValidPointClusters(setsOfClusterIndices, inputCloud_);
if (validClusters.empty()) {
std::cout << "[TreeDetector] No valid clusters found\n";
return;
}
auto clusterInfo = extractClusterInformation(validClusters);
detectedTreeClusters_ = clusterInfo;
namespace ch = std::chrono;
const auto endTime = std::chrono::steady_clock::now();
double numSec = ch::duration_cast<ch::microseconds>(endTime - startTime).count() / 1e6;
if (treeDetectionParam_.isPrintTiming_) {
std::cout << "Tree detection took: " << numSec << " seconds \n";
}
std::cout << "[TreeDetector]: " << detectedTreeClusters_.size() << " trees were detected \n";
}
const TreeDetector::ClusterVector& TreeDetector::getDetectedTreeClusters() const {
return detectedTreeClusters_;
}
PointIndices TreeDetector::extractClusterIndices(const PointCloud::ConstPtr cloud) const {
pcl::search::KdTree<pcl::PointXYZ>::Ptr kdTree(new pcl::search::KdTree<pcl::PointXYZ>);
kdTree->setInputCloud(cloud);
PointIndices clusterIndices;
pcl::EuclideanClusterExtraction<pcl::PointXYZ> euclideanClusterExtraction;
euclideanClusterExtraction.setClusterTolerance(treeDetectionParam_.clusterTolerance_);
euclideanClusterExtraction.setMinClusterSize(treeDetectionParam_.minNumPointsTree_);
euclideanClusterExtraction.setMaxClusterSize(treeDetectionParam_.maxNumPointsTree_);
euclideanClusterExtraction.setSearchMethod(kdTree);
euclideanClusterExtraction.setInputCloud(cloud);
euclideanClusterExtraction.extract(clusterIndices);
// std::cout << "Min cluster size: " << euclideanClusterExtraction.getMinClusterSize() << "\n";
// std::cout << "Max cluster size: " << euclideanClusterExtraction.getMaxClusterSize() << "\n";
// std::cout << "Cluster tolerance: " << euclideanClusterExtraction.getClusterTolerance() << "\n";
std::cout << "[TreeDetector]: " << clusterIndices.size() << " clusters from cloud extracted." << "\n";
return clusterIndices;
}
PointCloudPtrVector TreeDetector::extractValidPointClusters(const PointIndices &setOfClusterIndices,
PointCloud::ConstPtr cloud) const {
//these clusters are hopefully trees
PointCloudPtrVector validClusters;
for (std::vector<pcl::PointIndices>::const_iterator it = setOfClusterIndices.begin();
it != setOfClusterIndices.end(); ++it) {
PointCloud::Ptr cloudCluster = extractClusterFromIndices(it->indices, cloud);
const bool isDiscardCluster = !isGravityAlignmentStraightEnough(cloudCluster) || isClusterTooLow(cloudCluster)
|| isClusterRadiusTooBig(cloudCluster);
if (isDiscardCluster) {
continue;
}
validClusters.push_back(PointCloud::Ptr(new PointCloud()));
validClusters.back() = cloudCluster;
}
return validClusters;
}
PointCloud::Ptr TreeDetector::extractClusterFromIndices(const std::vector<int> &indices,
PointCloud::ConstPtr cloud) const {
PointCloud::Ptr cloudCluster(new PointCloud);
for (auto index : indices) {
cloudCluster->points.push_back(cloud->points[index]);
}
cloudCluster->width = cloudCluster->points.size();
cloudCluster->height = 1;
cloudCluster->is_dense = true;
return cloudCluster;
}
bool TreeDetector::isClusterTooLow(PointCloud::ConstPtr cloudCluster) const {
auto clusterDimension = getClusterDimensions(cloudCluster);
//discard if too low
if (clusterDimension.dimZ_ < treeDetectionParam_.minHeightTree_) {
if (treeDetectionParam_.isPrintDiscardedTreeInstances_) {
std::cout << "Discard cluster candidate with height " << clusterDimension.dimZ_ << "m. \n";
}
return true;
}
return false;
}
bool TreeDetector::isClusterRadiusTooBig(PointCloud::ConstPtr cloudCluster) const {
auto clusterDimension = getClusterDimensions(cloudCluster);
//discard if diameter wrong
if (clusterDimension.dimX_ > treeDetectionParam_.maxDiameterTree_
|| clusterDimension.dimY_ > treeDetectionParam_.maxDiameterTree_) {
if (treeDetectionParam_.isPrintDiscardedTreeInstances_) {
std::cout << "Discard cluster with width in x axis " << clusterDimension.dimX_ << "m. \n";
std::cout << "Width in y axis " << clusterDimension.dimY_ << "m. \n";
}
return true;
}
return false;
}
ClusterDimensions TreeDetector::getClusterDimensions(PointCloud::ConstPtr clusterCloud) const {
pcl::PointXYZ minPt, maxPt;
pcl::getMinMax3D(*clusterCloud, minPt, maxPt);
ClusterDimensions clusterDimensions;
clusterDimensions.dimX_ = maxPt.x - minPt.x;
clusterDimensions.dimY_ = maxPt.y - minPt.y;
clusterDimensions.dimZ_ = maxPt.z - minPt.z;
// std::cout << "Max x: " << maxPt.x << std::endl;
// std::cout << "Max y: " << maxPt.y << std::endl;
// std::cout << "Max z: " << maxPt.z << std::endl;
// std::cout << "Min x: " << minPt.x << std::endl;
// std::cout << "Min y: " << minPt.y << std::endl;
// std::cout << "Min z: " << minPt.z << std::endl;
return clusterDimensions;
}
bool TreeDetector::isGravityAlignmentStraightEnough(PointCloud::ConstPtr cloudCluster) const {
double gravityAlignement = getClusterGravityAlignment(cloudCluster);
// ROS_DEBUG_STREAM("Gravity Alignment: " << gravityAlignement);
if (gravityAlignement > treeDetectionParam_.minEigenVectorAlignment_) {
return true;
} else {
if (treeDetectionParam_.isPrintDiscardedTreeInstances_) {
std::cout << "Discarding because the the gravity alignment " << gravityAlignement << " is less than: "
<< treeDetectionParam_.minEigenVectorAlignment_ << "\n";
}
return false;
}
}
double TreeDetector::getClusterGravityAlignment(PointCloud::ConstPtr cloudCluster) const {
pcl::PCA<pcl::PointXYZ> cloudPCA = new pcl::PCA<pcl::PointXYZ>;
cloudPCA.setInputCloud(cloudCluster);
Eigen::Matrix3f eigenVectors = cloudPCA.getEigenVectors();
Eigen::Vector3f gravityAligned = Eigen::Vector3f::UnitZ();
Eigen::Vector3f principleAxis = eigenVectors.col(0);
double principleAxisAlignment = std::abs(principleAxis.dot(gravityAligned));
std::pair<Eigen::Vector3d, double> returnValue;
return principleAxisAlignment;
}
Eigen::Vector3d TreeDetector::getClusterMean(PointCloud::ConstPtr cloudCluster) const {
// pcl::PCA<pcl::PointXYZ> cloudPCA = new pcl::PCA<pcl::PointXYZ>;
// cloudPCA.setInputCloud(cloudCluster);
// Eigen::Vector4f mean = cloudPCA.getMean();
const int N = cloudCluster->size();
double meanX = 0, meanY = 0, meanZ = 0;
for (int i = 0; i < N; ++i) {
meanX += cloudCluster->points.at(i).x;
meanY += cloudCluster->points.at(i).y;
meanZ += cloudCluster->points.at(i).z;
}
return Eigen::Vector3d(meanX / N, meanY / N, meanZ / N);
}
TreeDetector::ClusterVector TreeDetector::extractClusterInformation(const PointCloudPtrVector &validClusters) const {
auto clusterCloudToCluster = [this](const PointCloud::Ptr cloud) {
Cluster cluster;
cluster.position_ = getClusterMean(cloud);
cluster.clusterDimensions_ = getClusterDimensions(cloud);
return cluster;
};
std::vector<Cluster> clusters;
clusters.reserve(validClusters.size());
for (int i = 0; i < validClusters.size(); ++i) {
Cluster c = clusterCloudToCluster(validClusters.at(i));
clusters.push_back(c);
}
return clusters;
}
} // namespace tree_detection
| 34.449153 | 117 | 0.748462 | [
"vector"
] |
9ac7f2eb7cd63dc86a937f4b46433180d0fca81d | 10,520 | cpp | C++ | src/iat_record.cpp | darkise/ROS-Audio | 886020ff04f43c24138d3b3e1ffd5a22a8dfa088 | [
"Apache-2.0"
] | 1 | 2019-10-25T12:35:07.000Z | 2019-10-25T12:35:07.000Z | src/iat_record.cpp | darkise/ROS-Audio | 886020ff04f43c24138d3b3e1ffd5a22a8dfa088 | [
"Apache-2.0"
] | null | null | null | src/iat_record.cpp | darkise/ROS-Audio | 886020ff04f43c24138d3b3e1ffd5a22a8dfa088 | [
"Apache-2.0"
] | 2 | 2019-04-24T07:49:30.000Z | 2019-06-26T05:47:07.000Z | /*
* 语音听写(iFly Auto Transform)技术能够实时地将语音转换成对应的文字。
*/
/*
Copyright 2018 Alex Wang
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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "qisr.h"
#include "msp_cmn.h"
#include "msp_errors.h"
#include "speech_recognizer.h"
#include <iconv.h>
/* for ROS and C++*/
#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Int8.h>
#include <std_msgs/String.h>
#include <serial/serial.h>
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
#define FRAME_LEN 640
#define BUFFER_SIZE 4096
/* microphone mode */
#define eMicPhone_Closed 0
#define eMicPhone_Activate 1
#define eMicPhone_Communicate 2
#define eMicPhone_Communicate_Quit -2
/* UART COMMAND */
#define VERSION "VER\n"
#define RESET "RESET\n"
#define TALK "CALL_MODE 1\n"
#define LOCALIZATION "CALL_MODE 0\n"
#define WAKE_UP_YES "WAKEUP 1\n"
#define WAKE_UP_NO "WAKEUP 0\n"
#define BEAM_0 "BEAM 0\n"
#define BEAM_1 "BEAM 1\n"
#define BEAM_2 "BEAM 2\n"
#define BEAM_3 "BEAM 3\n"
#define BEAM_4 "BEAM 4\n"
#define BEAM_5 "BEAM 5\n"
static void show_result(char *string, char is_over)
{
printf("\rResult:[ %s ]", string);
if(is_over)
putchar('\n');
}
static char *g_result = NULL;
static unsigned int g_buffersize = BUFFER_SIZE;
void on_result(const char *result, char is_last)
{
if (result) {
size_t left = g_buffersize - 1 - strlen(g_result);
size_t size = strlen(result);
if (left < size) {
g_result = (char*)realloc(g_result, g_buffersize + BUFFER_SIZE);
if (g_result)
g_buffersize += BUFFER_SIZE;
else {
printf("mem alloc failed\n");
return;
}
}
strncat(g_result, result, size);
show_result(g_result, is_last);
}
}
void on_speech_begin()
{
if (g_result)
{
free(g_result);
}
g_result = (char*)malloc(BUFFER_SIZE);
g_buffersize = BUFFER_SIZE;
memset(g_result, 0, g_buffersize);
printf("Start Listening...\n");
}
void on_speech_end(int reason)
{
if (reason == END_REASON_VAD_DETECT)
{
printf("\nSpeaking done \n");
}
else
printf("\nRecognizer error %d\n", reason);
}
/* demo recognize the audio from microphone */
static void demo_mic( char* session_begin_params) /* const char* session_begin_params */
{
int errcode;
int i = 0;
struct speech_rec iat;
struct speech_rec_notifier recnotifier = {
on_result,
on_speech_begin,
on_speech_end
};
errcode = sr_init(&iat, session_begin_params, SR_MIC, &recnotifier);
if (errcode) {
printf("speech recognizer init failed\n");
return;
}
errcode = sr_start_listening(&iat);
if (errcode) {
printf("start listen failed %d\n", errcode);
}
/* demo 10 seconds recording */
while(i++ < 10)
{
sleep(1);
}
errcode = sr_stop_listening(&iat);
if (errcode) {
printf("stop listening failed %d\n", errcode);
}
sr_uninit(&iat);
}
/* the mode of the microphone */
volatile int microphone_mode;
volatile int microphone_mode_cmd;
void microphone_cmd_cb(const std_msgs::Int8ConstPtr &msg)
{
if(msg->data == 0)
{
microphone_mode_cmd = eMicPhone_Closed;
//cout << "microphone mode: Closed" << endl;
}
if(msg->data == 2)
{
microphone_mode_cmd = eMicPhone_Communicate;
//cout << "microphone mode: Communicate" << endl;
}
if(msg->data == -2)
{
microphone_mode_cmd = eMicPhone_Communicate_Quit;
//cout << "microphone mode: Communicate_Quit" << endl;
}
}
/* main thread: start/stop record ; query the result of recgonization.
* record thread: record callback(data write)
* helper thread: ui(keystroke detection)
*/
int main(int argc, char* argv[])
{
/* ros */
ros::init(argc, argv, "ros_audio");
ros::NodeHandle nh;
/* publish the microphone state information */
ros::Publisher mode_info_pub = nh.advertise<std_msgs::Int8>("microphone_mode_info", 1000);
std_msgs::Int8 mode_info;
/* publish the wake up angle */
ros::Publisher angle_pub = nh.advertise<std_msgs::Int8>("wake_up_angle", 1000);
std_msgs::Int8 angle_info;
/* publish communication cmd */
ros::Publisher communicate_pub = nh.advertise<std_msgs::Bool>("communicate",1000);
std_msgs::Bool communicate_mode;
/* subscribe microphone command to change the state of 6MIC ARRAY */
ros::Subscriber microphone_cmd_sub = nh.subscribe("microphone_mode_cmd",1000,microphone_cmd_cb);
ros::AsyncSpinner spinner(4);
spinner.start();
init:
/*set Serial Port values*/
serial::Serial ser;
try
{
/* Port need to be changed accordin to system settings */
ser.setPort("/dev/ttyUSB0");
ser.setBaudrate(115200);
serial::Timeout time_out = serial::Timeout::simpleTimeout(1000);
ser.setTimeout(time_out);
ser.setStopbits(serial::stopbits_one);
ser.setFlowcontrol(serial::flowcontrol_none);
ser.setParity(serial::parity_none);
ser.open();
}
catch (serial::IOException& e)
{
ROS_ERROR_STREAM("Unable to open Serial Port");
return -1;
/* bash command */
//system("echo 'passwd' | sudo -S chmod 777 /dev/ttyUSB* ");
//goto init;
}
/* make sure the Serial Port is opened */
if(ser.isOpen())
{
ROS_INFO_STREAM("Serial Port initialized");
}
else
{
goto init;
}
/* the angle when waked up */
int angle;
/* SDK from IFlytek*/
int ret = MSP_SUCCESS;
int upload_on = 1; /* whether upload the user word */
/* login params, please do keep the appid correct */
const char* login_params = "appid = 5b0f9ad2, work_dir = .";
int aud_src = 0; /* from mic or file */
int next = 0;
bool activated = false;
/*
* See "iFlytek MSC Reference Manual"
*/
char* session_begin_params =
"sub = iat, domain = iat, language = zh_cn, "
"accent = mandarin, sample_rate = 16000, "
"result_type = plain, result_encoding = utf8";
/* Login first. the 1st arg is username, the 2nd arg is password
* just set them as NULL. the 3rd arg is login paramertes
* */
ret = MSPLogin(NULL, NULL, login_params);
if (MSP_SUCCESS != ret) {
printf("MSPLogin failed , Error code %d.\n",ret);
goto exit; // login fail, exit the program
}
cout << "If you want to use the microphone, please activate it first or please use the communicate mode ..!" << endl;
while(ros::ok())
{
aud_src = 1;
if(aud_src != 0)
{
/* if the mode command is the communication, change it */
if(microphone_mode_cmd == eMicPhone_Communicate)
{
microphone_mode = eMicPhone_Communicate;
cout << "change to communicating mode ..." << endl;
ser.write(TALK);
mode_info.data = eMicPhone_Communicate;
mode_info_pub.publish(mode_info);
communicate_mode.data = true;
communicate_pub.publish(communicate_mode);
ros::Duration(5).sleep();
microphone_mode_cmd = -99;
}
/* when communication is done */
if(microphone_mode_cmd == eMicPhone_Communicate_Quit)
{
microphone_mode = eMicPhone_Communicate_Quit;
cout << "quit communicating mode ..." << endl;
mode_info.data = eMicPhone_Communicate_Quit;
mode_info_pub.publish(mode_info);
communicate_mode.data = false;
communicate_pub.publish(communicate_mode);
ros::Duration(5).sleep();
microphone_mode_cmd = -99;
}
activate:
/* process the activate mode here */
if(microphone_mode != eMicPhone_Communicate)
{
/* wake up and localization mode */
ser.write(LOCALIZATION);
ser.write(WAKE_UP_YES);
/* read Serial data */
if(ser.available())
{
/* if we get the wake-up angle, we know the microphone is activated */
std_msgs::String result;
result.data = ser.read(ser.available());
string s = result.data;
/* get the angle */
int pos = s.find("angle:");
if(pos != -1 )
{
cout << " activated! " << endl;
/* activation mode */
microphone_mode = eMicPhone_Activate;
mode_info.data = eMicPhone_Activate;
mode_info_pub.publish(mode_info);
activated = true;
/* get the angle */
string ang;
ang = s.substr(pos+6,3);
stringstream ss;
ss << ang;
ss >> angle;
cout << "angle=" << angle << endl;
angle_info.data = angle;
angle_pub.publish(angle_info);
}
else
{
if(microphone_mode != eMicPhone_Activate)
{
//ROS_INFO_STREAM("Please activate the microphone !" << endl);
goto activate;
}
}
}
/* if the microphone is activated, we then get the audio result recognized by SDK and do what we want */
if(microphone_mode == eMicPhone_Activate)
{
printf(" Recognizing the speech from microphone\n");
printf("Speak in 10 seconds\n");
demo_mic(session_begin_params);
printf("10 sec passed\n");
string audio = g_result;
if(!audio.empty())
{
/*remove punctuation*/
audio.erase(audio.size()-3,3);
cout << "received " << audio << endl;
/* do Semantic Analysis */
}
else
{
close:
/* if the microphone is activated and no audio result received, then we close it */
if(microphone_mode != eMicPhone_Closed)
{
cout << "No audio data received, closing soon..." << endl;
cout << "If you want to use the microphone, please reactivate it !" << endl;
/* reset and will receive no audio result */
ser.write(RESET);
/* closed mode */
microphone_mode = eMicPhone_Closed;
mode_info.data = eMicPhone_Closed;
mode_info_pub.publish(mode_info);
activated = false;
}
}
}
}
}
}
exit:
MSPLogout(); // Logout...
return 0;
}
| 26.169154 | 119 | 0.635361 | [
"transform"
] |
9ac97ce255ed65995c61471927067dd66ad0d627 | 1,948 | cpp | C++ | algorithm/trie.cpp | nnmmfftt/contest | 71947ce7edd6f1fada27d4ef8faeece903efaa19 | [
"MIT"
] | null | null | null | algorithm/trie.cpp | nnmmfftt/contest | 71947ce7edd6f1fada27d4ef8faeece903efaa19 | [
"MIT"
] | null | null | null | algorithm/trie.cpp | nnmmfftt/contest | 71947ce7edd6f1fada27d4ef8faeece903efaa19 | [
"MIT"
] | null | null | null | #include<stdlib.h>
#include<iostream>
#include<vector>
using namespace std;
typedef struct trie {
int val;
trie* next[26];
trie() {
val = 0;
memset(next, 0, sizeof(next));
}
}Trie;
int trie_insert_str(Trie *root, string s) {
int len = s.size();
if (len == 0)
return 0;
for (int i = 0; i < len; ++i) {
if (root->next[s[i] - 'a'] == NULL) {
root->next[s[i] - 'a'] = new struct trie;
}
if (!root->next[s[i] - 'a'])
goto out;
root = root->next[s[i] - 'a'];
root->val++;
}
return 0;
out:
return -1;
}
string max_match(Trie* root, string s) {
int len = s.size();
string ret;
if (len == 0)
return 0;
for (int i = 0; i < len; ++i) {
ret = s.substr(0, root->next[s[i] - 'a']->val);
if (root->next[s[i] - 'a'] == NULL)
return false;
root = root->next[s[i] - 'a'];
}
return ret;
}
int trie_max_prefix(Trie* root, string s) {
int len = s.size();
if (len == 0)
return 0;
for (int i = 0; i < len; ++i) {
if (root->next[s[i] - 'a'] == NULL)
return 0;
root = root->next[s[i] - 'a'];
}
return root->val;
}
int match(Trie* root, string s) {
int len = s.size();
if (len == 0)
return 0;
for (int i = 0; i < len; ++i) {
if (root->next[s[i] - 'a'] == NULL)
return false;
else root = root->next[s[i] - 'a'];
}
return true;
}
int trie_delete_str(Trie* root, string s) {
int len = s.size();
if (len == 0) return 0;
for (int i = 0; i < len; ++i) {
if (root->next[s[i] - 'a'] == NULL) {
return -1;
}
root = root->next[s[i] - 'a'];
root->val--;
if (root->val == 0) {
delete root;
root = NULL;
}
}return 0;
}
int main() {
trie* root = new Trie();
vector<string> strs = { "banana","ban","bank","abort","abs" };
for (int i = 0; i < strs.size(); ++i) {
int rc = trie_insert_str(root, strs[i]);
if (rc != -1)
continue;
else break;
}
int m;
cin >> m;
while (m--) {
string stmp;
cin >> stmp;
cout << trie_max_prefix(root,stmp) << endl;
}
return 0;
} | 18.912621 | 63 | 0.531314 | [
"vector"
] |
9ad17e52680c75eaab1d0de7d29e5c86df23f1d2 | 15,294 | cpp | C++ | readfile.cpp | GoogleBot42/CS253_HW10 | 7574aa9788918f1c6714c989dcca407e960d9604 | [
"MIT"
] | null | null | null | readfile.cpp | GoogleBot42/CS253_HW10 | 7574aa9788918f1c6714c989dcca407e960d9604 | [
"MIT"
] | null | null | null | readfile.cpp | GoogleBot42/CS253_HW10 | 7574aa9788918f1c6714c989dcca407e960d9604 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include "readfile.h"
using std::cerr;
using std::endl;
using std::vector;
using std::string;
void readList(string filename, vector<string> &list) {
list.resize(0);
std::ifstream file(filename, std::ifstream::in);
if (!file) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
string line;
while (file >> line)
list.push_back(line);
file.close();
}
int getClassNum(const string &filename) {
int uniqueNum;
int clusterNum;
if (sscanf(filename.c_str(), "class%d_%d.pgm", &clusterNum, &uniqueNum) != 2) {
cerr << "Filename " << filename << " must take the form classN_#.pgm." << endl;
exit(-1);
}
return clusterNum;
}
// v----------- For reading pgmimages ---------v
// ascii whitespace lookup table
// includes: ' ', '\n', and '\r'
bool isWhiteSpaceTable [256] = {
false, false, false, false, false, false, false, false, false, false, true, false, false, true, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
};
int isNumTable [256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
inline bool isWhiteSpace(char c) {
//return c == ' ' || c == '\n' || c == '\r';
return isWhiteSpaceTable[(int)c];
}
inline bool toNum(char c, int &val) {
return (val = isNumTable[(int)c]) != -1;
}
inline bool readThreeDigitNum(char c1, char c2, char c3, int &num) {
num = 0;
int n1,n2,n3;
if (!toNum(c1,n1)) return false;
if (isWhiteSpace(c2)) {
// one digit num
num += n1;
} else if (isWhiteSpace(c3)) {
// two digit num
if (!toNum(c2,n2)) return false;
num += n1 * 10;
num += n2;
} else {
// three digit num
if (!toNum(c2,n2) || !toNum(c3,n3)) return false;
num += n1 * 100;
num += n2 * 10;
num += n3;
}
return true;
}
// increments the data pointer passed the current token
// this is very hackish and will only for for parsing tokens
// that are three chars or less if a char is bigger than that
// this function will error upon attempting to pass the token
// the next time it is run
bool increment(char *&data, int &bytesLeft, char &c1, char &c2, char &c3) {
int count = 1;
// get to a place that is whitespace, now we have passed the data that we just read
while (!isWhiteSpace(data[count])) { count++; }
// we should not have gone over anything bigger than three chars
// that would be an error (I am taking advantage that no token will be longer than
// three chars in a text file pgm image)
if (count > 3) {
cerr << "Unrecognized token in file." << endl; // too long
exit(-1);
}
// now skip over all of the whitespace
while (isWhiteSpace(data[count])) { count++; }
bytesLeft -= count;
if (bytesLeft <= 0) {
// out of data
return true;
}
// now we are at some data that is interesting
// update each char so that together they
// represent the token
data += count;
c1 = data[0];
c2 = data[1];
c3 = data[2];
return false; // a least one more byte left to parse
}
// entirely hand written, even faster pgm loader
/* -----------------------------/ ^^^^^^^ \ */
/* / | | * * | | */
/* / | ) | ||\__/ @ \__/ */
/* \/ \ / /----------\______/ \ // '-' */
/* ||=|= ||=|= */
// This function has always been the slowest part of my program
// so I dedicate it my dog Daisy. My favorite stubborn corgi. RIP
void readPGM(const string &filename, histogram &h, int &clusterNum) {
int uniqueNum;
if (sscanf(filename.c_str(), "class%d_%d.pgm", &clusterNum, &uniqueNum) != 2) {
cerr << "Filename " << filename << " must take the form classN_#.pgm." << endl;
exit(-1);
}
int FILE;
char *src;
struct stat statbuf;
FILE = open(filename.c_str(), O_RDONLY);
if (FILE < 0) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
// find the size of the file
if (fstat(FILE,&statbuf) < 0) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
// map to memory
src = (char *)mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, FILE, 0);
if (src == (caddr_t) -1) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
// close file
close(FILE);
char *data = src;
int size = statbuf.st_size;
int bytesLeft = size;
// make sure that there is at least room for a header
// because we assume that below
if (size < 2) {
cerr << "No pgm image file header in " << filename;
cerr << " (Needs a \"P2\")" << endl;
exit(-1);
}
bool outOfMem = false;
char c1, c2, c3;
c1 = data[0];
c2 = data[1];
if (c1 != 'P' || c2 != '2') {
cerr << "No pgm image file header in " << filename;
cerr << " (Needs a \"P2\")" << endl;
exit(-1);
}
// width, height, and image depth
// all of which are static in the programming assignment
// so I am taking advange so I can make it faster :D
outOfMem = increment(data, bytesLeft, c1, c2, c3);
if (outOfMem || c1 != '1' || c2 != '2' || c3 != '8') {
cerr << "No valid width in " << filename << endl;
exit(-1);
}
outOfMem = increment(data, bytesLeft, c1, c2, c3);
if (outOfMem || c1 != '1' || c2 != '2' || c3 != '8') {
cerr << "No valid height in " << filename << endl;
exit(-1);
}
outOfMem = increment(data, bytesLeft, c1, c2, c3);
if (outOfMem || c1 != '2' || c2 != '5' || c3 != '5') {
cerr << filename << " Only 255 can be image depth." << endl;
exit(-1);
}
// now for the actual data
// how many we have parsed
int count = 0;
// when we are done cout should equal EXPECTED_COUNT
const int EXPECTED_COUNT = 128*128;
outOfMem = increment(data, bytesLeft, c1, c2, c3);
while (!outOfMem) {
int value;
if (!readThreeDigitNum(c1,c2,c3,value)) {
cerr << "Only numbers can be in " << filename << endl;
exit(-1);
}
if (value < 0 || value > 255) {
cerr << "\t" << c1 << c2 << c3 << "\t" << value << endl;
cerr << "The numbers in " << filename << " can only range from [0-255]." << endl;
exit(-1);
}
h.addData(value);
count++;
outOfMem = increment(data, bytesLeft, c1, c2, c3);
}
if (count != EXPECTED_COUNT) {
cerr << "Width * Height and data values count mismatch in " << filename << endl;
cerr << "Found " << count << " data values." << endl;
exit(-1);
}
// close memory mapped file
munmap(src,size);
}
// old versions of helper functions
/*inline bool isNum(char c) {
return c >= '0' && c <= '9';
}
inline int toNum(char c) {
return c - '0';
}
inline bool readThreeDigitNum(char c1, char c2, char c3, int &num) {
num = 0;
if (!isNum(c1)) return false;
if (isWhiteSpace(c2)) {
// one digit num
num += toNum(c1);
} else if (isWhiteSpace(c3)) {
// two digit num
if (!isNum(c2)) return false;
num += toNum(c1) * 10;
num += toNum(c2);
} else {
// three digit num
if (!isNum(c2) || !isNum(c3)) return false;
num += toNum(c1) * 100;
num += toNum(c2) * 10;
num += toNum(c3);
}
return true;
}*/
// major editions of the old versions for comparison
/*inline bool readThreeDigitNum(char *s, int &num) {
num = 0;
int length = strlen(s);
if (length > 3) return false;
for (int i=0; i<length; i++) {
num *= 10;
char c = s[i];
if (c >= '0' && c <= '9')
num += c - '0';
else
return false;
}
return true;
}*/
// This function is a rewrite. The old one is below
// This one runs in about half the time because up
// until the rewrite, this function was litterally
// 95% of my runtime.
/*void readPGM(string filename, histogram &h, int &clusterNum, char *buffer) {
int uniqueNum;
if (sscanf(filename.c_str(), "class%d_%d.pgm", &clusterNum, &uniqueNum) != 2) {
cerr << "Filename " << filename << " must take the form classN_#.pgm." << endl;
exit(-1);
}
// not os dependent but slower?
// FILE *f = fopen(filename.c_str(), "r");
//
// if (f == NULL) {
// cerr << "Cannot open " << filename << endl;
// exit(-1);
// }
//
// fseek(f, 0, SEEK_END);
// long fsize = ftell(f);
// fseek(f, 0, SEEK_SET);
// fread(buffer, fsize, 1, f);
// fclose(f);
//
// buffer[fsize] = '\0';
int FILE;
char *src;
struct stat statbuf;
FILE = open(filename.c_str(), O_RDONLY);
if (FILE < 0) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
// find the size of the file
if (fstat(FILE,&statbuf) < 0) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
src = (char *)mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, FILE, 0);
if (src == (caddr_t) -1) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
memcpy(buffer, src, statbuf.st_size);
buffer[statbuf.st_size] = 0;
// create tokenizer
const char *sep = " \r\n";
char *saveptr; // need for the threadsafe version of strtok
char *next = strtok_r(buffer, sep, &saveptr);
if (next == NULL || strcmp(next,"P2") != 0) {
cerr << "No pgm image file header in " << filename;
cerr << " (Needs a \"P2\")" << endl;
exit(-1);
}
// width, height, and image depth
// all of which are static in the programming assignment
// so I am taking advange so I can make it faster :D
next = strtok_r(NULL, sep, &saveptr);
if (next == NULL || strcmp(next, "128")) {
cerr << "No valid width in " << filename << endl;
exit(-1);
}
next = strtok_r(NULL, sep, &saveptr);
if (next == NULL || strcmp(next, "128")) {
cerr << "No valid height in " << filename << endl;
exit(-1);
}
next = strtok_r(NULL, sep, &saveptr);
if (next == NULL || strcmp(next, "255")) {
cerr << filename << " Only 255 can be image depth." << endl;
exit(-1);
}
// now for the actual data
// how many we have parsed
int count = 0;
// when we are done cout should equal EXPECTED_COUNT
const int EXPECTED_COUNT = 128*128;
next = strtok_r(NULL, sep, &saveptr);
while (next != NULL) {
int value;
if (!readThreeDigitNum(next, value)) {
cerr << "Only numbers can be in " << filename << endl;
cerr << "Found \"" << next << "\" instead." << endl;
exit(-1);
}
// too slow
char *end;
// long value = strtol(next, &end, 10);
// if (end == next || *end != '\0' || errno == ERANGE) {
// cerr << "Only numbers can be in " << filename << endl;
// cerr << "Found \"" << next << "\" instead." << endl;
// exit(-1);
// }
if (value < 0 || value > 255) {
cerr << "The numbers in " << filename << " can only range from [0-255]." << endl;
exit(-1);
}
h.addData(value);
count++; next = strtok_r(NULL, sep, &saveptr);
}
if (count != EXPECTED_COUNT) {
cerr << "Width * Height and data values count mismatch in " << filename << endl;
cerr << "Found " << count << " data values." << endl;
exit(-1);
}
}*/
// old version just for comparison
/*void readPGM(string filename, histogram &h, int &clusterNum, char *buffer) {
int width;
int height;
int uniqueNum;
if (sscanf(filename.c_str(), "class%d_%d.pgm", &clusterNum, &uniqueNum) != 2) {
cerr << "Filename " << filename << " must take the form classN_#.pgm." << endl;
exit(-1);
}
std::ifstream inputFile;
inputFile.open(filename.c_str());
if (!inputFile) {
cerr << "Cannot open " << filename << endl;
exit(-1);
}
std::stringstream file;
file << inputFile.rdbuf();
inputFile.close();
char header[128];
file >> header;
if (strcmp(header,"P2")) {
cerr << "No pgm image file header in " << filename;
cerr << " (Needs a \"P2\")" << endl;
exit(-1);
}
file >> width;
file >> height;
if (file.fail()) {
cerr << "No width and height in " << filename << endl;
exit(-1);
}
if (width != 128 && height != 128) {
cerr << "Width and height must be both 128 in " << filename << endl;
exit(-1);
}
int tmp;
file >> tmp;
if (file.fail()) {
cerr << "No max image depth defined in " << filename << endl;
exit(-1);
}
if (tmp != 255) {
cerr << filename << " Only 255 can be the max image width." << endl;
exit(-1);
}
int num;
int count = 0;
while (true) {
file >> num;
if (file.eof() && file.fail()) break;
if (file.fail()) {
cerr << "Only numbers can be in " << filename << endl;
exit(-1);
}
if (num < 0 || num >= 256) {
cerr << "The numbers in " << filename << " can only range from [0-255]." << endl;
exit(-1);
}
count++;
h.addData(num);
}
if (count == 0) {
cerr << filename << " is empty." << endl;
exit(-1);
}
if (width != abs(width) || height != abs(height)) {
cerr << "Error in " << filename << " cannot have a negative width or height" << endl;
exit(-1);
}
if (count != width * height) {
cerr << "Width * Height and data values count mismatch in " << filename << endl;
cerr << "Found " << count << " data values." << endl;
exit(-1);
}
}*/
| 28.165746 | 112 | 0.575258 | [
"vector"
] |
9ad8cd687153a1e43fde4c11261fca05ca2dc287 | 7,693 | cpp | C++ | test/qt/remote_device/messages/test_RemoteMessage.cpp | misery/AusweisApp2 | dab96eb2bdd8a132023964d4aeecc7069d12a244 | [
"Apache-2.0"
] | null | null | null | test/qt/remote_device/messages/test_RemoteMessage.cpp | misery/AusweisApp2 | dab96eb2bdd8a132023964d4aeecc7069d12a244 | [
"Apache-2.0"
] | null | null | null | test/qt/remote_device/messages/test_RemoteMessage.cpp | misery/AusweisApp2 | dab96eb2bdd8a132023964d4aeecc7069d12a244 | [
"Apache-2.0"
] | null | null | null | /*!
* \copyright Copyright (c) 2018 Governikus GmbH & Co. KG, Germany
*/
#include "messages/RemoteMessage.h"
#include "LogHandler.h"
#include <QtTest>
using namespace governikus;
class test_RemoteMessage
: public QObject
{
Q_OBJECT
private:
void checkMissingContextHandle(RemoteCardMessageType type)
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("{\n"
" \"msg\": \"%1\"\n"
"}\n");
const auto& obj = RemoteMessage::parseByteArray(input.replace("%1", QTest::currentDataTag()));
QVERIFY(!obj.isEmpty());
RemoteMessage msg(obj);
QCOMPARE(msg.getType(), type);
QCOMPARE(msg.getContextHandle(), QString());
if (type == RemoteCardMessageType::IFDEstablishContext)
{
QVERIFY(!msg.isIncomplete());
QCOMPARE(logSpy.count(), 0);
return;
}
QVERIFY(msg.isIncomplete());
if (type != RemoteCardMessageType::UNDEFINED)
{
QCOMPARE(logSpy.count(), 1);
QVERIFY(logSpy.at(0).at(0).toString().contains(QString("Missing value \"ContextHandle\"")));
return;
}
QCOMPARE(logSpy.count(), 2);
QVERIFY(logSpy.at(0).at(0).toString().contains(QString("Invalid messageType received: \"")));
QVERIFY(logSpy.at(1).at(0).toString().contains(QString("Missing value \"ContextHandle\"")));
}
void checkEmptyContextHandle(RemoteCardMessageType type)
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("{\n"
" \"ContextHandle\": \"\",\n"
" \"msg\": \"%1\"\n"
"}\n");
const auto& obj = RemoteMessage::parseByteArray(input.replace("%1", QTest::currentDataTag()));
QVERIFY(!obj.isEmpty());
RemoteMessage msg(obj);
QCOMPARE(msg.getType(), type);
QCOMPARE(msg.getContextHandle(), QString());
if (type != RemoteCardMessageType::UNDEFINED)
{
QVERIFY(!msg.isIncomplete());
QCOMPARE(logSpy.count(), 0);
return;
}
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 1);
QVERIFY(logSpy.at(0).at(0).toString().contains(QString("Invalid messageType received: \"")));
}
void checkValidContextHandle(RemoteCardMessageType type)
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("{\n"
" \"ContextHandle\": \"TestContext\",\n"
" \"msg\": \"%1\"\n"
"}\n");
const auto& obj = RemoteMessage::parseByteArray(input.replace("%1", QTest::currentDataTag()));
QVERIFY(!obj.isEmpty());
RemoteMessage msg(obj);
QCOMPARE(msg.getType(), type);
if (type == RemoteCardMessageType::IFDEstablishContext)
{
QCOMPARE(msg.getContextHandle(), QString());
QVERIFY(!msg.isIncomplete());
QCOMPARE(logSpy.count(), 0);
return;
}
QCOMPARE(msg.getContextHandle(), QString("TestContext"));
if (type != RemoteCardMessageType::UNDEFINED)
{
QVERIFY(!msg.isIncomplete());
QCOMPARE(logSpy.count(), 0);
return;
}
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 1);
QVERIFY(logSpy.at(0).at(0).toString().contains(QString("Invalid messageType received: \"")));
}
private Q_SLOTS:
void initTestCase()
{
Env::getSingleton<LogHandler>()->init();
}
void invalidJson()
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("FooBar");
const auto& obj = RemoteMessage::parseByteArray(input);
QVERIFY(obj.isEmpty());
RemoteMessage msg(obj);
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 5);
QVERIFY(logSpy.at(0).at(0).toString().contains("Json parsing failed. 1 : \"illegal value\""));
QVERIFY(logSpy.at(1).at(0).toString().contains("Expected object at top level"));
QVERIFY(logSpy.at(2).at(0).toString().contains("Missing value \"msg\""));
QVERIFY(logSpy.at(3).at(0).toString().contains("Invalid messageType received: \"\""));
QVERIFY(logSpy.at(4).at(0).toString().contains("Missing value \"ContextHandle\""));
}
void missingObject()
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("[]");
const auto& obj = RemoteMessage::parseByteArray(input);
QVERIFY(obj.isEmpty());
RemoteMessage msg(obj);
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 4);
QVERIFY(logSpy.at(0).at(0).toString().contains("Expected object at top level"));
QVERIFY(logSpy.at(1).at(0).toString().contains("Missing value \"msg\""));
QVERIFY(logSpy.at(2).at(0).toString().contains("Invalid messageType received: \"\""));
QVERIFY(logSpy.at(3).at(0).toString().contains("Missing value \"ContextHandle\""));
}
void emptyObject()
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("{}");
const auto& obj = RemoteMessage::parseByteArray(input);
QVERIFY(obj.isEmpty());
RemoteMessage msg(obj);
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 4);
QVERIFY(logSpy.at(0).at(0).toString().contains("Expected object at top level"));
QVERIFY(logSpy.at(1).at(0).toString().contains("Missing value \"msg\""));
QVERIFY(logSpy.at(2).at(0).toString().contains("Invalid messageType received: \"\""));
QVERIFY(logSpy.at(3).at(0).toString().contains("Missing value \"ContextHandle\""));
}
void missingMessageType()
{
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("{\n"
" \"ContextHandle\": \"TestContext\"\n"
"}\n");
const auto& obj = RemoteMessage::parseByteArray(input.replace(50, 2, QTest::currentDataTag()));
QVERIFY(!obj.isEmpty());
RemoteMessage msg(obj);
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 2);
QVERIFY(logSpy.at(0).at(0).toString().contains(QString("Missing value \"msg\"")));
QVERIFY(logSpy.at(1).at(0).toString().contains(QString("Invalid messageType received: \"\"")));
}
void messageType_data()
{
QTest::addColumn<RemoteCardMessageType>("type");
QTest::newRow("") << RemoteCardMessageType::UNDEFINED;
const auto& typeList = Enum<RemoteCardMessageType>::getList();
for (const auto& type : typeList)
{
QTest::newRow(getEnumName(type).data()) << type;
}
QTest::newRow("unknown") << RemoteCardMessageType::UNDEFINED;
}
void messageType()
{
QFETCH(RemoteCardMessageType, type);
QSignalSpy logSpy(Env::getSingleton<LogHandler>(), &LogHandler::fireLog);
QByteArray input("{\n"
" \"ContextHandle\": \"TestContext\",\n"
" \"msg\": \"%1\"\n"
"}\n");
const auto& obj = RemoteMessage::parseByteArray(input.replace("%1", QTest::currentDataTag()));
QVERIFY(!obj.isEmpty());
RemoteMessage msg(obj);
QCOMPARE(msg.getType(), type);
if (type != RemoteCardMessageType::UNDEFINED)
{
QVERIFY(!msg.isIncomplete());
QCOMPARE(logSpy.count(), 0);
return;
}
QVERIFY(msg.isIncomplete());
QCOMPARE(logSpy.count(), 1);
QVERIFY(logSpy.at(0).at(0).toString().contains(QString("Invalid messageType received: \"")));
}
void contextHandle_data()
{
QTest::addColumn<RemoteCardMessageType>("type");
QTest::newRow("") << RemoteCardMessageType::UNDEFINED;
const auto& msgTypes = Enum<RemoteCardMessageType>::getList();
for (const auto& type : msgTypes)
{
QTest::newRow(getEnumName(type).data()) << type;
}
QTest::newRow("unknown") << RemoteCardMessageType::UNDEFINED;
}
void contextHandle()
{
QFETCH(RemoteCardMessageType, type);
checkMissingContextHandle(type);
checkEmptyContextHandle(type);
checkValidContextHandle(type);
}
};
QTEST_GUILESS_MAIN(test_RemoteMessage)
#include "test_RemoteMessage.moc"
| 27.772563 | 98 | 0.658651 | [
"object"
] |
9ad8f35609e714ba785fae798c66d10403d09e4d | 4,326 | cc | C++ | tests/utils/test_compressor.cc | dvuckovic/eckit | 58a918e7be8fe073f37683abf639374ab1ad3e4f | [
"Apache-2.0"
] | 10 | 2018-03-01T22:11:10.000Z | 2021-05-17T14:13:58.000Z | tests/utils/test_compressor.cc | dvuckovic/eckit | 58a918e7be8fe073f37683abf639374ab1ad3e4f | [
"Apache-2.0"
] | 43 | 2018-04-11T11:13:44.000Z | 2022-03-31T15:28:03.000Z | tests/utils/test_compressor.cc | dvuckovic/eckit | 58a918e7be8fe073f37683abf639374ab1ad3e4f | [
"Apache-2.0"
] | 20 | 2018-03-07T21:36:50.000Z | 2022-03-30T13:25:25.000Z | /*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include <cstring>
#include <iostream>
#include <memory>
#include "eckit/io/Buffer.h"
#include "eckit/utils/Compressor.h"
#include "eckit/utils/MD5.h"
#include "eckit/testing/Test.h"
using namespace std;
using namespace eckit;
using namespace eckit::testing;
namespace eckit {
namespace test {
static std::string msg("THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG'S BACK 1234567890");
static std::vector<std::string> compressions{"none", "snappy", "lz4", "bzip2", "aec"};
//----------------------------------------------------------------------------------------------------------------------
void EXPECT_compress_uncompress_1(Compressor& c, const Buffer& in, size_t ulen) {
// Buffers are not allocated. The compress/uncompress will do so as required
Buffer compressed;
Buffer uncompressed;
size_t clen = c.compress(in, ulen, compressed);
c.uncompress(compressed, clen, uncompressed, ulen);
EXPECT(std::memcmp(uncompressed, in, ulen) == 0);
}
void EXPECT_compress_uncompress_2(Compressor& c, const Buffer& in, size_t ulen) {
// Buffers are pre-allocated. This may allow implementation dependent optimizations
Buffer compressed(size_t(1.2 * ulen));
Buffer uncompressed(size_t(1.2 * ulen));
size_t clen = c.compress(in, ulen, compressed);
c.uncompress(compressed, clen, uncompressed, ulen);
EXPECT(std::memcmp(uncompressed, in, ulen) == 0);
}
void EXPECT_reproducible_compression(Compressor& c, size_t times) {
std::vector<size_t> reproduce_lengths;
std::vector<std::string> reproduce_checksum;
for (size_t i = 0; i < times + 1; ++i) {
Buffer uncompressed(msg.data(), msg.size());
Buffer compressed;
size_t compressed_size = c.compress(uncompressed, uncompressed.size(), compressed);
reproduce_lengths.emplace_back(compressed_size);
reproduce_checksum.emplace_back(eckit::MD5(compressed, compressed_size));
}
const auto& ref_length = reproduce_lengths.front();
bool reproducible_length{true};
for (auto& length : reproduce_lengths) {
if (length != ref_length) {
reproducible_length = false;
}
}
EXPECT(reproducible_length);
const auto& ref_checksum = reproduce_checksum.front();
bool reproducible_checksum{true};
for (auto& checksum : reproduce_checksum) {
if (checksum != ref_checksum) {
reproducible_checksum = false;
}
}
EXPECT(reproducible_checksum);
}
CASE("Builders") {
std::unique_ptr<Compressor> c;
SECTION("CASE No Compression - case insensitive") {
EXPECT_NO_THROW(c.reset(CompressorFactory::instance().build("nOnE")));
}
SECTION("Not Existing Compression") {
EXPECT_THROWS(c.reset(CompressorFactory::instance().build("dummy name")));
}
}
CASE("Compression") {
Buffer in(2 * msg.size()); // oversized on purpose
in.copy(msg.c_str(), msg.size());
const size_t len = msg.size(); // valid size
std::unique_ptr<Compressor> c;
SECTION("CASE Default Compression") {
EXPECT_NO_THROW(c.reset(CompressorFactory::instance().build()));
EXPECT_compress_uncompress_1(*c, in, len);
EXPECT_compress_uncompress_2(*c, in, len);
}
for (const auto& compression : compressions) {
SECTION("CASE " + compression) {
if (CompressorFactory::instance().has(compression)) {
EXPECT_NO_THROW(c.reset(CompressorFactory::instance().build(compression)));
EXPECT_compress_uncompress_1(*c, in, len);
EXPECT_compress_uncompress_2(*c, in, len);
EXPECT_reproducible_compression(*c, 10);
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------
} // end namespace test
} // end namespace eckit
int main(int argc, char* argv[]) {
return run_tests(argc, argv);
}
| 33.022901 | 120 | 0.638234 | [
"vector"
] |
9adb49db1d3acd9be67c69061e8e973d0fa952d4 | 2,974 | cc | C++ | sample.cc | r-lyeh/metatracker-wip | 0d67bc52e8b60c250867f9cb0ec249d499bbbe6a | [
"Zlib"
] | null | null | null | sample.cc | r-lyeh/metatracker-wip | 0d67bc52e8b60c250867f9cb0ec249d499bbbe6a | [
"Zlib"
] | null | null | null | sample.cc | r-lyeh/metatracker-wip | 0d67bc52e8b60c250867f9cb0ec249d499bbbe6a | [
"Zlib"
] | null | null | null | // simple sync app
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
std::vector<std::string> split( const std::string &input, char sep ) {
std::istringstream ss(input);
std::vector<std::string> words;
std::string word;
while( std::getline(ss, word, sep) )
words.push_back( word );
return words;
}
std::string song = R"*(
Are you going to Scarborough Fair?
Parsley, sage, rosemary, and thyme;
Remember me to the one who lives there,
For once she was a true love of mine.
Tell her to make me a cambric shirt,
Parsley, sage, rosemary, and thyme;
Without a seam or needlework,
Then she'll be a true lover of mine.
Tell her to wash it in yonder well,
Parsley, sage, rosemary, and thyme;
Where never spring water or rain ever fell,
And she shall be a true lover of mine.
Tell her to dry it on yonder thorn,
Parsley, sage, rosemary, and thyme;
Which never bore blossom since Adam was born,
Then she shall be a true lover of mine.
Now he has asked me questions three,
Parsley, sage, rosemary, and thyme;
I hope he'll answer as many for me
Before he shall be a true lover of mine.
Tell him to buy me an acre of land,
Parsley, sage, rosemary, and thyme;
Between the salt water and the sea sand,
Then he shall be a true lover of mine.
Tell him to plough it with a ram's horn,
Parsley, sage, rosemary, and thyme;
And sow it all over with one pepper corn,
And he shall be a true lover of mine.
Tell him to sheer't with a sickle of leather,
Parsley, sage, rosemary, and thyme;
And bind it up with a peacock feather.
And he shall be a true lover of mine.
Tell him to thrash it on yonder wall,
Parsley, sage, rosemary, and thyme,
And never let one corn of it fall,
Then he shall be a true lover of mine.
When he has done and finished his work.
Parsley, sage, rosemary, and thyme:
Oh, tell him to come and he'll have his shirt,
And he shall be a true lover of mine.)*";
#include <chrono>
void sleep4( double seconds ) {
std::this_thread::sleep_for( std::chrono::milliseconds( int(seconds * 1000) ));
}
int main() {
if(0) {
auto words = split( song, ' ' );
for( unsigned it = 0, end = words.size(); it < end; ++it ) {
std::cout << (it+1) << ") " << words[it] << std::endl;
double delay = strlen(words[it].c_str()) * 0.075;
char ch = words[it].back() != '"' ? words[it].back() : words[it][ words[it].size() - 2 ];
switch( ch ) {
break; default : sleep4( delay );
break; case '?':
case ',': sleep4( delay + 0.5 );
break; case '.': sleep4( delay + 2.0 );
}
}
return 0;
}
int t0 = 0, t1 = 1000;
for(;;) {
t0 ++;
t0 %= t1;
printf("metatracker %d %d\n", t0, t1 );
printf("random %d %d\n", rand(), rand());
std::this_thread::sleep_for( std::chrono::milliseconds(1) );
}
}
| 31.638298 | 101 | 0.633154 | [
"vector"
] |
9ade8cc9887adc14ea86d5655a4a62d1ccaf82b5 | 6,995 | cpp | C++ | discoverer/discoverer.cpp | KOLANICH/HydrArgs | d3ccbd6f03e2e70c3c3d00856dc16b7240b802f3 | [
"Unlicense"
] | null | null | null | discoverer/discoverer.cpp | KOLANICH/HydrArgs | d3ccbd6f03e2e70c3c3d00856dc16b7240b802f3 | [
"Unlicense"
] | null | null | null | discoverer/discoverer.cpp | KOLANICH/HydrArgs | d3ccbd6f03e2e70c3c3d00856dc16b7240b802f3 | [
"Unlicense"
] | null | null | null | #include <algorithm>
#include <filesystem>
#include <iostream>
#include <unordered_map>
#include <whereami.h>
#include <cassert>
#include <HydrArgs/HydrArgs.hpp>
using namespace HydrArgs;
#define USE_DYLIB
#ifndef USE_DYLIB
#include <function_loader/function_loader.hpp>
using DynLibT = burda::function_loader::function_loader;
#else
#include <DyLib.hpp>
using DynLibT = DyLib;
#endif
#include "searchPaths.hpp"
using namespace HydrArgs;
namespace HydrArgs::Backend{
const ParserCapabilities capabilities{
.help = {
.error_message = false,
.help = false,
.usage = false,
.value_name = false,
.value_unit = false
},
.native_positional = {
.mandatory = false,
.optional = false,
.optional_before_mandatory = false
},
.dashed = {
.mandatory = false,
.optional = false
},
.bellsAndWhistles = {
.path_validation = false,
.auto_complete = false,
.wide_strings = false
},
.important = {
.stable = false,
.bug_memory_safety = false,
.bug_terminates_itself = false,
.bug_prints_itself = false,
.other_grave_bugs = false,
.permissive_license = false
}
};
const char ctorFuncName[] = "argsParserFactory";
const std::string backendFileNameStemPrefix{"HydrArgs_backend_"};
const std::string libBackendFileNameStemPrefix{"lib" + backendFileNameStemPrefix};
const std::filesystem::path soExt{".so"};
DynLibT *loadedLib = nullptr;
std::function<ArgsParserFactoryT> chosenFactory;
struct DiscoveredBackend{
const std::string backendPath;
ParserCapabilities caps;
DiscoveredBackend(const std::string &backendPath, ParserCapabilities caps): backendPath(backendPath), caps(caps){}
};
std::filesystem::path backendsPath;
struct HydrArgsDiscovererErrorCategory: public std::error_category{
virtual const char * name() const noexcept override {
return "HydrArgs discoverer has errored";
}
virtual std::string message(int ev) const override {
switch(static_cast<std::errc>(ev)) {
case std::errc::no_such_file_or_directory:
return "Backends haven't been found";
default:
return "Unknown HydrArgs discoverer error";
}
}
};
static HydrArgsDiscovererErrorCategory HydrArgs_discoverer_error;
struct BackendNotDiscoveredError: public std::filesystem::filesystem_error{
BackendNotDiscoveredError(const std::filesystem::path &dir): std::filesystem::filesystem_error("No backend was discovered.", dir, std::error_code(static_cast<int>(std::errc::no_such_file_or_directory), HydrArgs_discoverer_error)){}
};
void initializeBackendsPath(){
std::string myPathStr;
auto myPathSize = wai_getModulePath(nullptr, 0, nullptr);
myPathStr.reserve(myPathSize);
myPathStr.resize(myPathSize);
wai_getModulePath(myPathStr.data(), myPathSize, nullptr);
std::filesystem::path myPath(myPathStr);
//std::cout << "My dll path: " << myPathStr << std::endl;
backendsPath = myPath.parent_path();
//std::cout << "My dll parent dir: " << backendsPath << std::endl;
}
void loadBackend(DiscoveredBackend &backend){
loadedLib = new DynLibT(backend.backendPath);
#ifndef USE_DYLIB
chosenFactory = loadedLib->get_function<ArgsParserFactoryT>(ctorFuncName);
#else
chosenFactory = loadedLib->getFunction<ArgsParserFactoryT>(ctorFuncName);
#endif
}
typedef std::unordered_map<std::string, DiscoveredBackend> BackendsCollectionT;
static BackendsCollectionT discoveredBackends;
void discoverBackendsFromPath(BackendsCollectionT &discoveredBackends, Streams streams, const std::filesystem::path &backendsPath, bool shouldPrintDebugOutput){
//std::cout << "Searching for backends in dir: " << backendsPath << std::endl;
if(!std::filesystem::is_directory(backendsPath)){
if(shouldPrintDebugOutput){
streams.cerr << "Backends dir path does not point to a dir: " << backendsPath << std::endl;
}
return;
}
std::filesystem::directory_iterator iter(backendsPath);
for(auto libCand: iter){
auto p = libCand.path();
std::string stem{p.stem()};
if(p.extension() == soExt){
size_t prefixLen = 0;
if(stem.starts_with(libBackendFileNameStemPrefix)){
prefixLen = libBackendFileNameStemPrefix.size();
} else if(stem.starts_with(backendFileNameStemPrefix)){
prefixLen = backendFileNameStemPrefix.size();
}
if(prefixLen){
auto name = stem.substr(prefixLen);
if(shouldPrintDebugOutput){
streams.cerr << "Probing candidate: " << stem << std::endl;
}
std::string libPathStr{p};
DynLibT candidateLibrary(libPathStr.data());
auto caps = candidateLibrary.getVariable<ParserCapabilities>("capabilities");
if(shouldPrintDebugOutput){
streams.cerr << "Candidate score: " << std::hex << caps.getScore() << std::endl;
}
discoveredBackends.emplace(name, DiscoveredBackend{libPathStr, caps});
}
}
}
}
void discoverBackends(BackendsCollectionT &discoveredBackends, Streams streams, bool shouldPrintDebugOutput){
if(backendsPath.empty()){
initializeBackendsPath();
}
for(auto &parentDir: std::span(searchPaths, searchPathsCount)){
discoverBackendsFromPath(discoveredBackends, streams, backendsPath / parentDir, shouldPrintDebugOutput);
}
/*#if defined(HYDRARGS_SCAN_BACKENDS_DIR)
discoverBackendsFromPath(discoveredBackends, streams, backendsPath.parent_path() / "backends");
#endif*/
if(discoveredBackends.size() == 0){
throw BackendNotDiscoveredError(backendsPath);
}
}
constexpr const char backendEnvVar[] = "HYDRARGS_BACKEND";
constexpr const char discovererDebugEnvVar[] = "HYDRARGS_DISCOVERER_DEBUG";
//decltype(discoveredBackends)::node_type chooseBackend(){
std::pair<const std::string, DiscoveredBackend&> chooseBackend(BackendsCollectionT &discoveredBackends, Streams streams [[maybe_unused]], bool shouldPrintDebugOutput [[maybe_unused]] =false){
auto envVar = getenv(const_cast<char *>(backendEnvVar));
if(envVar){
auto res = discoveredBackends.find(envVar);
if(res != end(discoveredBackends)){
return {res->first, res->second};
}
}
auto el = std::max_element(begin(discoveredBackends), end(discoveredBackends), [](std::pair<const std::string, DiscoveredBackend> &a, std::pair<const std::string, DiscoveredBackend> &b) -> bool{
return b.second.caps > a.second.caps;
});
return {el->first, el->second};
}
IArgsParser * argsParserFactory(const std::string &name, const std::string &descr, const std::string &usage, std::vector<Arg*> dashedSpec, std::vector<Arg*> positionalSpec, Streams streams){
bool shouldPrintDebugOutput = getenv(const_cast<char *>(discovererDebugEnvVar));
if(!discoveredBackends.size()){
discoverBackends(discoveredBackends, streams, shouldPrintDebugOutput);
}
auto b = chooseBackend(discoveredBackends, streams, shouldPrintDebugOutput);
if(shouldPrintDebugOutput){
streams.cerr << "Selected backend: " << b.first << std::endl;
}
loadBackend(b.second);
return chosenFactory(name, descr, usage, dashedSpec, positionalSpec, streams);
}
};
| 33.151659 | 233 | 0.733095 | [
"vector"
] |
9adf47b61a1ecc7529062bb6b4544e6f84269e94 | 4,475 | cpp | C++ | src/utils.cpp | nickerso/get-model-server | 9301b10624885fdf2e10148bd6616e48470222a1 | [
"Apache-2.0"
] | null | null | null | src/utils.cpp | nickerso/get-model-server | 9301b10624885fdf2e10148bd6616e48470222a1 | [
"Apache-2.0"
] | null | null | null | src/utils.cpp | nickerso/get-model-server | 9301b10624885fdf2e10148bd6616e48470222a1 | [
"Apache-2.0"
] | null | null | null | #include <curl/curl.h>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <libxml/uri.h>
#include <json/json.h>
#include <sedml/SedTypes.h>
#include "utils.hpp"
class CurlData
{
public:
CurlData()
{
std::cout << "Creating a persistent CurlData handle" << std::endl;
mCurl = curl_easy_init();
}
~CurlData()
{
std::cout << "Destroying a persistent CurlData handle" << std::endl;
if (mCurl) curl_easy_cleanup(mCurl);
}
CURL* mCurl;
};
static size_t retrieveContent(char* buffer, size_t size, size_t nmemb, void* string)
{
std::string* s = static_cast<std::string*>(string);
size_t bytes = size * nmemb;
s->append(buffer, bytes);
return bytes;
}
std::string getUrlContent(const std::string &url)
{
static CurlData curlHandle;
std::string data, headerData;
CURL* curl = curlHandle.mCurl;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, retrieveContent);
curl_easy_setopt(curl, CURLOPT_WRITEHEADER, static_cast<void*>(&headerData));
curl_easy_setopt(curl, CURLOPT_WRITEDATA, static_cast<void*>(&data));
//curl_easy_setopt(curl, CURLOPT_HEADER, 1);
CURLcode res = curl_easy_perform(curl);
if(CURLE_OK != res)
{
/* we failed */
std::cerr << "curl told us " << res << std::endl;
return "";
}
// check headers
std::vector<std::string> headers;
headers = splitString(headerData, '\n', headers);
if (headers.size() > 0)
{
// have some headers to check
if (headers[0].find("200") == std::string::npos)
{
// HTTP 200 OK header response not seen so delete any returned data
data.clear();
}
}
return data;
}
std::vector<std::string>& splitString(const std::string &s, char delim, std::vector<std::string>& elems)
{
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::string urlChildOf(const std::string& url, const std::string& base)
{
std::string result;
size_t found = url.find(base);
if (found == 0)
{
result = url.substr(base.size());
}
return result;
}
Json::Value getSedOutputsJson(SedDocument *doc)
{
Json::Value root;
std::cout << "The document has " << doc->getNumOutputs() << " output(s)." << std::endl;
for (unsigned int i = 0; i < doc->getNumOutputs(); ++i)
{
SedOutput* current = doc->getOutput(i);
Json::Value output;
if (current->isSetId()) output["id"] = current->getId();
switch(current->getTypeCode())
{
case SEDML_OUTPUT_REPORT:
{
output["type"] = "report";
SedReport* r = static_cast<SedReport*>(current);
std::cout << "\tReport id=" << current->getId() << " numDataSets=" << r->getNumDataSets() << std::endl;
output["numberOfDataSets"] = r->getNumDataSets();
break;
}
case SEDML_OUTPUT_PLOT2D:
{
output["type"] = "plot2d";
SedPlot2D* p = static_cast<SedPlot2D*>(current);
std::cout << "\tPlot2d id=" << current->getId() << " numCurves=" << p->getNumCurves() << std::endl;
for (unsigned int j = 0; j < p->getNumCurves(); ++j)
{
const SedCurve* curve = p->getCurve(j);
Json::Value c;
// always have an index, id optional? so use the id to index this curve
c["index"] = j;
if (curve->isSetId()) c["id"] = curve->getId();
if (curve->isSetName()) c["name"] = curve->getName();
// required attributes, so no need to check them
c["logX"] = curve->getLogX();
c["logY"] = curve->getLogY();
output["curves"].append(c);
}
break;
}
case SEDML_OUTPUT_PLOT3D:
{
output["type"] = "plot3d";
SedPlot3D* p = static_cast<SedPlot3D*>(current);
std::cout << "\tPlot3d id=" << current->getId() << " numSurfaces=" << p->getNumSurfaces() << std::endl;
break;
}
default:
std::cout << "\tEncountered unknown output " << current->getId() << std::endl;
break;
}
root.append(output);
}
return root;
}
| 30.650685 | 115 | 0.559106 | [
"vector"
] |
9ae0267701d6ac509f4b3528e8bb102d2451aaff | 4,725 | hpp | C++ | include/SSVUtils/Core/String/Internal/SplitHelper.hpp | SuperV1234/SSVUtils | a0e801b180bf65d7b3be4ea1e15b840c52e92efc | [
"AFL-3.0"
] | 55 | 2015-01-27T09:45:01.000Z | 2020-05-18T18:26:44.000Z | include/SSVUtils/Core/String/Internal/SplitHelper.hpp | vittorioromeo/SSVUtils | dafa2499bcd350c3bfdbfb84d522e022c3513a93 | [
"AFL-3.0"
] | 10 | 2015-01-12T20:08:59.000Z | 2020-08-29T23:40:59.000Z | include/SSVUtils/Core/String/Internal/SplitHelper.hpp | vittorioromeo/SSVUtils | dafa2499bcd350c3bfdbfb84d522e022c3513a93 | [
"AFL-3.0"
] | 8 | 2015-02-24T04:30:50.000Z | 2021-02-04T04:37:58.000Z | // Copyright (c) 2013-2015 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#ifndef SSVU_CORE_STRING_INTERNAL_SPLITHELPER
#define SSVU_CORE_STRING_INTERNAL_SPLITHELPER
#include <string>
#include <vector>
namespace ssvu
{
namespace Impl
{
using StrSize = std::string::size_type;
inline StrSize findFirstOf(const std::string& mStr, const StrSize& mStartAt,
const std::vector<std::string>& mSeparator, StrSize& mLength)
{
StrSize result{std::numeric_limits<StrSize>::max()};
for(const auto& s : mSeparator)
{
StrSize temp{mStr.find(s, mStartAt)};
if(temp < result)
{
result = temp;
mLength = s.size();
}
}
return result;
}
template <typename T>
struct SplitFindHelperDefault
{
inline static StrSize getNextIdx(
const std::string& mStr, const T& mSeparator, StrSize mStart)
{
return mStr.find(mSeparator, mStart);
}
};
template <typename T>
struct SplitFindHelper;
template <>
struct SplitFindHelper<char> : public SplitFindHelperDefault<char>
{
};
template <>
struct SplitFindHelper<std::string> : public SplitFindHelperDefault<std::string>
{
};
template <std::size_t TN>
struct SplitFindHelper<char[TN]>
{
inline static StrSize getNextIdx(
const std::string& mStr, const char (&mSeparator)[TN], StrSize mStart)
{
std::string separator(&mSeparator[0], &mSeparator[TN - 1]);
return mStr.find(separator, mStart);
}
};
template <typename T, Split TM>
struct SplitHelperImpl
{
inline static void split(std::vector<std::string>& mTarget,
const std::string& mStr, const T& mSeparator,
std::size_t mSeparatorSize)
{
StrSize pos{0}, startAt{0};
std::string token;
while((pos = mStr.find(mSeparator, startAt)) != std::string::npos)
{
auto tokenLength(pos - startAt);
// If we need to keep the separator in the splitted strings,
// add
// the separator's length to the token length
if(TM == Split::TrailingSeparator) tokenLength += mSeparatorSize;
token = mStr.substr(startAt, tokenLength);
if(!token.empty()) mTarget.emplace_back(token);
if(TM == Split::TokenizeSeparator)
mTarget.emplace_back(mStr, pos - 1, mSeparatorSize);
startAt = pos + mSeparatorSize;
}
std::string reimaining(mStr.substr(startAt, mStr.size() - startAt));
if(!reimaining.empty()) mTarget.emplace_back(reimaining);
}
};
template <typename T, Split TM>
struct SplitHelper;
template <Split TM>
struct SplitHelper<char, TM>
{
inline static void split(std::vector<std::string>& mTarget,
const std::string& mStr, char mSeparator)
{
SplitHelperImpl<char, TM>::split(mTarget, mStr, mSeparator, 1);
}
};
template <Split TM, std::size_t TN>
struct SplitHelper<char[TN], TM>
{
inline static void split(std::vector<std::string>& mTarget,
const std::string& mStr, const char (&mSeparator)[TN])
{
SplitHelperImpl<char[TN], TM>::split(mTarget, mStr, mSeparator, TN - 1);
}
};
template <Split TM>
struct SplitHelper<std::string, TM> : public SplitHelperImpl<std::string, TM>
{
inline static void split(std::vector<std::string>& mTarget,
const std::string& mStr, const std::string& mSeparator)
{
SplitHelperImpl<std::string, TM>::split(
mTarget, mStr, mSeparator, mSeparator.size());
}
};
template <Split TM>
struct SplitHelper<std::vector<std::string>, TM>
{
inline static void split(std::vector<std::string>& mTarget,
const std::string& mStr, const std::vector<std::string>& mSeparator)
{
StrSize pos{0}, startAt{0}, lastLength;
std::string token;
while((pos = findFirstOf(mStr, startAt, mSeparator, lastLength)) !=
std::string::npos)
{
auto tokenLength(pos - startAt);
// If we need to keep the separator in the splitted strings,
// add
// the separator's length to the token length
if(TM == Split::TrailingSeparator) tokenLength += lastLength;
token = mStr.substr(startAt, tokenLength);
if(!token.empty()) mTarget.emplace_back(token);
if(TM == Split::TokenizeSeparator)
mTarget.emplace_back(mStr, pos, lastLength);
startAt = pos + lastLength;
}
std::string reimaining(mStr.substr(startAt, mStr.size() - startAt));
if(!reimaining.empty()) mTarget.emplace_back(reimaining);
}
};
} // namespace Impl
} // namespace ssvu
#endif
| 29.905063 | 80 | 0.635767 | [
"vector"
] |
9ae1724a161fb4d6fb7187a5a8288c231c877ddf | 2,198 | hpp | C++ | ablateLibrary/domain/fieldDescription.hpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | null | null | null | ablateLibrary/domain/fieldDescription.hpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 8 | 2020-12-28T16:05:56.000Z | 2021-01-12T14:36:22.000Z | ablateLibrary/domain/fieldDescription.hpp | mtmcgurn-buffalo/ablate | 35ee9a30277908775a61d78462ea9724ee631a9b | [
"BSD-3-Clause"
] | 1 | 2021-12-14T22:39:13.000Z | 2021-12-14T22:39:13.000Z | #ifndef ABLATELIBRARY_FIELDDESCRIPTION_HPP
#define ABLATELIBRARY_FIELDDESCRIPTION_HPP
#include <petsc.h>
#include <memory>
#include <parameters/parameters.hpp>
#include <string>
#include <vector>
#include "domain/field.hpp"
#include "domain/region.hpp"
#include "fieldDescriptor.hpp"
namespace ablate::domain {
/**
* Describes the necessary information to produce a field in the domain/dm
*/
struct FieldDescription : public FieldDescriptor, public std::enable_shared_from_this<FieldDescription> {
virtual ~FieldDescription();
// Helper variable, replaces any components with this value with one for each dimension
inline const static std::string DIMENSION = "_DIMENSION_";
inline const static std::vector<std::string> ONECOMPONENT = {"_"};
// The name of the field
const std::string name;
// The prefix for field options
const std::string prefix;
// The components held in this field
std::vector<std::string> components = {"_"};
// If the field is solution or aux
const enum FieldLocation location = FieldLocation::SOL;
// The type of field (FEM/FVM)
const enum FieldType type = FieldType::FEM;
// The region for the field (nullptr is everywhere)
const std::shared_ptr<domain::Region> region;
FieldDescription(std::string name, std::string prefix, std::vector<std::string> components, FieldLocation location, FieldType type, std::shared_ptr<domain::Region> = {},
std::shared_ptr<parameters::Parameters> = {});
/**
* Public function that will cause the components to expand or decompress based upon the number of dims
*/
void DecompressComponents(PetscInt dim);
/** Allow a single FieldDescription to report it self allowing FieldDescription to be used as FieldDescriptor**/
std::vector<std::shared_ptr<FieldDescription>> GetFields() override;
/**
* Create the petsc field used by the dm
* @param dm
* @return
*/
virtual PetscObject CreatePetscField(DM dm) const;
private:
// Petsc options specific for this field
PetscOptions options = nullptr;
};
} // namespace ablate::domain
#endif // ABLATELIBRARY_FIELDDESCRIPTION_HPP
| 32.323529 | 173 | 0.712466 | [
"vector"
] |
9aee8e5e04b7cc1da4895e32df0d5f5706c343fa | 5,903 | cc | C++ | tensorflow/compiler/mlir/tensorflow/utils/tf_xla_mlir_translate.cc | CaptainDuke/tensorflow | ae2d518569f1f74d71642c4bedadecbb523fac4d | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/tensorflow/utils/tf_xla_mlir_translate.cc | CaptainDuke/tensorflow | ae2d518569f1f74d71642c4bedadecbb523fac4d | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/tensorflow/utils/tf_xla_mlir_translate.cc | CaptainDuke/tensorflow | ae2d518569f1f74d71642c4bedadecbb523fac4d | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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 <string>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/IR/Dialect.h" // from @llvm-project
#include "mlir/IR/Module.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/Translation.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate_cl.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h"
#include "tensorflow/compiler/mlir/utils/string_container_utils.h"
#include "tensorflow/compiler/mlir/xla/xla_mlir_translate_cl.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/xla/service/hlo.pb.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_module_config.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/status.h"
namespace tensorflow {
namespace {
mlir::LogicalResult PrintHloModuleText(
const XlaCompilationResult& compilation_result, llvm::raw_ostream& output) {
const xla::HloModuleConfig module_config(
compilation_result.computation->GetProgramShape().ValueOrDie());
auto status_or_hlo_module = xla::HloModule::CreateFromProto(
compilation_result.computation->proto(), module_config);
if (!status_or_hlo_module.ok()) {
LOG(ERROR) << "Conversion to HLO module failed: "
<< status_or_hlo_module.status().error_message();
return mlir::failure();
}
xla::HloModule* hlo_module = status_or_hlo_module.ValueOrDie().get();
output << hlo_module->ToString();
if (!compilation_result.input_mapping.empty())
output << "// InputMapping {"
<< absl::StrJoin(compilation_result.input_mapping, ", ") << "}\n";
for (const auto& xla_input_shape : compilation_result.xla_input_shapes)
output << "// XlaInputShape " << xla_input_shape.ToString() << '\n';
output << "// XlaOutputShape "
<< compilation_result.xla_output_shape.ToString() << '\n';
for (const auto& xla_output_description : compilation_result.outputs) {
output << "// XlaOutputDescription type="
<< DataTypeString(xla_output_description.type) << " shape=("
<< absl::StrJoin(xla_output_description.shape.dim_sizes(), ", ")
<< ')';
if (xla_output_description.input_index >= 0)
output << " input_index=" << xla_output_description.input_index;
if (xla_output_description.is_constant) output << " constant";
if (xla_output_description.is_tensor_list) output << " tensor_list";
output << '\n';
}
for (const auto& resource_update : compilation_result.resource_updates) {
output << "// ResourceUpdate input_index=" << resource_update.input_index
<< " type=" << DataTypeString(resource_update.type) << " shape=("
<< absl::StrJoin(resource_update.shape.dim_sizes(), " ") << ')';
if (resource_update.modified) output << " modified";
output << '\n';
}
return mlir::success();
}
Status ParseArgumentShapes(
absl::string_view input_shapes_str,
llvm::SmallVectorImpl<TensorOrResourceShape>& arg_shapes) {
arg_shapes.clear();
std::vector<std::vector<int>> input_shapes_vector;
TF_RETURN_IF_ERROR(ParseNodeShapes(input_shapes_str, input_shapes_vector));
arg_shapes.resize(input_shapes_vector.size());
for (const auto& shape : llvm::enumerate(input_shapes_vector))
TF_RETURN_IF_ERROR(TensorShapeUtils::MakeShape(
shape.value(), &arg_shapes[shape.index()].shape));
return Status::OK();
}
} // anonymous namespace
static mlir::LogicalResult MlirTfToHloTextTranslateFunction(
mlir::ModuleOp module_op, llvm::raw_ostream& output) {
if (!module_op) return mlir::failure();
llvm::SmallVector<TensorOrResourceShape, 4> arg_shapes;
auto args_status =
ParseArgumentShapes(mlir::StringRefToView(input_shapes), arg_shapes);
if (!args_status.ok()) {
LOG(ERROR) << args_status.error_message();
return mlir::failure();
}
XlaCompilationResult compilation_result;
auto compilation_status = CompileMlirToXlaHlo(
module_op, arg_shapes, "XLA_CPU_JIT", emit_use_tuple_arg,
emit_return_tuple, IdentityShapeRepresentationFn(), &compilation_result,
/*custom_legalization_passes=*/{});
if (!compilation_status.ok()) {
LOG(ERROR) << "TF/XLA compilation failed: "
<< compilation_status.error_message();
return mlir::failure();
}
return PrintHloModuleText(compilation_result, output);
}
} // namespace tensorflow
static void RegisterInputDialects(mlir::DialectRegistry& registry) {
registry.insert<mlir::StandardOpsDialect, mlir::TF::TensorFlowDialect>();
}
static mlir::TranslateFromMLIRRegistration MlirTfXlaToHloTextTranslate(
"mlir-tf-to-hlo-text", tensorflow::MlirTfToHloTextTranslateFunction,
RegisterInputDialects);
| 40.156463 | 80 | 0.726919 | [
"shape",
"vector"
] |
9af026dab33b55dbbefeb60c97dde0741329e0b2 | 7,244 | cpp | C++ | dlls/weapons/CSniperRifle.cpp | Admer456/halflife-dnf01 | a3cacddb5ff3dedfea2d157c72711ba1df429dac | [
"Unlicense"
] | null | null | null | dlls/weapons/CSniperRifle.cpp | Admer456/halflife-dnf01 | a3cacddb5ff3dedfea2d157c72711ba1df429dac | [
"Unlicense"
] | null | null | null | dlls/weapons/CSniperRifle.cpp | Admer456/halflife-dnf01 | a3cacddb5ff3dedfea2d157c72711ba1df429dac | [
"Unlicense"
] | null | null | null | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "player.h"
#include "Weapons.h"
#include "gamerules.h"
#include "CSniperRifle.h"
#include "CProjectileBullet.h"
#ifndef CLIENT_DLL
TYPEDESCRIPTION CSniperRifle::m_SaveData[] =
{
DEFINE_FIELD( CSniperRifle, m_flReloadStart, FIELD_TIME ),
DEFINE_FIELD( CSniperRifle, m_bReloading, FIELD_BOOLEAN ),
};
IMPLEMENT_SAVERESTORE( CSniperRifle, CSniperRifle::BaseClass );
#endif
LINK_ENTITY_TO_CLASS( weapon_sniperrifle, CSniperRifle );
void CSniperRifle::Precache()
{
pev->classname = MAKE_STRING( "weapon_sniperrifle" );
BaseClass::Precache();
m_iId = WEAPON_SNIPERRIFLE;
PRECACHE_MODEL( "models/w_m40a1.mdl" );
PRECACHE_MODEL( "models/v_m40a1.mdl" );
PRECACHE_MODEL( "models/p_m40a1.mdl" );
PRECACHE_SOUND( "weapons/sniper_fire.wav" );
PRECACHE_SOUND( "weapons/sniper_zoom.wav" );
PRECACHE_SOUND( "weapons/sniper_reload_first_seq.wav" );
PRECACHE_SOUND( "weapons/sniper_reload_second_seq.wav" );
PRECACHE_SOUND( "weapons/sniper_miss.wav" );
PRECACHE_SOUND( "weapons/sniper_bolt1.wav" );
PRECACHE_SOUND( "weapons/sniper_bolt2.wav" );
m_usSniper = PRECACHE_EVENT( 1, "events/sniper.sc" );
}
void CSniperRifle::Spawn()
{
Precache();
SET_MODEL( edict(), "models/w_m40a1.mdl" );
m_iDefaultAmmo = SNIPERRIFLE_DEFAULT_GIVE;
FallInit(); // get ready to fall down.
}
BOOL CSniperRifle::AddToPlayer( CBasePlayer* pPlayer )
{
if( BaseClass::AddToPlayer( pPlayer ) )
{
MESSAGE_BEGIN( MSG_ONE, gmsgWeapPickup, NULL, pPlayer->edict() );
WRITE_BYTE( m_iId );
MESSAGE_END();
return true;
}
return false;
}
BOOL CSniperRifle::Deploy()
{
return BaseClass::DefaultDeploy( "models/v_m40a1.mdl", "models/p_m40a1.mdl", SNIPERRIFLE_DRAW, "bow" );
}
void CSniperRifle::Holster( int skiplocal )
{
m_fInReload = false;// cancel any reload in progress.
if( m_bInZoom )
SecondaryAttack();
m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.25;
SendWeaponAnim( SNIPERRIFLE_HOLSTER );
}
void CSniperRifle::WeaponIdle()
{
//Update autoaim
m_pPlayer->GetAutoaimVector( AUTOAIM_2DEGREES );
ResetEmptySound();
if( m_bReloading && gpGlobals->time >= m_flReloadStart + 2.324 )
{
SendWeaponAnim( SNIPERRIFLE_RELOAD2 );
m_bReloading = false;
}
if( m_flTimeWeaponIdle < UTIL_WeaponTimeBase() )
{
if( m_iClip )
SendWeaponAnim( SNIPERRIFLE_SLOWIDLE );
else
SendWeaponAnim( SNIPERRIFLE_SLOWIDLE2 );
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 4.348;
}
}
void CSniperRifle::PrimaryAttack()
{
if( m_pPlayer->pev->waterlevel == WATERLEVEL_HEAD )
{
PlayEmptySound();
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + 1.0f;
return;
}
if( !m_iClip )
{
PlayEmptySound();
return;
}
m_pPlayer->m_iWeaponVolume = QUIET_GUN_VOLUME;
--m_iClip;
m_pPlayer->SetAnimation( PLAYER_ATTACK1 );
Vector vecSrc = m_pPlayer->GetGunPosition() - (gpGlobals->v_up * 2) + (gpGlobals->v_right * 2) + (gpGlobals->v_forward * 4);
Vector vecAiming = m_pPlayer->GetAutoaimVector(AUTOAIM_10DEGREES);
Vector anglesAim = m_pPlayer->pev->v_angle + m_pPlayer->pev->punchangle;
UTIL_MakeVectors(anglesAim);
Vector vecDir = gpGlobals->v_forward;
#ifndef CLIENT_DLL
CProjectileBullet *pBullet = CProjectileBullet::LaunchProjectile(WDT_Eagle, m_pPlayer);
pBullet->pev->origin = vecSrc;
pBullet->pev->angles = anglesAim;
pBullet->pev->owner = m_pPlayer->edict();
pBullet->pev->avelocity.z = 90;
pBullet->pev->angles.x *= -1;
ALERT(at_console, "\naim %f\tplayer %f", anglesAim.y, m_pPlayer->pev->angles.y);
#endif
//TODO: 8192 constant should be defined somewhere - Solokiller
/* Vector vecShot = m_pPlayer->FireBulletsPlayer( 1,
vecSrc, vecAiming, g_vecZero,
8192, BULLET_PLAYER_762, 0, 0,
m_pPlayer->pev, m_pPlayer->random_seed );
PLAYBACK_EVENT_FULL( FEV_NOTHOST,
m_pPlayer->edict(), m_usSniper, 0,
g_vecZero, g_vecZero,
vecShot.x, vecShot.y,
m_iClip, m_pPlayer->m_rgAmmo[ PrimaryAmmoIndex() ],
0, 0 ); */
if (m_iClip != 1)
SendWeaponAnim(SNIPERRIFLE_FIRELASTROUND);
else
SendWeaponAnim(SNIPERRIFLE_FIRE);
EMIT_SOUND_DYN(ENT(pev), CHAN_WEAPON, "weapons/sniper_fire.wav", 1.0, ATTN_NORM, 0, 90 + (RANDOM_FLOAT(-10, 10)));
m_pPlayer->pev->punchangle.x += RANDOM_FLOAT(4.0, 8.5);
m_pPlayer->pev->punchangle.y += RANDOM_FLOAT(1.0, 4.5);
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + 2.0f;
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 2.0f;
}
void CSniperRifle::SecondaryAttack()
{
EMIT_SOUND_DYN( m_pPlayer->edict(), CHAN_ITEM, "weapons/sniper_zoom.wav", VOL_NORM, ATTN_NORM, 0, PITCH_NORM );
m_bInZoom = !m_bInZoom;
ToggleZoom();
//TODO: use UTIL_WeaponTimeBase() - Solokiller
//TODO: this doesn't really make sense
pev->nextthink = 0.0 + 0.1;
m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + 0.1 + 0.5;
}
void CSniperRifle::Reload()
{
if( m_pPlayer->ammo_762 > 0 )
{
if( m_bInZoom )
{
ToggleZoom();
}
if( m_iClip )
{
if( DefaultReload( SNIPERRIFLE_MAX_CLIP, SNIPERRIFLE_RELOAD3, 2.324, 1 ) )
{
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + 2.324;
}
}
else if( DefaultReload( SNIPERRIFLE_MAX_CLIP, SNIPERRIFLE_RELOAD1, 2.324, 1 ) )
{
m_flNextPrimaryAttack = UTIL_WeaponTimeBase() + 4.102;
m_flReloadStart = gpGlobals->time;
m_bReloading = true;
}
else
{
m_bReloading = false;
}
}
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 4.102;
}
int CSniperRifle::iItemSlot()
{
return 4;
}
int CSniperRifle::GetItemInfo( ItemInfo* p )
{
p->pszAmmo1 = "762";
p->iMaxAmmo1 = SNIPERRIFLE_MAX_CARRY;
p->pszName = STRING( pev->classname );
p->pszAmmo2 = 0;
p->iMaxAmmo2 = WEAPON_NOCLIP;
p->iMaxClip = SNIPERRIFLE_MAX_CLIP;
p->iSlot = 5;
p->iPosition = 2;
p->iFlags = 0;
p->iId = m_iId = WEAPON_SNIPERRIFLE;
p->iWeight = SNIPERRIFLE_WEIGHT;
return true;
}
void CSniperRifle::ToggleZoom()
{
if( m_pPlayer->pev->fov == 0 )
{
m_pPlayer->pev->fov = 18;
m_pPlayer->m_iFOV = 18;
m_bInZoom = true;
}
else
{
m_pPlayer->pev->fov = 0;
m_pPlayer->m_iFOV = 0;
m_bInZoom = false;
}
}
class CSniperRifleAmmo : public CBasePlayerAmmo
{
public:
using BaseClass = CBasePlayerAmmo;
void Spawn( void ) override
{
Precache();
SET_MODEL( edict(), "models/w_m40a1clip.mdl" );
CBasePlayerAmmo::Spawn();
}
void Precache( void ) override
{
PRECACHE_MODEL( "models/w_m40a1clip.mdl" );
PRECACHE_SOUND( "items/9mmclip1.wav" );
}
BOOL AddAmmo( CBaseEntity *pOther ) override
{
if( pOther->GiveAmmo( AMMO_SNIPERRIFLE_GIVE, "762", SNIPERRIFLE_MAX_CARRY ) != -1 )
{
EMIT_SOUND( edict(), CHAN_ITEM, "items/9mmclip1.wav", VOL_NORM, ATTN_NORM );
return true;
}
return false;
}
};
LINK_ENTITY_TO_CLASS( ammo_762, CSniperRifleAmmo );
| 23.596091 | 125 | 0.710795 | [
"object",
"vector"
] |
9afafe0a532aee580ebcb5532779099608c23612 | 10,613 | cc | C++ | chrome/browser/chromeos/tab_closeable_state_watcher.cc | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | chrome/browser/chromeos/tab_closeable_state_watcher.cc | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | chrome/browser/chromeos/tab_closeable_state_watcher.cc | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2012 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 "chrome/browser/chromeos/tab_closeable_state_watcher.h"
#include "base/command_line.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// TabCloseableStateWatcher::TabStripWatcher, public:
TabCloseableStateWatcher::TabStripWatcher::TabStripWatcher(
TabCloseableStateWatcher* main_watcher, const Browser* browser)
: main_watcher_(main_watcher),
browser_(browser) {
browser_->tabstrip_model()->AddObserver(this);
}
TabCloseableStateWatcher::TabStripWatcher::~TabStripWatcher() {
browser_->tabstrip_model()->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// TabCloseableStateWatcher::TabStripWatcher,
// TabStripModelObserver implementation:
void TabCloseableStateWatcher::TabStripWatcher::TabInsertedAt(
TabContentsWrapper* tab_contents, int index, bool foreground) {
main_watcher_->OnTabStripChanged(browser_, false);
}
void TabCloseableStateWatcher::TabStripWatcher::TabClosingAt(
TabStripModel* tab_strip_model,
TabContentsWrapper* tab_contents,
int index) {
// Check if the last tab is closing.
if (tab_strip_model->count() == 1)
main_watcher_->OnTabStripChanged(browser_, true);
}
void TabCloseableStateWatcher::TabStripWatcher::TabDetachedAt(
TabContentsWrapper* tab_contents, int index) {
main_watcher_->OnTabStripChanged(browser_, false);
}
void TabCloseableStateWatcher::TabStripWatcher::TabChangedAt(
TabContentsWrapper* tab_contents, int index, TabChangeType change_type) {
main_watcher_->OnTabStripChanged(browser_, false);
}
////////////////////////////////////////////////////////////////////////////////
// TabCloseableStateWatcher, public:
TabCloseableStateWatcher::TabCloseableStateWatcher()
: can_close_tab_(true),
signing_off_(false),
guest_session_(
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kGuestSession)),
waiting_for_browser_(false) {
BrowserList::AddObserver(this);
notification_registrar_.Add(this, content::NOTIFICATION_APP_EXITING,
content::NotificationService::AllSources());
}
TabCloseableStateWatcher::~TabCloseableStateWatcher() {
BrowserList::RemoveObserver(this);
if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers())
DCHECK(tabstrip_watchers_.empty());
}
bool TabCloseableStateWatcher::CanCloseTab(const Browser* browser) const {
return browser->is_type_tabbed() ?
(can_close_tab_ || waiting_for_browser_) : true;
}
bool TabCloseableStateWatcher::CanCloseTabs(const Browser* browser,
std::vector<int>* indices) const {
if (signing_off_ || waiting_for_browser_ || tabstrip_watchers_.size() > 1 ||
!browser->is_type_tabbed() ||
(browser->profile()->IsOffTheRecord() && !guest_session_))
return true;
if (!can_close_tab_) {
indices->clear();
return false;
}
TabStripModel* tabstrip_model = browser->tabstrip_model();
// If we're not closing all tabs, there's no restriction.
if (static_cast<int>(indices->size()) != tabstrip_model->count())
return true;
// If first tab is NTP, it can't be closed.
// In TabStripModel::InternalCloseTabs (which calls
// Browser::CanCloseContents which in turn calls this method), all
// renderer processes of tabs could be terminated before the tabs are actually
// closed.
// As tabs are being closed, notification TabDetachedAt is called.
// When this happens to the last second tab, we would prevent the last NTP
// tab from being closed.
// If we don't prevent this NTP tab from being closed now, its renderer
// process would have been terminated but the tab won't be detached later,
// resulting in the "Aw, Snap" page replacing the first NTP.
// This is the main purpose of this method CanCloseTabs.
for (size_t i = 0; i < indices->size(); ++i) {
if ((*indices)[i] == 0) {
if (tabstrip_model->GetTabContentsAt(0)->web_contents()->GetURL() ==
GURL(chrome::kChromeUINewTabURL)) { // First tab is NewTabPage.
indices->erase(indices->begin() + i); // Don't close it.
return false;
}
break;
}
}
return true;
}
bool TabCloseableStateWatcher::CanCloseBrowser(Browser* browser) {
BrowserActionType action_type;
bool can_close = CanCloseBrowserImpl(browser, &action_type);
if (action_type == OPEN_WINDOW) {
browser->NewWindow();
} else if (action_type == OPEN_NTP) {
// NTP will be opened before closing last tab (via TabStripModelObserver::
// TabClosingAt), close all tabs now.
browser->CloseAllTabs();
}
return can_close;
}
void TabCloseableStateWatcher::OnWindowCloseCanceled(Browser* browser) {
// This could be a call to cancel APP_EXITING if user doesn't proceed with
// unloading handler.
if (signing_off_) {
signing_off_ = false;
CheckAndUpdateState(browser);
}
}
////////////////////////////////////////////////////////////////////////////////
// TabCloseableStateWatcher, BrowserList::Observer implementation:
void TabCloseableStateWatcher::OnBrowserAdded(const Browser* browser) {
waiting_for_browser_ = false;
// Only tabbed browsers may affect closeable state.
if (!browser->is_type_tabbed())
return;
// Create TabStripWatcher to observe tabstrip of new browser.
tabstrip_watchers_.push_back(new TabStripWatcher(this, browser));
// When a normal browser is just added, there's no tabs yet, so we wait till
// TabInsertedAt notification to check for change in state.
}
void TabCloseableStateWatcher::OnBrowserRemoved(const Browser* browser) {
// Only tabbed browsers may affect closeable state.
if (!browser->is_type_tabbed())
return;
// Remove TabStripWatcher for browser that is being removed.
for (std::vector<TabStripWatcher*>::iterator it = tabstrip_watchers_.begin();
it != tabstrip_watchers_.end(); ++it) {
if ((*it)->browser() == browser) {
delete (*it);
tabstrip_watchers_.erase(it);
break;
}
}
CheckAndUpdateState(NULL);
}
////////////////////////////////////////////////////////////////////////////////
// TabCloseableStateWatcher, content::NotificationObserver implementation:
void TabCloseableStateWatcher::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type != content::NOTIFICATION_APP_EXITING)
NOTREACHED();
if (!signing_off_) {
signing_off_ = true;
SetCloseableState(true);
}
}
////////////////////////////////////////////////////////////////////////////////
// TabCloseableStateWatcher, private
void TabCloseableStateWatcher::OnTabStripChanged(const Browser* browser,
bool closing_last_tab) {
if (waiting_for_browser_)
return;
if (!closing_last_tab) {
CheckAndUpdateState(browser);
return;
}
// Before closing last tab, open new window or NTP if necessary.
BrowserActionType action_type;
CanCloseBrowserImpl(browser, &action_type);
if (action_type != NONE) {
Browser* mutable_browser = const_cast<Browser*>(browser);
if (action_type == OPEN_WINDOW)
mutable_browser->NewWindow();
else if (action_type == OPEN_NTP)
mutable_browser->NewTab();
}
}
void TabCloseableStateWatcher::CheckAndUpdateState(
const Browser* browser_to_check) {
if (waiting_for_browser_ || signing_off_ || tabstrip_watchers_.empty() ||
(browser_to_check && !browser_to_check->is_type_tabbed()))
return;
bool new_can_close;
if (tabstrip_watchers_.size() > 1) {
new_can_close = true;
} else { // There's only 1 normal browser.
if (!browser_to_check)
browser_to_check = tabstrip_watchers_[0]->browser();
if (browser_to_check->profile()->IsOffTheRecord() && !guest_session_) {
new_can_close = true;
} else {
TabStripModel* tabstrip_model = browser_to_check->tabstrip_model();
if (tabstrip_model->count() == 1) {
new_can_close =
tabstrip_model->GetTabContentsAt(0)->web_contents()->GetURL() !=
GURL(chrome::kChromeUINewTabURL); // Tab is not NewTabPage.
} else {
new_can_close = true;
}
}
}
SetCloseableState(new_can_close);
}
void TabCloseableStateWatcher::SetCloseableState(bool closeable) {
if (can_close_tab_ == closeable) // No change in state.
return;
can_close_tab_ = closeable;
// Notify of change in tab closeable state.
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TAB_CLOSEABLE_STATE_CHANGED,
content::NotificationService::AllSources(),
content::Details<bool>(&can_close_tab_));
}
bool TabCloseableStateWatcher::CanCloseBrowserImpl(
const Browser* browser,
BrowserActionType* action_type) {
*action_type = NONE;
// If we're waiting for a new browser allow the close.
if (waiting_for_browser_)
return true;
// Browser is always closeable when signing off.
if (signing_off_)
return true;
// Non-tabbed browsers are always closeable.
if (!browser->is_type_tabbed())
return true;
// If this is not the last normal browser, it's always closeable.
if (tabstrip_watchers_.size() > 1)
return true;
// If last normal browser is incognito, open a non-incognito window, and allow
// closing of incognito one (if not guest). When this happens we need to wait
// for the new browser before doing any other actions as the new browser may
// be created by way of session restore, which is async.
if (browser->profile()->IsOffTheRecord() && !guest_session_) {
*action_type = OPEN_WINDOW;
waiting_for_browser_ = true;
return true;
}
// If tab is not closeable, browser is not closeable.
if (!can_close_tab_)
return false;
// Otherwise, close existing tabs, and deny closing of browser.
// TabClosingAt will open NTP when the last tab is being closed.
*action_type = OPEN_NTP;
return false;
}
} // namespace chromeos
| 34.016026 | 80 | 0.691699 | [
"vector"
] |
9afe4bb85372ca1db5795ab4140dfe430ad938bb | 13,894 | hpp | C++ | ThirdParty/oglplus-develop/include/oglplus/config.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/include/oglplus/config.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/include/oglplus/config.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | /**
* @file oglplus/config.hpp
* @brief Compile-time configuration options
*
* @author Matus Chochlik
*
* Copyright 2010-2013 Matus Chochlik. 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)
*/
#pragma once
#ifndef OGLPLUS_CONFIG_1107121519_HPP
#define OGLPLUS_CONFIG_1107121519_HPP
#ifndef OGLPLUS_NO_SITE_CONFIG
#include <oglplus/site_config.hpp>
#endif
#ifndef OGLPLUS_USE_GLEW
#define OGLPLUS_USE_GLEW 0
#endif
#ifndef OGLPLUS_USE_FREEGLUT
#define OGLPLUS_USE_FREEGLUT 0
#endif
#ifndef OGLPLUS_USE_BOOST_CONFIG
#define OGLPLUS_USE_BOOST_CONFIG 0
#endif
#if OGLPLUS_USE_BOOST_CONFIG
#include <boost/config.hpp>
#endif
#include <oglplus/config_compiler.hpp>
// define GLAPIENTRY
#ifdef GLAPIENTRY
#undef GLAPIENTRY
#endif
// borrowed from glew.h which does define GLAPIENTRY properly
// at the beginning but undefs it at the end of the header
#if defined(__MINGW32__) || defined(__CYGWIN__)
# define GLAPIENTRY __stdcall
#elif (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__)
# define GLAPIENTRY __stdcall
#else
# define GLAPIENTRY
#endif
// -------------------- Compile-time configuration ----------------------------
/** @defgroup compile_time_config Compile-time configuration
*
* @section oglplus_configuration_options Configuration options
*
* This section describes compile-time preprocessor symbols that
* can be used to configure several aspects of @OGLplus.
*
* Most of the options are set either to a zero or a non-zero
* integer value to disable or enable the behavior controlled
* by the option.
*
* All options have a default value which can be overriden by
* setting the option before @c oglplus/config.hpp is processed
* either by editing the @c oglplus/site_config.hpp file or by
* using the @c -D compiler option (or its equivalent for defining
* preprocessor symbols on the command-line).
*/
#include <oglplus/config_basic.hpp>
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the testing of object type on construction
/** Setting this preprocessor option to a non-zero integer value
* disables the additional checking of the type of object
* returned by OpenGL's @c glGen*(...) functions during the construction
* of an Object. Setting it to zero enables the check.
*
* By default this option is set to 1, i.e. object type tests are disabled.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_DONT_TEST_OBJECT_TYPE
#else
# ifndef OGLPLUS_DONT_TEST_OBJECT_TYPE
# define OGLPLUS_DONT_TEST_OBJECT_TYPE 1
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling textual object descriptions
/** Setting this preprocessor option to a non-zero integer value
* disables the @ref oglplus_object_description attached to
* various specializations of @c Object (like Program, Shader,
* Texture, etc.) during construction by the means of the ObjectDesc
* parameter in constructor of Object.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. objects descriptions are enabled, when not in low-profile mode
* and disabled otherwise.
*
* @note Object descriptions use statically initialized data which
* may cause problems if the final executable is built together from
* several different object files. Because of this, if object descriptions
* are enabled it is recommended that OGLplus applications are built with
* #OGLPLUS_LINK_LIBRARY set to non-zero or are built as a single translation
* unit.
*
* @see OGLPLUS_LINK_LIBRARY
*
* @ingroup compile_time_config
*/
#define OGLPLUS_NO_OBJECT_DESCS
#else
# ifndef OGLPLUS_NO_OBJECT_DESCS
# define OGLPLUS_NO_OBJECT_DESCS OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch enabling lazy implementation of StrLit
/** The StrLit class has two implementations, one referred to as 'Lazy'
* which only stores the pointer to the C-string literal where the size
* is obtained lazily only when required. The other implementation lets
* the compiler to determine and store the size of the literal during
* compilation.
*
* The advantage of the lazy implementation is smaller code size and slightly
* better compilation times, while the calculation of the size of the literal
* adds run-time overhead. The other implementation results in slightly
* larger binaries but has the advantage that the size of the literal is
* pre-calculated.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. lazy string literals are enabled, when in low-profile mode
* and disabled otherwise.
*
* @see StrLit
*
* @ingroup compile_time_config
*/
#define OGLPLUS_LAZY_STR_LIT
#else
# ifndef OGLPLUS_LAZY_STR_LIT
# define OGLPLUS_LAZY_STR_LIT OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the functions returning enumerated value names
/** Setting this preprocessor symbol to a nonzero value causes that
* the @c EnumValueName(Enum) functions always return an empty string.
* When set to zero these functions return a textual name of an enumerated
* value passed as argument.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. enumeration value names are enabled, when not in low-profile mode
* and disabled otherwise.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_NO_ENUM_VALUE_NAMES
#else
# ifndef OGLPLUS_NO_ENUM_VALUE_NAMES
# define OGLPLUS_NO_ENUM_VALUE_NAMES OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the functions returning enumerated value ranges
/** Setting this preprocessor symbol to a nonzero value causes that
* the @c EnumValueRange<Enum>() functions always return an empty range.
* When set to zero these functions return a range of all values in the
* enumeration passed as template argument.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. enumeration value ranges are enabled, when not in low-profile mode
* and disabled otherwise.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_NO_ENUM_VALUE_RANGES
#else
# ifndef OGLPLUS_NO_ENUM_VALUE_RANGES
# define OGLPLUS_NO_ENUM_VALUE_RANGES OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling UTF-8 validity checks in various functions
/** Setting this preprocessor symbol to a nonzero value causes that
* the @c StrLit and @c String constructors skip the UTF-8 validity checks.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. the UTF-8 validity checks are enabled, when not in low-profile mode
* and disabled otherwise.
*
* @see String
* @see StrLit
*
* @ingroup compile_time_config
*/
#define OGLPLUS_NO_UTF8_CHECKS
#else
# ifndef OGLPLUS_NO_UTF8_CHECKS
# define OGLPLUS_NO_UTF8_CHECKS OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling checks of validity of pointers to functions
/** Setting this preprocessor symbol to a nonzero value causes that
* if the OpenGL functions are called through a pointer then the pointer
* is checked before it is used to call the function. If enabled and a pointer
* to GL function is nullptr then the MissingFunction exception is thrown.
*
* This check can safely be disabled if functions from the GL API are
* not called through pointers.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. the function pointer checks are enabled, when not in low-profile mode,
* and disabled otherwise. The check however requires variadic templates.
* If variadic templates are not available then the checks are disabled.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_NO_GLFUNC_CHECKS
#else
# ifndef OGLPLUS_NO_GLFUNC_CHECKS
# define OGLPLUS_NO_GLFUNC_CHECKS OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch entirely disabling typechecking of uniforms.
/** Setting this preprocessor symbol to a nonzero value causes that
* even the Uniform variables that are declared with UniformTypecheckingLevel
* other than None, are not typechecked.
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. typechecking of uniforms is enabled when not in low-profile mode,
* and disabled otherwise.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_NO_UNIFORM_TYPECHECK
#else
# ifndef OGLPLUS_NO_UNIFORM_TYPECHECK
# define OGLPLUS_NO_UNIFORM_TYPECHECK OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch enabling customized @ref error_handling
/**
* By default this option is set to 0, i.e. customized error handling
* is is disabled.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_CUSTOM_ERROR_HANDLING
#else
# ifndef OGLPLUS_CUSTOM_ERROR_HANDLING
# define OGLPLUS_CUSTOM_ERROR_HANDLING 0
# endif
#endif
// Configuration options related to ErrorInfo
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorGLSymbol attribute of ErrorInfo
/**
* @see ErrorGLSymbol()
*
* By default this option is set to 0, i.e. ErrorGLSymbol is enabled.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_GL_SYMBOL
#else
# ifndef OGLPLUS_ERROR_INFO_NO_GL_SYMBOL
# define OGLPLUS_ERROR_INFO_NO_GL_SYMBOL 0
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorFile attribute of ErrorInfo
/**
* @see ErrorFile()
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. ErrorFile is enabled, when not in low-profile and disabled otherwise.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_FILE
#else
# ifndef OGLPLUS_ERROR_INFO_NO_FILE
# define OGLPLUS_ERROR_INFO_NO_FILE OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorLine attribute of ErrorInfo
/**
* @see ErrorLine()
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. ErrorLine is enabled, when not in low-profile and disabled otherwise.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_LINE OGLPLUS_LOW_PROFILE
#else
# ifndef OGLPLUS_ERROR_INFO_NO_LINE
# define OGLPLUS_ERROR_INFO_NO_LINE OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorFunc attribute of ErrorInfo
/**
* @see ErrorFunc()
*
* By default this option is set to 0, i.e. ErrorFunc is enabled.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_FUNC
#else
# ifndef OGLPLUS_ERROR_INFO_NO_FUNC
# define OGLPLUS_ERROR_INFO_NO_FUNC 0
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorClassName attribute of ErrorInfo
/**
* @see ErrorClassName()
*
* By default this option is set to 0, i.e. ErrorClassName is enabled.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_CLASS_NAME
#else
# ifndef OGLPLUS_ERROR_INFO_NO_CLASS_NAME
# define OGLPLUS_ERROR_INFO_NO_CLASS_NAME 0
# endif
#endif
#if OGLPLUS_NO_ENUM_VALUE_NAMES
#ifdef OGLPLUS_ERROR_INFO_NO_BIND_TARGET
#undef OGLPLUS_ERROR_INFO_NO_BIND_TARGET
#endif
#define OGLPLUS_ERROR_INFO_NO_BIND_TARGET 1
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorBindTarget attribute of ErrorInfo
/**
* @see ErrorBindTarget()
*
* By default this option is set to 0, i.e. ErrorBindTarget is enabled,
* unless #OGLPLUS_NO_ENUM_VALUE_NAMES is set to a non-zero value,
* in which case ErrorBindTarget is disabled and returns an empty string.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_BIND_TARGET
#else
# ifndef OGLPLUS_ERROR_INFO_NO_BIND_TARGET
# define OGLPLUS_ERROR_INFO_NO_BIND_TARGET 0
# endif
#endif
#if OGLPLUS_NO_OBJECT_DESCS
#ifdef OGLPLUS_ERROR_INFO_NO_OBJECT_DESC
#undef OGLPLUS_ERROR_INFO_NO_OBJECT_DESC
#endif
#define OGLPLUS_ERROR_INFO_NO_OBJECT_DESC 1
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the ErrorObjectDescription attribute of ErrorInfo
/**
* @see ErrorObjectDescription()
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. ErrorObjectDescription is enabled, when not in low-profile and disabled
* otherwise and returns an empty string.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_INFO_NO_OBJECT_DESC
#else
# ifndef OGLPLUS_ERROR_INFO_NO_OBJECT_DESC
# define OGLPLUS_ERROR_INFO_NO_OBJECT_DESC OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the PropagationInfo function in Error
/**
* @see Error::PropagationInfo()
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. Error::PropagationInfo() is enabled, when not in low-profile
* and disabled otherwise and returns an empty list.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_NO_PROPAGATION_INFO
#else
# ifndef OGLPLUS_ERROR_NO_PROPAGATION_INFO
# define OGLPLUS_ERROR_NO_PROPAGATION_INFO OGLPLUS_LOW_PROFILE
# endif
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Compile-time switch disabling the Properties in Error
/**
* @see Error::Properties()
*
* By default this option is set to the same value as #OGLPLUS_LOW_PROFILE,
* i.e. Error::Properties() is enabled, when not in low-profile
* and disabled otherwise and returns an empty map.
*
* @ingroup compile_time_config
*/
#define OGLPLUS_ERROR_NO_PROPERTIES
#else
# ifndef OGLPLUS_ERROR_NO_PROPERTIES
# define OGLPLUS_ERROR_NO_PROPERTIES OGLPLUS_LOW_PROFILE
# endif
#endif
#include <oglplus/auxiliary/enum_class.hpp>
#endif // include guard
| 31.013393 | 83 | 0.778466 | [
"object"
] |
b104c6a7c6b65a1eab88813adb5696f084d55835 | 3,244 | hpp | C++ | src/framework/shared/inc/private/um/fxinterruptthreadpoolum.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/shared/inc/private/um/fxinterruptthreadpoolum.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 13 | 2019-06-13T15:58:03.000Z | 2022-02-18T22:53:35.000Z | src/framework/shared/inc/private/um/fxinterruptthreadpoolum.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
FxInterruptThreadpoolUm.hpp
Abstract:
This file contains the class definition for the threadpool for interrupt object.
Author:
Environment:
User mode only
Revision History:
--*/
#pragma once
#define MINIMUM_THREAD_COUNT_DEFAULT (1)
class FxInterrupt;
class FxInterruptThreadpool : FxGlobalsStump
{
private:
//
// Pointer to structure representing thread pool
//
PTP_POOL m_Pool;
//
// Structure representing callback environment for thread pool
//
TP_CALLBACK_ENVIRON m_CallbackEnvironment;
//
// Minimum thread pool thread count
//
ULONG m_MinimumThreadCount;
HRESULT
Initialize(
);
public:
FxInterruptThreadpool(
PFX_DRIVER_GLOBALS FxDriverGlobals
);
using FxStump::operator delete;
~FxInterruptThreadpool();
static
HRESULT
_CreateAndInit(
_In_ PFX_DRIVER_GLOBALS DriverGlobals,
_Out_ FxInterruptThreadpool** ppThreadpool
);
PTP_CALLBACK_ENVIRON
GetCallbackEnvironment(
VOID
)
{
return &m_CallbackEnvironment;
}
PTP_WAIT
CreateThreadpoolWait(
__in PTP_WAIT_CALLBACK pfnwa,
__inout_opt PVOID Context
)
{
return ::CreateThreadpoolWait(pfnwa, Context, &m_CallbackEnvironment);
}
HRESULT
UpdateThreadPoolThreadLimits(
_In_ ULONG InterruptCount
);
};
class FxInterruptWaitblock : FxGlobalsStump
{
private:
//
// threadpool wait block
//
PTP_WAIT m_Wait;
//
// auto reset event
//
HANDLE m_Event;
HRESULT
Initialize(
__in FxInterruptThreadpool* Threadpool,
__in FxInterrupt* Interrupt,
__in PTP_WAIT_CALLBACK WaitCallback
);
public:
static
HRESULT
_CreateAndInit(
_In_ FxInterruptThreadpool* Threadpool,
_In_ FxInterrupt* Interrupt,
_In_ PTP_WAIT_CALLBACK WaitCallback,
_Out_ FxInterruptWaitblock** Waitblock
);
FxInterruptWaitblock(
PFX_DRIVER_GLOBALS FxDriverGlobals
) :
FxGlobalsStump(FxDriverGlobals),
m_Wait(NULL),
m_Event(NULL)
{
}
using FxStump::operator delete;
~FxInterruptWaitblock();
VOID
CloseThreadpoolWait(
VOID
)
{
::CloseThreadpoolWait(m_Wait);
}
VOID
SetThreadpoolWait(
VOID
)
{
//
// associates event with wait block and queues it
// to thread pool queue.
//
::SetThreadpoolWait(m_Wait, m_Event, NULL);
}
VOID
ClearThreadpoolWait(
VOID
)
{
//
// Passing a NULL handle clears the wait
//
::SetThreadpoolWait(m_Wait, NULL, NULL);
}
VOID
WaitForOutstandingCallbackToComplete(
VOID
)
{
::WaitForThreadpoolWaitCallbacks(m_Wait, FALSE);
}
HANDLE
GetEventHandle(
VOID
)
{
return m_Event;
}
VOID
ResetEvent(
VOID
)
{
::ResetEvent(m_Event);
}
};
| 16.22 | 84 | 0.59402 | [
"object"
] |
b1096ac10187e69084851042686dedafae167f14 | 4,068 | cpp | C++ | src/VideoNode.cpp | oskude/radiance | 006e32947513570638f551022faccffd8d86a33c | [
"MIT"
] | 143 | 2016-05-02T22:08:13.000Z | 2022-03-31T21:56:12.000Z | src/VideoNode.cpp | oskude/radiance | 006e32947513570638f551022faccffd8d86a33c | [
"MIT"
] | 95 | 2016-05-05T01:43:51.000Z | 2021-10-19T19:14:53.000Z | src/VideoNode.cpp | oskude/radiance | 006e32947513570638f551022faccffd8d86a33c | [
"MIT"
] | 19 | 2016-07-18T07:35:21.000Z | 2022-01-10T17:19:16.000Z | #include "VideoNode.h"
#include "Model.h"
#include <QtQml>
VideoNode::VideoNode(Context *context)
: m_context(context)
{
}
int VideoNode::inputCount() {
QMutexLocker locker(&m_stateLock);
return m_inputCount;
}
void VideoNode::setInputCount(int value) {
bool changed = false;
{
QMutexLocker locker(&m_stateLock);
if (value != m_inputCount) {
m_inputCount = value;
changed = true;
}
}
if (changed) emit inputCountChanged(value);
}
VideoNode::NodeState VideoNode::nodeState() {
QMutexLocker locker(&m_stateLock);
return m_nodeState;
}
void VideoNode::setNodeState(NodeState value) {
bool changed = false;
{
QMutexLocker locker(&m_stateLock);
if (value != m_nodeState) {
m_nodeState = value;
changed = true;
}
}
if (changed) emit nodeStateChanged(value);
}
QList<QSharedPointer<Chain>> VideoNode::chains() {
QMutexLocker locker(&m_stateLock);
return m_chains;
}
void VideoNode::setChains(QList<QSharedPointer<Chain>> chains) {
bool wereChainsChanged = false;
QList<QSharedPointer<Chain>> toRemove;
QList<QSharedPointer<Chain>> toAdd;
{
QMutexLocker locker(&m_stateLock);
toRemove = m_chains;
for (int i=0; i<chains.count(); i++) {
if (m_chains.contains(chains.at(i))) {
// If it exists already, don't remove it
toRemove.removeAll(chains.at(i));
} else {
// If it doesn't exist already, add it
toAdd.append(chains.at(i)); // Add it
}
}
if (!toAdd.empty() || !toRemove.empty()) {
m_chains = chains;
wereChainsChanged = true;
}
}
if (wereChainsChanged) {
chainsEdited(toAdd, toRemove);
emit chainsChanged(chains);
}
}
bool VideoNode::frozenInput() {
QMutexLocker locker(&m_stateLock);
return m_frozenInput;
}
void VideoNode::setFrozenInput(bool value) {
bool changed = false;
{
QMutexLocker locker(&m_stateLock);
if (value != m_frozenInput) {
m_frozenInput = value;
changed = true;
}
}
if (changed) emit frozenInputChanged(value);
}
bool VideoNode::frozenOutput() {
QMutexLocker locker(&m_stateLock);
return m_frozenOutput;
}
void VideoNode::setFrozenOutput(bool value) {
bool changed = false;
{
QMutexLocker locker(&m_stateLock);
if (value != m_frozenOutput) {
m_frozenOutput = value;
changed = true;
}
}
if (changed) emit frozenOutputChanged(value);
}
bool VideoNode::frozenParameters() {
QMutexLocker locker(&m_stateLock);
return m_frozenParameters;
}
void VideoNode::setFrozenParameters(bool value) {
bool changed = false;
{
QMutexLocker locker(&m_stateLock);
if (value != m_frozenParameters) {
m_frozenParameters = value;
changed = true;
}
}
if (changed) emit frozenParametersChanged(value);
}
Context *VideoNode::context() {
// Not mutable, so no need to lock
return m_context;
}
QJsonObject VideoNode::serialize() {
QJsonObject o;
o.insert("type", metaObject()->className());
return o;
}
QList<QSharedPointer<Chain>> VideoNode::requestedChains() {
return QList<QSharedPointer<Chain>>();
}
void VideoNode::chainsEdited(QList<QSharedPointer<Chain>> added, QList<QSharedPointer<Chain>> removed) {
}
GLuint VideoNode::paint(QSharedPointer<Chain> chain, QVector<GLuint> inputTextures) {
Q_UNUSED(chain);
Q_UNUSED(inputTextures);
return 0;
}
void VideoNode::setLastModel(QWeakPointer<Model> model) {
QMutexLocker locker(&m_stateLock);
m_lastModel = model;
}
QWeakPointer<Model> VideoNode::lastModel() {
QMutexLocker locker(&m_stateLock);
return m_lastModel;
}
QDebug operator<<(QDebug debug, const VideoNode &vn)
{
QDebugStateSaver saver(debug);
debug.nospace() << "VideoNode";
return debug;
}
| 24.214286 | 104 | 0.627581 | [
"model"
] |
b10b45ebb62f5b1c28f444361444d1915121652f | 13,998 | hpp | C++ | vlc_linux/vlc-3.0.16/modules/demux/mkv/demux.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/mkv/demux.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/mkv/demux.hpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*****************************************************************************
* demux.hpp : matroska demuxer
*****************************************************************************
* Copyright (C) 2003-2004 VLC authors and VideoLAN
* $Id: 314e1066a86fc88a48679f02fb95ee34a5b17b8c $
*
* Authors: Laurent Aimar <fenrir@via.ecp.fr>
* Steve Lhomme <steve.lhomme@free.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef VLC_MKV_DEMUX_HPP_
#define VLC_MKV_DEMUX_HPP_
#include "mkv.hpp"
#include "chapter_command.hpp"
#include "virtual_segment.hpp"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#undef ATTRIBUTE_PACKED
#undef PRAGMA_PACK_BEGIN
#undef PRAGMA_PACK_END
#if defined(__GNUC__)
#define ATTRIBUTE_PACKED __attribute__ ((packed))
#define PRAGMA_PACK 0
#endif
#if !defined(ATTRIBUTE_PACKED)
#define ATTRIBUTE_PACKED
#define PRAGMA_PACK 1
#endif
#if PRAGMA_PACK
#pragma pack(1)
#endif
/*************************************
* taken from libdvdnav / libdvdread
**************************************/
/**
* DVD Time Information.
*/
typedef struct {
uint8_t hour;
uint8_t minute;
uint8_t second;
uint8_t frame_u; /* The two high bits are the frame rate. */
} ATTRIBUTE_PACKED dvd_time_t;
/**
* User Operations.
*/
typedef struct {
#ifdef WORDS_BIGENDIAN
unsigned char zero : 7; /* 25-31 */
unsigned char video_pres_mode_change : 1; /* 24 */
unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
unsigned char angle_change : 1;
unsigned char subpic_stream_change : 1;
unsigned char audio_stream_change : 1;
unsigned char pause_on : 1;
unsigned char still_off : 1;
unsigned char button_select_or_activate : 1;
unsigned char resume : 1; /* 16 */
unsigned char chapter_menu_call : 1; /* 15 */
unsigned char angle_menu_call : 1;
unsigned char audio_menu_call : 1;
unsigned char subpic_menu_call : 1;
unsigned char root_menu_call : 1;
unsigned char title_menu_call : 1;
unsigned char backward_scan : 1;
unsigned char forward_scan : 1; /* 8 */
unsigned char next_pg_search : 1; /* 7 */
unsigned char prev_or_top_pg_search : 1;
unsigned char time_or_chapter_search : 1;
unsigned char go_up : 1;
unsigned char stop : 1;
unsigned char title_play : 1;
unsigned char chapter_search_or_play : 1;
unsigned char title_or_time_play : 1; /* 0 */
#else
unsigned char video_pres_mode_change : 1; /* 24 */
unsigned char zero : 7; /* 25-31 */
unsigned char resume : 1; /* 16 */
unsigned char button_select_or_activate : 1;
unsigned char still_off : 1;
unsigned char pause_on : 1;
unsigned char audio_stream_change : 1;
unsigned char subpic_stream_change : 1;
unsigned char angle_change : 1;
unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
unsigned char forward_scan : 1; /* 8 */
unsigned char backward_scan : 1;
unsigned char title_menu_call : 1;
unsigned char root_menu_call : 1;
unsigned char subpic_menu_call : 1;
unsigned char audio_menu_call : 1;
unsigned char angle_menu_call : 1;
unsigned char chapter_menu_call : 1; /* 15 */
unsigned char title_or_time_play : 1; /* 0 */
unsigned char chapter_search_or_play : 1;
unsigned char title_play : 1;
unsigned char stop : 1;
unsigned char go_up : 1;
unsigned char time_or_chapter_search : 1;
unsigned char prev_or_top_pg_search : 1;
unsigned char next_pg_search : 1; /* 7 */
#endif
} ATTRIBUTE_PACKED user_ops_t;
/**
* Type to store per-command data.
*/
typedef struct {
uint8_t bytes[8];
} ATTRIBUTE_PACKED vm_cmd_t;
#define COMMAND_DATA_SIZE 8
/**
* PCI General Information
*/
typedef struct {
uint32_t nv_pck_lbn; /**< sector address of this nav pack */
uint16_t vobu_cat; /**< 'category' of vobu */
uint16_t zero1; /**< reserved */
user_ops_t vobu_uop_ctl; /**< UOP of vobu */
uint32_t vobu_s_ptm; /**< start presentation time of vobu */
uint32_t vobu_e_ptm; /**< end presentation time of vobu */
uint32_t vobu_se_e_ptm; /**< end ptm of sequence end in vobu */
dvd_time_t e_eltm; /**< Cell elapsed time */
char vobu_isrc[32];
} ATTRIBUTE_PACKED pci_gi_t;
/**
* Non Seamless Angle Information
*/
typedef struct {
uint32_t nsml_agl_dsta[9]; /**< address of destination vobu in AGL_C#n */
} ATTRIBUTE_PACKED nsml_agli_t;
/**
* Highlight General Information
*
* For btngrX_dsp_ty the bits have the following meaning:
* 000b: normal 4/3 only buttons
* XX1b: wide (16/9) buttons
* X1Xb: letterbox buttons
* 1XXb: pan&scan buttons
*/
typedef struct {
uint16_t hli_ss; /**< status, only low 2 bits 0: no buttons, 1: different 2: equal 3: eual except for button cmds */
uint32_t hli_s_ptm; /**< start ptm of hli */
uint32_t hli_e_ptm; /**< end ptm of hli */
uint32_t btn_se_e_ptm; /**< end ptm of button select */
#ifdef WORDS_BIGENDIAN
unsigned char zero1 : 2; /**< reserved */
unsigned char btngr_ns : 2; /**< number of button groups 1, 2 or 3 with 36/18/12 buttons */
unsigned char zero2 : 1; /**< reserved */
unsigned char btngr1_dsp_ty : 3; /**< display type of subpic stream for button group 1 */
unsigned char zero3 : 1; /**< reserved */
unsigned char btngr2_dsp_ty : 3; /**< display type of subpic stream for button group 2 */
unsigned char zero4 : 1; /**< reserved */
unsigned char btngr3_dsp_ty : 3; /**< display type of subpic stream for button group 3 */
#else
unsigned char btngr1_dsp_ty : 3;
unsigned char zero2 : 1;
unsigned char btngr_ns : 2;
unsigned char zero1 : 2;
unsigned char btngr3_dsp_ty : 3;
unsigned char zero4 : 1;
unsigned char btngr2_dsp_ty : 3;
unsigned char zero3 : 1;
#endif
uint8_t btn_ofn; /**< button offset number range 0-255 */
uint8_t btn_ns; /**< number of valid buttons <= 36/18/12 (low 6 bits) */
uint8_t nsl_btn_ns; /**< number of buttons selectable by U_BTNNi (low 6 bits) nsl_btn_ns <= btn_ns */
uint8_t zero5; /**< reserved */
uint8_t fosl_btnn; /**< forcedly selected button (low 6 bits) */
uint8_t foac_btnn; /**< forcedly activated button (low 6 bits) */
} ATTRIBUTE_PACKED hl_gi_t;
/**
* Button Color Information Table
* Each entry beeing a 32bit word that contains the color indexs and alpha
* values to use. They are all represented by 4 bit number and stored
* like this [Ci3, Ci2, Ci1, Ci0, A3, A2, A1, A0]. The actual palette
* that the indexes reference is in the PGC.
* \todo split the uint32_t into a struct
*/
typedef struct {
uint32_t btn_coli[3][2]; /**< [button color number-1][select:0/action:1] */
} ATTRIBUTE_PACKED btn_colit_t;
/**
* Button Information
*
* NOTE: I've had to change the structure from the disk layout to get
* the packing to work with Sun's Forte C compiler.
* The 4 and 7 bytes are 'rotated' was: ABC DEF GHIJ is: ABCG DEFH IJ
*/
typedef struct {
#ifdef WORDS_BIGENDIAN
uint32 btn_coln : 2; /**< button color number */
uint32 x_start : 10; /**< x start offset within the overlay */
uint32 zero1 : 2; /**< reserved */
uint32 x_end : 10; /**< x end offset within the overlay */
uint32 zero3 : 2; /**< reserved */
uint32 up : 6; /**< button index when pressing up */
uint32 auto_action_mode : 2; /**< 0: no, 1: activated if selected */
uint32 y_start : 10; /**< y start offset within the overlay */
uint32 zero2 : 2; /**< reserved */
uint32 y_end : 10; /**< y end offset within the overlay */
uint32 zero4 : 2; /**< reserved */
uint32 down : 6; /**< button index when pressing down */
unsigned char zero5 : 2; /**< reserved */
unsigned char left : 6; /**< button index when pressing left */
unsigned char zero6 : 2; /**< reserved */
unsigned char right : 6; /**< button index when pressing right */
#else
uint32 x_end : 10;
uint32 zero1 : 2;
uint32 x_start : 10;
uint32 btn_coln : 2;
uint32 up : 6;
uint32 zero3 : 2;
uint32 y_end : 10;
uint32 zero2 : 2;
uint32 y_start : 10;
uint32 auto_action_mode : 2;
uint32 down : 6;
uint32 zero4 : 2;
unsigned char left : 6;
unsigned char zero5 : 2;
unsigned char right : 6;
unsigned char zero6 : 2;
#endif
vm_cmd_t cmd;
} ATTRIBUTE_PACKED btni_t;
/**
* Highlight Information
*/
typedef struct {
hl_gi_t hl_gi;
btn_colit_t btn_colit;
btni_t btnit[36];
} ATTRIBUTE_PACKED hli_t;
/**
* PCI packet
*/
typedef struct {
pci_gi_t pci_gi;
nsml_agli_t nsml_agli;
hli_t hli;
uint8_t zero1[189];
} ATTRIBUTE_PACKED pci_t;
#if PRAGMA_PACK
#pragma pack()
#endif
////////////////////////////////////////
class virtual_segment_c;
class chapter_item_c;
class event_thread_t
{
public:
event_thread_t(demux_t *);
virtual ~event_thread_t();
void SetPci(const pci_t *data);
void ResetPci();
private:
void EventThread();
static void *EventThread(void *);
static int EventMouse( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
static int EventKey( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
static int EventInput( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
demux_t *p_demux;
bool is_running;
vlc_thread_t thread;
vlc_mutex_t lock;
vlc_cond_t wait;
bool b_abort;
bool b_moved;
bool b_clicked;
int i_key_action;
bool b_vout;
pci_t pci_packet;
};
struct demux_sys_t
{
public:
demux_sys_t( demux_t & demux )
:demuxer(demux)
,i_pts(VLC_TS_INVALID)
,i_pcr(VLC_TS_INVALID)
,i_start_pts(VLC_TS_0)
,i_mk_chapter_time(0)
,meta(NULL)
,i_current_title(0)
,p_current_vsegment(NULL)
,dvd_interpretor( *this )
,f_duration(-1.0)
,p_input(NULL)
,p_ev(NULL)
{
vlc_mutex_init( &lock_demuxer );
}
virtual ~demux_sys_t();
/* current data */
demux_t & demuxer;
mtime_t i_pts;
mtime_t i_pcr;
mtime_t i_start_pts;
mtime_t i_mk_chapter_time;
vlc_meta_t *meta;
std::vector<input_title_t*> titles; // matroska editions
size_t i_current_title;
std::vector<matroska_stream_c*> streams;
std::vector<attachment_c*> stored_attachments;
std::vector<matroska_segment_c*> opened_segments;
std::vector<virtual_segment_c*> used_vsegments;
virtual_segment_c *p_current_vsegment;
dvd_command_interpretor_c dvd_interpretor;
/* duration of the stream */
float f_duration;
matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
virtual_chapter_c *BrowseCodecPrivate( unsigned int codec_id,
bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
const void *p_cookie,
size_t i_cookie_size,
virtual_segment_c * & p_vsegment_found );
virtual_chapter_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_vsegment_found );
void PreloadFamily( const matroska_segment_c & of_segment );
bool PreloadLinked();
bool FreeUnused();
bool PreparePlayback( virtual_segment_c & new_vsegment, mtime_t i_mk_date );
bool AnalyseAllSegmentsFound( demux_t *p_demux, matroska_stream_c *, bool b_initial = false );
void JumpTo( virtual_segment_c & vsegment, virtual_chapter_c & vchapter );
void InitUi();
void CleanUi();
/* for spu variables */
input_thread_t *p_input;
uint8_t palette[4][4];
vlc_mutex_t lock_demuxer;
/* event */
event_thread_t *p_ev;
};
#endif
| 34.648515 | 133 | 0.581583 | [
"vector"
] |
624185d70aeaa27005ff27d074e3440366c45971 | 3,143 | cpp | C++ | extensions/http-curl/tests/C2LogHeartbeatTest.cpp | nandorsoma/nifi-minifi-cpp | 182e5b98a390d6073c43ffc88ecf7511ad0d3ff5 | [
"Apache-2.0"
] | null | null | null | extensions/http-curl/tests/C2LogHeartbeatTest.cpp | nandorsoma/nifi-minifi-cpp | 182e5b98a390d6073c43ffc88ecf7511ad0d3ff5 | [
"Apache-2.0"
] | null | null | null | extensions/http-curl/tests/C2LogHeartbeatTest.cpp | nandorsoma/nifi-minifi-cpp | 182e5b98a390d6073c43ffc88ecf7511ad0d3ff5 | [
"Apache-2.0"
] | null | null | null | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#undef NDEBUG
#include "TestBase.h"
#include "Catch.h"
#include "c2/C2Agent.h"
#include "c2/HeartbeatLogger.h"
#include "protocols/RESTProtocol.h"
#include "protocols/RESTSender.h"
#include "HTTPIntegrationBase.h"
#include "HTTPHandlers.h"
#include "range/v3/action/sort.hpp"
#include "range/v3/action/unique.hpp"
#include "range/v3/range/conversion.hpp"
#include "range/v3/view/filter.hpp"
#include "range/v3/view/split.hpp"
#include "range/v3/view/transform.hpp"
#include "utils/IntegrationTestUtils.h"
#include "utils/StringUtils.h"
#include "properties/Configuration.h"
class VerifyLogC2Heartbeat : public VerifyC2Base {
public:
void testSetup() override {
LogTestController::getInstance().setTrace<minifi::c2::C2Agent>();
LogTestController::getInstance().setDebug<minifi::c2::RESTSender>();
LogTestController::getInstance().setDebug<minifi::c2::RESTProtocol>();
// the heartbeat is logged at TRACE level
LogTestController::getInstance().setTrace<minifi::c2::HeartbeatLogger>();
VerifyC2Base::testSetup();
}
void runAssertions() override {
using org::apache::nifi::minifi::utils::verifyLogLinePresenceInPollTime;
assert(verifyLogLinePresenceInPollTime(
std::chrono::milliseconds(wait_time_),
"\"operation\": \"heartbeat\""));
const auto log = LogTestController::getInstance().log_output.str();
auto types_in_heartbeat = log | ranges::views::split('\n')
| ranges::views::transform([](auto&& rng) { return rng | ranges::to<std::string>; })
| ranges::views::filter([](auto&& line) { return utils::StringUtils::startsWith(line, " \"type\":"); })
| ranges::to<std::vector<std::string>>;
const auto num_types = types_in_heartbeat.size();
types_in_heartbeat |= ranges::actions::sort | ranges::actions::unique;
const auto num_distinct_types = types_in_heartbeat.size();
assert(num_types == num_distinct_types);
}
void configureC2() override {
VerifyC2Base::configureC2();
configuration->set(org::apache::nifi::minifi::Configuration::nifi_c2_agent_heartbeat_reporter_classes, "HeartbeatLogger");
}
};
int main() {
VerifyLogC2Heartbeat harness;
HeartbeatHandler responder(harness.getConfiguration());
harness.setUrl("https://localhost:0/heartbeat", &responder);
harness.run();
}
| 39.2875 | 142 | 0.721285 | [
"vector",
"transform"
] |
62523ae878ef63350fa20f64529c24b73121d7ea | 3,118 | cpp | C++ | aoc2016/aoc162302.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | aoc2016/aoc162302.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | aoc2016/aoc162302.cpp | jiayuehua/adventOfCode | fd47ddefd286fe94db204a9850110f8d1d74d15b | [
"Unlicense"
] | null | null | null | #include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <fmt/format.h>
#include <string>
#include <cctype>
#include <unordered_map>
#include <map>
#include <range/v3/all.hpp>
struct Machine
{
typedef void (Machine::*MemFunc)(const std::string &l, const std::string &r);
std::map<std::string, MemFunc> calls_;
std::map<std::string, std::string> togglefuns_;
Machine()
{
m["a"] = 12;
m["b"] = 0;
m["c"] = 0;
m["d"] = 0;
calls_["cpy"] = &Machine::cpy;
calls_["dec"] = &Machine::dec;
calls_["inc"] = &Machine::inc;
calls_["jnz"] = &Machine::jnz;
calls_["tgl"] = &Machine::tgl;
togglefuns_["inc"] = "dec";
togglefuns_["dec"] = "inc";
togglefuns_["tgl"] = "inc";
togglefuns_["jnz"] = "cpy";
togglefuns_["cpy"] = "jnz";
}
friend std::istream &operator>>(std::istream &is, Machine &m)
{
std::string op, opanda, opandb;
while (is >> op >> opanda >> opandb) {
m.ops_.push_back(std::make_tuple(op, std::move(opanda), std::move(opandb)));
}
return is;
}
int pos_ = 0;
std::unordered_map<std::string, int> m;
std::vector<std::tuple<std::string, std::string, std::string>> ops_;
void jnz(const std::string &operand, const std::string &v)
{
int n = getvalue(operand);
int value = getvalue(v);
if (n) {
pos_ += value;
} else {
++pos_;
}
}
void tgl(const std::string &lhs, const std::string &rhs)
{
int offset = getvalue(lhs);
if (valid(pos_ + offset)) {
auto &op = std::get<0>(ops_[pos_ + offset]);
op = togglefuns_[op];
}
++pos_;
}
int getvalue(const std::string &operand)
{
int n;
if (std::isdigit(operand[0]) || operand[0] == '-') {
n = std::stoi(operand);
} else {
n = m[operand];
}
return n;
}
bool isnumber(const std::string &s) const
{
return std::isdigit(s[0]) || s[0] == '-';
}
void cpy(const std::string &lhs, const std::string &rhs)
{
if (!isnumber(rhs)) {
auto value = getvalue(lhs);
m[rhs] = value;
}
++pos_;
}
void inc(const std::string &lhs, const std::string &)
{
++m[lhs];
++pos_;
}
void dec(const std::string &lhs, const std::string &)
{
--m[lhs];
++pos_;
}
bool valid() const
{
return (0 <= pos_) && (pos_ < ops_.size());
}
bool valid(int pos) const
{
return (0 <= pos) && (pos < ops_.size());
}
void execute()
{
while (valid()) {
//fmt::print("a:{},b:{},c:{},d:{};", m["a"], m["b"], m["c"], m["d"]);
if (pos_ == 9) {
m["a"] = m["a"] + m["b"] * m["d"];
++pos_;
continue;
}
fmt::print("pos:{},{} {} {}\n", pos_, std::get<0>(this->ops_[pos_]), std::get<1>(this->ops_[pos_]), std::get<2>(this->ops_[pos_]));
auto op = calls_[std::get<0>(this->ops_[pos_])];
(this->*op)(std::get<1>(this->ops_[pos_]), std::get<2>(this->ops_[pos_]));
}
}
};
int main(int argc, char **argv)
{
if (argc > 1) {
std::ifstream ifs(argv[1]);
Machine m;
ifs >> m;
m.execute();
fmt::print("{}\n", m.m["a"]);
}
} | 23.443609 | 137 | 0.527261 | [
"vector"
] |
625f01e877b30060e78a40aca6476c23789f2841 | 5,086 | cpp | C++ | src/mempoolmonitor.cpp | LaplaceKorea/blockchain-indexer | f2ae12d3afe68ea599198cfa24334fe71293f97c | [
"MIT"
] | 12 | 2018-02-06T00:54:15.000Z | 2021-07-04T21:56:48.000Z | src/mempoolmonitor.cpp | Lattice-Trade/blockchain-indexer | f2ae12d3afe68ea599198cfa24334fe71293f97c | [
"MIT"
] | 5 | 2018-02-05T18:56:12.000Z | 2022-01-27T16:09:20.000Z | src/mempoolmonitor.cpp | Lattice-Trade/blockchain-indexer | f2ae12d3afe68ea599198cfa24334fe71293f97c | [
"MIT"
] | 8 | 2018-02-05T19:00:56.000Z | 2022-01-27T17:07:10.000Z | /* VTC Blockindexer - A utility to build additional indexes to the
Vertcoin blockchain by scanning and indexing the blockfiles
downloaded by Vertcoin Core.
Copyright (C) 2017 Gert-Jaap Glasbergen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mempoolmonitor.h"
#include "utility.h"
#include "scriptsolver.h"
#include "blockchaintypes.h"
#include <unordered_map>
#include <chrono>
#include <thread>
#include <time.h>
#include "byte_array_buffer.h"
using namespace std;
// This map keeps the memorypool transactions deserialized in memory.
VtcBlockIndexer::MempoolMonitor::MempoolMonitor() {
httpClient.reset(new jsonrpc::HttpClient("http://middleware:middleware@" + std::string(std::getenv("COIND_HOST")) + ":8332"));
vertcoind.reset(new VertcoinClient(*httpClient));
blockReader.reset(new VtcBlockIndexer::BlockReader(""));
scriptSolver.reset(new VtcBlockIndexer::ScriptSolver());
}
void VtcBlockIndexer::MempoolMonitor::startWatcher() {
while(true) {
try {
const Json::Value mempool = vertcoind->getrawmempool();
for ( uint index = 0; index < mempool.size(); ++index )
{
if(mempoolTransactions.find(mempool[index].asString()) == mempoolTransactions.end()) {
const Json::Value rawTx = vertcoind->getrawtransaction(mempool[index].asString(), false);
std::vector<unsigned char> rawTxBytes = VtcBlockIndexer::Utility::hexToBytes(rawTx.asString());
byte_array_buffer streambuf(&rawTxBytes[0], rawTxBytes.size());
std::istream stream(&streambuf);
VtcBlockIndexer::Transaction tx = blockReader->readTransaction(stream);
mempoolTransactions[mempool[index].asString()] = tx;
for(VtcBlockIndexer::TransactionOutput out : tx.outputs) {
out.txHash = tx.txHash;
vector<string> addresses = scriptSolver->getAddressesFromScript(out.script);
for(string address : addresses) {
if(addressMempoolTransactions.find(address) == addressMempoolTransactions.end())
{
addressMempoolTransactions[address] = {};
}
addressMempoolTransactions[address].push_back(out);
}
}
}
}
} catch(const jsonrpc::JsonRpcException& e) {
const std::string message(e.what());
cout << "Error reading mempool " << message << endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
string VtcBlockIndexer::MempoolMonitor::outpointSpend(string txid, uint32_t vout) {
for (auto kvp : mempoolTransactions) {
VtcBlockIndexer::Transaction tx = kvp.second;
for (VtcBlockIndexer::TransactionInput txi : tx.inputs) {
if(txi.txHash.compare(txid) == 0 && txi.txoIndex == vout) {
return tx.txHash;
}
}
}
return "";
}
vector<VtcBlockIndexer::TransactionOutput> VtcBlockIndexer::MempoolMonitor::getTxos(std::string address) {
if(addressMempoolTransactions.find(address) == addressMempoolTransactions.end())
{
return {};
}
return vector<VtcBlockIndexer::TransactionOutput>(addressMempoolTransactions[address]);
}
void VtcBlockIndexer::MempoolMonitor::transactionIndexed(std::string txid) {
if(mempoolTransactions.find(txid) != mempoolTransactions.end()) {
mempoolTransactions.erase(txid);
unordered_map<string, std::vector<VtcBlockIndexer::TransactionOutput>> changedMempoolAddressTxes;
for (auto kvp : addressMempoolTransactions) {
vector<VtcBlockIndexer::TransactionOutput> newVector = {};
bool itemsRemoved = false;
for (VtcBlockIndexer::TransactionOutput txo : kvp.second) {
if(txo.txHash.compare(txid) != 0) {
newVector.push_back(txo);
} else {
itemsRemoved = true;
}
}
if(itemsRemoved) {
changedMempoolAddressTxes[kvp.first] = newVector;
}
}
for (auto kvp : changedMempoolAddressTxes) {
addressMempoolTransactions[kvp.first] = kvp.second;
}
}
}
| 40.047244 | 130 | 0.6221 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.