blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
32a626865948bc03c9d4d57f9455d28ec7b885f3
cb954f4769f77ac4bb6ee0138aaa5ac7afaec743
/createnotepaddialog.cpp
b64b37ef8b295ba0a10d92f2eedba8e862b87c41
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
graylira/PomodroidoLite
261c192e26ec70cf83b9d31a7f717a35835102cf
1e831199708888d037ac0652b645faeaca4e82c1
refs/heads/master
2020-04-16T17:50:40.555332
2019-01-21T07:46:16
2019-01-21T07:46:16
165,791,189
2
0
Apache-2.0
2019-01-18T11:08:29
2019-01-15T05:32:46
C++
UTF-8
C++
false
false
6,596
cpp
#include <QSettings> #include <QMessageBox> #include <vector> #include <QDir> #include <QMenu> #include <QTextStream> #include <iostream> #include "ui_createnotepaddialog.h" #include "createnotepaddialog.h" #include "savenotepadinidialog.h" #include "parameter_config.h" using namespace std; CreateNotepadDialog::CreateNotepadDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CreateNotepadDialog) { ui->setupUi(this); ListInit(); ui->listWidget_record->setContextMenuPolicy(Qt::CustomContextMenu); m_nPomodroidoID = -1; connect(ui->listWidget_record, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&))); //配置表table 增加右键菜单 } CreateNotepadDialog::CreateNotepadDialog(const unsigned int& PomodroidoID,QWidget *parent) : QDialog(parent), ui(new Ui::CreateNotepadDialog) { ui->setupUi(this); ListInit(); m_nPomodroidoID = PomodroidoID; ui->listWidget_record->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->listWidget_record, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ShowContextMenu(const QPoint&))); //配置表table 增加右键菜单 } CreateNotepadDialog::~CreateNotepadDialog() { delete ui; } void CreateNotepadDialog::ListInit() { vector<QString> vecName; vector<QString>::const_iterator it; QDir *dir = new QDir(Base_Path); QStringList filter; QString strNameTemp; QList<QFileInfo> *fileInfo = new QList<QFileInfo>(dir->entryInfoList(filter)); int num = ui->listWidget_record->count(); ui->listWidget_record->setFocus(); for (int i = 0; i<num; i++) { QListWidgetItem*item = ui->listWidget_record->takeItem(0); delete item; } for (int i = 0; i<fileInfo->count(); i++) { strNameTemp = fileInfo->at(i).fileName(); strNameTemp = strNameTemp.left(strNameTemp.length() - 4); vecName.push_back(strNameTemp); } if ((fileInfo->count()>0) && (!vecName.empty())) { for (it = vecName.begin() + 2; it != vecName.end(); ++it) { ui->listWidget_record->addItem(*it); } } delete fileInfo; } bool CreateNotepadDialog::upLoadingSlot() { SaveNotepadIniDialog saveNotepadIniDialog; QString txtTypeRemark; QString curName, text, qPath; if (saveNotepadIniDialog.exec() == QDialog::Accepted) { curName = saveNotepadIniDialog.GetIniName(); if(m_nPomodroidoID==-1) txtTypeRemark = "普通记事本-"; else txtTypeRemark = "番茄-" + QString::number(m_nPomodroidoID)+"-"; /*存入当前配置名到系统配置*/ QSettings *configIniWriteSetting = new QSettings(Files_Path, QSettings::IniFormat); configIniWriteSetting->setValue(Config_Setting_IniName, curName); delete configIniWriteSetting; /*分选配置*/ qPath = Base_Path + txtTypeRemark + curName; QSettings *configIniWriteSettingUser = new QSettings(qPath, QSettings::IniFormat); QFileInfo fileInfo(qPath); if(fileInfo.isFile()) { QMessageBox::information(this, "提示","日志已存在!");//return -1; return false; } /*用户信息配置*/ text = ui->textEdit_content->toPlainText(); QFile f(qPath); if(!f.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::information(this, "提示","写入失败!");//return -1; return false; } QTextStream txtOutput(&f); txtOutput << text << endl; QMessageBox::information(this, "提示","日志保存成功!"); ListInit(); delete configIniWriteSettingUser; } return true; } /*-------------------------------------------------------- 函数名:ShowContextMenu(void) 功能:list 菜单模块 创建:赵泽文 出口: 入口: --------------------------------------------------------*/ void CreateNotepadDialog::ShowContextMenu(const QPoint& ) { QMenu *cmenu = nullptr; if (cmenu)//保证同时只存在一个menu,及时释放内存 { delete cmenu; cmenu = nullptr; } cmenu = new QMenu(ui->listWidget_record); QAction *deleteSortAction = cmenu->addAction("删除"); connect(deleteSortAction, SIGNAL(triggered(bool)), this, SLOT(DeleteIniSort())); cmenu->exec(QCursor::pos());//在当前鼠标位置显示 } /*-------------------------------------------------------- 函数名:DeleteIniSort(void) 功能:list 菜单 的删除选项 创建:赵泽文 出口: 入口: --------------------------------------------------------*/ void CreateNotepadDialog::DeleteIniSort() { QString curName = ui->listWidget_record->currentItem()->text(); QString strPath = Base_Path + curName+".txt"; QFile file(strPath); QListWidgetItem* item = ui->listWidget_record->takeItem(ui->listWidget_record->currentRow()); file.remove(); int num = ui->listWidget_record->count(); if (num > 0) //重新写入 { curName = ui->listWidget_record->currentItem()->text(); curName = curName.left(curName.length() - 4); QSettings *configIniWriteSetting = new QSettings(Files_Path, QSettings::IniFormat); configIniWriteSetting->setValue(Config_Setting_IniName, curName); delete configIniWriteSetting; } else if (num == 0) QMessageBox::information(this, "提示", "无任何日志信息!"); delete item; } /*-------------------------------------------------------- 函数名:loadIniInfoSlot(void) 功能:tabwidget双击载入配置方案 创建:赵泽文 出口: 入口: --------------------------------------------------------*/ void CreateNotepadDialog::loadIniInfoSlot() { QString qPath,curName; curName = ui->listWidget_record->currentItem()->text(); qPath = Base_Path + curName +".txt"; QFile f(qPath); if(!f.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::information(this, "提示","读取失败!");//return -1; } QTextStream txtInput(&f); QString lineStr; while(!txtInput.atEnd()) { lineStr += txtInput.readLine(); } f.close(); ui->textEdit_content->setText(lineStr); // /*存入当前配置名到系统配置*/ // curName = curName.left(curName.length() - 4); // QSettings *configIniWriteSetting = new QSettings(Files_Path, QSettings::IniFormat); // configIniWriteSetting->setValue(Config_Setting_IniName, curName); // delete configIniWriteSetting; }
[ "graylira@163.com" ]
graylira@163.com
4d014804b0b88893e31c4010c0eb178c9dee1c57
9f581bd3ffcf17184bd6d2896789cc65bcfe7cc9
/Software/Modules/Base/Sources/resources.cpp
40f59cbca1680bd84c6a061c80473a7e603d1164
[]
no_license
imptz/ABMI.00083-01
c35d841d645ca46d57e2a853ba73992849aa950c
11a574d68a51467a20a2b2b2908ad210954c3d35
refs/heads/master
2016-09-06T16:02:12.953520
2013-10-31T13:13:43
2013-10-31T13:13:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
cpp
#include "resources.h" const char* ExceptionResourcesInit::what() const throw(){ return "Initialize failed"; } const char* ExceptionResourcesNotFound::what() const throw(){ return "Resource not found"; } Resources::Resources() : fInit(false){ } std::ifstream::pos_type Resources::getFileSize(std::string filename) { std::ifstream in(filename.c_str(), std::ifstream::in | std::ifstream::binary); in.seekg(0, std::ifstream::end); std::ifstream::pos_type size = in.tellg(); in.close(); return size; } void Resources::init(std::string _resourcesDir){ resourcesDir = _resourcesDir; DIR *dp; struct dirent *dirp; if((dp = opendir(resourcesDir.c_str())) == NULL) throw ExceptionResourcesInit(); while ((dirp = readdir(dp)) != NULL){ std::string fileName(dirp->d_name); if ((fileName != ".") && (fileName != "..")){ resourcesList["/" + fileName] = getFileSize(resourcesDir + "/" + fileName); } } closedir(dp); fInit = true; } Resource Resources::getResource(std::string name){ if (!fInit) throw ExceptionResourcesNotFound(); auto it = resourcesList.find(name); if (it == resourcesList.end()) throw ExceptionResourcesNotFound(); std::ifstream resourceFile(resourcesDir + name, std::ifstream::in | std::ifstream::binary); if (!resourceFile.good()) throw ExceptionResourcesNotFound(); Resource result; result.size = resourcesList[name]; result.pData = new char[result.size]; std::filebuf* pbuf = resourceFile.rdbuf(); pbuf->sgetn(result.pData, result.size); resourceFile.close(); return result; }
[ "ilja@ptz.com" ]
ilja@ptz.com
4c3e0dfc5fee6e07dfb65055c5f1bd8ba9a7a904
2a9246c620b588068e2a82a166f7836bf56938e3
/HiHLTAlgos/macros/TrigAnalysis/commonUtility.h
a83b3cf266c6c22a25317057752fca53540b6878
[]
no_license
CmsHI/CVS_CmsHi
6dc20b07a34a8927f1af3d11b59b59058b5ddeeb
9b9dcd34a1b718e4649ca2ddc34583706dfd5d1c
refs/heads/master
2021-01-20T15:36:12.324219
2013-06-20T13:06:49
2013-06-20T13:06:49
11,457,757
0
1
null
null
null
null
UTF-8
C++
false
false
7,340
h
#ifndef CommonUtility_h #define CommonUtility_h #include <TGraphAsymmErrors.h> #include <TLegend.h> #include <TF1.h> #include <TCanvas.h> #include "TError.h" #include "TLatex.h" #include "TGaxis.h" #include "TMath.h" #include "TH1.h" void makeMultiPanelCanvas(TCanvas*& canv, const Int_t columns, const Int_t rows, const Float_t leftOffset=0., const Float_t bottomOffset=0., const Float_t leftMargin=0.2, const Float_t bottomMargin=0.2, const Float_t edge=0.05) { if (canv==0) { Error("makeMultiPanelCanvas","Got null canvas."); return; } canv->Clear(); TPad* pad[columns][rows]; Float_t Xlow[columns]; Float_t Xup[columns]; Float_t Ylow[rows]; Float_t Yup[rows]; Float_t PadWidth = (1.0-leftOffset)/((1.0/(1.0-leftMargin)) + (1.0/(1.0-edge))+(Float_t)columns-2.0); Float_t PadHeight = (1.0-bottomOffset)/((1.0/(1.0-bottomMargin)) + (1.0/(1.0-edge))+(Float_t)rows-2.0); Xlow[0] = leftOffset; Xup[0] = leftOffset + PadWidth/(1.0-leftMargin); Xup[columns-1] = 1; Xlow[columns-1] = 1.0-PadWidth/(1.0-edge); Yup[0] = 1; Ylow[0] = 1.0-PadHeight/(1.0-edge); Ylow[rows-1] = bottomOffset; Yup[rows-1] = bottomOffset + PadHeight/(1.0-bottomMargin); for(Int_t i=1;i<columns-1;i++) { Xlow[i] = Xup[0] + (i-1)*PadWidth; Xup[i] = Xup[0] + (i)*PadWidth; } Int_t ct = 0; for(Int_t i=rows-2;i>0;i--) { Ylow[i] = Yup[rows-1] + ct*PadHeight; Yup[i] = Yup[rows-1] + (ct+1)*PadHeight; ct++; } TString padName; for(Int_t i=0;i<columns;i++) { for(Int_t j=0;j<rows;j++) { canv->cd(); padName = Form("p_%d_%d",i,j); pad[i][j] = new TPad(padName.Data(),padName.Data(), Xlow[i],Ylow[j],Xup[i],Yup[j]); if(i==0) pad[i][j]->SetLeftMargin(leftMargin); else pad[i][j]->SetLeftMargin(0); if(i==(columns-1)) pad[i][j]->SetRightMargin(edge); else pad[i][j]->SetRightMargin(0); if(j==0) pad[i][j]->SetTopMargin(edge); else pad[i][j]->SetTopMargin(0); if(j==(rows-1)) pad[i][j]->SetBottomMargin(bottomMargin); else pad[i][j]->SetBottomMargin(0); pad[i][j]->Draw(); pad[i][j]->cd(); pad[i][j]->SetNumber(columns*j+i+1); } } } void twikiSave(TCanvas* c=0, char* name="",int w=0,int h=0) { if ( w==0) w = c->GetWindowWidth(); if ( h==0) h = c->GetWindowHeight(); c->SaveAs(name); cout << Form(" <br/> <img src=\"%%ATTACHURLPATH%%/%s\" alt=\"%s\" width='%d' height='%d'/>",name,name,w,h)<< endl; } void centralityBinning(float *b=0) { b[0]= 0; b[1]= 5.045; b[2]= 7.145; b[3]= 8.755; b[4]= 10.105; b[5]= 11.294; b[6]= 12.373; b[7]= 13.359; b[8]= 14.283; b[9]= 15.202; b[10] = 100; } void handsomeTH1( TH1 *a=0, int col =1, float size=1, int markerstyle=20) { //a->SetMarkerColor(col); //a->SetMarkerSize(size); //a->SetMarkerStyle(markerstyle); //a->SetLineColor(col); //a->GetYaxis()->SetTitleOffset(1.25); a->GetXaxis()->CenterTitle(); a->GetYaxis()->CenterTitle(); } void handsomeTGraph(TGraphAsymmErrors* a, int col=1) { a->SetLineColor(col); a->SetMarkerColor(col); a->SetMarkerSize(1.0); a->SetMarkerStyle(24); } void scaleInt( TH1 *a=0) { float fac = a->Integral(1,a->GetNbinsX()); if ( fac>0) a->Scale(1./fac); } void handsomeTH1Sumw2( TH1 *a=0, int col =1, float size=1, int markerstyle=20) { handsomeTH1(a,col,size,markerstyle); a->Sumw2(); } void handsomeTH1N( TH1 *a=0, int col =1) { handsomeTH1(a,col); a->Scale(1./a->GetEntries()); } void handsomeTH1OnlyColor( TH1 *a=0, int col =1) { a->SetMarkerColor(col); a->SetLineColor(col); a->GetYaxis()->SetTitleOffset(1.25); } void easyLeg( TLegend *a=0 , char * head="") { a->SetBorderSize(0); a->SetHeader(head); a->SetTextFont(62); a->SetLineColor(1); a->SetLineStyle(1); a->SetLineWidth(1); a->SetFillColor(0); a->SetFillStyle(0); } TH1* cleverRange(TH1* h,float fac=1.2, float minY=1.e-3) { float maxY = fac * h->GetBinContent(h->GetMaximumBin()); cout <<" ranged will be set as " << minY << " ~ " << maxY << endl; h->SetAxisRange(minY,maxY,"Y"); return h; } TF1* cleverGaus(TH1* h, char* title="h", float c = 2.5) { if ( h->GetEntries() == 0 ) { TF1 *fit0 = new TF1(title,"gaus",-1,1); fit0->SetParameters(0,0,0); return fit0; } int peakBin = h->GetMaximumBin(); double peak = h->GetBinCenter(peakBin); double sigma = h->GetRMS(); TF1 *fit1 = new TF1(title,"gaus",peak-c*sigma,peak+c*sigma); h->Fit(fit1,"LL M R Q"); return fit1; } void addCms(TCanvas *c) { c->cd(); TLatex *cms = new TLatex(0.6013,0.89,"CMS Preliminary"); cms->SetTextFont(63); cms->SetTextSize(16); cms->SetNDC(); cms->Draw(); } //--------------------------------------------------- void drawText(const char *text, float xp, float yp, int textSize=18){ TLatex *tex = new TLatex(xp,yp,text); tex->SetTextFont(63); //tex->SetTextSize(20); tex->SetTextSize(textSize); //tex->SetTextSize(0.05); tex->SetTextColor(kBlack); tex->SetLineWidth(1); tex->SetNDC(); tex->Draw(); } //--------------------------------------------------- void drawPatch(float x1, float y1, float x2, float y2){ TLegend *t1=new TLegend(x1,y1,x2,y2); t1->SetFillColor(kWhite); t1->SetBorderSize(0); t1->SetFillStyle(1001); t1->Draw(""); } void fixedFontAxis(TGaxis * ax) { ax->SetLabelFont(43); ax->SetLabelOffset(0.01); ax->SetLabelSize(22); ax->SetTitleFont(43); ax->SetTitleSize(24); ax->SetTitleOffset(2); } void fixedFontHist(TH1D * h, Float_t xoffset=1.2, Float_t yoffset=2.) { h->SetLabelFont(43,"X"); h->SetLabelFont(43,"Y"); //h->SetLabelOffset(0.01); h->SetLabelSize(22); h->SetTitleFont(43); h->SetTitleSize(24); h->SetLabelSize(22,"Y"); h->SetTitleFont(43,"Y"); h->SetTitleSize(24,"Y"); h->SetTitleOffset(xoffset,"X"); h->SetTitleOffset(yoffset,"Y"); h->GetXaxis()->CenterTitle(); h->GetYaxis()->CenterTitle(); } //--------------------------------------------------- void drawTextOver(const char *text, float xp, float yp){ TLatex *tex = new TLatex(xp,yp,text); tex->SetTextFont(63); tex->SetTextSize(22); //tex->SetTextSize(0.05); tex->SetTextColor(kBlack); tex->SetLineWidth(1); tex->SetNDC(); tex->Draw(); } //-------------------------------------------------- void mcStyle1(TH1* h=0) { h->SetLineColor(kRed); h->SetFillColor(kRed-9); h->SetFillStyle(3004); } void mcStyle2(TH1* h=0) { h->SetLineColor(kBlue); h->SetFillColor(kAzure-8); h->SetFillStyle(3005); } //-------------------------------------------------- void AdditionalSysUncert(TH1 * h,Float_t frac) { using namespace TMath; for (Int_t i=1; i<=h->GetNbinsX(); ++i) { Float_t y=h->GetBinContent(i); Float_t ye= h->GetBinError(i); h->SetBinError(i,Sqrt(ye*ye+frac*y*frac*y)); //cout << "Old Error: " << ye << "New Error: " << h->GetBinError(i) << endl; } } #endif
[ "" ]
9416869439a42c39aa62ae4a59f5e24f88aad4e3
50dd655a8c7aa00cc507f2098732257b74eac69e
/arduino/termometro/termometro.ino
6daa19de40a5eeb3233379d308ed9aaa95f19f87
[]
no_license
carlogilmar/Arduino-Learning
1f0e0b4a3c24fbe491d1dcc0204ee55204a43dcf
9c0ebedc1d95da9412a3e3c18d1cc52dd0f64d67
refs/heads/master
2020-03-20T18:52:13.142307
2018-08-31T06:16:36
2018-08-31T06:16:36
137,608,696
0
0
null
null
null
null
UTF-8
C++
false
false
109
ino
#include <dht11.h> void setup() { //lcd.begin(16,2); //16 by 2 character display } void loop() { }
[ "carlogilmar12@gmail.com" ]
carlogilmar12@gmail.com
2155630f3ab232fd919a56ac06e0a37882856aec
58442eee8eb1c04a7d83cea7697993a93bd6b3d5
/client_man.cpp
6e2c45209ca01c60bfe94265bd1ae3c3d462c4bb
[]
no_license
codingsf/Server
1033016beb4e270b4ff87bd6053c66c741b47272
e37656860c16c989d3c5f177940e534de25a40cb
refs/heads/master
2020-12-30T12:22:38.978330
2016-05-25T15:42:14
2016-05-25T15:42:14
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,063
cpp
/* * client_man.cpp * * Created on: 2016Äê5ÔÂ25ÈÕ * Author: LeoBrilliant */ #include "opend.h" #define NALLOC 10 static void client_alloc(void) { int i; if(client == NULL) { client = (Client*)malloc(NALLOC * sizeof(Client)); } else { client = (Client*)realloc(client, (client_size + NALLOC) * sizeof(Client)); } if(client == NULL) { err_sys("can't alloc for client array"); } for(i = client_size; i < client_size + NALLOC; ++i) { client[i].fd = -1; } client_size += NALLOC; } int client_add(int fd, uid_t uid) { int i; if(client == NULL) { client_alloc(); } again: for(i = 0; i < client_size; ++i) { if(client[i].fd == -1) { client[i].fd = fd; client[i].uid = uid; return i; } } client_alloc(); goto again; return -1; } void client_del(int fd) { int i; for(i = 0; i < client_size; ++i) { if(client[i].fd == fd) { client[i].fd = -1; return; } } log_quit("can't find client entry for fd %d", fd); }
[ "LeoBrilliant@gmail.com" ]
LeoBrilliant@gmail.com
a1e0bbcb01f267c514fce52cb813281162cfa4e6
547e9725d44e99f3bbb11bb88712a84126de5a0e
/WindowApi_Portfolio/Astar.cpp
9760c007597d928bf604352c1b84ba6c42ecba82
[]
no_license
endeoddl19/WindowApi_Portfolio
5ecb59ba2d643145d3117155497e893705c67556
f462b59d91a393758ffab1a8760610c518f85624
refs/heads/master
2023-07-12T22:19:55.730658
2021-08-17T08:11:25
2021-08-17T08:11:25
392,666,261
0
0
null
null
null
null
UTF-8
C++
false
false
2,331
cpp
#define _CRT_SECURE_NO_WARNINGS #include "Astar.h" #include <iostream> #include <algorithm> #include <cmath> using namespace std; #define MAX 20481024 int xdir[4] = { 0,1,0,-1 }; int ydir[4] = { 1,0,-1,0 }; ANode* map[8][8]; int getH(int x, int y, int dx, int dy) { int h; int xdis = abs(dx - x); int ydis = abs(dy - y); h = 10 * (xdis + ydis); return h; } void ANode::setMap() { int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { ANode* t = new ANode(i, j); map[i][j] = t; } } HANDLE hFile; TCHAR inBuff[128]; DWORD size = 0; int pt = 0; hFile = CreateFile(_T("maps/test1.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0); memset(inBuff, 0, sizeof(inBuff)); ReadFile(hFile, inBuff, 127 * sizeof(TCHAR), &size, NULL); CloseHandle(hFile); for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) map[i][j]->val = (int)inBuff[pt++]; } } void ANode::AStar(int sx, int sy, int dx, int dy) { int x = sx; int y = sy; int min = MAX; POINT pt = { -1,-1 }; while (pt.x != dx && pt.y != dy) { for (int i = 0; i < 4; i++) { x = sx; y = sy; x += xdir[i]; y += ydir[i]; if (x >= 0 && y >= 0) { map[x][y]->g += 10; map[x][y]->h = getH(x, y, dx, dy); map[x][y]->f = map[x][y]->g + map[x][y]->h; if (map[x][y]->f < min && map[x][y]->val != 0) { min = map[x][y]->f; pt = { x,y }; } } } map[pt.x][pt.y]->open = true; sx = pt.x; sy = pt.y; } } vector<POINT> ANode::getPath() { vector<POINT> path; /*int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { if (map[i][j]->val != 0) path->push_back({ i,j }); } }*/ path.push_back({ 1,0 }); path.push_back({ 2,0 }); path.push_back({ 3,0 }); path.push_back({ 4,0 }); path.push_back({ 5,0 }); path.push_back({ 6,0 }); path.push_back({ 7,1 }); path.push_back({ 6,2 }); path.push_back({ 5,2 }); path.push_back({ 4,3 }); path.push_back({ 3,3 }); path.push_back({ 2,4 }); path.push_back({ 1,5 }); path.push_back({ 1,6 }); path.push_back({ 1,7 }); path.push_back({ 2,6 }); path.push_back({ 3,6 }); path.push_back({ 4,6 }); path.push_back({ 5,5 }); path.push_back({ 6,6 }); path.push_back({ 7,6 }); return path; } void ANode::close() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) delete map[i][j]; } }
[ "endeoddl19@naver.com" ]
endeoddl19@naver.com
dcac7f611f1e5c2c6a0a72a292e789c175483200
aeb04f825fe007bd1b264b9171cf18a5ba14c03e
/open_spiel/examples/example.cc
9f49fcc7fc553e811fe4da1b4c6f0805931baf6e
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
julianhartmann1/HCII
a9b351175e20b2ecbe86b63f5267eaac5a77bedf
8169379b5bf17bdf592213358fadd41e9df4a5e4
refs/heads/master
2023-04-29T12:44:26.693748
2021-05-08T12:16:31
2021-05-08T12:16:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,334
cc
// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <unistd.h> #include <memory> #include <random> #include "open_spiel/abseil-cpp/absl/flags/flag.h" #include "open_spiel/abseil-cpp/absl/flags/parse.h" #include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_utils.h" ABSL_FLAG(std::string, game, "leduc_poker", "The name of the game to play."); ABSL_FLAG(int, players, 0, "How many players in this game, 0 for default."); ABSL_FLAG(bool, show_infostate, false, "Show the information state."); ABSL_FLAG(int, seed, 0, "Seed for the random number generator. 0 for auto."); ABSL_FLAG(bool, show_legals, false, "Show the legal moves."); void PrintLegalActions(const open_spiel::State& state, open_spiel::Player player, const std::vector<open_spiel::Action>& movelist) { std::cerr << "Legal moves for player " << player << ":" << std::endl; for (open_spiel::Action action : movelist) { std::cerr << " " << state.ActionToString(player, action) << std::endl; } } int main(int argc, char** argv) { absl::ParseCommandLine(argc, argv); std::string game_name = absl::GetFlag(FLAGS_game); auto players = absl::GetFlag(FLAGS_players); bool show_infostate = absl::GetFlag(FLAGS_show_infostate); int seed = absl::GetFlag(FLAGS_seed); bool show_legals = absl::GetFlag(FLAGS_show_legals); // Print out registered games. std::cerr << "Registered games:" << std::endl; std::vector<std::string> names = open_spiel::RegisteredGames(); for (const std::string& name : names) { std::cerr << name << std::endl; } // Random number generator. std::mt19937 rng(seed ? seed : time(0)); // Create the game. std::cerr << "Creating game..\n" << std::endl; // Add any specified parameters to override the defaults. open_spiel::GameParameters params; if (players > 0) { params["players"] = open_spiel::GameParameter(players); } std::shared_ptr<const open_spiel::Game> game = open_spiel::LoadGame(game_name, params); if (!game) { std::cerr << "problem with loading game, exiting..." << std::endl; return -1; } std::cerr << "Starting new game..." << std::endl; std::unique_ptr<open_spiel::State> state = game->NewInitialState(); std::cerr << "Initial state:" << std::endl; std::cerr << "State:" << std::endl << state->ToString() << std::endl; while (!state->IsTerminal()) { std::cerr << "player " << state->CurrentPlayer() << std::endl; if (state->IsChanceNode()) { // Chance node; sample one according to underlying distribution. std::vector<std::pair<open_spiel::Action, double>> outcomes = state->ChanceOutcomes(); open_spiel::Action action = open_spiel::SampleAction(outcomes, rng).first; std::cerr << "sampled outcome: " << state->ActionToString(open_spiel::kChancePlayerId, action) << std::endl; state->ApplyAction(action); } else if (state->IsSimultaneousNode()) { // open_spiel::Players choose simultaneously? std::vector<open_spiel::Action> joint_action; std::vector<float> infostate(game->InformationStateTensorSize()); // Sample a action for each player for (auto player = open_spiel::Player{0}; player < game->NumPlayers(); ++player) { if (show_infostate) { if (game->GetType().provides_information_state_tensor) { state->InformationStateTensor(player, absl::MakeSpan(infostate)); std::cerr << "player " << player << ": " << absl::StrJoin(infostate, " ") << std::endl; } if (game->GetType().provides_information_state_string) { std::cerr << "player " << player << ": " << state->InformationStateString(player) << std::endl; } } std::vector<open_spiel::Action> actions = state->LegalActions(player); if (show_legals) { PrintLegalActions(*state, player, actions); } absl::uniform_int_distribution<> dis(0, actions.size() - 1); open_spiel::Action action = actions[dis(rng)]; joint_action.push_back(action); std::cerr << "player " << player << " chose " << state->ActionToString(player, action) << std::endl; } state->ApplyActions(joint_action); } else { // Decision node, sample one uniformly. auto player = state->CurrentPlayer(); if (show_infostate) { if (game->GetType().provides_information_state_tensor) { std::vector<float> infostate; state->InformationStateTensor(player, absl::MakeSpan(infostate)); std::cerr << "player " << player << ": " << absl::StrJoin(infostate, " ") << std::endl; } if (game->GetType().provides_information_state_string) { std::cerr << "player " << player << ": " << state->InformationStateString(player) << std::endl; } } std::vector<open_spiel::Action> actions = state->LegalActions(); if (show_legals) { PrintLegalActions(*state, player, actions); } absl::uniform_int_distribution<> dis(0, actions.size() - 1); auto action = actions[dis(rng)]; std::cerr << "chose action: " << state->ActionToString(player, action) << std::endl; state->ApplyAction(action); } std::cerr << "State: " << std::endl << state->ToString() << std::endl; } auto returns = state->Returns(); for (auto p = open_spiel::Player{0}; p < game->NumPlayers(); p++) { std::cerr << "Final return to player " << p << " is " << returns[p] << std::endl; } }
[ "63606142+julianhartmann1@users.noreply.github.com" ]
63606142+julianhartmann1@users.noreply.github.com
a296a8177a70cdb38a52511216ed9ead4812f78e
6cfe7c65380924bfd6fe46a7b6cd5b006b333e96
/source/geometry/src/GateCompressedVoxelOutput.cc
dd1db5dd8b0d145357eed8ca9c253d1e48cac95c
[]
no_license
copernicus231/gatempi
800eb61dd5de373d591e9cb49630172e1c4809b2
b97c38418458dfd21e8d25887419f7967871782e
refs/heads/master
2020-12-24T12:01:56.966710
2012-08-13T05:12:22
2012-08-13T05:12:22
5,534,931
1
0
null
null
null
null
UTF-8
C++
false
false
9,909
cc
/*---------------------- GATE version name: gate_v6 Copyright (C): OpenGATE Collaboration This software is distributed under the terms of the GNU Lesser General Public Licence (LGPL) See GATE/LICENSE.txt for further details ----------------------*/ #include <exception> #include "GateCompressedVoxelOutput.hh" #include "GateCompressedVoxelOutputMessenger.hh" #include "GateVoxelCompressor.hh" #include "GateTrajectoryNavigator.hh" #include "globals.hh" #include "G4Run.hh" #include "G4Step.hh" #include "G4Event.hh" #include "GateCrystalHit.hh" #include "GatePhantomHit.hh" #include "G4VHitsCollection.hh" #include "G4HCofThisEvent.hh" #include "G4TrajectoryContainer.hh" #include "G4Material.hh" #include "G4VProcess.hh" #include "GateRecorderBase.hh" #include "G4ios.hh" #include "G4UImanager.hh" #include "G4RunManager.hh" #include "GatePrimaryGeneratorAction.hh" #include "G4ParticleDefinition.hh" #include "G4Positron.hh" #include "G4GenericIon.hh" //#include "GateSourceMgr.hh" #include "G4Navigator.hh" #include "G4TransportationManager.hh" #include "GateOutputMgr.hh" #include "GateCompressedVoxel.hh" #include "GateCompressedVoxelParameterized.hh" #include "GateVVolume.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... GateCompressedVoxelOutput::GateCompressedVoxelOutput(const G4String& name,const G4String& phantomName, GateOutputMgr* outputMgr,DigiMode digiMode,GateCompressedVoxelParameterized* inserter) : GateVOutputModule(name,outputMgr,digiMode), m_array(new std::valarray<float>), m_arraySquare(new std::valarray<float>), m_arrayCounts(new std::valarray<unsigned int>), m_inserter(inserter), m_fileName(" "), // All default output file from all output modules are set to " ". // They are then checked in GateApplicationMgr::StartDAQ, using // the VOutputModule pure virtual method GiveNameOfFile() m_uncertainty(false), m_phantomName(phantomName) { m_isEnabled = true; // This module is clearly call by the user, so enable is true when constructing output module m_outputMessenger = new GateCompressedVoxelOutputMessenger(this); m_trajectoryNavigator = new GateTrajectoryNavigator(); SetVerboseLevel(0); // G4cout << "GateCompressedVoxelOutput::GateCompressedVoxelOutput - Constructor entered. Output name " << GetName() << ", phantomName "<< m_phantomName << G4endl << std::flush ; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- GateCompressedVoxelOutput::~GateCompressedVoxelOutput() { delete m_outputMessenger; if (nVerboseLevel > 0) G4cout << "GateCompressedVoxelOutput deleting..." << G4endl; delete m_array; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- const G4String& GateCompressedVoxelOutput::GiveNameOfFile() { return m_fileName; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- void GateCompressedVoxelOutput::RecordBeginOfAcquisition() { // G4cout << "GateCompressedVoxelOutput::RecordBeginOfAcquisition - Entered at " << this << " for "<< GetName() << G4endl << std::flush ; if (nVerboseLevel > 2) G4cout << "GateCompressedVoxelOutput::RecordBeginOfAcquisition - Entered " << G4endl; G4cout<< (*G4Material::GetMaterialTable()) << G4endl; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // write a binary file (4 bytes floats) containing the dose in cGy void GateCompressedVoxelOutput::RecordEndOfAcquisition() { static const double Gy (joule/kilogram); static const double cGy(Gy/100.0); // Get initial dimensions and size of the phantom and calculate original voxel volume GateVGeometryVoxelReader* theReader ( m_inserter->GetReader()); const G4ThreeVector voxelSize ( theReader->GetVoxelSize()); const G4ThreeVector voxelNumber ( theReader->GetVoxelNx(), theReader->GetVoxelNy(), theReader->GetVoxelNz()); const int totalVoxelNumber ( int(voxelNumber.x() * voxelNumber.y() * voxelNumber.z()) ); const double voxelVolume ( voxelSize.x() * voxelSize.y() * voxelSize.z() ); const int dimx ( 1 ); const int dimy ( int(voxelNumber.x()) ); const int dimz ( int(voxelNumber.x() * voxelNumber.y()) ); // Allocate the array to hold dose for every expanded voxel std::valarray<float>* expandedArray(0); try{ expandedArray = new std::valarray<float>; expandedArray->resize( totalVoxelNumber ); } catch(...){ G4Exception("GateCompressedVoxelOutput::RecordEndOfAcquisition - No memory for expanded array."); } // Process each (compressed) voxel: for (unsigned int i=0; i<m_array->size(); i++){ // a) calculate dose const GateCompressedVoxel& gcv ( theReader->GetCompressor().GetVoxel(i)); G4Material* mat ( (*G4Material::GetMaterialTable())[gcv[6]]); double density ( mat->GetDensity()); double volume ( gcv[3] * gcv[4] * gcv[5] * voxelVolume); double mass ( density*volume ); double dose ( (*m_array)[i] / mass ); // b) put dose value in expanded voxels for (int l=gcv[0]; l<gcv[0]+gcv[3]; l++) for (int m=gcv[1]; m<gcv[1]+gcv[4]; m++) for (int n=gcv[2]; n<gcv[2]+gcv[5]; n++) (*expandedArray)[ l*dimz + m*dimy + n*dimx ] = dose/cGy; } // Output the dose array std::ofstream f; f.open(m_fileName, std::ofstream::out | std::ofstream::binary); for (unsigned int i=0; i< expandedArray->size(); i++) f.write( (char*)&(*expandedArray)[i], sizeof(float)); f.close(); delete expandedArray; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- void GateCompressedVoxelOutput::RecordBeginOfRun(const G4Run * ) { if (nVerboseLevel > 2) G4cout << "GateCompressedVoxelOutput::RecordBeginOfRun" << G4endl; } //--------------------------------------------------------------------------- //---------------------------------------------------------------------------- void GateCompressedVoxelOutput::RecordEndOfRun(const G4Run * ) { if (nVerboseLevel > 2) G4cout << "GateCompressedVoxelOutput::RecordEndOfRun" << G4endl; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void GateCompressedVoxelOutput::RecordBeginOfEvent(const G4Event* ) { if (nVerboseLevel > 2) G4cout << "GateCompressedVoxelOutput::RecordBeginOfEvent" << G4endl; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void GateCompressedVoxelOutput::RecordEndOfEvent(const G4Event* ) { GateVGeometryVoxelReader* theReader( m_inserter->GetReader()); if(!theReader) G4Exception("GateCompressedVoxelOutput::RecordEndOfEvent - No reader."); // Set the array size if necessary if(m_array->size() == 0) { int voxelNumber = theReader->GetCompressor().GetNbOfCopies(); m_array->resize(voxelNumber); if (m_uncertainty){ m_arraySquare->resize(voxelNumber); m_arrayCounts->resize(voxelNumber); } } if (nVerboseLevel > 2) G4cout << "GateCompressedVoxelOutput::RecordEndOfEvent - Entered for phantom "<< m_phantomName << G4endl; GatePhantomHitsCollection* PHC = GetOutputMgr()->GetPhantomHitCollection(); G4int NpHits = PHC->entries(); for (G4int i=0;i<NpHits;i++){ GatePhantomHit* h ( (*PHC)[i] ); G4double edep ( h->GetEdep() ); G4int n ( h->GetVoxelCoordinates() ); G4String physVolName ( h->GetPhysVolName() ); if( 0 == physVolName.compare(0, m_phantomName.size(), m_phantomName) ){ // G4cout << "GateCompressedVoxelOutput::RecordEndOfEvent - HIT at voxel "<< n << " in "<< physVolName << G4endl; (*m_array)[n]+=edep; if (m_uncertainty){ (*m_arrayCounts) [n]++; (*m_arraySquare) [n]+= edep*edep; } if (nVerboseLevel > 2) G4cout << "hit= " << i << ", n= " << n << ", edep " << edep << ", process " << h->GetProcess() << ", array[n] " << (*m_array)[n] << ", square[n] " << (*m_arraySquare)[n] << ", counts[n] " << (*m_arrayCounts)[n] << G4endl; }// end if phantom }//end for loop } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void GateCompressedVoxelOutput::RecordStepWithVolume(const GateVVolume *, const G4Step* ) { if (nVerboseLevel > 2) G4cout << "GateCompressedVoxelOutput::RecordStep" << G4endl; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void GateCompressedVoxelOutput::SetVerboseLevel(G4int val) { nVerboseLevel = val; if (m_trajectoryNavigator) m_trajectoryNavigator->SetVerboseLevel(val); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void GateCompressedVoxelOutput::SetSaveUncertainty(G4bool b) { m_uncertainty=b; } //---------------------------------------------------------------------------
[ "copernicus231@gmail.com" ]
copernicus231@gmail.com
24df3f7d1a41079a90a0b17961cdced2c2b951e1
44a17902fe132720dc71ee0b02dae6a388f36df4
/2021/Final/I.cpp
dd472b19aa48c16421e9a6e1e68cc38eb683f6be
[]
no_license
wupsi/PP1_2021_Spring
3ac83b090dc19ae35d28a73659624fb16f1566ef
914acb647fec29a78bd8bc6ac91cff6c861396ae
refs/heads/main
2023-07-28T21:25:35.297747
2021-09-14T01:17:25
2021-09-14T01:17:25
406,180,042
3
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
#include <iostream> using namespace std; int main(){ int n; cin >> n; string sur, last; int q1, q2, q3, q4, sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0; string arr[n + 1]; int arrsum[100100], quiz1[n + 1], quiz2[n + 1], quiz3[n + 1], quiz4[n + 1]; for(int i = 0; i < n; i++){ cin >> sur >> last >> q1 >> q2 >> q3 >> q4; arrsum[i] = q1 + q2 + q3 + q4; if(arrsum[i] > 20) arr[i] = last; quiz1[i] = q1; quiz2[i] = q2; quiz3[i] = q3; quiz4[i] = q4; sum1 += quiz1[i]; sum2 += quiz2[i]; sum3 += quiz3[i]; sum4 += quiz4[i]; } for(int i = 0; i < n; i++){ if(sum1 == 0) arrsum[i]++; if(sum2 == 0) arrsum[i]++; if(sum3 == 0) arrsum[i]++; if(sum4 == 0) arrsum[i]++; } for(int i = 1; i < n; i++){ for(int k = 0; k < n - i; k++){ if(arrsum[k] < arrsum[k + 1]){ int temp = arrsum[k]; string temp1 = arr[k]; arrsum[k] = arrsum[k + 1]; arr[k] = arr[k + 1]; arrsum[k + 1] = temp; arr[k + 1] = temp1; } } } for(int i = 0; i <= n; i++){ cout << arr[i] << " " << arrsum[i] << endl; } }
[ "codehook25@gmail.com" ]
codehook25@gmail.com
f33916cea9373808b5f93a95aaa0656387e06a8c
cfe47409faf4904128a0e8819dbbff4aa262ee71
/Timer/Timer.h
4ab0d1ba6da485ce1f76c7cdc118f47be9397c08
[]
no_license
zoozoozu/GraduateProject
ff76058d00a02f6527ce09616cbecf2ffad8277d
47f5a07d71563ccd4e342d33a19e87677d6f4d41
refs/heads/master
2021-05-12T19:45:51.369213
2018-07-22T08:05:14
2018-07-22T08:05:14
117,102,381
0
0
null
null
null
null
UTF-8
C++
false
false
578
h
#pragma once const ULONG MAX_SAMPLE_COUNT = 50; class CTimer { private: bool m_bHardwareHasPerformanceCounter; float m_fTimeScale; float m_fTimeElapsed; __int64 m_nCurrentTime; __int64 m_nLastTime; __int64 m_PerformanceFrequency; float m_fFrameTime[MAX_SAMPLE_COUNT]; ULONG m_nSampleCount; unsigned long m_nCurrentFrameRate; unsigned long m_FramePerSecond; float m_fFPSTimeElapsed; public: CTimer(); virtual ~CTimer(); void Tick(float fLockFPS = 0.0f); unsigned long GetFrameRate(LPTSTR lpszString = NULL, int nCharacters = 0); float GetTimeElapsed(); };
[ "12hjpoint@gmail.com" ]
12hjpoint@gmail.com
e69c5c85a2a3f94aa77c61f587ab3add3efa0be8
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigHypothesis/TrigAFPHypo/src/TrigAFPJetAllTE.cxx
192c74bee41764b9d777943abd03b19fffb111dc
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
12,577
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "TrigAFPHypo/TrigAFPJetAllTE.h" #include "xAODJet/JetContainer.h" #include "xAODJet/Jet.h" #include "xAODForward/AFPTrackContainer.h" #include "xAODForward/AFPTrack.h" #include "PathResolver/PathResolver.h" #include "xAODTrigger/TrigPassBits.h" #include <math.h> TrigAFPJetAllTE::TrigAFPJetAllTE(const std::string& name, ISvcLocator* pSvcLocator) : HLT::AllTEAlgo(name, pSvcLocator), m_decision(false), m_useCachedResult(false), m_transportBeam1(nullptr), m_transportBeam2(nullptr) { //Radius and rectangular thresholds declareProperty("maxProtonDist", m_maxProtonDist = 2.0, "Cut on distance between measured and extrapolated proton"); declareProperty("maxProtonDiff_x", m_maxProtonDiff_x = 2.5, "Cut on x difference between measured and extrapolated proton"); declareProperty("maxProtonDiff_y", m_maxProtonDiff_y = 2.0, "Cut on y difference between measured and extrapolated proton"); declareProperty("beamEnergy", m_beamEnergy = 6500.0, "Energy of one beam i.e. half of centre-of-mass energy"); declareProperty("protonTransportParamFileName1", m_protonTransportParamFileName1 = "final_parameterization_b1.txt", "Name of the file with proton transport parametrisation"); declareProperty("protonTransportParamFileName2", m_protonTransportParamFileName2 = "final_parameterization_b2.txt", "Name of the file with proton transport parametrisation"); declareProperty("protonPosShift_x", m_protonPosShift_x = -97.0, "Expected difference in x position between measured and predicted proton."); declareProperty("protonPosShift_y", m_protonPosShift_y = 5.0, "Expected difference in y position between measured and predicted proton."); declareProperty("alignmentCorrection_nearA", m_alignmentCorrection_nearA = 0, "Shift due to alignment in x for protons in near station A ."); declareProperty("alignmentCorrection_nearC", m_alignmentCorrection_nearC = 0, "Shift due to alignment in x for protons in near station C ."); declareProperty("requireDoubleTag", m_requireDoubleTag = true, "Determine if a single or double tag is required in the hypo decision"); declareMonitoredVariable("NJets", m_jetsN); declareMonitoredVariable("Etajj", m_dijetEta); declareMonitoredVariable("Yjj", m_dijetRapidity); declareMonitoredVariable("Mjj", m_dijetMass); declareMonitoredVariable("Diff_pos_A", m_sideA_minDist); declareMonitoredVariable("Diff_pos_C", m_sideC_minDist); declareMonitoredVariable("N_trk_C", m_sideC_tracksN); declareMonitoredVariable("N_trk_A", m_sideA_tracksN); declareMonitoredVariable("Diff_x_A", m_sideA_diffX); declareMonitoredVariable("Diff_x_C", m_sideC_diffX); declareMonitoredVariable("Diff_y_A", m_sideA_diffY); declareMonitoredVariable("Diff_y_C", m_sideC_diffY); declareMonitoredVariable("x_A", m_sideA_trkX); declareMonitoredVariable("x_C", m_sideC_trkX); declareMonitoredVariable("y_A", m_sideA_trkY); declareMonitoredVariable("y_C", m_sideC_trkY); declareMonitoredVariable("param_x_A", m_sideA_predictX); declareMonitoredVariable("param_x_C", m_sideC_predictX); declareMonitoredVariable("param_y_A", m_sideA_predictY); declareMonitoredVariable("param_y_C", m_sideC_predictY); } HLT::ErrorCode TrigAFPJetAllTE::hltInitialize() { ATH_MSG_DEBUG("Initialization. The correct configuration of this algorithm " << "requires jets ordered in increasing energy"); //Retrieving the parameterization file std::string filePath1 = PathResolver::find_file( m_protonTransportParamFileName1.c_str(), "DATAPATH", PathResolver::RecursiveSearch); if (filePath1.length() == 0) { ATH_MSG_WARNING( "The parameterization file " << m_protonTransportParamFileName1.c_str() << " was not found in optics. Using default file."); filePath1 = PathResolver::find_file("final_parameterization_b1.txt", "DATAPATH", PathResolver::RecursiveSearch); m_protonTransportParamFileName1 = "final_parameterization_b1.txt"; } else ATH_MSG_DEBUG("The parameterization file " << m_protonTransportParamFileName1.c_str() << " was found"); //Defining the parameterization object m_transportBeam1 = new AFPProtonTransportTool(filePath1); //Retrieving the parameterization file std::string filePath2 = PathResolver::find_file( m_protonTransportParamFileName2.c_str(), "DATAPATH", PathResolver::RecursiveSearch); if (filePath1.length() == 0) { ATH_MSG_WARNING( "The parameterization file " << m_protonTransportParamFileName2.c_str() << " was not found in optics. Using default file."); filePath2 = PathResolver::find_file("final_parameterization_b2.txt", "DATAPATH", PathResolver::RecursiveSearch); m_protonTransportParamFileName2 = "final_parameterization_b2.txt"; } else ATH_MSG_DEBUG("The parameterization file " << m_protonTransportParamFileName2.c_str() << " was found"); //Defining the parameterization object m_transportBeam2 = new AFPProtonTransportTool(filePath2); ATH_MSG_INFO("Cut on distance between measured and extrapolated proton: " << m_maxProtonDist); ATH_MSG_INFO("Cut on x difference between measured and extrapolated proton: " << m_maxProtonDiff_x); ATH_MSG_INFO("Cut on y difference between measured and extrapolated proton: " << m_maxProtonDiff_y); ATH_MSG_INFO("Name of the file with proton transport parametrisation beam 1: " << m_protonTransportParamFileName1); ATH_MSG_INFO("Name of the file with proton transport parametrisation beam 2: " << m_protonTransportParamFileName2); // total energy is twice the beam energy m_totalEnergy = 2 * m_beamEnergy; return HLT::OK; } struct DescendingEt: std::binary_function<const xAOD::Jet*, const xAOD::Jet*, bool> { bool operator () (const xAOD::Jet* l, const xAOD::Jet* r) const { return l->p4().Et() > r->p4().Et(); } }; TrigAFPJetAllTE::~TrigAFPJetAllTE() { } HLT::ErrorCode TrigAFPJetAllTE::hltExecute(std::vector<std::vector<HLT::TriggerElement*> >& tes_in, unsigned int output) { ATH_MSG_DEBUG("*** Executing this TrigJetHypo : " << name()); // do calculations only if result is not cached if (!m_useCachedResult) { beforeExecMonitors().ignore(); // Retrieving jets from tes_in[0] const xAOD::JetContainer* outJets(nullptr); HLT::ErrorCode statJets = getFeature(tes_in[0].front(), outJets); if (statJets != HLT::OK) { ATH_MSG_WARNING("Failed to get JetCollections"); return HLT::OK; } if (outJets == nullptr) { ATH_MSG_DEBUG("Got no JetCollections associated to the TE!"); return HLT::MISSING_FEATURE; } std::vector<const xAOD::Jet*> theJets(outJets->begin(), outJets->end()); if (theJets.size() == 0) { ATH_MSG_DEBUG("Size of JetCollection is 0!"); return HLT::OK; } //Resetting selection variables bool passRCutA = false; bool passRCutC = false; bool passXYCutA = false; bool passXYCutC = false; //Resetting dijet system variables m_dijetMass = -999; m_dijetEta = -999; m_dijetRapidity = -999; m_jetsN = theJets.size(); if (theJets.size() >= 2) { //Sorting jets by energy std::sort(theJets.begin(), theJets.end(), DescendingEt()); const TLorentzVector jet1(theJets[0]->p4()); const TLorentzVector jet2(theJets[1]->p4()); const TLorentzVector dijet = jet1 + jet2; //To calculate relative energy loss m_dijetMass = dijet.M() * m_GeV; m_dijetEta = dijet.Eta(); m_dijetRapidity = dijet.Rapidity(); const double xiJet1 = exp(m_dijetRapidity) * m_dijetMass / (m_totalEnergy); //As in // https://arxiv.org/abs/1503.00699 const double xiJet2 = exp(-m_dijetRapidity) * m_dijetMass / (m_totalEnergy); //A side proton energy prediction const double predictProton1_e = m_beamEnergy * (1. - xiJet1); //C side proton energy prediction const double predictProton2_e = m_beamEnergy * (1. - xiJet2); m_sideA_predictX = 1e3 * m_transportBeam2->x(0, 0, 0, 0, 0, predictProton1_e) + m_protonPosShift_x; m_sideA_predictY = 1e3 * m_transportBeam2->y(0, 0, 0, 0, 0, predictProton1_e) + m_protonPosShift_y; m_sideC_predictX = 1e3 * m_transportBeam1->x(0, 0, 0, 0, 0, predictProton2_e) + m_protonPosShift_x; m_sideC_predictY = 1e3 * m_transportBeam1->y(0, 0, 0, 0, 0, predictProton2_e) + m_protonPosShift_y; ATH_MSG_DEBUG("x1: " << m_sideA_predictX); ATH_MSG_DEBUG("y1: " << m_sideA_predictY); ATH_MSG_DEBUG("x2: " << m_sideC_predictX); ATH_MSG_DEBUG("y2: " << m_sideC_predictY); ATH_MSG_DEBUG("Mjj: " << m_dijetMass << " Etajj: " << m_dijetEta << " Yjj: " << m_dijetRapidity); xAOD::AFPTrackContainer* tracks = nullptr; if (evtStore()->retrieve(tracks, "AFPTrackContainer").isFailure()) { ATH_MSG_WARNING("Could not retrieve AFP Tracks"); return HLT::OK; } ATH_MSG_DEBUG("Tracks size: " << tracks->size()); //Resetting counters and variables m_sideA_minDist = 999.; m_sideC_minDist = 999.; m_sideA_tracksN = 0; m_sideC_tracksN = 0; const xAOD::AFPTrack* nearestTrkSideA = nullptr; const xAOD::AFPTrack* nearestTrkSideC = nullptr; // find nearest tracks for (const xAOD::AFPTrack* theTrack : *tracks) { //Tracks from A side near station if (theTrack->stationID() == 1) { m_sideA_tracksN++; const double xDiff = m_sideA_predictX - (theTrack->xLocal() + m_alignmentCorrection_nearA); const double yDiff = m_sideA_predictY - theTrack->yLocal(); const double distance = sqrt(xDiff * xDiff + yDiff * yDiff); //To get the closest track from prediction if (distance < m_sideA_minDist) { m_sideA_minDist = distance; nearestTrkSideA = theTrack; } } //Tracks from C side near station else if (theTrack->stationID() == 2) { m_sideC_tracksN++; const double xDiff = m_sideC_predictX - (theTrack->xLocal() + m_alignmentCorrection_nearC); const double yDiff = m_sideC_predictY - theTrack->yLocal(); const double distance = sqrt(xDiff * xDiff + yDiff * yDiff); if (distance < m_sideC_minDist) { m_sideC_minDist = distance; nearestTrkSideC = theTrack; } } } // close loop over afp tracks // check cuts on A side if (nearestTrkSideA) { m_sideA_trkX = nearestTrkSideA->xLocal() + m_alignmentCorrection_nearA; m_sideA_trkY = nearestTrkSideA->yLocal(); m_sideA_diffX = m_sideA_predictX - m_sideA_trkX; m_sideA_diffY = m_sideA_predictY - m_sideA_trkY; //Cutting on distance relative to the mean if (m_sideA_minDist < m_maxProtonDist) passRCutA = true; //Cutting on x and y relative to the mean if (fabs(m_sideA_diffX) < m_maxProtonDiff_x && fabs(m_sideA_diffY) < m_maxProtonDiff_y) passXYCutA = true; } else { m_sideA_trkX = 999; m_sideA_trkY = 999; m_sideA_diffX = 999; m_sideA_diffY = 999; } // check cuts on C side if (nearestTrkSideC) { m_sideC_trkX = nearestTrkSideC->xLocal() + m_alignmentCorrection_nearC; m_sideC_trkY = nearestTrkSideC->yLocal(); m_sideC_diffX = m_sideC_predictX - m_sideC_trkX; m_sideC_diffY = m_sideC_predictY - m_sideC_trkY; //Cutting on distance relative to the mean if (m_sideC_minDist < m_maxProtonDist) passRCutC = true; //Cutting on x and y relative to the mean if (fabs(m_sideC_diffX) < m_maxProtonDiff_x && fabs(m_sideC_diffY) < m_maxProtonDiff_y) passXYCutC = true; } else { m_sideC_trkX = 999; m_sideC_trkY = 999; m_sideC_diffX = 999; m_sideC_diffY = 999; } // make decision const bool passSideA = passRCutA && passXYCutA; const bool passSideC = passRCutC && passXYCutC; if (m_requireDoubleTag) m_decision = passSideA && passSideC; else m_decision = passSideA || passSideC; if(m_decision) ATH_MSG_DEBUG("AFPJetAllTE: Event passed! SUCCESS!"); afterExecMonitors().ignore(); ATH_MSG_DEBUG("Before the end of TrigAFPJetAllTE::Execute"); } // close if (theJets.size() >= 2) m_useCachedResult = true; } // close if (!m_useCachedResult) // save decision HLT::TEVec allTEs; HLT::TriggerElement* outputTE = config()->getNavigation()->addNode(allTEs, output); outputTE->setActiveState(m_decision); return HLT::OK; } HLT::ErrorCode TrigAFPJetAllTE::hltEndEvent() { m_useCachedResult = false; m_decision = false; return HLT::OK; } HLT::ErrorCode TrigAFPJetAllTE::hltFinalize() { if (m_transportBeam1) { delete m_transportBeam1; m_transportBeam1 = nullptr; } if (m_transportBeam2) { delete m_transportBeam2; m_transportBeam2 = nullptr; } return HLT::OK; }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
400f3ebc5fbb2a0dce5041f063c8f3bc245d475e
6bcfa632ace300ea2fbd8734017dda9c8deb5b81
/Erros.h
cab063af62fb38993c8d1fdf612804f5db0014c5
[]
no_license
manecas/CastleWar-1617-POO
8657a5b45c0bfdfc55ea619df2a5693f927dfd43
9ba9f253928264eee7c6add5a1c560ad4ac4bd9b
refs/heads/master
2021-01-19T19:37:09.800788
2017-01-27T10:20:47
2017-01-27T10:20:47
75,129,348
0
0
null
null
null
null
UTF-8
C++
false
false
1,562
h
#ifndef _ERROS #define _ERROS namespace Erros { const int NUM_SERES_INVALIDO = 0; const int FORA_LIMITES_CASTELO = 1; const int SEM_MOEDAS = 2; const int SEM_CASTELO = 3; const int FABRICO_SERES_OK = 4; const int NUM_MOEDAS_INVALIDO = 5; const int MOEDAS_OK = 6; const int LIMITE_PLANICIE_INVALIDO = 7; const int EDIFICIO_INVALIDO = 8; const int EDIFICIO_OK = 9; const int POSICAO_OCUPADA = 10; const int LIMITE_COLONIA_INVALIDO = 11; const int NAO_PODE_REPARAR = 12; const int VENDESTE_OK = 13; const int JOGO_GUARDADO_OK = 14; const int NOME_INVALIDO = 15; const int JOGO_REMOVIDO = 16; const int JOGO_CARREGADO = 17; const int MODO_RECOLHE_OK = 18; const int MODO_RECOLHE_INVALIDO = 19; const int MODO_ATAQUE_OK = 20; const int MODO_ATAQUE_INVALIDO = 21; const int DIM_DEFINIDO = 22; const int DIM_POR_DEFINIR = 23; const int NUM_OPONENTES_INVALIDO = 24; const int OPONENTES_OK = 25; const int MUDASTE_CASTELO = 26; const int MAX_PERFIS_ATINGIGO = 27; const int PERFIL_JA_EXISTE = 28; const int PERFIL_OK = 29; const int SEM_FORCA = 30; const int ADD_CARACTERISTICA_OK = 31; const int PERFIL_NAO_EXISTE = 32; const int REMOVE_CARACTERISTICA_OK = 33; const int CARACTERISTICA_NAO_EXISTE = 34; const int REMOVE_PERFIL_OK = 35; const int FOCO_OK = 36; const int VENDER_CASTELO_INVALIDO = 37; const int PERDESTE = 38; const int GANHASTE = 39; const int LETRA_PERFIL_INVALIDA = 40; const int NAO_DEFINIU_OPONENTES = 41; const int NAO_DEFINIU_PERFIL = 42; const int COMANDO_NAO_RECONHECIDO = 101; } #endif // !_ERROS
[ "djluis-69@hotmail.com" ]
djluis-69@hotmail.com
1969cb878d46c7664ef093377ce61a2846e0aaf0
02d063758c8e7a5ad0843b32146f2c92c9defaac
/include/ibeosdk/database/datamodel/BsonT.cpp
653ee3c39b8727611ccd4e40ca068c2ba911468d
[ "MIT" ]
permissive
chouer19/enjoyDriving
f0a9a20fe576c39bb210e7e597adf610bb719696
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
refs/heads/master
2021-10-24T20:26:11.429966
2019-03-28T14:05:33
2019-03-28T14:05:33
166,670,001
1
0
null
null
null
null
UTF-8
C++
false
false
1,601
cpp
//====================================================================== /*! \file BsonT.cpp * * \copydoc Copyright * \author Kristian Bischoff (kb) * \date Feb 8, 2016 *///------------------------------------------------------------------- //====================================================================== #include <ibeosdk/database/datamodel/BsonT.hpp> //====================================================================== namespace ibeosdk { namespace dbaccess { //====================================================================== const std::string BsonBase::bsonFtId = "ID"; const std::string BsonBase::bsonFtMongoId = "_id"; const std::string BsonBase::bsonFtObjId = "ObjectID"; const std::string BsonBase::bsonFtType = "Type"; const std::string BsonBase::bsonFtTimestamp = "Timestamp"; const std::string BsonBase::bsonFtBinaryData = "BinaryData"; const std::string BsonBase::bsonFtFile = "File"; const std::string BsonBase::bsonFtVersion = "Version"; const std::string BsonBase::bsonFtClass = "Class"; const std::string BsonBase::bsonFtX = "X"; const std::string BsonBase::bsonFtY = "Y"; const std::string BsonBase::bsonFtZ = "Z"; const std::string BsonBase::bsonFtLat = "Latitude"; const std::string BsonBase::bsonFtLon = "Longitude"; const std::string BsonBase::bsonFtAlt = "Altitude"; //====================================================================== } // namespace dbaccess } // namespace ibeosdk //======================================================================
[ "xuec16@mails.tsinghua.edu.cn" ]
xuec16@mails.tsinghua.edu.cn
2f7eaa917587292b28b2431ca8d824455eb126ae
3af71bf6368e46d2652cfb947cd5f32f1e291a12
/17 queue circular/src/17 queue circular.cpp
e6bd8c6ed32bed064db1b074e142819f30b78843
[]
no_license
JD-93/AlgoDS
56222b2911d6c0ca805379479b0c883450d3b8d5
b24f42bd2e43830688d29b157d3d9acc7124300f
refs/heads/master
2021-03-14T18:39:16.496320
2020-03-20T12:56:58
2020-03-20T12:56:58
246,785,160
0
0
null
2020-03-17T19:09:10
2020-03-12T08:47:11
C++
UTF-8
C++
false
false
3,818
cpp
// QUEUE #include <iostream> using namespace std; #include <iomanip> //================================================== typedef int ELEMENT ; // typedef int to ELEMENT // b/c in future we can modify int to structure of any user defined data type // LOOK to the future ironman :) const int size = 5 ; typedef struct { // THIS IS ACTUAL DABBA people call it QUEUE ELEMENT ele[size] ; int front ; // QUEUE contains ELEMENT type aray of 5 capacity int rear ; // one front and rear index counter }QUEUE; //================================================ typedef enum {EXIT,JOINELEMENT,LEAVEELEMENT,TRAVERSE}MENUOPERATIONS ; int menulist ( ) { cout<<"\n\n0. EXIT "<<endl ; cout<<"1. JOINELEMENT "<<endl ; cout<<"2. LEAVEELEMENT "<<endl ; cout<<"3. TRAVERSE "<<endl ; cout<<"choice is : " ; MENUOPERATIONS choice ; scanf("%d",&choice ) ; return choice ; } //================================================= void init_queue(QUEUE &q) ; void join_element(QUEUE &q, ELEMENT &item ) ; void leave_element(QUEUE &q) ; void peek_element(QUEUE &q) ; bool is_empti(QUEUE &q) ; bool is_full(QUEUE &q) ; void accept_ELEMENT(ELEMENT &item) ; void display(QUEUE &q) ; //================================================= int main() { QUEUE q ; init_queue(q) ; display(q) ; int choice ; while ((choice = menulist()) != 0 ) { switch (choice) { case EXIT: break; case JOINELEMENT : if (is_full(q) ) { cout<<"\nQUEUE is already full"<<endl ; } else { ELEMENT item ; accept_ELEMENT(item) ; join_element(q,item) ; display(q) ; } break ; case LEAVEELEMENT : if (is_empti(q)) { cout<<"\nQUEUE is already empty"<<endl ; } else { peek_element(q) ; leave_element(q) ; display(q) ; } break ; case TRAVERSE : display(q) ; break ; default: cout<<"Enter valid choice " <<endl ; break; } } cout<<"\n\n\nTHANKS FOR USING PROGRAM"<<endl ; cout<<"========================="<<endl ; return 0; } //================================================================ // here are queue functions void leave_element(QUEUE &q) { q.ele[q.front] = 0 ; /* for (int i=q.front ; i<q.rear ; i++) { q.ele[i] = q.ele[i+1] ; q.ele[i+1] = 0 ; } q.rear-- ; */ q.front++ ; } //-------------------------------------------------------------------- void peek_element(QUEUE &q) { cout<<"\PEEK ed value is : "<<q.ele[q.front] << endl ; // display ELEMENT cout<<endl ; } //----------------------------------------------------------------- bool is_empti(QUEUE &q) { if ( (q.front == q.rear)&&(q.front ==0) ) return true ; else return false ; } //----------------------------------------------------------------- bool is_full(QUEUE &q) { if (q.rear-size == q.front ) return true ; if ((q.rear == q.front )&& (q.front != 0)) return true ; else return false ; } //---------------------------------------------------------------- void join_element(QUEUE &q, ELEMENT &item) { if (q.rear == size ) q.rear = 0 ; q.ele[q.rear] = item ; q.rear++ ; } //----------------------------------------------------------------- void accept_ELEMENT(ELEMENT &item ) { cout<<"Enter ELEMENT : "<<endl ; cout<<"Enter integer : "; cin>>item ; } //------------------------------------------------------------------- void display(QUEUE &q) { cout<<"\nQUEUE is :"<<endl ; for (int i=0 ; i<size ; i++) cout<<setw(4)<<q.ele[i] ; cout<<"\nrear : "<<q.rear <<endl ; cout<<"front : "<<q.front <<endl ; } //------------------------------------------------------------------ void init_queue(QUEUE &q) { q.rear = 0 ; q.front = 0 ; for (int i=0 ; i<size ; i++) q.ele[i] = 0 ; } //------------------------------------------------------------------
[ "kachare.jaydeep@gmail.com" ]
kachare.jaydeep@gmail.com
16d2243414f2586b34eedad67d6b5cef98747a74
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/winmgmt/esscomp/correlation/updprov/updcmd.cpp
b1cbe8558478b1dd62b15e5081ff34b72bbf3f94
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,746
cpp
#include "precomp.h" #include <wbemutil.h> #include <wbemcli.h> #include <arrtempl.h> #include "updcmd.h" #include "updnspc.h" #include "updsink.h" const LPCWSTR g_wszDataAlias = L"__THISDATA"; const LPCWSTR g_wszEventAlias = L"__THISEVENT"; const LPCWSTR g_wszUpdateEventClass = L"MSFT_UCEventBase"; const LPCWSTR g_wszDynamic = L"Dynamic"; const LPCWSTR g_wszProvider = L"Provider"; const LPCWSTR g_wszServer = L"__Server"; const LPCWSTR g_wszNamespace = L"__Namespace"; const LPCWSTR g_wszTransientProvider = L"Microsoft WMI Transient Provider"; // {405595AA-1E14-11d3-B33D-00105A1F4AAF} static const GUID CLSID_TransientProvider = { 0x405595aa, 0x1e14, 0x11d3, {0xb3, 0x3d, 0x0, 0x10, 0x5a, 0x1f, 0x4a, 0xaf}}; class CWbemProviderInitSink : public IWbemProviderInitSink { STDMETHOD_(ULONG, AddRef)() { return 1; } STDMETHOD_(ULONG, Release)() { return 1; } STDMETHOD(QueryInterface)( REFIID, void** ) { return NULL; } STDMETHOD(SetStatus) ( long lStatus, long lFlags ) { return lFlags; } }; inline void RemoveAliasKeyword( CPropertyName& rAlias ) { CPropertyName NewProp; long cElements = rAlias.GetNumElements(); for( long i=1; i < cElements; i++ ) { NewProp.AddElement( rAlias.GetStringAt(i) ); } rAlias = NewProp; } // this should be a global function of qllex.cpp or something. int FlipOperator(int nOp) { switch(nOp) { case QL1_OPERATOR_GREATER: return QL1_OPERATOR_LESS; case QL1_OPERATOR_LESS: return QL1_OPERATOR_GREATER; case QL1_OPERATOR_LESSOREQUALS: return QL1_OPERATOR_GREATEROREQUALS; case QL1_OPERATOR_GREATEROREQUALS: return QL1_OPERATOR_LESSOREQUALS; case QL1_OPERATOR_ISA: return QL1_OPERATOR_INV_ISA; case QL1_OPERATOR_ISNOTA: return QL1_OPERATOR_INV_ISNOTA; case QL1_OPERATOR_INV_ISA: return QL1_OPERATOR_ISA; case QL1_OPERATOR_INV_ISNOTA: return QL1_OPERATOR_ISNOTA; default: return nOp; } } inline HRESULT SetPropHandle( CPropertyName& rPropName, IWmiObjectAccessFactory* pAccessFact ) { HRESULT hr; LPVOID pvHandle; LPWSTR wszPropName = rPropName.GetText(); if ( wszPropName == NULL ) { return WBEM_E_OUT_OF_MEMORY; } hr = pAccessFact->GetPropHandle( wszPropName, 0, &pvHandle ); delete wszPropName; if ( FAILED(hr) ) { return hr; } rPropName.SetHandle( pvHandle ); return WBEM_S_NO_ERROR; } HRESULT IsClassTransient( IWbemClassObject* pClassObj ) { // // We can tell for sure a class is transient if it is backed by // the transient provider. // HRESULT hr; CWbemPtr<IWbemQualifierSet> pQualSet; hr = pClassObj->GetQualifierSet( &pQualSet ); if ( FAILED(hr) ) { return hr; } hr = pQualSet->Get( g_wszDynamic, 0, NULL, NULL ); if ( hr == WBEM_E_NOT_FOUND ) { return WBEM_S_FALSE; } else if ( FAILED(hr) ) { return hr; } VARIANT varProvider; VariantInit( &varProvider ); CClearMe cmvarProvider( &varProvider ); hr = pQualSet->Get( g_wszProvider, 0, &varProvider, NULL ); if ( hr == WBEM_E_NOT_FOUND || V_VT(&varProvider) != VT_BSTR ) { return WBEM_E_INVALID_OBJECT; } else if ( FAILED(hr) ) { return hr; } if ( _wcsicmp( V_BSTR(&varProvider), g_wszTransientProvider ) != 0 ) { return WBEM_S_FALSE; } return WBEM_S_NO_ERROR; } // // if S_FALSE is returned, then ppDirectSvc will be NULL. // HRESULT GetDirectSvc( IWbemClassObject* pClassObj, IWbemServices* pUpdSvc, IWbemServices** ppDirectSvc ) { HRESULT hr; *ppDirectSvc = NULL; // // if the svc pointer is remote, then we cannot perform the optimization. // this is because queries for the state will be issued to the svc ptr // and will return nothing, because the state will only live in this // process. In short, the transient state must ALWAYS exist in the // winmgmt process. // CWbemPtr<IClientSecurity> pClientSec; hr = pUpdSvc->QueryInterface( IID_IClientSecurity, (void**)&pClientSec ); if ( SUCCEEDED(hr) ) { return WBEM_S_FALSE; } // // we can perform the optimization. Get the namespace str and // instantiate the transient provider. // VARIANT varNamespace; hr = pClassObj->Get( g_wszNamespace, 0, &varNamespace, NULL, NULL ); if ( FAILED(hr) ) { return hr; } _DBG_ASSERT( V_VT(&varNamespace) == VT_BSTR ); CClearMe cmvarNamespace( &varNamespace ); CWbemPtr<IWbemProviderInit> pDirectInit; hr = CoCreateInstance( CLSID_TransientProvider, NULL, CLSCTX_INPROC_SERVER, IID_IWbemProviderInit, (void**)&pDirectInit ); if ( FAILED(hr) ) { return hr; } CWbemProviderInitSink InitSink; hr = pDirectInit->Initialize( NULL, 0, V_BSTR(&varNamespace), NULL, pUpdSvc, NULL, &InitSink ); if ( FAILED(hr) ) { return hr; } return pDirectInit->QueryInterface(IID_IWbemServices, (void**)ppDirectSvc); } /******************************************************************** CUpdConsCommand *********************************************************************/ HRESULT CUpdConsCommand::ProcessUpdateQuery( LPCWSTR wszUpdateQuery, IWbemServices* pUpdSvc, CUpdConsState& rState, IWbemClassObject** ppUpdClass ) { HRESULT hr; *ppUpdClass = NULL; CTextLexSource Lexer( wszUpdateQuery ); CSQLParser Parser( Lexer ); if ( Parser.Parse( m_SqlCmd ) != 0 ) { rState.SetErrStr( Parser.CurrentToken() ); return WBEM_E_INVALID_QUERY; } if ( m_SqlCmd.m_eCommandType == SQLCommand::e_Select ) { rState.SetErrStr( wszUpdateQuery ); return WBEM_E_QUERY_NOT_IMPLEMENTED; } hr = pUpdSvc->GetObject( m_SqlCmd.bsClassName, 0, NULL, ppUpdClass, NULL); if ( FAILED(hr) ) { rState.SetErrStr( m_SqlCmd.bsClassName ); return hr; } return WBEM_S_NO_ERROR; } HRESULT CUpdConsCommand::ProcessDataQuery( LPCWSTR wszDataQuery, IWbemServices* pDataSvc, CUpdConsState& rState, IWbemClassObject** ppDataClass ) { *ppDataClass = NULL; return WBEM_S_NO_ERROR; } HRESULT CUpdConsCommand::ProcessEventQuery( LPCWSTR wszEventQuery, IWbemServices* pEventSvc, CUpdConsState& rState, IWbemClassObject** ppEventClass ) { // // TODO: in the future we should be able to optimize the correlator // for the incoming events too. It would be nice to know the type of // incoming events so that we can obtain fast accessors. // *ppEventClass = NULL; return WBEM_S_NO_ERROR; } HRESULT CUpdConsCommand::InitializeAccessFactories(IWbemClassObject* pUpdClass) { HRESULT hr; // // obtain access factories and prepare them for fetching prop access hdls. // CWbemPtr<IClassFactory> pClassFact; hr = CoGetClassObject( CLSID_WmiSmartObjectAccessFactory, CLSCTX_INPROC, NULL, IID_IClassFactory, (void**)&pClassFact ); if ( FAILED(hr) ) { return hr; } hr = pClassFact->CreateInstance( NULL, IID_IWmiObjectAccessFactory, (void**)&m_pEventAccessFact ); if ( FAILED(hr) ) { return hr; } hr = pClassFact->CreateInstance( NULL, IID_IWmiObjectAccessFactory, (void**)&m_pDataAccessFact ); if ( FAILED(hr) ) { return hr; } hr = pClassFact->CreateInstance( NULL, IID_IWmiObjectAccessFactory, (void**)&m_pInstAccessFact ); if ( FAILED(hr) ) { return hr; } hr = m_pInstAccessFact->SetObjectTemplate( pUpdClass ); if ( FAILED(hr) ) { return hr; } return WBEM_S_NO_ERROR; } /******************************************************************** InitializePropertyInfo() - This method examines the SQLCommand object and constructs a summary to aid in its execution. It also finishes checking the semantics of the SQL command. Since the parser does not have the alias support built into it, it is checked here. This method does modify the SQLCommand by removing the ALIAS keywords DATA/OBJECT from the property names. This method also obtains a property access handle from the appropriate access factory for the each referenced property and stores it with the prop structure. ********************************************************************/ HRESULT CUpdConsCommand::InitializePropertyInfo( CUpdConsState& rState ) { HRESULT hr; LPCWSTR wszAlias; // // process properties in the assignment tokens. // _DBG_ASSERT( m_SqlCmd.nNumberOfProperties == m_SqlCmd.m_AssignmentTokens.size() ); int i; for( i=0; i < m_SqlCmd.m_AssignmentTokens.size(); i++ ) { SQLAssignmentToken& rAssignToken = m_SqlCmd.m_AssignmentTokens[i]; for( int j=0; j < rAssignToken.size(); j++ ) { CPropertyName& rPropName = rAssignToken[j].m_PropName; if ( rPropName.GetNumElements() == 0 ) { continue; } wszAlias = rPropName.GetStringAt(0); _DBG_ASSERT(wszAlias != NULL); if ( _wcsicmp( wszAlias, g_wszDataAlias ) == 0 ) { m_DataAliasOffsets.AddAssignOffset( i, j ); RemoveAliasKeyword( rPropName ); hr = SetPropHandle( rPropName, m_pDataAccessFact ); } else if ( _wcsicmp( wszAlias, g_wszEventAlias ) == 0 ) { m_EventAliasOffsets.AddAssignOffset( i, j ); RemoveAliasKeyword( rPropName ); hr = SetPropHandle( rPropName, m_pEventAccessFact ); } else { hr = SetPropHandle( rPropName, m_pInstAccessFact ); } if ( FAILED(hr) ) { rState.SetErrStr( wszAlias ); return hr; } } // // process property on the left side of the assignment. // CPropertyName& rPropName = m_SqlCmd.pRequestedPropertyNames[i]; _DBG_ASSERT( rPropName.GetNumElements() > 0 ); hr = SetPropHandle( rPropName, m_pInstAccessFact ); if ( FAILED(hr) ) { rState.SetErrStr( wszAlias ); return hr; } } // // process properties in the condition clause // // TODO : I should be setting the bPropComp value in a token // to FALSE after detecting the presence of an alias. However, // the alias name is stored in the Prop2 member of the token and // that will not be copied by the assignment op or copy ctor if // bPropComp is false. This should be fixed, but in the meanwhile I'm // going to use the presence of a value in the vConstValue to signal // that it is not a real prop compare. for( i=0; i < m_SqlCmd.nNumTokens; i++ ) { CPropertyName& rProp1 = m_SqlCmd.pArrayOfTokens[i].PropertyName; CPropertyName& rProp2 = m_SqlCmd.pArrayOfTokens[i].PropertyName2; if ( m_SqlCmd.pArrayOfTokens[i].nTokenType != QL_LEVEL_1_TOKEN::OP_EXPRESSION ) { continue; } _DBG_ASSERT( rProp1.GetNumElements() > 0 ); wszAlias = rProp1.GetStringAt(0); _DBG_ASSERT( wszAlias != NULL ); BOOL bAlias = FALSE; if ( _wcsicmp( wszAlias, g_wszDataAlias ) == 0 ) { bAlias = TRUE; m_DataAliasOffsets.AddWhereOffset(i); RemoveAliasKeyword( rProp1 ); hr = SetPropHandle( rProp1, m_pDataAccessFact ); } else if ( _wcsicmp( wszAlias, g_wszEventAlias ) == 0 ) { bAlias = TRUE; m_EventAliasOffsets.AddWhereOffset(i); RemoveAliasKeyword( rProp1 ); hr = SetPropHandle( rProp1, m_pEventAccessFact ); } else { hr = SetPropHandle( rProp1, m_pInstAccessFact ); } if ( FAILED(hr) ) { rState.SetErrStr( wszAlias ); return hr; } if ( !m_SqlCmd.pArrayOfTokens[i].m_bPropComp ) { if ( bAlias ) { // // this means that someone is trying to compare an // alias to const val. Not a valid use of aliases. // rState.SetErrStr( wszAlias ); return WBEM_E_INVALID_QUERY; } else { continue; } } _DBG_ASSERT( rProp2.GetNumElements() > 0 ); wszAlias = rProp2.GetStringAt(0); _DBG_ASSERT( wszAlias != NULL ); if ( _wcsicmp( wszAlias, g_wszDataAlias ) == 0 ) { if ( !bAlias ) { m_DataAliasOffsets.AddWhereOffset(i); RemoveAliasKeyword( rProp2 ); hr = SetPropHandle( rProp2, m_pDataAccessFact ); } else { hr = WBEM_E_INVALID_QUERY; } } else if ( _wcsicmp( wszAlias, g_wszEventAlias ) == 0 ) { if ( !bAlias ) { m_EventAliasOffsets.AddWhereOffset(i); RemoveAliasKeyword( rProp2 ); hr = SetPropHandle( rProp2, m_pEventAccessFact ); } else { hr = WBEM_E_INVALID_QUERY; } } else { hr = SetPropHandle( rProp2, m_pInstAccessFact ); if ( bAlias ) { // this is the case we where have a real propname as the // second prop and an alias as the first. We must adjust // the token so that the real propname is first and the alias // is second because we need to stay consistent // with the prop <rel_operator> const model which the QL1 // Parser has established. CPropertyName Tmp = rProp1; rProp1 = rProp2; rProp2 = Tmp; // of course the operator must be flipped .. int& nOp = m_SqlCmd.pArrayOfTokens[i].nOperator; nOp = FlipOperator( nOp ); } } if ( FAILED(hr) ) { rState.SetErrStr( wszAlias ); return hr; } } return WBEM_S_NO_ERROR; } HRESULT CUpdConsCommand::InitializeDefaultAccessors() { HRESULT hr; // // get default accessors from the factories. These are only used // we're guaranteed that calls to Execute() are serialized. If not, // then Execute() will be responsible for allocating new ones. // hr = m_pEventAccessFact->GetObjectAccess( &m_pEventAccess ); if ( FAILED(hr) ) { return hr; } hr = m_pDataAccessFact->GetObjectAccess( &m_pDataAccess ); if ( FAILED(hr) ) { return hr; } hr = m_pInstAccessFact->GetObjectAccess( &m_pInstAccess ); if ( FAILED(hr) ) { return hr; } hr = m_pInstAccessFact->GetObjectAccess( &m_pOrigInstAccess ); return hr; } HRESULT CUpdConsCommand::InitializeExecSinks( ULONG ulFlags, IWbemServices* pUpdSvc, IWbemClassObject* pUpdClass, LPCWSTR wszDataQuery, IWbemServices* pDataSvc ) { HRESULT hr; CUpdConsNamespace* pNamespace = m_pScenario->GetNamespace(); // // only care about update disposition flags // ulFlags &= 0x3; // // only set pEventSink if our class is derived from our // extrinsic event class. The presence of this pointer will be // used to tell us which sink to create. // CWbemPtr<IWbemObjectSink> pEventSink; hr = pUpdClass->InheritsFrom( g_wszUpdateEventClass ); if ( hr == WBEM_S_NO_ERROR ) { pEventSink = pNamespace->GetEventSink(); } else if ( FAILED(hr) ) { return hr; } // // here we determine if we can use the direct svc optimization // first check to see if the class is transient. // BOOL bTransient = FALSE; hr = IsClassTransient( pUpdClass ); CWbemPtr<IWbemServices> pSvc; if ( hr == WBEM_S_NO_ERROR ) { hr = GetDirectSvc( pUpdClass, pUpdSvc, &pSvc ); if ( FAILED(hr) ) { return hr; } bTransient = TRUE; ulFlags |= WBEM_FLAG_RETURN_IMMEDIATELY; } else { pSvc = pUpdSvc; } CWbemPtr<IWbemClassObject> pCmdTraceClass; CWbemPtr<IWbemClassObject> pInstTraceClass; // // now that we've got everything set, set up the sink chain that // we'll use to do the execute. // CWbemPtr<CUpdConsSink> pSink; // // create sink chain based on command type // if ( m_SqlCmd.m_eCommandType == SQLCommand::e_Update ) { pCmdTraceClass = pNamespace->GetUpdateCmdTraceClass(); pInstTraceClass = pNamespace->GetUpdateInstTraceClass(); pSink = new CPutSink( pSvc, ulFlags, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CAssignmentSink( bTransient, pUpdClass, m_SqlCmd.m_eCommandType, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CTraceSink( m_pScenario, pInstTraceClass, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CFilterSink( pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } // // use the async version only in the case where we go directly to // the transient provider. // if ( bTransient ) { pSink = new CFetchTargetObjectsAsync( pSvc, pSink ); } else { pSink = new CFetchTargetObjectsSync( pSvc, pSink ); } if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } } else if ( m_SqlCmd.m_eCommandType == SQLCommand::e_Insert ) { pCmdTraceClass = pNamespace->GetInsertCmdTraceClass(); pInstTraceClass = pNamespace->GetInsertInstTraceClass(); // // If inserts are going to be done on an Extrinsic event class, // then use the event sink instead of an update sink. // if ( pEventSink != NULL ) { pSink = new CBranchIndicateSink( pEventSink, pSink ); } else { pSink = new CPutSink( pSvc, ulFlags, pSink ); } if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CAssignmentSink( bTransient, pUpdClass, m_SqlCmd.m_eCommandType, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CTraceSink( m_pScenario, pInstTraceClass, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CNoFetchTargetObjects( pUpdClass, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } } else { // // we never go direct with deletes because we would have to queue // objects to delete until we were done enumerating them. // pCmdTraceClass = pNamespace->GetDeleteCmdTraceClass(); pInstTraceClass = pNamespace->GetDeleteInstTraceClass(); pSink = new CDeleteSink( pUpdSvc, 0, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CTraceSink( m_pScenario, pInstTraceClass, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CFilterSink( pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CFetchTargetObjectsSync( pUpdSvc, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } } pSink = new CTraceSink( m_pScenario, pCmdTraceClass, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } pSink = new CResolverSink( m_EventAliasOffsets, m_DataAliasOffsets, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } if ( wszDataQuery != NULL && *wszDataQuery != '\0' ) { pSink = new CFetchDataSink( wszDataQuery, pDataSvc, pSink ); if ( pSink == NULL ) { return WBEM_E_OUT_OF_MEMORY; } } m_pSink = pSink; return WBEM_S_NO_ERROR; } /***************************************************************************** CUpdConsCommand ******************************************************************************/ HRESULT CUpdConsCommand::Create( LPCWSTR wszUpdateQuery, LPCWSTR wszDataQuery, ULONG ulFlags, IWbemServices* pUpdSvc, IWbemServices* pDataSvc, CUpdConsScenario* pScenario, CUpdConsState& rState, CUpdConsCommand** ppCmd ) { HRESULT hr; *ppCmd = NULL; CWbemPtr<CUpdConsCommand> pCmd = new CUpdConsCommand( pScenario ); if ( pCmd == NULL ) { return WBEM_E_OUT_OF_MEMORY; } CWbemPtr<IWbemClassObject> pUpdClass, pDataClass, pEventClass; hr = pCmd->ProcessUpdateQuery( wszUpdateQuery, pUpdSvc, rState, &pUpdClass ); if ( FAILED(hr) ) { return hr; } hr = pCmd->ProcessDataQuery( wszDataQuery, pDataSvc, rState, &pDataClass ); if ( FAILED(hr) ) { return hr; } hr = pCmd->ProcessEventQuery( NULL, NULL, rState, &pEventClass ); if ( FAILED(hr) ) { return hr; } hr = pCmd->InitializeAccessFactories( pUpdClass ); if ( FAILED(hr) ) { return hr; } hr = pCmd->InitializePropertyInfo( rState ); if ( FAILED(hr) ) { return hr; } hr = pCmd->InitializeDefaultAccessors(); if ( FAILED(hr) ) { return hr; } hr = pCmd->InitializeExecSinks( ulFlags, pUpdSvc, pUpdClass, wszDataQuery, pDataSvc ); if ( FAILED(hr) ) { return hr; } pCmd->AddRef(); *ppCmd = pCmd; return WBEM_S_NO_ERROR; } HRESULT CUpdConsCommand::Execute( CUpdConsState& rState, BOOL bConcurrent ) { HRESULT hr; if ( !bConcurrent ) { rState.SetSqlCmd( &m_SqlCmd, FALSE ); hr = rState.SetEventAccess(m_pEventAccess); if ( FAILED(hr) ) { return hr; } hr = rState.SetDataAccess(m_pDataAccess); if ( FAILED(hr) ) { return hr; } hr = rState.SetInstAccess(m_pInstAccess); if ( FAILED(hr) ) { return hr; } hr = rState.SetOrigInstAccess(m_pOrigInstAccess); if ( FAILED(hr) ) { return hr; } } else { SQLCommand* pCmd = new SQLCommand( m_SqlCmd ); if ( pCmd == NULL ) { return WBEM_E_OUT_OF_MEMORY; } rState.SetSqlCmd( pCmd, TRUE ); CWbemPtr<IWmiObjectAccess> pAccess; hr = m_pEventAccessFact->GetObjectAccess( &pAccess ); if ( FAILED(hr) || FAILED(hr=rState.SetEventAccess(pAccess)) ) { return hr; } pAccess.Release(); hr = m_pDataAccessFact->GetObjectAccess( &pAccess ); if ( FAILED(hr) || FAILED(hr=rState.SetDataAccess(pAccess)) ) { return hr; } pAccess.Release(); hr = m_pInstAccessFact->GetObjectAccess( &pAccess ); if ( FAILED(hr) || FAILED(hr=rState.SetInstAccess(pAccess)) ) { return hr; } pAccess.Release(); hr = m_pInstAccessFact->GetObjectAccess( &pAccess ); if ( FAILED(hr) || FAILED(hr=rState.SetOrigInstAccess(pAccess)) ) { return hr; } pAccess.Release(); } hr = m_pSink->Execute( rState ); // // at this point we reset any state that is not needed // by caller. // rState.SetInst( NULL ); rState.SetData( NULL ); return hr; }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
59f2010ae30916ef4ed3e06344be175276016916
23ea7fc0dde3c46a4599241116dbb24efb763fe5
/host/tools/configtool/common/win32/IdleMessage.h
50494f919ca517c8c3a45d4c13ff9752d8d55299
[]
no_license
metadevfoundation/ecos-ax-som-bf609
5a1fa24c344533f308e2cf3a40843eb2dd1ca644
4d587d59f5daf3e76ae44323e0bcb5463f1ce54a
refs/heads/master
2020-12-28T21:28:53.139917
2014-03-12T16:53:37
2014-03-12T16:53:37
33,082,245
0
1
null
2020-08-30T00:56:00
2015-03-29T17:36:55
C
UTF-8
C++
false
false
2,043
h
// ####ECOSHOSTGPLCOPYRIGHTBEGIN#### // ------------------------------------------- // This file is part of the eCos host tools. // Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc. // // 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 2 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, write to the // Free Software Foundation, Inc., 51 Franklin Street, // Fifth Floor, Boston, MA 02110-1301, USA. // ------------------------------------------- // ####ECOSHOSTGPLCOPYRIGHTEND#### // IdleMessage.h: interface for the CIdleMessage class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_IDLEMESSAGE_H__D2C84B41_378B_11D3_8567_A711BD1AC4A3__INCLUDED_) #define AFX_IDLEMESSAGE_H__D2C84B41_378B_11D3_8567_A711BD1AC4A3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CIdleMessage { public: void Reset(); void Set(LPCTSTR psz); CIdleMessage(LPCTSTR pszMsg); virtual ~CIdleMessage(); protected: CString m_strPrevIdle; }; #endif // !defined(AFX_IDLEMESSAGE_H__D2C84B41_378B_11D3_8567_A711BD1AC4A3__INCLUDED_)
[ "aleksandr.loiko@axonim.by" ]
aleksandr.loiko@axonim.by
070af49e423c612d4c019eda0ea48600ddf79f9b
d5df1d2220e9e6131cfaffd5f6777f38a58bee9f
/school/cs175/final/old.cpp
a7cdfa7809140560f98c5ed888790994addc92a5
[]
no_license
crimsoncantab/oldschool
1515b9441e79039f553d3fd77d0f5a02049da98a
7167abd746af40563383ed76dff206615eadea93
refs/heads/master
2021-01-10T13:15:50.089623
2016-01-18T07:38:52
2016-01-18T07:38:52
48,214,341
1
0
null
null
null
null
UTF-8
C++
false
false
24,923
cpp
//////////////////////////////////////////////////////////////////////// // // Harvard University // CS175 : Computer Graphics // Professor Steven Gortler // // Formatted for 4-space tabs, wide lines // //////////////////////////////////////////////////////////////////////// #include <cstdio> #include <cstdlib> #include <cassert> #include <GL/glew.h> #ifdef __MAC__ # include <GLUT/glut.h> #else # include <GL/glut.h> #endif #include <vector> #include <list> #include <ctime> #include <iostream> #include <fstream> #include <sstream> #include "ppm.h" #include "matrix4.h" #include "rbt.h" #include "shader.h" #include "arcball.h" #include "mesh.h" using namespace std; // ----------- GL stuff static const double frust_fovy = 60.0; // 60 degree field of view in y direction static const double frust_near = -0.1; // near plane static const double frust_far = -50.0; // far plane static const double floor_y = -2.0; // y coordinate of the floor static const double floor_size = 10.0; // half the floor length enum {SKY=0, OBJECT0=1}; enum {WORLD_SKY=0, SKY_SKY=1}; static int window_width = 512; static int window_height = 512; static bool mouse_lclick_button, mouse_rclick_button, mouse_mclick_button; static int mouse_click_x, mouse_click_y; // coordinates for mouse click event static int active_shader = 0; static int active_object = 0; static int active_eye = SKY; static int active_camera_frame = WORLD_SKY; static bool draw_shells = false; static bool display_arcball = false; static double arcball_radius = 2.5; static Mesh mesh; static std::vector <Vector3> tips, vtips; static vector<Mesh> shells; static float fur_height = 0.21; static const int num_shells = 32; static float texture_coord = 1; static float stiffness = .3; static float time_step = 0.01; static const int num_sim_idle = 15; static const Vector3 gravity(0, -0.5, 0); static float damping = 0.96; GLuint h_texture_fins; // texture handles GLuint h_texture_shells; struct ShaderState { GLuint h_program_; GLuint h_texture_; GLint h_texUnit0_; GLint h_texUnit1_; GLint h_uLight_; /// handle to uniform variable for light vector GLint h_uProjMatrix_; /// handle to unifrom var for projection matrix GLint h_uModelViewMatrix_; /// handle to uniform var for model view matrices for Base GLint h_uNormalMatrix_; /// handle to uniform var for transforming normals for Base GLint h_colorAmbient_; /// handle to attribute variable for color of vertex GLint h_colorDiffuse_; /// handle to attribute variable for color of vertex GLint h_vtexCoord_; /// handle to uniform variable for light vector GLint h_vTangent_; GLint h_valpha_exponent_; }; static std::vector <ShaderState> SState(2); // initializes a vector with 2 ShaderState static const char * const shader_file[3][2] = { {"./shaders/shader.vert", "./shaders/shader.frag"}, // basic rendering {"./shaders/shader_shells.vert", "./shaders/shader_shells.frag"} // shells }; // --------- Scene static const Vector3 Light(10.0, 5.5, 17.0); // light position struct Cube { Rbt pose_; Vector3 color_; Cube() {} Cube(const Rbt& p, const Vector3& c) : pose_(p), color_(c) {} }; static Rbt skyPose_(Vector3(0.0, 0.5, 7.0)); static Cube cube_ = Cube(Rbt(Vector3(0.0, 0.0, 0.0)), Vector3(1, 0, 0)); static void init_tips() { vtips.resize(mesh.getNumVertices(), Vector3(0)); tips.resize(mesh.getNumVertices()); for (int i = 0; i < mesh.getNumVertices(); i++) { tips[i] = cube_.pose_ * (mesh.getVertex(i).getPosition() + mesh.getVertex(i).getNormal() * fur_height); } // TODO: initialize tips to "at-rest" hair tips in world coordinates } static void sendModelViewNormalMatrix(const Matrix4& MVM) // takes MVM and sends it (and normal matrix) to the vertex shader { GLfloat glmatrix[16]; MVM.writeToColumnMajorMatrix(glmatrix); // send MVM safe_glUniformMatrix4fv(SState[active_shader].h_uModelViewMatrix_, glmatrix); MVM.getNormalMatrix().writeToColumnMajorMatrix(glmatrix); // send normal matrix safe_glUniformMatrix4fv(SState[active_shader].h_uNormalMatrix_, glmatrix); } static Rbt getEyePose() { return active_eye == SKY ? skyPose_ : cube_.pose_; } static Rbt getArcballPose() { return active_object == SKY ? (active_camera_frame == WORLD_SKY ? Rbt() : skyPose_) : cube_.pose_; } static void drawArcBall() { sendModelViewNormalMatrix((getEyePose().getInverse() * getArcballPose()).getMatrix()); glutWireSphere(arcball_radius, 20, 20); // draw wireframe sphere } static void init_normals(Mesh& m) { for (int i = 0; i < m.getNumVertices(); ++i) m.getVertex(i).setNormal(Vector3(0)); for (int i = 0; i < m.getNumFaces(); ++i) { const Vector3 n = m.getFace(i).getNormal(); if (std::abs(Vector3::dot(n, n) - 1) < 1e-6) // we only use valid normals for (int j = 0; j < m.getFace(i).getNumVertices(); ++j) m.getFace(i).getVertex(j).setNormal(m.getFace(i).getVertex(j).getNormal() + n); } for (int i = 0; i < m.getNumVertices(); ++i) m.getVertex(i).setNormal(m.getVertex(i).getNormal().length2() < 1e-10 ? Vector3() : m.getVertex(i).getNormal().normalize()); } static void draw_vertex(const Vector3& v, const Vector3& n) { glNormal3f(n[0], n[1], n[2]); glVertex3f(v[0], v[1], v[2]); } static void draw(Mesh& m, const Vector3& LightE) { GLfloat glmatrix[16]; const Matrix4 projmat = Matrix4::makeProjection(frust_fovy, window_width / static_cast <double> (window_height), frust_near, frust_far); projmat.writeToColumnMajorMatrix(glmatrix); const Rbt eyeInverse = getEyePose().getInverse(); sendModelViewNormalMatrix((eyeInverse * cube_.pose_).getMatrix()); init_normals(m); glEnable(GL_CULL_FACE); glBegin(GL_TRIANGLES); for (int i = 0; i < m.getNumFaces(); ++i) // draw the base mesh { safe_glVertexAttrib3f(SState[0].h_colorAmbient_, 0.45, 0.3, 0.3); safe_glVertexAttrib3f(SState[0].h_colorDiffuse_, 0.2, 0.2, 0.2); draw_vertex(m.getFace(i).getVertex(0).getPosition(), m.getFace(i).getVertex(0).getNormal()); safe_glVertexAttrib3f(SState[0].h_colorAmbient_, 0.45, 0.3, 0.3); safe_glVertexAttrib3f(SState[0].h_colorDiffuse_, 0.2, 0.2, 0.2); draw_vertex(m.getFace(i).getVertex(1).getPosition(), m.getFace(i).getVertex(1).getNormal()); safe_glVertexAttrib3f(SState[0].h_colorAmbient_, 0.45, 0.3, 0.3); safe_glVertexAttrib3f(SState[0].h_colorDiffuse_, 0.2, 0.2, 0.2); draw_vertex(m.getFace(i).getVertex(2).getPosition(), m.getFace(i).getVertex(2).getNormal()); } glEnd(); glEnable(GL_BLEND); // for the rest of the drawing (shells) enable alpha blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); if (draw_shells) { active_shader = 1; safe_glUseProgram(SState[active_shader].h_program_); safe_glUniformMatrix4fv(SState[active_shader].h_uProjMatrix_, glmatrix); safe_glUniform3f(SState[active_shader].h_uLight_, LightE[0], LightE[1], LightE[2]); sendModelViewNormalMatrix((eyeInverse * cube_.pose_).getMatrix()); safe_glUniform1i(SState[active_shader].h_texUnit0_, 0); safe_glUniform1i(SState[active_shader].h_texUnit1_, 1); glDepthMask(GL_TRUE); // enables writing to depth-buffer Mesh shell_m(m); for (int i = 0; i < shell_m.getNumVertices(); i++) { shell_m.getVertex(i).setPosition(cube_.pose_ * tips[i]); } for (int i = 0; i < num_shells; ++i) { float h = i/(float)num_shells * fur_height; // TODO: before drawing each shell, set (valpha_exponent = 2 + // 5*(height/fur_height)), where "height" is the height of the // current shell, and fur_height is the total height of the // fur. safe_glUniform1f(SState[active_shader].h_valpha_exponent_,2 + 5*(h/fur_height)); // TODO: draw shells. // // VShader expects that you set (vtexCoord) (texture // coordinates into the shell-texture) VShader also expects // that you set gl_Normal (which will be the tangent direction // of the hair) glBegin(GL_TRIANGLES); for (int j = 0; j < m.getNumFaces(); ++j) { Mesh::Face face = m.getFace(j); Mesh::Face shell_face = shell_m.getFace(j); for (int k = 0; k < 3; k++) { Mesh::Vertex v = face.getVertex(k); Vector3 p = v.getPosition(); Vector3 s = p + v.getNormal()* fur_height; Vector3 t = shell_face.getVertex(k).getPosition(); Vector3 n = (s - p)/num_shells; Vector3 d = (t - s) * (2. / (num_shells * (num_shells + 1))); Vector3 pi = p + (n * (i+1)) + d * ((i * (i-1)) / 2.); safe_glVertexAttrib2f(SState[active_shader].h_vtexCoord_,(k==1 || k==3)? 0 : texture_coord,(k==1 || k==2)? 0 : texture_coord); draw_vertex(pi, n + d * i); } } glEnd(); } } glDepthMask(GL_TRUE); // enables writing to depth-buffer glDisable(GL_BLEND); glEnable(GL_CULL_FACE); // draw the shells } static void drawStuff() { active_shader = 0; safe_glUseProgram(SState[active_shader].h_program_); GLfloat glmatrix[16]; const Matrix4 projmat = Matrix4::makeProjection(frust_fovy, window_width / static_cast <double> (window_height), frust_near, frust_far); projmat.writeToColumnMajorMatrix(glmatrix); safe_glUniformMatrix4fv(SState[active_shader].h_uProjMatrix_, glmatrix); // build & send proj. matrix to vshader const Rbt eyeInverse = getEyePose().getInverse(); const Vector3 light = eyeInverse * Light; // light direction in eye coordinates safe_glUniform3f(SState[active_shader].h_uLight_, light[0], light[1], light[2]); // draw floor const Rbt groundFrame = Rbt(); // identity sendModelViewNormalMatrix((eyeInverse * groundFrame).getMatrix()); // draw the floor glBegin(GL_TRIANGLES); safe_glVertexAttrib3f(SState[active_shader].h_colorAmbient_, 0.0, 0.0, 0.0); safe_glVertexAttrib3f(SState[active_shader].h_colorDiffuse_, 0.4, 1, 0.4); glNormal3f(0.0, 1.0, 0.0); glVertex3f(-floor_size, floor_y, -floor_size); safe_glVertexAttrib3f(SState[active_shader].h_colorAmbient_, 0.0, 0.0, 0.0); safe_glVertexAttrib3f(SState[active_shader].h_colorDiffuse_, 0.4, 1, 0.4); glNormal3f(0.0, 1.0, 0.0); glVertex3f( floor_size, floor_y, floor_size); safe_glVertexAttrib3f(SState[active_shader].h_colorAmbient_, 0.0, 0.0, 0.0); safe_glVertexAttrib3f(SState[active_shader].h_colorDiffuse_, 0.4, 1, 0.4); glNormal3f(0.0, 1.0, 0.0); glVertex3f( floor_size, floor_y, -floor_size); safe_glVertexAttrib3f(SState[active_shader].h_colorAmbient_, 0.0, 0.0, 0.0); safe_glVertexAttrib3f(SState[active_shader].h_colorDiffuse_, 0.4, 1, 0.4); glNormal3f(0.0, 1.0, 0.0); glVertex3f(-floor_size, floor_y, -floor_size); safe_glVertexAttrib3f(SState[active_shader].h_colorAmbient_, 0.0, 0.0, 0.0); safe_glVertexAttrib3f(SState[active_shader].h_colorDiffuse_, 0.4, 1, 0.4); glNormal3f(0.0, 1.0, 0.0); glVertex3f(-floor_size, floor_y, floor_size); safe_glVertexAttrib3f(SState[active_shader].h_colorAmbient_, 0.0, 0.0, 0.0); safe_glVertexAttrib3f(SState[active_shader].h_colorDiffuse_, 0.4, 1, 0.4); glNormal3f(0.0, 1.0, 0.0); glVertex3f( floor_size, floor_y, floor_size); glEnd(); if (display_arcball) drawArcBall(); // draw the arcball on top of everything else draw(mesh, light); } static void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear framebuffer color&depth drawStuff(); glutSwapBuffers(); // show the back buffer (where we rendered stuff) const GLenum errCode = glGetError(); // check for errors if (errCode != GL_NO_ERROR) std::cerr << "Error: " << gluErrorString(errCode) << std::endl; } static void reshape(const int w, const int h) { window_width = w; window_height = h; glViewport(0, 0, w, h); std::cerr << "Size of window is now " << w << "x" << h << std::endl; glutPostRedisplay(); } static Vector3 getArbBallDirection(Vector3 p, const double r) { if (p[0]*p[0]+p[1]*p[1] > r*r) p *= std::sqrt((r*r - 1) / (p[0]*p[0]+p[1]*p[1])); // in case the mouse moved outside the arcball return Vector3(p[0], p[1], std::sqrt(r*r - (p[0]*p[0]+p[1]*p[1]))).normalize(); } static Rbt moveArcball(const Vector3& p0, const Vector3& p1) { const Matrix4 projMatrix = Matrix4::makeProjection(frust_fovy, window_width / static_cast <double> (window_height), frust_near, frust_far); const Rbt eyeInverse = getEyePose().getInverse(); const Vector3 arcballCenter = getArcballPose().getTranslation(); Vector2 ballScreenCenter; double ballScreenRadius; if (!getScreenSpaceCircle(eyeInverse * arcballCenter, arcball_radius, projMatrix, frust_near, frust_fovy, window_width, window_height, &ballScreenCenter, &ballScreenRadius)) return Rbt(); const Vector3 v0 = getArbBallDirection(p0 - Vector3(ballScreenCenter[0], ballScreenCenter[1], 0), ballScreenRadius); const Vector3 v1 = getArbBallDirection(p1 - Vector3(ballScreenCenter[0], ballScreenCenter[1], 0), ballScreenRadius); return Rbt(Quaternion(0.0, v1[0], v1[1], v1[2]) * Quaternion(0.0, v0[0], v0[1], v0[2])); } static Rbt do_Q_to_O_wrt_A(const Rbt& O, const Rbt& Q, const Rbt& A) { return A * Q * A.getInverse() * O; } static void motion(const int x, const int y) { if (!mouse_lclick_button && !mouse_rclick_button && !mouse_mclick_button) return; if (active_object == SKY && active_eye != SKY) return; // we do not edit the eye when viewed from the objects const int nx = x; const int ny = window_height - y - 1; const double dx = nx - mouse_click_x; const double dy = ny - mouse_click_y; Rbt Q = mouse_lclick_button && !mouse_rclick_button ? Rbt(Quaternion::makeXRotation(-dy) * Quaternion::makeYRotation(dx)) : ( mouse_rclick_button && !mouse_lclick_button ? Rbt(Vector3(dx, dy, 0) * 0.01) : Rbt(Vector3(0, 0, -dy) * 0.01)); if ((active_object != SKY && active_object != active_eye) || (active_object == SKY && active_camera_frame == WORLD_SKY)) if (mouse_lclick_button && !mouse_rclick_button) { Q = moveArcball(Vector3(mouse_click_x, mouse_click_y, 0), Vector3(nx, ny, 0)); } if (active_object == active_eye) { if (active_eye != SKY || active_camera_frame != WORLD_SKY) { if (mouse_lclick_button && !mouse_rclick_button) Q = Q.getInverse(); } else Q = Q.getInverse(); } Rbt& O = active_object == SKY ? skyPose_ : cube_.pose_; const Rbt A(active_object == OBJECT0 ? cube_.pose_.getTranslation() : ( // the translation part of the reference frame active_camera_frame == WORLD_SKY ? Vector3() : skyPose_.getTranslation()), active_eye == OBJECT0 ? cube_.pose_.getRotation() : // the rotation part of the reference frame skyPose_.getRotation()); O = do_Q_to_O_wrt_A(O, Q, A); mouse_click_x = nx; mouse_click_y = ny; glutPostRedisplay(); // we always redraw if we changed the scene } static void mouse(const int button, const int state, const int x, const int y) { mouse_click_x = x; mouse_click_y = window_height - y - 1; // conversion from GLUT window-coordinate-system to OpenGL window-coordinate-system if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) mouse_lclick_button = true; if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) mouse_rclick_button = true; if (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) mouse_mclick_button = true; if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) mouse_lclick_button = false; if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP) mouse_rclick_button = false; if (button == GLUT_MIDDLE_BUTTON && state == GLUT_UP) mouse_mclick_button = false; display_arcball = state == GLUT_DOWN; } static void keyboard(const unsigned char key, const int x, const int y) { switch (key) { case 27: exit(0); // ESC case 'h': std::cerr << " ============== H E L P ==============\n\n"; std::cerr << "h\t\thelp menu\n"; std::cerr << "w\t\tsave screenshot\n"; std::cerr << "s\t\tToggle draw-shells on/off.\n"; std::cerr << "o\t\tCycle object to edit\n"; std::cerr << "v\t\tCycle view\n"; std::cerr << "drag left mouse to rotate\n"; break; case 'w': glFlush(); WritePPMScreenshot(window_width, window_height, "out.ppm"); break; case 's': draw_shells = !draw_shells; break; case 'v': active_eye = (active_eye+1) % 2; std::cerr << "Active eye is " << (active_eye == SKY ? "sky eye\n" : (active_eye == OBJECT0 ? "object0 eye\n" : "object1 eye\n")); break; case 'o': active_object = (active_object+1) % 2; std::cerr << "Active object is " << (active_object == SKY ? "sky eye\n" : (active_object == OBJECT0 ? "object0\n" : "object1\n")); break; case 'm': active_camera_frame = (active_camera_frame+1) % 2; std::cerr << "Editing sky eye w.r.t. " << (active_camera_frame == WORLD_SKY ? "world-sky frame\n" : "sky-sky frame\n"); break; case '-': case '_': stiffness /= 1.05; cout<<"stiffness: "<<stiffness<<endl; break; case '=': case '+': stiffness *= 1.05; cout<<"stiffness: "<<stiffness<<endl; break; case 'z': if (damping > .93) { damping /= 1.001; } cout<<"damping: "<<damping<<endl; break; case 'x': if (damping < 0.999) { damping *= 1.001; } else { damping = 0.999; } cout<<"damping: "<<damping<<endl; break; } glutPostRedisplay(); } static void special_keyboard(const int key, const int x, const int y) { switch (key) { case GLUT_KEY_RIGHT: fur_height *= 1.05; cout<<"fur height: "<<fur_height<<endl; break; case GLUT_KEY_LEFT: fur_height /= 1.05; cout<<"fur height: "<<fur_height<<endl; break; case GLUT_KEY_UP: texture_coord *= 1.05; cout<<"texture coord: "<<texture_coord<<endl; break; case GLUT_KEY_DOWN: texture_coord /= 1.05; cout<<"texture coord: "<<texture_coord<<endl; break; } glutPostRedisplay(); } static void idle() { // TODO: animate the dynamics here for (int i = 0; i < num_sim_idle; i++) { for (int j = 0; j < mesh.getNumVertices(); j ++) { Vector3 p_world = cube_.pose_/*.getInverse()*/ * mesh.getVertex(j).getPosition(); Vector3 s_world = cube_.pose_/*.getInverse()*/ * mesh.getVertex(j).getPosition() + mesh.getVertex(j).getNormal()* fur_height; Vector3 a = gravity + ((s_world - tips[j]) * stiffness); tips[j] = tips[j] + vtips[j] * time_step; tips[j] = p_world + ((tips[j] - p_world)/(tips[j] - p_world).length()) * fur_height; vtips[j] = (vtips[j] + a * time_step) * damping; } } glutPostRedisplay(); } static void initGlutState(int argc, char * argv[]) { glutInit(&argc, argv); // initialize Glut based on cmd-line args glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); // RGBA pixel channels and double buffering glutInitWindowSize(window_width, window_height); // create a window glutCreateWindow("Assignment 9"); // title the window glutDisplayFunc(display); // display rendering callback glutReshapeFunc(reshape); // window reshape callback glutMotionFunc(motion); // mouse movement callback glutMouseFunc(mouse); // mouse click callback glutKeyboardFunc(keyboard); glutSpecialFunc(special_keyboard); glutIdleFunc(idle); } static void InitGLState() { glClearColor(128./255., 200./255., 255./255., 0.); glClearDepth(0.); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_PACK_ALIGNMENT, 1); glCullFace(GL_BACK); // glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_GREATER); glReadBuffer(GL_BACK); // set up texture safe_glActiveTexture(GL_TEXTURE0); int twidth, theight, maxcol; FILE * f = std::fopen("textures/shell.ppm", "r"); if (!f) { std::cerr << "Unable to open shell.ppm for reading. Exiting...\n"; exit(1); } std::fscanf(f, "P3 %d %d %d", &twidth, &theight, &maxcol); assert(maxcol == 255); char *pixdata = new char[twidth*theight*3]; for (int i = 0; i < twidth*theight; ++i) { int r, g, b; std::fscanf(f, "%d %d %d", &r, &g, &b); pixdata[3*i+0] = r; pixdata[3*i+1] = g; pixdata[3*i+2] = b; } glGenTextures(1, &h_texture_shells); glBindTexture(GL_TEXTURE_2D, h_texture_shells); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, twidth, theight, 0, GL_RGB, GL_UNSIGNED_BYTE, pixdata); delete [] pixdata; //second texture safe_glActiveTexture(GL_TEXTURE1); f = std::fopen("textures/fin.ppm", "r"); if (!f) { std::cerr << "Unable to open fin.ppm for reading. Exiting...\n"; exit(1); } std::fscanf(f, "P3 %d %d %d", &twidth, &theight, &maxcol); assert(maxcol == 255); pixdata = new char[twidth*theight*3]; for (int i = 0; i < twidth*theight; ++i) { int r, g, b; std::fscanf(f, "%d %d %d", &r, &g, &b); pixdata[3*i+0] = r; pixdata[3*i+1] = g; pixdata[3*i+2] = b; } glGenTextures(1, &h_texture_fins); glBindTexture(GL_TEXTURE_2D, h_texture_fins); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, twidth, theight, 0, GL_RGB, GL_UNSIGNED_BYTE, pixdata); delete [] pixdata; } int main(int argc, char * argv[]) { mesh.load("bunny.mesh");//"ico.vp"); // for tests you can use "ico.vp" which is a 20-triangle mesh init_normals(mesh); init_tips(); initGlutState(argc,argv); glewInit(); // load the OpenGL extensions if (!GLEW_VERSION_2_0) { // Check that our graphics card and driver support the necessary extensions if (glewGetExtension("GL_ARB_fragment_shader")!= GL_TRUE || glewGetExtension("GL_ARB_vertex_shader")!= GL_TRUE || glewGetExtension("GL_ARB_shader_objects") != GL_TRUE || glewGetExtension("GL_ARB_shading_language_100") != GL_TRUE) { std::cerr << "Error: card/driver does not support OpenGL Shading Language\n"; assert(0); } } InitGLState(); // this is our own ftion for setting some GL state for (std::size_t i = 0; i < SState.size(); ++i) { std::cerr << "Building shader: " << i << std::endl; const int shadeRet = ShaderInit(shader_file[i][0], shader_file[i][1], &SState[i].h_program_); if (!shadeRet) { std::cerr << "Error: could not build the shaders " << shader_file[i][0] << ", and " << shader_file[i][1] << ". Exiting...\n"; assert(0); } SState[i].h_uLight_ = safe_glGetUniformLocation(SState[i].h_program_, "uLight"); // Retrieve handles to variables in program SState[i].h_uProjMatrix_ = safe_glGetUniformLocation(SState[i].h_program_, "uProjMatrix"); SState[i].h_uModelViewMatrix_ = safe_glGetUniformLocation(SState[i].h_program_, "uModelViewMatrix"); SState[i].h_uNormalMatrix_ = safe_glGetUniformLocation(SState[i].h_program_, "uNormalMatrix"); SState[i].h_texUnit0_ = safe_glGetUniformLocation(SState[i].h_program_, "texUnit0"); SState[i].h_texUnit1_ = safe_glGetUniformLocation(SState[i].h_program_, "texUnit1"); SState[i].h_vtexCoord_ = safe_glGetAttribLocation(SState[i].h_program_, "vtexCoord"); SState[i].h_vTangent_ = safe_glGetAttribLocation(SState[i].h_program_, "vTangent"); SState[i].h_valpha_exponent_ = safe_glGetUniformLocation(SState[i].h_program_, "valpha_exponent"); SState[i].h_colorAmbient_ = safe_glGetAttribLocation(SState[i].h_program_, "colorAmbient"); SState[i].h_colorDiffuse_ = safe_glGetAttribLocation(SState[i].h_program_, "colorDiffuse"); } glutMainLoop(); // Pass control to glut to handle the main program loop return 0; }
[ "mcginnis.loren@gmail.com" ]
mcginnis.loren@gmail.com
7f9ff97159d49498e78e347ca62de708ea379932
7669a4f87d7322dd0fac42197d4684cb4a78891d
/STL_GraphicsEngine2/src/private/Mesh.cpp
0ca8243c5451a9bb772379734dc39afc8155adf1
[]
no_license
mingyu243/STL_GraphicsEngine2
0a96e0b7418809b59c8ba39e2883f3eae99c938c
695e6176954318efed857e85ab72f2339409080e
refs/heads/main
2023-03-18T16:40:21.144184
2021-03-08T08:10:48
2021-03-08T08:10:48
339,295,316
1
1
null
null
null
null
UHC
C++
false
false
1,638
cpp
#include "Mesh.h" Mesh::Mesh() : vertexBuffer(), indexBuffer(), inputLayout(), transform(), // transform(TransformBuffer())랑 같음. position(Vector3f::Zero), rotation(Vector3f::Zero), scale(Vector3f::One) { } Mesh::~Mesh() { } void Mesh::RenderBuffers(ID3D11DeviceContext* deviceContext) { BindBuffers(deviceContext); DrawBuffers(deviceContext); } void Mesh::BindBuffers(ID3D11DeviceContext* deviceContext) { vertexBuffer.Bind(deviceContext); indexBuffer.Bind(deviceContext); inputLayout.Bind(deviceContext); deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // 선을 그릴 때는 LineList. transform.Bind(deviceContext); } void Mesh::DrawBuffers(ID3D11DeviceContext* deviceContext) { // Draw //deviceContext->Draw(vertexCount, 0); // 이게 DrawCall이다. deviceContext->DrawIndexed(indexBuffer.Count(), 0, 0); // 인덱스 버퍼로 그리려면 이거 씀. } void Mesh::UpdateBuffers(ID3D11DeviceContext* deviceContext) { transform.transformMatrix = Matrix4f::Scale(scale) * Matrix4f::Rotation(rotation) * Matrix4f::Translation(position); } void Mesh::SetPosition(float x, float y, float z) { position = Vector3f(x, y, z); } void Mesh::SetPosition(Vector3f position) { this->position = position; } void Mesh::SetRotation(float x, float y, float z) { rotation = Vector3f(x, y, z); } void Mesh::SetRotation(Vector3f rotation) { this->rotation = rotation; } void Mesh::SetScale(float x, float y, float z) { scale = Vector3f(x, y, z); } void Mesh::SetScale(Vector3f scale) { this->scale = scale; }
[ "jmg6017@naver.com" ]
jmg6017@naver.com
f84ed1203294022f13c4015ac9cc4cb48fcecd0b
09840032043b360fae5175cbf2857bb09c74f4b9
/src/bam_job_xmsi.cpp
5ef91a16ea31fa07ac2d946175f5da59961cf705
[]
no_license
tschoonj/bam-quant
025c34e7a80afd0baf72e4cd910889dce8327253
84b332355c26b7d97f3feddd222ed0898af5ae2a
refs/heads/master
2021-01-22T08:19:33.135033
2015-10-05T15:16:57
2015-10-05T15:16:57
25,427,896
1
0
null
null
null
null
UTF-8
C++
false
false
9,263
cpp
#include "bam_job_xmsi.h" #include <iostream> #include <libxml/tree.h> #include <glibmm/module.h> #include <cstring> using namespace BAM; using namespace BAM::Job; bool XMSI::random_acquisition_started = false; void XMSI::Initialize() { xmi_init_hdf5(); //check number of threads if (options.omp_num_threads > xmi_omp_get_max_threads() || options.omp_num_threads < 1) { options.omp_num_threads = xmi_omp_get_max_threads(); } //check the hdf5 files if (!hdf5_file.empty()) hdf5_file_c = strdup(hdf5_file.c_str()); if (xmi_get_hdf5_data_file(&hdf5_file_c) == 0) { throw BAM::Exception("BAM::Job::XMSI::Initialize -> Error in xmi_get_hdf5_data_file"); } //get Fortran counterpart of input xmi_input_C2F(xmimsim_input->GetInternalPointer(), &inputFPtr); if (xmi_init_input(&inputFPtr) == 0) { throw BAM::Exception("BAM::Job::XMSI::Initialize -> Error in xmi_init_input"); } if (options.verbose) std::cout <<"Reading HDF5 datafile" << std::endl; //read from HDF5 file what needs to be read in if (xmi_init_from_hdf5(hdf5_file_c, inputFPtr, &hdf5FPtr, options) == 0) { throw BAM::Exception("Could not initialize from hdf5 data file"); } else if (options.verbose) std::cout << "HDF5 datafile "<< hdf5_file <<" successfully processed" << std::endl; xmi_update_input_from_hdf5(inputFPtr, hdf5FPtr); } void XMSI::Start() { /* * * 1) solid angle grid * 2) run the actual simulation * 3) apply detector response function * */ if (!random_acquisition_started) { throw BAM::Exception("BAM::Job::XMSI::Start -> Cannot start XMSI job before launching the random number acquisition"); } if (options.use_variance_reduction) { if (!xmimsim_hdf5_solid_angles.empty()) xmimsim_hdf5_solid_angles_c = strdup(xmimsim_hdf5_solid_angles.c_str()); if (xmi_get_solid_angle_file(&xmimsim_hdf5_solid_angles_c, 1) == 0) throw BAM::Exception("BAM::Job::XMSI::Start-> Error in xmi_get_solid_angle_file"); //check if solid angles are already precalculated if (options.verbose) std::cout << "Querying " << xmimsim_hdf5_solid_angles_c << " for solid angle grid" << std::endl; if (xmi_find_solid_angle_match(xmimsim_hdf5_solid_angles_c , xmimsim_input->GetInternalPointer(), &solid_angles, options) == 0) throw BAM::Exception("BAM::Job::XMSI::Start -> Error in xmi_find_solid_angle_match"); if (solid_angles == 0) { if (options.verbose) std::cout << "Precalculating solid angle grid" << std::endl; //doesn't exist yet //convert input to string char *xmi_input_string = 0; if (xmi_write_input_xml_to_string(&xmi_input_string, xmimsim_input->GetInternalPointer()) == 0) { throw BAM::Exception("BAM::Job::XMSI::Start -> Error in xmi_write_input_xml_to_string"); } xmi_solid_angle_calculation(inputFPtr, &solid_angles, xmi_input_string, options); //update hdf5 file if( xmi_update_solid_angle_hdf5_file(xmimsim_hdf5_solid_angles_c, solid_angles) == 0) throw BAM::Exception("BAM::Job::XMSI::Start -> Error in xmi_update_solid_angle_hdf5_file"); else if (options.verbose) std::cout << xmimsim_hdf5_solid_angles_c << " was successfully updated with new solid angle grid" << std::endl; xmlFree(xmi_input_string); } else if (options.verbose) std::cout << "Solid angle grid already present in " << xmimsim_hdf5_solid_angles_c << std::endl; } else if (options.verbose) std::cout << "Operating in brute-force mode: solid angle grid is redundant" << std::endl; if (options.verbose) std::cout << "Simulating interactions" << std::endl; double *channels; double **channels_conv; double *brute_history; double *var_red_history; double zero_sum; if (xmi_main_msim(inputFPtr, hdf5FPtr, 1, &channels, options, &brute_history, &var_red_history, solid_angles) == 0) { throw BAM::Exception("BAM::Job::XMSI::Start -> Error in xmi_main_msim"); } if (options.verbose) std::cout << "Interactions simulation finished" << std::endl; #define ARRAY3D_FORTRAN(array,i,j,k,Ni,Nj,Nk) (array[(Nj)*(Nk)*(i-1)+(Nk)*(j-1)+(k-1)]) //watch out, I'm doing something naughty here :-) #define ARRAY2D_FORTRAN(array,i,j,Ni,Nj) (array[(Nj)*(i)+(j)]) zero_sum = xmi_sum_double(channels, xmimsim_input->GetInternalPointer()->detector->nchannels); //convolute spectrum channels_conv = (double **) malloc(sizeof(double *)*(xmimsim_input->GetInternalPointer()->general->n_interactions_trajectory+1)); if (options.use_escape_peaks) { if (!xmimsim_hdf5_escape_ratios.empty()) xmimsim_hdf5_escape_ratios_c = strdup(xmimsim_hdf5_escape_ratios.c_str()); if (xmi_get_escape_ratios_file(&xmimsim_hdf5_escape_ratios_c, 1) == 0) throw BAM::Exception("BAM::Job::XMSI::Initialize -> Error in xmi_get_escape_ratios_file"); //check if escape ratios are already precalculated if (options.verbose) std::cout << "Querying " << xmimsim_hdf5_escape_ratios_c << " for escape ratios" << std::endl; if (xmi_find_escape_ratios_match(xmimsim_hdf5_escape_ratios_c , xmimsim_input->GetInternalPointer(), &escape_ratios, options) == 0) throw BAM::Exception("BAM::Job::XMSI::Initialize -> Error in xmi_find_escape_ratios_match"); if (escape_ratios == 0) { if (options.verbose) std::cout << "Precalculating escape peak ratios" << std::endl; //doesn't exist yet //convert input to string char *xmi_input_string = 0; if (xmi_write_input_xml_to_string(&xmi_input_string, xmimsim_input->GetInternalPointer()) == 0) { throw BAM::Exception("BAM::Job::XMSI::Initialize -> Error in xmi_write_input_xml_to_string"); } xmi_escape_ratios_calculation(xmimsim_input->GetInternalPointer(), &escape_ratios, xmi_input_string, hdf5_file_c, options, xmi_get_default_escape_ratios_options()); //update hdf5 file if(xmi_update_escape_ratios_hdf5_file(xmimsim_hdf5_escape_ratios_c , escape_ratios) == 0) throw BAM::Exception("BAM::Job::XMSI::Initialize -> Error in xmi_update_escape_ratios_hdf5_file"); else if (options.verbose) std::cout << xmimsim_hdf5_escape_ratios_c << " was successfully updated with new escape peak ratios" << std::endl; xmlFree(xmi_input_string); } else if (options.verbose) std::cout << "Escape peak ratios already present in " << xmimsim_hdf5_escape_ratios_c << std::endl; } else if (options.verbose) std::cout << "No escape peaks requested: escape peak calculation is redundant" << std::endl; double **channels_ptrs = (double **) malloc(sizeof(double *) * (xmimsim_input->GetInternalPointer()->general->n_interactions_trajectory+1)); for (int i = 0 ; i <= xmimsim_input->GetInternalPointer()->general->n_interactions_trajectory ; i++) channels_ptrs[i] = channels+i*xmimsim_input->GetInternalPointer()->detector->nchannels; if (options.custom_detector_response == NULL) xmi_detector_convolute_all(inputFPtr, channels_ptrs, channels_conv, options, escape_ratios, xmimsim_input->GetInternalPointer()->general->n_interactions_trajectory, zero_sum > 0.0 ? 1 : 0); else { XmiDetectorConvoluteAll xmi_detector_convolute_all_custom; if (!Glib::Module::get_supported()) { throw BAM::Exception("BAM::Job::XMSI::Start -> No module support on this platform: cannot use custom detector convolution routine"); } Glib::Module module(std::string(options.custom_detector_response)); if (!module) { throw BAM::Exception(std::string("BAM::Job::XMSI::Start -> Could not open ") + options.custom_detector_response + ": " + Glib::Module::get_last_error()); } if (!module.get_symbol("xmi_detector_convolute_all_custom", (void *&) xmi_detector_convolute_all_custom)) { throw BAM::Exception(std::string("Error retrieving xmi_detector_convolute_all_custom in ") + options.custom_detector_response + ": " + Glib::Module::get_last_error()); } else if (options.verbose) std::cout << "xmi_detector_convolute_all_custom loaded from " << options.custom_detector_response << std::endl; xmi_detector_convolute_all_custom(inputFPtr, channels_ptrs, channels_conv, options, escape_ratios, xmimsim_input->GetInternalPointer()->general->n_interactions_trajectory, zero_sum > 0.0 ? 1 : 0); } free(channels_ptrs); xmimsim_output = new BAM::File::XMSO(xmi_output_raw2struct(xmimsim_input->GetInternalPointer(), brute_history, options.use_variance_reduction == 1 ? var_red_history : NULL, channels_conv, channels, (char *) xmsi_filename.c_str(), zero_sum > 0.0 ? 1 : 0)); for (int i=(zero_sum > 0.0 ? 0 : 1) ; i <= xmimsim_input->GetInternalPointer()->general->n_interactions_trajectory ; i++) { xmi_deallocate(channels_conv[i] ); } free(channels_conv); xmi_deallocate(channels); xmi_deallocate(brute_history); if (options.use_variance_reduction) xmi_deallocate(var_red_history); }
[ "Tom.Schoonjans@bam.de" ]
Tom.Schoonjans@bam.de
57c81b1ec05699ee5f61dc3d1935ff4e54f609b2
3cd834cff8eb0994f66230835c8051bc92de30e1
/GL/Shader.cpp
21844719d007c8cf65bedfddda3daf27b971add5
[]
no_license
galapaegos/Legends
72d195ce2e9f00d828b3944b567184cdb8eea5c9
a335339d768ec96cfc03056805630d5bbb276008
refs/heads/master
2020-03-28T16:30:36.619506
2020-02-03T13:40:16
2020-02-03T13:40:16
148,702,776
0
0
null
null
null
null
UTF-8
C++
false
false
2,097
cpp
#include "stdafx.h" #include "Shader.h" #include <fstream> #include <sstream> std::string get_program_log(GLuint object) { GLint length = 0; glGetObjectParameterivARB(object, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length); CHECK_ERROR(); std::string log; if (length > 0) { GLcharARB *compile_log = new GLcharARB[length]; GLint characters_written = 0; glGetInfoLogARB(object, length, &characters_written, compile_log); CHECK_ERROR(); log = compile_log; delete[] compile_log; } return log; } Shader::Shader(const GLenum &type) : shader_type(type) { shader_file = ""; shader_id = 0; shader_compiled = false; } void Shader::load(const std::string &file) { shader_file = file; std::ifstream f(file); std::stringstream buffer; buffer << f.rdbuf(); shader_contents = buffer.str(); shader_compiled = false; } bool Shader::compile() { if (shader_id == 0) { shader_id = glCreateShader(shader_type); } if (shader_id && !shader_compiled) { const char *buffer = shader_contents.c_str(); glShaderSource(shader_id, 1, &buffer, nullptr); CHECK_ERROR(); glCompileShader(shader_id); CHECK_ERROR(); GLint success; glGetShaderiv(shader_id, GL_COMPILE_STATUS, &success); CHECK_ERROR(); std::string log = get_program_log(shader_id); if (success == GL_FALSE) { printf("shader_file:%s\ncompile log:\n%s", shader_file.c_str(), log.c_str()); return false; } else { printf("shader_file:%s\nwarnings:\n%s\n", shader_file.c_str(), log.c_str()); } } return true; } void Shader::release() { if (shader_id) { glDeleteShader(shader_id); CHECK_ERROR(); } } void Shader::attach(const GLuint &program) { if (shader_id == 0) { shader_id = glCreateShader(shader_type); CHECK_ERROR(); } if (program && shader_id) { glAttachShader(program, shader_id); CHECK_ERROR(); } } void Shader::detach(const GLuint &program) { if (program && shader_id) { glDetachShader(program, shader_id); CHECK_ERROR(); } } VertexShader::VertexShader() : Shader(GL_VERTEX_SHADER) { } FragmentShader::FragmentShader() : Shader(GL_FRAGMENT_SHADER) { }
[ "bhittle@osc.edu" ]
bhittle@osc.edu
668c5fcfa60d7de0e036ac58aeddc348b8cd9f3c
ad07c970ac13a2ca8356166daee05b1038ea1442
/ExplorerXP/FileViewer/AutoFont.h
ddb85d6ce56869da4ae2fe190dd23aa333eebd36
[ "Apache-2.0" ]
permissive
chunyou128/explorerxp
168cf93cd490c96564ad64ad6932cbec3948b492
c68bf161bb77bf5c9b3476be0e795d23bb0b6b5f
refs/heads/master
2022-12-31T08:17:29.844082
2020-10-26T23:35:53
2020-10-26T23:35:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,329
h
//CAutoFont class definition // //This class will simplify the creation and use of the CFont object //By Jamie Nordmeyer #ifndef AUTOFONT #define AUTOFONT class CAutoFont : public CFont { private: LOGFONT lf;//Stores this fonts LogFont for quick retrieval COLORREF fontColor; CString GetToken(CString& str, LPCTSTR c);//Used in Expand function HDC hDC; public: CAutoFont();//Default Constructor CAutoFont(CString facename);//Font name constructor CAutoFont(LOGFONT& logfont);//LogFont constructor CAutoFont(CFont font);//Constructs font based on existing font CAutoFont(CFont* pFont);//Constructs font based on existing font ~CAutoFont();//Destructor LONG SetHeight(LONG height); LONG SetHeightA(LONG height); LONG SetWidth(LONG width); LONG SetEscapement(LONG esc); LONG SetOrientation(LONG or); LONG SetWeight(LONG weight); BYTE SetCharset(BYTE charset); BYTE SetOutPrecision(BYTE op); BYTE SetClipPrecision(BYTE cp); BYTE SetQuality(BYTE qual); BYTE SetPitchAndFamily(BYTE paf); CString SetFaceName(CString facename); LPCTSTR SetFaceName(LPCTSTR facename); BOOL SetBold(BOOL B); BOOL SetItalic(BOOL i); BOOL SetUnderline(BOOL u); BOOL SetStrikeOut(BOOL s); void SetLogFont(LOGFONT& logfont); void SetFontColor(COLORREF color); void SetDC(HDC dc); LONG GetHeight(); LONG GetWidth(); LONG GetEscapement(); LONG GetOrientation(); LONG GetWeight(); BYTE GetCharset(); BYTE GetOutPrecision(); BYTE GetClipPrecision(); BYTE GetQuality(); BYTE GetPitchAndFamily(); LPCTSTR GetFaceName(); BOOL GetBold(); BOOL GetItalic(); BOOL GetUnderline(); BOOL GetStrikeOut(); COLORREF GetFontColor(); //GetLogFont is a member of CFont, and is used as normal. //These two functions are good for registry... CString ContractFont();//Places font info into single string void ExtractFont(CString& str);//Parses single string font info. //This function allows seamless use of the CFontDialog object //f: CFont or CAutoFont object to initialize the dlg with. //color: initial color shown in font color dialog //pPrinterDC: points to a printer DC if needed //pParentWnd: parent window of dialog, if needed // //The new font is returned through f, the new color through color void GetFontFromDialog(CFont *f=NULL, DWORD *color=0, CDC *pPrinterDC=NULL, CWnd *pParentWnd=NULL); }; #endif
[ "Nikolay Avrionov" ]
Nikolay Avrionov
faeb30d15d2c61cfd6b5d5d928695ae531455071
f795ba3bf8029161da05f5d632efb41c8c85f0c2
/Code/Chapter 3/Samples/Bluetooth_AT/Bluetooth_AT.ino
f46cbba13267f49ebe63ca83b18154e970249d0d
[]
no_license
hbr890627/IDEsign
ff509185762c06b57c1ed75c4fac28501a2e81bf
a5a18e2b57ae211bc0a2204df77584655b6d04bb
refs/heads/master
2022-04-14T01:48:26.615108
2020-03-28T09:49:48
2020-03-28T09:49:48
241,384,674
0
2
null
2020-02-23T19:20:03
2020-02-18T14:38:38
C++
UTF-8
C++
false
false
562
ino
#include <SoftwareSerial.h> // 引用程式庫 // 定義連接藍牙模組的序列埠 SoftwareSerial BTSerial(10,11); //RX TX void setup() { Serial.begin(9600); Serial.println("Enter AT commands"); BTSerial.begin(38400); //藍芽模組傳輸速度 } void loop() { // 若收到藍牙模組的資料,則送到「序列埠監控視窗」 if (BTSerial.available()){ Serial.write(BTSerial.read()); } // 若收到「序列埠監控視窗」的資料,則送到藍牙模組 if (Serial.available()){ BTSerial.write(Serial.read()); } }
[ "hbr890627@gmail.com" ]
hbr890627@gmail.com
d307121e0127ff2073dfcc2b23f1ce0dabd96ef8
66880b4c06bf662d058b1184642e9f052779ea9e
/external/vixl/test/test-fuzz-a64.cc
0a35e8652992a5b4e65c8ac410f305dc22a53549
[]
no_license
ParkHanbum/dex2ir
afa195163a048efa01c1cbd44c90ffd84565d053
a4cc0fe939146ca258c50a6b52b8fa09313f5eb4
refs/heads/master
2022-07-02T20:28:19.323269
2022-05-30T09:22:33
2022-05-30T09:22:33
247,693,944
51
16
null
null
null
null
UTF-8
C++
false
false
3,896
cc
// Copyright 2013, ARM Limited // 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 ARM Limited 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 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. #include <stdlib.h> #include "cctest.h" #include "a64/decoder-a64.h" #include "a64/disasm-a64.h" #define TEST(name) TEST_(FUZZ_##name) namespace vixl { TEST(decoder) { // Feed noise into the decoder to check that it doesn't crash. // 43 million = ~1% of the instruction space. static const int instruction_count = 43 * 1024 * 1024; uint16_t seed[3] = {1, 2, 3}; seed48(seed); Decoder decoder; Instruction buffer[kInstructionSize]; for (int i = 0; i < instruction_count; i++) { uint32_t instr = mrand48(); buffer->SetInstructionBits(instr); decoder.Decode(buffer); } } TEST(disasm) { // Feed noise into the disassembler to check that it doesn't crash. // 9 million = ~0.2% of the instruction space. static const int instruction_count = 9 * 1024 * 1024; uint16_t seed[3] = {42, 43, 44}; seed48(seed); Decoder decoder; Disassembler disasm; Instruction buffer[kInstructionSize]; decoder.AppendVisitor(&disasm); for (int i = 0; i < instruction_count; i++) { uint32_t instr = mrand48(); buffer->SetInstructionBits(instr); decoder.Decode(buffer); } } #if 0 // These tests are commented out as they take a long time to run, causing the // test script to timeout. After enabling them, they are best run individually // using cctest: // // cctest_sim FUZZ_decoder_pedantic // cctest_sim FUZZ_disasm_pedantic // // or cctest_sim_g for debug builds. TEST(decoder_pedantic) { // Test the entire instruction space. Decoder decoder; Instruction buffer[kInstructionSize]; for (uint64_t i = 0; i < (UINT64_C(1) << 32); i++) { if ((i & 0xffffff) == 0) { fprintf(stderr, "0x%08" PRIx32 "\n", static_cast<uint32_t>(i)); } buffer->SetInstructionBits(static_cast<uint32_t>(i)); decoder.Decode(buffer); } } TEST(disasm_pedantic) { // Test the entire instruction space. Warning: takes about 30 minutes on a // high-end CPU. Decoder decoder; PrintDisassembler disasm(stdout); Instruction buffer[kInstructionSize]; decoder.AppendVisitor(&disasm); for (uint64_t i = 0; i < (UINT64_C(1) << 32); i++) { if ((i & 0xffff) == 0) { fprintf(stderr, "0x%08" PRIx32 "\n", static_cast<uint32_t>(i)); } buffer->SetInstructionBits(static_cast<uint32_t>(i)); decoder.Decode(buffer); } } #endif } // namespace vixl
[ "kese111@gmail.com" ]
kese111@gmail.com
06e0aebc9cca49f96e3a6b49f1215dbc3882859d
17387a1fe1f117b381e27907b41b219dc452aad7
/Code/Nicolina/Beta Jian/Codename Jian/Jian/OptionsState.cpp
240584bb843e901e7c11bd7facc8f10fbe370832
[]
no_license
Picopic/Possession
d818c7337fb378d5989b35f3dac03f95bf8afe17
57654a4772e484bdde38d59a8c81c3c12bad9e3b
refs/heads/master
2021-01-20T05:49:42.461662
2015-03-05T15:51:20
2015-03-05T15:51:20
16,170,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
//OptionsState.cpp //You can choose to enter "Options" from the StartMenuState. //You can only go back to StartMenuState from here. #include "stdafx.h" #include "OptionsState.h" using namespace sf; OptionsState::OptionsState(sf::RenderWindow* OptionWindow){ m_window = OptionWindow; } OptionsState::~OptionsState(){ } bool OptionsState::Initialize(){ m_done = false; return false; } bool OptionsState::Enter(){ std::cout << "Welcome to the OptionsState" << std::endl; std::cout << "Press 4 to go back to StartMenuState" <<std::endl; return false; } bool OptionsState::Exit(){ return false; } bool OptionsState::Update(){ m_done = false; if(Keyboard::isKeyPressed(Keyboard::Num4)) { m_next_state = "StartMenuState"; m_done=true; }; return m_done; } std::string OptionsState::Next(){ return m_next_state; } bool OptionsState::IsType(const std::string& Type){ return Type == "OptionsState"; } bool OptionsState::Draw(){ m_window->clear(Color(0x99, 0xff, 0x55, 0xff)); m_window->display(); return false; }
[ "pico@live.se" ]
pico@live.se
44d456d1dd318f079a51b077c270e2371c799bac
5bd3fa92c0ef7bd03334422dc36d615167fe553d
/Day Code/Day 03 - Character Arrays/Character Arrays.cpp
b92333209dc68f033228b5f7616b75a5970709fc
[]
no_license
Bl00per/AIE-Programming
c42c5766dc81a8d99abe636a8444068ab76ac2fa
1e0fbee6ccc958c3bb56917aa685866548baf04c
refs/heads/master
2020-05-01T13:07:09.278007
2019-08-21T05:17:54
2019-08-21T05:17:54
177,482,113
1
0
null
null
null
null
UTF-8
C++
false
false
643
cpp
#include <iostream> #define _CRT_SECURE_NO_WARNINGS int main() { //const char* char name[] = "Will"; char large_buffer[64] = "Will"; std::cout << strlen(name) << "\n"; char surname[] = "Hart"; int compare = strcmp(name, surname); //-1 lhs first alphabetically std::cout << compare << "\n"; compare = strcmp(surname, name); // 1 rhs first alphabetically std::cout << compare << "\n"; compare = strcmp(name, name); // 0 the same std::cout << compare << "\n"; char buffer[256] = "abcdefghijklmnopqrstuvwxyz"; strcpy(buffer, name); // oNly copies over till source null strcat(buffer, surname); system("Pause"); return 0; }
[ "clouduniversemc@gmail.com" ]
clouduniversemc@gmail.com
dcf2acd767b25973abbfe6934c89114a172b3f18
c55fcfa188d079ebd2200e53335a9a8e88160f38
/serial_from_arduino/serial_from_arduino.ino
c0f405743accf9f2056b032c4b1e9a6c33fed9ba
[]
no_license
AlbertoBoem/Serial_Arduino-to-Pd
c80e40ebc52f797519b59c0b39c23dd8cbfd5c33
c58420c5328090960fdd07dfb79f0d0d5dd22b5a
refs/heads/master
2020-04-15T02:18:17.352833
2015-04-28T09:45:38
2015-04-28T09:45:38
34,334,435
0
0
null
null
null
null
UTF-8
C++
false
false
3,042
ino
//On Off state led int ledCheck = 6; //Output LED int led1_pin = 8; int led2_pin = 9; int led3_pin = 10; int led4_pin = 11; int brightnessLed = 0; int fadeAmount = 5; //Pushbutton const int button_pin = 26; //24 int buttonState = 0; // variable for reading the pushbutton status int buttonCounter = 0; int lastButtonState = 0; //Reading Sensors int sensorPin1 = A0; //LDR 1 int sensorPin2 = A1; //LDR 2 int sensorPin3 = A2; //LDR 3 int sensorPin4 = A3; //LDR 4 int sensorPin5 = A4; //LDR 5 int sensorPin6 = A5; //LDR 6 //LED int ledPin1 = 40; //LED 1 int ledPin2 = 38; //LED 2 int ledPin3 = 36; //LED 3 int ledPin4 = 34; //LED 4 int ledPin5 = 32; //LED 5 int ledPin6 = 30; //LED 6 //Distance values int sensorValueA = 0; int sensorValueB = 0; int sensorValueC = 0; int sensorValueD = 0; int sensorValueE = 0; int sensorValueF = 0; //*************************************************************************************** void setup() { Serial.begin(9600); //19200 //On Off led state pinMode(ledCheck, OUTPUT); } //*************************************************************************************** void loop() { startDistanceSensors(); //turn led on and read data from the ldr printData(); //print data on the serial port delay(10); } //*************************************************************************************** void startDistanceSensors() { // turn led on digitalWrite(ledPin1, HIGH); digitalWrite(ledPin2, HIGH); digitalWrite(ledPin3, HIGH); digitalWrite(ledPin4, HIGH); digitalWrite(ledPin5, HIGH); digitalWrite(ledPin6, HIGH); // read the value from the sensor: sensorValueA = analogRead(sensorPin1); sensorValueB = analogRead(sensorPin2); sensorValueC = analogRead(sensorPin3); sensorValueD = analogRead(sensorPin4); sensorValueE = analogRead(sensorPin5); sensorValueF = analogRead(sensorPin6); } //*************************************************************************************** void printData() { //Serial print to pd Serial.print(F("A ")); //Values //Distance sensors Serial.print(sensorValueA, DEC); //Distance sensors Serial.print(F(" ")); Serial.print(sensorValueB, DEC); Serial.print(F(" ")); Serial.print(sensorValueC, DEC); Serial.print(F(" ")); Serial.print(sensorValueD, DEC); Serial.print(F(" ")); Serial.print(sensorValueE, DEC); Serial.print(F(" ")); Serial.print(sensorValueF, DEC); Serial.print(F(" ")); Serial.println(); } //*************************************************************************************** /* Mapping of the distance sensors (ldr + led) SensorValue A = sensorPin1 + ledPin5 SensorValue B = sensorPin2 + ledPin2 SensorValue C = sensorPin3 + ledPin6 SensorValue D = sensorPin4 + ledPin3 SensorValue E = sensorPin5 + ledPin1 SensorValue F = sensorPin6 + ledPin4 */ //***********************
[ "boem.alberto@gmail.com" ]
boem.alberto@gmail.com
0adb1ed69563f1562acbad5a0b81a875a077726e
d51caae88cbc18e3497ff5855e1332b36f5b839f
/ACO/HardConstraint.cpp
581d09d18b6f78d871b8ca06bb09807aea5f9563
[]
no_license
HonzoBonzo/NurseSchedulingBackend
d04cc556379a656b5f7bc60af734ed4d39661a6e
c497340847d69a52a9aadb1a521dcceb202f0203
refs/heads/master
2021-01-23T00:25:35.135922
2017-04-14T11:22:04
2017-04-14T11:30:32
85,731,055
0
1
null
2017-04-14T11:30:33
2017-03-21T17:09:01
null
UTF-8
C++
false
false
4,575
cpp
#include <iostream> #include "HardConstraint.h" bool HardConstraint::daily_demand_for_shifts(int employee) { return true; } // 1. Cover needs to be fulfilled (i.e. no shifts must be left unassigned). bool HardConstraint::cover_fulfilled(int employee) { char *ptr = &_solution[employee][0], *tmp; return true; } // 2. For each day a nurse may start only one shift. bool HardConstraint::only_one_shift_per_day(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0; for (int d = 0; d < _no_days; ++d) { tmp = &ptr[_d_j(d)]; s = tmp[EARLY] + tmp[DAY] + tmp[LATE] + tmp[NIGHT] + tmp[REST]; if (s != 1) return false; } return true; } // 3. Within a scheduling period a nurse is allowed to exceed the numer of hours // for which they are available for their department by at most 4 hours. bool HardConstraint::exceed_hours(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0, sd = 0, sn = 0, k; int e36 = _no_weeks * 36, e32 = _no_weeks * 32, e20 = _no_weeks * 20; if (_no_weeks > 0) { for (int d = 0; d < _no_days; ++d) { k = _es_j(d); sd += ptr[k + EARLY] + ptr[k + DAY] + ptr[k + LATE]; sn += ptr[k + NIGHT]; } s = 9 * sd + 8 * sn; if (employee < 12) return (e36 <= s && s <= (e36 + 4)); else if (employee == 12) return (e32 <= s && s <= (e32 + 4)); else return (e20 <= s && s <= (e20 + 4)); } return true; } // 4. The maximum numer of night shifts is 3 per period of 5 consecutive weeks. bool HardConstraint::maximum_number_of_nights(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0; for (int d = 0; d < _no_days; ++d) s += ptr[_ns_j(d)]; if (s > 3) return false; return true; } // 5. A nurse must receive at least 2 weekends off duty per 5 week period. // A weekend off duty lasts 60 hours including Saturday 00:00 to Monday 04 : 00. bool HardConstraint::weekends_off(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0; for (int sat = 0; sat < _no_weeks; ++sat) { tmp = &ptr[_sat_j(sat)]; s += tmp[REST] + tmp[5 + REST]; } if (s < 4) return false; // 2 weekends * 2 rest return true; } // 6. Following a series of at least 2 consecutive night shifts a 42 hours rest is required. bool HardConstraint::rest_hours_after_nights(int employee) { char *ptr = &_solution[employee][0], *tmp; int sn = 0, sr = 0; for (int d = 0; d < _no_days; ++d) { sn = ptr[_ns_j(d)] + ptr[_ns_j((d + 1) % _max_no_days)]; sr = ptr[_rs_j((d + 2) % _max_no_days)] + ptr[_rs_j((d + 3) % _max_no_days)]; if (sn == 2 && sr != 2) return false; } return true; } // 7. During any period of 24 consecutive hours, at least 11 hours of rest is required. bool HardConstraint::rest_hours_in_any_consecutive_24_period(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0, k1, k2; for (int d = 0; d < _no_days; ++d) { k1 = _es_j(d); k2 = _es_j((d + 1) % _max_no_days); s += (ptr[k1 + LATE] == 1 && ptr[k2 + EARLY] == 1) + (ptr[k1 + LATE] == 1 && ptr[k2 + DAY] == 1) + (ptr[k1 + NIGHT] == 1 && ptr[k2 + EARLY] == 1) + (ptr[k1 + NIGHT] == 1 && ptr[k2 + DAY] == 1) + (ptr[k1 + NIGHT] == 1 && ptr[k2 + LATE] == 1); } if (s > 0) return false; return true; } // 8. A night shift has to be followed by at least 14 hours rest. An exception // is that once in a period of 21 days for 24 consecutive hours, the resting // time may be reduced to 8 hours. bool HardConstraint::rest_hours_following_night(int employee) { char *ptr = &_solution[employee][0], *tmp; return true; } // 9. The numer of consecutive night shifts is at most 3. bool HardConstraint::consecutive_nights(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0; for (int d = 0; d < _no_days; ++d) { s = ptr[_ns_j(d)] + ptr[_ns_j((d + 1) % _max_no_days)] + ptr[_ns_j((d + 2) % _max_no_days)] + ptr[_ns_j((d + 3) % _max_no_days)]; if (s > 3) return false; } return true; } // 10. The numer of consecutive shifts (workdays) is at most 6. bool HardConstraint::consecutive_shifts(int employee) { char *ptr = &_solution[employee][0], *tmp; int s = 0; for (int d = 0; d < _no_days; ++d) { s = ptr[_rs_j(d)] + ptr[_rs_j((d + 1) % _max_no_days)] + ptr[_rs_j((d + 2) % _max_no_days)] + ptr[_rs_j((d + 3) % _max_no_days)] + ptr[_rs_j((d + 4) % _max_no_days)] + ptr[_rs_j((d + 5) % _max_no_days)]; if (s == 0) return false; } return true; }
[ "konradb12@gmail.com" ]
konradb12@gmail.com
1e375cdca60ae84ede0ae95d1af27fb31c348931
78c6e3d6e544f0fa497cde1915c7286c8592e585
/VSIM/GUI/notdone.cxx
bb997c169d4ee96f08ab74082bdcdbb136a22647
[ "Apache-2.0" ]
permissive
sbednarz/chemical-kinetics-simulator
c73ecefb5905ee8268a12cac4b947643ea34717b
4f032d2b38dfd0de1178a18051c9bc7c009ffcc5
refs/heads/master
2021-01-21T13:21:12.027644
2016-05-13T18:38:47
2016-05-13T18:38:47
46,676,615
6
2
null
null
null
null
UTF-8
C++
false
false
1,065
cxx
// ---------------------------------------------------------------------------- // // Copyright (C) 1996, 1998, 2012 International Business Machines Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- #include "vsim.hxx" void UnderConstruction() { MessBox( NULL, WB_OK, String( "Under Construction"), String( "This feature is not yet implemented" ) ).Execute(); }
[ "hnsbrg@gmail.com" ]
hnsbrg@gmail.com
234e645433a290cd3374342840dc7d2831b8ffce
46b07f014b9d1f0047dc0591fe116caee3c1810f
/c++22/obsidade morbida.cpp
ace723e858bcc1831f7ee058b29b94c91a5353b6
[]
no_license
Lucasraupp/C_MAIS_MAIS
ab706f8aacef8022ff1099e29f26968d3447bbb5
37c38b2bd504087e003f29628d3b673361ce74ce
refs/heads/master
2021-01-17T23:00:06.764156
2016-06-08T11:54:55
2016-06-08T11:54:55
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
986
cpp
#include<math.h> #include<iostream.h> #include<conio.h> #include<dos.h> /*Exercício 7 – Faça um Um programa que calcule e mostre o imc do usuário e uma das seguintes informações de acordo com o que segue: Abaixo de 17 -> Muito abaixo do peso Entre 17 e 18,49 -> Abaixo do peso Entre 18,5 e 24,99 -> Peso Normal Entre 25 e 29,99 -> Acima do peso Entre 30 e 34,99 -> Obesidade I Entre 35 e 39,99 -> Obesidade II (severa) Acima 40 -> Obesidade III (mórbida) */ void main() { float altura, imc; int peso; cout<<"\nDigite sua altura\t"; cin>>altura; cout<<"\nDigite seu peso\t"; cin>>peso; imc=(peso/pow(altura,2)); if (imc<17){ cout<<"Muito abaixo do peso!!"; } else { if (imc<18.5) { cout<<"Abaixo do peso"; } else { if (imc<25){ cout<<"Peso normal"; } else { if (imc<30){ cout<<"Acima do peso"; } else { if (imc<35){ cout<<"Obsidade II(Severa)"; } else { cout<<"Obesidade III (mórbida)"; } } } } } getch(); }
[ "joao.moreira@qi.edu.br" ]
joao.moreira@qi.edu.br
cb0c1029f1876cfddf1f40627fda36180542b63e
579482e8e0843ca832cbf2907d8c6e34ed6bd87d
/avsys2012/week8_simpleStepSeqMod/src/testApp.cpp
252e4fea894592bd6d29c89f5178dace588a8909
[]
no_license
firmread/avsys2013
46fd5f2ed9c5053cc1f7aa5415b1feee59aa0f9e
1d079cc9a8164b7ac1fa4a8e3112f4c986c59214
refs/heads/master
2020-05-20T09:31:24.633510
2013-04-16T13:49:15
2013-04-16T13:49:15
8,830,629
1
0
null
null
null
null
UTF-8
C++
false
false
4,734
cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSoundStreamSetup(2,0,this, 44100, 512, 4); ofSetColor(255, 255, 255); ofSetFrameRate(60); //set up the notes for(int i=0;i<24;i++){ notePlayer[23-i].setup(); notePlayer[23-i].setVolume(1.0); notePlayer[23-i].setFrequency(midi.getFreqForNote(48+i)); } resetSequencer(); setBPM(220); } //-------------------------------------------------------------- void testApp::setBPM(int targetBPM){ bpmInt = targetBPM; bpm = 60.0f / bpmInt; //60 seconds in a minute / 120 beats per second noteLength = bpm; // have notes play for 100% of the bpm time. } //-------------------------------------------------------------- void testApp::resetSequencer(){ for(int x=0;x<32;x++) { for(int y=0;y<24;y++){ notes[x][y]=false; notesAlt[x][y]=false; } } lastNoteStartTime = ofGetElapsedTimef(); sequencerPosition = 0; movedThisFrame=0; } //-------------------------------------------------------------- void testApp::update(){ if(ofGetElapsedTimef() > lastNoteStartTime + bpm) { sequencerPosition++; lastNoteStartTime = ofGetElapsedTimef(); if(sequencerPosition == ofGetWidth()/32) sequencerPosition = 0; movedThisFrame=0; } } //-------------------------------------------------------------- void testApp::draw(){ //draw the sequencer playbar ofSetColor(255, 0, 0); ofRect(sequencerPosition*32, 0, 32, ofGetHeight()); //draw the sequencer notes for(int x=0;x<32;x++) { for(int y=0;y<24;y++) { ofSetColor(0,0,0); if(notes[x][y]) ofRect(x*32, y*32, 32, 32); ofSetColor(0,255,0); if(notesAlt[x][y]) //draw the alt notes ofRect(x*32+10, y*32+10, 12, 12); } } ofSetColor(0, 0, 255); ofDrawBitmapString("bpm = "+ofToString(bpmInt), 10, 10); ofDrawBitmapString("press a/z to modify", 10, 25); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key=='a') bpmInt+=10; else if(key == 'z') bpmInt-=10; setBPM(bpmInt); if(key=='x') resetSequencer(); } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ if(button == 0) notes[x/32][y/32] = setVal; else notesAlt[x/32][y/32] = setVal; } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ if(button == 0){ // if left mouse click, set a up moving note setVal = !notes[x/32][y/32]; notes[x/32][y/32] = setVal; }else { //if right mouse click, set a down moving note setVal = !notesAlt[x/32][y/32]; notesAlt[x/32][y/32] = setVal; } } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } void testApp::audioRequested(float * output, int bufferSize, int nChannels){ int column = sequencerPosition; // store this in case it changes while this function is running int notesPlayed = 0; for (int i = 0; i < bufferSize; i++){ output[i*nChannels ] = 0; output[i*nChannels + 1] = 0; } if(ofGetElapsedTimef() < lastNoteStartTime + noteLength) //move notes up { for(int y=0; y<24; y++){ if(notes[column][y]){ notePlayer[y].addToSoundBuffer(output, bufferSize); notesPlayed++; if(movedThisFrame<2){ notes[column][y] = false; if(y>0) notes[column][y-1] = true; else notes[column][23] = true; } } } for(int y=24; y>=0; y--){ // go through backwards, move notes down. we have to loop through backwards because otherwise, we'll move a note down, and then check the same note we just moved next frame and move it down again, instantly moving all notes to the bottom if(notesAlt[column][y]){ notePlayer[y].addToSoundBuffer(output, bufferSize); notesPlayed++; if(movedThisFrame<2){ notesAlt[column][y] = false; if(y!=23) notesAlt[column][y+1] = true; else notesAlt[column][0] = true; } } } } movedThisFrame++; notesPlayed = MAX(notesPlayed, 4); // if we have less than 4 things playing at once, we'll notice the volume shift too clearly for (int i = 0; i < bufferSize; i++){ // avgerage all the inputs so the sound never goes over 1.0 output[i*nChannels ] /= notesPlayed; output[i*nChannels + 1] /= notesPlayed; } }
[ "litchirhythm@gmail.com" ]
litchirhythm@gmail.com
fbb98a0ee9320d86cb146040bdd923087f5b7f9c
0252ba61fad7be288984461c68bdcab65ffdabf8
/LAB3/Lab3/Lab3/Lab3/main.cpp
20a56fbe3a2bed43b128957f3c6080e91e68563c
[]
no_license
GuanYuankai/CSCI---6555
6e94609385ad64e0d2f749721d07503fb08f7c73
d0035544a7e50b2d833bc4ceaa6fc36e69df3b25
refs/heads/master
2020-03-29T23:08:17.798044
2018-12-18T22:31:25
2018-12-18T22:31:25
150,457,920
0
0
null
null
null
null
UTF-8
C++
false
false
7,832
cpp
#include <iostream> #include <fstream> #include <math.h> #include <cmath> #include <cstring> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/ext.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/string_cast.hpp> #include "shader.h" #include "LoadModel.h" #include "BindBuffer.hpp" #include "PhysicalEngine.hpp" using namespace std; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); void processInput(GLFWwindow *window); const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; float lookat_Y = 20.0f; float lookat_X = 40.0f; float lookat_Z = 40.0f; int main() { string off = "ball.off"; Model ball1 = LoadModel(off); Model ball2 = LoadModel(off); Model ball3 = LoadModel(off); string off_plane = "plane.off"; Model plane = LoadModel(off_plane); glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LAB3", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glEnable(GL_DEPTH_TEST); Shader ourShader("shader.vs", "shader.fs"); Shader ourShader_Plane("shader_plane.vs", "shader_plane.fs"); BufferObj ball1_buffer; ball1_buffer = BindBuffer(ball1); BufferObj ball2_buffer; ball2_buffer = BindBuffer(ball2); BufferObj ball3_buffer; ball3_buffer = BindBuffer(ball3); BufferObj plane_buffer; plane_buffer = BindBuffer(plane); glm::mat4 view = glm::mat4(1.0f); view = glm::lookAt(glm::vec3(lookat_X, lookat_Y, lookat_Z), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 projection; projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH/(float)SCR_HEIGHT, 0.1f, 100.0f); ball1.velocity = glm::vec3(5.0f, 0.0f, 3.0f); ball2.velocity = glm::vec3(-5.0f, 0.0f, 3.0f); ball3.velocity = glm::vec3(0.0f, 0.0f, 10.0f); glm::mat4 trans = glm::mat4(1.0f); ball1.position= glm::vec3(-10.0f, 5.0f, 5.0f); ball2.position= glm::vec3(10.0f,5.0f, 5.0f); ball3.position= glm::vec3(3.0f,5.0f, 5.0f); glfwSetKeyCallback(window, key_callback); while (!glfwWindowShouldClose(window)) { processInput(window); ourShader.use(); glm::mat4 view = glm::mat4(1.0f); view = glm::lookAt(glm::vec3(lookat_X, lookat_Y, lookat_Z), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); int viewLoc = glad_glGetUniformLocation(ourShader.ID, "view"); glad_glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); int projLoc = glad_glGetUniformLocation(ourShader.ID, "projection"); glad_glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); int transLoc = glad_glGetUniformLocation(ourShader.ID, "trans"); ourShader_Plane.use(); int viewLoc_Plane = glad_glGetUniformLocation(ourShader_Plane.ID, "view"); glad_glUniformMatrix4fv(viewLoc_Plane, 1, GL_FALSE, glm::value_ptr(view)); int projLoc_Plane = glad_glGetUniformLocation(ourShader_Plane.ID, "projection"); glad_glUniformMatrix4fv(projLoc_Plane, 1, GL_FALSE, glm::value_ptr(projection)); int transLoc_Plane = glad_glGetUniformLocation(ourShader_Plane.ID, "trans"); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ourShader.use(); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glm::vec3 accelerate = glm::vec3(0.0f); float time = 0.02f; ball1 = Accelerate(ball1, accelerate, time); ball1 = Velocity(ball1, time); trans[3] = glm::vec4(ball1.position, 1.0f); glBindVertexArray(ball1_buffer.VAO); glad_glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(trans)); glDrawElements(GL_TRIANGLES, ball1.numberIndice * 3, GL_UNSIGNED_INT, 0); ball1 = Boundarybounce(ball1); ball2 = Accelerate(ball2, accelerate, time); ball2 = Velocity(ball2, time); trans[3] = glm::vec4(ball2.position, 1.0f); glBindVertexArray(ball2_buffer.VAO); glad_glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(trans)); glDrawElements(GL_TRIANGLES, ball2.numberIndice * 3, GL_UNSIGNED_INT, 0); ball2 = Boundarybounce(ball2); ball3 = Accelerate(ball3, accelerate, time); ball3 = Velocity(ball3, time); trans[3] = glm::vec4(ball3.position, 1.0f); glBindVertexArray(ball3_buffer.VAO); glad_glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(trans)); glDrawElements(GL_TRIANGLES, ball2.numberIndice * 3, GL_UNSIGNED_INT, 0); ball3 = Boundarybounce(ball3); Collision(ball1, ball2); Collision(ball1, ball3); Collision(ball3, ball2); ourShader_Plane.use(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glm::mat4 plane_tranc = glm::mat4(1.0f); glBindVertexArray(plane_buffer.VAO); glad_glUniformMatrix4fv(transLoc_Plane, 1, GL_FALSE, glm::value_ptr(plane_tranc)); glDrawElements(GL_TRIANGLES, plane.numberIndice * 3, GL_UNSIGNED_INT, 0); cout << "position:" << glm::to_string(ball1.position) << endl; glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &plane_buffer.VAO); glDeleteBuffers(1, &plane_buffer.VBO); glDeleteBuffers(1, &plane_buffer.EBO); glDeleteVertexArrays(1, &ball1_buffer.VAO); glDeleteBuffers(1, &ball1_buffer.VBO); glDeleteBuffers(1, &ball1_buffer.EBO); glDeleteVertexArrays(1, &ball2_buffer.VAO); glDeleteBuffers(1, &ball2_buffer.VBO); glDeleteBuffers(1, &ball2_buffer.EBO); glDeleteVertexArrays(1, &ball3_buffer.VAO); glDeleteBuffers(1, &ball3_buffer.VBO); glDeleteBuffers(1, &ball3_buffer.EBO); glfwTerminate(); return 0; } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_UP && action == GLFW_PRESS) lookat_Y += 1.0f; if (key == GLFW_KEY_DOWN && action == GLFW_PRESS) lookat_Y -= 1.0f; if (key == GLFW_KEY_A && action == GLFW_PRESS) lookat_X -= 1.0f; if (key == GLFW_KEY_D && action == GLFW_PRESS) lookat_X += 1.0f; if (key == GLFW_KEY_S && action == GLFW_PRESS) lookat_Z += 1.0f; if (key == GLFW_KEY_W && action == GLFW_PRESS) lookat_Z += 1.0f; }
[ "35901736+GuanYuankai@users.noreply.github.com" ]
35901736+GuanYuankai@users.noreply.github.com
6dab51991577b6bb3be833521998a20512909bda
4fcf2967da46f37c831b72b7b97f705d3364306d
/problems/acmicpc_1420.cpp
c4bf31d61b5654fb9b1c230ac02f56a0248be2be
[ "MIT" ]
permissive
qawbecrdtey/BOJ-sol
e2be11e60c3c19e88439665d586cb69234f2e5db
249b988225a8b4f52d27c5f526d7c8d3f4de557c
refs/heads/master
2023-08-03T15:04:50.837332
2023-07-30T08:25:58
2023-07-30T08:25:58
205,078,469
0
0
null
null
null
null
UTF-8
C++
false
false
3,063
cpp
#include <algorithm> #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; class flow { class vertex; class edge { public: vertex const *from; vertex const *to; private: int capacity; edge *reverse; edge(vertex const *from, vertex const *to, int capacity) : from(from), to(to), capacity(capacity), reverse(nullptr) {} public: static pair<edge*, edge*> make_edge(vertex const *from, vertex const *to) { auto forward = new edge(from, to, 1); auto reverse = new edge(to, from, 0); forward->reverse = reverse; reverse->reverse = forward; return { forward, reverse }; } void fill(int f) { capacity -= f; reverse->capacity += f; } [[nodiscard]] bool full() const { return !capacity; } [[nodiscard]] int size() const { return capacity; } }; class vertex { public: vector<edge*> edges; void add_edge(vertex *to) { auto [forward, reverse] = edge::make_edge(this, to); edges.push_back(forward); to->edges.push_back(reverse); } }; int source, sink; int vertex_cnt; vertex *vertices; public: flow(int vertex_cnt, int source, int sink, vector<pair<int, int>> const &edges) : source((source << 1) | 1), sink(sink << 1), vertex_cnt(vertex_cnt << 1), vertices(new vertex[vertex_cnt << 1]()) { // -> 2k -> 2k+1 -> for(int i = 0; i < vertex_cnt; i++) { vertices[i << 1].add_edge(&vertices[(i << 1) | 1]); } for(auto [f, t] : edges) { if(f != sink && t != source) vertices[(f << 1) | 1].add_edge(&vertices[t << 1]); if(f != source && t != sink) vertices[(t << 1) | 1].add_edge(&vertices[f << 1]); } } int find_path() { struct info { int now; edge *in_edge; int in_flow; }; vector<edge*> visited(vertex_cnt); queue<info> q; q.push({ source, nullptr, 2 }); while(!q.empty()) { auto [now, in_edge, in_flow] = q.front(); q.pop(); if(visited[now]) continue; visited[now] = in_edge; if(now == sink) { while(in_edge) { in_edge->fill(in_flow); in_edge = visited[in_edge->from - vertices]; } return in_flow; } for(auto e : vertices[now].edges) { auto const next = (int)(e->to - vertices); if(next == source || visited[next] || e->full()) continue; q.push({ next, e, min(in_flow, e->size()) }); } } return 0; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n, m; cin >> n >> m; auto a = new string[n]; int source, sink; vector<pair<int, int>> edges; for(int i = 0; i < n; i++) { cin >> a[i]; for(int j = 0; j < m; j++) { if(a[i][j] == '#') continue; if(a[i][j] == 'K') source = i * m + j; else if(a[i][j] == 'H') sink = i * m + j; if(i && a[i - 1][j] != '#') edges.emplace_back(((i - 1) * m + j), (i * m + j)); if(j && a[i][j - 1] != '#') edges.emplace_back((i * m + j - 1), (i * m + j)); } } if(abs(source / m - sink / m) + abs(source % m - sink % m) == 1) { cout << -1; return 0; } flow F(n * m, source, sink, edges); int total_flow = 0, f; while((f = F.find_path())) total_flow += f; cout << total_flow; }
[ "qawbecrdtey@naver.com" ]
qawbecrdtey@naver.com
40fe530cc97615cdf424f3a8bc07e1d8ca33bfeb
1e58f86db88d590ce63110c885c52305d67f8136
/GlobalData/configtreeobject_Network.cpp
13c16db9f7313f7984a2abde8797ff7929073e5a
[]
no_license
urielyan/F270
32a9b87780b6b0bbbd8e072ca4305cd38dc975c1
c3d1eceead895ded12166eeb6748df111f46ef2d
refs/heads/master
2021-01-10T02:06:40.335370
2016-03-02T03:23:02
2016-03-02T03:23:02
52,927,128
1
1
null
null
null
null
UTF-8
C++
false
false
66,183
cpp
#include "configtreeobject_Network.h" #include "cfgchannel.h" #include "../Common/winnetworkconfig.h" #include "../Common/xmlconfigparser.h" #include "cfgGlobalDef.h" #include "Common/devboard.h" #include "cfgconfig_network.h" ConfigTreeObject_Network *ConfigTreeObject_Network::instance(QObject *parent) { static ConfigTreeObject_Network data(parent); return &data; } ConfigTreeObject_Network::ConfigTreeObject_Network(QObject *parent): ConfigObject(parent) { //Network settings代理树 QFile fileDelegate(":/configtree/Image/configTree/Network/Network_SettingDelegate/delegate.xml"); if(!fileDelegate.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file: Network_setting!"; }else{ XmlConfigParser::parseConfigXml(fileDelegate, static_cast<ConfigObject*>(parent), \ (QObject*)this); fileDelegate.close(); } } void ConfigTreeObject_Network::updateStrShowOn() { updateStrShowOn_basic(); updateStrShowOn_FTP(); updateStrShowOn_SMTP(); updateStrShowOn_EMAIL(); updateStrShowOn_SNTP(); updateStrShowOn_Server(); updateStrShowOn_Modbus(); } void ConfigTreeObject_Network::updateStrShowOn_basic() { slotBasicAutoIPChange(); slotBasicAutoDNSChange(); slotBasicIPAddrChange(); slotBasicIPMaskChange(); slotBasicIPGatewayChange(); slotBasicDNSPriChange(); slotBasicDNSSecChange(); } void ConfigTreeObject_Network::updateStrShowOn_FTP() { slotFTPFunctionChange(); slotFTPTransferFileDisplayChange(); slotFTPTransferFileReportChange(); slotFTPTransferFileDataChange(); slotFTPTransferFileAlarmChange(); slotFTPTransferFileSnapChange(); slotFTPTransferFileDeviceChange(); slotFTPEncrptionChange(); slotFTPEncrptionVerficationChange(); slotFTPTransferWaitDisplayChange(); slotFTPTransferWaitReportChange(); slotFTPPriPortChange(); slotFTPPriModeChange(); slotFTPPriServerChange(); slotFTPPriNameChange(); slotFTPPriPasswdChange(); slotFTPPriDirectionChange(); slotFTPSecPortChange(); slotFTPSecModeChange(); slotFTPSecServerChange(); slotFTPSecNameChange(); slotFTPSecPasswdChange(); slotFTPSecDirectionChange(); } void ConfigTreeObject_Network::updateStrShowOn_SMTP() { slotSMTPFunctionChange(); slotSMTPAuthChange(); slotSMTPEncryptionChange(); slotSMTPEncryptionVerifcationChange(); slotSMTPSMTPPortChange(); slotSMTPSMTPServerChange(); slotSMTPSMTPNameChange(); slotSMTPSMTPPasswdChange(); slotSMTPPOP3PortChange(); slotSMTPPOP3ServerChange(); slotSMTPPOP3NameChange(); slotSMTPPOP3PasswdChange(); } void ConfigTreeObject_Network::updateStrShowOn_EMAIL() { slotEMAILHeaderR1Change(); slotEMAILHeaderR2Change(); slotEMAILHeaderSenderChange(); slotEMAILHeaderSubjectChange(); slotEMAILContentsHeaderChange(); slotEMAILContentsURLChange(); slotEMAILAlarmNotificationChange(); slotEMAILAlarmDataChange(); slotEMAILAlarmSubjectChange(); slotEMAILAlarmSetChange(); slotEMAILAlarmReportChange(); slotEMAILScheduledNotificationChange(); slotEMAILScheduledDataChange(); slotEMAILScheduledR1InteralChange(); slotEMAILScheduledR1TimeHChange(); slotEMAILScheduledR1TimeMChange(); slotEMAILScheduledR2InteralChange(); slotEMAILScheduledR2TimeHChange(); slotEMAILScheduledR2TimeMChange(); slotEMAILSystemMemoryChange(); slotEMAILSystemPowerChange(); slotEMAILSystemErrorChange(); slotEMAILUserChange(); } void ConfigTreeObject_Network::updateStrShowOn_SNTP() { slotSNTPFunctionChange(); slotSNTPServerPortChange(); slotSNTPServerNameChange(); slotSNTPActionIntervalChange(); slotSNTPActionTimeoutChange(); slotSNTPActionTimeChange(); } void ConfigTreeObject_Network::updateStrShowOn_Server() { slotServerModbusFunctionChange(); slotServerModbus1SwitchChange(); slotServerModbus1IPChange(); slotServerModbus2SwitchChange(); slotServerModbus2IPChange(); slotServerModbus3SwitchChange(); slotServerModbus3IPChange(); slotServerModbus4SwitchChange(); slotServerModbus4IPChange(); slotServerModbus5SwitchChange(); slotServerModbus5IPChange(); slotServerModbus6SwitchChange(); slotServerModbus6IPChange(); slotServerModbus7SwitchChange(); slotServerModbus7IPChange(); slotServerModbus8SwitchChange(); slotServerModbus8IPChange(); slotServerModbus9SwitchChange(); slotServerModbus9IPChange(); slotServerModbus10SwitchChange(); slotServerModbus10IPChange(); slotServerSettingFTPFunctionChange(); slotServerSettingFTPEncyptionChange(); slotServerSettingFTPPortChange(); slotServerSettingFTPKeepChange(); slotServerSettingHTTPFunctionChange(); slotServerSettingHTTPEncyptionChange(); slotServerSettingHTTPPortChange(); slotServerSettingSNTPFunctionChange(); slotServerSettingSNTPPortChange(); slotServerSettingModbusFunctionChange(); slotServerSettingModbusPortChange(); slotServerSettingModbusDelayChange(); } void ConfigTreeObject_Network::updateStrShowOn_Modbus() { slotNetworkModbusBasicFunctionChange(); slotNetworkModbusBasicInteralChange(); slotNetworkModbusBasicWaitTimeChange(); slotNetworkModbusBasicConnectChange(); slotNetworkModbusBasicTimeoutChange(); //slotNetworkModbusServerNumberChange(); slotNetworkModbusServerServerNameChange(); slotNetworkModbusServerServerPortChange(); //slotNetworkModbusCommandNumberChange(); slotNetworkModbusCommandTypeChange(); slotNetworkModbusCommandServerChange(); slotNetworkModbusCommandUnitChange(); slotNetworkModbusCommandDataTypeChange(); slotNetworkModbusCommandRegisterChange(); slotNetworkModbusCommandChanelTypeChange(); slotNetworkModbusCommandFirstCHChange(); slotNetworkModbusCommandLastCHChange(); } void ConfigTreeObject_Network::slotCreateNetworksettingTree(QObject *parent) { //Network setting 配置树 QFile file(":/configtree/Image/configTree/Network/Network_Setting/config.xml"); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file: Network_setting!"; }else{ XmlConfigParser::parseConfigXml(file, static_cast<ConfigObject*>(parent)); file.close(); } quint32 ID_server = ConfigTreeObject::getConfigObject(Modbus_ServerNum_Setting)->getObjectID(); quint32 ID_command = ConfigTreeObject::getConfigObject(Modbus_CommandNum_Setting)->getObjectID(); ConfigTreeObject::getConfigObject(Modbus_ServerNum_Setting)->initData(0, 0, ID_server); ConfigTreeObject::getConfigObject(Modbus_CommandNum_Setting)->initData(0, 0, ID_command); ConfigTreeObject::getConfigObject(Modbus_ServerNum_Setting)->setStrShowOn("1"); ConfigTreeObject::getConfigObject(Modbus_CommandNum_Setting)->setStrShowOn("1"); m_cmdNumChannelTypeFlag = false; m_cmdNumDataTypeFlag = false; } void ConfigTreeObject_Network::slotNetworkDelegateChange() { QFile delegateChange(":/configtree/Image/configTree/Network/Network_DelegateChange/delegateChange.xml"); if(!delegateChange.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file: AI_settingDelegateChange!"; }else{ XmlConfigParser::parseDelegateChangeXml(delegateChange); delegateChange.close(); } _curStatus = false; updateStrShowOn(); _curStatus = true; } void ConfigTreeObject_Network::slotBasicAutoIPChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_AutoIP)->getData(); QFile file(XML_Network_Basic_AutoIP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotBasicAutoDNSChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_AutoDNS)->getData(); QFile file(XML_Network_Basic_AutoDNS); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotBasicIPAddrChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_IPAddr)->getData(); QFile file(XML_Network_Basic_IPAddr); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } ConfigTreeObject::getConfigObject(Network_Basic_Deledate_IPMask)->changeData("0.0.0.0", false); ConfigTreeObject::getConfigObject(Network_Basic_Deledate_Gateway)->changeData("0.0.0.0", false); } void ConfigTreeObject_Network::slotBasicIPMaskChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_IPMask)->getData(); QFile file(XML_Network_Basic_IPMask); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotBasicIPGatewayChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_Gateway)->getData(); QFile file(XML_Network_Basic_IPGateway); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotBasicDNSPriChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_DNSPri)->getData(); QFile file(XML_Network_Basic_DNSPri); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotBasicDNSSecChange() { QVariant value = ConfigTreeObject::getConfigObject(Network_Basic_Deledate_DNSSec)->getData(); QFile file(XML_Network_Basic_DNSSec); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_FUNCTION)->getData(); QFile file(XML_Network_FTP_FUNCTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferFileDisplayChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERFILE_DISPLAY)->getData(); QFile file(XML_Network_FTP_TRANSFERFILE_DISPLAY); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferFileReportChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERFILE_REPORT)->getData(); QFile file(XML_Network_FTP_TRANSFERFILE_REPORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferFileDataChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERFILE_DATA)->getData(); QFile file(XML_Network_FTP_TRANSFERFILE_DATA); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferFileAlarmChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERFILE_ALARM)->getData(); QFile file(XML_Network_FTP_TRANSFERFILE_ALARM); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferFileSnapChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERFILE_SNAP)->getData(); QFile file(XML_Network_FTP_TRANSFERFILE_SNAP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferFileDeviceChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERFILE_DEVICE)->getData(); QFile file(XML_Network_FTP_TRANSFERFILE_DEVICE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPEncrptionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_ENCRYPTION_ENCRYPTION)->getData(); QFile file(XML_Network_FTP_ENCRYPTION_ENCRYPTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPEncrptionVerficationChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_ENCRYPTION_VERFICATION)->getData(); QFile file(XML_Network_FTP_ENCRYPTION_VERFICATION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferWaitDisplayChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERWAIT_DISPLAY)->getData(); QFile file(XML_Network_FTP_TRANSFERWAIT_DISPLAY); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPTransferWaitReportChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_TRANSFERWAIT_REPORT)->getData(); QFile file(XML_Network_FTP_TRANSFERWAIT_REPORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPPriPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_PRI_PORT)->getData(); QFile file(XML_Network_FTP_PRI_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPPriModeChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_PRI_MODE)->getData(); QFile file(XML_Network_FTP_PRI_MODE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPPriServerChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_PRI_SERVER)->getData(); QFile file(XML_Network_FTP_PRI_SERVER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPPriNameChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_PRI_NAME)->getData(); QFile file(XML_Network_FTP_PRI_NAME); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPPriPasswdChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_PRI_PASSWD)->getData(); QFile file(XML_Network_FTP_PRI_PASSWD); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPPriDirectionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_PRI_DIRECTION)->getData(); QFile file(XML_Network_FTP_PRI_DIRECTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPSecPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_SEC_PORT)->getData(); QFile file(XML_Network_FTP_SEC_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPSecModeChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_SEC_MODE)->getData(); QFile file(XML_Network_FTP_SEC_MODE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPSecServerChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_SEC_SERVER)->getData(); QFile file(XML_Network_FTP_SEC_SERVER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPSecNameChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_SEC_NAME)->getData(); QFile file(XML_Network_FTP_SEC_NAME); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPSecPasswdChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_SEC_PASSWD)->getData(); QFile file(XML_Network_FTP_SEC_PASSWD); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotFTPSecDirectionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_FTP_Deledate_SEC_DIRECTORY)->getData(); QFile file(XML_Network_FTP_SEC_DIRECTORY); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_Deledate_FUNCTION)->getData(); QFile file(XML_Network_SMTP_FUNCTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPAuthChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_Deledate_AUTH)->getData(); QFile file(XML_Network_SMTP_AUTH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPEncryptionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_Deledate_ENCRYPTION)->getData(); QFile file(XML_Network_SMTP_ENCRYPTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPEncryptionVerifcationChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_ENCRYPTION_Deledate_VERIFICATION)->getData(); QFile file(XML_Network_SMTP_VERFICATION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPSMTPPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_SMTP_Deledate_PORT)->getData(); QFile file(XML_Network_SMTP_SMTP_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPSMTPServerChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_SMTP_Deledate_SERVER)->getData(); QFile file(XML_Network_SMTP_SMTP_SERVER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPSMTPNameChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_SMTP_Deledate_NAME)->getData(); QFile file(XML_Network_SMTP_SMTP_USER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPSMTPPasswdChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_SMTP_Deledate_PASSWD)->getData(); QFile file(XML_Network_SMTP_SMTP_PASSWD); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPPOP3PortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_POP3_Deledate_PORT)->getData(); QFile file(XML_Network_SMTP_POP3_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPPOP3ServerChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_POP3_Deledate_SERVER)->getData(); QFile file(XML_Network_SMTP_POP3_SERVER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPPOP3NameChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_POP3_Deledate_NAME)->getData(); QFile file(XML_Network_SMTP_POP3_USER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSMTPPOP3PasswdChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SMTP_POP3_Deledate_PASSWD)->getData(); QFile file(XML_Network_SMTP_POP3_PASSWD); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILHeaderR1Change() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_HEADER_R1)->getData(); QFile file(XML_Network_EMAIL_HEADER_R1); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILHeaderR2Change() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_HEADER_R2)->getData(); QFile file(XML_Network_EMAIL_HEADER_R2); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILHeaderSenderChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_HEADER_SENDER)->getData(); QFile file(XML_Network_EMAIL_HEADER_SENDER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILHeaderSubjectChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_HEADER_SUBJECT)->getData(); QFile file(XML_Network_EMAIL_HEADER_SUBJECT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILContentsHeaderChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_CONTENTS_HEADER)->getData(); QFile file(XML_Network_EMAIL_CONTENTS_HEADER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILContentsURLChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_CONTENTS_URL)->getData(); QFile file(XML_Network_EMAIL_CONTENTS_URL); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILAlarmNotificationChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_ALARM_NOTIFICATION)->getData(); QFile file(XML_Network_EMAIL_ALARM_NOITIFICATION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILAlarmDataChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_ALARM_DATA)->getData(); QFile file(XML_Network_EMAIL_ALARM_ATTACH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILAlarmSubjectChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_ALARM_SUBJECT)->getData(); QFile file(XML_Network_EMAIL_ALARM_INCLUDE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILAlarmSetChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_ALARM_SET)->getData(); QFile file(XML_Network_EMAIL_ALARM_CHANELSET); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILAlarmReportChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_ALARM_REPORT)->getData(); QFile file(XML_Network_EMAIL_REPORT_NOITIFICATION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledNotificationChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_NOTIFICATION)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_NOITIFICATION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledDataChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_DATA)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_ATTACH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledR1InteralChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_R1_INTERAL)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_R1_INTERVAL); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledR1TimeHChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_R1_TIMEH)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_R1_HOUR); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledR1TimeMChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_R1_TIMEM)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_R1_MINUTE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledR2InteralChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_R2_INTERAL)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_R2_INTERVAL); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledR2TimeHChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_R2_TIMEH)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_R2_HOUR); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILScheduledR2TimeMChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SCHEDULED_R2_TIMEM)->getData(); QFile file(XML_Network_EMAIL_SCHEEDULED_R2_MINUTE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILSystemMemoryChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SYSTEM_MEMORY)->getData(); QFile file(XML_Network_EMAIL_SYSTEM_MEMORY); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILSystemPowerChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SYSTEM_POWER)->getData(); QFile file(XML_Network_EMAIL_SYSTEM_POWER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILSystemErrorChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SYSTEM_ERROR)->getData(); QFile file(XML_Network_EMAIL_SYSTEM_ERROR); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotEMAILUserChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_EMAIL_Deledate_SYSTEM_USER)->getData(); QFile file(XML_Network_EMAIL_SYSTEM_NOITIFICATION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSNTPFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SNTP_Deledate_FUNCTION)->getData(); QFile file(XML_Network_SNTP_FUNCTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSNTPServerPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SNTP_Deledate_SERVER_POER)->getData(); QFile file(XML_Network_SNTP_NUMBER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSNTPServerNameChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SNTP_Deledate_SERVER_NAME)->getData(); QFile file(XML_Network_SNTP_SERVER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSNTPActionIntervalChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SNTP_Deledate_ACTION_INTERVAL)->getData(); QFile file(XML_Network_SNTP_INTERVAL); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSNTPActionTimeoutChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SNTP_Deledate_ACTION_TIMEOUT)->getData(); QFile file(XML_Network_SNTP_TIMEOUT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotSNTPActionTimeChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SNTP_Deledate_ACTION_TIME)->getData(); QFile file(XML_Network_SNTP_TIMEADJUST); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbusFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_FUNCTIOM)->getData(); QFile file(XML_Network_Server_Modbus_FUNCTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus1SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_1_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_1_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus1IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_1_IP)->getData(); QFile file(XML_Network_Server_Modbus_1_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus2SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_2_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_2_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus2IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_2_IP)->getData(); QFile file(XML_Network_Server_Modbus_2_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus3SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_3_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_3_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus3IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_3_IP)->getData(); QFile file(XML_Network_Server_Modbus_3_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus4SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_4_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_4_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus4IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_4_IP)->getData(); QFile file(XML_Network_Server_Modbus_4_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus5SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_5_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_5_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus5IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_5_IP)->getData(); QFile file(XML_Network_Server_Modbus_5_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus6SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_6_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_6_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus6IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_6_IP)->getData(); QFile file(XML_Network_Server_Modbus_6_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus7SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_7_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_7_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus7IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_7_IP)->getData(); QFile file(XML_Network_Server_Modbus_7_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus8SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_8_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_8_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus8IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_8_IP)->getData(); QFile file(XML_Network_Server_Modbus_8_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus9SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_9_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_9_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus9IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_9_IP)->getData(); QFile file(XML_Network_Server_Modbus_9_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus10SwitchChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_10_SWITCH)->getData(); QFile file(XML_Network_Server_Modbus_10_SWTICH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerModbus10IPChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_MODBUS_10_IP)->getData(); QFile file(XML_Network_Server_Modbus_10_IP); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingFTPFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_FTP_FUNCTION)->getData(); QFile file(XML_Network_Server_List_FTP_SWITCH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingFTPEncyptionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_FTP_ENCYPTION)->getData(); QFile file(XML_Network_Server_List_FTP_ENCRYPTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingFTPPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_FTP_PORT)->getData(); QFile file(XML_Network_Server_List_FTP_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingFTPKeepChange() { ConfigObject *pConfigObj = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_FTP_KEEP); quint32 ID = ID_NetWork_Server_List_FTPConnectHole; QString valueStr = CfgConfig::instance()->getValObjectStr(ID, 0, pConfigObj); pConfigObj->setStrShowOn(valueStr); } void ConfigTreeObject_Network::slotServerSettingHTTPFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_HTTP_FUNCTION)->getData(); QFile file(XML_Network_Server_List_HTTP_SWITCH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingHTTPEncyptionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_HTTP_ENCYPTION)->getData(); QFile file(XML_Network_Server_List_HTTP_ENCRYPTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingHTTPPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_HTTP_PORT)->getData(); QFile file(XML_Network_Server_List_HTTP_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingSNTPFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_SNTP_FUNCTION)->getData(); QFile file(XML_Network_Server_List_SNTP_SWITCH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingSNTPPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_SNTP_PORT)->getData(); QFile file(XML_Network_Server_List_SNTP_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingModbusFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_MODBUS_FUNCTION)->getData(); QFile file(XML_Network_Server_List_MODBUS_SWITCH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingModbusPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_MODBUS_PORT)->getData(); QFile file(XML_Network_Server_List_MODBUS_PORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotServerSettingModbusDelayChange() { ConfigObject *pConfigObj = ConfigTreeObject::getConfigObject(NETWORK_SERVER_Deledate_SETTING_MODBUS_DELAY); quint32 ID = ID_NetWork_Server_Modbus_ModbusServerTimeOut; QString valueStr = CfgConfig::instance()->getValObjectStr(ID, 0, pConfigObj); pConfigObj->setStrShowOn(valueStr); } void ConfigTreeObject_Network::slotNetworkModbusBasicFunctionChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_BASIC_FUNCTION)->getData(); QFile file(XML_Network_Modbus_BASIC_FUNCTION); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusBasicInteralChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_BASIC_INTERVAL)->getData(); QFile file(XML_Network_Modbus_BASIC_INTERVAL); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusBasicWaitTimeChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_BASIC_RECOVER)->getData(); QFile file(XML_Network_Modbus_BASIC_RECOVER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusBasicConnectChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_BASIC_CONNECT)->getData(); QFile file(XML_Network_Modbus_BASIC_CONNECT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusBasicTimeoutChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_BASIC_CONNECT_TIMEOUT)->getData(); QFile file(XML_Network_Modbus_BASIC_CONNECT_TIMEOUT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusServerNumberChange() { ConfigObject *pObj = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_SERVER_NUMBER); if(pObj){ quint32 num = pObj->getData().toUInt(); pObj->setStrShowOn(QString("%1").arg(num+1)); } } void ConfigTreeObject_Network::slotNetworkModbusServerServerNameChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_SERVER_SERVERNAME)->getData(); QFile file(XML_Network_Modbus_SERVER_SERVERNAME); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusServerServerPortChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_SERVER_SERVERPORT)->getData(); QFile file(XML_Network_Modbus_SERVER_SERVERPORT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandNumberChange() { ConfigObject *pObj = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_NUMBER); if(pObj){ quint32 num = pObj->getData().toUInt(); pObj->setStrShowOn(QString("%1").arg(num+1)); } } void ConfigTreeObject_Network::slotNetworkModbusCommandTypeChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_TYPE)->getData(); QFile file(XML_Network_Modbus_COMMAND_TYPE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandServerChange() { ConfigObject *pObj = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_SERVER); if(pObj){ quint32 num = pObj->getData().toUInt(); pObj->setStrShowOn(QString("%1").arg(num+1)); } } void ConfigTreeObject_Network::slotNetworkModbusCommandUnitChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_UNIT)->getData(); QFile file(XML_Network_Modbus_COMMAND_UNIT); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandDataTypeChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_DATATYPE)->getData(); int data = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_REGISTER)->getData().toInt(); switch (value.toInt()) { case NetworkModbusCommandDataType_Bit: if (data > 10000) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_REGISTER)->changeData("1",false); break; default: { QVariant type = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_TYPE)->getData(); switch (type.toInt()) { case NetworkModbusCommandType_Read: if (data < 30001 || (data > 39999 && data < 300001) || (data > 399999)) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_REGISTER)->changeData("30001",false); break; case NetworkModbusCommandType_Write: if (data < 40001 || (data > 49999 && data < 400001) || (data > 499999)) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_REGISTER)->changeData("40001",false); break; default: break; } break; } } QFile file(XML_Network_Modbus_COMMAND_DATATYPE); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandRegisterChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_REGISTER)->getData(); QFile file(XML_Network_Modbus_COMMAND_REGISTER); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandChanelTypeChange() { quint32 type = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_TYPE)->getData().toUInt(); QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_CHANELTYPE)->getData(); quint32 valueF = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)->getData().toUInt(); quint32 valueL = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)->getData().toUInt(); //QString样式转的int,非map对应的quint32 int StrvalueF = CfgConfig_Network::instance()->getNetworkModbusChValObjStr(valueF).toInt(); int StrvalueL = CfgConfig_Network::instance()->getNetworkModbusChValObjStr(valueL).toInt(); QFile file; if (value.toString() == "0") { ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_CHANELTYPE)->changeData(NetworkModbusCommandChanelType_COMM, false); return; } switch (type) { case NetworkModbusCommandType_Read: { ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_CHANELTYPE)\ ->changeData(NetworkModbusCommandChanelType_COMM, false); file.setFileName(XML_Network_Modbus_COMMAND_CHANELTYPE_R); //first channel if (StrvalueF > 300) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)\ ->changeData(CfgChannel::instance()->getExistChannelComm().first(), false); //last channel if (StrvalueL > 300) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)\ ->changeData(CfgChannel::instance()->getExistChannelComm().first(), false); break; } case NetworkModbusCommandType_Write: { QList<DevBoard *> boardList = CfgChannel::instance()->getList_BoardIO(); //wait ....modify if (boardList.isEmpty()) { file.setFileName(XML_Network_Modbus_COMMAND_CHANELTYPE_HIDEIO); } else { file.setFileName(XML_Network_Modbus_COMMAND_CHANELTYPE_W); } //first channel switch (value.toInt()) { case Channel_Type_Comm: { //first channel if (StrvalueF > 300) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)\ ->changeData(CfgChannel::instance()->getExistChannelComm().first(), false); //last channel if (StrvalueL > 300) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)\ ->changeData(CfgChannel::instance()->getExistChannelComm().first(), false); break; } case Channel_Type_Math: { //first channel if (StrvalueF > 100) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)\ ->changeData(CfgChannel::instance()->getExistChannelMath().first(), false); //last channel if (StrvalueL > 100) ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)\ ->changeData(CfgChannel::instance()->getExistChannelMath().first(), false); break; } case Channel_Type_AI: case Channel_Type_DI: case Channel_Type_DO: { quint32 codeF, codeL; int tempModule = 0; int moduleMin = boardList.value(0)->getBoardModule(); moduleMin = boardList.value(0)->getBoardModule(); for (int i = 0; i < boardList.size(); ++i) { if (boardList.value(i)->getBoardModule() < moduleMin) { tempModule = i; moduleMin = boardList.value(i)->getBoardModule(); } } switch (boardList.value(tempModule)->getBoardType()) { case STATUS_BOARD_TYPE_AI: codeF = CHANNEL_AI_CODER(CHANNEL_UNIT(valueF), CHANNEL_MODULE(valueF), CHANNEL_NUM(valueF)); codeL = CHANNEL_AI_CODER(CHANNEL_UNIT(valueL), CHANNEL_MODULE(valueL), CHANNEL_NUM(valueL)); break; case STATUS_BOARD_TYPE_DI: codeF = CHANNEL_DI_CODER(CHANNEL_UNIT(valueF), CHANNEL_MODULE(valueF), CHANNEL_NUM(valueF)); codeL = CHANNEL_DI_CODER(CHANNEL_UNIT(valueL), CHANNEL_MODULE(valueL), CHANNEL_NUM(valueL)); break; case STATUS_BOARD_TYPE_DO: codeF = CHANNEL_DO_CODER(CHANNEL_UNIT(valueF), CHANNEL_MODULE(valueF), CHANNEL_NUM(valueF)); codeL = CHANNEL_DO_CODER(CHANNEL_UNIT(valueL), CHANNEL_MODULE(valueL), CHANNEL_NUM(valueL)); break; default: break; } ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)\ ->changeData(codeF, false); ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)\ ->changeData(codeL, false); break; } default: break; } break; } default: return; } if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Range!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandFirstCHChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)->getData(); QFile file(XML_Network_Modbus_COMMAND_FIRSTCH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandLastCHChange() { QVariant value = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)->getData(); QVariant value_f = ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_FIRSTCH)->getData(); if (value.toInt() < value_f.toInt()) { ConfigTreeObject::getConfigObject(NETWORK_MODBUS_Deledate_COMMAND_LASTCH)->changeData(value_f.toInt(), false); return; } QFile file(XML_Network_Modbus_COMMAND_LASTCH); if(!file.open(QFile::ReadOnly | QFile::Text)){ qWarning()<< "Can't open the file:Range:Type!"; }else{ XmlConfigParser::parseValueChangeXml(file, value); file.close(); } } void ConfigTreeObject_Network::slotNetworkModbusCommandTypeRelationChange() { slotNetworkModbusCommandChanelTypeChange(); slotNetworkModbusCommandDataTypeChange(); slotNetworkModbusCommandFirstCHChange(); slotNetworkModbusCommandLastCHChange(); } void ConfigTreeObject_Network::slotNetworkModbusCommandChanelTypeRelationChange() { slotNetworkModbusCommandFirstCHChange(); slotNetworkModbusCommandLastCHChange(); }
[ "urielyan@sina.com" ]
urielyan@sina.com
52a3b0957172b5f0adae16f79accec72f254253d
6ba04db92d995e0f4a474289ee80f22f310644fd
/datastructures/reads/ScanData.cpp
a75f4e88a153e7ebc197f35d8de3e6f5b52ac281
[]
no_license
pbjd/pblibblasr
a1cc810cef21c8807769d42a48d55eff963f8634
053af8420ecf50199949c4d27cf8c66bf0ea04ce
refs/heads/master
2021-01-10T22:12:33.182489
2013-10-10T21:05:57
2013-10-10T21:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
88
cpp
#include "ScanData.hpp" std::string ScanData::GetMovieName() { return movieName; }
[ "jdrake@pacificbiosciences.com" ]
jdrake@pacificbiosciences.com
bc3eb2042d0599f9e0686f9f13e82e051ac8b7c5
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_Veggie_Rockarrot_classes.hpp
9ad06b524c6f2f1199bbcfba49a25315d1ebb8c8
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
923
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_Veggie_Rockarrot_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass PrimalItemConsumable_Veggie_Rockarrot.PrimalItemConsumable_Veggie_Rockarrot_C // 0x0000 (0x0AE8 - 0x0AE8) class UPrimalItemConsumable_Veggie_Rockarrot_C : public UPrimalItemConsumable_Veggie_Base_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItemConsumable_Veggie_Rockarrot.PrimalItemConsumable_Veggie_Rockarrot_C"); return ptr; } void ExecuteUbergraph_PrimalItemConsumable_Veggie_Rockarrot(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
3f727d114f6f3fcf6b99b0a35337a4c6a681bffa
ff16f579882da22c09fb37b45e3ce5a432212818
/Chapter5.1/SDL_game/TextureManager.h
354084a867d9c6f79b73b51d15b3ef5f42874442
[]
no_license
kvelaro/SDL_game
4c44ad6eec65b6fb4520ba7601e165cb0edddf37
d4c4a7f38a1f2aa56b994bc0671cd08706df5ea2
refs/heads/master
2022-01-09T19:44:12.954241
2019-06-28T11:46:53
2019-06-28T11:46:53
188,982,450
1
3
null
null
null
null
UTF-8
C++
false
false
912
h
#pragma once #ifndef __TEXTUREMANAGER__ #define __TEXTUREMANAGER__ #include <iostream> #include <map> #include <SDL.h> using namespace std; class TextureManager { public: bool load(string fileName, std::string id, SDL_Renderer* pRenderer); void draw(string id, int x, int y, int width, int height, SDL_Renderer* pRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE); void drawFrame(string id, int x, int y, int width, int height, int currentRow, int currentFrame, SDL_Renderer* pRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE); void clearFromTextureMap(string id); static TextureManager* Instance() { if (s_pInstance == 0) { s_pInstance = new TextureManager(); return s_pInstance; } return s_pInstance; } private: TextureManager() {} map<string, SDL_Texture *> m_textureMap; static TextureManager *s_pInstance; }; typedef TextureManager TheTextureManager; #endif // !__TEXTUREMANAGER__
[ "kamilmiem@gmail.com" ]
kamilmiem@gmail.com
87a90ad4445d36b97f8a653f1d2657a35c8fe5d9
93bf4bbafe0524335ea1216f7f2941348c2cd1bd
/tensorflow/core/util/sparse/dim_comparator.h
1ba4baccc368853e563da4e8e1a34e24f1851ff7
[ "Apache-2.0" ]
permissive
sachinpro/sachinpro.github.io
c4951734b09588cad58711a76fe657f110163c11
c3bbd8d89818f5d8bb7296c851ed5e52c19728e3
refs/heads/master
2022-12-23T10:00:13.902459
2016-06-27T13:18:27
2016-06-27T13:25:58
25,289,839
1
1
Apache-2.0
2022-12-15T00:45:03
2014-10-16T06:44:30
C++
UTF-8
C++
false
false
3,344
h
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_UTIL_SPARSE_DIM_COMPARATOR_H_ #define TENSORFLOW_UTIL_SPARSE_DIM_COMPARATOR_H_ #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace sparse { ///////////////// // DimComparator ///////////////// // // Helper class, mainly used by the IndexSortOrder. This comparator // can be passed to e.g. std::sort, or any other sorter, to sort two // rows of an index matrix according to the dimension(s) of interest. // The dimensions to sort by are passed to the constructor as "order". // // Example: if given index matrix IX, two rows ai and bi, and order = {2,1}. // operator() compares // IX(ai,2) < IX(bi,2). // If IX(ai,2) == IX(bi,2), it compares // IX(ai,1) < IX(bi,1). // // This can be used to sort a vector of row indices into IX according to // the values in IX in particular columns (dimensions) of interest. class DimComparator { public: typedef typename gtl::ArraySlice<int64> VarDimArray; inline DimComparator(const TTypes<int64>::Matrix& ix, const VarDimArray& order, int dims) : ix_(ix), order_(order), dims_(dims) { CHECK_GT(order.size(), size_t{0}) << "Must order using at least one index"; CHECK_LE(order.size(), dims_) << "Can only sort up to dims"; for (size_t d = 0; d < order.size(); ++d) { CHECK_GE(order[d], 0); CHECK_LT(order[d], dims); } } inline bool operator()(const int64 i, const int64 j) const { for (int di = 0; di < dims_; ++di) { const int64 d = order_[di]; if (ix_(i, d) < ix_(j, d)) return true; if (ix_(i, d) > ix_(j, d)) return false; } return false; } // Compares two indices taken from corresponding index matrices, using the // standard, row-major (or lexicographic) order. Useful for cases that need // to distinguish between all three orderings (<, ==, >). inline static int cmp(const TTypes<int64>::ConstMatrix& a_idx, const TTypes<int64>::ConstMatrix& b_idx, const int64 a_row, const int64 b_row, const int dims) { for (int d = 0; d < dims; ++d) { const int64 a = a_idx(a_row, d); const int64 b = b_idx(b_row, d); if (a < b) { return -1; } else if (a > b) { return 1; } } return 0; } const TTypes<int64>::Matrix ix_; const VarDimArray order_; const int dims_; }; } // namespace sparse } // namespace tensorflow #endif // TENSORFLOW_UTIL_SPARSE_DIM_COMPARATOR_H_
[ "x0234443@ti.com" ]
x0234443@ti.com
fd28afaa5cecba0615f534042d8e664e56de0ec3
8e2c6a5f242fc1c531d1598e302f0b98ad194c9d
/statechart/internal/state_machine_impl.cc
3ac3cd16e20ba0f191ad22b2e82d8fd81e91558f
[ "Apache-2.0" ]
permissive
kenvay/statechart
6ab35ed234a2f765a1f387ccda5811d033042b30
d283cefab5a051a91c21be46d97bc18407fd7628
refs/heads/master
2022-03-15T19:24:46.590951
2019-12-10T01:34:08
2019-12-10T01:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,220
cc
// Copyright 2018 The StateChart Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "statechart/internal/state_machine_impl.h" #include "absl/memory/memory.h" #include "statechart/internal/event_dispatcher.h" #include "statechart/internal/executor.h" #include "statechart/internal/light_weight_datamodel.h" #include "statechart/internal/model.h" #include "statechart/internal/runtime.h" using ::absl::WrapUnique; namespace state_chart { class StateMachineListener; } // namespace state_chart namespace state_chart { // static std::unique_ptr<StateMachine> StateMachineImpl::Create( const Executor* executor, const Model* model, std::unique_ptr<Runtime> runtime) { RETURN_NULL_IF(executor == nullptr || model == nullptr || runtime == nullptr); return WrapUnique(new StateMachineImpl(executor, model, std::move(runtime))); } StateMachineImpl::StateMachineImpl(const Executor* executor, const Model* model, std::unique_ptr<Runtime> runtime) : executor_(executor), model_(model), runtime_(std::move(runtime)) {} // override void StateMachineImpl::Start() { executor_->Start(model_, runtime_.get()); } // override void StateMachineImpl::SendEvent(const string& event, const string& payload) { executor_->SendEvent(model_, runtime_.get(), event, payload); } // override void StateMachineImpl::AddListener(StateMachineListener* listener) { runtime_->GetEventDispatcher()->AddListener(listener); } // override const Runtime& StateMachineImpl::GetRuntime() const { return *runtime_; } // override const Model& StateMachineImpl::GetModel() const { return *model_; } } // namespace state_chart
[ "srgandhe@google.com" ]
srgandhe@google.com
9fff23655a0054270cf7bd6345f07b34facca40c
c6357b98d9d1ec4161bd6fb457ceb3a396a4552d
/Forums/ClassLibraryWrapper/AssemblyInfo.cpp
a57d0cb2dc69293dc0bc3a1a796e3a0c06a9642a
[]
no_license
SimpleSamples/Repos
33b2a16c86f4ebaa0f1016d65701d7a4b9c08a46
eaa9b4ef2e2dbddb2e85fd0e74cfcd75e2193c02
refs/heads/master
2023-06-07T22:27:51.737364
2022-08-31T03:51:02
2022-08-31T03:51:02
167,258,199
0
2
null
2023-05-31T20:28:52
2019-01-23T21:37:59
C#
UTF-8
C++
false
false
751
cpp
#include "pch.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; [assembly:AssemblyTitleAttribute(L"ClassLibraryWrapper")]; [assembly:AssemblyDescriptionAttribute(L"")]; [assembly:AssemblyConfigurationAttribute(L"")]; [assembly:AssemblyCompanyAttribute(L"")]; [assembly:AssemblyProductAttribute(L"ClassLibraryWrapper")]; [assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2021")]; [assembly:AssemblyTrademarkAttribute(L"")]; [assembly:AssemblyCultureAttribute(L"")]; [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)];
[ "SimpleSamples@users.noreply.github.com" ]
SimpleSamples@users.noreply.github.com
40a0bb5b8e9272a5300604168b2636e7c60148f8
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/lite/tools/benchmark/experimental/delegate_performance/android/src/main/native/accuracy_benchmark.cc
906b109f86da666c15d01a8866c67e1f0493c75b
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
5,665
cc
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/tools/benchmark/experimental/delegate_performance/android/src/main/native/accuracy_benchmark.h" #include <errno.h> #include <stdio.h> #include <sys/stat.h> #include <cstddef> #include <string> #include <vector> #include "flatbuffers/buffer.h" // from @flatbuffers #include "flatbuffers/flatbuffer_builder.h" // from @flatbuffers #include "tensorflow/lite/acceleration/configuration/configuration_generated.h" #include "tensorflow/lite/experimental/acceleration/mini_benchmark/c/c_api.h" #include "tensorflow/lite/kernels/internal/compatibility.h" #include "tensorflow/lite/logger.h" #include "tensorflow/lite/minimal_logging.h" #include "tensorflow/lite/tools/benchmark/experimental/delegate_performance/android/src/main/native/status_codes.h" namespace tflite { namespace benchmark { namespace accuracy { namespace { std::vector<const tflite::BenchmarkEvent*> ToBenchmarkEvents(uint8_t* data, size_t size) { std::vector<const tflite::BenchmarkEvent*> results; uint8_t* current_root = data; while (current_root < data + size) { flatbuffers::uoffset_t current_size = flatbuffers::GetPrefixedSize(current_root); results.push_back( flatbuffers::GetSizePrefixedRoot<tflite::BenchmarkEvent>(current_root)); current_root += current_size + sizeof(flatbuffers::uoffset_t); } // Checks the data read is not over the bounds of the buffer. TFLITE_CHECK_EQ(current_root, data + size); return results; } } // namespace flatbuffers::Offset<BenchmarkEvent> Benchmark( flatbuffers::FlatBufferBuilder& fbb, const TFLiteSettings& tflite_settings, int model_fd, size_t model_offset, size_t model_size, const char* result_path_chars) { std::string result_path(result_path_chars); std::string storage_path = result_path + "/storage_path.fb"; int return_code = std::remove(storage_path.c_str()); if (return_code) { TFLITE_LOG_PROD(TFLITE_LOG_WARNING, "Failed to remove storage file (%s): %s.", storage_path.c_str(), strerror(errno)); } flatbuffers::FlatBufferBuilder mini_benchmark_fbb; TFLiteSettingsT tflite_settings_t; tflite_settings.UnPackTo(&tflite_settings_t); flatbuffers::Offset<TFLiteSettings> tflite_settings_offset = CreateTFLiteSettings(mini_benchmark_fbb, &tflite_settings_t); flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<TFLiteSettings>>> tflite_settings_vector_offset = mini_benchmark_fbb.CreateVector({tflite_settings_offset}); ModelFileBuilder model_file_builder(mini_benchmark_fbb); model_file_builder.add_fd(model_fd); model_file_builder.add_offset(model_offset); model_file_builder.add_length(model_size); flatbuffers::Offset<ModelFile> model_file_offset = model_file_builder.Finish(); flatbuffers::Offset<BenchmarkStoragePaths> storage_paths_offset = CreateBenchmarkStoragePaths(mini_benchmark_fbb, mini_benchmark_fbb.CreateString(storage_path), mini_benchmark_fbb.CreateString(result_path)); flatbuffers::Offset<ValidationSettings> validation_settings_offset = CreateValidationSettings(mini_benchmark_fbb, /*per_test_timeout_ms=*/5000); mini_benchmark_fbb.Finish(CreateMinibenchmarkSettings( mini_benchmark_fbb, tflite_settings_vector_offset, model_file_offset, storage_paths_offset, validation_settings_offset)); TfLiteMiniBenchmarkSettings* settings = TfLiteMiniBenchmarkSettingsCreate(); TfLiteMiniBenchmarkSettingsSetFlatBufferData( settings, mini_benchmark_fbb.GetBufferPointer(), mini_benchmark_fbb.GetSize()); TfLiteMiniBenchmarkResult* result = TfLiteBlockingValidatorRunnerTriggerValidation(settings); std::vector<const BenchmarkEvent*> events = ToBenchmarkEvents(TfLiteMiniBenchmarkResultFlatBufferData(result), TfLiteMiniBenchmarkResultFlatBufferDataSize(result)); TfLiteMiniBenchmarkSettingsFree(settings); // The settings contains one test only. Therefore, the benchmark checks for // the first result only. if (events.size() != 1) { TfLiteMiniBenchmarkResultFree(result); TFLITE_LOG_PROD( TFLITE_LOG_ERROR, "Number of result events (%zu) doesn't match the expectation (%zu).", events.size(), 1); flatbuffers::Offset<BenchmarkError> error = CreateBenchmarkError(fbb, BenchmarkStage_INFERENCE, /*exit_code=*/kBenchmarkResultCountMismatch); BenchmarkEventBuilder builder(fbb); builder.add_event_type(BenchmarkEventType_ERROR); builder.add_error(error); return builder.Finish(); } BenchmarkEventT benchmark_event; events[0]->UnPackTo(&benchmark_event); TfLiteMiniBenchmarkResultFree(result); return CreateBenchmarkEvent(fbb, &benchmark_event); } } // namespace accuracy } // namespace benchmark } // namespace tflite
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
9e205e2f4124de6fe60f18b41f0fcf98d71973bd
1f7cdf773f1e9ec93f3458af8f2e086a19eecad3
/Tablice/main.cpp
36e052131329cfefb0d1492c4dd210d0e41a44bb
[]
no_license
konekwronek/SPOJ
a87fb67c1c4b331123388565f04277304b532d3b
6efae91ed90a1cf7a94277c65becb35add9de690
refs/heads/master
2020-03-20T08:41:20.880674
2018-06-14T13:23:06
2018-06-14T13:23:06
137,316,238
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
#include <iostream> using namespace std; int main() { int t, n, i, pice; int tab[100]; cin >> t; while(t > 0) { cin >> n; if(n <= 100){ for(i = 0; i < n; i++) { cin >> pice; tab[i] = pice; } for(i = n - 1; i >= 0; i--) { cout << tab[i] << " "; } cout << endl; } t--; } return 0; }
[ "32572821+konekwronek@users.noreply.github.com" ]
32572821+konekwronek@users.noreply.github.com
84f48ca2f6755a6846db4b2ec3983a0efe188c53
9fad4848e43f4487730185e4f50e05a044f865ab
/src/chrome/browser/ui/webui/settings/settings_default_browser_handler.cc
a25e964a1f916ab40978c876b48a00015109a3e7
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
2,978
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/settings_default_browser_handler.h" #include "base/bind.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/startup/default_browser_prompt.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui.h" namespace settings { namespace { bool IsDisabledByPolicy(const BooleanPrefMember& pref) { return pref.IsManaged() && !pref.GetValue(); } } // namespace DefaultBrowserHandler::DefaultBrowserHandler(content::WebUI* webui) : weak_ptr_factory_(this) { default_browser_worker_ = new shell_integration::DefaultBrowserWorker( base::Bind(&DefaultBrowserHandler::OnDefaultBrowserWorkerFinished, weak_ptr_factory_.GetWeakPtr())); default_browser_policy_.Init( prefs::kDefaultBrowserSettingEnabled, g_browser_process->local_state(), base::Bind(&DefaultBrowserHandler::RequestDefaultBrowserState, base::Unretained(this), nullptr)); } DefaultBrowserHandler::~DefaultBrowserHandler() {} void DefaultBrowserHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "SettingsDefaultBrowser.requestDefaultBrowserState", base::Bind(&DefaultBrowserHandler::RequestDefaultBrowserState, base::Unretained(this))); web_ui()->RegisterMessageCallback( "SettingsDefaultBrowser.setAsDefaultBrowser", base::Bind(&DefaultBrowserHandler::SetAsDefaultBrowser, base::Unretained(this))); } void DefaultBrowserHandler::RequestDefaultBrowserState( const base::ListValue* /*args*/) { default_browser_worker_->StartCheckIsDefault(); } void DefaultBrowserHandler::SetAsDefaultBrowser(const base::ListValue* args) { CHECK(!IsDisabledByPolicy(default_browser_policy_)); default_browser_worker_->StartSetAsDefault(); // If the user attempted to make Chrome the default browser, notify // them when this changes. chrome::ResetDefaultBrowserPrompt(Profile::FromWebUI(web_ui())); } void DefaultBrowserHandler::OnDefaultBrowserWorkerFinished( shell_integration::DefaultWebClientState state) { if (state == shell_integration::IS_DEFAULT) { // Notify the user in the future if Chrome ceases to be the user's chosen // default browser. chrome::ResetDefaultBrowserPrompt(Profile::FromWebUI(web_ui())); } base::FundamentalValue is_default(state == shell_integration::IS_DEFAULT); base::FundamentalValue can_be_default( state != shell_integration::UNKNOWN_DEFAULT && !IsDisabledByPolicy(default_browser_policy_) && shell_integration::CanSetAsDefaultBrowser()); web_ui()->CallJavascriptFunction("Settings.updateDefaultBrowserState", is_default, can_be_default); } } // namespace settings
[ "dummas@163.com" ]
dummas@163.com
8dbadf4a4fc2edefe86451122531e7e0e8481c38
5b42752be28426f8057149ceb24f487a67d394b4
/TankWar/AI_Follow_Collide_BasePawn.h
388cef4b4194f531fce9772c6eb1c04440ea8120
[]
no_license
181847/TankWar
77453ce47a18b43d816e1c52fda23d4db0c7b940
9825b7be603c8d086fbf7051beb1b228cc5cd1d3
refs/heads/master
2021-01-19T12:25:32.995239
2018-01-14T09:35:35
2018-01-14T09:35:35
100,784,780
0
0
null
null
null
null
GB18030
C++
false
false
1,463
h
#pragma once #include "BasePawn.h" //获取Pawn中针对的FollowCommander #define STATIC_P_AI_COMMANDER(Class_Base_On_AI_Follow_Collide_BasePawn) (Class_Base_On_AI_Follow_Collide_BasePawn.m_pAICommander) //获取Pawn中针对的FollowCommander #define STATIC_P_FOLLOW_COMMANDER(Class_Base_On_AI_Follow_Collide_BasePawn) (Class_Base_On_AI_Follow_Collide_BasePawn.m_pFollowCommander) //获取Pawn中针对的FollowCommander #define STATIC_P_COLLIDE_COMMANDER(Class_Base_On_AI_Follow_Collide_BasePawn) (Class_Base_On_AI_Follow_Collide_BasePawn.m_pCollideCommander) class AI_Follow_Collide_BasePawn : public BasePawn { public: AI_Follow_Collide_BasePawn(); ~AI_Follow_Collide_BasePawn(); //生成Pawn的生成代理结构,这个结构用于PawnMaster中,使得PawnMaster能够控制生成Pawn。 virtual PawnCommandTemplate* GeneratePawnCommandTemplate() = 0; //注册AICommander。 virtual void RegisterAICommander (AICommander* pAICommander); //注册跟随Commander virtual void RegisterFollowCommander (FollowCommander* pFollowCommander); //注册碰撞Commander virtual void RegisterCollideCommander (CollideCommander* pCollideCommander); protected: //负责这个Pawn自动控制的AICommander。 static AICommander * m_pAICommander; //负责这个Pawn的ControlItem跟随效果的Commander。 static FollowCommander * m_pFollowCommander; //负责这个Pawn碰撞效果的Commander。 static CollideCommander * m_pCollideCommander; };
[ "753090084@qq.com" ]
753090084@qq.com
2c0022174d432ab7b031607b93cfc7eb5aedd595
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc
a2b95c063326e779edb53ed1ec4b69e6269b44a3
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
3,038
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.h" #include "base/bind.h" #include "base/task/post_task.h" #include "base/values.h" #include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_ui.h" #include "crypto/nss_util.h" using content::BrowserThread; namespace chromeos { CryptohomeWebUIHandler::CryptohomeWebUIHandler() : weak_ptr_factory_(this) {} CryptohomeWebUIHandler::~CryptohomeWebUIHandler() {} void CryptohomeWebUIHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "pageLoaded", base::BindRepeating(&CryptohomeWebUIHandler::OnPageLoaded, weak_ptr_factory_.GetWeakPtr())); } void CryptohomeWebUIHandler::OnPageLoaded(const base::ListValue* args) { CryptohomeClient* cryptohome_client = CryptohomeClient::Get(); cryptohome_client->IsMounted(GetCryptohomeBoolCallback("is-mounted")); cryptohome_client->TpmIsReady(GetCryptohomeBoolCallback("tpm-is-ready")); cryptohome_client->TpmIsEnabled(GetCryptohomeBoolCallback("tpm-is-enabled")); cryptohome_client->TpmIsOwned(GetCryptohomeBoolCallback("tpm-is-owned")); cryptohome_client->TpmIsBeingOwned( GetCryptohomeBoolCallback("tpm-is-being-owned")); cryptohome_client->Pkcs11IsTpmTokenReady( GetCryptohomeBoolCallback("pkcs11-is-tpm-token-ready")); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {BrowserThread::IO}, base::Bind(&crypto::IsTPMTokenReady, base::Closure()), base::Bind(&CryptohomeWebUIHandler::DidGetNSSUtilInfoOnUIThread, weak_ptr_factory_.GetWeakPtr())); } void CryptohomeWebUIHandler::DidGetNSSUtilInfoOnUIThread( bool is_tpm_token_ready) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::Value is_tpm_token_ready_value(is_tpm_token_ready); SetCryptohomeProperty("is-tpm-token-ready", is_tpm_token_ready_value); } DBusMethodCallback<bool> CryptohomeWebUIHandler::GetCryptohomeBoolCallback( const std::string& destination_id) { return base::BindOnce(&CryptohomeWebUIHandler::OnCryptohomeBoolProperty, weak_ptr_factory_.GetWeakPtr(), destination_id); } void CryptohomeWebUIHandler::OnCryptohomeBoolProperty( const std::string& destination_id, base::Optional<bool> result) { SetCryptohomeProperty(destination_id, base::Value(result.value_or(false))); } void CryptohomeWebUIHandler::SetCryptohomeProperty( const std::string& destination_id, const base::Value& value) { base::Value destination_id_value(destination_id); web_ui()->CallJavascriptFunctionUnsafe("SetCryptohomeProperty", destination_id_value, value); } } // namespace chromeos
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
d1905f6724284a32fd5218cd9d97f40ba4cdaee3
ea345983989a5c6c1643374a4aa4f8dda5c57fbf
/audience-common/include/audience/common/audience_common.h
e49af89ae830ed467c6980e7532f9753e6f0cb72
[]
no_license
dave0629/MyJenkinsPipeline
cd76e72d5be491d380194e43fc4ea86d0cfb4e92
93c0f9398a5c30c34a8060024c6db7c7423531b6
refs/heads/master
2021-05-24T18:38:00.961808
2020-04-27T16:17:24
2020-04-27T16:17:24
253,702,106
0
0
null
null
null
null
UTF-8
C++
false
false
274
h
#ifndef AUDIENCE_INCLUDE_AUDIENCE_COMMON_AUDIENCE_COMMON_H_ #define AUDIENCE_INCLUDE_AUDIENCE_COMMON_AUDIENCE_COMMON_H_ #include <string> class AudienceCommon { public: std::string echo(std::string s); }; #endif // AUDIENCE_INCLUDE_AUDIENCE_COMMON_AUDIENCE_COMMON_H_
[ "dave_chen@trendmicro.com" ]
dave_chen@trendmicro.com
75fac381323f8504ab58c23507e42e9a3039fedd
0aae0f80f581221b2fd6cb0ec63ad6de29a4f355
/main.cpp
1acc8b1021344531031059e28e27d71fb5bfb8f6
[]
no_license
iWhiteLion/Colas-C-
607af2ec510ab9b9766239a56e13f9143674da9f
fa7a2343442ed98bf33050496478cc397b9337e4
refs/heads/main
2023-06-20T03:24:53.943826
2021-07-05T04:32:03
2021-07-05T04:32:03
382,997,864
0
0
null
null
null
null
UTF-8
C++
false
false
1,668
cpp
#include <iostream> #include <queue> using namespace std; //Probando Git int main() { int opc, num; queue <int> cola; cout << "= = = Colas = = ="; do { cout << "\n1. Encolar" "\n2. Desencolar" "\n3. Frente" "\n4. Ultimo" "\n5. Tiene datos?" "\n6. Salir" "\nIngrese su opcion: "; cin >> opc; switch(opc) { case 6: cout << "Gracias por usar este programa"<<endl; cout << "Programa finalizado."; break; case 1: cout << "Ingrese el numero que desea encolar: "; cin >> num; cola.push(num); break; case 2: if(cola.empty()) cout << "\nERROR: La cola esta vacia."; else cola.pop(); cout<<"Numero desencolado"<<endl; break; case 3: if(cola.empty()) cout << "\nERROR: La cola esta vacia."; else cout << "\n-El numero del frente es: " << cola.front(); break; case 4: if(cola.empty()) cout << "\nERROR: La cola esta vacia."; else cout << "\n--El ultimo numero es: " << cola.back(); break; case 5: if(cola.empty()) cout << "La cola esta vacia."; else cout << "La cola tiene datos."; break; default: cout << "\nOpcion Invalida."; break; } }while(opc != 6); return 0; }
[ "ttelloi@est.ups.edu.ec" ]
ttelloi@est.ups.edu.ec
abc0c19042b97519bb47f7deec636b586640ee3d
a93bb0f268cf5e2de2dd745c86a160ca60fada86
/源代码/Thirdparty/UGC/inc/Algorithm/UGRelLines.h
e90ade6927ae6e049739114c1e43d585153ddc63
[ "Apache-2.0" ]
permissive
15831944/Fdo_SuperMap
ea22b74ecfc5f983f2decefe4c2cf29007b85bf6
3d4309d0f45fa63abcde188825a997077dd444f4
refs/heads/master
2021-05-29T09:57:19.433966
2015-05-22T09:03:56
2015-05-22T09:03:56
null
0
0
null
null
null
null
GB18030
C++
false
false
9,236
h
/*! \file UGRelLines.h * \brief 线线空间位置关系 * \author ugc team * \attention * Copyright(c) 1996-2004 SuperMap GIS Technologies,Inc.<br> * All Rights Reserved * \version $Id: UGRelLines.h,v 1.10 2007/11/02 10:20:58 qiuli Exp $ */ #if !defined(AFX_UGRELLINELINE_H__98175692_7F5B_4534_A287_7F7C990E4436__INCLUDED_) #define AFX_UGRELLINELINE_H__98175692_7F5B_4534_A287_7F7C990E4436__INCLUDED_ #include "Base/ugdefs.h" #include "Algorithm/UGPoint2D.h" namespace UGC { // 术语定义: // LineSeg: 线段,由两点组成,仅包括两个端点及其之间的部分; 两点不能相同 // Polyline: 折线, 多点组成一个连续的点串; 多点不能为同一个点 // PolyPolyline: 复杂折线, 由多个折线组成, 折线间首尾可不相交 // //! \brief 线线空间位置关系类 class ALGORITHM_API UGRelLines { private: UGRelLines(); public: // 线线基本空间关系判断 /// 完全相等 //! \brief 判断线段和线段是否相等 //! \remarks 相等: 点的个数,对应坐标值 static UGbool IsIdentical(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线和折线是否相等 //! \remarks 相等: 点的个数,对应坐标值 static UGbool IsIdentical(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); // by guohui 2007.10.16 //! \brief 判断折线和折线是否相等 //! \remarks 相等: 点的个数,对应坐标值 static UGbool IsIdentical(const UGPoint2D* pPoints1,const UGint* lPolyCount1, UGint nSubCount1, const UGPoint2D* pPoints2,const UGint* lPolyCount2, UGint nSubCount2); /// 包含 //! \brief 判断线段1是否包含线段2 //! \remarks 包含: 线段1和线段2的交集等于线段2 static UGbool IsContain(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线是否包含线段 //! \remarks 包含: 折线和线段的交集等于线段 static UGbool IsContain(const UGPoint2D* pPoints, UGint nPntCount, const UGPoint2D& pntStart, const UGPoint2D& pntEnd); static UGbool IsContain(const UGPoint2D* pPoints,const UGint* lPolyCount, UGint nSubCount, const UGPoint2D& pntStart, const UGPoint2D& pntEnd); //! \brief 判断折线1是否包含折线2 //! \remarks 包含: 折线1和折线2的交集等于折线2 static UGbool IsContain(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); // by guohui 2007.10.16 copy from UGGeoRelation::IsLineBContainLineB //! \brief 判断折线1是否包含折线2 static UGbool IsContain(const UGPoint2D* pPoints1,const UGint* lPolyCount1, UGint nSubCount1, const UGPoint2D* pPoints2,const UGint* lPolyCount2, UGint nSubCount2); // 相互包含 //! \brief 判断线段和线段是否重合 //! \remarks 重合: 两者互相包含 static UGbool IsContainEachOther(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线和折线是否重合 //! \remarks 重合: 两者互相包含 static UGbool IsContainEachOther(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); // 交叠 //! \brief 判断线段和线段是否交叠 //! \remarks 交叠: 两者交集必须有一维部分,且不能重合 static UGbool IsOverlap(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线和折线是否交叠 //! \remarks 交叠: 两者交集必须有一维部分,且不能重合 static UGbool IsOverlap(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); //! \brief 判断折线和折线是否交叠 //! \remarks 交叠: 两者交集必须有一维部分,且不能重合 static UGbool IsOverlap(const UGPoint2D* pPoints1,const UGint* lPolyCount1, UGint nSubCount1, const UGPoint2D* pPoints2,const UGint* lPolyCount2, UGint nSubCount2); // 相交 //! \brief 判断线段和线段是否相交 //! \remarks 相交: 两者的交集必须有零维部分 static UGbool IsIntersect(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2, UGdouble dTolerance=EP); //! \brief 判断折线和折线是否相交 //! \remarks 相交: 两者的交集必须有零维部分 static UGbool IsIntersect(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); //跨越 //! \brief 判断线段1是否跨越线段2 //! \remarks 跨越: 线段1被线段2分割为至少两个部分,分别位于2的两侧,且分离点不等于端点(起点or终点) static UGbool IsCross(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线1是否跨越折线2 //! \remarks 跨越: 折线1被折线2分割为至少两个部分,分别位于2的两侧,且分离点不等于端点(起点or终点) static UGbool IsCross(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); //! \brief 判断折线1是否跨越折线2 //! \remarks 跨越: 折线1被折线2分割为至少两个部分,分别位于2的两侧,且分离点不等于端点(起点or终点) static UGbool IsCross(const UGPoint2D* pPoints1,const UGint* lPolyCount1, UGint nSubCount1, const UGPoint2D* pPoints2,const UGint* lPolyCount2, UGint nSubCount2); // 相离 //! \brief 判断线段和线段是否相离 //! \remarks 相离: 两者交集为空集 static UGbool IsDisjoint(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线和折线是否相离 //! \remarks 相离: 两者交集为空集 static UGbool IsDisjoint(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); public: // 上述基本关系的组成实用关系判断 //! \brief 判断线段1是否和线段2接触 //! \remarks 接触: 交集不为空,即不相离 static UGbool IsTouch(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断折线1是否和折线2接触 //! \remarks 接触: 交集不为空,即不相离 static UGbool IsTouch(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); //! \brief 线段交集有一维部分 //! \remarks 等于 Contain(A,B) || Contain(B,A) || Overlap static UGbool IsMatch(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 线段交集有一维部分 //! \remarks 等于 Contain(A,B) || Contain(B,A) || Overlap static UGbool IsMatch(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); // add by guohui 2007.10.08 //! \brief 线段交集有一维部分 //! \remarks 等于 Contain(A,B) || Contain(B,A) || Overlap static UGbool IsMatch(const UGPoint2D* pPoints1, const UGint* pPolyCount1,UGint nSubCount1, const UGPoint2D* pPoints2, const UGint* pPolyCount2,UGint nSubCount2); //! \brief 线和线内部是否相交 //! \remarks 线内部的定义是:除了线的两个端点外的线的其他部分 static UGbool IsInteriorIntersect(const UGPoint2D* pPoints1, UGint nPntCount1, const UGPoint2D* pPoints2, UGint nPntCount2); public: // 其他一下实用判断算法 //! \brief 判断线段是否垂直, 可以没有交点 static UGbool IsPerpendicular(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断线段是否平行, 可以在同一条直线上,也可以重叠,甚至重合 static UGbool IsParallel(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 判断线段的最小距离是否在容限范围之内 static UGbool IsNear(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2, const UGdouble dDistance); public: // 内部辅助使用,空间算法库外不得使用 //! \brief 返回值精确的描述两条线段相交的情况 static UGint IntersectLineSegment(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); //! \brief 得到一条线段中距离From点很近的点,求之点离From点不超过一个单位 static UGPoint2D GetTestPoint(const UGPoint2D* pPointFrom, const UGPoint2D* pPointTo); //! \brief 线段1和线段2 是否同向 //! \remarks 矢量方向在同一个象限内 static UGbool IsSameQuadrant(const UGPoint2D& pntStart1, const UGPoint2D& pntEnd1, const UGPoint2D& pntStart2, const UGPoint2D& pntEnd2); }; } #endif // !defined(AFX_UGRELLINELINE_H__98175692_7F5B_4534_A287_7F7C990E4436__INCLUDED_)
[ "huanliang26@126.com" ]
huanliang26@126.com
6ec08f91fda9cc56e7e2757664b83fafa5d13cba
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s05/CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_22b.cpp
173c9ecbd5b871b6f29948dedca62bd83b8b4dce
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
2,578
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_22b.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_free.label.xml Template File: sources-sinks-22b.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new [] * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete [] * BadSink : Deallocate data using free() * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_array_free_int_22 { #ifndef OMITBAD /* The global variable below is used to drive control flow in the sink function. Since it is in a C++ namespace, it doesn't need a globally unique name. */ extern int badGlobal; void badSink(int * data) { if(badGlobal) { /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete [] to deallocate the memory */ free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The static variables below are used to drive control flow in the sink functions. Since they are in a C++ namespace, they don't need globally unique names. */ extern int goodB2G1Global; extern int goodB2G2Global; extern int goodG2B1Global; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ void goodB2G1Sink(int * data) { if(goodB2G1Global) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Deallocate the memory using delete [] */ delete [] data; } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ void goodB2G2Sink(int * data) { if(goodB2G2Global) { /* FIX: Deallocate the memory using delete [] */ delete [] data; } } /* goodG2B1() - use goodsource and badsink */ void goodG2B1Sink(int * data) { if(goodG2B1Global) { /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete [] to deallocate the memory */ free(data); } } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
2eeb0782191e2ad96769dbd9dcf6ffb8403f033c
a46f282294984c06cffe6056c64cd4bcdd83739a
/src/prey.cpp
c32a089bc3a2b88f78734d0fc1981167da6923d9
[]
no_license
ignatovskiy/tp-lab-7
171cb94f2f7a0e47a80be67c93b0f4f4f1486b35
f83360134344b05e72aeb9289b3e8f6a74e04162
refs/heads/master
2022-05-30T19:45:48.880696
2020-05-03T14:37:15
2020-05-03T14:37:15
259,671,912
0
0
null
2020-04-28T15:10:12
2020-04-28T15:10:11
null
UTF-8
C++
false
false
997
cpp
// // Created by Ignatovskiy Nikita on 28.04.2020. // #include "prey.h" Prey::Prey(Cell *cell): Object(cell) { this->type = ObjType::PREY; this->lifetime = LIFETIME_PREY; this->reproduceTime = REPRODUCE_TIME_PREY; } char Prey::getSymbol() { return PREY_N; } void Prey::move() { Cell* freeCell = this->cell->getNearFreeCell(); if (freeCell) { this->cell->setObject(nullptr); this->cell = freeCell; freeCell->setObject(this); } } void Prey::reproduce() { Cell* freeCell = this->cell->getNearFreeCell(); if (freeCell) { auto* childPrey = new Prey(freeCell); freeCell->setObject(childPrey); freeCell->getOcean()->spawnObject(childPrey); } } bool Prey::live() { if (!this->lifetime--) return false; move(); if (this->reproduceTime == 0) { reproduce(); this->reproduceTime = REPRODUCE_TIME_PREY; } this->reproduceTime -= 1; return true; }
[ "naignatovskiy@edu.hse.ru" ]
naignatovskiy@edu.hse.ru
cf9eb7d9ba21e81c34c4f45068d7a855d0f5ef9c
fa90921dc14b89f6ba69b7eda9e4e4c475869be2
/Semestralka/Semestralka.cpp
89e6e65bd77dfddd16fddd6276a39779a5f8aa59
[]
no_license
markolukicluk99/Semestralka---Elektronicky-Ukolovnik
f23091a97700d6c6cb36c2acd8e27e3b55dc8897
fd46a5e946a06afbdaab5cc462c99ab402d3f921
refs/heads/master
2020-09-28T09:48:02.740536
2019-12-11T15:40:52
2019-12-11T15:40:52
226,751,952
0
0
null
null
null
null
UTF-8
C++
false
false
406
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <iostream> #include <Windows.h> #include "elektronickyukolovnik.h" #include <conio.h> #include <time.h> /* SEMESTRALNI PRACE ---Elektronicky Ukolovnik--- ---Predmet: BPC-PC1T-------- ---Marko Lukic-------------- ---Veljko Lazarevic--------- ---Skupina: BPC-TLI03------- */ int main() { navigace(); return 0; }
[ "markolukicluk99@gmail.com" ]
markolukicluk99@gmail.com
e3937650d324af7467fdeb5949797c0c7332f29b
ddba92bfd56acc0a4b92f42aab45ff7e5af71ffb
/src/materials/refractive.cpp
6f60ba973ad3f1bf63a060ef782174131683892b
[]
no_license
xueliuxing28/raytracer-3
811b69fb1f952352976ea72c430242394a9b0d66
f0241c5c55401755a4c103ad2aadc18854deda21
refs/heads/master
2021-12-15T23:00:35.272719
2017-09-10T14:28:58
2017-09-10T14:28:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,037
cpp
#include "refractive.h" #include "..\utilities\random.h" Refractive::Refractive(float refraction) : refraction(refraction) { } static bool refract(const Vector3& I, const Vector3& N, float niOverNt, Vector3& refracted) { Vector3 ui = glm::normalize(I); Vector3 un = glm::normalize(N); float dt = glm::dot(ui, un); float discriminant = 1.0f - niOverNt * niOverNt * (1 - dt * dt); if (discriminant > 0) { refracted = niOverNt * (ui - N * dt) - N * glm::sqrt(discriminant); return true; } return false; } static float polyApprox(float cosine, float refraction) { float r = (1.0f - refraction) / (1.0f + refraction); r = r * r; return r + (1.0f - r) * glm::pow(1.0f - cosine, 5); } bool Refractive::scatter(const Ray &ray, const Intersection &intersection, Vector3 &attenuation, Ray &scattered) const { Vector3 outwardNormal; Vector3 reflected = glm::reflect(ray.direction, intersection.normal); float niOverNt; attenuation = Vector3(1, 1, 1); float cosine; if (glm::dot(ray.direction, intersection.normal) > 0) { outwardNormal = -intersection.normal; niOverNt = refraction; cosine = glm::dot(ray.direction, intersection.normal) / glm::length(ray.direction); cosine = glm::sqrt(1.0f - refraction * refraction * (1.0f - cosine * cosine)); } else { outwardNormal = intersection.normal; niOverNt = 1.0f / refraction; cosine = -glm::dot(ray.direction, intersection.normal) / glm::length(ray.direction); } Vector3 refracted; float prob; if (refract(ray.direction, outwardNormal, niOverNt, refracted)) { prob = polyApprox(cosine, refraction); } else { scattered = Ray(intersection.point, reflected); return true; } if (Random::random() < prob) { scattered = Ray(intersection.point, reflected); } else { scattered = Ray(intersection.point, refracted); } return true; }
[ "ruidanielcaridade@gmail.com" ]
ruidanielcaridade@gmail.com
47df21e4eb4cbf0b1a6a9bf34dc10e175fdec0d7
393125abdafa8288e155780b3101263bfcd2e0c0
/leap year.cpp
1d58af5768c4395bdf5e1bff445606d2dbad7a8f
[]
no_license
SraboniIbnatAddri/Basic-problem-solve-in-cpp
6aa9490230f267f7e9fe798d2d94966fb371043b
be96afdca475a173cd39478337baa9f018f28fb5
refs/heads/master
2021-05-25T16:57:34.296694
2020-04-15T06:47:57
2020-04-15T06:47:57
253,830,433
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include<iostream> #include<conio.h> using namespace std; int main() { int year; cout<<"Enter any year: "; cin>>year; if(year%400==0) { cout<<"Leap year"; } else if (year%4==0 && year%100!=0) { cout<<"Leap year"; } else{ cout<<"Not leap year"; } getch(); }
[ "SraboniibnatAddri.com" ]
SraboniibnatAddri.com
47aee11766a008b87f242878cb880329e2a2a778
3cb118a5946bd8417e8fbe25207eff0817a98258
/Classes/ScheduleCounterProtocol.h
ca33274dc4cbca7e5b14b146c6fd7fbe3a8d7207
[]
no_license
JimiWasBornIn1988/FishingJoy
7a93c431ee4895cfa637c3fc72a304a012c17cc2
02814c21e61c5630b04fda9d29b5a6b02c8ba761
refs/heads/master
2021-01-19T07:35:33.825718
2014-06-13T05:44:32
2014-06-13T05:44:32
20,791,418
0
1
null
null
null
null
GB18030
C++
false
false
402
h
#ifndef __FishingJoy__ScheduleCounterProtocol__ #define __FishingJoy__ScheduleCounterProtocol__ class ScheduleCounterDelegate { public: /** * @brief Required */ virtual void scheduleTimeUp() = 0; /** * @brief Optional * * @param number 需要设置的数字 */ virtual void setScheduleNumber(int number){ return; }; }; #endif /* defined(__FishingJoy__ScheduleCounterProtocol__) */
[ "rockblue1988@gmail.com" ]
rockblue1988@gmail.com
ea24b38b6e8a1ae7ae4ccef2aff9b972042006c1
2dc9ab0ec71fd31900173fb15a6f2c85753180c4
/ui/base/x/x11_drag_drop_client.h
9a0df14cf71857c1e23b948ee3e0feea800b579e
[ "BSD-3-Clause" ]
permissive
Forilan/chromium
ec337c30d23c22d11fbdf814a40b9b4c26000d78
562b20b68672e7831054ec8f160d5f7ae940eae4
refs/heads/master
2023-02-28T02:43:17.744240
2020-05-12T02:23:44
2020-05-12T02:23:44
231,539,724
0
0
BSD-3-Clause
2020-05-12T02:23:45
2020-01-03T07:52:37
null
UTF-8
C++
false
false
9,709
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_BASE_X_X11_DRAG_DROP_CLIENT_H_ #define UI_BASE_X_X11_DRAG_DROP_CLIENT_H_ #include <vector> #include "base/component_export.h" #include "base/timer/timer.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/base/x/selection_utils.h" #include "ui/base/x/x11_drag_context.h" #include "ui/base/x/x11_topmost_window_finder.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/x/x11.h" namespace ui { class OSExchangeData; class XOSExchangeDataProvider; // Converts the current set of X masks into the set of ui::EventFlags. COMPONENT_EXPORT(UI_BASE_X) int XGetMaskAsEventFlags(); // Handles XDND (X11 drag and drop protocol) for the given window. // // Doesn't fetch XDND events from the event source; those should be taken by // the client and fed to |OnXdnd...| and |OnSelectionNotify| methods. class COMPONENT_EXPORT(UI_BASE_X) XDragDropClient { public: // Handlers and callbacks that should be implemented at the consumer side. class Delegate { public: // Creates the window finder. virtual std::unique_ptr<XTopmostWindowFinder> CreateWindowFinder() = 0; // Updates the drag status by the new position. Returns the drag operation // possible at that position. // // Handling XdndPosition can be paused while waiting for more data; this is // called either synchronously from OnXdndPosition, or asynchronously after // we've received data requested from the other window. virtual int UpdateDrag(const gfx::Point& screen_point) = 0; // Updates the mouse cursor shape. virtual void UpdateCursor( DragDropTypes::DragOperation negotiated_operation) = 0; // Called when data from another application enters the window. virtual void OnBeginForeignDrag(XID window) = 0; // Called when data from another application is about to leave the window. virtual void OnEndForeignDrag() = 0; // Called just before the drag leaves the window. virtual void OnBeforeDragLeave() = 0; // Drops data at the current location and returns the resulting operation. virtual int PerformDrop() = 0; // Called to end the move loop that is maintained by the subclass. virtual void EndMoveLoop() = 0; protected: virtual ~Delegate() = default; }; XDragDropClient(Delegate* delegate, Display* xdisplay, XID xwindow); virtual ~XDragDropClient(); XDragDropClient(const XDragDropClient&) = delete; XDragDropClient& operator=(const XDragDropClient&) = delete; XID xwindow() const { return xwindow_; } XDragContext* target_current_context() { return target_current_context_.get(); } const XOSExchangeDataProvider* source_provider() const { return source_provider_; } int current_modifier_state() const { return current_modifier_state_; } // Handling XdndPosition can be paused while waiting for more data; this is // called either synchronously from OnXdndPosition, or asynchronously after // we've received data requested from the other window. void CompleteXdndPosition(XID source_window, const gfx::Point& screen_point); void ProcessMouseMove(const gfx::Point& screen_point, unsigned long event_time); // During the blocking StartDragAndDrop() call, this converts the views-style // |drag_operation_| bitfield into a vector of Atoms to offer to other // processes. std::vector<Atom> GetOfferedDragOperations() const; // Tries to handle the XDND event. Returns true for all known event types: // XdndEnter, XdndLeave, XdndPosition, XdndStatus, XdndDrop, and XdndFinished; // returns false if an event of an unexpected type has been passed. bool HandleXdndEvent(const XClientMessageEvent& event); // These |Handle...| methods essentially implement the // views::X11MoveLoopDelegate interface. void HandleMouseMovement(const gfx::Point& screen_point, int flags, base::TimeTicks event_time); void HandleMouseReleased(); void HandleMoveLoopEnded(); // Called when XSelection data has been copied to our process. void OnSelectionNotify(const XSelectionEvent& xselection); // Resets the drag state so the object is ready to handle the drag. Sets // X window properties so that the desktop environment is aware of available // actions. Sets |source_provider_| so properties of dragged data can be // queried afterwards. Should be called before entering the main drag loop. void InitDrag(int operation, const OSExchangeData* data); // Cleans up the drag state after the drag is done. Removes the X window // properties related to the drag operation. Should be called after exiting // the main drag loop. void CleanupDrag(); protected: enum class SourceState { // |source_current_window_| will receive a drop once we receive an // XdndStatus from it. kPendingDrop, // The move looped will be ended once we receive XdndFinished from // |source_current_window_|. We should not send XdndPosition to // |source_current_window_| while in this state. kDropped, // There is no drag in progress or there is a drag in progress and the // user has not yet released the mouse. kOther, }; DragDropTypes::DragOperation negotiated_operation() const { return negotiated_operation_; } // Updates |current_modifier_state_| with the given set of flags. void UpdateModifierState(int flags); // Resets the drag context. Calls |OnEndForeignDrag()| if necessary. void ResetDragContext(); void StopRepeatMouseMoveTimer(); // Start timer to end the move loop if the target is too slow to respond after // the mouse is released. void StartEndMoveLoopTimer(); void StopEndMoveLoopTimer(); private: // These methods handle the various X11 client messages from the platform. void OnXdndEnter(const XClientMessageEvent& event); void OnXdndPosition(const XClientMessageEvent& event); void OnXdndStatus(const XClientMessageEvent& event); void OnXdndLeave(const XClientMessageEvent& event); void OnXdndDrop(const XClientMessageEvent& event); void OnXdndFinished(const XClientMessageEvent& event); // Creates an XEvent and fills it in with values typical for XDND messages: // the type of event is set to ClientMessage, the format is set to 32 (longs), // and the zero member of data payload is set to |xwindow_|. All other data // members are zeroed, as per XDND specification. XEvent PrepareXdndClientMessage(const char* message, XID recipient) const; // Finds the topmost X11 window at |screen_point| and returns it if it is // Xdnd aware. Returns x11::None otherwise. // Virtual for testing. virtual XID FindWindowFor(const gfx::Point& screen_point); // Sends |xev| to |xid|, optionally short circuiting the round trip to the X // server. // Virtual for testing. virtual void SendXClientEvent(XID xid, XEvent* xev); void SendXdndEnter(XID dest_window, const std::vector<Atom>& targets); void SendXdndPosition(XID dest_window, const gfx::Point& screen_point, unsigned long event_time); void SendXdndLeave(XID dest_window); void SendXdndDrop(XID dest_window); // We maintain a mapping of live XDragDropClient objects to their X11 windows, // so that we'd able to short circuit sending X11 messages to windows in our // process. static XDragDropClient* GetForWindow(XID window); void EndMoveLoop(); Delegate* const delegate_; Display* const xdisplay_; const XID xwindow_; // Target side information. std::unique_ptr<XDragContext> target_current_context_; // Source side information. XID source_current_window_ = x11::None; SourceState source_state_ = SourceState::kOther; const XOSExchangeDataProvider* source_provider_ = nullptr; // The operation bitfield as requested by StartDragAndDrop. int drag_operation_ = 0; // The modifier state for the most recent mouse move. Used to bypass an // asynchronous roundtrip through the X11 server. int current_modifier_state_ = 0; // We offer the other window a list of possible operations, // XdndActionsList. This is the requested action from the other window. This // is DRAG_NONE if we haven't sent out an XdndPosition message yet, haven't // yet received an XdndStatus or if the other window has told us that there's // no action that we can agree on. DragDropTypes::DragOperation negotiated_operation_ = DragDropTypes::DRAG_NONE; // In the Xdnd protocol, we aren't supposed to send another XdndPosition // message until we have received a confirming XdndStatus message. bool waiting_on_status_ = false; // If we would send an XdndPosition message while we're waiting for an // XdndStatus response, we need to cache the latest details we'd send. std::unique_ptr<std::pair<gfx::Point, unsigned long>> next_position_message_; // Reprocesses the most recent mouse move event if the mouse has not moved // in a while in case the window stacking order has changed and // |source_current_window_| needs to be updated. base::OneShotTimer repeat_mouse_move_timer_; // Ends the move loop if the target is too slow to respond after the mouse is // released. base::OneShotTimer end_move_loop_timer_; // When the mouse is released, we need to wait for the last XdndStatus message // only if we have previously received a status message from // |source_current_window_|. bool status_received_since_enter_ = false; }; } // namespace ui #endif // UI_BASE_X_X11_DRAG_DROP_CLIENT_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
dfa115052195991f7b031fa100485979881306a2
1372aae72fb3bfcc3d3ee1b65139b011aafde9f6
/Practice/20/C++/Project Truth in vine/Project Truth in vine/Project Truth in vine.cpp
9220880e51f9e2704efedab92dedd62f42351007
[]
no_license
NeutralMoon/Programming
03da82e97848096c4db104641eb8883d40ff8815
7317830236bb1b3a0c6396ebf3d58f03323a35a6
refs/heads/master
2023-04-06T19:51:31.891978
2021-04-18T19:44:04
2021-04-18T19:44:04
296,363,269
0
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
#include <iostream> #include <vector> using namespace std; int main() { int groshi, n, k, b = 0; cin >> groshi >> n; vector<string> napitki(n); vector<int> price(n); vector<int> v(n); vector<int> rez(n); vector<int> litr(n); vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> napitki[i] >> price[i] >> v[i]; rez[i] = groshi / price[i]; litr[i] = rez[i] * v[i]; if (litr[i] == 0) b++; } if (b == n) { cout << -1 << endl; return(0); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (litr[i] > litr[j]) k = i; } } cout << napitki[k] << " " << rez[k] << " " << endl << litr[k] << endl << groshi - (price[k] * rez[k]) << endl; return(0); }
[ "4Krio9Gen3@gmail.com" ]
4Krio9Gen3@gmail.com
547f3d9d8c3fa421255558309e3c524fc7f7da60
378d404d4b8ec12dd9548470fa3b33d3dec087ff
/Graph/DAG/lib/verify/AOJ_GRL_4_A.cpp
be319361a391ee158d6b90f1428b6ed8bb0c9e99
[]
no_license
kk-katayama/com_pro
d0e8871aff88e7939d439c37f9cafd2d11a870fc
a3a6a3bcb846e2eded42d1fed5d9495e53a73e41
refs/heads/master
2021-06-25T18:49:35.320092
2021-02-05T06:50:38
2021-02-05T06:50:38
200,748,000
0
0
null
null
null
null
UTF-8
C++
false
false
3,391
cpp
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <utility> #include <set> #include <map> #include <cmath> #include <queue> #include <cstdio> #include <limits> #define rep(i,n) for(int i = 0; i < n; ++i) #define rep1(i,n) for(int i = 1; i <= n; ++i) using namespace std; template<class T>bool chmax(T &a, const T &b) { if(a < b){ a = b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if(a > b){ a = b; return 1; } return 0; } using ll = long long; using ld = long double; using pi = pair<int,int>; using pl = pair<ll,ll>; using vi = vector<int>; using vii = vector<vi>; using vl = vector<ll>; using vll = vector<vl>; const int inf = numeric_limits<int>::max(); const ll infll = numeric_limits<ll>::max(); //**************************************** // Graph template //**************************************** // status of edge template <typename X> struct Edge{ int from; int to; X cost; Edge() = default; Edge(int from, int to, X cost) : from(from), to(to), cost(cost) {} }; // status of node template <typename X> struct Node{ int idx; vector<Edge<X>> edge, rev; Node() = default; explicit Node(int idx) : idx(idx) {} }; template <typename X> class Graph{ private: int n; // number of node int m; // number of edge vector<Node<X>> node; void Init_Node() { rep(i,n) node.emplace_back(i); } public: explicit Graph(int n) : n(n) { Init_Node(); } // edges have no-weight Graph(int n, int m, vector<int> from, vector<int> to) : n(n), m(m) { Init_Node(); rep(i,m) { add_edge(from[i], to[i]); // add_edge(to[i], from[i]); add_rev(to[i], from[i]); } } // edges have weight Graph(int n, int m, vector<int> from, vector<int> to, vector<X> cost) : n(n), m(m) { Init_Node(); rep(i,m) { add_edge(from[i], to[i], cost[i]); // add_edge(to[i], from[i], cost[i]); add_rev(to[i], from[i], cost[i]); } } void add_edge(int from, int to, X cost = 1) { node[from].edge.emplace_back(from, to, cost); } void add_rev(int from, int to, X cost = 1) { node[from].rev.emplace_back(from, to, cost); } void scc() { vector<bool> used(n, false); vi vs; // 帰りがけ順の並び auto dfs = [&](auto self, int v) ->void{ used[v] = true; for(auto next: node[v].edge) { int w = next.to; if( !used[w] ) self(self, w); } vs.push_back(v); }; rep(v, n) { if( !used[v] ) dfs(dfs, v); } used.assign(n, false); vi cmp(n); // 属する強連結成分のトポロジカル順序 cmp[v] = x なら頂点v はx 番目 auto rdfs = [&](auto self, int v, int k) ->void{ used[v] = true; cmp[v] = k; for(auto next: node[v].rev) { int w = next.to; if( !used[w] ) self(self, w, k); } }; int j = 0; for (int i = n - 1; i >= 0; --i) { if( !used[vs[i]] ) rdfs(rdfs, vs[i], j++); } // sccを使って何かしたいならここに書いたらいいよ vector<bool> f(n, false); rep(i,n) { if(f[cmp[i]]) { cout << 1 << "\n"; return; } f[cmp[i]] = true; } cout << 0 << "\n"; } }; int main(){ int n,m; cin >> n >> m; vi a(m), b(m); rep(i,m) cin >> a[i] >> b[i]; Graph<int> gp(n, m, a, b); gp.scc(); return 0; }
[ "galapagos4444@gmail.com" ]
galapagos4444@gmail.com
1d045960733868a00b79a308ae3f70517ac92015
9c27f0843a24dee80067c28cef96a502662865d5
/Graphics.cpp
55519d81edbe8fdd190ec7c314bd2281efb059c8
[ "LicenseRef-scancode-public-domain" ]
permissive
ixchow/Checkpointable-Box2D
21400ca5bf60c617129469b997ced999619c50b8
c15c0bb26492b650c9c253cb62f425883a46939d
refs/heads/master
2016-09-06T02:22:43.423900
2012-05-22T13:17:32
2012-05-22T13:17:32
3,384,439
1
0
null
null
null
null
UTF-8
C++
false
false
2,618
cpp
#include "Graphics.hpp" #include <iostream> #include <list> #include <utility> #include <assert.h> using std::string; using std::cerr; using std::endl; using std::list; using std::pair; using std::make_pair; namespace Graphics { Vector2ui screen_size = make_vector(800U, 600U); bool fullscreen = false; namespace { //private-type variables. SDL_Surface *surface = NULL; bool sub_inited = false; bool inited = false; } //end anon namespace bool init(int flags) { if (SDL_InitSubSystem(SDL_INIT_VIDEO) == 0) { sub_inited = true; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8); if (flags & NEED_ACCUM) { SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 16); SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 16); SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 16); } //SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8); //SDL_GL_SetAttribute( SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 24); if (flags & NEED_STENCIL) { SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 8); } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1); if (flags & WANT_VSYNC) { #ifdef SDL_GL_SWAP_CONTROL SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 1); #else cerr << "Using a version of SDL that doesn't support VSYNC." << endl; #endif } if (flags & WANT_MULTISAMPLE4) { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 4 ); } if (flags & WANT_MULTISAMPLE8) { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 8 ); } if (flags & WANT_MULTISAMPLE16) { SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 16 ); } if (fullscreen) { surface = SDL_SetVideoMode(screen_size.x, screen_size.y, 24, SDL_OPENGL | SDL_FULLSCREEN); } else { surface = SDL_SetVideoMode(screen_size.x, screen_size.y, 24, SDL_OPENGL); } if (surface) { inited = true; } else { cerr << "Could not create video surface: " << SDL_GetError() << endl; } } else { cerr << "Could not init video: " << SDL_GetError() << endl; } if (sub_inited && !inited) { deinit(); } return inited; } void deinit() { if (sub_inited) { SDL_QuitSubSystem(SDL_INIT_VIDEO); sub_inited = false; inited = false; surface = NULL; } } void gl_errors(string const &where) { GLuint err; while ((err = glGetError()) != GL_NO_ERROR) { cerr << "(in " << where << ") OpenGL error #" << err << ": " << gluErrorString(err) << endl; } } }
[ "jmccann@cs.cmu.edu" ]
jmccann@cs.cmu.edu
2232cbdf64be7b2adc44dbde3e991c1448cc42a4
b1af8bb863a6730e6e4e93129efbad89d33cf509
/SDK/SCUM_UI_Loading_classes.hpp
0436aefffcf7bd841a49a4a6fcdab2552fc85630
[]
no_license
frankie-11/SCUM_SDK7.13.2020
b3bbd8fb9b6c03120b865a6254eca6a2389ea654
7b48bcf9e8088aa8917c07dd6756eac90e3f693a
refs/heads/master
2022-11-16T05:48:55.729087
2020-07-13T23:48:50
2020-07-13T23:48:50
279,433,512
0
1
null
null
null
null
UTF-8
C++
false
false
2,539
hpp
#pragma once // SCUM (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass UI_Loading.UI_Loading_C // 0x0018 (0x0268 - 0x0250) class UUI_Loading_C : public ULoadingScreen { public: class UHeartbeatWidget* HeartbeatWidget_1; // 0x0250(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* Image_37; // 0x0258(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* Image_38; // 0x0260(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass UI_Loading.UI_Loading_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "60810131+frankie-11@users.noreply.github.com" ]
60810131+frankie-11@users.noreply.github.com
1ba94bd84e4edf0e8bc8065578d0b33104e1b354
520647be9af9b8b4f5ed9f32e53c8fec1407ef8b
/challenge/jul2020/day2.cpp
41736344ac466d33a9dba8413d33659c2b625abc
[]
no_license
gxyau/leetcode
0419453affec44a6520859f6a6f07701d204b14d
61e966ab3d6182c9d10a8f8f9aabf2717ea4c23e
refs/heads/master
2021-06-27T00:39:33.544665
2020-09-20T21:15:32
2020-09-20T21:15:32
149,101,979
0
0
null
2020-09-20T21:15:33
2018-09-17T09:34:17
C++
UTF-8
C++
false
false
1,998
cpp
// Day 2, Binary Tree Level Order Traversal II #include <algorithm> #include <iostream> #include <queue> #include <vector> using std::queue; using std::vector; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class SolutionDay2 { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { if (root == nullptr) return vector<vector<int>> (0); vector<vector<int>> reversed; vector<int> level; queue<TreeNode*> q1, q2; q1.push(root); TreeNode* ptr; while (!q1.empty() || !q2.empty()) { if (!q1.empty()) { ptr = q1.front(); q1.pop(); level.push_back(ptr->val); if (ptr->left) q2.push(ptr->left); if (ptr->right) q2.push(ptr->right); } else { // q2 not empty q1 = q2; q2 = queue<TreeNode*>(); reversed.push_back(level); level.resize(0); } } reversed.push_back(level); // Two queues, level traversal std::reverse(reversed.begin(), reversed.end()); return reversed; } }; int main() { SolutionDay2 sol; TreeNode* root; // Test case 1 root = new TreeNode(3); root->left = new TreeNode(9); root->right = new TreeNode(20); root->right->left = new TreeNode(15); root->right->right = new TreeNode(7); vector<vector<int>> reversed = sol.levelOrderBottom(root); // Printing levels std::cout << "The levels are: \n"; for (auto vec : reversed) { for (auto x : vec) { std::cout << x << " "; } std::cout << "\n\n"; } // Compile successful return 0; }
[ "GuoXian.Yau@gmail.com" ]
GuoXian.Yau@gmail.com
4a04e7e0cb0c08844add6870ccf131c1733d63ae
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/new_hunk_5849.cpp
1f5257514043521d83e33da54cab735b981a06dd
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
156
cpp
if (offset <= ceil_offset) { if (nongit_ok) { if (chdir(cwd)) die_errno("Cannot come back to cwd"); *nongit_ok = 1; return NULL; }
[ "993273596@qq.com" ]
993273596@qq.com
3743dcde03a91a34ba97d4a1649e43ffae61c39e
76ba685a8380e6aa62687db8ce2d8037caecfe23
/merkaba/DisplayBuffers.h
6110250548e84434e7d6d3d8c516a2c788195b3a
[]
no_license
iceboundflame/merkaba-teensy
f4d092f671fafd6c7332dca3a54f3c7050933482
3210ed8bfd791f26ecbf2aa135824b6020d5850d
refs/heads/master
2020-05-31T22:50:30.328833
2019-05-19T01:28:17
2019-05-19T01:28:17
190,527,922
1
0
null
null
null
null
UTF-8
C++
false
false
2,685
h
#pragma once #include <vector> #define __ASSERT_USE_STDERR #include <assert.h> #include <Arduino.h> #include "Streaming.h" #include "Display.h" /// // Drawing utils inline int revIndex(int nLeds, int i, bool rev) { return rev ? nLeds - 1 - i : i; } inline CRGB& rev(CRGBSet leds, int i, bool rev) { return rev ? leds[leds.size() - 1 - i] : leds[i]; } //// Warning: 'rev' doesn't work if CRGBSet is reversed! //void drawBar(CRGBSet leds, CRGB color, float len, bool rev=false) { // len = min(len, leds.size()); // int lenFloor = floor(len); // int lenCeil = ceil(len); // //// if (rev) //// leds = leds(leds.size() - 1, 0); // // if (lenFloor > 0) { // leds(revIndex(leds, 0, rev), // revIndex(leds, lenFloor - 1, rev)).fill_solid(color); // } // if (lenCeil != lenFloor) { // int i = revIndex(leds, lenCeil - 1, rev); // leds[i] = color; // leds[i].nscale8((len - lenFloor) * 255); // } //} // //void drawCenterBar(CRGBSet leds, CRGB color, float len) { // // FIXME: Odd #s? //// drawBar( //// CRGBSet(leds, leds.size()/2-1, 0), //// color, len/2); // CRGBSet fwdHalf(leds, leds.size()/2, leds.size()-1); // drawBar(fwdHalf, color, len/2); // CRGBSet backHalf(leds, 0, leds.size()/2-1); // drawBar(backHalf, color, len/2, true); //// backHalf = fwdHalf; //} ///////// class Segment { public: int segmentIdx; bool reverse; // to match structure diagram, segmentNum is 1-based. // but segmentIdx is 0-based. Segment(int segmentNum_, bool reverse_) : segmentIdx(segmentNum_-1), reverse(reverse_) { } CRGBSet raw() { return gDisplay.getRawSegment(segmentIdx); } CRGB& operator[](int led) { return rev(raw(), led, reverse); } int ledToRawFullBufIndex(int led) { return segmentIdx * N_PER_SEGMENT + revIndex(N_PER_SEGMENT, led, reverse); } void copyFrom(CRGBSet& set) { assert(set.size() == N_PER_SEGMENT); for (int i = 0 ; i < N_PER_SEGMENT; ++i) { operator[](i) = set[i]; } } }; extern Segment gAllSegments[]; extern Segment* const gOctaSegments; extern Segment* const gMiniTetraSegments; extern std::vector<std::vector<Segment>> gOrbits; class MiniTetraLegsByHeightBuffer { CRGB data_[N_PER_SEGMENT]; public: CRGBSet data() { // top to bottom return CRGBSet(data_, N_PER_SEGMENT); } // mini tetras in [0..7]: 0-3 = down tetra, 4-7 = up tetra void apply(Display* display, std::vector<int>& miniTetras) { CRGBSet x = data(); for (int miniTetra : miniTetras) { for (int segment = 0; segment < 3; segment++) { gMiniTetraSegments[miniTetra * 3 + segment].copyFrom(x); } } } };
[ "dliu@pinterest.com" ]
dliu@pinterest.com
09c868cbde2a7f570385d113ac7d1f8e38ef9b39
61704d40a31683c186c21faed860055952da04f8
/modules/contour/include/contour.h
341cd6c7cd8c4c12b0bcf68653dd08d6a45953dd
[]
no_license
ThisIsBrain/ucv
b1e3dccd6db0136ed521ecf0c2ae7f59ec55191f
5402fbfa6fe5a1b979a05368b272a6c92f5c79b3
refs/heads/master
2021-01-22T01:28:24.049213
2015-04-14T21:07:26
2015-04-14T21:07:26
33,527,554
0
0
null
null
null
null
UTF-8
C++
false
false
1,662
h
#ifndef CONTOUR_H #define CONTOUR_H #include "ucv.h" #include "opencv_methods.h" namespace ucv { //поиск контуров void findContours( IplImage* src, //исходное контурное изобрвжение ContourStorage* contours //указаетль на хранилеще контуров ); //соседний контурный пиксель //ВОЗВРАЩАЕТ: false - если нет соседних точек inline bool NEIGHBOR_PIXEL( IplImage* src, //исходное контурное изображение CvPoint* pt //указатель на исходную точку, сюда же будет записана координата соседней точки ); //Линеная аппроксимация (Douglas-Peucker algorithm) void approxContoursDp( ucv::Contour* contour, //указатель на исходный контур ucv::DominantPoints* dominantPoints, //указатель на массив куда будут записаны доминирующие точки ucv::DominantPointsIt beginNode, //начало отрезка контура ucv::DominantPointsIt endNode, //конец отрезка контура float eps //точность аппроксимации в пикселях ); //отрисовка контура на изображении void drawContour( IplImage* src, //исходное изображение ucv::Contour* contour, //контур CvScalar color //цвет контура ); } #endif /*End of file contour.h*/
[ "raketomania@yandex.ru" ]
raketomania@yandex.ru
cae538ab9f8f81168c7106a07e397dcf4c52419d
f9c0e72964954dc9a2f497dbaea8faa9da49e538
/src/blst_evm384_no_asm.cpp
3d91dbe800083fc781a61c836e35535b290e6aaf
[ "Apache-2.0" ]
permissive
jwasinger/blst_evm384
6206b0056f2f64e4956aa55b4abdd95e65fdae8f
5333351c32b662240a43947d9998231fa389be38
refs/heads/main
2023-01-06T14:34:07.677083
2020-11-10T16:40:56
2020-11-10T16:40:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,700
cpp
// Copyright Supranational LLC // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <cstdint> #include "blst_evm384.h" void add_mod_384_no_asm(vec384 ret, const vec384 a, const vec384 b, const vec384 p) { __uint128_t limbx; uint64_t mask, carry, borrow; vec384 tmp; std::size_t i; for (carry=0, i=0; i<6; i++) { limbx = a[i] + (b[i] + (__uint128_t)carry); tmp[i] = (uint64_t)limbx; carry = (uint64_t)(limbx >> 64); } for (borrow=0, i=0; i<6; i++) { limbx = tmp[i] - (p[i] + (__uint128_t)borrow); ret[i] = (uint64_t)limbx; borrow = (uint64_t)(limbx >> 64) & 1; } mask = carry - borrow; for(i=0; i<6; i++) ret[i] = (ret[i] & ~mask) | (tmp[i] & mask); } void sub_mod_384_no_asm(vec384 ret, const vec384 a, const vec384 b, const vec384 p) { __uint128_t limbx; uint64_t mask, carry, borrow; std::size_t i; for (borrow=0, i=0; i<6; i++) { limbx = a[i] - (b[i] + (__uint128_t)borrow); ret[i] = (uint64_t)limbx; borrow = (uint64_t)(limbx >> 64) & 1; } mask = 0 - borrow; for (carry=0, i=0; i<6; i++) { limbx = ret[i] + ((p[i] & mask) + (__uint128_t)carry); ret[i] = (uint64_t)limbx; carry = (uint64_t)(limbx >> 64); } } void mul_mont_384_no_asm(vec384 ret, const vec384 a, const vec384 b, const vec384 p, uint64_t n0) { __uint128_t limbx; uint64_t mask, borrow, mx, hi, tmp[7], carry; std::size_t i, j; for (mx=b[0], hi=0, i=0; i<6; i++) { limbx = (mx * (__uint128_t)a[i]) + hi; tmp[i] = (uint64_t)limbx; hi = (uint64_t)(limbx >> 64); } mx = n0*tmp[0]; tmp[i] = hi; for (carry=0, j=0; ; ) { limbx = (mx * (__uint128_t)p[0]) + tmp[0]; hi = (uint64_t)(limbx >> 64); for (i=1; i<6; i++) { limbx = (mx * (__uint128_t)p[i] + hi) + tmp[i]; tmp[i-1] = (uint64_t)limbx; hi = (uint64_t)(limbx >> 64); } limbx = tmp[i] + (hi + (__uint128_t)carry); tmp[i-1] = (uint64_t)limbx; carry = (uint64_t)(limbx >> 64); if (++j==6) break; for (mx=b[j], hi=0, i=0; i<6; i++) { limbx = (mx * (__uint128_t)a[i] + hi) + tmp[i]; tmp[i] = (uint64_t)limbx; hi = (uint64_t)(limbx >> 64); } mx = n0*tmp[0]; limbx = hi + (__uint128_t)carry; tmp[i] = (uint64_t)limbx; carry = (uint64_t)(limbx >> 64); } for (borrow=0, i=0; i<6; i++) { limbx = tmp[i] - (p[i] + (__uint128_t)borrow); ret[i] = (uint64_t)limbx; borrow = (uint64_t)(limbx >> 64) & 1; } mask = carry - borrow; for(i=0; i<6; i++) ret[i] = (ret[i] & ~mask) | (tmp[i] & mask); }
[ "sean@supranational.net" ]
sean@supranational.net
5afe958a6852f10266302b9fe80d2d99d58dd6fb
f84a0ee6bee670736b64427b93d5141061be22ba
/codeforces/818/B.cpp
3d23368e3bebee7f0162e41449df07c4b07fdc97
[]
no_license
joseleite19/competitive-programming
eaeb03b6a250619a4490f5da5274da3ba8017b62
f00e7a6cb84d7b06b09d00fffd7c5ac68a7b99e3
refs/heads/master
2020-04-15T14:05:40.261419
2017-12-19T18:34:42
2017-12-19T18:34:42
57,311,825
1
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
#include <bits/stdc++.h> using namespace std; int n, m, l[222], v[222]; int main(){ scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) scanf("%d", l+i); for(int i = 0; i+1 < m; i++){ int tmp = (l[i+1] - l[i]); if(tmp <= 0){ tmp += n; } if(v[ l[i] ] && v[ l[i] ] != tmp) return printf("-1\n"), 0; v[ l[i] ] = tmp; } set<int> s; for(int i = 1; i <= n; i++) s.insert(i); for(int i = 1; i <= n; i++) if(v[i]){ if(!s.count(v[i])) return printf("-1\n"), 0; s.erase(v[i]); } for(int i = 1; i <= n; i++) if(!v[i]){ v[i] = *s.begin(); s.erase(s.begin()); } for(int i = 1; i <= n; i++) printf("%d ", v[i]); printf("\n"); return 0; }
[ "leite.josemarcos@gmail.com" ]
leite.josemarcos@gmail.com
1bfc2b4f7d4e15bdfa17fe99e0b4f2639054aec5
3f5bec0a4904ab116c6c2d58315e9c15da0a5d76
/moveit/moveit_ros/perception/depth_image_octomap_updater/src/depth_image_octomap_updater.cpp
11ca20cfa8d62fbb708dccab3221045fed394b35
[ "BSD-3-Clause" ]
permissive
Subinsdev/src
ef18fb457df424c2122e7e46457239d8877dcd94
1d794ed892d93f56fc72daca9e3b193878f24e78
refs/heads/main
2023-04-12T10:09:25.141151
2021-05-16T18:34:33
2021-05-16T18:34:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,920
cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * 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 Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan, Suat Gedikli */ #include <moveit/depth_image_octomap_updater/depth_image_octomap_updater.h> #include <moveit/occupancy_map_monitor/occupancy_map_monitor.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2/LinearMath/Vector3.h> #include <tf2/LinearMath/Transform.h> #include <geometric_shapes/shape_operations.h> #include <sensor_msgs/image_encodings.h> #include <XmlRpcException.h> #include <stdint.h> #include <memory> namespace occupancy_map_monitor { DepthImageOctomapUpdater::DepthImageOctomapUpdater() : OccupancyMapUpdater("DepthImageUpdater") , nh_("~") , input_depth_transport_(nh_) , model_depth_transport_(nh_) , filtered_depth_transport_(nh_) , filtered_label_transport_(nh_) , image_topic_("depth") , queue_size_(5) , near_clipping_plane_distance_(0.3) , far_clipping_plane_distance_(5.0) , shadow_threshold_(0.04) , padding_scale_(0.0) , padding_offset_(0.02) , max_update_rate_(0) , skip_vertical_pixels_(4) , skip_horizontal_pixels_(6) , image_callback_count_(0) , average_callback_dt_(0.0) , good_tf_(5) , // start optimistically, so we do not output warnings right from the beginning failed_tf_(0) , K0_(0.0) , K2_(0.0) , K4_(0.0) , K5_(0.0) { } DepthImageOctomapUpdater::~DepthImageOctomapUpdater() { stopHelper(); } bool DepthImageOctomapUpdater::setParams(XmlRpc::XmlRpcValue& params) { try { sensor_type_ = (std::string)params["sensor_type"]; if (params.hasMember("image_topic")) image_topic_ = (std::string)params["image_topic"]; if (params.hasMember("queue_size")) queue_size_ = (int)params["queue_size"]; readXmlParam(params, "near_clipping_plane_distance", &near_clipping_plane_distance_); readXmlParam(params, "far_clipping_plane_distance", &far_clipping_plane_distance_); readXmlParam(params, "shadow_threshold", &shadow_threshold_); readXmlParam(params, "padding_scale", &padding_scale_); readXmlParam(params, "padding_offset", &padding_offset_); if (params.hasMember("max_update_rate")) readXmlParam(params, "max_update_rate", &max_update_rate_); readXmlParam(params, "skip_vertical_pixels", &skip_vertical_pixels_); readXmlParam(params, "skip_horizontal_pixels", &skip_horizontal_pixels_); if (params.hasMember("filtered_cloud_topic")) filtered_cloud_topic_ = static_cast<const std::string&>(params["filtered_cloud_topic"]); } catch (XmlRpc::XmlRpcException& ex) { ROS_ERROR("XmlRpc Exception: %s", ex.getMessage().c_str()); return false; } return true; } bool DepthImageOctomapUpdater::initialize() { tf_buffer_ = monitor_->getTFClient(); free_space_updater_.reset(new LazyFreeSpaceUpdater(tree_)); // create our mesh filter mesh_filter_.reset(new mesh_filter::MeshFilter<mesh_filter::StereoCameraModel>( mesh_filter::MeshFilterBase::TransformCallback(), mesh_filter::StereoCameraModel::REGISTERED_PSDK_PARAMS)); mesh_filter_->parameters().setDepthRange(near_clipping_plane_distance_, far_clipping_plane_distance_); mesh_filter_->setShadowThreshold(shadow_threshold_); mesh_filter_->setPaddingOffset(padding_offset_); mesh_filter_->setPaddingScale(padding_scale_); mesh_filter_->setTransformCallback(boost::bind(&DepthImageOctomapUpdater::getShapeTransform, this, _1, _2)); return true; } void DepthImageOctomapUpdater::start() { image_transport::TransportHints hints("raw", ros::TransportHints(), nh_); pub_model_depth_image_ = model_depth_transport_.advertiseCamera("model_depth", 1); if (!filtered_cloud_topic_.empty()) pub_filtered_depth_image_ = filtered_depth_transport_.advertiseCamera(filtered_cloud_topic_, 1); else pub_filtered_depth_image_ = filtered_depth_transport_.advertiseCamera("filtered_depth", 1); pub_filtered_label_image_ = filtered_label_transport_.advertiseCamera("filtered_label", 1); sub_depth_image_ = input_depth_transport_.subscribeCamera(image_topic_, queue_size_, &DepthImageOctomapUpdater::depthImageCallback, this, hints); } void DepthImageOctomapUpdater::stop() { stopHelper(); } void DepthImageOctomapUpdater::stopHelper() { sub_depth_image_.shutdown(); } mesh_filter::MeshHandle DepthImageOctomapUpdater::excludeShape(const shapes::ShapeConstPtr& shape) { mesh_filter::MeshHandle h = 0; if (mesh_filter_) { if (shape->type == shapes::MESH) h = mesh_filter_->addMesh(static_cast<const shapes::Mesh&>(*shape)); else { std::unique_ptr<shapes::Mesh> m(shapes::createMeshFromShape(shape.get())); if (m) h = mesh_filter_->addMesh(*m); } } else ROS_ERROR("Mesh filter not yet initialized!"); return h; } void DepthImageOctomapUpdater::forgetShape(mesh_filter::MeshHandle handle) { if (mesh_filter_) mesh_filter_->removeMesh(handle); } bool DepthImageOctomapUpdater::getShapeTransform(mesh_filter::MeshHandle h, Eigen::Isometry3d& transform) const { ShapeTransformCache::const_iterator it = transform_cache_.find(h); if (it == transform_cache_.end()) { ROS_ERROR("Internal error. Mesh filter handle %u not found", h); return false; } transform = it->second; return true; } namespace { bool host_is_big_endian() { union { uint32_t i; char c[sizeof(uint32_t)]; } bint = { 0x01020304 }; return bint.c[0] == 1; } } // namespace static const bool HOST_IS_BIG_ENDIAN = host_is_big_endian(); void DepthImageOctomapUpdater::depthImageCallback(const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg) { ROS_DEBUG("Received a new depth image message (frame = '%s', encoding='%s')", depth_msg->header.frame_id.c_str(), depth_msg->encoding.c_str()); ros::WallTime start = ros::WallTime::now(); if (max_update_rate_ > 0) { // ensure we are not updating the octomap representation too often if (ros::Time::now() - last_update_time_ <= ros::Duration(1.0 / max_update_rate_)) return; last_update_time_ = ros::Time::now(); } // measure the frequency at which we receive updates if (image_callback_count_ < 1000) { if (image_callback_count_ > 0) { const double dt_start = (start - last_depth_callback_start_).toSec(); if (image_callback_count_ < 2) average_callback_dt_ = dt_start; else average_callback_dt_ = ((image_callback_count_ - 1) * average_callback_dt_ + dt_start) / (double)image_callback_count_; } } else // every 1000 updates we reset the counter almost to the beginning (use 2 so we don't have so much of a ripple in // the measured average) image_callback_count_ = 2; last_depth_callback_start_ = start; ++image_callback_count_; if (monitor_->getMapFrame().empty()) monitor_->setMapFrame(depth_msg->header.frame_id); /* get transform for cloud into map frame */ tf2::Stamped<tf2::Transform> map_h_sensor; if (monitor_->getMapFrame() == depth_msg->header.frame_id) map_h_sensor.setIdentity(); else { if (tf_buffer_) { // wait at most 50ms static const double TEST_DT = 0.005; const int nt = (int)(0.5 + average_callback_dt_ / TEST_DT) * std::max(1, ((int)queue_size_ / 2)); bool found = false; std::string err; for (int t = 0; t < nt; ++t) try { tf2::fromMsg(tf_buffer_->lookupTransform(monitor_->getMapFrame(), depth_msg->header.frame_id, depth_msg->header.stamp), map_h_sensor); found = true; break; } catch (tf2::TransformException& ex) { static const ros::Duration D(TEST_DT); err = ex.what(); D.sleep(); } static const unsigned int MAX_TF_COUNTER = 1000; // so we avoid int overflow if (found) { good_tf_++; if (good_tf_ > MAX_TF_COUNTER) { const unsigned int div = MAX_TF_COUNTER / 10; good_tf_ /= div; failed_tf_ /= div; } } else { failed_tf_++; if (failed_tf_ > good_tf_) ROS_WARN_THROTTLE(1, "More than half of the image messages discared due to TF being unavailable (%u%%). " "Transform error of sensor data: %s; quitting callback.", (100 * failed_tf_) / (good_tf_ + failed_tf_), err.c_str()); else ROS_DEBUG_THROTTLE(1, "Transform error of sensor data: %s; quitting callback", err.c_str()); if (failed_tf_ > MAX_TF_COUNTER) { const unsigned int div = MAX_TF_COUNTER / 10; good_tf_ /= div; failed_tf_ /= div; } return; } } else return; } if (!updateTransformCache(depth_msg->header.frame_id, depth_msg->header.stamp)) { ROS_ERROR_THROTTLE(1, "Transform cache was not updated. Self-filtering may fail."); return; } if (depth_msg->is_bigendian && !HOST_IS_BIG_ENDIAN) ROS_ERROR_THROTTLE(1, "endian problem: received image data does not match host"); const int w = depth_msg->width; const int h = depth_msg->height; // call the mesh filter mesh_filter::StereoCameraModel::Parameters& params = mesh_filter_->parameters(); params.setCameraParameters(info_msg->K[0], info_msg->K[4], info_msg->K[2], info_msg->K[5]); params.setImageSize(w, h); const bool is_u_short = depth_msg->encoding == sensor_msgs::image_encodings::TYPE_16UC1; if (is_u_short) mesh_filter_->filter(&depth_msg->data[0], GL_UNSIGNED_SHORT); else { if (depth_msg->encoding != sensor_msgs::image_encodings::TYPE_32FC1) { ROS_ERROR_THROTTLE(1, "Unexpected encoding type: '%s'. Ignoring input.", depth_msg->encoding.c_str()); return; } mesh_filter_->filter(&depth_msg->data[0], GL_FLOAT); } // the mesh filter runs in background; compute extra things in the meantime // Use correct principal point from calibration const double px = info_msg->K[2]; const double py = info_msg->K[5]; // if the camera parameters have changed at all, recompute the cache we had if (w >= static_cast<int>(x_cache_.size()) || h >= static_cast<int>(y_cache_.size()) || K2_ != px || K5_ != py || K0_ != info_msg->K[0] || K4_ != info_msg->K[4]) { K2_ = px; K5_ = py; K0_ = info_msg->K[0]; K4_ = info_msg->K[4]; inv_fx_ = 1.0 / K0_; inv_fy_ = 1.0 / K4_; // if there are any NaNs, discard data if (!(px == px && py == py && inv_fx_ == inv_fx_ && inv_fy_ == inv_fy_)) return; // Pre-compute some constants if (static_cast<int>(x_cache_.size()) < w) x_cache_.resize(w); if (static_cast<int>(y_cache_.size()) < h) y_cache_.resize(h); for (int x = 0; x < w; ++x) x_cache_[x] = (x - px) * inv_fx_; for (int y = 0; y < h; ++y) y_cache_[y] = (y - py) * inv_fy_; } const octomap::point3d sensor_origin(map_h_sensor.getOrigin().getX(), map_h_sensor.getOrigin().getY(), map_h_sensor.getOrigin().getZ()); octomap::KeySet* occupied_cells_ptr = new octomap::KeySet(); octomap::KeySet* model_cells_ptr = new octomap::KeySet(); octomap::KeySet& occupied_cells = *occupied_cells_ptr; octomap::KeySet& model_cells = *model_cells_ptr; // allocate memory if needed std::size_t img_size = h * w; if (filtered_labels_.size() < img_size) filtered_labels_.resize(img_size); // get the labels of the filtered data const unsigned int* labels_row = &filtered_labels_[0]; mesh_filter_->getFilteredLabels(&filtered_labels_[0]); // publish debug information if needed if (debug_info_) { sensor_msgs::Image debug_msg; debug_msg.header = depth_msg->header; debug_msg.height = h; debug_msg.width = w; debug_msg.is_bigendian = HOST_IS_BIG_ENDIAN; debug_msg.encoding = sensor_msgs::image_encodings::TYPE_32FC1; debug_msg.step = w * sizeof(float); debug_msg.data.resize(img_size * sizeof(float)); mesh_filter_->getModelDepth(reinterpret_cast<float*>(&debug_msg.data[0])); pub_model_depth_image_.publish(debug_msg, *info_msg); sensor_msgs::Image filtered_depth_msg; filtered_depth_msg.header = depth_msg->header; filtered_depth_msg.height = h; filtered_depth_msg.width = w; filtered_depth_msg.is_bigendian = HOST_IS_BIG_ENDIAN; filtered_depth_msg.encoding = sensor_msgs::image_encodings::TYPE_32FC1; filtered_depth_msg.step = w * sizeof(float); filtered_depth_msg.data.resize(img_size * sizeof(float)); mesh_filter_->getFilteredDepth(reinterpret_cast<float*>(&filtered_depth_msg.data[0])); pub_filtered_depth_image_.publish(filtered_depth_msg, *info_msg); sensor_msgs::Image label_msg; label_msg.header = depth_msg->header; label_msg.height = h; label_msg.width = w; label_msg.is_bigendian = HOST_IS_BIG_ENDIAN; label_msg.encoding = sensor_msgs::image_encodings::RGBA8; label_msg.step = w * sizeof(unsigned int); label_msg.data.resize(img_size * sizeof(unsigned int)); mesh_filter_->getFilteredLabels(reinterpret_cast<unsigned int*>(&label_msg.data[0])); pub_filtered_label_image_.publish(label_msg, *info_msg); } if (!filtered_cloud_topic_.empty()) { sensor_msgs::Image filtered_msg; filtered_msg.header = depth_msg->header; filtered_msg.height = h; filtered_msg.width = w; filtered_msg.is_bigendian = HOST_IS_BIG_ENDIAN; filtered_msg.encoding = sensor_msgs::image_encodings::TYPE_16UC1; filtered_msg.step = w * sizeof(unsigned short); filtered_msg.data.resize(img_size * sizeof(unsigned short)); // reuse float buffer across callbacks static std::vector<float> filtered_data; if (filtered_data.size() < img_size) filtered_data.resize(img_size); mesh_filter_->getFilteredDepth(reinterpret_cast<float*>(&filtered_data[0])); unsigned short* msg_data = reinterpret_cast<unsigned short*>(&filtered_msg.data[0]); for (std::size_t i = 0; i < img_size; ++i) { // rescale depth to millimeter to work with `unsigned short` msg_data[i] = static_cast<unsigned short>(filtered_data[i] * 1000 + 0.5); } pub_filtered_depth_image_.publish(filtered_msg, *info_msg); } // figure out occupied cells and model cells tree_->lockRead(); try { const int h_bound = h - skip_vertical_pixels_; const int w_bound = w - skip_horizontal_pixels_; if (is_u_short) { const uint16_t* input_row = reinterpret_cast<const uint16_t*>(&depth_msg->data[0]); for (int y = skip_vertical_pixels_; y < h_bound; ++y, labels_row += w, input_row += w) for (int x = skip_horizontal_pixels_; x < w_bound; ++x) { // not filtered if (labels_row[x] == mesh_filter::MeshFilterBase::Background) { float zz = (float)input_row[x] * 1e-3; // scale from mm to m float yy = y_cache_[y] * zz; float xx = x_cache_[x] * zz; /* transform to map frame */ tf2::Vector3 point_tf = map_h_sensor * tf2::Vector3(xx, yy, zz); occupied_cells.insert(tree_->coordToKey(point_tf.getX(), point_tf.getY(), point_tf.getZ())); } // on far plane or a model point -> remove else if (labels_row[x] >= mesh_filter::MeshFilterBase::FarClip) { float zz = input_row[x] * 1e-3; float yy = y_cache_[y] * zz; float xx = x_cache_[x] * zz; /* transform to map frame */ tf2::Vector3 point_tf = map_h_sensor * tf2::Vector3(xx, yy, zz); // add to the list of model cells model_cells.insert(tree_->coordToKey(point_tf.getX(), point_tf.getY(), point_tf.getZ())); } } } else { const float* input_row = reinterpret_cast<const float*>(&depth_msg->data[0]); for (int y = skip_vertical_pixels_; y < h_bound; ++y, labels_row += w, input_row += w) for (int x = skip_horizontal_pixels_; x < w_bound; ++x) { if (labels_row[x] == mesh_filter::MeshFilterBase::Background) { float zz = input_row[x]; float yy = y_cache_[y] * zz; float xx = x_cache_[x] * zz; /* transform to map frame */ tf2::Vector3 point_tf = map_h_sensor * tf2::Vector3(xx, yy, zz); occupied_cells.insert(tree_->coordToKey(point_tf.getX(), point_tf.getY(), point_tf.getZ())); } else if (labels_row[x] >= mesh_filter::MeshFilterBase::FarClip) { float zz = input_row[x]; float yy = y_cache_[y] * zz; float xx = x_cache_[x] * zz; /* transform to map frame */ tf2::Vector3 point_tf = map_h_sensor * tf2::Vector3(xx, yy, zz); // add to the list of model cells model_cells.insert(tree_->coordToKey(point_tf.getX(), point_tf.getY(), point_tf.getZ())); } } } } catch (...) { tree_->unlockRead(); ROS_ERROR("Internal error while parsing depth data"); return; } tree_->unlockRead(); /* cells that overlap with the model are not occupied */ for (octomap::KeySet::iterator it = model_cells.begin(), end = model_cells.end(); it != end; ++it) occupied_cells.erase(*it); // mark occupied cells tree_->lockWrite(); try { /* now mark all occupied cells */ for (octomap::KeySet::iterator it = occupied_cells.begin(), end = occupied_cells.end(); it != end; ++it) tree_->updateNode(*it, true); } catch (...) { ROS_ERROR("Internal error while updating octree"); } tree_->unlockWrite(); tree_->triggerUpdateCallback(); // at this point we still have not freed the space free_space_updater_->pushLazyUpdate(occupied_cells_ptr, model_cells_ptr, sensor_origin); ROS_DEBUG("Processed depth image in %lf ms", (ros::WallTime::now() - start).toSec() * 1000.0); } } // namespace occupancy_map_monitor
[ "goyalneehit@gmail.com" ]
goyalneehit@gmail.com
142b845b0aef9d1f182d0b603581bf165ff18ad5
b146eeede067b25bf0d455b7ce9e7d228c163044
/ThreadLooper.cpp
c1be4848bae0e47913aa1185663e8907daaf7286
[ "MIT", "Apache-2.0" ]
permissive
willir/libeventThread
b94e5da554d6b2d81abfc9510b514686f07344be
1d39fa5b8fe187e79f14a3062aa139524d2c37be
refs/heads/master
2016-08-08T21:26:22.442168
2016-01-18T07:53:33
2016-01-18T07:53:33
49,860,201
0
0
null
null
null
null
UTF-8
C++
false
false
541
cpp
#include "ThreadLooper.h" #include <iostream> using boost::thread; using std::cerr; using std::endl; namespace thread_loop { ThreadLooper::~ThreadLooper() { stop(); } void ThreadLooper::start() { mThread.reset(new thread(&ThreadLooper::startLoop, this)); } void ThreadLooper::stop() { if(!mThread) { cerr << "ThreadLooper::stop:" << getDebugName() << " already stopped" << endl; return; } stopLoop(); mThread->join(); mThread.reset(); ASSERT(!started()); } } // namespace thread_loop
[ "willir29@yandex.ru" ]
willir29@yandex.ru
a41761ae844cd8f22c64acbe33876de03713c4d2
ffb568806e34199501c4ca6b61ac86ee9cc8de2e
/tool_project/ModelConverter/ShaderCompiler/util_SizedEnum.h
bdac3ca2945a1d21401edf5fd61e037f970e9080
[]
no_license
Fumikage8/gen7-source
433fb475695b2d5ffada25a45999f98419b75b6b
f2f572b8355d043beb468004f5e293b490747953
refs/heads/main
2023-01-06T00:00:14.171807
2020-10-20T18:49:53
2020-10-20T18:49:53
305,500,113
3
1
null
null
null
null
UTF-8
C++
false
false
8,256
h
/*---------------------------------------------------------------------------* Project: Horizon File: util_SizedEnum.h Copyright (C)2009-2013 Nintendo Co., Ltd. All rights reserved. These coded instructions, statements, and computer programs contain proprietary information of Nintendo of America Inc. and/or Nintendo Company Ltd., and are protected by Federal copyright law. They may not be disclosed to third parties or copied or duplicated in any form, in whole or in part, without the prior written consent of Nintendo. $Rev: 50823 $ *---------------------------------------------------------------------------*/ #ifndef NN_UTIL_UTIL_SIZEDENUM_H_ #define NN_UTIL_UTIL_SIZEDENUM_H_ #include "types.h" //#include <nn/util/util_StaticAssert.h> #ifdef __cplusplus namespace nn { namespace util { //--------------------------------------------------------------------------- //! :category ユーティリティクラステンプレート //! //! @tparam StorageT enum 値の格納に使う型 //! @tparam EnumT 対象の列挙体型 //! //! @brief 固定サイズで列挙体型を扱うためのクラステンプレートです。 //! //! このクラスを使用することで enum 値のサイズを明示的に使用して扱うことができます。 //! //! EnumT 型の列挙体型を StorageT 型の変数に格納して扱えるようにします。 //--------------------------------------------------------------------------- template <typename StorageT, typename EnumT> class SizedEnum { private: typedef SizedEnum<StorageT, EnumT> Self; // NN_STATIC_ASSERT(sizeof(EnumT) <= sizeof(StorageT)); private: StorageT m_EnumValue; public: //--------------------------------------------------------------------------- //! @brief コンストラクタです。 //! //! 初期化なしのコンストラクタです。 //--------------------------------------------------------------------------- SizedEnum() {} //--------------------------------------------------------------------------- //! @brief //! //! 指定した初期値で初期化するコンストラクタです。 //! //! @param[in] e このインスタンスの初期値 //--------------------------------------------------------------------------- SizedEnum(EnumT e) { Set(e); } //--------------------------------------------------------------------------- //! @brief 列挙体型への型変換演算子です。 //! //! EnumT 型の値を直接読み取ることができます。 //--------------------------------------------------------------------------- operator EnumT() const { return Get(); } //--------------------------------------------------------------------------- //! @brief 列挙体型を代入するための代入演算子です。 //! //! EnumT 型の値を代入演算子で直接設定できます。 //! //! @param[in] e 新しく設定する値。 //! //! @return 自身の参照を返します。 //--------------------------------------------------------------------------- Self& operator =(EnumT e) { Set(e); return *this; } //--------------------------------------------------------------------------- //! @brief 値を設定します。 //! //! このインスタンスが管理している値を更新します。 //! //! @param[in] e 新しく設定する値。 //--------------------------------------------------------------------------- void Set(EnumT e) { m_EnumValue = static_cast<StorageT>(e); } //--------------------------------------------------------------------------- //! @brief 値を取得します。 //! //! このインスタンスが管理している値を列挙体型で取得します。 //! //! @return このインスタンスの値を返します。 //--------------------------------------------------------------------------- EnumT Get() const { return static_cast<EnumT>(m_EnumValue); } }; //--------------------------------------------------------------------------- //! :category ユーティリティクラステンプレート //! //! @tparam EnumT 対象の列挙体型 //! //! @brief 1 バイトサイズで SizedEnum を部分特殊化したクラステンプレートです。 //! //! EnumT 型の列挙体型を 1 バイトのサイズとして扱うためのクラスです。 //--------------------------------------------------------------------------- template <typename EnumT> class SizedEnum1 : public SizedEnum<bit8, EnumT> { public: //--------------------------------------------------------------------------- //! @brief コンストラクタです。 //! //! 初期化なしのコンストラクタです。 //--------------------------------------------------------------------------- SizedEnum1() : SizedEnum<bit8, EnumT>() {} //--------------------------------------------------------------------------- //! @brief //! //! 指定した初期値で初期化するコンストラクタです。 //! //! @param[in] e このインスタンスの初期値 //--------------------------------------------------------------------------- SizedEnum1(EnumT e) : SizedEnum<bit8, EnumT>(e) {} }; //--------------------------------------------------------------------------- //! :category ユーティリティクラステンプレート //! //! @tparam EnumT 対象の列挙体型 //! //! @brief 2 バイトサイズで SizedEnum を部分特殊化したクラステンプレートです。 //! //! EnumT 型の列挙体型を 2 バイトのサイズとして扱うためのクラスです。 //--------------------------------------------------------------------------- template <typename EnumT> class SizedEnum2 : public SizedEnum<bit16, EnumT> { public: //--------------------------------------------------------------------------- //! @brief コンストラクタです。 //! //! 初期化なしのコンストラクタです。 //--------------------------------------------------------------------------- SizedEnum2() : SizedEnum<bit16, EnumT>() {} //--------------------------------------------------------------------------- //! @brief //! //! 指定した初期値で初期化するコンストラクタです。 //! //! @param[in] e このインスタンスの初期値 //--------------------------------------------------------------------------- SizedEnum2(EnumT e) : SizedEnum<bit16, EnumT>(e) {} }; //--------------------------------------------------------------------------- //! :category ユーティリティクラステンプレート //! //! @tparam EnumT 対象の列挙体型 //! //! @brief 4 バイトサイズで SizedEnum を部分特殊化したクラステンプレートです。 //! //! EnumT 型の列挙体型を 4 バイトのサイズとして扱うためのクラスです。 //--------------------------------------------------------------------------- template <typename EnumT> class SizedEnum4 : public SizedEnum<bit32, EnumT> { public: //--------------------------------------------------------------------------- //! @brief コンストラクタです。 //! //! 初期化なしのコンストラクタです。 //--------------------------------------------------------------------------- SizedEnum4() : SizedEnum<bit32, EnumT>() {} //--------------------------------------------------------------------------- //! @brief //! //! 指定した初期値で初期化するコンストラクタです。 //! //! @param[in] e このインスタンスの初期値 //--------------------------------------------------------------------------- SizedEnum4(EnumT e) : SizedEnum<bit32, EnumT>(e) {} }; }} #endif // __cplusplus #endif /* NN_UTIL_UTIL_SIZEDENUM_H_ */
[ "forestgamer141@gmail.com" ]
forestgamer141@gmail.com
4bfefcaa3756b6b0d9d68de53975623e7868d636
08cd8642d160a329ad98a0a05f677a39c0faf57d
/live/liveMedia/MP3InternalsHuffman.hh
cf48c3ce1735339b83e0b1d27433147d513ba124
[ "LGPL-2.1-only", "BSD-3-Clause" ]
permissive
watson-yu/RTSPSource
e3cd040ad91113b1e3ad3c37b0e703fb1a271a27
2392e598cbd0cac32903ed228bf9117711911ab4
refs/heads/master
2020-11-28T06:35:41.871198
2019-12-30T02:20:16
2019-12-30T02:20:16
229,730,274
0
0
BSD-3-Clause
2019-12-23T10:32:49
2019-12-23T10:32:48
null
UTF-8
C++
false
false
2,653
hh
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved. // MP3 internal implementation details (Huffman encoding) // C++ header #ifndef _MP3_INTERNALS_HUFFMAN_HH #define _MP3_INTERNALS_HUFFMAN_HH #ifndef _MP3_INTERNALS_HH #include "MP3Internals.hh" #endif void updateSideInfoForHuffman(MP3SideInfo& sideInfo, Boolean isMPEG2, unsigned char const* mainDataPtr, unsigned p23L0, unsigned p23L1, unsigned& part23Length0a, unsigned& part23Length0aTruncation, unsigned& part23Length0b, unsigned& part23Length0bTruncation, unsigned& part23Length1a, unsigned& part23Length1aTruncation, unsigned& part23Length1b, unsigned& part23Length1bTruncation); #define SSLIMIT 18 class MP3HuffmanEncodingInfo { public: MP3HuffmanEncodingInfo(Boolean includeDecodedValues = False); ~MP3HuffmanEncodingInfo(); public: unsigned numSamples; unsigned allBitOffsets[SBLIMIT*SSLIMIT + 1]; unsigned reg1Start, reg2Start, bigvalStart; /* special bit offsets */ unsigned* decodedValues; }; /* forward */ void MP3HuffmanDecode(MP3SideInfo::gr_info_s_t* gr, int isMPEG2, unsigned char const* fromBasePtr, unsigned fromBitOffset, unsigned fromLength, unsigned& scaleFactorsLength, MP3HuffmanEncodingInfo& hei); extern unsigned char huffdec[]; // huffman table data // The following are used if we process Huffman-decoded values #ifdef FOUR_BYTE_SAMPLES #define BYTES_PER_SAMPLE_VALUE 4 #else #ifdef TWO_BYTE_SAMPLES #define BYTES_PER_SAMPLE_VALUE 2 #else // ONE_BYTE_SAMPLES #define BYTES_PER_SAMPLE_VALUE 1 #endif #endif #ifdef DO_HUFFMAN_ENCODING unsigned MP3HuffmanEncode(MP3SideInfo::gr_info_s_t const* gr, unsigned char const* fromPtr, unsigned char* toPtr, unsigned toBitOffset, unsigned numHuffBits); #endif #endif
[ "fyeh@us.ibm.com" ]
fyeh@us.ibm.com
a98070ac9f4ac8eb9c0ce15b171cd2196905c583
728b7daecd3c1e00ca6d5d95093347c7e8a293cc
/src/testexamples.cpp
c8c05c75879e5fb6f4f96aa23db2258a5b63a0bb
[ "MIT" ]
permissive
manyoso/hof
d36c3cb2af9d66b74cfb2f5948acc3c4414d3fb4
fdbd3b89c2c221ef3030a313d8430ed088fe76dc
refs/heads/master
2021-01-10T07:54:45.981172
2015-12-04T19:50:00
2015-12-04T19:50:00
45,718,029
2
0
null
null
null
null
UTF-8
C++
false
false
2,311
cpp
#include <QtCore> #include "testhof.h" enum Expectation { Normal, // expect no timeout and no crash NoCrash, // expect no crash Timeout // expect timeout }; QString runHof(const QString& file, const QString& input, bool* ok, bool verbose = false, int msecsToTimeout = 5000, Expectation e = Expectation::Normal) { QDir bin(QCoreApplication::applicationDirPath()); QProcess hof; hof.setProgram(bin.path() + QDir::separator() + "hof"); QStringList args = QStringList() << "--file" << file << "--input" << input; if (verbose) { args.append("--verbose"); hof.setProcessChannelMode(QProcess::ForwardedErrorChannel); } hof.setArguments(args); hof.start(); bool finished = hof.waitForFinished(msecsToTimeout); if (!finished) { hof.kill(); hof.waitForFinished(); } /* special value used to indicate stack depth exceeded */ switch (e) { case Expectation::Normal: { *ok = finished && hof.exitStatus() == QProcess::NormalExit && (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2); break; } case Expectation::NoCrash: { *ok = !finished || (hof.exitStatus() == QProcess::NormalExit && (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2)); break; } case Expectation::Timeout: { *ok = !finished; break; } default: *ok = false; break; } if (!*ok) { qDebug() << "exit status:" << hof.exitStatus() << " code:" << hof.exitCode() << " error:" << hof.error(); } return hof.readAll().trimmed(); } // church numerals #define INC(X) "AASAASAKSK" X #define ZERO "AKI" #define ONE "I" #define TWO INC(ONE) #define THREE INC(TWO) #define FOUR INC(THREE) #define FIVE INC(FOUR) void TestHof::testExamples() { bool ok = false; QString out; out = runHof("examples/decrement.lambda", TWO, &ok); QCOMPARE(out, QString("II")); QVERIFY(ok); out = runHof("examples/print-list.lambda", QString(), &ok); QCOMPARE(out, QString("abcd")); QVERIFY(ok); }
[ "manyoso@yahoo.com" ]
manyoso@yahoo.com
29eb9fd0da41852ce604132b23384cadf37ffe2c
0463e7a555311bcb3ecb2d22ddbfd5e2b14a5369
/problems/1029/std.cpp
bf04e1ebd3b36df6957ffb1cee3e9f8651827e39
[]
no_license
rainboyOJ/contest_problem
33080d8c2d78b8fb1a10e7dff553283c17c5f729
f0cd8f7b4322af4cd65425969b3553b95e7bb00d
refs/heads/master
2023-07-15T16:13:53.965860
2021-08-28T02:23:40
2021-08-28T02:23:40
387,683,939
0
0
null
null
null
null
UTF-8
C++
false
false
1,282
cpp
/* author: Rainboy email: rainboylvx@qq.com time: 2021年 08月 09日 星期一 13:50:23 CST */ #include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e6+5,maxe = 1e6+5; //点与边的数量 /* 定义全局变量 */ int T,a[3]; int f[2][maxn]; // f[0][j] 容量为j的情况,不吃药片能否达到j // f[1][j] 容量为j的情况,吃药片能否达到j // f[0][j] = f[0][j] || f[0][j-w[i]] // f[1][j] = f[1][j] || f[1][j-w[i]] || f[0][2*j] // int main(){ scanf("%d%d%d",&T,&a[1],&a[2]); f[0][0] = 1; f[1][0] = 1; int ans = -1; for(int k = 1;k<=2;k++){ for(int i = a[k] ;i<=T ;i++) { if( f[0][i] == 0 && f[0][i-a[k]] == 1){ f[0][i] = 1; f[1][i>>1] = 1; ans = max(ans,i); } //printf("f[0][%d]= %d \n",i,f[0][i]); } //printf("================\n"); } //printf("================\n"); //printf("================\n"); for(int k = 1;k<=2;k++){ for(int i = a[k] ;i<=T ;i++) { if( f[1][i-a[k]] == 1){ f[1][i] = 1; ans = max(ans,i); } //printf("f[1][%d]= %d \n",i,f[1][i]); } } printf("%d",ans); return 0; }
[ "rainboylvx@qq.com" ]
rainboylvx@qq.com
0cc82fd193cd8e8cfe0464f2a2df0db0f28f7739
3a61ee83973304287a5c5535c36e2e694bbf89aa
/include/DUtility.h
eeb028f43a7b78bd95ee7b0afa673fd85ab89497
[]
no_license
DamonsJ/DamonsUtility
12456b238f29beb26f806ce33a4a9fb5f49a1c22
e77bae70b925e3d6d0b0458f59f81a33d4cfe703
refs/heads/master
2020-08-29T06:01:54.711149
2019-12-09T03:00:28
2019-12-09T03:00:28
217,949,462
0
0
null
null
null
null
UTF-8
C++
false
false
382
h
#ifndef _DUTILITY_HEADER_ #define _DUTILITY_HEADER_ #ifdef _WIN32 #ifdef DU_DLL_PROVIDER #define DU_DLL_API _declspec(dllexport) #else #define DU_DLL_API _declspec(dllimport) #endif #else #define DU_DLL_API #endif #include <chrono> #include <string> #include <iomanip> #include <vector> #include <fstream> #include <iostream> #include <stdexcept> #endif// 2018/10/29
[ "sunhonglei@goldwind.com.cn" ]
sunhonglei@goldwind.com.cn
9aeac8d48ef5a61b1e722194debf5931d0c435cd
773f615ca7f3111f33c9ee34c23359df0f7dd3e0
/SPA/EvaluatorHelper.h
2915a2b707e1c75544dc0343613670a5e773f302
[]
no_license
keloysiusmak/cs3201-group6-spa
9b97df28accf5187b61b110ac4c4bb5545dda02a
6cb4f849c9c59edb82661d51bc579b0df3338732
refs/heads/master
2021-09-12T08:20:51.849978
2018-04-15T15:37:32
2018-04-15T15:37:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,906
h
#pragma once #include "ClauseResults.h" #include "Utils.h" #include "IntermediateTable.h" #include <list> #include <assert.h> class EvaluatorHelper { public: static Clause generalizeClause(Clause &clause); static void cacheUnsanitized(Clause &clause, ClauseResults &clauseResults, map<Clause, vector<vector<int>>> &cache); static void cacheSanitized(Clause &clause, ClauseResults &clauseResults, map<Clause, vector<vector<int>>> &cache); static bool unsanitizedClauseInCache(Clause &clause, map<Clause, vector<vector<int>>> &cache); static bool clauseInCache(Clause &clause, map<Clause, vector<vector<int>>> &cache); static void mergeClauseTable(ClauseResults &clauseResults, IntermediateTable &iTable); static void mergeWithoutOverlap(ClauseResults &clauseResults, IntermediateTable &iTable); static void mergeWithOverlap(ClauseResults &clauseResults, IntermediateTable &iTable); static void sortTable(Param &p, IntermediateTable &iTable); static vector<vector<int>> mergeSortResults(int index, vector<vector<int>> &results); static IntermediateTable mergeIntermediateTables(IntermediateTable &iTable1, IntermediateTable &iTable2); static bool clauseParamsInTable(Clause &clause, IntermediateTable &iTable); static bool clauseResultsParamsInTable(ClauseResults &clauseResults, IntermediateTable &iTable); static void addClauseParamToTable(ClauseResults &clauseResults, IntermediateTable &iTable); static IntermediateTable findTableWithParam(Param p, vector<IntermediateTable> &iTables); static int withClauseNumSyns(Clause &clause, IntermediateTable &iTable); /* Extension Helpers */ static vector<vector<int>> crossVectors(vector<vector<int>> &set1, vector<vector<int>> &set2); static void subtractSetSingle(ClauseResults &clauseResults, vector<vector<int>> &setToSubtract); static void subtractSetDouble(ClauseResults &clauseResults, vector<vector<int>> &setToSubtract); };
[ "shitian007@hotmail.com" ]
shitian007@hotmail.com
c143b885d116d06619d995ef07625b2df186646b
d74e52322b90cca77ea6f943825ff57a47ce24b9
/BombMan/test bomb.cpp
308b794e79f46e9673d30d585a0540d23abe111d
[]
no_license
181847/ConsoleApplicationGame
63083c5b1895c6c2e817052ff9ae49b8b7b408a1
5c0aba2402849709f7a61880e61ceb8cbf69d4b1
refs/heads/master
2021-05-12T12:05:40.999544
2018-01-14T08:47:33
2018-01-14T08:47:33
117,403,573
0
0
null
null
null
null
UTF-8
C++
false
false
2,059
cpp
#include "stdafx.h" #include"Character Bomb.h" #include "File Bomb.h" #ifdef PHONE_TEST #define CLR clrscr() #elif COMPUTER_TEST #define CLR goto_xy(0, 0) //#define CLR system("cls") #endif using namespace std; int main() { cout << "start game" << endl; ControlString control_input; Point p1(1, 2, cha), p2(5, 6, gro), p3(7, 8, atk), p4(9, 10, obj), p5(11, 12, obj), p6(13, 14, obj), p7(15, 6, obj), p8(17, 8, gro), p9(19, 10, cha); cout << "start creat object" << endl; new Character(UP, "Tomclancy", 90, human, "wsad ", 17, p1); new Character(UP, "Tom", 54, human, "omjlk", 70, p9); new Character(UP, "Sam", 54, human, "28465", 70, 3, 3, cha); new Character(UP, "MONSTER", 5, monster, "tvfhg", 21, 3, 4, cha); new Character(UP, "MONSTER", 5, monster, "tvfhg", 21, 13, 5, cha); new Character(UP, "MONSTER", 5, monster, "tvfhg", 21, 3, 6, cha); new Object(5, true, transfer("bomb"), 40, 9, 10, obj); new Object(5, true, bomb, 40, 8, 11, obj); new Object(5, true, bomb, 40, 9, 12, obj); new Object(4, false, supply, 99, p5); new Object(1, false, treasure, 99, p6); new Object(20, false, monster_maker, 10, p7); new Object(20, false, none, 10, 17, 6, obj); for (int i = 0; i < Subject::map.height; i ++) for (int j = 0; j < Subject::map.width; j ++) if (i == 0 || i == Subject::map.height -1 || j == 0 || j == Subject::map.width - 1) new Ground(wall, 99, j, i, gro); else if (i % 2 == 0 && j % 2 == 0) new Ground(wall, 99, j, i, gro); else new Ground(space, 99, j, i, gro); cout << "end creat object" << endl; while (Subject::counter ++ <= 11000) { control_input.get_control_input(); *(Character::cl) << control_input; Character::cl -> clear(); Object::ol -> clear(); Attack::al -> clear(); CLR; cout << "output" << Subject::map; cout << *(Character_List*)(Character::cl); cout << Subject::counter << endl; /* #ifdef PHONE_TEST usleep(289999); #elif COMPUTER_TEST Sleep(1); #endif */ } }
[ "753090084@qq.com" ]
753090084@qq.com
b3d9825eb0ff69efbdd602e37a77ac9f5d2774b0
cb0e95a000b82f6191ed2ca5cbfa886d95c47670
/src/BM1000Payload.cpp
23abbd8b18dc9aed490690624e264a4380d93800
[ "MIT" ]
permissive
andriyadi/PulseOximeterLib
a05f50f96b2f0f050908d20de9b3795fe796f77b
f93ddea3fdc506a9937c410be147d658e5fed62d
refs/heads/main
2023-07-04T14:25:35.660385
2021-08-01T15:24:14
2021-08-01T15:24:14
391,660,285
0
0
null
null
null
null
UTF-8
C++
false
false
4,877
cpp
// // Created by Andri Yadi on 26/07/21. // #include "BM1000Payload.h" BM1000Payload::BM1000Payload() { spo2 = BM1000_INVALID_SPO2; pleth = BM1000_INVALID_PLETH; //PLETHYSMOGRAM pulseRate = BM1000_INVALID_PULSE_RATE; }; BM1000Payload::~BM1000Payload() = default; bool BM1000Payload::parse(const uint8_t *pData, size_t length) { if (length < 5) { return false; } spo2 = pData[4]; pleth = pData[1]; pulseRate = pData[3] | ((pData[2] & 0x40) << 1); //Bit 6 (0x40) of Byte 2 is bit 7 of the Pulse Rate BM1000PayloadSystemFlags1_t sFlag1; sFlag1.SystemFlags1 = pData[0]; BM1000PayloadSystemFlags2_t sFlag2; sFlag2.SystemFlags2 = pData[2]; //printf("No finger: %d || ", sFlag2.noFinger); noFinger = sFlag2.noFinger == 1; notCalibrating = sFlag2.notCalib == 1; barGraph = sFlag2.bargraph; sensorSignalStrength = sFlag1.signalStrength; hasSensorSignal = sFlag1.noSignal == 0; time_t _curTime; time(&_curTime); timestamp = (long)_curTime; return true; } std::string BM1000Payload::toString() const { char retc[96]; auto retl = snprintf(retc, 96, "[%ld] SpO2: %d, BPM: %d, PPG: %d, Finger? %d, Calib? %d, Sig: %d, Graph: %d", timestamp, spo2, pulseRate, pleth, !noFinger, !notCalibrating, sensorSignalStrength, barGraph); retc[retl] = 0; return std::string(retc); } bool operator==(const BM1000Payload &p1, const BM1000Payload &p2) { if (p1.equalityType == OximeterPayloadEqualityType_PPG) { return (p1.spo2 == p2.spo2 && p1.pulseRate == p2.pulseRate && p1.pleth == p2.pleth); } else if (p1.equalityType == OximeterPayloadEqualityType_BarGraph) { return (p1.spo2 == p2.spo2 && p1.pulseRate == p2.pulseRate && p1.barGraph == p2.barGraph); } else if (p1.equalityType == OximeterPayloadEqualityType_PulseRate) { return (p1.spo2 == p2.spo2 && p1.pulseRate == p2.pulseRate); } else { return false; } } bool operator!=(const BM1000Payload &p1, const BM1000Payload &p2) { return !(p1 == p2); } BM1000PayloadCollection::BM1000PayloadCollection() { } BM1000PayloadCollection::~BM1000PayloadCollection() { payloads_.clear(); } bool BM1000PayloadCollection::enqueuePayload(const BM1000Payload &payload, bool noDuplicate, bool onlyValidVal) { bool retVal = false; // Check validity if (onlyValidVal) { if (payload.pulseRate == BM1000_INVALID_PULSE_RATE || payload.spo2 >= BM1000_INVALID_SPO2) { return retVal; } } if (!payloadSemaphore_.take(2, "payload")) { //printf("In jail\r\n"); return retVal; } #if PAYLOAD_COL_USE_RINGBUF // Check equality with last added payload if (noDuplicate) { //printf("last pleth: %d, payload pleth: %d\r\n", lastPayload_.pleth, payload.pleth); if (payload == lastPayload_) { //printf("SAME\r\n"); payloadSemaphore_.give(); return retVal; } } // If above not return, payload is different from lastPayload lastPayload_ = payload; // Copy retVal = payloads_.push(payload); payloadSemaphore_.give(); #else if (payloads_.size() > BM1000_MAX_PAYLOAD_COLLECTION_SIZE - 1) { //printf("FULL\r\n"); payloads_.pop_front(); } // Check equality with last added payload if (!payloads_.empty() && noDuplicate) { auto &_lastPayload = payloads_.back(); //printf("last: %d, now: %d\r\n", _lastPayload.pleth, payload.pleth); if (payload == _lastPayload) { //printf("SAME\r\n"); payloadSemaphore_.give(); return retVal; } } payloads_.push_back(payload); payloadSemaphore_.give(); retVal = true; #endif bpmAvg_ = (uint8_t) roundf((1.0f/100) * bpmFilter_(payload.pulseRate*100)); spo2Avg_ = (uint8_t) roundf((1.0f/100) * spo2Filter_(payload.spo2*100)); return retVal; } BM1000Payload *BM1000PayloadCollection::dequeOne() { if (!payloadSemaphore_.take(10, "payload")) { //printf("In jail\r\n"); return nullptr; } #if PAYLOAD_COL_USE_RINGBUF if (payloads_.isEmpty()) { payloadSemaphore_.give(); return nullptr; } BM1000Payload *_retVal = nullptr; if (payloads_.pop(firstElement)) { _retVal = &firstElement; } payloadSemaphore_.give(); return _retVal; #else if (payloads_.empty()) { payloadSemaphore_.give(); // important return nullptr; } // auto *_ret = &payloads_.front(); // payloadSemaphore_.give(); // return _ret; firstElement = std::move(payloads_.front()); payloads_.pop_front(); payloadSemaphore_.give(); return &firstElement; #endif }
[ "an.dri@me.com" ]
an.dri@me.com
83bec1d8011e586464b196968d50e27cac556420
fc2d01d1afa08ffc46c23901163c37e679c3beaf
/AI/FollowSearch.cpp
eb232b5a9cfd12ba741bc4e41b6612ee5eee9ed9
[]
no_license
seblef/ShadowEngine
a9428607b49cdd41eb22dcbd8504555454e26a0c
fba95e910c63269bfe0a05ab639dc78b6c16ab8b
refs/heads/master
2023-02-14T19:08:25.878492
2021-01-08T16:16:44
2021-01-08T16:16:44
113,681,956
1
0
null
null
null
null
UTF-8
C++
false
false
1,389
cpp
#include "stdafx.h" #include "FollowSearch.h" #include "AIAgent.h" #include "Ids.h" #include "AISystem.h" #include "AIDebugger.h" #include <NavigationLib.h> bool FollowSearch::onEvent(AIAgent* a, const AIEvent& e) { Vector3 dir; float dist; const Vector3& pos(a->getCallback()->getAgentPosition()); switch (e.getName()) { case AIEVT_ENTER: #ifdef _DEBUG_AI // AIDebugger::getSingletonRef().logOut("Agent %i (%s) recieving ENTER event.", a->getID(), getStateName()); #endif dir = a->getLastKnownPlayerPosition() - pos; dir.normalize(); a->getCallback()->runTo(a->getLastKnownPlayerPosition(), dir); return true; break; case AIEVT_SEEPLAYER: #ifdef _DEBUG_AI AIDebugger::getSingletonRef().logOut("Agent %i (%s) recieving SEEPLAYER event.", a->getID(), getStateName()); #endif _machine->setState(a, FOLLOW_TRACK_STATE_ID); return true; break; case AIEVT_ENDMOVE: #ifdef _DEBUG_AI AIDebugger::getSingletonRef().logOut("Agent %i (%s) recieving ENDMOVE event.", a->getID(), getStateName()); #endif _machine->setState(a, FOLLOW_IDLE_STATE_ID); return true; case AIEVT_HIT: #ifdef _DEBUG_AI int damage = e.getIntParam(); AIDebugger::getSingletonRef().logOut("Agent %i hitted by agent %i (damage: %f)", a->getID(), e.getSenderID(), *((float*)&damage)); #endif return true; } return false; }
[ "sebast.lefort@gmail.com" ]
sebast.lefort@gmail.com
e77d910c7f7e698af68e466bd894f940e0321dc7
de390163287fda86b73df015d6b6a3dc5e1bf736
/Codeforces/Round 599 (Div. 2)/C.cpp
c5e0ad8c964902f86461f7fd9e1cbb5776be53f5
[]
no_license
iamarshsingh/Competative_programming
fb71a7b62d4ba2846deae25203f9087f31a0b675
09418842d029b20d2df0f5b5a5e87619f44a18b3
refs/heads/master
2020-06-26T14:39:59.199295
2020-03-28T14:05:26
2020-03-28T14:05:26
97,026,462
1
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
#include <bits/stdc++.h> #define int long long int #define ld long double #define MOD 1000000007 #define N 1000006 #define INF 1000000000000000000 #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); #define randright srand(chrono::steady_clock::now().time_since_epoch().count()); using namespace std; void solve(){ int n; cin>>n; int g = n; for(int i=2;i*i<=n;i++){ if(n%i==0){ g = __gcd(g,i); g = __gcd(g,(n/i)); } } cout<<g<<'\n'; } signed main(){ int t=1; // cin>>t; while(t--){ solve(); } }
[ "singh.arshdeep1999@gmail.com" ]
singh.arshdeep1999@gmail.com
b82a0b76994989329383b8bd5209997ec0a7a9d6
87966d2fa603b9dd72368647e304a9496d140051
/Modify2/huffman.h
46d0135df142ac56aba094bb957e8ac1cfe2618c
[]
no_license
YuhaoZhuang/Data-Structures-and-Algorithms
89e91033e5bb9ef6d9571760b3effe4de440a75e
886aad0ce25e2e36dbcd0ad3abd56ba75c4284a3
refs/heads/master
2020-08-17T22:05:43.704487
2019-10-17T06:17:04
2019-10-17T06:17:04
215,716,463
0
0
null
null
null
null
UTF-8
C++
false
false
7,861
h
#ifndef HUFFMAN_H_ #define HUFFMAN_H_ #include <array> #include <cstddef> #include <cctype> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <cerrno> #include <map> #include "bstream.h" #include "pqueue.h" class HuffmanNode { public: explicit HuffmanNode(char ch, size_t freq, HuffmanNode* left = nullptr, HuffmanNode* right = nullptr) : ch_(ch), freq_(freq), left_(left), right_(right) { } bool IsLeaf() { // Node is a leaf if it doesn't have any children return left_ == nullptr && right_ == nullptr; } bool operator < (const HuffmanNode& n) const { // In case of equality, make it deterministic based on character if (freq_ == n.freq_) return ch_ < n.ch_; // Otherwise compare frequencies return freq_ < n.freq_; } size_t freq() { return freq_; } size_t data() { return ch_; } HuffmanNode* left() { return left_; } HuffmanNode* right() { return right_; } private: char ch_; size_t freq_; HuffmanNode *left_, *right_; }; // Comparator for HuffmanNode* struct Compare { bool operator() (const HuffmanNode* node1, const HuffmanNode* node2) { return (*node1) < (*node2); } }; class Huffman { public: static void Compress(std::ifstream& ifs, std::ofstream& ofs); static void Decompress(std::ifstream& ifs, std::ofstream& ofs); private: static std::string GetInput(std::ifstream& fin); static void BuildTree(PQueue<HuffmanNode*, Compare>& huff_tree); static void OutputTree(HuffmanNode* node, BinaryOutputStream& bos); static void DeleteTree(HuffmanNode* node); static HuffmanNode* GetNextNode(BinaryInputStream& bis); static void GenerateFreqTable(std::map<char, int>& freq, std::string& contents); static void GenerateCodingTable(HuffmanNode* node, std::string bitstring, std::map<char, std::string>& code_table); static char GetEncodedChar(HuffmanNode* node, BinaryInputStream& bis); static void Print(HuffmanNode* node); }; void Huffman::Compress(std::ifstream& ifs, std::ofstream& ofs) { PQueue<HuffmanNode*, Compare> huff_tree; BinaryOutputStream bos(ofs); std::string contents = GetInput(ifs); std::map<char, int> freq; std::map<char, std::string> code_table; GenerateFreqTable(freq, contents); for (const auto& c : freq) { // allocate space for HuffmanNode on heap huff_tree.Push(new HuffmanNode(c.first, c.second)); } BuildTree(huff_tree); OutputTree(huff_tree.Top(), bos); // output number of encoded characters in binary bos.PutInt(static_cast<int>(contents.size())); GenerateCodingTable(huff_tree.Top(), "", code_table); // output the encoding for each character for (auto ch : contents) // loop through each bit character in bitstring for (auto bit : code_table[ch]) (bit == '1') ? bos.PutBit(1) : bos.PutBit(0); DeleteTree(huff_tree.Top()); bos.Close(); // flush binary stream ofs.close(); } void Huffman::Decompress(std::ifstream& ifs, std::ofstream& ofs) { BinaryInputStream bis(ifs); BinaryOutputStream bos(ofs); std::map<char, std::string> code_table; // read in the first bit for the root node // if the root is a leaf, only one type of character in file if (bis.GetBit()) { char ch = bis.GetChar(); int size = bis.GetInt(); while (size--) bos.PutChar(ch); return; } // reconstruct the huffman tree HuffmanNode* root = new HuffmanNode(0, 0, GetNextNode(bis), GetNextNode(bis)); int size = bis.GetInt(); // print out all the encoded characters while (size--) { bos.PutChar(GetEncodedChar(root, bis)); } // read bits from the stream until we find a codeword, then print it // loop while we still have characters in the stream // (go left if 0 bit, right if 1 bit, output char if we reach leaf node) // write character in output file // check for memory leaks DeleteTree(root); } // restructure the priority queue of Huffman leaf nodes into a Huffman tree void Huffman::BuildTree(PQueue<HuffmanNode*, Compare>& huff_tree) { while (huff_tree.Size() != 1) { HuffmanNode* node1 = huff_tree.Top(); huff_tree.Pop(); HuffmanNode* node2 = huff_tree.Top(); huff_tree.Pop(); HuffmanNode* internal_node = new HuffmanNode (0, node1->freq() + node2->freq(), node1, node2); huff_tree.Push(internal_node); } } // output the tree in binary format (using pre order traversal) // each internal node has 2 leaf nodes, so we don't need to check nullptr void Huffman::OutputTree(HuffmanNode* node, BinaryOutputStream& bos) { if (node->data() != 0) { // leaf node: output '1' and char bos.PutBit(1); bos.PutChar(node->data()); } else { // internal node bos.PutBit(0); OutputTree(node->left(), bos); OutputTree(node->right(), bos); } } // delete the nodes of the tree using a post order traversal void Huffman::DeleteTree(HuffmanNode* node) { if (node == nullptr) return; // recursively delete subtrees, then delete node when going up recursion DeleteTree(node->left()); DeleteTree(node->right()); delete(node); } // recursively reconstruct the Huffman tree from the bitstring, // by creating new nodes // and recursively setting the next node node in the list as left/right child // (the order is correct because huffman tree is given in preorder traversal) HuffmanNode* Huffman::GetNextNode(BinaryInputStream& bis) { if (bis.GetBit()) { // create leaf node // std::cout << "created leaf node" << std::endl; return new HuffmanNode(bis.GetChar(), 0); } else { // internal node: recursively set left and right children // to next node in preorder traversal return new HuffmanNode(0, 0, GetNextNode(bis), GetNextNode(bis)); } } void Huffman::GenerateFreqTable(std::map<char, int>& freq, std::string& contents) { for (unsigned int i = 0; i < contents.size(); i++) { // value already exists in map if (freq.find(contents[i]) != freq.end()) freq[contents[i]]++; else freq[contents[i]] = 1; } } void Huffman::GenerateCodingTable(HuffmanNode* node, std::string bitstring, std::map<char, std::string>& code_table) { // store encoding for each leaf node if (node->data() != 0) { code_table[node->data()] = bitstring; } else { GenerateCodingTable(node->left(), bitstring + '0', code_table); GenerateCodingTable(node->right(), bitstring + '1', code_table); } } // use the Huffman tree to recursively read in the next encoded // char from bitstring // go left if 0 bit, go right if 1 bit, return the char when we read the node // huffman codes are unique by prefix char Huffman::GetEncodedChar(HuffmanNode* node, BinaryInputStream& bis) { if (node->data() != 0) // leaf node return node->data(); if (bis.GetBit()) // go right if bit is 1 return GetEncodedChar(node->right(), bis); else // go left return GetEncodedChar(node->left(), bis); } // reads the input file into a string std::string Huffman::GetInput(std::ifstream& fin) { if (fin) { std::string contents; fin.seekg(0, std::ios::end); contents.resize(fin.tellg()); // get length of the file fin.seekg(0, std::ios::beg); fin.read(&contents[0], contents.size()); // read data as a block fin.close(); return(contents); } throw(errno); } // print function for debugging purposes void Huffman::Print(HuffmanNode* node) { if (node == nullptr) return; if (node->data() == 0) // internal node std::cout << node->data(); else std::cout << static_cast<char>(node->data()); std::cout << " " << node->freq() << std::endl; Print(node->left()); Print(node->right()); } #endif // HUFFMAN_H_
[ "zhuangy625@gmail.com" ]
zhuangy625@gmail.com
46f6eacecc60f8eb4f9bbe217bb7e061efea36bd
e5b98edd817712e1dbcabd927cc1fee62c664fd7
/Classes/module/arena/arenaExchange/ArenaExchangeLayerList.hpp
32493a28b4ee09ee2d02503e5afa0034e448140c
[]
no_license
yuangu/project
1a49092221e502bd5f070d7de634e4415c6a2314
cc0b354aaa994c0ee2d20d1e3d74da492063945f
refs/heads/master
2020-05-02T20:09:06.234554
2018-12-18T01:56:36
2018-12-18T01:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,986
hpp
// // ArenaExchangeLayerList.hpp // FightPass // // Created by chenyanbin on 16/3/10. // // #ifndef ArenaExchangeLayerList_hpp #define ArenaExchangeLayerList_hpp #include "extensions/cocos-ext.h" #include "cocos2d.h" #include "../../BaseLayer.h" #include "../../data/BaseTypeData.h" USING_NS_CC_EXT; USING_NS_CC; class ArenaExchangeLayerList : public BaseLayer, TableViewDataSource,TableViewDelegate { public: ArenaExchangeLayerList(); ~ArenaExchangeLayerList(); virtual bool init(); static ArenaExchangeLayerList* create(); protected: virtual void onExit(); virtual void onEnter(); virtual void onExitTransitionDidStart(); virtual void onEnterTransitionDidFinish(); virtual void addEventListener(); virtual void removeEventListener(); virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx); virtual ssize_t numberOfCellsInTableView(TableView *table); virtual void tableCellTouched(TableView* table, TableViewCell* cell); virtual Size tableCellSizeForIndex(TableView *table,ssize_t idx); virtual void scrollViewDidScroll(ScrollView* view); virtual void scrollViewDidZoom(ScrollView* view) {}; private: void createLayer(); Sprite* singleList(int idx); void createTable(); void onExchangeClick(Ref* pSender); void setTopData(int _rank,int _fightPowe,int _honer); Node* getTopNode(const char* titlePath,int value); void onitemClick(Node* pSender); void onUpdataBtn(Ref* pSender); void requestExchangeMsg(int refresh); void onExchangeMsgProcess(EventCustom* msg); void requestOneExchangeMsg(int itemid); private: TableView* _tableView; int TAG_TABLEVIEW; int m_ownGloy;//个人荣誉值 int m_index; Vector<BaseTypeData*>* m_baselist; int m_custHonnor; bool m_isUpdata;//shifoushuaxin int TAG_TOPNODE;// int m_combatPower;//战斗力 int m_currentRank;//当前排名 }; #endif /* ArenaExchangeLayerList_hpp */
[ "chenyanbin@ixianlai.com" ]
chenyanbin@ixianlai.com
0d82c0a49ef22e33a5c3d2f349eeeddd08c692dc
e0b96a03c19f8224ceb453d759b934357ab9450c
/3rd/shfe_md/include/quote_datatype_shfe_deep.h
9fefd691e500c96c2fea072df256c54d36ff16c2
[]
no_license
19199883/yao
4893d530c9e702c138690b44ed1027278aebf45b
9cc3a2b14ed5e342756e5ce2a12356847bfa4305
refs/heads/master
2021-06-15T03:39:24.990285
2021-04-20T12:53:10
2021-04-20T12:53:10
187,030,672
0
2
null
null
null
null
UTF-8
C++
false
false
1,552
h
#pragma once #ifndef DLL_PUBLIC #define DLL_PUBLIC __attribute__ ((visibility("default"))) #endif #include <string> #pragma pack(push) #pragma pack(8) #pragma pack(1) #define MAX_PAIR 120 struct PVPair { double price; int volume; }; struct MDPack { char instrument[10]; char islast; int seqno; char direction; short count; PVPair data[MAX_PAIR]; }; #pragma pack() // 上期全息委托 typedef char TShfeFtdcInstrumentIDType[31]; typedef char TShfeFtdcDirectionType; typedef double TShfeFtdcPriceType; typedef int TShfeFtdcVolumeType; ///买 #define THOST_FTDC_D_Buy '0' #define SHFE_FTDC_D_Buy '0' ///卖 #define THOST_FTDC_D_Sell '1' #define SHFE_FTDC_D_Sell '1' struct DLL_PUBLIC CShfeFtdcMBLMarketDataField { CShfeFtdcMBLMarketDataField() { this->damaged = false; } ///合约代码 TShfeFtdcInstrumentIDType InstrumentID; ///买卖方向 TShfeFtdcDirectionType Direction; ///价格 TShfeFtdcPriceType Price; ///数量 TShfeFtdcVolumeType Volume; // flag whethere this data is damaged for package loss bool damaged; }; // TODO:to be removed struct DLL_PUBLIC SHFEQuote { CShfeFtdcMBLMarketDataField field; bool isLast; SHFEQuote(const CShfeFtdcMBLMarketDataField &d, bool last) : field(d), isLast(last) { } SHFEQuote(bool last) { isLast = last; } SHFEQuote() { isLast = false; } // HH:MM:SS.mmm std::string GetQuoteTime() const { return "0"; } }; #pragma pack(pop)
[ "17199883@qq.com" ]
17199883@qq.com
184b26fb811eb7f5ae1eded07d67aae56d282b0d
b292168a299483841e5eab63b8c2a153dcf5c6de
/Classes/CardDraggingState.h
99dded0eb15a671d40d7080093f54071ade3cf31
[]
no_license
francis1122/RogueDeck
81622d512ff6ebbbc1856f2133d80fed8a2403d4
f7e1853cd01bfff0ff50cd1033486889cbe8db37
refs/heads/master
2020-06-03T17:04:03.540198
2014-04-16T00:31:40
2014-04-16T00:31:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,482
h
// // CardDraggingState.h // RogueDeck // // Created by Hunter Francis on 12/6/13. // // #ifndef __RogueDeck__CardDraggingState__ #define __RogueDeck__CardDraggingState__ #include "cocos2d.h" #include "UIState.h" #include "CardSprite.h" class BaseObject; class CardDraggingState : public UIState { public: // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(CardSprite *_selectedCard); void highlightInteractiveObjects(CardSprite *card); CardSprite *selectedCard; CardSprite *draggingCard; // implement the "static node()" method manually // CREATE_FUNC(HandCardSelectedState); //cocos2d::CCArray* allTouchesFromSet(cocos2d::CCSet *touches); virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); virtual void ccTouchMoved(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); virtual void ccTouchEnded(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); virtual void ccTouchCancelled(cocos2d::CCTouch *touch, cocos2d::CCEvent *event); //state changes virtual void transitionToNormalState(); virtual void transitionToHandCardSelectedState(CardSprite* selectedCard); virtual void transitionToSelectMonsterState(CardSprite* selectedCard); virtual void transitionToCardTargetingState(CardSprite* selectedCard); private: }; #endif /* defined(__RogueDeck__CardDraggingState__) */
[ "francis1122@gmail.com" ]
francis1122@gmail.com
385ceb91856a366ece5b251d71ab59e3ac11cd6f
902e56e5eb4dcf96da2b8c926c63e9a0cc30bf96
/Sources/Tools/EPI/GUI/GuiDocumentManager.h
2da728c0cfca3d6b80748c406c1bb04f74d46f63
[ "BSD-3-Clause" ]
permissive
benkaraban/anima-games-engine
d4e26c80f1025dcef05418a071c0c9cbd18a5670
8aa7a5368933f1b82c90f24814f1447119346c3b
refs/heads/master
2016-08-04T18:31:46.790039
2015-03-22T08:13:55
2015-03-22T08:13:55
32,633,432
2
0
null
null
null
null
UTF-8
C++
false
false
3,188
h
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef DOCUMENT_MANAGER_H_ #define DOCUMENT_MANAGER_H_ #include <Core/Standard.h> #include <EPI/GUI/GuiDocument.moc.h> namespace EPI { class DocumentRenderer; enum DocumentType; //----------------------------------------------------------------------------- class LM_API_EPI GuiDocumentManager : public QObject, public Core::Object { public: GuiDocumentManager(); virtual ~GuiDocumentManager(); const Ptr<GuiDocument>& createGuiDocument(const DocumentType type, const Core::String& title=L"", const Ptr<DocumentRenderer>& pDocRdr=null); const Ptr<GuiDocument>& loadGuiDocument(const Ptr<ImportInfo> & pImportInfo, bool & docAlreadyOpened, const Ptr<DocumentRenderer>& pDocRdr=null); Ptr<GuiDocument> destroyGuiDocument(int32 id); Ptr<GuiDocument> getGuiDocument(int32 id) const; Ptr<GuiDocument> getCurrentGuiDocument() const {return getGuiDocument(_idCurrentGDoc);} int32 getCurrentGuiDocumentId() const {return _idCurrentGDoc;} Ptr<GuiDocument> selectGuiDocument(int32 id); /** * permet d'acceder a la liste de documents */ const Core::List<Ptr<GuiDocument> >& getAllGuiDocument() const {return _gDocs;} Core::List<Ptr<GuiDocument> >& getAllGuiDocument() {return _gDocs;} bool isEmpty() const; private: int32 _idCurrentGDoc; Core::List<Ptr<GuiDocument> > _gDocs; }; //----------------------------------------------------------------------------- } // namespace EPI #endif // DOCUMENT_MANAGER_H_
[ "contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c" ]
contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c
328b8a6585a177baa1cca6ec5d8648f0793add41
323788cf746237167c70f38117d3fbd26e92c041
/sandbox/korbinian/src/featbin/append-feats.cc
1fcbb23dd1b45bd1952d5af824514fad6bfc3495
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
zweiein/kaldi
3cfc5d1fc66c1ca32c74f71171d4af2e2512f15c
708448c693272af0d68c8e178c7b4ff836125acf
refs/heads/master
2020-12-26T00:45:36.907011
2015-10-23T21:17:02
2015-10-23T21:17:02
46,313,562
0
1
null
2015-11-17T00:57:57
2015-11-17T00:57:57
null
UTF-8
C++
false
false
3,656
cc
// featbin/append-feats.cc // Copyright 2012 Petr Motlicek Pawel Swietojanski // Johns Hopkins University (author: Daniel Povey) // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "matrix/kaldi-matrix.h" int main(int argc, char *argv[]) { try { using namespace kaldi; const char *usage = "Append 2 feature-streams [and possibly change format]\n" "Note, this is deprecated; please use paste-feats\n" "Usage: append-feats [options] <in-rspecifier1> <in-rspecifier2> <out-wspecifier>\n" "Also see paste-feats which does a similar thing\n" "Example: append-feats --feats-offset-in1 5 --num-feats-in1 5 scp:list1.scp " "scp:list2.scp ark:-\n"; ParseOptions po(usage); bool truncate_frames = false; po.Register("truncate-frames", &truncate_frames, "If true, do not treat it " "as an error when files differ in number of frames, but truncate " "the longest one."); po.Read(argc, argv); if (po.NumArgs() != 3) { po.PrintUsage(); exit(1); } std::string rspecifier1 = po.GetArg(1); std::string rspecifier2 = po.GetArg(2); std::string wspecifier = po.GetArg(3); BaseFloatMatrixWriter feats_writer(wspecifier); SequentialBaseFloatMatrixReader feats_reader1(rspecifier1); RandomAccessBaseFloatMatrixReader feats_reader2(rspecifier2); int32 num_done = 0, num_err = 0; for (; !feats_reader1.Done(); feats_reader1.Next()) { std::string utt = feats_reader1.Key(); if (!feats_reader2.HasKey(utt)) { KALDI_WARN << "Could not find features for " << utt << " in " << rspecifier2 << ": producing no output for the utterance"; num_err++; continue; } const Matrix<BaseFloat> &feats1 = feats_reader1.Value(); const Matrix<BaseFloat> &feats2 = feats_reader2.Value(utt); if (feats1.NumRows() != feats2.NumRows() && !truncate_frames) { KALDI_WARN << "For utterance " << utt << ", features have different " << "#frames " << feats1.NumRows() << " vs. " << feats2.NumRows() << ", producing no output (use " << "--truncate-frames=true if you want output)"; num_err++; continue; } int32 num_frames = std::min(feats1.NumRows(), feats2.NumRows()), dim1 = feats1.NumCols(), dim2 = feats2.NumCols(); Matrix<BaseFloat> output(num_frames, dim1 + dim2, kUndefined); output.Range(0, num_frames, 0, dim1).CopyFromMat( feats1.Range(0, num_frames, 0, dim1)); output.Range(0, num_frames, dim1, dim2).CopyFromMat( feats2.Range(0, num_frames, 0, dim2)); feats_writer.Write(utt, output); num_done++; } KALDI_LOG << "Appended " << num_done << " feats; " << num_err << " with errors."; return (num_done != 0 ? 0 : 1); } catch (const std::exception& e) { std::cerr << e.what(); return -1; } }
[ "sikoried@5e6a8d80-dfce-4ca6-a32a-6e07a63d50c8" ]
sikoried@5e6a8d80-dfce-4ca6-a32a-6e07a63d50c8
98ad323f94b6edcee01793b59f70593ccefe7f96
4570baccfdd36ad0f59597c0e117f695b9f64033
/src/coincontrol.h
c078d2d0e6de7d1fb5c9ddd55af5b23b38237a76
[ "MIT" ]
permissive
toni25010/deliv-node
118881b763fcabe2143c0f6c63938af6a7287564
3f249f3b3cfb49b0b71ae1e6522b851861864f40
refs/heads/master
2020-04-07T04:38:12.168934
2018-11-08T20:10:15
2018-11-08T20:10:15
158,065,237
1
0
MIT
2018-11-18T08:50:34
2018-11-18T08:50:34
null
UTF-8
C++
false
false
2,193
h
// Copyright (c) 2011-2013 The Bitcoin developers // Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_COINCONTROL_H #define BITCOIN_COINCONTROL_H #include "primitives/transaction.h" #include "script/standard.h" /** Coin Control Features. */ class CCoinControl { public: CTxDestination destChange; bool useObfuScation; bool useSwiftTX; bool fSplitBlock; int nSplitBlock; //! If false, allows unselected inputs, but requires all selected inputs be used bool fAllowOtherInputs; //! Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria bool fAllowWatchOnly; //! Minimum absolute fee (not per kilobyte) CAmount nMinimumTotalFee; CCoinControl() { SetNull(); } void SetNull() { destChange = CNoDestination(); setSelected.clear(); useSwiftTX = false; useObfuScation = false; fAllowOtherInputs = false; fAllowWatchOnly = true; nMinimumTotalFee = 0; fSplitBlock = false; nSplitBlock = 1; } bool HasSelected() const { return (setSelected.size() > 0); } bool IsSelected(const uint256& hash, unsigned int n) const { COutPoint outpt(hash, n); return (setSelected.count(outpt) > 0); } void Select(const COutPoint& output) { setSelected.insert(output); } void UnSelect(const COutPoint& output) { setSelected.erase(output); } void UnSelectAll() { setSelected.clear(); } void ListSelected(std::vector<COutPoint>& vOutpoints) { vOutpoints.assign(setSelected.begin(), setSelected.end()); } unsigned int QuantitySelected() { return setSelected.size(); } void SetSelection(std::set<COutPoint> setSelected) { this->setSelected.clear(); this->setSelected = setSelected; } private: std::set<COutPoint> setSelected; }; #endif // BITCOIN_COINCONTROL_H
[ "terry@deliziaproject.com" ]
terry@deliziaproject.com
ef297829354d95c3fac61b95b1edf23b31838e17
d60a6c8021362a1481d660dc7d28c47a2e3d6558
/src/qt/guiutil.cpp
8f9317c0801be8e13ce3791dfb8363004860954e
[ "MIT" ]
permissive
terabit-hq/terabit
40b749df11c7d3cc29b7f806fc5393654f0b649b
4ed2189be074bc0b09109b2802308e0a671f4600
refs/heads/master
2021-01-17T20:59:54.205773
2017-09-27T11:29:41
2017-09-27T11:29:41
86,557,012
2
1
null
null
null
null
UTF-8
C++
false
false
17,197
cpp
#include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #if BOOST_FILESYSTEM_VERSION >= 3 #include <boost/filesystem/detail/utf8_codecvt_facet.hpp> #endif #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif #if BOOST_FILESYSTEM_VERSION >= 3 static boost::filesystem::detail::utf8_codecvt_facet utf8; #endif namespace GUIUtil { #if BOOST_FILESYSTEM_VERSION >= 3 boost::filesystem::path qstringToBoostPath(const QString &path) { return boost::filesystem::path(path.toStdString(), utf8); } QString boostPathToQString(const boost::filesystem::path &path) { return QString::fromStdString(path.string(utf8)); } #else #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older boost::filesystem::path qstringToBoostPath(const QString &path) { return boost::filesystem::path(path.toStdString()); } QString boostPathToQString(const boost::filesystem::path &path) { return QString::fromStdString(path.string()); } #endif QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); #if QT_VERSION >= 0x040800 font.setStyleHint(QFont::Monospace); #else font.setStyleHint(QFont::TypeWriter); #endif return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // NovaCoin: check prefix if(uri.scheme() != QString("terabit")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert terabit:// to terabit: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("terabit://")) { uri.replace(0, 12, "terabit:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "Terabit.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(Q_OS_LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "terabit.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=Terabit\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("Terabit-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " terabit-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("Terabit-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } void SetBlackThemeQSS(QApplication& app) { app.setStyleSheet("QWidget { background: rgb(41,44,48); }" "QFrame { border: none; }" "QComboBox { color: rgb(255,255,255); }" "QComboBox QAbstractItemView::item { color: rgb(255,255,255); }" "QPushButton { background: rgb(226,189,121); color: rgb(21,21,21); }" "QDoubleSpinBox { background: rgb(63,67,72); color: rgb(255,255,255); border-color: rgb(194,194,194); }" "QLineEdit { background: rgb(63,67,72); color: rgb(255,255,255); border-color: rgb(194,194,194); }" "QTextEdit { background: rgb(63,67,72); color: rgb(255,255,255); }" "QPlainTextEdit { background: rgb(63,67,72); color: rgb(255,255,255); }" "QMenuBar { background: rgb(41,44,48); color: rgb(110,116,126); }" "QMenu { background: rgb(30,32,36); color: rgb(222,222,222); }" "QMenu::item:selected { background-color: rgb(48,140,198); }" "QLabel { color: rgb(120,127,139); }" "QScrollBar { color: rgb(255,255,255); }" "QCheckBox { color: rgb(120,127,139); }" "QRadioButton { color: rgb(120,127,139); }" "QTabBar::tab { color: rgb(120,127,139); border: 1px solid rgb(78,79,83); border-bottom: none; padding: 5px; }" "QTabBar::tab:selected { background: rgb(41,44,48); }" "QTabBar::tab:!selected { background: rgb(24,26,30); margin-top: 2px; }" "QTabWidget::pane { border: 1px solid rgb(78,79,83); }" "QToolButton { background: rgb(30,32,36); color: rgb(116,122,134); border: none; border-left-color: rgb(30,32,36); border-left-style: solid; border-left-width: 6px; margin-top: 8px; margin-bottom: 8px; }" "QToolButton:checked { color: rgb(255,255,255); border: none; border-left-color: rgb(215,173,94); border-left-style: solid; border-left-width: 6px; }" "QProgressBar { color: rgb(149,148,148); border-color: rgb(255,255,255); border-width: 3px; border-style: solid; }" "QProgressBar::chunk { background: rgb(255,255,255); }" "QTreeView::item { background: rgb(41,44,48); color: rgb(212,213,213); }" "QTreeView::item:selected { background-color: rgb(48,140,198); }" "QTableView { background: rgb(66,71,78); color: rgb(212,213,213); gridline-color: rgb(157,160,165); }" "QHeaderView::section { background: rgb(29,34,39); color: rgb(255,255,255); }" "QToolBar { background: rgb(30,32,36); border: none; }"); } } // namespace GUIUtil
[ "yangchigi@yangchigi.com" ]
yangchigi@yangchigi.com
413b8195cea34817b65645ca611a8fe5d9c62eda
64829fda6e8a31e8861711727918ba26bb3b0eee
/QuickEngine/Source/Utilities/Texture.h
0e374a25c5bba3ae2c222154ef37aea621fb0b61
[]
no_license
StephenAArredondo/QuickEngine
48610c32f7d51d0690aa9bdb7f66e5289129aafe
22efd3f01ba6ae9cf2e00d4e750a59b4021f9fa8
refs/heads/master
2021-03-30T16:52:34.356282
2015-04-20T11:44:58
2015-04-20T11:44:58
34,091,038
0
0
null
null
null
null
UTF-8
C++
false
false
2,145
h
#ifndef _TEXTURE_H_ #define _TEXTURE_H_ #include <Common.h> #include <string> class Texture { private: enum eTextureType { NONE = 0, LOADED, CREATED, COPIED }; // Unique ID given by the TextureManager for referencing this texture unsigned int m_uiUniqueID; std::string m_szTextureName; // Number of objects that reference this texture unsigned int m_uiReferenceCount; // Holds image size and pointer to pixel array SDL_Texture* m_Image; // Image width value int m_nWidth; // Image height value int m_nHeight; // ID returned from glGenTextures GLuint m_uiHandle; // GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_CUBE GLuint m_uiTextureTarget; // If the texture was loaded from a file or created during runtime for general use unsigned int m_uiTextureType; bool GenerateTexture(); public: Texture(); ~Texture(); Texture(const Texture& _pTexture){} Texture* operator=(const Texture&){} Texture(std::string _szTextureName, std::string _szTexturePath); Texture(unsigned int _uiWidth, unsigned int _uiHeight, SDL_Color _eColor, std::string _szTextureName); // Loads a texture file specified at the file path bool LoadTexture(std::string _szTextureName, std::string _szTexturePath); // Creates a simple texture from memory bool CreateTexture(unsigned int _uiWidth, unsigned int _uiHeight, SDL_Color _eColor, std::string _szTextureName); // Saves the currently held texture to the HDD bool SaveTexture(std::string _szFileName); // Increase the ref count by one inline void AddRef() { m_uiReferenceCount++; } // Decreases the ref count by one and returns whether there are any remaining references inline bool RemoveRef() { return ((--m_uiReferenceCount) == 0) ? true : false; } void SetUniqueID(unsigned int _uiUniqueID) { m_uiUniqueID = _uiUniqueID; } inline std::string GetTextureName() { return m_szTextureName; } inline const SDL_Texture* GetTexture() { return m_Image; } inline unsigned int GetTextureWidth() { return m_nWidth; } inline unsigned int GetTextureHeight() { return m_nHeight; } inline GLuint GetTextureHandle() { return m_uiHandle; } void DeleteTextures(); }; #endif
[ "StephenAArredondo@users.noreply.github.com" ]
StephenAArredondo@users.noreply.github.com
ec460b2059c6d1f5eeb589ff2441d63da1e1a917
36b22f80a3325d95bb913a4bd0b16a73d113906c
/src/bixd/app/misc/NegativeUNLVote.cpp
0a85ac9f7f44a9d2ae10cb1ff97cd24e7e3883c1
[ "MIT" ]
permissive
VardanMelik/bixrp-old
32ec279ba1d5e3ff1799a9c17ed6a5b884ba044a
eab3140ea4bc3ef65ff9e4d73d7badff5f39e6cf
refs/heads/main
2023-06-07T06:13:29.320600
2021-06-23T04:10:57
2021-06-23T04:10:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,197
cpp
//------------------------------------------------------------------------------ /* This file is part of bixd Copyright (c) 2020 bixd Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <bixd/app/consensus/RCLValidations.h> #include <bixd/app/ledger/Ledger.h> #include <bixd/app/misc/NegativeUNLVote.h> namespace bixd { NegativeUNLVote::NegativeUNLVote(NodeID const& myId, beast::Journal j) : myId_(myId), j_(j) { } void NegativeUNLVote::doVoting( std::shared_ptr<Ledger const> const& prevLedger, hash_set<PublicKey> const& unlKeys, RCLValidations& validations, std::shared_ptr<SHAMap> const& initialSet) { // Voting steps: // -- build a reliability score table of validators // -- process the table and find all candidates to disable or to re-enable // -- pick one to disable and one to re-enable if any // -- if found candidates, add ttUNL_MODIFY Tx // Build NodeID set for internal use. // Build NodeID to PublicKey map for lookup before creating ttUNL_MODIFY Tx. hash_set<NodeID> unlNodeIDs; hash_map<NodeID, PublicKey> nidToKeyMap; for (auto const& k : unlKeys) { auto nid = calcNodeID(k); nidToKeyMap.emplace(nid, k); unlNodeIDs.emplace(nid); } // Build a reliability score table of validators if (std::optional<hash_map<NodeID, std::uint32_t>> scoreTable = buildScoreTable(prevLedger, unlNodeIDs, validations)) { // build next negUnl auto negUnlKeys = prevLedger->negativeUNL(); auto negUnlToDisable = prevLedger->validatorToDisable(); auto negUnlToReEnable = prevLedger->validatorToReEnable(); if (negUnlToDisable) negUnlKeys.insert(*negUnlToDisable); if (negUnlToReEnable) negUnlKeys.erase(*negUnlToReEnable); hash_set<NodeID> negUnlNodeIDs; for (auto const& k : negUnlKeys) { auto nid = calcNodeID(k); negUnlNodeIDs.emplace(nid); if (!nidToKeyMap.count(nid)) { nidToKeyMap.emplace(nid, k); } } auto const seq = prevLedger->info().seq + 1; purgeNewValidators(seq); // Process the table and find all candidates to disable or to re-enable auto const candidates = findAllCandidates(unlNodeIDs, negUnlNodeIDs, *scoreTable); // Pick one to disable and one to re-enable if any, add ttUNL_MODIFY Tx if (!candidates.toDisableCandidates.empty()) { auto n = choose(prevLedger->info().hash, candidates.toDisableCandidates); assert(nidToKeyMap.count(n)); addTx(seq, nidToKeyMap[n], ToDisable, initialSet); } if (!candidates.toReEnableCandidates.empty()) { auto n = choose( prevLedger->info().hash, candidates.toReEnableCandidates); assert(nidToKeyMap.count(n)); addTx(seq, nidToKeyMap[n], ToReEnable, initialSet); } } } void NegativeUNLVote::addTx( LedgerIndex seq, PublicKey const& vp, NegativeUNLModify modify, std::shared_ptr<SHAMap> const& initialSet) { STTx negUnlTx(ttUNL_MODIFY, [&](auto& obj) { obj.setFieldU8(sfUNLModifyDisabling, modify == ToDisable ? 1 : 0); obj.setFieldU32(sfLedgerSequence, seq); obj.setFieldVL(sfUNLModifyValidator, vp.slice()); }); uint256 txID = negUnlTx.getTransactionID(); Serializer s; negUnlTx.add(s); if (!initialSet->addGiveItem( SHAMapNodeType::tnTRANSACTION_NM, std::make_shared<SHAMapItem>(txID, s.peekData()))) { JLOG(j_.warn()) << "N-UNL: ledger seq=" << seq << ", add ttUNL_MODIFY tx failed"; } else { JLOG(j_.debug()) << "N-UNL: ledger seq=" << seq << ", add a ttUNL_MODIFY Tx with txID: " << txID << ", the validator to " << (modify == ToDisable ? "disable: " : "re-enable: ") << vp; } } NodeID NegativeUNLVote::choose( uint256 const& randomPadData, std::vector<NodeID> const& candidates) { assert(!candidates.empty()); static_assert(NodeID::bytes <= uint256::bytes); NodeID randomPad = NodeID::fromVoid(randomPadData.data()); NodeID txNodeID = candidates[0]; for (int j = 1; j < candidates.size(); ++j) { if ((candidates[j] ^ randomPad) < (txNodeID ^ randomPad)) { txNodeID = candidates[j]; } } return txNodeID; } std::optional<hash_map<NodeID, std::uint32_t>> NegativeUNLVote::buildScoreTable( std::shared_ptr<Ledger const> const& prevLedger, hash_set<NodeID> const& unl, RCLValidations& validations) { // Find agreed validation messages received for // the last FLAG_LEDGER_INTERVAL (i.e. 256) ledgers, // for every validator, and fill the score table. // Ask the validation container to keep enough validation message history // for next time. auto const seq = prevLedger->info().seq + 1; validations.setSeqToKeep(seq - 1); // Find FLAG_LEDGER_INTERVAL (i.e. 256) previous ledger hashes auto const hashIndex = prevLedger->read(keylet::skip()); if (!hashIndex || !hashIndex->isFieldPresent(sfHashes)) { JLOG(j_.debug()) << "N-UNL: ledger " << seq << " no history."; return {}; } auto const ledgerAncestors = hashIndex->getFieldV256(sfHashes).value(); auto const numAncestors = ledgerAncestors.size(); if (numAncestors < FLAG_LEDGER_INTERVAL) { JLOG(j_.debug()) << "N-UNL: ledger " << seq << " not enough history. Can trace back only " << numAncestors << " ledgers."; return {}; } // have enough ledger ancestors, build the score table hash_map<NodeID, std::uint32_t> scoreTable; for (auto const& k : unl) { scoreTable[k] = 0; } // Query the validation container for every ledger hash and fill // the score table. for (int i = 0; i < FLAG_LEDGER_INTERVAL; ++i) { for (auto const& v : validations.getTrustedForLedger( ledgerAncestors[numAncestors - 1 - i])) { if (scoreTable.count(v->getNodeID())) ++scoreTable[v->getNodeID()]; } } // Return false if the validation message history or local node's // participation in the history is not good. auto const myValidationCount = [&]() -> std::uint32_t { if (auto const it = scoreTable.find(myId_); it != scoreTable.end()) return it->second; return 0; }(); if (myValidationCount < negativeUNLMinLocalValsToVote) { JLOG(j_.debug()) << "N-UNL: ledger " << seq << ". Local node only issued " << myValidationCount << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers." << " The reliability measurement could be wrong."; return {}; } else if ( myValidationCount > negativeUNLMinLocalValsToVote && myValidationCount <= FLAG_LEDGER_INTERVAL) { return scoreTable; } else { // cannot happen because validations.getTrustedForLedger does not // return multiple validations of the same ledger from a validator. JLOG(j_.error()) << "N-UNL: ledger " << seq << ". Local node issued " << myValidationCount << " validations in last " << FLAG_LEDGER_INTERVAL << " ledgers. Too many!"; return {}; } } NegativeUNLVote::Candidates const NegativeUNLVote::findAllCandidates( hash_set<NodeID> const& unl, hash_set<NodeID> const& negUnl, hash_map<NodeID, std::uint32_t> const& scoreTable) { // Compute if need to find more validators to disable auto const canAdd = [&]() -> bool { auto const maxNegativeListed = static_cast<std::size_t>( std::ceil(unl.size() * negativeUNLMaxListed)); std::size_t negativeListed = 0; for (auto const& n : unl) { if (negUnl.count(n)) ++negativeListed; } bool const result = negativeListed < maxNegativeListed; JLOG(j_.trace()) << "N-UNL: nodeId " << myId_ << " lowWaterMark " << negativeUNLLowWaterMark << " highWaterMark " << negativeUNLHighWaterMark << " canAdd " << result << " negativeListed " << negativeListed << " maxNegativeListed " << maxNegativeListed; return result; }(); Candidates candidates; for (auto const& [nodeId, score] : scoreTable) { JLOG(j_.trace()) << "N-UNL: node " << nodeId << " score " << score; // Find toDisable Candidates: check if // (1) canAdd, // (2) has less than negativeUNLLowWaterMark validations, // (3) is not in negUnl, and // (4) is not a new validator. if (canAdd && score < negativeUNLLowWaterMark && !negUnl.count(nodeId) && !newValidators_.count(nodeId)) { JLOG(j_.trace()) << "N-UNL: toDisable candidate " << nodeId; candidates.toDisableCandidates.push_back(nodeId); } // Find toReEnable Candidates: check if // (1) has more than negativeUNLHighWaterMark validations, // (2) is in negUnl if (score > negativeUNLHighWaterMark && negUnl.count(nodeId)) { JLOG(j_.trace()) << "N-UNL: toReEnable candidate " << nodeId; candidates.toReEnableCandidates.push_back(nodeId); } } // If a negative UNL validator is removed from nodes' UNLs, it is no longer // a validator. It should be removed from the negative UNL too. // Note that even if it is still offline and in minority nodes' UNLs, it // will not be re-added to the negative UNL. Because the UNLModify Tx will // not be included in the agreed TxSet of a ledger. // // Find this kind of toReEnable Candidate if did not find any toReEnable // candidate yet: check if // (1) is in negUnl // (2) is not in unl. if (candidates.toReEnableCandidates.empty()) { for (auto const& n : negUnl) { if (!unl.count(n)) { candidates.toReEnableCandidates.push_back(n); } } } return candidates; } void NegativeUNLVote::newValidators( LedgerIndex seq, hash_set<NodeID> const& nowTrusted) { std::lock_guard lock(mutex_); for (auto const& n : nowTrusted) { if (newValidators_.find(n) == newValidators_.end()) { JLOG(j_.trace()) << "N-UNL: add a new validator " << n << " at ledger seq=" << seq; newValidators_[n] = seq; } } } void NegativeUNLVote::purgeNewValidators(LedgerIndex seq) { std::lock_guard lock(mutex_); auto i = newValidators_.begin(); while (i != newValidators_.end()) { if (seq - i->second > newValidatorDisableSkip) { i = newValidators_.erase(i); } else { ++i; } } } } // namespace bixd
[ "eyemotiongamestudio@gmail.com" ]
eyemotiongamestudio@gmail.com
2f181ef76d1cfd07149223a0d354844847a935a0
adb617ebb67e6287ce088d1c3760f900601502c8
/lib-ltc/src/ltcdisplayparamssave.cpp
34ea10a561fb897171b8974444bcea2bf360849e
[]
no_license
smith-48116/rpidmx512
451765f57fc9fed52436a1cc137c89c240d477df
973c90f9d82a2f8072a420980c337b4a1c58bf30
refs/heads/master
2021-01-02T10:02:19.629337
2020-02-09T17:36:25
2020-02-09T17:36:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,205
cpp
/** * @file ltcdisplayparamssave.cpp * */ /* Copyright (C) 2019-2020 by Arjan van Vught mailto:info@raspberrypi-dmx.nl * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #if !defined(__clang__) // Needed for compiling on MacOS #pragma GCC push_options #pragma GCC optimize ("Os") #endif #include <stdint.h> #include <string.h> #include <assert.h> #include "ltcdisplayparams.h" #include "ltcdisplayparamsconst.h" #include "devicesparamsconst.h" // Displays #include "ltcdisplaymax7219.h" #include "ltcdisplayws28xx.h" #include "ws28xx.h" #include "ws28xxconst.h" #include "rgbmapping.h" #include "propertiesbuilder.h" void LtcDisplayParams::Builder(const struct TLtcDisplayParams *ptLtcDisplayParams, uint8_t *pBuffer, uint32_t nLength, uint32_t &nSize) { assert(pBuffer != 0); if (ptLtcDisplayParams != 0) { memcpy(&m_tLtcDisplayParams, ptLtcDisplayParams, sizeof(struct TLtcDisplayParams)); } else { m_pLtcDisplayParamsStore->Copy(&m_tLtcDisplayParams); } PropertiesBuilder builder(LtcDisplayParamsConst::FILE_NAME, pBuffer, nLength); builder.Add(LtcDisplayParamsConst::WS28XX_TYPE, m_tLtcDisplayParams.nWS28xxType == LTCDISPLAYWS28XX_TYPE_7SEGMENT ? "7segment" : "matrix" , isMaskSet(LTCDISPLAY_PARAMS_MASK_WS28XX_TYPE)); builder.Add(DevicesParamsConst::LED_TYPE, WS28xx::GetLedTypeString((TWS28XXType) m_tLtcDisplayParams.nLedType), isMaskSet(LTCDISPLAY_PARAMS_MASK_LED_TYPE)); if (!isMaskSet(LTCDISPLAY_PARAMS_MASK_RGB_MAPPING)) { m_tLtcDisplayParams.nRgbMapping = (uint8_t) WS28xx::GetRgbMapping((TWS28XXType) m_tLtcDisplayParams.nWS28xxType); } builder.Add(DevicesParamsConst::LED_RGB_MAPPING, RGBMapping::ToString((TRGBMapping) m_tLtcDisplayParams.nRgbMapping), isMaskSet(LTCDISPLAY_PARAMS_MASK_RGB_MAPPING)); builder.Add(LtcDisplayParamsConst::WS28XX_INTENSITY, m_tLtcDisplayParams.nWS28xxIntensity, isMaskSet(LTCDISPLAY_PARAMS_MASK_WS28XX_INTENSITY)); builder.Add(LtcDisplayParamsConst::WS28XX_COLON_BLINK_MODE, m_tLtcDisplayParams.nWS28xxColonBlinkMode == LTCDISPLAYWS28XX_COLON_BLINK_MODE_OFF ? "off" : (m_tLtcDisplayParams.nWS28xxColonBlinkMode == LTCDISPLAYWS28XX_COLON_BLINK_MODE_DOWN ? "down" : "up") , isMaskSet(LTCDISPLAY_PARAMS_MASK_WS28XX_COLON_BLINK_MODE)); for (uint32_t nIndex = 0; nIndex < LTCDISPLAYWS28XX_COLOUR_INDEX_LAST; nIndex++) { builder.AddHex24(LtcDisplayParamsConst::WS28XX_COLOUR[nIndex], m_tLtcDisplayParams.aWS28xxColour[nIndex],isMaskSet(LTCDISPLAY_PARAMS_MASK_WS28XX_COLOUR_INDEX << nIndex)); } builder.Add(LtcDisplayParamsConst::MAX7219_TYPE, m_tLtcDisplayParams.nMax7219Type == LTCDISPLAYMAX7219_TYPE_7SEGMENT ? "7segment" : "matrix" , isMaskSet(LTCDISPLAY_PARAMS_MASK_MAX7219_TYPE)); builder.Add(LtcDisplayParamsConst::MAX7219_INTENSITY, m_tLtcDisplayParams.nMax7219Intensity, isMaskSet(LTCDISPLAY_PARAMS_MASK_MAX7219_INTENSITY)); builder.Add(DevicesParamsConst::GLOBAL_BRIGHTNESS, m_tLtcDisplayParams.nGlobalBrightness, isMaskSet(LTCDISPLAY_PARAMS_MASK_GLOBAL_BRIGHTNESS)); nSize = builder.GetSize(); } void LtcDisplayParams::Save(uint8_t *pBuffer, uint32_t nLength, uint32_t &nSize) { if (m_pLtcDisplayParamsStore == 0) { nSize = 0; return; } Builder(0, pBuffer, nLength, nSize); }
[ "Arjan.van.Vught@gmail.com" ]
Arjan.van.Vught@gmail.com
330383e4afbedb82ab2dfbd507afc59f92522d6b
e37003a3e3309a0a385c71b2aaf505870b444f62
/src/ui/views/controls/combobox/combobox_unittest.cc
ea81193011ccb0beb9a4859d28330f18067974fe
[ "BSD-3-Clause", "MIT" ]
permissive
joshgarde/aurora
d2128e598a09adb1092af1fdf16369993c33204a
3afc1c70facbf78030e58ce543c93131d979a7b8
refs/heads/master
2020-12-24T10:57:31.412033
2016-07-12T07:44:36
2016-07-12T07:44:36
63,039,902
2
0
null
null
null
null
UTF-8
C++
false
false
26,923
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/combobox/combobox.h" #include <set> #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "ui/base/ime/input_method.h" #include "ui/base/ime/text_input_client.h" #include "ui/base/models/combobox_model.h" #include "ui/base/models/menu_model.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" #include "ui/events/event_utils.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/views/controls/combobox/combobox_listener.h" #include "ui/views/test/combobox_test_api.h" #include "ui/views/test/views_test_base.h" #include "ui/views/widget/widget.h" using base::ASCIIToUTF16; namespace views { using test::ComboboxTestApi; namespace { // A wrapper of Combobox to intercept the result of OnKeyPressed() and // OnKeyReleased() methods. class TestCombobox : public Combobox { public: TestCombobox(ui::ComboboxModel* model, Combobox::Style style) : Combobox(model, style), key_handled_(false), key_received_(false) {} bool OnKeyPressed(const ui::KeyEvent& e) override { key_received_ = true; key_handled_ = Combobox::OnKeyPressed(e); return key_handled_; } bool OnKeyReleased(const ui::KeyEvent& e) override { key_received_ = true; key_handled_ = Combobox::OnKeyReleased(e); return key_handled_; } bool key_handled() const { return key_handled_; } bool key_received() const { return key_received_; } void clear() { key_received_ = key_handled_ = false; } private: bool key_handled_; bool key_received_; DISALLOW_COPY_AND_ASSIGN(TestCombobox); }; // A concrete class is needed to test the combobox. class TestComboboxModel : public ui::ComboboxModel { public: TestComboboxModel() {} ~TestComboboxModel() override {} enum { kItemCount = 10 }; // ui::ComboboxModel: int GetItemCount() const override { return item_count_; } base::string16 GetItemAt(int index) override { if (IsItemSeparatorAt(index)) { NOTREACHED(); return ASCIIToUTF16("SEPARATOR"); } return ASCIIToUTF16(index % 2 == 0 ? "PEANUT BUTTER" : "JELLY"); } bool IsItemSeparatorAt(int index) override { return separators_.find(index) != separators_.end(); } int GetDefaultIndex() const override { // Return the first index that is not a separator. for (int index = 0; index < kItemCount; ++index) { if (separators_.find(index) == separators_.end()) return index; } NOTREACHED(); return 0; } void SetSeparators(const std::set<int>& separators) { separators_ = separators; } void set_item_count(int item_count) { item_count_ = item_count; } private: std::set<int> separators_; int item_count_ = kItemCount; DISALLOW_COPY_AND_ASSIGN(TestComboboxModel); }; // A combobox model which refers to a vector. class VectorComboboxModel : public ui::ComboboxModel { public: explicit VectorComboboxModel(std::vector<std::string>* values) : values_(values) {} ~VectorComboboxModel() override {} void set_default_index(int default_index) { default_index_ = default_index; } // ui::ComboboxModel: int GetItemCount() const override { return (int)values_->size(); } base::string16 GetItemAt(int index) override { return ASCIIToUTF16(values_->at(index)); } bool IsItemSeparatorAt(int index) override { return false; } int GetDefaultIndex() const override { return default_index_; } private: std::vector<std::string>* values_; int default_index_ = 0; DISALLOW_COPY_AND_ASSIGN(VectorComboboxModel); }; class EvilListener : public ComboboxListener { public: EvilListener() : deleted_(false) {} ~EvilListener() override{}; // ComboboxListener: void OnPerformAction(Combobox* combobox) override { delete combobox; deleted_ = true; } bool deleted() const { return deleted_; } private: bool deleted_; DISALLOW_COPY_AND_ASSIGN(EvilListener); }; class TestComboboxListener : public views::ComboboxListener { public: TestComboboxListener() : perform_action_index_(-1), actions_performed_(0) {} ~TestComboboxListener() override {} void OnPerformAction(views::Combobox* combobox) override { perform_action_index_ = combobox->selected_index(); actions_performed_++; } int perform_action_index() const { return perform_action_index_; } bool on_perform_action_called() const { return actions_performed_ > 0; } int actions_performed() const { return actions_performed_; } private: int perform_action_index_; int actions_performed_; private: DISALLOW_COPY_AND_ASSIGN(TestComboboxListener); }; } // namespace class ComboboxTest : public ViewsTestBase { public: ComboboxTest() : widget_(NULL), combobox_(NULL) {} void TearDown() override { if (widget_) widget_->Close(); ViewsTestBase::TearDown(); } void InitCombobox(const std::set<int>* separators, Combobox::Style style) { model_.reset(new TestComboboxModel()); if (separators) model_->SetSeparators(*separators); ASSERT_FALSE(combobox_); combobox_ = new TestCombobox(model_.get(), style); test_api_.reset(new ComboboxTestApi(combobox_)); combobox_->set_id(1); widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(200, 200, 200, 200); widget_->Init(params); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(combobox_); combobox_->RequestFocus(); combobox_->SizeToPreferredSize(); } protected: void SendKeyEvent(ui::KeyboardCode key_code) { SendKeyEventWithType(key_code, ui::ET_KEY_PRESSED); } void SendKeyEventWithType(ui::KeyboardCode key_code, ui::EventType type) { ui::KeyEvent event(type, key_code, ui::EF_NONE); FocusManager* focus_manager = widget_->GetFocusManager(); widget_->OnKeyEvent(&event); if (!event.handled() && focus_manager) focus_manager->OnKeyEvent(event); } View* GetFocusedView() { return widget_->GetFocusManager()->GetFocusedView(); } void PerformMousePress(const gfx::Point& point) { ui::MouseEvent pressed_event = ui::MouseEvent( ui::ET_MOUSE_PRESSED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); widget_->OnMouseEvent(&pressed_event); } void PerformMouseRelease(const gfx::Point& point) { ui::MouseEvent released_event = ui::MouseEvent( ui::ET_MOUSE_RELEASED, point, point, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); widget_->OnMouseEvent(&released_event); } void PerformClick(const gfx::Point& point) { PerformMousePress(point); PerformMouseRelease(point); } // We need widget to populate wrapper class. Widget* widget_; // |combobox_| will be allocated InitCombobox() and then owned by |widget_|. TestCombobox* combobox_; std::unique_ptr<ComboboxTestApi> test_api_; // Combobox does not take ownership of the model, hence it needs to be scoped. std::unique_ptr<TestComboboxModel> model_; private: DISALLOW_COPY_AND_ASSIGN(ComboboxTest); }; TEST_F(ComboboxTest, KeyTest) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); SendKeyEvent(ui::VKEY_END); EXPECT_EQ(combobox_->selected_index() + 1, model_->GetItemCount()); SendKeyEvent(ui::VKEY_HOME); EXPECT_EQ(combobox_->selected_index(), 0); SendKeyEvent(ui::VKEY_DOWN); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(combobox_->selected_index(), 2); SendKeyEvent(ui::VKEY_RIGHT); EXPECT_EQ(combobox_->selected_index(), 2); SendKeyEvent(ui::VKEY_LEFT); EXPECT_EQ(combobox_->selected_index(), 2); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(combobox_->selected_index(), 1); SendKeyEvent(ui::VKEY_PRIOR); EXPECT_EQ(combobox_->selected_index(), 0); SendKeyEvent(ui::VKEY_NEXT); EXPECT_EQ(combobox_->selected_index(), model_->GetItemCount() - 1); } // Check that if a combobox is disabled before it has a native wrapper, then the // native wrapper inherits the disabled state when it gets created. TEST_F(ComboboxTest, DisabilityTest) { model_.reset(new TestComboboxModel()); ASSERT_FALSE(combobox_); combobox_ = new TestCombobox(model_.get(), Combobox::STYLE_NORMAL); combobox_->SetEnabled(false); widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(100, 100, 100, 100); widget_->Init(params); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(combobox_); EXPECT_FALSE(combobox_->enabled()); } // Verifies that we don't select a separator line in combobox when navigating // through keyboard. TEST_F(ComboboxTest, SkipSeparatorSimple) { std::set<int> separators; separators.insert(2); InitCombobox(&separators, Combobox::STYLE_NORMAL); EXPECT_EQ(0, combobox_->selected_index()); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(1, combobox_->selected_index()); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(3, combobox_->selected_index()); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(1, combobox_->selected_index()); SendKeyEvent(ui::VKEY_HOME); EXPECT_EQ(0, combobox_->selected_index()); SendKeyEvent(ui::VKEY_PRIOR); EXPECT_EQ(0, combobox_->selected_index()); SendKeyEvent(ui::VKEY_END); EXPECT_EQ(9, combobox_->selected_index()); } // Verifies that we never select the separator that is in the beginning of the // combobox list when navigating through keyboard. TEST_F(ComboboxTest, SkipSeparatorBeginning) { std::set<int> separators; separators.insert(0); InitCombobox(&separators, Combobox::STYLE_NORMAL); EXPECT_EQ(1, combobox_->selected_index()); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(2, combobox_->selected_index()); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(3, combobox_->selected_index()); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(2, combobox_->selected_index()); SendKeyEvent(ui::VKEY_HOME); EXPECT_EQ(1, combobox_->selected_index()); SendKeyEvent(ui::VKEY_PRIOR); EXPECT_EQ(1, combobox_->selected_index()); SendKeyEvent(ui::VKEY_END); EXPECT_EQ(9, combobox_->selected_index()); } // Verifies that we never select the separator that is in the end of the // combobox list when navigating through keyboard. TEST_F(ComboboxTest, SkipSeparatorEnd) { std::set<int> separators; separators.insert(TestComboboxModel::kItemCount - 1); InitCombobox(&separators, Combobox::STYLE_NORMAL); combobox_->SetSelectedIndex(8); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(8, combobox_->selected_index()); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(7, combobox_->selected_index()); SendKeyEvent(ui::VKEY_END); EXPECT_EQ(8, combobox_->selected_index()); } // Verifies that we never select any of the adjacent separators (multiple // consecutive) that appear in the beginning of the combobox list when // navigating through keyboard. TEST_F(ComboboxTest, SkipMultipleSeparatorsAtBeginning) { std::set<int> separators; separators.insert(0); separators.insert(1); separators.insert(2); InitCombobox(&separators, Combobox::STYLE_NORMAL); EXPECT_EQ(3, combobox_->selected_index()); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(4, combobox_->selected_index()); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(3, combobox_->selected_index()); SendKeyEvent(ui::VKEY_NEXT); EXPECT_EQ(9, combobox_->selected_index()); SendKeyEvent(ui::VKEY_HOME); EXPECT_EQ(3, combobox_->selected_index()); SendKeyEvent(ui::VKEY_END); EXPECT_EQ(9, combobox_->selected_index()); SendKeyEvent(ui::VKEY_PRIOR); EXPECT_EQ(3, combobox_->selected_index()); } // Verifies that we never select any of the adjacent separators (multiple // consecutive) that appear in the middle of the combobox list when navigating // through keyboard. TEST_F(ComboboxTest, SkipMultipleAdjacentSeparatorsAtMiddle) { std::set<int> separators; separators.insert(4); separators.insert(5); separators.insert(6); InitCombobox(&separators, Combobox::STYLE_NORMAL); combobox_->SetSelectedIndex(3); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(7, combobox_->selected_index()); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(3, combobox_->selected_index()); } // Verifies that we never select any of the adjacent separators (multiple // consecutive) that appear in the end of the combobox list when navigating // through keyboard. TEST_F(ComboboxTest, SkipMultipleSeparatorsAtEnd) { std::set<int> separators; separators.insert(7); separators.insert(8); separators.insert(9); InitCombobox(&separators, Combobox::STYLE_NORMAL); combobox_->SetSelectedIndex(6); SendKeyEvent(ui::VKEY_DOWN); EXPECT_EQ(6, combobox_->selected_index()); SendKeyEvent(ui::VKEY_UP); EXPECT_EQ(5, combobox_->selected_index()); SendKeyEvent(ui::VKEY_HOME); EXPECT_EQ(0, combobox_->selected_index()); SendKeyEvent(ui::VKEY_NEXT); EXPECT_EQ(6, combobox_->selected_index()); SendKeyEvent(ui::VKEY_PRIOR); EXPECT_EQ(0, combobox_->selected_index()); SendKeyEvent(ui::VKEY_END); EXPECT_EQ(6, combobox_->selected_index()); } TEST_F(ComboboxTest, GetTextForRowTest) { std::set<int> separators; separators.insert(0); separators.insert(1); separators.insert(9); InitCombobox(&separators, Combobox::STYLE_NORMAL); for (int i = 0; i < combobox_->GetRowCount(); ++i) { if (separators.count(i) != 0) { EXPECT_TRUE(combobox_->GetTextForRow(i).empty()) << i; } else { EXPECT_EQ(ASCIIToUTF16(i % 2 == 0 ? "PEANUT BUTTER" : "JELLY"), combobox_->GetTextForRow(i)) << i; } } } // Verifies selecting the first matching value (and returning whether found). TEST_F(ComboboxTest, SelectValue) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); ASSERT_EQ(model_->GetDefaultIndex(), combobox_->selected_index()); EXPECT_TRUE(combobox_->SelectValue(ASCIIToUTF16("PEANUT BUTTER"))); EXPECT_EQ(0, combobox_->selected_index()); EXPECT_TRUE(combobox_->SelectValue(ASCIIToUTF16("JELLY"))); EXPECT_EQ(1, combobox_->selected_index()); EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("BANANAS"))); EXPECT_EQ(1, combobox_->selected_index()); } TEST_F(ComboboxTest, SelectValueActionStyle) { // With the action style, the selected index is always 0. InitCombobox(nullptr, Combobox::STYLE_ACTION); EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("PEANUT BUTTER"))); EXPECT_EQ(0, combobox_->selected_index()); EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("JELLY"))); EXPECT_EQ(0, combobox_->selected_index()); EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("BANANAS"))); EXPECT_EQ(0, combobox_->selected_index()); } TEST_F(ComboboxTest, SelectIndexActionStyle) { InitCombobox(nullptr, Combobox::STYLE_ACTION); // With the action style, the selected index is always 0. combobox_->SetSelectedIndex(1); EXPECT_EQ(0, combobox_->selected_index()); combobox_->SetSelectedIndex(2); EXPECT_EQ(0, combobox_->selected_index()); combobox_->SetSelectedIndex(3); EXPECT_EQ(0, combobox_->selected_index()); } TEST_F(ComboboxTest, ListenerHandlesDelete) { TestComboboxModel model; // |combobox| will be deleted on change. TestCombobox* combobox = new TestCombobox(&model, Combobox::STYLE_NORMAL); std::unique_ptr<EvilListener> evil_listener(new EvilListener()); combobox->set_listener(evil_listener.get()); ASSERT_NO_FATAL_FAILURE(ComboboxTestApi(combobox).PerformActionAt(2)); EXPECT_TRUE(evil_listener->deleted()); // With STYLE_ACTION // |combobox| will be deleted on change. combobox = new TestCombobox(&model, Combobox::STYLE_ACTION); evil_listener.reset(new EvilListener()); combobox->set_listener(evil_listener.get()); ASSERT_NO_FATAL_FAILURE(ComboboxTestApi(combobox).PerformActionAt(2)); EXPECT_TRUE(evil_listener->deleted()); } TEST_F(ComboboxTest, Click) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); TestComboboxListener listener; combobox_->set_listener(&listener); combobox_->Layout(); int menu_show_count = 0; test_api_->InstallTestMenuRunner(&menu_show_count); // Click the left side. The menu is shown. EXPECT_EQ(0, menu_show_count); PerformClick(gfx::Point(combobox_->x() + 1, combobox_->y() + combobox_->height() / 2)); EXPECT_FALSE(listener.on_perform_action_called()); EXPECT_EQ(1, menu_show_count); } TEST_F(ComboboxTest, ClickButDisabled) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); TestComboboxListener listener; combobox_->set_listener(&listener); combobox_->Layout(); combobox_->SetEnabled(false); // Click the left side, but nothing happens since the combobox is disabled. int menu_show_count = 0; test_api_->InstallTestMenuRunner(&menu_show_count); PerformClick(gfx::Point(combobox_->x() + 1, combobox_->y() + combobox_->height() / 2)); EXPECT_FALSE(listener.on_perform_action_called()); EXPECT_EQ(0, menu_show_count); } TEST_F(ComboboxTest, NotifyOnClickWithReturnKey) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); TestComboboxListener listener; combobox_->set_listener(&listener); // With STYLE_NORMAL, the click event is ignored. SendKeyEvent(ui::VKEY_RETURN); EXPECT_FALSE(listener.on_perform_action_called()); } TEST_F(ComboboxTest, NotifyOnClickWithReturnKeyActionStyle) { InitCombobox(nullptr, Combobox::STYLE_ACTION); TestComboboxListener listener; combobox_->set_listener(&listener); // With STYLE_ACTION, the click event is notified. SendKeyEvent(ui::VKEY_RETURN); EXPECT_TRUE(listener.on_perform_action_called()); EXPECT_EQ(0, listener.perform_action_index()); } TEST_F(ComboboxTest, NotifyOnClickWithSpaceKey) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); TestComboboxListener listener; combobox_->set_listener(&listener); // With STYLE_NORMAL, the click event is ignored. SendKeyEvent(ui::VKEY_SPACE); EXPECT_FALSE(listener.on_perform_action_called()); SendKeyEventWithType(ui::VKEY_SPACE, ui::ET_KEY_RELEASED); EXPECT_FALSE(listener.on_perform_action_called()); } TEST_F(ComboboxTest, NotifyOnClickWithSpaceKeyActionStyle) { InitCombobox(nullptr, Combobox::STYLE_ACTION); TestComboboxListener listener; combobox_->set_listener(&listener); // With STYLE_ACTION, the click event is notified after releasing. SendKeyEvent(ui::VKEY_SPACE); EXPECT_FALSE(listener.on_perform_action_called()); SendKeyEventWithType(ui::VKEY_SPACE, ui::ET_KEY_RELEASED); EXPECT_TRUE(listener.on_perform_action_called()); EXPECT_EQ(0, listener.perform_action_index()); } TEST_F(ComboboxTest, NotifyOnClickWithMouse) { InitCombobox(nullptr, Combobox::STYLE_ACTION); TestComboboxListener listener; combobox_->set_listener(&listener); combobox_->Layout(); // Click the right side (arrow button). The menu is shown. int menu_show_count = 0; test_api_->InstallTestMenuRunner(&menu_show_count); const gfx::Point right_point(combobox_->x() + combobox_->width() - 1, combobox_->y() + combobox_->height() / 2); EXPECT_EQ(0, menu_show_count); // On Mac, actions occur on mouse down. Otherwise mouse up. #if defined(OS_MACOSX) const int kActOnMouseDown = 1; #else const int kActOnMouseDown = 0; #endif PerformMousePress(right_point); EXPECT_EQ(kActOnMouseDown, menu_show_count); PerformMouseRelease(right_point); EXPECT_EQ(1, menu_show_count); // Click the left side (text button). The click event is notified. const gfx::Point left_point( gfx::Point(combobox_->x() + 1, combobox_->y() + combobox_->height() / 2)); test_api_->InstallTestMenuRunner(&menu_show_count); PerformMousePress(left_point); PerformMouseRelease(left_point); EXPECT_EQ(1, menu_show_count); // Unchanged. EXPECT_EQ(0, listener.perform_action_index()); } TEST_F(ComboboxTest, ConsumingPressKeyEvents) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); EXPECT_FALSE(combobox_->OnKeyPressed( ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE))); EXPECT_FALSE(combobox_->OnKeyPressed( ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE))); } TEST_F(ComboboxTest, ConsumingKeyPressEventsActionStyle) { // When the combobox's style is STYLE_ACTION, pressing events of a space key // or an enter key will be consumed. InitCombobox(nullptr, Combobox::STYLE_ACTION); EXPECT_TRUE(combobox_->OnKeyPressed( ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE))); EXPECT_TRUE(combobox_->OnKeyPressed( ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE))); } TEST_F(ComboboxTest, ContentWidth) { std::vector<std::string> values; VectorComboboxModel model(&values); TestCombobox combobox(&model, Combobox::STYLE_NORMAL); TestCombobox action_combobox(&model, Combobox::STYLE_ACTION); ComboboxTestApi test_api(&combobox); ComboboxTestApi action_test_api(&action_combobox); std::string long_item = "this is the long item"; std::string short_item = "s"; values.resize(1); values[0] = long_item; combobox.ModelChanged(); action_combobox.ModelChanged(); const int long_item_width = test_api.content_size().width(); values[0] = short_item; combobox.ModelChanged(); action_combobox.ModelChanged(); const int short_item_width = test_api.content_size().width(); values.resize(2); values[0] = short_item; values[1] = long_item; combobox.ModelChanged(); action_combobox.ModelChanged(); // When the style is STYLE_NORMAL, the width will fit with the longest item. EXPECT_EQ(long_item_width, test_api.content_size().width()); // When the style is STYLE_ACTION, the width will fit with the selected item's // width. EXPECT_EQ(short_item_width, action_test_api.content_size().width()); } // Test that model updates preserve the selected index, so long as it is in // range. TEST_F(ComboboxTest, ModelChanged) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); EXPECT_EQ(0, combobox_->GetSelectedRow()); EXPECT_EQ(10, combobox_->GetRowCount()); combobox_->SetSelectedIndex(4); EXPECT_EQ(4, combobox_->GetSelectedRow()); model_->set_item_count(5); combobox_->ModelChanged(); EXPECT_EQ(5, combobox_->GetRowCount()); EXPECT_EQ(4, combobox_->GetSelectedRow()); // Unchanged. model_->set_item_count(4); combobox_->ModelChanged(); EXPECT_EQ(4, combobox_->GetRowCount()); EXPECT_EQ(0, combobox_->GetSelectedRow()); // Resets. // Restore a non-zero selection. combobox_->SetSelectedIndex(2); EXPECT_EQ(2, combobox_->GetSelectedRow()); // Make the selected index a separator. std::set<int> separators; separators.insert(2); model_->SetSeparators(separators); combobox_->ModelChanged(); EXPECT_EQ(4, combobox_->GetRowCount()); EXPECT_EQ(0, combobox_->GetSelectedRow()); // Resets. // Restore a non-zero selection. combobox_->SetSelectedIndex(1); EXPECT_EQ(1, combobox_->GetSelectedRow()); // Test an empty model. model_->set_item_count(0); combobox_->ModelChanged(); EXPECT_EQ(0, combobox_->GetRowCount()); EXPECT_EQ(0, combobox_->GetSelectedRow()); // Resets. } TEST_F(ComboboxTest, TypingPrefixNotifiesListener) { InitCombobox(nullptr, Combobox::STYLE_NORMAL); TestComboboxListener listener; combobox_->set_listener(&listener); ui::TextInputClient* input_client = widget_->GetInputMethod()->GetTextInputClient(); // Type the first character of the second menu item ("JELLY"). ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_J, ui::DomCode::US_J, 0, ui::DomKey::FromCharacter('J'), ui::EventTimeForNow()); input_client->InsertChar(key_event); EXPECT_EQ(1, listener.actions_performed()); EXPECT_EQ(1, listener.perform_action_index()); // Type the second character of "JELLY", item shouldn't change and // OnPerformAction() shouldn't be re-called. key_event = ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_E, ui::DomCode::US_E, 0, ui::DomKey::FromCharacter('E'), ui::EventTimeForNow()); input_client->InsertChar(key_event); EXPECT_EQ(1, listener.actions_performed()); EXPECT_EQ(1, listener.perform_action_index()); // Clears the typed text. combobox_->OnBlur(); combobox_->RequestFocus(); // Type the first character of "PEANUT BUTTER", which should change the // selected index and perform an action. key_event = ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_E, ui::DomCode::US_P, 0, ui::DomKey::FromCharacter('P'), ui::EventTimeForNow()); input_client->InsertChar(key_event); EXPECT_EQ(2, listener.actions_performed()); EXPECT_EQ(2, listener.perform_action_index()); } // Test properties on the Combobox menu model. TEST_F(ComboboxTest, MenuModel) { const int kSeparatorIndex = 3; std::set<int> separators; separators.insert(kSeparatorIndex); InitCombobox(&separators, Combobox::STYLE_NORMAL); ui::MenuModel* menu_model = test_api_->menu_model(); EXPECT_EQ(TestComboboxModel::kItemCount, menu_model->GetItemCount()); EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, menu_model->GetTypeAt(kSeparatorIndex)); #if defined(OS_MACOSX) // Comboboxes on Mac should have checkmarks, with the selected item checked, EXPECT_EQ(ui::MenuModel::TYPE_CHECK, menu_model->GetTypeAt(0)); EXPECT_EQ(ui::MenuModel::TYPE_CHECK, menu_model->GetTypeAt(1)); EXPECT_TRUE(menu_model->IsItemCheckedAt(0)); EXPECT_FALSE(menu_model->IsItemCheckedAt(1)); combobox_->SetSelectedIndex(1); EXPECT_FALSE(menu_model->IsItemCheckedAt(0)); EXPECT_TRUE(menu_model->IsItemCheckedAt(1)); #else EXPECT_EQ(ui::MenuModel::TYPE_COMMAND, menu_model->GetTypeAt(0)); EXPECT_EQ(ui::MenuModel::TYPE_COMMAND, menu_model->GetTypeAt(1)); #endif EXPECT_EQ(ASCIIToUTF16("PEANUT BUTTER"), menu_model->GetLabelAt(0)); EXPECT_EQ(ASCIIToUTF16("JELLY"), menu_model->GetLabelAt(1)); EXPECT_TRUE(menu_model->IsVisibleAt(0)); } // Check that with STYLE_ACTION, the first item (only) is not shown. TEST_F(ComboboxTest, MenuModelActionStyleMac) { const int kSeparatorIndex = 3; std::set<int> separators; separators.insert(kSeparatorIndex); InitCombobox(&separators, Combobox::STYLE_ACTION); ui::MenuModel* menu_model = test_api_->menu_model(); EXPECT_EQ(TestComboboxModel::kItemCount, menu_model->GetItemCount()); EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, menu_model->GetTypeAt(kSeparatorIndex)); EXPECT_EQ(ui::MenuModel::TYPE_COMMAND, menu_model->GetTypeAt(0)); EXPECT_EQ(ui::MenuModel::TYPE_COMMAND, menu_model->GetTypeAt(1)); EXPECT_EQ(ASCIIToUTF16("PEANUT BUTTER"), menu_model->GetLabelAt(0)); EXPECT_EQ(ASCIIToUTF16("JELLY"), menu_model->GetLabelAt(1)); EXPECT_FALSE(menu_model->IsVisibleAt(0)); EXPECT_TRUE(menu_model->IsVisibleAt(1)); } } // namespace views
[ "joshgarde@gmail.com" ]
joshgarde@gmail.com
38c510fe7d0a88ff89ff57d9a7babe4e5046f64b
11e97f87deb25babb4a32c80941e7ff4e476c92a
/AUS/HRT_450T/Motion/FormSerial.cpp
804d7c1dc92c92d8ad46ce770a360843db93d7b4
[]
no_license
xhyangxianjun/Builder6-program
b9d03d98658db5a5a8cf1586210a373bc391dc48
a12d811d7a5fa3dba6d3e8c05989a41cb89783de
refs/heads/master
2022-04-03T00:25:47.274355
2019-09-19T08:26:56
2019-09-19T08:26:56
null
0
0
null
null
null
null
UHC
C++
false
false
2,751
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "UtilDefine.h" #include "UserIni.h" #include "FormSerial.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" #define SERIAL_PATH "C:\\Serial.srl" TFrmSerial *FrmSerial; //--------------------------------------------------------------------------- __fastcall TFrmSerial::TFrmSerial(TComponent* Owner) : TForm(Owner) { String sSerialList = EQP_SERIAL_LIST ; String sSerial ; while(sSerialList !=""){ if(sSerialList.Pos(",")){ sSerial = sSerialList.SubString(1,sSerialList.Pos(",")-1); sSerialList.Delete(1,sSerialList.Pos(",")); lbSerial -> AddItem(sSerial , NULL); } } } //--------------------------------------------------------------------------- void __fastcall TFrmSerial::btSetSerialClick(TObject *Sender) { //[lbSerial -> ItemIndex] AnsiString sTemp = lbSerial -> Items -> Strings[lbSerial -> ItemIndex] ; edSerial -> Text = sTemp ; TUserINI UserINI; //Make Dir. String sFilePath = SERIAL_PATH; AnsiString sSerial = sTemp ; UserINI.Save(sFilePath.c_str() , "Data" , "Serial" , sSerial ); } //--------------------------------------------------------------------------- bool TFrmSerial::CheckSourceSerial() { TUserINI UserINI; //Make Dir. String sFilePath = SERIAL_PATH; AnsiString sSerial ; if(!FileExists(sFilePath)) { edSerial -> Text = ""; return false ; } UserINI.Load(sFilePath.c_str() , "Data" , "Serial" , sSerial ); edSerial -> Text = sSerial ; String sSerialList = EQP_SERIAL_LIST ; sSerial = edSerial -> Text ; /* 어떤 프로그램이.. C++ 빌더 IDE 에서 실행되고 있는지를 알아 내려면... 상용 컴포넌트 제작사들이 하는 식으로... 패런트 프로세스 아이디를 알아내서... 그 프로세스가 "BDS.EXE"인지를 확인하는 게 가장 효과적인 방법임... http://cbuilder.borlandforum.com/impboard/impboard.dll?action=read&db=bcb_qna&no=68495 */ bool bTemp = IsDebuggerPresent() ; bool bRet = (sSerialList.Pos(sSerial+",") || IsDebuggerPresent()) ; return bRet ; } void __fastcall TFrmSerial::btCloseClick(TObject *Sender) { Close(); } //--------------------------------------------------------------------------- void __fastcall TFrmSerial::FormClose(TObject *Sender, TCloseAction &Action) { ModalResult = mrOk ; } //---------------------------------------------------------------------------
[ "sheepdw@gmail.com" ]
sheepdw@gmail.com
3c2f7a03802c2f6818075074e27fe70c1e422e99
4b1d86c3b19b4c469769b0c5297c93573d092c4f
/projects/Topic_04_NavMesh/Topic_04_NavMesh.h
0354e4d2dac8d3bf8f3e3ff90ee44ff420150f64
[ "MIT" ]
permissive
iancarnation/AIE_Systems_Exercises
07cfda65779b338cd60590f83ba97f3330a997f3
16d2390956d1902b738b6f44929a3fa732aa634f
refs/heads/master
2021-01-02T06:33:15.118877
2015-01-23T22:53:37
2015-01-23T22:53:37
26,340,432
0
0
null
null
null
null
UTF-8
C++
false
false
955
h
#pragma once #include "Application.h" #include <glm/glm.hpp> #include <FBXFile.h> // derived application class that wraps up all globals neatly class Topic_04_NavMesh : public Application { public: Topic_04_NavMesh(); virtual ~Topic_04_NavMesh(); struct NavNodeTri { glm::vec3 position; glm::vec3 vertices[3]; NavNodeTri* adjacentNodes[3]; float f, g, h; NavNodeTri* parent; }; std::vector<NavNodeTri*> m_graph; protected: virtual bool onCreate(int a_argc, char* a_argv[]); virtual void onUpdate(float a_deltaTime); virtual void onDraw(); virtual void onDestroy(); void buildNavMesh(FBXMeshNode* a_mesh, std::vector<NavNodeTri*>& a_graph); void createOpenGLBuffers(FBXFile* a_fbx); void cleanupOpenGLBuffers(FBXFile* a_fbx); struct GLData { unsigned int vao, vbo, ibo; }; FBXFile* m_sponza; FBXFile* m_navMesh; unsigned int m_shaderProgram; glm::mat4 m_cameraMatrix; glm::mat4 m_projectionMatrix; };
[ "iancarnation@gmail.com" ]
iancarnation@gmail.com
16d7d38d90fef262e466dc474faea99f62d2eaed
d4f8f61167ffcc80f6f6d8eca763f5ec2c4672e1
/Tensors/order_n_tensor.hpp
0432b69b607ddf5d5218ab4ed033e92801cb9d31
[]
no_license
VenuGopal1899/Cpp-Projects
81d8f81039774063317a2fb6e173199698548fc1
682bb36be425ac9b43f2cf0fdcb599c4a6e6f5f0
refs/heads/master
2022-11-21T16:37:21.743253
2020-07-22T04:06:35
2020-07-22T04:06:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
701
hpp
#ifndef ordern_tensor_hpp #define ordern_tensor_hpp #include "tensor.hpp" /* Implements an order-3 tensor. */ class MatrixTensorN : public Tensor { private: vector<size_t> m_size; vector<vector<float>> m_values; public: MatrixTensorN(const vector<size_t> &_size) { resize(_size); } const vector<size_t> &size() const override { return m_size; } void resize(const vector<size_t> &dims) override { } virtual float read(const vector<size_t> &i) const override { } virtual void write(const vector<size_t> &i, float value) override { } }; #endif
[ "venumalladi18@gmail.com" ]
venumalladi18@gmail.com
5b404d852150b17161d7d5f517f8bbc364ac9389
3803dc5e1f51cb251110127d453ab96f55596745
/pod_core/capi/scheme_table_vrfq_test_capi.h
93e566397f9afda2674c5143f826d2278c5269a6
[]
no_license
huyuguang/ZkPod2-lib
da92c3ca6fb07b83e78c74c6a01d7347d8505814
ce3f438829f1e729ce14c5dd22231c75cf3a6237
refs/heads/master
2021-07-07T16:05:30.504736
2020-12-30T09:11:07
2020-12-30T09:11:07
215,526,300
3
0
null
null
null
null
UTF-8
C++
false
false
302
h
#pragma once #include <string> #include <vector> namespace scheme::table::vrfq::capi { bool Test(std::string const& publish_path, std::string const& output_path, std::string const& query_key, std::vector<std::string> const& query_values); } // namespace scheme::table::vrfq::capi
[ "yuguang.hu@outlook.com" ]
yuguang.hu@outlook.com
83f821e6555775170d78418521c5852ecf7ae9d9
6ec46668f3341e0be1ffdf36eb463b74732354ed
/source/Cpps/Engine/Terrain/TerrainMesh.cpp
acc5434f56714dc21b90ce76bee05c2fbfb21307
[]
no_license
Game-Engine-Development/Forest-Game-Engine
ec01f2df147c5cba4a2fa2207431ccda7d2fe133
6d8595d2247e0da2dde83891259d40d06d2e65c3
refs/heads/master
2023-03-03T04:02:49.052586
2021-02-04T22:15:42
2021-02-04T22:15:42
273,428,561
1
0
null
null
null
null
UTF-8
C++
false
false
7,362
cpp
#include "Headers/Engine/Terrain/TerrainMesh.h" TerrainMesh::TerrainMesh(const char *const filename) : noise(std::nullopt) { loadTerrain(vertices, normals, texCoords, indices, filename); numOfVertices = indices.size(); glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &texCoordBuffer); glGenBuffers(1, &EBO); glGenBuffers(1, &normalBuffer); bindVAO(); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer); glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, 0); unbindVAO(); } TerrainMesh::TerrainMesh(const char *const filename, const long seed) : noise(Noise::OpenSimplex2S(seed)) { loadTerrain(vertices, normals, texCoords, indices, filename); numOfVertices = indices.size(); glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &texCoordBuffer); glGenBuffers(1, &EBO); glGenBuffers(1, &normalBuffer); bindVAO(); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer); glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(glm::vec2), &texCoords[0], GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), nullptr); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, 0); unbindVAO(); } TerrainMesh::~TerrainMesh() { glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &texCoordBuffer); glDeleteBuffers(1, &normalBuffer); glDeleteBuffers(1, &EBO); glDeleteVertexArrays(1, &VAO); } void TerrainMesh::bindVAO() const { glBindVertexArray(VAO); } void TerrainMesh::unbindVAO() { glBindVertexArray(0); } [[nodiscard]] unsigned int TerrainMesh::getNumOfVertices() const { return numOfVertices; } void TerrainMesh::loadTerrain(std::vector<glm::vec3> &vertices, std::vector<glm::vec3> &normals, std::vector<glm::vec2> &texCoords, std::vector<unsigned int> &indices, const char *const filename) { int width{}, nrchannels{}; unsigned char *const data = stbi_load(filename, &width, &height, &nrchannels, 1); dataContainer = std::make_unique<stb_PointerContainer>(data, width, height, nrchannels); for(int i = 0; i < height; ++i) { for(int j = 0; j < height; ++j) { const auto floatI = static_cast<float>(i); const auto floatJ = static_cast<float>(j); const auto heightAsFloat = static_cast<float>(height - 1); const float iOverHeight = floatI/heightAsFloat; const float jOverHeight = floatJ/heightAsFloat; vertices.emplace_back(jOverHeight * SIZE, getHeight(j, i), iOverHeight * SIZE); normals.push_back(calculateNormal(j, i)); texCoords.emplace_back(jOverHeight, iOverHeight); } } for(int gz = 0; gz < (height - 1); ++gz){ for(int gx = 0; gx < (height - 1); ++gx){ const int topLeft = gz * height + gx; const int topRight = topLeft + 1; const int bottomLeft = (gz + 1) * height + gx; const int bottomRight = bottomLeft + 1; indices.push_back(topLeft); indices.push_back(bottomLeft); indices.push_back(topRight); indices.push_back(topRight); indices.push_back(bottomLeft); indices.push_back(bottomRight); } } const auto comp = [](const glm::vec3 a, const glm::vec3 b) { return a.y < b.y; }; const auto minmax = std::minmax_element(std::begin(vertices), std::end(vertices), comp); minHeight = minmax.first->y; std::cout << "minHeight: " << minHeight << '\n'; maxHeight = minmax.second->y; std::cout << "maxHeight: " << maxHeight << '\n'; } [[nodiscard]] float TerrainMesh::getHeightFromNoise(double x, double z) const { assert(x <= height); assert(z <= height); constexpr float fRadius = 5.f; //modify this to scale noise const double fScaleX = x / (height-1); //0 <= x <= fPeriodSize const double fPeriodX = fScaleX * 2 * M_PI; //0 <= fPeriod <= 2PI x = fRadius * (std::sin(fPeriodX) + 1); //apply same to y const double fScaleZ = z / (height-1); const double fPeriodZ = fScaleZ * 2 * M_PI; z = fRadius * (std::cos(fPeriodZ) + 1); return std::clamp(minHeight, static_cast<float>(noise->Noise2(x/1000.0, z/1000.0) + noise->Noise2(x/100.0, z/100.0) + noise->Noise2(x, z)) * multiplier, maxHeight); } [[nodiscard]] float TerrainMesh::getHeightFromHeightmap(const int x, const int z) const { const int clampedX = std::clamp(x, 0, getWidth()); const int clampedZ = std::clamp(z, 0, getWidth()); const int index = clampedZ * height + clampedX; const float data = dataContainer->getData()[index]; const float ret = (data/128.f - 1.0f) * MAX_HEIGHT; //std::cout << "ret: " << ret << '\n'; return ret; } [[nodiscard]] glm::vec3 TerrainMesh::calculateNormal(const int x, const int z) const { const float heightL = getHeight(x - 1, z); const float heightR = getHeight(x + 1, z); const float heightU = getHeight(x, z + 1); const float heightD = getHeight(x, z - 1); const glm::vec3 normal(heightL - heightR, 2, heightD - heightU); return glm::normalize(normal); } [[nodiscard]] int TerrainMesh::getWidth() const { return height; } [[nodiscard]] float TerrainMesh::getHeight(const int x, const int z) const { return (!noise.has_value()) ? getHeightFromHeightmap(x, z) : getHeightFromNoise(x, z); } [[nodiscard]] float TerrainMesh::getMinHeight() const { return minHeight; } [[nodiscard]] float TerrainMesh::getMaxHeight() const { return maxHeight; } [[nodiscard]] glm::vec2 TerrainMesh::getX_Y_InWorldCoords(const float indexX, const float indexY) const noexcept { const float sizeOfTile = SIZE/height; return glm::vec2(indexX*sizeOfTile, indexY*sizeOfTile) + glm::vec2(0.5f*sizeOfTile); }
[ "sandlincoln@gmail.com" ]
sandlincoln@gmail.com
9a9d400e816b332b7b49865192f7dc95807dba04
c2a62b8cad77ee23bbb6e5cedb880287b5d7d431
/Sonic_Quilt/attiny_tests_NO/attiny_test1/attiny_test1.ino
6e501aede569340208461e52ae1032708ae22aba
[]
no_license
lizastark/Projects
8521d0c77271372324e745bf143b74bf444d4a76
ebd3588aa761e73654b96d5f7b5f645712d5c55a
refs/heads/master
2021-06-08T23:00:08.090153
2019-10-30T19:20:36
2019-10-30T19:20:36
115,811,160
0
0
null
null
null
null
UTF-8
C++
false
false
2,186
ino
/* * By WK * http://cyaninfinite.com/projects/playing-music-tracks-with-df-robot-mp3-player-module/ * * Checklist: * Why do these commands work when mine don't? * Need to integrate with sensors * try setting volume separately in setup and removing from function * */ #include "SoftwareSerial.h" //MP3 Settings SoftwareSerial mySerial(10, 9); # define Start_Byte 0x7E # define Version_Byte 0xFF # define Command_Length 0x06 # define End_Byte 0xEF # define Acknowledge 0x00 //Returns info with command 0x41 [0x01: info, 0x00: no info] void setup() { //MP3 mySerial.begin(9600); delay(1000); playFirst(); // putting this in the loop causes it to reset - something with the delay? } //uint8_t i = 0; //short int t = 30; void loop() { playNext(); /* //Get vol execute_CMD(0x43, 0, 0); delay(500); while (mySerial.available() > 0) { oled.print(mySerial.read()); oled.print(" "); } */ /* playNext(); t = 30; if (i < 2) { i++; } else { i = 0; } */ } void playFirst() { execute_CMD(0x3F, 0, 0); delay(500); setVolume(20); delay(500); execute_CMD(0x11, 0, 1); delay(500); mySerial.println("Track 1"); } /* void pause() { execute_CMD(0x0E, 0, 0); delay(500); } void play() { execute_CMD(0x0D, 0, 1); delay(500); } */ void playNext() { execute_CMD(0x01, 0, 1); //delay(500); mySerial.println("Track 2"); } /* void playPrevious() { execute_CMD(0x02, 0, 1); delay(500); } */ void setVolume(int volume) { execute_CMD(0x06, 0, volume); // Set the volume (0x00~0x30) delay(2000); } void execute_CMD(byte CMD, byte Par1, byte Par2) // Excecute the command and parameters { // Calculate the checksum (2 bytes) word checksum = -(Version_Byte + Command_Length + CMD + Acknowledge + Par1 + Par2); // Build the command line byte Command_line[10] = { Start_Byte, Version_Byte, Command_Length, CMD, Acknowledge, Par1, Par2, highByte(checksum), lowByte(checksum), End_Byte }; //Send the command line to the module for (byte k = 0; k < 10; k++) { mySerial.write( Command_line[k]); } }
[ "lizastark@gmail.com" ]
lizastark@gmail.com
7e57f0c58974ab5280c66afef38dda6ce66e5cf7
7a3771e499a27f809434ea80c6b9710a678d7a02
/UVa/10112MyacmTriangle.cpp
57a3e52992887b59c96c5906b86b38476680099c
[]
no_license
sunset1995/ACM_ICPC_prac
b00e9ccb36fe37fede78361267668233f0c201f2
22a7850dcc7a1d15e1fd6a6fe7e43251ca15db1b
refs/heads/master
2021-01-19T02:49:27.177125
2016-06-18T13:12:55
2016-06-18T13:12:55
45,678,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
#include <cstdio> #include <cmath> #include <cstdlib> using namespace std; struct point{ char name; int x,y; point operator-(const point &rth) const{ point np; np.x = x-rth.x , np.y = y-rth.y; return np; } } p[20]; double areaTriangle(point &p1,point &p2,point &p3){ point v1 = p2-p1 , v2 = p3-p1; return fabs( (double)v1.x*v2.y - v1.y*v2.x )/2; } bool inTriangle(point &p1,point &p2,point &p3,point &pp){ double Atri = areaTriangle( p1,p2,p3 ); double A1 = areaTriangle( p1,p2,pp ); double A2 = areaTriangle( p1,p3,pp ); double A3 = areaTriangle( p2,p3,pp ); return ( A1+A2+A3-Atri ) < 1e-9L; } int main(){ int n; while( scanf(" %d",&n)!=EOF && n ){ for(int i=0;i<n;++i) scanf(" %c%d%d",&p[i].name , &p[i].x , &p[i].y); double maxArea = 0L; int a=0,b=0,c=0; for(int i=n-1;i>1;--i) for(int j=i-1;j>0;--j) for(int k=j-1;k>=0;--k){ double nowArea = areaTriangle(p[i],p[j],p[k]); if( nowArea < maxArea ) continue; bool insideOk = true; for(int g=0;g<n && insideOk;++g){ if( g==i || g==j || g==k ) continue; if( inTriangle(p[i],p[j],p[k],p[g]) ) insideOk = false; } if( !insideOk ) continue; a = k , b = j , c = i; maxArea = nowArea; } printf("%c%c%c\n",p[a].name , p[b].name , p[c].name); } }
[ "s2821d3721@gmail.com" ]
s2821d3721@gmail.com
a371a0e8e0f6fd80d3b911996985ad5f862ace52
330ac72b5d10749ab2a22997084790aa27107faf
/Digicode/Alarme.h
d923b2e514376f376e860cc95d0649286d94a6f4
[]
no_license
maxime-minguella/TP4
295a442071bdc7def17e29df9e4972a080752ff6
769513a76ed44bdd7094d013f45d8fe1be983bc5
refs/heads/master
2020-05-18T00:22:26.447956
2019-04-29T14:33:31
2019-04-29T14:33:31
184,060,518
0
0
null
2019-04-29T11:43:50
2019-04-29T11:43:50
null
UTF-8
C++
false
false
210
h
#ifndef ALARME_H #define ALARME_H #include <iostream> #include <unistd.h> namespace nsDigicode { class Alarme { public: Alarme(); void declencher(); }; } #endif // ALARME_H
[ "m18002434@a-maq-iutinfo.salsa.univ-amu.fr" ]
m18002434@a-maq-iutinfo.salsa.univ-amu.fr
99a4b543f99866d06882d410b7ebb49a7c3f5e68
41119c1351cc85a3f04a4dd8779575d1b11da240
/io/DigitalInputPullUp/DigitalInputPullUp.ino
a78656bbab1d3b4cc6c6c2bf703b601a7489d967
[]
no_license
pincoin/arduino-example
b8906e8e6d64d8a9b1203aedbb2ee52e7495158c
fab906710e8483ba7442d5278b4a1a47867b9543
refs/heads/master
2021-01-10T06:16:43.285420
2015-12-19T18:07:29
2015-12-19T18:07:29
46,922,145
1
0
null
null
null
null
UTF-8
C++
false
false
608
ino
/* * DigitalInputPullUp: 내부 소프트웨어 풀업 저항 연결 버튼 예제 * * 버튼이 눌리면 LED를 켜고 떼면 LED를 끈다. * * 12번 핀에서 LED 및 220옴 저항 직렬 연결해서 GND로 연결 * 2번 핀에 스위치만 연결 * * 주의: 내부 풀업 저항 연결시 버튼이 눌리면 LOW 상태 */ const int ledPin = 12; const int buttonPin = 2; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); } void loop() { if (digitalRead(buttonPin) == LOW) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } }
[ "pincoin.info@gmail.com" ]
pincoin.info@gmail.com
bfba7a563fc83d38a31ae0d56a9153a64c74b739
08554887ec34bf36c13e77537299379a5a6ce22b
/Geiger-Counter-Arduino.ino
6ea6bca2825a34248b35c4ccba3a4d712d08e7cd
[]
no_license
akshayrajp/Geiger-Counter-Arduino
38a155a23148fb68ba9ca457ffb1bbd6fb593718
9f3138ef16ae174950b267ee7ad6f3e787f5a196
refs/heads/main
2023-03-02T18:19:03.953959
2021-02-13T14:47:48
2021-02-13T14:47:48
325,962,462
1
0
null
null
null
null
UTF-8
C++
false
false
1,392
ino
#include <Time.h> #include <TimeLib.h> // Connect the GND pin on Arduino to the GND pin on the Geiger counter. // Connect the 5V pin on Arduino to the 5V pin on the Geiger counter. // Connect the VIN pin on the Geiger counter to the D2 pin on Arduino. unsigned long counts; // variable for GM Tube events unsigned long previousMillis; // variable for measuring time #define LOG_PERIOD 1000 // count rate #define usv_multiplier 0.1 // For the J305β tube #define cpm_multiplier 2.3456 // For the J305β tube void impulse() { counts++; } void setup() { counts = 0; Serial.begin(9600); pinMode(2, INPUT); attachInterrupt(digitalPinToInterrupt(2), impulse, FALLING); // define external interrupts } void loop() { String usv, cpm; unsigned long currentMillis = millis(); if (currentMillis - previousMillis > LOG_PERIOD) { previousMillis = currentMillis; if(counts != 0) { // Log the time time_t t = now(); String time = String((minute(t) * 60) + (second(t))); // Print in μSv/hr usv = String(counts * usv_multiplier); Serial.println("usv " + time + " " + usv); // Print in CPM cpm = String(counts * cpm_multiplier); Serial.println("cpm " + time + " " + cpm); } counts = 0; } }
[ "akj.rajpurohit@gmail.com" ]
akj.rajpurohit@gmail.com
cef1038c9625b2c02e5406ab2121bef7efd920ad
61ec65afe654d16cb56a44dfb7a342228536cc98
/brewpi_avr/TempSensor.h
9ec4c855b6768288b84d0c6d90ed3df22c8c496a
[]
no_license
pjpeers/brewpi-avr
fbd3f3273c4020654171a1c24f30f3f0f8380bd3
d52dafdc7a3c948a2e38c6cfd7322bcb5766e3a9
refs/heads/master
2021-01-15T21:49:36.646424
2013-03-15T21:33:51
2013-03-15T21:33:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,096
h
/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi 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. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SENSORS_H_ #define SENSORS_H_ #include "FixedFilter.h" #include "OneWire.h" #include "DallasTemperature.h" #include "temperatureFormats.h" #include "pins.h" #include <stdlib.h> class TempSensor{ public: TempSensor(const uint8_t pinNumber) : pinNr(pinNumber){ lastRequestTime = 0; connected = 0; updateCounter = 255; // first update for slope filter after (255-13s) oneWire = new OneWire(pinNr); sensor = new DallasTemperature(oneWire); }; ~TempSensor(){ delete oneWire; delete sensor; }; void init(); bool isConnected(void); void update(void); fixed7_9 read(void); fixed7_9 readFastFiltered(void); fixed7_9 readSlowFiltered(void); fixed7_9 readSlope(void); fixed7_9 detectPosPeak(void); //returns positive peak or INT_MIN when no peak has been found fixed7_9 detectNegPeak(void); //returns negative peak or INT_MIN when no peak has been found void setFastFilterCoefficients(uint16_t ab); void setSlowFilterCoefficients(uint16_t ab); void setSlopeFilterCoefficients(uint16_t ab); private: const uint8_t pinNr; bool connected; unsigned long lastRequestTime; // in milliseconds unsigned char updateCounter; fixed7_25 prevOutputForSlope; FixedFilter fastFilter; FixedFilter slowFilter; FixedFilter slopeFilter; OneWire * oneWire; DallasTemperature * sensor; DeviceAddress sensorAddress; }; #endif /* SENSORS_H_ */
[ "github@brewpi.com" ]
github@brewpi.com
7f3e98ace3f4bb5eeb764fe175c14f740c2a2038
ef6fe7ecde14ccc5b98b33fbccc13832f3ec5692
/src/Thread.h
d79c0eb64c19b1a1db085479a8f613d3b8d6a078
[]
no_license
eprediger/cache-sim
d1e77922afa9d6b82a4d1ebe336b7bb4b25ba289
000fb9f6cbe6c2a78ab92b81ea7f3de7f300e39f
refs/heads/master
2020-03-28T14:18:37.684277
2018-09-25T05:01:42
2018-09-25T05:01:42
148,476,052
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
#ifndef __THREAD_H__ #define __THREAD_H__ #include <thread> class Thread { public: Thread(); virtual ~Thread(); Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; void start(); virtual void run() = 0; void join(); Thread(Thread&& other); Thread& operator=(Thread&& other); private: std::thread thread; }; #endif
[ "ej.prediger@gmail.com" ]
ej.prediger@gmail.com