text
stringlengths 8
6.88M
|
|---|
// VectorSpace.hpp
#ifndef VectorSpace_HPP
#define VectorSpace_HPP
template<typename Type, int N> class VectorSpace
{
private:
Type arr[N];
public:
// Constructors & destructor
VectorSpace();
VectorSpace(const Type& value); // All elements get this value
VectorSpace(const VectorSpace<Type, N>& source);
virtual ~VectorSpace();
// Selectors
int Size() const;
int MinIndex() const;
int MaxIndex() const;
// Some properties
Type innerProduct (const VectorSpace<Type, N>& p2) const; // Inner product
Type Norm() const; // The l Infinity norm
Type componentProduct() const; // The product of all components
// Numeric operations
VectorSpace<Type, N> operator - () const; // The negative of a vector
VectorSpace<Type, N> operator + (const VectorSpace<Type, N>& v2) const;
VectorSpace<Type, N> operator - (const VectorSpace<Type, N>& v2) const;
VectorSpace<Type, N> operator + (const Type& offset) const; // Add offset to each coord
VectorSpace<Type, N> operator - (const Type& offset) const; // Sub offset to each coord
// ** Template member functions ** Premultiplication by a field value
template <typename F> VectorSpace<Type, N>
friend operator * (const F& scalar, const VectorSpace<Type, N>& pt);
// Operators
Type& operator[](int index); // Index operator for non const VectorSpaces
const Type& operator[](int index) const; // Index operator for const VectorSpaces
VectorSpace<Type, N>& operator = (const VectorSpace<Type, N>& source);
};
#endif // VectorSpace_hpp
|
class Solution
{
public:
//Function to find the next greater element for each element of the array.
vector<long long> nextLargerElement(vector<long long> arr, int n){
stack<long long> st;
vector<long long> ans(n,0);
for(int i = n-1;i>=0;i--){
while(st.size()!=0){
long long temp = st.top();
if(temp>arr[i]) {
ans[i]=temp;
break;
}
else {
st.pop();
}
}
if(st.size()==0) ans[i]=-1;
st.push(arr[i]);
}
return ans;
}
};
|
#include "drawFrames.h"
#include "cursorSet.h"
#include <stdio.h>
#include <ctime>
#include <conio.h>
#include <windows.h>
#include "time.h"
#include <string>
#include "webClock.h"
#include <iomanip>
#include <iostream>
#include "clockMenus.h"
using namespace std;
void drawFrames::createFrame(int startRow, int startCol, cursorSet newCursorLoc) {
newCursorLoc.setNewCursor(startRow, startCol);
cout << setfill('*') << setw(30) << "";
cout << setfill(' ') << setw(10) << "";
cout << setfill('*') << setw(30) << "";
cout << setfill(' ');
newCursorLoc.setNewCursor(startRow + 1, startCol);
cout << "*";
cout << setw(21) << right << "24-HOUR CLOCK" << setw(8) << right << "*";
cout << setw(10) << "";
cout << "*";
cout << setw(21) << right << "12-HOUR CLOCK" << setw(8) << right << "*";
newCursorLoc.setNewCursor(startRow + 2, startCol);
cout << "*" << setw(29) << right << "*" << setw(11) << right << "*" << setw(29) << right << "*";
newCursorLoc.setNewCursor(startRow + 3, startCol);
cout << setfill('*') << setw(30) << "";
cout << setfill(' ') << setw(10) << "";
cout << setfill('*') << setw(30) << "";
}
|
/********************************************************************************
** Form generated from reading UI file 'editdata.ui'
**
** Created by: Qt User Interface Compiler version 5.15.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_EDITDATA_H
#define UI_EDITDATA_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTableView>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_EditData
{
public:
QFrame *frame;
QTabWidget *tabWidget;
QWidget *tab;
QPushButton *pushButton;
QPushButton *pushButton_2;
QTableView *table_cakes;
QWidget *tab_2;
QTableView *table_raw;
QPushButton *pushButton_3;
QPushButton *pushButton_4;
QWidget *tab_3;
QTableView *table_shops;
QPushButton *pushButton_5;
QPushButton *pushButton_6;
void setupUi(QWidget *EditData)
{
if (EditData->objectName().isEmpty())
EditData->setObjectName(QString::fromUtf8("EditData"));
EditData->resize(1985, 1044);
EditData->setStyleSheet(QString::fromUtf8("*{\n"
" \n"
" background-color: rgb(214, 182, 187);\n"
" font-family: Roboto;\n"
" font-size: 24px;\n"
" font-weight: bold;\n"
"}\n"
"\n"
"QFrame{\n"
" background-color: #FCFCFC;\n"
" border-radius: 20px;\n"
"}\n"
"\n"
""));
frame = new QFrame(EditData);
frame->setObjectName(QString::fromUtf8("frame"));
frame->setGeometry(QRect(60, 50, 1601, 761));
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Raised);
tabWidget = new QTabWidget(frame);
tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
tabWidget->setGeometry(QRect(10, 10, 1381, 741));
tabWidget->setStyleSheet(QString::fromUtf8("*{\n"
" background-color: rgb(244, 231, 231);\n"
"}\n"
"\n"
"QWidget::tab{\n"
" height: 60px;\n"
" width: 455px;\n"
" color: #575757;\n"
"}"));
tabWidget->setTabPosition(QTabWidget::South);
tab = new QWidget();
tab->setObjectName(QString::fromUtf8("tab"));
pushButton = new QPushButton(tab);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setGeometry(QRect(920, 60, 251, 61));
pushButton->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
pushButton_2 = new QPushButton(tab);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setGeometry(QRect(920, 170, 251, 61));
pushButton_2->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
table_cakes = new QTableView(tab);
table_cakes->setObjectName(QString::fromUtf8("table_cakes"));
table_cakes->setGeometry(QRect(130, 130, 541, 361));
table_cakes->setStyleSheet(QString::fromUtf8("background-color: #FCFCFC;"));
tabWidget->addTab(tab, QString());
tab_2 = new QWidget();
tab_2->setObjectName(QString::fromUtf8("tab_2"));
table_raw = new QTableView(tab_2);
table_raw->setObjectName(QString::fromUtf8("table_raw"));
table_raw->setGeometry(QRect(110, 70, 591, 501));
table_raw->setStyleSheet(QString::fromUtf8("background-color: #FCFCFC;"));
pushButton_3 = new QPushButton(tab_2);
pushButton_3->setObjectName(QString::fromUtf8("pushButton_3"));
pushButton_3->setGeometry(QRect(830, 70, 251, 51));
pushButton_3->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
pushButton_4 = new QPushButton(tab_2);
pushButton_4->setObjectName(QString::fromUtf8("pushButton_4"));
pushButton_4->setGeometry(QRect(830, 180, 281, 71));
pushButton_4->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
tabWidget->addTab(tab_2, QString());
tab_3 = new QWidget();
tab_3->setObjectName(QString::fromUtf8("tab_3"));
tab_3->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
table_shops = new QTableView(tab_3);
table_shops->setObjectName(QString::fromUtf8("table_shops"));
table_shops->setGeometry(QRect(230, 110, 391, 321));
table_shops->setStyleSheet(QString::fromUtf8("background-color: #FCFCFC;"));
pushButton_5 = new QPushButton(tab_3);
pushButton_5->setObjectName(QString::fromUtf8("pushButton_5"));
pushButton_5->setGeometry(QRect(920, 120, 251, 61));
pushButton_5->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
pushButton_6 = new QPushButton(tab_3);
pushButton_6->setObjectName(QString::fromUtf8("pushButton_6"));
pushButton_6->setGeometry(QRect(920, 250, 261, 61));
pushButton_6->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" background-color: rgb(128, 66, 77);\n"
" color: #FBFBFB;\n"
" border-radius: 20px;\n"
"}"));
tabWidget->addTab(tab_3, QString());
retranslateUi(EditData);
tabWidget->setCurrentIndex(0);
QMetaObject::connectSlotsByName(EditData);
} // setupUi
void retranslateUi(QWidget *EditData)
{
EditData->setWindowTitle(QCoreApplication::translate("EditData", "Form", nullptr));
pushButton->setText(QCoreApplication::translate("EditData", "PushButton", nullptr));
pushButton_2->setText(QCoreApplication::translate("EditData", "PushButton", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tab), QCoreApplication::translate("EditData", "\320\222\320\270\320\277\321\226\321\207\320\272\320\260", nullptr));
pushButton_3->setText(QCoreApplication::translate("EditData", "PushButton", nullptr));
pushButton_4->setText(QCoreApplication::translate("EditData", "PushButton", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tab_2), QCoreApplication::translate("EditData", "\320\241\320\270\321\200\320\276\320\262\320\270\320\275\320\260", nullptr));
pushButton_5->setText(QCoreApplication::translate("EditData", "PushButton", nullptr));
pushButton_6->setText(QCoreApplication::translate("EditData", "\320\222\320\270\320\264\320\260\320\273\320\270\321\202\320\270 \320\267\320\260\320\277\320\270\321\201", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tab_3), QCoreApplication::translate("EditData", "\320\234\320\260\320\263\320\260\320\267\320\270\320\275\320\270", nullptr));
} // retranslateUi
};
namespace Ui {
class EditData: public Ui_EditData {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_EDITDATA_H
|
//
// Created by 송지원 on 2020/06/30.
//
#include <iostream>
#include <queue>
#include <utility>
using namespace std;
#define X first
#define Y second
int box[1002][1002];
int dis[1002][1002];
int N, M;
char input;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
bool alive = false;
int alive_time = -1;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
queue<pair<int, int>> Qj;
queue<pair<int, int>> Qfire;
for (int i=0; i<N; i++) {
for (int j=0; j<M; j++) {
cin >> input;
if (input == '#') box[i][j] = -1;
else if (input == '.') {
box[i][j] = 0;
dis[i][j] = -1;
}
else if (input == 'J') {
Qj.push({i, j});
}
else if (input == 'F') {
Qfire.push({i, j});
box[i][j] = -2;
}
}
}
while (true) {
int temp_size = Qj.size();
for (int x=0; x<temp_size; x++){
auto cur = Qj.front();
if (cur.X==0 || cur.X==N-1 || cur.Y==0 || cur.Y==M-1) {
alive = true;
break;
}
Qj.pop();
for (int dir=0; dir<4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx<0 || nx>=N || ny<0 || ny>=M) continue;
if (box[nx][ny] != 0 || dis[nx][ny] >= 0) continue;
Qj.push({nx, ny});
dis[nx][ny] = dis[cur.X][cur.Y] + 1;
alive_time = max(alive_time, dis[nx][ny]);
}
}
alive_time++;
temp_size = Qfire.size();
for (int x=0; x<temp_size; x++){
auto cur = Qfire.front();
Qfire.pop();
for (int dir=0; dir<4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx<0 || nx>=N || ny<0 || ny>=M) continue;
if (box[nx][ny] == -1 ) continue;
Qfire.push({nx, ny});
box[nx][ny] = -2;
}
}
if (alive) break;
}
if (alive) cout << alive_time+1 ;
else cout << "IMPOSSIBLE";
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
**
*/
#include "core/pch.h"
#ifdef DATASTREAM_BITARRAY
#include "modules/datastream/fl_lib.h"
#include "modules/datastream/fl_bitarray.h"
#define ONES 0xffffffff
void DataStream_BitArray::AddBitsL(uint32 value, uint32 bits)
{
OP_ASSERT(bits > 0 && bits <= 32);
// mask out the overflowing bits
value &= ONES >> (32 - bits);
OP_ASSERT(bits == 32 || (value < (UINT32)(1 << bits)));
if (bits > m_bits_left)
{
// first fill up the existing byte
bits -= m_bits_left;
uint32 fill_bits = value >> bits;
value &= ONES >> (32 - bits);
m_current_bytes[0] |= fill_bits;
uint32 cur_byte = 1;
// write all remaining full bytes
while (bits >= 8)
{
bits -= 8;
m_current_bytes[cur_byte++] = value >> bits;
value &= ONES >> (32 - bits);
}
// flush all our full bytes and reset buffer
AddContentL(m_current_bytes, cur_byte);
m_bits_left = 8;
m_initialize = 0;
}
// and put the remaining bits in the current_byte
m_bits_left -= bits;
value <<= m_bits_left;
m_current_bytes[0] |= value;
if (m_bits_left == 0) // flush the byte
{
AddContentL(m_current_bytes, 1);
m_initialize = 0;
m_bits_left = 8;
}
}
void DataStream_BitArray::Add1sL(uint32 number_of_ones)
{
OP_ASSERT(number_of_ones <= 32);
uint32 value = ONES >> (32 - number_of_ones);
AddBitsL(value, number_of_ones);
}
void DataStream_BitArray::PadAndFlushL() {
if (m_bits_left == 8) // everything already flushed
return;
AddContentL(m_current_bytes, 1);
m_initialize = 0;
m_bits_left = 8;
}
#endif // DATASTREAM_BITARRAY
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#if USE_OPENGL
#include "OpenGlService.h"
#include "OpenGl.h"
namespace View {
void OpenGlService::init (int resX, int resY)
{
glShadeModel(GL_FLAT);
glDisable (GL_DEPTH_TEST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
/*
* Alpha blending. Niestety tekstura jest w niektorych miejscach
* przezroczysta, ale wystaje spodniej niebieski kolor prostokątu.
*/
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Transformacje.
// glMatrixMode (GL_MODELVIEW);
// glLoadIdentity ();
// gluOrtho2D (0, 0, resX, resY);
float aspectRatio = double (resY) / resX;
float rX = 100.0;
float rY = rX * aspectRatio;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
// gluOrtho2D (-resX / 2.0, resX / 2.0, -resY / 2.0, resY / 2.0);
gluOrtho2D (-rX, rX, -rY, rY);
// glEnable(GL_LINE_SMOOTH);
// glEnable(GL_POINT_SMOOTH);
// glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
// glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
glPointSize (3);
// glDrawArrays
glEnableClientState(GL_VERTEX_ARRAY);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
/*
* Te dwie poniższe komendy ustawiają filtrowanie dla przybliżania i
* oddalania. GL_NEAREST - kolor z 1 teksela najbliższego pixelowi.
*/
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
/****************************************************************************/
void OpenGlService::free ()
{
}
/****************************************************************************/
void OpenGlService::mouseToDisplay (int x, int y, int windowWidth, int windowHeight, float *nx, float *ny)
{
GLdouble model[16];
glGetDoublev (GL_MODELVIEW_MATRIX, model);
GLdouble proj[16];
glGetDoublev (GL_PROJECTION_MATRIX, proj);
GLint view[4];
glGetIntegerv (GL_VIEWPORT, view);
GLdouble mx, my, mz;
gluUnProject(x, windowHeight - y, 0.0f, model, proj, view, &mx, &my, &mz);
*nx = mx;
*ny = my;
}
} /* namespace View */
#endif
|
//
// Created by ischelle on 05/05/2021.
//
#include "Dispatcher.hpp"
namespace pandemic
{
Dispatcher::Dispatcher(Board board, City city) : Player(board, city)
{
//nothing
}
}
|
#pragma once
#include <iberbar/Utility/Unknown.h>
#include <map>
namespace iberbar
{
template < typename TKey, typename TValue >
class TResourceManager
{
public:
typedef std::map<TKey, TValue*> _Map;
public:
TResourceManager() {}
~TResourceManager();
public:
bool Find( const TKey& key, TValue** ppOut );
protected:
_Map m_Cache;
};
}
template < typename TKey, typename TValue >
iberbar::TResourceManager< TKey, TValue >::~TResourceManager()
{
_Map::iterator iter = m_Cache.begin();
_Map::iterator end = m_Cache.end();
for ( ; iter != end; iter++ )
{
if ( iter->second != nullptr )
{
UNKNOWN_SAFE_RELEASE_NULL( iter->second );
iter->second = nullptr;
}
}
m_Cache.Clear();
}
template < typename TKey, typename TValue >
bool iberbar::TResourceManager< TKey, TValue >::Find( const TKey& key, TValue** ppOut )
{
TValue* pValue;
std::map<int, int*> s;
_Map::iterator iter = m_Cache.find( key );
if ( iter == m_Cache.end() )
return false;
pValue = iter->second;
if ( ppOut != nullptr )
{
if ( *ppOut )
(*ppOut)->Release();
(*ppOut) = pValue;
(*ppOut)->AddRef();
}
return true;
}
|
struct BaseSystem
{
virtual void update() = 0;
void accept(EntityRef e) { entities.emplace(e); }
protected:
std::set<EntityRef> entities;
ComponentManager* components = nullptr;
};
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// M - input 1 columns N - input 1 columns/input 2 rows K - input 2 columns
void matMultiplyOnHost(float* A, float* B, float* C, int M, int N, int K)
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < K; j++)
{
C[i * K + j] = 0.0;
for (int x = 0; x < N; x++)
{
C[i * K + j] += A[i * N + x] * B[x * K + j];
}
}
}
return;
}
//CPU Matrix Multiplication with Bias added
void matMultiplyOnHostBias(float* A, float* B, float* C, float* bias, int M, int N, int K)
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < K; j++)
{
C[i * K + j] = 0.0;
for (int x = 0; x < N; x++)
{
C[i * K + j] += A[i * N + x] * B[x * K + j];
}
C[i * K + j] += bias[i * K + j];
}
}
return;
}
// Relu CPU function
void reluActivationForwardOnHost(float* Z, float* A, int Z_x_dim, int Z_y_dim) {
for(int index = 0; index < Z_x_dim * Z_y_dim; index++) {
A[index] = fmaxf(Z[index], 0);
}
}
//*************************************************************
void Print_Mat(int Row, int Col, float* Mat)//Function To print the Matrix
{
for (int i = 0; i < Row * Col; i++)
{
printf("%f ", *(Mat + i));
if ((i % Col) == 0)
{
printf("\n");
}
}
}
int input_rows = 1;
int input_cols = 784;
int layer1_rows = 784;
int layer1_cols = 128;
int layer2_rows = 128;
int layer2_cols = 10;
int output_rows = input_rows;
int output_cols = 10;
int main(int argc, char** argv) {
float* host_input;
float* host_output;
float* host_layer1w;
float* host_layer1b;
float* host_layer1out;
float* host_layer2w;
float* host_layer2b;
float* hostComputedC;
host_input = (float*)malloc(sizeof(float) * input_rows * input_cols);
host_output = (float*)malloc(sizeof(float) * output_rows * output_cols);
host_layer1w = (float*)malloc(sizeof(float) * layer1_rows * layer1_cols);
host_layer1b = (float*)malloc(sizeof(float) * input_rows * layer1_cols);
host_layer1out = (float*)malloc(sizeof(float) * input_rows * layer1_cols);
host_layer2w = (float*)malloc(sizeof(float) * layer2_rows * layer2_cols);
host_layer2b = (float*)malloc(sizeof(float) * input_rows * layer2_cols);
hostComputedC = (float*)malloc(sizeof(float) * input_rows * layer1_cols);
for (int i = 0; i < input_rows * input_cols; i++)//Matrix Initialization
{
host_input[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
}
for (int i = 0; i < layer1_rows * layer1_cols; i++)
{
host_layer1w[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
}
for (int i = 0; i < input_rows * layer1_cols; i++)
{
host_layer1b[i] = 1.0;
}
for (int i = 0; i < layer2_rows * layer2_cols; i++)
{
host_layer2w[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
}
for (int i = 0; i < input_rows * layer2_cols; i++)
{
host_layer2b[i] = 1.0;
}
matMultiplyOnHost(host_input, host_layer1w, hostComputedC, input_rows, input_cols, layer1_cols);
printf("\nMatrix C From Host\n");
Print_Mat(input_rows, layer1_cols, hostComputedC);//Function Call
return 0;
}
|
#include "../inc.h"
#include "../linear/matrix.h"
#include "../geometry/affine.h"
#include "../geometry/transform.h"
#include "camera.h"
#include <array>
#include <functional>
#include <vector>
#ifndef CLASS_PLOT
#define CLASS_PLOT
namespace Z_3D_LIB_FOR_EGE {
class _plot;
class _plot {
typedef _plot _Tself;
typedef double _Titem;
typedef _affine_vector _Tv4;
typedef _camera _Tcamera;
typedef _vector < 3, _Titem > _Tv3;
typedef _square < 4, _Titem > _Tm4;
std::vector< std::vector< _Tv4 > > _cols;
std::vector< std::vector< _Tv4 > > _rows;
public:
_plot(
const std::array< _Titem, 3 >& sRange,
const std::array< _Titem, 3 >& tRange,
const std::function< _Titem(_Titem, _Titem) >& xFunc,
const std::function< _Titem(_Titem, _Titem) >& yFunc,
const std::function< _Titem(_Titem, _Titem) >& zFunc
) {
_Titem _ss = sRange[0], _se = sRange[1], _sc = (size_t)sRange[2], _st = (_se - _ss) / _sc;
_Titem _ts = tRange[0], _te = tRange[1], _tc = (size_t)tRange[2], _tt = (_te - _ts) / _tc;
_Titem _s = _ss;
for (size_t i = 0; i < _sc; _s += _st, i++) {
_Titem _t = _ts;
_cols.push_back(std::vector< _Tv4 >());
for (size_t j = 0; j < _tc; _t += _tt, j++) {
_cols[i].push_back({ xFunc(_s, _t), yFunc(_s, _t), zFunc(_s, _t), 1 });
}
}
_Titem _t = _ts;
for (size_t i = 0; i < _tc; _t += _tt, i++) {
_Titem _s = _ss;
_rows.push_back(std::vector< _Tv4 >());
for (size_t j = 0; j < _sc; _s += _st, j++) {
_rows[i].push_back({ xFunc(_s, _t), yFunc(_s, _t), zFunc(_s, _t), 1 });
}
}
}
void draw(
const std::function< void(_Titem, _Titem, _Titem, _Titem) >& drawFunc,
const _Tcamera& camera,
const _Tm4& trans = _Tm4(IDENTITY_MATRIX)
) {
_Tv4 _ds, _de, _max, _min, _x, _y, _z;
_Titem _ds_dp, _de_dp;
_max = _min = _cols[0][0];
for (size_t i = 0; i < _cols.size(); i++) {
for (size_t j = 0; j < _cols[i].size(); j++) {
if (j) {
_ds_dp = _transform::pseudodepth(camera.v(), camera.e(), _cols[i][j]);
_de_dp = _transform::pseudodepth(camera.v(), camera.e(), _cols[i][j - 1]);
if (_ds_dp < _Titem(1) && _de_dp < _Titem(1)) {
_ds = (_cols[i][j] * trans).normalize();
_de = (_cols[i][j - 1] * trans).normalize();
drawFunc(_ds[0], _ds[1], _de[0], _de[1]);
if (_cols[i][j][0] > _max[0]) _max[0] = _cols[i][j][0];
if (_cols[i][j][1] > _max[1]) _max[1] = _cols[i][j][1];
if (_cols[i][j][2] > _max[2]) _max[2] = _cols[i][j][2];
if (_cols[i][j][0] < _min[0]) _min[0] = _cols[i][j][0];
if (_cols[i][j][1] < _min[1]) _min[1] = _cols[i][j][1];
if (_cols[i][j][2] < _min[2]) _min[2] = _cols[i][j][2];
}
}
}
}
for (size_t i = 0; i < _rows.size(); i++) {
for (size_t j = 0; j < _rows[i].size(); j++) {
if (j) {
_ds_dp = _transform::pseudodepth(camera.v(), camera.e(), _rows[i][j]);
_de_dp = _transform::pseudodepth(camera.v(), camera.e(), _rows[i][j - 1]);
if (_ds_dp < _Titem(1) && _de_dp < _Titem(1)) {
_ds = (_rows[i][j] * trans).normalize();
_de = (_rows[i][j - 1] * trans).normalize();
drawFunc(_ds[0], _ds[1], _de[0], _de[1]);
}
}
}
}
_x = { _max[0] - _min[0], 0, 0, 0 };
_y = { 0, _max[1] - _min[1], 0, 0 };
_z = { 0, 0, _max[2] - _min[2], 0 };
_ds = (_min * trans).normalize();
_ds_dp = _transform::pseudodepth(camera.v(), camera.e(), _min);
if (_ds_dp < _Titem(1)) {
_de_dp = _transform::pseudodepth(camera.v(), camera.e(), _min + _x);
if (_de_dp < _Titem(1)) {
_de = ((_min + _x) * trans).normalize();
drawFunc(_ds[0], _ds[1], _de[0], _de[1]);
}
_de_dp = _transform::pseudodepth(camera.v(), camera.e(), _min + _y);
if (_de_dp < _Titem(1)) {
_de = ((_min + _y) * trans).normalize();
drawFunc(_ds[0], _ds[1], _de[0], _de[1]);
}
_de_dp = _transform::pseudodepth(camera.v(), camera.e(), _min + _z);
if (_de_dp < _Titem(1)) {
_de = ((_min + _z) * trans).normalize();
drawFunc(_ds[0], _ds[1], _de[0], _de[1]);
}
}
}
};
}
#endif !PLOT_CLASSES
|
#ifndef PARSER_H_
#define PARSER_H_
#include <string>
#define SHORT_FIELD 24
#define LONG_FIELD 128
using namespace std;
/* symbol_table is a single entry in the symbol table array containing information about
variable declarations, loops, and control statments
these will be the commands found in the symbol table. Due to the fact that commands will
be read in from a config file however, they are subject to change.
name: value:
int int value
float float value
if next else line# or eif line# if no else present
eif if line#
elseif next else line# or eif if last else statement
else next else line# or eif if last else statement
for efor line#
efor for line#
do edo line#
edo do line#
while ewhile line#
ewhile while line#
location:
each command in symbol table will have the array index that it can be found at in parsed programs source
count:
each variable, and each group of if/else/eif, for/efor, do/edo, while/ewhile will have a unique count to
identify themselves and group together control/loop structures.
*/
struct symbol_table{
char name[SHORT_FIELD];
float value;
int location;
int count;
};
/* actions are individual lines in the actions array. They are read in from a config file and tell the parser what
action to take when a given command is read in. This allows the parseing language to be defined somewhat
dynamically from said config file. This also focuses the language definition into one location so later
communications with the main program will be synchronized by reading the same file.
sytnax will be used in conjunction with regular expression matching to identify commands.
See actions.cfg
*/
struct action_struct{
char command[SHORT_FIELD];
char action[SHORT_FIELD];
char link[SHORT_FIELD];
char syntax[LONG_FIELD];
};
/* pre_parse_array is a tool used to reduce lookups to other arrays while storing pre-parse relevant information in
single struct elements. During pre parse an array of these will be used to store information temporarily about each
line of program code.
*/
struct pre_parse_array{
int action_index;
int symbol_index;
char variables[LONG_FIELD];
};
class Parser{
public:
Parser(string * code,int pcount,char * cfg_path);
~Parser();
void loadcfg(char * cfg_path);
void preparse();
int get_action(string line); //returns action index of a given line
int action_to_int(string action); //returns int action values based on string conversion
string get_variables(string line, string syntax); //returns variables from a given line of code based on syntax froma actions.cfg
string get_value(string line,string var_type); //function for returning specific variable values from coded get_varibales strings
int get_next_link(string command, string links, int pcount); //negotiates evaluate commands
string eval_link(string command,string links); //helper function for get_next_link
void parse();
float lookup_eval(string vars); //lookup and evaluate
void disp_at();
void disp_st();
void disp_ppa();
private:
int p_count; //holds the length of the code array
int a_count; //holds the lenght of the actions array
int s_count; //holds the lenght of the symbol table array
string * program; //program array
symbol_table * st; //symbol table array
action_struct * actions; //action list array
pre_parse_array * ppa;//meta-data for program code
};
#endif //PARSER_H_
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int numDecodings(string s) {
//基本思想:动态规划法,dp[i]表示前i个字符的解码方式的总个数
//如果当前字符不等于0,则当前字符可以解码成单个字符,所以dp[i]+=dp[i-1]
//如果当前字符和前一个字符在10-26之间,则两个字符也可以成对解码,所以dp[i]+=dp[i-2]
if (s.size() == 0)
return 0;
int res = 0, i;
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
if (s[0] != '0')
dp[1] = 1;
for (i = 2; i <= s.size(); i++)
{
if (s[i - 2] == '1' || s[i - 2] == '2' && s[i - 1] <= '6')
dp[i] += dp[i - 2];
if (s[i - 1] != '0')
dp[i] += dp[i - 1];
}
return dp[s.size()];
}
};
class Solution1 {
public:
int res = 0;
int numDecodings(string s) {
//基本思想:递归回溯法,超时
if (s.size() == 0)
return 0;
Recursion(s, 0);
return res;
}
void Recursion(string &s, int pos)
{
if (pos == s.size())
{
res++;
return;
}
if (s[pos] > '0')
{
Recursion(s, pos + 1);
}
if (pos + 1 <= s.size() - 1 && (s[pos] == '1' || s[pos] == '2' && s[pos + 1] <= '6'))
{
Recursion(s, pos + 2);
}
return;
}
};
int main()
{
Solution solute;
string s = "01";
cout << solute.numDecodings(s) << endl;
return 0;
}
|
// Created by: Peter KURNEV
// Copyright (c) 2010-2014 OPEN CASCADE SAS
// Copyright (c) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
// Copyright (c) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, CEDRAT,
// EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BOPAlgo_BuilderArea_HeaderFile
#define _BOPAlgo_BuilderArea_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BOPAlgo_Algo.hxx>
#include <NCollection_BaseAllocator.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_IndexedMapOfOrientedShape.hxx>
class IntTools_Context;
//! The root class for algorithms to build
//! faces/solids from set of edges/faces
class BOPAlgo_BuilderArea : public BOPAlgo_Algo
{
public:
DEFINE_STANDARD_ALLOC
//! Sets the context for the algorithms
void SetContext (const Handle(IntTools_Context)& theContext) {
myContext = theContext;
}
//! Returns the input shapes
const TopTools_ListOfShape& Shapes() const {
return myShapes;
}
//! Sets the shapes for building areas
void SetShapes(const TopTools_ListOfShape& theLS) {
myShapes = theLS;
}
//! Returns the found loops
const TopTools_ListOfShape& Loops() const {
return myLoops;
}
//! Returns the found areas
const TopTools_ListOfShape& Areas() const {
return myAreas;
}
//! Defines the preventing of addition of internal parts into result.
//! The default value is FALSE, i.e. the internal parts are added into result.
void SetAvoidInternalShapes(const Standard_Boolean theAvoidInternal) {
myAvoidInternalShapes = theAvoidInternal;
}
//! Returns the AvoidInternalShapes flag
Standard_Boolean IsAvoidInternalShapes() const {
return myAvoidInternalShapes;
}
protected:
Standard_EXPORT BOPAlgo_BuilderArea();
Standard_EXPORT virtual ~BOPAlgo_BuilderArea();
Standard_EXPORT BOPAlgo_BuilderArea(const Handle(NCollection_BaseAllocator)& theAllocator);
virtual void PerformShapesToAvoid(const Message_ProgressRange& theRange) = 0;
virtual void PerformLoops(const Message_ProgressRange& theRange) = 0;
virtual void PerformAreas(const Message_ProgressRange& theRange) = 0;
virtual void PerformInternalShapes(const Message_ProgressRange& theRange) = 0;
Handle(IntTools_Context) myContext;
TopTools_ListOfShape myShapes;
TopTools_ListOfShape myLoops;
TopTools_ListOfShape myLoopsInternal;
TopTools_ListOfShape myAreas;
TopTools_IndexedMapOfOrientedShape myShapesToAvoid;
Standard_Boolean myAvoidInternalShapes;
private:
};
#endif // _BOPAlgo_BuilderArea_HeaderFile
|
#ifndef __MODEL_ACTBROWSER_H
#define __MODEL_ACTBROWSER_H
#include "IModelWindow.h"
#include "ModelActTable.h"
namespace wh{
//---------------------------------------------------------------------------
class ModelActBrowserWindow : public IModelWindow
{
public:
using FuncActivateCallback
= std::function<int(const ModelActTable::RowType& act)>;
ModelActBrowserWindow();
void DoSwap(std::shared_ptr<ModelActTable> table);
void UpdateExist();
void SetActs(const std::set<int64_t>& act_idents);
void DoActivate();
void SetActivateCallback(const FuncActivateCallback& fn);
using SigRefresh = sig::signal<void(std::shared_ptr<const ModelActTable>)>;
using SigGetSelection = sig::signal<void(std::set<int64_t>&)>;
SigRefresh sigBeforeRefresh;
SigRefresh sigAfterRefresh;
SigGetSelection sigGetSelection;
//using SigOperation = sig::signal<void(Operation op, const std::vector<const IIdent64*>&)>;
//SigOperation sigOperation;
private:
std::shared_ptr<ModelActTable> mActTable;
FuncActivateCallback mFuncActivateCallback;
};
//---------------------------------------------------------------------------
} //namespace wh{
#endif // __*_H
|
#ifndef OFXCOMMANDPATTERNTHREADSYNCWINH
#define OFXCOMMANDPATTERNTHREADSYNCWINH
#include <windows.h>
#include <process.h>
class ofxCommandProcessorThreadSyncWin : public ofxCommandProcessorThreadSync{
protected:
HANDLE mutex_handle;
bool acquired;
public:
ofxCommandProcessorThreadSyncWin()
:mutex_handle(NULL)
,acquired(false)
{
mutex_handle = CreateMutex(NULL, false, NULL);
if(mutex_handle == NULL) {
CloseHandle(mutex_handle);
}
}
virtual ~ofxCommandProcessorThreadSyncWin() {
unlock();
CloseHandle(mutex_handle);
}
virtual bool lock() {
if(mutex_handle != NULL) {
DWORD result = WaitForSingleObject(mutex_handle, INFINITE);
if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED) {
acquired = true;
}
}
return acquired;
}
virtual void unlock() const {
if(mutex_handle) {
ReleaseMutex(mutex_handle);
}
}
virtual void wait(int nMillis) {
Sleep(nMillis);
if(isLocked()) {
unlock();
}
lock();
}
virtual void notify() {
if(isLocked()) {
unlock();
}
}
virtual bool isLocked() const {
return acquired;
}
};
#endif
|
#include <iostream>
#include <cmath>
using namespace std;
//number of neuron
const auto INPUT_NUM = 2;
const auto FIRST = 3;
const auto SECOND = 2;
const auto OUTPUT = 2;
double sigmoid(double x) {
return 1 / ( 1 + exp(-x));
}
int main(){
int i, j;
double temp;
cout << "first layer output" << endl;
double input[INPUT_NUM] = {1.0, 0.5};
double weight_1[INPUT_NUM][FIRST]= { {0.1, 0.3, 0.5},{0.2, 0.4, 0.6} };
double bias_1[FIRST]= {0.1, 0.2, 0.3};
double layer_1[FIRST] = {};
for(i=0; i<extent<decltype(weight_1),1>::value; i++){
temp = 0;
for(j=0; j<extent<decltype(input),0>::value; j++){
temp += input[j] * weight_1[j][i];
}
temp += bias_1[i];
layer_1[i] = sigmoid(temp);
cout << layer_1[i] << endl;
}
cout << "second layer output" << endl;
double weight_2[FIRST][SECOND]= { {0.1, 0.4},{0.2, 0.5}, {0.3, 0.6} };
double bias_2[SECOND]= {0.1, 0.2};
double layer_2[SECOND] = {};
for(i=0; i<extent<decltype(weight_2),1>::value; i++){
temp = 0;
for(j=0; j<extent<decltype(layer_1),0>::value; j++){
temp += layer_1[j] * weight_2[j][i];
}
temp += bias_2[i];
layer_2[i] = sigmoid(temp);
cout << layer_2[i] << endl;
}
cout << "third layer output" << endl;
double weight_3[SECOND][OUTPUT]= { {0.1, 0.3},{0.2, 0.4} };
double bias_3[OUTPUT]= {0.1, 0.2};
double output[OUTPUT] = {};
for(i=0; i<extent<decltype(weight_3),1>::value; i++){
temp = 0;
for(j=0; j<extent<decltype(layer_2),0>::value; j++){
temp += layer_2[j] * weight_3[j][i];
}
temp += bias_3[i];
output[i] = temp; //identity function
cout << output[i] << endl;
}
return 0;
}
|
/*
* Created by Peng Qixiang on 2018/8/8.
*/
/*
* 最小的k个数
* 输入n个整数,找出其中最小的K个数。
* 例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
*
*/
# include <iostream>
# include <vector>
# include <queue>
using namespace std;
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
// 异常处理!!!!!!!!!!!!!!!!!!!!
if(input.size() < k || input.empty() || k <= 0) return vector<int>();
// 用最大堆
vector<int> res(k);
priority_queue<int> heap;
for(int i = 0; i < k; i++){
heap.push(input[i]);
}
for(int i = k; i < input.size(); i++){
if(input[i] < heap.top()){
heap.pop();
heap.push(input[i]);
}
}
for(int i = k-1; i >= 0; i--){
res[i] = heap.top();
heap.pop();
}
return res;
}
};
int main(){
Solution s = Solution();
vector<int> test;
test.push_back(4);
test.push_back(5);
test.push_back(1);
test.push_back(6);
test.push_back(2);
test.push_back(7);
test.push_back(3);
test.push_back(8);
vector<int> res = s.GetLeastNumbers_Solution(test, 4);
for(int i = 0; i < res.size(); i++){
cout << res[i] << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
#define isNum(c) ('0'<=c&&c<='9')
using namespace std;
const int maxn = 10000;
const int maxm = 1000;
int n, m, k, t, L, R, ans = -1, res = 0, maxx = -1, x[maxn], y[maxn], l[maxn], r[maxn];
int ret; char ch;
int vis[maxn][maxm];
struct Bird{
int i, h, cnt;
} u, v, q[maxn * 1000];
int read() {
ch = getchar(), ret = 0;
while (!isNum(ch)) ch = getchar();
while (isNum(ch)) ret = ret * 10 + ch - '0', ch = getchar();
return ret;
}
void add(int x, int y, int z) {
q[++R] = {x, y, z};
}
int main() {
// freopen("testdata.in", "r+", stdin);
n = read(), m = read();
k = read();
for (int i = 1; i <= n; i++)
x[i] = read(), y[i] = read();
for (int i = 1; i <= n; i++)
l[i] = 0, r[i] = m + 1;
for (int i = 1; i <= k; i++) {
t = read();
l[t] = read(), r[t] = read();
}
L = 1, R = 0;
for (int i = 1; i <= m; i++) add(0, i, 0);
int i, h;
while (L <= R) {
u = q[L++];
i = u.i + 1;
h = u.h;
// cout << i << " " << h << endl;
if (i > maxx) maxx = i;
if (i > n) {
res = 1;
if (ans == -1 || ans > u.cnt)
ans = u.cnt;
continue;
}
if (l[i] < h - y[i] && h - y[i] < r[i]) {//不点击
add(i, h - y[i], u.cnt);
}
for (int j = 1; j <= m; j++) {//点击次数
if (l[i] >= h + j * x[i]) continue;
else if (r[i] <= h + j * x[i]) {
if (r[i] == m + 1) {
add(i, m, u.cnt + j);
}
break;
}
else {
if (!vis[i][h + j * x[i]])
add(i, h + j * x[i], u.cnt + j);
}
}
}
if (!res) {
ans = 0;
for (int i = 1; i < maxx; i++)
if (r[i] != m + 1) ans++;
}
printf("%d\n%d", res, ans);
return 0;
}
|
#include "../Headers/edge.h"
Edge::Edge()
{
node_id = 0;
weight = 0;
}
Edge::Edge(int id, int wt)
{
node_id = id;
weight = wt;
}
Edge::~Edge()
{
}
|
#include <iostream>
#include <vector>
#include <string>
void stugum(std::string str) {
for(auto i = 0; i < str.size(); ++i) {
if(str[i] < 'A' || str[i] > 'z' || (str[i] >'Z' && str[i] < 'a')) {
str[i] = '\0';
}
}
std::cout << str << std::endl;
}
int main() {
std::string str;
std::vector <std::string> vec;
std::cout << "cragir@ verjacnelu hamar nermuceq exit" << '\n';
do{
std::getline(std::cin, str);
vec.push_back(str);
} while(str != "exit");
std::cout << '\n';
for (auto i = 0; i < vec.size(); i++) {
stugum(vec[i]);
}
return 0;
}
|
#include <iostream>
#include <string>
#include "compiler.hpp"
void Conditions::eq(char* a,char* b, int yylineno) {
controllVariable(a,yylineno);
controllVariable(b,yylineno);
Variable var1 = variables.at(a);
Variable var2 = variables.at(b);
whileLoop.push(commands.size());
long mem2 = getMemory2Index(var2,yylineno);
long mem1 = getMemory1Index(var1,yylineno);
if(mem1 != 0) {
addCommand("LOAD "+longToString(mem1));
}
addCommand("SUB "+longToString(mem2));
addCommand("JZERO "+longToString(cmdIndex+2));
addCommand("JUMP $j");
jumps.push(commands.size()-1);
}
void Conditions::notEq(char* a,char* b, int yylineno) {
controllVariable(a,yylineno);
controllVariable(b,yylineno);
Variable var1 = variables.at(a);
Variable var2 = variables.at(b);
whileLoop.push(commands.size());
long mem2 = getMemory2Index(var2,yylineno);
long mem1 = getMemory1Index(var1,yylineno);
if(mem1 != 0) {
addCommand("LOAD "+longToString(mem1));
}
addCommand("SUB "+longToString(mem2));
addCommand("JZERO $j");
jumps.push(commands.size()-1);
}
void Conditions::less(char* a,char* b, int yylineno) {
controllVariable(a,yylineno);
controllVariable(b,yylineno);
Variable var1 = variables.at(a);
Variable var2 = variables.at(b);
whileLoop.push(commands.size());
long mem2 = getMemory2Index(var2,yylineno);
long mem1 = getMemory1Index(var1,yylineno);
if(mem1 != 0) {
addCommand("LOAD "+longToString(mem1));
}
addCommand("SUB "+longToString(mem2));
addCommand("JNEG "+longToString(cmdIndex+2));
addCommand("JUMP $j");
jumps.push(commands.size()-1);
}
void Conditions::greater(char* a,char* b, int yylineno) {
controllVariable(a,yylineno);
controllVariable(b,yylineno);
Variable var1 = variables.at(a);
Variable var2 = variables.at(b);
whileLoop.push(commands.size());
long mem2 = getMemory2Index(var2,yylineno);
long mem1 = getMemory1Index(var1,yylineno);
if(mem1 != 0) {
addCommand("LOAD "+longToString(mem1));
}
addCommand("SUB "+longToString(mem2));
addCommand("JPOS "+longToString(cmdIndex+2));
addCommand("JUMP $j");
jumps.push(commands.size()-1);
}
void Conditions::lessEq(char* a,char* b, int yylineno) {
controllVariable(a,yylineno);
controllVariable(b,yylineno);
Variable var1 = variables.at(a);
Variable var2 = variables.at(b);
whileLoop.push(commands.size());
long mem2 = getMemory2Index(var2,yylineno);
long mem1 = getMemory1Index(var1,yylineno);
if(mem1 != 0) {
addCommand("LOAD "+longToString(mem1));
}
addCommand("SUB "+longToString(mem2));
addCommand("JPOS $j");
jumps.push(commands.size()-1);
}
void Conditions::greaterEq(char* a,char* b, int yylineno) {
controllVariable(a,yylineno);
controllVariable(b,yylineno);
Variable var1 = variables.at(a);
Variable var2 = variables.at(b);
whileLoop.push(commands.size());
long mem2 = getMemory2Index(var2,yylineno);
long mem1 = getMemory1Index(var1,yylineno);
if(mem1 != 0) {
addCommand("LOAD "+longToString(mem1));
}
addCommand("SUB "+longToString(mem2));
addCommand("JNEG $j");
jumps.push(commands.size()-1);
}
|
#include "node.h"
Node::Node(QObject* parent)
{
}
|
#include "stivaDouble.h"
bool DStack::isEmpty() {
return first== nullptr;
}
void DStack::push(double val) {
if(first== nullptr)
{
first=new nodeD;
first->val=val;
first->next= nullptr;
}
else
{
nodeD *p=new nodeD;
p->val=val;
p->next=first;
first=p;
}
}
void DStack::pop() {
if(first->next== nullptr)
{
delete first;
first= nullptr;
}
else{
nodeD *p=first;
first=first->next;
p->next= nullptr;
delete p;
}
}
double DStack::top() {
return first->val;
}
|
#include <Version.h>
#include <Window.h>
#include <Model.h>
#include <Camera.h>
#include <Lights/LightRenderer.h>
#include <Shaders/Program.h>
class CWindowTest : public CWindow
{
public:
CWindowTest(int width, int height, const std::wstring &title)
: CWindow(width, height, title)
, _camera(glm::vec3(2.0f, 4.0f, 6.0f), glm::vec3(0.0f, 3.5f, 0.0f))
, _model("assets/hulk/hulk.obj")
, _flashlightOn(true)
, _rotateAngle(0.0f)
, _rotateSpeed(0.0f)
{
utils::Log(utils::CFormat(L"CWindowTest::CWindowTest(%%)") << title, utils::ELogLevel::Debug);
Resize(width, height); // FIXME: Move to another place (but not CWindow constructor)
Init();
_simple.loadShaders("glsl/Basic.glsl");
_simple.loadUniforms();
_simple.loadUniformBlocks();
_shading.loadShaders("glsl/Shading.glsl");
_shading.loadUniforms();
_shading.loadUniformBlocks();
}
virtual ~CWindowTest()
{
utils::Log(utils::CFormat(L"CWindowTest::~CWindowTest()"), utils::ELogLevel::Debug);
}
virtual void Init() override;
virtual void Update(float deltaTime) override;
virtual void Render() override;
virtual void Resize(int width, int height) override;
virtual void Key(int key, int action, int mods) override;
virtual void Cursor(float xpos, float ypos) override;
private:
CCamera _camera;
CProgram _simple;
CProgram _shading;
CModel _model;
CLightRenderer _lights;
std::shared_ptr<CDirectionalLight> _sun;
std::shared_ptr<CPointLight> _lamp;
std::shared_ptr<CSpotlight> _flashlight;
bool _flashlightOn;
float _rotateAngle;
float _rotateSpeed;
};
void CWindowTest::Init()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
_sun.reset(new CDirectionalLight(glm::vec3(1.0f, 1.0f, 0.0f)));
_sun->setAmbientIntensity(0.01f);
_sun->setDiffuseIntensity(2.0f);
_sun->setColor(glm::vec3(1.0f, 0.2f, 0.0f));
_lights.addLight(_sun);
_lamp.reset(new CPointLight(glm::vec3(-1.0f, 1.0f, 2.0f)));
_lamp->setAmbientIntensity(0.01f);
_lamp->setDiffuseIntensity(30.0f);
_lamp->setColor(glm::vec3(1.0f, 0.7f, 0.0f));
_lights.addLight(_lamp);
}
void CWindowTest::Update(float deltaTime)
{
_rotateAngle += _rotateSpeed * deltaTime;
if (_rotateAngle >= 360.0f) {
_rotateAngle = 0.0f;
}
static const float moveSpeed = 5.0f; // units per second
if (GetKeyState(GLFW_KEY_W) == GLFW_PRESS) {
_camera.move(deltaTime * moveSpeed * _camera.getDirection());
} else if (GetKeyState(GLFW_KEY_S) == GLFW_PRESS) {
_camera.move(deltaTime * moveSpeed * -_camera.getDirection());
} else if (GetKeyState(GLFW_KEY_D) == GLFW_PRESS) {
_camera.move(deltaTime * moveSpeed * _camera.getRight());
} else if (GetKeyState(GLFW_KEY_A) == GLFW_PRESS) {
_camera.move(deltaTime * moveSpeed * -_camera.getRight());
}
}
void CWindowTest::Render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
static const bool useLight = true;
// Set shader program as the active one
CProgram ¤t = useLight ? _shading : _simple;
current.use();
{
// Model matrix: Scale * Rotation * Translation
glm::mat4 modelMatrix = glm::rotate( glm::mat4(1.0f), glm::radians(_rotateAngle), glm::vec3(0.0f, 1.0f, 0.0f) );
glUniformMatrix4fv(current.getUniform("modelMatrix"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
if (_flashlightOn && !_flashlight)
{
// _spotlight.reset(new CSpotlight(glm::vec3(2.0f, 4.0f, 6.0f), glm::vec3(-0.5f, 0.0f, -1.5f), 10.0f));
_flashlight.reset(new CSpotlight(_camera.getPosition(), _camera.getDirection(), 10.0f));
_flashlight->setAmbientIntensity(0.01f);
_flashlight->setDiffuseIntensity(50.0f);
_flashlight->setColor(glm::vec3(0.0f, 0.2f, 1.0f));
_lights.addLight(_flashlight);
}
else if (!_flashlightOn && _flashlight)
{
_flashlight.reset();
}
if (GetKeyState(GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS && _flashlight)
{
_flashlight->setPosition(_camera.getPosition());
_flashlight->setDirection(_camera.getDirection());
}
_lights.render();
_model.render();
}
current.unuse();
SetCursorPosition(_width/2.0f, _height/2.0f);
utils::checkErrorStatus();
}
void CWindowTest::Resize(int width, int height)
{
utils::Log(utils::CFormat(L"CWindowTest::Resize(%%x%%)") << width << height, utils::ELogLevel::Debug);
_camera.setAspectRatio( static_cast<float>(_width / _height) );
glViewport(0, 0, width, height);
}
void CWindowTest::Key(int key, int action, int mods)
{
UNUSED(mods);
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
Destroy();
} else if (key == GLFW_KEY_LEFT) {
if (action == GLFW_PRESS) {
_rotateSpeed = 45.0f;
} else if (action == GLFW_RELEASE && _rotateSpeed > 0.0f) {
_rotateSpeed = 0.0f;
}
} else if (key == GLFW_KEY_RIGHT) {
if (action == GLFW_PRESS) {
_rotateSpeed = -45.0f;
} else if (action == GLFW_RELEASE && _rotateSpeed < 0.0f) {
_rotateSpeed = 0.0f;
}
} else if (key == GLFW_KEY_F) {
if (action == GLFW_PRESS) {
_flashlightOn = !_flashlightOn;
}
}
}
void CWindowTest::Cursor(float xpos, float ypos)
{
// utils::Log(utils::CFormat(L"CWindowTest::Cursor(%%, %%)") << xpos << ypos, utils::ELogLevel::Debug);
static const float mouseSensitivity = 0.0005f;
const float rotate_x = _height/2.0f - ypos;
const float rotate_y = _width/2.0f - xpos;
_camera.pitch(rotate_x * mouseSensitivity);
_camera.rotate(rotate_y * mouseSensitivity, glm::vec3(0.0f, 1.0f, 0.0f));
}
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
utils::Log(utils::CFormat(L"CoNE3D version: %%.%%.%%")
<< CONE3D_VERSION_MAJOR << CONE3D_VERSION_MINOR
<< CONE3D_VERSION_REVISION, utils::ELogLevel::Info);
try
{
// Initialize glfw library
if ( !glfwInit() ) {
throw std::runtime_error("Failed to initialize window library");
}
CWindowTest window(640, 360, L"CoNE3D Window Test");
window.Process();
// Clean up glfw library
glfwTerminate();
}
catch (const std::exception &ex)
{
utils::Log(ex.what(), utils::ELogLevel::Error);
}
return 0;
}
|
#include "TestFramework.h"
#include "treeface/gl/VertexTemplate.h"
#include <treecore/Array.h>
#include <treecore/ArrayRef.h>
#include <treecore/Variant.h>
using namespace treeface;
using namespace treecore;
void TestFramework::content()
{
TypedTemplate attr1{ "position", 3, TFGL_TYPE_FLOAT };
TypedTemplate attr2{ "color", 4, TFGL_TYPE_UNSIGNED_BYTE };
TypedTemplate attr3{ "normal", 3, TFGL_TYPE_FLOAT };
TypedTemplate attr4{ "tangent", 3, TFGL_TYPE_FLOAT };
VertexTemplate vtx_temp;
vtx_temp.add_attrib( attr1, false, 4 );
vtx_temp.add_attrib( attr2, false, 0 );
vtx_temp.add_attrib( attr3, false, 4 );
vtx_temp.add_attrib( attr4, false, 4 );
IS( vtx_temp.vertex_size(), 40 );
IS( vtx_temp.n_elems(), 13 );
IS( vtx_temp.n_attribs(), 4 );
IS( vtx_temp.get_elem_offset( 0 ), 0 );
IS( vtx_temp.get_elem_offset( 1 ), 4 );
IS( vtx_temp.get_elem_offset( 2 ), 8 );
IS( vtx_temp.get_elem_offset( 3 ), 12 );
IS( vtx_temp.get_elem_offset( 4 ), 13 );
IS( vtx_temp.get_elem_offset( 5 ), 14 );
IS( vtx_temp.get_elem_offset( 6 ), 15 );
IS( vtx_temp.get_elem_offset( 7 ), 16 );
IS( vtx_temp.get_elem_offset( 8 ), 20 );
IS( vtx_temp.get_elem_offset( 9 ), 24 );
IS( vtx_temp.get_elem_offset( 10 ), 28 );
IS( vtx_temp.get_elem_offset( 11 ), 32 );
IS( vtx_temp.get_elem_offset( 12 ), 36 );
IS( vtx_temp.get_elem_offset( 0, 0 ), 0 );
IS( vtx_temp.get_elem_offset( 0, 1 ), 4 );
IS( vtx_temp.get_elem_offset( 0, 2 ), 8 );
IS( vtx_temp.get_elem_offset( 1, 0 ), 12 );
IS( vtx_temp.get_elem_offset( 1, 1 ), 13 );
IS( vtx_temp.get_elem_offset( 1, 2 ), 14 );
IS( vtx_temp.get_elem_offset( 1, 3 ), 15 );
IS( vtx_temp.get_elem_offset( 2, 0 ), 16 );
IS( vtx_temp.get_elem_offset( 2, 1 ), 20 );
IS( vtx_temp.get_elem_offset( 2, 2 ), 24 );
IS( vtx_temp.get_elem_offset( 3, 0 ), 28 );
IS( vtx_temp.get_elem_offset( 3, 1 ), 32 );
IS( vtx_temp.get_elem_offset( 3, 2 ), 36 );
IS( vtx_temp.get_elem_type( 0 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 1 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 2 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 3 ), GL_UNSIGNED_BYTE );
IS( vtx_temp.get_elem_type( 4 ), GL_UNSIGNED_BYTE );
IS( vtx_temp.get_elem_type( 5 ), GL_UNSIGNED_BYTE );
IS( vtx_temp.get_elem_type( 6 ), GL_UNSIGNED_BYTE );
IS( vtx_temp.get_elem_type( 7 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 8 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 9 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 10 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 11 ), GL_FLOAT );
IS( vtx_temp.get_elem_type( 12 ), GL_FLOAT );
GLbyte* mem = (GLbyte*) malloc( vtx_temp.vertex_size() );
vtx_temp.set_value_at( mem, 0, var( 1.0 ) );
vtx_temp.set_value_at( mem, 1, var( 2.0 ) );
vtx_temp.set_value_at( mem, 2, var( 3.0 ) );
vtx_temp.set_value_at( mem, 3, var( 255 ) );
vtx_temp.set_value_at( mem, 4, var( 127 ) );
vtx_temp.set_value_at( mem, 5, var( 63 ) );
vtx_temp.set_value_at( mem, 6, var( 255 ) );
vtx_temp.set_value_at( mem, 7, var( 4.0 ) );
vtx_temp.set_value_at( mem, 8, var( 5.0 ) );
vtx_temp.set_value_at( mem, 9, var( 6.0 ) );
vtx_temp.set_value_at( mem, 10, var( 7.0 ) );
vtx_temp.set_value_at( mem, 11, var( 8.0 ) );
vtx_temp.set_value_at( mem, 12, var( 9.0 ) );
IS( *(float*) mem, 1.0 );
IS( *(float*) (mem + 4), 2.0 );
IS( *(float*) (mem + 8), 3.0 );
IS( *(GLubyte*) (mem + 12), 0xff );
IS( *(GLubyte*) (mem + 13), 0x7f );
IS( *(GLubyte*) (mem + 14), 0x3f );
IS( *(GLubyte*) (mem + 15), 0xff );
IS( *(float*) (mem + 16), 4.0 );
IS( *(float*) (mem + 20), 5.0 );
IS( *(float*) (mem + 24), 6.0 );
IS( *(float*) (mem + 28), 7.0 );
IS( *(float*) (mem + 32), 8.0 );
IS( *(float*) (mem + 36), 9.0 );
}
|
#ifndef OBJETO_H
#define OBJETO_H
#include <string>
#include <iostream>
#include <cmath>
#include "Shader.h"
using namespace std;
struct vertex {
float x, y, z;
float r, g, b;
float nx, ny, nz;
};
struct material {
float ka, kd, ks;
float expd, exps;
};
typedef unsigned int indexT;
class Objeto {
public:
Objeto(const camera &cam, string meshfilename):cam(cam) {
r = 1.0;
g = 1.0;
b = 1.0;
load(meshfilename);
mesh = meshfilename;
faceculling = false;
mat = new material;
mat->ka = 0.1;
mat->kd = mat->ks = 0.5;
mat->expd = mat->exps = 1.0;
}
~Objeto() {
delete vert;
delete ind;
delete mat;
}
bool faceculling;
void scale(float s) {
modelMatrix.scale(s, s, s);
}
void rotatey(int a) {
modelMatrix.rotatey(a);
}
void rotatez(int a) {
modelMatrix.rotatez(a);
}
void rotatex(int a) {
modelMatrix.rotatex(a);
}
void translate(float dx, float dy, float dz) {
modelMatrix.translate(dx, dy, dz);
}
void draw(const Shader *shader);
void defineMaterial(float ka, float kd, float expd, float ks, float exps);
void defineColor(float r, float g, float b);
protected:
private:
int nv, nf, ne;
float r, g, b;
string mesh;
mat44 modelMatrix;
const camera &cam;
vertex *vert;
indexT *ind;
material *mat;
GLuint iVBO, iIBO;
void load(string filename);
};
void Objeto::load(string filename) {
ifstream f(filename);
int i, j, k;
string s;
f >> s; // le a palavra "OFF"
f >> nv >> nf >> ne; // lê o nro de vértices, faces e arestas
vert = new vertex[nv];
ind = new indexT[3*nf];
// lê a posição dos pontos
for (i=0; i<nv; i++) f >> vert[i].x >> vert[i].y >> vert[i].z; // >> vert[i].r >> vert[i].g >> vert[i].b;
// lê os índices dos polígonos
for (i=0, j=0; i<nf; i++, j+=3) f >> k >> ind[j] >> ind[j+1] >> ind[j+2];
// lê as cores e zera as normais
for (i=0; i<nv; i++) {
vert[i].r = r;
vert[i].g = g;
vert[i].b = b;
vert[i].nx = 0.0;
vert[i].ny = 0.0;
vert[i].nz = 0.0;
}
// Calcular as normais
vertex *v1, *v2, *v3;
float ax, ay, az, bx, by, bz, nx, ny, nz, norm;
for(i = 0, j = 0; i<nf; i++) {
v1 = vert + ind[j++];
v2 = vert + ind[j++];
v3 = vert + ind[j++];
ax = v1->x-v2->x;
ay = v1->y-v2->y;
az = v1->z-v2->z;
bx = v1->x-v3->x;
by = v1->y-v3->y;
bz = v1->z-v3->z;
nx = ay*bz - az*by;
ny = az*bx - ax*bz;
nz = ax*by - ay*bx;
v1->nx += nx;
v1->ny += ny;
v1->nz += nz;
v2->nx += nx;
v2->ny += ny;
v2->nz += nz;
v3->nx += nx;
v3->ny += ny;
v3->nz += nz;
}
for (i=0; i<nv; i++) {
ax = vert[i].nx;
ay = vert[i].ny;
az = vert[i].nz;
norm = sqrt(ax*ax + ay*ay + az*az);
vert[i].nx = ax/norm;
vert[i].ny = ay/norm;
vert[i].nz = az/norm;
}
// Criação do VBO e IBO
glGenBuffers(1, &iVBO);
glBindBuffer(GL_ARRAY_BUFFER, iVBO);
glBufferData(GL_ARRAY_BUFFER, nv*sizeof(vertex), vert, GL_STATIC_DRAW);
glGenBuffers(1, &iIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3*nf*sizeof(indexT), ind, GL_STATIC_DRAW);
}
void Objeto::draw(const Shader *shader) {
glBindBuffer(GL_ARRAY_BUFFER, iVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), (void *)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), (void *)12);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), (void *)24);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iIBO);
if (faceculling) glEnable(GL_CULL_FACE);
else glDisable(GL_CULL_FACE);
const float coef[3] = {mat->ka, mat->kd, mat->ks};
const float exp[2] = {mat->expd, mat->exps};
shader->sendMaterial(coef,exp);
shader->sendMVP(modelMatrix.multleft(cam.mptr));
glDrawElements(GL_TRIANGLES, 3*nf, GL_UNSIGNED_INT, (GLvoid*)0);
}
void Objeto::defineMaterial(float ka, float kd, float expd, float ks, float exps){
mat->ka = ka;
mat->kd = kd;
mat->ks = ks;
mat->expd = expd;
mat->exps = exps;
}
void Objeto::defineColor(float r, float g, float b){
this->r = r;
this->g = g;
this->b = b;
load(mesh);
}
#endif // OBJETO_H
|
#include"Node.h"
#include"LR1Parser.h"
#include"DFA.h"
//################################词法分析器所需要的额外函数 #################################
string s5edgeJudge(string s) {
if (s != "\"" || s == "digit" || s == "letter") {
return "chars1";
}
else {
return s;
}
}
string s7edgeJudge(string s) {
if (s != "'" || s == "digit" || s == "letter") {
return "chars2";
}
else {
return s;
}
}
string convertInput(char c) {
if (isdigit(c)) {
return string("digit");
}
else if (isalnum(c)) {
return string("letter");
}
else {
return string(1, c);
}
}
int main() {
const string inputfile = "D:\\input.txt";
const string reportfile = "D:\\report.txt";
const string modelfile = "D:\\model.txt";
const string tokenfile = "D:\\token.txt";
vector<token> tokenstream = vector<token>();
//####################################### 词法分析模块 #######################################################//
//构造状态机
int stateNum = 10; // 有10个状态
string edges[] = { "_", "letter","digit",".", "\"","chars1","'","chars2" }; //chars1代表除了”之外的字符,chars2 代表除了‘之外的字符
//申请一个2维数组,初始化为-1
vector<int>** stateM = new vector<int>*[stateNum];
for (int i = 0; i < stateNum; i++) {
stateM[i] = new vector<int>[stateNum];
for (int j = 0; j < stateNum; j++) {
stateM[i][j] = vector<int>();
}
}
stateM[0][1] = vector<int>({ 0,1 });
stateM[1][1] = vector<int>({ 0,1,2 });
stateM[0][2] = vector<int>({ 2 });
stateM[2][2] = vector<int>({ 2 });
stateM[2][3] = vector<int>({ 3 });
stateM[3][4] = vector<int>({ 2 });
stateM[4][4] = vector<int>({ 2 });
stateM[0][5] = vector<int>({ 4 });
stateM[5][5] = vector<int>({ 5 });
stateM[5][6] = vector<int>({ 4 });
stateM[0][7] = vector<int>({ 6 });
stateM[7][8] = vector<int>({ 7 });
stateM[8][9] = vector<int>({ 6 });
DFA myDFA = DFA(); //终止符是空格
myDFA.initStates(stateNum, stateM, edges);
// 增加终止状态
myDFA.addTokenItem(1, 0, "id"); // 1状态是终态 , id(变量)
myDFA.addTokenItem(2, 1, "num"); //2 状态终态 , 数字
myDFA.addTokenItem(4, 2, "num"); //4 状态终态 , 数字
myDFA.addTokenItem(6, 3, "string"); //6 状态 ,字符串
myDFA.addTokenItem(9, 4, "char"); //9 状态 ,字符
//增加保留字
vector<string> keepWords= vector<string>({ "if","else","while","do","(",")","+","-","*","/", ";" ,"=","and","or","not",">","<",">=","<","==","!=" ,"true","false"
"id","num","then","{" ,"}" });
for (int i = 0; i < keepWords.size(); i++) {
myDFA.addKeepWord(keepWords[i], 5 + i);
}
// 附加边判断函数
myDFA.getState(7).setEdgeJudgeFunction(s7edgeJudge);
myDFA.getState(5).setEdgeJudgeFunction(s5edgeJudge);
//######################### 扫描文件模块
ifstream fin = ifstream();
fin.open("D:\\input.txt", ios::in);
if (!fin.is_open()) {
cout << "无法打开文件流" << endl;
return 0;
}
ofstream fout = ofstream();
fout.open(tokenfile, ios::out);
if (!fout.is_open()) {
cout << "无法打开文件流" << endl;
return 0;
}
string str;
char c;
bool isIgnore = false;
while (fin.get(c)) {
if ((c == ' ' || c == '\n' || c == '\t') && isIgnore == false) {
if (str == "") {
continue;
}
token t = myDFA.scan(str, convertInput);
tokenstream.push_back(t);
fout << t << endl;
str.clear();
continue;
}
else {
if (c == '\"') {
if (isIgnore == false) {
isIgnore = true;
}
else {
isIgnore = false;
}
}
str += c;
}
};
if (str != "") {
token t = myDFA.scan(str, convertInput);
tokenstream.push_back(t);
fout << t << endl;
}
fin.close();
//delete数组
for (int i = 0; i < stateNum; i++) {
if (stateM[i] != nullptr) {
delete[] stateM[i];
}
}
delete[] stateM;
//########################################语法分析模块####################################################
// 构造表达式,表达式定义的文法同 词法分析器 , 从表达式生成状态表
set<string> nonTerminators = set<string>({ "S1","S","E","EA","EO","rop","C","T","WD","I" });
set<string> terminators = set<string>({ "if","else","while","do","(",")","+","-","*","/", ";" ,"=","and","or","not",">","<",">=","<=","<","==","!=" ,"true","false",
"id","num","then","$","none","{","}" });
vector < vector<string>> productions = vector < vector<string>>();
productions.push_back(vector<string>({ "S1","S" }));
productions.push_back(vector<string>({ "S","id","=","E" ,";"}));
productions.push_back(vector<string>({ "S","S","S" }));
productions.push_back(vector<string>({ "S","T","{","S","}" }));
productions.push_back(vector<string>({ "S","C","{","S","}" }));
productions.push_back(vector<string>({ "T","C","{","S","}","else" }));
productions.push_back(vector<string>({ "C","if","(","E",")","then" }));
productions.push_back(vector<string>({ "S","WD","{","S","}" }));
productions.push_back(vector<string>({ "WD","while","(","E",")" ,"do"}));
productions.push_back(vector<string>({ "E","EA","E" }));
productions.push_back(vector<string>({ "E","EO","E" }));
productions.push_back(vector<string>({ "E","not","E" }));
productions.push_back(vector<string>({ "E","(","E",")" }));
productions.push_back(vector<string>({ "E","E","rop","E" }));
productions.push_back(vector<string>({ "EA","E","and" }));
productions.push_back(vector<string>({ "EO","E","or" }));
productions.push_back(vector<string>({ "E","id" }));
productions.push_back(vector<string>({ "E","true" }));
productions.push_back(vector<string>({ "E","false" }));
productions.push_back(vector<string>({ "E","num" }));
productions.push_back(vector<string>({ "rop",">" }));
productions.push_back(vector<string>({ "rop",">=" }));
productions.push_back(vector<string>({ "rop","<" }));
productions.push_back(vector<string>({ "rop","<=" }));
productions.push_back(vector<string>({ "rop","==" }));
productions.push_back(vector<string>({ "rop","!=" }));
productions.push_back(vector<string>({ "E","E" ,"+","E"}));
productions.push_back(vector<string>({ "E","E" ,"-","E" }));
productions.push_back(vector<string>({ "E","E" ,"*","E" }));
productions.push_back(vector<string>({ "E","E" ,"/","E" }));
LR1Parser myParser = LR1Parser(terminators, nonTerminators, productions);
/*
//#########################small demo ##################################
set<string> terminators = set<string>({"none","$","a","b","c","d"});
set<string> nonTerminators = set<string>({ "S1","S","A","B"});
vector < vector<string>> productions = vector < vector<string>>();
productions.push_back(vector<string>({ "S1","S" }));
productions.push_back(vector<string>({ "S","A","a" }));
productions.push_back(vector<string>({ "S","b","A","c" }));
productions.push_back(vector<string>({ "S","B","c" }));
productions.push_back(vector<string>({ "S","b","B","a" }));
productions.push_back(vector<string>({ "S","S","S" }));
productions.push_back(vector<string>({ "S","none" }));
productions.push_back(vector<string>({ "A","d" }));
productions.push_back(vector<string>({ "B","d" }));
LR1Parser myParser = LR1Parser(terminators, nonTerminators, productions);
*/
//设置初始状态
std::pair<string, int> p1 = make_pair("S1", 0);
vector<std::pair<string, int>> ps = vector<std::pair<string, int>>();
ps.push_back(p1);
vector<set<string>> followset = vector<set<string>>({ set<string>{"$"} });
myParser.initStates(ps, followset);
myParser.buildParserGraph();
myParser.buildParserTable();
// 解决二义性问题
vector < pair<int, pair<string, int>> >deleteOperations = vector < pair<int, pair<string, int>>>();
deleteOperations.push_back(make_pair(48, make_pair("id", 1))); // 83状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(47, make_pair("id", 1))); // 84状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(79, make_pair("id", 1))); // 84状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(48, make_pair("if", 1))); // 83状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(47, make_pair("if", 1))); // 84状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(79, make_pair("if", 1))); // 84状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(48, make_pair("while", 1))); // 83状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(47, make_pair("while", 1))); // 84状态下读入分号 ,删除产生式
deleteOperations.push_back(make_pair(79, make_pair("while", 1))); // 83状态下读入分号 ,删除产生式
//解决优先级和结合性带来的从图
deleteOperations.push_back(make_pair(33, make_pair("!=", 0))); //33 状态 S - > EA E ,优先级比and高保留产生式, 优先级 <= and 保留规约式
deleteOperations.push_back(make_pair(33, make_pair("+", 0))); //左结合保留归约式
deleteOperations.push_back(make_pair(33, make_pair("-", 0)));
deleteOperations.push_back(make_pair(33, make_pair("*", 0)));
deleteOperations.push_back(make_pair(33, make_pair("/", 0)));
deleteOperations.push_back(make_pair(33, make_pair("<", 0)));
deleteOperations.push_back(make_pair(33, make_pair("<=", 0)));
deleteOperations.push_back(make_pair(33, make_pair("==", 0)));
deleteOperations.push_back(make_pair(33, make_pair(">", 0)));
deleteOperations.push_back(make_pair(33, make_pair(">=", 0)));
deleteOperations.push_back(make_pair(33, make_pair("and", 1)));
deleteOperations.push_back(make_pair(33, make_pair("or", 1)));
deleteOperations.push_back(make_pair(34, make_pair("!=", 0))); //34 状态 S - > E0 E ,优先级比or高保留产生式(0), 优先级 <= or 保留规约式(1)
deleteOperations.push_back(make_pair(34, make_pair("+", 0))); //左结合保留归约式
deleteOperations.push_back(make_pair(34, make_pair("-", 0)));
deleteOperations.push_back(make_pair(34, make_pair("*", 0)));
deleteOperations.push_back(make_pair(34, make_pair("/", 0)));
deleteOperations.push_back(make_pair(34, make_pair("<", 0)));
deleteOperations.push_back(make_pair(34, make_pair("<=", 0)));
deleteOperations.push_back(make_pair(34, make_pair("==", 0)));
deleteOperations.push_back(make_pair(34, make_pair(">", 0)));
deleteOperations.push_back(make_pair(34, make_pair(">=", 0)));
deleteOperations.push_back(make_pair(34, make_pair("and", 0)));
deleteOperations.push_back(make_pair(34, make_pair("or", 1)));
deleteOperations.push_back(make_pair(35, make_pair("!=", 1))); //35 状态 S - > not E ,优先级比not高保留产生式(0), 优先级 <= not 保留规约式(1)
deleteOperations.push_back(make_pair(35, make_pair("+", 1))); //左结合保留归约式
deleteOperations.push_back(make_pair(35, make_pair("-", 1)));
deleteOperations.push_back(make_pair(35, make_pair("*", 1)));
deleteOperations.push_back(make_pair(35, make_pair("/", 1)));
deleteOperations.push_back(make_pair(35, make_pair("<", 1)));
deleteOperations.push_back(make_pair(35, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(35, make_pair("==", 1)));
deleteOperations.push_back(make_pair(35, make_pair(">", 1)));
deleteOperations.push_back(make_pair(35, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(35, make_pair("and", 1)));
deleteOperations.push_back(make_pair(35, make_pair("or", 1)));
deleteOperations.push_back(make_pair(37, make_pair("!=", 1))); //37 状态 S - > E rop E (rop是> < >= <=, ==, !=) ,优先级比not高保留产生式(0), 优先级 <= not 保留规约式(1)
deleteOperations.push_back(make_pair(37, make_pair("+", 0))); //左结合保留归约式
deleteOperations.push_back(make_pair(37, make_pair("-", 0)));
deleteOperations.push_back(make_pair(37, make_pair("*", 0)));
deleteOperations.push_back(make_pair(37, make_pair("/", 0)));
deleteOperations.push_back(make_pair(37, make_pair("<", 1)));
deleteOperations.push_back(make_pair(37, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(37, make_pair("==", 1)));
deleteOperations.push_back(make_pair(37, make_pair(">", 1)));
deleteOperations.push_back(make_pair(37, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(37, make_pair("and", 0)));
deleteOperations.push_back(make_pair(37, make_pair("or", 0)));
deleteOperations.push_back(make_pair(38, make_pair("!=", 1))); //38 状态 S - > E + E ,优先级比+高保留产生式(0), 优先级 <=+ 保留规约式(1)
deleteOperations.push_back(make_pair(38, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(38, make_pair("-", 1)));
deleteOperations.push_back(make_pair(38, make_pair("*", 0)));
deleteOperations.push_back(make_pair(38, make_pair("/", 0)));
deleteOperations.push_back(make_pair(38, make_pair("<", 1)));
deleteOperations.push_back(make_pair(38, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(38, make_pair("==", 1)));
deleteOperations.push_back(make_pair(38, make_pair(">", 1)));
deleteOperations.push_back(make_pair(38, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(38, make_pair("and", 1)));
deleteOperations.push_back(make_pair(38, make_pair("or", 1)));
deleteOperations.push_back(make_pair(39, make_pair("!=", 1))); //39 状态 S - > E - E ,优先级比+高保留产生式(0), 优先级 <= - 保留规约式(1)
deleteOperations.push_back(make_pair(39, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(39, make_pair("-", 1)));
deleteOperations.push_back(make_pair(39, make_pair("*", 0)));
deleteOperations.push_back(make_pair(39, make_pair("/", 0)));
deleteOperations.push_back(make_pair(39, make_pair("<", 1)));
deleteOperations.push_back(make_pair(39, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(39, make_pair("==", 1)));
deleteOperations.push_back(make_pair(39, make_pair(">", 1)));
deleteOperations.push_back(make_pair(39, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(39, make_pair("and", 1)));
deleteOperations.push_back(make_pair(39, make_pair("or", 1)));
deleteOperations.push_back(make_pair(40, make_pair("!=", 1))); //40 状态 S - > E * E ,优先级比+高保留产生式(0), 优先级 <= - 保留规约式(1)
deleteOperations.push_back(make_pair(40, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(40, make_pair("-", 1)));
deleteOperations.push_back(make_pair(40, make_pair("*", 1)));
deleteOperations.push_back(make_pair(40, make_pair("/", 1)));
deleteOperations.push_back(make_pair(40, make_pair("<", 1)));
deleteOperations.push_back(make_pair(40, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(40, make_pair("==", 1)));
deleteOperations.push_back(make_pair(40, make_pair(">", 1)));
deleteOperations.push_back(make_pair(40, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(40, make_pair("and", 1)));
deleteOperations.push_back(make_pair(40, make_pair("or", 1)));
deleteOperations.push_back(make_pair(41, make_pair("!=", 1))); //41 状态 S - > E / E ,优先级比/高保留产生式(0), 优先级 <= /保留规约式(1)
deleteOperations.push_back(make_pair(41, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(41, make_pair("-", 1)));
deleteOperations.push_back(make_pair(41, make_pair("*", 1)));
deleteOperations.push_back(make_pair(41, make_pair("/", 1)));
deleteOperations.push_back(make_pair(41, make_pair("<", 1)));
deleteOperations.push_back(make_pair(41, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(41, make_pair("==", 1)));
deleteOperations.push_back(make_pair(41, make_pair(">", 1)));
deleteOperations.push_back(make_pair(41, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(41, make_pair("and", 1)));
deleteOperations.push_back(make_pair(41, make_pair("or", 1)));
//
deleteOperations.push_back(make_pair(86, make_pair("!=", 0))); //86 状态 S - > EA E ,优先级比and高保留产生式, 优先级 <= and 保留规约式
deleteOperations.push_back(make_pair(86, make_pair("+", 0))); //左结合保留归约式
deleteOperations.push_back(make_pair(86, make_pair("-", 0)));
deleteOperations.push_back(make_pair(86, make_pair("*", 0)));
deleteOperations.push_back(make_pair(86, make_pair("/", 0)));
deleteOperations.push_back(make_pair(86, make_pair("<", 0)));
deleteOperations.push_back(make_pair(86, make_pair("<=", 0)));
deleteOperations.push_back(make_pair(86, make_pair("==", 0)));
deleteOperations.push_back(make_pair(86, make_pair(">", 0)));
deleteOperations.push_back(make_pair(86, make_pair(">=", 0)));
deleteOperations.push_back(make_pair(86, make_pair("and", 1)));
deleteOperations.push_back(make_pair(86, make_pair("or", 1)));
deleteOperations.push_back(make_pair(87, make_pair("!=", 0))); //87 状态 S - > E0 E ,优先级比or高保留产生式(0), 优先级 <= or 保留规约式(1)
deleteOperations.push_back(make_pair(87, make_pair("+", 0))); //左结合保留归约式
deleteOperations.push_back(make_pair(87, make_pair("-", 0)));
deleteOperations.push_back(make_pair(87, make_pair("*", 0)));
deleteOperations.push_back(make_pair(87, make_pair("/", 0)));
deleteOperations.push_back(make_pair(87, make_pair("<", 0)));
deleteOperations.push_back(make_pair(87, make_pair("<=", 0)));
deleteOperations.push_back(make_pair(87, make_pair("==", 0)));
deleteOperations.push_back(make_pair(87, make_pair(">", 0)));
deleteOperations.push_back(make_pair(87, make_pair(">=", 0)));
deleteOperations.push_back(make_pair(87, make_pair("and", 0)));
deleteOperations.push_back(make_pair(87, make_pair("or", 1)));
deleteOperations.push_back(make_pair(88, make_pair("!=", 1))); //88 状态 S - > not E ,优先级比not高保留产生式(0), 优先级 <= not 保留规约式(1)
deleteOperations.push_back(make_pair(88, make_pair("+", 1))); //左结合保留归约式
deleteOperations.push_back(make_pair(88, make_pair("-", 1)));
deleteOperations.push_back(make_pair(88, make_pair("*", 1)));
deleteOperations.push_back(make_pair(88, make_pair("/", 1)));
deleteOperations.push_back(make_pair(88, make_pair("<", 1)));
deleteOperations.push_back(make_pair(88, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(88, make_pair("==", 1)));
deleteOperations.push_back(make_pair(88, make_pair(">", 1)));
deleteOperations.push_back(make_pair(88, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(88, make_pair("and", 1)));
deleteOperations.push_back(make_pair(88, make_pair("or", 1)));
deleteOperations.push_back(make_pair(89, make_pair("!=", 1))); //89 状态 S - > E rop E (rop是> < >= <=, ==, !=) ,优先级比not高保留产生式(0), 优先级 <= not 保留规约式(1)
deleteOperations.push_back(make_pair(89, make_pair("+", 0))); //左结合保留归约式
deleteOperations.push_back(make_pair(89, make_pair("-", 0)));
deleteOperations.push_back(make_pair(89, make_pair("*", 0)));
deleteOperations.push_back(make_pair(89, make_pair("/", 0)));
deleteOperations.push_back(make_pair(89, make_pair("<", 1)));
deleteOperations.push_back(make_pair(89, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(89, make_pair("==", 1)));
deleteOperations.push_back(make_pair(89, make_pair(">", 1)));
deleteOperations.push_back(make_pair(89, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(89, make_pair("and", 0)));
deleteOperations.push_back(make_pair(89, make_pair("or", 0)));
deleteOperations.push_back(make_pair(90, make_pair("!=", 1))); //90 状态 S - > E + E ,优先级比+高保留产生式(0), 优先级 <=+ 保留规约式(1)
deleteOperations.push_back(make_pair(90, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(90, make_pair("-", 1)));
deleteOperations.push_back(make_pair(90, make_pair("*", 0)));
deleteOperations.push_back(make_pair(90, make_pair("/", 0)));
deleteOperations.push_back(make_pair(90, make_pair("<", 1)));
deleteOperations.push_back(make_pair(90, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(90, make_pair("==", 1)));
deleteOperations.push_back(make_pair(90, make_pair(">", 1)));
deleteOperations.push_back(make_pair(90, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(90, make_pair("and", 1)));
deleteOperations.push_back(make_pair(90, make_pair("or", 1)));
deleteOperations.push_back(make_pair(91, make_pair("!=", 1))); //91 状态 S - > E - E ,优先级比+高保留产生式(0), 优先级 <= - 保留规约式(1)
deleteOperations.push_back(make_pair(91, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(91, make_pair("-", 1)));
deleteOperations.push_back(make_pair(91, make_pair("*", 0)));
deleteOperations.push_back(make_pair(91, make_pair("/", 0)));
deleteOperations.push_back(make_pair(91, make_pair("<", 1)));
deleteOperations.push_back(make_pair(91, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(91, make_pair("==", 1)));
deleteOperations.push_back(make_pair(91, make_pair(">", 1)));
deleteOperations.push_back(make_pair(91, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(91, make_pair("and", 1)));
deleteOperations.push_back(make_pair(91, make_pair("or", 1)));
deleteOperations.push_back(make_pair(92, make_pair("!=", 1))); //92 状态 S - > E * E ,优先级比+高保留产生式(0), 优先级 <= - 保留规约式(1)
deleteOperations.push_back(make_pair(92, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(92, make_pair("-", 1)));
deleteOperations.push_back(make_pair(92, make_pair("*", 1)));
deleteOperations.push_back(make_pair(92, make_pair("/", 1)));
deleteOperations.push_back(make_pair(92, make_pair("<", 1)));
deleteOperations.push_back(make_pair(92, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(92, make_pair("==", 1)));
deleteOperations.push_back(make_pair(92, make_pair(">", 1)));
deleteOperations.push_back(make_pair(92, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(92, make_pair("and", 1)));
deleteOperations.push_back(make_pair(92, make_pair("or", 1)));
deleteOperations.push_back(make_pair(93, make_pair("!=", 1))); //93状态 S - > E / E ,优先级比/高保留产生式(0), 优先级 <= /保留规约式(1)
deleteOperations.push_back(make_pair(93, make_pair("+", 1))); //左结合保留归约式 (1)
deleteOperations.push_back(make_pair(93, make_pair("-", 1)));
deleteOperations.push_back(make_pair(93, make_pair("*", 1)));
deleteOperations.push_back(make_pair(93, make_pair("/", 1)));
deleteOperations.push_back(make_pair(93, make_pair("<", 1)));
deleteOperations.push_back(make_pair(93, make_pair("<=", 1)));
deleteOperations.push_back(make_pair(93, make_pair("==", 1)));
deleteOperations.push_back(make_pair(93, make_pair(">", 1)));
deleteOperations.push_back(make_pair(93, make_pair(">=", 1)));
deleteOperations.push_back(make_pair(93, make_pair("and", 1)));
deleteOperations.push_back(make_pair(93, make_pair("or", 1)));
myParser.sloveAmbiguousTable(deleteOperations);
ofstream fout2 = ofstream();
fout2.open(modelfile, ios::out);
if (!fout2.is_open()) {
cout << "无法打开模型文本" << endl;
return false;
}
myParser.outParserModel(fout2);
fout2.close();
// 进行语法分析
myParser.scanTokenStream(tokenstream, reportfile);
system("pause");
return 0;
}
/*
// 构造表达式,表达式定义的文法同 词法分析器 , 从表达式生成状态表
set<string> nonTerminators = set<string>({ "S","A","B","S1" });
set<string> terminators = set<string>({ "a","b","none","$","c","d" });
vector<string> production0 = vector<string>({ "S1","S", });
vector<string> production1 = vector<string>({ "S","A","a"});
vector<string> production2 = vector<string>({ "S","b","A","c" });
vector<string> production3 = vector<string>({ "S","B","c" });
vector<string> production4 = vector<string>({ "S","b","B","a" });
vector<string> production5 = vector<string>({ "A","d" });
vector<string> production6 = vector<string>({ "B","d", });
vector < vector<string>> productions = vector < vector<string>>(
{
production0,production1,production2,production3,production4,production5,production6
});
*/
|
#include<iostream>
// Принимаем знак оператора от пользователя
char getMatematicalOperation() {
while (true) {
std::cout << "Enter one of the following: +, -, *, /: ";
char op;
std::cin >> op;
// Переменные типа char могут принимать любые символы из
// пользовательского ввода, поэтому нам не стоит беспокоиться по поводу
// возникновения неудачного извлечения
std::cin.ignore(32767, '\n'); // удаляем лишний балласт
// Выполняем проверку пользовательского ввода
if (op == '+' || op == '-' || op == '*' || op == '/') {
return op; // возвращаем обратно в caller (main)
}
else { // в противном случае, сообщаем пользователю что что-то пошло не так
std::cout << "Oops! That input is invalid. Please try again.\n";
}
}
}
|
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> pii;
#define ll long long
#define fi first
#define se second
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a))
#define FOREACH(a, b) for (auto&(a) : (b))
#define REP(i, n) FOR(i, 0, n)
#define REPN(i, n) FORN(i, 1, n)
#define dbg(x) cout << (#x) << " is " << (x) << endl;
#define dbg2(x, y) cout << (#x) << " is " << (x) << " and " << (#y) << " is " << y << endl;
#define dbgarr(x, sz) \
for (int asdf = 0; asdf < (sz); asdf++) cout << x[asdf] << ' '; \
cout << endl;
#define dbgarr2(x, rose, colin) \
for (int asdf2 = 0; asdf2 < rose; asdf2++) { \
dbgarr(x[asdf2], colin); \
}
#define dbgitem(x) \
for (auto asdf = x.begin(); asdf != x.end(); asdf++) cout << *asdf << ' '; \
cout << endl;
const int mod = 1e9 + 7;
int n, A[200000];
struct Solution {
int solve() {
int pl[200000], nr[200001] = {0}, pos = 0, neg = 0, res = n;
REP(i, n) {
pl[i] = pos += A[i] >= 0;
nr[n - i - 1] = neg += A[n - 1 - i] <= 0;
}
REP(i, n - 1) { // day i = last negative day
res = min(res, pl[i] + nr[i + 1]);
}
return res;
}
};
int main() {
ifstream fin;
ios::sync_with_stdio(false);
fin.open("input.txt");
fin >> n;
ofstream fout;
fout.open("output.txt");
REP(i, n)
fin >> A[i];
Solution test;
auto res = test.solve();
fout << res << endl;
}
|
#pragma once
namespace KafkaZ {
enum class PollStatus { Message, Error, EndOfPartition, Empty, TimedOut };
}
|
#ifndef SECONDSERVICEIMPL_H_
#define SECONDSERVICEIMPL_H_
#include <iostream>
#include "SecondService.h"
using namespace ::thrift::multiplex::demo;
class SecondServiceHandler : virtual public SecondServiceIf
{
public:
SecondServiceHandler()
{
// Your initialization goes here
}
void blahBlah()
{
// Your implementation goes here
std::cout << "I am service2" << std::endl;
}
};
#endif
|
#ifndef file_io_h
#define file_io_h
#include <exception>
#include <vector>
#include <string>
#include <fstream>
#include <streambuf>
#include "stb/stb_image.h"
namespace avl
{
inline std::vector<uint8_t> read_file_binary(const std::string pathToFile)
{
FILE * f = fopen(pathToFile.c_str(), "rb");
if (!f)
throw std::runtime_error("file not found");
fseek(f, 0, SEEK_END);
size_t lengthInBytes = ftell(f);
fseek(f, 0, SEEK_SET);
std::vector<uint8_t> fileBuffer(lengthInBytes);
size_t elementsRead = fread(fileBuffer.data(), 1, lengthInBytes, f);
if (elementsRead == 0 || fileBuffer.size() < 4)
throw std::runtime_error("error reading file or file too small");
fclose(f);
return fileBuffer;
}
inline std::string read_file_text(const std::string & pathToFile)
{
std::ifstream t(pathToFile);
std::string str ((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
return str;
}
inline std::vector<uint8_t> load_image_data(const std::string & path)
{
auto binaryFile = read_file_binary(path);
int width, height, nBytes;
auto data = stbi_load_from_memory(binaryFile.data(), (int)binaryFile.size(), &width, &height, &nBytes, 0);
std::vector<uint8_t> d(width * height * nBytes);
memcpy(d.data(), data, nBytes * width * height);
stbi_image_free(data);
return d;
}
}
#endif // file_io_h
|
// https://www.codechef.com/problems/GCDQ
/******************************************
* AUTHOR : Abhishek Naidu *
* NICK : abhisheknaiidu *
******************************************/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define all(n) n.begin(),n.end()
#define REP(i,a,n) for (int i=a; i<=n; i++)
#define N 101
#define pii pair<int,int>
#define vi vector<int>
#define mii map<int,int>
#define ps(x,y) fixed<<setprecision(y)<<x
#define mk(arr,n,type) type *arr=new type[n];
#define w(x) int x; cin>>x; while(x--)
#define pqb priority_queue<int>
#define pqs priority_queue<int,vi,greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define f first
#define s second
#define int long long int
#define pb push_back
#define mp make_pair
#define inf 1e18
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
int pre[100005], suf[100005];
int a[100001];
// STEP 1
// Approach to solve this problem -
// To answer the query L to R
// find out GCD of elements 1 to L-1 = g1
// then find out the GCD of elements from
// R+1 to N = g2
// Answer will be now = GCD(g1,g2)
// STEP 2
// Prepare prefix and suffix array
// Pre[] = array to store gcd of first i elements at pos i
// Pre[i] = gcd(a[1],a[2],... a[i])
// Suf[] = array to store gcd of elements from i to N
// Suf[i] = gcd(a[i], a[i+1] .... a[N])
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b );
}
int32_t main()
{
abhisheknaiidu();
w(x) {
int n, q;
cin >> n >> q;
REP(i, 1, n) cin >> a[i];
pre[0] = suf[n + 1] = 0;
// to initialize prefix array
REP(i, 1, n) pre[i] = gcd(pre[i - 1], a[i]);
// to inialize suffix array
for (int i = n; i >= 1; i--)
suf[i] = gcd(a[i], suf[i + 1]);
while (q--) {
int l, r;
cin >> l >> r;
cout << gcd(pre[l - 1], suf[r + 1]) << endl;
}
}
return 0;
}
|
#include <iostream>
#define ll unsigned long long
using namespace std;
int mod1e10(long long v) {
return (int) (v % 1000000000);
}
struct vertex {
int key;
int height;
ll sLeft, sRight;
vertex *left, *right;
};
vertex *make_v(int value) {
auto *v = new vertex;
v->key = value;
v->left = v->right = nullptr;
v->height = 1;
v->sLeft = v->sRight = 0;
return v;
}
class binaryTree {
public:
void print() {
print(head);
}
ll lrSum(int l, int r) {
vertex *mid = findMid(head, l, r);
if (mid == nullptr) {
return 0;
}
ll s = mid->sLeft + mid->sRight + mid->key;
return lrSum(s, mid, l, r);
}
vertex *find(int x) {
return find(head, x);
}
void insert(int x) {
if (head == nullptr)
head = make_v(x);
else if (find(x) == nullptr)
head = insert(head, x);
}
private:
vertex *head;
static vertex *findMid(vertex *mid, int l, int r) {
if (mid == nullptr)
return nullptr;
if (mid->key >= l && mid->key <= r) {
return mid;
}
if (mid->key > r)
return findMid(mid->left, l, r);
else
return findMid(mid->right, l, r);
}
static ll lrSum(ll s, vertex *v, int l, int r) {
vertex *temp = v;
while (temp != nullptr) {
if (temp->key == l) {
s -= temp->sLeft;
break;
}
if (temp->key < l) {
s -= (temp->sLeft + temp->key);
temp = temp->right;
} else {
temp = temp->left;
}
}
temp = v;
while (temp != nullptr) {
if (temp->key == r) {
s -= temp->sRight;
break;
}
if (temp->key > r) {
s -= (temp->sRight + temp->key);
temp = temp->left;
} else {
temp = temp->right;
}
}
return s;
}
static vertex *lowLeftRotate(vertex *v) {
vertex *temp = v->right;
v->right = temp->left;
temp->left = v;
setHeight(v);
setHeight(temp);
return temp;
}
static vertex *lowRightRotate(vertex *v) {
vertex *temp = v->left;
v->left = temp->right;
temp->right = v;
setHeight(v);
setHeight(temp);
return temp;
}
static vertex *bigLeftRotate(vertex *v) {
v->right = lowRightRotate(v->right);
return lowLeftRotate(v);
}
static vertex *bigRightRotate(vertex *v) {
v->left = lowLeftRotate(v->left);
return lowRightRotate(v);
}
static vertex *balance(vertex *v) {
if (v == nullptr)
return v;
setHeight(v);
int b = getBalance(v);
if (b == -2) {
if (getBalance(v->right) > 0)
return bigLeftRotate(v);
else
return lowLeftRotate(v);
} else if (b == 2) {
if (getBalance(v->left) < 0)
return bigRightRotate(v);
else
return lowRightRotate(v);
}
return v;
}
static void setHeight(vertex *v) {
v->height = max(getHeight(v->left), getHeight(v->right)) + 1;
v->sLeft = v->left ? v->left->sLeft + v->left->sRight + v->left->key : 0;
v->sRight = v->right ? v->right->sLeft + v->right->sRight + v->right->key : 0;
}
static int getBalance(vertex *v) {
return getHeight(v->left) - getHeight(v->right);
}
static int getHeight(vertex *v) {
return v != nullptr ? v->height : 0;
}
static void print(vertex *v) {
if (v != nullptr) {
cout << v->key << endl;
print(v->left);
print(v->right);
}
}
static vertex *find(vertex *v, int x) {
if (v == nullptr || v->key == x)
return v;
if (x < v->key)
return find(v->left, x);
else
return find(v->right, x);
}
static vertex *mini(vertex *v) {
if (v->left == nullptr)
return v;
return mini(v->left);
}
static vertex *maxi(vertex *v) {
if (v->right == nullptr)
return v;
return maxi(v->right);
}
static vertex *insert(vertex *v, int x) {
if (v == nullptr)
return make_v(x);
else if (x < v->key)
v->left = insert(v->left, x);
else
v->right = insert(v->right, x);
return balance(v);
}
};
int main() {
binaryTree bt{};
string inp;
int n;
cin >> n;
long long last = -1;
for (int i = 0; i < n; i++) {
cin >> inp;
if (inp == "+") {
int value;
cin >> value;
if (last != -1) {
bt.insert(mod1e10(value + last));
} else {
bt.insert(value);
}
last = -1;
} else {
int l, r;
cin >> l >> r;
last = (long long) bt.lrSum(l, r);
cout << last << endl;
}
}
return 0;
}
|
#include<cstdio>
#include<cstring>
using namespace std;
int main(){
//input
char name[10];
scanf("%s",&name);
//output
printf("Hello %s",name);
return 0;
}
|
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* left = nullptr;
Node* right = nullptr;
};
Node* newNode(int data){
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = nullptr;
return temp;
}
Node* constructTreeutil(int pre[], int* preIndex, int low, int high, int size){
if(*preIndex >= size || low > high)
return nullptr;
Node* root = newNode(pre[*preIndex]);
*preIndex = *preIndex + 1;
if(low == high)
return root;
int i;
for(i = low; i<= high; i++){
if(pre[i] > root->data)
break;
}
root->left = constructTreeutil(pre, preIndex, *preIndex, i-1, size);
root->right = constructTreeutil(pre, preIndex, i, high, size);
return root;
}
Node* constructTheTree(int pre[], int size){
int preIndex = 0;
return constructTreeutil(pre, &preIndex, 0, size-1, size);
}
void printInorder(Node* node){
if(node == nullptr)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
int main(){
int pre[6] = {10,5,1,7,40,50};
int size = sizeof(pre)/ sizeof(int);
Node* root = constructTheTree(pre, size);
printInorder(root);
return 0;
}
|
//本题目比较特殊,易超时, 用了dj算法堆优化+邻接表
//但要注意此题,需要枚举每一个点
//并求所有奶牛到达此点的距离总和
//再将求出的和值找出最小值,并输出.
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
const int MAXX=2147483647;//最大值
using namespace std;
struct line
{
int be,af,we;//分存前点 后点 权重
int next;
}l[3000];
struct p
{
int num,diss;
bool operator < (const p &a) const
{
return diss > a.diss;
}
};
int head[810];
int num=0;
int dis[810];//存最小距离
bool f[810];
int cow[810];
int n1,m,n,x;
int sum,minn=MAXX;
void add(int bee,int aff,int wee)//邻接表加入元素
{
l[++num].next=head[bee];
l[num].be=bee;
l[num].af=aff;
l[num].we=wee;
head[bee]=num;
}
void dj(int s);
int main()
{
scanf("%d%d%d",&n1,&n,&m);//输入
for(int i=1;i<=n1;i++)//输入奶牛数,并将其累加到cow数组中
{
scanf("%d",&x);
cow[x]++;
}
for(int i=0;i<m;i++)//输入边
{
int bee,aff,wee;
scanf("%d%d%d",&bee,&aff,&wee);
add(bee,aff,wee);//注意双向
add(aff,bee,wee);
}
for(int i=1;i<=n;i++)//以每一个点为起点,都找一遍
dj(i);
printf("%d",minn);//输出 最小值
}
void dj(int s)
{
memset(f,0,sizeof(f));
priority_queue <p> q;
p tmp;
tmp.num=s,tmp.diss=0;
for(int i=1;i<=n;i++)
dis[i]=MAXX;//赋极值
dis[s]=0;//初始化
q.push(tmp);
while(!q.empty())
{
int topp=q.top().num;
q.pop();
if(f[topp])
continue;
f[topp]=1;
for(int j=head[topp];j;j=l[j].next)//找topp点的临点,并进行比较
{
if(dis[l[j].af] > dis[topp]+l[j].we && !f[l[j].af])
{
dis[l[j].af] = dis[topp]+l[j].we;
tmp.num=l[j].af;
tmp.diss=dis[l[j].af];
q.push(tmp);//将tmp加入队列中
}
}
}
for(int i=1;i<=n;i++)
sum+=dis[i]*cow[i];//计算总距离和
minn=min(sum,minn);
sum=0;
}
|
#include "ListChats.h"
ListChats::ListChats() {}
std::string ListChats::encode() const {
parser->clear();
return parser->getJson();
}
void ListChats::decode(const std::string &jsonStr) {
parser->setJson(jsonStr);
ChatItem chatItem;
for (const auto& item : parser->getArrayJsonStr(KeyWords::chats)) {
chatItem.decode(item);
chats.push_back(chatItem);
}
}
|
#ifndef vector_h
#define vector_h
#include <iostream>
#include <memory>
#include <string>
#include "vectoBase.h"
template <typename T, typename A = std::allocator<T>>
class vector : private vector_base<T, A>
{
A alloc;
int sz;
T *elem;
int space;
void copy(const vector &arg);
public:
vector() : sz{0}, elem{nullptr}, space{0} {}
explicit vector(int s) : sz{s}, elem{alloc.allocate(s)}, space{s}
{
for (int i = 0; i < sz; ++i)
alloc.construct(elem + i, T());
}
vector(const vector &);
vector &operator=(const vector &);
~vector()
{
for (int i = 0; i < sz; ++i)
{
alloc.destroy(elem + i);
}
alloc.deallocate(elem, sz);
}
T &at(int n);
const T &at(int n) const;
T &operator[](int n) { return elem[n]; }
const T &operator[](int n) const { return elem[n]; };
int size() const { return sz; }
int capacity() const { return space; }
void resize(int newsize, T val = T());
void push_back(const T &d);
void reserve(int newalloc);
};
template <class T, class A>
vector<T, A>::vector(const vector &arg)
: sz{arg.sz}, space{arg.sz}, elem{alloc.allocate(arg.space)}
{
copy(arg);
}
template <class T, class A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
if (this == &a)
return *this;
if (a.sz <= space)
{
for (int i = 0; i < a.sz; ++i)
elem[i] = a.elem[i];
sz = a.sz;
return *this;
}
T *p = alloc.allocate(a.space);
for (int i = 0; i < a.sz; i++)
alloc.construct(&p[i], a.elem[i]);
for (int i = 0; i < sz; i++)
alloc.destroy(&elem[i]);
alloc.deallocate(elem, space);
space = sz = a.sz;
elem = p;
return *this;
}
template <class T, class A>
void vector<T, A>::copy(const vector &arg)
{
for (int i = 0; i < arg.sz; i++)
alloc.construct(elem + i, arg[i]);
}
template <typename T, typename A>
T &vector<T, A>::at(int n)
{
if (n < 0 || sz <= n)
{
std::string s = "Wrong index";
throw std::out_of_range(s);
}
return elem[n];
}
template <typename T, typename A>
const T &vector<T, A>::at(int n) const
{
if (n < 0 || sz <= n)
{
std::string s = "Wrong index";
throw std::out_of_range(s);
}
return elem[n];
}
template <typename T, typename A>
void vector<T, A>::reserve(int newalloc)
{
if (newalloc <= this->space)
return;
vector_base<T, A> b(this->alloc, newalloc);
std::uninitialized_copy(elem, elem + sz, b.elem);
b.sz = sz;
T *temp = this->elem;
int temp_space = this->space;
this->space = newalloc;
this->elem = b.elem;
for (int i = 0; i < this->sz; ++i)
this->alloc.destroy(temp + i);
b.elem = temp;
b.space = temp_space;
}
template <typename T, typename A>
void vector<T, A>::resize(int newsize, T val) //
{
reserve(newsize);
for (int i = sz; i < newsize; ++i)
alloc.construct(elem + i, val);
for (int i = newsize; i < sz; ++i)
alloc.destroy(elem + i);
sz = newsize;
}
template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
if (space == 0)
reserve(8);
else
{
if (sz == space)
{
reserve(2 * space);
}
}
alloc.construct(elem + sz, val);
++sz;
};
#endif
|
#ifndef VECTOR_H
#define VECTOR_H
#include "global.h"
class Vector
{
public:
Vector();
static vector<float> direction(vector<float> a, vector<float> b);
static vector<float> normal(vector<float> a, vector<float> b);
static float absolute(vector<float> a);
static vector<float> normalize(vector<float> a);
static std::vector<float> vectorIntersection(std::vector<float> paramA, std::vector<float> paramB);
};
#endif // VECTOR_H
|
#include<iostream>
using namespace std;
#include<string>
#include"Employee.h"
const int kMaxEmployees=100;
const int kFirstEmployeeNumber=1000;
class Database
{
public:
Database();
~Database();
Employee& addEmployee(string inFirstName,string inLastName);
Employee& getEmployee(int inEmployeeNumber);
Employee& getEmployee(string inFirstName,string inLastName);
void displayAll();
void displayCurrent();
void displayFormer();
protected:
Employee mEmployees[kMaxEmployees];
int mNextSlot;
int mNextEmployeeNumber;
};
|
#include <iostream>
#include <fstream>
using namespace std;
// FIXME: not working
int main() {
// C++代码里,想在某个参数中启用多个选项,基本都是通过位运算的或
// 例如我想设置只读和在末尾打开的模式,就写成ios::in | ios::ate
// 这是因为这些FLAG都是仅有一位是1,从1、2、4、8..往后排列,所以或运算不会互相干扰
// 想判断某个mode是否开启,就用(mode && ios::in) == 1 去判断
// ios::ate: at the end, 表示打开时文件指针定位到末尾
// ifstream f = ifstream("~/.gitconfig", ios::in | ios::beg);
ifstream f = ifstream("~/.apple_dance", ios::in | ios::beg);
system("pwd");
char buff;
while (f >> buff) {
cout << buff;
}
// string line;
// while (getline(f, line)) {
// cout << line << endl;
// }
// f.close();
return 0;
}
|
/***************************************************************************
* Vec2.h *
* *
* Vec2 is a trivial encapsulation of 2D floating-point coordinates. *
* It has all of the obvious operators defined as inline functions. *
* *
* History: *
* 04/01/2003 Initial coding. *
* *
***************************************************************************/
#ifndef __VEC2_INCLUDED__
#define __VEC2_INCLUDED__
#include <iostream>
#include <cmath>
struct Vec2 {
inline Vec2() { x = 0; y = 0; }
inline Vec2( float a, float b ) { x = a; y = b; }
float x;
float y;
};
inline float LengthSquared( const Vec2 &A )
{
return A.x * A.x + A.y * A.y;
}
inline float Length( const Vec2 &A )
{
return sqrt( LengthSquared( A ) );
}
inline Vec2 operator+( const Vec2 &A, const Vec2 &B )
{
return Vec2( A.x + B.x, A.y + B.y );
}
inline Vec2 operator-( const Vec2 &A, const Vec2 &B )
{
return Vec2( A.x - B.x, A.y - B.y );
}
inline Vec2 operator-( const Vec2 &A ) // Unary minus.
{
return Vec2( -A.x, -A.y );
}
inline Vec2 operator*( float a, const Vec2 &A )
{
return Vec2( a * A.x, a * A.y );
}
inline Vec2 operator*( const Vec2 &A, float a )
{
return Vec2( a * A.x, a * A.y );
}
inline float operator*( const Vec2 &A, const Vec2 &B ) // Inner product.
{
return (A.x * B.x) + (A.y * B.y);
}
inline Vec2 operator/( const Vec2 &A, float c )
{
return Vec2( A.x / c, A.y / c );
}
inline float operator^( const Vec2 &A, const Vec2 &B ) // Z-component of Cross product.
{
return A.x * B.y - A.y * B.x;
}
inline Vec2& operator+=( Vec2 &A, const Vec2 &B )
{
A.x += B.x;
A.y += B.y;
return A;
}
inline Vec2& operator-=( Vec2 &A, const Vec2 &B )
{
A.x -= B.x;
A.y -= B.y;
return A;
}
inline Vec2 &operator*=( Vec2 &A, float a )
{
A.x *= a;
A.y *= a;
return A;
}
inline Vec2& operator/=( Vec2 &A, float a )
{
A.x /= a;
A.y /= a;
return A;
}
inline Vec2 Unit( const Vec2 &A )
{
float d = LengthSquared( A );
return d > 0.0 ? A / sqrt(d) : Vec2(0,0);
}
inline std::ostream &operator<<( std::ostream &out, const Vec2 &A )
{
out << "(" << A.x << ", " << A.y << ") ";
return out;
}
#endif
|
#ifndef __CGREEJNIHELPER_H__
#define __CGREEJNIHELPER_H__
#include "jni/JniHelper.h"
#include "GreeExtensionMacros.h"
NS_CC_GREE_EXT_BEGIN
//bool getEnv(JNIEnv **env);
typedef struct JniFieldInfo_
{
JNIEnv *env;
jclass classID;
jfieldID fieldID;
} JniFieldInfo;
class GreeJniHelper
{
public:
static bool getInstanceMethodInfo(JniMethodInfo &methodinfo, jobject &obj, const char *methodName, const char *paramCode);
static bool getStaticFieldInfo(JniFieldInfo &fieldinfo, const char *className, const char *fieldName, const char *paramCode);
};
NS_CC_GREE_EXT_END
#endif
|
#include <sstream>
#include "RootFile.h"
#include <TROOT.h>
#include <TStyle.h>
#include "TMath.h"
RootFile::RootFile(TString fileName, TString pedestalName,
bool isRawPedestalRun, bool isPedestalRun, bool isZSRun, bool clusteringOn,
std::vector<int> xChips, std::vector<int> yChips, int mapping) :
isRawPedestalRun(isRawPedestalRun), isPedestalRun(isPedestalRun), isZSRun(
isZSRun), clusteringOn(clusteringOn), fFileName(
fileName), fPedestalName(pedestalName), xChipIDs(xChips), yChipIDs(
yChips), mapping(mapping)
{
if (!isZSRun && !isRawPedestalRun)
{
fFilePedestal = new TFile(fPedestalName);
std::cout << "Pedestal root file " << fPedestalName << " opened!"
<< std::endl;
}
InitRootFile();
for(int n = 0; n<NFEC * NAPV;n++) {
rawPedestalNoise.push_back(new TH1F());
rawPedestalOffset.push_back(new TH1F());
pedestalNoise.push_back(new TH1F());
pedestalOffset.push_back(new TH1F());
std::vector<TH1F*> channelHistos;
for(int k = 0; k<NCH * NAPV;k++) {
channelHistos.push_back(new TH1F());
}
chipData.push_back(channelHistos);
}
}
//====================================================================================================================
RootFile::~RootFile()
{
FillHits();
this->WriteRootFile();
fFile->Close();
if (!isRawPedestalRun && !isPedestalRun)
{
DeleteHitsTree();
}
}
void RootFile::SetRunFlags(bool isRawPedestal, bool isPedestal)
{
isRawPedestalRun = isRawPedestal;
isPedestalRun = isPedestal;
}
void RootFile::InitPedestalData(int fecID, int apvID)
{
if (isRawPedestalRun || (!isRawPedestalRun && !isPedestalRun && !isZSRun))
{
float min = -2048;
float max = 2048;
float nbin = 4097;
for (int stripNo = 0; stripNo < NCH; stripNo++)
{
int theID = (fecID - 1) * NAPV + apvID;
std::stringstream out;
out << theID << " " << stripNo;
TString idStr = out.str();
chipData[theID][stripNo] = new TH1F(idStr, idStr, nbin, min, max);
if (stripData.size() < NCH)
{
stripData.push_back(new std::vector<float>());
}
}
}
else if (isPedestalRun)
{
for (int stripNo = 0; stripNo < NCH; stripNo++)
{
int theID = (fecID - 1) * NAPV + apvID;
chipData[theID][stripNo]->Reset();
}
}
}
void RootFile::FillStripData(int stripNo, float rawdata)
{
//if(isPedestalRun)
//std::cout << stripNo << " " << rawdata << std::endl;
stripData[stripNo]->push_back(rawdata);
}
bool RootFile::StripDataExists(int stripNo)
{
if (stripData[stripNo]->empty())
{
return false;
}
else
{
return true;
}
}
float RootFile::GetStripData(int stripNo, int timeBin)
{
return stripData[stripNo]->at(timeBin);
}
float RootFile::GetMeanStripData(int stripNo)
{
float mean = TMath::Mean(stripData[stripNo]->begin(),
stripData[stripNo]->end());
stripData[stripNo]->clear();
return mean;
}
void RootFile::ClearStripData(int stripNo)
{
stripData[stripNo]->clear();
}
void RootFile::InitPedestalHistograms(int fecID, int apvID)
{
int theID = (fecID - 1) * NAPV + apvID;
std::stringstream outFecID;
outFecID << fecID;
TString fecIDStr = outFecID.str();
std::stringstream outApvID;
outApvID << apvID;
TString apvIDStr = outApvID.str();
if (isRawPedestalRun)
{
float min = -0.5;
float max = 127.5;
float nbin = 128;
TString pedName = "fecID_" + fecIDStr + "_apvID_" + apvIDStr
+ "_rawNoise";
rawPedestalNoise[theID] = new TH1F(pedName, pedName, nbin, min, max);
pedName = "fecID_" + fecIDStr + "_apvID_" + apvIDStr + "_rawOffset";
rawPedestalOffset[theID] = new TH1F(pedName, pedName, nbin, min, max);
}
else if (isPedestalRun)
{
float min = -0.5;
float max = 127.5;
float nbin = 128;
TString pedName = "fecID_" + fecIDStr + "_apvID_" + apvIDStr + "_noise";
pedestalNoise[theID] = new TH1F(pedName, pedName, nbin, min, max);
pedName = "fecID_" + fecIDStr + "_apvID_" + apvIDStr + "_offset";
pedestalOffset[theID] = new TH1F(pedName, pedName, nbin, min, max);
}
else if (!isZSRun)
{
float min = -0.5;
float max = 127.5;
float nbin = 128;
TString pedName = "fecID_" + fecIDStr + "_apvID_" + apvIDStr + "_noise";
pedestalNoise[theID] = new TH1F(pedName, pedName, nbin, min, max);
pedestalNoise[theID] = (TH1F*) fFilePedestal->Get(pedName);
pedName = "fecID_" + fecIDStr + "_apvID_" + apvIDStr + "_offset";
pedestalOffset[theID] = new TH1F(pedName, pedName, nbin, min, max);
pedestalOffset[theID] = (TH1F*) fFilePedestal->Get(pedName);
}
}
void RootFile::FillPedestalData(int fecID, int apvID, int stripNo, float mean)
{
int theID = (fecID - 1) * NAPV + apvID;
chipData[theID][stripNo]->Fill(mean);
}
void RootFile::CreateHistograms(int minFecID, int maxFecID, int minAPVID,
int maxAPVID)
{
if (isRawPedestalRun)
{
for (int fecID = minFecID; fecID <= maxFecID; fecID++)
{
for (int apvID = minAPVID; apvID <= maxAPVID; apvID++)
{
int theID = (fecID - 1) * NAPV + apvID;
for (int stripNo = 0; stripNo < NCH; stripNo++)
{
//std::cout << theID << std::endl;
float offset = chipData[theID][stripNo]->GetMean();
float noise = chipData[theID][stripNo]->GetRMS();
rawPedestalNoise[theID]->Fill(stripNo, noise);
rawPedestalOffset[theID]->Fill(stripNo, offset);
}
}
}
}
else if (isPedestalRun)
{
for (int fecID = minFecID; fecID <= maxFecID; fecID++)
{
for (int apvID = minAPVID; apvID <= maxAPVID; apvID++)
{
int theID = (fecID - 1) * NAPV + apvID;
for (int stripNo = 0; stripNo < NCH; stripNo++)
{
float offset = chipData[theID][stripNo]->GetMean();
float noise = chipData[theID][stripNo]->GetRMS();
pedestalNoise[theID]->Fill(stripNo, noise);
pedestalOffset[theID]->Fill(stripNo, offset);
}
}
}
}
}
float RootFile::GetStripPedestalOffset(int fecID, int apvID, int stripNr)
{
int theID = (fecID - 1) * NAPV + apvID;
return pedestalOffset[theID]->GetBinContent(stripNr + 1);
}
float RootFile::GetStripPedestalNoise(int fecID, int apvID, int stripNr)
{
int theID = (fecID - 1) * NAPV + apvID;
return pedestalNoise[theID]->GetBinContent(stripNr + 1);
}
float RootFile::GetStripRawPedestalOffset(int fecID, int apvID, int stripNr)
{
int theID = (fecID - 1) * NAPV + apvID;
return rawPedestalOffset[theID]->GetBinContent(stripNr + 1);
}
float RootFile::GetStripRawPedestalNoise(int fecID, int apvID, int stripNr)
{
int theID = (fecID - 1) * NAPV + apvID;
return rawPedestalNoise[theID]->GetBinContent(stripNr + 1);
}
float RootFile::GetMeanPedestalOffset(int fecID, int apvID)
{
int theID = (fecID - 1) * NAPV + apvID;
return pedestalOffset[theID]->GetMean();
}
//====================================================================================================================
void RootFile::DeleteHitsTree()
{
std::cout << "DeleteHitsTree()" << std::endl;
if (m_adc0)
delete[] m_adc0;
if (m_adc1)
delete[] m_adc1;
if (m_adc2)
delete[] m_adc2;
if (m_adc3)
delete[] m_adc3;
if (m_adc4)
delete[] m_adc4;
if (m_adc5)
delete[] m_adc5;
if (m_adc6)
delete[] m_adc6;
if (m_adc7)
delete[] m_adc7;
if (m_adc8)
delete[] m_adc8;
if (m_adc9)
delete[] m_adc9;
if (m_adc10)
delete[] m_adc10;
if (m_adc11)
delete[] m_adc11;
if (m_adc12)
delete[] m_adc12;
if (m_adc13)
delete[] m_adc13;
if (m_adc14)
delete[] m_adc14;
if (m_adc15)
delete[] m_adc15;
if (m_adc16)
delete[] m_adc16;
if (m_adc17)
delete[] m_adc17;
if (m_adc18)
delete[] m_adc18;
if (m_adc19)
delete[] m_adc19;
if (m_adc20)
delete[] m_adc20;
if (m_adc21)
delete[] m_adc21;
if (m_adc22)
delete[] m_adc22;
if (m_adc23)
delete[] m_adc23;
if (m_adc24)
delete[] m_adc24;
if (m_adc25)
delete[] m_adc25;
if (m_adc26)
delete[] m_adc26;
if (m_adc27)
delete[] m_adc27;
if (m_adc28)
delete[] m_adc28;
if (m_adc29)
delete[] m_adc29;
if (m_hitTimeBin)
delete[] m_hitTimeBin;
if (m_hitMaxADC)
delete[] m_hitMaxADC;
if (m_strip)
delete[] m_strip;
if (m_strip_chip)
delete[] m_strip_chip;
if (m_x)
delete[] m_x;
if (m_y)
delete[] m_y;
if (m_planeID)
delete[] m_planeID;
if (m_apvID)
delete[] m_apvID;
if (m_fecID)
delete[] m_fecID;
std::cout << "END DeleteHitsTree()" << std::endl;
}
//====================================================================================================================
void RootFile::AddHits(signed int timestamp, int us, int eventId, int fecID,
int apvID, int chNo, float maxADC, int timeBinMaxADC,
std::vector<float> &timeBinADCs)
{
newData = true;
if (isFirstLine)
{
isFirstLine = false;
fTextFile
<< "timestamp, us, eventId, fecID, apvID, chNo, adc00, adc01, adc02, adc03,adc04,adc05,adc06,adc07,adc08,adc09,adc10,adc11, adc12,adc13,adc14,adc15,adc16,adc17,adc18,adc19,adc20,adc21,adc22,adc23,adc24,adc25,adc26,adc27,adc28,adc29"
<< std::endl;
}
fTextFile << timestamp << "," << us << "," << eventId << "," << fecID << ","
<< apvID << "," << chNo;
for (int i = 0; i < 30; i++)
{
fTextFile << "," << timeBinADCs[i];
}
fTextFile << std::endl;
m_timestamp = timestamp;
m_us = us;
m_evtID = eventId;
m_fecID[m_chID] = fecID;
m_apvID[m_chID] = apvID;
int stripNo = chNo;
//std::cout << "strip no" << stripNo << std::endl;
m_strip_chip[m_chID] = stripNo;
//stripNo = 127 - stripNo;
unsigned int planeID = GetPlaneID(apvID);
// Plane 0: x
// plane 1: y
unsigned int x = 0;
unsigned int y = 0;
if (planeID == 0)
{
x = GetChannelX(apvID, stripNo);
y = -1;
}
else if (planeID == 1)
{
y = GetChannelY(apvID, stripNo);
x = -1;
}
else
{
x = -1;
y = -1;
}
if (planeID == 0)
{
m_strip[m_chID] = x;
m_planeID[m_chID] = 0;
m_x[m_nchX] = x;
m_nchX++;
}
else if (planeID == 1)
{
m_strip[m_chID] = y;
m_planeID[m_chID] = 1;
m_y[m_nchY] = y;
m_nchY++;
}
m_hitTimeBin[m_chID] = timeBinMaxADC;
m_hitMaxADC[m_chID] = maxADC;
m_adc0[m_chID] = timeBinADCs[0];
m_adc1[m_chID] = timeBinADCs[1];
m_adc2[m_chID] = timeBinADCs[2];
m_adc3[m_chID] = timeBinADCs[3];
m_adc4[m_chID] = timeBinADCs[4];
m_adc5[m_chID] = timeBinADCs[5];
m_adc6[m_chID] = timeBinADCs[6];
m_adc7[m_chID] = timeBinADCs[7];
m_adc8[m_chID] = timeBinADCs[8];
m_adc9[m_chID] = timeBinADCs[9];
m_adc10[m_chID] = timeBinADCs[10];
m_adc11[m_chID] = timeBinADCs[11];
m_adc12[m_chID] = timeBinADCs[12];
m_adc13[m_chID] = timeBinADCs[13];
m_adc14[m_chID] = timeBinADCs[14];
m_adc15[m_chID] = timeBinADCs[15];
m_adc16[m_chID] = timeBinADCs[16];
m_adc17[m_chID] = timeBinADCs[17];
m_adc18[m_chID] = timeBinADCs[18];
m_adc19[m_chID] = timeBinADCs[19];
m_adc20[m_chID] = timeBinADCs[20];
m_adc21[m_chID] = timeBinADCs[21];
m_adc22[m_chID] = timeBinADCs[22];
m_adc23[m_chID] = timeBinADCs[23];
m_adc24[m_chID] = timeBinADCs[24];
m_adc25[m_chID] = timeBinADCs[25];
m_adc26[m_chID] = timeBinADCs[26];
m_adc27[m_chID] = timeBinADCs[27];
m_adc28[m_chID] = timeBinADCs[28];
m_adc29[m_chID] = timeBinADCs[29];
if (clusteringOn)
{
int pStrip = m_strip[m_chID];
int numMaximaStripX = 0;
int numMaximaStripY = 0;
if (m_planeID[m_chID] == 0)
{
float amp0 = 0;
float amp1 = 0;
float amp2 = 0;
int timeBin1 = 0;
float pAmplitude = 0;
float pHalf = 0;
float pPeak = 0;
float pIntegral = 0;
for (int timeBin = 29; timeBin >= 0; timeBin--)
{
if (timeBinADCs[timeBin] > amplitudeThreshold)
{
if (txd < timeBin
|| (txd == timeBin && timeBinADCs[timeBin] < exd))
{
xd = pStrip;
txd = timeBin;
exd = timeBinADCs[timeBin];
}
break;
}
}
for (int timeBin = 0; timeBin < 30; timeBin++)
{
amp2 = amp1;
amp1 = amp0;
amp0 = timeBinADCs[timeBin];
if (amp2 <= amp1 && amp0 < amp1 && amp1 > amplitudeThreshold
&& abs(timeBin1 - timeBin) > 2)
{
stripMaximaX.push_back(pStrip);
timeMaximaX.push_back(timeBin - 1);
energyMaximaX.push_back(amp1);
timeBin1 = timeBin - 1;
if (amp0 > 1400)
{
numMaximaStripX++;
}
}
else if (timeBin == 29 && amp0 > amp1 && amp1 > amp2
&& amp0 > amplitudeThreshold
&& abs(timeBin1 - timeBin) > 2)
{
stripMaximaX.push_back(pStrip);
timeMaximaX.push_back(timeBin);
energyMaximaX.push_back(amp0);
timeBin1 = timeBin;
if (amp0 > 1400)
{
numMaximaStripX++;
}
}
if (pAmplitude < timeBinADCs[timeBin]
&& amplitudeThreshold < timeBinADCs[timeBin])
{
pAmplitude = timeBinADCs[timeBin];
pPeak = timeBin;
if (pAmplitude > maxAmplitudeX)
{
maxAmplitudeX = pAmplitude;
tMaxAmplitudeX = timeBin;
}
}
pIntegral += timeBinADCs[timeBin];
}
if (numMaximaStripX >= 4)
{
discardFlag = 1;
}
int timeBin;
for (timeBin = 0; timeBin < 30; timeBin++)
{
if (timeBinADCs[timeBin] > pAmplitude / 2.)
break;
}
if (timeBin > 0 && timeBin < 29)
{
pHalf = (timeBin - 1)
+ (pAmplitude / 2. - timeBinADCs[timeBin - 1])
/ (timeBinADCs[timeBin]
- timeBinADCs[timeBin - 1]);
}
else
{
pHalf = -.5;
}
if ((pHalf > tx0 || tx0 < 0.)
|| (pHalf == tx0 && ex0 > timeBinADCs[timeBin]))
{
tx0 = pHalf;
x0 = pStrip;
ex0 = timeBinADCs[timeBin];
}
if ((pHalf < txf || txf < 0.)
|| (pHalf == txf && exf > timeBinADCs[timeBin]))
{
txf = pHalf;
xf = pStrip;
exf = timeBinADCs[timeBin];
}
if ((txmax < pPeak || txmax < 0.)
|| (pPeak == txmax && exmax > pAmplitude))
{
txmax = pPeak;
xmax = pStrip;
exmax = pAmplitude;
}
xm += pAmplitude * (double) pStrip;
xi += pIntegral * (double) pStrip;
xAmplitude += pAmplitude;
xIntegral += pIntegral;
nx++;
}
else
{
float amp0 = 0;
float amp1 = 0;
float amp2 = 0;
int timeBin1 = 0;
float pAmplitude = 0;
float pHalf = 0;
float pPeak = 0;
float pIntegral = 0;
for (int timeBin = 29; timeBin >= 0; timeBin--)
{
if (timeBinADCs[timeBin] > amplitudeThreshold)
{
if (tyd < timeBin
|| (tyd == timeBin && timeBinADCs[timeBin] < eyd))
{
yd = pStrip;
tyd = timeBin;
eyd = timeBinADCs[timeBin];
}
break;
}
}
for (int timeBin = 0; timeBin < 30; timeBin++)
{
amp2 = amp1;
amp1 = amp0;
amp0 = timeBinADCs[timeBin];
if (amp2 <= amp1 && amp0 < amp1 && amp1 > amplitudeThreshold
&& abs(timeBin1 - timeBin) > 2)
{
stripMaximaY.push_back(pStrip);
timeMaximaY.push_back(timeBin - 1);
energyMaximaY.push_back(amp1);
timeBin1 = timeBin - 1;
if (amp0 > 1400)
{
numMaximaStripY++;
}
}
else if (timeBin == 29 && amp0 > amp1 && amp1 > amp2
&& amp0 > amplitudeThreshold
&& abs(timeBin1 - timeBin) > 2)
{
stripMaximaY.push_back(stripNo);
timeMaximaY.push_back(pStrip);
energyMaximaY.push_back(amp0);
timeBin1 = timeBin;
if (amp0 > 1400)
{
numMaximaStripY++;
}
}
if (pAmplitude < timeBinADCs[timeBin]
&& amplitudeThreshold < timeBinADCs[timeBin])
{
pAmplitude = timeBinADCs[timeBin];
pPeak = timeBin;
if (pAmplitude > maxAmplitudeY)
{
maxAmplitudeY = pAmplitude;
tMaxAmplitudeY = timeBin;
}
}
pIntegral += timeBinADCs[timeBin];
}
if (numMaximaStripX >= 4)
{
discardFlag = true;
}
int timeBin;
for (timeBin = 0; timeBin < 30; timeBin++)
{
if (timeBinADCs[timeBin] > pAmplitude / 2.)
break;
}
if (timeBin > 0 && timeBin < 29)
{
pHalf = (timeBin - 1)
+ (pAmplitude / 2. - timeBinADCs[timeBin - 1])
/ (timeBinADCs[timeBin]
- timeBinADCs[timeBin - 1]);
}
else
{
pHalf = -.5;
}
if ((pHalf > ty0 || ty0 < 0.)
|| (pHalf == ty0 && ey0 > timeBinADCs[timeBin]))
{
ty0 = pHalf;
y0 = pStrip;
ey0 = timeBinADCs[timeBin];
}
if ((pHalf < tyf || tyf < 0.)
|| (pHalf == tyf && eyf > timeBinADCs[timeBin]))
{
tyf = pHalf;
yf = pStrip;
eyf = timeBinADCs[timeBin];
}
if ((tymax < pPeak || tymax < 0.)
|| (pPeak == tymax && eymax > pAmplitude))
{
tymax = pPeak;
ymax = pStrip;
eymax = pAmplitude;
}
ym += pAmplitude * (double) pStrip;
yi += pIntegral * (double) pStrip;
yAmplitude += pAmplitude;
yIntegral += pIntegral;
ny++;
}
}
m_chID++;
}
void RootFile::FillHits()
{
if (!isPedestalRun && !isRawPedestalRun && newData)
{
ntx = TMath::Abs(tx0 - txf) + 1;
nty = TMath::Abs(ty0 - tyf) + 1;
if (xAmplitude > 0)
{
xm /= xAmplitude;
}
if (xIntegral > 0)
{
xi /= xIntegral;
}
if (yAmplitude > 0)
{
ym /= yAmplitude;
}
if (yIntegral > 0)
{
yi /= yIntegral;
}
numMaximaX = timeMaximaX.size();
numMaximaY = timeMaximaY.size();
if (numMaximaX > 0 && numMaximaY > 0 && numMaximaX < DISCARD_THRESHOLD
&& numMaximaY < DISCARD_THRESHOLD && discardFlag == false)
{
for (int row = 0; row < numMaximaX; row++)
{
if ((txs < timeMaximaX[row])
|| (txs == timeMaximaX[row] && exs > energyMaximaX[row]))
{
txs = timeMaximaX[row];
xs = stripMaximaX[row];
exs = energyMaximaX[row];
}
}
for (int row = 0; row < timeMaximaY.size(); row++)
{
if ((tys < timeMaximaY[row])
|| (tys == timeMaximaY[row] && eys > energyMaximaY[row]))
{
tys = timeMaximaY[row];
ys = stripMaximaY[row];
eys = energyMaximaY[row];
}
}
}
fHitTree->Fill();
newData = false;
resetClusterData();
m_chID = 0;
m_nchX = 0;
m_nchY = 0;
}
}
//====================================================================================================================
void RootFile::InitRootFile()
{
// C++ 2011: Initialization not here, but in header
isFirstLine = true;
newData = false;
amplitudeThreshold = 0;
numMaximaX = 0;
numMaximaY = 0;
x0 = 0;
y0 = 0;
xf = 0;
yf = 0;
xm = 0;
ym = 0;
xi = 0;
yi = 0;
xs = 0;
ys = 0;
xd = 0;
yd = 0;
xmax = 0;
ymax = 0;
xAmplitude = 0;
xIntegral = 0;
yAmplitude = 0;
yIntegral = 0;
maxAmplitudeX = 0;
maxAmplitudeY = 0;
tMaxAmplitudeX = 0;
tMaxAmplitudeY = 0;
tx0 = 0;
ty0 = 0;
txf = 0;
tyf = 0;
txs = 0;
tys = 0;
txd = 0;
tyd = 0;
txmax = 0;
tymax = 0;
ex0 = 0;
ey0 = 0;
exf = 0;
eyf = 0;
exs = 0;
eys = 0;
exd = 0;
eyd = 0;
exmax = 0;
eymax = 0;
nx = 0;
ny = 0;
ntx = 0;
nty = 0;
discardFlag = false;
// C++ 2011: Initialization in header
m_evtID = 0;
m_chID = 0;
m_nchX = 0;
m_nchY = 0;
fFile = TFile::Open(fFileName, "RECREATE");
if (!isPedestalRun && !isRawPedestalRun)
{
TString textFileName = fFileName;
textFileName.ReplaceAll(".root", ".csv");
fTextFile.open(textFileName);
fHitTree = new TTree("events", "GEM events ROOT file");
fHitTree->SetDirectory(fFile);
m_fecID = new int[10000];
m_apvID = new int[10000];
m_strip = new int[10000];
m_strip_chip = new int[10000];
m_x = new short[10000];
m_y = new short[10000];
m_planeID = new int[10000];
m_hitTimeBin = new int[10000];
m_hitMaxADC = new short[10000];
m_adc0 = new short[10000];
m_adc1 = new short[10000];
m_adc2 = new short[10000];
m_adc3 = new short[10000];
m_adc4 = new short[10000];
m_adc5 = new short[10000];
m_adc6 = new short[10000];
m_adc7 = new short[10000];
m_adc8 = new short[10000];
m_adc9 = new short[10000];
m_adc10 = new short[10000];
m_adc11 = new short[10000];
m_adc12 = new short[10000];
m_adc13 = new short[10000];
m_adc14 = new short[10000];
m_adc15 = new short[10000];
m_adc16 = new short[10000];
m_adc17 = new short[10000];
m_adc18 = new short[10000];
m_adc19 = new short[10000];
m_adc20 = new short[10000];
m_adc21 = new short[10000];
m_adc22 = new short[10000];
m_adc23 = new short[10000];
m_adc24 = new short[10000];
m_adc25 = new short[10000];
m_adc26 = new short[10000];
m_adc27 = new short[10000];
m_adc28 = new short[10000];
m_adc29 = new short[10000];
fHitTree->Branch("timestamp", &m_timestamp, "timestamp/I");
fHitTree->Branch("us", &m_us, "us/I");
fHitTree->Branch("evtID", &m_evtID, "evtID/I");
fHitTree->Branch("nch", &m_chID, "nch/I");
fHitTree->Branch("nchX", &m_nchX, "nchX/I");
fHitTree->Branch("nchY", &m_nchY, "nchY/I");
fHitTree->Branch("fecID", m_fecID, "fecID[nch]/I");
fHitTree->Branch("apvID", m_apvID, "apvID[nch]/I");
fHitTree->Branch("planeID", m_planeID, "planeID[nch]/I");
fHitTree->Branch("strip_chip", m_strip_chip, "strip_chip[nch]/I");
fHitTree->Branch("strip", m_strip, "strip[nch]/I");
fHitTree->Branch("x", m_x, "x[nchX]/s");
fHitTree->Branch("y", m_y, "y[nchY]/s");
fHitTree->Branch("hitTimebin", m_hitTimeBin, "hitTimeBin[nch]/I");
fHitTree->Branch("hitMaxADC", m_hitMaxADC, "hitMaxADC[nch]/S");
fHitTree->Branch("adc0", m_adc0, "adc0[nch]/S");
fHitTree->Branch("adc1", m_adc1, "adc1[nch]/S");
fHitTree->Branch("adc2", m_adc2, "adc2[nch]/S");
fHitTree->Branch("adc3", m_adc3, "adc3[nch]/S");
fHitTree->Branch("adc4", m_adc4, "adc4[nch]/S");
fHitTree->Branch("adc5", m_adc5, "adc5[nch]/S");
fHitTree->Branch("adc6", m_adc6, "adc6[nch]/S");
fHitTree->Branch("adc7", m_adc7, "adc7[nch]/S");
fHitTree->Branch("adc8", m_adc8, "adc8[nch]/S");
fHitTree->Branch("adc9", m_adc9, "adc9[nch]/S");
fHitTree->Branch("adc10", m_adc10, "adc10[nch]/S");
fHitTree->Branch("adc11", m_adc11, "adc11[nch]/S");
fHitTree->Branch("adc12", m_adc12, "adc12[nch]/S");
fHitTree->Branch("adc13", m_adc13, "adc13[nch]/S");
fHitTree->Branch("adc14", m_adc14, "adc14[nch]/S");
fHitTree->Branch("adc15", m_adc15, "adc15[nch]/S");
fHitTree->Branch("adc16", m_adc16, "adc16[nch]/S");
fHitTree->Branch("adc17", m_adc17, "adc17[nch]/S");
fHitTree->Branch("adc18", m_adc18, "adc18[nch]/S");
fHitTree->Branch("adc19", m_adc19, "adc19[nch]/S");
fHitTree->Branch("adc20", m_adc20, "adc20[nch]/S");
fHitTree->Branch("adc21", m_adc21, "adc21[nch]/S");
fHitTree->Branch("adc22", m_adc22, "adc22[nch]/S");
fHitTree->Branch("adc23", m_adc23, "adc23[nch]/S");
fHitTree->Branch("adc24", m_adc24, "adc24[nch]/S");
fHitTree->Branch("adc25", m_adc25, "adc25[nch]/S");
fHitTree->Branch("adc26", m_adc26, "adc26[nch]/S");
fHitTree->Branch("adc27", m_adc27, "adc27[nch]/S");
fHitTree->Branch("adc28", m_adc28, "adc28[nch]/S");
fHitTree->Branch("adc29", m_adc29, "adc29[nch]/S");
//std::cout << "Hit tree created!" << std::endl;
if (clusteringOn)
{
resetClusterData();
fHitTree->Branch("nx", &nx, "nx/I");
fHitTree->Branch("ny", &ny, "ny/I");
fHitTree->Branch("ntx", &ntx, "ntx/I");
fHitTree->Branch("nty", &nty, "nty/I");
fHitTree->Branch("numMaximaX", &numMaximaX, "numMaximaX/I");
fHitTree->Branch("numMaximaY", &numMaximaY, "numMaximaY/I");
fHitTree->Branch("maxAmplitudeX", &maxAmplitudeX,
"maxAmplitudeX/D");
fHitTree->Branch("maxAmplitudeY", &maxAmplitudeY,
"maxAmplitudeY/D");
fHitTree->Branch("tMaxAmplitudeX", &tMaxAmplitudeX,
"tMaxAmplitudeX/D");
fHitTree->Branch("tMaxAmplitudeY", &tMaxAmplitudeY,
"tMaxAmplitudeY/D");
fHitTree->Branch("xAmplitude", &xAmplitude, "xAmplitude/D");
fHitTree->Branch("yAmplitude", &yAmplitude, "yAmplitude/D");
fHitTree->Branch("xIntegral", &xIntegral, "xIntegral/D");
fHitTree->Branch("yIntegral", &yIntegral, "yIntegral/D");
fHitTree->Branch("xm", &xm, "xm/D");
fHitTree->Branch("ym", &ym, "ym/D");
fHitTree->Branch("xi", &xi, "xi/D");
fHitTree->Branch("yi", &yi, "yi/D");
fHitTree->Branch("x0", &x0, "x0/D");
fHitTree->Branch("tx0", &tx0, "tx0/D");
fHitTree->Branch("y0", &y0, "y0/D");
fHitTree->Branch("ty0", &ty0, "ty0/D");
fHitTree->Branch("xf", &xf, "xf/D");
fHitTree->Branch("txf", &txf, "txf/D");
fHitTree->Branch("yf", &yf, "yf/D");
fHitTree->Branch("tyf", &tyf, "tyf/D");
fHitTree->Branch("xs", &xs, "xs/D");
fHitTree->Branch("txs", &txs, "txs/D");
fHitTree->Branch("ys", &ys, "ys/D");
fHitTree->Branch("tys", &tys, "tys/D");
fHitTree->Branch("xd", &xd, "xd/D");
fHitTree->Branch("txd", &txd, "txd/D");
fHitTree->Branch("yd", &yd, "yd/D");
fHitTree->Branch("tyd", &tyd, "tyd/D");
fHitTree->Branch("xmax", &xmax, "xmax/D");
fHitTree->Branch("txmax", &txmax, "txmax/D");
fHitTree->Branch("ymax", &ymax, "ymax/D");
fHitTree->Branch("tymax", &tymax, "tymax/D");
}
}
std::cout << "Root file " << fFileName << " created!" << std::endl;
}
//====================================================================================================================
void RootFile::WriteRootFile()
{
if (isRawPedestalRun)
{
std::cout << "isRawPedestalRun" << std::endl;
int i = 0;
std::vector<TH1F*>::const_iterator itr;
for (itr = rawPedestalNoise.begin(); itr != rawPedestalNoise.end();
++itr)
{
if (rawPedestalNoise[i])
{
rawPedestalNoise[i]->SetOption("HIST");
rawPedestalOffset[i]->SetOption("HIST");
rawPedestalNoise[i]->Write(0, TObject::kWriteDelete);
rawPedestalOffset[i]->Write(0, TObject::kWriteDelete);
}
i++;
}
}
else if (isPedestalRun)
{
int i = 0;
std::vector<TH1F*>::const_iterator itr;
for (itr = rawPedestalNoise.begin(); itr != rawPedestalNoise.end();
++itr)
{
if (rawPedestalNoise[i])
{
rawPedestalNoise[i]->SetOption("HIST");
rawPedestalOffset[i]->SetOption("HIST");
rawPedestalNoise[i]->Write(0, TObject::kWriteDelete);
rawPedestalOffset[i]->Write(0, TObject::kWriteDelete);
}
i++;
}
i = 0;
for (itr = pedestalNoise.begin(); itr != pedestalNoise.end(); ++itr)
{
if (pedestalNoise[i])
{
pedestalNoise[i]->SetOption("HIST");
pedestalOffset[i]->SetOption("HIST");
pedestalNoise[i]->Write(0, TObject::kWriteDelete);
pedestalOffset[i]->Write(0, TObject::kWriteDelete);
}
i++;
}
}
else
{
std::cout << "else" << std::endl;
fHitTree->Write(0, TObject::kWriteDelete);
if (fTextFile.is_open())
{
fTextFile.close();
}
}
//fFile->Write(0, TObject::kWriteDelete);
//fFile->Write();
}
int RootFile::GetStripNumber(int chNo)
{
chNo = (32 * (chNo % 4)) + (8 * (int) (chNo / 4))
- (31 * (int) (chNo / 16));
//CMS
if(mapping == 1) {
if(chNo%2 == 1) {
chNo = (127 - chNo)/2;
}
else {
chNo = 64 + chNo/2;
}
}
//CMS inverted
else if(mapping == 2) {
if(chNo%2 == 1) {
chNo = 64 + (127 - chNo)/2;
}
else {
chNo = chNo/2;
}
}
return chNo;
}
void RootFile::resetClusterData()
{
discardFlag = false;
x0 = y0 = xf = yf = xm = ym = xi = yi = xs = ys = xd = yd = xmax = ymax = 0;
xAmplitude = xIntegral = yAmplitude = yIntegral = 0.;
nx = ny = 0;
tx0 = ty0 = txf = tyf = txs = tys = txd = tyd = txmax = tymax = -1.;
ex0 = ey0 = exf = eyf = exs = eys = exd = eyd = exmax = eymax = 9999999;
nx = ny = 0;
ntx = nty = 0;
numMaximaX = 0;
numMaximaY = 0;
maxAmplitudeX = maxAmplitudeY = tMaxAmplitudeX = tMaxAmplitudeY = 0;
stripMaximaX.clear();
stripMaximaY.clear();
timeMaximaX.clear();
timeMaximaY.clear();
energyMaximaX.clear();
energyMaximaY.clear();
}
unsigned int RootFile::GetPlaneID(unsigned int chipID)
{
std::vector<int>::iterator it;
it = find(xChipIDs.begin(), xChipIDs.end(), chipID);
if (it != xChipIDs.end())
{
return 0;
}
else
{
it = find(yChipIDs.begin(), yChipIDs.end(), chipID);
if (it != yChipIDs.end())
{
return 1;
}
else
{
return -1;
}
}
}
unsigned int RootFile::GetChannelX(unsigned int chipID, unsigned int channelID)
{
std::vector<int>::iterator it;
it = find(xChipIDs.begin(), xChipIDs.end(), chipID);
if (it != xChipIDs.end())
{
int pos = it - xChipIDs.begin();
return (channelID + pos * 128);
}
else
{
return -1;
}
}
unsigned int RootFile::GetChannelY(unsigned int chipID, unsigned int channelID)
{
std::vector<int>::iterator it;
it = find(yChipIDs.begin(), yChipIDs.end(), chipID);
if (it != yChipIDs.end())
{
int pos = it - yChipIDs.begin();
return (channelID + pos * 128);
}
else
{
return -1;
}
}
|
#include "Peon.hpp"
#include "Victim.hpp"
#include "Sorcerer.hpp"
#include "Navalny.hpp"
int main()
{
std::cout << "\033[32m Sorcerer creation:\033[0m \n";
Sorcerer volodya("Vladimir", "Bunker");
std::cout << volodya << std::endl;
std::cout << "\033[32m Victim tests:\033[0m \n";
Victim jimss("Jimmy");
std::cout << jimss << std::endl;
Victim jos(jimss);
std::cout << jos << std::endl;
Victim unnamed("Unnamed");
std::cout << unnamed;
unnamed = jos;
std::cout << unnamed << std::endl;
std::cout << "\033[32m Navalny tests:\033[0m \n";
Navalny lexa("JlexXxa Navalny");
std::cout << lexa << std::endl;
Navalny july("July");
std::cout << july << std::endl;
july = lexa;
std::cout << july << std::endl;
std::cout << "\033[32m Peon tests:\033[0m \n";
Peon joes("Joes");
std::cout << joes << std::endl;
Peon jims("Jims");
std::cout << jims << std::endl;
joes = jims;
std::cout << joes << std::endl;
std::cout << "\033[32m Polymorph tests by reference:\033[0m \n";
Victim *tmp = &lexa;
Victim *tmp1 = &jimss;
Victim *tmp2 = &jims;
volodya.polymorph(jimss);
volodya.polymorph(lexa);
volodya.polymorph(jims);
std::cout << "\n\033[32m Polymorph tests by pointer:\033[0m \n";
volodya.polymorph(*tmp1);
volodya.polymorph(*tmp);
volodya.polymorph(*tmp2);
std::cout << "\n\033[32m Subjuct tests:\033[0m \n";
Sorcerer robert("Robert", "the Magnificent");
Victim jim("Jimmy");
Peon joe("Joe");
std::cout << robert << jim << joe;
robert.polymorph(jim);
robert.polymorph(joe);
std::cout << "\n\033[32m Destructor tests:\033[0m \n";
return 0;
}
|
#include "mytcpsocket.h"
MyTcpSocket::MyTcpSocket(QObject *parent) :
QObject(parent)
{
}
void MyTcpSocket::doConnect()
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));
connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));
connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));
qDebug() << "connecting...";
// this is not blocking call
socket->connectToHost("google.com", 80);
// we need to wait...
if(!socket->waitForConnected(5000))
{
qDebug() << "Error: " << socket->errorString();
}
}
void MyTcpSocket::connected()
{
qDebug() << "connected...";
// Hey server, tell me about you.
socket->write("HEAD / HTTP/1.0\r\n\r\n\r\n\r\n");
}
void MyTcpSocket::disconnected()
{
qDebug() << "disconnected...";
}
void MyTcpSocket::bytesWritten(qint64 bytes)
{
qDebug() << bytes << " bytes written...";
}
void MyTcpSocket::readyRead()
{
qDebug() << "reading...";
// read the data from the socket
qDebug() << socket->readAll();
}
|
/*
* @lc app=leetcode id=480 lang=cpp
*
* [480] Sliding Window Median
*
* https://leetcode.com/problems/sliding-window-median/description/
*
* algorithms
* Hard (33.15%)
* Likes: 451
* Dislikes: 48
* Total Accepted: 28.1K
* Total Submissions: 84.9K
* Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
*
* Median is the middle value in an ordered integer list. If the size of the
* list is even, there is no middle value. So the median is the mean of the two
* middle value.
* Examples:
* [2,3,4] , the median is 3
* [2 ,3], the median is (2 + 3) / 2 = 2.5
*
* Given an array nums, there is a sliding window of size k which is moving
* from the very left of the array to the very right. You can only see the k
* numbers in the window. Each time the sliding window moves right by one
* position. Your job is to output the median array for each window in the
* original array.
*
* For example,
* Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
*
*
* Window position Median
* --------------- -----
* [1 3 -1] -3 5 3 6 7 1
* 1 [3 -1 -3] 5 3 6 7 -1
* 1 3 [-1 -3 5] 3 6 7 -1
* 1 3 -1 [-3 5 3] 6 7 3
* 1 3 -1 -3 [5 3 6] 7 5
* 1 3 -1 -3 5 [3 6 7] 6
*
*
* Therefore, return the median sliding window as [1,-1,-1,3,5,6].
*
* Note:
* You may assume k is always valid, ie: k is always smaller than input array's
* size for non-empty array.
*/
class Solution {
public:
vector<double> medianSlidingWindow(vector<int> &nums, int k) {
multiset<int> window;
vector<double> medians;
for (int i = 0; i < nums.size(); i++) {
window.insert(nums[i]);
if (window.size() >= k) {
auto mid = next(window.begin(), k / 2);
medians.emplace_back((double(*mid) + *prev(mid, 1 - k % 2)) / 2.0);
window.erase(window.lower_bound(nums[i - k + 1]));
}
}
return medians;
}
};
|
#if !defined(FUTURE_FTDCTRADERAPI_H)
#define FUTURE_FTDCTRADERAPI_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "FutureFtdcUserApiStruct.h"
#if defined(ISLIB) && defined(WIN32)
#ifdef LIB_TRADER_API_EXPORT
#define TRADER_API_EXPORT __declspec(dllexport)
#else
#define TRADER_API_EXPORT __declspec(dllimport)
#endif
#else
#define TRADER_API_EXPORT
#endif
class CFutureFtdcTraderSpi
{
public:
///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
virtual void OnFrontConnected(){};
///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
///@param nReason 错误原因
/// 0x1001 网络读失败
/// 0x1002 网络写失败
/// 0x2001 接收心跳超时
/// 0x2002 发送心跳失败
/// 0x2003 收到错误报文
virtual void OnFrontDisconnected(int nReason){};
///心跳超时警告。当长时间未收到报文时,该方法被调用。
///@param nTimeLapse 距离上次接收报文的时间
virtual void OnHeartBeatWarning(int nTimeLapse){};
///客户端认证响应
virtual void OnRspAuthenticate(CFutureFtdcRspAuthenticateField *pRspAuthenticateField, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///登录请求响应
virtual void OnRspUserLogin(CFutureFtdcRspUserLoginField *pRspUserLogin, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///登出请求响应
virtual void OnRspUserLogout(CFutureFtdcUserLogoutField *pUserLogout, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///用户口令更新请求响应
virtual void OnRspUserPasswordUpdate(CFutureFtdcUserPasswordUpdateField *pUserPasswordUpdate, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///资金账户口令更新请求响应
virtual void OnRspTradingAccountPasswordUpdate(CFutureFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///报单录入请求响应
virtual void OnRspOrderInsert(CFutureFtdcInputOrderField *pInputOrder, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///报单操作请求响应
virtual void OnRspOrderAction(CFutureFtdcInputOrderActionField *pInputOrderAction, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///查询最大报单数量响应
virtual void OnRspQueryMaxOrderVolume(CFutureFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///投资者结算结果确认响应
virtual void OnRspSettlementInfoConfirm(CFutureFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///执行宣告录入请求响应
virtual void OnRspExecOrderInsert(CFutureFtdcInputExecOrderField *pInputExecOrder, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///执行宣告操作请求响应
virtual void OnRspExecOrderAction(CFutureFtdcInputExecOrderActionField *pInputExecOrderAction, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///报价录入请求响应
virtual void OnRspQuoteInsert(CFutureFtdcInputQuoteField *pInputQuote, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///报价操作请求响应
virtual void OnRspQuoteAction(CFutureFtdcInputQuoteActionField *pInputQuoteAction, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///询价操作应答
virtual void OnRspForQuote(CFutureFtdcInputForQuoteField *pInputForQuote, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///请求资金内转响应
virtual void OnRspInternalTransfer(CFutureFtdcInternalTransferField *pInternalTransfer, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///错误应答
virtual void OnRspError(CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///报单通知
virtual void OnRtnOrder(CFutureFtdcOrderField *pOrder) {};
///成交通知
virtual void OnRtnTrade(CFutureFtdcTradeField *pTrade) {};
///报单录入错误回报
virtual void OnErrRtnOrderInsert(CFutureFtdcInputOrderField *pInputOrder, CFutureFtdcRspInfoField *pRspInfo) {};
///报单操作错误回报
virtual void OnErrRtnOrderAction(CFutureFtdcOrderActionField *pOrderAction, CFutureFtdcRspInfoField *pRspInfo) {};
///合约交易状态通知
virtual void OnRtnInstrumentStatus(CFutureFtdcInstrumentStatusField *pInstrumentStatus) {};
///提示条件单校验错误
virtual void OnRtnErrorConditionalOrder(CFutureFtdcErrorConditionalOrderField *pErrorConditionalOrder) {};
///报价录入错误回报
virtual void OnErrRtnQuoteInsert(CFutureFtdcInputQuoteField *pInputQuote, CFutureFtdcRspInfoField *pRspInfo) {};
///报价操作错误回报
virtual void OnErrRtnQuoteAction(CFutureFtdcQuoteActionField *pQuoteAction, CFutureFtdcRspInfoField *pRspInfo) {};
///询价通知
virtual void OnRtnForQuote(CFutureFtdcForQuoteField *pForQuote) {};
///询价回报
virtual void OnRtnExchRspForQuote(CFutureFtdcExchRspForQuoteField *pExchRspForQuote) {};
///提示交易所询价失败
virtual void OnRtnErrExchRtnForQuote(CFutureFtdcErrRtnExchRtnForQuoteField *pErrRtnExchRtnForQuote) {};
///交易所报单录入错误回报
virtual void OnRtnErrExchRtnOrderInsert(CFutureFtdcExchangeOrderInsertErrorField *pExchangeOrderInsertError) {};
///交易所报单操作错误回报
virtual void OnRtnErrExchRtnOrderAction(CFutureFtdcExchangeOrderActionErrorField *pExchangeOrderActionError) {};
///银行发起银行资金转期货通知
virtual void OnRtnFromBankToFutureByBank(CFutureFtdcRspTransferField *pRspTransfer) {};
///银行发起期货资金转银行通知
virtual void OnRtnFromFutureToBankByBank(CFutureFtdcRspTransferField *pRspTransfer) {};
///银行发起冲正银行转期货通知
virtual void OnRtnRepealFromBankToFutureByBank(CFutureFtdcRspRepealField *pRspRepeal) {};
///银行发起冲正期货转银行通知
virtual void OnRtnRepealFromFutureToBankByBank(CFutureFtdcRspRepealField *pRspRepeal) {};
///期货发起银行资金转期货通知
virtual void OnRtnFromBankToFutureByFuture(CFutureFtdcRspTransferField *pRspTransfer) {};
///期货发起期货资金转银行通知
virtual void OnRtnFromFutureToBankByFuture(CFutureFtdcRspTransferField *pRspTransfer) {};
///系统运行时期货端手工发起冲正银行转期货请求,银行处理完毕后报盘发回的通知
virtual void OnRtnRepealFromBankToFutureByFutureManual(CFutureFtdcRspRepealField *pRspRepeal) {};
///系统运行时期货端手工发起冲正期货转银行请求,银行处理完毕后报盘发回的通知
virtual void OnRtnRepealFromFutureToBankByFutureManual(CFutureFtdcRspRepealField *pRspRepeal) {};
///期货发起查询银行余额通知
virtual void OnRtnQueryBankBalanceByFuture(CFutureFtdcNotifyQueryAccountField *pNotifyQueryAccount) {};
///期货发起银行资金转期货错误回报
virtual void OnErrRtnBankToFutureByFuture(CFutureFtdcReqTransferField *pReqTransfer, CFutureFtdcRspInfoField *pRspInfo) {};
///期货发起期货资金转银行错误回报
virtual void OnErrRtnFutureToBankByFuture(CFutureFtdcReqTransferField *pReqTransfer, CFutureFtdcRspInfoField *pRspInfo) {};
///系统运行时期货端手工发起冲正银行转期货错误回报
virtual void OnErrRtnRepealBankToFutureByFutureManual(CFutureFtdcReqRepealField *pReqRepeal, CFutureFtdcRspInfoField *pRspInfo) {};
///系统运行时期货端手工发起冲正期货转银行错误回报
virtual void OnErrRtnRepealFutureToBankByFutureManual(CFutureFtdcReqRepealField *pReqRepeal, CFutureFtdcRspInfoField *pRspInfo) {};
///期货发起查询银行余额错误回报
virtual void OnErrRtnQueryBankBalanceByFuture(CFutureFtdcReqQueryAccountField *pReqQueryAccount, CFutureFtdcRspInfoField *pRspInfo) {};
///期货发起冲正银行转期货请求,银行处理完毕后报盘发回的通知
virtual void OnRtnRepealFromBankToFutureByFuture(CFutureFtdcRspRepealField *pRspRepeal) {};
///期货发起冲正期货转银行请求,银行处理完毕后报盘发回的通知
virtual void OnRtnRepealFromFutureToBankByFuture(CFutureFtdcRspRepealField *pRspRepeal) {};
///期货发起银行资金转期货应答
virtual void OnRspFromBankToFutureByFuture(CFutureFtdcReqTransferField *pReqTransfer, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///期货发起期货资金转银行应答
virtual void OnRspFromFutureToBankByFuture(CFutureFtdcReqTransferField *pReqTransfer, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///银行发起银期开户通知
virtual void OnRtnOpenAccountByBank(CFutureFtdcOpenAccountField *pOpenAccount) {};
///银行发起银期销户通知
virtual void OnRtnCancelAccountByBank(CFutureFtdcCancelAccountField *pCancelAccount) {};
///银行发起变更银行账号通知
virtual void OnRtnChangeAccountByBank(CFutureFtdcChangeAccountField *pChangeAccount) {};
};
#ifndef WINDOWS
#if __GNUC__ >= 4
#pragma GCC visibility push(default)
#endif
#endif
class TRADER_API_EXPORT CFutureFtdcTraderApi
{
public:
///创建TraderApi
///@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录
///@return 创建出的UserApi
//modify for udp marketdata
static CFutureFtdcTraderApi *CreateFtdcTraderApi(const char *pszFlowPath = "", const bool bIsUsingUdp=false);
///删除接口对象本身
///@remark 不再使用本接口对象时,调用该函数删除接口对象
virtual void Release() = 0;
///初始化
///@remark 初始化运行环境,只有调用后,接口才开始工作
virtual void Init() = 0;
///等待接口线程结束运行
///@return 线程退出代码
virtual int Join() = 0;
///获取当前交易日
///@retrun 获取到的交易日
///@remark 只有登录成功后,才能得到正确的交易日
virtual const char *GetTradingDay() = 0;
///注册前置机网络地址
///@param pszFrontAddress:前置机网络地址。
///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:17001”。
///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。
virtual void RegisterFront(char *pszFrontAddress, unsigned int priority = 0) = 0;
///注册回调接口
///@param pSpi 派生自回调接口类的实例
virtual void RegisterSpi(CFutureFtdcTraderSpi *pSpi) = 0;
///订阅私有流。
///@param nResumeType 私有流重传方式
/// FUTURE_TERT_RESTART:从本交易日开始重传
/// FUTURE_TERT_RESUME:从上次收到的续传
/// FUTURE_TERT_QUICK:只传送登录后私有流的内容
///@remark 该方法要在Init方法前调用。若不调用则不会收到私有流的数据。
virtual void SubscribePrivateTopic(FUTURE_TE_RESUME_TYPE nResumeType) = 0;
///订阅公共流。
///@param nResumeType 公共流重传方式
/// FUTURE_TERT_RESTART:从本交易日开始重传
/// FUTURE_TERT_RESUME:从上次收到的续传
/// FUTURE_TERT_QUICK:只传送登录后公共流的内容
///@remark 该方法要在Init方法前调用。若不调用则不会收到公共流的数据。
virtual void SubscribePublicTopic(FUTURE_TE_RESUME_TYPE nResumeType) = 0;
///客户端认证请求
virtual int ReqAuthenticate(CFutureFtdcReqAuthenticateField *pReqAuthenticateField, int nRequestID) = 0;
///用户登录请求
virtual int ReqUserLogin(CFutureFtdcReqUserLoginField *pReqUserLoginField, int nRequestID) = 0;
///登出请求
virtual int ReqUserLogout(CFutureFtdcUserLogoutField *pUserLogout, int nRequestID) = 0;
///用户口令更新请求
virtual int ReqUserPasswordUpdate(CFutureFtdcUserPasswordUpdateField *pUserPasswordUpdate, int nRequestID) = 0;
///资金账户口令更新请求
virtual int ReqTradingAccountPasswordUpdate(CFutureFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, int nRequestID) = 0;
///报单录入请求
virtual int ReqOrderInsert(CFutureFtdcInputOrderField *pInputOrder, int nRequestID) = 0;
///报单操作请求
virtual int ReqOrderAction(CFutureFtdcInputOrderActionField *pInputOrderAction, int nRequestID) = 0;
///查询最大报单数量请求
virtual int ReqQueryMaxOrderVolume(CFutureFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, int nRequestID) = 0;
///投资者结算结果确认
virtual int ReqSettlementInfoConfirm(CFutureFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, int nRequestID) = 0;
///执行宣告录入请求
virtual int ReqExecOrderInsert(CFutureFtdcInputExecOrderField *pInputExecOrder, int nRequestID) = 0;
///执行宣告操作请求
virtual int ReqExecOrderAction(CFutureFtdcInputExecOrderActionField *pInputExecOrderAction, int nRequestID) = 0;
///报价录入请求
virtual int ReqQuoteInsert(CFutureFtdcInputQuoteField *pInputQuote, int nRequestID) = 0;
///报价操作请求
virtual int ReqQuoteAction(CFutureFtdcInputQuoteActionField *pInputQuoteAction, int nRequestID) = 0;
///询价操作请求
virtual int ReqForQuote(CFutureFtdcInputForQuoteField *pInputForQuote, int nRequestID) = 0;
///请求资金内转
virtual int ReqInternalTransfer(CFutureFtdcInternalTransferField *pInternalTransfer, int nRequestID) = 0;
///期货发起银行资金转期货请求
virtual int ReqFromBankToFutureByFuture(CFutureFtdcReqTransferField *pReqTransfer, int nRequestID) = 0;
///期货发起期货资金转银行请求
virtual int ReqFromFutureToBankByFuture(CFutureFtdcReqTransferField *pReqTransfer, int nRequestID) = 0;
protected:
~CFutureFtdcTraderApi(){};
};
#ifndef WINDOWS
#if __GNUC__ >= 4
#pragma GCC visibility pop
#endif
#endif
#endif
|
// LogOnDlg.cpp: 구현 파일
//
#include "pch.h"
#include "ClientDemo.h"
#include "LogOnDlg.h"
#include "afxdialogex.h"
#include "ClientSocket.h"
#include "ClientDemoDlg.h"
#define WM_CLIENT_LOGON WM_USER + 4
// CLogOnDlg 대화 상자
IMPLEMENT_DYNAMIC(CLogOnDlg, CDialogEx)
CLogOnDlg::CLogOnDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DIALOG_LOGON, pParent)
, m_strUID(_T(""))
, m_nUPw(NULL)
{
}
CLogOnDlg::~CLogOnDlg()
{
}
void CLogOnDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_ID, m_strUID);
DDX_Text(pDX, IDC_EDIT_PW, m_nUPw);
DDX_Control(pDX, IDC_COMBO_SELSV, m_cbServerNo);
}
BEGIN_MESSAGE_MAP(CLogOnDlg, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON_ACCEPT, &CLogOnDlg::OnBnClickedButtonAccept)
END_MESSAGE_MAP()
// CLogOnDlg 메시지 처리기
void CLogOnDlg::OnBnClickedButtonAccept()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
UpdateData(TRUE);
CString mesForm;
int serverNo = m_cbServerNo.GetCurSel();
CClientDemoDlg* pMainDlg = (CClientDemoDlg*)AfxGetMainWnd();
pMainDlg->m_ClientSocket.SetWnd(this->m_hWnd);
pMainDlg->m_ClientSocket.Create();
if (pMainDlg->m_ClientSocket.Connect(TESTIP, SERVER_PORT_0) == FALSE) {
AfxMessageBox(_T("ERROR : FAILED TO CONNECT SERVER"));
PostQuitMessage(0);
return;
}
else {
mesForm.Format(_T("%d\t%s\t%d\n"), WM_CLIENT_LOGON, m_strUID.GetString(), m_nUPw);
#ifdef _UNICODE
pMainDlg->m_ClientSocket.Send(mesForm, mesForm.GetLength() * 2);
#else
pMainDlg->m_ClientSocket.Send(mesForm, mesForm.GetLength() * 3);
#endif
}
}
|
#include "_pch.h"
#include "MoveObjView.h"
#include <boost/algorithm/string.hpp>
#include <wx/statline.h>
#include "RecentDstOidPresenter.h"
using namespace wh;
//---------------------------------------------------------------------------
class Node
:public boost::noncopyable
{
public:
Node(const Node* parent, int tid = 0, void* val = nullptr)
:mParent(parent), mTypeId(tid), mVal(val)
{}
const Node* mParent;
int mTypeId;
void* mVal;
std::vector< std::shared_ptr<Node> > mChilds;
};
//---------------------------------------------------------------------------
class DvModel
: public wxDataViewModel
{
void SetTree(const ObjTree* tree, std::shared_ptr<Node>& node)
{
if (!tree)
return;
auto view_node = node.get();
view_node->mChilds.clear();
view_node->mChilds.reserve(tree->mType.size());
auto& types = view_node->mChilds;
for (const auto& tp : tree->mType)
{
auto type_node = std::make_shared<Node>(view_node, 10, (void*)&tp);
auto rng = tree->GetTypeRange(tp.mId);
while (rng.first != rng.second)
{
const Obj* obj_data = rng.first.operator->();
std::wstring obj_name = obj_data->mTitle.ToStdWstring();
boost::algorithm::to_lower(obj_name);
if (mFilterStr.empty() || std::wstring::npos != obj_name.find(mFilterStr))
{
auto obj_node = std::make_shared<Node>(type_node.get(), 20, (void*)obj_data);
type_node->mChilds.emplace_back(obj_node);
}
++rng.first;
}//while (rng.first != rng.second)
if (type_node->mChilds.size())
types.emplace_back(type_node);
}//for
}
void RebuldTree()
{
if (!mFilterStr.empty() || !mRecentEnable) // mode filter
{
//mRootNode->mChilds.clear();
//mRootNode->mChilds.emplace_back(mDstNode);
mDstNode->mParent = nullptr;
mRootNode = mDstNode;
}
else // mode all
{
//mRootNode->mChilds.clear();
//mRootNode->mChilds.emplace_back(mRecentNode);
//mRootNode->mChilds.emplace_back(mDstNode);
mDstNode->mParent = mTopRootNode.get();
mRootNode = mTopRootNode;
}
this->Cleared();
}
public:
const Node& GetNode()const{ return *mRootNode; };
const Node& GetDstNode()const{ return *mDstNode; };
DvModel()
:wxDataViewModel(), mRootNode(new Node(nullptr))
{
mRecentNode = std::make_shared<Node>(mRootNode.get(), 1, (void*)&mRecentTree);
mDstNode = std::make_shared<Node>(mRootNode.get(), 1, (void*)&mDstTree);
mRootNode->mChilds.emplace_back(mRecentNode);
mRootNode->mChilds.emplace_back(mDstNode);
mTopRootNode = mRootNode;
}
void SetRecentEnable(bool enable)
{
mRecentEnable = enable;
RebuldTree();
}
void SetFilter(const wxString& str)
{
auto new_ss = std::wstring(str.ToStdWstring());
boost::algorithm::to_lower(new_ss);
if (mFilterStr != new_ss)
{
mFilterStr = new_ss;
SetTree(mDstTree, mDstNode);
RebuldTree();
}
}
void SetDstTree(const ObjTree& tree)
{
mDstTree = &tree;
SetTree(mDstTree, mDstNode);
RebuldTree();
}
void SetRecentTree(const ObjTree& tree)
{
mRecentTree = &tree;
std::wstring tmp;
tmp.swap(mFilterStr);
SetTree(mRecentTree, mRecentNode);
tmp.swap(mFilterStr);
RebuldTree();
}
virtual bool IsContainer(const wxDataViewItem &item)const override
{
if ( !item.IsOk())
return true;
auto node = static_cast<Node*> (item.GetID());
if (20 == node->mTypeId)
return false;
return true;
}
virtual wxDataViewItem GetParent(const wxDataViewItem &item) const override
{
if (!item.IsOk())
wxDataViewItem();
auto node = static_cast<Node*> (item.GetID());
if (0 == node->mTypeId )
return wxDataViewItem();
if( 1 == node->mTypeId)
return wxDataViewItem();
if (nullptr==node->mParent)
return wxDataViewItem();
if (mRootNode.get() == node->mParent)
return wxDataViewItem();
return wxDataViewItem((void*)node->mParent);
}
virtual unsigned int GetChildren(const wxDataViewItem &parent, wxDataViewItemArray &array) const override
{
const Node* parent_node = parent.IsOk() ?
static_cast<Node*> (parent.GetID())
: mRootNode.get();
if (20 == parent_node->mTypeId)
return 0;
for (size_t i = 0; i < parent_node->mChilds.size();++i)
{
const Node* ch = parent_node->mChilds[i].get();
wxDataViewItem item((void*)ch);
array.Add(item);
}
return array.size();
}
virtual unsigned int GetColumnCount() const override
{
return 2;
}
virtual wxString GetColumnType(unsigned int col) const
{
switch (col)
{
case 0: return "wxDataViewIconText";
default: break;
}
return "string";
}
virtual void GetValue(wxVariant & variant,
const wxDataViewItem & item,
unsigned int col
) const override
{
;
switch (col)
{
case 0:
{
Node* node = static_cast<Node*> (item.GetID());
switch (node->mTypeId)
{
case 1:
{
if (node->mVal == &mRecentTree)
variant << wxDataViewIconText("Недавние", ResMgr::GetInstance()->m_ico_history24);
else if (node->mVal == &mDstTree)
variant << wxDataViewIconText("Все", ResMgr::GetInstance()->m_ico_folder_type24);
}
break;
case 10:
{
auto cls = static_cast<Type*> (node->mVal);
variant << wxDataViewIconText(cls->mTitle, ResMgr::GetInstance()->m_ico_type_num24);
}
break;
case 20:
{
auto obj = static_cast<Obj*> (node->mVal);
variant << wxDataViewIconText(obj->mTitle, wxNullIcon);
}
break;
default: break;
}
if(variant.IsNull())
variant << wxDataViewIconText("*ERROR*", wxNullIcon);
}
break;
case 1:
{
auto node = static_cast<Node*> (item.GetID());
if (20 == node->mTypeId)
{
auto obj = static_cast<Obj*> (node->mVal);
variant = obj->mPath;
}
}//case 1:
break;
default: break;
}
if (variant.IsNull())
variant << wxDataViewIconText("*ERROR*", wxNullIcon);
}
bool SetValue(const wxVariant &, const wxDataViewItem &, unsigned int)override
{
return false;
}
protected:
const ObjTree* mRecentTree = nullptr;
const ObjTree* mDstTree = nullptr;
std::shared_ptr<Node> mTopRootNode;
std::shared_ptr<Node> mRootNode;
std::shared_ptr<Node> mRecentNode;
std::shared_ptr<Node> mDstNode;
std::wstring mFilterStr;
bool mRecentEnable=true;
};//class DwModel
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
XMoveObjView::XMoveObjView(wxWindow* parent)
{
mFrame = new wxDialog(parent, wxID_ANY, "Перемещение"
, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
const wxIcon ico("ICO_MOVE_24", wxBITMAP_TYPE_ICO_RESOURCE, 24, 24);
mFrame->SetIcon(ico);
mFrame->SetMinSize(mFrame->GetSize());
mFrame->SetSize(mFrame->GetSize()*1.8);
wxSizer* szrMain = new wxBoxSizer(wxVERTICAL);
mInfo = new wxStaticText(mFrame, wxID_ANY, wxEmptyString);
mInfo->Wrap(-1);
szrMain->Add(mInfo, 0, wxALL | wxEXPAND, 5);
//Panel Object list
mObjListPanel = new wxPanel(mFrame);
mObjBrowser = std::make_shared<ViewTableBrowser>(mObjListPanel);
mObjBrowser->SetEditableQty(true);
mObjBrowser->SetVisibleQty(true);
wxSizer *objListSzr = new wxBoxSizer(wxVERTICAL);
objListSzr->Add(mObjBrowser->GetWnd(), 1, wxEXPAND, 5);
mObjListPanel->SetSizer(objListSzr);
// destination panel
mDstPanel = new wxPanel(mFrame);
BuildToolBar(mDstPanel);
BuildTree(mDstPanel);
wxSizer *dstSzr = new wxBoxSizer(wxVERTICAL);
dstSzr->Add(mToolBar, 0, wxALL | wxEXPAND, 0);
dstSzr->Add(mTree, 1, wxALL | wxEXPAND, 0);
mDstPanel->SetSizer(dstSzr);
szrMain->Add(mObjListPanel, 1, wxEXPAND, 5);
szrMain->Add(mDstPanel, 1, wxEXPAND, 5);
wxBoxSizer* msdbSizer = new wxBoxSizer(wxHORIZONTAL);
msdbSizer->Add(0, 0, 1, wxEXPAND, 5);
mBtnBack = new wxButton(mFrame, wxID_BACKWARD, "< Назад");
mBtnForward = new wxButton(mFrame, wxID_OK, "Далее >");
auto mbtnCancel = new wxButton(mFrame, wxID_CANCEL, "Закрыть");
msdbSizer->Add(mBtnBack, 0, wxALL, 5);
msdbSizer->Add(mBtnForward, 0, wxALL, 5);
msdbSizer->Add(mbtnCancel, 0, wxALL, 5);
szrMain->Add(msdbSizer, 0, wxEXPAND, 10);
mFrame->SetSizer(szrMain);
mFrame->Layout();
mFrame->Centre(wxBOTH);
mFrame->Bind(wxEVT_DESTROY, [this](wxWindowDestroyEvent& evt)
{
if (evt.GetWindow() != mFrame)
return;
mTimer.Stop();
mObjBrowser.reset();
mFrame = nullptr;
});
mFrame->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &XMoveObjView::OnCancel, this, wxID_CANCEL);
mFrame->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &XMoveObjView::OnOk, this, wxID_OK);
mFrame->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &XMoveObjView::OnBack, this, wxID_BACKWARD);
mTimer.Bind(wxEVT_TIMER, &XMoveObjView::OnTimer, this);
}
//---------------------------------------------------------------------------
XMoveObjView::XMoveObjView(const std::shared_ptr<IViewWindow>& parent)
:XMoveObjView(parent->GetWnd())
{
}
//---------------------------------------------------------------------------
XMoveObjView::~XMoveObjView()
{
//mFrame->Destroy();
//mFrame = nullptr;
}
//-----------------------------------------------------------------------------
void XMoveObjView::BuildToolBar(wxWindow* parent)
{
mToolBar = new wxAuiToolBar(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize
, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_PLAIN_BACKGROUND /*| wxAUI_TB_TEXT */);
{
std::function<void()> itemFunc = [this]()
{
wxBusyCursor busyCursor;
dynamic_cast<DvModel*>(mTree->GetModel())->SetFilter(wxEmptyString);
mFindCtrl->SetValue(wxEmptyString);
this->sigUpdate();
};
std::function<void(wxCommandEvent&)> eventFunctor
= std::bind(SafeCallEvent(), itemFunc, std::placeholders::_1);
const int winid(wxID_REFRESH);
const wxString label(L"Обновить");
const wxIcon& ico24 = ResMgr::GetInstance()->m_ico_refresh24;
mToolBar->AddTool(winid, label, ico24, label);
parent->Bind(wxEVT_COMMAND_MENU_SELECTED, eventFunctor, winid);
}
{
std::function<void()> itemFunc = [this]()
{
wxBusyCursor busyCursor;
bool enable = this->mToolBar->GetToolToggled(wxID_PROPERTIES);
this->sigEnableRecent(enable);
};
std::function<void(wxCommandEvent&)> eventFunctor
= std::bind(SafeCallEvent(), itemFunc, std::placeholders::_1);
const int winid = wxID_PROPERTIES;
const wxString label = L"Показать/скрыть недавние";
const wxIcon& ico24 = ResMgr::GetInstance()->m_ico_history24;
mToolBar->AddTool(winid, label, ico24, label, wxITEM_CHECK);
parent->Bind(wxEVT_COMMAND_MENU_SELECTED, eventFunctor, winid);
}
{
mToolBar->AddSeparator();
std::function<void()> itemFunc = [this]()
{
OnClickSearchBtn(wxCommandEvent());
};
std::function<void(wxCommandEvent&)> eventFunctor = std::bind(SafeCallEvent(), itemFunc, std::placeholders::_1);
// поиск|фильтр
//auto lbl = new wxStaticText(mToolBar, wxID_ANY, "Поиск по имени");
//mToolBar->AddControl(lbl, "Поиск2");
mFindCtrl = new wxTextCtrl(mToolBar, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER);
mFindCtrl->Bind(wxEVT_COMMAND_TEXT_ENTER, eventFunctor);
mFindCtrl->SetHint("фильтр");
mToolBar->AddControl(mFindCtrl, "поиск|фильтр");
const int winid = wxID_FIND;
const wxString label = L"Выполнить поиск|фильтр";
const wxIcon& ico24 = ResMgr::GetInstance()->m_ico_filter24;
auto tool = mToolBar->AddTool(winid, label, ico24, label, wxITEM_NORMAL);
tool->SetHasDropDown(true);
parent->Bind(wxEVT_AUITOOLBAR_TOOL_DROPDOWN, [this, tool](wxAuiToolBarEvent& evt)
{
if (evt.IsDropDownClicked())
{
wxMenu menu;
AppendBitmapMenu(&menu, wxID_FILE1, "Фильтр"
, ResMgr::GetInstance()->m_ico_filter24);
AppendBitmapMenu(&menu, wxID_FILE2, "Поиск"
, wxArtProvider::GetBitmap(wxART_FIND, wxART_TOOLBAR));
//tool->SetSticky(true);
wxRect rect = mToolBar->GetToolRect(tool->GetId());
wxPoint pt = mToolBar->ClientToScreen(rect.GetBottomLeft());
pt = mFrame->ScreenToClient(pt);
mFrame->PopupMenu(&menu, pt);
//tool->SetSticky(false);
//tool->SetSticky(true);
}
else if (evt.IsCommandEvent())
{
OnClickSearchBtn(evt);
}
}, winid);
parent->Bind(wxEVT_COMMAND_MENU_SELECTED, eventFunctor, wxID_FIND);
auto mgr = whDataMgr::GetInstance();
mFrame->Bind(wxEVT_COMMAND_MENU_SELECTED, [this, tool, mgr](wxCommandEvent& evt)
{
tool->SetBitmap(ResMgr::GetInstance()->m_ico_filter24);
mFindCtrl->SetHint("фильтр");
mToolBar->Refresh();
mgr->mRecentDstOidPresenter->SetFilterEnable(1);
this->OnClickSearchBtn(wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_FIND));
}
, wxID_FILE1);
mFrame->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &XMoveObjView::OnBack, this, wxID_BACKWARD);
mFrame->Bind(wxEVT_COMMAND_MENU_SELECTED, [this, tool, mgr](wxCommandEvent& evt)
{
tool->SetBitmap(wxArtProvider::GetBitmap(wxART_FIND, wxART_TOOLBAR));
mFindCtrl->SetHint("поиск");
mToolBar->Refresh();
mgr->mRecentDstOidPresenter->SetFilterEnable(0);
this->OnClickSearchBtn(wxCommandEvent(wxEVT_COMMAND_MENU_SELECTED, wxID_FIND));
}
, wxID_FILE2);
if (mgr->mRecentDstOidPresenter->GetFilterEnable())
{
mFindCtrl->SetHint("фильтр");
tool->SetBitmap(ResMgr::GetInstance()->m_ico_filter24);
mToolBar->Refresh();
}
else
{
mFindCtrl->SetHint("поиск");
tool->SetBitmap(wxArtProvider::GetBitmap(wxART_FIND, wxART_TOOLBAR));
mToolBar->Refresh();
}
}
mToolBar->Realize();
}
//-----------------------------------------------------------------------------
void XMoveObjView::AutosizeColumns()
{
//TEST_FUNC_TIME;
wxBusyCursor busyCursor;
for (size_t i = 0; i < mTree->GetColumnCount(); i++)
{
auto col_pos = mTree->GetModelColumnIndex(i);
auto col = mTree->GetColumn(col_pos);
if (col)
{
unsigned int bs = mTree->GetBestColumnWidth(i);
if (bs > 300)
bs = 300;
col->SetWidth(bs);
}
}
}
//-----------------------------------------------------------------------------
void XMoveObjView::BuildTree(wxWindow* parent)
{
mTree = new wxDataViewCtrl(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxDV_ROW_LINES | wxDV_VERT_RULES /*| wxDV_HORIZ_RULES*/);
auto dvModel = new DvModel();
mTree->AssociateModel(dvModel);
dvModel->DecRef();
mTree->AppendIconTextColumn("Имя", 0, wxDATAVIEW_CELL_INERT, 200,
wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE);
mTree->AppendTextColumn("Местоположение", 1, wxDATAVIEW_CELL_INERT, -1,
wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE);
//int ch = mTree->GetCharHeight();
//mTree->SetRowHeight(ch * 2 + 0);
mTree->SetRowHeight(26);
parent->Bind(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED, &XMoveObjView::OnActivated, this);
}
//-----------------------------------------------------------------------------
//virtual
void XMoveObjView::SetShow()//override;
{
StartCountdown();
mFrame->ShowModal();
}
//---------------------------------------------------------------------------
//virtual
void XMoveObjView::SetClose()//override;
{
StopCountdown();
mFrame->EndModal(wxID_CANCEL);
}
//-----------------------------------------------------------------------------
void XMoveObjView::OnClose(wxCloseEvent& evt)
{
StopCountdown();
this->sigUnlock();
SetClose();
}
//-----------------------------------------------------------------------------
void XMoveObjView::OnCancel(wxCommandEvent& evt)
{
OnClose(wxCloseEvent());
}
//-----------------------------------------------------------------------------
void XMoveObjView::OnBack(wxCommandEvent& evt)
{
int page = 0;
if (mDstPanel->IsShown())
page = 0;
else
page = 1;
SetSelectPage(page);
}
//-----------------------------------------------------------------------------
void XMoveObjView::GetSelection(std::set<int64_t>& sel)const
{
auto item = mTree->GetCurrentItem();
if (!item.IsOk())
return;
auto sel_node = static_cast<Node*>(item.GetID());
if (sel_node->mTypeId == 20)
{
auto sel_obj = static_cast<Obj*>(sel_node->mVal);
unsigned long ival;
if (sel_obj->mId.ToCULong(&ival))
sel.emplace(ival);
}
}
//-----------------------------------------------------------------------------
void XMoveObjView::OnOk(wxCommandEvent& evt)
{
if (!mDstPanel->IsShown())
{
SetSelectPage(1);
return;
}
sigExecute();
}
//---------------------------------------------------------------------------
void XMoveObjView::OnActivated(wxDataViewEvent& evt)
{
OnOk();
}
//---------------------------------------------------------------------------
void XMoveObjView::ExpandAll()
{
auto dvmodel = dynamic_cast<DvModel*>(mTree->GetModel());
const Node& root = dvmodel->GetNode();
wxDataViewItem dvitem((void*)&root);
ExpandTree(dvitem);
}
//---------------------------------------------------------------------------
void XMoveObjView::ExpandTree(const wxDataViewItem& dvitem, bool recursive)
{
if (!dvitem.IsOk())
return;
const Node* node = static_cast<const Node*>((void*)dvitem);
for (const auto& child : node->mChilds)
{
const Node* ch = child.get();
wxDataViewItem type((void*)ch);
mTree->Expand(type);
if (recursive)
{
wxDataViewItem dvitem((void*)ch);
ExpandTree(dvitem, recursive);
}
}
}
//---------------------------------------------------------------------------
void XMoveObjView::OnClickSearchBtn(wxCommandEvent& event)
{
auto dvmodel = dynamic_cast<DvModel*>(mTree->GetModel());
if (mFindCtrl->GetValue().IsEmpty())
{
dvmodel->SetFilter(mFindCtrl->GetValue());
ExpandAll();
return;
}
if ("фильтр" == mFindCtrl->GetHint())
{
dvmodel->SetFilter(mFindCtrl->GetValue());
ExpandAll();
return;
}
dvmodel->SetFilter("");
const auto& dst_node = dvmodel->GetDstNode();
std::wstring ss = mFindCtrl->GetValue();
boost::algorithm::to_lower(ss);
bool isFind = false;
for (const auto& tp : dst_node.mChilds)
{
for (const auto& obj : tp->mChilds)
{
const auto* obj_val = static_cast<const Obj*>(obj->mVal);
std::wstring str = obj_val->mTitle.ToStdWstring();
boost::algorithm::to_lower(str);
if (std::wstring::npos != str.find(ss))
{
wxDataViewItem item(obj.get());
mTree->Select(item);
mTree->SetCurrentItem(item);
mTree->EnsureVisible(item, mTree->GetColumn(0));
//mTree->SetFocus();
isFind = true;
break;
}
}//for
if (isFind)
break;
}//for (const auto& tp : dst_node.mChilds)
//ExpandAll();
}
//-----------------------------------------------------------------------------
//virtual
std::shared_ptr<ViewTableBrowser> XMoveObjView::GetViewObjBrowser()const
{
return mObjBrowser;
}
//---------------------------------------------------------------------------
//virtual
void XMoveObjView::UpdateRecent(const ObjTree& tree)//override
{
auto dvmodel = dynamic_cast<DvModel*>(mTree->GetModel());
dvmodel->SetRecentTree(tree);
}
//---------------------------------------------------------------------------
//virtual
void XMoveObjView::UpdateDst(const ObjTree& tree)//override
{
auto dvmodel = dynamic_cast<DvModel*>(mTree->GetModel());
dvmodel->SetDstTree(tree);
ExpandAll();
AutosizeColumns();
}
//---------------------------------------------------------------------------
//virtual
void XMoveObjView::EnableRecent(bool enable)//override
{
mToolBar->ToggleTool(wxID_PROPERTIES, enable);
auto dvmodel = dynamic_cast<DvModel*>(mTree->GetModel());
dvmodel->SetRecentEnable(enable);
ExpandAll();
}
//-----------------------------------------------------------------------------
void XMoveObjView::SetSelectPage(int page)
{
switch (page)
{
default:
case 0:
mObjListPanel->Show();
mDstPanel->Hide();
mBtnBack->Hide();
mBtnForward->SetLabel("Вперёд >");
mInfo->SetLabel("Внимание! "
"Выбранные объекты заблокированы на 10 минут для выполнения перемещения."
"\nДля перехода к выбору действий нажмите кнопку 'Далее >'"
"\nДля именения количества перемещаемых объектов один клик на количество.");
mFrame->Layout();
break;
case 1:
mObjListPanel->Hide();
mDstPanel->Show();
mBtnBack->Show();
mBtnForward->SetLabel("Выполнить");
mInfo->SetLabel(
"Выберети объект, в который необходимо переместить выбранные объекты "
"\nДля выполнения перемещения нажмите кнопку 'Выполнить'"
"\nили двойной клик левой кнопкой мыши на необходимом объекте."
);
mFrame->Layout();
break;
}
}
//-----------------------------------------------------------------------------
void XMoveObjView::OnTimer(wxTimerEvent &evt)
{
StepCountdown();
}
//-----------------------------------------------------------------------------
void XMoveObjView::StartCountdown()
{
mMillSecLeft = 1000 * 60 * 10;//10min
mTimer.Start(1000 * 10);//10sec
mFrame->SetTitle("Перемещение");
}
//-----------------------------------------------------------------------------
void XMoveObjView::StepCountdown()
{
if (mMillSecLeft > 0)
{
mMillSecLeft -= 1000 * 10;
mFrame->SetTitle(wxString::Format(
"Перемещение."
" Автосброс блокировки объекта через %d:%d"
, mMillSecLeft / 1000 / 60
, (mMillSecLeft / 1000) % 60));
}
else
{
mTimer.Stop();
mMillSecLeft = 0;
mFrame->SetTitle("Выполнение перемещения невозможно. "
"Перезапустите этот диалог ");
}
}
//-----------------------------------------------------------------------------
void XMoveObjView::StopCountdown()
{
mTimer.Stop();
}
|
// Created on: 1995-02-07
// Created by: Jacques GOUSSARD
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomInt_LineConstructor_HeaderFile
#define _GeomInt_LineConstructor_HeaderFile
#include <GeomAdaptor_Surface.hxx>
#include <TColStd_SequenceOfReal.hxx>
class Adaptor3d_TopolTool;
class IntPatch_Line;
//! Splits given Line.
class GeomInt_LineConstructor
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
GeomInt_LineConstructor();
//! Initializes me by two surfaces and corresponding
//! tools which represent boundaries of surfaces
void Load (const Handle(Adaptor3d_TopolTool)& D1, const Handle(Adaptor3d_TopolTool)& D2, const Handle(GeomAdaptor_Surface)& S1, const Handle(GeomAdaptor_Surface)& S2);
//! Splits line
Standard_EXPORT void Perform (const Handle(IntPatch_Line)& L);
//! Returns True if splitting was successful
Standard_Boolean IsDone() const;
//! Returns number of splits
Standard_Integer NbParts() const;
//! Return first and last parameters
//! for given index of split
void Part (const Standard_Integer I, Standard_Real& WFirst, Standard_Real& WLast) const;
protected:
Standard_EXPORT void TreatCircle (const Handle(IntPatch_Line)& aLine, const Standard_Real aTol);
private:
Standard_Boolean done;
TColStd_SequenceOfReal seqp;
Handle(Adaptor3d_TopolTool) myDom1;
Handle(Adaptor3d_TopolTool) myDom2;
Handle(GeomAdaptor_Surface) myHS1;
Handle(GeomAdaptor_Surface) myHS2;
};
#include <GeomInt_LineConstructor.lxx>
#endif // _GeomInt_LineConstructor_HeaderFile
|
//本题使用dijkstra算法的堆优化+邻接表,才避免了超时
// 基本思想与普通的dj相同,但在寻找最小的距离值时使用了优先队列
//这样就可以删去一层循环, 变为直接区队首元素.
//为了使用优先队列,定义一个结构体p来存编号与距离最小值
//并按照 距离最小值升序排列
//即可大大降低时间复杂度.
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
const int INF = 2147483647;//最大值
const int MARX = 1e5+10;
using namespace std;
//=============================================================
struct edge
{
int u,v,w,ne;//分存前点 后点 权重
}e[MARX<<1];
struct p
{
int num,diss;
bool operator < (const p &a) const
{
return diss > a.diss;
}
}tmp;
int head[MARX],dis[MARX];
bool f[MARX];
int num,n,m,s,x;
//=============================================================
void add(int u,int v,int w)//邻接表加入元素
{
e[++num].ne=head[u],head[u]=num;
e[num].u=u,e[num].v=v,e[num].w=w;
}
void dj(int s)
{
priority_queue <p> q;
tmp.num=s,tmp.diss=0;q.push(tmp);
for(int i=1;i<=n;i++) dis[i]=INF;//赋极值
dis[s]=0;//初始化
while(!q.empty())
{
int top=q.top().num; q.pop();
if(f[top]) continue;
f[top]=1;
for(int j=head[top];j;j=e[j].ne)//找k点的临点,并进行比较
{
if(dis[e[j].v] > dis[top]+e[j].w && (!f[e[j].v]))
{
dis[e[j].v] = dis[top]+e[j].w;
tmp.num=e[j].v;
tmp.diss=dis[e[j].v];
q.push(tmp);
}
}
}
}
//=============================================================
int main()
{
scanf("%d%d%d",&n,&m,&s);//输入
for(int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
}
dj(s);
for(int i=1;i<=n;i++) printf("%d ",dis[i]);
}
/*
//2019.10.10
By:Luckyblock
使用STL中的 pair类实现
简单好写
#include<cstdio>
#include<cstring>
#include<ctype.h>
#include<queue>
#define int long long
const int MARX = 2e6+10;
//=============================================================
struct edge
{
int u,v,w,ne;
}e[MARX<<1];
int n,m,num, head[MARX];
int dis[MARX];
bool vis[MARX];
//=============================================================
inline int read()
{
int s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
void add(int u,int v,int w)
{
e[++num].u = u,e[num].v = v, e[num].w = w;
e[num].ne = head[u], head[u] = num;
}
void dijkstra(int start)
{
std::priority_queue <std::pair<int,int> > q;
memset(dis,63,sizeof(dis));
dis[start] = 0 ;
q.push(std::make_pair(0,start));
for(; !q.empty(); )
{
std::pair <int,int> top = q.top(); q.pop();
if(vis[top.second]) continue;
vis[top.second] = 1;
for(int i=head[top.second]; i; i = e[i].ne)
if(dis[e[i].v] > dis[e[i].u] + e[i].w)
{
dis[e[i].v] = dis[e[i].u] + e[i].w;
q.push(std::make_pair(-dis[e[i].v], e[i].v));
}
}
}
//=============================================================
signed main()
{
n = read(), m = read();
int s = read();
for(int i=1; i<=m; i++)
{
int u = read(), v = read(), w = read();
add(u,v,w);
}
dijkstra(s);
for(int i=1; i<=n; i++) printf("%lld ",dis[i]);
}
*/
|
// Created on: 1991-04-03
// Created by: Remi GILET
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GccAna_Lin2d2Tan_HeaderFile
#define _GccAna_Lin2d2Tan_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Integer.hxx>
#include <TColgp_Array1OfLin2d.hxx>
#include <GccEnt_Array1OfPosition.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <GccEnt_Position.hxx>
class gp_Pnt2d;
class GccEnt_QualifiedCirc;
class gp_Lin2d;
//! This class implements the algorithms used to
//! create 2d lines tangent to 2 other elements which
//! can be circles or points.
//! Describes functions for building a 2D line:
//! - tangential to 2 circles, or
//! - tangential to a circle and passing through a point, or
//! - passing through 2 points.
//! A Lin2d2Tan object provides a framework for:
//! - defining the construction of 2D line(s),
//! - implementing the construction algorithm, and
//! consulting the result(s).
//! Some constructors may check the type of the qualified argument
//! and raise BadQualifier Error in case of incorrect couple (qualifier,
//! curv).
//! For example: "EnclosedCirc".
class GccAna_Lin2d2Tan
{
public:
DEFINE_STANDARD_ALLOC
//! This methods implements the algorithms used to
//! create 2d lines passing through 2 points.
//! Tolerance is used because we can't create a line
//! when the distance between the two points is too small.
Standard_EXPORT GccAna_Lin2d2Tan(const gp_Pnt2d& ThePoint1, const gp_Pnt2d& ThePoint2, const Standard_Real Tolerance);
//! This methods implements the algorithms used to
//! create 2d lines tangent to one circle and passing
//! through a point.
//! Exception BadQualifier is raised in the case of
//! EnclosedCirc
//! Tolerance is used because there is no solution
//! when the point is inside the solution according to
//! the tolerance.
Standard_EXPORT GccAna_Lin2d2Tan(const GccEnt_QualifiedCirc& Qualified1, const gp_Pnt2d& ThePoint, const Standard_Real Tolerance);
//! This methods implements the algorithms used to
//! create 2d lines tangent to 2 circles.
//! Exception BadQualifier is raised in the case of
//! EnclosedCirc
Standard_EXPORT GccAna_Lin2d2Tan(const GccEnt_QualifiedCirc& Qualified1, const GccEnt_QualifiedCirc& Qualified2, const Standard_Real Tolerance);
//! This method returns true when there is a solution
//! and false in the other cases.
Standard_EXPORT Standard_Boolean IsDone() const;
//! This method returns the number of solutions.
//! Raises NotDone if the construction algorithm didn't succeed.
Standard_EXPORT Standard_Integer NbSolutions() const;
//! Returns the solution number Index and raises OutOfRange
//! exception if Index is greater than the number of solutions.
//! Be careful: the Index is only a way to get all the
//! solutions, but is not associated to these outside the
//! context of the algorithm-object. Raises OutOfRange is raised if Index is greater than
//! the number of solutions.
//! It raises NotDone if the algorithm failed.
Standard_EXPORT gp_Lin2d ThisSolution (const Standard_Integer Index) const;
//! Returns the qualifiers Qualif1 and Qualif2 of the
//! tangency arguments for the solution of index Index
//! computed by this algorithm.
//! The returned qualifiers are:
//! - those specified at the start of construction when the
//! solutions are defined as enclosing or outside with
//! respect to the arguments, or
//! - those computed during construction (i.e. enclosing or
//! outside) when the solutions are defined as unqualified
//! with respect to the arguments, or
//! - GccEnt_noqualifier if the tangency argument is a point.
//! Exceptions
//! Standard_OutOfRange if Index is less than zero or
//! greater than the number of solutions computed by this algorithm.
//! StdFail_NotDone if the construction fails.
Standard_EXPORT void WhichQualifier (const Standard_Integer Index, GccEnt_Position& Qualif1, GccEnt_Position& Qualif2) const;
//! Returns information about the tangency point between the
//! result number Index and the first argument.
//! ParSol is the intrinsic parameter of the point PntSol on
//! the solution curv.
//! ParArg is the intrinsic parameter of the point PntSol on
//! the argument curv. Raises OutOfRange is raised if Index is greater than
//! the number of solutions.
//! It raises NotDone if the algorithm failed.
Standard_EXPORT void Tangency1 (const Standard_Integer Index, Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const;
//! Returns information about the tangency point between the
//! result number Index and the second argument.
//! ParSol is the intrinsic parameter of the point ParSol on
//! the solution curv.
//! ParArg is the intrinsic parameter of the point PntSol on
//! the argument curv. Raises OutOfRange is raised if Index is greater than
//! the number of solutions.
//! It raises NotDone if the algorithm failed.
Standard_EXPORT void Tangency2 (const Standard_Integer Index, Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const;
protected:
private:
Standard_Boolean WellDone;
Standard_Integer NbrSol;
TColgp_Array1OfLin2d linsol;
GccEnt_Array1OfPosition qualifier1;
GccEnt_Array1OfPosition qualifier2;
TColgp_Array1OfPnt2d pnttg1sol;
TColgp_Array1OfPnt2d pnttg2sol;
TColStd_Array1OfReal par1sol;
TColStd_Array1OfReal par2sol;
TColStd_Array1OfReal pararg1;
TColStd_Array1OfReal pararg2;
};
#endif // _GccAna_Lin2d2Tan_HeaderFile
|
//STLデバック機能をOFFにする
#define _SECURE_SCL (0)
#define _HAS_ITERATOR_DEBUGGING (0)
//GameLで使用するヘッダー
#include "GameL\SceneObjManager.h"
#include "GameL\DrawFont.h"
#include "GameL\Audio.h"
#include "GameL\DrawTexture.h"
//使用するネームスペース
using namespace GameL;
//使用ヘッダー
#include"SceneRanking.h"
#include "GameHead.h"
//コンストラクタ
CSceneRanking::CSceneRanking()
{
}
//デストラクタ
CSceneRanking::~CSceneRanking()
{
}
//初期化メソッド
void CSceneRanking::InitScene()
{
//背景オブジェクト作成
CObjRanking* or = new CObjRanking();
Objs::InsertObj(or, OBJ_RANKING, 4);
}
//実行中メソッド
void CSceneRanking::Scene()
{
}
|
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define ll long long int
#define pi pair<ll,ll>
#define pii pair<ll,pi>
#define f first
#define mp make_pair
#define mod 1000000007
#define s second
#define pb push_back
int main(int argc, char const *argv[])
{
int n,k;
cin >> n >> k;
std::vector<int> v(n);
for (int w_i = 0; w_i < n; +w_i)
{
cin >> v[w_i];
}
int count = 0;
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n ; ++j)
{
if((v[i] + v[j]) % k == 0) {
count++;
}
}
}
cout << count <<std::endl;
return 0;
}
|
#ifndef MULTIPLY_H
#define MULTIPLY_H
#include <QString>
#include "operation.h"
class Multiply : public Operation
{
public:
Multiply(double factor);
~Multiply();
double compute(const double input) const;
QString toQString(void) const;
protected:
double factor;
};
#endif // MULTIPLY_H
|
#include <iostream>
#include <algorithm>
#define MAX_DATA 10000
using namespace std;
struct node {
int priority;
node * left, *right;
int c; //размер дерева (правое + левое + корень)
int data;
bool HaveToAdd;
bool HaveToSet;
int HaveToAddValue;
int HaveToSetValue;
int RMQ;
int RSQ;
node(){
priority = rand() % 100 - 1;
left = right = NULL;
c = 1;
}
node(int a){
priority = rand() % 100 - 1;
left = right = NULL;
c = 1;
data = a;
RMQ = data;
RSQ = data;
HaveToAdd = 0;
HaveToSet = 0;
}
};
typedef node * item;
void SetAt(item &tree, int begin, int end, int newValue){
if (tree != NULL){
if (tree->c == end - begin + 1){
SetAt(tree->left, begin, tree->left->c);
SetAt(tree->right, tree->left->c + 1, end - tree->left->c - 1);
Push(tree);
tree->HaveToSet = 1;
tree->HaveToSetValue = newValue;
}
}
}
void Push(item x){
if (x->HaveToSet > 0){
x->data = x->HaveToSet;
x->HaveToSet = 0;
}
if (x->HaveToAdd > 0){
x->data += HaveToAddValue;
x->HaveToAdd = 0;
}
}
void merge(item & tree, item first, item second) {
if (!first || !second){
if (!first)
tree = second;
else
tree = first;
}
else if (first->priority > second->priority){
merge(first->right, first->right, second);
tree = first;
tree->c = tree->right->c + tree->left->c + 1;
tree->RSQ = tree->right->RSQ + tree->left->RSQ + tree->data;
tree->RMQ = min(tree->right->RMQ, tree->left->RMQ, tree->data);
}
else{
merge(second->left, first, second->left);
tree = second;
tree->c = tree->left->c + tree->right->c + 1;
tree->RSQ = tree->right->RSQ + tree->left->RSQ + tree->data;
tree->RMQ = min(tree->right->RMQ, tree->left->RMQ, tree->data);
}
}
void split(item tree, int i, item & left, item & right) {//cut 5 elements from the left side
/*if (!tree)
left = right = NULL;
else */if (i == tree->left->c){
left = tree->left;
right = tree;
right->left = NULL;
right->c = tree->c - tree->left->c;
right->RMQ = min(right->data, right->right->data);
right->RSQ = right->data + right->right->data;
}
else if (i < tree->left->c){
split(tree->left, i, left, tree->left);
right = tree;
right->c = right->left->c + right->right->c + 1;
right->RMQ = min(right->left->data, right->right->data);
right->RSQ = min(right->left->data, right->right->data);
}
else{
split(tree->right, i - tree->c - 1, tree->right, right);
left = tree;
left->c = left->left->c + left->right->c + 1;
left->RMQ = min(right->left->data, right->right->data);
left->RSQ = min(right->left->data, right->right->data);
}
}
void insert (item & tree, int i, item it) {
item l;
item r;
split(tree, i, l, r);
merge(l, l, it);
merge(tree, l, r);
}
void remove(item &tree, int i){
item l;
item deleted;
item r;
split(tree, i, l, r);
split(r, 1, deleted, r);
merge(tree, l, r);
}
void shift(item &tree, int begin, int end, int shiftBy){
int mid = end - shiftBy;
item left, right, firstPart, secondPart;
split(tree, end, tree, right);
split(tree, mid, tree, secondPart);
split(tree, begin, left, firstPart);
merge(tree, left, secondPart);
merge(tree, tree, firstPart);
merge(tree, tree, secondPart);
}
void Set(item &tree, int i, int newValue){
item itemToChange = Find(tree, i);
itemToChange->RSQ += (newValue - itemToChange->data);
itemToChange->RMQ = min(itemToChange->RMQ, newValue);
itemToChange->data = newValue;
}
void Add(item &tree, int i, int addValue){
item itemToChange = Find(tree, i);
itemToChange->RSQ += addValue;
itemToChange->RMQ = min(itemToChange->left->data, itemToChange->right->data);
itemToChange->data = addValue;
}
item Find(item tree, int i){
if (i == tree->left->c)
return tree;
else if (tree->left->c > i)
Find(tree->left, i);
else
Find(tree->right, i);
}
void SetAt(item &tree, int begin, int end, int newValue){
}
int RMQ(item tree, int begin, int end){
if (!tree)
return MAX_DATA;
if (tree->left->c + 1 < begin)
return RMQ(tree->right, begin - tree->left->c - 1, end - tree->left->c - 1);
else if (tree->left->c > end)
return RMQ(tree->left, begin, end);
else if (tree->left->c + 1 == end){
return min(RMQ(tree->left, begin, end - 1), tree->data);
}
else{
return min(RMQ(tree->left, begin, tree->left->c), tree->data, RSQ(tree->right, 0, end - tree->left->c - 1));
}
}
int RSQ(item tree, int begin, int end){
if (!tree)
return 0;
else if (tree->left->c + 1 < begin)
return RSQ(tree->right, begin - tree->left->c - 1, end - tree->left->c - 1);
else if (tree->left->c > end)
return RSQ(tree->left, begin, end);
else if (tree->left->c + 1 == end){
return RSQ(tree->left, begin, end - 1) + tree->data;
}
else{
return RSQ(tree->left, begin, tree->left->c) + tree->data + RSQ(tree->right, 0, end - tree->left->c - 1);
}
}
int main(){
}
|
// Copyright (c) 2019, Ryo Currency Project
//
// Portions of this file are available under BSD-3 license. Please see ORIGINAL-LICENSE for details
// All rights reserved.
//
// Ryo changes to this code are in public domain. Please note, other licences may apply to the file.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2014-2017, SUMOKOIN
// Parts of this file are originally copyright (c) 2014-2017, The Monero Project
// Parts of this file are originally copyright (c) 2012-2013, The Cryptonote developers
#pragma once
#include <inttypes.h>
#include <stddef.h>
// This header emulates NEON instructions in IEEE 754 compilant way
// Don't expect to use this code for anything other than verificaiton
struct float32x4_t
{
float v[4];
};
struct int32x4_t
{
int32_t v[4];
};
struct uint32x4_t
{
uint32_t v[4];
};
inline int32x4_t vld1q_s32(int32_t* v)
{
int32x4_t r;
r.v[0] = v[0];
r.v[1] = v[1];
r.v[2] = v[2];
r.v[3] = v[3];
return r;
}
inline void vst1q_s32(int32_t* v, const int32x4_t& a)
{
v[0] = a.v[0];
v[1] = a.v[1];
v[2] = a.v[2];
v[3] = a.v[3];
}
inline float32x4_t vdupq_n_f32(float a)
{
float32x4_t r;
r.v[0] = a;
r.v[1] = a;
r.v[2] = a;
r.v[3] = a;
return r;
}
inline int32x4_t vdupq_n_s32(int32_t a)
{
int32x4_t r;
r.v[0] = a;
r.v[1] = a;
r.v[2] = a;
r.v[3] = a;
return r;
}
inline uint32x4_t vdupq_n_u32(uint32_t a)
{
uint32x4_t r;
r.v[0] = a;
r.v[1] = a;
r.v[2] = a;
r.v[3] = a;
return r;
}
template <size_t v>
inline void vrot_si32(int32x4_t& r)
{
uint8_t tmp[v];
uint8_t* vt = (uint8_t*)&r;
for(size_t i = 0; i < v; i++)
tmp[i] = vt[i];
for(size_t i = 0; i < 16 - v; i++)
vt[i] = vt[i + v];
size_t e = 16 - v;
for(size_t i = e; i < 16; i++)
vt[i] = tmp[i - e];
}
template <>
inline void vrot_si32<0>(int32x4_t& r)
{
}
inline float32x4_t vcvtq_f32_s32(const int32x4_t& v)
{
float32x4_t r;
r.v[0] = v.v[0];
r.v[1] = v.v[1];
r.v[2] = v.v[2];
r.v[3] = v.v[3];
return r;
}
inline int32x4_t vcvtq_s32_f32(const float32x4_t& v)
{
int32x4_t r;
r.v[0] = v.v[0];
r.v[1] = v.v[1];
r.v[2] = v.v[2];
r.v[3] = v.v[3];
return r;
}
inline int32x4_t vorrq_s32(const int32x4_t& a, const int32x4_t& b)
{
int32x4_t r;
r.v[0] = a.v[0] | b.v[0];
r.v[1] = a.v[1] | b.v[1];
r.v[2] = a.v[2] | b.v[2];
r.v[3] = a.v[3] | b.v[3];
return r;
}
inline int32x4_t veorq_s32(const int32x4_t& a, const int32x4_t& b)
{
int32x4_t r;
r.v[0] = a.v[0] ^ b.v[0];
r.v[1] = a.v[1] ^ b.v[1];
r.v[2] = a.v[2] ^ b.v[2];
r.v[3] = a.v[3] ^ b.v[3];
return r;
}
inline float32x4_t vaddq_f32(const float32x4_t& a, const float32x4_t& b)
{
float32x4_t r;
r.v[0] = a.v[0] + b.v[0];
r.v[1] = a.v[1] + b.v[1];
r.v[2] = a.v[2] + b.v[2];
r.v[3] = a.v[3] + b.v[3];
return r;
}
inline float32x4_t vsubq_f32(const float32x4_t& a, const float32x4_t& b)
{
float32x4_t r;
r.v[0] = a.v[0] - b.v[0];
r.v[1] = a.v[1] - b.v[1];
r.v[2] = a.v[2] - b.v[2];
r.v[3] = a.v[3] - b.v[3];
return r;
}
inline float32x4_t vmulq_f32(const float32x4_t& a, const float32x4_t& b)
{
float32x4_t r;
r.v[0] = a.v[0] * b.v[0];
r.v[1] = a.v[1] * b.v[1];
r.v[2] = a.v[2] * b.v[2];
r.v[3] = a.v[3] * b.v[3];
return r;
}
inline float32x4_t vdivq_f32(const float32x4_t& a, const float32x4_t& b)
{
float32x4_t r;
r.v[0] = a.v[0] / b.v[0];
r.v[1] = a.v[1] / b.v[1];
r.v[2] = a.v[2] / b.v[2];
r.v[3] = a.v[3] / b.v[3];
return r;
}
inline void vandq_f32(float32x4_t& v, uint32_t v2)
{
uint32x4_t* vt = (uint32x4_t*)&v;
vt->v[0] &= v2;
vt->v[1] &= v2;
vt->v[2] &= v2;
vt->v[3] &= v2;
}
inline void vorq_f32(float32x4_t& v, uint32_t v2)
{
uint32x4_t* vt = (uint32x4_t*)&v;
vt->v[0] |= v2;
vt->v[1] |= v2;
vt->v[2] |= v2;
vt->v[3] |= v2;
}
inline void veorq_f32(float32x4_t& v, uint32_t v2)
{
uint32x4_t* vt = (uint32x4_t*)&v;
vt->v[0] ^= v2;
vt->v[1] ^= v2;
vt->v[2] ^= v2;
vt->v[3] ^= v2;
}
inline uint32_t vheor_s32(const int32x4_t& a)
{
int32_t r;
r = a.v[0] ^ a.v[1] ^ a.v[2] ^ a.v[3];
return (uint32_t)r;
}
|
//===-- client/fwd.hh - Forward Definitions -----------------------*- C++
//-*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Forward definitions related to odb_client
///
//===----------------------------------------------------------------------===//
#pragma once
namespace odb {
class AbstractDataClient;
class TCPDataClient;
} // namespace odb
|
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <ctime>
#include "pageLib.h"
int main(int argc, char *argv[])
{
if (argc < 3) {
printf("Usage: read_fixed_len_page <page_file> <page_size>\n");
return 0;
}
int csvPageSize = atoi(argv[2]);
Record csvRecord;
Page *csvPage;
FILE *pageFile;
int readNumber = 0;
char *target_ptr;
int recordCount=0;
int pageCount=0;
timeval tim;
gettimeofday(&tim, NULL);
double t1=tim.tv_sec+(tim.tv_usec/1000000.0);
pageFile = fopen (argv[1] , "r");
if (pageFile == NULL)
perror ("Error opening file");
csvPage = (Page *)malloc(sizeof(Page));
init_fixed_len_page(csvPage, csvPageSize, SLOT_SIZE);
int page_count = 0;
while ( ! feof (pageFile) )
{
readNumber = fread(csvPage->data,csvPageSize, sizeof(char),pageFile);
if(readNumber == 0) {
break;
}
for (int i = 0; i < fixed_len_page_capacity(csvPage); i++){
if (hasData(csvPage, i)){
read_fixed_len_page(csvPage, i, &csvRecord);
for(int j = 0; j < csvRecord.size(); j++){
//DO NOT REMOVE THIS PRINTF
printf("%s", csvRecord[j]);
if (j != csvRecord.size() - 1) {
printf(",");
} else {
printf("\n");
}
}
recordCount++;
free_record(&csvRecord);
}
}
pageCount++;
}
gettimeofday(&tim, NULL);
double t2=tim.tv_sec+(tim.tv_usec/1000000.0);
printf("NUMBER OF RECORDS: %d \n", recordCount);
printf("NUMBER OF PAGES: %d \n", pageCount);
printf("TIME: %f \n", (t2-t1)*1000);
fclose(pageFile);
//free(pageFile);
free(csvPage->data);
free(csvPage);
return 0;
}
|
/*
* License:
* License does not expire.
* Can be distributed in infinitely projects
* Can be distributed and / or packaged as a code or binary product (sublicensed)
* Commercial use allowed under the following conditions :
* - Crediting the Author
* Can modify source-code
*/
/*
* File: ErrorHandler.h
* Author: Suirad <darius-suirad@gmx.de>
*
* Created on 14. Januar 2018, 03:28
*/
#ifndef ERRORHANDLER_H
#define ERRORHANDLER_H
#include <string>
namespace core {
//Enum With all Error Codes
enum ERROR_CODE {
SUCCESS = 0,
ERROR_INIT_GLFW = 1,
ERROR_INIT_GLEW = 2,
ERROR_ENGINE = 3,
ERROR_OPEN_FILE = 4,
ERROR_COMPILE_SHADER = 5,
ERROR_CREATING_FRAMEBUFFER = 6
};
//Print Error With Timestamp and Error Header
void err(std::string error, int errorCode, bool exit_ = false);
}
#endif /* ERRORHANDLER_H */
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
// only gravity will pull me down
// Minimize the sum of product
int t;
cin >> t;
long long n, res;
while (t--) {
cin >> n;
vector<long long> a(n);
vector<long long> b(n);
for(int i=0; i<n; i++) {
cin >> a[i];
}
for(int i=0; i<n; i++) {
cin >> b[i];
}
res = 0;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for(int i=0; i<n; i++) {
res += a[i]*b[n-i-1];
}
cout << res << endl;
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
struct frac{
int num;
int den;
};
int d = 0;
frac f[11];
int gcd(int a, int b){
while(a*b != 0){
if(a > b)
a = a%b;
else
b = b%a;
}
return a+b;
}
bool comp(frac a, frac b){
return (double)a.num/a.den < (double)b.num/b.den;
}
void fracGenerator(int n){
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= i; ++j) {
if(gcd(i,j)==1) {
frac a{j,i};
f[d] = a;
d++;
}
}
}
sort(f,f+d, comp);
}
int main(){
freopen("SXPS.inp", "r", stdin);
freopen("SXPS.out", "w", stdout);
int n,k;
cin >> n >> k;
fracGenerator(n);
cout << f[k-1].num << "/" << f[k-1].den << " ";
return 0;
}
|
#include "src/Math/Matrix33.h"
#include <memory>
#include "src/Math/Vector2.h"
#include "src/Math/Math.h"
namespace Math {
Matrix33::Matrix33() {}
Matrix33::Matrix33(const Matrix33& a) {
memcpy_s(m, sizeof(m), a.m, sizeof(a.m));
}
Matrix33::~Matrix33() {}
Matrix33& Matrix33::operator=(const Matrix33& a) {
memcpy_s(m, sizeof(m), a.m, sizeof(a.m));
return *this;
}
void Matrix33::set_identity() {
m[0][0] = m[1][1] = m[2][2] = 1.f;
m[0][1] = m[0][2] = 0.f;
m[1][0] = m[1][2] = 0.f;
m[2][0] = m[2][1] = 0.f;
}
void Matrix33::set_transposition() {
Matrix33 prev = *this;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
m[i][j] = prev.m[j][i];
}
}
}
void Matrix33::set_inverse() {
float delta =
m[0][0]*m[1][1]*m[2][2] + m[1][0]*m[2][1]*m[0][2] + m[2][0]*m[0][1]*m[1][2] -
m[0][0]*m[2][1]*m[1][2] - m[2][0]*m[1][1]*m[0][2] - m[1][0]*m[0][1]*m[2][2];
//計算できない場合は終了
if (delta == 0.f) return;
//逆数にして計算負荷軽減
delta = 1.f / delta;
//逆行列計算
Matrix33 prev = *this;
m[0][0] = (prev.m[1][1]*prev.m[2][2] - prev.m[1][2]*prev.m[2][1])*delta;
m[0][1] = (prev.m[0][2]*prev.m[2][1] - prev.m[0][1]*prev.m[2][2])*delta;
m[0][2] = (prev.m[0][1]*prev.m[1][2] - prev.m[0][2]*prev.m[1][1])*delta;
m[1][0] = (prev.m[1][2]*prev.m[2][0] - prev.m[1][0]*prev.m[2][2])*delta;
m[1][1] = (prev.m[0][0]*prev.m[2][2] - prev.m[0][2]*prev.m[2][0])*delta;
m[1][2] = (prev.m[0][2]*prev.m[1][0] - prev.m[0][0]*prev.m[1][2])*delta;
m[2][0] = (prev.m[1][0]*prev.m[2][1] - prev.m[1][1]*prev.m[2][0])*delta;
m[2][1] = (prev.m[0][1]*prev.m[2][0] - prev.m[0][0]*prev.m[2][1])*delta;
m[2][2] = (prev.m[0][0]*prev.m[1][1] - prev.m[0][1]*prev.m[1][0])*delta;
}
void Matrix33::set_translate(const Vector2& t) {
m[0][0] = m[1][1] = m[2][2] = 1.f;
m[0][2] = t.x;
m[1][2] = t.y;
m[0][1] = 0.f;
m[1][0] = 0.f;
m[2][0] = m[2][1] = 0.f;
}
void Matrix33::set_rotate(float deg) {
float s = Sin(deg);
float c = Cos(deg);
m[0][0] = m[1][1] = c;
m[2][2] = 1.f;
m[0][1] = -s;
m[1][0] = s;
m[0][2] = 0.f;
m[1][2] = 0.f;
m[2][0] = m[2][1] = 0.f;
}
void Matrix33::set_scale(const Vector2& s) {
m[0][0] = s.x;
m[1][1] = s.y;
m[2][2] = 1.f;
m[0][1] = m[0][2] = 0.f;
m[1][0] = m[1][2] = 0.f;
m[2][0] = m[2][1] = 0.f;
}
Matrix33& Matrix33::operator*=(const Matrix33& a) {
//同じベクトルで問題なし
float t[3][3];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
t[i][j] = 0.f;
for (int k = 0; k < 3; ++k) {
t[i][j] += (m[i][k] * a.m[k][j]);
}
}
}
memcpy_s(m, sizeof(m), t, sizeof(t));
return *this;
}
void Matrix33::multiply(Vector2* out, const Vector2& in) {
//同じベクトルで問題なし
float dx = in.x;
out->x = m[0][0] * dx + m[0][1] * in.y + m[0][2];
out->y = m[1][0] * dx + m[1][1] * in.y + m[1][2];
}
void Matrix33::world_mat_convert_for_normal() {
set_inverse();
set_transposition();
}
}//namespace Math
|
#include <iostream>
#include "DES.h"
using namespace std;
char encrypt( char text , unsigned short int key ){
unsigned char value,subkey1, subkey2;
value = text;
generateSubkeys( key , &subkey1, &subkey2 );
ip( &value );
}
void generateSubkeys( unsigned short int key, unsigned char* subkey1, unsigned char* subkey2 ){
unsigned short int left, right;
unsigned short int k;
k = p10( key );
//Split the key
left = (k >> 5) & 31;
right = k & 31;
//Circular Shift Left
left = ( left << 1 | left >> 4 ) & 31;
right = ( right << 1 | right >> 4 ) & 31;
*subkey1 = subKey1( left , right );
*subkey2 = subKey2( left , right );
}
short int p10( unsigned short int key ){
/**
* _________________________________________
* | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | Original
* | 8 | 6 | 9 | 4 | 7 | 1 | 10 | 2 | 3 | 5 | Permutación
*
*/
Permutation10 auxKey, aux;
aux.word = key;
auxKey.word = 0;
auxKey.p1 = aux.p5;
auxKey.p2 = aux.p3;
auxKey.p3 = aux.p2;
auxKey.p4 = aux.p10;
auxKey.p5 = aux.p1;
auxKey.p6 = aux.p7;
auxKey.p7 = aux.p4;
auxKey.p8 = aux.p9;
auxKey.p9 = aux.p6;
auxKey.p10 = aux.p8;
return auxKey.word;
}
unsigned char subKey1( unsigned short int left, unsigned short int rigth ){
unsigned short int aux;
unsigned char subKey;
aux = left << 5 | rigth;
subKey = p8( aux );
return subKey;
}
unsigned char subKey2( unsigned short int left, unsigned short int rigth ){
short int aux;
char subKey;
//Circular Shift Left
left = ( left << 2 | left >> 3 ) & 31;
rigth = ( rigth << 2 | rigth >> 3 ) & 31;
aux = left << 5 | rigth;
subKey = p8( aux );
return subKey;
}
short int p8( unsigned short int key ){
/**
* ________________________________________
* | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | Original
* | - | - | 5 | 8 | 4 | 7 | 3 | 6 | 1 | 2 | Permutación de compresión
*
*/
Permutation8 aux;
Permutation10 auxKey;
auxKey.word = key;
aux.word = 0;
aux.p1 = auxKey.p2;
aux.p2 = auxKey.p1;
aux.p3 = auxKey.p6;
aux.p4 = auxKey.p3;
aux.p5 = auxKey.p7;
aux.p6 = auxKey.p4;
aux.p7 = auxKey.p8;
aux.p8 = auxKey.p5;
return aux.word;
}
void ip( unsigned char *text){
/**
* _______________________________
* | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | Original
* | 7 | 3 | 6 | 8 | 5 | 1 | 4 | 2 | Permutación
*
*/
Permutation8 aux, final;
aux.word = *text;
final.p1 = aux.p2;
final.p2 = aux.p4;
final.p3 = aux.p1;
final.p4 = aux.p5;
final.p5 = aux.p8;
final.p6 = aux.p6;
final.p7 = aux.p3;
final.p8 = aux.p7;
*text = final.word;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef QUICK_COMPOSITE_H
#define QUICK_COMPOSITE_H
#include "adjunct/quick_toolkit/widgets/QuickBackgroundWidget.h"
#include "modules/widgets/OpWidget.h"
class OpButton;
class QuickButton;
/**
* A widget that groups several widgets so that they act as one.
*
* OpComposite can be used to build widgets like thumbnails.
*
* An OpComposite will update its "hover" skin state as the mouse pointer
* moves over itself or any of its descendants.
*
* If you add a button to an OpComposite and pass it to SetActionButton(),
* any mouse click on the descendants of the OpComposite will be passed to
* the button which was passed in aforementioned method.
*
* @authors Wojciech Dzierzanowski (wdzierzanowski), Deepak Arora (deepaka),
* Karianne Ekern (karianne.ekern)
*
*/
class OpComposite : public OpWidget
{
public:
OpComposite() : m_hovered(false), m_button(NULL) { }
void SetActionButton(OpButton* button);
// OpWidget
virtual Type GetType() { return OpTypedObject::WIDGET_TYPE_COMPOSITE; }
virtual void AddChild(OpWidget* child, BOOL is_internal_child = FALSE, BOOL first = FALSE);
virtual OP_STATUS GetText(OpString& text);
virtual void OnMouseMove(const OpPoint& point);
virtual void OnMouseLeave();
virtual void OnMouseUp(const OpPoint& point, MouseButton button, UINT8 nclicks);
virtual void OnMouseDown(const OpPoint& point, MouseButton button, UINT8 nclicks);
virtual void OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks);
virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse = FALSE);
virtual OpScopeWidgetInfo* CreateScopeWidgetInfo();
// OpWidgetListener
virtual void OnFocusChanged(OpWidget* widget, FOCUS_REASON reason) { GenerateSetSkinState(this, SKINSTATE_SELECTED, widget->IsFocused() ? true : false); }
// OpInputContext
virtual void SetFocus(FOCUS_REASON reason);
private:
class CompositeWidgetInfo;
void GenerateSetSkinState(OpWidget* widget, SkinState mask, bool state);
bool m_hovered;
OpButton* m_button;
};
class QuickComposite
: public QuickBackgroundWidget<OpComposite>
{
typedef QuickBackgroundWidget<OpComposite> Base;
IMPLEMENT_TYPEDOBJECT(Base);
public:
QuickComposite() : Base(true) {}
};
#endif // QUICK_COMPOSITE_H
|
/*
Petar 'PetarV' Velickovic
Algorithm: Cycle Detection
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 5001
using namespace std;
typedef long long lld;
int n;
struct Node
{
vector<int> adj;
};
Node graf[MAX_N];
bool mark[MAX_N];
//Algoritam za trazenje ciklusa u neusmerenom grafu, koristeci DFS
//Slozenost: O(V + E)
inline bool DFS(int start)
{
stack<int> dfs_stek;
stack<int> previous;
dfs_stek.push(start);
previous.push(-1);
while (!dfs_stek.empty())
{
int xt = dfs_stek.top();
int pt = previous.top();
dfs_stek.pop();
previous.pop();
mark[xt] = true;
for (int i=0;i<graf[xt].adj.size();i++)
{
if (!mark[graf[xt].adj[i]])
{
dfs_stek.push(graf[xt].adj[i]);
previous.push(xt);
mark[graf[xt].adj[i]] = true;
}
else if (graf[xt].adj[i] != pt) return true;
}
}
return false;
}
inline bool hasCycle(int n)
{
for (int i=0;i<n;i++)
{
if (!mark[i])
{
if (DFS(i)) return true;
}
}
return false;
}
int main()
{
n = 6;
graf[0].adj.push_back(1);
graf[1].adj.push_back(0);
graf[0].adj.push_back(2);
graf[2].adj.push_back(0);
graf[2].adj.push_back(1);
graf[1].adj.push_back(2);
graf[3].adj.push_back(5);
graf[5].adj.push_back(3);
printf("%d\n",hasCycle(n) ? 1 : 0);
return 0;
}
|
#ifndef __INCLUDE_RTSP_SESSION_H__
#define __INCLUDE_RTSP_SESSION_H__
#include "Def.h"
#include "Thread.h"
#include "TcpSock.h"
#include "Mutex.h"
#include <time.h>
#include <string>
#include "DataSrc.h"
class CRtspSession : CThread
{
public:
CRtspSession();
~CRtspSession();
public:
int Start( int fd, NotifyFun fun, long user_info );
private:
virtual void thread_proc( long user_info );
int recv_data();
int handle_data();
int parse_data( const char* data, int len );
int handle_cmd( const char* data, int len );
private:
NotifyFun m_fun;
long m_user_info;
CTcpSock m_sock;
enum{
MAX_RECV_BUF_LEN = 1024*4,
};
char m_recv_buf[MAX_RECV_BUF_LEN];
uint32_t m_recv_len;
CMutex m_mutex;
CDataSrc m_data_src;
private:
RtspMethodT parse_method( const char* data, int len );
void parser_common( const char* data, int len );
int parser_url( const char* data, int len );
int get_str( const char* data, int len, const char* s_mark, const char* e_mark, char* dest, int dest_len );
int handle_describe( const char* data, int len );
int handle_setup( const char* data, int len );
int handle_play( const char* data, int len );
int handle_pause();
int handle_teardowm();
int handle_other_method();
int send_simple_cmd( int code );
int send_cmd( const char* data, int len );
private:
static void notify_fun( long id, long msg, long user_info );
private:
char m_cseq[128];
int m_rtp_ch;
char m_session[128];
char m_url[256];
};
#endif
|
// RsaToolbox includes
#include "General.h"
#include "VnaPulseGenerator.h"
#include "VnaChannel.h"
#include "Vna.h"
using namespace RsaToolbox;
// Qt includes
#include <QString>
VnaPulseGenerator::VnaPulseGenerator(QObject *parent) :
QObject(parent)
{
placeholder.reset(new Vna());
_vna = placeholder.data();
_channel.reset(new VnaChannel());
_channelIndex = 0;
}
VnaPulseGenerator::VnaPulseGenerator(const VnaPulseGenerator &other)
{
if (other.isFullyInitialized()) {
_vna = other._vna;
_channel.reset(new VnaChannel(*other._channel.data()));
_channelIndex = other._channelIndex;
}
else {
placeholder.reset(new Vna());
_vna = placeholder.data();
_channel.reset(new VnaChannel());
_channelIndex = 0;
}
}
VnaPulseGenerator::VnaPulseGenerator(Vna *vna, VnaChannel *channel, QObject *parent) :
QObject(parent)
{
_vna = vna;
_channel.reset(new VnaChannel(*channel));
_channelIndex = channel->index();
}
VnaPulseGenerator::VnaPulseGenerator(Vna *vna, uint channelIndex, QObject *parent) :
QObject(parent)
{
_vna = vna;
_channel.reset(new VnaChannel(vna, channelIndex, this));
_channelIndex = channelIndex;
}
VnaPulseGenerator::~VnaPulseGenerator() {
}
bool VnaPulseGenerator::isOn() {
QString scpi = ":SENS%1:PULS:GEN?\n";
scpi = scpi.arg(_channelIndex);
return _vna->query(scpi).trimmed() == "1";
}
void VnaPulseGenerator::on(bool isOn) {
QString scpi = ":SENS%1:PULS:GEN %2\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(isOn? "1" : "0");
_vna->write(scpi);
}
void VnaPulseGenerator::off(bool isOff) {
on(!isOff);
}
VnaPulseType VnaPulseGenerator::type() {
QString type = ":SENS%1:PULS:GEN1:TYPE?\n";
type = type.arg(_channelIndex);
type = _vna->query(type).trimmed();
return vnaPulseTypeFromScpi(type);
}
void VnaPulseGenerator::setType(VnaPulseType type) {
QString scpi = ":SENS%1:PULS:GEN1:TYPE %2\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(toScpi(type));
_vna->write(scpi);
}
double VnaPulseGenerator::pulseWidth_s() {
QString scpi = ":SENS%1:PULS:GEN1:WIDT?\n";
scpi = scpi.arg(_channelIndex);
return _vna->query(scpi).trimmed().toDouble();
}
void VnaPulseGenerator::setPulseWidth(double value, SiPrefix prefix) {
QString scpi = ":SENS%1:PULS:GEN1:WIDT %2 %3\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(value);
scpi = scpi.arg(toString(prefix, Units::Seconds));
_vna->write(scpi);
}
double VnaPulseGenerator::period_s() {
QString scpi = ":SENS%1:PULS:GEN1:PER?\n";
scpi = scpi.arg(_channelIndex);
return _vna->query(scpi).trimmed().toDouble();
}
void VnaPulseGenerator::setPeriod(double value, SiPrefix prefix) {
QString scpi = ":SENS%1:PULS:GEN1:PER %2 %3\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(value);
scpi = scpi.arg(toString(prefix, Units::Seconds));
_vna->write(scpi);
}
bool VnaPulseGenerator::isInverted() {
QString scpi = ":SENS%1:PULS:GEN1:POL?\n";
scpi = scpi.arg(_channelIndex);
return _vna->query(scpi).trimmed() == "INV";
}
void VnaPulseGenerator::setInverted(bool isInverted) {
QString scpi = ":SENS%1:PULS:GEN1:POL %2\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(isInverted? "INV" : "NORM");
_vna->write(scpi);
}
bool VnaPulseGenerator::isChannelSpecific() {
QString scpi = "SENS%1:PULS:GEN1:MODE?\n";
scpi = scpi.arg(_channelIndex);
const QString result = _vna->query(scpi).trimmed();
return result.startsWith("CSP", Qt::CaseInsensitive);
}
void VnaPulseGenerator::setChannelSpecific(bool isSpecific) {
QString scpi = "SENS%1:PULS:GEN1:MODE %2\n";
scpi = scpi.arg(_channelIndex);
scpi = scpi.arg(isSpecific? "CSP" : "CONT");
_vna->write(scpi);
}
void VnaPulseGenerator::operator=(VnaPulseGenerator const &other) {
if (other.isFullyInitialized()) {
_vna = other._vna;
_channel.reset(new VnaChannel(*other._channel.data()));
_channelIndex = other._channelIndex;
}
else {
placeholder.reset(new Vna());
_vna = placeholder.data();
_channel.reset(new VnaChannel());
_channelIndex = 0;
}
}
// Private
bool VnaPulseGenerator::isFullyInitialized() const {
if (_vna == NULL)
return(false);
if (_vna == placeholder.data())
return(false);
//else
return(true);
}
|
#pragma once
#include "Bindable.h"
class IndexBuffer : public Bindable
{
public:
IndexBuffer(VeritasEngine& vin, const void* indices, size_t TypeSize, size_t Count)noexcept;
public:
void Bind(VeritasEngine& vin) override;
uint32_t GetCount()const noexcept;
private:
wrl::ComPtr<IVBuffer> pVBuf;
uint32_t indexCount = 0;
VFORMAT format = VFORMAT::FORMAT_NONE;
};
|
/*
문제 링크 : https://www.acmicpc.net/problem/13458
문제 풀이 : 그리디? 브루트포스?
문제 풀이 참고 블로그 : https://na982.tistory.com/85?category=145346
*/
#include <iostream>
using namespace std;
int nTestPeople[1000001];
int main(void)
{
int N; // 시험장의 개수
int B, C;
long long nResult = 0;
cin >> N;
for (int i = 1; i <= N; i++)
{
cin >> nTestPeople[i];
}
cin >> B >> C;
for (int i = 1; i <= N; i++)
{
nTestPeople[i] -= B;
nResult++;
if (nTestPeople[i] > 0)
{
nResult += nTestPeople[i] / C;
if (nTestPeople[i] % C != 0)
{
nResult++;
}
}
}
cout << nResult << endl;
return 0;
}
|
#include <iostream>
#include <cmath>
using namespace std;
struct Point3D { double x, y, z; };
struct Line3D { Point3D p, q; };
double distance(Line3D l, Point3D p) {
double x0 = p.x, y0 = p.y, z0 = p.z;
double x1 = l.p.x, y1 = l.p.y, z1 = l.p.z;
double x2 = l.q.x, y2 = l.q.y, z2 = l.q.z;
double a = x2 - x1;
double b = y2 - y1;
double c = z2 - z1;
double a2 = a * a;
double b2 = b * b;
double c2 = c * c;
double r2 = a2 + b2 + c2;
double t2 = -(a * (x1 - x0) + b * (y1 - y0) + c * (z1 - z0));
if(t2 < 0) return sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) + (z1 - z0) * (z1 - z0));
if(t2 > r2) return sqrt((x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0) + (z2 - z0) * (z2 - z0));
double fx = b * (z1 - z0) - c * (y1 - y0);
double fy = c * (x1 - x0) - a * (z1 - z0);
double fz = a * (y1 - y0) - b * (x1 - x0);
double f2 = fx * fx + fy * fy + fz * fz;
return sqrt(f2 / r2);
}
int main(void) {
Point3D p = (Point3D) { 1, 6, 9 };
Line3D l = (Line3D) { (Point3D) { 2, 5, 3 }, (Point3D) { -1, 1, 7 } };
cout << distance(l, p) << endl;
return 0;
}
|
/************************************
未main提供函数接口以及函数声明
Person类以及Manp类
*************************************/
#pragma once
#include<stdio.h>
#include<iostream>
#include<Windows.h>
using namespace std;
const int _exity = 0;
const int _exitx = 4;
struct Pos
{
int x;
int y;
};
class Person
{
public:
struct Pos _rPos, p_rPos;
char P = 'R';
Person();
void direction(char a[][11]);
void move(char a[][11]);
int Juge();
int getstep()
{
return step;
}
private:
enum derect
{
UP,
DOWN,
LEFT,
RIGHT,
} _edirection;
int step=0;
};
class Manp
{
public:
Manp(char a[][11], int x, int y);
void Drowp(struct Pos p, struct Pos p2,char e);
void Gotoxy(int x, int y);
};
|
#include <AccelStepper.h>
#define EN_PIN 2
#define STEP_PIN 3
#define DIR_PIN 4
#define MS_PIN A5
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
bool moveDone = true;
void setup()
{
Serial.begin(9600);
pinMode(MS_PIN, OUTPUT);
digitalWrite(MS_PIN, HIGH);
stepper.setEnablePin(EN_PIN);
stepper.setPinsInverted(true, true, true);
stepper.setMaxSpeed(500.0f);
stepper.setAcceleration(1000.0f);
Serial.println("RDY");
}
void loop()
{
if (Serial.available() > 2)
{
int delta = Serial.parseInt();
stepper.enableOutputs();
stepper.move(delta);
moveDone = false;
}
if (!moveDone && !stepper.isRunning())
{
stepper.disableOutputs();
Serial.println("MD");
moveDone = true;
}
stepper.run();
}
|
const int mos=30;
const int mos1=31;
const int mas=32;
const int mas1=33;
const int moso=34;
const int moso1=35;
const int maso=36;
const int maso1=37;
void ileri(){
digitalWrite(mos ,HIGH);
digitalWrite(mos1 ,LOW);
digitalWrite(mas ,HIGH);
digitalWrite(mas1 ,LOW);
digitalWrite(moso ,HIGH);
digitalWrite(moso1 ,LOW);
digitalWrite(maso ,HIGH);
digitalWrite(maso1 ,LOW);
}
void geri(){
digitalWrite(mos ,LOW);
digitalWrite(mos1 ,HIGH);
digitalWrite(mas ,LOW);
digitalWrite(mas1 ,HIGH);
digitalWrite(moso ,LOW);
digitalWrite(moso1 ,HIGH);
digitalWrite(maso ,LOW);
digitalWrite(maso1 ,HIGH);
}
void sag() {
digitalWrite(mos ,HIGH);
digitalWrite(mos1 ,LOW);
digitalWrite(mas ,HIGH);
digitalWrite(mas1 ,LOW);
digitalWrite(moso ,LOW);
digitalWrite(moso1 ,HIGH);
digitalWrite(maso ,LOW);
digitalWrite(maso1 ,HIGH);
}
void sol(){
digitalWrite(mos ,LOW);
digitalWrite(mos1 ,HIGH);
digitalWrite(mas ,LOW);
digitalWrite(mas1 ,HIGH);
digitalWrite(moso ,HIGH);
digitalWrite(moso1 ,LOW);
digitalWrite(maso ,HIGH);
digitalWrite(maso1 ,LOW);
}
void dur(){
digitalWrite(maso1 ,LOW);
digitalWrite(maso ,LOW);
digitalWrite(moso1 ,LOW);
digitalWrite(moso ,LOW);
digitalWrite(mas1 ,LOW);
digitalWrite(mas ,LOW);
digitalWrite(mos1 ,LOW);
digitalWrite(mos ,LOW);
}
int state;
void setup() {
pinMode(mos ,OUTPUT);
pinMode(mos1 ,OUTPUT);
pinMode(mas ,OUTPUT);
pinMode(mos1 ,OUTPUT);
pinMode(moso ,OUTPUT);
pinMode(mos1 ,OUTPUT);
pinMode(maso ,OUTPUT);
pinMode(maso1 ,OUTPUT);
Serial.begin(9600);
}
void loop() {
if(digitalRead(state)==LOW) {
dur();
}
if(Serial.available() > 0){
state = Serial.read();
}
if (state == 66){
geri();
}
if (state == 70){
ileri();
}
if (state == 82){
sag();
}
if (state == 76){
sol();
}
if (state == 83){
dur();
}
if (state == 0){
dur();
}
}
|
#include "BlurEffect.h"
#include "Window.h"
BlurEffect::BlurEffect() {
fbo = new Fbo(window::getWindowSize(), false);
shader.addShader("shaders/gui.vsh", GL_VERTEX_SHADER);
shader.addShader("shaders/blurEffect.fsh", GL_FRAGMENT_SHADER);
shader.start();
shader.bindTextureUnit("textureSampler", 0);
shader.activateUniform("resolution");
shader.activateUniform("radius");
shader.activateUniform("blurDirection");
shader.activateUniform("useBlur");
shader.activateUniform("useMMatrix");
shader.stop();
}
void BlurEffect::applyBlur(unsigned int vaoId, unsigned int rgbTexture, float resolution, float radius, glm::vec2 blurDirection, bool useBlur) {
shader.start();
glBindVertexArray(vaoId);
glEnableVertexAttribArray(0);
fbo->bindFrameBuffer();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.setUniformVariable("useMMatrix", false);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, rgbTexture);
shader.setUniformVariable("useBlur", useBlur);
shader.setUniformVariable("resolution", resolution);
shader.setUniformVariable("radius", radius);
shader.setUniformVariable("blurDirection", blurDirection);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
fbo->unbindFrameBuffer();
glDisableVertexAttribArray(0);
glBindVertexArray(0);
shader.stop();
}
BlurEffect::~BlurEffect() {
delete fbo;
}
|
#include "BitSize.h"
#include <algorithm>
#include <limits>
#include <sstream>
#include <iomanip>
#include <cassert>
#define BITS_IN_BYTE 8.
#define BYTES_IN_KIBIBIT 128.
#define BYTES_IN_MEBIBIT 131072.
#define BYTES_IN_GIBIBIT 134217728.
#define BYTES_IN_TEBIBIT 137438953472.
#define BYTES_IN_PEBIBIT 140737488355328.5
#define BYTES_IN_KILOBIT 125.
#define BYTES_IN_MEGABIT 125000.
#define BYTES_IN_GIGABIT 125000000.
#define BYTES_IN_TERABIT 125000000000.
#define BYTES_IN_PETABIT 125000000000000.
namespace hvn3 {
BitSize::BitSize(double bytes, BytePrefix prefix) :
BitSize(bytes, prefix, prefix == BytePrefix::Binary ? ByteUnit::IEC : ByteUnit::Metric) {
}
BitSize::BitSize(double bytes, BytePrefix prefix, ByteUnit unit) {
assert(unit != ByteUnit::IEC || prefix == BytePrefix::Binary);
_bytes = RoundBytesToNearestBit(bytes);
_unit = unit;
_prefix = prefix;
}
double BitSize::Bits() const {
return _bytes * BITS_IN_BYTE;
}
double BitSize::Bytes() const {
return _bytes;
}
double BitSize::Kilobits() const {
return Bytes() / BytesInKilobit(_prefix);
}
double BitSize::Megabits() const {
return Bytes() / BytesInMegabit(_prefix);
}
double BitSize::Gigabits() const {
return Bytes() / BytesInGigabit(_prefix);
}
double BitSize::Terabits() const {
return Bytes() / BytesInTerabit(_prefix);
}
double BitSize::Petabits() const {
return Bytes() / BytesInPetabit(_prefix);
}
std::string BitSize::LargestUnitSymbol() const {
if ((std::abs)(Petabits()) >= 1.0)
return PetabitSymbol(_unit);
if ((std::abs)(Terabits()) >= 1.0)
return TerabitSymbol(_unit);
if ((std::abs)(Gigabits()) >= 1.0)
return GigabitSymbol(_unit);
if ((std::abs)(Megabits()) >= 1.0)
return MegabitSymbol(_unit);
if ((std::abs)(Kilobits()) >= 1.0)
return KilobitSymbol(_unit);
if ((std::abs)(Bytes()) >= 1.0)
return ByteSymbol(_unit);
return BitSymbol(_unit);
}
double BitSize::LargestUnitValue() const {
if ((std::abs)(Petabits()) >= 1.0)
return Petabits();
if ((std::abs)(Terabits()) >= 1.0)
return Terabits();
if ((std::abs)(Gigabits()) >= 1.0)
return Gigabits();
if ((std::abs)(Megabits()) >= 1.0)
return Megabits();
if ((std::abs)(Kilobits()) >= 1.0)
return Kilobits();
if ((std::abs)(Bytes()) >= 1.0)
return Bytes();
return Bits();
}
void BitSize::AddBits(double size) {
*this = BitSize(Bytes() + BitsInByte(_prefix) / size, _prefix, _unit);
}
void BitSize::AddBytes(double size) {
*this = BitSize(Bytes() + size, _prefix, _unit);
}
void BitSize::AddKilobits(double size) {
*this = BitSize(Bytes() + size * BytesInKilobit(_prefix), _prefix, _unit);
}
void BitSize::AddMegabits(double size) {
*this = BitSize(Bytes() + size * BytesInMegabit(_prefix), _prefix, _unit);
}
void BitSize::AddGigabits(double size) {
*this = BitSize(Bytes() + size * BytesInGigabit(_prefix), _prefix, _unit);
}
void BitSize::AddTerabits(double size) {
*this = BitSize(Bytes() + size * BytesInTerabit(_prefix), _prefix, _unit);
}
void BitSize::AddPetabits(double size) {
*this = BitSize(Bytes() + size * BytesInPetabit(_prefix), _prefix, _unit);
}
std::string BitSize::ToString(unsigned int precision) const {
std::stringstream stream;
stream << std::fixed << std::setprecision(precision) << LargestUnitValue() << ' ' << LargestUnitSymbol();
return stream.str();
}
BitSize BitSize::MinValue() {
return BitSize(0);
}
BitSize BitSize::MaxValue() {
return BitSize(DBL_MAX);
}
BitSize BitSize::Parse(const std::string& string) {
return Parse(string.c_str());
}
BitSize BitSize::Parse(const char* string) {
BitSize object(0);
if (!TryParse(string, object))
throw std::invalid_argument("The input string was not in the correct format.");
return object;
}
bool BitSize::TryParse(const std::string& string, BitSize& object) {
return TryParse(string.c_str(), object);
}
bool BitSize::TryParse(const char* string, BitSize& object) {
std::stringstream stream(string);
double size = 0.0;
std::string suffix;
// Read the size and suffix.
stream >> size >> suffix;
// If this fails, return false.
if (stream.fail())
return false;
// Compare the string to known suffixes.
if (suffix == BitSymbol())
object = BitSize::FromBits(size);
else if (suffix == ByteSymbol())
object = BitSize::FromBytes(size);
else if (suffix == KilobitSymbol(ByteUnit::IEC))
object = BitSize::FromKilobits(size, BytePrefix::Binary);
else if (suffix == KilobitSymbol(ByteUnit::JEDEC))
object = BitSize(size * BytesInKilobit(BytePrefix::Binary), BytePrefix::Binary, ByteUnit::JEDEC);
else if (suffix == KilobitSymbol(ByteUnit::Metric))
object = BitSize::FromKilobits(size, BytePrefix::Decimal);
else if (suffix == MegabitSymbol(ByteUnit::IEC))
object = BitSize::FromMegabits(size, BytePrefix::Binary);
else if (suffix == MegabitSymbol(ByteUnit::Metric))
object = BitSize::FromMegabits(size, BytePrefix::Decimal);
else if (suffix == GigabitSymbol(ByteUnit::IEC))
object = BitSize::FromGigabits(size, BytePrefix::Binary);
else if (suffix == GigabitSymbol(ByteUnit::Metric))
object = BitSize::FromGigabits(size, BytePrefix::Decimal);
else if (suffix == TerabitSymbol(ByteUnit::IEC))
object = BitSize::FromTerabits(size, BytePrefix::Binary);
else if (suffix == TerabitSymbol(ByteUnit::Metric))
object = BitSize::FromTerabits(size, BytePrefix::Decimal);
else if (suffix == PetabitSymbol(ByteUnit::IEC))
object = BitSize::FromPetabits(size, BytePrefix::Binary);
else if (suffix == PetabitSymbol(ByteUnit::Metric))
object = BitSize::FromPetabits(size, BytePrefix::Decimal);
else
object = BitSize::FromBits(size);
return true;
}
BitSize BitSize::FromBits(double size, BytePrefix prefix) {
return BitSize(size / BitsInByte(prefix), prefix);
}
BitSize BitSize::FromBytes(double size, BytePrefix prefix) {
return BitSize(size, prefix);
}
BitSize BitSize::FromKilobits(double size, BytePrefix prefix) {
return BitSize(size * BytesInKilobit(prefix), prefix);
}
BitSize BitSize::FromMegabits(double size, BytePrefix prefix) {
return BitSize(size * BytesInMegabit(prefix), prefix);
}
BitSize BitSize::FromGigabits(double size, BytePrefix prefix) {
return BitSize(size * BytesInGigabit(prefix), prefix);
}
BitSize BitSize::FromTerabits(double size, BytePrefix prefix) {
return BitSize(size * BytesInTerabit(prefix), prefix);
}
BitSize BitSize::FromPetabits(double size, BytePrefix prefix) {
return BitSize(size * BytesInPetabit(prefix), prefix);
}
double BitSize::BitsInByte(BytePrefix prefix) {
return BITS_IN_BYTE;
}
double BitSize::BytesInKilobit(BytePrefix prefix) {
switch (prefix) {
case BytePrefix::Binary:
return BYTES_IN_KIBIBIT;
case BytePrefix::Decimal:
return BYTES_IN_KILOBIT;
}
}
double BitSize::BytesInMegabit(BytePrefix prefix) {
switch (prefix) {
case BytePrefix::Binary:
return BYTES_IN_MEBIBIT;
case BytePrefix::Decimal:
return BYTES_IN_MEGABIT;
}
}
double BitSize::BytesInGigabit(BytePrefix prefix) {
switch (prefix) {
case BytePrefix::Binary:
return BYTES_IN_GIBIBIT;
case BytePrefix::Decimal:
return BYTES_IN_GIGABIT;
}
}
double BitSize::BytesInTerabit(BytePrefix prefix) {
switch (prefix) {
case BytePrefix::Binary:
return BYTES_IN_TEBIBIT;
case BytePrefix::Decimal:
return BYTES_IN_TERABIT;
}
}
double BitSize::BytesInPetabit(BytePrefix prefix) {
switch (prefix) {
case BytePrefix::Binary:
return BYTES_IN_PEBIBIT;
case BytePrefix::Decimal:
return BYTES_IN_PETABIT;
}
}
std::string BitSize::BitSymbol(ByteUnit unit) {
return "b";
}
std::string BitSize::ByteSymbol(ByteUnit unit) {
return "B";
}
std::string BitSize::KilobitSymbol(ByteUnit unit) {
switch (unit) {
case ByteUnit::IEC:
return "Kibit";
case ByteUnit::JEDEC:
return "Kbit";
case ByteUnit::Metric:
return "kbit";
}
}
std::string BitSize::MegabitSymbol(ByteUnit unit) {
switch (unit) {
case ByteUnit::IEC:
return "Mibit";
case ByteUnit::JEDEC:
case ByteUnit::Metric:
return "Mbit";
}
}
std::string BitSize::GigabitSymbol(ByteUnit unit) {
switch (unit) {
case ByteUnit::IEC:
return "Gibit";
case ByteUnit::JEDEC:
case ByteUnit::Metric:
return "Gbit";
}
}
std::string BitSize::TerabitSymbol(ByteUnit unit) {
switch (unit) {
case ByteUnit::IEC:
return "Tibit";
case ByteUnit::JEDEC:
case ByteUnit::Metric:
return "Tbit";
}
}
std::string BitSize::PetabitSymbol(ByteUnit unit) {
switch (unit) {
case ByteUnit::IEC:
return "Pibit";
case ByteUnit::JEDEC:
case ByteUnit::Metric:
return "Pbit";
}
}
BitSize& BitSize::operator+=(const BitSize& rhs) {
_bytes += rhs._bytes;
return *this;
}
BitSize& BitSize::operator-=(const BitSize& rhs) {
_bytes -= rhs._bytes;
return *this;
}
bool operator==(const BitSize& lhs, const BitSize& rhs) {
return (std::abs)(lhs.Bytes() - rhs.Bytes()) < 0.125; // difference of less than 1 bit
}
bool operator!=(const BitSize& lhs, const BitSize& rhs) {
return !(lhs == rhs);
}
bool operator<(const BitSize& lhs, const BitSize& rhs) {
return lhs.Bytes() < rhs.Bytes();
}
bool operator<=(const BitSize& lhs, const BitSize& rhs) {
return (lhs.Bytes() < rhs.Bytes()) || (lhs == rhs);
}
bool operator>(const BitSize& lhs, const BitSize& rhs) {
return lhs.Bytes() > rhs.Bytes();
}
bool operator>=(const BitSize& lhs, const BitSize& rhs) {
return (lhs.Bytes() > rhs.Bytes()) || (lhs == rhs);
}
BitSize operator+(const BitSize& lhs, const BitSize& rhs) {
return(BitSize(lhs.Bytes() + rhs.Bytes(), lhs._prefix, lhs._unit));
}
BitSize operator-(const BitSize& lhs, const BitSize& rhs) {
return(BitSize(lhs.Bytes() - rhs.Bytes(), lhs._prefix, lhs._unit));
}
std::ostream& operator<<(std::ostream& lhs, const BitSize& rhs) {
return lhs << rhs.ToString();
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2006 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#include "core/pch.h"
#if defined PREFS_HAS_LNGLIGHT
#include "modules/prefsfile/accessors/lnglight.h"
BOOL LangAccessorLight::ParseLineL(uni_char *line, PrefsMap *)
{
const size_t platformlen = sizeof BUILDNUMSUFFIX - 1;
if (!m_isinfoblock)
{
if (uni_strni_eq(line, "[INFO]", 6))
{
m_isinfoblock = TRUE;
}
}
else
{
if (!m_hascode && uni_strni_eq(line, "LANGUAGE=", 9))
{
size_t namelen = uni_strlen(line);
if ('"' == line[9] && '"' == line[namelen - 1])
{
OpStatus::Ignore(m_code.Set(line + 10, namelen - 11));
}
else
{
OpStatus::Ignore(m_code.Set(line + 9, namelen - 9));
}
m_hascode = TRUE;
}
else if (!m_hasname && uni_strni_eq(line, "LANGUAGENAME=", 13))
{
size_t namelen = uni_strlen(line);
if ('"' == line[13] && '"' == line[namelen - 1])
{
OpStatus::Ignore(m_name.Set(line + 14, namelen - 15));
}
else
{
OpStatus::Ignore(m_name.Set(line + 13, namelen - 13));
}
m_hasname = TRUE;
}
else if (!m_hasbuild && uni_strni_eq(line, "BUILD." BUILDNUMSUFFIX "=", 6 + platformlen))
{
size_t namelen = uni_strlen(line);
if ('"' == line[7 + platformlen] && '"' == line[namelen - 1])
{
OpStatus::Ignore(m_build.Set(line + 8 + platformlen, namelen - 9 - platformlen));
}
else
{
OpStatus::Ignore(m_build.Set(line + 7 + platformlen, namelen - 7 - platformlen));
}
m_hasbuild = TRUE;
}
else if (!m_hasdb && uni_strni_eq(line, "DB.VERSION=", 11))
{
size_t namelen = uni_strlen(line);
if ('"' == line[11] && '"' == line[namelen - 1])
{
OpStatus::Ignore(m_db.Set(line + 12, namelen - 13));
}
else
{
OpStatus::Ignore(m_db.Set(line + 11, namelen - 11));
}
m_hasdb = TRUE;
}
else if ('[' == *line)
{
m_isinfoblock = FALSE;
}
}
return m_hascode && m_hasname && m_hasbuild && m_hasdb;
}
OP_STATUS LangAccessorLight::GetFileInfo(OpString &code, OpString &name, OpString &build)
{
OP_STATUS rc = code.Set(m_code);
if (OpStatus::IsError(rc)) return rc;
rc = name.Set(m_name);
if (OpStatus::IsError(rc)) return rc;
return build.Set(m_build);
}
OP_STATUS LangAccessorLight::GetDatabaseVersion(OpString &db_version)
{
return db_version.Set(m_db);
}
#endif // PREFS_HAS_LNGLIGHT
|
//
// Created by Yujing Shen on 29/05/2017.
//
#ifndef TENSORGRAPH_SRCNODE_H
#define TENSORGRAPH_SRCNODE_H
#include "../SessionNode.h"
namespace sjtu{
class SrcNode: public SessionNode
{
public:
SrcNode(Session *sess, const Shape& shape);
virtual ~SrcNode();
virtual Node forward() override ;
virtual Node backward() override ;
virtual Node optimize() override ;
};
}
#endif //TENSORGRAPH_SRCNODE_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
**
** Copyright (C) 1995-2000 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
/** @file opelminfo.cpp
*
* Header and implementation of the element info used in the link panel
*
* @author Stig Halvorsen
*
*/
#ifndef OP_ELM_INFO_H
#define OP_ELM_INFO_H
class URL;
#include "modules/util/opstring.h"
#include "modules/logdoc/link_type.h"
class OpElementInfo
{
public:
enum EIType {
UNKNOWN,
CLINK,
A,
LINK,
GO
};
private:
EIType m_type;
LinkType
m_kind;
URL* m_url;
const uni_char* m_title;
const uni_char* m_alt;
const uni_char* m_rel;
const uni_char* m_rev;
OpString m_text;
INT32 m_font_size;
INT32 m_font_weight;
INT32 m_font_color;
public:
OpElementInfo(EIType type, LinkType kind = LINK_TYPE_OTHER) :
m_type(type), m_kind(kind), m_url(NULL), m_title(NULL), m_alt(NULL),
m_font_size(0), m_font_weight(0), m_font_color(0) {}
EIType GetType() { return m_type; }
void SetType(EIType type) { m_type = type; }
LinkType GetKind() { return m_kind; }
const URL* GetURL() { return m_url; }
void SetURL(URL* url) { m_url = url; }
const uni_char* GetTitle() { return m_title; }
void SetTitle(const uni_char *title) { m_title = title; }
const uni_char* GetAlt() { return m_alt; }
void SetAlt(const uni_char *alt) { m_alt = alt; }
const uni_char* GetRel() { return m_rel; }
void SetRel(const uni_char *rel) { m_rel = rel; }
const uni_char* GetRev() { return m_rev; }
void SetRev(const uni_char* rev) { m_rev = rev; }
const uni_char* GetText() { return m_text.CStr(); }
OP_STATUS SetText(const uni_char *txt) { return m_text.Set(txt); }
OP_STATUS AppendText(const uni_char *txt) { return m_text.Append(txt); }
INT32 GetFontSize() { return m_font_size; }
void SetFontSize(INT32 size) { m_font_size = size; }
INT32 GetFontWeight() { return m_font_weight; }
void SetFontWeight(INT32 weight) { m_font_weight = weight; }
INT32 GetTextColor() { return m_font_color; }
void SetTextColor(INT32 color) { m_font_color = color; }
// Include the first image thingy?
const URL* GetImageURL() { return NULL; }
const uni_char* GetImageTitle() { return NULL; }
const uni_char* GetImageAlt() { return NULL; }
};
#endif // OP_ELM_INFO_H
|
#ifndef RICERCA_H
#define RICERCA_H
#include "vinolistwidget.h"
#include "mycomboboxtipo.h"
#include <model.h>
#include <QLineEdit>
#include <QCheckBox>
#include <QComboBox>
#include <QPushButton>
#include <QFormLayout>
#include <QRadioButton>
#include <QLabel>
#include <QLCDNumber>
class Ricerca: public QWidget
{
Q_OBJECT
private:
QLabel *labelRicerca;
QLabel *labelTag;
QCheckBox *checkboxTipo;
ComboBoxTipo *cercaPerTipo;
QCheckBox *checkboxNome;
QLineEdit *cercaPerNome;
QCheckBox *checkboxNazione;
QLineEdit *cercaPerNazione;
QCheckBox *checkboxProduttore;
QLineEdit *cercaPerProduttore;
QCheckBox *checkboxColore;
QLineEdit *cercaPerColore;
QCheckBox *checkboxAnnata;
QLineEdit *cercaPerAnnata;
QCheckBox *checkboxPrezzo;
QSlider *sliderPrezzo;
QLCDNumber *lcdPrezzo;
QRadioButton *prezzoMinore;
QRadioButton *prezzoMaggiore;
Model *modello;
QPushButton *buttonCerca;
QPushButton *buttonReset;
QPushButton *buttonEliminaTrovato;
VinoListWidget *listaVini;
public:
Ricerca(QWidget* = nullptr);
QLineEdit *getCercaPerNome() const;
QLineEdit *getCercaPerNazione() const;
QLineEdit *getCercaPerProduttore() const;
QLineEdit *getCercaPerColore() const;
QLineEdit *getCercaPerAnnata() const;
QLCDNumber *getCercaPerPrezzo() const;
ComboBoxTipo *getCercaPerTipo() const;
QRadioButton *getRadioButtonPrezzoMinore() const;
QRadioButton *getRadioButtonPrezzoMaggiore() const;
QPushButton *getButtonCerca() const;
QPushButton *getButtonReset() const;
VinoListWidget *getListaVini() const;
QPushButton *getButtonEliminaTrovato() const;
QCheckBox *getCheckboxNome() const;
QCheckBox *getCheckboxNazione() const;
QCheckBox *getCheckboxProduttore() const;
QCheckBox *getCheckboxColore() const;
QCheckBox *getCheckboxAnnata() const;
QCheckBox *getCheckboxPrezzo() const;
QCheckBox *getCheckboxTipo() const;
private slots:
void slotDisabilitaElementi() const;
void slotRadioButtonMaggiore(bool) const;
void slotRadioButtonMinore(bool) const;
public slots:
void slotResetRicerca() const;
signals:
void signalEliminaTuttiElementi(Model*);
};
#endif // RICERCA_H
|
#include <iostream>
#include <vector>
using namespace std;
long mod=1000000007;
long a[100001];
long sumlist[100001];
int ncalc(int N){
long tmp = 1;
while(1){
tmp *= (long)N;
N--;
tmp %= mod;
if (N == 0) break;
}
return tmp;
}
//aのp乗を求めるアルゴリズム
//p=62>31>30>15>14>7>6>3>2>1>0
//計算量はO(logp)になる。
long long modpow(long a, int p){
if (p == 0) return 1;
if (p%2 == 0){
//p even
int halfP = p/2;
long long half = modpow(a, halfP);
//a^(p/2)をhalfとしてhalf*halfを計算
return half * half % mod;
}
else {
return a * modpow(a, p-1) % mod;
}
}
int main(){
int N;
cin >> N;
for(int i = 0; i < N; i++)
{
int tmp = 0;
cin >> tmp;
a[i] = tmp;
}
int nex = ncalc(N);
//printf("%d\n",nex);
int sum = 0;
for(int i = 2; i <= N; i++)
{
//nexが1000000007を超えたとき、nex / iの計算が想定通りにならない。
int tmp = nex * modpow((long)i, mod - 2) % mod;
sum += tmp;
sum %= mod;
sumlist[i-2] = sum;
}
//sumlist[0] = 24/2 24/3 24/4
long long ans = 0;
for(int i = 0; i < N; i++){
long long anum = 0;
//ai - ai
anum += nex;
//printf("aunm %d %d\n",anum, a[i]);
//ai - ai+1 - an
if(i != N - 1){
anum += sumlist[N - i - 2];
anum %= mod;
}
//printf("aunm %d %d %d\n",anum, a[i], sumlist[N-i-1]);
//ai - ai-1 a0
if(i != 0){
anum += sumlist[i - 1];
anum %= mod;
}
//printf("aunm %d %d\n",anum, a[i]);
ans += a[i] * anum;
ans %= mod;
}
cout << ans << endl;
}
|
//
// c_board.h
// unblockme_solver
//
// Created by Alexander G Anderson on 12/16/13.
// Copyright (c) 2013 Alexander G Anderson. All rights reserved.
//
/*
CBoard = Compressed Board
Blocks are stored with using the coordinates of their top left entry, and their size.
----> i (first coordinate)
|
|
|
V
j (second coordinate)
Sample usage:
Cboard c;
// Initialize the blocks and block lengths
c.add_bl_h(0,0,2)
c.add_bl_v(1,0,2)
// After the first board, all subsequent boards are created by shifting blocks
// continuing to use add_bl_h adds lengths to the static block size arrays
Cboard c1 = c
c1.bl_h.first += 1 or -1
*/
#ifndef __unblockme_solver__c_board__
#define __unblockme_solver__c_board__
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
// loc = location of upper right corner of the block
typedef std::pair<int,int> loc;
class CBoard {
public:
// h = horizontal blocks
// v = vertical blocks
// s = size of the blocks
static std::vector<int> s_h;
static std::vector<int> s_v;
// stores locations of blocks
vector<loc> bl_h;
vector<loc> bl_v;
CBoard();
// add a horizontal block
void add_bl_h(int i, int j, int size);
// add a vertical block
void add_bl_v(int i, int j, int size);
// print the contents of the CBoard
void print();
};
#endif /* defined(__unblockme_solver__c_board__) */
|
/**
* @file test.h
* @author Gerbrand De Laender
* @date 07/04/2021
* @version 1.0
*
* @brief E091103, Master thesis
*
* @section DESCRIPTION
*
* Test bench helper functions. Template parameters are:
* T = Data type excluding AXI4-Stream side channels
*
*/
#pragma once
#include <iostream>
#include <string>
#include <stdio.h>
#include "np_add_subtract_multiply_divide_f4.h"
// Print out an array in a human-readable format.
template <typename T>
void print_arr(T *arr, std::string name, int len)
{
std::cout << name << "\n---\n";
for (int i = 0; i < len; i++) {
#if defined(TYPE_FLOAT) || defined(TYPE_DOUBLE)
printf("%5.2f ", arr[i]);
#else
printf("%d ", arr[i]);
#endif
}
printf("\n");
}
// Print out a matrix in a human-readable format.
template <typename T>
void print_mat(T *mat, std::string name, int rows, int cols)
{
std::cout << name << "\n---\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
#if defined(TYPE_FLOAT) || defined(TYPE_DOUBLE)
printf ("%5.2f ", mat[i * sizeof(T) + j]);
#else
printf ("%d ", mat[i * sizeof(T) + j]);
#endif
}
printf("\n");
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2000-2008 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef BOOKMARK_INI_STORAGE_H
#define BOOKMARK_INI_STORAGE_H
#ifdef CORE_BOOKMARKS_SUPPORT
#include "modules/util/opfile/opfile.h"
#include "modules/util/opstrlst.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/bookmarks/bookmark_item.h"
#include "modules/bookmarks/bookmark_storage_provider.h"
/**
* An implementation of the BookmarkStorageProvider API for storing
* bookmarks in an INI-file using prefsfile.
*/
class BookmarkIniStorage : public BookmarkStorageProvider
{
public:
BookmarkIniStorage(BookmarkManager *manager);
virtual ~BookmarkIniStorage();
/**
* Set which file to load bookmarks from. Need only to be called
* once.
*/
virtual OP_STATUS OpenLoad(const uni_char *filename, OpFileFolder folder);
/**
* Specify which file to save bookmarks to. Need not be called if
* this file is the same as set by call to OpenLoad.
*/
virtual OP_STATUS OpenSave(const uni_char *filename, OpFileFolder folder);
virtual OP_STATUS Close();
virtual OP_STATUS UseFormat(BookmarkFormatType format);
virtual OP_STATUS SaveBookmark(BookmarkItem *bookmark);
virtual OP_STATUS ClearStorage();
virtual OP_STATUS LoadBookmark(BookmarkItem *bookmark);
virtual OP_STATUS FolderBegin(BookmarkItem *folder);
virtual OP_STATUS FolderEnd(BookmarkItem *folder);
virtual BOOL MoreBookmarks();
virtual void RegisterListener(BookmarkStorageListener *l);
virtual void UnRegisterListener(BookmarkStorageListener *l);
void AddToPool(BookmarkListElm *elm);
void RemoveFromPool(uni_char *uid);
BookmarkListElm* FetchFromPool(uni_char *uid);
BookmarkListElm* FetchParentFromPool(uni_char *puid);
private:
/**
* Check if file with name filename exists in folder. If it do not
* then create it.
* @return OpStatus::OK if everything is ok.
*/
OP_STATUS CheckIfExists(const uni_char *filename, OpFileFolder folder);
OP_STATUS LoadAttribute(BookmarkAttributeType attribute, const PrefsSection *section_name, const uni_char *entry_name, BookmarkItem *bookmark);
OP_STATUS LoadIntAttribute(BookmarkAttributeType attribute, const PrefsSection *section_name, const uni_char *entry_name, BookmarkItem *bookmark);
OP_STATUS SaveAttribute(BookmarkAttributeType attribute, const uni_char *section_name, const uni_char *entry_name, BookmarkItem *bookmark);
OP_STATUS SaveIntAttribute(BookmarkAttributeType attribute, const uni_char *section_name, const uni_char *entry_name, BookmarkItem *bookmark);
OP_STATUS SaveTargetFolderValues(const uni_char *section_name, BookmarkItem *bookmark);
void LoadTargetFolderValues(const PrefsSection *section, BookmarkItem *bookmark);
uni_char *m_filename;
OpFileFolder m_folder;
OpFile *m_bookmark_file;
PrefsFile *m_bookmark_prefs;
UINT m_current_section;
UINT m_index;
BookmarkItem *m_current_folder;
BookmarkFormatType m_format;
OpString_list m_sections;
BookmarkStorageListener *m_listener;
Head m_pool;
};
#endif // CORE_BOOKMARKS_SUPPORT
#endif // BOOKMARK_INI_STORAGE_H
|
#include<iostream>
#include <fstream>
#include <cstdlib>
#include <string.h>
using namespace std;
main(){
fstream file("file.txt");
string a;
char b[1];
cout<<"file-s unshij awah\n";
while(file>>a){
cout<<a<<" ";
}
ofstream bichih;
bichih.open("file.txt");
bichih<<"SEAS";
bichih.close();
file.close();
}
|
#include "stdafx.h"
#include "butil.h"
using namespace std;
string block_to_string(blockContents b) {
string str;
str += "blockNum:" + to_string(b.blockNum);
str += "parentHash:" + b.parentHash;
str += "txnCount:" + to_string(b.txnCount);
str += "txns:" + seriealize(b.txns);
return str;
}
trans transacitonDumpBlock(string s, string r) {
srand((unsigned int)time(NULL));
int amount = rand();
trans dumps;
srand((unsigned int)time(NULL));
std::array<int, 20> target = { -1, 1,1,1,1 - 1,-1,1,1,1, -1,-1, 1, 1, -1, 1,1,1,-1,1 };
string lsd = s;
string lre = r;
for (int i = 0; i < BLOCK_SIZE; i += 2) {
if (target[i] == 1)
{
lsd = s;
lre = r;
}
else {
lsd = r;
lre = s;
}
dumps.push_back(fpair(lsd, -1 * rand()));
dumps.push_back(fpair(lre, rand()));
};
return dumps;
}
void addTransaction(trans* trans, string s, string r, int amount) {
trans->push_back(fpair(s, amount * -1));
trans->push_back(fpair(r, amount));
}
state updateState(const state& pstate, const trans& txn) {
auto tit = txn.begin();
state lstate = pstate;
for (auto tit = txn.begin(); tit != txn.end(); tit++)
{
if (lstate.find(tit->first) == lstate.end())
lstate[tit->first] = tit->second;
else
lstate[tit->first] += tit->second;
}
return lstate;
}
int sumTransfered(const trans& ptxn) {
int sum = 0;
for (auto it = ptxn.begin(); it != ptxn.end(); it++)
sum += it->second;
return sum;
}
bool isValidTxn(const trans &ptxn, const state &pstate) {
if (sumTransfered(ptxn) != 0)
return false;
for (auto it = ptxn.begin(); it != ptxn.end(); it++)
{
auto found_trans = pstate.find(it->first);
if (found_trans != pstate.end()) {
int account_balance = found_trans->second;
int overflow_check = account_balance - it->second;
if (overflow_check < 0) {
return false;
}
}
}
return true;
}
void stateToTxn(trans* txn, const state& state) {
auto it = state.begin();
for (; it != state.end(); it++) {
txn->push_back(*it);
}
}
chain genesisTxnFactory(const state &initial) {
trans gen_block_txn;
state gen_state;
auto it = initial.begin();
for (; it != initial.end(); it++) {
gen_block_txn.push_back(*it);
}
blockContents initial_block(1, "" , 1, gen_block_txn);
string block_str = block_to_string(initial_block);
string block_hash = sha256(block_str);
return chain(initial_block);
}
chain appendChain(const chain &prev, const trans& trans) {
blockContents block(prev.content.blockNum + 1, prev.hash, trans.size(), trans);
return chain(block);
}
void mockValid() {
state mock_state;
trans mock_txn;
mock_state.insert(fpair("louis", 5));
mock_state.insert(fpair("bob", 5));
genesisTxnFactory(mock_state);
addTransaction(&mock_txn, "louis", "bob", 3);
addTransaction(&mock_txn, "louis", "bob", 1);
bool result = isValidTxn(mock_txn, mock_state);
if (result)
updateState(mock_state, mock_txn);
cout << "txn valid : " << result << endl;
}
|
/*
* PlayerMessage.cpp
*
* Created on: Jun 28, 2017
* Author: root
*/
#include "PlayerMessage.h"
#include "MessageStruct/ServerReturn2Int.pb.h"
#include "MessageStruct/ServerReturn3Int.pb.h"
#include "MessageStruct/ServerReturn4Int.pb.h"
#include "MessageStruct/ServerReturn5Int.pb.h"
#include "MessageStruct/ServerReturnInt.pb.h"
#include "MessageStruct/ServerReturnIntChar.pb.h"
#include "SvrConfig.h"
#include "Log/Logger.h"
#include "Network/Message_Facade.h"
#include "../../MessageBuild.h"
#include "../../ServerManager.h"
#include "Common.h"
#include "ServerMsgDefine.h"
#include "MsgCommonClass.h"
#include "MessageStruct/CharLogin/PlayerInfo.pb.h"
#include "MessageStruct/CharLogin/CharBaseInfo.pb.h"
#include "../ObjectFactory.h"
PlayerMessage * PlayerMessage::m_instance = 0;
PlayerMessage::PlayerMessage()
{
m_PlayerCache.clear();
//注册定时器
if(m_timerID.IsValid())
{
m_timerID.SetNull();
}
DEF_MSG_REQUEST_REG_FUN(eGameServer, MSG_REQ_GT2GM_CLIENTIN);
DEF_MSG_REQUEST_REG_FUN(eGameServer, MSG_REQ_GT2GM_PLAYERINFO);
DEF_MSG_REQUEST_REG_FUN(eGameServer, MSG_REQ_GT2GM_PLAYEREXIT);
DEF_MSG_ACK_REG_FUN(eGameServer, MSG_REQ_GM2DB_PLAYERINFO);
DEF_MSG_ACK_REG_FUN(eGameServer, MSG_REQ_GS2DB_SAVE_PLAYERDATA);
DEF_MSG_REQUEST_REG_FUN(eGameServer, MSG_REQ_GT2GM_SYN_ATTR);
m_timerID = TimerInterface::GetInstance()->RegRepeatedTime(&PlayerMessage::RemoveDelayPlayer, this, 0, 0, 0, 0,20 * 1000, 20 * 1000);
}
PlayerMessage::~PlayerMessage()
{
if(m_timerID.IsValid())
{
m_timerID.SetNull();
}
Smart_Ptr<Player> nullPlayer;
map<int64, Smart_Ptr<Player> >::iterator it = m_allPlayer.begin();
for (; it != m_allPlayer.end(); ++it)
{
it->second->SetMyself(nullPlayer);
cout << endl;
cout << "~PlayerMessage SetMyself Charid "
<< it->second->GetID() << " playerdd "
<< &it->second << endl;
cout << endl;
}
map<int64, PLayerCache >::iterator itCa = m_PlayerCache.begin();
for (; itCa != m_PlayerCache.end(); ++itCa)
{
itCa->second.playerCache->SetMyself(nullPlayer);
cout << endl;
cout << "~PlayerMessage SetMyself Charid "
<< itCa->second.playerCache->GetID()
<< " playerdd " << &itCa->second.playerCache
<< endl;
cout << endl;
}
m_PlayerCache.clear();
m_allPlayer.clear();
}
void PlayerMessage::Handle_Message(Safe_Smart_Ptr<Message> &message)
{
DEF_SWITCH_TRY_DISPATCH_BEGIN
DEF_SWITCH_TRY_DISPATCH_END
}
void PlayerMessage::Handle_Request(Safe_Smart_Ptr<Message> &message)
{
DEF_SWITCH_TRY_DISPATCH_BEGIN
DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_GT2GM_CLIENTIN);
DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_GT2GM_PLAYERINFO);
DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_GT2GM_PLAYEREXIT);
DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_GT2GM_SYN_ATTR);
DEF_SWITCH_TRY_DISPATCH_END
}
void PlayerMessage::Handle_Ack(Safe_Smart_Ptr<Message> &message)
{
DEF_SWITCH_TRY_DISPATCH_BEGIN
// DEF_MSG_ACK_DISPATCH_FUN(MSG_REQ_GT2WS_CLIENTIN);
DEF_MSG_ACK_DISPATCH_FUN(MSG_REQ_GM2DB_PLAYERINFO);
DEF_MSG_ACK_DISPATCH_FUN(MSG_REQ_GS2DB_SAVE_PLAYERDATA);
// DEF_MSG_ACK_DISPATCH_FUN(MSG_REQ_GM2GT_PLAYER_ONLINE);
DEF_SWITCH_TRY_DISPATCH_END
}
void PlayerMessage::addSendDataCach(int64 charID, SaveDataInfo& sendData)
{
std::map<int64,SaveDataInfo>::iterator it=m_saveDataList.find(charID);
if(it==m_saveDataList.end())
{
m_saveDataList[charID] = sendData;
}
}
void PlayerMessage::dealWithSaveResult(SaveDataInfo& data)
{
//次数达到之后才会处理
data.count -= 1;
if(data.count > 0 )
return;
if(data.content.Get() == NULL)
return;
//
switch(data.msgtype)
{
case SimpleMessage:
{
break;
}
case Request:
{
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(data.msgid, data.message, data.content.Get(), Request);
messRet->SetAct(data.m_act);
Message_Facade::Send(messRet);
break;
}
case Ack:
{
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(data.msgid, data.message, data.content.Get());
Message_Facade::Send(messRet);
break;
}
default:
break;
}
}
int64 PlayerMessage::GetCharidByName(string name)
{
map<int64, Smart_Ptr<Player> >::iterator it;
for (it = m_allPlayer.begin(); it != m_allPlayer.end(); ++it)
{
if (it->second->GetName() == name)
return it->first;
}
return 0;
}
bool PlayerMessage::IsOnline(int64 charid)
{
map<int64, PLayerCache >::iterator itCache = m_PlayerCache.find(charid);
if (itCache != m_PlayerCache.end())
{
return true;
}
map<int64, Smart_Ptr<Player> >::iterator it = m_allPlayer.find(charid);
if (it != m_allPlayer.end())
{
return true;
}
return false;
}
bool PlayerMessage::IsOnlineEx(int64 charid)
{
map<int64, Smart_Ptr<Player> >::iterator it = m_allPlayer.find(charid);
if (it != m_allPlayer.end())
{
return true;
}
return false;
}
void PlayerMessage::RemoveDelayPlayer(void* arg)
{
DWORD64 ntime = CUtil::GetNowSecond();
DWORD64 ndeteTime = 0;
map<int64, PLayerCache >::iterator ite = m_PlayerCache.begin();
for (; ite != m_PlayerCache.end();)
{
if(ite->second.bFlag)
{
ndeteTime = 60 * 1000;
}
else
{
ndeteTime = 15 * 1000;
}
DWORD64 deftime = ntime - ite->second.time;
if (deftime > ndeteTime)
{
Smart_Ptr<Player> player = ite->second.playerCache;
player->SetOffLineTime(ntime);
LOG_ERROR(FILEINFO, "remove delay nowtime[%lld], oldtime[%lld], player[%lld] and gameserver request gt exit", ntime, ite->second.time, GET_PLAYER_CHARID(player->GetID()));
if(player->GetType() == ePlayer)
{
//退出除副本以外的信息
// PlayerRemoveMemberEventArgs tArgs(player,GROUP_REMOVEMETHOD_OUT);
// FireGlobalEvent(PlAYER_LOGINOUT_CLEAR_EVENT_TYPE, tArgs);
// player->FireEvent(PlAYER_LOGINOUT_CLEAR_EVENT_TYPE, tArgs);
SaveDataInfo sendData;
ite->second.playerCache->SaveAllPlayer(sendData,true,true);
//通知GT玩家下线
ServerReturn::ServerRetInt sim;
sim.set_ret(player->GetID());
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_SIM_GM2GT_PLAYER_EXIT, &sim, player->GetChannelID(), SimpleMessage);
Message_Facade::Send(messRet);
Smart_Ptr<Player> myself;
ite->second.playerCache->SetMyself(myself);
m_PlayerCache.erase(ite++);
}
else
{
Smart_Ptr<Player> myself;
ite->second.playerCache->SetMyself(myself);
m_PlayerCache.erase(ite++);
}
}
else
{
++ite;
}
}
}
bool PlayerMessage::PlayerLogout(Smart_Ptr<Player> pObj)
{
if(pObj && pObj->GetType() == ePlayer)
{
}
return true;
}
//网关服请求游戏服玩家信息
DEF_MSG_REQUEST_DEFINE_FUN(PlayerMessage, MSG_REQ_GT2GM_PLAYERINFO)
{
ServerReturn::ServerRetIntChar req;
ServerReturn::ServerRetInt con;
int len = 0;
char *str = message->GetBuffer(len);
req.ParseFromArray(str, len);
LOG_DEBUG(FILEINFO, "Player login on and get playerinfo[%lld]", GET_SERVER_CHARID(req.retf()));
Smart_Ptr<SvrItem> dbSvr = NULL;
if(IsOnline(req.retf()))
{
LOG_ERROR(FILEINFO, "player[%lld] is online", GET_SERVER_CHARID(req.retf()));
return;
}
//找到DB服
ServerConHandler::GetInstance()->GetDBServerBySvrID(GET_SERVER_CHARID(req.retf()),dbSvr);
if(!dbSvr)
{
LOG_FATAL(FILEINFO, "Gameserver find no DBServer in server [serverID=%lld]",GET_SERVER_CHARID(req.retf()));
return;
}
con.set_ret(GET_PLAYER_CHARID(req.retf()));
//建立游戏服向DB服请求玩家信息
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GM2DB_PLAYERINFO, &con, dbSvr.Get(), Request);
string client_ip = req.rets();
messRet->SetAct(new StringIntAct(message, 0, 0, client_ip));
Message_Facade::Send(messRet);
}
//游戏服请求DB服玩家信息
DEF_MSG_ACK_DEFINE_FUN(PlayerMessage, MSG_REQ_GM2DB_PLAYERINFO)
{
//请求超时
if (message->GetErrno() == eReqTimeOut)
{
LOG_DEBUG(FILEINFO, "gameserver request dbserver player info and ack timeout");
return;
}
//声明玩家信息的各个结构体
PlayerInfo::PlayerInfo content;
int len = 0;
int64 nowTime = CUtil::GetNowSecond();
char *con = message->GetBuffer(len);
content.ParseFromArray(con, len);
const PlayerInfo::BaseInfo& bsinfo = content.bsinfo();
if(IsOnline(bsinfo.charid()))
{
LOG_ERROR(FILEINFO, "player[%lld] is online", bsinfo.charid());
return;
}
Smart_Ptr<Object> obj = ObjectFactory::GetInstance()->AllocObject(ePlayer);
//将obj定为一个玩家Player
Smart_Ptr<Player> player = obj;
player->SetMyself(player);
//设置玩家登录时间
player->SetLoginTime(nowTime);
player->SetChannelID(static_cast<StringIntAct *>(act.Get())->mesReq->GetChannelID());
player->SetDBChannelID(Message_Facade::BindGroupChannel(static_cast<StringIntAct *>(act.Get())->mesReq->GetChannelID(), ServerConHandler::GetInstance()->GetDBChannelBySvrID(GET_SERVER_CHARID(player->GetID()))));
player->InitBaseInfo(content.bsinfo());
PLayerCache cache;
cache.playerCache = player;
cache.time = nowTime;
cache.bFlag = true;
m_PlayerCache[bsinfo.charid()] = cache;
if(!(static_cast<StringIntAct *>(act.Get())->mesDataf))
{ //刚登录的
player->SetIP(static_cast<StringIntAct *>(act.Get())->mesDatafo); //刚登录设置 玩家的 IP信息
}
#ifdef DEBUG
int endTime = CUtil::GetNowSecond();
if(endTime - nowTime > 100)
{
printf("\n 玩家初始化时间: time=%lld \n", endTime - nowTime );
LOG_FATAL(FILEINFO, "ack player info and need more time[%lld]", endTime - nowTime);
}
#endif
if(!(static_cast<StringIntAct *>(act.Get())->mesReq))
{
LOG_DEBUG(FILEINFO, "player login in game and finish player[%lld] info ", GET_PLAYER_CHARID(player->GetID()));
CharLogin::CharBaseInfo info;
player->SetCharBaseInfo(&info);
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GT2GM_PLAYERINFO,static_cast<commonAct *>(act.Get())->mesReq,&info);
messRet->SetMessageTime(info.charid());
Message_Facade::Send(messRet);
}
}
DEF_MSG_ACK_DEFINE_FUN(PlayerMessage, MSG_REQ_GS2DB_SAVE_PLAYERDATA)
{
int64 charID = static_cast<IntAct*>(act.Get())->mesData;
std::map<int64,SaveDataInfo>::iterator it=m_saveDataList.find(charID);
if(it==m_saveDataList.end())
{
LOG_DEBUG(FILEINFO, "\n 请求保存玩家数据时返回找不到玩家:id=%lld \n", charID);
return;
}
dealWithSaveResult(it->second);
m_saveDataList.erase(it);
}
//网关服发消息通知clientin
DEF_MSG_REQUEST_DEFINE_FUN(PlayerMessage, MSG_REQ_GT2GM_CLIENTIN)
{
ServerReturn::ServerRetInt meContent;
char *con;
int len = 0;
con = message->GetBuffer(len);
meContent.ParseFromArray(con, len);
int64 charID = message->GetMessageTime();
map<int64, Smart_Ptr<Player> >::iterator itMap = m_allPlayer.find(charID);
if (itMap != m_allPlayer.end())
{
LOG_ERROR(FILEINFO, " player[%lld] already online ", charID);
return;
}
map<int64, PLayerCache >::iterator it = m_PlayerCache.find(charID);
if(it != m_PlayerCache.end())
{
Smart_Ptr<Player> tempPlayer = it->second.playerCache;
Smart_Ptr<Object> obj = tempPlayer;
//进入事件触发
if(tempPlayer)
{
// PlayerLoginEventArgs tArgs(tempPlayer,GET_MAP_ID(obj->GetMapID()));
// tempPlayer->FireEvent(PLAYER_ENTERMAP_EVENT_TYPE, tArgs);
}
//玩家登入完成,添加到玩家列表里,删除Cache值
m_PlayerCache.erase(it);
m_allPlayer[charID] = tempPlayer;
Safe_Smart_Ptr<CommBaseOut::Message> gatemess = build_message(MSG_REQ_GT2GM_CLIENTIN, message, &meContent);
Message_Facade::Send(gatemess);
}
else
{
LOG_ERROR(FILEINFO, "MSG_REQ_GT2GM_CLIENTIN: player[%lld] login in timeout, time=%lld", GET_PLAYER_CHARID(charID), CUtil::GetNowSecond());
}
}
DEF_MSG_REQUEST_DEFINE_FUN(PlayerMessage, MSG_REQ_GT2GM_PLAYEREXIT)
{
ServerReturn::ServerDoubleInt meContent;
Smart_Ptr<ServerReturn::ServerRetInt> ack = new ServerReturn::ServerRetInt();
char *con;
int len = 0;
con = message->GetBuffer(len);
meContent.ParseFromArray(con, len);
ack->set_ret(meContent.retf());
int64 offlineTime = CUtil::GetNowSecond();
//下线,清玩家缓存
map<int64, PLayerCache >::iterator ite = m_PlayerCache.find(meContent.retf());
if (ite != m_PlayerCache.end())
{
ite->second.playerCache->SetOffLineTime(offlineTime);
if (ite->second.playerCache->GetType() == ePlayer)
{
PlayerLogout(ite->second.playerCache);
SaveDataInfo sendData;
sendData.msgtype = Ack;
sendData.msgid = MSG_REQ_GT2GM_PLAYEREXIT;
sendData.message = message;
sendData.content = ack;
ite->second.playerCache->SaveAllPlayer(sendData,true,true);
Smart_Ptr<Player> myself;
ite->second.playerCache->SetMyself(myself);
}
m_PlayerCache.erase(ite);
}
else
{
//从玩家列表中移出
map<int64, Smart_Ptr<Player> >::iterator it = m_allPlayer.find(meContent.retf());
if (it != m_allPlayer.end())
{
it->second->SetOffLineTime(offlineTime);
Smart_Ptr<Object> obj = it->second;
if (obj->GetType() == ePlayer)
{
PlayerLogout(it->second);
{
SaveDataInfo sendData;
sendData.msgtype = Ack;
sendData.msgid = MSG_REQ_GT2GM_PLAYEREXIT;
sendData.message = message;
sendData.content = ack;
it->second->SaveAllPlayer(sendData,true,true);
}
Smart_Ptr<Player> myself;
it->second->SetMyself(myself);
}
m_allPlayer.erase(it);
}
else
{
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GT2GM_PLAYEREXIT, message, ack.Get());
Message_Facade::Send(messRet);
}
}
}
//更新玩家属性
DEF_MSG_REQUEST_DEFINE_FUN(PlayerMessage, MSG_REQ_GT2GM_SYN_ATTR)
{
CharLogin::SynCharBase meContent;
char *con;
int len = 0;
con = message->GetBuffer(len);
meContent.ParseFromArray(con, len);
int64 charID = message->GetMessageTime();
Smart_Ptr<Player> player;
GetPlayerByCharid(charID, player);
if(player)
{
player->SetTypeValue(meContent);
}
}
|
#pragma once
#include <iberbar/RHI/OpenGL/Headers.h>
namespace iberbar
{
namespace RHI
{
class IDevice;
}
}
extern "C" __iberbarRHIOpenGLApi__ iberbar::RHI::IDevice* iberbarRhiDeviceCreate();
|
/*
========================================================================
DEVise Data Visualization Software
(c) Copyright 1992-1996
By the DEVise Development Group
Madison, Wisconsin
All Rights Reserved.
========================================================================
Under no circumstances is this software to be copied, distributed,
or altered in any way without prior permission from the DEVise
Development Group.
*/
/*
Implementation of DataSourceFileStream class.
*/
/*
$Id: DataSourceFileStream.c,v 1.9 1996/12/03 20:36:07 jussi Exp $
$Log: DataSourceFileStream.c,v $
Revision 1.9 1996/12/03 20:36:07 jussi
Added support for concurrent I/O.
Revision 1.8 1996/11/18 22:29:01 jussi
Added DataSize() method.
Revision 1.7 1996/10/07 22:53:57 wenger
Added more error checking and better error messages in response to
some of the problems uncovered by CS 737 students.
Revision 1.6 1996/08/04 21:23:23 beyer
DataSource's are now reference counted.
Added Version() which TData now check to see if the DataSource has changed,
and if it has, it rebuilds its index and invalidates the cache.
DataSourceFixedBuf is a DataSourceBuf that allocates and destoyes its
own buffer.
DerivedDataSource functionality is now in the TData constructor.
Added some defaults for virtual methods.
Revision 1.5 1996/07/01 19:31:33 jussi
Added an asynchronous I/O interface to the data source classes.
Added a third parameter (char *param) to data sources because
the DataSegment template requires that all data sources have the
same constructor (DataSourceWeb requires the third parameter).
Revision 1.4 1996/06/27 15:50:58 jussi
Added IsOk() method which is used by TDataAscii and TDataBinary
to determine if a file is still accessible. Also moved GetModTime()
functionality from TDataAscii/TDataBinary to the DataSource
classes.
Revision 1.3 1996/06/04 19:58:44 wenger
Added the data segment option to TDataBinary; various minor cleanups.
Revision 1.2 1996/06/04 14:20:23 wenger
Ascii data can now be read from session files (or other files
where the data is only part of the file); added some assertions
to check for pointer alignment in functions that rely on this;
Makefile changes to make compiling with debugging easier.
Revision 1.1 1996/05/22 17:52:03 wenger
Extended DataSource subclasses to handle tape data; changed TDataAscii
and TDataBinary classes to use new DataSource subclasses to hide the
differences between tape and disk files.
*/
#define _DataSourceFileStream_c_
//#define DEBUG
#include <stdio.h>
#include <string.h>
#include <errno.h>
//#include <unistd.h>
//#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "DataSourceFileStream.h"
#include "Util.h"
#include "DevError.h"
#if !defined(lint) && defined(RCSID)
static char rcsid[] = "$RCSfile: DataSourceFileStream.c,v $ $Revision: 1.9 $ $State: Exp $";
#endif
static char * srcFile = __FILE__;
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::DataSourceFileStream
* DataSourceFileStream constructor.
*/
DataSourceFileStream::DataSourceFileStream(char *filename, char *label)
: DataSource(label)
{
DO_DEBUG(printf("DataSourceFileStream::DataSourceFileStream(%s, %s)\n",
filename, (label != NULL) ? label : "null"));
_filename = strdup(filename);
_file = NULL;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::~DataSourceFileStream
* DataSourceFileStream destructor.
*/
DataSourceFileStream::~DataSourceFileStream()
{
DO_DEBUG(printf("DataSourceFileStream::~DataSourceFileStream()\n"));
delete [] _filename;
if (_file != NULL) fclose(_file);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Open
* Do an fopen() on the file corresponding to the DataSourceFileStream object.
*/
DevStatus
DataSourceFileStream::Open(char *mode)
{
DO_DEBUG(printf("DataSourceFileStream::Open()\n"));
DevStatus result = StatusOk;
_file = fopen(_filename, mode);
if (_file == NULL)
{
char errBuf[MAXPATHLEN+100];
sprintf(errBuf, "unable to open file %s", _filename);
reportError(errBuf, errno);
result = StatusFailed;
}
return result;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::IsOk
* Return true if file is open and in good status.
*/
Boolean
DataSourceFileStream::IsOk()
{
if (!_file)
return false;
struct stat sbuf;
if (stat(_filename, &sbuf) < 0)
return false;
// All the following checks succeed even if the file has been deleted!
// Stat is almost the only function that recognizes that a file
// has been removed. Doing an fopen/fclose would also work.
#if 0
if (GetModTime() < 0)
return false;
if (fseek(_file, 0, SEEK_CUR) < 0)
return false;
if (Tell() < 0)
return false;
#endif
return true;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Close
* Do an fclose() on the file corresponding to the DataSourceFileStream object.
*/
DevStatus
DataSourceFileStream::Close()
{
DO_DEBUG(printf("DataSourceFileStream::Close()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
DevStatus result = StatusOk;
if (fclose(_file) != 0)
{
reportError("error closing file", errno);
result = StatusFailed;
}
_file = NULL; // So destructor doesn't try to close it again.
return result;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Fgets
* Do an fgets() on the file corresponding to the DataSourceFileStream object.
*/
char *
DataSourceFileStream::Fgets(char *buffer, int bufSize)
{
DO_DEBUG(printf("DataSourceFileStream::Fgets()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
errno = 0;
char *result = fgets(buffer, bufSize, _file);
if ((result == NULL) && (errno != 0)) reportErrSys("fgets");
return result;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Fread
* Do fread() on the stream associated with this object.
*/
size_t
DataSourceFileStream::Fread(char *buf, size_t size, size_t itemCount)
{
DO_DEBUG(printf("DataSourceFileStream::Fread()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
return fread(buf, size, itemCount, _file);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Read
* Do read() on the stream associated with this object.
*/
size_t
DataSourceFileStream::Read(char *buf, int byteCount)
{
DO_DEBUG(printf("DataSourceFileStream::Read()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
return read(fileno(_file), buf, byteCount);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Fwrite
* Do fwrite() on the stream associated with this object.
*/
size_t
DataSourceFileStream::Fwrite(const char *buf, size_t size, size_t itemCount)
{
DO_DEBUG(printf("DataSourceFileStream::Fwrite()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
return fwrite(buf, size, itemCount, _file);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Write
* Do write() on the stream associated with this object.
*/
size_t
DataSourceFileStream::Write(const char *buf, size_t byteCount)
{
DO_DEBUG(printf("DataSourceFileStream::Write()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
return write(fileno(_file), buf, byteCount);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Seek
* Do fseek() on the stream associated with this object.
*/
int
DataSourceFileStream::Seek(long offset, int from)
{
DO_DEBUG(printf("DataSourceFileStream::Seek()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
return fseek(_file, offset, from);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::Tell
* Do ftell() on the stream associated with this object.
*/
long
DataSourceFileStream::Tell()
{
DO_DEBUG(printf("DataSourceFileStream::Tell()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
return ftell(_file);
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::gotoEnd
* Go to the end of the file associated with this object, and return the
* offset of the end of the file.
*/
int
DataSourceFileStream::gotoEnd()
{
//DO_DEBUG(printf("DataSourceFileStream::gotoEnd()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
int result = 0;
if (fseek(_file, 0, SEEK_END) < 0)
{
reportError("Cannot seek to end of file", errno);
result = -1;
DOASSERT(false, "");
}
else
{
result = ftell(_file);
if (result < 0)
{
reportError("Cannot get current file position", errno);
result = -1;
DOASSERT(false, "");
}
}
return result;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::append
* Append the given record to the end of the file associated with this
* object.
*/
int
DataSourceFileStream::append(void *buf, int recSize)
{
DO_DEBUG(printf("DataSourceFileStream::append()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
int result = 0;
if (gotoEnd() < 0)
{
reportError("Cannot go to end of file", devNoSyserr);
result = -1;
}
else
{
result = write(fileno(_file), buf, recSize);
}
return result;
}
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::GetModTime
* Returns the last modification time of the object.
*/
int
DataSourceFileStream::GetModTime()
{
DO_DEBUG(printf("DataSourceFileStream::GetModTime()\n"));
DOASSERT(_file != NULL, "Invalid file pointer");
struct stat sbuf;
int status = fstat(fileno(_file), &sbuf);
if (status < 0) {
reportError("Cannot get modification time for file", devNoSyserr);
return -1;
}
int result = (long)sbuf.st_mtime;
return result;
}
/*============================================================================*/
/*------------------------------------------------------------------------------
* function: DataSourceFileStream::DataSize
* Return file size.
*/
bytecount_t
DataSourceFileStream::DataSize()
{
if (!_file)
return 0;
struct stat sbuf;
if (stat(_filename, &sbuf) < 0)
return 0;
return (bytecount_t)sbuf.st_size;
}
|
#include "main-app.h"
#include "main-frame.h"
IMPLEMENT_APP(MyApp)
bool MyApp::OnInit()
{
wxFileConfig *pConfig1 = new wxFileConfig(wxT("ec-fc"),wxT("lyqx"),
wxT("ec-fc.ini"),wxT("ec-fc.ini"),
wxCONFIG_USE_GLOBAL_FILE|wxCONFIG_USE_RELATIVE_PATH);
wxConfigBase::Set(pConfig1);
wxConfigBase::Get() -> SetRecordDefaults();
MyFrame *frame = new MyFrame(wxT("Hello wxDC"), wxPoint(50,50), wxSize(940,680));
//frame->SetAutoLayout(true);
frame->Show(true);
SetTopWindow(frame);
return true;
}
int MyApp::OnExit()
{
delete wxConfigBase::Set((wxConfigBase *) NULL);
return 0;
}
|
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
string str;
cout << "Enter string to check if anagram or not" << endl;
getline(cin, str);
transform(str.begin(), str.end(), str.begin(), ::toupper);
int fre_even = 0;
int fre_odd = 0;
int fre_one = 0;
int q = 0;
for (char x = 'A'; x <= 'Z'; x++)
{
int count = 0;
for (int y = 0; y < str.length(); y++)
{
char c = str[y];
if (c == x)
{
count++;
}
}
if (count % 2 != 0)
{
if (count == 1)
{
fre_one++;
}
else
{
fre_odd++;
}
}
else if (count % 2 == 0 && count!=0)
{
fre_even++;
}
else
{
continue;
}
}
if (fre_one > 1 || fre_odd > 0)
{
cout << "NO";
}
else
{
cout << "YES";
}
return 0;
}
|
#include "Server.h"
#include <iostream>
Server::Server(short port, int max_connections, int input_buffer_size)
{
peer_ = new BasePeer(input_buffer_size);
peer_->Bind(port);
max_connections_ = max_connections;
}
Server::~Server()
{
free(peer_);
}
bool Server::Start()
{
return peer_->Listen(max_connections_);
}
bool Server::Update()
{
return peer_->Update();
}
void Server::Stop()
{
peer_->Close(peer_->getPeerSocket());
}
void Server::SetCallbacks(void (*on_recv)(SOCKET handle, unsigned char* buffer, int length),
void (*on_connect)(SOCKET handle),
void (*on_disconnect)(SOCKET handle))
{
peer_->SetCallbacks(on_recv, on_connect, on_disconnect);
}
void Server::Send(SOCKET handle, BufferWriter writer)
{
peer_->Send(handle, writer.getBuffer(), writer.getPosition());
}
|
#pragma once
#include <vector>
#include "ADetection.hh"
#include "State.hh"
using namespace boost::asio;
class ToSDetection : public ADetection
{
private:
struct ToSVariation
{
ip::address from;
ip::address to;
double variance;
ToSVariation(ip::address f_ip, ip::address t_ip)
: from(f_ip), to(t_ip), variance(0)
{
}
};
std::vector<ToSVariation> _variations;
void testToSValues(boost::ptr_vector<State>&);
void findToSVariations(boost::ptr_vector<State>&);
void registerToSVariations(ToSVariation&, boost::ptr_vector<State>&);
void analyseToSVariations();
public:
ToSDetection();
~ToSDetection();
void work(boost::ptr_vector<State>);
};
|
#ifndef ENDGAME_H
#define ENDGAME_H
#include <QWidget>
#include <QLabel>
#include <QTimer>
namespace Ui {
class EndGame;
}
class EndGame : public QWidget
{
Q_OBJECT
bool gameOver;
public:
EndGame(QWidget *parent = 0, bool gameOver_ = true);
~EndGame();
bool checkHighScore();
QTimer* getBonusTimer() { return bonusTimer; }
private slots:
void on_PBcontinue_clicked();
void bonusTimerHit();
private:
Ui::EndGame *ui;
QWidget* widgetParent;
QTimer* bonusTimer;
int bonusToAdd;
int bonusAmount;
};
#endif // ENDGAME_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef DOM_DOMSELECTION_H
#define DOM_DOMSELECTION_H
#include "modules/dom/src/domobj.h"
#ifdef DOM_SELECTION_SUPPORT
#include "modules/dom/src/domrange/range.h"
#include "modules/util/tempbuf.h"
class DOM_Document;
class DOM_Node;
class DOM_WindowSelection
: public DOM_BuiltInConstructor
{
protected:
DOM_WindowSelection(DOM_Document *document);
~DOM_WindowSelection();
/** The document the selection belongs to. */
DOM_Document *owner_document;
/** The range associated with the selection. Can be NULL if nothing is
* selected and no script has added a range. */
DOM_Range *range;
/** TRUE if the selection's direction is forward, otherwise FALSE. */
BOOL forwards;
/** TRUE if the user has made a new selection and we need to update the
* internal range before doing further operations on it. */
BOOL is_dirty;
/** If TRUE, we are currently updating the member range from the users
* selection and we should not trigger any further updates as long
* as that is going on. */
BOOL is_updating_range;
/** If TRUE calls to UpdateSelectionFromRange() will be no-op. */
BOOL lock_updates_from_range;
/** Called to check if the selection is collapsed.
* @param[out] is_collapsed TRUE after the call if selection is collapsed.
* @returns Normal OOM values. */
OP_STATUS IsCollapsed(BOOL &is_collapsed);
/** Called before operations on the member range to make sure we have
* updated the range to the user selection if needed.
* @returns Normal OOM values. */
OP_STATUS UpdateRange()
{
if (!range)
return UpdateRangeFromSelection();
return OpStatus::OK;
}
/** Gets both the end points of the associated range. Depending on the
* direction of the selection, the anchor point and the focus point can
* be the first or second end point of the range.
* @param[out] anchorBP Will contain the anchor point after the call.
* @param[out] focusBP Will contain the focus point after the call. */
void GetAnchorAndFocus(DOM_Range::BoundaryPoint &anchorBP, DOM_Range::BoundaryPoint &focusBP);
/** Gets the node of one of the end points of the associated range.
* @param[out] node Will contain a pointer to the requested node if the
* call is successful.
* @param anchor If TRUE, the anchor node will be fetched, otherwise
* the focus node.
* @returns Normal OOM values. */
OP_STATUS GetBoundaryNode(DOM_Node *&node, BOOL anchor);
/** Gets the offset of one of the end points of the associated range.
* @param[out] offset Will contain the requested offset if the call
* is successful.
* @param anchor If TRUE, the anchor offset will be fetched, otherwise
* the focus offset.
* @returns Normal OOM values. */
OP_STATUS GetBoundaryOffset(unsigned &offset, BOOL anchor);
/** Must be called to update the member range from a user selection.
* @returns Normal OOM values. */
OP_STATUS UpdateRangeFromSelection();
/** Must be called after operations on the member range to set the actual
* selection in the displayed document.
* @returns Normal OOM values. */
OP_STATUS UpdateSelectionFromRange();
friend class DOM_Range;
public:
static OP_STATUS Make(DOM_WindowSelection *&selection, DOM_Document *document);
DOM_Range* GetRange() { return range; }
/** Called when the user has changed the selection in any way to mark that
* the member range needs update to the new user selection before any
* future operations on the range. */
void OnSelectionUpdated() { if (!is_updating_range) range = NULL; }
virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
virtual BOOL IsA(int type) { return type == DOM_TYPE_WINDOWSELECTION || DOM_Object::IsA(type); }
virtual void GCTrace();
DOM_DECLARE_FUNCTION(getRangeAt);
DOM_DECLARE_FUNCTION(collapse);
DOM_DECLARE_FUNCTION(extend);
DOM_DECLARE_FUNCTION(containsNode);
DOM_DECLARE_FUNCTION(selectAllChildren);
DOM_DECLARE_FUNCTION(addRange);
DOM_DECLARE_FUNCTION(deleteFromDocument);
DOM_DECLARE_FUNCTION(toString);
enum { FUNCTIONS_ARRAY_SIZE = 10 };
DOM_DECLARE_FUNCTION_WITH_DATA(removeRange);
DOM_DECLARE_FUNCTION_WITH_DATA(collapseToStartOrEnd);
enum { FUNCTIONS_WITH_DATA_ARRAY_SIZE = 5 };
};
#endif // DOM_SELECTION_SUPPORT
#endif // DOM_DOMSELECTION_H
|
#ifndef __AUTOPTR_H__
#define __AUTOPTR_H__
// this class is NOT safe for array new's. It will not properly call
// the destructor for each element and you will silently leak memory.
// it does work for classes requiring no destructor however(base types)
template<typename type>
class idAutoPtr
{
public:
explicit idAutoPtr(type *ptr = 0)
: mPtr(ptr)
{
}
~idAutoPtr()
{
delete mPtr;
}
type &operator*() const
{
return *mPtr;
}
type *operator->() const
{
return &**this;
}
type *get() const
{
return mPtr;
}
type *release()
{
type *ptr = mPtr;
mPtr = NULL;
return ptr;
}
void reset(type *ptr = NULL)
{
if (ptr != mPtr)
delete mPtr;
mPtr = ptr;
}
operator type*()
{
return get();
}
private:
// disallow copies
idAutoPtr<type> &operator=(idAutoPtr<type>& ptr);
idAutoPtr(idAutoPtr<type>& ptr);
type *mPtr;
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.