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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d9d9ce5902682f9c628ed76751ef40cfb054ac22 | 1,327 | cpp | C++ | openbr/plugins/metadata/normalizemetadata.cpp | kassemitani/openbr | 7b453f7abc6f997839a858f4b7686bc5e21ef7b2 | [
"Apache-2.0"
] | 1,883 | 2015-01-04T07:04:24.000Z | 2022-03-30T13:33:37.000Z | openbr/plugins/metadata/normalizemetadata.cpp | kassemitani/openbr | 7b453f7abc6f997839a858f4b7686bc5e21ef7b2 | [
"Apache-2.0"
] | 272 | 2015-01-02T09:53:20.000Z | 2022-03-29T08:04:33.000Z | openbr/plugins/metadata/normalizemetadata.cpp | kassemitani/openbr | 7b453f7abc6f997839a858f4b7686bc5e21ef7b2 | [
"Apache-2.0"
] | 718 | 2015-01-02T18:51:07.000Z | 2022-03-29T08:10:53.000Z | #include <openbr/plugins/openbr_internal.h>
namespace br
{
/*!
* \ingroup transforms
* \brief Normalize a floating point metadata item to be between -1 and 1. Useful for classifier labels.
* \br_property QString inputVariable Metadata key for the item to scale. Default is empty string.
* \br_property float min Minimum possible value for the metadata item (will be scaled to -1). Default is -1.
* \br_property float min Maximum possible value for the metadata item (will be scaled to 1). Default is 1.
* \author Scott Klum \cite sklum
*/
class NormalizeMetadataTransform : public UntrainableMetadataTransform
{
Q_OBJECT
Q_PROPERTY(QString inputVariable READ get_inputVariable WRITE set_inputVariable RESET reset_inputVariable STORED false)
Q_PROPERTY(float min READ get_min WRITE set_min RESET reset_min STORED false)
Q_PROPERTY(float max READ get_max WRITE set_max RESET reset_max STORED false)
BR_PROPERTY(QString, inputVariable, QString())
BR_PROPERTY(float, min, -1)
BR_PROPERTY(float, max, 1)
void projectMetadata(const File &src, File &dst) const
{
dst = src;
dst.set(inputVariable,2*(dst.get<float>(inputVariable)-min)/(max-min)-1);
}
};
BR_REGISTER(Transform, NormalizeMetadataTransform)
} // namespace br
#include "metadata/normalizemetadata.moc"
| 34.921053 | 123 | 0.752072 | [
"transform"
] |
d9db94058235e28af932bf55aa9822936fd25c58 | 4,847 | cpp | C++ | heat2d-sycl/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 58 | 2020-08-06T18:53:44.000Z | 2021-10-01T07:59:46.000Z | heat2d-sycl/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 2 | 2020-12-04T12:35:02.000Z | 2021-03-04T22:49:25.000Z | heat2d-sycl/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 13 | 2020-08-19T13:44:18.000Z | 2021-09-08T04:25:34.000Z | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <sys/time.h>
#include <math.h>
#include <vector>
#include "defs.h"
#include "common.h"
#include "io.c"
#include "lapl_ss.c"
double
stop_watch(double t0)
{
double time;
struct timeval t;
gettimeofday(&t, NULL);
time = (double) t.tv_sec + (double) t.tv_usec * 1e-6;
return time-t0;
}
void
usage(char *argv[]) {
fprintf(stderr, " Usage: %s LX LY NITER IN_FILE\nIN_FILE can be generated by python mkinit LX LY IN_FILE\n",
argv[0]);
return;
}
int Lx, Ly;
int main(int argc, char *argv[]) {
/* Check the number of command line arguments */
if(argc != 5) {
usage(argv);
exit(1);
}
/* The length of the array in x and y is read from the command
line */
Lx = atoi(argv[1]);
Ly = atoi(argv[2]);
if (Lx % NTX != 0 || Ly % NTY != 0) {
printf("Array length LX and LY must be a multiple of block size %d and %d, respectively\n",
NTX, NTY);
exit(1);
}
/* The number of iterations */
int niter = atoi(argv[3]);
assert(niter >= 1);
/* Fixed "sigma" */
float sigma = 0.01;
printf(" Ly,Lx = %d,%d\n", Ly, Lx);
printf(" niter = %d\n", niter);
printf(" input file = %s\n", argv[4]);
/* Allocate the buffer for the data */
float *cpu_arr = (float*) malloc(sizeof(float)*Lx*Ly);
/* read file to buffer */
read_from_file(cpu_arr, argv[4]);
/* allocate super-site buffers */
supersite *ssarr[2];
posix_memalign((void**)&ssarr[0], 16, sizeof(supersite)*Lx*Ly/4);
posix_memalign((void**)&ssarr[1], 16, sizeof(supersite)*Lx*Ly/4);
/* convert input array to super-site packed */
to_supersite(ssarr[0], cpu_arr);
/* do iterations, record time */
double t0 = stop_watch(0);
for(int i=0; i<niter; i++) {
lapl_iter_supersite(ssarr[(i+1)%2], sigma, ssarr[i%2]);
}
t0 = stop_watch(t0)/(double)niter;
/* write the result after niter iteraions */
//char fname[256];
/* construct filename */
//sprintf(fname, "%s.ss%08d", argv[5], niter);
/* convert from super-site packed */
from_supersite(cpu_arr, ssarr[niter%2]);
/* write to file */
//write_to_file(fname, arr);
/* write timing info */
printf(" iters = %8d, (Lx,Ly) = %6d, %6d, t = %8.1f usec/iter, BW = %6.3f GB/s, P = %6.3f Gflop/s\n",
niter, Lx, Ly, t0*1e6,
Lx*Ly*sizeof(float)*2.0/(t0*1.0e9),
(Lx*Ly*6.0)/(t0*1.0e9));
/* free super-site buffers */
for(int i=0; i<2; i++) {
free(ssarr[i]);
}
/*
* GPU part
*/
/* read file again for GPU run */
float *gpu_arr = (float*) malloc(sizeof(float)*Lx*Ly);
read_from_file(gpu_arr, argv[4]);
float xdelta = sigma / (1.0+4.0*sigma);
float xnorm = 1.0/(1.0+4.0*sigma);
{
#ifdef USE_GPU
gpu_selector dev_sel;
#else
cpu_selector dev_sel;
#endif
queue q(dev_sel);
int lx = Lx;
int ly = Ly;
buffer<float, 1> d_in(lx*ly);
buffer<float, 1> d_out(lx*ly);
d_in.set_final_data(nullptr);
d_out.set_final_data(nullptr);
q.submit([&](auto &h) {
auto a = d_in.get_access<sycl_write>(h);
h.copy(gpu_arr, a);
});
q.wait();
// start timer
t0 = stop_watch(0);
auto global_range = range<1>(ly*lx);
auto local_range = range<1>(NTY*NTX);
for(int i=0; i<niter; i++) {
q.submit([&](auto &h) {
auto out = d_out.get_access<sycl_write>(h);
auto in = d_in.get_access<sycl_read>(h);
h.template parallel_for<class stencil>(nd_range<1>(global_range, local_range), [=](nd_item<1> item) {
int idx = item.get_global_id(0);
int x = idx % lx;
int y = idx / lx;
int v00 = y*lx + x;
int v0p = y*lx + (x + 1)%lx;
int v0m = y*lx + (lx + x - 1)%lx;
int vp0 = ((y+1)%ly)*lx + x;
int vm0 = ((ly+y-1)%ly)*lx + x;
out[v00] = xnorm*in[v00] + xdelta*(in[v0p] + in[v0m] + in[vp0] + in[vm0]);
});
});
// Pointer swap
auto tmp = std::move(d_in);
d_in = std::move(d_out);
d_out = std::move(tmp);
}
q.wait();
t0 = stop_watch(t0)/(double)niter;
q.submit([&](auto &h) {
auto a = d_in.get_access<sycl_read>(h);
h.copy(a, gpu_arr);
});
}
printf("Device: iters = %8d, (Lx,Ly) = %6d, %6d, t = %8.1f usec/iter, BW = %6.3f GB/s, P = %6.3f Gflop/s\n",
niter, Lx, Ly, t0*1e6,
Lx*Ly*sizeof(float)*2.0/(t0*1.0e9),
(Lx*Ly*6.0)/(t0*1.0e9));
// verification
for (int i = 0; i < Lx*Ly; i++) {
// choose 1e-2 because the error rate increases with the iteration from 1 to 100000
if ( std::fabs(cpu_arr[i] - gpu_arr[i]) > 1e-2 ) {
printf("FAILED at %d cpu=%f gpu=%f\n", i, cpu_arr[i], gpu_arr[i]);
/* free main memory array */
free(cpu_arr);
free(gpu_arr);
return 1;
}
}
/* write to file */
//write_to_file(fname, arr);
/* write timing info */
free(cpu_arr);
free(gpu_arr);
return 0;
}
| 26.2 | 111 | 0.579534 | [
"vector"
] |
d9dc888c9ec3f6929f56862d8fcd8af2d756d912 | 7,503 | cpp | C++ | Base/PLMesh/src/Creator/MeshCreatorTorus.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLMesh/src/Creator/MeshCreatorTorus.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 19 | 2018-08-24T08:10:13.000Z | 2018-11-29T06:39:08.000Z | Base/PLMesh/src/Creator/MeshCreatorTorus.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: MeshCreatorTorus.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLMath/Vector2.h>
#include <PLRenderer/Renderer/IndexBuffer.h>
#include <PLRenderer/Renderer/VertexBuffer.h>
#include "PLMesh/Geometry.h"
#include "PLMesh/MeshManager.h"
#include "PLMesh/MeshLODLevel.h"
#include "PLMesh/MeshMorphTarget.h"
#include "PLMesh/Creator/MeshCreatorTorus.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
using namespace PLMath;
using namespace PLRenderer;
namespace PLMesh {
//[-------------------------------------------------------]
//[ RTTI interface ]
//[-------------------------------------------------------]
pl_implement_class(MeshCreatorTorus)
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Default constructor
*/
MeshCreatorTorus::MeshCreatorTorus() :
Radius(this),
Width(this),
Sides(this),
Rings(this),
Offset(this)
{
}
/**
* @brief
* Destructor
*/
MeshCreatorTorus::~MeshCreatorTorus()
{
}
//[-------------------------------------------------------]
//[ Private virtual MeshCreator functions ]
//[-------------------------------------------------------]
Mesh *MeshCreatorTorus::Create(Mesh &cMesh, uint32 nLODLevel, bool bStatic) const
{
// Call base implementation
MeshCreator::Create(cMesh, nLODLevel, bStatic);
// Get morph target
MeshMorphTarget *pMorphTarget = cMesh.GetMorphTarget(0);
if (pMorphTarget && pMorphTarget->GetVertexBuffer()) {
// Increment sides and rings to handle texture coordinate wrapping
uint32 nSides = Sides+1;
uint32 nRings = Rings+1;
// Allocate vertex buffer
VertexBuffer *pVertexBuffer = pMorphTarget->GetVertexBuffer();
pVertexBuffer->AddVertexAttribute(VertexBuffer::Position, 0, VertexBuffer::Float3);
if (TexCoords)
pVertexBuffer->AddVertexAttribute(VertexBuffer::TexCoord, 0, VertexBuffer::Float2);
if (Normals)
pVertexBuffer->AddVertexAttribute(VertexBuffer::Normal, 0, VertexBuffer::Float3);
pVertexBuffer->Allocate(nSides*nRings, bStatic ? Usage::Static : Usage::Dynamic);
// Setup vertices
if (pVertexBuffer->Lock(Lock::WriteOnly)) {
const float fRingDelta = static_cast<float>(Math::Pi2/(nRings-1));
const float fSideDelta = static_cast<float>(Math::Pi2/(nSides-1));
float fRadius = Width;
float fWidth = Radius;
// Get offset
const Vector3 &vOffset = Offset.Get();
uint32 nVertex = 0;
for (uint32 i=0; i<nRings; i++) {
float theta = i*fRingDelta;
float cosTheta = Math::Cos(theta);
float sinTheta = Math::Sin(theta);
for (uint32 j=0; j<nSides; j++) {
float phi = j*fSideDelta;
float cosPhi = Math::Cos(phi);
float sinPhi = Math::Sin(phi);
float dist = fWidth + fRadius*cosPhi;
// (x,y,z) below is the parametric equation for a torus
// when theta and phi both vary from 0 to pi
float *pfVertex = static_cast<float*>(pVertexBuffer->GetData(nVertex, VertexBuffer::Position));
// x = cos(theta)*(R + r*cos(phi))
pfVertex[Vector3::X] = vOffset.x + cosTheta*dist;
// y = -sin(theta)*(R + r*cos(phi))
pfVertex[Vector3::Y] = vOffset.y - sinTheta*dist;
// z = r*sin(phi)
pfVertex[Vector3::Z] = vOffset.z + fRadius*sinPhi;
// Texture coordinates for each vertex
if (TexCoords) {
pfVertex = static_cast<float*>(pVertexBuffer->GetData(nVertex, VertexBuffer::TexCoord));
pfVertex[Vector2::X] = static_cast<float>(j)/nSides;
pfVertex[Vector2::Y] = static_cast<float>(i)/nRings;
}
// Normal
if (Normals) {
pfVertex = static_cast<float*>(pVertexBuffer->GetData(nVertex, VertexBuffer::Normal));
pfVertex[Vector3::X] = cosTheta*cosPhi;
pfVertex[Vector3::Y] = -sinTheta*cosPhi;
pfVertex[Vector3::Z] = sinPhi;
}
nVertex++;
}
}
// Unlock the vertex buffer
pVertexBuffer->Unlock();
}
// Get LOD level
MeshLODLevel *pLODLevel = cMesh.GetLODLevel(nLODLevel);
if (pLODLevel && pLODLevel->GetIndexBuffer()) { // Setup geometry
// Allocate index buffer
IndexBuffer *pIndexBuffer = pLODLevel->GetIndexBuffer();
uint32 nIndices = nSides*2*Rings;
pIndexBuffer->SetElementTypeByMaximumIndex(pVertexBuffer->GetNumOfElements()-1);
pIndexBuffer->Allocate(nIndices, bStatic ? Usage::Static : Usage::Dynamic);
// Create and setup geometries
Array<Geometry> &lstGeometries = *pLODLevel->GetGeometries();
if (pIndexBuffer->Lock(Lock::WriteOnly)) {
uint32 nIndex = 0;
if (Order) {
for (uint32 i=0; i<Rings; i++) {
// Create and setup new geometry
Geometry &cGeometry = lstGeometries.Add();
cGeometry.SetPrimitiveType(Primitive::TriangleStrip);
cGeometry.SetStartIndex(i*nSides*2);
cGeometry.SetIndexSize(nSides*2);
uint32 ii = i+1;
for (uint32 j=0; j<nSides; j++) {
pIndexBuffer->SetData(nIndex++, i*nSides+j);
pIndexBuffer->SetData(nIndex++, ii*nSides+j);
}
}
} else {
for (uint32 i=0; i<Rings; i++) {
// Create and setup new geometry
Geometry &cGeometry = lstGeometries.Add();
cGeometry.SetPrimitiveType(Primitive::TriangleStrip);
cGeometry.SetStartIndex(i*nSides*2);
cGeometry.SetIndexSize(nSides*2);
uint32 ii = i+1;
for (uint32 j=0; j<nSides; j++) {
pIndexBuffer->SetData(nIndex++, ii*nSides+j);
pIndexBuffer->SetData(nIndex++, i*nSides+j);
}
}
}
// Unlock the index buffer
pIndexBuffer->Unlock();
}
}
}
// Return the created mesh
return &cMesh;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLMesh
| 35.391509 | 100 | 0.587365 | [
"mesh",
"geometry"
] |
d9e2fba659b8828dfcac4c31d6dc93ecc8ed7d76 | 1,209 | hpp | C++ | module-audio/board/linux/PulseAudioWrapper.hpp | GravisZro/MuditaOS | 4230da15e69350c3ef9e742ec587e5f70154fabd | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-audio/board/linux/PulseAudioWrapper.hpp | GravisZro/MuditaOS | 4230da15e69350c3ef9e742ec587e5f70154fabd | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-audio/board/linux/PulseAudioWrapper.hpp | GravisZro/MuditaOS | 4230da15e69350c3ef9e742ec587e5f70154fabd | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <pulse/pulseaudio.h>
#include <Audio/AudioFormat.hpp>
#include <Audio/AbstractStream.hpp>
#include <cstdint>
#include <functional>
#include <deque>
#include <vector>
namespace audio
{
class PulseAudioWrapper
{
public:
using WriteCallback = std::function<void(const std::size_t size)>;
PulseAudioWrapper(WriteCallback write_cb, AudioFormat audio_format);
~PulseAudioWrapper();
void insert(audio::AbstractStream::Span span);
void consume();
std::size_t bytes() const;
private:
void context_state_callback();
void *worker();
void stream_write_cb(size_t length);
void quit(int ret = 0);
pthread_t tid{};
pa_stream *stream{nullptr};
pa_mainloop *mainloop{nullptr};
pa_mainloop_api *mainloop_api{nullptr};
pa_context *context{nullptr};
WriteCallback write_cb;
AudioFormat audio_format;
std::vector<std::uint8_t> cache{};
std::uint32_t cache_pos{};
};
} // namespace audio
| 25.1875 | 76 | 0.652605 | [
"vector"
] |
d9e5ad9bead4c7ebf395f94571c914620c3cc30b | 2,180 | cpp | C++ | atcoder/corp/diverta2019_2_c.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | 1 | 2018-11-12T15:18:55.000Z | 2018-11-12T15:18:55.000Z | atcoder/corp/diverta2019_2_c.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | atcoder/corp/diverta2019_2_c.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
//typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
#define UNIQUE(c) sort(ALL(c)), c.erase(unique(ALL(c)), c.end())
const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = {0, 1, 0, -1};
int main() {
// use scanf in CodeForces!
cin.tie(0);
ios_base::sync_with_stdio(false);
int N; cin >> N;
vector<int> A(N); REP(i, N) cin >> A[i];
sort(ALL(A));
if (A[0] >= 0) {
int now = A[0];
vector<pair<int, int>> ans;
FOR(i, 1, N-1) {
ans.push_back(make_pair(now, A[i]));
now -= A[i];
}
ans.push_back(make_pair(A[N-1], now));
cout << A[N-1] - now << endl;
for (pair<int, int> p : ans) {
int x, y; tie(x, y) = p;
cout << x << ' ' << y << endl;
}
} else if (A[N-1] <= 0) {
int now = A[N-1];
vector<pair<int, int>> ans;
REP(i, N-1) {
ans.push_back(make_pair(now, A[i]));
now -= A[i];
}
cout << now << endl;
for (pair<int, int> p : ans) {
int x, y; tie(x, y) = p;
cout << x << ' ' << y << endl;
}
} else {
vector<int> pos, neg, zero;
for (int x : A) {
if (x > 0) {
pos.emplace_back(x);
} else if (x < 0) {
neg.emplace_back(x);
} else {
zero.emplace_back(x);
}
}
vector<pair<int, int>> ans;
int pos_now = pos[0], neg_now = neg[0];
if (pos.size() > 1) {
FOR(i, 1, pos.size()) {
ans.push_back(make_pair(neg_now, pos[i]));
neg_now -= pos[i];
}
}
if (neg.size() > 1) {
FOR(i, 1, neg.size()) {
ans.push_back(make_pair(pos_now, neg[i]));
pos_now -= neg[i];
}
}
REP(i, zero.size()) ans.push_back(make_pair(pos_now, 0));
ans.push_back(make_pair(pos_now, neg_now));
cout << pos_now - neg_now << endl;
for (pair<int, int> p : ans) {
int x, y; tie(x, y) = p;
cout << x << ' ' << y << endl;
}
}
return 0;
}
| 23.956044 | 64 | 0.490367 | [
"vector"
] |
d9e9ef52f49a3bacf2c90c5bf2acec5bcb2278fd | 2,971 | cpp | C++ | dev/Gems/StartingPointMovement/Code/Source/StartingPointMovementGem.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/StartingPointMovement/Code/Source/StartingPointMovementGem.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/StartingPointMovement/Code/Source/StartingPointMovementGem.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StartingPointMovement_precompiled.h"
#include <platform_impl.h>
#include <AzCore/Module/Module.h>
#include <AzFramework/Metrics/MetricsPlainTextNameRegistration.h>
#include <AzCore/Serialization/SerializeContext.h>
namespace StartingPointMovement
{
// Dummy component to get reflect function
class StartingPointMovementDummyComponent
: public AZ::Component
{
public:
AZ_COMPONENT(StartingPointMovementDummyComponent, "{6C9DA3DD-A0B3-4DCB-B77B-E93C4AF89134}");
static void Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->ClassDeprecate("Event Action Bindings", "{2BB79CFC-7EBC-4EF4-A62E-5D64CB45CDBD}");
serializeContext->Class<StartingPointMovementDummyComponent, AZ::Component>()
->Version(0)
;
}
}
void Activate() override { }
void Deactivate() override { }
};
class StartingPointMovementModule
: public AZ::Module
{
public:
AZ_RTTI(StartingPointMovementModule, "{AE406AE3-77AE-4CA6-84AD-842224EE2188}", AZ::Module);
StartingPointMovementModule()
: AZ::Module()
{
m_descriptors.insert(m_descriptors.end(), {
StartingPointMovementDummyComponent::CreateDescriptor(),
});
// This is an internal Amazon gem, so register it's components for metrics tracking, otherwise the name of the component won't get sent back.
// IF YOU ARE A THIRDPARTY WRITING A GEM, DO NOT REGISTER YOUR COMPONENTS WITH EditorMetricsComponentRegistrationBus
AZStd::vector<AZ::Uuid> typeIds;
typeIds.reserve(m_descriptors.size());
for (AZ::ComponentDescriptor* descriptor : m_descriptors)
{
typeIds.emplace_back(descriptor->GetUuid());
}
EBUS_EVENT(AzFramework::MetricsPlainTextNameRegistrationBus, RegisterForNameSending, typeIds);
}
};
}
// DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM
// The first parameter should be GemName_GemIdLower
// The second should be the fully qualified name of the class above
AZ_DECLARE_MODULE_CLASS(StartingPointMovement_73d8779dc28a4123b7c9ed76217464af, StartingPointMovement::StartingPointMovementModule)
| 38.584416 | 153 | 0.687647 | [
"vector"
] |
d9f5458ac29629ae6dc355c031d2097ad58ef45b | 10,094 | cc | C++ | src/reader/spirv/parser_impl_function_decl_test.cc | jhanssen/tint | 30c1f25a7a4e180419444c12046348edb0f8fdd0 | [
"Apache-2.0"
] | null | null | null | src/reader/spirv/parser_impl_function_decl_test.cc | jhanssen/tint | 30c1f25a7a4e180419444c12046348edb0f8fdd0 | [
"Apache-2.0"
] | null | null | null | src/reader/spirv/parser_impl_function_decl_test.cc | jhanssen/tint | 30c1f25a7a4e180419444c12046348edb0f8fdd0 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sstream>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "src/ast/module.h"
#include "src/reader/spirv/parser_impl.h"
#include "src/reader/spirv/parser_impl_test_helper.h"
#include "src/reader/spirv/spirv_tools_helpers_test.h"
namespace tint {
namespace reader {
namespace spirv {
namespace {
using ::testing::HasSubstr;
/// @returns a SPIR-V assembly segment which assigns debug names
/// to particular IDs.
std::string Names(std::vector<std::string> ids) {
std::ostringstream outs;
for (auto& id : ids) {
outs << " OpName %" << id << " \"" << id << "\"\n";
}
return outs.str();
}
std::string CommonTypes() {
return R"(
%void = OpTypeVoid
%voidfn = OpTypeFunction %void
%float = OpTypeFloat 32
%uint = OpTypeInt 32 0
%int = OpTypeInt 32 1
%float_0 = OpConstant %float 0.0
)";
}
TEST_F(SpvParserTest, EmitFunctions_NoFunctions) {
auto p = parser(test::Assemble(CommonTypes()));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, Not(HasSubstr("Function{")));
}
TEST_F(SpvParserTest, EmitFunctions_FunctionWithoutBody) {
auto p = parser(test::Assemble(Names({"main"}) + CommonTypes() + R"(
%main = OpFunction %void None %voidfn
OpFunctionEnd
)"));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, Not(HasSubstr("Function{")));
}
TEST_F(SpvParserTest, EmitFunctions_Function_EntryPoint_Vertex) {
std::string input = Names({"main"}) + R"(OpEntryPoint Vertex %main "main"
)" + CommonTypes() + R"(
%main = OpFunction %void None %voidfn
%entry = OpLabel
OpReturn
OpFunctionEnd)";
auto p = parser(test::Assemble(input));
ASSERT_TRUE(p->BuildAndParseInternalModule());
ASSERT_TRUE(p->error().empty()) << p->error();
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, HasSubstr(R"(
Function )" + program.Symbols().Get("main").to_str() +
R"( -> __void
StageDecoration{vertex}
()
{)"));
}
TEST_F(SpvParserTest, EmitFunctions_Function_EntryPoint_Fragment) {
std::string input = Names({"main"}) + R"(OpEntryPoint Fragment %main "main"
)" + CommonTypes() + R"(
%main = OpFunction %void None %voidfn
%entry = OpLabel
OpReturn
OpFunctionEnd)";
auto p = parser(test::Assemble(input));
ASSERT_TRUE(p->BuildAndParseInternalModule());
ASSERT_TRUE(p->error().empty()) << p->error();
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, HasSubstr(R"(
Function )" + program.Symbols().Get("main").to_str() +
R"( -> __void
StageDecoration{fragment}
()
{)"));
}
TEST_F(SpvParserTest, EmitFunctions_Function_EntryPoint_GLCompute) {
std::string input = Names({"main"}) + R"(OpEntryPoint GLCompute %main "main"
)" + CommonTypes() + R"(
%main = OpFunction %void None %voidfn
%entry = OpLabel
OpReturn
OpFunctionEnd)";
auto p = parser(test::Assemble(input));
ASSERT_TRUE(p->BuildAndParseInternalModule());
ASSERT_TRUE(p->error().empty()) << p->error();
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, HasSubstr(R"(
Function )" + program.Symbols().Get("main").to_str() +
R"( -> __void
StageDecoration{compute}
()
{)"));
}
TEST_F(SpvParserTest, EmitFunctions_Function_EntryPoint_MultipleEntryPoints) {
std::string input = Names({"main"}) +
R"(OpEntryPoint GLCompute %main "comp_main"
OpEntryPoint Fragment %main "frag_main"
)" + CommonTypes() + R"(
%main = OpFunction %void None %voidfn
%entry = OpLabel
OpReturn
OpFunctionEnd)";
auto p = parser(test::Assemble(input));
ASSERT_TRUE(p->BuildAndParseInternalModule());
ASSERT_TRUE(p->error().empty()) << p->error();
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, HasSubstr(R"(
Function )" + program.Symbols().Get("frag_main").to_str() +
R"( -> __void
StageDecoration{fragment}
()
{)"));
EXPECT_THAT(program_ast, HasSubstr(R"(
Function )" + program.Symbols().Get("comp_main").to_str() +
R"( -> __void
StageDecoration{compute}
()
{)"));
}
TEST_F(SpvParserTest, EmitFunctions_VoidFunctionWithoutParams) {
auto p = parser(test::Assemble(Names({"main"}) + CommonTypes() + R"(
%main = OpFunction %void None %voidfn
%entry = OpLabel
OpReturn
OpFunctionEnd
)"));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = program.AST().to_str();
EXPECT_THAT(program_ast, HasSubstr(R"(
Function )" + program.Symbols().Get("main").to_str() +
R"( -> __void
()
{)"));
}
TEST_F(SpvParserTest, EmitFunctions_CalleePrecedesCaller) {
auto p = parser(test::Assemble(
Names({"root", "branch", "leaf", "leaf_result", "branch_result"}) +
CommonTypes() + R"(
%uintfn = OpTypeFunction %uint
%uint_0 = OpConstant %uint 0
%root = OpFunction %void None %voidfn
%root_entry = OpLabel
%branch_result = OpFunctionCall %uint %branch
OpReturn
OpFunctionEnd
%branch = OpFunction %uint None %uintfn
%branch_entry = OpLabel
%leaf_result = OpFunctionCall %uint %leaf
OpReturnValue %leaf_result
OpFunctionEnd
%leaf = OpFunction %uint None %uintfn
%leaf_entry = OpLabel
OpReturnValue %uint_0
OpFunctionEnd
)"));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = Demangler().Demangle(program);
EXPECT_THAT(program_ast, HasSubstr(R"(
Function leaf -> __u32
()
{
Return{
{
ScalarConstructor[not set]{0}
}
}
}
Function branch -> __u32
()
{
VariableDeclStatement{
VariableConst{
leaf_result
none
__u32
{
Call[not set]{
Identifier[not set]{leaf}
(
)
}
}
}
}
Return{
{
Identifier[not set]{leaf_result}
}
}
}
Function root -> __void
()
{
VariableDeclStatement{
VariableConst{
branch_result
none
__u32
{
Call[not set]{
Identifier[not set]{branch}
(
)
}
}
}
}
Return{}
}
})")) << program_ast;
}
TEST_F(SpvParserTest, EmitFunctions_NonVoidResultType) {
auto p = parser(test::Assemble(Names({"ret_float"}) + CommonTypes() + R"(
%fn_ret_float = OpTypeFunction %float
%ret_float = OpFunction %float None %fn_ret_float
%ret_float_entry = OpLabel
OpReturnValue %float_0
OpFunctionEnd
)"));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = Demangler().Demangle(program);
EXPECT_THAT(program_ast, HasSubstr(R"(
Function ret_float -> __f32
()
{
Return{
{
ScalarConstructor[not set]{0.000000}
}
}
})"))
<< program_ast;
}
TEST_F(SpvParserTest, EmitFunctions_MixedParamTypes) {
auto p = parser(test::Assemble(Names({"mixed_params", "a", "b", "c"}) +
CommonTypes() + R"(
%fn_mixed_params = OpTypeFunction %float %uint %float %int
%mixed_params = OpFunction %void None %fn_mixed_params
%a = OpFunctionParameter %uint
%b = OpFunctionParameter %float
%c = OpFunctionParameter %int
%mixed_entry = OpLabel
OpReturn
OpFunctionEnd
)"));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = Demangler().Demangle(program);
EXPECT_THAT(program_ast, HasSubstr(R"(
Function mixed_params -> __void
(
VariableConst{
a
none
__u32
}
VariableConst{
b
none
__f32
}
VariableConst{
c
none
__i32
}
)
{
Return{}
})"));
}
TEST_F(SpvParserTest, EmitFunctions_GenerateParamNames) {
auto p = parser(test::Assemble(Names({"mixed_params"}) + CommonTypes() + R"(
%fn_mixed_params = OpTypeFunction %float %uint %float %int
%mixed_params = OpFunction %void None %fn_mixed_params
%14 = OpFunctionParameter %uint
%15 = OpFunctionParameter %float
%16 = OpFunctionParameter %int
%mixed_entry = OpLabel
OpReturn
OpFunctionEnd
)"));
EXPECT_TRUE(p->BuildAndParseInternalModule());
EXPECT_TRUE(p->error().empty());
Program program = p->program();
const auto program_ast = Demangler().Demangle(program);
EXPECT_THAT(program_ast, HasSubstr(R"(
Function mixed_params -> __void
(
VariableConst{
x_14
none
__u32
}
VariableConst{
x_15
none
__f32
}
VariableConst{
x_16
none
__i32
}
)
{
Return{}
})"))
<< program_ast;
}
} // namespace
} // namespace spirv
} // namespace reader
} // namespace tint
| 26.633245 | 78 | 0.63404 | [
"vector"
] |
d9fe6a500e791decfb327a81fb98d88e56068819 | 6,794 | cpp | C++ | src/DANE/dane_omp.cpp | microsoft/DistrOpt | 73f2fc0c5d12257d4fb4e1aacc77ab23a0d2de98 | [
"MIT"
] | 1 | 2020-10-26T10:23:27.000Z | 2020-10-26T10:23:27.000Z | src/DANE/dane_omp.cpp | microsoft/DistrOpt | 73f2fc0c5d12257d4fb4e1aacc77ab23a0d2de98 | [
"MIT"
] | null | null | null | src/DANE/dane_omp.cpp | microsoft/DistrOpt | 73f2fc0c5d12257d4fb4e1aacc77ab23a0d2de98 | [
"MIT"
] | 3 | 2020-09-04T06:36:36.000Z | 2021-11-10T11:28:05.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <algorithm>
#include "timer.h"
#include "utils.h"
#include "randalgms.h"
#include "dane_omp.h"
#include "lbfgs_omp.h"
namespace distropt
{
// formatted output: "iter pcg_itrs primal_obj newton_dec time"
void formatted_output(std::ostream &ofs, const int iters, const int epochs, const double primal_obj, const double t_dane)
{
ofs << std::setw(3) << iters
<< std::setw(6) << epochs
<< std::fixed << std::setprecision(12)
<< std::setw(16) << primal_obj
<< std::fixed << std::setprecision(3)
<< std::setw(9) << t_dane
<< std::endl;
}
int dane_omp(const SparseMatrixCSR &X, const Vector &y, const ISmoothLoss &f, const double lambda,
const SquaredL2Norm &g, Vector &wio, const int m, const dane_params ¶ms)
{
// N is totoal number of examples on all machines, D is the feature dimension
size_t N = X.nrows();
size_t D = X.ncols();
if (y.length() != N || wio.length() != D) {
throw std::runtime_error("DANE: Input/output matrix and vector dimensions do not match.");
}
// split X into m submatrices consisting subsets of randomly permuted rows
std::vector<SubSparseMatrixCSR*> Xi(m);
std::vector<SubVector*> yi(m);
Vector w(D), grad(D), Xw(N), drv(N);
std::vector<Vector*> wi(m), gi(m); // m Vectors of dimension D
std::vector<SubVector*> Xiw(m), drvi(m);
// use the same random seed by specifying seed=1, otherwise random_device() is used
std::vector<size_t> rowperm = random_permutation(N, 1);
//std::vector<size_t> rowperm = random_permutation(N);
Vector y_perm(y, rowperm); // permute the y vector to match rows of Xi, used by yi[i]
size_t row_stride = N / m;
size_t row_remain = N % m;
size_t row_start = 0;
for (int i = 0; i < m; i++) {
size_t n_rows = i < row_remain ? row_stride + 1 : row_stride;
std::vector<size_t> subrows(rowperm.begin() + row_start, rowperm.begin() + (row_start + n_rows));
Xi[i] = new SubSparseMatrixCSR(X, subrows);
yi[i] = new SubVector(y_perm, row_start, n_rows);
wi[i] = new Vector(D);
gi[i] = new Vector(D);
Xiw[i] = new SubVector(Xw, row_start, n_rows);
drvi[i] = new SubVector(drv, row_start, n_rows);
row_start += n_rows;
}
//---------------------------------------------------------------------
// declare variables for tracking progress and time spent in different activities
HighResTimer timer;
std::vector<int> n_epochs;
std::vector<double> primal_obj, t_dane;
// compute initial primal and dual objective values
int sdca_passes = 0;
if (params.avg_init) {
w.scale(0);
for (int i = 1; i < m; i++) {
wi[i]->copy(wio);
sdca_passes = randalgms::sdca(*Xi[i], *yi[i], f, lambda, g, params.ini_itrs, params.eps_init, *wi[i], *Xiw[i], 'p', 'd', false);
w.axpy(1.0 / m, *wi[i]);
}
}
else {
w.copy(wio);
}
// be careful that X and y is not shuffled, but the blocks are defined over shuffled versions!
X.aAxby(1.0, w, 0, Xw);
double sum_loss = f.sum_loss(Xw, y);
primal_obj.push_back(sum_loss / N + lambda*g(w));
t_dane.push_back(timer.seconds_from_start());
n_epochs.push_back(sdca_passes);
if (params.display) {
std::cout << std::endl << "iter passes primal_obj time" << std::endl;
formatted_output(std::cout, 0, n_epochs[0], primal_obj[0], t_dane[0]);
}
// construct OffsetQuadratic as unit regularizer for PCG
OffsetQuadratic q_regu(D);
// DANE main loop
double mu = params.mu_dane;
int n_itrs = 0;
for (n_itrs = 1; n_itrs <= params.max_itrs; n_itrs++)
{
// compute global gradient
X.aAxby(1.0, w, 0, Xw);
f.derivative(Xw, y, drv);
X.aATxby(1.0, drv, 0, grad);
grad.scale(1.0 / N);
// need to include L2 regularization, but the same appears in both grad and gi[i]
grad.axpy(lambda, w);
for (int i = 0; i < m; i++) {
size_t Ni = yi[i]->length();
double ci = double(m*Ni) / N;
Xi[i]->aAxby(1.0, w, 0, *Xiw[i]);
f.derivative(*Xiw[i], *yi[i], *drvi[i]);
Xi[i]->aATxby(1.0, *drvi[i], 0, *gi[i]);
//gi[i]->scale(1.0 / Ni);
gi[i]->scale(double(m) / N);
// need to include L2 regularization, but the same appears in both grad and gi[i]
gi[i]->axpy(ci*lambda, w);
//gi[i]->axpy(lambda, w);
// solve the DANE local problem
gi[i]->axpy(-1.0, grad);
if (params.local_solver == 's') {
gi[i]->axpy(mu, w);
gi[i]->scale(1.0 / (ci*lambda + mu));
//gi[i]->scale(1.0 / (lambda + mu));
q_regu.update_offset(*gi[i]);
double local_lambda = lambda + mu / ci;
//double local_lambda = (lambda + mu) / ci;
sdca_passes = randalgms::sdca(*Xi[i], *yi[i], f, local_lambda, q_regu, params.sdca_itrs, params.sdca_epsilon,
*wi[i], *Xiw[i], 'p', params.sdca_update, params.sdca_display);
}
else
{
// prepare for calling LBFGS
RegularizedLoss localoss(*Xi[i], *yi[i], f.symbol(), lambda, g.symbol());
auto localfval = [&localoss, &w, &gi, i, ci, mu](const Vector &x) {
Vector dw(x);
dw.axpy(-1.0, w);
return ci*localoss.regu_loss(x) - gi[i]->dot(x) + (mu / 2)*dw.dot(dw);
};
auto localgrad = [&localoss, &w, &gi, i, ci, mu](const Vector &x, Vector &g) {
Vector dw(x);
dw.axpy(-1.0, w);
localoss.regu_grad(x, g);
g.scale(ci);
g.axpy(-1.0, *gi[i]);
g.axpy(mu, dw);
return ci*localoss.regu_loss(x) - gi[i]->dot(x) + (mu / 2)*dw.dot(dw);
};
lbfgs_params local_params;
local_params.eps_grad = 1e-8;
local_params.display = false;
sdca_passes = lbfgs_omp(localfval, localgrad, w, *wi[i], local_params);
}
}
w.scale(0);
for (int i = 0; i < m; i++) {
w.axpy(1.0 / m, *wi[i]);
}
// compute new primal and dual objective values
X.aAxby(1.0, w, 0, Xw);
double sum_loss = f.sum_loss(Xw, y);
// record time and epochs
primal_obj.push_back(sum_loss / N + lambda*g(w));
n_epochs.push_back(sdca_passes);
t_dane.push_back(timer.seconds_from_start());
if (params.display)
{
formatted_output(std::cout, n_itrs, n_epochs[n_itrs], primal_obj[n_itrs], t_dane[n_itrs]);
}
}
// delete memory allocated explicitly
for (size_t i = 0; i < m; i++) {
delete Xi[i];
delete yi[i];
delete wi[i];
delete gi[i];
delete Xiw[i];
delete drvi[i];
}
// --------------------------------------------------------------------------
// return final iterate and number of iterations
wio.copy(w);
return n_itrs;
}
} | 33.303922 | 133 | 0.588608 | [
"vector"
] |
8a0e1403f5a1476fd3f285c966e471338c30e194 | 1,111 | hpp | C++ | platforms/linux/src/Application/Packets/Commands/GetControllersIds/GetControllersIdsResponse.hpp | iotile/baBLE-linux | faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db | [
"MIT"
] | 13 | 2018-07-04T16:35:37.000Z | 2021-03-03T10:41:07.000Z | platforms/linux/src/Application/Packets/Commands/GetControllersIds/GetControllersIdsResponse.hpp | iotile/baBLE | faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db | [
"MIT"
] | 11 | 2018-06-01T20:32:32.000Z | 2019-01-21T17:03:47.000Z | platforms/linux/src/Application/Packets/Commands/GetControllersIds/GetControllersIdsResponse.hpp | iotile/baBLE-linux | faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db | [
"MIT"
] | null | null | null | #ifndef BABLE_GETCONTROLLERSIDSRESPONSE_HPP
#define BABLE_GETCONTROLLERSIDSRESPONSE_HPP
#include "Application/Packets/Base/ControllerToHostPacket.hpp"
namespace Packet {
namespace Commands {
class GetControllersIdsResponse : public ControllerToHostPacket {
public:
static const Packet::Type initial_type() {
return Packet::Type::MGMT;
};
static const uint16_t initial_packet_code() {
return Format::MGMT::CommandCode::GetControllersList;
};
static const uint16_t final_packet_code() {
return static_cast<uint16_t>(BaBLE::Payload::GetControllersIds);
};
GetControllersIdsResponse();
void unserialize(MGMTFormatExtractor& extractor) override;
std::vector<uint8_t> serialize(FlatbuffersFormatBuilder& builder) const override;
const std::string stringify() const override;
inline const std::vector<uint16_t>& get_controllers_ids() const {
return m_controllers_ids;
}
private:
std::vector<uint16_t> m_controllers_ids;
};
}
}
#endif //BABLE_GETCONTROLLERSIDSRESPONSE_HPP
| 24.152174 | 87 | 0.715572 | [
"vector"
] |
8a0f0e218689605ece56a04f1325fad865c1e63a | 10,947 | cpp | C++ | source/smarties/ReplayMemory/Episode.cpp | waitong94/smarties | e48fe6a8ba4695e20146cf5ca7c6720989217ed3 | [
"MIT"
] | 91 | 2018-07-16T07:54:06.000Z | 2022-03-15T09:50:22.000Z | source/smarties/ReplayMemory/Episode.cpp | waitong94/smarties | e48fe6a8ba4695e20146cf5ca7c6720989217ed3 | [
"MIT"
] | 7 | 2019-04-03T03:14:59.000Z | 2021-11-17T09:02:14.000Z | source/smarties/ReplayMemory/Episode.cpp | waitong94/smarties | e48fe6a8ba4695e20146cf5ca7c6720989217ed3 | [
"MIT"
] | 36 | 2018-07-16T08:08:35.000Z | 2022-03-29T02:40:20.000Z | //
// smarties
// Copyright (c) 2018 CSE-Lab, ETH Zurich, Switzerland. All rights reserved.
// Distributed under the terms of the MIT license.
//
// Created by Guido Novati (novatig@ethz.ch).
//
#include "Episode.h"
#include "../Core/Agent.h"
#include <cstring>
#include <cmath>
#include <algorithm>
namespace smarties
{
Episode::Episode(const std::vector<Fval>& data, const MDPdescriptor& _MDP)
: MDP(_MDP)
{
unpackEpisode(data);
}
std::vector<Fval> Episode::packEpisode()
{
const Uint dS = MDP.dimStateObserved, dI = MDP.dimState-MDP.dimStateObserved;
const Uint dA = MDP.dimAction, dP = MDP.policyVecDim, N = states.size();
assert(states.size() == actions.size() && states.size() == policies.size());
const Uint totalSize = Episode::computeTotalEpisodeSize(MDP, N);
assert( N == Episode::computeTotalEpisodeNstep(MDP, totalSize) );
std::vector<Fval> ret(totalSize, 0);
Fval* buf = ret.data();
for (Uint i = 0; i<N; ++i)
{
assert(states[i].size() == dS and latent_states[i].size() == dI);
assert(actions[i].size() == dA and policies[i].size() == dP);
std::copy(states[i].begin(), states[i].end(), buf);
buf[dS] = rewards[i]; buf += dS + 1;
std::copy(actions[i].begin(), actions[i].end(), buf); buf += dA;
std::copy(policies[i].begin(), policies[i].end(), buf); buf += dP;
std::copy(latent_states[i].begin(), latent_states[i].end(), buf); buf += dI;
}
/////////////////////////////////////////////////////////////////////////////
// following vectors may be of size less than N because
// some algorithms do not allocate them. I.e. Q-learning-based
// algorithms do not need to advance retrace-like value estimates
assert(returnEstimator.size() <= N); returnEstimator.resize(N);
std::copy(returnEstimator.begin(), returnEstimator.end(), buf); buf += N;
assert(actionAdvantage.size() <= N); actionAdvantage.resize(N);
std::copy(actionAdvantage.begin(), actionAdvantage.end(), buf); buf += N;
assert(stateValue.size() <= N); stateValue.resize(N);
std::copy(stateValue.begin(), stateValue.end(), buf); buf += N;
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// post processing quantities might not be already allocated
assert(deltaValue.size() <= N); deltaValue.resize(N);
std::copy(deltaValue.begin(), deltaValue.end(), buf); buf += N;
assert(offPolicImpW.size() <= N); offPolicImpW.resize(N);
std::copy(offPolicImpW.begin(), offPolicImpW.end(), buf); buf += N;
assert(KullbLeibDiv.size() <= N); KullbLeibDiv.resize(N);
std::copy(KullbLeibDiv.begin(), KullbLeibDiv.end(), buf); buf += N;
/////////////////////////////////////////////////////////////////////////////
assert((Uint) (buf-ret.data()) == (dS + dA + dP + dI + 7) * N);
char * charPos = (char*) buf;
memcpy(charPos, &bReachedTermState, sizeof(bool)); charPos += sizeof(bool);
memcpy(charPos, & ID, sizeof(Sint)); charPos += sizeof(Sint);
memcpy(charPos, &just_sampled, sizeof(Sint)); charPos += sizeof(Sint);
memcpy(charPos, & agentID, sizeof(Sint)); charPos += sizeof(Sint);
// assert(buf - ret.data() == (ptrdiff_t) totalSize);
return ret;
}
void Episode::save(FILE * f)
{
const Uint seq_len = states.size();
fwrite(& seq_len, sizeof(Uint), 1, f);
Fvec buffer = packEpisode();
fwrite(buffer.data(), sizeof(Fval), buffer.size(), f);
}
void Episode::unpackEpisode(const std::vector<Fval>& data)
{
const Uint dS = MDP.dimStateObserved, dI = MDP.dimState-MDP.dimStateObserved;
const Uint dA = MDP.dimAction, dP = MDP.policyVecDim;
const Uint N = Episode::computeTotalEpisodeNstep(MDP, data.size());
assert( data.size() == Episode::computeTotalEpisodeSize(MDP, N) );
const Fval* buf = data.data();
assert(states.size() == 0);
for (Uint i = 0; i<N; ++i) {
states.push_back( Fvec(buf, buf + dS));
rewards.push_back(buf[dS]); buf += dS + 1;
actions.push_back( Rvec(buf, buf + dA)); buf += dA;
policies.push_back(Rvec(buf, buf + dP)); buf += dP;
latent_states.push_back(Fvec(buf, buf + dI)); buf += dI;
}
/////////////////////////////////////////////////////////////////////////////
returnEstimator = std::vector<nnReal>(buf, buf + N); buf += N;
actionAdvantage = std::vector<nnReal>(buf, buf + N); buf += N;
stateValue = std::vector<nnReal>(buf, buf + N); buf += N;
/////////////////////////////////////////////////////////////////////////////
deltaValue = std::vector<Fval>(buf, buf + N); buf += N;
offPolicImpW = std::vector<Fval>(buf, buf + N); buf += N;
KullbLeibDiv = std::vector<Fval>(buf, buf + N); buf += N;
/////////////////////////////////////////////////////////////////////////////
assert((Uint) (buf - data.data()) == (dS + dA + dP + dI + 7) * N);
priorityImpW = std::vector<float>(N, 1);
totR = Utilities::sum(rewards);
/////////////////////////////////////////////////////////////////////////////
const char * charPos = (const char *) buf;
memcpy(&bReachedTermState, charPos, sizeof(bool)); charPos += sizeof(bool);
memcpy(& ID, charPos, sizeof(Sint)); charPos += sizeof(Sint);
memcpy(&just_sampled, charPos, sizeof(Sint)); charPos += sizeof(Sint);
memcpy(& agentID, charPos, sizeof(Sint)); charPos += sizeof(Sint);
}
int Episode::restart(FILE * f)
{
Uint N = 0;
if(fread(& N, sizeof(Uint), 1, f) != 1) return 1;
const Uint totalSize = Episode::computeTotalEpisodeSize(MDP, N);
std::vector<Fval> buffer(totalSize);
if(fread(buffer.data(), sizeof(Fval), totalSize, f) != totalSize)
die("mismatch");
unpackEpisode(buffer);
return 0;
}
template<typename T>
inline bool isDifferent(const std::atomic<T>& a, const std::atomic<T>& b) {
static constexpr T EPS = std::numeric_limits<float>::epsilon(), tol = 100*EPS;
const auto norm = std::max({std::fabs(a.load()), std::fabs(b.load()), EPS});
return std::fabs(a-b)/norm > tol;
}
template<typename T>
inline bool isDifferent(const T& a, const T& b) {
static constexpr T EPS = std::numeric_limits<float>::epsilon(), tol = 100*EPS;
const auto norm = std::max({std::fabs(a), std::fabs(b), EPS});
return std::fabs(a-b)/norm > tol;
}
template<typename T>
inline bool isDifferent(const std::vector<T>& a, const std::vector<T>& b) {
if(a.size() not_eq b.size()) return true;
for(size_t i=0; i<b.size(); ++i) if( isDifferent(a[i], b[i]) ) return true;
return false;
}
bool Episode::isEqual(const Episode & S) const
{
if(isDifferent(S.states , states )) assert(false && "states");
if(isDifferent(S.actions , actions )) assert(false && "actions");
if(isDifferent(S.policies , policies )) assert(false && "policies");
if(isDifferent(S.rewards , rewards )) assert(false && "rewards");
if(isDifferent(S.returnEstimator, returnEstimator)) assert(false && "ret");
if(isDifferent(S.actionAdvantage, actionAdvantage)) assert(false && "adv");
if(isDifferent(S.stateValue , stateValue )) assert(false && "val");
if(isDifferent(S.deltaValue, deltaValue)) assert(false && "deltaValue");
if(isDifferent(S.offPolicImpW, offPolicImpW)) assert(false && "offPolicImpW");
if(isDifferent(S.KullbLeibDiv, KullbLeibDiv)) assert(false && "KullbLeibDiv");
if(S.bReachedTermState not_eq bReachedTermState) assert(false && "ended");
if(S.ID not_eq ID ) assert(false && "ID");
if(S.just_sampled not_eq just_sampled) assert(false && "just_sampled");
if(S.agentID not_eq agentID ) assert(false && "agentID");
return true;
}
std::vector<float> Episode::logToFile(const Uint iterStep) const
{
const Uint dS = MDP.dimStateObserved, dI = MDP.dimState - dS;
const Uint dA = MDP.dimAction, dP = MDP.policyVecDim, N = states.size();
std::vector<float> buffer(N * (4 + dS + dI + dA + dP));
float * pos = buffer.data();
for (Uint t=0; t<N; ++t)
{
assert(states[t].size() == dS and dI == latent_states[t].size());
assert(actions[t].size() == dA and dP == policies[t].size());
*(pos++) = iterStep + 0.1;
const auto steptype = t==0 ? INIT : ( isTerminal(t) ? TERM : (
isTruncated(t) ? LAST : CONT ) );
*(pos++) = status2int(steptype) + 0.1;
*(pos++) = t + 0.1;
const auto S = StateInfo::observedAndLatent2state(states[t], latent_states[t], MDP);
std::copy(S.begin(), S.end(), pos); pos += dS + dI;
const auto A = ActionInfo::learnerAction2envAction<float>(actions[t], MDP);
std::copy(A.begin(), A.end(), pos); pos += dA;
*(pos++) = rewards[t];
const auto P = ActionInfo::learnerPolicy2envPolicy<float>(policies[t], MDP);
std::copy(P.begin(), P.end(), pos); pos += dP;
assert(A.size() == dA and P.size() == dP and S.size() == dS + dI);
}
return buffer;
}
void Episode::updateCumulative(const Fval C, const Fval invC)
{
const Uint N = ndata();
const Fval invN = 1 / (Fval) N;
Uint nFarPol = 0;
Fval _sumE2=0, _maxAE = -1e9, _maxQ = -1e9, _sumQ2=0, _minQ = 1e9, _sumQ1=0;
for (Uint t = 0; t < N; ++t) {
// float precision may cause DKL to be slightly negative:
assert(KullbLeibDiv[t] >= - FVAL_EPS && offPolicImpW[t] >= 0);
// sequence is off policy if offPol W is out of 1/C : C
if (offPolicImpW[t] > C or offPolicImpW[t] < invC) ++nFarPol;
_sumE2 += deltaValue[t] * deltaValue[t];
_maxAE = std::max(_maxAE, std::fabs(deltaValue[t]));
const Fval Q = actionAdvantage[t] + stateValue[t];
_maxQ = std::max(_maxQ, Q);
_minQ = std::min(_minQ, Q);
_sumQ2 += Q*Q;
_sumQ1 += Q;
}
fracFarPolSteps = invN * nFarPol;
avgSquaredErr = invN * _sumE2;
maxAbsError = _maxAE;
sumSquaredQ = _sumQ2;
sumQ = _sumQ1;
maxQ = _maxQ;
minQ = _minQ;
assert(std::fabs(rewards[0])<1e-16);
totR = Utilities::sum(rewards);
avgKLDivergence = invN * Utilities::sum(KullbLeibDiv);
}
void Episode::finalize(const Uint index)
{
ID = index;
const Uint N = nsteps();
stateValue.resize(N, 0);
actionAdvantage.resize(N, 0);
// whatever the meaning of deltaValue, initialize with all zeros
// this must be taken into account when sorting/filtering
deltaValue.resize(N, 0);
KullbLeibDiv.resize(N, 0);
// off pol and priority importance weights are initialized to 1
offPolicImpW.resize(N, 1);
offPolicImpW.back() = 0;
priorityImpW.resize(N, 1);
returnEstimator.resize(N, 0);
#ifndef NDEBUG
Fval dbg_sumR = std::accumulate(rewards.begin(), rewards.end(), (Fval)0);
//Fval dbg_norm = std::max(std::fabs(totR), std::fabs(dbg_sumR));
Fval dbg_norm = std::max((Fval)1, std::fabs(totR));
assert(std::fabs(totR-dbg_sumR)/dbg_norm < 100*FVAL_EPS);
#endif
}
void Episode::initPreTrainErrorPlaceholder(const Fval maxError)
{
deltaValue = Fvec(nsteps(), maxError);
avgSquaredErr = maxError * maxError;
maxAbsError = maxError;
}
}
| 39.663043 | 88 | 0.604366 | [
"vector"
] |
8a18070f1524ae7bc7c3b39decb002396ad2d2e7 | 2,325 | hh | C++ | elements/analysis/timestampaccum.hh | MassimoGirondi/fastclick | 71b9a3392c2e847a22de3c354be1d9f61216cb5b | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | elements/analysis/timestampaccum.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | elements/analysis/timestampaccum.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | // -*- c-basic-offset: 4 -*-
#ifndef CLICK_TIMESTAMPACCUM_HH
#define CLICK_TIMESTAMPACCUM_HH
#include <click/batchelement.hh>
#include <click/straccum.hh>
#include <click/args.hh>
CLICK_DECLS
/*
=c
TimestampAccum()
=s timestamps
collects differences in timestamps
=d
For each passing packet, measures the elapsed time since the packet's
timestamp. Keeps track of the total elapsed time accumulated over all packets.
=h count read-only
Returns the number of packets that have passed.
=h time read-only
Returns the accumulated timestamp difference for all passing packets in seconds.
=h min read-only
Returns the minimal timestamp difference across all passing packets in seconds.
=h max read-only
Returns the maximal timestamp difference across all passing packets in seconds.
=h average_time read-only
Returns the average timestamp difference over all passing packets.
=h reset_counts write-only
Resets C<count> and C<time> counters to zero when written.
=a SetCycleCount, RoundTripCycleCount, SetPerfCount, PerfCountAccum */
template <template <typename> class T>
class TimestampAccumBase : public BatchElement { public:
TimestampAccumBase() CLICK_COLD;
~TimestampAccumBase() CLICK_COLD;
const char *class_name() const { return "TimestampAccum"; }
const char *port_count() const { return "1-/="; }
int configure(Vector<String> &conf, ErrorHandler *errh);
int initialize(ErrorHandler *) CLICK_COLD;
void add_handlers() CLICK_COLD;
void push(int, Packet *);
#if HAVE_BATCH
void push_batch(int, PacketBatch *);
#endif
protected:
struct State {
State() : nsec_accum(0), count(0), nsec_min(UINT64_MAX), nsec_max(0) {
};
uint64_t nsec_accum;
uint64_t count;
uint64_t nsec_min;
uint64_t nsec_max;
};
T<State> _state;
bool _steady;
static String read_handler(Element *, void *) CLICK_COLD;
static int reset_handler(const String &, Element *, void *, ErrorHandler *);
};
typedef TimestampAccumBase<not_per_thread> TimestampAccum;
class TimestampAccumMP : public TimestampAccumBase<per_thread> { public:
const char *class_name() const { return "TimestampAccumMP"; }
void add_handlers() CLICK_COLD;
static String read_handler(Element *, void *) CLICK_COLD;
};
CLICK_ENDDECLS
#endif
| 24.734043 | 80 | 0.734624 | [
"vector"
] |
8a1abbd5f01dcc14db47154e302eb6206259e952 | 5,022 | cpp | C++ | src/sigma/test/unit_tests.cpp | Beekers-McCluer/NixCore | e62cdcd5ac8a089948e9a22e6a3a60d139cb1e4e | [
"MIT"
] | 43 | 2018-06-27T22:35:17.000Z | 2021-01-21T01:18:15.000Z | src/sigma/test/unit_tests.cpp | Beekers-McCluer/NixCore | e62cdcd5ac8a089948e9a22e6a3a60d139cb1e4e | [
"MIT"
] | 32 | 2018-06-27T12:43:36.000Z | 2020-12-04T22:23:36.000Z | src/sigma/test/unit_tests.cpp | Beekers-McCluer/NixCore | e62cdcd5ac8a089948e9a22e6a3a60d139cb1e4e | [
"MIT"
] | 27 | 2018-06-27T16:07:19.000Z | 2021-02-21T21:10:38.000Z | #include "../r1_proof.h"
#include "../r1_proof_generator.h"
#include "../sigma_primitives.h"
#include "../../test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
using namespace secp_primitives;
using namespace sigma;
namespace {
struct sigma_unit_tests_fixture {
// struct sigma_unit_tests_fixture : public TestingSetup {
// sigma_unit_tests_fixture() = default;
int N;
int n;
int m;
int index;
GroupElement g;
std::vector<GroupElement> h_gens;
Scalar rB;
std::vector <Scalar> sigma;
std::unique_ptr<R1ProofGenerator<Scalar, GroupElement>> r1prover;
R1Proof<Scalar, GroupElement> r1proof;
Scalar x;
std::vector <std::vector<Scalar>> P_i_k;
std::vector<Scalar> f_;
std::vector<Scalar> a;
std::vector <Scalar> Pk;
secp_primitives::Scalar r;
std::vector<secp_primitives::GroupElement> commits;
sigma_unit_tests_fixture() {
// sigma_unit_tests_fixture() : TestingSetup(CBaseChainParams::REGTEST) {
N = 16;
n = 4;
index = 13;
m = (int)(log(N) / log(n));
g.randomize();
for(int i = 0; i < n * m; ++i ){
h_gens.push_back(secp_primitives::GroupElement());
h_gens[i].randomize();
}
rB.randomize();
SigmaPrimitives<Scalar,GroupElement>::convert_to_sigma(index, n, m, sigma);
r1prover.reset(new R1ProofGenerator<Scalar, GroupElement>(g, h_gens, sigma, rB, n, m));
Pk.resize(m);
for (int k = 0; k < m; ++k) {
Pk[k].randomize();
}
r.randomize();
for(int i = 0; i < N; ++i){
if(i == (index)){
secp_primitives::GroupElement c;
secp_primitives::Scalar zero(uint64_t(0));
c = sigma::SigmaPrimitives<Scalar,GroupElement>::commit(g, zero, h_gens[0], r);
commits.push_back(c);
}
else{
commits.push_back(secp_primitives::GroupElement());
commits[i].randomize();
}
}
(*r1prover).proof(a, r1proof);
x = (*r1prover).x_;
P_i_k.resize(N);
for (int i = 0; i < N; ++i) {
std::vector <Scalar>& coefficients = P_i_k[i];
std::vector<uint64_t> I = SigmaPrimitives<Scalar,GroupElement>::convert_to_nal(i, n, m);
coefficients.push_back(sigma[I[0]]);
coefficients.push_back(a[I[0]]);
for (int j = 1; j < m; ++j) {
SigmaPrimitives<Scalar,GroupElement>::new_factor(sigma[j * n + I[j]], a[j * n + I[j]], coefficients);
}
std::reverse(coefficients.begin(), coefficients.end());
}
f_ = r1proof.f_;
std::vector<Scalar> f;
for(int j = 0; j < m; ++j){
f.push_back(sigma[j * n] * x + a[j * n]);
int k = n - 1;
for(int i = 0; i < k; ++i){
f.push_back(r1proof.f_[j * k + i]);
}
}
f_= f;
}
~sigma_unit_tests_fixture(){}
};
BOOST_FIXTURE_TEST_SUITE(sigma_unit_tests,sigma_unit_tests_fixture)
BOOST_AUTO_TEST_CASE(unit_f_and_p_x)
{
for(int i = 0; i < N; ++i){
std::vector<uint64_t> I = SigmaPrimitives<Scalar,GroupElement>::convert_to_nal(i, n, m);
Scalar f_i(uint64_t(1));
Scalar p_i_x(uint64_t(0));
for(int j = 0; j < m; ++j){
f_i *= f_[j*n + I[j]];
p_i_x += (P_i_k[i][j]*x.exponent(j));
}
if(i==index)
p_i_x += (P_i_k[i][m]*x.exponent(m));
BOOST_CHECK(f_i==p_i_x);
}
}
BOOST_AUTO_TEST_CASE(unit_commits)
{
Scalar z;
z = r * x.exponent(uint64_t(m));
Scalar sum;
Scalar x_k(uint64_t(1));
for (int k = 0; k < m; ++k) {
sum += (Pk[k] * x_k);
x_k *= x;
}
z -= sum;
GroupElement coommit = SigmaPrimitives<Scalar,GroupElement>::commit(g, Scalar(uint64_t(0)), h_gens[0], z);
GroupElement commits_;
for(int k = 0; k< m; ++k){
commits_ += (SigmaPrimitives<Scalar,GroupElement>::commit(
g, Scalar(uint64_t(0)), h_gens[0], Pk[k])) * (x.exponent(k)).negate();
}
commits_ += (commits[index] * x.exponent(m));
BOOST_CHECK(coommit == commits_);
}
BOOST_AUTO_TEST_CASE(unit_G_k_prime)
{
std::vector<Scalar> f_i_;
for(int i = 0; i < N; ++i){
std::vector<uint64_t> I = SigmaPrimitives<Scalar,GroupElement>::convert_to_nal(i, n, m);
Scalar f_i(uint64_t(1));
for(int j = 0; j < m; ++j){
f_i *= f_[j*n + I[j]];
}
f_i_.push_back(f_i);
}
secp_primitives::MultiExponent mult(commits, f_i_);
GroupElement C = mult.get_multiple();
GroupElement G;
for(int k = 0; k < m; ++k){
GroupElement Gk_prime;
for(int i = 0; i < N; ++i)
Gk_prime += commits[i] * P_i_k[i][k];
G += (Gk_prime)* ((x.exponent(k)).negate());
}
BOOST_CHECK((C + G) == (commits[index] * (x.exponent(m))));
}
BOOST_AUTO_TEST_SUITE_END()
}
| 30.621951 | 117 | 0.54779 | [
"vector"
] |
8a219713dbe7cb175217cbcbcdda6415a8f89813 | 791 | cpp | C++ | MFC/day07/day07/MFCData/MFCData.cpp | youngqqcn/WindowsNotes | e18485cd9516bab11c51c66511c40055ae33df23 | [
"MIT"
] | 44 | 2019-03-24T10:50:53.000Z | 2022-03-25T16:29:17.000Z | MFC/day07/day07/MFCData/MFCData.cpp | youngqqcn/WindowsNotes | e18485cd9516bab11c51c66511c40055ae33df23 | [
"MIT"
] | null | null | null | MFC/day07/day07/MFCData/MFCData.cpp | youngqqcn/WindowsNotes | e18485cd9516bab11c51c66511c40055ae33df23 | [
"MIT"
] | 13 | 2019-05-09T16:20:58.000Z | 2022-03-08T06:48:34.000Z | // MFCData.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MFCData.h"
#include <afxtempl.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
class CAnimal
{
public:
int iLegs;
};
void Arr()
{
CArray<int , int> arInt;
arInt.Add(100);
cout << arInt[0] << endl;
CArray<CAnimal, CAnimal&> arAnimal;
}
void StrArr()
{
CStringArray arStrs;
arStrs.Add("Test1");
arStrs.Add("Test2");
cout << arStrs[0].GetBuffer(0) << endl;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
//StrArr();
Arr();
return 0;
}
| 11.3 | 77 | 0.591656 | [
"object"
] |
8a220102a4993b5375f7df0fd19bb45efca9112f | 8,841 | hpp | C++ | examples/ui/Drawing2D.hpp | tobiaskohlbau/IPPP | 91432f00b49ea5a83648e3294ad5b4b661dcd284 | [
"Apache-2.0"
] | null | null | null | examples/ui/Drawing2D.hpp | tobiaskohlbau/IPPP | 91432f00b49ea5a83648e3294ad5b4b661dcd284 | [
"Apache-2.0"
] | null | null | null | examples/ui/Drawing2D.hpp | tobiaskohlbau/IPPP | 91432f00b49ea5a83648e3294ad5b4b661dcd284 | [
"Apache-2.0"
] | null | null | null | #ifndef DRAWING2D_HPP
#define DRAWING2D_HPP
#include <type_traits>
#include "opencv2/core/eigen.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <Eigen/Core>
#include <ippp/Identifier.h>
#include <ippp/dataObj/Node.hpp>
#include <ippp/dataObj/PointList.hpp>
#include <ippp/types.h>
#include <ippp/util/Logging.h>
#include <ippp/environment/robot/SerialRobot2D.h>
namespace ippp {
namespace drawing {
/*!
* \brief Draw nodes and there edge to the parent Node
* \author Sascha Kaden
* \param[in] vector of nodes
* \param[in,out] image
* \param[in] color of the nodes
* \param[in] color of the edges
* \param[in] thickness of the points
* \date 2016-05-25
*/
template <unsigned int dim>
void drawTree2D(const std::vector<std::shared_ptr<Node<dim>>> &nodes, cv::Mat &image, Eigen::Vector3i colorNode,
Eigen::Vector3i colorEdge, int thickness) {
static_assert(dim == 2, "Dimension has to be 2");
for (auto &elem : nodes) {
cv::Point point(elem->getValue(0), elem->getValue(1));
// cv::circle(image, point, 3, cv::Scalar(colorNode[0], colorNode[1], colorNode[2]), 1);
if (elem->getParentNode() != nullptr) {
cv::Point point2(elem->getParentNode()->getValue(0), elem->getParentNode()->getValue(1));
cv::line(image, point, point2, cv::Scalar(colorEdge[0], colorEdge[1], colorEdge[2]), thickness);
}
}
}
/*!
* \brief Draw nodes and there edge to the child Nodes
* \author Sascha Kaden
* \param[in] vector of nodes
* \param[in,out] image
* \param[in] color of the nodes
* \param[in] color of the edges
* \param[in] thickness of the points
* \date 2016-05-25
*/
template <unsigned int dim>
void drawGraph2D(const std::vector<std::shared_ptr<Node<dim>>> &nodes, cv::Mat &image, Eigen::Vector3i colorNode,
Eigen::Vector3i colorEdge, int thickness) {
static_assert(dim == 2, "Dimension has to be 2");
for (auto &elem : nodes) {
cv::Point point(elem->getValue(0), elem->getValue(1));
// cv::circle(image, point, 3, cv::Scalar(colorNode[0], colorNode[1], colorNode[2]), 1);
for (auto &child : elem->getChildNodes()) {
if (child != nullptr) {
cv::Point point2(child->getValue(0), child->getValue(1));
cv::line(image, point, point2, cv::Scalar(colorEdge[0], colorEdge[1], colorEdge[2]), thickness);
}
}
}
}
/*!
* \brief Draw a path with the passed points in an image
* \author Sascha Kaden
* \param[in] vector of points
* \param[in,out] image
* \param[in] color of the points
* \param[in] thickness of the points
* \date 2016-05-25
*/
static void drawPath2D(const std::vector<Vector2> configs, cv::Mat &image, Eigen::Vector3i colorPoint, int thickness) {
if (configs.empty())
return;
for (int i = 0; i < configs.size(); ++i) {
cv::Point point(configs[i][0], configs[i][1]);
cv::circle(image, point, 2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
}
}
/*!
* \brief Draw a triangle path with the passed triangles and posses in an image
* \author Sascha Kaden
* \param[in] config
* \param[in] SerialRobot2D
* \param[in,out] image
* \param[in] color of the triangle lines
* \param[in] thickness of the lines
* \date 2016-05-25
*/
template <unsigned int dim>
static void drawSerialRobot2D(const Vector<dim> config, const std::shared_ptr<SerialRobot2D> &robot, cv::Mat &image,
Eigen::Vector3i colorPoint, int thickness) {
Logging::info("start drawing of SerialRobot2D", "Drawing2D");
auto baseMesh = robot->getBaseModel()->m_mesh;
auto jointModels = robot->getJointModels();
std::vector<Mesh> jointMeshes;
for (auto &model : jointModels)
jointMeshes.push_back(model->m_mesh);
auto AsLinks = robot->getLinkTrafos(config);
cad::transformVertices(robot->getPose(), baseMesh.vertices);
for (size_t i = 0; i < AsLinks.size(); ++i)
cad::transformVertices(AsLinks[i], jointMeshes[i].vertices);
for (auto &face : baseMesh.faces) {
auto pt1 = cv::Point2i(static_cast<int>(baseMesh.vertices[face[0]][0]),
static_cast<int>(baseMesh.vertices[face[0]][1]));
auto pt2 = cv::Point2i(static_cast<int>(baseMesh.vertices[face[1]][0]),
static_cast<int>(baseMesh.vertices[face[1]][1]));
auto pt3 = cv::Point2i(static_cast<int>(baseMesh.vertices[face[2]][0]),
static_cast<int>(baseMesh.vertices[face[2]][1]));
cv::line(image, pt1, pt2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
cv::line(image, pt1, pt3, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
cv::line(image, pt3, pt2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
}
for (auto &mesh : jointMeshes) {
for (auto &face : mesh.faces) {
auto pt1 = cv::Point2i(static_cast<int>(mesh.vertices[face[0]][0]),
static_cast<int>(mesh.vertices[face[0]][1]));
auto pt2 = cv::Point2i(static_cast<int>(mesh.vertices[face[1]][0]),
static_cast<int>(mesh.vertices[face[1]][1]));
auto pt3 = cv::Point2i(static_cast<int>(mesh.vertices[face[2]][0]),
static_cast<int>(mesh.vertices[face[2]][1]));
cv::line(image, pt1, pt2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
cv::line(image, pt1, pt3, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
cv::line(image, pt3, pt2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
}
}
}
/*!
* \brief Draw a triangle path with the passed triangles and posses in an image
* \author Sascha Kaden
* \param[in] vector of transformations
* \param[in] vector of triangles
* \param[in,out] image
* \param[in] color of the triangle lines
* \param[in] thickness of the lines
* \date 2016-05-25
*/
static void drawTrianglePath(const std::vector<Vector3> configs, const Mesh mesh, cv::Mat &image, Eigen::Vector3i colorPoint,
int thickness) {
if (configs.empty())
return;
Logging::info("start drawing of triangles", "Drawing2D");
for (auto &config : configs) {
auto tempMesh = mesh;
Vector6 tmpConfig = util::Vecd(config[0], config[1], 0, 0, 0, config[2]);
auto T = util::poseVecToTransform(tmpConfig);
cad::transformVertices(T, tempMesh.vertices);
for (auto &face : tempMesh.faces) {
auto pt1 =
cv::Point2i(static_cast<int>(tempMesh.vertices[face[0]][0]), static_cast<int>(tempMesh.vertices[face[0]][1]));
auto pt2 =
cv::Point2i(static_cast<int>(tempMesh.vertices[face[1]][0]), static_cast<int>(tempMesh.vertices[face[1]][1]));
auto pt3 =
cv::Point2i(static_cast<int>(tempMesh.vertices[face[2]][0]), static_cast<int>(tempMesh.vertices[face[2]][1]));
cv::line(image, pt1, pt2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
cv::line(image, pt1, pt3, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
cv::line(image, pt3, pt2, cv::Scalar(colorPoint[0], colorPoint[1], colorPoint[2]), thickness);
}
}
}
/*!
* \brief Convert cv::Mat to integer Eigen matrix
* \author Sascha Kaden
* \param[in] image
* \param[out] Eigen matrix
* \date 2016-12-18
*/
static Eigen::MatrixXi cvToEigen(cv::Mat cvMat) {
if (cvMat.empty()) {
Logging::error("Image is empty", "Drawing2D");
return Eigen::MatrixXi();
}
cv::Mat dst;
cvMat.convertTo(dst, CV_32SC1);
Eigen::Map<Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> A_Eigen(dst.ptr<int>(), dst.rows, dst.cols);
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> B = A_Eigen;
return B;
}
/*!
* \brief Convert cv::Mat to integer Eigen matrix
* \author Sascha Kaden
* \param[in] image
* \param[out] Eigen matrix
* \date 2016-12-18
*/
static cv::Mat eigenToCV(Eigen::MatrixXi eigenMat) {
cv::Mat cvMat(eigenMat.rows(), eigenMat.cols(), CV_32SC1, eigenMat.data());
if (Eigen::RowMajorBit) {
cv::transpose(cvMat, cvMat);
}
cv::Mat dst;
cvMat.convertTo(dst, CV_8UC1);
return dst;
}
} /* namespace drawing */
} /* namespace ippp */
#endif /* DRAWING2D_HPP */
| 39.293333 | 128 | 0.609207 | [
"cad",
"mesh",
"vector",
"model"
] |
8a27218d901285520ba45af0316c380e358fd79f | 18,153 | cc | C++ | Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | Calibration/EcalCalibAlgos/src/PhiSymmetryCalibration.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "Calibration/EcalCalibAlgos/interface/PhiSymmetryCalibration.h"
// System include files
#include <memory>
// Framework
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "DataFormats/EcalDetId/interface/EEDetId.h"
#include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h"
#include "CondFormats/EcalObjects/interface/EcalIntercalibErrors.h"
#include "CondTools/Ecal/interface/EcalIntercalibConstantsXMLTranslator.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
// Geometry
#include "Geometry/Records/interface/CaloGeometryRecord.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloGeometry.h"
//Channel status
#include "CondFormats/EcalObjects/interface/EcalChannelStatus.h"
#include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h"
#include "CondFormats/EcalObjects/interface/EcalChannelStatusCode.h"
#include "FWCore/Framework/interface/Run.h"
#include "boost/filesystem/operations.hpp"
using namespace std;
#include <fstream>
#include <iostream>
#include "TH2F.h"
#include "TFile.h"
#include "TTree.h"
#include "TH1F.h"
#include "TF1.h"
#include "TGraph.h"
#include "TCanvas.h"
const float PhiSymmetryCalibration::kMiscalRangeEB = .05;
const float PhiSymmetryCalibration::kMiscalRangeEE = .10;
//_____________________________________________________________________________
// Class constructor
PhiSymmetryCalibration::PhiSymmetryCalibration(const edm::ParameterSet& iConfig) :
ecalHitsProducer_(iConfig.getParameter<std::string>("ecalRecHitsProducer")),
barrelHits_( iConfig.getParameter< std::string > ("barrelHitCollection")),
endcapHits_( iConfig.getParameter< std::string > ("endcapHitCollection")),
eCut_barl_( iConfig.getParameter< double > ("eCut_barrel") ),
ap_( iConfig.getParameter<double> ("ap") ),
b_( iConfig.getParameter<double> ("b") ),
eventSet_( iConfig.getParameter< int > ("eventSet") ),
statusThreshold_(iConfig.getUntrackedParameter<int>("statusThreshold",3)),
reiteration_(iConfig.getUntrackedParameter< bool > ("reiteration",false)),
oldcalibfile_(iConfig.getUntrackedParameter<std::string>("oldcalibfile",
"EcalintercalibConstants.xml"))
{
isfirstpass_=true;
et_spectrum_b_histos.resize(kBarlRings);
e_spectrum_b_histos.resize(kBarlRings);
et_spectrum_e_histos.resize(kEndcEtaRings);
e_spectrum_e_histos.resize(kEndcEtaRings);
spectra=true;
nevents_=0;
eventsinrun_=0;
eventsinlb_=0;
}
//_____________________________________________________________________________
// Close files, etc.
PhiSymmetryCalibration::~PhiSymmetryCalibration()
{
for(Int_t i=0;i<kBarlRings;i++){
delete et_spectrum_b_histos[i];
delete e_spectrum_b_histos[i];
}
for(Int_t i=0;i<kEndcEtaRings;i++){
delete et_spectrum_e_histos[i];
delete e_spectrum_e_histos[i];
}
}
//_____________________________________________________________________________
// Initialize algorithm
void PhiSymmetryCalibration::beginJob( )
{
// initialize arrays
for (int sign=0; sign<kSides; sign++) {
for (int ieta=0; ieta<kBarlRings; ieta++) {
for (int iphi=0; iphi<kBarlWedges; iphi++) {
etsum_barl_[ieta][iphi][sign]=0.;
nhits_barl_[ieta][iphi][sign]=0;
}
}
for (int ix=0; ix<kEndcWedgesX; ix++) {
for (int iy=0; iy<kEndcWedgesY; iy++) {
etsum_endc_[ix][iy][sign]=0.;
nhits_endc_[ix][iy][sign]=0;
}
}
}
for (int imiscal=0; imiscal<kNMiscalBinsEB; imiscal++) {
miscalEB_[imiscal]= (1-kMiscalRangeEB) + float(imiscal)* (2*kMiscalRangeEB/(kNMiscalBinsEB-1));
for (int ieta=0; ieta<kBarlRings; ieta++) etsum_barl_miscal_[imiscal][ieta]=0.;
}
for (int imiscal=0; imiscal<kNMiscalBinsEE; imiscal++) {
miscalEE_[imiscal]= (1-kMiscalRangeEE) + float(imiscal)* (2*kMiscalRangeEE/(kNMiscalBinsEE-1));
for (int ring=0; ring<kEndcEtaRings; ring++) etsum_endc_miscal_[imiscal][ring]=0.;
}
// start spectra stuff
if (eventSet_!=1) spectra = false;
if(spectra)
{
ostringstream t;
for(Int_t i=0;i<kBarlRings;i++)
{
t << "et_spectrum_b_" << i+1;
et_spectrum_b_histos[i]=new TH1F(t.str().c_str(),";E_{T} [MeV]",50,0.,500.);
t.str("");
t << "e_spectrum_b_" << i+1;
e_spectrum_b_histos[i]=new TH1F(t.str().c_str(),";E [MeV]",50,0.,500.);
t.str("");
}
for(Int_t i=0;i<kEndcEtaRings;i++)
{
t << "et_spectrum_e_" << i+1;
et_spectrum_e_histos[i]=new TH1F(t.str().c_str(),";E_{T} [MeV]",75,0.,1500.);
t.str("");
t << "e_spectrum_e_" << i+1;
e_spectrum_e_histos[i]=new TH1F(t.str().c_str(),";E [MeV]",75,0.,1500.);
t.str("");
}
}
// end spectra stuff
}
//_____________________________________________________________________________
// Terminate algorithm
void PhiSymmetryCalibration::endJob()
{
edm::LogInfo("Calibration") << "[PhiSymmetryCalibration] At end of job";
// start spectra stuff
if(spectra)
{
TFile f("Espectra_plus.root","recreate");
for(int i=0;i<kBarlRings;i++){
et_spectrum_b_histos[i]->Write();
e_spectrum_b_histos[i]->Write();
}
for(int i=0;i<kEndcEtaRings;i++){
et_spectrum_e_histos[i]->Write();
e_spectrum_e_histos[i]->Write();
}
f.Close();
}
if (eventSet_==1) {
// calculate factors to convert from fractional deviation of ET sum from
// the mean to the estimate of the miscalibration factor
getKfactors();
std::ofstream k_barl_out("k_barl.dat", ios::out);
for (int ieta=0; ieta<kBarlRings; ieta++)
k_barl_out << ieta << " " << k_barl_[ieta] << endl;
k_barl_out.close();
std::ofstream k_endc_out("k_endc.dat", ios::out);
for (int ring=0; ring<kEndcEtaRings; ring++)
k_endc_out << ring << " " << k_endc_[ring] << endl;
k_endc_out.close();
}
if (eventSet_!=0) {
// output ET sums
stringstream etsum_file_barl;
etsum_file_barl << "etsum_barl_"<<eventSet_<<".dat";
std::ofstream etsum_barl_out(etsum_file_barl.str().c_str(),ios::out);
for (int ieta=0; ieta<kBarlRings; ieta++) {
for (int iphi=0; iphi<kBarlWedges; iphi++) {
for (int sign=0; sign<kSides; sign++) {
etsum_barl_out << eventSet_ << " " << ieta << " " << iphi << " " << sign
<< " " << etsum_barl_[ieta][iphi][sign] << " "
<< nhits_barl_[ieta][iphi][sign] << endl;
}
}
}
etsum_barl_out.close();
stringstream etsum_file_endc;
etsum_file_endc << "etsum_endc_"<<eventSet_<<".dat";
std::ofstream etsum_endc_out(etsum_file_endc.str().c_str(),ios::out);
for (int ix=0; ix<kEndcWedgesX; ix++) {
for (int iy=0; iy<kEndcWedgesY; iy++) {
int ring = e_.endcapRing_[ix][iy];
if (ring!=-1) {
for (int sign=0; sign<kSides; sign++) {
etsum_endc_out << eventSet_ << " " << ix << " " << iy << " " << sign
<< " " << etsum_endc_[ix][iy][sign] << " "
<< nhits_endc_[ix][iy][sign]<<" "
<< e_.endcapRing_[ix][iy]<<endl;
}
}
}
}
etsum_endc_out.close();
}
cout<<"Events processed " << nevents_<< endl;
}
//_____________________________________________________________________________
// Called at each event
void PhiSymmetryCalibration::analyze( const edm::Event& event, const edm::EventSetup& setup )
{
using namespace edm;
using namespace std;
if (isfirstpass_) {
setUp(setup);
isfirstpass_=false;
}
Handle<EBRecHitCollection> barrelRecHitsHandle;
Handle<EERecHitCollection> endcapRecHitsHandle;
event.getByLabel(ecalHitsProducer_,barrelHits_,barrelRecHitsHandle);
if (!barrelRecHitsHandle.isValid()) {
LogError("") << "[PhiSymmetryCalibration] Error! Can't get product!" << std::endl;
}
event.getByLabel(ecalHitsProducer_,endcapHits_,endcapRecHitsHandle);
if (!endcapRecHitsHandle.isValid()) {
LogError("") << "[PhiSymmetryCalibration] Error! Can't get product!" << std::endl;
}
// get the ecal geometry
edm::ESHandle<CaloGeometry> geoHandle;
setup.get<CaloGeometryRecord>().get(geoHandle);
const CaloSubdetectorGeometry *barrelGeometry =
geoHandle->getSubdetectorGeometry(DetId::Ecal, EcalBarrel);
const CaloSubdetectorGeometry *endcapGeometry =
geoHandle->getSubdetectorGeometry(DetId::Ecal, EcalEndcap);
bool pass=false;
// select interesting EcalRecHits (barrel)
EBRecHitCollection::const_iterator itb;
for (itb=barrelRecHitsHandle->begin(); itb!=barrelRecHitsHandle->end(); itb++) {
EBDetId hit = EBDetId(itb->id());
float eta = barrelGeometry->getGeometry(hit)->getPosition().eta();
float et = itb->energy()/cosh(eta);
float e = itb->energy();
// if iterating, correct by the previous calib constants found,
// which are supplied in the form of correction
if (reiteration_) {
et= et * oldCalibs_[hit];
e = e * oldCalibs_[hit];
}
float et_thr = eCut_barl_/cosh(eta) + 1.;
int sign = hit.ieta()>0 ? 1 : 0;
if (e > eCut_barl_ && et < et_thr && e_.goodCell_barl[abs(hit.ieta())-1][hit.iphi()-1][sign]) {
etsum_barl_[abs(hit.ieta())-1][hit.iphi()-1][sign] += et;
nhits_barl_[abs(hit.ieta())-1][hit.iphi()-1][sign] ++;
pass =true;
}//if energy
if (eventSet_==1) {
// apply a miscalibration to all crystals and increment the
// ET sum, combined for all crystals
for (int imiscal=0; imiscal<kNMiscalBinsEB; imiscal++) {
if (miscalEB_[imiscal]*e > eCut_barl_&& miscalEB_[imiscal]*et < et_thr && e_.goodCell_barl[abs(hit.ieta())-1][hit.iphi()-1][sign]) {
etsum_barl_miscal_[imiscal][abs(hit.ieta())-1] += miscalEB_[imiscal]*et;
}
}
// spectra stuff
if(spectra && hit.ieta()>0) //POSITIVE!!!
// if(spectra && hit.ieta()<0) //NEGATIVE!!!
{
et_spectrum_b_histos[abs(hit.ieta())-1]->Fill(et*1000.);
e_spectrum_b_histos[abs(hit.ieta())-1]->Fill(e*1000.);
}//if spectra
}//if eventSet_==1
}//for barl
// select interesting EcalRecHits (endcaps)
EERecHitCollection::const_iterator ite;
for (ite=endcapRecHitsHandle->begin(); ite!=endcapRecHitsHandle->end(); ite++) {
EEDetId hit = EEDetId(ite->id());
float eta = abs(endcapGeometry->getGeometry(hit)->getPosition().eta());
//float phi = endcapGeometry->getGeometry(hit)->getPosition().phi();
float et = ite->energy()/cosh(eta);
float e = ite->energy();
// if iterating, multiply by the previous correction factor
if (reiteration_) {
et= et * oldCalibs_[hit];
e = e * oldCalibs_[hit];
}
int sign = hit.zside()>0 ? 1 : 0;
// changes of eCut_endc_ -> variable linearthr
// e_cut = ap + eta_ring*b
double eCut_endc=0;
for (int ring=0; ring<kEndcEtaRings; ring++) {
if(eta>e_.etaBoundary_[ring] && eta<e_.etaBoundary_[ring+1])
{
float eta_ring= abs(e_.cellPos_[ring][50].eta()) ;
eCut_endc = ap_ + eta_ring*b_;
}
}
float et_thr = eCut_endc/cosh(eta) + 1.;
if (e > eCut_endc && et < et_thr && e_.goodCell_endc[hit.ix()-1][hit.iy()-1][sign]){
etsum_endc_[hit.ix()-1][hit.iy()-1][sign] += et;
nhits_endc_[hit.ix()-1][hit.iy()-1][sign] ++;
pass=true;
}
if (eventSet_==1) {
// apply a miscalibration to all crystals and increment the
// ET sum, combined for all crystals
for (int imiscal=0; imiscal<kNMiscalBinsEE; imiscal++) {
if (miscalEE_[imiscal]*e> eCut_endc && et*miscalEE_[imiscal] < et_thr && e_.goodCell_endc[hit.ix()-1][hit.iy()-1][sign]){
int ring = e_.endcapRing_[hit.ix()-1][hit.iy()-1];
etsum_endc_miscal_[imiscal][ring] += miscalEE_[imiscal]*et;
}
}
// spectra stuff
if(spectra && hit.zside()>0) //POSITIVE!!!
{
int ring = e_.endcapRing_[hit.ix()-1][hit.iy()-1];
et_spectrum_e_histos[ring]->Fill(et*1000.);
e_spectrum_e_histos[ring]->Fill(e*1000.);
if(ring==16)
{
//int iphi_endc = 0;
for (int ip=0; ip<e_.nRing_[ring]; ip++) {
//if (phi==e_.phi_endc_[ip][ring]) iphi_endc=ip;
}
}
}//if spectra
}//if eventSet_==1
}//for endc
if (pass) {
nevents_++;
eventsinrun_++;
eventsinlb_++;
}
}
void PhiSymmetryCalibration::endRun(edm::Run const& run, const edm::EventSetup&){
std::cout << "PHIREPRT : run "<< run.run()
<< " start " << (run.beginTime().value()>>32)
<< " end " << (run.endTime().value()>>32)
<< " dur " << (run.endTime().value()>>32)- (run.beginTime().value()>>32)
<< " npass " << eventsinrun_ << std::endl;
eventsinrun_=0;
return ;
}
//_____________________________________________________________________________
void PhiSymmetryCalibration::getKfactors()
{
float epsilon_T_eb[kNMiscalBinsEB];
float epsilon_M_eb[kNMiscalBinsEB];
float epsilon_T_ee[kNMiscalBinsEE];
float epsilon_M_ee[kNMiscalBinsEE];
std::vector<TGraph*> k_barl_graph(kBarlRings);
std::vector<TCanvas*> k_barl_plot(kBarlRings);
//Create our own TF1 to avoid threading problems
TF1 mypol1("mypol1","pol1");
for (int ieta=0; ieta<kBarlRings; ieta++) {
for (int imiscal=0; imiscal<kNMiscalBinsEB; imiscal++) {
int middlebin = int (kNMiscalBinsEB/2);
epsilon_T_eb[imiscal] = etsum_barl_miscal_[imiscal][ieta]/etsum_barl_miscal_[middlebin][ieta] - 1.;
epsilon_M_eb[imiscal] = miscalEB_[imiscal] - 1.;
}
k_barl_graph[ieta] = new TGraph (kNMiscalBinsEB,epsilon_M_eb,epsilon_T_eb);
k_barl_graph[ieta]->Fit(&mypol1);
ostringstream t;
t<< "k_barl_" << ieta+1;
k_barl_plot[ieta] = new TCanvas(t.str().c_str(),"");
k_barl_plot[ieta]->SetFillColor(10);
k_barl_plot[ieta]->SetGrid();
k_barl_graph[ieta]->SetMarkerSize(1.);
k_barl_graph[ieta]->SetMarkerColor(4);
k_barl_graph[ieta]->SetMarkerStyle(20);
k_barl_graph[ieta]->GetXaxis()->SetLimits(-1.*kMiscalRangeEB,kMiscalRangeEB);
k_barl_graph[ieta]->GetXaxis()->SetTitleSize(.05);
k_barl_graph[ieta]->GetYaxis()->SetTitleSize(.05);
k_barl_graph[ieta]->GetXaxis()->SetTitle("#epsilon_{M}");
k_barl_graph[ieta]->GetYaxis()->SetTitle("#epsilon_{T}");
k_barl_graph[ieta]->Draw("AP");
k_barl_[ieta] = k_barl_graph[ieta]->GetFunction("pol1")->GetParameter(1);
std::cout << "k_barl_[" << ieta << "]=" << k_barl_[ieta] << std::endl;
}
std::vector<TGraph*> k_endc_graph(kEndcEtaRings);
std::vector<TCanvas*> k_endc_plot(kEndcEtaRings);
for (int ring=0; ring<kEndcEtaRings; ring++) {
for (int imiscal=0; imiscal<kNMiscalBinsEE; imiscal++) {
int middlebin = int (kNMiscalBinsEE/2);
epsilon_T_ee[imiscal] = etsum_endc_miscal_[imiscal][ring]/etsum_endc_miscal_[middlebin][ring] - 1.;
epsilon_M_ee[imiscal] = miscalEE_[imiscal] - 1.;
}
k_endc_graph[ring] = new TGraph (kNMiscalBinsEE,epsilon_M_ee,epsilon_T_ee);
k_endc_graph[ring]->Fit(&mypol1);
ostringstream t;
t<< "k_endc_"<< ring+1;
k_endc_plot[ring] = new TCanvas(t.str().c_str(),"");
k_endc_plot[ring]->SetFillColor(10);
k_endc_plot[ring]->SetGrid();
k_endc_graph[ring]->SetMarkerSize(1.);
k_endc_graph[ring]->SetMarkerColor(4);
k_endc_graph[ring]->SetMarkerStyle(20);
k_endc_graph[ring]->GetXaxis()->SetLimits(-1*kMiscalRangeEE,kMiscalRangeEE);
k_endc_graph[ring]->GetXaxis()->SetTitleSize(.05);
k_endc_graph[ring]->GetYaxis()->SetTitleSize(.05);
k_endc_graph[ring]->GetXaxis()->SetTitle("#epsilon_{M}");
k_endc_graph[ring]->GetYaxis()->SetTitle("#epsilon_{T}");
k_endc_graph[ring]->Draw("AP");
k_endc_[ring] = k_endc_graph[ring]->GetFunction("pol1")->GetParameter(1);
std::cout << "k_endc_[" << ring << "]=" << k_endc_[ring] << std::endl;
}
TFile f("PhiSymmetryCalibration_kFactors.root","recreate");
for (int ieta=0; ieta<kBarlRings; ieta++) {
k_barl_plot[ieta]->Write();
delete k_barl_plot[ieta];
delete k_barl_graph[ieta];
}
for (int ring=0; ring<kEndcEtaRings; ring++) {
k_endc_plot[ring]->Write();
delete k_endc_plot[ring];
delete k_endc_graph[ring];
}
f.Close();
}
//_____________________________________________________________________________
void PhiSymmetryCalibration::setUp(const edm::EventSetup& setup){
edm::ESHandle<EcalChannelStatus> chStatus;
setup.get<EcalChannelStatusRcd>().get(chStatus);
edm::ESHandle<CaloGeometry> geoHandle;
setup.get<CaloGeometryRecord>().get(geoHandle);
e_.setup(&(*geoHandle), &(*chStatus), statusThreshold_);
if (reiteration_){
EcalCondHeader h;
// namespace fs = boost::filesystem;
// fs::path p(oldcalibfile_.c_str(),fs::native);
// if (!fs::exists(p)) edm::LogError("PhiSym") << "File not found: "
// << oldcalibfile_ <<endl;
edm::FileInPath fip("Calibration/EcalCalibAlgos/data/"+oldcalibfile_);
int ret=
EcalIntercalibConstantsXMLTranslator::readXML(fip.fullPath(),h,oldCalibs_);
if (ret) edm::LogError("PhiSym")<<"Error reading XML files"<<endl;;
} else {
// in fact if not reiterating, oldCalibs_ will never be used
edm::ESHandle<EcalIntercalibConstants> pIcal;
setup.get<EcalIntercalibConstantsRcd>().get(pIcal);
oldCalibs_=*pIcal;
}
}
void PhiSymmetryCalibration::endLuminosityBlock(edm::LuminosityBlock const& lb, edm::EventSetup const&){
if ((lb.endTime().value()>>32)- (lb.beginTime().value()>>32) <60 )
return;
std::cout << "PHILB : run "<< lb.run()
<< " id " << lb.id()
<< " start " << (lb.beginTime().value()>>32)
<< " end " << (lb.endTime().value()>>32)
<< " dur " << (lb.endTime().value()>>32)- (lb.beginTime().value()>>32)
<< " npass " << eventsinlb_ << std::endl;
eventsinlb_=0;
}
| 29.906096 | 134 | 0.658624 | [
"geometry",
"vector"
] |
8a29085d6cde08151c6e5d04bb2592859791d08c | 6,928 | cpp | C++ | 03_Tutorial/T02_XMCocos2D-CookBook/Source/Libraries/mcLua.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 03_Tutorial/T02_XMCocos2D-CookBook/Source/Libraries/mcLua.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 03_Tutorial/T02_XMCocos2D-CookBook/Source/Libraries/mcLua.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /* --------------------------------------------------------------------------
*
* File mcLua.cpp
* Ported By Young-Hwan Mun
* Contact xmsoft77@gmail.com
*
* Created by Robert Grzesek on 11/10/09
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft.
* Copyright (c) 2009 GRZ Software LLC. All rights reserved.
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "mcLua.h"
// Below are the functions used for the yield funtions.
static KDint LuaYieldSeconds ( lua_State* l )
{
mcLuaScript* s;
lua_pushlightuserdata ( l, l );
lua_gettable ( l, LUA_GLOBALSINDEX );
s = (mcLuaScript*) lua_touserdata ( l, -1 );
KDfloat n = (KDfloat) lua_tonumber ( l, 1 );
s->YieldSeconds ( n );
// kdPrintf ( "waitSeconds %f\n", n );
return ( lua_yield ( l, 0 ) );
}
static KDint LuaYieldFrames ( lua_State* l )
{
mcLuaScript* s;
lua_pushlightuserdata ( l, l );
lua_gettable ( l, LUA_GLOBALSINDEX );
s = (mcLuaScript*) lua_touserdata ( l, -1 );
KDint f = (KDint) lua_tonumber ( l, 1 );
s->YieldFrames ( f );
// kdPrintf ( "waitFrames %d\n", f );
return ( lua_yield ( l, 0 ) );
}
static KDint LuaYieldPause ( lua_State* l )
{
mcLuaScript* s;
lua_pushlightuserdata ( l, l );
lua_gettable ( l, LUA_GLOBALSINDEX );
s = (mcLuaScript*) lua_touserdata ( l, -1 );
s->YieldPause ( );
// kdPrintf ( "pause \n" );
return ( lua_yield ( l, 0 ) );
}
//---------------------------------------------------------------
mcLuaManager::mcLuaManager ( KDvoid )
{
m_pHead = KD_NULL;
m_pMainState = lua_open ( );
// Add functions for waiting
static const luaL_reg scriptLib [ ] =
{
{ "waitSeconds" , LuaYieldSeconds },
{ "waitFrames" , LuaYieldFrames },
{ "pause" , LuaYieldPause },
{ KD_NULL , KD_NULL }
};
LuaOpenLibrary ( "script", scriptLib );
// add the base library
luaopen_base ( m_pMainState );
luaopen_math ( m_pMainState );
luaopen_string ( m_pMainState );
lua_settop ( m_pMainState, 0 );
}
mcLuaManager::~mcLuaManager ( KDvoid )
{
mcLuaScript* n = m_pHead;
while ( n )
{
mcLuaScript* i = n->m_pNext;
delete ( n );
n = i;
}
lua_close ( m_pMainState );
}
KDbool mcLuaManager::LuaOpenLibrary ( const KDchar* szName, const luaL_reg* pLibs )
{
if ( m_pHead != KD_NULL )
{
return 0;
}
luaL_openlib ( m_pMainState, szName, pLibs, 0 );
return 1;
}
KDvoid mcLuaManager::SetGlobalNumber ( const KDchar* szName, KDdouble dVal )
{
lua_pushnumber ( m_pMainState, dVal );
lua_setglobal ( m_pMainState, szName );
}
KDvoid mcLuaManager::SetGlobalInteger ( const KDchar* szName, KDint nVal )
{
lua_pushinteger ( m_pMainState, nVal );
lua_setglobal ( m_pMainState, szName );
}
KDvoid mcLuaManager::SetGlobalString ( const KDchar* szName, const KDchar* szVal )
{
lua_pushstring ( m_pMainState, szVal );
lua_setglobal ( m_pMainState, szName );
}
mcLuaScript* mcLuaManager::CreateScript ( KDvoid )
{
lua_State* s = lua_newthread ( m_pMainState );
// Add reference to the new thread in the Lua Registry so
// will not be garbage collected
KDint r = luaL_ref ( m_pMainState, LUA_REGISTRYINDEX );
// Create a new mcLuaScript object to hold the new thread
mcLuaScript* ns = new mcLuaScript ( s, this, r );
// Add an entry to map the new lua_State to the
// new mcLuaScript object
lua_pushlightuserdata ( m_pMainState, s );
lua_pushlightuserdata ( m_pMainState, ns );
lua_settable ( m_pMainState, LUA_GLOBALSINDEX );
// insert the new script into the list
ns->m_pNext = m_pHead;
m_pHead = ns;
return ns;
}
KDvoid mcLuaManager::DestroyScript ( mcLuaScript* s )
{
if ( s == m_pHead )
{
m_pHead = s->m_pNext;
delete ( s );
return;
}
mcLuaScript* pLast = m_pHead;
for ( mcLuaScript* l = pLast->m_pNext; l != NULL; l = l->m_pNext )
{
if ( l == s )
{
pLast->m_pNext = l->m_pNext;
delete ( l );
return;
}
pLast = l;
}
}
KDvoid mcLuaManager::Update ( KDfloat fElapsedSeconds )
{
mcLuaScript* n = m_pHead;
while ( n )
{
n = n->Update ( fElapsedSeconds );
}
}
//---------------------------------------------------------------
mcLuaScript::mcLuaScript ( lua_State* l, mcLuaManager* pMan, KDint nRegistryRef )
{
m_pNext = KD_NULL;
m_nRegistryRef = nRegistryRef;
m_pState = l;
m_pManager = pMan;
m_eYieldMode = YM_NONE;
m_nWaitFrames = 0;
m_fWaitTime = 0;
}
mcLuaScript::~mcLuaScript ( KDvoid )
{
luaL_unref ( m_pState, LUA_REGISTRYINDEX, m_nRegistryRef );
}
KDvoid mcLuaScript::LoadFile ( const KDchar* szName )
{
kdPrintf ( "mcLuaScript::LoadFile() - %s\n", szName );
KDint nErr = luaL_loadfile ( m_pState, szName );
if ( nErr )
{
kdPrintf ( "luaL_loadfile Error- %s\n", lua_tostring ( m_pState, -1 ) );
lua_pop ( m_pState, 1 );
}
lua_resume ( m_pState, 0 );
}
KDvoid mcLuaScript::LoadString ( const KDchar* szBuffer )
{
KDint nErr = luaL_loadstring ( m_pState, szBuffer );
if ( nErr )
{
kdPrintf ( "%s", lua_tostring ( m_pState, -1 ) );
lua_pop ( m_pState, 1 );
}
lua_resume ( m_pState, 0 );
}
mcLuaScript* mcLuaScript::Update ( KDfloat fElapsedSeconds )
{
if ( m_eYieldMode == YM_TIME )
{
m_fWaitTime -= fElapsedSeconds;
if ( m_fWaitTime > 0 )
{
return m_pNext;
}
}
if ( m_eYieldMode == YM_FRAME )
{
--m_nWaitFrames;
if ( m_nWaitFrames > 0 )
{
return m_pNext;
}
}
if ( m_eYieldMode == YM_PAUSE )
{
return m_pNext;
}
m_eYieldMode = YM_NONE;
lua_resume ( m_pState, 0 );
return m_pNext;
}
KDvoid mcLuaScript::YieldFrames ( KDint nNum )
{
m_eYieldMode = YM_FRAME;
m_nWaitFrames = nNum;
}
KDvoid mcLuaScript::YieldSeconds ( KDfloat fSecs )
{
// kdPrintf ( "YieldSeconds \n" );
m_eYieldMode = YM_TIME;
m_fWaitTime = fSecs;
}
KDvoid mcLuaScript::YieldPause ( KDvoid )
{
m_eYieldMode = YM_PAUSE;
}
KDvoid mcLuaScript::YieldResume ( KDvoid )
{
// kdPrintf ( "resume \n" );
m_eYieldMode = YM_NONE;
} | 23.564626 | 83 | 0.618505 | [
"object"
] |
8a33b1179539fe79ad1d1c117ec845d69648fd1c | 3,372 | cpp | C++ | vcgapps/vcglib/apps/sample/trimesh_clustering/trimesh_clustering.cpp | mattjr/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | 14 | 2015-01-11T02:53:04.000Z | 2021-11-25T17:31:22.000Z | vcgapps/vcglib/apps/sample/trimesh_clustering/trimesh_clustering.cpp | skair39/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | null | null | null | vcgapps/vcglib/apps/sample/trimesh_clustering/trimesh_clustering.cpp | skair39/structured | 0cb4635af7602f2a243a9b739e5ed757424ab2a7 | [
"Apache-2.0"
] | 14 | 2015-07-21T04:47:52.000Z | 2020-03-12T12:31:25.000Z |
// mesh definition
//#include <vcg/simplex/vertex/with/vn.h>
//#include <vcg/simplex/face/with/af.h>
//#include <vcg/complex/complex.h>
#include<vcg/simplex/vertex/base.h>
#include<vcg/simplex/face/base.h>
#include<vcg/simplex/face/topology.h>
#include<vcg/complex/complex.h>
#include <vcg/complex/algorithms/update/bounding.h>
#include <vcg/complex/algorithms/update/topology.h>
#include <vcg/complex/algorithms/update/normal.h>
#include <vcg/complex/algorithms/update/flag.h>
#include <vcg/complex/algorithms/clustering.h>
// input output
#include <wrap/io_trimesh/import_ply.h>
#include <wrap/io_trimesh/export_ply.h>
// std
#include <vector>
#include <time.h>
using namespace vcg;
using namespace std;
class MyFace;
class MyVertex;
struct MyUsedTypes : public UsedTypes< Use<MyVertex> ::AsVertexType,
Use<MyFace> ::AsFaceType>{};
class MyVertex : public Vertex< MyUsedTypes, vertex::Coord3f, vertex::Normal3f, vertex::BitFlags >{};
class MyFace : public Face < MyUsedTypes, face::VertexRef, face::Normal3f, face::BitFlags > {};
class MyMesh : public vcg::tri::TriMesh< vector<MyVertex>, vector<MyFace> > {};
int main(int argc, char **argv)
{
if(argc<3)
{
printf(
"\n trimesh_clustering ("__DATE__")\n"
" Visual Computing Group I.S.T.I. C.N.R.\n"
"Usage: PlyRefine filein.ply fileout.ply [opt] \n"
"options: \n"
"-k cellnum approx number of cluster that should be defined; (default 10e5)\n"
"-s size in absolute units the size of the clustering cell (override the previous param)\n"
"-d enable the duplication of faces for double surfaces\n"
);
exit(0);
}
int i=3;
int CellNum=100000;
float CellSize=0;
bool DupFace=false;
while(i<argc)
{
if(argv[i][0]!='-')
{printf("Error unable to parse option '%s'\n",argv[i]); exit(0);}
switch(argv[i][1])
{
case 'k' : CellNum=atoi(argv[i+1]); ++i; printf("Using %i clustering cells\n",CellNum); break;
case 's' : CellSize=atof(argv[i+1]); ++i; printf("Using %5f as clustering cell size\n",CellSize); break;
case 'd' : DupFace=true; printf("Enabling the duplication of faces for double surfaces\n"); break;
default : {printf("Error unable to parse option '%s'\n",argv[i]); exit(0);}
}
++i;
}
MyMesh m;
if(vcg::tri::io::ImporterPLY<MyMesh>::Open(m,argv[1])!=0)
{
printf("Error reading file %s\n",argv[1]);
exit(0);
}
vcg::tri::UpdateBounding<MyMesh>::Box(m);
vcg::tri::UpdateNormals<MyMesh>::PerFace(m);
printf("Input mesh vn:%i fn:%i\n",m.vn,m.fn);
vcg::tri::Clustering<MyMesh, vcg::tri::AverageColorCell<MyMesh> > Grid;
Grid.DuplicateFaceParam=DupFace;
Grid.Init(m.bbox,CellNum,CellSize);
printf("Clustering to %i cells\n",Grid.Grid.siz[0]*Grid.Grid.siz[1]*Grid.Grid.siz[2] );
printf("Grid of %i x %i x %i cells\n",Grid.Grid.siz[0],Grid.Grid.siz[1],Grid.Grid.siz[2]);
printf("with cells size of %.2f x %.2f x %.2f units\n",Grid.Grid.voxel[0],Grid.Grid.voxel[1],Grid.Grid.voxel[2]);
int t0=clock();
Grid.AddMesh(m);
int t1=clock();
Grid.ExtractMesh(m);
int t2=clock();
printf("Output mesh vn:%i fn:%i\n",m.vn,m.fn);
printf("Simplified in :%i msec (%i+%i)\n",t2-t0,t1-t0,t2-t1);
vcg::tri::io::PlyInfo pi;
vcg::tri::io::ExporterPLY<MyMesh>::Save(m,argv[2],pi.mask);
return 0;
}
| 31.811321 | 115 | 0.655397 | [
"mesh",
"vector"
] |
8a38098a5cfe6a62b4b37f617ff51af6cd9311ce | 3,251 | cpp | C++ | Summer Engine/Source Code/MeshImporter.cpp | albertec1/Summer-Engine | 088c7acb1d953ff787823795ac575452db2e08b0 | [
"MIT"
] | null | null | null | Summer Engine/Source Code/MeshImporter.cpp | albertec1/Summer-Engine | 088c7acb1d953ff787823795ac575452db2e08b0 | [
"MIT"
] | null | null | null | Summer Engine/Source Code/MeshImporter.cpp | albertec1/Summer-Engine | 088c7acb1d953ff787823795ac575452db2e08b0 | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "MeshImporter.h"
#include "Assimp.h"
#pragma comment (lib, "assimp.lib")
#include <cmath>
MeshImporter::MeshImporter()
{
}
MeshImporter::~MeshImporter()
{
}
MeshInfo* MeshImporter::LoadScene(const std::string& filename)
{
MeshInfo* ret = nullptr;
//import the scene from a file
const char* file_path = filename.c_str();
//Assimp::Importer Importer; //what is this? Could it be a better implementation?
//const aiScene* scene = Importer.ReadFile(file_path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_JoinIdenticalVertices);
LOG("Loading Model from file: %s", file_path);
const aiScene* scene = aiImportFile(file_path, aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
//Make sure the scene was loaded correctly
if (scene != nullptr && scene->HasMeshes())
{
// Use scene->mNumMeshes to iterate on scene->mMeshes array
for (uint i = 0; i < scene->mNumMeshes; ++i)
{
ret = ImportMesh(scene, i);
}
}
else
{
LOG("No meshes at scene %s", file_path);
}
if (scene != nullptr && scene->HasMaterials())
{
/* for (uint i = 0; i < scene->mNumMaterials; ++i)
{
}*/
}
aiReleaseImport(scene);
return ret;
}
MeshInfo* MeshImporter::ImportMesh(const aiScene* scene, int i)
{
bool ret = true;
MeshInfo* ourMesh = new MeshInfo();
// New mesh
aiMesh* currentMesh = scene->mMeshes[i];
// copy vertices
ourMesh->num_vertices = currentMesh->mNumVertices;
// create a float array with the size of the number of vertices of the mesh * 3 accounting for x, y and z
ourMesh->vertices = new float[ourMesh->num_vertices * 3];
// store into the previously created array the content of the vertices array of the mesh we are loading
memcpy(ourMesh->vertices, currentMesh->mVertices, sizeof(float) * ourMesh->num_vertices * 3);
if (currentMesh->HasTextureCoords(0))
{
ourMesh->num_tex_coords = currentMesh->mNumVertices;
ourMesh->texture_coords = new float[currentMesh->mNumVertices * 2];
for (unsigned int i = 0; i < ourMesh->num_tex_coords; i++)
{
ourMesh->texture_coords[i * 2] = currentMesh->mTextureCoords[0][i].x;
ourMesh->texture_coords[i * 2 + 1] = currentMesh->mTextureCoords[0][i].y;
}
}
if (currentMesh->HasNormals())
{
ourMesh->num_normals = currentMesh->mNumVertices;
ourMesh->normals = new float [currentMesh->mNumVertices * 3];
memcpy(ourMesh->normals, currentMesh->mNormals, sizeof(float) * ourMesh->num_normals * 3);
}
//copy faces
if (currentMesh->HasFaces())
{
//copy number of indices
ourMesh->num_indices = currentMesh->mNumFaces * 3;
////create an array with the size of the number of indices
ourMesh->indices = new uint [ourMesh->num_indices];
//for each face
for (uint i = 0; i < currentMesh->mNumFaces; ++i)
{
const aiFace& face = currentMesh->mFaces[i];
if (face.mNumIndices != 3)
{
LOG("WARNING, geometry face with != 3 indices!");
}
else
{
//copy the 3 face indices into our indices array
memcpy(&ourMesh->indices[i * 3], currentMesh->mFaces[i].mIndices, 3 * sizeof(uint));
}
}
}
return ourMesh;
}
void MeshImporter::Clear()
{
}
| 27.319328 | 193 | 0.697631 | [
"mesh",
"geometry",
"model"
] |
8a39336aa5f0540541b12526a4ff8b2901130712 | 59,042 | cc | C++ | open_spiel/games/tarok_test.cc | Limmen/open_spiel | 2d4d7b783a9161e2c4c90f70dec29d6982fac6c1 | [
"Apache-2.0"
] | 1 | 2021-12-31T01:45:58.000Z | 2021-12-31T01:45:58.000Z | open_spiel/games/tarok_test.cc | Limmen/open_spiel | 2d4d7b783a9161e2c4c90f70dec29d6982fac6c1 | [
"Apache-2.0"
] | null | null | null | open_spiel/games/tarok_test.cc | Limmen/open_spiel | 2d4d7b783a9161e2c4c90f70dec29d6982fac6c1 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 DeepMind Technologies Limited
//
// 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 "open_spiel/games/tarok.h"
#include "open_spiel/spiel.h"
#include "open_spiel/tests/basic_tests.h"
namespace open_spiel {
namespace tarok {
constexpr int kDealCardsAction = 0;
constexpr int kBidTwoAction = 3;
constexpr int kBidOneAction = 4;
constexpr int kBidSoloTwoAction = 6;
constexpr int kBidBeggarAction = 8;
constexpr int kBidSoloWithoutAction = 9;
constexpr int kBidOpenBeggarAction = 10;
constexpr int kBidColourValatAction = 11;
constexpr int kBidValatWithoutAction = 12;
const std::array<Card, 54> card_deck = InitializeCardDeck();
// helper methods
std::shared_ptr<const TarokGame> NewTarokGame(const GameParameters& params) {
return std::static_pointer_cast<const TarokGame>(LoadGame("tarok", params));
}
std::unique_ptr<TarokState> StateAfterActions(
const GameParameters& params, const std::vector<Action>& actions) {
auto state = NewTarokGame(params)->NewInitialTarokState();
for (auto const& action : actions) {
state->ApplyAction(action);
}
return state;
}
bool AllActionsInOtherActions(const std::vector<Action>& actions,
const std::vector<Action>& other_actions) {
for (auto const& action : actions) {
if (std::find(other_actions.begin(), other_actions.end(), action) ==
other_actions.end()) {
return false;
}
}
return true;
}
Action CardLongNameToAction(const std::string& long_name) {
for (int i = 0; i < card_deck.size(); i++) {
if (card_deck.at(i).long_name == long_name) return i;
}
SpielFatalError("Invalid long_name!");
return -1;
}
std::vector<Action> CardLongNamesToActions(
const std::vector<std::string>& long_names) {
std::vector<Action> actions;
actions.reserve(long_names.size());
for (auto const long_name : long_names) {
actions.push_back(CardLongNameToAction(long_name));
}
return actions;
}
template <typename T>
bool AllEq(const std::vector<T>& xs0, const std::vector<T>& xs1) {
if (xs0.size() != xs1.size()) return false;
for (int i = 0; i < xs0.size(); i++) {
if (xs0.at(i) != xs1.at(i)) return false;
}
return true;
}
// testing
void BasicGameTests() {
testing::LoadGameTest("tarok");
testing::ChanceOutcomesTest(*LoadGame("tarok"));
testing::RandomSimTest(*LoadGame("tarok"), 100);
}
// cards tests
void CardDeckShufflingSeedTest() {
auto game = NewTarokGame(GameParameters({{"rng_seed", GameParameter(0)}}));
// subsequent shuffles within the same game should be different
auto state1 = game->NewInitialTarokState();
state1->ApplyAction(0);
auto state2 = game->NewInitialTarokState();
state2->ApplyAction(0);
SPIEL_CHECK_NE(state1->PlayerCards(0), state2->PlayerCards(0));
game = NewTarokGame(GameParameters({{"rng_seed", GameParameter(0)}}));
// shuffles should be the same when recreating a game with the same seed
auto state3 = game->NewInitialTarokState();
state3->ApplyAction(0);
auto state4 = game->NewInitialTarokState();
state4->ApplyAction(0);
SPIEL_CHECK_EQ(state1->PlayerCards(0), state3->PlayerCards(0));
SPIEL_CHECK_EQ(state2->PlayerCards(0), state4->PlayerCards(0));
}
void DealtCardsSizeTest(int num_players) {
auto [talon, players_cards] = DealCards(num_players, 42);
SPIEL_CHECK_EQ(talon.size(), 6);
int num_cards_per_player = 48 / num_players;
for (auto const& player_cards : players_cards) {
SPIEL_CHECK_EQ(player_cards.size(), num_cards_per_player);
}
}
void DealtCardsContentTest(int num_players) {
// 3 players
auto [talon, players_cards] = DealCards(num_players, 42);
// flatten and sort all the dealt cards
std::vector<int> all_dealt_cards(talon.begin(), talon.end());
for (auto const& player_cards : players_cards) {
all_dealt_cards.insert(all_dealt_cards.end(), player_cards.begin(),
player_cards.end());
}
std::sort(all_dealt_cards.begin(), all_dealt_cards.end());
// check the actual content
for (int i = 0; i < 54; i++) {
SPIEL_CHECK_EQ(all_dealt_cards.at(i), i);
}
}
void PlayersCardsSortedTest() {
auto [talon, players_cards] = DealCards(3, 42);
for (auto const& player_cards : players_cards) {
SPIEL_CHECK_TRUE(std::is_sorted(player_cards.begin(), player_cards.end()));
}
}
void CountCardsTest() {
std::vector<Action> all_card_actions(54);
std::iota(all_card_actions.begin(), all_card_actions.end(), 0);
SPIEL_CHECK_EQ(CardPoints(all_card_actions, card_deck), 70);
SPIEL_CHECK_EQ(CardPoints({}, card_deck), 0);
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions({"II"}), card_deck), 0);
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions({"II", "III"}), card_deck),
1);
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions({"Mond"}), card_deck), 4);
std::vector<std::string> cards{"Mond", "Jack of Diamonds"};
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions(cards), card_deck), 6);
cards = {"XIV", "Mond", "Jack of Diamonds"};
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions(cards), card_deck), 6);
cards = {"XIV", "Mond", "Jack of Diamonds", "Queen of Diamonds"};
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions(cards), card_deck), 9);
cards = {"II", "Jack of Clubs", "Queen of Clubs", "Mond", "King of Clubs"};
SPIEL_CHECK_EQ(CardPoints(CardLongNamesToActions(cards), card_deck), 14);
}
void CardDealingPhaseTest() {
auto game = NewTarokGame(GameParameters());
auto state = game->NewInitialTarokState();
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kCardDealing);
SPIEL_CHECK_EQ(state->CurrentPlayer(), kChancePlayerId);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_TRUE(state->TalonSets().empty());
for (int i = 0; i < game->NumPlayers(); i++) {
SPIEL_CHECK_TRUE(state->PlayerCards(i).empty());
}
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0}));
SPIEL_CHECK_TRUE(AllEq(state->ChanceOutcomes(), {{0, 1.0}}));
// deal the cards
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_NE(state->CurrentPlayer(), kChancePlayerId);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
// talon sets are only visible in the talon exchange phase
SPIEL_CHECK_TRUE(state->TalonSets().empty());
SPIEL_CHECK_EQ(state->Talon().size(), 6);
for (int i = 0; i < game->NumPlayers(); i++) {
SPIEL_CHECK_FALSE(state->PlayerCards(i).empty());
}
SPIEL_CHECK_TRUE(state->ChanceOutcomes().empty());
}
// bidding phase tests
void BiddingPhase3PlayersTest1() {
// scenario: all players pass
auto game = NewTarokGame(GameParameters());
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidKlopAction, kBidThreeAction, kBidTwoAction, kBidOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidKlopAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
}
void BiddingPhase3PlayersTest2() {
// scenario: forehand passes, player 1 eventually bids beggar, player 2 bids
// beggar
auto game = NewTarokGame(GameParameters());
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidTwoAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidOneAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidBeggarAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidBeggarAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidBeggarAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kBeggar);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
}
void BiddingPhase3PlayersTest3() {
// scenario: forehand passes, player 1 bids beggar, player 2 bids solo without
auto game = NewTarokGame(GameParameters());
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidBeggarAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidSoloWithoutAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(),
{kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidSoloWithoutAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kSoloWithout);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
}
void BiddingPhase3PlayersTest4() {
// scenario: forehand bids valat without, others are forced to pass, todo: we
// could check this case in DoApplyActionInBidding and simply finish the
// bidding phase early
auto game = NewTarokGame(GameParameters());
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidTwoAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidOneAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidOneAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidOneAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidValatWithoutAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {kBidPassAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {kBidPassAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {kBidValatWithoutAction}));
state->ApplyAction(kBidValatWithoutAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kValatWithout);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
}
void BiddingPhase4PlayersTest1() {
// scenario: all players pass
auto game = NewTarokGame(GameParameters({{"players", GameParameter(4)}}));
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidKlopAction, kBidThreeAction, kBidTwoAction, kBidOneAction,
kBidSoloThreeAction, kBidSoloTwoAction, kBidSoloOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidKlopAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
}
void BiddingPhase4PlayersTest2() {
// scenario: forehand bids one, player 2 bids one, others pass
auto game = NewTarokGame(GameParameters({{"players", GameParameter(4)}}));
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidOneAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidSoloThreeAction, kBidSoloTwoAction,
kBidSoloOneAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidOneAction, kBidSoloThreeAction, kBidSoloTwoAction,
kBidSoloOneAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidOneAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidSoloThreeAction, kBidSoloTwoAction,
kBidSoloOneAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidOneAction, kBidSoloThreeAction, kBidSoloTwoAction, kBidSoloOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidOneAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kKingCalling);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
}
void BiddingPhase4PlayersTest3() {
// scenario: player 1 bids solo three, player 3 eventually bids solo one,
// others pass
auto game = NewTarokGame(GameParameters({{"players", GameParameter(4)}}));
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidSoloThreeAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloTwoAction, kBidSoloOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloTwoAction, kBidSoloOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidSoloTwoAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloTwoAction, kBidSoloOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloTwoAction, kBidSoloOneAction,
kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidSoloOneAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kSoloOne);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
}
void BiddingPhase4PlayersTest4() {
// scenario: player 2 bids beggar, others pass
auto game = NewTarokGame(GameParameters({{"players", GameParameter(4)}}));
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidBeggarAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(
state->LegalActions(),
{kBidPassAction, kBidBeggarAction, kBidSoloWithoutAction,
kBidOpenBeggarAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidBeggarAction, kBidSoloWithoutAction, kBidOpenBeggarAction,
kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidBeggarAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kBeggar);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
}
void BiddingPhase4PlayersTest5() {
// scenario: forehand passes, player 1 bids open beggar, player 2 bids colour
// valat without, player 3 bids valat without
auto game = NewTarokGame(GameParameters({{"players", GameParameter(4)}}));
auto state = game->NewInitialTarokState();
state->ApplyAction(kDealCardsAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kBidding);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kNotSelected);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidTwoAction, kBidOneAction, kBidSoloThreeAction,
kBidSoloTwoAction, kBidSoloOneAction, kBidBeggarAction,
kBidSoloWithoutAction, kBidOpenBeggarAction, kBidColourValatAction,
kBidValatWithoutAction}));
state->ApplyAction(kBidOpenBeggarAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{kBidPassAction, kBidColourValatAction, kBidValatWithoutAction}));
state->ApplyAction(kBidColourValatAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(), {kBidPassAction, kBidValatWithoutAction}));
state->ApplyAction(kBidValatWithoutAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(), {kBidPassAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(), {kBidPassAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(), {kBidPassAction, kBidValatWithoutAction}));
state->ApplyAction(kBidPassAction);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {kBidValatWithoutAction}));
state->ApplyAction(kBidValatWithoutAction);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kValatWithout);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
}
// talon exchange phase tests
void TalonExchangePhaseTest1() {
// 3 talon exchanges, select the first set
auto state = StateAfterActions(
GameParameters(),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidThreeAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kThree);
auto talon_initial = state->TalonSets();
SPIEL_CHECK_EQ(talon_initial.size(), 2);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 1}));
for (auto const& talon_set : talon_initial) {
SPIEL_CHECK_EQ(talon_set.size(), 3);
}
// select the first set
state->ApplyAction(0);
auto talon_end = state->TalonSets();
SPIEL_CHECK_EQ(talon_end.size(), 1);
SPIEL_CHECK_EQ(talon_initial.at(1), talon_end.at(0));
SPIEL_CHECK_TRUE(AllActionsInOtherActions(
talon_initial.at(0), state->PlayerCards(state->CurrentPlayer())));
// discard the first three cards
auto legal_actions = state->LegalActions();
for (int i = 0; i < 3; i++) {
state->ApplyAction(legal_actions.at(i));
SPIEL_CHECK_FALSE(AllActionsInOtherActions(
{legal_actions.at(i)}, state->PlayerCards(state->CurrentPlayer())));
}
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
void TalonExchangePhaseTest2() {
// 3 talon exchanges, select the second set
auto state = StateAfterActions(
GameParameters(),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidThreeAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kThree);
auto talon_initial = state->TalonSets();
SPIEL_CHECK_EQ(talon_initial.size(), 2);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 1}));
for (auto const& talon_set : talon_initial) {
SPIEL_CHECK_EQ(talon_set.size(), 3);
}
// select the second set
state->ApplyAction(1);
auto talon_end = state->TalonSets();
SPIEL_CHECK_EQ(talon_end.size(), 1);
SPIEL_CHECK_EQ(talon_initial.at(0), talon_end.at(0));
SPIEL_CHECK_TRUE(AllActionsInOtherActions(
talon_initial.at(1), state->PlayerCards(state->CurrentPlayer())));
// discard the first three cards
auto legal_actions = state->LegalActions();
for (int i = 0; i < 3; i++) {
state->ApplyAction(legal_actions.at(i));
SPIEL_CHECK_FALSE(AllActionsInOtherActions(
{legal_actions.at(i)}, state->PlayerCards(state->CurrentPlayer())));
}
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
void TalonExchangePhaseTest3() {
// 2 talon exchanges, select the middle set
auto state = StateAfterActions(
GameParameters(),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidTwoAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kTwo);
auto talon_initial = state->TalonSets();
SPIEL_CHECK_EQ(talon_initial.size(), 3);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 1, 2}));
for (auto const& talon_set : talon_initial) {
SPIEL_CHECK_EQ(talon_set.size(), 2);
}
// select the middle set
state->ApplyAction(1);
auto talon_end = state->TalonSets();
SPIEL_CHECK_EQ(talon_end.size(), 2);
SPIEL_CHECK_EQ(talon_initial.at(0), talon_end.at(0));
SPIEL_CHECK_EQ(talon_initial.at(2), talon_end.at(1));
SPIEL_CHECK_TRUE(AllActionsInOtherActions(
talon_initial.at(1), state->PlayerCards(state->CurrentPlayer())));
// discard the first two cards
auto legal_actions = state->LegalActions();
for (int i = 0; i < 2; i++) {
state->ApplyAction(legal_actions.at(i));
SPIEL_CHECK_FALSE(AllActionsInOtherActions(
{legal_actions.at(i)}, state->PlayerCards(state->CurrentPlayer())));
}
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
void TalonExchangePhaseTest4() {
// 1 talon exchange, select the first set
auto state = StateAfterActions(
GameParameters(),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
auto talon_initial = state->TalonSets();
SPIEL_CHECK_EQ(talon_initial.size(), 6);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 1, 2, 3, 4, 5}));
for (auto const& talon_set : talon_initial) {
SPIEL_CHECK_EQ(talon_set.size(), 1);
}
// select the first set
state->ApplyAction(0);
auto talon_end = state->TalonSets();
SPIEL_CHECK_EQ(talon_end.size(), 5);
for (int i = 1; i < 6; i++) {
SPIEL_CHECK_EQ(talon_initial.at(i), talon_end.at(i - 1));
}
SPIEL_CHECK_TRUE(AllActionsInOtherActions(
talon_initial.at(0), state->PlayerCards(state->CurrentPlayer())));
// discard the last card
auto legal_actions = state->LegalActions();
state->ApplyAction(legal_actions.at(legal_actions.size() - 1));
SPIEL_CHECK_FALSE(
AllActionsInOtherActions({legal_actions.at(legal_actions.size() - 1)},
state->PlayerCards(state->CurrentPlayer())));
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
void TalonExchangePhaseTest5() {
// 1 talon exchange, select the fourth set
auto state = StateAfterActions(
GameParameters(),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
auto talon_initial = state->TalonSets();
SPIEL_CHECK_EQ(talon_initial.size(), 6);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 1, 2, 3, 4, 5}));
for (auto const& talon_set : talon_initial) {
SPIEL_CHECK_EQ(talon_set.size(), 1);
}
// select the fourth set
state->ApplyAction(3);
auto talon_end = state->TalonSets();
SPIEL_CHECK_EQ(talon_end.size(), 5);
for (int i = 0; i < 5; i++) {
if (i < 3)
SPIEL_CHECK_EQ(talon_initial.at(i), talon_end.at(i));
else
SPIEL_CHECK_EQ(talon_initial.at(i + 1), talon_end.at(i));
}
SPIEL_CHECK_TRUE(AllActionsInOtherActions(
talon_initial.at(3), state->PlayerCards(state->CurrentPlayer())));
// discard the second card
auto legal_actions = state->LegalActions();
state->ApplyAction(legal_actions.at(1));
SPIEL_CHECK_FALSE(AllActionsInOtherActions(
{legal_actions.at(1)}, state->PlayerCards(state->CurrentPlayer())));
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
void TalonExchangePhaseTest6() {
// 1 talon exchange, select the last set
auto state = StateAfterActions(
GameParameters(),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
auto talon_initial = state->TalonSets();
SPIEL_CHECK_EQ(talon_initial.size(), 6);
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 1, 2, 3, 4, 5}));
for (auto const& talon_set : talon_initial) {
SPIEL_CHECK_EQ(talon_set.size(), 1);
}
// select the last set
state->ApplyAction(5);
auto talon_end = state->TalonSets();
SPIEL_CHECK_EQ(talon_end.size(), 5);
for (int i = 0; i < 5; i++) {
SPIEL_CHECK_EQ(talon_initial.at(i), talon_end.at(i));
}
SPIEL_CHECK_TRUE(AllActionsInOtherActions(
talon_initial.at(5), state->PlayerCards(state->CurrentPlayer())));
// discard the first card
auto legal_actions = state->LegalActions();
state->ApplyAction(legal_actions.at(0));
SPIEL_CHECK_FALSE(AllActionsInOtherActions(
{legal_actions.at(0)}, state->PlayerCards(state->CurrentPlayer())));
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
void TalonExchangePhaseTest7() {
// check that taroks and kings cannot be exchanged
auto state =
StateAfterActions(GameParameters({{"rng_seed", GameParameter(42)}}),
{kDealCardsAction, kBidPassAction, kBidOneAction,
kBidPassAction, kBidOneAction, 1});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
// check taroks and kings are not in legal actions
for (auto const& action : state->LegalActions()) {
const Card& card = card_deck.at(action);
SPIEL_CHECK_TRUE(card.suit != CardSuit::kTaroks);
SPIEL_CHECK_NE(card.points, 5);
}
}
void TalonExchangePhaseTest8() {
// check that tarok can be exchanged if player has no other choice
auto state =
StateAfterActions(GameParameters({{"players", GameParameter(4)},
{"rng_seed", GameParameter(141750)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction,
kBidPassAction, kBidSoloTwoAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kSoloTwo);
// select first set from talon
state->ApplyAction(0);
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
// first the player must exchange non-tarok or non-king card
// check taroks and kings are not in legal actions
for (auto const& action : state->LegalActions()) {
const Card& card = card_deck.at(action);
SPIEL_CHECK_TRUE(card.suit != CardSuit::kTaroks);
SPIEL_CHECK_NE(card.points, 5);
}
state->ApplyAction(state->LegalActions().at(0));
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTalonExchange);
// at this point the player has only taroks and kings in his hand but still
// needs to exchange one card
// check only taroks (no trula or kings) are in legal actions
for (auto const& action : state->LegalActions()) {
const Card& card = card_deck.at(action);
SPIEL_CHECK_TRUE(card.suit == CardSuit::kTaroks);
SPIEL_CHECK_NE(card.points, 5);
}
state->ApplyAction(state->LegalActions().at(0));
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
}
// tricks playing phase tests
static inline const GameParameters kTricksPlayingGameParams = GameParameters(
{{"players", GameParameter(3)}, {"rng_seed", GameParameter(634317)}});
// the above "rng_seed" yields:
//
// player 0 cards:
// ('II', 1), ('IIII', 3), ('V', 4), ('VIII', 7), ('XI', 10), ('XIX', 18),
// ('Mond', 20), ('Jack of Hearts', 26), ('Knight of Hearts', 27), ('4 of
// Diamonds', 30), ('8 of Spades', 39), ('Jack of Spades', 42), ('King of
// Spades', 45), ('10 of Clubs', 49), ('Jack of Clubs', 50), ('Knight of Clubs',
// 51)
//
// player 1 cards:
// ('III', 2), ('VII', 6), ('XII', 11), ('XIII', 12), ('XIV', 13), ('XX', 19),
// ('Skis', 21), ('1 of Hearts', 25), ('3 of Diamonds', 31), ('Knight of
// Diamonds', 35), ('Queen of Diamonds', 36), ('King of Diamonds', 37), ('7 of
// Spades', 38), ('Knight of Spades', 43), ('8 of Clubs', 47), ('Queen of
// Clubs', 52)
//
// player 2 cards:
// ('Pagat', 0), ('VI', 5), ('IX', 8), ('X', 9), ('XV', 14), ('XVI', 15),
// ('XVII', 16), ('XVIII', 17), ('4 of Hearts', 22), ('2 of Diamonds', 32), ('1
// of Diamonds', 33), ('Jack of Diamonds', 34), ('9 of Spades', 40), ('10 of
// Spades', 41), ('9 of Clubs', 48), ('King of Clubs', 53)
void TricksPlayingPhaseTest1() {
// check forced pagat in klop
auto state = StateAfterActions(
kTricksPlayingGameParams,
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidKlopAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20, 26, 27,
30, 39, 42, 45, 49, 50, 51}));
state->ApplyAction(20);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {20}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {21}));
state->ApplyAction(21);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {20, 21}));
// pagat is forced
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0}));
state->ApplyAction(0);
// pagat won the trick
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
}
void TricksPlayingPhaseTest2() {
// check pagat not a legal action in klop when following and all taroks lower
auto state = StateAfterActions(
kTricksPlayingGameParams,
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidKlopAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20, 26, 27,
30, 39, 42, 45, 49, 50, 51}));
state->ApplyAction(18);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {18}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {19, 21}));
state->ApplyAction(21);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {18, 21}));
// pagat not available but all other taroks available
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {5, 8, 9, 14, 15, 16, 17}));
state->ApplyAction(17);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
}
void TricksPlayingPhaseTest3() {
// check pagat not a legal action in klop when opening
auto state = StateAfterActions(
kTricksPlayingGameParams,
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidKlopAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20, 26, 27,
30, 39, 42, 45, 49, 50, 51}));
state->ApplyAction(4);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {4}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {6, 11, 12, 13, 19, 21}));
state->ApplyAction(6);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {4, 6}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {8, 9, 14, 15, 16, 17}));
state->ApplyAction(8);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {5, 9, 14, 15, 16, 17, 22, 32,
33, 34, 40, 41, 48, 53}));
}
void TricksPlayingPhaseTest4() {
// check legal non-tarok cards in klop
auto state = StateAfterActions(
kTricksPlayingGameParams,
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidKlopAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20, 26, 27,
30, 39, 42, 45, 49, 50, 51}));
state->ApplyAction(42);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {42}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {43}));
state->ApplyAction(43);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {42, 43}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {40, 41}));
state->ApplyAction(41);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
}
void TricksPlayingPhaseTest5() {
// check scenarios where no card has to be beaten in klop
auto state = StateAfterActions(
kTricksPlayingGameParams,
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidKlopAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20, 26, 27,
30, 39, 42, 45, 49, 50, 51}));
state->ApplyAction(30);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {30}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {31, 35, 36, 37}));
state->ApplyAction(37);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {30, 37}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {32, 33, 34}));
state->ApplyAction(34);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {2, 6, 11, 12, 13, 19, 21, 25,
31, 35, 36, 38, 43, 47, 52}));
state->ApplyAction(52);
state->ApplyAction(53);
state->ApplyAction(51);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(),
{5, 8, 9, 14, 15, 16, 17, 22, 32, 33, 40, 41, 48}));
state->ApplyAction(32);
// can't follow suit, i.e. forced to play tarok
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {32}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20}));
state->ApplyAction(1);
// doesn't have to beat the opening card due to the second card being tarok
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {32, 1}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {31, 35, 36}));
state->ApplyAction(36);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
}
void TricksPlayingPhaseTest6() {
// check taroks don't win in colour valat
auto state = StateAfterActions(
kTricksPlayingGameParams,
{kDealCardsAction, kBidColourValatAction, kBidPassAction, kBidPassAction,
kBidColourValatAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(),
ContractName::kColourValatWithout);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(
AllEq(state->LegalActions(),
{2, 6, 11, 12, 13, 19, 21, 25, 31, 35, 36, 37, 38, 43, 47, 52}));
state->ApplyAction(35);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {35}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {32, 33, 34}));
state->ApplyAction(32);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {35, 32}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {30}));
state->ApplyAction(30);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {2, 6, 11, 12, 13, 19, 21, 25,
31, 36, 37, 38, 43, 47, 52}));
state->ApplyAction(37);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {37}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {33, 34}));
state->ApplyAction(33);
// can't follow suit, i.e. forced to play tarok
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {37, 33}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20}));
state->ApplyAction(1);
// tarok didn't win the trick
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
}
void TricksPlayingPhaseTest7() {
// check positive contracts scenarios
auto state =
StateAfterActions(kTricksPlayingGameParams,
{kDealCardsAction, kBidPassAction, kBidTwoAction,
kBidPassAction, kBidTwoAction, 0, 40, 41});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kTwo);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20, 26, 27,
30, 39, 42, 45, 49, 50, 51}));
state->ApplyAction(30);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {30}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {31, 35, 36, 37}));
state->ApplyAction(31);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {30, 31}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {32, 33, 34}));
state->ApplyAction(32);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {0, 5, 8, 9, 14, 15, 16, 17, 22,
24, 28, 33, 34, 48, 53}));
state->ApplyAction(33);
// can't follow suit, i.e. forced to play tarok
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {33}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {1, 3, 4, 7, 10, 18, 20}));
state->ApplyAction(18);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->TrickCards(), {33, 18}));
SPIEL_CHECK_TRUE(AllEq(state->LegalActions(), {35, 36, 37}));
state->ApplyAction(37);
// tarok won the trick
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(state->TrickCards().empty());
}
// captured mond tests
void CapturedMondTest1() {
// mond captured by skis
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(634317)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction, 0, 49});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
// play mond
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
state->ApplyAction(CardLongNameToAction("Mond"));
// play skis
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Skis"));
// play low tarok
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("VI"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {-20, 0, 0}));
}
void CapturedMondTest2() {
// mond captured by pagat (emperor trick)
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(634317)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction, 0, 49});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
// play mond
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
state->ApplyAction(CardLongNameToAction("Mond"));
// play skis
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Skis"));
// play pagat
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("Pagat"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {-20, 0, 0}));
}
void CapturedMondTest3() {
// mond taken from talon
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(497200)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction, 3, 49});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {0, 0, 0}));
}
void CapturedMondTest4() {
// mond left in talon
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(497200)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOneAction, 0, 49});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {-20, 0, 0}));
}
void CapturedMondTest5() {
// mond left in talon but won with a called king
auto state = StateAfterActions(
GameParameters(
{{"players", GameParameter(4)}, {"rng_seed", GameParameter(297029)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidPassAction,
kBidOneAction, kKingOfSpadesAction, 2, 49});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
// play the called king and win the trick
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {-20, 0, 0, 0}));
state->ApplyAction(CardLongNameToAction("King of Spades"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Queen of Spades"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("8 of Spades"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 3);
state->ApplyAction(CardLongNameToAction("7 of Spades"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {0, 0, 0, 0}));
}
void CapturedMondTest6() {
// mond captured by ally should also be penalized
auto state =
StateAfterActions(GameParameters({{"rng_seed", GameParameter(634317)}}),
{kDealCardsAction, kBidPassAction, kBidOneAction,
kBidPassAction, kBidOneAction, 0, 22});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOne);
// play mond
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
state->ApplyAction(CardLongNameToAction("Mond"));
// play skis
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Skis"));
// play low tarok
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("VI"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {-20, 0, 0}));
}
void CapturedMondTest7() {
// mond captured in klop should not be penalized
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(634317)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidKlopAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kKlop);
// play mond
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
state->ApplyAction(CardLongNameToAction("Mond"));
// play skis
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Skis"));
// play pagat
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("Pagat"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {0, 0, 0}));
}
void CapturedMondTest8() {
// mond captured in bagger should not be penalized
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(634317)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidBeggarAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kBeggar);
// play mond
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
state->ApplyAction(CardLongNameToAction("Mond"));
// play skis
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Skis"));
// play pagat
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("Pagat"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {0, 0, 0}));
}
void CapturedMondTest9() {
// mond captured in open bagger should not be penalized
auto state = StateAfterActions(
GameParameters({{"rng_seed", GameParameter(634317)}}),
{kDealCardsAction, kBidPassAction, kBidPassAction, kBidOpenBeggarAction});
SPIEL_CHECK_EQ(state->CurrentGamePhase(), GamePhase::kTricksPlaying);
SPIEL_CHECK_EQ(state->SelectedContractName(), ContractName::kOpenBeggar);
// play mond
SPIEL_CHECK_EQ(state->CurrentPlayer(), 0);
state->ApplyAction(CardLongNameToAction("Mond"));
// play skis
SPIEL_CHECK_EQ(state->CurrentPlayer(), 1);
state->ApplyAction(CardLongNameToAction("Skis"));
// play pagat
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
state->ApplyAction(CardLongNameToAction("Pagat"));
SPIEL_CHECK_EQ(state->CurrentPlayer(), 2);
SPIEL_CHECK_TRUE(AllEq(state->CapturedMondPenalties(), {0, 0, 0}));
}
} // namespace tarok
} // namespace open_spiel
int main(int argc, char** argv) {
open_spiel::tarok::BasicGameTests();
// cards tests
open_spiel::tarok::CardDeckShufflingSeedTest();
open_spiel::tarok::DealtCardsSizeTest(3);
open_spiel::tarok::DealtCardsSizeTest(4);
open_spiel::tarok::DealtCardsContentTest(3);
open_spiel::tarok::DealtCardsContentTest(4);
open_spiel::tarok::PlayersCardsSortedTest();
open_spiel::tarok::CountCardsTest();
open_spiel::tarok::CardDealingPhaseTest();
// bidding phase tests
open_spiel::tarok::BiddingPhase3PlayersTest1();
open_spiel::tarok::BiddingPhase3PlayersTest2();
open_spiel::tarok::BiddingPhase3PlayersTest3();
open_spiel::tarok::BiddingPhase3PlayersTest4();
open_spiel::tarok::BiddingPhase4PlayersTest1();
open_spiel::tarok::BiddingPhase4PlayersTest2();
open_spiel::tarok::BiddingPhase4PlayersTest3();
open_spiel::tarok::BiddingPhase4PlayersTest4();
open_spiel::tarok::BiddingPhase4PlayersTest5();
// talon exchange phase tests
open_spiel::tarok::TalonExchangePhaseTest1();
open_spiel::tarok::TalonExchangePhaseTest2();
open_spiel::tarok::TalonExchangePhaseTest3();
open_spiel::tarok::TalonExchangePhaseTest4();
open_spiel::tarok::TalonExchangePhaseTest5();
open_spiel::tarok::TalonExchangePhaseTest6();
open_spiel::tarok::TalonExchangePhaseTest7();
open_spiel::tarok::TalonExchangePhaseTest8();
// tricks playing phase tests
open_spiel::tarok::TricksPlayingPhaseTest1();
open_spiel::tarok::TricksPlayingPhaseTest2();
open_spiel::tarok::TricksPlayingPhaseTest3();
open_spiel::tarok::TricksPlayingPhaseTest4();
open_spiel::tarok::TricksPlayingPhaseTest5();
open_spiel::tarok::TricksPlayingPhaseTest6();
open_spiel::tarok::TricksPlayingPhaseTest7();
// captured mond tests
open_spiel::tarok::CapturedMondTest1();
open_spiel::tarok::CapturedMondTest2();
open_spiel::tarok::CapturedMondTest3();
open_spiel::tarok::CapturedMondTest4();
open_spiel::tarok::CapturedMondTest5();
open_spiel::tarok::CapturedMondTest6();
open_spiel::tarok::CapturedMondTest7();
open_spiel::tarok::CapturedMondTest8();
open_spiel::tarok::CapturedMondTest9();
}
| 40.718621 | 80 | 0.716134 | [
"vector"
] |
8a3bfab4557b727bba6276ec530efd4e6c73f50b | 572 | cpp | C++ | 2DGameEngine/src/rendering/shaders/GuiShader.cpp | pbeaulieu26/2DGameEngine | 898a7d92d91cd77b51bf71245e78dcc33e344bc5 | [
"Apache-2.0"
] | null | null | null | 2DGameEngine/src/rendering/shaders/GuiShader.cpp | pbeaulieu26/2DGameEngine | 898a7d92d91cd77b51bf71245e78dcc33e344bc5 | [
"Apache-2.0"
] | null | null | null | 2DGameEngine/src/rendering/shaders/GuiShader.cpp | pbeaulieu26/2DGameEngine | 898a7d92d91cd77b51bf71245e78dcc33e344bc5 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "GuiShader.h"
namespace
{
const char * vertexShaderFile = "res/shaders/guiVertexShader.txt";
const char * fragmentShaderFile = "res/shaders/guiFragmentShader.txt";
const std::vector<const GLchar *> attributes{ "position" };
}
GuiShader::GuiShader()
: ShaderProgram(vertexShaderFile, fragmentShaderFile, attributes)
{
m_locationTransformationMatrix = getUniformLocation("transformationMatrix");
}
void GuiShader::loadTransformationMatrix(const glm::mat4& matrix)
{
loadMatrix(m_locationTransformationMatrix, matrix);
}
| 26 | 80 | 0.758741 | [
"vector"
] |
8a3d308157c990bce3e8d9814a28b845fc10a048 | 218 | hpp | C++ | vector.hpp | cassiorenan/eve | 3795aa86cc42dfc94c446392db6e1eefa7b561cf | [
"MIT"
] | null | null | null | vector.hpp | cassiorenan/eve | 3795aa86cc42dfc94c446392db6e1eefa7b561cf | [
"MIT"
] | null | null | null | vector.hpp | cassiorenan/eve | 3795aa86cc42dfc94c446392db6e1eefa7b561cf | [
"MIT"
] | null | null | null | #ifndef EVE_VECTOR_HPP
#define EVE_VECTOR_HPP
#include "detail/vector.hpp"
#include "detail/structured_bindings.hpp"
#include "detail/operators.hpp"
namespace eve {
using detail::vector;
} // namespace eve
#endif
| 14.533333 | 41 | 0.770642 | [
"vector"
] |
8a43addeed02045cc9d09c49cc3b43462c222fe1 | 2,307 | cc | C++ | CondFormats/CSCObjects/test/stubs/CSCCrossTalkReadAnalyzer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 2 | 2020-10-26T18:40:32.000Z | 2021-04-10T16:33:25.000Z | CondFormats/CSCObjects/test/stubs/CSCCrossTalkReadAnalyzer.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 25 | 2016-06-24T20:55:32.000Z | 2022-02-01T19:24:45.000Z | CondFormats/CSCObjects/test/stubs/CSCCrossTalkReadAnalyzer.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 8 | 2016-03-25T07:17:43.000Z | 2021-07-08T17:11:21.000Z | /*----------------------------------------------------------------------
Toy EDProducers and EDProducts for testing purposes only.
----------------------------------------------------------------------*/
#include <stdexcept>
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include "FWCore/Framework/interface/global/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Utilities/interface/ESGetToken.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "CondFormats/CSCObjects/interface/CSCcrosstalk.h"
#include "CondFormats/DataRecord/interface/CSCcrosstalkRcd.h"
using namespace std;
namespace edmtest {
class CSCCrossTalkReadAnalyzer : public edm::global::EDAnalyzer<> {
public:
explicit CSCCrossTalkReadAnalyzer(edm::ParameterSet const& p) : crosstalkToken_{esConsumes()} {}
~CSCCrossTalkReadAnalyzer() override {}
void analyze(edm::StreamID, const edm::Event& e, const edm::EventSetup& c) const override;
private:
edm::ESGetToken<CSCcrosstalk, CSCcrosstalkRcd> crosstalkToken_;
};
void CSCCrossTalkReadAnalyzer::analyze(edm::StreamID, const edm::Event& e, const edm::EventSetup& context) const {
using namespace edm::eventsetup;
// Context is not used.
edm::LogSystem log("CSCCrossTalk");
log << " I AM IN RUN NUMBER " << e.id().run() << std::endl;
log << " ---EVENT NUMBER " << e.id().event() << std::endl;
const CSCcrosstalk* mycrosstalk = &context.getData(crosstalkToken_);
std::map<int, std::vector<CSCcrosstalk::Item> >::const_iterator it;
for (it = mycrosstalk->crosstalk.begin(); it != mycrosstalk->crosstalk.end(); ++it) {
log << "layer id found " << it->first << std::endl;
std::vector<CSCcrosstalk::Item>::const_iterator crosstalkit;
for (crosstalkit = it->second.begin(); crosstalkit != it->second.end(); ++crosstalkit) {
log << " crosstalk_slope_right: " << crosstalkit->xtalk_slope_right
<< " crosstalk_intercept_right: " << crosstalkit->xtalk_intercept_right << std::endl;
}
}
}
DEFINE_FWK_MODULE(CSCCrossTalkReadAnalyzer);
} // namespace edmtest
| 39.775862 | 116 | 0.671001 | [
"vector"
] |
8a4504746343bd42933e196aee1e1ced9d32d765 | 2,080 | cc | C++ | cpp/703_Kth_Largest_Element_in_a_Stream/kthLargestElementInAStream2.cc | JetChars/leetcode | 3014d694fecf9ed0bd5881d21319bf0f04b69f12 | [
"MIT"
] | null | null | null | cpp/703_Kth_Largest_Element_in_a_Stream/kthLargestElementInAStream2.cc | JetChars/leetcode | 3014d694fecf9ed0bd5881d21319bf0f04b69f12 | [
"MIT"
] | null | null | null | cpp/703_Kth_Largest_Element_in_a_Stream/kthLargestElementInAStream2.cc | JetChars/leetcode | 3014d694fecf9ed0bd5881d21319bf0f04b69f12 | [
"MIT"
] | null | null | null | // C/C++ File
// AUTHOR: jetchars
// FILE: cpp/703_Kth_Largest_Element_in_a_Stream/kthLargestElementInAStream.cc
// ROLE: TODO (some explanation)
// CREATED: 2018-12-23 00:01:56
// MODIFIED: 2018-12-23 02:35:58
/*
Design a class to find the kth largest element in a stream. Note that it is the
kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an
integer array nums, which contains initial elements from the stream. For each
call to the method KthLargest.add, return the element representing the kth
largest element in the stream.
Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums' length ≥ k-1 and k ≥ 1.
*/
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
bool cmp(const int &a, const int &b) { return a > b; }
class KthLargest {
public:
priority_queue<int, vector<int>, greater<int>> pq;
int size;
KthLargest(int k, vector<int> nums) {
size = k;
for (int i = 0; i < nums.size(); i++) {
pq.push(nums[i]);
if (pq.size() > k)
pq.pop();
}
}
int add(int val) {
pq.push(val);
if (pq.size() > size)
pq.pop();
return pq.top();
}
}; // namespace stdclassKthLargest
int main() {
int k = 3;
vector<int> arr{4, 5, 8, 2};
KthLargest *kthLargest = new KthLargest(k, arr);
int input[]{3, 5, 10, 9, 4};
for (auto j : input) {
cout << "input: " << j << endl;
/* cout << "current heap: "; */
/* for (auto i : kthLargest->heap) */
/* cout << i << ' '; */
/* cout << endl; */
cout << "evict: " << kthLargest->add(j) << endl; // returns 4
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
| 26.329114 | 79 | 0.632692 | [
"object",
"vector"
] |
8a4a87c682e456280f584dfe766384d3321c1781 | 12,438 | cpp | C++ | main.cpp | Patryk707/Projekt_Patryk_Kaczmarek | f356359792b12a8418f7d29aa2bb6aba3587c3ef | [
"MIT"
] | null | null | null | main.cpp | Patryk707/Projekt_Patryk_Kaczmarek | f356359792b12a8418f7d29aa2bb6aba3587c3ef | [
"MIT"
] | null | null | null | main.cpp | Patryk707/Projekt_Patryk_Kaczmarek | f356359792b12a8418f7d29aa2bb6aba3587c3ef | [
"MIT"
] | null | null | null | #include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "bohater.h"
#include "przeciwnik.h"
#include "pocisk.h"
#include <vector>
using namespace std;
using namespace sf;
vector<Pocisk> Pocisk::wystrzelone_pociski;
vector<Pocisk> Pocisk::wrogie_pociski;
Texture loadtexture(const string &filename_with_path){
Texture texture;
if(!texture.loadFromFile(filename_with_path)){
cerr<<"Could not load texture"<<endl;
}
return texture;
}
void tworzenie_scian(vector<unique_ptr<Sprite>> &otoczenie, Texture &sciana_tekstura,Texture &blok_tekstura,RenderWindow &window, Bohater &postac){
auto block0=make_unique<Sprite>();
block0->setTexture(blok_tekstura);
block0->setPosition(0,window.getSize().y-50);
block0->setTextureRect(IntRect(0,0,window.getSize().x,50));
otoczenie.emplace_back(move(block0));
auto block1=make_unique<Sprite>();
block1->setTexture(blok_tekstura);
block1->setPosition(150,window.getSize().y-50-postac.getGlobalBounds().height);
block1->setScale(0.5,0.43);
otoczenie.emplace_back(move(block1));
auto block2=make_unique<Sprite>();
block2->setTexture(blok_tekstura);
block2->setPosition(214,window.getSize().y-50-2*postac.getGlobalBounds().height);
block2->setScale(0.5,0.86);
otoczenie.emplace_back(move(block2));
auto wall2=make_unique<Sprite>();
wall2->setTexture(sciana_tekstura);
wall2->setPosition(385,window.getSize().y-152);
wall2->setScale(3,0.2);
otoczenie.emplace_back(move(wall2));
auto block3=make_unique<Sprite>();
block3->setTexture(blok_tekstura);
block3->setPosition(window.getSize().x/2+200,window.getSize().y-50-1*postac.getGlobalBounds().height);
block3->setScale(0.5,0.43);
otoczenie.emplace_back(move(block3));
auto block4=make_unique<Sprite>();
block4->setTexture(blok_tekstura);
block4->setPosition(window.getSize().x/2+264,window.getSize().y-50-2*postac.getGlobalBounds().height);
block4->setScale(2.5,0.86);
otoczenie.emplace_back(move(block4));
auto block5=make_unique<Sprite>();
block5->setTexture(blok_tekstura);
block5->setPosition(window.getSize().x/2+584,window.getSize().y-50-3*postac.getGlobalBounds().height);
block5->setScale(2,1.29);
otoczenie.emplace_back(move(block5));
auto wall3=make_unique<Sprite>();
wall3->setTexture(sciana_tekstura);
wall3->setScale(1.75,0.2);
wall3->setPosition(window.getSize().x/2+264,window.getSize().y-50-3*postac.getGlobalBounds().height-30);
otoczenie.emplace_back(move(wall3));
auto block6=make_unique<Sprite>();
block6->setTexture(blok_tekstura);
block6->setPosition(window.getSize().x/2-210,window.getSize().y-80-3*postac.getGlobalBounds().height);
block6->setTextureRect(IntRect(0,0,128,64));
block6->setScale(2.8,0.5);
otoczenie.emplace_back(move(block6));
auto block7=make_unique<Sprite>();
block7->setTexture(blok_tekstura);
block7->setPosition(window.getSize().x/2-594,window.getSize().y-80-4*postac.getGlobalBounds().height);
//block7->setTextureRect(IntRect(0,0,128,64));
block7->setScale(3,0.43);
otoczenie.emplace_back(move(block7));
}
int main()
{
RenderWindow window(VideoMode(1600,900 ),"Projekt");
window.setFramerateLimit(60);
Event event;
//Texture platformy_tekstura=loadtexture("./../Projekt_proba1/Environment/ground_grass_small.png");
//platformy_tekstura.setRepeated(true);
Texture bohater_tekstura=loadtexture("./../Projekt_proba2/john_static.png");
Texture sciana_tekstura=loadtexture("./../Projekt_proba2/grass.png");
Texture blok_tekstura=loadtexture("./../Projekt_proba2/grassMid.png");
Texture przeciwnik_tekstura=loadtexture("./../Projekt_proba2/grunt.png");
sciana_tekstura.setRepeated(true);
blok_tekstura.setRepeated(true);
vector<unique_ptr<Sprite>> otoczenie;
//postac
Vector2f position(50, window.getSize().y-80);
Bohater postac(position);
postac.setScale(2.5,2.5);
postac.setOrigin(float(bohater_tekstura.getSize().x) / 2, float(bohater_tekstura.getSize().y) / 2);
postac.setTexture(bohater_tekstura);
postac.setBounds(0, window.getSize().x, 0, window.getSize().y);
postac.setSpeed(200, 200);
//walls
tworzenie_scian(otoczenie,sciana_tekstura,blok_tekstura,window, postac);
//przeciwnik
//vector<unique_ptr<Sprite>> przeciwnicy;
//auto przeciwnik1=make_unique<Przeciwnik>(Vector2f(0.4,0.4));
//przeciwnik1->setTexture(przeciwnik_tekstura);
//przeciwnik1->set_position(Vector2f(1000,500));
//przeciwnicy.emplace_back(move(przeciwnik1));
//auto przeciwnik2=make_unique<Przeciwnik>(Vector2f(0.4,0.4));
//przeciwnik2->setTexture(przeciwnik_tekstura);
//przeciwnik2->set_position(Vector2f(500,500));
//przeciwnicy.emplace_back(move(przeciwnik2));
// auto przeciwnik3=make_unique<Przeciwnik>(Vector2f(0.4,0.4));
//przeciwnik3->setTexture(przeciwnik_tekstura);
//przeciwnik3->set_position(Vector2f(800,500));
//przeciwnicy.emplace_back(move(przeciwnik3));
//----------------
vector<Przeciwnik> enemies;
Przeciwnik enemy1(Vector2f(-2.5,2.5));
enemy1.setTexture(przeciwnik_tekstura);
enemy1.set_position(Vector2f(400,window.getSize().y-80));
enemy1.setOrigin(float(przeciwnik_tekstura.getSize().x) / 2, float(przeciwnik_tekstura.getSize().y) / 2);
enemy1.shot_cooldown.restart();
enemy1.setBounds(280,window.getSize().x/2+200);
enemies.emplace_back(enemy1);
Przeciwnik enemy2(Vector2f(-2.5,2.5));
enemy2.setTexture(przeciwnik_tekstura);
enemy2.set_position(Vector2f(700,window.getSize().y-80));
enemy2.setOrigin(float(przeciwnik_tekstura.getSize().x) / 2, float(przeciwnik_tekstura.getSize().y) / 2);
enemy2.shot_cooldown.restart();
enemy2.setBounds(280,window.getSize().x/2+200);
enemies.emplace_back(enemy2);
Przeciwnik enemy3(Vector2f(-2.5,2.5));
enemy3.setTexture(przeciwnik_tekstura);
enemy3.set_position(Vector2f(400,window.getSize().y-178));
enemy3.setOrigin(float(przeciwnik_tekstura.getSize().x) / 2, float(przeciwnik_tekstura.getSize().y) / 2);
enemy3.shot_cooldown.restart();
enemy3.setBounds(385,769);
enemies.emplace_back(enemy3);
Przeciwnik enemy4(Vector2f(-2.5,2.5));
enemy4.setTexture(przeciwnik_tekstura);
enemy4.set_position(Vector2f(window.getSize().x/2+300,window.getSize().y-76-2*postac.getGlobalBounds().height));
enemy4.setOrigin(float(przeciwnik_tekstura.getSize().x) / 2, float(przeciwnik_tekstura.getSize().y) / 2);
enemy4.shot_cooldown.restart();
enemy4.setBounds(window.getSize().x/2+264,window.getSize().x/2+584);
enemies.emplace_back(enemy4);
Przeciwnik enemy5(Vector2f(-2.5,2.5));
enemy5.setTexture(przeciwnik_tekstura);
enemy5.set_position(Vector2f(window.getSize().x/2,627));
enemy5.setOrigin(float(przeciwnik_tekstura.getSize().x) / 2, float(przeciwnik_tekstura.getSize().y) / 2);
enemy5.shot_cooldown.restart();
enemy5.setBounds(window.getSize().x/2-210,window.getSize().x/2+150);
enemies.emplace_back(enemy5);
//pocisk
bool wystrzelony=false;
Clock clock;
Clock shot_cooldown;
shot_cooldown.restart();
srand(time(NULL));
while(window.isOpen()){
Time elapsed = clock.restart();
window.clear(Color::Black);
window.pollEvent(event);
if(event.type==Event::Closed){
window.close();
break;
}
if(Event::KeyReleased){
postac.is_jumping=false;
}
//wystrzeliwanie pociskow
if (!wystrzelony and Keyboard::isKeyPressed(Keyboard::Space)
and shot_cooldown.getElapsedTime().asSeconds() >= 1) {
postac.shoot();
shot_cooldown.restart();
wystrzelony = true;
} else if (wystrzelony and !Keyboard::isKeyPressed(Keyboard::Space)) {
wystrzelony = false;
}
// for(auto &enemy : enemies){
// if (!enemy.wrogi_wystrzelony and enemy.shot_cooldown.getElapsedTime().asSeconds() >= 1) {
// enemy.shoot();
// enemy.shot_cooldown.restart();
// enemy.wrogi_wystrzelony = true;
// } else if (enemy.wrogi_wystrzelony) {
// enemy.wrogi_wystrzelony = false;
// }
//}
//wystrzeliwanie pociskow
for (auto& wystrzelony_pocisk : Pocisk::wystrzelone_pociski) {
window.draw(wystrzelony_pocisk);
wystrzelony_pocisk.set_speed(wystrzelony_pocisk.getFacing() ? 3 : -3);
}
for (auto& wrogi_pocisk : Pocisk::wrogie_pociski) {
window.draw(wrogi_pocisk);
wrogi_pocisk.set_speed(wrogi_pocisk.getFacing() ? 3 : -3);
}
//otoczenie a pociski
for(auto &wystrzelony_pocisk : Pocisk::wystrzelone_pociski){
for(auto &sciana : otoczenie){
if(wystrzelony_pocisk.check_collision(*sciana)){
wystrzelony_pocisk.set_position(Vector2f(10000,10000));
}
}
}
for(auto &wystrzelony_pocisk : Pocisk::wrogie_pociski){
for(auto &sciana : otoczenie){
if(wystrzelony_pocisk.check_collision(*sciana)){
wystrzelony_pocisk.set_position(Vector2f(10000,10000));
}
}
}
//przeciwnik a pocisk
for(auto &wystrzelony_pocisk : Pocisk::wystrzelone_pociski){
for(auto i=0; i<enemies.size(); i++){
if(wystrzelony_pocisk.check_collision(enemies[i])){
//wystrzelony_pocisk.Pocisk::~Pocisk();
wystrzelony_pocisk.set_position(Vector2f(10000,10000));
enemies[i].set_lives(-1);
if(!enemies[i].is_alive()){
enemies[i].set_position(Vector2f(10000,10000));
}
}
}
}
//bohater a pocisk
for(auto &wystrzelony_pocisk : Pocisk::wrogie_pociski){
if(wystrzelony_pocisk.check_collision(postac)){
wystrzelony_pocisk.set_position(Vector2f(10000,10000));
postac.set_lives(-1);
if(!postac.is_alive()){
postac.move(10000,10000);
}
}
}
//enemy animation
for(auto &enemy : enemies){
if(postac.getGlobalBounds().left>enemy.left_borderline and
postac.getGlobalBounds().left+postac.getGlobalBounds().width<enemy.right_borderline and
postac.getGlobalBounds().top>enemy.getGlobalBounds().top-enemy.getGlobalBounds().height and
postac.getGlobalBounds().top+postac.getGlobalBounds().height<enemy.getGlobalBounds().top+2*enemy.getGlobalBounds().height){
if(postac.getGlobalBounds().left<enemy.getGlobalBounds().left){
enemy.setScale(-2.5,2.5);
enemy.setFacing(false);
}
if(postac.getGlobalBounds().left>enemy.getGlobalBounds().left){
enemy.setScale(2.5,2.5);
enemy.setFacing(true);
}
if (!enemy.wrogi_wystrzelony and enemy.shot_cooldown.getElapsedTime().asSeconds() >= 1) {
enemy.shoot();
enemy.shot_cooldown.restart();
enemy.wrogi_wystrzelony = true;
} else if (enemy.wrogi_wystrzelony) {
enemy.wrogi_wystrzelony = false;
}
}
else{
enemy.animate(elapsed);
}
}
//collision postac
postac.collision(otoczenie,elapsed);
//if(postac.check_collision(otoczenie)){
//cout<<"Kolizja!";
//cout<<postac.getGlobalBounds().left;
//cout<<postac.getGlobalBounds().top;
//}
//drawing
for(const auto &ksztalty:otoczenie){
window.draw(*ksztalty);
}
//for(const auto &przeciwnik:przeciwnicy){
// window.draw(*przeciwnik);
//}
for(auto &enemy : enemies){
window.draw(enemy);
}
//window.draw(enemy1);
window.draw(postac);
window.display();
}
return 0;
}
| 36.690265 | 147 | 0.638447 | [
"vector"
] |
8a4e3e1ee6d982ab92d3aaf1e486c057bae579cd | 2,155 | hpp | C++ | include/csutil.hpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | include/csutil.hpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | include/csutil.hpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | /**
* \file csutil.hpp
* \brief Utility class - helper computations for CS
*
*/
#pragma once
#include <TFile.h>
#include <TTree.h>
#include <TVector3.h>
#include <TMath.h>
#include "consts.hpp"
#include "common.hpp"
#include "elacuts.hpp"
#include "commonalg.hpp"
#include "solidangle.hpp"
#include "scattyield.hpp"
namespace s13 {
namespace ana {
/*
Makes interpolator for conversion of lab angle to CM.
*/
TInterpPtr make_lab2cm_angle_interp(DatasetType ds_type);
// DEPRECATED: those angle conversion functions are deprecated as
// they use nonrelativistic conversion formulas
// use make_lab2_cm_angle_interp() instead
/*
Convert theta2 angle lab to theta CM.
*/
// Double_t lab_theta_angle_to_cm(Double_t theta_lab);
/*
Converts theta CM to theta2 lab.
*/
// Double_t cm_theta_angle_to_lab(Double_t theta_cm);
/*
Convert solid angle from lab to CM.
*/
double lab2cm_solid_angle_factor(double proton_cm_theta_rad,
DatasetType ds_type);
/*
Converts yield from lab to center of mass frame.
*/
ScatteringYield lab_yield_to_cm(const ScatteringYield& lab_yield,
DatasetType ds_type);
/*
Converts CS from lab to center of mass frame.
*/
ScatteringYield lab_cs_to_cm(const ScatteringYield& lab_cs,
DatasetType ds_type);
/*
Computes cross section values from passed elastic scattering yields
and experimental parameters. Essentialy it just converts
counts into mbarns.
Params:
solid_angle: SolidAngle interface implementationwhich will return
solid angle for the bin.
num_beam_incident: Number of incident beam particles.
tgt_areal_density: Target density [cm-2]
Returns: ScatteringYield object containing yields in mbarn units.
*/
ScatteringYield
cs_from_yields(ScatteringYield& yields,
SolidAngle& solid_angle,
double num_beam_incident,
double tgt_areal_density);
}
}
| 26.9375 | 73 | 0.6529 | [
"object",
"solid"
] |
8a50ff73ec64b9ce80058ce2159394203ac70792 | 2,775 | cc | C++ | src/operator/sequence_last.cc | viper7882/mxnet_win32 | 8b05c0cf83026147efd70a21abb3ac25ca6099f1 | [
"Apache-2.0"
] | 7 | 2017-08-04T07:10:22.000Z | 2020-07-02T13:01:28.000Z | src/operator/sequence_last.cc | yanghaojin/BMXNet | 102f8d0ed59529bbd162c37bf07ae58ad6c4caa1 | [
"Apache-2.0"
] | null | null | null | src/operator/sequence_last.cc | yanghaojin/BMXNet | 102f8d0ed59529bbd162c37bf07ae58ad6c4caa1 | [
"Apache-2.0"
] | 11 | 2018-02-27T15:32:09.000Z | 2021-04-21T08:48:17.000Z | /*!
* Copyright (c) 2015 by Contributors
* \file sequence_last.cc
* \brief
* \author Sebastian Bodenstein
*/
#include "./sequence_last-inl.h"
namespace mxnet {
namespace op {
template <>
Operator *CreateOp<cpu>(SequenceLastParam param, int dtype) {
Operator *op = NULL;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType,
{ op = new SequenceLastOp<cpu, DType>(param); })
return op;
}
// DO_BIND_DISPATCH comes from operator_common.h
Operator *SequenceLastProp::CreateOperatorEx(Context ctx,
std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}
DMLC_REGISTER_PARAMETER(SequenceLastParam);
MXNET_REGISTER_OP_PROPERTY(SequenceLast, SequenceLastProp)
.describe(R"code(Takes the last element of a sequence.
This function takes an n-dimensional input array of the form
[max_sequence_length, batch_size, other_feature_dims] and returns a (n-1)-dimensional array
of the form [batch_size, other_feature_dims].
Parameter `sequence_length` is used to handle variable-length sequences. `sequence_length` should be
an input array of positive ints of dimension [batch_size]. To use this parameter,
set `use_sequence_length` to `True`, otherwise each example in the batch is assumed
to have the max sequence length.
.. note:: Alternatively, you can also use `take` operator.
Example::
x = [[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]],
[[ 10., 11., 12.],
[ 13., 14., 15.],
[ 16., 17., 18.]],
[[ 19., 20., 21.],
[ 22., 23., 24.],
[ 25., 26., 27.]]]
// returns last sequence when sequence_length parameter is not used
SequenceLast(x) = [[ 19., 20., 21.],
[ 22., 23., 24.],
[ 25., 26., 27.]]
// sequence_length y is used
SequenceLast(x, y=[1,1,1], use_sequence_length=True) =
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]]
// sequence_length y is used
SequenceLast(x, y=[1,2,3], use_sequence_length=True) =
[[ 1., 2., 3.],
[ 13., 14., 15.],
[ 25., 26., 27.]]
)code" ADD_FILELINE)
.add_argument("data", "NDArray-or-Symbol",
"n-dimensional input array of the form [max_sequence_length,"
" batch_size, other_feature_dims] where n>2")
.add_argument("sequence_length", "NDArray-or-Symbol",
"vector of sequence lengths of the form [batch_size]")
.add_arguments(SequenceLastParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 33.433735 | 100 | 0.576577 | [
"vector"
] |
8a5212daa9f81997e00ad290eccbf105d3d8a64f | 5,859 | cpp | C++ | src/demo/demo_animation.cpp | sophia-x/RayTracing | 1092971b08ff17e8642e408e2cb0c518d6591e2b | [
"MIT"
] | 1 | 2016-05-05T10:20:45.000Z | 2016-05-05T10:20:45.000Z | src/demo/demo_animation.cpp | sophia-x/RayTracing | 1092971b08ff17e8642e408e2cb0c518d6591e2b | [
"MIT"
] | null | null | null | src/demo/demo_animation.cpp | sophia-x/RayTracing | 1092971b08ff17e8642e408e2cb0c518d6591e2b | [
"MIT"
] | null | null | null | #include "demo.hpp"
#define __FPS__ 12
const static mat4 I = mat4(1);
class KnotSpirit: public Spirit {
private:
Mesh *__knot;
mat4 __base;
float __rotate_speed;
float __min_scale, __max_scale;
float __scale_speed;
float __scale;
public:
KnotSpirit(Mesh *knot, const vec3 &position, float size): __knot(knot), __base(translate(position) * scale(vec3(size))) {
__rotate_speed = PI / 2;
__scale = __min_scale = 0.5; __max_scale = 1.5;
__scale_speed = 0.3;
}
void update(size_t idx, size_t FPS) {
if (__scale > __max_scale || __scale < __min_scale) {
__scale_speed *= -1;
}
__scale += __scale_speed / FPS;
__knot->transform(__base * scale(vec3(__scale)) * rotate((__rotate_speed * idx) / FPS, vec3(1, 1, 1)));
}
};
class SetSpirit: public Spirit {
private:
ModelSet *__set;
float __rotate_speed1, __rotate_speed2, __rotate_speed3;
public:
SetSpirit(ModelSet *set): __set(set) {
__rotate_speed1 = PI / 2;
__rotate_speed2 = PI / 1.5;
__rotate_speed3 = PI / 4;
}
void update(size_t idx, size_t FPS) {
__set->setMat(0, rotate((__rotate_speed1 * idx) / FPS, vec3(1, 0, 0))*translate(vec3(0, 1.2, 0))*scale(vec3(0.25)));
__set->setMat(1, rotate((__rotate_speed2 * idx) / FPS, vec3(0, 1, 0))*translate(vec3(1.5, 0, 0))*scale(vec3(0.35)));
__set->setMat(2, rotate((__rotate_speed3 * idx) / FPS, vec3(0, 1, 0))*scale(vec3(0.5)));
__set->transform(translate(vec3(0.5, 0.5, -4)));
}
};
class PointLightSpirit : public Spirit {
private:
PointLight *__light;
float __rotate_speed;
public:
PointLightSpirit(PointLight *light): __light(light) {
__rotate_speed = PI / 8;
}
void update(size_t idx, size_t FPS) {
__light->transform(rotate((__rotate_speed * idx) / FPS, vec3(0, 0, -1))*translate(vec3(-5, 0, 0))*scale(vec3(0.01)));
}
};
void scene_animation(const char *file_name, size_t width, float radio) {
/*************************Init Scene**********************/
Scene scene(vec3(0), 5);
/*************************Add textures**********************/
Texture *chess_board = new Texture("textures/chess_board.jpg");
Texture *mountain = new Texture("textures/mountain.jpg");
Texture *planet = new Texture("textures/planet.jpg");
scene.addTexture(chess_board);
scene.addTexture(mountain);
scene.addTexture(planet);
/*************************Spirits vector**********************/
vector<Spirit *> spirits;
/*************************Add models & Spirits**********************/
// background plane
scene.addModel(Plane (vec3(13, 10, -15), vec3(-13, 10, -15), vec3(-13, -7.4, -15), vec3(13, -7.4, -15),
vec2(1.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0),
Material(mountain, 1, 1, vec3(1.0), 0.5, 0.0, 00, 0.0, 0.0, 0.0, 0.00)));
// ground plane
scene.addModel(Plane (vec3(13, -2, -13), vec3(-13, -2, -13), vec3(-13, -2, 0), vec3(13, -2, 0),
vec2(1.0, 0.0), vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0),
Material(chess_board, 1.0, 1.0, vec3(1.0), 0.5, 0.0, 00, 0.0, 0.0, 0.0, 0.00)));
// Spheres
SphereModel *sphere1 = new SphereModel(Material(vec3(0.0, 1.0, 0.0), 0.1, 0.0, 00, 0.7, 0.0, 0.0, 0.00));
SphereModel *sphere2 = new SphereModel(Material(vec3(1.0, 1.0, 1.0), 0.0, 0.0, 00, 0.0, 1.0, 1.3, 0.00));
SphereModel *center = new SphereModel(Material(planet, 1.0, 1.0, vec3(1.0, 1.0, 1.0), 0.8, 0.2, 20, 0.0, 0.0, 0.0, 0.00));
vector<Model *> models = {sphere1, sphere2, center};
vector<mat4> mats = {I, I, I};
ModelSet *set = new ModelSet(models, mats);
scene.addModel(set);
spirits.push_back(new SetSpirit(set));
//OBJ
Mesh *knot = new Mesh("objs/knot.3DS", Material(vec3(1.0, 0.0, 0.0), 0.5, 0.5, 20, 0.0, 0.0, 0.0, 0.00));
scene.addModel(knot);
spirits.push_back(new KnotSpirit(knot, vec3(-1, 0, -2.5), 0.5));
/*************************Add Light**********************/
// Point Light
PointLight *p_light = new PointLight(vec3(1.5));
scene.addLight(p_light);
spirits.push_back(new PointLightSpirit(p_light));
// AreaLight
scene.addLight(new AreaLight(vec3(0, 5, -4), 1, 1, vec3(0.35)));
/*************************Init camera**********************/
// PinHoleCamera
// PinHoleCamera camera(vec3(0, 0, 0), vec3(0, 0, -1), vec3(0, 1, 0), radians(60.0f), radio);
// DepthCamera
DepthCamera camera(vec3(0, 0, 0), vec3(0, 0, -1), vec3(0, 1, 0), radians(60.0f), radio);
camera.setScene(&scene);
/*************************Init VideoWriter*********************/
VideoWriter writer(file_name, CV_FOURCC('m', 'p', '4', 'v'), __FPS__, Size(width, camera.getHeight(width)));
/*************************Animation generation**********************/
float f = 1000;
float f_s = 1.1;
for (size_t i = 0; i < __FPS__ * 10; i++) {
cout << "*******************************************************************" << endl;
cout << "Frame " << i << endl;
auto begin = chrono::system_clock::now();
/*************************Update spirits' states**********************/
for (auto it = spirits.begin(); it != spirits.end(); it++)
(*it)->update(i, __FPS__);
/*************************Init k-d tree**********************/
scene.buildWorld();
/*************************Start rendering**********************/
// DepthCamera
Mat result(camera.getHeight(width), width, CV_32FC3);
{
float min_f = 1, max_f = 1000;
if (f > max_f || f < min_f)
f_s = 1.0 / f_s;
f /= f_s;
camera.render(result, f, 4, 16, 16);
// camera.render(result, 4);
}
auto end = chrono::system_clock::now();
std::chrono::duration<double> dur = end - begin;
cout << "Frame " << i << " generation time:" << dur.count() << " s" << endl;
/*************************Write & Show**************************/
imshow("Animation", result);
waitKey(1);
writer << result;
}
for (auto it = spirits.begin(); it != spirits.end(); it++)
delete (*it);
} | 34.263158 | 123 | 0.560335 | [
"mesh",
"render",
"vector",
"model",
"transform"
] |
a442dc4f4cf876823b76670f7f9b09d0b8bc3a49 | 2,442 | cpp | C++ | Void/NaturalLanguageProcessing/PartOfSpeech/VPartOfSpeech.cpp | bekdepo/Void | ef41b044724db75438b9697a788665b9938f6a9a | [
"MIT"
] | 2 | 2021-05-29T11:07:15.000Z | 2021-08-05T03:11:57.000Z | Void/NaturalLanguageProcessing/PartOfSpeech/VPartOfSpeech.cpp | bekdepo/Void | ef41b044724db75438b9697a788665b9938f6a9a | [
"MIT"
] | null | null | null | Void/NaturalLanguageProcessing/PartOfSpeech/VPartOfSpeech.cpp | bekdepo/Void | ef41b044724db75438b9697a788665b9938f6a9a | [
"MIT"
] | 1 | 2021-05-29T11:07:16.000Z | 2021-05-29T11:07:16.000Z | #include "VPartOfSpeech.h"
#include "../../Utility/String/VString.h"
#include <algorithm>
//----------------------------------------------------------------------------------------------------
namespace Void
{
// VCorpusGameSkill
//----------------------------------------------------------------------------------------------------
VPartOfSpeechMapper::VPartOfSpeechMapper()
{
Initialize();
}
//----------------------------------------------------------------------------------------------------
VPartOfSpeechMapper::VPartOfSpeechMapper(const VPartOfSpeechMapper& _mapper)
:
mMapper(_mapper.mMapper)
{
}
//----------------------------------------------------------------------------------------------------
VPartOfSpeechMapper::~VPartOfSpeechMapper()
{
}
//----------------------------------------------------------------------------------------------------
VPartOfSpeech VPartOfSpeechMapper::PartOfSpeech(std::string _string)
{
std::transform(_string.begin(), _string.end(), _string.begin(), ::tolower);
_string = Replace(_string, std::regex("[^a-z]"), "");
auto it = mMapper.find(_string);
if (it != mMapper.end())
{
return it->second;
}
return VPartOfSpeech::None;
}
//----------------------------------------------------------------------------------------------------
void VPartOfSpeechMapper::Initialize()
{
mMapper["n"] = VPartOfSpeech::Noun;
mMapper["pron"] = VPartOfSpeech::Pronoun;
mMapper["adj"] = VPartOfSpeech::Adjective;
mMapper["v"] = VPartOfSpeech::Verb;
mMapper["ad"] = VPartOfSpeech::Adverb;
mMapper["prep"] = VPartOfSpeech::Preposition;
mMapper["conj"] = VPartOfSpeech::Conjunction;
mMapper["int"] = VPartOfSpeech::Interjection;
mMapper["art"] = VPartOfSpeech::Article;
mMapper["num"] = VPartOfSpeech::Numeral;
}
// Test
//----------------------------------------------------------------------------------------------------
void VPartOfSpeechTest()
{
VPartOfSpeechMapper mapper = VPartOfSpeechMapper();
auto test = mapper.PartOfSpeech("n");
test = mapper.PartOfSpeech("V");
test = mapper.PartOfSpeech("!@num.!@");
test = mapper.PartOfSpeech("");
return;
}
}
| 35.391304 | 106 | 0.4095 | [
"transform"
] |
a451c28184fc0e85c940775a09975715708a6147 | 1,459 | cpp | C++ | codeforces/F - Controversial Rounds/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/F - Controversial Rounds/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/F - Controversial Rounds/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Aug/17/2020 19:19
* solution_verdict: Accepted language: GNU C++17
* run_time: 888 ms memory_used: 17900 KB
* problem: https://codeforces.com/contest/1398/problem/F
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int a[N+2],b[N+2],la[N+2],lb[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;string s;cin>>s;s="#"+s;
for(int i=1;i<=n;i++)
{
a[i]=a[i-1]+(s[i]=='0');
b[i]=b[i-1]+(s[i]=='1');
la[i]=la[i-1];if(s[i]=='0')la[i]=i;
lb[i]=lb[i-1];if(s[i]=='1')lb[i]=i;
}
for(int d=1;d<=n;d++)
{
int cnt=0,p=0;
while(true)
{
if(p+d>n)break;
if(a[p+d]-a[p]==0||b[p+d]-b[p]==0)cnt++,p+=d;
else p=min(la[p+d],lb[p+d]);
}
cout<<cnt<<" ";
}
cout<<endl;
return 0;
} | 28.607843 | 111 | 0.441398 | [
"vector"
] |
a459d9e4d86fb17675b739015fdb6162f3bfa79b | 4,147 | cpp | C++ | enduser/netmeeting/ulsldap/spstdatt.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/netmeeting/ulsldap/spstdatt.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/netmeeting/ulsldap/spstdatt.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /* ----------------------------------------------------------------------
Module: ULS.DLL (Service Provider)
File: spstdatt.cpp
Content: This file contains the standard-attribute object.
History:
10/15/96 Chu, Lon-Chan [lonchanc]
Created.
Copyright (c) Microsoft Corporation 1996-1997
---------------------------------------------------------------------- */
#include "ulsp.h"
#include "spinc.h"
/* ---------- public methods ----------- */
UlsLdap_CStdAttrs::UlsLdap_CStdAttrs ( VOID )
{
}
UlsLdap_CStdAttrs::~UlsLdap_CStdAttrs ( VOID )
{
}
/* ---------- protected methods ----------- */
HRESULT UlsLdap_CStdAttrs::SetStdAttrs (
ULONG *puRespID,
ULONG *puMsgID,
ULONG uNotifyMsg,
VOID *pInfo,
SERVER_INFO *pServerInfo,
TCHAR *pszDN )
{
MyAssert (puRespID != NULL || puMsgID != NULL);
MyAssert (pInfo != NULL);
MyAssert (pServerInfo != NULL);
MyAssert (pszDN != NULL);
// cache info
//
HRESULT hr = CacheInfo (pInfo);
if (hr != S_OK)
return hr;
// Build modify array for ldap_modify()
//
LDAPMod **ppMod = NULL;
hr = CreateSetStdAttrsModArr (&ppMod);
if (hr != S_OK)
return hr;
MyAssert (ppMod != NULL);
// so far, we are done with local preparation
//
// Get the session object
//
UlsLdap_CSession *pSession = NULL;
hr = g_pSessionContainer->GetSession (&pSession, pServerInfo);
if (hr != S_OK)
{
MemFree (ppMod);
return hr;
}
MyAssert (pSession != NULL);
// Get the ldap session
//
LDAP *ld = pSession->GetLd ();
MyAssert (ld != NULL);
// Send the data over the wire
//
ULONG uMsgID = ldap_modify (ld, pszDN, ppMod);
MemFree (ppMod);
if (uMsgID == -1)
{
hr = ::LdapError2Hresult (ld->ld_errno);
pSession->Disconnect ();
return hr;
}
// If the caller requests a response id,
// then submit this pending item.
// else free up the session object
//
if (puRespID != NULL)
{
// Initialize pending info
//
PENDING_INFO PendingInfo;
::FillDefPendingInfo (&PendingInfo, ld, uMsgID, INVALID_MSG_ID);
PendingInfo.uLdapResType = LDAP_RES_MODIFY;
PendingInfo.uNotifyMsg = uNotifyMsg;
// Queue it
//
hr = g_pPendingQueue->EnterRequest (pSession, &PendingInfo);
if (hr != S_OK)
{
// If queueing failed, then clean up
//
ldap_abandon (ld, uMsgID);
pSession->Disconnect ();
MyAssert (FALSE);
}
// Return the reponse id
//
*puRespID = PendingInfo.uRespID;
}
else
{
// Free up session (i.e. decrement the reference count)
//
pSession->Disconnect ();
}
if (puMsgID != NULL)
*puMsgID = uMsgID;
return hr;
}
HRESULT
FillDefStdAttrsModArr (
LDAPMod ***pppMod,
DWORD dwFlags,
ULONG cMaxAttrs,
ULONG *pcTotal, // in/out parameter!!!
LONG IsbuModOp,
ULONG cPrefix,
TCHAR *pszPrefix )
{
MyAssert (pppMod != NULL);
MyAssert (pcTotal != NULL);
MyAssert ( (cPrefix == 0 && pszPrefix == NULL) ||
(cPrefix != 0 && pszPrefix != NULL));
// Figure out the num of attributes
//
ULONG cAttrs = 0;
for (ULONG i = 0; i < cMaxAttrs; i++)
{
if (dwFlags & 0x01)
cAttrs++;
dwFlags >>= 1;
}
// Allocate modify list
//
ULONG cTotal = *pcTotal + cPrefix + cAttrs;
ULONG cbMod = IlsCalcModifyListSize (cTotal);
*pppMod = (LDAPMod **) MemAlloc (cbMod);
if (*pppMod == NULL)
return ULS_E_MEMORY;
// Fill in the modify list
//
LDAPMod *pMod;
for (i = 0; i < cTotal; i++)
{
pMod = IlsGetModifyListMod (pppMod, cTotal, i);
(*pppMod)[i] = pMod;
pMod->mod_values = (TCHAR **) (pMod + 1);
if (i < cPrefix)
{
pMod->mod_op = LDAP_MOD_REPLACE;
pMod->mod_type = pszPrefix;
pszPrefix += lstrlen (pszPrefix) + 1;
*(pMod->mod_values) = pszPrefix;
pszPrefix += lstrlen (pszPrefix) + 1;
}
}
// Fix up the last one
//
IlsFixUpModOp ((*pppMod)[0], LDAP_MOD_REPLACE, IsbuModOp);
(*pppMod)[cTotal] = NULL;
// Return the total number of entries if needed
//
if (pcTotal)
*pcTotal = cTotal;
return S_OK;
}
/* ---------- private methods ----------- */
| 20.529703 | 77 | 0.581866 | [
"object"
] |
a46294a1105f0bcb7c2b0e83367e906ce9b86752 | 647 | cpp | C++ | source/Requester.cpp | JFlaherty347/Participation-Manager | ec3dadf235e96387928245b8c37335de862331ac | [
"Apache-2.0"
] | null | null | null | source/Requester.cpp | JFlaherty347/Participation-Manager | ec3dadf235e96387928245b8c37335de862331ac | [
"Apache-2.0"
] | null | null | null | source/Requester.cpp | JFlaherty347/Participation-Manager | ec3dadf235e96387928245b8c37335de862331ac | [
"Apache-2.0"
] | null | null | null | #include "Requester.h"
Result *Requester::makeRequest(Request *request)
{
vector<User *> *rawResults = request->useRequest();
return request->packageResults(rawResults);
}
// int main(int argc, char *argv[])
// {
// printf("Testing Requester:::\n");
// Request *myRequest = new GetAllUsersRequest();
// GetAllUsersResult *myResults = (GetAllUsersResult *)Requester::makeRequest(myRequest);
// vector<User *> *myUsers = myResults->getResults();
// printf("Printing users: \n");
// for(int i = 0; i < myUsers->size(); i++)
// {
// User *theUser = myUsers->at(i);
// printf("name: '%s'\n", (theUser->getName()).c_str());
// }
// }
| 25.88 | 90 | 0.639876 | [
"vector"
] |
a479a578443c12a0c46090730583ff0cb420f0fe | 7,638 | cpp | C++ | Source/AstralShipwright/Game/NovaAsteroid.cpp | arbonagw/AstralShipwright | 8a41015f23fa810ab79d72460f9ada2dd7e37852 | [
"BSD-3-Clause"
] | 59 | 2021-11-29T22:20:03.000Z | 2022-03-17T00:07:48.000Z | Source/AstralShipwright/Game/NovaAsteroid.cpp | arbonagw/AstralShipwright | 8a41015f23fa810ab79d72460f9ada2dd7e37852 | [
"BSD-3-Clause"
] | null | null | null | Source/AstralShipwright/Game/NovaAsteroid.cpp | arbonagw/AstralShipwright | 8a41015f23fa810ab79d72460f9ada2dd7e37852 | [
"BSD-3-Clause"
] | 4 | 2022-01-05T09:44:12.000Z | 2022-02-21T02:02:32.000Z | // Astral Shipwright - Gwennaël Arbona
#include "NovaAsteroid.h"
#include "NovaPlanetarium.h"
#include "NovaGameState.h"
#include "NovaOrbitalSimulationComponent.h"
#include "Neutron/System/NeutronAssetManager.h"
#include "Components/StaticMeshComponent.h"
#include "NiagaraFunctionLibrary.h"
#include "NiagaraComponent.h"
/*----------------------------------------------------
Mineral source
----------------------------------------------------*/
FNovaAsteroidMineralSource::FNovaAsteroidMineralSource(FRandomStream& RandomStream)
: Direction(RandomStream.GetUnitVector()), TargetAngularDistance(RandomStream.FRandRange(20, 80))
{}
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
ANovaAsteroid::ANovaAsteroid() : Super(), LoadingAssets(false)
{
// Create the main mesh
AsteroidMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Asteroid"));
SetRootComponent(AsteroidMesh);
// Defaults
PrimaryActorTick.bCanEverTick = true;
SetReplicates(false);
bAlwaysRelevant = true;
}
/*----------------------------------------------------
Interface
----------------------------------------------------*/
void ANovaAsteroid::BeginPlay()
{
Super::BeginPlay();
#if WITH_EDITOR
if (!IsValid(GetOwner()))
{
NLOG("ANovaAsteroid::BeginPlay : spawning as fallback");
const UNovaAsteroidConfiguration* AsteroidConfiguration =
UNeutronAssetManager::Get()->GetDefaultAsset<UNovaAsteroidConfiguration>();
NCHECK(AsteroidConfiguration);
FRandomStream Random;
Initialize(FNovaAsteroid(Random, AsteroidConfiguration, 0, 0));
}
#endif // WITH_EDITOR
}
void ANovaAsteroid::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (!IsLoadingAssets())
{
ProcessMovement();
ProcessDust();
#if WITH_EDITOR && 0
FVector Center, Extent;
GetActorBounds(false, Center, Extent);
for (int32 Pitch = -90; Pitch < 90; Pitch += 5)
{
for (int32 Yaw = 0; Yaw < 360; Yaw += 5)
{
FRotator CurrentRotation = FRotator(Pitch, Yaw, 0);
FLinearColor Color = FMath::Lerp(FLinearColor::Blue, FLinearColor::Red, GetMineralDensity(CurrentRotation.Vector()));
DrawDebugPoint(GetWorld(), GetActorLocation() + CurrentRotation.Vector() * (Extent.Size() / (2 * Asteroid.Scale)), 5,
Color.ToFColor(true));
}
}
#endif // WITH_EDITOR
}
}
void ANovaAsteroid::Initialize(const FNovaAsteroid& InAsteroid)
{
// Initialize to safe defaults
LoadingAssets = true;
Asteroid = InAsteroid;
SetActorRotation(InAsteroid.Rotation);
SetActorScale3D(Asteroid.Scale * FVector(1, 1, 1));
// Initialize minerals
FRandomStream Random(Asteroid.MineralsSeed);
for (int32 Index = 0; Index < Random.RandRange(5, 10); Index++)
{
MineralSources.Add(FNovaAsteroidMineralSource(Random));
}
// Default game path : load assets and resume initializing later
if (IsValid(GetOwner()))
{
SetActorLocation(FVector(0, 0, -1000 * 1000 * 100));
UNeutronAssetManager::Get()->LoadAssets({Asteroid.Mesh.ToSoftObjectPath(), Asteroid.DustEffect.ToSoftObjectPath()},
FStreamableDelegate::CreateUObject(this, &ANovaAsteroid::PostLoadInitialize));
}
#if WITH_EDITOR
else
{
Asteroid.Mesh.LoadSynchronous();
Asteroid.DustEffect.LoadSynchronous();
PostLoadInitialize();
}
#endif // WITH_EDITOR
}
double ANovaAsteroid::GetMineralDensity(const FVector& Direction) const
{
double Density = 0;
for (const FNovaAsteroidMineralSource& Source : MineralSources)
{
double AngularDistance =
FMath::RadiansToDegrees(Direction.ToOrientationQuat().AngularDistance(Source.Direction.ToOrientationQuat()));
Density += 1.0 - FMath::Clamp(AngularDistance / Source.TargetAngularDistance, 0.0, 1.0);
}
return FMath::Clamp(Density, 0.0, 1.0);
}
/*----------------------------------------------------
Internals
----------------------------------------------------*/
void ANovaAsteroid::PostLoadInitialize()
{
LoadingAssets = false;
NLOG("ANovaAsteroid::PostLoadInitialize : ready to show '%s'", *Asteroid.Identifier.ToString(EGuidFormats::Short));
// Setup asteroid mesh & material
NCHECK(Asteroid.Mesh.IsValid());
AsteroidMesh->SetStaticMesh(Asteroid.Mesh.Get());
MaterialInstance = AsteroidMesh->CreateAndSetMaterialInstanceDynamic(0);
MaterialInstance->SetScalarParameterValue("AsteroidScale", Asteroid.Scale);
// Create random effects
for (int32 Index = 0; Index < Asteroid.EffectsCount; Index++)
{
DustSources.Add(FMath::VRand());
UNiagaraComponent* Emitter = UNiagaraFunctionLibrary::SpawnSystemAttached(Asteroid.DustEffect.Get(), AsteroidMesh, NAME_None,
GetActorLocation(), FRotator::ZeroRotator, EAttachLocation::KeepWorldPosition, false);
Emitter->SetWorldScale3D(Asteroid.Scale * FVector(1, 1, 1));
DustEmitters.Add(Emitter);
}
}
void ANovaAsteroid::ProcessMovement()
{
if (IsValid(GetOwner()))
{
// Get basic game state pointers
const ANovaGameState* GameState = GetWorld()->GetGameState<ANovaGameState>();
NCHECK(GameState);
const UNovaOrbitalSimulationComponent* OrbitalSimulation = GameState->GetOrbitalSimulation();
NCHECK(OrbitalSimulation);
// Get locations
const FVector2D PlayerLocation = OrbitalSimulation->GetPlayerCartesianLocation();
const FVector2D AsteroidLocation = OrbitalSimulation->GetAsteroidLocation(Asteroid.Identifier).GetCartesianLocation();
FVector2D LocationInKilometers = AsteroidLocation - PlayerLocation;
// Transform the location accounting for angle and scale
const FVector2D PlayerDirection = PlayerLocation.GetSafeNormal();
double PlayerAngle = 180 + FMath::RadiansToDegrees(FMath::Atan2(PlayerDirection.X, PlayerDirection.Y));
LocationInKilometers = LocationInKilometers.GetRotated(PlayerAngle);
const FVector RelativeOrbitalLocation = FVector(0, -LocationInKilometers.X, LocationInKilometers.Y) * 1000 * 100;
SetActorLocation(RelativeOrbitalLocation);
}
}
void ANovaAsteroid::ProcessDust()
{
// Get the planetarium
TArray<AActor*> PlanetariumCandidates;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ANovaPlanetarium::StaticClass(), PlanetariumCandidates);
NCHECK(PlanetariumCandidates.Num() > 0);
const ANovaPlanetarium* Planetarium = Cast<ANovaPlanetarium>(PlanetariumCandidates[0]);
// Get world data
FVector AsteroidLocation = GetActorLocation();
FVector SunDirection = Planetarium->GetSunDirection();
float CollisionSize = AsteroidMesh->GetCollisionShape().GetExtent().Size();
// Compute new FX locations
for (int32 Index = 0; Index < DustEmitters.Num(); Index++)
{
FVector RandomDirection = FVector::CrossProduct(SunDirection, DustSources[Index]);
RandomDirection.Normalize();
FVector StartPoint = AsteroidLocation + RandomDirection * CollisionSize;
// Trace params
FHitResult HitResult(ForceInit);
FCollisionQueryParams TraceParams(FName(TEXT("Asteroid Trace")), false, NULL);
TraceParams.bTraceComplex = true;
TraceParams.bReturnPhysicalMaterial = false;
ECollisionChannel CollisionChannel = ECollisionChannel::ECC_WorldDynamic;
// Trace
bool FoundHit = GetWorld()->LineTraceSingleByChannel(HitResult, StartPoint, AsteroidLocation, CollisionChannel, TraceParams);
if (FoundHit && HitResult.GetActor() == this && IsValid(DustEmitters[Index]))
{
FVector EffectLocation = HitResult.Location;
if (!DustEmitters[Index]->IsActive())
{
DustEmitters[Index]->Activate();
}
DustEmitters[Index]->SetWorldLocation(EffectLocation);
DustEmitters[Index]->SetWorldRotation(SunDirection.Rotation());
}
else
{
DustEmitters[Index]->Deactivate();
}
}
}
| 31.958159 | 127 | 0.706337 | [
"mesh",
"vector",
"transform"
] |
a47fe63891b841d2bb4fd93e29c22e07734358e6 | 4,511 | cc | C++ | components/download/internal/background_service/scheduler/scheduler_impl.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/download/internal/background_service/scheduler/scheduler_impl.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/download/internal/background_service/scheduler/scheduler_impl.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 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/download/internal/background_service/scheduler/scheduler_impl.h"
#include "components/download/internal/background_service/client_set.h"
#include "components/download/internal/background_service/config.h"
#include "components/download/internal/background_service/entry_utils.h"
#include "components/download/internal/background_service/scheduler/device_status.h"
#include "components/download/public/background_service/download_params.h"
#include "components/download/public/background_service/task_scheduler.h"
namespace download {
namespace {
// Returns a vector of elements contained in the |set|.
template <typename T>
std::vector<T> ToList(const std::set<T>& set) {
std::vector<T> list;
for (const auto& element : set) {
list.push_back(element);
}
return list;
}
} // namespace
SchedulerImpl::SchedulerImpl(TaskScheduler* task_scheduler,
Configuration* config,
const ClientSet* clients)
: SchedulerImpl(task_scheduler,
config,
ToList<DownloadClient>(clients->GetRegisteredClients())) {}
SchedulerImpl::SchedulerImpl(TaskScheduler* task_scheduler,
Configuration* config,
const std::vector<DownloadClient>& clients)
: task_scheduler_(task_scheduler),
config_(config),
download_clients_(clients),
current_client_index_(0) {
DCHECK(task_scheduler_);
}
SchedulerImpl::~SchedulerImpl() = default;
void SchedulerImpl::Reschedule(const Model::EntryList& entries) {
if (entries.empty()) {
task_scheduler_->CancelTask(DownloadTaskType::DOWNLOAD_TASK);
return;
}
// TODO(xingliu): Support NetworkRequirements::OPTIMISTIC.
Criteria criteria = util::GetSchedulingCriteria(
entries, config_->download_battery_percentage);
task_scheduler_->ScheduleTask(
DownloadTaskType::DOWNLOAD_TASK, criteria.requires_unmetered_network,
criteria.requires_battery_charging, criteria.optimal_battery_percentage,
base::saturated_cast<long>(config_->window_start_time.InSeconds()),
base::saturated_cast<long>(config_->window_end_time.InSeconds()));
}
Entry* SchedulerImpl::Next(const Model::EntryList& entries,
const DeviceStatus& device_status) {
std::map<DownloadClient, Entry*> candidates =
FindCandidates(entries, device_status);
Entry* entry = nullptr;
size_t index = current_client_index_;
// Finds the next entry to download.
for (size_t i = 0; i < download_clients_.size(); ++i) {
DownloadClient client =
download_clients_[(index + i) % download_clients_.size()];
Entry* candidate = candidates[client];
// Some clients may have no entries, continue to check other clients.
if (!candidate)
continue;
bool ui_priority =
candidate->scheduling_params.priority == SchedulingParams::Priority::UI;
// Records the first available candidate. Keep iterating to see if there
// are UI priority entries for other clients.
if (!entry || ui_priority) {
entry = candidate;
// Load balancing between clients.
current_client_index_ = (index + i + 1) % download_clients_.size();
// UI priority entry will be processed immediately.
if (ui_priority)
break;
}
}
return entry;
}
std::map<DownloadClient, Entry*> SchedulerImpl::FindCandidates(
const Model::EntryList& entries,
const DeviceStatus& device_status) {
std::map<DownloadClient, Entry*> candidates;
if (entries.empty())
return candidates;
for (auto* const entry : entries) {
DCHECK(entry);
const SchedulingParams& current_params = entry->scheduling_params;
// Every download needs to pass the state and device status check.
if (entry->state != Entry::State::AVAILABLE ||
!device_status
.MeetsCondition(current_params,
config_->download_battery_percentage)
.MeetsRequirements()) {
continue;
}
// Find the most appropriate download based on priority and cancel time.
Entry* candidate = candidates[entry->client];
if (!candidate || util::EntryBetterThan(*entry, *candidate)) {
candidates[entry->client] = entry;
}
}
return candidates;
}
} // namespace download
| 33.414815 | 85 | 0.694524 | [
"vector",
"model"
] |
a48043c326cb1875b924ba0aa8bd5b7166af847b | 670 | cpp | C++ | Shape/main.cpp | tomosu/PBR_Practice | 3ecc1d7ffed11fc88767615d2ac122c70e15d9c2 | [
"MIT"
] | 1 | 2016-06-23T09:08:27.000Z | 2016-06-23T09:08:27.000Z | Shape/main.cpp | tomosu/PBR_Practice | 3ecc1d7ffed11fc88767615d2ac122c70e15d9c2 | [
"MIT"
] | null | null | null | Shape/main.cpp | tomosu/PBR_Practice | 3ecc1d7ffed11fc88767615d2ac122c70e15d9c2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include "HitInformation.h"
#include "Shape.h"
int main()
{
SharedMaterialPtr material;
//////////////////////
// create sphere
//////////////////////
Vec3 center(0.0, 0.0, 0.0);
Real radius =3.0;
ShapeParam param(center, radius);
SharedShapePtr sphere =Shape::CreateShape(material, param);
//////////////////////
// get hit point
//////////////////////
Vec3 origin(-10.0, 0.0, 0.0);
Vec3 direction(1.0, 0.0, 0.0);
Ray ray(origin, direction);
HitInformation info;
sphere->GetHitInformation(ray, 9999999.9, 0.00001, &info);
std::cout << "t:" << info.RayParam << std::endl;
return 0;
}
| 19.705882 | 61 | 0.558209 | [
"shape"
] |
a4822072c23cae741cd1392f82b736d6bea31039 | 1,839 | hpp | C++ | idl_parser/include/morbid/idl_parser/struct_def.hpp | felipealmeida/mORBid | 3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b | [
"BSL-1.0"
] | 2 | 2018-01-31T07:06:23.000Z | 2021-02-18T00:49:05.000Z | idl_parser/include/morbid/idl_parser/struct_def.hpp | felipealmeida/mORBid | 3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b | [
"BSL-1.0"
] | null | null | null | idl_parser/include/morbid/idl_parser/struct_def.hpp | felipealmeida/mORBid | 3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b | [
"BSL-1.0"
] | null | null | null | /* (c) Copyright 2012 Felipe Magno de Almeida
*
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef MORBID_IDL_PARSER_STRUCT_DEF_HPP
#define MORBID_IDL_PARSER_STRUCT_DEF_HPP
#include <morbid/idl_parser/type_spec.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <ostream>
#include <string>
namespace morbid { namespace idl_parser {
template <typename Iterator>
struct struct_member
{
type_spec<Iterator> type;
std::string name;
struct_member(type_spec<Iterator> type, std::string name)
: type(type), name(name) {}
struct_member() {}
};
template <typename Iterator>
struct struct_def
{
std::string name;
std::vector<struct_member<Iterator> > members;
};
template <typename Iterator>
std::ostream& operator<<(std::ostream& os, struct_member<Iterator> m)
{
return os << "[struct_member name: " << m.name << " type: " << m.type << "]";
}
template <typename Iterator>
std::ostream& operator<<(std::ostream& os, struct_def<Iterator> d)
{
os << "[struct_def name: " << d.name << " members: ";
std::copy(d.members.begin(), d.members.end()
, std::ostream_iterator<struct_member<Iterator> >(os, ", "));
return os << "]";
}
} }
BOOST_FUSION_ADAPT_TPL_STRUCT((Iterator)
, (::morbid::idl_parser::struct_member) (Iterator)
, (::morbid::idl_parser::type_spec<Iterator>, type)
(std::string, name));
BOOST_FUSION_ADAPT_TPL_STRUCT((Iterator)
, (::morbid::idl_parser::struct_def) (Iterator)
, (std::string, name)
(std::vector< ::morbid::idl_parser::struct_member<Iterator> >, members));
#endif
| 27.863636 | 105 | 0.636215 | [
"vector"
] |
a48502f33ef4e92d47af6e6ada6432b7730401e4 | 1,254 | cpp | C++ | 102-binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp | nagestx/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | 3 | 2018-12-15T14:07:12.000Z | 2020-07-19T23:18:09.000Z | 102-binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp | yangyangu/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | null | null | null | 102-binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp | yangyangu/MyLeetCode | ef2a98b48485a0cebc442bbbbdb2690ba51484e1 | [
"MIT"
] | null | null | null | // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
//
//
// For example:
// Given binary tree [3,9,20,null,null,15,7],
//
// 3
// / \
// 9 20
// / \
// 15 7
//
//
//
// return its level order traversal as:
//
// [
// [3],
// [9,20],
// [15,7]
// ]
//
//
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<pair<TreeNode*,int>> q;
TreeNode * p = NULL;
q.push(make_pair(root,0));
while(!q.empty()){
p = q.front().first;
int l = q.front().second;
q.pop();
if(l == res.size()){
res.push_back(vector<int>());
}
res[l].push_back(p->val);
if(p->left)
q.push(make_pair(p->left,l + 1));
if(p->right)
q.push(make_pair(p->right,l + 1));
}
return res;
}
};
| 20.9 | 121 | 0.461722 | [
"vector"
] |
a4862c22255f1965255a794a727a804663fc4efc | 22,696 | cpp | C++ | cachelib/allocator/tests/MM2QTest.cpp | GerHobbelt/CacheLib | 580bf6950aad89cf86dbc153f12dada79b71eaf7 | [
"Apache-2.0"
] | 578 | 2021-09-01T14:19:55.000Z | 2022-03-29T12:22:46.000Z | cachelib/allocator/tests/MM2QTest.cpp | igchor/Cachelib | 7db2c643d49fd0a4ec6c492d94a400cbe0515a70 | [
"Apache-2.0"
] | 61 | 2021-09-02T18:48:06.000Z | 2022-03-31T01:56:00.000Z | cachelib/allocator/tests/MM2QTest.cpp | igchor/Cachelib | 7db2c643d49fd0a4ec6c492d94a400cbe0515a70 | [
"Apache-2.0"
] | 88 | 2021-09-02T21:22:19.000Z | 2022-03-27T07:40:27.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Random.h>
#include "cachelib/allocator/MM2Q.h"
#include "cachelib/allocator/tests/MMTypeTest.h"
namespace facebook {
namespace cachelib {
using MM2QTest = MMTypeTest<MM2Q>;
TEST_F(MM2QTest, AddBasic) { testAddBasic(MM2Q::Config{}); }
TEST_F(MM2QTest, RemoveBasic) { testRemoveBasic(MM2Q::Config{}); }
TEST_F(MM2QTest, RemoveWithSmallQueues) {
MM2Q::Config config{};
config.coldSizePercent = 10;
config.hotSizePercent = 35;
config.lruRefreshTime = 0;
Container c(config, {});
std::vector<std::unique_ptr<Node>> nodes;
createSimpleContainer(c, nodes);
// access to move items from cold to warm
for (auto& node : nodes) {
ASSERT_TRUE(c.recordAccess(*node, AccessMode::kRead));
}
// trying to remove through iterator should work as expected.
// no need of iter++ since remove will do that.
for (auto iter = c.getEvictionIterator(); iter;) {
auto& node = *iter;
ASSERT_TRUE(node.isInMMContainer());
// this will move the iter.
c.remove(iter);
ASSERT_FALSE(node.isInMMContainer());
if (iter) {
ASSERT_NE((*iter).getId(), node.getId());
}
}
ASSERT_EQ(c.getStats().size, 0);
for (const auto& node : nodes) {
ASSERT_FALSE(node->isInMMContainer());
}
}
TEST_F(MM2QTest, RecordAccessBasic) {
MM2Q::Config c;
// Change lruRefreshTime to make sure only the first recordAccess bumps
// the node and subsequent recordAccess invocations do not.
c.lruRefreshTime = 100;
testRecordAccessBasic(std::move(c));
}
TEST_F(MM2QTest, RecordAccessWrites) {
using Nodes = std::vector<std::unique_ptr<Node>>;
// access the nodes in the container randomly with the given access mode and
// ensure that nodes are updated in lru with access mode write (read) only
// when updateOnWrite (updateOnRead) is enabled.
auto testWithAccessMode = [](Container& c_, const Nodes& nodes_,
AccessMode mode, bool updateOnWrites,
bool updateOnReads) {
// accessing must at least update the update time. to do so, first set the
// updateTime of the node to be in the past.
const uint32_t timeInPastStart = 100;
std::vector<uint32_t> prevNodeTime;
int i = 0;
for (auto& node : nodes_) {
auto time = timeInPastStart + i;
node->setUpdateTime(time);
ASSERT_EQ(node->getUpdateTime(), time);
prevNodeTime.push_back(time);
i++;
}
std::vector<int> nodeOrderPrev;
for (auto itr = c_.getEvictionIterator(); itr; ++itr) {
nodeOrderPrev.push_back(itr->getId());
}
int nAccess = 1000;
std::set<int> accessedNodes;
while (nAccess-- || accessedNodes.size() < nodes_.size()) {
auto& node = *(nodes_.begin() + folly::Random::rand32() % nodes_.size());
accessedNodes.insert(node->getId());
c_.recordAccess(*node, mode);
}
i = 0;
const auto now = util::getCurrentTimeSec();
for (const auto& node : nodes_) {
if ((mode == AccessMode::kWrite && updateOnWrites) ||
(mode == AccessMode::kRead && updateOnReads)) {
ASSERT_GT(node->getUpdateTime(), prevNodeTime[i++]);
ASSERT_LE(node->getUpdateTime(), now);
} else {
ASSERT_EQ(node->getUpdateTime(), prevNodeTime[i++]);
}
}
// after a random set of recordAccess, test the order of the nodes in the
// lru.
std::vector<int> nodeOrderCurr;
for (auto itr = c_.getEvictionIterator(); itr; ++itr) {
nodeOrderCurr.push_back(itr->getId());
}
if ((mode == AccessMode::kWrite && updateOnWrites) ||
(mode == AccessMode::kRead && updateOnReads)) {
ASSERT_NE(nodeOrderCurr, nodeOrderPrev);
} else {
ASSERT_EQ(nodeOrderCurr, nodeOrderPrev);
}
};
auto createNodes = [](Container& c, Nodes& nodes) {
// put some nodes in the container and ensure that the recordAccess does not
// change the fact that the node is still in container.
const int numNodes = 10;
for (int i = 0; i < numNodes; i++) {
nodes.emplace_back(new Node{i});
auto& node = nodes.back();
ASSERT_TRUE(c.add(*node));
}
};
MM2Q::Config config1{/* lruRefreshTime */ 0,
/* lruRefreshRatio */ 0.,
/* updateOnWrite */ false,
/* updateOnRead */ false,
/* tryLockUpdate */ false,
/* updateOnRecordAccess */ true,
/* hotSizePercent */ 30,
/* coldSizePercent */ 30};
Container c1{config1, {}};
MM2Q::Config config2{/* lruRefreshTime */ 0,
/* lruRefreshRatio */ 0.,
/* updateOnWrite */ false,
/* updateOnRead */ true,
/* tryLockUpdate */ false,
/* updateOnRecordAccess */ true,
/* hotSizePercent */ 30,
/* coldSizePercent */ 30};
Container c2{config2, {}};
MM2Q::Config config3{/* lruRefreshTime */ 0,
/* lruRefreshRatio */ 0.,
/* updateOnWrite */ true,
/* updateOnRead */ false,
/* tryLockUpdate */ false,
/* updateOnRecordAccess */ true,
/* hotSizePercent */ 30,
/* coldSizePercent */ 30};
Container c3{config3, {}};
MM2Q::Config config4{/* lruRefreshTime */ 0,
/* lruRefreshRatio */ 0.,
/* updateOnWrite */ true,
/* updateOnRead */ true,
/* tryLockUpdate */ false,
/* updateOnRecordAccess */ true,
/* hotSizePercent */ 30,
/* coldSizePercent */ 30};
Container c4{config4, {}};
Nodes nodes1, nodes2, nodes3, nodes4;
createNodes(c1, nodes1);
createNodes(c2, nodes2);
createNodes(c3, nodes3);
createNodes(c4, nodes4);
testWithAccessMode(c1, nodes1, AccessMode::kWrite, config1.updateOnWrite,
config1.updateOnRead);
testWithAccessMode(c1, nodes1, AccessMode::kRead, config1.updateOnWrite,
config1.updateOnRead);
testWithAccessMode(c2, nodes2, AccessMode::kWrite, config2.updateOnWrite,
config2.updateOnRead);
testWithAccessMode(c2, nodes2, AccessMode::kRead, config2.updateOnWrite,
config2.updateOnRead);
testWithAccessMode(c3, nodes3, AccessMode::kWrite, config3.updateOnWrite,
config3.updateOnRead);
testWithAccessMode(c3, nodes3, AccessMode::kRead, config3.updateOnWrite,
config3.updateOnRead);
testWithAccessMode(c4, nodes4, AccessMode::kWrite, config4.updateOnWrite,
config4.updateOnRead);
testWithAccessMode(c4, nodes4, AccessMode::kRead, config4.updateOnWrite,
config4.updateOnRead);
}
template <typename MMType>
void MMTypeTest<MMType>::testIterate(std::vector<std::unique_ptr<Node>>& nodes,
Container& c) {
auto it2q = c.getEvictionIterator();
auto it = nodes.begin();
while (it2q) {
ASSERT_EQ(it2q->getId(), (*it)->getId());
++it2q;
++it;
}
}
template <typename MMType>
void MMTypeTest<MMType>::testMatch(std::string expected,
MMTypeTest<MMType>::Container& c) {
int index = -1;
std::string actual;
auto it2q = c.getEvictionIterator();
while (it2q) {
++index;
actual += folly::stringPrintf(
"%d:%s, ", it2q->getId(),
(c.isHot(*it2q) ? "H" : (c.isCold(*it2q) ? "C" : "W")));
++it2q;
}
ASSERT_EQ(expected, actual);
}
TEST_F(MM2QTest, DetailedTest) {
MM2Q::Config config;
config.lruRefreshTime = 0;
config.updateOnWrite = false;
config.hotSizePercent = 35;
config.coldSizePercent = 30;
// For 6 element, 35% gives us 2
// elements in hot and warm cache
Container c{config, {}};
using Nodes = std::vector<std::unique_ptr<Node>>;
Nodes nodes;
int numNodes = 6;
for (int i = 0; i < numNodes; i++) {
nodes.emplace_back(new Node{i});
auto& node = nodes.back();
c.add(*node);
}
testIterate(nodes, c);
testMatch("0:C, 1:C, 2:C, 3:C, 4:H, 5:H, ", c);
// Move 3 to top of the hot cache
c.recordAccess(*(nodes[4]), AccessMode::kRead);
testMatch("0:C, 1:C, 2:C, 3:C, 5:H, 4:H, ", c);
// Move 1 (cold) to warm cache
c.recordAccess(*(nodes[1]), AccessMode::kRead);
testMatch("0:C, 2:C, 3:C, 5:H, 4:H, 1:W, ", c);
// Move 2 (cold) to warm cache
c.recordAccess(*(nodes[2]), AccessMode::kRead);
testMatch("0:C, 3:C, 5:H, 4:H, 1:W, 2:W, ", c);
// Move 1 (warm) to top of warm cache
c.recordAccess(*(nodes[1]), AccessMode::kRead);
testMatch("0:C, 3:C, 5:H, 4:H, 2:W, 1:W, ", c);
// Move 3 (cold) to top of warm cache
c.recordAccess(*(nodes[3]), AccessMode::kRead);
testMatch("0:C, 2:C, 5:H, 4:H, 1:W, 3:W, ", c);
// Add 6 to hot cache.
nodes.emplace_back(new Node{6});
c.add(*(nodes[6]));
testMatch("0:C, 2:C, 5:C, 4:H, 6:H, 1:W, 3:W, ", c);
// Test arbitrary node deletion.
// Delete a hot node
c.remove(*(nodes[4]));
nodes.erase(nodes.begin() + 4);
testMatch("0:C, 2:C, 5:C, 6:H, 1:W, 3:W, ", c);
// Delete a cold node
c.remove(*(nodes[2]));
nodes.erase(nodes.begin() + 2);
testMatch("0:C, 5:C, 1:C, 6:H, 3:W, ", c);
// Delete a warm node
c.remove(*(nodes[2]));
nodes.erase(nodes.begin() + 2);
testMatch("0:C, 5:C, 1:C, 6:H, ", c);
int listSize = nodes.size();
for (auto it = nodes.begin(); it != nodes.end(); ++it) {
ASSERT_EQ(c.remove(*(it->get())), true);
ASSERT_EQ(c.size(), --listSize);
}
ASSERT_EQ(c.size(), 0);
}
TEST_F(MM2QTest, SegmentStress) {
// given hot/cold segment sizes, run a finite number of random operations
// on it and ensure that the tail sizes match what we expect it to be.
auto doStressTest = [&](unsigned int hotSizePercent,
unsigned int coldSizePercent) {
MM2Q::Config config;
config.lruRefreshTime = 0;
config.hotSizePercent = hotSizePercent;
config.coldSizePercent = coldSizePercent;
Container c{config, {}};
constexpr auto nNodes = 500;
using Nodes = std::vector<std::unique_ptr<Node>>;
Nodes nodes;
for (int i = 0; i < nNodes; i++) {
nodes.emplace_back(new Node{i});
}
// list of nodes currently in lru
std::unordered_set<int> inLru;
// add a random node into the lru that is not present.
// the lru must not be full at this point.
auto addRandomNode = [&]() {
if (inLru.size() >= nNodes) {
return;
}
auto n = folly::Random::rand32() % nNodes;
while (inLru.count(n) != 0) {
n = folly::Random::rand32() % nNodes;
}
c.add(*nodes[n]);
assert(inLru.count(n) == 0);
inLru.insert(n);
};
// removes a random node that is present in the lru.
auto removeRandomNode = [&]() {
if (inLru.empty()) {
return;
}
auto n = folly::Random::rand32() % nNodes;
while (inLru.count(n) == 0) {
n = folly::Random::rand32() % nNodes;
}
c.remove(*nodes[n]);
assert(inLru.count(n) != 0);
inLru.erase(n);
};
// on a non-empty lru, bump up a random node
auto recordRandomNode = [&]() {
if (inLru.empty()) {
return;
}
auto n = folly::Random::rand32() % nNodes;
while (inLru.count(n) == 0) {
n = folly::Random::rand32() % nNodes;
}
c.recordAccess(*nodes[n], AccessMode::kRead);
};
int opsToComplete = 100000;
folly::ThreadLocalPRNG prng = folly::ThreadLocalPRNG();
std::mt19937 gen(folly::Random::rand32(prng));
std::uniform_real_distribution<> opDis(0, 1);
// probabilities for different operation.
const double addPct = 0.4;
const double recordAccesPct = 0.9;
const double removePct = 0.2;
int completedOps = 0;
while (++completedOps < opsToComplete) {
auto op = opDis(gen);
if (inLru.size() < nNodes && op < addPct) {
addRandomNode();
}
if (op < removePct && !inLru.empty()) {
removeRandomNode();
}
if (op < recordAccesPct && !inLru.empty()) {
recordRandomNode();
}
if (!inLru.empty() && completedOps > 1000) {
// to trigger a rebalance.
const auto errorMargin = 2;
const unsigned int actualColdPercent =
(c.getEvictionAgeStat(0).coldQueueStat.size) * 100 / inLru.size();
EXPECT_TRUE(actualColdPercent >= coldSizePercent - errorMargin &&
actualColdPercent <= coldSizePercent + errorMargin)
<< "Actual: " << actualColdPercent
<< ", Expected: " << coldSizePercent;
const unsigned int actualHotPercent =
c.getEvictionAgeStat(0).hotQueueStat.size * 100 / inLru.size();
EXPECT_TRUE(actualHotPercent >= hotSizePercent - errorMargin &&
actualHotPercent <= hotSizePercent + errorMargin)
<< "Actual: " << actualHotPercent
<< ", Expected: " << hotSizePercent;
}
}
};
doStressTest(10, 60);
doStressTest(20, 50);
doStressTest(30, 45);
doStressTest(40, 60);
doStressTest(60, 40);
}
TEST_F(MM2QTest, Serialization) { testSerializationBasic(MM2Q::Config{}); }
TEST_F(MM2QTest, Reconfigure) {
MM2Q::Config config;
config.hotSizePercent = 0;
config.coldSizePercent = 0;
config.defaultLruRefreshTime = 0;
config.lruRefreshTime = 0;
config.lruRefreshRatio = 0.8;
config.mmReconfigureIntervalSecs = std::chrono::seconds(4);
Container container(config, {});
std::vector<std::unique_ptr<Node>> nodes;
nodes.emplace_back(new Node{0});
container.add(*nodes[0]);
container.recordAccess(*nodes[0], AccessMode::kRead); // promote 0 to warm
sleep(1);
nodes.emplace_back(new Node{1});
container.add(*nodes[1]);
container.recordAccess(*nodes[1], AccessMode::kRead); // promote 1 to warm
sleep(2);
// node 0 (age 3) gets promoted
EXPECT_TRUE(container.recordAccess(*nodes[0], AccessMode::kRead));
sleep(2);
nodes.emplace_back(new Node{2});
container.add(*nodes[2]);
container.recordAccess(*nodes[2], AccessMode::kRead); // promote 2 to warm
// set refresh time to 4 * 0.8 = 3.2 = 3
container.recordAccess(*nodes[2], AccessMode::kRead);
// node 0 (age 2) does not get promoted
EXPECT_FALSE(container.recordAccess(*nodes[0], AccessMode::kRead));
}
TEST_F(MM2QTest, TailHits) {
MM2Q::Config config;
const size_t numItemInSlab = Slab::kSize / sizeof(Node);
config.lruRefreshTime = 0;
config.coldSizePercent = 50;
config.hotSizePercent = 0;
using LruType = MM2Q::LruType;
// test with tail lists
config.tailSize = numItemInSlab;
{
Container container(config, {});
std::vector<std::unique_ptr<Node>> nodes;
// add 2 slabs of items, which should all be in Cold
for (uint32_t i = 0; i < numItemInSlab * 2; i++) {
nodes.emplace_back(new Node{static_cast<int>(i)});
container.add(*nodes[i]);
}
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::ColdTail));
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::Cold));
EXPECT_EQ(2 * numItemInSlab,
container.getEvictionAgeStat(0).coldQueueStat.size);
EXPECT_EQ(0, getListSize(container, LruType::WarmTail));
EXPECT_EQ(0, getListSize(container, LruType::Warm));
EXPECT_EQ(0, container.getEvictionAgeStat(0).warmQueueStat.size);
// promote 1 slab of them to Warm tail
for (uint32_t i = 0; i < numItemInSlab; i++) {
container.recordAccess(*nodes[i], AccessMode::kRead);
}
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::ColdTail));
EXPECT_EQ(0, getListSize(container, LruType::Cold));
EXPECT_EQ(numItemInSlab,
container.getEvictionAgeStat(0).coldQueueStat.size);
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::WarmTail));
EXPECT_EQ(0, getListSize(container, LruType::Warm));
EXPECT_EQ(numItemInSlab,
container.getEvictionAgeStat(0).warmQueueStat.size);
// access all items, warm before cold
// after rebalance, there should be half in warm tail, half in cold tail
// (because warm can take at most 50% of items)
for (uint32_t i = 0; i < numItemInSlab; i++) {
container.recordAccess(*nodes[i], AccessMode::kRead);
}
for (uint32_t i = 0; i < numItemInSlab; i++) {
container.recordAccess(*nodes[i + numItemInSlab], AccessMode::kRead);
}
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::ColdTail));
EXPECT_EQ(0, getListSize(container, LruType::Cold));
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::WarmTail));
EXPECT_EQ(0, getListSize(container, LruType::Warm));
// cold tail should have 2 * numItemInSlab hits, and warm tail numItemInslab
// hits
EXPECT_EQ((2 + 1) * numItemInSlab / 2,
container.getStats().numTailAccesses);
// cannot disable tail lists because a cold roll is required
EXPECT_TRUE(container.tailTrackingEnabled_);
config.addExtraConfig(0);
ASSERT_EQ(0, config.tailSize);
EXPECT_THROW(container.setConfig(config), std::invalid_argument);
}
// disable tail lists; we shouldn't have non-empty tails anymore
config.tailSize = 0;
{
Container container(config, {});
std::vector<std::unique_ptr<Node>> nodes;
// add 2 slabs of items; tails should remain empty
for (uint32_t i = 0; i < numItemInSlab * 2; i++) {
nodes.emplace_back(new Node{static_cast<int>(i)});
container.add(*nodes[i]);
}
EXPECT_EQ(0, getListSize(container, LruType::ColdTail));
EXPECT_EQ(numItemInSlab * 2, getListSize(container, LruType::Cold));
EXPECT_EQ(numItemInSlab * 2,
container.getEvictionAgeStat(0).coldQueueStat.size);
EXPECT_EQ(0, getListSize(container, LruType::WarmTail));
EXPECT_EQ(0, getListSize(container, LruType::Warm));
EXPECT_EQ(0, container.getEvictionAgeStat(0).warmQueueStat.size);
// promote 1 slab of them to Warm
for (uint32_t i = 0; i < numItemInSlab; i++) {
container.recordAccess(*nodes[i], AccessMode::kRead);
}
EXPECT_EQ(0, getListSize(container, LruType::ColdTail));
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::Cold));
EXPECT_EQ(0, getListSize(container, LruType::WarmTail));
EXPECT_EQ(numItemInSlab, getListSize(container, LruType::Warm));
config.addExtraConfig(1);
ASSERT_FALSE(container.tailTrackingEnabled_);
// cannot enable tail hits because cold roll is required
EXPECT_THROW(container.setConfig(config), std::invalid_argument);
}
}
// If we previously have only 3 lists for 2Q and now want to expand to 5
// without turning on tail hits tracking, we should be able to avoid cold
// roll by adjusting the lists to the correct position
TEST_F(MM2QTest, DeserializeToMoreLists) {
MM2Q::Config config;
config.lruRefreshTime = 0;
config.coldSizePercent = 50;
config.hotSizePercent = 30;
const size_t numItems = 10;
const size_t numItemsCold = numItems * config.coldSizePercent / 100;
const size_t numItemsHot = numItems * config.hotSizePercent / 100;
const size_t numItemsWarm =
numItems * (100 - config.coldSizePercent - config.hotSizePercent) / 100;
using LruType = MM2Q::LruType;
std::vector<std::unique_ptr<Node>> nodes;
Container c1(config, {});
//
// insert items to lists
for (uint32_t i = 0; i < numItems; i++) {
nodes.emplace_back(new Node{static_cast<int>(i)});
c1.add(*nodes[i]);
}
for (uint32_t i = 0; i < numItemsWarm; i++) {
c1.recordAccess(*nodes[i], AccessMode::kRead);
}
ASSERT_EQ(numItemsHot, c1.getEvictionAgeStat(0).hotQueueStat.size);
ASSERT_EQ(numItemsCold, c1.getEvictionAgeStat(0).coldQueueStat.size);
ASSERT_EQ(numItemsWarm, c1.getEvictionAgeStat(0).warmQueueStat.size);
// move lists so that it only have 3 lists
auto& lists = c1.lru_.lists_;
std::swap(lists[1], lists[LruType::Hot]); // move Hot to pos 1
std::swap(lists[2], lists[LruType::Cold]); // move Cold to pos 2
lists.pop_back();
lists.pop_back();
ASSERT_EQ(3, lists.size());
// save state
auto serializedData = c1.saveState();
// deserialize to c2
Container c2(serializedData, {});
// check list sizes
ASSERT_EQ(numItemsHot, c2.getEvictionAgeStat(0).hotQueueStat.size);
ASSERT_EQ(numItemsCold, c2.getEvictionAgeStat(0).coldQueueStat.size);
ASSERT_EQ(numItemsWarm, c2.getEvictionAgeStat(0).warmQueueStat.size);
}
TEST_F(MM2QTest, TailTrackingEnabledCheck) {
MM2Q::Config config;
serialization::MultiDListObject lrus;
{
ASSERT_EQ(0, config.tailSize);
Container c(config, {});
// a new container created with zero tailSize should have tail tracking
// disabled
EXPECT_FALSE(c.tailTrackingEnabled_);
}
config.addExtraConfig(1);
{
Container c1(config, {});
// a new container created with non-zero tailSize should have tail tracking
// enabled.
EXPECT_TRUE(c1.tailTrackingEnabled_);
// and serialization should preserve that
auto serializedData = c1.saveState();
lrus = *serializedData.lrus_ref();
Container c2(serializedData, {});
EXPECT_TRUE(c2.tailTrackingEnabled_);
// disabling tail tracking should throw
config.addExtraConfig(0);
EXPECT_THROW(c2.setConfig(config), std::invalid_argument);
}
{
serialization::MM2QObject serializedData;
EXPECT_FALSE(*serializedData.tailTrackingEnabled_ref());
*serializedData.config_ref()->hotSizePercent_ref() = 10;
*serializedData.config_ref()->coldSizePercent_ref() = 20;
*serializedData.lrus_ref() = lrus;
// serialization object should by default have the flags dirty
Container c(serializedData, {});
EXPECT_FALSE(c.tailTrackingEnabled_);
// cannot turn on tail hits tracking
auto newConfig = c.getConfig();
newConfig.addExtraConfig(2);
EXPECT_THROW(c.setConfig(newConfig), std::invalid_argument);
}
}
} // namespace cachelib
} // namespace facebook
| 34.387879 | 80 | 0.634914 | [
"object",
"vector"
] |
a4923a00c3427ee7cea538c084eead1ebcbb80bb | 3,467 | hpp | C++ | engine/math/VectorNeon.hpp | wzhengsen/ouzel | b3b99c42b39efd2998c03967ee8d5b3e91305167 | [
"Unlicense"
] | null | null | null | engine/math/VectorNeon.hpp | wzhengsen/ouzel | b3b99c42b39efd2998c03967ee8d5b3e91305167 | [
"Unlicense"
] | null | null | null | engine/math/VectorNeon.hpp | wzhengsen/ouzel | b3b99c42b39efd2998c03967ee8d5b3e91305167 | [
"Unlicense"
] | null | null | null | // Ouzel by Elviss Strazdins
#ifndef OUZEL_MATH_VECTOR_NEON_HPP
#define OUZEL_MATH_VECTOR_NEON_HPP
#include "Vector.hpp"
#ifdef __ARM_NEON__
# include <arm_neon.h>
namespace omath
{
template <>
inline auto operator-(const Vector<float, 4>& vector) noexcept
{
Vector<float, 4> result;
vst1q_f32(result.v, vnegq_f32(vld1q_f32(vector.v)));
return result;
}
template <>
inline void negate(Vector<float, 4>& vector) noexcept
{
vst1q_f32(vector.v, vnegq_f32(vld1q_f32(vector.v)));
}
template <>
[[nodiscard]] inline auto operator+(const Vector<float, 4>& vector1,
const Vector<float, 4>& vector2) noexcept
{
Vector<float, 4> result;
vst1q_f32(result.v, vaddq_f32(vld1q_f32(vector1.v), vld1q_f32(vector2.v)));
return result;
}
template <>
inline auto& operator+=(Vector<float, 4>& vector1,
const Vector<float, 4>& vector2) noexcept
{
vst1q_f32(vector1.v, vaddq_f32(vld1q_f32(vector1.v), vld1q_f32(vector2.v)));
return vector1;
}
template <>
[[nodiscard]] inline auto operator-(const Vector<float, 4>& vector1,
const Vector<float, 4>& vector2) noexcept
{
Vector<float, 4> result;
vst1q_f32(result.v, vsubq_f32(vld1q_f32(vector1.v), vld1q_f32(vector2.v)));
return result;
}
template <>
inline auto& operator-=(Vector<float, 4>& vector1,
const Vector<float, 4>& vector2) noexcept
{
vst1q_f32(vector1.v, vsubq_f32(vld1q_f32(vector1.v), vld1q_f32(vector2.v)));
return vector1;
}
template <>
[[nodiscard]] inline auto operator*(const Vector<float, 4>& vector,
const float scalar) noexcept
{
Vector<float, 4> result;
const auto s = vdupq_n_f32(scalar);
vst1q_f32(result.v, vmulq_f32(vld1q_f32(vector.v), s));
return result;
}
template <>
inline auto& operator*=(Vector<float, 4>& vector,
const float scalar) noexcept
{
const auto s = vdupq_n_f32(scalar);
vst1q_f32(vector.v, vmulq_f32(vld1q_f32(vector.v), s));
return vector;
}
template <>
[[nodiscard]] inline auto operator/(const Vector<float, 4>& vector,
const float scalar) noexcept
{
Vector<float, 4> result;
const auto s = vdupq_n_f32(scalar);
vst1q_f32(result.v, vdivq_f32(vld1q_f32(vector.v), s));
return result;
}
template <>
inline auto& operator/=(Vector<float, 4>& vector,
const float scalar) noexcept
{
const auto s = vdupq_n_f32(scalar);
vst1q_f32(vector.v, vdivq_f32(vld1q_f32(vector.v), s));
return vector;
}
template <>
[[nodiscard]] inline auto dot(const Vector<float, 4>& vector1,
const Vector<float, 4>& vector2) noexcept
{
const auto t1 = vmulq_f32(vld1q_f32(vector1.v), vld1q_f32(vector2.v));
const auto t2 = vaddq_f32(t1, vrev64q_f32(t1));
const auto t3 = vaddq_f32(t2, vcombine_f32(vget_high_f32(t2), vget_low_f32(t2)));
const float result = vgetq_lane_f32(t3, 0);
return result;
}
}
#endif // __ARM_NEON__
#endif // OUZEL_MATH_VECTOR_NEON_HPP
| 30.412281 | 89 | 0.582348 | [
"vector"
] |
a49d603f16d8a28f9aa0eedb9be016b0d6552bd2 | 13,664 | hpp | C++ | include/adm/elements/audio_content.hpp | IRT-Open-Source/libadm | 442f51229e760db1caca4b962bfaad58a9c7d9b8 | [
"Apache-2.0"
] | 14 | 2018-07-24T12:18:05.000Z | 2020-05-11T19:14:49.000Z | include/adm/elements/audio_content.hpp | IRT-Open-Source/libadm | 442f51229e760db1caca4b962bfaad58a9c7d9b8 | [
"Apache-2.0"
] | 19 | 2018-07-30T15:02:54.000Z | 2020-05-21T10:13:19.000Z | include/adm/elements/audio_content.hpp | IRT-Open-Source/libadm | 442f51229e760db1caca4b962bfaad58a9c7d9b8 | [
"Apache-2.0"
] | 7 | 2018-07-24T12:18:12.000Z | 2020-02-14T11:18:12.000Z | /// @file audio_content.hpp
#pragma once
#include <boost/optional.hpp>
#include <memory>
#include <vector>
#include "adm/elements/audio_content_id.hpp"
#include "adm/elements/audio_object.hpp"
#include "adm/elements/dialogue.hpp"
#include "adm/elements/label.hpp"
#include "adm/elements/loudness_metadata.hpp"
#include "adm/elements_fwd.hpp"
#include "adm/helper/element_range.hpp"
#include "adm/detail/named_option_helper.hpp"
#include "adm/export.h"
#include "adm/detail/auto_base.hpp"
namespace adm {
class Document;
/// @brief Tag for NamedType ::AudioContentName
struct AudioContentNameTag {};
/// @brief NamedType for the audioContentName attribute
using AudioContentName = detail::NamedType<std::string, AudioContentNameTag>;
/// @brief Tag for NamedType ::AudioContentLanguage
struct AudioContentLanguageTag {};
/// @brief NamedType for the language attribute of the
/// audioContent element
using AudioContentLanguage =
detail::NamedType<std::string, AudioContentLanguageTag>;
/// @brief Tag for AudioContent
struct AudioContentTag {};
namespace detail {
using AudioContentBase = HasParameters<VectorParameter<Labels>,
VectorParameter<LoudnessMetadatas>>;
} // namespace detail
/**
* @brief Class representation of the audioContent ADM element
*
* \rst
* +--------------------------+----------------------------------+----------------------------+
* | ADM Parameter | Parameter Type | Pattern Type |
* +==========================+==================================+============================+
* | audioContentID | :class:`AudioContentId` | :class:`RequiredParameter` |
* +--------------------------+----------------------------------+----------------------------+
* | audioContentName | :type:`AudioContentName` | :class:`RequiredParameter` |
* +--------------------------+----------------------------------+----------------------------+
* | audioContentLanguage | :type:`AudioContentLanguage` | :class:`OptionalParameter` |
* +--------------------------+----------------------------------+----------------------------+
* | audioContentLabel | :type:`Labels` | :class:`VectorParameter` |
* +--------------------------+----------------------------------+----------------------------+
* | loudnessMetadata | :type:`LoudnessMetadatas` | :class:`VectorParameter` |
* +--------------------------+----------------------------------+----------------------------+
* | - dialogue | - :type:`DialogueId` | custom |
* | - nonDialogueContentKind | - :type:`ContentKind` | |
* | - dialogueContentKind | - :type:`NonDialogueContentKind` | |
* | - mixedContentKind | - :type:`DialogueContentKind` | |
* | | - :type:`MixedContentKind` | |
* +--------------------------+----------------------------------+----------------------------+
* \endrst
*
* For the behaviour of dialogue elements, see set(DialogueId).
*/
class AudioContent : public std::enable_shared_from_this<AudioContent>,
private detail::AudioContentBase {
public:
typedef AudioContentTag tag;
/// Type that holds the id for this element;
typedef AudioContentId id_type;
/**
* @brief Static create function template
*
* Templated static create function which accepts a variable
* number of ADM parameters in random order after the
* mandatory ADM parameters. The actual constructor is
* private. This way it is ensured, that an AudioContent
* object can only be created as a `std::shared_ptr`.
*/
template <typename... Parameters>
static std::shared_ptr<AudioContent> create(
AudioContentName name, Parameters... optionalNamedArgs);
/**
* @brief Copy AudioContent
*
* The actual copy constructor is private to ensure that an
* AudioContent can only be created as a `std::shared_ptr`.
* This is not a deep copy! All referenced objects will be
* disconnected.
*/
ADM_EXPORT std::shared_ptr<AudioContent> copy() const;
/**
* @brief ADM parameter getter template
*
* Templated getter with the wanted ADM parameter type as
* template argument. If currently no value is available
* trying to get the ADM parameter will result in an
* exception. Check with the has method before
*/
template <typename Parameter>
Parameter get() const;
/**
* @brief ADM parameter has template
*
* Templated has method with the ADM parameter type as
* template argument. Returns true if the ADM parameter is
* set or has a default value.
*/
template <typename Parameter>
bool has() const;
/**
* @brief ADM parameter isDefault template
*
* Templated isDefault method with the ADM parameter type as
* template argument. Returns true if the ADM parameter is
* the default value.
*/
template <typename Parameter>
bool isDefault() const;
using detail::AudioContentBase::add;
using detail::AudioContentBase::remove;
using detail::AudioContentBase::set;
/// @brief AudioContentId setter
ADM_EXPORT void set(AudioContentId id);
/// @brief AudioContentName setter
ADM_EXPORT void set(AudioContentName name);
/// @brief AudioContentLanguage setter
ADM_EXPORT void set(AudioContentLanguage language);
///@{
/**
* @brief Dialogue setter
*
* \note Setting one of the dialogue kinds always ensures
* consistency. If
* ::DialogueId is set the corresponding ContentKind will be
* set to undefined. If one of the ContentKinds is set
* ::DialogueId will be set accordingly.
*/
ADM_EXPORT void set(DialogueId kind);
ADM_EXPORT void set(ContentKind kind);
ADM_EXPORT void set(NonDialogueContentKind kind);
ADM_EXPORT void set(DialogueContentKind kind);
ADM_EXPORT void set(MixedContentKind kind);
///@}
/**
* @brief ADM parameter unset template
*
* Templated unset method with the ADM parameter type as
* template argument. Removes an ADM parameter if it is
* optional or resets it to the default value if there is
* one.
*
* \note Unsetting ::DialogueId automatically unsets the
* corresponding ContentKind. Unsetting one of the
* ContentKinds automatically unsets
* ::DialogueId.
*/
template <typename Parameter>
void unset();
/// @brief Add reference to an AudioObject
ADM_EXPORT bool addReference(std::shared_ptr<AudioObject> object);
/**
* @brief Get references to ADM elements template
*
* Templated get method with the ADM parameter type as
*template argument. Returns a set of all references to the
*adm elements with the specified type.
*/
template <typename Element>
ElementRange<const Element> getReferences() const;
/**
* @brief Get references to ADM elements template
*
* Templated get method with the ADM parameter type as
*template argument. Returns a set of all references to the
*adm elements with the specified type.
*/
template <typename Element>
ElementRange<Element> getReferences();
// template <typename Element>
// ElementRange<const Element> getReferences()
// const;
/// @brief Remove reference to an AudioObject
ADM_EXPORT void removeReference(std::shared_ptr<AudioObject> object);
/**
* @brief Clear references to Elements template
*
* Templated clear method with the ADM parameter type as
*template argument. Removes all references to the adm
*elements with the specified type.
*/
template <typename Element>
void clearReferences();
/**
* @brief Print overview to ostream
*/
ADM_EXPORT void print(std::ostream& os) const;
/// Get adm::Document this element belongs to
ADM_EXPORT std::weak_ptr<Document> getParent() const;
private:
friend class AudioContentAttorney;
ADM_EXPORT explicit AudioContent(AudioContentName name);
ADM_EXPORT AudioContent(const AudioContent&) = default;
ADM_EXPORT AudioContent(AudioContent&&) = default;
using detail::AudioContentBase::get;
using detail::AudioContentBase::has;
using detail::AudioContentBase::isDefault;
using detail::AudioContentBase::unset;
ADM_EXPORT AudioContentId
get(detail::ParameterTraits<AudioContentId>::tag) const;
ADM_EXPORT AudioContentName
get(detail::ParameterTraits<AudioContentName>::tag) const;
ADM_EXPORT AudioContentLanguage
get(detail::ParameterTraits<AudioContentLanguage>::tag) const;
ADM_EXPORT DialogueId get(detail::ParameterTraits<DialogueId>::tag) const;
ADM_EXPORT ContentKind get(detail::ParameterTraits<ContentKind>::tag) const;
ADM_EXPORT NonDialogueContentKind
get(detail::ParameterTraits<NonDialogueContentKind>::tag) const;
ADM_EXPORT DialogueContentKind
get(detail::ParameterTraits<DialogueContentKind>::tag) const;
ADM_EXPORT MixedContentKind
get(detail::ParameterTraits<MixedContentKind>::tag) const;
ADM_EXPORT bool has(detail::ParameterTraits<AudioContentId>::tag) const;
ADM_EXPORT bool has(detail::ParameterTraits<AudioContentName>::tag) const;
ADM_EXPORT bool has(
detail::ParameterTraits<AudioContentLanguage>::tag) const;
ADM_EXPORT bool has(detail::ParameterTraits<DialogueId>::tag) const;
ADM_EXPORT bool has(detail::ParameterTraits<ContentKind>::tag) const;
ADM_EXPORT bool has(
detail::ParameterTraits<NonDialogueContentKind>::tag) const;
ADM_EXPORT bool has(
detail::ParameterTraits<DialogueContentKind>::tag) const;
ADM_EXPORT bool has(detail::ParameterTraits<MixedContentKind>::tag) const;
template <typename Tag>
bool isDefault(Tag) const {
return false;
}
ADM_EXPORT void unset(detail::ParameterTraits<AudioContentLanguage>::tag);
ADM_EXPORT void unset(detail::ParameterTraits<DialogueId>::tag);
ADM_EXPORT void unset(detail::ParameterTraits<ContentKind>::tag);
ADM_EXPORT void unset(detail::ParameterTraits<NonDialogueContentKind>::tag);
ADM_EXPORT void unset(detail::ParameterTraits<DialogueContentKind>::tag);
ADM_EXPORT void unset(detail::ParameterTraits<MixedContentKind>::tag);
ADM_EXPORT ElementRange<const AudioObject> getReferences(
detail::ParameterTraits<AudioObject>::tag) const;
ADM_EXPORT ElementRange<AudioObject> getReferences(
detail::ParameterTraits<AudioObject>::tag);
ADM_EXPORT void clearReferences(detail::ParameterTraits<AudioObject>::tag);
ADM_EXPORT void disconnectReferences();
void setParent(std::weak_ptr<Document> document);
std::weak_ptr<Document> parent_;
AudioContentId id_;
AudioContentName name_;
boost::optional<AudioContentLanguage> language_;
std::vector<std::shared_ptr<AudioObject>> audioObjects_;
boost::optional<DialogueId> dialogueId_;
boost::optional<NonDialogueContentKind> nonDialogueContentKind_;
boost::optional<DialogueContentKind> dialogueContentKind_;
boost::optional<MixedContentKind> mixedContentKind_;
};
ADM_EXPORT std::ostream& operator<<(
std::ostream& stream, const LoudnessMetadatas& loudnessMetaDatas);
// ---- Implementation ---- //
template <typename... Parameters>
std::shared_ptr<AudioContent> AudioContent::create(
AudioContentName name, Parameters... optionalNamedArgs) {
std::shared_ptr<AudioContent> content(new AudioContent(name));
detail::setNamedOptionHelper(
content, std::forward<Parameters>(optionalNamedArgs)...);
return content;
}
template <typename Parameter>
Parameter AudioContent::get() const {
typedef typename detail::ParameterTraits<Parameter>::tag Tag;
return get(Tag());
}
template <typename Parameter>
bool AudioContent::has() const {
typedef typename detail::ParameterTraits<Parameter>::tag Tag;
return has(Tag());
}
template <typename Parameter>
bool AudioContent::isDefault() const {
typedef typename detail::ParameterTraits<Parameter>::tag Tag;
return isDefault(Tag());
}
template <typename Parameter>
void AudioContent::unset() {
typedef typename detail::ParameterTraits<Parameter>::tag Tag;
return unset(Tag());
}
template <typename Element>
ElementRange<const Element> AudioContent::getReferences() const {
typedef typename detail::ParameterTraits<Element>::tag Tag;
return getReferences(Tag());
}
inline ElementRange<const AudioObject> AudioContent::getReferences(
detail::ParameterTraits<AudioObject>::tag) const {
return detail::makeElementRange<AudioObject>(audioObjects_);
}
template <typename Element>
ElementRange<Element> AudioContent::getReferences() {
typedef typename detail::ParameterTraits<Element>::tag Tag;
return getReferences(Tag());
}
inline ElementRange<AudioObject> AudioContent::getReferences(
detail::ParameterTraits<AudioObject>::tag) {
return detail::makeElementRange<AudioObject>(audioObjects_);
}
template <typename Element>
void AudioContent::clearReferences() {
typedef typename detail::ParameterTraits<Element>::tag Tag;
clearReferences(Tag());
}
} // namespace adm
| 37.745856 | 97 | 0.650176 | [
"object",
"vector"
] |
a4a36038e8a112ad54a207f2d117e52dbf58e333 | 4,543 | cpp | C++ | Source/Camera/Src/PolarCamera.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 12 | 2019-01-08T23:10:37.000Z | 2021-06-04T09:48:42.000Z | Source/Camera/Src/PolarCamera.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 38 | 2017-04-05T00:27:24.000Z | 2018-12-25T08:34:04.000Z | Source/Camera/Src/PolarCamera.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 4 | 2019-03-27T10:07:32.000Z | 2021-07-15T03:22:27.000Z | #include "Camera/PolarCamera.h"
#include "Math/Transform.h"
#include "Math/Geometry.h"
#include "Utils/Macros.h"
namespace Azura {
namespace {
const Vector3f UNIT_LOOK = Vector3f(0, 0, 1);
const Vector3f UNIT_RIGHT = Vector3f(1, 0, 0);
const Vector3f UNIT_UP = Vector3f(0, 1, 0);
const Vector3f UNIT_EYE = Vector3f(0, 0, 0);
} // namespace
PolarCamera::PolarCamera(U32 width, U32 height)
: Camera(width, height) {
PolarCamera::Recompute();
}
PolarCamera::PolarCamera(U32 width, U32 height, float thethaDeg, float phiDeg, float zoom)
: Camera(width, height), m_theta(Math::ToRadians(thethaDeg)), m_phi(Math::ToRadians(phiDeg)), m_zoom(zoom) {
PolarCamera::Recompute();
}
void PolarCamera::Recompute() {
const Matrix4f transform = Matrix4f::FromRotationMatrix(Matrix4f::RotationY(m_theta)) *
Matrix4f::FromRotationMatrix(Matrix3f::RotationX(m_phi)) *
Matrix4f::FromTranslationVector(Vector3f(0, 0, 1) * m_zoom);
m_look = Transform::Downgrade(transform * Vector4f(UNIT_LOOK, 0.0f));
m_up = Transform::Downgrade(transform * Vector4f(UNIT_UP, 0.0f));
m_right = Transform::Downgrade(transform * Vector4f(UNIT_RIGHT, 0.0f));
// Position must be affected by Translation
m_eye = Transform::Downgrade(transform * Vector4f(UNIT_EYE, 1.0f));
m_view = Transform::LookAt(m_ref, m_eye, m_up);
m_proj = Transform::Perspective(45.0f, 16.0f / 9.0f, 0.1f, 100.0f);
m_viewProj = m_proj * m_view;
m_invViewProj = m_viewProj.Inverse();
}
void PolarCamera::OnMouseEvent(MouseEvent mouseEvent) {
if (mouseEvent.m_internalType != MouseEventType::Drag)
{
return;
}
const float anglePerPixel = 5;
RotateAboutUp(mouseEvent.m_eventX * anglePerPixel * m_sensitivity);
RotateAboutRight(mouseEvent.m_eventY * anglePerPixel * m_sensitivity);
Recompute();
}
void PolarCamera::OnKeyEvent(KeyEvent keyEvent) {
if (keyEvent.m_internalType == KeyEventType::KeyPress) {
switch (keyEvent.m_key) {
case KeyboardKey::W:
m_moveUpFactor = 1;
break;
case KeyboardKey::S:
m_moveUpFactor = -1;
break;
case KeyboardKey::D:
m_moveRightFactor = -1;
break;
case KeyboardKey::A:
m_moveRightFactor = 1;
break;
case KeyboardKey::Q:
m_zoomFactor = 1;
break;
case KeyboardKey::E:
m_zoomFactor = -1;
break;
case KeyboardKey::Unmapped:
case KeyboardKey::Esc:
case KeyboardKey::Up:
case KeyboardKey::Down:
case KeyboardKey::Left:
case KeyboardKey::Right:
case KeyboardKey::T:
case KeyboardKey::Y:
default:
break;
}
} else if (keyEvent.m_internalType == KeyEventType::KeyRelease) {
switch (keyEvent.m_key) {
case KeyboardKey::W:
m_moveUpFactor = 0;
break;
case KeyboardKey::S:
m_moveUpFactor = 0;
break;
case KeyboardKey::D:
m_moveRightFactor = 0;
break;
case KeyboardKey::A:
m_moveRightFactor = 0;
break;
case KeyboardKey::Q:
m_zoomFactor = 0;
break;
case KeyboardKey::E:
m_zoomFactor = 0;
break;
case KeyboardKey::Unmapped:
case KeyboardKey::Esc:
case KeyboardKey::Up:
case KeyboardKey::Down:
case KeyboardKey::Left:
case KeyboardKey::Right:
case KeyboardKey::T:
case KeyboardKey::Y:
default:
break;
}
}
}
void PolarCamera::SetZoom(float value) {
m_zoom = value;
}
void PolarCamera::SetZoomAndRecompute(float value) {
SetZoom(value);
Recompute();
}
void PolarCamera::RotateAboutUp(float deg) {
m_theta += Math::ToRadians(deg);
}
void PolarCamera::RotateAboutRight(float deg) {
m_phi += Math::ToRadians(deg);
}
void PolarCamera::TranslateAlongLook(float amount) {
m_zoom += amount;
}
void PolarCamera::SetStepSize(float value) {
m_stepSize = value;
}
void PolarCamera::Update(float timeDelta) {
const float distance = m_stepSize * timeDelta;
bool needsRecompute = false;
if (m_moveUpFactor != 0) {
RotateAboutRight(distance * m_moveUpFactor);
needsRecompute = true;
}
if (m_moveRightFactor != 0) {
RotateAboutUp(distance * m_moveRightFactor);
needsRecompute = true;
}
if (m_zoomFactor != 0) {
TranslateAlongLook(distance * m_zoomFactor);
needsRecompute = true;
}
if (needsRecompute) {
Recompute();
}
}
} // namespace Azura
| 24.690217 | 111 | 0.643848 | [
"geometry",
"transform"
] |
a4a8064398d2c3c6ab9730cf055accc376947e30 | 5,586 | hpp | C++ | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/Area.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 5 | 2021-05-27T21:50:33.000Z | 2022-01-28T11:54:32.000Z | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/Area.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | null | null | null | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/Area.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 1 | 2021-01-04T21:12:05.000Z | 2021-01-04T21:12:05.000Z | #ifndef GODOT_CPP_AREA_HPP
#define GODOT_CPP_AREA_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Area.hpp"
#include "CollisionObject.hpp"
namespace godot {
class Node;
class Area : public CollisionObject {
struct ___method_bindings {
godot_method_bind *mb__area_enter_tree;
godot_method_bind *mb__area_exit_tree;
godot_method_bind *mb__area_inout;
godot_method_bind *mb__body_enter_tree;
godot_method_bind *mb__body_exit_tree;
godot_method_bind *mb__body_inout;
godot_method_bind *mb_get_angular_damp;
godot_method_bind *mb_get_audio_bus;
godot_method_bind *mb_get_collision_layer;
godot_method_bind *mb_get_collision_layer_bit;
godot_method_bind *mb_get_collision_mask;
godot_method_bind *mb_get_collision_mask_bit;
godot_method_bind *mb_get_gravity;
godot_method_bind *mb_get_gravity_distance_scale;
godot_method_bind *mb_get_gravity_vector;
godot_method_bind *mb_get_linear_damp;
godot_method_bind *mb_get_overlapping_areas;
godot_method_bind *mb_get_overlapping_bodies;
godot_method_bind *mb_get_priority;
godot_method_bind *mb_get_reverb_amount;
godot_method_bind *mb_get_reverb_bus;
godot_method_bind *mb_get_reverb_uniformity;
godot_method_bind *mb_get_space_override_mode;
godot_method_bind *mb_is_gravity_a_point;
godot_method_bind *mb_is_monitorable;
godot_method_bind *mb_is_monitoring;
godot_method_bind *mb_is_overriding_audio_bus;
godot_method_bind *mb_is_using_reverb_bus;
godot_method_bind *mb_overlaps_area;
godot_method_bind *mb_overlaps_body;
godot_method_bind *mb_set_angular_damp;
godot_method_bind *mb_set_audio_bus;
godot_method_bind *mb_set_audio_bus_override;
godot_method_bind *mb_set_collision_layer;
godot_method_bind *mb_set_collision_layer_bit;
godot_method_bind *mb_set_collision_mask;
godot_method_bind *mb_set_collision_mask_bit;
godot_method_bind *mb_set_gravity;
godot_method_bind *mb_set_gravity_distance_scale;
godot_method_bind *mb_set_gravity_is_point;
godot_method_bind *mb_set_gravity_vector;
godot_method_bind *mb_set_linear_damp;
godot_method_bind *mb_set_monitorable;
godot_method_bind *mb_set_monitoring;
godot_method_bind *mb_set_priority;
godot_method_bind *mb_set_reverb_amount;
godot_method_bind *mb_set_reverb_bus;
godot_method_bind *mb_set_reverb_uniformity;
godot_method_bind *mb_set_space_override_mode;
godot_method_bind *mb_set_use_reverb_bus;
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "Area"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
enum SpaceOverride {
SPACE_OVERRIDE_DISABLED = 0,
SPACE_OVERRIDE_COMBINE = 1,
SPACE_OVERRIDE_COMBINE_REPLACE = 2,
SPACE_OVERRIDE_REPLACE = 3,
SPACE_OVERRIDE_REPLACE_COMBINE = 4,
};
// constants
static Area *_new();
// methods
void _area_enter_tree(const int64_t id);
void _area_exit_tree(const int64_t id);
void _area_inout(const int64_t arg0, const RID arg1, const int64_t arg2, const int64_t arg3, const int64_t arg4);
void _body_enter_tree(const int64_t id);
void _body_exit_tree(const int64_t id);
void _body_inout(const int64_t arg0, const RID arg1, const int64_t arg2, const int64_t arg3, const int64_t arg4);
real_t get_angular_damp() const;
String get_audio_bus() const;
int64_t get_collision_layer() const;
bool get_collision_layer_bit(const int64_t bit) const;
int64_t get_collision_mask() const;
bool get_collision_mask_bit(const int64_t bit) const;
real_t get_gravity() const;
real_t get_gravity_distance_scale() const;
Vector3 get_gravity_vector() const;
real_t get_linear_damp() const;
Array get_overlapping_areas() const;
Array get_overlapping_bodies() const;
real_t get_priority() const;
real_t get_reverb_amount() const;
String get_reverb_bus() const;
real_t get_reverb_uniformity() const;
Area::SpaceOverride get_space_override_mode() const;
bool is_gravity_a_point() const;
bool is_monitorable() const;
bool is_monitoring() const;
bool is_overriding_audio_bus() const;
bool is_using_reverb_bus() const;
bool overlaps_area(const Node *area) const;
bool overlaps_body(const Node *body) const;
void set_angular_damp(const real_t angular_damp);
void set_audio_bus(const String name);
void set_audio_bus_override(const bool enable);
void set_collision_layer(const int64_t collision_layer);
void set_collision_layer_bit(const int64_t bit, const bool value);
void set_collision_mask(const int64_t collision_mask);
void set_collision_mask_bit(const int64_t bit, const bool value);
void set_gravity(const real_t gravity);
void set_gravity_distance_scale(const real_t distance_scale);
void set_gravity_is_point(const bool enable);
void set_gravity_vector(const Vector3 vector);
void set_linear_damp(const real_t linear_damp);
void set_monitorable(const bool enable);
void set_monitoring(const bool enable);
void set_priority(const real_t priority);
void set_reverb_amount(const real_t amount);
void set_reverb_bus(const String name);
void set_reverb_uniformity(const real_t amount);
void set_space_override_mode(const int64_t enable);
void set_use_reverb_bus(const bool enable);
};
}
#endif | 37.24 | 245 | 0.821339 | [
"object",
"vector"
] |
a4b599471d883d6fa568c3e24626c307ed691bb1 | 2,095 | cpp | C++ | examples/mpc.cpp | PepMS/eagle-mpc | 522b4af6f31dcdec72c9c461ace28bb774aa4057 | [
"BSD-3-Clause"
] | 10 | 2021-07-14T10:50:20.000Z | 2022-03-14T06:27:13.000Z | examples/mpc.cpp | PepMS/multicopter-mpc | 522b4af6f31dcdec72c9c461ace28bb774aa4057 | [
"BSD-3-Clause"
] | 29 | 2020-06-04T08:38:52.000Z | 2020-09-25T10:26:25.000Z | examples/mpc.cpp | PepMS/eagle-mpc | 522b4af6f31dcdec72c9c461ace28bb774aa4057 | [
"BSD-3-Clause"
] | 2 | 2021-11-02T02:14:45.000Z | 2022-01-10T11:32:59.000Z | // #include <iostream>
// #include "crocoddyl/core/optctrl/shooting.hpp"
// #include "crocoddyl/core/solvers/box-fddp.hpp"
// #include "crocoddyl/core/solvers/fddp.hpp"
// #include "crocoddyl/core/utils/callbacks.hpp"
// #include "crocoddyl/multibody/actuations/multicopter-base.hpp"
// #include "crocoddyl/multibody/states/multibody.hpp"
// #include "eagle_mpc/mpc-controllers/carrot-mpc.hpp"
// #include "eagle_mpc/utils/parser_yaml.hpp"
// #include "eagle_mpc/utils/params_server.hpp"
// #include "eagle_mpc/path.h"
// #include "eagle_mpc/sbfddp.hpp"
int main(void) {
// eagle_mpc::ParserYaml parser_aux(
// "/home/pepms/robotics/libraries/multicopter-mpc/config/trajectory/trajectory.yaml", "", true);
// eagle_mpc::ParamsServer server_aux(parser_aux.get_params());
// std::string trajectory_yaml = server_aux.getParam<std::string>("trajectory_file");
// boost::shared_ptr<eagle_mpc::Trajectory> trajectory = eagle_mpc::Trajectory::create();
// trajectory->autoSetup("/home/pepms/robotics/libraries/multicopter-mpc/config/trajectory/" + trajectory_yaml);
// // boost::shared_ptr<crocoddyl::ShootingProblem> problem =
// // trajectory->createProblem(10, false, trajectory->get_robot_state()->zero(), "IntegratedActionModelEuler");
// // boost::shared_ptr<crocoddyl::SolverBoxFDDP> solver = boost::make_shared<crocoddyl::SolverBoxFDDP>(problem);
// boost::shared_ptr<crocoddyl::ShootingProblem> problem =
// trajectory->createProblem(10, true, "IntegratedActionModelEuler");
// boost::shared_ptr<eagle_mpc::SolverSbFDDP> solver =
// boost::make_shared<eagle_mpc::SolverSbFDDP>(problem, trajectory->get_squash());
// std::vector<boost::shared_ptr<crocoddyl::CallbackAbstract>> callbacks;
// callbacks.push_back(boost::make_shared<crocoddyl::CallbackVerbose>());
// solver->setCallbacks(callbacks);
// solver->solve(crocoddyl::DEFAULT_VECTOR, crocoddyl::DEFAULT_VECTOR);
// eagle_mpc::CarrotMpc carrot_mpc(trajectory,
// "/home/pepms/robotics/libraries/multicopter-mpc/config/mpc/mpc.yaml");
} | 48.72093 | 118 | 0.728878 | [
"vector"
] |
8a54ed2a290ab84656717f92e0ff49b84ba82594 | 1,526 | cpp | C++ | Sky.cpp | xLightling/DX11Starter | 21b7cecab109e8e55b65c6c249c630a08e695c66 | [
"MIT"
] | null | null | null | Sky.cpp | xLightling/DX11Starter | 21b7cecab109e8e55b65c6c249c630a08e695c66 | [
"MIT"
] | null | null | null | Sky.cpp | xLightling/DX11Starter | 21b7cecab109e8e55b65c6c249c630a08e695c66 | [
"MIT"
] | null | null | null | #include "Sky.h"
Sky::Sky(
std::shared_ptr<Mesh> _mesh,
std::shared_ptr<SimpleVertexShader> _vertexShader,
std::shared_ptr<SimplePixelShader> _pixelShader,
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> _cubemap,
Microsoft::WRL::ComPtr<ID3D11SamplerState> _sampler,
Microsoft::WRL::ComPtr<ID3D11Device> _device)
{
mesh = _mesh;
cubemap = _cubemap;
sampler = _sampler;
vertexShader = _vertexShader;
pixelShader = _pixelShader;
D3D11_RASTERIZER_DESC rDesc = {};
rDesc.FillMode = D3D11_FILL_SOLID;
rDesc.CullMode = D3D11_CULL_FRONT;
_device->CreateRasterizerState(&rDesc, rasterizerState.GetAddressOf());
D3D11_DEPTH_STENCIL_DESC dDesc = {};
dDesc.DepthEnable = true;
dDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
_device->CreateDepthStencilState(&dDesc, depthState.GetAddressOf());
}
Sky::~Sky()
{
}
void Sky::Draw(Microsoft::WRL::ComPtr<ID3D11DeviceContext> _context, std::shared_ptr<Camera> _camera)
{
_context->RSSetState(rasterizerState.Get());
_context->OMSetDepthStencilState(depthState.Get(), 0);
vertexShader->SetMatrix4x4("view", _camera->GetViewMatrix());
vertexShader->SetMatrix4x4("projection", _camera->GetProjectionMatrix());
vertexShader->CopyAllBufferData();
vertexShader->SetShader();
pixelShader->SetShaderResourceView("SkyTexture", cubemap.Get());
pixelShader->SetSamplerState("Sampler", sampler.Get());
pixelShader->CopyAllBufferData();
pixelShader->SetShader();
mesh->Draw();
_context->RSSetState(0);
_context->OMSetDepthStencilState(0, 0);
}
| 29.346154 | 101 | 0.761468 | [
"mesh"
] |
8a570aa9eb741c3fe67a654b0b654f12ec2a582f | 538 | hpp | C++ | include/system.hpp | YuZheng0/ParticleModel | 313611cd44af03e4e70e287287b5c9ee2d1e29e9 | [
"MIT"
] | null | null | null | include/system.hpp | YuZheng0/ParticleModel | 313611cd44af03e4e70e287287b5c9ee2d1e29e9 | [
"MIT"
] | null | null | null | include/system.hpp | YuZheng0/ParticleModel | 313611cd44af03e4e70e287287b5c9ee2d1e29e9 | [
"MIT"
] | null | null | null | #ifndef SYSTEM_HPP
#define SYSTEM_HPP
#include <vector>
#include "particle.hpp"
class System
{
public:
System(double,double,double,int);
System();
int numberOfParticles();
bool addParticle(Particle newParticle);
// void getDistance();
double getEnergy();
std::vector<std::vector<double>> coordinates();
//double g2(double,double);
void evolve(double, int);
private:
std::vector<Particle> particles;
//std::vector<double> distances;
double density;
double length;
std::size_t number; //The number of particles
};
#endif
| 17.933333 | 48 | 0.730483 | [
"vector"
] |
8a5faef74c1861bbdc49eab1e0d7ffba033db0db | 4,883 | cpp | C++ | src/assets/Image.cpp | Ghimli/new-ospgl | 31bd84e52d954683671211ff16ce8702bdb87312 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/assets/Image.cpp | Ghimli/new-ospgl | 31bd84e52d954683671211ff16ce8702bdb87312 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/assets/Image.cpp | Ghimli/new-ospgl | 31bd84e52d954683671211ff16ce8702bdb87312 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include "Image.h"
#include "AssetManager.h"
#include <stb/stb_image.h>
#include <sstream>
#include "../util/MathUtil.h"
int Image::get_index(int x, int y)
{
logger->check(x >= 0 && y >= 0 && x < width && y < height,
"Pixel out of bounds ({},{}) / ({},{})", x, y, width, height);
return y * width + x;
}
glm::vec4 Image::sample_bilinear(float x, float y)
{
logger->check(config.in_memory, "Image must be present in RAM for CPU sampling");
int w = get_width();
int h = get_height();
glm::vec2 cf = glm::vec2(x * w, y * h);
float x1 = floor(x * (float)w);
float x2 = ceil(x * (float)w);
float y1 = floor(y * (float)h);
float y2 = ceil(y * (float)h);
glm::vec2 tl = glm::vec2(x1, y1);
glm::vec2 tr = glm::vec2(x2, y1);
glm::vec2 bl = glm::vec2(x1, y2);
glm::vec2 br = glm::vec2(x2, y2);
int tli = get_index(MathUtil::int_repeat((int)tl.x, w - 1), MathUtil::int_clamp((int)tl.y, h - 1));
int tri = get_index(MathUtil::int_repeat((int)tr.x, w - 1), MathUtil::int_clamp((int)tr.y, h - 1));
int bli = get_index(MathUtil::int_repeat((int)bl.x, w - 1), MathUtil::int_clamp((int)bl.y, h - 1));
int bri = get_index(MathUtil::int_repeat((int)br.x, w - 1), MathUtil::int_clamp((int)br.y, h - 1));
glm::vec4 tls = get_rgba(tli);
glm::vec4 trs = get_rgba(tri);
glm::vec4 bls = get_rgba(bli);
glm::vec4 brs = get_rgba(bri);
// Interpolate in X, which we use as the base interp
float x_point = (cf.x - x1) / (x2 - x1);
glm::vec4 xtop = glm::mix(tls, trs, x_point);
glm::vec4 xbot = glm::mix(bls, brs, x_point);
// Interpolate in Y, between xtop and xbot
float y_point = (cf.y - y1) / (y2 - y1);
glm::vec4 interp;
if (x1 == x2 && y1 == y2)
{
// Return any of them
interp = tls;
}
else if (x1 == x2)
{
// Interpolate in y
interp = glm::mix(tls, bls, y_point);
}
else if (y1 == y2)
{
// Interpolate in x
interp = glm::mix(tls, trs, x_point);
}
else
{
interp = glm::mix(xtop, xbot, y_point);
}
return interp;
}
glm::vec4 Image::sample_bilinear(glm::vec2 px)
{
return sample_bilinear(px.x, px.y);
}
glm::dvec4 Image::sample_bilinear_double(glm::dvec2 px)
{
return sample_bilinear_double(px.x, px.y);
}
glm::dvec4 Image::sample_bilinear_double(double x, double y)
{
return sample_bilinear((float)x, (float)y);
}
glm::vec4 Image::get_rgba(int i)
{
return glm::vec4(fdata[i * 4 + 0], fdata[i * 4 + 1], fdata[i * 4 + 2], fdata[i * 4 + 3]);
}
glm::vec4 Image::get_rgba(int x, int y)
{
return get_rgba(get_index(x, y));
}
Image::Image(ImageConfig config, const std::string& path)
{
this->config = config;
int c_dump;
uint8_t* u8data = stbi_load(path.c_str(), &width, &height, &c_dump, 4);
fdata = nullptr;
if (config.upload)
{
logger->debug("Uplading texture to OpenGL");
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLenum source_format;
source_format = GL_RGBA;
GLenum target_format = GL_RGBA;
glTexImage2D(GL_TEXTURE_2D, 0, target_format, width, height, 0, source_format, GL_UNSIGNED_BYTE, u8data);
glGenerateMipmap(GL_TEXTURE_2D);
}
if (config.in_memory)
{
// We must convert image data to floats
fdata = (float*)malloc(width * height * 4 * sizeof(float));
for (size_t i = 0; i < width * height; i++)
{
fdata[i * 4 + 0] = (float)u8data[i * 4 + 0] / 255.0f;
fdata[i * 4 + 1] = (float)u8data[i * 4 + 1] / 255.0f;
fdata[i * 4 + 2] = (float)u8data[i * 4 + 2] / 255.0f;
fdata[i * 4 + 3] = (float)u8data[i * 4 + 3] / 255.0f;
}
}
stbi_image_free(u8data);
}
Image::~Image()
{
if (config.in_memory)
{
if (fdata != nullptr)
{
free(fdata);
fdata = nullptr;
}
}
if (config.upload && id != 0)
{
glDeleteTextures(1, &id);
}
}
static const std::string default_toml = R"-(
upload = true
in_memory = false
)-";
Image* load_image(const std::string& path, const std::string& name, const std::string& pkg, const cpptoml::table& cfg)
{
if (!AssetManager::file_exists(path))
{
logger->error("Could not load image {}, file not found!", path);
return nullptr;
}
std::shared_ptr<cpptoml::table> def_toml = SerializeUtil::load_string(default_toml);
std::shared_ptr<cpptoml::table> sub_ptr = nullptr;
if (cfg.get_table_qualified("image"))
{
sub_ptr = cfg.get_table_qualified("image");
}
else
{
sub_ptr = def_toml;
}
ImageConfig config;
::deserialize(config, *sub_ptr);
Image* n_image = new Image(config, path);
return n_image;
}
| 23.475962 | 126 | 0.652263 | [
"object"
] |
8a66a4095c94be853a2ad7cac06f1d51a7b3fd3b | 6,460 | cpp | C++ | Source/server/src/SimpleHttpServer.cpp | fmiguelgarcia/crossover | 380d12e7cb9f892894889f7a0f25ecd60c775fc7 | [
"MIT"
] | null | null | null | Source/server/src/SimpleHttpServer.cpp | fmiguelgarcia/crossover | 380d12e7cb9f892894889f7a0f25ecd60c775fc7 | [
"MIT"
] | null | null | null | Source/server/src/SimpleHttpServer.cpp | fmiguelgarcia/crossover | 380d12e7cb9f892894889f7a0f25ecd60c775fc7 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2016 Francisco Miguel Garcia
*<francisco.miguel.garcia.rodriguez@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 "SimpleHttpServer.hpp"
#include "ServerSettings.hpp"
#include <QSettings>
#include <QTcpServer>
#include <QTcpSocket>
#include <QStringBuilder>
#include <QTimer>
#include <memory>
#include <algorithm>
using namespace crossOver::server;
using namespace std;
namespace
{
inline QString Http200Response () noexcept
{
return QStringLiteral ("HTTP-1.1 200 OK\r\n\r\n");
}
QString Http401Unauthorized ()
{
const QString rawContent =
QStringLiteral ("HTTP-1.1 401\r\n") %
QStringLiteral ("WWW-Authenticate: Digest user@crossOver.com\r\n") %
QStringLiteral ("Content-Length: 0\r\n") % QStringLiteral ("\r\n");
return rawContent;
}
inline QString HttpHeaderAuthorization () noexcept
{
return QStringLiteral ("Authorization");
}
void debugHttpPackage (shared_ptr<HttpRequestProc> rp)
{
QString httpDgb;
QTextStream os (&httpDgb);
os << "HTTP:\n\tHeaders:";
for (auto header : rp->headers)
os << "\n\t\t" << header.first << ": " << header.second;
os << "\n\tData (" << rp->content.size () << "): " << rp->content;
qDebug () << httpDgb;
}
/// @brief It parses the HTTP headers.
void loadHttpHeaders (shared_ptr<HttpRequestProc> rp)
{
int separatorPos;
QString headerLine;
QString field, value;
do
{
headerLine = rp->client->readLine ();
separatorPos = headerLine.indexOf (QChar (':'));
field = headerLine.leftRef (separatorPos).trimmed ().toString ();
value = headerLine.midRef ((separatorPos > -1) ? (separatorPos + 1)
: (headerLine.size ()))
.trimmed ()
.toString ();
rp->headers.insert (make_pair (field, value));
} while (!rp->isHeaderFinished () && !headerLine.isEmpty ());
}
/// @brief It checks if headers containt a valid Authorization.
/// @return It returns true if this request has a valid authorization.
bool isBasicAuthenticatedValid (shared_ptr<HttpRequestProc> rp,
const vector<QString> &basicAuthRealM)
{
bool isValidAuth = false;
auto itr = rp->headers.find (HttpHeaderAuthorization ());
if (itr != end (rp->headers))
{
// Authentication header has the following format, so we need to extract
// the realm part:
// Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
int spaceIndex = itr->second.indexOf (' ');
if (spaceIndex > 0)
{
rp->realm = itr->second.mid (spaceIndex + 1);
isValidAuth = binary_search (begin (basicAuthRealM),
end (basicAuthRealM), rp->realm);
}
}
return isValidAuth;
}
/// @brief It requests a valid authorization to the client using HTTP 401 code.
void requestUserAuthenticate (shared_ptr<HttpRequestProc> rp)
{
rp->client->write (Http401Unauthorized ().toUtf8 ());
rp->client->flush ();
}
void sendHttp200 (shared_ptr<HttpRequestProc> rp)
{
rp->client->write (Http200Response ().toUtf8 ().constData ());
QTcpSocket * client = rp->client;
QTimer * disconnTimer = new QTimer();
disconnTimer->start( 10000);
disconnTimer->connect( disconnTimer, &QTimer::timeout, client, [client, disconnTimer]() {
client->disconnectFromHost();
// client->deleteLater();
disconnTimer->deleteLater();
});
}
}
SimpleHttpServer::SimpleHttpServer (QObject *parent) : QObject (parent)
{
QSettings settings;
const quint16 port = settings.value ( ServerSettings::httpPort(), 8080).toUInt ();
m_serverSocket = new QTcpServer (this);
connect (m_serverSocket, &QTcpServer::newConnection, this,
&SimpleHttpServer::onNewConnection);
if (!m_serverSocket->listen (QHostAddress::Any, port))
qFatal ("[crossOver::server::Server] It can not listen on port %d", port);
}
void SimpleHttpServer::onNewConnection ()
{
shared_ptr<HttpRequestProc> rp = make_shared<HttpRequestProc>();
rp->client = m_serverSocket->nextPendingConnection ();
connect (rp->client, &QAbstractSocket::disconnected, this, [rp]()
{
rp->client->deleteLater ();
});
connect (rp->client, &QTcpSocket::readyRead, this, [this, rp]()
{
this->onReadyRead (rp);
});
}
void SimpleHttpServer::onReadyRead (shared_ptr<HttpRequestProc> rp)
{
// Read headers
if (!rp->isHeaderFinished ())
loadHttpHeaders (rp);
// Read content
rp->content.append (rp->client->readAll ());
// Check
if (rp->isContentReady ())
{
processRequest (rp);
}
}
void SimpleHttpServer::processRequest (shared_ptr<HttpRequestProc> rp)
{
// debugHttpPackage (rp);
if (!isBasicAuthenticatedValid (rp, m_basicAuthAllowed))
{
requestUserAuthenticate (rp);
return;
}
// Respond to client and close connection.
sendHttp200 (rp);
// Emit payload is ready
emit payLoadReady (rp->realm, rp->content);
}
bool HttpRequestProc::isHeaderFinished () const
{
return headers.find ("") != end (headers);
}
bool HttpRequestProc::isContentReady () const
{
bool ok = false;
int contentLenght;
auto itr = headers.find ("Content-Length");
if (itr != end (headers))
contentLenght = itr->second.toInt (&ok);
return ok && contentLenght == content.size ();
}
void SimpleHttpServer::addBasicAuthentication (const QString &realm)
{
if (!binary_search (begin (m_basicAuthAllowed), end (m_basicAuthAllowed),
realm))
{
m_basicAuthAllowed.push_back (realm);
sort (begin (m_basicAuthAllowed), end (m_basicAuthAllowed));
}
}
| 28.333333 | 91 | 0.69644 | [
"vector"
] |
8a68e279878e265e52a2213fa00446f53d2084e2 | 7,409 | cpp | C++ | lib/ffm-train.cpp | turi-code/python-libffm | 6d3b8f8b8732f8456379c87595048381d3f7df1b | [
"BSD-3-Clause"
] | 205 | 2016-08-06T18:08:12.000Z | 2021-08-29T19:41:58.000Z | lib/ffm-train.cpp | jzhang45/python-libffm | 6d3b8f8b8732f8456379c87595048381d3f7df1b | [
"BSD-3-Clause"
] | 7 | 2016-07-12T06:07:58.000Z | 2019-02-06T13:11:47.000Z | lib/ffm-train.cpp | jzhang45/python-libffm | 6d3b8f8b8732f8456379c87595048381d3f7df1b | [
"BSD-3-Clause"
] | 75 | 2016-07-29T08:48:20.000Z | 2022-02-01T13:54:23.000Z | #include <iostream>
#include <stdexcept>
#include <cstring>
#include <vector>
#include "ffm.h"
using namespace std;
using namespace ffm;
string train_help()
{
return string(
"usage: ffm-train [options] training_set_file [model_file]\n"
"\n"
"options:\n"
"-l <lambda>: set regularization parameter (default 0)\n"
"-k <factor>: set number of latent factors (default 4)\n"
"-t <iteration>: set number of iterations (default 15)\n"
"-r <eta>: set learning rate (default 0.1)\n"
"-s <nr_threads>: set number of threads (default 1)\n"
"-p <path>: set path to the validation set\n"
"--quiet: quiet model (no output)\n"
"--norm: do instance-wise normalization\n"
"--no-rand: disable random update\n");
}
struct Option
{
Option() : param(ffm_get_default_param()), nr_folds(1), do_cv(false) {}
string tr_path, va_path, model_path;
ffm_parameter param;
ffm_int nr_folds;
bool do_cv;
};
Option parse_option(int argc, char **argv)
{
vector<string> args;
for(int i = 0; i < argc; i++)
args.push_back(string(argv[i]));
if(argc == 1)
throw invalid_argument(train_help());
Option opt;
ffm_int i = 1;
for(; i < argc; i++)
{
if(args[i].compare("-t") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify number of iterations after -t");
i++;
opt.param.nr_iters = stoi(args[i]);
if(opt.param.nr_iters <= 0)
throw invalid_argument("number of iterations should be greater than zero");
}
else if(args[i].compare("-k") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify number of factors after -k");
i++;
opt.param.k = stoi(args[i]);
if(opt.param.k <= 0)
throw invalid_argument("number of factors should be greater than zero");
}
else if(args[i].compare("-r") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify eta after -r");
i++;
opt.param.eta = stof(args[i]);
if(opt.param.eta <= 0)
throw invalid_argument("learning rate should be greater than zero");
}
else if(args[i].compare("-l") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify lambda after -l");
i++;
opt.param.lambda = stof(args[i]);
if(opt.param.lambda < 0)
throw invalid_argument("regularization cost should not be smaller than zero");
}
else if(args[i].compare("-s") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify number of threads after -s");
i++;
opt.param.nr_threads = stoi(args[i]);
if(opt.param.nr_threads <= 0)
throw invalid_argument("number of threads should be greater than zero");
}
else if(args[i].compare("-v") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify number of folds after -v");
i++;
opt.nr_folds = stoi(args[i]);
if(opt.nr_folds <= 1)
throw invalid_argument("number of folds should be greater than one");
opt.do_cv = true;
}
else if(args[i].compare("-p") == 0)
{
if(i == argc-1)
throw invalid_argument("need to specify path after -p");
i++;
opt.va_path = args[i];
}
else if(args[i].compare("--norm") == 0)
{
opt.param.normalization= true;
}
else if(args[i].compare("--quiet") == 0)
{
opt.param.quiet = true;
}
else if(args[i].compare("--no-rand") == 0)
{
opt.param.random = false;
}
else
{
break;
}
}
if(i != argc-2 && i != argc-1)
throw invalid_argument("cannot parse command\n");
opt.tr_path = args[i];
i++;
if(i < argc)
{
opt.model_path = string(args[i]);
}
else if(i == argc)
{
const char *ptr = strrchr(&*opt.tr_path.begin(), '/');
if(!ptr)
ptr = opt.tr_path.c_str();
else
++ptr;
opt.model_path = string(ptr) + ".model";
}
else
{
throw invalid_argument("cannot parse argument");
}
return opt;
}
ffm_problem read_problem(string path)
{
int const kMaxLineSize = 1000000;
ffm_problem prob;
prob.l = 0;
prob.n = 0;
prob.m = 0;
prob.X = nullptr;
prob.P = nullptr;
prob.Y = nullptr;
if(path.empty())
return prob;
FILE *f = fopen(path.c_str(), "r");
if(f == nullptr)
throw runtime_error("cannot open " + path);
char line[kMaxLineSize];
ffm_long nnz = 0;
for(ffm_int i = 0; fgets(line, kMaxLineSize, f) != nullptr; i++, prob.l++)
{
strtok(line, " \t");
for(; ; nnz++)
{
char *field_char = strtok(nullptr,":");
strtok(nullptr,":");
strtok(nullptr," \t");
if(field_char == nullptr || *field_char == '\n')
break;
}
}
rewind(f);
prob.X = new ffm_node[nnz];
prob.P = new ffm_long[prob.l+1];
prob.Y = new ffm_float[prob.l];
ffm_long p = 0;
prob.P[0] = 0;
for(ffm_int i = 0; fgets(line, kMaxLineSize, f) != nullptr; i++)
{
char *y_char = strtok(line, " \t");
ffm_float y = (atoi(y_char)>0)? 1.0f : -1.0f;
prob.Y[i] = y;
for(; ; ++p)
{
char *field_char = strtok(nullptr,":");
char *idx_char = strtok(nullptr,":");
char *value_char = strtok(nullptr," \t");
if(field_char == nullptr || *field_char == '\n')
break;
ffm_int field = atoi(field_char);
ffm_int idx = atoi(idx_char);
ffm_float value = atof(value_char);
prob.m = max(prob.m, field+1);
prob.n = max(prob.n, idx+1);
prob.X[p].f = field;
prob.X[p].j = idx;
prob.X[p].v = value;
}
prob.P[i+1] = p;
}
fclose(f);
return prob;
}
void destroy_problem(ffm_problem &prob)
{
delete[] prob.X;
delete[] prob.P;
delete[] prob.Y;
}
int main(int argc, char **argv)
{
Option opt;
try
{
opt = parse_option(argc, argv);
}
catch(invalid_argument &e)
{
cout << e.what() << endl;
return 1;
}
ffm_problem tr, va;
try
{
tr = read_problem(opt.tr_path);
va = read_problem(opt.va_path);
}
catch(runtime_error &e)
{
cout << e.what() << endl;
return 1;
}
if(opt.do_cv)
{
ffm_cross_validation(&tr, opt.nr_folds, opt.param);
}
else
{
ffm_model *model = train_with_validation(&tr, &va, opt.param);
ffm_int status = ffm_save_model(model, opt.model_path.c_str());
if(status != 0)
{
destroy_problem(tr);
destroy_problem(va);
ffm_destroy_model(&model);
return 1;
}
ffm_destroy_model(&model);
}
destroy_problem(tr);
destroy_problem(va);
return 0;
}
| 25.460481 | 94 | 0.509111 | [
"vector",
"model"
] |
8a6a95b028ff1fb08f80b33d5f5eed2f7d444ca7 | 5,276 | cpp | C++ | state_searcher/lib/searcher.cpp | samueljero/TCPwn | 8514a9fa53123e4abe45460d008de2f5d91500f8 | [
"BSD-3-Clause"
] | 14 | 2018-02-20T07:11:40.000Z | 2021-09-23T08:31:59.000Z | state_searcher/lib/searcher.cpp | samueljero/TCPwn | 8514a9fa53123e4abe45460d008de2f5d91500f8 | [
"BSD-3-Clause"
] | 1 | 2018-08-18T23:06:53.000Z | 2018-08-21T00:01:06.000Z | state_searcher/lib/searcher.cpp | samueljero/TCPwn | 8514a9fa53123e4abe45460d008de2f5d91500f8 | [
"BSD-3-Clause"
] | 9 | 2017-12-01T15:45:18.000Z | 2020-04-14T02:42:32.000Z | //== searcher.cpp -----------------------------------------==//
//
// Created on: Apr 27, 2016
// Author: Endadul Hoque (mhoque@purdue.edu)
//==-------------------------------------------------------==//
#include "searcher.h"
#include "config.h"
#define ENABLE_DEBUG
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
int debug = 1;
Searcher::Searcher(Graph *g){
FANCY_ASSERT("Graph can't be NULL", g);
graph = g;
}
bool Searcher::existsAction(Path& p, Action &action) {
for(Path::iterator it = p.begin(), et = p.end(); it != et; ++it){
FANCY_ASSERT("Node can't be null", it->first != NULL);
// check the list of action of this edge
if(it->second){
Edge *edge = it->second;
if(edge->containsAction(action)){
return true;
}
}
}
return false;
}
string Searcher::toString(Path &p){
stringstream ss;
Node *cycle_start = NULL;
bool hasCycle = false;
// Find if the path has a cycle
Path::reverse_iterator last_elem = p.rbegin();
if(last_elem->second){
cycle_start = last_elem->first->getEndNode(last_elem->second);
if(cycle_start){
hasCycle = true;
}
}
for(Path::iterator it = p.begin(), et = p.end(); it != et; ){
if(hasCycle){
if(it->first == cycle_start){
ss << "[";
}
}
ss << "<" << it->first->name << ", \"" << it->second->toStringEdgeConditions() << "\">";
++it;
if(it != et){
ss << " ; ";
}
}
if (hasCycle){
ss << "]+";
}
ss << "\n";
return ss.str();
}
void Searcher::scanForSinglePath(Node* u, Path& path, Action &action) {
bool baseCase = false;
if(u->isOnPath()){
// Reached a cycle
baseCase = true;
}
else if(u->isLeafNode()){
// Reached a leaf node
baseCase = true;
// Add u to the path
path.push_back(std::make_pair(u, (Edge *)NULL));
u->onPath = false;
}
if(baseCase){
// Check if the path is a suitable one
if(existsAction(path, action)){
output_paths.push_back(path);
}
}
else{
// Mark u to be on the path
u->onPath = true;
for(Node::TransitionList::iterator it = u->beginTransitions(), et = u->endTransitions();
it != et; ++it){
// Add (u, edge) to the path
std::pair< Node*, Edge* > path_elem = std::make_pair(u, it->first);
path.push_back(path_elem);
// Explore (v = adj(u, e)
scanForSinglePath(it->second, path, action);
// Remove (u, e) from the path
Path::iterator path_it = std::find(path.begin(), path.end(), path_elem);
if(path_it == path.end()){
FATAL_ERROR("Path must contain <" << path_elem.first->name << ", " << path_elem.second->ID << ">"
<< " and Path is -- " << toString(path));
}
path.erase(path_it, path.end());
}
// Reset u to be not on the path
u->onPath = false;
}
}
bool Searcher::findPaths(Action action) {
Node *root = graph->getRoot();
FANCY_ASSERT("Root node can't be NULL", root != NULL);
// Root node is always on path
root->onPath = true;
output_paths.clear();
// For each edge of the root search for a single path
for(Node::TransitionList::iterator it = root->beginTransitions(), et = root->endTransitions();
it != et; ++it){
// Create a new path
Path path;
// Add (root, the edge)
path.push_back(std::make_pair(root, it->first));
// scan for a single path from it->second
scanForSinglePath(it->second, path, action);
}
if (output_paths.empty())
return false;
else
return true;
}
void Searcher::printPaths(ostream &os){
if(output_paths.empty()){
os << "Found no path for output" << endl;
}
else{
for(std::vector<Path>::iterator it = output_paths.begin(), et = output_paths.end(); it != et;
++it){
os << toString(*it);
}
}
}
string Searcher::toStringPathConditions(Path &p){
stringstream ss;
Node *cycle_start = NULL;
bool hasCycle = false;
// Find if the path has a cycle
Path::reverse_iterator last_elem = p.rbegin();
if(last_elem->second){
cycle_start = last_elem->first->getEndNode(last_elem->second);
if(cycle_start){
hasCycle = true;
}
}
int stepCount = 0;
for(Path::iterator it = p.begin(), et = p.end(); it != et; ){
if(hasCycle){
if(it->first == cycle_start){
ss << "---CYCLE_STARTS_FROM_HERE---\n";
}
}
ss << "step " << stepCount++ << ": " << it->second->toStringEdgeConditions();
++it;
if(it != et){
ss << "\n";
}
}
ss << "\n";
return ss.str();
}
void Searcher::printAbstractTestCases(std::string prefix){
if(output_paths.empty()){
cerr << "Found no path for output" << endl;
return;
}
string filename;
stringstream ss;
int count = 0;
for(std::vector<Path>::iterator it = output_paths.begin(), et = output_paths.end(); it != et;
++it){
ss << prefix << "-" << count << ".txt";
filename = ss.str();
ofstream fout(filename.c_str(), ios_base::out);
if(!fout.is_open())
FATAL_ERROR("Failed to open file: " << filename);
fout << toStringPathConditions(*it).c_str();
fout.close();
ss.str(string()); // clear stream
count++;
}
}
void Searcher::printPaths() {
printPaths(std::cout);
}
| 23.873303 | 105 | 0.572214 | [
"vector"
] |
8a75d3146c6b4b0c938de9c1c9cee653ee4dbf15 | 7,154 | cpp | C++ | src/mod/visualize/airblast_vectors.cpp | fugueinheels/sigsegv-mvm | 092a69d44a3ed9aacd14886037f4093a27ff816b | [
"BSD-2-Clause"
] | 7 | 2021-03-02T02:27:18.000Z | 2022-02-18T00:56:28.000Z | src/mod/visualize/airblast_vectors.cpp | fugueinheels/sigsegv-mvm | 092a69d44a3ed9aacd14886037f4093a27ff816b | [
"BSD-2-Clause"
] | 3 | 2021-11-29T15:53:02.000Z | 2022-02-21T13:09:22.000Z | src/mod/visualize/airblast_vectors.cpp | fugueinheels/sigsegv-mvm | 092a69d44a3ed9aacd14886037f4093a27ff816b | [
"BSD-2-Clause"
] | 5 | 2021-03-04T20:26:11.000Z | 2021-11-26T07:09:24.000Z | #include "mod.h"
#include "stub/tfplayer.h"
#include "stub/tfweaponbase.h"
#if 0 // obsolete as of Inferno Update
namespace Mod::Visualize::Airblast_Vectors
{
ConVar cvar_eye_r("sig_visualize_airblast_vectors_eye_r", "0x00", FCVAR_NOTIFY, "Visualization: eye vector color (red)");
ConVar cvar_eye_g("sig_visualize_airblast_vectors_eye_g", "0xff", FCVAR_NOTIFY, "Visualization: eye vector color (green)");
ConVar cvar_eye_b("sig_visualize_airblast_vectors_eye_b", "0xff", FCVAR_NOTIFY, "Visualization: eye vector color (blue)");
ConVar cvar_eye_a("sig_visualize_airblast_vectors_eye_a", "0xff", FCVAR_NOTIFY, "Visualization: eye vector color (alpha)");
ConVar cvar_dwsc_r("sig_visualize_airblast_vectors_dwsc_r", "0xff", FCVAR_NOTIFY, "Visualization: delta-WSC vector color (red)");
ConVar cvar_dwsc_g("sig_visualize_airblast_vectors_dwsc_g", "0x00", FCVAR_NOTIFY, "Visualization: delta-WSC vector color (green)");
ConVar cvar_dwsc_b("sig_visualize_airblast_vectors_dwsc_b", "0xff", FCVAR_NOTIFY, "Visualization: delta-WSC vector color (blue)");
ConVar cvar_dwsc_a("sig_visualize_airblast_vectors_dwsc_a", "0xff", FCVAR_NOTIFY, "Visualization: delta-WSC vector color (alpha)");
ConVar cvar_imp_main_r("sig_visualize_airblast_vectors_imp_main_r", "0xff", FCVAR_NOTIFY, "Visualization: main impulse vector color (red)");
ConVar cvar_imp_main_g("sig_visualize_airblast_vectors_imp_main_g", "0x00", FCVAR_NOTIFY, "Visualization: main impulse vector color (green)");
ConVar cvar_imp_main_b("sig_visualize_airblast_vectors_imp_main_b", "0x00", FCVAR_NOTIFY, "Visualization: main impulse vector color (blue)");
ConVar cvar_imp_main_a("sig_visualize_airblast_vectors_imp_main_a", "0xff", FCVAR_NOTIFY, "Visualization: main impulse vector color (alpha)");
ConVar cvar_imp_vert_r("sig_visualize_airblast_vectors_imp_vert_r", "0x00", FCVAR_NOTIFY, "Visualization: vertical impulse vector color (red)");
ConVar cvar_imp_vert_g("sig_visualize_airblast_vectors_imp_vert_g", "0xff", FCVAR_NOTIFY, "Visualization: vertical impulse vector color (green)");
ConVar cvar_imp_vert_b("sig_visualize_airblast_vectors_imp_vert_b", "0x00", FCVAR_NOTIFY, "Visualization: vertical impulse vector color (blue)");
ConVar cvar_imp_vert_a("sig_visualize_airblast_vectors_imp_vert_a", "0xff", FCVAR_NOTIFY, "Visualization: vertical impulse vector color (alpha)");
ConVar cvar_imp_sum_r("sig_visualize_airblast_vectors_imp_sum_r", "0xff", FCVAR_NOTIFY, "Visualization: impulse vector sum color (red)");
ConVar cvar_imp_sum_g("sig_visualize_airblast_vectors_imp_sum_g", "0xff", FCVAR_NOTIFY, "Visualization: impulse vector sum color (green)");
ConVar cvar_imp_sum_b("sig_visualize_airblast_vectors_imp_sum_b", "0x00", FCVAR_NOTIFY, "Visualization: impulse vector sum color (blue)");
ConVar cvar_imp_sum_a("sig_visualize_airblast_vectors_imp_sum_a", "0xff", FCVAR_NOTIFY, "Visualization: impulse vector sum color (alpha)");
#define CVAR_COLOR(name) \
std::strtol(cvar_ ## name ## _r.GetString(), nullptr, 0), \
std::strtol(cvar_ ## name ## _g.GetString(), nullptr, 0), \
std::strtol(cvar_ ## name ## _b.GetString(), nullptr, 0), \
std::strtol(cvar_ ## name ## _a.GetString(), nullptr, 0)
float attr__airblast_pushback_scale = -1.0f;
float attr__airblast_vertical_pushback_scale = -1.0f;
DETOUR_DECL_STATIC(float, CAttributeManager_AttribHookValue_float, float value, const char *attr, const CBaseEntity *ent, CUtlVector<CBaseEntity *> *vec, bool b1)
{
auto result = DETOUR_STATIC_CALL(CAttributeManager_AttribHookValue_float)(value, attr, ent, vec, b1);
if (strcmp(attr, "airblast_pushback_scale") == 0) {
attr__airblast_pushback_scale = result;
}
if (strcmp(attr, "airblast_vertical_pushback_scale") == 0) {
attr__airblast_vertical_pushback_scale = result;
}
return result;
}
DETOUR_DECL_MEMBER(bool, CTFFlameThrower_DeflectPlayer, CTFPlayer *pVictim, CTFPlayer *pPyro, const Vector& vecEyeFwd, const Vector& vecBoxCenter, const Vector& vecBoxSize)
{
NDebugOverlay::Clear();
auto result = DETOUR_MEMBER_CALL(CTFFlameThrower_DeflectPlayer)(pVictim, pPyro, vecEyeFwd, vecBoxCenter, vecBoxSize);
Vector vecDeltaWSC = (pVictim->WorldSpaceCenter() - pPyro->WorldSpaceCenter());
NDebugOverlay::VertArrow(pPyro->WorldSpaceCenter(), pPyro->WorldSpaceCenter() + (100.0f * vecEyeFwd),
3.0f, CVAR_COLOR(eye), true, 3600.0f);
NDebugOverlay::EntityTextAtPosition(pPyro->WorldSpaceCenter() + (100.0f * vecEyeFwd), -1,
"xhair", 3600.0f, CVAR_COLOR(eye));
NDebugOverlay::VertArrow(pPyro->WorldSpaceCenter(), pPyro->WorldSpaceCenter() + (100.0f * vecDeltaWSC.Normalized()),
3.0f, CVAR_COLOR(dwsc), true, 3600.0f);
NDebugOverlay::EntityTextAtPosition(pPyro->WorldSpaceCenter() + (100.0f * vecDeltaWSC.Normalized()), -1,
"delta-WSC", 3600.0f, CVAR_COLOR(dwsc));
// TODO: draw sphere: WSC of pyro
// TODO: draw sphere: WSC of victim
if (result) {
Vector vA = pVictim->WorldSpaceCenter();
Vector vB = vA + ((attr__airblast_pushback_scale * vecDeltaWSC.Normalized()) / 3.0f);
Vector vC = vB + ((attr__airblast_vertical_pushback_scale * Vector(0.0f, 0.0f, 1.0f)) / 3.0f);
NDebugOverlay::VertArrow(vA, vB, 3.0f, CVAR_COLOR(imp_main), true, 3600.0f);
NDebugOverlay::EntityTextAtPosition((vA + vB) / 2.0f, 0, "Delta-WSC", 3600.0f, CVAR_COLOR(imp_main));
NDebugOverlay::EntityTextAtPosition((vA + vB) / 2.0f, 1, "Impulse", 3600.0f, CVAR_COLOR(imp_main));
NDebugOverlay::VertArrow(vB, vC, 3.0f, CVAR_COLOR(imp_vert), true, 3600.0f);
NDebugOverlay::EntityTextAtPosition((vB + vC) / 2.0f, 0, "Vertical", 3600.0f, CVAR_COLOR(imp_vert));
NDebugOverlay::EntityTextAtPosition((vB + vC) / 2.0f, 1, "Impulse", 3600.0f, CVAR_COLOR(imp_vert));
NDebugOverlay::VertArrow(vA, vC, 3.0f, CVAR_COLOR(imp_sum), true, 3600.0f);
NDebugOverlay::EntityTextAtPosition((vA + vC) / 2.0f, 0, "Vector Sum", 3600.0f, CVAR_COLOR(imp_sum));
}
return result;
}
DETOUR_DECL_MEMBER(void, CTFPlayer_ApplyGenericPushbackImpulse, const Vector& impulse, CTFPlayer * inflictor)
{
DevMsg("ApplyGenericPushbackImpulse: %6.1f [ %+7.1f %+7.1f %+7.1f ]\n",
impulse.Length(), impulse.x, impulse.y, impulse.z);
DETOUR_MEMBER_CALL(CTFPlayer_ApplyGenericPushbackImpulse)(impulse, inflictor);
}
class CMod : public IMod
{
public:
CMod() : IMod("Visualize:Airblast_Vectors")
{
MOD_ADD_DETOUR_STATIC(CAttributeManager_AttribHookValue_float, "CAttributeManager::AttribHookValue<float>");
MOD_ADD_DETOUR_MEMBER(CTFFlameThrower_DeflectPlayer, "CTFFlameThrower::DeflectPlayer");
MOD_ADD_DETOUR_MEMBER(CTFPlayer_ApplyGenericPushbackImpulse, "CTFPlayer::ApplyGenericPushbackImpulse");
}
};
CMod s_Mod;
ConVar cvar_enable("sig_visualize_airblast_vectors", "0", FCVAR_NOTIFY,
"Visualization: draw vectors used for airblast deflection of players",
[](IConVar *pConVar, const char *pOldValue, float flOldValue){
s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool());
});
}
#endif
| 54.610687 | 174 | 0.740705 | [
"vector"
] |
8a79b652739b38c54a16d9afc6eb34f4e68ac255 | 2,005 | cpp | C++ | multimedia/danim/src/appel/values/geom/pickgeom.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | multimedia/danim/src/appel/values/geom/pickgeom.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | multimedia/danim/src/appel/values/geom/pickgeom.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z |
/*******************************************************************************
Copyright (c) 1995-96 Microsoft Corporation
Abstract:
Support for pickable geometries.
*******************************************************************************/
#include "headers.h"
#include "appelles/gattr.h"
#include "privinc/geomi.h"
#include "privinc/probe.h"
class PickableGeom : public AttributedGeom {
public:
PickableGeom(Geometry *geom, int id, bool uType = false,
GCIUnknown *u = NULL)
: AttributedGeom(geom), _eventId(id), _hasData(uType), _long(u) {}
virtual void DoKids(GCFuncObj proc) {
AttributedGeom::DoKids(proc);
(*proc)(_long);
}
#if _USE_PRINT
// Print a representation to a stream.
ostream& Print(ostream& os) {
return os << "PickableGeometry(" << _geometry << ")";
}
#endif
void RayIntersect(RayIntersectCtx& ctx) {
// Tell the context that this pickable image is a candidate for
// picking, perform the pick on the underlying geometry, then
// remove this pickable as a candidate by popping it off of the
// stack.
ctx.PushPickableAsCandidate(_eventId, _hasData, _long);
_geometry->RayIntersect(ctx);
ctx.PopPickableAsCandidate();
}
protected:
int _eventId;
bool _hasData;
GCIUnknown *_long;
};
// Note that this is called with a pick event ID generated through
// CAML.
Geometry *PRIVPickableGeometry(Geometry *geo,
AxANumber *id,
AxABoolean *ignoresOcclusion)
{
return NEW PickableGeom(geo, (int)NumberToReal(id));
}
AxAValue PRIVPickableGeomWithData(AxAValue geo,
int id,
GCIUnknown *data,
bool)
{
return NEW PickableGeom(SAFE_CAST(Geometry*,geo), id, true, data);
}
| 28.239437 | 81 | 0.537656 | [
"geometry"
] |
8a83617b6629bbbb6544e53c8a3f4a225229cf0a | 16,545 | cpp | C++ | searchCondition.cpp | Kenshins/BooliCPP | 5a4b47abed54f4df271aa249c3370fee1ace1506 | [
"Unlicense",
"MIT"
] | null | null | null | searchCondition.cpp | Kenshins/BooliCPP | 5a4b47abed54f4df271aa249c3370fee1ace1506 | [
"Unlicense",
"MIT"
] | null | null | null | searchCondition.cpp | Kenshins/BooliCPP | 5a4b47abed54f4df271aa249c3370fee1ace1506 | [
"Unlicense",
"MIT"
] | null | null | null | #include "searchCondition.h"
#include <string>
#include <algorithm>
#include <stdexcept>
#include <sstream>
#include <ctime>
#include <time.h>
using namespace std;
// Supporting types
center::center(int la, int ln)
{
SetLatLong(la, ln);
}
void center::SetLatLong(int la, int ln)
{
SetLat(la);
SetLong(ln);
}
void center::SetLat(int la)
{
if (la < 0 || la > 90)
{
throw std::invalid_argument( "center la cannot be lower then 0 or higher then 90!" );
}
latitude = la;
}
void center::SetLong(int ln)
{
if (ln < 0 || ln > 180)
{
throw std::invalid_argument( "center ln cannot be lower then 0 or higher then 180!" );
}
longitude = ln;
}
std::string center::RetCenter()
{
stringstream ss;
ss << latitude << "," <<longitude;
return ss.str();
}
dimension::dimension(int x, int y)
{
SetX(x);
SetY(y);
}
void dimension::SetX(int inx)
{
if (inx < 0)
throw std::invalid_argument( "dimension x cannot be negative!" );
x = inx;
}
void dimension::SetY(int iny)
{
if (iny < 0)
throw std::invalid_argument( "dimension y cannot be negative!" );
y = iny;
}
std::string dimension::RetDim()
{
stringstream ss;
ss << x << "," << y;
return ss.str();
}
bbox::bbox(double lat_lo, double lng_lo, double lat_hi, double lng_hi)
{
if (lat_lo < 0 || lat_lo > 90)
{
throw std::invalid_argument( "bbox: lat_lo cannot be lower then 0 or higher then 90!" );
}
if (lng_lo < 0 || lng_lo > 180)
{
throw std::invalid_argument( "bbox: lng_lo cannot be lower then 0 or higher then 180!" );
}
if (lat_hi < 0 || lat_hi > 90)
{
throw std::invalid_argument( "bbox: lat_hi cannot be lower then 0 or higher then 90!" );
}
if (lng_hi < 0 || lng_hi > 180)
{
throw std::invalid_argument( "bbox: lng_hi cannot be lower then 0 or higher then 180!" );
}
if ( lat_lo > lat_hi)
{
throw std::invalid_argument( "bbox: lat_lo cannot be higher then lat_hi!" );
}
if ( lng_lo > lng_hi)
{
throw std::invalid_argument( "bbox: lng_lo cannot be higer then lng_hi!" );
}
latLo = lat_lo;
lngLo = lng_lo;
latHi = lat_hi;
lngHi = lng_hi;
}
std::string bbox::RetBbox()
{
stringstream ss;
ss << latLo << "," << lngLo << "," << latHi << "," << lngHi;
return ss.str();
}
objectType::objectType(std::string oT)
{
std::transform(oT.begin(), oT.end(),oT.begin(), ::tolower);
if (oT == "villa")
{
object_type = oT;
}
else if (oT == "lägenhet")
{
object_type = oT;
}
else if (oT == "gård")
{
object_type = oT;
}
else if (oT == "tomt-mark")
{
object_type = oT;
}
else if (oT == "fritidshus")
{
object_type = oT;
}
else if (oT == "parhus")
{
object_type = oT;
}
else if (oT == "radhus")
{
object_type = oT;
}
else if (oT == "kedjehus")
{
object_type = oT;
}
else
{
throw std::invalid_argument( "objectType:" + oT + "unknown objectType!" );
}
}
std::string objectType::retObjectType()
{
return object_type;
}
minPublishedDate::minPublishedDate(tm *t)
{
if (!util::valid_date(t->tm_year, t->tm_mon, t->tm_mday))
{
throw std::invalid_argument( "minPublishedDate: date is invalid!" );
}
minPubDateTime = t;
}
std::string minPublishedDate::retMinPublishedDate()
{
std::string month = "";
if (minPubDateTime->tm_mon < 10)
month = "0" + std::to_string(minPubDateTime->tm_mon);
else
month = std::to_string(minPubDateTime->tm_mon);
return std::to_string(minPubDateTime->tm_year) + month + std::to_string(minPubDateTime->tm_mday);
}
maxPublishedDate::maxPublishedDate(tm *t)
{
if (!util::valid_date(t->tm_year, t->tm_mon, t->tm_mday))
{
throw std::invalid_argument( "minPublishedDate: date is invalid!" );
}
maxPubDateTime = t;
}
std::string maxPublishedDate::retMaxPublishedDate()
{
std::string month = "";
if (maxPubDateTime->tm_mon < 10)
month = "0" + std::to_string(maxPubDateTime->tm_mon);
else
month = std::to_string(maxPubDateTime->tm_mon);
return std::to_string(maxPubDateTime->tm_year) + month + std::to_string(maxPubDateTime->tm_mday);
}
minSoldDate::minSoldDate(tm *t)
{
if (!util::valid_date(t->tm_year, t->tm_mon, t->tm_mday))
{
throw std::invalid_argument( "minPublishedDate: date is invalid!" );
}
minSoldDateTime = t;
}
std::string minSoldDate::retMinSoldDate()
{
std::string month = "";
if (minSoldDateTime->tm_mon < 10)
month = "0" + std::to_string(minSoldDateTime->tm_mon);
else
month = std::to_string(minSoldDateTime->tm_mon);
return std::to_string(minSoldDateTime->tm_year) + month + std::to_string(minSoldDateTime->tm_mday);
}
maxSoldDate::maxSoldDate(tm *t)
{
if (!util::valid_date(t->tm_year, t->tm_mon, t->tm_mday))
{
throw std::invalid_argument( "minPublishedDate: date is invalid!" );
}
maxSoldDateTime = t;
}
std::string maxSoldDate::retMaxSoldDate()
{
std::string month = "";
if (maxSoldDateTime->tm_mon < 10)
month = "0" + std::to_string(maxSoldDateTime->tm_mon);
else
month = std::to_string(maxSoldDateTime->tm_mon);
return std::to_string(maxSoldDateTime->tm_year) + month + std::to_string(maxSoldDateTime->tm_mday);
}
// searchCondition
listingsSearchCondition::listingsSearchCondition()
{
}
void searchCondition::SetQ(std::string q)
{
checkNoDuplicateMainInput(Q);
query = q;
}
void searchCondition::SetC(center *c)
{
checkNoDuplicateMainInput(CENTER);
if (c)
cent = c;
}
void searchCondition::SetDim(dimension *d)
{
checkNoDuplicateMainInput(DIM);
if (dim)
dim = d;
}
void searchCondition::SetBbox(bbox *b)
{
checkNoDuplicateMainInput(BBOX);
if (bB)
bB = b;
}
void searchCondition::SetAreaId(std::string aId)
{
checkNoDuplicateMainInput(AREAID);
areaId = aId;
}
void searchCondition::SetMinRooms(int minR)
{
if (minR < 0)
throw std::invalid_argument( "SetMinRooms: min rooms cannot be negative!" );
minRooms = minR;
}
void searchCondition::SetMaxRooms(int maxR)
{
if (maxR < 0)
throw std::invalid_argument( "SetMaxRooms: max rooms cannot be negative!" );
maxRooms = maxR;
}
void searchCondition::SetMaxRent(int maxRe)
{
if (maxRe < 0)
throw std::invalid_argument( "SetMaxRent: max rent cannot be negative!" );
maxRent = maxRe;
}
void searchCondition::SetMinLivingArea(int minLA)
{
if (minLA < 0)
throw std::invalid_argument( "SetMinLivingArea: min living area cannot be negative!" );
minLivingArea = minLA;
}
void searchCondition::SetMaxLivingArea(int maxLA)
{
if (maxLA < 0)
throw std::invalid_argument( "SetMaxLivingArea: max living area cannot be negative!" );
maxLivingArea = maxLA;
}
void searchCondition::SetMinPlotArea(int minPA)
{
if (minPA < 0)
throw std::invalid_argument( "SetMinPlotArea: min plot area cannot be negative!" );
minPlotArea = minPA;
}
void searchCondition::SetMaxPlotArea(int maxPA)
{
if (maxPA < 0)
throw std::invalid_argument( "SetMaxPlotArea: max plot area cannot be negative!" );
maxPlotArea = maxPA;
}
void searchCondition::SetMinPublishDate(minPublishedDate *minPD)
{
if (minPD)
minPubDate = minPD;
}
void searchCondition::SetMaxPublishDate(maxPublishedDate *maxPD)
{
if (maxPD)
maxPubDate = maxPD;
}
void searchCondition::SetObjectType(std::string oT)
{
objectT = new objectType(oT);
}
void searchCondition::SetMinConstructionYear(int minCY)
{
if (minCY < 0)
throw std::invalid_argument( "SetMinConstructionYear: min construction year cannot be negative!" );
minConstructionYear = minCY;
}
void searchCondition::SetMaxConstructionYear(int maxCY)
{
if (maxCY < 0)
throw std::invalid_argument( "SetMaxConstructionYear: max construction year cannot be negative!" );
maxConstructionYear = maxCY;
}
void searchCondition::SetIsNewConstruction(bool nC)
{
isNewConstruction = nC;
}
void searchCondition::SetIncludeUnset(bool iU)
{
includeUnset = iU;
}
void searchCondition::SetLimit(int l)
{
limit = l;
}
void searchCondition::SetOffset(int o)
{
offset = o;
}
void searchCondition::checkNoDuplicateMainInput(MainInput in)
{
if (in == BBOX)
{
if (cent != NULL || dim != NULL || areaId != "" || query != "")
{
throw std::invalid_argument( "SetBbox: Cannot set bbox if center, dimension, areaid or q is set!" );
}
}
else if (in == Q)
{
if (bB != NULL || dim != NULL || areaId != "" || cent != NULL)
{
throw std::invalid_argument( "SetQ: Cannot set center if bbox, dimension, areaid or center is set!" );
}
}
else if (in == CENTER)
{
if (bB != NULL || dim != NULL || areaId != "" || query != "")
{
throw std::invalid_argument( "SetC: Cannot set center if bbox, dimension, areaid or q is set!" );
}
}
else if (in == DIM)
{
if (bB != NULL || cent != NULL || areaId != "" || query != "")
{
throw std::invalid_argument( "SetDim: Cannot set dimension if bbox, areaid, center or q is set!" );
}
}
else if (in == AREAID)
{
if (bB != NULL || cent != NULL || dim != NULL || query != "")
{
throw std::invalid_argument( "SetAreaId: Cannot set areaid if dimension, center, bbox or q is set!" );
}
}
}
std::string searchCondition::CommonSearchConditionResult(std::string tableSpecific)
{
std::string booliString = "";
if (query != "")
booliString += "q=" + query;
if (cent)
{
booliString += "center=" + cent->RetCenter();
if (dim)
booliString += "&dim=" + dim->RetDim();
}
if (bB)
booliString += "bbox=" + bB->RetBbox();
if (areaId != "")
booliString += "areaId=" + areaId;
if (minRooms != 0)
booliString += "&minRooms=" + util::intToString(minRooms);
if (maxRooms != 0)
booliString += "&maxRooms=" + util::intToString(maxRooms);
if (maxRent != 0)
booliString += "&maxRent=" + util::intToString(maxRent);
if (minLivingArea != 0)
booliString += "&minLivingArea=" + util::intToString(minLivingArea);
if (maxLivingArea != 0)
booliString += "&maxLivingArea=" + util::intToString(maxLivingArea);
if (minPlotArea != 0)
booliString += "&minPlotArea=" + util::intToString(minPlotArea);
if (maxPlotArea != 0)
booliString += "&maxPlotArea=" + util::intToString(maxPlotArea);
if (objectT != NULL)
booliString += "&objectType=" + objectT->retObjectType();
if (minConstructionYear != 0)
booliString += "&minConstructionYear=" + util::intToString(minConstructionYear);
if (maxConstructionYear != 0)
booliString += "&maxConstructionYear=" + util::intToString(maxConstructionYear);
if (minPubDate != NULL)
booliString += "&minPublished=" + minPubDate->retMinPublishedDate();
if (maxPubDate != NULL)
booliString += "&maxPublished=" + maxPubDate->retMaxPublishedDate();
if (tableSpecific != "")
booliString += tableSpecific;
if (isNewConstruction)
booliString += "&isNewConstruction=1";
if (!includeUnset)
booliString += "&includeUnset=0";
booliString += "&limit=" + util::intToString(limit);
if (offset != 0)
booliString += "&offset=" + util::intToString(offset);
return booliString;
}
// listing search condition
void listingsSearchCondition::SetMinListPrice(int minLP)
{
if (minLP < 0)
throw std::invalid_argument( "SetMinListPrice: Min list price cannot be negative!" );
minListPrice = minLP;
}
void listingsSearchCondition::SetMaxListPrice(int maxLP)
{
if (maxLP < 0)
throw std::invalid_argument( "SetMaxListPrice: Max list price cannot be negative!" );
maxListPrice = maxLP;
}
void listingsSearchCondition::SetMinListSqmPrice(int minLSP)
{
if (minLSP < 0)
throw std::invalid_argument( "SetMinListSqmPrice: Min list square meter price cannot be negative!" );
minListSqmPrice = minLSP;
}
void listingsSearchCondition::SetMaxListSqmPrice(int maxLSP)
{
if (maxLSP < 0)
throw std::invalid_argument( "SetMaxListSqmPrice: Max list square meter price cannot be negative!" );
maxListSqmPrice = maxLSP;
}
void listingsSearchCondition::SetPriceDecrease(bool pD)
{
priceDecrease = pD;
}
std::string listingsSearchCondition::SearchConditionResult()
{
std::string booliString = "";
if (minListPrice != 0)
booliString += "&minListPrice=" + util::intToString(minListPrice);
if (maxListPrice != 0)
booliString += "&maxListPrice=" + std::to_string(maxListPrice);
if (minListSqmPrice != 0)
booliString += "&minListSqmPrice=" + util::intToString(minListSqmPrice);
if (maxListSqmPrice != 0)
booliString += "&maxListSqmPrice=" + util::intToString(maxListSqmPrice);
if (priceDecrease)
booliString += "&priceDecrease=1";
return "listings?" + this->CommonSearchConditionResult(booliString);
}
// sold search condition
void soldSearchCondition::SetMinSoldPrice(int minSP)
{
if (minSP < 0)
throw std::invalid_argument( "SetMinSoldPrice: Min sold price cannot be negative!" );
minSoldPrice = minSP;
}
void soldSearchCondition::SetMaxSoldPrice(int maxSP)
{
if (maxSP < 0)
throw std::invalid_argument( "SetMaxSoldPrice: Max sold price cannot be negative!" );
maxSoldPrice = maxSP;
}
void soldSearchCondition::SetMinSoldSqmPrice(int minSSP)
{
if (minSSP < 0)
throw std::invalid_argument( "SetMinSoldSqmPrice: Min sold square meter price cannot be negative!" );
minSoldSqmPrice = minSSP;
}
void soldSearchCondition::SetMaxSoldSqmPrice(int maxSSP)
{
if (maxSSP < 0)
throw std::invalid_argument( "SetMaxSoldSqmPrice: Max sold square meter price cannot be negative!" );
maxSoldSqmPrice = maxSSP;
}
void soldSearchCondition::SetMinSoldDate(minSoldDate *minSD)
{
if (minSD)
minSDate = minSD;
}
void soldSearchCondition::SetMaxSoldDate(maxSoldDate *maxSD)
{
if (maxSD)
maxSDate = maxSD;
}
soldSearchCondition::soldSearchCondition()
{
}
std::string soldSearchCondition::SearchConditionResult()
{
std::string booliString = "";
if (minSoldPrice != 0)
booliString += "&minSoldPrice=" + util::intToString(minSoldPrice);
if (maxSoldPrice != 0)
booliString += "&maxSoldPrice=" + std::to_string(maxSoldPrice);
if (minSoldSqmPrice != 0)
booliString += "&minSoldSqmPrice=" + util::intToString(minSoldSqmPrice);
if (maxSoldSqmPrice != 0)
booliString += "&maxSoldSqmPrice=" + util::intToString(maxSoldSqmPrice);
if (minSDate != NULL)
booliString += "&minSoldDate=" + minSDate->retMinSoldDate();
if (maxSDate != NULL)
booliString += "&maxSoldDate=" + maxSDate->retMaxSoldDate();
return "sold?" + this->CommonSearchConditionResult(booliString);
}
// area search condition
areaSearchCondition::areaSearchCondition()
{
}
std::string areaSearchCondition::SearchConditionResult()
{
std::string booliString = "areas?";
if (query != "")
booliString += "q=" + query;
if (lat != 0 || lng != 0)
{
stringstream ss;
ss << "lat=" << lat << "&lng=" << lng;
booliString += ss.str();
}
if (listings)
booliString += "&listings=1";
if (transactions)
booliString += "&transactions=1";
booliString += "&limit=" + util::intToString(limit);
return booliString;
}
void areaSearchCondition::SetQ(std::string q)
{
if (lat != 0 || lng != 0)
throw std::invalid_argument( "SetQ: Cannot set query string if lat or long is set!" );
query = q;
}
void areaSearchCondition::SetLat(double la)
{
if (query != "")
throw std::invalid_argument( "SetLat: Cannot set lat if query is set!" );
lat = la;
}
void areaSearchCondition::SetLng(double lo)
{
if (query != "")
throw std::invalid_argument( "SetLng: Cannot set long if query is set!" );
lng = lo;
}
void areaSearchCondition::SetListings(bool list)
{
listings = list;
}
void areaSearchCondition::SetTransactions(bool trans)
{
transactions = trans;
}
void areaSearchCondition::SetLimit(int l)
{
limit = l;
}
std::string util::intToString(int d)
{
std::ostringstream strs;
strs << d;
return strs.str();
}
bool util::isleapyear(int year){
return (!(year%4) && (year%100) || !(year%400));
}
// TODO: Maybe I rewrite this to return a error string instead
bool util::valid_date(int year,int month,int day){
unsigned short monthlen[]={31,28,31,30,31,30,31,31,30,31,30,31};
if (!year || !month || !day || month>12)
return 0;
if (year < 1800 || year > 3000)
return 0;
if (month < 0 || month > 11)
return 0;
if (isleapyear(year) && month==2)
monthlen[1]++;
if (day>monthlen[month-1])
return 0;
return 1;
}
| 22.118984 | 105 | 0.655606 | [
"transform"
] |
8a854cee80aaa10a60bf221b65bcfe7ab71d3b79 | 3,704 | cpp | C++ | pwiz/analysis/passive/RegionSlice.cpp | edyp-lab/pwiz-mzdb | d13ce17f4061596c7e3daf9cf5671167b5996831 | [
"Apache-2.0"
] | 11 | 2015-01-08T08:33:44.000Z | 2019-07-12T06:14:54.000Z | pwiz/analysis/passive/RegionSlice.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | pwiz/analysis/passive/RegionSlice.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 4 | 2016-02-03T09:41:16.000Z | 2021-08-01T18:42:36.000Z | //
// $Id: RegionSlice.cpp 4168 2012-12-04 23:19:57Z pcbrefugee $
//
//
// Original author: Darren Kessner <darren@proteowizard.org>
//
// Copyright 2008 Spielberg Family Center for Applied Proteomics
// Cedars-Sinai Medical Center, Los Angeles, California 90048
//
// 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.
//
#define PWIZ_SOURCE
#include "RegionSlice.hpp"
#include "pwiz/data/msdata/TextWriter.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/fstream.hpp"
#include "pwiz/utility/misc/Std.hpp"
namespace pwiz {
namespace analysis {
PWIZ_API_DECL RegionSlice::Config::Config(const string& args)
{
mzRange = make_pair(0, numeric_limits<double>::max());
rtRange = make_pair(0, numeric_limits<double>::max());
indexRange = make_pair(0, numeric_limits<size_t>::max());
scanNumberRange = make_pair(0, numeric_limits<int>::max());
dumpRegionData = true;
vector<string> tokens;
istringstream iss(args);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));
ostringstream suffix;
suffix << ".slice";
for (vector<string>::const_iterator it=tokens.begin(); it!=tokens.end(); ++it)
{
if(checkDelimiter(*it))
{
// that was a valid delimiter arg
}
else if (parseRange("mz", *it, mzRange, "RegionSlice::Config"))
{
suffix << ".mz_" << fixed << setprecision(4) << mzRange.first
<< "-" << mzRange.second;
}
else if (parseRange("rt", *it, rtRange, "RegionSlice::Config"))
{
suffix << ".rt_" << fixed << setprecision(2) << rtRange.first
<< "-" << rtRange.second;
}
else if (parseRange("index", *it, indexRange, "RegionSlice::Config"))
{
suffix << ".index_" << indexRange.first << "-" << indexRange.second;
}
else if (parseRange("sn", *it, scanNumberRange, "RegionSlice::Config"))
{
suffix << ".sn_" << scanNumberRange.first << "-" << scanNumberRange.second;
}
else
{
cerr << "[RegionSlice::Config] Ignoring argument: " << *it << endl;
}
}
suffix << getFileExtension(); // based on delimiter type
filenameSuffix = suffix.str();
}
PWIZ_API_DECL RegionSlice::RegionSlice(const MSDataCache& cache, const Config& config)
: cache_(cache),
regionAnalyzer_(new RegionAnalyzer(config, cache_))
{}
PWIZ_API_DECL void RegionSlice::open(const DataInfo& dataInfo)
{
regionAnalyzer_->open(dataInfo);
}
PWIZ_API_DECL
MSDataAnalyzer::UpdateRequest
RegionSlice::updateRequested(const DataInfo& dataInfo,
const SpectrumIdentity& spectrumIdentity) const
{
return regionAnalyzer_->updateRequested(dataInfo, spectrumIdentity);
}
PWIZ_API_DECL
void RegionSlice::update(const DataInfo& dataInfo,
const Spectrum& spectrum)
{
return regionAnalyzer_->update(dataInfo, spectrum);
}
PWIZ_API_DECL void RegionSlice::close(const DataInfo& dataInfo)
{
regionAnalyzer_->close(dataInfo);
}
} // namespace analysis
} // namespace pwiz
| 30.113821 | 91 | 0.648758 | [
"vector"
] |
8a8bbcaf592612221075d8031600b2d45efd4238 | 1,498 | cc | C++ | 2019/d2s2.cc | danielrayali/adventofcode | 29bfd54013a4ba832b7c846d2770eb03692d67de | [
"MIT"
] | null | null | null | 2019/d2s2.cc | danielrayali/adventofcode | 29bfd54013a4ba832b7c846d2770eb03692d67de | [
"MIT"
] | null | null | null | 2019/d2s2.cc | danielrayali/adventofcode | 29bfd54013a4ba832b7c846d2770eb03692d67de | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <set>
#include <vector>
using namespace std;
void Process(vector<int>& opcodes) {
for (int i = 0; i < opcodes.size(); i += 4) {
if (opcodes[i] == 99)
break;
int op = opcodes[i];
int lpos = opcodes[i + 1];
int rpos = opcodes[i + 2];
int opos = opcodes[i + 3];
if (op == 1) {
opcodes[opos] = opcodes[lpos] + opcodes[rpos];
} else if (op == 2) {
opcodes[opos] = opcodes[lpos] * opcodes[rpos];
}
}
}
int main(int argc, char* argv[]) {
if (argc != 2) {
cerr << "Give a file to parse" << endl;
return 0;
}
vector<int> opcodes;
string path(argv[1]);
ifstream in(path);
cout << "Inputs: ";
while (!in.eof()) {
int current = 0;
in >> current;
char temp;
in >> temp;
opcodes.push_back(current);
cout << current << " ";
}
cout << endl;
// Apply error correction
vector<int> attempt;
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 100; ++j) {
attempt = opcodes;
attempt[1] = i;
attempt[2] = j;
Process(attempt);
if (attempt[0] == 19690720) {
cout << "Noun: " << i << "\nVerb: " << j << endl;
cout << "100 * " << i << " + " << j << " = " << 100 * i + j << endl;
break;
}
}
}
return 0;
}
| 23.777778 | 84 | 0.435247 | [
"vector"
] |
8a8ed5d2f9b1eab981496af7f2fec035bee05015 | 1,370 | cpp | C++ | aws-cpp-sdk-securityhub/source/model/RuleGroupSourceStatelessRuleMatchAttributesSources.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-securityhub/source/model/RuleGroupSourceStatelessRuleMatchAttributesSources.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-securityhub/source/model/RuleGroupSourceStatelessRuleMatchAttributesSources.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/securityhub/model/RuleGroupSourceStatelessRuleMatchAttributesSources.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SecurityHub
{
namespace Model
{
RuleGroupSourceStatelessRuleMatchAttributesSources::RuleGroupSourceStatelessRuleMatchAttributesSources() :
m_addressDefinitionHasBeenSet(false)
{
}
RuleGroupSourceStatelessRuleMatchAttributesSources::RuleGroupSourceStatelessRuleMatchAttributesSources(JsonView jsonValue) :
m_addressDefinitionHasBeenSet(false)
{
*this = jsonValue;
}
RuleGroupSourceStatelessRuleMatchAttributesSources& RuleGroupSourceStatelessRuleMatchAttributesSources::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("AddressDefinition"))
{
m_addressDefinition = jsonValue.GetString("AddressDefinition");
m_addressDefinitionHasBeenSet = true;
}
return *this;
}
JsonValue RuleGroupSourceStatelessRuleMatchAttributesSources::Jsonize() const
{
JsonValue payload;
if(m_addressDefinitionHasBeenSet)
{
payload.WithString("AddressDefinition", m_addressDefinition);
}
return payload;
}
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
| 22.833333 | 134 | 0.79854 | [
"model"
] |
8a9098150d6591d5416165ac39a1d433608888fc | 7,211 | hpp | C++ | include/NUnit/Framework/Internal/ITestExecutionContext.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/NUnit/Framework/Internal/ITestExecutionContext.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/NUnit/Framework/Internal/ITestExecutionContext.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: NUnit::Framework::Internal
namespace NUnit::Framework::Internal {
// Forward declaring type: TestResult
class TestResult;
}
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: TextWriter
class TextWriter;
}
// Forward declaring namespace: NUnit::Framework::Constraints
namespace NUnit::Framework::Constraints {
// Forward declaring type: ValueFormatter
class ValueFormatter;
}
// Completed forward declares
// Begin il2cpp-utils forward declares
struct Il2CppObject;
// Completed il2cpp-utils forward declares
// Type namespace: NUnit.Framework.Internal
namespace NUnit::Framework::Internal {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: NUnit.Framework.Internal.ITestExecutionContext
// [TokenAttribute] Offset: FFFFFFFF
class ITestExecutionContext {
public:
// Creating value type constructor for type: ITestExecutionContext
ITestExecutionContext() noexcept {}
// public NUnit.Framework.Internal.TestResult get_CurrentResult()
// Offset: 0xFFFFFFFF
NUnit::Framework::Internal::TestResult* get_CurrentResult();
// public System.Void set_CurrentResult(NUnit.Framework.Internal.TestResult value)
// Offset: 0xFFFFFFFF
void set_CurrentResult(NUnit::Framework::Internal::TestResult* value);
// public System.IO.TextWriter get_OutWriter()
// Offset: 0xFFFFFFFF
System::IO::TextWriter* get_OutWriter();
// public System.Object get_TestObject()
// Offset: 0xFFFFFFFF
::Il2CppObject* get_TestObject();
// public System.Void set_TestObject(System.Object value)
// Offset: 0xFFFFFFFF
void set_TestObject(::Il2CppObject* value);
// public NUnit.Framework.Constraints.ValueFormatter get_CurrentValueFormatter()
// Offset: 0xFFFFFFFF
NUnit::Framework::Constraints::ValueFormatter* get_CurrentValueFormatter();
// public System.Void IncrementAssertCount()
// Offset: 0xFFFFFFFF
void IncrementAssertCount();
}; // NUnit.Framework.Internal.ITestExecutionContext
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(NUnit::Framework::Internal::ITestExecutionContext*, "NUnit.Framework.Internal", "ITestExecutionContext");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::get_CurrentResult
// Il2CppName: get_CurrentResult
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<NUnit::Framework::Internal::TestResult* (NUnit::Framework::Internal::ITestExecutionContext::*)()>(&NUnit::Framework::Internal::ITestExecutionContext::get_CurrentResult)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "get_CurrentResult", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::set_CurrentResult
// Il2CppName: set_CurrentResult
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NUnit::Framework::Internal::ITestExecutionContext::*)(NUnit::Framework::Internal::TestResult*)>(&NUnit::Framework::Internal::ITestExecutionContext::set_CurrentResult)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("NUnit.Framework.Internal", "TestResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "set_CurrentResult", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::get_OutWriter
// Il2CppName: get_OutWriter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IO::TextWriter* (NUnit::Framework::Internal::ITestExecutionContext::*)()>(&NUnit::Framework::Internal::ITestExecutionContext::get_OutWriter)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "get_OutWriter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::get_TestObject
// Il2CppName: get_TestObject
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (NUnit::Framework::Internal::ITestExecutionContext::*)()>(&NUnit::Framework::Internal::ITestExecutionContext::get_TestObject)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "get_TestObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::set_TestObject
// Il2CppName: set_TestObject
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NUnit::Framework::Internal::ITestExecutionContext::*)(::Il2CppObject*)>(&NUnit::Framework::Internal::ITestExecutionContext::set_TestObject)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "set_TestObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::get_CurrentValueFormatter
// Il2CppName: get_CurrentValueFormatter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<NUnit::Framework::Constraints::ValueFormatter* (NUnit::Framework::Internal::ITestExecutionContext::*)()>(&NUnit::Framework::Internal::ITestExecutionContext::get_CurrentValueFormatter)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "get_CurrentValueFormatter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ITestExecutionContext::IncrementAssertCount
// Il2CppName: IncrementAssertCount
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (NUnit::Framework::Internal::ITestExecutionContext::*)()>(&NUnit::Framework::Internal::ITestExecutionContext::IncrementAssertCount)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ITestExecutionContext*), "IncrementAssertCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 58.626016 | 256 | 0.749965 | [
"object",
"vector"
] |
8a92cfb40fddf880583559f238f3bf9a719dac20 | 4,802 | hpp | C++ | GosuImpl/Graphics/DrawOpQueue.hpp | oli-obk/gosu | b186b223a2f97a7b485580e07bcce35adbbbfd89 | [
"MIT"
] | null | null | null | GosuImpl/Graphics/DrawOpQueue.hpp | oli-obk/gosu | b186b223a2f97a7b485580e07bcce35adbbbfd89 | [
"MIT"
] | null | null | null | GosuImpl/Graphics/DrawOpQueue.hpp | oli-obk/gosu | b186b223a2f97a7b485580e07bcce35adbbbfd89 | [
"MIT"
] | null | null | null | #ifndef GOSUIMPL_GRAPHICS_DRAWOPQUEUE_HPP
#define GOSUIMPL_GRAPHICS_DRAWOPQUEUE_HPP
#include <Gosu/TR1.hpp>
#include "Common.hpp"
#include "TransformStack.hpp"
#include "ClipRectStack.hpp"
#include "DrawOp.hpp"
#include <cassert>
#include <algorithm>
#include <map>
#include <vector>
#include <cmath>
class Gosu::DrawOpQueue
{
TransformStack transformStack;
ClipRectStack clipRectStack;
typedef std::vector<DrawOp> DrawOps;
DrawOps ops;
typedef std::vector<std::tr1::function<void()> > GLBlocks;
GLBlocks glBlocks;
public:
void scheduleDrawOp(DrawOp op)
{
if (clipRectStack.clippedWorldAway())
return;
#ifdef GOSU_IS_IPHONE
// No triangles, no lines supported
assert (op.verticesOrBlockIndex == 4);
#endif
op.renderState.transform = &transformStack.current();
if (const ClipRect* cr = clipRectStack.maybeEffectiveRect())
op.renderState.clipRect = *cr;
ops.push_back(op);
}
void scheduleGL(std::tr1::function<void()> glBlock, ZPos z)
{
// TODO: Document this case: Clipped-away GL blocks are *not* being run.
if (clipRectStack.clippedWorldAway())
return;
int complementOfBlockIndex = ~(int)glBlocks.size();
glBlocks.push_back(glBlock);
DrawOp op;
op.verticesOrBlockIndex = complementOfBlockIndex;
op.renderState.transform = &transformStack.current();
if (const ClipRect* cr = clipRectStack.maybeEffectiveRect())
op.renderState.clipRect = *cr;
op.z = z;
ops.push_back(op);
}
void beginClipping(double x, double y, double width, double height, double screenHeight)
{
// Apply current transformation.
double left = x, right = x + width;
double top = y, bottom = y + height;
applyTransform(transformStack.current(), left, top);
applyTransform(transformStack.current(), right, bottom);
double physX = std::min(left, right);
double physY = std::min(top, bottom);
double physWidth = std::abs(left - right);
double physHeight = std::abs(top - bottom);
// Adjust for OpenGL having the wrong idea of where y=0 is.
// TODO: This should really happen *right before* setting up
// the glScissor.
physY = screenHeight - physY - physHeight;
clipRectStack.beginClipping(physX, physY, physWidth, physHeight);
}
void endClipping()
{
clipRectStack.endClipping();
}
void setBaseTransform(const Transform& baseTransform)
{
transformStack.setBaseTransform(baseTransform);
}
void pushTransform(const Transform& transform)
{
transformStack.push(transform);
}
void popTransform()
{
transformStack.pop();
}
void performDrawOpsAndCode()
{
// Apply Z-Ordering.
std::stable_sort(ops.begin(), ops.end());
RenderStateManager manager;
#ifdef GOSU_IS_IPHONE
if (ops.empty())
return;
DrawOps::const_iterator current = ops.begin(), last = ops.end() - 1;
for (; current != last; ++current)
{
manager.setRenderState(current->renderState);
current->perform(&*(current + 1));
}
manager.setRenderState(last->renderState);
last->perform(0);
#else
for (DrawOps::const_iterator current = ops.begin(), last = ops.end();
current != last; ++current)
{
manager.setRenderState(current->renderState);
if (current->verticesOrBlockIndex >= 0)
current->perform(0);
else
{
// GL code
int blockIndex = ~current->verticesOrBlockIndex;
assert (blockIndex >= 0);
assert (blockIndex < glBlocks.size());
glBlocks[blockIndex]();
manager.enforceAfterUntrustedGL();
}
}
#endif
}
void compileTo(VertexArrays& vas)
{
if (!glBlocks.empty())
throw std::logic_error("Custom code cannot be recorded into a macro");
std::stable_sort(ops.begin(), ops.end());
for (DrawOps::const_iterator op = ops.begin(), end = ops.end(); op != end; ++op)
op->compileTo(vas);
}
// This retains the current stack of transforms and clippings.
void clearQueue()
{
glBlocks.clear();
ops.clear();
}
// This clears the queue and starts with new stacks. This must not be called
// when endClipping/popTransform calls might still be pending.
void reset()
{
transformStack.reset();
clipRectStack.clear();
clearQueue();
}
};
#endif
| 28.414201 | 92 | 0.600583 | [
"vector",
"transform"
] |
8a960933f65393de1d1eb8aebcdecf47cf223fb3 | 1,697 | cpp | C++ | src/_5GS/pdu_5gs_sm.cpp | OPENAIRINTERFACE/oai-libnascodec-cpp | c87005933fa6d748909f7fd8f1e0b1412abd0458 | [
"Apache-2.0"
] | 3 | 2019-12-06T14:17:41.000Z | 2020-09-30T17:26:17.000Z | src/_5GS/pdu_5gs_sm.cpp | OPENAIRINTERFACE/oai-libnascodec-cpp | c87005933fa6d748909f7fd8f1e0b1412abd0458 | [
"Apache-2.0"
] | null | null | null | src/_5GS/pdu_5gs_sm.cpp | OPENAIRINTERFACE/oai-libnascodec-cpp | c87005933fa6d748909f7fd8f1e0b1412abd0458 | [
"Apache-2.0"
] | 4 | 2019-12-06T14:22:37.000Z | 2021-03-20T01:44:55.000Z | #include <_5GS/pdu_5gs_sm.h>
namespace _5GS
{
Pdu5gsSm::Pdu5gsSm(IE::PDU_session_identity psi,
IE::Procedure_transaction_identity pti)
{
m_pdu_session_identity = psi;
m_procedure_transaction_identity = pti;
}
int Pdu5gsSm::codeSMHeader(std::vector<uint8_t> &data) const
{
int size = 0;
size += m_pdu_session_identity.code(data, InformationElement::Format::V);
size += m_procedure_transaction_identity.code(data, InformationElement::Format::V);
size += m_message_type.code(data, InformationElement::Format::V);
return size;
}
std::string Pdu5gsSm::header_to_string() const
{
std::string str;
// TODO add security header
// FIXME factorize
str += m_pdu_session_identity.to_string() +
", ";
str += m_procedure_transaction_identity.to_string() +
", ";
str += m_message_type.to_string();
return str;
}
int Pdu5gsSm::decode(const std::vector<uint8_t> &data)
{
// TODO security header
int offset = 1;
int size = offset;
// XXX tmp: copy for easier writing or slice for performance ?
std::vector<uint8_t> tmp = data;
// FIXME factorize
tmp.erase(tmp.begin(), tmp.begin() + size);
size = m_pdu_session_identity.decode_V(data[offset]);
offset += size;
tmp.erase(tmp.begin(), tmp.begin() + size);
size = m_procedure_transaction_identity.decode_V(data[offset + 1]);
offset += size;
tmp.erase(tmp.begin(), tmp.begin() + size);
m_message_type.decode(tmp, InformationElement::Format::V);
offset += size;
return offset;
}
}; // namespace _5GS
| 26.936508 | 90 | 0.628757 | [
"vector"
] |
8a9779e9605a59959de570e6171dc397023b38d6 | 2,134 | cpp | C++ | algorithms/design-circular-queue.cpp | Chronoviser/leetcode-1 | 65ee0504d64c345f822f216fef6e54dd62b8f858 | [
"MIT"
] | 41 | 2018-07-03T07:35:30.000Z | 2021-09-25T09:33:43.000Z | algorithms/design-circular-queue.cpp | Chronoviser/leetcode-1 | 65ee0504d64c345f822f216fef6e54dd62b8f858 | [
"MIT"
] | 2 | 2018-07-23T10:50:11.000Z | 2020-10-06T07:34:29.000Z | algorithms/design-circular-queue.cpp | Chronoviser/leetcode-1 | 65ee0504d64c345f822f216fef6e54dd62b8f858 | [
"MIT"
] | 7 | 2018-07-06T13:43:18.000Z | 2020-10-06T02:29:57.000Z | class MyCircularQueue {
private:
vector<int> data;
int front = 0, rear = 0;
bool full = false;
int size()
{
if (this->full) return this->data.size();
if (this->front <= this->rear) {
return this->rear - this->front;
} else {
return this->rear + this->data.size() - this->front;
}
}
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
this->data = vector<int>(k, -1);
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value)
{
if (this->isFull()) return false;
this->rear = (this->rear + 1) % this->data.size();
this->data[this->rear % this->data.size()] = value;
if (this->rear == this->front) {
this->full = true;
}
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue()
{
if (this->isEmpty()) return false;
this->front = (this->front + 1) % this->data.size();
this->full = false;
return true;
}
/** Get the front item from the queue. */
int Front()
{
if (this->isEmpty()) return -1;
return this->data[(this->front + 1) % this->data.size()];
}
/** Get the last item from the queue. */
int Rear()
{
if (this->isEmpty()) return -1;
return this->data[this->rear];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
return this->size() == 0;
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
return this->full;
}
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* bool param_1 = obj.enQueue(value);
* bool param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* bool param_5 = obj.isEmpty();
* bool param_6 = obj.isFull();
*/
| 24.528736 | 97 | 0.550141 | [
"object",
"vector"
] |
8a9e7b89f503cd24f9563fe40a153006ee3ff8ca | 2,582 | cc | C++ | src/main.cc | bozbalci/fk | f38576f313cfae0117c2e5145c02de2ecc1831a8 | [
"BSD-2-Clause"
] | 2 | 2017-03-28T13:06:56.000Z | 2020-09-14T05:56:00.000Z | src/main.cc | bozbalci/fk | f38576f313cfae0117c2e5145c02de2ecc1831a8 | [
"BSD-2-Clause"
] | 1 | 2017-03-07T19:58:51.000Z | 2017-03-07T20:16:48.000Z | src/main.cc | bozbalci/fk | f38576f313cfae0117c2e5145c02de2ecc1831a8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2017, Berk Ozbalci
* All rights reserved.
*/
#include "parser/parser.h"
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Value.h>
#include <iostream>
#include <fstream>
#include <sstream>
int
main(int argc, char *argv[])
{
// TODO: Make this more beautiful.
// begin hack --------------------
if (argc < 2)
{
std::cout << "usage: fk [filename]" << std::endl;
return 1;
}
std::string filename(argv[1]);
std::ifstream t(filename);
std::stringstream buffer;
buffer << t.rdbuf();
std::string program_data = buffer.str();
// end hack --------------------
FkParser parser(program_data);
llvm::LLVMContext llvm_context;
std::string module_name = "testmodule";
llvm::ErrorOr<llvm::Module *> module_or_err
= new llvm::Module(module_name, llvm_context);
auto owner = std::unique_ptr<llvm::Module>(module_or_err.get());
auto *module = owner.get();
auto *MainF = llvm::cast<llvm::Function>(
module->getOrInsertFunction(
"main",
llvm::Type::getInt32Ty(llvm_context),
(llvm::Type *) 0
)
);
llvm::BasicBlock *entry_block = llvm::BasicBlock::Create(
llvm_context,
"EntryBlock", // convention
MainF
);
llvm::IRBuilder<> builder(entry_block);
builder.SetInsertPoint(entry_block);
parser.generate_code(module, builder);
builder.CreateRet(builder.getInt32(0));
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string error_string;
llvm::EngineBuilder *EB = new llvm::EngineBuilder(std::move(owner));
llvm::ExecutionEngine *EE = EB->setErrorStr(&error_string)
.setMCJITMemoryManager(std::unique_ptr<llvm::SectionMemoryManager>
(new llvm::SectionMemoryManager())).create();
if (!error_string.empty())
{
std::cerr << error_string << std::endl;
exit(1);
}
EE->finalizeObject();
std::vector<llvm::GenericValue> Args(0);
llvm::GenericValue gv = EE->runFunction(MainF, Args);
delete EE;
llvm::llvm_shutdown();
return 0;
}
| 26.618557 | 74 | 0.640976 | [
"vector"
] |
8a9fd430aa9c1ec770af8fcd37d4a635f86714ef | 3,013 | cpp | C++ | Source/Database/Value.cpp | alvinahmadov/Dixter | 6f98f1e84192e1e43eee409bdee6b3dac75d6443 | [
"MIT"
] | 4 | 2018-12-06T01:20:50.000Z | 2019-08-04T10:19:23.000Z | Source/Database/Value.cpp | alvinahmadov/Dixter | 6f98f1e84192e1e43eee409bdee6b3dac75d6443 | [
"MIT"
] | null | null | null | Source/Database/Value.cpp | alvinahmadov/Dixter | 6f98f1e84192e1e43eee409bdee6b3dac75d6443 | [
"MIT"
] | null | null | null | /**
* Copyright (C) 2015-2019
* Author Alvin Ahmadov <alvin.dev.ahmadov@gmail.com>
*
* This file is part of Dixter Project
* License-Identifier: MIT License
* See README.md for more information.
*/
#include "Value.hpp"
#include "Macros.hpp"
#include "Exception.hpp"
namespace Dixter
{
namespace Database
{
TValue::TValue(const TString& name, EDataType type, TSize size,
bool null, bool primaryKey, bool autoIncrement) noexcept
: m_null(null),
m_primaryKey(primaryKey),
m_autoIncrement(autoIncrement),
m_size(size),
m_name(name),
m_type(type)
{ }
const TString&
TValue::getValueName() const
{
return m_name;
}
const EDataType&
TValue::getType() const
{
return m_type;
}
TString
TValue::getTypeString() const
{
switch (m_type)
{
case EDataType::kBit:
return dxSTR(BIT);
case EDataType::kTinyInt:
return dxSTR(TINYINT);
case EDataType::kSmallInt:
return dxSTR(SMALLINT);
case EDataType::kMediumInt:
return dxSTR(MEDIUMINT);
case EDataType::kInteger:
return dxSTR(INTEGER);
case EDataType::kBigInt:
return dxSTR(BIGINT);
case EDataType::kReal:
return dxSTR(REAL);
case EDataType::kNumeric:
return dxSTR(NUMERIC);
case EDataType::kChar:
return dxSTR(CHAR);
case EDataType::kBinary:
return dxSTR(BINARY);
case EDataType::kVarChar:
return dxSTR(VARCHAR);
case EDataType::kVarBinary:
return dxSTR(VARBINARY);
case EDataType::kLongVarChar:
return dxSTR(LONGVARCHAR);
case EDataType::kLongVarBinary:
return dxSTR(LONGVARBINARY);
case EDataType::kTimeStamp:
return dxSTR(TIMESTAMP);
case EDataType::kDate:
return dxSTR(DATE);
case EDataType::kTime:
return dxSTR(TIME);
case EDataType::kYear:
return dxSTR(YEAR);
case EDataType::kDecimal:
return dxSTR(DECIMAL);
case EDataType::kDouble:
return dxSTR(DOUBLE);
case EDataType::kGeometry:
return dxSTR(GEOMETRY);
case EDataType::kEnum:
return dxSTR(ENUM);
case EDataType::kSet:
return dxSTR(SET);
case EDataType::kSqlNull:
return dxSTR(SQLNULL);
case EDataType::kJson:
return dxSTR(JSON);
case EDataType::kTinyText:
return dxSTR(TINYTEXT);
case EDataType::kText:
return dxSTR(TEXT);
case EDataType::kMediumText:
return dxSTR(MEDIUMTEXT);
case EDataType::kLongText:
return dxSTR(LONGTEXT);
case EDataType::kInt:
return dxSTR(INT);
case EDataType::kBool:
return dxSTR(BOOL);
default:
throw TNotFoundException("%s:%d Unknown type.\n", __FILE__, __LINE__);
}
}
const TSize&
TValue::getSize() const
{
return m_size;
}
bool TValue::isAutoIncrement() const
{
return m_autoIncrement;
}
bool TValue::isPrimaryKey() const
{
return m_primaryKey;
}
bool TValue::isNull() const
{
return m_null;
}
} // namespace Database
} // namespace Dixter | 22.654135 | 75 | 0.65682 | [
"geometry"
] |
8aa1d0b0ecc673e8c5576aae4a164df240a02989 | 2,973 | cpp | C++ | 4_course/4_week_construct_suffix_array_and_tree/2_suffix_array/main.cpp | claytonjwong/Algorithms-UCSD | 09d433a1cbc00dc8d913ece8716ac539b81340cd | [
"Unlicense"
] | 6 | 2019-11-13T01:19:28.000Z | 2021-08-10T19:19:57.000Z | 4_course/4_week_construct_suffix_array_and_tree/2_suffix_array/main.cpp | claytonjwong/Algorithms-UCSD | 09d433a1cbc00dc8d913ece8716ac539b81340cd | [
"Unlicense"
] | null | null | null | 4_course/4_week_construct_suffix_array_and_tree/2_suffix_array/main.cpp | claytonjwong/Algorithms-UCSD | 09d433a1cbc00dc8d913ece8716ac539b81340cd | [
"Unlicense"
] | 3 | 2019-11-13T03:11:15.000Z | 2020-11-28T20:05:38.000Z | /**
*
* C++ implementation to create a Suffix Array in near-linear time
*
* (c) Copyright 2019 Clayton J. Wong ( http://www.claytonjwong.com )
*
**/
#include <iomanip>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
using namespace std;
using Collection = vector< int >;
using Count = Collection;
using Class = Collection;
using Order = Collection;
int main() {
string S; cin >> S;
const auto N = static_cast< int >( S.size() );
Order order( N ); { // order <- SortCharacters( S )
const auto M = 'T' + 1; // alphabet size
Count cnt( M, 0 );
for( auto i{ 0 }; i < N; ++i ){
auto ch = S[ i ];
++cnt[ ch ]; // count of each unique char
}
for( auto j{ 1 }; j < M; ++j )
cnt[ j ] += cnt[ j-1 ]; // prefix sums ( i.e. one-past the end of each unique char's index range )
for( auto i{ N-1 }; 0 <= i; --i ){
auto ch = S[ i ];
--cnt[ ch ];
order[ cnt[ ch ] ] = i;
}
}
Class classes( N ); { // classes <- ComputeCharClasses( S, order )
classes[ order[ 0 ] ] = 0;
for( auto i{ 1 }; i < N; ++i )
if( S[ order[ i ] ] != S[ order[ i-1 ] ] )
classes[ order[ i ] ] = classes[ order[ i-1 ] ] + 1; // diff equivalence class
else
classes[ order[ i ] ] = classes[ order[ i-1 ] ]; // same equivalence class
}
for( auto L{ 1 }; L < N; L *= 2 ){ // order <- SortDoubled( S, L, order, classes )
Count cnt( N, 0 ); {
for( auto i{ 0 }; i < N; ++i ){
auto cl = classes[ i ];
++cnt[ cl ];
}
for( auto j{ 1 }; j < N; ++j )
cnt[ j ] += cnt[ j-1 ];
}
Order next_order( N ); {
for( auto i{ N-1 }; 0 <= i; --i ){
auto start = ( order[ i ] - L + N ) % N; // start is the begin index of the doubled cyclic shift
auto cl = classes[ start ];
--cnt[ cl ];
next_order[ cnt[ cl ] ] = start;
}
}
order.swap( next_order );
Class next_classes( N ); { // UpdateClasses( L, next_order, classes )
next_classes[ order[ 0 ] ] = 0;
for( auto i{ 1 }; i < N; ++i ){
auto pre = order[ i-1 ], preMid = ( pre + L ) % N,
cur = order[ i ], curMid = ( cur + L ) % N;
if( classes[ pre ] != classes[ cur ] || classes[ preMid ] != classes[ curMid ] )
next_classes[ cur ] = next_classes[ pre ] + 1; // diff equivalence class
else
next_classes[ cur ] = next_classes[ pre ]; // same equivalence class
}
}
classes.swap( next_classes );
}
copy_n( order.begin(), N, ostream_iterator< int >( cout, " " ) ); cout << endl;
return 0;
}
| 36.256098 | 112 | 0.459805 | [
"vector"
] |
8aa4a62b07817a399ca6ab9d4413cf99b4a1f4ab | 6,518 | cpp | C++ | sky/engine/core/rendering/RenderLayerModelObject.cpp | viettrungluu-cr/mojo | 950de5bc66e00aeb1f7bdf2987f253986c0a7614 | [
"BSD-3-Clause"
] | 5 | 2019-05-24T01:25:34.000Z | 2020-04-06T05:07:01.000Z | sky/engine/core/rendering/RenderLayerModelObject.cpp | viettrungluu-cr/mojo | 950de5bc66e00aeb1f7bdf2987f253986c0a7614 | [
"BSD-3-Clause"
] | null | null | null | sky/engine/core/rendering/RenderLayerModelObject.cpp | viettrungluu-cr/mojo | 950de5bc66e00aeb1f7bdf2987f253986c0a7614 | [
"BSD-3-Clause"
] | 5 | 2016-12-23T04:21:10.000Z | 2020-06-18T13:52:33.000Z | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
* (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2010, 2012 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "sky/engine/config.h"
#include "sky/engine/core/rendering/RenderLayerModelObject.h"
#include "sky/engine/core/frame/LocalFrame.h"
#include "sky/engine/core/rendering/RenderLayer.h"
#include "sky/engine/core/rendering/RenderView.h"
namespace blink {
RenderLayerModelObject::RenderLayerModelObject(ContainerNode* node)
: RenderObject(node)
{
}
RenderLayerModelObject::~RenderLayerModelObject()
{
// Our layer should have been destroyed and cleared by now
ASSERT(!hasLayer());
ASSERT(!m_layer);
}
void RenderLayerModelObject::destroyLayer()
{
setHasLayer(false);
m_layer = nullptr;
}
void RenderLayerModelObject::createLayer(LayerType type)
{
ASSERT(!m_layer);
m_layer = adoptPtr(new RenderLayer(this, type));
setHasLayer(true);
m_layer->insertOnlyThisLayer();
}
bool RenderLayerModelObject::hasSelfPaintingLayer() const
{
return m_layer && m_layer->isSelfPaintingLayer();
}
ScrollableArea* RenderLayerModelObject::scrollableArea() const
{
return m_layer ? m_layer->scrollableArea() : 0;
}
void RenderLayerModelObject::willBeDestroyed()
{
RenderObject::willBeDestroyed();
destroyLayer();
}
void RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
{
if (RenderStyle* oldStyle = style()) {
if (parent() && diff.needsPaintInvalidationLayer()) {
if (oldStyle->hasAutoClip() != newStyle.hasAutoClip()
|| oldStyle->clip() != newStyle.clip())
layer()->clipper().clearClipRectsIncludingDescendants();
}
}
RenderObject::styleWillChange(diff, newStyle);
}
void RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
bool hadTransform = hasTransform();
RenderObject::styleDidChange(diff, oldStyle);
updateFromStyle();
LayerType type = layerTypeRequired();
if (type != NoLayer) {
if (!layer()) {
createLayer(type);
if (parent() && !needsLayout()) {
// FIXME: This invalidation is overly broad. We should update to
// do the correct invalidation at RenderStyle::diff time. crbug.com/349061
layer()->renderer()->setShouldDoFullPaintInvalidation(true);
// FIXME: We should call a specialized version of this function.
layer()->updateLayerPositionsAfterLayout();
}
}
} else if (layer() && layer()->parent()) {
setHasTransform(false); // Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.
layer()->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
if (hadTransform)
setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
}
if (layer()) {
// FIXME: Ideally we shouldn't need this setter but we can't easily infer an overflow-only layer
// from the style.
layer()->setLayerType(type);
layer()->styleChanged(diff, oldStyle);
}
}
InvalidationReason RenderLayerModelObject::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)
{
const LayoutRect oldPaintInvalidationRect = previousPaintInvalidationRect();
const LayoutPoint oldPositionFromPaintInvalidationContainer = previousPositionFromPaintInvalidationContainer();
setPreviousPaintInvalidationRect(boundsRectForPaintInvalidation(&newPaintInvalidationContainer, &paintInvalidationState));
setPreviousPositionFromPaintInvalidationContainer(RenderLayer::positionFromPaintInvalidationContainer(this, &newPaintInvalidationContainer, &paintInvalidationState));
// If we are set to do a full paint invalidation that means the RenderView will issue
// paint invalidations. We can then skip issuing of paint invalidations for the child
// renderers as they'll be covered by the RenderView.
if (view()->doingFullPaintInvalidation())
return InvalidationNone;
return RenderObject::invalidatePaintIfNeeded(newPaintInvalidationContainer, oldPaintInvalidationRect, oldPositionFromPaintInvalidationContainer, paintInvalidationState);
}
void RenderLayerModelObject::invalidateTreeIfNeeded(const PaintInvalidationState& paintInvalidationState)
{
// FIXME: SVG should probably also go through this unified paint invalidation system.
ASSERT(!needsLayout());
if (!shouldCheckForPaintInvalidation(paintInvalidationState))
return;
bool establishesNewPaintInvalidationContainer = isPaintInvalidationContainer();
const RenderLayerModelObject& newPaintInvalidationContainer = *adjustCompositedContainerForSpecialAncestors(establishesNewPaintInvalidationContainer ? this : &paintInvalidationState.paintInvalidationContainer());
ASSERT(&newPaintInvalidationContainer == containerForPaintInvalidation());
InvalidationReason reason = invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);
PaintInvalidationState childTreeWalkState(paintInvalidationState, *this, newPaintInvalidationContainer);
if (reason == InvalidationLocationChange || reason == InvalidationFull)
childTreeWalkState.setForceCheckForPaintInvalidation();
RenderObject::invalidateTreeIfNeeded(childTreeWalkState);
}
} // namespace blink
| 40.484472 | 216 | 0.73857 | [
"object",
"transform"
] |
8ab00d398b70b08079bf2a227f2f833caa5efd6e | 14,144 | hh | C++ | include/ftk/features/feature_curve.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 19 | 2018-11-01T02:15:17.000Z | 2022-03-28T16:55:00.000Z | include/ftk/features/feature_curve.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 12 | 2019-04-14T12:49:41.000Z | 2021-10-20T03:59:21.000Z | include/ftk/features/feature_curve.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 9 | 2019-02-08T19:40:46.000Z | 2021-06-15T00:31:09.000Z | #ifndef _FTK_FEATURE_CURVE_T_HH
#define _FTK_FEATURE_CURVE_T_HH
#include <ftk/features/feature_point.hh>
namespace ftk {
struct feature_curve_t : public std::vector<feature_point_t>
{
feature_curve_t() {}
feature_curve_t(const feature_curve_t&);
feature_curve_t& operator=(const feature_curve_t&);
void relabel(int i); // assign id for traj and each point in the traj
void update_statistics();
void derive_velocity(); // (const std::vector<double> &dog_kernel); // assuming the traj contains only ordinal points (dt=1)
std::vector<feature_curve_t> split() const; // split to consistent subtrajs
std::vector<int/*idx in original traj*/> to_ordinals() const;
std::vector<int/*idx in original traj*/> select(std::function<bool(const feature_point_t&)> f);
void rotate(); //! if the traj is a loop and the type is inconsistent, rotate the traj before splitting
void reorder(); //! reorder by timestep
void adjust_time(); //! assuming traj has only one single branch and is organized in ascending order, ensure that the time increases monotonously
void smooth_ordinal_types(const int half_window_size=2); // make types of ordinal points robust to noises
void smooth_interval_types(); //! make types in intervals consistent
void discard(std::function<bool(const feature_point_t&)> f);
void discard_high_cond(double threshold = 1e8); //! prune points with very high condition numbers, unless the point is ordinal
void discard_interval_points();
void discard_degenerate_points();
int locate(double t, bool cap=false/*lower (false) or higher (true) cap*/) const; //! locate interval id of given t; assuming the traj is already reordered
void copy_info(feature_curve_t& t) {id = t.id; complete = t.complete; loop = t.loop;}
feature_curve_t intercept(int t0, int t1) const; //! assuming the traj is already reordered
template <int k=2> void unwrap(const double period); // unwrap the curve in a periodical domain
public:
int id;
bool complete = false, loop = false;
std::array<double, FTK_CP_MAX_NUM_VARS> max, min, persistence;
std::array<double, 3> bbmin, bbmax; // bounding box
double tmin, tmax; // time bounding box
double vmmin, vmmax; // min/max moving speed
unsigned int consistent_type = 0; // 0 if no consistent type
};
/////////
inline feature_curve_t::feature_curve_t(const feature_curve_t& c)
{
id = c.id;
complete = c.complete;
loop = c.loop;
max = c.max;
min = c.min;
persistence = c.persistence;
bbmin = c.bbmin;
bbmax = c.bbmax;
tmin = c.tmin;
tmax = c.tmax;
vmmin = c.vmmin;
vmmax = c.vmmax;
consistent_type = c.consistent_type;
for (const feature_point_t& p : c)
this->push_back(p);
}
inline feature_curve_t& feature_curve_t::operator=(const feature_curve_t& c)
{
id = c.id;
complete = c.complete;
loop = c.loop;
max = c.max;
min = c.min;
persistence = c.persistence;
bbmin = c.bbmin;
bbmax = c.bbmax;
tmin = c.tmin;
tmax = c.tmax;
vmmin = c.vmmin;
vmmax = c.vmmax;
consistent_type = c.consistent_type;
clear();
for (const feature_point_t& p : c)
this->push_back(p);
return *this;
}
inline void feature_curve_t::relabel(int i)
{
id = i;
for (i = 0; i < size(); i ++)
at(i).id = id;
}
inline std::vector<int> feature_curve_t::select(std::function<bool(const feature_point_t&)> f)
{
std::vector<int> result;
for (int i = 0; i < size(); i ++)
if (f(at(i)))
result.push_back(i);
return result;
}
inline void feature_curve_t::discard(std::function<bool(const feature_point_t&)> f)
{
feature_curve_t traj;
traj.copy_info(*this);
for (const auto &cp : *this)
if (!f(cp))
traj.push_back(cp);
traj.update_statistics();
*this = traj;
}
inline void feature_curve_t::discard_interval_points() {
discard([&](const feature_point_t& cp) { return !cp.ordinal; });
}
inline void feature_curve_t::discard_degenerate_points() {
discard([&](const feature_point_t& cp) {
return cp.type == 0 || cp.type == 1;
});
}
inline void feature_curve_t::discard_high_cond(double threshold)
{
discard([&](const feature_point_t& cp) {
if (std::isinf(cp.cond) || std::isnan(cp.cond) || cp.cond > threshold) return true;
else return false;
});
}
inline void feature_curve_t::update_statistics() {
if (empty()) return; // nothing to do
max.fill( std::numeric_limits<double>::lowest() );
min.fill( std::numeric_limits<double>::max() );
bbmax.fill( std::numeric_limits<double>::lowest() );
bbmin.fill( std::numeric_limits<double>::max() );
tmax = std::numeric_limits<double>::lowest();
tmin = std::numeric_limits<double>::max();
vmmax = std::numeric_limits<double>::lowest();
vmmin = std::numeric_limits<double>::max();
for (auto i = 0; i < size(); i ++) {
for (int k = 0; k < FTK_CP_MAX_NUM_VARS; k ++) {
max[k] = std::max(max[k], at(i).scalar[k]);
min[k] = std::min(min[k], at(i).scalar[k]);
}
for (int k = 0; k < 3; k ++) {
bbmax[k] = std::max(bbmax[k], at(i).x[k]);
bbmin[k] = std::min(bbmin[k], at(i).x[k]);
}
tmax = std::max(tmax, at(i).t);
tmin = std::min(tmin, at(i).t);
vmmax = std::max(vmmax, at(i).vmag());
vmmin = std::min(vmmin, at(i).vmag());
}
for (int k = 0; k < FTK_CP_MAX_NUM_VARS; k ++)
persistence[k] = max[k] - min[k];
consistent_type = at(0).type;
for (auto i = 0; i < size(); i ++)
if (consistent_type != at(i).type) {
consistent_type = 0;
break;
}
}
inline std::vector<feature_curve_t> feature_curve_t::split() const
{
std::vector<feature_curve_t> results;
feature_curve_t subtraj;
unsigned int current_type;
for (auto i = 0; i < size(); i ++) {
if (subtraj.empty())
current_type = at(i).type;
if (at(i).type == current_type)
subtraj.push_back(at(i));
if (at(i).type != current_type || i == size() - 1) {
if (subtraj.size() > 0) {
subtraj.update_statistics();
results.push_back(subtraj);
subtraj.clear();
}
}
}
return results;
}
inline std::vector<int> feature_curve_t::to_ordinals() const
{
std::vector<int> result;
for (auto i = 0; i < size(); i ++)
if (at(i).ordinal)
result.push_back(i);
return result;
}
inline void feature_curve_t::rotate() //! if the traj is a loop and the type is inconsistent, rotate the traj before splitting
{
if (!loop) return;
if (front().type != back().type) return;
int i;
for (i = 0; i < size(); i ++)
if (front().type != at(i).type) break;
if (i < size()) {
// fprintf(stderr, "rotating, i=%d, size=%zu\n", i, size());
std::rotate(begin(), begin()+i, end());
}
}
inline void feature_curve_t::reorder() { // reorder by timestep
if (empty()) return;
if (loop) return;
bool reverse = false;
if (front().timestep == back().timestep) {
if (front().t > back().t) reverse = true;
} else {
if (front().timestep > back().timestep)
reverse = true;
}
if (reverse)
std::reverse(std::begin(*this), std::end(*this));
}
inline void feature_curve_t::adjust_time() { //! assuming traj has only one single branch and is organized in ascending order, ensure that the time increases monotonously
// ascending loop
for (auto i = 0; i < size(); i ++) {
if (i == 0 || at(i).ordinal) continue;
at(i).t = std::max(at(i-1).t, at(i).t);
}
// descending loop
for (auto i = size(); i -- > 0; ) {
if (i == size() - 1 || at(i).ordinal) continue;
at(i).t = std::min(at(i+1).t, at(i).t);
}
}
inline void feature_curve_t::smooth_ordinal_types(const int half_window_size) {
auto ordinals = to_ordinals();
if (ordinals.size() < half_window_size*2+1) return;
// 1. smooth ordinal types
std::map<int/*idx in orginal traj*/, unsigned int/*target type*/> pending_changes;
for (int i = half_window_size; i < ordinals.size() - half_window_size; i ++) {
unsigned int local_consistent_type = at(ordinals[i - half_window_size]).type;
for (int j = i - half_window_size; j <= i + half_window_size; j ++) {
if (j == i) continue;
else if (local_consistent_type != at(ordinals[j]).type) {
local_consistent_type = 0; // type is inconsistent within the window
break;
}
}
if (local_consistent_type != 0 && at(ordinals[i]).type != local_consistent_type)
pending_changes[ordinals[i]] = local_consistent_type;
}
for (const auto &kv : pending_changes)
at(kv.first).type = kv.second;
}
inline void feature_curve_t::smooth_interval_types() { //! make types in intervals consistent
const auto ordinals = to_ordinals();
if (ordinals.empty()) return;
// front terminal
const unsigned int front_terminal_type = at(ordinals[0]).type;
for (int i = 0; i < ordinals[0]; i ++)
at(i).type = front_terminal_type;
// back terminal
const unsigned int back_terminal_type = at(ordinals[ordinals.size()-1]).type;
for (int i = ordinals[ordinals.size()-1]; i < size(); i ++)
at(i).type = back_terminal_type;
// intervals; preventing type oscilation within intervals
for (int i = 0; i < ordinals.size()-1; i ++) {
if (at(ordinals[i]).type == at(ordinals[i+1]).type) {
const unsigned int interval_type = at(ordinals[i]).type;
for (int j = ordinals[i]; j < ordinals[i+1]; j ++)
at(j).type = interval_type;
} else { // find the first point that changes type, and then smooth the rest in the interval
const unsigned int ltype = at(ordinals[i]).type, rtype = at(ordinals[i+1]).type;
int j;
for (j = ordinals[i] ; j < ordinals[i+1]; j ++)
if (at(j).type != ltype) break;
for (; j < ordinals[i+1]; j ++)
at(j).type = rtype;
}
}
}
inline int feature_curve_t::locate(double t, bool cap) const
{
return 0; // TODO: WIP
}
inline feature_curve_t feature_curve_t::intercept(int t0, int t1) const //! assuming the traj is already reordered
{
feature_curve_t result;
if (t0 > back().t || t1 < front().t)
return result;
for (int i = 0; i < size(); i ++)
if (at(i).t >= t0 && at(i).t <= t1)
result.push_back(at(i));
if (result.size() > 0) {
result.relabel(id);
result.update_statistics();
}
return result;
}
template <int k> void feature_curve_t::unwrap(const double period)
{
for (int i = 0; i < size()-1; i ++) {
const double delta = at(i+1).x[k] - at(i).x[k];
if (delta >= period/2) {
for (int j = i+1; j < size(); j ++)
at(j).x[k] -= period;
} else if (delta <= -period/2) {
for (int j = i+1; j < size(); j ++)
at(j).x[k] += period;
}
}
// update_statistics();
bbmin[k] = std::numeric_limits<double>::max();
bbmax[k] = std::numeric_limits<double>::lowest();
for (auto i = 0; i < size(); i ++) {
bbmax[k] = std::max(bbmax[k], at(i).x[k]);
bbmin[k] = std::min(bbmin[k], at(i).x[k]);
}
}
inline void feature_curve_t::derive_velocity() // const std::vector<double> &kernel)
{
if (size() < 2) return;
// const int half_kernel_size = kernel.size() / 2;
for (int k = 0; k < 3 /*cpdims*/; k ++) {
for (int i = 0; i < size(); i ++) {
if (i == 0) at(i).
v[k] = at(i+1).x[k] - at(i).x[k];
else if (i == size()-1)
at(i).v[k] = at(i).x[k] - at(i-1).x[k];
else at(i).v[k] =
0.5 * (at(i+1).x[k] - at(i-1).x[k]);
}
#if 0
// preparation & padding
std::vector<double> f(size() + half_kernel_size * 2);
for (int i = 0; i < half_kernel_size; i ++) {
f[i] = front().x[k];
f[half_kernel_size + size() + i] = back().x[k];
}
for (int i = 0; i < size(); i ++)
f[half_kernel_size + i] = at(i).x[k];
// convolution
for (int i = 0; i < size(); i ++) {
double v = 0;
for (int j = 0; j < kernel.size(); j ++)
v += f[i + half_kernel_size + j] * kernel[j];
at(i).velocity[k] = v;
}
#endif
}
}
} // namespace ftk
// serialization w/ json
namespace nlohmann
{
using namespace ftk;
template <>
struct adl_serializer<feature_curve_t> {
static void to_json(json &j, const feature_curve_t& t) {
j = {
{"id", t.id},
{"max", t.max},
{"min", t.min},
{"persistence", t.persistence},
{"bbmin", t.bbmin},
{"bbmax", t.bbmax},
{"tmin", t.tmin},
{"tmax", t.tmax},
{"consistent_type", t.consistent_type},
{"traj", static_cast<std::vector<feature_point_t>>(t)}
};
}
static void from_json(const json&j, feature_curve_t& t) {
t.id = j["id"];
t.max = j["max"];
t.min = j["min"];
t.persistence = j["persistence"];
t.bbmin = j["bbmin"];
t.bbmax = j["bbmax"];
t.tmin = j["tmin"];
t.tmax = j["tmax"];
t.consistent_type = j["consistent_type"];
std::vector<feature_point_t> traj = j["traj"];
t.clear();
t.insert(t.begin(), traj.begin(), traj.end());
}
};
}
// serialization
namespace diy {
template <> struct Serialization<ftk::feature_curve_t> {
static void save(diy::BinaryBuffer& bb, const ftk::feature_curve_t &t) {
diy::save(bb, t.complete);
diy::save(bb, t.max);
diy::save(bb, t.min);
diy::save(bb, t.persistence);
diy::save(bb, t.bbmin);
diy::save(bb, t.bbmax);
diy::save(bb, t.tmin);
diy::save(bb, t.tmax);
diy::save(bb, t.consistent_type);
diy::save(bb, t.size());
for (auto i = 0; i < t.size(); i ++)
diy::save(bb, t[i]);
// diy::save<std::vector<ftk::feature_point_t>>(bb, t);
}
static void load(diy::BinaryBuffer& bb, ftk::feature_curve_t &t) {
diy::load(bb, t.complete);
diy::load(bb, t.max);
diy::load(bb, t.min);
diy::load(bb, t.persistence);
diy::load(bb, t.bbmin);
diy::load(bb, t.bbmax);
diy::load(bb, t.tmin);
diy::load(bb, t.tmax);
diy::load(bb, t.consistent_type);
size_t s;
diy::load(bb, s);
t.resize(s);
for (auto i = 0; i < t.size(); i ++)
diy::load(bb, t[i]);
// diy::load<std::vector<ftk::feature_point_t>>(bb, t);
}
};
} // namespace diy
#endif
| 30.093617 | 170 | 0.605204 | [
"vector"
] |
8ab86905725d8a9c324e68fa97718091016032bb | 1,327 | cpp | C++ | core/game_engine/base_engine.cpp | anschen1994/RLCardCXX | 87820626d8f3ef4a2da63ab37a97064980bd4dd5 | [
"MIT"
] | 1 | 2021-12-03T00:06:22.000Z | 2021-12-03T00:06:22.000Z | core/game_engine/base_engine.cpp | anschen1994/RLCardCXX | 87820626d8f3ef4a2da63ab37a97064980bd4dd5 | [
"MIT"
] | null | null | null | core/game_engine/base_engine.cpp | anschen1994/RLCardCXX | 87820626d8f3ef4a2da63ab37a97064980bd4dd5 | [
"MIT"
] | null | null | null | #include "base_engine.h"
#include "../utils/helper.h"
namespace rlcard
{
namespace engine
{
int Card::hash(const string &_suit, const string &_rank)
{
int suit_index = rlcard::GetIndexOfVector(kSuit, _suit);
int rank_index = rlcard::GetIndexOfVector(kRank, _rank);
return rank_index + 100 * suit_index;
}
Dealer::~Dealer()
{
for (auto card : deck_)
{
delete card;
}
deck_.clear();
for (auto card : remained_cards_)
{
delete card;
}
remained_cards_.clear();
}
const vector<Card*> & Player::GetHandCard()
{
return hand_cards_;
}
Player::Player(const Player & _player)
{
for (auto card : _player.hand_cards_)
{
Card * p_card = new Card(card->GetSuit(), card->GetRank());
hand_cards_.push_back(p_card);
}
player_id_ = _player.player_id_;
}
Player::~Player()
{
for (auto card : hand_cards_)
{
delete card;
}
hand_cards_.clear();
}
} // namespace engine
} // namespace rlcard
| 24.574074 | 75 | 0.470234 | [
"vector"
] |
8abc3b0ca4c9ad83e64c8d12085f3a14d472d069 | 1,702 | hpp | C++ | src/share/state_json_writer.hpp | egelwan/Karabiner-Elements | 896439dd2130904275553282063dd7fe4852e1a8 | [
"Unlicense"
] | 5,422 | 2019-10-27T17:51:04.000Z | 2022-03-31T15:45:41.000Z | src/share/state_json_writer.hpp | egelwan/Karabiner-Elements | 896439dd2130904275553282063dd7fe4852e1a8 | [
"Unlicense"
] | 1,310 | 2019-10-28T04:57:24.000Z | 2022-03-31T04:55:37.000Z | src/share/state_json_writer.hpp | egelwan/Karabiner-Elements | 896439dd2130904275553282063dd7fe4852e1a8 | [
"Unlicense"
] | 282 | 2019-10-28T02:36:04.000Z | 2022-03-19T06:18:54.000Z | #pragma once
// `krbn::state_json_writer` can be used safely in a multi-threaded environment.
#include "json_utility.hpp"
#include "json_writer.hpp"
#include <optional>
#include <thread>
namespace krbn {
class state_json_writer final {
public:
state_json_writer(const std::filesystem::path& file_path) : file_path_(file_path),
state_(nlohmann::json::object()) {
std::ifstream input(file_path);
if (input) {
try {
state_ = json_utility::parse_jsonc(input);
} catch (std::exception& e) {
logger::get_logger()->error("parse error in {0}: {1}", file_path.string(), e.what());
}
} else {
sync_save();
}
}
template <typename T>
void set(const std::string& key,
const T& value) {
std::lock_guard<std::mutex> guard(mutex_);
if (state_[key] == value) {
return;
}
state_[key] = value;
sync_save();
}
void set(const std::string& key,
const std::nullopt_t value) {
std::lock_guard<std::mutex> guard(mutex_);
if (!state_.contains(key)) {
return;
}
state_.erase(key);
sync_save();
}
template <typename T>
void set(const std::string& key,
const std::optional<T>& value) {
if (value) {
set(key, *value);
} else {
set(key, std::nullopt);
}
}
private:
void sync_save(void) {
json_writer::sync_save_to_file(state_,
file_path_,
0755,
0644);
}
std::filesystem::path file_path_;
std::mutex mutex_;
nlohmann::json state_;
};
} // namespace krbn
| 22.103896 | 96 | 0.552291 | [
"object"
] |
8ac2fc7057567d7ad2a1d4ab988709d141df8ce2 | 490 | hpp | C++ | src/Actor.hpp | jesusredondo/templateRouguelite | 212d729f6e43076b7f487a64c20430ba375dd51b | [
"Unlicense"
] | null | null | null | src/Actor.hpp | jesusredondo/templateRouguelite | 212d729f6e43076b7f487a64c20430ba375dd51b | [
"Unlicense"
] | null | null | null | src/Actor.hpp | jesusredondo/templateRouguelite | 212d729f6e43076b7f487a64c20430ba375dd51b | [
"Unlicense"
] | null | null | null | #include "main.hpp"
#pragma once
class Actor {
public :
int x,y; // position on map
int ch; // ascii code
std::string name;
TCODColor col; // color
bool blocks; //Se puede andar por encima?
Attacker* attacker; // El componente de ataque
Destructible* destructible; // El componente destructible
Ai* ai; // El componente de actualización
Actor(int x, int y, int ch, std::string name, const TCODColor &col);
~Actor();
void render( ) const;
void update() ;
};
| 18.846154 | 71 | 0.665306 | [
"render"
] |
8ac9fb3fc45f6299d5b295d6601c4a369857cd33 | 1,267 | hpp | C++ | src/mover.hpp | Piepenguin1995/retro-rpg | 09b72d7a8a4d2a9e94b09957bcb88bcf08a67eeb | [
"MIT"
] | 5 | 2016-02-09T20:05:57.000Z | 2016-11-02T01:48:54.000Z | src/mover.hpp | dbMansfield/retro-rpg | 09b72d7a8a4d2a9e94b09957bcb88bcf08a67eeb | [
"MIT"
] | null | null | null | src/mover.hpp | dbMansfield/retro-rpg | 09b72d7a8a4d2a9e94b09957bcb88bcf08a67eeb | [
"MIT"
] | 3 | 2016-02-09T20:06:04.000Z | 2016-06-23T13:12:22.000Z | #ifndef MOVER_HPP
#define MOVER_HPP
#include <SFML/System.hpp>
#include <JsonBox.h>
#include <iostream>
class TileMap;
// Direction the entity is moving in
enum class Direction { NORTH = 'n', SOUTH = 's', EAST = 'e', WEST = 'w', NONE = 0 };
// Convert a cardinal direction n,e,s,w to a unit vector
sf::Vector2f dirToVec(Direction dir);
// Calculate the predominant cardinal direction a vector is pointing in
Direction vecToDir(const sf::Vector2f& dir);
class Mover
{
protected:
// Position of the entity in the game world, in grid squares not pixels
sf::Vector2f pos;
public:
virtual Mover* clone() const = 0;
virtual ~Mover();
virtual const sf::Vector2f& getPosition() const;
virtual void setPosition(const sf::Vector2f pos);
virtual bool isMoving() const = 0;
virtual Direction getFacing() const = 0;
virtual void setFacing(Direction facing) = 0;
// Update the entity's position according to their velocity
virtual void update(float dt) = 0;
// Attempt to move the entity in the direction dir in the environment
// described by tm over a time interval dt
virtual void step(float dt, Direction dir, const TileMap& tm) = 0;
virtual JsonBox::Object toJson() const;
virtual void load(const JsonBox::Value& v);
};
#endif /* MOVER_HPP */
| 25.34 | 84 | 0.722968 | [
"object",
"vector"
] |
8acea653a07e67677e7b4068a017870d82cd1218 | 3,503 | cpp | C++ | src/shared/engine/MoveCommand.cpp | Welteam/Projet-IS | 4feeeb39aca9af720f22c8bb3a41f2583fb8cb9b | [
"Unlicense"
] | null | null | null | src/shared/engine/MoveCommand.cpp | Welteam/Projet-IS | 4feeeb39aca9af720f22c8bb3a41f2583fb8cb9b | [
"Unlicense"
] | null | null | null | src/shared/engine/MoveCommand.cpp | Welteam/Projet-IS | 4feeeb39aca9af720f22c8bb3a41f2583fb8cb9b | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <utility>
#include <vector>
#include "MoveCommand.h"
#include "Cordinate.cpp"
#include <chrono>
#include <thread>
namespace engine {
MoveCommand::MoveCommand(std::shared_ptr<state::Character> selectedUnit, int newX, int newY) {
this->selectedUnit = std::move(selectedUnit);
this->destination = Node{.x = newX, .y = newY};
}
bool MoveCommand::execute(state::GameState &gameState) {
std::cout << "("<< selectedUnit->getX() << ", "<< selectedUnit->getY() <<")" << std::endl;
engine::Node depart = {.x = selectedUnit->getX(), .y = selectedUnit->getY()};
vector<Node> nodes = Cordinate::aStar(depart, destination, gameState.getWorld(), gameState.getGameObjects(), selectedUnit.get()->getPm());
if(nodes.at(nodes.size()-1).x == destination.x && nodes.at(nodes.size()-1).y == destination.y){
Node lastMove = Node{.x = selectedUnit->getX(), .y = selectedUnit->getY()};
for(auto node : nodes){
state::Player player = gameState.getActivePlayer();
vector<state::Character> newUnits;
for(auto unit : player.getUnits()){
if(unit.getX() == lastMove.x && unit.getY() == lastMove.y){
if((unit.getX()-node.x) == 1){
unit.setOrientation(state::Orientation::WEST);
} else if((unit.getX()-node.x) == -1){
unit.setOrientation(state::Orientation::EST);
} else {
if((unit.getY()-node.y) == 1){
unit.setOrientation(state::Orientation::NORTH);
} else if((unit.getY()-node.y) == -1){
unit.setOrientation(state::Orientation::SOUTH);
}
}
unit.setX(node.x);
unit.setY(node.y);
lastMove = Node{.x = node.x, .y = node.y};
if(!(unit.getX() == selectedUnit->getX() && unit.getY() == selectedUnit->getY())){
unit.usePm(1);
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
newUnits.push_back(unit);
}
player.setUnits(newUnits);
if(player.getId() == 1){
gameState.setPlayer1(player);
gameState.setActivePlayer(gameState.getPlayer1());
} else {
gameState.setPlayer2(player);
gameState.setActivePlayer(gameState.getPlayer2());
}
}
} else {
cout << " can't reach destination" << endl;
}
return nodes.size() != 1;
}
Json::Value MoveCommand::serialize(Json::Value &root) {
Json::Value newCmd;
newCmd["CommandTypeId"] = CommandTypeId::MOVE_CMD;
newCmd["selectedUnitX"] = this->selectedUnit->getX();
newCmd["selectedUnitY"] = this->selectedUnit->getY();
newCmd["destinationX"] = this->destination.x;
newCmd["destinationY"] = this->destination.y;
if(!(root["commands"].empty())) {
root["commands"][root["commands"].size()] = newCmd;
}
else {
root["commands"][0] = newCmd;
}
return root;
}
}
| 43.246914 | 146 | 0.492435 | [
"vector"
] |
8aceedb0effb108707e0776517f5ed4b7c57e950 | 1,094 | cpp | C++ | CPP/Offer/55/IsAVLTreeOffer.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Offer/55/IsAVLTreeOffer.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Offer/55/IsAVLTreeOffer.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | //
// Created by Insomnia on 18-10-14.
// 同 leetcode 110
// Balanced Binary Tree
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) {
return true;
}
int ld = depthOfTree(root->left);
int rd = depthOfTree(root->right);
return isBalanced(root->left) && isBalanced(root->right) && abs(ld - rd) <= 1;
}
private:
int depthOfTree(TreeNode *node) {
if (!node) {
return 0;
}
int ld = depthOfTree(node->left);
int rd = depthOfTree(node->right);
return max(ld, rd) + 1;
}
};
int main() {
TreeNode a(3);
TreeNode b(9);
TreeNode c(20);
TreeNode d(15);
TreeNode e(7);
a.left = &b;
a.right = &c;
c.left = &d;
c.right = &e;
Solution solution;
cout << boolalpha << solution.isBalanced(&a) << endl;
return 0;
} | 19.192982 | 86 | 0.541133 | [
"vector"
] |
8ad3f2ba08b2ecef8ef942071b794c4d821ba56a | 4,009 | cpp | C++ | sources/routing/route_matcher.cpp | deguangchow/NetFlex | 8fbdee6601dcbaa5be12e467bee82f1f648cd63b | [
"MIT"
] | null | null | null | sources/routing/route_matcher.cpp | deguangchow/NetFlex | 8fbdee6601dcbaa5be12e467bee82f1f648cd63b | [
"MIT"
] | null | null | null | sources/routing/route_matcher.cpp | deguangchow/NetFlex | 8fbdee6601dcbaa5be12e467bee82f1f648cd63b | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@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 <netflex/routing/route_matcher.hpp>
namespace netflex {
namespace routing {
//!
//! ctor & dtor
//!
route_matcher::route_matcher(const std::string& path) {
build_match_regex(path);
}
//!
//! build matching regex
//!
void
route_matcher::build_match_regex(const std::string& sPath) {
//! match var1 in /abc/:var1/def
std::regex regexFindURLParams("/:([a-zA-Z0-9_\\-]+)");
std::smatch smatchData;
auto posMatched = std::sregex_iterator(sPath.cbegin(), sPath.cend(), regexFindURLParams);
auto const& posEnd = std::sregex_iterator();
while (posMatched != posEnd) {
auto param = posMatched->str();
if (!std::regex_match(param, smatchData, regexFindURLParams))
continue;
//! sm is [/:var, var]
m_vctURLParams.push_back(smatchData[1]);
++posMatched;
}
//! transform /abc/:var1/def into /abc/([a-zA-Z0-9]*)/def to match url params values
//! also match trailing slash, get params and #comments
//!
//! regex_replace(path, reg, "/([a-zA-Z0-9]+)") ==> transform /abc/:var1/def into /abc/([a-zA-Z0-9]*)/def
//! "/?((\\?([^=]+)=([^&\\#]*))(&([^=]+)=([^&\\#]*))*)?(\\#.*)?" ==> match trailing slash, get params and #comments
//! > /? ==> match trailing slash
//! > ((\\?([^=]+)=([^&\\#]*))(&([^=]+)=([^&\\#]*))*)? ==> match get params
//! > (\\?([^=]+)=([^&\\#]*)) ==> match first ?var=val
//! > (&([^=]+)=([^&\\#]*))*)?(\\#.*)? ==> match subsequent &var=val
//! > (\\#.*)? ==> match #comments
m_strMatchRegex = std::regex_replace(sPath, regexFindURLParams,
std::string("/([a-zA-Z0-9_\\-]+)")) + "/?((\\?([^=]+)=([^&\\#]*))(&([^=]+)=([^&\\#]*))*)?(\\#.*)*";
m_regexMatch = std::regex(m_strMatchRegex);
}
//!
//! matching
//!
bool
route_matcher::match(const std::string& sPath, params_t& mapParams) const {
std::smatch smatchData;
if (!std::regex_match(sPath, smatchData, m_regexMatch))
return false;
//! expected url params are in sm[1..m_url_params.size()]
for (size_t i = 1; i <= m_vctURLParams.size(); ++i)
mapParams[m_vctURLParams[i - 1]] = smatchData[i];
//! sm[m_url_params.size() + 1] contains get_params
match_get_params(smatchData[m_vctURLParams.size() + 1], mapParams);
return true;
}
void
route_matcher::match_get_params(const std::string& sPath, params_t& mapParams) const {
std::regex regexParams("[\\?&]([^=]+)=([^&]*)");
std::smatch smatchData;
auto posMatched = std::sregex_iterator(sPath.cbegin(), sPath.cend(), regexParams);
auto const& posEnd = std::sregex_iterator();
while (posMatched != posEnd) {
auto sParam = posMatched->str();
if (!std::regex_match(sParam, smatchData, regexParams))
continue;
//! sm is [?key1=val1, key1, val1]
mapParams[smatchData[1]] = smatchData[2];
++posMatched;
}
}
} // namespace routing
} // namespace netflex
| 33.132231 | 117 | 0.63981 | [
"transform"
] |
e9d37d3c7d63db358829647c045baf8bba9f156c | 6,699 | cc | C++ | stapl_release/test/containers/heap/dis_heap.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/test/containers/heap/dis_heap.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/test/containers/heap/dis_heap.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#include <stapl/containers/heap/heap.hpp>
#include <stapl/views/vector_view.hpp>
#include <stapl/containers/vector/vector.hpp>
#include <stapl/containers/distribution/directory/vector_directory.hpp>
#include <stapl/containers/distribution/directory/container_directory.hpp>
#include <vector>
#include <stapl/algorithms/algorithm.hpp>
#include <stapl/domains/indexed.hpp>
#include <stapl/containers/partitions/balanced.hpp>
#include <stapl/containers/mapping/mapper.hpp>
#include "../../test_report.hpp"
using namespace stapl;
using namespace std;
typedef heap_base_container_traits
<int,std::less<int> > bc_traits;
typedef heap_base_container
<int,std::less<int>, bc_traits > bc_type;
typedef bc_type::gid_type gid_type;
typedef bc_type::value_type value_type;
typedef container_manager_heap<bc_type> cm_type;
typedef cm_type::iterator cm_iter;
typedef balanced_partition< indexed_domain<size_t> > partitioner_type;
typedef mapper<size_t> mapper_type;
typedef list_manager<partitioner_type, mapper_type> heap_manager_type;
typedef heap_traits<int, std::less<int>,
partitioner_type, mapper_type> heap_traits_type;
typedef heap<int, std::less<int>,
partitioner_type, mapper_type,
heap_traits_type> heap_type;
typedef heap_distribution<heap_type> dis_type;
typedef heap_traits_type::directory_type directory_type;
typedef stapl::vector<size_t> vec_type;
typedef stapl::vector_view< vec_type > vec_view_type;
stapl::exit_code stapl_main(int argc, char* argv[])
{
if (argc < 2) {
std::cerr << "usage: exe n" << std::endl;
exit(1);
}
size_t n = atol(argv[1]);
srand(time(NULL));
int my_f = 0;
int nb_part = 0;
if (n > 10) {
my_f = rand() % ((int) (n/10));
}
if (my_f == 0) {
nb_part = 1;
} else {
nb_part = my_f;
}
bool passed = true;
indexed_domain <size_t> dom(0,n-1); //Domain size_t from 0 to n-1
partitioner_type Partitionner(dom,nb_part) ; //Creating trunc(n/2) partition
//map the partitions to the previous domain
mapper_type Mapper(indexed_domain<size_t> (0,nb_part - 1));
//Fake pointer to the heap needed by the distribution
//At heap level, this pointer will be real
heap_type* ptr_pheap = new heap_type();
cm_type cm(Partitionner,Mapper);
cm_type cm_full(Partitionner, Mapper);
cm_type cm_full2(Partitionner, Mapper);
cm_type cm_full3(Partitionner, Mapper);
directory_type Directory;
cm_full.push_bc();
cm_full2.push_bc();
cm_full3.push_bc();
for (size_t i = 0 ; i < n ; ++i) {
(*(*(cm_full.begin()))).push(i);
(*(*(cm_full2.begin()))).push(i);
(*(*(cm_full3.begin()))).push(i);
}
dis_type distrib1(Directory,cm_full);
distrib1.end();
dis_type distrib5(Directory,cm_full3);
dis_type distrib2(distrib1);
dis_type distrib3(Directory,cm);
bc_type* bc = new bc_type();
for (size_t i = 0 ; i < n ; ++i) {
bc->push(2*i);
}
distrib5.container_manager().push_bc(bc);
if ( (distrib1.size() != n*get_num_locations()) ||
distrib5.size() != 2*n*get_num_locations()
|| *(*(distrib1.container_manager().begin()))->begin() != int (n-1)
|| (distrib2.size() != n*get_num_locations())
|| (distrib3.size() != 0) )
passed = false;
STAPL_TEST_REPORT(passed,"Testing constructors");
passed = true;
for (size_t i = 0 ; i < n ; ++i) {
int my_r = rand() % 50;
distrib1.push(my_r);
distrib3.push(my_r);
}
STAPL_TEST_REPORT(passed,"Testing push()");
passed = true;
gid_type top_result = distrib5.get_top().first;
value_type val_read = *(*(distrib5.container_manager().begin()))->begin();
for (cm_iter it = distrib5.container_manager().begin() ;
it != distrib5.container_manager().end() ; ++it) {
for (bc_type::iterator iter = (*it)->begin() ;
iter != (*it)->end() ; ++iter) {
if (*iter > val_read)
val_read = *iter;
}
}
if (val_read != distrib5.get_element(top_result))
passed = false;
STAPL_TEST_REPORT(passed,"Testing get_top() and top()");
passed = true;
if (stapl::get_location_id() == 0)
distrib1.push(50 + 2*n);
value_type result_pop = distrib1.pop();
if (result_pop != int(50 + 2*n))
std::cout << "ERROR in pop() !!!" <<std::endl;
//Look for it in the heap
for (cm_iter it = distrib1.container_manager().begin() ;
it != distrib1.container_manager().end() ; ++it) {
for (bc_type::iterator iter = (*it)->begin() ;
iter != (*it)->end() ; ++iter) {
if (*iter == result_pop) {
passed = false;
std::cout << "Hum .. this is embarassing ... top element should ";
std::cout << "have been removed from heap o_O" <<std::endl;
}
}
}
STAPL_TEST_REPORT(passed,"Testing pop()");
passed = true;
if (!distrib1.is_heap()) {
passed = false;
std::cout<<"Not heap but should"<<endl;
}
cm_iter it = distrib1.container_manager().begin();
bool is_root = false;
size_t rand_bc = rand()%(distrib1.container_manager().num_bc());
//Get a random element in a random bc
if (rand_bc > 0)
--rand_bc;
for (size_t i = 0 ; i < rand_bc ; ++i)
++it;
bc_type::iterator iter = (*it)->begin();
size_t rand_elem = rand() % ((*it)->size());
if (rand_elem > 0)
--rand_elem;
for (size_t i = 0 ; i < rand_elem ; ++i)
++iter;
//Corrupt value if not top
if (iter == (*it)->begin())
is_root = true;
else (*iter) = 50 + 3*n;
if (distrib1.is_heap())
if (!is_root) {
std::cout<<"Heap but should'nt"<<endl;
passed = false;
}
STAPL_TEST_REPORT(passed,"Testing is_heap()");
passed = true;
dis_type distrib_it(Directory,cm_full2);
size_t k = 0;
stapl::rmi_fence();
dis_type::iterator itera = distrib_it.end();
for (dis_type::iterator iterator = distrib_it.begin() ;
iterator != itera ; ++iterator) {
++k;
}
if (k/stapl::get_num_locations() != cm_full2.size())
passed = false;
STAPL_TEST_REPORT(passed,"Testing Global iteration");
delete ptr_pheap;
return EXIT_SUCCESS;
}
| 30.312217 | 79 | 0.626511 | [
"vector"
] |
e9d5be55f7b468f0d0f80a6cd1032379d85b980a | 1,705 | hpp | C++ | include/eemp.hpp | goens/TUD_computational_group_theory | 3f4703cae1ac049089db23eafc321e8daca2d99d | [
"MIT"
] | 2 | 2018-09-10T09:31:17.000Z | 2018-10-14T15:19:20.000Z | include/eemp.hpp | goens/TUD_computational_group_theory | 3f4703cae1ac049089db23eafc321e8daca2d99d | [
"MIT"
] | 7 | 2020-06-11T07:25:08.000Z | 2020-12-19T09:07:50.000Z | include/eemp.hpp | goens/TUD_computational_group_theory | 3f4703cae1ac049089db23eafc321e8daca2d99d | [
"MIT"
] | 2 | 2020-09-10T19:31:57.000Z | 2020-12-09T13:17:50.000Z | #if 0
#ifndef GUARD_EEMP_H
#define GUARD_EEMP_H
#include <ostream>
#include <utility>
#include <vector>
namespace mpsym
{
namespace internal
{
class PartialPerm;
class PermGroup;
namespace eemp
{
struct SchreierTree {
std::vector<std::pair<unsigned, unsigned>> data;
};
struct OrbitGraph {
std::vector<std::vector<unsigned>> data;
};
std::vector<std::vector<unsigned>> action_component(
std::vector<unsigned> const &alpha,
std::vector<PartialPerm> const &generators, unsigned dom_max,
SchreierTree &schreier_tree, OrbitGraph &orbit_graph);
std::pair<unsigned, std::vector<unsigned>> strongly_connected_components(
OrbitGraph const &orbit_graph);
SchreierTree scc_spanning_tree(
unsigned i, OrbitGraph const &orbit_graph,
std::vector<unsigned> const &scc);
PartialPerm schreier_trace(
unsigned x, SchreierTree const &schreier_tree,
std::vector<PartialPerm> const &generators, unsigned dom_max,
unsigned target = 0u);
PermGroup schreier_generators(
unsigned i, std::vector<PartialPerm> const &generators, unsigned dom_max,
std::vector<std::vector<unsigned>> const &action_component,
SchreierTree const &schreier_tree, OrbitGraph const &orbit_graph,
std::vector<unsigned> const &sccs);
std::vector<PartialPerm> r_class_representatives(
SchreierTree const &schreier_tree,
std::vector<PartialPerm> const &generators);
std::vector<std::vector<unsigned>> expand_partition(
std::vector<unsigned> partition);
std::ostream &operator<<(std::ostream &os, SchreierTree const &schreier_tree);
std::ostream &operator<<(std::ostream &os, OrbitGraph const &orbit_graph);
} // namespace eemp
} // namespace internal
} // namespace mpsym
#endif // GUARD_EEMP_H
#endif
| 24.014085 | 78 | 0.761877 | [
"vector"
] |
e9d73979f2557a2c155d60c9dde1c0754b4a6136 | 50,723 | cpp | C++ | cheng4/protocol.cpp | kmar/cheng4 | d3adbb83555a31f88bc5337a6188447940757e73 | [
"Zlib"
] | 13 | 2016-06-03T23:58:41.000Z | 2022-03-31T19:09:11.000Z | cheng4/protocol.cpp | kmar/cheng4 | d3adbb83555a31f88bc5337a6188447940757e73 | [
"Zlib"
] | 1 | 2021-05-04T14:29:19.000Z | 2021-05-04T18:44:19.000Z | cheng4/protocol.cpp | kmar/cheng4 | d3adbb83555a31f88bc5337a6188447940757e73 | [
"Zlib"
] | 5 | 2016-06-03T23:58:41.000Z | 2022-03-15T12:45:00.000Z | /*
You can use this program under the terms of either the following zlib-compatible license
or as public domain (where applicable)
Copyright (C) 2012-2015, 2020-2021 Martin Sedlak
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "protocol.h"
#include "engine.h"
#include "version.h"
#include "movegen.h"
#include "thread.h"
#include "tune.h"
#include "utils.h"
#include "filterpgn.h"
#include <deque>
#include <cctype>
#include <algorithm>
// these because of pbook
#include <set>
#include <vector>
#include <iostream>
#include <fstream>
#ifdef IS_X64
# define maxHash "65536"
#else
# define maxHash "1024"
#endif
// TODO: - refactor into separate methods, simplify
namespace cheng4
{
static u64 pbook( std::ofstream &ofs, std::set< Signature > &procmap, Board &b, Search &s,
std::vector<Move> &line, Ply p, Depth d )
{
u64 res = 0;
std::set< Signature >::const_iterator ci = procmap.find(b.sig());
if ( ci != procmap.end() )
return res;
SearchMode sm;
sm.reset();
sm.maxDepth = 18;
sm.multiPV = 16 >> p;
if ( sm.multiPV > 8 )
sm.multiPV = 8;
if ( sm.multiPV < 2 )
sm.multiPV = 2;
if ( d == 1 )
sm.multiPV = 1;
s.clearHash();
s.clearSlots();
s.iterate(b, sm, 1);
procmap.insert( b.sig() );
std::vector< Move > moves;
size_t num = std::min( (size_t)sm.multiPV, s.rootMoves.count );
for (size_t i=0; i<num; i++)
{
if ( abs(s.rootMoves.sorted[i]->score) > 40 )
continue;
moves.push_back( s.rootMoves.sorted[i]->move );
}
if ( moves.empty() )
return res;
if ( d <= 0 )
{
// dump line
std::string l;
Board tb;
tb.reset();
for (size_t i=0; i<line.size(); i++)
{
l += tb.toSAN(line[i]);
l += ' ';
UndoInfo ui;
bool isCheck = tb.isCheck( line[i], tb.discovered() );
tb.doMove( line[i], ui, isCheck );
}
ofs << l << std::endl;
std::cout << '.';
return 1;
}
Bitboard dc = b.discovered();
Move m;
for ( size_t i=0; i<moves.size(); i++ )
{
m = moves[i];
UndoInfo ui;
bool isCheck = b.isCheck( m, dc );
b.doMove( m, ui, isCheck );
line.push_back( m );
res += pbook( ofs, procmap, b, s, line, p+1, d-1 );
line.pop_back();
b.undoMove( ui );
}
return res;
}
static void pbook()
{
std::set< Signature > okmap;
TransTable tt;
Search *s = new Search;
tt.resize( 64*4096*1024 ); // 256 MB
s->setHashTable( &tt );
Board b;
b.reset();
std::ofstream ofs("booklines.txt");
std::vector< Move > line;
u64 res = pbook( ofs, okmap, b, *s, line, 0, 8 );
if ( !ofs )
{
std::cout << "can't write outfile" << std::endl;
}
std::cout << "positions: " << res << std::endl;
delete s;
}
static void runEPDSuite( const EPDFile &epd, Depth depth )
{
TransTable tt;
Search *s = new Search;
tt.resize( 4096*1024 );
s->setHashTable( &tt );
size_t matching = 0;
size_t total = epd.positions.size();
for ( size_t i=0; i<total; i++ )
{
const EPDPosition &ep = epd.positions[i];
s->clearSlots();
s->clearHash();
Board b;
if ( !b.fromFEN( ep.fen.c_str() ) )
continue;
SearchMode sm;
sm.reset();
sm.maxDepth = depth;
s->iterate( b, sm, 1 );
Move bm = s->iterBest;
size_t j;
for ( j=0; j<ep.avoid.size(); j++ )
if ( bm == ep.avoid[j] )
break;
if ( j < ep.avoid.size() )
continue; // avoid_failed
for ( j=0; j<ep.best.size(); j++ )
if ( bm == ep.best[j] )
break;
if ( (!ep.avoid.empty() && ep.best.empty()) || j < ep.best.size() )
{
// matching!
matching++;
}
}
std::cout << matching << " out of " << total << " positions passed" << std::endl;
delete s;
}
struct PerfTest
{
const char *fen;
Depth depth;
NodeCount count;
};
static const PerfTest suite[] =
{
// my artificial perft suite:
// avoid en passant capture:
{ "8/5bk1/8/2Pp4/8/1K6/8/8 w - d6 0 1", 6, 824064ull },
{ "8/8/1k6/8/2pP4/8/5BK1/8 b - d3 0 1", 6, 824064ull },
// en passant capture checks opponent:
{ "8/8/1k6/2b5/2pP4/8/5K2/8 b - d3 0 1", 6, 1440467ull },
{ "8/5k2/8/2Pp4/2B5/1K6/8/8 w - d6 0 1", 6, 1440467ull },
// short castling gives check:
{ "5k2/8/8/8/8/8/8/4K2R w K - 0 1", 6, 661072ull },
{ "4k2r/8/8/8/8/8/8/5K2 b k - 0 1", 6, 661072ull },
// long castling gives check:
{ "3k4/8/8/8/8/8/8/R3K3 w Q - 0 1", 6, 803711ull },
{ "r3k3/8/8/8/8/8/8/3K4 b q - 0 1", 6, 803711ull },
// castling (including losing cr due to rook capture):
{ "r3k2r/1b4bq/8/8/8/8/7B/R3K2R w KQkq - 0 1", 4, 1274206ull },
{ "r3k2r/7b/8/8/8/8/1B4BQ/R3K2R b KQkq - 0 1", 4, 1274206ull },
// castling prevented:
{ "r3k2r/8/3Q4/8/8/5q2/8/R3K2R b KQkq - 0 1", 4, 1720476ull },
{ "r3k2r/8/5Q2/8/8/3q4/8/R3K2R w KQkq - 0 1", 4, 1720476ull },
// promote out of check:
{ "2K2r2/4P3/8/8/8/8/8/3k4 w - - 0 1", 6, 3821001ull },
{ "3K4/8/8/8/8/8/4p3/2k2R2 b - - 0 1", 6, 3821001ull },
// discovered check:
{ "8/8/1P2K3/8/2n5/1q6/8/5k2 b - - 0 1", 5, 1004658ull },
{ "5K2/8/1Q6/2N5/8/1p2k3/8/8 w - - 0 1", 5, 1004658ull },
// promote to give check:
{ "4k3/1P6/8/8/8/8/K7/8 w - - 0 1", 6, 217342ull },
{ "8/k7/8/8/8/8/1p6/4K3 b - - 0 1", 6, 217342ull },
// underpromote to check:
{ "8/P1k5/K7/8/8/8/8/8 w - - 0 1", 6, 92683ull },
{ "8/8/8/8/8/k7/p1K5/8 b - - 0 1", 6, 92683ull },
// self stalemate:
{ "K1k5/8/P7/8/8/8/8/8 w - - 0 1", 6, 2217ull },
{ "8/8/8/8/8/p7/8/k1K5 b - - 0 1", 6, 2217ull },
// stalemate/checkmate:
{ "8/k1P5/8/1K6/8/8/8/8 w - - 0 1", 7, 567584ull },
{ "8/8/8/8/1k6/8/K1p5/8 b - - 0 1", 7, 567584ull },
// double check:
{ "8/8/2k5/5q2/5n2/8/5K2/8 b - - 0 1", 4, 23527ull },
{ "8/5k2/8/5N2/5Q2/2K5/8/8 w - - 0 1", 4, 23527ull },
{ 0, 0, 0 }
};
// TODO: more positions?
static const char *benchFens[] =
{
"2kr2nr/pp1n1ppp/2p1p3/q7/1b1P1B2/P1N2Q1P/1PP1BPP1/R3K2R w KQ - 1",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r5n1/p2q3k/4b2p/3pB3/2PP1QpP/8/PP4P1/5RK1 w - - 1",
"2kr1b1r/ppp3p1/5nbp/4B3/2P5/3P2Nq/PP2BP2/R2Q1RK1 b - - 0",
"3r4/8/8/P7/1P6/1K3kpR/8/8 b - - 0 70",
"8/8/8/P7/1n6/1P4k1/3K2p1/6B1 w - - 5 71",
"8/1P2Qr1k/2b3pp/2pBp3/5q2/1N2R3/6KP/8 w - - 5 54",
"r1b1rbk1/1p3p1p/p2ppBp1/4P3/q4P1Q/P2B4/1PP3PP/1R3R1K w - - 0 24",
0
};
static void bench()
{
NodeCount total = 0;
Search *s = new Search;
TransTable *tt = new TransTable;
tt->resize( 1*1048576 );
s->setHashTable(tt);
Board b;
SearchMode sm;
sm.reset();
sm.maxDepth = 15;
const char **p = benchFens;
i32 ticks = Timer::getMillisec();
while ( *p )
{
s->clearHash();
s->clearSlots();
b.fromFEN( *p++ );
s->iterate(b, sm, 1 );
total += s->nodes;
}
ticks = Timer::getMillisec() - ticks;
delete tt;
delete s;
std::cout << total << " nodes in "
<< ticks << " msec (" << std::fixed
<< total*1000/(ticks ? ticks : 1) << " nps)" << std::endl;
}
static NodeCount perft( cheng4::Board &b, Depth depth )
{
if ( !depth )
return 1;
NodeCount res = 0;
MoveGen mg( b );
if ( depth == 1 )
{
// bulk counting only
while ( mg.next() != mcNone )
res++;
return res;
}
Move m;
UndoInfo ui;
while ( (m = mg.next()) != mcNone )
{
bool isCheck = b.isCheck(m, mg.discovered() );
b.doMove( m, ui, isCheck );
res += perft( b, depth-1 );
b.undoMove( ui );
}
return res;
}
struct TacPosBench
{
const char *fen;
const char *move;
int minDepth;
Score minScore;
i32 time;
};
struct TacPosBenchCbk
{
const TacPosBench *pos;
Search *search;
i32 startTicks;
};
static std::string uciScore( Score score );
static void tbcbk(const SearchInfo &si, void *param)
{
const TacPosBenchCbk *tb = (const TacPosBenchCbk *)param;
if ((si.flags & (sifDepth | sifPV)) != (sifDepth | sifPV))
return;
if (si.depth < tb->pos->minDepth)
return;
Board b;
b.fromFEN(tb->pos->fen);
Move m = b.fromSAN(std::string(tb->pos->move));
std::cout << "depth: " << (int)si.depth << " score: " << uciScore(si.pvScore) << " PV: ";
uint pvidx = 0;
for (const Move *pv = si.pv; *pv; pv++)
{
if (pvidx >= si.pvCount)
break;
std::cout << b.toSAN(*pv) << " ";
UndoInfo ui;
b.doMove(*pv, ui, b.isCheck(*pv, b.discovered()));
++pvidx;
}
std::cout << "time: " << (Timer::getMillisec() - tb->startTicks) << " msec" << std::endl;
if (m != si.pv[0])
return;
if (si.pvScore < tb->pos->minScore)
return;
tb->search->abort();
}
static void tbench()
{
TacPosBench tb[] =
{
// actually I think multiple moves win here
{"8/4kp2/1p2p3/1P2P1p1/1P4P1/3K4/8/8 b - - 6 57", "f5", 10, 100, 0},
{"1rb2rk1/4R1p1/1pqn1pBp/3p4/5Q2/1NP3PP/6PK/4R3 w - - 0 30", "Re1e6", 10, -scInfinity, 0},
{"rn1q1rk1/pbpp2pp/1p1bp3/5p2/1PPP4/P2BP3/2QN1PPP/R1B2RK1 b - b3 0 11", "Bxh2+", 10, -scInfinity, 0},
{"8/6B1/p5p1/Pp4kp/1P5r/5P1Q/4q1PK/8 w - -", "Qxh4", 10, -scInfinity, 0},
{"rn3r2/1bq2p1k/p3p3/1pb1P1Q1/P1p5/2P5/4BPPP/R2R2K1 w - - 5 28", "Bd3", 10, -scInfinity, 0},
{"8/2r3p1/2P4p/p2B1P2/Pp3Kp1/7k/1P2r3/3R4 w - - 6 50", "Rh1+", 10, 15, 0},
{"2r3rk/p2nBb1p/1pB2P2/1P6/P1PP3b/2Q1N1q1/6N1/2R3K1 b", "Rxc6", 10, -scInfinity, 0},
{"rnbq2k1/p1r2p1p/1p1p1Pp1/1BpPn1N1/P7/2P5/6PP/R1B1QRK1 w - -", "Nxh7", 10, -scInfinity, 0},
{"3r2k1/5pp1/p1B4p/qp1P4/2n5/r1P3P1/5PKP/2QRR3 w - - 0 27", "d6", 10, -scInfinity, 0},
{"1r4r1/3q1npk/2b1pbnp/Rp1p4/1N1P3P/2PQ1pP1/1K3B2/5B1R w - - 0 1", "Qxg6+", 10, -scInfinity, 0},
{"rn3r2/1bq2ppk/p3p2p/1pb1P2Q/P1p5/2P2N2/3BBPPP/R2R2K1 w - - 4 20", "Bxh6", 10, -scInfinity, 0},
{0, 0, 0, 0, 0}
};
TransTable tt;
tt.resize(128*1024*1024);
int pos = 1;
i32 startTicks = Timer::getMillisec();
for (TacPosBench *t = tb; t->fen; t++, pos++)
{
Search search;
search.setHashTable(&tt);
search.clearHash();
search.clearSlots();
Board b;
b.fromFEN(t->fen);
search.board = b;
TacPosBenchCbk cbk;
cbk.pos = t;
cbk.search = &search;
cbk.startTicks = startTicks;
search.setCallback(tbcbk, &cbk);
std::cout << "position " << pos << " FEN " << t->fen << " (" << t->move << ")" << std::endl;
search.rep.clear();
search.rep.push( b.sig(), 1 );
t->time = Timer::getMillisec();
SearchMode sm;
sm.reset();
search.iterate(b, sm);
t->time = Timer::getMillisec() - t->time;
}
std::cout << std::endl;
std::cout << "results:" << std::endl;
pos = 1;
i32 totalTime = 0;
for (TacPosBench *t = tb; t->fen; t++, pos++)
{
std::cout << "position " << pos << " (" << t->move << ") solved in " << t->time << " msec" << std::endl;
totalTime += t->time;
}
std::cout << "total time: " << totalTime << " msec" << std::endl;
}
static bool pbench()
{
uint count = 0;
for (const PerfTest *pt = suite; pt->fen; pt++ )
count++;
i32 totticks = Timer::getMillisec();
uint index = 0;
uint fails = 0;
for (const PerfTest *pt = suite; pt->fen; pt++, index++ )
{
std::cout << "position " << 1+index << "/" << count << " : " << pt->fen << std::endl;
cheng4::Board b;
if ( !b.fromFEN( pt->fen ) )
{
std::cout << "ILLEGAL FEN!" << std::endl;
return 0;
}
NodeCount result;
i32 ticks = Timer::getMillisec();
std::cout << "perft(" << (int)pt->depth << ") = " << (result = perft( b, pt->depth )) << std::endl;
ticks = Timer::getMillisec() - ticks;
std::cout << "took " << (double)ticks / 1000.0 << " sec, " << (double)result / 1000.0 / (double)ticks << " Mnps" << std::endl;
if ( result != pt->count )
fails++;
std::cout << ((result == pt->count) ? "passed" : "FAILED!") << std::endl;
}
totticks = Timer::getMillisec() - totticks;
std::cout << "total " << (double)totticks / 1000.0 << " sec" << std::endl;
if ( fails )
std::cout << fails << " / " << count << " FAILED!" << std::endl;
else
std::cout << "ALL OK" << std::endl;
return !fails;
}
static void filterPgn( const char *fname )
{
FilterPgn fp;
if (!fp.parse(fname))
{
std::cout << "failed to parse " << fname << std::endl;
return;
}
if (!fp.write("filterPgn_out.fen"))
std::cout << "failed to write filterPgn_out.fen" << std::endl;
else
std::cout << "all ok" << std::endl;
}
// Protocol
void Protocol::Level::reset()
{
moves = 0;
mins = 0;
secs = 0;
inc = 0;
move = 1;
}
static void protoCallback( const SearchInfo &si, void *param )
{
static_cast<Protocol *>(param)->searchCallback( si );
}
Protocol::Protocol( Engine &eng ) : multiPV(1), protover(1), analyze(0), force(0), clocksRunning(0), engineColor(ctBlack),
invalidState(0), frc(0), edit(0), post(1), fixedTime(0), maxCores(64), adjudicated(0), type( ptNative ),
engine(eng), quitFlag(0)
{
level.reset();
npsLimit = 0;
depthLimit = 0;
timeLimit = 0;
etime = otime = 60*1000;
searchMode.reset();
eng.setCallback( protoCallback, this );
}
Protocol::~Protocol()
{
engine.setCallback( 0, 0 );
}
bool Protocol::parse( const std::string &line )
{
MutexLock _( parseMutex );
switch( type )
{
case ptUCI:
return parseUCI( line );
case ptCECP:
return parseCECP( line );
case ptNative:
break;
}
if ( line == "uci" )
{
type = ptUCI;
return parseUCI( line );
}
if ( line == "xboard" )
{
type = ptCECP;
return parseCECP( line );
}
if ( line == "quit" )
{
quitFlag = 1;
return 1;
}
// new: force uci mode if not otherwise specified
type = ptUCI;
engine.setUCIMode(1);
return parseUCI(line);
}
bool Protocol::shouldQuit() const
{
return quitFlag;
}
// start sending (reset buffer)
void Protocol::sendStart( uint flags )
{
mutex.lock();
sendStr.str( std::string() );
switch( type )
{
case ptUCI:
if ( !(flags & (sifRaw | sifBestMove | sifPonderMove)) )
sendStr << "info";
break;
case ptCECP:
break;
case ptNative:
break;
}
}
// start sending (reset buffer)
void Protocol::sendEnd()
{
// coding around rdbuf()->in_avail() which doesn't always work!
std::string strg = sendStr.str();
if ( !strg.empty() )
{
std::cout << strg << std::endl;
std::cout.flush(); // FIXME: this is necessary under Linux to work properly under xboard
}
mutex.unlock();
}
// called from search
void Protocol::searchCallback( const SearchInfo &si )
{
sendStart( si.flags );
if ( si.flags & sifDepth )
sendDepth( si.depth );
if ( si.flags & sifSelDepth )
sendSelDepth( si.selDepth );
if ( si.flags & sifTime )
sendTime( si.time );
if ( si.flags & sifNodes )
sendNodes( si.nodes );
if ( si.flags & sifNPS )
sendNPS( si.nps );
if (si.flags & sifHashFull)
sendHashFull(si.hashFull);
if ( si.flags & sifCurIndex )
sendCurIndex( si.curIndex, si.curCount );
if ( si.flags & sifCurMove )
sendCurMove( si.curMove );
if ( si.flags & sifPV )
{
assert( (si.flags & sifNodes) && (si.flags & sifTime) && (si.flags & sifDepth) );
sendPV( si, si.pvIndex, si.pvScore, si.pvBound, (size_t)si.pvCount, si.pv );
}
if ( si.flags & sifBestMove )
sendBest( si.bestMove, (si.flags & sifPonderMove) ? si.ponderMove : mcNone );
sendEnd();
if ( si.flags & sifBestMove )
finishBest();
}
// send current depth
void Protocol::sendDepth( Depth d )
{
switch( type )
{
case ptUCI:
sendStr << " depth " << (int)d;
break;
case ptCECP:
case ptNative:
break;
}
}
// send selective depth
void Protocol::sendSelDepth( Ply d )
{
switch( type )
{
case ptUCI:
sendStr << " seldepth " << (int)d;
break;
case ptCECP:
case ptNative:
break;
}
}
// send time
void Protocol::sendTime( Time time )
{
switch( type )
{
case ptUCI:
sendStr << " time " << time;
break;
case ptCECP:
case ptNative:
break;
}
}
// send nodes
void Protocol::sendNodes( NodeCount n )
{
switch( type )
{
case ptUCI:
sendStr << " nodes " << n;
break;
case ptCECP:
case ptNative:
break;
}
}
// send nodes
void Protocol::sendNPS( NodeCount n )
{
switch( type )
{
case ptUCI:
sendStr << " nps " << n;
break;
case ptCECP:
case ptNative:
break;
}
}
// send hashfull
void Protocol::sendHashFull( uint hashFull )
{
switch( type )
{
case ptUCI:
sendStr << " hashfull " << hashFull;
break;
case ptCECP:
case ptNative:
break;
}
}
// send current move index (zero based)
void Protocol::sendCurIndex( MoveCount index, MoveCount /*count*/ )
{
switch( type )
{
case ptUCI:
sendStr << " currmovenumber " << (index+1);
break;
case ptCECP:
case ptNative:
break;
}
}
// send current move
void Protocol::sendCurMove( Move move )
{
switch( type )
{
case ptUCI:
sendStr << " currmove " << engine.board().toUCI(move);
break;
case ptCECP:
case ptNative:
break;
}
}
static std::string uciScore( Score score )
{
std::stringstream res;
if ( ScorePack::isMate( score ) )
{
int msc = score >= 0 ? (scInfinity - score)/2 + 1 : (-scInfinity - score + 1)/2 - 1;
assert( msc );
assert( (msc >= 0 && score >= 0) || (msc < 0 && score < 0) );
res << "mate " << msc;
} else res << "cp " << score;
return res.str();
}
// index: k-best(multipv) zero-based index
void Protocol::sendPV( const SearchInfo &si, uint index, Score score, enum BoundType bound, size_t pvCount,
const Move *pv )
{
switch( type )
{
case ptUCI:
if ( bound == btLower )
sendStr << " lowerbound ";
else if ( bound == btUpper )
sendStr << " upperbound ";
sendStr << " multipv " << (1+index) << " score " << uciScore( score ) << " pv";
if (pvCount)
{
Board b( engine.board() );
for (size_t i=0; i<pvCount; i++)
{
sendStr << " " << b.toUCI( pv[i] );
UndoInfo ui;
b.doMove( pv[i], ui, b.isCheck( pv[i], b.discovered() ) );
}
}
break;
case ptCECP:
if ( !post )
break;
{
Depth d = 0;
Time t = 0;
NodeCount n = 0;
if ( si.flags & sifDepth )
d = si.depth;
if ( si.flags & sifTime )
t = si.time;
if ( si.flags & sifNodes )
n = si.nodes;
sendStr.width(3);
sendStr << (int)d;
bound = btExact; // FIXME: WinBoard seems to have problems with additional + or - => disabled
sendStr << (bound == btUpper ? '-' : bound == btLower ? '+' : ' ');
sendStr << " ";
sendStr.width(5);
// TODO: convert score to pseudo-standard mate scores
sendStr << score << " ";
sendStr.width(8);
sendStr << (t/10) << " ";
sendStr.width(12);
sendStr << n;
Board b( engine.board() );
Move ponder = mcNone;
if ( engine.isPondering() )
ponder = engine.getPonderMove();
if ( ponder != mcNone )
sendStr << " (" << engine.ponderBoard().toSAN( ponder ) << ')';
for (size_t i=0; i<pvCount; i++)
{
sendStr << " " << b.toSAN( pv[i] );
UndoInfo ui;
b.doMove( pv[i], ui, b.isCheck( pv[i], b.discovered() ) );
}
sendStr.width(1);
// report mates at the end of the PV as text
if (ScorePack::isMate(score))
sendStr << " ;" << uciScore(score);
}
break;
case ptNative:
break;
}
}
// send best move
void Protocol::sendBest( Move best, Move ponder )
{
switch( type )
{
case ptUCI:
sendStr << "bestmove " << engine.board().toUCI( best );
if ( ponder != mcNone )
{
Board b( engine.board() );
UndoInfo ui;
b.doMove( best, ui, b.isCheck( best, b.discovered() ) );
sendStr << " ponder " << b.toUCI( ponder );
}
break;
case ptCECP:
if ( !analyze )
{
sendStr << "move " << engine.board().toUCI( best );
engine.doMoveInternal( best, 1 );
engine.setPonderMove( ponder );
}
break;
case ptNative:
break;
}
}
void Protocol::finishBest()
{
if ( type != ptCECP || analyze )
return;
// called from another thread!
MutexLock _( parseMutex );
// now check to see whether it's already game over
if ( adjudicate() )
return;
etime -= Timer::getMillisec() - startTicks;
startPondering(1);
}
// send raw mesage
void Protocol::sendRaw( const std::string &msg )
{
sendStr << msg;
}
// send raw EOL
void Protocol::sendEOL()
{
sendStr << std::endl;
}
// send custom info message
void Protocol::sendInfo( const std::string &msg )
{
switch( type )
{
case ptUCI:
sendStr << " string " << msg;
break;
case ptCECP:
case ptNative:
break;
}
}
// UCI parser
static std::string nextToken( const std::string &str, size_t &start )
{
std::string res;
const char *c = str.c_str() + start;
// consume initial whitespace
while ( *c && isspace(*c & 255) )
c++;
const char *beg = c;
// token
while ( *c && !isspace(*c & 255) )
c++;
if ( c > beg )
res = std::string( beg, c );
start = c - str.c_str();
return res;
}
// to simplify option parsing
static std::string nextOptToken( const std::string &str, size_t &start )
{
std::string res;
const char *c = str.c_str() + start;
// consume initial whitespace/=
while ( *c && isspace(*c & 255) )
c++;
const char *beg = c;
// token
while ( *c && *c != '=' )
c++;
if ( c > beg )
res = std::string( beg, c );
start = c - str.c_str();
if ( *c == '=' )
start++;
return res;
}
// parse UCI command
bool Protocol::parseUCI( const std::string &line )
{
size_t pos = 0;
std::string token = nextToken( line, pos );
if ( token.empty() )
return 0;
if ( token == "ponderhit" )
{
engine.ponderHit();
return 1;
}
if ( token == "stop" )
{
engine.stopSearch();
return 1;
}
if ( token == "isready" )
{
sendStart( sifRaw );
sendRaw( "readyok" );
sendEnd();
return 1;
}
if ( token == "go" )
{
SearchMode sm;
sm.reset();
sm.multiPV = multiPV;
i32 wtime, btime, winc, binc, movestogo;
wtime = btime = winc = binc = movestogo = 0;
for (;;)
{
token = nextToken( line, pos );
if ( token.empty() )
break;
if ( token == "ponder" )
{
sm.ponder = 1;
}
else
if ( token == "infinite" )
{
sm.reset();
sm.multiPV = multiPV;
}
else if ( token == "movetime" )
{
// parse movetime
token = nextToken( line, pos );
if ( token.empty() )
{
error( "movetime requires time parameter", line );
return 0;
}
long mt = strtol( token.c_str(), 0, 10 );
if ( mt <= 0 )
mt = -1;
sm.absLimit = sm.maxTime = (i32)mt;
sm.fixedTime = 1;
}
else if ( token == "movestogo" )
{
// parse movestogo
token = nextToken( line, pos );
if ( token.empty() )
{
error( "movestogo requires int parameter", line );
return 0;
}
long mt = strtol( token.c_str(), 0, 10 );
movestogo = (i32)mt;
}
else if ( token == "winc" )
{
// parse winc
token = nextToken( line, pos );
if ( token.empty() )
{
error( "winc requires int parameter", line );
return 0;
}
long i = strtol( token.c_str(), 0, 10 );
winc = (i32)i;
}
else if ( token == "binc" )
{
// parse binc
token = nextToken( line, pos );
if ( token.empty() )
{
error( "binc requires int parameter", line );
return 0;
}
long i = strtol( token.c_str(), 0, 10 );
binc = (i32)i;
}
else if ( token == "wtime" )
{
// parse wtime
token = nextToken( line, pos );
if ( token.empty() )
{
error( "wtime requires time parameter", line );
return 0;
}
long t = strtol( token.c_str(), 0, 10 );
if ( t <= 0 )
t = -1;
wtime = (i32)t;
}
else if ( token == "btime" )
{
// parse btime
token = nextToken( line, pos );
if ( token.empty() )
{
error( "btime requires time parameter", line );
return 0;
}
long t = strtol( token.c_str(), 0, 10 );
if ( t <= 0 )
t = -1;
btime = (i32)t;
}
else if ( token == "depth" )
{
// parse depth
token = nextToken( line, pos );
if ( token.empty() )
{
error( "depth requires int parameter", line );
return 0;
}
long i = strtol( token.c_str(), 0, 10 );
sm.maxDepth = (Depth)std::min( (int)maxDepth, (int)i );
}
else if ( token == "mate" )
{
// parse mate
token = nextToken( line, pos );
if ( token.empty() )
{
error( "mate requires int parameter", line );
return 0;
}
long i = strtol( token.c_str(), 0, 10 );
sm.mateSearch = (uint)std::max(0l, i);
}
else if ( token == "nodes" )
{
// parse nodes
token = nextToken( line, pos );
if ( token.empty() )
{
error( "nodes requires int parameter", line );
return 0;
}
std::stringstream ss;
ss.str( token );
ss >> sm.maxNodes;
} else if ( token == "searchmoves" )
{
// parse moves to restrict search to
for (;;)
{
size_t opos = pos;
token = nextToken( line, pos );
if ( token.empty() )
break;
// now parse UCI move
const Board &b = engine.board();
Move m = b.fromUCI( token );
bool legal = b.inCheck() ? b.isLegal<1, 0>(m, b.pins() ) :
b.isLegal<0, 0>(m, b.pins() );
if ( !legal )
{
pos = opos;
break;
}
sm.moves.push_back( m );
}
}
}
if ( wtime || btime )
{
// tournament time controls!
engine.abortSearch();
Color turn = engine.mainThread->search.board.turn();
i32 mytime, myinc, optime, opinc;
if ( turn == ctWhite )
{
mytime = wtime;
myinc = winc;
optime = btime;
opinc = binc;
}
else
{
mytime = btime;
myinc = binc;
optime = wtime;
opinc = winc;
}
allocTime( mytime, myinc, optime, opinc, movestogo, sm );
}
engine.startSearch( sm );
return 1;
}
if ( token == "position" )
{
engine.abortSearch();
token = nextToken( line, pos );
if ( token.empty() )
return 0;
if ( token == "startpos" )
{
engine.resetBoard();
} else if ( token == "fen" )
{
Board b;
const char *c = line.c_str() + pos;
c = b.fromFEN( c );
if ( !c )
{
error( "illegal fen from GUI", line );
return 0;
}
engine.setBoard( b );
pos = c - line.c_str();
} else {
error( "invalid position command", line );
return 0;
}
token = nextToken( line, pos );
if ( token == "moves" )
{
// parse moves
const char *c = line.c_str() + pos;
for (;;)
{
skipSpaces(c);
// now parse UCI move
Move m = engine.board().fromUCI( c );
if ( m == mcNone )
break;
if ( !engine.doMove( m ) )
{
illegalMove( m, line );
return 0;
}
}
return 1;
}
return 1;
}
if ( token == "quit" )
{
quitFlag = 1;
return 1;
}
if ( token == "uci" )
{
#ifdef USE_TUNING
PSq::init();
#endif
sendStart( sifRaw );
sendRaw( "id name "); sendRaw( Version::version() ); sendEOL();
sendRaw( "id author "); sendRaw( Version::author() ); sendEOL();
sendRaw( "option name Hash type spin min 1 max " maxHash " default 32" ); sendEOL();
sendRaw( "option name Clear Hash type button" ); sendEOL();
sendRaw( "option name Ponder type check default false" ); sendEOL();
sendRaw( "option name OwnBook type check default true" ); sendEOL();
sendRaw( "option name MultiPV type spin min 1 max 256 default 1" ); sendEOL();
sendRaw( "option name UCI_Chess960 type check default false" ); sendEOL();
sendRaw( "option name Threads type spin min 1 max 512 default 1" ); sendEOL();
sendRaw( "option name UCI_LimitStrength type check default false" ); sendEOL();
sendRaw( "option name UCI_Elo type spin min 800 max 2500 default 2500" ); sendEOL();
sendRaw( "option name NullMove type check default true" ); sendEOL();
sendRaw( "option name Contempt type spin min -100 max 100 default 0" ); sendEOL();
#ifdef USE_TUNING
for ( size_t i=0; i<TunableParams::paramCount(); i++ )
{
const TunableBase *par = TunableParams::getParam(i);
std::string str = "option name " + par->name() + " type spin min -1000000 max 1000000 default " + par->get();
sendRaw( str ); sendEOL();
}
#endif
sendRaw( "uciok" );
sendEnd();
engine.setUCIMode(1);
return 1;
}
if ( token == "setoption" )
{
parseUCIOptions( line, pos );
return 1;
}
if ( token == "ucinewgame" )
{
engine.abortSearch();
engine.clearHash();
return 1;
}
if ( parseSpecial( token, line, pos ) )
return 1;
error( "unknown command", line );
return 0;
}
bool Protocol::parseUCIOptions( const std::string &line, size_t &pos )
{
std::string token;
token = nextToken( line, pos );
if ( token != "name" )
{
error( "name expected", line );
return 0;
}
std::string key;
for (;;)
{
token = nextToken( line, pos );
if ( token.empty() )
break;
if ( token == "value" )
break;
if ( key.empty() )
key = token;
else
key = key + " " + token;
}
std::string value;
const char *c = line.c_str() + pos;
// skip blanks
while ( *c && isspace(*c & 255) )
c++;
value = c;
// examine key
if ( key == "Clear Hash" )
{
engine.clearHash();
return 1;
}
if ( key == "Hash" )
{
long hm = strtol( value.c_str(), 0, 10 );
return engine.setHash( (uint)std::max(1l, hm) );
}
if ( key == "Ponder" )
{
engine.setPonder( value == "true" );
return 1;
}
if ( key == "Threads" )
{
long thr = strtol( value.c_str(), 0, 10 );
engine.setThreads( (uint)std::max( 1l, thr ) );
return 1;
}
if ( key == "MultiPV" )
{
long mpv = strtol( value.c_str(), 0, 10 );
multiPV = (uint)std::max( 1l, std::min( 256l, mpv ) );
engine.setMultiPV( multiPV );
return 1;
}
if ( key == "OwnBook" )
{
engine.setOwnBook( value != "false" ); // was value == "true", this is just to fix an annoying Arena bug!
return 1;
}
if ( key == "UCI_Chess960" )
{
// handled automatically
return 1;
}
if ( key == "UCI_LimitStrength")
{
engine.setLimit( value == "true" );
return 1;
}
if ( key == "UCI_Elo")
{
long elo = strtol( value.c_str(), 0, 10 );
elo = std::max( 800L, elo );
elo = std::min( 2500L, elo );
engine.setElo( (u32)elo );
return 1;
}
if ( key == "Contempt")
{
long contempt = strtol( value.c_str(), 0, 10 );
contempt = std::max( -100L, contempt );
contempt = std::min( 100L, contempt );
engine.setContempt( (Score)contempt );
return 1;
}
if ( key == "NullMove")
{
engine.setNullMove( value != "false" );
return 1;
}
#ifdef USE_TUNING
if ( TunableParams::setParam(key.c_str(), value.c_str()) )
{
PSq::init();
return 1;
}
#endif
error( "unknown option", line );
return 0;
}
void Protocol::setSearchModeCECP( SearchMode &sm )
{
sm.reset();
sm.multiPV = multiPV;
if ( timeLimit )
{
sm.absLimit = sm.maxTime = timeLimit;
sm.fixedTime = fixedTime;
}
else
{
i32 movestogo = 0;
if ( level.moves )
{
// calculate movestogo
uint move = engine.board().move();
move -= level.move;
move %= level.moves;
move = level.moves - move;
movestogo = (i32)move;
}
i32 einc = level.inc, oinc = level.inc;
allocTime( etime, einc, otime, oinc, movestogo, sm );
}
if ( npsLimit )
sm.maxNodes = npsLimit * sm.maxTime;
sm.maxDepth = depthLimit;
}
// start CECP-mode search
bool Protocol::startSearchCECP()
{
if ( force )
return 0;
Color stm = engine.board().turn();
if ( stm != engineColor )
return 0;
startTicks = Timer::getMillisec();
SearchMode sm;
sm.reset();
setSearchModeCECP( sm );
engine.startSearch( sm );
return 1;
}
bool Protocol::parseCECP( const std::string &line )
{
bool res = parseCECPInternal( line );
if ( res && !invalidState && !edit && analyze )
{
SearchMode sm;
sm.reset();
sm.multiPV = multiPV;
engine.startSearch( sm );
}
return res;
}
bool Protocol::parseCECPEdit( const std::string &line )
{
size_t pos = 0;
std::string token = nextToken( line, pos );
if ( token.empty() )
return 0;
if ( token == "c" )
{
// flip color
editBoard.setTurn( flip( editBoard.turn() ) );
return 1;
}
if ( token == "#" )
{
editBoard.clearPieces();
return 1;
}
if ( token == "." )
{
edit = 0;
editBoard.updateBitboards();
if ( !editBoard.isValid() )
{
sendStart( sifRaw );
sendRaw( "tellusererror Illegal position" );
sendEnd();
invalidState = 1;
error( "edit: invalid position", line );
return 0;
}
// assign castling rights automatically!
editBoard.setFischerRandom( frc );
editBoard.autoCastlingRights();
engine.setBoard( editBoard );
level.move = editBoard.move();
return 1;
}
// assume it's in the format Pa4 (xa4 is extended and should clear square)
if ( token.length() == 3 )
{
const char *c = token.c_str();
char ch = c[0] | 32;
int f = (int)((c[1] | 32) - 'a');
bool invalid = 0;
if ( f < AFILE || f > HFILE )
invalid = 1;
if ( c[2] < '1' || c[2] > '8' )
invalid = 1;
Piece pt = ptNone;
int r = -1;
if ( !invalid )
{
r = ('8' - c[2]) ^ RANK8;
switch( ch )
{
case 'x':
pt = ptNone;
break;
case 'p':
pt = ptPawn;
break;
case 'n':
pt = ptKnight;
break;
case 'b':
pt = ptBishop;
break;
case 'r':
pt = ptRook;
break;
case 'q':
pt = ptQueen;
break;
case 'k':
pt = ptKing;
break;
default:
invalid = 1;
}
}
if ( !invalid )
{
editBoard.setPiece( editBoard.turn(), pt, SquarePack::init( (File)f, (Rank)r ) );
return 1;
}
}
error( "unknown command", line );
return 0;
}
void Protocol::abortSearch()
{
engine.abortSearch();
}
void Protocol::startPondering( bool nostop )
{
if ( force || analyze || edit || engine.board().turn() == engineColor )
return;
if ( engine.getPonder() && !engine.isPondering() )
{
SearchMode sm;
sm.reset();
setSearchModeCECP( sm );
engine.startPondering( sm, nostop );
}
}
bool Protocol::parseCECPInternal( const std::string &line )
{
if ( edit )
return parseCECPEdit( line );
size_t pos = 0;
std::string token = nextToken( line, pos );
if ( token.empty() )
return 0;
// look for move first...
// note that the move could be a rook capture => castling!
Move move = engine.actualBoard().fromUCI( token );
if ( move != mcNone )
{
bool phit = 0;
if ( !invalidState && engine.doMove( move, 0, &phit ) )
{
if ( adjudicate() )
return 1;
// only start new search if move was not ponderhit
if ( !phit )
startSearchCECP();
return 1;
}
illegalMove( move, line );
return 0;
}
if ( token == "go" )
{
if ( invalidState )
{
error( "current board state is invalid", line );
return 0;
}
leaveForce();
engineColor = engine.board().turn();
startSearchCECP();
return 1;
}
if ( token == "time" )
{
fixedTime = 0;
token = nextToken( line, pos );
if ( token.empty() )
{
error( "time arg expected", line );
return 0;
}
long tmp = strtol( token.c_str(), 0, 10 );
etime = (tmp > 0) ? (Time)(tmp * 10) : (Time)-1;
return 1;
}
if ( token == "otim" )
{
fixedTime = 0;
token = nextToken( line, pos );
if ( token.empty() )
{
error( "otim arg expected", line );
return 0;
}
long tmp = strtol( token.c_str(), 0, 10 );
otime = (tmp > 0) ? (Time)(tmp * 10) : (Time)-1;
return 1;
}
if ( token == "force" )
{
enterForce();
return 1;
}
if ( token == "white" )
{
stopClocks();
engineColor = ctBlack;
if ( setTurn( ctWhite ) )
return 1;
error( "can't set stm to white", line );
return 0;
}
if ( token == "black" )
{
stopClocks();
engineColor = ctWhite;
if ( setTurn( ctBlack ) )
return 1;
error( "can't set stm to black", line );
return 0;
}
if ( token == "level" )
{
// parse level...
// only increment is float according to hgm
// the format is:
// moves min(:sec) inc
timeLimit = 0; // override time limit
fixedTime = 0;
Level lev;
lev.reset();
lev.move = engine.board().move();
token = nextToken( line, pos );
if ( token.empty() )
{
error( "level moves expected", line );
return 0;
}
long lmoves = std::max( 0l, strtol( token.c_str(), 0, 10 ) );
lev.moves = (uint)lmoves;
token = nextToken( line, pos );
if ( token.empty() )
{
error( "level time expected", line );
return 0;
}
const char *c = token.c_str();
long lmins = std::max( 0l, strtol( c, (char **)&c, 10 ) );
lev.mins = (uint)lmins;
lev.secs = 0;
if ( *c == ':' )
{
// parse secs
c++;
long lsecs = std::max( 0l, strtol( c, 0, 10 ) );
lev.secs = (uint)lsecs;
}
token = nextToken( line, pos );
if ( token.empty() )
{
error( "level inc expected", line );
return 0;
}
double dinc = std::max( 0.0, strtod( token.c_str(), 0 ) );
dinc *= 1000;
lev.inc = (Time)dinc;
level = lev;
return 1;
}
if ( token == "st" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "st arg expected", line );
return 0;
}
long tmp = strtol( token.c_str(), 0, 10 );
timeLimit = (tmp > 0) ? (Time)(tmp * 1000) : (Time)-1;
fixedTime = 1;
return 1;
}
if ( token == "sd" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "sd arg expected", line );
return 0;
}
long tmp = strtol( token.c_str(), 0, 10 );
depthLimit = (tmp > 0) ? (Depth)tmp : 1;
return 1;
}
if ( token == "nps" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "nps arg expected", line );
return 0;
}
std::stringstream ss( token );
ss.str( token );
ss >> npsLimit;
return 1;
}
if ( token == "ping" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "ping arg expected", line );
return 0;
}
sendStart( sifRaw );
sendRaw( "pong " );
sendRaw( token );
sendEnd();
return 1;
}
if ( token == "memory" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "memory arg expected", line );
return 0;
}
uint memory;
std::stringstream ss( token );
ss.str( token );
ss >> memory;
if ( memory < 1 )
memory = 1;
if ( !engine.setHash( memory ) )
{
error( "couldn't adjust memory", line );
return 0;
}
return 1;
}
if ( token == "protover" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "protover arg expected", line );
return 0;
}
long pver = strtol( token.c_str(), 0, 10 );
protover = (int)pver;
// FIXME: ping temporarily disabled as it probably causes connection stalls in xboard mode in cutechess
sendStart( sifRaw );
sendRaw(
"feature name=0 san=0 usermove=0 time=1 sigint=0 sigterm=0 pause=0 reuse=1 analyze=1 colors=0 setboard=1 "
"nps=1 smp=1 debug=0 draw=0 playother=1 variants=\"normal,fischerandom\" ics=0 memory=1 ping=0 "
"option=\"Clear Hash -button\" option=\"Hash -spin 32 1 " maxHash "\" option=\"Threads -spin 1 1 512\" "
"option=\"OwnBook -check 1\" option=\"LimitStrength -check 0\" option=\"Elo -spin 2500 800 2500\" "
"option=\"MultiPV -spin 1 1 256\" option=\"NullMove -check 1\" option=\"Contempt -spin 0 -100 100\" myname=\""
);
sendRaw( Version::version() );
sendRaw( "\" "
"done=1"
);
sendEnd();
return 1;
}
if ( token == "variant" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "variant arg expected", line );
return 0;
}
if ( token != "normal" && token != "fischerandom" )
{
error( "unsupported variant", line );
return 0;
}
frc = token == "fischerandom";
return 1;
}
if ( token == "easy" )
{
if ( engine.getPonder() )
{
// abort search if pondering
if ( engine.isPondering() )
abortSearch();
engine.setPonder(0);
}
return 1;
}
if ( token == "hard" )
{
if ( !engine.getPonder() )
{
engine.setPonder(1);
startPondering();
}
return 1;
}
if ( token == "exit" )
{
if ( analyze )
{
abortSearch();
analyze = 0;
return 1;
}
error( "not analyzing", line );
return 0;
}
if ( token == "cores" )
{
token = nextToken( line, pos );
if ( token.empty() )
{
error( "cores arg expected", line );
return 0;
}
long cores = strtol( token.c_str(), 0, 10 );
maxCores = (uint)std::max( 1l, cores );
engine.limitThreads( maxCores );
return 1;
}
if ( token == "option" )
{
token = nextOptToken( line, pos );
if ( token.empty() )
{
error( "option arg expected", line );
return 0;
}
// parse options here
// FIXME: separate method to handle this
if ( token == "Clear Hash" )
{
engine.clearHash();
return 1;
}
if ( token == "Hash" )
{
long hsz = std::max( 1l, strtol( line.c_str() + pos, 0, 10 ) );
if ( !engine.setHash( (uint)hsz ) )
error( "couldn't set hash size", line );
return 1;
}
if ( token == "Threads" )
{
long thr = strtol( line.c_str() + pos, 0, 10 );
engine.setThreads( (uint)std::max( 1l, thr ) );
return 1;
}
if ( token == "MultiPV" )
{
long mpv = strtol( line.c_str() + pos, 0, 10 );
multiPV = (uint)std::max( 1l, std::min( 256l, mpv ) );
engine.setMultiPV( multiPV );
return 1;
}
if ( token == "OwnBook" )
{
long obk = strtol( line.c_str() + pos, 0, 10 );
engine.setOwnBook( obk != 0 );
return 1;
}
if ( token == "NullMove" )
{
long nm = strtol( line.c_str() + pos, 0, 10 );
engine.setNullMove( nm != 0 );
return 1;
}
if ( token == "LimitStrength" )
{
long lst = strtol( line.c_str() + pos, 0, 10 );
engine.setLimit( lst != 0 );
return 1;
}
if ( token == "Elo" )
{
long elo = strtol( line.c_str() + pos, 0, 10 );
engine.setElo( (u32)std::max( 2500l, std::min( 800l, elo ) ) );
return 1;
}
if ( token == "Contempt")
{
long contempt = strtol( line.c_str() + pos, 0, 10 );
contempt = std::max( -100L, contempt );
contempt = std::min( 100L, contempt );
engine.setContempt( (Score)contempt );
return 1;
}
error( "uknown option", line );
return 0;
}
if ( token == "quit" )
{
quitFlag = 1;
return 1;
}
if ( token == "analyze" )
{
if ( !invalidState )
{
analyze = 1;
return 1;
}
error( "current board state is invalid", line );
return 0;
}
if ( token == "new" )
{
leaveForce();
npsLimit = 0;
depthLimit = 0;
timeLimit = 0;
fixedTime = 0;
invalidState = 0;
abortSearch();
engine.clearHash();
engine.resetBoard();
engineColor = ctBlack;
searchMode.reset();
// reset clocks
resetClocks();
adjudicated = 0;
return 1;
}
if ( token == "undo" )
{
if ( !invalidState && engine.undoMove() )
return 1;
error( "can't undo", line );
return 0;
}
if ( token == "remove" )
{
// this complicated expression is to silence some static analyzers
if ( !invalidState && engine.undoMove() )
if ( engine.undoMove() )
return 1;
error( "can't remove", line );
return 0;
}
if ( token == "playother" )
{
leaveForce();
engine.abortSearch();
Color oec = engineColor;
engineColor = flip( engine.turn() );
if ( oec != engineColor )
std::swap( etime, otime );
startSearchCECP();
// start pondering if enabled...
startPondering();
return 1;
}
if ( token == "?" )
{
// FIXME: what to do if ? is received while pondering (doing nothing ATM)
if ( !analyze && !engine.isPondering() )
{
// FIXME: this causes deadlocks now that I've fixed UCI pondering bug...
// FIXME: this is super ugly, redesign and rewrite completely!!! (really?)
parseMutex.unlock();
engine.stopSearch();
parseMutex.lock();
}
return 1;
}
if ( token == "result" )
{
// don't waste system resource just in case the engine is pondering
if ( !analyze )
abortSearch();
return 1;
}
if ( token == "setboard" )
{
invalidState = 0;
Board b;
if ( !b.fromFEN( line.c_str() + pos ) )
{
sendStart( sifRaw );
sendRaw( "tellusererror Illegal position" );
sendEnd();
invalidState = 1;
error( "invalid fen", line );
return 0;
}
engine.setBoard( b );
level.move = b.move();
return 1;
}
if ( token == "edit" )
{
abortSearch();
invalidState = 0;
editBoard = engine.board();
edit = 1;
return 1;
}
if ( token == "accepted" )
{
// silently ignore
return 1;
}
if ( token == "post" )
{
post = 1;
return 1;
}
if ( token == "nopost" )
{
post = 0;
return 1;
}
if ( token == "uci" )
{
// switch to the (preferred atm) UCI protocol
type = ptUCI;
return parseUCI( line );
}
if ( token == "xboard" )
{
#ifdef USE_TUNING
PSq::init();
#endif
return 1; // consume silently
}
if ( parseSpecial( token, line, pos ) )
return 1;
error( "unknown command", line );
return 0;
}
void Protocol::error( const std::string &msg, const std::string &line )
{
switch( type )
{
case ptUCI:
sendStart(0);
sendInfo( msg );
sendEnd();
break;
case ptCECP:
sendStart( sifRaw );
sendRaw( "Error (" );
sendRaw( msg );
sendRaw( "): ");
sendRaw( line );
sendEnd();
break;
case ptNative:
break;
}
}
// CECP: reset clock
void Protocol::resetClocks()
{
// TODO: implement...
}
void Protocol::stopClocks()
{
abortSearch();
clocksRunning = 0;
}
bool Protocol::setTurn( Color c )
{
return engine.setTurn( c );
}
void Protocol::leaveForce()
{
if ( force )
{
force = 0;
}
}
void Protocol::enterForce()
{
stopClocks();
force = 1;
}
void Protocol::illegalMove( Move m, const std::string &line )
{
switch( type )
{
case ptUCI:
error( "illegal move from GUI", line );
break;
case ptCECP:
sendStart( sifRaw );
sendRaw( "Illegal move: " );
sendRaw( engine.board().toUCI( m ) );
sendEnd();
break;
case ptNative:
break;
}
}
// try to adjudicate game after engine/user move
// if it's win/draw/loss, result is nonzero and appropriate string is sent to GUI
bool Protocol::adjudicate()
{
const Board &b = engine.board();
Draw dr = b.isDraw();
if ( dr == drawMaterial )
{
sendStart( sifRaw );
sendRaw( "result 1/2-1/2 {Insufficient material}" );
sendEnd();
adjudicated = 1;
return 1;
}
if ( dr == drawFifty )
{
sendStart( sifRaw );
sendRaw( "result 1/2-1/2 {Fifty move rule}" );
sendEnd();
adjudicated = 1;
return 1;
}
MoveGen mg( b );
Move m = mg.next();
if ( m == mcNone )
{
if ( b.inCheck() )
{
// mated!
sendStart( sifRaw );
if ( b.turn() == ctBlack )
{
sendRaw( "result 1-0 {White mates}" );
adjudicated = 1*2;
}
else
{
sendRaw( "result 0-1 {Black mates}" );
adjudicated = -1*2;
}
sendEnd();
adjudicated |= 1;
} else
{
// stalemate
sendStart( sifRaw );
sendRaw( "result 1/2-1/2 {Stalemate}" );
sendEnd();
adjudicated = 1;
}
return 1;
}
// check for draw by repetition!
if ( engine.isThreefold() )
{
sendStart( sifRaw );
sendRaw( "result 1/2-1/2 {Threefold repetition}" );
sendEnd();
adjudicated = 1;
return 1;
}
return 0;
}
// parse special (nonstd) command
bool Protocol::parseSpecial( const std::string &token, const std::string &line, size_t &pos )
{
if ( token == "dump" )
{
engine.abortSearch();
engine.board().dump();
Score evl = engine.mainThread->search.eval.eval( engine.board() );
std::cout << "eval: " << evl << std::endl;
std::cout.flush();
return 1;
}
if ( token == "bench" )
{
engine.abortSearch();
bench();
return 1;
}
if ( token == "pbench" )
{
engine.abortSearch();
pbench();
return 1;
}
if ( token == "tbench" )
{
engine.abortSearch();
tbench();
return 1;
}
if ( token == "perft" )
{
std::string t = nextToken( line, pos );
if ( t.empty() )
{
error( "perft arg expected", line );
return 1;
}
engine.abortSearch();
long tmp = strtol( t.c_str(), 0, 10 );
Depth d = (Depth)( std::max( 1l, std::min( (long)maxDepth, tmp ) ) );
Board b( engine.board() );
i32 ms = Timer::getMillisec();
NodeCount res = perft( b, d );
ms = Timer::getMillisec() - ms;
std::cout << res << " nodes" << std::endl;
std::cout << "took " << ms << " ms" << std::endl;
std::cout.flush();
return 1;
}
if ( token == "divide" )
{
std::string t = nextToken( line, pos );
if ( t.empty() )
{
error( "divide arg expected", line );
return 1;
}
engine.abortSearch();
long tmp = strtol( t.c_str(), 0, 10 );
Depth d = (Depth)( std::max( 1l, std::min( (long)maxDepth, tmp ) ) );
Board b( engine.board() );
MoveGen mg( b );
Move m;
NodeCount total = 0;
MoveCount mc = 0;
i32 ms = Timer::getMillisec();
while ( (m = mg.next()) != mcNone )
{
mc++;
bool isCheck = b.isCheck( m, mg.discovered() );
std::cout << b.toSAN( m ) << ' ';
UndoInfo ui;
b.doMove( m, ui, isCheck );
NodeCount nc = perft( b, d-1 );
b.undoMove( ui );
total += nc;
std::cout << nc << std::endl;
}
ms = Timer::getMillisec() - ms;
std::cout << (uint)mc << " moves " << total << " nodes" << std::endl;
std::cout << "took " << ms << " ms" << std::endl;
std::cout.flush();
return 1;
}
if ( token == "book" )
{
// special book debug
engine.abortSearch();
Board b( engine.board() );
std::vector< Move > moves;
std::vector< u32 > counts;
u32 sum;
sum = std::max(1u, engine.book.enumEntries(b, moves, 0, &counts));
assert( moves.size() == counts.size() );
for ( size_t i=0; i<moves.size(); i++ )
{
std::string move = b.toSAN( moves[i] );
u32 score = sum ? counts[i]*100 / sum : 0;
std::cout << move << " count " << counts[i] << " score " << score << std::endl;
}
// enumerate moves to avoid
std::max(1u, engine.book.enumEntries(b, moves, 1, &counts));
assert( moves.size() == counts.size() );
if ( moves.empty() )
return 1;
std::cout << "avoid moves:" << std::endl;
for ( size_t i=0; i<moves.size(); i++ )
{
std::string move = b.toSAN( moves[i] );
std::cout << move << " count " << counts[i] << std::endl;
}
return 1;
}
if ( token == "filterpgn" )
{
// filter pgn
filterPgn( line.c_str() + pos );
return 1;
}
if ( token == "loadepd" )
{
// epd debug
if ( !epd.load( line.c_str() + pos ) )
{
std::cout << "failed to load epd!" << std::endl;
}
return 1;
}
if ( token == "runepd" )
{
const char *tmp = line.c_str() + pos;
skipSpaces(tmp);
long depth = 2;
if (isdigit(*tmp))
depth = strtol(tmp, 0, 10);
// epd debug run, fixed depth
runEPDSuite( epd, (Depth)depth);
return 1;
}
if ( token == "pbook" )
{
pbook();
return 1;
}
#ifdef USE_TUNING
if ( token == "params" )
{
TunableParams::get()->dump();
std::cout.flush();
return 1;
}
#endif
return 0;
}
void Protocol::allocTime(i32 mytime, i32 myinc, i32 /*optime*/, i32 /*opinc*/, i32 movestogo, SearchMode &sm)
{
sm.absLimit = 0;
i32 mvl;
bool suddenDeath = 0;
if ( movestogo == 0 )
{
// sudden death
suddenDeath = 1;
movestogo = 25;
mytime -= 100; // reserve
}
mvl = (mytime + movestogo * myinc) / movestogo;
if ( suddenDeath && mvl > mytime/2 )
mvl = mytime/2;
if ( movestogo == 1 )
sm.absLimit = mvl -= 100; // reserve
else
sm.absLimit = mytime/4;
if ( mvl <= 0 )
mvl = -1;
if ( sm.absLimit <= 0 )
sm.absLimit = -1;
sm.maxTime = mvl;
}
// is game over (CECP)?
int Protocol::isGameOverCECP() const
{
return adjudicated;
}
}
| 21.294291 | 128 | 0.58299 | [
"vector"
] |
e9e2f02ff8d6205ef21e4def51848dea688b1d93 | 956 | cpp | C++ | src/soso/TransformSystem.cpp | markkorput/Entity-Component-Samples | 983258f6b6fec674396bd6c54f0f70c215e8238f | [
"MIT"
] | 108 | 2015-10-22T23:19:01.000Z | 2021-11-13T00:50:58.000Z | src/soso/TransformSystem.cpp | markkorput/Entity-Component-Samples | 983258f6b6fec674396bd6c54f0f70c215e8238f | [
"MIT"
] | 3 | 2015-10-22T19:26:08.000Z | 2017-12-02T05:41:24.000Z | src/soso/TransformSystem.cpp | markkorput/Entity-Component-Samples | 983258f6b6fec674396bd6c54f0f70c215e8238f | [
"MIT"
] | 13 | 2015-10-23T09:08:17.000Z | 2021-02-03T12:23:51.000Z | //
// TransformSystem.cpp
//
// Created by Soso Limited on 1/8/15.
//
//
#include "TransformSystem.h"
#include "HierarchyComponent.h"
#include "Transform.h"
using namespace entityx;
using namespace cinder;
using namespace soso;
void TransformSystem::update(EntityManager &entities, EventManager &events, TimeDelta dt)
{
ComponentHandle<Transform> transform;
/// If/when entityx allows us to order our components in memory based on their hierarchy,
/// we will be able to walk through and simply update in linear order.
/// We could also do that if we wrote our own memory allocator for transforms (which we are unlikely to pursue).
for (Entity __unused e : entities.entities_with_components(transform))
{
if (transform->isRoot())
{
transform->composeTransform(mat4(1));
transform->descend([] (const Transform &parent, Transform &child) {
child.composeTransform(parent.worldTransform());
});
}
}
}
| 27.314286 | 114 | 0.714435 | [
"transform"
] |
e9e41eaba186d6e7cd77d53dddcff33956030f07 | 7,770 | cpp | C++ | sim/AgentEnvWindow.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | sim/AgentEnvWindow.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | sim/AgentEnvWindow.cpp | snumrl/VSports | c35bc82db31cd7252ab3d0f78c3f941bae5e799b | [
"Apache-2.0"
] | null | null | null | // #include "AgentEnvWindow.h"
// #include "Environment.h"
// #include "../render/GLfunctionsDART.h"
// #include "../model/SkelMaker.h"
// #include "../model/SkelHelper.h"
// #include "../pyvs/EnvironmentPython.h"
// // #include <GL/glew.h>
// #include <GL/glut.h>
// #include <GL/glew.h>
// #include <GLFW/glfw3.h>
// // Include GLM
// #include <glm/glm.hpp>
// using namespace glm;
// #include <iostream>
// using namespace dart::dynamics;
// using namespace dart::simulation;
// using namespace std;
// #include <EGL/egl.h>
// static const EGLint configAttribs[] = {
// EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
// EGL_BLUE_SIZE, 8,
// EGL_GREEN_SIZE, 8,
// EGL_RED_SIZE, 8,
// EGL_DEPTH_SIZE, 8,
// EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
// EGL_NONE
// };
// static const int pbufferWidth = 9;
// static const int pbufferHeight = 9;
// static const EGLint pbufferAttribs[] = {
// EGL_WIDTH, pbufferWidth,
// EGL_HEIGHT, pbufferHeight,
// EGL_NONE,
// };
// static EGLint const attribute_list[] = {
// EGL_RED_SIZE, 1,
// EGL_GREEN_SIZE, 1,
// EGL_BLUE_SIZE, 1,
// EGL_NONE
// };
// // typedef ... NativeWindowType;
// // extern NativeWindowType createNativeWindow(void);
// AgentEnvWindow::
// AgentEnvWindow(int index, Environment* env)
// :SimWindow(), mIndex(index)
// {
// // EGLDisplay eglDpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
// // EGLint major, minor;
// // eglInitialize(eglDpy, &major, &minor);
// // // 2. Select an appropriate configuration
// // EGLint numConfigs;
// // EGLConfig eglCfg;
// // eglChooseConfig(eglDpy, configAttribs, &eglCfg, 1, &numConfigs);
// // // 3. Create a surface
// // EGLSurface eglSurf = eglCreatePbufferSurface(eglDpy, eglCfg,
// // pbufferAttribs);
// // // 4. Bind the API
// // eglBindAPI(EGL_OPENGL_API);
// // // 5. Create a context and make it current
// // EGLContext eglCtx = eglCreateContext(eglDpy, eglCfg, EGL_NO_CONTEXT,
// // NULL);
// // eglMakeCurrent(eglDpy, eglSurf, eglSurf, eglCtx);
// // from now on use your OpenGL context
// // 6. Terminate EGL when finished
// // eglTerminate(eglDpy);
// mEnv = env;
// initWindow(84, 84, "Agent 0 view");
// setAgentView();
// initGoalpost();
// cout<<"2222222"<<endl;
// }
// void
// AgentEnvWindow::
// initWindow(int _w, int _h, char* _name)
// {
// EGLDisplay display;
// EGLConfig config;
// EGLContext context;
// EGLSurface surface;
// // NativeWindowType native_window;
// EGLint num_config;
// /* get an EGL display connection */
// display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
// /* initialize the EGL display connection */
// eglInitialize(display, NULL, NULL);
// /* get an appropriate EGL frame buffer configuration */
// eglChooseConfig(display, attribute_list, &config, 1, &num_config);
// /* create an EGL rendering context */
// context = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
// cout<<"11111111"<<endl;
// mWindows.push_back(this);
// glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE | GLUT_ACCUM);
// /* create a native window */
// glutInitWindowSize(_w, _h);
// int native_window = glutCreateWindow(_name);
// /* create an EGL window surface */
// surface = eglCreateWindowSurface(display, config, native_window, NULL);
// /* connect the context to the surface */
// eglMakeCurrent(display, surface, surface, context);
// // cout<<"22222222"<<endl;
// // glutInitWindowPosition(1500, -500);
// // glutInitWindowSize(_w, _h);
// // cout<<"3333333333"<<endl;
// // mWinIDs.push_back(glutCreateWindow(_name));
// // cout<<"444444444"<<endl;
// // glutHideWindow();
// // glutDisplayFunc(displayEvent);
// // glutReshapeFunc(reshapeEvent);
// // glutKeyboardFunc(keyboardEvent);
// // glutKeyboardUpFunc(keyboardUpEvent);
// // glutMouseFunc(mouseEvent);
// // glutMotionFunc(motionEvent);
// // glutTimerFunc(mDisplayTimeout, timerEvent, 0);
// mScreenshotTemp.resize(4*_w*_h);
// mScreenshotTemp2.resize(4*_w*_h);
// agentViewImg.resize(4*_w*_h);
// agentViewImgTemp.resize(4*_w*_h);
// // glfw.window_hint(glfw.VISIBLE, false);
// // glut.
// }
// void
// AgentEnvWindow::
// setAgentView()
// {
// Eigen::Vector3d characterPosition;
// SkeletonPtr skel = mEnv->getCharacter(mIndex)->getSkeleton();
// characterPosition.segment(0,2) = skel->getPositions().segment(0,2);
// characterPosition[2] = 0.5;
// mCamera->lookAt = characterPosition;
// mCamera->up = Eigen::Vector3d(0.0, 0.0, 1.0);
// Eigen::AngleAxisd rotation = Eigen::AngleAxisd(skel->getPosition(2), mCamera->up);
// // cout<<mEnv->getCharacter(mIndex)->getDirection()<<endl;
// // mEnv->getCharacter(mIndex)->getSkeleton()->
// // setPosition(2, mEnv->getCharacter(mIndex)->getSkeleton()->getPosition(2)+0.02);
// mCamera->eye = characterPosition + rotation*Eigen::Vector3d(-1.2, 0.0, +0.2);
// }
// void
// AgentEnvWindow::
// initGoalpost()
// {
// redGoalpostSkel = SkelHelper::makeGoalpost(Eigen::Vector3d(-4.0, 0.0, 0.25 + floorDepth), "red");
// blueGoalpostSkel = SkelHelper::makeGoalpost(Eigen::Vector3d(4.0, 0.0, 0.25 + floorDepth), "blue");
// mWorld->addSkeleton(redGoalpostSkel);
// mWorld->addSkeleton(blueGoalpostSkel);
// }
// void
// AgentEnvWindow::
// display()
// {
// cout<<"3333333333333"<<endl;
// glClearColor(0.85, 0.85, 1.0, 1.0);
// // glClearColor(1.0, 1.0, 1.0, 1.0);
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// glEnable(GL_DEPTH_TEST);
// cout<<"4444444444"<<endl;
// initLights();
// cout<<"55555555555"<<endl;
// setAgentView();
// mCamera->apply();
// std::vector<Character2D*> chars = mEnv->getCharacters();
// for(int i=0;i<chars.size();i++)
// {
// // if (i!=0)
// // continue;
// if(chars[i]->getTeamName() == "A")
// GUI::drawSkeleton(chars[i]->getSkeleton(), Eigen::Vector3d(1.0, 0.0, 0.0));
// // else
// // GUI::drawSkeleton(chars[i]->getSkeleton(), Eigen::Vector3d(0.0, 0.0, 1.0));
// }
// GUI::drawSkeleton(mEnv->floorSkel, Eigen::Vector3d(0.5, 1.0, 0.5));
// GUI::drawSkeleton(mEnv->ballSkel, Eigen::Vector3d(0.1, 0.1, 0.1));
// GUI::drawSkeleton(mEnv->wallSkel, Eigen::Vector3d(0.5,0.5,0.5));
// // Not simulated just for see
// GUI::drawSkeleton(redGoalpostSkel, Eigen::Vector3d(1.0, 1.0, 1.0), true);
// GUI::drawSkeleton(blueGoalpostSkel, Eigen::Vector3d(1.0, 1.0, 1.0));
// GUI::drawSoccerLine(8, 6);
// // glutSwapBuffers();
// // if(mTakeScreenShot)
// // {
// // screenshot();
// // }
// cout<<"66666666666"<<endl;
// // glutPostRedisplay();
// cout<<glutGet(GLUT_WINDOW_WIDTH)<<endl;
// cout<<glutGet(GLUT_WINDOW_HEIGHT)<<endl;
// cout<<"777777777777"<<endl;
// screenshot();
// getAgentView();
// cout<<"88888888888"<<endl;
// // eglSwapBuffers(display, surface);
// }
// void
// AgentEnvWindow::
// getAgentView()
// {
// int tw = glutGet(GLUT_WINDOW_WIDTH);
// int th = glutGet(GLUT_WINDOW_HEIGHT);
// glReadPixels(0, 0, tw, th, GL_RGBA, GL_UNSIGNED_BYTE, &agentViewImgTemp[0]);
// // reverse temp2 temp1
// for (int row = 0; row < th; row++) {
// memcpy(&agentViewImg[row * tw * 4],
// &agentViewImgTemp[(th - row - 1) * tw * 4], tw * 4);
// }
// }
// void
// AgentEnvWindow::
// keyboard(unsigned char key, int x, int y)
// {
// // SimWindow::keyboard(key, x, y);
// }
// void
// AgentEnvWindow::
// keyboardUp(unsigned char key, int x, int y)
// {
// // SimWindow::keyboardUp(key, x, y);
// }
// void
// AgentEnvWindow::
// timer(int value)
// {
// SimWindow::timer(value);
// }
// void
// AgentEnvWindow::
// mouse(int button, int state, int x, int y)
// {
// }
// void
// AgentEnvWindow::
// motion(int x, int y)
// {
// }
| 25.309446 | 102 | 0.634878 | [
"render",
"vector",
"model"
] |
e9e6b902d947acb8e2281d93b3afbaf0e0a3d778 | 4,107 | hpp | C++ | core/assimp_scene.hpp | ChaithanyaSingamala/gl-examples | b5ed43cbbd32d5e2629421b6877e724d2069a92f | [
"MIT"
] | null | null | null | core/assimp_scene.hpp | ChaithanyaSingamala/gl-examples | b5ed43cbbd32d5e2629421b6877e724d2069a92f | [
"MIT"
] | null | null | null | core/assimp_scene.hpp | ChaithanyaSingamala/gl-examples | b5ed43cbbd32d5e2629421b6877e724d2069a92f | [
"MIT"
] | null | null | null | #pragma once
#include "scene.hpp"
#include "transfrom.hpp"
#include "helper.h"
#include "assimp/Importer.hpp"
#include "assimp/scene.h"
#include "assimp/postprocess.h"
using namespace glm;
using namespace std;
class AssimpScene : public Scene {
public:
AssimpScene(std::string _filename)
{
vector<char> dataStr = ReadBinaryFile(_filename);
size_t dataLength = dataStr.size();
void* data = dataStr.data();
string ext = _filename.substr(_filename.find_last_of('.'), _filename.length());
Assimp::Importer importer;
const aiScene* scene = importer.ReadFileFromMemory(data, dataLength, aiProcess_Triangulate | aiProcess_FlipUVs, ext.c_str());
if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
{
string error = importer.GetErrorString();
LogE("ERROR::ASSIMP: %s", error.c_str());
}
string directory = _filename.substr(0, _filename.find_last_of('/'));
ProcessNode(scene->mRootNode, scene);
}
void ProcessNode(aiNode * node, const aiScene * scene)
{
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
this->meshes.push_back(ProcessMesh(mesh, scene));
}
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
ProcessNode(node->mChildren[i], scene);
}
}
Mesh * ProcessMesh(aiMesh * mesh, const aiScene * scene)
{
std::vector<unsigned short> indices;
//vector<Texture> textures;
int totalVertexLength = 8;
std::vector<float> vertices(mesh->mNumVertices * totalVertexLength);
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
vertices[0 + i * totalVertexLength] = mesh->mVertices[i].x;
vertices[1 + i * totalVertexLength] = mesh->mVertices[i].y;
vertices[2 + i * totalVertexLength] = mesh->mVertices[i].z;
// Normals
if (mesh->mNormals)
{
vertices[3 + i * totalVertexLength] = mesh->mNormals[i].x;
vertices[4 + i * totalVertexLength] = mesh->mNormals[i].y;
vertices[5 + i * totalVertexLength] = mesh->mNormals[i].z;
}
else
{
vertices[3 + i * totalVertexLength] = 0.0f;
vertices[4 + i * totalVertexLength] = 0.0f;
vertices[5 + i * totalVertexLength] = 0.0f;
}
if (mesh->mTextureCoords[0]) // Does the mesh contain texture coordinates?
{
vertices[6 + i * totalVertexLength] = mesh->mTextureCoords[0][i].x;
vertices[7 + i * totalVertexLength] = mesh->mTextureCoords[0][i].y;
}
else
{
vertices[6 + i * totalVertexLength] = 0.0f;
vertices[7 + i * totalVertexLength] = 0.0f;
}
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
/** /
// Process materials
if (mesh->mMaterialIndex >= 0)
{
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// We assume a convention for sampler names in the shaders. Each diffuse texture should be named
// as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
// Same applies to other texture as the following list summarizes:
// Diffuse: texture_diffuseN
// Specular: texture_specularN
// Normal: texture_normalN
// 1. Diffuse maps
vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. Specular maps
vector<Texture> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
}
*/
return new Mesh(vertices, indices,
{
{ 0, 0, 3, 8 },
{ 2, 3, 3, 8, },
{ 1, 6, 2, 8 },
}
);
#if 0
return new Mesh(vertices, indices,
{
{ _shader->GetAttribLocation("vertexPosition"), 0, 3, 8 },
{ _shader->GetAttribLocation("vertexNormal"), 3, 3, 8, },
{ _shader->GetAttribLocation("UV0"), 6, 2, 8 },
}
);
#endif
}
virtual void Render(Camera *camera) override
{
for (auto mesh : meshes)
mesh->Render();
}
}; | 29.12766 | 127 | 0.668615 | [
"mesh",
"render",
"vector"
] |
e9ec9ab6b482f3944094e8a9e8f0f7ea8228774d | 444 | cpp | C++ | 2020 Leetcode Challenges/09 September Leetcode Challenge 2020/26 Teemo Attacking.cpp | FazeelUsmani/Leetcode | aff4c119178f132c28a39506ffaa75606e0a861b | [
"MIT"
] | 7 | 2020-12-01T14:27:57.000Z | 2022-02-12T09:17:22.000Z | 2020 Leetcode Challenges/09 September Leetcode Challenge 2020/26 Teemo Attacking.cpp | FazeelUsmani/Leetcode | aff4c119178f132c28a39506ffaa75606e0a861b | [
"MIT"
] | 4 | 2020-11-12T17:49:22.000Z | 2021-09-06T07:46:37.000Z | 2020 Leetcode Challenges/09 September Leetcode Challenge 2020/26 Teemo Attacking.cpp | FazeelUsmani/Leetcode | aff4c119178f132c28a39506ffaa75606e0a861b | [
"MIT"
] | 6 | 2021-05-21T03:49:22.000Z | 2022-01-20T20:36:53.000Z | class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
if (timeSeries.size() == 0) return 0;
if (timeSeries.size() == 1) return duration;
int total = 0;
for (int i = 1; i < timeSeries.size(); ++i)
total += min(duration, timeSeries[i]-timeSeries[i-1]);
total += duration;
return total;
}
};
| 26.117647 | 69 | 0.502252 | [
"vector"
] |
e9edcefb63f74e62bc7cf5f5c6fada8b8ff2ebcb | 5,673 | cpp | C++ | examples/target_hit_detection.cpp | embeddr/vec | 990cceee55e044629ab9da52c58a633374583017 | [
"MIT"
] | null | null | null | examples/target_hit_detection.cpp | embeddr/vec | 990cceee55e044629ab9da52c58a633374583017 | [
"MIT"
] | 4 | 2021-03-29T05:28:03.000Z | 2021-09-26T03:28:02.000Z | examples/target_hit_detection.cpp | embeddr/vec | 990cceee55e044629ab9da52c58a633374583017 | [
"MIT"
] | null | null | null | // Vec library usage example: target hit detection
//
// This is an example of a basic interview-style problem on vector geometry for game programming.
// The premise is that we want to implement the hit-detection logic for a simple shooting gallery
// mini-game. There exists a flat, circular target at some position and orientation in 3D space, and
// a player shooting in a known direction from some other point in space.
//
// We can fully describe a circular target with the following:
// 1. The point in space at which the center of the target lies (p0)
// 2. The vector normal to the plane on which the target lies (n)
// 3. The radius of the target (r)
//
// Similarly, we can fully describe a player shot with the following:
// 1. The point in space at which the player is shooting from (s)
// 2. The vector describing the direction of the player's shot (v)
//
// The player's shot projects a ray with parametric equation:
//
// ps = s + tv
//
// Where t is a scalar in the range [0, inf) since we only want to project in the forward direction.
// We can sweep t across this range to generate any point ps along the trajectory of the shot.
//
// The target lies on a plane described by the implicit equation:
//
// (p - p0) dot n = 0
//
// The vector formed by the difference between any arbitrary point p on the plane and the known
// center of the target p0 will be orthogonal to the normal vector, meaning the dot product is zero.
//
// We can plug the above parametric ray equation in for point p in the implicit plane equation
// and attempt to solve for t to see if the ray actually intersects the plane:
//
// (s + tv - p0) dot n = 0
// ((s - p0) dot n) + (tv dot n) = 0
// tv dot n = (p0 - s) dot n
// t = ((p0 - s) dot n) / (v dot n)
//
// At this point we can check the denominator (v dot n) for zero, as that would blow up the
// equation and also indicates that the shot is parallel to the surface of the plane, meaning
// there is no intersect point (unless the shooting point s was actually on the surface of the
// plane, which we'll choose to not worry about).
//
// Assuming the denominator is not zero, we can solve for t. If t is positive, there is an
// intersect point in the direction of the player's shot. If t is negative, then there is an
// intersect on the line, but in the opposite direction of the player's shot, so the shot is
// obviously a miss.
//
// If t is positive, we can plug that back into the original ray equation to solve for the actual
// intersect point:
//
// p1 = s + tv
//
// We can then check the euclidean distance between intersect point p1 and target center point
// p0, and compare that to the radius of the target. However, calculating the euclidean distance
// requires taking the square root of (p1 - p0) dot (p1 - p0), and square roots are relatively
// expensive. It's more computationally efficient to instead square the radius and compare the
// square of both sides:
//
// If (p1 - p0) dot (p1 - p0) < r^2 , the shot is a hit.
//
// This logic is implemented below in check_target_hit().
#include <iostream>
#include <iomanip>
#include "vec.hpp"
using vec::Vec3f;
using std::cout;
using std::endl;
// Shot parameters
struct Shot {
Vec3f position; // Position of shot relative to arbitrary origin [m_x,m_y,m_z]
Vec3f direction; // Direction of shot [unitless]
};
// Target parameters
struct CircleTarget {
Vec3f position; // Position of center of target relative to arbitrary origin [m_x,m_y,m_z]
Vec3f normal; // Normal of the plane on which the target lies [unitless]
float radius; // Radius of target [m]
};
std::ostream& operator<<(std::ostream& os, const Shot& rhs) {
os << "Shot:" << endl;
os << " position: " << rhs.position << endl;
os << " direction: " << rhs.direction << endl;
return os;
}
std::ostream& operator<<(std::ostream& os, const CircleTarget& rhs) {
os << "CircleTarget:" << endl;
os << " position: " << rhs.position << endl;
os << " normal: " << rhs.normal << endl;
os << " radius: " << rhs.radius << endl;
return os;
}
// Check if the provided shot hit the provided circular target
constexpr bool check_target_hit(const Shot& shot, const CircleTarget& target) {
const float denominator = dot(shot.direction, target.normal);
if (std::abs(denominator) < 0.00001f) {
// Shot is approximately parallel with the plane; no hit
return false;
}
const float numerator = dot((target.position - shot.position), target.normal);
const float t = numerator / denominator;
if (t < 0.0f) {
// Shot is in wrong direction; no hit
return false;
}
// Intersect point exists; check distance from target center against radius
// Note: checking square of distance against square of radius for efficiency
const Vec3f intersect = shot.position + (t * shot.direction);
return euclidean2(intersect, target.position) < (target.radius * target.radius);
}
int main() {
cout << "Vec example: circular target hit detection" << endl;
// Arbitrary constexpr example
constexpr Shot shot{
.position = Vec3f{0.0f, -0.5f, 0.0f},
.direction = Vec3f{1.0f, 0.2f, 0.0f},
};
constexpr CircleTarget target{
.position = Vec3f{5.0f, 0.0f, 0.0f},
.normal = Vec3f{-1.0f, 0.0f, 0.5f},
.radius = 1.0f,
};
constexpr bool hit = check_target_hit(shot, target);
cout << std::fixed << std::setprecision(1);
cout << shot << target << "Result: " << (hit ? "hit!" : "miss") << endl;
// TODO: runtime example with user input
return EXIT_SUCCESS;
} | 39.124138 | 100 | 0.673541 | [
"geometry",
"vector",
"3d"
] |
e9f482a858571d8efb275eb0668d0c2f75ee6c0a | 5,176 | cpp | C++ | lib/src/main/cpp/lib/pixFu_launcher/Launcher.cpp | nebular/PixEngine_Android | 02aad4aec8a625bdd1447ca63453e31976a97fa1 | [
"CC-BY-4.0"
] | 5 | 2020-04-23T11:11:28.000Z | 2021-09-13T14:45:05.000Z | lib/src/main/cpp/lib/pixFu_launcher/Launcher.cpp | nebular/PixFu_Android_src | 02aad4aec8a625bdd1447ca63453e31976a97fa1 | [
"CC-BY-4.0"
] | null | null | null | lib/src/main/cpp/lib/pixFu_launcher/Launcher.cpp | nebular/PixFu_Android_src | 02aad4aec8a625bdd1447ca63453e31976a97fa1 | [
"CC-BY-4.0"
] | null | null | null | /*
* Generic Android Native OpenGL Application Launcher
* Author: Rodolfo Lopez Pintor 2020.
*
* License: Creative Commons CC-BY 4.0
*
* This is the native part of the launcher application. Will lbe called by Android to initialize, render,
* deinit and on mouse events.
*
*/
#include <jni.h>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "Fu.hpp"
#include "Launcher.h"
#include "RendererPix.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
static Pix::Renderer *g_renderer = nullptr;
// these functions are called from Java, hence the exotic decorations
extern "C" {
JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_init(JNIEnv *env, jclass obj, jstring path);
JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_resize(JNIEnv *env, jclass obj, jint width,
jint height);
JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_onTouch(JNIEnv *env, jclass obj,
jobject motionEvent, jint decodedAction,
jint pointerId, jfloat screenDensity);
};
#if !defined(DYNAMIC_ES3)
static GLboolean gl3stubInit() {
return GL_TRUE;
}
#endif
/**
* Initialization. This is really onSurfaceCreated and the place to init OpenGL
* It may be called several times if the user goes back to home, etc.
* Called from JAVA
*/
extern "C" JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_init(JNIEnv *env, jclass obj,
jstring internalFilesPath) {
if (g_renderer == nullptr) {
const char *cstr = env->GetStringUTFChars(internalFilesPath, nullptr);
/*
* Initialize the Base Path for the PGE. Android is very restrictive and will only allow to write
* in very few places. This path is the internal application storage directory, and all assets are
* copied here by the Java part.
*/
Pix::FuPlatform::setPath(std::string(cstr) + "/");
/*
* Creates the Pge Renderer. It is there where we will instantiate the PGE, and
* where the PGE object lives.
*/
const char *versionStr = (const char *) glGetString(GL_VERSION);
if ((strstr(versionStr, "OpenGL ES 3.") && gl3stubInit()) ||
strstr(versionStr, "OpenGL ES 2.")) {
Pix::FuPlatform *platform = Pix::PixFuPlatformAndroid::instance();
Pix::Fu *engine = (dynamic_cast<Pix::PixFuPlatformAndroid *>(platform))->engine();
g_renderer = Pix::RendererPix::createRender(engine);
} else {
ALOGE("Unsupported OpenGL ES version");
}
} else {
g_renderer->onLifeCycle(Pix::Renderer::ONSURFACECREATED);
}
}
/**
* "Resize" is really our main function, as it is the first place where we know about the window
* size that has been assigned to us (we request the window size and it is later confirmed here
* by Android's openGL stack)
*
* Called from JAVA when the size is known.
*
*/
extern "C" JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_resize(JNIEnv *env, jclass obj, jint width,
jint height) {
if (g_renderer) {
g_renderer->resize((unsigned) width, (unsigned) height);
}
}
/**
* This is called by the OpenGL stack th request a frame.
*/
extern "C" JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_step(JNIEnv *env, jclass obj) {
if (g_renderer) {
g_renderer->render();
}
}
extern "C" JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_onPause(JNIEnv *env, jclass obj,
jboolean status) {
if (g_renderer) {
g_renderer->onLifeCycle(status ? Pix::Renderer::ONPAUSE : Pix::Renderer::ONRESUME);
}
}
/**
* This is called by the Java Activity to send MotionEvents (touch events)
*/
extern "C" JNIEXPORT void JNICALL
Java_tv_nebular_pixFu_launcher_NativeLauncher_onTouch(JNIEnv *jenv, jclass obj,
jobject motionEvent, jint decodedAction,
jint pointerId, jfloat screenDensity) {
jclass motionEventClass = jenv->GetObjectClass(motionEvent);
jmethodID pointersCountMethodId = jenv->GetMethodID(motionEventClass, "getPointerCount", "()I");
int pointersCount = jenv->CallIntMethod(motionEvent, pointersCountMethodId);
jmethodID getActionMethodId = jenv->GetMethodID(motionEventClass, "getAction", "()I");
int32_t action = jenv->CallIntMethod(motionEvent, getActionMethodId);
jmethodID getXMethodId = jenv->GetMethodID(motionEventClass, "getX", "(I)F");
float x0 = jenv->CallFloatMethod(motionEvent, getXMethodId, 0);
jmethodID getYMethodId = jenv->GetMethodID(motionEventClass, "getY", "(I)F");
float y0 = jenv->CallFloatMethod(motionEvent, getYMethodId, 0);
float x1 = -1;
float y1 = -1;
if (pointersCount > 1) {
x1 = jenv->CallFloatMethod(motionEvent, getXMethodId, 1);
y1 = jenv->CallFloatMethod(motionEvent, getYMethodId, 1);
}
Pix::MotionEvent_t inputEvent;
inputEvent.PointersCount = pointersCount;
inputEvent.Action = action;
inputEvent.RawAction = decodedAction;
inputEvent.PointerId = pointerId;
inputEvent.X0 = x0 / screenDensity;
inputEvent.Y0 = y0 / screenDensity;
inputEvent.X1 = x1 / screenDensity;
inputEvent.Y1 = y1 / screenDensity;
g_renderer->onMotionEvent(inputEvent);
}
#pragma clang diagnostic pop | 30.269006 | 105 | 0.731453 | [
"render",
"object"
] |
e9f94248cf5c9edbfb5bf7fd782d685b1784cc3c | 14,172 | cpp | C++ | src/LuaPlugins.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 5 | 2020-09-02T06:58:15.000Z | 2021-12-26T02:29:35.000Z | src/LuaPlugins.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 10 | 2021-11-23T16:10:38.000Z | 2021-12-30T16:05:52.000Z | src/LuaPlugins.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 1 | 2021-07-13T16:55:53.000Z | 2021-07-13T16:55:53.000Z | #include "../include/LuaPlugins.hpp"
#include "../include/Server.hpp"
#include "../include/Utils/Vector.hpp"
#include <iostream>
#include <vector>
#include <map>
#include <filesystem>
#undef SendMessage
namespace LuaPlugins {
std::vector<sol::function> authEvent;
std::vector<sol::function> messageEvent;
std::vector<sol::function> joinEvent;
std::vector<sol::function> positionOrientationEvent;
std::vector<sol::function> setBlockEvent;
std::vector<sol::function> disconnectEvent;
std::vector<sol::function> playerClickedEvent;
std::vector<sol::function> extEntryEvent;
} // namespace LuaPlugins
void LuaPlugin::Init()
{
try {
m_env["include"] = [&](std::string filename)
{
m_lua->script_file("plugins/" + m_name + "/" + filename, m_env);
};
m_lua->script_file(m_filename, m_env);
} catch (std::runtime_error &e) {
std::cerr << "LuaPlugin::Init(): " << e.what() << std::endl;
}
sol::function init = m_env["Init"];
if (!init.valid())
throw std::runtime_error(std::string("LuaPlugin: " + m_name + " (" + m_filename + ") Init function not found"));
sol::function tick = m_env["Tick"];
if (tick.valid())
m_tick = tick;
try {
init();
}
catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}
void LuaPlugin::Tick()
{
if (m_tick != sol::nil)
m_tick();
}
void PluginHandler::InitLua()
{
m_lua = std::make_shared<sol::state>();
m_lua->open_libraries(sol::lib::base, sol::lib::coroutine, sol::lib::string, sol::lib::io, sol::lib::table, sol::lib::math, sol::lib::os, sol::lib::debug);
m_lua->new_usertype<Net::Client>("Client",
"GetSID", &Net::Client::GetSID,
"QueuePacket", &Net::Client::QueuePacket
);
m_lua->new_usertype<Utils::MCString>("MCString",
sol::constructors<Utils::MCString(const std::string&)>()
);
m_lua->new_usertype<Player>("Player",
"GetClient", &Player::GetClient,
"GetName", &Player::GetName,
"GetWorld", &Player::GetWorld,
"GetPID", &Player::GetPID,
"GetPosition", &Player::GetPosition,
"SetPosition", &Player::SetPosition,
"GetHeldBlock", &Player::GetHeldBlock,
"SetHotbarSlot", &Player::SetHotbarSlot,
"SetInventoryOrder", &Player::SetInventoryOrder,
"SendMessage", &Player::SendMessage
);
m_lua->new_usertype<World>("World",
"AddPlayer", &World::AddPlayer,
"RemovePlayer", &World::RemovePlayer,
"GetName", &World::GetName,
"GetPlayers", &World::GetPlayers,
"GetSpawnPosition", &World::GetSpawnPosition,
"GetMap", &World::GetMap,
"GetWeatherType", &World::GetWeatherType,
"SetSpawnPosition", &World::SetSpawnPosition,
"SetMap", &World::SetMap,
"SetWeatherType", &World::SetWeatherType,
"SendWeatherType", &World::SendWeatherType
);
m_lua->new_usertype<Map>("Map",
"PeekBlock", &Map::PeekBlock,
"LoadFromFile", &Map::LoadFromFile
);
m_lua->new_usertype<Utils::Vector>("Vector",
sol::constructors<Utils::Vector(float, float, float)>(),
"Normalized", &Utils::Vector::Normalized,
"x", sol::property(&Utils::Vector::SetX, &Utils::Vector::GetX),
"y", sol::property(&Utils::Vector::SetY, &Utils::Vector::GetY),
"z", sol::property(&Utils::Vector::SetZ, &Utils::Vector::GetZ)
);
m_lua->new_usertype<Net::Packet>("Packet");
(*m_lua)["GetPlugin"] = [&](std::string name) {
std::shared_ptr<LuaPlugin> plugin = std::dynamic_pointer_cast<LuaPlugin>(GetPlugin(name));
assert(plugin != nullptr);
return plugin->GetEnv();
};
m_lua->set_function("RegisterEvent", [&](std::string name, sol::function func)
{
if (name == "OnAuthentication")
LuaPlugins::authEvent.push_back(func);
else if (name == "OnMessage")
LuaPlugins::messageEvent.push_back(func);
else if (name == "OnJoin")
LuaPlugins::joinEvent.push_back(func);
else if (name == "OnPositionOrientation")
LuaPlugins::positionOrientationEvent.push_back(func);
else if (name == "OnSetBlock")
LuaPlugins::setBlockEvent.push_back(func);
else if (name == "OnDisconnect")
LuaPlugins::disconnectEvent.push_back(func);
else if (name == "OnPlayerClicked")
LuaPlugins::playerClickedEvent.push_back(func);
else if (name == "OnExtEntry")
LuaPlugins::extEntryEvent.push_back(func);
else
LOG(LOGLEVEL_WARNING, "RegisterEvent: Invalid event %s", name.c_str());
}
);
(*m_lua)["ReloadPlugins"] = [&]() { m_reloadPlugins = true; };
(*m_lua)["BlockDefaultEventHandler"] = [&]() { Server::GetInstance()->BlockDefaultEventHandler(); };
(*m_lua)["GetWorld"] = [&](std::string name) { return Server::GetInstance()->GetWorld(name); };
(*m_lua)["GetWorlds"] = [&]() { return Server::GetInstance()->GetWorlds(); };
(*m_lua)["GetPlayer"] = [&](int8_t pid) { return Server::GetInstance()->GetPlayer(pid); };
(*m_lua)["GivePrivilege"] = [&](std::string name, std::string priv) { return Server::GetInstance()->GetPrivilegeHandler().GivePrivilege(name, priv); };
(*m_lua)["TakePrivilege"] = [&](std::string name, std::string priv) { return Server::GetInstance()->GetPrivilegeHandler().TakePrivilege(name, priv); };
(*m_lua)["MakeMap"] = [&]() { return std::make_shared<Map>(); };
/* BEGIN AUTOGENERATED CODE SECTION */
// ClassicProtocol
(*m_lua)["MakePositionOrientationPacket"] = &Net::ClassicProtocol::MakePositionOrientationPacket;
(*m_lua)["MakeOrientationPacket"] = &Net::ClassicProtocol::MakeOrientationPacket;
(*m_lua)["MakeDespawnPacket"] = &Net::ClassicProtocol::MakeDespawnPacket;
(*m_lua)["MakeMessagePacket"] = &Net::ClassicProtocol::MakeMessagePacket;
(*m_lua)["MakeServerIdentificationPacket"] = &Net::ClassicProtocol::MakeServerIdentificationPacket;
(*m_lua)["MakeLevelInitializePacket"] = &Net::ClassicProtocol::MakeLevelInitializePacket;
(*m_lua)["MakeLevelDataChunkPacket"] = &Net::ClassicProtocol::MakeLevelDataChunkPacket;
(*m_lua)["MakeLevelFinalizePacket"] = &Net::ClassicProtocol::MakeLevelFinalizePacket;
(*m_lua)["MakeSetBlock2Packet"] = &Net::ClassicProtocol::MakeSetBlock2Packet;
(*m_lua)["MakeSpawnPlayerPacket"] = &Net::ClassicProtocol::MakeSpawnPlayerPacket;
(*m_lua)["MakeUserTypePacket"] = &Net::ClassicProtocol::MakeUserTypePacket;
(*m_lua)["MakeDisconnectPlayerPacket"] = &Net::ClassicProtocol::MakeDisconnectPlayerPacket;
// ExtendedProtocol
(*m_lua)["MakeExtInfoPacket"] = &Net::ExtendedProtocol::MakeExtInfoPacket;
(*m_lua)["MakeExtEntryPacket"] = &Net::ExtendedProtocol::MakeExtEntryPacket;
(*m_lua)["MakeSetClickDistancePacket"] = &Net::ExtendedProtocol::MakeSetClickDistancePacket;
(*m_lua)["MakeCustomBlocksPacket"] = &Net::ExtendedProtocol::MakeCustomBlocksPacket;
(*m_lua)["MakeHoldThisPacket"] = &Net::ExtendedProtocol::MakeHoldThisPacket;
(*m_lua)["MakeSetTextHotKeyPacket"] = &Net::ExtendedProtocol::MakeSetTextHotKeyPacket;
(*m_lua)["MakeExtAddPlayerNamePacket"] = &Net::ExtendedProtocol::MakeExtAddPlayerNamePacket;
(*m_lua)["MakeExtAddEntity2Packet"] = &Net::ExtendedProtocol::MakeExtAddEntity2Packet;
(*m_lua)["MakeExtRemovePlayerNamePacket"] = &Net::ExtendedProtocol::MakeExtRemovePlayerNamePacket;
(*m_lua)["MakeEnvSetColorPacket"] = &Net::ExtendedProtocol::MakeEnvSetColorPacket;
(*m_lua)["MakeMakeSelectionPacket"] = &Net::ExtendedProtocol::MakeMakeSelectionPacket;
(*m_lua)["MakeRemoveSelectionPacket"] = &Net::ExtendedProtocol::MakeRemoveSelectionPacket;
(*m_lua)["MakeSetBlockPermissionPacket"] = &Net::ExtendedProtocol::MakeSetBlockPermissionPacket;
(*m_lua)["MakeChangeModelPacket"] = &Net::ExtendedProtocol::MakeChangeModelPacket;
(*m_lua)["MakeEnvSetWeatherTypePacket"] = &Net::ExtendedProtocol::MakeEnvSetWeatherTypePacket;
(*m_lua)["MakeHackControlPacket"] = &Net::ExtendedProtocol::MakeHackControlPacket;
(*m_lua)["MakeDefineBlockPacket"] = &Net::ExtendedProtocol::MakeDefineBlockPacket;
(*m_lua)["MakeRemoveBlockDefinitionPacket"] = &Net::ExtendedProtocol::MakeRemoveBlockDefinitionPacket;
(*m_lua)["MakeDefineBlockExtPacket"] = &Net::ExtendedProtocol::MakeDefineBlockExtPacket;
(*m_lua)["MakeSetTextColorPacket"] = &Net::ExtendedProtocol::MakeSetTextColorPacket;
(*m_lua)["MakeSetMapEnvURLPacket"] = &Net::ExtendedProtocol::MakeSetMapEnvURLPacket;
(*m_lua)["MakeSetMapEnvPropertyPacket"] = &Net::ExtendedProtocol::MakeSetMapEnvPropertyPacket;
(*m_lua)["MakeSetEntityPropertyPacket"] = &Net::ExtendedProtocol::MakeSetEntityPropertyPacket;
(*m_lua)["MakeTwoWayPingPacket"] = &Net::ExtendedProtocol::MakeTwoWayPingPacket;
(*m_lua)["MakeSetInventoryOrderPacket"] = &Net::ExtendedProtocol::MakeSetInventoryOrderPacket;
(*m_lua)["MakeSetHotbarPacket"] = &Net::ExtendedProtocol::MakeSetHotbarPacket;
(*m_lua)["MakeSetSpawnpointPacket"] = &Net::ExtendedProtocol::MakeSetSpawnpointPacket;
(*m_lua)["MakeVelocityControlPacket"] = &Net::ExtendedProtocol::MakeVelocityControlPacket;
(*m_lua)["MakeDefineEffectPacket"] = &Net::ExtendedProtocol::MakeDefineEffectPacket;
(*m_lua)["MakeSpawnEffectPacket"] = &Net::ExtendedProtocol::MakeSpawnEffectPacket;
/* END AUTOGENERATED CODE SECTION */
}
void PluginHandler::LoadPlugins()
{
std::string pluginDir = "plugins";
for (auto iter = std::filesystem::recursive_directory_iterator(pluginDir);
iter != std::filesystem::recursive_directory_iterator();
++iter) {
const std::string filename = iter->path().string();
std::string pluginName = iter->path().parent_path().filename().string();
if (iter->path().filename().string() == "init.lua") {
std::shared_ptr<IPlugin> plugin = std::make_shared<LuaPlugin>(m_lua, filename, pluginName);
AddPlugin(std::move(plugin));
}
}
// FIXME: Add priorities instead?
auto iter = std::find_if(
m_plugins.begin(), m_plugins.end(),
[&](std::shared_ptr<IPlugin>& plugin)
{
return plugin->GetName() == "Core";
}
);
if (iter != m_plugins.end())
std::rotate(m_plugins.begin(), iter, iter + 1);
for (auto& plugin : m_plugins) {
std::string pluginName = plugin->GetName();
try {
plugin->Init();
LOG(LOGLEVEL_DEBUG, "Loaded plugin: %s", pluginName.c_str());
}
catch (const std::runtime_error& e) {
LOG(LOGLEVEL_WARNING, "PluginHandler error (%s): %s", pluginName.c_str(), e.what());
}
}
}
void PluginHandler::ReloadPlugins()
{
LuaPlugins::authEvent.clear();
LuaPlugins::messageEvent.clear();
LuaPlugins::joinEvent.clear();
LuaPlugins::positionOrientationEvent.clear();
LuaPlugins::setBlockEvent.clear();
LuaPlugins::disconnectEvent.clear();
LuaPlugins::playerClickedEvent.clear();
LuaPlugins::extEntryEvent.clear();
m_plugins.clear();
m_lua.reset();
InitLua();
LoadPlugins();
// Re-trigger auth/join events for all players
auto worlds = Server::GetInstance()->GetWorlds();
for (auto& world : worlds) {
auto players = world.second->GetPlayers();
for (auto& player : players) {
TriggerAuthEvent(player);
TriggerJoinEvent(player, player->GetWorld());
}
}
}
void PluginHandler::AddPlugin(std::shared_ptr<IPlugin> plugin)
{
m_plugins.push_back(std::move(plugin));
}
void PluginHandler::Update()
{
if (m_reloadPlugins) {
m_reloadPlugins = false;
ReloadPlugins();
return;
}
// TODO: update at regular intervals (tick rate)
for (auto& plugin : m_plugins) {
try {
plugin->Tick();
} catch(std::runtime_error& e) {
std::cerr << e.what() << std::endl;
}
}
}
void PluginHandler::TriggerAuthEvent(Player::PlayerPtr player)
{
try {
for (auto& func : LuaPlugins::authEvent)
func(player);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerAuthEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerMessageEvent(Player::PlayerPtr player, std::string message, uint8_t flag)
{
sol::table table = m_lua->create_table_with("message", message, "flag", flag);
try {
for (auto& func : LuaPlugins::messageEvent)
func(player, table);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerMessageEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerJoinEvent(Player::PlayerPtr player, World* world)
{
try {
for (auto& func : LuaPlugins::joinEvent)
func(player, world);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerJoinEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerPositionOrientationEvent(Player::PlayerPtr player, Utils::Vector position, uint8_t yaw, uint8_t pitch)
{
sol::table table = m_lua->create_table_with("position", position, "yaw", yaw, "pitch", pitch);
try {
for (auto& func : LuaPlugins::positionOrientationEvent)
func(player, table);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerPositionOrientationEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerSetBlockEvent(Player::PlayerPtr player, int blockType, Utils::Vector position)
{
try {
for (auto& func : LuaPlugins::setBlockEvent)
func(player, blockType, position);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerSetBlockEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerDisconnectEvent(Player::PlayerPtr player)
{
try {
for (auto& func : LuaPlugins::disconnectEvent)
func(player);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerDisconnectEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerPlayerClickedEvent(
Player::PlayerPtr player,
uint8_t button,
uint8_t action,
uint16_t yaw,
uint16_t pitch,
int8_t targetEntityID,
int16_t targetBlockX,
int16_t targetBlockY,
int16_t targetBlockZ,
uint8_t targetBlockFace
)
{
sol::table table = m_lua->create_table_with(
"button", button,
"action", action,
"yaw", yaw,
"pitch", pitch,
"targetEntityID", targetEntityID,
"targetBlockX", targetBlockX,
"targetBlockY", targetBlockY,
"targetBlockZ", targetBlockZ,
"targetBlockFace", targetBlockFace
);
try {
for (auto& func : LuaPlugins::playerClickedEvent)
func(player, table);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerPlayerClickedEvent exception: " << e.what() << std::endl;
}
}
void PluginHandler::TriggerExtEntryEvent(Player::PlayerPtr player, std::string name, uint32_t version)
{
sol::table table = m_lua->create_table_with(
"name", name,
"version", version
);
try {
for (auto& func : LuaPlugins::extEntryEvent)
func(player, table);
}
catch (std::runtime_error& e) {
std::cerr << "TriggerExtEntryEvent exception: " << e.what() << std::endl;
}
}
| 34.735294 | 156 | 0.711967 | [
"vector"
] |
e9fd3c7ea058735dec66ef5f61477168a823106b | 34,935 | cpp | C++ | src/vm/winrttypenameconverter.cpp | kouvel/coreclr | e8b17841cb5ce923aec48a1b0c12042d445d508f | [
"MIT"
] | 159 | 2020-06-17T01:01:55.000Z | 2022-03-28T10:33:37.000Z | src/vm/winrttypenameconverter.cpp | kouvel/coreclr | e8b17841cb5ce923aec48a1b0c12042d445d508f | [
"MIT"
] | 19 | 2020-06-27T01:16:35.000Z | 2022-02-06T20:33:24.000Z | src/vm/winrttypenameconverter.cpp | kouvel/coreclr | e8b17841cb5ce923aec48a1b0c12042d445d508f | [
"MIT"
] | 19 | 2020-05-21T08:18:20.000Z | 2021-06-29T01:13:13.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: WinRTTypeNameConverter.cpp
//
//
//
// ============================================================================
#include "common.h"
#ifdef FEATURE_COMINTEROP
#include "winrttypenameconverter.h"
#include "typeresolution.h"
struct RedirectedTypeNames
{
LPCSTR szClrNamespace;
LPCSTR szClrName;
WinMDAdapter::FrameworkAssemblyIndex assembly;
WinMDAdapter::WinMDTypeKind kind;
};
#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, ncontractAsmIndex, nWinRTIndex, nClrIndex, nWinMDTypeKind) \
{ szClrNS, szClrName, WinMDAdapter::FrameworkAssembly_ ## nClrAsmIdx, WinMDAdapter::WinMDTypeKind_ ## nWinMDTypeKind },
static const RedirectedTypeNames g_redirectedTypeNames[WinMDAdapter::RedirectedTypeIndex_Count] =
{
#include "winrtprojectedtypes.h"
};
#undef DEFINE_PROJECTED_TYPE
struct RedirectedTypeNamesKey
{
RedirectedTypeNamesKey(LPCSTR szNamespace, LPCSTR szName) :
m_szNamespace(szNamespace),
m_szName(szName)
{
LIMITED_METHOD_CONTRACT;
}
LPCSTR m_szNamespace;
LPCSTR m_szName;
};
class RedirectedTypeNamesTraits : public NoRemoveSHashTraits< DefaultSHashTraits<const RedirectedTypeNames *> >
{
public:
typedef RedirectedTypeNamesKey key_t;
static key_t GetKey(element_t e)
{
LIMITED_METHOD_CONTRACT;
return RedirectedTypeNamesKey(e->szClrNamespace, e->szClrName);
}
static BOOL Equals(key_t k1, key_t k2)
{
LIMITED_METHOD_CONTRACT;
return (strcmp(k1.m_szName, k2.m_szName) == 0) && (strcmp(k1.m_szNamespace, k2.m_szNamespace) == 0);
}
static count_t Hash(key_t k)
{
LIMITED_METHOD_CONTRACT;
// Only use the Name when calculating the hash value. Many redirected types share the same namespace so
// there isn't a lot of value in using the namespace when calculating the hash value.
return HashStringA(k.m_szName);
}
static const element_t Null() { LIMITED_METHOD_CONTRACT; return NULL; }
static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return e == NULL; }
};
typedef SHash< RedirectedTypeNamesTraits > RedirectedTypeNamesHashTable;
static RedirectedTypeNamesHashTable * s_pRedirectedTypeNamesHashTable = NULL;
//
// Return the redirection index and type kind if the MethodTable* is a redirected type
//
bool WinRTTypeNameConverter::ResolveRedirectedType(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex * pIndex, WinMDAdapter::WinMDTypeKind * pKind /*=NULL*/)
{
LIMITED_METHOD_CONTRACT;
WinMDAdapter::RedirectedTypeIndex index = pMT->GetClass()->GetWinRTRedirectedTypeIndex();
if (index == WinMDAdapter::RedirectedTypeIndex_Invalid)
return false;
if (pIndex != NULL)
*pIndex = index;
if (pKind != NULL)
*pKind = g_redirectedTypeNames[index].kind;
return true;
}
#ifndef DACCESS_COMPILE
class MethodTableListNode;
// Information to help in generating a runtimeclass name for a managed type
// implementing a generic WinRT interface
struct WinRTTypeNameInfo
{
MethodTableListNode* PreviouslyVisitedTypes;
CorGenericParamAttr CurrentTypeParameterVariance;
WinRTTypeNameInfo(MethodTableListNode* pPreviouslyVisitedTypes) :
PreviouslyVisitedTypes(pPreviouslyVisitedTypes),
CurrentTypeParameterVariance(gpNonVariant)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pPreviouslyVisitedTypes != nullptr);
}
};
// Helper data structure to build a stack allocated reverse linked list of MethodTables that we're examining
// while building up WinRT runtimeclass name
class MethodTableListNode
{
MethodTable* m_pMT; // Type examined while building the runtimeclass name
MethodTableListNode* m_pPrevious; // Previous node in the list
public:
MethodTableListNode(MethodTable* pMT, WinRTTypeNameInfo* pCurrent)
: m_pMT(pMT),
m_pPrevious(nullptr)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pMT != nullptr);
if (pCurrent != nullptr)
{
m_pPrevious = pCurrent->PreviouslyVisitedTypes;
}
}
bool Contains(MethodTable* pMT)
{
LIMITED_METHOD_CONTRACT;
if (pMT == m_pMT)
{
return true;
}
else if (m_pPrevious == nullptr)
{
return false;
}
else
{
return m_pPrevious->Contains(pMT);
}
}
};
//
// Append WinRT type name for the specified type handle
//
bool WinRTTypeNameConverter::AppendWinRTTypeNameForManagedType(
TypeHandle thManagedType,
SString &strWinRTTypeName,
bool bForGetRuntimeClassName,
bool *pbIsPrimitive)
{
WRAPPER_NO_CONTRACT;
return AppendWinRTTypeNameForManagedType(thManagedType, strWinRTTypeName, bForGetRuntimeClassName, pbIsPrimitive, nullptr);
}
bool WinRTTypeNameConverter::AppendWinRTTypeNameForManagedType(
TypeHandle thManagedType,
SString &strWinRTTypeName,
bool bForGetRuntimeClassName,
bool *pbIsPrimitive,
WinRTTypeNameInfo *pCurrentTypeInfo)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(!thManagedType.IsNull());
PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK));
PRECONDITION(CheckPointer(pCurrentTypeInfo, NULL_OK));
}
CONTRACTL_END;
if (pbIsPrimitive)
*pbIsPrimitive = false;
MethodTable *pMT = thManagedType.GetMethodTable();
BOOL fIsIReference = FALSE, fIsIReferenceArray = FALSE;
if (pMT->GetNumGenericArgs() == 1)
{
fIsIReference = pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEIMPL));
fIsIReferenceArray = pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEARRAYIMPL));
}
WinMDAdapter::RedirectedTypeIndex index;
if (ResolveRedirectedType(pMT, &index))
{
// Redirected types
// Use the redirected WinRT name
strWinRTTypeName.Append(WinMDAdapter::GetRedirectedTypeFullWinRTName(index));
}
else if (fIsIReference || fIsIReferenceArray)
{
//
// Convert CLRIReferenceImpl<T>/CLRIReferenceArrayImpl<T> to a WinRT Type
//
// If GetRuntimeClassName = true, return IReference<T>/IReferenceArray<T>
// Otherwise, return T/IReferenceArray`1<T>
//
Instantiation inst = pMT->GetInstantiation();
_ASSERTE(inst.GetNumArgs() == 1);
TypeHandle th = inst[0];
// I'm sure there are ways to avoid duplication here but I prefer this way - it is easier to understand
if (fIsIReference)
{
if (bForGetRuntimeClassName)
{
//
// IReference<T>
//
strWinRTTypeName.Append(W("Windows.Foundation.IReference`1<"));
if (!AppendWinRTTypeNameForManagedType(
th,
strWinRTTypeName,
bForGetRuntimeClassName,
NULL
))
return false;
strWinRTTypeName.Append(W('>'));
return true;
}
else
{
//
// T
//
return AppendWinRTTypeNameForManagedType(
th,
strWinRTTypeName,
bForGetRuntimeClassName,
pbIsPrimitive
);
}
}
else
{
//
// IReferenceArray<T>
//
strWinRTTypeName.Append(W("Windows.Foundation.IReferenceArray`1<"));
if (!AppendWinRTTypeNameForManagedType(
th,
strWinRTTypeName,
bForGetRuntimeClassName,
NULL))
return false;
strWinRTTypeName.Append(W('>'));
return true;
}
}
else if (pMT->IsProjectedFromWinRT() || pMT->IsExportedToWinRT())
{
//
// WinRT type
//
SString strTypeName;
pMT->_GetFullyQualifiedNameForClassNestedAware(strTypeName);
strWinRTTypeName.Append(strTypeName);
}
else if (AppendWinRTNameForPrimitiveType(pMT, strWinRTTypeName))
{
//
// WinRT primitive type, return immediately
//
if (pbIsPrimitive)
*pbIsPrimitive = true;
return true;
}
else if (pMT->IsArray())
{
if (bForGetRuntimeClassName)
{
//
// An array is not a valid WinRT type - it must be wrapped in IReferenceArray to be a valid
// WinRT type
//
return false;
}
else
{
//
// System.Type marshaling - convert array type into IReferenceArray<T>
//
strWinRTTypeName.Append(W("Windows.Foundation.IReferenceArray`1<"));
if (!AppendWinRTTypeNameForManagedType(thManagedType.AsArray()->GetArrayElementTypeHandle(), strWinRTTypeName, bForGetRuntimeClassName, NULL))
return false;
strWinRTTypeName.Append(W('>'));
}
}
else if (bForGetRuntimeClassName)
{
//
// Not a WinRT type or a WinRT Primitive type,
// but if it implements a WinRT interface we will return the interface name.
// Which interface should we return if it implements multiple WinRT interfaces?
// For now we return the top most interface. And if there are more than one
// top most interfaces, we return the first one we encounter during the interface enumeration.
//
//
// We also need to keep track of the types we've already considered, so we don't wind up in an
// infinite recursion processing generic interfaces.
// For example, in the case where we have:
//
// class ManagedType : IEnumerable<ManagedType>
//
// We do not want to keep recursing on the ManagedType type parameter. Instead, we should
// discover that we've already attempted to figure out what the best representation for
// ManagedType is, and bail out.
//
// This is a linear search, however that shouldn't generally be a problem, since generic
// nesting should not be very large in the common case.
if (pCurrentTypeInfo != nullptr && pCurrentTypeInfo->PreviouslyVisitedTypes->Contains(pMT))
{
// We should only be restricting this recursion on non-WinRT types that may have WinRT interfaces
_ASSERTE(!pMT->IsProjectedFromWinRT() && !pMT->IsExportedToWinRT() && !pMT->IsTruePrimitive());
// We have two choices. If this is a reference type and the interface parameter is covariant, we
// can use IInspectable as the closure. Otherwise, we need to simply fail out with no possible
// type name.
if (pCurrentTypeInfo->CurrentTypeParameterVariance == gpCovariant &&
thManagedType.IsBoxedAndCanCastTo(TypeHandle(g_pObjectClass), nullptr))
{
// Object is used in runtime class names for generics closed over IInspectable at the ABI
strWinRTTypeName.Append(W("Object"));
return true;
}
else
{
return false;
}
}
// This is the "top" most redirected interface implemented by pMT.
// E.g. if pMT implements both IList`1 and IEnumerable`1, we pick IList`1.
MethodTable* pTopIfaceMT = NULL;
WinMDAdapter::RedirectedTypeIndex idxTopIface = (WinMDAdapter::RedirectedTypeIndex)-1;
MethodTable::InterfaceMapIterator it = pMT->IterateInterfaceMap();
while (it.Next())
{
MethodTable* pIfaceMT = it.GetInterface();
if (ResolveRedirectedType(pIfaceMT, &index) ||
pIfaceMT->IsProjectedFromWinRT())
{
if (pTopIfaceMT == NULL || pIfaceMT->ImplementsInterface(pTopIfaceMT))
{
pTopIfaceMT = pIfaceMT;
// If pIfaceMT is not a redirected type, idxTopIface will contain garbage.
// But that is fine because we will only use idxTopIface if pTopIfaceMT
// is a redirected type.
idxTopIface = index;
}
}
}
if (pTopIfaceMT != NULL)
{
if (pTopIfaceMT->IsProjectedFromWinRT())
{
// Mscorlib contains copies of WinRT interfaces - don't return their names,
// instead return names of the corresponding interfaces in Windows.Foundation.winmd.
if (pTopIfaceMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IKEYVALUEPAIR)))
strWinRTTypeName.Append(W("Windows.Foundation.Collections.IKeyValuePair`2"));
else if (pTopIfaceMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IITERATOR)))
strWinRTTypeName.Append(W("Windows.Foundation.Collections.IIterator`1"));
else if (pTopIfaceMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IPROPERTYVALUE)))
strWinRTTypeName.Append(W("Windows.Foundation.IPropertyValue"));
else
{
SString strTypeName;
pTopIfaceMT->_GetFullyQualifiedNameForClassNestedAware(strTypeName);
strWinRTTypeName.Append(strTypeName);
}
}
else
strWinRTTypeName.Append(WinMDAdapter::GetRedirectedTypeFullWinRTName(idxTopIface));
// Since we are returning the typeName for the pTopIfaceMT we should use the same interfaceType
// to check for instantiation and creating the closed generic.
pMT = pTopIfaceMT;
}
else
return false;
}
else
{
//
// Non-WinRT type, Non-WinRT-Primitive type
//
return false;
}
// We allow typeName generation for only open types or completely instantiated types.
// In case it is a generic type definition like IList<T> we return the typeName as IVector'1 only
// and hence we do not need to visit the arguments.
if (pMT->HasInstantiation() && (!pMT->IsGenericTypeDefinition()))
{
// Add the current type we're trying to get a runtimeclass name for to the list of types
// we've already seen, so we can check for infinite recursion on the generic parameters.
MethodTableListNode examinedTypeList(thManagedType.GetMethodTable(), pCurrentTypeInfo);
strWinRTTypeName.Append(W('<'));
//
// Convert each arguments
//
Instantiation inst = pMT->GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); ++i)
{
TypeHandle th = inst[i];
// We have a partial open type with us and hence we should throw.
if(th.ContainsGenericVariables())
COMPlusThrowArgumentException(W("th"), W("Argument_TypeNotValid"));
if (i > 0)
strWinRTTypeName.Append(W(','));
// In the recursive case, we can sometimes do a better job of getting a runtimeclass name if
// the actual instantiated type can be substitued for a different type due to variance on the
// generic type parameter. In order to allow that to occur when processing this parameter,
// make a note of the variance properties to pass along with the previously examined type list
WinRTTypeNameInfo currentParameterInfo(&examinedTypeList);
if (pMT->HasVariance())
{
currentParameterInfo.CurrentTypeParameterVariance = pMT->GetClass()->GetVarianceOfTypeParameter(i);
}
// Convert to WinRT type name
// If it is not a WinRT type, return immediately
if (!AppendWinRTTypeNameForManagedType(th, strWinRTTypeName, bForGetRuntimeClassName, NULL, ¤tParameterInfo))
return false;
}
strWinRTTypeName.Append(W('>'));
}
return true;
}
//
// Lookup table : CorElementType -> WinRT primitive type name
//
LPCWSTR const s_wszCorElementTypeToWinRTNameMapping[] =
{
NULL, // ELEMENT_TYPE_END = 0x0,
NULL, // ELEMENT_TYPE_VOID = 0x1,
W("Boolean"), // ELEMENT_TYPE_BOOLEAN = 0x2,
W("Char16"), // ELEMENT_TYPE_CHAR = 0x3,
NULL, // ELEMENT_TYPE_I1 = 0x4,
W("UInt8"), // ELEMENT_TYPE_U1 = 0x5,
W("Int16"), // ELEMENT_TYPE_I2 = 0x6,
W("UInt16"), // ELEMENT_TYPE_U2 = 0x7,
W("Int32"), // ELEMENT_TYPE_I4 = 0x8,
W("UInt32"), // ELEMENT_TYPE_U4 = 0x9,
W("Int64"), // ELEMENT_TYPE_I8 = 0xa,
W("UInt64"), // ELEMENT_TYPE_U8 = 0xb,
W("Single"), // ELEMENT_TYPE_R4 = 0xc,
W("Double"), // ELEMENT_TYPE_R8 = 0xd,
W("String"), // ELEMENT_TYPE_STRING = 0xe,
NULL, // ELEMENT_TYPE_PTR = 0xf,
NULL, // ELEMENT_TYPE_BYREF = 0x10,
NULL, // ELEMENT_TYPE_VALUETYPE = 0x11,
NULL, // ELEMENT_TYPE_CLASS = 0x12,
NULL, // ??? = 0x13,
NULL, // ELEMENT_TYPE_ARRAY = 0x14,
NULL, // ??? = 0x15,
NULL, // ELEMENT_TYPE_TYPEDBYREF = 0x16,
NULL, // ELEMENT_TYPE_I = 0x18,
NULL, // ELEMENT_TYPE_U = 0x19,
NULL, // ??? = 0x1A,
NULL, // ELEMENT_TYPE_FNPTR = 0x1B,
W("Object"), // ELEMENT_TYPE_OBJECT = 0x1C,
};
//
// Get predefined WinRT name for a primitive type
//
bool WinRTTypeNameConverter::GetWinRTNameForPrimitiveType(MethodTable *pMT, SString *pName)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pMT, NULL_OK));
}
CONTRACTL_END;
CorElementType elemType = TypeHandle(pMT).GetSignatureCorElementType();
//
// Try to find it in a lookup table
//
if (elemType >= 0 && elemType < _countof(s_wszCorElementTypeToWinRTNameMapping))
{
LPCWSTR wszName = s_wszCorElementTypeToWinRTNameMapping[elemType];
if (wszName != NULL)
{
if (pName != NULL)
{
pName->SetLiteral(wszName);
}
return true;
}
}
if (elemType == ELEMENT_TYPE_VALUETYPE)
{
if (pMT->GetModule()->IsSystem() &&
IsTypeRefOrDef(g_GuidClassName, pMT->GetModule(), pMT->GetCl()))
{
if (pName != NULL)
{
pName->SetLiteral(W("Guid"));
}
return true;
}
}
else if (elemType == ELEMENT_TYPE_CLASS)
{
if (pMT == g_pObjectClass)
{
if (pName != NULL)
{
pName->SetLiteral(W("Object"));
}
return true;
}
if (pMT == g_pStringClass)
{
if (pName != NULL)
{
pName->SetLiteral(W("String"));
}
return true;
}
}
// it's not a primitive
return false;
}
//
// Append the WinRT type name for the method table, if it is a WinRT primitive type
//
bool WinRTTypeNameConverter::AppendWinRTNameForPrimitiveType(MethodTable *pMT, SString &strName)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pMT, NULL_OK));
}
CONTRACTL_END;
SString strPrimitiveTypeName;
if (GetWinRTNameForPrimitiveType(pMT, &strPrimitiveTypeName))
{
strName.Append(strPrimitiveTypeName);
return true;
}
return false;
}
// static
bool WinRTTypeNameConverter::IsRedirectedType(MethodTable *pMT, WinMDAdapter::WinMDTypeKind kind)
{
LIMITED_METHOD_CONTRACT;
WinMDAdapter::RedirectedTypeIndex index;
return (ResolveRedirectedType(pMT, &index) && (g_redirectedTypeNames[index].kind == kind));
}
//
// Determine if the given type redirected only by doing name comparisons. This is used to
// calculate the redirected type index at EEClass creation time.
//
// static
WinMDAdapter::RedirectedTypeIndex WinRTTypeNameConverter::GetRedirectedTypeIndexByName(
Module *pModule,
mdTypeDef token)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pModule));
}
CONTRACTL_END;
// If the redirected type hashtable has not been initialized initialize it
if (s_pRedirectedTypeNamesHashTable == NULL)
{
NewHolder<RedirectedTypeNamesHashTable> pRedirectedTypeNamesHashTable = new RedirectedTypeNamesHashTable();
pRedirectedTypeNamesHashTable->Reallocate(2 * COUNTOF(g_redirectedTypeNames));
for (int i = 0; i < COUNTOF(g_redirectedTypeNames); ++i)
{
pRedirectedTypeNamesHashTable->Add(&(g_redirectedTypeNames[i]));
}
if (InterlockedCompareExchangeT(&s_pRedirectedTypeNamesHashTable, pRedirectedTypeNamesHashTable.GetValue(), NULL) == NULL)
{
pRedirectedTypeNamesHashTable.SuppressRelease();
}
}
IMDInternalImport *pInternalImport = pModule->GetMDImport();
LPCSTR szName;
LPCSTR szNamespace;
IfFailThrow(pInternalImport->GetNameOfTypeDef(token, &szName, &szNamespace));
const RedirectedTypeNames *const * ppRedirectedNames = s_pRedirectedTypeNamesHashTable->LookupPtr(RedirectedTypeNamesKey(szNamespace, szName));
if (ppRedirectedNames == NULL)
{
return WinMDAdapter::RedirectedTypeIndex_Invalid;
}
UINT redirectedTypeIndex = (UINT)(*ppRedirectedNames - g_redirectedTypeNames);
_ASSERTE(redirectedTypeIndex < COUNTOF(g_redirectedTypeNames));
// If the redirected assembly is mscorlib just compare it directly. This is necessary because
// WinMDAdapter::GetExtraAssemblyRefProps does not support mscorlib
if (g_redirectedTypeNames[redirectedTypeIndex].assembly == WinMDAdapter::FrameworkAssembly_Mscorlib)
{
return MscorlibBinder::GetModule()->GetAssembly() == pModule->GetAssembly() ?
(WinMDAdapter::RedirectedTypeIndex)redirectedTypeIndex :
WinMDAdapter::RedirectedTypeIndex_Invalid;
}
LPCSTR pSimpleName;
AssemblyMetaDataInternal context;
const BYTE * pbKeyToken;
DWORD cbKeyTokenLength;
DWORD dwFlags;
WinMDAdapter::GetExtraAssemblyRefProps(
g_redirectedTypeNames[redirectedTypeIndex].assembly,
&pSimpleName,
&context,
&pbKeyToken,
&cbKeyTokenLength,
&dwFlags);
AssemblySpec spec;
IfFailThrow(spec.Init(
pSimpleName,
&context,
pbKeyToken,
cbKeyTokenLength,
dwFlags));
Assembly* pRedirectedAssembly = spec.LoadAssembly(
FILE_LOADED,
FALSE); // fThrowOnFileNotFound
if (pRedirectedAssembly == NULL)
{
return WinMDAdapter::RedirectedTypeIndex_Invalid;
}
// Resolve the name in the redirected assembly to the actual type def and assembly
NameHandle nameHandle(szNamespace, szName);
nameHandle.SetTokenNotToLoad(tdAllTypes);
Module * pTypeDefModule;
mdTypeDef typeDefToken;
if (ClassLoader::ResolveNameToTypeDefThrowing(
pRedirectedAssembly->GetManifestModule(),
&nameHandle,
&pTypeDefModule,
&typeDefToken,
Loader::DontLoad))
{
// Finally check if the assembly from this type def token mathes the assembly type forwareded from the
// redirected assembly
if (pTypeDefModule->GetAssembly() == pModule->GetAssembly())
{
return (WinMDAdapter::RedirectedTypeIndex)redirectedTypeIndex;
}
}
return WinMDAdapter::RedirectedTypeIndex_Invalid;
}
struct WinRTPrimitiveTypeMapping
{
BinderClassID binderID;
LPCWSTR wszWinRTName;
};
#define DEFINE_PRIMITIVE_TYPE_MAPPING(elementType, winrtTypeName) { elementType, L##winrtTypeName },
//
// Pre-sorted mapping : WinRT primitive type string -> BinderClassID
//
const WinRTPrimitiveTypeMapping s_winRTPrimitiveTypeMapping[] =
{
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__BOOLEAN, "Boolean")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__CHAR, "Char16")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__DOUBLE, "Double")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__GUID, "Guid")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__INT16, "Int16")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__INT32, "Int32")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__INT64, "Int64")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__OBJECT, "Object")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__SINGLE, "Single")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__STRING, "String")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__UINT16, "UInt16")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__UINT32, "UInt32")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__UINT64, "UInt64")
DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__BYTE, "UInt8")
};
//
// Return MethodTable* for the specified WinRT primitive type name
//
bool WinRTTypeNameConverter::GetMethodTableFromWinRTPrimitiveType(LPCWSTR wszTypeName, UINT32 uTypeNameLen, MethodTable **ppMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(ppMT));
}
CONTRACTL_END;
if (uTypeNameLen >= 4 && uTypeNameLen <= 7)
{
//
// Binary search the lookup table
//
int begin = 0, end = _countof(s_winRTPrimitiveTypeMapping) - 1;
while (begin <= end)
{
_ASSERTE(begin >= 0 && begin <= _countof(s_winRTPrimitiveTypeMapping) - 1);
_ASSERTE(end >= 0 && end <= _countof(s_winRTPrimitiveTypeMapping) - 1);
int mid = (begin + end) / 2;
int ret = wcscmp(wszTypeName, s_winRTPrimitiveTypeMapping[mid].wszWinRTName);
if (ret == 0)
{
*ppMT = MscorlibBinder::GetClass(s_winRTPrimitiveTypeMapping[mid].binderID);
return true;
}
else if (ret > 0)
{
begin = mid + 1;
}
else
{
end = mid - 1;
}
}
}
// it's not a primitive
return false;
}
// Is the specified MethodTable a redirected WinRT type?
bool WinRTTypeNameConverter::IsRedirectedWinRTSourceType(MethodTable *pMT)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (!pMT->IsProjectedFromWinRT())
return false;
// redirected types are hidden (made internal) by the adapter
if (IsTdPublic(pMT->GetClass()->GetProtection()))
return false;
DefineFullyQualifiedNameForClassW();
LPCWSTR pszName = GetFullyQualifiedNameForClassW_WinRT(pMT);
return !!WinMDAdapter::ConvertWellKnownFullTypeNameFromWinRTToClr(&pszName, NULL);
}
//
// Get TypeHandle from a WinRT type name
// Parse the WinRT type name in the form of WinRTType=TypeName[<WinRTType[, WinRTType, ...]>]
//
TypeHandle WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeName(LPCWSTR wszWinRTTypeName, ICLRPrivBinder * loadBinder, bool *pbIsPrimitive)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(wszWinRTTypeName));
PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK));
}
CONTRACTL_END;
SString ssTypeName(SString::Literal, wszWinRTTypeName);
TypeHandle th = LoadManagedTypeForWinRTTypeNameInternal(&ssTypeName, loadBinder, pbIsPrimitive);
if (th.IsNull())
{
COMPlusThrowArgumentException(W("typeName"), NULL);
}
return th;
}
// Helper used by code:GetWinRTType to compose a generic type from an array of components.
// For example [IDictionary`2, int, IList`1, string] yields IDictionary`2<int, IList`1<string>>.
static TypeHandle ComposeTypeRecursively(CQuickArray<TypeHandle> &rqPartTypes, DWORD *pIndex)
{
CONTRACTL
{
MODE_ANY;
THROWS;
GC_TRIGGERS;
PRECONDITION(*pIndex < rqPartTypes.Size());
}
CONTRACTL_END;
DWORD index = (*pIndex)++;
TypeHandle th = rqPartTypes[index];
if (th.HasInstantiation())
{
DWORD dwArgCount = th.GetNumGenericArgs();
for (DWORD i = 0; i < dwArgCount; i++)
{
// we scan rqPartTypes linearly so we know that the elements can be reused
rqPartTypes[i + index] = ComposeTypeRecursively(rqPartTypes, pIndex);
}
Instantiation inst(rqPartTypes.Ptr() + index, dwArgCount);
th = th.Instantiate(inst);
}
else if (th == g_pArrayClass)
{
// Support for arrays
rqPartTypes[index] = ComposeTypeRecursively(rqPartTypes, pIndex);
th = ClassLoader::LoadArrayTypeThrowing(rqPartTypes[index], ELEMENT_TYPE_SZARRAY, 1);
}
return th;
}
#ifdef CROSSGEN_COMPILE
//
// In crossgen, we use a mockup of RoParseTypeName since we need to run on pre-Win8 machines.
//
extern "C" HRESULT WINAPI CrossgenRoParseTypeName(SString* typeName, DWORD *partsCount, SString **typeNameParts);
#endif
//
// Return TypeHandle for the specified WinRT type name (supports generic type)
// Updates wszWinRTTypeName pointer as it parse the string
//
TypeHandle WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeNameInternal(SString *ssTypeName, ICLRPrivBinder* loadBinder, bool *pbIsPrimitive)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(ssTypeName));
PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK));
}
CONTRACTL_END;
if (pbIsPrimitive)
*pbIsPrimitive = false;
if (ssTypeName->IsEmpty())
return TypeHandle();
TypeHandle typeHandle;
SString::Iterator it = ssTypeName->Begin();
if (ssTypeName->Find(it, W('<')))
{
// this is a generic type - use RoParseTypeName to break it down into components
CQuickArray<TypeHandle> rqPartTypes;
#ifndef CROSSGEN_COMPILE
DWORD dwPartsCount = 0;
HSTRING *rhsPartNames;
CoTaskMemHSTRINGArrayHolder hsNamePartsHolder;
IfFailThrow(RoParseTypeName(WinRtStringRef(ssTypeName->GetUnicode(), ssTypeName->GetCount()), &dwPartsCount, &rhsPartNames));
hsNamePartsHolder.Init(rhsPartNames, dwPartsCount);
rqPartTypes.AllocThrows(dwPartsCount);
// load the components
for (DWORD i = 0; i < dwPartsCount; i++)
{
UINT32 cchPartLength;
PCWSTR wszPart = WindowsGetStringRawBuffer(rhsPartNames[i], &cchPartLength);
StackSString ssPartName(wszPart, cchPartLength);
rqPartTypes[i] = GetManagedTypeFromSimpleWinRTNameInternal(&ssPartName, loadBinder, nullptr);
}
#else //CROSSGEN_COMPILE
//
// In crossgen, we use a mockup of RoParseTypeName since we need to run on pre-Win8 machines.
//
DWORD dwPartsCount = 0;
SString *rhsPartNames;
IfFailThrow(CrossgenRoParseTypeName(ssTypeName, &dwPartsCount, &rhsPartNames));
_ASSERTE(rhsPartNames != nullptr);
rqPartTypes.AllocThrows(dwPartsCount);
// load the components
for (DWORD i = 0; i < dwPartsCount; i++)
{
rqPartTypes[i] = GetManagedTypeFromSimpleWinRTNameInternal(&rhsPartNames[i], loadBinder, NULL);
}
delete[] rhsPartNames;
#endif //CROSSGEN_COMPILE
// and instantiate the generic type
DWORD dwIndex = 0;
typeHandle = ComposeTypeRecursively(rqPartTypes, &dwIndex);
_ASSERTE(dwIndex == rqPartTypes.Size());
return typeHandle;
}
else
{
return GetManagedTypeFromSimpleWinRTNameInternal(ssTypeName, loadBinder, pbIsPrimitive);
}
}
//
// Return MethodTable* for the specified WinRT primitive type name (non-generic type)
// Updates wszWinRTTypeName pointer as it parse the string
//
TypeHandle WinRTTypeNameConverter::GetManagedTypeFromSimpleWinRTNameInternal(SString *ssTypeName, ICLRPrivBinder* loadBinder, bool *pbIsPrimitive)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(ssTypeName));
PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK));
}
CONTRACTL_END;
if (pbIsPrimitive)
*pbIsPrimitive = false;
if (ssTypeName->IsEmpty())
return TypeHandle();
//
// Redirection
//
LPCWSTR pwszTypeName = ssTypeName->GetUnicode();
WinMDAdapter::RedirectedTypeIndex uIndex;
MethodTable *pMT = NULL;
if (WinMDAdapter::ConvertWellKnownFullTypeNameFromWinRTToClr(&pwszTypeName, &uIndex))
{
//
// Well known redirected types
//
return TypeHandle(GetAppDomain()->GetRedirectedType(uIndex));
}
else if (GetMethodTableFromWinRTPrimitiveType(pwszTypeName, ssTypeName->GetCount(), &pMT))
{
//
// Primitive type
//
if (pbIsPrimitive)
*pbIsPrimitive = true;
return TypeHandle(pMT);
}
else if (wcscmp(pwszTypeName, W("Windows.Foundation.IReferenceArray`1")) == 0)
{
//
// Handle array case - return the array and we'll create the array later
//
return TypeHandle(g_pArrayClass);
}
else
{
//
// A regular WinRT type
//
return LoadWinRTType(ssTypeName, TRUE, loadBinder);
}
}
#endif // !DACCESS_COMPILE
#endif // FEATURE_COMINTEROP
| 33.239772 | 159 | 0.618148 | [
"object"
] |
e9ff4d50e41f3eea2fc784e44f36507afb6e4ac6 | 2,897 | cpp | C++ | Codeforces/Codeforces Round 662/C.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | 1 | 2021-03-05T14:16:46.000Z | 2021-03-05T14:16:46.000Z | Codeforces/Codeforces Round 662/C.cpp | K-ona/CPP-Training | aa312970505f67c270257c8a5816e89c10f2d1ce | [
"Apache-2.0"
] | null | null | null | Codeforces/Codeforces Round 662/C.cpp | K-ona/CPP-Training | aa312970505f67c270257c8a5816e89c10f2d1ce | [
"Apache-2.0"
] | null | null | null | // This code is written by Karry5307
#include<bits/stdc++.h>
// copied by Kona@vscode
// Definition
#define For(i,x,y) for(register int i=(x);i<(y);i++)
#define Forr(i,x,y) for(register int i=(x);i<=(y);i++)
#define Rep(i,x,y) for(register int i=(x);i>(y);i--)
#define Repp(i,x,y) for(register int i=(x);i>=(y);i--)
#define ve vector
#define iter iterator
#define pb emplace_back
#define popb pop_back
#define all(x) x.begin(),x.end()
#define sz(x) (int)(x.size())
#define F first
#define S second
using namespace std;
// Typedefs
typedef int ll;
typedef long long int li;
typedef unsigned int ul;
typedef unsigned long long int ull;
typedef double db;
typedef long double ldb;
typedef pair<ll,ll> pii;
typedef pair<li,li> pll;
const ll MAXN=4e5+51,MOD=998244353,inf=0x3f3f3f3f;
// Structures and variables
ll test,n,mx,l,r,mid,res;
ll x[MAXN],barrel[MAXN];
// Fast IO
inline ll read()
{
register ll num=0,neg=1;
register char ch=getchar();
while(!isdigit(ch)&&ch!='-') ch=getchar();
if(ch=='-') neg=-1,ch=getchar();
while(isdigit(ch)) num=(num<<3)+(num<<1)+(ch-'0'),ch=getchar();
return neg==1?num:-num;
}
inline li readu()
{
register li num=0;
register char ch=getchar();
while(!isdigit(ch)) ch=getchar();
while(isdigit(ch)) num=(num<<3)+(num<<1)+(ch-'0'),ch=getchar();
return num;
}
template<class T>
inline void writep(T x)
{
if(x<0){return (void)putchar('-'),writep(-x);}
if(x<10){return (void)putchar(x|48);}
writep(x/10),putchar((x%10)|48);
}
template<class T>
inline void write(T x,char ch=' '){writep(x),putchar(ch);}
template<class T>
inline void writeln(T x){writep(x),putchar('\n');}
// chkmin and chkmax
template<class T>
inline void chkmax(T &x,const T &y){x=x>y?x:y;}
template<class T>
inline void chkmin(T &x,const T &y){x=x<y?x:y;}
// Functions
template<class T,class Compare>
inline void sort(ve<T>&v,Compare cmp=less<T>()){sort(all(v),cmp);}
template<class T>
inline void reverse(ve<T>&v){reverse(all(v));}
template<class T>
inline void clear(T *arr){memset(arr,0,sizeof(arr));}
template<class T>
inline void setInf(T *arr){memset(arr,0x3f,sizeof(arr));}
// Math funcs
inline ll qpow(ll base,ll exponent)
{
li res=1;
while(exponent)
{
if(exponent&1)
{
res=(li)res*base%MOD;
}
base=(li)base*base%MOD,exponent>>=1;
}
return res;
}
inline ll gcd(ll x,ll y)
{
return !y?x:gcd(y,x%y);
}
inline li lcm(ll x,ll y)
{
return x/gcd(x,y)*y;
}
// Functions
inline bool check(ll mid)
{
ll gx=(n-1)/mid+1,gy=(n-1)%mid+1;
return mx<=gx&&barrel[gx]<=gy&&barrel[gx-1]<=mid;
}
inline void solve()
{
l=1,r=n=read(),res=mx=0;
for(register int i=1;i<=n;i++)
{
x[i]=barrel[i]=0;
}
for(register int i=1;i<=n;i++)
{
mx=max(mx,++x[read()]);
}
for(register int i=1;i<=n;i++)
{
res+=(x[i]==mx);
}
printf("%d\n",(n-mx*res)/(mx-1)+res-1);
}
int main()
{
test=read();
for(register int i=0;i<test;i++)
{
solve();
}
} | 22.992063 | 67 | 0.638937 | [
"vector"
] |
1801a71e61f26ef9f22f237a93168c249928240a | 10,508 | cpp | C++ | src/core/Context.cpp | KeinR/Nafy | b576a08b028cff00a7cb02331699dc8b2fecf3bf | [
"MIT"
] | null | null | null | src/core/Context.cpp | KeinR/Nafy | b576a08b028cff00a7cb02331699dc8b2fecf3bf | [
"MIT"
] | null | null | null | src/core/Context.cpp | KeinR/Nafy | b576a08b028cff00a7cb02331699dc8b2fecf3bf | [
"MIT"
] | null | null | null | #include "Context.h"
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#include <memory>
#include <cmath> // DEBUG
#include "../shaders/ShaderFactory.h"
#include "error.h"
#include "../env/env.h"
#include "../text/ftype.h"
#include "../text/Font.h"
#include "../text/Text.h"
#include "../gui/Image.h"
#include "../audio/Device.h"
#include "../audio/AudioContext.h"
#include "../audio/SoundData.h"
#include "../audio/SoundBuffer.h"
#include "../audio/Speaker.h"
void nafy::Context::makeCurrent() {
glfwMakeContextCurrent(window);
setContext(this);
}
nafy::Context::Context(int winWidth, int winHeight, const char *winTitle):
window(plusContext(winWidth, winHeight, winTitle)),
defaultShaders{
ShaderFactory("resources/shaders/sprite.vert", "resources/shaders/sprite.frag").make(
Shader::uni::sampler0 | Shader::uni::model
),
ShaderFactory("resources/shaders/prim.vert", "resources/shaders/prim.frag").make(
Shader::uni::color | Shader::uni::model
)
},
defaultFont(makeFont(FontFactory(getPath("resources/fonts/Arial.ttf")))),
root(nullptr), current(nullptr), run(false), runGameAction(false), userAdvance(false), vsync(0)
{
makeCurrent();
setFPS(60);
dispatch.setAsRoot(window);
views.reset(new views_s());
// Shortcuts, serve no other purpose
views_s::home_s &home = views->home;
views_s::game_s &game = views->game;
views_s::menu_s &menu = views->menu;
// Init home screen
home.background.setHex(0x2f67f5);
// The title, centered at the top
home.title.setString("NAFY");
home.title.setY(10);
home.title.setAlign(Font::textAlign::center);
home.title.generate();
home.title.setX((winWidth - home.title.getWidth()) / 2);
// Button that starts the game
home.startGame.setY(50);
home.startGame.getColor().setHex(0x1a5d6e);
home.startGame.getText().setAlign(Font::textAlign::center);
home.startGame.getText().setString("Start game!");
home.startGame.setWidth(100);
home.startGame.setX((winWidth - home.startGame.getWidth()) / 2);
home.startGame.setOnClick([this](Button *caller, int button, int mods) -> void {
// Change view to game view
this->setDispatch(this->getViewsRef().game.dispatch);
this->setBackground(this->getViewsRef().game.background);
// Disable button so that it can't be pressed despite being invisable
this->setGameRunning(true);
// set cursor to normal (TODO: This is a bad way of doing this!)
releaseCursor();
});
home.startGame.setOnEnter([](Button *caller) -> void {
setCursorHand();
caller->getColor().setHex(0x3e7887);
});
home.startGame.setOnLeave([](Button *caller) -> void {
releaseCursor();
caller->getColor().setHex(0x1a5d6e);
});
home.startGame.setCornerRadius(10);
home.startGame.generate();
home.startGame.setDispatch(home.dispatch);
home.startGame.setEnabled(true);
home.dispatch.addRenderCallback(home.title);
home.dispatch.addRenderCallback(home.startGame);
// Setup game screen
game.background.setHex(0x00c465);
// The text box with the crawling text, the main focus of any visual novel
game.crawl.setX(10);
game.crawl.setY(winHeight - 60);
game.crawl.setHeight(50);
game.crawl.setWidth(winWidth - 10 * 2);
game.crawl.getColor().setHex(0x7d7fff);
game.crawl.setMargin(5);
// Top-left corner is pointy because we have the "speaker box" on top of it
game.crawl.setCornerRadius(0, 0);
game.crawl.setCornerRadius(1, 7);
game.crawl.setCornerRadius(2, 7);
game.crawl.setCornerRadius(3, 7);
// We're actually using a button so that we can get user input,
// and the default button text align is center
game.crawl.getText().setAlign(Font::textAlign::left);
game.crawl.setOnRelease([this](CrawlButton *caller, int button, int mods) -> void {
if (button == GLFW_MOUSE_BUTTON_LEFT) {
this->setUserAdvance(true);
}
});
game.crawl.generate();
// The aforementioned "speaker box", displays the name of
// whoever's currently speaking
game.speaker.setX(10); // Aligned with the crawl box
game.speaker.setY(winHeight - 75);
game.speaker.setHeight(15);
game.speaker.setWidth(80);
game.speaker.getBox().getColor().setHex(0xa6a7ff);
game.speaker.setMargin(2);
// Smaller font size so that it doesn't stand out as much
game.speaker.getText().setFontSize(12);
// Default align for TextRec is left
game.speaker.getText().setAlign(Font::textAlign::center);
game.speaker.generate();
game.crawl.setDispatch(game.dispatch);
game.dispatch.addRenderCallback(game.crawl);
game.dispatch.addRenderCallback(game.speaker);
// Init the "dropdown" menu, this is shown when the user presses escape.
// It acts as a nexus of sorts that allows the user to go to the main menu,
// return to game, save, load, quit, etc.
// TODO: Finish this
menu.bg.getColor().setVal(0, 0, 0, 0.5);
menu.topTitle.setString("PAUSED");
menu.topTitle.generate();
menu.topTitle.setX((winWidth - menu.topTitle.getWidth()) / 2);
menu.topTitle.setY(20);
#define MARGIN 6
menu.resumeGame.getText().setString("Resume");
menu.resumeGame.getText().generate();
menu.resumeGame.setX((winWidth - menu.resumeGame.getText().getWidth() - MARGIN) / 2);
menu.resumeGame.setY(50);
menu.resumeGame.setMargin(MARGIN);
menu.toMenu.getText().setString("Main menu");
menu.toMenu.getText().generate();
menu.toMenu.setX((winWidth - menu.toMenu.getText().getWidth() - MARGIN) / 2);
menu.toMenu.setY(70);
menu.toMenu.setMargin(MARGIN);
#undef MARGIN
menu.resumeGame.setDispatch(menu.dispatch);
menu.toMenu.setDispatch(menu.dispatch);
menu.dispatch.addRenderCallback(menu.topTitle);
menu.dispatch.addRenderCallback(menu.resumeGame);
menu.dispatch.addRenderCallback(menu.toMenu);
// Start off at home
setBackground(home.background);
setDispatch(home.dispatch);
}
nafy::Context::~Context() {
minusContext(window);
}
void nafy::Context::runFrame() {
if (runGameAction) {
current->run(this);
}
}
nafy::EventDispatch &nafy::Context::getDispatch() {
return dispatch;
}
void nafy::Context::activate() {
// I mean, it's good to have control over what happens when the user calls it...
makeCurrent();
}
void nafy::Context::setRoot(Scene &root) {
this->root = &root;
}
void nafy::Context::setCurrent(Scene ¤t) {
this->current = ¤t;
// init must always be called before run
this->current->init(this);
}
void nafy::Context::revert() {
setCurrent(*root);
}
void nafy::Context::start() {
revert();
resume();
}
void nafy::Context::resume() {
if (current == nullptr) {
throw error("`current` must NOT be nullptr. Did you forget to call setRoot(Scene&)?");
}
run = true;
makeCurrent();
while (!shouldStop()) {
const float end = glfwGetTime() + frameCooldown;
glClearColor(
background->get()[0],
background->get()[1],
background->get()[2],
background->get()[3]
);
glClear(GL_COLOR_BUFFER_BIT);
dispatch.render();
glfwSwapBuffers(window);
runFrame();
// Check for errors, and throw an exception if there is one.
// TODO: Add error hooks so that every error doesn't cause a crash
GLenum glerror = glGetError();
if (glerror != GL_NO_ERROR) {
throw gl_error(glerror);
}
ALenum alerror = alGetError();
if (alerror != AL_NO_ERROR) {
throw al_error(alerror);
}
do {
// Minimal input lag -dabs-
glfwPollEvents();
// So that it isn's a total resource hog while waiting.
// For some reason, this works... At least on my machine
std::this_thread::sleep_for(std::chrono::nanoseconds(1));
} while (!shouldStop() && glfwGetTime() < end);
}
}
void nafy::Context::stop() {
run = false;
}
void nafy::Context::stopIfCurrent(Scene *obj) {
if (obj == current) {
setGameRunning(false);
}
}
void nafy::Context::setGameRunning(bool value) {
runGameAction = value;
}
void nafy::Context::setDispatch(EventDispatch &dis) {
dispatch.clearAll();
dispatch.addChild(dis);
dis.setToggled(true);
dispatch.setToggled(true);
}
void nafy::Context::setBackground(Color &color) {
background = &color;
}
void nafy::Context::setFPS(unsigned int fps) {
framesPerSecond = fps;
// glfwGetTime() returns seconds as a float
frameCooldown = 1.0f / fps;
}
unsigned int nafy::Context::getFPS() {
return framesPerSecond;
}
void nafy::Context::setVSync(int lv) {
vsync = lv;
makeCurrent();
glfwSwapInterval(vsync);
}
int nafy::Context::getVSync() {
return vsync;
}
Font::type nafy::Context::makeFont(const FontFactory &factory) {
textLib.makeFont(factory);
return textLib.makeFont(factory);
}
void nafy::Context::setDefaultSpriteShader(const shader_t &shader) {
defaultShaders.sprite = shader;
}
void nafy::Context::setDefaultPrimShader(const shader_t &shader) {
defaultShaders.prim = shader;
}
void nafy::Context::setDefaultFont(const Font::type &font) {
defaultFont = font;
}
std::shared_ptr<nafy::Context::views_s> nafy::Context::getViews() {
return views;
}
nafy::Context::views_s &nafy::Context::getViewsRef() {
return *views;
}
void nafy::Context::setSpeaker(const std::string &name) {
views->game.speaker.getText().setString(name);
views->game.speaker.getText().generate();
}
nafy::shader_t nafy::Context::getDefaultSpriteShader() {
return defaultShaders.sprite;
}
nafy::shader_t nafy::Context::getDefaultPrimShader() {
return defaultShaders.prim;
}
Font::type nafy::Context::getDefaultFont() {
return defaultFont;
}
TextCrawl &nafy::Context::getCrawl() {
return views->game.crawl.getDisplay().getText();
}
nafy::EventDispatch &nafy::Context::getGameDispatch() {
return views->game.dispatch;
}
bool nafy::Context::shouldStop() {
return glfwWindowShouldClose(window) || !run;
}
void nafy::Context::setUserAdvance(bool value) {
userAdvance = value;
}
bool nafy::Context::getUserAdvance() {
return userAdvance;
}
| 28.789041 | 99 | 0.657594 | [
"render",
"vector",
"model"
] |
1802d01be78a0413745917abeff1fcd9ff499393 | 27,032 | hpp | C++ | src/ast/ast.hpp | myrjola/cee_scrap | f0c9cee7545956aa3b9abf2654a08085010589b7 | [
"MIT"
] | null | null | null | src/ast/ast.hpp | myrjola/cee_scrap | f0c9cee7545956aa3b9abf2654a08085010589b7 | [
"MIT"
] | null | null | null | src/ast/ast.hpp | myrjola/cee_scrap | f0c9cee7545956aa3b9abf2654a08085010589b7 | [
"MIT"
] | null | null | null | /*
* Copyright:
* Gabriel Hjort Blindell, 2012
*
* 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.
*
*/
#ifndef CEE_AST_AST__H
#define CEE_AST_AST__H
/**
* @file
* @brief Defines the classes needed for the AST.
*/
#include <exception>
#include <list>
#include <string>
/**
* @brief Contains all classes and functions used for constructing an AST.
*
* The \c AST namespace contains all classes and functions that are needed for
* creating an AST for a particular input source program.
*/
namespace AST {
class NStatementList;
class NStatement;
class NExpression;
class NVariable;
class IVisitor;
/**
* Defines the operator types that can be used in an expression (this includes
* both unary and binary expressions).
*/
enum ExpressionOperator {
PLUS,
MINUS,
MUL,
DIV
};
/**
* \brief Node tree exception.
*
* Exception which may be thrown when the AST tree is traversed.
*/
class NodeError : public std::exception {
public:
/**
* Creates a node error with no error message.
*/
NodeError(void);
/**
* Creates a node error with error message.
*
* @param message
* Error message.
*/
NodeError(const std::string& message);
/**
* Destroys this exception.
*/
virtual ~NodeError(void) throw();
/**
* Gets the error message.
*
* @returns Error message.
*/
virtual const char* what() const throw();
private:
/**
* Error message.
*/
std::string _message;
};
/**
* \brief Abstract base class for the AST nodes.
*
* The Node class provides the methods that will be needed for all nodes in the
* AST. These include line and column access methods, but also declares the \c
* accept(IVisitor*) method that must be implemented by all deriving subclasses.
* Each implementation of accept(IVisitor*) must work as follows:
* -# Invoke IVisitor::preVisit()
* -# Invoke IVisitor::visit()
* -# Invoke accept() on all child nodes
* - Between each accept() to the children,
* invoke IVisitor::betweenChildren()
* -# Invoke IVisitor::postVisit()
*
* The order in which the child nodes are visited is determined by making a
* call to the corresponding IVisitor::getChildVisitOrder() method. This is of
* course only needed when the node contains more than one child.
*
* The IVisitor::preVisit() and IVisitor::postVisit() methods have its uses when
* actions must be taken before or after a node is visited. For example, when
* pretty-printing an AST, the IVisitor::preVisit() and IVisitor::postVisit()
* methods can be used to control the level of indentation.
*/
class Node {
public:
/**
* Creates a node.
*
* @param line
* Line number at which this node was found.
* @param column
* Column number at which this node was found.
*/
Node(int line, int column);
/**
* Destroys this node and all of its child nodes.
*/
virtual ~Node(void);
/**
* Get line number at which this node was declared.
*
* @returns Line number.
*/
int getLine(void) const;
/**
* Get column number at which this node was declared.
*
* @returns Column number.
*/
int getColumn(void) const;
/**
* Makes a visit to this node by the given visitor.
*
* @param visitor
* Visitor.
* @throws NodeError
* When an error occurs.
*/
virtual void accept(IVisitor* visitor) throw(NodeError) = 0;
private:
/**
* Line number at which this node was declared.
*/
int _line;
/**
* Column number at which this node was declared.
*/
int _column;
};
/**
* \brief Program node class.
*
* Class for the root node of the AST.
*/
class NProgram : public Node {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param statements
* Statement list node.
*/
NProgram(
NStatementList* statements,
int line,
int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NProgram(void);
/**
* Gets the statement list node.
*
* @returns Statement list node.
*/
NStatementList* getStatementList(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Statement list node.
*/
NStatementList* _statements;
};
/**
* \brief Statement list node class.
*
* Class for a list of statements.
*/
class NStatementList : public Node {
public:
/**
* \copydoc Node::Node(int, int)
*/
NStatementList(int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NStatementList(void);
/**
* Appends a statement node as child of this node.
*
* @param node
* Statement node.
*/
void appendStatement(NStatement* node);
/**
* \copydoc appendStatement(NStatement*)
*
* @returns This node.
*
* Alias to appendStatement(NStatement*)
*/
NStatementList& operator<<(NStatement* node);
/**
* Gets all statement nodes that are children of this node.
*
* @returns List of statement nodes.
*/
std::list<NStatement*> getStatements(void);
/**
* \copydoc Node::accept(IVisitor*)
*
* In IVisitor::NORMAL visiting order, the child nodes are visited in the
* order they appear in the list retrieved from getStatements(void).
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* List of statement nodes.
*/
std::list<NStatement*> _statements;
};
/**
* \brief Abstract statement node class.
*
* Abstract class for a statement.
*/
class NStatement : public Node {
public:
/**
* \copydoc Node::Node(int, int)
*/
NStatement(int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NStatement(void);
};
/**
* \brief Assignment node class.
*
* Class for an assignment.
*/
class NAssignment : public NStatement {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param variable
* Variable node
* @param expr
* Expression node.
*/
NAssignment(NVariable* variable, NExpression* expr, int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NAssignment(void);
/**
* Gets the variable node.
*
* @returns Variable node.
*/
NVariable* getVariable(void) const;
/**
* Gets the expression node.
*
* @returns Expression node.
*/
NExpression* getExpression(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*
* In IVisitor::NORMAL visiting order, the variable node is visited before
* the expression node.
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Variable node.
*/
NVariable* _variable;
/**
* Expression node.
*/
NExpression* _expr;
};
/**
* \brief Print node class.
*
* Class for a print assignment.
*/
class NPrint : public NStatement {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param expr
* Expression node.
*/
NPrint(NExpression* expr, int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NPrint(void);
/**
* Gets the expression node.
*
* @returns Expression node.
*/
NExpression* getExpression(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Expression node.
*/
NExpression* _expr;
};
/**
* \brief Abstract expression node class.
*
* Abstract class for an expression.
*/
class NExpression : public Node {
public:
/**
* \copydoc Node::Node(int, int)
*/
NExpression(int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NExpression(void);
};
/**
* \brief Unary-operator expression node class.
*
* Class for the unary-operator expressions.
*/
class NExpressionUnary : public NExpression {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param op
* Unary operator.
* @param expr
* Expression node.
*/
NExpressionUnary(
ExpressionOperator op,
NExpression* expr,
int line,
int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NExpressionUnary(void);
/**
* Gets the expression node.
*
* @returns Expression node.
*/
NExpression* getExpression(void) const;
/**
* Gets the operator.
*
* @returns ExpressionOperator.
*/
ExpressionOperator getOperator(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Expression operator.
*/
ExpressionOperator _op;
/**
* Expression node.
*/
NExpression* _expr;
};
/**
* \brief Binary-operator expression node class.
*
* Class for the binary-operator expressions.
*/
class NExpressionBinary : public NExpression {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param lhs
* Left-hand side expression node.
* @param op
* Binary operator.
* @param rhs
* Right-hand side expression node.
*/
NExpressionBinary(
NExpression* lhs,
ExpressionOperator op,
NExpression* rhs,
int line,
int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NExpressionBinary(void);
/**
* Gets the left-hand side expression node.
*
* @returns Expression node.
*/
NExpression* getLhsExpression(void) const;
/**
* Gets the operator.
*
* @returns ExpressionOperator.
*/
ExpressionOperator getOperator(void) const;
/**
* Gets the right-hand side expression node.
*
* @returns Expression node.
*/
NExpression* getRhsExpression(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*
* In IVisitor::NORMAL visiting order, the left-hand side expression node is
* visited before the right-hand side expression node.
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Left-hand side expression node.
*/
NExpression* _lhs;
/**
* Expression operator.
*/
ExpressionOperator _op;
/**
* Right-hand side expression node.
*/
NExpression* _rhs;
};
/**
* \brief Number node class
*
* Class for a number.
*/
class NNumber : public NExpression {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param number
* Number value.
*/
NNumber(const std::string& number, int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NNumber(void);
/**
* Gets the number value.
*
* @returns Number value.
*/
std::string getNumber(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Number as a string.
*/
std::string _number;
};
/**
* \brief Variable node class.
*
* Class for a variable.
*/
class NVariable : public NExpression {
public:
/**
* \copydoc Node::Node(int, int)
*
* @param name
* Variable name.
*/
NVariable(const std::string& name, int line, int column);
/**
* \copydoc Node::~Node(void)
*/
virtual ~NVariable(void);
/**
* Gets the variable name.
*
* @returns Variable name.
*/
std::string getName(void) const;
/**
* \copydoc Node::accept(IVisitor*)
*/
virtual void accept(IVisitor* visitor) throw(NodeError);
private:
/**
* Variable name.
*/
std::string _name;
};
/**
* \brief AST visitor interface.
*
* Defines the interface of a visitor object (according to the <a
* href="http://en.wikipedia.org/wiki/Visitor_pattern"><em>Visitor</em></a>
* design pattern).
*
* The core part of a visitor is the \c visit() function. It decides what to do
* with the current node. \c visit() is always invoked on the current node prior
* to visiting its children. Two additional methods - \c preVisit() and \c
* postVisit() - are used to take actions before visiting the node, and after
* having visited the node and all of its children. There is also another method
* - betweenChildren() - which is invoked after one child has been visited but
* before visiting the next child (this only applies if the node has more than
* one child node).
*/
class IVisitor {
public:
/**
* Defines the possible orders in which child nodes can be visited.
*/
enum VisitOrder {
/**
* Child nodes are visited in normal order.
*/
NORMAL,
/**
* Child nodes are visited in reversed order (compared to the normal
* order).
*/
REVERSED
};
public:
/**
* Destroys this visitor.
*/
virtual ~IVisitor(void);
/**
* Hook that is invoked \e before the node is visited.
*
* @param node
* Node about to visit.
* @throws NodeError
* When an error occurs.
*/
virtual void preVisit(Node* node) throw(NodeError) = 0;
/**
* Hook that is invoked when the node is to be visited.
*
* @param node
* Node to visit.
* @throws NodeError
* When an error occurs.
*/
virtual void visit(Node* node) throw(NodeError) = 0;
/**
* Hook that is invoked \e after the node is visited.
*
* @param node
* Node which was visited.
* @throws NodeError
* When an error occurs.
*/
virtual void postVisit(Node* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NProgram* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NProgram* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NProgram* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NStatementList* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NStatementList* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NStatementList* node) throw(NodeError) = 0;
/**
* Hook that is invoked between the visiting of the child nodes.
*
* @param node
* Node that contains the child nodes.
* @throws NodeError
* When an error occurs.
*/
virtual void betweenChildren(NStatementList* node) throw(NodeError) = 0;
/**
* Determines in which order the child nodes are to be visited.
*
* @param node
* Node that contains the child nodes.
* @throws NodeError
* When an error occurs.
*/
virtual VisitOrder getChildVisitOrder(NStatementList* node)
throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NStatement* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NStatement* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NStatement* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NAssignment* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NAssignment* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NAssignment* node) throw(NodeError) = 0;
/**
* \copydoc betweenChildren(NStatementList*)
*/
virtual void betweenChildren(NAssignment* node) throw(NodeError) = 0;
/**
* \copydoc getChildVisitOrder(NStatementList*)
*/
virtual VisitOrder getChildVisitOrder(NAssignment* node)
throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NPrint* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NPrint* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NPrint* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NExpression* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NExpression* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NExpression* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NExpressionUnary* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NExpressionUnary* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NExpressionUnary* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NExpressionBinary* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NExpressionBinary* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NExpressionBinary* node) throw(NodeError) = 0;
/**
* \copydoc betweenChildren(NStatementList*)
*/
virtual void betweenChildren(NExpressionBinary* node) throw(NodeError) = 0;
/**
* \copydoc getChildVisitOrder(NStatementList*)
*/
virtual VisitOrder getChildVisitOrder(NExpressionBinary* node)
throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NVariable* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NVariable* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NVariable* node) throw(NodeError) = 0;
/**
* \copydoc preVisit(Node*)
*/
virtual void preVisit(NNumber* node) throw(NodeError) = 0;
/**
* \copydoc visit(Node*)
*/
virtual void visit(NNumber* node) throw(NodeError) = 0;
/**
* \copydoc postVisit(Node*)
*/
virtual void postVisit(NNumber* node) throw(NodeError) = 0;
};
/**
* \brief Default implementation of an IVisitor.
*
* Implements a default visitor, whose implementation of all methods do nothing.
* This is convenient when a new visitor only needs to handle a small set of
* node classes.
*
* See IVisitor for more information.
*/
class DefaultVisitor : public IVisitor {
public:
/**
* \copydoc IVisitor::~IVisitor()
*/
virtual ~DefaultVisitor(void);
/**
* \copydoc IVisitor::preVisit(Node*)
*
* Does nothing by default.
*/
virtual void preVisit(Node* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(Node*)
*
* Does nothing by default.
*/
virtual void visit(Node* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(Node*)
*
* Does nothing by default.
*/
virtual void postVisit(Node* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NProgram*)
*
* Does nothing by default.
*/
virtual void preVisit(NProgram* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NProgram*)
*
* Does nothing by default.
*/
virtual void visit(NProgram* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NProgram*)
*
* Does nothing by default.
*/
virtual void postVisit(NProgram* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NStatementList*)
*
* Does nothing by default.
*/
virtual void preVisit(NStatementList* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NStatementList*)
*
* Does nothing by default.
*/
virtual void visit(NStatementList* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NStatementList*)
*
* Does nothing by default.
*/
virtual void postVisit(NStatementList* node) throw(NodeError);
/**
* \copydoc IVisitor::betweenChildren(NStatementList*)
*
* Does nothing by default.
*/
virtual void betweenChildren(NStatementList* node) throw(NodeError);
/**
* \copydoc IVisitor::getChildVisitOrder(NStatementList*)
*
* @returns IVisitor::NORMAL by default.
*/
virtual IVisitor::VisitOrder getChildVisitOrder(NStatementList* node)
throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NStatement*)
*
* Does nothing by default.
*/
virtual void preVisit(NStatement* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NStatement*)
*
* Does nothing by default.
*/
virtual void visit(NStatement* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NStatement*)
*
* Does nothing by default.
*/
virtual void postVisit(NStatement* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NAssignment*)
*
* Does nothing by default.
*/
virtual void preVisit(NAssignment* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NAssignment*)
*
* Does nothing by default.
*/
virtual void visit(NAssignment* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NAssignment*)
*
* Does nothing by default.
*/
virtual void postVisit(NAssignment* node) throw(NodeError);
/**
* \copydoc IVisitor::betweenChildren(NAssignment*)
*
* Does nothing by default.
*/
virtual void betweenChildren(NAssignment* node) throw(NodeError);
/**
* \copydoc IVisitor::getChildVisitOrder(NAssignment*)
*
* @returns IVisitor::NORMAL by default.
*/
virtual IVisitor::VisitOrder getChildVisitOrder(NAssignment* node)
throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NPrint*)
*
* Does nothing by default.
*/
virtual void preVisit(NPrint* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NPrint*)
*
* Does nothing by default.
*/
virtual void visit(NPrint* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NPrint*)
*
* Does nothing by default.
*/
virtual void postVisit(NPrint* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NExpression*)
*
* Does nothing by default.
*/
virtual void preVisit(NExpression* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NExpression*)
*
* Does nothing by default.
*/
virtual void visit(NExpression* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NExpression*)
*
* Does nothing by default.
*/
virtual void postVisit(NExpression* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NExpressionUnary*)
*
* Does nothing by default.
*/
virtual void preVisit(NExpressionUnary* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NExpressionUnary*)
*
* Does nothing by default.
*/
virtual void visit(NExpressionUnary* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NExpressionUnary*)
*
* Does nothing by default.
*/
virtual void postVisit(NExpressionUnary* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NExpressionBinary*)
*
* Does nothing by default.
*/
virtual void preVisit(NExpressionBinary* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NExpressionBinary*)
*
* Does nothing by default.
*/
virtual void visit(NExpressionBinary* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NExpressionBinary*)
*
* Does nothing by default.
*/
virtual void postVisit(NExpressionBinary* node) throw(NodeError);
/**
* \copydoc IVisitor::betweenChildren(NExpressionBinary*)
*
* Does nothing by default.
*/
virtual void betweenChildren(NExpressionBinary* node) throw(NodeError);
/**
* \copydoc IVisitor::getChildVisitOrder(NExpressionBinary*)
*
* @returns IVisitor::NORMAL by default.
*/
virtual IVisitor::VisitOrder getChildVisitOrder(NExpressionBinary* node)
throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NVariable*)
*
* Does nothing by default.
*/
virtual void preVisit(NVariable* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NVariable*)
*
* Does nothing by default.
*/
virtual void visit(NVariable* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NVariable*)
*
* Does nothing by default.
*/
virtual void postVisit(NVariable* node) throw(NodeError);
/**
* \copydoc IVisitor::preVisit(NNumber*)
*
* Does nothing by default.
*/
virtual void preVisit(NNumber* node) throw(NodeError);
/**
* \copydoc IVisitor::visit(NNumber*)
*
* Does nothing by default.
*/
virtual void visit(NNumber* node) throw(NodeError);
/**
* \copydoc IVisitor::postVisit(NNumber*)
*
* Does nothing by default.
*/
virtual void postVisit(NNumber* node) throw(NodeError);
};
}
#endif
| 22.966865 | 80 | 0.601731 | [
"object"
] |
18110a8ef62bf86bea5cf133bc943d87a33a5fd3 | 9,680 | cp | C++ | Form/Mod/Gen.cp | romiras/Blackbox-fw-playground | 6de94dc65513e657a9b86c1772e2c07742b608a8 | [
"BSD-2-Clause"
] | 1 | 2018-03-15T00:25:25.000Z | 2018-03-15T00:25:25.000Z | Form/Mod/Gen.cps | Spirit-of-Oberon/LightBox | 8a45ed11dcc02ae97e86f264dcee3e07c910ff9d | [
"BSD-2-Clause"
] | null | null | null | Form/Mod/Gen.cps | Spirit-of-Oberon/LightBox | 8a45ed11dcc02ae97e86f264dcee3e07c910ff9d | [
"BSD-2-Clause"
] | 1 | 2021-04-14T21:17:51.000Z | 2021-04-14T21:17:51.000Z | MODULE FormGen;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
purpose = ""
changes = ""
issues = ""
**)
IMPORT
Strings, Meta, Dates, Files, Ports, Views, Properties, Dialog, Containers, Documents,
Controls, StdDialog, StdCmds, FormModels, FormViews, FormControllers;
CONST
defaultDelta = 4 * Ports.point;
minW = 10 * Ports.mm; minH = 4 * Ports.mm;
maxW = 200 * Ports.mm; maxH = 50 * Ports.mm;
TYPE
ProcVal = RECORD (Meta.Value)
p: PROCEDURE
END;
VAR
new*: RECORD
link*: Dialog.String
END;
list: RECORD (Meta.Value) p*: POINTER TO Dialog.List END;
select: RECORD (Meta.Value) p*: POINTER TO Dialog.Selection END;
combo: RECORD (Meta.Value) p*: POINTER TO Dialog.Combo END;
date: RECORD (Meta.Value) p*: POINTER TO Dates.Date END;
time: RECORD (Meta.Value) p*: POINTER TO Dates.Time END;
color: RECORD (Meta.Value) p*: POINTER TO Dialog.Color END;
currency: RECORD (Meta.Value) p*: POINTER TO Dialog.Currency END;
tree: RECORD (Meta.Value) p*: POINTER TO Dialog.Tree END;
PROCEDURE GetSize (v: Views.View; VAR w, h: INTEGER);
BEGIN
w := Views.undefined; h := Views.undefined;
Properties.PreferredSize(v, minW, maxW, minH, maxH, minW, minH, w, h)
END GetSize;
PROCEDURE Gen (f: FormModels.Model; fv: FormViews.View; VAR path, name: ARRAY OF CHAR;
wr: FormModels.Writer; var: Meta.Item; VAR x, y, max: INTEGER; VAR first: BOOLEAN);
VAR v, str: Views.View; dummy, delta, x0, y0, m, w, h, i: INTEGER; n: Meta.Name;
p: Controls.Prop; s: Meta.Scanner; elem: Meta.Item; ok, back: BOOLEAN; pv: ProcVal;
BEGIN
dummy := 0; delta := defaultDelta; FormViews.RoundToGrid(fv, dummy, delta);
NEW(p); p.guard := ""; p.notifier := ""; p.label := ""; p.level := 0;
p.opt[0] := FALSE; p.opt[1] := FALSE; p.opt[2] := FALSE; p.opt[3] := FALSE; p.opt[4] := FALSE;
back := FALSE;
FormViews.RoundToGrid(fv, x, y);
v := NIL; w := Views.undefined; x0 := x; y0 := y;
IF (name[0] >= "0") & (name[0] <= "9") THEN p.link := path + "[" + name + "]"
ELSIF name # "" THEN p.link := path + "." + name
ELSE p.link := path$
END;
IF var.obj = Meta.modObj THEN (* traverse module *)
s.ConnectTo(var); s.Scan; m := 0;
WHILE ~ s.eos DO
s.GetObjName(n);
Gen(f, fv, p.link, n, wr, s.this, x, y, m, first);
s.Scan
END;
IF m > max THEN max := m END;
ELSIF var.obj = Meta.procObj THEN
var.GetVal(pv, ok);
IF ok THEN (* command *)
IF first THEN p.opt[Controls.default] := TRUE END;
p.label := name$; v := Controls.dir.NewPushButton(p);
p.opt[Controls.default] := FALSE; first := FALSE
END
ELSIF var.obj = Meta.varObj THEN
IF (var.typ IN {Meta.byteTyp, Meta.sIntTyp, Meta.longTyp, Meta.intTyp, Meta.sRealTyp, Meta.realTyp})
OR (var.typ = Meta.arrTyp) & (var.BaseTyp() = Meta.charTyp) THEN
p.opt[Controls.left] := TRUE; v := Controls.dir.NewField(p)
ELSIF var.typ = Meta.boolTyp THEN
p.label := name$; v := Controls.dir.NewCheckBox(p)
ELSIF var.typ = Meta.procTyp THEN
var.GetVal(pv, ok);
IF ok THEN (* command *)
IF first THEN p.opt[Controls.default] := TRUE END;
p.label := name$; v := Controls.dir.NewPushButton(p);
p.opt[Controls.default] := FALSE; first := FALSE
END
ELSIF var.typ = Meta.recTyp THEN
IF var.Is(list) THEN v := Controls.dir.NewListBox(p)
ELSIF var.Is(select) THEN v := Controls.dir.NewSelectionBox(p)
ELSIF var.Is(combo) THEN v := Controls.dir.NewComboBox(p)
ELSIF var.Is(date) THEN v := Controls.dir.NewDateField(p)
ELSIF var.Is(time) THEN v := Controls.dir.NewTimeField(p)
ELSIF var.Is(color) THEN v := Controls.dir.NewColorField(p)
ELSIF var.Is(currency) THEN p.opt[Controls.left] := TRUE; v := Controls.dir.NewField(p)
ELSIF var.Is(tree) THEN
p.opt[Controls.haslines] := TRUE; p.opt[Controls.hasbuttons] := TRUE;
p.opt[Controls.atroot] := TRUE; p.opt[Controls.foldericons] := TRUE;
v := Controls.dir.NewTreeControl(p)
ELSE (* traverse record *)
s.ConnectTo(var); s.Scan; m := 0;
IF name # "" THEN INC(x, delta); INC(y, 4 * delta) END;
WHILE ~ s.eos DO
s.GetObjName(n);
Gen(f, fv, p.link, n, wr, s.this, x, y, m, first);
s.Scan
END;
IF m > max THEN max := m END;
IF (name # "") & (m > 0) THEN (* insert group *)
p.label := name$; v := Controls.dir.NewGroup(p);
w := m; x := x0; h := y + delta - y0; y := y0; back := TRUE
END
END
ELSIF var.typ = Meta.arrTyp THEN (* traverse array *)
i := 0; m := 0;
IF name # "" THEN INC(x, delta); INC(y, 4 * delta) END;
WHILE i < var.Len() DO
var.Index(i, elem);
Strings.IntToString(i, n);
Gen(f, fv, p.link, n, wr, elem, x, y, m, first);
INC(i)
END;
IF m > max THEN max := m END;
IF (name # "") & (m > 0) THEN (* insert group *)
p.label := name$; v := Controls.dir.NewGroup(p);
w := m; x := x0; h := y + delta - y0; y := y0; back := TRUE
END
END
END;
IF v # NIL THEN
IF (name # "") & (p.label = "") THEN
p.label := name$;
str := Controls.dir.NewCaption(p); GetSize(str, w, h);
wr.WriteView(str, x, y, x + w, y + h); INC(x, w + delta);
FormViews.RoundToGrid(fv, x, y)
END;
IF ~back THEN GetSize(v, w, h) END;
wr.WriteView(v, x, y, x + w, y + h); INC(x, w + delta);
IF back THEN f.PutAbove(v, NIL) END;
y := y + h + delta
END;
IF x > max THEN max := x END;
x := x0
END Gen;
PROCEDURE NewDialog (name: ARRAY OF CHAR): Views.View;
VAR var: Meta.Item; x, y, max: INTEGER; wr: FormModels.Writer; d: Documents.Document;
f: FormModels.Model; v: FormViews.View; first: BOOLEAN; n: ARRAY 4 OF CHAR;
c: Containers.Controller;
BEGIN
f := NIL; v := NIL;
Meta.LookupPath(name, var);
IF (var.obj = Meta.varObj) OR (var.obj = Meta.modObj) THEN
x := defaultDelta; y := defaultDelta; max := 50 * Ports.point; first := TRUE;
f := FormModels.dir.New();
v := FormViews.dir.New(f); c := v.ThisController();
IF c # NIL THEN
c.SetOpts(Containers.layout)
ELSE
v.SetController(FormControllers.dir.NewController(Containers.layout))
END;
wr := f.NewWriter(NIL); wr.Set(NIL); n := "";
Gen(f, v, name, n, wr, var, x, y, max, first);
d := Documents.dir.New(v, max, y)
ELSE Dialog.ShowParamMsg("#Form:VariableNotFound", name, "", "")
END;
RETURN v
END NewDialog;
PROCEDURE Create*;
VAR v: Views.View; i, j: INTEGER; mod, name: Files.Name; loc: Files.Locator;
w: FormViews.View; c: Containers.Controller;
BEGIN
v := NIL;
IF new.link = "" THEN
w := FormViews.dir.New(FormModels.dir.New()); c := w.ThisController();
IF c # NIL THEN
c.SetOpts({FormControllers.noFocus})
ELSE
w.SetController(FormControllers.dir.NewController({FormControllers.noFocus}))
END;
v := w
ELSE
v := NewDialog(new.link)
END;
IF v # NIL THEN
mod := new.link$; new.link := ""; name := "";
StdCmds.CloseDialog;
IF mod # "" THEN
i := 0; WHILE (mod[i] # 0X) & (mod[i] # ".") DO INC(i) END;
IF mod[i] # 0X THEN (* module.variable *)
mod[i] := 0X; INC(i); j := 0;
WHILE mod[i] # 0X DO name[j] := mod[i]; INC(i); INC(j) END;
name[j] := 0X
END;
StdDialog.GetSubLoc(mod, "Rsrc", loc, mod);
IF name = "" THEN name := mod$ END;
loc.res := 77
ELSE
loc := NIL; name := ""
END;
Views.Open(v, loc, name, NIL);
Views.BeginModification(Views.notUndoable, v);
Views.EndModification(Views.notUndoable, v)
END
END Create;
PROCEDURE Empty*;
BEGIN
new.link := ""; Create
END Empty;
PROCEDURE CreateGuard* (VAR par: Dialog.Par);
BEGIN
IF new.link = "" THEN par.disabled := TRUE END
END CreateGuard;
END FormGen.
| 43.214286 | 112 | 0.491632 | [
"model"
] |
18127b233cbf016b168a9604bbdd3f77cc32d43c | 2,913 | hpp | C++ | CPP_rtype_2019/src/client/EntityClient.hpp | ltabis/epitech-projects | e38b3f00a4ac44c969d5e4880cd65084dc2c870a | [
"MIT"
] | null | null | null | CPP_rtype_2019/src/client/EntityClient.hpp | ltabis/epitech-projects | e38b3f00a4ac44c969d5e4880cd65084dc2c870a | [
"MIT"
] | null | null | null | CPP_rtype_2019/src/client/EntityClient.hpp | ltabis/epitech-projects | e38b3f00a4ac44c969d5e4880cd65084dc2c870a | [
"MIT"
] | 1 | 2021-01-07T17:41:14.000Z | 2021-01-07T17:41:14.000Z | /*
** EPITECH PROJECT, 2019
** CPP_rtype_2019
** File description:
** Entity class declaration
*/
/// \file Entity.hpp
/// \author Lucas T.
/// \brief Header file for the Entity class
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
#include "Logger.hpp"
namespace Client {
/// \class Entity
/// \brief Entity class, create an entity in the game world
class Entity {
public:
/// \brief constructor
/// Create an entity with an empty texture
/// \param texture : the empty texture of the entity
Entity(sf::Texture &texture);
/// \brief constructor
/// Create an entity with an empty texture
/// \param texture : the texture of the entity
/// \param textureIdx : id of the texture
Entity(sf::Texture &texture, std::size_t textureIdx);
/// \brief destructor
/// Destroy the Entity class
~Entity() = default;
/// \return a boolean, true if the entity is visible, false otherwise
/// \brief Check if the entity is visible
bool isVisible() const;
/// \return a boolean, true if the entity is deleted, false otherwise
/// \brief Check if the entity is deleted
bool deleted() const;
/// \brief return the sprite of the current entity
/// \return the sprite of the entity
sf::Sprite &sprite();
/// \brief return the texture index of the current entity
/// \return the texture index of the entity
std::size_t textureIdx();
/// \brief set the texture of the entity
/// \param textureIdx : the new texture index of the entity
/// \param texture : the new texture
void setTextureIdx(std::size_t textureIdx, sf::Texture &texture);
/// \brief set the position of the entity
/// \param x : x coordinates
/// \param y : y coordinates
/// \param z : z coordinates
void setPosition(float x, float y, float z);
/// \brief set the position of the entity
/// \param top : top position of the rectangle
/// \param left : left position of the rectangle
/// \param width : width position of the rectangle
/// \param heigth : heigth position of the rectangle
void setTextureRect(float top, float left, float width, float heigth);
private:
/*! has the entity been deleted */
bool _deleted;
/*! is the entity visible */
bool _visible;
/*! the sprite*/
sf::Sprite _sprite;
/*! the texture id */
std::size_t _textureIdx;
/*! the rect of the texture */
sf::IntRect _rect;
};
} | 33.102273 | 82 | 0.558187 | [
"vector"
] |
181319ca888fd4f1a0feb02f4349ce6c9f4145fd | 1,553 | hpp | C++ | src/word-break-ii.hpp | Red-Li/leetcode | 908d579f4dbf63a0099b6aae909265300ead46c5 | [
"Apache-2.0"
] | null | null | null | src/word-break-ii.hpp | Red-Li/leetcode | 908d579f4dbf63a0099b6aae909265300ead46c5 | [
"Apache-2.0"
] | null | null | null | src/word-break-ii.hpp | Red-Li/leetcode | 908d579f4dbf63a0099b6aae909265300ead46c5 | [
"Apache-2.0"
] | null | null | null | class Solution {
vector<string> wordBreak(string s,
unordered_set<string> &dict,
vector<int> &flags,
vector<vector<string> > &his)
{
vector<string> res;
if(s.size()){
for(unordered_set<string>::iterator it = dict.begin(); it != dict.end(); ++it){
size_t psize = it->size();
if(psize <= s.size() && s.substr(0, psize) == *it){
int idx = s.size() - psize;
string prefix = s.substr(0, psize);
if(!flags[idx]){
his[idx] = wordBreak(
s.substr(psize, s.size() - psize),
dict,
flags,
his
);
flags[idx] = 1;
}
for(size_t i = 0; i < his[idx].size(); ++i){
string &ss = his[idx][i];
res.push_back(prefix + (ss.size() ? " " : "") + ss);
}
}
}
}
else{
res.push_back("");
}
return move(res);
}
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
vector<vector<string> > his(s.size(), vector<string>());
vector<int> flags(s.size(), 0);
return move(wordBreak(s, dict, flags, his));
}
};
| 34.511111 | 91 | 0.364456 | [
"vector"
] |
181db375e9138af182ccdebaf3142e5e48bd9d3e | 2,992 | hpp | C++ | maxon_epos_driver/include/maxon_epos_driver/Device.hpp | Mlahoud/maxon_epos_ros | 6e0dfbfe7405eab27fd91ad434601f614951b7f1 | [
"MIT"
] | 12 | 2019-06-10T20:21:53.000Z | 2022-03-12T14:44:42.000Z | maxon_epos_driver/include/maxon_epos_driver/Device.hpp | Mlahoud/maxon_epos_ros | 6e0dfbfe7405eab27fd91ad434601f614951b7f1 | [
"MIT"
] | 5 | 2019-08-09T11:29:46.000Z | 2022-01-31T07:28:57.000Z | maxon_epos_driver/include/maxon_epos_driver/Device.hpp | Mlahoud/maxon_epos_ros | 6e0dfbfe7405eab27fd91ad434601f614951b7f1 | [
"MIT"
] | 6 | 2020-05-28T06:48:11.000Z | 2022-02-25T11:12:03.000Z | /**
* @file Device
* @brief
* @author arwtyxouymz
* @date 2019-06-04 12:13:53
*/
#ifndef _Device_HPP
#define _Device_HPP
#include <string>
#include <vector>
#include <memory>
#include <map>
#include "maxon_epos_driver/utils/Macros.hpp"
/**
* @brief Information of device
*/
class DeviceInfo {
public:
DeviceInfo();
DeviceInfo(const std::string &device_name, const std::string &protocol_stack,
const std::string &interface_name, const std::string &portname);
virtual ~DeviceInfo();
public:
std::string device_name;
std::string protocol_stack;
std::string interface_name;
std::string port_name;
};
/**
* @brief Handle of device
*/
class DeviceHandle {
public:
DeviceHandle();
DeviceHandle(const DeviceInfo& info);
DeviceHandle(const DeviceInfo& info, const std::shared_ptr<void> master_device_ptr);
virtual ~DeviceHandle();
private:
static std::shared_ptr<void> MakePtr(const DeviceInfo &device_info);
static std::shared_ptr<void> MakeSubPtr(const DeviceInfo &device_info, const std::shared_ptr<void> master_device_ptr);
static void* OpenDevice(const DeviceInfo &device_info);
static void* OpenSubDevice(const DeviceInfo &device_info, const std::shared_ptr<void> master_device_ptr);
static void CloseDevice(void *raw_device_ptr);
static void CloseSubDevice(void *raw_device_ptr);
public:
std::shared_ptr<void> ptr;
};
/**
* @brief Information of Node
*/
class NodeInfo : public DeviceInfo {
public:
NodeInfo();
NodeInfo(const DeviceInfo &device_info, const unsigned short node_id);
virtual ~NodeInfo();
public:
unsigned short node_id;
};
/**
* @brief Handle of node
*/
class NodeHandle : public DeviceHandle {
public:
NodeHandle();
NodeHandle(const NodeInfo &node_info);
NodeHandle(const NodeInfo &node_info, const DeviceHandle &device_handle);
NodeHandle(const DeviceHandle &device_handle, const unsigned short node_id);
virtual ~NodeHandle();
public:
unsigned short node_id;
};
/**
* @brief DeviceInfo Comparison
*/
struct CompareNodeInfo
{
bool operator()(const NodeInfo &a, const NodeInfo &b)
{
if (a.device_name != b.device_name) {
return a.device_name < b.device_name;
}
if (a.protocol_stack != b.protocol_stack) {
return a.protocol_stack < b.protocol_stack;
}
if (a.interface_name != b.interface_name) {
return a.interface_name < b.interface_name;
}
if (a.port_name != b.port_name) {
return a.port_name < b.port_name;
}
return a.node_id < b.node_id;
}
};
class HandleManager {
public:
HandleManager();
~HandleManager();
static NodeHandle CreateEposHandle(const DeviceInfo &device_info, const unsigned short node_id);
private:
static std::shared_ptr<NodeHandle> m_master_handle;
static std::vector<std::shared_ptr<NodeHandle>> m_sub_handles;
};
#endif // _Device_HPP
| 23.936 | 122 | 0.686497 | [
"vector"
] |
181f84cc8294665693168ebb6375f2ce60be94d5 | 905 | cpp | C++ | HighLo-Unit/src/UnitTest.cpp | HighLo-Engine/HighLo-Unit | 7c23b7d1400fd70e76b918ad616144d5cfad937f | [
"MIT"
] | null | null | null | HighLo-Unit/src/UnitTest.cpp | HighLo-Engine/HighLo-Unit | 7c23b7d1400fd70e76b918ad616144d5cfad937f | [
"MIT"
] | null | null | null | HighLo-Unit/src/UnitTest.cpp | HighLo-Engine/HighLo-Unit | 7c23b7d1400fd70e76b918ad616144d5cfad937f | [
"MIT"
] | null | null | null | #include "UnitTest.h"
namespace highloUnit
{
void UnitTest::AppendTest(const HighLoUnitFunc &func, const char *name, bool enabled)
{
UnitFuncs.push_back({ func, name, enabled });
}
void UnitTest::AppendAllTests(const std::vector<UnitTestEntry> &funcs)
{
for (UnitTestEntry entry : funcs)
{
UnitFuncs.push_back(entry);
}
}
int32 UnitTest::ExecuteTests()
{
int32 exitCode = 0;
int32 i = 0;
Timer timer("GlobalTimer");
for (i = 0; i < UnitFuncs.size(); ++i)
{
if (!UnitFuncs[i].Enabled)
{
std::cout << "Skipped test " << UnitFuncs[i].FunctionName << std::endl;
continue;
}
exitCode = UnitFuncs[i].Function();
if (exitCode == 1)
{
std::cout << "Error: Some tests have failed!" << std::endl;
return 1;
}
}
timer.Stop();
std::cout << "OK: All Tests have passed successfully!" << timer.GetOutputString() << std::endl;
return 0;
}
} | 20.568182 | 97 | 0.628729 | [
"vector"
] |
18230fdcb89df13b5d8a0d655a9ef7ed5a3ee445 | 8,832 | cpp | C++ | dds/DCPS/InfoRepoDiscovery/DataWriterRemoteC.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | dds/DCPS/InfoRepoDiscovery/DataWriterRemoteC.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | dds/DCPS/InfoRepoDiscovery/DataWriterRemoteC.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | // -*- C++ -*-
// $Id$
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v2.2a_p7
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.cs.wustl.edu/~schmidt/TAO.html
**/
// TAO_IDL - Generated from
// be/be_codegen.cpp:376
#include "DataWriterRemoteC.h"
#include "tao/CDR.h"
#include "tao/Exception_Data.h"
#include "tao/Invocation_Adapter.h"
#include "tao/Object_T.h"
#include "ace/OS_NS_string.h"
#if !defined (__ACE_INLINE__)
#include "DataWriterRemoteC.inl"
#endif /* !defined INLINE */
// TAO_IDL - Generated from
// be/be_visitor_interface/interface_cs.cpp:51
// Traits specializations for OpenDDS::DCPS::DataWriterRemote.
OpenDDS::DCPS::DataWriterRemote_ptr
TAO::Objref_Traits<OpenDDS::DCPS::DataWriterRemote>::duplicate (
OpenDDS::DCPS::DataWriterRemote_ptr p)
{
return OpenDDS::DCPS::DataWriterRemote::_duplicate (p);
}
void
TAO::Objref_Traits<OpenDDS::DCPS::DataWriterRemote>::release (
OpenDDS::DCPS::DataWriterRemote_ptr p)
{
::CORBA::release (p);
}
OpenDDS::DCPS::DataWriterRemote_ptr
TAO::Objref_Traits<OpenDDS::DCPS::DataWriterRemote>::nil (void)
{
return OpenDDS::DCPS::DataWriterRemote::_nil ();
}
::CORBA::Boolean
TAO::Objref_Traits<OpenDDS::DCPS::DataWriterRemote>::marshal (
const OpenDDS::DCPS::DataWriterRemote_ptr p,
TAO_OutputCDR & cdr)
{
return ::CORBA::Object::marshal (p, cdr);
}
// TAO_IDL - Generated from
// be/be_visitor_operation/operation_cs.cpp:91
void
OpenDDS::DCPS::DataWriterRemote::add_association (
const ::OpenDDS::DCPS::RepoId & yourId,
const ::OpenDDS::DCPS::ReaderAssociation & reader,
::CORBA::Boolean active)
{
if (!this->is_evaluated ())
{
::CORBA::Object::tao_object_initialize (this);
}
TAO::Arg_Traits< void>::ret_val _tao_retval;
TAO::Arg_Traits< ::OpenDDS::DCPS::GUID_t>::in_arg_val _tao_yourId (yourId);
TAO::Arg_Traits< ::OpenDDS::DCPS::ReaderAssociation>::in_arg_val _tao_reader (reader);
TAO::Arg_Traits< ::ACE_InputCDR::to_boolean>::in_arg_val _tao_active (active);
TAO::Argument *_the_tao_operation_signature [] =
{
&_tao_retval,
&_tao_yourId,
&_tao_reader,
&_tao_active
};
TAO::Invocation_Adapter _tao_call (
this,
_the_tao_operation_signature,
4,
"add_association",
15,
TAO::TAO_CO_NONE | TAO::TAO_CO_THRU_POA_STRATEGY,
TAO::TAO_ONEWAY_INVOCATION
);
_tao_call.invoke (0, 0);
}
// TAO_IDL - Generated from
// be/be_visitor_operation/operation_cs.cpp:91
void
OpenDDS::DCPS::DataWriterRemote::association_complete (
const ::OpenDDS::DCPS::RepoId & remote_id)
{
if (!this->is_evaluated ())
{
::CORBA::Object::tao_object_initialize (this);
}
TAO::Arg_Traits< void>::ret_val _tao_retval;
TAO::Arg_Traits< ::OpenDDS::DCPS::GUID_t>::in_arg_val _tao_remote_id (remote_id);
TAO::Argument *_the_tao_operation_signature [] =
{
&_tao_retval,
&_tao_remote_id
};
TAO::Invocation_Adapter _tao_call (
this,
_the_tao_operation_signature,
2,
"association_complete",
20,
TAO::TAO_CO_NONE | TAO::TAO_CO_THRU_POA_STRATEGY,
TAO::TAO_ONEWAY_INVOCATION
);
_tao_call.invoke (0, 0);
}
// TAO_IDL - Generated from
// be/be_visitor_operation/operation_cs.cpp:91
void
OpenDDS::DCPS::DataWriterRemote::remove_associations (
const ::OpenDDS::DCPS::ReaderIdSeq & readers,
::CORBA::Boolean notify_lost)
{
if (!this->is_evaluated ())
{
::CORBA::Object::tao_object_initialize (this);
}
TAO::Arg_Traits< void>::ret_val _tao_retval;
TAO::Arg_Traits< ::OpenDDS::DCPS::ReaderIdSeq>::in_arg_val _tao_readers (readers);
TAO::Arg_Traits< ::ACE_InputCDR::to_boolean>::in_arg_val _tao_notify_lost (notify_lost);
TAO::Argument *_the_tao_operation_signature [] =
{
&_tao_retval,
&_tao_readers,
&_tao_notify_lost
};
TAO::Invocation_Adapter _tao_call (
this,
_the_tao_operation_signature,
3,
"remove_associations",
19,
TAO::TAO_CO_NONE | TAO::TAO_CO_THRU_POA_STRATEGY,
TAO::TAO_ONEWAY_INVOCATION
);
_tao_call.invoke (0, 0);
}
// TAO_IDL - Generated from
// be/be_visitor_operation/operation_cs.cpp:91
void
OpenDDS::DCPS::DataWriterRemote::update_incompatible_qos (
const ::OpenDDS::DCPS::IncompatibleQosStatus & status)
{
if (!this->is_evaluated ())
{
::CORBA::Object::tao_object_initialize (this);
}
TAO::Arg_Traits< void>::ret_val _tao_retval;
TAO::Arg_Traits< ::OpenDDS::DCPS::IncompatibleQosStatus>::in_arg_val _tao_status (status);
TAO::Argument *_the_tao_operation_signature [] =
{
&_tao_retval,
&_tao_status
};
TAO::Invocation_Adapter _tao_call (
this,
_the_tao_operation_signature,
2,
"update_incompatible_qos",
23,
TAO::TAO_CO_NONE | TAO::TAO_CO_THRU_POA_STRATEGY,
TAO::TAO_ONEWAY_INVOCATION
);
_tao_call.invoke (0, 0);
}
// TAO_IDL - Generated from
// be/be_visitor_operation/operation_cs.cpp:91
void
OpenDDS::DCPS::DataWriterRemote::update_subscription_params (
const ::OpenDDS::DCPS::RepoId & readerId,
const ::DDS::StringSeq & exprParams)
{
if (!this->is_evaluated ())
{
::CORBA::Object::tao_object_initialize (this);
}
TAO::Arg_Traits< void>::ret_val _tao_retval;
TAO::Arg_Traits< ::OpenDDS::DCPS::GUID_t>::in_arg_val _tao_readerId (readerId);
TAO::Arg_Traits< ::DDS::StringSeq>::in_arg_val _tao_exprParams (exprParams);
TAO::Argument *_the_tao_operation_signature [] =
{
&_tao_retval,
&_tao_readerId,
&_tao_exprParams
};
TAO::Invocation_Adapter _tao_call (
this,
_the_tao_operation_signature,
3,
"update_subscription_params",
26,
TAO::TAO_CO_NONE | TAO::TAO_CO_THRU_POA_STRATEGY
);
_tao_call.invoke (0, 0);
}
OpenDDS::DCPS::DataWriterRemote::DataWriterRemote (void)
{
}
OpenDDS::DCPS::DataWriterRemote::~DataWriterRemote (void)
{
}
OpenDDS::DCPS::DataWriterRemote_ptr
OpenDDS::DCPS::DataWriterRemote::_narrow (
::CORBA::Object_ptr _tao_objref)
{
return
TAO::Narrow_Utils<DataWriterRemote>::narrow (
_tao_objref,
"IDL:OpenDDS/DCPS/DataWriterRemote:1.0");
}
OpenDDS::DCPS::DataWriterRemote_ptr
OpenDDS::DCPS::DataWriterRemote::_unchecked_narrow (
::CORBA::Object_ptr _tao_objref)
{
return
TAO::Narrow_Utils<DataWriterRemote>::unchecked_narrow (
_tao_objref);
}
OpenDDS::DCPS::DataWriterRemote_ptr
OpenDDS::DCPS::DataWriterRemote::_nil (void)
{
return 0;
}
OpenDDS::DCPS::DataWriterRemote_ptr
OpenDDS::DCPS::DataWriterRemote::_duplicate (DataWriterRemote_ptr obj)
{
if (! ::CORBA::is_nil (obj))
{
obj->_add_ref ();
}
return obj;
}
void
OpenDDS::DCPS::DataWriterRemote::_tao_release (DataWriterRemote_ptr obj)
{
::CORBA::release (obj);
}
::CORBA::Boolean
OpenDDS::DCPS::DataWriterRemote::_is_a (const char *value)
{
if (
ACE_OS::strcmp (
value,
"IDL:OpenDDS/DCPS/DataWriterRemote:1.0"
) == 0 ||
ACE_OS::strcmp (
value,
"IDL:omg.org/CORBA/Object:1.0"
) == 0
)
{
return true; // success using local knowledge
}
else
{
return this->::CORBA::Object::_is_a (value);
}
}
const char* OpenDDS::DCPS::DataWriterRemote::_interface_repository_id (void) const
{
return "IDL:OpenDDS/DCPS/DataWriterRemote:1.0";
}
::CORBA::Boolean
OpenDDS::DCPS::DataWriterRemote::marshal (TAO_OutputCDR &cdr)
{
return (cdr << this);
}
// TAO_IDL - Generated from
// be/be_visitor_interface/cdr_op_cs.cpp:54
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
::CORBA::Boolean operator<< (
TAO_OutputCDR &strm,
const OpenDDS::DCPS::DataWriterRemote_ptr _tao_objref)
{
::CORBA::Object_ptr _tao_corba_obj = _tao_objref;
return (strm << _tao_corba_obj);
}
::CORBA::Boolean operator>> (
TAO_InputCDR &strm,
OpenDDS::DCPS::DataWriterRemote_ptr &_tao_objref)
{
::CORBA::Object_var obj;
if (!(strm >> obj.inout ()))
{
return false;
}
typedef ::OpenDDS::DCPS::DataWriterRemote RHS_SCOPED_NAME;
// Narrow to the right type.
_tao_objref =
TAO::Narrow_Utils<RHS_SCOPED_NAME>::unchecked_narrow (obj.in ());
return true;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 23.181102 | 92 | 0.677989 | [
"object"
] |
1826d64e399915b5c79735e2c5657ac8426025e8 | 4,238 | cpp | C++ | src/decomp0.cpp | jim-bo/silp2 | 1186a84b2570af0e4ed305ddfff8f931e012eadf | [
"MIT"
] | 1 | 2018-01-29T05:00:43.000Z | 2018-01-29T05:00:43.000Z | src/decomp0.cpp | jim-bo/silp2 | 1186a84b2570af0e4ed305ddfff8f931e012eadf | [
"MIT"
] | 1 | 2016-01-31T13:13:10.000Z | 2016-02-02T14:16:05.000Z | src/decomp0.cpp | jim-bo/silp2 | 1186a84b2570af0e4ed305ddfff8f931e012eadf | [
"MIT"
] | null | null | null | /*
* decompose.cpp
*
* Created on: Feb 27, 2012
* Author: jlindsay
*/
// header
#include "decompose.h"
// namespaces
using namespace std;
using namespace ogdf;
// I/O buffer.
char BUFFER [512];
/*
* helper functions
*/
// breaks string at tab.
void tokenize(string txt, vector<string> & result){
// clear result.
result.clear();
// define seperator.
boost::char_separator<char> sep("\t");
// tokenize the line.
boost::tokenizer<boost::char_separator<char> > tokens(txt, sep);
// add tokens to vector.
BOOST_FOREACH(string t, tokens){
result.push_back(t);
}
}
Graph load_graph(const char * file_path){
Graph G;
string line;
vector<string> tokens;
ifstream fin(file_path);
if( fin.is_open() == true ){
// grab the header.
getline(fin, line);
tokenize(line, tokens);
// parse.
int num_nodes = atoi(tokens[0].c_str());
int num_edges = atoi(tokens[1].c_str());
// add the nodes.
Array<node> nlist(0, num_nodes);
for(int i=0; i<num_nodes; i++){
nlist[i] = G.newNode();
}
// add the edges.
int p, q;
for(int i=0; i<num_edges; i++){
getline(fin, line);
tokenize(line, tokens);
p = atoi(tokens[0].c_str());
q = atoi(tokens[1].c_str());
G.newEdge(nlist[p], nlist[q]);
}
} else {
WRITE_ERR("bad input file\n");
exit(1);
}
// close the file.
fin.close();
// return the graph.
return G;
}
int main(int argc, char* argv[]) {
// arguments.
const char * in_file = argv[1];
const char * out_file = argv[2];
// read the graph.
WRITE_OUT("loading graph\n");
Graph G = load_graph(in_file);
// sanity check.
if( isConnected(G) == false ){
WRITE_ERR("not connected?\n");
exit(1);
}
// perform decomposition.
WRITE_OUT("performing decomposition\n");
BCTree D(G, false);
sprintf(BUFFER, "Bnodes: %d\nCnode: %d\n", D.numberOfBComps(), D.numberOfCComps());
WRITE_OUT(BUFFER);
// get the tree.
const Graph &T = D.bcTree();
// open output file.
FILE * fout = fopen(out_file, "w");
// identify root of bcTree
node root = NULL;
node n;
edge e;
int cnt;
forall_nodes(n, T){
// count outgoing edges.
cnt = 0;
forall_adj_edges(e, n) {
if(e->source() != n) continue;
cnt += 1;
}
// die once we find it.
if( cnt == 0 ){
root = n;
break;
}
}
// sanity.
if( root == NULL){
WRITE_ERR("couldn't find a root in bcTREE\n");
exit(1);
}
// write the node entries and sets.
WRITE_OUT("writing components\n");
map<int, int> compmap;
set<int> comp;
set<int>::iterator cit;
SListIterator<edge> eit;
int cidx = 0;
forall_nodes(n, T){
if( D.typeOfBNode(n) == D.BComp ){
// get a list of edges.
SList<edge> cedges = D.hEdges(n);
// build a set of original nodes.
comp.clear();
for(eit=cedges.begin(); eit.valid(); ++eit){
e = *eit;
comp.insert(D.original(e->source())->index());
comp.insert(D.original(e->target())->index());
}
// assign id.
compmap[n->index()] = cidx;
cidx++;
// write out id.
fprintf(fout, "N\t%d", compmap[n->index()]);
// write out sets.
for(cit=comp.begin(); cit!=comp.end(); cit++){
fprintf(fout, "\t%d", *cit);
}
fprintf(fout, "\n");
}
}
// free up memory.
comp.clear();
// write the cut edges.
WRITE_OUT("writing cuts\n");
set<int> parents, children;
set<int>::iterator pit;
edge e1, e2;
node s, t, c;
forall_nodes(n, T){
if( D.typeOfBNode(n) == D.CComp ){
// build set of parents.
parents.clear();
forall_adj_edges(e1, n) {
if(e1->source() != n) continue;
parents.insert(compmap[e1->target()->index()]);
}
// build set of children.
children.clear();
forall_adj_edges(e1, n) {
if(e1->target() != n) continue;
children.insert(compmap[e1->source()->index()]);
}
// identify the cut-node.
forall_adj_edges(e1, n) {
if(e1->source() != n) continue;
c = D.original(D.cutVertex(n, e1->source()));
break;
}
// write all combinations.
for(pit=parents.begin(); pit!=parents.end(); pit++){
for(cit=children.begin(); cit!=children.end(); cit++){
fprintf(fout, "E\t%d\t%d\t%d\n", *pit, *cit, c->index());
}
}
}
}
// close output.
fclose(fout);
}
| 19.351598 | 84 | 0.590137 | [
"vector"
] |
1828364eca5e9827f369a1dd5b156eda1619005f | 7,863 | cpp | C++ | aws-cpp-sdk-wafv2/source/model/Statement.cpp | grujicbr/aws-sdk-cpp | bdd43c178042f09c6739645e3f6cd17822a7c35c | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-wafv2/source/model/Statement.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-wafv2/source/model/Statement.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/wafv2/model/Statement.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace WAFV2
{
namespace Model
{
Statement::Statement() :
m_byteMatchStatementHasBeenSet(false),
m_sqliMatchStatementHasBeenSet(false),
m_xssMatchStatementHasBeenSet(false),
m_sizeConstraintStatementHasBeenSet(false),
m_geoMatchStatementHasBeenSet(false),
m_ruleGroupReferenceStatementHasBeenSet(false),
m_iPSetReferenceStatementHasBeenSet(false),
m_regexPatternSetReferenceStatementHasBeenSet(false),
m_rateBasedStatementHasBeenSet(false),
m_andStatementHasBeenSet(false),
m_orStatementHasBeenSet(false),
m_notStatementHasBeenSet(false),
m_managedRuleGroupStatementHasBeenSet(false)
{
}
Statement::Statement(JsonView jsonValue) :
m_byteMatchStatementHasBeenSet(false),
m_sqliMatchStatementHasBeenSet(false),
m_xssMatchStatementHasBeenSet(false),
m_sizeConstraintStatementHasBeenSet(false),
m_geoMatchStatementHasBeenSet(false),
m_ruleGroupReferenceStatementHasBeenSet(false),
m_iPSetReferenceStatementHasBeenSet(false),
m_regexPatternSetReferenceStatementHasBeenSet(false),
m_rateBasedStatementHasBeenSet(false),
m_andStatementHasBeenSet(false),
m_orStatementHasBeenSet(false),
m_notStatementHasBeenSet(false),
m_managedRuleGroupStatementHasBeenSet(false)
{
*this = jsonValue;
}
const RateBasedStatement& Statement::GetRateBasedStatement() const{ return m_rateBasedStatement[0]; }
bool Statement::RateBasedStatementHasBeenSet() const { return m_rateBasedStatementHasBeenSet; }
void Statement::SetRateBasedStatement(const RateBasedStatement& value) { m_rateBasedStatementHasBeenSet = true; m_rateBasedStatement.resize(1); m_rateBasedStatement[0] = value; }
void Statement::SetRateBasedStatement(RateBasedStatement&& value) { m_rateBasedStatementHasBeenSet = true; m_rateBasedStatement.resize(1); m_rateBasedStatement[0] = std::move(value); }
Statement& Statement::WithRateBasedStatement(const RateBasedStatement& value) { SetRateBasedStatement(value); return *this;}
Statement& Statement::WithRateBasedStatement(RateBasedStatement&& value) { SetRateBasedStatement(std::move(value)); return *this;}
const NotStatement& Statement::GetNotStatement() const{ return m_notStatement[0]; }
bool Statement::NotStatementHasBeenSet() const { return m_notStatementHasBeenSet; }
void Statement::SetNotStatement(const NotStatement& value) { m_notStatementHasBeenSet = true; m_notStatement.resize(1); m_notStatement[0] = value; }
void Statement::SetNotStatement(NotStatement&& value) { m_notStatementHasBeenSet = true; m_notStatement.resize(1); m_notStatement[0] = std::move(value); }
Statement& Statement::WithNotStatement(const NotStatement& value) { SetNotStatement(value); return *this;}
Statement& Statement::WithNotStatement(NotStatement&& value) { SetNotStatement(std::move(value)); return *this;}
Statement& Statement::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("ByteMatchStatement"))
{
m_byteMatchStatement = jsonValue.GetObject("ByteMatchStatement");
m_byteMatchStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("SqliMatchStatement"))
{
m_sqliMatchStatement = jsonValue.GetObject("SqliMatchStatement");
m_sqliMatchStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("XssMatchStatement"))
{
m_xssMatchStatement = jsonValue.GetObject("XssMatchStatement");
m_xssMatchStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("SizeConstraintStatement"))
{
m_sizeConstraintStatement = jsonValue.GetObject("SizeConstraintStatement");
m_sizeConstraintStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("GeoMatchStatement"))
{
m_geoMatchStatement = jsonValue.GetObject("GeoMatchStatement");
m_geoMatchStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("RuleGroupReferenceStatement"))
{
m_ruleGroupReferenceStatement = jsonValue.GetObject("RuleGroupReferenceStatement");
m_ruleGroupReferenceStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("IPSetReferenceStatement"))
{
m_iPSetReferenceStatement = jsonValue.GetObject("IPSetReferenceStatement");
m_iPSetReferenceStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("RegexPatternSetReferenceStatement"))
{
m_regexPatternSetReferenceStatement = jsonValue.GetObject("RegexPatternSetReferenceStatement");
m_regexPatternSetReferenceStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("RateBasedStatement"))
{
m_rateBasedStatement.resize(1);
m_rateBasedStatement[0] = jsonValue.GetObject("RateBasedStatement");
m_rateBasedStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("AndStatement"))
{
m_andStatement = jsonValue.GetObject("AndStatement");
m_andStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("OrStatement"))
{
m_orStatement = jsonValue.GetObject("OrStatement");
m_orStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("NotStatement"))
{
m_notStatement.resize(1);
m_notStatement[0] = jsonValue.GetObject("NotStatement");
m_notStatementHasBeenSet = true;
}
if(jsonValue.ValueExists("ManagedRuleGroupStatement"))
{
m_managedRuleGroupStatement = jsonValue.GetObject("ManagedRuleGroupStatement");
m_managedRuleGroupStatementHasBeenSet = true;
}
return *this;
}
JsonValue Statement::Jsonize() const
{
JsonValue payload;
if(m_byteMatchStatementHasBeenSet)
{
payload.WithObject("ByteMatchStatement", m_byteMatchStatement.Jsonize());
}
if(m_sqliMatchStatementHasBeenSet)
{
payload.WithObject("SqliMatchStatement", m_sqliMatchStatement.Jsonize());
}
if(m_xssMatchStatementHasBeenSet)
{
payload.WithObject("XssMatchStatement", m_xssMatchStatement.Jsonize());
}
if(m_sizeConstraintStatementHasBeenSet)
{
payload.WithObject("SizeConstraintStatement", m_sizeConstraintStatement.Jsonize());
}
if(m_geoMatchStatementHasBeenSet)
{
payload.WithObject("GeoMatchStatement", m_geoMatchStatement.Jsonize());
}
if(m_ruleGroupReferenceStatementHasBeenSet)
{
payload.WithObject("RuleGroupReferenceStatement", m_ruleGroupReferenceStatement.Jsonize());
}
if(m_iPSetReferenceStatementHasBeenSet)
{
payload.WithObject("IPSetReferenceStatement", m_iPSetReferenceStatement.Jsonize());
}
if(m_regexPatternSetReferenceStatementHasBeenSet)
{
payload.WithObject("RegexPatternSetReferenceStatement", m_regexPatternSetReferenceStatement.Jsonize());
}
if(m_rateBasedStatementHasBeenSet)
{
payload.WithObject("RateBasedStatement", m_rateBasedStatement[0].Jsonize());
}
if(m_andStatementHasBeenSet)
{
payload.WithObject("AndStatement", m_andStatement.Jsonize());
}
if(m_orStatementHasBeenSet)
{
payload.WithObject("OrStatement", m_orStatement.Jsonize());
}
if(m_notStatementHasBeenSet)
{
payload.WithObject("NotStatement", m_notStatement[0].Jsonize());
}
if(m_managedRuleGroupStatementHasBeenSet)
{
payload.WithObject("ManagedRuleGroupStatement", m_managedRuleGroupStatement.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace WAFV2
} // namespace Aws
| 29.56015 | 184 | 0.775658 | [
"model"
] |
182a7f3e535771f83b80942bc48aee614e6abffa | 2,678 | hpp | C++ | workspace/globber.hpp | 5cript/minide | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | [
"MIT"
] | null | null | null | workspace/globber.hpp | 5cript/minide | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | [
"MIT"
] | 1 | 2018-01-26T00:06:19.000Z | 2018-01-26T00:06:54.000Z | workspace/globber.hpp | 5cript/minide | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | [
"MIT"
] | null | null | null | #pragma once
#include "../filesystem.hpp"
#include <string>
namespace MinIDE
{
class Globber
{
public:
/**
* @param root The root directory to glob files (or dirs) in.
* @param directories Collect directories instead of files if true.
*/
Globber(std::string root, bool directories = false);
void setBlackList(std::vector <std::string> const& blackList);
void setDirectoryBlackList(std::vector <std::string> const& blackList);
std::vector <path> glob(std::string const& mask, bool prependRoot);
std::vector <path> globRecursive(std::string const& mask, bool prependRoot);
std::vector <path> glob(std::vector <std::string> const& masks, bool prependRoot);
std::vector <path> globRecursive(std::vector <std::string> const& masks, bool prependRoot);
private:
template <typename IteratorT>
void globImpl(IteratorT& i, std::vector <path>& result, std::vector<std::string> const& masks, bool prependRoot)
{
if (!exists(i->status())) // does p actually exist?
return;
bool cont = false;
if (!directories_ && is_regular_file(i->status()))
cont = true;
else if (directories_ && is_directory(i->status()))
cont = true;
if (!cont)
return;
auto pathTemp = boost::filesystem::relative(i->path(), root_).string();
std::replace(pathTemp.begin(), pathTemp.end(), '\\', '/');
auto p = path{pathTemp};
if (isBlacklisted(p))
return;
bool anyMask = masks.empty();
for (auto const& mask : masks)
{
if (checkMask(p, mask))
{
anyMask = true;
break;
}
}
if (!anyMask)
return;
if (prependRoot)
result.push_back(root_ / p);
else
result.push_back(p);
}
/**
* Check for a *? wildcard match.
*/
bool checkMask(path const& p, std::string const& mask);
/**
* Returns whether the path is within the black list or not.
*
* @return Return true if path is BLACKLISTED.
*/
bool isBlacklisted(path const& p);
private:
path root_;
std::vector <std::string> blackList_;
std::vector <std::string> dirBlackList_;
bool directories_;
};
}
| 30.781609 | 121 | 0.505975 | [
"vector"
] |
182fcc55859528bc97122cb25c4cc61bc667c1a9 | 15,863 | hpp | C++ | src/sqlixx/statement.hpp | dmitigr/sqlixx | 8949f08a93c1bbbfe45ae92be1b58ad2b6f2e3db | [
"Apache-2.0"
] | 4 | 2020-03-21T02:26:09.000Z | 2022-02-02T08:19:17.000Z | src/sqlixx/statement.hpp | dmitigr/sqlixx | 8949f08a93c1bbbfe45ae92be1b58ad2b6f2e3db | [
"Apache-2.0"
] | 1 | 2021-11-10T05:50:42.000Z | 2021-11-17T15:13:03.000Z | src/sqlixx/statement.hpp | dmitigr/sqlixx | 8949f08a93c1bbbfe45ae92be1b58ad2b6f2e3db | [
"Apache-2.0"
] | null | null | null | // -*- C++ -*-
//
// Copyright 2022 Dmitry Igrishin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef DMITIGR_SQLIXX_STATEMENT_HPP
#define DMITIGR_SQLIXX_STATEMENT_HPP
#include "conversions.hpp"
#include "../base/assert.hpp"
#include <sqlite3.h>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <new>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
namespace dmitigr::sqlixx {
class Statement;
namespace detail {
template<typename F, typename = void>
struct Execute_callback_traits final {
constexpr static bool is_valid = false;
};
template<typename F>
struct Execute_callback_traits<F,
std::enable_if_t<std::is_invocable_v<F, const Statement&>>> final {
using Result = std::invoke_result_t<F, const Statement&>;
constexpr static bool is_result_void = std::is_same_v<Result, void>;
constexpr static bool is_valid =
std::is_invocable_r_v<bool, F, const Statement&> || is_result_void;
constexpr static bool has_error_parameter = false;
};
template<typename F>
struct Execute_callback_traits<F,
std::enable_if_t<std::is_invocable_v<F, const Statement&, int>>> final {
using Result = std::invoke_result_t<F, const Statement&, int>;
constexpr static bool is_result_void = std::is_same_v<Result, void>;
constexpr static bool is_valid =
std::is_invocable_r_v<bool, F, const Statement&, int> || is_result_void;
constexpr static bool has_error_parameter = true;
};
} // namespace detail
/// A prepared statement.
class Statement final {
public:
/// The destructor.
~Statement()
{
try {
close();
} catch(const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
} catch(...) {}
}
/// The constructor.
explicit Statement(sqlite3_stmt* const handle = {})
: handle_{handle}
{}
/// @overload
Statement(sqlite3* const handle, const std::string_view sql,
const unsigned int flags = 0)
{
if (!handle)
throw Exception{"cannot create SQLite statement using invalid handle"};
if (const int r = sqlite3_prepare_v3(handle, sql.data(),
static_cast<int>(sql.size()), flags, &handle_, nullptr); r != SQLITE_OK)
throw Sqlite_exception{r, std::string{"cannot prepare SQLite statement "}
.append(sql).append(" (").append(sqlite3_errmsg(handle)).append(")")};
DMITIGR_ASSERT(handle_);
}
/// Non-copyable.
Statement(const Statement&) = delete;
/// Non-copyable.
Statement& operator=(const Statement&) = delete;
/// The move constructor.
Statement(Statement&& rhs) noexcept
{
Statement tmp;
tmp.swap(rhs); // reset rhs to the default state
swap(tmp);
}
/// The move assignment operator.
Statement& operator=(Statement&& rhs) noexcept
{
if (this != &rhs) {
Statement tmp{std::move(rhs)};
swap(tmp);
}
return *this;
}
/// The swap operation.
void swap(Statement& other) noexcept
{
using std::swap;
swap(last_step_result_, other.last_step_result_);
swap(handle_, other.handle_);
}
/// @returns The underlying handle.
sqlite3_stmt* handle() const noexcept
{
return handle_;
}
/// @returns `true` if this object keeps handle, or `false` otherwise.
explicit operator bool() const noexcept
{
return handle_;
}
/// @returns The released handle.
sqlite3_stmt* release() noexcept
{
auto* const result = handle_;
last_step_result_ = -1;
handle_ = {};
return result;
}
/**
* @brief Closes the statement.
*
* @returns Non SQLITE_OK if the most recent execution of statement failed.
*/
int close()
{
const int result = sqlite3_finalize(handle_);
last_step_result_ = -1;
handle_ = {};
return result;
}
// ---------------------------------------------------------------------------
/// @name Parameters
/// @remarks Parameter indexes starts from zero!
/// @{
/**
* @returns The number of parameters.
*
* @par Requires
* `handle()`.
*/
int parameter_count() const
{
if (!handle_)
throw Exception{"cannot get parameter count of invalid SQLite statement"};
return sqlite3_bind_parameter_count(handle_);
}
/**
* @returns The parameter index, or -1 if no parameter `name` presents.
*
* @par Requires
* `handle() && name`.
*/
int parameter_index(const char* const name) const
{
if (!handle_)
throw Exception{"cannot get parameter index of invalid SQLite statement"};
else if (!name)
throw Exception{"cannot get SQLite statement parameter index using "
"invalid name"};
return sqlite3_bind_parameter_index(handle_, name) - 1;
}
/**
* @returns The parameter index.
*
* @par Requires
* `handle() && name`.
*/
int parameter_index_throw(const char* const name) const
{
const int index = parameter_index(name);
if (index < 0)
throw Exception{std::string{"SQLite statement has no parameter "}
.append(name)};
return index;
}
/**
* @returns The name of the parameter by the `index`.
*
* @par Requires
* `handle() && index < parameter_count()`.
*/
std::string parameter_name(const int index) const
{
if (!handle_)
throw Exception{"cannot get parameter name of invalid SQLite statement"};
else if (!(index < parameter_count()))
throw Exception{"cannot get SQLite statement parameter name using "
"invalid index"};
return sqlite3_column_name(handle_, index + 1);
}
/**
* @brief Binds all the parameters with NULL.
*
* @par Requires
* `handle()`.
*/
void bind_null()
{
if (!handle_)
throw Exception{"cannot bind NULL to parameters of invalid SQLite "
"statement"};
detail::check_bind(handle_, sqlite3_clear_bindings(handle_));
}
/**
* @brief Binds the parameter of the specified index with NULL.
*
* @par Requires
* `handle() && index < parameter_count()`.
*/
void bind_null(const int index)
{
if (!handle_)
throw Exception{"cannot bind NULL to a parameter of invalid SQLite "
"statement"};
else if (!(index < parameter_count()))
throw Exception{"cannot bind NULL to a parameter of SQLite statement "
"using invalid index"};
detail::check_bind(handle_, sqlite3_bind_null(handle_, index + 1));
}
/// @overload
void bind_null(const char* const name)
{
bind_null(parameter_index_throw(name));
}
/**
* @brief Binds the parameter of the specified index with `value`.
*
* @par Requires
* `handle() && index < parameter_count()`.
*
* @remarks `value` is assumed to be UTF-8 encoded.
*/
void bind(const int index, const char* const value)
{
if (!handle_)
throw Exception{"cannot bind a text to a parameter of invalid SQLite "
"statement"};
else if (!(index < parameter_count()))
throw Exception{"cannot bind a text to a parameter of SQLite statement "
"using invalid index"};
detail::check_bind(handle_,
sqlite3_bind_text(handle_, index + 1, value, -1, SQLITE_STATIC));
}
/// @overload
void bind(const char* const name, const char* const value)
{
bind(parameter_index_throw(name), value);
}
/**
* @brief Binds the parameter of the specified index with the value of type `T`.
*
* @param index A zero-based index of the parameter.
* @param value A value to bind. If this parameter is `lvalue`, then it's
* assumed that the value is a constant and does not need to be copied. If this
* parameter is `rvalue`, then it's assumed to be destructed after this function
* returns, so SQLite is required to make a private copy of the value before
* return.
*
* @par Requires
* `handle() && index < parameter_count()`.
*/
template<typename T>
void bind(const int index, T&& value)
{
if (!handle_)
throw Exception{"cannot bind a value to a parameter of invalid SQLite "
"statement"};
else if (!(index < parameter_count()))
throw Exception{"cannot bind a value to a parameter of SQLite statement "
"using invalid index"};
using U = std::decay_t<T>;
Conversions<U>::bind(handle_, index + 1, std::forward<T>(value));
}
/// @overload
template<typename T>
void bind(const char* const name, T&& value)
{
bind(parameter_index_throw(name), std::forward<T>(value));
}
/**
* @brief Binds parameters by indexes in range [0, sizeof ... (values)).
*
* @details In other words:
* @code bind_many(value1, value2, value3) @endcode
* equivalently to
* @code (bind(0, value1), bind(1, value1), bind(2, value2)) @endcode
*
* @see bind().
*/
template<typename ... Types>
void bind_many(Types&& ... values)
{
bind_many__(std::make_index_sequence<sizeof ... (Types)>{},
std::forward<Types>(values)...);
}
/// @}
// ---------------------------------------------------------------------------
/// @name Execution
/// @{
/**
* @brief Executes the prepared statement.
*
* @param callback A function to be called for each retrieved row. The callback:
* -# can be defined with a parameter of type `const Statement&`. The exception
* will be thrown on error in this case.
* -# can be defined with two parameters of type `const Statement&` and `int`.
* In case of error an error code will be passed as the second argument of
* the callback instead of throwing exception and execution will be stopped
* after callback returns. In case of success, `0` will be passed as the second
* argument of the callback.
* -# can return a value convertible to `bool` to indicate should the execution
* to be continued after the callback returns or not;
* -# can return `void` to indicate that execution must be proceed until a
* completion or an error.
* @param values Values to bind with parameters. Binding will take place if this
* method is never been called before for this instance or if the last value it
* return was `SQLITE_DONE`.
*
* @par Requires
* `handle()`.
*
* @remarks If the last value of this method was `SQLITE_DONE` then `reset()`
* will be called automatically.
*
* @returns The result of `sqlite3_step()`.
*
* @see reset().
*/
template<typename F, typename ... Types>
std::enable_if_t<detail::Execute_callback_traits<F>::is_valid, int>
execute(F&& callback, Types&& ... values)
{
if (!handle_)
throw Exception{"cannot execute invalid SQLite statement"};
if (last_step_result_ == SQLITE_DONE)
reset();
if (last_step_result_ < 0 || last_step_result_ == SQLITE_DONE)
bind_many(std::forward<Types>(values)...);
while (true) {
using Traits = detail::Execute_callback_traits<F>;
switch (last_step_result_ = sqlite3_step(handle_)) {
case SQLITE_ROW:
if constexpr (!Traits::is_result_void) {
if constexpr (!Traits::has_error_parameter) {
if (!callback(static_cast<const Statement&>(*this)))
return last_step_result_;
} else {
if (!callback(static_cast<const Statement&>(*this), last_step_result_))
return last_step_result_;
}
} else {
if constexpr (!Traits::has_error_parameter)
callback(static_cast<const Statement&>(*this));
else
callback(static_cast<const Statement&>(*this), last_step_result_);
}
continue;
case SQLITE_DONE:
return last_step_result_;
default:
if constexpr (Traits::has_error_parameter) {
callback(static_cast<const Statement&>(*this), last_step_result_);
return last_step_result_;
} else
throw Sqlite_exception{last_step_result_,
std::string{"SQLite statement execution failed"}
.append(" (").append(sqlite3_errmsg(sqlite3_db_handle(handle_)))
.append(")")};
}
}
}
/// @overload
template<typename ... Types>
int execute(Types&& ... values)
{
return execute([](const auto&){return true;}, std::forward<Types>(values)...);
}
/// Resets the statement back to its initial state, ready to be executed.
int reset()
{
last_step_result_ = -1;
return sqlite3_reset(handle_);
}
/// @}
// ---------------------------------------------------------------------------
/// @name Result
/// @{
/**
* @returns The number of columns.
*
* @par Requires
* `handle()`.
*/
int column_count() const
{
if (!handle_)
throw Exception{"cannot get result column count of invalid SQLite "
"statement"};
return sqlite3_column_count(handle_);
}
/**
* @returns The column index, or -1 if no column `name` presents.
*
* @par Requires
* `handle() && name`.
*/
int column_index(const char* const name) const
{
if (!handle_)
throw Exception{"cannot get result column index of invalid SQLite "
"statement"};
else if (!name)
throw Exception{"cannot get result column index of SQLite statement "
"using invalid name"};
const int count = column_count();
for (int i = 0; i < count; ++i) {
if (const char* const nm = sqlite3_column_name(handle_, i)) {
if (!std::strcmp(name, nm))
return i;
} else
throw std::bad_alloc{};
}
return -1;
}
/**
* @returns The column index.
*
* @par Requires
* `handle() && name`.
*/
int column_index_throw(const char* const name) const
{
const int index = column_index(name);
if (index < 0)
throw Exception{std::string{"SQLite result has no column "}.append(name)};
return index;
}
/**
* @returns The name of the column by the `index`.
*
* @par Requires
* `handle() && index < column_count()`.
*/
std::string column_name(const int index) const
{
if (!handle_)
throw Exception{"cannot get result column name of invalid SQLite "
"statement"};
else if (!(index < column_count()))
throw Exception{"cannot get result column count of SQLite statement "
"using invalid index"};
return sqlite3_column_name(handle_, index);
}
/**
* @returns The result of statement execution.
*
* @tparam T The resulting type of statement execution result.
*
* @par Requires
* `handle() && index < column_count()`.
*/
template<typename T>
T result(const int index) const
{
if (!handle_)
throw Exception{"cannot get result column value of invalid SQLite "
"statement"};
else if (!(index < column_count()))
throw Exception{"cannot get result column value of SQLite statement "
"using invalid index"};
using U = std::decay_t<T>;
return Conversions<U>::result(handle_, index);
}
/// @overload
template<typename T>
T result(const char* const name) const
{
return result<T>(column_index_throw(name));
}
/// @}
private:
int last_step_result_{-1};
sqlite3_stmt* handle_{};
template<std::size_t ... I, typename ... Types>
void bind_many__(std::index_sequence<I...>, Types&& ... values)
{
(bind(static_cast<int>(I), std::forward<Types>(values)), ...);
}
};
} // namespace dmitigr::sqlixx
#endif // DMITIGR_SQLIXX_STATEMENT_HPP
| 27.684119 | 83 | 0.633424 | [
"object"
] |
183448ea1d6489658d4c846d655711ac229e3eaa | 1,091 | cpp | C++ | c++/test/test_factor_rev.cpp | jacksonloper/celerite2 | e413e28dc43ba33e67960b51a9cbbac43c2f58df | [
"MIT"
] | 38 | 2020-10-10T02:43:53.000Z | 2022-03-30T09:59:21.000Z | c++/test/test_factor_rev.cpp | jacksonloper/celerite2 | e413e28dc43ba33e67960b51a9cbbac43c2f58df | [
"MIT"
] | 34 | 2020-10-06T18:50:47.000Z | 2022-01-28T10:33:04.000Z | c++/test/test_factor_rev.cpp | jacksonloper/celerite2 | e413e28dc43ba33e67960b51a9cbbac43c2f58df | [
"MIT"
] | 6 | 2020-11-09T18:12:54.000Z | 2022-02-03T20:20:59.000Z | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "helpers.hpp"
#include <celerite2/celerite2.h>
using namespace celerite2::test;
using namespace celerite2::core;
TEMPLATE_LIST_TEST_CASE("check the results of factor_rev", "[factor_rev]", TestKernels) {
SETUP_TEST(10);
CoeffVector bc(J);
Vector d, bd(N), bx(N), ba(N);
LowRank W, bW(N, J), bU(N, J), bV(N, J);
Matrix S;
auto func = [](auto x, auto c, auto a, auto U, auto V, auto d, auto W, auto S) {
factor(x, c, a, U, V, d, W, S);
return std::make_tuple(d, W);
};
auto rev = [](auto x, auto c, auto a, auto U, auto V, auto d, auto W, auto S, auto bd, auto bW, auto bx, auto bc, auto ba, auto bU, auto bV) {
factor_rev(x, c, a, U, V, d, W, S, bd, bW, bx, bc, ba, bU, bV);
return std::make_tuple(bx, bc, ba, bU, bV);
};
// Required to compute the initial values
int flag = factor(x, c, a, U, V, d, W, S);
REQUIRE(flag == 0);
REQUIRE(
check_grad(func, rev, std::make_tuple(x, c, a, U, V), std::make_tuple(d, W, S), std::make_tuple(bd, bW), std::make_tuple(bx, bc, ba, bU, bV)));
}
| 31.171429 | 148 | 0.615949 | [
"vector"
] |
1837183b358a38c896f0e7f96d8f6ef626c758f2 | 3,565 | cpp | C++ | modules/task_2/tashirev_i_horiz_scheme/main.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2020-11-20T15:05:12.000Z | 2020-11-20T15:05:12.000Z | modules/task_2/tashirev_i_horiz_scheme/main.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2021-02-13T03:00:05.000Z | 2021-02-13T03:00:05.000Z | modules/task_2/tashirev_i_horiz_scheme/main.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2020-10-11T09:11:57.000Z | 2020-10-11T09:11:57.000Z | // Copyright 2020 Tashirev Ivan
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include "../../../modules/task_2/tashirev_i_horiz_scheme/RibbonHorizontalPattern.h"
TEST(Parallel_Operations_MPI, Test_Matrix4_3) {
const int rows = 4;
const int columns = 3;
std::vector<int> matr;
std::vector<int> vec;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
matr = getMatrix(rows, columns);
vec = getVector(columns);
}
std::vector<int> multiply = multMatrixParallel(matr, rows, columns, vec, columns);
if (rank == 0) {
std::vector<int> multiplyNotParall = multMatrixSeq(matr, rows, columns, vec, columns);
ASSERT_EQ(multiplyNotParall, multiply);
}
}
TEST(Parallel_Operations_MPI, Test_Matrix5_3) {
const int rows = 5;
const int columns = 3;
std::vector<int> matr;
std::vector<int> vec;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
matr = getMatrix(rows, columns);
vec = getVector(columns);
}
std::vector<int> multiply = multMatrixParallel(matr, rows, columns, vec, columns);
if (rank == 0) {
std::vector<int> multiplyNotParall = multMatrixSeq(matr, rows, columns, vec, columns);
ASSERT_EQ(multiplyNotParall, multiply);
}
}
TEST(Parallel_Operations_MPI, Test_Matrix10_10) {
const int rows = 10;
const int columns = 10;
std::vector<int> matr;
std::vector<int> vec;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
matr = getMatrix(rows, columns);
vec = getVector(columns);
}
std::vector<int> multiply = multMatrixParallel(matr, rows, columns, vec, columns);
if (rank == 0) {
std::vector<int> multiplyNotParall = multMatrixSeq(matr, rows, columns, vec, columns);
ASSERT_EQ(multiplyNotParall, multiply);
}
}
TEST(Parallel_Operations_MPI, Test_Matrix10_5) {
const int rows = 10;
const int columns = 5;
std::vector<int> matr;
std::vector<int> vec;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
matr = getMatrix(rows, columns);
vec = getVector(columns);
}
std::vector<int> multiply = multMatrixParallel(matr, rows, columns, vec, columns);
if (rank == 0) {
std::vector<int> multiplyNotParall = multMatrixSeq(matr, rows, columns, vec, columns);
ASSERT_EQ(multiplyNotParall, multiply);
}
}
TEST(Parallel_Operations_MPI, Test_Matrix20_5) {
const int rows = 20;
const int columns = 5;
std::vector<int> matr;
std::vector<int> vec;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
matr = getMatrix(rows, columns);
vec = getVector(columns);
}
std::vector<int> multiply = multMatrixParallel(matr, rows, columns, vec, columns);
if (rank == 0) {
std::vector<int> multiplyNotParall = multMatrixSeq(matr, rows, columns, vec, columns);
ASSERT_EQ(multiplyNotParall, multiply);
}
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 31.548673 | 94 | 0.651613 | [
"vector"
] |
1841ce19736c4a6c05b4e9d4fc6efebdb3ab351b | 4,890 | hpp | C++ | src/graph.hpp | Nash2829/Graph-Algorithms-Book | 388abc036aaa2ec94b790fac0d9b025e1589b5f1 | [
"MIT"
] | null | null | null | src/graph.hpp | Nash2829/Graph-Algorithms-Book | 388abc036aaa2ec94b790fac0d9b025e1589b5f1 | [
"MIT"
] | null | null | null | src/graph.hpp | Nash2829/Graph-Algorithms-Book | 388abc036aaa2ec94b790fac0d9b025e1589b5f1 | [
"MIT"
] | null | null | null | // graph.hpp
#ifndef GRAPH_HPP
#define GRAPH_HPP
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
using Vertex = int;
using Edge = std::pair<Vertex, Vertex>; // first stores vertex and second stores the edge weight
class weightedGraph {
protected:
/**
* Number of Vertices.
*
*/
Vertex V;
/**
* Adjacency list representation.
*
*/
std::vector<Edge> *adj;
/**
* Directed or undirected graph.
*
*/
bool directed;
public:
/**
* @brief Constructs a new weighted Graph object.
*
* @param _V number of vertices in the graph.
* @param _directed default value = false. specify as true if the graph is directed.
*/
weightedGraph(Vertex _V, bool _directed = false) : V(_V), directed(_directed) {
adj = new std::vector<Edge> [V + 1](); // 1-based indexing for vertices
}
/**
* @brief Constructs a new weighted Graph object. It is a copy of an old one.
*
* @param copy the old weighted Graph object to be copied.
*/
weightedGraph(const weightedGraph ©) : V(copy.V), directed(copy.directed) {
adj = new std::vector<Edge> [V + 1]();
for (Vertex i = 0; i <= V; ++i) {
adj[i] = copy.adj[i];
}
}
/**
* @brief Destroys the weighted Graph object.
*
*/
virtual ~weightedGraph() {
delete []adj;
}
/**
* @brief Gets number of vertices
*
* @return Vertex Number of vertices
*/
inline const Vertex getV() const { return V; }
/**
* @brief Gets the Adj[u] vector
*
* @param u Vertex whose adjacency list is needed
* @return const std::vector<Edge>& Returns const reference to weightedGraph::adj[u]
*/
inline const std::vector<Edge>& getAdj(int u) const {
return adj[u];
}
/**
* @brief adds an edge from vertex u to v. If directed is false, also adds an edge
* from v to u.
* @param u vertex from which edge comes out.
* @param v vertex to which edge comes in.
* @param weight the weight of the edge.
*/
void addEdge(Vertex u, Vertex v, Vertex weight) {
adj[u].push_back(Edge(v, weight));
if (not directed)
adj[v].push_back(Edge(u, weight));
}
};
class Graph {
protected:
/**
* Number of Vertices.
*
*/
Vertex V;
/**
* Adjacency list representation.
*
*/
std::vector<Vertex> *adj;
/**
* Directed or undirected graph.
*
*/
bool directed;
public:
/**
* @brief Constructs a new Graph object.
*
* @param _V number of vertices in the graph.
* @param _directed default value = false. Specify as true if the graph is directed
*/
Graph(Vertex _V, bool _directed = false) : V(_V), directed(_directed) {
adj = new std::vector<Vertex> [V + 1](); // 1-based indexing for vertices
}
/**
* @brief Constructs a new Graph object. It is a copy of an old one.
*
* @param copy the old Graph object to be copied.
*/
Graph(const Graph ©) : V(copy.V), directed(copy.directed) {
adj = new std::vector<Vertex> [V + 1]();
for (Vertex i = 0; i <= V; ++i) {
adj[i] = copy.adj[i];
}
}
/**
* @brief Destroys the Graph object.
*
*/
virtual ~Graph() {
delete []adj;
}
/**
* @brief Gets number of vertices
*
* @return Vertex Number of vertices
*/
inline const Vertex getV() const { return V; }
/**
* @brief Gets the Adj[u] vector
*
* @param u Vertex whose adjacency list is needed
* @return const std::vector<Vertex>& Returns const reference to Graph::adj[u]
*/
inline const std::vector<Vertex>& getAdj(int u) const {
return adj[u];
}
/**
* @brief adds an edge from vertex u to v. If directed is false, also adds an edge
* from v to u.
* @param u vertex from which edge comes out.
* @param v vertex to which edge comes in.
*/
void addEdge(Vertex u, Vertex v) {
adj[u].push_back(v);
if (not directed)
adj[v].push_back(u);
}
};
#endif
| 26.576087 | 96 | 0.493456 | [
"object",
"vector"
] |
1849ac70ae021250942fcab1e4f0a878fe35d30a | 1,961 | cpp | C++ | aws-cpp-sdk-frauddetector/source/model/TrainingMetrics.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-frauddetector/source/model/TrainingMetrics.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-frauddetector/source/model/TrainingMetrics.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/frauddetector/model/TrainingMetrics.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FraudDetector
{
namespace Model
{
TrainingMetrics::TrainingMetrics() :
m_auc(0.0),
m_aucHasBeenSet(false),
m_metricDataPointsHasBeenSet(false)
{
}
TrainingMetrics::TrainingMetrics(JsonView jsonValue) :
m_auc(0.0),
m_aucHasBeenSet(false),
m_metricDataPointsHasBeenSet(false)
{
*this = jsonValue;
}
TrainingMetrics& TrainingMetrics::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("auc"))
{
m_auc = jsonValue.GetDouble("auc");
m_aucHasBeenSet = true;
}
if(jsonValue.ValueExists("metricDataPoints"))
{
Array<JsonView> metricDataPointsJsonList = jsonValue.GetArray("metricDataPoints");
for(unsigned metricDataPointsIndex = 0; metricDataPointsIndex < metricDataPointsJsonList.GetLength(); ++metricDataPointsIndex)
{
m_metricDataPoints.push_back(metricDataPointsJsonList[metricDataPointsIndex].AsObject());
}
m_metricDataPointsHasBeenSet = true;
}
return *this;
}
JsonValue TrainingMetrics::Jsonize() const
{
JsonValue payload;
if(m_aucHasBeenSet)
{
payload.WithDouble("auc", m_auc);
}
if(m_metricDataPointsHasBeenSet)
{
Array<JsonValue> metricDataPointsJsonList(m_metricDataPoints.size());
for(unsigned metricDataPointsIndex = 0; metricDataPointsIndex < metricDataPointsJsonList.GetLength(); ++metricDataPointsIndex)
{
metricDataPointsJsonList[metricDataPointsIndex].AsObject(m_metricDataPoints[metricDataPointsIndex].Jsonize());
}
payload.WithArray("metricDataPoints", std::move(metricDataPointsJsonList));
}
return payload;
}
} // namespace Model
} // namespace FraudDetector
} // namespace Aws
| 23.070588 | 130 | 0.745538 | [
"model"
] |
184a0942fae64f93279316eaecb747f5e0a3a21f | 11,652 | cpp | C++ | src/main.cpp | ernestocanibano/CarND-Path-Planning-P1 | ba95fc92e71f12e30352a515fd84ffbdfb8c00bd | [
"MIT"
] | null | null | null | src/main.cpp | ernestocanibano/CarND-Path-Planning-P1 | ba95fc92e71f12e30352a515fd84ffbdfb8c00bd | [
"MIT"
] | null | null | null | src/main.cpp | ernestocanibano/CarND-Path-Planning-P1 | ba95fc92e71f12e30352a515fd84ffbdfb8c00bd | [
"MIT"
] | null | null | null | #include <uWS/uWS.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "helpers.h"
#include "json.hpp"
#include "spline.h"
// for convenience
using nlohmann::json;
using std::string;
using std::vector;
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
std::ifstream in_map_(map_file_.c_str(), std::ifstream::in);
string line;
while (getline(in_map_, line)) {
std::istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
//reference speed
double ref_speed = 0.0;
int next_lane = 2;
h.onMessage([&next_lane,&ref_speed,&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,
&map_waypoints_dx,&map_waypoints_dy]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side
// of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
json msgJson;
vector<double> next_x_vals;
vector<double> next_y_vals;
/**
* TODO: define a path made up of (x,y) points that the car will visit
* sequentially every .02 seconds
*/
double lane_width = 4; // Lane width in meters
int wp_spacing = 30; //distance in meters between two reference waypoints
int horizont = 30; //distance ahead to generate a new trajectory
auto prev_size = previous_path_x.size(); //size of the previous path
double acceleration = 4; // acceleration m/s^2
double max_acceleration = 9; // acceleration m/s^2
double max_speed = 49 * 0.44704; //maximum speed m/s
double target_speed = ref_speed;
//check which line is my car
auto lane = getLane(car_d, lane_width);
//calculate acceleration in function of the points moved
if(prev_size == 0){
end_path_s = car_s;
}
//look for the closest car in front of me
bool car_in_front = false;
bool car_on_left = false;
bool car_on_left_slow = false;
bool car_on_right = false;
bool car_on_right_slow = false;
float new_speed = 0;
for(int i=0; i<sensor_fusion.size(); i++){
float check_car_d = sensor_fusion[i][6];
float check_car_s = sensor_fusion[i][5];
float vx = sensor_fusion[i][3];
float vy = sensor_fusion[i][4];
float check_car_v = sqrt(vx*vx+vy*vy);
int check_lane = getLane(check_car_d, lane_width);
if(check_lane > 0){//ignore them
if(check_lane == lane){
if( (check_car_s-car_s) > 0){
if( (check_car_s-end_path_s) < 0){ //possible collission stop quickly
car_in_front = true;
new_speed = 0;
acceleration = max_acceleration;
}else if( (check_car_s-end_path_s) < 30){ //adapt of the speed of the car ahead
car_in_front = true;
new_speed = check_car_v;
}
}
}else if(check_lane == (lane-1)){
if( (check_car_s-car_s) < -5 && (check_car_s-car_s) > -20){
if(check_car_v > ref_speed){
car_on_left = true;
}
}else if( (check_car_s-car_s) > -5){
if( (check_car_s-end_path_s) < 10){
car_on_left = true;
}else if( (check_car_s-end_path_s) < 30){
car_on_left = true;
}
}
}else if(check_lane == (lane+1)){
if( (check_car_s-car_s) < -5 && (check_car_s-car_s) > -20){
if(check_car_v > ref_speed){
car_on_right = true;
}
}else if( (check_car_s-car_s) > -5){
if( (check_car_s-end_path_s) < 10){
car_on_right = true;
}else if( (check_car_s-end_path_s) < 30){
car_on_right = true;
}
}
}
}
}
//only perform other action if a lane changing is not in process
if(lane == next_lane){
if(car_in_front){
if(lane == 2){ //center
if(!car_on_left){
lane--;
//target_speed = max_speed;
}else if(!car_on_right){
lane++;
//target_speed = max_speed;
}else{
target_speed = new_speed;
}
}else if(lane == 1){ //left
if(!car_on_right){
lane++;
//target_speed = max_speed;
}else{
target_speed = new_speed;
}
}else if(lane == 3){//right
if(!car_on_left){
lane--;
//target_speed = max_speed;
}else{
target_speed = new_speed;
}
}
}else{
target_speed = max_speed;
}
next_lane = lane ;
}
//This point is the beginning of the trajectory
auto current_yaw = deg2rad(car_yaw);
double current_x;
double current_y;
/** The new trajectory of the car has to be tangent to the previous trajectory.
* It will be generated using several reference waypoints and will be smoothed using spline.
* The first two points of the new trajectory have match the last two points of the old tajectory to get the tangency.
*/
//Reference waypoints to generate a trajectory
vector<double> ref_x_vals; //reference trajectory 'x' values
vector<double> ref_y_vals; //reference trajectory 'y' values
vector<double> ref_wp0(2);
vector<double> ref_wp1(2);
//If an old trajectory doesn't exist, it can be use the current position of the car as second point of the new trajectory.
//The first one is calculated backwards knowing the current yaw angle of the car and assuming the minimum distance unit (1 meter)
if(prev_size < 2){
ref_wp0[0] = car_x - cos(current_yaw);
ref_wp0[1] = car_y - sin(current_yaw);
ref_wp1[0] = car_x;
ref_wp1[1] = car_y;
}
//if exists an old trajectory, the last two points will be used.
else{
ref_wp0[0] = previous_path_x[prev_size-2];
ref_wp0[1] = previous_path_y[prev_size-2];
ref_wp1[0] = previous_path_x[prev_size-1];
ref_wp1[1] = previous_path_y[prev_size-1];
//update the yaw angle
current_yaw = atan2(ref_wp1[1]-ref_wp0[1], ref_wp1[0]-ref_wp0[0]);
//Add the remaining points of the old trajectory to the new trajectory
for(int i=0; i<prev_size; i++){
next_x_vals.push_back(previous_path_x[i]);
next_y_vals.push_back(previous_path_y[i]);
}
}
current_x = ref_wp1[0];
current_y = ref_wp1[1];
//Add more waypoints to be used as reference, three waypoints are enough to generate a lane change.
vector<double> ref_wp2 = getXY(end_path_s+1*wp_spacing, (next_lane-1)*lane_width+lane_width/2, map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector<double> ref_wp3 = getXY(end_path_s+2*wp_spacing, (next_lane-1)*lane_width+lane_width/2, map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector<double> ref_wp4 = getXY(end_path_s+3*wp_spacing, (next_lane-1)*lane_width+lane_width/2, map_waypoints_s, map_waypoints_x, map_waypoints_y);
ref_x_vals.push_back(ref_wp0[0]);
ref_x_vals.push_back(ref_wp1[0]);
ref_x_vals.push_back(ref_wp2[0]);
ref_x_vals.push_back(ref_wp3[0]);
ref_x_vals.push_back(ref_wp4[0]);
ref_y_vals.push_back(ref_wp0[1]);
ref_y_vals.push_back(ref_wp1[1]);
ref_y_vals.push_back(ref_wp2[1]);
ref_y_vals.push_back(ref_wp3[1]);
ref_y_vals.push_back(ref_wp4[1]);
//To use spline points have to be sorted, therefore it is better work in local coordinates from here
for(int i=0; i<ref_x_vals.size(); i++){
vector<double> point = getLocalXY(ref_x_vals[i], ref_y_vals[i], current_x, current_y, current_yaw);
ref_x_vals[i] = point[0];
ref_y_vals[i] = point[1];
}
//use spline to smooth the reference trajectory
tk::spline s;
s.set_points(ref_x_vals, ref_y_vals);
double target_x = horizont;
double target_y = s(target_x);
double target_theta = atan2(target_y, target_x);
double target_distance = 0;
//Add the new points to trajectory
for(int i=1; i<=(50-prev_size); i++){
if(ref_speed > target_speed){
ref_speed -= (acceleration * 0.02);
if(ref_speed < 0){
ref_speed = 0;
}
}else if (ref_speed < target_speed){
ref_speed += (acceleration * 0.02);
if(ref_speed > max_speed){
ref_speed = max_speed;
}
}
target_distance += ref_speed*0.02;
double x_point = target_distance*cos(target_theta);
double y_point = s(x_point);
vector<double> next_point = getGlobalXY(x_point, y_point, current_x, current_y, current_yaw);
next_x_vals.push_back(next_point[0]);
next_y_vals.push_back(next_point[1]);
}
/***********************************************************/
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
} // end "telemetry" if
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} // end websocket if
}); // end h.onMessage
h.onConnection([&ref_speed, &h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
ref_speed = 0.0;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
} | 33.196581 | 151 | 0.599468 | [
"object",
"vector"
] |
184f6aa92950d68e6dbbff60bfd2709d24f2a423 | 9,182 | cpp | C++ | unittests/Athena-Entities/tests/test_Animation.cpp | Kanma/Athena-Entities | c463bef9b5a6ec7989f3524739d0030ff24f32fe | [
"MIT"
] | 1 | 2016-10-30T07:34:37.000Z | 2016-10-30T07:34:37.000Z | unittests/Athena-Entities/tests/test_Animation.cpp | Kanma/Athena-Entities | c463bef9b5a6ec7989f3524739d0030ff24f32fe | [
"MIT"
] | null | null | null | unittests/Athena-Entities/tests/test_Animation.cpp | Kanma/Athena-Entities | c463bef9b5a6ec7989f3524739d0030ff24f32fe | [
"MIT"
] | null | null | null | #include <UnitTest++.h>
#include <Athena-Entities/Animation.h>
#include <Athena-Entities/ComponentAnimation.h>
#include <Athena-Core/Utils/Iterators.h>
using namespace Athena::Entities;
using namespace Athena::Utils;
class MinMaxAnimation: public ComponentAnimation
{
public:
MinMaxAnimation(float min = 0.0f, float max = 10.0f, float length = 10.0f)
: min(min), max(max), length(length), timepos(0.0f), weight(1.0f),
loop(false), enabled(false)
{
}
virtual ~MinMaxAnimation()
{
}
virtual void setTimePosition(float fTimePos)
{
if (!enabled)
return;
timepos = fTimePos;
value = min + (max - min) * fTimePos / length;
}
virtual float getTimePosition() const
{
return timepos;
}
virtual float getLength() const
{
return length;
}
virtual void setCurrentWeight(float fWeight)
{
weight = fWeight;
}
virtual float getCurrentWeight() const
{
return weight;
}
virtual void setEnabled(bool bEnabled)
{
enabled = bEnabled;
}
virtual void setLooping(bool bLoop)
{
loop = bLoop;
}
float min;
float max;
float length;
float timepos;
float weight;
float value;
bool loop;
bool enabled;
};
class Animable
{
public:
float value;
std::vector<MinMaxAnimation*> animations;
void update()
{
value = 0.0f;
VectorIterator<std::vector<MinMaxAnimation*> > iter(animations);
while (iter.hasMoreElements())
{
MinMaxAnimation* pAnim = iter.getNext();
value += pAnim->getCurrentWeight() * pAnim->value;
}
}
};
SUITE(AnimationTests)
{
TEST(Creation)
{
Animation anim("test");
CHECK_EQUAL(0, anim.getNbComponentAnimations());
}
TEST(AddOneComponentAnimation)
{
MinMaxAnimation a1;
Animation anim("test");
anim.addComponentAnimation(&a1);
CHECK_EQUAL(1, anim.getNbComponentAnimations());
}
TEST(AddTwoComponentAnimations)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
CHECK_EQUAL(2, anim.getNbComponentAnimations());
}
TEST(AddRemoveComponentAnimation)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
anim.removeComponentAnimation(&a1);
CHECK_EQUAL(1, anim.getNbComponentAnimations());
}
TEST(Enabling)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
anim.setEnabled(false);
anim.setEnabled(true);
CHECK(anim.isEnabled());
CHECK(a1.enabled);
CHECK(a2.enabled);
}
TEST(Disabling)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
anim.setEnabled(true);
anim.setEnabled(false);
CHECK(!anim.isEnabled());
CHECK(!a1.enabled);
CHECK(!a2.enabled);
}
TEST(AddComponentAnimationsToEnabledAnimation)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.setEnabled(true);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
CHECK(a1.enabled);
CHECK(a2.enabled);
}
TEST(AddComponentAnimationsToDisabledAnimation)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.setEnabled(false);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
CHECK(!a1.enabled);
CHECK(!a2.enabled);
}
TEST(Looping)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
anim.setLooping(false);
anim.setLooping(true);
CHECK(anim.isLooping());
CHECK(a1.loop);
CHECK(a2.loop);
}
TEST(NotLooping)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
anim.setLooping(true);
anim.setLooping(false);
CHECK(!anim.isLooping());
CHECK(!a1.loop);
CHECK(!a2.loop);
}
TEST(AddComponentAnimationsToLoopingAnimation)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.setLooping(true);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
CHECK(a1.loop);
CHECK(a2.loop);
}
TEST(AddComponentAnimationsToNotLoopingAnimation)
{
MinMaxAnimation a1, a2;
Animation anim("test");
anim.setLooping(false);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
CHECK(!a1.loop);
CHECK(!a2.loop);
}
TEST(UpdateOneComponentAnimation)
{
Animable animable;
MinMaxAnimation a1(0.0f, 10.0f, 10.0f);
Animation anim("test");
anim.setEnabled(true);
animable.animations.push_back(&a1);
anim.addComponentAnimation(&a1);
anim.reset();
animable.update();
CHECK_CLOSE(0.0f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(5.0f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(10.0f, animable.value, 1e-6f);
}
TEST(UpdateTwoComponentAnimationsWithSameLength)
{
Animable animable;
MinMaxAnimation a1(0.0f, 10.0f, 10.0f);
MinMaxAnimation a2(0.0f, 5.0f, 10.0f);
Animation anim("test");
anim.setEnabled(true);
animable.animations.push_back(&a1);
animable.animations.push_back(&a2);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
a1.setWeight(0.5f);
a2.setWeight(0.5f);
anim.reset();
animable.update();
CHECK_CLOSE(0.0f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(3.75f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(7.5f, animable.value, 1e-6f);
}
TEST(UpdateTwoComponentAnimationsWithSameLengthAndDifferentWeights)
{
Animable animable;
MinMaxAnimation a1(0.0f, 10.0f, 10.0f);
MinMaxAnimation a2(0.0f, 5.0f, 10.0f);
Animation anim("test");
anim.setEnabled(true);
animable.animations.push_back(&a1);
animable.animations.push_back(&a2);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
a1.setWeight(0.75f);
a2.setWeight(0.25f);
anim.reset();
animable.update();
CHECK_CLOSE(0.0f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(4.375f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(8.75f, animable.value, 1e-6f);
}
TEST(UpdateTwoComponentAnimationsWithDifferentLengths)
{
Animable animable;
MinMaxAnimation a1(0.0f, 10.0f, 10.0f);
MinMaxAnimation a2(0.0f, 5.0f, 5.0f);
Animation anim("test");
anim.setEnabled(true);
animable.animations.push_back(&a1);
animable.animations.push_back(&a2);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
a1.setWeight(0.5f);
a2.setWeight(0.5f);
anim.reset();
animable.update();
CHECK_CLOSE(0.0f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(5.0f, animable.value, 1e-6f);
anim.update(5.0f);
animable.update();
CHECK_CLOSE(7.5f, animable.value, 1e-6f);
}
TEST(UpdateTwoComponentAnimationsWithDifferentLengthsAndOffset)
{
Animable animable;
MinMaxAnimation a1(0.0f, 10.0f, 10.0f);
MinMaxAnimation a2(0.0f, 5.0f, 5.0f);
Animation anim("test");
anim.setEnabled(true);
animable.animations.push_back(&a1);
animable.animations.push_back(&a2);
a1.setWeight(0.5f);
a2.setWeight(0.5f);
a2.setOffset(2.5f);
anim.addComponentAnimation(&a1);
anim.addComponentAnimation(&a2);
anim.reset();
animable.update();
CHECK_CLOSE(0.0f, animable.value, 1e-6f);
anim.update(2.5f);
animable.update();
CHECK_CLOSE(1.25f, animable.value, 1e-6f);
anim.update(2.5f);
animable.update();
CHECK_CLOSE(3.75f, animable.value, 1e-6f);
anim.update(2.5f);
animable.update();
CHECK_CLOSE(6.25f, animable.value, 1e-6f);
anim.update(2.5f);
animable.update();
CHECK_CLOSE(7.5f, animable.value, 1e-6f);
}
}
| 21.914081 | 78 | 0.588216 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.