blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
9a910878cc2156fa598cf3e5fe5731b768fffc06
ae68506d397c28f95e8bfee86832cb951cd031aa
/castle venia/Castlevania/Fireball.cpp
161b5d83f00b93f755ed5adf50473307c7682c80
[]
no_license
yshaia7/castle-venia
7219191d01d7e4c85d43d197a5c48865b16a8e5a
594a99679f1c576ef4e4f712b4d2d417a4226c9b
refs/heads/master
2020-07-13T20:41:33.106408
2020-07-04T10:08:47
2020-07-04T10:08:47
205,150,725
0
0
null
null
null
null
UTF-8
C++
false
false
442
cpp
Fireball.cpp
#include "Fireball.h" //---------------------------------------------------------- Fireball::Fireball(sf::Vector2f origin, int direction) : Range(origin, direction) { m_velocity.x = 3; if (direction == 0) { m_velocity.x = -m_velocity.x; m_sprite.setOrigin({ m_sprite.getLocalBounds().left, 0 }); m_sprite.scale(-1, 1); } } //---------------------------------------------------------- Fireball::~Fireball() { }
be6bdf3236cc40dc9de79dc2dd0bea40ea20c2a4
773fcc0b33a9733ca1760db6b1bffb43364d8026
/_SAFC_/SAFC_InnerModules/CAT.h
0fda10a6b29b1017967db3f0b84ccab05ef2217a
[ "Apache-2.0" ]
permissive
DixelU/SAFC
e341b4a162c95edbee0e0639e43810d86779d95a
144325849ac460d5e78689cd06f6571ba3837366
refs/heads/master
2023-08-18T18:22:22.810386
2023-08-14T17:17:09
2023-08-14T17:17:09
167,155,875
8
0
Apache-2.0
2023-01-08T04:56:34
2019-01-23T09:30:31
C++
UTF-8
C++
false
false
633
h
CAT.h
#pragma once #ifndef SAF_CAT #define SAF_CAT #include <optional> #include <Windows.h> struct CutAndTransposeKeys { std::uint8_t Min, Max; std::int16_t TransposeVal; CutAndTransposeKeys(std::uint8_t Min, std::uint8_t Max, std::int16_t TransposeVal = 0) { this->Min = Min; this->Max = Max; this->TransposeVal = TransposeVal; } inline std::optional<std::uint8_t> process(std::uint8_t Value) { if (Value <= Max && Value >= Min) { std::int16_t SValue = (std::int16_t)Value + TransposeVal; if (SValue < 0 || SValue>255)return {}; Value = SValue; return Value; } else { return {}; } } }; #endif
b99c243c9eb537e4751e210ef872ffd47dfa5c59
a74acf296bd4380b4b98819c23b9b20fdf663c34
/opencv_project1/mainwindow.cpp
f9174b0db0608b00c3897fa31f32d4f3aebb38f6
[]
no_license
zenglingchang/Opencv_project
809adc73417b036e5cd68d09209b5b84269cdd13
b3a2cc0ff49ebe04471fadf1805ce55cdd460810
refs/heads/master
2020-03-15T00:17:53.069717
2018-05-22T07:57:07
2018-05-22T07:57:07
131,864,756
0
0
null
null
null
null
UTF-8
C++
false
false
7,386
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" int X[]={-1,1,0,0,1,1,-1,-1}; int Y[]={0,0,-1,1,-1,1,-1}; std::stack<std::pair<int,int>> S_p; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->spinBox->setMinimum(0); ui->spinBox->setMaximum(255); ui->spinBox->setSingleStep(1); ui->Slider->setMinimum(0); ui->Slider->setMaximum(255); ui->Slider->setSingleStep(5); connect(ui->spinBox,SIGNAL(valueChanged(int)),ui->Slider,SLOT(setValue(int))); connect(ui->Slider,SIGNAL(valueChanged(int)),ui->spinBox,SLOT(setValue(int))); p1=std::pair<int,int>(190,533),p2=std::pair<int,int>(510,810); } MainWindow::~MainWindow() { delete ui; } int MainWindow::d(cv::Vec3b a, cv::Vec3b b) { return std::sqrt((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1])+(a[2]-b[2])*(a[2]-b[2])); } void MainWindow::search_tree(cv::Mat &gray,cv::Mat &Fmat,std::pair<int,int> p,std::vector<std::pair<int,int>> &buffer) { S_p.push(p); std::pair<int,int> temp; p1.first=cv::max(p1.first,0),p1.second=cv::max(p1.second,0); p2.first=cv::min(p2.first,image.rows),p2.second=cv::min(p2.second,image.cols); qDebug()<<p1.first<<" "<<p1.second<<" "<<p2.first<<" "<<p2.second; while(!S_p.empty()){ temp=S_p.top(); S_p.pop(); for(int i=0;i<8;i++) if((temp.first+X[i]>p1.first&&temp.first+X[i]<p2.first)&&(temp.second+Y[i]>p1.second&&temp.second+Y[i]<p2.second)&& //(int)cabs(color,(gray.at<uchar>(temp.first+X[i],temp.second+Y[i])/4)+3*((aver/num))/4)<ui->spinBox->value()) 3*d(image.at<cv::Vec3b>(temp.first,temp.second),image.at<cv::Vec3b>(temp.first+X[i],temp.second+Y[i]))/4 +d(image.at<cv::Vec3b>(p.first,p.second),image.at<cv::Vec3b>(temp.first+X[i],temp.second+Y[i]))/4<ui->spinBox->value()) { if(Fmat.at<uchar>(temp.first+X[i],temp.second+Y[i])!=255){ //qDebug()<<temp.first<<" "<<temp.second<<" "<<d(image.at<cv::Vec3b>(temp.first,temp.second),image.at<cv::Vec3b>(temp.first+X[i],temp.second+Y[i]))<<" "<<ui->spinBox->value(); Fmat.at<uchar>(temp.first+X[i],temp.second+Y[i])=255; S_p.push(std::pair<int,int>(temp.first+X[i],temp.second+Y[i])); } } buffer.push_back(temp); } } void MainWindow::pooling(cv::Mat &src, cv::Mat &dst,int blockSize) { dst=src; int half=blockSize/2; cv::Mat iimage; cv::integral(src,iimage,CV_32S); qDebug()<<"start!"; for(int i=p1.first;i<p2.first;i++) { qDebug()<<i; int x1=cv::max(i-half,p1.first),x2=cv::min(i+half,p2.first-1); cv::Vec3b *data=dst.ptr<cv::Vec3b>(i); cv::Vec3i *idata1=iimage.ptr<cv::Vec3i>(x1); cv::Vec3i *idata2=iimage.ptr<cv::Vec3i>(x2); for(int j=p1.second;j<p2.second;j++) { int y1=cv::max(j-half,p1.second),y2=cv::min(j+half,p2.second-1),area=(y2-y1)*(x2-x1); if(data[j][0]==0&&data[j][1]==0&&data[j][2]==0){ for(int k=0;k<3;k++) data[j][k]=(idata2[y2][k]+idata1[y1][k]-idata1[y2][k]-idata2[y1][k])/area; //qDebug()<<i<<" "<<j<<" "<<data[j][0]<<" "<<data[j][1]<<" "<<data[j][2]<<" "<<area; } } } } void MainWindow::cut(cv::Mat &src, cv::Mat &gray_cut) { cv::Mat_<cv::Vec3b>::iterator itd=src.begin<cv::Vec3b>(); cv::Mat_<uchar>::iterator itc=gray_cut.begin<uchar>(); while(itc!=gray_cut.end<uchar>()){ if(*itc==255) (*itd)[0]=0,(*itd)[1]=0,(*itd)[2]=0; itc++,itd++; } } void MainWindow::func(cv::Mat &result) { cv::Mat Gcut=cv::imread("C:\\Users\\suning\\Desktop\\computer_vision\\opencv_1\\cut_tree.png"), temp=cv::imread("C:\\Users\\suning\\Desktop\\computer_vision\\opencv_1\\deal_tree.png"); cut(temp,Gcut); result=temp; //pooling(temp,result,4); cv::namedWindow("image",CV_WINDOW_NORMAL); cv::imshow("image",result); cv::resizeWindow("image",1000,(int)1000.0*image.size().height/image.size().width); } void MainWindow::on_pushButton_clicked() { cv::Mat temp; cv::cvtColor(image,temp,CV_BGR2RGB); cv::cvtColor(image,temp,CV_BGR2RGB);//opencv读取图片按照BGR方式读取,为了正常显示,所以将BGR转为RGB QImage showImage((const uchar*)temp.data,image.cols,image.rows,image.cols*image.channels(),QImage::Format_RGB888); showImage = showImage.scaled(ui->label->width(),ui->label->height(),Qt::KeepAspectRatio); ui->label->setPixmap(QPixmap::fromImage(showImage)); //将图片显示在QLabel上 } void MainWindow::on_pushButton_2_clicked() { std::vector<std::pair<int,int>> buffer; cv::Mat gray_img,flag_mat(cv::Size(image.cols,image.rows),CV_8UC1,cv::Scalar(0)),ima(cv::Size(image.cols,image.rows),CV_8UC3); cv::cvtColor(image,gray_img,CV_BGR2GRAY); search_tree(gray_img,flag_mat,std::pair<int,int>(ui->YEdit->text().toInt(),ui->XEdit->text().toInt()),buffer); for(auto p:buffer) for(int i=0;i<3;i++) ima.at<cv::Vec3b>(p.first,p.second)[i]=image.at<cv::Vec3b>(p.first,p.second)[i]; cv::namedWindow("test",CV_WINDOW_NORMAL); cv::namedWindow("gray",CV_WINDOW_NORMAL); cv::namedWindow("image",CV_WINDOW_NORMAL); cv::imshow("test",flag_mat); cv::imshow("gray",gray_img); cv::imshow("image",ima); cv::resizeWindow("test",1000,(int)1000.0*image.size().height/image.size().width); cv::resizeWindow("gray",1000,(int)1000.0*image.size().height/image.size().width); cv::resizeWindow("image",1000,(int)1000.0*image.size().height/image.size().width); } void MainWindow::on_pushButton_3_clicked() { cv::Mat result,iimage; func(result); for(int i=p1.first;i<p2.first;i++) { cv::Vec3b *data=result.ptr<cv::Vec3b>(i), *data1=image.ptr<cv::Vec3b>(i+5); for(int j=p1.second;j<p2.second;j++) { if(data[j][0]!=0||data[j][1]!=0||data[j][2]!=0){ for(int k=0;k<3;k++) data1[j-499][k]=data[j][k]; //qDebug()<<i<<" "<<j<<" "<<data[j][0]<<" "<<data[j][1]<<" "<<data[j][2]<<" "<<area; } } } int half=1; cv::integral(image,iimage,CV_32S); for(int i=p1.first;i<p2.first;i++) { qDebug()<<i; int x1=cv::max(i-half,p1.first),x2=cv::min(i+half,p2.first-1); cv::Vec3b *temp=result.ptr<cv::Vec3b>(i),*data=image.ptr<cv::Vec3b>(i+5); cv::Vec3i *idata1=iimage.ptr<cv::Vec3i>(x1+5); cv::Vec3i *idata2=iimage.ptr<cv::Vec3i>(x2+5); for(int j=p1.second;j<p2.second;j++) { int y1=cv::max(j-half,p1.second)-499,y2=cv::min(j+half,p2.second-1)-499,area=(y2-y1)*(x2-x1); if(temp[j][0]<2&&temp[j][1]<2&&temp[j][2]<2){ for(int k=0;k<3;k++) data[j-499][k]=(idata2[y2][k]+idata1[y1][k]-idata1[y2][k]-idata2[y1][k])/area; //qDebug()<<i<<" "<<j<<" "<<data[j][0]<<" "<<data[j][1]<<" "<<data[j][2]<<" "<<area; } } } } void MainWindow::on_pushButton_4_clicked() { cv::imwrite("C:\\Users\\suning\\Desktop\\computer_vision\\opencv_1\\save.jpg",image); }
e5e3bef506a03dbabcc094340e402746f2535f66
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir22441/dir22442/dir22443/dir22444/dir22630/file22794.cpp
e7fcc624845aa7e4e3a1b6710196fe132d536ee5
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file22794.cpp
#ifndef file22794 #error "macro file22794 must be defined" #endif static const char* file22794String = "file22794";
c4d1b0d534c66651c7f224925e56bc746c83f165
975f01015f94d67bdfdc9086bdafd8ac59332a0f
/source/ExerciseSet.h
e6f8f5e5a7ced42ade7287bab1d446d63466616f
[ "MIT" ]
permissive
R-Fehler/microbit-samples
55f3fd7a45e9e2c9dae8c9b3bd560b1912da7356
24dd4a1a3a28c3572b7142e03b39bfc65395b43c
refs/heads/master
2023-02-03T00:35:16.004423
2020-12-19T17:41:37
2020-12-19T17:41:37
174,408,960
0
0
null
null
null
null
UTF-8
C++
false
false
1,282
h
ExerciseSet.h
#ifndef MICROBIT_SAMPLES_EXERCISE_SET_H #define MICROBIT_SAMPLES_EXERCISE_SET_H #include "MicroBitEvent.h" #include "MicroBitUARTService.h" #include "Microbit.h" #include "TwoDigitDisplay.h" #include "myInput.h" #define DPTIMEUNTILFIRSTREP 300 #define MAX_FILTER_REDUCTION_CONSTANT 3 //#define ACCELOREMETERSERIALOUTPUT extern MicroBit uBit; extern MicroBitUARTService *uart; class ExerciseSet{ public: uint16_t weight; uint8_t reps; bool isDone; ExerciseSet(); ExerciseSet(int w, int r); void updateReps(){ // MicroBitEvent evt(SetRepsID,reps); } void updateWeight(){ // MicroBitEvent evt(SetWeightID,weight); } void updateIsDone(){ // MicroBitEvent evt(SetIsDoneID,isDone); } void cntReps(myInput& input, uint32_t threshold=1300000); private: Sample3D accel; Sample3D accelbuff; uint32_t buffer; uint32_t lowpass; uint32_t myForce(const Sample3D& sample) { return (uint32_t)sample.x*(uint32_t)sample.x + (uint32_t)sample.y*(uint32_t)sample.y + (uint32_t)sample.z*(uint32_t)sample.z; } uint32_t maxC(uint32_t a, uint32_t b) { return (a <= b) ? b : a; } uint32_t minC(uint32_t a, uint32_t b) { return (a >= b) ? b : a; } }; #endif // !MICROBIT_SAMPLES_EXERCISE_SET_H
0ab56edae6d793bf55c51e793b62b0b7a8fce46c
edab58696afb07657232f17490b24c8e1e11b6c2
/uva/1116.cpp
86cbe594bfb1a76622a4e04e0b3aa2ca8042ec1a
[]
no_license
mhcayan/competitive-programming
cd8e08da67138cfbdcd2d47cd70572a7fc6435fd
f80ab6929a5d2eb780d35679688ea39138cf9e8a
refs/heads/master
2022-05-27T15:03:46.147224
2022-05-22T00:21:29
2022-05-22T00:21:29
161,851,714
0
0
null
null
null
null
UTF-8
C++
false
false
287
cpp
1116.cpp
#include<stdio.h> int main() { long cas,t,n,e; scanf("%ld",&cas); for(t=1;t<=cas;t++) { scanf("%ld",&n); if(n%2) printf("Case %ld: Impossible\n",t); else { e=1; while(n%2==0) { n=n/2; e*=2; } printf("Case %ld: %ld %ld\n",t,n,e); } } return 0; }
8bac50fd79c6900726378d3e9c90b98c9a7de06f
971c8fef5e1c3e23a9fbba046e075a30c4508077
/Processamento Gráfico - TGB - Jogo 2D Tiles/Tile.h
22ef04c9a110955b399d55e3cc34437eba268bf7
[]
no_license
leofelix077/processamentoGrafico
2b58e3acc8e593278ae2984c0c26ea13a69d9a6c
3e799b1b1736b21325d59f75e1fe3e9f215b036f
refs/heads/master
2020-03-09T08:33:01.297204
2018-04-09T00:33:50
2018-04-09T00:33:50
128,691,869
0
1
null
null
null
null
UTF-8
C++
false
false
358
h
Tile.h
#pragma once #include "Image.h" //---------------------------------------------------------------------- //classe descontinuada class Tile { public: Tile(int id, Image *img) { this->id = id; this->img = img; } int getId() { return id; } //---------------------------------------------------------------------- private: int id; Image *img; };
1f3381b133b8fa8e188e0fa4e4d395498cfdc401
6799592f780197259b8217c70c7f905da233a2ed
/plugins/ftp/lib/DirList/unix.cpp
be7dcdbaf8c51050efd10bef02624c6d4ebe6c9b
[ "BSD-3-Clause" ]
permissive
FarGroup/FarManager
22b1f754a4cf4bcc6e1822a6ce66408fabf140d5
da34b0c6da3e03518b8ce7e53783e9fda518bac4
refs/heads/master
2023-08-20T04:52:54.443453
2023-08-12T20:53:56
2023-08-12T20:53:56
107,807,404
1,691
228
BSD-3-Clause
2023-09-14T20:07:19
2017-10-21T18:55:45
C++
UTF-8
C++
false
false
8,433
cpp
unix.cpp
#include <all_far.h> #pragma hdrstop #include "Int.h" #define MIN_DATETIME_STRING (3+4) //The minimal date-time string is "F 2000" /* *--Full format 1 2 3 4 5 6 7 01234567890123456789012345678901234567890123456789012345678901234567890123456789 Sep 1 1990 - start with ' ' Sep 11 11:59 Sep 11 01:59 - start with 0 Sep 11 1:59 - start with ' ' Dec 12 1989 FCv 23 1990 *--Short format: 1 2 3 4 5 6 7 01234567890123456789012345678901234567890123456789012345678901234567890123456789 f 01:07 - time f 01:7 - minutes with one digit F 15:43 f 2002 - only year *--Expanded format: 1 2 3 4 5 6 7 01234567890123456789012345678901234567890123456789012345678901234567890123456789 *2005-06-20 14:22 *2005-07-08 19:21 *2004-10-14 14:14 *2004-10-14 14:14 */ BOOL net_convert_unix_date(LPSTR& datestr, Time_t& decoded) { SYSTEMTIME st; GetSystemTime(&st); st.wMilliseconds = 0; st.wSecond = 0; st.wDayOfWeek = 0; char *bcol = datestr; /* Column begin */ char *ecol; /* Column end */ //Expanded format (DDDD-) if(NET_IS_DIGIT(bcol[0]) && NET_IS_DIGIT(bcol[1]) && NET_IS_DIGIT(bcol[2]) && NET_IS_DIGIT(bcol[3]) && bcol[4] == '-') { #define CVT( nm, start, end ) bcol[end] = 0; \ st.nm = atoi(bcol+start); \ CHECK( (st.nm == MAX_WORD), FALSE ) CVT(wYear, 0, 4) CVT(wMonth, 5, 7) CVT(wDay, 8, 10) CVT(wHour, 11, 13) CVT(wMinute,14, 16) #undef CVT datestr = bcol + 17; return SystemTimeToFileTime(&st, decoded); } //Month+day or short format // (ecol must be set to char after decoded part) if(NET_TO_UPPER(bcol[0]) == 'F' && NET_IS_SPACE(bcol[1])) { //Short format - ignore month and day ecol = bcol + 2; } else { //Month if(NET_IS_DIGIT(bcol[0]) && NET_IS_DIGIT(bcol[1]) && NET_IS_SPACE(bcol[2])) st.wMonth = AtoI(bcol,MAX_WORD); else st.wMonth = NET_MonthNo(datestr); CHECK((st.wMonth == MAX_WORD), FALSE) bcol = SkipSpace(SkipNSpace(bcol)); CHECK((*bcol == 0), FALSE) //Day ecol = SkipNSpace(bcol); if(*ecol != ' ') return FALSE; *ecol = 0; st.wDay = AtoI(bcol,MAX_WORD); *ecol = ' '; CHECK((st.wDay == MAX_WORD), FALSE) } //Year or time ecol = SkipSpace(ecol); bcol = ecol; if(bcol[2] != ':' && bcol[1] != ':') { //Four digits year ecol = SkipDigit(bcol); CHECK((ecol == bcol), FALSE) *ecol = 0; st.wYear = AtoI(bcol,MAX_WORD); ecol++; CHECK((st.wYear == MAX_WORD), FALSE) //Only first three digits of year with cut last digit if(st.wYear > 190 && st.wYear < 300) { st.wYear *= 10; } st.wSecond = 0; st.wMinute = 0; st.wHour = 0; } else { // Time /* If the time is given as hh:mm, then the file is less than 1 year * old, but we might shift calandar year. This is avoided by checking * if the date parsed is future or not. */ if(bcol[1] == ':') { bcol--; *bcol = '0'; } CHECK((!TwoDigits(bcol,st.wHour)), FALSE) //Time minutes may be specified by single digit //In this case next character is space CHECK((!NET_IS_DIGIT(bcol[3])), FALSE) if(bcol[4] == ' ') { st.wMinute = (0 + (bcol[3]-'0')) * 10; ecol = bcol + 5; } else { CHECK((!TwoDigits(bcol+3,st.wMinute)), FALSE) ecol = bcol + 6; } } datestr = ecol; if(SystemTimeToFileTime(&st, decoded)) return TRUE; CHECK((st.wDay < 31), FALSE) st.wDay = 30; return SystemTimeToFileTime(&st, decoded); } /* nlinks * group * owner size date|time * --------------------------------------------------------- * 2 montulli eng 512 Nov 8 23:23 CVS * 1 montulli eng 2244 Nov 8 23:23 Imakefile * root montulli eng 14615 Nov 9 17:03 Makefile * root root 6, 10 Jun 17 17:45 con10 * root root 6, 2 Jun 17 17:45 con2 */ BOOL net_parse_ls_line(char *line, NET_FileEntryInfo* entry_info, BOOL nLinks) { char *e; int len; //Skip nlinks if(nLinks) line = SkipNSpace(SkipSpace(line)); line = SkipSpace(line); CHECK((*line == 0), FALSE) //Owner e = SkipNSpace(line); CHECK((*e == 0), FALSE) len = Min((int)ARRAYSIZE(entry_info->FTPOwner)-1, (int)(e-line)); StrCpy(entry_info->FTPOwner, line, len+1); //Delimiter entry_info->FTPOwner[len++] = ':'; //Group line = SkipSpace(e); if(line[0] == '@' && line[1] == ' ') line = SkipSpace(line+1); e = SkipNSpace(line); CHECK((*e == 0), FALSE) StrCpy(entry_info->FTPOwner+len, line, Min((int)ARRAYSIZE(entry_info->FTPOwner) - len, (int)(e-line+1))); //Size line = SkipSpace(e); if(line[0] == '@' && line[1] == ' ') line = SkipSpace(line+1); e = SkipNSpace(line); //Check`n`Skip trailing ',' e--; if(*e == ',') { line = SkipSpace(e+1); e = SkipNSpace(line); } else e++; CHECK((*e == 0), FALSE) *e = 0; entry_info->size = AtoI(line, (__int64)-1); *e = ' '; CHECK((entry_info->size == (__int64)-1), FALSE) //Date line = SkipSpace(e); CHECK((!net_convert_unix_date(line,entry_info->date)), FALSE) //File name if(*line) { FTPHostPlugin* host = FTP_Info->GetHostOpt(); if(!host || !host->UseStartSpaces) line = SkipSpace(line); StrCpy(entry_info->FindData.cFileName, line, ARRAYSIZE(entry_info->FindData.cFileName)); } else { entry_info->FindData.cFileName[0] = ' '; entry_info->FindData.cFileName[1] = 0; } return TRUE; } /* * ls -l listing: * * drwxr-xr-x 2 montulli eng 512 Nov 8 23:23 CVS * -rw-r--r-- 1 montulli eng 2244 Nov 8 23:23 Imakefile * -rw-r--r-- 1 montulli eng 14615 Nov 9 17:03 Makefile * * ls -s listing: * * 69792668804186112 drwxrw-rw- 1 root root 0 Nov 15 14:01 . * 69792668804186112 drwxrw-rw- 1 root root 0 Nov 15 14:01 .. * 69792668804186113 dr-x-w---- 1 root root 512 Dec 1 02:16 Archives * * Full dates: * * -rw-r--r-- 1 panfilov users 139264 2005-06-20 14:22 AddTransToStacks.doc * -rw------- 1 panfilov users 535 2005-07-08 19:21 .bash_history * -rw-r--r-- 1 panfilov users 703 2004-10-14 14:14 .bash_profile * -rw-r--r-- 1 panfilov users 1290 2004-10-14 14:14 .bashrc */ BOOL WINAPI idPRParceUnix(const FTPServerInfo* Server, FTPFileInfo* p, char *entry, int entry_len) { NET_FileEntryInfo entry_info; BOOL remove_size = FALSE; char first; int off = 0; CHECK((!is_unix_start(entry, entry_len,&off)), FALSE) entry += off; entry_len -= off; first = NET_TO_UPPER(*entry); StrCpy(entry_info.UnixMode, entry, ARRAYSIZE(entry_info.UnixMode)); entry += 10; entry_len-=10; //Skip ACL if(*entry == '+') { entry++; entry_len--; } //D Dir if(first == 'D') { /* it's a directory */ entry_info.FileType = NET_DIRECTORY; remove_size = TRUE; /* size is not useful */ } else //C Char-device //B Block-device if(first == 'C' || first == 'B') { SET_FLAG(entry_info.FindData.dwFileAttributes, FILE_ATTRIBUTE_SYSTEM); } else //N ? //S Socket //P Pipe if(first == 'N' || first == 'S' || first == 'P') { SET_FLAG(entry_info.FindData.dwFileAttributes, FILE_ATTRIBUTE_HIDDEN); } else //L Link if(first == 'L') { /* it's a symbolic link, does the user care about * knowing if it is symbolic? I think so since * it might be a directory */ entry_info.FileType = NET_SYM_LINK; remove_size = TRUE; /* size is not useful */ int i; /* strip off " -> pathname" */ for(i = entry_len - 1; (i > 3) && (!NET_IS_SPACE(entry[i]) || (entry[i-1] != '>') || (entry[i-2] != '-') || (entry[i-3] != ' ')); i--) ; /* null body */ if(i > 3) { entry[i-3] = '\0'; StrCpy(entry_info.Link, entry + i + 1, ARRAYSIZE(entry_info.Link)); i = static_cast<int>(strlen(entry_info.Link)); if(i) { i--; if(entry_info.Link[i] == '/') entry_info.FileType = NET_SYM_LINK_TO_DIR; else ; } } } /* link */ if(!net_parse_ls_line(entry, &entry_info, TRUE) && !net_parse_ls_line(entry, &entry_info, FALSE)) return FALSE; if(remove_size) entry_info.size = 0; return ConvertEntry(&entry_info,p); }
332dbe0d81e2e3060e446fbfe409869551f1d64a
f5f97b069e9506f39c4a40d09056555fe8179b6f
/MiniTest_01/Game/Game/Lib/Object3D.cpp
62be16c3405338423df6bfdac309013d1e65a957
[]
no_license
nezumimusume/GamePG_2017
16434f7f6fc35d7f312da09bcdf70274b41c5570
7674c648f94343782e6beb3bc617a12becc8223e
refs/heads/master
2023-07-20T15:57:25.695194
2017-07-10T15:04:28
2017-07-10T15:04:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
cpp
Object3D.cpp
/*! *@brief Actor */ #include "stdafx.h" #include "Lib/Object3D.h" CLight Object3D::defaultLight; void Object3D::Init(const char* filePath, const CCamera& camera) { defaultLight.SetDiffuseLightDirection(0, CVector3(0.707f, 0.0f, -0.707f)); defaultLight.SetDiffuseLightDirection(1, CVector3(-0.707f, 0.0f, -0.707f)); defaultLight.SetDiffuseLightDirection(2, CVector3(0.0f, 0.707f, 0.707f)); defaultLight.SetDiffuseLightDirection(3, CVector3(0.0f, -0.707f, 0.0f)); defaultLight.SetDiffuseLightColor(0, CVector4(2.0f, 2.0f, 2.0f, 10.0f)); defaultLight.SetDiffuseLightColor(1, CVector4(0.8f, 0.8f, 0.8f, 1.0f)); defaultLight.SetDiffuseLightColor(2, CVector4(0.8f, 0.8f, 0.8f, 1.0f)); defaultLight.SetDiffuseLightColor(3, CVector4(0.8f, 0.8f, 0.8f, 1.0f)); defaultLight.SetLimLightColor(CVector4(2.0f, 2.0f, 2.0f, 1.0f)); defaultLight.SetLimLightDirection(CVector3(0.0f, 0.0f, -1.0f)); skinModelData.LoadModelData(filePath, &animation); skinModel.Init(skinModelData.GetBody()); skinModel.SetLight(&defaultLight); skinModel.SetShadowCasterFlag(true); skinModel.SetShadowReceiverFlag(true); this->camera = &camera; } void Object3D::Update() { animation.Update(GameTime().GetFrameDeltaTime()); skinModel.Update(position, rotation, scale); } void Object3D::Render(CRenderContext& renderContext) { if (camera != nullptr) { skinModel.Draw(renderContext, camera->GetViewMatrix(), camera->GetProjectionMatrix()); } else { TK_LOG("warning camera is null!!!"); } }
0679920dff0fe357bad0a9aec0a335b18b74967b
5b9e02d6199b3be3a83cedad9eb4ad58f784274e
/_OSODT/alg_3/_old/alg31.cpp
e5226764aada02c67bdb45c409b57d8dcb52f208
[]
no_license
ZonDBeer/Bachelor_work
2a09cdf894a83f846484325bba7981c25d5d87b5
36226b68ad9496ad7c31d7c1c4ca1482ce4991bc
refs/heads/master
2020-03-19T02:56:08.576575
2018-06-01T07:35:50
2018-06-01T07:35:50
135,676,749
0
0
null
null
null
null
UTF-8
C++
false
false
8,093
cpp
alg31.cpp
//#include "stdafx.h" //#include <intrin.h> //#include <conio.h> #include <cstdio> #include <cstdlib> #include <malloc.h> #include <sys/time.h> #include <immintrin.h> #define MAX 10000000 // MAX t_data size using namespace std; double wtime() { struct timeval t; gettimeofday(&t, NULL); return (double)t.tv_sec + (double)t.tv_usec * 1E-6; } void mask_avr(double X, double* T, int NBIG) { double *xx = new double[2]; double *Tx = new double[2]; for (int i = 0; i < NBIG-1; i+=2) { __m128d a; __m128d x; Tx[0] = T[i]; Tx[1] = T[i + 1]; a = _mm_load_pd(Tx); xx[0] = X; xx[1] = X; x = _mm_load_pd(xx); __m128d cm = _mm_max_pd(a, x); _mm_store_pd(xx, cm); T[i] = xx[0]; T[i+1] = xx[1]; } delete[] xx; delete[] Tx; for (int i = 0; i < NBIG; i++) printf("%i - %f\n", i, T[i]); } // поиск с использованием интринсиков int LUF_AVX(double X, double* T, int NBIG) { int M = 33; int N = NBIG; int LUF = 0; if (N <= 0) return -1; do { int L = (N - 1) / (M - 1); if (L == 0) { int K = 0; // _mm_max_pd сравнивает только два элемента вектора double *tmpX = new double[2]; // два элемента равных Х double *tmpT = new double[2]; // два элемента из массива Т for (int i = LUF; i < NBIG-1; i+=2) { __m128d mT; // вектор элементов равных Х __m128d mX; // вектор элементов массива Т tmpT[0] = T[i]; tmpT[1] = T[i + 1]; mT = _mm_load_pd(tmpT); // загрузка выбранных элементов в вектор mT tmpX[0] = X; tmpX[1] = X; mX = _mm_load_pd(tmpX); // загрузка элементов равных Х в вектор mX // если Х больше элемента вектора mT, то под соответствующим индексом в весторе cm __m128d cm = _mm_max_pd(mT, mX); // будет записан Х, иначе будет записан соответствующий элемент вектора mT _mm_store_pd(tmpX, cm); // выгрузка в tmpX содержимого вектора cm // т.е. если Х остается максимальным значением на данном промежутке // инкрементируем К if (tmpX[0] == X) { K = K + 1; } if (tmpX[1] == X) { K = K + 1; } } delete[] tmpX; delete[] tmpT; LUF = LUF + K; return LUF; } int K = 0; // _mm_max_pd сравнивает только два элемента вектора double *tmpX = new double[2]; // два элемента равных Х double *tmpT = new double[2]; // два элемента из массива Т for (int i = LUF; i < N-1; i += L*2) { __m128d mT; // вектор элементов равных Х __m128d mX; // вектор элементов массива Т tmpT[0] = T[i]; tmpT[1] = T[i + L]; mT = _mm_load_pd(tmpT); // загрузка выбранных элементов в вектор mT tmpX[0] = X; tmpX[1] = X; mX = _mm_load_pd(tmpX); // загрузка элементов равных Х в вектор mX // если Х больше элемента вектора mT, то под соответствующим индексом в весторе cm __m128d cm = _mm_max_pd(mT, mX); // будет записан Х, иначе будет записан соответствующий элемент вектора mT _mm_store_pd(tmpX, cm); // выгрузка в tmpX содержимого вектора cm // т.е. если Х остается максимальным значением на данном промежутке // инкрементируем К if (tmpX[0] == X) { K = K + 1; } if (tmpX[1] == X) { K = K + 1; } } delete[] tmpX; delete[] tmpT; int J = 1 + (K - 1)*L; if (K == 0) return LUF; else LUF = LUF + J; if (K == M) N = N - J; else N = L - 1; } while (N > 1); return LUF; } // поиск элемента с делением интервала на М частей int LUF(double X, double T[], int NBIG) { int M = 33; int N = NBIG; int LUF = 0; if (N <= 0) return -1; do { int L = (N - 1)/(M - 1); if (L == 0) { int K = 0; for (int i = LUF; i < NBIG; i++) { if (T[i] <= X) { K = K + 1; } else break; } LUF = LUF + K; return LUF; } int K = 0; for (int i = LUF; i < N; i += L) { if (T[i] <= X) { K = K + 1; } else break; } int J = 1 + (K - 1)*L; if (K == 0) return LUF; else LUF = LUF + J; if (K == M) N = N - J; else N = L - 1; } while (N > 1); return LUF; } int main() { int x = 9999990; double *t_data; double t; t_data = (double*)malloc(MAX * sizeof(double)); //double *arr = new double[MAX]; // 600 for (int i = 0; i < MAX; i++) // 600 { t_data[i] = i; } t = wtime(); int z = LUF_AVX(x, t_data/*arr*/, MAX); printf("LUF_AVX - %d\n", z); printf("Data[x] = %f\n", t_data[z]); t = wtime() - t; printf("%.12f\n\n", t); t = wtime(); int z1 = LUF(x, t_data/*arr*/, MAX); printf("LUF - %d\n", z1); printf("Data[x] = %f\n", t_data[z1]); t = wtime() - t; printf("%.12f\n\n", t); //system("pause"); return 0; }
15348fef53b188311f934cc353ce1fc10e433d9e
048fafade61e500adcce2d4d153ad5e9bb845468
/day04/test.cpp
fb078c489d37a8eb26300e8778c67a435236cfa1
[]
no_license
ngulya/CPP
2a8e36fd9662c5a68e2e9440522d06d47aa7c499
936e4111a673e38e044541a52be03855a7744ecc
refs/heads/master
2021-08-24T06:40:21.797362
2017-12-08T13:00:00
2017-12-08T13:00:00
113,574,733
1
0
null
null
null
null
UTF-8
C++
false
false
1,417
cpp
test.cpp
// ************************************************************************** // // // // ::: :::::::: // // test.cpp :+: :+: :+: // // +:+ +:+ +:+ // // By: ngulya <marvin@42.fr> +#+ +:+ +#+ // // +#+#+#+#+#+ +#+ // // Created: 2017/11/04 14:22:57 by ngulya #+# #+# // // Updated: 2017/11/04 14:22:58 by ngulya ### ########.fr // // // // ************************************************************************** // #include <string> #include <iostream> using namespace std; class Good { public: virtual void sayHello(string const &target); }; class Bad : public Good { public: void sayHello(string const &target); }; void Good::sayHello(string const &target) { cout<<"Hello "<<target<<endl; } void Bad::sayHello(string const &target) { cout<<"Fuck off "<<target<<endl; } int main(int argc, char const *argv[]) { Bad * b = new Bad(); Good * g = new Bad(); b->sayHello("student"); g->sayHello("student"); return 0; }
10682b87617395a9387b5c450a25eadf04b752df
8583b5bfc594b994f51d24d012e92ae66bf2e5ea
/src/BabylonCpp/src/meshes/builders/mesh_builder_options.cpp
39f8fc68b5372d7b7d63fe5d40f5a29c4abe64c1
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
samdauwe/BabylonCpp
84b8e51b59f04a847681a97fa6fe0a5c554e9e1f
3dad13a666299cbcf2e2db5b24575c19743e1000
refs/heads/master
2022-01-09T02:49:55.057544
2022-01-02T19:27:12
2022-01-02T19:27:12
77,682,359
309
41
Apache-2.0
2020-11-06T12:16:17
2016-12-30T11:29:05
C++
UTF-8
C++
false
false
16,874
cpp
mesh_builder_options.cpp
#include <babylon/meshes/builders/mesh_builder_options.h> namespace BABYLON { //-------------------------------------------------------------------------------------------------- // Box mesh options //-------------------------------------------------------------------------------------------------- BoxOptions::BoxOptions() : size{std::nullopt} , width{std::nullopt} , height{std::nullopt} , depth{std::nullopt} , faceUV{{Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f)}} , faceColors{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , wrap{std::nullopt} , topBaseAt{std::nullopt} , bottomBaseAt{std::nullopt} , updatable{std::nullopt} { } void BoxOptions::setFaceColor(size_t faceIndex, const Color4& color) { if (!faceColors) { faceColors = {Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f)}; } faceColors.value()[faceIndex] = color; } BoxOptions::~BoxOptions() = default; //-------------------------------------------------------------------------------------------------- // Cylinder or cone mesh options //-------------------------------------------------------------------------------------------------- CylinderOptions::CylinderOptions() : height{std::nullopt} , diameterTop{std::nullopt} , diameterBottom{std::nullopt} , diameter{std::nullopt} , tessellation{std::nullopt} , subdivisions{std::nullopt} , arc{std::nullopt} , updatable{std::nullopt} , hasRings{std::nullopt} , enclose{std::nullopt} , cap{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} { } CylinderOptions::~CylinderOptions() = default; //-------------------------------------------------------------------------------------------------- // Dashed lines mesh options //-------------------------------------------------------------------------------------------------- DashedLinesOptions::DashedLinesOptions() : dashSize{std::nullopt} , gapSize{std::nullopt} , dashNb{std::nullopt} , updatable{std::nullopt} , useVertexAlpha{std::nullopt} , instance{nullptr} { } DashedLinesOptions::~DashedLinesOptions() = default; //-------------------------------------------------------------------------------------------------- // Decal mesh options //-------------------------------------------------------------------------------------------------- DecalOptions::DecalOptions() : position{std::nullopt}, normal{std::nullopt}, size{std::nullopt}, angle{std::nullopt} { } DecalOptions::~DecalOptions() = default; //-------------------------------------------------------------------------------------------------- // Disc mesh options //-------------------------------------------------------------------------------------------------- DiscOptions::DiscOptions() : radius{std::nullopt} , tessellation{std::nullopt} , arc{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} { } DiscOptions::~DiscOptions() = default; //-------------------------------------------------------------------------------------------------- // Extrude shape mesh options //-------------------------------------------------------------------------------------------------- ExtrudeShapeOptions::ExtrudeShapeOptions() : scale{std::nullopt} , rotation{std::nullopt} , cap{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , instance{nullptr} , invertUV{std::nullopt} { } ExtrudeShapeOptions::~ExtrudeShapeOptions() = default; //-------------------------------------------------------------------------------------------------- // Extrude shape custom mesh options //-------------------------------------------------------------------------------------------------- ExtrudeShapeCustomOptions::ExtrudeShapeCustomOptions() : scaleFunction{nullptr} , rotationFunction{nullptr} , ribbonCloseArray{std::nullopt} , ribbonClosePath{std::nullopt} , cap{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , invertUV{std::nullopt} { } ExtrudeShapeCustomOptions::~ExtrudeShapeCustomOptions() = default; //-------------------------------------------------------------------------------------------------- // Ground from height map mesh options //-------------------------------------------------------------------------------------------------- GroundFromHeightMapOptions::GroundFromHeightMapOptions() : width{std::nullopt} , height{std::nullopt} , subdivisions{std::nullopt} , minHeight{std::nullopt} , maxHeight{std::nullopt} , colorFilter{std::nullopt} , alphaFilter{std::nullopt} , updatable{std::nullopt} , bufferWidth{std::nullopt} , bufferHeight{std::nullopt} , onReady{nullptr} { } GroundFromHeightMapOptions::~GroundFromHeightMapOptions() = default; //-------------------------------------------------------------------------------------------------- // Ground mesh options //-------------------------------------------------------------------------------------------------- GroundOptions::GroundOptions() : width{std::nullopt} , height{std::nullopt} , subdivisions{std::nullopt} , subdivisionsX{std::nullopt} , subdivisionsY{std::nullopt} , updatable{std::nullopt} { } GroundOptions::~GroundOptions() = default; //-------------------------------------------------------------------------------------------------- // Hemisphere mesh options //-------------------------------------------------------------------------------------------------- HemisphereOptions::HemisphereOptions() : segments{std::nullopt}, diameter{std::nullopt}, sideOrientation{std::nullopt} { } HemisphereOptions::~HemisphereOptions() = default; //-------------------------------------------------------------------------------------------------- // Icosphere mesh options //-------------------------------------------------------------------------------------------------- IcoSphereOptions::IcoSphereOptions() : radius{std::nullopt} , radiusX{std::nullopt} , radiusY{std::nullopt} , radiusZ{std::nullopt} , flat{std::nullopt} , subdivisions{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , updatable{std::nullopt} { } IcoSphereOptions::~IcoSphereOptions() = default; //-------------------------------------------------------------------------------------------------- // Capsule mesh options //-------------------------------------------------------------------------------------------------- ICreateCapsuleOptions::ICreateCapsuleOptions() : orientation{std::nullopt} , subdivisions{std::nullopt} , tessellation{std::nullopt} , height{std::nullopt} , radius{std::nullopt} , capSubdivisions{std::nullopt} , radiusTop{std::nullopt} , radiusBottom{std::nullopt} , topCapSubdivisions{std::nullopt} , bottomCapSubdivisions{std::nullopt} { } ICreateCapsuleOptions::~ICreateCapsuleOptions() = default; //-------------------------------------------------------------------------------------------------- // Lathe mesh options //-------------------------------------------------------------------------------------------------- LatheOptions::LatheOptions() : radius{std::nullopt} , tessellation{std::nullopt} , clip{std::nullopt} , arc{std::nullopt} , closed{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , cap{std::nullopt} , invertUV{std::nullopt} { } LatheOptions::~LatheOptions() = default; //-------------------------------------------------------------------------------------------------- // Lines mesh options //-------------------------------------------------------------------------------------------------- LinesOptions::LinesOptions() : updatable{std::nullopt}, useVertexAlpha{std::nullopt}, instance{nullptr} { } LinesOptions::~LinesOptions() = default; //-------------------------------------------------------------------------------------------------- // Line system mesh options //-------------------------------------------------------------------------------------------------- LineSystemOptions::LineSystemOptions() : updatable{std::nullopt}, useVertexAlpha{std::nullopt}, instance{nullptr} { } LineSystemOptions::LineSystemOptions(LinesOptions& linesOptions) : updatable{linesOptions.updatable} , useVertexAlpha{linesOptions.useVertexAlpha} , instance{linesOptions.instance} { if (!linesOptions.points.empty()) { lines.emplace_back(linesOptions.points); } if (!linesOptions.colors.empty()) { colors.emplace_back(linesOptions.colors); } } LineSystemOptions::~LineSystemOptions() = default; //-------------------------------------------------------------------------------------------------- // Plane mesh options //-------------------------------------------------------------------------------------------------- PlaneOptions::PlaneOptions() : size{std::nullopt} , width{std::nullopt} , height{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , updatable{std::nullopt} , sourcePlane{nullptr} { } PlaneOptions::~PlaneOptions() = default; //-------------------------------------------------------------------------------------------------- // Polyhedron mesh options //-------------------------------------------------------------------------------------------------- PolyhedronOptions::PolyhedronOptions() : type{std::nullopt} , size{std::nullopt} , sizeX{std::nullopt} , sizeY{std::nullopt} , sizeZ{std::nullopt} , custom{std::nullopt} , flat{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} { } PolyhedronOptions::~PolyhedronOptions() = default; //-------------------------------------------------------------------------------------------------- // Polygon mesh options //-------------------------------------------------------------------------------------------------- PolygonOptions::PolygonOptions() : depth{std::nullopt} , smoothingThreshold{std::nullopt} , faceUV{{ Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), }} , faceColors{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{Vector4(0.f, 0.f, 1.f, 1.f)} , backUVs{Vector4(0.f, 0.f, 1.f, 1.f)} , wrap{std::nullopt} { } PolygonOptions::~PolygonOptions() = default; //-------------------------------------------------------------------------------------------------- // Ribbon mesh options //-------------------------------------------------------------------------------------------------- RibbonOptions::RibbonOptions() : closeArray{std::nullopt} , closePath{std::nullopt} , offset{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , instance{nullptr} , invertUV{std::nullopt} { } RibbonOptions::~RibbonOptions() = default; //-------------------------------------------------------------------------------------------------- // Sphere mesh options //-------------------------------------------------------------------------------------------------- SphereOptions::SphereOptions() : segments{std::nullopt} , diameter{std::nullopt} , diameterX{std::nullopt} , diameterY{std::nullopt} , diameterZ{std::nullopt} , arc{std::nullopt} , slice{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , dedupTopBottomIndices{std::nullopt} , updatable{std::nullopt} { } SphereOptions::SphereOptions(const SphereOptions& other) = default; SphereOptions::SphereOptions(SphereOptions&& other) = default; SphereOptions& SphereOptions::operator=(const SphereOptions& other) = default; SphereOptions& SphereOptions::operator=(SphereOptions&& other) = default; SphereOptions::~SphereOptions() = default; //-------------------------------------------------------------------------------------------------- // Tiled box mesh options //-------------------------------------------------------------------------------------------------- TiledBoxOptions::TiledBoxOptions() : pattern{std::nullopt} , size{std::nullopt} , width{std::nullopt} , height{std::nullopt} , depth{std::nullopt} , tileSize{std::nullopt} , tileWidth{std::nullopt} , tileHeight{std::nullopt} , alignHorizontal{std::nullopt} , alignVertical{std::nullopt} , faceUV{{Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f), Vector4(0.f, 0.f, 1.f, 1.f)}} , faceColors{{Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f), Color4(1.f, 1.f, 1.f, 1.f)}} , sideOrientation{std::nullopt} , updatable{std::nullopt} { } TiledBoxOptions::~TiledBoxOptions() = default; //-------------------------------------------------------------------------------------------------- // Tiled ground mesh options //-------------------------------------------------------------------------------------------------- TiledGroundOptions::TiledGroundOptions() : xmin{std::nullopt} , zmin{std::nullopt} , xmax{std::nullopt} , zmax{std::nullopt} , subdivisions{std::nullopt} , precision{std::nullopt} , updatable{std::nullopt} { } TiledGroundOptions::~TiledGroundOptions() = default; //-------------------------------------------------------------------------------------------------- // Tiled plane mesh options //-------------------------------------------------------------------------------------------------- TiledPlaneOptions::TiledPlaneOptions() : pattern{std::nullopt} , tileSize{std::nullopt} , tileWidth{std::nullopt} , tileHeight{std::nullopt} , size{std::nullopt} , width{std::nullopt} , height{std::nullopt} , alignHorizontal{std::nullopt} , alignVertical{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} { } TiledPlaneOptions::~TiledPlaneOptions() = default; //-------------------------------------------------------------------------------------------------- // Torus mesh options //-------------------------------------------------------------------------------------------------- TorusOptions::TorusOptions() : diameter{std::nullopt} , thickness{std::nullopt} , tessellation{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} { } TorusOptions::~TorusOptions() = default; //-------------------------------------------------------------------------------------------------- // TorusKnot mesh options //-------------------------------------------------------------------------------------------------- TorusKnotOptions::TorusKnotOptions() : radius{std::nullopt} , tube{std::nullopt} , radialSegments{std::nullopt} , tubularSegments{std::nullopt} , p{std::nullopt} , q{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} { } TorusKnotOptions::~TorusKnotOptions() = default; //-------------------------------------------------------------------------------------------------- // Tube mesh options //-------------------------------------------------------------------------------------------------- TubeOptions::TubeOptions() : radius{std::nullopt} , tessellation{std::nullopt} , radiusFunction{nullptr} , cap{std::nullopt} , arc{std::nullopt} , updatable{std::nullopt} , sideOrientation{std::nullopt} , frontUVs{std::nullopt} , backUVs{std::nullopt} , instance{nullptr} , invertUV{std::nullopt} { } TubeOptions::~TubeOptions() = default; } // end of namespace BABYLON
41321c5e45ed4df895380ab3d812cab0495d44e0
f3978512d2ee7ce7b68fb0bf227cf8f7a5845f7a
/FileTransferApp/main.cpp
c22ba47c90fd21fd203c606a50ef15694be3c049
[]
no_license
Feoggou/filetransfer
d4bc37f489b4d1f8959a4c654142055dcbfe7591
ae641e5dd94b071a8c5c84fa5f795aee04840163
refs/heads/master
2020-06-02T04:39:44.974383
2013-08-04T14:41:25
2013-08-04T14:41:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,192
cpp
main.cpp
#include <math.h> #include <exception> #include "General.h" #include "Application.h" #include "MainDlg.h" #include "resource.h" #include "Recv.h" #include "Send.h" #include "String.h" //the variable that specifies if the connection and all that goes with it should end or not BOOL bOrderEnd = false; //this specifies how the program is currently connected (as a server, as a client, or not connected) Conn Connected = Conn::NotConnected; //this specifies the status of the transfer: if file(s) are being sent, are being retrieved or both DWORD dwDataTransfer = 0; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); UNREFERENCED_PARAMETER(nCmdShow); MessageBox(0, L"The app is during refactoring, and is not functional yet. If you want something, check out the first commit(s)!", L"Hard luck!", 0); try { Application app(hInstance); app.ShowMainDialog(); } catch (std::exception& e) { //TODO MessageBoxA(0, e.what(), "Fatal error!", MB_ICONERROR); } return 0; }
cf6b2ac3fd3d25d5c71bef14014a4c502ef2f621
3c325be3820097a67c08d7048ca3552db71e446c
/codeforces/1280A.cpp
7489720773084252e8694fbd80ced28ce9a0e353
[]
no_license
M45UDrana/DS-Algo-Problem-Solving
2dc2ba53f162675ddc6b549f0c84b702f738a485
5548d514f9ffff7aa618b29fcb8440a8b85afb8b
refs/heads/main
2023-07-17T06:14:51.062413
2021-09-01T18:19:14
2021-09-01T18:19:14
375,086,950
0
0
null
null
null
null
UTF-8
C++
false
false
523
cpp
1280A.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll inf = 1e9+7; int main() { int t; cin >> t; while(t--) { ll n; cin >> n; string s; cin >> s; ll m = s.size(); for(int i = 0; s.size() < n; i++) { int x = s[i]-'0', md = s.size(); while(x > 1 and s.size() < n) { for(int j = i+1; j < md and s.size() < n; j++) s += s[j]; x--; } } for(int i = 0; i < n; i++) m = ((m-1) * ll(s[i]-'0') ) % inf; cout << (m+n)%inf << endl; } return 0; }
7600b1a72c3dcab76cc6e8f9cbf1f026eb3373f6
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/base/gmock_unittest.cc
649054de9b8ce2794cf6e2267dc454b30bd7fd33
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
3,928
cc
gmock_unittest.cc
// Copyright 2009 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This test is a simple sanity check to make sure gmock is able to build/link // correctly. It just instantiates a mock object and runs through a couple of // the basic mock features. #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" // Gmock matchers and actions that we use below. using testing::AnyOf; using testing::Eq; using testing::Return; using testing::SetArgPointee; using testing::WithArg; using testing::_; namespace { // Simple class that we can mock out the behavior for. Everything is virtual // for easy mocking. class SampleClass { public: SampleClass() = default; virtual ~SampleClass() = default; virtual int ReturnSomething() { return -1; } virtual void ReturnNothingConstly() const { } virtual void OutputParam(int* a) { } virtual int ReturnSecond(int a, int b) { return b; } }; // Declare a mock for the class. class MockSampleClass : public SampleClass { public: MOCK_METHOD(int, ReturnSomething, ()); MOCK_METHOD(void, ReturnNothingConstly, (), (const)); MOCK_METHOD(void, OutputParam, (int* a)); MOCK_METHOD(int, ReturnSecond, (int a, int b)); }; // Create a couple of custom actions. Custom actions can be used for adding // more complex behavior into your mock...though if you start needing these, ask // if you're asking your mock to do too much. ACTION(ReturnVal) { // Return the first argument received. return arg0; } ACTION(ReturnSecond) { // Returns the second argument. This basically implemetns ReturnSecond. return arg1; } TEST(GmockTest, SimpleMatchAndActions) { // Basic test of some simple gmock matchers, actions, and cardinality // expectations. MockSampleClass mock; EXPECT_CALL(mock, ReturnSomething()) .WillOnce(Return(1)) .WillOnce(Return(2)) .WillOnce(Return(3)); EXPECT_EQ(1, mock.ReturnSomething()); EXPECT_EQ(2, mock.ReturnSomething()); EXPECT_EQ(3, mock.ReturnSomething()); EXPECT_CALL(mock, ReturnNothingConstly()).Times(2); mock.ReturnNothingConstly(); mock.ReturnNothingConstly(); } TEST(GmockTest, AssignArgument) { // Capture an argument for examination. MockSampleClass mock; EXPECT_CALL(mock, OutputParam(_)).WillRepeatedly(SetArgPointee<0>(5)); int arg = 0; mock.OutputParam(&arg); EXPECT_EQ(5, arg); } TEST(GmockTest, SideEffects) { // Capture an argument for examination. MockSampleClass mock; EXPECT_CALL(mock, OutputParam(_)).WillRepeatedly(SetArgPointee<0>(5)); int arg = 0; mock.OutputParam(&arg); EXPECT_EQ(5, arg); } TEST(GmockTest, CustomAction_ReturnSecond) { // Test a mock of the ReturnSecond behavior using an action that provides an // alternate implementation of the function. Danger here though, this is // starting to add too much behavior of the mock, which means the mock // implementation might start to have bugs itself. MockSampleClass mock; EXPECT_CALL(mock, ReturnSecond(_, AnyOf(Eq(4), Eq(5)))) .WillRepeatedly(ReturnSecond()); EXPECT_EQ(4, mock.ReturnSecond(-1, 4)); EXPECT_EQ(5, mock.ReturnSecond(0, 5)); EXPECT_EQ(4, mock.ReturnSecond(0xdeadbeef, 4)); EXPECT_EQ(4, mock.ReturnSecond(112358, 4)); EXPECT_EQ(5, mock.ReturnSecond(1337, 5)); } TEST(GmockTest, CustomAction_ReturnVal) { // Alternate implemention of ReturnSecond using a more general custom action, // and a WithArg adapter to bridge the interfaces. MockSampleClass mock; EXPECT_CALL(mock, ReturnSecond(_, AnyOf(Eq(4), Eq(5)))) .WillRepeatedly(WithArg<1>(ReturnVal())); EXPECT_EQ(4, mock.ReturnSecond(-1, 4)); EXPECT_EQ(5, mock.ReturnSecond(0, 5)); EXPECT_EQ(4, mock.ReturnSecond(0xdeadbeef, 4)); EXPECT_EQ(4, mock.ReturnSecond(112358, 4)); EXPECT_EQ(5, mock.ReturnSecond(1337, 5)); } } // namespace
963e4db5cf0a37d82c4807bfc8063119b5e06aba
cae9161d77926313e0062333dd1e76784b112765
/game/packet/requestprivatestorequit.cpp
bacead049b2dda7c382c1745fbdfa03f9b15a0f9
[]
no_license
yury-dymov/legacy_l2tradebot
9cbd0f94da8fc3ed7239715c5b349e0ee6689277
914671cdd31a884020a531ec86915d4a09de7523
refs/heads/master
2021-01-10T01:11:08.096960
2016-08-12T17:23:11
2016-08-12T17:23:11
55,140,565
0
0
null
null
null
null
UTF-8
C++
false
false
146
cpp
requestprivatestorequit.cpp
#include "gamepacket.h" string GamePacket::requestPrivateStoreQuit () { string ret; ret += E_C_GAME_REQUEST_PRIVATE_STORE_QUIT; return ret; }
bb131a5914556ffe3ae4d6b969272b90d2ff3298
80947518e20f28660dc92580e1726573493b7d6c
/aoba/ir/node_inputs.h
6458992f586eba89ec8ecf6be264bef0612365ef
[]
no_license
blockspacer/aoba
6a3148f93d8b8cb9f9a87a44d12cd93e5285ffce
675d1e534c765bf77e1b8df81510b3431d1156d0
refs/heads/master
2020-09-14T20:40:09.023275
2017-11-12T15:27:23
2017-11-12T15:27:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,264
h
node_inputs.h
// Copyright (c) 2016 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef AOBA_IR_NODE_INPUTS_H_ #define AOBA_IR_NODE_INPUTS_H_ #include <vector> #include "base/macros.h" namespace aoba { class Zone; namespace ir { class Node; // // NodeInputs represens input nodes of |Node| with use chain. // class NodeInputs final { public: // // UseEdge // // The instances of this class are allocated into |Zone|. // struct UseEdge final { const Node* from_; const Node* to_; UseEdge* next_; UseEdge* previous_; }; NodeInputs(); ~NodeInputs(); // Input node getter for Node::Inputs::Iterator const Node& input_at(const Node& owner, size_t index) const; size_t number_of_inputs(const Node& owner) const; void Init(Zone* zone, const Node& owner, const std::vector<const Node*>& nodes); void Init(const Node& owner, const std::vector<const Node*>& nodes); // Initialize |use_edge| and link to |to|'s use edge list. void InitAt(size_t index, const Node& from, const Node& to); private: // // UseEdgeList // struct UseEdgeList final { size_t capacity_; size_t size_; UseEdge* elements_; }; static_assert(sizeof(UseEdgeList) <= sizeof(UseEdge), "UseEdgeList must be smaller than or equal to UseEdge"); // Initialize use edge specified by |use_edge| with |to|. static void InitUseEdge(UseEdge* use_edge, const Node& from, const Node& to); // Initialize use edge starts from |use_edge| with |input_nodes|. static void InitUseEdges(UseEdge* use_edge, const Node& from, const std::vector<const Node*>& input_nodes); const UseEdge* UseEdgeAt(const Node& owner, size_t index) const; UseEdge* UseEdgeAt(const Node& owner, size_t index); // A list of used nodes of this node. UseEdge* first_use_edge_ = nullptr; // |inputs_| must be the last member field. We allocate |UseEdge| after // |Node|. union { UseEdge inline_[1]; UseEdgeList outline_; } edges_; DISALLOW_COPY_AND_ASSIGN(NodeInputs); }; } // namespace ir } // namespace aoba #endif // AOBA_IR_NODE_INPUTS_H_
ce2c1a9d4966856845b5c7345a6ac65bdf67ab71
1c2371f6f0d9a3a6758fe9a2262dcb29d5548505
/src/banking/InvalidPIN.cpp
720080f540699420b49a68cf8130eee2e9de0637
[ "MIT" ]
permissive
hxbc01/project-cpp-qt-atm
c820f83ad577621463344a80ed8054341a34a015
021a46517bd7a64df4e8f5507dd3261a7f6506bd
refs/heads/master
2022-04-22T15:55:14.112215
2020-04-26T21:56:57
2020-04-26T21:56:57
268,283,108
1
0
MIT
2020-05-31T13:12:33
2020-05-31T13:12:33
null
UTF-8
C++
false
false
221
cpp
InvalidPIN.cpp
#include <QDebug> #include "InvalidPIN.h" banking::InvalidPIN::InvalidPIN() : StatusFailure("Invalid PIN") { } banking::InvalidPIN::~InvalidPIN() { } bool banking::InvalidPIN::isInvalidPIN() { return true; }
bd1b2dff817765c3564b129f5b842546cea03213
6fafdbe916c2469c0b8c56a4da86ac819bd0da37
/code/bp-heterogeneoTW/ModeloHeuristica.cpp
e958db8aa16ea0c3d1680da6dd1c916a1c731927
[]
no_license
lulzzz/phd-cross-docking
ca84b7f749be778b27cd72b0a2f54e35b075969f
980e5abc9402cadeff5916c63bc8298df8aaf247
refs/heads/master
2021-05-09T15:08:44.878172
2017-02-17T17:36:47
2017-02-17T17:36:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,262
cpp
ModeloHeuristica.cpp
#include "ModeloHeuristica.h" ModeloHeuristica::~ModeloHeuristica(){ int maxVeiculos = lambdaInt.getSize(); objective.end(); constraints1.endElements(); constraints2.endElements(); constraints3.endElements(); constraints4.endElements(); constraints5.endElements(); constraints6.endElements(); for (int k = 0; k < maxVeiculos; ++k){ lambdaInt[k].endElements(); gammaInt[k].endElements(); tauInt[k].endElements(); } lambdaInt.end(); gammaInt.end(); tauInt.end(); cplex.end(); model.end(); } ModeloHeuristica::ModeloHeuristica(ModeloCplex& mCplex){ model = IloModel(mCplex.env); cplex = IloCplex(model); cplex.setOut(mCplex.env.getNullStream()); initVars(mCplex); setObjectiveFunction(mCplex); setConstraints1e2(mCplex); setConstraints3e4(mCplex); setConstraints5e6(mCplex); } void ModeloHeuristica::initVars(ModeloCplex& mCplex){ int maxV = mCplex.maxVeic; int numCommod = mCplex.nCommodities; lambdaInt = IloArray<IloIntVarArray>(mCplex.env, maxV); for (int i = 0; i < maxV; i++){ lambdaInt[i] = IloIntVarArray(mCplex.env, mCplex.qRotasForn[i], 0, 1); } gammaInt = IloArray<IloIntVarArray>(mCplex.env, maxV); for (int i = 0; i < maxV; i++){ gammaInt[i] = IloIntVarArray(mCplex.env, mCplex.qRotasCons[i], 0, 1); } tauInt = IloArray<IloIntVarArray>(mCplex.env, maxV); for (int i = 0; i < maxV; i++){ tauInt[i] = IloIntVarArray(mCplex.env, (numCommod+1), 0, 1); } } void ModeloHeuristica::setObjectiveFunction(ModeloCplex& mCplex){ int maxV = mCplex.maxVeic; int numCommod = mCplex.nCommodities; IloExpr expObj = IloExpr(mCplex.env); for (int k = 0; k < maxV; ++k){ for (int r = 0; r < mCplex.qRotasForn[k]; ++r){ expObj += (mCplex.ptrRotasForn[k][r]->getCusto() * lambdaInt[k][r]); } } for (int k = 0; k < maxV; ++k){ for (int r = 0; r < mCplex.qRotasCons[k]; ++r){ expObj += (mCplex.ptrRotasCons[k][r]->getCusto() * gammaInt[k][r]); } } for (int k = 0; k < maxV; ++k){ for (int i = 1; i <= numCommod; ++i){ expObj += (mCplex.custoTrocaCD * tauInt[k][i]); } } objective = IloObjective(mCplex.env, expObj); model.add(objective); } void ModeloHeuristica::setConstraints1e2(ModeloCplex& mCplex){ int maxV = mCplex.maxVeic; constraints1 = IloRangeArray(mCplex.env, maxV); constraints2 = IloRangeArray(mCplex.env, maxV); for (int k = 0; k < maxV; ++k){ IloExpr exp1 = IloExpr(mCplex.env); for (int r = 0; r < mCplex.qRotasForn[k]; ++r){ exp1 += lambdaInt[k][r]; } constraints1[k] = (exp1 == 1); model.add(constraints1[k]); exp1.end(); IloExpr exp2 = IloExpr(mCplex.env); for (int r = 0; r < mCplex.qRotasCons[k]; ++r){ exp2 += gammaInt[k][r]; } constraints2[k] = (exp2 == 1); model.add(constraints2[k]); exp2.end(); } } void ModeloHeuristica::setConstraints3e4(ModeloCplex& mCplex){ int maxV = mCplex.maxVeic; int numCommod = mCplex.nCommodities; vector<short int*>* matrizA_qr = mCplex.A_qr; vector<short int*>* matrizB_qr = mCplex.B_qr; constraints3 = IloRangeArray(mCplex.env, numCommod); constraints4 = IloRangeArray(mCplex.env, numCommod); for (int i = 1; i <= numCommod; ++i){ IloExpr exp3 = IloExpr(mCplex.env); for (int k = 0; k < maxV; ++k){ for (int r = 0; r < mCplex.qRotasForn[k]; ++r){ if(matrizA_qr[k][r][i] > 0){ exp3 += lambdaInt[k][r]; } } } constraints3[i-1] = (exp3 == 1); model.add(constraints3[i-1]); IloExpr exp4 = IloExpr(mCplex.env); for (int k = 0; k < maxV; ++k){ for (int r = 0; r < mCplex.qRotasCons[k]; ++r){ if (matrizB_qr[k][r][i] > 0){ exp4 += gammaInt[k][r]; } } } constraints4[i-1] = (exp4 == 1); model.add(constraints4[i-1]); } } void ModeloHeuristica::setConstraints5e6(ModeloCplex& mCplex){ int maxV = mCplex.maxVeic; int numCommod = mCplex.nCommodities; constraints5 = IloRangeArray(mCplex.env, maxV*numCommod); constraints6 = IloRangeArray(mCplex.env, maxV*numCommod); vector<short int*>* matrizA_qr = mCplex.A_qr; vector<short int*>* matrizB_qr = mCplex.B_qr; int contadorRestr = 0; for (int k = 0; k < maxV; ++k){ for (int i = 1; i <= numCommod; ++i){ constraints5[contadorRestr] = IloRange(mCplex.env, 0, +IloInfinity); constraints6[contadorRestr] = IloRange(mCplex.env, 0, +IloInfinity); IloExpr exp5 = IloExpr(mCplex.env); IloExpr exp6 = IloExpr(mCplex.env); //FORNECEDORES for (int r = 0; r < mCplex.qRotasForn[k]; ++r){ if (matrizA_qr[k][r][i] > 0){ exp5 += lambdaInt[k][r]; exp6 -= lambdaInt[k][r]; } } //CONSUMIDORES for (int r = 0; r < mCplex.qRotasCons[k]; ++r){ if (matrizB_qr[k][r][i] > 0){ exp5 -= gammaInt[k][r]; exp6 += gammaInt[k][r]; } } exp5 += tauInt[k][i]; exp6 += tauInt[k][i]; constraints5[contadorRestr] = (exp5 >= 0); constraints6[contadorRestr] = (exp6 >= 0); model.add(constraints5[contadorRestr]); model.add(constraints6[contadorRestr]); ++contadorRestr; } } } float ModeloHeuristica::optimize(){ int limite = 10 * lambdaInt.getSize();; // 10x o numero de veiculos cplex.setParam(IloCplex::TiLim, limite); cplex.solve(); if ((cplex.getStatus() == IloAlgorithm::Feasible) || (cplex.getStatus() == IloAlgorithm::Optimal)){ return cplex.getObjValue(); }else{ return MAIS_INFINITO; } }
58de82cbbea93a36a813b3a4de21960ba17a688b
550c97fa465ace75d1252731e36a66ea97aa12b1
/src/main.cpp
df4d484bdbbc1d1fd30decefc1d80c16c19d9ef9
[]
no_license
peterborkuti/thermocam
1bd1bed7551b948526169c4d9cc6cb37fec9aa64
624fc14d83cc3cffd7bfd147670138cf6bb9e037
refs/heads/master
2021-01-22T03:54:57.777599
2014-10-19T19:24:59
2014-10-19T19:24:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,031
cpp
main.cpp
/* * main.cpp * * Created on: Sep 9, 2014 * Author: peter */ #include <iostream> #include "numberscanner/numberscanner.hpp" #include "distancemeter/distancemeter.hpp" #include "imagereader/imagereader.hpp" #include "cli/cli.hpp" #include <cstdio> /* int omain() { std::cout << "START" << std::endl; ns::NumberScanner ns(0); dm::DistanceMeter dm("/dev/ttyUSB0"); ir::ImageReader ir(1); for(int i = 6; i < 98; i++) { dm.measure(3); char buf[100]; std::sprintf(buf, "%08d.png", i); std::string fileName(buf); ns::ScannedValue sv = ns.scanFile(fileName); if ((sv.error == 0) && sv.scan && dm.read() && ir.readCamera()) { int distance = dm.getRawDistance(); int j = 1; while ((distance == 0) && (j < 10)) { dm.measure(0); distance = dm.getRawDistance(); j++; } if (j >= 10) { std::cerr << "Distancemeter got 0, I gave it up" << std::endl; continue; } sprintf(buf, "tcam_%03.1f_%d.png", sv.value, distance); std::string fn(buf); ir.saveImage(fn); } } std::cout << "END" << std::endl; } */ int readDistance(dm::DistanceMeter &dm, int times = 0, bool measure_OK = false) { if (dm::ERROR_TEST_MODE == dm.error) { return -1; } bool success = dm.read(); std::cout << "dm.read - success:" << success << std::endl; int distance = -1; if (success) { distance = dm.getRawDistance(); std::cout << "0 distance " << distance << std::endl; int j = 1; while ((distance == 0) && (j < 10)) { success = false; bool measure_OK = dm.measure(0); std::cout << j << " - dm.measure_OK" << measure_OK << std::endl; if (measure_OK) success = dm.read(); std::cout << j << " - dm.read success: " << success << std::endl; if (measure_OK && success) distance = dm.getRawDistance(); std::cout << j << " - distance:" << distance << std::endl; j++; } if (j >= 10) { std::cerr << "Distancemeter got 0, I gave it up" << std::endl; return -1; } } return distance; } int PREV_STATE = -1; int STATE = -1; int STATE_COUNTER = 0; std::string stateStrings[] = {"start", "hold", "scan", "error"}; bool do_dm = false, do_ns = false, do_ir = false; void initState(int state) { if (state != STATE) { STATE_COUNTER = 1; PREV_STATE = STATE; std::cout << "new state:" << stateStrings[state] << std::endl; } else { STATE_COUNTER++; std::cout << "in state:" << stateStrings[state] << ", " << STATE_COUNTER <<std::endl; } } void stateStart() { initState(0); } void stateHold() { initState(1); } void stateScan() { initState(2); } void stateError() { initState(3); } void showPictures(cv::Mat const dspImg, cv::Mat camImg) { if (do_ns) cv::imshow("display", dspImg); if (do_ir) cv::imshow("camera", camImg); cv::waitKey(3); } int main(int argc, const char** argv) { CLI cli; int ir_cam = -10, ns_cam = -10, fps = 15; std::string dm_dev(""); if (!cli.parse(argc, argv, dm_dev, ir_cam, ns_cam, fps)) { return 0; } do_dm = (dm_dev.compare("") != 0); do_ir = (ir_cam >= 0); do_ns = (ns_cam >= 0); printf("ns_cam: %d, ir_cam:%d\n", ns_cam, ir_cam); ir::ImageReader ir(ir_cam); ir::ImageReader ir_ns(ns_cam); std::cout << "ir_cam" << ir_cam << std::endl; ns::NumberScanner ns(ir_ns); dm::DistanceMeter dm(dm_dev); cv::namedWindow("camera", cv::WINDOW_AUTOSIZE); cv::namedWindow("display", cv::WINDOW_AUTOSIZE); ns::ScannedValue sv; bool measure_OK = false; double distance = -1; double storedDistance = -1; std::cout << "dm init - error:" << dm.error << std::endl; if (do_dm) measure_OK = dm.measure(0); while (true) { if (do_ns) sv = ns.scanCamera(); if (do_ir) ir.readCamera(); if (do_dm && measure_OK) { bool success = dm.read(); if (success) { distance = dm.getDistanceInMMeter(); } else { std::cout << "dm readDistance - error:" << dm.error << std::endl; } } if (do_dm) measure_OK = dm.measure(3); printf("Distance: %03.1f mm, Temperature: %03.1f, Scan:%d, Hold:%d\n", distance, sv.value, sv.scan, sv.hold); // Thermometer states // name | scan | hold | state //----------+------+------+-------- // start | 0 | 0 | Showing the last measured value and laser is on. // camera can gets the word in the time of scanning. // SHOW PICTURE // hold | 0 | 1 | Laser is off // STORE PICTURE right after state (1,0) with stored distance // SHOW PICTURE // scan | 1 | 0 | Measuring. Showed temperature is false. Laser is ON // STORE DISTANCE // STORE PICTURE with laser // error | 1 | 1 | Impossible if ((sv.scan == 0) && (sv.hold == 0)) { stateStart(); } else if ((sv.scan == 0) && (sv.hold == 1)){ stateHold(); } else if ((sv.scan == 1) && (sv.hold == 0)){ stateScan(); } else { stateError(); } showPictures(ns.getBinaryImage(), ir.getImage()); } std::cout << "END" << std::endl; }
5b77ddee61f35fb296bbfaf336595a56393654e1
62efb9ba2ffdfcb0aacca9d7bf1f347a9ee535e1
/NNGameFramework/Main.cpp
338615ee0f54592cf9128fee5a3b34dc5c844616
[]
no_license
agebreak/Sample_2DFighter
97c3caa60bd4a4962624f0c3c07fa236d56ba575
da13929920d21241f09bdc96cd53fcb9f7285cf7
refs/heads/master
2021-01-10T20:55:36.485414
2013-11-07T07:30:24
2013-11-07T07:30:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
Main.cpp
#include "NNApplication.h" #include "SpriteExampleScene.h" #include "C2DFighterScene.h" int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nShowCmd ) { #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); //_CrtSetBreakAlloc( ); #endif NNApplication* Application = NNApplication::GetInstance(); Application->Init( L"2D Fighter", 1280, 720, D2D ); // NNSceneDirector::GetInstance()->ChangeScene( /* Insert Scene! */ ); NNSceneDirector::GetInstance()->ChangeScene( new C2DFighterScene() ); Application->Run(); NNApplication::GetInstance()->Release(); return 0; }
ac2ced379dc5b17a137b313948cd041a6fb129e9
7e84926686c4055a570855e4b299b0eb254c4a52
/Rain_fence.cpp
a624082f25c6ef2ad53a3ad61d6bea6a49780704
[]
no_license
Minhvn98/ATBM
c0f66c806915eba18206944df7ee43c034558f21
494c3934e2c81ed58e32aa26f5713839a31d998b
refs/heads/master
2020-06-23T11:28:50.950998
2020-01-14T08:44:16
2020-01-14T08:44:16
198,609,532
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
Rain_fence.cpp
#include<iostream> using namespace std; main(){ string s, s1, s2; cout << "Nhap chuoi : "; getline(cin, s); //Ma hoa for(int i = 0; i < s.size(); i++){ if(i % 2 == 0) s1 += s[i]; else s2 += s[i]; } s = s1 + s2; cout << "Chuoi sau ma hoa : " << s <<endl; // Giai ma string P; if(s.size() % 2 == 0){ for(int i = 0; i < s.size()/2; i++) P = P + s[i] + s[i + s.size()/2]; } else{ for(int i = 0; i < s.size()/2; i++) P = P + s[i] + s[i + s.size()/2 + 1]; P = P + s[s.size()/2]; } cout << "Chuoi sau khi giai ma : " << P; }
865230fcb3d1f27102f0bfa731a3d6e2cd653a46
e92af86f33f4bdd457578733074d3c7f6aa7c7fb
/source/GameCommon/SceneObject.proto.fflua.cc
c6433cab3d590cb7ca71afcadd9bc637dd5b8555
[]
no_license
crazysnail/XServer
aac7e0aaa9da29c74144241e1cc926b8c76d0514
da9f9ae3842e253dcacb2b83b25c5fa56927bdd3
refs/heads/master
2022-03-25T15:52:57.238609
2019-12-04T09:25:33
2019-12-04T09:25:33
224,835,205
0
0
null
null
null
null
UTF-8
C++
false
true
13,344
cc
SceneObject.proto.fflua.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: SceneObject.proto #include "SceneObject.pb.h" #include "SceneObject.proto.fflua.h" namespace Packet { bool SceneLayout_fflua_reg(lua_State* state) { //for decltype SceneLayout* message(nullptr); message; ff::fflua_register_t<SceneLayout, ctor()>(state, "SceneLayout", "google::protobuf::Message") // required int32 id = 1; .def(&SceneLayout::id, "id") .def(&SceneLayout::set_id, "set_id") // required int32 scene_id = 2; .def(&SceneLayout::scene_id, "scene_id") .def(&SceneLayout::set_scene_id, "set_scene_id") // required .Packet.Position position = 3; .def(&SceneLayout::position, "position") .def(&SceneLayout::mutable_position, "mutable_position") // required float angle = 4; .def(&SceneLayout::angle, "angle") .def(&SceneLayout::set_angle, "set_angle") // required int32 group_index = 5; .def(&SceneLayout::group_index, "group_index") .def(&SceneLayout::set_group_index, "set_group_index") .def(&SceneLayout::ByteSize, "ByteSize") .def(&SceneLayout::SetInitialized, "SetInitialized") ; return true; } bool NpcStaticConfig_fflua_reg(lua_State* state) { //for decltype NpcStaticConfig* message(nullptr); message; ff::fflua_register_t<NpcStaticConfig, ctor()>(state, "NpcStaticConfig", "google::protobuf::Message") // required int32 index = 1; .def(&NpcStaticConfig::index, "index") .def(&NpcStaticConfig::set_index, "set_index") // required int32 npc_id = 2; .def(&NpcStaticConfig::npc_id, "npc_id") .def(&NpcStaticConfig::set_npc_id, "set_npc_id") // required int32 pos_id = 3; .def(&NpcStaticConfig::pos_id, "pos_id") .def(&NpcStaticConfig::set_pos_id, "set_pos_id") // repeated string talk_option = 4; .def(&NpcStaticConfig::talk_option_size, "talk_option_size") .def<const std::string& (NpcStaticConfig::*)(int) const>(&NpcStaticConfig::talk_option, "talk_option") .def<void (NpcStaticConfig::*)(int, const std::string&)>(&NpcStaticConfig::set_talk_option, "set_talk_option") .def<void (NpcStaticConfig::*)(const std::string&)>(&NpcStaticConfig::add_talk_option, "add_talk_option") .def(&NpcStaticConfig::ByteSize, "ByteSize") .def(&NpcStaticConfig::SetInitialized, "SetInitialized") ; return true; } bool NpcDynamicConfig_fflua_reg(lua_State* state) { //for decltype NpcDynamicConfig* message(nullptr); message; ff::fflua_register_t<NpcDynamicConfig, ctor()>(state, "NpcDynamicConfig", "google::protobuf::Message") // required int32 index = 1; .def(&NpcDynamicConfig::index, "index") .def(&NpcDynamicConfig::set_index, "set_index") // required int32 group_id = 2; .def(&NpcDynamicConfig::group_id, "group_id") .def(&NpcDynamicConfig::set_group_id, "set_group_id") // required int32 npc_id = 3; .def(&NpcDynamicConfig::npc_id, "npc_id") .def(&NpcDynamicConfig::set_npc_id, "set_npc_id") // repeated int32 monster_group = 4; .def(&NpcDynamicConfig::monster_group_size, "monster_group_size") .def<decltype(message->monster_group(0)) (NpcDynamicConfig::*)(int) const>(&NpcDynamicConfig::monster_group, "monster_group") .def<void(NpcDynamicConfig::*)(int, const decltype(message->monster_group(0)))>(&NpcDynamicConfig::set_monster_group, "set_monster_group") .def(&NpcDynamicConfig::add_monster_group, "add_monster_group") // repeated string talk_option = 5; .def(&NpcDynamicConfig::talk_option_size, "talk_option_size") .def<const std::string& (NpcDynamicConfig::*)(int) const>(&NpcDynamicConfig::talk_option, "talk_option") .def<void (NpcDynamicConfig::*)(int, const std::string&)>(&NpcDynamicConfig::set_talk_option, "set_talk_option") .def<void (NpcDynamicConfig::*)(const std::string&)>(&NpcDynamicConfig::add_talk_option, "add_talk_option") // required string npc_tag = 6; .def(&NpcDynamicConfig::npc_tag, "npc_tag") .def<void (NpcDynamicConfig::*)(const std::string&)>(&NpcDynamicConfig::set_npc_tag, "set_npc_tag") // required int32 pos_id = 7; .def(&NpcDynamicConfig::pos_id, "pos_id") .def(&NpcDynamicConfig::set_pos_id, "set_pos_id") .def(&NpcDynamicConfig::ByteSize, "ByteSize") .def(&NpcDynamicConfig::SetInitialized, "SetInitialized") ; return true; } bool PositionGroupConfig_fflua_reg(lua_State* state) { //for decltype PositionGroupConfig* message(nullptr); message; ff::fflua_register_t<PositionGroupConfig, ctor()>(state, "PositionGroupConfig", "google::protobuf::Message") // required int32 group_id = 1; .def(&PositionGroupConfig::group_id, "group_id") .def(&PositionGroupConfig::set_group_id, "set_group_id") // required int32 pos_id = 2; .def(&PositionGroupConfig::pos_id, "pos_id") .def(&PositionGroupConfig::set_pos_id, "set_pos_id") .def(&PositionGroupConfig::ByteSize, "ByteSize") .def(&PositionGroupConfig::SetInitialized, "SetInitialized") ; return true; } bool NpcInfo_fflua_reg(lua_State* state) { //for decltype NpcInfo* message(nullptr); message; ff::fflua_register_t<NpcInfo, ctor()>(state, "NpcInfo", "google::protobuf::Message") // required int32 index = 1; .def(&NpcInfo::index, "index") .def(&NpcInfo::set_index, "set_index") // required int32 pos_id = 2; .def(&NpcInfo::pos_id, "pos_id") .def(&NpcInfo::set_pos_id, "set_pos_id") // required int32 series_id = 3; .def(&NpcInfo::series_id, "series_id") .def(&NpcInfo::set_series_id, "set_series_id") // required int32 lifetime = 4; .def(&NpcInfo::lifetime, "lifetime") .def(&NpcInfo::set_lifetime, "set_lifetime") .def(&NpcInfo::ByteSize, "ByteSize") .def(&NpcInfo::SetInitialized, "SetInitialized") ; return true; } bool PlayerList_fflua_reg(lua_State* state) { //for decltype PlayerList* message(nullptr); message; ff::fflua_register_t<PlayerList, ctor()>(state, "PlayerList", "google::protobuf::Message") // repeated .Packet.PlayerBasicInfo player_info = 1; .def(&PlayerList::player_info_size, "player_info_size") .def<decltype(message->player_info(0)) (PlayerList::*)(int) const>(&PlayerList::player_info, "player_info") .def<decltype(message->mutable_player_info(0)) (PlayerList::*)(int)>(&PlayerList::mutable_player_info, "mutable_player_info") .def(&PlayerList::add_player_info, "add_player_info") .def(&PlayerList::ByteSize, "ByteSize") .def(&PlayerList::SetInitialized, "SetInitialized") ; return true; } bool NpcList_fflua_reg(lua_State* state) { //for decltype NpcList* message(nullptr); message; ff::fflua_register_t<NpcList, ctor()>(state, "NpcList", "google::protobuf::Message") // repeated .Packet.NpcInfo npc_info = 1; .def(&NpcList::npc_info_size, "npc_info_size") .def<decltype(message->npc_info(0)) (NpcList::*)(int) const>(&NpcList::npc_info, "npc_info") .def<decltype(message->mutable_npc_info(0)) (NpcList::*)(int)>(&NpcList::mutable_npc_info, "mutable_npc_info") .def(&NpcList::add_npc_info, "add_npc_info") // required .Packet.NpcOption option = 2; .def(&NpcList::option, "option") .def(&NpcList::set_option, "set_option") .def(&NpcList::ByteSize, "ByteSize") .def(&NpcList::SetInitialized, "SetInitialized") ; return true; } bool PlayerNpc_fflua_reg(lua_State* state) { //for decltype PlayerNpc* message(nullptr); message; ff::fflua_register_t<PlayerNpc, ctor()>(state, "PlayerNpc", "google::protobuf::Message") // required .DB.TrialTarget target = 1; .def(&PlayerNpc::target, "target") .def(&PlayerNpc::mutable_target, "mutable_target") .def(&PlayerNpc::ByteSize, "ByteSize") .def(&PlayerNpc::SetInitialized, "SetInitialized") ; return true; } bool PlayerNpcList_fflua_reg(lua_State* state) { //for decltype PlayerNpcList* message(nullptr); message; ff::fflua_register_t<PlayerNpcList, ctor()>(state, "PlayerNpcList", "google::protobuf::Message") // repeated .Packet.PlayerNpc player_npc = 1; .def(&PlayerNpcList::player_npc_size, "player_npc_size") .def<decltype(message->player_npc(0)) (PlayerNpcList::*)(int) const>(&PlayerNpcList::player_npc, "player_npc") .def<decltype(message->mutable_player_npc(0)) (PlayerNpcList::*)(int)>(&PlayerNpcList::mutable_player_npc, "mutable_player_npc") .def(&PlayerNpcList::add_player_npc, "add_player_npc") // required .Packet.NpcOption option = 2; .def(&PlayerNpcList::option, "option") .def(&PlayerNpcList::set_option, "set_option") .def(&PlayerNpcList::ByteSize, "ByteSize") .def(&PlayerNpcList::SetInitialized, "SetInitialized") ; return true; } bool NpcSession_fflua_reg(lua_State* state) { //for decltype NpcSession* message(nullptr); message; ff::fflua_register_t<NpcSession, ctor()>(state, "NpcSession", "google::protobuf::Message") // required int32 index = 1; .def(&NpcSession::index, "index") .def(&NpcSession::set_index, "set_index") // optional int32 series_id = 2; .def(&NpcSession::series_id, "series_id") .def(&NpcSession::set_series_id, "set_series_id") .def(&NpcSession::has_series_id, "has_series_id") // optional int32 mission_id = 3; .def(&NpcSession::mission_id, "mission_id") .def(&NpcSession::set_mission_id, "set_mission_id") .def(&NpcSession::has_mission_id, "has_mission_id") // optional .Packet.MissionOption option = 4; .def(&NpcSession::option, "option") .def(&NpcSession::set_option, "set_option") .def(&NpcSession::has_option, "has_option") // optional int32 option_index = 5; .def(&NpcSession::option_index, "option_index") .def(&NpcSession::set_option_index, "set_option_index") .def(&NpcSession::has_option_index, "has_option_index") .def(&NpcSession::ByteSize, "ByteSize") .def(&NpcSession::SetInitialized, "SetInitialized") ; return true; } bool PlayerNpcSession_fflua_reg(lua_State* state) { //for decltype PlayerNpcSession* message(nullptr); message; ff::fflua_register_t<PlayerNpcSession, ctor()>(state, "PlayerNpcSession", "google::protobuf::Message") // required fixed64 target_guid = 1; .def(&PlayerNpcSession::target_guid, "target_guid") .def(&PlayerNpcSession::set_target_guid, "set_target_guid") // optional int32 option_index = 2; .def(&PlayerNpcSession::option_index, "option_index") .def(&PlayerNpcSession::set_option_index, "set_option_index") .def(&PlayerNpcSession::has_option_index, "has_option_index") .def(&PlayerNpcSession::ByteSize, "ByteSize") .def(&PlayerNpcSession::SetInitialized, "SetInitialized") ; return true; } bool NpcSessionReply_fflua_reg(lua_State* state) { //for decltype NpcSessionReply* message(nullptr); message; ff::fflua_register_t<NpcSessionReply, ctor()>(state, "NpcSessionReply", "google::protobuf::Message") // required int32 index = 1; .def(&NpcSessionReply::index, "index") .def(&NpcSessionReply::set_index, "set_index") // required string msg_name = 2; .def(&NpcSessionReply::msg_name, "msg_name") .def<void (NpcSessionReply::*)(const std::string&)>(&NpcSessionReply::set_msg_name, "set_msg_name") // optional string string_param = 3; .def(&NpcSessionReply::string_param, "string_param") .def<void (NpcSessionReply::*)(const std::string&)>(&NpcSessionReply::set_string_param, "set_string_param") .def(&NpcSessionReply::has_string_param, "has_string_param") // optional int32 int_param = 4; .def(&NpcSessionReply::int_param, "int_param") .def(&NpcSessionReply::set_int_param, "set_int_param") .def(&NpcSessionReply::has_int_param, "has_int_param") .def(&NpcSessionReply::ByteSize, "ByteSize") .def(&NpcSessionReply::SetInitialized, "SetInitialized") ; return true; } bool NoNpcSession_fflua_reg(lua_State* state) { //for decltype NoNpcSession* message(nullptr); message; ff::fflua_register_t<NoNpcSession, ctor()>(state, "NoNpcSession", "google::protobuf::Message") // required string string_param = 1; .def(&NoNpcSession::string_param, "string_param") .def<void (NoNpcSession::*)(const std::string&)>(&NoNpcSession::set_string_param, "set_string_param") // required fixed64 long_param = 2; .def(&NoNpcSession::long_param, "long_param") .def(&NoNpcSession::set_long_param, "set_long_param") // required int32 int_param = 3; .def(&NoNpcSession::int_param, "int_param") .def(&NoNpcSession::set_int_param, "set_int_param") .def(&NoNpcSession::ByteSize, "ByteSize") .def(&NoNpcSession::SetInitialized, "SetInitialized") ; return true; } bool MountConfig_fflua_reg(lua_State* state) { //for decltype MountConfig* message(nullptr); message; ff::fflua_register_t<MountConfig, ctor()>(state, "MountConfig", "google::protobuf::Message") // required int32 id = 1; .def(&MountConfig::id, "id") .def(&MountConfig::set_id, "set_id") // required int32 speed = 2; .def(&MountConfig::speed, "speed") .def(&MountConfig::set_speed, "set_speed") // required int32 impact_id = 3; .def(&MountConfig::impact_id, "impact_id") .def(&MountConfig::set_impact_id, "set_impact_id") .def(&MountConfig::ByteSize, "ByteSize") .def(&MountConfig::SetInitialized, "SetInitialized") ; return true; } bool SceneObject_fflua_regist_all(lua_State* state) { SceneLayout_fflua_reg(state); NpcStaticConfig_fflua_reg(state); NpcDynamicConfig_fflua_reg(state); PositionGroupConfig_fflua_reg(state); NpcInfo_fflua_reg(state); PlayerList_fflua_reg(state); NpcList_fflua_reg(state); PlayerNpc_fflua_reg(state); PlayerNpcList_fflua_reg(state); NpcSession_fflua_reg(state); PlayerNpcSession_fflua_reg(state); NpcSessionReply_fflua_reg(state); NoNpcSession_fflua_reg(state); MountConfig_fflua_reg(state); return true; } }
c45ab2624e886b1fa0a871e225a8bcd2d457fe8a
473c46829b93e230f05a9bbfb927959d0ab1fd6f
/temp/Graph.h
d6bbf717fd63ffc831afd45d80da9a524ad932c1
[]
no_license
Sh4nglj/BA1-2-Data-Structure
357d63e97095c5866f8712cd852237b80f93ea7d
9c4051c35e38a4dfd71807f1de3eb92ac4ff3910
refs/heads/master
2022-09-28T16:01:35.739846
2020-06-04T10:44:31
2020-06-04T10:44:31
263,648,277
0
0
null
null
null
null
GB18030
C++
false
false
1,624
h
Graph.h
/******************************************************************************* * FileName: Graph.h * Author: Name * Student Number: Student_id * Date: 2020/04/29 11:24:55 * Version: v1.0 * Description: Data Structure Experiment #11 *******************************************************************************/ #ifndef GRAPH_H #define GRAPH_H class Graph { private: struct EdgeNode { EdgeNode* next; int dest; int weight; }; struct VexNode { EdgeNode* first = nullptr; int data; int indegree = 0; int outdegree = 0; }; VexNode* data; int num = 0; int point_Num = 0;//记录点的个数 public: /** * 类的构造函数 @name Graph(int) @param arg1 最大的定点数 @return */ Graph(int max_v); /** * 类的析构函数 @name ~Graph() @param @return */ ~Graph(); /** * 向图中加入(s, t), 权重为w的单向 @name addedge(int, int, int) @param arg1 边的顶点1 @param arg2 边的顶点2 @param arg3 边的权重 @return void */ void addedge(int s, int t, int w); /** * 询问图中节点的个数 @name int getV() @param @return int 图中节点的个数 */ int getV(); /** * 询问图拓扑排序的结果,并将结果储存在数组中 @name int* topological() @param @return int* 拓扑排序的结果 */ int* topological(); }; #endif;
4bc1fc3677a5418b9210f425422056f55f6d78c1
013c01020523b5b184c1f44bf7df41ab2ed59923
/Projet4/FrostbiteGeneral.h
00cec8025010bea278071bcf29ee72b3ab6abf69
[]
no_license
Kuwagamon/Cplus
499e2539a540699a373982379f06dd2c403db033
6787e366526903f0aa16f3c337646acbca975109
refs/heads/master
2023-03-15T16:19:27.066441
2015-04-24T19:40:20
2015-04-24T19:40:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,777
h
FrostbiteGeneral.h
#pragma once #include <Windows.h> #include "Eastl.h" namespace fb { // typedef eastl::allocator eastl_arena_allocator; #define EASTLDummyAllocatorType template<typename T> class WeakToken { public: T* m_RealPtr; //0x0000 };//Size=0x0008 template<typename T> class ConstWeakPtr { public: WeakToken<T>* m_Token; //0x0000 T* Get() { if (m_Token && m_Token->m_RealPtr) { DWORD_PTR realPtr = (DWORD_PTR) m_Token->m_RealPtr; return (T*) (realPtr - sizeof(DWORD_PTR)); } return NULL; } };//Size=0x0008 template<typename T> class WeakPtr : public ConstWeakPtr<T> { };//Size=0x0008 template<typename T> class Array : public eastl::BasicArray<T> { };//Size=0x0008 struct Guid { unsigned long m_Data1; //0x0000 unsigned short m_Data2; //0x0004 unsigned short m_Data3; //0x0006 unsigned char m_Data4[8]; //0x0008 };//Size=0x0010 struct Color32 { union { struct { unsigned char m_R; //0x0000 unsigned char m_G; //0x0001 unsigned char m_B; //0x0002 unsigned char m_A; //0x0003 }; unsigned int m_Data; //0x0000 }; Color32(unsigned char r1, unsigned char g1, unsigned char b1, unsigned char a1); Color32(unsigned int col); };//Size=0x0004 template<class T> class Tuple2 { public: T m_Element1; T m_Element2; Tuple2(T element1, T element2) { m_Element1 = element1; m_Element2 = element2; } };//Size=2*T }
c50b1bb6b49dc07d51d16f0e4fd5045d6f5a3398
69379350f785b0931a26741b6f817b43ea06d520
/QuickSort.h
9075884e206c8d655956ed9448d215eba16b2383
[]
no_license
wangsi12/Sort
fbd73e0b1d3e35eeac88b54258e893f4542faa5a
60f041f0b8c67c65ffc82d078d76bc2f980077e0
refs/heads/master
2020-04-28T00:30:29.882555
2019-03-10T13:15:45
2019-03-10T13:15:45
174,818,044
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
263
h
QuickSort.h
#ifndef QUICKSORT_H void QuickSort(int* nums, int low, int high);//µÝ¹é template<typename T> void QuickSortTemplate(T* nums, int low, int high); template<typename T> void QuickSortTemplate1(T* nums, int n); void Test_QuickSort(); #endif // !QUICKSORT_H
f7ba083f1b495daeb6cc4bce8cda00dd3b81021e
7fb17afc90efcee56bc38025ca92c5c9785e3813
/Concurrency3/concurrency3.cpp
d7859986d2ef9d91f368f1ee41dd84f53c369712
[]
no_license
bomberm/CS444Assignments
f6ae1a780bdb2c263af00243e2c18a799deeb48e
c096e1402df86479f8ece55562647b5d65778dc3
refs/heads/master
2021-08-19T19:01:34.435021
2017-11-27T06:21:43
2017-11-27T06:21:43
106,240,092
0
0
null
null
null
null
UTF-8
C++
false
false
1,936
cpp
concurrency3.cpp
#include <iostream> #include <thread> #include <sstream> #include <stdlib.h> #include <unistd.h> #include <vector> #include "generalHelpers.h" #include "sharedResource.h" void problem1(); void problem2(); int main(void) { std::string input; int choice; std::cout << "Please select if you would like to see the demonstration of Problem 1 (enter 1) or Problem 2 (enter 2)" << std::endl; std::getline(std::cin, input); srand(time(NULL)); while(true) { std::stringstream(input) >> choice; if(1 == choice) { problem1(); } else if (2 == choice) { problem2(); } else { std::cout << "ERROR: Choice not valid. Please enter 1 for Problem 1 or 2 for Problem 2." << std::endl; std::getline(std::cin, input); } } } void problem1() { SharedResource *resource = new SharedResource; std::vector<std::thread> threads; int sleepTime = (rand() % 3) + 1; while(1) { if(resource->isOverloaded()) { sleep(4); //little pause to make sure system isn't ENTIRELY overwhelmed } threads.emplace_back(consumeResource, resource); threads.back().detach(); sleep(sleepTime); sleepTime = (rand() % 2 ) +1; } } void problem2() { std::vector<std::thread> threads; ListHandler *list_handler = new ListHandler(); // Spawn processes while(true) { // Check if a deleter is waiting if (list_handler->isDeleting()) { sleep(5); } int process_choice = (rand() % 100); // spawn searcher if (process_choice < 40) threads.emplace_back(searcher, list_handler, (rand() % 25)); // spawn inserter if (process_choice >= 40 && process_choice < 70) threads.emplace_back(inserter, list_handler, (rand() % 25)); // spawn deleter if (process_choice >= 70) threads.emplace_back(deleter, list_handler, (rand () % 25)); threads.back().detach(); sleep(1); } }
b3ce5c8dd8b177d2df89305deacce3a9ca1500ac
03c4096d19255a6e72b40949ff2e77ba79fa74f7
/HCalib/HCalib.h
e5f820cb51fb1c1e49079114e0dbc9c2fefed977
[]
no_license
sPHENIX-Collaboration/analysis
c0687cd1b4ea9ec426e71303d2a8b4c34d19c11c
dc932e3355d09898bba525ac1e6292ade5c48d02
refs/heads/master
2023-08-31T22:22:52.275236
2023-08-29T22:53:04
2023-08-29T22:53:04
37,741,543
4
58
null
2023-09-13T19:37:21
2015-06-19T19:25:00
C
UTF-8
C++
false
false
1,186
h
HCalib.h
#ifndef __HCALIB_H__ #define __HCALIB_H__ #include <fun4all/SubsysReco.h> #include <string> class PHCompositeNode; class RawTowerContainer; class RawTowerGeomContainer; class PHG4CellContainer; class PHG4ScintillatorSlatContainer; class TFile; class TH1F; class RawTower; #include <g4detectors/PHG4ScintillatorSlatDefs.h> #include <calobase/RawTowerDefs.h> #include <map> class HCalib : public SubsysReco { public: typedef std::map<PHG4ScintillatorSlatDefs::keytype,TH1F *> SlatMap; typedef std::map<RawTowerDefs::keytype, TH1F *> TowerMap; HCalib(); virtual ~HCalib() {} int Init(PHCompositeNode *topNode); int process_event(PHCompositeNode *topNode); int End(PHCompositeNode *topNode); int genkey(const int detid, const int etabin, const int phibin); enum detid { HCALIN=0, HCALOUT=1 }; protected: bool is_proto; void GetNodes(PHCompositeNode *topNode, const std::string &det = "None"); PHCompositeNode *topNode; RawTowerContainer *towers; PHG4CellContainer* slats; PHG4ScintillatorSlatContainer* proto_slats; float threshold; TFile *outfile; SlatMap slat_hists; TowerMap tower_hists; bool fill_towers; bool fill_slats; }; #endif
f18ec264992d07edf847e1486d45fd60431d59f8
91ac3071b9e5de4ad796c884ab1d945234d79dc7
/Algorithm/Stringarray/waveARR.cpp
e0b2862748ea56d17dede6183c3f877ee5c39777
[]
no_license
anshumanvarshney/CODE
aa22950acf1aed4a694774454716dd5acff38143
a93bb1f20a246948d178a1a59d1ce99945c063f6
refs/heads/master
2021-05-04T12:15:56.879649
2018-02-05T10:48:21
2018-02-05T10:48:21
120,291,672
0
0
null
null
null
null
UTF-8
C++
false
false
3,021
cpp
waveARR.cpp
/* Sort an array in wave form Given an unsorted array of integers, sort the array into a wave like array. An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ….. opposite to zigzag Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {20, 5, 10, 2, 80, 6, 100, 3} OR any other array that is in wave form Input: arr[] = {20, 10, 8, 6, 4, 2} Output: arr[] = {20, 8, 10, 4, 6, 2} OR {10, 8, 20, 2, 6, 4} OR any other array that is in wave form Input: arr[] = {2, 4, 6, 8, 10, 20} Output: arr[] = {4, 2, 8, 6, 20, 10} OR any other array that is in wave form Input: arr[] = {3, 6, 5, 10, 7, 20} Output: arr[] = {6, 3, 10, 5, 20, 7} OR any other array that is in wave form */ /* A Simple Solution is to use sorting. First sort the input array, then swap all adjacent elements. For example, let the input array be {3, 6, 5, 10, 7, 20}. After sorting, we get {3, 5, 6, 7, 10, 20}. After swapping adjacent elements, we get {5, 3, 7, 6, 20, 10}.*/ /* #include<iostream> #include<algorithm> using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5].. void sortInWave(int arr[], int n) { // Sort the input array sort(arr, arr+n); // Swap adjacent elements for (int i=0; i<n-1; i += 2) swap(&arr[i], &arr[i+1]); } // Driver program to test above function int main() { int arr[] = {10, 90, 49, 2, 1, 5, 23}; int n = sizeof(arr)/sizeof(arr[0]); sortInWave(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; } or in O(n)*/ // A O(n) program to sort an input array in wave form #include<iostream> using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., arr[0] >= // arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] .... void sortInWave(int arr[], int n) { // Traverse all even elements for (int i = 0; i < n; i+=2)//i=i+2 { // If current even element is smaller than previous if (i>0 && arr[i-1] > arr[i] ) swap(&arr[i], &arr[i-1]); // If current even element is smaller than next if (i<n-1 && arr[i] < arr[i+1] ) swap(&arr[i], &arr[i + 1]); } } /*or opposite to zigzig */ // Driver program to test above function int main() { int arr[] = {10, 90, 49, 2, 1, 5, 23}; int n = sizeof(arr)/sizeof(arr[0]); sortInWave(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; }
2693e35a4abea5bb7e0ae2c5be12e26b3d4d4a89
fffcaf31dbaa4b7a880fdbbbe32f950122d626d8
/pathtracer13/include/display/film.h
1bed0ab35fa6a397fae47eb26a955f4d102d4f54
[]
no_license
CS-FreeStyle/papi-cuda
4622c8d6acaf9b0564d301df55a409637b003f0f
1eb28a4e4a6bde009b4415f71e6658127aeff043
refs/heads/master
2020-06-16T18:59:02.027877
2012-07-12T22:05:07
2012-07-12T22:05:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,794
h
film.h
/*************************************************************************** * Copyright (C) 1998-2009 by David Bucciarelli (davibu@interfree.it) * * * * This file is part of SmallLuxGPU. * * * * SmallLuxGPU is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * SmallLuxGPU is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * This project is based on PBRT ; see http://www.pbrt.org * * and Lux Renderer website : http://www.luxrender.net * ***************************************************************************/ #ifndef _FILM_H #define _FILM_H #include <cstddef> #include <cmath> #include "utils.h" #include "geometry/vector.h" #include "geometry/spectrum.h" #include "pathtracer.h" #define GAMMA_TABLE_SIZE 1024 #define FILTER_TABLE_SIZE 16 class Film { public: unsigned int width, height; unsigned int pixelCount; unsigned int statsTotalSampleCount; double statsStartSampleTime, statsAvgSampleSec; RGB *pixelsRadiance; float *pixelWeights; float *pixels; float gammaTable[GAMMA_TABLE_SIZE]; Film(const unsigned int w, unsigned int h) { pixelsRadiance = NULL; pixelWeights = NULL; pixels = NULL; InitGammaTable(); Init(w, h); } void StartSampleTime() { statsStartSampleTime = WallClockTime(); } unsigned int GetWidth() { return width; } unsigned int GetHeight() { return height; } unsigned int GetTotalSampleCount() { return statsTotalSampleCount; } double GetTotalTime() { return WallClockTime() - statsStartSampleTime; } double GetAvgSampleSec() { const double elapsedTime = WallClockTime() - statsStartSampleTime; const double k = (elapsedTime < 10.0) ? 1.0 : (1.0 / (2.5 * elapsedTime)); statsAvgSampleSec = k * statsTotalSampleCount / elapsedTime + (1.0 - k) * statsAvgSampleSec; return statsAvgSampleSec; } virtual ~Film() { if (pixelsRadiance) delete[] pixelsRadiance; if (pixelWeights) delete[] pixelWeights; if (pixels) delete[] pixels; } virtual void Init(const unsigned int w, unsigned int h) { if (pixelsRadiance) delete[] pixelsRadiance; if (pixelWeights) delete[] pixelWeights; if (pixels) delete[] pixels; pixelCount = w * h; pixelsRadiance = new RGB[pixelCount]; pixels = new float[pixelCount * 3]; pixelWeights = new float[pixelCount]; for (unsigned int i = 0, j = 0; i < pixelCount; ++i) { pixelsRadiance[i] = 0.f; pixelWeights[i] = 0.f; pixels[j++] = 0.f; pixels[j++] = 0.f; pixels[j++] = 0.f; } width = w; height = h; cerr << "Film size " << width << "x" << height << endl; statsTotalSampleCount = 0; statsAvgSampleSec = 0.0; statsStartSampleTime = WallClockTime(); } virtual void Reset() { for (unsigned int i = 0; i < pixelCount; ++i) { pixelsRadiance[i] = 0.f; pixelWeights[i] = 0.f; } statsTotalSampleCount = 0; statsAvgSampleSec = 0.0; statsStartSampleTime = WallClockTime(); } __HD__ void UpdateScreenBuffer() { unsigned int count = width * height; for (unsigned int i = 0, j = 0; i < count; ++i) { const float weight = pixelWeights[i]; if (weight == 0.f) j += 3; else { const float invWeight = 1.f / weight; pixels[j++] = Radiance2PixelFloat(pixelsRadiance[i].r * invWeight); pixels[j++] = Radiance2PixelFloat(pixelsRadiance[i].g * invWeight); pixels[j++] = Radiance2PixelFloat(pixelsRadiance[i].b * invWeight); } } } const float *GetScreenBuffer() const { return pixels; } __HD__ void SavePPM(const string &fileName) { // Update pixels UpdateScreenBuffer(); const float *pixels = GetScreenBuffer(); ofstream file; file.exceptions(ifstream::eofbit | ifstream::failbit | ifstream::badbit); file.open(fileName.c_str(), ios::out); file << "P3\n" << width << " " << height << "\n255\n"; for (unsigned int y = 0; y < height; ++y) { for (unsigned int x = 0; x < width; ++x) { const int offset = 3 * (x + (height - y - 1) * width); const int r = (int) (pixels[offset] * 255.f + .5f); const int g = (int) (pixels[offset + 1] * 255.f + .5f); const int b = (int) (pixels[offset + 2] * 255.f + .5f); file << r << " " << g << " " << b << " "; } } file.close(); } void InitGammaTable() { float x = 0.f; const float dx = 1.f / GAMMA_TABLE_SIZE; for (int i = 0; i < GAMMA_TABLE_SIZE; ++i, x += dx) gammaTable[i] = powf(Clamp(x, 0.f, 1.f), 1.f / 2.2f); } __HD__ float Radiance2PixelFloat(const float x) const { // Very slow ! //return powf(Clamp(x, 0.f, 1.f), 1.f / 2.2f); const unsigned int index = Min<unsigned int> ( Floor2UInt(GAMMA_TABLE_SIZE * Clamp(x, 0.f, 1.f)), GAMMA_TABLE_SIZE - 1); return gammaTable[index]; } }; #endif /* _FILM_H */
323842d163e4d8e36b3928cb0cfa3ec0c392507f
492976adfdf031252c85de91a185bfd625738a0c
/src/Game/AI/AI/aiChemicalEnemyFindPlayer.cpp
de0569c43db2b4aa9d35a2363cf2809c867ed51b
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
571
cpp
aiChemicalEnemyFindPlayer.cpp
#include "Game/AI/AI/aiChemicalEnemyFindPlayer.h" namespace uking::ai { ChemicalEnemyFindPlayer::ChemicalEnemyFindPlayer(const InitArg& arg) : LandHumEnemyFindPlayer(arg) {} ChemicalEnemyFindPlayer::~ChemicalEnemyFindPlayer() = default; void ChemicalEnemyFindPlayer::enter_(ksys::act::ai::InlineParamPack* params) { LandHumEnemyFindPlayer::enter_(params); } void ChemicalEnemyFindPlayer::leave_() { LandHumEnemyFindPlayer::leave_(); } void ChemicalEnemyFindPlayer::loadParams_() { LandHumEnemyFindPlayer::loadParams_(); } } // namespace uking::ai
ff5286cad1bc341670f9f8dac2568e9ba8c6fd6b
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/onnxruntime/core/providers/cann/npu_data_transfer.cc
2f51c550b207ef8aba665ad32a795e5154bb3c54
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
4,608
cc
npu_data_transfer.cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Copyright (c) Huawei. All rights reserved. // Licensed under the MIT License. #include "core/providers/shared_library/provider_api.h" #include "core/providers/cann/npu_data_transfer.h" namespace onnxruntime { NPUDataTransfer::NPUDataTransfer() {} NPUDataTransfer::~NPUDataTransfer() {} bool NPUDataTransfer::CanCopy(const OrtDevice& src_device, const OrtDevice& dst_device) const { return src_device.Type() == OrtDevice::NPU || dst_device.Type() == OrtDevice::NPU; } common::Status NPUDataTransfer::CopyTensor(const Tensor& src, Tensor& dst) const { size_t bytes = src.SizeInBytes(); const void* src_data = src.DataRaw(); void* dst_data = dst.MutableDataRaw(); auto& src_device = src.Location().device; auto& dst_device = dst.Location().device; // for the sync version of memcpy, launch to cann default stream if (dst_device.Type() == OrtDevice::NPU) { if (src_device.Type() == OrtDevice::NPU) { // Copy only if the two addresses are different. if (dst_data != src_data) { CANN_RETURN_IF_ERROR(aclrtMemcpy(dst_data, bytes, src_data, bytes, ACL_MEMCPY_DEVICE_TO_DEVICE)); CANN_RETURN_IF_ERROR(aclrtSynchronizeStream(nullptr)); } } else { // copy from other CPU memory to NPU, this is blocking CANN_RETURN_IF_ERROR(aclrtMemcpy(dst_data, bytes, src_data, bytes, ACL_MEMCPY_HOST_TO_DEVICE)); CANN_RETURN_IF_ERROR(aclrtSynchronizeStream(nullptr)); } } else if (src_device.Type() == OrtDevice::NPU) { // copying from NPU to CPU memory, this is blocking CANN_RETURN_IF_ERROR(aclrtMemcpy(dst_data, bytes, src_data, bytes, ACL_MEMCPY_DEVICE_TO_HOST)); CANN_RETURN_IF_ERROR(aclrtSynchronizeStream(nullptr)); } else { // copying between cpu memory memcpy(dst_data, src_data, bytes); } return Status::OK(); } common::Status NPUDataTransfer::CopyTensorAsync(const Tensor& src, Tensor& dst, Stream& stream) const { size_t bytes = src.SizeInBytes(); const void* src_data = src.DataRaw(); void* dst_data = dst.MutableDataRaw(); auto& src_device = src.Location().device; auto& dst_device = dst.Location().device; if (dst_device.Type() == OrtDevice::NPU) { if (src_device.Type() == OrtDevice::CPU) { // copy from pinned memory to NPU, this is non-blocking CANN_RETURN_IF_ERROR(aclrtMemcpyAsync(dst_data, bytes, src_data, bytes, ACL_MEMCPY_HOST_TO_DEVICE, static_cast<aclrtStream>(stream.GetHandle()))); } else if (src_device.Type() == OrtDevice::NPU) { // copying between NPU, this is non-blocking if (dst_data != src_data) { CANN_RETURN_IF_ERROR(aclrtMemcpyAsync(dst_data, bytes, src_data, bytes, ACL_MEMCPY_DEVICE_TO_DEVICE, static_cast<aclrtStream>(stream.GetHandle()))); } } } else if (src_device.Type() == OrtDevice::NPU) { if (dst_device.Type() == OrtDevice::CPU) { // copying from NPU to pinned memory, this is non-blocking CANN_RETURN_IF_ERROR(aclrtMemcpyAsync(dst_data, bytes, src_data, bytes, ACL_MEMCPY_DEVICE_TO_HOST, static_cast<aclrtStream>(stream.GetHandle()))); } } else { if (src_device.MemType() == OrtDevice::MemType::CANN_PINNED) { // sync the stream first to make sure the data arrived CANN_RETURN_IF_ERROR(aclrtSynchronizeStream(static_cast<aclrtStream>(stream.GetHandle()))); } memcpy(dst_data, src_data, bytes); } return Status::OK(); } } // namespace onnxruntime
fea62a5eeea4908ad154950711859a6239771352
2d9cd06217a836395bcad23dfcf6e4a670663af3
/libraries/kali/string.h
6e2fca44ed5b081d9a8276e2910683a8aa679594
[ "MIT" ]
permissive
seven-phases/spectrum-analyzer
922b5effea4190447f848a5d22a645f3528c39e7
b3638de0a194cf43afb5e96c9e6bc7c9ca2687d7
refs/heads/master
2021-01-10T04:16:14.125687
2015-07-14T00:07:41
2015-07-14T00:07:41
36,190,752
101
23
null
null
null
null
UTF-8
C++
false
false
2,734
h
string.h
#ifndef KALI_STRING_INCLUDED #define KALI_STRING_INCLUDED #include <string.h> #include <stdarg.h> #include "kali/platform.h" // ............................................................................ namespace kali { namespace details { // ............................................................................ template <unsigned Size> struct String { String(const char* src) {copy(data, src, size);} explicit String(const char* format, ...) format__ { if (format) { va_list arglist; va_start(arglist, format); vsnprintf(data, size, format, arglist); va_end(arglist); data[size - 1] = 0; } else *data = 0; } String() {*data = 0;} char* operator () () {return data;} operator const char* () const {return data;} const char* operator () () const {return data;} enum {size = Size}; private: char data[size]; template <typename T> String(T); template <typename T> operator T () const; // ........................................................................ // extra helpers: public: const char* append(const char* src) { // meet Schlemiel size_t n = strlen(data); copy(data + n, src, int(size - n)); return data; } template <int n> static wchar_t* a2w(wchar_t (&dst)[n], const char* src) {return copy(dst, src, n);} static wchar_t* a2w(wchar_t* dst, const char* src, int n) {return copy(dst, src, n);} template <int n> static char* w2a(char (&dst)[n], const wchar_t* src) {return copy(dst, src, n);} static char* w2a(char* dst, const wchar_t* src, int n) {return copy(dst, src, n);} #if MACOSX_ static NSString* ns(const char* src) { return !src ? nil : [NSString stringWithCString:src encoding:NSMacOSRomanStringEncoding]; } #endif private: template <typename A, typename B> static A* copy(A* restrict_ dst, const B* restrict_ src, int n) { A* p = dst; while ((--n > 0) && *src) *p++ = A(*src++); *p = 0; return dst; } // ........................................................................ }; // ~ struct String // ............................................................................ } // ~ namespace details // ............................................................................ typedef details::String <256> string; // ............................................................................ } // ~ namespace kali // ............................................................................ #endif // ~ KALI_STRING_INCLUDED
fb3a41c2fa0c1e15d79e594ccfe7abe3eb1afd5d
65ac436d3a7f2cd86a6449a1952ed0d50e283852
/L2/src/architecture.h
fa192968347ba6990f9d6fe86e4b5b9303ceef9e
[]
no_license
dwivedisankalp97/Compiler-Construction
a38a7faddd1b25507ddcee9415197d533ee0e769
678f69ba1011fc7160150c521afcda804e8973c6
refs/heads/master
2022-04-11T07:04:12.158465
2020-03-05T20:00:24
2020-03-05T20:00:24
244,785,642
0
0
null
null
null
null
UTF-8
C++
false
false
176
h
architecture.h
#pragma once namespace L2 { extern std::string GPregisters[16] = {"rdi", "rax", "rbx", "rbp", "r10", "r11", "r12", "r13", "r14", "r15", "rsi", "r8", "r9", "rcx", "rdx"}; }
6505112ef4a469b385f508e138b33ad46b444fb1
39ac6d3f7f93be4a1a7bf4bf7bc8b292bec9e552
/src/core/events/eventdispatch.h
25b4b232530e0d64e541b6ef10afb57b575b7dce
[ "MIT" ]
permissive
jpxor/Boilerplate
d3cc7840d29a4d4392f6a6c9fb477936471bdbc7
c1736b1a1fc714be21fba5f3159f6483b888a662
refs/heads/master
2021-09-04T05:15:22.135249
2018-01-16T07:16:37
2018-01-16T07:16:37
106,244,746
1
0
null
null
null
null
UTF-8
C++
false
false
599
h
eventdispatch.h
#pragma once #include <memory> #include <functional> namespace Events{ class Event{ public: int id; Event(int event_id):id(event_id){;;} }; int subscribe(std::string chan_name, std::function<void(std::unique_ptr<Event>&)> callback); void unsubscribe(std::string chan_name, int id); void dispatch_now(std::string chan_name, std::unique_ptr<Event> event); void dispatch_async(std::string chan_name, std::unique_ptr<Event>& event); void dispatch_later(std::string chan_name, std::unique_ptr<Event> event); void dispatch_waiting_events(); }
7b76ba37b9dd0e1ea94d6b29bd0936aa3381195b
2d91d1af1f049248c9e5f2c4047289d614fcb0b4
/cpp_utils/BLEAddress.h
7eff4da4bb624185410f474b1632a1121cd99eea
[ "Apache-2.0" ]
permissive
chegewara/esp32-snippets
8b9d8e5fb8cbe9ef912b38561795620944b59b01
874ce79815817a4796612716c95ea6d639c9df0b
refs/heads/wip
2021-05-07T03:38:48.099902
2018-10-01T23:37:06
2018-10-01T23:37:06
110,790,433
9
4
Apache-2.0
2018-10-03T22:53:41
2017-11-15T06:01:18
C
UTF-8
C++
false
false
749
h
BLEAddress.h
/* * BLEAddress.h * * Created on: Jul 2, 2017 * Author: kolban */ #ifndef COMPONENTS_CPP_UTILS_BLEADDRESS_H_ #define COMPONENTS_CPP_UTILS_BLEADDRESS_H_ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include <esp_gap_ble_api.h> // ESP32 BLE #include <string> /** * @brief A %BLE device address. * * Every %BLE device has a unique address which can be used to identify it and form connections. */ class BLEAddress { public: BLEAddress(esp_bd_addr_t address); BLEAddress(std::string stringAddress); bool equals(BLEAddress otherAddress); esp_bd_addr_t* getNative(); std::string toString(); private: esp_bd_addr_t m_address; }; #endif /* CONFIG_BT_ENABLED */ #endif /* COMPONENTS_CPP_UTILS_BLEADDRESS_H_ */
bf73f814aecaecb231aa204ae3d9b4ea5747417a
5c176fb35c7f24229657e78014ad151f0bf49880
/UglyNumber.cpp
7f61ea13a0bb1264aa220000445aee3e5ef35f4b
[]
no_license
YangKai-NEU/algorithms
e3caac49d6e30bdcbe3268ad16e797167a03f5eb
308f0f3434392b294747099626c42b963e0ebfef
refs/heads/master
2021-01-22T07:42:30.083682
2017-09-04T02:55:18
2017-09-04T02:55:18
102,311,499
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
UglyNumber.cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: int GetUglyNumber_Solution(int index) { vector<int> s; s.push_back(0); s.push_back(1); int pos2=1; int pos3=1; int pos5=1; for(int i=2;i<=index;i++){ s.push_back(min(min(s[pos2]*2,s[pos3]*3),s[pos5]*5)); if(s[i]==s[pos2]*2){ pos2++; } if(s[i]==s[pos3]*3){ pos3++; } if(s[i]==s[pos5]*5){ pos5++; } } return s[index]; } }; int main(int argc, char *argv[]) { Solution solution; cout<<solution.GetUglyNumber_Solution(5)<<endl; return 0; }
4a5437d4103490a9c791fd07db6b9ef879fcbd60
751f8fce7aa82084e5d5e08a8e36033e105d7de0
/Client/src/Game.cpp
5afa2a5fe47ac83215713152186936a1a8d52e7a
[]
no_license
jstoja/r-type
fe8563d3a00eda5f56ed4ac69a7206acd06aa5e2
8e2a290abca5c1094527afcf6669073552fa86ed
refs/heads/master
2021-01-20T01:03:42.751198
2013-01-23T11:00:27
2013-01-23T11:00:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,980
cpp
Game.cpp
// // Game.cpp for R-Type in /home/olivie_a/R-Type // // Made by Samuel Olivier // Login <olivie_a@epitech.net> // // Started on ven. janv. 18 10:36:08 2013 Samuel Olivier // #include "Game.h" Game::Game(uint32 id) : Object(id), _nbPlayer(0), _nbSlot(0) { } Game::~Game() { _clear(); } void Game::setName(std::string const& name) { _name = name; } std::string const& Game::getName() const { return (_name); } void Game::setNbPlayer(uint32 nbPlayer) { _nbPlayer = nbPlayer; } uint32 Game::getNbPlayer() const { return (_nbPlayer); } void Game::setNbSlot(uint32 nbSlot) { _nbSlot = nbSlot; } uint32 Game::getNbSlot() const { return (_nbSlot); } void Game::addPlayer(Player* player) { _players.push_back(player); _nbPlayer = _players.size(); } void Game::addPlayer(Network::TcpPacket& packet) { _players.push_back(Player::newPlayer(packet)); _nbPlayer = _players.size(); } std::list<Player*> const& Game::getPlayers() const { return (_players); } void Game::setPlayers(std::list<Player*> const& players) { _clear(); _players = players; _nbPlayer = _players.size(); } void Game::setPlayers(Network::TcpPacket& packet) { uint32 size; _clear(); packet >> size; for (uint32 i = 0; i < size; ++i) { Player* player = Player::newPlayer(packet); _players.push_back(player); } _nbPlayer = _players.size(); } void Game::_clear() { for (std::list<Player*>::iterator it = _players.begin(); it != _players.end(); ++it) delete *it; _players.clear(); _nbPlayer = 0; } void Game::setPlayerReady(uint32 playerId, bool value) { for (std::list<Player*>::iterator it = _players.begin(); it != _players.end(); ++it) if ((*it)->getId() == playerId) (*it)->setIsReady(value); } Game* Game::newGame(Network::TcpPacket& packet) { uint32 id, nbPlayer, nbSlot; std::string name; Game* res; packet >> id >> name >> nbPlayer >> nbSlot; res = new Game(id); res->setName(name); res->setNbPlayer(nbPlayer); res->setNbSlot(nbSlot); return (res); }
5577d2d8f830860168e8eb2f90360efcbff8a2dc
450c9a8e8d590b5ad887611cfcf6804248755dfd
/2054/sol.cc
3d1dabdd58d57afb48c01c4ca9f70c6ae0dffc0b
[]
no_license
bcc32/tju-online-judge
64d6a4afbdf9b8f8cbbeb0c881fefac94dfde967
7e0c38bcff12b5d48b6d4d3c4320242a2022030f
refs/heads/master
2021-01-24T17:37:53.715808
2020-01-25T18:23:09
2020-01-25T18:23:09
3,436,343
0
0
null
null
null
null
UTF-8
C++
false
false
1,819
cc
sol.cc
#include <iostream> #include <vector> #include <utility> #include <algorithm> using namespace std; bool cmp(pair< pair<int, int>, pair<int, int> > a, pair< pair<int, int>, pair<int, int> > b); int main(void) { int dollars, cents, a, b, c, d; char foo; for (cin >> dollars >> foo >> cents >> a >> b >> c >> d; !cin.eof(); cin >> dollars >> foo >> cents >> a >> b >> c >> d) { int n = 100 * dollars + cents; vector< pair< pair<int, int>, pair<int, int> > > v; for (int x = 0; x <= a; x++) { if (25 * x > n) break; for (int y = 0; y <= b; y++) { if (25 * x + 10 * y > n) break; for (int z = 0; z <= c; z++) { if (25 * x + 10 * y + 5 * z > n) break; for (int w = 0; w <= d; w++) { if (25 * x + 10 * y + 5 * z + w > n) break; else if (25 * x + 10 * y + 5 * z + w == n) v.push_back(make_pair(make_pair(x, y), make_pair(z, w))); } } } } if (v.size() > 0) { pair< pair<int, int>, pair<int, int> > p = *min_element(v.begin(), v.end(), cmp); cout << p.first.first << " " << p.first.second << " " << p.second.first << " " << p.second.second << endl; } else cout << "NO EXACT CHANGE" << endl; } } bool cmp(pair< pair<int, int>, pair<int, int> > a, pair< pair<int, int>, pair<int, int> > b) { return a.first.first + a.first.second + a.second.first + a.second.second < b.first.first + b.first.second + b.second.first + b.second.second; }
fb0909667bce8b7c063ad87afd987e5d97c8ade7
9903efc5369774f7e4ddb0dbe610d4a3bb3b3759
/mq/lock/thread.cpp
60039c1e2293a46f627f231e1182009f998dfbbc
[]
no_license
wyf2317/C-
6a49f583bcf0728c4da1ac0f2a40afec2cfe9b0e
50ea7cc5a4e677ebb3d5fdd614968d74ac1bde84
refs/heads/master
2020-07-10T13:05:32.423245
2019-09-19T13:17:46
2019-09-19T13:17:46
204,269,321
0
0
null
null
null
null
UTF-8
C++
false
false
625
cpp
thread.cpp
// g++ -lpthread -std=c++11 thread.cpp #include <stdio.h> #include <iostream> #include <thread> #include <mutex> // std::mutex std::mutex mtx; // mutex for critical section int money; void addMoney(int id) { for (int i = 0; i < 10000; i++) { mtx.lock(); money = money + 1; mtx.unlock(); } } int main() { money = 0; std::thread threads[100]; for (int i = 0 ; i < 100; i++) { threads[i] = std::thread(addMoney, i); } for (auto& th : threads) th.join(); printf("total money:%d\n", money); return 0; }
8718f3b98569df9922d33df3c6110accecde21be
271b2bdcd2534ecc63ef480474c82f8503440101
/JPEG-Encoder-SIMD/BitBuffer.h
2013c643642d3a125db754852f2ef2c41cf303b6
[]
no_license
Irame/JPEG-Encoder
4174e4179f2033722951ed6551f6a0fbd01df4a0
5636d696e341500eac19e02efaf0e5e539f0d176
refs/heads/master
2021-01-10T17:54:51.997641
2016-12-17T12:29:00
2016-12-17T12:29:00
43,671,990
9
3
null
null
null
null
UTF-8
C++
false
false
2,908
h
BitBuffer.h
#pragma once #include <vector> #include <memory> class BitBuffer { size_t bufferSizeInByte; std::vector<byte> data; // position in 'data' in bits size_t dataBitOffset; void ensureFreeSpace(size_t numOfBits); static byte joinTwoBytes(byte leftByte, byte rightByte, size_t leftCount); void pushBits(const BitBuffer& buffer, bool escape); void pushBits(size_t numOfBits, const void* buffer, bool escape); void pushBits(size_t numOfBits, const void* buffer, size_t offset, bool escape); public: BitBuffer(size_t initialBufferSize = 0); // Get the size in bits (number of set bits) size_t getSize() const { return dataBitOffset; }; // Get the maximum number of bits that can be stored at the moment size_t getCapacity() const { return bufferSizeInByte * 8; }; void fillToByteBorder(); // Appends a single bit at the end of the BitBuffer void pushBit(bool val); // Adds the content of buffer. void pushBits(const BitBuffer& buffer); // Adds a certain number of bits from a specific location with an offset void pushBits(size_t numOfBits, const void* buffer, size_t offset); // Adds a certain number of bits from a specific location void pushBits(size_t numOfBits, const void* buffer); // Adds the content of buffer. 0xFF bytes will be escaped. void pushBitsEscaped(const BitBuffer& buffer); // Adds a certain number of bits from a specific location. 0xFF bytes will be escaped. void pushBitsEscaped(size_t numOfBits, const void* buffer); // Adds a certain number of bits from a specific location with an offset. 0xFF bytes will be escaped. void pushBitsEscaped(size_t numOfBits, const void* buffer, size_t offset); // Returns the bit at the given index bool getBit(size_t index) const; // Writes the requested bits into an out byte array void getBits(size_t index, void* out, size_t numOfBits) const; // clears conent void clear(); // Writes all bits from the buffer into a file (in binary) void writeToFile(std::string file); // compares two BitBuffer bool operator==(const BitBuffer& other) const; bool operator<(const BitBuffer& other) const; bool operator>(const BitBuffer& other) const; int compare(const BitBuffer& other) const; // Converts the Buffer into a string of '0' and '1' in blocks seperated by ' ' or ' ' friend std::ostream& operator<<(std::ostream& strm, const BitBuffer& bitBuffer); // Generic write method template<typename T> void push(T& value, size_t offset) { pushBits(sizeof(T) * 8, &value, offset); } template<typename T> void push(T& value) { pushBits(sizeof(T) * 8, &value); } }; // specialized version for bool template<> inline void BitBuffer::push(bool& value, size_t offset) { pushBit(value); } typedef std::shared_ptr<BitBuffer> BitBufferPtr; typedef std::shared_ptr<const BitBuffer> ConstBitBufferPtr;
b3e166e1849f4066f4bdf654ec48a1d7a1ff6064
3dc794e259aecc627f617be97c77fe247e99a0cb
/src/json_rpc.h
22e682a574a1c4fcbf58df23103c40d5d179c984
[]
no_license
bebac/fuzzy-octo-avenger
0cbb9e783d4279a698719b728df6ff5f4e747b29
9e37192307479c204873ecd3e3aacce5ed882738
refs/heads/master
2021-01-01T06:49:57.114440
2016-01-25T18:32:08
2016-01-25T18:32:08
23,521,652
1
0
null
null
null
null
UTF-8
C++
false
false
5,395
h
json_rpc.h
// ---------------------------------------------------------------------------- // // Filename : json_rpc.h // // Author : Benny Bach <benny.bach@gmail.com> // Copyright (C) 2014 // // --- Description: ----------------------------------------------------------- // // // ---------------------------------------------------------------------------- #ifndef __json_rpc_h__ #define __json_rpc_h__ // ---------------------------------------------------------------------------- #include <dripcore/loop.h> #include <dripcore/eventable.h> #include <json/json.h> // ---------------------------------------------------------------------------- #include <string> #include <cstring> #include <thread> #include <functional> #include <map> #include <queue> #include <condition_variable> #include <atomic> // ---------------------------------------------------------------------------- #include <unistd.h> #include <sys/eventfd.h> // ---------------------------------------------------------------------------- class json_rpc_request { public: json_rpc_request() : error_code_(0) { } public: const std::string& version() const { return version_; } const std::string& method() const { return method_; } const json::value& params() const { return params_; } const json::value& id() const { return id_; } public: bool is_valid() const { return error_code_ == 0; } public: int error_code() const { return error_code_; } public: static json_rpc_request from_json(json::value& v) { json_rpc_request self; if ( v.is_object() ) { auto& o = v.as_object(); if ( !o["jsonrpc"].is_string() ) { self.error_code_ = -32600; } if ( !o["method"].is_string() ) { self.error_code_ = -32600; } if ( !o["params"].is_null() ) { self.params_ = o["params"]; } else { self.params_ = json::value(); } if ( !o["id"].is_null() ) { self.id_ = o["id"]; } if ( self.is_valid() ) { self.version_ = o["jsonrpc"].as_string(); self.method_ = o["method"].as_string(); } } else { self.error_code_ = -32600; } return std::move(self); } private: std::string version_; std::string method_; json::value params_; json::value id_; // If error != 0 none of the above will be valid. int error_code_; }; // ---------------------------------------------------------------------------- class json_rpc_response { friend std::string to_string(const json_rpc_response& response); public: json_rpc_response(const json_rpc_request& request) : object_{ { "jsonrpc", "2.0" }, { "id", request.id() } } { if ( !request.is_valid() ) { error(request.error_code(), "Invalid Request"); } } public: void set_result(json::value value) { object_["result"] = std::move(value); } public: void error(int error_code, std::string error_message) { object_["error"] = json::object{ { "code", error_code }, { "message", std::move(error_message) } }; } public: void method_not_found() { error(-32601, "Method not found"); } public: void invalid_params() { error(-32602, "Invalid params"); } private: json::object object_; }; // ---------------------------------------------------------------------------- inline std::string to_string(const json_rpc_response& response) { return to_string(response.object_); } // ---------------------------------------------------------------------------- class json_rpc_notification { friend std::string to_string(const json_rpc_notification& notification); public: json_rpc_notification(const std::string& method, json::value params) : object_{ { "jsonrpc", "2.0" }, { "method", method }, { "params", params } } { } private: json::object object_; }; // ---------------------------------------------------------------------------- inline std::string to_string(const json_rpc_notification& notification) { return to_string(notification.object_); } // ---------------------------------------------------------------------------- namespace jsonrpc { namespace server { class connection; } class service { using lock_guard = std::lock_guard<std::recursive_mutex>; using method_func = std::function<json_rpc_response(const json_rpc_request& request)>; public: service(); public: ~service(); public: void add_method(const std::string& name, method_func method) { methods_.emplace(std::move(name), std::move(method)); } public: json_rpc_response execute(const json_rpc_request& request); public: void send_notification(json_rpc_notification notification); public: void attach_connection(std::shared_ptr<server::connection> connection); void detach_connection(std::shared_ptr<server::connection> connection); private: using method_map_t = std::map<std::string, method_func>; using connection_ptr = std::weak_ptr<server::connection>; using connection_container = std::set<connection_ptr, std::owner_less<connection_ptr>>; private: method_map_t methods_; connection_container connections_; std::recursive_mutex mutex_; }; } // ---------------------------------------------------------------------------- #endif // __json_rpc_h__
05d86a6e1ea0eded56ffa6c598dcfca6e777015c
bdd9f3cdabe0c768641cf61855a6f24174735410
/src/engine/client/application/DatabaseObjectViewer/ChildFrame.h
9c9ae012ba397cd667f3dac0abee2d9cf17abaaa
[]
no_license
SWG-Source/client-tools
4452209136b376ab369b979e5c4a3464be28257b
30ec3031184243154c3ba99cedffb2603d005343
refs/heads/master
2023-08-31T07:44:22.692402
2023-08-28T04:34:07
2023-08-28T04:34:07
159,086,319
15
47
null
2022-04-15T16:20:34
2018-11-25T23:57:31
C++
UTF-8
C++
false
false
1,100
h
ChildFrame.h
// ====================================================================== // // ChildFrame.h // asommers // // copyright 2003, sony online entertainment // // ====================================================================== #ifndef INCLUDED_ChildFrame_H #define INCLUDED_ChildFrame_H // ====================================================================== class ChildFrame : public CMDIChildWnd { DECLARE_DYNCREATE(ChildFrame) public: ChildFrame(); virtual ~ChildFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif //{{AFX_VIRTUAL(ChildFrame) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL protected: //{{AFX_MSG(ChildFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; // ====================================================================== //{{AFX_INSERT_LOCATION}} // ====================================================================== #endif
d35b996e6c131d8985c298cc277ced28e7e270e8
df4a25b6271058d66faf1374fbb1b1d9563a5f7f
/dungeon-sounder/dungeon-sounder/dungeonsounder.h
1be40785309e0baf419c37c71059aa80bc8cf780
[ "MIT" ]
permissive
Talndir/dungeon-sounder
d05e132d58ca65e329512662eafe97b6559f8cbf
3c42c2c065e1e09a9bee1d2def36e342b14ef673
refs/heads/master
2021-01-01T06:36:04.582111
2017-07-27T16:32:47
2017-07-27T16:32:47
97,465,236
1
0
null
null
null
null
UTF-8
C++
false
false
594
h
dungeonsounder.h
#pragma once #include <QtWidgets/QMainWindow> #include "ui_dungeonsounder.h" #include "buttonsoundengine.h" class dungeonsounder : public QMainWindow { Q_OBJECT public: dungeonsounder(QWidget *parent = Q_NULLPTR); virtual ~dungeonsounder(); private slots: void handleSoundButton(); void stopIndividualSounds(); void stopPageSounds(); void stopAllSounds(); private: Ui::dungeonsounderClass ui; bool loadSounds(); bool loadPages(); bool loadPage(QString pageName); SoundButton* createButton(QJsonObject& buttonObject, QString pageName); ButtonSoundEngine* soundEngine; };
6aafc01721f0acedd291d911d506170d2d0d4134
ca6b7bd6516e5098310cd803168007249f3b469d
/src/applications/mne_scan/libs/scDisp/realtimemultisamplearraywidget.cpp
a817644495811882aad9c7c0e0fb3cfcfa5de58c
[ "BSD-3-Clause" ]
permissive
mne-tools/mne-cpp
125e90d2373cb30ae8207fb3e2317511356a4705
3b3c722936981e4ecc3310c3b38f60b1737c69ec
refs/heads/main
2023-08-16T16:41:05.569008
2023-08-09T15:28:39
2023-08-09T17:52:56
5,600,932
145
150
BSD-3-Clause
2023-08-09T17:52:57
2012-08-29T13:33:22
C++
UTF-8
C++
false
false
17,071
cpp
realtimemultisamplearraywidget.cpp
//============================================================================================================= /** * @file realtimemultisamplearraywidget.cpp * @author Lars Debor <Lars.Debor@tu-ilmenau.de>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Lorenz Esch <lesch@mgh.harvard.edu> * @since 0.1.0 * @date July, 2012 * * @section LICENSE * * Copyright (C) 2012, Lars Debor, Christoph Dinh, Lorenz Esch. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Definition of the RealTimeMultiSampleArrayWidget Class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "realtimemultisamplearraywidget.h" #include <disp/viewers/filterdesignview.h> #include <disp/viewers/channelselectionview.h> #include <disp/viewers/helpers/channelinfomodel.h> #include <disp/viewers/rtfiffrawview.h> #include <disp/viewers/scalingview.h> #include <disp/viewers/projectorsview.h> #include <disp/viewers/filtersettingsview.h> #include <disp/viewers/compensatorview.h> #include <disp/viewers/spharasettingsview.h> #include <disp/viewers/fiffrawviewsettings.h> #include <disp/viewers/triggerdetectionview.h> #include <scMeas/realtimemultisamplearray.h> #include <rtprocessing/helpers/filterkernel.h> #include <fiff/fiff_info.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QAction> #include <QDate> #include <QVBoxLayout> #include <QCheckBox> #include <QDir> #include <QSettings> #include <QToolBar> #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace SCDISPLIB; using namespace SCMEASLIB; using namespace DISPLIB; using namespace RTPROCESSINGLIB; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RealTimeMultiSampleArrayWidget::RealTimeMultiSampleArrayWidget(QSharedPointer<QTime> &pTime, QWidget* parent) : MeasurementWidget(parent) , m_iMaxFilterTapSize(-1) { Q_UNUSED(pTime) qRegisterMetaType<QMap<int,QList<QPair<int,double> > > >(); } //============================================================================================================= RealTimeMultiSampleArrayWidget::~RealTimeMultiSampleArrayWidget() { QSettings settings("MNECPP"); if(m_pChannelDataView && m_pRTMSA) { settings.setValue(QString("RTMSAW/showHideBad"), m_pChannelDataView->getBadChannelHideStatus()); } } //============================================================================================================= void RealTimeMultiSampleArrayWidget::update(SCMEASLIB::Measurement::SPtr pMeasurement) { if(!m_pRTMSA) { m_pRTMSA = qSharedPointerDynamicCast<RealTimeMultiSampleArray>(pMeasurement); } if(m_pRTMSA) { if(m_pRTMSA->isChInit() && !m_pFiffInfo) { m_pFiffInfo = m_pRTMSA->info(); m_iMaxFilterTapSize = m_pRTMSA->getMultiSampleArray().first().cols(); if(!m_bDisplayWidgetsInitialized) { initDisplayControllWidgets(); } } if (!m_pRTMSA->getMultiSampleArray().isEmpty()) { //Add data to table view m_pChannelDataView->addData(m_pRTMSA->getMultiSampleArray()); } } } //============================================================================================================= void RealTimeMultiSampleArrayWidget::initDisplayControllWidgets() { if(m_pFiffInfo) { //Create table view and set layout m_pChannelDataView = new RtFiffRawView(QString("MNESCAN/RTMSAW"), this); m_pChannelDataView->hide(); QVBoxLayout *rtmsaLayout = new QVBoxLayout(this); rtmsaLayout->setContentsMargins(0,0,0,0); this->setLayout(rtmsaLayout); this->setMinimumSize(300,50); // Prepare actions QToolBar* pToolBar = new QToolBar; QAction* pActionSelectSensors = new QAction(QIcon(":/images/selectSensors.png"), tr("Show the channel selection view"),this); pActionSelectSensors->setToolTip(tr("Show the channel selection view")); connect(pActionSelectSensors, &QAction::triggered, this, &RealTimeMultiSampleArrayWidget::showSensorSelectionWidget); pActionSelectSensors->setVisible(true); pToolBar->addAction(pActionSelectSensors); m_pActionHideBad = new QAction(QIcon(":/images/hideBad.png"), tr("Toggle bad channel visibility"),this); m_pActionHideBad->setStatusTip(tr("Toggle bad channel visibility")); connect(m_pActionHideBad.data(), &QAction::triggered, this, &RealTimeMultiSampleArrayWidget::onHideBadChannels); m_pActionHideBad->setVisible(true); pToolBar->addAction(m_pActionHideBad); // Add toolbar and channel data view rtmsaLayout->addWidget(pToolBar); rtmsaLayout->addWidget(m_pChannelDataView); // Init channel view QSettings settings("MNECPP"); QString sRTMSAWName = m_pRTMSA->getName(); m_pChannelDataView->show(); m_pChannelDataView->init(m_pFiffInfo); if(settings.value(QString("RTMSAW/showHideBad"), false).toBool()) { this->onHideBadChannels(); } //Init channel selection manager m_pChannelInfoModel = ChannelInfoModel::SPtr::create(m_pFiffInfo, this); m_pChannelSelectionView = ChannelSelectionView::SPtr::create(QString("MNESCAN/RTMSAW"), this, m_pChannelInfoModel, Qt::Window); m_pChannelSelectionView->setWindowTitle(tr(QString("%1: Channel Selection Window").arg(sRTMSAWName).toUtf8())); connect(m_pChannelSelectionView.data(), &ChannelSelectionView::loadedLayoutMap, m_pChannelInfoModel.data(), &ChannelInfoModel::layoutChanged); connect(m_pChannelInfoModel.data(), &ChannelInfoModel::channelsMappedToLayout, m_pChannelSelectionView.data(), &ChannelSelectionView::setCurrentlyMappedFiffChannels); connect(m_pChannelSelectionView.data(), &ChannelSelectionView::showSelectedChannelsOnly, m_pChannelDataView.data(), &RtFiffRawView::showSelectedChannelsOnly); connect(m_pChannelDataView.data(), &RtFiffRawView::channelMarkingChanged, m_pChannelSelectionView.data(), &ChannelSelectionView::updateBadChannels); m_pChannelInfoModel->layoutChanged(m_pChannelSelectionView->getLayoutMap()); //Init control widgets QList<QWidget*> lControlWidgets; // // Quick control projectors // ProjectorsView* pProjectorsView = new ProjectorsView(QString("MNESCAN/RTMSAW")); // pProjectorsView->setObjectName("group_tab_Noise_SSP"); // lControlWidgets.append(pProjectorsView); // connect(pProjectorsView, &ProjectorsView::projSelectionChanged, // m_pChannelDataView.data(), &RtFiffRawView::updateProjection); // pProjectorsView->setProjectors(m_pFiffInfo->projs); // // Quick control compensators // CompensatorView* pCompensatorView = new CompensatorView(QString("MNESCAN/RTMSAW")); // pCompensatorView->setObjectName("group_tab_Noise_Comp"); // lControlWidgets.append(pCompensatorView); // connect(pCompensatorView, &CompensatorView::compSelectionChanged, // m_pChannelDataView.data(), &RtFiffRawView::updateCompensator); // pCompensatorView->setCompensators(m_pFiffInfo->comps); // // Quick control filter // FilterSettingsView* pFilterSettingsView = new FilterSettingsView(QString("MNESCAN/RTMSAW")); // pFilterSettingsView->setObjectName("group_tab_Noise_Filter"); // lControlWidgets.append(pFilterSettingsView); // connect(pFilterSettingsView->getFilterView().data(), &FilterDesignView::filterChannelTypeChanged, // m_pChannelDataView.data(), &RtFiffRawView::setFilterChannelType); // connect(pFilterSettingsView->getFilterView().data(), &FilterDesignView::filterChanged, // m_pChannelDataView.data(), &RtFiffRawView::setFilter); // connect(pFilterSettingsView, &FilterSettingsView::filterActivationChanged, // m_pChannelDataView.data(), &RtFiffRawView::setFilterActive); // m_pChannelDataView->setFilterActive(pFilterSettingsView->getFilterActive()); // m_pChannelDataView->setFilterChannelType(pFilterSettingsView->getFilterView()->getChannelType()); // pFilterSettingsView->getFilterView()->setWindowSize(m_iMaxFilterTapSize); // pFilterSettingsView->getFilterView()->setMaxAllowedFilterTaps(m_iMaxFilterTapSize); // pFilterSettingsView->getFilterView()->init(m_pFiffInfo->sfreq); // // Quick control SPHARA settings // SpharaSettingsView* pSpharaSettingsView = new SpharaSettingsView(); // pSpharaSettingsView->setObjectName("group_tab_Noise_SPHARA"); // lControlWidgets.append(pSpharaSettingsView); // connect(pSpharaSettingsView, &SpharaSettingsView::spharaActivationChanged, // m_pChannelDataView.data(), &RtFiffRawView::updateSpharaActivation); // connect(pSpharaSettingsView, &SpharaSettingsView::spharaOptionsChanged, // m_pChannelDataView.data(), &RtFiffRawView::updateSpharaOptions); // Quick control scaling ScalingView* pScalingView = new ScalingView(QString("MNESCAN/RTMSAW"), 0, Qt::Widget, m_pFiffInfo->get_channel_types()); pScalingView->setObjectName("group_tab_View_Scaling"); lControlWidgets.append(pScalingView); connect(pScalingView, &ScalingView::scalingChanged, m_pChannelDataView.data(), &RtFiffRawView::setScalingMap); m_pChannelDataView->setScalingMap(pScalingView->getScaleMap()); // Quick control channel data settings FiffRawViewSettings* pChannelDataSettingsView = new FiffRawViewSettings(QString("MNESCAN/RTMSAW")); pChannelDataSettingsView->setObjectName("group_tab_View_General"); lControlWidgets.append(pChannelDataSettingsView); connect(pChannelDataSettingsView, &FiffRawViewSettings::signalColorChanged, m_pChannelDataView.data(), &RtFiffRawView::setSignalColor); connect(pChannelDataSettingsView, &FiffRawViewSettings::backgroundColorChanged, m_pChannelDataView.data(), &RtFiffRawView::setBackgroundColor); connect(pChannelDataSettingsView, &FiffRawViewSettings::zoomChanged, m_pChannelDataView.data(), &RtFiffRawView::setZoom); connect(pChannelDataSettingsView, &FiffRawViewSettings::timeWindowChanged, m_pChannelDataView.data(), &RtFiffRawView::setWindowSize); connect(pChannelDataSettingsView, &FiffRawViewSettings::distanceTimeSpacerChanged, m_pChannelDataView.data(), &RtFiffRawView::setDistanceTimeSpacer); connect(pChannelDataSettingsView, &FiffRawViewSettings::makeScreenshot, this, &RealTimeMultiSampleArrayWidget::onMakeScreenshot); m_pChannelDataView->setZoom(pChannelDataSettingsView->getZoom()); m_pChannelDataView->setWindowSize(pChannelDataSettingsView->getWindowSize()); m_pChannelDataView->setDistanceTimeSpacer(pChannelDataSettingsView->getDistanceTimeSpacer()); m_pChannelDataView->setBackgroundColor(pChannelDataSettingsView->getBackgroundColor()); m_pChannelDataView->setSignalColor(pChannelDataSettingsView->getSignalColor()); // Quick control trigger detection settings TriggerDetectionView* pTriggerDetectionView = new TriggerDetectionView(QString("MNESCAN/RTMSAW")); pTriggerDetectionView->setObjectName("group_tab_View_Triggers"); lControlWidgets.append(pTriggerDetectionView); connect(pTriggerDetectionView, &TriggerDetectionView::triggerInfoChanged, m_pChannelDataView.data(), &RtFiffRawView::triggerInfoChanged); connect(pTriggerDetectionView, &TriggerDetectionView::resetTriggerCounter, m_pChannelDataView.data(), &RtFiffRawView::resetTriggerCounter); connect(m_pChannelDataView.data(), &RtFiffRawView::triggerDetected, pTriggerDetectionView, &TriggerDetectionView::setNumberDetectedTriggersAndTypes); pTriggerDetectionView->init(m_pFiffInfo); emit displayControlWidgetsChanged(lControlWidgets, sRTMSAWName); //Initialized m_bDisplayWidgetsInitialized = true; } } //============================================================================================================= void RealTimeMultiSampleArrayWidget::showSensorSelectionWidget() { if(m_pChannelSelectionView->isActiveWindow()) { m_pChannelSelectionView->hide(); } else { m_pChannelSelectionView->activateWindow(); m_pChannelSelectionView->show(); } } //============================================================================================================= void RealTimeMultiSampleArrayWidget::onMakeScreenshot(const QString& imageType) { // Create file name QString sDate = QDate::currentDate().toString("yyyy_MM_dd"); QString sTime = QTime::currentTime().toString("hh_mm_ss"); if(!QDir("./Screenshots").exists()) { QDir().mkdir("./Screenshots"); } QString fileName; if(imageType.contains("SVG")) { fileName = QString("./Screenshots/%1-%2-DataView.svg").arg(sDate).arg(sTime); } else if(imageType.contains("PNG")) { fileName = QString("./Screenshots/%1-%2-DataView.png").arg(sDate).arg(sTime); } m_pChannelDataView->takeScreenshot(fileName); } //============================================================================================================= void RealTimeMultiSampleArrayWidget::onHideBadChannels() { m_pChannelDataView->hideBadChannels(); if(m_pActionHideBad->toolTip() == "Show all bad channels") { m_pActionHideBad->setIcon(QIcon(":/images/hideBad.png")); m_pActionHideBad->setToolTip("Hide all bad channels"); m_pActionHideBad->setStatusTip(tr("Hide all bad channels")); } else { m_pActionHideBad->setIcon(QIcon(":/images/showBad.png")); m_pActionHideBad->setToolTip("Show all bad channels"); m_pActionHideBad->setStatusTip(tr("Show all bad channels")); } } //============================================================================================================= void RealTimeMultiSampleArrayWidget::updateOpenGLViewport() { if(m_pChannelDataView) { m_pChannelDataView->updateOpenGLViewport(); } }
e79adb11160a8ccbd3dc3295e9f2187b4d377c71
19912a564e911ff015ac365ebd57428bad54eeed
/projects/SkyWays/Classes/TileObject.cpp
68c829e24f280afebdd282f38859f670bed7c1b3
[ "MIT" ]
permissive
chiguire/skyways
1df66bac8720882ba81113714db5c0c60ac8a5bc
cdabba86d2155573ce25bbc4a21099c224fb27d7
refs/heads/master
2021-01-13T13:04:19.613776
2013-11-14T11:58:06
2013-11-14T11:58:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
146
cpp
TileObject.cpp
/* * TileObject.cpp * * Author: Ciro */ #include "TileObject.h" TileObject::TileObject() : body(NULL) { } TileObject::~TileObject() { }
6f7fad73c7fb2b8de581dea79f2b915cc45c0309
1763d06f5671d725a54cdacc34a9e956a8bdbc69
/Core/Source/IceSceneManager.cpp
e87dc70a20ccf86dfedcde2bf663b4b21480c39c
[]
no_license
JohannKollmann/blackstar-engine
09697e6ca9834730302defa41412a070a9492461
25daf59562d31479e471c66eb787dd901e0a479d
refs/heads/master
2016-09-06T11:15:01.776148
2013-04-23T13:26:40
2013-04-23T13:26:40
42,470,412
2
0
null
null
null
null
UTF-8
C++
false
false
28,685
cpp
IceSceneManager.cpp
#include "IceSceneManager.h" #include "IceMain.h" #include "LoadSave.h" #include "IceWeatherController.h" #include "Saveable.h" #include "shellapi.h" #include "IceScriptSystem.h" #include "IceAIManager.h" #include "IceProcessNode.h" #include "IceProcessNodeQueue.h" #include "IceProcessNodeManager.h" #include "IceScriptedProcess.h" #include "IceMaterialTable.h" #include "IceCameraController.h" #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include "IceUtils.h" #include "mmsystem.h" #include "Caelum.h" namespace Ice { SceneManager::SceneManager() { mWeatherController = 0; mIndoorRendering = false; mClockEnabled = true; mNextID = 0; mDayTime = 0.0f; mMaxDayTime = 86400.0f; mTimeScale = 64.0f; mShowEditorVisuals = false; mClearingScene = false; JoinNewsgroup(GlobalMessageIDs::UPDATE_PER_FRAME); } SceneManager::~SceneManager() { } unsigned int SceneManager::RequestID() { return mNextID++; } Ogre::String SceneManager::RequestIDStr() { return Ogre::StringConverter::toString(RequestID()); } void SceneManager::RegisterPlayer(GameObjectPtr player) { mPlayer = player; } void SceneManager::ShowEditorMeshes(bool show) { mShowEditorVisuals = show; for (auto i = mGameObjects.begin(); i != mGameObjects.end(); i++) { i->second->ShowEditorVisuals(show); } } WeatherController* SceneManager::GetWeatherController() { return mWeatherController; } void SceneManager::Init() { Reset(); Main::Instance().GetOgreSceneMgr()->createStaticGeometry("StaticGeometry"); } void SceneManager::PostInit() { } void SceneManager::ClearGameObjects() { mClearingScene = true; mGameObjects.clear(); mClearingScene = false; } void SceneManager::Reset() { AIManager::Instance().GetNavigationMesh()->Reset(); ClearGameObjects(); SetToOutdoor(); } void SceneManager::Shutdown() { SetToIndoor(); AIManager::Instance().Shutdown(); } void SceneManager::SetToIndoor() { if (mWeatherController) { ICE_DELETE mWeatherController; mWeatherController = NULL; } mIndoorRendering = true; } void SceneManager::SetToOutdoor() { /*Main::Instance().GetOgreSceneMgr()->setSkyBox(true, "Skybox/LostValley"); Main::Instance().GetOgreSceneMgr()->getSkyBoxNode()->getAttachedObject(0)->setVisibilityFlags( Ice::VisibilityFlags::V_SKY); Ogre::Light *Light = Main::Instance().GetOgreSceneMgr()->createLight("Light0"); Light->setType(Ogre::Light::LT_DIRECTIONAL); Light->setDirection(0, -1, 0.9); Light->setDiffuseColour(2, 2, 2); Light->setSpecularColour(Ogre::ColourValue(1, 0.9, 0.6));*/ if (!mWeatherController) mWeatherController = ICE_NEW WeatherController(); SetTimeScale(mTimeScale); SetTime(11, 0); mIndoorRendering = false; if (!mWeatherController->GetCaelumSystem()->getSun()->getForceDisable()) AIManager::Instance().RegisterLight(mWeatherController->GetCaelumSystem()->getSun()->getMainLight()); else AIManager::Instance().RegisterLight(mWeatherController->GetCaelumSystem()->getMoon()->getMainLight()); } GameObjectPtr SceneManager::AddLevelMesh(Ogre::String meshname) { Ice::GameObjectPtr object = CreateGameObject(); //object->SetGlobalScale(Ogre::Vector3(0.1, 0.1, 0.1)); //test object->AddComponent(Ice::GOComponentPtr(new Ice::GOCMeshRenderable(meshname, true))); object->AddComponent(Ice::GOComponentPtr(new Ice::GOCStaticBody(meshname))); object->SetSelectable(false); AIManager::Instance().GetNavigationMesh()->AddOgreMesh(object->GetComponent<GOCMeshRenderable>()->GetEntity()->getMesh()); return object; } void SceneManager::RegisterGameObject(GameObjectPtr object) { mGameObjects.insert(std::make_pair<int, GameObjectPtr>(object->GetID(), object)); } void SceneManager::CreateNavigationMesh() { AIManager::Instance().GetNavigationMesh()->Reset(); ITERATE(i, mGameObjects) { if (i->second->GetComponent<GOCMeshRenderable>() && i->second->GetComponent<GOCStaticBody>()) AIManager::Instance().GetNavigationMesh()->AddOgreMesh(i->second->GetComponent<GOCMeshRenderable>()->GetEntity()->getMesh()); } AIManager::Instance().GetNavigationMesh()->Update(); } void SceneManager::LoadLevel(Ogre::String levelfile, bool load_dynamic) { Msg msg; msg.typeID = GlobalMessageIDs::LOADLEVEL_BEGIN; MessageSystem::Instance().MulticastMessage(msg, true); ClearGameObjects(); LoadSave::LoadSystem *ls = LoadSave::LoadSave::Instance().LoadFile(levelfile); std::shared_ptr<DataMap> levelparams = ls->LoadTypedObject<DataMap>(); SetParameters(levelparams.get()); std::vector<GameObjectPtr> objects; ls->LoadAtom("vector<GameObjectPtr>", &objects); //objects call RegisterObject ls->CloseFile(); delete ls; CreateNavigationMesh(); msg.typeID = GlobalMessageIDs::LOADLEVEL_END; MessageSystem::Instance().MulticastMessage(msg, true); } void SceneManager::SaveLevel(Ogre::String levelfile) { Msg msg; msg.typeID = GlobalMessageIDs::SAVELEVEL_BEGIN; MessageSystem::Instance().MulticastMessage(msg, true); ShowEditorMeshes(false); LoadSave::SaveSystem *ss=LoadSave::LoadSave::Instance().CreateSaveFile(levelfile, levelfile + ".xml"); DataMap map; GetParameters(&map); ss->SaveObject(&map, "LevelParams"); std::vector<GameObjectPtr> objects; for (auto i = mGameObjects.begin(); i != mGameObjects.end(); i++) objects.push_back(i->second); ss->SaveAtom("vector<GameObjectPtr>", &objects, "Objects"); //ss->SaveObject(AIManager::Instance().GetNavigationMesh(), "WayMesh"); ss->CloseFiles(); ICE_DELETE ss; msg.typeID = GlobalMessageIDs::SAVELEVEL_END; MessageSystem::Instance().MulticastMessage(msg, true); } void SceneManager::SetParameters(DataMap *parameters) { SetWeatherParameters(parameters); mStartupScriptName = parameters->GetValue<Ogre::String>("Startup Script", ""); if (mStartupScriptName != "") ScriptSystem::GetInstance().CreateInstance(mStartupScriptName); } void SceneManager::GetParameters(DataMap *parameters) { parameters->AddOgreString("Startup Script", mStartupScriptName); GetWeatherParameters(parameters); } void SceneManager::SetWeatherParameters(DataMap *parameters) { DataMap currParams; GetWeatherParameters(&currParams); bool indoor = parameters->GetBool("Indoor", currParams.GetBool("Indoor")); if (indoor) SetToIndoor(); else { SetToOutdoor(); mWeatherController->GetCaelumSystem()->getSun()->setAmbientMultiplier(parameters->GetOgreCol("AmbientLight", currParams.GetOgreCol("AmbientLight"))); mWeatherController->GetCaelumSystem()->getSun()->setDiffuseMultiplier(parameters->GetOgreCol("Sun_DiffuseLight", currParams.GetOgreCol("Sun_DiffuseLight"))); mWeatherController->GetCaelumSystem()->getSun()->setSpecularMultiplier(parameters->GetOgreCol("Sun_SpecularLight", currParams.GetOgreCol("Sun_SpecularLight"))); mWeatherController->Update(0); } Ogre::GpuSharedParametersPtr hdrParams = Ogre::GpuProgramManager::getSingleton().getSharedParameters("HDRParams"); Ogre::ColourValue col = parameters->GetOgreCol("Luminence_Factor", currParams.GetOgreCol("Luminence_Factor")); col.a = 0; hdrParams->setNamedConstant("Luminence_Factor", col); hdrParams->setNamedConstant("Tonemap_White", parameters->GetFloat("Tonemap_White")); col = parameters->GetOgreCol("Brightpass_Threshold", currParams.GetOgreCol("Brightpass_Threshold")); col.a = 0; hdrParams->setNamedConstant("Brightpass_Threshold", col); col = parameters->GetOgreCol("BrightpassAmbient_Threshold", currParams.GetOgreCol("BrightpassAmbient_Threshold")); col.a = 0; hdrParams->setNamedConstant("BrightpassAmbient_Threshold", col); hdrParams->setNamedConstant("BloomAmbient_GlareScale", parameters->GetValue<float>("BloomAmbient_GlareScale", 0.5f)); hdrParams->setNamedConstant("BloomAmbient_GlarePower", parameters->GetValue<float>("BloomAmbient_GlarePower", 0.5f)); hdrParams->setNamedConstant("Bloom_GlareScale", parameters->GetValue<float>("Bloom_GlareScale", parameters->GetFloat("Bloom_GlareScale"))); hdrParams->setNamedConstant("Bloom_GlarePower", parameters->GetValue<float>("Bloom_GlarePower", parameters->GetFloat("Bloom_GlarePower"))); hdrParams->setNamedConstant("Bloom_StarScale", parameters->GetValue<float>("Bloom_StarScale", parameters->GetFloat("Bloom_StarScale"))); hdrParams->setNamedConstant("Bloom_StarPower", parameters->GetValue<float>("Bloom_StarPower", parameters->GetFloat("Bloom_StarPower"))); hdrParams->setNamedConstant("LinearTonemap_KeyLumScale", parameters->GetFloat("LinearTonemap_KeyLumScale", parameters->GetFloat("LinearTonemap_KeyLumScale"))); hdrParams->setNamedConstant("LinearTonemap_KeyMax", parameters->GetFloat("LinearTonemap_KeyMax", parameters->GetFloat("LinearTonemap_KeyMax"))); hdrParams->setNamedConstant("LinearTonemap_KeyMaxOffset", parameters->GetFloat("LinearTonemap_KeyMaxOffset", parameters->GetFloat("LinearTonemap_KeyMaxOffset"))); hdrParams->setNamedConstant("LinearTonemap_KeyMin", parameters->GetFloat("LinearTonemap_KeyMin", parameters->GetFloat("LinearTonemap_KeyMin"))); hdrParams->setNamedConstant("LightAdaption_Exponent", parameters->GetValue<float>("LightAdaption_Exponent", parameters->GetFloat("LightAdaption_Exponent"))); hdrParams->setNamedConstant("LightAdaption_Factor", parameters->GetValue<float>("LightAdaption_Factor", parameters->GetFloat("LightAdaption_Factor"))); hdrParams->setNamedConstant("ShadowAdaption_Exponent", parameters->GetValue<float>("ShadowAdaption_Exponent", parameters->GetFloat("ShadowAdaption_Exponent"))); hdrParams->setNamedConstant("ShadowAdaption_Factor", parameters->GetValue<float>("ShadowAdaption_Factor", parameters->GetFloat("ShadowAdaption_Factor"))); } void SceneManager::GetWeatherParameters(DataMap *parameters) { parameters->AddBool("Indoor", mIndoorRendering); if (mWeatherController) { parameters->AddOgreCol("AmbientLight", mWeatherController->GetCaelumSystem()->getSun()->getAmbientMultiplier()); parameters->AddOgreCol("Sun_DiffuseLight", mWeatherController->GetCaelumSystem()->getSun()->getDiffuseMultiplier()); parameters->AddOgreCol("Sun_SpecularLight", mWeatherController->GetCaelumSystem()->getSun()->getSpecularMultiplier()); } Ogre::GpuSharedParametersPtr hdrParams = Ogre::GpuProgramManager::getSingleton().getSharedParameters("HDRParams"); float *buf = hdrParams->getFloatPointer(0); parameters->AddOgreVec3("Luminence_Factor", Ogre::Vector3(buf[0], buf[1], buf[2])); parameters->AddFloat("Tonemap_White", buf[4]); //skip buf[3] (float4) parameters->AddOgreVec3("Brightpass_Threshold", Ogre::Vector3(buf[5], buf[6], buf[7])); parameters->AddOgreVec3("BrightpassAmbient_Threshold", Ogre::Vector3(buf[9], buf[10], buf[11])); parameters->AddFloat("BloomAmbient_GlareScale", buf[13]); parameters->AddFloat("BloomAmbient_GlarePower", buf[14]); parameters->AddFloat("Bloom_GlareScale", buf[15]); parameters->AddFloat("Bloom_GlarePower", buf[16]); parameters->AddFloat("Bloom_StarScale", buf[17]); parameters->AddFloat("Bloom_StarPower", buf[18]); parameters->AddFloat("LinearTonemap_KeyLumScale", buf[19]); parameters->AddFloat("LinearTonemap_KeyMax", buf[20]); parameters->AddFloat("LinearTonemap_KeyMaxOffset", buf[21]); parameters->AddFloat("LinearTonemap_KeyMin", buf[22]); parameters->AddFloat("LightAdaption_Exponent", buf[23]); parameters->AddFloat("LightAdaption_Factor", buf[24]); parameters->AddFloat("ShadowAdaption_Exponent", buf[25]); parameters->AddFloat("ShadowAdaption_Factor", buf[26]); } std::unordered_map<int, GameObjectPtr>& SceneManager::GetGameObjects() { return mGameObjects; } void SceneManager::RemoveGameObject(int objectID) { auto i = mGameObjects.find(objectID); if (i != mGameObjects.end()) mGameObjects.erase(i); } GameObjectPtr SceneManager::CreateGameObject() { GameObjectPtr object = std::make_shared<GameObject>(); object->SetWeakThis(std::weak_ptr<GameObject>(object)); mGameObjects.insert(std::make_pair<int, GameObjectPtr>(object->GetID(), object)); return object; } GameObjectPtr SceneManager::GetObjectByInternID(int id) { auto i = mGameObjects.find(id); if (i != mGameObjects.end()) return i->second; return GameObjectPtr(); } std::vector<ScriptParam> SceneManager::Lua_LoadLevel(Script& caller, std::vector<ScriptParam> vParams) { std::vector<ScriptParam> out; if (vParams.size() == 1) { if (vParams[0].getType() == ScriptParam::PARM_TYPE_STRING) { SceneManager::Instance().LoadLevel(vParams[0].getString()); } } return out; } std::vector<ScriptParam> SceneManager::Lua_SaveLevel(Script& caller, std::vector<ScriptParam> vParams) { std::vector<ScriptParam> out; if (vParams.size() == 1) { if (vParams[0].getType() == ScriptParam::PARM_TYPE_STRING) { SceneManager::Instance().SaveLevel(vParams[0].getString()); } } return out; } std::vector<ScriptParam> SceneManager::Lua_LogMessage(Script& caller, std::vector<ScriptParam> vParams) { Ogre::String msg = Lua_ConcatToString(caller, vParams)[0].getString(); Log::Instance().LogMessage(msg); return std::vector<ScriptParam>(); } std::vector<ScriptParam> SceneManager::Lua_ConcatToString(Script& caller, std::vector<ScriptParam> vParams) { Ogre::String str = ""; for(unsigned int iArg=0; iArg<vParams.size(); iArg++) { switch(vParams[iArg].getType()) { case ScriptParam::PARM_TYPE_STRING: str = str + vParams[iArg].getString().c_str(); break; case ScriptParam::PARM_TYPE_BOOL: str = str + Ogre::StringConverter::toString(vParams[iArg].getBool()); break; case ScriptParam::PARM_TYPE_FLOAT: { float val = static_cast<float>(vParams[iArg].getFloat()); str = str + Ogre::StringConverter::toString(val); break; } case ScriptParam::PARM_TYPE_INT: str = str + Ogre::StringConverter::toString(vParams[iArg].getInt()); break; case ScriptParam::PARM_TYPE_TABLE: { str = str + "{ "; std::map<ScriptParam, ScriptParam> mTable=vParams[iArg].getTable(); for(std::map<ScriptParam, ScriptParam>::const_iterator it=mTable.begin(); it!=mTable.end();) { str = str + "["; //stl-spam... str = str + Lua_ConcatToString(caller, std::vector<ScriptParam>(1, it->first))[0].getString().c_str(); str = str + "]="; str = str + Lua_ConcatToString(caller, std::vector<ScriptParam>(1, it->second))[0].getString().c_str(); it++; if(it!=mTable.end()) str = str + ", "; } str = str + " }"; break; } default: break; } } SCRIPT_RETURNVALUE(str) } std::vector<ScriptParam> SceneManager::Lua_GetRandomNumber(Script& caller, std::vector<ScriptParam> vParams) { float random = 0; auto err = Utils::TestParameters(vParams, "float float"); if (err == "") { random = Ogre::Math::RangeRandom(vParams[0].getFloat(), vParams[1].getFloat()); SCRIPT_RETURNVALUE(random) } else SCRIPT_RETURNERROR(err) } std::vector<ScriptParam> SceneManager::Lua_InsertMesh(Script& caller, std::vector<ScriptParam> vParams) { std::vector<ScriptParam> out; if (vParams.size() != 3) return out; if (vParams[0].getType() != ScriptParam::PARM_TYPE_STRING) return out; Ogre::String mesh = vParams[0].getString().c_str(); if (vParams[1].getType() != ScriptParam::PARM_TYPE_BOOL) return out; bool shadows = vParams[1].getBool(); if (vParams[2].getType() != ScriptParam::PARM_TYPE_FLOAT) return out; int collision = (int)vParams[2].getFloat(); GameObjectPtr object = Instance().CreateGameObject(); object->AddComponent(GOComponentPtr(new GOCMeshRenderable(mesh, shadows))); if (collision == -1) { object->AddComponent(GOComponentPtr(new GOCStaticBody(mesh))); } else if (collision >= 0 && collision <= 3) { object->AddComponent(GOComponentPtr(new GOCRigidBody(mesh, 10, collision))); } out.push_back(ScriptParam(object->GetID())); return out; } void SceneManager::ReceiveMessage(Msg &msg) { if (msg.typeID == GlobalMessageIDs::UPDATE_PER_FRAME) { float time = msg.params.GetFloat("TIME"); if (mClockEnabled) { mDayTime += (time*mTimeScale); if (mDayTime >= mMaxDayTime) mDayTime = 0.0f; if (mWeatherController) mWeatherController->Update(time); } } } void SceneManager::EnableClock(bool enable) { mClockEnabled = enable; Msg msg; msg.typeID = GlobalMessageIDs::ENABLE_GAME_CLOCK; msg.params.AddBool("enable", enable); MessageSystem::Instance().MulticastMessage(msg); } void SceneManager::SetTimeScale(float scale) { mTimeScale = scale; if (mWeatherController) mWeatherController->SetSpeedFactor(scale); } void SceneManager::SetTime(int hours, int minutes) { mDayTime = (float)(hours * 3600.0f + minutes * 60.0f); if (mWeatherController) mWeatherController->SetTime(hours, minutes); } int SceneManager::GetHour() { return (int)(mDayTime / 3600); } int SceneManager::GetMinutes() { int hour = GetHour(); float fhour = 3600.0f * hour; float dif = mDayTime - fhour; return dif / 60; } Ogre::TexturePtr SceneManager::CreatePreviewRender(Ogre::SceneNode *node, Ogre::String name, float width, float height) { Ogre::Camera *camera = node->getCreator()->createCamera(name + "_Cam"); camera->setNearClipDistance(0.1f); camera->setFarClipDistance(0); camera->setPosition(mNextPreviewPos); camera->setDirection(0,0,1); camera->setAspectRatio(width / height); Ogre::Vector3 node_dimensions = Ogre::Vector3(1,1,1); Ogre::Vector3 center = Ogre::Vector3(0,0,0); if (node->getAttachedObject(0)) { if (!node->getAttachedObject(0)->getBoundingBox().isNull()) { node_dimensions = node->getAttachedObject(0)->getBoundingBox().getSize(); center = node->getAttachedObject(0)->getBoundingBox().getCenter(); } } float max = node_dimensions.x > node_dimensions.y ? node_dimensions.x : node_dimensions.y; max = max > node_dimensions.z ? max : node_dimensions.z; float scale_factor = 1.0f / max; float z_offset = (1.0f - (node_dimensions.z * scale_factor)) * 0.5f; node->scale(scale_factor, scale_factor, scale_factor); node->setPosition(mNextPreviewPos + Ogre::Vector3(0, 0, 1.9f-z_offset) + (scale_factor * center * -1.0f)); mNextPreviewPos.x += node_dimensions.x * 2; Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(name + "_Tex", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, width, height, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); Ogre::RenderTexture *renderTexture = texture->getBuffer()->getRenderTarget(); renderTexture->addViewport(camera); renderTexture->setAutoUpdated(true); renderTexture->getViewport(0)->setClearEveryFrame(true); renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black); renderTexture->getViewport(0)->setOverlaysEnabled(false); if (width == 256 && height == 256) Ogre::CompositorManager::getSingleton().addCompositor(renderTexture->getViewport(0), "AntiAlias_256")->setEnabled(true); /*Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(name + "_Mat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); Ogre::Technique *technique = material->createTechnique(); technique->createPass(); material->getTechnique(0)->getPass(0)->setLightingEnabled(false); material->getTechnique(0)->getPass(0)->createTextureUnitState(name + "_Tex");*/ return texture; } void SceneManager::DestroyPreviewRender(Ogre::String name) { if (Ogre::TextureManager::getSingleton().resourceExists(name + "_Tex")) { Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(name + "_Tex"); Ogre::Viewport *vp = texture->getBuffer()->getRenderTarget()->getViewport(0); vp->getCamera()->getSceneManager()->destroyCamera(vp->getCamera()); texture->getBuffer()->getRenderTarget()->removeAllViewports(); Ogre::TextureManager::getSingleton().remove(name + "_Tex"); } //if (Ogre::MaterialManager::getSingleton().resourceExists(name + "_Mat")) Ogre::MaterialManager::getSingleton().remove(name + "_Mat"); } std::vector<ScriptParam> SceneManager::Lua_GetThis(Script& caller, std::vector<ScriptParam> vParams) { std::vector<ScriptParam> out; int id = -1; ScriptUser *scriptUser = ScriptSystem::GetInstance().GetScriptableObject(caller.GetID()); if (!scriptUser) IceWarning("No object is associated with the calling script.") else id = scriptUser->GetThisID(); out.push_back(ScriptParam(id)); return out; } std::vector<ScriptParam> SceneManager::Lua_GetObjectByName(Script& caller, std::vector<ScriptParam> vParams) { int returnID = -1; auto err = Utils::TestParameters(vParams, "string"); if (err == "") { Ogre::String name = vParams[0].getString(); for (auto i = Instance().mGameObjects.begin(); i != Instance().mGameObjects.end(); i++) { if (i->second->GetName() == name) { returnID = i->first; break; } } } else SCRIPT_RETURNERROR(err) std::vector<ScriptParam> out; out.push_back(returnID); return out; } std::vector<ScriptParam> SceneManager::Lua_GetFocusObject(Script& caller, std::vector<ScriptParam> params) { float maxDist = 5; int id = -1; Ogre::Vector3 origin = Main::Instance().GetCamera()->getDerivedPosition(); if (SceneManager::Instance().GetPlayer()) origin = SceneManager::Instance().GetPlayer()->GetGlobalPosition() + Ogre::Vector3(0, 2, 0); Ogre::Vector3 dir = Main::Instance().GetCamera()->getDerivedDirection().normalisedCopy(); PxRaycastHit buffer[10]; bool blockingHit; PxU32 numHits = Main::Instance().GetPhysXScene()->getPxScene()->raycastMultiple(OgrePhysX::toPx(origin), OgrePhysX::toPx(dir), maxDist, PxSceneQueryFlag::eNORMAL, buffer, 10, blockingHit); for (unsigned int i = 0; i < numHits; ++i) { if (buffer[i].shape->getActor().userData) { GameObject *object = (GameObject*)buffer[i].shape->getActor().userData; if (object == SceneManager::Instance().GetPlayer().get()) continue; id = object->GetID(); break; } } std::vector<ScriptParam> returner; returner.push_back(ScriptParam(id)); return returner; } std::vector<ScriptParam> SceneManager::Lua_CreateMaterialProfile(Script& caller, std::vector<ScriptParam> vParams) { //CreateMaterialProfile(string name, float restitution = 0.1f, float staticFriction = 0.5f, float dynamicFriction = 0.5f std::vector<ScriptParam> ret; std::vector<Ice::ScriptParam> vRef; vRef.push_back(ScriptParam(std::string())); //Name std::string strErrString=Ice::Utils::TestParameters(vParams, vRef, true); if (strErrString != "") { Utils::LogParameterErrors(caller, strErrString); ret.push_back(ScriptParam(0)); return ret; } float staticFriction = 0.5f; float dynamicFriction = 0.5f; float restitution = 0.5f; if(vParams.size()!=1) { vRef.push_back(ScriptParam(1.0)); //staticFriction vRef.push_back(ScriptParam(1.0)); //dynamicFriction vRef.push_back(ScriptParam(1.0)); //restitution strErrString=Ice::Utils::TestParameters(vParams, vRef); if (strErrString != "") { SCRIPT_RETURNERROR(strErrString) } staticFriction = vParams[1].getFloat(); staticFriction = vParams[2].getFloat(); staticFriction = vParams[3].getFloat(); } MaterialTable::Instance().AddMaterialProfile(vParams[0].getString().c_str(), OgrePhysX::getPxPhysics()->createMaterial(staticFriction, dynamicFriction, restitution)); SCRIPT_RETURN() } std::vector<ScriptParam> SceneManager::Lua_Play3DSound(Script& caller, std::vector<ScriptParam> vParams) { std::vector<Ice::ScriptParam> vRef; vRef.push_back(ScriptParam(0.0f)); //x pos vRef.push_back(ScriptParam(0.0f)); //y pos vRef.push_back(ScriptParam(0.0f)); //z pos vRef.push_back(ScriptParam(std::string())); //Soundfile vRef.push_back(ScriptParam(0.0f)); //Range vRef.push_back(ScriptParam(0.0f)); //Loudness std::string strErrString=Ice::Utils::TestParameters(vParams, vRef); if (strErrString != "") { Utils::LogParameterErrors(caller, strErrString); return std::vector<ScriptParam>(); } Ogre::Vector3 position; position.x = vParams[0].getFloat(); position.y = vParams[1].getFloat(); position.z = vParams[2].getFloat(); std::string soundFile = vParams[3].getString(); float range = vParams[4].getFloat(); float loudness = vParams[5].getFloat(); //if (loudness > 1) loudness = 1; if (Ogre::ResourceGroupManager::getSingleton().resourceExists("General", soundFile)) { int id = Ice::SceneManager::Instance().RequestID(); Ogre::SceneNode *node = Ice::Main::Instance().GetOgreSceneMgr()->getRootSceneNode()->createChildSceneNode(position); OgreOggSound::OgreOggISound *sound = Ice::Main::Instance().GetSoundManager()->createSound(Ogre::StringConverter::toString(id), soundFile, true, false); sound->setReferenceDistance(range/2); sound->setMaxDistance(range); sound->setVolume(loudness); sound->play(); sound->setListener(&(Instance().mOggListener)); node->attachObject(sound); AIManager::Instance().NotifySound(soundFile, position, range, loudness); } return std::vector<ScriptParam>(); } void SceneManager::OggListener::soundStopped(OgreOggSound::OgreOggISound* sound) { Main::Instance().GetOgreSceneMgr()->destroySceneNode(sound->getParentSceneNode()); Main::Instance().GetSoundManager()->destroySound(sound); } SceneManager::OggCamSync::OggCamSync() { JoinNewsgroup(GlobalMessageIDs::UPDATE_PER_FRAME); } void SceneManager::OggCamSync::ReceiveMessage(Msg &msg) { Main::Instance().GetSoundManager()->getListener()->setPosition(Main::Instance().GetCamera()->getDerivedPosition()); Main::Instance().GetSoundManager()->getListener()->setOrientation(Main::Instance().GetCamera()->getDerivedOrientation()); } std::vector<ScriptParam> SceneManager::Lua_CreateGameObject(Script& caller, std::vector<ScriptParam> vParams) { GameObjectPtr object = Instance().CreateGameObject(); SCRIPT_RETURNVALUE(object->GetID()); } std::vector<ScriptParam> SceneManager::Lua_GetGameTimeHour(Script& caller, std::vector<ScriptParam> vParams) { std::vector<ScriptParam> out; out.push_back(ScriptParam(Instance().GetHour())); return out; } std::vector<ScriptParam> SceneManager::Lua_GetGameTimeMinutes(Script& caller, std::vector<ScriptParam> vParams) { std::vector<ScriptParam> out; out.push_back(ScriptParam(Instance().GetMinutes())); return out; } std::vector<ScriptParam> SceneManager::Lua_SetGameTime(Script& caller, std::vector<ScriptParam> vParams) { auto err = Utils::TestParameters(vParams, "int int"); if (err == "") { int hour = vParams[0].getInt(); int minutes = vParams[1].getInt(); Instance().SetTime(hour, minutes); } else SCRIPT_RETURNERROR(err) SCRIPT_RETURN() } std::vector<ScriptParam> SceneManager::Lua_SetGameTimeScale(Script& caller, std::vector<ScriptParam> vParams) { auto err = Utils::TestParameters(vParams, "float"); if (err == "") { float scale = vParams[0].getFloat(); Instance().SetTimeScale(scale); } SCRIPT_RETURN() } std::vector<ScriptParam> SceneManager::Lua_GetPlayer(Script& caller, std::vector<ScriptParam> params) { int errout = -1; if (!Instance().GetPlayer()) SCRIPT_RETURNVALUE(errout) else SCRIPT_RETURNVALUE(Instance().GetPlayer()->GetID()) } void SceneManager::AcquireCamera(CameraController *cam) { if (mCameraStack.size() > 0) mCameraStack.top()->DetachCamera(); mCameraStack.push(cam); cam->AttachCamera(Main::Instance().GetCamera()); } void SceneManager::TerminateCurrentCameraController() { IceAssert((mCameraStack.size() > 0)); mCameraStack.top()->DetachCamera(); mCameraStack.pop(); if (mCameraStack.size() > 0) mCameraStack.top()->AttachCamera(Main::Instance().GetCamera()); } SceneManager& SceneManager::Instance() { static SceneManager TheOneAndOnly; return TheOneAndOnly; }; }
5a90098e70f38041205484242972035e5620fbef
7d7eef464406ad65ebaa924ffd3258ae3a09c171
/include/bad/storage/store_iterator.hh
3a4992352daecd6403604cd40c4ea4dce807bd17
[]
no_license
ekmett/bad
5d70b3715fa756789c699341235ebbc1a6deaf7d
978b8056ffafc992fd1b7300ccf7bd1219cd3a20
refs/heads/main
2023-03-29T04:06:43.432870
2021-03-18T20:35:35
2021-03-18T20:35:35
330,171,266
16
2
null
null
null
null
UTF-8
C++
false
false
8,936
hh
store_iterator.hh
#ifndef BAD_STORAGE_STORE_ITERATOR_HH #define BAD_STORAGE_STORE_ITERATOR_HH #include "bad/common.hh" /// \file /// \author Edward Kmett /// \brief const_store_expr_iterator and store_expr_iterator implementations namespace bad::storage::detail { template <size_t d, size_t s, class T, class plane> struct const_store_iterator final { using value_type = plane const; using difference_type = ptrdiff_t; using pointer = value_type *; using reference = value_type &; using iterator_category = std::random_access_iterator_tag; BAD(hd,inline,noalias) constexpr explicit const_store_iterator(T const * p = nullptr, ptrdiff_t i = 0) noexcept : p(p), i(i) {} BAD(hd,inline,noalias) constexpr const_store_iterator(const_store_iterator const & rhs) noexcept : p(rhs.p), i(rhs.i) {} BAD(hd,inline,noalias) constexpr const_store_iterator(const_store_iterator && rhs) noexcept : p(std::move(rhs.p)), i(std::move(rhs.i)) {} BAD(reinitializes,hd,inline,noalias) const_store_iterator & operator =( const_store_iterator rhs ) noexcept { p = rhs.p; i = rhs.i; return *this; } BAD(reinitializes,hd,inline,noalias) const_store_iterator & operator =( const_store_iterator && rhs ) noexcept { p = std::move(rhs.p); i = std::move(rhs.i); return *this; } // default constructible, moveable T const * p; ptrdiff_t i; // NB: store_iterators are only comparable if they come from the same container BAD(hd,nodiscard,inline,pure) friend bool operator ==( const_store_iterator lhs, const_store_iterator rhs ) noexcept { return lhs.i == rhs.i; } // NB: store_iterators are only comparable if they come from the same container BAD(hd,nodiscard,inline,pure) friend bool operator !=( const_store_iterator lhs, const_store_iterator rhs ) noexcept { return lhs.i != rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator <( const_store_iterator lhs, const_store_iterator rhs ) noexcept { return lhs.i < rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator >( const_store_iterator lhs, const_store_iterator rhs ) noexcept { return lhs.i > rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator <=( const_store_iterator lhs, const_store_iterator rhs ) noexcept { return lhs.i <= rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator >=( const_store_iterator lhs, const_store_iterator rhs ) noexcept { return lhs.i >= rhs.i; } BAD(hd,inline,noalias) const_store_iterator & operator ++() noexcept { ++i; return *this; } BAD(hd,inline,noalias) const_store_iterator operator ++(int) noexcept { return { p, i++ }; } BAD(hd,inline,noalias) const_store_iterator & operator --() noexcept { --i; return *this; } BAD(hd,inline,noalias) const_store_iterator operator --(int) noexcept { return { p, i-- }; } BAD(hd,nodiscard,inline,pure) friend const_store_iterator operator +( const_store_iterator lhs, ptrdiff_t rhs ) noexcept { return { lhs.p, lhs.i + rhs }; } BAD(hd,nodiscard,inline,pure) friend const_store_iterator operator +( ptrdiff_t lhs, const_store_iterator rhs ) noexcept { return { rhs.p, rhs.i + lhs }; } BAD(hd,nodiscard,inline,pure) friend const_store_iterator operator -( const_store_iterator lhs, ptrdiff_t rhs ) noexcept { return { lhs.p, lhs.i - rhs }; } BAD(hd,nodiscard,inline,pure) friend ptrdiff_t operator -( const_store_iterator lhs, const_store_iterator rhs ) noexcept { assert(lhs.p == rhs.p); return lhs.i - rhs.i; } BAD(hd,inline,noalias) const_store_iterator & operator +=( ptrdiff_t rhs ) noexcept { i += rhs; return *this; } BAD(hd,inline,noalias) const_store_iterator & operator -=( ptrdiff_t rhs ) noexcept { i -= rhs; return *this; } BAD(hd,nodiscard,inline,pure) reference operator *() const noexcept { return *reinterpret_cast<pointer>(p + i*s); } BAD(hd,nodiscard,inline,pure) pointer operator ->() const noexcept { return reinterpret_cast<pointer>(p + i*s); } BAD(hd,nodiscard,inline,pure) reference operator[]( ptrdiff_t di ) const noexcept { return *reinterpret_cast<pointer>(p + (i+di)*s); } BAD(hd,nodiscard,inline,pure) bool valid() const noexcept { return p != nullptr && 0 <= i && i < d; } }; /// \ingroup storage_group template <size_t d, size_t s, class T, class plane> struct store_iterator final { using value_type = plane; using difference_type = ptrdiff_t; using pointer = value_type *; using reference = value_type &; using iterator_category = std::random_access_iterator_tag; BAD(hd,inline,noalias) constexpr explicit store_iterator( T* p = nullptr, ptrdiff_t i = 0 ) noexcept : p(p), i(i) {} BAD(hd,inline,noalias) constexpr store_iterator(store_iterator const & rhs) noexcept : p(rhs.p), i(rhs.i) {} BAD(hd,inline,noalias) constexpr store_iterator(store_iterator && rhs) noexcept : p(std::move(rhs.p)), i(std::move(rhs.i)) {} BAD(reinitializes,hd,inline,noalias) store_iterator & operator =(store_iterator rhs) noexcept { p = rhs.p; i = rhs.i; return *this; } BAD(reinitializes,hd,inline,noalias) store_iterator & operator =(store_iterator && rhs) noexcept { p = std::move(rhs.p); i = std::move(rhs.i); return *this; } T * p; ptrdiff_t i; BAD(hd,nodiscard,inline,pure) operator const_store_iterator<d,s,T,plane>() const { return const_store_iterator(p, i); } // valid across sources BAD(hd,nodiscard,inline,pure) friend bool operator ==(store_iterator lhs, store_iterator rhs) noexcept { return lhs.i == rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator !=(store_iterator lhs, store_iterator rhs) noexcept { return lhs.i != rhs.i; } // valid within a single source BAD(hd,nodiscard,inline,pure) friend bool operator <(store_iterator lhs, store_iterator rhs) noexcept { return lhs.i < rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator >(store_iterator lhs, store_iterator rhs) noexcept { return lhs.i > rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator <=(store_iterator lhs, store_iterator rhs) noexcept { return lhs.i <= rhs.i; } BAD(hd,nodiscard,inline,pure) friend bool operator >=(store_iterator lhs, store_iterator rhs) noexcept { return lhs.i >= rhs.i; } BAD(hd,inline,noalias) store_iterator & operator ++() noexcept { ++i; return *this; } BAD(hd,inline,noalias) store_iterator operator ++(int) noexcept { return store_iterator(p, i++); } BAD(hd,inline,noalias) store_iterator & operator --() noexcept { --i; return *this; } BAD(hd,inline,noalias) store_iterator operator --(int) noexcept { return store_iterator(p, i--); } BAD(hd,nodiscard,inline,pure) friend store_iterator operator +(store_iterator lhs, ptrdiff_t rhs) noexcept { return store_iterator(lhs.p, lhs.i + rhs); } BAD(hd,nodiscard,inline,pure) friend store_iterator operator -(store_iterator lhs, ptrdiff_t rhs) noexcept { return store_iterator(lhs.p, lhs.i - rhs); } BAD(hd,nodiscard,inline,pure) friend ptrdiff_t operator -(store_iterator lhs, store_iterator rhs) noexcept { assert(lhs.p == rhs.p); return lhs.i - rhs.i; } BAD(hd,inline,noalias) store_iterator & operator +=(ptrdiff_t rhs) noexcept { i += rhs; return *this; } BAD(hd,inline,noalias) store_iterator & operator -=(ptrdiff_t rhs) noexcept { i -= rhs; return *this; } BAD(hd,nodiscard,inline,pure) reference operator *() const noexcept { return *reinterpret_cast<pointer>(p + i*s); } BAD(hd,nodiscard,inline,pure) pointer operator ->() const noexcept { return reinterpret_cast<pointer>(p + i*s); } BAD(hd,nodiscard,inline,pure) reference operator[](ptrdiff_t di) const noexcept { return *reinterpret_cast<pointer>(p + (i+di)*s); } BAD(hd,nodiscard,inline,pure) bool valid() const noexcept { return 0 <= i && i < d; } BAD(hd,nodiscard,inline,pure) friend store_iterator operator + (ptrdiff_t lhs, store_iterator rhs) { return store_iterator(rhs.p, rhs.i + lhs); } }; } #endif
a699e687648ea486b5dc4af7a536c0931e48d7d5
f57380148cd8a325d8621e9ab7fb2bca9237f667
/Door.cpp
8912853aeeaa5df2014716bf537957569a4441be
[]
no_license
Roggan1/OOAD2
8456a65d8684f3e6003cb9ed3a6f529635cb2482
e4b08c4464837d0b2ccfba792eeee415b70515db
refs/heads/master
2021-01-17T11:55:01.227548
2017-06-27T21:08:34
2017-06-27T21:08:34
95,593,846
0
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
Door.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Door.cpp * Author: stud * * Created on 21. Mai 2017, 14:35 */ #include "Door.h" Door::Door() { m_Status=false; } Door::~Door() { } char Door::getSymbol() { if (m_Status == true) { return '/'; } else { return 'X'; } } void Door::onEnter(Character* Char, Tile* fromTile) { if (m_Status == false) { cout << "Die Tür ist verschlossen" << endl; m_Char = Char; onLeave(fromTile); } else { m_Char = Char; } }
d543518a5a3a70f19cb353df8f813c03a791ac16
e94ca3b308dddd06fe4255f35b123fd38e811ed0
/src/obj/crypto/CryptoBlock.h
28a0f6ed19836c703bc330f580fb2877312e00dc
[]
no_license
LoghinVladDev/IS-T1-CPP
848836e952a3622fbb8c110fac58ba4a7538f2a9
46855995ecc85a350babdeb8422c1a40c2eec813
refs/heads/master
2023-01-05T07:31:17.844548
2020-11-08T01:55:48
2020-11-08T01:55:48
310,169,069
1
0
null
null
null
null
UTF-8
C++
false
false
6,439
h
CryptoBlock.h
// // Created by loghin on 02.11.2020. // #ifndef SI_T1_CRYPTOBLOCK_H #define SI_T1_CRYPTOBLOCK_H #include <types.h> #include <cstring> #include <algorithm> #include <string> #include <list> namespace crypto { typedef enum : byte { BITS_64 = 8, BITS_128 = 16, BITS_256 = 32, BITS_512 = 64 } BlockSize; template<BlockSize byteSize> class CryptoBlock { private: byte _data[byteSize + 1]; byte _padData{' '}; public: explicit CryptoBlock(byte padData = ' ') noexcept: _padData(padData) {// NOLINT(cppcoreguidelines-pro-type-member-init) std::memset(this->_data, this->_padData, static_cast < std::size_t > ( byteSize )); this->_data[static_cast < std::size_t > ( byteSize )] = '\0'; } CryptoBlock(CryptoBlock<byteSize> const &&block) noexcept { // NOLINT(cppcoreguidelines-pro-type-member-init) std::memcpy(this->_data, block._data, static_cast < std::size_t > ( byteSize ) + 1); } CryptoBlock(CryptoBlock<byteSize> const &block) noexcept { // NOLINT(cppcoreguidelines-pro-type-member-init) std::memcpy(this->_data, block._data, static_cast < std::size_t > ( byteSize ) + 1); } explicit CryptoBlock(const byte *pData, std::size_t dataSize,byte padData = ' ') noexcept { // NOLINT(cppcoreguidelines-pro-type-member-init) std::memcpy(this->_data, pData, std::min(dataSize, static_cast < std::size_t > ( byteSize ))); if (dataSize < static_cast < std::size_t > ( byteSize )) std::memset(this->_data + dataSize, padData, static_cast < std::size_t > ( byteSize ) - dataSize); this->_data[static_cast < std::size_t > ( byteSize )] = 0; } explicit CryptoBlock(const char *pData,byte padData = ' ') noexcept { // NOLINT(cppcoreguidelines-pro-type-member-init) auto dataSize = static_cast < std::size_t > ( std::strlen(pData)); std::memcpy(this->_data, pData, std::min(dataSize, static_cast < std::size_t > ( byteSize ))); if (dataSize < static_cast < std::size_t > ( byteSize )) std::memset(this->_data + dataSize, padData, static_cast < std::size_t > ( byteSize ) - dataSize); this->_data[static_cast < std::size_t > ( byteSize )] = 0; } CryptoBlock<byteSize> &setPadData(byte padData) noexcept { this->_padData = padData; return *this; } [[nodiscard]] const byte *data() const noexcept { return this->_data; } CryptoBlock<byteSize> &operator=(const CryptoBlock<byteSize> &block) noexcept { if (this == &block) return *this; std::memcpy(this->_data, block._data, static_cast < std::size_t > ( byteSize ) + 1); return *this; } CryptoBlock<byteSize> &setData(const CryptoBlock<byteSize> &block) noexcept { return (*this = block); } CryptoBlock<byteSize> &setData(const byte *pData, std::size_t dataSize, byte padData = ' ') noexcept { std::memcpy(this->_data, pData, std::min(dataSize, static_cast < std::size_t > ( byteSize ))); if (dataSize < static_cast < std::size_t > ( byteSize )) std::memset(this->_data + dataSize, padData, static_cast < std::size_t > ( byteSize ) - dataSize); this->_data[static_cast < std::size_t > ( byteSize )] = 0; return *this; } friend CryptoBlock<byteSize> operator ^ (const CryptoBlock<byteSize> &a, const CryptoBlock<byteSize> &b) noexcept { CryptoBlock<byteSize> result; for (std::size_t i = 0; i < static_cast < std::size_t > ( byteSize ); i++) result[i] = a[i] ^ b[i]; return result; } [[nodiscard]] std::string toString() const noexcept { return static_cast < std::basic_string<char> > ( *this ); } explicit operator std::basic_string<char>() const noexcept { return std::basic_string<char>("{ size = ").append( std::to_string(static_cast < std::size_t > ( byteSize ))).append(", data = '").append( reinterpret_cast < const char * > (this->_data)).append("'}"); } friend std::ostream &operator<<(std::ostream &buffer, const CryptoBlock<byteSize> &object) noexcept { return buffer << static_cast < std::string > ( object ); } byte operator[](int index) const noexcept { if (index < 0) index += ((0 - index) / static_cast < int > ( byteSize ) + 1) * static_cast < int > ( byteSize ); return this->_data[index % static_cast < std::size_t > ( byteSize )]; } byte &operator[](int index) noexcept { if (index < 0) index += ((0 - index) / static_cast < int > ( byteSize ) + 1) * static_cast < int > ( byteSize ); return this->_data[index % static_cast < std::size_t > ( byteSize )]; } [[nodiscard]] std::string toHexString() const noexcept; static std::list<CryptoBlock<byteSize> > split(const char *, uint32 = 0) noexcept; }; } #include <iomanip> #include <sstream> template<crypto::BlockSize size> std::string crypto::CryptoBlock<size>::toHexString() const noexcept { std::stringstream stream; stream << "{ block = "; for (std::size_t i = 0; i < static_cast < std::size_t > ( size ); i++) stream << std::hex << std::setfill('0') << std::setw(2) << static_cast < uint32 > ( this->data()[i] ) << ' '; stream << " }"; return stream.str(); } template<crypto::BlockSize byteSize> std::list<crypto::CryptoBlock<byteSize> > crypto::CryptoBlock<byteSize>::split(const char *pText, uint32 lengthOverride) noexcept { std::size_t length; if ( lengthOverride == 0 ) length = strlen(pText); else length = lengthOverride; std::list<CryptoBlock<byteSize> > list; for (std::size_t i = 0, count = length / static_cast < std::size_t > ( byteSize ); i < count; i++) { list.emplace_back(pText + i * static_cast < std::size_t > ( byteSize )); } if (length % static_cast < std::size_t > ( byteSize ) != 0) list.emplace_back(pText + length - length % 16); return list; } #endif //SI_T1_CRYPTOBLOCK_H
2d13509a4339d397ccd3c749bdbdba7dd29467ff
25e69032c803a1ecb7706d924289bf1197250bae
/GASystem/GASystem/GASystem/geneticalgorithm.h
4d6a15d52d7090ca283a1dee30c1b97cfb4b6913
[]
no_license
igorawratu/NNGA
ee553997ba652b7478e4ea8517c2911cdeaf7643
8b84fb1a61ef433a6209b8ba9ea29dc58a62ed79
refs/heads/master
2016-09-01T21:38:47.149291
2015-03-14T07:53:23
2015-03-14T07:53:23
10,990,053
0
0
null
null
null
null
UTF-8
C++
false
false
560
h
geneticalgorithm.h
#ifndef GENETICALGORITHM_H #define GENETICALGORITHM_H #include <vector> #include <string> #include "simulationcontainer.h" #include "filewriter.h" using namespace std; class GeneticAlgorithm { public: GeneticAlgorithm(){ pTotalFitnessEvals = 20000; } virtual ~GeneticAlgorithm(){} virtual Solution train(SimulationContainer* _simulationContainer, string _outputFileName)=0; virtual void stopSlaves()=0; protected: double pBestOverallFit; uint pNumFitEval; uint pTotalFitnessEvals; string pFileName; }; #endif
1844425c386923e633a7b6a13aadc70f142b5c58
d3dea2b8adb52261d6c8a125ed7ff5a532a06059
/Lab11/Lab11/lab11.cpp
e06c0b41bafdfdad5b94aa72baa749443c4fb09e
[]
no_license
clfz6/CS201L_Lab11
9c4447ed36b10c5d1a0a2f2eb22a881659b30fea
ed6cd46bf0be6ef02f9a14d484b7a339a3975b97
refs/heads/master
2022-11-22T21:35:13.955186
2020-07-18T21:59:42
2020-07-18T21:59:42
280,692,536
0
0
null
null
null
null
UTF-8
C++
false
false
2,000
cpp
lab11.cpp
#include "Employee.h" #include <fstream> #include <iostream> #include <string> #include <vector> using namespace std; int main() { ifstream fin("input.txt"); ofstream fout("output.txt"); string input, f_name, l_name; vector<Employee> employees; int id, size, rate; \ if (fin.fail()) { cout << "Input file failed to open" << endl; } if (fout.fail()) { cout << "Output file failed to open" << endl; } while (fin.good()) { fin >> input; if (input == "NEW") { fin >> id; fin >> f_name >> l_name; Employee emp(id, f_name + " " + l_name); employees.push_back(emp); } else if (input == "RAISE") { fin >> id; size = employees.size(); for (int i = 0; i < size; i++) { if (employees[i].getEmployeeID() == id) { fin >> rate; employees[i].giveRaise(rate); } } } else if (input == "PAY") { size = employees.size(); for (int i = 0; i < size; i++) { if (employees[i].isEmployed() == true) employees[i].pay(); } } else if (input == "FIRE") { fin >> id; size = employees.size(); for (int i = 0; i < size; i++) { if (employees[i].getEmployeeID() == id) employees[i].fire(); } } else { fout << "Error" << endl; } } size = employees.size(); for (int i = 0; i < size; i++) { if (employees[i].isEmployed() == true) { fout << employees[i].getName() << ", ID Number " << employees[i].getEmployeeID() << ":" << endl; fout << "Current pay rate: $" << employees[i].getPayRate() << endl; fout << "Pay earned to date: $" << employees[i].getBalance() << endl << endl; } else if (employees[i].isEmployed() == false) { fout << employees[i].getName() << ", ID Number " << employees[i].getEmployeeID() << ":" << endl; fout << "Not employed with the company." << endl; fout << "Pay earned to date: $" << employees[i].getBalance() << endl << endl; } else { fout << "Error" << endl << endl; } } fin.close(); fout.close(); return 0; }
68aacd3aaead538cdcd495995e9cf03db717ab10
ecd2833f00a2df88d6224deef4be6478375a0982
/week5/CharacterFrequencyIterator.cpp
657a1637b1587bb9a68d5f5818b1a4bf328eaee6
[]
no_license
pondodev/dspwork
0f273843a0f210b8cd75bbdb16750353aae24e8b
b2ae7b73f74a0ec3073913e31481c5153e28854d
refs/heads/master
2021-05-17T20:50:20.563042
2020-03-29T03:20:52
2020-03-29T03:20:52
250,944,876
0
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
CharacterFrequencyIterator.cpp
#include "CharacterFrequencyIterator.h" void CharacterFrequencyIterator::advanceIndex() { } CharacterFrequencyIterator::CharacterFrequencyIterator( const CharacterCounter& aCounter, bool aSort) { } void CharacterFrequencyIterator::sort() { } const CharacterMap& CharacterFrequencyIterator::operator*() const { } CharacterFrequencyIterator& CharacterFrequencyIterator::operator++() { } CharacterFrequencyIterator CharacterFrequencyIterator::operator++( int ) { } bool CharacterFrequencyIterator::operator==( const CharacterFrequencyIterator& aOther ) const { } bool CharacterFrequencyIterator::operator!=( const CharacterFrequencyIterator& aOther ) const { } CharacterFrequencyIterator CharacterFrequencyIterator::begin() const { } CharacterFrequencyIterator CharacterFrequencyIterator::end() const { }
de7b932d42db535f9a30d2e834be7ea86d85a7bc
9fb8b1fae3283cf8f1fb01441ffba781ae0377f3
/examples/example9.cpp
a29c93b68389dadafb5fb2e6f2518e2695b45eb1
[]
no_license
wthibault/ssg
efaf10dd1728dc036e20827050f7421bcb8a4f39
cba8876dbcb740f31198c830feced8a12e1fb99c
refs/heads/master
2022-03-15T02:44:34.505013
2022-02-05T16:32:12
2022-02-05T16:32:12
7,494,493
15
3
null
null
null
null
UTF-8
C++
false
false
3,512
cpp
example9.cpp
// // example9.cpp // articulated figure // #include "ssg.h" using namespace glm; #include <iostream> #include <iomanip> #include <sstream> #include <string> using namespace std; using namespace ssg; Ptr<Instance> root; Camera camera; int width, height; vector<vec3> controlPoints; Ptr<Instance> link0, link1, link2; vec3 upperArmJointOffset (1,1,0); vec3 lowerArmJointOffset (1,0,0); float getNow() { return static_cast<double>(glutGet(GLUT_ELAPSED_TIME)) / 1000.0 ; } /////////////////////////////////////////////////////////////// mat4 upperArmMatrix ( float angle ) { mat4 t = translate ( mat4(), vec3 ( upperArmJointOffset ) ); mat4 r = rotate ( mat4(), angle, vec3(0,0,1) ); return t * r; } mat4 lowerArmMatrix ( float angle ) { mat4 t = translate ( mat4(), vec3 ( lowerArmJointOffset ) ); mat4 r = rotate ( mat4(), angle, vec3(0,0,1) ); return t * r; } void display () { glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); static float lastFrame = getNow(); float now = getNow(); root->update(now-lastFrame); link1->setMatrix ( upperArmMatrix ( 60 * sin(now) ) ); link2->setMatrix ( lowerArmMatrix ( 45 * sin(now) ) ); camera.draw(root); glutSwapBuffers(); lastFrame = now; // std::cout << now << std::endl; } void timer ( int delay ) { glutTimerFunc( delay, timer, delay ); glutPostRedisplay(); } void reshape (int w, int h) { width = w; height = h; camera.setupPerspective ( w, h ); } void keyboard (unsigned char key, int x, int y) { switch (key) { case 27: /* ESC */ exit(0); break; default: break; } } void init (int argc, char **argv) { // create a primitive. if supplied on command line, read a .obj wavefront file ObjFilePrimitive *body, *upperArm, *lowerArm; body = new ObjFilePrimitive ( "objfiles/body.obj" ); upperArm = new ObjFilePrimitive ( "objfiles/upper_arm.obj" ); lowerArm = new ObjFilePrimitive ( "objfiles/lower_arm.obj" ); // create the graph link0 = Ptr<Instance> (new Instance); link0->addChild ( body ); link0->setMatrix ( mat4() ); link1 = Ptr<Instance> (new Instance); link1->addChild ( upperArm ); link1->setMatrix ( upperArmMatrix(0) ); link0->addChild ( link1 ); link2 = Ptr<Instance> (new Instance); link2->addChild ( lowerArm ); link2->setMatrix ( lowerArmMatrix(0) ); link1->addChild ( link2 ); // set the instance as the scene root root = link0; // enable camera trackball camera.enableTrackball (true); // the lights are global for all objects in the scene RenderingEnvironment::getInstance().lightPosition = vec4 ( 4,10,5,1 ); RenderingEnvironment::getInstance().lightColor = vec4 ( 1,1,1,1 ); // misc OpenGL state glClearColor (0.0, 0.0, 0.0, 1.0); glEnable(GL_DEPTH_TEST); } void mouse ( int button, int state, int x, int y ) { if ( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) { camera.startMouse ( x, height-y ); } } void motion ( int x, int y ) { camera.dragMouse(x,height-y); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ); glutInitWindowSize (300, 300); glutInitWindowPosition (100, 100); glutCreateWindow (argv[0]); #ifndef __APPLE__ glewInit(); #endif init(argc,argv); glutDisplayFunc ( display ); glutReshapeFunc ( reshape ); glutKeyboardFunc ( keyboard ); glutMouseFunc ( mouse ); glutMotionFunc ( motion ); glutTimerFunc( 33,timer,33 ); glutMainLoop(); return 0; }
13cccec9dc972e65afa3a6b174b09629e653be0f
51fdb0052b36d0b7bf221b8ffbcc662632f1bfef
/tensorflow/compiler/plugin/poplar/driver/tools/while_loop_util.cc
303fe4540f52f999136108065886e626411abfed
[ "Apache-2.0" ]
permissive
DavidChan0519/tensorflow
f78a50b5d7f25e6aed1d3965555767d00d14c180
09116526433a1a89d2ff213e143bf5745666d0cc
refs/heads/master
2022-11-15T23:58:13.574558
2019-05-31T10:56:36
2019-05-31T10:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,394
cc
while_loop_util.cc
#include "tensorflow/compiler/plugin/poplar/driver/tools/while_loop_util.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/shape_util.h" #include <map> #include <set> namespace xla { namespace poplarplugin { namespace { StatusOr<int64> GetLoopDelta(const HloInstruction* delta) { if (delta->opcode() == HloOpcode::kConstant) { if (WhileLoopUtil::Is32BitsOrLessIntegerConstant(delta)) { TF_ASSIGN_OR_RETURN(int64 delta_value, LiteralScalarToNativeType<int64>(delta->literal())); if (std::llabs(delta_value) == 1) { return delta_value; } } } else if (delta->opcode() == HloOpcode::kNegate && delta->operand(0)->opcode() == HloOpcode::kConstant) { const HloInstruction* constant = delta->operand(0); if (WhileLoopUtil::Is32BitsOrLessIntegerConstant(constant)) { TF_ASSIGN_OR_RETURN(int64 delta_value, LiteralScalarToNativeType<int64>( constant->literal())); if (std::llabs(delta_value) == 1) { return -delta_value; } } } return xla::FailedPrecondition("Not a loop delta."); } // Returns a the delta counter if this instruction is incremented/decremented // by (-)1 - simplify it so that it's always an add - for example subtracting 1 // is the same as adding -1. absl::optional<int64> GetLoopCounter(const HloInstruction* loop_counter) { // Loop delta cases if (loop_counter->opcode() == HloOpcode::kAdd) { // For addition, a loop delta can be either LHS or RHS auto lhs_statusor = GetLoopDelta(loop_counter->operand(0)); if (lhs_statusor.ok()) { return lhs_statusor.ValueOrDie(); } auto rhs_statusor = GetLoopDelta(loop_counter->operand(1)); if (rhs_statusor.ok()) { return rhs_statusor.ValueOrDie(); } } else if (loop_counter->opcode() == HloOpcode::kSubtract) { // For subtract, a loop delta can be only on RHS auto rhs_statusor = GetLoopDelta(loop_counter->operand(1)); if (rhs_statusor.ok()) { return -rhs_statusor.ValueOrDie(); } } return absl::nullopt; } } // namespace bool WhileLoopUtil::IsGTEFromParamIndex(const HloInstruction* inst, int64 param_index) { return inst->opcode() == HloOpcode::kGetTupleElement && inst->operand(0)->opcode() == HloOpcode::kParameter && inst->operand(0)->parameter_number() == param_index; } bool WhileLoopUtil::Is32BitsOrLessIntegerConstant(const HloInstruction* inst) { return IsScalarConstant(inst) && (ShapeUtil::ElementIsIntegralWithBits(inst->shape(), 8) || ShapeUtil::ElementIsIntegralWithBits(inst->shape(), 16) || ShapeUtil::ElementIsIntegralWithBits(inst->shape(), 32)); } std::vector<std::pair<HloInstruction*, int64>> WhileLoopUtil::FindMatchingLoopDeltasInsideBody( const HloInstruction* inst, const HloComputation* while_body) { CHECK_EQ(inst->opcode(), HloOpcode::kGetTupleElement); std::vector<std::pair<HloInstruction*, int64>> ret; // Check that the GTE is on a tuple that is only used by GTEs. const HloInstruction* tuple = inst->operand(0); if (absl::c_any_of(tuple->users(), [](HloInstruction* user) { return user->opcode() != HloOpcode::kGetTupleElement; })) { return ret; } const int64 tuple_index_cond = inst->tuple_index(); for (HloInstruction* user : inst->users()) { // Check whether this is a loop counter. auto optional_loop_counter = GetLoopCounter(user); if (!optional_loop_counter) { continue; } // check that the user is only used once if (user->user_count() == 1) { HloInstruction* inst = user->users()[0]; // check that inst is a root Tuple instruction with the user in the // right index if (inst->opcode() == HloOpcode::kTuple && inst == while_body->root_instruction() && inst->operands()[tuple_index_cond] == user) { ret.push_back({user, *optional_loop_counter}); } } } return ret; } } // namespace poplarplugin } // namespace xla
b1a6366c073d74c65fb8c0d24159f5b1407520bf
b1ad48788ca9da319c3f808faf52d58013d1ee61
/Gragh/Cut Edge, Edge-Biconnected component.cpp
bb5c0e36768230d2f183864d2c63e98a304b6675
[]
no_license
darenlin49/ACM_Algorithm_Templates
e26f59bd933595b602ee5291dbeef4d65aad83b5
3359717b1c6b36464f2bc4e67952a8c60ce9c018
refs/heads/master
2021-05-28T03:43:34.594182
2014-11-18T05:18:16
2014-11-18T05:18:16
null
0
0
null
null
null
null
GB18030
C++
false
false
6,256
cpp
Cut Edge, Edge-Biconnected component.cpp
/** POJ 3352 && POJ 3177 题意:加几条边原图才能变成边双连通分量 [求割边]对图深度优先搜索,定义DFS(u)为u在搜索树(以下简称为树)中被遍历到的次序号。定义Low(u)为u或u的子树中能通过非父子边追溯到的最早的节点,即DFS序号最小的节点。根据定义,则有:Low(u)=Min {DFS(u),DFS(v)|(u,v)为后向边(等价于DFS(v)<DFS(u)且v不为u的父亲节点),Low(v)|(u,v)为树枝边} [条件]一条无向边(u,v)是桥,当且仅当(u,v)为树枝边,且满足DFS(u)<Low(v) [求点双连通分支]只需在求出所有的桥以后,把桥边删除,原图变成了多个连通块,则每个连通块就是一个边双连通分支。桥不属于任何一个边双连通分支,其余的边和每个顶点都属于且只属于一个边双连通分支。 [注]重边对求割边和边连通分量有影响,重边处理方法是在DFS时标记每条边及其反向边是否被访问过(即按边访问),而不是判断顶点(按点访问)。 **/ /* 无重边 */ const int MAXV = 5005; const int MAXE = 20005; struct node{ int u, v; int next; int opp; //把一个无向边拆成两个有向边,对应反向边标号 }arc[MAXE]; int cnt, head[MAXV]; void init(){ cnt = 0; mem(head, -1); return ; } void add(int u, int v){ arc[cnt].u = u; arc[cnt].v = v; arc[cnt].next = head[u]; arc[cnt].opp = cnt + 1; head[u] = cnt ++; arc[cnt].u = v; arc[cnt].v = u; arc[cnt].next = head[v]; arc[cnt].opp = cnt - 1; head[v] = cnt ++; return ; } int id, dfn[MAXV], low[MAXV]; int bridge[MAXE]; //标记该边是不是桥 void tarjan(int u, int father){ dfn[u] = low[u] = ++id; for (int i = head[u]; i != -1; i = arc[i].next){ int v = arc[i].v; if (v == father) continue; if (!dfn[v]){ tarjan(v, u); low[u] = min(low[u], low[v]); if (dfn[u] < low[v]){ bridge[i] = 1; //两个反向的有向边表示无向边 bridge[arc[i].opp] = 1; } } else{ low[u] = min(low[u], dfn[v]); } } } bool vis[MAXV]; int bcc_num; //边双连通分量数 int bcc[MAXV]; //标记点属于哪个边双连通分支 void fill(int u){ //在删除桥的图中对每个点染色,确定他所属的边双联通分量 vis[u] = 1; bcc[u] = bcc_num; for (int i = head[u]; i != -1; i = arc[i].next){ if (bridge[i]) continue; int v = arc[i].v; if (!vis[v]) fill(v); } } int deg[MAXV]; //缩点后的新图节点度数,便于计算叶子结点数 bool vis_arc[MAXE]; //某无向边(两个有向边)只访问一次, int find_bcc(int n){ //返回还需添加几条边才能成为边双连通图 mem(vis, 0); mem(deg, 0); //确定每个点所属边双联通分量 for (int i = 1; i <= n; i ++){ if (!vis[i]){ ++ bcc_num; fill(i); } } mem(vis_arc, 0); //计算还需连几条边才能构成双联通图 for (int i = 0; i < cnt; i ++){ if (!vis_arc[i]){ //这里一定要注意计算度数时一条无向边只能算一次 vis_arc[i] = vis_arc[arc[i].opp] = 1; int u = arc[i].u; int v = arc[i].v; if (bcc[u] != bcc[v]){ deg[bcc[u]] ++; deg[bcc[v]] ++; } } } int res = 0; for (int i = 1; i <= bcc_num; i ++){ if (deg[i] == 1) res ++; } return (res+1)/2; } void solve(int n){ id = bcc_num =0; mem(dfn, 0); mem(low, 0); mem(bridge, 0); for (int i = 1; i <= n; i ++){ if (!dfn[i]) tarjan(1, 0); } printf("%d\n", find_bcc(n)); return ; } int main(){ int F,R; while(scanf("%d %d", &F, &R) != EOF){ init(); for (int i = 0; i < R; i ++){ int u, v; scanf("%d %d", &u, &v); add(u, v); } solve(F); } return 0; } /* 有重边BCC,按边DFS */ const int MAXV = 200005; const int MAXE = 2000005; struct node{ int u, v; int next; bool bridge; }arc[MAXE]; int cnt, head[MAXV]; void init(){ cnt = 0; mem(head, -1); return ; } void add(int u, int v){ arc[cnt].u = u; arc[cnt].v = v; arc[cnt].next = head[u]; arc[cnt].bridge = false; head[u] = cnt ++; arc[cnt].u = v; arc[cnt].v = u; arc[cnt].next = head[v]; arc[cnt].bridge = false; head[v] = cnt ++; return ; } int id, dfn[MAXV], low[MAXV]; int bridge_num; bool vis_arc[MAXE]; //一条边无向边(两个有向边)只访问一次, void tarjan(int u){ dfn[u] = low[u] = ++ id; for (int i = head[u]; i != -1; i = arc[i].next){ if (vis_arc[i]) continue; int v = arc[i].v; vis_arc[i] = vis_arc[i^1] = 1; //判重边 if (!dfn[v]){ tarjan(v); low[u] = min(low[u], low[v]); if (dfn[u] < low[v]){ arc[i].bridge = true; arc[i^1].bridge = true; bridge_num ++; } } else{ low[u] = min(low[u], dfn[v]); } } } int bcc_num; bool vis[MAXV]; int mark[MAXV]; //标记点属于哪个边双连通分支 vector <int> bcc[MAXV]; void fill(int u){ bcc[bcc_num].push_back(u); mark[u] = bcc_num; for (int i = head[u]; i != -1; i = arc[i].next){ if (arc[i].bridge) continue; int v = arc[i].v; if (mark[v] == 0) fill(v); } } void find_bcc(int n){ mem(vis, 0); mem(mark, 0); //确定每个点所属边双联通分量 for (int i = 1; i <= n; i ++){ if (mark[i] == 0){ ++ bcc_num; bcc[bcc_num].clear(); fill(i); } } return ; } void solve(int n){ id = bcc_num = bridge_num = 0; mem(dfn, 0); mem(low, 0); mem(vis_arc, 0); for (int i = 1; i <= n; i ++){ if (!dfn[i]) tarjan(i); } find_bcc(n); return ; } int main(){ return 0; }
67a1292e97423090a967aeaf8d5aa685ba75a8d0
78653238a8c09d466d62faa01984afb97a73da30
/cxx/net/ipv4_error.h
d532c268b7b801ccc9c18dbe21a8884f5e6e96c2
[ "MIT" ]
permissive
RomaA2000/tgnews
3790a5197bd5149086ec79f331e2c175012f6d85
bae476b616df02d2b8e1ea5cbe3bc82e738714a8
refs/heads/master
2022-08-30T18:17:53.753413
2020-05-25T18:28:46
2020-05-25T18:28:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
878
h
ipv4_error.h
#ifndef WEB_CRACKER_IPV4_EXCEPTION_H #define WEB_CRACKER_IPV4_EXCEPTION_H #include <string> #include <stdexcept> #if defined(__linux) || defined(__APPLE__) #define gerrno errno #define NET_EINPROGRESS EINPROGRESS #elif defined(WIN32) #define gerrno WSAGetLastError() #define NET_EINPROGRESS WSAEINPROGRESS #endif #define IPV4_ERROR(X) ipv4::error(std::string("IPV4 ERROR: ") + X \ + " in file: " + __FILE__ \ + " in function: " + __func__ + "(...)" \ + " on line: " + std::to_string(__LINE__) \ + ": " + std::to_string(gerrno)) #define IPV4_EXC(X) throw IPV4_ERROR(X) namespace ipv4 { class error : public std::runtime_error { public: using std::runtime_error::runtime_error; using std::runtime_error::what; }; } // namespace ipv4 #endif //WEB_CRACKER_IPV4_EXCEPTION_H
2d7c60cc7044dcce10e34ffe4b4bdfa4043de2ac
ee2bcf0c6cb100f6b72d3e655d4a93663112f24e
/mobile-pc-filetransfer/test_pcserver/clientmain.cpp
70b142107c9d87b0586d5ae8ea35809dfcc18f74
[]
no_license
wyrover/mobile-pc-filetransfer
194b2b5a865add1f5c69a44ac67793752ef79c24
4b397713aa1f5a1def2e2be737a66f640c1ec198
refs/heads/master
2021-01-16T00:41:54.821177
2014-11-21T12:33:39
2014-11-21T12:33:39
null
0
0
null
null
null
null
GB18030
C++
false
false
6,323
cpp
clientmain.cpp
#include <boost/asio.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/algorithm/string.hpp> #include <regex> #include <array> #include <vector> #include <memory> #include <utility> #include <sstream> #include <thread> #include "tcpclient.h" namespace asio = boost::asio; namespace property_tree = boost::property_tree; class pc_manager { public: typedef std::vector<std::pair<std::string, asio::ip::tcp::endpoint>> pcinfo; public: pc_manager(asio::io_service& ioservice, asio::ip::udp::endpoint multicast_endpoint) : m_udpsocket(ioservice) , m_tcpsocket(ioservice) , m_multicast_endpoint(multicast_endpoint) { m_udpsocket.open(asio::ip::udp::v4()); property_tree::ptree ptree; ptree.put("type", "pcinfo"); ptree.put("value", ""); std::stringstream ss; property_tree::write_json(ss, ptree); std::string json{ ss.str() }; m_udpsocket.send_to(asio::buffer(json, json.size()), m_multicast_endpoint); start_scan_info(); } pcinfo& get_pcinfo() { return m_pcinfo; } public: bool ls(std::string pcname, std::string dirname) { auto itfind = m_connections.find(pcname); if (itfind == m_connections.end()) { std::cerr << "not connect to pc: " << pcname << std::endl; return false; } itfind->second->ls(dirname); return true; } bool connect(std::string pcname) { if (m_connections.count(pcname)) { return true; } pcinfo::iterator itfind = std::find_if(m_pcinfo.begin(), m_pcinfo.end(), [&pcname](pcinfo::value_type& v) { return v.first == pcname; } ); if (itfind == m_pcinfo.end()) { // 没有找到指定的PC return false; } std::shared_ptr<tcpclient> client = std::make_shared<tcpclient>(m_udpsocket.get_io_service()); bool ret = client->connect(itfind->second); if (!ret) { return false; } m_connections.insert(std::make_pair(pcname, client)); return true; } private: void start_scan_info() { m_udpsocket.async_receive_from(asio::buffer(m_udpbuf, m_udpbuf.max_size()), m_new_pc_endpoint, [this](const boost::system::error_code& e, std::size_t size) { read_handler(e, size); } ); } void read_handler(const boost::system::error_code& e, std::size_t size) { if (!e) { std::stringstream ss(std::string(m_udpbuf.begin(), m_udpbuf.begin() + size)); property_tree::ptree ptree; property_tree::read_json(ss, ptree); std::string type = ptree.get<std::string>("type", ""); if (!type.empty()) { if (type == "pcname") { std::string pcname = ptree.get<std::string>("value"); m_pcinfo.emplace_back(std::make_pair(pcname, asio::ip::tcp::endpoint(m_new_pc_endpoint.address(), m_new_pc_endpoint.port()))); std::cout << "new pc: " << pcname << std::endl; } else if (type == "listdir") { auto value = ptree.get_child("value"); for (auto file : value) { std::cout << file.second.get<std::string>("type") << " : " << file.second.get<std::string>("path") << std::endl; } } else { std::cerr << "unknow msg:" << ss.str() << std::endl; } } else { std::cerr << "error msg in " << __FUNCTION__ << ": " << ss.str() << std::endl; } } else { std::cerr << __FUNCTION__ << ": " << e.value() << ":" << e.message() << "\n"; } start_scan_info(); } private: asio::ip::udp::socket m_udpsocket; std::array<char, 1024> m_udpbuf; asio::ip::udp::endpoint m_new_pc_endpoint; asio::ip::udp::endpoint m_multicast_endpoint; asio::ip::tcp::socket m_tcpsocket; pcinfo m_pcinfo; std::map<std::string, std::shared_ptr<tcpclient>> m_connections; }; class stdinput_handler { public: stdinput_handler(asio::io_service& ioservice, std::shared_ptr<pc_manager> pcmanager) : m_std_input(ioservice, ::GetStdHandle(STD_INPUT_HANDLE)) , m_pc_manager(pcmanager) { start_read(); } private: void start_read() { std::cout << ">: "; asio::async_read_until(m_std_input, m_streambuf, "\n", boost::bind(&stdinput_handler::read_handler, this , asio::placeholders::error , asio::placeholders::bytes_transferred ) ); } void read_handler(const boost::system::error_code& e, std::size_t size) { if (!e) { std::istream stream(&m_streambuf); std::string cmd; std::getline(stream, cmd); boost::trim(cmd); if (cmd == "pcinfo") { for (auto info : m_pc_manager->get_pcinfo()) { std::cout << info.first << std::endl; } } start_read(); } else { std::cerr << "error in read_handler\n"; } } private: asio::windows::stream_handle m_std_input; asio::streambuf m_streambuf; std::shared_ptr<pc_manager> m_pc_manager; }; static void input_thread(boost::asio::io_service* io_service, std::shared_ptr<pc_manager> pcmanager) { while (!std::cin.eof()) { // std::cout << ">: "; std::string cmd; std::getline(std::cin, cmd); boost::trim(cmd); io_service->post([=]{ if (cmd == "pcinfo") { for (auto info : pcmanager->get_pcinfo()) { std::cout << info.first << std::endl; } return; } std::regex regex_listdir(R"(ls\s([\w-]+)\s*([\w-\\/:]*))"); std::smatch match_result; if (std::regex_match(cmd, match_result, regex_listdir)) { if (!pcmanager->ls(match_result[1].str(), match_result[2].str())) { std::cerr << "cannot find pc: " << match_result[1].str() << std::endl; } return; } std::regex regex_connect(R"(connect\s([\w-]+)\s*)"); if (std::regex_match(cmd, match_result, regex_connect)) { if (!pcmanager->connect(match_result[1].str()) ) { std::cerr << "cannot connect to: " << match_result[1].str() << std::endl; } else { std::cout << "connect " << match_result[1].str() << " successfully.\n"; } } else { std::cerr << "error cmd in input thread\n"; } }); } } int main() { asio::io_service ioservice; auto multicast_address = asio::ip::address::from_string("225.0.0.1"); asio::ip::udp::endpoint multicast_endpoint(multicast_address, 10000); std::shared_ptr<pc_manager> pcmanager(new pc_manager(ioservice, multicast_endpoint)); // stdinput_handler input_handler(ioservice, pcmanager); std::thread thread(&input_thread, &ioservice, pcmanager); ioservice.run(); }
98a58d3e697cba62a0280e8d66ae491e06d4f576
88040197168aef6cdde84a5fa0e56129808506da
/Prev/C/prog/pointers/character or string/04 pointers to multiple strings/pointers to number of striongs.cpp
fa495c713df97291f5ec803561c16b403005c4ab
[]
no_license
A-Samad1206/cpp
9d0f1d2d30d96e9fa75031e2dc0a309e2b9907e2
410135d5861d9883697efca7510bb800176f54e8
refs/heads/master
2023-07-18T00:47:28.345492
2021-09-03T17:58:38
2021-09-03T17:58:38
402,854,816
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
pointers to number of striongs.cpp
//to print %s it NOT need dereferencing contrar to 2-d array of characters. //bcoz array holds address of every strings //evident from 01 and 02. //name+i=&name[i]. //to retrive charcters *name[i]. //NO METHODS TO RETRIEVE CHARACTER. #include<stdio.h> main() { char *name[]={"ABDUS SAMAD","AHAD","TALHA"}; //printf("01-------------\n"); printf("\n01----concept---------\n"); for(int i=0;i<3;i++) { printf("\n%u",*(i+name));//it is address of name[i]. } printf("\n-------------\n"); for(int i=0;i<3;i++) { printf("\n%u",name[i]);//AS NAME[I] IS HOLDING ONLY ADDRESS OF STRINGS. } printf("\n02-------------\n"); for(int i=0;i<3;i++) { printf("%s\t%s\n",name[i],i[name]); } printf("\n03-----CHARACTER RETRIEVE--------\n"); for(int i=0;i<3;i++) { FOR(J=0;J<) printf("%c\t%c\n",*(*(name+i)+3)/***(name+i)+3*/,**(i+name));//**(name+i)+3A=65+3=D } printf("\n04-------------\n"); for(int i=0;i<3;i++) { printf("%c\t%c\n",*name[i],*i[name]); } /*printf("05-------------\n"); for(int i=0;i<3;i++) { printf("\n%s",*name++);IT IS CONSTANT BCOZ OF ARRAY. }*/ for(int i=0;i<3;i++) { printf("\n%lu",sizeof(name[i]));//it means it holds only initial address. } for(int i=0;i<3;i++) { printf("\n%lu",sizeof(*name[i]));//it means it IT SHOWING A,A,T. } }
5b1a65c184fe81c05cb2b8a09ac2d441794e9ea5
3e700f47bd3e33250cc248c01b1e6ee1261049ef
/Codeforces/873/b2.cpp
2649b3349b66f73870e4d182b5558671b282dff9
[]
no_license
pranavgupta1234/AlgorithmsAndDataStructures
8012e5f10d6f7cdbe65c1db31ad6ffa516f04207
a7530d66839265dbf542af8d3d7904d28da74d69
refs/heads/master
2021-05-01T05:03:42.246193
2019-04-27T23:16:39
2019-04-27T23:16:39
79,713,495
1
0
null
null
null
null
UTF-8
C++
false
false
817
cpp
b2.cpp
#ifdef __GNUC__ #pragma GCC target("sse4,avx") #endif #include <immintrin.h> #include <algorithm> #include <string> #include <iostream> #include <vector> #include <cstdint> #include <numeric> void run(std::istream &in, std::ostream &out) { size_t n; in >> n; std::string s; in >> s; std::vector<int> prev(2 * n + 1, -1); size_t cur = n; int ans = 0; prev[cur] = 0; for (int i = 0; i < n; i++) { if (s[i] == '0') { cur++; } else { cur--; } if (prev[cur] != -1) { ans = std::max(ans, i + 1 - prev[cur]); } else { prev[cur] = i + 1; } } out << ans << std::endl; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(nullptr); run(std::cin, std::cout); return 0; }
c1588b7b61f377df2bc80c55fbabd54be2641d5f
2ee533886925ba001cdce500d8c31fa2015b57b7
/Source/ExportApiWinMM.cpp
fe36786355fb1873a280020e3f90b11e894f0ff0
[ "BSD-3-Clause" ]
permissive
Rufoo/Xidi
23f330a67df0ad2b181e4bcf3be92f6d93d95c78
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
refs/heads/master
2023-02-20T22:07:37.286610
2021-01-25T00:12:15
2021-01-25T00:12:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,975
cpp
ExportApiWinMM.cpp
/***************************************************************************** * Xidi * DirectInput interface for XInput controllers. ***************************************************************************** * Authored by Samuel Grossman * Copyright (c) 2016-2021 *************************************************************************//** * @file ExportApiWinMM.cpp * Implementation of primary exported functions for the WinMM library. *****************************************************************************/ #include "ImportApiWinMM.h" #include "WrapperJoyWinMM.h" using namespace Xidi; extern "C" { // -------- DLL EXPORT FUNCTIONS --------------------------------------- // // See WinMM documentation for more information. LRESULT WINAPI ExportApiWinMMCloseDriver(HDRVR hdrvr, LPARAM lParam1, LPARAM lParam2) { return ImportApiWinMM::CloseDriver(hdrvr, lParam1, lParam2); } // --------- LRESULT WINAPI ExportApiWinMMDefDriverProc(DWORD_PTR dwDriverId, HDRVR hdrvr, UINT msg, LONG lParam1, LONG lParam2) { return ImportApiWinMM::DefDriverProc(dwDriverId, hdrvr, msg, lParam1, lParam2); } // --------- BOOL WINAPI ExportApiWinMMDriverCallback(DWORD dwCallBack, DWORD dwFlags, HDRVR hdrvr, DWORD msg, DWORD dwUser, DWORD dwParam1, DWORD dwParam2) { return ImportApiWinMM::DriverCallback(dwCallBack, dwFlags, hdrvr, msg, dwUser, dwParam1, dwParam2); } // --------- HMODULE WINAPI ExportApiWinMMDrvGetModuleHandle(HDRVR hDriver) { return ImportApiWinMM::DrvGetModuleHandle(hDriver); } // --------- HMODULE WINAPI ExportApiWinMMGetDriverModuleHandle(HDRVR hdrvr) { return ImportApiWinMM::GetDriverModuleHandle(hdrvr); } // --------- HDRVR WINAPI ExportApiWinMMOpenDriver(LPCWSTR lpDriverName, LPCWSTR lpSectionName, LPARAM lParam) { return ImportApiWinMM::OpenDriver(lpDriverName, lpSectionName, lParam); } // --------- BOOL WINAPI ExportApiWinMMPlaySoundA(LPCSTR pszSound, HMODULE hmod, DWORD fdwSound) { return ImportApiWinMM::PlaySoundA(pszSound, hmod, fdwSound); } // --------- BOOL WINAPI ExportApiWinMMPlaySoundW(LPCWSTR pszSound, HMODULE hmod, DWORD fdwSound) { return ImportApiWinMM::PlaySoundW(pszSound, hmod, fdwSound); } // --------- LRESULT WINAPI ExportApiWinMMSendDriverMessage(HDRVR hdrvr, UINT msg, LPARAM lParam1, LPARAM lParam2) { return ImportApiWinMM::SendDriverMessage(hdrvr, msg, lParam1, lParam2); } // --------- MMRESULT WINAPI ExportApiWinMMAuxGetDevCapsA(UINT_PTR uDeviceID, LPAUXCAPSA lpCaps, UINT cbCaps) { return ImportApiWinMM::auxGetDevCapsA(uDeviceID, lpCaps, cbCaps); } // --------- MMRESULT WINAPI ExportApiWinMMAuxGetDevCapsW(UINT_PTR uDeviceID, LPAUXCAPSW lpCaps, UINT cbCaps) { return ImportApiWinMM::auxGetDevCapsW(uDeviceID, lpCaps, cbCaps); } // --------- UINT WINAPI ExportApiWinMMAuxGetNumDevs(void) { return ImportApiWinMM::auxGetNumDevs(); } // --------- MMRESULT WINAPI ExportApiWinMMAuxGetVolume(UINT uDeviceID, LPDWORD lpdwVolume) { return ImportApiWinMM::auxGetVolume(uDeviceID, lpdwVolume); } // --------- MMRESULT WINAPI ExportApiWinMMAuxOutMessage(UINT uDeviceID, UINT uMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { return ImportApiWinMM::auxOutMessage(uDeviceID, uMsg, dwParam1, dwParam2); } // --------- MMRESULT WINAPI ExportApiWinMMAuxSetVolume(UINT uDeviceID, DWORD dwVolume) { return ImportApiWinMM::auxSetVolume(uDeviceID, dwVolume); } // --------- MMRESULT WINAPI ExportApiWinMMJoyConfigChanged(DWORD dwFlags) { return WrapperJoyWinMM::JoyConfigChanged(dwFlags); } // --------- MMRESULT WINAPI ExportApiWinMMJoyGetDevCapsA(UINT_PTR uJoyID, LPJOYCAPSA pjc, UINT cbjc) { return WrapperJoyWinMM::JoyGetDevCaps(uJoyID, pjc, cbjc); } // --------- MMRESULT WINAPI ExportApiWinMMJoyGetDevCapsW(UINT_PTR uJoyID, LPJOYCAPSW pjc, UINT cbjc) { return WrapperJoyWinMM::JoyGetDevCaps(uJoyID, pjc, cbjc); } // --------- UINT WINAPI ExportApiWinMMJoyGetNumDevs(void) { return WrapperJoyWinMM::JoyGetNumDevs(); } // --------- MMRESULT WINAPI ExportApiWinMMJoyGetPos(UINT uJoyID, LPJOYINFO pji) { return WrapperJoyWinMM::JoyGetPos(uJoyID, pji); } // --------- MMRESULT WINAPI ExportApiWinMMJoyGetPosEx(UINT uJoyID, LPJOYINFOEX pji) { return WrapperJoyWinMM::JoyGetPosEx(uJoyID, pji); } // --------- MMRESULT WINAPI ExportApiWinMMJoyGetThreshold(UINT uJoyID, LPUINT puThreshold) { return WrapperJoyWinMM::JoyGetThreshold(uJoyID, puThreshold); } // --------- MMRESULT WINAPI ExportApiWinMMJoyReleaseCapture(UINT uJoyID) { return WrapperJoyWinMM::JoyReleaseCapture(uJoyID); } // --------- MMRESULT WINAPI ExportApiWinMMJoySetCapture(HWND hwnd, UINT uJoyID, UINT uPeriod, BOOL fChanged) { return WrapperJoyWinMM::JoySetCapture(hwnd, uJoyID, uPeriod, fChanged); } // --------- MMRESULT WINAPI ExportApiWinMMJoySetThreshold(UINT uJoyID, UINT uThreshold) { return WrapperJoyWinMM::JoySetThreshold(uJoyID, uThreshold); } // --------- BOOL WINAPI ExportApiWinMMMCIDriverNotify(HWND hwndCallback, MCIDEVICEID IDDevice, UINT uStatus) { return ImportApiWinMM::mciDriverNotify(hwndCallback, IDDevice, uStatus); } // --------- UINT WINAPI ExportApiWinMMMCIDriverYield(MCIDEVICEID IDDevice) { return ImportApiWinMM::mciDriverYield(IDDevice); } // --------- BOOL WINAPI ExportApiWinMMMCIExecute(LPCSTR pszCommand) { return ImportApiWinMM::mciExecute(pszCommand); } // --------- BOOL WINAPI ExportApiWinMMMCIFreeCommandResource(UINT uResource) { return ImportApiWinMM::mciFreeCommandResource(uResource); } // --------- HANDLE WINAPI ExportApiWinMMMCIGetCreatorTask(MCIDEVICEID IDDevice) { return ImportApiWinMM::mciGetCreatorTask(IDDevice); } // --------- MCIDEVICEID WINAPI ExportApiWinMMMCIGetDeviceIDA(LPCSTR lpszDevice) { return ImportApiWinMM::mciGetDeviceIDA(lpszDevice); } // --------- MCIDEVICEID WINAPI ExportApiWinMMMCIGetDeviceIDW(LPCWSTR lpszDevice) { return ImportApiWinMM::mciGetDeviceIDW(lpszDevice); } // --------- MCIDEVICEID WINAPI ExportApiWinMMMCIGetDeviceIDFromElementIDA(DWORD dwElementID, LPCSTR lpstrType) { return ImportApiWinMM::mciGetDeviceIDFromElementIDA(dwElementID, lpstrType); } // --------- MCIDEVICEID WINAPI ExportApiWinMMMCIGetDeviceIDFromElementIDW(DWORD dwElementID, LPCWSTR lpstrType) { return ImportApiWinMM::mciGetDeviceIDFromElementIDW(dwElementID, lpstrType); } // --------- DWORD_PTR WINAPI ExportApiWinMMMCIGetDriverData(MCIDEVICEID IDDevice) { return ImportApiWinMM::mciGetDriverData(IDDevice); } // --------- BOOL WINAPI ExportApiWinMMMCIGetErrorStringA(DWORD fdwError, LPCSTR lpszErrorText, UINT cchErrorText) { return ImportApiWinMM::mciGetErrorStringA(fdwError, lpszErrorText, cchErrorText); } // --------- BOOL WINAPI ExportApiWinMMMCIGetErrorStringW(DWORD fdwError, LPWSTR lpszErrorText, UINT cchErrorText) { return ImportApiWinMM::mciGetErrorStringW(fdwError, lpszErrorText, cchErrorText); } // --------- YIELDPROC WINAPI ExportApiWinMMMCIGetYieldProc(MCIDEVICEID IDDevice, LPDWORD lpdwYieldData) { return ImportApiWinMM::mciGetYieldProc(IDDevice, lpdwYieldData); } // --------- UINT WINAPI ExportApiWinMMMCILoadCommandResource(HINSTANCE hInst, LPCWSTR lpwstrResourceName, UINT uType) { return ImportApiWinMM::mciLoadCommandResource(hInst, lpwstrResourceName, uType); } // --------- MCIERROR WINAPI ExportApiWinMMMCISendCommandA(MCIDEVICEID IDDevice, UINT uMsg, DWORD_PTR fdwCommand, DWORD_PTR dwParam) { return ImportApiWinMM::mciSendCommandA(IDDevice, uMsg, fdwCommand, dwParam); } // --------- MCIERROR WINAPI ExportApiWinMMMCISendCommandW(MCIDEVICEID IDDevice, UINT uMsg, DWORD_PTR fdwCommand, DWORD_PTR dwParam) { return ImportApiWinMM::mciSendCommandW(IDDevice, uMsg, fdwCommand, dwParam); } // --------- MCIERROR WINAPI ExportApiWinMMMCISendStringA(LPCSTR lpszCommand, LPSTR lpszReturnString, UINT cchReturn, HANDLE hwndCallback) { return ImportApiWinMM::mciSendStringA(lpszCommand, lpszReturnString, cchReturn, hwndCallback); } // --------- MCIERROR WINAPI ExportApiWinMMMCISendStringW(LPCWSTR lpszCommand, LPWSTR lpszReturnString, UINT cchReturn, HANDLE hwndCallback) { return ImportApiWinMM::mciSendStringW(lpszCommand, lpszReturnString, cchReturn, hwndCallback); } // --------- BOOL WINAPI ExportApiWinMMMCISetDriverData(MCIDEVICEID IDDevice, DWORD_PTR data) { return ImportApiWinMM::mciSetDriverData(IDDevice, data); } // --------- UINT WINAPI ExportApiWinMMMCISetYieldProc(MCIDEVICEID IDDevice, YIELDPROC yp, DWORD dwYieldData) { return ImportApiWinMM::mciSetYieldProc(IDDevice, yp, dwYieldData); } // --------- MMRESULT WINAPI ExportApiWinMMMidiConnect(HMIDI hMidi, HMIDIOUT hmo, LPVOID pReserved) { return ImportApiWinMM::midiConnect(hMidi, hmo, pReserved); } // --------- MMRESULT WINAPI ExportApiWinMMMidiDisconnect(HMIDI hMidi, HMIDIOUT hmo, LPVOID pReserved) { return ImportApiWinMM::midiDisconnect(hMidi, hmo, pReserved); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInAddBuffer(HMIDIIN hMidiIn, LPMIDIHDR lpMidiInHdr, UINT cbMidiInHdr) { return ImportApiWinMM::midiInAddBuffer(hMidiIn, lpMidiInHdr, cbMidiInHdr); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInClose(HMIDIIN hMidiIn) { return ImportApiWinMM::midiInClose(hMidiIn); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInGetDevCapsA(UINT_PTR uDeviceID, LPMIDIINCAPSA lpMidiInCaps, UINT cbMidiInCaps) { return ImportApiWinMM::midiInGetDevCapsA(uDeviceID, lpMidiInCaps, cbMidiInCaps); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInGetDevCapsW(UINT_PTR uDeviceID, LPMIDIINCAPSW lpMidiInCaps, UINT cbMidiInCaps) { return ImportApiWinMM::midiInGetDevCapsW(uDeviceID, lpMidiInCaps, cbMidiInCaps); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInGetErrorTextA(MMRESULT wError, LPSTR lpText, UINT cchText) { return ImportApiWinMM::midiInGetErrorTextA(wError, lpText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInGetErrorTextW(MMRESULT wError, LPWSTR lpText, UINT cchText) { return ImportApiWinMM::midiInGetErrorTextW(wError, lpText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInGetID(HMIDIIN hmi, LPUINT puDeviceID) { return ImportApiWinMM::midiInGetID(hmi, puDeviceID); } // --------- UINT WINAPI ExportApiWinMMMidiInGetNumDevs(void) { return ImportApiWinMM::midiInGetNumDevs(); } // --------- DWORD WINAPI ExportApiWinMMMidiInMessage(HMIDIIN deviceID, UINT msg, DWORD_PTR dw1, DWORD_PTR dw2) { return ImportApiWinMM::midiInMessage(deviceID, msg, dw1, dw2); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInOpen(LPHMIDIIN lphMidiIn, UINT uDeviceID, DWORD_PTR dwCallback, DWORD_PTR dwCallbackInstance, DWORD dwFlags) { return ImportApiWinMM::midiInOpen(lphMidiIn, uDeviceID, dwCallback, dwCallbackInstance, dwFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInPrepareHeader(HMIDIIN hMidiIn, LPMIDIHDR lpMidiInHdr, UINT cbMidiInHdr) { return ImportApiWinMM::midiInPrepareHeader(hMidiIn, lpMidiInHdr, cbMidiInHdr); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInReset(HMIDIIN hMidiIn) { return ImportApiWinMM::midiInReset(hMidiIn); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInStart(HMIDIIN hMidiIn) { return ImportApiWinMM::midiInStart(hMidiIn); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInStop(HMIDIIN hMidiIn) { return ImportApiWinMM::midiInStop(hMidiIn); } // --------- MMRESULT WINAPI ExportApiWinMMMidiInUnprepareHeader(HMIDIIN hMidiIn, LPMIDIHDR lpMidiInHdr, UINT cbMidiInHdr) { return ImportApiWinMM::midiInUnprepareHeader(hMidiIn, lpMidiInHdr, cbMidiInHdr); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutCacheDrumPatches(HMIDIOUT hmo, UINT wPatch, WORD* lpKeyArray, UINT wFlags) { return ImportApiWinMM::midiOutCacheDrumPatches(hmo, wPatch, lpKeyArray, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutCachePatches(HMIDIOUT hmo, UINT wBank, WORD* lpPatchArray, UINT wFlags) { return ImportApiWinMM::midiOutCachePatches(hmo, wBank, lpPatchArray, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutClose(HMIDIOUT hmo) { return ImportApiWinMM::midiOutClose(hmo); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutGetDevCapsA(UINT_PTR uDeviceID, LPMIDIOUTCAPSA lpMidiOutCaps, UINT cbMidiOutCaps) { return ImportApiWinMM::midiOutGetDevCapsA(uDeviceID, lpMidiOutCaps, cbMidiOutCaps); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutGetDevCapsW(UINT_PTR uDeviceID, LPMIDIOUTCAPSW lpMidiOutCaps, UINT cbMidiOutCaps) { return ImportApiWinMM::midiOutGetDevCapsW(uDeviceID, lpMidiOutCaps, cbMidiOutCaps); } // --------- UINT WINAPI ExportApiWinMMMidiOutGetErrorTextA(MMRESULT mmrError, LPSTR lpText, UINT cchText) { return ImportApiWinMM::midiOutGetErrorTextA(mmrError, lpText, cchText); } // --------- UINT WINAPI ExportApiWinMMMidiOutGetErrorTextW(MMRESULT mmrError, LPWSTR lpText, UINT cchText) { return ImportApiWinMM::midiOutGetErrorTextW(mmrError, lpText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutGetID(HMIDIOUT hmo, LPUINT puDeviceID) { return ImportApiWinMM::midiOutGetID(hmo, puDeviceID); } // --------- UINT WINAPI ExportApiWinMMMidiOutGetNumDevs(void) { return ImportApiWinMM::midiOutGetNumDevs(); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutGetVolume(HMIDIOUT hmo, LPDWORD lpdwVolume) { return ImportApiWinMM::midiOutGetVolume(hmo, lpdwVolume); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutLongMsg(HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr) { return ImportApiWinMM::midiOutLongMsg(hmo, lpMidiOutHdr, cbMidiOutHdr); } // --------- DWORD WINAPI ExportApiWinMMMidiOutMessage(HMIDIOUT deviceID, UINT msg, DWORD_PTR dw1, DWORD_PTR dw2) { return ImportApiWinMM::midiOutMessage(deviceID, msg, dw1, dw2); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutOpen(LPHMIDIOUT lphmo, UINT uDeviceID, DWORD_PTR dwCallback, DWORD_PTR dwCallbackInstance, DWORD dwFlags) { return ImportApiWinMM::midiOutOpen(lphmo, uDeviceID, dwCallback, dwCallbackInstance, dwFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutPrepareHeader(HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr) { return ImportApiWinMM::midiOutPrepareHeader(hmo, lpMidiOutHdr, cbMidiOutHdr); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutReset(HMIDIOUT hmo) { return ImportApiWinMM::midiOutReset(hmo); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutSetVolume(HMIDIOUT hmo, DWORD dwVolume) { return ImportApiWinMM::midiOutSetVolume(hmo, dwVolume); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutShortMsg(HMIDIOUT hmo, DWORD dwMsg) { return ImportApiWinMM::midiOutShortMsg(hmo, dwMsg); } // --------- MMRESULT WINAPI ExportApiWinMMMidiOutUnprepareHeader(HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr) { return ImportApiWinMM::midiOutUnprepareHeader(hmo, lpMidiOutHdr, cbMidiOutHdr); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamClose(HMIDISTRM hStream) { return ImportApiWinMM::midiStreamClose(hStream); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamOpen(LPHMIDISTRM lphStream, LPUINT puDeviceID, DWORD cMidi, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen) { return ImportApiWinMM::midiStreamOpen(lphStream, puDeviceID, cMidi, dwCallback, dwInstance, fdwOpen); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamOut(HMIDISTRM hMidiStream, LPMIDIHDR lpMidiHdr, UINT cbMidiHdr) { return ImportApiWinMM::midiStreamOut(hMidiStream, lpMidiHdr, cbMidiHdr); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamPause(HMIDISTRM hms) { return ImportApiWinMM::midiStreamPause(hms); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamPosition(HMIDISTRM hms, LPMMTIME pmmt, UINT cbmmt) { return ImportApiWinMM::midiStreamPosition(hms, pmmt, cbmmt); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamProperty(HMIDISTRM hm, LPBYTE lppropdata, DWORD dwProperty) { return ImportApiWinMM::midiStreamProperty(hm, lppropdata, dwProperty); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamRestart(HMIDISTRM hms) { return ImportApiWinMM::midiStreamRestart(hms); } // --------- MMRESULT WINAPI ExportApiWinMMMidiStreamStop(HMIDISTRM hms) { return ImportApiWinMM::midiStreamStop(hms); } // --------- MMRESULT WINAPI ExportApiWinMMMixerClose(HMIXER hmx) { return ImportApiWinMM::mixerClose(hmx); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetControlDetailsA(HMIXEROBJ hmxobj, LPMIXERCONTROLDETAILS pmxcd, DWORD fdwDetails) { return ImportApiWinMM::mixerGetControlDetailsA(hmxobj, pmxcd, fdwDetails); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetControlDetailsW(HMIXEROBJ hmxobj, LPMIXERCONTROLDETAILS pmxcd, DWORD fdwDetails) { return ImportApiWinMM::mixerGetControlDetailsW(hmxobj, pmxcd, fdwDetails); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetDevCapsA(UINT_PTR uMxId, LPMIXERCAPS pmxcaps, UINT cbmxcaps) { return ImportApiWinMM::mixerGetDevCapsA(uMxId, pmxcaps, cbmxcaps); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetDevCapsW(UINT_PTR uMxId, LPMIXERCAPS pmxcaps, UINT cbmxcaps) { return ImportApiWinMM::mixerGetDevCapsW(uMxId, pmxcaps, cbmxcaps); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetID(HMIXEROBJ hmxobj, UINT* puMxId, DWORD fdwId) { return ImportApiWinMM::mixerGetID(hmxobj, puMxId, fdwId); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetLineControlsA(HMIXEROBJ hmxobj, LPMIXERLINECONTROLS pmxlc, DWORD fdwControls) { return ImportApiWinMM::mixerGetLineControlsA(hmxobj, pmxlc, fdwControls); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetLineControlsW(HMIXEROBJ hmxobj, LPMIXERLINECONTROLS pmxlc, DWORD fdwControls) { return ImportApiWinMM::mixerGetLineControlsW(hmxobj, pmxlc, fdwControls); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetLineInfoA(HMIXEROBJ hmxobj, LPMIXERLINE pmxl, DWORD fdwInfo) { return ImportApiWinMM::mixerGetLineInfoA(hmxobj, pmxl, fdwInfo); } // --------- MMRESULT WINAPI ExportApiWinMMMixerGetLineInfoW(HMIXEROBJ hmxobj, LPMIXERLINE pmxl, DWORD fdwInfo) { return ImportApiWinMM::mixerGetLineInfoW(hmxobj, pmxl, fdwInfo); } // --------- UINT WINAPI ExportApiWinMMMixerGetNumDevs(void) { return ImportApiWinMM::mixerGetNumDevs(); } // --------- DWORD WINAPI ExportApiWinMMMixerMessage(HMIXER driverID, UINT uMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { return ImportApiWinMM::mixerMessage(driverID, uMsg, dwParam1, dwParam2); } // --------- MMRESULT WINAPI ExportApiWinMMMixerOpen(LPHMIXER phmx, UINT uMxId, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen) { return ImportApiWinMM::mixerOpen(phmx, uMxId, dwCallback, dwInstance, fdwOpen); } // --------- MMRESULT WINAPI ExportApiWinMMMixerSetControlDetails(HMIXEROBJ hmxobj, LPMIXERCONTROLDETAILS pmxcd, DWORD fdwDetails) { return ImportApiWinMM::mixerSetControlDetails(hmxobj, pmxcd, fdwDetails); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOAdvance(HMMIO hmmio, LPMMIOINFO lpmmioinfo, UINT wFlags) { return ImportApiWinMM::mmioAdvance(hmmio, lpmmioinfo, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOAscend(HMMIO hmmio, LPMMCKINFO lpck, UINT wFlags) { return ImportApiWinMM::mmioAscend(hmmio, lpck, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOClose(HMMIO hmmio, UINT wFlags) { return ImportApiWinMM::mmioClose(hmmio, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOCreateChunk(HMMIO hmmio, LPMMCKINFO lpck, UINT wFlags) { return ImportApiWinMM::mmioCreateChunk(hmmio, lpck, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIODescend(HMMIO hmmio, LPMMCKINFO lpck, LPCMMCKINFO lpckParent, UINT wFlags) { return ImportApiWinMM::mmioDescend(hmmio, lpck, lpckParent, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOFlush(HMMIO hmmio, UINT fuFlush) { return ImportApiWinMM::mmioFlush(hmmio, fuFlush); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOGetInfo(HMMIO hmmio, LPMMIOINFO lpmmioinfo, UINT wFlags) { return ImportApiWinMM::mmioGetInfo(hmmio, lpmmioinfo, wFlags); } // --------- LPMMIOPROC WINAPI ExportApiWinMMMMIOInstallIOProcA(FOURCC fccIOProc, LPMMIOPROC pIOProc, DWORD dwFlags) { return ImportApiWinMM::mmioInstallIOProcA(fccIOProc, pIOProc, dwFlags); } // --------- LPMMIOPROC WINAPI ExportApiWinMMMMIOInstallIOProcW(FOURCC fccIOProc, LPMMIOPROC pIOProc, DWORD dwFlags) { return ImportApiWinMM::mmioInstallIOProcW(fccIOProc, pIOProc, dwFlags); } // --------- HMMIO WINAPI ExportApiWinMMMMIOOpenA(LPSTR szFilename, LPMMIOINFO lpmmioinfo, DWORD dwOpenFlags) { return ImportApiWinMM::mmioOpenA(szFilename, lpmmioinfo, dwOpenFlags); } // --------- HMMIO WINAPI ExportApiWinMMMMIOOpenW(LPWSTR szFilename, LPMMIOINFO lpmmioinfo, DWORD dwOpenFlags) { return ImportApiWinMM::mmioOpenW(szFilename, lpmmioinfo, dwOpenFlags); } // --------- LONG WINAPI ExportApiWinMMMMIORead(HMMIO hmmio, HPSTR pch, LONG cch) { return ImportApiWinMM::mmioRead(hmmio, pch, cch); } // --------- MMRESULT WINAPI ExportApiWinMMMMIORenameA(LPCSTR szFilename, LPCSTR szNewFilename, LPCMMIOINFO lpmmioinfo, DWORD dwRenameFlags) { return ImportApiWinMM::mmioRenameA(szFilename, szNewFilename, lpmmioinfo, dwRenameFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIORenameW(LPCWSTR szFilename, LPCWSTR szNewFilename, LPCMMIOINFO lpmmioinfo, DWORD dwRenameFlags) { return ImportApiWinMM::mmioRenameW(szFilename, szNewFilename, lpmmioinfo, dwRenameFlags); } // --------- LONG WINAPI ExportApiWinMMMMIOSeek(HMMIO hmmio, LONG lOffset, int iOrigin) { return ImportApiWinMM::mmioSeek(hmmio, lOffset, iOrigin); } // --------- LRESULT WINAPI ExportApiWinMMMMIOSendMessage(HMMIO hmmio, UINT wMsg, LPARAM lParam1, LPARAM lParam2) { return ImportApiWinMM::mmioSendMessage(hmmio, wMsg, lParam1, lParam2); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOSetBuffer(HMMIO hmmio, LPSTR pchBuffer, LONG cchBuffer, UINT wFlags) { return ImportApiWinMM::mmioSetBuffer(hmmio, pchBuffer, cchBuffer, wFlags); } // --------- MMRESULT WINAPI ExportApiWinMMMMIOSetInfo(HMMIO hmmio, LPCMMIOINFO lpmmioinfo, UINT wFlags) { return ImportApiWinMM::mmioSetInfo(hmmio, lpmmioinfo, wFlags); } // --------- FOURCC WINAPI ExportApiWinMMMMIOStringToFOURCCA(LPCSTR sz, UINT wFlags) { return ImportApiWinMM::mmioStringToFOURCCA(sz, wFlags); } // --------- FOURCC WINAPI ExportApiWinMMMMIOStringToFOURCCW(LPCWSTR sz, UINT wFlags) { return ImportApiWinMM::mmioStringToFOURCCW(sz, wFlags); } // --------- LONG WINAPI ExportApiWinMMMMIOWrite(HMMIO hmmio, const char* pch, LONG cch) { return ImportApiWinMM::mmioWrite(hmmio, pch, cch); } // --------- BOOL WINAPI ExportApiWinMMSndPlaySoundA(LPCSTR lpszSound, UINT fuSound) { return ImportApiWinMM::sndPlaySoundA(lpszSound, fuSound); } // --------- BOOL WINAPI ExportApiWinMMSndPlaySoundW(LPCWSTR lpszSound, UINT fuSound) { return ImportApiWinMM::sndPlaySoundW(lpszSound, fuSound); } // --------- MMRESULT WINAPI ExportApiWinMMTimeBeginPeriod(UINT uPeriod) { return ImportApiWinMM::timeBeginPeriod(uPeriod); } // --------- MMRESULT WINAPI ExportApiWinMMTimeEndPeriod(UINT uPeriod) { return ImportApiWinMM::timeEndPeriod(uPeriod); } // --------- MMRESULT WINAPI ExportApiWinMMTimeGetDevCaps(LPTIMECAPS ptc, UINT cbtc) { return ImportApiWinMM::timeGetDevCaps(ptc, cbtc); } // --------- MMRESULT WINAPI ExportApiWinMMTimeGetSystemTime(LPMMTIME pmmt, UINT cbmmt) { return ImportApiWinMM::timeGetSystemTime(pmmt, cbmmt); } // --------- DWORD WINAPI ExportApiWinMMTimeGetTime(void) { return ImportApiWinMM::timeGetTime(); } // --------- MMRESULT WINAPI ExportApiWinMMTimeKillEvent(UINT uTimerID) { return ImportApiWinMM::timeKillEvent(uTimerID); } // --------- MMRESULT WINAPI ExportApiWinMMTimeSetEvent(UINT uDelay, UINT uResolution, LPTIMECALLBACK lpTimeProc, DWORD_PTR dwUser, UINT fuEvent) { return ImportApiWinMM::timeSetEvent(uDelay, uResolution, lpTimeProc, dwUser, fuEvent); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInAddBuffer(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh) { return ImportApiWinMM::waveInAddBuffer(hwi, pwh, cbwh); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInClose(HWAVEIN hwi) { return ImportApiWinMM::waveInClose(hwi); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInGetDevCapsA(UINT_PTR uDeviceID, LPWAVEINCAPSA pwic, UINT cbwic) { return ImportApiWinMM::waveInGetDevCapsA(uDeviceID, pwic, cbwic); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInGetDevCapsW(UINT_PTR uDeviceID, LPWAVEINCAPSW pwic, UINT cbwic) { return ImportApiWinMM::waveInGetDevCapsW(uDeviceID, pwic, cbwic); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInGetErrorTextA(MMRESULT mmrError, LPCSTR pszText, UINT cchText) { return ImportApiWinMM::waveInGetErrorTextA(mmrError, pszText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInGetErrorTextW(MMRESULT mmrError, LPWSTR pszText, UINT cchText) { return ImportApiWinMM::waveInGetErrorTextW(mmrError, pszText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInGetID(HWAVEIN hwi, LPUINT puDeviceID) { return ImportApiWinMM::waveInGetID(hwi, puDeviceID); } // --------- UINT WINAPI ExportApiWinMMWaveInGetNumDevs(void) { return ImportApiWinMM::waveInGetNumDevs(); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInGetPosition(HWAVEIN hwi, LPMMTIME pmmt, UINT cbmmt) { return ImportApiWinMM::waveInGetPosition(hwi, pmmt, cbmmt); } // --------- DWORD WINAPI ExportApiWinMMWaveInMessage(HWAVEIN deviceID, UINT uMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { return ImportApiWinMM::waveInMessage(deviceID, uMsg, dwParam1, dwParam2); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInOpen(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwCallbackInstance, DWORD fdwOpen) { return ImportApiWinMM::waveInOpen(phwi, uDeviceID, pwfx, dwCallback, dwCallbackInstance, fdwOpen); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInPrepareHeader(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh) { return ImportApiWinMM::waveInPrepareHeader(hwi, pwh, cbwh); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInReset(HWAVEIN hwi) { return ImportApiWinMM::waveInReset(hwi); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInStart(HWAVEIN hwi) { return ImportApiWinMM::waveInStart(hwi); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInStop(HWAVEIN hwi) { return ImportApiWinMM::waveInStop(hwi); } // --------- MMRESULT WINAPI ExportApiWinMMWaveInUnprepareHeader(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh) { return ImportApiWinMM::waveInUnprepareHeader(hwi, pwh, cbwh); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutBreakLoop(HWAVEOUT hwo) { return ImportApiWinMM::waveOutBreakLoop(hwo); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutClose(HWAVEOUT hwo) { return ImportApiWinMM::waveOutClose(hwo); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetDevCapsA(UINT_PTR uDeviceID, LPWAVEOUTCAPSA pwoc, UINT cbwoc) { return ImportApiWinMM::waveOutGetDevCapsA(uDeviceID, pwoc, cbwoc); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetDevCapsW(UINT_PTR uDeviceID, LPWAVEOUTCAPSW pwoc, UINT cbwoc) { return ImportApiWinMM::waveOutGetDevCapsW(uDeviceID, pwoc, cbwoc); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetErrorTextA(MMRESULT mmrError, LPCSTR pszText, UINT cchText) { return ImportApiWinMM::waveOutGetErrorTextA(mmrError, pszText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetErrorTextW(MMRESULT mmrError, LPWSTR pszText, UINT cchText) { return ImportApiWinMM::waveOutGetErrorTextW(mmrError, pszText, cchText); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetID(HWAVEOUT hwo, LPUINT puDeviceID) { return ImportApiWinMM::waveOutGetID(hwo, puDeviceID); } // --------- UINT WINAPI ExportApiWinMMWaveOutGetNumDevs(void) { return ImportApiWinMM::waveOutGetNumDevs(); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetPitch(HWAVEOUT hwo, LPDWORD pdwPitch) { return ImportApiWinMM::waveOutGetPitch(hwo, pdwPitch); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetPlaybackRate(HWAVEOUT hwo, LPDWORD pdwRate) { return ImportApiWinMM::waveOutGetPlaybackRate(hwo, pdwRate); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetPosition(HWAVEOUT hwo, LPMMTIME pmmt, UINT cbmmt) { return ImportApiWinMM::waveOutGetPosition(hwo, pmmt, cbmmt); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutGetVolume(HWAVEOUT hwo, LPDWORD pdwVolume) { return ImportApiWinMM::waveOutGetVolume(hwo, pdwVolume); } // --------- DWORD WINAPI ExportApiWinMMWaveOutMessage(HWAVEOUT deviceID, UINT uMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { return ImportApiWinMM::waveOutMessage(deviceID, uMsg, dwParam1, dwParam2); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutOpen(LPHWAVEOUT phwo, UINT_PTR uDeviceID, LPWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwCallbackInstance, DWORD fdwOpen) { return ImportApiWinMM::waveOutOpen(phwo, uDeviceID, pwfx, dwCallback, dwCallbackInstance, fdwOpen); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutPause(HWAVEOUT hwo) { return ImportApiWinMM::waveOutPause(hwo); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutPrepareHeader(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh) { return ImportApiWinMM::waveOutPrepareHeader(hwo, pwh, cbwh); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutReset(HWAVEOUT hwo) { return ImportApiWinMM::waveOutReset(hwo); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutRestart(HWAVEOUT hwo) { return ImportApiWinMM::waveOutRestart(hwo); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutSetPitch(HWAVEOUT hwo, DWORD dwPitch) { return ImportApiWinMM::waveOutSetPitch(hwo, dwPitch); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutSetPlaybackRate(HWAVEOUT hwo, DWORD dwRate) { return ImportApiWinMM::waveOutSetPlaybackRate(hwo, dwRate); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutSetVolume(HWAVEOUT hwo, DWORD dwVolume) { return ImportApiWinMM::waveOutSetVolume(hwo, dwVolume); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutUnprepareHeader(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh) { return ImportApiWinMM::waveOutUnprepareHeader(hwo, pwh, cbwh); } // --------- MMRESULT WINAPI ExportApiWinMMWaveOutWrite(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh) { return ImportApiWinMM::waveOutWrite(hwo, pwh, cbwh); } }
b72266b5c5489fc6c31f2c2979b883bf1965c242
d2190cbb5ea5463410eb84ec8b4c6a660e4b3d0e
/old_hydra/hydra/tags/aug04/mdcutil/hmdcoffset.h
b3832aba53e0a2d2696787567391ba9d5d0480ec
[]
no_license
wesmail/hydra
6c681572ff6db2c60c9e36ec864a3c0e83e6aa6a
ab934d4c7eff335cc2d25f212034121f050aadf1
refs/heads/master
2021-07-05T17:04:53.402387
2020-08-12T08:54:11
2020-08-12T08:54:11
149,625,232
0
0
null
null
null
null
UTF-8
C++
false
false
8,866
h
hmdcoffset.h
#ifndef HMDCOFFSET_H #define HMDCOFFSET_H #include "hreconstructor.h" #include "hstartdef.h" #include "hmdctimecut.h" #include "hlocation.h" #define HEX_NAN 0x7fc00000 typedef Int_t MyInt; typedef Float_t MyFloat; typedef TH1F MyHist; class TFile; class HCategory; class HIterator; class HMdcCalPar; class HMdcCalParRaw; class HMdcLookupGeom; class HMdcLookupRaw; class HMdcTimeCut; class HMdcSizesCells; class TH2F; class TNtuple; class TF1; class TString; typedef MyInt MyField[6][4][16][96][2048]; class HMdcOffset : public HReconstructor { protected: static const Int_t nbin; // Number of bins ih the histogramms static const Int_t nbinm1; // nbin - 1 static const Int_t nbinp1; // nbin + 1 static const Int_t nSubEvents; // The max. number of objects per event HCategory *rawCat; // pointer to the raw data HCategory* hitStartCat; // pointer to the cal data HCategory* clusCat; // pointer to the cluster data HIterator *iter; // iterator on raw data HIterator* iter_start; // iterator on start cal data. HIterator* iter_clus; // iterator on clus data. HLocation locraw; // HMdcCalParRaw *calparraw; // pointer to HMdcCalParRaw container HMdcTimeCut *timecut; // pointer to HMdcTimeCut container HMdcLookupGeom *lookupgeom; // pointer to HMdcLookupGeom container HMdcLookupRaw *lookupraw; // pointer to HMdcLookupRaw container HMdcSizesCells *sizescells; // pointer to HMdcSizesCells container Float_t signalspeed; //! speed of the signal on the wire [ns/mm] Int_t eventcounter; Int_t skipcounter; Int_t nSkipEvents; // number of skipped events per file Int_t nStep; // step size for print events Float_t validRange; // allowed interval arround mean of offsets Bool_t isPulserFile; // flag for a external calibration file (pulser) Bool_t noStart; // flag if starttime should not be used Bool_t useTimeCuts; // switch on/off time cuts usage Bool_t useClusters; // switch on/off clusters/raw Bool_t useWireOffset; // switch on/off substraction of signal time on wire Bool_t useTof; // switch on/off substraction of minimum tof Char_t *fNameAsciiOffset; // file name of ascii output file Char_t *fNameRootOffset; // file name of root output file FILE *ferrorlog; // File pointer to errorlog TNtuple* offsetTuple; // pointer to NTuple for offset TNtuple* offsetPulserTuple; // pointer to NTuple for multiple peaks of pulser files Float_t minfitthreshold; // minimum threshold for linear fit (y-range) Float_t maxfitthreshold; // maximum threshold for linear fit (y-range) Int_t offsetfitNoise; // offset of the fit range for the subtraction of the noise (start at yequalzero going to the left) Int_t widthfitNoise; // width of the fit range Int_t rangeGauss; // fit range of the gaussian fit around calculated offset MyField *hreverse; // array for the drift-time (Time1) to be filled in eventloop MyHist *hinv; // drift-time histograms to hold collected data MyHist *hint; // integrated drift-time histograms MyHist *htime1temp; // temp drift-time histogram TH2F *htime1_mbo[16]; // 2-D hist time1 vers tdc TH2F *htime1_lay[6]; // 2-D hist time1 vers cell TF1* toffunc[4][6]; // TF1 fits for minimum tof MyFloat yequalzero; // intersection point of the first fit and the x-axis MyFloat crosspointX; // x-value of the intersection point of the two linear fits->offset MyFloat fitpar0; // first fit parameter of the first linear fit MyFloat fitpar0error; // error of the first fit parameter of the first linear fit MyFloat fitpar1; // second fit parameter of the first linear fit MyFloat fitpar1error; // error of the second fit parameter of the first linear fit MyFloat fitparNoise0; // first fit parameter of the second linear fit MyFloat fitparNoise0error; // error of the first fit parameter of the second linear fit MyFloat fitparNoise1; // second fit parameter of the second linear fit MyFloat fitparNoise1error; // error of the second fit parameter of the second linear fit MyFloat totalsigma; // sigma of the offset calculated from the sigmas of the two linear fits MyFloat fitGaussMean; // mean of the gaussian fit MyFloat fitGaussSigma; // sigma of the gaussian fit Float_t meanhOffset; Float_t offsets[6][4][16][96]; Float_t offsetErr[6][4][16][96]; Float_t offset1[6][4][16][96]; Int_t integral[6][4][16][96]; Float_t fitslope1[6][4][16][96]; Float_t fitslope2[6][4][16][96]; Float_t offsetpulser[6][4][16][96][5]; Float_t myoffset; Float_t myerror; public: HMdcOffset(); HMdcOffset(Text_t* name,Text_t* title); ~HMdcOffset(); Bool_t init(); Bool_t reinit(); Bool_t finalize(); Int_t execute(); void setSignalSpeed(Float_t speed) {signalspeed=speed;} void setCounter(Int_t size) {nStep=size;} void setOutputAscii(Char_t*); void setOutputRoot (Char_t*); void setPulserFile() {isPulserFile=kTRUE;} void setNotUseStart(Bool_t nouse){noStart=nouse;} void setUseClusters(Bool_t use) {useClusters=use;} void setUseWireOffset(Bool_t use){useWireOffset=use;} void setUseTof(TString inp); void setNSkipEvents(Int_t nskipevents){nSkipEvents=nskipevents;} void setValidOffsetRange(Float_t range){validRange=range;} void setUseTimeCuts(Bool_t cut){useTimeCuts=cut;} void setNoiseOffset(Int_t i) {offsetfitNoise =i;} void setNoiseWidth (Int_t i) {widthfitNoise =i;} void setThresholdMin(Float_t f) {minfitthreshold=f;} void setThresholdMax(Float_t f) {maxfitthreshold=f;} void setNoise(Int_t o, Int_t w) {offsetfitNoise=o; widthfitNoise=w;} void setThreshold(Float_t min, Float_t max) {minfitthreshold=min; maxfitthreshold=max;} void setRangeGauss(Int_t i) {rangeGauss=i;} protected: Int_t executeRaw(); Int_t executeClus(); Bool_t isNaN(MyFloat f) {return *((long int*)&f)==HEX_NAN;} void setDefault(); ofstream *openAsciiFile(); TDirectory *Mkdir(TDirectory *, Char_t *, Int_t, Int_t p=1); void createHist(TFile*,Int_t, Int_t, Int_t, Int_t); void createHist_2D(Int_t, Int_t); void fillHist (Int_t, Int_t, Int_t, Int_t); void fillHist_2D(Int_t, Int_t, Int_t, Int_t); Int_t fitHist (Int_t, Int_t, Int_t, Int_t); void writeHist (TFile*); void writeHist_2D(); void deleteHist(); void deleteHist_2D(); void fillNTuples(Int_t, Int_t, Int_t, Int_t); Float_t getstarttime(); void writeAscii(ofstream&, Int_t, Int_t, Int_t, Int_t); void initVariables(); void findMultiplePeaks(Int_t,Int_t,Int_t,Int_t); void initMemory() { for(Int_t s=0;s<6;s++) { for(Int_t m=0;m<4;m++) { for(Int_t mb=0;mb<16;mb++) { for(Int_t t=0;t<96;t++) { for(Int_t bin=0;bin<2048;bin++) { (*hreverse) [s][m][mb][t][bin]=0; } } } } } } void initArrays() { for(Int_t s=0; s<6; s++){ for(Int_t mo=0; mo<4; mo++){ for(Int_t mb=0; mb<16; mb++){ for(Int_t t=0; t<96; t++){ offsets[s][mo][mb][t]=0; offsetErr[s][mo][mb][t]=0; offset1[s][mo][mb][t]=0; integral[s][mo][mb][t]=0; fitslope1[s][mo][mb][t]=0; fitslope2[s][mo][mb][t]=0; for(Int_t j=0; j<5; j++) { offsetpulser[s][mo][mb][t][j]=0; } } } } } } Bool_t testTimeCuts(Int_t s, Int_t m,Float_t t1,Float_t t2) { if(timecut->cutTime1(s,m,t1)&& timecut->cutTime2(s,m,t2)&& timecut->cutTimesDif(s,m,t2,t1)) return kTRUE; else return kFALSE; } void fillArrays(TH1F*,Int_t, Int_t, Int_t, Int_t); void fillCalParRaw(TH1F*,Int_t, Int_t, Int_t, Int_t); void printStatus(); public: // This has to be placed at the end (--> root dox) ClassDef(HMdcOffset, 0) // class for the calculation of the offsets per tdc channel }; #endif /* !HMDCOFFSET_H */
ce9993efe7e3129aa8a6f8caff99cd7f08f7df45
0a669f975928aa153ecd643f82d4133b253cc1dd
/Widgets/MainWidget/headerwidget.h
d3f54652e7a7b719f84cd93be51fde6e31a32441
[]
no_license
ZhaZhaXie1024/XHotel
29c951ea840c790871d0b93d5ed5f923d4f26827
5207d4b7b94b787d98e1f8eed24157aa99972351
refs/heads/main
2023-09-01T04:27:59.885947
2021-10-30T06:56:23
2021-10-30T06:56:23
328,307,148
3
0
null
null
null
null
UTF-8
C++
false
false
721
h
headerwidget.h
#ifndef HEADERWIDGET_H #define HEADERWIDGET_H #include <QWidget> /** * @brief RETCODE_RESTART * * define a retcode:773 = 'r'+'e'+'s'+'t'+'a'+'r'+'t' = restart * * 即为 重启 的意思 */ static const int RETCODE_RESTART = 773; namespace Ui { class HeaderWidget; } class HeaderWidget : public QWidget { Q_OBJECT public: explicit HeaderWidget(QWidget *parent = nullptr); HeaderWidget(QString operatorName,QWidget *parent = nullptr); ~HeaderWidget(); //初始化 void init(); //设置用户名称 void setUserName(QString name = "用户名"); public slots: //注销登录按钮 void onLoginOutBtn(); private: Ui::HeaderWidget *ui; }; #endif // HEADERWIDGET_H
154e1c5dc6c3c2640e10add95d1a777b41027f8c
8b71e5bf7385f545ef5b2542d98655e5bfacb41c
/examples/CouplingLBNS/components/java/cca/cfd/NSAbstractImplementation.h
6b55705084f9c50b5f9ba89dfa33c40810136bac
[]
no_license
ascodt-users/ascodt-nightly
1494f695ffb6ef22c81a36c379beb9ec8837325f
35d8222c9ea39ece35987c97946fd9fd0f7e794a
refs/heads/master
2020-05-31T08:45:35.308852
2014-09-22T03:43:39
2014-09-22T03:43:39
10,525,634
0
0
null
null
null
null
UTF-8
C++
false
false
2,350
h
NSAbstractImplementation.h
#ifndef CCA_CFD_NSABSTRACTIMPLEMENTATION_H_ #define CCA_CFD_NSABSTRACTIMPLEMENTATION_H_ // // ASCoDT - Advanced Scientific Computing Development Toolkit // // This file was generated by ASCoDT's simplified SIDL compiler. // // Authors: Tobias Weinzierl, Atanas Atanasov // #include "cca/cfd/LBSolverNativeDispatcher.h" #include "cca/cfd/NSSolver.h" #include "cca/cfd/NS2LB.h" #include "Component.h" namespace cca { namespace cfd { class NSAbstractImplementation; } } class cca::cfd::NSAbstractImplementation: public Component ,public cca::cfd::NSSolver,public cca::cfd::NS2LB{ protected: cca::cfd::LBSolverNativeDispatcher* _lb; public: NSAbstractImplementation(); virtual ~NSAbstractImplementation(); /** * @see Case class */ void connectlb(cca::cfd::LBSolverNativeDispatcher* port); void disconnectlb(); void retrievePressureCopyParallel(double* pressure, const int pressure_len); void retrieveJacobianCopyParallel(double* jacobian, const int jacobian_len); void retrieveVelocitiesCopyParallel(double* velocityX, const int velocityX_len,double* velocityY, const int velocityY_len,double* velocityZ, const int velocityZ_len); void retrieveVelocitiesSizeParallel(int& memory); void retrieveTimestepParallel(double& timestep); void iterateParallel(); void syncrParallel(int& value); void plotParallel(); void forwardVelocitiesParallel(const int* keys, const int keys_len,const int* offsets, const int offsets_len,const int* flips, const int flips_len,const double* values, const int values_len,int& ackn); void iterateInnerParallel(); void iterateBoundaryParallel(); void closeNSProfilesParallel(); void printNSProfilesParallel(); void printNSPressureParallel(); void setVelocitiesParallel(const double* velocitiesX, const int velocitiesX_len,const double* velocitiesY, const int velocitiesY_len,const double* velocitiesZ, const int velocitiesZ_len); void solveOneTimestepPhaseTwoParallel(); void solveOneTimestepPhaseOneParallel(); void solveParallel(); void setupCommForLBRegionParallel(const int* startOfRegion, const int startOfRegion_len,const int* endOfRegion, const int endOfRegion_len,const std::string* commids, const int commids_len); void setupParallel(const std::string inputScenario); }; #endif
91a6911e22e0e78026e7a2271362f869c988db59
815c1e11221e7ceff832b2b41a60ae760c56b269
/parser.cpp
8e7da62826b8b9428b5474a5a14f6f10b9b58ee2
[]
no_license
jerry-peng/llvm-kaleidoscope
36d4818849eb94fa0c45791570032f4455e17d2c
b22b788eb33c66ec2e6ef55c5544eb3a523155b5
refs/heads/master
2020-03-27T16:30:16.179513
2019-12-25T14:18:29
2019-12-25T14:18:29
146,787,569
0
0
null
null
null
null
UTF-8
C++
false
false
7,192
cpp
parser.cpp
#include "parser.h" std::unique_ptr<ExprAST> log_error_e(const char *str) { log_error(str); return nullptr; } std::unique_ptr<PrototypeAST> log_error_p(const char *str) { log_error(str); return nullptr; } // cur_tok/get_next_tok() - provide a simple token buffer int get_next_tok() { return cur_tok = gettok(); } // NumberExpr ::= number std::unique_ptr<ExprAST> parse_number_expr() { auto result = llvm::make_unique<NumberExprAST>(num_val); get_next_tok(); return std::move(result); } // ParenExpr ::= '(' Expr ')' std::unique_ptr<ExprAST> parse_paren_expr() { // eat '(' get_next_tok(); auto V = parse_expression(); if (!V) return nullptr; if (cur_tok != ')') return log_error_e("expected ')'"); //eat ')' get_next_tok(); return V; } // IdentifierExpr ::= identifier // ::= identifier '(' expression* ')' // The second production for function calls std::unique_ptr<ExprAST> parse_identifier_expr() { std::string id_name = identifier_str; //eat identifier. get_next_tok(); // For simple variable reference if (cur_tok != '(') { return llvm::make_unique<VariableExprAST>(id_name); } // For function calls get_next_tok(); std::vector<std::unique_ptr<ExprAST>> args; if (cur_tok != ')') { while (1) { if (auto arg = parse_expression()) { args.push_back(std::move(arg)); } else { return nullptr; } if (cur_tok == ')') { break; } if (cur_tok != ',') return log_error_e("Expected ')' or ',' in argument list"); get_next_tok(); } } // eat ')' get_next_tok(); return llvm::make_unique<CallExprAST>(id_name, std::move(args)); } // Primary ::= IdentifierExpr // ::= NumberExpr // ::= ParenExpr std::unique_ptr<ExprAST> parse_primary() { switch (cur_tok) { default: return log_error_e("unknown token when expecting an expression"); case tok_identifier: return parse_identifier_expr(); case tok_number: return parse_number_expr(); case '(': return parse_paren_expr(); } } // get_tok_precedence - Get the precedence of binary operator token int get_tok_precedence() { if (!isascii(cur_tok)) return -1; // Make sure it's a declared binary operator int tok_prec = bin_op_precedence[cur_tok]; if (tok_prec <= 0) return -1; return tok_prec; } // bin_op_rhs ::= ('+' primary)* std::unique_ptr<ExprAST> parse_bin_op_rhs(int expr_prec, std::unique_ptr<ExprAST> LHS) { // If this is a binary operator, find its precedence while (1) { int tok_prec = get_tok_precedence(); // If this is a binary operator that holds at least as tightly as the current // binary operator, consume it, otherwise we are done. if (tok_prec < expr_prec) { return LHS; } int bin_op = cur_tok; get_next_tok(); // Parse the primary expression after the binary operator auto RHS = parse_primary(); if (!RHS) return nullptr; // If binary operator binds less tightly with RHS than the operator after RHS, let // the pending operator take RHS as its LHS int next_prec = get_tok_precedence(); if (tok_prec < next_prec) { RHS = parse_bin_op_rhs(tok_prec + 1, std::move(RHS)); if (!RHS) { return nullptr; } } // Merge LHS/RHS LHS = llvm::make_unique<BinaryOpExprAST>(bin_op, std::move(LHS), std::move(RHS)); } } // expression ::= primary bin_op_rhs std:: unique_ptr<ExprAST> parse_expression() { auto LHS = parse_primary(); if (!LHS) { return nullptr; } return parse_bin_op_rhs(0, std::move(LHS)); } // prototype ::= id '(' id* ')' std::unique_ptr<PrototypeAST> parse_prototype() { if (cur_tok != tok_identifier) { return log_error_p("Expected function name in prototype"); } std::string fn_name = identifier_str; get_next_tok(); if (cur_tok != '(') { return log_error_p("Expected '(' in prototype"); } // Read the list of argument names std::vector<std::string> arg_names; while (get_next_tok() == tok_identifier) { arg_names.push_back(identifier_str); } if (cur_tok != ')') { return log_error_p("Expected ')' in prototype"); } // success get_next_tok(); return llvm::make_unique<PrototypeAST>(fn_name, std::move(arg_names)); } // definition ::= 'def' prototype expression std::unique_ptr<FunctionAST> parse_definition() { // eat def get_next_tok(); auto proto = parse_prototype(); if (!proto) { return nullptr; } if (auto expr = parse_expression()) { return llvm::make_unique<FunctionAST>(std::move(proto), std::move(expr)); } return nullptr; } // external ::= 'extern' prototype std::unique_ptr<PrototypeAST> parse_extern() { // eat extern get_next_tok(); return parse_prototype(); } // top_level_expr ::= expression std::unique_ptr<FunctionAST> parse_top_level_expr() { if (auto expr = parse_expression()) { // Make an anonymous proto auto proto = llvm::make_unique<PrototypeAST>("", std::vector<std::string>()); return llvm::make_unique<FunctionAST>(std::move(proto), std::move(expr)); } return nullptr; } // top ::= definition | external | expression | ';' void main_loop() { while(1) { fprintf(stderr, "ready> "); switch (cur_tok) { case tok_eof: return; case ';': // ignore top-level semicolons get_next_tok(); break; case tok_def: handle_definition(); break; case tok_extern: handle_extern(); break; default: handle_top_level_expression(); break; } } } void handle_definition() { if (auto fn_AST = parse_definition()) { if (auto *fn_IR = fn_AST->codegen()) { fprintf(stderr, "Read function definition."); fn_IR->print(errs()); fprintf(stderr, "\n"); } } else { // Skip token for error recovery get_next_tok(); } } void handle_extern() { if (auto proto_AST = parse_extern()) { if (auto *fn_IR = proto_AST->codegen()) { fprintf(stderr, "Read extern"); fn_IR->print(errs()); fprintf(stderr, "\n"); } } else { // Skip token for error recovery get_next_tok(); } } void handle_top_level_expression() { // Evaluate a top-level expression into an anonymous function if (auto fn_AST = parse_top_level_expr()) { if (auto *fn_IR = fn_AST->codegen()) { fprintf(stderr, "Read top-level expression"); fn_IR->print(errs()); fprintf(stderr, "\n"); } } else { // Skip token for error recovery. get_next_tok(); } }
fa0ec14a0d8682da89ee7d22acc7d9ee9e4c2377
9b786a416df97d9ab806d8601b4f1f1fae777715
/3033/escape-from-enemy-territory.cc
4c9a588857d3bee2690fb908f1af5d4b7f44a741
[]
no_license
ailyanlu/tju
b5368074141140b674119e575da24931fe7d7646
57f16b9226266dd19be49110c524c68c12c328f1
refs/heads/master
2018-01-15T16:35:42.653356
2011-01-24T01:16:47
2011-01-24T01:16:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,326
cc
escape-from-enemy-territory.cc
#include <cstdio> #include <algorithm> #include <iostream> #include <cstdlib> #include <cmath> #include <map> #include <vector> #include <queue> #include <set> using namespace std; #define FOR(i, x) for (int i = 0; i < x; i++) #define FORI(i,a, x) for (int i = a; i < x; i++) #define ALL(x) (x).begin(), (x).end() #define FORE(i, x) for (__typeof__((x).begin()) i = (x).begin(); i != (x).end(); i++) #define SZ(x) ((int) (x).size()) #define EPS 1E-10 #define INF 0x3F3F3F3F #define MAX 1000 #define INSERT(q,x) q.push(x); int main() { int x, y, xx, yy, T, N, X, Y, xr, yr, s; int bx, by; scanf("%d",&T); while(T--) { queue<int> Q; scanf("%d%d%d",&N,&X,&Y); vector< vector<int> > F(X, vector<int>(Y, -1)); scanf("%d%d%d%d",&xx,&yy,&xr,&yr); FOR(i,N) { scanf("%d%d",&bx,&by); INSERT(Q,bx); INSERT(Q,by); F[bx][by]=0; } while(!Q.empty()) { x = Q.front(); Q.pop(); y = Q.front(); Q.pop(); s = F[x][y]; if(x+1<X && F[x+1][y]==-1) { F[x+1][y] = s+1; INSERT(Q,x+1); INSERT(Q,y); } if(y+1<Y && F[x][y+1]==-1) { F[x][y+1] = s+1; INSERT(Q,x); INSERT(Q,y+1); } if(x-1>=0 && F[x-1][y]==-1) { F[x-1][y] = s+1; INSERT(Q,x-1); INSERT(Q,y); } if(y-1>=0 && F[x][y-1]==-1) { F[x][y-1] = s+1; INSERT(Q,x); INSERT(Q,y-1); } } int d[][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int lo = -1, hi = min(F[xx][yy], F[xr][yr]), m; int lim; while(lo!=hi) { vector< vector<int> > r(X, vector<int>(Y, INF)); m=(lo+hi+1)/2; INSERT(Q,xx); INSERT(Q,yy); r[xx][yy]=0; while(!Q.empty()) { x = Q.front(); Q.pop(); y = Q.front(); Q.pop(); FOR(i,4) { if(x+d[i][0]>=X || x+d[i][0]<0 || y+d[i][1]>=Y || y+d[i][1]<0) continue; if(m<=F[x+d[i][0]][y+d[i][1]] && r[x][y]+1<r[x+d[i][0]][y+d[i][1]]) { r[x+d[i][0]][y+d[i][1]]=r[x][y]+1; INSERT(Q,x+d[i][0]); INSERT(Q,y+d[i][1]); } } } if(r[xr][yr]!=INF) lim=m, lo=m, s=r[xr][yr]; else hi=m-1; } printf("%d %d\n",lim,s); } return 0; }
0514654154da31b4e654a753a510f38307f7d0ab
0dc970a658392a7f68bb37ba4d04a01134f5f96c
/GCodeExporter.h
f68c29150e2acab4d388b5083b3feba72e41229c
[ "MIT" ]
permissive
AwesomeCNC/CncClock
cde89c011258ba054180262ec672686c50af82d2
93fb78d59ff7ed87515056ea01a8bd0452a45dd9
refs/heads/master
2021-12-20T17:52:10.919616
2017-04-15T05:16:02
2017-04-15T05:16:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
h
GCodeExporter.h
#pragma once // TODO: Exports GCode given a series of parts. // Also displays what the parts will look like once exported, accounting for bit radius. class GCodeExporter { public: GCodeExporter(); ~GCodeExporter(); };
2fda194b90163b0d27a3af489e740bcca62eeeb2
c4eaa3e6cdca0ef6eea9487735369fb4d215949f
/2DAE07_Geers_Pieter_digdug/Minigin/SMState.cpp
76ba2f4d55a4b646bda2abdcce17ae3974a211ad
[]
no_license
PieterGeers/DigDug
483fc09f6425501aea7e690831517d695c56bea2
b69e05ca025558a089d1d10bda1ee01677292a54
refs/heads/master
2022-02-26T02:42:53.016532
2019-10-31T15:37:02
2019-10-31T15:37:02
175,878,736
0
0
null
null
null
null
UTF-8
C++
false
false
3,505
cpp
SMState.cpp
#include "MiniginPCH.h" #include "SMState.h" #include "SMAction.h" #include "SMTransition.h" #include "Debug.h" SMState::SMState(std::vector<SMAction*> entryActions, std::vector<SMAction*> actions, std::vector<SMAction*> exitActions, std::vector<SMTransition*> transitions) :m_EntryActions(entryActions) ,m_Actions(actions) ,m_ExitActions(exitActions) ,m_Transitions(transitions) { } SMState::~SMState() { for (auto a : m_EntryActions) { if (a != nullptr) { delete a; a = nullptr; } } for (auto a : m_ExitActions) { if (a != nullptr) { delete a; a = nullptr; } } for (auto a : m_Actions) { if (a != nullptr) { delete a; a = nullptr; } } for (auto a : m_Transitions) { if (a != nullptr) { delete a; a = nullptr; } } } void SMState::SetEntryActions(std::vector<SMAction*> entryActions) { for (auto action : entryActions) { const auto it = std::find(m_EntryActions.begin(), m_EntryActions.end(), action); if (it == m_EntryActions.end()) m_EntryActions.push_back(action); else Debug::LogWarning("Trying to add the same EntryActions twice"); } } void SMState::SetEntryAction(SMAction* entryAction) { const auto it = std::find(m_EntryActions.begin(), m_EntryActions.end(), entryAction); if (it == m_EntryActions.end()) m_EntryActions.push_back(entryAction); else Debug::LogWarning("Trying to add the same EntryActions twice"); } void SMState::SetActions(std::vector<SMAction*> actions) { for (auto action : actions) { const auto it = std::find(m_Actions.begin(), m_Actions.end(), action); if (it == m_Actions.end()) m_Actions.push_back(action); else Debug::LogWarning("Trying to add the same Actions twice"); } } void SMState::SetAction(SMAction* action) { const auto it = std::find(m_Actions.begin(), m_Actions.end(), action); if (it == m_Actions.end()) m_Actions.push_back(action); else Debug::LogWarning("Trying to add the same Actions twice"); } void SMState::SetExitActions(std::vector<SMAction*> exitActions) { for (auto action : exitActions) { const auto it = std::find(m_ExitActions.begin(), m_ExitActions.end(), action); if (it == m_ExitActions.end()) m_ExitActions.push_back(action); else Debug::LogWarning("Trying to add the same ExitActions twice"); } } void SMState::SetExitAction(SMAction* exitAction) { const auto it = std::find(m_ExitActions.begin(), m_ExitActions.end(), exitAction); if (it == m_ExitActions.end()) m_ExitActions.push_back(exitAction); else Debug::LogWarning("Trying to add the same ExitActions twice"); } void SMState::SetTransitions(std::vector<SMTransition*> transitions) { for (auto action : transitions) { const auto it = std::find(m_Transitions.begin(), m_Transitions.end(), action); if (it == m_Transitions.end()) m_Transitions.push_back(action); else Debug::LogWarning("Trying to add the same Transition twice"); } } void SMState::SetTransition(SMTransition* transition) { const auto it = std::find(m_Transitions.begin(), m_Transitions.end(), transition); if (it == m_Transitions.end()) m_Transitions.push_back(transition); else Debug::LogWarning("Trying to add the same Transition twice"); } void SMState::RunAction(int idx) const { for (auto action : m_Actions) action->Invoke(idx); } void SMState::RunEntryActions(int idx) const { for (auto action : m_EntryActions) action->Invoke(idx); } void SMState::RunExitActions(int idx) const { for (auto action : m_ExitActions) action->Invoke(idx); }
5e74362947caf9d80f4efc07e0136056fc0dc065
f405ecb43b6fd95778020101eee4163340e747ff
/energy_monitoring_210_v3.ino
aa37d7275d6c2bc28e22fc890267cbc212c1d150
[]
no_license
caletagreen/Automation
61e45703540c669942edc4b7e441ebbcf1af9c8d
04bea4765958608855029138d074f60345863394
refs/heads/master
2021-01-18T21:24:21.550521
2018-03-05T04:39:05
2018-03-05T04:39:05
35,110,961
2
1
null
null
null
null
UTF-8
C++
false
false
4,069
ino
energy_monitoring_210_v3.ino
/* www.caletagreen.com Energy monitoring 210 V. Store data on m2mlight.com: - Real power consumption of cooktop - Real power of the house (210 V) - Input voltage of the house - Input currents (phase1 and phase2) of the house Use m2mData arduino library (https://github.com/m2mlight/m2mData) First, define sensors on m2mlight.com and obtain api_key identifiers Credits: - https://roysoala.wordpress.com/2012/04/20/energy-monitoring-using-pachube-and-arduino-1-0/ */ // Define what libraries to load #include "EmonLib.h" #include <SPI.h> #include <Ethernet.h> #include <m2mData.h> // Configure the Ethernet Shield byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0xE4, 0x61 }; // arduino mac address byte ip[] = { 192, 168, 1, 15 }; // arduino ip address // Variables EnergyMonitor emon1; // Create an instance for induction cooker EnergyMonitor emon2; // Create an instance for phase1 EnergyMonitor emon3; // Create an instance for phase2 m2mData sensor; // create an instance for m2mData void setup() { // Energy monitor Cooktop emon1.voltage(2, 245.5, 1.7); // Voltage: input pin, calibration, phase_shift emon1.current(3, 29); // Current: input pin, calibration // Energy monitor Phase1 emon2.voltage(2, 245.5, 1.7); // Voltage: input pin, calibration, phase_shift emon2.current(4, 29); // Current: input pin, calibration // Energy monitor Phase2 emon3.voltage(2, 245.5, 1.7); // Voltage: input pin, calibration, phase_shift emon3.current(5, 29); // Current: input pin, calibration Ethernet.begin(mac, ip); // start the ethernet connection Serial.begin(9600); // enable serial data print delay(1000); } // Define api_key for each sensor. These api_key values are obtained from m2mlight.com char api_key1[] = "1nja1c"; // Voltage char api_key2[] = "1njc28"; // Cooker real power char api_key3[] = "1njd49"; // Current phase 1 char api_key4[] = "1njkia"; // Current phase 2 char api_key5[] = "1njwib"; // Total real power void loop() { emon1.calcVI(20,2000); // Calculate all. No.of half wavelengths (crossings), time-out emon2.calcVI(20,2000); // Calculate all. No.of half wavelengths (crossings), time-out emon3.calcVI(20,2000); // Calculate all. No.of half wavelengths (crossings), time-out float supplyVoltage = emon1.Vrms; // extract voltage into variable float realPowerCooker = emon1.realPower; // extract Real Power into variable float IrmsPhase1 = emon2.Irms; // extract current1 into variable float IrmsPhase2 = emon3.Irms; // extract current2 into variable float realPowerTotal = (abs(IrmsPhase1) * supplyVoltage / 1.73) + (abs(IrmsPhase2) * supplyVoltage / 1.73); Serial.print("realPowerCooker:"); Serial.println(realPowerCooker); // emon1.serialprint(); // Print out all variables (realpower, apparent power, Vrms, Irms, power factor) Serial.print("IrmsPhase1:"); Serial.println(IrmsPhase1); // emon2.serialprint(); // Print out all variables (realpower, apparent power, Vrms, Irms, power factor) Serial.print("IrmsPhase2:"); Serial.println(IrmsPhase2); // emon3.serialprint(); // Print out all variables (realpower, apparent power, Vrms, Irms, power factor) Serial.print("realPowerTotal:"); Serial.println(realPowerTotal); // // Prevent undesired readings if (realPowerCooker<0) realPowerCooker = 0; if (IrmsPhase1<0) IrmsPhase1 = 0; if (IrmsPhase2<0) IrmsPhase2 = 0; if (realPowerTotal<0) realPowerTotal = 0; // Store sensors values on m2mlight sensor.sendValue(api_key1, supplyVoltage); sensor.sendValue(api_key2, realPowerCooker); sensor.sendValue(api_key3, IrmsPhase1); sensor.sendValue(api_key4, IrmsPhase2); sensor.sendValue(api_key5, realPowerTotal); delay(15000); //send values every 15 seconds }
d03ab3183d7ba5882859562b946be35f274631d0
b47259e4774efe357cd82db8035c0120273e5367
/1_semestr/Recursive/backend.cpp
fc12b80670d6068283ff6009b772c4f3037498ba
[]
no_license
Arseniy16/MIPT
ac56f6672bf022d3caffed540d37367a4c61bd6f
4b6b15e925f8aeebe8ff53d110a976b00c21a5e2
refs/heads/master
2023-04-13T18:31:13.351263
2021-04-28T14:52:07
2021-04-28T14:52:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,816
cpp
backend.cpp
#include "tree.cpp" enum STATES { IN__FUNCTION = 0, OUT_FUNCTION, PUSH_ME, POP_TO_ME }; // for IF, ELSE, WHILE... int global_counter = 0; void Interpretate(Node* node, FILE* ams, int state = 0) { if (!node) return; assert(ams); switch (node->type) { case TOKEN_NUMBER: if (state == PUSH_ME) { fprintf(ams, "push %lg\n", node->data.value); break; } if (state == POP_TO_ME) { printf("POP to NUMBER\n"); abort(); } printf("What i have to do with this value?\n"); abort(); case TOKEN_OPERATOR: Interpretate(node->left, ams, PUSH_ME); Interpretate(node->right, ams, PUSH_ME); switch (node->data.type) { case OP_NULL: break; case OP_PLUS: fprintf(ams, "add\n\n"); break; case OP_MINUS: fprintf(ams, "sub\n\n"); break; case OP_DIV: fprintf(ams, "div\n\n"); break; case OP_MULT: fprintf(ams, "mult\n\n"); break; case OP_POW: fprintf(ams, "pwr\n\n"); break; case OP_G: fprintf(ams, "jae"); break; case OP_GE: fprintf(ams, "ja"); break; case OP_L: fprintf(ams, "jbe"); break; case OP_LE: fprintf(ams, "jb"); break; case OP_E: fprintf(ams, "jne"); break; case OP_NE: fprintf(ams, "je"); break; default: printf("Unknown operator type: %d", node->data.type); abort(); } break; case TOKEN_VARIABLE: if (state == PUSH_ME) { fprintf(ams, "push v%02d\n", node->data.type); break; } if (state == POP_TO_ME) { fprintf(ams, "pop v%02d\n", node->data.type); break; } printf("What i have to do with this variable?\n"); abort(); case TOKEN_FUNCTION: { if (strcmp(functions[node->data.type].name, "get") == 0) { fprintf(ams, "put\n"); Interpretate(node->left, ams, POP_TO_ME); return; } if (strcmp(functions[node->data.type].name, "put") == 0) { Interpretate(node->left, ams, PUSH_ME); fprintf(ams, "print\npop\n"); return; } Node* args = node->right; if (args->type == TOKEN_NUMBER) fprintf(ams, "push %lg\n", args->data.value); if (args->type == TOKEN_VARIABLE) fprintf(ams, "push v%02d\n", args->data.type); fprintf(ams, "call func_%s\n", functions[node->data.type].name); if (state == PUSH_ME) fprintf(ams, "push cx\n"); } return; case TOKEN_GLOBAL_FUNCTION: { if (state != OUT_FUNCTION) { Node* args = node->left; while (args != NULL) { Interpretate(args->right, ams, PUSH_ME); args = args->left; } fprintf(ams, "call func_%s\n", functions_names.list[node->data.type]); if (state == PUSH_ME) fprintf(ams, "push cx\n"); return; } fprintf(ams, ":func_%s\n", functions_names.list[node->data.type]); fprintf(ams, "pop bx\n"); // Arguments char list_variables[MAX_NUMBER_VARIABLES] = {}; int list_it = 0; Node* args = node->left; while (args != NULL) { if (args->right->type == TOKEN_VARIABLE) list_variables[list_it++] = args->right->data.type; else { printf("Invalid variable in intitial: %d\n", args->type); abort(); } args = args->left; } for (int i = list_it - 1; i >= 0; --i) fprintf(ams, "pop v%02d\n", list_variables[i]); fprintf(ams, "push bx\n"); Interpretate(node->right, ams); fprintf(ams, "\n\n"); } break; case TOKEN_SYMBOL: switch (node->data.type) { case '=': Interpretate(node->right, ams, PUSH_ME); Interpretate(node->left, ams, POP_TO_ME); break; default: printf("Unknown symbol: %c", node->data.type); abort(); } break; case TOKEN_SYSTEM: switch (node->data.type) { case SYS_NULL: fprintf(ams, ";----------------------------------------\n\n"); Interpretate(node->left, ams, OUT_FUNCTION); Interpretate(node->right, ams); break; case SYS_IF: { int if_counter = global_counter++; fprintf(ams, " ;Start if\n"); Interpretate(node->left, ams); fprintf(ams, " begin_else_%d\n", if_counter); fprintf(ams, ":begin_if_%d\n", if_counter); Interpretate(node->right->left, ams); fprintf(ams, "jmp end_if_%d\n", if_counter); fprintf(ams, ":begin_else_%d\n", if_counter); Interpretate(node->right->right, ams); fprintf(ams, ":end_if_%d\n", if_counter); fprintf(ams, " ;End if\n\n"); } break; case SYS_WHILE: { int while_counter = global_counter++; fprintf(ams, ":begin_condition_%d\n", while_counter); Interpretate(node->left, ams); fprintf(ams, " end_while_%d\n", while_counter); Interpretate(node->right, ams); fprintf(ams, "jmp begin_condition_%d\n", while_counter); fprintf(ams, ":end_while_%d\n", while_counter); } break; case SYS_RETURN: Interpretate(node->left, ams, PUSH_ME); fprintf(ams, "pop cx\n"); fprintf(ams, "return\n"); return; case SYS_END_P: return; default: printf("Unknown SYS_TYPE: %d", node->data.type); abort(); } break; default: printf("Unknown type: %d", node->type); abort(); } } void BackEnd(const char* code, const char* ams_file) { assert(code); assert(ams_file); Node* tree = TreeLoad(code); NodePrint(tree, "HelpFiles/tree.doxy"); int number_global = 0; Node* node = tree; while (node != NULL) { if (node->left->type == TOKEN_SYMBOL) number_global++; node = node->right; } FILE* ams = fopen(ams_file, "w"); fprintf(ams, "push %d\n", number_global); fprintf(ams, "pop dx\n"); fprintf(ams, "call func_main\n"); fprintf(ams, "end\n"); Interpretate(tree, ams, OUT_FUNCTION); TreeDelete(&tree); } int main() { BackEnd("HelpFiles/frontend.tree", "HelpFiles/tree.ams"); return 0; }
c0965ac3c325548740b4eb4c631b621e38bb16bf
a3f2feb2c5906b238f77c63fe716420a7495a9e7
/Include/Button.h
d24a4264c053a535daddc9e0eee7d4dc225c5c16
[]
no_license
XiaZiXi/Dragonfly
e206c25d09e66113ebaa2f08ea4fd2aa0630d752
869043162ebf23349a48c22f36b4a1674c2c138e
refs/heads/master
2020-03-17T00:21:12.181173
2017-10-13T07:45:39
2017-10-13T07:45:39
133,113,176
1
0
null
2018-05-12T04:14:06
2018-05-12T04:14:06
null
UTF-8
C++
false
false
322
h
Button.h
#pragma once #include "SFML/Graphics.hpp" namespace df { namespace Mouse { // Set of mouse buttons recognized by Dragonfly. enum Button { UNDEFINED_MOUSE_BUTTON = -1, LEFT = sf::Mouse::Left, RIGHT = sf::Mouse::Right, MIDDLE = sf::Mouse::Middle }; static std::vector<Button> buttons = { LEFT, RIGHT, MIDDLE }; } }
6544a703d92019a383f3daf958527f7a04814e9b
c3a19e2f6e092340cd6afa0388fc0fedf393c1ca
/src/ooc_cudnnSoftmaxBackward_optimize.cpp
269a32cbf9a1df2cb4e1f68b8a2dcbbed5725447
[ "MIT" ]
permissive
yukiito2/ooc_cuDNN
e568762d1fc61bbcd0734e3027b1395fa0653c49
b366abf5c0e22713f23f8e5fcdd628eead40fbea
refs/heads/master
2020-03-08T08:43:53.426848
2018-04-05T06:07:56
2018-04-05T06:07:56
128,029,095
4
3
null
null
null
null
UTF-8
C++
false
false
7,552
cpp
ooc_cudnnSoftmaxBackward_optimize.cpp
#include "ooc_cudnn.h" #include <sys/time.h> #include <float.h> double cudnnSoftmaxBackward_weight; double cudnnSoftmaxBackward_bias; extern double cudaMemcpy_weight; extern double cudaMemcpy_bias; cudnnStatus_t CUDNNWINAPI ooc_cudnnSoftmaxBackwardProfile(){ int i, loop = 100; struct timeval t1, t2; double time1, time2; double size1, size2; size_t n = 1, c = 128, h = 128, w = 128; float *dx, *y, *dy; float alpha = 1.0, beta = 0.0; cudaMalloc((void**)&dx, n*c*h*w*sizeof(float)); cudaMalloc((void**)&y, n*c*h*w*sizeof(float)); cudaMalloc((void**)&dy, n*c*h*w*sizeof(float)); // profile Softmax cudnnHandle_t handle; cudnnTensorDescriptor_t dxDesc, yDesc, dyDesc; cudnnCreate(&handle); cudnnCreateTensorDescriptor(&dxDesc); cudnnCreateTensorDescriptor(&yDesc); cudnnCreateTensorDescriptor(&dyDesc); cudnnSetTensor4dDescriptor(dxDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, c, h, w); cudnnSetTensor4dDescriptor(yDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, c, h, w); cudnnSetTensor4dDescriptor(dyDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, c, h, w); // time1, size1 cudaDeviceSynchronize(); gettimeofday(&t1, NULL); for(i = 0; i < loop; i++){ cudnnSoftmaxBackward(handle, CUDNN_SOFTMAX_FAST, CUDNN_SOFTMAX_MODE_CHANNEL, &alpha, yDesc, dy, dyDesc, dy, &beta, dxDesc, dx); } cudaDeviceSynchronize(); gettimeofday(&t2, NULL); time1 = ((double)(t2.tv_usec-t1.tv_usec) * 1000 + (double)(t2.tv_sec-t1.tv_sec) * 1000 * 1000 * 1000) / (double)loop; size1 = (double)(n * c * h * w * sizeof(float)); // time2, size2 c /= 2; cudnnSetTensor4dDescriptor(dxDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, c, h, w); cudnnSetTensor4dDescriptor(yDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, c, h, w); cudnnSetTensor4dDescriptor(dyDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, n, c, h, w); cudaDeviceSynchronize(); gettimeofday(&t1, NULL); for(i = 0; i < loop; i++){ cudnnSoftmaxBackward(handle, CUDNN_SOFTMAX_FAST, CUDNN_SOFTMAX_MODE_CHANNEL, &alpha, yDesc, dy, dyDesc, dy, &beta, dxDesc, dx); } cudaDeviceSynchronize(); gettimeofday(&t2, NULL); time2 = ((double)(t2.tv_usec-t1.tv_usec) * 1000 + (double)(t2.tv_sec-t1.tv_sec) * 1000 * 1000 * 1000) / (double)loop; size2 = (double)(n * c * h * w * sizeof(float)); // cudnnSoftmaxBackward_weight, cudnnSoftmaxBackward_bias cudnnSoftmaxBackward_weight = (time1 - time2) / (size1 - size2); cudnnSoftmaxBackward_bias = time1 - cudnnSoftmaxBackward_weight * size1; cudnnDestroyTensorDescriptor(dxDesc); cudnnDestroyTensorDescriptor(yDesc); cudnnDestroyTensorDescriptor(dyDesc); cudnnDestroy(handle); cudaFree(dx); cudaFree(y); cudaFree(dy); return CUDNN_STATUS_SUCCESS; } double model_softmax_back( const size_t n, const size_t c, const size_t h, const size_t w, const size_t d_dx_s, const size_t d_y_s, const size_t d_dy_s, const size_t data_size, const size_t d_mem_free, const int n_step, const int h_step ){ double t = DBL_MAX; size_t d_n = n / n_step; if(n % n_step != 0) d_n++; size_t d_h = h / h_step; if(h % h_step != 0) d_h++; //check parameter if(d_n*c*d_h*w >= 2.0*1024.0*1024.0*1024.0) return t; size_t d_mem_dx = d_n * c * d_h * w * data_size * d_dx_s; size_t d_mem_y = d_n * c * d_h * w * data_size * d_y_s; size_t d_mem_dy = d_n * c * d_h * w * data_size * d_dy_s; size_t comp_softmax = d_n * c * d_h * w * data_size; if(d_mem_dx + d_mem_y + d_mem_dy < d_mem_free / 3){ double t_pre = cudaMemcpy_weight * (d_mem_y + d_mem_dy) + cudaMemcpy_bias * (d_y_s + d_dy_s); double t_softmax = cudnnSoftmaxBackward_weight * comp_softmax + cudnnSoftmaxBackward_bias; double t_off = cudaMemcpy_weight * d_mem_dx + cudaMemcpy_bias * d_dx_s; double t_tmp = t_pre; if(t_tmp < t_softmax) t_tmp = t_softmax; if(t_tmp < t_off) t_tmp = t_off; t = t_pre + t_softmax + t_off + (n_step * h_step - 1) * t_tmp; } return t; } cudnnStatus_t CUDNNWINAPI ooc_cudnnSoftmaxBackward_optimize( const size_t n, const size_t c, const size_t h, const size_t w, const bool dx_on_device, const bool y_on_device, const bool dy_on_device, const size_t data_size, cudnnSoftmaxMode_t mode, int *n_step, int *h_step ){ int tmp; double time; double time_opt = DBL_MAX; // memory information size_t d_mem_free, d_mem_total; cudaMemGetInfo(&d_mem_free, &d_mem_total); size_t d_dx_s = 0; if(!dx_on_device) d_dx_s = 1; size_t d_y_s = 0; if(!y_on_device) d_y_s = 1; size_t d_dy_s = 0; if(!dy_on_device) d_dy_s = 1; int n_step_opt = 1, h_step_opt = 1; if(mode == CUDNN_SOFTMAX_MODE_CHANNEL){ tmp = 1; for(h_step_opt = 1; h_step_opt <= h; h_step_opt++){ time = model_softmax_back(n, c, h, w, d_dx_s, d_y_s, d_dy_s, data_size, d_mem_free, n_step_opt, h_step_opt); if(time < time_opt){ time_opt = time; tmp = h_step_opt; } } h_step_opt = tmp; } tmp = 1; for(n_step_opt = 1; n_step_opt <= n; n_step_opt++){ time = model_softmax_back(n, c, h, w, d_dx_s, d_y_s, d_dy_s, data_size, d_mem_free, n_step_opt, h_step_opt); if(time < time_opt){ time_opt = time; tmp = n_step_opt; } } n_step_opt = tmp; *n_step = n_step_opt; *h_step = h_step_opt; return CUDNN_STATUS_SUCCESS; }
0769c54afff78bce669e8386b6809ffe386fc8f9
e85db833349381ba8347168161ac02996813de4e
/tabularFomatting.cpp
80d6f5d60cd79f3592ea3c74328ed509a545d6ba
[]
no_license
jjbutler52/Code-samples
3c1e0dc63a1d963aa17c7ed81cd831f5c6580df0
8f317edc03862bd5557fc1b56f699ba9ed458b18
refs/heads/master
2023-03-30T02:26:34.532878
2021-03-07T02:28:19
2021-03-07T02:28:19
314,299,622
0
0
null
null
null
null
UTF-8
C++
false
false
734
cpp
tabularFomatting.cpp
#include <iostream> #include <ios> #include <iomanip> using namespace std; void f_to_c(double fah) { double cent = 0.0; cent = 5 * (fah - 32) / 9; cout << setw(15) << left << fah << " degF" << "|"; cout << setw(16) << right << cent << " degC" << endl; } void tabularFormatting() { cout << " Fahrenheit to Centigrade Scale" << endl << endl; cout << setw(20) << left << "Fahrenheit" << "|"; cout << setw(21) << right << "Centigrade" << endl; cout << "-------------------------------------------" << endl; double fahr = 0.0; for (int i = 0; i < 40; i = i + 10) { fahr = fahr + i; f_to_c(fahr); } cout << "-------------------------------------------" << endl; }
918b970ea8c4bbb2f4fc816ea19c514588513051
82ec9ecef04a3b16b3670706b6482faf1cb7d452
/Practica 1/3_1_5_Scope.cpp
8d05c762db8d80cb395412ff3bea7ae4c7c45af8
[]
no_license
Pimed23/Practica
3ae73b3556cb5ac4672f60dfc64c7bb92bdd0c66
a82635ec3909179bd4b31180c2e3a90af293d91c
refs/heads/master
2020-05-04T17:09:54.320597
2019-04-24T05:04:32
2019-04-24T05:04:32
179,300,795
0
0
null
null
null
null
UTF-8
C++
false
false
491
cpp
3_1_5_Scope.cpp
#include <iostream> using namespace std; // #include <iostream> // using namespace std; int main() { cout << "Hello, world!\n"; return 0; } #include <iostream> // Don't compile because cout was no declarated in this scope // cout belongs to iostream library // C++ follow a secuence top - down // First the first line is execute then the second later the third and so on // If we move the line 8 and insert in the first line // The program compiles and works
4f9eee195a298b7ccf7df6837e08d74c9616c68b
a8d0bb2f9a42320be0aa5e383f1ce67e5e44d2c6
/Advanced Datastructures/033 BITwithRURQ.cpp
7dc43c739967b39b8d6414f98bab14995820eeb6
[]
no_license
camperjett/DSA_dups
f5728e06f1874bafbaf8561752e8552fee2170fa
f20fb4be1463398f568dbf629a597d8d0ae92e8f
refs/heads/main
2023-04-19T18:18:55.674116
2021-05-15T12:51:21
2021-05-15T12:51:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,336
cpp
033 BITwithRURQ.cpp
#include<bits/stdc++.h> using namespace std; // basic BIT functions void update(int* BIT, int i, int val, int sz){ i++; for(; i<=sz; i+=i&-i){ BIT[i] = val; } } int getSum(int* BIT, int i, int sz){ i++; int sum = 0; for(; i>0; i-=i&-i){ sum+=BIT[i]; } return sum; } int query(int* BIT, int l, int r, int sz){ return getSum(BIT, r, sz)-getSum(BIT, l-1, sz); } // range update functions void rangeUpdate(int* BIT1, int* BIT2, int l, int r, int val, int sz){ // update BIT1 update(BIT1, l, val, sz); update(BIT1, r+1, -val, sz); // update BIT2 update(BIT2, l, val*(l-1), sz); update(BIT2, r+1, -val*r, sz); } int getSum2(int* BIT1, int* BIT2, int i, int sz){ return getSum(BIT1, i, sz)*i - getSum(BIT2, i, sz); } int rangeSum(int* BIT1, int* BIT2, int l, int r, int sz){ return getSum2(BIT1, BIT2, r, sz)-getSum2(BIT1, BIT2, l-1, sz); } int* constructBIT(int n){ int* temp = new int[n+1]; memset(temp, 0, sizeof(int)*(n+1)); return temp; } int main(){ int n; cin>>n; // vector<int> v(n); // for(int i=0; i<n; i++) cin>>v[i]; int* BIT1 = constructBIT(n); int* BIT2 = constructBIT(n); // rangeUpdate(BIT1, BIT2, 0, 5, 99, n); rangeUpdate(BIT1, BIT2, 3, 6, 999, n); cout<<rangeSum(BIT1, BIT2, 5, 6, n); }
af73ea8d90e71617e99e3f3dafc686f454866959
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/tao/PortableServer/Upcall_Command.cpp
52dc05020e2d9f39618d62f27c4cff8416bd2e01
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
166
cpp
Upcall_Command.cpp
#include "tao/PortableServer/Upcall_Command.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO::Upcall_Command::~Upcall_Command (void) { } TAO_END_VERSIONED_NAMESPACE_DECL
716ec65fe6c77d328a44a4f1dfa17197da767346
38a2d029f071efee27e676ec22625c166769552e
/Source code/Paint/StatusBar.h
59b3a096fa51097f640f8ddb8c4a8d389a8b60d2
[ "MIT" ]
permissive
tqbdev/Paint-Win32-Dll
d610c001f93dba22be36cc644cda471a7ca85de0
291cdedc4d15c07692a9f7a43804796aa267cb65
refs/heads/master
2021-01-24T12:05:25.796883
2018-02-27T11:27:13
2018-02-27T11:27:13
123,118,200
1
0
null
2018-02-27T11:27:14
2018-02-27T11:14:42
C++
UTF-8
C++
false
false
394
h
StatusBar.h
#pragma once namespace MyPaint { class StatusBar { private: HINSTANCE hInst_; HWND hParent_; HWND hStatusBar_; long ID_; public: StatusBar(); ~StatusBar(); void Create(HWND parentWnd, long ID, HINSTANCE hParentInst, long lStyle = WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP | SBARS_TOOLTIPS); HWND GetThisHandle(); int GetThisID(); void Resize(); }; }
327aa859b709c906b853887e95c75613c62bb81a
23c7bf7123e9408f77d54b169b3d898f4551028b
/swap_3rdvariable.cpp
2bf14887cdd42d25ba675b906629703ac1f7acfa
[]
no_license
ganeshknvs/sample_programs2
8f6f624351f6779edb9dec0ea77e1d9841441703
eff2326f68660ac9f8e4b0c2962e40c244ac6b46
refs/heads/master
2020-03-24T10:19:13.625014
2018-07-28T06:49:45
2018-07-28T06:49:45
142,653,147
0
0
null
null
null
null
UTF-8
C++
false
false
212
cpp
swap_3rdvariable.cpp
#include<iostream> using namespace std; int swap(int &x, int &y) { x = x+y; y = x-y; x = x-y; } int main() { int a = 30; int b = 20; swap(a,b); cout << a << endl; cout << b << endl; return 0; }
9a3a820add88cf7c9e2d2b09a2a5af37ac78d42c
342f81e941f6e936264b4902c7b75ef2387c8a7d
/STL/iostream/main.cpp
253100c80ed542e25e4e6cb761345bfb3e11d4eb
[]
no_license
linzhenhua/Cpp_STL_test
b96ac9cd338d23fa4691727a918c96cf54c7a328
132e7bb9acb7acb92750836df69d0fa6c4f9f373
refs/heads/master
2020-12-30T23:09:00.671360
2017-10-17T09:44:04
2017-10-17T09:44:04
80,620,520
1
0
null
null
null
null
GB18030
C++
false
false
1,677
cpp
main.cpp
#include <string.h> #include <iostream> #include <sstream> #include <fstream> #include <string> using namespace std; void myIosteam1() { stringstream i; cout << i.good() << "\t" << i.bad() << '\t' << i.eof() << '\t' << i.fail() << '\n'; cout << i.rdstate() << endl; } void myIosteam2() { char str[5]; cin >> str; //cin.get(str, 5); //cin >> str; //cin.get(str, 5, '8'); //cin.getline(str, 5, '2'); cout << str << endl; } void myOstream1() { char str = 'a'; cout.put(str); } void myOstream2() { bool a; cout << std::noboolalpha << a << "==" << std::boolalpha << a << endl; cout << std::oct << 10 << std::hex << 10 << endl; cout.unsetf(std::ios::oct); //cout.setf(std::ios::hex); cout << 11 << endl; cout.unsetf(std::ios::hex); cout << 10.3366 << endl; } void myFileOpt() { //定义一个文件类对象 fstream File; //打开文件 File.open("test.txt", ios::in | ios::out | ios::binary | ios::app); //判断是否打开成功 if(!File) { cout << "open file error" << endl; return ; } //写文件 string name = "linzhenhua"; //cout << sizeof(name) << endl; File.write(name.c_str(), name.length()); //读文件 char str[100] = {0}; //先获取文件的长度 File.seekg(0, File.end); int length = File.tellg(); File.seekg(0, File.beg); File.read(str, length); cout << str << endl; //关闭文件 File.close(); } int main(int argc, char *argv[]) { //myIosteam1(); //myIosteam2(); //myOstream1(); //myOstream2(); myFileOpt(); return 0; }
a051526ceca8c8933832c30e1131702f4affe86b
d96607cdf79c4f3818788cfe2bef9888a49d56a8
/C++ How to Program/Chapter_7/7.33-linear-search-rec.cpp
632618ffeca2b4b2fe50f382571cd7c68cf587be
[]
no_license
dasanchez/hellocpp
41646533ee826e59841b25961b5ff6dc93b3487d
3b37c21d4f864686ba0c5fe60f4939ea06d91cda
refs/heads/master
2021-06-02T08:56:46.201450
2020-09-28T03:16:20
2020-09-28T03:16:20
126,009,535
0
0
null
2018-08-12T21:02:20
2018-03-20T11:51:02
C++
UTF-8
C++
false
false
1,157
cpp
7.33-linear-search-rec.cpp
// 7.33: Linear Search by Recursion // Use recursive function linearSearch to perform // a linear search of the array. // The function should receive an integer array and // the size of the array as arguments. // If the search key is found, return the array subscript; // otherwise, return -1. #include <iostream> using namespace std; const int elements = 6; int linearSearch(const int array[], int arraySize, int key, int index); int main() { int searchArray[elements] = {1, 2, 4, 8, 16, 32}; int key; cout << "Enter the key (a power of 2 lower than 50): "; cin >> key; int result = linearSearch(searchArray, elements, key, 0); if (result >= 0) cout << "The key is at subscript " << result << "." << endl; else cout << "The key was not found." << endl; } int linearSearch(const int array[], int arraySize, int key, int index) { // cout << "Array size: " << arraySize << ", index: " << index << endl; if (array[0] == key) return index; else if (arraySize == 1) return -1; else { index++; return linearSearch(array + 1, arraySize - 1, key, index); } }
618831a1611026bef58e812457bd1162fbd8a521
3b748bf71830029a9c9b7132456a8c8b4a23282a
/test/simulation_test/world_test.cpp
2c2add0b55969b8578c9e83edc6c938fe040d944
[ "MIT" ]
permissive
CoffeeMcRoasted/ucloth
97a9e7d1191f95336e66f0e5feee35dbc9542ab2
e0e22ca8d8205894b2d0bca5ceaa0b2481a70b24
refs/heads/master
2022-07-05T03:14:34.116858
2020-02-06T23:58:58
2020-02-07T00:45:49
238,817,533
2
0
null
null
null
null
UTF-8
C++
false
false
120
cpp
world_test.cpp
#include <gtest/gtest.h> #include <simulation/world.h> TEST(UClothWorldTest, HelloTest) { EXPECT_EQ(true, true); }
e09aae6c37653addb076c03fb8c414dc2dc3ebe7
71a256308ea30a4125fa6a52341512963697d244
/pre/Object-Oriented Programming/Inheritance/Virtual Function/Shape.h
86fb36d2ef0737b210b8d44371d0a1f2d7a924f3
[]
no_license
oymin2001/DataStructure
ac6d76ae120b59f097a3daf688b65f8859ca5bc6
e676d886f88153b9f566df04f125321e1f693777
refs/heads/master
2023-03-04T09:39:34.604986
2023-02-28T11:22:17
2023-02-28T11:22:17
285,205,505
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
Shape.h
#ifndef SHAPE_H #define SHAPE_H #include<string> #include"Position.h" using namespace std; enum COLORS{RED,BLUE,BLACK,ORANGE}; extern const char* shapeColor[]; class Shape { friend ostream& operator<<(ostream& S, Shape&); public: Shape(); Shape(Position p, COLORS color, string name); virtual ~Shape(); virtual void draw(); Position getPosition() { return pos; } void setPosition(Position p) { pos.pos_x = p.pos_x; pos.pos_y = p.pos_y; } COLORS getColor() { return color; } void setColor(COLORS c) { color = c; } protected: Position pos; COLORS color; string name; }; #endif // !SHAPE_H
d7e356e337ed77868738d273223ffdfd54378825
591dbb1cf8799698c670cd11c277bc6a76abf9a3
/src/OpenLoco/Windows/ToolbarBottomEditor.cpp
7a2b88be452f2fc37e3504cd311741309d5844e3
[ "MIT" ]
permissive
aw20368/OpenLoco
4956fb8b01d7f4b39c73be920e64358892304c22
ce37179813b0036b38061c604581e70f8d41873f
refs/heads/master
2021-07-06T00:50:06.205984
2020-10-09T15:52:08
2020-10-09T15:52:08
190,220,932
0
0
MIT
2020-10-10T18:59:12
2019-06-04T14:44:18
C++
UTF-8
C++
false
false
353
cpp
ToolbarBottomEditor.cpp
#include "../Interop/Interop.hpp" #include "../Ui/WindowManager.h" using namespace OpenLoco::Interop; namespace OpenLoco::Ui::Windows::ToolbarBottom::Editor { // 0x0043CCCD void open() { call(0x0043CCCD); // Note call to window_resize_gui_scenario_editor not part of this function // move when implemented. } }
c8a4f17df8edacb10ce2fd2ba1ecf70f6d775fe8
079fc299d6a1622832f738bac1f28167df6b0b9c
/cpp_module04/ex03/Unequiped.hpp
c01ac2450c1c6a2b517cc560c96dfb7da380c7d5
[]
no_license
xogml123/cpp
294fa038e078a18cf3e24fdd7eea32692b634b25
4e2a24e169ad2e31cb8d9d6ba3afa2f8de21d9f3
refs/heads/master
2023-08-14T01:40:37.260112
2021-10-06T14:59:55
2021-10-06T14:59:55
374,075,489
0
0
null
null
null
null
UTF-8
C++
false
false
176
hpp
Unequiped.hpp
#ifndef UNDQUIPED_HPP # define UNDQUIPED_HPP #include "AMateria.hpp" struct Unequiped{ Unequiped(AMateria* am); ~Unequiped(); AMateria* m; Unequiped* link; }; #endif
2a958d41e3be152c3a48d263f3b16cf3ed7e977a
de7e771699065ec21a340ada1060a3cf0bec3091
/core/src/test/org/apache/lucene/analysis/TestCharArraySet.cpp
be9163aae952d05e4608f3624f4fae2b29b6bcf3
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
15,830
cpp
TestCharArraySet.cpp
using namespace std; #include "TestCharArraySet.h" namespace org::apache::lucene::analysis { using CharArraySet = org::apache::lucene::analysis::CharArraySet; using LuceneTestCase = org::apache::lucene::util::LuceneTestCase; std::deque<wstring> const TestCharArraySet::TEST_STOP_WORDS = { L"a", L"an", L"and", L"are", L"as", L"at", L"be", L"but", L"by", L"for", L"if", L"in", L"into", L"is", L"it", L"no", L"not", L"of", L"on", L"or", L"such", L"that", L"the", L"their", L"then", L"there", L"these", L"they", L"this", L"to", L"was", L"will", L"with"}; void TestCharArraySet::testRehash() { shared_ptr<CharArraySet> cas = make_shared<CharArraySet>(0, true); for (int i = 0; i < TEST_STOP_WORDS.size(); i++) { cas->add(TEST_STOP_WORDS[i]); } assertEquals(TEST_STOP_WORDS.size(), cas->size()); for (int i = 0; i < TEST_STOP_WORDS.size(); i++) { assertTrue(cas->contains(TEST_STOP_WORDS[i])); } } void TestCharArraySet::testNonZeroOffset() { std::deque<wstring> words = {L"Hello", L"World", L"this", L"is", L"a", L"test"}; std::deque<wchar_t> findme = (wstring(L"xthisy")).toCharArray(); shared_ptr<CharArraySet> set = make_shared<CharArraySet>(10, true); set->addAll(Arrays::asList(words)); assertTrue(set->contains(findme, 1, 4)); assertTrue(set->contains(wstring(findme, 1, 4))); // test unmodifiable set = CharArraySet::unmodifiableSet(set); assertTrue(set->contains(findme, 1, 4)); assertTrue(set->contains(wstring(findme, 1, 4))); } void TestCharArraySet::testObjectContains() { shared_ptr<CharArraySet> set = make_shared<CharArraySet>(10, true); optional<int> val = static_cast<Integer>(1); set->add(val); assertTrue(set->contains(val)); assertTrue(set->contains(optional<int>(1))); // another integer assertTrue(set->contains(L"1")); assertTrue(set->contains(std::deque<wchar_t>{L'1'})); // test unmodifiable set = CharArraySet::unmodifiableSet(set); assertTrue(set->contains(val)); assertTrue(set->contains(optional<int>(1))); // another integer assertTrue(set->contains(L"1")); assertTrue(set->contains(std::deque<wchar_t>{L'1'})); } void TestCharArraySet::testClear() { shared_ptr<CharArraySet> set = make_shared<CharArraySet>(10, true); set->addAll(Arrays::asList(TEST_STOP_WORDS)); assertEquals(L"Not all words added", TEST_STOP_WORDS.size(), set->size()); set->clear(); assertEquals(L"not empty", 0, set->size()); for (int i = 0; i < TEST_STOP_WORDS.size(); i++) { assertFalse(set->contains(TEST_STOP_WORDS[i])); } set->addAll(Arrays::asList(TEST_STOP_WORDS)); assertEquals(L"Not all words added", TEST_STOP_WORDS.size(), set->size()); for (int i = 0; i < TEST_STOP_WORDS.size(); i++) { assertTrue(set->contains(TEST_STOP_WORDS[i])); } } void TestCharArraySet::testModifyOnUnmodifiable() { shared_ptr<CharArraySet> set = make_shared<CharArraySet>(10, true); set->addAll(Arrays::asList(TEST_STOP_WORDS)); constexpr int size = set->size(); set = CharArraySet::unmodifiableSet(set); assertEquals(L"Set size changed due to unmodifiableSet call", size, set->size()); wstring NOT_IN_SET = L"SirGallahad"; assertFalse(L"Test std::wstring already exists in set", set->contains(NOT_IN_SET)); try { set->add(NOT_IN_SET.toCharArray()); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertFalse(L"Test std::wstring has been added to unmodifiable set", set->contains(NOT_IN_SET)); assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } try { set->add(NOT_IN_SET); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertFalse(L"Test std::wstring has been added to unmodifiable set", set->contains(NOT_IN_SET)); assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } try { set->add(make_shared<StringBuilder>(NOT_IN_SET)); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertFalse(L"Test std::wstring has been added to unmodifiable set", set->contains(NOT_IN_SET)); assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } try { set->clear(); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertFalse(L"Changed unmodifiable set", set->contains(NOT_IN_SET)); assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } try { set->add(static_cast<any>(NOT_IN_SET)); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertFalse(L"Test std::wstring has been added to unmodifiable set", set->contains(NOT_IN_SET)); assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } // This test was changed in 3.1, as a contains() call on the given deque // using the "correct" iterator's current key (now a char[]) on a Set<std::wstring> // would not hit any element of the CAS and therefor never call remove() on // the iterator try { set->removeAll( make_shared<CharArraySet>(Arrays::asList(TEST_STOP_WORDS), true)); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } try { set->retainAll(make_shared<CharArraySet>(Arrays::asList(NOT_IN_SET), true)); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertEquals(L"Size of unmodifiable set has changed", size, set->size()); } try { set->addAll(Arrays::asList(NOT_IN_SET)); fail(L"Modified unmodifiable set"); } catch (const UnsupportedOperationException &e) { // expected assertFalse(L"Test std::wstring has been added to unmodifiable set", set->contains(NOT_IN_SET)); } for (int i = 0; i < TEST_STOP_WORDS.size(); i++) { assertTrue(set->contains(TEST_STOP_WORDS[i])); } } void TestCharArraySet::testUnmodifiableSet() { shared_ptr<CharArraySet> set = make_shared<CharArraySet>(10, true); set->addAll(Arrays::asList(TEST_STOP_WORDS)); set->add(static_cast<Integer>(1)); constexpr int size = set->size(); set = CharArraySet::unmodifiableSet(set); assertEquals(L"Set size changed due to unmodifiableSet call", size, set->size()); for (auto stopword : TEST_STOP_WORDS) { assertTrue(set->contains(stopword)); } assertTrue(set->contains(static_cast<Integer>(1))); assertTrue(set->contains(L"1")); assertTrue(set->contains(std::deque<wchar_t>{L'1'})); expectThrows(NullPointerException::typeid, [&]() { CharArraySet::unmodifiableSet(nullptr); }); } void TestCharArraySet::testSupplementaryChars() { wstring missing = L"Term %s is missing in the set"; wstring falsePos = L"Term %s is in the set but shouldn't"; // for reference see // http://unicode.org/cldr/utility/deque-unicodeset.jsp?a=[[%3ACase_Sensitive%3DTrue%3A]%26[^[\u0000-\uFFFF]]]&esc=on std::deque<wstring> upperArr = { L"Abc\ud801\udc1c", L"\ud801\udc1c\ud801\udc1cCDE", L"A\ud801\udc1cB"}; std::deque<wstring> lowerArr = { L"abc\ud801\udc44", L"\ud801\udc44\ud801\udc44cde", L"a\ud801\udc44b"}; shared_ptr<CharArraySet> set = make_shared<CharArraySet>(Arrays::asList(TEST_STOP_WORDS), true); for (auto upper : upperArr) { set->add(upper); } for (int i = 0; i < upperArr.size(); i++) { assertTrue(wstring::format(Locale::ROOT, missing, upperArr[i]), set->contains(upperArr[i])); assertTrue(wstring::format(Locale::ROOT, missing, lowerArr[i]), set->contains(lowerArr[i])); } set = make_shared<CharArraySet>(Arrays::asList(TEST_STOP_WORDS), false); for (auto upper : upperArr) { set->add(upper); } for (int i = 0; i < upperArr.size(); i++) { assertTrue(wstring::format(Locale::ROOT, missing, upperArr[i]), set->contains(upperArr[i])); assertFalse(wstring::format(Locale::ROOT, falsePos, lowerArr[i]), set->contains(lowerArr[i])); } } void TestCharArraySet::testSingleHighSurrogate() { wstring missing = L"Term %s is missing in the set"; wstring falsePos = L"Term %s is in the set but shouldn't"; std::deque<wstring> upperArr = {L"ABC\uD800", L"ABC\uD800EfG", L"\uD800EfG", L"\uD800\ud801\udc1cB"}; std::deque<wstring> lowerArr = {L"abc\uD800", L"abc\uD800efg", L"\uD800efg", L"\uD800\ud801\udc44b"}; shared_ptr<CharArraySet> set = make_shared<CharArraySet>(Arrays::asList(TEST_STOP_WORDS), true); for (auto upper : upperArr) { set->add(upper); } for (int i = 0; i < upperArr.size(); i++) { assertTrue(wstring::format(Locale::ROOT, missing, upperArr[i]), set->contains(upperArr[i])); assertTrue(wstring::format(Locale::ROOT, missing, lowerArr[i]), set->contains(lowerArr[i])); } set = make_shared<CharArraySet>(Arrays::asList(TEST_STOP_WORDS), false); for (auto upper : upperArr) { set->add(upper); } for (int i = 0; i < upperArr.size(); i++) { assertTrue(wstring::format(Locale::ROOT, missing, upperArr[i]), set->contains(upperArr[i])); assertFalse(wstring::format(Locale::ROOT, falsePos, upperArr[i]), set->contains(lowerArr[i])); } } // C++ TODO: Most Java annotations will not have direct C++ equivalents: // ORIGINAL LINE: @SuppressWarnings("deprecated") public void // testCopyCharArraySetBWCompat() void TestCharArraySet::testCopyCharArraySetBWCompat() { shared_ptr<CharArraySet> setIngoreCase = make_shared<CharArraySet>(10, true); shared_ptr<CharArraySet> setCaseSensitive = make_shared<CharArraySet>(10, false); deque<wstring> stopwords = deque<wstring>{TEST_STOP_WORDS}; deque<wstring> stopwordsUpper = deque<wstring>(); for (auto string : stopwords) { stopwordsUpper.push_back(string.toUpperCase(Locale::ROOT)); } setIngoreCase->addAll(Arrays::asList(TEST_STOP_WORDS)); setIngoreCase->add(static_cast<Integer>(1)); setCaseSensitive->addAll(Arrays::asList(TEST_STOP_WORDS)); setCaseSensitive->add(static_cast<Integer>(1)); shared_ptr<CharArraySet> copy = CharArraySet::copy(setIngoreCase); shared_ptr<CharArraySet> copyCaseSens = CharArraySet::copy(setCaseSensitive); assertEquals(setIngoreCase->size(), copy->size()); assertEquals(setCaseSensitive->size(), copy->size()); assertTrue(copy->containsAll(stopwords)); assertTrue(copy->containsAll(stopwordsUpper)); assertTrue(copyCaseSens->containsAll(stopwords)); for (auto string : stopwordsUpper) { assertFalse(copyCaseSens->contains(string)); } // test adding terms to the copy deque<wstring> newWords = deque<wstring>(); for (auto string : stopwords) { newWords.push_back(string + L"_1"); } copy->addAll(newWords); assertTrue(copy->containsAll(stopwords)); assertTrue(copy->containsAll(stopwordsUpper)); assertTrue(copy->containsAll(newWords)); // new added terms are not in the source set for (auto string : newWords) { assertFalse(setIngoreCase->contains(string)); assertFalse(setCaseSensitive->contains(string)); } } void TestCharArraySet::testCopyCharArraySet() { shared_ptr<CharArraySet> setIngoreCase = make_shared<CharArraySet>(10, true); shared_ptr<CharArraySet> setCaseSensitive = make_shared<CharArraySet>(10, false); deque<wstring> stopwords = deque<wstring>{TEST_STOP_WORDS}; deque<wstring> stopwordsUpper = deque<wstring>(); for (auto string : stopwords) { stopwordsUpper.push_back(string.toUpperCase(Locale::ROOT)); } setIngoreCase->addAll(Arrays::asList(TEST_STOP_WORDS)); setIngoreCase->add(static_cast<Integer>(1)); setCaseSensitive->addAll(Arrays::asList(TEST_STOP_WORDS)); setCaseSensitive->add(static_cast<Integer>(1)); shared_ptr<CharArraySet> copy = CharArraySet::copy(setIngoreCase); shared_ptr<CharArraySet> copyCaseSens = CharArraySet::copy(setCaseSensitive); assertEquals(setIngoreCase->size(), copy->size()); assertEquals(setCaseSensitive->size(), copy->size()); assertTrue(copy->containsAll(stopwords)); assertTrue(copy->containsAll(stopwordsUpper)); assertTrue(copyCaseSens->containsAll(stopwords)); for (auto string : stopwordsUpper) { assertFalse(copyCaseSens->contains(string)); } // test adding terms to the copy deque<wstring> newWords = deque<wstring>(); for (auto string : stopwords) { newWords.push_back(string + L"_1"); } copy->addAll(newWords); assertTrue(copy->containsAll(stopwords)); assertTrue(copy->containsAll(stopwordsUpper)); assertTrue(copy->containsAll(newWords)); // new added terms are not in the source set for (auto string : newWords) { assertFalse(setIngoreCase->contains(string)); assertFalse(setCaseSensitive->contains(string)); } } void TestCharArraySet::testCopyJDKSet() { shared_ptr<Set<wstring>> set = unordered_set<wstring>(); deque<wstring> stopwords = deque<wstring>{TEST_STOP_WORDS}; deque<wstring> stopwordsUpper = deque<wstring>(); for (auto string : stopwords) { stopwordsUpper.push_back(string.toUpperCase(Locale::ROOT)); } set->addAll(Arrays::asList(TEST_STOP_WORDS)); shared_ptr<CharArraySet> copy = CharArraySet::copy(set); assertEquals(set->size(), copy->size()); assertEquals(set->size(), copy->size()); assertTrue(copy->containsAll(stopwords)); for (auto string : stopwordsUpper) { assertFalse(copy->contains(string)); } deque<wstring> newWords = deque<wstring>(); for (auto string : stopwords) { newWords.push_back(string + L"_1"); } copy->addAll(newWords); assertTrue(copy->containsAll(stopwords)); assertTrue(copy->containsAll(newWords)); // new added terms are not in the source set for (auto string : newWords) { assertFalse(set->contains(string)); } } void TestCharArraySet::testCopyEmptySet() { assertSame(CharArraySet::EMPTY_SET, CharArraySet::copy(CharArraySet::EMPTY_SET)); } void TestCharArraySet::testEmptySet() { assertEquals(0, CharArraySet::EMPTY_SET->size()); assertTrue(CharArraySet::EMPTY_SET->isEmpty()); for (auto stopword : TEST_STOP_WORDS) { assertFalse(CharArraySet::EMPTY_SET->contains(stopword)); } assertFalse(CharArraySet::EMPTY_SET->contains(L"foo")); assertFalse(CharArraySet::EMPTY_SET->contains(static_cast<any>(L"foo"))); assertFalse( CharArraySet::EMPTY_SET->contains((wstring(L"foo")).toCharArray())); assertFalse( CharArraySet::EMPTY_SET->contains((wstring(L"foo")).toCharArray(), 0, 3)); } void TestCharArraySet::testContainsWithNull() { shared_ptr<CharArraySet> set = make_shared<CharArraySet>(1, true); expectThrows(NullPointerException::typeid, [&]() { set->contains(static_cast<std::deque<wchar_t>>(nullptr), 0, 10); }); expectThrows(NullPointerException::typeid, [&]() { set->contains(std::static_pointer_cast<std::wstring>(nullptr)); }); expectThrows(NullPointerException::typeid, [&]() { set->contains(static_cast<any>(nullptr)); }); } void TestCharArraySet::testToString() { shared_ptr<CharArraySet> set = CharArraySet::copy(Collections::singleton(L"test")); // C++ TODO: There is no native C++ equivalent to 'toString': assertEquals(L"[test]", set->toString()); set->add(L"test2"); // C++ TODO: There is no native C++ equivalent to 'toString': assertTrue(set->toString()->find(L", ") != wstring::npos); } } // namespace org::apache::lucene::analysis
5909858745fc3a30f5f3b51c7a2999396f623b94
e4ddd6fc2b956a7e7d9fdf24bf86ecbdd33efdfe
/SanzidaAfrinNishu/based.h
737121985668328f081c9acd342854afa76e3247
[]
no_license
Basedul/StaticToNonstatic
727fa988f5f2a5cb1565a20568d7c559f3e1af3d
2a1b85da8f6a588a33d551f0e4de1aa787b2ef76
refs/heads/master
2020-09-23T05:25:45.797726
2019-12-02T16:08:43
2019-12-02T16:08:43
225,416,025
0
0
null
null
null
null
UTF-8
C++
false
false
173
h
based.h
#ifndef BASED_H #define BASED_H class based : public QObject { Q_OBJECT public: based(QObject *parent = 0); public slots: void finaly(); }; #endif // BASED_H
874fcc25065fb8a680284f4426f811f60a1d4172
ae6892121cdedd98a22f2e8dedde644b64803377
/Vertex.h
c7d951512be94e0afdefe891d9bfbe6a565ffd24
[]
no_license
ssjjsj/mygame
0abfa7599a9b25d6ef30e2a07fe9f177c6c8e202
57e67dfbd424819db7757c715a6315af09537774
refs/heads/master
2021-01-21T04:50:14.024920
2016-06-27T12:31:02
2016-06-27T12:31:02
48,326,567
0
0
null
null
null
null
UTF-8
C++
false
false
857
h
Vertex.h
#ifndef VERTEX_H #define VERTEX_H #include "MathHelp.h" #include <vector> #include "BoneVertexAssignment.h" using namespace std; namespace MyVertex { enum VertexType { P_N_UV = 0, P_C, }; struct Vertex { XMFLOAT3 Pos; XMFLOAT3 Nor; XMFLOAT2 UV; XMFLOAT4 boneIndexs; XMFLOAT4 weight; Vertex() { Pos.x = 0.0f; Pos.y = 0.0f; Pos.z = 0.0f; Nor.x = 0.0f; Nor.y = 0.0f; Nor.z = 0.0f; UV.x = 0.0f; UV.y = 0.0f; weight.x = 0.0f; weight.y = 0.0f; weight.z = 0.0f; weight.w = 0.0f; boneIndexs.x = 0.0f; boneIndexs.y = 0.0f; boneIndexs.z = 0.0f; boneIndexs.w = 0.0f; } }; struct Vertex_P4_C { XMFLOAT4 Pos; XMFLOAT4 Color; }; struct ModelData { vector<Vertex> vertexs; vector<UINT> indexs; string materialName; vector<BoneVertexAssignment> boneVertexAssigns; }; }; #endif
3983178b32fce6e49ce3b2b8907417066f6efbd9
3b51b742b316038513f3094141efa5cec7ba9c74
/AIR3 System/AirPathFind.cpp
3cbbc5c39f785642fa3674e802a030cc51ef0379
[ "BSD-2-Clause" ]
permissive
Sgw32/AIR3-System
e4c1a6076c1567e02a21b2bb3a1231a7dc03d2bc
6fd06acf662ababd4d5092bd14699fa61b370dad
refs/heads/master
2021-01-17T15:30:09.211029
2016-05-12T22:59:31
2016-05-12T22:59:31
42,395,902
1
1
null
null
null
null
UTF-8
C++
false
false
2,789
cpp
AirPathFind.cpp
#include "AirPathFind.h" __declspec(dllexport) AirPathFind::AirPathFind() { dFound=false; } __declspec(dllexport) AirPathFind::~AirPathFind() { } __declspec(dllexport) void AirPathFind::setNodes(std::vector<NPCNode*> nodes) { mNodesStartup=nodes; } __declspec(dllexport) void AirPathFind::setWorld(OgreNewt::World* world) { mWorld=world; } __declspec(dllexport) OgreNewt::Body* AirPathFind::ray(Ogre::Vector3 pos,Ogre::Vector3 end) { OgreNewt::BasicRaycast shootRay(mWorld,pos,end); return shootRay.getFirstHit().mBody; } __declspec(dllexport) vector<NPCNode*> AirPathFind::search(int type,NPCNode* pos,NPCNode* end) { path.clear(); dFound=false; firstNode=pos; mNodes=mNodesStartup; mNodesMarked.clear(); if (type==DEPTH_FIRST_SEARCH) processDFSearch(pos,end); /*if (type==2) n processAIR3Search(pos,end);*/ /*int i = path.size(); i=i+1;*/ return path; } __declspec(dllexport) void AirPathFind::processDFSearch(NPCNode* pos,NPCNode* end) { LogManager::getSingleton().logMessage("Depth-first search iteration.pos="+StringConverter::toString(pos->getPosition())+"end="+StringConverter::toString(end->getPosition())); NPCNode* s; vector<NPCNode*>::iterator i; if (firstNode==pos) { LogManager::getSingleton().logMessage("Iteration one, passing first node."); path.push_back(pos); mNodesMarked.push_back(pos); } if (pos==end) { LogManager::getSingleton().logMessage("The destination is equal from the start. Not a mistake in definition?"); path.push_back(end); dFound=true; return; } OgreNewt::Body* bod; bod=ray(pos->getPosition(),end->getPosition()); if (!bod || bod->getName()=="PLAYER1" ) { LogManager::getSingleton().logMessage("The pass is free to the end, or the pass collides PLAYER!pos="+StringConverter::toString(pos->getPosition())+"end="+StringConverter::toString(end->getPosition())); path.push_back(end); dFound=true; return; } /*if ((pos!=firstNode)&&bod) return;*/ //int i; LogManager::getSingleton().logMessage("Finding a free pass...Found a path="+StringConverter::toString(dFound)); for (i=mNodes.begin();i!=mNodes.end();i++) { bod=ray(pos->getPosition(),(*i)->getPosition()); int j; bool n; n=false; LogManager::getSingleton().logMessage(StringConverter::toString(mNodesMarked.size())); for (j=0;j!=mNodesMarked.size();j++) { if ((*i)==mNodesMarked[j]) { n=true; break; } } if ((!dFound)&&!bod&&!n) { path.push_back((*i)); s=*i; mNodesMarked.push_back(*i); LogManager::getSingleton().logMessage(StringConverter::toString(s->getPosition())); processDFSearch(s,end); } } LogManager::getSingleton().logMessage("Path not found. Sorry!"); } __declspec(dllexport) void AirPathFind::processAIR3Search(Ogre::Vector3 pos,Ogre::Vector3 end) { }
072b33384b7abf371c509b07fb69849e67fbf74c
962e521c226d816934c03a5dfdb85d9dee2d0564
/Chapter7/7.2.3(1).cpp
51268a2a785adef03dfc068a64899847a279784a
[]
no_license
mezhdelova/Essentials
58eaed8e5248cab4899de031df8bb356d6ea9f39
09d1440917a494d675f2b1770cbf82d93d62ba2b
refs/heads/master
2021-05-15T19:52:30.967790
2017-12-20T05:53:12
2017-12-20T05:53:12
107,812,798
1
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
7.2.3(1).cpp
#include <string> #include <iostream> using namespace std; const int DivideByZero = 111; float internaldiv(float arg1, float arg2) { if (0 == arg2) throw DivideByZero; return arg1 / arg2; } float div(float arg1, float arg2) { if (arg2 == 0.0) throw string ("Your input is not valid. You can't divide by zero."); return internaldiv(arg1, arg2); } int main(void) { float a, b; try { while (cin >> a) { cin >> b; cout << div(a, b) << endl; } } catch (string &exp) { cout << "Are you kidding me?" << endl; cout << exp << endl; } return 0; }
b820f2beb674b0302478fc7c57f3a09d1d864793
7ec3a516999a3324d03f2f9b3c3e236fbbe8d837
/src/Game.cpp
f9352bbefd293dae8b705f556532761f7b108392
[]
no_license
antaires/tic-tac-toe-c-plus-plus
ba0db2c3d1225c359b9d10874c3050247b2332a6
26d159a8eba599ba1a664ed672f26135a8e91844
refs/heads/master
2021-01-09T12:52:12.116035
2020-02-29T08:42:07
2020-02-29T08:42:07
242,306,875
1
0
null
null
null
null
UTF-8
C++
false
false
1,592
cpp
Game.cpp
#include "./Game.h" Game::Game() { this->isRunning = false; } bool Game::IsRunning() const { return this->isRunning; } void Game::Initialize(int width, int height){ this->board = new Board(); this->graphics = new Graphics(); this->minimax = new Minimax(); graphics->Initialize(width, height); Start(); isRunning = true; return; } void Game::Start(){ this->currentPlayer = HUMAN; this->currentMove = 'X'; this->index = (ROW * COLUMN); gameState = START; board->Initialize(); } void Game::ProcessInput(){ if (!graphics->ProcessInput(board, gameState, currentPlayer, isRunning, index)){ isRunning = false; } if (board->GetBoardState() == RESET){ Game::Start(); } } void Game::ProcessAI(){ if (currentPlayer == PC && gameState == PLAYING){ minimax->GetBestMove(board, index); } } void Game::Update(){ // set move on board if (board->Update(currentMove, index)){ Game::TogglePlayer(); } gameState = board->GetBoardState(); } void Game::Render(){ graphics->Render(board, gameState); } void Game::TogglePlayer(){ if (currentPlayer == HUMAN){ currentPlayer = PC; currentMove = 'O'; } else { currentPlayer = HUMAN; currentMove = 'X'; } } unsigned int Game::GetGameState(){ return board->GetBoardState(); } unsigned int Game::GetCurrentPlayer(){ return this->currentPlayer; } unsigned int Game::GetCurrentMove(){ return this->currentMove; } unsigned int Game::GetIndex(){ return this->index; } void Game::Destroy(){ graphics->Destroy(); delete board; delete graphics; delete minimax; }
f6394bf40ba1a52677ce1f39689683113e44bfe4
a70581d6277d6f7540e26c83c854623aa2eccd87
/server/src/httpRequestParser.cpp
17627dcbcad498fb03ff6bce211e904fdbdb7400
[ "MIT" ]
permissive
icecreamrua/tiny-htttp-server
27f5ab97f7c0568ccacb0c569e020f6b6a0222a3
5ceb6bbe9753c895966fb1ecefad86b3d42d1a5a
refs/heads/main
2023-07-25T22:42:11.879648
2021-09-06T12:33:31
2021-09-06T12:33:31
402,740,761
0
0
null
null
null
null
GB18030
C++
false
false
5,914
cpp
httpRequestParser.cpp
#include "httpRequestParser.h" #include<iostream> httpRequestParser::httpRequestParser() : tem_data(new char[4096]), tem_idx(0), tem_size(4096), parser_state(ParserState::Request_Line_Parser) { } httpRequestParser::~httpRequestParser() { delete[] tem_data; } int httpRequestParser::getLine(std::string& output) { char tem; while ( buffer_idx < buffer_size && tem_idx < tem_size) { tem = buffer[buffer_idx]; tem_data[tem_idx] = tem; if (tem == '\r') { if (++buffer_idx==buffer_size) { return Line_More; } if (buffer[buffer_idx++] == '\n') { if (tem_idx == tem_size) { return Line_Overload; } else { tem_data[tem_idx] = '\0'; output += tem_data; memset(tem_data, 0, tem_size); int ret = tem_idx; tem_idx = 0; return ret; } } } ++tem_idx; ++buffer_idx; } if (tem_idx >= tem_size) return Line_Overload; else return Line_More; } int httpRequestParser::getn(std::string& output, size_t n) { if (n >= tem_size) return -1; size_t buffer_rest = buffer_size - buffer_idx; size_t tem_need = n - tem_idx; //缓存中数据字节大于需求量 if (buffer_rest >= tem_need) { memcpy(tem_data + tem_idx, buffer + buffer_idx, tem_need); buffer_idx += tem_need; tem_idx += tem_need; tem_data[tem_idx] = '\0'; output += tem_data; memset(tem_data, 0, n); tem_idx = 0; return 0; } memcpy(tem_data + tem_idx, buffer + buffer_idx, buffer_rest); buffer_idx += buffer_rest; return n - buffer_rest; } int httpRequestParser::setBuffer(const char* buffer) { this->buffer = buffer; return 0; } int httpRequestParser::setBufferSize(ssize_t len) { buffer_size = len; buffer_idx = 0; return 0; } int httpRequestParser::setRequest(httpRequest& request) { this->request = &request; return 0; } std::string httpRequestParser::decodeURL(const std::string& url) { if (url.empty()) return std::string(); std::string ret; int n = url.size(); for (int url_index = 0; url_index < n; ++url_index) { if (url[url_index] == '%') { if (url_index+2 < n ) { ret += std::stoi(url.substr(++url_index, 2), nullptr, 16); ++url_index; } else break; } else { ret += url[url_index]; } } return ret; } std::string httpRequestParser::getURI(const std::string& url) { int n = url.size(); if (!n) return std::string(); int url_idx = 0; if (url.substr(url_idx, 7) == "http://") { url_idx = 7; url_idx = url.find('/', url_idx); if (url_idx == std::string::npos) { return std::string(); } return url.substr(url_idx); } return url; } std::string& httpRequestParser::trim(std::string& str) { if (str.empty()) return str; str.erase(0, str.find_first_not_of(" ")); str.erase(str.find_last_not_of(" ") + 1); return str; } httpRequest::RequestState httpRequestParser::parseLine(std::string& line) { int n = line.size(); size_t line_idx = 0; //idx指向请求方式 if (line.find_first_of("GET") == line_idx) { request->method = httpDefinition::HttpMethod::GET; } else if (line.find_first_of("POST") == line_idx) { request->method = httpDefinition::HttpMethod::POST; } else if (line.find_first_of("PUT") == line_idx) { request->method = httpDefinition::HttpMethod::PUT; } else { request->method = httpDefinition::HttpMethod::METHOD_NOT_SUPPORT; return httpRequest::RequestState::Not_Support; } line_idx = line.find_first_of(" "); if (line_idx == std::string::npos) { return httpRequest::Bad_Request; } line_idx = line.find_first_not_of(" ", line_idx); //idx指向URI size_t uri_end = line.find_first_of(" ", line_idx); if(uri_end== std::string::npos) { return httpRequest::Bad_Request; } std::string URI = line.substr(line_idx, uri_end - line_idx); if (URI.empty()) { return httpRequest::Bad_Request; } URI = getURI(URI); URI = decodeURL(URI); size_t query_idx = URI.find_first_of('?'); if (query_idx != std::string::npos) { request->query = URI.substr(query_idx + 1, uri_end - query_idx - 1); request->file_path = URI.substr(0, query_idx); } else { request->file_path = URI; } line_idx = uri_end; line_idx = line.find_first_not_of(" ", line_idx); //idx指向http version std::string http_version = line.substr(line_idx, 8); if (http_version == "HTTP/1.1") { request->version = httpDefinition::HttpVersion::HTTP_11; request->keep_alive = true; } else if (http_version == "HTTP/1.0") { request->version = httpDefinition::HttpVersion::HTTP_10; } else if (http_version.find_first_of("HTTP/") != std::string::npos) { request->version = httpDefinition::HttpVersion::VERSION_NOT_SUPPORT; } else { return httpRequest::RequestState::Bad_Request; } parser_state = Request_Header_Parser; return httpRequest::RequestState::Continue_Request; } httpRequest::RequestState httpRequestParser::parseHeader_fromLine(std::string& line) { int n = line.size(); if (!n) { parser_state = Request_Body_Parser; return httpRequest::RequestState::Continue_Request; } if (n > 200) return httpRequest::RequestState::Bad_Request; char key[200], value[200]; std::sscanf(line.data(), "%[^:]:%[^:]", key, value); std::string key_s(key); std::string value_s(value); trim(key_s); trim(value_s); std::transform(key_s.begin(), key_s.end(), key_s.begin(), toupper); request->headerMp[key_s] = value_s; if (key_s == "CONTENT-LENGTH") { request->content_length = std::stoi(value_s); } if (key_s == "Connection") { if (value_s == "Keep-Alive") { request->keep_alive = true; } else if (value_s == "Close") { request->keep_alive = false; } } return httpRequest::RequestState::Continue_Request; }
fa9c18695a82f27642d0097849d4e107b32af829
b0069cfa317b9281f064a7fbd9d1463c33ee1ac4
/Firestore/core/src/model/field_index.h
57f159e9c670025bfbdb59ae757245e7cf1cc77e
[ "Swift-exception", "MIT", "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
firebase/firebase-ios-sdk
5bb2b5ef2be28c993e993517059452ddb8bee1e6
1dc90cdd619c5e8493df4a01138e2d87e61bc027
refs/heads/master
2023-08-29T23:15:28.905909
2023-08-29T21:49:41
2023-08-29T21:49:41
89,033,556
5,048
1,594
Apache-2.0
2023-09-14T21:11:30
2017-04-22T00:26:50
Objective-C
UTF-8
C++
false
false
9,742
h
field_index.h
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FIRESTORE_CORE_SRC_MODEL_FIELD_INDEX_H_ #define FIRESTORE_CORE_SRC_MODEL_FIELD_INDEX_H_ #include <string> #include <utility> #include <vector> #include "Firestore/core/src/model/document.h" #include "Firestore/core/src/model/document_key.h" #include "Firestore/core/src/model/field_path.h" #include "Firestore/core/src/model/snapshot_version.h" #include "Firestore/core/src/util/comparison.h" #include "absl/types/optional.h" namespace firebase { namespace firestore { namespace model { /** An index component consisting of field path and index type. */ class Segment : public util::Comparable<Segment> { public: /** The type of the index, e.g. for which type of query it can be used. */ enum Kind { /** * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN * queries. */ kAscending, /** * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN * queries. */ kDescending, /** Contains index. Can be used for Contains and ArrayContainsAny */ kContains, }; Segment(FieldPath field_path, Kind kind) : field_path_(std::move(field_path)), kind_(kind) { } /** The field path of the component. */ const FieldPath& field_path() const { return field_path_; } /** The indexes sorting order. */ Kind kind() const { return kind_; } util::ComparisonResult CompareTo(const Segment& rhs) const; private: FieldPath field_path_; Kind kind_; }; /** * Stores the latest read time and document that were processed for an index. */ class IndexOffset : public util::Comparable<IndexOffset> { public: /** * Creates an offset that matches all documents with a read time higher than * `read_time` or with a key higher than `key` for equal read times. */ IndexOffset(SnapshotVersion read_time, DocumentKey key, model::BatchId largest_batch_id) : read_time_(std::move(read_time)), document_key_(std::move(key)), largest_batch_id_(largest_batch_id) { } /** * The initial mutation batch id for each index. Gets updated during index * backfill. */ static constexpr model::BatchId InitialLargestBatchId() { return -1; } static IndexOffset None(); /** * Creates an offset that matches all documents with a read time higher than * `read_time`. */ static IndexOffset CreateSuccessor(SnapshotVersion read_time); /** Creates a new offset based on the provided document. */ static IndexOffset FromDocument(const Document& document); static util::ComparisonResult DocumentCompare(const Document& lhs, const Document& rhs); /** * Returns the latest read time version that has been indexed by Firestore for * this field index. */ const SnapshotVersion& read_time() const { return read_time_; } /** * Returns the key of the last document that was indexed for this query. * Returns `DocumentKey::Empty()` if no document has been indexed. */ const DocumentKey& document_key() const { return document_key_; } /** * Returns the largest mutation batch id that's been processed by index * backfilling. */ model::BatchId largest_batch_id() const { return largest_batch_id_; } /** Creates a pretty-printed description of the IndexOffset for debugging. */ std::string ToString() const { return absl::StrCat( "Index Offset: {read time: ", read_time_.ToString(), ", document key: ", document_key_.ToString(), ", largest batch id: ", std::to_string(largest_batch_id_), "}"); } util::ComparisonResult CompareTo(const IndexOffset& rhs) const; private: SnapshotVersion read_time_; DocumentKey document_key_; model::BatchId largest_batch_id_; }; /** * Stores the "high water mark" that indicates how updated the Index is for * the current user. */ class IndexState { public: /** * The initial sequence number for each index. Gets updated during index * backfill. */ constexpr static ListenSequenceNumber InitialSequenceNumber() { return 0; } IndexState() : sequence_number_(InitialSequenceNumber()), index_offset_(IndexOffset::None()) { } IndexState(ListenSequenceNumber sequence_number, IndexOffset offset) : sequence_number_(sequence_number), index_offset_(std::move(offset)) { } IndexState(ListenSequenceNumber sequence_number, SnapshotVersion read_time, DocumentKey key, model::BatchId largest_batch_id) : sequence_number_(sequence_number), index_offset_(std::move(read_time), std::move(key), largest_batch_id) { } /** * Returns a number that indicates when the index was last updated (relative * to other indexes). */ ListenSequenceNumber sequence_number() const { return sequence_number_; } /** Returns the latest indexed read time and document. */ const IndexOffset& index_offset() const { return index_offset_; } private: friend bool operator==(const IndexState& lhs, const IndexState& rhs); friend bool operator!=(const IndexState& lhs, const IndexState& rhs); ListenSequenceNumber sequence_number_; IndexOffset index_offset_; }; inline bool operator==(const IndexState& lhs, const IndexState& rhs) { return lhs.sequence_number_ == rhs.sequence_number_ && lhs.index_offset_ == rhs.index_offset_; } inline bool operator!=(const IndexState& lhs, const IndexState& rhs) { return !(lhs == rhs); } /** * An index definition for field indices in Firestore. * * Every index is associated with a collection. The definition contains a list * of fields and their index kind (which can be `Segment::Kind::kAscending`, * `Segment::Kind::kDescending` or `Segment::Kind::kContains` for * ArrayContains/ArrayContainsAny queries. * * Unlike the backend, the SDK does not differentiate between collection or * collection group-scoped indices. Every index can be used for both single * collection and collection group queries. */ class FieldIndex { public: /** An ID for an index that has not yet been added to persistence. */ constexpr static int32_t UnknownId() { return -1; } /** The state of an index that has not yet been backfilled. */ static IndexState InitialState() { static const IndexState kNone(IndexState::InitialSequenceNumber(), IndexOffset::None()); return kNone; } /** * Compares indexes by collection group and segments. Ignores update time * and index ID. */ static util::ComparisonResult SemanticCompare(const FieldIndex& left, const FieldIndex& right); FieldIndex() : index_id_(UnknownId()) { } FieldIndex(int32_t index_id, std::string collection_group, std::vector<Segment> segments, IndexState state) : index_id_(index_id), collection_group_(std::move(collection_group)), segments_(std::move(segments)), state_(std::move(state)) { } /** * The index ID. Returns -1 if the index ID is not available (e.g. the index * has not yet been persisted). */ int32_t index_id() const { return index_id_; } /** The collection ID this index applies to. */ const std::string& collection_group() const { return collection_group_; } /** Returns all field segments for this index. */ const std::vector<Segment>& segments() const { return segments_; } /** Returns how up-to-date the index is for the current user. */ const IndexState& index_state() const { return state_; } /** Returns all directional (ascending/descending) segments for this index. */ std::vector<Segment> GetDirectionalSegments() const; /** Returns the ArrayContains/ArrayContainsAny segment for this index. */ absl::optional<Segment> GetArraySegment() const; /** * A type that can be used as the "Compare" template parameter of ordered * collections to have the elements ordered using * `FieldIndex::SemanticCompare()`. * * Example: * std::set<FieldIndex, FieldIndex::SemanticLess> result; */ struct SemanticLess { bool operator()(const FieldIndex& left, const FieldIndex& right) const { return FieldIndex::SemanticCompare(left, right) == util::ComparisonResult::Ascending; } }; private: friend bool operator==(const FieldIndex& lhs, const FieldIndex& rhs); friend bool operator!=(const FieldIndex& lhs, const FieldIndex& rhs); int32_t index_id_ = UnknownId(); std::string collection_group_; std::vector<Segment> segments_; IndexState state_; }; inline bool operator==(const FieldIndex& lhs, const FieldIndex& rhs) { return lhs.index_id_ == rhs.index_id_ && lhs.collection_group_ == rhs.collection_group_ && lhs.segments_ == rhs.segments_ && lhs.state_ == rhs.state_; } inline bool operator!=(const FieldIndex& lhs, const FieldIndex& rhs) { return !(lhs == rhs); } } // namespace model } // namespace firestore } // namespace firebase #endif // FIRESTORE_CORE_SRC_MODEL_FIELD_INDEX_H_
961d61f401581ea376dcd8aedf76fef4f1ebdf7c
41863ae6b2f4c48d584c30d4f584541d6dea73f2
/Solution.cpp
8e90865029454022962c16dea4ef69e4bac5e76a
[]
no_license
MaximFisherman/CodingGame_Shadows-of-the-Knight-2
e55b986dacf18d5a06a617a920f80e77a81573e8
fdffaa5a0fb8dacd16448219d50505196a51a055
refs/heads/master
2020-03-24T14:30:51.588124
2018-07-29T15:04:45
2018-07-29T15:04:45
142,770,464
0
0
null
null
null
null
UTF-8
C++
false
false
8,201
cpp
Solution.cpp
#include <iostream> #include <string> #include <vector> #include <stack> #include <algorithm> using namespace std; #define _DEBUG_ #define _DEBUG_COORD namespace user { struct coordinate { public: int x; int y; coordinate() : x(0), y(0) {}; coordinate(int _x, int _y) : x(_x), y(_y) {}; coordinate(const coordinate& coord) : x(coord.x), y(coord.y) { }; coordinate& operator = (const coordinate& right) { //check self-assignment if (this == &right) { return *this; } this->x = right.x; this->y = right.y; return *this; } private: friend const coordinate operator+(const coordinate& left,const coordinate& right); friend const coordinate operator+=(const coordinate& left, const coordinate& right); friend const coordinate operator/(const coordinate& left, const coordinate& right); friend const coordinate operator/(const coordinate& left, int right); }; const coordinate operator+(const coordinate& left, coordinate& right) { return coordinate(left.x + right.x, left.y + right.y); } const coordinate operator+=(coordinate& left, coordinate& right) { return coordinate(left + right); } const coordinate operator/(const coordinate& left, const coordinate& right) { coordinate coord; coord.x = left.x / right.x; coord.y = left.y / right.x; #ifdef _DEBUG_COORD cerr << "|=========================|" << endl; cerr << "operator/(coordinate, coordinate)" << endl; cerr << coord.x << " " << coord.y << endl; #endif return coord; } const coordinate operator/(const coordinate& left, int right) { coordinate coord; coord.x = left.x / right; coord.y = left.y / right; #ifdef _DEBUG_COORD cerr << "|=========================|" << endl; cerr << "operator/(coordinate, int)" << endl; cerr << coord.x << " " << coord.y << endl; #endif return coord; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct Rectangle { Rectangle(user::coordinate _vertex1, user::coordinate _vertex2) : vertex1(_vertex1), vertex2(_vertex2) { #ifdef _DEBUG_ cerr << "|-------------------|\n"; cerr << "Constructor Rectangle \n"; cerr << "vertex1 " << _vertex1.x << " " << _vertex1.y << "\n"; cerr << "vertex2 " << _vertex2.x << " " << _vertex2.y << "\n\n\n"; #endif } user::coordinate getRectangleCenter() { return user::coordinate(vertex2.x / 2, vertex1.y + (abs(vertex2.y - vertex1.y) / 2)); } user::coordinate vertex1; /* HIGHT rectansle points */ user::coordinate vertex2; /* WIDTH rectansle points */ }; class Search { public: user::coordinate convertCoordinate(int x, int y) { return user::coordinate(x, (H - y)); } void Move(std::string position) { bool horizontalAlignment = H <= 3 ? true : false; bool firstMove = false; #ifdef _DEBUG_ cerr << "\n|-------------------|\n"; cerr << "Move: " << position << endl << endl; #endif if(position == "UNKNOWN") { rectangles.push(Rectangle(user::coordinate(0, 0), user::coordinate(W, H / 2))); rectangles.push(Rectangle(user::coordinate(0, H / 2), user::coordinate(W, H))); cout << rectangles.top().getRectangleCenter().x << " " << rectangles.top().getRectangleCenter().y << endl; //rectangles.pop(); } if(position == "WARMER") { if(horizontalAlignment == true) { //W = rectangles.top().vertex2.x; } else { if () #ifdef _DEBUG_ cerr << "\n|-------------------|\n"; cerr << "H: " << abs(rectangles.top().vertex1.y - rectangles.top().vertex2.y) << endl << endl; #endif H = abs(rectangles.top().vertex1.y - rectangles.top().vertex2.y); /* width not change with vertical aligment */ user::coordinate coordLastRectangleV1 = rectangles.top().vertex1; user::coordinate coordLastRectangleV2 = rectangles.top().vertex2; #ifdef _DEBUG_ cerr << "\n|-------------------|\n"; cerr << "coordLastRectangleV1: " << coordLastRectangleV1.x << " " << coordLastRectangleV1.y << endl; #endif stack<Rectangle>().swap(rectangles); //clear stack rectangles.push(Rectangle(user::coordinate(0, coordLastRectangleV1.y), user::coordinate(W, coordLastRectangleV1.y + H / 2))); rectangles.push(Rectangle(user::coordinate(0, coordLastRectangleV1.y + H / 2), user::coordinate(W, coordLastRectangleV1.y + H))); cout << rectangles.top().getRectangleCenter().x << " " << rectangles.top().getRectangleCenter().y << endl; } } if(position == "COLDER") { rectangles.pop(); cout << rectangles.top().getRectangleCenter().x << " " << rectangles.top().getRectangleCenter().y << endl; } if(position == "SAME") { cout << "stop stop stop" << endl; } } Search(int _H, int _W) : H(_H - 1), W(_W - 1) {}; private: //Triangle tr(user::coordinate(0, 16), user::coordinate(5, 0), user::coordinate(0, 0)); std::stack<Rectangle> rectangles; int W, H; }; int main() { int W; // width of the building. int H; // height of the building. cin >> W >> H; cin.ignore(); cerr << "H: " << H << " W:" << W << endl; Search tr(H, W); int N; // maximum number of turns before game over. cin >> N; cin.ignore(); int X0; int Y0; cin >> X0 >> Y0; cin.ignore(); // game loop while (1) { string bombDir; // Current distance to the bomb compared to previous distance (COLDER, WARMER, SAME or UNKNOWN) cin >> bombDir; cin.ignore(); cerr << bombDir << endl; //cout << W / 2 << " " << (H / 2) / 2 << endl; //cout << "0 31" << endl; //cout << "17 0" << endl; //cout << "9 15" << endl; //cout <<"asdasdad" << endl; tr.Move(bombDir); } }
e160582e15d8798a88d87c5000359074f85f5790
87f9cb5d08c5b75a3e2767b653976039f67a9560
/mot/cholesky.h
737b4b206080158240a7d7f0eca8c2ecdccf4e01
[]
no_license
sunlinlin-aragon/TensorRT-Scaled-YOLOv4
e287c9c440956fd07f704d0d0fc3c70a6a8afbbf
520b54b469221f55e1afb7c4396a0a854dd74c13
refs/heads/master
2023-04-20T04:10:30.951232
2021-04-29T13:37:21
2021-04-29T13:37:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
310
h
cholesky.h
#ifndef _CHOLESKY_H_ #define _CHOLESKY_H_ #include <vector> namespace cholesky{ using namespace std; vector<vector<float>> fuck_cholesky(const vector<vector<float>> matrix); vector<vector<float>> fuck_cholesky_solve(const vector<vector<float>>lower_diag,const vector<vector<float>> b); } #endif
6e46398e2e3fd03dd5529645bd3cf33867b9ca8d
01cef00c34ac59e6ed6017f13e410709293ac94e
/include/cores/CameraCore.hpp
2a10148843f59005ee2518c9935b0f668b01cf68
[]
no_license
thelaui/guacamole-attic
4b35130f45a97f2c2169d2262bbcb259de4881dd
e267d7c4a68a833fda5d125b023744b1ae9f72de
refs/heads/master
2020-04-11T04:27:38.150880
2012-11-11T12:33:13
2012-11-11T12:33:13
2,898,153
1
0
null
null
null
null
UTF-8
C++
false
false
2,611
hpp
CameraCore.hpp
//////////////////////////////////////////////////////////////////////////////// // Guacamole - An interesting scenegraph implementation. // // Copyright: (c) 2011-2012 by Felix Lauer and Simon Schneegans // Contact: felix.lauer@uni-weimar.de / simon.schneegans@uni-weimar.de // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // // You should have received a copy of the GNU General Public License along with // this program. If not, see <http://www.gnu.org/licenses/>. // /// \file /// \brief Declaration of the CameraCore class. //////////////////////////////////////////////////////////////////////////////// #ifndef GUA_CAMERA_CORE_HPP #define GUA_CAMERA_CORE_HPP #include "scenegraph/Core.hpp" //////////////////////////////////////////////////////////////////////////////// /// \brief This class is used to represent a camera in the SceneGraph. /// //////////////////////////////////////////////////////////////////////////////// namespace gua { class CameraCore: public Core { public: //////////////////////////////////////////////////////////////////////// ///\brief Constructor. /// /// This constructs a CameraCore with the given parameters and calls /// the constructor of base class Core with the type CAMERA. /// ///\param stereo_width The gap between the eyes. //////////////////////////////////////////////////////////////////////// CameraCore(float stereo_width = 0.f); //////////////////////////////////////////////////////////////////////// ///\brief Destructor. /// /// This destructs a CameraCore. //////////////////////////////////////////////////////////////////////// virtual ~CameraCore(); //////////////////////////////////////////////////////////////////////// ///\brief Returns the StereoCameraCore's gap between the eyes. /// ///\return The camera's eye gap. //////////////////////////////////////////////////////////////////////// float get_stereo_width() const; private: float stereo_width_; }; } #endif // GUA_CAMERA_CORE_HPP
253b50b00815d714d740254697d41f2178177820
800ad43d3b6e27c5ad1e3e8fac97c5fb1fb9f697
/R-Prototype/Game/Renderer.cpp
4b740d0b239faed4d92c4d938faef866c8df64e3
[]
no_license
lmsierra/R-Prototype
dd6531e38da32215701e93a1c0c905496f08c4f0
df0519d47466ae756d9d97751b6c01cb60f6a59f
refs/heads/master
2021-01-23T13:35:31.003030
2017-09-07T00:19:59
2017-09-07T00:19:59
102,670,898
0
0
null
null
null
null
UTF-8
C++
false
false
777
cpp
Renderer.cpp
#include "stdafx.h" #include "Renderer.h" #include "Sprite.h" #include "HUD.h" Renderer::Renderer() { } Renderer::~Renderer() { } void Renderer::Init() { hud = new HUD(); } void Renderer::Deinit() { sprites.clear(); } void Renderer::AddSprite(Sprite *sprite) { sprites.push_back(sprite); } void Renderer::DeleteSprite(Sprite* sprite) { for(int i = 0; i < sprites.size(); i++) { if(sprites[i] == sprite) { sprites.erase(sprites.begin() + i); } } } void Renderer::Run() { for(Sprite* sprite : sprites) { CORE_RenderCenteredSprite(sprite->GetPos(), sprite->GetSize(), sprite->GetTexture()); } hud->Draw(); }
03313b8048cb27ba13f6794eb681465eb1e2e758
a6881510f380da03ff438003b47248caa87f1cef
/server/src/main.cpp
4d65e0e2d1f0e8efb951602c9c350447ac17ab8a
[]
no_license
P3ti/RakSAMP
d6ea216aff175e81eb77b1e675d0c130c5163846
670cf880f8c1541334f31b25ec0e1e3a7640b722
refs/heads/master
2018-01-12T15:00:31.237615
2017-07-09T07:49:53
2017-07-09T07:49:53
21,405,476
74
50
null
2018-08-20T02:52:39
2014-07-01T23:38:33
C++
UTF-8
C++
false
false
3,386
cpp
main.cpp
/* Updated to 0.3.7 by P3ti */ #include "main.h" TiXmlDocument xmlSettings; char szWorkingDirectory[MAX_PATH]; int iMainLoop = 1; RakServerInterface *pRakServer = NULL; unsigned int _uiRndSrvChallenge; int iPort; unsigned short usMaxPlayers; int iLagCompensation; char szLogFile[MAX_PATH]; FILE *flLog = NULL; struct stPlayerInfo playerInfo[MAX_PLAYERS]; int main(int argc, char *argv[]) { if(GetModuleFileName(NULL, szWorkingDirectory, sizeof(szWorkingDirectory) - 32) != 0) { if(strrchr(szWorkingDirectory, '\\') != NULL) *strrchr(szWorkingDirectory, '\\') = 0; else strcpy_s(szWorkingDirectory, 1, "."); } else strcpy_s(szWorkingDirectory, 1, "."); SetConsoleTitle("RakSAMP server"); if(!xmlSettings.LoadFile("RakSAMPServer.xml")) { MessageBox(NULL, "Failed to load the config file", "ERROR ERROR ERROR ERROR", MB_ICONERROR); ExitProcess(0); } TiXmlElement* serverElement = xmlSettings.FirstChildElement("server"); if(serverElement) { usMaxPlayers = (unsigned short)atoi(serverElement->Attribute("max_players")); iPort = (int)atoi(serverElement->Attribute("port")); strcpy(serverName, serverElement->Attribute("name")); iLagCompensation = (int)atoi(serverElement->Attribute("lagcomp")); if(iLagCompensation) modifyRuleValue("lagcomp", "On"); else modifyRuleValue("lagcomp", "Off"); } Log(" "); Log(" * ============================== *"); Log(" RakSAMP server "); Log(" "); Log(" Version: " RAKSAMP_VERSION " "); Log(" Authors: " AUTHOR " "); Log(" * ============================== *"); Log(" "); LoadScripts(); // Create a challenge number for the clients to be able to connect srand((unsigned int)time(NULL)); _uiRndSrvChallenge = (unsigned int)rand(); pRakServer = RakNetworkFactory::GetRakServerInterface(); LoadBanList(); pRakServer->Start(usMaxPlayers, 0, 5, iPort); pRakServer->StartOccasionalPing(); RegisterServerRPCs(pRakServer); // Main loop while(iMainLoop) { UpdateNetwork(); Sleep(5); } if(flLog != NULL) { fclose(flLog); flLog = NULL; } pRakServer->Disconnect(300); RakNetworkFactory::DestroyRakServerInterface(pRakServer); return 0; } void Log ( char *fmt, ... ) { SYSTEMTIME time; va_list ap; if ( flLog == NULL ) { flLog = fopen( "RakSAMPServer.log", "a" ); if ( flLog == NULL ) return; } GetLocalTime( &time ); fprintf( flLog, "[%02d:%02d:%02d.%03d] ", time.wHour, time.wMinute, time.wSecond, time.wMilliseconds ); va_start( ap, fmt ); vprintf( fmt, ap ); vfprintf( flLog, fmt, ap ); va_end( ap ); fprintf( flLog, "\n" ); printf( "\n" ); fflush( flLog ); } unsigned char rand_byteRange(unsigned char a, unsigned char b) { return ((b-a)*((unsigned char)rand()/RAND_MAX))+a; } unsigned short rand_shortRange(unsigned short a, unsigned short b) { return ((b-a)*((unsigned short)rand()/RAND_MAX))+a; } unsigned int rand_intRange(unsigned int a, unsigned int b) { return ((b-a)*((unsigned int)rand()/RAND_MAX))+a; } float rand_floatRange(float a, float b) { return ((b-a)*((float)rand()/RAND_MAX))+a; } void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789~" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; }
ec345e8ffaee76f2fe1472525a0d30821d6e1c1e
f62223da2505395adf6954d21a3443411229c23f
/Core/RequestFactory.h
face3c3da29e007aaadf10169202c824189e1e13
[]
no_license
jell0wed/8tracksplayer
08f0e7da42a84ff31b80634522bc169d94e07587
139b46b2d413c3832286c8ef0411b1771402b19f
refs/heads/master
2021-01-01T18:17:47.282635
2015-01-23T05:47:15
2015-01-23T05:47:15
29,718,357
0
0
null
null
null
null
UTF-8
C++
false
false
653
h
RequestFactory.h
#ifndef REQUESTFACTORY_H #define REQUESTFACTORY_H /** factory used to create request from specified actions and parameters */ #include <map> #include <string> #include <assert.h> #include "API_Defines.h" #include "BaseRequest.h" #include "LoginRequest.h" #include "MixSearchRequest.h" #include "PlayTokenRequest.h" #include "GetSetRequest.h" #include "PlayReportRequest.h" #include "GetTagsRequest.h" #include "GetMixRequest.h" using std::map; using std::string; using std::pair; namespace tracksAPI { class RequestFactory { public: static BaseRequest* createRequest(API_ACTIONS action, map<API_REQUESTS_PARAMS, string> params); }; } #endif
81d2672cc0166f6f3e69b60bdfeee2bd1ba45fab
8c731cbbe3743b7e275a486b6a6582d732e08e4a
/myhttpd.cc
34106242f8a1e0d129f2ab0359d5f7617445bbc0
[]
no_license
HongxuMeng/cs252
6fcadd0bb62484fb5dac4742e2412598953223b5
5eccecf9bf833cc6ed3287115fd0db6aa94b3fcc
refs/heads/master
2022-01-22T19:47:18.969123
2019-07-31T20:34:12
2019-07-31T20:34:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,209
cc
myhttpd.cc
const char * usage = " \n"; #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <time.h> #include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <sys/stat.h> #include <fcntl.h> #include <time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <bits/stdc++.h> #include <pthread.h> using namespace std; time_t startime; string contentType; int debug = 1; int QueueLength = 5; //global var for mode 1 for -f; 2 for -t; 3 for -p; 0 for basic int mode = 0; //port number int port = 0; //flag for compare helper; 0 for asc, 1 for des; int cmp_flag = 0; //number of request int num_req = 0; pthread_mutex_t mutex1; // Processes time request void processRequest( int socket ); void dispatchHTTP(int fd); void *loopthread(int fd); void poolOfThreads(int masterSocket); void createThreadForEachRequest(int masterSocket); string get_argument(string docpath); extern "C" void killzombie(int sig); void poolOfThreads(int masterSocket) { pthread_t tid[4]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&mutex1, NULL); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); for (int i = 0; i < 4; i++) { pthread_create(&tid[i], NULL, (void * (*)(void *))loopthread, (void *)masterSocket); } loopthread(masterSocket); } void *loopthread (int fd) { while (1) { pthread_mutex_lock(&mutex1); struct sockaddr_in clientIPAddress; int alen = sizeof(clientIPAddress); int slaveSocket = accept(fd, (struct sockaddr *)&clientIPAddress, (socklen_t*)&alen); ++num_req; pthread_mutex_unlock(&mutex1); if (slaveSocket >= 0) { dispatchHTTP(slaveSocket); } } } int main( int argc, char ** argv ) { if (argc == 2) { // Get the port from the arguments port = atoi( argv[1] ); } else if (argc == 3) { //get the concurrency type if (argv[1][0] == '-') { if (argv[1][1] == 'f') { //create a new process for each request mode = 1; } else if (argv[1][1] == 't') { //create a new thread for each request mode = 2; } else if (argv[1][1] == 'p') { //pool of threads mode = 3; printf("ppppppppppppppppp\n"); printf("mode:"); printf("%d",mode); printf("\n"); } else { fprintf( stderr, "%s", usage); exit(-1); } } port = atoi( argv[2] ); } else { fprintf( stderr, "%s", usage ); exit(-1); } printf("mmmmmmmmmm\n"); printf("mode:"); printf("%d",mode); printf("\n"); struct sigaction sa2; sa2.sa_handler = killzombie; sigemptyset(&sa2.sa_mask); sa2.sa_flags = SA_RESTART; if (sigaction(SIGCHLD,&sa2, NULL)) { perror("sigaction"); exit(2); } //printf("mode:%s\n",mode); // Set the IP address and port for this server struct sockaddr_in serverIPAddress; memset( &serverIPAddress, 0, sizeof(serverIPAddress) ); serverIPAddress.sin_family = AF_INET; serverIPAddress.sin_addr.s_addr = INADDR_ANY; serverIPAddress.sin_port = htons((u_short) port); // Allocate a socket int masterSocket = socket(PF_INET, SOCK_STREAM, 0); if ( masterSocket < 0) { perror("socket"); exit( -1 ); } // Set socket options to reuse port. Otherwise we will // have to wait about 2 minutes before reusing the sae port number int optval = 1; int err = setsockopt(masterSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof( int ) ); // Bind the socket to the IP address and port int error = bind( masterSocket, (struct sockaddr *)&serverIPAddress, sizeof(serverIPAddress) ); if ( error ) { perror("bind"); exit( -1 ); } // Put socket in listening mode and set the // size of the queue of unprocessed connections error = listen( masterSocket, QueueLength); if ( error ) { perror("listen"); exit( -1 ); } printf("mode: %d ==================\n",mode); if (mode == 3) { printf("p mode===========================================\n"); poolOfThreads(masterSocket); printf("oooooo"); } /*else if(mode==2){ createThreadForEachRequest(masterSocket); }*/ else { while ( 1 ) { // Accept incoming connections struct sockaddr_in clientIPAddress; int alen = sizeof( clientIPAddress ); int slaveSocket = accept( masterSocket, (struct sockaddr *)&clientIPAddress, (socklen_t*)&alen); //needs modify, keep server running if there is an error if ( slaveSocket < 0 ) { perror( "accept" ); exit( -1 ); } num_req++; if (mode == 0) { processRequest(slaveSocket); close(slaveSocket); } //process based -f else if (mode == 1) { pid_t slave = fork(); if (slave == 0) { processRequest(slaveSocket); close(slaveSocket); } close(slaveSocket); } //thread based else if (mode == 2) { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&thread, &attr, (void* (*)(void*))dispatchHTTP, (void *) slaveSocket); } } } } void createThreadForEachRequest(int masterSocket) { while (1) { struct sockaddr_in clientIPAddress; int alen = sizeof( clientIPAddress ); int slaveSocket = accept( masterSocket, (struct sockaddr *)&clientIPAddress, (socklen_t*)&alen); if (slaveSocket >= 0) { // When the thread ends resources are recycled num_req++; pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); pthread_create(&thread, &attr,(void* (*)(void*))dispatchHTTP, (void *) slaveSocket); } } } void processRequest(int socket) { const int size = 4000; int length = 0; int n; int gotGet = 0; int docpath_index = 0; unsigned char newChar; unsigned char oldChar = 0; unsigned char olldchar = 0; unsigned char ollldchar = 0; string request; string request_type; string docpath; string argument; //read request while (length < size && (n = read(socket, &newChar, sizeof(newChar))) > 0) { printf("%c",newChar); if (newChar == ' ') { if (!gotGet) { gotGet = length; //request_type = request; } else if (!docpath_index) { docpath_index = length; docpath = request.substr(gotGet+1, length-gotGet-1); } } else if (newChar == '\n' && oldChar == '\r' && olldchar == '\n' && ollldchar == '\r') { break; } else { ollldchar = olldchar; olldchar = oldChar; oldChar = newChar; } ++length; request += newChar; } printf("request:%s\n",request); //autherization int auth=1; char *occur; int l=request.length(); char rl[l+1]; strcpy(rl,request.c_str()); printf("docpath: %s\n",docpath); occur=strstr(rl,"Authorization: Basic"); if(occur){ printf("here"); char * occur2; occur2=strstr(occur,"\r\n"); char cred[100]={0}; strncpy(cred,occur+21,occur2-occur-21); printf("cred=%s\n",cred); printf("number %d\n",strcmp(cred,"U3Vubnk6MTIzNDU2Nw==")); if(strcmp(cred,"U3Vubnk6MTIzNDU2Nw==")!=0){ printf("0\n"); auth=0; } } printf("auth=%d\n",auth); if(auth==0|| occur==NULL){ //print write(socket,"HTTP/1.1 401 Unauthorized\r\n",strlen("HTTP/1.1 401 Unauthorized\r\n")); write(socket,"WWW-Authenticate: Basic realm=\"myhttpd-cs252\"\r\n",strlen("WWW-Authenticate: Basic realm=\"myhttpd-cs252\"\r\n")); return; } char cwd[size + 1] = {0}; getcwd(cwd, sizeof(cwd)); string address; address = cwd; //get adddress if (strcmp(docpath.c_str(),"/") == 0 && docpath.length() == 1) { address +="/http-root-dir/htdocs/index.html"; } else{ address += "/http-root-dir/htdocs"; address += docpath; } char rpp[size + 1] = ""; char *res = realpath(address.c_str(), rpp); printf("rpp:%s",rpp); if (strstr(rpp, ".text") || strstr(rpp, ".text/")) { contentType = "text/plain"; } else if (strstr(rpp, ".gif") || strstr(rpp, ".gif/")) { contentType = "image/gif"; } else { contentType = "text/html"; } DIR *directory = opendir(rpp); FILE *document; if (strstr(rpp, ".gif") || strstr(rpp, ".gif/")) { document = fopen(address.c_str(), "rb"); }else{ document = fopen(address.c_str(), "r"); } if (document > 0) { const char * protocol = "HTTP/1.0 200 Document follows"; const char * crlf = "\r\n"; const char * server = "Server: CS 252 lab5/1.0"; const char * content_type = "Content-type: "; write(socket, protocol, strlen(protocol)); write(socket, crlf, strlen(crlf)); write(socket, server, strlen(server)); write(socket, crlf, strlen(crlf)); write(socket, content_type, strlen(content_type)); write(socket, crlf, strlen(crlf)); write(socket, crlf, strlen(crlf)); long count = 0; char ch; while (count = read(fileno(document), &ch,sizeof(ch))) { if (write(socket, &ch, sizeof(ch)) != count) { perror("write"); } } fclose(document); } else { const char * notFound = "HTTP/1.0 404 File Not Found"; const char * crlf = "\r\n"; const char * server = "Server: CS 252 lab5/1.0"; const char * content_type = "Content-type: "; const char * err_msg = "File not Found"; write(socket, notFound, strlen(notFound)); write(socket, crlf, strlen(crlf)); write(socket, server, strlen(server)); write(socket, crlf, strlen(crlf)); write(socket, content_type, strlen(content_type)); write(socket, crlf, strlen(crlf)); write(socket, crlf, strlen(crlf)); write(socket, err_msg, strlen(err_msg)); } } void dispatchHTTP (int socket) { processRequest(socket); close(socket); } extern "C" void killzombie(int sig) { int pid = 1; while(waitpid(-1, NULL, WNOHANG) > 0); }
ef924b43be4e9fde799348c4c077cdff9dcf7e20
c76e78581983830158b2a6f56b807e37132f4bba
/Codeforces/c1400-1499/c1433p3.cpp
8a2f7321f72dfeecfadbf25b3c157ffb5fa7da61
[]
no_license
itslinotlie/competitive-programming-solutions
7f72e27bbc53046174a95246598c3c9c2096b965
b639ebe3c060bb3c0b304080152cc9d958e52bfb
refs/heads/master
2021-07-17T17:48:42.639357
2021-05-29T03:07:47
2021-05-29T03:07:47
249,599,291
2
1
null
null
null
null
UTF-8
C++
false
false
853
cpp
c1433p3.cpp
// 10/20/2020 // https://codeforces.com/contest/1433/problem/C #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define CLR(a) memset(a, 0, sizeof(a)) #define REP(i, n) for(int i=0;i<n;i++) #define FOR(i, n) for(int i=1;i<=n;i++) #define F first #define S second const int mxn = 3e5+5; int t, n, a[mxn], maxi, b, id; int main() { cin >> t; while(t--) { cin >> n; b = 1; id = 1; memset(a, 0, sizeof(a)); for (int i=1;i<=n;i++) cin >> a[i]; for (int i=2;i<=n;i++) { if(a[id]!=a[i]) b=0; if(a[i]>a[id]) id = i; } if(!b) { for (int i=2;i<n;i++) { if(a[i]==a[id] && (a[i]>a[i-1] || a[i]>a[i+1])) {id = i; break;} } } if(b) puts("-1"); else cout << id << endl; } }