blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
cf4e4109e985df4652649a92771689beb930e250 | C++ | jacktrip/Simple-FFT | /unit-tests/test_with_native_cpp_pointer_based_arrays.cpp | UTF-8 | 4,523 | 2.65625 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | #include "../include/simple_fft/fft_settings.h"
// Native C++ arrays use square brackets for element access operator
#ifndef __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR
#define __USE_SQUARE_BRACKETS_FOR_ELEMENT_ACCESS_OPERATOR
#endif
#include "../include/simple_fft/fft.h"
#include "test_fft.h"
#include <iostream>
namespace simple_fft {
namespace fft_test {
int testNativeArraysFFT()
{
std::cout << "Testing FFT algorithms with native C++ arrays on heap using "
<< "pointers to operate them" << std::endl;
using namespace pulse_params;
std::vector<real_type> t, x, y;
makeGridsForPulse3D(t, x, y);
// typedefing arrays
typedef real_type* RealArray1D;
typedef complex_type* ComplexArray1D;
typedef real_type** RealArray2D;
typedef complex_type** ComplexArray2D;
typedef real_type*** RealArray3D;
typedef complex_type*** ComplexArray3D;
// 1D fields and spectrum
RealArray1D E1_real = new real_type[nt];
ComplexArray1D E1_complex = new complex_type[nt];
ComplexArray1D G1 = new complex_type[nt];
ComplexArray1D E1_restored = new complex_type[nt];
// 2D fields and spectrum
RealArray2D E2_real = new RealArray1D[nt];
for(size_t i = 0; i < nt; ++i) {
E2_real[i] = new real_type[nx];
}
ComplexArray2D E2_complex = new ComplexArray1D[nt];
for(size_t i = 0; i < nt; ++i) {
E2_complex[i] = new complex_type[nx];
}
ComplexArray2D G2 = new ComplexArray1D[nt];
for(size_t i = 0; i < nt; ++i) {
G2[i] = new complex_type[nx];
}
ComplexArray2D E2_restored = new ComplexArray1D[nt];
for(size_t i = 0; i < nt; ++i) {
E2_restored[i] = new complex_type[nx];
}
// 3D fields and spectrum
RealArray3D E3_real = new RealArray2D[nt];
for(size_t i = 0; i < nt; ++i) {
E3_real[i] = new RealArray1D[nx];
for(size_t j = 0; j < nx; ++j) {
E3_real[i][j] = new real_type[ny];
}
}
ComplexArray3D E3_complex = new ComplexArray2D[nt];
for(size_t i = 0; i < nt; ++i) {
E3_complex[i] = new ComplexArray1D[nx];
for(size_t j = 0; j < nx; ++j) {
E3_complex[i][j] = new complex_type[ny];
}
}
ComplexArray3D G3 = new ComplexArray2D[nt];
for(size_t i = 0; i < nt; ++i) {
G3[i] = new ComplexArray1D[nx];
for(size_t j = 0; j < nx; ++j) {
G3[i][j] = new complex_type[ny];
}
}
ComplexArray3D E3_restored = new ComplexArray2D[nt];
for(size_t i = 0; i < nt; ++i) {
E3_restored[i] = new ComplexArray1D[nx];
for(size_t j = 0; j < nx; ++j) {
E3_restored[i][j] = new complex_type[ny];
}
}
if (!commonPartsForTests3D(E1_real, E2_real, E3_real, E1_complex, E2_complex,
E3_complex, G1, G2, G3, E1_restored, E2_restored,
E3_restored, t, x, y))
{
std::cout << "Tests of FFT with native C++ pointer-based arrays on heap "
<< "returned with errors!" << std::endl;
return FAILURE;
}
// free 3D arrays
for(size_t j = 0; j < nx; ++j) {
for(size_t i = 0; i < nt; ++i) {
delete[] E3_restored[i];
E3_restored[i] = NULL;
delete[] G3[i];
G3[i] = NULL;
delete[] E3_complex[i];
E3_complex[i] = NULL;
delete[] E3_real[i];
E3_real[i] = NULL;
}
delete[] E3_restored[j];
E3_restored[j] = NULL;
delete[] G3[j];
G3[j] = NULL;
delete[] E3_complex[j];
E3_complex[j] = NULL;
delete[] E3_real[j];
E3_real[j] = 0;
}
delete[] E3_restored;
delete[] G3;
delete[] E3_complex;
delete[] E3_real;
// free 2D arrays
for(size_t i = 0; i < nt; ++i) {
delete[] E2_restored[i];
E2_restored[i] = NULL;
delete[] G2[i];
G2[i] = NULL;
delete[] E2_complex[i];
E2_complex[i] = NULL;
delete[] E2_real[i];
E2_real[i] = NULL;
}
delete[] E2_restored;
delete[] G2;
delete[] E2_complex;
delete[] E2_real;
// free 1D arrays
delete[] E1_restored;
delete[] G1;
delete[] E1_complex;
delete[] E1_real;
std::cout << "Tests of FFT for native C++ pointer-based arrays on heap "
<< "completed successfully!" << std::endl;
return SUCCESS;
}
} // namespace fft_test
} // namespace simple_fft
| true |
4de3760079f9dfba74dd97b919582790f5f251bc | C++ | dahai78/noip | /第一章编程基础/ch05循环控制/02.cpp | UTF-8 | 972 | 3.234375 | 3 | [] | no_license | /*
江苏省黄桥中学 戴海源 版权所有 程序仅供参考 交流联系 626071473@qq.com
*/
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
int n;
cin >>n;
double total=0;
for(int i=0; i<n; i++)
{
double years;
cin >> years;
total += years;
}
cout << setprecision(4) << fixed << total / n;
}
/*********************************************************************************
均值
描述
给出一组样本数据,计算其均值。
输入
输入有两行,第一行包含一个整数n(n小于100),代表样本容量;第二行包含n个绝对值不超过1000的浮点数,代表各个样本数据。
输出
输出一行,包含一个浮点数,表示均值,精确到小数点后4位。
样例输入
2
1.0 3.0
样例输出
2.0000
************************************************************************************/ | true |
2e05a1c7c49824eef4755025be66f91a99755956 | C++ | Tsunaou/GraphicsYoung | /LineController.cpp | UTF-8 | 13,019 | 2.515625 | 3 | [] | no_license | #include "LineController.h"
LineController::LineController()
{
this->curLine = NULL;
this->painter = NULL;
this->setLP =SETNULL;
this->errorPara = 0;
}
void LineController::clearState()
{
this->curLine = NULL;
this->painter = NULL;
this->setLP =SETNULL;
this->errorPara = 0;
}
void LineController::getStartAndEnd(QPoint &start, QPoint &end)
{
start = curLine->startPoint.getQPoint(); //将直线信息存储下来
end = curLine->endPoint.getQPoint(); //将最终绘制的直线信息存储下来
}
void LineController::setBigger(QPainter* painter, QMouseEvent *e, QPen pen)
{
qDebug()<<"Before Bigger,start.x is"<< this->curLine->startPoint.getX() <<endl;
this->curLine->setStartPoint(this->curLine->startPoint*ZOOM_IN);
this->curLine->setEndPoint(this->curLine->endPoint*ZOOM_IN);
qDebug()<<"Line bigger"<<endl;
qDebug()<<"After Bigger,start.x is"<< this->curLine->startPoint.getX() <<endl;
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
void LineController::setSmaller(QPainter* painter, QMouseEvent *e, QPen pen)
{
this->curLine->setStartPoint(this->curLine->startPoint*ZOOM_OUT);
this->curLine->setEndPoint(this->curLine->endPoint*ZOOM_OUT);
qDebug()<<"Line smaller"<<endl;
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
bool LineController::cutLineLiangBsrsky(QPoint cutStart, QPoint cutEnd, QPainter *painter, QPen pen)
{
//在这里进行判断
//对裁剪窗口预处理
double xmin = std::min(cutStart.x(),cutEnd.x()); //决定裁剪窗口的参数
double ymin = std::min(cutStart.y(),cutEnd.y()); //传入的是决定裁剪窗口的对角线上的顶点,因此做一下处理
double xmax = std::max(cutStart.x(),cutEnd.x());
double ymax = std::max(cutStart.y(),cutEnd.y());
//得到待裁剪直线的各个端点
double x1 = curLine->startPoint.getX();
double y1 = curLine->startPoint.getY();
double x2 = curLine->endPoint.getX();
double y2 = curLine->endPoint.getY();
//各个参数的定义
double dx = x2-x1; //△x
double dy = y2-y1; //△y
double p[4] = {-dx,dx,-dy,dy};
double q[4] = {x1-xmin,xmax-x1,y1-ymin,ymax-y1};
double u1 = 0;
double u2 = 1;
//梁友栋裁剪算法,对p和q进行判断
for(int i=0;i<4;i++){
if(fabs(p[i])<1e-6 && q[i]<0){ //p=0且q<0时,舍弃该线段
this->clearState();
return false;
}
double r = q[i]/p[i];
if(p[i]<0){
u1 = r>u1?r:u1; //u1取0和各个r值之中的最大值
}else{
u2 = r<u2?r:u2; //u2取1和各个r值之中的最小值
}
if(u1>u2){ //如果u1>u2,则线段完全落在裁剪窗口之外,应当被舍弃
this->clearState();
return false;
}
}
qDebug()<<"梁友栋"<<endl;
curLine->setStartPoint(Point(x1+int(u1*dx+0.5), y1+int(u1*dy+0.5)));
curLine->setEndPoint(Point(x1+int(u2*dx+0.5), y1+int(u2*dy+0.5)));
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
return true;
}
Point LineController::getTheAccurayRotatePoint(qreal ridus, int x, int y)
{
int resX = x-ROTATE_ACCURACY;
int resY = y-ROTATE_ACCURACY;
double minDiff =100;
for(int i=x-ROTATE_ACCURACY;i<=x+ROTATE_ACCURACY;i++){
for(int j=y-ROTATE_ACCURACY;j<=y+ROTATE_ACCURACY;j++){
Point tmp(i,j);
double diffTmp = fabs(this->curLine->centerPoint.distanceToPoint(tmp.getQPoint())-ridus);
if(diffTmp<minDiff){
resX=i;
resY=j;
minDiff = diffTmp;
}
}
}
return Point(resX,resY);
}
bool LineController::isOperationing(QMouseEvent *e,QPoint &start,QPoint &end)
{
if(e->button()==Qt::LeftButton){
if(curLine->startPoint.distanceToPoint(e->pos())<=5)
{
qDebug()<<"SETBEGIN"<<endl;
setLP = SETBEGIN;
return true;
}
else if(curLine->endPoint.distanceToPoint(e->pos())<=5)
{
qDebug()<<"SETEND"<<endl;
setLP = SETEND;
return true;
}
else if(curLine->centerPoint.distanceToPoint(e->pos())<=5)
{
setLP = SETCENTER;
return true;
}
else if(curLine->rotatePoint.distanceToPoint(e->pos())<=5)
{
setLP = SETHANDLE;
return true;
}
}
setLP=SETNULL;
*state = UNDO;
start = curLine->startPoint.getQPoint(); //将直线信息存储下来
end = curLine->endPoint.getQPoint(); //将最终绘制的直线信息存储下来
curLine = NULL;
return false;
}
void LineController::mousePressEvent(QPainter *painter, QMouseEvent *e, QPen pen)
{
qDebug()<<"LineController::mousePressEvent"<<endl;
if(curLine!=NULL){
qDebug()<<"curLine!=NULL"<<endl;
}else{
qDebug()<<"curLine==NULL"<<endl;
}
if(e->button()==Qt::LeftButton || e->button()== Qt::RightButton)
{
if(e->button()==Qt::LeftButton && curLine!=NULL)
{
if(curLine->startPoint.distanceToPoint(e->pos())<=5)
{
qDebug()<<"SETBEGIN"<<endl;
setLP = SETBEGIN;
return;
}
else if(curLine->endPoint.distanceToPoint(e->pos())<=5)
{
qDebug()<<"SETEND"<<endl;
setLP = SETEND;
return;
}
else if(curLine->centerPoint.distanceToPoint(e->pos())<=5)
{
setLP = SETCENTER;
return;
}
else if(curLine->rotatePoint.distanceToPoint(e->pos())<=5)
{
setLP = SETHANDLE;
return;
}
setLP = SETNULL;
*state = UNDO;
curLine = NULL;
return;
}
Point curPoint(e->pos().x(),e->pos().y());
curLine = new Line();
curLine->setStartPoint(curPoint);
curLine->setEndPoint(curPoint);
setLP = SETEND;
*state = DRAWING;
}
}
void LineController::mouseMoveEvent(QPainter *painter, QMouseEvent *e, QPen pen)
{
qDebug()<<"LineController::mouseMoveEvent"<<endl;
this->painter = painter;
Point curPoint(e->pos().x(),e->pos().y());
if (curLine == NULL)
return;
switch(setLP){
case SETBEGIN: this->setStartPoint(curPoint); break;
case SETEND: this->setEndPoint(curPoint); break;
case SETCENTER: this->moveToPoint(curPoint); break;
case SETHANDLE: this->rotateToPoint(curPoint); break;
default:
qDebug()<<"Error setLP"<<endl;
}
}
void LineController::mouseReleaseEvent(QPainter *painter, QMouseEvent *e, QPen pen)
{
qDebug()<<"LineController::mouseReleaseEvent"<<endl;
qDebug()<<"state is";
switch (*state) {
case UNDO:
qDebug()<<"UNDO"<<endl;
break;
case DRAWING :
qDebug()<<"DRAWING"<<endl;
break;
}
this->painter = painter;
qDebug()<<"LineController::mouseReleaseEvent"<<endl;
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
void LineController::MyDrawLineBresenham(QPainter *painter, QPoint &start, QPoint &end)
{
if(!painter->isActive()) {return;}//保证在Painter有效的时候才进行
//首先先在这里实现我的直线算法
qDebug()<<"MyDrawLine Bresenham"<<endl;
int x1 = start.x();
int y1 = start.y();
int x2 = end.x();
int y2 = end.y();
int x,y,dx,dy,p;
x=x1;
y=y1;
dx=x2-x1;
dy=y2-y1;
p=2*dy-dx;
for(;x<=x2;x++)
{
QPoint temPt(x,y);
painter->drawPoint(temPt);
if(p>=0)
{ y++;
p+=2*(dy-dx);
}
else
{
p+=2*dy;
}
}
}
void LineController::MyDrawLineDDA(QPainter *painter, QPoint &start, QPoint &end)
{
if(!painter->isActive()) {return;}//保证在Painter有效的时候才进行
//首先先在这里实现我的直线算法
qDebug()<<"MyDrawLine DDA"<<endl;
qDebug()<< "before"<<endl;
int x1 = start.x();
qDebug()<< "after"<<endl;
int y1 = start.y();
int x2 = end.x();
int y2 = end.y();
double dx=x2-x1;
double dy=y2-y1;
double e=(fabs(dx)>fabs(dy))?fabs(dx):fabs(dy);
double x=x1;
double y=y1;
dx/=e;
dy/=e;
for(int i=1;i<=e;i++){
QPoint temPt((int)(x+0.5), (int)(y+0.5));
painter->drawPoint(temPt);
x+=dx;
y+=dy;
}
}
void LineController::setStartPoint(Point point)
{
qDebug() << "setStartPoint("<<endl;
curLine->setStartPoint(point);
qDebug() << "StartPoint(" <<curLine->startPoint.point.x()<<","<<curLine->startPoint.point.y()<<")"<<endl;
qDebug() << "EndPoint(" <<curLine->endPoint.point.x()<<","<<curLine->endPoint.point.y()<<")"<<endl;
//顺序不知道为啥会影响粗细。。
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
void LineController::setEndPoint(Point point)
{
qDebug() << "setEndPoint("<<endl;
curLine->setEndPoint(point);
qDebug() << "StartPoint(" <<curLine->startPoint.point.x()<<","<<curLine->startPoint.point.y()<<")"<<endl;
qDebug() << "EndPoint(" <<curLine->endPoint.point.x()<<","<<curLine->endPoint.point.y()<<")"<<endl;
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
void LineController::moveToPoint(Point point)
{
int offsetX = point.getX() - curLine->centerPoint.getX();
int offsetY = point.getY() - curLine->centerPoint.getY();
curLine->setStartPoint(Point(curLine->startPoint.getX()+offsetX,curLine->startPoint.getY()+offsetY));
curLine->setEndPoint(Point(curLine->endPoint.getX()+offsetX,curLine->endPoint.getY()+offsetY));
qDebug() << "StartPoint(" <<curLine->startPoint.point.x()<<","<<curLine->startPoint.point.y()<<")"<<endl;
qDebug() << "EndPoint(" <<curLine->endPoint.point.x()<<","<<curLine->endPoint.point.y()<<")"<<endl;
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
void LineController::rotateToPoint(Point point)
{
double RotaryAngle = getRotaryAngle(curLine->centerPoint,curLine->rotatePoint,point);
bool wiseFlag = clockWise(curLine->centerPoint,curLine->rotatePoint,point);
if(wiseFlag)
qDebug()<<"顺时针"<<endl;
else
qDebug()<<"逆时针"<<endl;
if(wiseFlag){//顺时针转
RotaryAngle *= -1;
}
//把x和y绕rx0和ry0旋转RotaryAngle度
int x = curLine->startPoint.getX();
int y = curLine->startPoint.getY();
int rx0 = curLine->centerPoint.getX();
int ry0 = curLine->centerPoint.getY();
int rotateStartX = (x - rx0)*cos(RotaryAngle) + (y - ry0)*sin(RotaryAngle) + rx0 ;
int rotateStartY = -(x - rx0)*sin(RotaryAngle) + (y - ry0)*cos(RotaryAngle) + ry0 ;
//curLine->setLength();
qreal l = this->curLine->getLength();
qDebug()<<"校正前:坐标为(" << rotateStartX<<","<<rotateStartY<< "),长度为"<<l<<endl;
Point accurayP = this->getTheAccurayRotatePoint(l/2,rotateStartX,rotateStartY);
rotateStartX = accurayP.getX();
rotateStartY = accurayP.getY();
curLine->setStartPoint(Point(rotateStartX,rotateStartY));
curLine->setEndPoint(Point(2*rx0-rotateStartX,2*ry0-rotateStartY));
qreal l2 = curLine->startPoint.distanceToPoint(curLine->endPoint.getQPoint());
qDebug()<<"校正后:坐标为(" << rotateStartX<<","<<rotateStartY<< "),长度为"<<l2<<endl;
this->errorPara += l2-l;
qDebug()<<"旋转累积误差为"<<this->errorPara<<endl;
qDebug() << "StartPoint(" <<curLine->startPoint.point.x()<<","<<curLine->startPoint.point.y()<<")"<<endl;
qDebug() << "EndPoint(" <<curLine->endPoint.point.x()<<","<<curLine->endPoint.point.y()<<")"<<endl;
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
drawHandle(painter,pen);
}
void LineController::setState(DRAW_STATE *state)
{
this->state = state;
}
void LineController::drawHandle(QPainter *painter, QPen pen)
{
curLine->startPoint.DrawCyclePoint(painter,pen);
curLine->endPoint.DrawCyclePoint(painter,pen);
curLine->centerPoint.DrawWarnPoint(painter,pen);
curLine->rotatePoint.DrawCyclePoint(painter,pen);
}
void LineController::drawWhileCutting(QPainter *painter, QPen pen)
{
MyDrawLineDDA(painter,curLine->startPoint.point,curLine->endPoint.point);
curLine->startPoint.DrawCyclePoint(painter,pen);
curLine->endPoint.DrawCyclePoint(painter,pen);
curLine->centerPoint.DrawWarnPoint(painter,pen);
curLine->rotatePoint.DrawCyclePoint(painter,pen);
}
| true |
61f803180359bd0d46ea60bc6957cdc22d34ad6b | C++ | dchassin/gridlabd | /source/realtime.cpp | UTF-8 | 1,585 | 2.671875 | 3 | [
"BSD-3-Clause",
"GPL-3.0-or-later"
] | permissive | /* realtime.cpp
* Copyright (C) 2008 Battelle Memorial Institute
* This module handle realtime events such as regular update to the environment, alarms and processing time limits.
*/
#include "gldcore.h"
// SET_MYCONTEXT(DMC_REALTIME) // used only if IN_MYCONTEXT is present
time_t realtime_now(void)
{
return time(NULL);
}
static time_t starttime = 0;
time_t realtime_starttime(void)
{
if ( starttime==0 )
starttime = realtime_now();
return starttime;
}
time_t realtime_runtime(void)
{
return realtime_now() - starttime;
}
/****************************************************************/
typedef struct s_eventlist {
time_t at;
STATUS (*call)(void);
struct s_eventlist *next;
} EVENT;
static EVENT *eventlist = NULL;
STATUS realtime_schedule_event(time_t at, STATUS (*callback)(void))
{
EVENT *event = (EVENT*)malloc(sizeof(EVENT));
if (event==NULL)
{
errno=ENOMEM;
return FAILED;
}
event->at = at;
event->call = callback;
event->next = eventlist;
eventlist = event;
return SUCCESS;
}
STATUS realtime_run_schedule(void)
{
time_t now = realtime_now();
EVENT *event, *last=NULL;
for (event=eventlist; event!=NULL; event=event->next)
{
if (event->at<=now)
{
STATUS (*call)(void) = event->call;
/* delete from list */
if (last==NULL) /* event is first in list */
eventlist = event->next;
else
last->next = event->next;
free(event);
event = NULL;
/* callback */
if ((*call)()==FAILED)
return FAILED;
/* retreat to previous event */
event = last;
if (event==NULL)
break;
}
}
return SUCCESS;
}
| true |
6045b4414742db0299c029d3236f7adce58b4c58 | C++ | Gweentaycy/VRGateway | /VRGateway/VLCVRApp.cpp | UTF-8 | 4,192 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
#include "VLCVRApp.h"
#include "Screen.h"
#include "colorshader.h"
#include <array>
VLCVRApp::VLCVRApp(bool stereo_input) : m_stereo_input(stereo_input)
{
m_background_colors[0] = 0.0f;
m_background_colors[1] = 0.0f;
m_background_colors[2] = 0.0f;
}
VLCVRApp::~VLCVRApp()
{
}
void VLCVRApp::ButtonPressed(vr::EVRButtonId button)
{
switch (button)
{
case vr::k_EButton_DPad_Right:
{
Matrix4 m;
m.scale(1.1f);
m_scale_matrix *= m;
break;
}
case vr::k_EButton_DPad_Left:
{
Matrix4 m;
m.scale(1.0f/1.1f);
m_scale_matrix *= m;
break;
}
case vr::k_EButton_DPad_Up:
{
Matrix4 m;
m.translate(Vector3(0,0.1f,0));
m_position_matrix *= m;
break;
}
case vr::k_EButton_DPad_Down:
{
Matrix4 m;
m.translate(Vector3(0, -0.1f, 0));
m_position_matrix *= m;
break;
}
}
}
void VLCVRApp::ProcessButton(const ControllerID device, const vr::VRControllerState_t &state)
{
std::array<vr::EVRButtonId,6> buttons = { vr::k_EButton_DPad_Left, vr::k_EButton_DPad_Up , vr::k_EButton_DPad_Right, vr::k_EButton_DPad_Down, vr::k_EButton_A, vr::k_EButton_ApplicationMenu };
uint64_t pressed_buttons = ButtonsFromState(state);
for(auto button : buttons)
{
uint64_t mask = vr::ButtonMaskFromId(button);
uint64_t current_button_state = pressed_buttons & mask;
uint64_t previous_button_state = m_prev_state.at(device) & mask;
if (current_button_state && !previous_button_state)
{
ButtonPressed(button);
}
}
m_prev_state.at(device) = pressed_buttons;
}
void VLCVRApp::HandleController()
{
}
bool VLCVRApp::renderWorld(D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, bool left)
{
bool result = true;
Model *obj = ((!left) & m_stereo_input ) ? m_right_screen.get() : m_left_screen.get();
if (obj == nullptr)
return false;
obj->Render(m_pImmediateContext);
// Render the model using the color shader.
D3DXMATRIX world = worldMatrix * m_scale_matrix * m_position_matrix;
result = m_ColorShader->Render(m_pImmediateContext, obj->GetIndexCount(), world, viewMatrix, projectionMatrix, obj->GetTexture());
if (!result)
{
return false;
}
return true;
}
bool VLCVRApp::setupWorld()
{
RECT src_rect;
GetWindowRect(m_source_window, &src_rect);
int rect_width = src_rect.right - src_rect.left + 1;
int rect_height = src_rect.bottom - src_rect.top + 1;
float sx = static_cast<float>(rect_width) / static_cast<float>(rect_height);
Vector3 screen_position(0, -0.1f, -2.0f);
float input_scale = m_stereo_input ? 0.5f : 1.0f;
m_left_screen.reset(new Screen);
float screen_size = 2.0f;
m_left_screen->SetScreenSize(screen_size);
m_left_screen->SetScreenPosition(screen_position);
// Initialize the model object.
bool result = m_left_screen->Initialize(m_pDevice, sx, input_scale,0.0f);
if (!result)
{
MyDebugDlg(L"Could not initialize the model object.");
return false;
}
m_left_screen->SetTexture(m_source_texture);
if (m_stereo_input)
{
m_right_screen.reset(new Screen);
m_right_screen->SetScreenSize(screen_size);
m_right_screen->SetScreenPosition(screen_position);
// Initialize the model object.
result = m_right_screen->Initialize(m_pDevice, sx, 0.5f, 0.5f);
if (!result)
{
MyDebugDlg(L"Could not initialize the model object." );
return false;
}
m_right_screen->SetTexture(m_source_texture);
}
return true;
}
bool VLCVRApp::NeedScreen()
{
return false;
}
const wchar_t *VLCVRApp::GetSourceParentClassName() const
{
return L"QWidget";
}
const wchar_t *VLCVRApp::GetSourceParentWindowName() const
{
return L"VLC media player";
}
const wchar_t *VLCVRApp::GetSourceClassName() const
{
return L"VLC video output";
}
const wchar_t *VLCVRApp::GetSourceWindowName() const
{
return nullptr;
} | true |
8ebc1359cfb12b4fcddd9722c4d061aee411a97e | C++ | ZihengZZH/LeetCode | /cpp/ReverseString.cpp | UTF-8 | 870 | 3.40625 | 3 | [] | no_license | /*
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
NOTE: Try to avoid running-time-exceeded
*/
#include <vector>
#include <bitset>
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <time.h>
#include <sstream>
using namespace std;
string reverseString(string s) {
string res = "";
for (int i = s.length()-1; i >= 0; i--) {
res += s[i];
}
return res;
}
int main() {
while (true) {
clock_t start;
clock_t stop;
int i;
string input = "hello";
string output;
start = clock();
stop = start + CLOCKS_PER_SEC;
for (i = 0; clock() < stop; i++) {
output = reverseString(input);
}
cout << "ANSWER IS " << output << endl;
printf("%f ms (%d trials)\n", 1000 * (double)start / CLOCKS_PER_SEC / i, i);
system("pause");
}
}
| true |
50ee4faa066eef3b439ad41d0d4c2f06213978ef | C++ | mamboguy/SpiritPhone | /commProject.ino | UTF-8 | 6,227 | 2.734375 | 3 | [] | no_license |
#include <SoftwareSerial.h>
#include <Adafruit_Soundboard.h>
/////////////////??////////GENERATED CODE///////////////////////////
// Choose any two pins that can be used with SoftwareSerial to RX & TX
#define SFX_TX 11
#define SFX_RX 10
// Connect to the RST pin on the Sound Board
#define SFX_RST 4
// We'll be using software serial
SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);
// pass the software serial to Adafruit_soundboard, the second
// argument is the debug port (not used really) and the third
// arg is the reset pin
Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);
/////////////////////////END GENERATED CODE/////////////////////////
/*
PINS USED:
2 - Breadboard Push Button
4 - SFX_RST
5 - PIR
6 - Push to talk button
8 - Dial
10 - SFX_RX
11 - SFX_TX
12 - Remote pin
*/
//CONSTANTS DEFINED FOR PIN LOCATION
const int PUSH_BUTTON_PIN = 2;
const int PIR_PIN = 5;
const int PUSH_TO_TALK_PIN = 6;
const int DIAL_PIN = 8;
const int PHONE_HOOK_PIN = 12;
const int REMOTE_PIN = 12;
//OTHER CONSTANTS
const long REMOTE_DELAY = 7200000; //Remote delays all processing for 2 hours
//MIN_PIR_DELAY to MAX_PIR_DELAY is the ranges of random time between PIR checks
const long MIN_PIR_DELAY = 1000; //in testing, 5-10s
const long MAX_PIR_DELAY = 2000;
/*
const int MIN_PIR_DELAY = 90000; //live, 90-900s
const int MAX_PIR_DELAY = 900000;
*/
//Variables for the reading current status
int buttonState = 0;
int pushToTalkState = 0;
int pirState = LOW;
int dialState = 0;
int phoneHookState = 0;
int remoteState = 0;
//timerValue - creates a random amount of time between PIR sensor checks
long timerValue = 0;
void setup() {
//Declare INPUT_PULLUP sensors
pinMode(PUSH_BUTTON_PIN, INPUT_PULLUP);
pinMode(PUSH_TO_TALK_PIN, INPUT_PULLUP);
pinMode(DIAL_PIN, INPUT_PULLUP);
pinMode(PHONE_HOOK_PIN, INPUT_PULLUP);
pinMode(REMOTE_PIN, INPUT_PULLUP);
//Declare INPUT sensors
pinMode(PIR_PIN, INPUT);
/////////////This is all from the original sound FX code////////////////////////
Serial.begin(115200);
Serial.println("Adafruit Sound Board!");
// softwareserial at 9600 baud
ss.begin(9600);
// can also do Serial1.begin(9600)
if (!sfx.reset()) {
Serial.println("Not found");
while (1);
}
Serial.println("SFX board found");
}
/////////////STATES///////////////
//State null = forever loop
//State 0 = phone on hook
//State 1 = phone lifted
//State 2 = button triggered
//State 3 = dial spun
//BEGIN LOOPING
void loop() {
//generate random timer
timerValue = random(MIN_PIR_DELAY, MAX_PIR_DELAY);
long startTime = millis();
do {
//read the state of the varius input values
phoneHookState = digitalRead(PHONE_HOOK_PIN);
remoteState = digitalRead(REMOTE_PIN);
if(phoneHookState == HIGH){
//if phone is lifted
state1();
/*
} else if (remoteState == HIGH){
//If remote is used, delay all processing for 2 hours
delay(REMOTE_DELAY);
*/
}
} while ((millis() - startTime) < timerValue);
//if random timer reached, go to state0
state0;
}
//triggers either a ringtone or soundclip after a specified delay
void triggerSound(int delayLength, bool ringtone){
//delay a specified amount of time
delay(delayLength);
//if ringtone sound
if (ringtone){
//Get a random ring tone
long randRingTone = random(5,9);
//Play random ringtone
sfx.playTrack((uint8_t)randRingTone); //THIS LINE PLAYS from the "randRingTone"
} else {
digitalWrite(13,HIGH);
//Get a random soundclip
//long randVader = random(5);
//Play random soundclip
//sfx.playTrack((uint8_t)randVader); //THIS LINE PLAYS from the "randVader" file selection
}
digitalWrite(13,LOW);
}
bool checkPIR(){
//Check the pir's current state
pirState = digitalRead(PIR_PIN);
//return PIR status of high or not
return (pirState == HIGH);
}
//Phone on receiver
void state0(){
//grab the current time value
unsigned long startTime = millis();
do {
//wait 0.5s between detection checks
delay(500);
if (checkPIR){
//if detection, play ringtone
triggerSound(0,true);
//End the cycle of checking since something was detected
startTime = millis() + 10000;
}
//check if PIR to detects something for 10s
} while ((millis()-startTime) < 10000);
//if no detection, drop to state null (forever loop)
}
//Phone lifted, nothing pressed
void state1(){
//trigger sound w/ delay
triggerSound(2000, false);
//continue will cause a loop until the phone is placed back on the receiver
bool continueLoop = true;
//loop forever for next phone input
while(continueLoop){
//read the state of the various input values
pushToTalkState = digitalRead(PUSH_TO_TALK_PIN);
phoneHookState = digitalRead(PHONE_HOOK_PIN);
dialState = digitalRead(DIAL_PIN);
if (phoneHookState == HIGH){
//on phone placed back on holder, reset to null state
continueLoop = false;
} else if (pushToTalkState == HIGH){
//on push to talk button use, go to state 2
state2();
} else if (dialState == HIGH){
//on dial used, go to state 3
state3();
}
}
}
//Push to talk button triggered
void state2(){
//trigger sound w/o delay
triggerSound(250, false);
//drop back to state 1
}
//Dial spun
void state3(){
//Wait until dial no longer active
while (dialState == HIGH){
//Check dial status while it is not moving every .1s
delay(100);
dialState = digitalRead(DIAL_PIN);
}
//trigger sound w/ delay
triggerSound(250, false);
//drop back to state 1
}
//Remote used
void state4(){
//Prep an infinite loop
bool continueLoop = true;
//Delay a second to allow user to lift hand off remote button
delay(1000);
//Loop until remote is used again
while (continueLoop){
//Check remote state every .1s
delay(100);
remoteState = digitalRead(REMOTE_PIN);
//If remote was used, exit loop
if (remoteState == HIGH){
continueLoop = false;
}
}
//Drop back to null state
}
| true |
a5745a861fce144fad9cc46ef6dbbba601a0af6e | C++ | SebastianMateo/sfmlgames | /Puralax/Puralax/Board.cpp | UTF-8 | 7,551 | 3.40625 | 3 | [
"MIT"
] | permissive | #include "Board.h"
#include <SFML/Graphics.hpp>
#include "Util.h"
#include <cmath>
#include <iostream>
void Node::propagate(Node::Color capturedColor, Node::Color propagatedColor, std::set<Node*> propagatedNodes)
{
//First we add to the set of propagated nodes
propagatedNodes.insert(this);
//Unless the color is the one of the captured, we stop
if (mColor != capturedColor)
return;
//We change the color and propagate to neighbor nodes
mColor = propagatedColor;
auto neighbors = mBoard->getNeighbors(this);
for (auto neighbor : neighbors)
{
if (propagatedNodes.find(neighbor) == propagatedNodes.end())
{
neighbor->propagate(capturedColor, propagatedColor, propagatedNodes);
}
}
}
bool Node::capture(Node *toNode)
{
if (toNode->getColor() == this->getColor())
return false;
if (toNode->getColor() == Node::Color::EMPTY)
{
//And we set as the current color the toNode
toNode->setColor(this->getColor());
//Then we set as empty the fromNode
this->setColor(Node::Color::EMPTY);
//We increase the amount of movements of the targeted node to the origin - 1 and the origin to 0
toNode->mAmount = mAmount - 1;
mAmount = 0;
}
else
{
//We need to know what the captured color was
auto capturedColor = toNode->getColor();
auto propagatedColor = this->getColor();
//And we set as the current color the toNode
toNode->setColor(propagatedColor);
//Create a set of all propagated nodes and add the toNode and fromNode
std::set<Node*> propagatedNodes;
propagatedNodes.insert(this);
propagatedNodes.insert(toNode);
//Check all neighbors that are the same color
auto neighbors = mBoard->getNeighbors(toNode);
for (auto neighbor : neighbors)
{
//If we didn't propated here, we propagate
if (propagatedNodes.find(neighbor) == propagatedNodes.end())
{
neighbor->propagate(capturedColor, propagatedColor, propagatedNodes);
}
}
//Decrease the number of movements
mAmount--;
}
return true;
}
Node::Color Node::parseColor(char color)
{
switch (color)
{
case 'E':
return Color::EMPTY;
case 'R':
return Color::RED;
case 'G':
return Color::GREEN;
case 'Y':
return Color::YELLOW;
case 'B':
return Color::BLUE;
case 'P':
return Color::PURPLE;
}
}
Node::Node(int x, int y, const char color, int amount, Board* board) : x(x), y(y), mAmount(amount), mBoard(board)
{
mColor = Node::parseColor(color);
}
Node::Node(int x, int y, Color color, int amount, Board* board) : x(x), y(y), mAmount(amount), mColor(color), mBoard(board) { }
//Level in format A,3A,B,C;D,A,C
/* Level Format
E: Empty
R: Red
G: Green
Y: Yellow
B: Blue
P: Purple
Example: "E,E,E;E,R3,E;E,G,E"
*/
Board::Board(const int size, const std::string level, const char winningColor) : mSize(size), map(size, std::vector<Node*>(size))
{
auto rows = Util::split(level, ";");
int i = 0;
for (std::string row : rows)
{
int j = 0;
auto tiles = Util::split(row, ",");
for (std::string tile : tiles)
{
int amount = 0;
if (tile.size() > 1)
{
amount = tile.at(1) - '0';
}
map[i][j] = new Node(i, j, tile.at(0), amount, this);
j++;
}
i++;
}
mWinningColor = Node::parseColor(winningColor);
}
Board::Board(const std::string fullLevel)
{
auto level = Util::split(fullLevel, "|");
auto rows = Util::split(level[1], ";");
int i = 0;
for (std::string row : rows)
{
int j = 0;
map.push_back(std::vector<Node*>());
auto tiles = Util::split(row, ",");
for (std::string tile : tiles)
{
int amount = 0;
if (tile.size() > 1)
{
amount = tile.at(1) - '0';
}
map[i].push_back(new Node(i, j, tile.at(0), amount, this));
j++;
}
i++;
}
mSize = rows.size();
mWinningColor = Node::parseColor(level[2].at(0));
}
Board::Board(const Board& board)
{
mSize = board.mSize;
mWinningColor = board.mWinningColor;
int i = 0;
for (auto row : board.map)
{
map.push_back(std::vector<Node*>());
for (auto node : row)
{
map[i].push_back(new Node(node->x, node->y, node->mColor, node->mAmount, this));
}
i++;
}
}
std::string Board::hash()
{
std::string hashString;
for (auto row : map)
{
for (auto node : row)
{
hashString.append(std::to_string(static_cast<int>(node->getColor())));
hashString.append(std::to_string(node->getAmount()));
}
}
return hashString;
}
std::list<Board::Movement> Board::getAvailableMovements()
{
std::list <Movement> availableMovements;
for (auto column : map)
{
for (auto node : column)
{
if (node->canMove())
{
//Check neighbors
auto neighbors = getNeighbors(node);
auto color = node->getColor();
for (auto neighbor : neighbors)
{
if (neighbor->getColor() != color)
{
availableMovements.push_back(Movement(node->x, node->y, neighbor->x, neighbor->y));
}
}
}
}
}
return availableMovements;
}
Board::~Board()
{
for (auto col : map)
{
for (auto cel : col)
{
delete cel;
}
}
}
bool Board::didWeWon()
{
for (auto col : map)
{
for (auto node : col)
{
//If the non empty are the same as the winning color
if (node->getColor() != mWinningColor && node->getColor() != Node::Color::EMPTY)
return false;
}
}
return true;
}
bool Board::didWeLost()
{
//We lost if we don't have at least one color of the winning color with movements
for (auto row : map)
{
for (auto node : row)
{
//If we have at least one with the winning color with movements, we haven't lost yet
if (node->getColor() == mWinningColor && node->getAmount() > 0)
return false;
}
}
return true;
}
bool Board::move(int fromX, int fromY, int toX, int toY)
{
//Check if the From node can move
Node *fromNode = map[fromX][fromY];
if (fromNode->canMove())
{
//Check that the other node is adjacent
if ( (abs(fromX - toX) == 1 && fromY - toY == 0 ) || (fromX - toX == 0 && abs(fromY - toY) == 1) )
{
//Capture the other node
Node *toNode = map[toX][toY];
return fromNode->capture(toNode);
}
}
return false;
}
std::vector<Node*> Board::getNeighbors(Node *node)
{
std::vector<Node*> neighbors;
if (node->x > 0)
neighbors.push_back(map[node->x - 1][node->y]);
if (node->y > 0)
neighbors.push_back(map[node->x][node->y - 1]);
if (node->x < mSize - 1)
neighbors.push_back(map[node->x + 1][node->y]);
if (node->y < mSize - 1)
neighbors.push_back(map[node->x][node->y + 1]);
return neighbors;
} | true |
84542cae371a5e8233f98e95e5b18343fd8e5a0f | C++ | allenck/DecoderPro_app | /libPr3/opath.cpp | UTF-8 | 9,376 | 2.5625 | 3 | [] | no_license | #include "opath.h"
#include "oblock.h"
#include "portal.h"
#include <QTimer>
#include "abstractturnout.h"
#include "warranttableaction.h"
//OPath::OPath(QObject *parent) :
// Path(parent)
//{
//}
/**
* Extends jmri.Path.
* An OPath is a route that traverses a Block from one boundary to another.
* The mBlock parameter of Path is used to reference the Block to which this OPath belongs.
* (Not a destination Block as might be inferred from the naming in Path.java)
* <P>
* An OPath inherits the List of BeanSettings for all the turnouts needed to traverse the Block.
* It also has references to the Portals (block boundary objects) through wich it enters or
* exits the block. One of these may be NULL, if the OPath dead ends within the block.
*
* @author Pete Cressman Copyright (C) 2009
*/
///*public*/ class OPath extends jmri.Path {
/**
* Create an object with default directions of NONE, and
* no setting element.
*/
/*public*/ OPath::OPath(Block* owner, QString name, QObject *parent)
: Path(owner, 0, 0, parent)
{
//super(owner, 0, 0);
common();
_name = name;
setObjectName(name);
}
/*public*/ OPath::OPath(Block* owner, int toBlockDirection, int fromBlockDirection, QObject *parent)
: Path(owner, toBlockDirection, fromBlockDirection, parent)
{
//super(owner, toBlockDirection, fromBlockDirection);
common();
}
/*public*/ OPath::OPath(Block* owner, int toBlockDirection, int fromBlockDirection, BeanSetting* setting, QObject *parent)
: Path(owner, toBlockDirection, fromBlockDirection, setting, parent)
{
//super(owner, toBlockDirection, fromBlockDirection, setting);
common();
}
///*public*/ OPath::OPath(QString name, OBlock* owner, Portal* entry, int fromBlockDirection,
// Portal* exit, int toBlockDirection, QObject *parent) : Path(owner, toBlockDirection, fromBlockDirection, parent)
/*public*/ OPath::OPath(QString name, OBlock* owner, Portal* entry, Portal* exit, QList<BeanSetting*> settings,QObject *parent) : Path(owner, 0, 0, parent)
{
//super(owner, 0, 0);
common();
_name = name;
setObjectName(name);
_fromPortal = entry;
_toPortal = exit;
if (!settings.isEmpty())
{
for (int i = 0; i < settings.size(); i++)
{
addSetting(settings.at(i));
}
}
if (log->isDebugEnabled())
{
log->debug("Ctor: name= " + name + ", block= " + owner->getDisplayName()
+ ", fromPortal= " + (_fromPortal == NULL ? "null" : _fromPortal->getName())
+ ", toPortal= " + (_toPortal == NULL ? "null" : _toPortal->getName()));
}
}
void OPath::common()
{
log = new Logger("OPath");
log->setDebugEnabled(true);
_timerActive = false;
_fromPortal = NULL;
_toPortal = NULL;
_listener = NULL;
}
//@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR")
// OPath ctor invokes Path ctor via super(), which calls this, before the internal
// _block variable has been set so that Path.getPath() can work. In this implementation,
// getPath() only controls whether log->debug(...) is fired, but this might change if/when
// super.setBlock(...) is changed, in which case this logic will fail.
/*public*/ void OPath::setBlock(Block* block)
{
if (getBlock()==block) { return; }
if (log->isDebugEnabled()) log->debug("OPath \""+_name+"\" changing blocks from "+
(getBlock()!=NULL ? getBlock()->getDisplayName() : NULL)+
" to "+(block!=NULL ? block->getDisplayName() : NULL)+".");
Path::setBlock(block);
}
/*protected*/ QString OPath::getOppositePortalName(QString name)
{
if (_fromPortal!=NULL && _fromPortal->getName()==(name))
{
if (_toPortal!=NULL)
{
return _toPortal->getName();
}
}
if (_toPortal!=NULL && _toPortal->getName()==(name))
{
if (_fromPortal!=NULL)
{
return _fromPortal->getName();
}
}
return NULL;
}
/*protected*/ bool OPath::validatePortals()
{
if (!_fromPortal->isValid())
{
return false;
}
return _toPortal->isValid();
}
/*public*/ void OPath::setName(QString name)
{
if (log->isDebugEnabled()) {
log->debug("OPath \"" + _name + "\" setName to " + name);
}
if (name == NULL || name.length() == 0)
{
return;
}
QString oldName = _name;
_name = name;
setObjectName(name);
OBlock* block = (OBlock*) getBlock();
block->pseudoPropertyChange("pathName", oldName, _name);
WarrantTableAction::pathNameChange(block, oldName, _name);
if (_fromPortal != NULL)
{
if (_fromPortal->addPath(this))
{
return;
}
}
if (_toPortal != NULL) {
_toPortal->addPath(this);
}
}
/*public*/ QString OPath::getName() { return _name; }
/*public*/ void OPath::setFromPortal(Portal* p)
{
if (log->isDebugEnabled() && p!=NULL) log->debug("OPath \""+_name+"\" setFromPortal= "+p->getName());
_fromPortal = p;
}
/*public*/ Portal* OPath::getFromPortal() { return _fromPortal; }
/*public*/ void OPath::setToPortal(Portal* p)
{
if (log->isDebugEnabled() && p!=NULL) log->debug("OPath \""+_name+"\" setToPortal= "+p->getName());
_toPortal = p;
}
/*public*/ Portal* OPath::getToPortal() { return _toPortal; }
/**
* Set path turnout commanded state and lock state
* @param delay following actions in seconds
* @param set when true, command turnout to settings, false don't set command - just do lock setting
* @param lockState set when lock==true, lockState unset when lock==false
* @param lock
* If lockState==0 setLocked() is not called. (lockState should be 1,2,3)
*/
/*public*/ void OPath::setTurnouts(int delay, bool set, int lockState, bool lock)
{
if(delay>0)
{
if (!_timerActive)
{
// Create a timer if one does not exist
if (_timer==NULL)
{
_listener = new OPTimeTurnout(this);
//_timer = new Timer(2000, _listener);
_timer = new QTimer();
//_timer.setRepeats(false);
_timer->setSingleShot(true);
}
_listener->setList(getSettings());
_listener->setParams(set, lockState, lock);
//_timer->setInitialDelay(delay*1000);
_timer->start(2000);
_timerActive = true;
connect(_timer, SIGNAL(timeout()), _listener, SLOT(actionPerformed()));
}
else
{
log->warn("timer already active for delayed turnout action on path "+toString());
}
}
else
{
fireTurnouts(getSettings(), set, lockState, lock);
}
}
void OPath::fireTurnouts(QList<BeanSetting*> list, bool set, int lockState, bool lock) {
for (int i=0; i<list.size(); i++) {
BeanSetting* bs = list.at(i);
Turnout* t = (Turnout*)bs->getBean()->self();
if (t==NULL) {
log->error("Invalid turnout on path "+toString());
} else {
if (set) {
((AbstractTurnout*)t)->setCommandedState(bs->getSetting());
}
if (lockState>0) {
((AbstractTurnout*)t)->setLocked(lockState, lock);
}
}
}
}
/*public*/ void OPath::dispose() {
if (_fromPortal!=NULL) { _fromPortal->removePath(this); }
if (_toPortal!=NULL) { _toPortal->removePath(this); }
}
/**
* Class for defining ActionListener for ACTION_DELAYED_TURNOUT
*/
//class TimeTurnout implements java.awt.event.ActionListener
//{
/*public*/ OPTimeTurnout::OPTimeTurnout(OPath* self ) {
this->self = self;
}
void OPTimeTurnout::setList(QList<BeanSetting*> l) {
list = l;
}
void OPTimeTurnout::setParams(bool s, int ls, bool l) {
set = s;
lockState = ls;
lock = l;
}
/*public*/ void OPTimeTurnout::actionPerformed(JActionEvent* event)
{
self->fireTurnouts(list, set, lockState, lock);
// Turn Timer OFF
if (self->_timer != NULL)
{
self->_timer->stop();
self->_timerActive = false;
}
}
//};
/*public*/ QString OPath::getDescription() {
return "\""+_name+"\""+(_fromPortal==NULL?"":" from portal "+_fromPortal->getName())+
(_toPortal==NULL?"":" to portal "+ _toPortal->getName());
}
/*public*/ QString OPath::toString()
{
return "OPath \""+_name+"\"on block "+(getBlock()!=NULL ? getBlock()->getDisplayName(): "NULL")+
(_fromPortal==NULL?"":" from portal "+_fromPortal->getName())+
(_toPortal==NULL?"":" to portal "+ _toPortal->getName());
}
/**
* override to disallow duplicate setting
*/
/*public*/ void OPath::addSetting(BeanSetting* t)
{
QListIterator<BeanSetting*> iter(getSettings());
while (iter.hasNext())
{
BeanSetting* bs = iter.next();
if (bs->getBeanName() == (t->getBeanName()))
{
log->error("TO setting for \"" + t->getBeanName() + "\" already set to " + QString::number(bs->getSetting()));
return;
}
}
Path::addSetting(t);
}
/**
* Override to indicate logical equality for use as paths in OBlocks.
*
*/
/*public*/ bool OPath::equals(OPath* path)
{
if (_fromPortal != NULL && _fromPortal != (path->getFromPortal()))
{
return false;
}
if (_toPortal != NULL && _toPortal != (path->getToPortal()))
{
return false;
}
if(_name != path->_name) // ACK I added this!
return false;
QListIterator<BeanSetting*> iter(path->getSettings());
while (iter.hasNext())
{
BeanSetting* beanSetting = iter.next();
QListIterator<BeanSetting*> it( getSettings());
while (it.hasNext())
{
BeanSetting* bs = it.next();
if ((bs->getBeanName().compare(beanSetting->getBeanName()) != 0))
{
return false;
}
if (bs->getSetting() != beanSetting->getSetting())
{
return false;
}
}
}
return true;
}
| true |
2dddf06bfebc9e7c9fee079232e7a669144a76b8 | C++ | rationalcoder/IceRunner | /src/icerunner/sound/soundmanager.cpp | UTF-8 | 1,804 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <thread>
#include <mutex>
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include "soundmanager.h"
namespace ice
{
namespace sound
{
bool SoundManager::Init()
{
if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0)
{
printf("failed to init audio\n");
goto fail1;
}
if (Mix_Init(MIX_INIT_OGG) == 0)
{
printf("failed to init OGG: %s\n", Mix_GetError());
goto fail2;
}
if (Mix_OpenAudio(44100, AUDIO_F32, 2, 1024))
{
printf("failed to open audio: %s\n", Mix_GetError());
goto fail3;
}
return true;
fail3:
Mix_Quit();
fail2:
SDL_QuitSubSystem(SDL_INIT_AUDIO);
fail1:
printf("failed to init the sound manager\n");
return false;
}
SoundManager::~SoundManager()
{
StopMusic();
Mix_CloseAudio();
Mix_Quit();
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
void SoundManager::Update()
{
// not doing anything in here after all...
}
void SoundManager::FadeOutMusic(uint16_t millis)
{
std::thread t([this, millis](){
Mix_FadeOutMusic(millis);
});
t.detach();
}
void SoundManager::FadeInMusic(Mix_Music* pMusic, uint16_t millis)
{
std::thread t([this, pMusic, millis](){
Mix_FadeInMusic(pMusic, 0, millis);
});
t.detach();
}
void SoundManager::StopMusic()
{
Mix_HaltMusic();
}
void SoundManager::PauseMusic()
{
Mix_PauseMusic();
}
void SoundManager::ResumeMusic()
{
Mix_ResumeMusic();
}
bool SoundManager::MusicIsPlaying()
{
return !!Mix_PlayingMusic();
}
bool SoundManager::MusicIsPaused()
{
return !!Mix_PausedMusic();
}
void SoundManager::SetMusicVolume(int volume)
{
Mix_VolumeMusic(volume);
}
int SoundManager::GetMaxVolume()
{
return MIX_MAX_VOLUME;
}
} // namespace sound
} // namespace ice
| true |
4517df1ab14a4d975e14b0dd7c0910fe51899ade | C++ | andyyhchen/cp-codes | /AC-codes/Q10018.cpp | UTF-8 | 401 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
unsigned long long int reverse(unsigned long long int i)
{
unsigned long long int ans=0;
while(i) ans*=10,ans+=i%10,i/=10;
return ans;
}
int main()
{
unsigned long long int N,P,tmp,c;
while(cin>>N)
while(N--&&cin>>P)
{
c=1;P+=reverse(P);
while(P!=reverse(P)) P+=reverse(P),c++;
cout<<c<<" "<<P<<"\n";
}
return 0;
}
| true |
f83bdfea780f81bfe79a68b80dc00dc28d347a0a | C++ | StephenBrownCS/cs740-xia | /SDL Example/sdl.cpp | UTF-8 | 6,916 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <SDL/SDL.h>
#include <time.h>
#include <cassert>
using namespace std;
SDL_Surface* initVideoDisplay();
void display_bmp(SDL_Surface* screen, const char *file_name);
void displayOverlay(SDL_Surface* screen);
void handle_theora_data(SDL_Surface* screen);
int main(){
SDL_Surface* screen = initVideoDisplay();
//display_bmp(screen, "blackbuck.bmp");
//displayOverlay(screen);
handle_theora_data(screen);
struct timespec tim, tim2;
tim.tv_sec = 10;
tim.tv_nsec = 500;
if(nanosleep(&tim, &tim2) < 0 ){
cerr << "Not happening bro" << endl;
return -1;
}
return 0;
}
SDL_Surface* initVideoDisplay(){
SDL_Surface *screen;
/* Initialize the SDL library */
if( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
fprintf(stderr,
"Couldn't initialize SDL: %s\n", SDL_GetError());
exit(1);
}
/* Clean up on exit */
atexit(SDL_Quit);
/*
* Initialize the display in a 640x480 8-bit palettized mode,
* requesting a software surface
*/
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
if ( screen == NULL ) {
fprintf(stderr, "Couldn't set 640x480x8 video mode: %s\n",
SDL_GetError());
exit(1);
}
return screen;
}
void display_bmp(SDL_Surface* screen, const char *file_name)
{
SDL_Surface *image;
/* Load the BMP file into a surface */
image = SDL_LoadBMP(file_name);
if (image == NULL) {
fprintf(stderr, "Couldn't load %s: %s\n", file_name, SDL_GetError());
return;
}
/*
* Palettized screen modes will have a default palette (a standard
* 8*8*4 colour cube), but if the image is palettized as well we can
* use that palette for a nicer colour matching
*/
if (image->format->palette && screen->format->palette) {
SDL_SetColors(screen, image->format->palette->colors, 0,
image->format->palette->ncolors);
}
/*
image = SDL_DisplayFormat(image);
if (image == NULL){
cerr << "Sorry, not happening bro" << endl;
return;
}
*/
/* Blit onto the screen surface */
if(SDL_BlitSurface(image, NULL, screen, NULL) < 0)
fprintf(stderr, "BlitSurface error: %s\n", SDL_GetError());
// SDL_UpdateRect doesn't work!
SDL_UpdateRect(screen, 0, 0, image->w, image->h);
// For some reason, we need to call SDL_Flip
SDL_Flip(screen);
//SDL_Delay(3000);
/* Free the allocated BMP surface */
SDL_FreeSurface(image);
}
void displayOverlay(SDL_Surface* screen){
SDL_Overlay* my_overlay = SDL_CreateYUVOverlay(640, 480, SDL_YV12_OVERLAY, screen);
if(my_overlay == NULL){
cerr << "Sorry Nick" << endl;
exit(-1);
}
/* Display number of planes */
printf("Planes: %d\n", my_overlay->planes);
/* Fill in video data */
char* y_video_data = new char[my_overlay->pitches[0]];
char* u_video_data = new char[my_overlay->pitches[1]];
char* v_video_data = new char[my_overlay->pitches[2]];
for(int i = 0; i < my_overlay->pitches[0]; i++){
y_video_data[i] = 0x10;
}
for(int i = 0; i < my_overlay->pitches[1]; i++){
u_video_data[i] = 0x80;
}
for(int i = 0; i < my_overlay->pitches[2]; i++){
v_video_data[i] = 0x80;
}
cout << "Unlock Baby!" << endl;
/* Fill in pixel data - the pitches array contains the length of a line in each plane */
SDL_LockSurface(screen);
int ret = SDL_LockYUVOverlay(my_overlay);
if (ret < 0){
cerr << "Couldn't lock!";
exit(-1);
}
memcpy(my_overlay->pixels[0], y_video_data, my_overlay->pitches[0]);
memcpy(my_overlay->pixels[1], u_video_data, my_overlay->pitches[1]);
memcpy(my_overlay->pixels[2], v_video_data, my_overlay->pitches[2]);
/* Draw a single pixel on (x, y)
*(my_overlay->pixels[0] + y * my_overlay->pitches[0] + x) = 0x10;
*(my_overlay->pixels[1] + y/2 * my_overlay->pitches[1] + x/2) = 0x80;
*(my_overlay->pixels[2] + y/2 * my_overlay->pitches[2] + x/2) = 0x80;
*/
SDL_UnlockSurface(screen);
SDL_UnlockYUVOverlay(my_overlay);
cout << "Createing Rectangle" << endl;
SDL_Rect video_rect;
video_rect.x = 0;
video_rect.y = 0;
video_rect.w = 640;
video_rect.h = 480;
SDL_Flip(screen);
cerr << "Flip Complete" << endl;
SDL_DisplayYUVOverlay(my_overlay, &video_rect);
SDL_Delay(3000);
delete[] y_video_data;
delete[] u_video_data;
delete[] v_video_data;
}
void handle_theora_data(SDL_Surface* screen) {
// If the return code is TH_DUPFRAME then we don't need to
// get the YUV data and display it since it's the same as
// the previous frame.
if (1/*ret == 0*/) {
// Create an SDL surface to display if we haven't
// already got one.
if (!screen) {
int r = SDL_Init(SDL_INIT_VIDEO);
assert(r == 0);
// This is the "window" that we display on
screen = SDL_SetVideoMode(560, //buffer[0].width,
320, //buffer[0].height,
0, //Bits per pixel
SDL_SWSURFACE);
assert(screen);
}
// Create a YUV overlay to do the YUV to RGB conversion
SDL_Overlay* mOverlay = NULL;
if (!mOverlay) {
// This is the thing we will be superimposing on our window
mOverlay = SDL_CreateYUVOverlay(560, //buffer[0].width,
320, //buffer[0].height,
SDL_YV12_OVERLAY,
screen);
assert(mOverlay);
}
/* Fill in video data */
char* y_video_data = new char[mOverlay->pitches[0]];
char* u_video_data = new char[mOverlay->pitches[1]];
char* v_video_data = new char[mOverlay->pitches[2]];
static SDL_Rect rect;
rect.x = 0;
rect.y = 0;
rect.w = 560;//buffer[0].width;
rect.h = 320;//buffer[0].height;
if( SDL_MUSTLOCK(screen) ){
if ( SDL_LockSurface(screen) < 0 ){
cerr << "Could not lock surface" << endl;
exit(-1);
}
}
// Copy each of the YUV buffer planes into mOverlay
memcpy(mOverlay->pixels[0], y_video_data, mOverlay->pitches[0]);
memcpy(mOverlay->pixels[1], u_video_data, mOverlay->pitches[1]);
memcpy(mOverlay->pixels[2], v_video_data, mOverlay->pitches[2]);
int x = 2;
int y = 0;
*(mOverlay->pixels[0] + y * mOverlay->pitches[0] + x) = 0x10;
*(mOverlay->pixels[1] + y/2 * mOverlay->pitches[1] + x/2) = 0x80;
*(mOverlay->pixels[2] + y/2 * mOverlay->pitches[2] + x/2) = 0x80;
if(SDL_MUSTLOCK(screen)){
SDL_UnlockSurface(screen);
}
SDL_UnlockYUVOverlay(mOverlay);
//SDL_Flip(mSurface);
SDL_DisplayYUVOverlay(mOverlay, &rect);
SDL_Delay(3000);
delete[] y_video_data;
delete[] u_video_data;
delete[] v_video_data;
}
}
| true |
cd4d83db7f20661741d6453bab1e7683c0732c52 | C++ | DionneLisaRoos/DroneSimulation | /DroneSimulator/DroneSimulator/LTexture.h | MacCentralEurope | 2,020 | 3.40625 | 3 | [] | no_license | //==============================================================
// Filename : LTexture.h
// Authors : Dionne Arins and Marnick Los.
// Version : -
// License : -
// Description : This function is used by the GUI and holds information about the texture of the loaded images.
//==============================================================
#pragma once
#include <SDL.h>
#include <string>
class LTexture
{
public:
LTexture() : mTexture(NULL), mWidth(0), mHeight(0), gRenderer(NULL) {}
~LTexture() {}
// Initialize renderer
void loadRenderer(SDL_Renderer& Renderer) {
gRenderer = &Renderer;
}
// Load image from file using the path as given by the input.
bool loadFromFile(std::string path) {
SDL_Texture* newTexture = NULL;
// Create surface for image and load the image from path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL) { printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); return false; }
// Create texture for image
newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
if (newTexture == NULL) { printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); return false; }
// Set the width and height of the image
mWidth = loadedSurface->w;
mHeight = loadedSurface->h;
// deallocate the loaded surface
SDL_FreeSurface(loadedSurface);
// Save the new texture
mTexture = newTexture;
// Return true when the file loading and creating the texture is done well
return true;
}
// deallocate the memory by destroying the texture and setting the variables to zero
void free() {
if (mTexture != NULL)
{
SDL_DestroyTexture(mTexture);
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
// Returns widht of the image
int getWidth() { return mWidth; }
// returns height of the image
int getHeight() { return mHeight; }
SDL_Texture* mTexture;
private:
// private object and variables
SDL_Renderer* gRenderer;
int mWidth;
int mHeight;
}; | true |
4f21dc1c0390059a1180ce99160b66be4eb17eb2 | C++ | Shtille/scythe | /src/math/common_math.cpp | UTF-8 | 3,929 | 3.078125 | 3 | [
"MIT"
] | permissive | #include "common_math.h"
#include <cmath>
namespace scythe {
float Sign(float x)
{
return (x < 0.0f) ? -1.0f : 1.0f;
}
static Vector3 ClosestPointOnLine(const Vector3& a, const Vector3& b, const Vector3& p)
{
Vector3 c = p - a;
Vector3 v = b - a;
float d = v.Length();
v *= 1.0f/d; // normalize
float t = v & c;
if (t < 0.0f)
return a;
if (t > d)
return b;
v *= t;
return (a + v);
}
Vector3 Orthogonalize(const Vector3& v1, const Vector3& v2)
{
Vector3 v2ProjV1 = ClosestPointOnLine(v1, -v1, v2);
Vector3 res = v2 - v2ProjV1;
res.Normalize();
return res;
}
float DistanceToCamera(const Vector3& world, const Matrix4& view)
{
Vector4 pos_eye = view * Vector4(world.x, world.y, world.z, 1.0f);
return Vector3(pos_eye.x, pos_eye.y, pos_eye.z).Length();
}
float DistanceToCamera(const Vector4& world, const Matrix4& view)
{
Vector4 pos_eye = view * world;
return Vector3(pos_eye.x, pos_eye.y, pos_eye.z).Length();
}
void WorldToScreen(const Vector4& world, const Matrix4& proj, const Matrix4& view,
const Vector4& viewport, Vector2 * screen)
{
// Step 1: 4d Clip space
Vector4 pos_clip = proj * view * world;
// Step 2: 3d Normalized Device Coordinate space
Vector3 pos_ndc = Vector3(pos_clip.x, pos_clip.y, pos_clip.z) / pos_clip.w;
// Step 3: Window Coordinate space
screen->x = (pos_ndc.x + 1.0f) * 0.5f * viewport.z + viewport.x;
screen->y = (pos_ndc.y + 1.0f) * 0.5f * viewport.w + viewport.y;
}
void ScreenToRay(const Vector2& screen, const Vector4& viewport,
const Matrix4& proj, const Matrix4& view, Vector3 * ray)
{
// Step 1: 3d Normalised Device Coordinates ( range [-1:1, -1:1, -1:1] )
Vector2 screen_ndc;
screen_ndc.x = 2.0f * (screen.x - viewport.x) / viewport.z - 1.0f;
screen_ndc.y = 2.0f * (screen.y - viewport.y) / viewport.w - 1.0f;
// We don't need z component actually
// Step 2: 4d Homogeneous Clip Coordinates ( range [-1:1, -1:1, -1:1, -1:1] )
Vector4 ray_clip(
screen_ndc.x,
screen_ndc.y,
-1.0, // We want our ray's z to point forwards - this is usually the negative z direction in OpenGL style.
1.0
);
// Step 3: 4d Eye (Camera) Coordinates ( range [-x:x, -y:y, -z:z, -w:w] )
Matrix4 inversed_proj;
proj.Invert(&inversed_proj);
Vector4 ray_eye = inversed_proj * ray_clip;
// Now, we only needed to un-project the x,y part, so let's manually set the z,w part to mean "forwards, and not a point".
ray_eye.z = -1.0f;
ray_eye.w = 0.0f;
// Step 4: 4d World Coordinates ( range [-x:x, -y:y, -z:z, -w:w] )
//ray = (view.GetInverse() * ray_eye).xyz();
Matrix4 inversed_view;
view.Invert(&inversed_view);
inversed_view.TransformVector(Vector3(ray_eye.x, ray_eye.y, ray_eye.z), ray);
ray->Normalize();
}
bool RaySphereIntersection(const Vector3& origin, const Vector3& direction,
const Vector3& center, float radius, Vector3 * intersection)
{
Vector3 line = origin - center;
float b = (direction & line);
float c = (line & line) - radius * radius;
float D = b * b - c;
if (D < 0.0f) // ray cannot intersect sphere
return false;
float t;
if (c > 0.0f) // origin is outside of sphere, choose closer hitpoint
t = -b - sqrtf(D);
else // origin is inside the sphere, choose forward hitpoint
t = -b + sqrtf(D);
if (t > 0.0f)
{
if (intersection)
*intersection = origin + t * direction;
return true;
}
else
return false;
}
bool RayPlaneIntersection(const Vector3& origin, const Vector3& direction,
const Vector4& plane, Vector3 * intersection)
{
float denom = direction.x * plane.x + direction.y * plane.y + direction.z * plane.z;
if (denom > 0.001f || denom < -0.001f)
{
if (intersection)
{
float t = -(origin.x * plane.x + origin.y * plane.y + origin.z * plane.z + plane.w)
/ denom;
*intersection = origin + t * direction;
}
return true;
}
else
return false;
}
} // namespace scythe | true |
f8f58bb85e2894f828d663bf8e5064d8398aa9a1 | C++ | udp-codes/resolucion-control-2-AlejandroPacheco | /alejandro-pacheco.cpp | UTF-8 | 2,221 | 3.015625 | 3 | [] | no_license | #include <iostream>
using namespace std;
//problema 1
class data{
public:
string data
data *netx;
data(){}
};
class TDA{
public:
TDA(){}
void insert(data x){}
data delete(){}
bool isempty(){}
};
class conjunto{
public:
TDA head;
conjunto(){}
void agregar(){
void insert(data x)
}
data sacar(){
data delete()
}
bool estaVacio(){
bool isempty()
}
bool pertenece(data x){
if(estaVacio())
return false;
else{
TDA *aux = head;
while(aux -> sacar() != x){
if(aux -> estaVacio()){
return false;
}
aux = aux ->sacar();
}
return true;
}
}
conjunto interseccion(conjunto c){
conjunto *aux = c;
conjunto *nuevo = new conjunto();
data *aux2 = aux ->sacar();
while(true){
if(aux -> estaVacio() == true){
break;
}
if(pertenece(aux2) == true){
nuevo ->agregar(aux2);
}else{
aux2 = aux->sacar();
continue;
}
return *nuevo;
}
}
void intersecta(conjunto c){
conjunto *aux = c;
data *aux2 = aux ->sacar();
while(true){
if(aux -> estaVacio() == true){
break;
}
if(pertenece(aux2) == false){
aux2 = aux->sacar();
continue;
}
}
}
conjunto union(conjunto c){
conjunto *aux = c;
conjunto *nuevo = new conjunto();
data *aux2 = aux ->sacar();
while(true){
if(aux -> estaVacio() == true){
break
}
if(pertenece(aux2) == true){
nuevo ->agregar(aux2);
}else{
nuevo ->agregar(aux2);
continue;
}
return *nuevo;
}
}
void une(conjunto c){
conjunto *aux = c;
conjunto *nuevo = new conjunto();
data *aux2 = aux ->sacar();
while(true){
if(aux -> estaVacio() == true){
break
}
if(pertenece(aux2) == false){
aux ->agregar(aux2);
}
}
}
};
//problema 2
class Item{
public:
string valor;
int cant_llamados;
void agregar(Item i){
if(estavacio()){
head = new Item();
}
else {
Item *aux = new Item();
aux -> sig = head;
head = aux;
}
}
int probabilidad(string valor){
if(estavacio()){
return false;
}
else{
Item *aux = head;
int P = 0;
int Q = 0;
while(aux!=NULL){
Q = Q+1;
if(aux->data == valor){
P=P+1;
}
else {
aux = aux->sig;
}
}
}
Int R= (P/Q)*100;
return R;
}
};
| true |
402b9f9a0ee659b2bdb4c5902800816291026aa9 | C++ | kbadillou/IDS6938-SimulationTechniques | /Discrete2/random.cpp | UTF-8 | 4,171 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #define _USE_MATH_DEFINES //for C++ Referenceshttps://msdn.microsoft.com/en-us/library/4hwaceh6.aspxhttp://www.cplusplus.com/forum/general/102410/
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <vector>
#include <chrono>
#include <fstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cmath> //referencehttp://www.cplusplus.com/reference/cmath/
int main()
{
// Get a random seed
//use a random device
std::random_device rd;
// 1) Change random number generators
//std::mt19937_64 engine(rd()); //Marsenne Twister
//std::knuth_b engine(rd()); //Knuth-B
//std::minstd_rand engine(rd()); //Minimal Standard
std::ranlux48 engine(rd()); //Ranlux
// Another seed intialization routine (this is just here for future reference for you.)
// initialize the random number generator with time-dependent seed
//uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
//std::seed_seq ss{ uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed >> 32) };
//std::mt19937_64 e2;
//e2.seed(ss);
// 2) - Change distribution types
std::uniform_real_distribution<> dist(0,100); // example of a uniform real distribution
//std::normal_distribution<> dist(5,2); // example of a normal distribution
//std::uniform_int_distribution<> dist(0,100); // example of uniform discrete distribution
//std::poisson_distribution<> dist(5); // example of poisson distribution
//std::exponential_distribution<> dist(5); //example of exponential distribution
auto generator = std::bind(dist, engine);
// 3) Play with N
unsigned int N = 1000; // number of values generated
double randomValue;
double rX;
double rY;
double q;
double range;
std::map<int, int> hist; //Counts of discrete values
//std::vector<double> raw; //raw random values
std::vector<double> rawX;
std::vector<double> rawY;
for (unsigned int i = 0; i < N; ++i) {
randomValue = generator();
//rX = generator(); //x coordinate
//rY = generator(); //y coordinate
//Unit circle code
q = generator() * (M_PI * 2);
range = sqrt(randomValue);
rX = (1.0 * range) * cos(q);
rY = (1.0 * range) * sin(q);
//Original Code:
//++hist[std::round(randomValue)]; // count the values
//raw.push_back(randomValue); //push the raw values
rawX.push_back(rX);
rawY.push_back(rY);
}
//for (auto p : hist) {
// Uncomment if you want to see the values
//std::cout << std::fixed << std::setprecision(1) << std::setw(2)
//<< p.first << " - "<< p.second << std::endl;
//std::cout << std::fixed << std::setprecision(1) << std::setw(2)
//<< p.first << " " << std::string(p.second / (N/500), '*') << std::endl;
// Print Results to File
/*
std::ofstream myfile;
myfile.open("mersenne_uniform_int_histogram.txt");
for (auto p : hist) {
myfile << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << "," << p.second << std::endl;
}
myfile.close();
*/
//for (auto p : rawX) {
// Uncomment if you want to see the values
//std::cout << std::fixed << std::setprecision(1) << std::setw(2)
//<< p << " - " << std::endl;
//}
std::ofstream myfile;
myfile.open("circle_ranlux_X.txt");
for (auto p : rawX) {
myfile << std::fixed << std::setprecision(5) << std::setw(2)
<< p << std::endl;
}
myfile.close();
myfile.open("circle_ranlux_Y.txt");
for (auto p : rawY) {
myfile << std::fixed << std::setprecision(5) << std::setw(2)
<< p << std::endl;
}
myfile.close();
//if you choose to write useful stats here
/*
myfile.open("mersenne_uniform_int__stats.txt");
double sum = std::accumulate(raw.begin(), raw.end(), 0.0);
double mean = sum / raw.size();
myfile << "mean: " << mean << std::endl;
std::cout << "mean: " << mean << std::endl;
std::vector<double> diff(raw.size());
std::transform(raw.begin(), raw.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / raw.size());
myfile << "stdev: " << stdev << std::endl;
std::cout << "stdev: " << stdev << std::endl;
myfile.close();
*/
}
| true |
88b1844bf70257bc04e26ef3c27b320c910c4f87 | C++ | Manojbhat09/graph_map_search | /SearchBase.h | UTF-8 | 561 | 2.703125 | 3 | [] | no_license | /*
* (C) 2014 Douglas Sievers
*
* SearchBase.h
*/
#ifndef SEARCH_BASE_H
#define SEARCH_BASE_H
#include "Node.h"
#include "Graph.h"
using namespace std;
// Enum for search status
//
enum SearchStatus { FAILURE, SEARCHING, SUCCESS };
class SearchBase
{
public:
// Constructor
//
SearchBase(Graph&);
// public utility functions
//
virtual void search(const int, const int) = 0;
void printSolution() const;
protected:
nodePtr initialNodePtr;
nodePtr goalNodePtr;
Graph& graph;
};
#endif /* SEARCH_BASE_H */ | true |
8da142e8fb51eedbaec8024499beb39a86ddf182 | C++ | marobright/RubicksCube | /cubeClass.h | UTF-8 | 999 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <string>
class Square
{
std::string colour;
public:
Square(){y = 5;}
void printColour();
int x;
int y;
};
void Square::printColour()
{
std::cout << colour << std::endl;
};
//#########################################################################
class Face
{
std::string side;
public:
Square squares[9];
void printSide();
void initColour(char colour);
};
void Face::printSide()
{
for(int i=0; i < 9; i++)
{
std::cout << squares[i].y << std::endl;
};
};
void Face::initColour(char colour)
{
for(int i=0; i < sizeof(squares); i++)
{
this->squares[i].y = i;
};
};
//#########################################################################
class Cube
{
std::string cube;
public:
//Cube();
Face faces[6];
void printCube();
};
void Cube::printCube()
{
std::cout << cube << std::endl;
};
//Cube::Cube()
//{
//};
| true |
f6d0795c261d595d27f0564acb8051272bdab484 | C++ | daoc-distrapp/OpenCL_AddArrays | /OpenCL_AddArrays/host.cpp | ISO-8859-1 | 3,599 | 2.9375 | 3 | [] | no_license |
#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
cl_int length = 1024;
//cl_int length = 1 << 20;
// Crea el contexto para una GPU
cl_context context = clCreateContextFromType(NULL, CL_DEVICE_TYPE_GPU, NULL, NULL, NULL);
// Obtiene el dispositivo
cl_device_id device;
clGetContextInfo(context, CL_CONTEXT_DEVICES, sizeof(cl_device_id), &device, NULL);
// Crea la cola de comandos (cola para las kernels)
cl_command_queue commandQueue;
commandQueue = clCreateCommandQueueWithProperties(context, device, NULL, NULL);
// Crea los buffer en el host, para los datos de entrada
cl_int* inputA = (cl_int*)malloc(sizeof(cl_int) * length);
cl_int* inputB = (cl_int*)malloc(sizeof(cl_int) * length);
// Inicializa los buffer del host con los valores de entrada
for (cl_int i = 0; i < length; i++) {
inputA[i] = i; //0,1,2,...,1023
inputB[i] = length - i; //1023,1022,...,0
}
// Crea los buffer en la GPU, tanto para valores de entrada como para valores de salida
cl_mem gpuBuffer_A = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(cl_int) * length, NULL, NULL);
cl_mem gpuBuffer_B = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(cl_int) * length, NULL, NULL);
cl_mem gpuBuffer_C = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(cl_int) * length, NULL, NULL);
// Copia los valores de entrada desde los buffer del host a los buffer de la GPU
clEnqueueWriteBuffer(commandQueue, gpuBuffer_A, CL_TRUE, 0, sizeof(cl_int) * length, inputA, 0, NULL, NULL);
clEnqueueWriteBuffer(commandQueue, gpuBuffer_B, CL_TRUE, 0, sizeof(cl_int) * length, inputB, 0, NULL, NULL);
// Lee el cdigo fuente de la kernel desde el archivo
char* source = NULL;
size_t sourceSize = 0;
FILE* fp = NULL;
fopen_s(&fp, "AddArraysKernel.cl", "rb");
fseek(fp, 0, SEEK_END);
sourceSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
source = new char[sourceSize];
fread(source, 1, sourceSize, fp);
// Crea el programa OpenCL y lo compila, a partir del cdigo fuente de la kernel
cl_program program = clCreateProgramWithSource(context, 1, (const char**)&source, &sourceSize, NULL);
clBuildProgram(program, 1, &device, "", NULL, NULL);
// Crea la kernel que se va a ejecutar, a partir del programa ya compilado
cl_kernel kernel = clCreateKernel(program, "addArrays", NULL);
// Pasa los argumentos a la kernel
clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&gpuBuffer_A);
clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&gpuBuffer_B);
clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&gpuBuffer_C);
// Ejecuta la kernel
size_t localSize = 64; //tamao del bloque de ejecucin
size_t globalSize = length; //nmero total de threads a ejecutar
clEnqueueNDRangeKernel(commandQueue, kernel, 1, NULL, &globalSize, &localSize, 0, NULL, NULL);
clFinish(commandQueue);
// Recupera el resultado desde la GPU y lo pone en un buffer del host
cl_int* outputC = (cl_int*)malloc(sizeof(cl_int) * length);
clEnqueueReadBuffer(commandQueue, gpuBuffer_C, CL_TRUE, 0, sizeof(cl_int) * length, outputC, 0, NULL, NULL);
// Presenta el resultado (si es menor o igual a 1024)
if (length <= 1024) {
for (cl_uint i = 0; i < length; i++) {
printf("Resultados %d: (%d + %d = %d)\n", i, inputA[i], inputB[i], outputC[i]);
}
}
printf("Listo con talla %d !!!\n", length);
// Libera los recursos
delete[] source;
clReleaseProgram(program);
clReleaseContext(context);
clReleaseMemObject(gpuBuffer_A);
clReleaseMemObject(gpuBuffer_B);
clReleaseMemObject(gpuBuffer_C);
free(inputA);
free(inputB);
free(outputC);
// Fin !!!
system("pause");
return 0;
} | true |
1e0de3e3740e9e6cc4a8b6cb84513a44cff4e44b | C++ | sabrine-gamdou/PersonalPlanner | /PersonalPlanner/task.cpp | UTF-8 | 1,932 | 3.140625 | 3 | [] | no_license | #include "task.h"
Task::Task(int t_taskID, QString t_title, QDate t_date, int t_importance, QString t_username) :
m_taskID(t_taskID), m_title(t_title), m_date(t_date), m_importance(t_importance), m_username(t_username)
{
}
Task::~Task(){
}
int Task::taskID() const{
return m_taskID;
}
void Task::setTaskID(int taskID){
m_taskID = taskID;
}
QString Task::title() const{
return m_title;
}
void Task::setTitle(const QString &title){
m_title = title;
}
QDate Task::date() const{
return m_date;
}
void Task::setDate(const QDate &date){
m_date = date;
}
QString Task::description() const{
return m_description;
}
void Task::setDescription(const QString &description){
m_description = description;
}
int Task::importance() const{
return m_importance;
}
void Task::setImportance(int importance){
m_importance = importance;
}
QString Task::status() const{
return m_status;
}
void Task::setStatus(const QString &status){
m_status = status;
}
QString Task::repetition() const{
return m_repetition;
}
void Task::setRepetition(const QString &repetition){
m_repetition = repetition;
}
QString Task::username() const{
return m_username;
}
void Task::setUsername(const QString &username){
m_username = username;
}
/*! \brief For us to see in console*/
QString Task::toString(){
QString string;
string.append("TaskID: ");
string.append(QString::number(m_taskID));
string.append("\nTitle: ");
string.append(m_title);
string.append("\nDescription: ");
string.append(m_description);
string.append("\nImportance: ");
string.append(QString::number(m_importance));
string.append("\nStatus: ");
string.append(m_status);
string.append("\nDate: ");
string.append(m_date.toString("dd.MM.yyyy"));
string.append("\nRepetition: ");
string.append(m_repetition);
return string;
}
| true |
49bbf0509653bb1d9eedb4c9058bce944446516e | C++ | ivigns/parallel-game-of-life | /gol-pthread/multithreading_utils.cpp | UTF-8 | 3,112 | 2.84375 | 3 | [] | no_license | #pragma once
#include "multithreading_utils.hpp"
// ReaderWriterLock
void ReaderWriterLock::ReaderLock() {
std::unique_lock<std::mutex> lock(mutex_);
if (waiting_threads_.empty() && (lock_state_ == RWLockState::Unlocked ||
lock_state_ == RWLockState::Reader)) {
lock_state_ = RWLockState::Reader;
++readers_acquired_lock_count_;
return;
}
std::condition_variable cond_var;
std::condition_variable* cond_var_ptr = &cond_var;
waiting_threads_.push(std::make_pair(cond_var_ptr,
RWLockState::Reader));
while ((lock_state_ != RWLockState::Unlocked &&
lock_state_ != RWLockState::Reader) ||
cond_var_ptr != waiting_threads_.front().first) {
cond_var.wait(lock);
}
waiting_threads_.pop();
lock_state_ = RWLockState::Reader;
++readers_acquired_lock_count_;
// Будим всех спящих читателей.
if (!waiting_threads_.empty() &&
waiting_threads_.front().second == RWLockState::Reader) {
waiting_threads_.front().first->notify_one();
}
}
void ReaderWriterLock::ReaderUnlock() {
std::lock_guard<std::mutex> lock(mutex_);
--readers_acquired_lock_count_;
if (readers_acquired_lock_count_ == 0) {
lock_state_ = RWLockState::Unlocked;
if (!waiting_threads_.empty()) {
waiting_threads_.front().first->notify_one();
}
}
}
void ReaderWriterLock::WriterLock() {
std::unique_lock<std::mutex> lock(mutex_);
if (waiting_threads_.empty() && lock_state_ == RWLockState::Unlocked) {
lock_state_ = RWLockState::Writer;
return;
}
std::condition_variable cond_var;
std::condition_variable* cond_var_ptr = &cond_var;
waiting_threads_.push(std::make_pair(cond_var_ptr,
RWLockState::Writer));
while (lock_state_ != RWLockState::Unlocked ||
cond_var_ptr != waiting_threads_.front().first) {
cond_var.wait(lock);
}
waiting_threads_.pop();
lock_state_ = RWLockState::Writer;
}
void ReaderWriterLock::WriterUnlock() {
std::lock_guard<std::mutex> lock(mutex_);
lock_state_ = RWLockState::Unlocked;
if (!waiting_threads_.empty()) {
waiting_threads_.front().first->notify_one();
}
}
// CyclicBarrier
void CyclicBarrier::PassThrough() {
std::unique_lock<std::mutex> lock(mutex_);
--num_threads_;
bool current_barrier_state = barrier_state_;
while (current_barrier_state == barrier_state_ && num_threads_ != 0) {
all_threads_entered_.wait(lock);
}
if (current_barrier_state == barrier_state_) {
barrier_state_ = !barrier_state_;
num_threads_ = capacity_;
{
std::unique_lock<std::mutex> outer_lock(outer_mutex_);
permission_ = false;
all_threads_stopped_.notify_one();
while (!permission_) {
all_threads_stopped_.wait(outer_lock);
}
}
all_threads_entered_.notify_all();
}
}
bool CyclicBarrier::ResizeBarrier(const size_t new_capacity) {
std::unique_lock<std::mutex> lock(mutex_);
if (num_threads_ < capacity_) { // Барьер используется.
return false;
}
num_threads_ = capacity_ = new_capacity;
return true;
} | true |
82c45e6d007f5a1e2adcedea32dba7030f038baf | C++ | perandersson/playstate2 | /core/filesystem/win32/Win32Directory.cpp | UTF-8 | 1,877 | 2.9375 | 3 | [] | no_license | #include "../../Memory.h"
#include "Win32Directory.h"
#include "Win32FileSystem.h"
#include <cassert>
using namespace core;
Win32Directory::Win32Directory(const Win32FileSystem& fileSystem, const std::string& path)
: mFileSystem(fileSystem), mPath(path), mDirectoryHandle(NULL)
{
}
Win32Directory::Win32Directory(const Win32FileSystem& fileSystem, HANDLE handle, const std::string& path)
: mFileSystem(fileSystem), mPath(path), mDirectoryHandle(handle)
{
}
Win32Directory::~Win32Directory()
{
if(mDirectoryHandle != NULL) {
CloseHandle(mDirectoryHandle);
mDirectoryHandle = NULL;
}
mPath.clear();
}
std::vector<std::shared_ptr<IFile>> Win32Directory::GetFiles() const
{
assert_not_implemented();
std::vector<std::shared_ptr<IFile>> files;
/*WIN32_FIND_DATAA ffd;
HANDLE fileHandle = INVALID_HANDLE_VALUE;
fileHandle = FindFirstFileA(mPath.c_str(), &ffd);
if(fileHandle == INVALID_HANDLE_VALUE) {
return files;
}
do {
files.push_back(ffd.cFileName);
} while(FindNextFileA(fileHandle, &ffd) != 0);
FindClose(fileHandle);*/
return files;
}
std::vector<std::shared_ptr<IDirectory>> Win32Directory::GetDirectories() const
{
assert_not_implemented();
std::vector<std::shared_ptr<IDirectory>> directories;
return directories;
}
std::shared_ptr<IFile> Win32Directory::OpenFile(const std::string& path) const
{
std::string fullPath = path;
if (mFileSystem.IsRelative(path)) {
fullPath = mPath + "/" + path;
}
return mFileSystem.OpenFile(fullPath);
}
std::shared_ptr<IDirectory> Win32Directory::OpenDirectory(const std::string& path) const
{
std::string fullPath = path;
if(mFileSystem.IsRelative(path)) {
fullPath = mPath + path;
}
return mFileSystem.OpenDirectory(fullPath);
}
const std::string& Win32Directory::GetAbsolutePath() const
{
return mPath;
}
bool Win32Directory::Exists() const
{
return mDirectoryHandle != NULL;
}
| true |
e28eaab4cb8c49f4999a3b5849a2a4e2b79137de | C++ | V0G3L/USSHCSR04 | /USSHCSR04/USSHCSR04.cpp | UTF-8 | 683 | 2.75 | 3 | [
"MIT"
] | permissive | #include "USSHCSR04.h"
// Constructors ////////////////////////////////////////////////////////////////
USSHCSR04::USSHCSR04(unsigned char echoPin, unsigned char trigPin)
{
//Pin map
_trigPin = trigPin;
_echoPin = echoPin;
}
// Public Methods //////////////////////////////////////////////////////////////
void USSHCSR04::init()
{
// Define pinMode for the pins
pinMode(_echoPin,OUTPUT);
pinMode(_trigPin,INPUT);
}
/*
*
* measure and return the time in ms that the sound needs to come back
*/
int USSHCSR04::measure()
{
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return pulseIn(_echoPin, HIGH);
}
| true |
c2d23291f315af0d1f133a5c93a8dd6cdc9b19f4 | C++ | andrinux/MOOC-Courses | /DS-Cpp/Practice/Q6-ZigZag.cpp | UTF-8 | 943 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
//Brute Force.
//This is absolutely wrong because of numRows would be 1
//if ((i + 1) % (numRows-1) == 0)
// flag = flag*(-1);
//Corner case is when numRows == 1;
string convert(string s, int numRows) {
//Edge cases.
if (numRows == 1 || numRows >= s.size())
return s;
//general case.
vector<string> store(numRows);
int flag = 1;
int N = s.size();
int idx = -1;
for (int i = 0; i < N; i++){
if (idx == (numRows - 1)) flag = -1;
if (idx == 0) flag = 1; //this line should be after the first line.
//cout << flag << " ";
idx = idx + flag;
store[idx].push_back(s[i]);
}
string res;
for (int i = 0; i < numRows; i++){
res = res + store[i];
}
return res;
}
};
int main()
{
Solution so;
string in = "PAYPALISHIRING";
cout << endl<< so.convert(in, 3);
return 1;
} | true |
2d2475b4aa5d0b9f489b5baed463d840878db997 | C++ | Intel-out-side/AtCoder | /ABC166/c.cpp | UTF-8 | 3,590 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll N, M;
vector<ll> H;
class DFS {
public:
// グラフの隣接リスト表現
using Graph = vector<vector<ll>>;
// ith node is visited -> true, not visted -> false
vector<bool> seen;
// ith node belongs to jth group
vector<ll> ids;
// ith group's size
vector<ll> size_of_id;
// edges from ith node
vector<ll> deg;
// ノードの数
ll num_of_nodes;
// 隣接リスト表現のリスト
Graph G;
vector<bool> is_good_peak;
DFS(ll n) {
num_of_nodes = n;
G = vector<vector<ll>>(num_of_nodes);
seen = vector<bool>(num_of_nodes, false);
ids = vector<ll>(num_of_nodes, -1);
size_of_id = vector<ll>(num_of_nodes, 0);
deg = vector<ll>(num_of_nodes, 0);
color = vector<ll>(num_of_nodes, WHITE);
is_good_peak = vector<bool>(num_of_nodes, true);
}
Graph get_graph() { return G; }
bool is_seen(ll ith_node) { return seen[ith_node]; }
ll get_id_of(ll ith_node) { return ids[ith_node]; }
ll get_deg_of(ll ith_node) { return deg[ith_node]; }
ll get_size_of_id(ll id) { return size_of_id[id]; }
vector<bool> get_good_peaks() {return is_good_peak;}
void graph_init(ll m) {
for (ll i = 0; i < m; i++) {
ll a, b;
cin >> a >> b;
a--; b--; //入力が1オリジンの場合
/*無向グラフの場合、例えば(5,8),(8,5)は重複するクエリなので片方を弾く*/
//vector<ll>::iterator itr1, itr2;
auto itr1 = find(G[a].begin(), G[a].end(), b);
auto itr2 = find(G[b].begin(), G[b].end(), a);
if (itr1 == G[a].end() && itr2 == G[b].end()) {
G[a].push_back(b); G[b].push_back(a); //重複を許さない
deg[a]++; deg[b]++;
}
/*有効グラフなら下記を使う*/
//G[a].push_back(b); deg[a]++;
//G[b].push_back(a); deg[b]++; // 無向グラフなら双方に足す
}
}
void dfs(ll v, ll id) {
seen[v] = true;
ids[v] = id;
size_of_id[id]++;
// 次に訪問できる
for (ll next_v : G[v]) {
if (seen[next_v]) continue;
dfs(next_v, id);
}
}
void dfs(ll v, ll tgt_h, ll tgt_num) {
seen[v] = true;
if (H[v] >= tgt_h && (v != tgt_num)) is_good_peak[tgt_num] = false;
for (ll next_v : G[v]) {
if (seen[next_v]) continue;
dfs(next_v, tgt_h, tgt_num);
}
}
/*
@param v : starting node
@param id : grouping each node by id.
*/
void stack_dfs(ll v, ll id) {
stack<ll> s;
s.push(v);
while (!s.empty()) {
ll now = s.top();
ll next_node = next_visit(now);
bool isCompleted = true;
if (next_node >= 0) {
isCompleted = !isCompleted;
s.push(next_node);
color[next_node] = GRAY;
}
if (isCompleted) {
color[now] = BLACK;
if (ids[now] == -1) {
ids[now] = id;
size_of_id[id]++;
}
seen[now] = true;
s.pop();
}
}
}
private:
const ll WHITE = 0;
const ll GRAY = 1;
const ll BLACK = 2;
vector<ll> color;
ll next_visit(ll now) {
for (ll adjacent_node : G[now]) {
if (color[adjacent_node] == WHITE) return adjacent_node;
}
return -1;
}
};
int main() {
cin >> N >> M;
H = vector<ll>(N);
for (ll i = 0; i < N; i++) cin >> H[i];
DFS d = DFS(N);
d.graph_init(M);
for (ll i = 0; i < N; i++) {
d.dfs(i, H[i], i);
}
vector<bool> is_good_peak = d.get_good_peaks();
ll ans = 0;
for (bool item : is_good_peak) {
if (item) ans++;
}
cout << ans << endl;
return 0;
}
| true |
c6595726eec1336c8d81776fad46ea90ca1c1ff8 | C++ | shimon0505004/Leetcode | /634_FindTheDerangementOfAnArray.cpp | UTF-8 | 692 | 3.21875 | 3 | [] | no_license | /*
shimon0505004
634. Find the Derangement of An Array
https://leetcode.com/problems/find-the-derangement-of-an-array/
*/
class Solution {
public:
int findDerangement_UsingOnSpace(int n)
{
vector<int> dearrangementNumber(n,0);
if(n>1)
{
dearrangementNumber[1] = 1;
for(int index=2;index<n;index++)
{
dearrangementNumber[index] = ((index) * (dearrangementNumber[index-1] + dearrangementNumber[index-2])) % 1000000007;
}
return dearrangementNumber[n-1];
}
return 0;
}
int findDerangement(int n) {
return findDerangement_UsingOnSpace(n);
}
}; | true |
54e1fa41999279d701ee2990a5f20ad165ae63de | C++ | BoxBy/Cpp | /20191219(Final-Exam)/Problem_2/Problem_2/Board.h | UTF-8 | 697 | 2.96875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <time.h>
using namespace std;
class Board {
private:
char data[15][15];
string direction[20];
int location[20][2];
public:
Board();
char getSpot(int row, int col);
void setSpot(char val, int row, int col);
string getDir(int i);
void setDir(string dir, int i);
int getLoc(int i, int j);
void setLoc(int val, int i, int j);
void placeList(vector<string>& list);
void printBoard(vector<string>& list);
string Anagram(string dir);
char isCorrect(string dir, int row, int col);
bool isHor(string dir, int row, int col);
void push(string dir, string str, int row, int col, int count);
};
| true |
6b97d61a12bb53d1b26c88f372eea70438d230ee | C++ | face4/AtCoder | /ABC/145/B.cpp | UTF-8 | 342 | 2.828125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n;
string s;
cin >> n >> s;
if(n%2){
cout << "No" << endl;
return 0;
}
for(int i = 0; i < n/2; i++){
if(s[i] != s[n/2+i]){
cout << "No" << endl;
return 0;
}
}
cout << "Yes" << endl;
return 0;
} | true |
07e27b814bafff8d270ec3445f917b29d691b0b6 | C++ | MasterWangdaoyong/My-C--Primer-Plus | /Learn/程序清单 5-10-01.cpp | UTF-8 | 361 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <string>
int main()
{
using namespace std;
int i = 0;
int x[5] = {1,2,3,4,5} ;
int y[5] = {11,12,13,14,4};
while (x[i] != y[4])
{
cout << x[i] << endl;
i++;
}
cout << "Doing it dangerously wrong: " << x[i] << endl;
return 0;
}
| true |
7225a02fcbe6c4837d0a57fefe9f64d42c1c33b1 | C++ | robert-porter/Airplane | /OpenGLApp/StraightPathMovementComponent.h | UTF-8 | 428 | 2.625 | 3 | [] | no_license | #pragma once
#include "stdincludes.h"
#include "MovementComponent.h"
#include "Vector2.h"
class StraightPathMovementComponent : public MovementComponent
{
public:
StraightPathMovementComponent(Entity *owner, float linearSpeed);
~StraightPathMovementComponent();
void Update(float deltaTime);
void SetSpeed(float newSpeed) { speed = newSpeed; }
float GetSpeed() const { return speed; }
private:
float speed;
};
| true |
6c4bd409e60b19e359f95222ad300dc75fde43ce | C++ | krzemien888/pea | /pea/TSPHeader.cpp | UTF-8 | 2,798 | 3.03125 | 3 | [] | no_license | #include "stdafx.h"
#include "TSPHeader.h"
std::string TSPHeader::getName() const
{
return name;
}
void TSPHeader::setName(std::string newName)
{
name = newName;
}
TSP::Type TSPHeader::getType() const
{
return type;
}
void TSPHeader::setType(TSP::Type newType)
{
type = newType;
}
std::string TSPHeader::getComment() const
{
return comment;
}
void TSPHeader::setComment(std::string newComment)
{
comment = newComment;
}
int TSPHeader::getDimension() const
{
return dimension;
}
void TSPHeader::setDimension(int newDimension)
{
dimension = newDimension;
}
int TSPHeader::getCapacity() const
{
return capacity;
}
void TSPHeader::setCapacity(int newCapacity)
{
capacity = newCapacity;
}
TSP::WeightType TSPHeader::getWeightType() const
{
return weightType;
}
void TSPHeader::setWeightType(TSP::WeightType newType)
{
weightType = newType;
}
TSP::EdgeWeightFormat TSPHeader::getEdgeWeightFormat() const
{
return edgeWeightFormat;
}
void TSPHeader::setWeightFormat(TSP::EdgeWeightFormat newWeight)
{
edgeWeightFormat = newWeight;
}
TSP::EdgeDataFormat TSPHeader::getEdgeDataFormat() const
{
return edgeDataFormat;
}
void TSPHeader::setEdgeDataFormat(TSP::EdgeDataFormat newFormat)
{
edgeDataFormat = newFormat;
}
TSP::NodeCoordType TSPHeader::getNodeCoordType() const
{
return nodeCoordType;
}
void TSPHeader::setNodeCoordType(TSP::NodeCoordType newCoordType)
{
nodeCoordType = newCoordType;
}
TSP::DisplayDataType TSPHeader::getDisplayDataType() const
{
return displayDataType;;
}
void TSPHeader::setDisplayDataType(TSP::DisplayDataType newDataType)
{
displayDataType = newDataType;
}
std::ostream & operator<<(std::ostream & stream, const TSPHeader & h)
{
using namespace std;
using namespace TSP;
if(!h.getName().empty())
stream << "NAME:" << h.getName() << endl;
if (h.getType() != Type::notSet)
stream << "TYPE:" << toString(h.getType()) << endl;
if (!h.getComment().empty())
stream << "COMMENT:" << h.getComment() << endl;
if(h.getDimension() > 0)
stream << "DIMENSION:" << h.getDimension() << endl;
if (h.getCapacity() > 0)
stream << "CAPACITY:" << h.getCapacity() << endl;
if (h.getWeightType() != WeightType::notSet)
stream << "EDGE_WEIGHT_TYPE:" << toString(h.getWeightType()) << endl;
if(h.getEdgeWeightFormat() != EdgeWeightFormat::notSet)
stream << "EDGE_WEIGHT_FORMAT:" << toString(h.getEdgeWeightFormat()) << endl;
if (h.getEdgeDataFormat() != EdgeDataFormat::notSet)
stream << "EDGE_DATA_FORMAT:" << toString(h.getEdgeDataFormat()) << endl;
if (h.getNodeCoordType() != NodeCoordType::notSet)
stream << "NODE_COORD_TYPE:" << toString(h.getNodeCoordType()) << endl;
if (h.getDisplayDataType() != DisplayDataType::notSet)
stream << "DISPLAY_DATA_TYPE:" << toString(h.getDisplayDataType()) << endl;
return stream;
}
| true |
26e8554183f346fd290a02d0fcfbafde6b398d31 | C++ | liangchenwater/Programmer-Tower-in-China | /OBJ.hpp | UTF-8 | 780 | 3.171875 | 3 | [] | no_license | //
// OBJ.hpp
//Declare the equipment in the rooms
#ifndef _OBJ_HPP_
#define _OBJ_HPP_
#include "BASIC_BLOCK.hpp"
class elevator:public basic_block{
public:
elevator(string,int=0);//string shows the floor the elevator going to take you to int shows the state(up or down)
void change_instruction(string&);//change the state
void welcome();
bool direction();
void execute();
friend class room;
friend class building;//building and room are "bigger" classes containing the elevator
};
//princess, medicine and diseases and toys are objs
class obj:public basic_block{
private:
string words;//the words of princess
public:
obj(int,string="\0",string="\0");
void welcome();
void execute();
bool direction();
};
#endif /* OBJ_hpp */
| true |
ee1fb8b97029a788ed4bc2adcf9387275d668683 | C++ | sPHENIX-Collaboration/eic-smear | /scripts/compiled_runpythia.cpp | UTF-8 | 2,166 | 2.546875 | 3 | [] | no_license | // wrapper to compile runpythia.cpp
#include<iostream>
#include<string>
#include<sstream>
#include<TString.h>
using namespace std;
void runpythia(TString outFile,
int nEvents,
double pElectron,
double pProton,
double minQ2,
double maxQ2,
int messageInterval );
// bool doFiltering,
// double minz,
// double maxcorrelation);
int main ( int argc, char** argv){
TString outFile;
int nEvents=0;
double pElectron=10;
double pProton=100;
double minQ2 = 1.;
double maxQ2 = -1.;
int messageInterval = 1000;
// bool doFiltering = false;
// double minz = 0.;
// double maxcorrelation = 2.;
// string helpstring="Usage: compiled_runpythia outFile nEvents pElectron pProton [minQ2] [maxQ2] [messageInterval] [doFiltering] [minz] [maxcorrelation]";
string helpstring="Usage: compiled_runpythia outFile nEvents pElectron pProton [minQ2] [maxQ2] [messageInterval]";
if ( argc >1 && string(argv[1]) == "-h" ) {
cout << helpstring << endl;
return -1;
}
// for (int i=0; i<argc; ++i ){
// cout << i << " " << argv[i] << endl;
// }
switch ( argc ){
// case 12:
// maxcorrelation = atof(argv[11]);
// // Fallthrough
// case 11:
// minz = atof(argv[10]);
// // Fallthrough
// case 10:
// std::istringstream(argv[9]) >> doFiltering;
// // Fallthrough
case 9:
messageInterval = atoi(argv[8]);
// Fallthrough
case 8:
maxQ2 = atof(argv[7]);
// Fallthrough
case 7:
minQ2 = atof(argv[6]);
// Fallthrough
case 6:
pElectron = atof(argv[5]);
// Fallthrough
case 5:
pProton = atof(argv[4]);
// Fallthrough
case 4:
pElectron = atof(argv[3]);
// Fallthrough
case 3:
nEvents = atoi(argv[2]);
// Fallthrough
case 2:
outFile = argv[1];
break;
default:
cout << helpstring << endl;
return -1;
}
cout<<endl;
// runpythia(outFile, nEvents, pElectron, pProton, minQ2, maxQ2,
// messageInterval, doFiltering, minz, maxcorrelation);
runpythia(outFile, nEvents, pElectron, pProton, minQ2, maxQ2, messageInterval);
return 0;
}
| true |
53904cf5ea160edb4702eb007c082331e15775fc | C++ | benjaminhuanghuang/ben-leetcode | /1443_Minimum_Time_to_Collect_All_Apples_in_a_Tree/solution.cpp | UTF-8 | 1,604 | 3.171875 | 3 | [] | no_license | /*
1443. Minimum Time to Collect All Apples in a Tree
Level: Medium
https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree
*/
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
#include <algorithm>
#include "common/ListNode.h"
#include "common/TreeNode.h"
using namespace std;
/*
https://zxi.mytechroad.com/blog/uncategorized/leetcode-1443-minimum-time-to-collect-all-apples-in-a-tree/
Solution:
*/
class Solution
{
public:
int minTime(int n, vector<vector<int>> &edges, vector<bool> &hasApple)
{
vector<vector<int>> g(n);
for (const auto &e : edges)
g[e[0]].push_back(e[1]);
function<int(int)> dfs = [&](int cur) {
int total = 0;
for (int nxt : g[cur])
{
int cost = dfs(nxt);
if (cost > 0 || hasApple[nxt])
total += 2 + cost;
}
return total;
};
return dfs(0);
}
};
class Solution
{
public:
int minTime(int n, vector<vector<int>> &edges,
vector<bool> &hasApple)
{
vector<vector<int>> g(n);
for (const auto &e : edges)
{
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}
vector<int> seen(n);
function<int(int)> dfs = [&](int cur) {
seen[cur] = 1;
int total = 0;
for (int child : g[cur])
{
if (seen[child])
continue;
int cost = dfs(child);
if (cost > 0 || hasApple[child])
total += 2 + cost;
}
return total;
};
return dfs(0);
}
}; | true |
8369b592a5632c6eeb04e4f48fd267ece57c9c0b | C++ | TakayukiKiyohara/Sandbox | /tkEngine/particle/tkParticleResources.h | SHIFT_JIS | 575 | 2.59375 | 3 | [] | no_license | /*!
*@brief p[eBÑ\[XNXB
*/
#ifndef _TKPARTICLERESOURCES_H_
#define _TKPARTICLERESOURCES_H_
namespace tkEngine{
/*!
*@brief \[XNXB
*/
class CParticleResources {
private:
CParticleResources();
~CParticleResources();
public:
/*!
*@brief eNX`[hB
*@param[in] filePath t@CpXB
*/
CTexture* LoadTexture( const char* filePath );
/*!
*@brief B
*/
void Release();
private:
friend class CEngine;
std::map<int, CTexture*> textureMap;
};
}
#endif
| true |
9579d531327318ab80ba60784f6dc2f0ebb26bc0 | C++ | vonElfvin/Kattis | /src/eligibility.cc | UTF-8 | 542 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n{}, courses{};
string name{}, began{}, birth{};
cin >> n;
for(int i{}; i<n; ++i){
cin >> name >> began >> birth >> courses;
cout << name << ' ';
if(stoi(began.substr(0,4))>=2010 || stoi(birth.substr(0,4))>=1991){
cout << "eligible";
}else{
if(courses>=41){
cout << "ineligible";
}else{
cout << "coach petitions";
}
}
cout << endl;
}
} | true |
bca03999d6d8fccb7b148ff04c3be583f9615f8f | C++ | SHJTurner/Vision3 | /stereo_recorder/stereo_recorder.cpp | UTF-8 | 2,768 | 2.65625 | 3 | [] | no_license | #include <thread>
#include <stdio.h>
#include <ctime>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define IMG_WIDTH 960
#define IMG_HEIGHT 720
#define cap0dev 1
#define cap1dev 2
using namespace std;
using namespace cv;
VideoCapture cap0;
VideoCapture cap1;
Mat img0;
Mat img1;
vector<Mat> leftImgs;
vector<Mat> rightImgs;
VideoWriter outputVideocap0;
VideoWriter outputVideocap1;
VideoCapture ConfigVideoCapture(int dev){
VideoCapture Vcapture(dev);
//Vcapture.open(dev);
Vcapture.set(CV_CAP_PROP_FRAME_WIDTH,IMG_WIDTH);
Vcapture.set(CV_CAP_PROP_FRAME_HEIGHT,IMG_HEIGHT);
return Vcapture;
}
void threadGrab0(){
cap0.grab();
cap0.retrieve(img0);
Mat Tmp = img0.t(); //Rotate Image
flip(Tmp,img0,0);
leftImgs.push_back(img0);
//outputVideocap0.write(img0);
}
void threadGrab1(){
cap1.grab();
cap1.retrieve(img1);
Mat Tmp = img1.t(); //Rotate Image
flip(Tmp,img1,1);
rightImgs.push_back(img1);
//outputVideocap1.write(img1);
}
int main(int argc, char** argv ){
//init capture devices
cap0 = ConfigVideoCapture(cap0dev);
cap1 = ConfigVideoCapture(cap1dev);
namedWindow("cap0",WINDOW_NORMAL);
namedWindow("cap1",WINDOW_NORMAL);
outputVideocap0.open("RecoredVideo/Cam0.avi",CV_FOURCC('M', 'J', 'P', 'G'),11,Size(720,960),true);
outputVideocap1.open("RecoredVideo/Cam1.avi",CV_FOURCC('M', 'J', 'P', 'G'),11,Size(720,960),true);
if (!outputVideocap0.isOpened() || !outputVideocap1.isOpened())
{
printf("Output video could not be opened\n");
return 0;
}
if (!cap0.isOpened() || !cap1.isOpened()){
printf("Output video could not be opened\n");
return 0;
}
//record video
printf("Starting to record video... \n(Press 'c'-key to stop)\n");
fflush(stdout);
for(;;){
clock_t begin = clock();
thread Grab0(threadGrab0);
thread Grab1(threadGrab1);
Grab0.join();
Grab1.join();
char c = (char)waitKey(1);
if( c == 'c')
break;
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
double fps = 1.0/elapsed_secs;
printf("FPS: %f (Press 'c'-key to stop)\n",fps);
fflush(stdout);
}
printf("Writeing video to harddrive...");
fflush(stdout);
for(Mat img : leftImgs)
{
outputVideocap0.write(img);
}
for(Mat img : rightImgs)
{
outputVideocap1.write(img);
}
outputVideocap0.release();
outputVideocap1.release();
printf(" done\n");
fflush(stdout);
return 0;
}
| true |
0400ab5f2750aef35ff0c2f0a544ce53a0e3be04 | C++ | crfh/gap_vector | /gap_vector.hpp | UTF-8 | 30,439 | 2.59375 | 3 | [] | no_license | /* gap_vector コンテナ
* このファイルは public-domain とします
*/
/* 特徴
* この実装では、例外安全性についてかなり注意を払っています。
* また、C++11対応のためのコードも含まれています。
*
* 注意
* 設定が必要です。
* * NDEBUG // これを#defineすると、デバッグコードが省かれます。
* * __GAP_CXX11__ // これを1にすると、c++11用のコードが展開されます gcc 4.5に関しては、自動でこれを行います
* * std::_Destroy // 区間に対してallocator.destroyを呼び出す関数です
*
*/
#ifndef GAP_VECTOR_HPP
#define GAP_VECTOR_HPP
#include <new>
#include <iterator>
#include <stdexcept>
#include <memory>
#ifndef NDEBUG
#include <iostream>
#endif
#ifdef __GXX_EXPERIMENTAL_CXX0X__
#define __GAP_CXX11__ 1
#endif
#if __GAP_CXX11__
#include <initializer_list>
#endif
#if __GAP_CXX11__
#define GAP_MAKE_MOVE_ITER(I) std::make_move_iterator((I))
#define GAP_FORWARD(A) std::forward<Args>((A))...
#else
#define GAP_MAKE_MOVE_ITER(I) (I)
#define GAP_FORWARD(A) (A)
#endif
namespace gap{
// 下は uninitialized に含まれない
namespace {
template< typename InputIter, typename ForwardIter, typename Alloc >
ForwardIter uninitialized_copy_a( InputIter first, InputIter last,
ForwardIter result, Alloc& alloc ){
ForwardIter t = result;
try{
for( ; first != last; ++first ){
alloc.construct( &*(result), *first );
++result;
}
} catch(...) {
Destroy( t, result, alloc );
throw;
}
return result;
}
template< typename InputIter, typename ForwardIter, typename Tp>
ForwardIter uninitialized_copy_a( InputIter first, InputIter last,
ForwardIter result, std::allocator<Tp>& )
{ return std::uninitialized_copy( first, last, result ); }
template< typename ForwardIter, typename size_type, typename Tp, typename Alloc >
void uninitialized_fill_n_a( ForwardIter first, size_type sz, const Tp& value, Alloc& alloc ) {
ForwardIter t = first;
try {
for( ; sz != 0; --sz ){
alloc.construct( &*(first), value );
++first;
}
} catch(...) {
Destroy( t, first, alloc );
}
}
template< typename ForwardIter, typename size_type, typename Tp >
void uninitialized_fill_n_a( ForwardIter first, size_type sz,
const Tp& value, std::allocator<Tp>& )
{ std::uninitialized_fill_n( first, sz, value ); }
/*template< typename ForwardIter, typename Alloc >
void Destroy( ForwardIter first, ForwardIter last, const Alloc& alloc )
{ for( ; first != last; ++first ) alloc.destroy( &*(first) ); }
template< typename ForwardIter, typename Tp >
void Destroy( ForwardIter first, ForwardIter last, const std::allocator<Tp>& alloc )
{ std::Destroy( first, last ); }*/
template< typename ForwardIter, typename Alloc >
void Destroy( ForwardIter first, ForwardIter last, Alloc& alloc )
{ std::_Destroy( first, last, alloc ); }
};
// gapのイテレータは、速くはない
namespace{
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
struct gap_iterator_base : public std::iterator<std::random_access_iterator_tag,Tp,
DiffTp, PtrTp, RefTp >
{
public:
typedef Tp value_type;
typedef DiffTp difference_type;
typedef PtrTp pointer;
typedef RefTp reference;
typedef gap_iterator_base Self;
gap_iterator_base() {}
gap_iterator_base( pointer c, pointer b, pointer e ): cur(c), gap_begin(b), gap_end(e) {}
gap_iterator_base( const Self& rhs ): cur(rhs.cur), gap_begin(rhs.gap_begin),
gap_end(rhs.gap_end) {}
Self& operator=( const Self& rhs ) {
cur = rhs.cur;
gap_begin = rhs.gap_begin;
gap_end = rhs.gap_end;
return *this;
}
Self operator+( difference_type n ) const {
if( cur < gap_begin && cur + n >= gap_begin )
return Self( cur + n + (gap_end-gap_begin), gap_begin, gap_end );
if( cur >= gap_end && cur + n < gap_end )
return Self( cur + n - (gap_end-gap_begin), gap_begin, gap_end );
return Self( cur + n, gap_begin, gap_end );
}
Self operator-( difference_type n ) const { return this->operator+(-n); }
difference_type operator-( const Self& rhs ) const {
if( cur < rhs.cur ){
if( cur > gap_begin || rhs.cur < gap_begin)
return rhs.cur - cur;
else
return rhs.cur - cur - (gap_end-gap_begin);
} else {
if( rhs.cur > gap_begin || cur < gap_begin)
return cur - rhs.cur;
else
return cur - rhs.cur - (gap_end-gap_begin);
}
}
Self& operator++() {
cur++;
cur = cur == gap_begin ? cur + (gap_end - gap_begin) : cur;
return *this;
}
Self operator++( int ) {
Self itr = *this;
++*this;
return itr;
}
Self& operator--() {
cur = cur == gap_end ? cur - (gap_end-gap_begin) -1 : cur - 1;
return *this;
}
Self operator--( int ) {
Self itr = *this;
--*this;
return itr;
}
Self& operator+=( difference_type n ) { return (*this = *this+n); }
Self& operator-=( difference_type n ) { return (*this = *this-n); }
reference operator*() const { return *cur; }
pointer operator->() const { return cur; }
operator pointer () const { return cur; }
pointer cur, gap_begin, gap_end;
};
}
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline bool
operator==( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return lhs.cur == rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp,
typename RDiffTp, typename RPtrTp, typename RRefTp >
inline bool
operator==( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,RDiffTp,RPtrTp,RRefTp>& rhs )
{ return lhs.cur == rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline bool
operator!=( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return lhs.cur != rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp,
typename RDiffTp, typename RPtrTp, typename RRefTp >
inline bool
operator!=( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,RDiffTp,RPtrTp,RRefTp>& rhs )
{ return lhs.cur != rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline bool
operator<( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return lhs.cur < rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp,
typename RDiffTp, typename RPtrTp, typename RRefTp >
inline bool
operator<( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,RDiffTp,RPtrTp,RRefTp>& rhs )
{ return lhs.cur < rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline bool
operator<=( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return lhs.cur <= rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp,
typename RDiffTp, typename RPtrTp, typename RRefTp >
inline bool
operator<=( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,RDiffTp,RPtrTp,RRefTp>& rhs )
{ return lhs.cur <= rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline bool
operator>( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return lhs.cur > rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp,
typename RDiffTp, typename RPtrTp, typename RRefTp >
inline bool
operator>( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,RDiffTp,RPtrTp,RRefTp>& rhs )
{ return lhs.cur > rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline bool
operator>=( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return lhs.cur >= rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp,
typename RDiffTp, typename RPtrTp, typename RRefTp >
inline bool
operator>=( const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& lhs,
const gap_iterator_base<Tp,RDiffTp,RPtrTp,RRefTp>& rhs )
{ return lhs.cur >= rhs.cur; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>
operator+( DiffTp lhs, const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return rhs+lhs; }
template< typename Tp, typename DiffTp, typename PtrTp, typename RefTp >
inline gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>
operator-( DiffTp lhs, const gap_iterator_base<Tp,DiffTp,PtrTp,RefTp>& rhs )
{ return rhs-lhs; }
// gap_vectorの例外安全性について
// gap_vectorでは、様々な操作で、内部データのコピーが発生する
// その結果、格納する型の例外安全性が、gap_vectorの例外安全性にとても関係する
// もし格納する型のデストラクタが例外を送出するなら、gap_vectorは例外安全でない
// そうでない場合
// もし格納する型のムーブコンストラクタが例外を送出するなら、gap_vectorは基本例外保証をする
// 一方で、格納する型のムーブコンストラクタが例外を送出しないなら、gap_vectorは、強い例外安全保証をする
// もし格納する型にムーブコンストラクタが定義されていない場合、以下のケースとなる
// もし格納する型のコピーコンストラクタが例外を送出するなら、gap_vectorは、基本例外安全保証をする
// もし格納する型のコピーコンストラクタが例外を送出しないなら、gap_vectorは、強い例外安全保証をする
// 詳細はそれぞれのメンバ関数宣言を参照のこと(書いていないものは、上のルールに従っている)
// また、constでない操作の場合、ほとんど確実にiteratorが破壊されることに注意
// vectorでは、ときどき破壊されるぐらいだが、gap_vectorでは、ほぼ間違いなくいつでも破壊される
// 基本的に、コピーやムーブで例外を出すようなオブジェクトは、unique_ptrに入れるべき
// インターフェースはvectorといっしょ
template< typename Tp, typename Alloc = std::allocator<Tp> >
class gap_vector {
public:
typedef typename Alloc::template rebind<Tp>::other alloc_type;
typedef Tp value_type;
typedef typename alloc_type::pointer pointer;
typedef typename alloc_type::const_pointer const_pointer;
typedef typename alloc_type::reference reference;
typedef typename alloc_type::const_reference const_reference;
typedef typename alloc_type::size_type size_type;
typedef typename alloc_type::difference_type difference_type;
typedef gap_iterator_base<value_type,difference_type,
pointer,reference>
iterator;
typedef gap_iterator_base<value_type,difference_type,
const_pointer,const_reference>
const_iterator;
typedef typename std::reverse_iterator<iterator> reverse_iterator;
typedef typename std::reverse_iterator<const_iterator>
const_reverse_iterator;
gap_vector(): bbegin(0), bend(0), gap_begin(0), gap_end(0) {}
explicit gap_vector( const alloc_type& alloc )
: bbegin(0), bend(0), gap_begin(0), gap_end(0), allocator(alloc) {}
explicit gap_vector( size_type n, const value_type& v = value_type(),
const alloc_type& alloc = alloc_type() )
: allocator(alloc) {
bbegin = allocator.allocate( n );
bend = gap_begin = gap_end = bbegin + n;
try {
uninitialized_fill_n_a( bbegin, n, v, allocator );
} catch( ... ){
allocator.deallocate( bbegin, n );
throw;
}
}
template< typename InputIter >
gap_vector( InputIter first, InputIter last )
: bbegin(0), bend(0), gap_begin(0), gap_end(0)
{
try{
insert( begin(), first, last );
} catch(...) {
m_release_buf();
throw;
}
}
gap_vector( const gap_vector& rhs )
: allocator(rhs.allocator) {
size_type sz = rhs.size();
pointer buf = allocator.allocate( sz );
try{
rhs.m_copy_to_buf( buf, allocator );
} catch(...) {
allocator.deallocate( buf, sz );
throw;
}
bbegin = buf; bend = gap_begin = gap_end = buf+sz;
}
#if __GAP_CXX11__
// ムーブコンストラクタは例外を送出しない
gap_vector( gap_vector&& rhs )
: bbegin(rhs.bbegin), bend(rhs.bend),
gap_begin(rhs.gap_begin), gap_end(rhs.gap_end), allocator( std::move(rhs.allocator) )
{ rhs.bbegin = rhs.bend = rhs.gap_begin = rhs.gap_end = 0; }
gap_vector( std::initializer_list<value_type> init,
const alloc_type& alloc = alloc_type() )
: bbegin(0), bend(0), gap_begin(0), gap_end(0), allocator(alloc)
{
try {
m_range_insert( begin(), init.begin(), init.end(), std::random_access_iterator_tag() );
} catch(...) {
m_release_buf();
throw;
}
}
#endif
~gap_vector()
{ m_release_buf(); }
gap_vector& operator=( const gap_vector& rhs ){
// データのコピー成功後にバッファの解放を行う
size_type sz = rhs.size();
pointer buf = allocator.allocate( sz );
try{
rhs.m_copy_to_buf( buf, allocator );
} catch(...) {
allocator.deallocate( buf, sz );
throw;
}
m_release_buf();
bbegin = buf; bend = gap_begin = gap_end = buf+sz;
return *this;
}
#if __GAP_CXX11__
// ムーブは例外を送出しない
gap_vector& operator=( gap_vector&& rhs ){
m_release_buf();
bbegin = rhs.bbegin;
bend = rhs.bend;
gap_begin = rhs.gap_begin;
gap_end = rhs.gap_end;
rhs.bbegin = rhs.bend = rhs.gap_begin = rhs.gap_end = 0;
return *this;
}
#endif
#if !__GAP_CXX11__
// insert後は、itrにあった要素がgapの直後にくるようになる
iterator insert( const iterator& itr, const value_type& e )
{ return m_emplace( itr, e ); }
#else
iterator insert( const iterator& itr, const value_type& e ) {
value_type t = e;
return m_emplace( itr, std::move(t) );
}
iterator insert( const iterator& itr, value_type&& e )
{ return emplace( itr, std::move(e) ); }
template<typename... Args>
iterator emplace( const iterator& itr, Args&&... args )
{ return m_emplace( itr, std::forward<Args>(args)...); }
#endif
template<typename InputIter>
void insert( const iterator& itr, InputIter first, InputIter last ){
typedef typename std::iterator_traits<InputIter>::iterator_category IterCategory;
m_range_insert( itr, first, last, IterCategory() );
}
// itr の位置の要素を削除し、gapの位置をitrのあった場所から始まるように移動する
void erase( const iterator& itr ){
pointer ptr = itr;
if( gap_begin < ptr ){
m_move_rtl( ptr );
allocator.destroy( gap_end++ );
}else {
m_move_ltr( ++ptr );
allocator.destroy( --gap_begin );
}
}
void erase( const iterator& first, const iterator& last ){
pointer f = first, l = last;
if( f > gap_end ) {
m_move_rtl( f ); // fより前を移動
Destroy( f, l, allocator );
gap_end = l;
} else if( l <= gap_end ) {
if( l == gap_end ) l = gap_begin;
else m_move_ltr( l ); // lを含めて移動
Destroy( f, l, allocator );
gap_begin = f;
} else {
Destroy( f, gap_begin, allocator );
Destroy( gap_end, l, allocator );
gap_begin = f; gap_end = l;
}
}
#if !__GAP_CXX11__
// push_back insert( end(), e ) と同じ
void push_back( const value_type& e ) { m_emplace_back(e); }
#else
void push_back( const value_type& e ) {
value_type t = e;
m_emplace_back(std::move(t));
}
template<typename... Args>
void emplace_back( Args&& ... args )
{ m_emplace_back( std::forward<Args>(args)... ); }
void push_back( value_type&& e ) { m_emplace_back( std::move(e) ); }
#endif
void pop_back() {
if( bend == gap_end ) allocator.destroy( --gap_begin );
else erase( --end() );
}
#if !__GAP_CXX11__
void push_front( const value_type& e ) { m_emplace_front(e); }
#else
void push_front( const value_type& e ) {
value_type t = e;
m_emplace_front(std::move(t));
}
template<typename... Args>
void emplace_front( Args&& ... args )
{ m_emplace_front( std::forward<Args>(args)... ); }
void push_front( value_type&& e ) { m_emplace_front( std::move(e) ); }
#endif
void pop_front() {
if( gap_begin == bbegin ) allocator.destroy( gap_end++ );
else erase( begin() );
}
// gapの幅を広げる つまり、gapの論理的な位置を変えない
void reserve( size_type n ){
if( n >= max_size() )
throw std::length_error("gap_vector::reserve");
if( capacity() < n ){
size_type sz = size() + n;
pointer buf = allocator.allocate(sz);
try{
m_move_to_newbuf( buf, sz );
} catch(...){
allocator.deallocate( buf, sz );
throw;
}
}
}
// shrink_to_fitはc++98でも実現でき、便利なので、どちらでも使えるようにしている
// cbegin, cend もそう
void shrink_to_fit() {
size_type sz = size();
pointer buf = allocator.allocate( sz );
try {
m_move_to_newbuf( buf, sz );
} catch(...) {
allocator.deallocate( buf );
throw;
}
}
void clear() {
Destroy( bbegin, gap_begin );
gap_begin = bbegin;
Destroy( gap_end, bend );
gap_end = bend;
}
void swap( gap_vector& rhs ) {
using std::swap;
swap( bbegin, rhs.bbegin );
swap( bend, rhs.bend );
swap( gap_begin, rhs.gap_begin );
swap( gap_end, rhs.gap_end );
swap( allocator, rhs.allocator );
}
size_type max_size() const { return allocator.max_size(); }
size_type capacity() const { return gap_end - gap_begin; }
bool empty() const { return bbegin == gap_begin && bend == gap_end; }
size_type size() const { return (bend - gap_end) + (gap_begin - bbegin); }
iterator end() {
return gap_end == bend ?
iterator(gap_begin,gap_begin,gap_end):
iterator(bend,gap_begin,gap_end);
}
iterator begin() {
return bbegin == gap_begin ?
iterator(gap_end,gap_begin,gap_end):
iterator(bbegin,gap_begin,gap_end);
}
const_iterator end() const { return cend(); }
const_iterator begin() const { return cbegin(); }
const_iterator cend() const {
return gap_end == bend ?
const_iterator(gap_begin,gap_begin,gap_end):
const_iterator(bend,gap_begin,gap_end);
}
const_iterator cbegin() const {
return bbegin == gap_begin ?
const_iterator(gap_end,gap_begin,gap_end):
const_iterator(bbegin,gap_begin,gap_end);
}
reverse_iterator rend() { return reverse_iterator(begin());}
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rend() const { return const_reverse_iterator(cbegin()); }
const_reverse_iterator rbegin() const { return const_reverse_iterator(cend()); }
const_reverse_iterator crend() const { return const_reverse_iterator(cbegin()); }
const_reverse_iterator crbegin() const { return const_reverse_iterator(cend()); }
reference front() { return gap_begin == bbegin ? *bend : *bbegin; }
const_reference front() const { return gap_begin == bbegin ? *bend : *bbegin; }
reference back() { return gap_end == bend ? *(gap_begin-1) : *(bend-1); }
const_reference back() const { return gap_end == bend ? *(gap_begin-1) : *(bend-1); }
reference operator[]( size_type indx ){
if( bbegin+indx >= gap_begin ){
return *(gap_end + (bbegin+indx-gap_begin));
} else
return *(bbegin+indx);
}
const_reference operator[]( size_type indx ) const {
if( bbegin+indx >= gap_begin ){
return *(gap_end + (bbegin+indx-gap_begin));
} else
return *(bbegin+indx);
}
reference at( size_type indx ){
if( size()<=indx ) throw std::out_of_range("gap_vector::at");
if( bbegin+indx >= gap_begin ){
return *(gap_end + (bbegin+indx-gap_begin));
} else
return *(bbegin+indx);
}
const_reference at( size_type indx ) const {
if( size()<=indx ) throw std::out_of_range("gap_vector::at");
if( bbegin+indx >= gap_begin ){
return *(gap_end + (bbegin+indx-gap_begin));
} else
return *(bbegin+indx);
}
#ifndef NDEBUG
void print() const {
for( pointer ptr=bbegin; ptr != gap_begin; ++ptr )
std::cout << *ptr << ',';
for( pointer ptr=gap_begin; ptr!=gap_end; ++ptr )
std::cout << '_' << ',';
for( pointer ptr=gap_end; ptr!=bend; ++ptr )
std::cout << *ptr << ',';
std::cout << std::endl;
}
#endif
private:
pointer bbegin; // メモリ領域の先頭
pointer bend; // メモリ領域の末尾 [bbegin,bend)
pointer gap_begin; // gap の先頭
pointer gap_end; // gap の末尾 [gap_begin,gap_end)
alloc_type allocator;
private:
// 2倍伸長ルールで、新しい領域の大きさを決める
size_type m_next_size() const { return bend-bbegin ? ((bend-bbegin)<<1) : 1; }
// 新しいバッファへ全要素を転送する
void m_move_to_newbuf( pointer buf, size_type sz ) {
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(bbegin),
GAP_MAKE_MOVE_ITER(gap_begin),
buf, allocator);
try{
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(gap_end),
GAP_MAKE_MOVE_ITER(bend),
buf+sz - (bend-gap_end), allocator );
}
catch(...){
Destroy( buf, gap_begin-bbegin+buf, allocator );
throw;
}
m_release_buf();
gap_begin = gap_begin-bbegin + buf;
bbegin = buf;
gap_end = buf+sz - (bend-gap_end);
bend = buf + sz;
}
// 新しいgap位置を受け取るバージョン
void m_move_to_newbuf( pointer buf, pointer g, size_type sz ){
if( g < gap_end ){
size_type r1 = g - bbegin;
size_type r2 = gap_begin - g;
size_type r3 = bend - gap_end;
pointer nwgap_end = buf+sz - r2 - r3;
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(bbegin),
GAP_MAKE_MOVE_ITER(g),
buf, allocator );
try{
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(g),
GAP_MAKE_MOVE_ITER(gap_begin),
nwgap_end, allocator );
} catch(...){
Destroy( buf, buf+r1, allocator );
throw;
}
try{
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(gap_end),
GAP_MAKE_MOVE_ITER(bend),
nwgap_end+r2, allocator );
} catch(...){
Destroy( buf, buf+r1, allocator );
Destroy( nwgap_end, nwgap_end+r2, allocator );
throw;
}
m_release_buf();
bbegin = buf; gap_begin = buf+r1; gap_end = nwgap_end; bend = buf+sz;
} else {
size_type r1 = gap_begin - bbegin;
size_type r2 = g-gap_end;
size_type r3 = bend - g;
pointer nwgap_end = buf+sz - r3;
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(bbegin),
GAP_MAKE_MOVE_ITER(gap_begin),
buf, allocator );
try{
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(gap_end),
GAP_MAKE_MOVE_ITER(g),
buf+r1, allocator );
} catch(...){
Destroy( buf, buf+r1, allocator );
throw;
}
try{
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(g),
GAP_MAKE_MOVE_ITER(bend),
nwgap_end, allocator );
} catch(...){
Destroy( buf, buf+r1, allocator );
Destroy( nwgap_end, nwgap_end+r2, allocator );
throw;
}
m_release_buf();
bbegin = buf; gap_begin = buf+r1+r2; gap_end = nwgap_end; bend = buf+sz;
}
}
// shrink_to_fitで未初期化領域へデータをコピーする
void m_copy_to_buf( pointer buf, alloc_type& al ) const {
uninitialized_copy_a( bbegin, gap_begin, buf, al );
try{
uninitialized_copy_a( gap_end, bend, buf+(gap_begin-bbegin), al );
} catch( ... ){
Destroy( buf, buf+(gap_begin-bbegin), al );
throw;
}
}
void m_release_buf(){
if( bbegin != 0 ){
Destroy( bbegin, gap_begin, allocator );
Destroy( gap_end, bend, allocator );
allocator.deallocate( bbegin, bend - bbegin );
}
}
// [gap_end, ptr) を、gap_beginへ移動する
void m_move_rtl( pointer ptr ){
pointer nwgap_end = gap_begin + (ptr - gap_end);
if( nwgap_end < gap_end ){
gap_begin =
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(gap_end),
GAP_MAKE_MOVE_ITER(ptr),
gap_begin, allocator );
Destroy( gap_end, ptr, allocator );
gap_end = ptr;
} else {
size_type un = gap_end - gap_begin;
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(gap_end),
GAP_MAKE_MOVE_ITER(gap_end+un),
gap_begin, allocator );
try{
std::copy( GAP_MAKE_MOVE_ITER(gap_end+un),
GAP_MAKE_MOVE_ITER(ptr),
gap_begin+un );
} catch( ... ){
Destroy( gap_begin, gap_begin+un, allocator );
throw;
}
Destroy( gap_begin+(ptr-gap_end), ptr, allocator );
gap_begin = gap_begin+(ptr-gap_end);
gap_end = ptr;
}
}
// [ptr, gap_begin) を、gap_endの直前へ移動する
void m_move_ltr( pointer ptr ){
size_type mvn = gap_begin - ptr; // 移動する個数
pointer nwgap_end = gap_end - mvn; // 新しい gap_end;
if( nwgap_end < gap_begin ){
size_type un = gap_end - gap_begin;
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(gap_begin-un),
GAP_MAKE_MOVE_ITER(gap_begin),
gap_end-un, allocator );
try{
std::copy_backward( GAP_MAKE_MOVE_ITER(ptr),
GAP_MAKE_MOVE_ITER(gap_begin-un),
gap_end - un );
} catch( ... ){
Destroy( gap_end-un, gap_end, allocator );
throw;
}
Destroy( ptr, nwgap_end, allocator );
} else {
uninitialized_copy_a( GAP_MAKE_MOVE_ITER(ptr),
GAP_MAKE_MOVE_ITER(gap_begin),
gap_end - mvn, allocator );
Destroy( ptr, gap_begin, allocator );
}
gap_begin = ptr;
gap_end = nwgap_end;
}
// gapの位置をitrの直前に変える
void m_make_gap( const iterator& itr ){
pointer ptr = itr;
if( gap_begin < ptr )
m_move_rtl( ptr );
else
m_move_ltr( ptr );
}
#ifdef __GAP_CXX11__
template<typename... Args>
iterator m_emplace( const iterator& itr, Args&&... args )
#else
iterator m_emplace( const iterator& itr, const value_type& args )
#endif
{
if( capacity() ){
m_make_gap( itr );
allocator.construct( gap_begin++, GAP_FORWARD(args) );
} else {
size_type sz = m_next_size();
gap_begin = itr;
gap_end = gap_begin;
pointer buf = allocator.allocate(sz);
try{
m_move_to_newbuf( buf, sz );
} catch( ... ){
allocator.deallocate( buf, sz );
throw;
}
allocator.construct( gap_begin++, GAP_FORWARD(args) );
}
return iterator( gap_begin-1, gap_begin, gap_end );
}
template<typename InputIter>
void
m_range_insert( iterator itr, InputIter first, InputIter last,
std::input_iterator_tag ){
for( ; first != last; ++first ){
itr = insert( itr, *first );
++itr;
}
}
template<typename ForwardIter >
void
m_range_insert( const iterator& itr, ForwardIter first, ForwardIter last,
std::forward_iterator_tag ){
size_type sz = std::distance(first,last); // forward_iteratorの場合、若干非効率
if( sz == 0 ) return;
if( capacity() >= sz ){
m_make_gap( itr );
gap_begin = uninitialized_copy_a( first, last, gap_begin, allocator );
} else {
size_type nsz = std::max( size()+sz, m_next_size() );
pointer buf = allocator.allocate( nsz );
try{
m_move_to_newbuf( buf, static_cast<pointer>(itr), nsz );
} catch(...) {
allocator.deallocate( buf, nsz );
throw;
}
gap_begin = uninitialized_copy_a( first, last, gap_begin, allocator );
}
}
#if __GAP_CXX11__
template<typename... Args>
void m_emplace_back( Args&&... args )
#else
void m_emplace_back( const value_type& args )
#endif
{
if( gap_end != gap_begin && gap_end == bend )
allocator.construct( gap_begin++, GAP_FORWARD(args) );
else m_emplace( end(), GAP_FORWARD(args) );
}
#if __GAP_CXX11__
template<typename... Args>
void m_emplace_front( Args&&... args )
#else
void m_emplace_front( const value_type& args )
#endif
{
if( gap_end != gap_begin && gap_begin == bbegin )
allocator.construct( --gap_end, GAP_FORWARD(args) );
else m_emplace( begin(), GAP_FORWARD(args) );
}
};
#undef GAP_MAKE_MOVE_ITER
#undef GAP_FORWARD
template<typename Tp, typename Alloc>
bool operator==( const gap_vector<Tp,Alloc>& lhs, const gap_vector<Tp,Alloc>& rhs )
{
return lhs.size() == rhs.size()
&& std::equal( lhs.begin(), lhs.end(), rhs.begin() );
}
template<typename Tp, typename Alloc>
bool operator!=( const gap_vector<Tp,Alloc>& lhs, const gap_vector<Tp,Alloc>& rhs )
{
return !(lhs==rhs);
}
template<typename Tp, typename Alloc>
bool operator<( const gap_vector<Tp,Alloc>& lhs, const gap_vector<Tp,Alloc>& rhs )
{
return std::lexicographical_compare( lhs.begin(), lhs.end(),
rhs.begin(), rhs.end() );
}
template<typename Tp, typename Alloc>
bool operator>( const gap_vector<Tp,Alloc>& lhs, const gap_vector<Tp,Alloc>& rhs )
{ return rhs < lhs; }
template<typename Tp, typename Alloc>
bool operator<=( const gap_vector<Tp,Alloc>& lhs, const gap_vector<Tp,Alloc>& rhs )
{ return !(rhs < lhs); }
template<typename Tp, typename Alloc>
bool operator>=( const gap_vector<Tp,Alloc>& lhs, const gap_vector<Tp,Alloc>& rhs )
{ return !(lhs < rhs); }
// gap_vectorをswapするときは、
// ...
// using std::swap;
// gap::gap_vector<Tp,Alloc> gap1, gap2;
// swap( gap1, gap2 );
// ...
// とすること
// swapは例外を送出しない
template< typename Tp, typename Alloc >
void swap( gap_vector<Tp,Alloc>& lhs, gap_vector<Tp,Alloc>& rhs )
{ lhs.swap( rhs ); }
}
#endif
| true |
1f6098a09e1eab7c8d38a081c10961fffcf9d063 | C++ | juanvillafrades/Caracterizacion-SiPMs | /Modulos/ControlTemperatura_MedidorCorriente/PID_control.ino | UTF-8 | 4,997 | 2.625 | 3 | [] | no_license | ////Juan Carlos Sánchez Villafrades ///////
// Algoritmo para implementar el control de temperatura y la lectura de la corriente en el SiPM
#include "PID_v1.h"
#define TemPin1 1
#define TemPin2 2
#define Heating 10
#define Cooling 11
int cont_tem=0;
int tem_adc1;
int tem_adc2;
float tem_avg, tem_amb;
float tem_sum=0;
float temp;
bool flagTemp = true;
unsigned long time1;
unsigned long time2;
unsigned long deltatime;
int sample_time = 2000; //tiempo de muestreo de la temperatura en el interior
int sample_time_amb = 2000; // tiempo hasta donde se promedia la temperara ambiente
float time_label;
/// nanoAmperimetro ////
int pinCorriente = 3;
int cor_adc;
float cor;
float cor_avg;
float cor_sum;
//// PID ///
double Setpoint, Input, Output;
// Parametros del controlador PID
double Kp=11.0576, Ki=0.043684, Kd=41.4475;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
void setup()
{
Serial.begin(9600);
pinMode(TemPin1, INPUT);
pinMode(TemPin2, INPUT);
pinMode (Heating, OUTPUT);
pinMode (Cooling, OUTPUT);
Serial.print(" Tiempo");
Serial.print(" ");
Serial.print(" Temperatura");
Serial.print(" ");
Serial.println("Corriente nA");
Setpoint = 25;
myPID.SetMode(AUTOMATIC); //turn the PID on
time2 = millis()-sample_time;
}
void loop()
{
//*****************************TEMPERATURA***************************//
time1 = millis();
deltatime = time1 - time2;
tem_adc1 = analogRead(TemPin1);
tem_adc2 = analogRead(TemPin2);
temp = (((float(tem_adc1)-float(tem_adc2))*500)/1024);
//temp =((float(tem_adc1)*500)/1024);
cor_adc = analogRead(pinCorriente); // lectura del valor de corriente en el SiPM
cor = (float(cor_adc)*50/1024);
cor_sum += cor;
tem_sum += temp;
cont_tem += 1;
if ((time1 >= sample_time_amb) && flagTemp) // Realiza la lectura de temperatura durante sample_time_amb segundos para establecer la temperatura ambiente
{
tem_amb = tem_sum/cont_tem;
tem_sum = tem_amb;
Input = tem_amb;
cont_tem = 1;
flagTemp = false;
}
if (!flagTemp) /// a partir de aqui se realiza el control y se empieza a mostrar la temperatura
{
//*****************************CONTROL***************************//
//*****************************CALENTAMIENTO********************//
if(Setpoint >= tem_amb)
{
// Acción de control para realizar calentamiento
myPID.SetTunings(11.0576, 0.043684, 41.4475);
myPID.SetOutputLimits(-6, 90);
myPID.SetSampleTime(sample_time);
myPID.SetControllerDirection(DIRECT);
myPID.Compute();
if (Output >= 0)
{
analogWrite(Heating, Output);
analogWrite(Cooling, 0);
}
else
{
analogWrite(Heating, 0);
analogWrite(Cooling, abs(Output));
}
//se promedia el valor de temperatura para intervalos de sample_time segundos
if((deltatime>=sample_time))
{
tem_avg = tem_sum/cont_tem;
time_label = (time1 - sample_time_amb)*0.001;
cor_avg = cor_sum/cont_tem;
Serial.print(" ");
Serial.print(time_label);
Serial.print(" ");
Serial.print(tem_avg,1);
Serial.print(" ");
Serial.print(cor_avg);
Serial.print(" ");
Serial.println(cont_tem);
// Serial.print(" ");
// Serial.println("Calentandoooooooooooo");
Input = tem_avg;
tem_sum = 0;
cont_tem = 0;
time2 = time1;
cor_sum = 0;
}
}
//*****************************REFRIGEREACION********************//
else
{
// Acción de control para realizar refrigeracion
myPID.SetTunings(30.36, 0.148, 100);
myPID.SetOutputLimits(-6, 243);
myPID.SetSampleTime(sample_time);
myPID.SetControllerDirection(REVERSE);
myPID.Compute();
if (Output >= 0)
{
analogWrite(Heating, 0);
analogWrite(Cooling, Output);
}
else
{
analogWrite(Heating, abs(Output));
analogWrite(Cooling, 0);
}
if((deltatime>=sample_time))
{
tem_avg = tem_sum/cont_tem;
time_label= (time1 - sample_time_amb)*0.001;
cor_avg = cor_sum/cont_tem;
Serial.print(" ");
Serial.print(time_label);
Serial.print(" ");
Serial.print(tem_avg,1);
Serial.print(" ");
Serial.print(cor_avg);
Serial.print(" ");
Serial.println(cont_tem);
// Serial.print(" ");
// Serial.println("Enfriando............");
Input = tem_avg;
tem_sum = 0;
cont_tem = 0;
time2 = time1;
cor_sum = 0;
}
}
}
}
| true |
e46b4cd4e66fa9ff9f4fe4017ad505437dc94671 | C++ | Ostrichisme/UVA | /10311.cpp | UTF-8 | 1,042 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
char prime[100000001]={0};
int main()
{
for(int i=2;i*i<=100000000;i++)
{
if(prime[i]==0)
{
for(int k=2*i;k<=100000000;k+=i)
prime[k]=1;
}
}
int num;
while(cin>>num)
{
if(num<5)
cout<<num<<" is not the sum of two primes!\n";
else if(num%2==1)
{
if(prime[num-2]==0)
cout<<num<<" is the sum of 2 and "<<num-2<<".\n";
else
cout<<num<<" is not the sum of two primes!\n";
}
else
{
int flag=0;
for(int i=(num-1)/2;i>=3;i--)
{
if(prime[i]==0&&prime[num-i]==0)
{
flag=1;
cout<<num<<" is the sum of "<<i<<" and "<<num-i<<".\n";
break;
}
}
if(flag==0)
cout<<num<<" is not the sum of two primes!\n";
}
}
}
| true |
ebc7020bc79e386c58a44e05051ec74a7aa83dc9 | C++ | Peterguo88/cone_detection | /src/image_handler.cpp | UTF-8 | 5,699 | 2.6875 | 3 | [] | no_license | #include <cone_detection/image_handler.hpp>
ImageHandler::ImageHandler(){}
ImageHandler::~ImageHandler(){}
void ImageHandler::init(std::string candidate_path, Cone cone, Detection detection){
//Init camera matrices.
cam_.initCamMatrices();
//Getting parameter.
cone_ = cone;
detection_ = detection;
candidate_path_ = candidate_path;
}
void ImageHandler::croppCandidates(std::vector <Candidate> xyz_index_vector){
//Clear vectors.
object_points_.clear();
image_points_.clear();
candidates_.clear();
candidate_indizes_.clear();
//Push back vector points (laser coords -> cam coords).
for(int i=0; i<xyz_index_vector.size(); ++i){
cv::Point3d point;
point.z = xyz_index_vector[i].x;
point.x = -xyz_index_vector[i].y;
point.y = -xyz_index_vector[i].z;
object_points_.push_back(point);
}
//Transform to pixel points.
transformPointToPixel();
//Rotate Image.
cv::Mat dst = rotateImage(180);
// Marking candidates.
cv::Mat src_copy = dst.clone();
if(image_points_.size() > 0){
// Draws the rect in the original image and show it.
for(int i=0; i<image_points_.size();++i){
cv::Point point = image_points_[i];
int x_start = point.x - cone_.width_pixel;
int y_start = point.y + cone_.height_pixel/2;
if(x_start < cam_.image_width-cone_.width_pixel && x_start > 0
&& y_start < cam_.image_height-cone_.height_pixel && y_start > 0){
cv::Mat cropped = croppImage(dst, x_start, y_start);
//Push back vectors.
candidates_.push_back(cropped);
candidate_indizes_.push_back(xyz_index_vector[i].index);
//Save and show candidate.
std::string name = candidate_path_ + "candidates/" + numberToString(xyz_index_vector[i].index) + ".jpg";
cv::imwrite(name, cropped);
cv::Point pt1(x_start, y_start);
cv::Point pt2(x_start+cone_.width_pixel,y_start-cone_.height_pixel);
cv::rectangle(src_copy, pt1, pt2, CV_RGB(255,0,0), 1);
}
}
}
cv::imshow("candidates", src_copy);
cv::waitKey(10);
}
void ImageHandler::showCones(Pose pose){
//Rotate image.
cv::Mat dst = rotateImage(180);
//Convert to global and show boundary boxes.
std::vector<Eigen::Vector2d> cones;
for(int i=0; i<cones_global_poses_.size(); ++i)
cones.push_back(pose.globalToLocal(cones_global_poses_[i]));
//Search for cones in front of car.
std::vector<Eigen::Vector2d> cones_in_front;
for(int i=0; i<cones.size(); ++i)
if(cones[i](0) > 0) cones_in_front.push_back(cones[i]);
//Show only image iff no cones in front.
cv::Mat src_copy = dst.clone();
if(cones_in_front.size() == 0){
cv::imshow("cones", src_copy);
cv::waitKey(5);
return;
}
//Convert to pixel.
object_points_.clear();
image_points_.clear();
for(int i=0; i<cones_in_front.size(); ++i){
cv::Point3d point;
point.z = cones_in_front[i](0);
point.x = -cones_in_front[i](1);
point.y = - (-1.33);
object_points_.push_back(point);
}
transformPointToPixel();
if(image_points_.size() > 0){
// Draws the rect in the original image and show it.
for(int i=0; i<image_points_.size();++i){
cv::Point point = image_points_[i];
int x_start = point.x - cone_.width_pixel;
int y_start = point.y;
if(x_start < cam_.image_width-cone_.width_pixel && x_start > 0
&& y_start < cam_.image_height-cone_.height_pixel && y_start > 0){
cv::Point pt1(x_start, y_start-cone_.height_pixel);
cv::Point pt2(x_start+cone_.width_pixel, y_start);
cv::rectangle(src_copy, pt1, pt2, CV_RGB(255,0,0), 1);
}
}
}
cv::imshow("cones", src_copy);
cv::waitKey(5);
}
void ImageHandler::transformPointToPixel(){
//Projecting.
if(object_points_.size() > 0){
cv::projectPoints(object_points_, cam_.rVec, cam_.tVec, cam_.intrisicMat, cam_.distCoeffs, image_points_);
}
}
std::vector<cv::Mat> ImageHandler::getCandidateVector(){return candidates_;}
std::vector<int> ImageHandler::getCandidateIndexVector(){return candidate_indizes_;}
cv_bridge::CvImagePtr ImageHandler::getImagePtr(){return cv_ptr_;}
sensor_msgs::Image ImageHandler::getSensorMsg(const cv::Mat base_image){
cv::Mat temp_image = cv_ptr_->image;
cv_bridge::CvImagePtr temp_ptr = cv_ptr_;
temp_ptr->image = base_image;
sensor_msgs::Image image_ptr = *temp_ptr->toImageMsg();
cv_ptr_->image = temp_image;
return image_ptr;
}
std::string ImageHandler::numberToString(int number){
std::stringstream ss;
ss << number;
return ss.str();
}
cv::Mat ImageHandler::croppImage(cv::Mat src, int x_start, int y_start){
cv::Rect rect(abs(x_start), abs(y_start-cone_.height_pixel),
cone_.width_pixel,cone_.height_pixel);
cv::Mat cropped(src, rect);
return cropped;
}
cv::Mat ImageHandler::rotateImage(double angle){
cv::Mat dst;
cv::Mat src = cv_ptr_->image;
cv::Point2f pt(cam_.image_width/2., cam_.image_height/2.);
cv::Mat rot = cv::getRotationMatrix2D(pt, angle, 1.0);
cv::warpAffine(src, dst, rot, cv::Size(cam_.image_width, cam_.image_height));
return dst;
}
void ImageHandler::setConePosition(Eigen::Vector2d cone_position){
cones_global_poses_.push_back(cone_position);
}
void ImageHandler::setImgPtr(cv_bridge::CvImagePtr cv_ptr){cv_ptr_ = cv_ptr;}
| true |
dc73084c0425532a2af479ae841aee25e213df44 | C++ | suomesta/rust_samples | /023_moudle/main.cpp | UTF-8 | 302 | 3.40625 | 3 | [] | no_license | #include <iostream>
namespace my_module {
struct Point
{
int x;
int y;
};
void output(int x, int y)
{
std::cout << x << " " << y << std::endl;
}
} // namespace my_module
int main(void)
{
my_module::Point point = {10, 20};
my_module::output(point.x, point.y);
return 0;
}
| true |
ac8611307249b2853eec2bb4fe329641c8b8204c | C++ | zlatkok/swospp | /main/xml/xmlparse.cpp | UTF-8 | 30,105 | 2.5625 | 3 | [
"MIT"
] | permissive | /** xmlparse.c
Main focal point of XML parser. Made up of lexer, parser and load/save routines/support.
*/
#include <errno.h>
#include "xmlparse.h"
#include "xmltree.h"
#include "qalloc.h"
#include "bfile.h"
struct XmlNodeListElem {
XmlNode *node;
struct XmlNodeListElem *next;
};
struct XmlContentListElem {
char *content;
int size;
int totalSize;
struct XmlContentListElem *next;
};
enum XmlParserState {
STATE_START,
STATE_TAG_OPENED,
STATE_INSIDE_TAG,
STATE_GET_ATTR_EQ,
STATE_GET_ATTR_VAL,
STATE_GET_POSSIBLE_CONTENT,
STATE_END_TAG_OPENED,
STATE_EXPECT_END_TAG_CLOSE,
};
/* parser internal variables... obviously, we're not thread-safe :P */
static int lineNo;
static int linesSkipped;
static const char *xmlFile;
static bool inTag;
static void *xmlHeap;
static XmlParserState parserState;
static char *attrName;
static int attrNameLen;
static XmlNodeListElem *nodeStack;
static XmlNode *xmlRoot;
static void initializeParser(const char *fileName, void *heap, int heapSize)
{
lineNo = 1;
linesSkipped = 0;
xmlFile = strrchr(fileName, '\\');
xmlFile = xmlFile ? xmlFile + 1 : fileName;
inTag = false;
qHeapInit(heap, heapSize);
xmlHeap = heap;
parserState = STATE_START;
nodeStack = nullptr;
attrName = nullptr;
attrNameLen = 0;
xmlRoot = nullptr;
}
#ifdef DEBUG
static void report(const char *text)
{
WriteToLog("%s(%d): %s", xmlFile, lineNo, text);
}
#else
#define report(text) ((void)0)
#endif
static const char *SymToStr(XmlSymbol sym)
{
static_assert(XML_SYM_MAX == 7, "Xml symbols changed.");
switch (sym) {
case XML_SYM_TAG_OPEN:
return "<";
case XML_SYM_TAG_OPEN_END_TAG:
return "</";
case XML_SYM_TAG_CLOSE:
return ">";
case XML_SYM_TAG_CLOSE_SOLO_TAG:
return "/>";
case XML_SYM_EQ:
return "=";
case XML_SYM_TEXT:
return "<text>";
case XML_SYM_EOF:
return "end of file";
case XML_SYM_MAX:
return "invalid symbol";
default:
assert_msg(0, "who was messing with xml symbols enum?");
return "";
}
}
static void *XmlAlloc(int size)
{
void *mem = qHeapAlloc(xmlHeap, size);
assert(xmlHeap && size > 0);
if (!mem)
report("error: Out of memory.");
return mem;
}
static char *XmlStrdup(char *data, int len)
{
char *copy = (char *)XmlAlloc(len + 1);
assert(len > 0);
if (copy) {
memcpy(copy, data, len);
copy[len] = '\0';
return copy;
}
return nullptr;
}
static void XmlFree(void *ptr)
{
qHeapFree(xmlHeap, ptr);
}
static bool PushNode(XmlNode *node)
{
XmlNodeListElem *elem = (XmlNodeListElem *)XmlAlloc(sizeof(XmlNodeListElem));
assert(xmlHeap);
if (!elem)
return false;
elem->node = node;
elem->next = nodeStack;
if (nodeStack)
AddXmlNode(nodeStack->node, node);
nodeStack = elem;
return true;
}
static XmlNode *PopNode()
{
XmlNodeListElem *elem = nodeStack;
assert(xmlHeap && nodeStack);
nodeStack = nodeStack->next;
return elem->node;
}
static XmlNode *TopNode()
{
assert(xmlHeap && nodeStack);
return nodeStack->node;
}
static XmlNode *PeekTopNode()
{
assert(xmlHeap);
return nodeStack ? nodeStack->node : nullptr;
}
/** GetXmlEscape
file -> buffered XML file to read from
& was already encountered, by using state matching determine if we have XML escape, one of:
< < less than
> > greater than
& & ampersand
' ' apostrophe
" " quotation mark
Return character replacement or 0 if not escape sequence.
*/
static char GetXmlEscape(BFile *file)
{
int readChars[4]; /* hold all characters encountered so far */
int count = 1; /* keep count of read characters */
readChars[0] = GetCharBFile(file);
assert(file);
/* < */
if (readChars[0] == 'l') {
readChars[count++] = GetCharBFile(file);
if (readChars[1] == 't') {
readChars[count++] = GetCharBFile(file);
if (readChars[2] == ';')
return '<';
}
/* > */
} else if (readChars[0] == 'g') {
readChars[count++] = GetCharBFile(file);
if (readChars[1] == 't') {
readChars[count++] = GetCharBFile(file);
if (readChars[2] == ';')
return '>';
}
/* & and ' */
} else if (readChars[0] == 'a') {
readChars[count++] = GetCharBFile(file);
if (readChars[1] == 'm') {
readChars[count++] = GetCharBFile(file);
if (readChars[2] == 'p') {
readChars[count++] = GetCharBFile(file);
if (readChars[3] == ';')
return '&';
}
} else if (readChars[1] == 'p') {
readChars[count++] = GetCharBFile(file);
if (readChars[2] == 'o') {
readChars[count++] = GetCharBFile(file);
if (readChars[3] == 's') {
readChars[count++] = GetCharBFile(file);
if (readChars[4] == ';')
return '\'';
}
}
}
/* " */
} else if (readChars[0] == 'q') {
readChars[count++] = GetCharBFile(file);
if (readChars[1] == 'u') {
readChars[count++] = GetCharBFile(file);
if (readChars[2] == 'o') {
readChars[count++] = GetCharBFile(file);
if (readChars[3] == 't') {
readChars[count++] = GetCharBFile(file);
if (readChars[4] == ';')
return '"';
}
}
}
}
/* no match, return all read characters to stream */
while (count--)
UngetCharBFile(file, readChars[count]);
return 0;
}
/** GetStringEscape
file -> buffered XML file to read from
Slash inside a string was encountered, resolve and return any escaped characters.
Return -1 for invalid escape sequence.
*/
static int GetStringEscape(BFile *file)
{
int readChars[3];
size_t count = 1;
assert(file);
readChars[0] = GetCharBFile(file);
if (readChars[0] == '\\')
return '\\';
else if (readChars[0] == 'n')
return '\n';
else if (readChars[0] == 'r')
return '\r';
else if (readChars[0] == 't')
return '\t';
else if (readChars[0] == 'b')
return '\b';
else if (readChars[0] == '"')
return '"';
else if (readChars[0] == '\'')
return '\'';
else if (readChars[0] == 'x') {
uint32_t val = 0;
int c;
int hexCount = 0;
while (c = GetCharBFile(file), isxdigit(c) && hexCount++ < 2) {
if (count < sizeofarray(readChars)) {
readChars[count++] = c;
val = (val << 4) | (c > '9' ? (c | 0x20) - 'a' + 10 : c - '0');
}
}
UngetCharBFile(file, c);
if (!hexCount)
report("\\x used with no following hex digits.");
if (hexCount > 0)
return val & 0xff;
} else if (isdigit(readChars[0])) {
int c;
int digitCount = 1;
int val = readChars[0] - '0';
while (c = GetCharBFile(file), isdigit(c)) {
if (count < sizeofarray(readChars)) {
/* screw octal, who the hell needs that */
readChars[count++] = c;
val = val * 10 + c - '0';
}
digitCount++;
}
UngetCharBFile(file, c);
if (digitCount > 3 || val > 255)
report("Numeric escape sequence out of range.");
return val & 0xff;
}
/* no match, return all read characters to stream */
assert((int)count >= 0 && count < sizeofarray(readChars));
while (count--)
UngetCharBFile(file, readChars[count]);
return -1;
}
/** SkipXmlComment
file -> buffered XML file to read from
Start XML comment symbol has already been found, now skip everything until end of comment symbol.
*/
static void SkipXmlComment(BFile *file)
{
int c;
int count;
char readChars[2];
assert(file);
while ((c = GetCharBFile(file)) >= 0) {
count = 0;
if (c == '-') {
readChars[count++] = GetCharBFile(file);
if (readChars[0] == '-') {
readChars[count++] = GetCharBFile(file);
if (readChars[1] == '>')
return;
}
} else if (c == '\n')
lineNo++;
while (count--)
UngetCharBFile(file, readChars[count]);
}
if (c < 0)
report("Unterminated comment found.");
UngetCharBFile(file, c);
}
/** GetText
file -> buffered XML file to read from
inTag - true if we are inside XML tag, break text into tokens then
buf -> buffer to receive collected text
bufSize -> maximum size of text buffer
Terminate buffer with zero and return number of characters written to buffer (not counting ending zero).
Any text blocks interspersed with strings will be merged and returned as a single block.
*/
static int GetText(BFile *file, bool inTag, char *buf, int bufSize)
{
int c;
int inQuote = 0;
char *p = buf, *stringEnd = buf;
assert(file);
assert(bufSize >= 0);
assert(buf);
/* get rid of initial whitespace */
while (isspace(PeekCharBFile(file)))
lineNo += GetCharBFile(file) == '\n';
while ((c = GetCharBFile(file)) >= 0) {
if (c == '&') {
char escaped = GetXmlEscape(file);
if (escaped)
c = escaped;
} else if (c == '"') {
/* get rid of whitespaces before and after strings */
if (!(inQuote ^= 1)) {
stringEnd = max(p - 1, buf);
if (!inTag)
while (isspace(PeekCharBFile(file)))
lineNo += GetCharBFile(file) == '\n';
} else
while (p - 1 > stringEnd && isspace(p[-1]))
lineNo -= *--p == '\n';
continue;
} else if (inQuote) {
if (c == '\\') {
int escaped = GetStringEscape(file);
if (escaped >= 0)
c = escaped;
}
} else if (c == '<') {
/* we can't warn about nested tags here, as it might only be a comment */
UngetCharBFile(file, '<');
break;
} else if (c == '/') {
if (PeekCharBFile(file) == '>') {
UngetCharBFile(file, '/');
break;
}
} else if (c == '>') {
UngetCharBFile(file, '>');
break;
} else if (inTag) {
if (c == '=') {
UngetCharBFile(file, '=');
break;
} else if (isspace(c)) {
while (isspace(PeekCharBFile(file)))
lineNo += GetCharBFile(file) == '\n';
break;
}
}
if (bufSize > 0) {
*p++ = c;
bufSize--;
lineNo += c == '\n';
}
}
if (inQuote) {
report("Unterminated string found.");
} else {
/* remove trailing whitespace if not quoted */
if (p > buf) {
int currentLineNo = lineNo;
while (isspace(p[-1]) && p > stringEnd + 1)
lineNo -= *--p == '\n';
/* we have to report line number for this symbol correctly, but we also have to
maintain correct line number for the symbol that follows */
linesSkipped = currentLineNo - lineNo;
assert(linesSkipped >= 0);
}
}
assert(p >= buf);
if (bufSize > 0)
*p = '\0';
else if (p > buf)
*--p = '\0';
return p - buf;
}
/** GetSymbol
file -> buffered file to read from
buf -> buffer to store found text to
bufSize -> the size of given buffer on entry,
number of characters written on exit
Main lexer routine. Return symbol found, along with text, if any. Buffer will always be
null-terminated if it's size is at least one. Size returned will not include ending zero.
*/
static XmlSymbol GetSymbol(BFile *file, char *buf, int *bufSize)
{
int numCharsMatched;
int matchedChars[3];
int c = GetCharBFile(file);
lineNo += linesSkipped;
linesSkipped = 0;
switch (c) {
case '<':
/* this could be open tag, open ending tag or an xml comment */
numCharsMatched = 1;
matchedChars[0] = GetCharBFile(file);
if (matchedChars[0] == '/') {
inTag = true;
return XML_SYM_TAG_OPEN_END_TAG;
} else if (matchedChars[0] == '!') {
matchedChars[numCharsMatched++] = GetCharBFile(file);
if (matchedChars[1] == '-') {
matchedChars[numCharsMatched++] = GetCharBFile(file);
if (matchedChars[2] == '-') {
SkipXmlComment(file);
return GetSymbol(file, buf, bufSize);
}
}
}
while (numCharsMatched--)
UngetCharBFile(file, matchedChars[numCharsMatched]);
inTag = true;
return XML_SYM_TAG_OPEN;
case '>':
inTag = false;
return XML_SYM_TAG_CLOSE;
case '/':
if (PeekCharBFile(file) == '>') {
GetCharBFile(file);
inTag = false;
return XML_SYM_TAG_CLOSE_SOLO_TAG;
}
break;
case '=':
if (inTag)
return XML_SYM_EQ;
break;
case -1:
return XML_SYM_EOF;
}
UngetCharBFile(file, c);
/* don't return 0-sized text */
return (*bufSize = GetText(file, inTag, buf, *bufSize)) ? XML_SYM_TEXT : GetSymbol(file, buf, bufSize);
}
static bool Expect(XmlSymbol expected, XmlSymbol given)
{
if (expected != given) {
WriteToLog("%s(%d): error: Expected '%s', got '%s' instead.",
xmlFile, lineNo, SymToStr(expected), SymToStr(given));
return false;
}
return true;
}
static bool FixXmlNodeContent(XmlNode *node)
{
XmlContentListElem *elem;
char *contents;
int currentOffset, totalSize;
assert(node);
if (node->type != XML_STRING && node->type != XML_ARRAY)
return true;
if (node->type == XML_STRING && !node->value.ptr) {
node->value.ptr = (char *)XmlAlloc(1);
node->value.ptr[0] = '\0';
node->length = 1;
return true;
}
assert(node->value.ptr);
totalSize = ((XmlContentListElem *)node->value.ptr)->totalSize;
assert(totalSize > 0);
contents = (char *)XmlAlloc(totalSize + (node->type == XML_STRING));
assert(contents);
if (!contents)
return false;
elem = (XmlContentListElem *)node->value.ptr;
currentOffset = totalSize;
if (node->type == XML_STRING)
contents[currentOffset] = '\0';
while (elem) {
currentOffset -= elem->size;
memcpy(contents + currentOffset, elem->content, elem->size);
elem = elem->next;
}
assert(currentOffset == 0);
node->value.ptr = contents;
node->length = totalSize + (node->type == XML_STRING);
return true;
}
static bool AddXmlPartialContent(XmlNode *node, char *content, int size)
{
int value, error, length;
const char *endPtr;
bool outOfRange = false;
XmlNodeType type;
assert(node && content && size >= 0);
type = XmlNodeGetType(node);
if (type == XML_EMPTY) {
report("error: Empty node can't have content.");
return false;
} else if (type != XML_STRING && type != XML_ARRAY) {
if (XmlNodeHasContent(node)) {
report("error: Only strings and arrays are allowed to be splitted.");
return false;
}
switch (type) {
case XML_CHAR:
case XML_SHORT:
case XML_INT:
value = strtol(content, &endPtr, 10, &error);
if (error == ERANGE)
outOfRange = true;
else if (error == EZERO && endPtr == content + size) {
if (type == XML_CHAR && (value < -128 || value > 127))
outOfRange = true;
else if (type == XML_SHORT && (value < -32768 || value > 32767))
outOfRange = true;
}
if (outOfRange) {
report("Numerical value out of specified range.");
} else if (error != EZERO || endPtr != content + size) {
report("error: Invalid numerical constant.");
return false;
}
length = 1;
if (type == XML_SHORT)
length = 2;
else if (type == XML_INT)
length = 4;
return AddXmlContent(node, type, &value, length);
default:
return AddXmlContent(node, type, content, size);
}
} else {
XmlContentListElem *lastElem = (XmlContentListElem *)node->value.ptr;
XmlContentListElem *elem = (XmlContentListElem *)XmlAlloc(sizeof(XmlContentListElem));
if (!elem)
return false;
elem->content = XmlStrdup(content, size);
elem->size = elem->totalSize = size;
if (lastElem)
elem->totalSize += lastElem->totalSize;
elem->next = lastElem;
node->value.ptr = (char *)elem;
}
return true;
}
/** ProcessSymbol
sym - symbol found
buf -> buffer containing symbol data; always zero-terminated if size is at least 1
bufSize - size of given buffer
Parsing work horse. Driven by state machine. Goes to next state based on current state and input.
*/
static bool ProcessSymbol(XmlSymbol sym, char *buf, int bufSize)
{
XmlNode *newNode;
switch (parserState) {
case STATE_START:
if (sym == XML_SYM_EOF) {
if (!xmlRoot) {
report("error: Root element missing.");
return false;
}
return true;
}
if (!PeekTopNode() && !Expect(XML_SYM_TAG_OPEN, sym))
return false;
parserState = STATE_TAG_OPENED;
return true;
case STATE_TAG_OPENED:
if (!Expect(XML_SYM_TEXT, sym))
return false;
assert(bufSize);
parserState = STATE_INSIDE_TAG;
/* new node opened, it is root if node stack is empty */
newNode = NewEmptyXmlNode(buf, bufSize);
if (!PeekTopNode()) {
if (xmlRoot) {
report("error: More than one root element found.");
return false;
}
xmlRoot = newNode;
}
return PushNode(newNode);
case STATE_INSIDE_TAG:
if (sym == XML_SYM_TAG_CLOSE || sym == XML_SYM_TAG_CLOSE_SOLO_TAG) {
assert(TopNode());
if (sym == XML_SYM_TAG_CLOSE_SOLO_TAG) {
if (!FixXmlNodeContent(TopNode()))
return false;
PopNode();
}
parserState = PeekTopNode() ? STATE_GET_POSSIBLE_CONTENT : STATE_START;
return true;
} else if (sym == XML_SYM_TEXT) {
XmlFree(attrName);
if (!(attrName = XmlStrdup(buf, bufSize)))
return false;
attrNameLen = bufSize;
parserState = STATE_GET_ATTR_EQ;
return true;
} else {
char error[128];
sprintf(error, "error: Unexpected symbol '%s' inside a tag.", SymToStr(sym));
report(error);
return false;
}
/* assume fall-through */
case STATE_GET_ATTR_EQ:
if (!Expect(XML_SYM_EQ, sym))
return false;
parserState = STATE_GET_ATTR_VAL;
return true;
case STATE_GET_ATTR_VAL:
if (!(Expect(XML_SYM_TEXT, sym)))
return false;
parserState = STATE_INSIDE_TAG;
assert(attrName && attrNameLen);
return AddXmlNodeAttribute(TopNode(), attrName, attrNameLen, buf, bufSize);
case STATE_GET_POSSIBLE_CONTENT:
if (sym == XML_SYM_TEXT) {
/* remain in this state */
return AddXmlPartialContent(TopNode(), buf, bufSize);
} else if (sym == XML_SYM_TAG_OPEN) {
parserState = STATE_TAG_OPENED;
return true;
} else if (sym == XML_SYM_TAG_OPEN_END_TAG) {
parserState = STATE_END_TAG_OPENED;
return true;
} else {
char error[128];
sprintf(error, "error: Unexpected symbol '%s' found inside tag content.", SymToStr(sym));
report(error);
return false;
}
/* assume fall-through */
case STATE_END_TAG_OPENED:
if (!Expect(XML_SYM_TEXT, sym))
return false;
if (strncmp(TopNode()->name, buf, bufSize)) {
report("error: Closing tag doesn't match opening.");
return false;
}
parserState = STATE_EXPECT_END_TAG_CLOSE;
return true;
case STATE_EXPECT_END_TAG_CLOSE:
if (!Expect(XML_SYM_TAG_CLOSE, sym))
return false;
if (!FixXmlNodeContent(TopNode()))
return false;
PopNode();
/* go back to start state if we're not inside any tag */
parserState = PeekTopNode() ? STATE_GET_POSSIBLE_CONTENT : STATE_START;
return true;
default:
assert_msg(0, "Unhandled xml parser state encountered.");
}
return false;
}
bool LoadXmlFile(XmlNode **root, const char *fileName, XmlSymbolProcessingFunction symProc)
{
XmlSymbol sym;
char xmlBuf[8 * 1024];
int bufSize = sizeof(xmlBuf);
char miniHeap[32 * 1024];
bool success = true;
BFile *file;
if (root)
*root = nullptr;
if (!(file = OpenBFile(F_READ_ONLY, fileName)))
return false;
initializeParser(fileName, miniHeap, sizeof(miniHeap));
auto oldSplitSize = qSetMinSplitSize(16);
if (!symProc)
symProc = ProcessSymbol;
while ((sym = GetSymbol(file, xmlBuf, &bufSize)) != XML_SYM_EOF) {
//WriteToLog("state: %d symbol: %s '%s'", parserState, SymToStr(sym), sym == XML_SYM_TEXT ? xmlBuf : "");
if (!symProc(sym, xmlBuf, bufSize)) {
qSetMinSplitSize(oldSplitSize);
CloseBFile(file);
return false;
}
bufSize = sizeof(xmlBuf);
}
/* notify callback about EOF too */
success = symProc(sym, xmlBuf, bufSize);
CloseBFile(file);
qSetMinSplitSize(oldSplitSize);
if (root) {
ReverseChildren(xmlRoot);
*root = xmlRoot;
}
return success;
}
static bool NeedsQuotes(const char *str, size_t len)
{
assert(str);
while (len--) {
if (*str < 32 || *str > 126)
return true;
switch (*str) {
case '"':
case '=':
case '<':
case '>':
case '/':
case '\\':
case ' ':
return true;
}
str++;
}
return false;
}
/* saves a lot of typing :P */
#define OUT_CHAR(c) { if (!PutCharBFile(file, c)) return false; }
#define OUT_STR(str, len) { if (!WriteStringToFile(file, str, len, indent, true)) return false; }
#define INDENT(len) { int i; for (i = 0; i < (len); i++) OUT_CHAR(' '); }
static bool WriteStringToFile(BFile *file, const char *string, size_t stringLen, int indent, bool zeroTerminated)
{
assert(file && string);
if (NeedsQuotes(string, stringLen)) {
int lineChars = indent + 1 + 4;
OUT_CHAR('"');
while (stringLen-- && (!zeroTerminated || *string)) {
if (*string < 32 || *string > 126) {
int hiByte = (*string & 0xf0) >> 4;
int loByte = *string & 0x0f;
OUT_CHAR('\\');
OUT_CHAR('x');
OUT_CHAR(hiByte + (hiByte > 9 ? 'a' - 10 : '0'));
OUT_CHAR(loByte + (loByte > 9 ? 'a' - 10 : '0'));
lineChars += 4;
} else if (*string == '"') {
OUT_CHAR('\\');
OUT_CHAR('"');
lineChars += 2;
} else if (*string == '\\') {
OUT_CHAR('\\');
OUT_CHAR('\\');
lineChars += 4;
} else if (*string == '\r') {
OUT_CHAR('\\');
OUT_CHAR('r');
lineChars += 4;
} else if (*string == '\n') {
OUT_CHAR('\\');
OUT_CHAR('n');
lineChars += 4;
} else if (*string == '\t') {
OUT_CHAR('\\');
OUT_CHAR('t');
lineChars += 4;
} else {
OUT_CHAR(*string);
lineChars++;
}
string++;
if (lineChars > 99 && stringLen) {
OUT_CHAR('"');
OUT_CHAR('\n');
INDENT(indent + 4);
OUT_CHAR('"');
lineChars = indent + 1 + 4;
}
}
OUT_CHAR('"');
return true;
} else {
if (stringLen > 100) {
while (stringLen > 0) {
INDENT(indent);
OUT_CHAR('"');
if (WriteBFile(file, string, 100) != 100)
return false;
OUT_CHAR('"');
OUT_CHAR('\n');
stringLen -= 100;
}
return true;
} else
return WriteBFile(file, string, stringLen) == (int)stringLen;
}
}
static bool WriteNodeContent(BFile *file, const XmlNode *node, int indent)
{
int val = 0;
char *numStr;
assert(file && node);
switch (XmlNodeGetType(node)) {
case XML_CHAR:
val = *node->value.charVal;
break;
case XML_SHORT:
val = *node->value.shortVal;
break;
case XML_INT:
val = *node->value.intVal;
break;
case XML_STRING:
case XML_ARRAY:
return WriteStringToFile(file, node->value.ptr, node->length - XmlNodeIsString(node),
indent, XmlNodeIsString(node));
case XML_EMPTY:
case XML_FUNC: // FIXME
return true;
default:
assert_msg(0, "Don't know how to write this content type!");
}
numStr = int2str(val);
return WriteBFile(file, numStr, strlen(numStr));
}
static bool WriteTreeToFile(BFile *file, const XmlNode *root, int indent)
{
bool soloNode = false;
bool isNumericNode;
static XmlAttributeInfo attributes[64];
size_t numAttributes;
if (!root || XmlNodeIsAnonymous(root))
return true;
do {
if (XmlNodeIsAnonymous(root)) {
root = XmlNodeGetNextSibling(root);
continue;
}
isNumericNode = XmlNodeIsNumeric(root);
/* open tag and write name */
INDENT(indent);
OUT_CHAR('<');
OUT_STR(XmlNodeGetName(root), XmlNodeGetNameLength(root));
numAttributes = GetXmlNodeNumAttributes(root);
/* make sure to write type attribute even if it's not explicitly added, and in 1st spot */
if (!XmlNodeIsEmpty(root) && !XmlNodeIsFunc(root) && !GetXmlNodeAttribute(root, "type", 4, nullptr)) {
size_t typeNameLen;
const char *typeName = XmlNodeTypeToString(XmlNodeGetType(root), &typeNameLen);
OUT_CHAR(' ');
OUT_STR("type", 4);
OUT_CHAR('=');
OUT_CHAR('"');
OUT_STR(typeName, typeNameLen);
OUT_CHAR('"');
}
/* write other attributes, if present */
assert(numAttributes <= sizeofarray(attributes));
GetXmlNodeAttributes(root, attributes);
for (size_t i = 0; i < numAttributes; i++) {
OUT_CHAR(' ');
OUT_STR(attributes[i].name, attributes[i].nameLength);
OUT_CHAR('=');
OUT_STR(attributes[i].value, attributes[i].valueLength);
}
if (XmlNodeIsLeaf(root) && !XmlNodeHasContent(root)) {
soloNode = true;
OUT_CHAR(' ');
OUT_CHAR('/');
} else
soloNode = false;
OUT_CHAR('>');
/* tag closed, write content, if present */
if (XmlNodeHasContent(root)) {
if (!isNumericNode) {
OUT_CHAR('\n');
INDENT(indent + 4);
}
if (!WriteNodeContent(file, root, indent))
return false;
if (!isNumericNode)
OUT_CHAR('\n');
} else
OUT_CHAR('\n');
/* handle custom data nodes */
if (XmlNodeIsFunc(root))
RefreshFuncData(root);
/* write subtree if present */
if (!XmlNodeIsLeaf(root) && !WriteTreeToFile(file, root->children, indent + (soloNode ? 0 : 4)))
return false;
if (!soloNode) {
if (!isNumericNode)
INDENT(indent);
OUT_CHAR('<');
OUT_CHAR('/');
OUT_STR(XmlNodeGetName(root), XmlNodeGetNameLength(root));
OUT_CHAR('>');
OUT_CHAR('\n');
}
root = XmlNodeGetNextSibling(root);
} while (root);
return true;
}
bool SaveXmlFile(XmlNode *root, const char *fileName, bool checkIfNeeded)
{
BFile *file;
bool result;
if (!root)
return false;
if (checkIfNeeded && XmlTreeUnmodified(root)) {
WriteToLog("%s not modified, returning.", fileName);
return true;
}
if (!(file = CreateBFile(ATTR_NONE, fileName))) {
WriteToLog("Failed to create %s.", fileName);
return false;
}
/* mark it as unmodified if we saved it successfully */
if ((result = WriteTreeToFile(file, root, 0)))
XmlTreeSnapshot(root);
if (result)
WriteToLog("%s written successfully.", fileName);
CloseBFile(file);
return result;
}
| true |
38fccfa507b0586b2c90e70b061c1fe7f5c4a998 | C++ | jiangtaojiang/PiMower | /Arduino/UILibrary/UILibrary/Utility/Logger.h | UTF-8 | 625 | 2.75 | 3 | [] | no_license | #pragma once
#include "Arduino.h"
#include <string>
#include <sstream>
#ifndef LOGGING_ENABLED
class Logger
{
public:
enum LogLevel
{
TRACE = 0,
WARN = 1,
CRITICAL =2,
FATAL = 3
};
static void Trace(const char *fmt, ...);
static void Warn(const char *fmt, ...);
static void Crit(const char *fmt, ...);
static void Fatal(const char *fmt, ...);
static void initLogger(LogLevel minimumLevel);
static void initLogger(LogLevel minimumLevel, long baudRate);
private:
static LogLevel minLevel;
static HardwareSerial *serial;
static std::string buildString(LogLevel level, const char *fmt, ...);
};
#endif
| true |
a09a22173e0078f69b776cdbb74c85f3ee6c41a7 | C++ | yijiantao/WorkSpace | /LeetCode Algorithms/20.有效的括号.cpp | UTF-8 | 649 | 3.359375 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=20 lang=cpp
*
* [20] 有效的括号
*/
// @lc code=start
class Solution {
public:
bool isValid(string s) {
stack<char> res;
for (auto _c: s) {
if (_c == '(' || _c == '{' || _c == '[') res.push(_c);
else {
if (_c == ')' && res.size() >= 1 && res.top() == '(') res.pop();
else if (_c == ']' && res.size() >= 1 && res.top() == '[') res.pop();
else if (_c == '}' && res.size() >= 1 && res.top() == '{') res.pop();
else return false;
}
}
return res.empty();
}
};
// @lc code=end
| true |
648afbcd793add49e502971cfcee0dd67947cfc9 | C++ | DrGilion/computergraphics2 | /pictureinfo.cpp | UTF-8 | 1,853 | 2.734375 | 3 | [] | no_license | #include "pictureinfo.h"
#include "imageviewer.h"
#include <string>
#include <sstream>
PictureInfo::PictureInfo() : FunctionBox("Helligkeit und Kontrast einstellen"){
layout->addRow("Helligkeit: ",brightSlider.get());
QObject::connect(brightButton.get(), QPushButton::clicked, this, PictureInfo::applyBrightness );
layout->addRow(brightButton.get());
contrastSlider->setValue(100);
contrastLayout->addRow("Kontrast: ",contrastSlider.get());
QObject::connect(contrastButton.get(), QPushButton::clicked, this, PictureInfo::applyContrast );
contrastLayout->addRow(contrastButton.get());
QObject::connect(autoContrastButton.get(), QPushButton::clicked, this, PictureInfo::applyAutomaticContrast );
//contrastLayout->addRow(autoContrastButton.get());
secondaryLayout->addLayout(contrastLayout.get());
slow->setMinimum(0);
shigh->setMinimum(0);
slow->setMaximum(100);
shigh->setMaximum(100);
robustContrastLayout->addRow("slow: ",slow.get());
shigh->setValue(100);
robustContrastLayout->addRow("shigh: ",shigh.get());
robustContrastLayout->addRow(robustContrastButton.get());
QObject::connect(robustContrastButton.get(), QPushButton::clicked, this, PictureInfo::applyRobustContrast );
secondaryLayout->addLayout(robustContrastLayout.get());
layout->addRow(secondaryLayout.get());
}
void PictureInfo::applyBrightness(){
Controller::instance()->changeBrightness(brightSlider->value());
}
void PictureInfo::applyContrast(){
Controller::instance()->changeContrast(contrastSlider->value()/100.0);
}
void PictureInfo::applyAutomaticContrast(){
Controller::instance()->automaticContrast(brightSlider->value(),contrastSlider->value()/100.0);
}
void PictureInfo::applyRobustContrast(){
Controller::instance()->robustContrast(slow->value(),shigh->value());
}
| true |
5df9ce8468e716de394835c4dc0684a1fcbbe85a | C++ | eagle518/rest_rpc | /rest_rpc/server/router.hpp | UTF-8 | 5,419 | 2.875 | 3 | [] | no_license | #pragma once
namespace timax { namespace rpc
{
template <typename Decode>
class connection;
template<typename Decode>
class router : boost::noncopyable
{
using connection_t = connection<Decode>;
public:
static router<Decode>& get()
{
static router instance;
return instance;
}
template<typename Function, typename AfterFunction>
void register_handler(std::string const & name, const Function& f, const AfterFunction& af)
{
register_nonmember_func(name, f, af);
}
template<typename Function, typename AfterFunction, typename Self>
void register_handler(const std::string& name, const Function& f, Self* self, const AfterFunction& af)
{
register_member_func(name, f, self, af);
}
void remove_handler(std::string const& name)
{
this->invokers_.erase(name);
}
bool has_handler(std::string const& func_name)
{
return invokers_.find(func_name) != invokers_.end();
}
void route(std::shared_ptr<connection_t> conn, const char* data, size_t size)
{
std::string func_name = data;
auto it = invokers_.find(func_name);
if (it != invokers_.end())
{
auto length = func_name.length();
blob bl = { data + length + 1, static_cast<uint32_t>(size - length - 1) };
it->second(conn, bl);
}
}
private:
router() = default;
router(const router&) = delete;
router(router&&) = delete;
template<typename Function, typename AfterFunction>
void register_nonmember_func(std::string const & name, const Function& f, const AfterFunction& afterfunc)
{
using std::placeholders::_1;
using std::placeholders::_2;
this->invokers_[name] = { std::bind(&invoker<Function, AfterFunction>::apply, f, afterfunc, _1, _2) };
}
template<typename Function, typename AfterFunction, typename Self>
void register_member_func(const std::string& name, const Function& f, Self* self, const AfterFunction& afterfunc)
{
using std::placeholders::_1;
using std::placeholders::_2;
this->invokers_[name] = { std::bind(&invoker<Function, AfterFunction>::template apply_member<Self>, f, self, afterfunc, _1, _2) };
}
template<typename Function, typename AfterFunction>
struct invoker
{
static inline void apply(const Function& func, const AfterFunction& afterfunc, std::shared_ptr<connection_t> conn, blob bl)
{
using tuple_type = typename function_traits<Function>::tuple_type;
try
{
Decode dr;
tuple_type tp = dr.template unpack<tuple_type>(bl.ptr, bl.size);
call(func, afterfunc, conn, tp);
}
catch (const std::exception& ex)
{
SPD_LOG_ERROR(ex.what());
conn->close();
}
catch (...)
{
conn->close();
}
}
template<typename F, typename ... Args>
static typename std::enable_if<std::is_void<typename std::result_of<F(Args...)>::type>::value>::type
call(const F& f, const AfterFunction& af, std::shared_ptr<connection_t> conn, const std::tuple<Args...>& tp)
{
call_helper(f, std::make_index_sequence<sizeof... (Args)>{}, tp);
if(af)
af(conn);
}
template<typename F, typename ... Args>
static typename std::enable_if<!std::is_void<typename std::result_of<F(Args...)>::type>::value>::type
call(const F& f, const AfterFunction& af, std::shared_ptr<connection_t> conn, const std::tuple<Args...>& tp)
{
auto r = call_helper(f, std::make_index_sequence<sizeof... (Args)>{}, tp);
if(af)
af(conn, r);
}
template<typename F, size_t... I, typename ... Args>
static auto call_helper(const F& f, const std::index_sequence<I...>&, const std::tuple<Args...>& tup)
{
return f(std::get<I>(tup)...);
}
//member function
template<typename Self>
static inline void apply_member(const Function& func, Self* self, const AfterFunction& afterfunc, std::shared_ptr<connection_t> conn, blob bl)
{
using tuple_type = typename function_traits<Function>::tuple_type;
try
{
Decode dr;
tuple_type tp = dr.template unpack<tuple_type>(bl.ptr, bl.size);
call_member(func, self, afterfunc, conn, tp);
}
catch (const std::exception& ex)
{
SPD_LOG_ERROR(ex.what());
conn->close();
}
catch (...)
{
conn->close();
}
}
template<typename F, typename Self, typename ... Args>
static inline std::enable_if_t<std::is_void<typename std::result_of<F(Self, Args...)>::type>::value>
call_member(const F& f, Self* self, const AfterFunction& af, std::shared_ptr<connection_t> conn, const std::tuple<Args...>& tp)
{
call_member_helper(f, self, std::make_index_sequence<sizeof... (Args)>{}, tp);
af(conn);
}
template<typename F, typename Self, typename ... Args>
static inline std::enable_if_t<!std::is_void<typename std::result_of<F(Self, Args...)>::type>::value>
call_member(const F& f, Self* self, const AfterFunction& af, std::shared_ptr<connection_t> conn, const std::tuple<Args...>& tp)
{
auto r = call_member_helper(f, self, std::make_index_sequence<sizeof... (Args)>{}, tp);
af(conn, r);
}
template<typename F, typename Self, size_t... Indexes, typename ... Args>
static auto call_member_helper(const F& f, Self* self, const std::index_sequence<Indexes...>&, const std::tuple<Args...>& tup)
{
return (*self.*f)(std::get<Indexes>(tup)...);
}
};
std::map<std::string, std::function<void(std::shared_ptr<connection_t>, blob)>> invokers_;
};
} }
| true |
5c446cc923584e0199aea12c0ac20033c1d692e6 | C++ | Fexilus/DAT205-Project | /src/mousepicking/picking.cpp | UTF-8 | 1,101 | 2.546875 | 3 | [] | no_license | #include "picking.h"
#include <glm/gtc/matrix_transform.hpp>
// Returns a movement vector in model space
glm::vec3 mousepicking::moveAlongPlane(glm::vec3 oldModelCoord, glm::vec2 newWinCoord, glm::mat4 modelViewMatrix, glm::mat4 projMatrix, glm::vec4 viewport, glm::vec3 modelSpacePlaneNormal)
{
float oldRelativePlaneHeight = glm::dot(oldModelCoord, glm::normalize(modelSpacePlaneNormal));
glm::vec3 modelSpaceNewMin = glm::unProject(glm::vec3(newWinCoord, 0), modelViewMatrix, projMatrix, viewport);
glm::vec3 modelSpaceNewMax = glm::unProject(glm::vec3(newWinCoord, 1), modelViewMatrix, projMatrix, viewport);
float newMinRelativePlaneHeight = glm::dot(modelSpaceNewMin, glm::normalize(modelSpacePlaneNormal));
float newMaxRelativePlaneHeight = glm::dot(modelSpaceNewMax, glm::normalize(modelSpacePlaneNormal));
float newMixVal = (oldRelativePlaneHeight - newMinRelativePlaneHeight) / (newMaxRelativePlaneHeight - newMinRelativePlaneHeight);
glm::vec3 modelSpaceNewPoint = (1 - newMixVal) * modelSpaceNewMin + newMixVal * modelSpaceNewMax;
return modelSpaceNewPoint - oldModelCoord;
}
| true |
0becfa4a8b23cbde6a4a7f12078bb46c05559321 | C++ | MahmoudKhaledAli/Flowchart-Simulator | /Actions/AddCond.h | UTF-8 | 885 | 3.046875 | 3 | [] | no_license | #ifndef ADD_COND_H
#define ADD_COND_H
#include "Action.h"
#include "..\Statements\Cond.h"
//Add Conditional Statement Action
//This class is responsible for
// 1 - Getting Conditional stat. coordinates from the user
// 2 - Creating an object of Cond class and fill it parameters
// 3 - Adding the created object to the list of statements
class AddCond : public Action
{
private:
Point Position;
string LHS; //Left Handside of the assignment (name of a variable)
OperandType RHSType; //type of RHS (variable or value)
string COp; //Operator
double RHSValue; //if the RHS is a value
string RHSVariable; //if the RHS is a variable
string Com; //Comment on the statement
public:
AddCond(ApplicationManager *pAppManager);
//Read parameters of conditional stat
virtual void ReadActionParameters();
//creating object of condition stat type
virtual void Execute();
};
#endif | true |
6cf5c5adfda7bfbc8e8ecc5fabd9ac2b0bf445c6 | C++ | kapil8882001/Coding-Practice-1 | /C++ Solutions/HashTable/LC290_WordPattern.cpp | UTF-8 | 1,472 | 3.59375 | 4 | [] | no_license | // 290. Word Pattern
/*
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.
*/
bool wordPattern(string pattern, string str) {
if(pattern.size() == 0 && str.size() == 0) return true;
if(pattern.size() == 0 || str.size() == 0) return false;
istringstream ss(str);
string token;
unordered_map<char, string> mp;
int pos = 0;
set<string> deduplicate; // avoid multiple tokens have the same key
while(pos < pattern.size() && std::getline(ss, token, ' ')) {
char c = pattern[pos];
if(mp.find(c) == mp.end()){
if(deduplicate.find(token) != deduplicate.end()) return false;
mp[c] = token;
deduplicate.insert(token);
}else{
if(mp[c] != token) return false;
}
pos++;
}
token.clear();
getline(ss, token, ' ');
return pos == pattern.size() && token.empty();
} | true |
e15776ccceee0d126aec59189fea10e3fe785f29 | C++ | pysoftmac/LeetCode-OJ | /Search for a Range.cpp | UTF-8 | 831 | 3.265625 | 3 | [] | no_license | #include "util.h"
class Solution {
public:
vector<int> searchRange(int A[], int n, int target)
{
int l = 0, r = n - 1, mid;
while(l <= r)
{
mid = (l + r) / 2;
if(A[mid] >= target)
r = mid - 1;
else
l = mid + 1;
}
int left = l;
l = 0, r = n - 1;
while(l <= r)
{
mid = (l + r) / 2;
if(A[mid] <= target)
l = mid + 1;
else
r = mid - 1;
}
int right = r;
vector<int> res;
if(left <= n - 1 && right >= 0 && A[left] == target)
{
res.push_back(left);
res.push_back(right);
}
else
{
res.push_back(-1);
res.push_back(-1);
}
return res;
}
void test()
{
int A[1] = {1};
vector<int> res = searchRange(A, 1, 0);
for(int i = 0; i < (int)res.size(); i++)
cout << res[i] << endl;
}
}; | true |
272290c7057995db32e0004f163e3027f46afdbe | C++ | ohlionel/codebase | /13307130248/assignment10/poj3579.cpp | UTF-8 | 924 | 2.875 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N;
vector<int> A;
void init()
{
A.resize(N);
for(int i = 0; i < N; i++)
{
scanf("%d", &A[i]);
}
sort(A.begin(), A.end());
}
long long calcNotSmaller(int dist)
{
long long count = 0;
for(vector<int>::iterator it = A.begin(); it != A.end(); it++)
{
if(*it + dist <= A[N - 1]) count += A.end() - lower_bound(it, A.end(), *it + dist);
}
return count;
}
void work()
{
int l = 0, r = 1000000000;
int bias = 1 - ((N - 1) * N / 2) % 2;
long long HalfCN2 = (long long)((N - 1) * N / 2 + 1) / 2;
while(l < r)
{
int mid = (l + r + 1) / 2;
if(calcNotSmaller(mid) >= HalfCN2 + bias)
{
l = mid;
}
else
{
r = mid - 1;
}
}
cout << r << endl;
}
int main()
{
while(scanf("%d", &N) != EOF)
{
init();
work();
}
return 0;
}
| true |
0bd886ce6d7396fcadda037d650491ced5a1a5dd | C++ | recheliu/3rd-party-lib-for-recheliu | /src/isotable/ijkmcube.v0.1/ijkmcube/ijktable.h | UTF-8 | 9,763 | 2.515625 | 3 | [] | no_license | /// \file ijktable.h
/// Class containing a table of isosurface patches in a given polyhedron.
/// All 2^numv +/- patterns are stored in the table
/// where numv = # polyhedron vertices.
/*
IJK: Isosurface Jeneration Code
Copyright (C) 2006, 2003, 2001 Rephael Wenger
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
(LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _IJKTABLE_
#define _IJKTABLE_
#include <iostream>
using namespace std;
namespace IJKTABLE {
typedef unsigned char u_char; // ADD-BY-LEETEN 04/21/2012
typedef u_char EDGE_INDEX;
typedef u_char FACET_INDEX;
typedef int TABLE_INDEX;
typedef int FACET;
const int NO_VERTEX = -1;
class ISOSURFACE_TABLE_POLYHEDRON {
protected:
int dimension;
int num_vertices;
int num_edges;
int num_facets;
int * vertex_coord;
int * edge_endpoint;
FACET * facet;
void FreeAll(); // free all memory
void Init(); // initialize
public:
ISOSURFACE_TABLE_POLYHEDRON(const int d); // constructor
~ISOSURFACE_TABLE_POLYHEDRON(); // destructor
ISOSURFACE_TABLE_POLYHEDRON(const ISOSURFACE_TABLE_POLYHEDRON & init);
// copy
const ISOSURFACE_TABLE_POLYHEDRON & operator =
(const ISOSURFACE_TABLE_POLYHEDRON &); // assign
// get functions
int Dimension() const { return(dimension); };
int NumVertices() const { return(num_vertices); };
int NumEdges() const { return(num_edges); };
int NumFacets() const { return(num_facets); };
int NumFacetVertices(const FACET_INDEX jf) const;
// jf = facet index
int VertexCoord(const int iv, const int ic) const
// iv = vertex index. ic = coordinate index.
{ return(vertex_coord[iv*dimension + ic]); };
int EdgeEndpoint(const EDGE_INDEX ie, const int j) const
// ie = edge index. j = 0 or 1.
{ return(edge_endpoint[int(ie)*2 + j]); };
FACET Facet(const FACET_INDEX jf) const
// jf = facet index
{ return(facet[jf]); };
int MidpointCoord(const EDGE_INDEX ie, const int ic) const;
bool VertexSign(const long code, const int iv) const;
bool FacetVertexFlag(const FACET_INDEX jf, const int iv) const
{ return(facet[jf] & ((1L) << iv)); };
// set functions
void SetDimension(const int d);
void SetNumVertices(const int numv);
void SetNumEdges(const int nume);
void SetNumFacets(const int numf);
void SetSize(const int numv, const int nume)
{ SetNumVertices(numv); SetNumEdges(nume); };
void SetSize(const int numv, const int nume, const int numf)
{ SetNumVertices(numv); SetNumEdges(nume); SetNumFacets(numf); };
void SetVertexCoord(const int iv, const int ic, const int coord);
// Note: SetNumVertices or SetSize must be called before SetVertexCoord
void SetEdge(const EDGE_INDEX ie, const int iv0, const int iv1);
// Note: SetNumEdges or SetSize must be called before SetEdge
void SetFacetVertex(const FACET_INDEX jf, const int iv, const bool in_facet);
// Note: SetNumFacets must be called before SetFacetVertex
// generate polyhedron
void GenCube(const int cube_dimension);
void GenSimplex(const int simplex_dimension);
// write polyhedron information
void WriteVertexCoordText(ostream & out) const;
void WriteEdgeListText(ostream & out) const;
void WriteFacetVerticesText(ostream & out) const;
// read polyhedron information
void ReadVertexCoordText(istream & in);
void ReadEdgeListText(istream & in);
void ReadFacetsText(istream & in);
// check functions
bool CheckDimension() const;
bool Check() const;
};
typedef ISOSURFACE_TABLE_POLYHEDRON * ISOSURFACE_TABLE_POLYHEDRON_PTR;
class ISOSURFACE_TABLE {
protected:
class ISOSURFACE_TABLE_ENTRY {
public:
int num_simplices;
EDGE_INDEX * simplex_vertex_list;
ISOSURFACE_TABLE_ENTRY();
~ISOSURFACE_TABLE_ENTRY();
bool Check() const;
};
protected:
ISOSURFACE_TABLE_POLYHEDRON polyhedron;
ISOSURFACE_TABLE_ENTRY * entry;
long num_table_entries;
// max # vertices allowed for table polyhedron
int max_num_vertices;
// isosurface table file header
static const char * const FILE_HEADER;
static const char * const VERTEX_HEADER;
static const char * const EDGE_HEADER;
static const char * const FACET_HEADER;
static const char * const TABLE_HEADER;
// old version file header
static const char * const FILE_HEADER_V1;
bool is_table_allocated;
// throw error if table is allocated
void CheckTableAlloc() const;
public:
ISOSURFACE_TABLE(const int d);
~ISOSURFACE_TABLE();
// get functions
const ISOSURFACE_TABLE_POLYHEDRON & Polyhedron() const
{ return(polyhedron); };
int Dimension() const { return(polyhedron.Dimension()); };
int SimplexDimension() const { return(Dimension()-1); };
int NumVerticesPerSimplex() const { return(SimplexDimension()+1); };
int NumTableEntries() const { return(num_table_entries); };
int NumSimplices(const TABLE_INDEX it) const
{ return(entry[it].num_simplices); };
EDGE_INDEX SimplexVertex
(const TABLE_INDEX it, const int is, const int iv) const
// it = table entry index. is = simplex index. iv = vertex index
// Note: Returns index of edge containing simplex vertex
{ return(entry[it].simplex_vertex_list[is*NumVerticesPerSimplex()+iv]); };
bool VertexSign(const TABLE_INDEX it, const int iv) const
{ return(polyhedron.VertexSign(it, iv)); };
int MaxNumVertices() const { return(max_num_vertices); };
// Note: Even tables for polyhedron of this size are probably impossible
// to compute/store
const char * const FileHeader() const { return(FILE_HEADER); };
const char * const VertexHeader() const { return(VERTEX_HEADER); };
const char * const EdgeHeader() const { return(EDGE_HEADER); };
const char * const FacetHeader() const { return(FACET_HEADER); };
const char * const TableHeader() const { return(TABLE_HEADER); };
const char * const FileHeaderV1() const { return(FILE_HEADER_V1); };
bool IsTableAllocated() const
{ return(is_table_allocated); };
// set functions
void SetNumPolyVertices(const int numv)
{ CheckTableAlloc(); polyhedron.SetNumVertices(numv); };
void SetNumPolyEdges(const int nume)
{ CheckTableAlloc(); polyhedron.SetNumEdges(nume); };
void SetNumPolyFacets(const int numf)
{ CheckTableAlloc(); polyhedron.SetNumFacets(numf); };
void SetPolySize(const int numv, const int nume)
{ SetNumPolyVertices(numv); SetNumPolyEdges(nume); };
void SetPolySize(const int numv, const int nume, const int numf)
{ SetNumPolyVertices(numv); SetNumPolyEdges(nume);
SetNumPolyFacets(numf); };
void SetPolyVertexCoord(const int iv, const int ic, const int coord)
{ CheckTableAlloc(); polyhedron.SetVertexCoord(iv, ic, coord); };
// Note: SetNumPolyVertices or SetPolySize must be called before
// SetPolyVertexCoord
void SetPolyEdge(const int ie, const int iv0, const int iv1)
{ CheckTableAlloc(); polyhedron.SetEdge(ie, iv0, iv1); };
// Note: SetNumPolyEdges or SetPolySize must be called before SetPolyEdge
void SetPolyFacetVertex(const int jf, const int iv, const bool in_facet)
{ CheckTableAlloc(); polyhedron.SetFacetVertex(jf, iv, in_facet); };
// Note: SetPolyNumFacetVertices must be called before SetPolyFacetVertex
void SetNumSimplices(const TABLE_INDEX it, const int nums);
void SetSimplexVertex(const TABLE_INDEX it, const int is,
const int iv, const EDGE_INDEX ie);
void Set(const ISOSURFACE_TABLE_POLYHEDRON & new_polyhedron)
{ CheckTableAlloc(); polyhedron = new_polyhedron;
AllocTable(); };
// generate polyhedron
void GenCube(const int cube_dimension)
{ CheckTableAlloc(); polyhedron.GenCube(cube_dimension); AllocTable(); };
// Note: Cubes of dimension > 4 will have too many vertices
void GenSimplex(const int simplex_dimension)
{ CheckTableAlloc(); polyhedron.GenSimplex(simplex_dimension);
AllocTable(); };
// allocate memory for isosurface table
// Must be called after defining polyhedron but before setting simplices
// Cannot be called twice; Automatically called by GenCube and GenSimplex
void AllocTable();
// write isotable
void WriteText(ostream & out);
void WriteFileHeaderText(ostream & out);
void WriteTableText(ostream & out);
// read isotable
void ReadText(istream & in);
void ReadFileHeaderText(istream & in);
void ReadTableText(istream & in);
// read/write old versions of isotable file
void WriteTextV1(ostream & out);
void ReadTextV1(istream & in);
void ReadNoHeaderTextV1(istream & in);
// check functions
bool CheckDimension(const int d) const;
bool CheckDimension() const
{ return(CheckDimension(Dimension())); };
bool CheckTable() const;
};
typedef ISOSURFACE_TABLE * ISOSURFACE_TABLE_PTR;
// routines for generating polyhedra
void generate_prism(const ISOSURFACE_TABLE_POLYHEDRON & base_polyhedron,
ISOSURFACE_TABLE_POLYHEDRON & prism);
// error class
class ISOSURFACE_TABLE_ERROR {
protected:
char * msg;
public:
ISOSURFACE_TABLE_ERROR() { msg = "No error message."; };
ISOSURFACE_TABLE_ERROR(char * error_msg)
{ msg = error_msg; };
char * Msg() const { return(msg); };
};
};
#endif
| true |
b8b91a23f0edf30ed595606eccec46b78b324ceb | C++ | luyi326/Project-Ball- | /BlackServo/main.cpp | UTF-8 | 1,874 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <signal.h>
#include <unistd.h>
#include "../BlackLib/BlackLib.h"
#include "../BlackLib/BlackGPIO.h"
#include "../BlackLib/BlackGPIO.h"
#include "./BlackServo.h"
using namespace BlackLib;
using namespace std;
void delay(float ms){
usleep(lround(ms*1000));
return;
}
BlackServo* myServo;
void sig_handler(int signo)
{
if (signo == SIGINT) {
cout << "\nReceived SIGINT" << endl;
myServo->move_to(90);
delay(100);
delete myServo;
exit(0);
}
}
int main (int argc, char* argv[]) {
if (signal(SIGINT, sig_handler) == SIG_ERR) {
cout << "Cannot register SIGINT handler" << endl;
return 1;
}
myServo = new BlackServo(EHRPWM1B, AIN0);
myServo->calibrate();
float precent = 100;
if (argc >= 2) {
precent = atoi(argv[1]);
}
myServo->move_to(precent);
// delay(1000);
while (!myServo->target_position_reached()) {
}
delay(1000);
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
cout << "Target position reached: " << myServo->current_position() << endl;
return 0;
}
| true |
82bb6190c8b8fc39d69615428c77a558f65e23c8 | C++ | Fabled-Zable/GameOfLime | /GameOfLime/GOL.h | UTF-8 | 4,434 | 3.453125 | 3 | [] | no_license | #pragma once
#include <vector>
class GOL
{
public:
enum class EState
{
DEAD,
ALIVE,
WALL,
ROOT,
CREEP_ONE,
CREEP_TWO
};
private:
std::vector< std::vector<EState> > grid;
public:
u_int height, width;
GOL()
{
height = 0;
width = 0;
}
GOL(u_int width, u_int height)
{
this->width = width;
this->height = height;
grid.resize(width);
for (unsigned int i = 0; i < grid.size(); i++)
{
grid[i].resize(height);
}
}
bool setCell(u_int x, u_int y, EState value)
{
if (x >= width || x < 0 || y >= height || y < 0)
//std::cout << "Set cell out of range x:" << x << " y:" << y << "\n";
return false;
grid[x][y] = value;
return true;
}
void shift(int shift_x, int shift_y)
{
std::vector< std::vector< EState > > newGrid;
newGrid.resize(grid.size());
for (unsigned int x = 0; x < grid.size(); x++)
{
newGrid[x].resize(grid[x].size());;
for (unsigned int y = 0; y < grid[x].size(); y++)
{
newGrid[x][y] = grid[x][y];
}
}
for(u_int x = 0; x < grid.size(); x++)
for (u_int y = 0; y < grid[x].size(); y++)
{
long int newX = x + shift_x;
long int newY = y + shift_y;
if (newX >= 0 && newX < (long int)grid.size() && newY >= 0 && newY < (long int)grid[x].size())
{
newGrid[newX][newY] = grid[x][y];
}
}
grid = newGrid;
}
void randomFill()
{
for(u_int x = 0; x < grid.size(); x++)
for (u_int y = 0; y < grid[x].size(); y++)
{
if (rand() % 5 == 0)
grid[x][y] = EState::ALIVE;
else
{
grid[x][y] = EState::DEAD;
}
}
}
EState getCell(u_int x, u_int y)
{
if (x >= width || x < 0 || y >= height || y < 0)
{
//std::cout << "Get cell out of range x:" << x << " y:" << y << "\n";
return EState::DEAD;
}
return grid[x][y];
}
bool isAlive(u_int x, u_int y)
{
EState cell = getCell(x, y);
return cell == EState::ALIVE || cell == EState::ROOT || cell == EState::CREEP_ONE || cell == EState::CREEP_TWO;
}
short unsigned int getNeighborCount(u_int x, u_int y)
{
short unsigned int neighborCount = 0;
if (isAlive(x, y + 1))//above
{
neighborCount++;
}
if (isAlive(x + 1, y + 1))//top right
{
neighborCount++;
}
if (isAlive(x - 1, y + 1))//top left
{
neighborCount++;
}
if (isAlive(x - 1, y))//left
{
neighborCount++;
}
if (isAlive(x + 1, y))//right
{
neighborCount++;
}
if (isAlive(x, y - 1))//below
{
neighborCount++;
}
if (isAlive(x + 1, y - 1))//bottom right
{
neighborCount++;
}
if (isAlive(x - 1, y - 1))//bottom left
{
neighborCount++;
}
return neighborCount;
}
void step ()
{
step([](u_int x, u_int y) -> void {});
}
void step(std::function<void(u_int x, u_int y)> cellChanged)
{
std::vector< std::vector< EState > > newGrid;
newGrid.resize(grid.size());
for (unsigned int x = 0; x < grid.size(); x++)
{
newGrid[x].resize(grid[x].size());;
for (unsigned int y = 0; y < grid[x].size(); y++)
{
newGrid[x][y] = grid[x][y];
}
}
for (u_int x = 0; x < width; x++)
for (u_int y = 0; y < height; y++)
{
switch (grid[x][y])
{
case EState::DEAD:
case EState::ALIVE:
{
short unsigned int neighborCount = getNeighborCount(x, y);
if (neighborCount < 2)
{
newGrid[x][y] = EState::DEAD;
}
if (neighborCount > 3)
{
newGrid[x][y] = EState::DEAD;
}
if (neighborCount == 3)
{
newGrid[x][y] = EState::ALIVE;
}
}
break;
case EState::CREEP_ONE:
case EState::CREEP_TWO:
{
if ((rand() % 2) == 0)
{
u_int new_x = x + rand() % 3 - 1;// -1 to 1
u_int new_y = y + rand() % 3 - 1;// -1 to 1
if(new_x >= 0 && new_y >= 0 && new_x < newGrid.size() && new_y < newGrid[new_x].size() && grid[new_x][new_y] != EState::WALL)
newGrid[new_x][new_y] = grid[x][y] == EState::CREEP_ONE ? EState::CREEP_ONE : EState::CREEP_TWO;
}
}
break;
default:
break;
}
}
std::vector<u_int> changedCells;
for (u_int x = 0; x < grid.size(); x++)
{
for (u_int y = 0; y < grid[x].size(); y++)
{
if (grid[x][y] != newGrid[x][y])
{
changedCells.push_back(x);
changedCells.push_back(y);
grid[x][y] = newGrid[x][y];
}
}
}
for (u_int i = 1; i < changedCells.size(); i += 2)
{
u_int x = changedCells[i - 1],
y = changedCells[i];
cellChanged(x, y);
}
}
};
| true |
41bc25664fdb37a0b324f3beb8290a5d3fc3edb0 | C++ | NewBediver/FarLight | /FarLight/src/FarLight/ResourceSystem/Resources/ShaderLibrary.cpp | UTF-8 | 1,315 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include "flpch.h"
#include "FarLight/Core/Core.h"
#include "FarLight/ResourceSystem/Resources/ShaderLibrary.h"
#include "FarLight/ConfigurationSystem/ConfigurationManager.h"
namespace FarLight
{
ShaderLibrary::ShaderLibrary() noexcept
{
auto shaders = ConfigurationManager::GetInstance().GetShaderLibraryConfiguration()->GetSavedShaders();
for (const auto& elm : shaders)
{
SetByName(elm->GetName(), elm);
}
}
bool ShaderLibrary::IsExistsByName(const std::string& name) const noexcept
{
return m_NameToUUID.find(name) != m_NameToUUID.end();
}
const Ref<ShaderResource>& ShaderLibrary::GetByName(const std::string& name) const noexcept
{
FL_CORE_ASSERT(IsExistsByName(name), "Library doesn't contain resource with the given id!");
return Get(m_NameToUUID.at(name));
}
void ShaderLibrary::SetByName(const std::string& key, const Ref<ShaderResource>& value) noexcept
{
m_NameToUUID[key] = value->GetId();
Set(value->GetId(), value);
}
void ShaderLibrary::RemoveByName(const std::string& name) noexcept
{
if (m_NameToUUID.find(name) != m_NameToUUID.end())
{
Remove(m_NameToUUID[name]);
m_NameToUUID.erase(name);
}
}
}
| true |
ca2db0880f042915684c77ed10150988e5d2e102 | C++ | ExpLife0011/V8 | /LiveShow/src/CommonLibrary/include/utility/IniFile.h | UTF-8 | 1,809 | 3.0625 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
using namespace std;
class CIniFile
{
public:
struct Record
{
string Section;
string Key;
string Value;
};
enum CommentChar
{
Pound = '#',
SemiColon = ';'
};
CIniFile(void);
virtual ~CIniFile(void);
static bool AddSection(string SectionName, string FileName);
static bool Create(string FileName);
static bool DeleteSection(string SectionName, string FileName);
static string GetValue(string KeyName, string SectionName, string FileName);
static bool SectionExists(string SectionName, string FileName);
static bool SetValue(string KeyName, string Value, string SectionName, string FileName);
static bool FileExists(string strFileName);//Added
private:
static vector<Record> GetSections(string FileName);
static vector<Record> GetRecord(string KeyName, string SectionName, string FileName);
static bool RecordExists(string KeyName, string SectionName, string FileName);
static bool Load(string FileName, vector<Record>& content);
static bool Save(string FileName, vector<Record>& content);
struct RecordSectionIs : std::unary_function<Record, bool>
{
std::string section_;
RecordSectionIs(const std::string& section): section_(section){}
bool operator()( const Record& rec ) const
{
return rec.Section == section_;
}
};
struct RecordSectionKeyIs : std::unary_function<Record, bool>
{
std::string section_;
std::string key_;
RecordSectionKeyIs(const std::string& section, const std::string& key): section_(section),key_(key){}
bool operator()( const Record& rec ) const
{
return ((rec.Section == section_)&&(rec.Key == key_));
}
};
}; | true |
3e9dc215a3cd5eb5ceae2fc4304fb410d1fb4e68 | C++ | dionb112/GamesAI | /Lab7/Game.cpp | UTF-8 | 3,305 | 3.125 | 3 | [] | no_license | /// <summary>
/// @author Dion Buckley
/// @date March 2020
/// fuzzy logic implementation
/// </summary>
#include "Game.h"
#include <iostream>
Game::Game() :
m_window{ sf::VideoMode{ 1280U, 720U, 32U }, "Lab 7" },
m_exitGame{false} //when true game will exit
{
setupFontAndText(); // load font
setupSprite(); // load texture
// first number (8) gives 5 enemeny unit sized force
// TODO: this number should be random
m_tiny = FuzzyLogic::fuzzyTriangle(8, -10, 0, 10);
m_small = FuzzyLogic::fuzzyTrapezoid(8, 2.5, 10, 15, 20);
m_moderate = FuzzyLogic::fuzzyTrapezoid(8, 15, 20, 25, 30);
m_large = FuzzyLogic::fuzzyGrade(8, 25, 30);
// enemy force at range of 25 units
// TODO: this number should also be random
m_close = FuzzyLogic::fuzzyTriangle(25, -30, 0, 30);
m_medium = FuzzyLogic::fuzzyTrapezoid(25, 10, 30, 50, 70);
m_far = FuzzyLogic::fuzzyGrade(25, 50, 70);
// Final threat assessment
m_low = FuzzyLogic::fuzzyOr(FuzzyLogic::fuzzyAnd(m_medium, m_tiny), FuzzyLogic::fuzzyAnd(m_medium, m_small));
m_medium = FuzzyLogic::fuzzyAnd(m_close, m_tiny);
m_high = FuzzyLogic::fuzzyAnd(m_close, FuzzyLogic::fuzzyNot(m_medium));
// test with values from slides
// output matches expected values, good
std::cout << m_low << std::endl;
std::cout << m_medium << std::endl;
std::cout << m_high << std::endl;
// Defuzzify
float deploy = (m_low * 10 + m_medium * 30 + m_high * 50) / (m_low + m_medium + m_high);
}
Game::~Game()
{
}
void Game::run()
{
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
const float fps{ 60.0f };
sf::Time timePerFrame = sf::seconds(1.0f / fps); // 60 fps
while (m_window.isOpen())
{
processEvents(); // as many as possible
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > timePerFrame)
{
timeSinceLastUpdate -= timePerFrame;
processEvents(); // at least 60 fps
update(timePerFrame); //60 fps
}
render(); // as many as possible
}
}
void Game::processEvents()
{
sf::Event newEvent;
while (m_window.pollEvent(newEvent))
{
if ( sf::Event::Closed == newEvent.type) // window message
{
m_exitGame = true;
}
if (sf::Event::KeyPressed == newEvent.type) //user pressed a key
{
processKeys(newEvent);
}
}
}
void Game::processKeys(sf::Event t_event)
{
if (sf::Keyboard::Escape == t_event.key.code)
{
m_exitGame = true;
}
}
void Game::update(sf::Time t_deltaTime) // dt is time interval per frame
{
if (m_exitGame)
{
m_window.close();
}
}
void Game::render()
{
m_window.clear(sf::Color::Black);
m_window.draw(m_text);
m_window.draw(m_sprite);
m_window.display();
}
void Game::setupFontAndText()
{
if (!m_ArialBlackfont.loadFromFile("ASSETS\\FONTS\\ariblk.ttf"))
{
std::cout << "problem loading arial black font" << std::endl;
}
m_text.setFont(m_ArialBlackfont);
m_text.setString("AI force fight");
m_text.setStyle(sf::Text::Underlined | sf::Text::Italic | sf::Text::Bold);
m_text.setPosition(90.0f, 40.0f);
m_text.setCharacterSize(42U);
m_text.setOutlineColor(sf::Color::Red);
m_text.setFillColor(sf::Color::Black);
m_text.setOutlineThickness(3.0f);
}
void Game::setupSprite()
{
if (!m_texture.loadFromFile("ASSETS\\IMAGES\\fuzzy.png"))
{
std::cout << "problem loading logo" << std::endl;
}
m_sprite.setTexture(m_texture);
}
| true |
7b39cd48e1716b7815f977e96f6b046f0297c0f7 | C++ | Wiktor1288/Sortowanie | /main.cpp | UTF-8 | 6,604 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include "scalanie.hpp"
#include "tablica.hpp"
#include <ctime>
#include "quick.hpp"
#include "kopiec.hpp"
#include "introspektywne.hpp"
using namespace std;
// funkcja wyswietlajaca menu
void menu()
{
cout <<"####################### MENU #######################" << endl;
cout << "1--> wprowadz tablice"<<endl;
cout << "2--> zwolnij miejsce (!uwaga wczesniej trzeba wybrac opcje wprowadz tablice!)"<<endl;
cout << "3--> wyswietl tablice"<<endl;
cout << "4--> sortowanie przez scalenie" <<endl;
cout << "5--> sortowanie szybkie (quick)" <<endl;
cout << "6--> sortowanie kopiec" <<endl;
cout << "7--> sortowanie introspektywne" <<endl;
cout << "8-> sprawdz poprawnosc posortowanych tablic" <<endl;
cout << "9--> KONIEC DZIAŁANIA PROGRAMU"<< endl;
cout << "##################################################"<<endl;
}
int main()
{
int rozmiar=0, opcja=1, opcja2=0, opcja3=0;
int licz=0;
bool powtarzaj=true, spraw_alok=false, powtarzaj2=true;
bool tak_nie;
double procent=0.0;
sortowanie_scalanie<int> obiekt;
tablice_do_sortowania<int> tablice[100];
tablice_do_sortowania<int> tablice_po[100];
quick<int> sort_szybki;
kopiec<int> kopiec1;
introspektywne<int> intro;
clock_t time_req;
//petla wykonywania dzialan z menu
while(powtarzaj)
{
menu();
cin >> opcja;
switch(opcja)
{
/*#########case 1##########
jest opcja ktora odpowaiada za stworzenie 100 tablic wybieralnego
rozmiaru. w casie tym ustala sie rozmiar tablicy oraz wybiera się
sposób uzupełnienia tablic. case ten również odpowiada za uzupełnie
danych w psozczegolnych klasach i zalokowanie odpowiedniej pamieci przez
metody tych klas. Wczesniej sprawdzane jest czy doszlo do zwolnienia miejsca
*/
case 1:
if(spraw_alok==false)
{
cout << "wprowadz rozmiar tablicy: ";
cin >> rozmiar;
cout << endl;
for(int i=0; i<100; i++)
{
tablice[i].zajmij_pamiec(rozmiar);
tablice_po[i].zajmij_pamiec(rozmiar);
}
obiekt.ustaw_pamiec(rozmiar);
sort_szybki.zajmij_pamiec(rozmiar);
kopiec1.zajmij_pamiec(rozmiar);
intro.zajmij_pamiec(rozmiar);
spraw_alok=true;
cout<< "wybierz opcje uzupelnienie:" <<endl;
cout<< "1--> uzupelniene losowe" << endl;
cout<< "2--> uzupelnienie procentowe" << endl;
cout<< "3--> uzupelnienie w odwrotnej kolejnosci" << endl;
cout<< "opcja: ";
cin >> opcja2;
cout<< endl;
switch(opcja2)
{
case 1:
for(int i=0; i<100; i++)
tablice[i].uzupelnij_losowo();
break;
case 2:
cout<< "wybierz procent uzupelnienia (90%=0.90): ";
cin >> procent;
cout << endl;
for(int i=0; i<100; i++)
tablice[i].uzupelnij_procent(procent);
break;
case 3:
for(int i=0; i<100; i++)
tablice[i].uzupelnij_odwrotna_kolejnosc();
break;
default:
cout<< "bledny wybor! wybierz opcje: ";
break;
}
}
else
cout<< "najpierw zwolnij miejsce!"<< endl;
break;
/*#####case 2##########
case ten odpowiada za zwolnienie pamieci, zajetej wczesniej przez
operator new w metodach typu "zajmij pamiec" w posczegolnych klasach
wczesniej sprawdzany jest warunek czy nastapila alokacja pamieci poprzez
wywolanie case 1
*/
case 2:
if(spraw_alok==true)
{
for(int i=0; i<100; i++)
{
tablice[i].zwolnij_miejsce();
tablice_po[i].zwolnij_miejsce();
}
obiekt.zwolnij_pamiec();
sort_szybki.zwolnij_pamiec();
kopiec1.zwolnij_pamiec();
intro.zwolnij_pamiec();
spraw_alok=false;
}
else
cout <<"Najpierw stworz tablice!" <<endl;
break;
/*###### case 3 ######
odpowiada za wypisanie wartosci aktualnych 100 tablic
*/
case 3:
powtarzaj2=true;
while(powtarzaj2)
{
cout<< "wybierz opcje:" << endl << "1--> wyswietl tablice, która została poddana sortowaniu" << endl
<< "2--> wyswietl tablice posortowana" << endl;
cin >> opcja3;
switch(opcja3)
{
case 1:
for(int i=0; i<100; i++)
tablice[i].wypisz();
powtarzaj2=false;
break;
case 2:
for(int i=0; i<100; i++)
tablice_po[i].wypisz();
powtarzaj2=false;
break;
default:
cout<< "bledna opcja, wybierz jeszcze raz:"<<endl;
break;
}
}
break;
/*###### case 4 ######
proces sortowania za pomoca metody scalania
oraz wypisanie czasu trawania tej operacji
*/
case 4:
time_req = clock();
for(int i=0; i<100; i++)
{
obiekt.uzupelnij_tablice_dosortowania(tablice[i].tablica);
obiekt.sort_scal(0,rozmiar-1);
obiekt.uzupelnij_tablice_posortowana(tablice_po[i].tablica);
}
time_req = clock() - time_req;
cout << "Using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
break;
/*###### case 5 ######
proces sortowania za pomoca metody sortowania szybkiego
oraz wypisanie czasu trawania tej operacji
*/
case 5:
time_req = clock();
for(int i=0; i<100; i++)
{
sort_szybki.uzupelnij_tablice(tablice[i].tablica);
sort_szybki.sort_quick(0,rozmiar-1);
sort_szybki.oddaj_tablice(tablice_po[i].tablica);
}
time_req = clock() - time_req;
cout << "Using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
break;
/*###### case 6 ######
proces sortowania za pomoca metody kopcowania
oraz wypisanie czasu trawania tej operacji
*/
case 6:
time_req = clock();
for(int i=0; i<100; i++)
{
kopiec1.uzupelnij_tablice(tablice[i].tablica);
kopiec1.sortuj();
kopiec1.oddaj_tablice(tablice_po[i].tablica);
}
time_req = clock() - time_req;
cout << "Using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
break;
/*###### case 4 ######
proces sortowania za pomoca metody i
oraz wypisanie czasu trawania tej operacji
*/
case 7:
time_req = clock();
for(int i=0; i<100; i++)
{
intro.uzupelnij_tablice(tablice[i].tablica);
intro.sortuj();
intro.oddaj_tablice(tablice_po[i].tablica);
}
time_req = clock() - time_req;
cout << "Using pow function, it took " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl;
break;
/*###### case 8 ######
sprawdzenie poprawnosci posortowanych tablic
*/
case 8:
for(int i=0; i<100; i++)
{
tak_nie=tablice_po[i].sprawdz_popr();
if(tak_nie==true)
++licz;
}
if(licz==100)
cout << "poprawnie posortowane"<<endl;
else
cout << "zle posortowane"<< endl;
licz=0;
break;
/*###### case 9######
Koniec dzialania programu wyjscie z petli
*/
case 9:
powtarzaj=false;
break;
default:
cout << "bledny wybor" << endl;
break;
}
}
return 0;
}
| true |
dad11d0c5433cf18bc0261d57dc789527a430782 | C++ | x0t1c-01/po | /MaterialeAutovalutazioneLaboratorio/Numbers/CalcolatriceAvanzata.cpp | UTF-8 | 4,368 | 3.734375 | 4 | [] | no_license |
#include "CalcolatriceAvanzata.h"
/*
Un numero P e` primo se e` > 1 ed e` divisibile solo per 1 e per P.
Una tripla di numeri C=(num1,num2,num3) e` bilanciata se esattamente uno tra num1 e num2 e` primo.
Restituire il numero di triple bilanciate presenti nella lista.
Se non sono presenti triple di numeri, restituire -1.
*/
bool CalcolatriceAvanzata::primo(int n){
for(int i=2;i<n/2;i++){
if(n%i==0)
return false;
}
return true;
}
int CalcolatriceAvanzata::metodo1(){
if(numeri.empty())
return -1;
int cont2=0;
for(auto it=numeri.begin();it!=numeri.end();it++){
int cont=0;
if(primo(it->getNum1()))
cont++;
if(primo(it->getNum2()))
cont++;
if(primo(it->getNum3()))
cont++;
if(cont==1)
cont2++;
}
return cont2;
}
/*
Restituire il num1 della terza tripla della lista ordinata nel seguente modo:
- Prima tutte le triple con il valore piu` alto di num1.
- A parita` di valore del num1, le triple con il valore piu` alto di num2.
- A parita` di valore del num2, le triple con il valore piu` alto di num3.
Se la lista ha meno di 3 elementi restituire -1.
ATTENZIONE: NON MODIFICARE la lista di numeri ma creare una copia temporanea.
*/
bool compare(const TriplaNumeri& i,const TriplaNumeri& j){
if(i.getNum1()>j.getNum1())
return true;
if(i.getNum1()==j.getNum1()){
if(i.getNum2()>j.getNum2())
return true;
if(i.getNum2()==j.getNum2())
return i.getNum3()>j.getNum3();
}
return false;
}
int CalcolatriceAvanzata::metodo2()
{
if(numeri.size()<3)
return -1;
list<TriplaNumeri> tmp = numeri;
tmp.sort(compare);
auto it=tmp.begin();
advance(it,2);
return it->getNum1();
}
/*
Sia LD la lista di triple duplicate.
Una tripla e` considerata duplicata se i primi due numeri sono uguali.
Restituire il massimo della somma tra num1 e num2 degli elementi in LD.
Esempio:
(1,2,4) (1,2,6) (3,4,7) (3,4,7) (3,4,8) (5,6,2) (6,5,2)
Le triple duplicate sono (1,2,_) e (3,4,_).
La somma di num1 e num2 della prima tripla e` pari a 3.
La somma di num1 e num2 della seconda tripla a 7.
Quindi il metodo deve restituire 7.
Se la lista e` vuota o non ha duplicati restituire -1.
*/
int CalcolatriceAvanzata::metodo3()
{
if(numeri.empty())
return -1;
int max=-1;
int cont2=0;
for(auto it=numeri.begin();it!=numeri.end();it++){
int cont=0,somma=0;
for(auto it2=numeri.begin();it2!=numeri.end();it2++){
if((it->getNum1()==it2->getNum1())&&(it->getNum2()==it2->getNum2()))
cont++;
}
if(cont>1){
somma+=it->getNum1()+it->getNum2();
cont2++;
if(somma>max)
max=somma;
}
}
if(cont2==0)
return -1;
return max;
}
/*
Sia P il primo numero a 4 cifre della lista (considerando solo il num3).
Sia PMAX il numero max che e` possibile comporre usando tutte le cifre di P.
Sia PMIN il numero min che e` possibile comporre usando tutte le cifre di P.
Restituire PMAX-PMIN.
Ad esempio, sia P = 1243, allora PMAX=4321 e PMIN=1234.
Se la lista e` vuota o se non ha numeri a 4 cifre restituire -1.
*/
int CalcolatriceAvanzata::metodo4()
{
if(numeri.empty())
return -1;
int a[4];
int dim=0;
for(auto it=numeri.begin();it!=numeri.end();it++){
if(((it->getNum3())>999)&&((it->getNum3())<10000)){
int x=it->getNum3();
while(x>0){
a[dim++]=x%10;
x/=10;
}
for(int i=0;i<dim-1;i++){
for(int j=0;j<dim-i-1;i++){
if(a[j]<a[i])
swap(a[i],a[j]);
}
}
/*for(int i=0;i<4;i++){
cout<<a[i]<<" ";
}
cout<<endl;*/
int pmax=0;
int pmin=0;
int e=1000;
for(int i=0;i<4;i++){
pmax+=a[i]*e;
e/=10;
}
int r=1000;
for(int i=3;i>=0;i--){
pmin+=a[i]*r;
r/=10;
}
/*cout<<endl;
cout<<pmax<<" "<<pmin;
*/
return pmax-pmin;
}
}
return -1;
}
| true |
2008125d1cd43045f53b052971582037ed9d3156 | C++ | fredsonjr/exercicios-prog | /exercicios-download/Prog/Aula 5/ex 5.cpp | UTF-8 | 297 | 3.296875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int funcao(float n, float s);
int main()
{
float n, s=0;
cout << "Entre com um numero:";
cin >> n;
funcao(n, s);
}
int funcao(float n, float s)
{
for(float i=1; i<=n; i++)
{
s=s+(1/i);
cout << s << endl;
}
}
| true |
863ed57d282c9144660622f22b01db8d565491c5 | C++ | zylzjucn/Leetcode | /100~199/152. Maximum Product Subarray.cpp | UTF-8 | 400 | 2.640625 | 3 | [] | no_license | class Solution {
public:
int maxProduct(vector<int>& n) {
int pmax = n[0];
int pmin = n[0];
int res = n[0];
for (int i = 1; i < n.size(); i++) {
if (n[i] < 0)
swap(pmax, pmin);
pmax = max(pmax * n[i], n[i]);
pmin = min(pmin * n[i], n[i]);
res = max(pmax, res);
}
return res;
}
};
| true |
4c47949f9866945dc8bcdd44dd350a627bc494fa | C++ | edweenie123/competitive-programming-solutions | /algorithm-templates/Data-Structure/Ordered-Set.cpp | UTF-8 | 1,256 | 3.359375 | 3 | [] | no_license | /*
The Ordered Set is an implementation of a "Balanced Binary Search Tree"
Its basically the same thing as a set, but it can perform more operations
find_by_order(k) - returns iterator to the kth largest element (counting from 0)
order_of_key(k) - returns the # of elements that are strictly less than k
Both operations are O(log n)
NOTE: ordered sets don't work with duplicate items
To get duplicate items to work, you can make the ordered set to use pairs instead
- the second element in a pair will contain a unique number
You have to change the typedef to do this though:
tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
*/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
int main() {
ordered_set o_set;
o_set.insert(1);
o_set.insert(2);
o_set.insert(3);
o_set.insert(4);
o_set.insert(5);
o_set.insert(6);
o_set.insert(7);
int fourthLargest = *o_set.find_by_order(3);
} | true |
7d23ccb21a72fe50c3b57caef3647a375715337f | C++ | adam-rumpf/social-transit-solver-single | /driver.cpp | UTF-8 | 9,399 | 3.09375 | 3 | [
"MIT"
] | permissive | /**
Main driver of the initial objective/constraint evaluation.
Contains the main function, which handles reading in the data, constructing the network, and calling the objective and constraint functions.
*/
#include <csignal>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <string>
#include "network.hpp"
#include "objective.hpp"
#include "constraints.hpp"
// Define input file names
#define NODE_FILE "data/node_data.txt"
#define ARC_FILE "data/arc_data.txt"
#define OD_FILE "data/od_data.txt"
#define TRANSIT_FILE "data/transit_data.txt"
#define VEHICLE_FILE "data/vehicle_data.txt"
#define OBJECTIVE_FILE "data/objective_data.txt"
#define PROBLEM_FILE "data/problem_data.txt"
#define USER_COST_FILE "data/user_cost_data.txt"
#define ASSIGNMENT_FILE "data/assignment_data.txt"
// Define output file names
#define METRIC_FILE "output/gravity_metrics.txt"
#define SOLUTION_LOG_FILE "output/initial_solution_log.txt"
#define FLOW_FILE "output/initial_flows.txt"
#define USER_COST_FILE_OUT "output/user_cost_data.txt"
using namespace std;
// Function prototypes
void STOP_REQUEST(int); // used to halt the program
vector<int> read_fleets(string); // reads in initial fleet sizes
void record_metrics(const vector<double> &); // writes accessibility metrics to an output file
void record_flows(Constraint *); // writes flow vector to an output file
void solution_log(const vector<int> &, const vector<double> &); // generates the initial row for the solution log given the solution vector and the element vector
void user_cost_file(string, string, double); // generates a copy of the given user cost file with the newly-calculated initial cost filled in
string solution_string(const vector<int> &); // converts a solution vector to a string
/// Main driver.
int main()
{
// Register signal handler for stop request
signal(SIGINT, STOP_REQUEST);
clock_t timer; // timer object used to time constraint and objective calculations
double obj_time = -1; // time required to calculate objective
double initial_objective = -1; // initial objective value
double con_time; // time required to calculate constraints
vector<double> initial_user_costs; // vector of initial user cost components
vector<double> solution_log_row; // initial row of solution log
// Get initial solution vector
vector<int> fleets = read_fleets(TRANSIT_FILE);
// Initialize network object
Network * Net = new Network(NODE_FILE, ARC_FILE, OD_FILE, TRANSIT_FILE, VEHICLE_FILE, PROBLEM_FILE);
// Use Objective object to calculate initial objective value and accessibility metrics
Objective * Obj = new Objective(OBJECTIVE_FILE, Net);
vector<double> metrics = Obj->all_metrics(fleets); // calculate all metrics
record_metrics(metrics); // write metrics to file
timer = clock();
initial_objective = Obj->calculate(fleets); // calculate initial objective value
obj_time = (1.0*clock() - timer) / CLOCKS_PER_SEC;
cout << "\nObjective calculation took " << obj_time << " seconds." << endl;
cout << "Initial objective value: " << initial_objective << endl;
// Use Constraint object to calculate initial constraint function values
Constraint * Con = new Constraint(USER_COST_FILE, ASSIGNMENT_FILE, FLOW_FILE, Net);
timer = clock();
initial_user_costs = Con->calculate(fleets).second; // calculate initial user costs
con_time = (1.0*clock() - timer) / CLOCKS_PER_SEC;
cout << "\nConstraint calculation took " << con_time << " seconds." << endl;
cout << "Initial user cost terms: ";
double tot = 0.0;
for (int i = 0; i < initial_user_costs.size(); i++)
{
tot += initial_user_costs[i];
cout << initial_user_costs[i] << ' ';
}
cout << endl;
cout << "Total: " << tot << endl;
// Assemble solution log row
for (int i = 0; i < initial_user_costs.size(); i++)
solution_log_row.push_back(initial_user_costs[i]);
solution_log_row.push_back(con_time);
solution_log_row.push_back(initial_objective);
solution_log_row.push_back(obj_time);
// Write solution log row to file
solution_log(fleets, solution_log_row);
// Write flows to file
record_flows(Con);
// Write updated user cost file
user_cost_file(USER_COST_FILE, USER_COST_FILE_OUT, tot);
return 0;
}
/// Signal handler for stop request. Exits program if the user presses [Ctrl]+[C].
void STOP_REQUEST(int signum)
{
exit(1);
}
/// Reads in initial fleet sizes from transit data file and returns them as a vector.
vector<int> read_fleets(string transit_file_name)
{
// Initialize empty fleet size vector
vector<int> fleets;
// Read transit data file
cout << "Reading initial fleet sizes from transit file..." << endl;
ifstream transit_file;
transit_file.open(transit_file_name);
if (transit_file.is_open())
{
string line, piece; // whole line and line element being read
getline(transit_file, line); // skip comment line
while (transit_file.eof() == false)
{
// Get whole line as a string stream
getline(transit_file, line);
if (line.size() == 0)
// Break for blank line at file end
break;
stringstream stream(line);
// Go through each piece of the line
getline(stream, piece, '\t'); // ID
getline(stream, piece, '\t'); // Name
getline(stream, piece, '\t'); // Type
getline(stream, piece, '\t'); // Fleet
int new_fleet = stoi(piece);
getline(stream, piece, '\t'); // Circuit
getline(stream, piece, '\t'); // Scaling
getline(stream, piece, '\t'); // LB
getline(stream, piece, '\t'); // UB
getline(stream, piece, '\t'); // Fare
getline(stream, piece, '\t'); // Frequency
getline(stream, piece, '\t'); // Capacity
// Create a line object and add it to the list
fleets.push_back(new_fleet);
}
transit_file.close();
}
else
cout << "Transit file failed to load." << endl;
return fleets;
}
/// Records vector of accessibility metrics to an output file.
void record_metrics(const vector<double> &metrics)
{
ofstream out_file(METRIC_FILE);
if (out_file.is_open())
{
cout << "Writing metrics to output file..." << endl;
// Write comment line
out_file << "Community_Area_ID\tGravity_Metric" << fixed << setprecision(15) << endl;
// Write all metrics
for (int i = 0; i < metrics.size(); i++)
out_file << i + 1 << '\t' << metrics[i] << endl;
out_file.close();
cout << "Successfuly recorded metrics!" << endl;
}
else
cout << "Metric file failed to open." << endl;
}
/// Records vector of core arc flows to an output file. Requires a reference to the Constraint object, which contains a flow vector.
void record_flows(Constraint * Con)
{
ofstream out_file(FLOW_FILE);
if (out_file.is_open())
{
cout << "Writing flows to output file..." << endl;
// Write comment line
out_file << "ID\tFlow" << fixed << setprecision(15) << endl;
// Write all flows
for (int i = 0; i < Con->Net->core_arcs.size(); i++)
out_file << Con->Net->core_arcs[i]->id << '\t' << Con->sol_pair.first[i] << endl;
out_file.close();
cout << "Successfully recorded flows!" << endl;
}
else
cout << "Flow file failed to open." << endl;
}
/// Records the initial row of the solution log.
void solution_log(const vector<int> &sol, const vector<double> &row)
{
ofstream log_file(SOLUTION_LOG_FILE);
if (log_file.is_open())
{
cout << "Writing to solution log file..." << endl;
// Write comment line
log_file << "Solution\tFeasible\tUC_Riding\tUC_Walking\tUC_Waiting\tCon_Time\tObjective\tObj_Time\t" << fixed << setprecision(15) << endl;
// Write contents of row vector
log_file << solution_string(sol) << "\t1\t";
for (int i = 0; i < row.size(); i++)
log_file << row[i] << '\t';
log_file << endl;
log_file.close();
cout << "Successfully recorded solution!" << endl;
}
else
cout << "Solution log file failed to open." << endl;
}
/**
Generates a copy of the user cost input file with a new value for the initial user cost.
Requires the name of the input file, the output file, and a new value, respectively.
*/
void user_cost_file(string input_file_name, string output_file_name, double val)
{
// Read input file while writing to output file
cout << "Creating updated copy of user cost file..." << endl;
ifstream in_file;
ofstream out_file(output_file_name);
in_file.open(input_file_name);
if (in_file.is_open() && out_file.is_open())
{
out_file << fixed << setprecision(15);
string line, piece; // whole line and line element being read
int count = 0; // line number
while (in_file.eof() == false)
{
count++;
// Get whole line as a string stream
getline(in_file, line);
if (line.size() == 0)
// Break for blank line at file end
break;
stringstream stream(line);
// Read pieces of each line
getline(stream, piece, '\t'); // left column
out_file << piece << '\t';
getline(stream, piece, '\t'); // right column
if (count == 2)
// Replace the original user cost value
out_file << val << endl;
else
// Otherwise directly copy the value
out_file << piece << endl;
}
in_file.close();
out_file.close();
cout << "Successfully copied user cost file!" << endl;
}
else
cout << "User cost file failed to load." << endl;
}
/// Converts a solution vector to a string by simply concatenating its digits separated by underscores.
string solution_string(const vector<int> &sol)
{
string out = "";
for (int i = 0; i < sol.size(); i++)
out += to_string(sol[i]) + '_';
out.pop_back();
return out;
}
| true |
3c926f739ab9f51857d0ce74712782bf7dbcc6b1 | C++ | marllboro/altis | /config/Config_SpawnPoints.hpp | UTF-8 | 8,091 | 2.78125 | 3 | [
"Ruby"
] | permissive | /*
* Format:
* 3: STRING (Conditions) - Must return boolean :
* String can contain any amount of conditions, aslong as the entire
* string returns a boolean. This allows you to check any levels, licenses etc,
* in any combination. For example:
* "call life_coplevel && license_civ_someLicense"
* This will also let you call any other function.
*
*/
class CfgSpawnPoints {
class Altis {
class Civilian {
class Kavala {
displayName = "Kavala";
spawnMarker = "civ_spawn_1";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class Athira {
displayName = "Athira";
spawnMarker = "civ_spawn_3";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class Pyrgos {
displayName = "Pyrgos";
spawnMarker = "civ_spawn_2";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class Sofia {
displayName = "Sofia";
spawnMarker = "civ_spawn_4";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class RebelN {
displayName = $STR_SP_Reb_N;
spawnMarker = "Rebelop";
icon = "\a3\ui_f\data\map\MapControl\bunker_ca.paa";
conditions = "license_civ_rebel";
};
class RebelS {
displayName = $STR_SP_Reb_S;
spawnMarker = "Rebelop_1";
icon = "\a3\ui_f\data\map\MapControl\bunker_ca.paa";
conditions = "license_civ_rebel";
};
class RebelE {
displayName = $STR_SP_Reb_E;
spawnMarker = "Rebelop_2";
icon = "\a3\ui_f\data\map\MapControl\bunker_ca.paa";
conditions = "license_civ_rebel";
};
};
class Cop {
class Kavala {
displayName = "Kavala HQ";
spawnMarker = "cop_spawn_1";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class Athira {
displayName = "Athira HQ";
spawnMarker = "cop_spawn_3";
icon = "\a3\ui_f\data\map\MapControl\fuelstation_ca.paa";
conditions = "";
};
class Pyrgos {
displayName = "Pyrgos HQ";
spawnMarker = "cop_spawn_2";
icon = "\a3\ui_f\data\map\GroupIcons\badge_rotate_0_gs.paa";
conditions = "";
};
class HW {
displayName = $STR_MAR_Highway_Patrol;
spawnMarker = "cop_spawn_5";
icon = "\a3\ui_f\data\map\GroupIcons\badge_rotate_0_gs.paa";
conditions = "call life_coplevel >= 3";
};
};
class Medic {
class Kavala {
displayName = $STR_SP_EMS_Kav;
spawnMarker = "medic_spawn_1";
icon = "\a3\ui_f\data\map\MapControl\hospital_ca.paa";
conditions = "";
};
class Athira {
displayName = $STR_SP_EMS_Ath;
spawnMarker = "medic_spawn_2";
icon = "\a3\ui_f\data\map\MapControl\hospital_ca.paa";
conditions = "";
};
class Pyrgos {
displayName = $STR_SP_EMS_Pyr;
spawnMarker = "medic_spawn_3";
icon = "\a3\ui_f\data\map\MapControl\hospital_ca.paa";
conditions = "";
};
};
};
class Tanoa {
class Civilian {
class Georgetown {
displayName = "Georgetown";
spawnMarker = "civ_spawn_1";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "!license_civ_rebel";
};
class Balavu {
displayName = "Balavu";
spawnMarker = "civ_spawn_3";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class Tuvanaka {
displayName = "Tuvanaka";
spawnMarker = "civ_spawn_2";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class Lijnhaven {
displayName = "Lijnhaven";
spawnMarker = "civ_spawn_4";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class RebelNW {
displayName = $STR_SP_Reb_NW;
spawnMarker = "Rebelop";
icon = "\a3\ui_f\data\map\MapControl\bunker_ca.paa";
conditions = "license_civ_rebel";
};
class RebelS {
displayName = $STR_SP_Reb_S;
spawnMarker = "Rebelop_1";
icon = "\a3\ui_f\data\map\MapControl\bunker_ca.paa";
conditions = "license_civ_rebel";
};
class RebelNE {
displayName = $STR_SP_Reb_NE;
spawnMarker = "Rebelop_2";
icon = "\a3\ui_f\data\map\MapControl\bunker_ca.paa";
conditions = "license_civ_rebel";
};
};
class Cop {
class NAirport {
displayName = $STR_SP_Cop_Air_N;
spawnMarker = "cop_spawn_1";
icon = "\a3\ui_f\data\map\MapControl\watertower_ca.paa";
conditions = "";
};
class SWAirport {
displayName = $STR_SP_Cop_Air_SW;
spawnMarker = "cop_spawn_3";
icon = "\a3\ui_f\data\map\MapControl\fuelstation_ca.paa";
conditions = "";
};
class GeorgetownHQ {
displayName = "Georgetown HQ";
spawnMarker = "cop_spawn_2";
icon = "\a3\ui_f\data\map\GroupIcons\badge_rotate_0_gs.paa";
conditions = "";
};
class Air {
displayName = $STR_MAR_Police_Air_HQ;
spawnMarker = "cop_spawn_4";
icon = "\a3\ui_f\data\map\Markers\NATO\b_air.paa";
conditions = "call life_coplevel >= 2 && {license_cop_cAir}";
};
class HW {
displayName = $STR_MAR_Highway_Patrol;
spawnMarker = "cop_spawn_5";
icon = "\a3\ui_f\data\map\GroupIcons\badge_rotate_0_gs.paa";
conditions = "call life_coplevel >= 3";
};
};
class Medic {
class SEHospital {
displayName = $STR_SP_EMS_SE;
spawnMarker = "medic_spawn_1";
icon = "\a3\ui_f\data\map\MapControl\hospital_ca.paa";
conditions = "";
};
class TanoukaHospital {
displayName = $STR_SP_EMS_Tan;
spawnMarker = "medic_spawn_2";
icon = "\a3\ui_f\data\map\MapControl\hospital_ca.paa";
conditions = "";
};
class NEAirportHospital {
displayName = $STR_SP_EMS_NEair;
spawnMarker = "medic_spawn_3";
icon = "\a3\ui_f\data\map\MapControl\hospital_ca.paa";
conditions = "";
};
};
};
};
| true |
a38a3bdc09ec223da4727e8b21ac6be67f60a58a | C++ | WithLei/ACM | /1137 Swipe.cpp | UTF-8 | 895 | 2.703125 | 3 | [] | no_license | #include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<map>
#include<list>
#include<cmath>
#include<set>
#include<queue>
using namespace std;
bool cmp(int x,int y){
if(x!=y)return x>y;
}
void swp(int* a,int* b){
if(*a>*b){
int t=*a;
*a=*b;
*b=t;
}
}
int main(){
int num[1002],n;
while(~scanf("%d",&n)){
memset(num,0,sizeof(num));
for(int i=0;i<n;i++){
scanf("%d",&num[i]);
}
int flag=0,k=n;
sort(num,num+n,cmp);
int range=0;
while(k){
range++;
bool m=false;
if(num[0]>0){
num[0]-=4;
if(num[0]<=0)k--;
}
for(int i=1;i<n;i++){
if(num[i]>0){
num[i]--;
if(num[i]==0)k--;
}
}
int t=0;
while(num[t]<num[t+1]&&t<=n-2){
int temp=num[t];
num[t]=num[t+1];
num[t+1]=temp;
t++;
}
}
printf("%d\n",range);
}
}
/*
3
1 2 100
*/ | true |
b7dd8c92bcbb8a9f32464be82395c1530fbfeadb | C++ | LiamTyler/Progression-old | /src/window.cpp | UTF-8 | 2,146 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "include/window.h"
Window::Window() : Window("Untitled", 640, 480)
{
}
Window::Window(const std::string& title, int w, int h) {
title_ = title;
width_ = w;
height_ = h;
fpsCounter_ = FPSCounter();
Init();
}
Window::~Window() {
SDL_GL_DeleteContext(glContext_);
SDL_DestroyWindow(sdlWindow_);
}
void Window::Init() {
sdlWindow_ = SDL_CreateWindow(
title_.c_str(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width_,
height_,
SDL_WINDOW_OPENGL);
if (sdlWindow_ == NULL) {
std::cerr << "Failed to create an SDL2 window" << std::endl;
exit(EXIT_FAILURE);
}
glContext_ = SDL_GL_CreateContext(sdlWindow_);
if (glContext_ == NULL) {
std::cerr << "Failed to create an opengl context" << std::endl;
exit(EXIT_FAILURE);
}
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to init GLEW" << std::endl;
exit(EXIT_FAILURE);
}
// print info
std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "Version: " << glGetString(GL_VERSION) << std::endl;
/*
if (SDL_GL_SetSwapInterval(1) < 0)
std::cerr << "Failed to set vsync" << std::endl;
*/
glEnable(GL_DEPTH_TEST);
InitEngineAfterWindow();
}
void Window::SwapWindow() {
SDL_GL_SwapWindow(sdlWindow_);
}
void Window::SetRelativeMouse(bool b) {
if (b)
SDL_SetRelativeMouseMode(SDL_TRUE);
else
SDL_SetRelativeMouseMode(SDL_FALSE);
}
float Window::GetTotalRuntime() {
return SDL_GetTicks() / 1000.0f;
}
float Window::GetDT() {
return fpsCounter_.GetDT();
}
void Window::StartFrame() {
fpsCounter_.StartFrame(GetTotalRuntime());
}
void Window::EndFrame() {
fpsCounter_.EndFrame();
SwapWindow();
}
void Window::SetFPSCallback(std::function<void(void*)> f, void* data) {
fpsCounter_.SetCallback(f, data);
}
void Window::ClearFPSCallback() {
fpsCounter_.SetCallback(nullptr, nullptr);
}
| true |
c218dcc46eef5fbb50bfe568c63c79ee6e42868d | C++ | breno-helf/TAPA.EXE | /contests/NEERC17/B.cpp | UTF-8 | 2,022 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int v[4];
for (int i = 0; i < 3; ++i) {
scanf("%d", &v[i]);
}
int v2[3];
for (int i = 0; i < 2; ++i) {
scanf("%d", &v2[i]);
}
sort(v, v+3);
sort(v2, v2+2);
int v3[3];
do{
for (int i = 0; i < 3; ++i) {
v3[0] = 2*v[0]+2*v[1];
v3[1] = 2*v[1]+v[2];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
sort(v, v+3);
do{
for (int i = 0; i < 3; ++i) {
v3[0] = 2*v[0]+2*v[1];
v3[1] = v[0]+v[1]+v[2];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
sort(v, v+3);
do{
for (int i = 0; i < 3; ++i) {
v3[0] = 2*v[0]+v[1];
v3[1] = 2*v[2]+v[1]+v[0];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
sort(v, v+3);
do{
for (int i = 0; i < 3; ++i) {
v3[0] = v[0]+v[1];
v3[1] = 3*v[2]+v[1]+v[0];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
sort(v, v+3);
do{
for (int i = 0; i < 3; ++i) {
v3[0] = 2*v[0]+v[1]+v[2];
v3[1] = v[0]+v[1]+v[2];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
sort(v, v+3);
do{
for (int i = 0; i < 3; ++i) {
v3[0] = 2*v[0]+v[1]+v[2];
v3[1] = 2*v[1]+v[2];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
sort(v, v+3);
do{
for (int i = 0; i < 3; ++i) {
v3[0] = 2*v[0]+v[1]+v[2];
v3[1] = v[0]+v[1]+v[2];
}
sort(v3, v3+2);
if(v3[0] <= v2[0] && v3[1] <= v2[1]) {
puts("Yes");
return 0;
}
}while(next_permutation(v, v+3));
puts("No");
}
| true |
5f94c0d7848f2ac4c5842a06787f997d8224a5a6 | C++ | dyxcode/unixExercise | /fileDirAttribute/set_file_access.cpp | UTF-8 | 460 | 2.90625 | 3 | [] | no_license | #include <cstdlib>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
int main(int argc, char *argv[]) {
if (argc != 2) {
cerr << "usage: ./a.out file_path" << endl;
exit(1);
}
struct stat buf;
if (stat(argv[1], &buf) < 0) {
cerr << "stat error" << endl;
exit(1);
}
if (chmod(argv[1], 0777) < 0) {
cerr << "chmod error" << endl;
exit(1);
}
return 0;
}
| true |
5010e2efe7cdc74cf20c9edcc2dbde7da0dcea0a | C++ | hyeonggeun0209/Linux | /Study/student.h | UTF-8 | 181 | 2.828125 | 3 | [] | no_license | class Student {
private:
char *_name;
int _age;
public:
Student();
Student(char *name, int age) {
_name=name;
_age=age;
}
char *getName();
}; | true |
b18f3e41020e3c370518dcbce63699343ac3a37b | C++ | ssh352/MyToolBox | /AT/AT_Driver/ItemTable.inl | UTF-8 | 2,128 | 2.9375 | 3 | [] | no_license | #pragma once
template<typename ItemType,typename ItemTraits>
ItemTable<ItemType,ItemTraits>::ItemTable(const char* apDBpath)
{
if(apDBpath == nullptr || strlen(apDBpath) == 0 )
{
throw std::exception("DBpath Null");
}
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status lstatus = leveldb::DB::Open(options,apDBpath, &m_pDB);
if(lstatus.ok())
{
LoadFromDB();
}
else
{
throw std::exception("Open Db Failed");
}
};
template<typename ItemType,typename ItemTraits>
ItemTable<ItemType,ItemTraits>::~ItemTable()
{
delete m_pDB;
}
template<typename ItemType,typename ItemTraits>
void ItemTable<ItemType,ItemTraits>::LoadFromDB()
{
leveldb::Iterator* liter = m_pDB->NewIterator(leveldb::ReadOptions());
for (liter->SeekToFirst(); liter->Valid(); liter->Next())
{
std::shared_ptr<ItemType> lStoreInstPtr(new ItemType);
memcpy(lStoreInstPtr.get(),liter->value().data(),liter->value().size());
KeyType lKeyType;
memcpy(&lKeyType,liter->key().data(),liter->key().size());
m_ItemMap[lKeyType] = lStoreInstPtr;
}
delete liter;
}
template<typename ItemType,typename ItemTraits>
typename ItemTable<ItemType,ItemTraits>::ItemPtr ItemTable<ItemType,ItemTraits>::GetItem( const KeyType& aItemID )
{
if(m_ItemMap.count(aItemID))
{
return m_ItemMap[aItemID];
}
else
{
return ItemPtr();
}
}
template<typename ItemType,typename ItemTraits>
void ItemTable<ItemType,ItemTraits>:: DelItem(const std::string& aItemID )
{
if(m_ItemMap.count(aItemID))
{
m_ItemMap.erase(aItemID);
}
}
template<typename ItemType,typename ItemTraits>
void ItemTable<ItemType,ItemTraits>::PutItem(ItemPtr apItem)
{
KeyType lItemID = ItemTraits::GetItemKey(apItem);
m_ItemMap[lItemID] = apItem;
leveldb::Slice lKey (((char*)&lItemID), sizeof(KeyType));
leveldb::Slice lVal (((char*)apItem.get()), sizeof(ItemType));
leveldb::Status lstatus =m_pDB->Put(leveldb::WriteOptions(), lKey,lVal);
if(!lstatus.ok())
{
ATLOG(AT::LogLevel::L_ERROR,"Can not Save DB");
}
}
template<typename ItemType,typename ItemTraits>
void ItemTable<ItemType,ItemTraits>::Clear()
{
m_ItemMap.clear();
}
| true |
fa94fb3d0ea8f417c2dae4e4f4998426c3637adf | C++ | cacarrilloc/Fair-Die-Loaded-Die-Program_2 | /LoadedDie.cpp | UTF-8 | 1,281 | 3.09375 | 3 | [] | no_license | /*********************************************************
** Author: Carlos Carrillo *
** Date: 10/12/2015 *
** Description: This is the class implementation file *
* of a class called LoadedDie. This class is a derived *
* class from the Die class. Its only data member *
* (SidesDie1) is inherited from the Die class. Its *
* only function (getloadedrollValue)returns the value *
* of a single roll that is higher than normal. *
********************************************************/
//LoadedDie.cpp
#include <iostream>
#include <cstdlib>
#include "LoadedDie.hpp"
using namespace std;
/********************************************************
* Function: getloadedrollValue() *
* Description: A non-parameter function that randomly *
* selects the value of a single roll of the loaded die *
* and returns that value. *
*******************************************************/
unsigned LoadedDie::getloadedrollValue()
{
unsigned lroll = rand() % SidesDie1 + 1;
unsigned loadedroll = lroll * 2;
if (loadedroll >= SidesDie1)
{
return SidesDie1;
}
else
return loadedroll;
}
| true |
4479964db902755eaa79b0db4f51b9fe50574aef | C++ | Belousov-EA/LineFollower | /PDAlgorithm.h | UTF-8 | 484 | 2.59375 | 3 | [] | no_license | #ifndef PD_ALGORITHM_H
#define PD_ALGORITHM_H
#include <Arduino.h>
class PDAlgorithm
{
public:
void init(float P, float D);
inline void toRegulate(float error);
void setPredError(float pError) {predError = pError;}
float getP() {return p;}
float getValue() {return force;}
void setPD(float P, float D);
protected:
float p;
float d;
private:
float force;
float predError;
unsigned long oldTime;
unsigned long nowTime;
};
#endif
| true |
338c7bab4b0b05d14060a331d3fa803836c9e1e7 | C++ | jnf611/cpp-init-prog | /cpp/s01-le-03-user-var.cpp | UTF-8 | 258 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n;
int n2;
cout << "enter a value for n" << endl;
cin >> n;// rm: if a char or a string is input, n is set to 0
n2 = n * n;
cout << "square of " << n << " is " << n2 << endl;
return 0;
}
| true |
094e8794a61c8b723c4724ac2313ca64c6162214 | C++ | Maxine100/CS100 | /Lab10/floor.hpp | UTF-8 | 494 | 2.953125 | 3 | [] | no_license | #ifndef FLOOD_HPP
#define FLOOR_HPP
class Floor : public Base {
public:
Base* input;
Floor(Base* input) {
this->input = input;
}
double evaluate() {
return floor(input->evaluate());
}
string stringify() {
return input->stringify();
}
Base* get_left() {
return input;
}
Base* get_right() {
return nullptr;
}
Iterator* create_iterator() {
return new UnaryIterator(this);
}
void accept(CountVisitor* count) {
count->visit_floor();
}
};
#endif
| true |
6a862e52e0ad4c22be255b2f489b55d3c2e2d6b6 | C++ | DeshErBojhaa/sports_programming | /codeforces/New Folder With Items/174 div 2/BB.cpp | UTF-8 | 550 | 2.578125 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<iostream>
#include<vector>
#include<queue>
#include<math.h>
#include<sstream>
using namespace std;
int main()
{
string str;
// cin>>str;
int a=0,f=0,i=0,n;
cin>>n;
for(int ii=0;ii<n;ii++)
{
char ch;
scanf(" %c",&ch);
if(ch=='A') a++;
if(ch=='F') f++;
else if(ch=='I')i++;
}
if(i==0) printf("%d\n",a);
else if(i==1) printf("1\n");
else printf("0\n");
}
| true |
7f3ce145a1bc7b54ff45d0f54cb3fdfdc45e0697 | C++ | Ernesto-Canales/FUNDA_101_Ernie | /C++/S29_CPP_Control_Structures_part4/S29_Exercise2.cpp | UTF-8 | 2,499 | 4 | 4 | [] | no_license | /*
*2. Suppose that classStanding is a char variable, and gpa and dues are double variables.
* Write a switch expression that assigns the dues as following:
* (Note that the code 'f' stands for first year students, the code 's' stands for second year students, the code 'j' stands for juniors, and the code 'n' stands for seniors.)
* a. If classStanding is 'f', the dues are $150.00;
* b. if classStanding is 's' (if gpa is at least 3.75, the dues are $75.00; otherwise, dues are 120.00);
* c. if classStanding is 'j' (if gpa is at least 3.75, the dues are $50.00; otherwise, dues are $100.00);
* d. if classStanding is 'n' (if gpa is at least 3.75, the dues are $25.00; otherwise, dues are $75.00).
*/
#include <iostream>
using namespace std;
int main() {
char classStanding;
double gpa, dues;
cout << "El anio cursado solo acepta f, s, j y n" << endl;
cout << "Ingrese el anio que esta cursando: ";
cin.get(classStanding);
cout << endl;
cout << "Ingrese su gpa: ";
cin >> gpa;
cout << endl;
if (gpa >= 0) {
switch(classStanding) {
case 'f': //Primer año
dues = 150.0;
cout << "Su cuota para este anio es: $" << dues;
break;
case 's': //Segundo año
if (gpa >= 3.75) {
dues = 75.0;
cout << "Su cuota para este anio es: $" << dues;
} else {
dues = 120.0;
cout << "Su cuota para este anio es: $" << dues;
}
break;
case 'j': //Tercer año
if (gpa >= 3.75) {
dues = 50.0;
cout << "Su cuota para este anio es: $" << dues;
} else {
dues = 100.0;
cout << "Su cuota para este anio es: $" << dues;
}
break;
case 'n': //Curto año
if (gpa >= 3.75) {
dues = 25.0;
cout << "Su cuota para este anio es: $" << dues;
} else {
dues = 75.0;
cout << "Su cuota para este anio es: $" << dues;
}
break;
default:
cout << "La letra ingreseda no existe en ninguno de los anios registrados";
}
} else {
cout << "El gpa no puede ser negativo";
}
return 0;
} | true |
1af34e812a6cc4457880a377322a2e5de1ae2d6c | C++ | guoanjie/Cpp-Primer | /ch06/6.27.cc | UTF-8 | 295 | 3.21875 | 3 | [] | no_license | #include <initializer_list>
#include <iostream>
using std::cout;
using std::endl;
using std::initializer_list;
int sum(initializer_list<int> il) {
int s = 0;
for (auto i : il)
s += i;
return s;
}
int main()
{
cout << sum({1, 2, 3, 4, 5, 6, 7}) << endl;
return 0;
}
| true |
3ba709b02626ebb9af5aed4ff1792bfbd8d1593d | C++ | nvtienanh/Hitechlab_humanoid | /rosmon/src/ros_interface.cpp | UTF-8 | 2,009 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
] | permissive | // Provides a ROS interface for controlling rosmon
// Author: Max Schwarz <max.schwarz@uni-bonn.de>
#include "ros_interface.h"
#include <rosmon/State.h>
#include <algorithm>
namespace rosmon
{
ROSInterface::ROSInterface(LaunchConfig* config)
: m_config(config)
, m_nh("~")
{
m_updateTimer = m_nh.createWallTimer(ros::WallDuration(1.0), boost::bind(&ROSInterface::update, this));
m_pub_state = m_nh.advertise<rosmon::State>("state", 10, true);
m_srv_startStop = m_nh.advertiseService("start_stop", &ROSInterface::handleStartStop, this);
}
ROSInterface::~ROSInterface()
{
}
void ROSInterface::update()
{
rosmon::State state;
state.header.stamp = ros::Time::now();
for(auto node : m_config->nodes())
{
rosmon::NodeState nstate;
nstate.name = node->name();
switch(node->state())
{
case Node::STATE_RUNNING:
nstate.state = nstate.RUNNING;
break;
case Node::STATE_CRASHED:
nstate.state = nstate.CRASHED;
break;
case Node::STATE_IDLE:
nstate.state = nstate.IDLE;
break;
case Node::STATE_WAITING:
nstate.state = nstate.WAITING;
break;
default:
nstate.state = nstate.IDLE;
break;
}
state.nodes.push_back(nstate);
}
m_pub_state.publish(state);
}
bool ROSInterface::handleStartStop(StartStopRequest& req, StartStopResponse& resp)
{
auto it = std::find_if(
m_config->nodes().begin(), m_config->nodes().end(),
[&](const Node::Ptr& n){ return n->name() == req.node; }
);
if(it == m_config->nodes().end())
return false;
switch(req.action)
{
case StartStopRequest::START:
(*it)->start();
break;
case StartStopRequest::STOP:
(*it)->stop();
break;
case StartStopRequest::RESTART:
(*it)->restart();
break;
}
return true;
}
void ROSInterface::shutdown()
{
m_updateTimer.stop();
// Send empty state packet to clear the GUI
rosmon::State state;
state.header.stamp = ros::Time::now();
m_pub_state.publish(state);
// HACK: Currently there is no way to make sure that we sent a message.
usleep(200 * 1000);
}
}
| true |
fa9ef4f0fd679d11218ad660c6de0b61d701417c | C++ | chos2008/chos-framework-c | /HIB_TEST/StrcatTest.cpp | UTF-8 | 3,167 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
int main()
{
const char* set = "set names ";
const char* gbk = "gbk";
int set_len = strlen(set);
int set_gbk = strlen(gbk);
int sz = set_len + set_gbk + 1;
//sz = 1024 * 1024 * 1024;
//sz = 0;
char *cs = (char *) malloc(sz);
memset(cs, 0, sz);
strcat(cs, set);
strcat(cs, gbk);
//cs[0] = 'a'; cs[1] = 'b'; cs[2] = 'c';
//strcat(cs, "gbk");
printf("%s\n", cs);
//Sleep(20000);
free(cs);
printf("free... %s\n", cs == NULL ? "null" : "not null");
//Sleep(20000);
/*
// 1
char *str1 = "abcdef";
int length = strlen(str1);
for (int i = 0; i < length; i++)
{
printf("%c", str1[i]);
}
printf("\n------------------\n");
//////////////////////////////////////////////////////////
// 2
char *str2 = "abcdefg";
while (*str2)
{
printf("%c", *str2++);
}
printf("\n------------------\n");
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 3
char *str3 = "abcdefg\0";
while (*str3)
{
printf("%c(%d)", *str3, *str3++);
}
printf("\n------------------\n");
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 4
char str4[] = {'a', 'b', 'c'};
int length4 = sizeof(str4) / sizeof(char);
printf("sizeof(str4): %d, sizeof(char): %d, length4: %d\n",
sizeof(str4), sizeof(char), length4);
for (int i4 = 0; i4 < length4; i4++)
{
printf("%c(%d)", str4[i4], str4[i4]);
}
printf("\n------------------\n");
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// 5
char str5[] = {'a', 'b', 'c', 'd', '\0'};
int length5 = sizeof(str5) / sizeof(char);
printf("sizeof(str5): %d, sizeof(char): %d, length5: %d\n", sizeof(str5), sizeof(char), length5);
for (int i5 = 0; i5 < length5; i5++)
{
printf("%c(%d)", str5[i5], str5[i5]);
}
printf("\n------------------\n");
//////////////////////////////////////////////////////////
//char d[20]="Golden Global";
char *d = (char *) malloc(255 * sizeof(char));
memset(d, 0, 255);
printf("%d\n", strlen(d));
//char *d = (char *) malloc(255);;
char *s=" View";
//clrscr();
strcat(d,s);
printf("%s\n",d);
printf("%d\n", strlen(d));
//getchar();
*/
/*
char *s = (char *) malloc(6 * sizeof(char));
memset(s, 0, 6);
printf("%d\n", sizeof(s));
printf("%d\n", sizeof(*s));
printf("%d\n", sizeof(char));
printf("%d\n", strlen(s));
printf("%s\n", s);
for (int i = 0; i < 5; i++)
{
s[i] = 'a';
}
printf("%d\n", sizeof(s));
printf("%d\n", sizeof(*s));
printf("%d\n", sizeof(char));
printf("%d\n", strlen(s));
printf("%s\n", s);
printf("======================\n");
char s2[6];
memset(s2, 0, 6);
printf("%d\n", sizeof(s2));
printf("%d\n", sizeof(*s2));
printf("%d\n", sizeof(char));
printf("%d\n", strlen(s2));
printf("%s\n", s2);
for (i = 0; i < 5; i++)
{
s2[i] = 'a';
}
printf("%d\n", sizeof(s2));
printf("%d\n", sizeof(*s2));
printf("%d\n", sizeof(char));
printf("%d\n", strlen(s2));
printf("%s\n", s2);
*/
return 0;
} | true |
767168804398a6505133c7050c68073054667a5d | C++ | wy0526/DataStructureAndAlgorithm | /啊哈算法/01_一大波数正在靠近_排序/01桶排序_参考.cpp | GB18030 | 575 | 3.015625 | 3 | [] | no_license | # include <stdio.h>
//# include <stdlib.h>
int main()
{
int a[11],i,j,t;
//ʼΪ
for(i=0;i<=10;i++)
{
a[i]=0;
}
//ͯЬijɼӦͰСһ
for(i=1;i<=5;i++)
{
scanf("%d",&t);
a[t]++;
}
//ѭͰ
for(i=0;i<=10;i++)
{ //ÿͰмСѭӡ
for(j=1;j<=a [i];j++)
{
printf("%d ",i);
}
}
//˴Ϊͣһ߿Դ
getchar();
// system("pause"); ͷļ<stdlib.h>
return 0;
}
| true |
349fd329adcd63c0212fe66e3362c2f6fd4f40b4 | C++ | yeahhhhhhhh/ndsl | /src/ndsl/net/ELThreadpool.cc | UTF-8 | 5,158 | 2.734375 | 3 | [] | no_license | /**
* @file ELThreadpool.cc
* @brief
* 封装EventLoop的线程和线程池
*
* @author Liu GuangRui
* @email 675040625@qq.com
*/
#include "ndsl/net/ELThreadpool.h"
#include "ndsl/net/EventLoop.h"
#include "ndsl/utils/Error.h"
// #include "ndsl/utils/Thread.h"
#include "ndsl/utils/Log.h"
namespace ndsl {
namespace net {
Thread::Thread(ThreadFunc threadfunc, void *param)
: func_(threadfunc)
, param_(param)
, id_(0)
, ret_(NULL)
{}
Thread::~Thread() {}
int Thread::run()
{
int ret = ::pthread_create(&id_, NULL, runInThread, (void *) this);
if (ret != S_OK) {
LOG(LOG_ERROR_LEVEL,
LOG_SOURCE_THREAD,
"pthread_create errno = %d:%s\n",
errno,
strerror(errno));
return S_FALSE;
}
return S_OK;
}
int Thread::join(void **retval)
{
int ret = ::pthread_join(id_, retval);
if (ret != S_OK) {
LOG(LOG_ERROR_LEVEL,
LOG_SOURCE_THREAD,
"pthread_join errno = %d:%s\n",
errno,
strerror(errno));
return S_FALSE;
}
return S_OK;
}
void *Thread::runInThread(void *arg)
{
LOG(LOG_INFO_LEVEL, LOG_SOURCE_THREAD, "one thread is running!\n");
Thread *th = static_cast<Thread *>(arg);
th->ret_ = th->func_(th->param_);
return (void *) th->ret_;
}
int Thread::getNumberOfProcessors()
{
int ret = ::sysconf(_SC_NPROCESSORS_ONLN);
if (ret == -1) {
LOG(LOG_ERROR_LEVEL,
LOG_SOURCE_THREAD,
"sysconf errno = %d:%s\n",
errno,
strerror(errno));
return S_FALSE;
}
return ret;
}
ELThread::ELThread(EventLoop *loop)
: loop_(loop)
, thread_(loop_->loop, loop)
, running_(false)
{}
ELThread::~ELThread()
{
// 若线程正在运行,则退出循环,等待线程结束
if (running_) {
loop_->quit();
join();
}
}
int ELThread::run()
{
int ret = thread_.run();
if (ret == S_OK) running_ = true;
return ret;
}
int ELThread::join()
{
int ret = thread_.join();
if (ret == S_OK) running_ = false;
return ret;
}
bool ELThread::isRunning() const { return running_; }
ELThreadpool::ELThreadpool()
: MaxThreads_(0)
, nextThread_(0)
{}
ELThreadpool::~ELThreadpool() {}
int ELThreadpool::start()
{
// 若没有设置最大线程数,则设为默认值
if (MaxThreads_ == 0) MaxThreads_ = capacity();
// 暂时打开一个线程
EventLoop *el = new EventLoop();
// EventLoop的初始化
int ret = el->init();
if (ret != S_OK) {
LOG(LOG_ERROR_LEVEL, LOG_SOURCE_ELTHREADPOOL, "EventLoop init error\n");
return S_FALSE;
}
ELThread *elt = new ELThread(el);
loops_.push_back(el);
loopThreads_.push_back(elt);
// 开启线程
ret = elt->run();
if (ret != S_OK) {
LOG(LOG_ERROR_LEVEL, LOG_SOURCE_ELTHREADPOOL, "ELThread run error\n");
return S_FALSE;
}
return S_OK;
}
EventLoop *ELThreadpool::getNextEventLoop()
{
nextThread_ %= MaxThreads_;
// 若已有足够多的线程,则直接返回
if (nextThread_ < loops_.size())
return loops_[nextThread_++];
else if (nextThread_ == loops_.size()) {
EventLoop *el = new EventLoop();
// EventLoop初始化
int ret = el->init();
if (ret != S_OK) {
LOG(LOG_ERROR_LEVEL, LOG_SOURCE_ELTHREADPOOL, "init error\n");
return NULL;
}
ELThread *elt = new ELThread(el);
loops_.push_back(el);
loopThreads_.push_back(elt);
// 开启线程
ret = elt->run();
if (ret != S_OK) {
LOG(LOG_ERROR_LEVEL, LOG_SOURCE_ELTHREADPOOL, "run error\n");
return NULL;
}
return loops_[nextThread_++];
} else {
LOG(LOG_ERROR_LEVEL, LOG_SOURCE_ELTHREADPOOL, "fatal error\n");
return NULL;
}
}
int ELThreadpool::setMaxThreads(unsigned int maxThreads)
{
// 若设置的线程数小于当前已有的线程数,则退出
if (maxThreads < loopThreads_.size()) return S_FALSE;
MaxThreads_ = capacity();
// 若超过默认的最大值,则设置为最大值
if (maxThreads > MaxThreads_) return S_OK;
MaxThreads_ = maxThreads;
return S_OK;
}
unsigned int ELThreadpool::getMaxThreads() const { return MaxThreads_; }
int ELThreadpool::quit()
{
if (loopThreads_.size() != loops_.size()) {
LOG(LOG_ERROR_LEVEL, LOG_SOURCE_ELTHREADPOOL, "fatal error\n");
return S_FALSE;
}
LOG(LOG_DEBUG_LEVEL,
LOG_SOURCE_ELTHREADPOOL,
"%d threads joined\n",
loops_.size());
for (int i = loops_.size() - 1; i >= 0; i--) {
delete loopThreads_[i];
delete loops_[i];
loops_.pop_back();
loopThreads_.pop_back();
}
return S_OK;
}
int ELThreadpool::getLoopsNum() { return loops_.size(); }
int ELThreadpool::capacity()
{
int processors = Thread::getNumberOfProcessors();
if (processors == S_FALSE) {
// 获取失败,默认返回1
return 1;
}
return Redundancy * processors;
}
} // namespace net
} // namespace ndsl | true |
83083d7d8fae936ee4ae582a4cceb02edc3a9b13 | C++ | BUW-Comp-Prog-Project/WS_19 | /ADDREV/Rhadames-Solved/42.cpp | UTF-8 | 393 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
int reverse(int x)
{
int y = 0;
while (x)
{
y = y * 10 + x % 10;
x = x/10;
}
return y;
}
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
int a,b;
cin >> a;
cin >> b;
a = reverse(a);
b = reverse(b);
int c = a + b;
cout << reverse(c) << endl;
}
return 0;
} | true |
a2aef093629f100975eb1c8dc46baa4f0c1b6c90 | C++ | Lisa941123/20200910-homework-basic | /750417/程式跟使用者打招呼.cpp | UTF-8 | 181 | 2.75 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
string name;
cout << "請輸入你的名子:";
cin >> name;
cout << "你好";
cout << name;
}
| true |
a67375bbe311e83843ef5179a3f8fcf4757703bf | C++ | wyt0602/algorithm | /others/GoF/Structual/Adapter.cc | UTF-8 | 882 | 3 | 3 | [] | no_license | /*********************************************************************************
*适配器模式:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于
* 接口不兼容而不能一起工作的那些类可以一起工作。
*(1)系统的数据和行为都正确,但接口不符时,考虑用适配器
*(2)适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致。
*
*
* 总结:此模式是在不得已的情况下才使用的,比如由于有多种系统要使用(数据库),它
* 的接口又不一致,那么用一个Adapter模式可以将这种差异对客户端屏蔽。(注意这里主要
* 针对的是类,需要和外观模式相区别)
*
* *******************************************************************************
*/
| true |
21083f8b662523f41e8092647599bd40ed7b7738 | C++ | bdugersuren/CS2040C | /Practice/Heap.cpp | UTF-8 | 4,071 | 4.34375 | 4 | [] | no_license | /*Practice Program for Binary Max Heap (priority queue)*/
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Heap {
private:
vector <int> tree; //To store binary max heap
int size = 0; //Number of elements in tree, with 1st item starting from size 1
public:
//Constructor to receive user input and build a binary max heap automatically
Heap(){
int temp;
while (cin >> temp){ //Receive user input
tree.push_back(temp);
++size;
if (cin.get() == '\n'){
break;
}
}
heapbuild(); //Build heap
}
//Build binary max heap from the "unheaped" vector
void heapbuild(){
for (int i = (size/2) - 1; i >=0; --i){ //Start from the 1st non-leaf node and go upwards
bubbledown(i); //Perform bubble down process for each non-leaf node
}
}
//Get the parent of any node at position "pos"
int getparent(int pos){
return floor((pos - 1) / 2);
}
//Get the left child of any node at position "pos"
int getleftchild(int pos){
return 2*pos + 1;
}
//Get the right child of any node at position "pos"
int getrightchild(int pos){
return 2*pos + 2;
}
//Swap nodes a and b
void swap(int a, int b){
int temp;
temp = tree[a];
tree[a] = tree[b];
tree[b] = temp;
}
//Bubble up procedure to maintain max heap property
void bubbleup(int pos){
while (getparent(pos) >= 0 && tree[getparent(pos)] < tree[pos]){
swap(getparent(pos), pos);
pos = getparent(pos);
} //Stop bubbling up when "pos" hits the root (0) or when the parent of "pos" is larger than "pos"
}
//Bubble down procedure to maintain max heap property
void bubbledown(int pos){
int child = getleftchild(pos); //Start with left child first
if (child < size){ //If left child exists (if not, then the base case has been reached)
int rightchild = getrightchild(pos);
//If right child exists and it is larger than the left child
if (rightchild < size && tree[rightchild] > tree[child]){
child = rightchild; //Always take the larger child
}
if (tree[pos] < tree[child]) { //Compare parent and child and swap if necessary
swap(pos, child);
bubbledown(child); //Then go to the new child position and continue bubbling down
}
} //If max heap property satisfied, do nothing
}
//Insert a new node
void push(int data){
tree.push_back(data); //Insert at the leaf position
++size;
bubbleup(size - 1); //Then bubble up until max heap property is satisfied
} //Note (size - 1) because vectors start from zero
//Delete the largest node (at the root) and return it as an int
int pop(){
int rootitem = tree[0]; //Extract root
tree[0] = tree[--size]; //Take the leaf at the end of the vector and put it at the root (and decrease size)
tree.pop_back(); //Delete the leaf that was moved
bubbledown(0); //Then bubble down the new "root" until max heap property is satisfied
return rootitem;
}
//Print contents of the heap
void printtree(){
for (int i = 0; i < size; ++i){
cout << tree[i];
}
cout << '\n';
}
};
int main(int argc, char const *argv[])
{
Heap CS2040C;
CS2040C.printtree();
CS2040C.push(10);
CS2040C.printtree();
int extract = CS2040C.pop();
CS2040C.printtree();
cout << extract << endl;
return 0;
}
| true |
005eadd632369bfce8069e2b8c97692a980a57bb | C++ | MateuszMajcher/numeryczne | /algorytmy/liczba_anty_pierwsza.cpp | UTF-8 | 882 | 3.25 | 3 | [] | no_license | //Zadanie 3 Zestaw 8
#include <iostream>
#include <stdlib.h>
using namespace std;
void liczba(int n){
int k; //liczba k jest liczba anty-pierwsza
int max = 0;
int x = 0;
int ile, j;
for( k = 1; k <= n; k++)
{
ile = 0;
j = 1;
while( j <= k)
{
if(k % j == 0)
ile += 2;
j++;
}
if(ile > max)
{
++x;
max = ile;
cout << k << "\t" << endl;
}
}
cout << endl;
cout << "Liczb anty-pierwszych jest: " << x << endl;
}
int main()
{
int n;
cout << "Podaj gorny zakres zbioru: ";
cin >> n;
cout << "\n\n";
liczba(n);
cout << endl;
system("pause");
return 0;
}
| true |
716e60f764cac97b256f6228ce82ff377a71667b | C++ | GustavoAC/SOMBRA | /src/main.cpp | UTF-8 | 14,652 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <memory>
#include <vector>
#include "canvas.h"
#include "circle.h"
#include "line.h"
#include "point.h"
#include "polygon.h"
#include "polyline.h"
#include "tinyxml.h"
Pixel GET_COLOR(const std::string& colorName) {
if (colorName == "black") return COLOR_BLACK;
if (colorName == "red") return COLOR_RED;
if (colorName == "green") return COLOR_GREEN;
if (colorName == "blue") return COLOR_BLUE;
if (colorName == "cyan") return COLOR_CYAN;
if (colorName == "yellow") return COLOR_YELLOW;
if (colorName == "magenta") return COLOR_MAGENTA;
if (colorName == "orange") return COLOR_ORANGE;
if (colorName == "purple") return COLOR_PURPLE;
return COLOR_WHITE;
}
Shape* readShape(TiXmlNode* pShape) {
std::string shapeValue(pShape->Value());
if (shapeValue == "line") {
std::shared_ptr<int> x1;
std::shared_ptr<int> y1;
std::shared_ptr<int> x2;
std::shared_ptr<int> y2;
int width = 1;
Pixel color = COLOR_BLACK;
TiXmlAttribute* pAttrib = pShape->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "x1") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
x1 = std::make_shared<int>(ival);
} else if (attribName == "y1") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
y1 = std::make_shared<int>(ival);
} else if (attribName == "x2") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
x2 = std::make_shared<int>(ival);
} else if (attribName == "y2") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
y2 = std::make_shared<int>(ival);
} else if (attribName == "width") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) width = ival;
} else if (attribName == "color") {
color = GET_COLOR(std::string(pAttrib->Value()));
} else if (attribName == "color_r") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setR(ival);
} else if (attribName == "color_g") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setG(ival);
} else if (attribName == "color_b") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setB(ival);
}
pAttrib = pAttrib->Next();
}
if (x1 == nullptr || x2 == nullptr || y1 == nullptr || y2 == nullptr) {
std::cout << "Unable to create line with given parameters\n";
return nullptr;
}
Shape* s = new Line(Point(*x1, *y1), Point(*x2, *y2), width, color);
return s;
} else if (shapeValue == "polyline") {
// if empty return null
if (pShape->FirstChild() == nullptr) return nullptr;
int width = 1;
Pixel color = COLOR_BLACK;
TiXmlAttribute* pAttrib = pShape->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "width") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) width = ival;
} else if (attribName == "color") {
color = GET_COLOR(std::string(pAttrib->Value()));
} else if (attribName == "color_r") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setR(ival);
} else if (attribName == "color_g") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setG(ival);
} else if (attribName == "color_b") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setB(ival);
}
pAttrib = pAttrib->Next();
}
Polyline* s = new Polyline(color, width);
TiXmlNode* pChild;
for (pChild = pShape->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT &&
std::string(pChild->Value()) == "point") {
std::shared_ptr<int> x;
std::shared_ptr<int> y;
TiXmlAttribute* pAttrib = pChild->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "x") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
x = std::make_shared<int>(ival);
} else if (attribName == "y") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
y = std::make_shared<int>(ival);
}
pAttrib = pAttrib->Next();
}
if (x == nullptr || y == nullptr) {
std::cout << "Unable to create point with given parameters\n";
continue;
}
s->addPoint(Point(*x, *y));
}
}
return s;
} else if (shapeValue == "polygon") {
// if empty return null
if (pShape->FirstChild() == nullptr) return nullptr;
int width = 1;
Pixel stroke_color = COLOR_BLACK;
std::shared_ptr<Pixel> fill_color;
TiXmlAttribute* pAttrib = pShape->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "width") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) width = ival;
} else if (attribName == "stroke_color") {
stroke_color = GET_COLOR(std::string(pAttrib->Value()));
} else if (attribName == "fill_color") {
fill_color = std::make_shared<Pixel>(GET_COLOR(std::string(pAttrib->Value())));
} else if (attribName == "stroke_color_r") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) stroke_color.setR(ival);
} else if (attribName == "stroke_color_g") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) stroke_color.setG(ival);
} else if (attribName == "stroke_color_b") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) stroke_color.setB(ival);
} else if (attribName == "fill_color_r") {
if (fill_color == nullptr) fill_color = std::make_shared<Pixel>(COLOR_BLACK);
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) fill_color->setR(ival);
} else if (attribName == "fill_color_g") {
if (fill_color == nullptr) fill_color = std::make_shared<Pixel>(COLOR_BLACK);
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) fill_color->setG(ival);
} else if (attribName == "fill_color_b") {
if (fill_color == nullptr) fill_color = std::make_shared<Pixel>(COLOR_BLACK);
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) fill_color->setB(ival);
}
pAttrib = pAttrib->Next();
}
std::vector<Point> points;
TiXmlNode* pChild;
for (pChild = pShape->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT &&
std::string(pChild->Value()) == "point") {
std::shared_ptr<int> x;
std::shared_ptr<int> y;
TiXmlAttribute* pAttrib = pChild->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "x") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
x = std::make_shared<int>(ival);
} else if (attribName == "y") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
y = std::make_shared<int>(ival);
}
pAttrib = pAttrib->Next();
}
if (x == nullptr || y == nullptr) {
std::cout << "Unable to create point with given parameters\n";
continue;
}
points.push_back(Point(*x, *y));
}
}
Polygon* s = new Polygon(points, stroke_color, width);
if (fill_color != nullptr) s->setFillColor(*fill_color);
return s;
} else if (shapeValue == "circle") {
std::shared_ptr<int> x;
std::shared_ptr<int> y;
std::shared_ptr<int> radius;
std::shared_ptr<Pixel> fill_color;
Pixel stroke_color = COLOR_BLACK;
TiXmlAttribute* pAttrib = pShape->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "x") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) x = std::make_shared<int>(ival);
} else if (attribName == "y") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) y = std::make_shared<int>(ival);
} else if (attribName == "radius") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS)
radius = std::make_shared<int>(ival);
} else if (attribName == "fill_color") {
fill_color = std::make_shared<Pixel>(GET_COLOR(std::string(pAttrib->Value())));
} else if (attribName == "stroke_color") {
stroke_color = GET_COLOR(std::string(pAttrib->Value()));
} else if (attribName == "stroke_color_r") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) stroke_color.setR(ival);
} else if (attribName == "stroke_color_g") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) stroke_color.setG(ival);
} else if (attribName == "stroke_color_b") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) stroke_color.setB(ival);
} else if (attribName == "fill_color_r") {
if (fill_color == nullptr) fill_color = std::make_shared<Pixel>(COLOR_BLACK);
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) fill_color->setR(ival);
} else if (attribName == "fill_color_g") {
if (fill_color == nullptr) fill_color = std::make_shared<Pixel>(COLOR_BLACK);
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) fill_color->setG(ival);
} else if (attribName == "fill_color_b") {
if (fill_color == nullptr) fill_color = std::make_shared<Pixel>(COLOR_BLACK);
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) fill_color->setB(ival);
}
pAttrib = pAttrib->Next();
}
if (x == nullptr || y == nullptr || radius == nullptr) {
std::cout << "Unable to create circle with given parameters\n";
return nullptr;
}
Shape* s;
if (fill_color == nullptr)
s = new Circle(Point(*x, *y), *radius, stroke_color);
else
s = new Circle(Point(*x, *y), *radius, stroke_color, *fill_color);
return s;
}
return nullptr;
}
void addShapesToCanvas(Canvas* canvas, TiXmlNode* pXmlCanvas) {
TiXmlNode* pChild;
for (pChild = pXmlCanvas->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT) {
Shape* s = readShape(pChild);
if (s != nullptr) {
canvas->draw(*s);
delete s;
}
}
}
}
Canvas* createCanvas(TiXmlNode* pParent) {
if (!pParent) return nullptr;
int t = pParent->Type();
switch (t) {
case TiXmlNode::TINYXML_ELEMENT:
if (std::string(pParent->Value()) == "canvas") {
int height = -1;
int width = -1;
Pixel color = COLOR_WHITE;
TiXmlAttribute* pAttrib = pParent->ToElement()->FirstAttribute();
int ival;
while (pAttrib) {
std::string attribName(pAttrib->Name());
if (attribName == "width") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) width = ival;
} else if (attribName == "height") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) height = ival;
} else if (attribName == "color") {
color = GET_COLOR(std::string(pAttrib->Value()));
} else if (attribName == "color_r") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setR(ival);
} else if (attribName == "color_g") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setG(ival);
} else if (attribName == "color_b") {
if (pAttrib->QueryIntValue(&ival) == TIXML_SUCCESS) color.setB(ival);
}
pAttrib = pAttrib->Next();
}
if (width < 0 || height < 0) {
std::cout << "Please specify positive values for canvas width and height\n";
return nullptr;
}
std::cout << "Creating Canvas...\n";
Canvas* canvas = new Canvas(width, height, color);
addShapesToCanvas(canvas, pParent);
return canvas;
}
break;
default:
break;
}
Canvas* canvas = nullptr;
TiXmlNode* pChild;
for (pChild = pParent->FirstChild(); pChild != 0 && canvas == nullptr;
pChild = pChild->NextSibling()) {
canvas = createCanvas(pChild);
}
return canvas;
}
int main(int argc, char const* argv[]) {
if (argc < 2) {
std::cout << "Please insert the xml description path as an argument" << std::endl;
return 1;
}
TiXmlDocument doc(argv[1]);
if (!doc.LoadFile()) {
std::cout << "Cannot parse the file\n";
return 1;
}
Canvas* canvas = createCanvas(&doc);
if (argc > 2)
canvas->writeToFile(argv[2]);
else
canvas->writeToFile(argv[1]);
delete canvas;
return 0;
} | true |
314a5a68e3a5b3cb50438cc4e19a481d4dfab48a | C++ | robertocosta/uep | /src/uep_encoder.hpp | UTF-8 | 13,220 | 2.59375 | 3 | [] | no_license | #ifndef UEP_UEP_ENCODER_HPP
#define UEP_UEP_ENCODER_HPP
#include "encoder.hpp"
#include "lt_param_set.hpp"
namespace uep {
/** Unequal error protection encoder.
* This class wraps an lt_encoder and passes it the expanded
* blocks. The pushed packets are stored in multiple queues,
* mantaining the order between packets with the same pariority. They
* are used to build expanded blocks according to the Ks, RFs and EF
* parameters.
*/
template <class Gen = std::random_device>
class uep_encoder {
typedef block_queue<uep_packet> queue_type;
public:
/** The collection of parameters required to setup the encoder. */
typedef lt_uep_parameter_set parameter_set;
/** The type of the object called to seed the row generator at each
* new block.
*/
typedef Gen seed_generator_type;
/** Iterator over the current block. */
//typedef typename lt_encoder<Gen>::const_block_iterator const_block_iterator;
static constexpr std::size_t BLOCK_WINDOW = lt_encoder<Gen>::BLOCK_WINDOW;
static constexpr std::size_t MAX_BLOCKNO = lt_encoder<Gen>::MAX_BLOCKNO;
static constexpr std::size_t MAX_SEQNO = uep_packet::MAX_SEQNO;
/** Construct using the given parameter set. */
explicit uep_encoder(const parameter_set &ps);
/** Construct using the given sub-block sizes, repetition factors,
* expansion factor, c and delta.
*/
template<typename KsIter, typename RFsIter>
explicit uep_encoder(KsIter ks_begin, KsIter ks_end,
RFsIter rfs_begin, RFsIter rfs_end,
std::size_t ef,
double c,
double delta);
/** Enqueue a packet according to its priority level. */
void push(fountain_packet &&p);
/** Enqueue a packet according to its priority level. */
void push(const fountain_packet &p);
/** Enqueue a packet with default priority 0. */
void push (packet &&p);
/** Enqueue a packet with default priority 0. */
void push (const packet &p);
/** Generate the next coded packet from the current block. */
fountain_packet next_coded();
/** Fill a partial block with padding packets. This allows to encode
* even if there are no more source packets to be passed.
*/
void pad_partial_block();
/** Drop the current block of packets and prepare to encode the next
* one.
*/
void next_block();
/** Drop all the blocks up to the given block number.
* This method throws an exception if there are not enough queued
* packets to skip.
*/
void next_block(std::size_t bn);
/** Return true when the encoder has been passed at least K packets
* and is ready to produce a coded packet.
*/
bool has_block() const;
/** The block size used by the underlying standard LT encoder. */
std::size_t block_size_out() const;
/** The block size used when considering the input packets. */
std::size_t block_size() const;
/** Alias of block_size. */
std::size_t block_size_in() const;
/** Alias of block_size. */
std::size_t K() const;
/** Constant reference to the array of blocksizes. */
const std::vector<std::size_t> &block_sizes() const;
/** The sequence number of the current block. */
std::size_t blockno() const;
/** Return a copy of the current block number counter. */
circular_counter<std::size_t> block_number_counter() const;
/** The sequence number of the last generated packet. */
std::size_t seqno() const;
/** The seed used in the current block. */
int block_seed() const;
/** The number of queued packets, excluding the current block. */
std::size_t queue_size() const;
/** Total number of (input) packets held by the encoder. */
std::size_t size() const;
/** Return the lt_row_generator used. */
const uep_row_generator &row_generator() const;
/** Return a copy of the RNG used to produce the block seeds. */
seed_generator_type seed_generator() const;
/** Return an iterator to the start of the current block. */
//const_block_iterator current_block_begin() const;
/** Return an iterator to the end of the current block. */
//const_block_iterator current_block_end() const;
/** Return the number of coded packets that were produced for the
* current block.
*/
std::size_t coded_count() const;
/** Return the total number of coded packets that were produced. */
std::size_t total_coded_count() const;
/** Number of padding packets added to the current block. */
std::size_t padding_count() const;
/** Total number of padding packets added to all blocks. */
std::size_t total_padding_count() const;
/** Is true when coded packets can be produced. */
explicit operator bool() const;
/** Is true when there is not a full block available. */
bool operator!() const;
/** Return the average time to extract a new packet up to now. */
double average_encoding_time() const {
return _enc_time_avg.value();
}
private:
log::default_logger basic_lg, perf_lg;
std::vector<queue_type> inp_queues; /**< The queues that
* store the packets
* belonging to
* different priority
* classes.
*/
circular_counter<> seqno_ctr; /**< Circular counter for the UEP
* sequence numbers.
*/
std::unique_ptr<lt_encoder<Gen>> std_enc; /**< The standard LT
* encoder. Use a
* pointer to allow
* non-movable seed
* generators.
*/
std::size_t pktsize; /**< The size of the pushed packets. */
stat::sum_counter<std::size_t> padding_cnt; /**< Number of padding
* packets.
*/
stat::average_counter _enc_time_avg; /**< Record the average
* encoding time.
*/
/** Check whether the queues have enough packets to build a block. */
void check_has_block();
};
// uep_decoder<Gen> template definitions
template <class Gen>
template<typename KsIter, typename RFsIter>
uep_encoder<Gen>::uep_encoder(KsIter ks_begin, KsIter ks_end,
RFsIter rfs_begin, RFsIter rfs_end,
std::size_t ef,
double c,
double delta) :
basic_lg(boost::log::keywords::channel = log::basic),
perf_lg(boost::log::keywords::channel = log::performance),
seqno_ctr(std::numeric_limits<uep_packet::seqno_type>::max()),
pktsize(0) {
auto uep_rowgen = std::make_unique<uep_row_generator>(ks_begin, ks_end,
rfs_begin, rfs_end,
ef,
c,
delta);
const auto &Ks = uep_rowgen->Ks();
inp_queues.reserve(Ks.size());
for (std::size_t Ki : Ks) {
inp_queues.emplace_back(Ki);
}
seqno_ctr.set(0);
std_enc = std::make_unique<lt_encoder<Gen>>(std::move(uep_rowgen));
}
template<typename Gen>
uep_encoder<Gen>::uep_encoder(const parameter_set &ps) :
uep_encoder(ps.Ks.begin(), ps.Ks.end(),
ps.RFs.begin(), ps.RFs.end(),
ps.EF,
ps.c,
ps.delta) {
}
template <class Gen>
void uep_encoder<Gen>::push(const fountain_packet &p) {
using std::move;
fountain_packet p_copy(p);
push(move(p_copy));
}
template <class Gen>
void uep_encoder<Gen>::push(fountain_packet &&p) {
if (pktsize == 0) pktsize = p.buffer().size();
else if (pktsize != p.buffer().size()) {
throw std::invalid_argument("The packets must have the same size");
}
uep_packet up(std::move(p.buffer()));
up.priority(p.getPriority());
up.sequence_number(seqno_ctr.value());
BOOST_LOG(perf_lg) << "uep_encoder::push new_packet"
<< " orig_size=" << up.buffer().size()
<< " priority=" << up.priority()
<< " seqno=" << up.sequence_number();
if (inp_queues.size() <= up.priority())
throw std::runtime_error("Priority is out of range");
inp_queues[up.priority()].push(std::move(up));
seqno_ctr.next();
check_has_block();
}
template <class Gen>
void uep_encoder<Gen>::push(packet &&p) {
fountain_packet fp(std::move(p));
fp.setPriority(0);
push(std::move(p));
}
template <class Gen>
void uep_encoder<Gen>::push(const packet &p) {
packet p_copy(p);
push(std::move(p));
}
template <class Gen>
fountain_packet uep_encoder<Gen>::next_coded() {
using namespace std::chrono;
auto t = high_resolution_clock::now();
fountain_packet coded_p = std_enc->next_coded();
duration<double> tdiff = high_resolution_clock::now() - t;
_enc_time_avg.add_sample(tdiff.count());
return coded_p;
}
template<typename Gen>
void uep_encoder<Gen>::pad_partial_block() {
if (has_block()) return;
std::size_t pad_cnt = 0;
for (queue_type &q : inp_queues) {
while (!q.has_block()) {
// Don't give the padding pkts a seqno
q.push(uep_packet::make_padding(pktsize));
++pad_cnt;
}
}
padding_cnt.add_sample(pad_cnt);
BOOST_LOG(perf_lg) << "uep_encoder::pad_partial_block"
<< " pad_cnt=" << pad_cnt;
check_has_block();
}
template <class Gen>
void uep_encoder<Gen>::next_block() {
std_enc->next_block();
padding_cnt.clear_last();
check_has_block();
}
template <class Gen>
void uep_encoder<Gen>::next_block(std::size_t bn) {
auto curr_bnc = std_enc->block_number_counter();
auto wanted_bnc(curr_bnc);
wanted_bnc.set(bn);
// Ignore if not in the comp. window
if (!wanted_bnc.is_after(curr_bnc)) return;
std::size_t dist = curr_bnc.forward_distance(wanted_bnc);
// Drop `dist-1` blocks from the queues
for (std::size_t i = 0; i < dist - 1; ++i) {
for (queue_type &iq : inp_queues) {
iq.pop_block();
}
}
// Push `dist-1` empty blocks
for (std::size_t i = 0; i < K() * (dist - 1); ++i) {
std_enc->push(packet());
}
std_enc->next_block(bn);
padding_cnt.clear_last();
check_has_block();
}
template <class Gen>
bool uep_encoder<Gen>::has_block() const {
return std_enc->has_block();
}
template <class Gen>
std::size_t uep_encoder<Gen>::block_size_out() const {
return row_generator().K_out();
}
template <class Gen>
std::size_t uep_encoder<Gen>::block_size() const {
return row_generator().K_in();
}
template <class Gen>
std::size_t uep_encoder<Gen>::block_size_in() const {
return block_size();
}
template <class Gen>
std::size_t uep_encoder<Gen>::K() const {
return block_size();
}
template <class Gen>
const std::vector<std::size_t> &uep_encoder<Gen>::block_sizes() const {
return row_generator().Ks();
}
template <class Gen>
std::size_t uep_encoder<Gen>::blockno() const {
return std_enc->blockno();
}
template <class Gen>
circular_counter<std::size_t> uep_encoder<Gen>::block_number_counter() const {
return std_enc->block_number_counter();
}
template <class Gen>
std::size_t uep_encoder<Gen>::seqno() const {
return std_enc->seqno();
}
template <class Gen>
int uep_encoder<Gen>::block_seed() const {
return std_enc->block_seed();
}
template <class Gen>
std::size_t uep_encoder<Gen>::queue_size() const {
return std::accumulate(inp_queues.cbegin(),
inp_queues.cend(),
0,
[](std::size_t sum,
const queue_type &iq) -> std::size_t {
return sum + iq.size();
});
}
template <class Gen>
std::size_t uep_encoder<Gen>::size() const {
return queue_size() + std_enc->size();
}
template <class Gen>
const uep_row_generator &uep_encoder<Gen>::row_generator() const {
return static_cast<const uep_row_generator&>(std_enc->row_generator());
}
template <class Gen>
typename uep_encoder<Gen>::seed_generator_type
uep_encoder<Gen>::seed_generator() const {
return std_enc->seed_generator();
}
// template <class Gen>
// typename uep_encoder<Gen>::const_block_iterator
// uep_encoder<Gen>::current_block_begin() const {
// return std_enc->current_block_begin();
// }
// template <class Gen>
// typename uep_encoder<Gen>::const_block_iterator
// uep_encoder<Gen>::current_block_end() const {
// return std_enc->current_block_end();
// }
template <class Gen>
std::size_t uep_encoder<Gen>::coded_count() const {
return std_enc->coded_count();
}
template <class Gen>
std::size_t uep_encoder<Gen>::total_coded_count() const {
return std_enc->total_coded_count();
}
template <class Gen>
uep_encoder<Gen>::operator bool() const {
return has_block();
}
template <class Gen>
bool uep_encoder<Gen>::operator!() const {
return !has_block();
}
template <class Gen>
void uep_encoder<Gen>::check_has_block() {
if (std_enc->has_block()) return; // Already has a block
if (std::any_of(inp_queues.cbegin(),
inp_queues.cend(),
[](const queue_type &q){
return !q.has_block();
})) {
return; // Not all sub-blocks are available
}
// Count the non-padding packets for each sub-block
std::vector<std::size_t> pkt_counts(inp_queues.size(), 0);
// Iterate over all queues
for (std::size_t i = 0; i < inp_queues.size(); ++i) {
queue_type &q = inp_queues[i];
// Convert the sub-block to packets
for (auto l = q.block_begin(); l != q.block_end(); ++l) {
const uep_packet &p = *l;
if (!p.padding()) ++pkt_counts[i];
std_enc->push(p.to_packet());
}
q.pop_block();
}
BOOST_LOG(perf_lg) << "uep_encoder::check_has_block"
<< " new_block"
<< " non_padding_pkts=" << pkt_counts;
}
template<typename Gen>
std::size_t uep_encoder<Gen>::padding_count() const {
return padding_cnt.last_sample(0);
}
template<typename Gen>
std::size_t uep_encoder<Gen>::total_padding_count() const {
return padding_cnt.value();
}
}
#endif
| true |
99e755854df40abdad7b0a2c4a7ea0bd43bf2d62 | C++ | harshchobisa/CS32 | /Project 3/ZombieDash/StudentWorld.cpp | UTF-8 | 15,353 | 2.96875 | 3 | [] | no_license | #include "StudentWorld.h"
#include "GameConstants.h"
#include <string>
#include <sstream>
#include <iomanip>
#include "Actor.h"
#include "Level.h"
using namespace std;
class Actor;
GameWorld* createStudentWorld(string assetPath)
{
return new StudentWorld(assetPath);
}
StudentWorld::StudentWorld(std::string assetDir):
GameWorld(assetDir)
{
m_numCitizens = 0;
m_finished = false;
}
StudentWorld::~StudentWorld()
{
cleanUp();
}
// Initializes the level and places all the actors where they need to be based on the level text file specification.
int StudentWorld::init()
{
Level lev(assetPath());
updateLevelString();
string levelFile = m_levelString;
//string levelFile = "level03.txt";
m_numCitizens = 0;
m_finished = false;
Level::LoadResult result = lev.loadLevel(levelFile);
if (result == Level::load_fail_file_not_found)
cerr << "Cannot find level01.txt data file" << endl;
else if (result == Level::load_fail_bad_format)
cerr << "Your level was improperly formatted" << endl;
else if (result == Level::load_success)
{
cerr << "Successfully loaded level" << endl;
for (int x = 0; x < LEVEL_WIDTH; x++)
{
for (int y = 0; y < LEVEL_HEIGHT; y++)
{
Level::MazeEntry ge = lev.getContentsOf(x,y); // level_x=5, level_y=10
double startX = x * 16;
double startY = y * 16;
switch (ge) // so x=80 and y=160
{
case Level::empty:
//cout << "Location 80,160 is empty" << endl; break;
break;
case Level::player:
{
cout << "Location " << startX << "," << startY << " starts with the player" << endl;
m_penelope = new Penelope(this, startX,startY);
//cout << typeid(*m_penelope).name() << endl;
break;
}
case Level::wall:
{
cout << "Location " << startX << "," << startY << " starts with a wall" << endl;
Actor *wll = new Wall(this, startX,startY);
//cout << typeid(*wll).name() << endl;
m_actors.push_back(wll);
break;
}
case Level::dumb_zombie:
{
cout << "Location " << startX << "," << startY << " starts with a dumb zombie" << endl;
Actor *dz = new DumbZombie(this, startX, startY);
m_actors.push_back(dz);
break;
}
case Level::smart_zombie:
{
cout << "Location " << startX << "," << startY << " starts with a smart zombie" << endl;
Actor *sz = new SmartZombie(this, startX, startY);
m_actors.push_back(sz);
break;
}
case Level::citizen:
{
cout << "Location " << startX << "," << startY << " starts with a citizen" << endl;
Actor *cz = new Citizen(this, startX, startY);
m_actors.push_back(cz);
m_numCitizens++;
break;
}
case Level::exit:
{
cout << "Location " << startX << "," << startY << " starts with a exit" << endl;
Actor *ex = new Exit(this, startX, startY);
m_actors.push_back(ex);
break;
}
case Level::pit:
{
cout << "Location " << startX << "," << startY << " starts with a pit" << endl;
Actor *p = new Pit(this, startX, startY);
m_actors.push_back(p);
break;
}
case Level::vaccine_goodie:
{
cout << "Location " << startX << "," << startY << " starts with a vaccine goodie" << endl;
Actor *vcc = new VaccineGoodie(this, startX, startY);
m_actors.push_back(vcc);
break;
}
case Level::gas_can_goodie:
{
cout << "Location " << startX << "," << startY << " starts with a gas can goodie" << endl;
Actor *gs = new GasCanGoodie(this, startX, startY);
m_actors.push_back(gs);
break;
}
case Level::landmine_goodie:
{
cout << "Location " << startX << "," << startY << " starts with a landmine goodie" << endl;
Actor *lm = new LandmineGoodie(this, startX, startY);
m_actors.push_back(lm);
break;
}
}
}
}
}
return GWSTATUS_CONTINUE_GAME;
}
//This function uses GameWorld’s virtual move(). The function runs the doSomething() for all actors.
//If Penelope dies, we end the game. If the level is finished, we end the game.
int StudentWorld::move()
{
m_penelope->doSomething();
vector<Actor*>:: iterator it;
it = m_actors.begin();
setGameStatText(createTitleString());
while (it != m_actors.end())
{
if (!((*it)->isDead()))
{
(*it)->doSomething();
if ((m_penelope->isDead()))
return GWSTATUS_PLAYER_DIED;
}
else{
vector<Actor*>:: iterator temp;
temp = it;
it--;
delete *temp;
m_actors.erase(temp);
}
it++;
}
cout << m_numCitizens << endl;
if (m_penelope->isDead())
{
return GWSTATUS_PLAYER_DIED;
}
if (m_finished)
{
if (getLevel() == 6)
return GWSTATUS_PLAYER_WON;
return GWSTATUS_FINISHED_LEVEL;
}
return GWSTATUS_CONTINUE_GAME;
}
//This function essentially creates the destructor by freeing up all of the dynamically allocated memory by deleting all the actors and Penelope.
void StudentWorld::cleanUp()
{
for (vector<Actor *>::iterator iter = m_actors.begin(); iter != m_actors.end(); )
{
delete *iter;
iter = m_actors.erase(iter);
}
delete m_penelope;
}
//For each actor that overlaps with A and is alive, take the appropriate action on A, such as burning it or picking up a goodie etc.
void StudentWorld::activateOnAppropriateActors(Actor * a)
{
if (!m_penelope->isDead() && overlap(m_penelope, a))
{
(a)->activateIfAppropriate(m_penelope);
}
vector<Actor*>:: iterator it;
it = m_actors.begin();
while (it != m_actors.end())
{
if (!(*it)->isDead() && overlap((*it), a) && (*it) != a)
{
(a)->activateIfAppropriate(*it);
}
it++;
}
}
//Adds dynamically created actors to the vector of actors I have.
void StudentWorld::addActor(Actor * a)
{
m_actors.push_back(a);
}
//Decrements m_numCitizens every time a citizen dies.
void StudentWorld::recordCitizenGone()
{
m_numCitizens--;
}
//If all the citizens are gone and Penelope exits, record that the level is finished and set m_finished to true.
void StudentWorld::recordLevelFinishedIfAllCitizensGone()
{
m_finished = true;
}
//Returns true if any actors that block movement’s bounding box intersect with the point x and y and that the blocking actor is not a.
bool StudentWorld::isAgentMovementBlockedAt(double x, double y, Actor* a) const ///HOW DO I STOP IT FROM BLOCKING ITSELF??????
{
int otherX = m_penelope->getX();
int otherY = m_penelope->getY();
if (x < otherX + SPRITE_WIDTH - 1 && x + SPRITE_WIDTH - 1 > otherX &&
y < otherY + SPRITE_HEIGHT - 1 && y + SPRITE_HEIGHT - 1 > otherY && m_penelope != a)
return true;
for (int i = 0; i < m_actors.size(); i++) {
if (m_actors[i]->blocksMovement() && m_actors[i] != a) {
otherX = m_actors[i]->getX();
otherY = m_actors[i]->getY();
if (x < otherX + SPRITE_WIDTH - 1 && x + SPRITE_WIDTH - 1 > otherX &&
y < otherY + SPRITE_HEIGHT - 1 && y + SPRITE_HEIGHT - 1 > otherY)
return true;
}
}
return false;
}
//Returns true is vomit is triggered at the point x,y.
bool StudentWorld::isZombieVomitTriggerAt(double x, double y, Actor * a) const
{
if (overlapPos(x, y, m_penelope))
return true;
for (int i = 0; i < m_actors.size(); i++)
{
if (m_actors[i]->triggersZombieVomit())
{
if (overlapPos(x, y, m_actors[i]))
{
return true;
}
}
}
return false;
}
//Finds the nearest Citizen or Penelope from the point x , y and sets distance to the distance of the actor found.
//Set otherX and otherY to the location of that object.
bool StudentWorld::locateNearestVomitTrigger(double x, double y, double & otherX, double & otherY, double & distance)
{
double smallestDist = (eucDist(x, y, m_penelope->getX(), m_penelope->getY()));
otherX = m_penelope->getX();
otherY = m_penelope->getY();
distance = smallestDist;
for(int z = 0; z < m_actors.size(); z ++)
{
if(m_actors[z]->triggersZombieVomit())
{
int x2 = m_actors[z]->getX();
int y2 = m_actors[z]->getY();
double temp = (eucDist(x, y, x2, y2));
if(temp < smallestDist)
{
otherX = x2;
otherY = y2;
distance = temp;
}
}
}
return true;
}
//Finds the nearest Penelope or Zombie to x, y and sets distance to the distance of the actor found.
//Set otherX and otherY to the location of that object. If we find a Penelope, set isThreat to true, else set it to false.
bool StudentWorld::locateNearestCitizenTrigger(double x, double y, double & otherX, double & otherY, double & distance, bool & isThreat) const
{
// compares closest zombie to penelope
double zombieX = 0, zombieY = 0, zombieDistance = 0.0;
double penelopeDistance = eucDist(x, y, m_penelope->getX(), m_penelope->getY());
if(!locateNearestCitizenThreat(x, y, zombieX, zombieY, zombieDistance) && penelopeDistance <= 6400)
{
otherX = m_penelope->getX();
otherY = m_penelope->getY();
distance = penelopeDistance;// getEuclideanDistance(x, y, otherX, otherY);
isThreat = false;
return true;
}
if(penelopeDistance < zombieDistance && penelopeDistance <= 6400)
{
//cerr << "Penelope: " << penelopeDistance << ", " << "Zombie: " << zombieDistance << endl;
otherX = m_penelope->getX();
otherY = m_penelope->getY();
distance = penelopeDistance;
isThreat = false;
return true;
}
if(zombieDistance <= 6400)
{
otherX = zombieX;
otherY = zombieY;
distance = zombieDistance;
isThreat = true;
return true;
}
return false;
}
//Finds the nearest to Zombie to x, y and sets distance to the distance of the actor found. Set otherX and otherY to the location of that object
bool StudentWorld::locateNearestCitizenThreat(double x, double y, double & otherX, double & otherY, double & distance) const
{
int zombieCount = 0;
if(m_actors.size() == 0)
{
return false;
}
distance = 9000 * 9000;
for(int i = 0; i < m_actors.size(); i++)
{
if(m_actors[i]->threatensCitizens())
{
zombieCount++;
int x2 = m_actors[i]->getX();
int y2 = m_actors[i]->getY();
double tempDistance = eucDist(x, y, x2, y2);
if (tempDistance < distance)
{
distance = tempDistance;
otherX = x2;
otherY = y2;
}
}
}
if (zombieCount == 0) return false;
return true;
}
//returns the euclidian distance between two points
double StudentWorld::eucDist(double x1, double y1, double x2, double y2) const
{
double xdiff = ((x1 + SPRITE_WIDTH/ 2) - (x2 + SPRITE_WIDTH/ 2));
double ydiff = ((y1 + SPRITE_HEIGHT/ 2) - (y2 + SPRITE_HEIGHT/ 2));
xdiff = xdiff * xdiff;
ydiff = ydiff * ydiff;
return (xdiff + ydiff);
}
//returns true is the two objects overlap
bool StudentWorld::overlap(Actor *a, Actor *b) const
{
return ((eucDist(a->getX(), a->getY(), b->getX(), b->getY())) <= 100);
}
//returns true is the an object and an object at point X,Y overlap
bool StudentWorld::overlapPos(double X, double Y, Actor *b) const
{
return ((eucDist(X, Y, b->getX(), b->getY())) <= 100);
}
//Returns true is flames are blocked at the point x,y.
bool StudentWorld::isFlameBlockedAt(double x, double y) const
{
for (int z = 0; z < m_actors.size(); z++)
{
if (m_actors[z]->blocksFlame())
{
int otherX = m_actors[z]->getX();
int otherY = m_actors[z]->getY();
if (x < otherX + SPRITE_WIDTH - 1 && x + SPRITE_WIDTH - 1 > otherX &&
y < otherY + SPRITE_HEIGHT - 1 && y + SPRITE_HEIGHT - 1 > otherY)
return true;
}
}
return false;
}
//uses stringstreams to create the status bar of the game
string StudentWorld::createTitleString()
{
ostringstream oss;
oss << "Score: ";
oss.fill('0');
if (getScore() >= 0) {
oss << setw(6) << getScore() << " ";
}
else {
oss << "-" << setw(5) << -getScore() << " ";
}
oss << "Level: ";
oss << getLevel() << " ";
oss << "Lives: ";
oss << getLives() << " ";
oss << "Vaccines: ";
oss << m_penelope->getNumVaccines() << " ";
oss << "Flames: ";
oss << m_penelope->getNumFlameCharges() << " ";
oss << "Mines: ";
oss << m_penelope->getNumLandmines() << " ";
oss << "Infected: ";
oss << m_penelope->getInfectionDuration() << endl;
return oss.str();
}
//increments the level string to move to the next level
void StudentWorld::updateLevelString()
{
if (getLevel() < 7)
{
ostringstream oss;
oss << "level";
oss.fill('0');
oss << setw(2) << getLevel() << ".txt";
m_levelString = oss.str();
}
}
//returns true if m_numCitizens is equal to zero.
bool StudentWorld::noMoreCitizens()
{
if (m_numCitizens == 0)
return true;
return false;
}
//returns true is there are overlapping actors at point X,Y
bool StudentWorld::overlappingActors(double x, double y) const
{
if (overlapPos(x, y, m_penelope))
return true;
for(int x = 0; x < m_actors.size(); x++)
{
if (overlapPos(x, y, m_actors[x]))
return true;
}
return false;
}
| true |
e12f2269f4c7103aa68c7236b3441f04df400c84 | C++ | MatisFactory/COOLing | /source/cooling/algorithms/bounding_volume_hierarchy.hpp | UTF-8 | 1,042 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <cooling/export/cooling_dll.hpp>
#include <cooling/algorithms/algorithm.hpp>
#include <memory>
namespace Cooling
{
enum class AXIS
{
X, Y, Z
};
AXIS findLongestAxis(const AABB& sceneAABB);
bool sortXAxis(const ObjectPtr& a, const ObjectPtr& b);
bool sortYAxis(const ObjectPtr& a, const ObjectPtr& b);
bool sortZAxis(const ObjectPtr& a, const ObjectPtr& b);
struct BVHNode
{
BVHNode() {}
BVHNode(const Node& node) : node(node) {}
Node node;
std::unique_ptr<BVHNode> left;
std::unique_ptr<BVHNode> right;
};
class COOLING_DLL BoundingVolumeHierarchy : public Algorithm
{
public:
BoundingVolumeHierarchy() = default;
void init(const Objects& objects, const AABB& sceneAABB) override;
void cullObjects(const FrustumPlanes& planes) override;
private:
BVHNode buildTree(const Objects& objects) const;
void divideNode(BVHNode& parent) const;
AABB computeSceneAABB(const Objects& objects) const;
void traverse(BVHNode* node, const FrustumPlanes& planes);
private:
BVHNode m_root;
};
} // namespace Cooling
| true |
a966c0e4cb39c75b05fcfff6287f9e26b82c1156 | C++ | sowrov/ChronicleLogger | /ChronicleLogger/src/main/com/sowrov/util/logsystem/levels/LevelManager.cpp | UTF-8 | 938 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #include "LevelManager.h"
namespace com {
namespace sowrov {
namespace util {
namespace logsystem {
namespace levels {
LevelManager::LevelManager() {
this->currentLevel = LogLevel::DEBUG;
}
LevelManager::LevelManager(int level) {
this->currentLevel = level;
}
void LevelManager::setLevel(int level) {
this->currentLevel = level;
}
int LevelManager::getLevel() {
return this->currentLevel;
}
bool LevelManager::isEnableLevel(int level) {
if (level <= this->currentLevel) {
return true;
}
else {
return false;
}
}
std::string LevelManager::getLevelName (int level) {
if (level == 0) {
return "NoLog";
}
else if (level == 1) {
return "Fatal";
}
else if (level == 2) {
return "Critical";
}
else if (level == 3) {
return "Warning";
}
else if (level == 4) {
return "Info";
}
else if (level == 5) {
return "Debug";
}
else {
return "Unknown";
}
}
}
}
}
}
} | true |
6e780061282b702388aabfab1d9fbbc7523c9936 | C++ | alpha74/iIB | /Programming/Array/Maximum_Unsorted_Subarray.cpp | UTF-8 | 1,935 | 3.421875 | 3 | [] | no_license | // https://www.interviewbit.com/problems/maximum-unsorted-subarray/
// Read all comments only sequentially.
vector<int> Solution::subUnsort(vector<int> &A)
{
int size = A.size() ;
vector<int> ret ;
int start = -1, end = -1 ;
if( size < 2 )
{
ret.push_back( -1 ) ;
return ret ;
}
bool stop = false ;
// Start from start till order is broken
for( int i = 0 ; i < size-1 && stop == false ; i++ )
{
if( A[i] > A[i+1] )
{
start = i ;
stop = true ;
}
}
stop = false ;
// Start from end till order is broken
for( int i = size-1 ; i > 0 && stop == false ; i-- )
{
if( A[i-1] > A[i] )
{
stop = true ;
end = i ;
}
}
// Check if array is already sorted
if( start == -1 && end == -1 )
{
ret.push_back( -1 ) ;
return ret ;
}
// Find min element in range: start, end
int min = start ;
int max = end ;
for( int i = start ; i <= end ; i++ )
{
if( A[i] < A[min] )
min = i ;
if( A[i] > A[max] )
max = i ;
}
// Find if any element is > A[min] in range 0,start-1
int actual_start = -1 ;
for( int i = 0 ; i < start && actual_start == -1 ; i++ )
{
if( A[i] > A[min] )
actual_start = i ;
}
// Find if any element is < A[max] in range size-1, end+1
int actual_end = -1 ;
for( int i = size-1 ; i > end && actual_end == -1 ; i-- )
{
if( A[i] < A[max] )
actual_end = i ;
}
// Check if new start and end are found
if( actual_start != -1 )
start = actual_start ;
if( actual_end != -1 )
end = actual_end ;
// Set return
ret.push_back( start ) ;
ret.push_back( end ) ;
return ret ;
}
| true |
6422fa26a485e0adf0b7108f70e657396bc1fb61 | C++ | jucham/rouage | /src/engine/shared/MapLoader.cpp | UTF-8 | 3,083 | 2.65625 | 3 | [] | no_license | #include <cassert>
#include "MapLoader.h"
std::string TexData::tileSetFilename = "nomapset.png";
MapLoader::MapLoader(const char* fileName) : FileHandler(fileName),
m_iNumTilesMaxWidth(0),
m_iNumTilesMaxHeight(0),
m_iTotalNumTiles(),
m_aPhysicData(0),
m_aTexData(0),
m_aItemData(0),
m_ValidMap(true)
{}
MapLoader::~MapLoader()
{
delete[] m_aPhysicData;
delete[] m_aTexData;
delete[] m_aItemData;
delete[] m_aSpawnData;
}
void MapLoader::ReadHeader()
{
m_File >> m_iNumTilesMaxWidth >> m_iNumTilesMaxHeight;
const int MIN_NUM_TILES = 5;
if (m_iNumTilesMaxWidth < MIN_NUM_TILES && m_iNumTilesMaxHeight < MIN_NUM_TILES) {
printf("Invalid map : the dimensions are too small. Set them greater than %d\n", MIN_NUM_TILES);
m_ValidMap = false;
}
}
void MapLoader::ReadData()
{
ReadPhysicLayer();
ReadTextureLayer();
ReadItemLayer();
ReadSpawnLayer();
if (m_iTotalNumTiles[SPAWN_LAYER] <= 0) {
printf("Invalid map : the map contains zero spawn point. [%d]\n", m_iTotalNumTiles[SPAWN_LAYER]);
m_ValidMap = false;
}
}
void MapLoader::ReadPhysicLayer()
{
m_File >> m_iTotalNumTiles[PHYSIC_LAYER];
m_aPhysicData = new PhysicData[ m_iTotalNumTiles[PHYSIC_LAYER] ];
for(int i=0; i < m_iTotalNumTiles[PHYSIC_LAYER]; ++i)
{
m_File >> m_aPhysicData[i].x >> m_aPhysicData[i].y;
for(int j=0; j < 4; ++j) { m_File >> m_aPhysicData[i].m_iSideSolidity[j]; }
}
}
void MapLoader::ReadTextureLayer()
{
m_File >> m_iTotalNumTiles[TEXTURE_LAYER];
m_aTexData = new TexData[ m_iTotalNumTiles[TEXTURE_LAYER] ];
if (m_iTotalNumTiles[TEXTURE_LAYER] > 0) {
m_File >> TexData::tileSetFilename;
for(int i=0; i < m_iTotalNumTiles[TEXTURE_LAYER]; ++i)
{
m_File >> m_aTexData[i].x >> m_aTexData[i].y >> m_aTexData[i].texId;
}
}
}
void MapLoader::ReadItemLayer()
{
m_File >> m_iTotalNumTiles[ITEM_LAYER];
m_aItemData = new ItemData[ m_iTotalNumTiles[ITEM_LAYER] ];
for(int i=0; i < m_iTotalNumTiles[ITEM_LAYER]; ++i)
{
m_File >> m_aItemData[i].x >> m_aItemData[i].y;
m_File >> m_aItemData[i].itemType >> m_aItemData[i].type;
}
}
void MapLoader::ReadSpawnLayer()
{
m_File >> m_iTotalNumTiles[SPAWN_LAYER];
m_aSpawnData = new SpawnData[ m_iTotalNumTiles[SPAWN_LAYER] ];
for(int i=0; i < m_iTotalNumTiles[SPAWN_LAYER]; ++i)
{
m_File >> m_aSpawnData[i].x >> m_aSpawnData[i].y;
}
}
const PhysicData& MapLoader::getPhysicData(int index) const {return m_aPhysicData[index];}
const TexData& MapLoader::getTexData(int index) const {return m_aTexData[index];}
const ItemData& MapLoader::getItemData(int index) const {return m_aItemData[index];}
const SpawnData& MapLoader::getSpawnData(int index) const {return m_aSpawnData[index];}
int MapLoader::NumTilesMaxWidth() const {return m_iNumTilesMaxWidth;}
int MapLoader::NumTilesMaxHeight() const {return m_iNumTilesMaxHeight;}
int MapLoader::TotalNumTiles(int layer) const {return m_iTotalNumTiles[layer];}
bool MapLoader::IsValidMap() const {return m_ValidMap;}
| true |
5bc4bbc75dccc115f384337b0ab962b1cb777d59 | C++ | crackersamdjam/DMOJ-Solutions | /CCC/ccc20j4.cpp | UTF-8 | 472 | 2.609375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
void init(){
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
freopen("err.txt", "w", stderr);
#endif
}
int main(){
init();
string s, t;
cin>>s>>t;
for(int i = 0; i < t.size(); i++){
rotate(t.begin(), t.begin()+1, t.end());
if(~s.find(t))
return cout<<"yes", 0;
}
cout<<"no";
return 0;
} | true |
19391638924f3e1b64e4d172fa2ef605397d3cd4 | C++ | stejsoftware/ArduinoLibrary | /src/Button.h | UTF-8 | 1,570 | 3.1875 | 3 | [] | no_license | #ifndef __Button_h_
#define __Button_h_
#include <Arduino.h>
// the amount of time required to identify a latch
#define BUTTON_DEBOUNCE_DELAY 50
// the max amount of time allowed to identify a click / double click
#define BUTTON_CLICK_TIMEOUT 200
#define BUTTON_DOUBLE_CLICK_TIMEOUT 500
#define BUTTON_HELD_TIMEOUT 1000
class Button;
typedef void (*ButtonEventHandler)(Button &button);
enum ButtonEvent
{
bePressed,
beReleased,
beClick,
beDblClick,
beHeld,
ButtonEvent_Count
};
class Button
{
public:
// CTOR: creates a button object
// pin: the pin that the button is attached to
// pressed_value: either HIGH or LOW; the value indicating the (defaults to HIGH)
// button was pressed
Button(uint8_t pin, uint8_t pressed_value = HIGH, bool use_pullup = false);
~Button();
// setup an event handler
void attach(ButtonEvent event, ButtonEventHandler handler);
// returns the number of clicks that have occurred
uint8_t clicks() const;
// returns the current state of the button accounting for debounce
bool read();
// reads the button and executes events as they occur
void run();
private:
// executes an event
void fire(ButtonEvent event);
Button(const Button &rhs);
Button &operator=(const Button &rhs);
uint8_t m_pin;
bool m_pressed_is_high;
uint32_t m_debounce_t;
uint32_t m_click_t;
uint32_t m_dbl_click_t;
uint8_t m_click_count;
bool m_last_read;
bool m_current_state;
bool m_held;
ButtonEventHandler m_handler[ButtonEvent_Count];
};
#endif // __Button_h_
| true |
6db8dfb1f1d34e9f134baafcd463dfcc2164bca7 | C++ | sid5566/Cpp_Full_Course | /codeTR8.cpp | UTF-8 | 256 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
typedef union codeTR8 //trail of enum AND struct
{
/* data */
int eId;
}oa;
int main()
{
oa CODER;
CODER.eId = 1;
cout<<"The value is "<<CODER.eId<<endl;
return 0;
} | true |
33686eac3f0114a24b68144353ce3378fd19a60f | C++ | shreyasharma98/DSA | /21.Dynamic Programming/stairCase.cpp | UTF-8 | 1,430 | 3.375 | 3 | [] | no_license | #include<iostream>
using namespace std;
//DP
long staircase(int n){
long *arr = new long[n+1];
for(int i =0;i<=n;i++)
{
arr[i] = 0;
}
arr[0] = 0;
arr[1] = 1;
arr[2] = 1+arr[1];
arr[3] = 1+arr[1]+arr[2];
for(int i = 4;i<=n;i++)
{
arr[i] = arr[i-1] + arr[i-2] + arr[i-3];
}
int res = arr[n];
delete []arr;
return res;
}
//MEMOIZAATION
/*
long helper(int n,long *arr)
{
if(n == 0)
{
return 0;
}
if(n == 1)
{
return 1;
}
if(n == 2)
{
return 1+helper(n-1,arr);
}
if(n == 3)
{
return 1+helper(n-1,arr)+helper(n-2,arr);
}
if(arr[n]!=0)
{
return arr[n];
}
long one,two,three;
one = helper(n-1,arr);
two = helper(n-2,arr);
three = helper(n-3,arr);
arr[n] = one+two+three;
return one+two+three;
}
long staircase(int n){
long *arr = new long[n+1];
for(int i =0;i<=n;i++)
{
arr[i] = 0;
}
return helper(n,arr);
}
*/
//Brute Force
/*
long staircase(int n){
if(n == 0)
{
return 0;
}
if(n == 1)
{
return 1;
}
if(n == 2)
{
return 1+staircase(n-1);
}
if(n == 3)
{
return 1+staircase(n-1)+staircase(n-2);
}
return staircase(n-1)+staircase(n-2)+staircase(n-3);
}
*/
int main(){
int n;
cin >> n ;
cout << staircase(n) << endl;
}
| true |
714d3b93d684af1ea52b470e242c6dcecf4ec82a | C++ | nothingct/BOJ_CodingTest | /연결요소의개수.cpp | UTF-8 | 823 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX = 1001;
vector<int> g[MAX];
bool check[MAX];
void dfs(int x){
check[x] = true;
for(int i=0 ; i <g[x].size(); i++){
int y = g[x][i];
if(!check[y]) dfs(y);
}
}
void bfs(int start){
queue<int> q;
check[start]=true; q.push(start);
while(!q.empty()){
int x = q.front(); q.pop();
for(int i=0; i<g[x].size(); i++){
int y = g[x][i];
if(!check[y]){
check[y]=true; q.push(y);
}
}
}
}
int main(){
int n,m;
cin>>n>>m;
for(int i=0; i<m; i++){
int u,v;
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
int ans =0;
for(int i=1; i<=n; i++){
if(!check[i]){
ans++;
// dfs(i);
bfs(i);
}
}
cout<<ans<<'\n';
} | true |
6839185e3fc264452ed2ac8a600db5ed11e7812a | C++ | ooooo-youwillsee/leetcode | /0000-0500/0350-Intersection-of-Two-Arrays-II/cpp_0350/Solution1.h | UTF-8 | 902 | 2.984375 | 3 | [
"MIT"
] | permissive | //
// Created by ooooo on 2019/12/29.
//
#ifndef CPP_0350_SOLUTION1_H
#define CPP_0350_SOLUTION1_H
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> intersect(vector<int> &nums1, vector<int> &nums2) {
unordered_map<int, int> map;
for (const auto &num : nums1) {
if (map.find(num) == map.end()) {
map[num] = 1;
} else {
map[num] = map[num] + 1;
}
}
vector<int> res;
for (const auto &num : nums2) {
if (map.find(num) != map.end()) {
res.push_back(num);
if (map[num] == 1) {
map.erase(num);
} else {
map[num] -= 1;
}
}
}
return res;
}
};
#endif //CPP_0350_SOLUTION1_H
| true |