hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53cffcce8f6c207095d511f4629668bd41857bb6 | 10,689 | cpp | C++ | iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | //
// G3MHUDDemoScene.cpp
// G3MApp
//
// Created by Diego Gomez Deck on 12/2/14.
// Copyright (c) 2014 Igo Software SL. All rights reserved.
//
#include "G3MHUDDemoScene.hpp"
//#include <G3MiOSSDK/G3MWidget.hpp>
#include <G3MiOSSDK/MapBoxLayer.hpp>
#include <G3MiOSSDK/LayerSet.hpp>
#include <G3MiOSSDK/CanvasImageBuilder.hpp>
#include <G3MiOSSDK/ICanvas.hpp>
#include <G3MiOSSDK/Color.hpp>
#include <G3MiOSSDK/IStringUtils.hpp>
#include <G3MiOSSDK/GFont.hpp>
#include <G3MiOSSDK/Context.hpp>
#include <G3MiOSSDK/HUDQuadWidget.hpp>
#include <G3MiOSSDK/HUDRenderer.hpp>
#include <G3MiOSSDK/HUDRelativePosition.hpp>
#include <G3MiOSSDK/HUDRelativeSize.hpp>
#include <G3MiOSSDK/LabelImageBuilder.hpp>
#include <G3MiOSSDK/DownloaderImageBuilder.hpp>
#include <G3MiOSSDK/HUDAbsolutePosition.hpp>
#include <G3MiOSSDK/GTask.hpp>
#include <G3MiOSSDK/G3MWidget.hpp>
#include <G3MiOSSDK/PeriodicalTask.hpp>
#include "G3MDemoModel.hpp"
class AltimeterCanvasImageBuilder : public CanvasImageBuilder {
private:
float _altitude = 38500;
float _step = 100;
protected:
void buildOnCanvas(const G3MContext* context,
ICanvas* canvas) {
const float width = canvas->getWidth();
const float height = canvas->getHeight();
canvas->setFillColor(Color::fromRGBA(0, 0, 0, 0.5));
canvas->fillRectangle(0, 0, width, height);
canvas->setFillColor(Color::white());
const IStringUtils* su = context->getStringUtils();
int altitude = _altitude;
canvas->setFont(GFont::monospaced(32));
for (int y = 0; y <= height; y += 16) {
if ((y % 80) == 0) {
canvas->fillRectangle(0, y-1.5f, width/6.0f, 3);
const std::string label = su->toString(altitude);
const Vector2F labelExtent = canvas->textExtent(label);
canvas->fillText(label,
width/6.0f * 1.25f,
y - labelExtent._y/2);
altitude -= 100;
}
else {
canvas->fillRectangle(0, y-0.5f, width/8.0f, 1);
}
}
canvas->setLineColor(Color::white());
canvas->setLineWidth(8);
canvas->strokeRectangle(0, 0, width, height);
}
public:
AltimeterCanvasImageBuilder() :
CanvasImageBuilder(256, 256*3)
{
}
bool isMutable() const {
return true;
}
void step() {
_altitude += _step;
if (_altitude > 40000) {
_altitude = 40000;
_step *= -1;
}
if (_altitude < 0) {
_altitude = 0;
_step *= -1;
}
changed();
}
};
class AnimateHUDWidgetsTask : public GTask {
private:
HUDQuadWidget* _compass1;
HUDQuadWidget* _compass2;
HUDQuadWidget* _ruler;
LabelImageBuilder* _labelBuilder;
AltimeterCanvasImageBuilder* _altimeterCanvasImageBuilder;
double _angleInRadians;
float _translationV;
float _translationStep;
public:
AnimateHUDWidgetsTask(HUDQuadWidget* compass1,
HUDQuadWidget* compass2,
HUDQuadWidget* ruler,
LabelImageBuilder* labelBuilder,
AltimeterCanvasImageBuilder* altimeterCanvasImageBuilder) :
_compass1(compass1),
_compass2(compass2),
_ruler(ruler),
_labelBuilder(labelBuilder),
_altimeterCanvasImageBuilder(altimeterCanvasImageBuilder),
_angleInRadians(0),
_translationV(0),
_translationStep(0.002)
{
}
void run(const G3MContext* context) {
_angleInRadians += Angle::fromDegrees(2)._radians;
// _labelBuilder->setText( Angle::fromRadians(_angleInRadians).description() );
double degrees = Angle::fromRadians(_angleInRadians)._degrees;
while (degrees > 360) {
degrees -= 360;
}
const std::string degreesText = IStringUtils::instance()->toString( IMathUtils::instance()->round( degrees ) );
_labelBuilder->setText( " " + degreesText );
// _compass1->setTexCoordsRotation(_angleInRadians,
// 0.5f, 0.5f);
_compass2->setTexCoordsRotation(-_angleInRadians,
0.5f, 0.5f);
// _compass3->setTexCoordsRotation(Angle::fromRadians(_angle),
// 0.5f, 0.5f);
if (_translationV > 0.5 || _translationV < 0) {
_translationStep *= -1;
}
_translationV += _translationStep;
_ruler->setTexCoordsTranslation(0, _translationV);
_altimeterCanvasImageBuilder->step();
}
};
void G3MHUDDemoScene::rawActivate(const G3MContext *context) {
G3MDemoModel* model = getModel();
G3MWidget* g3mWidget = model->getG3MWidget();
MapBoxLayer* layer = new MapBoxLayer("examples.map-m0t0lrpu",
TimeInterval::fromDays(30),
true,
2);
model->getLayerSet()->addLayer(layer);
HUDRenderer* hudRenderer = model->getHUDRenderer();
AltimeterCanvasImageBuilder* altimeterCanvasImageBuilder = new AltimeterCanvasImageBuilder();
HUDQuadWidget* test = new HUDQuadWidget(altimeterCanvasImageBuilder,
new HUDRelativePosition(0,
HUDRelativePosition::VIEWPORT_WIDTH,
HUDRelativePosition::RIGHT,
10),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_HEIGHT,
HUDRelativePosition::MIDDLE),
new HUDRelativeSize(0.22,
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new HUDRelativeSize(0.66,
HUDRelativeSize::VIEWPORT_MIN_AXIS)
);
hudRenderer->addWidget(test);
LabelImageBuilder* labelBuilder = new LabelImageBuilder("glob3", // text
GFont::monospaced(38), // font
6, // margin
Color::yellow(), // color
Color::black(), // shadowColor
3, // shadowBlur
1, // shadowOffsetX
-1, // shadowOffsetY
Color::red(), // backgroundColor
4, // cornerRadius
true // mutable
);
HUDQuadWidget* label = new HUDQuadWidget(labelBuilder,
new HUDAbsolutePosition(10),
new HUDAbsolutePosition(10),
new HUDRelativeSize(1, HUDRelativeSize::BITMAP_WIDTH),
new HUDRelativeSize(1, HUDRelativeSize::BITMAP_HEIGHT) );
hudRenderer->addWidget(label);
HUDQuadWidget* compass2 = new HUDQuadWidget(new DownloaderImageBuilder(URL("file:///CompassHeadings.png")),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_WIDTH,
HUDRelativePosition::CENTER),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_HEIGHT,
HUDRelativePosition::MIDDLE),
new HUDRelativeSize(0.25,
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new HUDRelativeSize(0.125,
HUDRelativeSize::VIEWPORT_MIN_AXIS));
compass2->setTexCoordsRotation(Angle::fromDegrees(30),
0.5f, 0.5f);
compass2->setTexCoordsScale(1, 0.5f);
hudRenderer->addWidget(compass2);
float visibleFactor = 3;
HUDQuadWidget* ruler = new HUDQuadWidget(new DownloaderImageBuilder(URL("file:///altimeter-ruler-1536x113.png")),
new HUDRelativePosition(1,
HUDRelativePosition::VIEWPORT_WIDTH,
HUDRelativePosition::LEFT,
10),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_HEIGHT,
HUDRelativePosition::MIDDLE),
new HUDRelativeSize(2 * (113.0 / 1536.0),
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new HUDRelativeSize(2 / visibleFactor,
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new DownloaderImageBuilder(URL("file:///widget-background.png")));
ruler->setTexCoordsScale(1 , 1.0f / visibleFactor);
hudRenderer->addWidget(ruler);
g3mWidget->addPeriodicalTask(new PeriodicalTask(TimeInterval::fromMilliseconds(50),
new AnimateHUDWidgetsTask(label,
compass2,
ruler,
labelBuilder,
altimeterCanvasImageBuilder)));
}
| 41.27027 | 116 | 0.477874 | AeroGlass |
53d1654bd095104482205740dbd1d2022d6be557 | 1,346 | hpp | C++ | Hardware/src/hard/rpi_gpio.hpp | torunxxx001/BookCollectionSystem | cce2942e30c460949ba729db432f0efdd66f8465 | [
"MIT"
] | null | null | null | Hardware/src/hard/rpi_gpio.hpp | torunxxx001/BookCollectionSystem | cce2942e30c460949ba729db432f0efdd66f8465 | [
"MIT"
] | null | null | null | Hardware/src/hard/rpi_gpio.hpp | torunxxx001/BookCollectionSystem | cce2942e30c460949ba729db432f0efdd66f8465 | [
"MIT"
] | null | null | null | /* 参考PDF[BCM2835-ARM-Peripherals.pdf] */
/* RaspberryPI用GPIO操作プログラム */
/*
対応表
PIN NAME
0 GPIO 2(SDA)
1 GPIO 3(SCL)
2 GPIO 4(GPCLK0)
3 GPIO 7(CE1)
4 GPIO 8(CE0)
5 GPIO 9(MISO)
6 GPIO 10(MOSI)
7 GPIO 11(SCLK)
8 GPIO 14(TXD)
9 GPIO 15(RXD)
10 GPIO 17
11 GPIO 18(PCM_CLK)
12 GPIO 22
13 GPIO 23
14 GPIO 24
15 GPIO 25
16 GPIO 27(PCM_DOUT)
17 GPIO 28
18 GPIO 29
19 GPIO 30
20 GPIO 31
*/
#ifndef __RPI_GPIO_HPP__
#define __RPI_GPIO_HPP__
/* バスアクセス用物理アドレス(Page.6 - 1.2.3) */
#define PHADDR_OFFSET 0x20000000
/* GPIOコントロールレジスタへのオフセット(Page.90 - 6.1) */
#define GPIO_CONTROL_OFFSET (PHADDR_OFFSET + 0x200000)
/* GPFSEL0からGPLEVまでのサイズ */
#define GPCONT_SIZE 0x3C
/* 各レジスタへのオフセット */
#define GPFSEL_OFFSET 0x00
#define GPSET_OFFSET 0x1C
#define GPCLR_OFFSET 0x28
#define GPLEV_OFFSET 0x34
/* モード定義 */
#define GPIO_INPUT 0
#define GPIO_OUTPUT 1
#define GPIO_ALT0 4
#define GPIO_ALT1 5
#define GPIO_ALT2 6
#define GPIO_ALT3 7
#define GPIO_ALT4 3
#define GPIO_ALT5 2
#define HIGH 1
#define LOW 0
extern const char* PINtoNAME[];
//GPIOコントロール用クラス
class gpio {
private:
//GPIOマッピング用ポインタ
static volatile unsigned int* gpio_control;
static int instance_count;
public:
gpio();
~gpio();
void mode_write(int pin, int mode);
void mode_read(int pin, int* mode);
void data_write(int pin, int data);
void data_read(int pin, int* data);
};
#endif
| 16.02381 | 54 | 0.732541 | torunxxx001 |
53d19d2e5ac46e190dc814d6c6e9592c5831fbe9 | 1,137 | cpp | C++ | src/query_tatami.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/query_tatami.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/query_tatami.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | #include "tatami/tatami.h"
#include "Rcpp.h"
#include "tatamize.h"
//[[Rcpp::export(rng=false)]]
Rcpp::IntegerVector tatami_dim(SEXP x) {
auto ptr = extract_NumericMatrix(x);
return Rcpp::IntegerVector::create(ptr->nrow(), ptr->ncol());
}
//[[Rcpp::export(rng=false)]]
Rcpp::NumericMatrix tatami_rows(SEXP x, Rcpp::IntegerVector rows, int first, int last) {
auto ptr = extract_NumericMatrix(x);
size_t nc = last - first;
Rcpp::NumericMatrix output(nc, rows.size());
double* optr = output.begin();
auto wrk = ptr->new_workspace(true);
for (auto r : rows) {
ptr->row_copy(r, optr, first, last, wrk.get());
}
return Rcpp::transpose(output);
}
//[[Rcpp::export(rng=false)]]
Rcpp::NumericMatrix tatami_columns(SEXP x, Rcpp::IntegerVector columns, int first, int last) {
auto ptr = extract_NumericMatrix(x);
size_t nr = last - first;
Rcpp::NumericMatrix output(nr, columns.size());
double* optr = output.begin();
auto wrk = ptr->new_workspace(false);
for (auto c : columns) {
ptr->column_copy(c, optr, first, last, wrk.get());
}
return output;
}
| 27.071429 | 94 | 0.648197 | LTLA |
53d3d8fbf496c15a7e0b017d0d78183d4f70afc5 | 1,256 | cpp | C++ | Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z | /*
We all know the distributive property that (a1+a2)*(b1+b2) = a1*b1 + a1*b2 + a2*b1 + a2*b2
Explanation
Distributive property is similar for AND and XOR here.
(a1^a2) & (b1^b2) = (a1&b1) ^ (a1&b2) ^ (a2&b1) ^ (a2&b2)
(I wasn't aware of this at first either)
另一种思路, 如果所有arr2 中的数 第一个bit 是奇数个(求所有数第一位bit的xor),if arr1[0] 第一个bit 为 1, 那么第一个 bit 可以留下来
如果所有arr2 中的数 第二个bit 是奇数个(求所有数第二位bit的xor),if arr1[0] 第二个bit 为 1, 那么第二个 bit 可以留下来
: : : : : : : : : : : : : : : : : : : :
如果所有arr2 中的数 第n个bit 是奇数个(求所有数第n位bit的xor),if arr1[0] 第n个bit 为 1, 那么第二个 bit 可以留下来
把这n 个 bit 结合到一起(xorb),就是 (arr1[0] & arr2 [0]) ^ (arr1[0] & arr2[1]) ... (arr1[0] & arr2[n2-1])
*/
class Solution {
public:
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int xora = 0, xorb = 0;
for (int& a: arr1)
xora ^= a;
for (int& b: arr2)
xorb ^= b;
return xora & xorb;
}
};
class Solution {
public:
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int xorb = 0;
for (int& b: arr2)
xorb ^= b;
int ret = 0;
for (int& a: arr1)
ret ^= (xorb & a);
return ret;
}
};
| 26.723404 | 104 | 0.514331 | beckswu |
53d43ebb01cd7590624edbe6e9033bcf44f6d4ad | 291 | cpp | C++ | Graph/DSU.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | 1 | 2021-07-20T06:08:26.000Z | 2021-07-20T06:08:26.000Z | Graph/DSU.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | Graph/DSU.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | #define MAX 20001
int par[MAX], sz[MAX];
void init(int v) {
par[v] = v;
sz[v] = 1;
}
int find(int v) {
return v == par[v] ? v : par[v] = find(par[v]);
}
void join(int u, int v) {
u = find(u), v = find(v);
if(u != v) {
if(sz[u] < sz[v]) swap(u, v);
par[v] = u;
sz[u] += sz[v];
}
} | 17.117647 | 48 | 0.484536 | scortier |
53d6db547db42be009f19c81dd2f8ad1d67d5f6a | 1,070 | cpp | C++ | Pm2Service/Pm2Helper.cpp | thebecwar/PM2Service | 594fdc39f734a425ccd61fd6132755f32882afb6 | [
"MIT"
] | null | null | null | Pm2Service/Pm2Helper.cpp | thebecwar/PM2Service | 594fdc39f734a425ccd61fd6132755f32882afb6 | [
"MIT"
] | null | null | null | Pm2Service/Pm2Helper.cpp | thebecwar/PM2Service | 594fdc39f734a425ccd61fd6132755f32882afb6 | [
"MIT"
] | null | null | null | #include "Pm2Helper.h"
#include "Process.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <PathCch.h>
#include <locale>
#include <codecvt>
#include <string>
#include <sstream>
void ConvertNarrowToWide(std::string& narrow, std::wstring& wide)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
wide = converter.from_bytes(narrow);
}
void FindPm2Path(std::wstring& path)
{
std::wstring command(L"node -e \"process.stdout.write(require.resolve('pm2/bin/pm2'))\"");
wchar_t buf[MAX_PATH];
GetModuleFileNameW(NULL, buf, MAX_PATH);
PathCchRemoveFileSpec(buf, MAX_PATH);
std::wstring programPath(buf);
Process proc(command);
proc.SetWorkingDir(programPath);
proc.StartProcess();
std::string pm2path;
proc.ReadStdOut(pm2path);
ConvertNarrowToWide(pm2path, path);
}
void BuildPm2Command(std::wstring& args, std::wstring& target)
{
std::wstring pm2path;
FindPm2Path(pm2path);
std::wstringstream ss;
ss << L"node.exe \"" << pm2path << L"\" " << args;
target = ss.str();
}
| 23.777778 | 94 | 0.692523 | thebecwar |
53d7aa80fd1ff968638b54548a45f3b42086a965 | 517 | cpp | C++ | unittest/tests/JsonTest/source/Application.cpp | Hurleyworks/Ketone | 97c0c730a6e3155154a0ccb87a535e109dfa3c7d | [
"Apache-2.0"
] | 1 | 2021-04-01T01:16:33.000Z | 2021-04-01T01:16:33.000Z | unittest/tests/JsonTest/source/Application.cpp | Hurleyworks/Ketone | 97c0c730a6e3155154a0ccb87a535e109dfa3c7d | [
"Apache-2.0"
] | null | null | null | unittest/tests/JsonTest/source/Application.cpp | Hurleyworks/Ketone | 97c0c730a6e3155154a0ccb87a535e109dfa3c7d | [
"Apache-2.0"
] | null | null | null | #include "Jahley.h"
#include <json.hpp>
const std::string APP_NAME = "JsonTest";
#ifdef CHECK
#undef CHECK
#endif
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
using json = nlohmann::json;
class Application : public Jahley::App
{
public:
Application(DesktopWindowSettings settings = DesktopWindowSettings(), bool windowApp = false) :
Jahley::App(settings, windowApp)
{
doctest::Context().run();
}
private:
};
Jahley::App* Jahley::CreateApplication()
{
return new Application();
}
| 14.771429 | 98 | 0.709865 | Hurleyworks |
53d82a58d6860797fcbbc6ec091433cc8d8e9769 | 1,402 | cpp | C++ | FERMIONS/WILSON/LoopMacros.cpp | markmace/OVERLAP | 2d26366aa862cbd36182db8ee3165d9fe4d3e704 | [
"MIT"
] | 1 | 2020-12-13T03:11:03.000Z | 2020-12-13T03:11:03.000Z | FERMIONS/WILSON/LoopMacros.cpp | markmace/OVERLAP | 2d26366aa862cbd36182db8ee3165d9fe4d3e704 | [
"MIT"
] | null | null | null | FERMIONS/WILSON/LoopMacros.cpp | markmace/OVERLAP | 2d26366aa862cbd36182db8ee3165d9fe4d3e704 | [
"MIT"
] | null | null | null | #ifndef __LOOP_MACROS_CPP__
#define __LOOP_MACROS_CPP__
#define START_FERMION_LOOP(gMatrixCoupling) \
\
for(INT i=0;i<Nc;i++){ \
for(INT j=0;j<Nc;j++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0){ \
#define END_FERMION_LOOP \
}\
}\
}\
}\
}
#define START_FERMION_LOOP_2(gMatrixCoupling,gMatrixCoupling2) \
\
for(INT i=0;i<Nc;i++){ \
for(INT j=0;j<Nc;j++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0 || gMatrixCoupling2[alpha][beta]!=0.0){ \
#define END_FERMION_LOOP \
}\
}\
}\
}\
}
#define START_LOCAL_FERMION_LOOP(gMatrixCoupling) \
\
for(INT i=0;i<Nc;i++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0){ \
#define END_LOCAL_FERMION_LOOP \
}\
}\
}\
}
#define START_LOCAL_FERMION_LOOP_2(gMatrixCoupling,gMatrixCoupling2) \
\
for(INT i=0;i<Nc;i++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0 || gMatrixCoupling2[alpha][beta]!=0.0){ \
#define END_LOCAL_FERMION_LOOP \
}\
}\
}\
}
#endif | 18.207792 | 78 | 0.702568 | markmace |
53dbd15883fca8e4fb9012fbe7b16ae78429f8df | 1,255 | cpp | C++ | ansi-c/fix_symbol.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | ansi-c/fix_symbol.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | ansi-c/fix_symbol.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************\
Module: ANSI-C Linking
Author: Daniel Kroening, [email protected]
\*******************************************************************/
#include "fix_symbol.h"
/*******************************************************************\
Function: fix_symbolt::fix_symbol
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void fix_symbolt::fix_symbol(symbolt &symbol)
{
type_mapt::const_iterator it=
type_map.find(symbol.name);
if(it!=type_map.end())
symbol.name=it->second.id();
replace(symbol.type);
replace(symbol.value);
}
/*******************************************************************\
Function: fix_symbolt::fix_context
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void fix_symbolt::fix_context(contextt &context)
{
for(type_mapt::const_iterator
t_it=type_map.begin();
t_it!=type_map.end();
t_it++)
{
symbolt* symb = context.find_symbol(t_it->first);
assert(symb != nullptr);
symbolt s = *symb;
s.name = t_it->second.identifier();
context.erase_symbol(t_it->first);
context.move(s);
}
}
| 19.920635 | 69 | 0.449402 | holao09 |
53de116229cda7fec51a86c23c78b472d07a9197 | 1,214 | cc | C++ | src/leaderboard.cc | CS126SP20/final-project-teresa622 | 38b1e943383fe9e71cfffb42460f855444754820 | [
"MIT"
] | null | null | null | src/leaderboard.cc | CS126SP20/final-project-teresa622 | 38b1e943383fe9e71cfffb42460f855444754820 | [
"MIT"
] | null | null | null | src/leaderboard.cc | CS126SP20/final-project-teresa622 | 38b1e943383fe9e71cfffb42460f855444754820 | [
"MIT"
] | null | null | null | //
// Created by Teresa Dong on 4/17/20.
//
#include <string>
#include "mylibrary/leaderboard.h"
#include "mylibrary/player.h"
namespace tetris {
LeaderBoard::LeaderBoard(const std::string& db_path) : db_{db_path} {
db_ << "CREATE TABLE if not exists leaderboard (\n"
" name TEXT NOT NULL,\n"
" score INTEGER NOT NULL\n"
");";
}
void LeaderBoard::AddScoreToLeaderBoard(const Player& player) {
db_ << u"insert into leaderboard (name,score) values (?,?);"
<< player.name
<< player.score;
}
std::vector<Player> GetPlayers(sqlite::database_binder* rows) {
std::vector<Player> players;
for (auto&& row : *rows) {
std::string name;
size_t score;
row >> name >> score;
Player player = {name, score};
players.push_back(player);
}
return players;
}
std::vector<Player> LeaderBoard::RetrieveHighScores(const size_t limit) {
try {
auto rows = db_<< "SELECT name,score FROM "
"leaderboard ORDER BY score DESC LIMIT (?);"
<< limit;
return GetPlayers(&rows);
} catch (const std::exception& e) {
std::cerr << "Query error at retrieve universal high scores";
}
}
} //namespace tetris
| 23.346154 | 73 | 0.623558 | CS126SP20 |
53de483523e0636452f358b5f0779fb78869303d | 628 | cpp | C++ | LuoguOJ/Luogu 2661.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | 1 | 2018-02-11T09:41:54.000Z | 2018-02-11T09:41:54.000Z | LuoguOJ/Luogu 2661.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | LuoguOJ/Luogu 2661.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
const int MAXN=2e6+10;
int disjoint[MAXN],dis[MAXN]={0},ans=2e6+10;
int getjoint(int s){
if(disjoint[s]!=s){
int last=disjoint[s];
disjoint[s]=getjoint(disjoint[s]);
dis[s]+=dis[last];
}
return disjoint[s];
}
void link(int s,int t){
int x=getjoint(s),y=getjoint(t);
if(x!=y){
disjoint[x]=y;
dis[s]=dis[t]+1;
}
else
ans=min(ans,dis[s]+dis[t]+1);
}
int main(){
int N;
cin>>N;
for(int i=1;i<=N;i++)
disjoint[i]=i;
for(int i=1;i<=N;i++){
int k;
cin>>k;
link(i,k);
}
cout<<ans<<'\n';
return 0;
} | 17.942857 | 57 | 0.600318 | tico88612 |
53debfd17bffc22006b3728f7979ccc1a195d383 | 2,701 | cpp | C++ | graph-source-code/118-E/745508.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/118-E/745508.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/118-E/745508.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <map>
#include <set>
#include <list>
#include <stack>
#include <cmath>
#include <queue>
#include <ctime>
#include <cfloat>
#include <vector>
#include <string>
#include <cstdio>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3FFFFFFFFFLL
#define FILL(X, V) memset( X, V, sizeof(X) )
#define TI(X) __typeof((X).begin())
#define ALL(V) V.begin(), V.end()
#define SIZE(V) int((V).size())
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define RFOR(i, b, a) for(int i = b; i >= a; --i)
#define REP(i, N) for(int i = 0; i < N; ++i)
#define RREP(i, N) for(int i = N-1; i >= 0; --i)
#define FORIT(i, a) for( TI(a) i = a.begin(); i != a.end(); i++ )
#define PB push_back
#define MP make_pair
template<typename T> T inline SQR( const T &a ){ return a*a; }
template<typename T> T inline ABS( const T &a ){ return a < 0 ? -a : a; }
template<typename T> T inline MIN( const T& a, const T& b){ if( a < b ) return a; return b; }
template<typename T> T inline MAX( const T& a, const T& b){ if( a > b ) return a; return b; }
const double EPS = 1e-9;
inline int SGN( double a ){ return ((a > EPS) ? (1) : ((a < -EPS) ? (-1) : (0))); }
inline int CMP( double a, double b ){ return SGN(a - b); }
typedef long long int64;
typedef unsigned long long uint64;
using namespace std;
#define MAXN 100000
vector< vector<int> > gr;
int parent[MAXN], low[MAXN], lbl[MAXN];
int dfsnum, bridges;
void dfs( int u ){
lbl[u] = low[u] = dfsnum++;
for( size_t i = 0, sz = gr[u].size(); i < sz; i++ ){
int v = gr[u][i];
if( lbl[v] == -1 ){
parent[v] = u;
dfs( v );
if( low[u] > low[v] ) low[u] = low[v];
if( low[v] == lbl[v] ) bridges++;
} else if( v != parent[u] ) low[u] = min( low[u], lbl[v] );
}
}
set< pair<int,int> > seen;
void show( int u ){
lbl[u] = 0;
for( size_t i = 0, sz = gr[u].size(); i < sz; i++ ){
int v = gr[u][i];
if( lbl[v] == -1 ){
cout << u+1 << " " << v+1 << "\n";
seen.insert( MP(min(u,v), max(u,v)) );
show( v );
} else if( seen.insert( MP(min(u,v),max(u,v))).second ) cout << u+1 << " " << v+1 << "\n";
}
}
int main( int argc, char* argv[] ){
ios::sync_with_stdio( false );
int n, m, u, v;
cin >> n >> m;
gr.resize(n);
REP( i, n ){ gr[i].clear(); lbl[i] = low[i] = -1; parent[i] = -1; }
REP( i, m ){
cin >> u >> v; u--, v--;
gr[u].PB( v );
gr[v].PB( u );
}
dfsnum = 0, bridges = 0; dfs( 0 );
if( bridges ) cout << "0" << "\n";
else{ REP( i, n ) lbl[i] = -1; show( 0 ); }
return 0;
}
| 20.007407 | 93 | 0.546835 | AmrARaouf |
53e19c7e9a43f973ed26aea01b09b554f826fbff | 2,162 | hpp | C++ | src/camera.hpp | mvorbrodt/engine | 0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c | [
"0BSD"
] | 3 | 2019-04-25T11:39:13.000Z | 2022-01-30T22:24:08.000Z | src/camera.hpp | mvorbrodt/engine | 0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c | [
"0BSD"
] | null | null | null | src/camera.hpp | mvorbrodt/engine | 0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c | [
"0BSD"
] | 1 | 2019-11-20T07:58:38.000Z | 2019-11-20T07:58:38.000Z | #pragma once
#include <cassert>
#include "types.hpp"
#include "vector.hpp"
#include "point.hpp"
#include "matrix.hpp"
#include "transforms.hpp"
#define MIN_FOV 10.0f
#define MAX_FOV 90.0f
namespace engine
{
class camera
{
public:
camera(real aspect, real fov = 60.0f, real _near = 1.0f, real _far = 100.0f, const point& origin = ORIGIN, const vector& direction = -UNIT_Z, const vector& up = UNIT_Y)
: m_aspect{ aspect }, m_fov{ fov }, m_near{ _near }, m_far{ _far }, m_origin{ origin }, m_direction{ direction }, m_up{ up }
{
assert(aspect != 0.0f && aspect > 0.0f);
assert(m_fov >= MIN_FOV && m_fov <= MAX_FOV);
assert(m_near >= 1.0f && m_far >= 1.0f && m_near < m_far);
m_direction.normalize();
m_up.normalize();
}
real get_aspect() const { return m_aspect; }
void set_aspect(real aspect) { m_aspect = aspect; }
real get_fov() const { return m_fov; }
void set_fov(real fov)
{
if(fov < MIN_FOV) fov = MIN_FOV;
if(fov > MAX_FOV) fov = MAX_FOV;
m_fov = fov;
}
real get_near() const { return m_near; }
void set_near(real _near)
{
if(_near < 1.0f) _near = 1.0f;
if(_near > m_far) _near = m_far - 1.0f;
m_near = _near;
}
real get_far() const { return m_far; }
void set_far(real _far)
{
if(_far < 1.0f) _far = 1.0f;
if(_far < m_near) _far = m_near + 1.0f;
m_far = _far;
}
void move(real forward, real side)
{
auto v = (m_up ^ m_direction).normal();
m_origin += forward * m_direction + side * v;
}
void turn(real angle)
{
auto m = engine::rotate(angle, m_up);
m_direction *= m;
}
void look(real angle)
{
auto side = (m_up ^ m_direction).normal();
auto m = engine::rotate(angle, side);
m_direction *= m;
}
void roll(real angle)
{
auto m = engine::rotate(angle, m_direction);
m_up *= m;
}
matrix view_matrix() const
{
auto at = m_origin + m_direction;
return look_at(m_origin, at, m_up);
}
matrix projection_matrix()
{
return projection(m_fov, m_aspect, m_near, m_far);
}
private:
real m_aspect;
real m_fov;
real m_near;
real m_far;
point m_origin;
vector m_direction;
vector m_up;
};
}
| 21.405941 | 170 | 0.630897 | mvorbrodt |
53e8532ad79bf9a0704c56fe0263f884d7dc31cc | 446 | cpp | C++ | 643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int sum=0;
for(int i=0;i<k;i++){
sum+=nums[i];
}
double avg=(double)sum/k;
int i=0, j=k;
while(j<nums.size()){
sum -= nums[i];
sum += nums[j];
double a = (double)sum/k;
avg = max(avg,a);
i++;
j++;
}
return avg;
}
}; | 22.3 | 53 | 0.394619 | SouvikChan |
53f20407d36b640aa7b0d498a7d180d06e7ac743 | 1,477 | cpp | C++ | linked-list/merge-sort-doublyLL.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | linked-list/merge-sort-doublyLL.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | linked-list/merge-sort-doublyLL.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next, *prev;
};
Node *merge(Node *a, Node *b)
{
// Base cases
if (!a)
return b;
if (!b)
return a;
if (a->data <= b->data)
{
a->next = merge(a->next, b);
a->next->prev = a;
a->prev = NULL;
return a;
}
else
{
b->next = merge(a, b->next);
b->next->prev = b;
b->prev = NULL;
return b;
}
}
pair<Node *, Node *> FrontBackSplit(Node *source)
{
Node *frontRef = nullptr, *backRef = nullptr;
if (source == nullptr || source->next == nullptr)
{
frontRef = source;
backRef = nullptr;
return make_pair(frontRef, backRef);
}
struct Node *slow = source;
struct Node *fast = source->next;
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
frontRef = source;
backRef = slow->next;
slow->next = NULL;
return make_pair(frontRef, backRef);
}
struct Node *sortDoubly(struct Node *head)
{
if (!head || !head->next)
return head;
pair<Node *, Node *> P = FrontBackSplit(head);
Node *p = P.first, *q = P.second;
p = sortDoubly(p);
q = sortDoubly(q);
head = merge(p, q);
return head;
} | 19.181818 | 54 | 0.475288 | Strider-7 |
53fa031c22b8eed150594efa271ddde6a8d2a68e | 9,895 | cpp | C++ | src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 13 | 2018-02-09T22:59:39.000Z | 2021-11-29T06:33:22.000Z | src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 17 | 2018-01-26T11:36:07.000Z | 2022-02-03T18:48:43.000Z | src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 4 | 2018-10-19T20:00:00.000Z | 2020-10-29T14:44:06.000Z | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file BinningFragmentStorage.cpp
**
** \author Roman Petrovski
**/
#include <cerrno>
#include <fstream>
#include "common/Debug.hh"
#include "common/Exceptions.hh"
#include "alignment/BinMetadata.hh"
#include "alignment/matchSelector/BinningFragmentStorage.hh"
namespace isaac
{
namespace alignment
{
namespace matchSelector
{
/**
* \brief creates bin data files at regular genomic intervals.
*
* \param contigsPerBinMax maximum number of different contigs to be associated with the
* same data file path
*/
static boost::filesystem::path makeDataFilePath(
std::size_t genomicOffset,
const uint64_t targetBinLength,
unsigned binIndex,
const reference::ReferencePosition& binStartPos,
const unsigned contigsPerBinMax,
const reference::SortedReferenceMetadata::Contigs& contigs,
const bfs::path& binDirectory,
unsigned &lastBinLastContig,
uint64_t& lastBinRoundedGenomicOffset,
unsigned & lastBinContigs,
uint64_t& lastFileNameGenomicOffset)
{
reference::ReferencePosition fileNameReferencePosition;
uint64_t roundedGenomicOffset = (genomicOffset / targetBinLength) * targetBinLength;
uint64_t fileNameGenomicOffset = roundedGenomicOffset;
if (binIndex && lastBinRoundedGenomicOffset == roundedGenomicOffset)
{
if (lastBinLastContig != binStartPos.getContigId())
{
++lastBinContigs;
}
if (contigsPerBinMax < lastBinContigs)
{
fileNameGenomicOffset = genomicOffset;
lastFileNameGenomicOffset = genomicOffset;
lastBinContigs = 0;
}
else
{
fileNameGenomicOffset = lastFileNameGenomicOffset;
}
}
else
{
lastBinRoundedGenomicOffset = roundedGenomicOffset;
lastFileNameGenomicOffset = fileNameGenomicOffset;
lastBinContigs = 0;
}
lastBinLastContig = binIndex ? binStartPos.getContigId() : 0;
fileNameReferencePosition = reference::genomicOffsetToPosition(fileNameGenomicOffset, contigs);
// ISAAC_THREAD_CERR << "roundedGenomicOffset:" << roundedGenomicOffset << std::endl;
// ISAAC_THREAD_CERR << "fileNameReferencePosition:" << fileNameReferencePosition << std::endl;
boost::filesystem::path binPath =
// Pad file names well, so that we don't have to worry about them becoming of different length.
// This is important for memory reservation to be stable
binDirectory / (boost::format("bin-%08d-%09d.dat")
% (binIndex ? (fileNameReferencePosition.getContigId() + 1) : 0)
% (binIndex ? fileNameReferencePosition.getPosition() : 0)).str();
return binPath;
}
static void buildBinPathList(
const alignment::matchSelector::BinIndexMap &binIndexMap,
const bfs::path &binDirectory,
const flowcell::BarcodeMetadataList &barcodeMetadataList,
const reference::SortedReferenceMetadata::Contigs &contigs,
const uint64_t targetBinLength,
alignment::BinMetadataList &ret)
{
ISAAC_TRACE_STAT("before buildBinPathList");
ISAAC_ASSERT_MSG(!binIndexMap.empty(), "Empty binIndexMap is illegal");
ISAAC_ASSERT_MSG(!binIndexMap.back().empty(), "Empty binIndexMap entry is illegal" << binIndexMap);
reference::SortedReferenceMetadata::Contigs offsetOderedContigs = contigs;
std::sort(offsetOderedContigs.begin(), offsetOderedContigs.end(),
[](const reference::SortedReferenceMetadata::Contig &left,
const reference::SortedReferenceMetadata::Contig &right)
{return left.genomicPosition_ < right.genomicPosition_;});
std::size_t genomicOffset = 0;
static const unsigned CONTIGS_PER_BIN_MAX = 16;
unsigned lastBinContigs = 0;
unsigned lastBinLastContig = -1;
uint64_t lastBinRoundedGenomicOffset = uint64_t(0) - 1;
uint64_t lastFileNameGenomicOffset = uint64_t(0) - 1;
BOOST_FOREACH(const std::vector<unsigned> &contigBins, binIndexMap)
{
ISAAC_ASSERT_MSG(!contigBins.empty(), "Unexpected empty contigBins");
// this offset goes in bin length increments. They don't sum up to the real contig length
std::size_t binGenomicOffset = genomicOffset;
for (unsigned i = contigBins.front(); contigBins.back() >= i; ++i)
{
const reference::ReferencePosition binStartPos = binIndexMap.getBinFirstPos(i);
// binIndexMap contig 0 is unaligned bin
ISAAC_ASSERT_MSG(!i || binIndexMap.getBinIndex(binStartPos) == i, "BinIndexMap is broken");
const boost::filesystem::path binPath =
makeDataFilePath(
binGenomicOffset, targetBinLength, i, binStartPos,
CONTIGS_PER_BIN_MAX, offsetOderedContigs, binDirectory,
lastBinLastContig, lastBinRoundedGenomicOffset,
lastBinContigs, lastFileNameGenomicOffset);
const uint64_t binLength = i ? binIndexMap.getBinFirstInvalidPos(i) - binStartPos : 0;
ret.push_back(
alignment::BinMetadata(barcodeMetadataList.size(), ret.size(), binStartPos, binLength, binPath));
// ISAAC_THREAD_CERR << "binPathList.back():" << binPathList.back() << std::endl;
binGenomicOffset += binLength;
}
// ISAAC_THREAD_CERR << "contigBins.front():" << contigBins.front() << std::endl;
if (!ret.back().isUnalignedBin())
{
genomicOffset += contigs.at(ret.back().getBinStart().getContigId()).totalBases_;
}
}
}
BinningFragmentStorage::BinningFragmentStorage(
const boost::filesystem::path &tempDirectory,
const bool keepUnaligned,
const BinIndexMap &binIndexMap,
const reference::SortedReferenceMetadata::Contigs& contigs,
const flowcell::BarcodeMetadataList &barcodeMetadataList,
const bool preAllocateBins,
const uint64_t expectedBinSize,
const uint64_t targetBinLength,
const unsigned threads,
alignment::BinMetadataList &binMetadataList):
FragmentBinner(keepUnaligned, binIndexMap, preAllocateBins ? expectedBinSize : 0, threads),
binIndexMap_(binIndexMap),
expectedBinSize_(expectedBinSize),
binMetadataList_(binMetadataList)
{
buildBinPathList(
binIndexMap, tempDirectory, barcodeMetadataList, contigs, targetBinLength, binMetadataList_);
const std::size_t worstCaseEstimatedUnalignedBins =
// This assumes that none of the data will align and we will need to
// make as many unaligned bins as we expect the aligned ones to be there
// This is both bad and weak. Bad because we allocate pile of memory
// that will never be used with proper aligning data.
// Weak because if in fact nothing will align, we might need more unaligned bins than we expect.
// Keeping this here because we're talking about a few thousands relatively small structures,
// so pile is not large enough to worry about, and the reallocation will occur while no other threads
// are using the list, so it should not invalidate any references.
binMetadataList_.size() * binIndexMap.getBinLength() / targetBinLength +
// in case the above math returns 0, we'll have room for at least one unaligned bin
1;
binMetadataList_.reserve(binMetadataList_.size() + worstCaseEstimatedUnalignedBins);
unalignedBinMetadataReserve_.resize(worstCaseEstimatedUnalignedBins, binMetadataList_.back());
FragmentBinner::open(binMetadataList_.begin(), binMetadataList_.end());
}
BinningFragmentStorage::~BinningFragmentStorage()
{
}
void BinningFragmentStorage::store(
const BamTemplate &bamTemplate,
const unsigned barcodeIdx,
const unsigned threadNumber)
{
common::StaticVector<char, READS_MAX * (sizeof(io::FragmentHeader) + FRAGMENT_BYTES_MAX)> buffer;
if (2 == bamTemplate.getFragmentCount())
{
packPairedFragment(bamTemplate, 0, barcodeIdx, binIndexMap_, std::back_inserter(buffer));
const io::FragmentAccessor &fragment0 = reinterpret_cast<const io::FragmentAccessor&>(buffer.front());
packPairedFragment(bamTemplate, 1, barcodeIdx, binIndexMap_, std::back_inserter(buffer));
const io::FragmentAccessor &fragment1 = *reinterpret_cast<const io::FragmentAccessor*>(&buffer.front() + fragment0.getTotalLength());
storePaired(fragment0, fragment1, binMetadataList_, threadNumber);
}
else
{
packSingleFragment(bamTemplate, barcodeIdx, std::back_inserter(buffer));
const io::FragmentAccessor &fragment = reinterpret_cast<const io::FragmentAccessor&>(buffer.front());
storeSingle(fragment, binMetadataList_, threadNumber);
}
}
void BinningFragmentStorage::prepareFlush() noexcept
{
if (binMetadataList_.front().getDataSize() > expectedBinSize_)
{
ISAAC_ASSERT_MSG(!unalignedBinMetadataReserve_.empty(), "Unexpectedly ran out of reserved BinMetadata when extending the unaligned bin");
// does not cause memory allocation because of reserve in constructor
binMetadataList_.resize(binMetadataList_.size() + 1);
using std::swap;
swap(binMetadataList_.back(), unalignedBinMetadataReserve_.back());
unalignedBinMetadataReserve_.pop_back();
binMetadataList_.back() = binMetadataList_.front();
binMetadataList_.front().startNew();
}
}
} //namespace matchSelector
} // namespace alignment
} // namespace isaac
| 41.57563 | 145 | 0.703183 | Illumina |
53fc218fdcd65dc427360ddb202a4d1c73c959e3 | 3,611 | cpp | C++ | geometry/src/capsule.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 10 | 2016-06-01T12:54:45.000Z | 2021-09-07T17:34:37.000Z | geometry/src/capsule.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | null | null | null | geometry/src/capsule.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 4 | 2017-05-03T14:03:03.000Z | 2021-01-04T04:31:15.000Z | //==============================================================
// Copyright (C) 2004 Danny Chapman
// [email protected]
//--------------------------------------------------------------
//
/// @file capsule.cpp
//
//==============================================================
#include "capsule.hpp"
#include "intersection.hpp"
using namespace JigLib;
//==============================================================
// Clone
//==============================================================
tPrimitive* tCapsule::Clone() const
{
return new tCapsule(*this);
}
//==============================================================
// SegmentIntersect
//==============================================================
bool tCapsule::SegmentIntersect(tScalar &frac, tVector3 &pos, tVector3 &normal, const class tSegment &seg) const
{
bool result;
if (result = SegmentCapsuleIntersection(&frac, seg, *this))
{
pos = seg.GetPoint(frac);
normal = pos - mTransform.position;
normal -= Dot(normal, mTransform.orientation.GetLook()) * mTransform.orientation.GetLook();
normal.NormaliseSafe();
}
return result;
}
//==============================================================
// GetMassProperties
//==============================================================
void tCapsule::GetMassProperties(const tPrimitiveProperties &primitiveProperties,
tScalar &mass,
tVector3 ¢erOfMass,
tMatrix33 &inertiaTensor) const
{
if (primitiveProperties.mMassType == tPrimitiveProperties::MASS)
{
mass = primitiveProperties.mMassOrDensity;
}
else
{
if (primitiveProperties.mMassDistribution == tPrimitiveProperties::SOLID)
mass = GetVolume() * primitiveProperties.mMassOrDensity;
else
mass = GetSurfaceArea() * primitiveProperties.mMassOrDensity;
}
centerOfMass = GetPos() + 0.5f * GetLength() * GetOrient().GetLook();
/// todo check solid/shell
// first cylinder
tScalar cylinderMass = mass * PI * Sq(mRadius) * mLength / GetVolume();
tScalar Ixx = 0.5f * cylinderMass * Sq(mRadius);
tScalar Iyy = 0.25f * cylinderMass * Sq(mRadius) + (1.0f / 12.0f) * cylinderMass * Sq(mLength);
tScalar Izz = Iyy;
// add ends
tScalar endMass = mass - cylinderMass;
Ixx += 0.2f * endMass * Sq(mRadius);
Iyy += 0.4f * endMass * Sq(mRadius) + endMass * Sq(0.5f * mLength);
Izz += 0.4f * endMass * Sq(mRadius) + endMass * Sq(0.5f * mLength);
inertiaTensor.Set(Ixx, 0.0f, 0.0f,
0.0f, Iyy, 0.0f,
0.0f, 0.0f, Izz);
// transform - e.g. see p664 of Physics-Based Animation
// todo is the order correct here? Does it matter?
// Calculate the tensor in a frame at the CoM, but aligned with the world axes
inertiaTensor = mTransform.orientation * inertiaTensor * mTransform.orientation.GetTranspose();
// Transfer of axe theorem
inertiaTensor(0, 0) = inertiaTensor(0, 0) + mass * (Sq(centerOfMass.y) + Sq(centerOfMass.z));
inertiaTensor(1, 1) = inertiaTensor(1, 1) + mass * (Sq(centerOfMass.z) + Sq(centerOfMass.x));
inertiaTensor(2, 2) = inertiaTensor(2, 2) + mass * (Sq(centerOfMass.x) + Sq(centerOfMass.y));
inertiaTensor(0, 1) = inertiaTensor(1, 0) = inertiaTensor(0, 1) - mass * centerOfMass.x * centerOfMass.y;
inertiaTensor(1, 2) = inertiaTensor(2, 1) = inertiaTensor(1, 2) - mass * centerOfMass.y * centerOfMass.z;
inertiaTensor(2, 0) = inertiaTensor(0, 2) = inertiaTensor(2, 0) - mass * centerOfMass.z * centerOfMass.x;
}
| 39.681319 | 112 | 0.546109 | Ludophonic |
d87cc8d47fa687a1a4fa586a5d626144557df6fb | 850 | hpp | C++ | poet/detail/utility.hpp | fmhess/libpoet | ca6a168a772a1452ac39745a851ba390e86fad30 | [
"BSL-1.0"
] | 1 | 2017-04-03T11:53:20.000Z | 2017-04-03T11:53:20.000Z | poet/detail/utility.hpp | fmhess/libpoet | ca6a168a772a1452ac39745a851ba390e86fad30 | [
"BSL-1.0"
] | null | null | null | poet/detail/utility.hpp | fmhess/libpoet | ca6a168a772a1452ac39745a851ba390e86fad30 | [
"BSL-1.0"
] | null | null | null | // copyright (c) Frank Mori Hess <[email protected]> 2008-04-13
// 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 _POET_DETAIL_UTILITY_HPP
#define _POET_DETAIL_UTILITY_HPP
#include <boost/weak_ptr.hpp>
namespace poet
{
namespace detail
{
// deadlock-free locking of a pair of locks with arbitrary locking order
template<typename LockT, typename LockU>
void lock_pair(LockT &a, LockU &b)
{
while(true)
{
a.lock();
if(b.try_lock()) return;
a.unlock();
b.lock();
if(a.try_lock()) return;
b.unlock();
}
}
template<typename T>
boost::weak_ptr<T> make_weak(const boost::shared_ptr<T> &sp)
{
return boost::weak_ptr<T>(sp);
}
}
}
#endif // _POET_DETAIL_UTILITY_HPP
| 21.25 | 75 | 0.685882 | fmhess |
d886b626bba54bf7c1acdaf6800e7e362c9ca320 | 1,378 | hpp | C++ | GLSL-Pipeline/Toolkits/include/System/Func.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Func.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Func.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "DLL.hpp"
#include <functional>
namespace System
{
/**
* \brief Encapsulates a method that has specified parameters and returns a value of the type specified by the TResult
* parameter. Unlike in other .NET languages, the first paramenter correspondes to TResult.
* \tparam TResult The type of the return value of the method that this delegate encapsulates.
* \tparam Args The parameters of the method that this delegate encapsulates.
*/
template<typename TResult, typename ...Args>
class DLLExport Func final
{
public:
typedef std::function<TResult(Args...)> FuncType;
Func(FuncType func);
~Func();
#pragma region Public Instance Methods
TResult Invoke(Args&&... args);
#pragma endregion
private:
FuncType func;
};
template <typename TResult, typename ... Args>
Func<TResult, Args...>::Func(FuncType func)
{
this->func = func;
}
template <typename TResult, typename ... Args>
Func<TResult, Args...>::~Func()
{
}
#pragma region Public Instance Methods
template <typename TResult, typename ... Args>
TResult Func<TResult, Args...>::Invoke(Args&&... args)
{
if (&func != nullptr)
{
return func(args...);
}
return nullptr;
}
#pragma endregion
}
| 23.758621 | 122 | 0.624819 | GilFerraz |
d88756cddfe30e47e7f80e2cfebaaa7174008521 | 493 | cc | C++ | endo/module_wrap.cc | Qard/endo | 6e3241b12e58344524711d4db4ed44d115fa8175 | [
"MIT"
] | null | null | null | endo/module_wrap.cc | Qard/endo | 6e3241b12e58344524711d4db4ed44d115fa8175 | [
"MIT"
] | null | null | null | endo/module_wrap.cc | Qard/endo | 6e3241b12e58344524711d4db4ed44d115fa8175 | [
"MIT"
] | null | null | null | #include "module_wrap.h"
namespace endo {
ModuleWrap::ModuleWrap(Isolate* isolate, Local<Module> module, Local<String> url)
: module_(isolate, module),
url_(isolate, url) {};
bool ModuleWrap::operator==(Local<Module>& mod) {
return module_.Get(Isolate::GetCurrent())->GetIdentityHash() == mod->GetIdentityHash();
}
Local<Module> ModuleWrap::module() {
return module_.Get(Isolate::GetCurrent());
}
Local<String> ModuleWrap::url() {
return url_.Get(Isolate::GetCurrent());
}
}
| 22.409091 | 89 | 0.703854 | Qard |
d88790b0562948b7fa957ebf6c42c2c0eea6b303 | 2,542 | cp | C++ | Sources_Common/Application/Preferences/CSearchStyle.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Sources_Common/Application/Preferences/CSearchStyle.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Sources_Common/Application/Preferences/CSearchStyle.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Search style data object
// Stores hierarchical search criteria that can be saved in prefs or applied as filter
#include "CSearchStyle.h"
#include "char_stream.h"
#pragma mark ____________________________CSearchStyle
extern const char* cSpace;
// Copy construct
CSearchStyle::CSearchStyle(const CSearchStyle& copy)
{
mItem = nil;
_copy(copy);
}
// Assignment with same type
CSearchStyle& CSearchStyle::operator=(const CSearchStyle& copy)
{
if (this != ©)
{
_tidy();
_copy(copy);
}
return *this;
}
// Compare with same type
int CSearchStyle::operator==(const CSearchStyle& other) const
{
// Just compare names
return mName == other.mName;
}
void CSearchStyle::_copy(const CSearchStyle& copy)
{
mName = copy.mName;
mItem = new CSearchItem(*copy.mItem);
}
// Parse S-Expression element
bool CSearchStyle::SetInfo(char_stream& txt, NumVersion vers_prefs)
{
bool result = true;
txt.get(mName, true);
mItem = new CSearchItem;
mItem->SetInfo(txt);
return result;
}
// Create S_Expression element
cdstring CSearchStyle::GetInfo(void) const
{
cdstring all;
cdstring temp = mName;
temp.quote();
temp.ConvertFromOS();
all += temp;
all += cSpace;
all += mItem->GetInfo();
return all;
}
#pragma mark ____________________________CSearchStyleList
// Find named style
const CSearchStyle* CSearchStyleList::FindStyle(const cdstring& name) const
{
CSearchStyle temp(name);
CSearchStyleList::const_iterator found = begin();
for(; found != end(); found++)
{
if (**found == temp)
break;
}
if (found != end())
return *found;
else
return nil;
}
// Find index of named style
long CSearchStyleList::FindIndexOf(const cdstring& name) const
{
CSearchStyle temp(name);
CSearchStyleList::const_iterator found = begin();
for(; found != end(); found++)
{
if (**found == temp)
break;
}
if (found != end())
return found - begin();
else
return -1;
}
| 20.336 | 86 | 0.709284 | mulberry-mail |
d88b09f7941ed97b33f164ff59b9cd7a0be36365 | 606 | hpp | C++ | Helios/src/Game.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | Helios/src/Game.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | Helios/src/Game.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <SDL.h>
#include <memory>
#include "Texture.hpp"
#include "Sprite.hpp"
#include "Clock.hpp"
#include "Input.hpp"
#include "Event.hpp"
#include "SceneStateMachine.hpp"
#include "scenes/SceneSplashScreen.hpp"
#include "scenes/SceneGame.hpp"
namespace Helio
{
class Game
{
private:
Event event;
Clock clock;
double deltaTime;
SceneStateMachine sceneStateMachine;
public:
Game();
void CaptureEvent();
//void CaptureInput();
void ProcessInput();
void Update();
void LateUpdate();
void Draw();
void CalculateDeltaTime();
bool IsRunning();
~Game();
};
} | 15.947368 | 39 | 0.70132 | rgracari |
d88f5accbe4168ea1013c8b0dca216ac0573e7fd | 29,740 | hpp | C++ | include/CameraModels/CameraModelUtils.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | 34 | 2016-11-13T22:17:50.000Z | 2021-01-20T19:59:25.000Z | include/CameraModels/CameraModelUtils.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | null | null | null | include/CameraModels/CameraModelUtils.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T00:45:56.000Z | 2019-04-02T11:56:50.000Z | /**
* ****************************************************************************
* Copyright (c) 2015, Robert Lukierski.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ****************************************************************************
* Common types and functions.
* ****************************************************************************
*/
#ifndef CAMERA_MODEL_UTILS_HPP
#define CAMERA_MODEL_UTILS_HPP
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <unsupported/Eigen/AutoDiff>
#include <sophus/so2.hpp>
#include <sophus/se2.hpp>
#include <sophus/so3.hpp>
#include <sophus/se3.hpp>
// For future Eigen + CUDA
#ifndef EIGEN_DEVICE_FUNC
#define EIGEN_DEVICE_FUNC
#endif // EIGEN_DEVICE_FUNC
// If Cereal serializer is preferred
#ifdef CAMERA_MODELS_SERIALIZER_CEREAL
#define CAMERA_MODELS_HAVE_SERIALIZER
#define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE(cereal::make_nvp(NAME,VAR))
#endif // CAMERA_MODELS_SERIALIZER_CEREAL
// If Boost serializer is preferred
#ifdef CAMERA_MODELS_SERIALIZER_BOOST
#define CAMERA_MODELS_HAVE_SERIALIZER
#define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE & boost::serialization::make_nvp(NAME,VAR)
#endif // CAMERA_MODELS_SERIALIZER_BOOST
#ifndef VISIONCORE_EIGEN_MISSING_BITS_HPP
#define VISIONCORE_EIGEN_MISSING_BITS_HPP
namespace Eigen
{
namespace numext
{
template<typename T>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
T atan2(const T& y, const T &x) {
EIGEN_USING_STD_MATH(atan2);
return atan2(y,x);
}
#ifdef __CUDACC__
template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
float atan2(const float& y, const float &x) { return ::atan2f(y,x); }
template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
double atan2(const double& y, const double &x) { return ::atan2(y,x); }
#endif
}
template<typename DerType>
inline const Eigen::AutoDiffScalar<EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(typename Eigen::internal::remove_all<DerType>::type, typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar, product)>
atan(const Eigen::AutoDiffScalar<DerType>& x)
{
using namespace Eigen;
EIGEN_UNUSED typedef typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar Scalar;
using numext::atan;
return Eigen::MakeAutoDiffScalar(atan(x.value()),x.derivatives() * ( Scalar(1) / (Scalar(1) + x.value() * x.value()) ));
}
}
#endif // VISIONCORE_EIGEN_MISSING_BITS_HPP
namespace cammod
{
/**
* Camera Models
*/
enum class CameraModelType
{
PinholeDistance = 0,
PinholeDistanceDistorted,
PinholeDisparity,
PinholeDisparityDistorted,
Generic,
GenericDistorted,
Spherical,
SphericalPovRay,
Fisheye,
FisheyeDistorted,
PinholeDisparityBrownConrady
};
template<CameraModelType cmt>
struct CameraModelToTypeAndName;
/**
* Collection of common 2D/3D types.
*/
template<typename T>
struct ComplexTypes
{
typedef Sophus::SO3<T> RotationT;
typedef Sophus::SE3<T> TransformT;
typedef Eigen::Map<TransformT> TransformMapT;
typedef Eigen::Map<const TransformT> ConstTransformMapT;
typedef Eigen::Map<RotationT> RotationMapT;
typedef Eigen::Map<const RotationT> ConstRotationMapT;
typedef Sophus::SO2<T> Rotation2DT;
typedef Sophus::SE2<T> Transform2DT;
typedef Eigen::Map<Transform2DT> Transform2DMapT;
typedef Eigen::Map<const Transform2DT> ConstTransform2DMapT;
typedef Eigen::Map<Rotation2DT> Rotation2DMapT;
typedef Eigen::Map<const Rotation2DT> ConstRotation2DMapT;
typedef typename Sophus::SE3<T>::Tangent TangentTransformT;
typedef Eigen::Map<typename Sophus::SE3<T>::Tangent> TangentTransformMapT;
typedef Eigen::Map<const typename Sophus::SE3<T>::Tangent> ConstTangentTransformMapT;
typedef typename Sophus::SE2<T>::Tangent TangentTransform2DT;
typedef Eigen::Map<typename Sophus::SE2<T>::Tangent> TangentTransform2DMapT;
typedef Eigen::Map<const typename Sophus::SE2<T>::Tangent> ConstTangentTransform2DMapT;
typedef typename Sophus::SO3<T>::Tangent TangentRotationT;
typedef Eigen::Map<typename Sophus::SO3<T>::Tangent> TangentRotationMapT;
typedef Eigen::Map<const typename Sophus::SO3<T>::Tangent> ConstTangentRotationMapT;
typedef typename Sophus::SO2<T>::Tangent TangentRotation2DT;
typedef Eigen::Map<typename Sophus::SO2<T>::Tangent> TangentRotation2DMapT;
typedef Eigen::Map<const typename Sophus::SO2<T>::Tangent> ConstTangentRotation2DMapT;
typedef Eigen::Matrix<T,2,1> PixelT;
typedef Eigen::Map<PixelT> PixelMapT;
typedef Eigen::Map<const PixelT> ConstPixelMapT;
typedef typename TransformT::Point PointT;
typedef Eigen::Map<PointT> PointMapT;
typedef Eigen::Map<const PointT> ConstPointMapT;
typedef typename Transform2DT::Point Point2DT;
typedef Eigen::Map<Point2DT> Point2DMapT;
typedef Eigen::Map<const Point2DT> ConstPoint2DMapT;
typedef Eigen::Quaternion<T> QuaternionT;
typedef Eigen::Map<QuaternionT> QuaternionMapT;
typedef Eigen::Map<const QuaternionT> ConstQuaternionMapT;
typedef Eigen::Matrix<T,2,3> ForwardPointJacobianT;
typedef Eigen::Map<ForwardPointJacobianT> ForwardPointJacobianMapT;
typedef Eigen::Map<const ForwardPointJacobianT> ConstForwardPointJacobianMapT;
typedef Eigen::Matrix<T,3,2> InversePointJacobianT;
typedef Eigen::Map<InversePointJacobianT> InversePointJacobianMapT;
typedef Eigen::Map<const InversePointJacobianT> ConstInversePointJacobianMapT;
typedef Eigen::Matrix<T,2,2> DistortionJacobianT;
typedef Eigen::Map<DistortionJacobianT> DistortionJacobianMapT;
typedef Eigen::Map<const DistortionJacobianT> ConstDistortionJacobianMapT;
template<int ParametersToOptimize>
using ForwardParametersJacobianT = Eigen::Matrix<T,2,ParametersToOptimize>;
template<int ParametersToOptimize>
using ForwardParametersJacobianMapT = Eigen::Map<ForwardParametersJacobianT<ParametersToOptimize>>;
template<int ParametersToOptimize>
using ConstForwardParametersJacobianMapT = Eigen::Map<const ForwardParametersJacobianT<ParametersToOptimize>>;
};
template<typename T>
EIGEN_DEVICE_FUNC static inline T getFieldOfView(T focal, T width)
{
using Eigen::numext::atan;
return T(2.0) * atan(width / (T(2.0) * focal));
}
template<typename T>
EIGEN_DEVICE_FUNC static inline T getFocalLength(T fov, T width)
{
using Eigen::numext::tan;
return width / (T(2.0) * tan(fov / T(2.0)));
}
/**
* Runtime polymorphic interface if one prefers that.
*/
template<typename T>
class CameraInterface
{
public:
virtual ~CameraInterface() { }
virtual CameraModelType getModelType() const = 0;
virtual const char* getModelName() const = 0;
virtual bool pointValid(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0;
virtual bool pixelValid(T x, T y) const = 0;
virtual bool pixelValidSquare(T x, T y) const = 0;
virtual bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const = 0;
virtual bool pixelValidCircular(T x, T y) const = 0;
virtual bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const = 0;
virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0;
virtual typename ComplexTypes<T>::PointT inverse(T x, T y) const = 0;
virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PointT& pt) const = 0;
virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose,
const typename ComplexTypes<T>::PointT& pt) const = 0;
virtual typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose,
T x, T y, T dist) const = 0;
virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1,
const typename ComplexTypes<T>::PixelT& pix, T dist,
const typename ComplexTypes<T>::TransformT& pose2) const = 0;
virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1,
T x, T y, T dist, const typename ComplexTypes<T>::TransformT& pose2) const = 0;
};
/**
* Functions / methods shared by all the camera models.
*/
template<typename Derived>
class CameraFunctions
{
static constexpr unsigned int ParametersToOptimize = Eigen::internal::traits<Derived>::ParametersToOptimize;
static constexpr bool HasForwardPointJacobian = Eigen::internal::traits<Derived>::HasForwardPointJacobian;
static constexpr bool HasForwardParametersJacobian = Eigen::internal::traits<Derived>::HasForwardParametersJacobian;
static constexpr bool HasInversePointJacobian = Eigen::internal::traits<Derived>::HasInversePointJacobian;
static constexpr bool HasInverseParametersJacobian = Eigen::internal::traits<Derived>::HasInverseParametersJacobian;
public:
typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;
// ------------------- statics ---------------------
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose.inverse() * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose.inverse() * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
return Derived::template pixelValidCircular<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
Derived::template resizeViewport<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PointT& pt)
{
return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd,
const typename ComplexTypes<T>::RotationT& pose,
const typename ComplexTypes<T>::PointT& pt)
{
return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const Derived& ccd,
const typename ComplexTypes<T>::PixelT& pix)
{
return Derived::template inverse<T>(ccd, pix(0), pix(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pix, T dist)
{
return Derived::template inverse<T>(ccd, pix(0), pix(1)) * dist;
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, T x, T y, T dist)
{
return Derived::template inverse<T>(ccd, x, y) * dist;
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PixelT& pix, T dist)
{
return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,pix)) * dist));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose,
T x, T y, T dist)
{
return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,x,y)) * dist));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose1,
const typename ComplexTypes<T>::PixelT& pix,
T dist,
const typename ComplexTypes<T>::TransformT& pose2)
{
return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, pix, dist));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose1,
T x, T y, T dist,
const typename ComplexTypes<T>::TransformT& pose2)
{
return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, x, y, dist));
}
// ------------------- non statics ---------------------
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(T x, T y)
{
Derived::template resizeViewport<T>(*static_cast<Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(const typename ComplexTypes<T>::PixelT& pt)
{
Derived::template resizeViewport<T>(*static_cast<Derived*>(this), pt(0), pt(1));
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pointValid(const typename ComplexTypes<T>::PointT& pt) const
{
return Derived::template pointValid<T>(*static_cast<const Derived*>(this), pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(T x, T y) const
{
return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(T x, T y) const
{
return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const
{
return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), pt(0), pt(1));
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(T x, T y) const
{
return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const
{
return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), pt(0), pt(1));
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const
{
return Derived::template forward<T>(*static_cast<const Derived*>(this), tmp_pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(T x, T y) const
{
return Derived::template inverse<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) const
{
return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) const
{
return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardPointJacobian, typename ComplexTypes<T>::ForwardPointJacobianT>::type forwardPointJacobian(const typename ComplexTypes<T>::PointT& pt) const
{
return Derived::template forwardPointJacobian<T>(*static_cast<const Derived*>(this), pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardParametersJacobian, typename ComplexTypes<T>::template ForwardParametersJacobianT<ParametersToOptimize> >::type forwardParametersJacobian(const typename ComplexTypes<T>::PointT& pt) const
{
return Derived::template forwardParametersJacobian<T>(*static_cast<const Derived*>(this), pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const
{
return CameraFunctions::inverse<T>(*static_cast<const Derived*>(this), pix);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pix, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), x, y, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PixelT& pix, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, pix, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, T x, T y, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, x, y, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, const typename ComplexTypes<T>::PixelT& pix, T dist,
const typename ComplexTypes<T>::TransformT& pose2) const
{
return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, pix, dist, pose2);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, T x, T y, T dist,
const typename ComplexTypes<T>::TransformT& pose2) const
{
return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, x, y, dist, pose2);
}
};
/**
* Wraps templated typed camera model into a polymorphic class.
*/
template <typename ModelT>
class CameraFromCRTP : public ModelT, public CameraInterface<typename ModelT::Scalar>
{
public:
typedef ModelT Derived;
typedef typename Derived::Scalar Scalar;
CameraFromCRTP() = default;
CameraFromCRTP(const Derived& d) : Derived(d) { }
CameraFromCRTP(const CameraFromCRTP& other) = default;
virtual ~CameraFromCRTP() { }
virtual CameraModelType getModelType() const
{
return Derived::ModelType;
}
virtual const char* getModelName() const
{
return CameraModelToTypeAndName<Derived::ModelType>::Name;
}
virtual bool pointValid(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const
{
return Derived::template pointValid<Scalar>(tmp_pt);
}
virtual bool pixelValid(Scalar x, Scalar y) const
{
return Derived::template pixelValid<Scalar>(x,y);
}
virtual bool pixelValidSquare(Scalar x, Scalar y) const
{
return Derived::template pixelValidSquare<Scalar>(x,y);
}
virtual bool pixelValidSquare(const typename ComplexTypes<Scalar>::PixelT& pt) const
{
return Derived::template pixelValidSquare<Scalar>(pt);
}
virtual bool pixelValidCircular(Scalar x, Scalar y) const
{
return Derived::template pixelValidCircular<Scalar>(x,y);
}
virtual bool pixelValidCircular(const typename ComplexTypes<Scalar>::PixelT& pt) const
{
return Derived::template pixelValidCircular<Scalar>(pt);
}
virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const
{
return Derived::template forward<Scalar>(tmp_pt);
}
virtual typename ComplexTypes<Scalar>::PointT inverse(Scalar x, Scalar y) const
{
return Derived::template inverse<Scalar>(x,y);
}
virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::TransformT& pose,
const typename ComplexTypes<Scalar>::PointT& pt) const
{
return Derived::template forward<Scalar>(pose, pt);
}
virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::RotationT& pose,
const typename ComplexTypes<Scalar>::PointT& pt) const
{
return Derived::template forward<Scalar>(pose, pt);
}
virtual typename ComplexTypes<Scalar>::PointT inverse(const typename ComplexTypes<Scalar>::PixelT& pix) const
{
return Derived::template inverse<Scalar>(pix);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::PixelT& pix,
Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(pix,dist);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(Scalar x, Scalar y, Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(x,y,dist);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose,
const typename ComplexTypes<Scalar>::PixelT& pix,
Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(pose,pix,dist);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose,
Scalar x, Scalar y, Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(pose,x,y,dist);
}
virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1,
const typename ComplexTypes<Scalar>::PixelT& pix,
Scalar dist,
const typename ComplexTypes<Scalar>::TransformT& pose2) const
{
return Derived::template twoFrameProject<Scalar>(pose1,pix,dist,pose2);
}
virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1,
Scalar x, Scalar y, Scalar dist,
const typename ComplexTypes<Scalar>::TransformT& pose2) const
{
return Derived::template twoFrameProject<Scalar>(pose1,x,y,dist,pose2);
}
};
}
#endif // CAMERA_MODEL_UTILS_HPP
| 46.323988 | 263 | 0.648857 | lukier |
d894353cd687d3ce761962c40144ad58c01ad041 | 1,234 | cpp | C++ | EngineAttempt0/project/src/engine/general/Transform.cpp | MEEMEEMAN/EngineAttempt0 | 2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6 | [
"MIT"
] | null | null | null | EngineAttempt0/project/src/engine/general/Transform.cpp | MEEMEEMAN/EngineAttempt0 | 2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6 | [
"MIT"
] | null | null | null | EngineAttempt0/project/src/engine/general/Transform.cpp | MEEMEEMAN/EngineAttempt0 | 2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6 | [
"MIT"
] | null | null | null | #include "Transform.h"
void Transform::UpdateTRS()
{
mat4 modelMatrix = mat4(1);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.x), vec3(1, 0, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.y), vec3(0, 1, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.z), vec3(0, 0, 1));
modelMatrix = glm::scale(modelMatrix, scale);
mModelMatrix = modelMatrix;
CalcDirections();
}
void Transform::UpdateSRT()
{
mat4 modelMatrix = mat4(1);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.x), vec3(1, 0, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.y), vec3(0, 1, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.z), vec3(0, 0, 1));
modelMatrix = glm::translate(modelMatrix, position);
mModelMatrix = modelMatrix;
CalcDirections();
}
void Transform::CalcDirections()
{
mat4 inverse = glm::inverse(mModelMatrix);
mForward = glm::normalize(glm::vec3(inverse[2]));
vec3 right = glm::normalize(glm::cross(mForward, vec3(0, 1, 0)));
mRight = right;
vec3 top = glm::normalize(glm::cross(mForward, mRight));
mUp = top;
}
| 26.826087 | 81 | 0.703404 | MEEMEEMAN |
d89886f2c4165e5ace2f8f6e9b07abdfd2d5d458 | 233 | cpp | C++ | library/src/ButtonMatrix.cpp | StratifyLabs/LvglAPI | c869d5b38ad3aa148fa0801d12271f2d9a6043c5 | [
"MIT"
] | 1 | 2022-01-03T19:16:58.000Z | 2022-01-03T19:16:58.000Z | library/src/ButtonMatrix.cpp | StratifyLabs/LvglAPI | c869d5b38ad3aa148fa0801d12271f2d9a6043c5 | [
"MIT"
] | null | null | null | library/src/ButtonMatrix.cpp | StratifyLabs/LvglAPI | c869d5b38ad3aa148fa0801d12271f2d9a6043c5 | [
"MIT"
] | null | null | null | #include "lvgl/ButtonMatrix.hpp"
using namespace lvgl;
LVGL_OBJECT_ASSERT_SIZE(ButtonMatrix);
ButtonMatrix::ButtonMatrix(const char * name){
m_object = api()->btnmatrix_create(screen_object());
set_user_data(m_object,name);
}
| 21.181818 | 54 | 0.776824 | StratifyLabs |
d8a4014bf20f395ce43b7168392b63d604bc2586 | 346 | cpp | C++ | C++/sum-of-digits-in-the-minimum-number.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/sum-of-digits-in-the-minimum-number.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/sum-of-digits-in-the-minimum-number.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n * l), l is the max length of numbers
// Space: O(l)
class Solution {
public:
int sumOfDigits(vector<int>& A) {
int min_num = *min_element(A.begin(),A.end());
int total = 0;
while (min_num) {
total += min_num % 10;
min_num /= 10;
}
return total % 2 == 0;
}
};
| 21.625 | 54 | 0.488439 | jaiskid |
d8ad75d32fe936031a6c65bbb6bc7d6318b204cc | 4,244 | cpp | C++ | src/platform/lpc17xx/power.cpp | wangyanjunmsn/vi-firmware | a5940ab6c773457d4c41e80273ae0ce327164d60 | [
"BSD-3-Clause"
] | 148 | 2015-01-01T18:32:25.000Z | 2022-03-05T12:02:24.000Z | src/platform/lpc17xx/power.cpp | wangyanjunmsn/vi-firmware | a5940ab6c773457d4c41e80273ae0ce327164d60 | [
"BSD-3-Clause"
] | 109 | 2015-02-11T16:33:49.000Z | 2021-01-04T16:14:00.000Z | src/platform/lpc17xx/power.cpp | wangyanjunmsn/vi-firmware | a5940ab6c773457d4c41e80273ae0ce327164d60 | [
"BSD-3-Clause"
] | 89 | 2015-02-04T00:39:29.000Z | 2021-10-03T00:01:17.000Z | #include "power.h"
#include "util/log.h"
#include "gpio.h"
#include "lpc17xx_pinsel.h"
#include "lpc17xx_clkpwr.h"
#include "lpc17xx_wdt.h"
#define POWER_CONTROL_PORT 2
#define POWER_CONTROL_PIN 13
#define PROGRAM_BUTTON_PORT 2
#define PROGRAM_BUTTON_PIN 12
namespace gpio = openxc::gpio;
using openxc::gpio::GPIO_VALUE_HIGH;
using openxc::gpio::GPIO_VALUE_LOW;
using openxc::gpio::GPIO_DIRECTION_OUTPUT;
using openxc::util::log::debug;
const uint32_t DISABLED_PERIPHERALS[] = {
CLKPWR_PCONP_PCTIM0,
CLKPWR_PCONP_PCTIM1,
CLKPWR_PCONP_PCSPI,
CLKPWR_PCONP_PCI2C0,
CLKPWR_PCONP_PCRTC,
CLKPWR_PCONP_PCSSP1,
CLKPWR_PCONP_PCI2C1,
CLKPWR_PCONP_PCSSP0,
CLKPWR_PCONP_PCI2C2,
};
void setPowerPassthroughStatus(bool enabled) {
int pinStatus;
debug("Switching 12v power passthrough ");
if(enabled) {
debug("on");
pinStatus = 0;
} else {
debug("off");
pinStatus = 1;
}
gpio::setValue(POWER_CONTROL_PORT, POWER_CONTROL_PIN,
pinStatus ? GPIO_VALUE_HIGH : GPIO_VALUE_LOW);
}
void openxc::power::initialize() {
// Configure 12v passthrough control as a digital output
PINSEL_CFG_Type powerPassthroughPinConfig;
powerPassthroughPinConfig.OpenDrain = 0;
powerPassthroughPinConfig.Pinmode = 1;
powerPassthroughPinConfig.Funcnum = 0;
powerPassthroughPinConfig.Portnum = POWER_CONTROL_PORT;
powerPassthroughPinConfig.Pinnum = POWER_CONTROL_PIN;
PINSEL_ConfigPin(&powerPassthroughPinConfig);
gpio::setDirection(POWER_CONTROL_PORT, POWER_CONTROL_PIN, GPIO_DIRECTION_OUTPUT);
setPowerPassthroughStatus(true);
debug("Turning off unused peripherals");
for(unsigned int i = 0; i < sizeof(DISABLED_PERIPHERALS) /
sizeof(DISABLED_PERIPHERALS[0]); i++) {
CLKPWR_ConfigPPWR(DISABLED_PERIPHERALS[i], DISABLE);
}
PINSEL_CFG_Type programButtonPinConfig;
programButtonPinConfig.OpenDrain = 0;
programButtonPinConfig.Pinmode = 1;
programButtonPinConfig.Funcnum = 1;
programButtonPinConfig.Portnum = PROGRAM_BUTTON_PORT;
programButtonPinConfig.Pinnum = PROGRAM_BUTTON_PIN;
PINSEL_ConfigPin(&programButtonPinConfig);
}
void openxc::power::handleWake() {
// This isn't especially graceful, we just reset the device after a
// wakeup. Then again, it makes the code a hell of a lot simpler because we
// only have to worry about initialization of core peripherals in one spot,
// setup() in vi_firmware.cpp and main.cpp. I'll leave this for now and we
// can revisit it if there is some reason we need to keep state between CAN
// wakeup events (e.g. fine_odometer_since_restart could be more persistant,
// but then it actually might be more confusing since it'd be
// fine_odometer_since_we_lost_power)
NVIC_SystemReset();
}
void openxc::power::suspend() {
debug("Going to low power mode");
NVIC_EnableIRQ(CANActivity_IRQn);
NVIC_EnableIRQ(EINT2_IRQn);
setPowerPassthroughStatus(false);
// Disable brown-out detection when we go into lower power
LPC_SC->PCON |= (1 << 2);
// TODO do we need to disable and disconnect the main PLL0 before ending
// deep sleep, accoridn gto errata lpc1768-16.march2010? it's in some
// example code from NXP.
CLKPWR_DeepSleep();
}
void openxc::power::enableWatchdogTimer(int microseconds) {
WDT_Init(WDT_CLKSRC_IRC, WDT_MODE_RESET);
WDT_Start(microseconds);
}
void openxc::power::disableWatchdogTimer() {
// TODO this is nuts, but you can't change the WDMOD register until after
// the WDT times out. But...we are using a RESET with the WDT, so the whole
// board will reset and then we don't have any idea if the WDT should be
// disabled or not! This makes it really difficult to use the WDT for both
// normal runtime hard freeze protection and periodic wakeup from sleep (to
// check if CAN is active via OBD-II). I have to disable the regular WDT for
// now for this reason.
LPC_WDT->WDMOD = 0x0;
}
void openxc::power::feedWatchdog() {
WDT_Feed();
}
extern "C" {
void CANActivity_IRQHandler(void) {
openxc::power::handleWake();
}
void EINT2_IRQHandler(void) {
openxc::power::handleWake();
}
}
| 31.671642 | 85 | 0.723139 | wangyanjunmsn |
d8ad9b57ba96684e2d202bffd040cf4b8cd25d22 | 2,228 | cpp | C++ | src/time.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/time.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/time.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | //
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 06 Jun 2011 Brian Frank Creation
// 19 Aug 2014 Radu Racariu<[email protected]> Ported to C++
//
#include "time.hpp"
#include <sstream>
#include <ctime>
////////////////////////////////////////////////
// Time
////////////////////////////////////////////////
using namespace haystack;
////////////////////////////////////////////////
// to zinc
////////////////////////////////////////////////
// Encode as "hh:mm:ss.FFF"
const std::string Time::to_zinc() const
{
std::stringstream os;
if (hour < 10) os << '0'; os << hour << ':';
if (minutes < 10) os << '0'; os << minutes << ':';
if (sec < 10) os << '0'; os << sec;
if (ms != 0)
{
os << '.';
if (ms < 10) os << '0';
if (ms < 100) os << '0';
os << ms;
}
return os.str();
}
const Time& Time::MIDNIGHT = *new Time(0, 0, 0);
////////////////////////////////////////////////
// Equal
////////////////////////////////////////////////
bool Time::operator ==(const Time &other) const
{
return (hour == other.hour && minutes == other.minutes && sec == other.sec && ms == other.ms);
}
bool Time::operator==(const Val &other) const
{
if (type() != other.type())
return false;
return *this == static_cast<const Time&>(other);
}
////////////////////////////////////////////////
// Comparators
////////////////////////////////////////////////
bool Time::operator <(const Val &other) const
{
return type() == other.type() && compareTo(((Time&)other)) < 0;
}
bool Time::operator >(const Val &other) const
{
return type() == other.type() && compareTo(((Time&)other)) > 0;
}
Time::auto_ptr_t Time::clone() const
{
return auto_ptr_t(new Time(*this));
}
int Time::compareTo(const Time &other) const
{
if (hour < other.hour) return -1; else if (hour > other.hour) return 1;
if (minutes < other.minutes) return -1; else if (minutes > other.minutes) return 1;
if (sec < other.sec) return -1; else if (sec > other.sec) return 1;
if (ms < other.ms) return -1; else if (ms > other.ms) return 1;
return 0;
}
| 26.211765 | 98 | 0.480251 | kushaldalsania |
d8b48ddfbda489b7b393ff79497c2ac72d382948 | 2,095 | cpp | C++ | simulation/Rendering/Window.cpp | Terae/3D_Langton_Ant | 017dadbe2962018db043bf50e8a6dcd49ade0eac | [
"MIT"
] | null | null | null | simulation/Rendering/Window.cpp | Terae/3D_Langton_Ant | 017dadbe2962018db043bf50e8a6dcd49ade0eac | [
"MIT"
] | null | null | null | simulation/Rendering/Window.cpp | Terae/3D_Langton_Ant | 017dadbe2962018db043bf50e8a6dcd49ade0eac | [
"MIT"
] | null | null | null | //
// Created by benji on 10/11/16.
//
#include "Window.h"
#include "Context.h"
void glfwErrorCallback(int error, const char* description) {
std::cerr << _RED("There was a glfw error : ") << description << _RED(" (" + std::to_string(error) + ")") << std::endl;
}
Window::Window(std::string title) {
std::cout << "Starting GLFW" << std::endl;
// Init GLFW
if(!glfwInit()) {
std::cerr << "Error during glfw initializing" << std::endl;
return;
}
glfwSetErrorCallback(glfwErrorCallback);
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_SAMPLES, 16);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
_window = glfwCreateWindow(800, 600, title.c_str(), nullptr, nullptr);
if (!_window) {
std::cout << "Failed to create the GLFW window" << std::endl;
glfwTerminate();
return;
}
glfwMakeContextCurrent(_window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
glfwSwapInterval(1);
_context = std::make_unique<Context>(_window);
glEnable(GL_MULTISAMPLE);
}
Window::~Window() {
destroy();
}
void Window::setTitle(std::string newTitle) {
glfwSetWindowTitle(_window, newTitle.c_str());
}
void Window::destroy() {
if(_destroyed) return;
_destroyed = true;
glfwDestroyWindow(_window);
glfwTerminate();
}
bool Window::isWindowOpened() {
return !glfwWindowShouldClose(_window);
}
void Window::setKeyCallback(GLFWkeyfun func) {
glfwSetKeyCallback(_window, func);
}
void Window::setScrollCallback(GLFWscrollfun func) {
glfwSetScrollCallback(_window, func);
}
void Window::setupFrame() {
int width, height;
glfwGetFramebufferSize(_window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void Window::finalizeFrame() {
glfwSwapBuffers(_window);
glfwPollEvents();
} | 24.08046 | 123 | 0.681623 | Terae |
d8bab90ef5648fdbaf3215e78ab86b647e808d74 | 88 | cpp | C++ | src/core/Distributor.cpp | jozhalaj/gateway | 49168dcbcf833da690048880bb33542ffbc90ce3 | [
"BSD-3-Clause"
] | 7 | 2018-06-09T05:55:59.000Z | 2021-01-05T05:19:02.000Z | src/core/Distributor.cpp | jozhalaj/gateway | 49168dcbcf833da690048880bb33542ffbc90ce3 | [
"BSD-3-Clause"
] | 1 | 2019-12-25T10:39:06.000Z | 2020-01-03T08:35:29.000Z | src/core/Distributor.cpp | jozhalaj/gateway | 49168dcbcf833da690048880bb33542ffbc90ce3 | [
"BSD-3-Clause"
] | 11 | 2018-05-10T08:29:05.000Z | 2020-01-22T20:49:32.000Z | #include "core/Distributor.h"
using namespace BeeeOn;
Distributor::~Distributor()
{
}
| 11 | 29 | 0.738636 | jozhalaj |
d8befa451c1a63907b4b8ddd0f23ce49f4c051be | 862 | cpp | C++ | atcoder/B - Palindrome-philia/AC.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | atcoder/B - Palindrome-philia/AC.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | atcoder/B - Palindrome-philia/AC.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2019-12-08 18:03:30
* solution_verdict: AC language: C++14 (GCC 5.4.1)
* run_time: 1 ms memory_used: 256 KB
* problem: https://atcoder.jp/contests/abc147/tasks/abc147_b
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
string s;cin>>s;int n=s.size();
int ans=0;
for(int i=0;i<n/2;i++)
if(s[i]!=s[n-1-i])ans++;
cout<<ans<<endl;
return 0;
} | 43.1 | 111 | 0.37123 | kzvd4729 |
d8bf6f2fc9a378f878a916d6e37e9a41f08a12af | 1,313 | cpp | C++ | libdocscript/src/runtime/procedure/lambda_procedure.cpp | sotvokun/docscript | 0718c8943e895672b9570524cd9eb7ff019d079f | [
"MIT"
] | 1 | 2021-12-11T11:04:21.000Z | 2021-12-11T11:04:21.000Z | libdocscript/src/runtime/procedure/lambda_procedure.cpp | sotvokun/docscript | 0718c8943e895672b9570524cd9eb7ff019d079f | [
"MIT"
] | null | null | null | libdocscript/src/runtime/procedure/lambda_procedure.cpp | sotvokun/docscript | 0718c8943e895672b9570524cd9eb7ff019d079f | [
"MIT"
] | null | null | null | #include "libdocscript/runtime/datatype.h"
#include "libdocscript/runtime/procedure.h"
#include "libdocscript/runtime/value.h"
#include "libdocscript/runtime/environment.h"
#include "libdocscript/interpreter.h"
namespace libdocscript::runtime {
// +--------------------+
// Constructor
// +--------------------+
LambdaProcedure::LambdaProcedure(const parm_list& parameters, func_body body)
: Procedure(Procedure::Lambda), _parameters(parameters), _expression(body)
{}
// +--------------------+
// Public Functions
// +--------------------+
Value LambdaProcedure::invoke(const args_list &args, Environment &env) const
{
if(_parameters.size() != args.size()) {
throw UnexceptNumberOfArgument(_parameters.size(), args.size());
}
Environment subenv = env.derive();
for(decltype(_parameters.size()) i = 0; i != _parameters.size(); ++i) {
subenv.set<Value>(_parameters[i], args[i]);
}
return Interpreter(subenv).eval(_expression);
}
// +--------------------+
// Private Functions
// +--------------------+
DataType *LambdaProcedure::rawptr_clone() const
{
return new LambdaProcedure(*this);
}
// +--------------------+
// Type Conversion
// +--------------------+
LambdaProcedure::operator std::string() const
{
return "#lambda-procedure";
}
} | 25.745098 | 77 | 0.600914 | sotvokun |
d8cd55713bb6d0e47bcf9a195ec14a4b22825b20 | 765 | cpp | C++ | lib/Dialect/XTen/IR/XTenDialect.cpp | jcamacho1234/mlir-xten | 721f97fc01dd39a2f54ef3b409ceb5a9528c61f4 | [
"Apache-2.0"
] | 10 | 2021-11-05T00:08:47.000Z | 2022-02-09T20:12:56.000Z | lib/Dialect/XTen/IR/XTenDialect.cpp | jcamacho1234/mlir-xten | 721f97fc01dd39a2f54ef3b409ceb5a9528c61f4 | [
"Apache-2.0"
] | 1 | 2022-01-27T17:21:14.000Z | 2022-01-27T17:22:41.000Z | lib/Dialect/XTen/IR/XTenDialect.cpp | jcamacho1234/mlir-xten | 721f97fc01dd39a2f54ef3b409ceb5a9528c61f4 | [
"Apache-2.0"
] | 6 | 2021-11-10T06:49:47.000Z | 2021-12-22T19:02:48.000Z | //===- XTenDialect.cpp ------------------------------------------*- C++ -*-===//
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// (c) Copyright 2021 Xilinx Inc.
//
//===----------------------------------------------------------------------===//
#include "xten/Dialect/XTen/XTenDialect.h"
#include "xten/Dialect/XTen/XTenOps.h"
#include "mlir/IR/DialectImplementation.h"
#include "xten/Dialect/XTen/XTenOpsDialect.cpp.inc"
using namespace mlir;
using namespace xilinx::xten;
void XTenDialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "xten/Dialect/XTen/XTenOps.cpp.inc"
>();
}
| 27.321429 | 80 | 0.605229 | jcamacho1234 |
d8d41db745f162d061bcb56fdf849608ac910537 | 1,179 | cpp | C++ | Shoot/src/Color.cpp | franticsoftware/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | 3 | 2019-10-04T19:44:44.000Z | 2021-07-27T15:59:39.000Z | Shoot/src/Color.cpp | franticsoftware/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | 1 | 2019-07-20T05:36:31.000Z | 2019-07-20T22:22:49.000Z | Shoot/src/Color.cpp | aminere/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | null | null | null | /*
Amine Rehioui
Created: May 1st 2010
*/
#include "Shoot.h"
#include "Color.h"
namespace shoot
{
// static variables initialization
Color Color::Red = Color(1.0f, 0.0f, 0.0f, 1.0f);
Color Color::Green = Color(0.0f, 1.0f, 0.0f, 1.0f);
Color Color::Blue = Color(0.0f, 0.0f, 1.0f, 1.0f);
Color Color::White = Color(1.0f, 1.0f, 1.0f, 1.0f);
Color Color::Black = Color(0.0f, 0.0f, 0.0f, 1.0f);
Color Color::Yellow = Color(1.0f, 1.0f, 0.0f, 1.0f);
Color Color::Zero = Color(0.0f, 0.0f, 0.0f, 0.0f);
//! constructor
Color::Color() : R(1.0f), G(1.0f), B(1.0f), A(1.0f)
{
}
bool Color::operator == (const Color& other) const
{
return (Math::FEqual(R, other.R)
&& Math::FEqual(G, other.G)
&& Math::FEqual(B, other.B)
&& Math::FEqual(A, other.A));
}
Color Color::operator + (const Color& other) const
{
Color result(R+other.R, G+other.G, B+other.B, A+other.A);
return result;
}
Color Color::operator - (const Color& other) const
{
Color result(R-other.R, G-other.G, B-other.B, A-other.A);
return result;
}
Color Color::operator * (f32 fValue) const
{
Color result(R*fValue, G*fValue, B*fValue, A*fValue);
return result;
}
}
| 21.436364 | 59 | 0.617472 | franticsoftware |
d8df3c1daffa3d064eeca194082eebff5b91e34e | 311 | cpp | C++ | legion/engine/llri-dx/llri.cpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 16 | 2021-09-10T18:11:37.000Z | 2022-01-26T06:28:51.000Z | legion/engine/llri-dx/llri.cpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 13 | 2021-09-12T16:28:47.000Z | 2022-02-07T19:34:01.000Z | legion/engine/llri-dx/llri.cpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 1 | 2021-08-15T23:35:32.000Z | 2021-08-15T23:35:32.000Z | /**
* @file llri.cpp
* @copyright 2021-2021 Leon Brands. All rights served.
* @license: https://github.com/Legion-Engine/Legion-LLRI/blob/main/LICENSE
*/
#include <llri/llri.hpp>
namespace llri
{
[[nodiscard]] implementation getImplementation()
{
return implementation::DirectX12;
}
}
| 19.4375 | 75 | 0.678457 | Rythe-Interactive |
d8e4153c4406f004e7438070813d1b8ed7ad35ac | 958 | cpp | C++ | dev/test/simple_start_stop/main.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | 3 | 2020-01-25T12:49:55.000Z | 2021-11-08T10:42:09.000Z | dev/test/simple_start_stop/main.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | null | null | null | dev/test/simple_start_stop/main.cpp | Stiffstream/mosquitto_transport | b7bd85746b7b5ba9f96a9128a12292ebb0604454 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <mosquitto_transport/a_transport_manager.hpp>
#include <so_5/all.hpp>
using namespace std::chrono_literals;
void
do_test()
{
mosquitto_transport::lib_initializer_t mosq_lib;
so_5::launch( [&mosq_lib]( auto & env ) {
env.introduce_coop( [&mosq_lib]( so_5::coop_t & coop ) {
using namespace mosquitto_transport;
coop.make_agent< a_transport_manager_t >(
std::ref(mosq_lib),
connection_params_t{
"test-client",
"localhost",
1883u,
5u },
spdlog::stdout_logger_mt( "mosqt" ) );
struct stop : so_5::signal_t {};
auto stopper = coop.define_agent();
stopper.on_start( [stopper]{
so_5::send_delayed< stop >( stopper, 15s );
} );
stopper.event< stop >(
stopper, [&coop] { coop.deregister_normally(); } );
} );
} );
}
int main()
{
try
{
do_test();
}
catch( const std::exception & ex )
{
std::cerr << "Oops! " << ex.what() << std::endl;
}
}
| 19.16 | 58 | 0.627349 | Stiffstream |
d8e694d86bf0df4afeb16f257b966127ed42f3fd | 867 | cpp | C++ | projects/abuild/cache/abi.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | projects/abuild/cache/abi.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | projects/abuild/cache/abi.cpp | agnesoft/adev-alt | 3df0329939e3048bbf5db252efb5f74de9c0f061 | [
"Apache-2.0"
] | null | null | null | #ifndef __clang__
export module abuild.cache:abi;
export import astl;
#endif
namespace abuild
{
//! The `ABI` represent the compiler toolchain
//! application binary interface.
export struct ABI
{
//! Processor architecture.
enum class Architecture
{
//! ARM
ARM,
//! Intel x86
X86
};
//! Architecture's register size.
enum class Bitness
{
//! 32 bits
X32,
//! 64 bits
X64
};
//! Platform or operating system.
enum class Platform
{
//! Linux
Linux,
//! Unix
Unix,
//! Windows
Windows
};
//! Processor architecture
Architecture architecture = Architecture::X86;
//! Register size
Bitness bitness = Bitness::X64;
//! Target platform
Platform platform = Platform::Linux;
};
}
| 15.763636 | 50 | 0.558247 | agnesoft |
d8e8d67e6a22e721c27a4f9ef527f81eb4c477a2 | 1,201 | cpp | C++ | 9999/1197.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 9999/1197.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 9999/1197.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | 1 | 2022-01-11T05:03:52.000Z | 2022-01-11T05:03:52.000Z | #include <iostream>
#include <tuple>
#include <vector>
#include <queue>
using namespace std;
vector<pair<int, int>> graph[10001];
int visited[10001];
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
int V, E;
cin >> V >> E;
for (int i = 0; i < E; i++)
{
int s, e, w;
cin >> s >> e >> w;
graph[s].push_back(make_pair(e, w));
graph[e].push_back(make_pair(s, w));
}
int cost = 0;
vector<int> mst_nodes;
vector<pair<int, int>> mst_edges;
priority_queue<tuple<int, int, int>> pq;
mst_nodes.push_back(1);
visited[1] = true;
for (int i = 0; i < graph[1].size(); i++){
pq.push(make_tuple(-graph[1][i].second, 1, graph[1][i].first));
}
while (!pq.empty())
{
int w = -get<0>(pq.top());
int s = get<1>(pq.top());
int e = get<2>(pq.top());
pq.pop();
if (visited[e]) continue;
mst_nodes.push_back(e);
mst_edges.push_back(make_pair(s, e));
for (int i = 0; i < graph[e].size(); i++){
pq.push(make_tuple(-graph[e][i].second, e, graph[e][i].first));
}
cost += w;
visited[e] = true;
}
cout << cost;
} | 24.510204 | 75 | 0.512073 | rmagur1203 |
d8e99a8f9376036a394248698698d57d76039d1d | 12,337 | cpp | C++ | GraphicsSandbox/Engine.cpp | UberCelloCzar/GraphicsSandbox | 3a96f99ca3693a67fdff69fdf7d338e8e5d21086 | [
"MIT"
] | null | null | null | GraphicsSandbox/Engine.cpp | UberCelloCzar/GraphicsSandbox | 3a96f99ca3693a67fdff69fdf7d338e8e5d21086 | [
"MIT"
] | null | null | null | GraphicsSandbox/Engine.cpp | UberCelloCzar/GraphicsSandbox | 3a96f99ca3693a67fdff69fdf7d338e8e5d21086 | [
"MIT"
] | null | null | null | #include "Engine.h"
#include "D11Graphics.h"
Engine::Engine()
{
}
Engine::~Engine()
{
}
void Engine::Initialize()
{
assetManager = new AssetManager();
graphics = new D11Graphics(); // Create whichever graphics system we're using and initialize it
graphics->Initialize();
GameSetup();
__int64 perfFreq;
QueryPerformanceFrequency((LARGE_INTEGER*)&perfFreq);
perfCounterSeconds = 1.0 / (double)perfFreq;
__int64 now;
QueryPerformanceCounter((LARGE_INTEGER*)&now);
startTime = now;
currentTime = now;
previousTime = now;
}
void Engine::GameSetup()
{
/* Load Shaders */
assetManager->LoadVertexShader((char*)"BaseVS", "BaseVertexShader", graphics);
assetManager->LoadPixelShader((char*)"BasePS", "BasePixelShader", graphics);
assetManager->LoadVertexShader((char*)"SkyboxVS", "SkyboxVertexShader", graphics);
assetManager->LoadPixelShader((char*)"SkyboxPS", "SkyboxPixelShader", graphics);
/* Initialize Camera */
camera = new Camera();
camera->position = XMFLOAT3(0.f, 0.f, -10.f);
camera->direction = XMFLOAT3(0.f, 0.f, 1.f);
camera->up = XMFLOAT3(0.f, 1.f, 0.f);
camera->rotationRads = XMFLOAT2(0.f, 0.f);
//camera->rotationMatrix = glm::rotate(glm::rotate(glm::mat4(1.f), -.1f, glm::vec3(1, 0, 0)), .1f, glm::vec3(0,1,0)); // Identity matrix
XMStoreFloat4(&camera->rotationQuaternion, XMQuaternionIdentity());
CalculateProjectionMatrix();
CalculateProjViewMatrix();
/* Load Models */
assetManager->LoadModel((char*)"Cube", "cube.obj", graphics);
assetManager->LoadModel((char*)"Cone", "cone.obj", graphics);
assetManager->LoadModel((char*)"Sphere", "sphere.obj", graphics);
assetManager->LoadModel((char*)"Cerberus", "Cerberus.fbx", graphics);
/* Load Textures */
{
assetManager->LoadDDSTexture((char*)"SM_EnvMap", "SnowMachineEnv", graphics);
assetManager->LoadDDSTexture((char*)"SM_IrrMap", "SnowMachineIrr", graphics);
assetManager->LoadDDSTexture((char*)"SM_SpecMap", "SnowMachineSpec", graphics);
assetManager->LoadDDSTexture((char*)"BRDF_LUT", "SnowMachineBrdf", graphics);
assetManager->LoadWICTexture((char*)"M_100Metal", "solidgoldmetal.png", graphics);
assetManager->LoadWICTexture((char*)"M_0Metal", "nometallic.png", graphics);
assetManager->LoadWICTexture((char*)"A_Gold", "solidgoldbase.png", graphics);
assetManager->LoadWICTexture((char*)"N_Plain", "solidgoldnormal.png", graphics);
assetManager->LoadWICTexture((char*)"R_Gold", "solidgoldroughness.png", graphics);
assetManager->LoadWICTexture((char*)"A_Snow", "Snow_001_COLOR.png", graphics);
assetManager->LoadWICTexture((char*)"N_Snow", "Snow_001_NORM.png", graphics);
assetManager->LoadWICTexture((char*)"R_Snow", "Snow_001_ROUGH.png", graphics);
assetManager->LoadWICTexture((char*)"AO_Snow", "Snow_001_OCC.png", graphics);
assetManager->LoadWICTexture((char*)"A_Rock", "holey-rock1-albedo.png", graphics);
assetManager->LoadWICTexture((char*)"AO_Rock", "holey-rock1-ao.png", graphics);
assetManager->LoadWICTexture((char*)"N_Rock", "holey-rock1-normal-ue.png", graphics);
assetManager->LoadWICTexture((char*)"R_Rock", "holey-rock1-roughness.png", graphics);
assetManager->LoadWICTexture((char*)"A_Cerberus", "Cerberus_A.jpg", graphics);
assetManager->LoadWICTexture((char*)"N_Cerberus", "Cerberus_N.jpg", graphics);
assetManager->LoadWICTexture((char*)"M_Cerberus", "Cerberus_M.jpg", graphics);
assetManager->LoadWICTexture((char*)"R_Cerberus", "Cerberus_R.jpg", graphics);
assetManager->LoadWICTexture((char*)"AO_Cerberus", "Cerberus_AO.jpg", graphics);
}
/* Create Game Objects */
GameEntity* cube = new GameEntity(); // Entity 0 should always be a unit cube
cube->position = XMFLOAT3(0.f, 0.f, 0.f);
cube->scale = XMFLOAT3(1.f, 1.f, 1.f);
XMStoreFloat4(&cube->rotationQuaternion, XMQuaternionIdentity());
cube->modelKey = "Cube";
cube->albedoKey = "A_Gold";
cube->normalKey = "N_Plain";
cube->metallicKey = "M_100Metal";
cube->roughnessKey = "R_Gold";
cube->aoKey = "M_100Metal";
cube->vertexShaderConstants = {};
GameEntity* snowball = new GameEntity();
snowball->position = XMFLOAT3(0.f, 0.f, 5.0f);
snowball->scale = XMFLOAT3(2.f, 2.f, 2.f);
XMStoreFloat4(&snowball->rotationQuaternion, XMQuaternionIdentity());
snowball->modelKey = "Sphere";
snowball->albedoKey = "A_Snow";
snowball->normalKey = "N_Snow";
snowball->metallicKey = "M_0Metal";
snowball->roughnessKey = "R_Snow";
snowball->aoKey = "AO_Snow";
snowball->vertexShaderConstants = {};
GameEntity* rock = new GameEntity();
rock->scale = XMFLOAT3(2.f, 2.f, 2.f);
rock->position = XMFLOAT3(5.f, 0.f, 5.0f);
XMStoreFloat4(&rock->rotationQuaternion, XMQuaternionIdentity());
rock->modelKey = "Sphere";
rock->albedoKey = "A_Rock";
rock->normalKey = "N_Rock";
rock->metallicKey = "M_0Metal";
rock->roughnessKey = "R_Rock";
rock->aoKey = "AO_Rock";
rock->vertexShaderConstants = {};
GameEntity* block = new GameEntity();
block->scale = XMFLOAT3(1.f, 1.f, 1.f);
block->position = XMFLOAT3(-5.f, 0.f, 5.0f);
XMStoreFloat4(&block->rotationQuaternion, XMQuaternionIdentity());
block->modelKey = "Cube";
block->albedoKey = "A_Gold";
block->normalKey = "N_Plain";
block->metallicKey = "M_100Metal";
block->roughnessKey = "R_Gold";
block->aoKey = "M_100Metal";
block->vertexShaderConstants = {};
GameEntity* cerberus = new GameEntity();
cerberus->scale = XMFLOAT3(.1f, .1f, .1f);
cerberus->position = XMFLOAT3(-10.f, 0.f, 20.0f);
XMStoreFloat4(&cerberus->rotationQuaternion, XMQuaternionIdentity());
cerberus->modelKey = "Cerberus";
cerberus->albedoKey = "A_Cerberus";
cerberus->normalKey = "N_Cerberus";
cerberus->metallicKey = "M_Cerberus";
cerberus->roughnessKey = "R_Cerberus";
cerberus->aoKey = "AO_Cerberus";
cerberus->vertexShaderConstants = {};
entities.push_back(cube);
entities.push_back(snowball);
entities.push_back(rock);
entities.push_back(block);
entities.push_back(cerberus);
for (auto& e : entities)
{
CalculateProjViewWorldMatrix(e);
e->vertexShaderConstantBuffer = graphics->CreateConstantBuffer(&(e->vertexShaderConstants), sizeof(VShaderConstants));
}
/* Create Constant Buffers */
pixelShaderConstants.cameraPosition.x = camera->position.x;
pixelShaderConstants.cameraPosition.y = camera->position.y;
pixelShaderConstants.cameraPosition.z = camera->position.z;
pixelShaderConstants.lightPos1 = XMFLOAT3A(5.f, 2.f, 15.f);
pixelShaderConstants.lightPos2 = XMFLOAT3A(10.f, 5.f, 3.f);
pixelShaderConstants.lightPos3 = XMFLOAT3A(0.f, 10.f, 7.f);
pixelShaderConstants.lightColor1 = XMFLOAT3A(.95f, .95f, 0.f);
pixelShaderConstants.lightColor2 = XMFLOAT3A(0.f, .95f, .95f);
pixelShaderConstants.lightColor3 = XMFLOAT3A(.95f, 0.f, .95f);
skyboxVShaderConstants.projection = camera->projection;
skyboxVShaderConstants.view = camera->view;
skyboxVShaderConstants.projection = camera->projection;
skyboxVShaderConstants.view = camera->view;
pixelShaderConstantBuffer = graphics->CreateConstantBuffer(&pixelShaderConstants, sizeof(PShaderConstants));
skyboxVShaderConstantBuffer = graphics->CreateConstantBuffer(&skyboxVShaderConstants, sizeof(SkyboxVShaderConstants));
}
void Engine::Run()
{
Initialize();
bool quit = false;
while (!quit)
{
UpdateTimer();
graphics->UpdateStats(totalTime);
Update();
Draw();
quit = graphics->HandleLowLevelEvents(GetAsyncKeyState(VK_ESCAPE));
}
ShutDown();
}
void Engine::UpdateTimer()
{
__int64 now;
QueryPerformanceCounter((LARGE_INTEGER*)&now); // Gat current time
currentTime = now;
deltaTime = std::max((float)((currentTime - previousTime) * perfCounterSeconds), 0.0f); // Calc delta time, ensure it's not less than zero
totalTime = (float)((currentTime - startTime) * perfCounterSeconds); // Calculate the total time from start to now
previousTime = currentTime; // Save current time for next frame
}
void Engine::Update()
{
//printf("%f, %f\n", graphics->rotateBy.x, graphics->rotateBy.y);
camera->Rotate(graphics->rotateBy.x, graphics->rotateBy.y);
graphics->rotateBy = XMFLOAT2(0, 0);
float right = 0;
float forward = 0;
float vert = 0;
if (GetAsyncKeyState('A') & 0x8000) right -= 5 * deltaTime;
if (GetAsyncKeyState('D') & 0x8000) right += 5 * deltaTime;
if (GetAsyncKeyState('W') & 0x8000) forward += 5 * deltaTime;
if (GetAsyncKeyState('S') & 0x8000) forward -= 5 * deltaTime;
if (GetAsyncKeyState('Q') & 0x8000) vert -= 5 * deltaTime;
if (GetAsyncKeyState('E') & 0x8000) vert += 5 * deltaTime;
if (forward != 0 || right != 0 || vert != 0) camera->Move(forward, right, vert);
}
void Engine::Draw()
{
graphics->BeginNewFrame();
CalculateProjViewMatrix();
graphics->SetVertexShader(assetManager->GetVertexShader(std::string("BaseVS")));
graphics->SetPixelShader(assetManager->GetPixelShader(std::string("BasePS")));
pixelShaderConstants.cameraPosition.x = camera->position.x;
pixelShaderConstants.cameraPosition.y = camera->position.y;
pixelShaderConstants.cameraPosition.z = camera->position.z;
for (size_t i = 1; i < entities.size(); ++i)
{
CalculateProjViewWorldMatrix(entities[i]); // Update the main matrix in the vertex shader constants area of the entity
graphics->SetConstantBufferVS(entities[i]->vertexShaderConstantBuffer, &(entities[i]->vertexShaderConstants), sizeof(VShaderConstants));
graphics->SetConstantBufferPS(pixelShaderConstantBuffer, &pixelShaderConstants, sizeof(PShaderConstants));
graphics->SetTexture(assetManager->GetTexture(entities[i]->albedoKey), 0);
graphics->SetTexture(assetManager->GetTexture(entities[i]->normalKey), 1);
graphics->SetTexture(assetManager->GetTexture(entities[i]->metallicKey), 2);
graphics->SetTexture(assetManager->GetTexture(entities[i]->roughnessKey), 3);
graphics->SetTexture(assetManager->GetTexture(entities[i]->aoKey), 4);
graphics->SetTexture(assetManager->GetTexture("BRDF_LUT"), 5);
graphics->SetTexture(assetManager->GetTexture("SM_IrrMap"), 6);
graphics->SetTexture(assetManager->GetTexture("SM_SpecMap"), 7);
Model* model = assetManager->GetModel(entities[i]->modelKey);
for (size_t j = 0; j < model->meshes.size(); ++j)
{
graphics->DrawMesh(model->meshes[j]); // If we have a bunch of the same object and we have time, I can add a render for instancing
}
}
/* Draw the Skybox Last */
graphics->SetVertexShader(assetManager->GetVertexShader(std::string("SkyboxVS")));
graphics->SetPixelShader(assetManager->GetPixelShader(std::string("SkyboxPS")));
CalculateProjViewWorldMatrix(entities[0]); // Update the main matrix in the vertex shader constants area of the entity
skyboxVShaderConstants.projection = camera->projection;
skyboxVShaderConstants.view = camera->view;
graphics->SetConstantBufferVS(skyboxVShaderConstantBuffer, &skyboxVShaderConstants, sizeof(SkyboxVShaderConstants));
graphics->SetTexture(assetManager->GetTexture("SM_EnvMap"), 0);
Model* model = assetManager->GetModel(entities[0]->modelKey);
graphics->DrawSkybox(model->meshes[0]);
graphics->EndFrame();
}
void Engine::ShutDown()
{
pixelShaderConstantBuffer->Release();
skyboxVShaderConstantBuffer->Release();
for (auto& e : entities)
{
e->vertexShaderConstantBuffer->Release();
delete e;
}
delete camera;
assetManager->Destroy();
graphics->DestroyGraphics();
delete assetManager;
delete graphics;
}
void Engine::CalculateProjectionMatrix()
{
XMStoreFloat4x4(&camera->projection, XMMatrixTranspose(XMMatrixPerspectiveFovLH(fov, graphics->aspectRatio, 0.1f, 1000.0f))); // Update with new w/h
}
void Engine::CalculateProjViewMatrix()
{
XMMATRIX view = XMMatrixTranspose(XMMatrixLookToLH(XMLoadFloat3(&camera->position), XMLoadFloat3(&camera->direction), XMLoadFloat3(&camera->up)));
XMStoreFloat4x4(&camera->view, view);
XMStoreFloat4x4(&camera->projView, XMLoadFloat4x4(&camera->projection) * view);
}
void Engine::CalculateProjViewWorldMatrix(GameEntity* entity)
{
XMMATRIX world = XMMatrixTranspose(XMMatrixScaling(entity->scale.x, entity->scale.y, entity->scale.z) * XMMatrixRotationQuaternion(XMLoadFloat4(&entity->rotationQuaternion)) * XMMatrixTranslation(entity->position.x, entity->position.y, entity->position.z));
XMStoreFloat4x4(&entity->vertexShaderConstants.world, world);
XMStoreFloat4x4(&entity->vertexShaderConstants.projViewWorld, XMLoadFloat4x4(&camera->projView) * world); // This result is already transpose, as the individual matrices are transpose and the mult order is reversed
}
| 39.415335 | 258 | 0.739078 | UberCelloCzar |
d8f3c20502910b642f3ca733a9c5e5b8a24ad94c | 607 | cpp | C++ | C++/Dynamic_Programming/1003.cpp | SkydevilK/BOJ | 4b79a258c52aca24683531d64736b91cbdfca3f2 | [
"MIT"
] | null | null | null | C++/Dynamic_Programming/1003.cpp | SkydevilK/BOJ | 4b79a258c52aca24683531d64736b91cbdfca3f2 | [
"MIT"
] | null | null | null | C++/Dynamic_Programming/1003.cpp | SkydevilK/BOJ | 4b79a258c52aca24683531d64736b91cbdfca3f2 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstring>
using namespace std;
int note_zero[41];
int note_one[41];
void dp()
{
for (int i = 2; i < 41; ++i)
{
note_zero[i] = note_zero[i - 2] + note_zero[i - 1];
note_one[i] = note_one[i - 2] + note_one[i - 1];
}
}
int main(void)
{
ios::sync_with_stdio(false);
memset(note_zero, -1, sizeof(note_zero));
memset(note_one, -1, sizeof(note_one));
note_zero[0] = 1;
note_one[0] = 0;
note_zero[1] = 0;
note_one[1] = 1;
dp();
int T;
cin >> T;
for (int test = 1; test <= T; ++test)
{
int N = 0;
cin >> N;
cout << note_zero[N] << " " << note_one[N] << "\n";
}
}
| 18.393939 | 53 | 0.578254 | SkydevilK |
d8f5827ed2e61a8b336526ab372312d3a21186ff | 666 | hpp | C++ | Canteen.hpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | Canteen.hpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | Canteen.hpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | /*********************************************************************
** Program Filename: Canteen.cpp
** Author: Diana Bacon
** Date: 2015-12-05
** Description: Definition of the Canteen class. Functions and data
** related to the derived class for Canteen spaces.
*********************************************************************/
#ifndef Canteen_hpp
#define Canteen_hpp
#include <iostream>
#include "Space.hpp"
class Canteen : public Space
{
private:
public:
Canteen(); // default constructor
bool enter(Airman* const); // special function
~Canteen() {}; // destructor
};
#endif /* Canteen_hpp */
| 25.615385 | 71 | 0.510511 | dianabacon |
d8f5f664fe03cf939591e9af0b3f1e7f625f0439 | 2,430 | cc | C++ | tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestBoundaryConditionPoints.hh" // Implementation of class methods
#include "pylith/bc/PointForce.hh" // USES PointForce
#include "data/PointForceDataTri3.hh" // USES PointForceDataTri3
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/MeshOps.hh" // USES MeshOps::nondimensionalize()
#include "pylith/topology/Stratum.hh" // USES Stratum
#include "pylith/meshio/MeshIOAscii.hh" // USES MeshIOAscii
#include "spatialdata/geocoords/CSCart.hh" // USES CSCart
#include "spatialdata/units/Nondimensional.hh" // USES Nondimensional
// ----------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( pylith::bc::TestBoundaryConditionPoints );
// ----------------------------------------------------------------------
// Test _getPoints().
void
pylith::bc::TestBoundaryConditionPoints::testGetPoints(void)
{ // testGetPoints
PYLITH_METHOD_BEGIN;
topology::Mesh mesh;
PointForce bc;
PointForceDataTri3 data;
meshio::MeshIOAscii iohandler;
iohandler.filename(data.meshFilename);
iohandler.read(&mesh);
spatialdata::geocoords::CSCart cs;
spatialdata::units::Nondimensional normalizer;
cs.setSpaceDim(mesh.dimension());
cs.initialize();
mesh.coordsys(&cs);
topology::MeshOps::nondimensionalize(&mesh, normalizer);
bc.label(data.label);
bc.BoundaryConditionPoints::_getPoints(mesh);
const PetscDM dmMesh = mesh.dmMesh();CPPUNIT_ASSERT(dmMesh);
topology::Stratum heightStratum(dmMesh, topology::Stratum::HEIGHT, 0);
const PetscInt numCells = heightStratum.size();
const size_t numPoints = data.numForcePts;
// Check points
const int offset = numCells;
CPPUNIT_ASSERT_EQUAL(numPoints, bc._points.size());
for (int i=0; i < numPoints; ++i)
CPPUNIT_ASSERT_EQUAL(data.forcePoints[i]+offset, bc._points[i]);
PYLITH_METHOD_END;
} // testGetPoints
// End of file
| 30.759494 | 76 | 0.654321 | Grant-Block |
d8f72b9194e0af9370f4ece7e39abd1393eef4a3 | 567 | hpp | C++ | src/palm/batch.hpp | leezhenghui/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 351 | 2016-10-12T14:06:09.000Z | 2022-03-24T14:53:54.000Z | src/palm/batch.hpp | leezhenghui/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 7 | 2017-03-07T01:49:16.000Z | 2018-07-27T08:51:54.000Z | src/palm/batch.hpp | UncP/Mushroom | 8aed2bdd80453d856145925d067bef5ed9d10ee0 | [
"BSD-3-Clause"
] | 62 | 2016-10-31T12:46:45.000Z | 2021-12-28T11:25:26.000Z | /**
* > Author: UncP
* > Github: www.github.com/UncP/Mushroom
* > License: BSD-3
* > Time: 2018-7-28 15:33:00
**/
#ifndef _BATCH_HPP_
#define _BATCH_HPP_
#include "../include/utility.hpp"
namespace Mushroom {
class KeySlice;
class Batch : private NoCopy
{
public:
static uint32_t Size;
static void SetSize(uint32_t size);
Batch();
~Batch();
void SetKeySlice(uint32_t idx, const char *key);
const KeySlice* GetKeySlice(uint32_t idx) const;
private:
KeySlice **batch_;
};
} // Mushroom
#endif /* _BATCH_HPP_ */ | 14.921053 | 50 | 0.643739 | leezhenghui |
d8febc737fe1416c65cd87a7bace3dc194b673ca | 3,369 | cpp | C++ | source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp | dabachma/ProMaIDes_src | 3fa6263c46f89abbdb407f2e1643843d54eb6ccc | [
"BSD-3-Clause"
] | null | null | null | #include "Sys_Headers_Precompiled.h"
//#include "Sys_Output_Flag_Dia.h"
// Constructor
Sys_Output_Flag_Dia::Sys_Output_Flag_Dia(QWidget *parent) : QDialog(parent){
this->old_flag=false;
this->new_flag=false;
ui.setupUi(this);
ui.checkBox->setChecked(this->old_flag);
QObject::connect(ui.okButton, SIGNAL(clicked()), this, SLOT(accept()));
QObject::connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
//count the memory
Sys_Memory_Count::self()->add_mem((sizeof(Sys_Output_Flag_Dia)), _sys_system_modules::SYS_SYS);
}
// Destructor
Sys_Output_Flag_Dia::~Sys_Output_Flag_Dia(void){
Sys_Memory_Count::self()->minus_mem(sizeof(Sys_Output_Flag_Dia), _sys_system_modules::SYS_SYS);
}
//___________
//public
//Set the text for which moduls the outputflag should be changed
void Sys_Output_Flag_Dia::set_txt_modul_type(_sys_system_modules type){
QIcon icon;
switch (type){
case _sys_system_modules::SYS_SYS:
this->text = "Change the flag for the Modul SYS";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":prom_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::FPL_SYS:
this->text = "Change the flag for the Modul FPL";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":fpl_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::HYD_SYS:
this->text = "Change the flag for the Modul HYD";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":hyd_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::MADM_SYS:
this->text = "Change the flag for the Modul MADM";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":madm_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::DAM_SYS:
this->text = "Change the flag for the Modul DAM";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":dam_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::RISK_SYS:
this->text = "Change the flag for the Modul RISK";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":risk_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::ALT_SYS:
this->text = "Change the flag for the Modul ALT";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":alt_icon");
this->setWindowIcon(icon);
break;
case _sys_system_modules::COST_SYS:
this->text = "Change the flag for the Modul COST";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
icon.addFile(":cost_icon");
this->setWindowIcon(icon);
break;
default:
this->text = "Change the flag for the Modul NOTKNOWN";
ui.typeLineEdit->setText(text);
ui.typeLineEdit->setReadOnly(true);
}
}
//Set the current output flag
void Sys_Output_Flag_Dia::set_current_flag(const bool flag){
this->old_flag=flag;
ui.checkBox->setChecked(this->old_flag);
}
//Make the dialog and get the new detailed flag
bool Sys_Output_Flag_Dia::get_new_detailed_flag(void){
int decision =this->exec();
//rejected
if(decision ==0){
return this->old_flag;
}
//accepted
else{
this->new_flag=ui.checkBox->isChecked();
return this->new_flag;
}
} | 30.908257 | 96 | 0.724844 | dabachma |
2b045b93305594bb73add275c035977d2754913a | 322 | cpp | C++ | compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 588 | 2015-10-07T15:55:08.000Z | 2022-03-29T00:35:44.000Z | compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 459 | 2015-10-05T23:29:59.000Z | 2022-03-29T14:13:37.000Z | compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp | fmilano/CppMicroServices | b7e79edb558a63e45f6788e4a8b4e787cf956689 | [
"Apache-2.0"
] | 218 | 2015-11-04T08:19:48.000Z | 2022-03-24T02:17:08.000Z | #include "ServiceImpl.hpp"
namespace dependent {
TestBundleDSDependentOptionalImpl::TestBundleDSDependentOptionalImpl(
const std::shared_ptr<test::TestBundleDSUpstreamDependency>& c)
: test::TestBundleDSDependent()
, ref(c)
{}
TestBundleDSDependentOptionalImpl::~TestBundleDSDependentOptionalImpl() =
default;
}
| 24.769231 | 73 | 0.807453 | fmilano |
2b0b1a3c8acf26e971ecac158c0b31e96a01c8c3 | 3,581 | cpp | C++ | src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 742 | 2017-07-05T02:49:36.000Z | 2022-03-30T12:55:43.000Z | src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 73 | 2017-07-06T12:50:51.000Z | 2022-03-07T08:07:07.000Z | src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 425 | 2017-07-04T22:03:29.000Z | 2022-03-29T06:59:06.000Z | // Copyright (C) 2007-2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Copyright (C) 2008 Mikael Mayer
// Copyright (C) 2008 Julia Jesse
// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "treeiksolverpos_nr_jl.hpp"
namespace KDL {
TreeIkSolverPos_NR_JL::TreeIkSolverPos_NR_JL(const Tree& _tree,
const std::vector<std::string>& _endpoints,
const JntArray& _q_min, const JntArray& _q_max,
TreeFkSolverPos& _fksolver, TreeIkSolverVel& _iksolver,
unsigned int _maxiter, double _eps) :
tree(_tree), q_min(_q_min), q_max(_q_max), iksolver(_iksolver),
fksolver(_fksolver), delta_q(tree.getNrOfJoints()),
endpoints(_endpoints), maxiter(_maxiter), eps(_eps)
{
for (size_t i = 0; i < endpoints.size(); i++) {
frames.insert(Frames::value_type(endpoints[i], Frame::Identity()));
delta_twists.insert(Twists::value_type(endpoints[i], Twist::Zero()));
}
}
double TreeIkSolverPos_NR_JL::CartToJnt(const JntArray& q_init, const Frames& p_in, JntArray& q_out) {
q_out = q_init;
//First check if all elements in p_in are available:
for(Frames::const_iterator f_des_it=p_in.begin();f_des_it!=p_in.end();++f_des_it)
if(frames.find(f_des_it->first)==frames.end())
return -2;
unsigned int k=0;
while(++k <= maxiter) {
for (Frames::const_iterator f_des_it=p_in.begin();f_des_it!=p_in.end();++f_des_it){
//Get all iterators for this endpoint
Frames::iterator f_it = frames.find(f_des_it->first);
Twists::iterator delta_twist = delta_twists.find(f_des_it->first);
fksolver.JntToCart(q_out, f_it->second, f_it->first);
delta_twist->second = diff(f_it->second, f_des_it->second);
}
double res = iksolver.CartToJnt(q_out, delta_twists, delta_q);
if (res < eps) return res;
Add(q_out, delta_q, q_out);
for (unsigned int j = 0; j < q_min.rows(); j++) {
if (q_out(j) < q_min(j))
q_out( j) = q_min(j);
else if (q_out(j) > q_max(j))
q_out( j) = q_max(j);
}
}
if (k <= maxiter)
return 0;
else
return -3;
}
TreeIkSolverPos_NR_JL::~TreeIkSolverPos_NR_JL() {
}
}//namespace
| 42.129412 | 106 | 0.586987 | matchRos |
2b0c787652070af035f365871a15e179c7f10756 | 505 | cpp | C++ | src/test/config/schema.cpp | mpoeter/config | 9a20b1dde685d42190310fa51ecd271e66d90ea0 | [
"MIT"
] | 1 | 2020-03-17T20:47:52.000Z | 2020-03-17T20:47:52.000Z | src/test/config/schema.cpp | mpoeter/config | 9a20b1dde685d42190310fa51ecd271e66d90ea0 | [
"MIT"
] | null | null | null | src/test/config/schema.cpp | mpoeter/config | 9a20b1dde685d42190310fa51ecd271e66d90ea0 | [
"MIT"
] | null | null | null | // Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/config/
#include <tao/config.hpp>
#include <tao/config/schema.hpp>
int main()
{
const auto tcs = tao::config::schema::from_file( "tests/schema.tcs" );
const auto data = tao::config::from_file( "tests/schema.jaxn" );
const auto error = tcs.validate( data );
if( error ) {
std::cerr << std::setw( 2 ) << error << std::endl;
}
return !error ? 0 : 1;
}
| 28.055556 | 76 | 0.645545 | mpoeter |
2b0f49c1638c7ea6bf8f3d63268c53943d885bd0 | 21,707 | hpp | C++ | src/character/character.hpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | 18 | 2016-05-26T18:11:31.000Z | 2022-02-10T20:00:52.000Z | src/character/character.hpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | null | null | null | src/character/character.hpp | Galfurian/RadMud | 1362cb0ee1b7a17386e57a98e29dd8baeea75af3 | [
"MIT"
] | 2 | 2016-06-30T15:20:01.000Z | 2020-08-27T18:28:33.000Z | /// @file character.hpp
/// @brief Define all the methods need to manipulate a character.
/// @details It's the master class for both Player and Mobile, here are defined
/// all the common methods needed to manipulate every dynamic living
/// beeing that are playing.
/// @author Enrico Fraccaroli
/// @date Aug 23 2014
/// @copyright
/// Copyright (c) 2016 Enrico Fraccaroli <[email protected]>
/// 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.
#pragma once
#include "ability.hpp"
#include "exit.hpp"
#include "race.hpp"
#include "item.hpp"
#include "faction.hpp"
#include "bodyPart.hpp"
#include "stringBuilder.hpp"
#include "effectManager.hpp"
#include "processInput.hpp"
#include "combatAction.hpp"
#include "argumentHandler.hpp"
#include "meleeWeaponItem.hpp"
#include "rangedWeaponItem.hpp"
#include "characterPosture.hpp"
#include "characterVector.hpp"
#include "skillManager.hpp"
#include "itemUtils.hpp"
#include <deque>
#include <mutex>
class Room;
class Player;
class Mobile;
struct lua_State;
/// The list of possible actions.
using GenderType = enum class GenderType_t
{
None, ///< The character has no gender (robot).
Female, ///< The character is a female.
Male ///< The character is a male.
};
/// Used to determine the flag of the character.
using CharacterFlag = enum class CharacterFlag_t
{
None = 0, ///< No flag.
IsGod = 1, ///< The character is a GOD.
Invisible = 2 ///< The character is invisible.
};
/// @brief Character class, father of Player and Mobile.
/// @details
/// It's the main class that contains all the information that both
/// players and NPCs shares. In order to allow dynamic casting(polymorphism),
/// i've created a method called isMobile, used to identify the subtype of the
/// subclass.
class Character :
public UpdateInterface
{
public:
/// Character name.
std::string name;
/// Character description.
std::string description;
/// Character gender.
GenderType gender;
/// Character weight.
double weight;
/// Character level.
unsigned int level;
/// Character flags.
unsigned int flags;
/// The character race.
Race * race;
/// The character faction.
Faction * faction;
/// Character health value.
unsigned int health;
/// Character stamina value.
unsigned int stamina;
/// Character level of hunger
int hunger;
/// Character level of thirst.
int thirst;
/// Character abilities.
std::map<Ability, unsigned int> abilities;
/// The current room the character is in.
Room * room;
/// Character's inventory.
ItemVector inventory;
/// Character's equipment.
ItemVector equipment;
/// Character's posture.
CharacterPosture posture;
/// The lua_State associated with this character.
lua_State * L;
/// Character current action.
std::deque<std::shared_ptr<GeneralAction>> actionQueue;
/// Mutex for the action queue.
mutable std::mutex actionQueueMutex;
/// The input handler.
std::shared_ptr<ProcessInput> inputProcessor;
/// Active effects on player.
EffectManager effectManager;
/// The player's list of skills.
SkillManager skillManager;
/// List of opponents.
CombatHandler combatHandler;
/// @brief Constructor.
Character();
/// @brief Destructor.
virtual ~Character();
/// @brief Disable copy constructor.
Character(const Character & source) = delete;
/// @brief Disable assign operator.
Character & operator=(const Character &) = delete;
/// @brief Check the correctness of the character information.
/// @return <b>True</b> if the information are correct,<br>
/// <b>False</b> otherwise.
virtual bool check() const;
/// @brief Used to identify if this character is an npc.
/// @return <b>True</b> if is an NPC,<br>
/// <b>False</b> otherwise.
virtual bool isMobile() const;
/// @brief Used to identify if this character is a player.
/// @return <b>True</b> if is an NPC,<br>
/// <b>False</b> otherwise.
virtual bool isPlayer() const;
/// @brief Fills the provided table with the information concerning the
/// character.
/// @param sheet The table that has to be filled.
virtual void getSheet(Table & sheet) const;
/// @brief Initializes the variables of the chracter.
virtual void initialize();
/// @brief Return the name of the character with all lowercase characters.
/// @return The name of the character.
virtual std::string getName() const = 0;
/// @brief Return the name of the character.
/// @return The name of the character.
std::string getNameCapital() const;
/// @brief Return the static description of this character.
/// @return The static description.
std::string getStaticDesc() const;
/// @brief Return the subject pronoun for the character.
std::string getSubjectPronoun() const;
/// @brief Return the possessive pronoun for the character.
std::string getPossessivePronoun() const;
/// @brief Return the object pronoun for the character.
std::string getObjectPronoun() const;
/// @brief Allows to set the value of a given ability.
/// @param ability The ability to set.
/// @param value The value to set.
/// @return <b>True</b> if the value is correct,<br>
/// <b>False</b> otherwise.
bool setAbility(const Ability & ability, const unsigned int & value);
/// @brief Provides the value of the given ability.
/// @param ability The ability to retrieve.
/// @param withEffects If set to false, this function just return the
/// ability value without the contribution due to
/// the active effects.
/// @return The overall ability value.
unsigned int getAbility(const Ability & ability,
bool withEffects = true) const;
/// @brief Provides the modifier of the given ability.
/// @param ability The ability of which the modifier has to be
/// retrieved.
/// @param withEffects If set to false, this function just return the
/// ability modifier without the contribution due
/// to the active effects.
/// @return The overall ability modifer.
unsigned int getAbilityModifier(const Ability & ability,
bool withEffects = true) const;
/// @brief Provides the base ten logarithm of the desired ability
/// modifier, multiplied by an optional multiplier. Also,
/// a base value can be provided.
/// @details Value = Base + (Multiplier * log10(AbilityModifier))
/// @param ability The ability of which the modifier has to be
/// retrieved.
/// @param base The base value to which the evaluated modifier is summed.
/// @param multiplier The log10 modifer is multiplied by this value.
/// @param withEffects If set to false, this function just return the
/// ability modifier without the contribution due
/// to the active effects.
/// @return The overall base ten logarithm of the given ability modifer.
unsigned int getAbilityLog(
const Ability & ability,
const double & base = 0.0,
const double & multiplier = 1.0,
const bool & withEffects = true) const;
/// @brief Allows to SET the health value.
/// @param value The value to set.
/// @param force <b>True</b> if the value is greather than the maximum
/// the function set the health to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has set the value,<br>
/// <b>False</b> otherwise.
bool setHealth(const unsigned int & value, const bool & force = false);
/// @brief Allows to ADD a value to the current health value.
/// @param value The value to add.
/// @param force <b>True</b> if the resulting value is greather than
/// the maximum the function set the health to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has added the value,<br>
/// <b>False</b> otherwise.
bool addHealth(const unsigned int & value, const bool & force = false);
/// @brief Allows to REMOVE a value to the current health value.
/// @param value The value to remove.
/// @param force <b>True</b> if the resulting value is lesser than
/// zero the function set the health to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has removed the value,<br>
/// <b>False</b> otherwise.
bool remHealth(const unsigned int & value, const bool & force = false);
/// @brief Return the max health value.
/// @param withEffects <b>True</b> also add the health due to effects,<br>
/// <b>False</b> otherwise.
/// @return The maximum health for this character.
unsigned int getMaxHealth(bool withEffects = true) const;
/// @brief Get character condition.
/// @param self If the sentence has to be for another character or not.
/// @return Condition of this character.
std::string getHealthCondition(const bool & self = false);
/// @brief Allows to SET the stamina value.
/// @param value The value to set.
/// @param force <b>True</b> if the value is greather than the maximum
/// the function set the stamina to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has set the value,<br>
/// <b>False</b> otherwise.
bool setStamina(const unsigned int & value, const bool & force = false);
/// @brief Allows to ADD a value to the current stamina value.
/// @param value The value to add.
/// @param force <b>True</b> if the resulting value is greather than
/// the maximum the function set the stamina to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has added the value,<br>
/// <b>False</b> otherwise.
bool addStamina(const unsigned int & value, const bool & force = false);
/// @brief Allows to REMOVE a value to the current stamina value.
/// @param value The value to remove.
/// @param force <b>True</b> if the resulting value is lesser than
/// zero the function set the stamina to it and
/// returns true,<br>
/// <b>False</b> return false.
/// @return <b>True</b> if the function has removed the value,<br>
/// <b>False</b> otherwise.
bool remStamina(const unsigned int & value, const bool & force = false);
/// @brief Return the max stamina value.
/// @param withEffects <b>True</b> also add the stamina due to effects,<br>
/// <b>False</b> otherwise.
/// @return The maximum stamina for this character.
unsigned int getMaxStamina(bool withEffects = true) const;
/// @brief Get the character stamina condition.
/// @return Stamina condition of the character.
std::string getStaminaCondition();
/// @brief Evaluate the maximum distance at which the character can still see.
/// @return The maximum radius of view.
int getViewDistance() const;
/// @brief Allows to set an action.
/// @param _action The action that has to be set.
void pushAction(const std::shared_ptr<GeneralAction> & _action);
/// @brief Provides a pointer to the action at the front position and
/// then remove it from the queue.
void popAction();
/// @brief Provides a pointer to the current action.
std::shared_ptr<GeneralAction> & getAction();
/// @brief Provides a pointer to the current action.
std::shared_ptr<GeneralAction> const & getAction() const;
/// @brief Performs any pending action.
void performAction();
/// @brief Allows to reset the entire action queue.
void resetActionQueue();
/// @brief Search for the item in the inventory.
/// @param key The item to search.
/// @param number Position of the item we want to look for.
/// @return The item, if it's in the character's inventory.
inline Item * findInventoryItem(std::string const & key, int & number)
{
return ItemUtils::FindItemIn(inventory, key, number);
}
/// @brief Search for the item in equipment.
/// @param key The item to search.
/// @param number Position of the item we want to look for.
/// @return The item, if it's in the character's equipment.
Item * findEquipmentItem(std::string const & key, int & number)
{
return ItemUtils::FindItemIn(equipment, key, number);
}
/// @brief Search an item nearby, (eq, inv, room).
/// @param key The item to search.
/// @param number Position of the item we want to look for.
/// @return The item, if it's found.
Item * findNearbyItem(std::string const & key, int & number);
/// @brief Search the item at given position and return it.
/// @param bodyPart The body part where the method need to search the item.
/// @return The item, if it's in the character's equipment.
Item * findItemAtBodyPart(const std::shared_ptr<BodyPart> & bodyPart) const;
/// @brief Add the passed item to character's inventory.
/// @param item The item to add to inventory.
virtual void addInventoryItem(Item *& item);
/// @brief Equip the passed item.
/// @param item The item to equip.
virtual void addEquipmentItem(Item *& item);
/// @brief Remove the passed item from the character's inventory.
/// @param item The item to remove from inventory.
/// @return <b>True</b> if the operation goes well,<br>
/// <b>False</b> otherwise.
virtual bool remInventoryItem(Item * item);
/// @brief Remove from current equipment the item.
/// @param item The item to remove.
/// @return <b>True</b> if the operation goes well,<br>
/// <b>False</b> otherwise.
virtual bool remEquipmentItem(Item * item);
/// @brief Check if the player can carry the item.
/// @param item The item we want to check.
/// @param quantity The amount of item to check (by default it is 1).
/// @return <b>True</b> if the character can lift the item,<br>
/// <b>False</b> otherwise.
bool canCarry(Item * item, unsigned int quantity) const;
/// @brief The total carrying weight for this character.
/// @return The total carrying weight.
double getCarryingWeight() const;
/// @brief The maximum carrying weight for this character.
/// @return The maximum carrying weight.
double getMaxCarryingWeight() const;
/// @brief Check if the character can wield a given item.
/// @param item The item to wield.
/// @param error The error message.
/// @return Where the item can be wielded.
std::vector<std::shared_ptr<BodyPart>> canWield(Item * item,
std::string & error) const;
/// @brief Check if the character can wear a given item.
/// @param item The item to wear.
/// @param error The error message.
/// @return Where the item can be worn.
std::vector<std::shared_ptr<BodyPart>> canWear(Item * item,
std::string & error) const;
/// @brief Checks if inside the inventory there is a light source.
/// @return <b>True</b> if there is a light source,<br>
/// <b>False</b> otherwise.
bool inventoryIsLit() const;
/// @brief Sums the given value to the current thirst.
/// @param value The value to sum.
void addThirst(const int & value);
/// @brief Get character level of thirst.
/// @return Thirst of this character.
std::string getThirstCondition() const;
/// @brief Sums the given value to the current hunger.
/// @param value The value to sum.
void addHunger(const int & value);
/// @brief Get character level of hunger.
/// @return Hunger of this character.
std::string getHungerCondition() const;
/// @brief Update the health.
void updateHealth();
/// @brief Update the stamina.
void updateStamina();
/// @brief Update the hunger.
void updateHunger();
/// @brief Update the thirst.
void updateThirst();
/// @brief Update the list of expired effects.
void updateExpiredEffects();
/// @brief Update the list of activated effects.
void updateActivatedEffects();
/// @brief Provide a detailed description of the character.
/// @return A detailed description of the character.
std::string getLook();
/// @brief Check if the current character can see the target character.
/// @param target The target character.
/// @return <b>True</b> if the can see the other character,<br>
/// <b>False</b> otherwise.
bool canSee(Character * target) const;
// Combat functions.
/// @brief Provides the overall armor class.
/// @return The armor class.
unsigned int getArmorClass() const;
/// @brief Function which checks if the character can attack
/// with a weapon equipped at the given body part.
/// @param bodyPart The body part at which the weapon could be.
/// @return <b>True</b> if the item is there,<br>
/// <b>False</b> otherwise.
bool canAttackWith(const std::shared_ptr<BodyPart> & bodyPart) const;
/// @brief Checks if the given target is both In Sight and within the Range of Sight.
/// @param target The target character.
/// @param range The maximum range.
/// @return <b>True</b> if the target is in sight,<br>
/// <b>False</b> otherwise.
bool isAtRange(Character * target, const int & range);
/// @brief Handle what happend when this character die.
virtual void kill();
/// @brief Create a corpse on the ground.
/// @return A pointer to the corpse.
Item * createCorpse();
/// @brief Handle character input.
/// @param command Command that need to be handled.
/// @return <b>True</b> if the command has been correctly executed,<br>
/// <b>False</b> otherwise.
bool doCommand(const std::string & command);
/// @brief Returns the character <b>statically</b> casted to player.
/// @return The player version of the character.
Player * toPlayer();
/// @brief Returns the character <b>statically</b> casted to mobile.
/// @return The mobile version of the character.
Mobile * toMobile();
/// @brief Specific function used by lua to add an equipment item.
void luaAddEquipment(Item * item);
/// @brief Specific function used by lua to remove an equipment item.
bool luaRemEquipment(Item * item);
/// @brief Specific function used by lua to add an inventory item.
void luaAddInventory(Item * item);
/// @brief Specific function used by lua to remove an inventory item.
bool luaRemInventory(Item * item);
/// @brief Operator used to order the character based on their name.
bool operator<(const class Character & source) const;
/// @brief Operator used to order the character based on their name.
bool operator==(const class Character & source) const;
/// @brief Sends a message to the character.
/// @param msg Message to send.
virtual void sendMsg(const std::string & msg);
/// @brief Sends a message to the character.
/// @param msg The message to send
/// @param args Packed arguments.
template<typename ... Args>
void sendMsg(const std::string & msg, const Args & ... args)
{
this->sendMsg(StringBuilder::build(msg, args ...));
}
protected:
void updateTicImpl() override;
void updateHourImpl() override;
};
/// @addtogroup FlagsToList
/// @{
/// Return the string describing the type of Gender.
std::string GetGenderTypeName(GenderType type);
/// Return the string describing the given character flag.
std::string GetCharacterFlagName(CharacterFlag flag);
/// Return a list of string containg the Character flags contained inside the value.
std::string GetCharacterFlagString(unsigned int flags);
/// @}
| 39.111712 | 89 | 0.642466 | Galfurian |
2b108cb66775235bc0ce8abd982dc031aad83e6d | 760 | hpp | C++ | TurbulentArena/DebugWindow.hpp | doodlemeat/Turbulent-Arena | 9030f291693e670f7751e23538e649cc24dc929f | [
"MIT"
] | 2 | 2017-02-03T04:30:29.000Z | 2017-03-27T19:33:38.000Z | TurbulentArena/DebugWindow.hpp | doodlemeat/Turbulent-Arena | 9030f291693e670f7751e23538e649cc24dc929f | [
"MIT"
] | null | null | null | TurbulentArena/DebugWindow.hpp | doodlemeat/Turbulent-Arena | 9030f291693e670f7751e23538e649cc24dc929f | [
"MIT"
] | null | null | null | //DebugWindow.hpp
#pragma once
#include <sstream>
namespace bjoernligan
{
class DebugWindow : public sf::Drawable
{
private:
DebugWindow(const bool &p_bActive);
DebugWindow(const DebugWindow&);
DebugWindow& operator=(const DebugWindow&);
public:
typedef std::unique_ptr<DebugWindow> Ptr;
static Ptr Create(const bool &p_bActive = false);
bool Initialize();
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
void Update(const float &p_fDeltaTime);
void SetActive(const bool &p_bActive);
void SetPos(const float &p_x, const float &p_y);
void SetPos(const sf::Vector2f &p_xPos);
private:
bool m_bActive;
sf::Text m_xFps;
std::stringstream m_xSStream;
std::unique_ptr<sf::RectangleShape> m_xBgRect;
};
} | 22.352941 | 69 | 0.734211 | doodlemeat |
2b154804a41ee453695ad335d17a303a816c4e21 | 402 | hpp | C++ | raptor/gallery/par_matrix_market.hpp | lukeolson/raptor | 526c88d0801634e6fb41375ae077f2d4aa3241a4 | [
"BSD-2-Clause"
] | 25 | 2017-11-20T21:45:43.000Z | 2019-01-27T15:03:25.000Z | raptor/gallery/par_matrix_market.hpp | haoxiangmiao/raptor | 866977b8166e39675a6a1fb883c57b7b9395d32f | [
"BSD-2-Clause"
] | 3 | 2017-11-21T01:20:20.000Z | 2018-11-16T17:33:06.000Z | raptor/gallery/par_matrix_market.hpp | haoxiangmiao/raptor | 866977b8166e39675a6a1fb883c57b7b9395d32f | [
"BSD-2-Clause"
] | 5 | 2017-11-20T22:03:57.000Z | 2018-12-05T10:30:22.000Z | /*
* Matrix Market I/O library for ANSI C
*
* See http://math.nist.gov/MatrixMarket for details.
*
*
*/
#ifndef PAR_MM_IO_H
#define PAR_MM_IO_H
#include "matrix_market.hpp"
#include "core/types.hpp"
#include "core/par_matrix.hpp"
using namespace raptor;
/* high level routines */
ParCSRMatrix* read_par_mm(const char *fname);
void write_par_mm(ParCSRMatrix* A, const char *fname);
#endif
| 15.461538 | 54 | 0.723881 | lukeolson |
2b15ae0c66fac4c2c4afbc7a6ce2c233d8fe5be9 | 867 | hpp | C++ | include/basic3d/zbuffer.hpp | MasterQ32/Basic3D | 1da1ad64116018afe2b97372d9632d0b72b1ff95 | [
"MIT"
] | 1 | 2018-11-15T22:29:55.000Z | 2018-11-15T22:29:55.000Z | include/basic3d/zbuffer.hpp | MasterQ32/Basic3D | 1da1ad64116018afe2b97372d9632d0b72b1ff95 | [
"MIT"
] | null | null | null | include/basic3d/zbuffer.hpp | MasterQ32/Basic3D | 1da1ad64116018afe2b97372d9632d0b72b1ff95 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <array>
#include <limits>
namespace Basic3D
{
//! Provides a basic z-buffer
template<int WIDTH, int HEIGHT, typename Depth = std::uint16_t>
class ZBuffer
{
public:
typedef Depth depth_t;
private:
std::array<depth_t, WIDTH * HEIGHT> zvalues;
public:
ZBuffer() : zvalues() {
this->clear();
}
void clear(depth_t depth = std::numeric_limits<depth_t>::max()) {
for(int i = 0; i < WIDTH * HEIGHT; i++)
this->zvalues[i] = depth;
}
public:
void setDepth(int x, int y, depth_t const & value) {
zvalues[y * WIDTH + x] = value;
}
depth_t const & getDepth(int x, int y) const {
return zvalues[y * WIDTH + x];
}
};
}
| 23.432432 | 74 | 0.509804 | MasterQ32 |
2b24d50623f5ba9c0ed59fd55b0cb00c616c6aa3 | 2,353 | tpp | C++ | src/algorithms/rem_factorial_EltZZ.tpp | adienes/remainder-tree | 0aa76214ab6f2a4389ec45a239ea660749989a90 | [
"MIT"
] | null | null | null | src/algorithms/rem_factorial_EltZZ.tpp | adienes/remainder-tree | 0aa76214ab6f2a4389ec45a239ea660749989a90 | [
"MIT"
] | null | null | null | src/algorithms/rem_factorial_EltZZ.tpp | adienes/remainder-tree | 0aa76214ab6f2a4389ec45a239ea660749989a90 | [
"MIT"
] | null | null | null | // included by rem_factorial_custom.tpp (in case we want to change the file location)
#include <cassert>
#include <NTL/ZZ_pX.h>
#include <NTL/matrix.h>
#include "../elements/element.hpp"
#include "factorial_engine.hpp"
using NTL::ZZ;
using NTL::ZZ_p;
using NTL::ZZ_pX;
using NTL::Mat;
Elt<ZZ> calculate_factorial(long n, const Elt<ZZ>& m, const std::function<vector<Elt<ZZ>> (long, long)>& get_A, const PolyMatrix& formula){
if (n == 0) {
return Elt<ZZ>(1);
}
assert(("No formula given!" && not formula.empty()));
assert(("Element given is not a square matrix." && (formula.size() == formula[0].size())));
// Matrix-type elements
assert(("ZZ's must have 1x1 matrix formulas." && ((long)formula.size() <= 1)));
// Do naive_factorial if n is small enough
if(n < 30000 || formula.size() == 0){
return naive_factorial<Elt<ZZ>, Elt<ZZ>>(n, m, get_A); // TODO: write naive_factorial
}
long maxdeg = 0;
for(const auto& term : formula[0][0]){
if(term.first > maxdeg){
maxdeg = term.first;
}
}
// Linear and Polynomial-type elements
if(n < 1000000000 || maxdeg >= 2){
// TODO: convert polynomial coefficients into ZZ_p and call poly_factorial()
// Otherwise, do poly_factorial
ZZ_pX poly;
for(const auto& term : formula[0][0]){
ZZ_p coeff;
coeff.init(m.t);
coeff = term.second;
SetCoeff(poly, term.first, coeff);
}
ZZ_p output;
output.init(m.t);
output = poly_factorial(n, m.t, poly); // TODO: write poly_factorial
Elt<ZZ> output_elt(rep(output));
return output_elt;
}
// Large Linear-type elements
else{
// TODO: convert polynomial coefficients into Mat<ZZ_p> and call matrix_factorial()
Mat<ZZ_pX> matrix;
matrix.SetDims(1, 1);
ZZ_pX poly;
for(const auto& term : formula[0][0]){
ZZ_p coeff;
coeff.init(m.t);
coeff = term.second;
SetCoeff(poly, term.first, coeff);
}
matrix.put(0, 0, poly);
Mat<ZZ_p> output;
output.SetDims(1, 1);
output = matrix_factorial(n, m.t, matrix);
Elt<ZZ> output_elt(rep(output.get(0, 0)));
return output_elt;
}
}
| 30.166667 | 139 | 0.576711 | adienes |
2b27eac05c8402f32f1dbad10a6b1ff5dc8f5ac5 | 2,363 | cpp | C++ | codeforces/round-278/div-2/candy_boxes.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | codeforces/round-278/div-2/candy_boxes.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | codeforces/round-278/div-2/candy_boxes.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
inline void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
inline void solve_with_four_left_boxes(const vector<unsigned int>& boxes)
{
if ((3 * boxes[0] == boxes[3]) && (boxes[1] + boxes[2] == 4 * boxes[0]))
{
cout << "YES\n";
}
else
{
cout << "NO\n";
}
}
inline void solve_with_three_left_boxes(const vector<unsigned int>& boxes)
{
unsigned int missing_box;
if (3 * boxes[0] == boxes[2])
{
missing_box = 4 * boxes[0] - boxes[1];
}
else if (boxes[1] + boxes[2] == 4 * boxes[0])
{
missing_box = 3 * boxes[0];
}
else if (4 * boxes[2] == 3 * (boxes[0] + boxes[1]))
{
missing_box = boxes[2] / 3;
}
else
{
cout << "NO\n";
return;
}
cout << "YES" << '\n'
<< missing_box << '\n';
}
inline void solve_with_two_left_boxes(const vector<unsigned int>& boxes)
{
if (boxes[1] <= 3 * boxes[0])
{
cout << "YES" << '\n'
<< 4 * boxes[0] - boxes[1] << '\n'
<< 3 * boxes[0] << '\n';
}
else
{
cout << "NO\n";
}
}
inline void solve_with_one_left_box(const vector<unsigned int>& boxes)
{
cout << "YES" << '\n'
<< boxes[0] << '\n'
<< 3 * boxes[0] << '\n'
<< 3 * boxes[0] << '\n';
}
inline void solve_with_zero_left_boxes(const vector<unsigned int>& boxes)
{
cout << "YES" << '\n'
<< 1 << '\n'
<< 1 << '\n'
<< 3 << '\n'
<< 3 << '\n';
}
int main()
{
use_io_optimizations();
unsigned int left_boxes;
cin >> left_boxes;
vector<unsigned int> boxes(4);
for (unsigned int i {0}; i < left_boxes; ++i)
{
cin >> boxes[i];
}
sort(boxes.begin(), boxes.begin() + left_boxes);
switch (left_boxes)
{
case 4:
solve_with_four_left_boxes(boxes);
break;
case 3:
solve_with_three_left_boxes(boxes);
break;
case 2:
solve_with_two_left_boxes(boxes);
break;
case 1:
solve_with_one_left_box(boxes);
break;
case 0:
solve_with_zero_left_boxes(boxes);
break;
}
return 0;
}
| 19.211382 | 76 | 0.493017 | Rkhoiwal |
1a7098538ce52920df14b974fe6a6a1f795fb3b6 | 396 | cpp | C++ | src/ClosestBinarySearchTreeValue.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | src/ClosestBinarySearchTreeValue.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | src/ClosestBinarySearchTreeValue.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "ClosestBinarySearchTreeValue.hpp"
#include <cmath>
using namespace std;
int ClosestBinarySearchTreeValue::closestValue(TreeNode *root, double target) {
int closest = root->val;
while (root) {
if (abs(root->val - target) < abs(closest - target))
closest = root->val;
root = root->val < target ? root->right : root->left;
}
return closest;
} | 26.4 | 79 | 0.643939 | yanzhe-chen |
1a751dfcaf4dbf84cbd4870d1bb0d7be2d22a8ed | 11,084 | cpp | C++ | src/lib/serialport/qserialportinfo_mac.cpp | Hayesie88/emstudio | 0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b | [
"MIT"
] | 8 | 2015-11-16T19:15:55.000Z | 2021-02-17T23:58:33.000Z | src/lib/serialport/qserialportinfo_mac.cpp | Hayesie88/emstudio | 0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b | [
"MIT"
] | 5 | 2015-11-12T00:19:59.000Z | 2020-03-23T10:18:19.000Z | src/lib/serialport/qserialportinfo_mac.cpp | Hayesie88/emstudio | 0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b | [
"MIT"
] | 11 | 2015-03-15T23:02:48.000Z | 2021-09-05T14:17:13.000Z | /****************************************************************************
**
** Copyright (C) 2011-2012 Denis Shienkov <[email protected]>
** Copyright (C) 2011 Sergey Belyashov <[email protected]>
** Copyright (C) 2012 Laszlo Papp <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qserialportinfo.h"
#include "qserialportinfo_p.h"
#include <sys/param.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/storage/IOStorageDeviceCharacteristics.h> // for kIOPropertyProductNameKey
#include <IOKit/usb/USB.h>
#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)
# include <IOKit/serial/ioss.h>
#endif
#include <IOKit/IOBSD.h>
QT_BEGIN_NAMESPACE
enum { MATCHING_PROPERTIES_COUNT = 6 };
QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
{
QList<QSerialPortInfo> serialPortInfoList;
int matchingPropertiesCounter = 0;
::CFMutableDictionaryRef matching = ::IOServiceMatching(kIOSerialBSDServiceValue);
if (!matching)
return serialPortInfoList;
::CFDictionaryAddValue(matching,
CFSTR(kIOSerialBSDTypeKey),
CFSTR(kIOSerialBSDAllTypes));
io_iterator_t iter = 0;
kern_return_t kr = ::IOServiceGetMatchingServices(kIOMasterPortDefault,
matching,
&iter);
if (kr != kIOReturnSuccess)
return serialPortInfoList;
io_registry_entry_t service;
while ((service = ::IOIteratorNext(iter))) {
::CFTypeRef device = 0;
::CFTypeRef portName = 0;
::CFTypeRef description = 0;
::CFTypeRef manufacturer = 0;
::CFTypeRef vendorIdentifier = 0;
::CFTypeRef productIdentifier = 0;
io_registry_entry_t entry = service;
// Find MacOSX-specific properties names.
do {
if (!device) {
device =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault,
0);
if (device)
++matchingPropertiesCounter;
}
if (!portName) {
portName =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kIOTTYDeviceKey),
kCFAllocatorDefault,
0);
if (portName)
++matchingPropertiesCounter;
}
if (!description) {
description =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kIOPropertyProductNameKey),
kCFAllocatorDefault,
0);
if (!description)
description =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBProductString),
kCFAllocatorDefault,
0);
if (!description)
description =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR("BTName"),
kCFAllocatorDefault,
0);
if (description)
++matchingPropertiesCounter;
}
if (!manufacturer) {
manufacturer =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBVendorString),
kCFAllocatorDefault,
0);
if (manufacturer)
++matchingPropertiesCounter;
}
if (!vendorIdentifier) {
vendorIdentifier =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBVendorID),
kCFAllocatorDefault,
0);
if (vendorIdentifier)
++matchingPropertiesCounter;
}
if (!productIdentifier) {
productIdentifier =
::IORegistryEntrySearchCFProperty(entry,
kIOServicePlane,
CFSTR(kUSBProductID),
kCFAllocatorDefault,
0);
if (productIdentifier)
++matchingPropertiesCounter;
}
// If all matching properties is found, then force break loop.
if (matchingPropertiesCounter == MATCHING_PROPERTIES_COUNT)
break;
kr = ::IORegistryEntryGetParentEntry(entry, kIOServicePlane, &entry);
} while (kr == kIOReturnSuccess);
(void) ::IOObjectRelease(entry);
// Convert from MacOSX-specific properties to Qt4-specific.
if (matchingPropertiesCounter > 0) {
QSerialPortInfo serialPortInfo;
QByteArray buffer(MAXPATHLEN, 0);
if (device) {
if (::CFStringGetCString(CFStringRef(device),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->device = QString::fromUtf8(buffer);
}
::CFRelease(device);
}
if (portName) {
if (::CFStringGetCString(CFStringRef(portName),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->portName = QString::fromUtf8(buffer);
}
::CFRelease(portName);
}
if (description) {
if (::CFStringGetCString(CFStringRef(description),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->description = QString::fromUtf8(buffer);
}
::CFRelease(description);
}
if (manufacturer) {
if (::CFStringGetCString(CFStringRef(manufacturer),
buffer.data(),
buffer.size(),
kCFStringEncodingUTF8)) {
serialPortInfo.d_ptr->manufacturer = QString::fromUtf8(buffer);
}
::CFRelease(manufacturer);
}
quint16 value = 0;
if (vendorIdentifier) {
serialPortInfo.d_ptr->hasVendorIdentifier = ::CFNumberGetValue(CFNumberRef(vendorIdentifier), kCFNumberIntType, &value);
if (serialPortInfo.d_ptr->hasVendorIdentifier)
serialPortInfo.d_ptr->vendorIdentifier = value;
::CFRelease(vendorIdentifier);
}
if (productIdentifier) {
serialPortInfo.d_ptr->hasProductIdentifier = ::CFNumberGetValue(CFNumberRef(productIdentifier), kCFNumberIntType, &value);
if (serialPortInfo.d_ptr->hasProductIdentifier)
serialPortInfo.d_ptr->productIdentifier = value;
::CFRelease(productIdentifier);
}
serialPortInfoList.append(serialPortInfo);
}
(void) ::IOObjectRelease(service);
}
(void) ::IOObjectRelease(iter);
return serialPortInfoList;
}
QT_END_NAMESPACE
| 40.600733 | 138 | 0.480603 | Hayesie88 |
1a775015d67a723319faa41188ea368f93b840f6 | 764 | cpp | C++ | greedy_problems/maximum_frequency_of_element.cpp | sanathvernekar/Routine_codes | a898ca7e79cf39c289cb2fefaf764c9f8e0eb331 | [
"MIT"
] | null | null | null | greedy_problems/maximum_frequency_of_element.cpp | sanathvernekar/Routine_codes | a898ca7e79cf39c289cb2fefaf764c9f8e0eb331 | [
"MIT"
] | null | null | null | greedy_problems/maximum_frequency_of_element.cpp | sanathvernekar/Routine_codes | a898ca7e79cf39c289cb2fefaf764c9f8e0eb331 | [
"MIT"
] | null | null | null | #include <vector>
#include <map>
#include<bits/stdc++.h>
using namespace std;
long long int max_frequency(vector<long long int> const& v)
{
map<long long int, long long int> frequencyMap;
long long int maxFrequency = 0;
long long int mostFrequentElement = 0;
for (long long int x : v)
{
long long int f = ++frequencyMap[x];
if (f > maxFrequency)
{
maxFrequency = f;
mostFrequentElement = x;
}
}
return maxFrequency;
}
int main()
{
long long int t,n,i,j,temp;
cin>>t;
while(t--){
cin>>n;
vector<long long int >v;
for(i=0;i<n;i++){
cin>>temp;
v.push_back(temp);
}
cout<<max_frequency(v)<<endl;
}
} | 21.222222 | 59 | 0.537958 | sanathvernekar |
1a7d0a4b1f6fbfbd04070f3df6da1bcfbd53a229 | 1,077 | cpp | C++ | STRINGS/Upper case conversion.cpp | snanacha/Coding-questions | 18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d | [
"MIT"
] | null | null | null | STRINGS/Upper case conversion.cpp | snanacha/Coding-questions | 18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d | [
"MIT"
] | 1 | 2021-03-30T14:00:56.000Z | 2021-03-30T14:00:56.000Z | STRINGS/Upper case conversion.cpp | snanacha/Coding-questions | 18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d | [
"MIT"
] | null | null | null | /*
Upper case conversion
School Accuracy: 72.51% Submissions: 1152 Points: 0
Given a string str, convert the first letter of each word in the string to uppercase.
Example 1:
Input:
str = "i love programming"
Output: "I Love Programming"
Explanation:
'I', 'L', 'P' are the first letters of
the three words.
Your Task:
You dont need to read input or print anything. Complete the function transform() which takes s as input parameter and returns the transformed string.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N) to store resultant string
Constraints:
1 <= N <= 104
The original string str only consists of lowercase alphabets and spaces to separate words.
*/
CODE
----
string transform(string s)
{
// code here
int i;
for(i=0;i<s.size();i++) // to check if first few characters of a string have spaces
{
if(s[i]!=' ')
{ s[i]=toupper(s[i]); break; }
}
for(;i<s.size();i++)
{
if(s[i]==' ')
{ s[i+1]=toupper(s[i+1]); }
}
return s;
} | 22.914894 | 150 | 0.622098 | snanacha |
1a7d59aa8da04b3bc9b6a7c6c73cdfb020f12695 | 2,133 | cpp | C++ | examples/sample2.cpp | SoultatosStefanos/preconditions | 7c306219153e32afe6a915178f1e1c9fa1bdac8b | [
"MIT"
] | 1 | 2021-09-07T21:10:05.000Z | 2021-09-07T21:10:05.000Z | examples/sample2.cpp | SoultatosStefanos/preconditions | 7c306219153e32afe6a915178f1e1c9fa1bdac8b | [
"MIT"
] | null | null | null | examples/sample2.cpp | SoultatosStefanos/preconditions | 7c306219153e32afe6a915178f1e1c9fa1bdac8b | [
"MIT"
] | null | null | null | /**
* @file sample2.cpp
* @author Soultatos Stefanos ([email protected])
* @brief Contains sample code for the filters
* @version 2.0
* @date 2021-10-29
*
* @copyright Copyright (c) 2021
*
*/
#include "preconditions/filters.hpp"
#include <array>
#include <string>
namespace {
// Instead of:
//
// if (b.empty)
// {
// throw std::invalid_argument();
// }
// return b;
//
//
std::string verify_non_empty_string(const std::string b)
{
const auto not_empty = [&](const std::string x) { return x.empty(); };
return Preconditions::filter_argument<std::string>(b, not_empty);
}
// Instead of:
//
// if (b == 0)
// {
// throw std::domain_error();
// }
//
//
int divide(const int a, const int b)
{
Preconditions::filter_domain<int>(
b, [&](const int x) { return x != 0; }); // inline
Preconditions::filter_domain<int>(
b, [&](const int x) { return x != 0; }, "zero!"); // with msg
return a / b;
}
// Instead of:
//
// if (length < 1)
// {
// throw std::length_error();
// }
//
//
void peek_length(const int length)
{
Preconditions::filter_length<int>(
length, [&](const int) { return length >= 1; }); // inline
Preconditions::filter_length<int>(
length, [&](const int) { return length >= 1; },
"illegal length"); // with msg
}
// Instead of:
//
// if (index >= 3)
// {
// throw std::out_of_range();
// }
//
//
int get_index_of_array(const std::array<int, 3> a, const int index)
{
const auto in_range = [&](const int i) { return i <= 2; };
Preconditions::filter_range<int>(index, in_range); // inline
Preconditions::filter_range<int>(index, in_range, "range!"); // with msg
return a[index];
}
class Entity {
public:
bool valid() const { return true; }
};
// Instead of:
//
// if(!en.valid())
// {
// ??
// }
//
//
void do_wth_entity(const Entity& en)
{
const auto valid = [&](const Entity& e) { return e.valid(); };
Preconditions::filter_state<Entity>(en, valid); // inline
Preconditions::filter_state<Entity>(en, valid,
"invalid state"); // with msg
}
} // namespace | 20.708738 | 76 | 0.586498 | SoultatosStefanos |
1a8046f70fc3a8f51fa385ecdcfba6767d5f840f | 313 | cpp | C++ | Codeforces Round 323/Asphalting Roads/main.cpp | sqc1999-oi/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | 1 | 2016-07-18T12:05:56.000Z | 2016-07-18T12:05:56.000Z | Codeforces Round 323/Asphalting Roads/main.cpp | sqc1999/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | null | null | null | Codeforces Round 323/Asphalting Roads/main.cpp | sqc1999/Codeforces | 5551e0e4b9dc66bb77c697568f0584aac3dbefae | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
bool vh[51], vv[51];
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 1; i <= n*n; i++)
{
int h, v;
cin >> h >> v;
if (!vh[h] && !vv[v])
{
vh[h] = vv[v] = true;
cout << i << ' ';
}
}
}
| 14.904762 | 32 | 0.456869 | sqc1999-oi |
1a8b5129949c5c0ff7268512f53daab7dcbdecd0 | 433 | cpp | C++ | binary_search.cpp | ankitelectronicsenemy/CppCodes | e2f274330c12e59a6c401c162e8d899690db0e14 | [
"Apache-2.0"
] | null | null | null | binary_search.cpp | ankitelectronicsenemy/CppCodes | e2f274330c12e59a6c401c162e8d899690db0e14 | [
"Apache-2.0"
] | null | null | null | binary_search.cpp | ankitelectronicsenemy/CppCodes | e2f274330c12e59a6c401c162e8d899690db0e14 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int binary_search(int arr[],int n,int key)
{
int s=0;
int e=n-1;
while(s<=e)
{
int mid=(s+e)/2;
if(arr[mid]==key)
{
return mid;
}
if(arr[mid]>key)
{
e=mid-1;
}
else if(arr[mid]<key)
{
s=mid+1;
}
else
return -1 ;
}
return -1;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int key;
cin>>key;
cout<< binary_search(arr,n,key);
} | 8.836735 | 42 | 0.556582 | ankitelectronicsenemy |
1a8c74b4b5e597e0cc6288bffb2bbdcec3b8371b | 2,585 | cpp | C++ | VC2010Samples/ATL/Advanced/mfcatl/objone.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2010Samples/ATL/Advanced/mfcatl/objone.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2010Samples/ATL/Advanced/mfcatl/objone.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // ObjOne.cpp : implementation file
//
// This is a part of the Active Template Library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
#include "premfcat.h"
#include "MfcAtl.h"
#include "ObjOne.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CObjectOne
IMPLEMENT_DYNCREATE(CObjectOne, CCmdTarget)
CObjectOne::CObjectOne()
{
EnableAutomation();
// To keep the application running as long as an OLE automation
// object is active, the constructor calls AfxOleLockApp.
AfxOleLockApp();
}
CObjectOne::~CObjectOne()
{
// To terminate the application when all objects created with
// with OLE automation, the destructor calls AfxOleUnlockApp.
AfxOleUnlockApp();
}
void CObjectOne::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. The base class will automatically
// deletes the object. Add additional cleanup required for your
// object before calling the base class.
CCmdTarget::OnFinalRelease();
}
BEGIN_MESSAGE_MAP(CObjectOne, CCmdTarget)
//{{AFX_MSG_MAP(CObjectOne)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CObjectOne, CCmdTarget)
//{{AFX_DISPATCH_MAP(CObjectOne)
DISP_FUNCTION(CObjectOne, "SayHello", SayHello, VT_BSTR, VTS_NONE)
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
// Note: we add support for IID_IObjectOne to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
// {5D0CE84F-D909-11CF-91FC-00A0C903976F}
static const IID IID_IObjectOne =
{ 0x5d0ce84f, 0xd909, 0x11cf, { 0x91, 0xfc, 0x0, 0xa0, 0xc9, 0x3, 0x97, 0x6f } };
BEGIN_INTERFACE_MAP(CObjectOne, CCmdTarget)
INTERFACE_PART(CObjectOne, IID_IObjectOne, Dispatch)
END_INTERFACE_MAP()
// {5D0CE850-D909-11CF-91FC-00A0C903976F}
IMPLEMENT_OLECREATE(CObjectOne, "MfcAtl.ObjectOne", 0x5d0ce850, 0xd909, 0x11cf, 0x91, 0xfc, 0x0, 0xa0, 0xc9, 0x3, 0x97, 0x6f)
/////////////////////////////////////////////////////////////////////////////
// CObjectOne message handlers
BSTR CObjectOne::SayHello()
{
return SysAllocString(OLESTR("Hello from Object One!"));
}
| 28.406593 | 125 | 0.716441 | alonmm |
1a8e101fc9fd68633703ee9420f4a7abe1788773 | 954 | cpp | C++ | src/Gui/ExportToDotDialog.cpp | loganek/gstcreator | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | [
"BSD-3-Clause"
] | 1 | 2015-10-10T23:21:00.000Z | 2015-10-10T23:21:00.000Z | src/Gui/ExportToDotDialog.cpp | loganek/gstcreator | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | [
"BSD-3-Clause"
] | null | null | null | src/Gui/ExportToDotDialog.cpp | loganek/gstcreator | 619f1a6f1ee39c7c5b883c0a676cd490f59ac81b | [
"BSD-3-Clause"
] | null | null | null | /*
* gstcreator
* ExportToDotDialog.cpp
*
* Created on: 24 sty 2014
* Author: Marcin Kolny <[email protected]>
*/
#include "ExportToDotDialog.h"
#include "ui_ExportToDotDialog.h"
#include <QCheckBox>
#include <QFileDialog>
#include <cstdlib>
ExportToDotDialog::ExportToDotDialog(QWidget *parent)
: QDialog(parent),
ui(new Ui::ExportToDotDialog)
{
ui->setupUi(this);
ui->pathLineEdit->setText(getenv("GST_DEBUG_DUMP_DOT_DIR"));
}
ExportToDotDialog::~ExportToDotDialog()
{
delete ui;
}
int ExportToDotDialog::get_graph_details() const
{
return (ui->statesCheckBox->isChecked() << 0) |
(ui->statesCheckBox->isChecked() << 1) |
(ui->statesCheckBox->isChecked() << 2) |
(ui->statesCheckBox->isChecked() << 3);
}
std::string ExportToDotDialog::get_filename() const
{
return ui->filenameLineEdit->text().toStdString();
}
bool ExportToDotDialog::is_master_model() const
{
return ui->mainBinRadioButton->isChecked();
}
| 20.73913 | 61 | 0.715933 | loganek |
1a98d628ebe2402e2871ca4d09c060ce8f3c353c | 726 | cpp | C++ | homomorphic_evaluation/src/main.cpp | dklee0501/PLDI_20_242_artifact_publication | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | 1 | 2022-02-14T02:37:58.000Z | 2022-02-14T02:37:58.000Z | homomorphic_evaluation/src/main.cpp | dklee0501/Lobster | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | null | null | null | homomorphic_evaluation/src/main.cpp | dklee0501/Lobster | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | null | null | null | #include "FHE.h"
#include <timing.h>
#include <EncryptedArray.h>
#include <NTL/lzz_pXFactoring.h>
#include <vector>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
#include <vector>
#include "NTL/ZZ_p.h"
#include <NTL/ZZ_pX.h>
#include <NTL/vec_ZZ_p.h>
#include <assert.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
long m=0, p=127, r=1; // Native plaintext space
// Computations will be 'modulo p'
long L; // Levels
long c=2; // Columns in key switching matrix
long w=64; // Hamming weight of secret key
long d=1;
long security;
long s;
long bnd;
ZZX G;
return 0;
}
| 20.742857 | 58 | 0.633609 | dklee0501 |
1aa1ca3764f44acc65714469fd96138ceacc60c5 | 1,534 | cpp | C++ | MPAGSCipher/CaesarCipher.cpp | MPAGS-CPP-2019/mpags-day-3-rrStein | e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.cpp | MPAGS-CPP-2019/mpags-day-3-rrStein | e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.cpp | MPAGS-CPP-2019/mpags-day-3-rrStein | e4ff5e2023dbb8e4a7981b25c7d11811ead13c0c | [
"MIT"
] | null | null | null | #include "CaesarCipher.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// #include "RunCaesarCipher.hpp"
// #include "RunCaesarCipher.cpp"
CaesarCipher::CaesarCipher(const std::string &caesar_key)
: caesar_key_{std::stoul(caesar_key)} {}
CaesarCipher::CaesarCipher(const size_t &caesar_key)
: caesar_key_{caesar_key} {}
std::string CaesarCipher::applyCipher(const std::string &inputText,
const bool encrypt) const
// : inputText_{inputText}, encrypt_{encrypt}
{
const size_t truncatedKey{caesar_key_ % alphabetSize_};
std::string outputText{""};
// Loop over the input text
char processedChar{'x'};
for (const auto &origChar : inputText) {
// For each character in the input text, find the corresponding position in
// the alphabet by using an indexed loop over the alphabet container
for (size_t i{0}; i < alphabetSize_; ++i) {
if (origChar == alphabet_[i]) {
// Apply the appropriate shift (depending on whether we're encrypting
// or decrypting) and determine the new character
// Can then break out of the loop over the alphabet
if (encrypt) {
processedChar = alphabet_[(i + truncatedKey) % alphabetSize_];
} else {
processedChar =
alphabet_[(i + alphabetSize_ - truncatedKey) % alphabetSize_];
}
break;
}
}
// Add the new character to the output text
outputText += processedChar;
}
return outputText;
} | 30.68 | 79 | 0.656454 | MPAGS-CPP-2019 |
1aaa3c3ebc0ac201b16987d8482409b46de800bb | 2,512 | hpp | C++ | include/graphplan/Action.hpp | aldukeman/graphplan | 33b575a75aa25243e0a3bc658a7932e75a1ef2ef | [
"MIT"
] | null | null | null | include/graphplan/Action.hpp | aldukeman/graphplan | 33b575a75aa25243e0a3bc658a7932e75a1ef2ef | [
"MIT"
] | 1 | 2016-01-13T20:42:26.000Z | 2022-03-10T02:14:49.000Z | include/graphplan/Action.hpp | aldukeman/graphplan | 33b575a75aa25243e0a3bc658a7932e75a1ef2ef | [
"MIT"
] | 1 | 2019-08-24T10:25:44.000Z | 2019-08-24T10:25:44.000Z | /**
* The MIT License (MIT)
*
* Copyright (c) 2014 Anton Dukeman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @file Action.hpp
* @author Anton Dukeman <[email protected]>
*
* An Action in Graphplan
*/
#ifndef _GRAPHPLAN_ACTION_H_
#define _GRAPHPLAN_ACTION_H_
#include <string>
#include <set>
#include "graphplan/Proposition.hpp"
namespace graphplan
{
class Action
{
public:
/// Constructor
Action(const std::string& n = "");
/// equality operator
bool operator==(const Action& a) const;
/// less than operator
bool operator<(const Action& a) const;
/// add delete
void add_effect(const Proposition& p);
/// add precondition
void add_precondition(const Proposition& p);
/// get proposition name
const std::string& get_name() const;
/// get adds
const std::set<Proposition>& get_effects() const;
/// get preconditions
const std::set<Proposition>& get_preconditions() const;
/// check if this is a maintenance action
bool is_maintenance_action() const;
/// get string version
std::string to_string() const;
/// set action name
void set_name(const std::string& n);
protected:
/// name of the proposition
std::string name_;
/// added propositions
std::set<Proposition> effects_;
/// required propositions
std::set<Proposition> preconditions_;
}; // class Action
} // namespace graphplan
#endif // _GRAPHPLAN_ACTION_H_
| 27.604396 | 80 | 0.705414 | aldukeman |
1aad3a3ec328941ebf17269947721d86450d3671 | 1,836 | cpp | C++ | test/stc/test-vcs.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 9 | 2016-01-10T20:59:02.000Z | 2019-01-09T14:18:13.000Z | test/stc/test-vcs.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 31 | 2015-01-30T17:46:17.000Z | 2017-03-04T17:33:50.000Z | test/stc/test-vcs.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 2 | 2015-04-05T08:45:22.000Z | 2018-08-24T06:43:24.000Z | ////////////////////////////////////////////////////////////////////////////////
// Name: test-vcs.cpp
// Purpose: Implementation for wex unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2021 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wex/core/config.h>
#include <wex/stc/vcs.h>
#include <wex/ui/menu.h>
#include "../test.h"
#include <vector>
TEST_SUITE_BEGIN("wex::vcs");
TEST_CASE("wex::vcs")
{
wex::path file(wex::test::get_path("test.h"));
file.make_absolute();
SUBCASE("statics")
{
REQUIRE(wex::vcs::load_document());
REQUIRE(wex::vcs::dir_exists(file));
REQUIRE(!wex::vcs::empty());
REQUIRE(wex::vcs::size() > 0);
}
SUBCASE("others")
{
// In wex::app the vcs is loaded, so current vcs is known,
// using this constructor results in command id 3, being add.
wex::vcs vcs(std::vector<wex::path>{file}, 3);
REQUIRE(vcs.config_dialog(wex::data::window().button(wxAPPLY | wxCANCEL)));
#ifndef __WXMSW__
REQUIRE(vcs.execute());
REQUIRE(vcs.execute("status"));
REQUIRE(!vcs.execute("xxx"));
REQUIRE(vcs.show_dialog(wex::data::window().button(wxAPPLY | wxCANCEL)));
REQUIRE(vcs.request(wex::data::window().button(wxAPPLY | wxCANCEL)));
REQUIRE(vcs.entry().build_menu(100, new wex::menu("test", 0)) > 0);
REQUIRE(vcs.entry().get_command().get_command() == "add");
REQUIRE(!vcs.get_branch().empty());
REQUIRE(vcs.toplevel().string().find("wex") != std::string::npos);
REQUIRE(vcs.name() == "Auto");
REQUIRE(!vcs.entry().get_command().is_open());
wex::config(_("vcs.Base folder"))
.set(std::list<std::string>{wxGetCwd().ToStdString()});
REQUIRE(vcs.set_entry_from_base());
REQUIRE(vcs.use());
#endif
}
}
TEST_SUITE_END();
| 27 | 80 | 0.582244 | antonvw |
1ab07d703b2db70916abe6b16f78f7bd63606c4b | 2,219 | cpp | C++ | contract/lite-client/tddb/td/db/utils/FileSyncState.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | 5 | 2019-10-15T18:26:06.000Z | 2020-05-09T14:09:49.000Z | contract/lite-client/tddb/td/db/utils/FileSyncState.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | null | null | null | contract/lite-client/tddb/td/db/utils/FileSyncState.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | 2 | 2020-07-24T16:09:02.000Z | 2021-08-18T17:08:28.000Z | /*
This file is part of TON Blockchain Library.
TON Blockchain 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.
TON Blockchain 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 TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2017-2019 Telegram Systems LLP
*/
#include "FileSyncState.h"
namespace td {
std::pair<FileSyncState::Reader, FileSyncState::Writer> FileSyncState::create() {
auto self = std::make_shared<Self>();
return {Reader(self), Writer(self)};
}
FileSyncState::Reader::Reader(std::shared_ptr<Self> self) : self(std::move(self)) {
}
bool FileSyncState::Reader::set_requested_sync_size(size_t size) const {
if (self->requested_synced_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->requested_synced_size.store(size, std::memory_order_release);
return true;
}
size_t FileSyncState::Reader::synced_size() const {
return self->synced_size;
}
size_t FileSyncState::Reader::flushed_size() const {
return self->flushed_size;
}
FileSyncState::Writer::Writer(std::shared_ptr<Self> self) : self(std::move(self)) {
}
size_t FileSyncState::Writer::get_requested_synced_size() {
return self->requested_synced_size.load(std::memory_order_acquire);
}
bool FileSyncState::Writer::set_synced_size(size_t size) {
if (self->synced_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->synced_size.store(size, std::memory_order_release);
return true;
}
bool FileSyncState::Writer::set_flushed_size(size_t size) {
if (self->flushed_size.load(std::memory_order_relaxed) == size) {
return false;
}
self->flushed_size.store(size, std::memory_order_release);
return true;
}
} // namespace td
| 32.632353 | 83 | 0.741325 | TONCommunity |
1ab2a2b907d33254514ee46febe49a69ed08a539 | 3,229 | cpp | C++ | Source/Core/BuildCommon/BakeModel.cpp | schuttejoe/ShootyEngine | 56a7fab5a479ec93d7f641bb64b8170f3b0d3095 | [
"MIT"
] | 81 | 2018-07-31T17:13:47.000Z | 2022-03-03T09:24:22.000Z | Source/Core/BuildCommon/BakeModel.cpp | schuttejoe/ShootyEngine | 56a7fab5a479ec93d7f641bb64b8170f3b0d3095 | [
"MIT"
] | 2 | 2018-10-15T04:39:43.000Z | 2019-12-05T03:46:50.000Z | Source/Core/BuildCommon/BakeModel.cpp | schuttejoe/ShootyEngine | 56a7fab5a479ec93d7f641bb64b8170f3b0d3095 | [
"MIT"
] | 9 | 2018-10-11T06:32:12.000Z | 2020-10-01T03:46:37.000Z | //=================================================================================================================================
// Joe Schutte
//=================================================================================================================================
#include "BuildCommon/BakeModel.h"
#include "BuildCore/BuildContext.h"
#include "SceneLib/ModelResource.h"
namespace Selas
{
//=============================================================================================================================
Error BakeModel(BuildProcessorContext* context, cpointer name, const BuiltModel& model)
{
ModelResourceData data;
data.aaBox = model.aaBox;
data.totalVertexCount = (uint32)model.positions.Count();
data.totalCurveVertexCount = (uint32)model.curveVertices.Count();
data.curveModelName = model.curveModelNameHash;
data.pad = 0;
data.indexSize = model.indices.DataSize();
data.faceIndexSize = model.faceIndexCounts.DataSize();
data.positionSize = model.positions.DataSize();
data.normalsSize = model.normals.DataSize();
data.tangentsSize = model.tangents.DataSize();
data.uvsSize = model.uvs.DataSize();
data.curveIndexSize = model.curveIndices.DataSize();
data.curveVertexSize = model.curveVertices.DataSize();
data.cameras.Append(model.cameras);
data.textureResourceNames.Append(model.textures);
data.materials.Append(model.materials);
data.materialHashes.Append(model.materialHashes);
data.meshes.Append(model.meshes);
data.curves.Append(model.curves);
context->CreateOutput(ModelResource::kDataType, ModelResource::kDataVersion, name, data);
ModelGeometryData geometry;
geometry.indexSize = model.indices.DataSize();
geometry.faceIndexSize = model.faceIndexCounts.DataSize();
geometry.positionSize = model.positions.DataSize();
geometry.normalsSize = model.normals.DataSize();
geometry.tangentsSize = model.tangents.DataSize();
geometry.uvsSize = model.uvs.DataSize();
geometry.curveIndexSize = model.curveIndices.DataSize();
geometry.curveVertexSize = model.curveVertices.DataSize();
geometry.indices = (uint32*)model.indices.DataPointer();
geometry.faceIndexCounts = (uint32*)model.faceIndexCounts.DataPointer();
geometry.positions = (float3*)model.positions.DataPointer();
geometry.normals = (float3*)model.normals.DataPointer();
geometry.tangents = (float4*)model.tangents.DataPointer();
geometry.uvs = (float2*)model.uvs.DataPointer();
geometry.curveIndices = (uint32*)model.curveIndices.DataPointer();
geometry.curveVertices = (float4*)model.curveVertices.DataPointer();
context->CreateOutput(ModelResource::kGeometryDataType, ModelResource::kDataVersion, name, geometry);
return Success_;
}
} | 52.934426 | 131 | 0.557138 | schuttejoe |
1ab3c6a1df288059f40f05ae58d6ee12e894cd73 | 1,037 | cpp | C++ | tests/fixture/test_assert.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | tests/fixture/test_assert.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | tests/fixture/test_assert.cpp | sugawaray/filemanager | 3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1 | [
"MIT"
] | null | null | null | #include <sstream>
#include "assert.h"
#include "test_assert.h"
using std::cerr;
using std::endl;
using std::ostringstream;
using test::fixture::Assert;
START_TEST(should_not_output_when_true)
{
ostringstream os;
Assert(true, 1, 2, os);
if (os.str() != "")
cerr << "should_not_output_when_true" << endl;
}
END_TEST
START_TEST(should_output_when_false_with_2_params)
{
ostringstream os;
Assert(false, 1, 2, os);
ostringstream expected;
expected << 1 << ":" << 2 << endl;
if (os.str() != expected.str()) {
cerr << os.str();
cerr << "should_output_when_false_with_2_params" << endl;
}
}
END_TEST
namespace test {
namespace fixture {
TCase* create_assert_tcase()
{
TCase* tcase(tcase_create("assert"));
tcase_add_test(tcase, should_not_output_when_true);
tcase_add_test(tcase, should_output_when_false_with_2_params);
return tcase;
}
Suite* create_assert_fixture_suite()
{
Suite* suite(suite_create("test::fixture::Assert"));
suite_add_tcase(suite, create_assert_tcase());
return suite;
}
} // fixture
} // test
| 19.942308 | 63 | 0.724204 | sugawaray |
1ab88a18dd8f74b863bbd45e262d092e29d0acfa | 432 | cpp | C++ | WindowsServiceCppTemplate/ServiceControlManager.cpp | AinoMegumi/WindowsServiceCppTemplate | fd123fe43c13356308b3d27a7a5692078979426d | [
"MIT"
] | 1 | 2021-07-06T14:31:15.000Z | 2021-07-06T14:31:15.000Z | WindowsServiceCppTemplate/ServiceControlManager.cpp | AinoMegumi/WindowsServiceCppTemplate | fd123fe43c13356308b3d27a7a5692078979426d | [
"MIT"
] | null | null | null | WindowsServiceCppTemplate/ServiceControlManager.cpp | AinoMegumi/WindowsServiceCppTemplate | fd123fe43c13356308b3d27a7a5692078979426d | [
"MIT"
] | null | null | null | #include "ServiceControlManager.h"
#include "GetErrorMessage.h"
#include <stdexcept>
ServiceControlManager::ServiceControlManager()
: SCM(OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) {
if (this->SCM == nullptr) {
throw std::runtime_error(
"Failed In OpenSCManager Function\n"
+ GetErrorMessageA()
);
}
}
ServiceControlManager::operator const SC_HANDLE& () const noexcept { return this->SCM; }
| 25.411765 | 89 | 0.710648 | AinoMegumi |
1ab92d52afb6aff23e6b6df1dcee0273b674a834 | 4,415 | cpp | C++ | src/args/Arg.cpp | GAStudyGroup/VRP | 54ec7ff3f0a4247d3effe609cf916fc235a08664 | [
"MIT"
] | 8 | 2018-11-28T15:13:26.000Z | 2021-10-08T18:34:28.000Z | sources/Arg.cpp | Arch23/Cpp-Argument-Parser | 03787751e725db8820b02b702e65b31537dc73d2 | [
"MIT"
] | 4 | 2018-03-28T19:26:27.000Z | 2018-04-07T03:02:15.000Z | sources/Arg.cpp | Arch23/Cpp-Argument-Parser | 03787751e725db8820b02b702e65b31537dc73d2 | [
"MIT"
] | 2 | 2019-12-12T09:36:48.000Z | 2020-04-23T08:26:22.000Z | #include "Arg.hpp"
#include <sstream>
using std::istringstream;
#include <set>
using std::set;
#include <algorithm>
using std::any_of;
#include <iostream>
using std::cout;
using std::endl;
Arg::Arg(int argc, char **argv):argc(argc),argv(argv){
programName = "Default Name";
helpSetted = false;
}
void Arg::newArgument(string arg, bool required, string description){
vector<string> argV{split(arg,'|')};
arguments.push_back(Argument(argV, required, description));
}
void Arg::validateArguments(){
//programmer error, name or alias repeated
nameConflict();
processInput();
if(helpSetted && isSet("help")){
throw std::runtime_error(help());
}else{
processRequired();
}
}
void Arg::processRequired(){
bool error{false};
string errorMsg{""};
for(Argument a : arguments){
if(a.getRequired() && a.getOption().empty()){
if(error){
errorMsg += "\n";
}
error = true;
errorMsg += "Required argument: "+a.getArg()[0];
}
}
throwException(errorMsg);
}
void Arg::processInput(){
vector<string> argVector;
bool error{false};
string errorMsg{""};
for(int i=1;i<argc;i++){
string arg = argv[i];
if(arg[0] == '-'){
arg.erase(0,1);
argVector.push_back(arg);
}else{
argVector.back() += " ";
argVector.back() += arg;
}
}
for(string arg : argVector){
vector<string> argSplited = split(arg);
Argument *a = getArgument(argSplited[0]);
if(a==nullptr){
if(error){
errorMsg += "\n";
}
error = true;
errorMsg += "Unexpected argument: "+argSplited[0];
}else{
string option{""};
for(unsigned i=1;i<argSplited.size();i++){
option += argSplited[i];
if((++i)<argSplited.size()){
option += " ";
}
}
a->setOption(option);
a->setArg(true);
}
}
throwException(errorMsg);
}
void Arg::throwException(string errorMsg){
if(!errorMsg.empty()){
if(helpSetted){
errorMsg += "\nUse -help or -h to display program options.";
}
throw std::runtime_error(errorMsg);
}
}
string Arg::help(){
string tmp{};
tmp += programName+"\n\n";
tmp += "Options:\n";
for(Argument a : arguments){
tmp += a.to_string();
tmp += "\n\n";
}
return(tmp);
}
Arg::Argument* Arg::getArgument(string arg){
vector<string> argV = split(arg,'|');
for(string s : argV){
for(Argument &a : arguments){
for(string name : a.getArg()){
if(name == s){
return(&a);
}
}
}
}
return(nullptr);
}
bool Arg::isSet(string arg){
Argument *a = getArgument(arg);
if(a!=nullptr){
return(a->isSet());
}
return false;
}
string Arg::getOption(string arg){
Argument *a = getArgument(arg);
if(a!=nullptr){
return(a->getOption());
}
return {};
}
void Arg::nameConflict(){
set<string> conflicting;
for(unsigned i=0;i<arguments.size();i++){
for(string n : arguments[i].getArg()){
for(unsigned j=0;j<arguments.size();j++){
if(i!=j){
vector<string> tmp{arguments[j].getArg()};
if(find(tmp.begin(),tmp.end(),n)!=tmp.end()){
conflicting.insert(n);
}
}
}
}
}
bool error{false};
string errorMsg{};
for(string n : conflicting){
if(error){
errorMsg+="\n";
}
error = true;
errorMsg += "Conflicting name or alias: "+n;
}
throwException(errorMsg);
}
void Arg::setProgramName(string name){
this->programName = name;
}
void Arg::setHelp(){
helpSetted = true;
newArgument("help|h",false,"Display options available.");
}
vector<string> Arg::split(const string s, char c) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, c)) {
if (!token.empty()) {
tokens.push_back(token);
}
}
return tokens;
}
| 22.757732 | 72 | 0.512797 | GAStudyGroup |
1aba131b0dfdbc8f2f780904bd7fd8947f4e4925 | 5,240 | cpp | C++ | StatsAPI/statsapi.cpp | freem/SMOnline-v1 | b7202ebf1b2d291952000d8c1673ea6175eb4bdd | [
"MIT"
] | 1 | 2021-05-24T09:23:49.000Z | 2021-05-24T09:23:49.000Z | StatsAPI/statsapi.cpp | freem/SMOnline-v1 | b7202ebf1b2d291952000d8c1673ea6175eb4bdd | [
"MIT"
] | null | null | null | StatsAPI/statsapi.cpp | freem/SMOnline-v1 | b7202ebf1b2d291952000d8c1673ea6175eb4bdd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "statsapi.h"
using namespace std;
void main(int argc, char* argv[])
{
statsAPI* api = NULL;
vector<CString> args;
if ((argc < 2) || (argc > 21))
return;
args.resize(argc - 1);
for(unsigned int i = 1; i < argc; i++)
args[i - 1] = argv[i];
api = new statsAPI;
api->ProcessCommandsV(args);
if (api)
{
delete api;
api = NULL;
}
}
statsAPI::statsAPI()
{
m_lktype = NONE;
m_database = NULL;
m_startInfo.Database = "stepmani_newstats"; //Not implemented
m_startInfo.Password = "1000Hilltop";
m_startInfo.Port = 3306;
m_startInfo.ServerName = "stepmaniaonline.com";
m_startInfo.UserName = "stepmani_stats";
}
statsAPI::~statsAPI()
{
//Make the API signal the end of the data when destructing.
cout << "END:END";
if (m_database)
delete m_database;
}
void statsAPI::ProcessCommandsV(vector<CString>& commands)
{
CString flag, value;
unsigned int pos = 0;
for (unsigned int i = 0; i < commands.size(); i++)
{
pos = commands[i].Find("=");
if (pos == CString::npos)
{
PrintError("Command \"" + commands[i] + "\" invalid. Ignoring.");
return;
}
flag = commands[i].substr(0,pos);
value = commands[i].substr(pos+1);
if (flag == "id")
{
m_id = value;
m_lktype = ID;
}
else if (flag == "name")
{
m_name = value;
m_lktype = NAME;
}
else if(flag == "op")
{
if (OpenSQLConnection())
ParseOperation(value);
else
PrintError(CString("SQL connection failed"));
}
else
{
PrintError("Unknown command \"" + commands[i] +"\".");
}
}
}
void statsAPI::PrintError(CString& error)
{
cout << "ERROR:" << error << endl;
}
bool statsAPI::ParseOperation(CString& op)
{
if (op == "lr")
{
switch (m_lktype)
{
case NONE:
break;
case NAME:
m_id = QueryID(m_name);
if (m_id != "Unknown" )
m_lktype = ID;
else
{
PrintError("Unknown name " + m_name);
return false;
}
case ID:
PrintQuery(QueryLastRound(m_id), "lr");
break;
}
return true;
}
else if (op == "total")
{
return true;
}
else
PrintError("Unknown operation \"" + op + "\". Ignoring.");
return false;
}
bool statsAPI::OpenSQLConnection()
{
try {
m_database = new ezMySQLConnection(m_startInfo);
m_database->Connect();
}
catch (const ezSQLException &e) {
PrintError(CString("SQL ERROR THROWN! Dec:" + e.Description));
return false;
}
return m_database->m_bLoggedIn;
}
CString statsAPI::QueryID(const CString& name)
{
m_query.m_InitialQuery = "select user_id from `stepmani_stats`.`phpbb_users` where username=\"" + name + "\" limit 0,1";
m_database->BlockingQuery( m_query );
if (m_result.isError)
throw;
m_result = m_query.m_ResultInfo;
if (m_result.FieldContents.size() <= 0)
return "Unknown";
return m_result.FieldContents[0][0].ToString();
}
void statsAPI::PrintQuery( ezSQLQuery &tQuery, string prefix )
{
//In the event we have an error, show it
if ( tQuery.m_ResultInfo.errorNum != 0 )
{
PrintError(CString(tQuery.m_ResultInfo.errorDesc));
exit ( 0 );
}
if ( tQuery.m_ResultInfo.FieldContents.size() == 0 )
{
PrintError(CString("No data for this user."));
exit (0);
}
//Record seed for finding rank.
//show table header
unsigned i = 0;
for ( i = 0; i < tQuery.m_ResultInfo.Header.size(); i++ )
{
cout << prefix<<tQuery.m_ResultInfo.Header[i].Field<<":";
if ( tQuery.m_ResultInfo.FieldContents.size() > 0 )
if ( tQuery.m_ResultInfo.FieldContents[0].size() > i )
{
cout<< tQuery.m_ResultInfo.FieldContents[0][i].ToString()<<endl;
// if ( tQuery.m_ResultInfo.Header[i].Field == "seed" )
// seed = tQuery.m_ResultInfo.FieldContents[0][i].ToString();
}
}
}
ezSQLQuery statsAPI::QueryLastRound(const CString& ID)
{
m_query.m_InitialQuery = "select * from player_stats where pid=" + ID + " order by round_ID desc limit 0,1";
m_database->BlockingQuery( m_query );
return m_query;
}
/*
* (c) 2003-2004 Joshua Allen, Charles Lohr
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 24.036697 | 121 | 0.676718 | freem |
1abdfc77cd9a9c7b46e8dc87f3257e84faa19fcb | 2,921 | cpp | C++ | qubus/src/isl/flow.cpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/src/isl/flow.cpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/src/isl/flow.cpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | #include <qubus/isl/flow.hpp>
namespace qubus
{
namespace isl
{
union_access_info::union_access_info(isl_union_access_info* handle_) : handle_(handle_)
{
}
union_access_info::union_access_info(const union_access_info& other)
: handle_(isl_union_access_info_copy(other.native_handle()))
{
}
union_access_info::~union_access_info()
{
isl_union_access_info_free(handle_);
}
union_access_info& union_access_info::operator=(union_access_info other)
{
isl_union_access_info_free(handle_);
handle_ = other.release();
return *this;
}
void union_access_info::set_must_source(isl::union_map source)
{
handle_ = isl_union_access_info_set_must_source(handle_, source.release());
}
void union_access_info::set_may_source(isl::union_map source)
{
handle_ = isl_union_access_info_set_may_source(handle_, source.release());
}
void union_access_info::set_schedule(isl::schedule sched)
{
handle_ = isl_union_access_info_set_schedule(handle_, sched.release());
}
isl_union_access_info* union_access_info::native_handle() const
{
return handle_;
}
isl_union_access_info* union_access_info::release() noexcept
{
isl_union_access_info* temp = handle_;
handle_ = nullptr;
return temp;
}
union_access_info union_access_info::from_sink(union_map sink)
{
return union_access_info(isl_union_access_info_from_sink(sink.release()));
}
union_flow::union_flow(isl_union_flow* handle_) : handle_(handle_)
{
}
union_flow::~union_flow()
{
isl_union_flow_free(handle_);
}
union_map union_flow::get_must_dependence() const
{
return union_map(isl_union_flow_get_must_dependence(handle_));
}
union_map union_flow::get_may_dependence() const
{
return union_map(isl_union_flow_get_may_dependence(handle_));
}
isl_union_flow* union_flow::native_handle() const
{
return handle_;
}
isl_union_flow* union_flow::release() noexcept
{
isl_union_flow* temp = handle_;
handle_ = nullptr;
return temp;
}
union_flow compute_flow(union_access_info access_info)
{
return union_flow(isl_union_access_info_compute_flow(access_info.release()));
}
int compute_flow(union_map sink, union_map must_source, union_map may_source, union_map schedule,
union_map& must_dep, union_map& may_dep, union_map& must_no_source,
union_map& may_no_source)
{
isl_union_map* must_dep_;
isl_union_map* may_dep_;
isl_union_map* must_no_source_;
isl_union_map* may_no_source_;
int result = isl_union_map_compute_flow(sink.release(), must_source.release(),
may_source.release(), schedule.release(), &must_dep_,
&may_dep_, &must_no_source_, &may_no_source_);
must_dep = union_map(must_dep_);
may_dep = union_map(may_dep_);
must_no_source = union_map(must_no_source_);
may_no_source = union_map(may_no_source_);
return result;
}
}
} | 23.556452 | 97 | 0.741869 | qubusproject |
1ac16c952417ad528f3a24ca9c19effbbebb83a6 | 3,876 | cpp | C++ | GUIproject/CourseWorkHypermarket/productlist.cpp | ashnaider/CourseWorkHypermarket | 9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a | [
"MIT"
] | 3 | 2020-05-27T18:37:43.000Z | 2020-06-21T05:40:57.000Z | GUIproject/CourseWorkHypermarket/productlist.cpp | ashnaider/CourseWorkHypermarket | 9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a | [
"MIT"
] | null | null | null | GUIproject/CourseWorkHypermarket/productlist.cpp | ashnaider/CourseWorkHypermarket | 9dd52dadf987020c2490f2a9a9cdcaa5b52fb12a | [
"MIT"
] | null | null | null | #include "productlist.h"
#include "product.h"
#include <sstream>
#include <string>
#include <vector>
ProductList::ProductList(QString productClass)
{
utilities = new Utilities;
QString filePath = utilities->generateFilePathForProduct(productClass);
productsInfo = utilities->readFileByWord(filePath, true);
productInfoHeader = productsInfo[0];
productsInfo.erase(productsInfo.begin());
allocateProducts(productClass);
}
void ProductList::allocateProducts(QString productClass) {
currectProductClass = productClass.toStdString();
for (const auto& line : productsInfo) {
std::string firm = line[0];
std::string name = line[1];
double price = std::stod(line[2]);
double maxDiscount = std::stod(line[3]);
if (productClass == "MobilePhones") {
bool isContract = (line[4] == "1") ? true : false;
int maxSimCards = std::stoi(line[5]);
fieldsQuantity = 6;
MobilePhone *mobilePhone;
mobilePhone = new MobilePhone(firm, name, price, maxDiscount,
isContract, maxSimCards);
ptrVecProductList.push_back(mobilePhone);
} else if (productClass == "Smartphones") {
bool isContract = (line[4] == "1") ? true : false;
int maxSimCards = std::stoi(line[5]);
std::string OS = line[6];
std::string preinstalledProgramms = line[7];
fieldsQuantity = 8;
std::stringstream sspp(preinstalledProgramms);
std::vector<std::string> pp;
std::string temp;
while (sspp >> temp) {
pp.push_back(temp);
}
Smartphone *smartphone;
smartphone = new Smartphone(firm, name, price, maxDiscount,
isContract, maxSimCards,
OS, pp);
ptrVecProductList.push_back(smartphone);
} else if (productClass == "Laptops") {
double diagonalSize = std::stod(line[4]);
double weight = std::stod(line[5]);
int cpuCores = std::stoi(line[6]);
int mainMemory = std::stoi(line[7]);
fieldsQuantity = 8;
Laptop *laptop;
laptop = new Laptop(firm, name, price, maxDiscount,
diagonalSize, weight, cpuCores, mainMemory);
ptrVecProductList.push_back(laptop);
}
}
}
const Product* ProductList::getProductByIndex(int index) {
if (index >= 0 && index < ptrVecProductList.size()) {
return ptrVecProductList[index];
} else {
return { };
}
}
int ProductList::GetFieldsQuantity() const {
return fieldsQuantity;
}
QString ProductList::GetQStringProductInfo(const Product *product) const {
QString result = QString::fromStdString(product->GetFirm()) +
"\t" +
QString::fromStdString(product->GetName()) +
"\t" +
QString::number(product->GetPrice()) +
"\t";
return result;
}
std::vector<std::string> ProductList::GetProductInfoInVec(int pNum) const {
return productsInfo[pNum];
}
QList<QString> ProductList::GetProductInfoHeader() const {
QList<QString> result;
for (const auto& word : productInfoHeader) {
result.push_back(QString::fromStdString(word));
}
return result;
}
ProductList::~ProductList() {
delete utilities;
for (auto& product : ptrVecProductList) {
delete product;
}
productsInfo.clear();
}
| 32.033058 | 81 | 0.54257 | ashnaider |
1ac39ca5b2ddb057e71738c30bbe6b4536a54da3 | 378 | hpp | C++ | simsync/include/simsync/synchronization/thread_start.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | simsync/include/simsync/synchronization/thread_start.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | simsync/include/simsync/synchronization/thread_start.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | #ifndef SIMSYNC_THREAD_START_HPP
#define SIMSYNC_THREAD_START_HPP
#include <simsync/synchronization/event.hpp>
namespace simsync {
class thread_start : public event {
public:
explicit thread_start(int32_t thread_id, thread_model &tm);
transition synchronize() override;
private:
void print(std::ostream &stream) const override;
};
}
#endif //SIMSYNC_THREAD_START_HPP
| 19.894737 | 61 | 0.793651 | mariobadr |
1ac5f29f8be19da29a2f75af508c1f322ef4907d | 296 | cpp | C++ | src/misc/memswap.cpp | Damdoshi/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 38 | 2016-07-30T09:35:19.000Z | 2022-03-04T10:13:48.000Z | src/misc/memswap.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 15 | 2017-02-12T19:20:52.000Z | 2021-06-09T09:30:52.000Z | src/misc/memswap.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 12 | 2016-10-06T09:06:59.000Z | 2022-03-04T10:14:00.000Z | // Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Lapin library
#include "lapin_private.h"
void bunny_memswap(void *a,
void *b,
size_t s)
{
void *c = bunny_alloca(s);
memcpy(c, a, s);
memcpy(a, b, s);
memcpy(b, c, s);
bunny_freea(c);
}
| 15.578947 | 32 | 0.577703 | Damdoshi |
1ad0e382a2b2a74cf034d6474b5ff0b8f8b86f5a | 1,669 | hpp | C++ | src/neuron/SwcNode.hpp | yzx9/NeuronSdfViewer | 454164dfccf80b806aac3cd7cca09e2cb8bd3c2a | [
"MIT"
] | 1 | 2021-12-31T10:29:56.000Z | 2021-12-31T10:29:56.000Z | src/neuron/SwcNode.hpp | yzx9/NeuronSdfViewer | 454164dfccf80b806aac3cd7cca09e2cb8bd3c2a | [
"MIT"
] | null | null | null | src/neuron/SwcNode.hpp | yzx9/NeuronSdfViewer | 454164dfccf80b806aac3cd7cca09e2cb8bd3c2a | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <regex>
#include <memory>
class SwcNode
{
public:
int id;
int type;
float x;
float y;
float z;
float raidus;
int parent;
std::unique_ptr<SwcNode> child;
std::unique_ptr<SwcNode> next;
static bool try_parse(const std::string &s, std::unique_ptr<SwcNode> &out)
{
constexpr auto pattern =
"\\s*"
"(\\d+)\\s" // index
"(\\d+)\\s" // type
"(-?\\d*(?:\\.\\d+)?)\\s" // x
"(-?\\d*(?:\\.\\d+)?)\\s" // y
"(-?\\d*(?:\\.\\d+)?)\\s" // z
"(-?\\d*(?:\\.\\d+)?)\\s" // radius
"(-1|\\d+)\\s*"; // parent
const static std::regex regex(pattern);
std::smatch match;
if (!std::regex_match(s, match, regex))
return false;
out = std::make_unique<SwcNode>();
out->id = std::stoi(match[1]);
out->type = std::stoi(match[2]);
out->x = std::stof(match[3]);
out->y = std::stof(match[4]);
out->z = std::stof(match[5]);
out->raidus = std::stof(match[6]);
out->parent = std::stoi(match[7]);
out->child = nullptr;
out->next = nullptr;
return true;
};
void add_brother(std::unique_ptr<SwcNode> brother)
{
if (next)
next->add_brother(std::move(brother));
else
next = std::move(brother);
};
void add_child(std::unique_ptr<SwcNode> new_child)
{
if (child)
child->add_brother(std::move(new_child));
else
child = std::move(new_child);
}
};
| 24.910448 | 78 | 0.461354 | yzx9 |
1adff208083bea1d0805b338aabccdebbc09a1d9 | 315 | inl | C++ | src/readers/F3DExodusIIReader.inl | Meakk/f3d | 40db15ab2a6500ea67bfee5d35714b5c5e2d993c | [
"BSD-3-Clause"
] | 318 | 2021-11-14T02:22:32.000Z | 2022-03-31T02:32:52.000Z | src/readers/F3DExodusIIReader.inl | Meakk/f3d | 40db15ab2a6500ea67bfee5d35714b5c5e2d993c | [
"BSD-3-Clause"
] | 223 | 2021-11-12T20:52:41.000Z | 2022-03-29T21:35:18.000Z | src/readers/F3DExodusIIReader.inl | Meakk/f3d | 40db15ab2a6500ea67bfee5d35714b5c5e2d993c | [
"BSD-3-Clause"
] | 24 | 2021-11-12T22:12:24.000Z | 2022-03-28T12:42:17.000Z | void ApplyCustomReader(vtkAlgorithm* reader, const std::string&) const override
{
vtkExodusIIReader* exReader = vtkExodusIIReader::SafeDownCast(reader);
exReader->UpdateInformation();
exReader->SetAllArrayStatus(vtkExodusIIReader::NODAL, 1);
exReader->SetAllArrayStatus(vtkExodusIIReader::ELEM_BLOCK, 1);
}
| 39.375 | 79 | 0.8 | Meakk |
1ae6ee53a1b5bd07a80998f710a02123d3fe9285 | 5,254 | hpp | C++ | Altis_Life.Altis/config/Config_Process.hpp | TomLorenzi/AltasiaV2-Public | 324e20c4730587de8f7e3eab8acbe9cb02912a1a | [
"MIT"
] | null | null | null | Altis_Life.Altis/config/Config_Process.hpp | TomLorenzi/AltasiaV2-Public | 324e20c4730587de8f7e3eab8acbe9cb02912a1a | [
"MIT"
] | null | null | null | Altis_Life.Altis/config/Config_Process.hpp | TomLorenzi/AltasiaV2-Public | 324e20c4730587de8f7e3eab8acbe9cb02912a1a | [
"MIT"
] | null | null | null | /*
* class:
* MaterialsReq (Needed to process) = Array - Format -> {{"ITEM CLASS",HOWMANY}}
* MaterialsGive (Returned items) = Array - Format -> {{"ITEM CLASS",HOWMANY}}
* Text (Progess Bar Text) = Localised String
* NoLicenseCost (Cost to process w/o license) = Scalar
*
* Example for multiprocess:
*
* class Example {
* MaterialsReq[] = {{"cocaine_processed",1},{"heroin_processed",1}};
* MaterialsGive[] = {{"diamond_cut",1}};
* Text = "STR_Process_Example";
* //ScrollText = "Process Example";
* NoLicenseCost = 4000;
* };
*/
class ProcessAction {
class oil {
MaterialsReq[] = {{"oil_unprocessed",1}};
MaterialsGive[] = {{"oil_processed",1}};
Text = "STR_Process_Oil";
//ScrollText = "Process Oil";
NoLicenseCost = 1200;
};
class diamond {
MaterialsReq[] = {{"diamond_uncut",1}};
MaterialsGive[] = {{"diamond_cut",1}};
Text = "STR_Process_Diamond";
//ScrollText = "Cut Diamonds";
NoLicenseCost = 1350;
};
class heroin {
MaterialsReq[] = {{"heroin_unprocessed",1}};
MaterialsGive[] = {{"heroin_processed",1}};
Text = "STR_Process_Heroin";
//ScrollText = "Process Heroin";
NoLicenseCost = 1750;
};
class copper {
MaterialsReq[] = {{"copper_unrefined",1}};
MaterialsGive[] = {{"copper_refined",1}};
Text = "STR_Process_Copper";
//ScrollText = "Refine Copper";
NoLicenseCost = 750;
};
class iron {
MaterialsReq[] = {{"iron_unrefined",1}};
MaterialsGive[] = {{"iron_refined",1}};
Text = "STR_Process_Iron";
//ScrollText = "Refine Iron";
NoLicenseCost = 1120;
};
class sand {
MaterialsReq[] = {{"sand",1}};
MaterialsGive[] = {{"glass",1}};
Text = "STR_Process_Sand";
//ScrollText = "Melt Sand into Glass";
NoLicenseCost = 650;
};
class salt {
MaterialsReq[] = {{"salt_unrefined",1}};
MaterialsGive[] = {{"salt_refined",1}};
Text = "STR_Process_Salt";
//ScrollText = "Refine Salt";
NoLicenseCost = 450;
};
class cocaine {
MaterialsReq[] = {{"cocaine_unprocessed",1}};
MaterialsGive[] = {{"cocaine_processed",1}};
Text = "STR_Process_Cocaine";
//ScrollText = "Process Cocaine";
NoLicenseCost = 1500;
};
class marijuana {
MaterialsReq[] = {{"cannabis",1}};
MaterialsGive[] = {{"marijuana",1}};
Text = "STR_Process_Marijuana";
//ScrollText = "Harvest Marijuana";
NoLicenseCost = 500;
};
class nos {
MaterialsReq[] = {{"marijuana",1}};
MaterialsGive[] = {{"joint",1}};
Text = "STR_Process_Joint";
NoLicenseCost = 500;
};
class cement {
MaterialsReq[] = {{"rock",1}};
MaterialsGive[] = {{"cement",1}};
Text = "STR_Process_Cement";
//ScrollText = "Mix Cement";
NoLicenseCost = 350;
};
class wood {
MaterialsReq[] = {{"wood",1}};
MaterialsGive[] = {{"paper",1}};
Text = "STR_Process_Wood";
NoLicenseCost = 350;
};
class paper {
MaterialsReq[] = {{"paper",1}};
MaterialsGive[] = {{"fakeMoney",1}};
Text = "STR_Process_FakeMoney";
NoLicenseCost = 350;
};
class cigarette {
MaterialsReq[] = {{"tabac",1}};
MaterialsGive[] = {{"cigarette",1}};
Text = "STR_Process_Cigarette";
NoLicenseCost = 350;
};
class cigar {
MaterialsReq[] = {{"tabac",1}};
MaterialsGive[] = {{"cigar",1}};
Text = "STR_Process_Cigar";
NoLicenseCost = 350;
};
class uraClean {
MaterialsReq[] = {{"uraWaste",1}};
MaterialsGive[] = {{"uraClean",1}};
Text = "STR_Process_UraClean";
NoLicenseCost = 350;
};
class uraRich {
MaterialsReq[] = {{"uraClean",1}};
MaterialsGive[] = {{"uraRich",1}};
Text = "STR_Process_UraRich";
NoLicenseCost = 350;
};
class uraFinal {
MaterialsReq[] = {{"uraRich",1}};
MaterialsGive[] = {{"uraFinal",1}};
Text = "STR_Process_UraFinal";
NoLicenseCost = 350;
};
class diamondHub {
MaterialsReq[] = {{"diamond_cut",1}};
MaterialsGive[] = {{"bague",1}};
Text = "STR_Process_Bague";
NoLicenseCost = 350;
};
class OxyScrap {
MaterialsReq[] = {{"copper_refined",1}};
MaterialsGive[] = {{"tuyau",1}};
Text = "STR_Process_Tuyau";
NoLicenseCost = 350;
};
class carte_graph {
MaterialsReq[] = {{"carte_graph_endom",1}};
MaterialsGive[] = {{"carte_graph",1}};
Text = "STR_Process_Carte_Graph";
NoLicenseCost = 350;
};
class bitcoin {
MaterialsReq[] = {{"carte_graph",18}};
MaterialsGive[] = {{"bitcoin",1}};
Text = "STR_Process_Bitcoin";
NoLicenseCost = 350;
};
class ordi {
MaterialsReq[] = {{"carte_graph",1}};
MaterialsGive[] = {{"ordi",1}};
Text = "STR_Process_Ordi";
NoLicenseCost = 350;
};
};
| 27.507853 | 85 | 0.533879 | TomLorenzi |
1aeb56dbe4e30c69fbc1793cc1cc979b07f51758 | 3,955 | cpp | C++ | base/pbr/VulkanObjModel.cpp | wessles/vkmerc | cb087f425cdbc0b204298833474cf62874505388 | [
"Unlicense"
] | 6 | 2020-10-09T02:48:54.000Z | 2021-07-30T06:31:20.000Z | base/pbr/VulkanObjModel.cpp | wessles/vkmerc | cb087f425cdbc0b204298833474cf62874505388 | [
"Unlicense"
] | null | null | null | base/pbr/VulkanObjModel.cpp | wessles/vkmerc | cb087f425cdbc0b204298833474cf62874505388 | [
"Unlicense"
] | null | null | null | #include "VulkanObjModel.h"
#include <unordered_map>
#include <filesystem>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtx/string_cast.hpp>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#include "../VulkanMesh.h"
#include "../scene/Scene.h"
#include "PbrMaterial.h"
static std::string GetBaseDir(const std::string& filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return "";
}
namespace vku {
VulkanObjModel::VulkanObjModel(const std::string& filename, Scene* scene, Pass* pass, std::map<std::string, std::string> macros) {
VulkanMeshData meshData{};
std::string base_dir = GetBaseDir(filename);
if (base_dir.empty()) {
base_dir = ".";
}
#ifdef _WIN32
base_dir += "\\";
#else
base_dir += "/";
#endif
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn, err;
if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename.c_str(), base_dir.c_str())) {
throw std::runtime_error(warn + err);
}
if (warn.size() + err.size() > 0) {
std::cout << "OBJ warning: " << (warn + err) << std::endl;
}
// load mesh data
std::unordered_map<Vertex, uint32_t> uniqueVertices{};
for (const auto& shape : shapes) {
for (const auto& index : shape.mesh.indices) {
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]
};
// calculate bounding box
min.x = std::min(min.x, vertex.pos.x);
min.y = std::min(min.y, vertex.pos.y);
min.z = std::min(min.z, vertex.pos.z);
max.x = std::max(max.x, vertex.pos.x);
max.y = std::max(max.y, vertex.pos.y);
max.z = std::max(max.z, vertex.pos.z);
vertex.normal = {
attrib.normals[3 * index.normal_index + 0],
attrib.normals[3 * index.normal_index + 1],
attrib.normals[3 * index.normal_index + 2],
};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
};
vertex.color = { 1.0f, 1.0f, 1.0f };
if (uniqueVertices.count(vertex) == 0) {
uniqueVertices[vertex] = static_cast<uint32_t>(meshData.vertices.size());
meshData.vertices.push_back(vertex);
}
meshData.indices.push_back(uniqueVertices[vertex]);
}
}
aabb = glm::translate(glm::mat4(1.0f), min) * glm::scale(glm::mat4(1.0f), max - min);
this->meshBuf = new VulkanMeshBuffer(scene->device, meshData);
// load material, based on default Blender BSDF .mtl export
if (materials.size() > 0) {
tinyobj::material_t mat = materials[0];
glm::vec4 albedo = glm::vec4(static_cast<float>(mat.diffuse[0]), static_cast<float>(mat.diffuse[1]), static_cast<float>(mat.diffuse[2]), 1.0f);
glm::vec4 emission = glm::vec4(static_cast<float>(mat.emission[0]), static_cast<float>(mat.emission[1]), static_cast<float>(mat.emission[2]), 1.0f);
float metallic = mat.specular[0];
float roughness = 1.0f - (static_cast<float>(mat.shininess) / 1000.0f);
PbrUniform uniform{};
uniform.albedo = albedo;
uniform.emissive = emission;
uniform.metallic = metallic;
uniform.roughness = roughness;
this->mat = new TexturelessPbrMaterial(uniform, scene, pass, macros);
}
}
VulkanObjModel::~VulkanObjModel() {
delete meshBuf;
delete mat;
}
void VulkanObjModel::render(VkCommandBuffer cmdBuf, uint32_t swapIdx, bool noMaterial) {
if (!noMaterial) {
mat->mat->bind(cmdBuf);
mat->matInstance->bind(cmdBuf, swapIdx);
}
vkCmdPushConstants(cmdBuf, mat->mat->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(glm::mat4), &this->localTransform);
meshBuf->draw(cmdBuf);
}
glm::mat4 VulkanObjModel::getAABBTransform()
{
return localTransform * aabb;
}
} | 29.736842 | 159 | 0.668015 | wessles |
8c1d6f83dd2669c716d71f751abe3b49418da6ad | 3,375 | cpp | C++ | vector.cpp | csiro-robotics/Morphogenesis | 4d390609f941a58f09529371d185a344573de35f | [
"BSD-3-Clause"
] | null | null | null | vector.cpp | csiro-robotics/Morphogenesis | 4d390609f941a58f09529371d185a344573de35f | [
"BSD-3-Clause"
] | null | null | null | vector.cpp | csiro-robotics/Morphogenesis | 4d390609f941a58f09529371d185a344573de35f | [
"BSD-3-Clause"
] | null | null | null |
#include "vector.h"
#include "matrix.h"
#define VTYPE float
Vector3DF &Vector3DF::operator*= (const MatrixF &op)
{
double *m = op.GetDataF ();
float xa, ya, za;
xa = x * float(*m++); ya = x * float(*m++); za = x * float(*m++); m++;
xa += y * float(*m++); ya += y * float(*m++); za += y * float(*m++); m++;
xa += z * float(*m++); ya += z * float(*m++); za += z * float(*m++); m++;
xa += float(*m++); ya += float(*m++); za += float(*m++);
x = xa; y = ya; z = za;
return *this;
}
// p' = Mp
Vector3DF &Vector3DF::operator*= (const Matrix4F &op)
{
float xa, ya, za;
xa = x * op.data[0] + y * op.data[4] + z * op.data[8] + op.data[12];
ya = x * op.data[1] + y * op.data[5] + z * op.data[9] + op.data[13];
za = x * op.data[2] + y * op.data[6] + z * op.data[10] + op.data[14];
x = xa; y = ya; z = za;
return *this;
}
Vector3DF& Vector3DF::Clamp (float a, float b)
{
x = (x<a) ? a : ((x>b) ? b : x);
y = (y<a) ? a : ((y>b) ? b : y);
z = (z<a) ? a : ((z>b) ? b : z);
return *this;
}
#define min3(a,b,c) ( (a<b) ? ((a<c) ? a : c) : ((b<c) ? b : c) )
#define max3(a,b,c) ( (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) )
Vector3DF Vector3DF::RGBtoHSV ()
{
float h,s,v;
float minv, maxv;
int i;
float f;
minv = min3(x, y, z);
maxv = max3(x, y, z);
if (minv==maxv) {
v = (float) maxv;
h = 0.0;
s = 0.0;
} else {
v = (float) maxv;
s = (maxv - minv) / maxv;
f = (x == minv) ? y - z : ((y == minv) ? z - x : x - y);
i = (x == minv) ? 3 : ((y == minv) ? 5 : 1);
h = (i - f / (maxv - minv) ) / 6.0f;
}
return Vector3DF(h,s,v);
}
Vector3DF Vector3DF::HSVtoRGB ()
{
double m, n, f;
int i = floor ( x*6.0 );
f = x*6.0 - i;
if ( i % 2 == 0 ) f = 1.0 - f;
m = z * (1.0 - y );
n = z * (1.0 - y * f );
switch ( i ) {
case 6:
case 0: return Vector3DF( z, n, m ); break;
case 1: return Vector3DF( n, z, m ); break;
case 2: return Vector3DF( m, z, n ); break;
case 3: return Vector3DF( m, n, z ); break;
case 4: return Vector3DF( n, m, z ); break;
case 5: return Vector3DF( z, m, n ); break;
};
return Vector3DF(1,1,1);
}
Vector4DF &Vector4DF::operator*= (const MatrixF &op)
{
double *m = op.GetDataF ();
VTYPE xa, ya, za, wa;
xa = x * float(*m++); ya = x * float(*m++); za = x * float(*m++); wa = x * float(*m++);
xa += y * float(*m++); ya += y * float(*m++); za += y * float(*m++); wa += y * float(*m++);
xa += z * float(*m++); ya += z * float(*m++); za += z * float(*m++); wa += z * float(*m++);
xa += w * float(*m++); ya += w * float(*m++); za += w * float(*m++); wa += w * float(*m++);
x = xa; y = ya; z = za; w = wa;
return *this;
}
Vector4DF &Vector4DF::operator*= (const Matrix4F &op)
{
float xa, ya, za, wa;
xa = x * op.data[0] + y * op.data[4] + z * op.data[8] + w * op.data[12];
ya = x * op.data[1] + y * op.data[5] + z * op.data[9] + w * op.data[13];
za = x * op.data[2] + y * op.data[6] + z * op.data[10] + w * op.data[14];
wa = x * op.data[3] + y * op.data[7] + z * op.data[11] + w * op.data[15];
x = xa; y = ya; z = za; w = wa;
return *this;
}
Vector4DF &Vector4DF::operator*= (const float* op)
{
float xa, ya, za, wa;
xa = x * op[0] + y * op[4] + z * op[8] + w * op[12];
ya = x * op[1] + y * op[5] + z * op[9] + w * op[13];
za = x * op[2] + y * op[6] + z * op[10] + w * op[14];
wa = x * op[3] + y * op[7] + z * op[11] + w * op[15];
x = xa; y = ya; z = za; w = wa;
return *this;
}
| 28.601695 | 92 | 0.47437 | csiro-robotics |
8c1dde0196518bd1550bee9b3f84249cf7060d1c | 198 | cpp | C++ | test_index_reference.cpp | insertinterestingnamehere/cython_overload_except | 00d76ad8020fcb21948545de8161da65f7f4acd8 | [
"BSD-2-Clause"
] | null | null | null | test_index_reference.cpp | insertinterestingnamehere/cython_overload_except | 00d76ad8020fcb21948545de8161da65f7f4acd8 | [
"BSD-2-Clause"
] | null | null | null | test_index_reference.cpp | insertinterestingnamehere/cython_overload_except | 00d76ad8020fcb21948545de8161da65f7f4acd8 | [
"BSD-2-Clause"
] | null | null | null | #include "add.cpp"
#include <iostream>
int main(){
wrapped_int a = 3;
long long b = 2;
std::cout << a[b].val << std::endl;
wrapped_int &temp = a[b];
std::cout << temp.val << std::endl;
}
| 18 | 37 | 0.580808 | insertinterestingnamehere |
8c1e21fcc1bfc1f79fd2dad6a5aa8ff6dc21c3ff | 2,280 | cpp | C++ | app/main.cpp | shivamakhauri04/midterm_project | 4d062d90cb459d035fa9453aa837463b1e72f5a5 | [
"MIT"
] | null | null | null | app/main.cpp | shivamakhauri04/midterm_project | 4d062d90cb459d035fa9453aa837463b1e72f5a5 | [
"MIT"
] | 9 | 2019-10-19T06:55:30.000Z | 2019-10-21T15:08:33.000Z | app/main.cpp | shivamakhauri04/midterm_project | 4d062d90cb459d035fa9453aa837463b1e72f5a5 | [
"MIT"
] | 1 | 2019-10-19T02:12:38.000Z | 2019-10-19T02:12:38.000Z | /**
* @file main.cpp
* @author Shivam Akhauri (Driver),Toyas Dhake (Navigator),
* @date 20 October 2019
* @copyright 2019 Toyas Dhake, Shivam Akhauri
* @brief Main file for implementation of the Depth Perception project.
*/
#include <dlib/opencv.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <iostream>
#include <distance.hpp>
#include <face.hpp>
#include <opencv2/highgui/highgui.hpp>
int main() {
// Constructor call for distance calculation
CalculateDistance calculateDistance;
// Initialise the video frame buffer of the camera
cv::VideoCapture cap(0);
// Check if the opencv was able to communicate with the camera
if (!cap.isOpened()) {
std::cout << "Unable to connect to camera" << std::endl;
return 1;
}
dlib::frontal_face_detector detector = dlib::get_frontal_face_detector();
// Assign a window named win to show the current frame
dlib::image_window win;
// Grab each frame and calculate distance till the window is closed
while (!win.is_closed()) {
// read each frame in the buffer one by one
cv::Mat temp;
// if not able to read a frame in the buffer, close the application
if (!cap.read(temp)) {
break;
}
std::vector<Face> faces = calculateDistance.getDistance(temp, detector);
// This is vector of faces with their distance
dlib::cv_image<dlib::bgr_pixel> cimg(temp);
// Display the frame all on the screen
win.clear_overlay();
win.set_image(cimg);
for (auto&& face : faces) {
// draw a bounding box around the face
dlib::rectangle rect(face.getX(), face.getY(), face.getW(),
face.getH());
// write the distance and the x,y coordinates
// of the detected face below the bounding box
win.add_overlay(dlib::image_window::overlay_rect(rect,
dlib::rgb_pixel(0, 255, 0),
std::to_string(face.getX()) + ", " +
std::to_string(face.getY()) + ", " +
std::to_string(face.getDistance())+" m"));
}
}
return 0;
}
| 38.644068 | 80 | 0.601316 | shivamakhauri04 |
8c28ff85a56ee2abce629feee801ca4185d9fd4e | 355 | cpp | C++ | tests/mixed/mixed_invalid_unwrap_test.cpp | pacmancoder/exl | ffd66d30e76d60aa7e4efe75274e4a8a35427961 | [
"BSL-1.0"
] | 1 | 2019-05-02T12:00:50.000Z | 2019-05-02T12:00:50.000Z | tests/mixed/mixed_invalid_unwrap_test.cpp | pacmancoder/exl | ffd66d30e76d60aa7e4efe75274e4a8a35427961 | [
"BSL-1.0"
] | 14 | 2019-02-13T17:21:07.000Z | 2019-03-08T21:40:38.000Z | tests/mixed/mixed_invalid_unwrap_test.cpp | pacmancoder/exl | ffd66d30e76d60aa7e4efe75274e4a8a35427961 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2019 Vladislav Nikonov <[email protected]>
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
#include <exl/mixed.hpp>
#include <termination_test.hpp>
void termination_test()
{
exl::mixed<char, int> m(422);
m.unwrap<char>();
} | 25.357143 | 83 | 0.715493 | pacmancoder |
8c2a7228c91fe29e32f4bdf0d3796f4e551b287c | 5,812 | hpp | C++ | src/libv/diff/diff.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/diff/diff.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/diff/diff.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.diff, File: src/libv/diff/diff.hpp, Author: Császár Mátyás [Vader]
#pragma once
// libv
#include <libv/utility/bytes/input_bytes.hpp>
#include <libv/utility/bytes/output_bytes.hpp>
// std
#include <optional>
#include <string>
#include <vector>
namespace libv {
namespace diff {
// -------------------------------------------------------------------------------------------------
static constexpr size_t default_match_block_size = 64;
// -------------------------------------------------------------------------------------------------
struct diff_info {
private:
static constexpr size_t invalid = std::numeric_limits<size_t>::max();
public:
size_t old_size = invalid;
size_t new_size = invalid;
public:
[[nodiscard]] constexpr inline bool valid() const noexcept {
return
old_size != invalid &&
new_size != invalid;
}
[[nodiscard]] explicit constexpr inline operator bool() const noexcept {
return valid();
}
[[nodiscard]] constexpr inline bool operator!() const noexcept {
return !valid();
}
};
namespace detail { // ------------------------------------------------------------------------------
void aux_create_diff(libv::input_bytes old, libv::input_bytes new_, libv::output_bytes out_diff, size_t match_block_size);
[[nodiscard]] diff_info aux_get_diff_info(libv::input_bytes diff);
[[nodiscard]] bool aux_check_diff(libv::input_bytes old, libv::input_bytes new_, libv::input_bytes diff);
[[nodiscard]] bool apply_patch(libv::input_bytes old, libv::input_bytes diff, libv::output_bytes out_new);
} // namespace -------------------------------------------------------------------------------------
/// Create a diff from \c old to \c new and appends at the end of \c diff.
///
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param match_block_size - Smaller block size improves compression but at the cost of performance. Recommended 16-16384
/// \return The resulting diff that can be applied to \c old to get \c new
template <typename In0, typename In1, typename Out>
inline void create_diff(In0&& old, In1&& new_, Out&& out_diff, size_t match_block_size = default_match_block_size) {
detail::aux_create_diff(libv::input_bytes(old), libv::input_bytes(new_), libv::output_bytes(out_diff), match_block_size);
}
/// Returns a diff created from \c old to \c new.
///
/// \template T - The output type used for diff (std::string or std::vector<std::byte>)
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param match_block_size - Smaller block size improves compression but at the cost of performance. Recommended 16-16384
/// \return The resulting diff that can be applied to \c old to get \c new
template <typename T, typename In0, typename In1>
[[nodiscard]] inline T create_diff(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
T diff;
create_diff(old, new_, diff, match_block_size);
return diff;
}
template <typename In0, typename In1>
[[nodiscard]] inline std::string create_diff_str(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
return create_diff<std::string>(old, new_, match_block_size);
}
template <typename In0, typename In1>
[[nodiscard]] inline std::vector<std::byte> create_diff_bin(In0&& old, In1&& new_, size_t match_block_size = default_match_block_size) {
return create_diff<std::vector<std::byte>>(old, new_, match_block_size);
}
/// \return Returns a non valid diff_info object upon failure, otherwise returns the diff info
template <typename In0>
[[nodiscard]] diff_info get_diff_info(In0&& diff) {
return detail::aux_get_diff_info(libv::input_bytes(diff));
}
/// Check if the \c diff applied to \c old will result in \c new.
///
/// \param old - The old version of the data
/// \param new_ - The new version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns true if \c diff can be applied to \c old and it results in \c new
template <typename In0, typename In1, typename In2>
[[nodiscard]] inline bool check_diff(In0&& old, In1&& new_, In2&& diff) {
return detail::aux_check_diff(libv::input_bytes(old), libv::input_bytes(new_), libv::input_bytes(diff));
}
/// Applies \c diff to \c old.
///
/// \param old - The old version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns the new version of the data after applying the \c diff or an empty optional if the \c diff cannot be applied to \olc
template <typename In0, typename In1, typename Out>
[[nodiscard]] inline bool apply_patch(In0&& old, In1&& diff, Out&& out_new) {
return detail::apply_patch(libv::input_bytes(old), libv::input_bytes(diff), libv::output_bytes(out_new));
}
/// Applies \c diff to \c old.
///
/// \param old - The old version of the data
/// \param diff - The diff that will be applied to \c old
/// \return Returns the new version of the data after applying the \c diff or an empty optional if the \c diff cannot be applied to \olc
template <typename T, typename In0, typename In1>
[[nodiscard]] inline std::optional<T> apply_patch(In0&& old, In1&& diff) {
std::optional<T> new_(std::in_place);
const auto success = apply_patch(old, diff, *new_);
if (!success)
new_.reset();
return new_;
}
template <typename In0, typename In1>
[[nodiscard]] inline std::optional<std::string> apply_patch_str(In0&& old, In1&& diff) {
return apply_patch<std::string>(old, diff);
}
template <typename In0, typename In1>
[[nodiscard]] inline std::optional<std::vector<std::byte>> apply_patch_bin(In0&& old, In1&& diff) {
return apply_patch<std::vector<std::byte>>(old, diff);
}
// -------------------------------------------------------------------------------------------------
} // namespace diff
} // namespace libv
| 39.808219 | 136 | 0.668789 | cpplibv |
8c2b0f8c42e3757625f710420e30b7d152444f96 | 14,696 | cpp | C++ | LSL/GLUtils.cpp | AntonBogomolov/LightSpeedLimit | 215d573f46eef63801cbd8df654f104401bae581 | [
"MIT"
] | null | null | null | LSL/GLUtils.cpp | AntonBogomolov/LightSpeedLimit | 215d573f46eef63801cbd8df654f104401bae581 | [
"MIT"
] | null | null | null | LSL/GLUtils.cpp | AntonBogomolov/LightSpeedLimit | 215d573f46eef63801cbd8df654f104401bae581 | [
"MIT"
] | null | null | null | #include "global.h"
#include "GLUtils.h"
#include "GLShaderObject.h"
#include "TextureManager.h"
#include "Texture.h"
#include "TextureAtlas.h"
#include "VertexArray.h"
#include "VertexBuffer.h"
#include "SceneGraphNode.h"
#include "ScreenObj.h"
#include "VideoManeger.h"
#include "DrawablePrimitive.h"
CGLUtils* CGLUtils::instance = NULL;
CVertexBuffer* CGLUtils::quad = NULL;
CVertexBuffer* CGLUtils::revQuad = NULL;
CVertexBuffer* CGLUtils::lQuad = NULL;
CDrawablePrimitive* CGLUtils::QuadNode = NULL;
CDrawablePrimitive* CGLUtils::revQuadNode = NULL;
byte* CGLUtils::glGetTexImage(const int texId, const int texW, const int texH)
{
GLuint* framebuffer = new GLuint[1];
glGenFramebuffers(1, framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer[0]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CTextureManager::getTexture(texId)->getID(), 0); // texId
int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
// Log.e("glGetTexImage", "image load faild");
}
byte* buff = new byte[texW * texH * 4];
glReadPixels(0, 0, texW, texH, GL_RGBA, GL_UNSIGNED_BYTE, buff);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, framebuffer);
return buff;
}
void CGLUtils::checkGlError(const string op)
{
int error;
while ((error = glGetError()) != GL_NO_ERROR)
{
}
}
CSceneGraphNodeDrawable* CGLUtils::getFullscreenDrawableNode()
{
if (!QuadNode) initFullscreenQuad();
return (CSceneGraphNodeDrawable*)QuadNode;
}
CSceneGraphNodeDrawable* CGLUtils::getFullscreenRevDrawableNode()
{
if (!revQuadNode) initFullscreenRevQuad();
return (CSceneGraphNodeDrawable*)revQuadNode;
}
CVertexBuffer* CGLUtils::initFullscreenQuad()
{
if (quad) delete quad;
quad = NULL;
quad = new CVertexBuffer();
if (!QuadNode) QuadNode = new CDrawablePrimitive();
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
GLfloat qcoords[] = { 0, 0, 1, 0, 1, 1, 0, 1 };
short qind[] = { 0, 1, 2, 0, 2, 3 };
quad->setVerticesData(qverts, 4 * 3);
quad->setTexData(qcoords, 4 * 2);
quad->setIndicesData(qind, 6);
QuadNode->setVBO(quad);
return quad;
}
void CGLUtils::drawFullscreenQuad(const CGLShaderObject* currShader)
{
if (quad == NULL) initFullscreenQuad();
if (quad)
{
quad->drawElements(0, currShader);
}
}
CVertexBuffer* CGLUtils::initFullscreenRevQuad()
{
if (revQuad) delete revQuad;
revQuad = NULL;
revQuad = new CVertexBuffer();
if (!revQuadNode) revQuadNode = new CDrawablePrimitive();
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
GLfloat qcoords[] = { 0, 1, 1, 1, 1, 0, 0, 0 };
short qind[] = { 0, 1, 2, 0, 2, 3 };
revQuad->setVerticesData(qverts, 4 * 3);
revQuad->setTexData(qcoords, 4 * 2);
revQuad->setIndicesData(qind, 6);
revQuadNode->setVBO(revQuad);
return revQuad;
}
void CGLUtils::drawFullscreenRevQuad(const CGLShaderObject* currShader)
{
if (revQuad == NULL) initFullscreenRevQuad();
if (revQuad)
{
revQuad->drawElements(0, currShader);
}
}
CVertexBuffer* CGLUtils::initLFullscreenQuad()
{
float flDataVert[] = { 0, 0, 0, 0, 0,
CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, 0,
0, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight,
CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, 0,
0, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight,
CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight
};
return NULL;
}
void CGLUtils::drawLFullscreenQuad(const CGLShaderObject* currShader)
{
if (lQuad == NULL) initLFullscreenQuad();
}
void CGLUtils::fillVBOData( float* vert, float* tex, float* vtex, short* ind, const CTexCoord* sprite, const CTexCoord* vsprite,
const int index, const CScreenObj* obj, const int direction, const float offset)
{
bool hasAdditionalTexCoord = false;
if (vtex != NULL && vsprite != NULL) hasAdditionalTexCoord = true;
if (vert == NULL) return;
if (tex == NULL ) return;
if (ind == NULL ) return;
if (sprite == NULL) return;
const glm::vec2* points = obj->getPointsCoords();
int X1 = points[0].x;
int Y1 = points[0].y;
int X2 = points[1].x;
int Y2 = points[1].y;
int X3 = points[2].x;
int Y3 = points[2].y;
int X4 = points[3].x;
int Y4 = points[3].y;
vert[index * 12 + 0] = X1; vert[index * 12 + 1] = Y1; vert[index * 12 + 2] = 0;
vert[index * 12 + 3] = X2 + offset; vert[index * 12 + 4] = Y2; vert[index * 12 + 5] = 0;
vert[index * 12 + 6] = X3 + offset; vert[index * 12 + 7] = Y3 + offset; vert[index * 12 + 8] = 0;
vert[index * 12 + 9] = X4; vert[index * 12 + 10] =Y4 + offset; vert[index * 12 + 11] = 0;
switch (direction)
{
case Defines::DIR_DOWN:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_LEFT:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_RIGHT:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
default:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
}
ind[index * 6 + 0] = (short)(index * 4); ind[index * 6 + 1] = (short)(index * 4 + 1); ind[index * 6 + 2] = (short)(index * 4 + 2);
ind[index * 6 + 3] = (short)(index * 4); ind[index * 6 + 4] = (short)(index * 4 + 2); ind[index * 6 + 5] = (short)(index * 4 + 3);
}
void CGLUtils::fillVBOVertData(float* vert, const int index, const CScreenObj* obj, const float offset)
{
if (vert == NULL) return;
const glm::vec2* points = obj->getPointsCoords();
int X1 = points[0].x;
int Y1 = points[0].y;
int X2 = points[1].x;
int Y2 = points[1].y;
int X3 = points[2].x;
int Y3 = points[2].y;
int X4 = points[3].x;
int Y4 = points[3].y;
vert[index * 12 + 0] = X1; vert[index * 12 + 1] = Y1; vert[index * 12 + 2] = 0;
vert[index * 12 + 3] = X2 + offset; vert[index * 12 + 4] = Y2; vert[index * 12 + 5] = 0;
vert[index * 12 + 6] = X3 + offset; vert[index * 12 + 7] = Y3 + offset; vert[index * 12 + 8] = 0;
vert[index * 12 + 9] = X4; vert[index * 12 + 10] =Y4 + offset; vert[index * 12 + 11] = 0;
}
void CGLUtils::fillVBOTexData(float* tex, float* vtex, const CTexCoord* sprite, const CTexCoord* vsprite, const int index, const int direction, const float offset)
{
bool hasAdditionalTexCoord = false;
if (vtex != NULL && vsprite != NULL) hasAdditionalTexCoord = true;
if (tex == NULL) return;
if (sprite == NULL) return;
switch (direction)
{
case Defines::DIR_DOWN:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_LEFT:
tex[index * 8 + 0] = sprite->tx + sprite->twidth; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty + sprite->theight;
tex[index * 8 + 4] = sprite->tx; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 4] = vsprite->tx; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty;
}
break;
case Defines::DIR_RIGHT:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty + sprite->theight;
tex[index * 8 + 2] = sprite->tx; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty;
tex[index * 8 + 6] = sprite->tx + sprite->twidth; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 2] = vsprite->tx; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty;
vtex[index * 8 + 6] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
default:
tex[index * 8 + 0] = sprite->tx; tex[index * 8 + 1] = sprite->ty;
tex[index * 8 + 2] = sprite->tx + sprite->twidth; tex[index * 8 + 3] = sprite->ty;
tex[index * 8 + 4] = sprite->tx + sprite->twidth; tex[index * 8 + 5] = sprite->ty + sprite->theight;
tex[index * 8 + 6] = sprite->tx; tex[index * 8 + 7] = sprite->ty + sprite->theight;
if (hasAdditionalTexCoord)
{
vtex[index * 8 + 0] = vsprite->tx; vtex[index * 8 + 1] = vsprite->ty;
vtex[index * 8 + 2] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 3] = vsprite->ty;
vtex[index * 8 + 4] = vsprite->tx + vsprite->twidth; vtex[index * 8 + 5] = vsprite->ty + vsprite->theight;
vtex[index * 8 + 6] = vsprite->tx; vtex[index * 8 + 7] = vsprite->ty + vsprite->theight;
}
break;
}
}
void CGLUtils::fillVBOIndData(short* ind, const int index)
{
if (ind == NULL) return;
ind[index * 6 + 0] = (short)(index * 4); ind[index * 6 + 1] = (short)(index * 4 + 1); ind[index * 6 + 2] = (short)(index * 4 + 2);
ind[index * 6 + 3] = (short)(index * 4); ind[index * 6 + 4] = (short)(index * 4 + 2); ind[index * 6 + 5] = (short)(index * 4 + 3);
}
void CGLUtils::fillVBOData(float* vert, short* ind, const int index, const float* geomData, const int geomDataCoordCnt, const float offset)
{
if (vert == NULL || ind == NULL || geomData == NULL) return;
if (geomDataCoordCnt < 1 || geomDataCoordCnt > 3) return;
int X = (int)geomData[index * geomDataCoordCnt + 0];
int Y = (int)geomData[index * geomDataCoordCnt + 1];
int Z = (int)geomData[index * geomDataCoordCnt + 2];
if (geomDataCoordCnt == 1)
{
X = (int)geomData[index * geomDataCoordCnt + 0];
Y = 0;
Z = 0;
}
if (geomDataCoordCnt == 2)
{
X = (int)geomData[index * geomDataCoordCnt + 0];
Y = (int)geomData[index * geomDataCoordCnt + 1];
Z = 0;
}
vert[index * 3 + 0] = X; vert[index * 3 + 1] = Y; vert[index * 3 + 2] = Z;
ind[index] = index;
}
CGLUtils::CGLUtils()
{
}
CGLUtils::~CGLUtils()
{
if (quad) delete quad;
if (lQuad) delete lQuad;
if (revQuad) delete revQuad;
if (QuadNode) delete QuadNode;
if (revQuadNode) delete revQuadNode;
}
CGLUtils* CGLUtils::GetInstance()
{
if (instance == NULL)
{
instance = new CGLUtils();
}
return instance;
}
void CGLUtils::resizeWindow()
{
glViewport(0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight);
if (QuadNode)
{
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
QuadNode->getVBOForModify()->setVerticesData(qverts, 4 * 3);
}
if (revQuadNode)
{
GLfloat qverts[] = { 0, 0, 0, CVideoManeger::scrWidth, 0, 0, CVideoManeger::scrWidth, CVideoManeger::scrHeight, 0, 0, CVideoManeger::scrHeight, 0 };
revQuadNode->getVBOForModify()->setVerticesData(qverts, 4 * 3);
}
} | 37.394402 | 163 | 0.62187 | AntonBogomolov |
8c32011a805538118756eb62bf63bb51db53a544 | 377 | cc | C++ | below2.1/speeding.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/speeding.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | below2.1/speeding.cc | danzel-py/Kattis-Problem-Archive | bce1929d654b1bceb104f96d68c74349273dd1ff | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int nu;
cin>>nu;
int t,p;
cin>>t>>p;
int mem, memp;
int max = 0;
for (int i = 0; i < nu-1; i++)
{
mem = t;
memp = p;
cin>>t>>p;
if((p - memp)/(t-mem)>max){
max = (p - memp)/(t-mem);
}
}
cout<<max;
return 0;
} | 15.08 | 37 | 0.37931 | danzel-py |
8c38b1f3f05a74824dc7ef74d8f65ded63d62a3a | 263 | hpp | C++ | tools/mem_usage/mem_usage.hpp | LioQing/personal-utils | e24d1ea1510087797c6b85bae89a3801a2e77f3d | [
"Unlicense"
] | null | null | null | tools/mem_usage/mem_usage.hpp | LioQing/personal-utils | e24d1ea1510087797c6b85bae89a3801a2e77f3d | [
"Unlicense"
] | null | null | null | tools/mem_usage/mem_usage.hpp | LioQing/personal-utils | e24d1ea1510087797c6b85bae89a3801a2e77f3d | [
"Unlicense"
] | null | null | null | #pragma once
#include <cstdint>
namespace lio
{
enum MemArgs : uint8_t
{
USAGE = 0b001,
COUNT = 0b010,
PEAK = 0b100
};
extern size_t memory_count;
extern size_t memory_used;
extern size_t memory_peak;
void print_mem_isage(uint8_t args = USAGE);
} | 13.842105 | 44 | 0.714829 | LioQing |
8c4025d9dbd5731fa3083db7d2c4fd5895e88a69 | 4,798 | cpp | C++ | Framework/Math/Scissor.cpp | dengwenyi88/Deferred_Lighting | b45b6590150a3119b0c2365f4795d93b3b4f0748 | [
"MIT"
] | 110 | 2017-06-23T17:12:28.000Z | 2022-02-22T19:11:38.000Z | RunTest/Framework3/Math/Scissor.cpp | dtrebilco/ECSAtto | 86a04f0bdc521c79f758df94250c1898c39213c8 | [
"MIT"
] | null | null | null | RunTest/Framework3/Math/Scissor.cpp | dtrebilco/ECSAtto | 86a04f0bdc521c79f758df94250c1898c39213c8 | [
"MIT"
] | 3 | 2018-02-12T00:16:18.000Z | 2018-02-18T11:12:35.000Z |
/* * * * * * * * * * * * * Author's note * * * * * * * * * * * *\
* _ _ _ _ _ _ _ _ _ _ _ _ *
* |_| |_| |_| |_| |_|_ _|_| |_| |_| _|_|_|_|_| *
* |_|_ _ _|_| |_| |_| |_|_|_|_|_| |_| |_| |_|_ _ _ *
* |_|_|_|_|_| |_| |_| |_| |_| |_| |_| |_| |_|_|_|_ *
* |_| |_| |_|_ _ _|_| |_| |_| |_|_ _ _|_| _ _ _ _|_| *
* |_| |_| |_|_|_| |_| |_| |_|_|_| |_|_|_|_| *
* *
* http://www.humus.name *
* *
* This file is a part of the work done by Humus. You are free to *
* use the code in any way you like, modified, unmodified or copied *
* into your own work. However, I expect you to respect these points: *
* - If you use this file and its contents unmodified, or use a major *
* part of this file, please credit the author and leave this note. *
* - For use in anything commercial, please request my approval. *
* - Share your work and ideas too as much as you can. *
* *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Scissor.h"
/*
bool getScissorRectangle(const mat4 &projection, const mat4 &modelview, const vec3 &camPos, const vec3 &lightPos, const float radius, const int width, const int height, int *x, int *y, int *w, int *h){
float d = distance(camPos, lightPos);
float p = d * radius / sqrtf(d * d - radius * radius);
vec3 dx = modelview.rows[0].xyz();
vec3 dy = modelview.rows[1].xyz();
// vec3 dz = normalize(lightPos - camPos);
// dx = cross(dy, dz);
// dy = cross(dz, dx);
vec3 dz = normalize(lightPos - camPos);
vec3 dx = normalize(vec3(dz.z, 0, -dz.x));
vec3 dy = normalize(cross(dz, dx));
vec4 leftPos = vec4(lightPos - p * dx, 1.0f);
vec4 rightPos = vec4(lightPos + p * dx, 1.0f);
mat4 mvp = projection * modelview;
leftPos = mvp * leftPos;
rightPos = mvp * rightPos;
int left = int(width * (leftPos.x / leftPos.z * 0.5f + 0.5f));
int right = int(width * (rightPos.x / rightPos.z * 0.5f + 0.5f));
*x = left;
*w = right - left;
*y = 0;
*h = height;
return true;
}
*/
#define EPSILON 0.0005f
bool getScissorRectangle(const mat4 &modelview, const vec3 &pos, const float radius, const float fov, const int width, const int height, int *x, int *y, int *w, int *h){
vec4 lightPos = modelview * vec4(pos, 1.0f);
float ex = tanf(fov / 2);
float ey = ex * height / width;
float Lxz = (lightPos.x * lightPos.x + lightPos.z * lightPos.z);
float a = -radius * lightPos.x / Lxz;
float b = (radius * radius - lightPos.z * lightPos.z) / Lxz;
float f = -b + a * a;
float lp = 0;
float rp = 1;
float bp = 0;
float tp = 1;
// if (f > EPSILON){
if (f > 0){
float Nx0 = -a + sqrtf(f);
float Nx1 = -a - sqrtf(f);
float Nz0 = (radius - Nx0 * lightPos.x) / lightPos.z;
float Nz1 = (radius - Nx1 * lightPos.x) / lightPos.z;
float x0 = 0.5f * (1 - Nz0 / (Nx0 * ex));
float x1 = 0.5f * (1 - Nz1 / (Nx1 * ex));
float Pz0 = (Lxz - radius * radius) / (lightPos.z - lightPos.x * Nz0 / Nx0);
float Pz1 = (Lxz - radius * radius) / (lightPos.z - lightPos.x * Nz1 / Nx1);
float Px0 = -(Pz0 * Nz0) / Nx0;
float Px1 = -(Pz1 * Nz1) / Nx1;
if (Px0 > lightPos.x) rp = x0;
if (Px0 < lightPos.x) lp = x0;
if (Px1 > lightPos.x && x1 < rp) rp = x1;
if (Px1 < lightPos.x && x1 > lp) lp = x1;
}
float Lyz = (lightPos.y * lightPos.y + lightPos.z * lightPos.z);
a = -radius * lightPos.y / Lyz;
b = (radius * radius - lightPos.z * lightPos.z) / Lyz;
f = -b + a * a;
// if (f > EPSILON){
if (f > 0){
float Ny0 = -a + sqrtf(f);
float Ny1 = -a - sqrtf(f);
float Nz0 = (radius - Ny0 * lightPos.y) / lightPos.z;
float Nz1 = (radius - Ny1 * lightPos.y) / lightPos.z;
float y0 = 0.5f * (1 - Nz0 / (Ny0 * ey));
float y1 = 0.5f * (1 - Nz1 / (Ny1 * ey));
float Pz0 = (Lyz - radius * radius) / (lightPos.z - lightPos.y * Nz0 / Ny0);
float Pz1 = (Lyz - radius * radius) / (lightPos.z - lightPos.y * Nz1 / Ny1);
float Py0 = -(Pz0 * Nz0) / Ny0;
float Py1 = -(Pz1 * Nz1) / Ny1;
if (Py0 > lightPos.y) tp = y0;
if (Py0 < lightPos.y) bp = y0;
if (Py1 > lightPos.y && y1 < tp) tp = y1;
if (Py1 < lightPos.y && y1 > bp) bp = y1;
}
lp *= width;
rp *= width;
tp *= height;
bp *= height;
int left = int(lp);
int right = int(rp);
int top = int(tp);
int bottom = int(bp);
if (right <= left || top <= bottom) return false;
*x = min(max(int(left), 0), width - 1);
*y = min(max(int(bottom), 0), height - 1);
*w = min(int(right) - *x, width - *x);
*h = min(int(top) - *y, height - *y);
return (*w > 0 && *h > 0);
}
| 32.418919 | 201 | 0.516048 | dengwenyi88 |
8c402ea7a19d66f47675ff19cdb33761cb9c5fe1 | 10,767 | cpp | C++ | app/src/main/jni/comitton/PdfCrypt.cpp | mryp/ComittoNxA | 9b46c267bff22c2090d75ac70b589f9a12d61457 | [
"Unlicense"
] | 14 | 2020-08-05T09:36:01.000Z | 2022-02-23T01:48:18.000Z | app/src/main/jni/comitton/PdfCrypt.cpp | yuma2a/ComittoNxA-Continued | 9d85c4f5753e534c3ff0cf83fe53df588872c8ff | [
"Unlicense"
] | 1 | 2021-11-13T14:23:07.000Z | 2021-11-13T14:23:07.000Z | app/src/main/jni/comitton/PdfCrypt.cpp | mryp/ComittoNxA | 9b46c267bff22c2090d75ac70b589f9a12d61457 | [
"Unlicense"
] | 4 | 2021-04-21T02:56:50.000Z | 2021-11-08T12:02:32.000Z | /*
MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
All rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
//#include "fitz-internal.h"
#include <string.h>
#include <android/log.h>
#include "PdfCrypt.h"
//#define DEBUG
/*
* Compute an encryption key (PDF 1.7 algorithm 3.2)
*/
static const unsigned char padding[32] =
{
0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
};
/*
* PDF 1.7 algorithm 3.1 and ExtensionLevel 3 algorithm 3.1a
*
* Using the global encryption key that was generated from the
* password, create a new key that is used to decrypt individual
* objects and streams. This key is based on the object and
* generation numbers.
*/
int computeObjectKey(int method, BYTE *crypt_key, int crypt_len, int num, int gen, BYTE *res_key)
{
fz_md5 md5;
unsigned char message[5];
if (method == PDF_CRYPT_AESV3) {
memcpy(res_key, crypt_key, crypt_len / 8);
return crypt_len / 8;
}
fz_md5_init(&md5);
fz_md5_update(&md5, crypt_key, crypt_len / 8);
message[0] = (num) & 0xFF;
message[1] = (num >> 8) & 0xFF;
message[2] = (num >> 16) & 0xFF;
message[3] = (gen) & 0xFF;
message[4] = (gen >> 8) & 0xFF;
fz_md5_update(&md5, message, 5);
if (method == PDF_CRYPT_AESV2) {
fz_md5_update(&md5, (unsigned char *)"sAlT", 4);
}
fz_md5_final(&md5, res_key);
if (crypt_len / 8 + 5 > 16) {
return 16;
}
return crypt_len / 8 + 5;
}
static void
pdf_compute_encryption_key(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *key)
{
#ifdef DEBUG
LOGD("pdf_compute_encryption_key");
#endif
unsigned char buf[32];
unsigned int p;
int i, n;
fz_md5 md5;
n = crypt->length / 8;
/* Step 1 - copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(buf, password, pwlen);
memcpy(buf + pwlen, padding, 32 - pwlen);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 1-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 2 - init md5 and pass value of step 1 */
fz_md5_init(&md5);
fz_md5_update(&md5, buf, 32);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 2-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 3 - pass O value */
fz_md5_update(&md5, crypt->o, 32);
/* Step 4 - pass P value as unsigned int, low-order byte first */
p = (unsigned int) crypt->p;
buf[0] = (p) & 0xFF;
buf[1] = (p >> 8) & 0xFF;
buf[2] = (p >> 16) & 0xFF;
buf[3] = (p >> 24) & 0xFF;
fz_md5_update(&md5, buf, 4);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 3-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 5 - pass first element of ID array */
fz_md5_update(&md5, crypt->id, crypt->id_len);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: id=%s,%d", crypt->id, crypt->id_len);
#endif
/* Step 6 (revision 4 or greater) - if metadata is not encrypted pass 0xFFFFFFFF */
if (crypt->r >= 4)
{
if (!crypt->encrypt_metadata)
{
buf[0] = 0xFF;
buf[1] = 0xFF;
buf[2] = 0xFF;
buf[3] = 0xFF;
fz_md5_update(&md5, buf, 4);
}
}
/* Step 7 - finish the hash */
fz_md5_final(&md5, buf);
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 4-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
/* Step 8 (revision 3 or greater) - do some voodoo 50 times */
if (crypt->r >= 3)
{
for (i = 0; i < 50; i++)
{
fz_md5_init(&md5);
fz_md5_update(&md5, buf, n);
fz_md5_final(&md5, buf);
}
}
/* Step 9 - the key is the first 'n' bytes of the result */
#ifdef DEBUG
LOGD("pdf_compute_encryption_key: 5-buf=%d,%d,%d,%d,%d,%d..., n=%d", (int)buf[0], (int)buf[1], (int)buf[2], (int)buf[3], (int)buf[4], (int)buf[5], n);
#endif
memcpy(key, buf, n);
}
/*
* Compute an encryption key (PDF 1.7 ExtensionLevel 3 algorithm 3.2a)
*/
static void
pdf_compute_encryption_key_r5(pdf_crypt *crypt, unsigned char *password, int pwlen, int ownerkey, unsigned char *validationkey)
{
unsigned char buffer[128 + 8 + 48];
fz_sha256 sha256;
fz_aes aes;
/* Step 2 - truncate UTF-8 password to 127 characters */
if (pwlen > 127)
pwlen = 127;
/* Step 3/4 - test password against owner/user key and compute encryption key */
memcpy(buffer, password, pwlen);
if (ownerkey)
{
memcpy(buffer + pwlen, crypt->o + 32, 8);
memcpy(buffer + pwlen + 8, crypt->u, 48);
}
else
memcpy(buffer + pwlen, crypt->u + 32, 8);
fz_sha256_init(&sha256);
fz_sha256_update(&sha256, buffer, pwlen + 8 + (ownerkey ? 48 : 0));
fz_sha256_final(&sha256, validationkey);
/* Step 3.5/4.5 - compute file encryption key from OE/UE */
memcpy(buffer + pwlen, crypt->u + 40, 8);
fz_sha256_init(&sha256);
fz_sha256_update(&sha256, buffer, pwlen + 8);
fz_sha256_final(&sha256, buffer);
/* clear password buffer and use it as iv */
memset(buffer + 32, 0, sizeof(buffer) - 32);
aes_setkey_dec(&aes, buffer, crypt->length);
aes_crypt_cbc(&aes, AES_DECRYPT, 32, buffer + 32, ownerkey ? crypt->oe : crypt->ue, crypt->key);
}
/*
* Computing the user password (PDF 1.7 algorithm 3.4 and 3.5)
* Also save the generated key for decrypting objects and streams in crypt->key.
*/
static void
pdf_compute_user_password(pdf_crypt *crypt, unsigned char *password, int pwlen, unsigned char *output)
{
#ifdef DEBUG
LOGD("pdf_compute_user_password: r=%d", crypt->r);
#endif
if (crypt->r == 2)
{
fz_arc4 arc4;
#ifdef DEBUG
LOGD("r==2", crypt->r);
#endif
pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
fz_arc4_init(&arc4, crypt->key, crypt->length / 8);
fz_arc4_encrypt(&arc4, output, padding, 32);
}
if (crypt->r == 3 || crypt->r == 4)
{
unsigned char xors[32];
unsigned char digest[16];
fz_md5 md5;
fz_arc4 arc4;
int i, x, n;
n = crypt->length / 8;
pdf_compute_encryption_key(crypt, password, pwlen, crypt->key);
fz_md5_init(&md5);
fz_md5_update(&md5, padding, 32);
fz_md5_update(&md5, crypt->id, crypt->id_len);
fz_md5_final(&md5, digest);
fz_arc4_init(&arc4, crypt->key, n);
fz_arc4_encrypt(&arc4, output, digest, 16);
for (x = 1; x <= 19; x++)
{
for (i = 0; i < n; i++)
xors[i] = crypt->key[i] ^ x;
fz_arc4_init(&arc4, xors, n);
fz_arc4_encrypt(&arc4, output, output, 16);
}
memcpy(output + 16, padding, 16);
}
if (crypt->r == 5)
{
pdf_compute_encryption_key_r5(crypt, password, pwlen, 0, output);
}
}
/*
* Authenticating the user password (PDF 1.7 algorithm 3.6
* and ExtensionLevel 3 algorithm 3.11)
* This also has the side effect of saving a key generated
* from the password for decrypting objects and streams.
*/
static int
pdf_authenticate_user_password(pdf_crypt *crypt, unsigned char *password, int pwlen)
{
#ifdef DEBUG
LOGD("pdf_authenticate_user_password");
#endif
unsigned char output[32];
pdf_compute_user_password(crypt, password, pwlen, output);
if (crypt->r == 2 || crypt->r == 5)
return memcmp(output, crypt->u, 32) == 0;
if (crypt->r == 3 || crypt->r == 4)
return memcmp(output, crypt->u, 16) == 0;
return 0;
}
/*
* Authenticating the owner password (PDF 1.7 algorithm 3.7
* and ExtensionLevel 3 algorithm 3.12)
* Generates the user password from the owner password
* and calls pdf_authenticate_user_password.
*/
static int
pdf_authenticate_owner_password(pdf_crypt *crypt, unsigned char *ownerpass, int pwlen)
{
unsigned char pwbuf[32];
unsigned char key[32];
unsigned char xors[32];
unsigned char userpass[32];
int i, n, x;
fz_md5 md5;
fz_arc4 arc4;
if (crypt->r == 5)
{
/* PDF 1.7 ExtensionLevel 3 algorithm 3.12 */
pdf_compute_encryption_key_r5(crypt, ownerpass, pwlen, 1, key);
return !memcmp(key, crypt->o, 32);
}
n = crypt->length / 8;
/* Step 1 -- steps 1 to 4 of PDF 1.7 algorithm 3.3 */
/* copy and pad password string */
if (pwlen > 32)
pwlen = 32;
memcpy(pwbuf, ownerpass, pwlen);
memcpy(pwbuf + pwlen, padding, 32 - pwlen);
/* take md5 hash of padded password */
fz_md5_init(&md5);
fz_md5_update(&md5, pwbuf, 32);
fz_md5_final(&md5, key);
/* do some voodoo 50 times (Revision 3 or greater) */
if (crypt->r >= 3)
{
for (i = 0; i < 50; i++)
{
fz_md5_init(&md5);
fz_md5_update(&md5, key, 16);
fz_md5_final(&md5, key);
}
}
/* Step 2 (Revision 2) */
if (crypt->r == 2)
{
fz_arc4_init(&arc4, key, n);
fz_arc4_encrypt(&arc4, userpass, crypt->o, 32);
}
/* Step 2 (Revision 3 or greater) */
if (crypt->r >= 3)
{
memcpy(userpass, crypt->o, 32);
for (x = 0; x < 20; x++)
{
for (i = 0; i < n; i++)
xors[i] = key[i] ^ (19 - x);
fz_arc4_init(&arc4, xors, n);
fz_arc4_encrypt(&arc4, userpass, userpass, 32);
}
}
return pdf_authenticate_user_password(crypt, userpass, 32);
}
int
pdf_authenticate_password(pdf_crypt *crypt, char *password)
{
#ifdef DEBUG
LOGD("pdf_authenticate_password");
#endif
if (crypt)
{
if (!password)
password = (char*)"";
if (pdf_authenticate_user_password(crypt, (unsigned char *)password, strlen(password)))
return 1;
if (pdf_authenticate_owner_password(crypt, (unsigned char *)password, strlen(password)))
return 1;
return 0;
}
return 1;
}
int
pdf_needs_password(pdf_crypt *crypt)
{
if (!crypt)
return 0;
if (pdf_authenticate_password(crypt, (char*)""))
return 0;
return 1;
}
int
pdf_has_permission(pdf_crypt *crypt, int p)
{
if (!crypt)
return 1;
return crypt->p & p;
}
unsigned char *
pdf_crypt_key(pdf_crypt *crypt)
{
if (crypt)
return crypt->key;
return NULL;
}
int
pdf_crypt_version(pdf_crypt *crypt)
{
if (crypt)
return crypt->v;
return 0;
}
int pdf_crypt_revision(pdf_crypt *crypt)
{
if (crypt)
return crypt->r;
return 0;
}
int
pdf_crypt_length(pdf_crypt *crypt)
{
if (crypt)
return crypt->length;
return 0;
}
| 24.414966 | 151 | 0.665181 | mryp |
8c4362e959450f80b6bf82e2f1ed5afb88ab06c5 | 13,332 | cpp | C++ | src/ui/inspectMode.cpp | averrin/lss | c2aa0486641fba15daceab3241122e387720c898 | [
"MIT"
] | 4 | 2018-07-09T20:53:06.000Z | 2018-07-12T07:10:19.000Z | src/ui/inspectMode.cpp | averrin/lss | c2aa0486641fba15daceab3241122e387720c898 | [
"MIT"
] | null | null | null | src/ui/inspectMode.cpp | averrin/lss | c2aa0486641fba15daceab3241122e387720c898 | [
"MIT"
] | null | null | null | #include "ui/inspectMode.hpp"
#include "ui/LSSApp.hpp"
#include "ui/fragment.hpp"
#include "lss/generator/room.hpp"
#include "lss/utils.hpp"
#include "ui/utils.hpp"
auto F = [](std::string c) { return std::make_shared<Fragment>(c); };
bool InspectMode::processKey(KeyEvent event) {
switch (event.getCode()) {
case SDL_SCANCODE_S:
highlightWhoCanSee = !highlightWhoCanSee;
app->state->invalidateSelection("change view mode");
render();
return true;
case SDL_SCANCODE_R:
showRooms = !showRooms;
app->state->invalidateSelection("change view mode");
render();
return true;
case SDL_SCANCODE_J:
case SDL_SCANCODE_H:
case SDL_SCANCODE_L:
if (event.isShiftDown()) {
showLightSources = !showLightSources;
app->state->invalidateSelection("change view mode");
render();
return true;
}
case SDL_SCANCODE_K:
case SDL_SCANCODE_Y:
case SDL_SCANCODE_U:
case SDL_SCANCODE_B:
case SDL_SCANCODE_N: {
auto d = ui_utils::getDir(event.getCode());
if (d == std::nullopt)
break;
auto nc = app->hero->currentLocation->getCell(
app->hero->currentLocation
->cells[app->state->cursor.y][app->state->cursor.x],
*utils::getDirectionByName(*d));
if (!nc)
break;
app->state->selectionClear();
app->state->setCursor({(*nc)->x, (*nc)->y});
render();
return true;
} break;
}
return false;
}
void InspectMode::render() {
auto location = app->hero->currentLocation;
auto cell = location->cells[app->state->cursor.y][app->state->cursor.x];
auto objects = location->getObjects(cell);
auto cc = app->hero->currentCell;
auto check = "<span color='green'>✔</span>";
app->state->selection.clear();
auto line = location->getLine(app->hero->currentCell, cell);
for (auto c : line) {
app->state->setSelection({{c->x, c->y}, COLORS::CURSOR_TRACE});
}
app->inspectState->setContent(
{F(fmt::format("Selected cell: <b>{}.{}</b>", cell->x, cell->y))});
app->inspectState->appendContent(State::END_LINE);
auto vs = "UNKNOWN";
if (cell->visibilityState == VisibilityState::SEEN) {
vs = "SEEN";
} else if (cell->visibilityState == VisibilityState::VISIBLE) {
vs = "VISISBLE";
}
app->inspectState->appendContent(
{F(fmt::format("Visibility state: <b>{}</b>", vs))});
app->inspectState->appendContent(State::END_LINE);
if (!app->debug && !app->hero->canSee(cell)) {
app->inspectState->appendContent(
{F(fmt::format("You cannot see this cell"))});
app->inspectState->appendContent(State::END_LINE);
return;
}
app->inspectState->appendContent(
{F(fmt::format("Type: <b>{}</b>", cell->type.name))});
app->inspectState->appendContent(State::END_LINE);
if (cell->type == CellType::UNKNOWN)
return;
app->inspectState->appendContent(
{F(fmt::format("Type <b>PASS</b>THROUGH: [<b>{}</b>]",
cell->type.passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Type <b>SEE</b>THROUGH: [<b>{}</b>]",
cell->type.passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"<b>PASS</b>THROUGH: [<b>{}</b>]", cell->passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"<b>SEE</b>THROUGH: [<b>{}</b>]", cell->passThrough ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Illuminated: [<b>{}</b>]", cell->illuminated ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Illumination: <b>{}</b>", cell->illumination))});
app->inspectState->appendContent(State::END_LINE);
auto f = app->state->fragments[cell->y * app->state->width + cell->x];
// app->inspectState->appendContent({F(fmt::format(
// "Cell Illumination: <b>{}</b>", f->alpha))});
// app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(
fmt::format("Cell features count: <b>{}</b>", cell->features.size()))});
app->inspectState->appendContent(State::END_LINE);
if (cell->features.size() > 0) {
app->inspectState->appendContent({F("<b>Cell Features</b>")});
app->inspectState->appendContent(State::END_LINE);
}
for (auto f : cell->features) {
if (f == CellFeature::BLOOD) {
app->inspectState->appendContent(
{F(fmt::format("BLOOD: [<b>{}</b>]", check))});
}
if (f == CellFeature::CAVE) {
app->inspectState->appendContent(
{F(fmt::format("CAVE: [<b>{}</b>]", check))});
}
if (f == CellFeature::ACID) {
app->inspectState->appendContent(
{F(fmt::format("ACID: [<b>{}</b>]", check))});
}
if (f == CellFeature::FROST) {
app->inspectState->appendContent(
{F(fmt::format("FROST: [<b>{}</b>]", check))});
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(State::END_LINE);
if (cell->room == nullptr) {
app->inspectState->appendContent(
{F(fmt::format("<b>Room is nullptr!</b>"))});
app->inspectState->appendContent(State::END_LINE);
} else {
app->inspectState->appendContent(
{F(fmt::format("Room @ <b>{}.{} [{}x{}]</b>", cell->room->x,
cell->room->y, cell->room->width, cell->room->height))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("HALL: [<b>{}</b>]",
cell->room->type == RoomType::HALL ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("PASSAGE: [<b>{}</b>]",
cell->room->type == RoomType::PASSAGE ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Room features count: <b>{}</b>", cell->room->features.size()))});
app->inspectState->appendContent(State::END_LINE);
if (app->debug && showRooms) {
for (auto c : cell->room->cells) {
app->state->selection.push_back({{c->x, c->y}, "#811"});
}
}
if (cell->room->features.size() > 0) {
app->inspectState->appendContent({F("<b>Room Features</b>")});
app->inspectState->appendContent(State::END_LINE);
}
for (auto f : cell->room->features) {
if (f == RoomFeature::DUNGEON) {
app->inspectState->appendContent(
{F(fmt::format("DUNGEON: [<b>{}</b>]", check))});
}
if (f == RoomFeature::CAVE) {
app->inspectState->appendContent(
{F(fmt::format("CAVE: [<b>{}</b>]", check))});
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent(
{F(fmt::format("Light sources: <b>{}</b>", cell->lightSources.size()))});
if (showLightSources) {
for (auto ls : cell->lightSources) {
auto c = ls->currentCell;
app->state->selection.push_back({{c->x, c->y}, "#1f1"});
}
}
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Hero: [<b>{}</b>]", cell == app->hero->currentCell ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Hero can <b>pass</b>: [<b>{}</b>]",
cell->canPass(app->hero->traits) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
{F(fmt::format("Hero can <b>see</b>: [<b>{}</b>]",
app->hero->canSee(cell) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(
fmt::format("Distance to hero: <b>{}</b>",
sqrt(pow(cc->x - cell->x, 2) + pow(cc->y - cell->y, 2))))});
app->inspectState->appendContent(State::END_LINE);
if (cell->type == CellType::WALL)
return;
auto allEnemies = utils::castObjects<Enemy>(location->objects);
for (auto e : allEnemies) {
if (e->canSee(cell) && highlightWhoCanSee) {
app->inspectState->appendContent(
{F(fmt::format("<b>{} @ {}.{}</b> can see: [<b>{}</b>]", e->type.name,
e->currentCell->x, e->currentCell->y,
e->canSee(cell) ? check : " "))});
app->state->selection.push_back(
{{e->currentCell->x, e->currentCell->y}, "#aaaa88"});
app->inspectState->appendContent(State::END_LINE);
}
}
app->inspectState->appendContent(
{F(fmt::format("Objects count: <b>{}</b>", objects.size()))});
app->inspectState->appendContent(State::END_LINE);
if (objects.size() > 0) {
auto isDoor = utils::castObjects<Door>(objects).size() > 0;
app->inspectState->appendContent(
{F(fmt::format("Door: [<b>{}</b>]", isDoor ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
// auto isTorch = utils::castObjects<TorchStand>(objects).size() > 0;
// app->inspectState->appendContent(
// {F(fmt::format("Torch: [<b>{}</b>]", isTorch ? check : " "))});
// app->inspectState->appendContent(State::END_LINE);
// auto isStatue = utils::castObjects<Statue>(objects).size() > 0;
// app->inspectState->appendContent(
// {F(fmt::format("Statue: [<b>{}</b>]", isStatue ? check : " "))});
// app->inspectState->appendContent(State::END_LINE);
auto enemies = utils::castObjects<Enemy>(objects);
if (enemies.size() > 0) {
std::vector<std::string> enemyNames;
for (auto e : enemies) {
enemyNames.push_back(e->type.name);
app->inspectState->appendContent(
{F(fmt::format("<b>{} @ {}.{}</b> can see HERO: [<b>{}</b>]",
e->type.name, e->currentCell->x, e->currentCell->y,
e->canSee(cc) ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F(fmt::format(
"Has glow: [<b>{}</b>]", e->hasLight() ? check : " "))});
app->inspectState->appendContent(State::END_LINE);
auto glow = e->getGlow();
if (glow) {
app->inspectState->appendContent(
{F(fmt::format("Light: <b>{}</b>, stable: {}", (*glow).distance,
(*glow).stable))});
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent({F(fmt::format(
"<b>HP</b>: {:d}/{:d} ({:d})", int(e->HP(e.get())),
int(e->HP_MAX(e.get())), int(e->hp_max * e->strength)))});
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format(
"<b>MP</b>: {:d}/{:d} ({:d})", int(e->MP(e.get())),
int(e->MP_MAX(e.get())), int(e->mp_max * e->intelligence))));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format("<b>Speed</b>: {} ({})",
e->SPEED(e.get()), e->speed)));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(F(fmt::format("<b>Defence</b>: {:d}",
int(e->DEF(e.get())))));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent(
F(fmt::format("<b>Damage</b>: {}", e->getDmgDesc())));
app->inspectState->appendContent(State::END_LINE);
app->inspectState->appendContent({F("Traits:")});
app->inspectState->appendContent(State::END_LINE);
for (auto t : e->traits) {
app->inspectState->appendContent(
{F(fmt::format(" * {}", t.name))});
app->inspectState->appendContent(State::END_LINE);
}
app->inspectState->appendContent({F("Inventory:")});
app->inspectState->appendContent(State::END_LINE);
for (auto s : e->equipment->slots) {
app->inspectState->appendContent({F(fmt::format(
" * {} -- {}", s->name,
s->item != nullptr ? s->item->getTitle(true) : "empty"))});
app->inspectState->appendContent(State::END_LINE);
}
}
app->inspectState->appendContent({F(
fmt::format("Enemies: <b>{}</b>", LibLog::utils::join(enemyNames, ", ")))});
app->inspectState->appendContent(State::END_LINE);
}
auto items = utils::castObjects<Item>(objects);
if (items.size() > 0) {
std::vector<std::string> itemNames;
for (auto i : items) {
itemNames.push_back(i->getFullTitle(true));
}
app->inspectState->appendContent(
{F(fmt::format("Items: <b>{}</b>", LibLog::utils::join(itemNames, ", ")))});
app->inspectState->appendContent(State::END_LINE);
}
}
app->state->invalidateSelection("move inspect cursor");
}
| 41.6625 | 91 | 0.578533 | averrin |
8c4761fc6234aa0a84b2b3511d7fb746f566f793 | 9,649 | cpp | C++ | experiments/src/globimap_test_polygons_mask.cpp | mlaass/globimap | 6bbcbf33cc39ed343662e6b98871dc6dfbc4648f | [
"MIT"
] | null | null | null | experiments/src/globimap_test_polygons_mask.cpp | mlaass/globimap | 6bbcbf33cc39ed343662e6b98871dc6dfbc4648f | [
"MIT"
] | null | null | null | experiments/src/globimap_test_polygons_mask.cpp | mlaass/globimap | 6bbcbf33cc39ed343662e6b98871dc6dfbc4648f | [
"MIT"
] | null | null | null | #include "globimap/counting_globimap.hpp"
#include "globimap_test_config.hpp"
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <math.h>
#include <string>
#include <highfive/H5File.hpp>
#include <tqdm.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include "archive.h"
#include "loc.hpp"
#include "rasterizer.hpp"
#include "shapefile.hpp"
#include <H5Cpp.h>
namespace fs = std::filesystem;
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
namespace bgt = boost::geometry::strategy::transform;
typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;
typedef bg::model::box<point_t> box_t;
typedef bg::model::polygon<point_t> polygon_t;
typedef std::vector<polygon_t> poly_collection_t;
#ifndef TUM1_ICAML_ORG
const std::string base_path = "/mnt/G/datasets/atlas/";
const std::string vector_base_path = "/mnt/G/datasets/vector/";
const std::string experiments_path =
"/home/moritz/workspace/bgdm/globimap/experiments/";
#else
const std::string base_path = "/home/moritz/tf/pointclouds_2d/data/";
const std::string experiments_path = "/home/moritz/tf/globimap/experiments/";
const std::string vector_base_path = "/home/moritz/tf/vector/";
#endif
std::vector<std::string> datasets{"twitter_1mio_coords.h5",
"twitter_10mio_coords.h5",
"twitter_100mio_coords.h5"};
// std::vector<std::string> datasets{"twitter_200mio_coords.h5",
// "asia_200mio_coords.h5"};
std::vector<std::string> polygon_sets{"tl_2017_us_zcta510",
"Global_LSIB_Polygons_Detailed"};
template <typename T> std::string render_hist(std::vector<T> hist) {
std::stringstream ss;
ss << "[";
for (auto i = 0; i < hist.size(); ++i) {
ss << hist[i] << ((i < (hist.size() - 1)) ? ", " : "");
}
ss << "]";
return ss.str();
}
template <typename T>
std::string render_stat(const std::string &name, std::vector<T> stat) {
double stat_min = FLT_MAX;
double stat_max = 0;
double stat_mean = 0;
double stat_std = 0;
for (double v : stat) {
stat_min = std::min(stat_min, v);
stat_max = std::max(stat_max, v);
stat_mean += v;
}
stat_mean /= stat.size();
for (double v : stat) {
stat_std += pow((stat_mean - v), 2);
}
stat_std /= stat.size();
stat_std = sqrt(stat_std);
std::stringstream ss;
ss << "\"" << name << "\": {\n";
ss << "\"min\": " << stat_min << ",\n";
ss << "\"max\": " << stat_max << ",\n";
ss << "\"mean\": " << stat_mean << ",\n";
ss << "\"std\": " << stat_std << ",\n";
ss << "\"hist\": " << render_hist(globimap::make_histogram(stat, 1000))
<< "\n";
ss << "}";
return ss.str();
}
std::string
test_polys_mask(globimap::CountingGloBiMap<> &g, size_t poly_size,
std::function<std::vector<uint64_t>(size_t)> poly_gen) {
std::vector<uint32_t> errors_mask;
std::vector<uint32_t> errors_hash;
std::vector<uint32_t> diff_mask_hash;
std::vector<uint32_t> sizes;
std::vector<uint32_t> sums_mask;
std::vector<uint32_t> sums_hash;
std::vector<uint32_t> sums;
std::vector<double> errors_mask_pc;
std::vector<double> errors_hash_pc;
int n = 0;
std::cout << "polygons: " << poly_size << " ..." << std::endl;
auto P = tq::trange(poly_size);
P.set_prefix("mask for polygons ");
for (const auto &idx : P) {
auto raster = poly_gen(idx);
if (raster.size() > 0) {
auto hsfn = g.to_hashfn(raster);
auto mask_conf = globimap::FilterConfig{
g.config.hash_k, {{1, g.config.layers[0].logsize}}};
auto mask = globimap::CountingGloBiMap(mask_conf, false);
mask.put_all(raster);
auto res_raster = g.get_sum_raster_collected(raster);
auto res_mask = g.get_sum_masked(mask);
auto res_hashfn = g.get_sum_hashfn(raster);
sums.push_back(res_raster);
sums_mask.push_back(res_mask);
sums_hash.push_back(res_hashfn);
uint64_t err_mask = std::abs((int64_t)res_mask - (int64_t)res_raster);
uint64_t err_hash = std::abs((int64_t)res_hashfn - (int64_t)res_raster);
uint64_t hash_mask_diff =
std::abs((int64_t)res_mask - (int64_t)res_hashfn);
errors_mask.push_back(err_mask);
errors_hash.push_back(err_hash);
double div = (double)res_raster;
double err_mask_pc = ((double)err_mask) / div;
double err_hash_pc = ((double)err_hash) / div;
if (div == 0) {
err_mask_pc = (err_mask > 0 ? 1 : 0);
err_hash_pc = (err_hash > 0 ? 1 : 0);
}
errors_mask_pc.push_back(err_mask_pc);
errors_hash_pc.push_back(err_hash_pc);
sizes.push_back(raster.size() / 2);
n++;
}
}
std::stringstream ss;
ss << "{\n";
ss << "\"summary\": " << g.summary() << ",\n";
ss << "\"polygons\": " << n << ",\n";
ss << render_stat("errors_mask_pc", errors_mask_pc) << ",\n";
ss << render_stat("errors_hash_pc", errors_hash_pc) << ",\n";
ss << render_stat("errors_mask", errors_mask) << ",\n";
ss << render_stat("errors_hash", errors_hash) << ",\n";
ss << render_stat("sums", sums) << ",\n";
ss << render_stat("sums_mask", sums_mask) << ",\n";
ss << render_stat("sums_hash", sums_hash) << ",\n";
ss << render_stat("sizes", sizes) << "\n";
ss << "\n}" << std::endl;
// std::cout << ss.str();
return ss.str();
}
static void encode_dataset(globimap::CountingGloBiMap<> &g,
const std::string &name, const std::string &ds,
uint width, uint height) {
auto filename = base_path + ds;
auto batch_size = 4096;
std::cout << "Encode \"" << filename << "\" \nwith cfg: " << name
<< std::endl;
using namespace HighFive;
// we create a new hdf5 file
auto file = File(filename, File::ReadWrite);
std::vector<std::vector<double>> read_data;
// we get the dataset
DataSet dataset = file.getDataSet("coords");
using std::chrono::duration;
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
auto t1 = high_resolution_clock::now();
std::vector<std::vector<double>> result;
auto shape = dataset.getDimensions();
int batches = std::floor(shape[0] / batch_size);
auto R = tq::trange(batches);
R.set_prefix("encoding batches ");
for (auto i : R) {
dataset.select({i * batch_size, 0}, {batch_size, 2}).read(result);
for (auto p : result) {
double x = (double)width * (((double)p[0] + 180.0) / 360.0);
double y = (double)height * (((double)p[0] + 90.0) / 180.0);
g.put({(uint64_t)x, (uint64_t)y});
}
}
auto t2 = high_resolution_clock::now();
duration<double, std::milli> insert_time = t2 - t1;
}
int main() {
std::vector<std::vector<globimap::LayerConfig>> cfgs;
get_configurations(cfgs, {16, 20, 24}, {8, 16, 32});
{
uint k = 8;
auto x = 0;
uint width = 2 * 8192, height = 2 * 8192;
std::string exp_name = "test_polygons_mask1";
save_configs(experiments_path + std::string("config_") + exp_name, cfgs);
mkdir((experiments_path + exp_name).c_str(), 0777);
for (auto c : cfgs) {
globimap::FilterConfig fc{k, c};
std::cout << "\n******************************************"
<< "\n******************************************" << std::endl;
std::cout << x << " / " << cfgs.size() << " fc: " << fc.to_string()
<< std::endl;
auto y = 0;
for (auto shp : polygon_sets) {
std::stringstream ss1;
ss1 << shp << "-" << width << "x" << height;
auto polyset_name = ss1.str();
std::stringstream ss;
ss << vector_base_path << polyset_name;
auto poly_path = ss.str();
int poly_count = 0;
for (auto e : fs::directory_iterator(poly_path))
poly_count += (e.is_regular_file() ? 1 : 0);
for (auto ds : datasets) {
std::stringstream fss;
fss << experiments_path << exp_name << "/" << exp_name << ".w"
<< width << "h" << height << "." << fc.to_string() << ds << "."
<< polyset_name << ".json";
if (file_exists(fss.str())) {
std::cout << "file already exists: " << fss.str() << std::endl;
} else {
std::cout << "run: " << fss.str() << std::endl;
std::ofstream out(fss.str());
auto g = globimap::CountingGloBiMap(fc, true);
encode_dataset(g, fc.to_string(), ds, width, height);
// g.detect_errors(0, 0, width, height);
std::cout << " COUNTER SIZE: " << g.counter.size() << std::endl;
std::cout << "test: " << polyset_name << std::endl;
out << test_polys_mask(g, poly_count, [&](int idx) {
std::vector<uint64_t> raster;
std::stringstream ss;
ss << poly_path << "/" << std::setw(8) << std::setfill('0')
<< idx;
auto filename = ss.str();
std::ifstream ifile(filename, std::ios::binary);
if (!ifile.is_open()) {
std::cout << "ERROR file doesn't exist: " << filename
<< std::endl;
return raster;
}
Archive<std::ifstream> a(ifile);
a >> raster;
ifile.close();
return raster;
});
out.close();
std::cout << "\n" << std::endl;
}
}
y++;
}
x++;
}
}
};
| 33.272414 | 79 | 0.5755 | mlaass |
8c4ae2f09ee13bd0829af2f0432da5c2187d79cf | 267 | hpp | C++ | include/boomhs/game_config.hpp | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 2 | 2016-07-22T10:09:21.000Z | 2017-09-16T06:50:01.000Z | include/boomhs/game_config.hpp | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | 14 | 2016-08-13T22:45:56.000Z | 2018-12-16T03:56:36.000Z | include/boomhs/game_config.hpp | bjadamson/BoomHS | 60b5d8ddc2490ec57e8f530ba7ce3135221e2ec4 | [
"MIT"
] | null | null | null | #pragma once
namespace boomhs
{
enum class GameGraphicsMode
{
Basic = 0,
Medium,
Advanced
};
struct GameGraphicsSettings
{
GameGraphicsMode mode = GameGraphicsMode::Basic;
bool disable_sunshafts = true;
};
} // namespace boomhs
| 13.35 | 63 | 0.662921 | bjadamson |
8c5328e5fdeb3c8b024ba1539ad80c1d7ae43227 | 1,256 | cpp | C++ | day16/part1.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | day16/part1.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | day16/part1.cpp | Moremar/advent_of_code_2016 | dea264671fc2c31baa42b1282751dfd1ae071a7d | [
"Apache-2.0"
] | null | null | null | #include "part1.hpp"
using namespace std;
vector<char> Part1::parse(const string &fileName) {
const string line = getFileLines(fileName)[0];
return { line.begin(), line.end() };
}
vector<char> checksum(const vector<char> &input, size_t targetSize) {
vector<char> res;
res.reserve(targetSize / 2);
for (size_t i = 0; i < targetSize/2; ++i) {
res.push_back(input.at(2 * i) == input.at(2 * i + 1) ? '1' : '0');
}
return (res.size() % 2 == 0) ? checksum(res, res.size()) : res;
}
string Part1::solveForDiscSpace(const vector<char> &initialKey, size_t discSpace) {
auto curr = initialKey;
// get a long enough data sequence by dragon curve
while (curr.size() < discSpace) {
vector<char> next;
next.reserve(curr.size() * 2 + 1);
copy(curr.begin(), curr.end(), back_inserter(next));
next.push_back('0');
transform(curr.rbegin(), curr.rend(), back_inserter(next), [](const char &c) {
return c == '0' ? '1' : '0';
});
curr = next;
}
const auto check = checksum(curr, discSpace);
return string(check.begin(), check.end());
}
string Part1::solve(const vector<char> &initialKey) {
return solveForDiscSpace(initialKey, 272);
}
| 28.545455 | 86 | 0.602707 | Moremar |
8c57260b688499deeb446882123cfda02314f283 | 2,941 | cpp | C++ | source/app/gui.cpp | emiyl/dumpling | 48d76f5a4c035585683e1b414df2b66d5bb12e15 | [
"MIT"
] | 53 | 2020-04-11T15:49:21.000Z | 2022-03-20T03:47:33.000Z | source/app/gui.cpp | emiyl/dumpling | 48d76f5a4c035585683e1b414df2b66d5bb12e15 | [
"MIT"
] | 22 | 2020-08-14T19:45:13.000Z | 2022-03-30T00:49:27.000Z | source/app/gui.cpp | emiyl/dumpling | 48d76f5a4c035585683e1b414df2b66d5bb12e15 | [
"MIT"
] | 11 | 2020-04-19T09:19:08.000Z | 2022-03-21T20:16:54.000Z | #include "gui.h"
#define NUM_LINES (16)
#define LINE_LENGTH (128)
#define MEMORY_HEAP_TAG (0x0002B2B2)
static char textBuffer[NUM_LINES][LINE_LENGTH];
static uint32_t currLineNumber = 0;
static uint8_t* frameBufferTVFrontPtr = nullptr;
static uint8_t* frameBufferTVBackPtr = nullptr;
static uint32_t frameBufferTVSize = 0;
static uint8_t* frameBufferDRCFrontPtr = nullptr;
static uint8_t* frameBufferDRCBackPtr = nullptr;
static uint32_t frameBufferDRCSize = 0;
static uint32_t* currTVFrameBuffer = nullptr;
static uint32_t* currDRCFrameBuffer = nullptr;
static uint32_t backgroundColor = 0x0b5d5e00;
bool initializeGUI() {
// Prepare rendering and framebuffers
OSScreenInit();
frameBufferTVSize = OSScreenGetBufferSizeEx(SCREEN_TV);
frameBufferDRCSize = OSScreenGetBufferSizeEx(SCREEN_DRC);
OSScreenEnableEx(SCREEN_TV, TRUE);
OSScreenEnableEx(SCREEN_DRC, TRUE);
MEMHeapHandle framebufferHeap = MEMGetBaseHeapHandle(MEM_BASE_HEAP_MEM1);
frameBufferTVFrontPtr = (uint8_t*)MEMAllocFromFrmHeapEx(framebufferHeap, frameBufferTVSize, 100);
frameBufferDRCFrontPtr = (uint8_t*)MEMAllocFromFrmHeapEx(framebufferHeap, frameBufferDRCSize, 100);
frameBufferTVBackPtr = frameBufferTVFrontPtr+(1280*720*4);
frameBufferDRCBackPtr = frameBufferDRCFrontPtr+(896*480*4);
currTVFrameBuffer = (uint32_t*)frameBufferTVFrontPtr;
currDRCFrameBuffer = (uint32_t*)frameBufferDRCFrontPtr;
OSScreenSetBufferEx(SCREEN_TV, currTVFrameBuffer);
OSScreenSetBufferEx(SCREEN_DRC, currDRCFrameBuffer);
WHBAddLogHandler(printLine);
return true;
}
void shutdownGUI() {
OSScreenShutdown();
MEMHeapHandle framebufferHeap = MEMGetBaseHeapHandle(MEM_BASE_HEAP_MEM1);
MEMFreeByStateToFrmHeap(framebufferHeap, MEMORY_HEAP_TAG);
}
void WHBLogConsoleDraw() {
OSScreenClearBufferEx(SCREEN_TV, backgroundColor);
OSScreenClearBufferEx(SCREEN_DRC, backgroundColor);
for (int32_t i=0; i<NUM_LINES; i++) {
OSScreenPutFontEx(SCREEN_TV, 0, i, textBuffer[i]);
OSScreenPutFontEx(SCREEN_DRC, 0, i, textBuffer[i]);
}
DCFlushRange(currTVFrameBuffer, frameBufferTVSize);
DCFlushRange(currTVFrameBuffer, frameBufferDRCSize);
OSScreenFlipBuffersEx(SCREEN_TV);
OSScreenFlipBuffersEx(SCREEN_DRC);
}
void printLine(const char* message) {
int32_t length = strlen(message);
if (length > LINE_LENGTH) {
length = LINE_LENGTH - 1;
}
if (currLineNumber == NUM_LINES) {
for (int i=0; i<NUM_LINES-1; i++) {
memcpy(textBuffer[i], textBuffer[i + 1], LINE_LENGTH);
}
memcpy(textBuffer[currLineNumber - 1], message, length);
textBuffer[currLineNumber - 1][length] = 0;
}
else {
memcpy(textBuffer[currLineNumber], message, length);
textBuffer[currLineNumber][length] = 0;
currLineNumber++;
}
}
void setBackgroundColor(uint32_t color) {
backgroundColor = color;
} | 32.318681 | 103 | 0.743285 | emiyl |
8c57cdf94eb7b2e42d37e44f18e63a7b93c55d6b | 146 | cpp | C++ | C03_ClassStructure/Main.cpp | Nolukdi/IGME309-2201 | 988d8bcae34613e5d88cb2cc92dafe0c1e8ff05a | [
"MIT"
] | 2 | 2020-08-20T14:54:45.000Z | 2020-09-13T17:37:34.000Z | C03_ClassStructure/Main.cpp | Nolukdi/IGME309-2201 | 988d8bcae34613e5d88cb2cc92dafe0c1e8ff05a | [
"MIT"
] | null | null | null | C03_ClassStructure/Main.cpp | Nolukdi/IGME309-2201 | 988d8bcae34613e5d88cb2cc92dafe0c1e8ff05a | [
"MIT"
] | 26 | 2020-08-20T17:39:34.000Z | 2021-02-27T16:27:06.000Z | #include "Main.h"
int main(void)
{
AppClass* pApp = new AppClass();
pApp->Run();
if (pApp)
{
delete pApp;
pApp = nullptr;
}
return 0;
} | 11.230769 | 33 | 0.59589 | Nolukdi |
8c58bcb88b8c8533858b93b5b5226d86efd5d4b7 | 11,114 | cpp | C++ | Lecture9/visualizer/theCamera.cpp | Zenologos/IDS6938-SimulationTechniques | b3630852b2edb3ec4e176b26f0de56b77b460a2a | [
"Apache-2.0"
] | null | null | null | Lecture9/visualizer/theCamera.cpp | Zenologos/IDS6938-SimulationTechniques | b3630852b2edb3ec4e176b26f0de56b77b460a2a | [
"Apache-2.0"
] | null | null | null | Lecture9/visualizer/theCamera.cpp | Zenologos/IDS6938-SimulationTechniques | b3630852b2edb3ec4e176b26f0de56b77b460a2a | [
"Apache-2.0"
] | null | null | null | #include "theCamera.h"
/** @brief Constructs a camera
*
* Constructs a camera object by setting the position, look at position, up vector.
* Puts together a model matrix, and projection matrix.
*
* @param width - float - width of window
* @param height - float - height of window
* @return void.
*/
Visualizer::theCamera::theCamera()
{
mIdenityMatrix = glm::mat4(1.0f);
mOrthoProjection = mIdenityMatrix * glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f);
}
void Visualizer::theCamera::settheCamera(float width, float height)
{
screenWidth = width;
screenHeight = height;
setCameraPosition(40.0f, 40.0f, 40.0f);
setLookAtPosition(0.0f, 0.0f, 0.0f);
setupVector(0.0f, 0.0f, 1.0f);
//setModelMatrix(glm::vec3(1.0f, 0.0f, 0.0f), 0.0f, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f));
mModelMatrix = glm::mat4(1.0f);
mProjectionMatrix = glm::mat4(1.0f);
//setProjectionMatrix(45.0f, width / height, 0.1f, 100000.0f);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
setName("myCamera");
realdiv = float(width + height);
roty = 0.0f;
rotx = 0.0f;
}
/** @brief Deconstructor a camera
*
* This function deconstructs the camera object
*/
Visualizer::theCamera::~theCamera(void)
{
}
/** @brief Translates the camera
*
* This function translates the camera in space.
*
* @param diffx - float - change in x
* @param diffy - float - change in y
* @return void.
*/
void Visualizer::theCamera::translate(float diffx, float diffy)
{
glm::vec3 c = getCameraPosition() - getLookAtPosition();
float change = sqrt(c.x*c.x + c.y*c.y + c.z*c.z);
//get the the view vector and then the right vector
glm::vec3 cameraW = glm::normalize(getLookAtPosition() - getCameraPosition());
glm::vec3 cameraU = glm::normalize(glm::cross(getupVector(), cameraW));
//TODO: need to add - Translate based on the magnitude
float magnitude = sqrt((cameraU.x*cameraU.x) + (cameraU.y*cameraU.y) + (cameraU.z*cameraU.z));
//x_changep/=magnitude;
//y_changep/=magnitude;
//z_changep/=magnitude;
//Do the actual translation lookatPosition
glm::vec3 changel = getLookAtPosition() + getupVector() * (35.5f*diffy / screenWidth);
changel += cameraU * (16.0f*diffx / screenHeight);
//Do the actual translation cameraPosition
glm::vec3 changec = getCameraPosition() + getupVector() * (35.5f*diffy / screenWidth);
changec += cameraU * (16.0f*diffx / screenHeight);
//set the camera
setCameraPosition(changec.x, changec.y, changec.z);
setLookAtPosition(changel.x, changel.y, changel.z);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
}
/** @brief Rotates the camera
*
* This function rotates the camera in space.
*
* @param diffx - float - change in x
* @param diffy - float - change in y
* @return void.
*/
void Visualizer::theCamera::rotate(float diffx, float diffy)
{
roty = -(float) 0.025f * diffx;
rotx = -(float) 0.025f * diffy;
float phi = (rotx);
float theta = (roty);
//get the view vector and the right vector
glm::vec3 cameraW = glm::normalize(getLookAtPosition() - getCameraPosition());
glm::vec3 cameraU = glm::normalize(glm::cross(cameraW, getupVector()));
//Get the quaterion rotate about the x and y axis: but fix the up axis to be constant
glm::quat myQuat = glm::normalize(glm::angleAxis(theta, glm::vec3(0.0f, 0.0f, 1.0f)) * glm::angleAxis(phi, glm::vec3(cameraU.x, cameraU.y, cameraU.z)));
glm::mat4 rotmat = glm::toMat4(myQuat); //make a rotation matrix
//Get the Camera position and vector to be rotated
//(remember to translate back, rotate, then translate)
glm::vec4 myPoint(getCameraPosition().x - getLookAtPosition().x, getCameraPosition().y - getLookAtPosition().y, getCameraPosition().z - getLookAtPosition().z, 1.0f);
glm::vec4 myVector(getupVector().x, getupVector().y, getupVector().z, 0.0f);
//Do the rotation
glm::vec4 newPosition = rotmat * myPoint;
glm::vec4 newUpVector = rotmat * myVector;
//glm::vec4 newUpVector = myQuat * myVector* glm::conjugate(myQuat); //not sure why this did not work
newUpVector = glm::normalize(newUpVector);
//translate back
newPosition.x += getLookAtPosition().x;
newPosition.y += getLookAtPosition().y;
newPosition.z += getLookAtPosition().z;
//set the camera
setCameraPosition(newPosition.x, newPosition.y, newPosition.z);
setupVector(newUpVector.x, newUpVector.y, newUpVector.z);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
}
/** @brief Zooms the camera
*
* This function zooms the camera in space.
*
* @param realdiff- float - total diff moved in both directions
* @return void.
*/
void Visualizer::theCamera::zoom(float realdiff)
{
//find the view vector, and move the camera on it
glm::vec3 change = getCameraPosition() - getLookAtPosition();
glm::vec3 change2 = getLookAtPosition() + change * (1 + 9.0f*realdiff / realdiv);
//set the camera
setCameraPosition(change2.x, change2.y, change2.z);
setViewMatrix(getCameraPosition(), getLookAtPosition(), getupVector());
}
/** @brief Update the MVP Matrix
*
* This function updates the MVP matrix : P * V * M
*
* @return glm::mat4 - MVP matrix.
*/
glm::mat4 Visualizer::theCamera::updateMVP()
{
return mProjectionMatrix * (mViewMatrix * mModelMatrix);
}
/** @brief Update the MV Matrix -Ortho
*
* This function updates the MV Ortho matrix : V * M
*
* @return glm::mat4 - MV matrix.
*/
glm::mat4 Visualizer::theCamera::updateMVP_ORTHO()
{
return mOrthoProjection;
}
/** @brief Gets the camera position
*
* This function returns the camera position in 3D space.
*
* @return glm::vec3 - camera position.
*/
glm::vec3 Visualizer::theCamera::getCameraPosition()
{
return mCameraPosition;
}
/** @brief Gets the look at position
*
* This function returns the camera look at position in 3D space.
*
* @return glm::vec3 - look at position.
*/
glm::vec3 Visualizer::theCamera::getLookAtPosition()
{
return mLookAtPosition;
}
/** @brief Gets the camera up vector
*
* This function returns the camera up vector.
*
* @return glm::vec3 - camera up vector.
*/
glm::vec3 Visualizer::theCamera::getupVector()
{
return mCameraUpVector;
}
/** @brief Sets the camera position
*
* This function sets the camera position in 3D space.
*
* @param x - float- x position
* @param y - float- y position
* @param z - float- z position
* @return void.
*/
void Visualizer::theCamera::setCameraPosition(float x, float y, float z)
{
mCameraPosition.x = x;
mCameraPosition.y = y;
mCameraPosition.z = z;
}
/** @brief Sets the look at position
*
* This function sets the camera looks at position in 3D space.
*
* @param x - float- x position
* @param y - float- y position
* @param z - float- z position
* @return void.
*/
void Visualizer::theCamera::setLookAtPosition(float x, float y, float z)
{
mLookAtPosition.x = x;
mLookAtPosition.y = y;
mLookAtPosition.z = z;
}
/** @brief Sets the camera up vectir
*
* This function sets the camera up vector.
*
* @param x - float- x direction
* @param y - float- y direction
* @param z - float- z direction
* @return void.
*/
void Visualizer::theCamera::setupVector(float x, float y, float z)
{
mCameraUpVector.x = x;
mCameraUpVector.y = y;
mCameraUpVector.z = z;
}
/** @brief Returns Projection Matrix
*
* This function returns the camera Projection Matrix.
*
* @return glm::mat4 - camera projection matrix.
*/
glm::mat4 Visualizer::theCamera::getProjectionMatrix()
{
return mProjectionMatrix;
}
/** @brief Returns View Matrix
*
* This function returns the camera View Matrix.
*
* @return glm::mat4 - camera view matrix.
*/
glm::mat4 Visualizer::theCamera::getViewMatrix()
{
return mViewMatrix;
}
/** @brief Returns Model Matrix
*
* This function returns the camera Model Matrix.
*
* @return glm::mat4 - camera model matrix.
*/
glm::mat4 Visualizer::theCamera::getModelMatrix()
{
return mModelMatrix;
}
/** @brief Process mouse event.
*
* This function processes mouse events.
*
* @return void.
*/
void Visualizer::theCamera::process_mouse_event()
{
}
/** @brief Returns the camera name
*
* This function returns the camera name.
*
* @return std::string - camera name.
*/
std::string Visualizer::theCamera::getName()
{
return mName;
}
/** @brief Sets teh camera name
*
* This function sets the camera name.
*
* @param - name - std::string - camera name
* @return void.
*/
void Visualizer::theCamera::setName(std::string name)
{
mName = name;
}
/** @brief Sets the Model Matrix
*
* This function sets the Model Matrix.
*
* @param rotate - glm::vec3 - rotate
* @param rotateaxis - float - axis to rotate
* @aram translate - glm::vec3 - translate
* @param scale - glm::vec3 - scale
* @return void.
*/
void Visualizer::theCamera::setModelMatrix(glm::vec3 rotate, float rotateaxis, glm::vec3 translate, glm::vec3 scale)
{
mModelMatrix = glm::mat4(1.0f);
mModelMatrix = glm::rotate(mModelMatrix, rotateaxis, rotate);
mModelMatrix = glm::translate(mModelMatrix, translate);
mModelMatrix = glm::scale(mModelMatrix, scale);
}
/** @brief Sets the projection matrix
*
* This function sets the projection matrix for a projective transform.
*
* @param fovy - float - field of view y
* @param aspect - float - aspect ration
* @param zNear - float - zNear plane
* @param zFar - float - zFar plane
* @return void.
*/
void Visualizer::theCamera::setProjectionMatrix(float fovy, float aspect, float zNear, float zFar)
{
mProjectionMatrix = glm::mat4(1.0f);
mProjectionMatrix *= glm::perspective(fovy, aspect, zNear, zFar);
}
/** @brief Sets the projection matrix for orthographic mode
*
* This function sets the projection matrix for a orthographic transform.
*
* @param left - float - left position
* @param right - float - right position
* @param bottom - float - bottom position
* @param top - float - top position
* @param zNear - float - zNear plane
* @param zFar - float - zFar plane
* @return void.
*/
void Visualizer::theCamera::setProjectionMatrix(float left, float right, float bottom, float top, float zNear, float zFar)
{
mProjectionMatrix = glm::mat4(1.0f);
mProjectionMatrix *= glm::ortho(left, right, bottom, top, zNear, zFar);
}
/** @brief Sets the view matrix
*
* This function sets the view matrix for the camera
*
* @param position - glm::vec3 - camera position
* @param lookat - glm::vec3 - look at position
* @param up - glm::vec3 - up vector
* @return void.
*/
void Visualizer::theCamera::setViewMatrix(glm::vec3 &position, glm::vec3 &lookat, glm::vec3 &up)
{
mViewMatrix = glm::mat4(1.0f);
mViewMatrix *= glm::lookAt(
position, // The eye's position in 3d space
lookat, // What the eye is looking at
up); // The eye's orientation vector (which way is up)
}
void Visualizer::theCamera::setViewMatrixY(glm::vec3 &position, glm::vec3 &lookat, glm::vec3 &up)
{
mViewMatrix = glm::mat4(1.0f);
mViewMatrix *= glm::lookAt(
position, // The eye's position in 3d space
lookat, // What the eye is looking at
up); // The eye's orientation vector (which way is up)
mViewMatrix[1][0] *= -1.0f;
mViewMatrix[1][1] *= -1.0f;
mViewMatrix[1][2] *= -1.0f;
mViewMatrix[1][3] *= -1.0f;
} | 26.089202 | 166 | 0.699028 | Zenologos |
8c5946d276ae225928ba41370ad04228e7d08352 | 2,506 | cc | C++ | src/structured-interface/detail/debug.cc | project-arcana/structured-interface | 56054310e08a3ae98f8065a90b454e23a36d60d9 | [
"MIT"
] | 1 | 2020-12-09T13:55:07.000Z | 2020-12-09T13:55:07.000Z | src/structured-interface/detail/debug.cc | project-arcana/structured-interface | 56054310e08a3ae98f8065a90b454e23a36d60d9 | [
"MIT"
] | 1 | 2019-09-29T09:02:03.000Z | 2019-09-29T09:02:03.000Z | src/structured-interface/detail/debug.cc | project-arcana/structured-interface | 56054310e08a3ae98f8065a90b454e23a36d60d9 | [
"MIT"
] | null | null | null | #include "debug.hh"
#include <iomanip>
#include <iostream>
#include <clean-core/string.hh>
#include <structured-interface/element_tree.hh>
#include <structured-interface/properties.hh>
#include <structured-interface/recorded_ui.hh>
namespace
{
void print_property(cc::string_view prefix, size_t prop_id, cc::span<std::byte const> value)
{
auto name = si::detail::get_property_name_from_id(prop_id);
auto type = si::detail::get_property_type_from_id(prop_id);
std::cout << cc::string(prefix).c_str() << "- " << std::string_view(name.data(), name.size()) << ": ";
if (type == cc::type_id<cc::string_view>())
{
std::cout << "\"";
std::cout << std::string_view(reinterpret_cast<char const*>(value.data()), value.size());
std::cout << "\"";
}
else
{
std::cout << std::hex;
for (auto v : value)
std::cout << " " << std::setw(2) << std::setfill('0') << unsigned(v);
std::cout << std::dec;
}
std::cout << std::endl;
}
}
void si::debug::print(recorded_ui const& r)
{
struct printer
{
int indent = 0;
cc::vector<size_t> id_stack;
std::string indent_str() const { return std::string(indent * 2, ' '); }
void start_element(size_t id, element_type type)
{
std::cout << indent_str() << "[" << cc::string(to_string(type)).c_str() << "] id: " << id << std::endl;
++indent;
id_stack.push_back(id);
}
void property(size_t prop_id, cc::span<std::byte const> value) { print_property(indent_str(), prop_id, value); }
void end_element()
{
--indent;
id_stack.pop_back();
}
};
r.visit(printer{});
}
namespace
{
void debug_print(cc::string prefix, si::element_tree const& t, si::element_tree::element const& e)
{
std::cout << prefix.c_str() << "[" << cc::string(to_string(e.type)).c_str() << "] id: " << e.id.id() << " (" << e.children_count << " c, "
<< e.properties_count << " p)" << std::endl;
auto cprefix = prefix + " ";
// TODO: properly print all properties
// for (auto const& p : t.packed_properties_of(e))
// print_property(cprefix, p.id.id(), p.value);
for (auto const& c : t.children_of(e))
debug_print(cprefix, t, c);
}
}
void si::debug::print(const si::element_tree& t)
{
std::cout << t.roots().size() << " roots" << std::endl;
for (auto const& e : t.roots())
debug_print(" ", t, e);
}
| 31.325 | 142 | 0.570231 | project-arcana |
8c5f17b009c88df2381cc99e3110295474d7802e | 1,699 | cpp | C++ | src/graph/src/FlowEdge.cpp | karz0n/algorithms | b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8 | [
"MIT"
] | 1 | 2020-04-18T14:34:16.000Z | 2020-04-18T14:34:16.000Z | src/graph/src/FlowEdge.cpp | karz0n/algorithms | b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8 | [
"MIT"
] | null | null | null | src/graph/src/FlowEdge.cpp | karz0n/algorithms | b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8 | [
"MIT"
] | null | null | null | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT WARRANTY OF ANY KIND; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MIT License for more details.
*/
/**
* @file FlowEdge.cpp
*
* @brief Flow edge graph data type implementation
*
* @author Denys Asauliak
* Contact: [email protected]
*/
#include "FlowEdge.hpp"
#include <stdexcept>
namespace algorithms {
FlowEdge::FlowEdge(std::size_t v, std::size_t w, double capacity)
: _v{v}
, _w{w}
, _capacity{capacity}
, _flow{0.0}
{
}
std::size_t
FlowEdge::from() const
{
return _v;
}
std::size_t
FlowEdge::to() const
{
return _w;
}
std::size_t
FlowEdge::other(std::size_t v) const
{
if (v == _v) {
return _w;
}
if (v == _w) {
return _v;
}
throw std::logic_error{"Invalid input argument"};
}
double
FlowEdge::capacity() const
{
return _capacity;
}
double
FlowEdge::flow() const
{
return _flow;
}
double
FlowEdge::residualCapacityTo(std::size_t v) const
{
if (v == _w) { // Forward edge
return _capacity - _flow;
}
if (v == _v) { // Backward edge
return _flow;
}
throw std::logic_error{"Invalid input argument"};
}
void
FlowEdge::addResidualFlowTo(std::size_t v, double delta)
{
if (v == _w) { // Forward Edge
_flow += delta;
return;
}
if (v == _v) { // Backward edge
_flow -= delta;
return;
}
throw std::logic_error{"Invalid input argument"};
}
} // namespace algorithms
| 17.515464 | 73 | 0.626839 | karz0n |
8c5fb83452c076d7e7240ae989fb6e1cc6e3ee1c | 6,783 | cpp | C++ | NoFTL_v1.0/shoreMT-KIT/src/workload/ssb/qpipe/qpipe_qsupplier.cpp | DBlabRT/NoFTL | cba8b5a6d9c422bdd39b01575244e557cbd12e43 | [
"Unlicense"
] | 4 | 2019-01-24T02:00:23.000Z | 2021-03-17T11:56:59.000Z | NoFTL_v1.0/shoreMT-KIT/src/workload/ssb/qpipe/qpipe_qsupplier.cpp | DBlabRT/NoFTL | cba8b5a6d9c422bdd39b01575244e557cbd12e43 | [
"Unlicense"
] | null | null | null | NoFTL_v1.0/shoreMT-KIT/src/workload/ssb/qpipe/qpipe_qsupplier.cpp | DBlabRT/NoFTL | cba8b5a6d9c422bdd39b01575244e557cbd12e43 | [
"Unlicense"
] | 4 | 2019-01-22T10:35:55.000Z | 2021-03-17T11:57:23.000Z | /* -*- mode:C++; c-basic-offset:4 -*-
Shore-kits -- Benchmark implementations for Shore-MT
Copyright (c) 2007-2009
Data Intensive Applications and Systems Labaratory (DIAS)
Ecole Polytechnique Federale de Lausanne
All Rights Reserved.
Permission to use, copy, modify and distribute this software and
its documentation is hereby granted, provided that both the
copyright notice and this permission notice appear in all copies of
the software, derivative works or modified versions, and any
portions thereof, and that both notices appear in supporting
documentation.
This code 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. THE AUTHORS
DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER
RESULTING FROM THE USE OF THIS SOFTWARE.
*/
/** @file: qpipe_qsupplier.cpp
*
* @brief: Implementation of simple QPIPE SSB tablescans over Shore-MT
*
* @author: Manos Athanassoulis
* @date: July 2010
*/
#include "workload/ssb/shore_ssb_env.h"
#include "qpipe.h"
using namespace shore;
using namespace qpipe;
ENTER_NAMESPACE(ssb);
/********************************************************************
*
* QPIPE qsupplier - Structures needed by operators
*
********************************************************************/
// the tuples after tablescan projection
typedef struct ssb_supplier_tuple projected_tuple;
struct count_tuple
{
int COUNT;
};
class supplier_tscan_filter_t : public tuple_filter_t
{
private:
ShoreSSBEnv* _ssbdb;
table_row_t* _prsupp;
rep_row_t _rr;
ssb_supplier_tuple _supplier;
public:
supplier_tscan_filter_t(ShoreSSBEnv* ssbdb, qsupplier_input_t &in)
: tuple_filter_t(ssbdb->supplier_desc()->maxsize()), _ssbdb(ssbdb)
{
// Get a supplier tupple from the tuple cache and allocate space
_prsupp = _ssbdb->supplier_man()->get_tuple();
_rr.set_ts(_ssbdb->supplier_man()->ts(),
_ssbdb->supplier_desc()->maxsize());
_prsupp->_rep = &_rr;
}
~supplier_tscan_filter_t()
{
// Give back the supplier tuple
_ssbdb->supplier_man()->give_tuple(_prsupp);
}
// Predication
bool select(const tuple_t &input) {
// Get next supplier and read its shipdate
if (!_ssbdb->supplier_man()->load(_prsupp, input.data)) {
assert(false); // RC(se_WRONG_DISK_DATA)
}
return (true);
}
// Projection
void project(tuple_t &d, const tuple_t &s) {
projected_tuple *dest;
dest = aligned_cast<projected_tuple>(d.data);
_prsupp->get_value(0, _supplier.S_SUPPKEY);
_prsupp->get_value(1, _supplier.S_NAME,25);
TRACE( TRACE_RECORD_FLOW, "%d|%s --d\n",
_supplier.S_SUPPKEY,
_supplier.S_NAME);
dest->S_SUPPKEY = _supplier.S_SUPPKEY;
strcpy(dest->S_NAME,_supplier.S_NAME);
}
supplier_tscan_filter_t* clone() const {
return new supplier_tscan_filter_t(*this);
}
c_str to_string() const {
return c_str("supplier_tscan_filter_t()");
}
};
struct count_aggregate_t : public tuple_aggregate_t {
default_key_extractor_t _extractor;
count_aggregate_t()
: tuple_aggregate_t(sizeof(projected_tuple))
{
}
virtual key_extractor_t* key_extractor() { return &_extractor; }
virtual void aggregate(char* agg_data, const tuple_t &) {
count_tuple* agg = aligned_cast<count_tuple>(agg_data);
agg->COUNT++;
}
virtual void finish(tuple_t &d, const char* agg_data) {
memcpy(d.data, agg_data, tuple_size());
}
virtual count_aggregate_t* clone() const {
return new count_aggregate_t(*this);
}
virtual c_str to_string() const {
return "count_aggregate_t";
}
};
class ssb_qsupplier_process_tuple_t : public process_tuple_t
{
public:
void begin() {
TRACE(TRACE_QUERY_RESULTS, "*** qsupplier ANSWER ...\n");
TRACE(TRACE_QUERY_RESULTS, "*** SUM_QTY\tSUM_BASE\tSUM_DISC...\n");
}
virtual void process(const tuple_t& output) {
projected_tuple *tuple;
tuple = aligned_cast<projected_tuple>(output.data);
TRACE( TRACE_QUERY_RESULTS, "%d|%s --d\n",
tuple->S_SUPPKEY,
tuple->S_NAME);
}
};
/********************************************************************
*
* QPIPE qsupplier - Packet creation and submission
*
********************************************************************/
w_rc_t ShoreSSBEnv::xct_qpipe_qsupplier(const int xct_id,
qsupplier_input_t& in)
{
TRACE( TRACE_ALWAYS, "********** qsupplier *********\n");
policy_t* dp = this->get_sched_policy();
xct_t* pxct = smthread_t::me()->xct();
// TSCAN PACKET
tuple_fifo* tscan_out_buffer =
new tuple_fifo(sizeof(projected_tuple));
tscan_packet_t* supplier_tscan_packet =
new tscan_packet_t("TSCAN SUPPLIER",
tscan_out_buffer,
new supplier_tscan_filter_t(this,in),
this->db(),
_psupplier_desc.get(),
pxct
//, SH
);
/* tuple_fifo* agg_output = new tuple_fifo(sizeof(count_tuple));
aggregate_packet_t* agg_packet =
new aggregate_packet_t(c_str("COUNT_AGGREGATE"),
agg_output,
new trivial_filter_t(agg_output->tuple_size()),
new count_aggregate_t(),
new int_key_extractor_t(),
date_tscan_packet);
new partial_aggregate_packet_t(c_str("COUNT_AGGREGATE"),
agg_output,
new trivial_filter_t(agg_output->tuple_size()),
qsupplier_tscan_packet,
new count_aggregate_t(),
new default_key_extractor_t(),
new int_key_compare_t());
*/
qpipe::query_state_t* qs = dp->query_state_create();
supplier_tscan_packet->assign_query_state(qs);
//agg_packet->assign_query_state(qs);
// Dispatch packet
ssb_qsupplier_process_tuple_t pt;
process_query(supplier_tscan_packet, pt);
dp->query_state_destroy(qs);
return (RCOK);
}
EXIT_NAMESPACE(ssb);
| 28.2625 | 78 | 0.579685 | DBlabRT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.