hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
15bd26e9d1e4062d0ad1ff06efa037304e75a13a
1,177
cpp
C++
apps/tests/test_font.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
15
2017-10-18T05:08:16.000Z
2022-02-02T11:01:46.000Z
apps/tests/test_font.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
null
null
null
apps/tests/test_font.cpp
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
1
2018-11-10T03:12:57.000Z
2018-11-10T03:12:57.000Z
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #include <base/contract.h> #include <fstream> #include <script/font_manager.h> namespace { int safemain( int /*argc*/, char * /*argv*/[] ) { std::shared_ptr<script::font_manager> fontmgr = script::font_manager::make(); auto fams = fontmgr->get_families(); for ( auto f: fams ) std::cout << f << std::endl; auto font = fontmgr->get_font( "Times", "bold", 16, 95, 95, 1024, 1024 ); if ( font ) { for ( char32_t c = 'a'; c <= 'z'; ++c ) font->load_glyph( c ); std::ofstream out( "font.raw" ); auto bmp = font->bitmap(); out.write( reinterpret_cast<const char *>( bmp.data() ), static_cast<std::streamsize>( bmp.size() ) ); } else throw std::runtime_error( "could not load font" ); return 0; } } // namespace //////////////////////////////////////// int main( int argc, char *argv[] ) { try { return safemain( argc, argv ); } catch ( std::exception &e ) { base::print_exception( std::cerr, e ); } return -1; }
21.796296
77
0.525913
kdt3rd
15c54d976d9f22078105d13579c798e57bce3c31
6,137
cpp
C++
src/codec/rdb/RdbDecoder.cpp
TimothyZhang023/vcdb
2604ab3703d82efdbf6c66a713b5b23a61b96672
[ "BSD-2-Clause" ]
null
null
null
src/codec/rdb/RdbDecoder.cpp
TimothyZhang023/vcdb
2604ab3703d82efdbf6c66a713b5b23a61b96672
[ "BSD-2-Clause" ]
null
null
null
src/codec/rdb/RdbDecoder.cpp
TimothyZhang023/vcdb
2604ab3703d82efdbf6c66a713b5b23a61b96672
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2017, Timothy. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "RdbDecoder.h" #include "util/bytes.h" #include "util/cfree.h" #include <netinet/in.h> #include <memory> extern "C" { #include "redis/lzf.h" #include "redis/endianconv.h" #include "redis/util.h" #include "redis/zmalloc.h" }; int RdbDecoder::rdbLoadLenByRef(int *isencoded, uint64_t *lenptr) { unsigned char buf[2]; int type; if (isencoded) *isencoded = 0; if (rioRead(buf, 1) == 0) return -1; type = (buf[0] & 0xC0) >> 6; if (type == RDB_ENCVAL) { /* Read a 6 bit encoding type. */ if (isencoded) *isencoded = 1; *lenptr = buf[0] & 0x3F; } else if (type == RDB_6BITLEN) { /* Read a 6 bit len. */ *lenptr = buf[0] & 0x3F; } else if (type == RDB_14BITLEN) { /* Read a 14 bit len. */ if (rioRead(buf + 1, 1) == 0) return -1; *lenptr = ((buf[0] & 0x3F) << 8) | buf[1]; } else if (buf[0] == RDB_32BITLEN) { /* Read a 32 bit len. */ uint32_t len; if (rioRead(&len, 4) == 0) return -1; *lenptr = ntohl(len); } else if (buf[0] == RDB_64BITLEN) { /* Read a 64 bit len. */ uint64_t len; if (rioRead(&len, 8) == 0) return -1; *lenptr = ntohu64(len); } else { rdbExitReportCorruptRDB( "Unknown length encoding %d in rdbLoadLen()", type); return -1; /* Never reached. */ } return 0; } size_t RdbDecoder::rioRead(void *buf, size_t len) { if (len > remain_size) { return 0; } memcpy((char *) buf, p, len); p = p + len; remain_size = remain_size - len; return len; } size_t RdbDecoder::rioReadString(const char **start, size_t len) { if (len > remain_size) { return 0; } *start = p; p = p + len; remain_size = remain_size - len; return len; } size_t RdbDecoder::rioReadString(std::string &res, size_t len) { if (len > remain_size) { return 0; } // res = std::string(p, len); res.assign(p, len); p = p + len; remain_size = remain_size - len; return len; } std::string RdbDecoder::rdbLoadIntegerObject(int enctype, int *ret) { unsigned char enc[4]; long long val; if (enctype == RDB_ENC_INT8) { if (rioRead(enc, 1) == 0) return NULL; val = (signed char) enc[0]; } else if (enctype == RDB_ENC_INT16) { uint16_t v; if (rioRead(enc, 2) == 0) return NULL; v = enc[0] | (enc[1] << 8); val = (int16_t) v; } else if (enctype == RDB_ENC_INT32) { uint32_t v; if (rioRead(enc, 4) == 0) return NULL; v = enc[0] | (enc[1] << 8) | (enc[2] << 16) | (enc[3] << 24); val = (int32_t) v; } else { val = 0; /* anti-warning */ rdbExitReportCorruptRDB("Unknown RDB integer encoding type %d", enctype); } return str((int64_t) val); } std::string RdbDecoder::rdbLoadLzfStringObject(int *ret) { uint64_t len, clen; char *t_val = NULL; if ((clen = rdbLoadLen(NULL)) == RDB_LENERR) return NULL; if ((len = rdbLoadLen(NULL)) == RDB_LENERR) return NULL; /* Allocate our target according to the uncompressed size. */ /* Load the compressed representation and uncompress it to target. */ const char* tmp_c; if (rioReadString(&tmp_c, clen) == 0) { *ret = -1; return ""; } std::unique_ptr<char, cfree_delete<char>> out((char *)malloc(len)); t_val = out.get(); if (lzf_decompress(tmp_c, clen, t_val, len) == 0) { *ret = -1; return ""; } std::string tmp(t_val, len); *ret = 0; return tmp; } std::string RdbDecoder::rdbGenericLoadStringObject(int *ret) { int isencoded; uint64_t len; len = rdbLoadLen(&isencoded); if (isencoded) { switch (len) { case RDB_ENC_INT8: case RDB_ENC_INT16: case RDB_ENC_INT32: return rdbLoadIntegerObject(len, ret); case RDB_ENC_LZF: return rdbLoadLzfStringObject(ret); default: rdbExitReportCorruptRDB("Unknown RDB string encoding type %d", len); } } if (len == RDB_LENERR) { *ret = -1; return ""; } std::string tmp; if (len && rioReadString(tmp, len) == 0) { *ret = -1; return ""; } else { *ret = 0; return tmp; } } bool RdbDecoder::verifyDumpPayload() { const char *footer; uint16_t rdbver; uint64_t crc; /* At least 2 bytes of RDB version and 8 of CRC64 should be present. */ if (remain_size < 10) return false; footer = p + (remain_size - 10); /* Verify RDB version */ rdbver = (footer[1] << 8) | footer[0]; if (rdbver > RDB_VERSION) return false; /* Verify CRC64 */ crc = crc64_fast(0, (const unsigned char *) p, remain_size - 8); memrev64ifbe(&crc); remain_size = remain_size - 10; return std::memcmp(&crc, footer + 2, 8) == 0; } int RdbDecoder::rdbLoadObjectType() { int type; if ((type = rdbLoadType()) == -1) return -1; if (!rdbIsObjectType(type)) return -1; return type; } uint64_t RdbDecoder::rdbLoadLen(int *isencoded) { uint64_t len; if (rdbLoadLenByRef(isencoded, &len) == -1) return RDB_LENERR; return len; } int RdbDecoder::rdbLoadType() { unsigned char type; if (rioRead(&type, 1) == 0) return -1; return type; } int RdbDecoder::rdbLoadBinaryDoubleValue(double *val) { if (rioRead(val,sizeof(*val)) == 0) return -1; memrev64ifbe(val); return 0; } int RdbDecoder::rdbLoadDoubleValue(double *val) { char buf[256]; unsigned char len; if (rioRead(&len,1) == 0) return -1; switch(len) { case 255: *val = R_NegInf; return 0; case 254: *val = R_PosInf; return 0; case 253: *val = R_Nan; return 0; default: if (rioRead(buf,len) == 0) return -1; buf[len] = '\0'; sscanf(buf, "%lg", val); return 0; } }
24.646586
89
0.561675
TimothyZhang023
15c65aa5c73eb13cf6190cdd1dde08de126e323f
12,423
cpp
C++
Start.cpp
kongying-tavern/yuanshendt-updater
68ab945a2f179b35857be125cdef14077b2329de
[ "WTFPL" ]
5
2021-08-08T15:09:51.000Z
2022-03-13T07:12:46.000Z
Start.cpp
kongying-tavern/yuanshendt-updater
68ab945a2f179b35857be125cdef14077b2329de
[ "WTFPL" ]
null
null
null
Start.cpp
kongying-tavern/yuanshendt-updater
68ab945a2f179b35857be125cdef14077b2329de
[ "WTFPL" ]
2
2021-09-25T01:03:44.000Z
2022-01-10T07:02:50.000Z
#include "Start.h" #include <QStringList> #include <QtWidgets/QMessageBox> #include <QCoreApplication> #include <QDebug> #include <QUrl> #include <QtConcurrent> #include <QFileInfo> #include <windows.h> #include "file.h" #include "MD5.h" #include "Sandefine.h" #include "Json.h" #include "mainwindow.h" Start *tp; Start::Start(QString dir, QObject *parent) : QObject(parent) { tp=this; qDebug()<<"Start被创建"; tp->stlog(moduleStart,"Start被创建",NULL); http = new HTTP("","",NULL);//单线程下载 connect(this, &Start::tstart, this, &Start::work); connect(http, &HTTP::tworkMessageBox, this, &Start::tworkMessageBox); workProcess = new QThread; moveToThread(workProcess); workProcess->start(); this->dir = dir; } Start::~Start() { tp->stlog(moduleStart,"Start被销毁",NULL); qDebug()<<"Start被销毁"; } void Start::dlworking(LONG64 dlnow,LONG64 dltotal,void *tid,QString path) { for(int i=0;i<maxDlThreah;++i) { //清理已完成的任务 //if(netspeed[i].dl==netspeed[i].total && netspeed[i].total>0) if( netspeed[i].isdling==true && (netspeed[i].dl==netspeed[i].total && netspeed[i].total>0)) { qDebug()<<&netspeed[i].tid<<"end dl"<<netspeed[i].path; netspeed[i].isdling=false; netspeed[i].tid=NULL; //netspeed[i].dl=0; //netspeed[i].hisDl=0; //netspeed[i].total=0; //netspeed[i].path=""; MainWindow::mutualUi->updataDlingmag();//更新进度文本 } } for(int i=0;i<3;++i) { if(netspeed[i].tid==NULL && path!="") { //新下载线程开始 qDebug()<<&tid<<"new dl"<<path; netspeed[i].isdling=true; netspeed[i].tid=tid; netspeed[i].dl=0; netspeed[i].dlt=QDateTime::currentDateTime().toMSecsSinceEpoch(); netspeed[i].hisDl=0; netspeed[i].hisDlt=QDateTime::currentDateTime().toMSecsSinceEpoch(); netspeed[i].total=0; netspeed[i].path=path; break; } if(netspeed[i].tid==tid) { //正在下载的线程 netspeed[i].dl=dlnow; netspeed[i].dlt=QDateTime::currentDateTime().toMSecsSinceEpoch(); netspeed[i].total=dltotal; break; } } } void Start::stlog(int module,QString str,int mod=NULL) { if(tp) emit tp->log(module,str,mod); } void Start::dldone() { emit tworkProcess(doneFile++,totalFile); tp->stlog(moduleStart,"下载完成 "+ QString::number(doneFile)+"/"+ QString::number(totalFile) ,NULL); } QString tNowWork() { //return ""; qint64 DETLAms; int p; LONG64 s; QString tem=""; QString tems="0.00B/s"; for(int i=0;i<3;++i) { if(netspeed[i].path!="") { //计算已下载的百分比 DETLAms=netspeed[i].dlt-netspeed[i].hisDlt; p = (int)(100*((double)netspeed[i].dl/(double)netspeed[i].total)); if(p<0)p=0; //下载速度格式化 //s = (netspeed[i].dl-netspeed[i].hisDl)*2; s=(int)((double)(netspeed[i].dl-netspeed[i].hisDl)*((double)1000/(double)DETLAms)); if(s>0)tems=conver(s); //下载信息构造 tem+=QString::number(p)+"%\t | " +QString(tems)+"\t | " +netspeed[i].path ; //下载字节数缓存 netspeed[i].hisDl=netspeed[i].dl; netspeed[i].hisDlt=netspeed[i].dlt; p=0; tems="0.00B/s"; if(i<2)tem+="\n"; } } return tem; } void Start::updaterErr() { tp->stlog(moduleStart,"自动更新失败",NULL); emit tworkProcess(0,1); MainWindow::mutualUi->changePBText("自动更新失败,请单击重试"); emit tworkFinished(false); MainWindow::mutualUi->changeMainPage(1,false); emit tworkMessageBox(1, "自动更新失败", uperr_new); } void Start::stopWork() { tp->stlog(moduleStart,"任务线程被要求终止",NULL); if(tpoolhttp->activeThreadCount()>0) { tp->stlog(moduleStart,"停止下载线程池",NULL); qDebug()<<"停止线程池"; tpoolhttp->thread()->terminate(); this->thread()->terminate(); } } void Start::work() { QString path=this->dir; //Start::updaterErr(); //return; MainWindow::mutualUi->changeMainPage(0); qDebug()<<"工作目标:"<<path; tp->stlog(moduleStart,"工作目标:"+path,NULL); //return; //return; /*前期工作********************************************************/ /*互斥原神本体路径*/ QFileInfo yuanshen(path+"/YuanShen.exe"); if(yuanshen.exists()) { qDebug()<<"目标目录找到原神本体"; tp->stlog(moduleStart,"目标目录找到原神本体",NULL); MainWindow::mutualUi->changeProgressBarColor( QString("rgb(255, 0, 0)") ,QString("rgb(255, 0, 0)")); MainWindow::mutualUi->changeMainPage0label_Text("?"); emit tworkMessageBox( 1, "我受过专业的训练", "但是请你不要把地图装在原神目录" ); MainWindow::mutualUi->changeMainPage(1,false); emit tworkFinished(false); tp->stlog(moduleStart,"线程主动退出",NULL); return; } /*获取系统环境变量temp*********************************************/ MainWindow::mutualUi->changeMainPage0label_Text("初始化..."); tp->stlog(moduleStart,"初始化...",NULL); emit tworkProcess(1,2); MainWindow::mutualUi->changeProgressBarColor( QString("rgb(235, 235, 235)") ,QString("rgb(58, 59, 64)")); QString tempPath; tempPath=getTempPath("temp"); qDebug()<<"临时目录:"<<tempPath; tp->stlog(moduleStart,"临时目录:"+tempPath,NULL); /*在%temp%创建临时目录*/ tempPath=tempPath+updaterTempDir; qDebug()<<"临时文件夹:"<<tempPath; tp->stlog(moduleStart,"创建临时文件夹"+tempPath,NULL); createFolderSlot(tempPath); /*在临时目录释放crt证书*/ tp->stlog(moduleStart,"释放crt证书",NULL); httpcrt(); /*获取在线md5******************************************************/ /* 获取在线文件md5 * url download.yuanshen.site/md5.json * url dlurl"md5.json" * path "md5.json" */ tp->stlog(moduleStart,"\r\n获取在线文件MD5json",NULL); MainWindow::mutualUi->changeMainPage0label_Text("获取在线文件MD5..."); http->httpDownLoad(dlurl"md5.json","md5.json"); /*读取在线文件md5.json到 * QJson newmd5.json * 字符串 QString newMD5Str * 文件数 QSL newFileList * 文件MD5 QSL newFileMD5 */ //_sleep(1000); QString newMD5Str; QStringList newFileList; QStringList newFileMD5; //qDebug()<<tempPath<<"download/md5.json"; tp->stlog(moduleStart,"读入MD5文件",NULL); newMD5Str = readTXT(tempPath+"download/md5.json"); qDebug()<<"开始转换成QSL"; tp->stlog(moduleStart,"格式化MD5List",NULL); JSON *json=new JSON(); json->tp=tp; json->jsonStr2QSL(newMD5Str,newFileList,newFileMD5); // return; /*按需读取本地文件MD5**************************************************/ emit tworkProcess(0,1);//进度条归零 QStringList needUpdate; QStringList needUpdateMD5; qDebug()<<"按需读取本地文件MD5:"<<path; emit log(moduleStart,"按需读取本地文件MD5",NULL); QString omd5; for(int i = 0; i< newFileList.size();++i) { //qDebug()<<newFileMD5.at(i)<<this->dir+"/"+newFileList.at(i); omd5 = getFlieMD5(this->dir+"/"+newFileList.at(i)); //emit log(moduleMD5,"本地文件MD5:"+omd5+"|"+newFileList.at(i),NULL); emit log(moduleMD5,"本地文件:\t"+newFileList.at(i),NULL); emit log(moduleMD5,"本地MD5:\t"+omd5,NULL); emit tworkProcess(i,newFileList.size()); MainWindow::mutualUi->changeMainPage0label_Text("正在扫描本地文件MD5:"+newFileList.at(i)); if(newFileMD5.at(i) == omd5) { emit log(moduleMD5,"云端MD5\t"+newFileMD5.at(i),NULL); }else{ qDebug()<<"MD5不匹配:"<<dir+"/"+newFileList.at(i); emit log(moduleMD5,"云端MD5\t"+newFileMD5.at(i)+"\t需要更新",NULL); needUpdate<<newFileList.at(i); needUpdateMD5<<newFileMD5.at(i); } emit log(moduleMD5,"\r\n",NULL); } //return; /*下载需要更新的文件**********************************************/ /* 下载文件 * 需要更新的文件在 QStringList needUpdater * 下载文件前需要对字符串做很多工作 * 一是反斜杠转斜杠并删除第一个斜杠 */ emit log(moduleStart,"根据本地文件MD5下载需要更新的文件",NULL); QString tem; MainWindow::mutualUi->changeProgressBarColor( QString("#3880cc") ,QString("#00c500")); int retry=0;//多线程下载如何重试QAQ totalFile=needUpdate.size(); doneFile=0; //初始libcurl线程池 emit log(moduleStart,"初始libcurl线程池",NULL); emit log(moduleStart,"设置同时下载任务数为"+QString::number(maxDlThreah),NULL); tpoolhttp=QThreadPool::globalInstance(); tpoolhttp->setMaxThreadCount(maxDlThreah); //tpoolhttp->setMaxThreadCount(needUpdate.size());//A8:我tm谢谢你 tpoolhttp->setExpiryTimeout(-1); for(int i = 0; i< needUpdate.size();++i) { if(needUpdateMD5.at(i)!=getFlieMD5(tempPath+"download/Map/"+needUpdate.at(i))) { qDebug()<<"全新下载"; emit log(moduleStart,"新建下载任务\t"+needUpdate.at(i),NULL); //构造下载链接 QString url=dlurlMap+QUrl::toPercentEncoding(needUpdate.at(i)); QString dlpath="Map/"+QString(needUpdate.at(i)); thttp = new HTTP(url,dlpath,this); connect(thttp,&HTTP::dldone ,this,&Start::dldone ,Qt::DirectConnection ); connect(thttp, &HTTP::tworkMessageBox , this, &Start::tworkMessageBox ,Qt::DirectConnection ); tpoolhttp->start(thttp); }else{ qDebug()<<needUpdate.at(i)<<"已下载"; tp->stlog(moduleStart,"文件已被下载\t"+needUpdate.at(i),NULL); Start::dldone(); } } //tpoolhttp->activeThreadCount(); tpoolhttp->dumpObjectTree(); tpoolhttp->waitForDone(-1); tpoolhttp->clear(); qDebug()<<"下载完成"; tp->stlog(moduleStart,"下载完成",NULL); //MainWindow::mutualUi->changeMainPage0label_Text("下载完成"); //qDebug()<<FindWindowW(NULL,(LPCWSTR)QString("「空荧酒馆」原神地图").unicode());//地图进程窗口 //return; /*移动文件至目标目录*********************************************/ /* * 移动文件 * 下载好的地图存在%temp%\download\Map\ * 移动的目标文件夹为path */ //MainWindow::mutualUi->changeMainPage0label_Text("正在移动文件"); tp->stlog(moduleStart,"正在移动文件",NULL); MainWindow::mutualUi->changeProgressBarColor( QString("#00c500") ,QString("#078bff")); int f=0; for(int i = 0; i< needUpdate.size();++i) { //构造新旧文件名 QString oldPath=getTempPath("temp")+ updaterTempDir+ "download/"+"Map/"+ QString(needUpdate.at(i)) ; QString newPath=path+ "/"+ QString(needUpdate.at(i)) ; qDebug()<<QString::number(i+1)+ "|"+ QString::number(needUpdate.size()) ; MainWindow::mutualUi->changeMainPage0label_Text( QString::number(i+1)+ "|"+ QString::number(needUpdate.size())+ " 正在移动文件:"+ needUpdate.at(i) ); QFileInfo info(newPath); createFolderSlot(info.path()); if(moveFile(oldPath,newPath)) { qDebug()<<"√(^-^)"; f=0; }else{ qDebug()<<"移动失败第"<<f<<"次"; f++; i--; if(f>1) { Start::updaterErr(); return; } } emit tworkProcess(i,needUpdate.size()); } emit tworkProcess(1,1); MainWindow::mutualUi->changeMainPage0label_Text("不存在的看不到这句话的"); MainWindow::mutualUi->changeMainPage(1,true); emit tworkFinished(true); tp->stlog(moduleStart,"更新流程结束",NULL); }
31.292191
101
0.519681
kongying-tavern
15cb6a77994877a44b18c097680e944e35a78627
659
cpp
C++
other/TopTec2021/S1/N.cpp
axelgio01/cp
7a1c3490f913e4aea53e46bcfb5bb56c9b15605d
[ "MIT" ]
null
null
null
other/TopTec2021/S1/N.cpp
axelgio01/cp
7a1c3490f913e4aea53e46bcfb5bb56c9b15605d
[ "MIT" ]
null
null
null
other/TopTec2021/S1/N.cpp
axelgio01/cp
7a1c3490f913e4aea53e46bcfb5bb56c9b15605d
[ "MIT" ]
null
null
null
// #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { long long n, all = 0; cin >> n; set<int> winners; vector< pair<long long, int> > a(n); for (int i = 0; i < n; ++i) { cin >> a[i].first; a[i].second = i + 1; all += a[i].first; } sort(a.rbegin(), a.rend()); for (int i = 0; i < n; ++i) { long long cur = a[i].first; all -= cur; winners.insert(a[i].second); if (cur > all) { break; } } cout << (int) winners.size() << '\n'; for (auto &ans : winners) { cout << ans << ' '; } cout << '\n'; } return 0; }
19.382353
39
0.496206
axelgio01
15cbab5c0ad05c8da83ca610ace158e8dd8666ac
10,307
cpp
C++
android/android_9/hardware/qcom/display/msm8960/liboverlay/overlayMdp.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
1
2017-09-22T01:41:30.000Z
2017-09-22T01:41:30.000Z
qcom/display/msm8960/liboverlay/overlayMdp.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
null
null
null
qcom/display/msm8960/liboverlay/overlayMdp.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
1
2018-02-24T19:09:04.000Z
2018-02-24T19:09:04.000Z
/* * Copyright (C) 2008 The Android Open Source Project * Copyright (c) 2010-2013, The Linux Foundation. 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 <mdp_version.h> #include "overlayUtils.h" #include "overlayMdp.h" #include "mdp_version.h" #define HSIC_SETTINGS_DEBUG 0 static inline bool isEqual(float f1, float f2) { return ((int)(f1*100) == (int)(f2*100)) ? true : false; } namespace ovutils = overlay::utils; namespace overlay { //Helper to even out x,w and y,h pairs //x,y are always evened to ceil and w,h are evened to floor static void normalizeCrop(uint32_t& xy, uint32_t& wh) { if(xy & 1) { utils::even_ceil(xy); if(wh & 1) utils::even_floor(wh); else wh -= 2; } else { utils::even_floor(wh); } } bool MdpCtrl::init(uint32_t fbnum) { // FD init if(!utils::openDev(mFd, fbnum, Res::fbPath, O_RDWR)){ ALOGE("Ctrl failed to init fbnum=%d", fbnum); return false; } return true; } void MdpCtrl::reset() { utils::memset0(mOVInfo); utils::memset0(mLkgo); mOVInfo.id = MSMFB_NEW_REQUEST; mLkgo.id = MSMFB_NEW_REQUEST; mOrientation = utils::OVERLAY_TRANSFORM_0; mDownscale = 0; #ifdef USES_POST_PROCESSING mPPChanged = false; memset(&mParams, 0, sizeof(struct compute_params)); mParams.params.conv_params.order = hsic_order_hsc_i; mParams.params.conv_params.interface = interface_rec601; mParams.params.conv_params.cc_matrix[0][0] = 1; mParams.params.conv_params.cc_matrix[1][1] = 1; mParams.params.conv_params.cc_matrix[2][2] = 1; #endif } bool MdpCtrl::close() { bool result = true; if(MSMFB_NEW_REQUEST != static_cast<int>(mOVInfo.id)) { if(!mdp_wrapper::unsetOverlay(mFd.getFD(), mOVInfo.id)) { ALOGE("MdpCtrl close error in unset"); result = false; } } #ifdef USES_POST_PROCESSING /* free allocated memory in PP */ if (mOVInfo.overlay_pp_cfg.igc_cfg.c0_c1_data) free(mOVInfo.overlay_pp_cfg.igc_cfg.c0_c1_data); #endif reset(); if(!mFd.close()) { result = false; } return result; } void MdpCtrl::setSource(const utils::PipeArgs& args) { setSrcWhf(args.whf); //TODO These are hardcoded. Can be moved out of setSource. mOVInfo.transp_mask = 0xffffffff; //TODO These calls should ideally be a part of setPipeParams API setFlags(args.mdpFlags); setZ(args.zorder); setIsFg(args.isFg); setPlaneAlpha(args.planeAlpha); setBlending(args.blending); } void MdpCtrl::setCrop(const utils::Dim& d) { setSrcRectDim(d); } void MdpCtrl::setPosition(const overlay::utils::Dim& d) { setDstRectDim(d); } void MdpCtrl::setTransform(const utils::eTransform& orient) { int rot = utils::getMdpOrient(orient); setUserData(rot); //getMdpOrient will switch the flips if the source is 90 rotated. //Clients in Android dont factor in 90 rotation while deciding the flip. mOrientation = static_cast<utils::eTransform>(rot); } void MdpCtrl::doTransform() { setRotationFlags(); utils::Whf whf = getSrcWhf(); utils::Dim dim = getSrcRectDim(); utils::preRotateSource(mOrientation, whf, dim); setSrcWhf(whf); setSrcRectDim(dim); } void MdpCtrl::doDownscale() { mOVInfo.src_rect.x >>= mDownscale; mOVInfo.src_rect.y >>= mDownscale; mOVInfo.src_rect.w >>= mDownscale; mOVInfo.src_rect.h >>= mDownscale; } bool MdpCtrl::set() { //deferred calcs, so APIs could be called in any order. doTransform(); doDownscale(); utils::Whf whf = getSrcWhf(); if(utils::isYuv(whf.format)) { normalizeCrop(mOVInfo.src_rect.x, mOVInfo.src_rect.w); normalizeCrop(mOVInfo.src_rect.y, mOVInfo.src_rect.h); utils::even_floor(mOVInfo.dst_rect.w); utils::even_floor(mOVInfo.dst_rect.h); } if(this->ovChanged()) { if(!mdp_wrapper::setOverlay(mFd.getFD(), mOVInfo)) { ALOGE("MdpCtrl failed to setOverlay, restoring last known " "good ov info"); mdp_wrapper::dump("== Bad OVInfo is: ", mOVInfo); mdp_wrapper::dump("== Last good known OVInfo is: ", mLkgo); this->restore(); return false; } this->save(); } return true; } bool MdpCtrl::get() { mdp_overlay ov; ov.id = mOVInfo.id; if (!mdp_wrapper::getOverlay(mFd.getFD(), ov)) { ALOGE("MdpCtrl get failed"); return false; } mOVInfo = ov; return true; } //Update src format based on rotator's destination format. void MdpCtrl::updateSrcFormat(const uint32_t& rotDestFmt) { utils::Whf whf = getSrcWhf(); whf.format = rotDestFmt; setSrcWhf(whf); } void MdpCtrl::dump() const { ALOGE("== Dump MdpCtrl start =="); mFd.dump(); mdp_wrapper::dump("mOVInfo", mOVInfo); ALOGE("== Dump MdpCtrl end =="); } void MdpCtrl::getDump(char *buf, size_t len) { ovutils::getDump(buf, len, "Ctrl(mdp_overlay)", mOVInfo); } void MdpData::dump() const { ALOGE("== Dump MdpData start =="); mFd.dump(); mdp_wrapper::dump("mOvData", mOvData); ALOGE("== Dump MdpData end =="); } void MdpData::getDump(char *buf, size_t len) { ovutils::getDump(buf, len, "Data(msmfb_overlay_data)", mOvData); } void MdpCtrl3D::dump() const { ALOGE("== Dump MdpCtrl start =="); mFd.dump(); ALOGE("== Dump MdpCtrl end =="); } bool MdpCtrl::setVisualParams(const MetaData_t& data) { #ifdef USES_POST_PROCESSING bool needUpdate = false; /* calculate the data */ if (data.operation & PP_PARAM_HSIC) { if (mParams.params.pa_params.hue != data.hsicData.hue) { ALOGD_IF(HSIC_SETTINGS_DEBUG, "Hue has changed from %d to %d", mParams.params.pa_params.hue,data.hsicData.hue); needUpdate = true; } if (!isEqual(mParams.params.pa_params.sat, data.hsicData.saturation)) { ALOGD_IF(HSIC_SETTINGS_DEBUG, "Saturation has changed from %f to %f", mParams.params.pa_params.sat, data.hsicData.saturation); needUpdate = true; } if (mParams.params.pa_params.intensity != data.hsicData.intensity) { ALOGD_IF(HSIC_SETTINGS_DEBUG, "Intensity has changed from %d to %d", mParams.params.pa_params.intensity, data.hsicData.intensity); needUpdate = true; } if (!isEqual(mParams.params.pa_params.contrast, data.hsicData.contrast)) { ALOGD_IF(HSIC_SETTINGS_DEBUG, "Contrast has changed from %f to %f", mParams.params.pa_params.contrast, data.hsicData.contrast); needUpdate = true; } if (needUpdate) { mParams.params.pa_params.hue = data.hsicData.hue; mParams.params.pa_params.sat = data.hsicData.saturation; mParams.params.pa_params.intensity = data.hsicData.intensity; mParams.params.pa_params.contrast = data.hsicData.contrast; mParams.params.pa_params.ops = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; mParams.operation |= PP_OP_PA; } } if (data.operation & PP_PARAM_SHARP2) { if (mParams.params.sharp_params.strength != data.Sharp2Data.strength) { needUpdate = true; } if (mParams.params.sharp_params.edge_thr != data.Sharp2Data.edge_thr) { needUpdate = true; } if (mParams.params.sharp_params.smooth_thr != data.Sharp2Data.smooth_thr) { needUpdate = true; } if (mParams.params.sharp_params.noise_thr != data.Sharp2Data.noise_thr) { needUpdate = true; } if (needUpdate) { mParams.params.sharp_params.strength = data.Sharp2Data.strength; mParams.params.sharp_params.edge_thr = data.Sharp2Data.edge_thr; mParams.params.sharp_params.smooth_thr = data.Sharp2Data.smooth_thr; mParams.params.sharp_params.noise_thr = data.Sharp2Data.noise_thr; mParams.params.sharp_params.ops = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; mParams.operation |= PP_OP_SHARP; } } if (data.operation & PP_PARAM_IGC) { if (mOVInfo.overlay_pp_cfg.igc_cfg.c0_c1_data == NULL){ uint32_t *igcData = (uint32_t *)malloc(2 * MAX_IGC_LUT_ENTRIES * sizeof(uint32_t)); if (!igcData) { ALOGE("IGC storage allocated failed"); return false; } mOVInfo.overlay_pp_cfg.igc_cfg.c0_c1_data = igcData; mOVInfo.overlay_pp_cfg.igc_cfg.c2_data = igcData + MAX_IGC_LUT_ENTRIES; } memcpy(mParams.params.igc_lut_params.c0, data.igcData.c0, sizeof(uint16_t) * MAX_IGC_LUT_ENTRIES); memcpy(mParams.params.igc_lut_params.c1, data.igcData.c1, sizeof(uint16_t) * MAX_IGC_LUT_ENTRIES); memcpy(mParams.params.igc_lut_params.c2, data.igcData.c2, sizeof(uint16_t) * MAX_IGC_LUT_ENTRIES); mParams.params.igc_lut_params.ops = MDP_PP_OPS_WRITE | MDP_PP_OPS_ENABLE; mParams.operation |= PP_OP_IGC; needUpdate = true; } if (data.operation & PP_PARAM_VID_INTFC) { mParams.params.conv_params.interface = (interface_type) data.video_interface; needUpdate = true; } if (needUpdate) { display_pp_compute_params(&mParams, &mOVInfo.overlay_pp_cfg); mPPChanged = true; } #endif return true; } } // overlay
31.045181
81
0.626953
yakuizhao
15ce56fd139435072285e28c57ca2ff95ab2a751
927
hpp
C++
flare/include/flare/paint/actor_gradient_fill.hpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
14
2019-04-29T15:17:24.000Z
2020-12-30T12:51:05.000Z
flare/include/flare/paint/actor_gradient_fill.hpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
null
null
null
flare/include/flare/paint/actor_gradient_fill.hpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
6
2019-04-29T15:17:25.000Z
2021-11-16T03:20:59.000Z
#ifndef _FLARE_ACTOR_GRADIENT_FILL_HPP_ #define _FLARE_ACTOR_GRADIENT_FILL_HPP_ #include "flare/paint/actor_fill.hpp" #include "flare/paint/actor_gradient_color.hpp" namespace flare { class BlockReader; class ActorArtboard; class ActorGradientFill : public ActorGradientColor, public ActorFill { typedef ActorGradientColor Base; public: ActorGradientFill(); void copy(const ActorGradientFill* gradientColor, ActorArtboard* artboard); static ActorGradientFill* read(ActorArtboard* artboard, BlockReader* reader, ActorGradientFill* component); void onShapeChanged(ActorShape* from, ActorShape* to) override; ActorComponent* makeInstance(ActorArtboard* artboard) const override; void initializeGraphics() override; void validatePaint() override { ActorGradientColor::validatePaint(); } void markPaintDirty() override { ActorGradientColor::markPaintDirty(); } }; } // namespace flare #endif
33.107143
109
0.79288
taehyub
15cf54349548aa7d69f0ab2680f1f21e2abb2bdd
6,994
cc
C++
RAVL2/PatternRec/Modeling/GaussianMixture/GaussianMixture.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/PatternRec/Modeling/GaussianMixture/GaussianMixture.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/PatternRec/Modeling/GaussianMixture/GaussianMixture.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //! rcsid="$Id: GaussianMixture.cc 4140 2004-03-23 15:31:15Z craftit $" //! lib=RavlPatternRec //! author="Charles Galambos" //! file="Ravl/PatternRec/Modeling/GaussianMixture/GaussianMixture.cc" #include "Ravl/PatternRec/GaussianMixture.hh" #include "Ravl/BinStream.hh" #include "Ravl/SArray1dIter.hh" #include "Ravl/SArray1dIter3.hh" #include "Ravl/SArray1dIter4.hh" #include "Ravl/SArray1dIter5.hh" #include "Ravl/VirtualConstructor.hh" #include "Ravl/config.h" #if RAVL_COMPILER_MIPSPRO #include "Ravl/VirtualConstructor.hh" #include "Ravl/BinStream.hh" #pragma instantiate RavlN::GaussianMixtureBodyC* RavlN::VCLoad(RavlN::BinIStreamC&,RavlN::GaussianMixtureBodyC*) #endif namespace RavlN { //: Constructor from an array of indexes. GaussianMixtureBodyC::GaussianMixtureBodyC(const SArray1dC<MeanCovarianceC> & prms, const SArray1dC<RealT> & wgt, bool diag) : params(prms), weights(wgt), isDiagonal(diag) { //: Lets do some checks if(params.Size()!=weights.Size()) RavlIssueError("Gaussian Mixture parameters not of same dimensionality as mixing weights"); UIntT outputSize = params.Size(); UIntT inputSize = params[0].Mean().Size(); if(outputSize<1) RavlIssueError("Gaussian Mixture model has output dimension of < 1"); if(inputSize<1) RavlIssueError("Gaussian Mixture model has input dimension < 1"); OutputSize(outputSize); InputSize(inputSize); //: Lets precompute stuff precompute(); } GaussianMixtureBodyC::GaussianMixtureBodyC(const SArray1dC<VectorC> & means, const SArray1dC<MatrixRSC> & covariances, const SArray1dC<RealT> & wgt, bool diag) : params(means.Size()), weights(wgt), isDiagonal(diag) { //: Lets do some checks if((means.Size()!=covariances.Size()) || (means.Size()!=weights.Size())) RavlIssueError("Gaussian Mixture parameters not of same dimension"); // now lets build our model for(SArray1dIter3C<MeanCovarianceC, VectorC, MatrixRSC>it(params, means, covariances);it;it++) it.Data1() = MeanCovarianceC(1, it.Data2(), it.Data3()); UIntT outputSize = params.Size(); UIntT inputSize = params[0].Mean().Size(); if(outputSize<1) RavlIssueError("Gaussian Mixture model has output dimension of < 1"); if(inputSize<1) RavlIssueError("Gaussian Mixture model has input dimension < 1"); OutputSize(outputSize); InputSize(inputSize); //: Lets precompute stuff precompute(); } //: Load from stream. GaussianMixtureBodyC::GaussianMixtureBodyC(istream &strm) : Function1BodyC(strm) { strm >> params >> weights >> isDiagonal; precompute(false); //: should of already regularised before writing to file, no need to do it again } //: Writes object to stream. bool GaussianMixtureBodyC::Save (ostream &out) const { if(!FunctionBodyC::Save(out)) return false; out << '\n' << params << '\n' << weights << '\n' << isDiagonal; return true; } //: Load from binary stream. GaussianMixtureBodyC::GaussianMixtureBodyC(BinIStreamC &strm) : Function1BodyC(strm) { strm >> params >> weights >> isDiagonal; precompute(false); //: should of already regularised before writing to file } //: Writes object to binary stream. bool GaussianMixtureBodyC::Save (BinOStreamC &out) const { if(!FunctionBodyC::Save(out)) return false; out << params << weights << isDiagonal; return true; } //: Get vector of individual values. VectorC GaussianMixtureBodyC::GaussianValues(const VectorC &data) const { //: do some checks if(data.Size()!=InputSize()) RavlIssueError("Input data of different dimension to that of model"); VectorC out(OutputSize()); for(SArray1dIter4C<MeanCovarianceC, RealT, MatrixRSC, RealT>it(params, weights, invCov, det);it;it++) { VectorC D = data - it.Data1().Mean(); out[it.Index()] = it.Data2() * ((1.0/(konst * Sqrt(it.Data4()))) * Exp(-0.5 * D.Dot(( it.Data3() * D)))); } return out; } //: Return the denisty value at point X RealT GaussianMixtureBodyC::DensityValue(const VectorC & data) const { RealT ret = 0; for(SArray1dIter4C<MeanCovarianceC, RealT, MatrixRSC, RealT> it(params, weights, invCov, det);it;it++) { VectorC D = data - it.Data1().Mean(); ret += it.Data2() * ((1.0/(konst * Sqrt(it.Data4()))) * Exp(-0.5 * D.Dot(( it.Data3() * D)))); } return ret; } //: Compute the density at a given point VectorC GaussianMixtureBodyC::Apply(const VectorC & data) const { VectorC ret(1); ret[0] = DensityValue(data); return ret; } //: Apply function to 'data' RealT GaussianMixtureBodyC::Apply1(const VectorC &data) const { return DensityValue(data); } //: Precompute the inverse matrices e.t.c.. void GaussianMixtureBodyC::precompute(bool regularise) { //: For speed, lets precompute some stuff konst = Pow(2.0* RavlConstN::pi, (RealT)InputSize()/2.0); //: First we have to check for very small variances //: The smallest variance we allow RealT smallVariance = 0.001; RealT smallDeterminant = 1e-150; //: lets regularise our model //: this has effect of increasing the distance slighty in all orthogonal directions //: not great, bit of a hack if(regularise) { for(SArray1dIterC<MeanCovarianceC> paramIt(params);paramIt;paramIt++) { for (UIntT i=0; i<inputSize; i++) paramIt.Data().Covariance()[i][i] += smallVariance; } } //: make room for the arrays invCov = SArray1dC<MatrixRSC>(OutputSize()); det = SArray1dC<RealT>(OutputSize()); //: compute inverse and determinant of models for(SArray1dIterC<MeanCovarianceC>paramIt(params);paramIt;paramIt++) { IndexC i = paramIt.Index(); if(!isDiagonal) { invCov[i] = paramIt.Data().Covariance().NearSingularInverse(det[i]); } else { det[i]=1.0; invCov [i] = MatrixRSC(inputSize); invCov[i].Fill(0.0); for(UIntT j=0;j<inputSize;j++) { invCov[i][j][j]=1.0/paramIt.Data().Covariance()[j][j]; det[i] *= paramIt.Data().Covariance()[j][j]; } } if(det[i]<smallDeterminant) { //: if this is called then we have a problem on one component //: having a very small variance. We do try and avoid this //: by setting a minimum allowed variance, but it is not foolproof. RavlIssueError("The deteminant is too small (or negative). Unsuitable data, perhaps use PCA."); } } } RAVL_INITVIRTUALCONSTRUCTOR_FULL(GaussianMixtureBodyC,GaussianMixtureC,Function1C); }
32.530233
161
0.667286
isuhao
15d132691ab76cd46b34a9f55d3b8503b32ac5f4
4,411
cc
C++
src/trace.cc
offis/libbla
4d6391df7ddd6a6ab0a61d9469b6f9fd49d060de
[ "Apache-2.0" ]
null
null
null
src/trace.cc
offis/libbla
4d6391df7ddd6a6ab0a61d9469b6f9fd49d060de
[ "Apache-2.0" ]
null
null
null
src/trace.cc
offis/libbla
4d6391df7ddd6a6ab0a61d9469b6f9fd49d060de
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018-2020 OFFIS Institute for Information Technology * Oldenburg, Germany * * 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. */ /* * trace.cc * * Created on: 21.06.2019 * Author: irune * Edited on: 08.07.2019 * Author: irune */ #include "../include/trace.h" #include <sstream> #include <iomanip> int traceSingleton::cnt; int traceSingleton::cntPet; int traceSingleton::cntPnet; int traceSingleton::counter; sysx::units::time_type traceSingleton::startTimeL1; sysx::units::time_type traceSingleton::startTimeL2; #ifdef TRACEON std::vector<std::string> traceSingleton::hierarchy; std::vector<std::string> traces; //#define NELEMS(x) (sizeof(x) / sizeof((x)[0])) traceSingleton::traceSingleton() : myfile_(NULL) { // myfile_.open("traces.txt") myfile_.rdbuf(std::cout.rdbuf());; cnt = 0; cntPet = -1; cntPnet = 0; counter = 0; startTimeL1 = timer::getTime(); startTimeL2 = timer::getTime(); } traceSingleton& traceSingleton::getInstance() { static traceSingleton instance; return instance; } void traceSingleton::print(std::string id, time_type instant){ auto &mem = memory::getInstance(); double time_ns = static_cast<double>(instant / ::sysx::si::milliseconds); for (int i = 0; i < (hierarchy.size() - 1); i++) { mem.bodies[counter].identity = mem.bodies[counter].identity + hierarchy.at(i) + "."; } mem.bodies[counter].identity = mem.bodies[counter].identity + " " + id + " " ; mem.bodies[counter].times = time_ns; counter++; } void traceSingleton::output(){ auto &mem = memory::getInstance(); mem.output(); //mem.switchingTime(); } void traceSingleton::FET_entry_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "FET_" << id; hierarchy.push_back(oss.str()); oss << ".Entry " << causal_id_; print(oss.str(), instant); } void traceSingleton::FET_exit_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "FET_" << id << ".Exit " << causal_id_; print(oss.str(), instant); } void traceSingleton::BET_entry_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "BET_" << id; hierarchy.push_back(oss.str()); oss << ".Entry " << causal_id_; print(oss.str(), instant); } void traceSingleton::BET_pentry_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "BET_" << id << ".PEntry " << causal_id_; print(oss.str(), instant); } void traceSingleton::BET_exit_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "BET_" << id << ".Exit " << causal_id_; print(oss.str(), instant); } void traceSingleton::PET_entry_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "PET_" << id; hierarchy.push_back(oss.str()); oss << ".Entry " << causal_id_; print(oss.str(), instant); } void traceSingleton::PET_exit_trace(int id, int causal_id_, time_type instant) { std::ostringstream oss; oss << "PET_" << id << ".Exit " << causal_id_; print(oss.str(), instant); } #else traceSingleton::traceSingleton(){ } traceSingleton& traceSingleton::getInstance() { static traceSingleton instance; return instance; } void traceSingleton::output(){} void traceSingleton::FET_entry_trace(int id, int causal_id_, time_type instant) { } void traceSingleton::FET_exit_trace(int id, int causal_id_, time_type instant) { } void traceSingleton::BET_entry_trace(int id, int causal_id_, time_type instant) { } void traceSingleton::BET_pentry_trace(int id, int causal_id_, time_type instant){ } void traceSingleton::BET_exit_trace(int id, int causal_id_, time_type instant) { } void traceSingleton::PET_entry_trace(int id, int causal_id_, time_type instant) { } void traceSingleton::PET_exit_trace(int id, int causal_id_, time_type instant) { } #endif //TRACEON
27.917722
89
0.697574
offis
15d2b2c8a1eac7279da29bc6a0b3b0f415de9f6d
6,599
cpp
C++
src/row_renderer.cpp
magicmoremagic/bengine-ctable
ab82acd66f3021888701fb086dcec0e0713038c2
[ "MIT" ]
null
null
null
src/row_renderer.cpp
magicmoremagic/bengine-ctable
ab82acd66f3021888701fb086dcec0e0713038c2
[ "MIT" ]
null
null
null
src/row_renderer.cpp
magicmoremagic/bengine-ctable
ab82acd66f3021888701fb086dcec0e0713038c2
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "row_renderer.hpp" #include "table_sizer.hpp" #include <memory> namespace be::ct { namespace detail { namespace { /////////////////////////////////////////////////////////////////////////////// U8 get_margin(const BorderConfig& config) { return config.margin > 0 ? config.margin - 1 : 0; } /////////////////////////////////////////////////////////////////////////////// U8 get_margin(const Row& row, BoxConfig::side side) { return get_margin(row.config().box.sides[side]); } /////////////////////////////////////////////////////////////////////////////// U8 get_padding(const Row& row, BoxConfig::side side) { return row.config().box.sides[side].padding; } } // be::ct::detail::() /////////////////////////////////////////////////////////////////////////////// RowRenderer::RowRenderer(const Row& row) : seq(), padding(seq, get_padding(row, BoxConfig::top_side), get_padding(row, BoxConfig::right_side), get_padding(row, BoxConfig::bottom_side), get_padding(row, BoxConfig::left_side), row.config().box.foreground, row.config().box.background), border(padding), margin(border, get_margin(row, BoxConfig::top_side), get_margin(row, BoxConfig::right_side), get_margin(row, BoxConfig::bottom_side), get_margin(row, BoxConfig::left_side)), config_(row.config().box), align_(row.config().box.align) { border.foreground(row.config().box.foreground); border.background(row.config().box.background); try_add_border_(BoxConfig::top_side); try_add_border_(BoxConfig::right_side); try_add_border_(BoxConfig::bottom_side); try_add_border_(BoxConfig::left_side); cells_.reserve(row.size()); for (const Cell& cell : row) { cells_.push_back(std::make_unique<CellRenderer>(cell)); seq.add(cells_.back().get()); } } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::auto_size(I32 max_total_width) { TableSizer sizer(1); sizer.add(*this); sizer.set_sizes(max_total_width); } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::combine_border_corners() { freeze(); for (auto& cell : cells_) { cell->combine_border_corners(); } if (config_.corners) { if (!border.left().empty()) { if (!border.top().empty()) { auto& bc = border.top().front(); bc = config_.corners(bc, border.left().front(), BoxConfig::top_side, BoxConfig::left_side); } if (!border.bottom().empty()) { auto& bc = border.bottom().front(); bc = config_.corners(bc, border.left().back(), BoxConfig::bottom_side, BoxConfig::left_side); } } if (!border.right().empty()) { if (!border.top().empty()) { auto& bc = border.top().back(); bc = config_.corners(bc, border.right().front(), BoxConfig::top_side, BoxConfig::right_side); } if (!border.bottom().empty()) { auto& bc = border.bottom().back(); bc = config_.corners(bc, border.right().back(), BoxConfig::bottom_side, BoxConfig::right_side); } } } } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::align(U8 align) { align_ = align; } /////////////////////////////////////////////////////////////////////////////// U8 RowRenderer::align() const { return align_; } /////////////////////////////////////////////////////////////////////////////// I32 RowRenderer::width_() const { return margin.width(); } /////////////////////////////////////////////////////////////////////////////// I32 RowRenderer::height_() const { return margin.height(); } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::freeze_() { bool first_freeze = cached_width_ == -1; if (first_freeze) { constexpr const U8 halign_mask = BoxConfig::align_left | BoxConfig::align_center | BoxConfig::align_right; constexpr const U8 valign_mask = BoxConfig::align_top | BoxConfig::align_middle | BoxConfig::align_bottom; for (auto& cell : cells_) { if ((cell->text.align() & halign_mask) == BoxConfig::inherit_alignment) { cell->text.align(cell->text.align() | (align_ & halign_mask)); } if ((cell->text.align() & valign_mask) == BoxConfig::inherit_alignment) { cell->text.align(cell->text.align() | (align_ & valign_mask)); } } } margin.freeze(); base::freeze_(); if (first_freeze) { generate_border_(BoxConfig::top_side); generate_border_(BoxConfig::right_side); generate_border_(BoxConfig::bottom_side); generate_border_(BoxConfig::left_side); } } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::render_(std::ostream& os) { margin(os); } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::try_add_border_(BoxConfig::side side) { if (config_.sides[side].margin > 0) { border.enabled(side, true); border.top().emplace_back(); } } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::generate_border_(BoxConfig::side side) { auto& b = border.get(side); if (!b.empty() || border.enabled(side)) { auto pattern = config_.sides[side].pattern; std::size_t size = 2 + (side == BoxConfig::top_side || side == BoxConfig::bottom_side ? padding.width() : padding.height()); b = expand_border_pattern(pattern, size); resolve_border_colors_(side); } } /////////////////////////////////////////////////////////////////////////////// void RowRenderer::resolve_border_colors_(BoxConfig::side side) { LogColor fg = config_.sides[side].foreground; LogColor bg = border.background(); if (fg == LogColor::current) { fg = border.foreground(); } else if (fg == LogColor::other) { fg = bg; } for (auto& bc : border.get(side)) { if (bc.foreground == LogColor::current) { bc.foreground = fg; } else if (bc.foreground == LogColor::other) { bc.foreground = bg; } if (bc.background == LogColor::current) { bc.background = bg; } else if (bc.background == LogColor::other) { bc.background = fg; } } } } // be::ct::detail } // be::ct
32.830846
112
0.504167
magicmoremagic
15d5ab60064d826ca43fd55ac8556a9b3cb52086
789
cpp
C++
uva/11000 - Bee adhoc recursive .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
uva/11000 - Bee adhoc recursive .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
uva/11000 - Bee adhoc recursive .cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <string.h> #include <math.h> #include <algorithm> #include <stack> #include <queue> using namespace std; long long ara[100]; long long bee_count(long long n) { if(n<=0) return 0; else if(n==1) return 1; else { if(ara[n] != -1) return ara[n]; else { ara[n]= bee_count(n-1)+bee_count(n-2); return ara[n]; } } } int main () { long long n,male=0,total=0,female=1; while(1) { scanf("%lld",&n); if(n== -1) break; memset(ara,-1,sizeof(ara)); male=bee_count(n+2)-1; total=bee_count(n+3)-1; printf("%lld %lld\n",male,total); } return 0; }
16.4375
51
0.47782
priojeetpriyom
15d74717934c1cdd6bd4f073ec485bf529f7e93d
6,872
cpp
C++
liblink/native/src/deterministic_wallet.cpp
oklink-dev/bitlink
69705ccd8469a11375ad3c08c00c9dc54773355e
[ "MIT" ]
null
null
null
liblink/native/src/deterministic_wallet.cpp
oklink-dev/bitlink
69705ccd8469a11375ad3c08c00c9dc54773355e
[ "MIT" ]
null
null
null
liblink/native/src/deterministic_wallet.cpp
oklink-dev/bitlink
69705ccd8469a11375ad3c08c00c9dc54773355e
[ "MIT" ]
null
null
null
/** * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "deterministic_wallet.hpp" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <openssl/ec.h> #include <openssl/obj_mac.h> #include <openssl/sha.h> #include "constants.hpp" #include "format.hpp" #include "utility/assert.hpp" #include "utility/sha256.hpp" template <typename ssl_type> struct ssl_wrapper { ssl_wrapper(ssl_type* obj) : obj(obj) {} virtual ~ssl_wrapper() { } operator ssl_type*() { return obj; } ssl_type* obj; }; struct ssl_bignum : public ssl_wrapper<BIGNUM> { ssl_bignum() : ssl_wrapper(BN_new()) {} ~ssl_bignum() { BN_free(obj); } }; #define SSL_TYPE(name, ssl_type, free_func) \ struct name \ : public ssl_wrapper<ssl_type> \ { \ name(ssl_type* obj) \ : ssl_wrapper(obj) {} \ ~name() \ { \ free_func(obj); \ } \ }; SSL_TYPE(ec_group, EC_GROUP, EC_GROUP_free) SSL_TYPE(ec_point, EC_POINT, EC_POINT_free) SSL_TYPE(bn_ctx, BN_CTX, BN_CTX_free) const std::string bignum_hex(BIGNUM* bn) { char* repr = BN_bn2hex(bn); std::string result = repr; OPENSSL_free(repr); boost::algorithm::to_lower(result); return result; } const data_chunk bignum_data(BIGNUM* bn) { data_chunk result(32); size_t copy_offset = result.size() - BN_num_bytes(bn); BN_bn2bin(bn, result.begin() + copy_offset); // Zero out beginning 0x00 bytes (if they exist). std::fill(result.begin(), result.begin() + copy_offset, 0x00); return result; } void deterministic_wallet::new_seed() { const size_t bits_needed = 8 * seed_size / 2; ssl_bignum rand_value; BN_rand(rand_value, bits_needed, 0, 0); bool set_success = set_seed(bignum_hex(rand_value)); BITCOIN_ASSERT(set_success); } secret_parameter stretch_seed(const std::string& seed) { BITCOIN_ASSERT(seed.size() == deterministic_wallet::seed_size); secret_parameter stretched; std::copy(seed.begin(), seed.end(), stretched.begin()); secret_parameter oldseed = stretched; for (size_t i = 0; i < 100000; ++i) { SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, stretched.data(), stretched.size()); SHA256_Update(&ctx, oldseed.data(), oldseed.size()); SHA256_Final(stretched.data(), &ctx); } return stretched; } data_chunk pubkey_from_secret(const secret_parameter& secret) { elliptic_curve_key privkey; if (!privkey.set_secret(secret)) return data_chunk(); return privkey.public_key(); } bool deterministic_wallet::set_seed(std::string seed) { // Trim spaces and newlines around the string. boost::algorithm::trim(seed); if (seed.size() != seed_size) return false; seed_ = seed; stretched_seed_ = stretch_seed(seed); master_public_key_ = pubkey_from_secret(stretched_seed_); // Snip the beginning 04 byte for compat reasons. master_public_key_.erase(master_public_key_.begin()); if (master_public_key_.empty()) return false; return true; } const std::string& deterministic_wallet::seed() const { return seed_; } bool deterministic_wallet::set_master_public_key(const data_chunk& mpk) { master_public_key_ = mpk; return true; } const data_chunk& deterministic_wallet::master_public_key() const { return master_public_key_; } data_chunk deterministic_wallet::generate_public_key( size_t n, bool for_change) const { hash_digest sequence = get_sequence(n, for_change); ssl_bignum x, y, z; BN_bin2bn(sequence.data(), sequence.size(), z); BN_bin2bn(master_public_key_.begin(), 32, x); BN_bin2bn(master_public_key_.begin() + 32, 32, y); // Create a point. ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1)); ec_point mpk(EC_POINT_new(group)); bn_ctx ctx(BN_CTX_new()); EC_POINT_set_affine_coordinates_GFp(group, mpk, x, y, ctx); ec_point result(EC_POINT_new(group)); // result pubkey_point = mpk_pubkey_point + z*curve.generator ssl_bignum one; BN_one(one); EC_POINT_mul(group, result, z, mpk, one, ctx); // Create the actual public key. EC_POINT_get_affine_coordinates_GFp(group, result, x, y, ctx); // 04 + x + y data_chunk raw_pubkey; raw_pubkey.push_back(0x04); extend_data(raw_pubkey, bignum_data(x)); extend_data(raw_pubkey, bignum_data(y)); return raw_pubkey; } secret_parameter deterministic_wallet::generate_secret( size_t n, bool for_change) const { if (seed_.empty()) return null_hash; ssl_bignum z; hash_digest sequence = get_sequence(n, for_change); BN_bin2bn(sequence.data(), sequence.size(), z); ec_group group(EC_GROUP_new_by_curve_name(NID_secp256k1)); ssl_bignum order; bn_ctx ctx(BN_CTX_new()); EC_GROUP_get_order(group, order, ctx); // secexp = (stretched_seed + z) % order ssl_bignum secexp; BN_bin2bn(stretched_seed_.data(), stretched_seed_.size(), secexp); BN_add(secexp, secexp, z); BN_mod(secexp, secexp, order, ctx); secret_parameter secret; int secexp_bytes_size = BN_num_bytes(secexp); BITCOIN_ASSERT(secexp_bytes_size >= 0 && static_cast<size_t>(BN_num_bytes(secexp)) <= secret.size()); // If bignum value begins with 0x00, then // SSL will skip to the first significant digit. size_t copy_offset = secret.size() - BN_num_bytes(secexp); BN_bn2bin(secexp, secret.data() + copy_offset); // Zero out beginning 0x00 bytes (if they exist). std::fill(secret.begin(), secret.begin() + copy_offset, 0x00); return secret; } hash_digest deterministic_wallet::get_sequence( size_t n, bool for_change) const { data_chunk chunk; extend_data(chunk, boost::lexical_cast<std::string>(n)); chunk.push_back(':'); chunk.push_back(for_change ? '1' : '0'); chunk.push_back(':'); extend_data(chunk, master_public_key_); hash_digest result = generate_sha256_hash(chunk); std::reverse(result.begin(), result.end()); return result; }
28.633333
75
0.688009
oklink-dev
15d8262e934770f5d917f21de8a33aa67d870cdd
789
cpp
C++
libyb/async/cancellation_token.cpp
avakar/libyb
09874b6ead7f09f6318c1730cdc4e2b7f231df5f
[ "BSL-1.0" ]
1
2016-08-22T07:45:41.000Z
2016-08-22T07:45:41.000Z
libyb/async/cancellation_token.cpp
avakar/libyb
09874b6ead7f09f6318c1730cdc4e2b7f231df5f
[ "BSL-1.0" ]
null
null
null
libyb/async/cancellation_token.cpp
avakar/libyb
09874b6ead7f09f6318c1730cdc4e2b7f231df5f
[ "BSL-1.0" ]
1
2016-11-01T11:43:10.000Z
2016-11-01T11:43:10.000Z
#include "cancellation_token.hpp" #include "detail/cancellation_token_task.hpp" using namespace yb; cancellation_token::cancellation_token() : m_core(0) { } cancellation_token::cancellation_token(detail::cancellation_token_core_base * core) : m_core(core) { assert(m_core); m_core->addref(); } cancellation_token::cancellation_token(cancellation_token const & o) : m_core(o.m_core) { if (m_core) m_core->addref(); } cancellation_token::~cancellation_token() { if (m_core) m_core->release(); } cancellation_token & cancellation_token::operator=(cancellation_token const & o) { if (o.m_core) o.m_core->addref(); if (m_core) m_core->release(); m_core = o.m_core; return *this; } void cancellation_token::cancel(cancel_level cl) { if (m_core) m_core->cancel(cl); }
17.533333
83
0.737643
avakar
15d940f8070c9d84379e28dad28af0b13fd94fb1
292
cpp
C++
Linked List/(Leetcode) 206 Reverse Linked List.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Linked List/(Leetcode) 206 Reverse Linked List.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Linked List/(Leetcode) 206 Reverse Linked List.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
class Solution { public: ListNode* reverseList(ListNode* head) { if(!head or !head->next) return head; ListNode* t = reverseList(head->next); ListNode* sn = head->next; sn->next = head; head->next=NULL; return t; } };
20.857143
46
0.517123
kothariji
15d9f9a3830d5e095f06541835660dc168304512
1,302
cpp
C++
test/main.cpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
11
2018-01-10T12:35:04.000Z
2018-08-29T01:47:48.000Z
test/main.cpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
null
null
null
test/main.cpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
2
2018-01-10T13:04:08.000Z
2018-01-10T13:24:12.000Z
#include <iostream> #include <thread> #include <chrono> #include <utility> #include <stdint.h> #include <stdio.h> #include <unistd.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <robot.h> #include "strategy.hpp" #include "game.hpp" #include "vision.hpp" #include "interact.hpp" int entry_point(int argc, const char *argv[]) { static char char_buffer[200]; robot_h robot = robot_init(); vision_init(robot); interact_init(robot); game_state_t game_state = load_initial_game_state(); std::cout << "Initial state = " << game_state << std::endl; try { game_state = strategy_init(game_state); bool moved; do { game_state = strategy_step(game_state, &moved); } while(moved); } catch (std::exception e) { } std::cout << "Wrapping up " << game_state << std::endl; game_state = strategy_term(game_state); std::cout << "I AM DONE (not sure if i won the game)" << std::endl; std::cout << "Strategy internal state:" << std::endl; strategy_print_internal_state(); std::cout << "Game state: " << std::endl; std::cout << game_state << "\n"; robot_mouse_move(robot, 2000, 100); robot_mouse_press(robot, ROBOT_BUTTON1_MASK); robot_mouse_release(robot, ROBOT_BUTTON1_MASK); robot_free(robot); return 0; }
22.067797
69
0.678955
fyquah95
15db8f5260aaa60a00b0c9e6ce2f08c738014e07
2,436
cc
C++
logging/rtc_event_log/events/rtc_event_begin_log.cc
brandongatling/WebRTC
5b661302097ba03e1055357556c35f6e5d37b550
[ "BSD-3-Clause" ]
null
null
null
logging/rtc_event_log/events/rtc_event_begin_log.cc
brandongatling/WebRTC
5b661302097ba03e1055357556c35f6e5d37b550
[ "BSD-3-Clause" ]
null
null
null
logging/rtc_event_log/events/rtc_event_begin_log.cc
brandongatling/WebRTC
5b661302097ba03e1055357556c35f6e5d37b550
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2021 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "logging/rtc_event_log/events/rtc_event_begin_log.h" #include "absl/strings/string_view.h" namespace webrtc { constexpr RtcEvent::Type RtcEventBeginLog::kType; constexpr EventParameters RtcEventBeginLog::event_params_; constexpr FieldParameters RtcEventBeginLog::utc_start_time_params_; RtcEventBeginLog::RtcEventBeginLog(Timestamp timestamp, Timestamp utc_start_time) : RtcEvent(timestamp.us()), utc_start_time_ms_(utc_start_time.ms()) {} RtcEventBeginLog::RtcEventBeginLog(const RtcEventBeginLog& other) : RtcEvent(other.timestamp_us_) {} RtcEventBeginLog::~RtcEventBeginLog() = default; std::string RtcEventBeginLog::Encode(rtc::ArrayView<const RtcEvent*> batch) { EventEncoder encoder(event_params_, batch); encoder.EncodeField( utc_start_time_params_, ExtractRtcEventMember(batch, &RtcEventBeginLog::utc_start_time_ms_)); return encoder.AsString(); } RtcEventLogParseStatus RtcEventBeginLog::Parse( absl::string_view encoded_bytes, bool batched, std::vector<LoggedStartEvent>& output) { EventParser parser; auto status = parser.Initialize(encoded_bytes, batched); if (!status.ok()) return status; rtc::ArrayView<LoggedStartEvent> output_batch = ExtendLoggedBatch(output, parser.NumEventsInBatch()); constexpr FieldParameters timestamp_params{ "timestamp_ms", FieldParameters::kTimestampField, FieldType::kVarInt, 64}; RtcEventLogParseStatusOr<rtc::ArrayView<uint64_t>> result = parser.ParseNumericField(timestamp_params); if (!result.ok()) return result.status(); PopulateRtcEventTimestamp(result.value(), &LoggedStartEvent::timestamp, output_batch); result = parser.ParseNumericField(utc_start_time_params_); if (!result.ok()) return result.status(); PopulateRtcEventTimestamp(result.value(), &LoggedStartEvent::utc_start_time, output_batch); return RtcEventLogParseStatus::Success(); } } // namespace webrtc
34.8
80
0.741379
brandongatling
15e4deccf52e9e0e9b5edf47ad2475e34f076184
1,109
cpp
C++
stxxl/lib/common/version.cpp
ernstki/kASA
f1d5722442ddce47bdb60406fd7e0636a22499b9
[ "BSL-1.0" ]
406
2015-01-31T01:37:16.000Z
2022-03-14T00:58:18.000Z
lib/common/version.cpp
bensuperpc/stxxl
b9e44f0ecba7d7111fbb33f3330c3e53f2b75236
[ "BSL-1.0" ]
82
2015-01-06T14:06:19.000Z
2021-05-02T13:30:32.000Z
lib/common/version.cpp
bensuperpc/stxxl
b9e44f0ecba7d7111fbb33f3330c3e53f2b75236
[ "BSL-1.0" ]
89
2015-02-11T20:01:16.000Z
2022-03-28T18:20:18.000Z
/*************************************************************************** * lib/common/version.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2007, 2008, 2011 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * Copyright (C) 2013 Timo Bingmann <tb@panthema.net> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <stxxl/bits/config.h> #include <stxxl/bits/namespace.h> #include <stxxl/bits/version.h> STXXL_BEGIN_NAMESPACE int version_major() { return STXXL_VERSION_MAJOR; } int version_minor() { return STXXL_VERSION_MINOR; } int version_patch() { return STXXL_VERSION_PATCH; } int version_integer() { return STXXL_VERSION_INTEGER; } const char * get_library_version_string() { return get_version_string(); } const char * get_library_version_string_long() { return get_version_string_long(); } STXXL_END_NAMESPACE // vim: et:ts=4:sw=4
20.924528
82
0.628494
ernstki
15e9e476c0ef06cbf429cd5e0b99c7263f2dd526
825
cc
C++
permission_broker/deny_usb_device_class_rule.cc
doitmovin/chromiumos-platform2
6462aaf43072307b5a40eb045a89e473381b5fda
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
permission_broker/deny_usb_device_class_rule.cc
doitmovin/chromiumos-platform2
6462aaf43072307b5a40eb045a89e473381b5fda
[ "BSD-3-Clause" ]
null
null
null
permission_broker/deny_usb_device_class_rule.cc
doitmovin/chromiumos-platform2
6462aaf43072307b5a40eb045a89e473381b5fda
[ "BSD-3-Clause" ]
2
2021-01-26T12:37:19.000Z
2021-05-18T13:37:57.000Z
// Copyright (c) 2012 The Chromium OS 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 "permission_broker/deny_usb_device_class_rule.h" #include <libudev.h> #include "base/strings/stringprintf.h" namespace permission_broker { DenyUsbDeviceClassRule::DenyUsbDeviceClassRule(const uint8_t device_class) : UsbSubsystemUdevRule("DenyUsbDeviceClassRule"), device_class_(base::StringPrintf("%.2x", device_class)) {} Rule::Result DenyUsbDeviceClassRule::ProcessUsbDevice( struct udev_device *device) { const char *device_class = udev_device_get_sysattr_value(device, "bDeviceClass"); if (device_class && (device_class_ == device_class)) return DENY; return IGNORE; } } // namespace permission_broker
30.555556
74
0.763636
doitmovin
15ea3ecde4733a3e20052b4a81f09ee8400f6a40
713
cpp
C++
PRACTICE/cntMvs_Hanoi.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/cntMvs_Hanoi.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/cntMvs_Hanoi.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; int num=0; void tower_of_brahma(int n,char a, char c,char b,char p) { if(n==0) exit(0); if(n==1) { cout<<"\nMove Disk "<<n<<" from "<<a<<" to "<<c; { if((a=='x' || b=='x'|| c=='x') && (a==p || b==p || c==p)) num++; } } else { tower_of_brahma(n-1,a,c,b,p); tower_of_brahma(n-1,a,b,c,p); tower_of_brahma(n-1,b,a,c,p); } } int main() { int n; char p; cin>>n>>p; tower_of_brahma(n,'X','Y','Z',p); cout<<"\n\nMoves:- "<<pow(2,n)-1<<endl; cout<<"\nNumber of Moves between X and "<<p<<" is "<<num; return 0; }
16.97619
69
0.4446
prasantmahato
15ebaa37a6285c8fb979107dbc94bfba7d7dee1b
142
hxx
C++
src/Providers/UNIXProviders/PolicyRuleValidityPeriod/UNIX_PolicyRuleValidityPeriod_ZOS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/PolicyRuleValidityPeriod/UNIX_PolicyRuleValidityPeriod_ZOS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/PolicyRuleValidityPeriod/UNIX_PolicyRuleValidityPeriod_ZOS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_ZOS #ifndef __UNIX_POLICYRULEVALIDITYPERIOD_PRIVATE_H #define __UNIX_POLICYRULEVALIDITYPERIOD_PRIVATE_H #endif #endif
11.833333
49
0.866197
brunolauze
15ecef24af6f7759bcada9beba84d795cc6dc336
22,295
hpp
C++
include/adl/std/string_view.hpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
2
2021-01-12T12:04:09.000Z
2022-03-21T10:09:54.000Z
include/adl/std/string_view.hpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
70
2017-02-25T16:37:48.000Z
2018-01-28T22:15:42.000Z
include/adl/std/string_view.hpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
null
null
null
// $flisboac 2017-04-01 /** * @file string_view.hpp */ #ifndef adl__std__string_view__hpp__ #define adl__std__string_view__hpp__ #if adl_CONFIG_LANG_IS_CPP17 #include <string_view> #else #include "adl/char_helper.hpp" #endif #include <string> #include <iterator> #include <type_traits> #include <stdexcept> #include "adl.cfg.hpp" // // [[ API ]] // adl_BEGIN_ROOT_MODULE #if adl_CONFIG_LANG_IS_CPP17 template <typename Char, typename Traits = std::char_traits<Char>> using basic_string_view = std::basic_string_view<Char, Traits>; using string_view = std::string_view; using wstring_view = std::wstring_view; template <typename Char> using char_traits = std::char_traits<Char>; #else template <typename Char> using char_traits = char_helper<Char>; template <typename Char, typename Traits = char_traits<Char>> class basic_string_view; using string_view = basic_string_view<char>; using wstring_view = basic_string_view<wchar_t>; template <typename Char, typename Traits> class basic_string_view { private: using helper_ = char_helper<Char>; public: using traits_type = Traits; using value_type = Char; using pointer = Char*; using const_pointer = const Char*; using reference = Char&; using const_reference = const Char&; using size_type = std::size_t; using difference_type = std::ptrdiff_t; constexpr static const size_type npos = (size_type) -1; static_assert(std::is_same<value_type, typename traits_type::char_type>::value, "Character types must be the same."); class const_iterator { public: constexpr const_iterator() noexcept = default; constexpr const_iterator(const const_iterator&) = default; constexpr const_iterator(const Char* value, size_type size, size_type pos, bool reverse) noexcept; constexpr bool operator==(const_iterator rhs) const noexcept; constexpr bool operator!=(const_iterator rhs) const noexcept; constexpr bool operator>=(const_iterator rhs) const noexcept; constexpr bool operator> (const_iterator rhs) const noexcept; constexpr bool operator<=(const_iterator rhs) const noexcept; constexpr bool operator< (const_iterator rhs) const noexcept; constexpr const_iterator operator+(size_type rhs) const; constexpr const_iterator operator-(size_type rhs) const; constexpr const_iterator& operator+=(size_type rhs); constexpr const_iterator& operator-=(size_type rhs); constexpr const Char& operator*() const; constexpr const Char& operator[](size_type rhs) const; constexpr const_iterator& operator++(); constexpr const_iterator operator++(int); constexpr const_iterator& operator--(); constexpr const_iterator operator--(int); private: bool reverse_ = false; size_type size_ { 0 }; size_type pos_ { 0 }; const_pointer value_ { helper_::empty_c_str }; }; using iterator = const_iterator; using const_reverse_iterator = iterator; using reverse_iterator = const_reverse_iterator; // Constructors and assignments constexpr basic_string_view() noexcept = default; constexpr basic_string_view(const basic_string_view& rhs) noexcept = default; constexpr basic_string_view(const Char* s, size_type count) noexcept; constexpr basic_string_view(const Char* s); basic_string_view& operator=(const basic_string_view& rhs) noexcept = default; // Iterators constexpr const_iterator begin() const noexcept; constexpr const_iterator cbegin() const noexcept; constexpr const_iterator end() const noexcept; constexpr const_iterator cend() const noexcept; constexpr const_iterator rbegin() const noexcept; constexpr const_iterator crbegin() const noexcept; constexpr const_iterator rend() const noexcept; constexpr const_iterator crend() const noexcept; // Accessors and properties constexpr const_reference at(size_type pos) const; constexpr const_reference front() const; constexpr const_reference back() const; constexpr const_pointer data() const noexcept; constexpr size_type size() const noexcept; constexpr size_type length() const noexcept; constexpr size_type max_size() const noexcept; constexpr bool empty() const noexcept; // Operations inline size_type copy(Char* dest, size_type count, size_type pos = 0) const; constexpr basic_string_view substr(size_type pos = 0, size_type count = npos) const; constexpr int compare(basic_string_view rhs) const; constexpr int compare(size_type pos, size_type count, basic_string_view rhs) const; constexpr int compare( size_type pos1, size_type count1, basic_string_view rhs, size_type pos2, size_type count2 ) const; constexpr int compare(const Char* s) const; constexpr int compare(size_type pos1, size_type count1, const Char* s) const; constexpr int compare(size_type pos1, size_type count1, const Char* s, size_type count2) const; // Operators constexpr const_reference operator[](size_type pos) const; constexpr bool operator==(basic_string_view rhs) const; constexpr bool operator!=(basic_string_view rhs) const; constexpr bool operator< (basic_string_view rhs) const; constexpr bool operator<=(basic_string_view rhs) const; constexpr bool operator> (basic_string_view rhs) const; constexpr bool operator>=(basic_string_view rhs) const; private: constexpr int compare_result_(int cmp, size_t rhs_size) const; private: size_type size_ { 0 }; const_pointer value_ { helper_::empty_c_str }; }; #endif template <typename Char> std::string to_string(basic_string_view<Char> const& str); std::string to_string(std::string str); namespace literals { inline namespace string_view { constexpr basic_string_view<char> operator "" _sv(const char* str, std::size_t len) noexcept; constexpr basic_string_view<wchar_t> operator "" _sv(const wchar_t* str, std::size_t len) noexcept; constexpr basic_string_view<char16_t> operator "" _sv(const char16_t* str, std::size_t len) noexcept; constexpr basic_string_view<char32_t> operator "" _sv(const char32_t* str, std::size_t len) noexcept; } } template <typename T> adl_IAPI T const* string_printf_basic_arg_(basic_string_view<T> const& value) noexcept(false); adl_END_ROOT_MODULE #if !adl_CONFIG_LANG_IS_CPP17 template <class CharT, class Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, adl::basic_string_view<CharT, Traits> v ); template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator+( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ); template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator-( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ); #endif // // [[ IMPLEMENTATION ]] // adl_BEGIN_ROOT_MODULE // // functions // template <typename Char> adl_IMPL std::string to_string(basic_string_view<Char> const& str) { return std::string(str.data(), str.size()); } adl_IMPL std::string to_string(std::string str) { return str; } template <typename T> adl_IMPL T const* string_printf_basic_arg_(basic_string_view<T> const& value) noexcept(false) { throw std::invalid_argument("Cannot string_printf with a basic_string_view argument."); } namespace literals { inline namespace string_view { constexpr basic_string_view<char> operator ""_sv(const char* str, std::size_t len) noexcept { return basic_string_view<char>(str, len); } constexpr basic_string_view<wchar_t> operator ""_sv(const wchar_t* str, std::size_t len) noexcept { return basic_string_view<wchar_t>(str, len); } constexpr basic_string_view<char16_t> operator ""_sv(const char16_t* str, std::size_t len) noexcept { return basic_string_view<char16_t>(str, len); } constexpr basic_string_view<char32_t> operator ""_sv(const char32_t* str, std::size_t len) noexcept { return basic_string_view<char32_t>(str, len); } } } adl_END_ROOT_MODULE #if !adl_CONFIG_LANG_IS_CPP17 template <class CharT, class Traits> adl_IMPL std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, adl::basic_string_view<CharT, Traits> v) { auto string = adl::to_string(v); os << string; return os; } template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator+( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ) { return iter + rhs; } template <typename Char, typename Traits> constexpr typename adl::basic_string_view<Char, Traits>::const_iterator operator-( typename adl::basic_string_view<Char, Traits>::size_type rhs, typename adl::basic_string_view<Char, Traits>::const_iterator iter ) { return iter - rhs; } #endif // !adl_CONFIG_LANG_IS_CPP17 // // [[ TEMPLATE IMPLEMENTATION ]] // #if !adl_CONFIG_LANG_IS_CPP17 // // basic_string_view // adl_BEGIN_ROOT_MODULE template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits>::basic_string_view( const Char* s, typename basic_string_view<Char, Traits>::size_type count ) noexcept : size_(count), value_(s) {} template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits>::basic_string_view(const Char* s) : size_(helper_::length(s)), value_(s) {} template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::begin() const noexcept { return const_iterator(value_, size_, 0, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::cbegin() const noexcept { return const_iterator(value_, size_, 0, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::end() const noexcept { return const_iterator(value_, size_, size_, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::cend() const noexcept { return const_iterator(value_, size_, size_, false); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::rbegin() const noexcept { return const_iterator(value_, size_, 0, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::crbegin() const noexcept { return const_iterator(value_, size_, 0, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::rend() const noexcept { return const_iterator(value_, size_, npos, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::crend() const noexcept { return const_iterator(value_, size_, npos, true); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::operator[]( typename basic_string_view<Char, Traits>::size_type pos ) const { return value_[pos]; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::at( basic_string_view::size_type pos ) const { return (pos < size_) ? value_[pos] : throw std::out_of_range("Index out of bounds"); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::front() const { return this->operator[](0); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_reference basic_string_view<Char, Traits>::back() const { return this->operator[](size_ - 1); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_pointer basic_string_view<Char, Traits>::data() const noexcept { return value_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::size() const noexcept { return size_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::length() const noexcept { return size_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::max_size() const noexcept { return npos - 1; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::empty() const noexcept { return size_ == 0; } template <typename Char, typename Traits> typename basic_string_view<Char, Traits>::size_type basic_string_view<Char, Traits>::copy( Char* dest, basic_string_view::size_type count, basic_string_view::size_type pos ) const { size_t nchars = 0; const size_t chars_limit = size() - pos; const size_t max_chars = count < chars_limit ? count : chars_limit; if (pos >= size_) throw std::out_of_range("Index out of bounds"); for (nchars = 0; nchars < max_chars; ++nchars) dest[nchars] = value_[nchars + pos]; return nchars; } template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits> basic_string_view<Char, Traits>::substr( basic_string_view::size_type pos, basic_string_view::size_type count ) const { return (pos < size_) ? count < size_ - pos ? basic_string_view(value_ + pos, count) : basic_string_view(value_ + pos, size_ - pos) : throw std::out_of_range("Index out of bounds"); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare(basic_string_view rhs) const { return compare_result_(Traits::compare(value_, rhs.value_, size_ < rhs.size_ ? size_ : rhs.size_), rhs.size_); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos, basic_string_view::size_type count, basic_string_view rhs ) const { return substr(pos, count).compare(rhs); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos1, basic_string_view::size_type count1, basic_string_view rhs, basic_string_view::size_type pos2, basic_string_view::size_type count2 ) const { return substr(pos1, count1).compare(rhs.substr(pos2, count2)); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare(const Char* s) const { return compare(basic_string_view(s)); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos1, basic_string_view::size_type count1, const Char* s ) const { return substr(pos1, count1).compare(basic_string_view(s)); } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare( basic_string_view::size_type pos1, basic_string_view::size_type count1, const Char* s, basic_string_view::size_type count2 ) const { return substr(pos1, count1).compare(basic_string_view(s, count2)); } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator==(basic_string_view rhs) const { return compare(rhs) == 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator!=(basic_string_view rhs) const { return compare(rhs) != 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator<(basic_string_view rhs) const { return compare(rhs) < 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator<=(basic_string_view rhs) const { return compare(rhs) <= 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator>(basic_string_view rhs) const { return compare(rhs) > 0; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::operator>=(basic_string_view rhs) const { return compare(rhs) >= 0; } template <typename Char, typename Traits> constexpr int basic_string_view<Char, Traits>::compare_result_(int cmp, size_t rhs_size) const { return cmp == 0 ? size_ < rhs_size ? -1 : size_ > rhs_size ? 1 : 0 : cmp; } // // basic_string_view::const_iterator // template <typename Char, typename Traits> constexpr basic_string_view<Char, Traits>::const_iterator::const_iterator( const Char* value, basic_string_view::size_type size, basic_string_view::size_type pos, bool reverse ) noexcept : reverse_(reverse), size_(size), pos_(pos), value_(value) {} template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator==( basic_string_view::const_iterator rhs ) const noexcept { return pos_ == rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator!=( basic_string_view::const_iterator rhs ) const noexcept { return pos_ != rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator>=( basic_string_view::const_iterator rhs ) const noexcept { return pos_ >= rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator>( basic_string_view::const_iterator rhs ) const noexcept { return pos_ > rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator<=( basic_string_view::const_iterator rhs ) const noexcept { return pos_ <= rhs.pos_; } template <typename Char, typename Traits> constexpr bool basic_string_view<Char, Traits>::const_iterator::operator<( basic_string_view::const_iterator rhs ) const noexcept { return pos_ < rhs.pos_; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator+( typename basic_string_view<Char, Traits>::size_type rhs ) const { return const_iterator(value_, size_, pos_ + rhs, reverse_); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator-( typename basic_string_view<Char, Traits>::size_type rhs ) const { return const_iterator(value_, size_, pos_ - rhs, reverse_); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator+=( typename basic_string_view<Char, Traits>::size_type rhs ) { pos_ += rhs; return *this; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator-=( typename basic_string_view<Char, Traits>::size_type rhs ) { pos_ -= rhs; return *this; } template <typename Char, typename Traits> constexpr const Char& basic_string_view<Char, Traits>::const_iterator::operator*() const { return value_[pos_]; } template <typename Char, typename Traits> constexpr const Char& basic_string_view<Char, Traits>::const_iterator::operator[]( typename basic_string_view<Char, Traits>::size_type rhs ) const { return value_[pos_ + rhs]; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator++() { if (reverse_) { --pos_; } else { ++pos_; } return *this; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator++(int) { return const_iterator(value_, size_, reverse_ ? pos_-- : pos_++, reverse_); } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator& basic_string_view<Char, Traits>::const_iterator::operator--() { if (reverse_) { ++pos_; } else { --pos_; } return *this; } template <typename Char, typename Traits> constexpr typename basic_string_view<Char, Traits>::const_iterator basic_string_view<Char, Traits>::const_iterator::operator--(int) { return const_iterator(value_, size_, reverse_ ? pos_++ : pos_--, reverse_); } adl_END_ROOT_MODULE #endif #endif // adl__std__string_view__hpp__
33.831563
116
0.719847
flisboac
15f5fbbf52fa8d2cbc7eb0886eee9fcbd7631cba
967
cpp
C++
plugins/imageviewer2/src/imageviewer2.cpp
sellendk/megamol
0e4840b1897706c861946992ce3524bafab53352
[ "BSD-3-Clause" ]
null
null
null
plugins/imageviewer2/src/imageviewer2.cpp
sellendk/megamol
0e4840b1897706c861946992ce3524bafab53352
[ "BSD-3-Clause" ]
null
null
null
plugins/imageviewer2/src/imageviewer2.cpp
sellendk/megamol
0e4840b1897706c861946992ce3524bafab53352
[ "BSD-3-Clause" ]
null
null
null
/** * MegaMol * Copyright (c) 2009-2021, MegaMol Dev Team * All rights reserved. */ #include "mmcore/utility/plugins/AbstractPluginInstance.h" #include "mmcore/utility/plugins/PluginRegister.h" #include "imageviewer2/ImageRenderer.h" namespace megamol::imageviewer2 { class Imaggeviewer2PluginInstance : public megamol::core::utility::plugins::AbstractPluginInstance { REGISTERPLUGIN(Imaggeviewer2PluginInstance) public: Imaggeviewer2PluginInstance() : megamol::core::utility::plugins::AbstractPluginInstance("imageviewer2", "The imageviewer2 plugin."){}; ~Imaggeviewer2PluginInstance() override = default; // Registers modules and calls void registerClasses() override { // register modules this->module_descriptions.RegisterAutoDescription<megamol::imageviewer2::ImageRenderer>(); // register calls } }; } // namespace megamol::imageviewer2
30.21875
120
0.698035
sellendk
15f7e542004949e62ed8473a52c962fa9cfb8d32
3,450
cpp
C++
modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Pyatckin Nikolai #include <math.h> #include <mpi.h> #include <random> #include <iostream> #include <algorithm> #include <functional> #include <vector> #include <utility> #include "../../../modules/task_3/pyatckin_n_integrals_rectangle/integrals_rectangle.h" double ParallelIntegral(std::function<double(const std::vector<double>)> func, std::vector <std::pair<double, double>> scope, const int num) { int dim = scope.size(); int num_rang; std::vector<double> local_scope(dim); std::vector<std::pair<double, double >> ranges(dim); int num_elem; int mrank; int numprocs, rank; MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (numprocs < 4) { numprocs = 2 - numprocs % 2; mrank = numprocs; } else { numprocs = 4; mrank = 4; } ranges = scope; num_rang = num; num_elem = pow(num_rang, dim - 1); if (rank == 0) { for (int i = 0; i < dim; ++i) { local_scope[i] = (scope[i].second - scope[i].first) / num_rang; } } MPI_Bcast(&mrank, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&num_elem, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&num_rang, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&local_scope[0], dim, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Bcast(&ranges[0], 2 * dim, MPI_DOUBLE, 0, MPI_COMM_WORLD); int rem = num_elem % numprocs; int count = num_elem / numprocs; std::vector<std::vector<double>> params(count); int tmp = 0; double sum = 0.0; if (rank < mrank) { if (rank < rem) { count++; tmp = rank * count; } else { tmp = rem * (count + 1) + (rank - rem) * count; } for (int i = 0; i < count; ++i) { int number = tmp + i; for (int j = 0; j < dim - 1; ++j) { int cef = number % num_rang; params[i].push_back(ranges[j].first + cef * local_scope[j] + local_scope[j] / 2); number /= num_rang; } } for (int i = 0; i < count; ++i) { for (int j = 0; j < num_rang; ++j) { params[i].push_back(ranges[dim - 1].first + j * local_scope[dim - 1] + local_scope[dim - 1] / 2); sum += func(params[i]); params[i].pop_back(); } } } double res = 0.0; MPI_Reduce(&sum, &res, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); for (int i = 0; i < dim; ++i) { res *= local_scope[i]; } return res; } double SeqIntegral(std::function<double(const std::vector<double>)> func, std::vector <std::pair<double, double>> scope, const int num) { int count = scope.size(); std::vector<double> local_scope(count); int64_t number = 1; for (int i = 0; i < count; ++i) { local_scope[i] = (scope[i].second - scope[i].first) / num; number *= num; } std::vector <double> params(count); double sum = 0.0; for (int i = 0; i < number; ++i) { int x = i; for (int j = 0; j < count; ++j) { int cef = x % num; params[j] = scope[j].first + cef * local_scope[j] + local_scope[j] / 2; x /= num; } sum += func(params); } for (int i = 0; i < count; ++i) { sum *= local_scope[i]; } return sum; }
30
87
0.526667
Gurgen-Arm
15f8d353eea57eae2457178605a9a659a97ae4e3
7,621
cpp
C++
src/TympanRemoteFormatter.cpp
jamescookmd/Tympan_Library
2d29cb8edbb281584668dd799f95eada11826b38
[ "MIT" ]
89
2017-03-25T19:27:07.000Z
2022-03-21T21:11:03.000Z
src/TympanRemoteFormatter.cpp
jamescookmd/Tympan_Library
2d29cb8edbb281584668dd799f95eada11826b38
[ "MIT" ]
43
2017-05-31T14:38:33.000Z
2022-03-29T09:34:58.000Z
src/TympanRemoteFormatter.cpp
jamescookmd/Tympan_Library
2d29cb8edbb281584668dd799f95eada11826b38
[ "MIT" ]
22
2017-03-07T22:15:59.000Z
2021-12-18T15:23:04.000Z
#include <TympanRemoteFormatter.h> String TR_Button::asString(void) { String s; //original method //s = "{'label':'" + label + "','cmd':'" + command + "','id':'" + id + "','width':'" + width + "'}"; //new method...don't waste time transmitting fields that don't exist s = "{"; if (label.length() > 0) s.concat("'label':'" + label + "',"); if (command.length() > 0) s.concat("'cmd':'" + command + "',"); if (id.length() > 0) s.concat("'id':'" + id + "',"); //if (width.length() > 0) s.concat("'width':'" + width + "'"); //no trailing comma s.concat("'width':'" + String(width) + "'"); //always have a width //if (s.endsWith(",")) s.remove(s.length()-1,1); //strip off trailing comma s.concat("}"); //close off the unit return s; } // //////////////////////////////////////////////////////////////////////////////////////////////////////// TR_Button* TR_Card::addButton(String label, String command, String id, int width) { //make a new button TR_Button *btn = new TR_Button(); if (btn==NULL) return btn; //return if we can't allocate it //link it to the previous button (linked list) TR_Button *prevLastButton = lastButton; if (prevLastButton != NULL) prevLastButton->nextButton = btn; //assign the new page to be the new last page lastButton = btn; nButtons++; //add the data btn->label = label; btn->prevButton = prevLastButton; btn->command = command; btn->id = id; btn->width = width; //we're done return btn; } TR_Button* TR_Card::getFirstButton(void) { TR_Button *btn = lastButton; if (btn == NULL) return NULL; //keep stepping back to find the first TR_Button *prev_btn = btn->prevButton; while (prev_btn != NULL) { btn = prev_btn; prev_btn = btn->prevButton; } return btn; } String TR_Card::asString(void) { String s; s = "{'name':'"+name+"'"; //write buttons TR_Button* btn = getFirstButton(); if (btn != NULL) { //write the first button s += ",'buttons':["; s += btn->asString(); //write other buttons TR_Button* next_button = btn->nextButton; while (next_button != NULL) { btn = next_button; s += ","; s += btn->asString(); next_button = btn->nextButton; } //finish the list s += "]"; } //close out s += "}"; return s; } // //////////////////////////////////////////////////////////////////////////////////////////////////////// TR_Card* TR_Page::addCard(String name) { //make a new card TR_Card *card = new TR_Card(); if (card==NULL) return card; //return if we can't allocate it //link it to the previous card (linked list) TR_Card *prevLastCard = lastCard; if (prevLastCard != NULL) prevLastCard->nextCard = card; //assign the new page to be the new last page lastCard = card; nCards++; //add the data card->name = name; card->prevCard = prevLastCard; //we're done return card; } TR_Card* TR_Page::getFirstCard(void) { TR_Card *card = lastCard; if (card == NULL) return NULL; //keep stepping back to find the first TR_Card *prev_card = card->prevCard; while (prev_card != NULL) { card = prev_card; prev_card = card->prevCard; } return card; } String TR_Page::asString(void) { String s; s = "{'title':'"+name+"'"; //write cards TR_Card* card = getFirstCard(); if (card != NULL) { //write first card s += ",'cards':["; s += card->asString(); //write additional cards TR_Card *next_card = card->nextCard; while (next_card != NULL) { card = next_card; s += ","; s += card->asString(); next_card = card->nextCard; } //finish the list s += "]"; } //close out s += "}"; return s; } // //////////////////////////////////////////////////////////////////////////////////////////////////////// TR_Page* TympanRemoteFormatter::addPage(String name) { //make a new page TR_Page *page = new TR_Page(); if (page==NULL) return page; //return if we can't allocate it //link it to the previous page (linked list) TR_Page *prevLastPage = lastPage; if (prevLastPage != NULL) prevLastPage->nextPage = page; //assign the new page to be the new last page lastPage = page; nCustomPages++; //add the data page->name = name; page->prevPage = prevLastPage; //we're done! return page; } void TympanRemoteFormatter::addPredefinedPage(String s) { if (predefPages.length()>0) { predefPages += ","; } predefPages += "'"+s+"'"; nPredefinedPages++; } TR_Page* TympanRemoteFormatter::getFirstPage(void) { TR_Page *page = lastPage; if (page == NULL) return NULL; //keep stepping back to find the first TR_Page *prev_page = page->prevPage; while (prev_page != NULL) { page = prev_page; prev_page = page->prevPage; } return page; } /* int TympanRemoteFormatter::c_str(char *c_str, int maxLen) { int dest=0, source=0; String s; s = String(F("JSON={'icon':'tympan.png',")); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; // Add pages: if (nCustomPages > 0) { s = String("'pages':[") + pages[0].asString(); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } for (int i=1; i<nCustomPages; i++) { s = String(",") + pages[i].asString(); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } if (nCustomPages > 0) { s = String("]"); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } // Add predefined pages: if (predefPages.length()>1) { if (dest>0) { s = String(","); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } s = String(F("'prescription':{'type':'BoysTown','pages':[")) + predefPages + String("]}"); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; } s = String("}"); source = 0; while ((dest < maxLen) && (source < (int)s.length())) c_str[dest++] = s[source++]; dest = min(dest,maxLen); c_str[dest] = '\0'; //null terminated return dest; } */ String TympanRemoteFormatter::asString(void) { String s; s = F("JSON={'icon':'tympan.png',"); // Add pages s += "'pages':["; //bool anyCustomPages = false; //we don't know yet TR_Page* page = getFirstPage(); if (page != NULL) { //anyCustomPages = true; //write the first page s += page->asString(); //add subsequent pages TR_Page* next_page = page->nextPage; while (next_page != NULL) { page = next_page; s += ","; s += page->asString(); next_page = page->nextPage; } } //close out the custom pages s += "]"; // Add predefined pages: if (predefPages.length()>1) { //if (s.length()>1) { s += ","; //} s += F("'prescription':{'type':'BoysTown','pages':[") + predefPages +"]}"; } //close out s += "}"; return s; } void TympanRemoteFormatter::asValidJSON(void) { String s; s = this->asString(); s.replace("'","\""); Serial.println(F("Pretty printed (a.k.a. valid json):")); Serial.println(s); } void TympanRemoteFormatter::deleteAllPages(void) { //loop through and delete each page that was created TR_Page *page = lastPage; while (page != NULL) { TR_Page *prev_page = page->prevPage; //look to the next loopo delete page; //delete the current page nCustomPages--; //decrement the count page = prev_page; //prepare for next loop if (page != NULL) page->nextPage = NULL; //there is no more next page lastPage = page; //update what the new lastPage is } //clear out the predefined pages predefPages = String(""); nPredefinedPages = 0; }
23.594427
107
0.583257
jamescookmd
15fbbd80d1d342f68c9745d56cb865482ebbf0c5
2,134
cpp
C++
apps/gadgetron/connection/nodes/common/Configuration.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
apps/gadgetron/connection/nodes/common/Configuration.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
apps/gadgetron/connection/nodes/common/Configuration.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
#include "Configuration.h" #include <vector> #include <ismrmrd/ismrmrd.h> #include "io/primitives.h" #include "MessageID.h" using namespace Gadgetron::Core; namespace Gadgetron::Server::Connection::Nodes { using Serializable = Core::variant<Config::External,Config>; static void send_header(std::iostream &stream, const Context::Header &header) { std::stringstream strstream; ISMRMRD::serialize(header, strstream); IO::write(stream, HEADER); IO::write_string_to_stream<uint32_t>(stream, strstream.str()); } static void send_config(std::iostream &stream, const Serializable &config) { Core::visit( [&stream](auto &config) { IO::write(stream, CONFIG); IO::write_string_to_stream<uint32_t>(stream, serialize_config(config)); }, config ); } void Configuration::send(std::iostream &stream) const { send_config(stream, config); send_header(stream, context.header); } Configuration::Configuration( Core::StreamContext context, Config config ) : context(std::move(context)), config{config} {} Configuration::Configuration( Core::StreamContext context, Config::External config ) : context(std::move(context)), config{config} {} Configuration::Configuration( Core::StreamContext context, Config::Distributed config ) : Configuration( std::move(context), Config{ config.readers, config.writers, config.stream } ) {} Configuration::Configuration( Core::StreamContext context, Config::PureDistributed config ) : Configuration( std::move(context), Config{ config.readers, config.writers, Config::Stream { "PureStream", std::vector<Config::Node>(config.stream.gadgets.begin(), config.stream.gadgets.end()) } } ) {} }
28.837838
105
0.574039
roopchansinghv
15fc69abe3f37640a4c6717bcfc94f1fc05cfdbb
5,276
cpp
C++
source/systems/enemysystem.cpp
alohaeee/DungeonSlayer
b1a95031371b5f5b3be8f8d592a56140047e61da
[ "MIT" ]
41
2020-01-31T15:18:57.000Z
2022-03-12T05:48:21.000Z
source/systems/enemysystem.cpp
alohaeee/DungeonSlayer
b1a95031371b5f5b3be8f8d592a56140047e61da
[ "MIT" ]
2
2020-01-31T15:18:52.000Z
2022-02-16T12:21:45.000Z
source/systems/enemysystem.cpp
alohaeee/DungeonSlayer
b1a95031371b5f5b3be8f8d592a56140047e61da
[ "MIT" ]
4
2020-03-27T05:10:19.000Z
2021-02-22T09:18:34.000Z
#include "enemysystem.hpp" #include "../core.hpp" #include <queue> void EnemyCreate(Vector2D spawn) { auto enemy = registry.create(); registry.assign<Enemy>(enemy); auto &pos = registry.assign<Position>(enemy); pos.position = spawn; auto &rect = registry.assign<RectCollider>(enemy); auto &sprite = registry.assign<Sprite>(enemy); auto &speed = registry.assign<MovementSpeed>(enemy); [[maybe_unused]] auto &vel = registry.assign<Velocity>(enemy); registry.assign<Health>(enemy, 2); registry.assign<ParticleData>(enemy); registry.assign<Active>(enemy); speed.speed = 150; registry.assign<CollisionLayer>(enemy, LayersID::ENEMY); sprite.texture = textureCache.resource("spritesheet"); sprite.scale = {2, 2}; sprite.rect = spriteSheet[spriteSheet("zombie_idle").first->second]; sprite.layer = 2; sprite.isFliped = false; rect.rect.w = sprite.rect.w * sprite.scale.x(); rect.rect.h = sprite.rect.h * sprite.scale.y(); auto &animation = registry.assign<AnimationPool>(enemy); auto idle = spriteSheet.GetTypeFamily("zombie_idle"); auto run = spriteSheet.GetTypeFamily("zombie_run"); animation.data.emplace("idle", Animation{idle, 0.07f, 0, 0}); animation.data.emplace("run", Animation{run, 0.07f, 0, 0}); animation.current = "idle"; auto view = registry.create(); auto multiplier = registry.assign<View>(view); registry.assign<Active>(view); registry.assign<CollisionLayer>(view, LayersID::ENEMY); multiplier.multiplier = 12; registry.assign<Position>(view); auto &view_rect = registry.assign<RectCollider>(view); view_rect.rect.w = sprite.rect.w * sprite.scale.x() * multiplier.multiplier; view_rect.rect.h = sprite.rect.h * sprite.scale.y() * multiplier.multiplier; view_rect.rect.x = -view_rect.rect.w / 2 + sprite.rect.w * sprite.scale.x(); view_rect.rect.y = -view_rect.rect.h / 2 + sprite.rect.h * sprite.scale.y(); auto &parent = registry.assign<Hierarchy>(enemy); parent.child = view; auto &child = registry.assign<Hierarchy>(view); child.parent = enemy; } void UpdateView() { auto view = registry.view<Hierarchy, Position, RectCollider, View>(); view.each([](auto &hierarchy, auto &position, auto &rect, auto &view) { auto parent_pos = registry.get<Position>(hierarchy.parent); position.position.Set(parent_pos.position.x(), parent_pos.position.y()); }); } void EnemyCharging(const CollisionData &lhs, const CollisionData &rhs) { if (registry.has<View>(lhs.id) && registry.has<Player>(rhs.id)) { auto &&[player_pos, player] = registry.get<Position, Player>(rhs.id); auto parent = registry.get<Hierarchy>(lhs.id).parent; auto &&[enemy_pos, enemy_vel, enemy_speed, enemy] = registry.get<Position, Velocity, MovementSpeed, Enemy>(parent); enemy_vel.x = (player_pos.position.normalized()).x() * enemy_speed.speed; enemy_vel.y = (player_pos.position.normalized()).y() * enemy_speed.speed; if (enemy_pos.position.x() > player_pos.position.x()) { enemy_vel.x *= -1; } else { enemy_vel.x *= 1; } if (enemy_pos.position.y() > player_pos.position.y()) { enemy_vel.y *= -1; } else { enemy_vel.y *= 1; } enemy.isCharched = true; enemy.dt = 0; } } void EnemyWalking(const float dt) { auto view = registry.view<Enemy, Velocity, MovementSpeed, Active>(); view.each([dt](auto &enemy, auto &vel, auto &speed, const auto &) { if (enemy.dt > enemy.time) { if (vel.x || vel.y) { vel.x = 0; vel.y = 0; } else { auto result = std::rand() % 2; if (result) { result = std::rand() % 2; if (result) { vel.x = 0.5f * speed.speed; } else { vel.x = -0.5f * speed.speed; } } else { result = std::rand() % 2; if (result) { vel.y = 0.5f * speed.speed; } else { vel.y = -0.5f * speed.speed; } } } vel.y = 0; enemy.dt = 0; } enemy.dt += dt; }); } void HealthUpdate() { auto view = registry.view<Enemy, Health, Active, Position>(); for (auto &entt : view) { auto &health = view.get<Health>(entt); if (health.health <= 0) { auto &&[position, enemy] = view.get<Position, Enemy>(entt); position.position = Enemy::spawns[Enemy::currentSpawn]; Enemy::currentSpawn++; health.health = 2; if (Enemy::currentSpawn >= Enemy::MAX_SPAWNS) { Enemy::currentSpawn = 0; } } } }
30.674419
81
0.539803
alohaeee
15fe425b500e890081af3276130fa48b5feb2512
1,085
cpp
C++
Pagerank_viz/pagenode.cpp
Ybalrid/pagerank_stocha_4A
8f265ad70f5284374922ba7988baaf5c99085abd
[ "MIT" ]
null
null
null
Pagerank_viz/pagenode.cpp
Ybalrid/pagerank_stocha_4A
8f265ad70f5284374922ba7988baaf5c99085abd
[ "MIT" ]
null
null
null
Pagerank_viz/pagenode.cpp
Ybalrid/pagerank_stocha_4A
8f265ad70f5284374922ba7988baaf5c99085abd
[ "MIT" ]
null
null
null
#include "pagenode.h" PageNode::PageNode(QString accessUrl) : url(accessUrl), elipse(nullptr), urlTag(nullptr), active(false), rank(0) { } void PageNode::linkTo(PageNode *otherPage) { linkedPages.push_back(otherPage); qDebug() << "Page " << url << " has an hyperlink to " << otherPage->getUrl(); } QString PageNode::getUrl() { return url; } QGraphicsEllipseItem* PageNode::getVisualNode() { return elipse; } QGraphicsTextItem* PageNode::getUrlTag() { return urlTag; } void PageNode::setElipse(QGraphicsEllipseItem *e) { elipse = e; } void PageNode::setUrlTag(QGraphicsTextItem *t) { urlTag = t; } QVector<PageNode*> PageNode::getLinkedPagesVector() { return linkedPages; } void PageNode::setActive(bool activeState) { active = activeState; } bool PageNode::isActive() { return active; } void PageNode::resetRank() { rank = 0; } void PageNode::incraseRank() { rank++; } float PageNode::getNormalizedRank(float maxRank) { return 10.0f * (rank/maxRank); } float PageNode::getRank() { return rank; }
13.910256
80
0.668203
Ybalrid
15fe9056534d1d419179b5a6a9d295a04da50446
9,590
cpp
C++
Code/RDBoost/Wrap/RDBase.cpp
i-tub/rdkit
fb49a33b5adaa2c203efdbeae568134095b353c7
[ "BSD-3-Clause" ]
null
null
null
Code/RDBoost/Wrap/RDBase.cpp
i-tub/rdkit
fb49a33b5adaa2c203efdbeae568134095b353c7
[ "BSD-3-Clause" ]
null
null
null
Code/RDBoost/Wrap/RDBase.cpp
i-tub/rdkit
fb49a33b5adaa2c203efdbeae568134095b353c7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2004-2019 greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <RDBoost/python.h> #include <iostream> #include <fstream> #include <RDBoost/Wrap.h> #include <RDBoost/python_streambuf.h> #include <RDGeneral/versions.h> #include <RDGeneral/Invariant.h> #include <cstdlib> #include <RDGeneral/RDLog.h> #if 0 #include <boost/log/functions.hpp> #if defined(BOOST_HAS_THREADS) #include <boost/log/extra/functions_ts.hpp> #endif #endif namespace python = boost::python; namespace logging = boost::logging; std::string _version() { return "$Id$"; } // std::ostream wrapper around Python's stderr stream struct PyErrStream : std::ostream, std::streambuf { static thread_local std::string buffer; PyErrStream() : std::ostream(this) { // All done! } int overflow(int c) override { write(c); return 0; } void write(char c) { if (c == '\n') { PyGILStateHolder h; PySys_WriteStderr("%s\n", buffer.c_str()); buffer.clear(); } else { buffer += c; } } }; // std::ostream wrapper around Python's logging module struct PyLogStream : std::ostream, std::streambuf { static thread_local std::string buffer; PyObject *logfn = nullptr; PyLogStream(std::string level) : std::ostream(this) { PyObject *module = PyImport_ImportModule("logging"); PyObject *logger = nullptr; if (module != nullptr) { logger = PyObject_CallMethod(module, "getLogger", "s", "rdkit"); Py_DECREF(module); } if (logger != nullptr) { logfn = PyObject_GetAttrString(logger, level.c_str()); Py_DECREF(logger); } if (PyErr_Occurred()) { PyErr_Print(); } } ~PyLogStream() { if (!_Py_IsFinalizing()) { Py_XDECREF(logfn); } } int overflow(int c) override { write(c); return 0; } void write(char c) { if (logfn == nullptr) { return; } if (c == '\n') { PyGILStateHolder h; PyObject *result = PyObject_CallFunction(logfn, "s", buffer.c_str()); Py_XDECREF(result); buffer.clear(); } else { buffer += c; } } }; // per-thread buffers for the Python loggers thread_local std::string PyErrStream::buffer; thread_local std::string PyLogStream::buffer; void LogToPythonLogger() { static PyLogStream debug("debug"); static PyLogStream info("info"); static PyLogStream warning("warning"); static PyLogStream error("error"); rdDebugLog = std::make_shared<logging::rdLogger>(&debug); rdInfoLog = std::make_shared<logging::rdLogger>(&info); rdWarningLog = std::make_shared<logging::rdLogger>(&warning); rdErrorLog = std::make_shared<logging::rdLogger>(&error); } void LogToPythonStderr() { static PyErrStream debug; static PyErrStream info; static PyErrStream warning; static PyErrStream error; rdDebugLog = std::make_shared<logging::rdLogger>(&debug); rdInfoLog = std::make_shared<logging::rdLogger>(&info); rdWarningLog = std::make_shared<logging::rdLogger>(&warning); rdErrorLog = std::make_shared<logging::rdLogger>(&error); } void WrapLogs() { static PyErrStream debug; //("RDKit DEBUG: "); static PyErrStream error; //("RDKit ERROR: "); static PyErrStream warning; //("RDKit WARNING: "); static PyErrStream info; //("RDKit INFO: "); if (!rdDebugLog || !rdInfoLog || !rdErrorLog || !rdWarningLog) { RDLog::InitLogs(); } rdDebugLog->SetTee(debug); rdInfoLog->SetTee(info); rdWarningLog->SetTee(warning); rdErrorLog->SetTee(error); } void EnableLog(std::string spec) { logging::enable_logs(spec); } void DisableLog(std::string spec) { logging::disable_logs(spec); } std::string LogStatus() { return logging::log_status(); } void AttachFileToLog(std::string spec, std::string filename, int delay = 100) { (void)spec; (void)filename; (void)delay; #if 0 #if defined(BOOST_HAS_THREADS) logging::manipulate_logs(spec) .add_appender(logging::ts_appender(logging::write_to_file(filename), delay)); #else logging::manipulate_logs(spec) .add_appender(logging::write_to_file(filename)); #endif #endif } void LogDebugMsg(const std::string &msg) { // NOGIL nogil; BOOST_LOG(rdDebugLog) << msg << std::endl; } void LogInfoMsg(const std::string &msg) { // NOGIL nogil; BOOST_LOG(rdInfoLog) << msg << std::endl; } void LogWarningMsg(const std::string &msg) { // NOGIL nogil; BOOST_LOG(rdWarningLog) << msg << std::endl; } void LogErrorMsg(const std::string &msg) { // NOGIL nogil; BOOST_LOG(rdErrorLog) << msg << std::endl; } void LogMessage(std::string spec, std::string msg) { if (spec == "rdApp.error") { LogErrorMsg(msg); } else if (spec == "rdApp.warning") { LogWarningMsg(msg); } else if (spec == "rdApp.info") { LogInfoMsg(msg); } else if (spec == "rdApp.debug") { LogDebugMsg(msg); } } class BlockLogs : public boost::noncopyable { public: BlockLogs() : m_log_setter{new RDLog::LogStateSetter} {} ~BlockLogs() = default; BlockLogs *enter() { return this; } void exit(python::object exc_type, python::object exc_val, python::object traceback) { RDUNUSED_PARAM(exc_type); RDUNUSED_PARAM(exc_val); RDUNUSED_PARAM(traceback); m_log_setter.reset(); } private: std::unique_ptr<RDLog::LogStateSetter> m_log_setter; }; namespace { struct python_streambuf_wrapper { typedef boost_adaptbx::python::streambuf wt; static void wrap() { using namespace boost::python; class_<wt, boost::noncopyable>("streambuf", no_init) .def(init<object &, std::size_t>( (arg("python_file_obj"), arg("buffer_size") = 0), "documentation")[with_custodian_and_ward_postcall<0, 2>()]); } }; struct python_ostream_wrapper { typedef boost_adaptbx::python::ostream wt; static void wrap() { using namespace boost::python; class_<std::ostream, boost::noncopyable>("std_ostream", no_init); class_<wt, boost::noncopyable, bases<std::ostream>>("ostream", no_init) .def(init<object &, std::size_t>( (arg("python_file_obj"), arg("buffer_size") = 0))); } }; void seedRNG(unsigned int seed) { std::srand(seed); } } // namespace BOOST_PYTHON_MODULE(rdBase) { python::scope().attr("__doc__") = "Module containing basic definitions for wrapped C++ code\n" "\n"; RDLog::InitLogs(); RegisterVectorConverter<int>(); RegisterVectorConverter<unsigned>(); RegisterVectorConverter<double>(); RegisterVectorConverter<std::string>(1); RegisterVectorConverter<std::vector<int>>(); RegisterVectorConverter<std::vector<unsigned>>(); RegisterVectorConverter<std::vector<double>>(); RegisterListConverter<int>(); RegisterListConverter<std::vector<int>>(); RegisterListConverter<std::vector<unsigned int>>(); python::register_exception_translator<IndexErrorException>( &translate_index_error); python::register_exception_translator<ValueErrorException>( &translate_value_error); python::register_exception_translator<KeyErrorException>( &translate_key_error); #if INVARIANT_EXCEPTION_METHOD python::register_exception_translator<Invar::Invariant>( &translate_invariant_error); #endif python::def("_version", _version, "Deprecated, use the constant rdkitVersion instead"); python::scope().attr("rdkitVersion") = RDKit::rdkitVersion; python::scope().attr("boostVersion") = RDKit::boostVersion; python::scope().attr("rdkitBuild") = RDKit::rdkitBuild; python::def("LogToCppStreams", RDLog::InitLogs, "Initialize RDKit logs with C++ streams"); python::def("LogToPythonLogger", LogToPythonLogger, "Initialize RDKit logs with Python's logging module"); python::def("LogToPythonStderr", LogToPythonStderr, "Initialize RDKit logs with Python's stderr stream"); python::def("WrapLogs", WrapLogs, "Tee the RDKit logs to Python's stderr stream"); python::def("EnableLog", EnableLog); python::def("DisableLog", DisableLog); python::def("LogStatus", LogStatus); python::def("LogDebugMsg", LogDebugMsg, "Log a message to the RDKit debug logs"); python::def("LogInfoMsg", LogInfoMsg, "Log a message to the RDKit info logs"); python::def("LogWarningMsg", LogWarningMsg, "Log a message to the RDKit warning logs"); python::def("LogErrorMsg", LogErrorMsg, "Log a message to the RDKit error logs"); python::def("LogMessage", LogMessage, "Log a message to any rdApp.* log"); python::def("AttachFileToLog", AttachFileToLog, "Causes the log to write to a file", (python::arg("spec"), python::arg("filename"), python::arg("delay") = 100)); python::def("SeedRandomNumberGenerator", seedRNG, "Provides a seed to the standard C random number generator\n" "This does not affect pure Python code, but is relevant to some " "of the RDKit C++ components.", (python::arg("seed"))); python_streambuf_wrapper::wrap(); python_ostream_wrapper::wrap(); python::class_<BlockLogs, boost::noncopyable>( "BlockLogs", "Temporarily block logs from outputting while this instance is in scope.", python::init<>()) .def("__enter__", &BlockLogs::enter, python::return_internal_reference<>()) .def("__exit__", &BlockLogs::exit); }
28.798799
80
0.670699
i-tub
15fedd99cf14f5ba20b3ebde86fb4f81c78b372f
3,082
cpp
C++
Magic-Name/main.cpp
KSCreator/General-Programs
b51cb9cc36e6eda72f3b402e278f25b512e9daa2
[ "MIT" ]
null
null
null
Magic-Name/main.cpp
KSCreator/General-Programs
b51cb9cc36e6eda72f3b402e278f25b512e9daa2
[ "MIT" ]
null
null
null
Magic-Name/main.cpp
KSCreator/General-Programs
b51cb9cc36e6eda72f3b402e278f25b512e9daa2
[ "MIT" ]
null
null
null
/* author : Keshav Sahu */ #include <cstdio> #include <cstring> #include <cctype> #include <cstdlib> using namespace std; void print(char c) { if(islower(c)) c = toupper(c); switch(c) { case 'A': printf("ooooo\no o\nooooo\no o\no o\n\n\n"); break; case 'B': printf("oooo \no o\nooooo\no o\noooo \n\n\n"); break; case 'C': printf(" oooo\no \no \no \n oooo\n\n\n"); break; case 'D': printf("oooo \n o o\n o o\n o o\noooo \n\n\n"); break; case 'E': printf("ooooo\no \nooooo\no \nooooo\n\n\n"); break; case 'F': printf("ooooo\no \nooooo\no \no \n\n\n"); break; case 'G': printf("ooooo\no o\no \no ooo\nooo o\n\n\n"); break; case 'H': printf("o o\no o\nooooo\no o\no o\n\n\n"); break; case 'I': printf(" o \n o \n o \n o \n o \n\n\n"); break; case 'J': printf(" oo \n o \n o \n o o \n ooo \n\n\n"); break; case 'K': printf(" o o\n o o \n oo \n o o \n o o\n\n\n"); break; case 'L': printf(" o \n o \n o \n o o\n oooo\n\n\n"); break; case 'M': printf(" o o \no o o\no o o\no o\no o\n\n\n"); break; case 'N': printf("o o\noo o\no o o\no oo\no o\n\n\n"); break; case 'O': printf("ooooo\no o\no o\no o\nooooo\n\n\n"); break; case 'P': printf("ooooo\no o\nooooo\no \no \n\n\n"); break; case 'Q': printf("oooo \no o \no o \noooo \n o\n\n\n"); break; case 'R': printf("ooooo\no o\noooo \no o \no o\n\n\n"); break; case 'S': printf("ooooo\no \nooooo\n o\nooooo\n\n\n"); break; case 'T': printf("ooooo\n o \n o \n o \n o \n\n\n"); break; case 'U': printf("o o\no o\no o\no o\n ooo \n\n\n"); break; case 'V': printf("o o\no o\no o\n o o \n o \n\n\n"); break; case 'W': printf("o o\no o\no o o\no o o\noo oo\n\n\n"); break; case 'X': printf("o o\n o o \n o \n o o \no o\n\n\n"); break; case 'Y': printf("o o\n o o \n o \n o \n o \n\n\n"); break; case 'Z': printf("ooooo\n o \n o \n o \nooooo\n\n\n"); break; case ' ': printf("\n\n\n\n\n\n\n"); break; default: printf("\n not \nsupported\ncharacter\n\n\n\n"); } } void print(char name[],int len) { for (int i = 0; i < len; i++) { print(name[i]); } } int main() { char name[20]; printf("Enter Your Name\n"); scanf("%[^\n]",name); int len = strlen(name); printf("View the magic\n\n\n"); print(name,len); system("pause"); return 0; }
24.656
58
0.41207
KSCreator
15ff7b0f4c71dd0f7362e433c7f149b9b05dbd40
685
cpp
C++
School C++/other2/Test array/Test array.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
School C++/other2/Test array/Test array.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
School C++/other2/Test array/Test array.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
// Test array.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream.h> void main(int argc, char* argv[]) { char account[16]={'5','4','5','8','0','9','8','3','9','3','3','8','3','9','7','6'},chari; int u=0; switch(account[0]){ case '4': chari='V'; break; case '5': chari='M'; break; case '3': if(account[1]=='7') chari='A'; else chari='X'; break; case '6': if(account[1]=='0') { for(int y=2;y<=3;y++) if(account[y]=='1') u++; if(u==2) chari='D'; else chari='X'; } else chari='X'; break; default: { chari='X'; break; } } cout<<account[0]<<" "<<chari<<endl; }
13.979592
90
0.50219
holtsoftware
c600a2b7c9054ffe775bb57ef175a0f3f6e8ae76
11,795
cpp
C++
Src/Celbody/Moon/ELP82.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
1,040
2021-07-27T12:12:06.000Z
2021-08-02T14:24:49.000Z
Src/Celbody/Moon/ELP82.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
20
2021-07-27T12:25:22.000Z
2021-08-02T12:22:19.000Z
Src/Celbody/Moon/ELP82.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
71
2021-07-27T14:19:49.000Z
2021-08-02T05:51:52.000Z
#include <math.h> #include <fstream> #include "OrbiterAPI.h" using namespace std; // #define INCLUDE_TIDAL_PERT // Uncomment this to add higher-order perturbation terms // (tidal, relativistic, solar eccentricity) // Warning: Using this can lead to inconsistencies since these // effects are not currently modelled in Orbiter's dynamic model. // =========================================================== // Global variables // =========================================================== typedef double SEQ3[3]; typedef double SEQ6[6]; static const double cpi = 3.141592653589793; static const double cpi2 = 2.0*cpi; static const double pis2 = cpi/2.0; static const double rad = 648000.0/cpi; static const double deg = cpi/180.0; static const double c1 = 60.0; static const double c2 = 3600.0; static const double ath = 384747.9806743165; static const double a0 = 384747.9806448954; static const double am = 0.074801329518; static const double alpha = 0.002571881335; static const double dtasm = 2.0*alpha/(3.0*am); static const double mjd2000 = 51544.5; // mjd->dj2000 offset static const double sc = 36525.0; static const double precess = 5029.0966/rad; static bool need_terms = true; // need to read terms? static const double def_prec = 1e-5; // default precision static double cur_prec = -1.0; // current precision static double delnu, dele, delg, delnp, delep; static double p1, p2, p3, p4, p5, q1, q2, q3, q4, q5; static double w[3][5], p[8][2], eart[5], peri[5], del[4][5], zeta[2]; static int nterm[3][12], nrang[3][12]; // current length of term sequences static SEQ6 *pc[3] = {0,0,0}; // main term sequences static SEQ3 *per[3] = {0,0,0}; // perturbation term sequences // =========================================================== // ELP82_init () // Set up invariant global parameters for ELP82 solver // =========================================================== void ELP82_init () { // Lunar arguments w[0][0] = (218.0+18.0/c1+59.95571/c2)*deg; w[1][0] = (83.0+21.0/c1+11.67475/c2)*deg; w[2][0] = (125.0+2.0/c1+40.39816/c2)*deg; eart[0] = (100.0+27.0/c1+59.22059/c2)*deg; peri[0] = (102.0+56.0/c1+14.42753/c2)*deg; w[0][1] = 1732559343.73604/rad; w[1][1] = 14643420.2632/rad; w[2][1] = -6967919.3622/rad; eart[1] = 129597742.2758/rad; peri[1] = 1161.2283/rad; w[0][2] = -5.8883/rad; w[1][2] = -38.2776/rad; w[2][2] = 6.3622/rad; eart[2] = -0.0202/rad; peri[2] = 0.5327/rad; w[0][3] = 0.6604e-2/rad; w[1][3] = -0.45047e-1/rad; w[2][3] = 0.7625e-2/rad; eart[3] = 0.9e-5/rad; peri[3] = -0.138e-3/rad; w[0][4] = -0.3169e-4/rad; w[1][4] = 0.21301e-3/rad; w[2][4] = -0.3586e-4/rad; eart[4] = 0.15e-6/rad; peri[4] = 0.0; // Planetary arguments p[0][0] = (252.0+15.0/c1+3.25986/c2)*deg; p[1][0] = (181.0+58.0/c1+47.28305/c2)*deg; p[2][0] = eart[0]; p[3][0] = (355.0+25.0/c1+59.78866/c2)*deg; p[4][0] = (34.0+21.0/c1+5.34212/c2)*deg; p[5][0] = (50.0+4.0/c1+38.89694/c2)*deg; p[6][0] = (314.0+3.0/c1+18.01841/c2)*deg; p[7][0] = (304.0+20.0/c1+55.19575/c2)*deg; p[0][1] = 538101628.68898/rad; p[1][1] = 210664136.43355/rad; p[2][1] = eart[1]; p[3][1] = 68905077.59284/rad; p[4][1] = 10925660.42861/rad; p[5][1] = 4399609.65932/rad; p[6][1] = 1542481.19393/rad; p[7][1] = 786550.32074/rad; // Corrections of the constants (fit to DE200/LE200) delnu = +0.55604/rad/w[0][1]; dele = +0.01789/rad; delg = -0.08066/rad; delnp = -0.06424/rad/w[0][1]; delep = -0.12879/rad; // Delaunay's arguments for (int i = 0; i < 5; i++) { del[0][i] = w[0][i] - eart[i]; del[3][i] = w[0][i] - w[2][i]; del[2][i] = w[0][i] - w[1][i]; del[1][i] = eart[i] - peri[i]; } del[0][0] = del[0][0] + cpi; zeta[0] = w[0][0]; zeta[1] = w[0][1] + precess; // Precession matrix p1 = 0.10180391e-4; p2 = 0.47020439e-6; p3 = -0.5417367e-9; p4 = -0.2507948e-11; p5 = 0.463486e-14; q1 = -0.113469002e-3; q2 = 0.12372674e-6; q3 = 0.1265417e-8; q4 = -0.1371808e-11; q5 = -0.320334e-14; } // =========================================================== // ELP82_exit () // Cleanup procedures // =========================================================== void ELP82_exit () { if (cur_prec >= 0.0) { for (int i = 0; i < 3; i++) { if (pc[i]) { delete []pc[i]; pc[i] = 0; } if (per[i]) { delete []per[i]; per[i] = 0; } } } cur_prec = -1.0; } // =========================================================== // ELP82_read () // Read the perturbation terms from file and store in global // parameters. The number of terms read depends on requested precision. // =========================================================== int ELP82_read (double prec) { // Term structure interfaces typedef struct { int ilu[4]; double coef[7]; } MainBin; typedef struct { int iz; int ilu[4]; double pha, x, per; } FigurBin; typedef struct { short ipla[11]; double pha, x, per; } PlanPerBin; // Check for existing terms if (cur_prec >= 0.0) { if (prec == cur_prec) return 0; // nothing to do for (int i = 0; i < 3; i++) { if (pc[i]) { delete []pc[i]; pc[i] = 0; } // remove existing terms if (per[i]) { delete []per[i]; per[i] = 0; } } } int ific, itab, m, mm, i, im, ir, k, ntot = 0, mtot = 0; double tgv, xx, y, pre[3], zone[6]; // Precision paremeters pre[0] = prec*rad; pre[1] = prec*rad; pre[2] = prec*ath; const char *datf = "Config\\Moon\\Data\\ELP82.dat"; ifstream ifs (datf); // term data stream if (!ifs) { oapiWriteLogError("ELP82: Data file not found: %s", datf); return -1; } // Read terms for main problem for (ific = 0; ific < 3; ific++) { ifs >> m; // number of terms available in sequence MainBin *block = new MainBin[m]; // temporary storage for terms for (ir = mm = 0; ir < m; ir++) { // read terms from file for (i = 0; i < 4; i++) ifs >> block[ir].ilu[i]; for (i = 0; i < 7; i++) ifs >> block[ir].coef[i]; if (fabs(block[ir].coef[0]) >= pre[ific]) mm++; // number of terms used } ntot += mm; mtot += m; if (mm) pc[ific] = new SEQ6[mm]; itab = 0; for (im = ir = 0; im < m; im++) { MainBin &lin = block[im]; xx = lin.coef[0]; if (fabs(xx) < pre[ific]) continue; tgv = lin.coef[1] + dtasm*lin.coef[5]; if (ific == 2) lin.coef[0] -= 2.0*lin.coef[0]*delnu/3.0; xx = lin.coef[0] + tgv*(delnp-am*delnu) + lin.coef[2]*delg + lin.coef[3]*dele + lin.coef[4]*delep; zone[0] = xx; for (k = 0; k <= 4; k++) { y = 0.0; for (i = 0; i < 4; i++) { y += lin.ilu[i]*del[i][k]; } zone[k+1] = y; } if (ific == 2) zone[1] += pis2; for (i = 0; i < 6; i++) pc[ific][ir][i] = zone[i]; ir++; } nterm[ific][0] = ir; nrang[ific][0] = 0; delete []block; } #ifdef INCLUDE_TIDAL_PERT int iv, j; // Read terms for tides, relativity, solar eccentricity (part 1) for (ific = 0; ific < 3; ific++) { iv = ific % 3; ifs >> m; FigurBin *block = new FigurBin[m]; for (ir = mm = 0; ir < m; ir++) { ifs >> block[ir].iz; for (i = 0; i < 4; i++) ifs >> block[ir].ilu[i]; ifs >> block[ir].pha >> block[ir].x >> block[ir].per; if (block[ir].x >= pre[iv]) mm++; } ntot += mm; mtot += m; if (mm) per[ific] = new SEQ3[mm]; itab = (ific/3) + 1; for (im = ir = 0; im < m; im++) { FigurBin &lin = block[im]; xx = lin.x; if (lin.x < pre[iv]) continue; zone[0] = xx; for (k = 0; k <= 1; k++) { y = (k ? lin.pha*deg : 0.0); y += lin.iz*zeta[k]; for (i = 0; i < 4; i++) y += lin.ilu[i]*del[i][k]; zone[k+1] = y; } j = nrang[iv][itab-1] + ir; for (i = 0; i < 3; i++) per[iv][i][j] = zone[i]; ir++; } nterm[iv][itab] = ir; nrang[iv][itab] = nrang[iv][itab-1] + nterm[iv][itab]; delete []block; } #endif // INCLUDE_TIDAL_PERT // Add: PlanetaryPerturbations // Add: FiguresTides oapiWriteLogV("ELP82: Precision %0.1le, Terms %d/%d", prec, ntot, mtot); need_terms = false; cur_prec = prec; return 0; } // =========================================================== // ELP82 () // Calculate lunar ephemeris using ELP2000-82 perturbation solutions // MS modifications: // - Time input is MJD instead of JD // - Added time derivatives (output in r[3] to r[5]) // =========================================================== int ELP82 (double mjd, double *r) { int k, iv, nt; double t[5]; double x, y, x1, x2, x3, pw, qw, ra, pwqw, pw2, qw2; double x_dot, y_dot, x1_dot, x2_dot, x3_dot, pw_dot, qw_dot; double ra_dot, pwqw_dot, pw2_dot, qw2_dot; double cosr0, sinr0, cosr1, sinr1; // Initialisation if (need_terms) ELP82_read (def_prec); // substitution of time t[0] = 1.0; t[1] = (mjd-mjd2000)/sc; t[2] = t[1]*t[1]; t[3] = t[2]*t[1]; t[4] = t[3]*t[1]; for (iv = 0; iv < 3; iv++) { r[iv] = r[iv+3] = 0.0; SEQ6 *pciv = pc[iv]; // main sequence (itab=0) for (nt = 0; nt < nterm[iv][0]; nt++) { x = pciv[nt][0]; x_dot = 0.0; y = pciv[nt][1]; y_dot = 0.0; for (k = 1; k <= 4; k++) { y += pciv[nt][k+1] * t[k]; y_dot += pciv[nt][k+1] * t[k-1] * k; } r[iv] += x*sin(y); r[iv+3] += x_dot*sin(y) + x*cos(y)*y_dot; } #ifdef INCLUDE_TIDAL_PERT int itab, j; // perturbation sequences (itab>0) for (itab = 1; itab < 2/*12*/; itab++) { for (nt = 0; nt < nterm[iv][itab]; nt++) { j = nrang[iv][itab-1] + nt; x = per[iv][0][j]; y = per[iv][1][j] + per[iv][2][j] * t[1]; if (itab == 2 || itab == 4 || itab == 6 || itab == 8) { x_dot = x; x *= t[1]; } if (itab == 11) { x_dot = x * t[1] * 2.0; x *= t[2]; } r[iv] += x*sin(y); r[iv+3] += x_dot*sin(y) + x*cos(y)*y_dot; } } #endif // INCLUDE_TIDAL_PERT } // Change of coordinates r[0] = r[0]/rad + w[0][0] + w[0][1]*t[1] + w[0][2]*t[2] + w[0][3]*t[3] + w[0][4]*t[4]; r[3] = r[3]/rad + w[0][1] + 2*w[0][2]*t[1] + 3*w[0][3]*t[2] + 4*w[0][4]*t[3]; r[1] = r[1]/rad; r[4] = r[4]/rad; r[2] = r[2]*a0/ath; r[5] = r[5]*a0/ath; cosr0 = cos(r[0]), sinr0 = sin(r[0]); cosr1 = cos(r[1]), sinr1 = sin(r[1]); x1 = r[2]*cosr1; x1_dot = r[5]*cosr1 - r[2]*sinr1*r[4]; x2 = x1*sinr0; x2_dot = x1_dot*sinr0 + x1*cosr0*r[3]; x1_dot = x1_dot*cosr0 - x1*sinr0*r[3]; x1 = x1*cosr0; x3 = r[2]*sinr1; x3_dot = r[5]*sinr1 + r[2]*cosr1*r[4]; pw = (p1+p2*t[1]+p3*t[2]+p4*t[3]+p5*t[4])*t[1]; pw_dot = p1 + 2*p2*t[1] + 3*p3*t[2] + 4*p4*t[3] + 5*p5*t[4]; qw = (q1+q2*t[1]+q3*t[2]+q4*t[3]+q5*t[4])*t[1]; qw_dot = q1 + 2*q2*t[1] + 3*q3*t[2] + 4*q4*t[3] + 5*q5*t[4]; ra = 2.0*sqrt(1-pw*pw-qw*qw); ra_dot = -4.0*(pw+qw)/ra; pwqw = 2.0*pw*qw; pwqw_dot = 2.0*(pw_dot*qw + pw*qw_dot); pw2 = 1-2.0*pw*pw; pw2_dot = -4.0*pw; qw2 = 1-2.0*qw*qw; qw2_dot = -4.0*qw; pw = pw*ra; pw_dot = pw_dot*ra + pw*ra_dot; qw = qw*ra; qw_dot = qw_dot*ra + qw*ra_dot; // at this point we swap y and z components to conform with orbiter convention // r[1] <-> r[2] and r[4] <-> r[5] r[0] = pw2*x1+pwqw*x2+pw*x3; r[3] = pw2_dot*x1 + pw2*x1_dot + pwqw_dot*x2 + pwqw*x2_dot + pw_dot*x3 + pw*x3_dot; r[2] = pwqw*x1+qw2*x2-qw*x3; r[5] = pwqw_dot*x1 + pwqw*x1_dot + qw2_dot*x2 + qw2*x2_dot - qw_dot*x3 - qw*x3_dot; r[1] = -pw*x1+qw*x2+(pw2+qw2-1)*x3; r[4] = -pw_dot*x1 - pw*x1_dot + qw_dot*x2 + qw*x2_dot + (pw2_dot+qw2_dot)*x3 + (pw2+qw2-1)*x3_dot; // ========= End of ELP82 code ========= // Below is conversion to Orbiter format // convert to m and m/s static double pscale = 1e3; static double vscale = 1e3/(86400.0*sc); r[0] *= pscale; r[1] *= pscale; r[2] *= pscale; r[3] *= vscale; r[4] *= vscale; r[5] *= vscale; return 0; }
27.303241
99
0.519118
Ybalrid
c60449d7a65fc4646ff830bb201ff8f7875eea77
2,357
cpp
C++
MORE CODING PLATFORMS/SPOJ/cot.cpp
Autoratch/CodeChef
6937e6b442e19df90a65f772939db9ab1a07a1b3
[ "Apache-2.0" ]
null
null
null
MORE CODING PLATFORMS/SPOJ/cot.cpp
Autoratch/CodeChef
6937e6b442e19df90a65f772939db9ab1a07a1b3
[ "Apache-2.0" ]
null
null
null
MORE CODING PLATFORMS/SPOJ/cot.cpp
Autoratch/CodeChef
6937e6b442e19df90a65f772939db9ab1a07a1b3
[ "Apache-2.0" ]
null
null
null
// https://www.spoj.com/problems/COT/ #include <bits/stdc++.h> using namespace std; const int N = 1.2e5; const int K = 20; int n,q; pair<int,int> res[N]; int id[N]; vector<int> adj[N]; struct node { int val,left,right; }tree[N*50]; int dp[K][N],lv[N]; int root[N],cnt; int clone(int idx){ tree[++cnt] = tree[idx]; return cnt; } void build(int l,int r,int idx) { cnt = max(cnt,idx); if(l==r) return; int m = (l+r)/2; tree[idx] = {0,idx*2,idx*2+1}; build(l,m,idx*2),build(m+1,r,idx*2+1); } int update(int l,int r,int idx,int x) { int now = clone(idx); tree[now].val++; if(l==r) return now; int m = (l+r)/2; if(x<=m) tree[now].left = update(l,m,tree[now].left,x); else tree[now].right = update(m+1,r,tree[now].right,x); return now; } int read(int l,int r,int aidx,int bidx,int pidx,int uidx,int k) { if(l==r) return l; int m = (l+r)/2; int tmp = tree[tree[aidx].left].val+tree[tree[bidx].left].val-tree[tree[pidx].left].val-tree[tree[uidx].left].val; if(k<=tmp) return read(l,m,tree[aidx].left,tree[bidx].left,tree[pidx].left,tree[uidx].left,k); else return read(m+1,r,tree[aidx].right,tree[bidx].right,tree[pidx].right,tree[uidx].right,k-tmp); } void dfs(int u,int p,int l) { root[u] = update(1,n,root[p],id[u]); dp[0][u] = p,lv[u] = l; for(int v : adj[u]) if(v!=p) dfs(v,u,l+1); } int lca(int a,int b) { if(lv[a]<lv[b]) swap(a,b); for(int i = K-1;i >= 0;i--) if(lv[dp[i][a]]>=lv[b]) a = dp[i][a]; if(a==b) return a; for(int i = K-1;i >= 0;i--) if(dp[i][a]!=dp[i][b]) a = dp[i][a],b = dp[i][b]; return dp[0][a]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> q; for(int i = 1;i <= n;i++) cin >> res[i].first,res[i].second = i; for(int i = 0;i < n-1;i++) { int a,b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } sort(res+1,res+n+1); for(int i = 1;i <= n;i++) id[res[i].second] = i; build(1,n,1); root[0] = 1; dfs(1,0,1); for(int i = 1;i < K;i++) for(int j = 1;j <= n;j++) dp[i][j] = dp[i-1][dp[i-1][j]]; while(q--) { int a,b,k; cin >> a >> b >> k; int l = lca(a,b); int tmp = read(1,n,root[a],root[b],root[l],root[dp[0][l]],k); cout << res[tmp].first << '\n'; } }
24.552083
119
0.518456
Autoratch
c60c1d964a15e2afaa937343b7ada13a270e7f60
2,245
cpp
C++
src/test_poly.cpp
willyii/PolynomialRootFinding
18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f
[ "MIT" ]
null
null
null
src/test_poly.cpp
willyii/PolynomialRootFinding
18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f
[ "MIT" ]
1
2021-03-13T00:53:54.000Z
2021-03-13T00:53:54.000Z
src/test_poly.cpp
willyii/PolynomialRootFinding
18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f
[ "MIT" ]
1
2021-01-13T12:54:48.000Z
2021-01-13T12:54:48.000Z
// ---------------------------------------------------------------------------- // // FILENAME: test_poly.h // // DESCRIPTION: // This file used to write some test function in poly class to check if the // some functions works good // // AUTHOR: Xinlong Yi // // ---------------------------------------------------------------------------- #include "poly.h" #include <iostream> #include <stdio.h> int main() { // Test Poly Class Poly<4> p; std::cout << "Test: default polynomial " << p << std::endl; double coef1[3] = {1, -2, 1}; Poly<3> p1(coef1, 3); std::cout << "Test: polynomial assign with coef " << p1 << std::endl; Poly<4> p2(p1); std::cout << "Test: polynomial assign with other poly" << p2 << std::endl; Poly<4> p3 = p1; std::cout << "Test: polynomial copy with other poly" << p3 << std::endl; std::cout << "Test: contain zero 4 " << p3.containZero(4) << std::endl; std::cout << "Test: degree of p3 " << p3.get_degree() << std::endl; auto v(p3.ValueAt(0)); std::cout << "Test: p3 value at 0 from " << v.lower() << " to " << v.upper() << std::endl; v = (p3.DerivativeAt(0)); std::cout << "Test: p3 derivate at 0 from " << v.lower() << " to " << v.upper() << std::endl; auto p3d(p3.Derivative()); std::cout << "Test: derative of p3 " << p3d << " degree: " << p3d.get_degree() << std::endl; auto ld(p3.lead_coef()); std::cout << "Test: p3 lead coef from " << ld.lower() << " to " << ld.upper() << std::endl; std::cout << "Test: sign change of p3 " << p3.SignChange() << std::endl; p3 += p3; std::cout << "Test: p3 += p3 " << p3 << std::endl; p3 -= p2; std::cout << "Test: p3 -= p2 " << p3 << std::endl; p3 *= 3; std::cout << "Test: p3 *= 3 " << p3 << std::endl; p3 /= 3; std::cout << "Test: p3 /= 3 " << p3 << std::endl; auto p4 = p3 + p3; std::cout << "Test: p3 + p3 " << p4 << std::endl; auto p5 = p4 - p3; std::cout << "Test: p4 - p3 " << p5 << std::endl; auto p6 = p3 * p3; std::cout << "Test: p3 * p3 " << p6 << std::endl; double coef7[2] = {-1, 1}; Poly<2> tmp(coef7, 2); auto p7 = Quotient(p2, tmp); std::cout << "Test: p2 / tmp: quotient " << p7 << std::endl; return 0; }
27.048193
80
0.489532
willyii
c60c8bff9e1ff6d3b43ff765aa2a409a62c1a729
1,634
cpp
C++
JAERO/zmq_audiosender.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
152
2015-12-02T01:38:42.000Z
2022-03-29T10:41:37.000Z
JAERO/zmq_audiosender.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
59
2015-12-02T02:11:24.000Z
2022-03-21T02:48:11.000Z
JAERO/zmq_audiosender.cpp
Roethenbach/JAERO
753a4409507a356489f3635b93dc16955c8cf01a
[ "MIT" ]
38
2015-12-07T16:24:03.000Z
2021-12-25T15:44:27.000Z
#include "zmq_audiosender.h" #include "zmq.h" #include <QDebug> ZMQAudioSender::ZMQAudioSender(QObject *parent) : QObject(parent) { zmqStatus = -1; context = zmq_ctx_new(); publisher = zmq_socket(context, ZMQ_PUB); int keepalive = 1; int keepalivecnt = 10; int keepaliveidle = 1; int keepaliveintrv = 1; zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE,(void*)&keepalive, sizeof(ZMQ_TCP_KEEPALIVE)); zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE_CNT,(void*)&keepalivecnt,sizeof(ZMQ_TCP_KEEPALIVE_CNT)); zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE_IDLE,(void*)&keepaliveidle,sizeof(ZMQ_TCP_KEEPALIVE_IDLE)); zmq_setsockopt(publisher, ZMQ_TCP_KEEPALIVE_INTVL,(void*)&keepaliveintrv,sizeof(ZMQ_TCP_KEEPALIVE_INTVL)); } void ZMQAudioSender::Start(QString &address, QString &topic) { Stop(); // bind socket this->topic=topic; connected_url=address.toUtf8().constData(); zmqStatus=zmq_bind(publisher, connected_url.c_str() ); } void ZMQAudioSender::Stop() { if(zmqStatus == 0) { zmqStatus = zmq_disconnect(publisher, connected_url.c_str()); } } void ZMQAudioSender::Voiceslot(QByteArray &data, QString &hex) { std::string topic_text = topic.toUtf8().constData(); zmq_setsockopt(publisher, ZMQ_IDENTITY, topic_text.c_str(), topic_text.length()); if(data.length()!=0) { zmq_send(publisher, topic_text.c_str(), topic_text.length(), ZMQ_SNDMORE); zmq_send(publisher, data.data(), data.length(), 0 ); } zmq_send(publisher, topic_text.c_str(), 5, ZMQ_SNDMORE); zmq_send(publisher, hex.toStdString().c_str(), 6, 0 ); }
31.423077
110
0.709302
Roethenbach
c60f071cbfa54737ee5662bf2351e0ff90b52ceb
57,305
cpp
C++
net/mmc/common/basehand.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/mmc/common/basehand.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/mmc/common/basehand.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**********************************************************************/ /** Microsoft Windows/NT **/ /** Copyright(c) Microsoft Corporation, 1997 - 1999 **/ /**********************************************************************/ /* node.cpp Root node information (the root node is not displayed in the MMC framework but contains information such as all of the subnodes in this snapin). FILE HISTORY: */ #include "stdafx.h" #include "basehand.h" #include "util.h" DEBUG_DECLARE_INSTANCE_COUNTER(CBaseHandler); /*!-------------------------------------------------------------------------- CBaseHandler::CBaseHandler - Author: KennT ---------------------------------------------------------------------------*/ CBaseHandler::CBaseHandler(ITFSComponentData *pTFSCompData) : m_cRef(1) { DEBUG_INCREMENT_INSTANCE_COUNTER(CBaseHandler); m_spTFSCompData.Set(pTFSCompData); pTFSCompData->GetNodeMgr(&m_spNodeMgr); } CBaseHandler::~CBaseHandler() { DEBUG_DECREMENT_INSTANCE_COUNTER(CBaseHandler); } IMPLEMENT_ADDREF_RELEASE(CBaseHandler) STDMETHODIMP CBaseHandler::QueryInterface(REFIID riid, LPVOID *ppv) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // Is the pointer bad? if (ppv == NULL) return E_INVALIDARG; // Place NULL in *ppv in case of failure *ppv = NULL; // This is the non-delegating IUnknown implementation if (riid == IID_IUnknown) *ppv = (LPVOID) this; else if (riid == IID_ITFSNodeHandler) *ppv = (ITFSNodeHandler *) this; // If we're going to return an interface, AddRef it first if (*ppv) { ((LPUNKNOWN) *ppv)->AddRef(); return hrOK; } else return E_NOINTERFACE; } STDMETHODIMP CBaseHandler::DestroyHandler(ITFSNode *pNode) { return hrOK; } /*!-------------------------------------------------------------------------- CBaseHandler::Notify Implementation of ITFSNodeHandler::Notify Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::Notify(ITFSNode *pNode, IDataObject *pDataObject, DWORD dwType, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM lParam) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; switch (event) { case MMCN_PROPERTY_CHANGE: hr = OnPropertyChange(pNode, pDataObject, dwType, arg, lParam); break; case MMCN_EXPAND: { // when MMC calls us to expand the root node, it // hands us the scopeID. We need to save it off here. SPITFSNode spRootNode; m_spNodeMgr->GetRootNode(&spRootNode); if (pNode == spRootNode) pNode->SetData(TFS_DATA_SCOPEID, lParam); // now walk the list of children for this node and // show them (they may have been added to the internal tree, // but not the UI before this node was expanded SPITFSNodeEnum spNodeEnum; ITFSNode * pCurrentNode; ULONG nNumReturned = 0; pNode->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); while (nNumReturned) { if (pCurrentNode->IsVisible() && !pCurrentNode->IsInUI()) pCurrentNode->Show(); pCurrentNode->Release(); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); } // Now call the notification handler for specific functionality hr = OnExpand(pNode, pDataObject, dwType, arg, lParam); } break; case MMCN_DELETE: hr = OnDelete(pNode, arg, lParam); break; case MMCN_RENAME: hr = OnRename(pNode, arg, lParam); break; /* case MMCN_CONTEXTMENU: hr = OnContextMenu(pNode, arg, lParam); break; */ case MMCN_REMOVE_CHILDREN: hr = OnRemoveChildren(pNode, pDataObject, arg, lParam); break; case MMCN_EXPANDSYNC: hr = OnExpandSync(pNode, pDataObject, arg, lParam); break; case MMCN_BTN_CLICK: switch (lParam) { case MMC_VERB_COPY: hr = OnVerbCopy(pNode, arg, lParam); break; case MMC_VERB_PASTE: hr = OnVerbPaste(pNode, arg, lParam); break; case MMC_VERB_DELETE: hr = OnVerbDelete(pNode, arg, lParam); break; case MMC_VERB_PROPERTIES: hr = OnVerbProperties(pNode, arg, lParam); break; case MMC_VERB_RENAME: hr = OnVerbRename(pNode, arg, lParam); break; case MMC_VERB_REFRESH: hr = OnVerbRefresh(pNode, arg, lParam); break; case MMC_VERB_PRINT: hr = OnVerbPrint(pNode, arg, lParam); break; }; break; case MMCN_RESTORE_VIEW: hr = OnRestoreView(pNode, arg, lParam); break; default: Panic1("Uknown event in CBaseHandler::Notify! 0x%x", event); // Handle new messages hr = S_FALSE; break; } return hr; } /*!-------------------------------------------------------------------------- CBaseHandler::CreatePropertyPages Implementation of ITFSNodeHandler::CreatePropertyPages Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::CreatePropertyPages(ITFSNode *pNode, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle, DWORD dwType) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; if (dwType & TFS_COMPDATA_CREATE) { // This is the case where we are asked to bring up property // pages when the user is adding a new snapin. These calls // are forwarded to the root node to handle. SPITFSNode spRootNode; SPITFSNodeHandler spHandler; // get the root node m_spNodeMgr->GetRootNode(&spRootNode); spRootNode->GetHandler(&spHandler); spHandler->CreatePropertyPages(spRootNode, lpProvider, pDataObject, handle, dwType); } return hr; } /*!-------------------------------------------------------------------------- CBaseHandler::HasPropertyPages Implementation of ITFSNodeHandler::HasPropertyPages Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::HasPropertyPages(ITFSNode *pNode, LPDATAOBJECT pDataObject, DATA_OBJECT_TYPES type, DWORD dwType) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; if (dwType & TFS_COMPDATA_CREATE) { // This is the case where we are asked to bring up property // pages when the user is adding a new snapin. These calls // are forwarded to the root node to handle. SPITFSNode spRootNode; SPITFSNodeHandler spHandler; // get the root node m_spNodeMgr->GetRootNode(&spRootNode); spRootNode->GetHandler(&spHandler); hr = spHandler->HasPropertyPages(spRootNode, pDataObject, type, dwType); } else { // we have no property pages in the normal case hr = S_FALSE; } return hr; } /*!-------------------------------------------------------------------------- CBaseHandler::OnAddMenuItems Implementation of ITFSNodeHandler::OnAddMenuItems Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::OnAddMenuItems(ITFSNode *pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long *pInsertionAllowed) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseHandler::OnCommand Implementation of ITFSNodeHandler::OnCommand Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::OnCommand(ITFSNode *pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseHandler::GetString Implementation of ITFSNodeHandler::GetString Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP_(LPCTSTR)CBaseHandler::GetString(ITFSNode *pNode, int nCol) { return _T("Foo"); } /*!-------------------------------------------------------------------------- CBaseHandler::UserNotify Implememntation of ITFSNodeHandler::UserNotify Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::UserNotify(ITFSNode *pNode, LPARAM dwParam1, LPARAM dwParam2) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseHandler::OnCreateDataObject Implementation of ITFSNodeHandler::OnCreateDataObject Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::OnCreateDataObject(MMC_COOKIE cookie, DATA_OBJECT_TYPES type, IDataObject **ppDataObject) { // this relies on the ComponentData to do this work return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseHandler::CreateNodeId2 Implementation of ITFSNodeHandler::CreateNodeId2 Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseHandler::CreateNodeId2(ITFSNode * pNode, BSTR * pbstrId, DWORD * pdwFlags) { HRESULT hr = S_FALSE; CString strId; COM_PROTECT_TRY { if (pbstrId == NULL) return hr; // call the handler function to get the data hr = OnCreateNodeId2(pNode, strId, pdwFlags); if (SUCCEEDED(hr) && hr != S_FALSE) { *pbstrId = ::SysAllocString((LPOLESTR) (LPCTSTR) strId); } } COM_PROTECT_CATCH return hr; } /*--------------------------------------------------------------------------- CBaseHandler Notifications ---------------------------------------------------------------------------*/ HRESULT CBaseHandler::OnPropertyChange(ITFSNode *pNode, LPDATAOBJECT pDataobject, DWORD dwType, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_PROPERTY_CHANGE) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnDelete(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_DELETE) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnRename(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_RENAME) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnExpand(ITFSNode *pNode, LPDATAOBJECT pDataObject, DWORD dwType, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_EXPAND) received\n"); return hrOK; } HRESULT CBaseHandler::OnRemoveChildren(ITFSNode *pNode, LPDATAOBJECT pDataObject, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_REMOVECHILDREN) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnExpandSync(ITFSNode *pNode, LPDATAOBJECT pDataObject, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_EXPANDSYNC) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnContextMenu(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_CONTEXTMENU) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbCopy(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_COPY) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbPaste(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_PASTE) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbDelete(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_DELETE) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbProperties(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_PROPERTIES) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbRename(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_RENAME) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbRefresh(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_REFRESH) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnVerbPrint(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_VERB_PRINT) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnRestoreView(ITFSNode *pNode, LPARAM arg, LPARAM lParam) { Trace0("IComponentData::Notify(MMCN_RESTORE_VIEW) received\n"); return S_FALSE; } HRESULT CBaseHandler::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * pdwFlags) { return S_FALSE; } DEBUG_DECLARE_INSTANCE_COUNTER(CBaseResultHandler); /*--------------------------------------------------------------------------- CBaseResultHandler implementation ---------------------------------------------------------------------------*/ CBaseResultHandler::CBaseResultHandler(ITFSComponentData *pTFSCompData) : m_cRef(1) { DEBUG_INCREMENT_INSTANCE_COUNTER(CBaseResultHandler); m_spTFSComponentData.Set(pTFSCompData); pTFSCompData->GetNodeMgr(&m_spResultNodeMgr); m_nColumnFormat = LVCFMT_LEFT; // default column alignment m_pColumnStringIDs = NULL; m_pColumnWidths = NULL; m_fMessageView = FALSE; } CBaseResultHandler::~CBaseResultHandler() { DEBUG_DECREMENT_INSTANCE_COUNTER(CBaseResultHandler); } IMPLEMENT_ADDREF_RELEASE(CBaseResultHandler) STDMETHODIMP CBaseResultHandler::QueryInterface(REFIID riid, LPVOID *ppv) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // Is the pointer bad? if (ppv == NULL) return E_INVALIDARG; // Place NULL in *ppv in case of failure *ppv = NULL; // This is the non-delegating IUnknown implementation if (riid == IID_IUnknown) *ppv = (LPVOID) this; else if (riid == IID_ITFSResultHandler) *ppv = (ITFSResultHandler *) this; // If we're going to return an interface, AddRef it first if (*ppv) { ((LPUNKNOWN) *ppv)->AddRef(); return hrOK; } else return E_NOINTERFACE; } STDMETHODIMP CBaseResultHandler::DestroyResultHandler(MMC_COOKIE cookie) { return hrOK; } /*!-------------------------------------------------------------------------- CBaseResultHandler::Notify Implementation of ITFSResultHandler::Notify Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::Notify ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPDATAOBJECT pDataObject, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM param ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = S_OK; pComponent->SetCurrentDataObject(pDataObject); COM_PROTECT_TRY { switch(event) { case MMCN_PROPERTY_CHANGE: hr = OnResultPropertyChange(pComponent, pDataObject, cookie, arg, param); break; case MMCN_ACTIVATE: hr = OnResultActivate(pComponent, cookie, arg, param); break; case MMCN_CLICK: hr = OnResultItemClkOrDblClk(pComponent, cookie, arg, param, FALSE); break; case MMCN_COLUMN_CLICK: hr = OnResultColumnClick(pComponent, arg, (BOOL)param); break; case MMCN_COLUMNS_CHANGED: hr = OnResultColumnsChanged(pComponent, pDataObject, (MMC_VISIBLE_COLUMNS *) param); break; case MMCN_DBLCLICK: hr = OnResultItemClkOrDblClk(pComponent, cookie, arg, param, TRUE); break; case MMCN_SHOW: { CWaitCursor wait; hr = OnResultShow(pComponent, cookie, arg, param); } break; case MMCN_SELECT: hr = OnResultSelect(pComponent, pDataObject, cookie, arg, param); break; case MMCN_INITOCX: hr = OnResultInitOcx(pComponent, pDataObject, cookie, arg, param); break; case MMCN_MINIMIZED: hr = OnResultMinimize(pComponent, cookie, arg, param); break; case MMCN_DELETE: hr = OnResultDelete(pComponent, pDataObject, cookie, arg, param); break; case MMCN_RENAME: hr = OnResultRename(pComponent, pDataObject, cookie, arg, param); break; case MMCN_REFRESH: hr = OnResultRefresh(pComponent, pDataObject, cookie, arg, param); break; case MMCN_CONTEXTHELP: hr = OnResultContextHelp(pComponent, pDataObject, cookie, arg, param); break; case MMCN_QUERY_PASTE: hr = OnResultQueryPaste(pComponent, pDataObject, cookie, arg, param); break; case MMCN_BTN_CLICK: switch (param) { case MMC_VERB_COPY: OnResultVerbCopy(pComponent, cookie, arg, param); break; case MMC_VERB_PASTE: OnResultVerbPaste(pComponent, cookie, arg, param); break; case MMC_VERB_DELETE: OnResultVerbDelete(pComponent, cookie, arg, param); break; case MMC_VERB_PROPERTIES: OnResultVerbProperties(pComponent, cookie, arg, param); break; case MMC_VERB_RENAME: OnResultVerbRename(pComponent, cookie, arg, param); break; case MMC_VERB_REFRESH: OnResultVerbRefresh(pComponent, cookie, arg, param); break; case MMC_VERB_PRINT: OnResultVerbPrint(pComponent, cookie, arg, param); break; default: break; } break; case MMCN_RESTORE_VIEW: hr = OnResultRestoreView(pComponent, cookie, arg, param); break; // Note - Future expansion of notify types possible default: Panic1("Uknown event in CBaseResultHandler::Notify! 0x%x", event); // Handle new messages hr = S_FALSE; break; } } COM_PROTECT_CATCH pComponent->SetCurrentDataObject(NULL); return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnUpdateView Implementation of ITFSResultHandler::UpdateView Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::UpdateView ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, LPARAM data, LPARAM hint ) { return OnResultUpdateView(pComponent, pDataObject, data, hint); } /*!-------------------------------------------------------------------------- CBaseResultHandler::GetString Implementation of ITFSResultHandler::GetString Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP_(LPCTSTR) CBaseResultHandler::GetString ( ITFSComponent * pComponent, MMC_COOKIE cookie, int nCol ) { return NULL; } /*!-------------------------------------------------------------------------- CBaseResultHandler::CompareItems Implementation of ITFSResultHandler::CompareItems Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) CBaseResultHandler::CompareItems ( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol ) { return S_FALSE; } STDMETHODIMP_(int) CBaseResultHandler::CompareItems ( ITFSComponent *pComponent, RDCOMPARE *prdc ) { // See if IResultCompare is implemented and use it. return CompareItems( pComponent, prdc->prdch1->cookie, prdc->prdch2->cookie, prdc->nColumn ); } // CBaseResultHandler::CompareItems() /*!-------------------------------------------------------------------------- CBaseResultHandler::FindItem called when the Virutal listbox needs to find an item. Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::FindItem ( LPRESULTFINDINFO pFindInfo, int * pnFoundIndex ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::CacheHint called when the virtual listbox has hint information that we can pre-load. The hint is not a guaruntee that the items will be used or that items outside this range will be used. Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::CacheHint ( int nStartIndex, int nEndIndex ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::SortItems called when the Virutal listbox data needs to be sorted Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::SortItems ( int nColumn, DWORD dwSortOptions, LPARAM lUserParam ) { return S_FALSE; } // task pad functions /*!-------------------------------------------------------------------------- CBaseResultHandler::TaskPadNotify - Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::TaskPadNotify ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPDATAOBJECT pDataObject, VARIANT * arg, VARIANT * param ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::EnumTasks - Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::EnumTasks ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPDATAOBJECT pDataObject, LPOLESTR pszTaskGroup, IEnumTASK ** ppEnumTask ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::TaskPadGetTitle - Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::TaskPadGetTitle ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR pszGroup, LPOLESTR * ppszTitle ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::TaskPadGetBackground - Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::TaskPadGetBackground ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR pszGroup, MMC_TASK_DISPLAY_OBJECT * pTDO ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::TaskPadGetDescriptiveText - Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::TaskPadGetDescriptiveText ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR pszGroup, LPOLESTR * pszDescriptiveText ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::HasPropertyPages Implementation of ITFSResultHandler::HasPropertyPages Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::HasPropertyPages ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPDATAOBJECT pDataObject ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::CreatePropertyPages Implementation of ITFSResultHandler::CreatePropertyPages Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::CreatePropertyPages ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::AddMenuItems Implementation of ITFSResultHandler::AddMenuItems Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::AddMenuItems ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPDATAOBJECT pDataObject, LPCONTEXTMENUCALLBACK pContextMenuCallback, long * pInsertionAllowed ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::Command Implementation of ITFSResultHandler::Command Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::Command ( ITFSComponent * pComponent, MMC_COOKIE cookie, int nCommandID, LPDATAOBJECT pDataObject ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnCreateControlbars Implementation of ITFSResultHandler::OnCreateControlbars Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::OnCreateControlbars ( ITFSComponent * pComponent, LPCONTROLBAR pControlBar ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::ControlbarNotify Implementation of ITFSResultHandler::ControlbarNotify Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::ControlbarNotify ( ITFSComponent * pComponent, MMC_NOTIFY_TYPE event, LPARAM arg, LPARAM param ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::UserResultNotify Implememntation of ITFSNodeHandler::UserResultNotify Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::UserResultNotify ( ITFSNode * pNode, LPARAM dwParam1, LPARAM dwParam2 ) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnCreateDataObject - Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CBaseResultHandler::OnCreateDataObject(ITFSComponent *pComponent, MMC_COOKIE cookie, DATA_OBJECT_TYPES type, IDataObject **ppDataObject) { // this relies on the ComponentData to do this work return S_FALSE; } /*--------------------------------------------------------------------------- CBaseResultHandler Notifications ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultPropertyChange(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param) { Trace0("IComponent::Notify(MMCN_PROPERTY_CHANGE) received\n"); return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultUpdateView Implementation of ITFSResultHandler::OnResultUpdateView Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultUpdateView ( ITFSComponent *pComponent, LPDATAOBJECT pDataObject, LPARAM data, LPARAM hint ) { SPITFSNode spSelectedNode; pComponent->GetSelectedNode(&spSelectedNode); if (hint == RESULT_PANE_DELETE_ALL) { if (spSelectedNode == NULL) return S_OK; // no selection for our IComponentData // // data contains the container whose result pane has to be refreshed // ITFSNode * pNode = reinterpret_cast<ITFSNode *>(data); Assert(pNode != NULL); // // do it only if selected, if not, reselecting will do a delete/enumeration // if (spSelectedNode == pNode && !m_fMessageView) { SPIResultData spResultData; pComponent->GetResultData(&spResultData); Assert(spResultData != NULL); spResultData->DeleteAllRsltItems(); } } else if (hint == RESULT_PANE_ADD_ALL) { if (spSelectedNode == NULL) return S_OK; // no selection for our IComponentData // // data contains the container whose result pane has to be refreshed // ITFSNode * pNode = reinterpret_cast<ITFSNode *>(data); Assert(pNode != NULL); // // do it only if selected, if not, reselecting will do a delete/enumeration // if (spSelectedNode == pNode) { SPIResultData spResultData; pComponent->GetResultData(&spResultData); Assert(spResultData != NULL); // // update all the nodes in the result pane // SPITFSNodeEnum spNodeEnum; ITFSNode * pCurrentNode; ULONG nNumReturned = 0; pNode->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); while (nNumReturned) { // All containers go into the scope pane and automatically get // put into the result pane for us by the MMC // if (!pCurrentNode->IsContainer()) { AddResultPaneItem(pComponent, pCurrentNode); } pCurrentNode->Release(); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); } } } else if (hint == RESULT_PANE_REPAINT) { if (spSelectedNode == NULL) return S_OK; // no selection for our IComponentData // // data contains the container whose result pane has to be refreshed // ITFSNode * pNode = reinterpret_cast<ITFSNode *>(data); //if (pNode == NULL) // pContainer = m_pSelectedNode; // passing NULL means apply to the current selection // // update all the nodes in the result pane // SPITFSNodeEnum spNodeEnum; ITFSNode * pCurrentNode; ULONG nNumReturned = 0; pNode->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); while (nNumReturned) { // All containers go into the scope pane and automatically get // put into the result pane for us by the MMC // if (!pCurrentNode->IsContainer()) { ChangeResultPaneItem(pComponent, pCurrentNode, RESULT_PANE_CHANGE_ITEM); } pCurrentNode->Release(); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); } } else if ( (hint == RESULT_PANE_ADD_ITEM) || (hint == RESULT_PANE_DELETE_ITEM) || (hint & RESULT_PANE_CHANGE_ITEM)) { ITFSNode * pNode = reinterpret_cast<ITFSNode *>(data); Assert(pNode != NULL); // // consider only if the parent is selected, otherwise will enumerate later when selected // SPITFSNode spParentNode; pNode->GetParent(&spParentNode); if (spSelectedNode == spParentNode) { if (hint & RESULT_PANE_CHANGE_ITEM) { ChangeResultPaneItem(pComponent, pNode, hint); } else if ( hint == RESULT_PANE_ADD_ITEM) { AddResultPaneItem(pComponent, pNode); } else if ( hint == RESULT_PANE_DELETE_ITEM) { DeleteResultPaneItem(pComponent, pNode); } } } else if ( hint == RESULT_PANE_SET_VIRTUAL_LB_SIZE ) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); if (pNode == spSelectedNode) { SetVirtualLbSize(pComponent, data); } } else if ( hint == RESULT_PANE_CLEAR_VIRTUAL_LB ) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); if (pNode == spSelectedNode) { ClearVirtualLb(pComponent, data); } } else if ( hint == RESULT_PANE_EXPAND ) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); SPIConsole spConsole; pComponent->GetConsole(&spConsole); spConsole->Expand(pNode->GetData(TFS_DATA_SCOPEID), (BOOL)data); } else if (hint == RESULT_PANE_SHOW_MESSAGE) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); BOOL fOldMessageView = (BOOL) data; // // do it only if selected // if (spSelectedNode == pNode) { if (!fOldMessageView) { SPIConsole spConsole; pComponent->GetConsole(&spConsole); spConsole->SelectScopeItem(pNode->GetData(TFS_DATA_SCOPEID)); } else { ShowResultMessage(pComponent, spInternal->m_cookie, NULL, NULL); } } } else if (hint == RESULT_PANE_CLEAR_MESSAGE) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); BOOL fOldMessageView = (BOOL) data; // // do it only if selected // if (spSelectedNode == pNode) { if (fOldMessageView) { SPIConsole spConsole; pComponent->GetConsole(&spConsole); spConsole->SelectScopeItem(pNode->GetData(TFS_DATA_SCOPEID)); } } } // else if return hrOK; } /*!-------------------------------------------------------------------------- CBaseResultHandler::ChangeResultPaneItem Implementation of ChangeResultPaneItem Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::ChangeResultPaneItem ( ITFSComponent * pComponent, ITFSNode * pNode, LPARAM changeMask ) { Assert(changeMask & RESULT_PANE_CHANGE_ITEM); Assert(pNode != NULL); HRESULTITEM itemID; HRESULT hr = hrOK; SPIResultData pResultData; CORg ( pComponent->GetResultData(&pResultData) ); CORg ( pResultData->FindItemByLParam(static_cast<LPARAM>(pNode->GetData(TFS_DATA_COOKIE)), &itemID) ); RESULTDATAITEM resultItem; ZeroMemory(&resultItem, sizeof(RESULTDATAITEM)); resultItem.itemID = itemID; if (changeMask & RESULT_PANE_CHANGE_ITEM_DATA) { resultItem.mask |= RDI_STR; resultItem.str = MMC_CALLBACK; } if (changeMask & RESULT_PANE_CHANGE_ITEM_ICON) { resultItem.mask |= RDI_IMAGE; resultItem.nImage = (int)pNode->GetData(TFS_DATA_IMAGEINDEX); } CORg ( pResultData->SetItem(&resultItem) ); CORg ( pResultData->UpdateItem(itemID) ); Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::AddResultPaneItem Implementation of AddResultPaneItem Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::AddResultPaneItem ( ITFSComponent * pComponent, ITFSNode * pNode ) { Assert(pNode != NULL); RESULTDATAITEM dataitemResult; HRESULT hr = hrOK; SPIResultData pResultData; CORg ( pComponent->GetResultData(&pResultData) ); ZeroMemory(&dataitemResult, sizeof(dataitemResult)); dataitemResult.mask = RDI_STR | RDI_IMAGE | RDI_PARAM; dataitemResult.str = MMC_CALLBACK; dataitemResult.mask |= SDI_IMAGE; dataitemResult.nImage = (int)pNode->GetData(TFS_DATA_IMAGEINDEX); dataitemResult.lParam = static_cast<LPARAM>(pNode->GetData(TFS_DATA_COOKIE)); CORg ( pResultData->InsertItem(&dataitemResult) ); Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::DeleteResultPaneItem Implementation of DeleteResultPaneItem Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::DeleteResultPaneItem ( ITFSComponent * pComponent, ITFSNode * pNode ) { Assert(pNode != NULL); HRESULT hr = hrOK; HRESULTITEM itemID; SPIResultData pResultData; CORg ( pComponent->GetResultData(&pResultData) ); CORg ( pResultData->FindItemByLParam(static_cast<LPARAM>(pNode->GetData(TFS_DATA_COOKIE)), &itemID) ); CORg ( pResultData->DeleteItem(itemID, 0 /* all cols */) ); Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::SetVirtualLbSize Sets the virtual listbox count. Over-ride this if you need to specify and options. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::SetVirtualLbSize ( ITFSComponent * pComponent, LONG_PTR data ) { HRESULT hr = hrOK; SPIResultData spResultData; CORg (pComponent->GetResultData(&spResultData)); CORg (spResultData->SetItemCount((int) data, MMCLV_UPDATE_NOINVALIDATEALL)); Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::ClearVirtualLb Sets the virtual listbox count. Over-ride this if you need to specify and options. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::ClearVirtualLb ( ITFSComponent * pComponent, LONG_PTR data ) { HRESULT hr = hrOK; SPIResultData spResultData; CORg (pComponent->GetResultData(&spResultData)); CORg (spResultData->SetItemCount((int) data, 0)); Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultActivate - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultActivate(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM param) { Trace0("IComponent::Notify(MMCN_ACTIVATE) received\n"); return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultItemClkOrDblClk - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultItemClkOrDblClk(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM param, BOOL bDoubleClick) { if (!bDoubleClick) Trace0("IComponent::Notify(MMCN_CLK) received\n"); else Trace0("IComponent::Notify(MMCN_DBLCLK) received\n"); // return false so that MMC does the default behavior (open the node); return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultShow - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultShow(ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { // Note - arg is TRUE when it is time to enumerate if (arg == TRUE) { // show the result view message if there is one ShowResultMessage(pComponent, cookie, arg, lParam); // Show the headers for this nodetype LoadColumns(pComponent, cookie, arg, lParam); EnumerateResultPane(pComponent, cookie, arg, lParam); SortColumns(pComponent); SPITFSNode spNode; m_spResultNodeMgr->FindNode(cookie, &spNode); pComponent->SetSelectedNode(spNode); } else { SaveColumns(pComponent, cookie, arg, lParam); pComponent->SetSelectedNode(NULL); // Free data associated with the result pane items, because // your node is no longer being displayed. // Note: The console will remove the items from the result pane } return hrOK; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultColumnClick - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultColumnClick(ITFSComponent *pComponent, LPARAM iColumn, BOOL fAscending) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultColumnsChanged - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultColumnsChanged(ITFSComponent *, LPDATAOBJECT, MMC_VISIBLE_COLUMNS *) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::ShowResultMessage - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::ShowResultMessage(ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { HRESULT hr = hrOK; SPIMessageView spMessageView; SPIUnknown spUnknown; SPIConsole spConsole; LPOLESTR pText = NULL; // put up our message text if (m_fMessageView) { if (pComponent) { CORg ( pComponent->GetConsole(&spConsole) ); CORg ( spConsole->QueryResultView(&spUnknown) ); CORg ( spMessageView.HrQuery(spUnknown) ); } // set the title text pText = (LPOLESTR)CoTaskMemAlloc (sizeof(OLECHAR) * (m_strMessageTitle.GetLength() + 1)); if (pText) { lstrcpy (pText, m_strMessageTitle); CORg(spMessageView->SetTitleText(pText)); // bugid:148215 vivekk CoTaskMemFree(pText); } // set the body text pText = (LPOLESTR)CoTaskMemAlloc (sizeof(OLECHAR) * (m_strMessageBody.GetLength() + 1)); if (pText) { lstrcpy (pText, m_strMessageBody); CORg(spMessageView->SetBodyText(pText)); // bugid:148215 vivekk CoTaskMemFree(pText); } // set the icon CORg(spMessageView->SetIcon(m_lMessageIcon)); COM_PROTECT_ERROR_LABEL; } return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::ShowMessage - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::ShowMessage(ITFSNode * pNode, LPCTSTR pszTitle, LPCTSTR pszBody, IconIdentifier lIcon) { HRESULT hr = hrOK; SPIComponentData spCompData; SPIConsole spConsole; SPIDataObject spDataObject; IDataObject * pDataObject; BOOL fOldMessageView; m_strMessageTitle = pszTitle; m_strMessageBody = pszBody; m_lMessageIcon = lIcon; fOldMessageView = m_fMessageView; m_fMessageView = TRUE; // tell the views to update themselves here m_spResultNodeMgr->GetComponentData(&spCompData); CORg ( spCompData->QueryDataObject((MMC_COOKIE) pNode, CCT_SCOPE, &pDataObject) ); spDataObject = pDataObject; CORg ( m_spResultNodeMgr->GetConsole(&spConsole) ); CORg ( spConsole->UpdateAllViews(pDataObject, (LPARAM) fOldMessageView, RESULT_PANE_SHOW_MESSAGE) ); COM_PROTECT_ERROR_LABEL; return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::ClearMessage - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::ClearMessage(ITFSNode * pNode) { HRESULT hr = hrOK; SPIComponentData spCompData; SPIConsole spConsole; SPIDataObject spDataObject; IDataObject * pDataObject; BOOL fOldMessageView; fOldMessageView = m_fMessageView; m_fMessageView = FALSE; // tell the views to update themselves here m_spResultNodeMgr->GetComponentData(&spCompData); CORg ( spCompData->QueryDataObject((MMC_COOKIE) pNode, CCT_SCOPE, &pDataObject) ); spDataObject = pDataObject; CORg ( m_spResultNodeMgr->GetConsole(&spConsole) ); CORg ( spConsole->UpdateAllViews(pDataObject, (LPARAM) fOldMessageView, RESULT_PANE_CLEAR_MESSAGE) ); COM_PROTECT_ERROR_LABEL; return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::LoadColumns - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::LoadColumns(ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); SPIHeaderCtrl spHeaderCtrl; pComponent->GetHeaderCtrl(&spHeaderCtrl); CString str; int i = 0; if (!m_pColumnStringIDs) return hrOK; if (!m_fMessageView) { while (TRUE) { int nColumnWidth = AUTO_WIDTH; if ( 0 == m_pColumnStringIDs[i] ) break; str.LoadString(m_pColumnStringIDs[i]); if (m_pColumnWidths) nColumnWidth = m_pColumnWidths[i]; spHeaderCtrl->InsertColumn(i, const_cast<LPTSTR>((LPCWSTR)str), m_nColumnFormat, nColumnWidth); i++; } } return hrOK; } /*!-------------------------------------------------------------------------- CBaseResultHandler::SaveColumns - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::SaveColumns(ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::SortColumns - Author: KennT ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::SortColumns(ITFSComponent *pComponent) { return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::EnumerateResultPane - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::EnumerateResultPane(ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); SPITFSNode spContainer; m_spResultNodeMgr->FindNode(cookie, &spContainer); // // Walk the list of children to see if there's anything // to put in the result pane // SPITFSNodeEnum spNodeEnum; ITFSNode * pCurrentNode; ULONG nNumReturned = 0; spContainer->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); while (nNumReturned) { // // All containers go into the scope pane and automatically get // put into the result pane for us by the MMC // if (!pCurrentNode->IsContainer() && pCurrentNode->IsVisible()) { AddResultPaneItem(pComponent, pCurrentNode); } pCurrentNode->Release(); spNodeEnum->Next(1, &pCurrentNode, &nNumReturned); } return hrOK; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultSelect - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultSelect(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { HRESULT hr = hrOK; SPIConsoleVerb spConsoleVerb; CORg (pComponent->GetConsoleVerb(&spConsoleVerb)); // Default is to turn everything off spConsoleVerb->SetVerbState(MMC_VERB_OPEN, HIDDEN, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_COPY, HIDDEN, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_PASTE, HIDDEN, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_DELETE, HIDDEN, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_PROPERTIES, HIDDEN, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_RENAME, HIDDEN, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_REFRESH, ENABLED, TRUE); spConsoleVerb->SetVerbState(MMC_VERB_PRINT, HIDDEN, TRUE); Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnResultInitOcx - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnResultInitOcx(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { // arg - not used // param - contains IUnknown to the OCX return S_FALSE; } /*!-------------------------------------------------------------------------- CBaseResultHandler::FIsTaskpadPreferred - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::FIsTaskpadPreferred(ITFSComponent *pComponent) { HRESULT hr = hrOK; SPIConsole spConsole; pComponent->GetConsole(&spConsole); hr = spConsole->IsTaskpadViewPreferred(); //Error: return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::DoTaskpadResultSelect Handlers with taskpads should override the OnResultSelect and call this to handle setting of the selected node. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::DoTaskpadResultSelect(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam, BOOL bTaskPadView) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spNode, spSelectedNode; HRESULT hr = hrOK; // if this node is being selected then set the selected node. // this node with a taskpad gets the MMCN_SHOW when the node is // de-selected, so that will set the selected node to NULL. if ( (HIWORD(arg) == TRUE) && bTaskPadView ) { m_spResultNodeMgr->FindNode(cookie, &spNode); pComponent->GetSelectedNode(&spSelectedNode); // in the normal case MMC will call whichever node is selected to // notify that is being de-selected. In this case our handler will // set the selected node to NULL. If the selected node is not null then // we are just being notified of something like a selection for a context // menu... if (!spSelectedNode) pComponent->SetSelectedNode(spNode); } // call the base class to handle anything else return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::OnGetResultViewType MMC calls this to get the result view information Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CBaseResultHandler::OnGetResultViewType ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR * ppViewType, long * pViewOptions ) { HRESULT hr = S_FALSE; // // use the MMC default result view if no message is specified. // Multiple selection, or virtual listbox, override this function. // See MMC sample code for example. The Message view uses an OCX... // if (m_fMessageView) { // create the message view thingie *pViewOptions = MMC_VIEW_OPTIONS_NOLISTVIEWS; LPOLESTR psz = NULL; StringFromCLSID(CLSID_MessageView, &psz); USES_CONVERSION; if (psz != NULL) { *ppViewType = psz; hr = S_OK; } } return hr; } /*!-------------------------------------------------------------------------- CBaseResultHandler::GetVirtualString called when the virtual listbox needs information on an index Author: EricDav ---------------------------------------------------------------------------*/ LPCWSTR CBaseResultHandler::GetVirtualString ( int nIndex, int nCol ) { return NULL; } /*!-------------------------------------------------------------------------- CBaseResultHandler::GetVirtualImage called when the virtual listbox needs an image index for an item Author: EricDav ---------------------------------------------------------------------------*/ int CBaseResultHandler::GetVirtualImage ( int nIndex ) { return 0; } HRESULT CBaseResultHandler::OnResultMinimize(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_MINIMIZE) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultDelete(ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_DELETE) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultRename(ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_RENAME) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultRefresh(ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_REFRESH) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultContextHelp(ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_CONTEXTHELP) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultQueryPaste(ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_QUERY_PASTE) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbCopy(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_COPY) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbPaste(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_PASTE) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbDelete(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_DELETE) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbProperties(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_PROPERTIES) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbRename(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_RENAME) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbRefresh(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_REFRESH) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultVerbPrint(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_VERB_PRINT) received\n"); return S_FALSE; } HRESULT CBaseResultHandler::OnResultRestoreView(ITFSComponent *pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { Trace0("IComponent::Notify(MMCN_RESTORE_VIEW) received\n"); return S_FALSE; }
29.59969
168
0.560702
npocmaka
c60fe3d4e0fd8982b78cc8624913bfd71ef4d7b9
1,054
hpp
C++
src/dp/lcs.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
src/dp/lcs.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
src/dp/lcs.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
#ifndef ALGORITHM_LCS_HPP #define ALGORITHM_LCS_HPP #include <algorithm> #include <string> #include <vector> namespace algorithm { // 最長共通部分列 (LCS:Longest Common Subsequence). O(|A|*|B|). template <class Class> Class lcs(const Class &a, const Class &b) { int an = a.size(), bn = b.size(); std::vector<std::vector<int> > dp(an + 1, std::vector<int>(bn + 1, 0)); // dp[i][j]:=(a[:i]とb[:j]のLCSの長さ). for(int i = 1; i <= an; ++i) for(int j = 1; j <= bn; ++j) { if(a[i - 1] == b[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } Class sub(dp[an][bn]); // sub[]:=(配列a, bのLCS). int i = an, j = bn, k = dp[an][bn]; while(k > 0) { if(a[i - 1] == b[j - 1]) { sub[k - 1] = a[i - 1]; i--, j--, k--; } else if(dp[i][j] == dp[i - 1][j]) { i--; } else { j--; } } return sub; } } // namespace algorithm #endif // ALGORITHM_LCS_HPP
26.35
111
0.44592
today2098
c61002540bab6c6d6a88589cba8f69b3771fa016
34,655
cpp
C++
renderer/scene.cpp
Svengali/Granite
90de56b405455ccf70deaa5befe762a2bbc7777e
[ "MIT" ]
null
null
null
renderer/scene.cpp
Svengali/Granite
90de56b405455ccf70deaa5befe762a2bbc7777e
[ "MIT" ]
null
null
null
renderer/scene.cpp
Svengali/Granite
90de56b405455ccf70deaa5befe762a2bbc7777e
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "scene.hpp" #include "transforms.hpp" #include "lights/lights.hpp" #include "simd.hpp" #include "task_composer.hpp" #include <float.h> using namespace std; namespace Granite { Scene::Scene() : spatials(pool.get_component_group<BoundedComponent, RenderInfoComponent, CachedSpatialTransformTimestampComponent>()), opaque(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, OpaqueComponent>()), transparent(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, TransparentComponent>()), positional_lights(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, PositionalLightComponent>()), irradiance_affecting_positional_lights(pool.get_component_group<RenderInfoComponent, PositionalLightComponent, CachedSpatialTransformTimestampComponent, IrradianceAffectingComponent>()), static_shadowing(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, CastsStaticShadowComponent>()), dynamic_shadowing(pool.get_component_group<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, CastsDynamicShadowComponent>()), render_pass_shadowing(pool.get_component_group<RenderPassComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, CastsDynamicShadowComponent>()), backgrounds(pool.get_component_group<UnboundedComponent, RenderableComponent>()), cameras(pool.get_component_group<CameraComponent, CachedTransformComponent>()), directional_lights(pool.get_component_group<DirectionalLightComponent, CachedTransformComponent>()), volumetric_diffuse_lights(pool.get_component_group<VolumetricDiffuseLightComponent, CachedSpatialTransformTimestampComponent, RenderInfoComponent>()), per_frame_updates(pool.get_component_group<PerFrameUpdateComponent>()), per_frame_update_transforms(pool.get_component_group<PerFrameUpdateTransformComponent, RenderInfoComponent>()), environments(pool.get_component_group<EnvironmentComponent>()), render_pass_sinks(pool.get_component_group<RenderPassSinkComponent, RenderableComponent, CullPlaneComponent>()), render_pass_creators(pool.get_component_group<RenderPassComponent>()) { } Scene::~Scene() { // Makes shutdown way faster :) // We know ahead of time we're going to delete everything, // so reduce a lot of overhead by deleting right away. pool.reset_groups(); destroy_entities(entities); destroy_entities(queued_entities); } template <typename T> static void gather_visible_renderables(const Frustum &frustum, VisibilityList &list, const T &objects, size_t begin_index, size_t end_index) { for (size_t i = begin_index; i < end_index; i++) { auto &o = objects[i]; auto *transform = get_component<RenderInfoComponent>(o); auto *renderable = get_component<RenderableComponent>(o); auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(o); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); if (transform->transform) { if ((renderable->renderable->flags & RENDERABLE_FORCE_VISIBLE_BIT) != 0 || SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) { list.push_back({ renderable->renderable.get(), transform, h.get() }); } } else list.push_back({ renderable->renderable.get(), nullptr, h.get() }); } } void Scene::add_render_passes(RenderGraph &graph) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->add_render_passes(graph); } } void Scene::add_render_pass_dependencies(RenderGraph &graph, RenderPass &main_pass) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->setup_render_pass_dependencies(graph, main_pass); } } void Scene::set_render_pass_data(const RendererSuite *suite, const RenderContext *context) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->set_base_renderer(suite); rpass->set_base_render_context(context); rpass->set_scene(this); } } void Scene::bind_render_graph_resources(RenderGraph &graph) { for (auto &pass : render_pass_creators) { auto *rpass = get_component<RenderPassComponent>(pass)->creator; rpass->setup_render_pass_resources(graph); } } void Scene::refresh_per_frame(const RenderContext &context, TaskComposer &composer) { per_frame_update_transforms_sorted = per_frame_update_transforms; per_frame_updates_sorted = per_frame_updates; stable_sort(per_frame_update_transforms_sorted.begin(), per_frame_update_transforms_sorted.end(), [](auto &a, auto &b) -> bool { int order_a = get_component<PerFrameUpdateTransformComponent>(a)->dependency_order; int order_b = get_component<PerFrameUpdateTransformComponent>(b)->dependency_order; return order_a < order_b; }); stable_sort(per_frame_updates_sorted.begin(), per_frame_updates_sorted.end(), [](auto &a, auto &b) -> bool { int order_a = get_component<PerFrameUpdateComponent>(a)->dependency_order; int order_b = get_component<PerFrameUpdateComponent>(b)->dependency_order; return order_a < order_b; }); int dep = std::numeric_limits<int>::min(); for (auto &update : per_frame_update_transforms_sorted) { auto *comp = get_component<PerFrameUpdateTransformComponent>(update); assert(comp->dependency_order != std::numeric_limits<int>::min()); if (comp->dependency_order != dep) { composer.begin_pipeline_stage(); dep = comp->dependency_order; } auto *refresh = comp->refresh; auto *transform = get_component<RenderInfoComponent>(update); if (refresh) refresh->refresh(context, transform, composer); } dep = std::numeric_limits<int>::min(); for (auto &update : per_frame_updates_sorted) { auto *comp = get_component<PerFrameUpdateComponent>(update); assert(comp->dependency_order != std::numeric_limits<int>::min()); if (comp->dependency_order != dep) { composer.begin_pipeline_stage(); dep = comp->dependency_order; } auto *refresh = comp->refresh; if (refresh) refresh->refresh(context, composer); } composer.begin_pipeline_stage(); } EnvironmentComponent *Scene::get_environment() const { if (environments.empty()) return nullptr; else return get_component<EnvironmentComponent>(environments.front()); } EntityPool &Scene::get_entity_pool() { return pool; } void Scene::gather_unbounded_renderables(VisibilityList &list) const { for (auto &background : backgrounds) list.push_back({ get_component<RenderableComponent>(background)->renderable.get(), nullptr }); } void Scene::gather_visible_render_pass_sinks(const vec3 &camera_pos, VisibilityList &list) const { for (auto &sink : render_pass_sinks) { auto &plane = get_component<CullPlaneComponent>(sink)->plane; if (dot(vec4(camera_pos, 1.0f), plane) > 0.0f) list.push_back({get_component<RenderableComponent>(sink)->renderable.get(), nullptr}); } } void Scene::gather_visible_opaque_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, opaque, 0, opaque.size()); } void Scene::gather_visible_opaque_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * opaque.size()) / num_indices; size_t end_index = ((index + 1) * opaque.size()) / num_indices; gather_visible_renderables(frustum, list, opaque, start_index, end_index); } void Scene::gather_visible_transparent_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, transparent, 0, transparent.size()); } void Scene::gather_visible_static_shadow_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, static_shadowing, 0, static_shadowing.size()); } void Scene::gather_visible_transparent_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * transparent.size()) / num_indices; size_t end_index = ((index + 1) * transparent.size()) / num_indices; gather_visible_renderables(frustum, list, transparent, start_index, end_index); } void Scene::gather_visible_static_shadow_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * static_shadowing.size()) / num_indices; size_t end_index = ((index + 1) * static_shadowing.size()) / num_indices; gather_visible_renderables(frustum, list, static_shadowing, start_index, end_index); } void Scene::gather_visible_dynamic_shadow_renderables(const Frustum &frustum, VisibilityList &list) const { gather_visible_renderables(frustum, list, dynamic_shadowing, 0, dynamic_shadowing.size()); for (auto &object : render_pass_shadowing) list.push_back({ get_component<RenderableComponent>(object)->renderable.get(), nullptr }); } void Scene::gather_visible_dynamic_shadow_renderables_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * dynamic_shadowing.size()) / num_indices; size_t end_index = ((index + 1) * dynamic_shadowing.size()) / num_indices; gather_visible_renderables(frustum, list, dynamic_shadowing, start_index, end_index); if (index == 0) for (auto &object : render_pass_shadowing) list.push_back({ get_component<RenderableComponent>(object)->renderable.get(), nullptr }); } static void gather_positional_lights(const Frustum &frustum, VisibilityList &list, const ComponentGroupVector< RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, PositionalLightComponent> &positional, size_t start_index, size_t end_index) { for (size_t i = start_index; i < end_index; i++) { auto &o = positional[i]; auto *transform = get_component<RenderInfoComponent>(o); auto *renderable = get_component<RenderableComponent>(o); auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(o); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); if (transform->transform) { if (SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) list.push_back({ renderable->renderable.get(), transform, h.get() }); } else list.push_back({ renderable->renderable.get(), nullptr, h.get() }); } } static void gather_positional_lights(const Frustum &frustum, PositionalLightList &list, const ComponentGroupVector<RenderInfoComponent, RenderableComponent, CachedSpatialTransformTimestampComponent, PositionalLightComponent> &positional, size_t start_index, size_t end_index) { for (size_t i = start_index; i < end_index; i++) { auto &o = positional[i]; auto *transform = get_component<RenderInfoComponent>(o); auto *light = get_component<PositionalLightComponent>(o)->light; auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(o); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); if (transform->transform) { if (SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) list.push_back({ light, transform, h.get() }); } else list.push_back({ light, transform, h.get() }); } } void Scene::gather_visible_positional_lights(const Frustum &frustum, VisibilityList &list) const { gather_positional_lights(frustum, list, positional_lights, 0, positional_lights.size()); } void Scene::gather_irradiance_affecting_positional_lights(PositionalLightList &list) const { for (auto &light_tup : irradiance_affecting_positional_lights) { auto *transform = get_component<RenderInfoComponent>(light_tup); auto *light = get_component<PositionalLightComponent>(light_tup)->light; auto *timestamp = get_component<CachedSpatialTransformTimestampComponent>(light_tup); Util::Hasher h; h.u64(timestamp->cookie); h.u32(timestamp->last_timestamp); list.push_back({ light, transform, h.get() }); } } void Scene::gather_visible_positional_lights(const Frustum &frustum, PositionalLightList &list) const { gather_positional_lights(frustum, list, positional_lights, 0, positional_lights.size()); } void Scene::gather_visible_volumetric_diffuse_lights(const Frustum &frustum, VolumetricDiffuseLightList &list) const { for (auto &o : volumetric_diffuse_lights) { auto *transform = get_component<RenderInfoComponent>(o); auto *light = get_component<VolumetricDiffuseLightComponent>(o); if (light->light.get_volume_view()) { if (transform->transform) { if (SIMD::frustum_cull(transform->world_aabb, frustum.get_planes())) list.push_back({ light, transform }); } else list.push_back({ light, transform }); } } } void Scene::gather_visible_positional_lights_subset(const Frustum &frustum, VisibilityList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * positional_lights.size()) / num_indices; size_t end_index = ((index + 1) * positional_lights.size()) / num_indices; gather_positional_lights(frustum, list, positional_lights, start_index, end_index); } void Scene::gather_visible_positional_lights_subset(const Frustum &frustum, PositionalLightList &list, unsigned index, unsigned num_indices) const { size_t start_index = (index * positional_lights.size()) / num_indices; size_t end_index = ((index + 1) * positional_lights.size()) / num_indices; gather_positional_lights(frustum, list, positional_lights, start_index, end_index); } size_t Scene::get_opaque_renderables_count() const { return opaque.size(); } size_t Scene::get_transparent_renderables_count() const { return transparent.size(); } size_t Scene::get_static_shadow_renderables_count() const { return static_shadowing.size(); } size_t Scene::get_dynamic_shadow_renderables_count() const { return dynamic_shadowing.size(); } size_t Scene::get_positional_lights_count() const { return positional_lights.size(); } #if 0 static void log_node_transforms(const Scene::Node &node) { for (unsigned i = 0; i < node.cached_skin_transform.bone_world_transforms.size(); i++) { LOGI("Joint #%u:\n", i); const auto &ibp = node.cached_skin_transform.bone_world_transforms[i]; LOGI(" Transform:\n" " [%f, %f, %f, %f]\n" " [%f, %f, %f, %f]\n" " [%f, %f, %f, %f]\n" " [%f, %f, %f, %f]\n", ibp[0][0], ibp[1][0], ibp[2][0], ibp[3][0], ibp[0][1], ibp[1][1], ibp[2][1], ibp[3][1], ibp[0][2], ibp[1][2], ibp[2][2], ibp[3][2], ibp[0][3], ibp[1][3], ibp[2][3], ibp[3][3]); } } #endif void Scene::update_skinning(Node &node) { if (node.get_skin() && !node.get_skin()->cached_skin_transform.bone_world_transforms.empty()) { auto &skin = *node.get_skin(); auto len = node.get_skin()->skin.size(); assert(skin.skin.size() == skin.cached_skin_transform.bone_world_transforms.size()); //assert(node.get_skin().cached_skin.size() == node.cached_skin_transform.bone_normal_transforms.size()); for (size_t i = 0; i < len; i++) { SIMD::mul(skin.cached_skin_transform.bone_world_transforms[i], skin.cached_skin[i]->world_transform, skin.inverse_bind_poses[i]); //node.cached_skin_transform.bone_normal_transforms[i] = node.get_skin().cached_skin[i]->normal_transform; } //log_node_transforms(node); } } void Scene::dispatch_collect_children(TraversalState *state) { size_t count = state->pending_count; // If we have a lot of child nodes, they will be farmed out to separate traversal states. // The spill-over will be collected, and sub-batches will be dispatched from that, etc. Node *children[TraversalState::BatchSize]; size_t unbatched_child_count = 0; for (size_t i = 0; i < count; i++) { NodeUpdateState update_state; Node *pending; if (state->single_parent) { pending = state->pending_list[i].get(); update_state = update_node_state(*pending, state->single_parent_is_dirty); if (update_state.self) update_transform_tree_node(*pending, *state->single_parent_transform); } else { pending = state->pending[i]; update_state = update_node_state(*pending, state->parent_is_dirty[i]); if (update_state.self) update_transform_tree_node(*pending, *state->parent_transforms[i]); } if (!update_state.children) continue; bool parent_is_dirty = update_state.self; auto *input_childs = pending->get_children().data(); size_t child_count = pending->get_children().size(); const mat4 *transform = &pending->cached_transform.world_transform; size_t derived_batch_count = child_count / TraversalState::BatchSize; for (size_t batch = 0; batch < derived_batch_count; batch++) { auto *child_state = traversal_state_pool.allocate(); child_state->traversal_done_dependency = state->traversal_done_dependency; child_state->traversal_done_dependency->add_flush_dependency(); child_state->group = state->group; child_state->pending_count = TraversalState::BatchSize; child_state->pending_list = &input_childs[batch * TraversalState::BatchSize]; child_state->single_parent = true; child_state->single_parent_transform = transform; child_state->single_parent_is_dirty = parent_is_dirty; dispatch_per_node_work(child_state); } for (size_t j = derived_batch_count * TraversalState::BatchSize; j < child_count; j++) { children[unbatched_child_count] = input_childs[j].get(); state->parent_is_dirty[unbatched_child_count] = parent_is_dirty; state->parent_transforms[unbatched_child_count] = transform; unbatched_child_count++; if (unbatched_child_count == TraversalState::BatchSize) { auto *child_state = traversal_state_pool.allocate(); child_state->traversal_done_dependency = state->traversal_done_dependency; child_state->traversal_done_dependency->add_flush_dependency(); child_state->group = state->group; child_state->pending_count = TraversalState::BatchSize; memcpy(child_state->pending, children, sizeof(children)); memcpy(child_state->parent_is_dirty, state->parent_is_dirty, sizeof(state->parent_is_dirty)); memcpy(child_state->parent_transforms, state->parent_transforms, sizeof(state->parent_transforms)); dispatch_per_node_work(child_state); unbatched_child_count = 0; } } } state->pending_count = unbatched_child_count; memcpy(state->pending, children, unbatched_child_count * sizeof(*children)); } TaskGroupHandle Scene::dispatch_per_node_work(TraversalState *state) { auto dispatcher_task = state->group->create_task([this, state]() { while (state->pending_count != 0) dispatch_collect_children(state); state->traversal_done_dependency->release_flush_dependency(); traversal_state_pool.free(state); }); dispatcher_task->set_desc("parallel-node-transform-update"); return dispatcher_task; } static const mat4 identity_transform(1.0f); void Scene::update_transform_tree(TaskComposer &composer) { if (!root_node) return; auto &group = composer.begin_pipeline_stage(); auto traversal = traversal_state_pool.allocate(); traversal->traversal_done_dependency = composer.get_thread_group().create_task(); traversal->pending_count = 1; traversal->pending[0] = root_node.get(); traversal->parent_is_dirty[0] = false; traversal->parent_transforms[0] = &identity_transform; traversal->group = &composer.get_thread_group(); traversal->traversal_done_dependency->add_flush_dependency(); auto dispatch = dispatch_per_node_work(traversal); if (auto dep = composer.get_pipeline_stage_dependency()) composer.get_thread_group().add_dependency(*dispatch, *dep); composer.get_thread_group().add_dependency(group, *traversal->traversal_done_dependency); } Scene::NodeUpdateState Scene::update_node_state(Node &node, bool parent_is_dirty) { bool transform_dirty = node.get_and_clear_transform_dirty() || parent_is_dirty; bool child_transforms_dirty = node.get_and_clear_child_transform_dirty() || transform_dirty; return { transform_dirty, child_transforms_dirty }; } void Scene::update_transform_tree_node(Node &node, const mat4 &transform) { compute_model_transform(node.cached_transform.world_transform, node.transform.scale, node.transform.rotation, node.transform.translation, transform); if (auto *skinning = node.get_skin()) for (auto &child : skinning->skeletons) update_transform_tree(*child, node.cached_transform.world_transform, true); //compute_normal_transform(node.cached_transform.normal_transform, node.cached_transform.world_transform); update_skinning(node); node.update_timestamp(); } void Scene::update_transform_tree(Node &node, const mat4 &transform, bool parent_is_dirty) { auto state = update_node_state(node, parent_is_dirty); if (state.self) update_transform_tree_node(node, transform); if (state.children) for (auto &child : node.get_children()) update_transform_tree(*child, node.cached_transform.world_transform, state.self); } size_t Scene::get_cached_transforms_count() const { return spatials.size(); } void Scene::update_cached_transforms_subset(unsigned index, unsigned num_indices) { size_t begin_index = (spatials.size() * index) / num_indices; size_t end_index = (spatials.size() * (index + 1)) / num_indices; update_cached_transforms_range(begin_index, end_index); } void Scene::update_all_transforms() { update_transform_tree(); update_transform_listener_components(); update_cached_transforms_range(0, spatials.size()); } void Scene::update_transform_tree() { if (root_node) update_transform_tree(*root_node, mat4(1.0f), false); } void Scene::update_transform_listener_components() { // Update camera transforms. for (auto &c : cameras) { CameraComponent *cam; CachedTransformComponent *transform; tie(cam, transform) = c; cam->camera.set_transform(transform->transform->world_transform); } // Update directional light transforms. for (auto &light : directional_lights) { DirectionalLightComponent *l; CachedTransformComponent *transform; tie(l, transform) = light; // v = [0, 0, 1, 0]. l->direction = normalize(transform->transform->world_transform[2].xyz()); } for (auto &light : volumetric_diffuse_lights) { VolumetricDiffuseLightComponent *l; CachedSpatialTransformTimestampComponent *timestamp; RenderInfoComponent *transform; tie(l, timestamp, transform) = light; if (timestamp->last_timestamp != l->timestamp) { // This is a somewhat expensive operation, so timestamp it. // We only expect this to run once since diffuse volumes really // cannot freely move around the scene due to the semi-baked nature of it. auto texture_to_world = transform->transform->world_transform * translate(vec3(-0.5f)); auto world_to_texture = inverse(texture_to_world); world_to_texture = transpose(world_to_texture); texture_to_world = transpose(texture_to_world); for (int i = 0; i < 3; i++) { l->world_to_texture[i] = world_to_texture[i]; l->texture_to_world[i] = texture_to_world[i]; } l->timestamp = timestamp->last_timestamp; } } } void Scene::update_cached_transforms_range(size_t begin_range, size_t end_range) { for (size_t i = begin_range; i < end_range; i++) { auto &s = spatials[i]; BoundedComponent *aabb; RenderInfoComponent *cached_transform; CachedSpatialTransformTimestampComponent *timestamp; tie(aabb, cached_transform, timestamp) = s; if (timestamp->last_timestamp != *timestamp->current_timestamp) { if (cached_transform->transform) { if (cached_transform->skin_transform) { // TODO: Isolate the AABB per bone. cached_transform->world_aabb = AABB(vec3(FLT_MAX), vec3(-FLT_MAX)); for (auto &m : cached_transform->skin_transform->bone_world_transforms) SIMD::transform_and_expand_aabb(cached_transform->world_aabb, *aabb->aabb, m); } else { SIMD::transform_aabb(cached_transform->world_aabb, *aabb->aabb, cached_transform->transform->world_transform); } } timestamp->last_timestamp = *timestamp->current_timestamp; } } } Scene::NodeHandle Scene::create_node() { return Scene::NodeHandle(node_pool.allocate(this)); } void Scene::NodeDeleter::operator()(Node *node) { node->parent_scene->get_node_pool().free(node); } static void add_bone(Scene::NodeHandle *bones, uint32_t parent, const SceneFormats::Skin::Bone &bone) { bones[parent]->get_skin()->skeletons.push_back(bones[bone.index]); for (auto &child : bone.children) add_bone(bones, bone.index, child); } Scene::NodeHandle Scene::create_skinned_node(const SceneFormats::Skin &skin) { auto node = create_node(); vector<NodeHandle> bones; bones.reserve(skin.joint_transforms.size()); for (size_t i = 0; i < skin.joint_transforms.size(); i++) { bones.push_back(create_node()); bones[i]->transform.translation = skin.joint_transforms[i].translation; bones[i]->transform.scale = skin.joint_transforms[i].scale; bones[i]->transform.rotation = skin.joint_transforms[i].rotation; } node->set_skin(skinning_pool.allocate()); auto &node_skin = *node->get_skin(); node_skin.cached_skin_transform.bone_world_transforms.resize(skin.joint_transforms.size()); //node->cached_skin_transform.bone_normal_transforms.resize(skin.joint_transforms.size()); node_skin.skin.reserve(skin.joint_transforms.size()); node_skin.cached_skin.reserve(skin.joint_transforms.size()); node_skin.inverse_bind_poses.reserve(skin.joint_transforms.size()); for (size_t i = 0; i < skin.joint_transforms.size(); i++) { node_skin.cached_skin.push_back(&bones[i]->cached_transform); node_skin.skin.push_back(&bones[i]->transform); node_skin.inverse_bind_poses.push_back(skin.inverse_bind_pose[i]); } for (auto &skeleton : skin.skeletons) { node->get_skin()->skeletons.push_back(bones[skeleton.index]); for (auto &child : skeleton.children) add_bone(bones.data(), skeleton.index, child); } node_skin.skin_compat = skin.skin_compat; return node; } void Scene::Node::add_child(NodeHandle node) { assert(this != node.get()); assert(node->parent == nullptr); node->parent = this; // Force parents to be notified. node->cached_transform_dirty = false; node->invalidate_cached_transform(); children.push_back(node); } Scene::NodeHandle Scene::Node::remove_child(Node *node) { assert(node->parent == this); node->parent = nullptr; auto handle = node->reference_from_this(); // Force parents to be notified. node->cached_transform_dirty = false; node->invalidate_cached_transform(); auto itr = remove_if(begin(children), end(children), [&](const NodeHandle &h) { return node == h.get(); }); assert(itr != end(children)); children.erase(itr, end(children)); return handle; } Scene::NodeHandle Scene::Node::remove_node_from_hierarchy(Node *node) { if (node->parent) return node->parent->remove_child(node); else return Scene::NodeHandle(nullptr); } void Scene::Node::invalidate_cached_transform() { if (!cached_transform_dirty) { cached_transform_dirty = true; for (auto *p = parent; p && !p->any_child_transform_dirty; p = p->parent) p->any_child_transform_dirty = true; } } Entity *Scene::create_entity() { Entity *entity = pool.create_entity(); entities.insert_front(entity); return entity; } static std::atomic<uint64_t> transform_cookies; Entity *Scene::create_volumetric_diffuse_light(uvec3 resolution, Node *node) { Entity *entity = pool.create_entity(); entities.insert_front(entity); auto *light = entity->allocate_component<VolumetricDiffuseLightComponent>(); light->light.set_resolution(resolution); auto *transform = entity->allocate_component<RenderInfoComponent>(); auto *timestamp = entity->allocate_component<CachedSpatialTransformTimestampComponent>(); auto *bounded = entity->allocate_component<BoundedComponent>(); bounded->aabb = &VolumetricDiffuseLight::get_static_aabb(); if (node) { transform->transform = &node->cached_transform; timestamp->current_timestamp = node->get_timestamp_pointer(); } timestamp->cookie = transform_cookies.fetch_add(std::memory_order_relaxed); return entity; } Entity *Scene::create_light(const SceneFormats::LightInfo &light, Node *node) { Entity *entity = pool.create_entity(); entities.insert_front(entity); switch (light.type) { case SceneFormats::LightInfo::Type::Directional: { auto *dir = entity->allocate_component<DirectionalLightComponent>(); auto *transform = entity->allocate_component<CachedTransformComponent>(); transform->transform = &node->cached_transform; dir->color = light.color; break; } case SceneFormats::LightInfo::Type::Point: case SceneFormats::LightInfo::Type::Spot: { AbstractRenderableHandle renderable; if (light.type == SceneFormats::LightInfo::Type::Point) renderable = Util::make_handle<PointLight>(); else { renderable = Util::make_handle<SpotLight>(); auto &spot = static_cast<SpotLight &>(*renderable); spot.set_spot_parameters(light.inner_cone, light.outer_cone); } auto &positional = static_cast<PositionalLight &>(*renderable); positional.set_color(light.color); if (light.range > 0.0f) positional.set_maximum_range(light.range); entity->allocate_component<PositionalLightComponent>()->light = &positional; entity->allocate_component<RenderableComponent>()->renderable = renderable; auto *transform = entity->allocate_component<RenderInfoComponent>(); auto *timestamp = entity->allocate_component<CachedSpatialTransformTimestampComponent>(); timestamp->cookie = transform_cookies.fetch_add(1, std::memory_order_relaxed); if (node) { transform->transform = &node->cached_transform; timestamp->current_timestamp = node->get_timestamp_pointer(); } auto *bounded = entity->allocate_component<BoundedComponent>(); bounded->aabb = renderable->get_static_aabb(); break; } } return entity; } Entity *Scene::create_renderable(AbstractRenderableHandle renderable, Node *node) { Entity *entity = pool.create_entity(); entities.insert_front(entity); if (renderable->has_static_aabb()) { auto *transform = entity->allocate_component<RenderInfoComponent>(); auto *timestamp = entity->allocate_component<CachedSpatialTransformTimestampComponent>(); timestamp->cookie = transform_cookies.fetch_add(1, std::memory_order_relaxed); if (node) { transform->transform = &node->cached_transform; timestamp->current_timestamp = node->get_timestamp_pointer(); if (node->get_skin() && !node->get_skin()->cached_skin.empty()) transform->skin_transform = &node->get_skin()->cached_skin_transform; } auto *bounded = entity->allocate_component<BoundedComponent>(); bounded->aabb = renderable->get_static_aabb(); } else entity->allocate_component<UnboundedComponent>(); auto *render = entity->allocate_component<RenderableComponent>(); switch (renderable->get_mesh_draw_pipeline()) { case DrawPipeline::AlphaBlend: entity->allocate_component<TransparentComponent>(); break; default: entity->allocate_component<OpaqueComponent>(); if (renderable->has_static_aabb()) { // TODO: Find a way to make this smarter. entity->allocate_component<CastsStaticShadowComponent>(); entity->allocate_component<CastsDynamicShadowComponent>(); } break; } render->renderable = renderable; return entity; } void Scene::destroy_entities(Util::IntrusiveList<Entity> &entity_list) { auto itr = entity_list.begin(); while (itr != entity_list.end()) { auto *to_free = itr.get(); itr = entity_list.erase(itr); to_free->get_pool()->delete_entity(to_free); } } void Scene::remove_entities_with_component(ComponentType id) { // We know ahead of time we're going to delete everything, // so reduce a lot of overhead by deleting right away. pool.reset_groups_for_component_type(id); auto itr = entities.begin(); while (itr != entities.end()) { if (itr->has_component(id)) { auto *to_free = itr.get(); itr = entities.erase(itr); to_free->get_pool()->delete_entity(to_free); } else ++itr; } } void Scene::destroy_queued_entities() { destroy_entities(queued_entities); } void Scene::destroy_entity(Entity *entity) { if (entity) { entities.erase(entity); entity->get_pool()->delete_entity(entity); } } void Scene::queue_destroy_entity(Entity *entity) { if (entity->mark_for_destruction()) { entities.erase(entity); queued_entities.insert_front(entity); } } }
33.909002
189
0.734872
Svengali
c6105c65a5f9e96217bbccf9a8cbb48ddc268d58
9,183
cpp
C++
Server_Db/MdfModel_File.cpp
suzhengquan/MBCAF
6da9e994a30c1c228961328d19e71493f1fa7726
[ "BSD-3-Clause" ]
2
2020-10-24T15:44:31.000Z
2021-05-31T03:22:02.000Z
Server_Db/MdfModel_File.cpp
suzhengquan/MBCAF
6da9e994a30c1c228961328d19e71493f1fa7726
[ "BSD-3-Clause" ]
null
null
null
Server_Db/MdfModel_File.cpp
suzhengquan/MBCAF
6da9e994a30c1c228961328d19e71493f1fa7726
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) "2018-2019", Shenzhen Mindeng Technology Co., Ltd(www.niiengine.com), Mindeng Base Communication Application Framework 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 "ORGANIZATION" 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. */ #include "MdfModel_File.h" #include "MdfServerConnect.h" #include "MdfDatabaseManager.h" #include "MBCAF.HubServer.pb.h" using namespace MBCAF::Proto; namespace Mdf { //----------------------------------------------------------------------- void OfflineFileExistA(ServerConnect * qconn, MdfMessage * msg) { MBCAF::HubServer::FileExistOfflineQ proto; MBCAF::HubServer::FileExistOfflineA protoA; if (msg->toProto(&proto)) { MdfMessage * remsg = new MdfMessage; uint32_t userid = proto.user_id(); Model_File* pModel = M_Only(Model_File); list<MBCAF::Proto::OfflineFileInfo> lsOffline; pModel->getOfflineFile(userid, lsOffline); protoA.set_user_id(userid); for (list<MBCAF::Proto::OfflineFileInfo>::iterator it = lsOffline.begin(); it != lsOffline.end(); ++it) { MBCAF::Proto::OfflineFileInfo* pInfo = protoA.add_offline_file_list(); pInfo->set_from_user_id(it->from_user_id()); pInfo->set_task_id(it->task_id()); pInfo->set_file_name(it->file_name()); pInfo->set_file_size(it->file_size()); } Mlog("userId=%u, count=%u", userid, protoA.offline_file_list_size()); protoA.set_attach_data(proto.attach_data()); remsg->setProto(&protoA); remsg->setSeqIdx(msg->getSeqIdx()); remsg->setCommandID(HSMSG(OfflineFileA)); M_Only(DataSyncManager)->response(qconn, remsg); } else { Mlog("parse pb failed"); } } //----------------------------------------------------------------------- void AddOfflineFileA(ServerConnect * qconn, MdfMessage * msg) { MBCAF::HubServer::FileAddOfflineQ proto; if (msg->toProto(&proto)) { uint32_t fromid = proto.from_user_id(); uint32_t toid = proto.to_user_id(); String strTaskId = proto.task_id(); String strFileName = proto.file_name(); uint32_t nFileSize = proto.file_size(); Model_File* pModel = Model_File::getInstance(); pModel->addOfflineFile(fromid, toid, strTaskId, strFileName, nFileSize); Mlog("fromId=%u, toId=%u, taskId=%s, fileName=%s, fileSize=%u", fromid, toid, strTaskId.c_str(), strFileName.c_str(), nFileSize); } } //----------------------------------------------------------------------- void DeleteOfflineFileA(ServerConnect * qconn, MdfMessage * msg) { MBCAF::HubServer::FileDeleteOfflineQ proto; if (msg->toProto(&proto)) { uint32_t fromid = proto.from_user_id(); uint32_t toid = proto.to_user_id(); String strTaskId = proto.task_id(); Model_File* pModel = Model_File::getInstance(); pModel->deleteOfflineFile(fromid, toid, strTaskId); Mlog("fromId=%u, toId=%u, taskId=%s", fromid, toid, strTaskId.c_str()); } } //----------------------------------------------------------------------- M_SingletonImpl(Model_File); //----------------------------------------------------------------------- Model_File::Model_File() { } //----------------------------------------------------------------------- Model_File::~Model_File() { } //----------------------------------------------------------------------- void Model_File::getOfflineFile(uint32_t userid, list<MBCAF::Proto::OfflineFileInfo> & lsOffline) { DatabaseManager * dbMag = M_Only(DatabaseManager); DatabaseConnect * dbConn = dbMag->getTempConnect("gsgsslave"); if (dbConn) { String strSql = "select * from IMTransmitFile where toId=" + itostr(userid) + " and state=0 order by created"; DatabaseResult * resSet = dbConn->execQuery(strSql.c_str()); if (resSet) { while (resSet->nextRow()) { String temp; Mi32 temp2; MBCAF::Proto::OfflineFileInfo offlineFile; resSet->getValue("fromId", temp2); offlineFile.set_from_user_id(temp2); resSet->getValue("taskId", temp); offlineFile.set_task_id(temp); resSet->getValue("fileName", temp); offlineFile.set_file_name(temp.c_str()); resSet->getValue("size", temp2); offlineFile.set_file_size(temp2); lsOffline.push_back(offlineFile); } delete resSet; } else { Mlog("no result for:%s", strSql.c_str()); } dbMag->freeTempConnect(dbConn); } else { Mlog("no db connection for gsgsslave"); } } //----------------------------------------------------------------------- void Model_File::addOfflineFile(uint32_t fromid, uint32_t toid, String & taskId, String & fileName, uint32_t fileSize) { DatabaseManager * dbMag = M_Only(DatabaseManager); DatabaseConnect * dbConn = dbMag->getTempConnect("gsgsmaster"); if (dbConn) { String strSql = "insert into IMTransmitFile (`fromId`,`toId`,`fileName`,`size`,`taskId`,`state`,`created`,`updated`) values(?,?,?,?,?,?,?,?)"; PrepareExec * pStmt = new PrepareExec(); if (pStmt->prepare(dbConn->getConnect(), strSql)) { uint32_t state = 0; uint32_t nCreated = (uint32_t)time(NULL); uint32_t index = 0; pStmt->setParam(index++, fromid); pStmt->setParam(index++, toid); pStmt->setParam(index++, fileName); pStmt->setParam(index++, fileSize); pStmt->setParam(index++, taskId); pStmt->setParam(index++, state); pStmt->setParam(index++, nCreated); pStmt->setParam(index++, nCreated); bool bRet = pStmt->exec(); if (!bRet) { Mlog("insert message failed: %s", strSql.c_str()); } } delete pStmt; dbMag->freeTempConnect(dbConn); } else { Mlog("no db connection for gsgsmaster"); } } //----------------------------------------------------------------------- void Model_File::deleteOfflineFile(uint32_t fromid, uint32_t toid, String & taskId) { DatabaseManager * dbMag = M_Only(DatabaseManager); DatabaseConnect * dbConn = dbMag->getTempConnect("gsgsmaster"); if (dbConn) { String strSql = "delete from IMTransmitFile where fromId=" + itostr(fromid) + " and toId=" + itostr(toid) + " and taskId='" + taskId + "'"; if (dbConn->exec(strSql.c_str())) { Mlog("delete offline file success.%d->%d:%s", fromid, toid, taskId.c_str()); } else { Mlog("delete offline file failed.%d->%d:%s", fromid, toid, taskId.c_str()); } dbMag->freeTempConnect(dbConn); } else { Mlog("no db connection for gsgsmaster"); } } //----------------------------------------------------------------------- }
42.711628
154
0.539584
suzhengquan
723e6aaad59bcfc5f04cde68e3bd5c4dda8fd5d8
1,145
cpp
C++
main/dashboard.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
2
2019-01-08T12:51:04.000Z
2019-01-08T12:51:04.000Z
main/dashboard.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
null
null
null
main/dashboard.cpp
lucasnunes/tcc_source
695610ec134d946694080fd2efae3f1dc41c2fa2
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2014 Lucas Nunes de Lima * * 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 "dashboard.hpp" #include "analog.hpp" #include "controller_io.hpp" #include <cstdlib> #include <string> #include <sstream> #include <cstdlib> namespace controller { namespace rest { std::string getValuesTo(const std::string& command, const std::string& param) { if(command == "inv_value") { int index = std::stoi(param); //Pin& pin = gpio::getPin(index); //pin.invertValue(); } return ""; } } }
26.627907
85
0.636681
lucasnunes
7241690856675888fdc257715c9d94e3c534ef4f
2,282
cpp
C++
codeforces/599E.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
codeforces/599E.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
codeforces/599E.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define N 100020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } ll dp[13][1<<13]; int ex[13], ey[13]; int ax[102], ay[102], az[102]; int n, m, q; bool mp[13][13]; inline bool in(int x, int s) { return s & (1 << x); } ll dfs(int u, int mask) { ll &res = dp[u][mask]; if (~res) return res; res = 0; mask ^= 1 << u; int pos = 0; while (pos < n) { if (in(pos, mask)) break; else ++ pos; } for (int submask = mask; submask; submask = (submask - 1) & mask) { if (in(pos, submask)) { int flag = 1, cnt = 0; for (int i = 1; i <= q; ++i) { if (az[i] == u && in(ax[i], submask) && in(ay[i], submask)) { flag = 0; break; } } for (int i = 1; i <= q; ++i) { if (in(az[i], submask) && (!in(ax[i], submask) || !in(ay[i], submask))) { flag = 0; break; } } for (int i = 1; i <= m; ++i) { if (ex[i] != u && ey[i] != u && (in(ex[i], submask) ^ in(ey[i], submask))) { flag = 0; break; } } int v = 0; for (int i = 0; i < n; ++i) { if (mp[u][i] && in(i, submask)) { ++cnt; v = i; } } if (!flag || cnt > 1) continue; if (cnt == 1) { res += dfs(v, submask) * dfs(u, mask ^ submask ^ (1 << u)); } else { for (v = 0; v < n; ++v) { if (in(v, submask)) { res += dfs(v, submask) * dfs(u, mask ^ submask ^ (1 << u)); } } } } } return res; } int main(int argc, char const *argv[]) { freopen("../tmp/.in", "r", stdin); n = read(), m = read(), q = read(); for (int i = 1; i <= m; ++i) { ex[i] = read() - 1; ey[i] = read() - 1; mp[ex[i]][ey[i]] = 1; mp[ey[i]][ex[i]] = 1; } for (int i = 1; i <= q; ++i) { ax[i] = read() - 1; ay[i] = read() - 1; az[i] = read() - 1; } memset(dp, -1, sizeof dp); for (int i = 0; i < n; ++i) { dp[i][1 << i] = 1; } printf("%lld\n", dfs(0, (1 << n) - 1)); return 0; }
23.285714
71
0.402279
swwind
72416e20b6daf9202ca650c6f209a92a71ecf810
3,968
cpp
C++
src/RK4Integrator.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
src/RK4Integrator.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
src/RK4Integrator.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
/* * RK4Integrator.cpp * * Created on: Jul 22, 2014 * Author: andy */ #include <RK4Integrator.h> #include <rrExecutableModel.h> extern "C" { #include <clapack/f2c.h> #include <clapack/clapack.h> } namespace rr { RK4Integrator::RK4Integrator(ExecutableModel *m, const SimulateOptions *o) { Log(Logger::LOG_NOTICE) << "creating runge-kutta integrator"; model = m; if (o) { opt = *o; } if (model) { stateVectorSize = model->getStateVector(NULL); k1 = new double[stateVectorSize]; k2 = new double[stateVectorSize]; k3 = new double[stateVectorSize]; k4 = new double[stateVectorSize]; y = new double[stateVectorSize]; ytmp = new double[stateVectorSize]; } else { stateVectorSize = 0; k1 = k2 = k3 = k4 = y = NULL; } } RK4Integrator::~RK4Integrator() { delete []k1; delete []k2; delete []k3; delete []k4; delete []y; delete []ytmp; } void RK4Integrator::setSimulateOptions(const SimulateOptions* options) { } double RK4Integrator::integrate(double t0, double h) { if (!model) { return -1; } Log(Logger::LOG_DEBUG) << "RK4Integrator::integrate(" << t0 << ", " << h << ")"; // blas daxpy: y -> y + \alpha x integer n = stateVectorSize; integer inc = 1; double alpha = 0; model->setTime(t0); model->getStateVector(y); // k1 = f(t_n, y_n) model->getStateVectorRate(t0, y, k1); // k2 = f(t_n + h/2, y_n + (h/2) * k_1) alpha = h/2.; dcopy_(&n, y, &inc, ytmp, &inc); daxpy_(&n, &alpha, k1, &inc, ytmp, &inc); model->getStateVectorRate(t0 + alpha, ytmp, k2); // k3 = f(t_n + h/2, y_n + (h/2) * k_2) alpha = h/2.; dcopy_(&n, y, &inc, ytmp, &inc); daxpy_(&n, &alpha, k2, &inc, ytmp, &inc); model->getStateVectorRate(t0 + alpha, ytmp, k3); // k4 = f(t_n + h, y_n + (h) * k_3) alpha = h; dcopy_(&n, y, &inc, ytmp, &inc); daxpy_(&n, &alpha, k3, &inc, ytmp, &inc); model->getStateVectorRate(t0 + alpha, ytmp, k4); // k_1 = k_1 + 2 k_2 alpha = 2.; daxpy_(&n, &alpha, k2, &inc, k1, &inc); // k_1 = (k_1 + 2 k_2) + 2 k_3 alpha = 2.; daxpy_(&n, &alpha, k3, &inc, k1, &inc); // k_1 = (k_1 + 2 k_2 + 2 k_3) + k_4 alpha = 1.; daxpy_(&n, &alpha, k4, &inc, k1, &inc); // y_{n+1} = (h/6)(k_1 + 2 k_2 + 2 k_3 + k_4); alpha = h/6.; daxpy_(&n, &alpha, k1, &inc, y, &inc); model->setTime(t0 + h); model->setStateVector(y); return t0 + h; } void RK4Integrator::restart(double t0) { } void RK4Integrator::setListener(IntegratorListenerPtr) { } IntegratorListenerPtr RK4Integrator::getListener() { return IntegratorListenerPtr(); } std::string RK4Integrator::toString() const { return toRepr(); } std::string RK4Integrator::toRepr() const { std::stringstream ss; ss << "< roadrunner.RK4Integrator() { 'this' : " << (void*)this << " }>"; return ss.str(); } std::string RK4Integrator::getName() const { return "rk4"; } void RK4Integrator::setItem(const std::string& key, const rr::Variant& value) { throw std::invalid_argument("invalid key"); } Variant RK4Integrator::getItem(const std::string& key) const { throw std::invalid_argument("invalid key"); } bool RK4Integrator::hasKey(const std::string& key) const { return false; } int RK4Integrator::deleteItem(const std::string& key) { return -1; } std::vector<std::string> RK4Integrator::getKeys() const { return std::vector<std::string>(); } const Dictionary* RK4Integrator::getIntegratorOptions() { // static instance static SimulateOptions opt; // defaults could have changed, so re-load them. opt = SimulateOptions(); opt.setItem("integrator", "rk4"); opt.setItem("integrator.description", "rk4 description"); opt.setItem("integrator.hint", "rk4 hint"); return &opt; } } /* namespace rr */
20.666667
74
0.590726
gitter-badger
724200aec014f9fed920f59d271ef751f882b96a
809
hpp
C++
src/model/Object.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
src/model/Object.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
src/model/Object.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
// // Created by Victor Vasiliev on 11/4/17. // #ifndef FT_RETRO_OBJECT_HPP #define FT_RETRO_OBJECT_HPP #include <string> #include "Position.hpp" namespace Model { class Object { protected: const std::string name; Model::Position position; bool isDestroyed; bool isNotIntersection; public: Object(); virtual ~Object(); explicit Object(const std::string &name, Model::Position position); Object(const Object &rhs); Object&operator=(const Object &rhs); const Model::Position& getPosition() const; const std::string& getName() const; void setPosition(Model::Position &position); bool isDestroy(); void destroy(); bool isIntersect(const Object &object); void setNotIntersection(bool notIntersection); bool isIsNotIntersection() const; }; } #endif //FT_RETRO_OBJECT_HPP
21.289474
69
0.730532
Vict0rynox
72445ea49f2159927813b1208056f7637cc1251b
6,815
hpp
C++
src/EngineImpl/EngineObjectSerilization.hpp
cyf-gh/HoneyGame
2448f4574c6e1a847f1395d97a3186d79b499b22
[ "MIT" ]
3
2021-11-27T01:24:26.000Z
2021-12-31T07:17:38.000Z
src/EngineImpl/EngineObjectSerilization.hpp
cyf-gh/HGEngine
2448f4574c6e1a847f1395d97a3186d79b499b22
[ "MIT" ]
null
null
null
src/EngineImpl/EngineObjectSerilization.hpp
cyf-gh/HGEngine
2448f4574c6e1a847f1395d97a3186d79b499b22
[ "MIT" ]
1
2021-10-01T07:18:58.000Z
2021-10-01T07:18:58.000Z
#pragma once #include <Serialization.h> #include <Memory.h> #include "EngineImpl.h" #include "Scene.h" #include "Transform.hpp" #include "Animation.h" #include "Collision.h" #include "Timer.hpp" #include "RigidBody.h" namespace HGEngine { namespace V1SDL { class GameObjectFactory : HG::Memory::NonCopyable { public: template<typename _T> HG_INLINE static _T* CreateByJson( std::string& strJson, const bool isEnable, const char* strObjNewName = "", const char* strObjKey = "Obj" ) { rapidjson::Document d; d.Parse( strJson.c_str() ); if( d.HasParseError() ) { HG_LOG_FAILED( std::format( "Parse Error: {}", std::to_string( d.GetParseError() ) ).c_str() ); return nullptr; } _T* g = new _T(); HG::Serialization::Unmarshal( ( GameObject& ) *g, strObjKey, d[strObjKey], d ); if( strcmp( strObjNewName, "" ) != 0 ) { g->SetName( strObjNewName ); } auto ps = HGEngine::V1SDL::EngineImpl::GetEngine()->GetCurrentScene(); if( ps != nullptr ) { ps->AttachGameObject( g ); } if( isEnable ) { g->Enable(); } return g; } }; } } namespace HG { namespace Serialization { HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Transform ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.f64Angle ); HG_MARSHAL_OBJECT_SETPROP( t.tLocalPos ); HG_MARSHAL_OBJECT_SETPROP( t.tLocalRect ); HG_MARSHAL_OBJECT_SETPROP( t.tPosition ); HG_MARSHAL_OBJECT_SETPROP( t.tRect ); HG_MARSHAL_OBJECT_SETPROP( t.tRotateCenter ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Transform ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.f64Angle ); HG_UNMARSHAL_GETOBJ( t.tLocalPos ); HG_UNMARSHAL_GETOBJ( t.tLocalRect ); HG_UNMARSHAL_GETOBJ( t.tPosition ); HG_UNMARSHAL_GETOBJ( t.tRect ); HG_UNMARSHAL_GETOBJ( t.tRotateCenter ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D::Frame ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.tPos ); HG_MARSHAL_OBJECT_SETPROP( t.tRect ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D::Frame ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.tPos ); HG_UNMARSHAL_GETOBJ( t.tRect ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.Col ); HG_MARSHAL_OBJECT_SETPROP( t.Row ); HG_MARSHAL_OBJECT_SETPROP( t.f32Interval ); HG_MARSHAL_OBJECT_SETPROP( t.IsIdle ); HG_MARSHAL_OBJECT_SETPROP( t.m_unIdleFrameIndex ); HG_MARSHAL_OBJECT_SETPROP( t.m_vecFrames ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Animator2D ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.Col ); HG_UNMARSHAL_GETOBJ( t.Row ); HG_UNMARSHAL_GETOBJ( t.f32Interval ); HG_UNMARSHAL_GETOBJ( t.IsIdle ); HG_UNMARSHAL_GETOBJ( t.m_unIdleFrameIndex ); HG_UNMARSHAL_GETOBJ( t.m_vecFrames ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::Timer ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.Active ); HG_MARSHAL_OBJECT_SETPROP( t.f32Delay ); HG_MARSHAL_OBJECT_SETPROP( t.f32DelayRest ); HG_MARSHAL_OBJECT_SETPROP( t.f32Elapsed ); HG_MARSHAL_OBJECT_SETPROP( t.f32ElpasedLoop ); HG_MARSHAL_OBJECT_SETPROP( t.f32Interval ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::Timer ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.Active ); HG_UNMARSHAL_GETOBJ( t.f32Delay ); HG_UNMARSHAL_GETOBJ( t.f32DelayRest ); HG_UNMARSHAL_GETOBJ( t.f32Elapsed ); HG_UNMARSHAL_GETOBJ( t.f32ElpasedLoop ); HG_UNMARSHAL_GETOBJ( t.f32Interval ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::RigidBody ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.AngularDrag ); HG_MARSHAL_OBJECT_SETPROP( t.GravityDrag ); HG_MARSHAL_OBJECT_SETPROP( t.IsFrozen ); HG_MARSHAL_OBJECT_SETPROP( t.LinearDrag ); HG_MARSHAL_OBJECT_SETPROP( t.Mass ); HG_MARSHAL_OBJECT_SETPROP( t.Velocity ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::RigidBody ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.AngularDrag ); HG_UNMARSHAL_GETOBJ( t.GravityDrag ); HG_UNMARSHAL_GETOBJ( t.IsFrozen ); HG_UNMARSHAL_GETOBJ( t.LinearDrag ); HG_UNMARSHAL_GETOBJ( t.Mass ); HG_UNMARSHAL_GETOBJ( t.Velocity ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::BoxCollision ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_OBJECT_SETPROP( t.Rect ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::BoxCollision ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.Rect ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( HGEngine::V1SDL::GameObject ) { HG_MARSHAL_OBJECT_START; auto n = std::string( t.GetName() ); Marshal( n, "Name", writer ); Marshal( t.m_vecComponents, "Components", writer ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HGEngine::V1SDL::GameObject ) { HG_UNMARSHAL_OBJECT_START; std::string Name; HG_UNMARSHAL_GETOBJ( Name ); t.SetName( Name.c_str() ); Unmarshal( t.m_vecComponents, "Components", d["Components"], rd ); for( auto& c : t.m_vecComponents ) { c->SetGameObject( &t ); } HG_UNMARSHAL_OBJECT_END; } #define HG_UNMARSHAL_COMPONENT( COMP_TYPE, NODE_NAME ) \ if( d.HasMember( NODE_NAME ) ) { \ t = new COMP_TYPE(NODE_NAME); \ Unmarshal( *static_cast< COMP_TYPE* >( t ), NODE_NAME, d[NODE_NAME], rd ); \ goto END; \ } #define HG_MARSHAL_GAMEOBJECTSETPROP( COMP_TYPE, NODE_NAME ) \ if( typeid( COMP_TYPE ).hash_code() == typeid( *t ).hash_code() ) { \ Marshal( *static_cast< COMP_TYPE* >( t ), NODE_NAME, writer ); \ } HG_MARSHAL_FULLSPEC( HG::HGComponent* ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::Transform, "Transform" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::Animator2D, "Animator2D" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::RigidBody, "RigidBody" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::BoxCollision, "BoxCollision" ); HG_MARSHAL_GAMEOBJECTSETPROP( HGEngine::V1SDL::Timer, "Timer" ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( HG::HGComponent* ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::Transform, "Transform" ); HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::Animator2D, "Animator2D" ); HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::RigidBody, "RigidBody" ); HG_UNMARSHAL_COMPONENT( HGEngine::V1SDL::BoxCollision, "BoxCollision" ); HG_UNMARSHAL_OBJECT_END; } HG_MARSHAL_FULLSPEC( SDL_Color ) { HG_MARSHAL_OBJECT_START; HG_MARSHAL_SETOBJ( t.a ); HG_MARSHAL_SETOBJ( t.r ); HG_MARSHAL_SETOBJ( t.g ); HG_MARSHAL_SETOBJ( t.b ); HG_MARSHAL_OBJECT_END; } HG_UNMARSHAL_FULLSPEC( SDL_Color ) { HG_UNMARSHAL_OBJECT_START; HG_UNMARSHAL_GETOBJ( t.a ); HG_UNMARSHAL_GETOBJ( t.r ); HG_UNMARSHAL_GETOBJ( t.g ); HG_UNMARSHAL_GETOBJ( t.b ); HG_UNMARSHAL_OBJECT_END; } } }
29.375
144
0.759208
cyf-gh
724da682e8d7cd313ec97c14438a25c420bf930b
5,838
cpp
C++
src/nvilidar_node.cpp
nvilidar/nvilidar_ros
dc03c44e581cb328f6dbdd23f63344c0e6a73d4b
[ "BSD-3-Clause" ]
null
null
null
src/nvilidar_node.cpp
nvilidar/nvilidar_ros
dc03c44e581cb328f6dbdd23f63344c0e6a73d4b
[ "BSD-3-Clause" ]
1
2021-11-22T06:44:48.000Z
2021-12-09T02:53:01.000Z
src/nvilidar_node.cpp
nvilidar/nvilidar_ros
dc03c44e581cb328f6dbdd23f63344c0e6a73d4b
[ "BSD-3-Clause" ]
null
null
null
#include "ros/ros.h" #include <vector> #include <iostream> #include <string.h> #include "sensor_msgs/LaserScan.h" #include "nvilidar_process.h" #include "nvilidar_def.h" using namespace nvilidar; #define ROSVerision "1.0.8" int main(int argc, char * argv[]) { ros::init(argc, argv, "nvilidar_node"); printf(" _ ___ _______ _ _____ _____ _____ \n"); printf("| \\ | \\ \\ / /_ _| | |_ _| __ \\ /\\ | __ \\\n"); printf("| \\| |\\ \\ / / | | | | | | | | | | / \\ | |__) |\n"); printf("| . ` | \\ \\/ / | | | | | | | | | |/ /\\ \\ | _ / \n"); printf("| |\\ | \\ / _| |_| |____ _| |_| |__| / ____ \\| | \\ \\\n"); printf("|_| \\_| \\/ |_____|______|_____|_____/_/ \\_\\_| \\ \\\n"); printf("\n"); fflush(stdout); ros::NodeHandle nh; ros::Publisher scan_pub = nh.advertise<sensor_msgs::LaserScan>("scan", 1000); ros::NodeHandle nh_private("~"); Nvilidar_UserConfigTypeDef cfg; bool use_socket = false; //默认不用socket //读取雷达配置 从rviz文件内 如果里面有配置对应参数 则走里面的数据。如果没有,则直接取函数第3个默认参数配置信息 nh_private.param<std::string>("serialport_name", cfg.serialport_name, "dev/nvilidar"); nh_private.param<int>("serialport_baud", cfg.serialport_baud, 921600); nh_private.param<std::string>("ip_addr", cfg.ip_addr, "192.168.1.200"); nh_private.param<int>("lidar_udp_port", cfg.lidar_udp_port, 8100); nh_private.param<int>("config_tcp_port", cfg.config_tcp_port, 8200); nh_private.param<std::string>("frame_id", cfg.frame_id, "laser_frame"); nh_private.param<bool>("resolution_fixed", cfg.resolution_fixed, true); nh_private.param<bool>("auto_reconnect", cfg.auto_reconnect, false); nh_private.param<bool>("reversion", cfg.reversion, false); nh_private.param<bool>("inverted", cfg.inverted, false); nh_private.param<double>("angle_max", cfg.angle_max , 180.0); nh_private.param<double>("angle_min", cfg.angle_min , -180.0); nh_private.param<double>("range_max", cfg.range_max , 64.0); nh_private.param<double>("range_min", cfg.range_min , 0.0); nh_private.param<double>("aim_speed", cfg.aim_speed , 10.0); nh_private.param<int>("sampling_rate", cfg.sampling_rate, 10000); nh_private.param<bool>("sensitive", cfg.sensitive, false); nh_private.param<int>("tailing_level", cfg.tailing_level, 6); nh_private.param<double>("angle_offset", cfg.angle_offset, 0.0); nh_private.param<bool>("apd_change_flag", cfg.apd_change_flag, false); nh_private.param<int>("apd_value", cfg.apd_value, 500); nh_private.param<bool>("single_channel", cfg.single_channel, false); nh_private.param<std::string>("ignore_array_string", cfg.ignore_array_string, ""); //过滤参数 nh_private.param<bool>("filter_jump_enable", cfg.filter_jump_enable, true); nh_private.param<int>("filter_jump_value_min", cfg.filter_jump_value_min, 3); nh_private.param<int>("filter_jump_value_max", cfg.filter_jump_value_max, 50); //更新数据 用网络或者串口 #if 1 nvilidar::LidarProcess laser(USE_SERIALPORT,cfg.serialport_name,cfg.serialport_baud); #else nvilidar::LidarProcess laser(USE_SOCKET,cfg.ip_addr, cfg.lidar_udp_port); #endif //根据配置 重新加载参数 laser.LidarReloadPara(cfg); ROS_INFO("[NVILIDAR INFO] Now NVILIDAR ROS SDK VERSION:%s .......", ROSVerision); //初始化 变量定义 bool ret = laser.LidarInitialialize(); if (ret) { //启动雷达 ret = laser.LidarTurnOn(); if (!ret) { ROS_ERROR("Failed to start Scan!!!"); } } else { ROS_ERROR("Error initializing NVILIDAR Comms and Status!!!"); } ros::Rate rate(50); LidarScan scan; while (ret && ros::ok()) { if(laser.LidarSamplingProcess(scan)) { if(scan.points.size() > 0) { sensor_msgs::LaserScan scan_msg; ros::Time start_scan_time; start_scan_time.sec = scan.stamp/1000000000ul; start_scan_time.nsec = scan.stamp%1000000000ul; scan_msg.header.stamp = start_scan_time; scan_msg.header.frame_id = cfg.frame_id; scan_msg.angle_min =(scan.config.min_angle); scan_msg.angle_max = (scan.config.max_angle); scan_msg.angle_increment = (scan.config.angle_increment); scan_msg.scan_time = scan.config.scan_time; scan_msg.time_increment = scan.config.time_increment; scan_msg.range_min = (scan.config.min_range); scan_msg.range_max = (scan.config.max_range); int size = (scan.config.max_angle - scan.config.min_angle)/ scan.config.angle_increment + 1; scan_msg.ranges.resize(size); scan_msg.intensities.resize(size); for(int i=0; i < scan.points.size(); i++) { int index = std::ceil((scan.points[i].angle - scan.config.min_angle)/scan.config.angle_increment); if(index >=0 && index < size) { scan_msg.ranges[index] = scan.points[i].range; scan_msg.intensities[index] = scan.points[i].intensity; } } scan_pub.publish(scan_msg); } else { ROS_WARN("Lidar Data Invalid!"); } } else //未收到数据 超过15次 则报错 { ROS_ERROR("Failed to get Lidar Data!"); break; } ros::spinOnce(); rate.sleep(); } laser.LidarTurnOff(); printf("[NVILIDAR INFO] Now NVILIDAR is stopping .......\n"); laser.LidarCloseHandle(); return 0; }
41.112676
118
0.585988
nvilidar
724fc2230c9f69d15e2f4c82f8bf86e1f3e1dc55
1,113
cpp
C++
aws-cpp-sdk-chime/source/model/InviteUsersResult.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-chime/source/model/InviteUsersResult.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-chime/source/model/InviteUsersResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/chime/model/InviteUsersResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Chime::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; InviteUsersResult::InviteUsersResult() { } InviteUsersResult::InviteUsersResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } InviteUsersResult& InviteUsersResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("Invites")) { Array<JsonView> invitesJsonList = jsonValue.GetArray("Invites"); for(unsigned invitesIndex = 0; invitesIndex < invitesJsonList.GetLength(); ++invitesIndex) { m_invites.push_back(invitesJsonList[invitesIndex].AsObject()); } } return *this; }
25.295455
102
0.747529
Neusoft-Technology-Solutions
725166c08c6ed5f09f09afe22b10f3f4f85f1714
1,490
cc
C++
elec/DVThreshSensor.cc
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
33
2018-12-12T20:05:06.000Z
2021-09-26T13:30:16.000Z
elec/DVThreshSensor.cc
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
5
2019-04-25T11:34:43.000Z
2021-11-14T04:35:37.000Z
elec/DVThreshSensor.cc
paulkefer/cardioid
59c07b714d8b066b4f84eb50487c36f6eadf634c
[ "MIT-0", "MIT" ]
15
2018-12-21T22:44:59.000Z
2021-08-29T10:30:25.000Z
#include "DVThreshSensor.hh" #include "Simulate.hh" DVThreshSensor::DVThreshSensor(const SensorParms& sp, const Anatomy& anatomy, const PotentialData& vdata, MPI_Comm comm) : Sensor(sp), vdata_(vdata), comm_(comm) { MPI_Comm comm_ = MPI_COMM_WORLD; MPI_Comm_rank(comm_, &myRank_); nlocal_=anatomy.nLocal(); threshold_ = sp.value; } void DVThreshSensor::eval(double time, int loop) { double maxdVdt=-10000.; double mindVdt= 10000.; ro_array_ptr<double> dVmDiffusion = vdata_.dVmDiffusionTransport_.useOn(CPU); ro_array_ptr<double> dVmReaction = vdata_.dVmReactionTransport_.useOn(CPU); for (unsigned ii=0; ii<nlocal_; ++ii) { double dVdt=dVmReaction[ii]+dVmDiffusion[ii]; if( dVdt>maxdVdt ) { maxdVdt=dVdt; } if( dVdt<mindVdt ) { mindVdt=dVdt; } } double maxMaxdVdt=0.; MPI_Reduce(&maxdVdt, &maxMaxdVdt, 1, MPI_DOUBLE, MPI_MAX, 0, comm_); double minMindVdt=0.; MPI_Reduce(&mindVdt, &minMindVdt, 1, MPI_DOUBLE, MPI_MIN, 0, comm_); // if abs of max and min are both less than sp.value, stop simulation if (fabs(maxMaxdVdt) < threshold_ && fabs(minMindVdt) < threshold_) { if (myRank_ == 0) std::cout << "DVThreshold sensor: maxdVdt = " << maxMaxdVdt << ", mindVdt = " << minMindVdt << ", threshold = " << threshold_ << " reached." << std::endl; exit(1); } }
29.215686
164
0.614765
paulkefer
725277bad64b39c1f3b6854a6039d141cbdcae56
1,199
cpp
C++
1-10/Euler7.cpp
Adhesh148/Euler-Project
857fe666b267a8bc156b2d4b8e54260f53ccd158
[ "MIT" ]
2
2020-08-09T17:17:27.000Z
2020-08-10T01:13:07.000Z
1-10/Euler7.cpp
Adhesh148/Euler-Project
857fe666b267a8bc156b2d4b8e54260f53ccd158
[ "MIT" ]
null
null
null
1-10/Euler7.cpp
Adhesh148/Euler-Project
857fe666b267a8bc156b2d4b8e54260f53ccd158
[ "MIT" ]
null
null
null
/****************************************** * AUTHOR : AdheshR* * Problem Statement: What is the Nth prime number? * Comment: Require faster method. Does not pass all test cases. Times out. ******************************************/ #include <bits/stdc++.h> using namespace std; long long int findNPrime(int N); bool isPrime(long long int n) ; int main() { int T; cin>>T; for(int i=0;i<T;++i) { int N; cin>>N; long long int Nprime = findNPrime(N); cout<<Nprime<<endl; } } long long int findNPrime(int N) { if(N == 1) return 2; if(N == 2) return 3; int count = 2; long int k = 1; while(count!=N) { long long int guess1 = 6*k - 1; long long int guess2 = 6*k + 1; ++k; if(isPrime(guess1) && ++count == N) return guess1; if(isPrime(guess2) && ++ count == N) return guess2; } } bool isPrime(long long int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; }
18.734375
74
0.526272
Adhesh148
725444c0d5869bff73466e01917be6549a8cb9d4
1,312
cpp
C++
debug/atomics/qss/sin_function.cpp
jorexe/haikunet
dd1697fdc4590de8d687816ec470e40193619b8f
[ "MIT" ]
2
2021-05-05T18:22:19.000Z
2022-01-21T13:50:27.000Z
debug/atomics/qss/sin_function.cpp
jorexe/haikunet
dd1697fdc4590de8d687816ec470e40193619b8f
[ "MIT" ]
null
null
null
debug/atomics/qss/sin_function.cpp
jorexe/haikunet
dd1697fdc4590de8d687816ec470e40193619b8f
[ "MIT" ]
1
2021-05-05T18:05:11.000Z
2021-05-05T18:05:11.000Z
#include "sin_function.h" void sin_function::init(double t,...) { va_list parameters; va_start(parameters, t); sigma=INF; for (int i=0;i<10;i++){ y[i]=0; u[i]=0; }; order=1; } double sin_function::ta(double t) { return sigma; } void sin_function::dint(double t) { sigma=INF; } void sin_function::dext(Event x, double t) { double *xv; xv=(double*)(x.value); switch(order){ case 1: u[0]=xv[0]; if (xv[1]!=0){order=2;u[1]=xv[1];} if (xv[2]!=0){order=3;u[2]=xv[2];} if (xv[3]!=0){order=4;u[3]=xv[3];} break; case 2: u[0]=xv[0]; u[1]=xv[1]; if (xv[2]!=0){order=3;u[2]=xv[2];} if (xv[3]!=0){order=4;u[3]=xv[3];} break; case 3: u[0]=xv[0]; u[1]=xv[1]; u[2]=xv[2]; if (xv[3]!=0){order=4;u[3]=xv[3];} break; case 4: u[0]=xv[0]; u[1]=xv[1]; u[2]=xv[2]; u[3]=xv[3]; } sigma=0; } Event sin_function::lambda(double t) { switch(order){ case 1: y[0]=sin(u[0]); break; case 2: y[0]=sin(u[0]); y[1]=cos(u[0])*u[1]; break; case 3: y[0]=sin(u[0]); y[1]=cos(u[0])*u[1]; y[2]=-sin(u[0])*u[1]*u[1]/2+cos(u[0])*u[2]; break; case 4: y[0]=sin(u[0]); y[1]=cos(u[0])*u[1]; y[2]=-sin(u[0])*u[1]*u[1]/2+cos(u[0])*u[2]; y[3]=-cos(u[0])*pow(u[1],3)/6-sin(u[0])*u[1]*u[2]+cos(u[0])*u[3]; } return Event(y,0); } void sin_function::exit() { }
17.263158
67
0.51753
jorexe
72552a27087650526330ce8bc4cddfc193cba1fd
6,282
cpp
C++
samples/old/sample_condens_tracking.cpp
gtmtg/cvdrone
ef736dc7a2a1a806f7cea4088268e439e53c1f33
[ "BSD-3-Clause" ]
1
2015-01-04T16:22:31.000Z
2015-01-04T16:22:31.000Z
cvdrone/samples/old/sample_condens_tracking.cpp
MLHCoderTeam/ARDrone
b7b51a2e8c172944c04e7b64bb792b68931e6d3f
[ "MIT" ]
null
null
null
cvdrone/samples/old/sample_condens_tracking.cpp
MLHCoderTeam/ARDrone
b7b51a2e8c172944c04e7b64bb792b68931e6d3f
[ "MIT" ]
1
2018-02-28T17:29:35.000Z
2018-02-28T17:29:35.000Z
#include "ardrone/ardrone.h" #include "opencv2/legacy/legacy.hpp" #include "opencv2/legacy/compat.hpp" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char **argv) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { printf("Failed to initialize.\n"); return -1; } // Particle filter CvConDensation *con = cvCreateConDensation(4, 0, 3000); // Setup CvMat *lowerBound = cvCreateMat(4, 1, CV_32FC1); CvMat *upperBound = cvCreateMat(4, 1, CV_32FC1); cvmSet(lowerBound, 0, 0, 0); cvmSet(lowerBound, 1, 0, 0); cvmSet(lowerBound, 2, 0, -10); cvmSet(lowerBound, 3, 0, -10); cvmSet(upperBound, 0, 0, ardrone.getImage()->width); cvmSet(upperBound, 1, 0, ardrone.getImage()->height); cvmSet(upperBound, 2, 0, 10); cvmSet(upperBound, 3, 0, 10); // Initialize particle filter cvConDensInitSampleSet(con, lowerBound, upperBound); // Linear system con->DynamMatr[0] = 1.0; con->DynamMatr[1] = 0.0; con->DynamMatr[2] = 1.0; con->DynamMatr[3] = 0.0; con->DynamMatr[4] = 0.0; con->DynamMatr[5] = 1.0; con->DynamMatr[6] = 0.0; con->DynamMatr[7] = 1.0; con->DynamMatr[8] = 0.0; con->DynamMatr[9] = 0.0; con->DynamMatr[10] = 1.0; con->DynamMatr[11] = 0.0; con->DynamMatr[12] = 0.0; con->DynamMatr[13] = 0.0; con->DynamMatr[14] = 0.0; con->DynamMatr[15] = 1.0; // Noises cvRandInit(&(con->RandS[0]), -25, 25, (int)cvGetTickCount()); cvRandInit(&(con->RandS[1]), -25, 25, (int)cvGetTickCount()); cvRandInit(&(con->RandS[2]), -5, 5, (int)cvGetTickCount()); cvRandInit(&(con->RandS[3]), -5, 5, (int)cvGetTickCount()); // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // Create a window cvNamedWindow("binalized"); cvCreateTrackbar("H max", "binalized", &maxH, 255); cvCreateTrackbar("H min", "binalized", &minH, 255); cvCreateTrackbar("S max", "binalized", &maxS, 255); cvCreateTrackbar("S min", "binalized", &minS, 255); cvCreateTrackbar("V max", "binalized", &maxV, 255); cvCreateTrackbar("V min", "binalized", &minV, 255); cvResizeWindow("binalized", 0, 0); // Main loop while (1) { // Key input int key = cvWaitKey(1); if (key == 0x1b) break; // Update if (!ardrone.update()) break; // Get an image IplImage *image = ardrone.getImage(); // HSV image IplImage *hsv = cvCloneImage(image); cvCvtColor(image, hsv, CV_RGB2HSV_FULL); // Binalized image IplImage *binalized = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1); // Binalize CvScalar lower = cvScalar(minH, minS, minV); CvScalar upper = cvScalar(maxH, maxS, maxV); cvInRangeS(hsv, lower, upper, binalized); // Show result cvShowImage("binalized", binalized); // De-noising cvMorphologyEx(binalized, binalized, NULL, NULL, CV_MOP_CLOSE); // Detect contours CvSeq *contour = NULL, *maxContour = NULL; CvMemStorage *contourStorage = cvCreateMemStorage(); cvFindContours(binalized, contourStorage, &contour, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find largest contour double max_area = 0.0; while (contour) { double area = fabs(cvContourArea(contour)); if ( area > max_area) { maxContour = contour; max_area = area; } contour = contour->h_next; } // Object detected if (maxContour) { // Draw a contour cvZero(binalized); cvDrawContours(binalized, maxContour, cvScalarAll(255), cvScalarAll(255), 0, CV_FILLED); // Calculate the moments CvMoments moments; cvMoments(binalized, &moments, 1); int my = (int)(moments.m01/moments.m00); int mx = (int)(moments.m10/moments.m00); cvCircle(image, cvPoint(mx, my), 10, CV_RGB(255,0,0)); // Calculate confidences for (int i = 0; i < con->SamplesNum; i++) { // Sample points float x = (con->flSamples[i][0]); float y = (con->flSamples[i][1]); // Valid sample point if (x > 0 && x < image->width && y > 0 && y < image->height) { // Assume as gauss distribution double sigma = 50.0; double dist = hypot(x - mx, y - my); // Distance to moment con->flConfidence[i] = 1.0 / (sqrt (2.0 * CV_PI) * sigma) * expf (-dist*dist / (2.0 * sigma*sigma)); } else con->flConfidence[i] = 0.0; cvCircle(image, cvPointFrom32f(cvPoint2D32f(x, y)), 3, CV_RGB(0,128,con->flConfidence[i] * 50000)); } } // Update phase cvConDensUpdateByTime(con); // Sum of positions and confidences for calcurate weighted mean value double sumX = 0, sumY = 0, sumConf = 0; for (int i = 0; i < con->SamplesNum; i++) { sumX += con->flConfidence[i] * con->flSamples[i][0]; sumY += con->flConfidence[i] * con->flSamples[i][1]; sumConf += con->flConfidence[i]; } // Estimated value if (sumConf > 0.0) { float x = sumX / sumConf; float y = sumY / sumConf; cvCircle(image, cvPointFrom32f(cvPoint2D32f(x, y)), 10, CV_RGB(0,255,0)); } // Display the image cvShowImage("camera", image); // Release memories cvReleaseImage(&hsv); cvReleaseImage(&binalized); cvReleaseMemStorage(&contourStorage); } // Release the particle filter cvReleaseMat(&lowerBound); cvReleaseMat(&upperBound); cvReleaseConDensation(&con); // See you ardrone.close(); return 0; }
35.094972
121
0.550143
gtmtg
72567483a939e0c7e0b7ecd1f4f8ac8eab46d3d9
2,682
cpp
C++
src/pool.cpp
yudhik11/OpenGL-LOZ
c1add7b09df2b99e1c82c21b56ba18b1cf7c4846
[ "MIT" ]
1
2019-08-29T02:01:20.000Z
2019-08-29T02:01:20.000Z
src/pool.cpp
yudhik11/OpenGL-LOZ
c1add7b09df2b99e1c82c21b56ba18b1cf7c4846
[ "MIT" ]
null
null
null
src/pool.cpp
yudhik11/OpenGL-LOZ
c1add7b09df2b99e1c82c21b56ba18b1cf7c4846
[ "MIT" ]
null
null
null
#include "pool.h" #include "main.h" Pool::Pool(float x, float y, color_t color) { this->position = glm::vec3(x, y, 0); this->rotation = 0; this->angular_speed = 0.5; this->level_angle = 0; speed = 0.2; static const GLfloat vertex_buffer_data[] = { -12345,-12345,-12345, -12345,-12345, 12345, -12345, 12345, 12345, 12345, 12345,-12345, -12345,-12345,-12345, -12345, 12345,-12345, 12345,-12345, 12345, -12345,-12345,-12345, 12345,-12345,-12345, 12345, 12345,-12345, 12345,-12345,-12345, -12345,-12345,-12345, -12345,-12345,-12345, -12345, 12345, 12345, -12345, 12345,-12345, 12345,-12345, 12345, -12345,-12345, 12345, -12345,-12345,-12345, -12345, 12345, 12345, -12345,-12345, 12345, 12345,-12345, 12345, 12345, 12345, 12345, 12345,-12345,-12345, 12345, 12345,-12345, 12345,-12345,-12345, 12345, 12345, 12345, 12345,-12345, 12345, 12345, 12345, 12345, 12345, 12345,-12345, -12345, 12345,-12345, 12345, 12345, 12345, -12345, 12345,-12345, -12345, 12345, 12345, 12345, 12345, 12345, -12345, 12345, 12345, 12345,-12345, 12345 }; this->object = create3DObject(GL_TRIANGLES, 12*3, vertex_buffer_data, color, GL_FILL); } void Pool::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0)); glm::mat4 rotate2 = glm::rotate((float) (this->level_angle * M_PI / 180.0f), glm::vec3( this->position.x, this->position.y, this->position.z)); Matrices.model *= (translate * rotate * rotate2); glm::mat4 MVP = VP * Matrices.model; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniform1f(Matrices.Transparency, 0.75); draw3DObject(this->object); glDisable(GL_BLEND); } void Pool::set_position(float x, float y) { this->position = glm::vec3(x, y, 0); } void Pool::shm(){ if(level_angle < -10.0f || level_angle > 10.0f){ angular_speed = -angular_speed; } this->level_angle += angular_speed; } void Pool::tick() { // this->rotation += speed; // this->position.x -= speed; // this->position.y -= speed; }
31.552941
100
0.55481
yudhik11
725848bbef08765ee3c2fd3a438ff55a57a816d3
314
cpp
C++
src/HttpException.cpp
Andreev-Sergey/diadocsdk-cpp
01d9fa2b90bc6f42ef3d9c20f29207b3a5bf6eda
[ "MIT" ]
7
2016-05-31T17:37:54.000Z
2022-01-17T14:28:18.000Z
src/HttpException.cpp
Andreev-Sergey/diadocsdk-cpp
01d9fa2b90bc6f42ef3d9c20f29207b3a5bf6eda
[ "MIT" ]
22
2017-02-07T09:34:02.000Z
2021-09-06T08:08:34.000Z
src/HttpException.cpp
Andreev-Sergey/diadocsdk-cpp
01d9fa2b90bc6f42ef3d9c20f29207b3a5bf6eda
[ "MIT" ]
23
2016-06-07T06:11:47.000Z
2020-10-06T13:00:21.000Z
#include "StdAfx.h" #include "HttpException.h" HttpException::HttpException(const std::string& message, DWORD statusCode, const std::string& serverMessage) : std::runtime_error(message + ": " + serverMessage) , StatusCode(statusCode) , ServerMessage(serverMessage) { } HttpException::~HttpException(void) { }
22.428571
108
0.751592
Andreev-Sergey
725925ee10fb01c182f23a7f473aae8e5d04e469
1,832
hpp
C++
DocTypeNode.hpp
chrisoldwood/XML
78913e7b9fbc1fbfec3779652d034ebd150668bc
[ "MIT" ]
1
2020-09-11T13:21:05.000Z
2020-09-11T13:21:05.000Z
DocTypeNode.hpp
chrisoldwood/XML
78913e7b9fbc1fbfec3779652d034ebd150668bc
[ "MIT" ]
null
null
null
DocTypeNode.hpp
chrisoldwood/XML
78913e7b9fbc1fbfec3779652d034ebd150668bc
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// //! \file DocTypeNode.hpp //! \brief The DocTypeNode class declaration. //! \author Chris Oldwood // Check for previous inclusion #ifndef XML_DOCTYPENODE_HPP #define XML_DOCTYPENODE_HPP #if _MSC_VER > 1000 #pragma once #endif #include "Node.hpp" namespace XML { //////////////////////////////////////////////////////////////////////////////// //! The XML node type used for the document type. The document type details are //! stored as a single string and not parsed. class DocTypeNode : public Node { public: //! Default constructor. DocTypeNode(); //! Construction from a string declaration. DocTypeNode(const tstring& declaration); // // Properties // //! Get the real type of the node. virtual NodeType type() const; //! Get the declaration. const tstring& declaration() const; //! Set the declaration. void setDeclaration(const tstring& declaration); private: // // Members. // tstring m_declaration; //!< The string declaration. //! Destructor. virtual ~DocTypeNode(); }; //! The default DocType smart-pointer type. typedef Core::RefCntPtr<DocTypeNode> DocTypeNodePtr; //////////////////////////////////////////////////////////////////////////////// //! Get the real type of the node. inline NodeType DocTypeNode::type() const { return DOCTYPE_NODE; } //////////////////////////////////////////////////////////////////////////////// //! Get the declaration. inline const tstring& DocTypeNode::declaration() const { return m_declaration; } //////////////////////////////////////////////////////////////////////////////// //! Set the declaration. inline void DocTypeNode::setDeclaration(const tstring& declaration_) { m_declaration = declaration_; } //namespace XML } #endif // XML_DOCTYPENODE_HPP
21.302326
80
0.566048
chrisoldwood
725a6fee179a041420c62fba2778f9c48875c24f
885
cpp
C++
plugin_III/game_III/COneSheet.cpp
gta-chaos-mod/plugin-sdk
e3bf176337774a2afc797a47825f81adde78e899
[ "Zlib" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
plugin_III/game_III/COneSheet.cpp
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
89
2016-05-08T06:42:36.000Z
2022-03-29T06:49:09.000Z
plugin_III/game_III/COneSheet.cpp
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto 3) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "COneSheet.h" PLUGIN_SOURCE_FILE int addrof(COneSheet::AddToList) = ADDRESS_BY_VERSION(0x512650, 0x512860, 0x5127F0); int gaddrof(COneSheet::AddToList) = GLOBAL_ADDRESS_BY_VERSION(0x512650, 0x512860, 0x5127F0); void COneSheet::AddToList(COneSheet *list) { plugin::CallMethodDynGlobal<COneSheet *, COneSheet *>(gaddrof(COneSheet::AddToList), this, list); } int addrof(COneSheet::RemoveFromList) = ADDRESS_BY_VERSION(0x512670, 0x512880, 0x512810); int gaddrof(COneSheet::RemoveFromList) = GLOBAL_ADDRESS_BY_VERSION(0x512670, 0x512880, 0x512810); void COneSheet::RemoveFromList() { plugin::CallMethodDynGlobal<COneSheet *>(gaddrof(COneSheet::RemoveFromList), this); }
36.875
101
0.769492
gta-chaos-mod
725a8de4df3ddf457f4cb88bfedb7bda0b6cadcc
4,830
cpp
C++
gbEmu/src/Gb.cpp
Mesiow/gbEmu
fe73b1a919517a34d30dd7a439efffbe68d8644a
[ "MIT" ]
2
2021-04-27T00:54:47.000Z
2021-06-07T13:41:25.000Z
gbEmu/src/Gb.cpp
Mesiow/gbEmu
fe73b1a919517a34d30dd7a439efffbe68d8644a
[ "MIT" ]
null
null
null
gbEmu/src/Gb.cpp
Mesiow/gbEmu
fe73b1a919517a34d30dd7a439efffbe68d8644a
[ "MIT" ]
null
null
null
#include "../include/Gb.h" namespace gbEmu { Gb::Gb() :mmu(), cpu(&mmu), ppu(&mmu), joypad(&mmu) { mmu.connectJoypad(&joypad); //cart.load("roms/Kirby's Dream Land.gb"); //cart.load("roms/Pokemon Red.gb"); //cart.load("roms/SUPERMAR.gbc"); //cart.load("roms/Dr. Mario.gb"); //cart.load("roms/Tetris.gb"); //cart.load("roms/ZELDA.gbc"); //cart.load("roms/fairylake.gb"); //cart.load("roms/Tennis.gb"); //Tests //cart.load("test_roms/02-interrupts.gb"); cart.load("test_roms/ppu/dmg-acid2.gb"); //cart.load("test_roms/ppu/bg_m9800_d8800.gb"); //cart.load("test_roms/numism.gb"); //cart.load("test_roms/statcount.gb"); //cart.load("test_roms/cpu_instrs.gb"); //cart.load("test_roms/mbc/mbc1/bits_mode.gb"); //cart.load("test_roms/instr_timing.gb"); //cart.load("test_roms/mem_timing.gb"); mmu.loadBios("roms/DMG_ROM.GB"); mmu.loadCartridge(&cart); ppu.init(); } void Gb::update(float dt) { s32 cycles_this_frame = 0; //each scanline takes 456 t cycles. //There are 154 scanlines per frame. //(456 * 154) = 70224(maxCycles) while (cycles_this_frame < maxCycles) { s32 cycle = cpu.clock(); cycles_this_frame += cycle; cpu.handleTimer(cycle); ppu.update(cycles_this_frame); cpu.handleInterrupts(); } ppu.bufferPixels(); /* if (dt < delayTime) { std::this_thread::sleep_for(std::chrono::duration<float, std::milli>(delayTime - dt)); }*/ } void Gb::render(sf::RenderTarget& target) { ppu.render(target); } void Gb::handleEvents(sf::Event& ev) { handleKeyReleased(ev); handleKeyPressed(ev); } void Gb::handleKeyReleased(sf::Event& ev) { if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Right) { joypad.keyReleased(Key::ArrowRight); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Left) { joypad.keyReleased(Key::ArrowLeft); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Up) { joypad.keyReleased(Key::ArrowUp); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Down) { joypad.keyReleased(Key::ArrowDown); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::S) { joypad.keyReleased(Key::S); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::A) { joypad.keyReleased(Key::A); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::LShift) { joypad.keyReleased(Key::LShift); } } if (ev.type == sf::Event::KeyReleased) { if (ev.key.code == sf::Keyboard::Enter) { joypad.keyReleased(Key::Enter); } } } void Gb::handleKeyPressed(sf::Event& ev) { if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Right) { joypad.keyPressed(Key::ArrowRight); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Left) { joypad.keyPressed(Key::ArrowLeft); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Up) { joypad.keyPressed(Key::ArrowUp); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Down) { joypad.keyPressed(Key::ArrowDown); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::S) { joypad.keyPressed(Key::S); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::A) { joypad.keyPressed(Key::A); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::LShift) { joypad.keyPressed(Key::LShift); } } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Enter) { joypad.keyPressed(Key::Enter); } } } }
28.75
68
0.478882
Mesiow
725b571610b47c931e2d3339b7b584a39cd9c48d
383
hpp
C++
include/experimental/status_value.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
105
2015-01-24T13:26:41.000Z
2022-02-18T15:36:53.000Z
include/experimental/status_value.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
37
2015-09-04T06:57:10.000Z
2021-09-09T18:01:44.000Z
include/experimental/status_value.hpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
23
2015-01-27T11:09:18.000Z
2021-10-04T02:23:30.000Z
// Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // (C) Copyright 2019 Vicente J. Botet Escriba #ifndef JASEL_EXPERIMENTAL_STATUS_VALUE_HPP #define JASEL_EXPERIMENTAL_STATUS_VALUE_HPP #include <experimental/fundamental/v3/status_value/status_value.hpp> #endif // header
29.461538
68
0.793734
jwakely
7265ba91a6d32c39d10da1194ee098b04f73e398
532
cpp
C++
practice/linked_list/reverse_ll.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
2
2018-06-26T09:52:14.000Z
2018-07-12T15:02:01.000Z
practice/linked_list/reverse_ll.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
practice/linked_list/reverse_ll.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // a recursive version // it is more elegant // struct Node { int data; struct Node *next; } // Should reverse list and return new head. struct Node* reverseList(struct Node *head) { // code here // return head of reversed list if(head->next == NULL) return head; struct Node* temp = head->next; struct Node* new_head = reverseList(head->next); temp->next = head; head->next = NULL; return new_head; } int main(){ return 0; }
15.647059
52
0.62218
sidgairo18
7267b5bc9d06ccd539dc8d8bdf8978cc162c4bf7
6,205
cc
C++
RecoJets/JetProducers/plugins/SubEventGenJetProducer.cc
flodamas/cmssw
fff9de2a54e62debab81057f8d6f8c82c2fd3dd6
[ "Apache-2.0" ]
null
null
null
RecoJets/JetProducers/plugins/SubEventGenJetProducer.cc
flodamas/cmssw
fff9de2a54e62debab81057f8d6f8c82c2fd3dd6
[ "Apache-2.0" ]
null
null
null
RecoJets/JetProducers/plugins/SubEventGenJetProducer.cc
flodamas/cmssw
fff9de2a54e62debab81057f8d6f8c82c2fd3dd6
[ "Apache-2.0" ]
null
null
null
#include "FWCore/Framework/interface/MakerMacros.h" #include "RecoJets/JetProducers/plugins/SubEventGenJetProducer.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Utilities/interface/isFinite.h" #include "RecoJets/JetProducers/interface/JetSpecific.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" using namespace std; using namespace reco; using namespace edm; using namespace cms; namespace { bool checkHydro(const reco::GenParticle * p){ const Candidate* m1 = p->mother(); while(m1){ int pdg = abs(m1->pdgId()); int st = m1->status(); LogDebug("SubEventMothers")<<"Pdg ID : "<<pdg<<endl; if(st == 3 || pdg < 9 || pdg == 21){ LogDebug("SubEventMothers")<<"Sub-Collision Found! Pdg ID : "<<pdg<<endl; return false; } const Candidate* m = m1->mother(); m1 = m; if(!m1) LogDebug("SubEventMothers")<<"No Mother, particle is : "<<pdg<<" with status "<<st<<endl; } // return true; return true; // Debugging - to be changed } } SubEventGenJetProducer::SubEventGenJetProducer(edm::ParameterSet const& conf): VirtualJetProducer( conf ) { // mapSrc_ = conf.getParameter<edm::InputTag>( "srcMap"); signalOnly_ = conf.getParameter<bool>("signalOnly"); ignoreHydro_ = conf.getUntrackedParameter<bool>("ignoreHydro", true); if(signalOnly_) ignoreHydro_ = 0; produces<reco::BasicJetCollection>(); // the subjet collections are set through the config file in the "jetCollInstanceName" field. input_cand_token_ = consumes<reco::CandidateView>(src_); } void SubEventGenJetProducer::inputTowers( ) { std::vector<edm::Ptr<reco::Candidate> >::const_iterator inBegin = inputs_.begin(), inEnd = inputs_.end(), i = inBegin; for (; i != inEnd; ++i ) { reco::CandidatePtr input = inputs_[i - inBegin]; if (edm::isNotFinite(input->pt())) continue; if (input->et() <inputEtMin_) continue; if (input->energy()<inputEMin_) continue; if (isAnomalousTower(input)) continue; edm::Ptr<reco::Candidate> p = inputs_[i - inBegin]; const GenParticle * pref = dynamic_cast<const GenParticle *>(p.get()); int subevent = pref->collisionId(); if(signalOnly_ && subevent != 0) continue; LogDebug("SubEventContainers")<<"SubEvent is : "<<subevent<<endl; LogDebug("SubEventContainers")<<"SubSize is : "<<subInputs_.size()<<endl; if(subevent >= (int)subInputs_.size()){ hydroTag_.resize(subevent+1, -1); subInputs_.resize(subevent+1); LogDebug("SubEventContainers")<<"SubSize is : "<<subInputs_.size()<<endl; LogDebug("SubEventContainers")<<"HydroTagSize is : "<<hydroTag_.size()<<endl; } LogDebug("SubEventContainers")<<"HydroTag is : "<<hydroTag_[subevent]<<endl; if(ignoreHydro_ && hydroTag_[subevent] != 0) hydroTag_[subevent] = (int)checkHydro(pref); subInputs_[subevent].push_back(fastjet::PseudoJet(input->px(),input->py(),input->pz(), input->energy())); subInputs_[subevent].back().set_user_index(i - inBegin); } } void SubEventGenJetProducer::produce(edm::Event& iEvent,const edm::EventSetup& iSetup){ LogDebug("VirtualJetProducer") << "Entered produce\n"; fjJets_.clear(); subInputs_.clear(); nSubParticles_.clear(); hydroTag_.clear(); inputs_.clear(); // get inputs and convert them to the fastjet format (fastjet::PeudoJet) edm::Handle<reco::CandidateView> inputsHandle; iEvent.getByToken(input_cand_token_, inputsHandle); for (size_t i = 0; i < inputsHandle->size(); ++i) { inputs_.push_back(inputsHandle->ptrAt(i)); } LogDebug("VirtualJetProducer") << "Got inputs\n"; inputTowers(); // Convert candidates to fastjet::PseudoJets. // Also correct to Primary Vertex. Will modify fjInputs_ // and use inputs_ //////////////// auto jets = std::make_unique<std::vector<GenJet>>(); subJets_ = jets.get(); LogDebug("VirtualJetProducer") << "Inputted towers\n"; size_t nsub = subInputs_.size(); for(size_t isub = 0; isub < nsub; ++isub){ if(ignoreHydro_ && hydroTag_[isub]) continue; fjJets_.clear(); fjInputs_.clear(); fjInputs_ = subInputs_[isub]; runAlgorithm( iEvent, iSetup ); } //Finalize LogDebug("SubEventJetProducer") << "Wrote jets\n"; iEvent.put(std::move(jets)); return; } void SubEventGenJetProducer::runAlgorithm( edm::Event & iEvent, edm::EventSetup const& iSetup) { // run algorithm fjJets_.clear(); fjClusterSeq_ = ClusterSequencePtr( new fastjet::ClusterSequence( fjInputs_, *fjJetDefinition_ ) ); fjJets_ = fastjet::sorted_by_pt(fjClusterSeq_->inclusive_jets(jetPtMin_)); using namespace reco; for (unsigned int ijet=0;ijet<fjJets_.size();++ijet) { GenJet jet; const fastjet::PseudoJet& fjJet = fjJets_[ijet]; std::vector<fastjet::PseudoJet> fjConstituents = sorted_by_pt(fjClusterSeq_->constituents(fjJet)); std::vector<CandidatePtr> constituents = getConstituents(fjConstituents); double px=fjJet.px(); double py=fjJet.py(); double pz=fjJet.pz(); double E=fjJet.E(); double jetArea=0.0; double pu=0.; writeSpecific( jet, Particle::LorentzVector(px, py, pz, E), vertex_, constituents, iSetup); jet.setJetArea (jetArea); jet.setPileup (pu); subJets_->push_back(jet); } } void SubEventGenJetProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription descSubEventJetProducer; fillDescriptionsFromSubEventGenJetProducer(descSubEventJetProducer); VirtualJetProducer::fillDescriptionsFromVirtualJetProducer(descSubEventJetProducer); descSubEventJetProducer.add<string>("jetCollInstanceName", ""); descSubEventJetProducer.add<bool>("sumRecHits", false); descriptions.add("SubEventGenJetProducer", descSubEventJetProducer); } void SubEventGenJetProducer::fillDescriptionsFromSubEventGenJetProducer( edm::ParameterSetDescription& desc) { desc.add<bool>("signalOnly", false); desc.addUntracked<bool>("ignoreHydro", true); } DEFINE_FWK_MODULE(SubEventGenJetProducer);
32.317708
102
0.682031
flodamas
726928ace6d3576618dca67f2cc3d39b5eed5662
1,276
hpp
C++
vegastrike/boost/1_28/boost/python/from_python.hpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/boost/1_28/boost/python/from_python.hpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/boost/1_28/boost/python/from_python.hpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
// Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #ifndef FROM_PYTHON_DWA2002128_HPP # define FROM_PYTHON_DWA2002128_HPP # include <boost/python/converter/from_python.hpp> namespace boost { namespace python { template <class T> struct from_python : converter::select_from_python<T>::type { typedef typename converter::select_from_python<T>::type base; from_python(PyObject*); }; // specialization for PyObject* template <> struct from_python<PyObject*> { from_python(PyObject*) {} bool convertible() const { return true; } PyObject* operator()(PyObject* source) const { return source; } }; template <> struct from_python<PyObject* const&> { from_python(PyObject*) {} bool convertible() const { return true; } PyObject*const& operator()(PyObject*const& source) const { return source; } }; // // implementations // template <class T> inline from_python<T>::from_python(PyObject* source) : base(source) { } }} // namespace boost::python #endif // FROM_PYTHON_DWA2002128_HPP
25.52
79
0.731975
Ezeer
726be744b2811e53c76fd038f580d4111cf5e1c4
756
cpp
C++
src/util/util_env.cpp
ChaosInitiative/dxvk-native
516c0a44b82d4b3d5000762594e0424eb383b9dd
[ "Zlib" ]
3
2020-12-20T08:53:33.000Z
2022-01-20T16:46:39.000Z
src/util/util_env.cpp
ChaosInitiative/dxvk-native
516c0a44b82d4b3d5000762594e0424eb383b9dd
[ "Zlib" ]
null
null
null
src/util/util_env.cpp
ChaosInitiative/dxvk-native
516c0a44b82d4b3d5000762594e0424eb383b9dd
[ "Zlib" ]
null
null
null
#include "util_env.h" namespace dxvk::env { #ifndef DXVK_NATIVE constexpr char dirSlash = '\\'; #else constexpr char dirSlash = '/'; #endif std::string getEnvVar(const char* name) { #ifdef DXVK_NATIVE char* result = std::getenv(name); return (result) ? result : ""; #else std::vector<WCHAR> result; result.resize(MAX_PATH + 1); DWORD len = ::GetEnvironmentVariableW(str::tows(name).c_str(), result.data(), MAX_PATH); result.resize(len); return str::fromws(result.data()); #endif } std::string getExeName() { std::string fullPath = getExePath(); auto n = fullPath.find_last_of(dirSlash); return (n != std::string::npos) ? fullPath.substr(n + 1) : fullPath; } }
18.9
92
0.616402
ChaosInitiative
726d09348dc66999cbe9d81150f434b8a8db666f
5,942
cpp
C++
GUI/control.cpp
MasterLufier/FT800-FT813
9297b7bfb26d7fe7b0f032b9d8145b3af975ac09
[ "MIT" ]
null
null
null
GUI/control.cpp
MasterLufier/FT800-FT813
9297b7bfb26d7fe7b0f032b9d8145b3af975ac09
[ "MIT" ]
null
null
null
GUI/control.cpp
MasterLufier/FT800-FT813
9297b7bfb26d7fe7b0f032b9d8145b3af975ac09
[ "MIT" ]
null
null
null
#include "control.h" namespace FTGUI { Button::Button(string label, Widget * parent) : Rectangle(parent) { m_name = "Button"; m_label = new Label(label, this); m_label->setHorizontalAlignment(Label::HCenter); m_label->setVerticalAlignment(Label::VCenter); m_label->setColor(m_theme->onPrimary()); if(m_parent->name() == "ButtonGroup") { setCheckable(true); } setGeometry(m_x, m_y, m_width, m_height); } void Button::setGeometry(int32_t x, int32_t y, uint16_t width, uint16_t height) { m_label->setGeometry(width / 2 - 1, height / 2 - 1, width, height); Widget::setGeometry(x, y, width, height); if(m_checker) { m_checker->setWidth(m_width - m_width / 5); m_checker->setX(m_width / 10); m_checker->setHeight(m_height / 12); m_checker->setY(m_height - m_checker->height()); } } void Button::setLabel(string text) { m_label->setText(text); } bool Button::pressed() const { return m_pressed; } void Button::setPressed(bool pressed) { m_pressed = pressed; if(pressed) setColor(theme()->primaryLight()); else setColor(theme()->primary()); if(m_visible) update(); } bool Button::touchPressed(int16_t x, int16_t y) { if(!m_enabled) return false; if(Widget::touchPressed(x, y)) { setPressed(true); return true; } return false; } bool Button::touchReleased(int16_t x, int16_t y, int16_t accelerationX, int16_t accelerationY) { if(!m_enabled) return false; if(Widget::touchReleased(x, y, accelerationX, accelerationY)) { if(!m_pressed) return true; setPressed(false); return true; } if(!m_pressed) return false; setPressed(false); return false; } bool Button::checkable() const { return m_checkable; } void Button::setCheckable(bool checkable) { m_checkable = checkable; if(m_checkable) { if(!m_checker) m_checker = new Rectangle(this); m_checker->setWidth(m_width - m_width / 5); m_checker->setX(m_width / 10); m_checker->setHeight(m_height / 12); m_checker->setColor(Main::LightGrey); m_checker->setY(m_height - m_checker->height()); } else { delete m_checker; } } bool Button::checked() const { return m_checked; } void Button::setChecked(bool checked) { if(!m_checkable) return; m_checked = checked; if(m_checked) { m_checker->setColor(Main::Error); } else { m_checker->setColor(Main::LightGrey); } if(m_visible) update(); } bool Button::enabled() const { return m_enabled; } void Button::setEnabled(bool enabled) { m_enabled = enabled; if(m_enabled) { setColor(theme()->primary()); m_label->setColor(theme()->onPrimary()); } else { setColor(Main::LightGrey); m_label->setColor(Main::Dark); } if(m_visible) update(); } void ButtonGroup::addWidget(Widget * widget) { // if(widget->name() != "Button") // { // error("Button group can contain only button as children \n"); // return; // } Widget::addWidget(widget); m_widgetAdded = true; } void ButtonGroup::show() { if(m_widgetAdded) { for(uint16_t i = 0; i < m_container.size(); ++i) { auto w = childAt(i); w->setCheckable(true); if(i == 0) w->setChecked(true); w->onReleased([&, in = i]() { if(m_index == in) return; this->setIndex(in); }); } m_widgetAdded = false; setGeometry(m_x, m_y, m_width, m_height); } Widget::show(); } void ButtonGroup::setGeometry(int32_t x, int32_t y, uint16_t width, uint16_t height) { Widget::setGeometry(x, y, width, height); uint16_t fWidth = (m_width / m_container.size()) - /*(m_container.size() * m_padding) -*/ m_padding; for(uint16_t i = 0; i < m_container.size(); ++i) { this->childAt(i)->setGeometry((i * (fWidth + m_padding)) + (m_padding / 2), 0, fWidth, m_height); } } uint16_t ButtonGroup::index() const { return m_index; } void ButtonGroup::setIndex(const uint16_t & index) { if(index == m_index) return; this->childAt(m_index)->setChecked(false); m_index = index; this->childAt(m_index)->setChecked(true); if(m_onIndexChanged) m_onIndexChanged->operator()(m_index); } uint8_t ButtonGroup::padding() const { return m_padding; } void ButtonGroup::setPadding(const uint8_t & padding) { m_padding = padding; } void ButtonGroup::setRadius(uint8_t radius) { for(uint16_t i = 0; i < m_container.size(); ++i) { childAt(i)->setRadius(radius); } } float RangeController::min() const { return m_min; } void RangeController::setMin(float min) { m_min = min; m_range = m_max - m_min; } float RangeController::max() const { return m_max; } void RangeController::setMax(float max) { m_max = max; m_range = m_max - m_min; } float RangeController::value() const { return m_value; } void RangeController::setValue(float value) { m_value = value; m_onValueChanged->operator()(value); //TODO: Move update from here to global level update function update(); } } // namespace FTGUI
21.070922
83
0.551498
MasterLufier
726e1a8ee51fb97176e7fc711d90dfa8c7e9a528
279
hpp
C++
WICWIU_src/Utils.hpp
KwonYeseong/WICWIU_stamp
690c3f194e507b59510229ed12a16f759235342c
[ "Apache-2.0" ]
3
2019-03-03T10:39:20.000Z
2020-08-10T12:45:06.000Z
WICWIU_src/Utils.hpp
yoondonghwee/WICWIU
2c515108985abf91802dd02a423be94afc883b2e
[ "Apache-2.0" ]
null
null
null
WICWIU_src/Utils.hpp
yoondonghwee/WICWIU
2c515108985abf91802dd02a423be94afc883b2e
[ "Apache-2.0" ]
null
null
null
#ifndef UTILS_H_ #define UTILS_H_ value #ifdef __CUDNN__ #define MAX_CUDA_DEVICE 32 int GetCurrentCudaDevice(); void GetKernelParameters(int totalThread, int *pNoBlock, int *pThreadsPerBlock, int blockSize = 128); #endif // ifdef __CUDNN__ #endif // ifndef UTILS_H_
17.4375
101
0.763441
KwonYeseong
726fb762ca049585f89ed29790b2ac8d91b85749
1,942
cpp
C++
mini/threading/event.cpp
geralltf/mini-tor
61d58749431fba970e19e0d35a53811956c69b16
[ "MIT" ]
380
2016-07-20T10:22:37.000Z
2022-03-30T08:47:44.000Z
mini/threading/event.cpp
geralltf/mini-tor
61d58749431fba970e19e0d35a53811956c69b16
[ "MIT" ]
24
2016-08-13T12:56:03.000Z
2021-05-26T01:59:17.000Z
mini/threading/event.cpp
geralltf/mini-tor
61d58749431fba970e19e0d35a53811956c69b16
[ "MIT" ]
105
2016-07-20T14:34:52.000Z
2022-02-17T13:31:25.000Z
#include "event.h" #include <mini/collections/list.h> #include <type_traits> namespace mini::threading { event::event( reset_type type, bool initial_state ) { _event = CreateEvent(NULL, (BOOL)type, initial_state, NULL); } event::~event( void ) { CloseHandle(_event); } void event::set( void ) { SetEvent(_event); } void event::reset( void ) { ResetEvent(_event); } wait_result event::wait( timeout_type timeout ) { return static_cast<wait_result>(WaitForSingleObject(_event, timeout)); } wait_result event::wait_for_all( buffer_ref<const event*> events, timeout_type timeout ) { collections::list<HANDLE> handles; for (auto&& event : events) { handles.add(event->_event); } return static_cast<wait_result>(WaitForMultipleObjects( static_cast<DWORD>(handles.get_size()), // // dirty hack - as long as 'event' class // consists only from one HANDLE member, // this should work just fine. // &handles[0], TRUE, timeout)); } wait_result event::wait_for_any( buffer_ref<const event*> events, timeout_type timeout ) { collections::list<HANDLE> handles; for (auto&& event : events) { handles.add(event->_event); } return static_cast<wait_result>(WaitForMultipleObjects( static_cast<DWORD>(handles.get_size()), // // dirty hack - as long as 'event' class // consists only from one HANDLE member, // this should work just fine. // &handles[0], FALSE, timeout)); } int event::index_from_wait_result( wait_result result ) { return result == wait_result::timeout ? -1 : result == wait_result::failed ? -1 : result > wait_result::abandoned ? (static_cast<int>(result) - static_cast<int>(wait_result::abandoned)) : static_cast<int>(result) - static_cast<int>(wait_result::success); } bool event::is_signaled( void ) { return wait(0) == wait_result::success; } }
16.457627
110
0.663749
geralltf
7271e994bcf6bfa9176fa08e62727f15d22d8b51
2,026
cpp
C++
src/Reader/IniConfigReader.cpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
src/Reader/IniConfigReader.cpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
src/Reader/IniConfigReader.cpp
fcaillaud/SARAH
ca79c7d9449cf07eec9d5cc13293ec0c128defc1
[ "MIT" ]
null
null
null
#include "IniConfigReader.hpp" namespace Sarah { namespace IO { IniConfigReader::IniConfigReader(std::string p_filePath): BaseReader(p_filePath) { } bool IniConfigReader::Read() { unsigned int vNumLine = 0; boost::smatch vMatches; const boost::regex vSectRegex("\\s*\\[.+\\]\\s*"); std::string vLine; std::string vCurrentSection = "undefined"; std::vector<std::string> vPropertyLine; std::string vPropertyName, vPropertyValue; while(GetLine(vLine)) { vNumLine++; //Si la ligne n'est pas un commentaire (# .... ou ; ....) if( ! (gu::IsComments(vLine, '#') || gu::IsComments(vLine, ';')) ) { if(boost::regex_match(vLine, vMatches, vSectRegex)) { if(vMatches.size() == 1) { vCurrentSection = gu::WithoutChar(gu::WithoutChar(vMatches[0], ']'), '['); vCurrentSection = gu::WithoutFrontSpace(gu::WithoutBackSpace(vCurrentSection)); m_config.insert(std::pair<std::string, Section>(vCurrentSection, Section())); } else { msg::Msg_Spe(msg::MSG_FLAG_ENUM::ERROR, "Error in IniConfigReader.Read : Line ", vNumLine, " -> Wrong Syntax in Section Declaration"); exit(-1); } } else { vLine = gu::WithoutComments(gu::WithoutComments(vLine, '#'), ';'); vPropertyLine = gu::Split(vLine, '='); if(vPropertyLine.size() == 2) { vPropertyName = gu::WithoutFrontSpace(gu::WithoutBackSpace(vPropertyLine[0])); vPropertyValue = gu::WithoutFrontSpace(gu::WithoutBackSpace(vPropertyLine[1])); m_config[vCurrentSection].insert(std::pair<std::string, std::string>(vPropertyName, vPropertyValue)); } else { //TODO : peut être gérer quand même l'erreur au lieu d'exit msg::Msg_Spe(msg::MSG_FLAG_ENUM::ERROR, "Error in IniConfigReader.Read : Line ", vNumLine, " -> Wrong Syntax in Property Declaration"); exit(-1); } } } } return HasSucceed(); } IniConfigReader::Config IniConfigReader::GetConfig() const { return m_config; } } }
25.974359
141
0.63771
fcaillaud
72724c64c69adc56877a8001b9e6686ba46a87a2
1,379
cpp
C++
src/Text.cpp
JohnBobSmith/SpaceyRocks
3ee95fbdd11f2f7c972b869931cce6c426c878d0
[ "MIT" ]
1
2019-04-19T05:08:25.000Z
2019-04-19T05:08:25.000Z
src/Text.cpp
JohnBobSmith/SpaceyRocks
3ee95fbdd11f2f7c972b869931cce6c426c878d0
[ "MIT" ]
null
null
null
src/Text.cpp
JohnBobSmith/SpaceyRocks
3ee95fbdd11f2f7c972b869931cce6c426c878d0
[ "MIT" ]
null
null
null
#include "Resources.h" #include "Text.h" #include "G_Miscfuncandvar.h" Text::Text() { //Screen dimensions G_Miscfuncandvar gmiscfuncandvar; //Load our font blockFont.loadFromFile( PKGDATADIR "/fonts/ehsmb.ttf"); //Load our game over text gameOverText.setFont(blockFont); gameOverText.setString("Game Over"); gameOverText.setCharacterSize(110); gameOverText.setColor(sf::Color::Red); gameOverText.setStyle(sf::Text::Regular); //Center the text on screen gameOverText.setPosition(gmiscfuncandvar.screenWidth / 8, gmiscfuncandvar.screenHeight / 3); //Load our victory/win text winText.setFont(blockFont); winText.setString("You WIN!!"); winText.setCharacterSize(110); winText.setColor(sf::Color::Green); winText.setStyle(sf::Text::Regular); //Center the text on screen winText.setPosition(gmiscfuncandvar.screenWidth / 8, gmiscfuncandvar.screenHeight / 3); //Load our "Space bar to start" text spaceTostartText.setFont(blockFont); spaceTostartText.setString("Space bar to start"); spaceTostartText.setCharacterSize(55); spaceTostartText.setColor(sf::Color::Yellow); spaceTostartText.setStyle(sf::Text::Regular); //Position this text just below our win/loss text spaceTostartText.setPosition(gmiscfuncandvar.screenWidth / 8, gmiscfuncandvar.screenHeight / 2); }
31.340909
100
0.725163
JohnBobSmith
72725dd87581dfa00f6c62f946932c03bf3f3fd3
1,937
cpp
C++
src/point_cloud_assembler_srv.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
null
null
null
src/point_cloud_assembler_srv.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
null
null
null
src/point_cloud_assembler_srv.cpp
StratomInc/laser_assembler
25640f99d043b37e34310e5e0194496b8cc55895
[ "Apache-2.0" ]
1
2021-04-08T15:03:40.000Z
2021-04-08T15:03:40.000Z
// Copyright 2018 Open Source Robotics Foundation, Inc. // // 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 <string> #include "laser_assembler/base_assembler_srv.hpp" namespace laser_assembler { /** * \brief Maintains a history of incremental point clouds (usually from laser scans) and generates a point cloud upon request * \todo Clean up the doxygen part of this header * params * * (Several params are inherited from BaseAssemblerSrv) */ class PointCloudAssemblerSrv : public BaseAssemblerSrv<sensor_msgs::msg::PointCloud> { public: PointCloudAssemblerSrv() { } ~PointCloudAssemblerSrv() { } unsigned int GetPointsInScan(const sensor_msgs::msg::PointCloud & scan) { return scan.points.size(); } void ConvertToCloud( const string & fixed_frame_id, const sensor_msgs::PointCloud & scan_in, sensor_msgs::PointCloud & cloud_out) { tf_->transformPointCloud(fixed_frame_id, scan_in, cloud_out); } private: }; } // namespace laser_assembler int main(int argc, char ** argv) { ros::init(argc, argv, "point_cloud_assembler"); ros::NodeHandle n; RCLCPP_WARN(n_->get_logger(), "The point_cloud_assembler_srv is deprecated. Please switch to " "using the laser_scan_assembler. Documentation is available at " "http://www.ros.org/wiki/laser_assembler"); laser_assembler::PointCloudAssemblerSrv pc_assembler; pc_assembler.start(); ros::spin(); return 0; }
29.348485
125
0.740836
StratomInc
727886d722fca616a9c4ac7ed4292cd9bd757a94
225
cpp
C++
tests/main.cpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
tests/main.cpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
tests/main.cpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2017 ** indie ** File description: ** A file for indie - Paul Laffitte */ #include <gtest/gtest.h> int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
13.235294
38
0.671111
arthurchaloin
727a625de94b958e82e00381a3cfe061e6d77dcb
6,689
cpp
C++
Tests/utils/FileHandle_Test.cpp
Longri/cachebox3.0_native
31e41b980901d5798689cd0d2e0be0e474e5489b
[ "Apache-2.0" ]
null
null
null
Tests/utils/FileHandle_Test.cpp
Longri/cachebox3.0_native
31e41b980901d5798689cd0d2e0be0e474e5489b
[ "Apache-2.0" ]
null
null
null
Tests/utils/FileHandle_Test.cpp
Longri/cachebox3.0_native
31e41b980901d5798689cd0d2e0be0e474e5489b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Longri * * This program 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 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * * * * Created by Longri on 22.07.18. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "../../src/utils/FileHandle.h" using testing::Eq; namespace { class FileHandle_Test : public testing::Test { public: }; } TEST_F(FileHandle_Test, testConstructor) { String16 path = String16("@Work/testDir/testFile.txt"); FileHandle fh(path); String16 expectedPath(path); ASSERT_EQ(expectedPath, fh.getAbsolutePath()); ASSERT_STREQ("@Work/testDir/testFile.txt", fh.getPath()); //check utf8 char array ASSERT_EQ(String16("testFile.txt"), fh.name()); ASSERT_EQ(String16("txt"), fh.extension()); ASSERT_EQ(String16("@Work/testDir/testFile"), fh.pathWithoutExtension()); } TEST_F(FileHandle_Test, testChilds) { String16 path = String16("@Work/testDir"); FileHandle fh(path); String16 child("child.txt"); FileHandle childFh = fh.child(child); ASSERT_STREQ("@Work/testDir/child.txt", childFh.getPath()); //check utf8 char array } TEST_F(FileHandle_Test, testParent) { String16 path = String16("@Work/testDir/testFile.txt"); FileHandle fh(path); String16 expectedPath(path); ASSERT_EQ(expectedPath, fh.getAbsolutePath()); ASSERT_STREQ("@Work/testDir/testFile.txt", fh.getPath()); //check utf8 char array ASSERT_EQ(String16("@Work/testDir"), fh.parent().getAbsolutePath()); String16 path2 = String16("../../test/cout.txt"); FileHandle fh2(path2); String16 endsWith = String16("/test/cout.txt"); ASSERT_TRUE(fh2.getAbsolutePath().endsWith(endsWith)); } TEST_F(FileHandle_Test, testExist) { String16 path = String16("./CMakeCache.txt"); FileHandle fh(path); String16 expected = FileHandle::getWorkingPath(); expected.append("/CMakeCache.txt"); ASSERT_TRUE(fh.exists()); ASSERT_EQ(expected, fh.getAbsolutePath()); ASSERT_FALSE(fh.isDirectory()); FileHandle parentFH = fh.parent(); ASSERT_TRUE(parentFH.isDirectory()); ASSERT_FALSE(parentFH.exists()); } TEST_F(FileHandle_Test, testList) { String16 workingPath = FileHandle::getWorkingPath(); FileHandle fileHandle(workingPath); FileHandle testResourcesDir = fileHandle.parent().child("Tests/TestResources"); ASSERT_TRUE(testResourcesDir.isDirectory()); std::vector<FileHandle> list = testResourcesDir.list(); int expected; #if defined(__APPLE__) expected = 8; //Apple has .DS folder #else expected=7; #endif ASSERT_EQ(expected, list.size()); bool testDirFound = false; for (int i = 0; i < list.size(); ++i) { FileHandle fh = list[i]; if (fh.name() == "TestDir") { if (fh.isDirectory()) { testDirFound = true; } } } ASSERT_TRUE(testDirFound); } TEST_F(FileHandle_Test, testListFilter) { String16 workingPath = FileHandle::getWorkingPath(); FileHandle fileHandle(workingPath); FileHandle testResourcesDir = fileHandle.parent().child("Tests/TestResources"); ASSERT_TRUE(testResourcesDir.isDirectory()); class directoryFilter : public FileFilter { bool accept(char *filePath) const override { // String16 str(filePath); FileHandle fh(filePath); return fh.isDirectory(); } }; std::vector<FileHandle> list = testResourcesDir.list(directoryFilter()); ASSERT_TRUE(list.size() == 1); //only dir's bool testDirFound = false; for (int i = 0; i < list.size(); ++i) { FileHandle fh = list[i]; if (fh.name() == "TestDir") { if (fh.isDirectory()) { testDirFound = true; } } } ASSERT_TRUE(testDirFound); } TEST_F(FileHandle_Test, testFileSize) { FileHandle testResourcesDir = FileHandle(FileHandle::getWorkingPath()).parent().child("Tests/TestResources"); FileHandle fh = testResourcesDir.child("TestFile.txt"); long fileSize = fh.fileSize(); ASSERT_EQ(10, fileSize); } TEST_F(FileHandle_Test, testMake_Delet_Dir) { FileHandle testResourcesDir = FileHandle(FileHandle::getWorkingPath()).parent().child("Tests/TestResources"); FileHandle makedDir = testResourcesDir.child("MakeDir"); ASSERT_TRUE(!makedDir.isDirectory()); makedDir.mkdirs(); ASSERT_TRUE(makedDir.isDirectory()); //Write File into directory FileHandle file = makedDir.child("WriteTestFile.txt"); String16 write("Write Utf8 Text '˷ꁾ' to File!\nWith two lines!"); file.writeString(write, false); String16 read = file.readString(); ASSERT_EQ(write, read); //delete directory ASSERT_TRUE(makedDir.deleteDirectory()); ASSERT_TRUE(!makedDir.isDirectory()); } TEST_F(FileHandle_Test, testWriteFile) { FileHandle testResourcesDir = FileHandle(FileHandle::getWorkingPath()).parent().child( "Tests/TestResources/TestDir"); FileHandle file = testResourcesDir.child("WriteTestFile.txt"); String16 write("Write Utf8 Text '˷ꁾ' to File!\nWith two lines!"); file.writeString(write, false); String16 read = file.readString(); ASSERT_EQ(write, read); } TEST_F(FileHandle_Test, testCopyFile) { FileHandle testResourcesDir = FileHandle(FileHandle::getWorkingPath()).parent().child("Tests/TestResources"); FileHandle makedDir = testResourcesDir.child("CopyTestDir"); ASSERT_TRUE(!makedDir.isDirectory()); makedDir.mkdirs(); ASSERT_TRUE(makedDir.isDirectory()); //copy file FileHandle oriFile = testResourcesDir.child("TestFileUtf8.txt"); FileHandle copyfile = makedDir.child("CopyTestFile.txt"); oriFile.copy(copyfile); String16 write("Write Utf8 Text '˷ꁾ' to File!\nWith two lines!"); copyfile.writeString(write, true); String16 copyExpectedRead("߷®Hällo߷®Hällo"); copyExpectedRead.append(write); String16 read = copyfile.readString(); ASSERT_EQ(copyExpectedRead, read); //delete directory ASSERT_TRUE(makedDir.deleteDirectory()); ASSERT_TRUE(!makedDir.isDirectory()); }
30.543379
113
0.685005
Longri
727b41d53150f4cc5c2a53a47e5bd2c77ebe1c83
477
cpp
C++
build/b4-e6-2d-e0-5c-5d/user_app.cpp
chp-lab/nx2003-kidbright
1660fccae722f61b56194cb44857c3e724e4c159
[ "MIT" ]
null
null
null
build/b4-e6-2d-e0-5c-5d/user_app.cpp
chp-lab/nx2003-kidbright
1660fccae722f61b56194cb44857c3e724e4c159
[ "MIT" ]
null
null
null
build/b4-e6-2d-e0-5c-5d/user_app.cpp
chp-lab/nx2003-kidbright
1660fccae722f61b56194cb44857c3e724e4c159
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <WiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> #include <WebServer.h> #include <NX2003BUZZER.h> NX2003BUZZER music = NX2003BUZZER(); void setup() { music.begin(); } void loop() { music.song((std::vector<int>{262,523,220,440,233,466,-1,-1,175,349,147,294,156,311,-1,-1,175,349,147,294,156,311,-1,-1,175,349,147,294,156,311,-1,-1,311,277,294,277,311,311,208,196,277,262,370,349,165,466,440,415,311,247,233,220,208}),250); }
19.08
244
0.668763
chp-lab
727b96770131694f5aa981bbc58a6a8113311d46
261
cpp
C++
judges/codeforces/exercises/anton_and_letters.cpp
eduardonunes2525/competitive-programming
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
[ "MIT" ]
null
null
null
judges/codeforces/exercises/anton_and_letters.cpp
eduardonunes2525/competitive-programming
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
[ "MIT" ]
1
2018-10-17T11:53:02.000Z
2018-10-17T11:54:42.000Z
judges/codeforces/exercises/anton_and_letters.cpp
eduardonunes2525/competitive-programming
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
[ "MIT" ]
1
2018-10-17T12:14:04.000Z
2018-10-17T12:14:04.000Z
#include<bits/stdc++.h> using namespace std; int main(){ string s; getline(cin, s); set<char> st; for(auto c : s) if((c >= 97 and c<= 122) or (c >= 65 and c<= 90)) st.insert(c); cout << st.size() << "\n"; return 0; }
16.3125
57
0.482759
eduardonunes2525
727dfdb90f9080b6e09f26186a7b5b9dcacae796
749
cpp
C++
mod02/ex00/Fixed.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod02/ex00/Fixed.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod02/ex00/Fixed.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
2
2021-01-31T13:52:11.000Z
2021-05-19T18:36:17.000Z
#include "Fixed.hpp" const int Fixed::_binary_point = 8; Fixed::Fixed() : _raw(0) { std::cout << "Default constructor called" << std::endl; } Fixed::~Fixed() { std::cout << "Destructor called" << std::endl; } Fixed::Fixed(const Fixed& other) { std::cout << "Copy constructor called" << std::endl; *this = other; } Fixed& Fixed::operator=(const Fixed& other) { std::cout << "Assignation constructor called" << std::endl; if (this != &other) _raw = other._raw; return *this; } int Fixed::getRawBits() const { std::cout << "getRawBits member function call" << std::endl; return _raw; } void Fixed::setRawBits(int const raw) { std::cout << "setRawBits member function call" << std::endl; _raw = raw; }
22.029412
84
0.623498
paozer
727e7f1c4a9cd522f6b8468b5f15f190cf532159
2,441
cpp
C++
jbmc/src/java_bytecode/load_method_by_regex.cpp
lpmi-13/cbmc
dc4ffae64430ac5b1c971da44ce0dba189a5b6bf
[ "BSD-4-Clause" ]
null
null
null
jbmc/src/java_bytecode/load_method_by_regex.cpp
lpmi-13/cbmc
dc4ffae64430ac5b1c971da44ce0dba189a5b6bf
[ "BSD-4-Clause" ]
null
null
null
jbmc/src/java_bytecode/load_method_by_regex.cpp
lpmi-13/cbmc
dc4ffae64430ac5b1c971da44ce0dba189a5b6bf
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Java Bytecode Author: Diffblue Ltd. \*******************************************************************/ #include "load_method_by_regex.h" #include <regex> #include <util/symbol_table.h> /// For a given user provided pattern, return a regex, having dealt with the /// cases where the user has not prefixed with java:: or suffixed with the /// descriptor /// \param pattern: The user provided pattern /// \return The regex to match with static std::regex build_regex_from_pattern(const std::string &pattern) { std::string modified_pattern = pattern; if(does_pattern_miss_descriptor(pattern)) modified_pattern += R"(:\(.*\).*)"; if(!has_prefix(pattern, "java::")) modified_pattern = "java::" + modified_pattern; return std::regex{modified_pattern}; } /// Identify if a parameter includes a part that will match a descriptor. That /// is, does it have a colon separtor. /// \param pattern: The user provided pattern /// \return True if no descriptor is found (that is, the only : relates to the /// java:: prefix. bool does_pattern_miss_descriptor(const std::string &pattern) { const size_t descriptor_index = pattern.rfind(':'); if(descriptor_index == std::string::npos) return true; const std::string java_prefix = "java::"; return descriptor_index == java_prefix.length() - 1 && has_prefix(pattern, java_prefix); } /// Create a lambda that returns the symbols that the given pattern should be /// loaded.If the pattern doesn't include a colon for matching the descriptor, /// append a :\(.*\).* to the regex. Note this will mean all overloaded /// methods will be marked as extra entry points for CI lazy loading. /// If the pattern doesn't include the java:: prefix, prefix that /// \param pattern: The user provided pattern /// \return The lambda to execute. std::function<std::vector<irep_idt>(const symbol_tablet &symbol_table)> build_load_method_by_regex(const std::string &pattern) { std::regex regex = build_regex_from_pattern(pattern); return [=](const symbol_tablet &symbol_table) { std::vector<irep_idt> matched_methods; for(const auto &symbol : symbol_table.symbols) { if( symbol.second.is_function() && std::regex_match(id2string(symbol.first), regex)) { matched_methods.push_back(symbol.first); } } return matched_methods; }; }
32.546667
78
0.669398
lpmi-13
727ea4f7adc197c7824460b9f2a8fcb17a618b5a
6,269
hh
C++
dune/xt/grid/grids.hh
dune-community/dune-xt-grid
3453f6619fabc016beaf32409627fec8712f3ef9
[ "BSD-2-Clause" ]
2
2016-04-04T08:06:07.000Z
2020-02-08T04:10:38.000Z
dune/xt/grid/grids.hh
dune-community/dune-xt-grid
3453f6619fabc016beaf32409627fec8712f3ef9
[ "BSD-2-Clause" ]
77
2016-01-24T22:11:21.000Z
2020-03-25T08:30:31.000Z
dune/xt/grid/grids.hh
dune-community/dune-xt-grid
3453f6619fabc016beaf32409627fec8712f3ef9
[ "BSD-2-Clause" ]
4
2016-11-08T10:12:44.000Z
2020-02-08T04:10:41.000Z
// This file is part of the dune-xt-grid project: // https://github.com/dune-community/dune-xt-grid // Copyright 2009-2018 dune-xt-grid developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2016 - 2018) // René Fritze (2017 - 2018) // TiKeil (2018) // Tobias Leibner (2016) #ifndef DUNE_XT_GRID_GRIDS_HH #define DUNE_XT_GRID_GRIDS_HH #include <boost/tuple/tuple.hpp> #if HAVE_ALBERTA # include <dune/xt/common/disable_warnings.hh> # include <dune/grid/albertagrid.hh> # include <dune/xt/common/reenable_warnings.hh> #endif #if HAVE_DUNE_ALUGRID # include <dune/alugrid/grid.hh> #endif #if HAVE_DUNE_SPGRID # include <dune/grid/spgrid.hh> # include <dune/grid/spgrid/dgfparser.hh> #endif #if HAVE_DUNE_UGGRID || HAVE_UG # include <dune/grid/uggrid.hh> #endif #include <dune/grid/onedgrid.hh> #include <dune/grid/yaspgrid.hh> // this is used by other headers typedef Dune::OneDGrid ONED_1D; typedef Dune::YaspGrid<1, Dune::EquidistantOffsetCoordinates<double, 1>> YASP_1D_EQUIDISTANT_OFFSET; typedef Dune::YaspGrid<2, Dune::EquidistantOffsetCoordinates<double, 2>> YASP_2D_EQUIDISTANT_OFFSET; typedef Dune::YaspGrid<3, Dune::EquidistantOffsetCoordinates<double, 3>> YASP_3D_EQUIDISTANT_OFFSET; typedef Dune::YaspGrid<4, Dune::EquidistantOffsetCoordinates<double, 4>> YASP_4D_EQUIDISTANT_OFFSET; #if HAVE_DUNE_ALUGRID typedef Dune::ALUGrid<2, 2, Dune::simplex, Dune::conforming> ALU_2D_SIMPLEX_CONFORMING; typedef Dune::ALUGrid<2, 2, Dune::simplex, Dune::nonconforming> ALU_2D_SIMPLEX_NONCONFORMING; typedef Dune::ALUGrid<2, 2, Dune::cube, Dune::nonconforming> ALU_2D_CUBE; typedef Dune::ALUGrid<3, 3, Dune::simplex, Dune::conforming> ALU_3D_SIMPLEX_CONFORMING; typedef Dune::ALUGrid<3, 3, Dune::simplex, Dune::nonconforming> ALU_3D_SIMPLEX_NONCONFORMING; typedef Dune::ALUGrid<3, 3, Dune::cube, Dune::nonconforming> ALU_3D_CUBE; #endif #if HAVE_DUNE_UGGRID || HAVE_UG typedef Dune::UGGrid<2> UG_2D; typedef Dune::UGGrid<3> UG_3D; #endif #if HAVE_ALBERTA typedef Dune::AlbertaGrid<2, 2> ALBERTA_2D; typedef Dune::AlbertaGrid<3, 3> ALBERTA_3D; #endif namespace Dune { namespace XT { namespace Grid { namespace internal { // To give better error messages, required below. template <size_t d> class ThereIsNoSimplexGridAvailableInDimension {}; } // namespace internal /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. */ using Available1dGridTypes = boost::tuple<ONED_1D, YASP_1D_EQUIDISTANT_OFFSET>; /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. */ using Available2dGridTypes = boost::tuple<YASP_2D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_2D_SIMPLEX_CONFORMING, ALU_2D_SIMPLEX_NONCONFORMING, ALU_2D_CUBE #endif #if HAVE_DUNE_UGGRID || HAVE_UG , UG_2D #endif >; /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. */ using Available3dGridTypes = boost::tuple<YASP_3D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_3D_SIMPLEX_CONFORMING, ALU_3D_SIMPLEX_NONCONFORMING, ALU_3D_CUBE #endif #if HAVE_DUNE_UGGRID || HAVE_UG , UG_3D #endif >; /** * \note Alberta grids are missing here on purpose, these cannot be handled automatically very well. * \todo Find a tuple implementation which allows for more than 10 elements! */ using AvailableGridTypes = boost::tuple<ONED_1D, /*YASP_1D_EQUIDISTANT_OFFSET,*/ YASP_2D_EQUIDISTANT_OFFSET, YASP_3D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_2D_SIMPLEX_CONFORMING, /*ALU_2D_SIMPLEX_NONCONFORMING,*/ ALU_2D_CUBE, ALU_3D_SIMPLEX_CONFORMING, /*ALU_3D_SIMPLEX_NONCONFORMING,*/ ALU_3D_CUBE #endif #if HAVE_DUNE_UGGRID || HAVE_UG , UG_2D, UG_3D #endif >; } // namespace Grid } // namespace XT } // namespace Dune using SIMPLEXGRID_1D = ONED_1D; using SIMPLEXGRID_2D = #if HAVE_DUNE_ALUGRID ALU_2D_SIMPLEX_CONFORMING; #elif HAVE_DUNE_UGGRID || HAVE_UG UG_2D; #else Dune::XT::Grid::internal::ThereIsNoSimplexGridAvailableInDimension<2>; #endif using SIMPLEXGRID_3D = #if HAVE_DUNE_ALUGRID ALU_3D_SIMPLEX_CONFORMING; #elif HAVE_DUNE_UGGRID || HAVE_UG UG_3D; #else Dune::XT::Grid::internal::ThereIsNoSimplexGridAvailableInDimension<3>; #endif using CUBEGRID_1D = ONED_1D; using CUBEGRID_2D = YASP_2D_EQUIDISTANT_OFFSET; using CUBEGRID_3D = YASP_3D_EQUIDISTANT_OFFSET; #if HAVE_DUNE_ALUGRID || HAVE_DUNE_UGGRID || HAVE_UG # define SIMPLEXGRID_2D_AVAILABLE 1 # define SIMPLEXGRID_3D_AVAILABLE 1 #else # define SIMPLEXGRID_2D_AVAILABLE 0 # define SIMPLEXGRID_3D_AVAILABLE 0 #endif using GRID_1D = ONED_1D; using GRID_2D = #if SIMPLEXGRID_2D_AVAILABLE SIMPLEXGRID_2D; #else YASP_2D_EQUIDISTANT_OFFSET; #endif using GRID_3D = #if SIMPLEXGRID_3D_AVAILABLE SIMPLEXGRID_3D; #else YASP_3D_EQUIDISTANT_OFFSET; #endif #endif // DUNE_XT_GRID_GRIDS_HH
31.984694
100
0.63471
dune-community
72819b0e64862f2e0e249903ce8470af40cf9153
32,754
cc
C++
3rd_party/volfill/OccGridRLE.cc
yuxng/3DVP
3551a31bc45d49e661f2140ea90b8bd83fe65e3b
[ "MIT" ]
42
2016-07-03T22:16:47.000Z
2021-03-30T22:23:46.000Z
3rd_party/volfill/OccGridRLE.cc
PeiliangLi/3DVP
3551a31bc45d49e661f2140ea90b8bd83fe65e3b
[ "MIT" ]
2
2016-11-12T10:36:48.000Z
2017-09-07T11:32:34.000Z
3rd_party/volfill/OccGridRLE.cc
PeiliangLi/3DVP
3551a31bc45d49e661f2140ea90b8bd83fe65e3b
[ "MIT" ]
16
2016-08-06T01:20:40.000Z
2020-07-13T14:59:35.000Z
/* Brian Curless Computer Graphics Laboratory Stanford University --------------------------------------------------------------------- Copyright (1997) The Board of Trustees of the Leland Stanford Junior University. Except for commercial resale, lease, license or other commercial transactions, permission is hereby given to use, copy, modify this software for academic purposes only. No part of this software or any derivatives thereof may be used in the production of computer models for resale or for use in a commercial product. STANFORD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THIS SOFTWARE. No support is implied or provided. */ #include <limits.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #ifdef linux #include <endian.h> #endif #include "OccGridRLE.h" // Lucas: // Should we recompact (copy twice) the RLE pointers after doing // a transpose? It would have better memory coherence, but it also // costs a lot... In my tests, it was faster to avoid recompacting. #define OCCGRIDRLE_RECOMPACT 0 OccScanlineRLE::OccScanlineRLE() { this->lengths = NULL; this->elements = NULL; } OccScanlineRLE::OccScanlineRLE(int dim) { this->lengths = new RunLength[dim]; this->elements = new OccElement[dim]; } OccScanlineRLE::~OccScanlineRLE() { if (this->lengths != NULL) { delete [] this->lengths; } if (this->elements != NULL) { delete [] this->elements; } } OccGridRLE::OccGridRLE() { this->xdim = this->ydim = this->zdim = 0; this->axis = Z_AXIS; this->flip = FALSE; this->origin[0] = 0; this->origin[1] = 0; this->origin[2] = 0; this->lengthChunker = NULL; this->elementChunker = NULL; this->rleScanline = new OccScanlineRLE; this->defaultElement = new OccElement; //this->defaultElement->value = 0; this->defaultElement->value = USHRT_MAX; this->defaultElement->totalWeight = 0; this->emptyNoWeight.value = 0; this->emptyNoWeight.totalWeight = 0; this->fullNoWeight.value = USHRT_MAX; this->fullNoWeight.totalWeight = 0; } OccGridRLE::OccGridRLE(int xd, int yd, int zd, int num) { this->xdim = this->ydim = this->zdim = 0; this->axis = Z_AXIS; this->flip = FALSE; this->origin[0] = 0; this->origin[1] = 0; this->origin[2] = 0; this->rleScanline = new OccScanlineRLE; this->defaultElement = new OccElement; this->defaultElement->value = 0; this->defaultElement->totalWeight = 0; this->emptyNoWeight.value = 0; this->emptyNoWeight.totalWeight = 0; this->fullNoWeight.value = USHRT_MAX; this->fullNoWeight.totalWeight = 0; this->lengthChunker = NULL; this->elementChunker = NULL; this->init(xd, yd, zd, num); } void OccGridRLE::init(int xd, int yd, int zd, int num) { int size1, size2, size3, sliceSize; this->xdim = xd; this->ydim = yd; this->zdim = zd; int maxdim = MAX(this->xdim, MAX(this->ydim, this->zdim)); this->sliceOrigins = new vec3f[maxdim]; this->scanline = new OccElement[maxdim]; this->axis = Z_AXIS; this->flip = FALSE; this->origin[0] = 0; this->origin[1] = 0; this->origin[2] = 0; size1 = xd*yd; size2 = xd*zd; size3 = yd*zd; sliceSize = MAX(MAX(size1, size2), size3); this->slice = new OccElement[sliceSize]; this->rleScanline = new OccScanlineRLE; this->defaultElement = new OccElement; this->defaultElement->value = USHRT_MAX; this->defaultElement->totalWeight = 0; this->emptyNoWeight.value = 0; this->emptyNoWeight.totalWeight = 0; this->fullNoWeight.value = USHRT_MAX; this->fullNoWeight.totalWeight = 0; this->lengthAddr = new RunLength*[sliceSize]; this->elementAddr = new OccElement*[sliceSize]; if (this->lengthChunker == NULL) this->lengthChunker = new ChunkAllocator(num); else if (this->lengthChunker->chunkSize != num) { delete this->lengthChunker; this->lengthChunker = new ChunkAllocator(num); } else { this->lengthChunker->reset(); } if (this->elementChunker == NULL) this->elementChunker = new ChunkAllocator(num); else if (this->elementChunker->chunkSize != num) { delete this->elementChunker; this->elementChunker = new ChunkAllocator(num); } else { this->elementChunker->reset(); } // Compute the maximum bytes needed for a scanline // Fix this!! if (sizeof(OccElement) >= 2*sizeof(ushort)) { this->transpXZbytesPerScanline = this->xdim*sizeof(OccElement)+3*sizeof(ushort); } else { this->transpXZbytesPerScanline = this->xdim/2* (sizeof(OccElement)+2*sizeof(ushort)) + sizeof(ushort); } this->transpXZslice = new uchar[this->zdim*this->transpXZbytesPerScanline]; this->clear(); } OccGridRLE::~OccGridRLE() { this->freeSpace(); } void OccGridRLE::freeSpace() { if (this->sliceOrigins != NULL) { delete [] this->sliceOrigins; } if (this->lengthAddr != NULL) { delete [] this->lengthAddr; } if (this->elementAddr != NULL) { delete [] this->elementAddr; } if (this->slice != NULL) { delete [] this->slice; } if (this->scanline != NULL) { delete [] this->scanline; } if (this->rleScanline != NULL) { delete this->rleScanline; } if (this->defaultElement != NULL) { delete this->defaultElement; } if (this->elementChunker != NULL) { delete this->elementChunker; } if (this->lengthChunker != NULL) { delete this->lengthChunker; } if (this->transpXZslice != NULL) { delete [] this->transpXZslice; } } void OccGridRLE::copyParams(OccGridRLE *other) { this->xdim = other->xdim; this->ydim = other->ydim; this->zdim = other->zdim; this->axis = other->axis; this->flip = other->flip; this->origin[0] = other->origin[0]; this->origin[1] = other->origin[1]; this->origin[2] = other->origin[2]; } void OccGridRLE::allocNewRun(int y, int z) { // Make room for contiguous runs and point the length and data // pointers to the next place that length and data will be put this->elementChunker->newChunkIfNeeded(sizeof(OccElement)*(this->xdim+1)); this->elementAddr[y + z*this->ydim] = (OccElement *)this->elementChunker->currentAddr; this->lengthChunker->newChunkIfNeeded(sizeof(RunLength)*(this->xdim+1)); this->lengthAddr[y + z*this->ydim] = (RunLength *)this->lengthChunker->currentAddr; setScanline(y, z); } void OccGridRLE::setScanline(int y, int z) { currentLength = this->lengthAddr[y + z*this->ydim]; currentElem = this->elementAddr[y + z*this->ydim]; } #if defined(linux) && BYTE_ORDER == LITTLE_ENDIAN static inline void swap_4(const void *p, size_t size) { char t; for (char *pc = (char *) p; pc < (char *) p + size; pc += 4) { t = pc[0]; pc[0] = pc[3]; pc[3] = t; t = pc[1]; pc[1] = pc[2]; pc[2] = t; } } static inline void swap_2(const void *p, size_t size) { char t; for (char *pc = (char *) p; pc < (char *) p + size; pc += 2) { t = pc[0]; pc[0] = pc[1]; pc[1] = t; } } static inline void write_fix_int(const void *p, size_t size, size_t nitems, FILE *fp) { swap_4(p, size * nitems); fwrite(p, size, nitems, fp); swap_4(p, size * nitems); } static inline void write_fix_float(const void *p, size_t size, size_t nitems, FILE *fp) { swap_4(p, size * nitems); fwrite(p, size, nitems, fp); swap_4(p, size * nitems); } static inline void write_fix_ushort(const void *p, size_t size, size_t nitems, FILE *fp) { swap_2(p, size * nitems); fwrite(p, size, nitems, fp); swap_2(p, size * nitems); } static inline void read_fix_int(void *p, size_t size, size_t nitems, FILE *fp) { fread(p, size, nitems, fp); swap_4(p, size * nitems); } static inline void read_fix_float(void *p, size_t size, size_t nitems, FILE *fp) { fread(p, size, nitems, fp); swap_4(p, size * nitems); } static inline void read_fix_ushort(void *p, size_t size, size_t nitems, FILE *fp) { fread(p, size, nitems, fp); swap_2(p, size * nitems); } #else static inline void write_fix_int(const void *p, size_t size, size_t nitems, FILE *fp) { fwrite(p, size, nitems, fp); } static inline void write_fix_float(const void *p, size_t size, size_t nitems, FILE *fp) { fwrite(p, size, nitems, fp); } static inline void write_fix_ushort(const void *p, size_t size, size_t nitems, FILE *fp) { fwrite(p, size, nitems, fp); } static inline void read_fix_int(void *p, size_t size, size_t nitems, FILE *fp) { fread(p, size, nitems, fp); } static inline void read_fix_float(void *p, size_t size, size_t nitems, FILE *fp) { fread(p, size, nitems, fp); } static inline void read_fix_ushort(void *p, size_t size, size_t nitems, FILE *fp) { fread(p, size, nitems, fp); } #endif int OccGridRLE::write(char *filename) { FILE *fp = fopen(filename, "wb"); if (fp == NULL) return FALSE; write_fix_int(&this->xdim, sizeof(int), 1, fp); write_fix_int(&this->ydim, sizeof(int), 1, fp); write_fix_int(&this->zdim, sizeof(int), 1, fp); write_fix_int(&this->axis, sizeof(int), 1, fp); write_fix_int(&this->flip, sizeof(int), 1, fp); write_fix_float(&this->origin, sizeof(float), 3, fp); write_fix_float(&this->resolution, sizeof(float), 1, fp); int yy, zz, numRuns, numElems; // First count bytes int lengthByteCount = 0; int elementByteCount = 0; for (zz = 0; zz < this->zdim; zz++) { for (yy = 0; yy < this->ydim; yy++) { runStats(yy, zz, &numRuns, &numElems); // Don't forget the END_OF_RUN lengthByteCount = lengthByteCount + (numRuns + 1)*sizeof(RunLength); elementByteCount = elementByteCount + (numElems)*sizeof(OccElement); } } write_fix_int(&lengthByteCount, sizeof(int), 1, fp); write_fix_int(&elementByteCount, sizeof(int), 1, fp); int i; RunLength length; int runType; OccElement *element; for (zz = 0; zz < this->zdim; zz++) { for (yy = 0; yy < this->ydim; yy++) { setScanline(yy, zz); while (TRUE) { length = getNextLength(); write_fix_ushort(&length, sizeof(RunLength), 1, fp); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; if (runType == OccGridRLE::CONSTANT_DATA) { element = getNextElement(); write_fix_ushort(element, sizeof(OccElement), 1, fp); } else { for (i=0; i<length; i++) { element = getNextElement(); write_fix_ushort(element, sizeof(OccElement), 1, fp); } } } } } fclose(fp); return TRUE; } int OccGridRLE::read(char *filename) { int size1, size2, size3, xd, yd, zd, sliceSize; FILE *fp = fopen(filename, "rb"); if (fp == NULL) return FALSE; read_fix_int(&xd, sizeof(int), 1, fp); read_fix_int(&yd, sizeof(int), 1, fp); read_fix_int(&zd, sizeof(int), 1, fp); if (xd != this->xdim || yd != this->ydim || zd != this->zdim) { size1 = xd*yd; size2 = xd*zd; size3 = yd*zd; sliceSize = MAX(MAX(size1, size2), size3); if (this->slice != NULL) delete [] this->slice; this->slice = new OccElement[sliceSize]; if (this->lengthAddr != NULL) delete [] this->lengthAddr; this->lengthAddr = new RunLength*[sliceSize]; if (this->elementAddr != NULL) delete [] this->elementAddr; this->elementAddr = new OccElement*[sliceSize]; int maxdim = MAX(xd, MAX(yd, zd)); if (this->sliceOrigins != NULL) delete [] this->sliceOrigins; this->sliceOrigins = new vec3f[maxdim]; if (this->scanline != NULL) delete [] this->scanline; this->scanline = new OccElement[maxdim]; this->xdim = xd; this->ydim = yd; this->zdim = zd; if (sizeof(OccElement) > 2*sizeof(ushort)) { this->transpXZbytesPerScanline = this->xdim*sizeof(OccElement)+3*sizeof(ushort); } else { this->transpXZbytesPerScanline = this->xdim/2* (sizeof(OccElement)+2*sizeof(ushort)) + sizeof(ushort); } if (this->transpXZslice != NULL) delete [] this->transpXZslice; this->transpXZslice = new uchar [this->zdim*this->transpXZbytesPerScanline]; } read_fix_int(&this->axis, sizeof(int), 1, fp); read_fix_int(&this->flip, sizeof(int), 1, fp); read_fix_float(&this->origin, sizeof(float), 3, fp); read_fix_float(&this->resolution, sizeof(float), 1, fp); int lengthByteCount, elementByteCount; read_fix_int(&lengthByteCount, sizeof(int), 1, fp); read_fix_int(&elementByteCount, sizeof(int), 1, fp); reset(); int i, yy, zz; RunLength length; int runType; OccElement element; for (zz = 0; zz < this->zdim; zz++) { for (yy = 0; yy < this->ydim; yy++) { allocNewRun(yy, zz); while (TRUE) { read_fix_ushort(&length, sizeof(RunLength), 1, fp); putNextLength(length); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; if (runType == OccGridRLE::CONSTANT_DATA) { read_fix_ushort(&element, sizeof(OccElement), 1, fp); putNextElement(&element); } else { for (i=0; i<length; i++) { read_fix_ushort(&element, sizeof(OccElement), 1, fp); putNextElement(&element); } } } } } fclose(fp); return TRUE; } int OccGridRLE::writeDen(char *) { /* orig_min[0] = extr_min[0] = map_min[0] = 0; orig_min[1] = extr_min[1] = map_min[1] = 0; orig_min[2] = extr_min[2] = map_min[2] = 0; orig_max[0] = extr_max[0] = map_max[0] = this->xdim - 1; orig_max[1] = extr_max[1] = map_max[1] = this->ydim - 1; orig_max[2] = extr_max[2] = map_max[2] = this->zdim - 1; orig_len[0] = extr_len[0] = map_len[0] = this->xdim; orig_len[1] = extr_len[1] = map_len[1] = this->ydim; orig_len[2] = extr_len[2] = map_len[2] = this->zdim; map_warps = 0; map_length = (long)map_len[X] * (long)map_len[Y] * (long)map_len[Z]; map_address = (uchar *)(this->elems); Store_Indexed_DEN_File(filename, sizeof(OccElement)); */ // So much for error checking... return TRUE; } void OccGridRLE::copy(OccGridRLE *other) { OccScanlineRLE *rleScanline; this->reset(); this->copyParams(other); for (int zz = 0; zz < this->zdim; zz++) { for (int yy = 0; yy < this->ydim; yy++) { rleScanline = other->getRLEScanline(yy, zz); this->copyScanline(rleScanline, yy, zz); } } } int OccGridRLE::transposeXZ(OccGridRLE *outGrid) { int zz, yy; OccScanlineRLE *rleScanlines; OccElement *elementData; RunLength *lengthData; int *runTypes; outGrid->reset(); outGrid->copyParams(this); SWAP_INT(outGrid->xdim, outGrid->zdim); SWAP_FLOAT(outGrid->origin[0], outGrid->origin[2]); // Set up the new scanlines rleScanlines = new OccScanlineRLE[outGrid->zdim]; /* rleScanlines = new OccScanlineRLE[outGrid->zdim]; for (zz = 0; zz < outGrid->zdim; zz++) { rleScanlines[zz].lengths = new RunLength[outGrid->xdim + 1]; rleScanlines[zz].elements = new OccElement[outGrid->xdim + 1]; } */ lengthData = new RunLength[(outGrid->xdim+1)*outGrid->zdim]; elementData = new OccElement[(outGrid->xdim)*outGrid->zdim]; for (zz = 0; zz < outGrid->zdim; zz++) { rleScanlines[zz].lengths = lengthData + zz*(outGrid->xdim + 1); rleScanlines[zz].elements = elementData + zz*(outGrid->xdim); } // For bookeeping runTypes = new int[outGrid->zdim]; // Rename the bookeeping int *runOffset = runTypes; // Loop over slices for (yy = 0; yy < this->ydim; yy++) { // Initialize scanlines and bookkeeping for (zz = 0; zz < outGrid->zdim; zz++) { rleScanlines[zz].reset(); runOffset[zz] = 0; } int xx; RunLength length; int runType, i; OccElement *element; // Lay down first scanline xx = 0; setScanline(yy, 0); while (TRUE) { length = getNextLength(); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; if (runType == OccGridRLE::CONSTANT_DATA) { element = getNextElement(); for (i=0; i < length; i++, xx++) { rleScanlines[xx].putNextElement(element); } } else { for (i=0; i<length; i++, xx++) { element = getNextElement(); rleScanlines[xx].putNextElement(element); } } } assert(xx == this->xdim); // Process the current and previous scanlines concurrently int end1, end2, type1, type2; RunLength length1, length2; OccElement *elem1, *elem2; OccScanlineRLE *lastScanline; // Loop over scanlines for (zz = 1; zz < this->zdim; zz++) { // Load up previous scanline lastScanline = getRLEScanline(yy, zz-1); lastScanline->reset(); // Load up current scanline setScanline(yy, zz); // Initialize xx = 0; end1 = 0; end2 = 0; while (xx < this->xdim) { // Load up new lengths and/or new element from prior scanline if (xx == end1) { length1 = lastScanline->getNextLength(); type1 = getRunType(&length1); end1 += length1; elem1 = lastScanline->getNextElement(); } else if (type1 == OccGridRLE::VARYING_DATA) { elem1 = lastScanline->getNextElement(); } // Load up new lengths and/or new element from current scanline if (xx == end2) { length2 = getNextLength(); type2 = getRunType(&length2); end2 += length2; elem2 = getNextElement(); } else if (type2 == OccGridRLE::VARYING_DATA) { elem2 = getNextElement(); } if (type1 == OccGridRLE::CONSTANT_DATA && type2 == OccGridRLE::CONSTANT_DATA && elem1->value == elem2->value && elem2->totalWeight == elem2->totalWeight) { // If both are the same constant value, then skip to end // of one of them, whichever comes first xx = MIN(end1, end2); } else if (type1 == OccGridRLE::VARYING_DATA && type2 == OccGridRLE::VARYING_DATA) { // If both are varying values, then write the new value rleScanlines[xx].putNextElement(elem2); xx++; } else { // Else, clean up old run by updating length length = zz - runOffset[xx]; setRunType(&length, type1); rleScanlines[xx].putNextLength(length); // Prepare for new run runOffset[xx] = zz; rleScanlines[xx].putNextElement(elem2); xx++; } } } // One last run through to finish up lengths zz = this->zdim; lastScanline = getRLEScanline(yy, zz-1); lastScanline->reset(); xx = 0; end1 = 0; while (xx < this->xdim) { if (xx == end1) { length1 = lastScanline->getNextLength(); type1 = getRunType(&length1); end1 += length1; elem1 = lastScanline->getNextElement(); } else if (type1 == OccGridRLE::VARYING_DATA) { elem1 = lastScanline->getNextElement(); } length = zz - runOffset[xx]; setRunType(&length, type1); rleScanlines[xx].putNextLength(length); xx++; } // Write out the end-of-run flags and copy runs to output grid for (zz = 0; zz < outGrid->zdim; zz++) { rleScanlines[zz].putNextLength(OccGridRLE::END_OF_RUN); outGrid->allocNewRun(yy, zz); outGrid->copyScanline(&rleScanlines[zz], yy, zz); } } #if OCCGRIDRLE_RECOMPACT // Re-compactify this->copy(outGrid); // Put into output outGrid->copy(this); #endif //OCCGRIDRLE_RECOMPACT // So that scanline deletion will not try to free these for (zz = 0; zz < outGrid->zdim; zz++) { rleScanlines[zz].lengths = NULL; rleScanlines[zz].elements = NULL; } delete [] rleScanlines; delete [] lengthData; delete [] elementData; delete [] runTypes; return TRUE; } int OccGridRLE::transposeXY(OccGridRLE *outGrid) { int zz, yy; OccScanlineRLE *rleScanlines; OccElement *elementData; RunLength *lengthData; int *runTypes; outGrid->reset(); outGrid->copyParams(this); SWAP_INT(outGrid->xdim, outGrid->ydim); SWAP_FLOAT(outGrid->origin[0], outGrid->origin[1]); rleScanlines = new OccScanlineRLE[outGrid->ydim]; lengthData = new RunLength[(outGrid->xdim+1)*outGrid->ydim]; elementData = new OccElement[(outGrid->xdim)*outGrid->ydim]; for (yy = 0; yy < outGrid->ydim; yy++) { rleScanlines[yy].lengths = lengthData + yy*(outGrid->xdim + 1); rleScanlines[yy].elements = elementData + yy*(outGrid->xdim); } runTypes = new int[outGrid->ydim]; // Rename the bookeeping int *runOffset = runTypes; // Loop over slices for (zz = 0; zz < this->zdim; zz++) { // Initialize scanlines and bookkeeping for (yy = 0; yy < outGrid->ydim; yy++) { rleScanlines[yy].reset(); runOffset[yy] = 0; } int xx; RunLength length; int runType, i; OccElement *element; // Lay down first scanline xx = 0; setScanline(0, zz); while (TRUE) { length = getNextLength(); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; if (runType == OccGridRLE::CONSTANT_DATA) { element = getNextElement(); for (i=0; i < length; i++, xx++) { rleScanlines[xx].putNextElement(element); } } else { for (i=0; i<length; i++, xx++) { element = getNextElement(); rleScanlines[xx].putNextElement(element); } } } assert(xx == this->xdim); // Process the current and previous scanlines concurrently int end1, end2, type1, type2; RunLength length1, length2; OccElement *elem1, *elem2; OccScanlineRLE *lastScanline; // Loop over scanlines for (yy = 1; yy < this->ydim; yy++) { // Load up previous scanline lastScanline = getRLEScanline(yy-1, zz); lastScanline->reset(); // Load up current scanline setScanline(yy, zz); // Initialize xx = 0; end1 = 0; end2 = 0; while (xx < this->xdim) { // Load up new lengths and/or new element from prior scanline if (xx == end1) { length1 = lastScanline->getNextLength(); type1 = getRunType(&length1); end1 += length1; elem1 = lastScanline->getNextElement(); } else if (type1 == OccGridRLE::VARYING_DATA) { elem1 = lastScanline->getNextElement(); } // Load up new lengths and/or new element from current scanline if (xx == end2) { length2 = getNextLength(); type2 = getRunType(&length2); end2 += length2; elem2 = getNextElement(); } else if (type2 == OccGridRLE::VARYING_DATA) { elem2 = getNextElement(); } if (type1 == OccGridRLE::CONSTANT_DATA && type2 == OccGridRLE::CONSTANT_DATA && elem1->value == elem2->value && elem2->totalWeight == elem2->totalWeight) { // If both are the same constant value, then skip to end // of one of them, whichever comes first xx = MIN(end1, end2); } else if (type1 == OccGridRLE::VARYING_DATA && type2 == OccGridRLE::VARYING_DATA) { // If both are varying values, then write the new value rleScanlines[xx].putNextElement(elem2); xx++; } else { // Else, clean up old run by updating length length = yy - runOffset[xx]; setRunType(&length, type1); rleScanlines[xx].putNextLength(length); // Prepare for new run runOffset[xx] = yy; rleScanlines[xx].putNextElement(elem2); xx++; } } } // One last run through to finish up lengths yy = this->ydim; lastScanline = getRLEScanline(yy-1, zz); lastScanline->reset(); xx = 0; end1 = 0; while (xx < this->xdim) { if (xx == end1) { length1 = lastScanline->getNextLength(); type1 = getRunType(&length1); end1 += length1; elem1 = lastScanline->getNextElement(); } else if (type1 == OccGridRLE::VARYING_DATA) { elem1 = lastScanline->getNextElement(); } length = yy - runOffset[xx]; setRunType(&length, type1); rleScanlines[xx].putNextLength(length); xx++; } // Write out the end-of-run flags and copy runs to output grid for (yy = 0; yy < outGrid->ydim; yy++) { rleScanlines[yy].putNextLength(OccGridRLE::END_OF_RUN); outGrid->allocNewRun(yy, zz); outGrid->copyScanline(&rleScanlines[yy], yy, zz); } } #if OCCGRIDRLE_RECOMPACT // Re-compactify this->copy(outGrid); // Put into output outGrid->copy(this); #endif //OCCGRIDRLE_RECOMPACT // So that scanline deletion will not try to free these for (yy = 0; yy < outGrid->ydim; yy++) { rleScanlines[yy].lengths = NULL; rleScanlines[yy].elements = NULL; } delete [] rleScanlines; delete [] lengthData; delete [] elementData; delete [] runTypes; return TRUE; } int OccGridRLE::transposeYZ(OccGridRLE *outGrid) { int yy,zz; OccScanlineRLE *rleScanline; outGrid->reset(); outGrid->copyParams(this); SWAP_INT(outGrid->ydim, outGrid->zdim); SWAP_FLOAT(outGrid->origin[1], outGrid->origin[2]); for (zz = 0; zz < outGrid->zdim; zz++) { for (yy = 0; yy < outGrid->ydim; yy++) { rleScanline = this->getRLEScanline(zz, yy); outGrid->copyScanline(rleScanline, yy, zz); } } if (outGrid->axis == Y_AXIS) outGrid->axis = Z_AXIS; else if (outGrid->axis == Z_AXIS) outGrid->axis = Y_AXIS; return TRUE; } OccScanlineRLE * OccGridRLE::getRLEScanline(int y, int z) { setScanline(y, z); rleScanline->lengths = currentLength; rleScanline->elements = currentElem; rleScanline->reset(); return rleScanline; } OccElement * OccGridRLE::getScanline(int y, int z, OccElement *line) { int i; assert (y<=ydim); assert (z<=zdim); assert (y>=0); assert (z>=0); setScanline(y, z); //printf ("%d %d\n",y,z); OccElement *scanPtr; if (line) scanPtr = line; else scanPtr = this->scanline; RunLength length; int runType; OccElement *element; int xx = 0; while (TRUE) { length = getNextLength(); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; if (runType == OccGridRLE::CONSTANT_DATA) { element = getNextElement(); for (i=0; i<length; i++, scanPtr++, xx++) { scanPtr->value = element->value; scanPtr->totalWeight = element->totalWeight; } } else { for (i=0; i<length; i++, scanPtr++, xx++) { element = getNextElement(); scanPtr->value = element->value; scanPtr->totalWeight = element->totalWeight; } } } assert(xx == this->xdim); if (line) return line; else return this->scanline; } void OccGridRLE::copyScanline(OccScanlineRLE *rleScanline, int y, int z) { int i; RunLength length; int runType; OccElement *element; rleScanline->reset(); allocNewRun(y,z); while (TRUE) { length = rleScanline->getNextLength(); putNextLength(length); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; if (runType == OccGridRLE::CONSTANT_DATA) { element = rleScanline->getNextElement(); putNextElement(element); } else { for (i=0; i<length; i++) { element = rleScanline->getNextElement(); putNextElement(element); } } } } void OccGridRLE::putScanline(OccElement *line, int y, int z) { OccElement *scan = line; ushort count; int xoff = 0; allocNewRun(y, z); while (TRUE) { if (scan->totalWeight == emptyNoWeight.totalWeight && scan->value == emptyNoWeight.value) { count = 0; while(scan->totalWeight == emptyNoWeight.totalWeight && scan->value == emptyNoWeight.value && xoff < this->xdim) { scan++; count++; xoff++; } setRunType(&count, OccGridRLE::CONSTANT_DATA); putNextLength(count); putNextElement(&emptyNoWeight); } else if (scan->totalWeight == fullNoWeight.totalWeight && scan->value == fullNoWeight.value) { count = 0; while(scan->totalWeight == fullNoWeight.totalWeight && scan->value == fullNoWeight.value && xoff < this->xdim) { scan++; count++; xoff++; } setRunType(&count, OccGridRLE::CONSTANT_DATA); putNextLength(count); putNextElement(&fullNoWeight); } else { count = 0; while (!(scan->totalWeight == emptyNoWeight.totalWeight && scan->value == emptyNoWeight.value) && !(scan->totalWeight == fullNoWeight.totalWeight && scan->value == fullNoWeight.value) && xoff < this->xdim) { putNextElement(scan); scan++; count++; xoff++; } setRunType(&count, OccGridRLE::VARYING_DATA); putNextLength(count); } if (xoff == this->xdim) { setRunType(&count, OccGridRLE::END_OF_RUN); putNextLength(count); break; } } } OccElement * OccGridRLE::getSlice(char *axis, int sliceNum, int *pxdim, int *pydim) { OccElement *buf1, *buf2; int xx, yy, zz; buf1 = slice; if (EQSTR(axis, "x")) { if (sliceNum < this->xdim) { for (yy = 0; yy < this->ydim; yy++) { for (zz = 0; zz <this->zdim; zz++, buf1++) { buf2 = this->getElement(sliceNum, yy, zz); buf1->value = buf2->value; buf1->totalWeight = buf2->totalWeight; } } } *pxdim = this->zdim; *pydim = this->ydim; } else if (EQSTR(axis, "y")) { if (sliceNum < this->ydim) { for (zz = 0; zz < this->zdim; zz++) { buf2 = this->getScanline(sliceNum,zz); for (xx = 0; xx < this->xdim; xx++, buf1++, buf2++) { buf1->value = buf2->value; buf1->totalWeight = buf2->totalWeight; } } } *pxdim = this->xdim; *pydim = this->zdim; } else if (EQSTR(axis, "z")) { if (sliceNum < this->zdim) { for (yy = 0; yy < this->ydim; yy++) { buf2 = this->getScanline(yy, sliceNum); for (xx = 0; xx < this->xdim; xx++, buf1++, buf2++) { buf1->value = buf2->value; buf1->totalWeight = buf2->totalWeight; } } } *pxdim = this->xdim; *pydim = this->ydim; } return this->slice; } void OccGridRLE::clear() { RunLength length, end; this->reset(); setRunType(&end, OccGridRLE::END_OF_RUN); length = this->xdim; setRunType(&length, OccGridRLE::CONSTANT_DATA); for (int zz = 0; zz < this->zdim; zz++) { for (int yy = 0; yy < this->ydim; yy++) { allocNewRun(yy, zz); putNextLength(length); putNextElement(defaultElement); putNextLength(end); } } } void OccGridRLE::reset() { this->lengthChunker->reset(); this->elementChunker->reset(); } void OccGridRLE::runStats(int yy, int zz, int *numRuns, int *numElems) { int runType, runCount, elemCount; RunLength length; setScanline(yy,zz); runCount = 0; elemCount = 0; while (TRUE) { length = getNextLength(); runType = getRunType(&length); if (runType == OccGridRLE::END_OF_RUN) break; elemCount += length; runCount++; } *numRuns = runCount; *numElems = elemCount; } OccElement * OccGridRLE::getElement(int xx, int yy, int zz) { OccElement *element; RunLength length; int runType; setScanline(yy, zz); int currentX = 0; while (TRUE) { length = getNextLength(); runType = getRunType(&length); assert(runType != OccGridRLE::END_OF_RUN); if (runType == OccGridRLE::CONSTANT_DATA) { element = getNextElement(); currentX += length; if (xx < currentX) break; } else { // Really inefficient!! /* for (int i = 0; i < length; i++, currentX++) { element = getNextElement(); if (xx == currentX) break; } */ if (xx < currentX+length) { currentElem += (xx - currentX); element = getNextElement(); break; } else { currentX += length; currentElem += length; } } } return element; } OccElement OccGridRLE::voxRead(int x, int y, int z) { assert(x>=0 && x<xdim && y>=0 && y<ydim && z>=0 && z<zdim); OccElement *line; line = getScanline(y,z); return line[x]; } void OccGridRLE::voxWrite(int x, int y, int z, OccElement &el) { assert(x>=0 && x<xdim && y>=0 && y<ydim && z>=0 && z<zdim); OccElement *line; line = getScanline(y,z); line[x]=el; putScanline(line,y,z); } OccGrid *OccGridRLE::voxExpand() { puts ("Expanding grid"); printf("OccEl size %d\n",sizeof(OccElement)); printf("About to use MB%d\n " ,(int)(sizeof(OccElement)*(double)xdim*(double)ydim*(double)zdim/(double)(1024*1024))); OccGrid *og=new OccGrid(xdim,ydim,zdim); for (int y=0;y<ydim;y++) for (int z=0;z<zdim; z++) { OccElement *line=getScanline(y,z); for (int x=0;x<xdim;x++) { *(og->address(x,y,z))=line[x]; } } puts ("Done expanding grid"); return og; } void OccGridRLE::voxRLE(OccGrid *og) { puts ("Starting grid RLE"); for (int y=0;y<ydim;y++) for (int z=0;z<zdim; z++) { OccElement *line=getScanline(y,z); for (int x=0;x<xdim;x++) { line[x]=*(og->address(x,y,z)); } putScanline(line,y,z); } puts ("Finished grid RLE"); }
22.904895
119
0.619466
yuxng
7281a54b3ef722d55d66c03ef2864b1def76573d
249
cpp
C++
Legacy/QFog2-MachO/QFogSource/Ansi_General/VECTOR_INST.cpp
artiste-qb-net/QFog-Pyodide
9ce6ad7ef6a7f7a71bbcd4fe6a6a35a5f02e8744
[ "BSD-3-Clause" ]
87
2015-12-17T22:19:21.000Z
2022-03-08T10:27:54.000Z
Legacy/QFog2-MachO/QFogSource/Ansi_General/VECTOR_INST.cpp
artiste-qb-net/QFog-Pyodide
9ce6ad7ef6a7f7a71bbcd4fe6a6a35a5f02e8744
[ "BSD-3-Clause" ]
18
2016-02-18T15:08:36.000Z
2021-03-10T00:52:36.000Z
Legacy/QFog2-MachO/QFogSource/Ansi_General/VECTOR_INST.cpp
artiste-qb-net/QFog-Pyodide
9ce6ad7ef6a7f7a71bbcd4fe6a6a35a5f02e8744
[ "BSD-3-Clause" ]
34
2015-11-29T09:08:46.000Z
2022-02-16T22:54:24.000Z
#include "VECTOR.cp" #include "NODE.h" #include "STRINGY.h" template class VECTOR<USHORT>; template class VECTOR<COMPLEX>; template class VECTOR<DOUBLE>; template class VECTOR<NODE *>; template class VECTOR<STRINGY>; template class VECTOR<SHORT>;
249
249
0.767068
artiste-qb-net
7282ae0314a78ba4f7b08e35c668c741d77384ab
3,510
cc
C++
cpp/23/23b.cc
ckennelly/advent-of-code-2020
c0ff6bb50b74873f6cc74aa432438a9e1d6aac06
[ "Apache-2.0" ]
null
null
null
cpp/23/23b.cc
ckennelly/advent-of-code-2020
c0ff6bb50b74873f6cc74aa432438a9e1d6aac06
[ "Apache-2.0" ]
null
null
null
cpp/23/23b.cc
ckennelly/advent-of-code-2020
c0ff6bb50b74873f6cc74aa432438a9e1d6aac06
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdio> #include <iostream> #include <map> #include <regex> #include <set> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" #include "absl/strings/numbers.h" #include "absl/strings/match.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/types/optional.h" std::string readAll() { std::stringstream buffer; buffer << std::cin.rdbuf(); return buffer.str(); } int64_t doGame(absl::string_view line) { std::list<int> cups; absl::flat_hash_map<int, std::list<int>::iterator> cup_labels; int max_cup = INT_MIN; for (auto c : line) { int cup = c - '0'; auto it = cups.insert(cups.end(), cup); bool success = cup_labels.emplace(cup, it).second; assert(success); (void) success; max_cup = std::max(max_cup, cup); } assert(max_cup == cups.size()); for (int i = max_cup + 1; i <= 1000000; i++) { auto it = cups.insert(cups.end(), i); bool success = cup_labels.emplace(i, it).second; assert(success); (void) success; } assert(cups.size() == 1000000); assert(cup_labels.size() == 1000000); max_cup = 1000000; for (int move = 0; move < 10 * 1000 * 1000; move++) { const size_t old_size = cups.size(); const int current_label = cups.front(); cups.erase(cups.begin()); int destination_cup = current_label; std::array<int, 3> picked_up; auto pickup_it = cups.begin(); for (int i = 0; i < 3; i++) { picked_up[i] = *pickup_it; pickup_it = cups.erase(pickup_it); } do { destination_cup--; if (destination_cup == 0) { destination_cup = max_cup; } if (destination_cup != picked_up[0] && destination_cup != picked_up[1] && destination_cup != picked_up[2]) { break; } } while (true); // The vector looks like: // [clockwise of current cup] ... [destination] [ picked up] ... current_label auto label_it = cup_labels.find(destination_cup); assert(*label_it->second == destination_cup); assert(label_it != cup_labels.end()); auto insert_loc = label_it->second; for (auto v : picked_up) { ++insert_loc; insert_loc = cups.insert(insert_loc, v); cup_labels[v] = insert_loc; } cup_labels[current_label] = cups.insert(cups.end(), current_label); assert(cups.size() == old_size); (void) old_size; } auto it = cup_labels.find(1); assert(it != cup_labels.end()); auto cup_it = it->second; assert(*cup_it == 1); int64_t product = 1; for (int i = 0; i < 2; i++) { ++cup_it; if (cup_it == cups.end()) { cup_it == cups.begin(); } product *= static_cast<int64_t>(*cup_it); } absl::FPrintF(stderr, "input %s => product %d\n", line, product); return product; } int main(int argc, char **argv) { std::vector<std::string> lines = absl::StrSplit(readAll(), "\n", absl::SkipEmpty()); assert(lines.size() == 1); assert(doGame("389125467") == 149245887792); absl::PrintF("%d\n", doGame(lines[0])); }
27.421875
86
0.567806
ckennelly
728315381e7f7ba0fd191936e1bb95ae2cd15d3a
3,077
cc
C++
localization/sparse_mapping/tools/localize.cc
nathantsoi/astrobee
bb0fc3e4110a14929bd4cf35c12b3c169bc6c756
[ "Apache-2.0" ]
629
2017-08-31T23:09:00.000Z
2022-03-30T11:55:40.000Z
localization/sparse_mapping/tools/localize.cc
nathantsoi/astrobee
bb0fc3e4110a14929bd4cf35c12b3c169bc6c756
[ "Apache-2.0" ]
269
2018-05-05T12:31:16.000Z
2022-03-30T22:04:11.000Z
localization/sparse_mapping/tools/localize.cc
nathantsoi/astrobee
bb0fc3e4110a14929bd4cf35c12b3c169bc6c756
[ "Apache-2.0" ]
248
2017-08-31T23:20:56.000Z
2022-03-30T22:29:16.000Z
/* Copyright (c) 2017, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * * All rights reserved. * * The Astrobee platform is 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 <ff_common/init.h> #include <sparse_mapping/sparse_map.h> #include <sparse_mapping/reprojection.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <thread> DEFINE_string(reference_map, "", "Reference map to localize against."); DECLARE_bool(histogram_equalization); // its value will be pulled from sparse_map.cc int main(int argc, char** argv) { if (argc < 3) { std::cerr << "Usage: localize <map file> <image>\n"; std::exit(0); } ff_common::InitFreeFlyerApplication(&argc, &argv); std::string map_file, img_file; if (FLAGS_reference_map != "") { // The use specified the map via -reference_map map_file = FLAGS_reference_map; img_file = argv[1]; } else { // The -reference_map option was omitted map_file = argv[1]; img_file = argv[2]; } // initialize map sparse_mapping::SparseMap map(map_file); // Ensure we localize with the same flag as in the map sparse_mapping::HistogramEqualizationCheck(map.GetHistogramEqualization(), FLAGS_histogram_equalization); // localize frame camera::CameraModel camera(Eigen::Vector3d(), Eigen::Matrix3d::Identity(), map.GetCameraParameters()); if (!map.Localize(img_file, &camera)) { LOG(ERROR) << "Failed to localize image."; return 1; } // print results Eigen::IOFormat CSVFormat(3, 0, ", ", ", "); // for (size_t i = 0; i < map.GetNumFrames(); i++) { // camera::CameraModel m(map.GetFrameGlobalTransform(i), map.GetCameraParameters()); // std::cout << map.GetFrameFilename(i); // Eigen::Vector3d camera_pos = m.GetPosition(); // printf(" map position: (%10.7f, %10.7f, %10.7f) ", // camera_pos.x(), camera_pos.y(), camera_pos.z()); // std::cout << "rotation: (" << m.GetRotation().matrix().format(CSVFormat) << ")\n"; // } // std::cout << "-----------------------------------" << std::endl; // std::cout << "Localization" << std::endl; // std::cout << img_file; Eigen::Vector3d camera_pos = camera.GetPosition(); printf(" localized position for %s: (%10.7f, %10.7f, %10.7f) ", img_file.c_str(), camera_pos.x(), camera_pos.y(), camera_pos.z()); std::cout << "rotation: (" << camera.GetRotation().matrix().format(CSVFormat) << ")\n"; return 0; }
36.630952
89
0.653234
nathantsoi
728589903c6585c21588bc3609b009f31c6e32df
572
hpp
C++
src/score/Score.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
src/score/Score.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
src/score/Score.hpp
rectoria/cpp_arcade
72bff5ec97f90dcc05ff4079f7ba30d5af9fb147
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** cpp_arcade ** File description: ** */ #ifndef SCORE_HPP #define SCORE_HPP #define SAVE_EXTENSION ".log" #define SAVE_PATH "./.save/" namespace Arcade{ class Score { public: Score(); ~Score(); public: void addGame(std::string &); std::map<std::string, std::string> getGameStats(std::string &); int getPlayerScore(std::string &, std::string &); void writeStats(std::string); void setScore(std::string &, std::string &, unsigned); private: std::map<std::string, std::map<std::string, std::string>> _stats; }; } #endif
17.875
67
0.664336
rectoria
72880b44f1c5a532e8d0452c43076991239254c0
3,131
hpp
C++
include/dca/phys/models/analytic_hamiltonians/util.hpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
27
2018-08-02T04:28:23.000Z
2021-07-08T02:14:20.000Z
include/dca/phys/models/analytic_hamiltonians/util.hpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
200
2018-08-02T18:19:03.000Z
2022-03-16T21:28:41.000Z
include/dca/phys/models/analytic_hamiltonians/util.hpp
PMDee/DCA
a8196ec3c88d07944e0499ff00358ea3c830b329
[ "BSD-3-Clause" ]
22
2018-08-15T15:50:00.000Z
2021-09-30T13:41:46.000Z
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Urs R. Haehner (haehneru@itp.phys.ethz.ch) // // This file provides utility functions for tasks that are common between different lattices. #ifndef DCA_PHYS_MODELS_ANALYTIC_HAMILTONIANS_UTIL_HPP #define DCA_PHYS_MODELS_ANALYTIC_HAMILTONIANS_UTIL_HPP #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/phys/domains/cluster/cluster_operations.hpp" namespace dca { namespace phys { namespace models { namespace util { // dca::phys::models::detail:: // Initializes the interaction part of the single-band real space Hubbard Hamiltonian with on-site // and nearest-neighbor interaction. // nn_vec contains the vectors that define the nearest neighbors. // In: parameters // nn_vec // Out: H_int template <typename ParametersType, typename BandDmn, typename SpinDmn, typename RDmn> void initializeSingleBandHint( const ParametersType& parameters, const std::vector<typename RDmn::parameter_type::element_type>& nn_vec, func::function<double, func::dmn_variadic<func::dmn_variadic<BandDmn, SpinDmn>, func::dmn_variadic<BandDmn, SpinDmn>, RDmn>>& H_int) { if (BandDmn::dmn_size() != 1) throw std::logic_error("Band domain size must be 1."); if (SpinDmn::dmn_size() != 2) throw std::logic_error("Spin domain size must be 2."); // Get the index of the origin (0,0). const int origin = RDmn::parameter_type::origin_index(); // Compute indices of nearest neighbors (nn) w.r.t. origin. std::vector<int> nn_index; const std::vector<typename RDmn::parameter_type::element_type>& super_basis = RDmn::parameter_type::get_super_basis_vectors(); const std::vector<typename RDmn::parameter_type::element_type>& elements = RDmn::parameter_type::get_elements(); for (const auto& vec : nn_vec) { std::vector<double> nn_vec_translated = domains::cluster_operations::translate_inside_cluster(vec, super_basis); nn_index.push_back( domains::cluster_operations::index(nn_vec_translated, elements, domains::BRILLOUIN_ZONE)); } // Set all elements to zero. H_int = 0.; // Nearest-neighbor opposite spin interaction const double V = parameters.get_V(); for (auto index : nn_index) { H_int(0, 0, 0, 1, index) = V; H_int(0, 1, 0, 0, index) = V; } // Nearest-neighbor same spin interaction const double V_prime = parameters.get_V_prime(); for (auto index : nn_index) { H_int(0, 0, 0, 0, index) = V_prime; H_int(0, 1, 0, 1, index) = V_prime; } // On-site interaction // This has to be set last since for small clusters a nearest neighbor might // be the same site and therefore V would overwrite U. const double U = parameters.get_U(); H_int(0, 0, 0, 1, origin) = U; H_int(0, 1, 0, 0, origin) = U; } } // util } // models } // phys } // dca #endif // DCA_PHYS_MODELS_ANALYTIC_HAMILTONIANS_UTIL_HPP
34.406593
100
0.705525
PMDee
7289002d01f4f9da506733556e686207fe86f0a4
765
cpp
C++
FootCommander.cpp
OmerK25/CPP-WarGame
641921f65781ed2ee28b153012e0b8926696db11
[ "MIT" ]
null
null
null
FootCommander.cpp
OmerK25/CPP-WarGame
641921f65781ed2ee28b153012e0b8926696db11
[ "MIT" ]
null
null
null
FootCommander.cpp
OmerK25/CPP-WarGame
641921f65781ed2ee28b153012e0b8926696db11
[ "MIT" ]
1
2020-06-08T17:12:48.000Z
2020-06-08T17:12:48.000Z
#include <vector> #include "FootCommander.hpp" #include <iostream> void FootCommander::act(vector<vector<Soldier *>> &board, pair<int, int> location) { FootSoldier::act(board, location); act_as_commander(board, location); } void FootCommander::act_as_commander(vector<vector<Soldier *>> &board, pair<int, int> location) { for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { Soldier *maybeFoot = board[i][j]; if (maybeFoot != nullptr && maybeFoot->_player() == _player()) { if (dynamic_cast<FootSoldier *>(maybeFoot) && !(dynamic_cast<FootCommander *>(maybeFoot))) maybeFoot->act(board, {i, j}); } } } }
30.6
106
0.56732
OmerK25
7291a4b2da4c02bfaca23a51fdc3be434cf32548
1,034
cc
C++
TC/DP-Practice-DIV1-300.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
TC/DP-Practice-DIV1-300.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
TC/DP-Practice-DIV1-300.cc
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <climits> #include <cstring> using namespace std; class EmoticonsDiv2 { public: int printSmiles(int); }; constexpr int MAXN = 1010; const int INF = INT_MAX / 3; int dp[MAXN][MAXN]; int func(int curr, int clipboard, const int goal) { if (curr == goal) { return 0; } else if (curr > goal) { return INF; } else { int& ans = dp[curr][clipboard]; if (ans == -1) { ans = INF; if (clipboard > 0) { ans = min(ans, 1 + func(curr + clipboard, clipboard, goal)); } ans = min(ans, 2 + func(2 * curr, curr, goal)); } return ans; } } int EmoticonsDiv2::printSmiles(int smiles) { memset(dp, -1, sizeof(dp)); return func(1, 0, smiles); } //Powered by [KawigiEdit] 2.0!
16.677419
64
0.647002
aajjbb
729697e6b1993a884f83d7e0d5953ac6d1b49f91
347
cpp
C++
code/source/common/events/KeyPressEvent.cpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
code/source/common/events/KeyPressEvent.cpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
code/source/common/events/KeyPressEvent.cpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
#include "common/events/KeyPressEvent.hpp" namespace id { namespace events { KeyPressEvent::KeyPressEvent(int keyCode, State state) : id::events::PressEvent(state), m_keyCode(keyCode) { /* do nothing */ } int KeyPressEvent::getKeyCode() { return m_keyCode; } } /* events */ } /* id */
24.785714
64
0.587896
StuntHacks
729a52697d4cad565ddcd4deffc2f0a061ac9ee4
1,813
cpp
C++
Mesh.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
5
2020-03-06T10:01:28.000Z
2020-05-06T07:57:20.000Z
Mesh.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
1
2020-03-06T02:51:50.000Z
2020-03-06T04:33:30.000Z
Mesh.cpp
rabinadk1/learnopengl
66e5a26af5e63aebc7274efc051f05a99211f5a9
[ "MIT" ]
29
2020-03-05T15:15:24.000Z
2021-07-21T07:05:00.000Z
#include "Mesh.hpp" #include "VertexBufferLayout.hpp" #include "Renderer.hpp" Mesh::Mesh(std::vector<Vertex> &vertices, std::vector<uint> &indices, const std::unordered_map<std::string, Texture> &texturesLoaded, std::vector<std::string> &textures) : m_TexturesLoaded(texturesLoaded), m_Vertices(vertices), m_Indices(indices), m_Textures(textures), m_VA(), m_IB(&indices[0], indices.size()), /* NOTE: Address of Vector and the address of first element of vector are different. Also, sizeof(<vector>) is the size of the vector not containing data */ m_VB(&vertices[0], sizeof(Vertex) * vertices.size()) { SetupMesh(); } void Mesh::SetupMesh() const { VertexBufferLayout layout; // For Vertex Positions layout.Push<float>(3); //For Vertex Normals layout.Push<float>(3); // For Vertex Texture Coords layout.Push<float>(2); // For Vertex Tangent layout.Push<float>(3); // For Vertex Bitangent layout.Push<float>(3); m_VA.AddBuffer(m_VB, layout); } void Mesh::Draw(Shader &shader) const { // bind appropriate textures uint diffuseNr = 1; uint specularNr = 1; for (uint i = 0; i < m_Textures.size(); ++i) { const Texture &texture = m_TexturesLoaded.find(m_Textures[i])->second; // retrieve texture number (the N in diffuse_textureN) std::string number; const std::string &textureType = texture.GetType(); if (textureType == "diffuse") number = std::to_string(diffuseNr++); else if (textureType == "specular") number = std::to_string(specularNr++); // transfer unsigned int to stream else continue; shader.SetUniform(("u_Material." + textureType + number).c_str(), static_cast<int>(i)); texture.Bind(i); } // Draw mesh Renderer::Draw(m_VA, m_IB); }
26.275362
169
0.66299
rabinadk1
729bb991876d772189dc4e027fe93c7d6d13e33f
887
cpp
C++
src/il/processing/il-processing.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
1
2019-07-01T02:02:40.000Z
2019-07-01T02:02:40.000Z
src/il/processing/il-processing.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
src/il/processing/il-processing.cpp
noct-lang/noct-bootstrap
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
[ "0BSD" ]
null
null
null
#include "il-processing.hpp" #include <type_traits> #include "common/logger.hpp" #include "il-pass.hpp" #include "passes/misc/il-clean-pass.hpp" #include "passes/misc/il-dependency-pass.hpp" #include "passes/misc/il-marker-pass.hpp" namespace Noctis { template<typename T, typename... Args> void ILProcessing::RunPass(ILModule& mod, const Args&... args) { static_assert(std::is_base_of_v<ILPass, T>, ""); T pass{ args... }; pass.Process(mod); } void ILProcessing::Process(ILModule& module) { g_Logger.Log("-- IL PROCESSING\n"); Timer timer(true); RunPass<ILDependencyPass>(module); RunPass<ILMarkerPass>(module); RunPass<ILBlockMergePass>(module); RunPass<ILRemoveGotoOnlyPass>(module); RunPass<ILRemoveUntouchableBlockPass>(module); timer.Stop(); g_Logger.Log("-- TOOK %s\n", timer.GetSMSFormat().c_str()); } }
25.342857
64
0.683202
noct-lang
729d54b118a8e70c51384c2bd381bbb94f2f72e3
1,877
cpp
C++
PAT/PAT Advanced/c++/1034.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:27.000Z
2019-09-18T23:45:27.000Z
PAT/PAT Advanced/c++/1034.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
null
null
null
PAT/PAT Advanced/c++/1034.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:28.000Z
2019-09-18T23:45:28.000Z
#include <cstdio> #include <iostream> #include <map> #include <functional> #include <string> #include <vector> using namespace std; //PAT Advanced Level 1034 Head of a Gang /* 直接用两个map进行姓名与int ID的转换 * DFS遍历连通分量,某连通分量满足条件,即为结果之一,此处存入以帮主名称为key的map中 */ map<int,string> hashToName; map<string,int> nameToHash; map<string,int> gangs; int personID = 1,K; int hashID(string s){ if(nameToHash.find(s) == nameToHash.end()){ nameToHash[s] = personID; hashToName[personID] = s; personID++; return personID - 1; } else{ return nameToHash[s]; } } int G[2005][2005],weight[2005]; bool visited[2005]; void dfs(int u,int & head,int & numMember,int & totalWeight){ visited[u] = true; numMember++; if(weight[u] > weight[head]) head = u; for(int v = 1;v < personID;v++){ //如果uv联通,将权重计入该连通分量后封死uv通路 if(G[u][v] > 0){ totalWeight += G[u][v]; G[u][v] = G[v][u] = 0; if(!visited[v]) dfs(v,head,numMember,totalWeight); } } } int main() { int N; cin >> N >> K; for(int i = 0;i < N;i++){ string str1,str2; int w; cin >> str1 >> str2 >> w; int ID1 = hashID(str1),ID2 = hashID(str2); weight[ID1] += w; weight[ID2] += w; G[ID1][ID2] += w; G[ID2][ID1] += w; } for(int i = 1; i < personID;i++){ if(!visited[i]){ int head = i,numMember = 0,totalWeight = 0; dfs(i,head,numMember,totalWeight); if(numMember > 2 && totalWeight > K){ //map内部自带对key排序 gangs[hashToName[head]] = numMember; } } } cout << gangs.size() << endl; for(auto it = gangs.begin();it != gangs.end();it++){ cout << it->first << ' ' << it->second << endl; } return 0; }
23.759494
61
0.520511
Accelerator404
729d5f6617baedc2e5768926b22c2ebaa0aa66bd
1,070
cpp
C++
Casino_Inc/Source/Casino_Inc/Data/CI_WeigthedInteractionChance.cpp
matthieu1345/CasinoInc
3f6db9038c191fb5037219dbd8db5c7041b8292e
[ "Apache-2.0" ]
1
2019-11-22T14:52:37.000Z
2019-11-22T14:52:37.000Z
Casino_Inc/Source/Casino_Inc/Data/CI_WeigthedInteractionChance.cpp
matthieu1345/CasinoInc
3f6db9038c191fb5037219dbd8db5c7041b8292e
[ "Apache-2.0" ]
1
2019-11-21T03:58:03.000Z
2019-11-21T03:58:03.000Z
Casino_Inc/Source/Casino_Inc/Data/CI_WeigthedInteractionChance.cpp
matthieu1345/CasinoInc
3f6db9038c191fb5037219dbd8db5c7041b8292e
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "CI_WeigthedInteractionChance.h" #include "DebugMacros.h" void FWeightedInteractionResult::OnPostDataImport(const UDataTable* InDataTable, const FName InRowName, TArray<FString>& OutCollectedImportProblems) { int totalChance = 0; for (auto node : InDataTable->GetRowMap()) { totalChance += ((FWeightedInteractionResult*)node.Value)->chance; } percentageChange = (1.0f / totalChance) * chance; } void FInteractionResult::RecalculateChance() { if (!IsValid(values)) return; totalChance = 0; for (auto node : values->GetRowMap()) { totalChance += ((FWeightedInteractionResult*)node.Value)->chance; } } FWeightedInteractionResult FInteractionResult::GetRandom() { int element = FMath::RandRange(0, totalChance); int counter = 0; for (auto node : values->GetRowMap()) { counter += ((FWeightedInteractionResult*)node.Value)->chance; if (counter >= element) return *(FWeightedInteractionResult*)node.Value; } return FWeightedInteractionResult(); }
22.765957
103
0.742991
matthieu1345
72a0ff04140f5f16d2ba92bbd273d3c65cd303f6
4,430
cpp
C++
solver/solver.cpp
ale64bit/kaktusat
afaac943079665184f900f318e7ac901619269dc
[ "MIT" ]
1
2021-11-17T13:43:12.000Z
2021-11-17T13:43:12.000Z
solver/solver.cpp
ale64bit/kaktusat
afaac943079665184f900f318e7ac901619269dc
[ "MIT" ]
null
null
null
solver/solver.cpp
ale64bit/kaktusat
afaac943079665184f900f318e7ac901619269dc
[ "MIT" ]
null
null
null
#include "solver.h" #include <set> #include <sstream> namespace solver { // A prefix used for temporary variables, which can't be used in ordinary // variables. static constexpr char kTmpSep = '$'; Var::Var(int x) : x(x) { CHECK(x > 0) << "variable representation must be positive, got x=" << x; } bool Var::operator==(const Var &that) const { return this->x == that.x; } bool Var::operator!=(const Var &that) const { return this->x != that.x; } bool Var::operator<(const Var &that) const { return this->x < that.x; } Var::operator Lit() const { return Lit(2 * x); } Lit Var::operator~() const { return Lit(2 * x + 1); } Lit::Lit(int l) : l(l) { CHECK(l > 0) << "literal representation must be positive, got l=" << l; } bool Lit::operator==(const Lit &that) const { return this->l == that.l; } bool Lit::operator!=(const Lit &that) const { return this->l != that.l; } bool Lit::operator<(const Lit &that) const { return this->l < that.l; } Lit Lit::operator~() const { return Lit(l ^ 1); } Var Lit::V() const { return Var(l >> 1); } Solver::Solver() : n_(0), tmpID_(0) {} Var Solver::NewTempVar(std::string prefix) { CHECK(prefix.find(kTmpSep) == std::string::npos) << "variable prefixes are not allowed to contain '" << kTmpSep << "'"; while (nameToVar_.count(prefix + kTmpSep + std::to_string(tmpID_))) { ++tmpID_; } std::string name = prefix + kTmpSep + std::to_string(tmpID_++); name_.push_back(name); ++n_; Var x(n_); nameToVar_.emplace(name, x); isTemp_.emplace_back(true); return x; } Var Solver::NewVar(std::string name) { CHECK(name.find(kTmpSep) == std::string::npos) << "variable names are not allowed to contain '" << kTmpSep << "'"; CHECK(!name.empty()) << "variable name cannot be empty"; CHECK(nameToVar_.count(name) == 0) << "duplicate variable name '" << name << "'"; name_.push_back(name); ++n_; Var x(n_); nameToVar_.emplace(name, x); isTemp_.emplace_back(false); return x; } Var Solver::NewOrGetVar(std::string name) { if (nameToVar_.count(name)) { return nameToVar_.at(name); } else { return NewVar(name); } } Var Solver::GetVar(std::string name) const { CHECK(nameToVar_.count(name) > 0) << "unknown variable name '" << name << "'"; return nameToVar_.at(name); } const std::vector<std::string> &Solver::GetVarNames() const { return name_; } const std::vector<std::vector<Lit>> &Solver::GetClauses() const { return clauses_; } std::string Solver::NameOf(Var x) const { return name_[x.ID() - 1]; } bool Solver::IsTemp(Var x) const { return isTemp_[x.ID() - 1]; } void Solver::AddClause(std::vector<Lit> c) { clauses_.emplace_back(c); } void Solver::Reset() { n_ = 0; name_.clear(); clauses_.clear(); nameToVar_.clear(); tmpID_ = 0; } bool Solver::Verify(const std::vector<Lit> &solution, std::string *errMsg) const { std::vector<bool> used(2 * n_ + 2, false); for (auto lit : solution) { if (used[lit.ID()] || used[(~lit).ID()]) { if (errMsg) { *errMsg = "literal used multiple times: " + ToString(lit.V()); } return false; } used[lit.ID()] = true; } for (auto clause : clauses_) { bool ok = false; for (auto lit : clause) { if (used[lit.ID()]) { ok = true; break; } } if (!ok) { if (errMsg) { *errMsg = "clause left unsatisfied: " + ToString(clause); } return false; } } return true; } std::string Solver::ToString(Var x) const { return name_[x.ID() - 1]; } std::string Solver::ToString(Lit l) const { std::string s = NameOf(l.V()); return (l != l.V()) ? "¬" + s : s; } std::string Solver::ToString(const std::vector<Lit> &lits, std::string sep, bool raw) const { std::stringstream out; bool first = true; for (auto l : lits) { if (!first) { out << sep; } first = false; if (raw) { out << (l.IsNeg() ? "-" : "") << l.V().ID(); } else { out << ToString(l); } } return out.str(); } std::string Solver::ToString() const { std::stringstream out; bool first = true; for (auto c : clauses_) { if (!first) { out << " ∧ "; } first = false; out << "("; for (size_t i = 0; i < c.size(); ++i) { if (i > 0) { out << " ∨ "; } out << ToString(c[i]); } out << ")"; } return out.str(); } } // namespace solver
26.058824
80
0.579684
ale64bit
72a1453d5fb959c8f97b29e4110a2ca2154389b5
2,091
cc
C++
flare/base/object_pool/ref_counted_test.cc
LiuYuHui/flare
f92cb6132e79ef2809fc0291a4923097ec84c248
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
2
2021-05-29T04:04:17.000Z
2022-02-04T05:33:17.000Z
flare/base/object_pool/ref_counted_test.cc
LiuYuHui/flare
f92cb6132e79ef2809fc0291a4923097ec84c248
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
flare/base/object_pool/ref_counted_test.cc
LiuYuHui/flare
f92cb6132e79ef2809fc0291a4923097ec84c248
[ "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
1
2022-02-17T10:13:04.000Z
2022-02-17T10:13:04.000Z
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "flare/base/object_pool/ref_counted.h" #include <thread> #include "thirdparty/googletest/gtest/gtest.h" #include "flare/testing/main.h" using namespace std::literals; namespace flare { struct RefCounted1 : object_pool::RefCounted<RefCounted1> { RefCounted1() { ++instances; } ~RefCounted1() { --instances; } inline static int instances = 0; }; template <> struct PoolTraits<RefCounted1> { static constexpr auto kType = PoolType::ThreadLocal; static constexpr auto kLowWaterMark = 0; static constexpr auto kHighWaterMark = 128; static constexpr auto kMaxIdle = 100ms; }; TEST(ObjectPoolRefCounted, All) { auto tid = std::this_thread::get_id(); auto pp = object_pool::GetRefCounted<RefCounted1>(); { auto p = object_pool::GetRefCounted<RefCounted1>(); ASSERT_EQ(2, RefCounted1::instances); auto p2 = p; ASSERT_EQ(2, RefCounted1::instances); } { ASSERT_EQ(2, RefCounted1::instances); // Not destroyed yet. auto p = object_pool::GetRefCounted<RefCounted1>(); ASSERT_EQ(2, RefCounted1::instances); auto p2 = p; ASSERT_EQ(2, RefCounted1::instances); } // `this_fiber::SleepFor` WON'T work, object pools are bound to thread. std::this_thread::sleep_for(200ms); pp.Reset(); // To trigger cache washout. ASSERT_EQ(tid, std::this_thread::get_id()); // The last one freed is kept alive by the pool. ASSERT_EQ(1, RefCounted1::instances); } } // namespace flare FLARE_TEST_MAIN
30.304348
80
0.721186
LiuYuHui
72a271fdcda4b6b69095e3cfa0e56e4b69d015ad
1,337
cpp
C++
src/GeometryGroupSampler.cpp
arpg/torch
601ec64854008d97e39d2ca86ef4a93f79930967
[ "Apache-2.0" ]
1
2018-05-29T03:08:54.000Z
2018-05-29T03:08:54.000Z
src/GeometryGroupSampler.cpp
arpg/torch
601ec64854008d97e39d2ca86ef4a93f79930967
[ "Apache-2.0" ]
null
null
null
src/GeometryGroupSampler.cpp
arpg/torch
601ec64854008d97e39d2ca86ef4a93f79930967
[ "Apache-2.0" ]
1
2017-07-24T11:58:52.000Z
2017-07-24T11:58:52.000Z
#include <torch/GeometryGroupSampler.h> #include <torch/Context.h> #include <torch/Distribution1D.h> #include <torch/PtxUtil.h> #include <torch/device/Geometry.h> namespace torch { GeometryGroupSampler::GeometryGroupSampler(std::shared_ptr<Context> context) : GeometrySampler(context) { Initialize(); } optix::Program GeometryGroupSampler::GetProgram() const { return m_program; } void GeometryGroupSampler::Add(const GeometryGroupData& group) { m_groups.push_back(group); } void GeometryGroupSampler::Clear() { m_groups.clear(); } void GeometryGroupSampler::Update() { GeometryGroupData* device; m_buffer->setSize(m_groups.size()); device = reinterpret_cast<GeometryGroupData*>(m_buffer->map()); std::copy(m_groups.begin(), m_groups.end(), device); m_buffer->unmap(); } void GeometryGroupSampler::Initialize() { CreateProgram(); CreateBuffer(); } void GeometryGroupSampler::CreateProgram() { const std::string file = PtxUtil::GetFile("GeometryGroupSampler"); m_program = m_context->CreateProgram(file, "Sample"); } void GeometryGroupSampler::CreateBuffer() { m_buffer = m_context->CreateBuffer(RT_BUFFER_INPUT); m_program["groups"]->setBuffer(m_buffer); m_buffer->setFormat(RT_FORMAT_USER); m_buffer->setElementSize(sizeof(GeometryGroupData)); m_buffer->setSize(0); } } // namespace torch
21.918033
78
0.753179
arpg
72a76be4410da2b2211e49d31b8a6571afb18219
1,108
cpp
C++
Practice Programs/question3.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
Practice Programs/question3.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
Practice Programs/question3.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "strutils.h" using namespace std; bool isVowel(string input) { string vowels = "aeiou"; for (int i = 0; i < input.length(); i++) { if (i != 0 && i != input.length()-1) { for (int k = 0; k < vowels.length(); k++) { if (vowels[k] == input[i]) { if(vowels[k] == input[i+1]) { return true; } } } } if (i != input.length()-1 && input[i] == input[i+1]) { return true; } } return false; } int main() { string a = "", input = ""; cout << "Please enter a string: "; cin >> a; for (int j = 0; j < a.length(); j++) { input += tolower(a[j]); } if (isVowel(input)) { cout << "The string " << input << " contain consequent words." << endl; } else { cout << "The string " << input << " does not contain consequent words." << endl; } return 0; }
20.518519
88
0.402527
egmnklc
72b0cb8382a022bcf2e5df7bc50664890e0baf2b
25,212
cpp
C++
p/validador/Measurer.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/validador/Measurer.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/validador/Measurer.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
#include "Measurer.h" using namespace std; Measurer::Measurer() { cm = 1.0; cf = 1.0; cs = 1.0; misses = 0; false_positives = 0; missmatches = 0; false_negatives = 0; gt_objects = 0; tk_objects = 0; missmatch_error = 0; detection_error = 0; report_level = BASIC_LEVEL; motp_error=0.0; motp_matches = 0; precision = 0; recall = 0; accuracy = 0; f1measure = 0; true_negatives = 0; true_positives = 0; mota = 0.0; motp = 0.0; start_frame = 0; stop_frame = 999999; mota_mean = 0.0; motp_mean = 0.0; mota_variance = 0.0; motp_mean = 0.0; } Measurer::Measurer(std::map<std::string,double> constants) { cm = constants["miss"]; cf = constants["false"]; cs = constants["mismatch"]; report_level = constants["report_level"]; missmatch_error = constants["mismatch_error"]; detection_error = constants["detection_error"]; motp_error = constants["motp_error"]; start_frame = constants["start_frame"]; stop_frame = constants["stop_frame"]; misses = 0; false_positives = 0; missmatches = 0; false_negatives = 0; gt_objects = 0; tk_objects = 0; motp_matches = 0; precision = 0; recall = 0; accuracy = 0; f1measure = 0; true_negatives = 0; true_positives = 0; mota = 0.0; motp = 0.0; } double Measurer::MeasureMota(map<int, vector< TrackPoint >> manotados, map<int, vector< TrackPoint >> mrastreados) { cout << "Analyzing tracking results for MOTA..." << endl; map<int, vector< TrackPoint >>::iterator ItmAnotados,ItmRastreados; std::vector<int> gt_frames; int fnumber = -1; for (ItmAnotados = manotados.begin(); ItmAnotados != manotados.end(); ItmAnotados++) { for (ItmRastreados = mrastreados.begin(); ItmRastreados != mrastreados.end(); ItmRastreados++) { if(ItmRastreados->first == ItmRastreados->first){///We have a match on the frame numbers vector< TrackPoint > datos_anotados, datos_rastreados; datos_anotados = ItmAnotados->second; datos_rastreados = ItmRastreados->second; vector<TrackPoint>::iterator ItAnotados,ItRastreados; for (ItAnotados = datos_anotados.begin(); ItAnotados != datos_anotados.end(); ItAnotados++, gt_objects++) { for (ItRastreados = datos_rastreados.begin(); ItRastreados != datos_rastreados.end(); ItRastreados++) { ///Determine the misses if(*ItRastreados==*ItAnotados){ ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; else true_positives++; break; } else if (*ItRastreados==datos_rastreados.back()){///Llegue al ultimo y no se encontro //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItRastreados->frame_number << endl; misses++; } } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } ///Count track objects only on gt frames for(unsigned int gtc =0; gtc<gt_frames.size();gtc++){ int gtfnumber = gt_frames[gtc]; for (ItRastreados = datos_rastreados.begin(); ItRastreados != datos_rastreados.end(); ItRastreados++) { if(gtfnumber==ItRastreados->frame_number) tk_objects++; } } }///if son el mismo frame number } } //false_positives = tk_objects - gt_objects; false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); //false_negatives = gt_objects - tk_objects; false_negatives = (gt_objects >= tk_objects) ? (gt_objects - tk_objects):(0); missmatches=missmatches/2; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2 * (precision * recall)/(precision + recall); cout << "Misses = " << misses << endl; cout << "Ture positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; cout << "Total ground truth objects = " << gt_objects << endl; mota = 1 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; return mota; } double Measurer::MeasureMota(vector< TrackPoint > anotados, vector< TrackPoint > rastreados) { cout << "Analyzing tracking results for MOTA..." << endl; ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); vector<TrackPoint>::iterator ItAnotados,ItRastreados; std::vector<int> gt_frames; int fnumber = -1; bool found1,found2,found3,found4; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ gt_objects++; found1 = FALSE; found2 = FALSE; found3 = FALSE; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame) && (found1 == FALSE)) { ///Determine the missmatches if(*ItRastreados==*ItAnotados){ //cout << "The player with id " << ItRastreados->label << " found on frame " << ItRastreados->frame_number << endl; ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; //else //true_positives++; found1 = TRUE; //cout << "Found player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; } else if (ItRastreados==rastreados.end()-1){///Determine the misses //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; misses++; found1 = FALSE; } ///Search for FN - Cuando esta en el GT pero no en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found2 == FALSE)){ if((ItAnotados->point.x < ItRastreados->point.x+detection_error) && (ItAnotados->point.x > ItRastreados->point.x-detection_error) && (ItAnotados->point.y < ItRastreados->point.y+detection_error) && (ItAnotados->point.y > ItRastreados->point.y-detection_error)) found2 = TRUE; ///Found a coincidence else{ //cout << "found posible player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; found2 = FALSE; } } ///Search for TP - Cuando esta en el GT y en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found3 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found3 = TRUE; ///Found a TP } } } if(found2 == FALSE){ //cout << "False negative of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; false_negatives++; } if(found3 == TRUE){ //cout << "True positive of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; true_positives++; } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } } /* ///Count track objects only on gt frames for(unsigned int gtc =0; gtc<gt_frames.size();gtc++){ int gtfnumber = gt_frames[gtc]; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if(ItRastreados->frame_number>=start_frame && ItRastreados->frame_number<=stop_frame) { if(gtfnumber==ItRastreados->frame_number) tk_objects++; } } } */ ///Search for FP - Cuando esta en el SUT y no en el GT for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame)) { tk_objects++; found4 = FALSE; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ ///Search for FP if((ItRastreados->frame_number == ItAnotados->frame_number) && (found4 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found4 = TRUE; ///El SUT esta en el GT } } } if(found4 == FALSE){ //cout << "False positive of player "<< ItRastreados->label << " on frame " << ItRastreados->frame_number << endl; false_positives++; } } } //false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); missmatches=missmatches/2.0; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2.0 * (precision * recall)/(precision + recall); cout << "Total ground truth objects = " << gt_objects << endl; cout << "Total SUT objects = " << tk_objects << endl; cout << "Misses = " << misses << endl; cout << "True positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; mota = 1.0 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; cout << "Finish with MOTA..." << endl; return mota; } double Measurer::MeasureMota(vector< TrackPoint > anotados, vector< TrackPoint > rastreados, int tid) { ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); std::vector<int> gt_frames; if(tid == 0){ cout << "Analyzing tracking results for MOTA..." << endl; vector<TrackPoint>::iterator ItAnotados,ItRastreados; int fnumber = -1; bool found1,found2,found3; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ gt_objects++; found1 = FALSE; found2 = FALSE; found3 = FALSE; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame) && (found1 == FALSE)) { ///Determine the missmatches if(*ItRastreados==*ItAnotados){ //cout << "The player with id " << ItRastreados->label << " found on frame " << ItRastreados->frame_number << endl; ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; //else //true_positives++; found1 = TRUE; //cout << "Found player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; } else if (ItRastreados==rastreados.end()-1){///Determine the misses //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; misses++; found1 = FALSE; } ///Search for FN - Cuando esta en el GT pero no en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found2 == FALSE)){ if((ItAnotados->point.x < ItRastreados->point.x+detection_error) && (ItAnotados->point.x > ItRastreados->point.x-detection_error) && (ItAnotados->point.y < ItRastreados->point.y+detection_error) && (ItAnotados->point.y > ItRastreados->point.y-detection_error)) found2 = TRUE; ///Found a coincidence else{ //cout << "found posible player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; found2 = FALSE; } } ///Search for TP - Cuando esta en el GT y en el SUT if((ItAnotados->frame_number == ItRastreados->frame_number) && (found3 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found3 = TRUE; ///Found a TP } } } if(found2 == FALSE){ //cout << "False negative of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; false_negatives++; } if(found3 == TRUE){ //cout << "True positive of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; true_positives++; } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } } cout << "Finish with MOTA on thread " << tid << endl; }///tid=0 ///Search for FP - Cuando esta en el SUT y no en el GT if(tid==1){ vector<TrackPoint>::iterator ItAnotados,ItRastreados; bool found4; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame)) { tk_objects++; found4 = FALSE; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ ///Search for FP if((ItRastreados->frame_number == ItAnotados->frame_number) && (found4 == FALSE)){ if((ItRastreados->point.x < ItAnotados->point.x+detection_error) && (ItRastreados->point.x > ItAnotados->point.x-detection_error) && (ItRastreados->point.y < ItAnotados->point.y+detection_error) && (ItRastreados->point.y > ItAnotados->point.y-detection_error)) found4 = TRUE; ///El SUT esta en el GT } } } if(found4 == FALSE){ //cout << "False positive of player "<< ItRastreados->label << " on frame " << ItRastreados->frame_number << endl; false_positives++; } } } cout << "Finish with MOTA on thread " << tid << endl; }///tid = 1 #pragma omp barrier //false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); missmatches=missmatches/2.0; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2.0 * (precision * recall)/(precision + recall); cout << "Total ground truth objects = " << gt_objects << endl; cout << "Total SUT objects" << tk_objects << endl; cout << "Misses = " << misses << endl; cout << "True positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; mota = 1.0 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; cout << "Finish with MOTA..." << endl; return mota; } double Measurer::MeasureMota_old(vector< TrackPoint > anotados, vector< TrackPoint > rastreados) { cout << "Analyzing tracking results for MOTA..." << endl; ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); vector<TrackPoint>::iterator ItAnotados,ItRastreados; std::vector<int> gt_frames; int fnumber = -1; bool found; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ gt_objects++; found = FALSE; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if((ItRastreados->frame_number>=start_frame) && (ItRastreados->frame_number<=stop_frame) && (found == FALSE)) { ///Determine the misses if(*ItRastreados==*ItAnotados){ //cout << "The player with id " << ItRastreados->label << " found on frame " << ItRastreados->frame_number << endl; ///Determine missmatches if((ItRastreados->point.x > ItAnotados->point.x+missmatch_error) || (ItRastreados->point.x < ItAnotados->point.x-missmatch_error) || (ItRastreados->point.y > ItAnotados->point.y+missmatch_error) || (ItRastreados->point.y < ItAnotados->point.y-missmatch_error)) missmatches++; else true_positives++; found = TRUE; //cout << "Found player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; } //else if (*ItRastreados==rastreados.back()){ else if (ItRastreados==rastreados.end()-1){ //cout << "Miss of player "<< ItAnotados->label << " on frame " << ItAnotados->frame_number << endl; misses++; found = FALSE; } } ///Search for FP } ///Create a list of the gt frame numbers if(ItAnotados->frame_number != fnumber){ gt_frames.push_back(ItAnotados->frame_number); fnumber = ItAnotados->frame_number; } } } ///Count track objects only on gt frames for(unsigned int gtc =0; gtc<gt_frames.size();gtc++){ int gtfnumber = gt_frames[gtc]; for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if(ItRastreados->frame_number>=start_frame && ItRastreados->frame_number<=stop_frame) { if(gtfnumber==ItRastreados->frame_number) tk_objects++; } } } //gt_objects = anotados.size(); //tk_objects = rastreados.size(); //false_positives = tk_objects - gt_objects; false_positives = (tk_objects>=gt_objects) ? (tk_objects - gt_objects):(0); //false_negatives = gt_objects - tk_objects; false_negatives = (gt_objects >= tk_objects) ? (gt_objects - tk_objects):(0); missmatches=missmatches/2.0; precision = true_positives/(true_positives+false_positives); recall = true_positives/(true_positives+false_negatives); f1measure = 2.0 * (precision * recall)/(precision + recall); cout << "Total ground truth objects = " << gt_objects << endl; cout << "Total SUT objects" << tk_objects << endl; cout << "Misses = " << misses << endl; cout << "True positive = " << true_positives << endl; cout << "False positives = " << false_positives << endl; cout << "False negatives = " << false_negatives << endl; cout << "Missmatches = " << missmatches << endl; cout << "Total analyzed frames = " << gt_frames.size() << endl; mota = 1.0 - (cm * misses + cf * false_positives + cs * missmatches)/gt_objects; return mota; } double Measurer::MeasureMotp(vector< TrackPoint > anotados, vector< TrackPoint > rastreados) { cout << "Analyzing tracking results for MOTP..." << endl; ///Sort trackpoints by frame number std::sort(anotados.begin(), anotados.end()); std::sort(rastreados.begin(), rastreados.end()); vector<TrackPoint>::iterator ItAnotados,ItRastreados; //Change this for a binary search!!! double distance_error = 0.0; for (ItAnotados = anotados.begin(); ItAnotados != anotados.end(); ItAnotados++) { if(ItAnotados->frame_number>=start_frame && ItAnotados->frame_number<=stop_frame){ for (ItRastreados = rastreados.begin(); ItRastreados != rastreados.end(); ItRastreados++) { if(ItRastreados->frame_number>=start_frame && ItRastreados->frame_number<=stop_frame) { if(*ItRastreados==*ItAnotados){ motp_matches++; ///Obtain euclidian distance double x = (double) (ItAnotados->point.x - ItRastreados->point.x); double y = (double) (ItAnotados->point.y - ItRastreados->point.y); double dist; dist = pow(x, 2) + pow(y, 2); dist = sqrt(dist); dist = (dist-motp_error>=0.0) ? (dist-motp_error):(0.0); distance_error=distance_error+dist; break; } } } } } motp = distance_error/motp_matches; cout << "Finish with MOTP..." << endl; return motp; } void Measurer::SaveResults(std::string report_file,std::string input_file,std::string annotation_file) { cout<< "Saving results to " << report_file << " ... " << endl; ofstream rfile; rfile.open (report_file); rfile <<"--- Resulting report ---" << endl; rfile << "\n- Input files -" << endl; rfile <<"Tracking file: " << input_file << endl; rfile <<"GT file: " << annotation_file << endl; rfile <<"\n- Configuration parameters -" << endl; rfile <<"Miss constant = " << cm << endl; rfile <<"False positive constant = " << cf << endl; rfile <<"Missmatch constant = " << cs << endl; rfile <<"Precision error = " << motp_error << endl; rfile <<"Mismatch error = " << missmatch_error << endl; rfile <<"Detection error = " << detection_error << endl; rfile <<"\n- Metrics values -" << endl; if(report_level == BASIC_LEVEL){ int space = 12; rfile << std::setw(space) << "F1" << std::setw(space) << "MOTA" << std::setw(space) << "MOTP" << endl; rfile << std::setw(space) << to_string_with_precision(f1measure) << std::setw(space) << to_string_with_precision((double)mota*100.0) + "\%" << std::setw(space) << to_string_with_precision(motp) + " px" << endl; } else if(report_level == FULL_LEVEL){ int space = 12; rfile << std::setw(space) << "GTobj" << std::setw(space) << "SUTobj" << std::setw(space) << "FP" << std::setw(space) << "FN" << std::setw(space) << "TP" << std::setw(space) << "Rcll" << std::setw(space) << "Prcn" << std::setw(space) << "F1" << endl; rfile << std::setw(space) << to_string_with_precision(gt_objects,0) << std::setw(space) << to_string_with_precision(tk_objects,0) << std::setw(space) << to_string_with_precision((double)false_positives/(double)tk_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)false_negatives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)true_positives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision(recall) << std::setw(space) << to_string_with_precision(precision) << std::setw(space) << to_string_with_precision(f1measure) << endl; } else if(report_level == FULLP_LEVEL){ int space = 12; rfile << std::setw(space) << "GTobj" << std::setw(space) << "SUTobj" << std::setw(space) << "FP" << std::setw(space) << "FN" << std::setw(space) << "TP" << std::setw(space) << "MS" << std::setw(space) << "MSM" << std::setw(space) << "Rcll" << std::setw(space) << "Prcn" << std::setw(space) << "F1" << std::setw(space) << "MOTA" << std::setw(space) << "MOTP" << endl; rfile << std::setw(space) << to_string_with_precision(gt_objects,0) << std::setw(space) << to_string_with_precision(tk_objects,0) << std::setw(space) << to_string_with_precision((double)false_positives/(double)tk_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)false_negatives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)true_positives/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)misses/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision((double)missmatches/(double)gt_objects*100.0) + "\%" << std::setw(space) << to_string_with_precision(recall) << std::setw(space) << to_string_with_precision(precision) << std::setw(space) << to_string_with_precision(f1measure) << std::setw(space) << to_string_with_precision((double)mota*100.0) + "\%" << std::setw(space) << to_string_with_precision(motp) + " px" << endl; } } double Measurer::CalculateMean(vector< double > data) { double sum=0.0; double mean=0.0; for(unsigned int i=0; i<data.size();i++) sum += data[i]; mean = sum/data.size(); return mean; } double Measurer::CalculateVariance(vector< double > data) { double sum=0.0; double mean=0.0; double variance=0.0; for(unsigned int i=0; i<data.size();i++) sum += data[i]; mean = sum/data.size(); for(unsigned int j=0; j<data.size();j++) variance += pow(data[j] - mean, 2); variance=variance/data.size(); return variance; } Measurer::~Measurer() { }
37.855856
120
0.65096
jose-lp
72b468e854a1c4a985950fd2d3a205613e87d923
5,730
cpp
C++
Class 03 - Index Buffer/Main.cpp
TheSampaio/LearnOpenGL
3451b9595a35e0c5bbbbe627c32abe8e08783a5b
[ "Unlicense" ]
null
null
null
Class 03 - Index Buffer/Main.cpp
TheSampaio/LearnOpenGL
3451b9595a35e0c5bbbbe627c32abe8e08783a5b
[ "Unlicense" ]
null
null
null
Class 03 - Index Buffer/Main.cpp
TheSampaio/LearnOpenGL
3451b9595a35e0c5bbbbe627c32abe8e08783a5b
[ "Unlicense" ]
null
null
null
#include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> // Vertex Shader source code const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; //Fragment Shader source code const char* fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(0.8f, 0.3f, 0.02f, 1.0f);\n" "}\n\0"; int main(void) { unsigned int windowWidth = 800; // Window's width unsigned int windowHeight = (windowWidth / 2) + (windowWidth / 2) / 2; // Window's height const char* windowName = "My OpenGL Window"; // Window's title glfwInit(); // Initializing GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Setting OpenGL version to '3'.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Setting OpenGL version to 3.'3' glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Choosing OpenGL's CORE mode if (!glfwInit()) // Verifying if GLFW was initialized { std::cout << "[ERROR]: Failed to initialize GLFW" << std::endl; return -1; } GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, windowName, NULL, NULL); // Creating the window if (!window) // Verifying if window was initialized { std::cout << "[ERROR]: Failed to create a window" << std::endl; glfwTerminate(); // Finilizing GLFW return -1; } glfwMakeContextCurrent(window); // Creating a context gladLoadGL(); // Loading GLAD glViewport(0, 0, windowWidth, windowHeight); // Creating a viewport GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); // Creating a vertex shader glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // Linking the vertexShaderSource to the vertex shader glCompileShader(vertexShader); // Compiling vertex shader into machine code GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Creating a fragment shader glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // Linking the fragmentShaderSource to the fragment shader glCompileShader(fragmentShader); // Compiling fragment shader into machine code GLuint shaderProgram = glCreateProgram(); // Creating a shader program glAttachShader(shaderProgram, vertexShader); // Linking the vertex shader to the shader program glAttachShader(shaderProgram, fragmentShader); // Linking the fragment shader to the shader program glLinkProgram(shaderProgram); // Mounting the shader program with vertex and fragment shaders glDeleteShader(vertexShader); // Delleting vertex shader after link glDeleteShader(fragmentShader); // Delleting fragment shader after link GLfloat vertices[] // Array vertices data { -0.5f, -0.5f * float(sqrt(3)) / 3, 0.0f, // Lower left corner 0.5f, -0.5f * float(sqrt(3)) / 3, 0.0f, // Lower right corner 0.0f, 0.5f * float(sqrt(3)) * 2 / 3, 0.0f, // Upper corner -0.5f / 2, 0.5f * float(sqrt(3)) / 6, 0.0f, // Inner left 0.5f / 2, 0.5f * float(sqrt(3)) / 6, 0.0f, // Inner right 0.0f, -0.5f * float(sqrt(3)) / 3, 0.0f // Inner down }; GLuint indices[] // Array indices data { 0, 3, 5, // Lower left triangle 3, 2, 4, // Lower right triangle 5, 4, 1 // Upper triangle }; GLuint VAO, VBO, EBO; // Defining a Vertex Array Object & Vertex Buffer Object glGenVertexArrays(1, &VAO); // Creating the VAO glGenBuffers(1, &VBO); // Creating the VBO glGenBuffers(1, &EBO); // Creating the EBO glBindVertexArray(VAO); // Bind the VAO glBindBuffer(GL_ARRAY_BUFFER, VBO); // Bind the VBO glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Storing the vertices in the VBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // Bind the EBO glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Storing the indices in the EBO glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // Configuring the VAO glEnableVertexAttribArray(0); // Enable the VAO to can use it // Bind the VBO, VAO and EBO to 0 so that we don't accidentally modify the VAO, VBO or EBO that was created glBindBuffer(GL_ARRAY_BUFFER, 0); // To avoid bugs glBindVertexArray(0); // To avoid bugs glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // To avoid bugs while (!glfwWindowShouldClose(window)) // Windows's loop { glClearColor(0.08f, 0.14f, 0.18f, 1.0f); // Choosing window's background's color glClear(GL_COLOR_BUFFER_BIT); // Cleaning up front buffer glUseProgram(shaderProgram); // Active the shader program glBindVertexArray(VAO); // Bind the VAO again glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0); // Tell OpenGL what to draw glfwSwapBuffers(window); // Swapping buffers glfwPollEvents(); // Processing window's events } // Deleting what we don't need anymore glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteProgram(shaderProgram); glfwDestroyWindow(window); // Destroying window's process glfwTerminate(); // Finilizing GLFW return 0; }
43.740458
126
0.633857
TheSampaio
72b4b96dcaf697708bc98bec2d9242eb6d0359fa
14,055
cpp
C++
aws-cpp-sdk-codebuild/source/model/BuildBatch.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-codebuild/source/model/BuildBatch.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-codebuild/source/model/BuildBatch.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/codebuild/model/BuildBatch.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CodeBuild { namespace Model { BuildBatch::BuildBatch() : m_idHasBeenSet(false), m_arnHasBeenSet(false), m_startTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_currentPhaseHasBeenSet(false), m_buildBatchStatus(StatusType::NOT_SET), m_buildBatchStatusHasBeenSet(false), m_sourceVersionHasBeenSet(false), m_resolvedSourceVersionHasBeenSet(false), m_projectNameHasBeenSet(false), m_phasesHasBeenSet(false), m_sourceHasBeenSet(false), m_secondarySourcesHasBeenSet(false), m_secondarySourceVersionsHasBeenSet(false), m_artifactsHasBeenSet(false), m_secondaryArtifactsHasBeenSet(false), m_cacheHasBeenSet(false), m_environmentHasBeenSet(false), m_serviceRoleHasBeenSet(false), m_logConfigHasBeenSet(false), m_buildTimeoutInMinutes(0), m_buildTimeoutInMinutesHasBeenSet(false), m_queuedTimeoutInMinutes(0), m_queuedTimeoutInMinutesHasBeenSet(false), m_complete(false), m_completeHasBeenSet(false), m_initiatorHasBeenSet(false), m_vpcConfigHasBeenSet(false), m_encryptionKeyHasBeenSet(false), m_buildBatchNumber(0), m_buildBatchNumberHasBeenSet(false), m_fileSystemLocationsHasBeenSet(false), m_buildBatchConfigHasBeenSet(false), m_buildGroupsHasBeenSet(false) { } BuildBatch::BuildBatch(JsonView jsonValue) : m_idHasBeenSet(false), m_arnHasBeenSet(false), m_startTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_currentPhaseHasBeenSet(false), m_buildBatchStatus(StatusType::NOT_SET), m_buildBatchStatusHasBeenSet(false), m_sourceVersionHasBeenSet(false), m_resolvedSourceVersionHasBeenSet(false), m_projectNameHasBeenSet(false), m_phasesHasBeenSet(false), m_sourceHasBeenSet(false), m_secondarySourcesHasBeenSet(false), m_secondarySourceVersionsHasBeenSet(false), m_artifactsHasBeenSet(false), m_secondaryArtifactsHasBeenSet(false), m_cacheHasBeenSet(false), m_environmentHasBeenSet(false), m_serviceRoleHasBeenSet(false), m_logConfigHasBeenSet(false), m_buildTimeoutInMinutes(0), m_buildTimeoutInMinutesHasBeenSet(false), m_queuedTimeoutInMinutes(0), m_queuedTimeoutInMinutesHasBeenSet(false), m_complete(false), m_completeHasBeenSet(false), m_initiatorHasBeenSet(false), m_vpcConfigHasBeenSet(false), m_encryptionKeyHasBeenSet(false), m_buildBatchNumber(0), m_buildBatchNumberHasBeenSet(false), m_fileSystemLocationsHasBeenSet(false), m_buildBatchConfigHasBeenSet(false), m_buildGroupsHasBeenSet(false) { *this = jsonValue; } BuildBatch& BuildBatch::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("id")) { m_id = jsonValue.GetString("id"); m_idHasBeenSet = true; } if(jsonValue.ValueExists("arn")) { m_arn = jsonValue.GetString("arn"); m_arnHasBeenSet = true; } if(jsonValue.ValueExists("startTime")) { m_startTime = jsonValue.GetDouble("startTime"); m_startTimeHasBeenSet = true; } if(jsonValue.ValueExists("endTime")) { m_endTime = jsonValue.GetDouble("endTime"); m_endTimeHasBeenSet = true; } if(jsonValue.ValueExists("currentPhase")) { m_currentPhase = jsonValue.GetString("currentPhase"); m_currentPhaseHasBeenSet = true; } if(jsonValue.ValueExists("buildBatchStatus")) { m_buildBatchStatus = StatusTypeMapper::GetStatusTypeForName(jsonValue.GetString("buildBatchStatus")); m_buildBatchStatusHasBeenSet = true; } if(jsonValue.ValueExists("sourceVersion")) { m_sourceVersion = jsonValue.GetString("sourceVersion"); m_sourceVersionHasBeenSet = true; } if(jsonValue.ValueExists("resolvedSourceVersion")) { m_resolvedSourceVersion = jsonValue.GetString("resolvedSourceVersion"); m_resolvedSourceVersionHasBeenSet = true; } if(jsonValue.ValueExists("projectName")) { m_projectName = jsonValue.GetString("projectName"); m_projectNameHasBeenSet = true; } if(jsonValue.ValueExists("phases")) { Array<JsonView> phasesJsonList = jsonValue.GetArray("phases"); for(unsigned phasesIndex = 0; phasesIndex < phasesJsonList.GetLength(); ++phasesIndex) { m_phases.push_back(phasesJsonList[phasesIndex].AsObject()); } m_phasesHasBeenSet = true; } if(jsonValue.ValueExists("source")) { m_source = jsonValue.GetObject("source"); m_sourceHasBeenSet = true; } if(jsonValue.ValueExists("secondarySources")) { Array<JsonView> secondarySourcesJsonList = jsonValue.GetArray("secondarySources"); for(unsigned secondarySourcesIndex = 0; secondarySourcesIndex < secondarySourcesJsonList.GetLength(); ++secondarySourcesIndex) { m_secondarySources.push_back(secondarySourcesJsonList[secondarySourcesIndex].AsObject()); } m_secondarySourcesHasBeenSet = true; } if(jsonValue.ValueExists("secondarySourceVersions")) { Array<JsonView> secondarySourceVersionsJsonList = jsonValue.GetArray("secondarySourceVersions"); for(unsigned secondarySourceVersionsIndex = 0; secondarySourceVersionsIndex < secondarySourceVersionsJsonList.GetLength(); ++secondarySourceVersionsIndex) { m_secondarySourceVersions.push_back(secondarySourceVersionsJsonList[secondarySourceVersionsIndex].AsObject()); } m_secondarySourceVersionsHasBeenSet = true; } if(jsonValue.ValueExists("artifacts")) { m_artifacts = jsonValue.GetObject("artifacts"); m_artifactsHasBeenSet = true; } if(jsonValue.ValueExists("secondaryArtifacts")) { Array<JsonView> secondaryArtifactsJsonList = jsonValue.GetArray("secondaryArtifacts"); for(unsigned secondaryArtifactsIndex = 0; secondaryArtifactsIndex < secondaryArtifactsJsonList.GetLength(); ++secondaryArtifactsIndex) { m_secondaryArtifacts.push_back(secondaryArtifactsJsonList[secondaryArtifactsIndex].AsObject()); } m_secondaryArtifactsHasBeenSet = true; } if(jsonValue.ValueExists("cache")) { m_cache = jsonValue.GetObject("cache"); m_cacheHasBeenSet = true; } if(jsonValue.ValueExists("environment")) { m_environment = jsonValue.GetObject("environment"); m_environmentHasBeenSet = true; } if(jsonValue.ValueExists("serviceRole")) { m_serviceRole = jsonValue.GetString("serviceRole"); m_serviceRoleHasBeenSet = true; } if(jsonValue.ValueExists("logConfig")) { m_logConfig = jsonValue.GetObject("logConfig"); m_logConfigHasBeenSet = true; } if(jsonValue.ValueExists("buildTimeoutInMinutes")) { m_buildTimeoutInMinutes = jsonValue.GetInteger("buildTimeoutInMinutes"); m_buildTimeoutInMinutesHasBeenSet = true; } if(jsonValue.ValueExists("queuedTimeoutInMinutes")) { m_queuedTimeoutInMinutes = jsonValue.GetInteger("queuedTimeoutInMinutes"); m_queuedTimeoutInMinutesHasBeenSet = true; } if(jsonValue.ValueExists("complete")) { m_complete = jsonValue.GetBool("complete"); m_completeHasBeenSet = true; } if(jsonValue.ValueExists("initiator")) { m_initiator = jsonValue.GetString("initiator"); m_initiatorHasBeenSet = true; } if(jsonValue.ValueExists("vpcConfig")) { m_vpcConfig = jsonValue.GetObject("vpcConfig"); m_vpcConfigHasBeenSet = true; } if(jsonValue.ValueExists("encryptionKey")) { m_encryptionKey = jsonValue.GetString("encryptionKey"); m_encryptionKeyHasBeenSet = true; } if(jsonValue.ValueExists("buildBatchNumber")) { m_buildBatchNumber = jsonValue.GetInt64("buildBatchNumber"); m_buildBatchNumberHasBeenSet = true; } if(jsonValue.ValueExists("fileSystemLocations")) { Array<JsonView> fileSystemLocationsJsonList = jsonValue.GetArray("fileSystemLocations"); for(unsigned fileSystemLocationsIndex = 0; fileSystemLocationsIndex < fileSystemLocationsJsonList.GetLength(); ++fileSystemLocationsIndex) { m_fileSystemLocations.push_back(fileSystemLocationsJsonList[fileSystemLocationsIndex].AsObject()); } m_fileSystemLocationsHasBeenSet = true; } if(jsonValue.ValueExists("buildBatchConfig")) { m_buildBatchConfig = jsonValue.GetObject("buildBatchConfig"); m_buildBatchConfigHasBeenSet = true; } if(jsonValue.ValueExists("buildGroups")) { Array<JsonView> buildGroupsJsonList = jsonValue.GetArray("buildGroups"); for(unsigned buildGroupsIndex = 0; buildGroupsIndex < buildGroupsJsonList.GetLength(); ++buildGroupsIndex) { m_buildGroups.push_back(buildGroupsJsonList[buildGroupsIndex].AsObject()); } m_buildGroupsHasBeenSet = true; } return *this; } JsonValue BuildBatch::Jsonize() const { JsonValue payload; if(m_idHasBeenSet) { payload.WithString("id", m_id); } if(m_arnHasBeenSet) { payload.WithString("arn", m_arn); } if(m_startTimeHasBeenSet) { payload.WithDouble("startTime", m_startTime.SecondsWithMSPrecision()); } if(m_endTimeHasBeenSet) { payload.WithDouble("endTime", m_endTime.SecondsWithMSPrecision()); } if(m_currentPhaseHasBeenSet) { payload.WithString("currentPhase", m_currentPhase); } if(m_buildBatchStatusHasBeenSet) { payload.WithString("buildBatchStatus", StatusTypeMapper::GetNameForStatusType(m_buildBatchStatus)); } if(m_sourceVersionHasBeenSet) { payload.WithString("sourceVersion", m_sourceVersion); } if(m_resolvedSourceVersionHasBeenSet) { payload.WithString("resolvedSourceVersion", m_resolvedSourceVersion); } if(m_projectNameHasBeenSet) { payload.WithString("projectName", m_projectName); } if(m_phasesHasBeenSet) { Array<JsonValue> phasesJsonList(m_phases.size()); for(unsigned phasesIndex = 0; phasesIndex < phasesJsonList.GetLength(); ++phasesIndex) { phasesJsonList[phasesIndex].AsObject(m_phases[phasesIndex].Jsonize()); } payload.WithArray("phases", std::move(phasesJsonList)); } if(m_sourceHasBeenSet) { payload.WithObject("source", m_source.Jsonize()); } if(m_secondarySourcesHasBeenSet) { Array<JsonValue> secondarySourcesJsonList(m_secondarySources.size()); for(unsigned secondarySourcesIndex = 0; secondarySourcesIndex < secondarySourcesJsonList.GetLength(); ++secondarySourcesIndex) { secondarySourcesJsonList[secondarySourcesIndex].AsObject(m_secondarySources[secondarySourcesIndex].Jsonize()); } payload.WithArray("secondarySources", std::move(secondarySourcesJsonList)); } if(m_secondarySourceVersionsHasBeenSet) { Array<JsonValue> secondarySourceVersionsJsonList(m_secondarySourceVersions.size()); for(unsigned secondarySourceVersionsIndex = 0; secondarySourceVersionsIndex < secondarySourceVersionsJsonList.GetLength(); ++secondarySourceVersionsIndex) { secondarySourceVersionsJsonList[secondarySourceVersionsIndex].AsObject(m_secondarySourceVersions[secondarySourceVersionsIndex].Jsonize()); } payload.WithArray("secondarySourceVersions", std::move(secondarySourceVersionsJsonList)); } if(m_artifactsHasBeenSet) { payload.WithObject("artifacts", m_artifacts.Jsonize()); } if(m_secondaryArtifactsHasBeenSet) { Array<JsonValue> secondaryArtifactsJsonList(m_secondaryArtifacts.size()); for(unsigned secondaryArtifactsIndex = 0; secondaryArtifactsIndex < secondaryArtifactsJsonList.GetLength(); ++secondaryArtifactsIndex) { secondaryArtifactsJsonList[secondaryArtifactsIndex].AsObject(m_secondaryArtifacts[secondaryArtifactsIndex].Jsonize()); } payload.WithArray("secondaryArtifacts", std::move(secondaryArtifactsJsonList)); } if(m_cacheHasBeenSet) { payload.WithObject("cache", m_cache.Jsonize()); } if(m_environmentHasBeenSet) { payload.WithObject("environment", m_environment.Jsonize()); } if(m_serviceRoleHasBeenSet) { payload.WithString("serviceRole", m_serviceRole); } if(m_logConfigHasBeenSet) { payload.WithObject("logConfig", m_logConfig.Jsonize()); } if(m_buildTimeoutInMinutesHasBeenSet) { payload.WithInteger("buildTimeoutInMinutes", m_buildTimeoutInMinutes); } if(m_queuedTimeoutInMinutesHasBeenSet) { payload.WithInteger("queuedTimeoutInMinutes", m_queuedTimeoutInMinutes); } if(m_completeHasBeenSet) { payload.WithBool("complete", m_complete); } if(m_initiatorHasBeenSet) { payload.WithString("initiator", m_initiator); } if(m_vpcConfigHasBeenSet) { payload.WithObject("vpcConfig", m_vpcConfig.Jsonize()); } if(m_encryptionKeyHasBeenSet) { payload.WithString("encryptionKey", m_encryptionKey); } if(m_buildBatchNumberHasBeenSet) { payload.WithInt64("buildBatchNumber", m_buildBatchNumber); } if(m_fileSystemLocationsHasBeenSet) { Array<JsonValue> fileSystemLocationsJsonList(m_fileSystemLocations.size()); for(unsigned fileSystemLocationsIndex = 0; fileSystemLocationsIndex < fileSystemLocationsJsonList.GetLength(); ++fileSystemLocationsIndex) { fileSystemLocationsJsonList[fileSystemLocationsIndex].AsObject(m_fileSystemLocations[fileSystemLocationsIndex].Jsonize()); } payload.WithArray("fileSystemLocations", std::move(fileSystemLocationsJsonList)); } if(m_buildBatchConfigHasBeenSet) { payload.WithObject("buildBatchConfig", m_buildBatchConfig.Jsonize()); } if(m_buildGroupsHasBeenSet) { Array<JsonValue> buildGroupsJsonList(m_buildGroups.size()); for(unsigned buildGroupsIndex = 0; buildGroupsIndex < buildGroupsJsonList.GetLength(); ++buildGroupsIndex) { buildGroupsJsonList[buildGroupsIndex].AsObject(m_buildGroups[buildGroupsIndex].Jsonize()); } payload.WithArray("buildGroups", std::move(buildGroupsJsonList)); } return payload; } } // namespace Model } // namespace CodeBuild } // namespace Aws
26.271028
158
0.749982
Neusoft-Technology-Solutions
72b50511dccafe526b02a66a55caac71c7d0084d
1,283
hpp
C++
src/common/types.hpp
marcesengel/realm-js
74b06e0f2aec8526056ccae1da6056e521853a44
[ "Apache-1.1" ]
null
null
null
src/common/types.hpp
marcesengel/realm-js
74b06e0f2aec8526056ccae1da6056e521853a44
[ "Apache-1.1" ]
null
null
null
src/common/types.hpp
marcesengel/realm-js
74b06e0f2aec8526056ccae1da6056e521853a44
[ "Apache-1.1" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #pragma once namespace realm { namespace js { namespace types { /* * Common idiom that covers Realm and JavaScript. */ enum Type { NotImplemented = -100, Object = 16, // We translate TypedLink (16) -> Object Undefined = -2, Null = -1, Integer = 0, Boolean = 1, String = 2, Binary = 4, Mixed = 6, Timestamp = 8, Float = 9, Double = 10, Decimal = 11, Link = 12, LinkList = 13, ObjectId = 15, UUID = 17, }; } // namespace types } // namespace js } // namespace realm
24.207547
76
0.577553
marcesengel
72b5c8d1c96cba94634aa99a07bac06bec91d2dd
2,347
cpp
C++
src/absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.cpp
leoneed03/reconstrutor
5e6417ed2b090617202cad1a10010141e4ce6615
[ "MIT" ]
null
null
null
src/absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.cpp
leoneed03/reconstrutor
5e6417ed2b090617202cad1a10010141e4ce6615
[ "MIT" ]
1
2021-05-21T15:52:37.000Z
2021-05-24T11:34:46.000Z
src/absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.cpp
leoneed03/reconstrutor
5e6417ed2b090617202cad1a10010141e4ce6615
[ "MIT" ]
null
null
null
// // Copyright (c) Leonid Seniukov. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. // #include "absolutePoseEstimation/rotationAveraging/RelativePosesG2oFormat.h" namespace gdr { RelativePosesG2oFormat::RelativePosesG2oFormat(const std::vector<RotationMeasurement> &relativeRotationsToSet) : relativeRotations(relativeRotationsToSet) {} std::ostream &operator<<(std::ostream &os, const RelativePosesG2oFormat &rotationsG2o) { assert(!rotationsG2o.relativeRotations.empty()); int minIndex = std::numeric_limits<int>::max() / 2; int maxIndex = -1; for (const auto &relativeRotation: rotationsG2o.relativeRotations) { int indexFromDestination = relativeRotation.getIndexFromDestination(); int indexToToBeTransformed = relativeRotation.getIndexToToBeTransformed(); if (indexFromDestination >= indexToToBeTransformed) { continue; } minIndex = std::min(minIndex, indexFromDestination); maxIndex = std::max(maxIndex, indexToToBeTransformed); } assert(minIndex == 0); assert(minIndex < maxIndex); for (int i = 0; i <= maxIndex; ++i) { std::string s1 = "VERTEX_SE3:QUAT "; std::string s2 = std::to_string(i) + " 0.000000 0.000000 0.000000 0.0 0.0 0.0 1.0\n"; os << s1 + s2; } std::string noise = " 10000.000000 0.000000 0.000000 0.000000 0.000000 0.000000 10000.000000 0.000000 0.000000 0.000000 0.000000 10000.000000 0.000000 0.000000 0.000000 10000.000000 0.000000 0.000000 10000.000000 0.000000 10000.000000"; for (const auto &relativeRotation: rotationsG2o.relativeRotations) { int indexFromDestination = relativeRotation.getIndexFromDestination(); int indexToToBeTransformed = relativeRotation.getIndexToToBeTransformed(); if (indexFromDestination >= indexToToBeTransformed) { continue; } os << "EDGE_SE3:QUAT " << indexFromDestination << ' ' << indexToToBeTransformed << ' '; os << 0.0 << ' ' << 0.0 << ' ' << 0.0 << ' ' << relativeRotation.getRotationSO3() << ' '; os << noise << std::endl; } return os; } }
39.116667
256
0.63187
leoneed03
72b64baf03887aab772b7e22e916d06b92e3cc20
26,591
cpp
C++
fastFEM/mesh/meshtype.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
4
2019-05-06T09:35:08.000Z
2021-05-14T16:26:45.000Z
fastFEM/mesh/meshtype.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
null
null
null
fastFEM/mesh/meshtype.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
[ "MIT" ]
1
2019-06-28T09:23:43.000Z
2019-06-28T09:23:43.000Z
// Copyright 2020 Poofee (https://github.com/Poofee) // // 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. // ------------------------------------------------------------------------ /***************************************************************************** * * * * * * ***************************************************************************** * * * Authors: Poofee * * Email: poofee@qq.com * * Address: * * Original Date: 2020-07-15 * * * *****************************************************************************/ #include <iostream> #include <fstream> #include "meshtype.h" using namespace std; // node_t //----------------------------------------------------------------------------- node_t::node_t() { } node_t::~node_t() { } void node_t::setXvec(double* y) { this->x[0] = y[0]; this->x[1] = y[1]; this->x[2] = y[2]; } double* node_t::getXvec() { return &this->x[0]; } void node_t::setX(int n, double y) { this->x[n] = y; } double node_t::getX(int n) const { return this->x[n]; } void node_t::setIndex(int n) { this->index = n; } int node_t::getIndex() const { return this->index; } // element_t //----------------------------------------------------------------------------- element_t::element_t() { } element_t::~element_t() { } void element_t::setNature(int n) { this->nature = n; } int element_t::getNature() const { return this->nature; } void element_t::setCode(int n) { this->code = n; } int element_t::getCode() const { return this->code; } void element_t::setNodes(int n) { this->nodes = n; } int element_t::getNodes() const { return this->nodes; } void element_t::setIndex(int n) { this->index = n; } int element_t::getIndex() const { return this->index; } void element_t::setSelected(int n) { this->selected = n; } int element_t::getSelected() const { return this->selected; } int element_t::getNodeIndex(int n) const { return this->node[n]; } void element_t::setNodeIndex(int m, int n) { this->node[m] = n; } void element_t::newNodeIndexes(int n) { this->node = new int[n]; } void element_t::deleteNodeIndexes() { delete [] this->node; } int* element_t::getNodeIndexes() const { return this->node; } // point_t //----------------------------------------------------------------------------- point_t::point_t() { } point_t::~point_t() { } void point_t::setSharp(bool b) { this->sharp_point = b; } bool point_t::isSharp() const { return this->sharp_point; } void point_t::setEdges(int n) { this->edges = n; } int point_t::getEdges() const { return this->edges; } int point_t::getEdgeIndex(int n) const { return this->edge[n]; } void point_t::setEdgeIndex(int m, int n) { this->edge[m] = n; } void point_t::newEdgeIndexes(int n) { this->edge = new int[n]; } void point_t::deleteEdgeIndexes() { delete [] this->edge; } // edge_t //----------------------------------------------------------------------------- edge_t::edge_t() { } edge_t::~edge_t() { } void edge_t::setSharp(bool b) { this->sharp_edge = b; } bool edge_t::isSharp() const { return this->sharp_edge; } void edge_t::setPoints(int n) { this->points = n; } int edge_t::getPoints() const { return this->points; } void edge_t::setPointIndex(int m, int n) { this->point[m] = n; } int edge_t::getPointIndex(int n) const { return this->point[n]; } void edge_t::newPointIndexes(int n) { this->point = new int[n]; } void edge_t::deletePointIndexes() { delete [] this->point; } void edge_t::setSurfaces(int n) { this->surfaces = n; } int edge_t::getSurfaces() const { return this->surfaces; } void edge_t::setSurfaceIndex(int m, int n) { this->surface[m] = n; } int edge_t::getSurfaceIndex(int n) const { return this->surface[n]; } void edge_t::newSurfaceIndexes(int n) { this->surface = new int[n]; } void edge_t::deleteSurfaceIndexes() { delete [] this->surface; } // surface_t //----------------------------------------------------------------------------- surface_t::surface_t() { } surface_t::~surface_t() { } void surface_t::setEdges(int n) { this->edges = n; } int surface_t::getEdges() const { return this->edges; } void surface_t::setEdgeIndex(int m, int n) { this->edge[m] = n; } int surface_t::getEdgeIndex(int n) const { return this->edge[n]; } void surface_t::newEdgeIndexes(int n) { this->edge = new int[n]; } void surface_t::deleteEdgeIndexes() { delete [] this->edge; } void surface_t::setElements(int n) { this->elements = n; } int surface_t::getElements() const { return this->elements; } void surface_t::setElementIndex(int m, int n) { this->element[m] = n; } int surface_t::getElementIndex(int n) const { return this->element[n]; } void surface_t::newElementIndexes(int n) { this->element = new int[n]; } void surface_t::deleteElementIndexes() { delete [] this->element; } double* surface_t::getNormalVec() { return &this->normal[0]; } void surface_t::setNormalVec(double* d) { this->normal[0] = d[0]; this->normal[1] = d[1]; this->normal[2] = d[2]; } double surface_t::getNormal(int n) const { return this->normal[n]; } void surface_t::setNormal(int n, double d) { this->normal[n] = d; } void surface_t::setVertexNormalVec(int n, double* d) { this->vertex_normals[n][0] = d[0]; this->vertex_normals[n][1] = d[1]; this->vertex_normals[n][2] = d[2]; } void surface_t::addVertexNormalVec(int n, double* d) { this->vertex_normals[n][0] += d[0]; this->vertex_normals[n][1] += d[1]; this->vertex_normals[n][2] += d[2]; } void surface_t::subVertexNormalVec(int n, double* d) { this->vertex_normals[n][0] -= d[0]; this->vertex_normals[n][1] -= d[1]; this->vertex_normals[n][2] -= d[2]; } double* surface_t::getVertexNormalVec(int n) { return &this->vertex_normals[n][0]; } // mesh_t //----------------------------------------------------------------------------- mesh_t::mesh_t() { this->setDefaults(); } mesh_t::~mesh_t() { } bool mesh_t::isUndefined() const { if((cdim < 0) || (dim < 0) || (nodes < 1)) return true; return false; } void mesh_t::clear() { delete [] element; delete [] surface; delete [] edge; delete [] point; delete [] node; setDefaults(); } void mesh_t::setDefaults() { cdim = -1; dim = -1; nodes = 0; node = 0; points = 0; point = 0; edges = 0; edge = 0; surfaces = 0; surface = 0; elements = 0; element = 0; } // Load Elmer mesh files and populate mesh structures //--------------------------------------------------------------------------- bool mesh_t::load(char* dirName) { char fileName[1024]; ifstream mesh_header; ifstream mesh_nodes; ifstream mesh_elements; ifstream mesh_boundary; // Header: //-------- sprintf(fileName, "%s/mesh.header", dirName); mesh_header.open(fileName); if(!mesh_header.is_open()) { cout << "Mesh: load: unable to open " << fileName << endl; return false; } int nodes, elements, boundaryelements, types, type, ntype; mesh_header >> nodes >> elements >> boundaryelements; mesh_header >> types; int elements_zero_d = 0; int elements_one_d = 0; int elements_two_d = 0; int elements_three_d = 0; for(int i = 0; i < types; i++) { mesh_header >> type >> ntype; switch(type/100) { case 1: elements_zero_d += ntype; break; case 2: elements_one_d += ntype; break; case 3: case 4: elements_two_d += ntype; break; case 5: case 6: case 7: case 8: elements_three_d += ntype; break; default: cout << "Unknown element family (possibly not implamented)" << endl; cout.flush(); return false; // exit(0); } } cout << "Summary:" << endl; cout << "Nodes: " << nodes << endl; cout << "Point elements: " << elements_zero_d << endl; cout << "Edge elements: " << elements_one_d << endl; cout << "Surface elements: " << elements_two_d << endl; cout << "Volume elements: " << elements_three_d << endl; cout.flush(); // Set mesh dimension: this->dim = 0; if(elements_one_d > 0) this->dim = 1; if(elements_two_d > 0) this->dim = 2; if(elements_three_d > 0) this->dim = 3; this->nodes = nodes; node = new node_t[nodes]; this->points = elements_zero_d; point = new point_t[this->points]; this->edges = elements_one_d; edge = new edge_t[this->edges]; this->surfaces = elements_two_d; surface = new surface_t[this->surfaces]; this->elements = elements_three_d; element = new element_t[this->elements]; mesh_header.close(); // Nodes: //------- sprintf(fileName, "%s/mesh.nodes", dirName); mesh_nodes.open(fileName); if(!mesh_nodes.is_open()) { cout << "Mesh: load: unable to open " << fileName << endl; return false; } int number, index; double x, y, z; for(int i = 0; i < nodes; i++) { node_t *node = &this->node[i]; mesh_nodes >> number >> index >> x >> y >> z; node->setX(0, x); node->setX(1, y); node->setX(2, z); node->setIndex(index); } mesh_nodes.close(); // Elements: //---------- sprintf(fileName, "%s/mesh.elements", dirName); mesh_elements.open(fileName); if(!mesh_elements.is_open()) { cout << "Mesh: load: unable to open " << fileName << endl; return false; } int current_point = 0; int current_edge = 0; int current_surface = 0; int current_element = 0; point_t *point = NULL; edge_t *edge = NULL; surface_t *surface = NULL; element_t *element = NULL; for(int i = 0; i < elements; i++) { mesh_elements >> number >> index >> type; switch(type/100) { case 1: point = &this->point[current_point++]; point->setNature(PDE_BULK); point->setIndex(index); point->setCode(type); point->setNodes(point->getCode() % 100); point->newNodeIndexes(point->getNodes()); for(int j = 0; j < point->getNodes(); j++) { int k; mesh_elements >> k; point->setNodeIndex(j, k-1); } point->setEdges(2); point->newEdgeIndexes(point->getEdges()); point->setEdgeIndex(0, -1); point->setEdgeIndex(1, -1); break; case 2: edge = &this->edge[current_edge++]; edge->setNature(PDE_BULK); edge->setIndex(index); edge->setCode(type); edge->setNodes(edge->getCode() % 100); edge->newNodeIndexes(edge->getNodes()); for(int j = 0; j < edge->getNodes(); j++) { int k; mesh_elements >> k; edge->setNodeIndex(j, k-1); } edge->setSurfaces(0); edge->newSurfaceIndexes(edge->getSurfaces()); edge->setSurfaceIndex(0, -1); edge->setSurfaceIndex(1, -1); break; case 3: case 4: surface = &this->surface[current_surface++]; surface->setNature(PDE_BULK); surface->setIndex(index); surface->setCode(type); surface->setNodes(surface->getCode() % 100); surface->newNodeIndexes(surface->getNodes()); for(int j = 0; j < surface->getNodes(); j++) { int k; mesh_elements >> k; surface->setNodeIndex(j, k-1); } surface->setEdges((int)(surface->getCode() / 100)); surface->newEdgeIndexes(surface->getEdges()); for(int j = 0; j < surface->getEdges(); j++) surface->setEdgeIndex(j, -1); surface->setElements(2); surface->newElementIndexes(surface->getElements()); surface->setElementIndex(0, -1); surface->setElementIndex(1, -1); break; case 5: case 6: case 7: case 8: element = &this->element[current_element++]; element->setNature(PDE_BULK); element->setIndex(index); element->setCode(type); element->setNodes(element->getCode() % 100); element->newNodeIndexes(element->getNodes()); for(int j = 0; j < element->getNodes(); j++) { int k; mesh_elements >> k; element->setNodeIndex(j, k-1); } break; default: cout << "Unknown element type (possibly not implemented" << endl; cout.flush(); return false; // exit(0); } } mesh_elements.close(); // Boundary elements: //------------------- sprintf(fileName, "%s/mesh.boundary", dirName); mesh_boundary.open(fileName); if(!mesh_boundary.is_open()) { cout << "Mesh: load: unable to open " << fileName << endl; return false; } int parent0, parent1; for(int i = 0; i < boundaryelements; i++) { mesh_boundary >> number >> index >> parent0 >> parent1 >> type; switch(type/100) { case 1: point = &this->point[current_point++]; point->setNature(PDE_BOUNDARY); point->setIndex(index); point->setEdges(2); point->newEdgeIndexes(point->getEdges()); point->setEdgeIndex(0, parent0 - 1); point->setEdgeIndex(1, parent0 - 1); point->setCode(type); point->setNodes(point->getCode() % 100); point->newNodeIndexes(point->getNodes()); for(int j = 0; j < point->getNodes(); j++) { int k; mesh_boundary >> k; point->setNodeIndex(j, k-1); } break; case 2: edge = &this->edge[current_edge++]; edge->setNature(PDE_BOUNDARY); edge->setIndex(index); edge->setSurfaces(2); edge->newSurfaceIndexes(edge->getSurfaces()); edge->setSurfaceIndex(0, parent0 - 1); edge->setSurfaceIndex(1, parent1 - 1); edge->setCode(type); edge->setNodes(edge->getCode() % 100); edge->newNodeIndexes(edge->getNodes()); for(int j = 0; j < edge->getNodes(); j++) { int k; mesh_boundary >> k; edge->setNodeIndex(j, k-1); } break; case 3: case 4: surface = &this->surface[current_surface++]; surface->setNature(PDE_BOUNDARY); surface->setIndex(index); surface->setElements(2); surface->newElementIndexes(surface->getElements()); surface->setElementIndex(0, parent0 - 1); surface->setElementIndex(1, parent1 - 1); surface->setCode(type); surface->setNodes(surface->getCode() % 100); surface->newNodeIndexes(surface->getNodes()); for(int j = 0; j < surface->getNodes(); j++) { int k; mesh_boundary >> k; surface->setNodeIndex(j, k-1); } surface->setEdges((int)(surface->getCode() / 100)); surface->newEdgeIndexes(surface->getEdges()); for(int j = 0; j < surface->getEdges(); j++) surface->setEdgeIndex(j, -1); break; case 5: case 6: case 7: case 8: // these can't be boundary elements break; default: break; } } mesh_boundary.close(); this->boundingBox(); return true; } // Save Elmer mesh files and populate mesh structures //--------------------------------------------------------------------------- bool mesh_t::save(char *dirName) { char fileName[1024]; ofstream mesh_header; ofstream mesh_nodes; ofstream mesh_elements; ofstream mesh_boundary; // Elmer's elements codes are smaller than 1000 int maxcode = 1000; int *bulk_by_type = new int[maxcode]; int *boundary_by_type = new int[maxcode]; for(int i = 0; i < maxcode; i++) { bulk_by_type[i] = 0; boundary_by_type[i] = 0; } for(int i = 0; i < elements; i++) { element_t *e = &element[i]; if(e->getNature() == PDE_BULK) bulk_by_type[e->getCode()]++; if(e->getNature() == PDE_BOUNDARY) boundary_by_type[e->getCode()]++; } for(int i = 0; i < surfaces; i++) { surface_t *s = &surface[i]; if(s->getNature() == PDE_BULK) bulk_by_type[s->getCode()]++; if(s->getNature() == PDE_BOUNDARY) boundary_by_type[s->getCode()]++; } for(int i = 0; i < edges; i++) { edge_t *e = &edge[i]; if(e->getNature() == PDE_BULK) bulk_by_type[e->getCode()]++; if(e->getNature() == PDE_BOUNDARY) boundary_by_type[e->getCode()]++; } for(int i = 0; i < points; i++) { point_t *p = &point[i]; if(p->getNature() == PDE_BULK) bulk_by_type[p->getCode()]++; if(p->getNature() == PDE_BOUNDARY) boundary_by_type[p->getCode()]++; } int bulk_elements = 0; int boundary_elements = 0; int element_types = 0; for(int i = 0; i < maxcode; i++) { bulk_elements += bulk_by_type[i]; boundary_elements += boundary_by_type[i]; if((bulk_by_type[i] > 0) || (boundary_by_type[i] > 0)) element_types++; } // Header: //--------- sprintf(fileName, "%s/mesh.header", dirName); mesh_header.open(fileName); if(!mesh_header.is_open()) { cout << "Unable to open " << fileName << endl; return false; } cout << "Saving " << nodes << " nodes" << endl; cout << "Saving " << bulk_elements << " elements" << endl; cout << "Saving " << boundary_elements << " boundary elements" << endl; cout.flush(); mesh_header << nodes << " "; mesh_header << bulk_elements << " "; mesh_header << boundary_elements << endl; mesh_header << element_types << endl; for(int i = 0; i < maxcode; i++) { int j = bulk_by_type[i] + boundary_by_type[i]; if(j > 0) mesh_header << i << " " << j << endl; } mesh_header.close(); // Nodes: //-------- sprintf(fileName, "%s/mesh.nodes", dirName); mesh_nodes.open(fileName); if(!mesh_nodes.is_open()) { cout << "Unable to open " << fileName << endl; return false; } for(int i = 0; i < this->nodes; i++) { node_t *node = &this->node[i]; int ind = node->getIndex(); mesh_nodes << i+1 << " " << ind << " "; mesh_nodes << node->getX(0) << " "; mesh_nodes << node->getX(1) << " "; mesh_nodes << node->getX(2) << endl; } mesh_nodes.close(); // Elements: //---------- sprintf(fileName, "%s/mesh.elements", dirName); mesh_elements.open(fileName); if(!mesh_elements.is_open()) { cout << "Unable to open " << fileName << endl; return false; } int current = 0; for(int i = 0; i < this->elements; i++) { element_t *e = &this->element[i]; int ind = e->getIndex(); if(ind < 1) ind = 1; if(e->getNature() == PDE_BULK) { mesh_elements << ++current << " "; mesh_elements << ind << " "; mesh_elements << e->getCode() << " "; for(int j = 0; j < e->getNodes(); j++) mesh_elements << e->getNodeIndex(j) + 1 << " "; mesh_elements << endl; } } for(int i = 0; i < this->surfaces; i++) { surface_t *s = &this->surface[i]; int ind = s->getIndex(); if(ind < 1) ind = 1; if(s->getNature() == PDE_BULK) { mesh_elements << ++current << " "; mesh_elements << ind << " "; mesh_elements << s->getCode() << " "; for(int j = 0; j < s->getNodes(); j++) mesh_elements << s->getNodeIndex(j) + 1 << " "; mesh_elements << endl; } } for(int i = 0; i < this->edges; i++) { edge_t *e = &this->edge[i]; int ind = e->getIndex(); if(ind < 1) ind = 1; if(e->getNature() == PDE_BULK) { mesh_elements << ++current << " "; mesh_elements << ind << " "; mesh_elements << e->getCode() << " "; for(int j = 0; j < e->getNodes(); j++) mesh_elements << e->getNodeIndex(j) + 1 << " "; mesh_elements << endl; } } for(int i = 0; i < this->points; i++) { point_t *p = &this->point[i]; int ind = p->getIndex(); if(ind < 1) ind = 1; if(p->getNature() == PDE_BULK) { mesh_elements << ++current << " "; mesh_elements << ind << " "; mesh_elements << p->getCode() << " "; for(int j = 0; j < p->getNodes(); j++) mesh_elements << p->getNodeIndex(j) + 1 << " "; mesh_elements << endl; } } mesh_elements.close(); // Boundary elements: //------------------- sprintf(fileName, "%s/mesh.boundary", dirName); mesh_boundary.open(fileName); if(!mesh_boundary.is_open()) { cout << "Unable to open " << fileName << endl; return false; } current = 0; for(int i = 0; i < this->surfaces; i++) { surface_t *s = &this->surface[i]; if(s->getNature() == PDE_BULK) continue; int e0 = s->getElementIndex(0) + 1; int e1 = s->getElementIndex(1) + 1; if(e0 < 0) e0 = 0; if(e1 < 0) e1 = 0; int ind = s->getIndex(); if(ind < 1) ind = 1; if(s->getNature() == PDE_BOUNDARY) { mesh_boundary << ++current << " "; mesh_boundary << ind << " "; mesh_boundary << e0 << " " << e1 << " "; mesh_boundary << s->getCode() << " "; for(int j = 0; j < s->getNodes(); j++) mesh_boundary << s->getNodeIndex(j) + 1 << " "; mesh_boundary << endl; } } for(int i = 0; i < this->edges; i++) { edge_t *e = &this->edge[i]; if(e->getNature() == PDE_BULK) continue; int s0 = e->getSurfaceIndex(0) + 1; int s1 = e->getSurfaceIndex(1) + 1; if(s0 < 0) s0 = 0; if(s1 < 0) s1 = 0; int ind = e->getIndex(); if(ind < 1) ind = 1; if(e->getNature() == PDE_BOUNDARY) { mesh_boundary << ++current << " "; mesh_boundary << ind << " "; mesh_boundary << s0 << " " << s1 << " "; mesh_boundary << e->getCode() << " "; for(int j = 0; j < e->getNodes(); j++) mesh_boundary << e->getNodeIndex(j) + 1 << " "; mesh_boundary << endl; } } for(int i = 0; i < this->points; i++) { point_t *p = &this->point[i]; int e0 = p->getEdgeIndex(0) + 1; int e1 = p->getEdgeIndex(1) + 1; if(e0 < 0) e0 = 0; if(e1 < 0) e1 = 0; int ind = p->getIndex(); if(ind < 1) ind = 1; if(p->getNature() == PDE_BOUNDARY) { mesh_boundary << ++current << " "; mesh_boundary << ind << " "; mesh_boundary << e0 << " " << e1 << " "; mesh_boundary << p->getCode() << " "; for(int j = 0; j < p->getNodes(); j++) mesh_boundary << p->getNodeIndex(j) + 1 << " "; mesh_boundary << endl; } } mesh_boundary.close(); delete [] bulk_by_type; delete [] boundary_by_type; return true; } // Bounding box... //----------------------------------------------------------------------------- double* mesh_t::boundingBox() { double *result = new double[10]; double xmin = +9e9; double xmax = -9e9; double ymin = +9e9; double ymax = -9e9; double zmin = +9e9; double zmax = -9e9; for(int i=0; i < this->nodes; i++) { node_t *node = &this->node[i]; if(node->getX(0) > xmax) xmax = node->getX(0); if(node->getX(0) < xmin) xmin = node->getX(0); if(node->getX(1) > ymax) ymax = node->getX(1); if(node->getX(1) < ymin) ymin = node->getX(1); if(node->getX(2) > zmax) zmax = node->getX(2); if(node->getX(2) < zmin) zmin = node->getX(2); } double xmid = (xmin + xmax)/2.0; double ymid = (ymin + ymax)/2.0; double zmid = (zmin + zmax)/2.0; double xlen = (xmax - xmin)/2.0; double ylen = (ymax - ymin)/2.0; double zlen = (zmax - zmin)/2.0; double s = xlen; if(ylen > s) s = ylen; if(zlen > s) s = zlen; s *= 1.1; bool sx = xmin==xmax; bool sy = ymin==ymax; bool sz = zmin==zmax; this->cdim = 3; if((sz && sy) || (sz && sx) || (sx && sy)) this->cdim = 1; else if(sz || sy || sx) this->cdim = 2; result[0] = xmin; result[1] = xmax; result[2] = ymin; result[3] = ymax; result[4] = zmin; result[5] = zmax; result[6] = xmid; result[7] = ymid; result[8] = zmid; result[9] = s; return result; } void mesh_t::setCdim(int n) { this->cdim = n; } int mesh_t::getCdim() const { return this->cdim; } void mesh_t::setDim(int n) { this->dim = n; } int mesh_t::getDim() const { return this->dim; } void mesh_t::setNodes(int n) { this->nodes = n; } int mesh_t::getNodes() const { return this->nodes; } void mesh_t::setPoints(int n) { this->points = n; } int mesh_t::getPoints() const { return this->points; } void mesh_t::setEdges(int n) { this->edges = n; } int mesh_t::getEdges() const { return this->edges; } void mesh_t::setSurfaces(int n) { this->surfaces = n; } int mesh_t::getSurfaces() const { return this->surfaces; } void mesh_t::setElements(int n) { this->elements = n; } int mesh_t::getElements() const { return this->elements; } node_t* mesh_t::getNode(int n) { return &this->node[n]; } void mesh_t::setNodeArray(node_t* n) { this->node = n; } void mesh_t::newNodeArray(int n) { this->node = new node_t[n]; } void mesh_t::deleteNodeArray() { delete [] this->node; } point_t* mesh_t::getPoint(int n) { return &this->point[n]; } void mesh_t::setPointArray(point_t* p) { this->point = p; } void mesh_t::newPointArray(int n) { this->point = new point_t[n]; } void mesh_t::deletePointArray() { delete [] this->point; } edge_t* mesh_t::getEdge(int n) { return &this->edge[n]; } void mesh_t::setEdgeArray(edge_t* e) { this->edge = e; } void mesh_t::newEdgeArray(int n) { this->edge = new edge_t[n]; } void mesh_t::deleteEdgeArray() { delete [] this->edge; } surface_t* mesh_t::getSurface(int n) { return &this->surface[n]; } void mesh_t::setSurfaceArray(surface_t* s) { this->surface = s; } void mesh_t::newSurfaceArray(int n) { this->surface = new surface_t[n]; } void mesh_t::deleteSurfaceArray() { delete [] this->surface; } element_t* mesh_t::getElement(int n) { return &this->element[n]; } void mesh_t::setElementArray(element_t* e) { this->element = e; } void mesh_t::newElementArray(int n) { this->element = new element_t[n]; } void mesh_t::deleteElementArray() { delete [] this->element; }
19.381195
79
0.548757
Poofee
72b9c08c09273f6a0f778472a98b538844f01dc3
4,421
cpp
C++
src/devices/bus/hp80_io/82900.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/bus/hp80_io/82900.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/bus/hp80_io/82900.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders: F. Ulivi /********************************************************************* 82900.cpp 82900 module (CP/M auxiliary processor) *********************************************************************/ #include "emu.h" #include "82900.h" // Debugging #define VERBOSE 0 #include "logmacro.h" // Bit manipulation namespace { template<typename T> constexpr T BIT_MASK(unsigned n) { return (T)1U << n; } template<typename T> void BIT_SET(T& w , unsigned n) { w |= BIT_MASK<T>(n); } } hp82900_io_card_device::hp82900_io_card_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig , HP82900_IO_CARD , tag , owner , clock), device_hp80_io_interface(mconfig, *this), m_cpu(*this , "cpu"), m_translator(*this , "xlator"), m_rom(*this , "rom") { } hp82900_io_card_device::~hp82900_io_card_device() { } void hp82900_io_card_device::install_read_write_handlers(address_space& space , uint16_t base_addr) { space.install_readwrite_handler(base_addr, base_addr + 1, read8sm_delegate(*m_translator, FUNC(hp_1mb5_device::cpu_r)), write8sm_delegate(*m_translator, FUNC(hp_1mb5_device::cpu_w))); } void hp82900_io_card_device::inten() { m_translator->inten(); } void hp82900_io_card_device::clear_service() { m_translator->clear_service(); } static INPUT_PORTS_START(hp82900_port) PORT_START("SC") PORT_CONFNAME(0xf , 3 , "Select Code") INPUT_PORTS_END ioport_constructor hp82900_io_card_device::device_input_ports() const { return INPUT_PORTS_NAME(hp82900_port); } void hp82900_io_card_device::device_start() { m_ram = std::make_unique<uint8_t[]>(65536); save_pointer(NAME(m_ram) , 65536); save_item(NAME(m_rom_enabled)); save_item(NAME(m_addr_latch)); } void hp82900_io_card_device::device_reset() { m_rom_enabled = true; } ROM_START(hp82900) ROM_REGION(0x800 , "rom" , 0) ROM_LOAD("82900-60002.bin" , 0 , 0x800 , CRC(48745bbb) SHA1(fb4427f729eedba5ac01809718b841c7bdd85e1f)) ROM_END WRITE_LINE_MEMBER(hp82900_io_card_device::reset_w) { LOG("reset_w %d\n" , state); m_cpu->set_input_line(INPUT_LINE_RESET , state); if (state) { // When reset is asserted, clear state device_reset(); } } uint8_t hp82900_io_card_device::cpu_mem_r(offs_t offset) { if (m_rom_enabled) { return m_rom[ offset & 0x7ff ]; } else { return m_ram[ offset ]; } } void hp82900_io_card_device::cpu_mem_w(offs_t offset, uint8_t data) { m_ram[ offset ] = data; } uint8_t hp82900_io_card_device::cpu_io_r(offs_t offset) { m_rom_enabled = false; uint8_t res; if (BIT(offset , 6) && (m_addr_latch & 0x82) == 0) { res = m_translator->uc_r(m_addr_latch & 1); } else { res = ~0; } return res; } void hp82900_io_card_device::cpu_io_w(offs_t offset, uint8_t data) { m_rom_enabled = false; if (BIT(offset , 6) && (m_addr_latch & 0x82) == 0) { m_translator->uc_w(m_addr_latch & 1 , data); } else if (BIT(offset , 7)) { m_addr_latch = data; } } void hp82900_io_card_device::cpu_mem_map(address_map &map) { map.unmap_value_high(); map(0x0000 , 0xffff).rw(FUNC(hp82900_io_card_device::cpu_mem_r) , FUNC(hp82900_io_card_device::cpu_mem_w)); } void hp82900_io_card_device::cpu_io_map(address_map &map) { map.unmap_value_high(); map.global_mask(0xff); map(0x00 , 0xff).rw(FUNC(hp82900_io_card_device::cpu_io_r) , FUNC(hp82900_io_card_device::cpu_io_w)); } void hp82900_io_card_device::z80_m1_w(uint8_t data) { // 1 wait state on each M1 cycle m_cpu->adjust_icount(-1); } const tiny_rom_entry *hp82900_io_card_device::device_rom_region() const { return ROM_NAME(hp82900); } void hp82900_io_card_device::device_add_mconfig(machine_config &config) { Z80(config , m_cpu , XTAL(8'000'000) / 2); m_cpu->set_addrmap(AS_PROGRAM , &hp82900_io_card_device::cpu_mem_map); m_cpu->set_addrmap(AS_IO , &hp82900_io_card_device::cpu_io_map); m_cpu->refresh_cb().set(FUNC(hp82900_io_card_device::z80_m1_w)); HP_1MB5(config, m_translator, 0); m_translator->irl_handler().set(FUNC(hp82900_io_card_device::irl_w)); m_translator->halt_handler().set(FUNC(hp82900_io_card_device::halt_w)); m_translator->reset_handler().set(FUNC(hp82900_io_card_device::reset_w)); m_translator->int_handler().set([this](int state) { m_cpu->set_input_line(INPUT_LINE_IRQ0 , !state); }); } // device type definition DEFINE_DEVICE_TYPE(HP82900_IO_CARD, hp82900_io_card_device, "hp82900", "HP82900 card")
25.262857
184
0.721104
Robbbert
72ba34c8d2c1cfa6e90221f37fb0f58e013976b9
1,748
hpp
C++
include/lol/def/GameflowLcdsGameDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/GameflowLcdsGameDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/GameflowLcdsGameDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct GameflowLcdsGameDTO { uint64_t id; int32_t mapId; std::string gameState; std::string queueTypeName; std::string gameMode; int32_t gameTypeConfigId; int32_t maxNumPlayers; std::string gameType; int32_t spectatorDelay; std::vector<json> teamOne; std::vector<json> teamTwo; std::vector<json> playerChampionSelections; }; inline void to_json(json& j, const GameflowLcdsGameDTO& v) { j["id"] = v.id; j["mapId"] = v.mapId; j["gameState"] = v.gameState; j["queueTypeName"] = v.queueTypeName; j["gameMode"] = v.gameMode; j["gameTypeConfigId"] = v.gameTypeConfigId; j["maxNumPlayers"] = v.maxNumPlayers; j["gameType"] = v.gameType; j["spectatorDelay"] = v.spectatorDelay; j["teamOne"] = v.teamOne; j["teamTwo"] = v.teamTwo; j["playerChampionSelections"] = v.playerChampionSelections; } inline void from_json(const json& j, GameflowLcdsGameDTO& v) { v.id = j.at("id").get<uint64_t>(); v.mapId = j.at("mapId").get<int32_t>(); v.gameState = j.at("gameState").get<std::string>(); v.queueTypeName = j.at("queueTypeName").get<std::string>(); v.gameMode = j.at("gameMode").get<std::string>(); v.gameTypeConfigId = j.at("gameTypeConfigId").get<int32_t>(); v.maxNumPlayers = j.at("maxNumPlayers").get<int32_t>(); v.gameType = j.at("gameType").get<std::string>(); v.spectatorDelay = j.at("spectatorDelay").get<int32_t>(); v.teamOne = j.at("teamOne").get<std::vector<json>>(); v.teamTwo = j.at("teamTwo").get<std::vector<json>>(); v.playerChampionSelections = j.at("playerChampionSelections").get<std::vector<json>>(); } }
38
92
0.641304
Maufeat
72ba6b923add5ea293acade1048ef638aaf347ee
378
cpp
C++
SJTUOJ/1359.cpp
Victrid/Atlas
da25d50424790e571f29b66fc815245c1093798c
[ "MIT" ]
1
2020-01-19T16:00:07.000Z
2020-01-19T16:00:07.000Z
SJTUOJ/1359.cpp
Victrid/Atlas
da25d50424790e571f29b66fc815245c1093798c
[ "MIT" ]
null
null
null
SJTUOJ/1359.cpp
Victrid/Atlas
da25d50424790e571f29b66fc815245c1093798c
[ "MIT" ]
null
null
null
#include <cstring> #include <iostream> using namespace std; int pharse(char chz) { if (chz == ' ') return 0; return chz - 'A' >= 26 ? chz - 'a' + 27 : chz - 'A' + 1; } int main() { string chs; int ans = 0; getline(cin, chs); for (int i = 0; chs[i] != '\0'; i++) { ans += (i + 1) * pharse(chs[i]); } cout << ans; return 0; }
18
60
0.465608
Victrid
72bb0a2fd8801002cb62f7ce5aefc2cdd705d356
71,100
cpp
C++
Source/source/mob_script_action.cpp
shantonusen/Pikifen
5a90f804fdf78bfd198eb838200a7aaf6d7ea842
[ "MIT" ]
null
null
null
Source/source/mob_script_action.cpp
shantonusen/Pikifen
5a90f804fdf78bfd198eb838200a7aaf6d7ea842
[ "MIT" ]
null
null
null
Source/source/mob_script_action.cpp
shantonusen/Pikifen
5a90f804fdf78bfd198eb838200a7aaf6d7ea842
[ "MIT" ]
null
null
null
/* * Copyright (c) Andre 'Espyo' Silva 2013. * The following source file belongs to the open-source project Pikifen. * Please read the included README and LICENSE files for more information. * Pikmin is copyright (c) Nintendo. * * === FILE DESCRIPTION === * Mob script action classes and * related functions. */ #include <algorithm> #include "mob_script_action.h" #include "functions.h" #include "game.h" #include "mobs/group_task.h" #include "mobs/scale.h" #include "mobs/tool.h" #include "utils/string_utils.h" using std::set; /* ---------------------------------------------------------------------------- * Creates a new, empty mob action. */ mob_action::mob_action() : type(MOB_ACTION_UNKNOWN), code(nullptr), extra_load_logic(nullptr) { } /* ---------------------------------------------------------------------------- * Creates a new, empty mob action call, of a certain type. * type: * Type of mob action call. */ mob_action_call::mob_action_call(MOB_ACTION_TYPES type) : action(nullptr), code(nullptr), parent_event(MOB_EV_UNKNOWN), mt(nullptr) { for(size_t a = 0; a < game.mob_actions.size(); ++a) { if(game.mob_actions[a].type == type) { action = &(game.mob_actions[a]); break; } } } /* ---------------------------------------------------------------------------- * Creates a new mob action call that is meant to run custom code. * code: * The function to run. */ mob_action_call::mob_action_call(custom_action_code code): action(nullptr), code(code), parent_event(MOB_EV_UNKNOWN), mt(nullptr) { for(size_t a = 0; a < game.mob_actions.size(); ++a) { if(game.mob_actions[a].type == MOB_ACTION_UNKNOWN) { action = &(game.mob_actions[a]); break; } } } /* ---------------------------------------------------------------------------- * Loads a mob action call from a data node. * dn: * The data node. * mt: * Mob type this action's fsm belongs to. */ bool mob_action_call::load_from_data_node(data_node* dn, mob_type* mt) { action = NULL; this->mt = mt; //First, get the name and arguments. vector<string> words = split(dn->name); for(size_t w = 0; w < words.size(); ++w) { words[w] = trim_spaces(words[w]); } string name = words[0]; if(!words.empty()) { words.erase(words.begin()); } //Find the corresponding action. for(size_t a = 0; a < game.mob_actions.size(); ++a) { if(game.mob_actions[a].type == MOB_ACTION_UNKNOWN) continue; if(game.mob_actions[a].name == name) { action = &(game.mob_actions[a]); } } if(!action) { log_error("Unknown script action name \"" + name + "\"!", dn); return false; } //Check if there are too many or too few arguments. size_t mandatory_parameters = action->parameters.size(); if(mandatory_parameters > 0) { if(action->parameters[mandatory_parameters - 1].is_extras) { mandatory_parameters--; } } if(words.size() < mandatory_parameters) { log_error( "The \"" + action->name + "\" action needs " + i2s(mandatory_parameters) + " arguments, but this call only " "has " + i2s(words.size()) + "! You're missing the \"" + action->parameters[words.size()].name + "\" parameter.", dn ); return false; } if(mandatory_parameters == action->parameters.size()) { if(words.size() > action->parameters.size()) { log_error( "The \"" + action->name + "\" action only needs " + i2s(action->parameters.size()) + " arguments, but this call " "has " + i2s(words.size()) + "!", dn ); return false; } } //Fetch the arguments, and check if any of them are not allowed. for(size_t w = 0; w < words.size(); ++w) { size_t param_nr = std::min(w, action->parameters.size() - 1); bool is_var = (words[w][0] == '$' && words[w].size() > 1); if(is_var && words[w].size() >= 2 && words[w][1] == '$') { //Two '$' in a row means it's meant to use a literal '$'. is_var = false; words[w].erase(words[w].begin()); } if(is_var) { if(action->parameters[param_nr].force_const) { log_error( "Argument #" + i2s(w) + " (\"" + words[w] + "\") is a " "variable, but the parameter \"" + action->parameters[param_nr].name + "\" can only be " "constant!", dn ); return false; } words[w].erase(words[w].begin()); //Remove the '$'. if(words[w].empty()) { log_error( "Argument #" + i2s(w) + " is trying to use a variable " "with no name!", dn ); return false; } } args.push_back(words[w]); arg_is_var.push_back(is_var); } //If this action needs extra parsing, do it now. if(action->extra_load_logic) { bool success = action->extra_load_logic(*this); if(!custom_error.empty()) { log_error(custom_error, dn); } return success; } return true; } /* ---------------------------------------------------------------------------- * Runs an action. * Return value is only used by the "if" actions, to indicate their * evaluation result. * m: * The mob. * custom_data_1: * Custom argument #1 to pass to the code. * custom_data_2: * Custom argument #2 to pass to the code. */ bool mob_action_call::run( mob* m, void* custom_data_1, void* custom_data_2 ) { //Custom code (i.e. instead of text-based script, use actual C++ code). if(code) { code(m, custom_data_1, custom_data_2); return false; } mob_action_run_data data(m, this); //Fill the arguments. Fetch values from variables if needed. data.args = args; for(size_t a = 0; a < args.size(); ++a) { if(arg_is_var[a]) { data.args[a] = m->vars[args[a]]; } } data.custom_data_1 = custom_data_1; data.custom_data_2 = custom_data_2; action->code(data); return data.return_value; } /* ---------------------------------------------------------------------------- * Loading code for the arachnorb logic plan mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::arachnorb_plan_logic(mob_action_call &call) { if(call.args[0] == "home") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_HOME); } else if(call.args[0] == "forward") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_FORWARD); } else if(call.args[0] == "cw_turn") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_CW_TURN); } else if(call.args[0] == "ccw_turn") { call.args[0] = i2s(MOB_ACTION_ARACHNORB_PLAN_LOGIC_CCW_TURN); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the calculation mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::calculate(mob_action_call &call) { if(call.args[2] == "+") { call.args[2] = i2s(MOB_ACTION_SET_VAR_SUM); } else if(call.args[2] == "-") { call.args[2] = i2s(MOB_ACTION_SET_VAR_SUBTRACT); } else if(call.args[2] == "*") { call.args[2] = i2s(MOB_ACTION_SET_VAR_MULTIPLY); } else if(call.args[2] == "/") { call.args[2] = i2s(MOB_ACTION_SET_VAR_DIVIDE); } else if(call.args[2] == "%") { call.args[2] = i2s(MOB_ACTION_SET_VAR_MODULO); } else { report_enum_error(call, 2); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the focus mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::focus(mob_action_call &call) { if(call.args[0] == "link") { call.args[0] = i2s(MOB_ACTION_FOCUS_LINK); } else if(call.args[0] == "parent") { call.args[0] = i2s(MOB_ACTION_FOCUS_PARENT); } else if(call.args[0] == "trigger") { call.args[0] = i2s(MOB_ACTION_FOCUS_TRIGGER); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the info getting script actions. * call: * Mob action call that called this. */ bool mob_action_loaders::get_info(mob_action_call &call) { if(call.args[1] == "angle") { call.args[1] = i2s(MOB_ACTION_GET_INFO_ANGLE); } else if(call.args[1] == "body_part") { call.args[1] = i2s(MOB_ACTION_GET_INFO_BODY_PART); } else if(call.args[1] == "chomped_pikmin") { call.args[1] = i2s(MOB_ACTION_GET_INFO_CHOMPED_PIKMIN); } else if(call.args[1] == "day_minutes") { call.args[1] = i2s(MOB_ACTION_GET_INFO_DAY_MINUTES); } else if(call.args[1] == "field_pikmin") { call.args[1] = i2s(MOB_ACTION_GET_INFO_FIELD_PIKMIN); } else if(call.args[1] == "focus_distance") { call.args[1] = i2s(MOB_ACTION_GET_INFO_FOCUS_DISTANCE); } else if(call.args[1] == "frame_signal") { call.args[1] = i2s(MOB_ACTION_GET_INFO_FRAME_SIGNAL); } else if(call.args[1] == "group_task_power") { call.args[1] = i2s(MOB_ACTION_GET_INFO_GROUP_TASK_POWER); } else if(call.args[1] == "hazard") { call.args[1] = i2s(MOB_ACTION_GET_INFO_HAZARD); } else if(call.args[1] == "health") { call.args[1] = i2s(MOB_ACTION_GET_INFO_HEALTH); } else if(call.args[1] == "latched_pikmin") { call.args[1] = i2s(MOB_ACTION_GET_INFO_LATCHED_PIKMIN); } else if(call.args[1] == "latched_pikmin_weight") { call.args[1] = i2s(MOB_ACTION_GET_INFO_LATCHED_PIKMIN_WEIGHT); } else if(call.args[1] == "message") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MESSAGE); } else if(call.args[1] == "message_sender") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MESSAGE_SENDER); } else if(call.args[1] == "mob_category") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MOB_CATEGORY); } else if(call.args[1] == "mob_type") { call.args[1] = i2s(MOB_ACTION_GET_INFO_MOB_TYPE); } else if(call.args[1] == "other_body_part") { call.args[1] = i2s(MOB_ACTION_GET_INFO_OTHER_BODY_PART); } else if(call.args[1] == "x") { call.args[1] = i2s(MOB_ACTION_GET_INFO_X); } else if(call.args[1] == "y") { call.args[1] = i2s(MOB_ACTION_GET_INFO_Y); } else if(call.args[1] == "z") { call.args[1] = i2s(MOB_ACTION_GET_INFO_Z); } else if(call.args[1] == "weight") { call.args[1] = i2s(MOB_ACTION_GET_INFO_WEIGHT); } else { report_enum_error(call, 1); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the hold focused mob mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::hold_focus(mob_action_call &call) { size_t p_nr = call.mt->anims.find_body_part(call.args[0]); if(p_nr == INVALID) { call.custom_error = "Unknown body part \"" + call.args[0] + "\"!"; return false; } call.args[0] = i2s(p_nr); return true; } /* ---------------------------------------------------------------------------- * Loading code for the "if" mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::if_function(mob_action_call &call) { if(call.args[1] == "=") { call.args[1] = i2s(MOB_ACTION_IF_OP_EQUAL); } else if(call.args[1] == "!=") { call.args[1] = i2s(MOB_ACTION_IF_OP_NOT); } else if(call.args[1] == "<") { call.args[1] = i2s(MOB_ACTION_IF_OP_LESS); } else if(call.args[1] == ">") { call.args[1] = i2s(MOB_ACTION_IF_OP_MORE); } else if(call.args[1] == "<=") { call.args[1] = i2s(MOB_ACTION_IF_OP_LESS_E); } else if(call.args[1] == ">=") { call.args[1] = i2s(MOB_ACTION_IF_OP_MORE_E); } else { report_enum_error(call, 1); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the move to target mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::move_to_target(mob_action_call &call) { if(call.args[0] == "arachnorb_foot_logic") { call.args[0] = i2s(MOB_ACTION_MOVE_ARACHNORB_FOOT_LOGIC); } else if(call.args[0] == "away_from_focused_mob") { call.args[0] = i2s(MOB_ACTION_MOVE_AWAY_FROM_FOCUSED_MOB); } else if(call.args[0] == "focused_mob") { call.args[0] = i2s(MOB_ACTION_MOVE_FOCUSED_MOB); } else if(call.args[0] == "focused_mob_position") { call.args[0] = i2s(MOB_ACTION_MOVE_FOCUSED_MOB_POS); } else if(call.args[0] == "home") { call.args[0] = i2s(MOB_ACTION_MOVE_HOME); } else if(call.args[0] == "linked_mob_average") { call.args[0] = i2s(MOB_ACTION_MOVE_LINKED_MOB_AVERAGE); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the status reception mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::receive_status(mob_action_call &call) { if(game.status_types.find(call.args[0]) == game.status_types.end()) { call.custom_error = "Unknown status effect \"" + call.args[0] + "\"!"; return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the status removal mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::remove_status(mob_action_call &call) { if(game.status_types.find(call.args[0]) == game.status_types.end()) { call.custom_error = "Unknown status effect \"" + call.args[0] + "\"!"; return false; } return true; } /* ---------------------------------------------------------------------------- * Reports an error of an unknown enum value. * call: * Mob action call that called this. * arg_nr: * Index number of the argument that is an enum. */ void mob_action_loaders::report_enum_error( mob_action_call &call, const size_t arg_nr ) { size_t param_nr = std::min(arg_nr, call.action->parameters.size() - 1); call.custom_error = "The parameter \"" + call.action->parameters[param_nr].name + "\" " "does not know what the value \"" + call.args[arg_nr] + "\" means!"; } /* ---------------------------------------------------------------------------- * Loading code for the animation setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_animation(mob_action_call &call) { size_t a_pos = call.mt->anims.find_animation(call.args[0]); if(a_pos == INVALID) { call.custom_error = "Unknown animation \"" + call.args[0] + "\"!"; return false; } call.args[0] = i2s(a_pos); for(size_t a = 1; a < call.args.size(); ++a) { if(call.args[a] == "no_restart") { call.args[a] = i2s(MOB_ACTION_SET_ANIMATION_NO_RESTART); } else { call.args[a] = "0"; } } return true; } /* ---------------------------------------------------------------------------- * Loading code for the far reach setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_far_reach(mob_action_call &call) { for(size_t r = 0; r < call.mt->reaches.size(); ++r) { if(call.mt->reaches[r].name == call.args[0]) { call.args[0] = i2s(r); return true; } } call.custom_error = "Unknown reach \"" + call.args[0] + "\"!"; return false; } /* ---------------------------------------------------------------------------- * Loading code for the holdable setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_holdable(mob_action_call &call) { for(size_t a = 0; a < call.args.size(); ++a) { if(call.args[a] == "pikmin") { call.args[a] = i2s(HOLDABLE_BY_PIKMIN); } else if(call.args[a] == "enemies") { call.args[a] = i2s(HOLDABLE_BY_ENEMIES); } else { report_enum_error(call, a); return false; } } return true; } /* ---------------------------------------------------------------------------- * Loading code for the near reach setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_near_reach(mob_action_call &call) { for(size_t r = 0; r < call.mt->reaches.size(); ++r) { if(call.mt->reaches[r].name == call.args[0]) { call.args[0] = i2s(r); return true; } } call.custom_error = "Unknown reach \"" + call.args[0] + "\"!"; return false; } /* ---------------------------------------------------------------------------- * Loading code for the team setting mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::set_team(mob_action_call &call) { size_t team_nr = string_to_team_nr(call.args[0]); if(team_nr == INVALID) { report_enum_error(call, 0); return false; } call.args[0] = i2s(team_nr); return true; } /* ---------------------------------------------------------------------------- * Loading code for the spawning mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::spawn(mob_action_call &call) { for(size_t s = 0; s < call.mt->spawns.size(); ++s) { if(call.mt->spawns[s].name == call.args[0]) { call.args[0] = i2s(s); return true; } } call.custom_error = "Unknown spawn info block \"" + call.args[0] + "\"!"; return false; } /* ---------------------------------------------------------------------------- * Loading code for the z stabilization mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::stabilize_z(mob_action_call &call) { if(call.args[0] == "lowest") { call.args[0] = i2s(MOB_ACTION_STABILIZE_Z_LOWEST); } else if(call.args[0] == "highest") { call.args[0] = i2s(MOB_ACTION_STABILIZE_Z_HIGHEST); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the chomping start mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::start_chomping(mob_action_call &call) { for(size_t s = 1; s < call.args.size(); ++s) { size_t p_nr = call.mt->anims.find_body_part(call.args[s]); if(p_nr == INVALID) { call.custom_error = "Unknown body part \"" + call.args[s] + "\"!"; return false; } call.args[s] = i2s(p_nr); } return true; } /* ---------------------------------------------------------------------------- * Loading code for the particle start mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::start_particles(mob_action_call &call) { if( game.custom_particle_generators.find(call.args[0]) == game.custom_particle_generators.end() ) { call.custom_error = "Unknown particle generator \"" + call.args[0] + "\"!"; return false; } return true; } /* ---------------------------------------------------------------------------- * Loading code for the turn to target mob script action. * call: * Mob action call that called this. */ bool mob_action_loaders::turn_to_target(mob_action_call &call) { if(call.args[0] == "arachnorb_head_logic") { call.args[0] = i2s(MOB_ACTION_TURN_ARACHNORB_HEAD_LOGIC); } else if(call.args[0] == "focused_mob") { call.args[0] = i2s(MOB_ACTION_TURN_FOCUSED_MOB); } else if(call.args[0] == "home") { call.args[0] = i2s(MOB_ACTION_TURN_HOME); } else { report_enum_error(call, 0); return false; } return true; } /* ---------------------------------------------------------------------------- * Creates a new mob action parameter struct. * name: * Name of the parameter. * type: * Type of parameter. * force_const: * If true, this must be a constant value. If false, it can also be a var. * is_extras: * If true, this is an array of them (minimum amount 0). */ mob_action_param::mob_action_param( const string &name, const MOB_ACTION_PARAM_TYPE type, const bool force_const, const bool is_extras ): name(name), type(type), force_const(force_const), is_extras(is_extras) { } /* ---------------------------------------------------------------------------- * Creates a new mob action run data struct. * m: * The mob responsible. * call: * Mob action call that called this. */ mob_action_run_data::mob_action_run_data(mob* m, mob_action_call* call) : m(m), call(call), custom_data_1(nullptr), custom_data_2(nullptr), return_value(false) { } /* ---------------------------------------------------------------------------- * Code for the health addition mob script action. * data: * Data about the action call. */ void mob_action_runners::add_health(mob_action_run_data &data) { data.m->set_health(true, false, s2f(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the arachnorb logic plan mob script action. * data: * Data about the action call. */ void mob_action_runners::arachnorb_plan_logic(mob_action_run_data &data) { data.m->arachnorb_plan_logic(s2i(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the calculation mob script action. * data: * Data about the action call. */ void mob_action_runners::calculate(mob_action_run_data &data) { float lhs = s2f(data.args[1]); size_t op = s2i(data.args[2]); float rhs = s2f(data.args[3]); float result = 0; switch(op) { case MOB_ACTION_SET_VAR_SUM: { result = lhs + rhs; break; } case MOB_ACTION_SET_VAR_SUBTRACT: { result = lhs - rhs; break; } case MOB_ACTION_SET_VAR_MULTIPLY: { result = lhs * rhs; break; } case MOB_ACTION_SET_VAR_DIVIDE: { if(rhs == 0) { result = 0; } else { result = lhs / rhs; } break; } case MOB_ACTION_SET_VAR_MODULO: { if(rhs == 0) { result = 0; } else { result = fmod(lhs, rhs); } break; } } data.m->vars[data.args[0]] = f2s(result); } /* ---------------------------------------------------------------------------- * Code for the deletion mob script action. * data: * Data about the action call. */ void mob_action_runners::delete_function(mob_action_run_data &data) { data.m->to_delete = true; } /* ---------------------------------------------------------------------------- * Code for the liquid draining mob script action. * data: * Data about the action call. */ void mob_action_runners::drain_liquid(mob_action_run_data &data) { sector* s_ptr = get_sector(data.m->pos, NULL, true); if(!s_ptr) return; vector<sector*> sectors_to_drain; s_ptr->get_neighbor_sectors_conditionally( [] (sector * s) -> bool { for(size_t h = 0; h < s->hazards.size(); ++h) { if(s->hazards[h]->associated_liquid) { return true; } } if(s->type == SECTOR_TYPE_BRIDGE) { return true; } if(s->type == SECTOR_TYPE_BRIDGE_RAIL) { return true; } return false; }, sectors_to_drain ); for(size_t s = 0; s < sectors_to_drain.size(); ++s) { sectors_to_drain[s]->draining_liquid = true; sectors_to_drain[s]->liquid_drain_left = LIQUID_DRAIN_DURATION; } } /* ---------------------------------------------------------------------------- * Code for the death finish mob script action. * data: * Data about the action call. */ void mob_action_runners::finish_dying(mob_action_run_data &data) { data.m->finish_dying(); } /* ---------------------------------------------------------------------------- * Code for the focus mob script action. * data: * Data about the action call. */ void mob_action_runners::focus(mob_action_run_data &data) { size_t t = s2i(data.args[0]); switch(t) { case MOB_ACTION_FOCUS_LINK: { if(!data.m->links.empty()) { data.m->focus_on_mob(data.m->links[0]); } break; } case MOB_ACTION_FOCUS_PARENT: { if(data.m->parent) { data.m->focus_on_mob(data.m->parent->m); } break; } case MOB_ACTION_FOCUS_TRIGGER: { if( data.call->parent_event == MOB_EV_OBJECT_IN_REACH || data.call->parent_event == MOB_EV_OPPONENT_IN_REACH || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED || data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT ) { data.m->focus_on_mob((mob*) (data.custom_data_1)); } else if( data.call->parent_event == MOB_EV_RECEIVE_MESSAGE ) { data.m->focus_on_mob((mob*) (data.custom_data_2)); } break; } } } /* ---------------------------------------------------------------------------- * Code for the follow path randomly mob script action. * data: * Data about the action call. */ void mob_action_runners::follow_path_randomly(mob_action_run_data &data) { string label; if(data.args.size() >= 1) { label = data.args[0]; } //We need to decide what the final stop is going to be. //First, get all eligible stops. vector<path_stop*> choices; if(label.empty()) { //If there's no label, then any stop is eligible. choices.insert( choices.end(), game.cur_area_data.path_stops.begin(), game.cur_area_data.path_stops.end() ); } else { //If there's a label, it'd be nice to only pick stops that have SOME //connection to the label. Checking the stop's outgoing links is //the best we can do, as to not overengineer or hurt performance. for(size_t s = 0; s < game.cur_area_data.path_stops.size(); ++s) { path_stop* s_ptr = game.cur_area_data.path_stops[s]; for(size_t l = 0; l < s_ptr->links.size(); ++l) { if(s_ptr->links[l]->label == label) { choices.push_back(s_ptr); break; } } } } //Pick a stop from the choices at random, but make sure we don't //pick a stop that the mob is practically on already. path_stop* final_stop = NULL; size_t tries = 0; if(!choices.empty()) { while(!final_stop && tries < 5) { size_t c = randomi(0, choices.size() - 1); if( dist(choices[c]->pos, data.m->pos) > chase_info_struct::DEF_TARGET_DISTANCE ) { final_stop = choices[c]; break; } tries++; } } //Go! Though if something went wrong, make it follow a path to nowhere, //so it can emit the MOB_EV_REACHED_DESTINATION event, and hopefully //make it clear that there was an error. data.m->follow_path( final_stop ? final_stop->pos : data.m->pos, true, data.m->get_base_speed(), chase_info_struct::DEF_TARGET_DISTANCE, true, label ); } /* ---------------------------------------------------------------------------- * Code for the follow path to absolute mob script action. * data: * Data about the action call. */ void mob_action_runners::follow_path_to_absolute(mob_action_run_data &data) { float x = s2f(data.args[0]); float y = s2f(data.args[1]); string label; if(data.args.size() >= 3) { label = data.args[2]; } data.m->follow_path( point(x, y), true, data.m->get_base_speed(), chase_info_struct::DEF_TARGET_DISTANCE, true, label ); } /* ---------------------------------------------------------------------------- * Code for the angle obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_angle(mob_action_run_data &data) { float center_x = s2f(data.args[1]); float center_y = s2f(data.args[2]); float focus_x = s2f(data.args[3]); float focus_y = s2f(data.args[4]); float angle = get_angle(point(center_x, center_y), point(focus_x, focus_y)); angle = rad_to_deg(angle); data.m->vars[data.args[0]] = f2s(angle); } /* ---------------------------------------------------------------------------- * Code for the mob script action for getting chomped. * data: * Data about the action call. */ void mob_action_runners::get_chomped(mob_action_run_data &data) { if(data.call->parent_event == MOB_EV_HITBOX_TOUCH_EAT) { ((mob*) (data.custom_data_1))->chomp( data.m, (hitbox*) (data.custom_data_2) ); } } /* ---------------------------------------------------------------------------- * Code for the coordinate from angle obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_coordinates_from_angle(mob_action_run_data &data) { float angle = s2f(data.args[2]); angle = deg_to_rad(angle); float magnitude = s2f(data.args[3]); point p = angle_to_coordinates(angle, magnitude); data.m->vars[data.args[0]] = f2s(p.x); data.m->vars[data.args[1]] = f2s(p.y); } /* ---------------------------------------------------------------------------- * Code for the distance obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_distance(mob_action_run_data &data) { float center_x = s2f(data.args[1]); float center_y = s2f(data.args[2]); float focus_x = s2f(data.args[3]); float focus_y = s2f(data.args[4]); data.m->vars[data.args[0]] = f2s( dist(point(center_x, center_y), point(focus_x, focus_y)).to_float() ); } /* ---------------------------------------------------------------------------- * Code for the floor Z obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_floor_z(mob_action_run_data &data) { float x = s2f(data.args[1]); float y = s2f(data.args[2]); sector* s = get_sector(point(x, y), NULL, true); data.m->vars[data.args[0]] = f2s(s ? s->z : 0); } /* ---------------------------------------------------------------------------- * Code for the info obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_focus_info(mob_action_run_data &data) { get_info_runner(data, data.m->focused_mob); } /* ---------------------------------------------------------------------------- * Code for the focused mob var getting script action. * data: * Data about the action call. */ void mob_action_runners::get_focus_var(mob_action_run_data &data) { if(!data.m->focused_mob) return; data.m->vars[data.args[0]] = data.m->focused_mob->vars[data.args[1]]; } /* ---------------------------------------------------------------------------- * Code for the info obtaining mob script action. * data: * Data about the action call. */ void mob_action_runners::get_info(mob_action_run_data &data) { get_info_runner(data, data.m); } /* ---------------------------------------------------------------------------- * Code for the decimal number randomization mob script action. * data: * Data about the action call. */ void mob_action_runners::get_random_decimal(mob_action_run_data &data) { data.m->vars[data.args[0]] = f2s(randomf(s2f(data.args[1]), s2f(data.args[2]))); } /* ---------------------------------------------------------------------------- * Code for the integer number randomization mob script action. * data: * Data about the action call. */ void mob_action_runners::get_random_int(mob_action_run_data &data) { data.m->vars[data.args[0]] = i2s(randomi(s2i(data.args[1]), s2i(data.args[2]))); } /* ---------------------------------------------------------------------------- * Code for the hold focused mob mob script action. * data: * Data about the action call. */ void mob_action_runners::hold_focus(mob_action_run_data &data) { if(data.m->focused_mob) { data.m->hold( data.m->focused_mob, s2i(data.args[0]), 0.0f, 0.0f, false, HOLD_ROTATION_METHOD_COPY_HOLDER ); } } /* ---------------------------------------------------------------------------- * Code for the "if" mob script action. * data: * Data about the action call. */ void mob_action_runners::if_function(mob_action_run_data &data) { string lhs = data.args[0]; size_t op = s2i(data.args[1]); string rhs = vector_tail_to_string(data.args, 2); switch(op) { case MOB_ACTION_IF_OP_EQUAL: { if(is_number(lhs)) { data.return_value = (s2f(lhs) == s2f(rhs)); } else { data.return_value = (lhs == rhs); } break; } case MOB_ACTION_IF_OP_NOT: { if(is_number(lhs)) { data.return_value = (s2f(lhs) != s2f(rhs)); } else { data.return_value = (lhs != rhs); } break; } case MOB_ACTION_IF_OP_LESS: { data.return_value = (s2f(lhs) < s2f(rhs)); break; } case MOB_ACTION_IF_OP_MORE: { data.return_value = (s2f(lhs) > s2f(rhs)); break; } case MOB_ACTION_IF_OP_LESS_E: { data.return_value = (s2f(lhs) <= s2f(rhs)); break; } case MOB_ACTION_IF_OP_MORE_E: { data.return_value = (s2f(lhs) >= s2f(rhs)); break; } } } /* ---------------------------------------------------------------------------- * Code for the link with focus mob script action. * data: * Data about the action call. */ void mob_action_runners::link_with_focus(mob_action_run_data &data) { if(!data.m->focused_mob) { return; } for(size_t l = 0; l < data.m->links.size(); ++l) { if(data.m->links[l] == data.m->focused_mob) { //Already linked. return; } } data.m->links.push_back(data.m->focused_mob); } /* ---------------------------------------------------------------------------- * Code for the load focused mob memory mob script action. * data: * Data about the action call. */ void mob_action_runners::load_focus_memory(mob_action_run_data &data) { if(data.m->focused_mob_memory.empty()) { return; } data.m->focus_on_mob(data.m->focused_mob_memory[s2i(data.args[0])]); } /* ---------------------------------------------------------------------------- * Code for the move to absolute coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::move_to_absolute(mob_action_run_data &data) { float x = s2f(data.args[0]); float y = s2f(data.args[1]); float z = data.args.size() > 2 ? s2f(data.args[2]) : data.m->z; data.m->chase(point(x, y), z); } /* ---------------------------------------------------------------------------- * Code for the move to relative coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::move_to_relative(mob_action_run_data &data) { float x = s2f(data.args[0]); float y = s2f(data.args[1]); float z = (data.args.size() > 2 ? s2f(data.args[2]) : 0); point p = rotate_point(point(x, y), data.m->angle); data.m->chase(data.m->pos + p, data.m->z + z); } /* ---------------------------------------------------------------------------- * Code for the move to target mob script action. * data: * Data about the action call. */ void mob_action_runners::move_to_target(mob_action_run_data &data) { size_t t = s2i(data.args[0]); switch(t) { case MOB_ACTION_MOVE_AWAY_FROM_FOCUSED_MOB: { if(data.m->focused_mob) { float a = get_angle(data.m->pos, data.m->focused_mob->pos); point offset = point(2000, 0); offset = rotate_point(offset, a + TAU / 2.0); data.m->chase(data.m->pos + offset, data.m->z); } else { data.m->stop_chasing(); } break; } case MOB_ACTION_MOVE_FOCUSED_MOB: { if(data.m->focused_mob) { data.m->chase(&data.m->focused_mob->pos, &data.m->focused_mob->z); } else { data.m->stop_chasing(); } break; } case MOB_ACTION_MOVE_FOCUSED_MOB_POS: { if(data.m->focused_mob) { data.m->chase(data.m->focused_mob->pos, data.m->focused_mob->z); } else { data.m->stop_chasing(); } break; } case MOB_ACTION_MOVE_HOME: { data.m->chase(data.m->home, data.m->z); break; } case MOB_ACTION_MOVE_ARACHNORB_FOOT_LOGIC: { data.m->arachnorb_foot_move_logic(); break; } case MOB_ACTION_MOVE_LINKED_MOB_AVERAGE: { if(data.m->links.empty()) { return; } point des; for(size_t l = 0; l < data.m->links.size(); ++l) { des += data.m->links[l]->pos; } des = des / data.m->links.size(); data.m->chase(des, data.m->z); break; } } } /* ---------------------------------------------------------------------------- * Code for the release order mob script action. * data: * Data about the action call. */ void mob_action_runners::order_release(mob_action_run_data &data) { if(data.m->holder.m) { data.m->holder.m->fsm.run_event(MOB_EV_RELEASE_ORDER, NULL, NULL); } } /* ---------------------------------------------------------------------------- * Code for the sound playing mob script action. * data: * Data about the action call. */ void mob_action_runners::play_sound(mob_action_run_data &data) { } /* ---------------------------------------------------------------------------- * Code for the text printing mob script action. * data: * Data about the action call. */ void mob_action_runners::print(mob_action_run_data &data) { string text = vector_tail_to_string(data.args, 0); print_info( "[DEBUG PRINT] " + data.m->type->name + " says:\n" + text, 10.0f ); } /* ---------------------------------------------------------------------------- * Code for the status reception mob script action. * data: * Data about the action call. */ void mob_action_runners::receive_status(mob_action_run_data &data) { data.m->apply_status_effect(game.status_types[data.args[0]], false); } /* ---------------------------------------------------------------------------- * Code for the release mob script action. * data: * Data about the action call. */ void mob_action_runners::release(mob_action_run_data &data) { data.m->release_chomped_pikmin(); } /* ---------------------------------------------------------------------------- * Code for the release stored mobs mob script action. * data: * Data about the action call. */ void mob_action_runners::release_stored_mobs(mob_action_run_data &data) { for(size_t m = 0; m < game.states.gameplay->mobs.all.size(); ++m) { mob* m_ptr = game.states.gameplay->mobs.all[m]; if(m_ptr->stored_inside_another == data.m) { data.m->release(m_ptr); m_ptr->stored_inside_another = NULL; m_ptr->time_alive = 0.0f; } } } /* ---------------------------------------------------------------------------- * Code for the status removal mob script action. * data: * Data about the action call. */ void mob_action_runners::remove_status(mob_action_run_data &data) { for(size_t s = 0; s < data.m->statuses.size(); ++s) { if(data.m->statuses[s].type->name == data.args[0]) { data.m->statuses[s].to_delete = true; } } } /* ---------------------------------------------------------------------------- * Code for the save focused mob memory mob script action. * data: * Data about the action call. */ void mob_action_runners::save_focus_memory(mob_action_run_data &data) { if(!data.m->focused_mob) { return; } data.m->focused_mob_memory[s2i(data.args[0])] = data.m->focused_mob; } /* ---------------------------------------------------------------------------- * Code for the focused mob message sending mob script action. * data: * Data about the action call. */ void mob_action_runners::send_message_to_focus(mob_action_run_data &data) { if(!data.m->focused_mob) return; data.m->send_message(data.m->focused_mob, data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the linked mob message sending mob script action. * data: * Data about the action call. */ void mob_action_runners::send_message_to_links(mob_action_run_data &data) { for(size_t l = 0; l < data.m->links.size(); ++l) { if(data.m->links[l] == data.m) continue; data.m->send_message(data.m->links[l], data.args[0]); } } /* ---------------------------------------------------------------------------- * Code for the nearby mob message sending mob script action. * data: * Data about the action call. */ void mob_action_runners::send_message_to_nearby(mob_action_run_data &data) { float d = s2f(data.args[0]); for(size_t m2 = 0; m2 < game.states.gameplay->mobs.all.size(); ++m2) { if(game.states.gameplay->mobs.all[m2] == data.m) { continue; } if(dist(data.m->pos, game.states.gameplay->mobs.all[m2]->pos) > d) { continue; } data.m->send_message( game.states.gameplay->mobs.all[m2], data.args[1] ); } } /* ---------------------------------------------------------------------------- * Code for the animation setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_animation(mob_action_run_data &data) { bool must_restart = ( data.args.size() > 1 && s2i(data.args[1]) == MOB_ACTION_SET_ANIMATION_NO_RESTART ); data.m->set_animation(s2i(data.args[0]), false, !must_restart); } /* ---------------------------------------------------------------------------- * Code for the block paths setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_can_block_paths(mob_action_run_data &data) { data.m->set_can_block_paths(s2b(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the far reach setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_far_reach(mob_action_run_data &data) { data.m->far_reach = s2i(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the flying setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_flying(mob_action_run_data &data) { data.m->can_move_in_midair = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the gravity setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_gravity(mob_action_run_data &data) { data.m->gravity_mult = s2f(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the health setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_health(mob_action_run_data &data) { data.m->set_health(false, false, s2f(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the height setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_height(mob_action_run_data &data) { data.m->height = s2f(data.args[0]); if(data.m->type->walkable) { //Update the Z of mobs standing on top of it. for(size_t m = 0; m < game.states.gameplay->mobs.all.size(); ++m) { mob* m2_ptr = game.states.gameplay->mobs.all[m]; if(m2_ptr->standing_on_mob == data.m) { m2_ptr->z = data.m->z + data.m->height; } } } } /* ---------------------------------------------------------------------------- * Code for the hiding setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_hiding(mob_action_run_data &data) { data.m->hide = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the holdable setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_holdable(mob_action_run_data &data) { if(typeid(*(data.m)) == typeid(tool)) { size_t flags = 0; for(size_t i = 0; i < data.args.size(); ++i) { flags |= s2i(data.args[i]); } ((tool*) (data.m))->holdability_flags = flags; } } /* ---------------------------------------------------------------------------- * Code for the huntable setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_huntable(mob_action_run_data &data) { data.m->is_huntable = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the limb animation setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_limb_animation(mob_action_run_data &data) { if(!data.m->parent) { return; } if(!data.m->parent->limb_anim.anim_db) { return; } size_t a = data.m->parent->limb_anim.anim_db->find_animation(data.args[0]); if(a == INVALID) { return; } data.m->parent->limb_anim.cur_anim = data.m->parent->limb_anim.anim_db->animations[a]; data.m->parent->limb_anim.start(); } /* ---------------------------------------------------------------------------- * Code for the near reach setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_near_reach(mob_action_run_data &data) { data.m->near_reach = s2i(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the radius setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_radius(mob_action_run_data &data) { data.m->radius = s2f(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the sector scroll setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_sector_scroll(mob_action_run_data &data) { sector* s_ptr = get_sector(data.m->pos, NULL, true); if(!s_ptr) return; s_ptr->scroll.x = s2f(data.args[0]); s_ptr->scroll.y = s2f(data.args[1]); } /* ---------------------------------------------------------------------------- * Code for the shadow visibility setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_shadow_visibility(mob_action_run_data &data) { data.m->show_shadow = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the state setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_state(mob_action_run_data &data) { data.m->fsm.set_state( s2i(data.args[0]), data.custom_data_1, data.custom_data_2 ); } /* ---------------------------------------------------------------------------- * Code for the tangible setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_tangible(mob_action_run_data &data) { data.m->tangible = s2b(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the team setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_team(mob_action_run_data &data) { data.m->team = s2i(data.args[0]); } /* ---------------------------------------------------------------------------- * Code for the timer setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_timer(mob_action_run_data &data) { data.m->set_timer(s2f(data.args[0])); } /* ---------------------------------------------------------------------------- * Code for the var setting mob script action. * data: * Data about the action call. */ void mob_action_runners::set_var(mob_action_run_data &data) { data.m->set_var(data.args[0], data.args[1]); } /* ---------------------------------------------------------------------------- * Code for the show message from var mob script action. * data: * Data about the action call. */ void mob_action_runners::show_message_from_var(mob_action_run_data &data) { start_message(data.m->vars[data.args[0]], NULL); } /* ---------------------------------------------------------------------------- * Code for the spawning mob script action. * data: * Data about the action call. */ void mob_action_runners::spawn(mob_action_run_data &data) { data.m->spawn(&data.m->type->spawns[s2i(data.args[0])]); } /* ---------------------------------------------------------------------------- * Code for the z stabilization mob script action. * data: * Data about the action call. */ void mob_action_runners::stabilize_z(mob_action_run_data &data) { if(data.m->links.empty()) { return; } float best_match_z = data.m->links[0]->z; size_t t = s2i(data.args[0]); for(size_t l = 1; l < data.m->links.size(); ++l) { switch(t) { case MOB_ACTION_STABILIZE_Z_HIGHEST: { if(data.m->links[l]->z > best_match_z) { best_match_z = data.m->links[l]->z; } break; } case MOB_ACTION_STABILIZE_Z_LOWEST: { if(data.m->links[l]->z < best_match_z) { best_match_z = data.m->links[l]->z; } break; } } } data.m->z = best_match_z + s2f(data.args[1]); } /* ---------------------------------------------------------------------------- * Code for the chomping start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_chomping(mob_action_run_data &data) { data.m->chomp_max = s2i(data.args[0]); data.m->chomp_body_parts.clear(); for(size_t p = 1; p < data.args.size(); ++p) { data.m->chomp_body_parts.push_back(s2i(data.args[p])); } } /* ---------------------------------------------------------------------------- * Code for the dying start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_dying(mob_action_run_data &data) { data.m->start_dying(); } /* ---------------------------------------------------------------------------- * Code for the height effect start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_height_effect(mob_action_run_data &data) { data.m->start_height_effect(); } /* ---------------------------------------------------------------------------- * Code for the particle start mob script action. * data: * Data about the action call. */ void mob_action_runners::start_particles(mob_action_run_data &data) { float offset_x = 0; float offset_y = 0; float offset_z = 0; if(data.args.size() > 1) offset_x = s2f(data.args[1]); if(data.args.size() > 2) offset_y = s2f(data.args[2]); if(data.args.size() > 3) offset_z = s2f(data.args[3]); particle_generator pg = game.custom_particle_generators[data.args[0]]; pg.id = MOB_PARTICLE_GENERATOR_SCRIPT; pg.follow_mob = data.m; pg.follow_angle = &data.m->angle; pg.follow_pos_offset = point(offset_x, offset_y); pg.follow_z_offset = offset_z; pg.reset(); data.m->particle_generators.push_back(pg); } /* ---------------------------------------------------------------------------- * Code for the stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop(mob_action_run_data &data) { data.m->stop_chasing(); data.m->stop_turning(); data.m->stop_following_path(); } /* ---------------------------------------------------------------------------- * Code for the chomp stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_chomping(mob_action_run_data &data) { data.m->chomp_max = 0; data.m->chomp_body_parts.clear(); } /* ---------------------------------------------------------------------------- * Code for the height effect stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_height_effect(mob_action_run_data &data) { data.m->stop_height_effect(); } /* ---------------------------------------------------------------------------- * Code for the particle stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_particles(mob_action_run_data &data) { data.m->remove_particle_generator(MOB_PARTICLE_GENERATOR_SCRIPT); } /* ---------------------------------------------------------------------------- * Code for the vertical stopping mob script action. * data: * Data about the action call. */ void mob_action_runners::stop_vertically(mob_action_run_data &data) { data.m->speed_z = 0; } /* ---------------------------------------------------------------------------- * Code for the focus storing mob script action. * data: * Data about the action call. */ void mob_action_runners::store_focus_inside(mob_action_run_data &data) { if(data.m->focused_mob) { if(!data.m->focused_mob->stored_inside_another) { data.m->hold( data.m->focused_mob, INVALID, 0.0f, 0.0f, false, HOLD_ROTATION_METHOD_NEVER ); data.m->focused_mob->stored_inside_another = data.m; } } } /* ---------------------------------------------------------------------------- * Code for the swallow mob script action. * data: * Data about the action call. */ void mob_action_runners::swallow(mob_action_run_data &data) { data.m->swallow_chomped_pikmin(s2i(data.args[1])); } /* ---------------------------------------------------------------------------- * Code for the swallow all mob script action. * data: * Data about the action call. */ void mob_action_runners::swallow_all(mob_action_run_data &data) { data.m->swallow_chomped_pikmin(data.m->chomping_mobs.size()); } /* ---------------------------------------------------------------------------- * Code for the teleport to absolute coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::teleport_to_absolute(mob_action_run_data &data) { data.m->stop_chasing(); data.m->chase( point(s2f(data.args[0]), s2f(data.args[1])), s2f(data.args[2]), CHASE_FLAG_TELEPORT ); } /* ---------------------------------------------------------------------------- * Code for the teleport to relative coordinates mob script action. * data: * Data about the action call. */ void mob_action_runners::teleport_to_relative(mob_action_run_data &data) { data.m->stop_chasing(); point p = rotate_point( point(s2f(data.args[0]), s2f(data.args[1])), data.m->angle ); data.m->chase( data.m->pos + p, data.m->z + s2f(data.args[2]), CHASE_FLAG_TELEPORT ); } /* ---------------------------------------------------------------------------- * Code for the throw focused mob mob script action. * data: * Data about the action call. */ void mob_action_runners::throw_focus(mob_action_run_data &data) { if(!data.m->focused_mob) { return; } if(data.m->focused_mob->holder.m == data.m) { data.m->release(data.m->focused_mob); } float max_height = s2f(data.args[3]); if(max_height == 0.0f) { //We just want to drop it, not throw it. return; } data.m->start_height_effect(); calculate_throw( data.m->focused_mob->pos, data.m->focused_mob->z, point(s2f(data.args[0]), s2f(data.args[1])), s2f(data.args[2]), max_height, GRAVITY_ADDER, &data.m->focused_mob->speed, &data.m->focused_mob->speed_z, NULL ); } /* ---------------------------------------------------------------------------- * Code for the turn to an absolute angle mob script action. * data: * Data about the action call. */ void mob_action_runners::turn_to_absolute(mob_action_run_data &data) { if(data.args.size() == 1) { //Turn to an absolute angle. data.m->face(deg_to_rad(s2f(data.args[0])), NULL); } else { //Turn to some absolute coordinates. float x = s2f(data.args[0]); float y = s2f(data.args[1]); data.m->face(get_angle(data.m->pos, point(x, y)), NULL); } } /* ---------------------------------------------------------------------------- * Code for the turn to a relative angle mob script action. * data: * Data about the action call. */ void mob_action_runners::turn_to_relative(mob_action_run_data &data) { if(data.args.size() == 1) { //Turn to a relative angle. data.m->face(data.m->angle + deg_to_rad(s2f(data.args[0])), NULL); } else { //Turn to some relative coordinates. float x = s2f(data.args[0]); float y = s2f(data.args[1]); point p = rotate_point(point(x, y), data.m->angle); data.m->face(get_angle(data.m->pos, data.m->pos + p), NULL); } } /* ---------------------------------------------------------------------------- * Code for the turn to target mob script action. * data: * Data about the action call. */ void mob_action_runners::turn_to_target(mob_action_run_data &data) { size_t t = s2i(data.args[0]); switch(t) { case MOB_ACTION_TURN_ARACHNORB_HEAD_LOGIC: { data.m->arachnorb_head_turn_logic(); break; } case MOB_ACTION_TURN_FOCUSED_MOB: { if(data.m->focused_mob) { data.m->face(0, &data.m->focused_mob->pos); } break; } case MOB_ACTION_TURN_HOME: { data.m->face(get_angle(data.m->pos, data.m->home), NULL); break; } } } /* ---------------------------------------------------------------------------- * Confirms if the "if", "else", "end_if", "goto", and "label" actions in * a given vector of actions are all okay, and there are no mismatches, like * for instance, an "else" without an "if". * Also checks if there are actions past a "set_state" action. * If everything is okay, returns true. If not, throws errors to the * error log and returns false. * actions: * The vector of actions to check. * dn: * Data node from where these actions came. */ bool assert_actions( const vector<mob_action_call*> &actions, data_node* dn ) { //Check if the "if"-related actions are okay. int if_level = 0; for(size_t a = 0; a < actions.size(); ++a) { switch(actions[a]->action->type) { case MOB_ACTION_IF: { if_level++; break; } case MOB_ACTION_ELSE: { if(if_level == 0) { log_error( "Found an \"else\" action without a matching " "\"if\" action!", dn ); return false; } break; } case MOB_ACTION_END_IF: { if(if_level == 0) { log_error( "Found an \"end_if\" action without a matching " "\"if\" action!", dn ); return false; } if_level--; break; } } } if(if_level > 0) { log_error( "Some \"if\" actions don't have a matching \"end_if\" action!", dn ); return false; } //Check if the "goto"-related actions are okay. set<string> labels; for(size_t a = 0; a < actions.size(); ++a) { if(actions[a]->action->type == MOB_ACTION_LABEL) { string name = actions[a]->args[0]; if(labels.find(name) != labels.end()) { log_error( "There are multiple labels called \"" + name + "\"!", dn ); return false; } labels.insert(name); } } for(size_t a = 0; a < actions.size(); ++a) { if(actions[a]->action->type == MOB_ACTION_GOTO) { string name = actions[a]->args[0]; if(labels.find(name) == labels.end()) { log_error( "There is no label called \"" + name + "\", even though " "there are \"goto\" actions that need it!", dn ); return false; } } } //Check if there are actions after a "set_state" action. bool passed_set_state = false; for(size_t a = 0; a < actions.size(); ++a) { switch(actions[a]->action->type) { case MOB_ACTION_SET_STATE: { passed_set_state = true; break; } case MOB_ACTION_ELSE: { passed_set_state = false; break; } case MOB_ACTION_END_IF: { passed_set_state = false; break; } case MOB_ACTION_LABEL: { passed_set_state = false; break; } default: { if(passed_set_state) { log_error( "There is an action \"" + actions[a]->action->name + "\" " "placed after a \"set_state\" action, which means it will " "never get run! Make sure you didn't mean to call it " "before the \"set_state\" action.", dn ); return false; } break; } } } return true; } /* ---------------------------------------------------------------------------- * A general function for get_info actions. * data: * The action's data. * target_mob: * The mob to get the info from, if applicable. */ void get_info_runner(mob_action_run_data &data, mob* target_mob) { if(target_mob == NULL) { return; } string* var = &(data.m->vars[data.args[0]]); size_t t = s2i(data.args[1]); switch(t) { case MOB_ACTION_GET_INFO_ANGLE: { *var = f2s(rad_to_deg(target_mob->angle)); break; } case MOB_ACTION_GET_INFO_BODY_PART: { if( data.call->parent_event == MOB_EV_HITBOX_TOUCH_A_N || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_A || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_N || data.call->parent_event == MOB_EV_DAMAGE ) { *var = ( (hitbox_interaction*)(data.custom_data_1) )->h1->body_part_name; } else if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED ) { *var = target_mob->get_closest_hitbox( ((mob*)(data.custom_data_1))->pos, INVALID, NULL )->body_part_name; } break; } case MOB_ACTION_GET_INFO_CHOMPED_PIKMIN: { *var = i2s(target_mob->chomping_mobs.size()); break; } case MOB_ACTION_GET_INFO_DAY_MINUTES: { *var = i2s(game.states.gameplay->day_minutes); break; } case MOB_ACTION_GET_INFO_FIELD_PIKMIN: { *var = i2s(game.states.gameplay->mobs.pikmin_list.size()); break; } case MOB_ACTION_GET_INFO_FOCUS_DISTANCE: { if(target_mob->focused_mob) { float d = dist(target_mob->pos, target_mob->focused_mob->pos).to_float(); *var = f2s(d); } break; } case MOB_ACTION_GET_INFO_FRAME_SIGNAL: { if(data.call->parent_event == MOB_EV_FRAME_SIGNAL) { *var = i2s(*((size_t*)(data.custom_data_1))); } break; } case MOB_ACTION_GET_INFO_GROUP_TASK_POWER: { if(target_mob->type->category->id == MOB_CATEGORY_GROUP_TASKS) { *var = f2s(((group_task*) target_mob)->get_power()); } break; } case MOB_ACTION_GET_INFO_HAZARD: { if( data.call->parent_event == MOB_EV_TOUCHED_HAZARD || data.call->parent_event == MOB_EV_LEFT_HAZARD ) { *var = ((hazard*) data.custom_data_1)->name; } break; } case MOB_ACTION_GET_INFO_HEALTH: { *var = i2s(target_mob->health); break; } case MOB_ACTION_GET_INFO_LATCHED_PIKMIN: { *var = i2s(target_mob->get_latched_pikmin_amount()); break; } case MOB_ACTION_GET_INFO_LATCHED_PIKMIN_WEIGHT: { *var = i2s(target_mob->get_latched_pikmin_weight()); break; } case MOB_ACTION_GET_INFO_MESSAGE: { if(data.call->parent_event == MOB_EV_RECEIVE_MESSAGE) { *var = *((string*)(data.custom_data_1)); } break; } case MOB_ACTION_GET_INFO_MESSAGE_SENDER: { if(data.call->parent_event == MOB_EV_RECEIVE_MESSAGE) { *var = ((mob*)(data.custom_data_2))->type->name; } break; } case MOB_ACTION_GET_INFO_MOB_CATEGORY: { if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_OBJECT_IN_REACH || data.call->parent_event == MOB_EV_OPPONENT_IN_REACH ) { *var = ((mob*)(data.custom_data_1))->type->category->name; } break; } case MOB_ACTION_GET_INFO_MOB_TYPE: { if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_OBJECT_IN_REACH || data.call->parent_event == MOB_EV_OPPONENT_IN_REACH || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED ) { *var = ((mob*)(data.custom_data_1))->type->name; } break; } case MOB_ACTION_GET_INFO_OTHER_BODY_PART: { if( data.call->parent_event == MOB_EV_HITBOX_TOUCH_A_N || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_A || data.call->parent_event == MOB_EV_HITBOX_TOUCH_N_N || data.call->parent_event == MOB_EV_DAMAGE ) { *var = ( (hitbox_interaction*)(data.custom_data_1) )->h2->body_part_name; } else if( data.call->parent_event == MOB_EV_TOUCHED_OBJECT || data.call->parent_event == MOB_EV_TOUCHED_OPPONENT || data.call->parent_event == MOB_EV_THROWN_PIKMIN_LANDED ) { *var = ((mob*)(data.custom_data_1))->get_closest_hitbox( target_mob->pos, INVALID, NULL )->body_part_name; } break; } case MOB_ACTION_GET_INFO_X: { *var = f2s(target_mob->pos.x); break; } case MOB_ACTION_GET_INFO_Y: { *var = f2s(target_mob->pos.y); break; } case MOB_ACTION_GET_INFO_Z: { *var = f2s(target_mob->z); break; } case MOB_ACTION_GET_INFO_WEIGHT: { if(target_mob->type->category->id == MOB_CATEGORY_SCALES) { scale* s_ptr = (scale*)(target_mob); *var = i2s(s_ptr->calculate_cur_weight()); } break; } } } /* ---------------------------------------------------------------------------- * Loads the actions to be run when the mob initializes. * mt: * The type of mob the actions are going to. * node: * The data node. * actions: * Vector of actions to be filled. */ void load_init_actions( mob_type* mt, data_node* node, vector<mob_action_call*>* actions ) { for(size_t a = 0; a < node->get_nr_of_children(); ++a) { mob_action_call* new_a = new mob_action_call(); if(new_a->load_from_data_node(node->get_child(a), mt)) { actions->push_back(new_a); } else { delete new_a; } } assert_actions(*actions, node); }
30.515021
80
0.522714
shantonusen
72bb381ee9399b33e73c21f850d32342611a6c5a
14,430
cc
C++
content/browser/appcache/appcache_subresource_url_factory.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/browser/appcache/appcache_subresource_url_factory.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/browser/appcache/appcache_subresource_url_factory.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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 "content/browser/appcache/appcache_subresource_url_factory.h" #include "base/bind.h" #include "base/logging.h" #include "content/browser/appcache/appcache_host.h" #include "content/browser/appcache/appcache_request_handler.h" #include "content/browser/appcache/appcache_url_loader_job.h" #include "content/browser/appcache/appcache_url_loader_request.h" #include "content/browser/url_loader_factory_getter.h" #include "content/public/browser/browser_thread.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/resource_response.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" namespace content { namespace { // URLLoader implementation that utilizes either a network loader // or an appcache loader depending on where the resources should // be loaded from. This class binds to the remote client in the // renderer and internally creates one or the other kind of loader. // The URLLoader and URLLoaderClient interfaces are proxied between // the remote consumer and the chosen internal loader. // // This class owns and scopes the lifetime of the AppCacheRequestHandler // for the duration of a subresource load. class SubresourceLoader : public network::mojom::URLLoader, public network::mojom::URLLoaderClient { public: SubresourceLoader(network::mojom::URLLoaderRequest url_loader_request, int32_t routing_id, int32_t request_id, uint32_t options, const network::ResourceRequest& request, network::mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& annotation, base::WeakPtr<AppCacheHost> appcache_host, scoped_refptr<URLLoaderFactoryGetter> net_factory_getter) : remote_binding_(this, std::move(url_loader_request)), remote_client_(std::move(client)), request_(request), routing_id_(routing_id), request_id_(request_id), options_(options), traffic_annotation_(annotation), network_loader_factory_(std::move(net_factory_getter)), local_client_binding_(this), host_(appcache_host), weak_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); remote_binding_.set_connection_error_handler(base::BindOnce( &SubresourceLoader::OnConnectionError, base::Unretained(this))); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SubresourceLoader::Start, weak_factory_.GetWeakPtr())); } private: ~SubresourceLoader() override {} void OnConnectionError() { delete this; } void Start() { if (!host_) { remote_client_->OnComplete( network::URLLoaderCompletionStatus(net::ERR_FAILED)); return; } handler_ = host_->CreateRequestHandler( AppCacheURLLoaderRequest::Create(request_), static_cast<ResourceType>(request_.resource_type), request_.should_reset_appcache); if (!handler_) { CreateAndStartNetworkLoader(); return; } handler_->MaybeCreateSubresourceLoader( request_, base::BindOnce(&SubresourceLoader::ContinueStart, weak_factory_.GetWeakPtr())); } void ContinueStart(SingleRequestURLLoaderFactory::RequestHandler handler) { if (handler) CreateAndStartAppCacheLoader(std::move(handler)); else CreateAndStartNetworkLoader(); } void CreateAndStartAppCacheLoader( SingleRequestURLLoaderFactory::RequestHandler handler) { DCHECK(!appcache_loader_) << "only expected to be called onced"; DCHECK(handler); // Disconnect from the network loader first. local_client_binding_.Close(); network_loader_ = nullptr; network::mojom::URLLoaderClientPtr client_ptr; local_client_binding_.Bind(mojo::MakeRequest(&client_ptr)); std::move(handler).Run(mojo::MakeRequest(&appcache_loader_), std::move(client_ptr)); } void CreateAndStartNetworkLoader() { DCHECK(!appcache_loader_); network::mojom::URLLoaderClientPtr client_ptr; local_client_binding_.Bind(mojo::MakeRequest(&client_ptr)); network_loader_factory_->GetNetworkFactory()->CreateLoaderAndStart( mojo::MakeRequest(&network_loader_), routing_id_, request_id_, options_, request_, std::move(client_ptr), traffic_annotation_); if (has_set_priority_) network_loader_->SetPriority(priority_, intra_priority_value_); if (has_paused_reading_) network_loader_->PauseReadingBodyFromNet(); } // network::mojom::URLLoader implementation // Called by the remote client in the renderer. void FollowRedirect(const base::Optional<net::HttpRequestHeaders>& modified_request_headers) override { DCHECK(!modified_request_headers.has_value()) << "Redirect with modified headers was not supported yet. " "crbug.com/845683"; if (!handler_) { network_loader_->FollowRedirect(base::nullopt); return; } DCHECK(network_loader_); DCHECK(!appcache_loader_); handler_->MaybeFollowSubresourceRedirect( redirect_info_, base::BindOnce(&SubresourceLoader::ContinueFollowRedirect, weak_factory_.GetWeakPtr())); } // network::mojom::URLLoader implementation void ProceedWithResponse() override { NOTREACHED(); } void ContinueFollowRedirect( SingleRequestURLLoaderFactory::RequestHandler handler) { if (handler) CreateAndStartAppCacheLoader(std::move(handler)); else network_loader_->FollowRedirect(base::nullopt); } void SetPriority(net::RequestPriority priority, int32_t intra_priority_value) override { has_set_priority_ = true; priority_ = priority; intra_priority_value_ = intra_priority_value; if (network_loader_) network_loader_->SetPriority(priority, intra_priority_value); } void PauseReadingBodyFromNet() override { has_paused_reading_ = true; if (network_loader_) network_loader_->PauseReadingBodyFromNet(); } void ResumeReadingBodyFromNet() override { has_paused_reading_ = false; if (network_loader_) network_loader_->ResumeReadingBodyFromNet(); } // network::mojom::URLLoaderClient implementation // Called by either the appcache or network loader, whichever is in use. void OnReceiveResponse( const network::ResourceResponseHead& response_head, network::mojom::DownloadedTempFilePtr downloaded_file) override { // Don't MaybeFallback for appcache produced responses. if (appcache_loader_ || !handler_) { remote_client_->OnReceiveResponse(response_head, std::move(downloaded_file)); return; } did_receive_network_response_ = true; handler_->MaybeFallbackForSubresourceResponse( response_head, base::BindOnce(&SubresourceLoader::ContinueOnReceiveResponse, weak_factory_.GetWeakPtr(), response_head, std::move(downloaded_file))); } void ContinueOnReceiveResponse( const network::ResourceResponseHead& response_head, network::mojom::DownloadedTempFilePtr downloaded_file, SingleRequestURLLoaderFactory::RequestHandler handler) { if (handler) { CreateAndStartAppCacheLoader(std::move(handler)); } else { remote_client_->OnReceiveResponse(response_head, std::move(downloaded_file)); } } void OnReceiveRedirect( const net::RedirectInfo& redirect_info, const network::ResourceResponseHead& response_head) override { DCHECK(network_loader_) << "appcache loader does not produce redirects"; if (!redirect_limit_--) { OnComplete( network::URLLoaderCompletionStatus(net::ERR_TOO_MANY_REDIRECTS)); return; } if (!handler_) { remote_client_->OnReceiveRedirect(redirect_info_, response_head); return; } redirect_info_ = redirect_info; handler_->MaybeFallbackForSubresourceRedirect( redirect_info, base::BindOnce(&SubresourceLoader::ContinueOnReceiveRedirect, weak_factory_.GetWeakPtr(), response_head)); } void ContinueOnReceiveRedirect( const network::ResourceResponseHead& response_head, SingleRequestURLLoaderFactory::RequestHandler handler) { if (handler) CreateAndStartAppCacheLoader(std::move(handler)); else remote_client_->OnReceiveRedirect(redirect_info_, response_head); } void OnDataDownloaded(int64_t data_len, int64_t encoded_data_len) override { remote_client_->OnDataDownloaded(data_len, encoded_data_len); } void OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback ack_callback) override { remote_client_->OnUploadProgress(current_position, total_size, std::move(ack_callback)); } void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override { remote_client_->OnReceiveCachedMetadata(data); } void OnTransferSizeUpdated(int32_t transfer_size_diff) override { remote_client_->OnTransferSizeUpdated(transfer_size_diff); } void OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) override { remote_client_->OnStartLoadingResponseBody(std::move(body)); } void OnComplete(const network::URLLoaderCompletionStatus& status) override { if (!network_loader_ || !handler_ || did_receive_network_response_ || status.error_code == net::OK) { remote_client_->OnComplete(status); return; } handler_->MaybeFallbackForSubresourceResponse( network::ResourceResponseHead(), base::BindOnce(&SubresourceLoader::ContinueOnComplete, weak_factory_.GetWeakPtr(), status)); } void ContinueOnComplete( const network::URLLoaderCompletionStatus& status, SingleRequestURLLoaderFactory::RequestHandler handler) { if (handler) CreateAndStartAppCacheLoader(std::move(handler)); else remote_client_->OnComplete(status); } // The binding and client pointer associated with the renderer. mojo::Binding<network::mojom::URLLoader> remote_binding_; network::mojom::URLLoaderClientPtr remote_client_; network::ResourceRequest request_; int32_t routing_id_; int32_t request_id_; uint32_t options_; net::MutableNetworkTrafficAnnotationTag traffic_annotation_; scoped_refptr<URLLoaderFactoryGetter> network_loader_factory_; net::RedirectInfo redirect_info_; int redirect_limit_ = net::URLRequest::kMaxRedirects; bool did_receive_network_response_ = false; bool has_paused_reading_ = false; bool has_set_priority_ = false; net::RequestPriority priority_; int32_t intra_priority_value_; // Core appcache logic that decides how to handle a request. std::unique_ptr<AppCacheRequestHandler> handler_; // The local binding to either our network or appcache loader, // we only use one of them at any given time. mojo::Binding<network::mojom::URLLoaderClient> local_client_binding_; network::mojom::URLLoaderPtr network_loader_; network::mojom::URLLoaderPtr appcache_loader_; base::WeakPtr<AppCacheHost> host_; base::WeakPtrFactory<SubresourceLoader> weak_factory_; DISALLOW_COPY_AND_ASSIGN(SubresourceLoader); }; } // namespace // Implements the URLLoaderFactory mojom for AppCache requests. AppCacheSubresourceURLFactory::AppCacheSubresourceURLFactory( URLLoaderFactoryGetter* default_url_loader_factory_getter, base::WeakPtr<AppCacheHost> host) : default_url_loader_factory_getter_(default_url_loader_factory_getter), appcache_host_(host), weak_factory_(this) { bindings_.set_connection_error_handler( base::Bind(&AppCacheSubresourceURLFactory::OnConnectionError, base::Unretained(this))); } AppCacheSubresourceURLFactory::~AppCacheSubresourceURLFactory() {} // static void AppCacheSubresourceURLFactory::CreateURLLoaderFactory( URLLoaderFactoryGetter* default_url_loader_factory_getter, base::WeakPtr<AppCacheHost> host, network::mojom::URLLoaderFactoryPtr* loader_factory) { DCHECK(host.get()); // This instance is effectively reference counted by the number of pipes open // to it and will get deleted when all clients drop their connections. // Please see OnConnectionError() for details. auto* impl = new AppCacheSubresourceURLFactory( default_url_loader_factory_getter, host); impl->Clone(mojo::MakeRequest(loader_factory)); // Save the factory in the host to ensure that we don't create it again when // the cache is selected, etc. host->SetAppCacheSubresourceFactory(impl); } void AppCacheSubresourceURLFactory::CreateLoaderAndStart( network::mojom::URLLoaderRequest url_loader_request, int32_t routing_id, int32_t request_id, uint32_t options, const network::ResourceRequest& request, network::mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) { DCHECK_CURRENTLY_ON(BrowserThread::IO); new SubresourceLoader(std::move(url_loader_request), routing_id, request_id, options, request, std::move(client), traffic_annotation, appcache_host_, default_url_loader_factory_getter_); } void AppCacheSubresourceURLFactory::Clone( network::mojom::URLLoaderFactoryRequest request) { bindings_.AddBinding(this, std::move(request)); } base::WeakPtr<AppCacheSubresourceURLFactory> AppCacheSubresourceURLFactory::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } void AppCacheSubresourceURLFactory::OnConnectionError() { if (bindings_.empty()) delete this; } } // namespace content
37.774869
80
0.726611
zipated
72c1b748ab5c3dfc784d038e4eeea1cce78b47e5
623
cpp
C++
hostsampleapp/uwp/Common/PerceptionTypes.cpp
sereilly/MixedReality-HolographicRemoting-Samples
d6ff35e13a5edda41e074b355bf82e875ab24e4a
[ "MIT" ]
null
null
null
hostsampleapp/uwp/Common/PerceptionTypes.cpp
sereilly/MixedReality-HolographicRemoting-Samples
d6ff35e13a5edda41e074b355bf82e875ab24e4a
[ "MIT" ]
null
null
null
hostsampleapp/uwp/Common/PerceptionTypes.cpp
sereilly/MixedReality-HolographicRemoting-Samples
d6ff35e13a5edda41e074b355bf82e875ab24e4a
[ "MIT" ]
null
null
null
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "../pch.h" // -- important: preserve order of these two includes (initguid before PerceptionTypes)! #include <initguid.h> #include "PerceptionTypes.h" // --
32.789474
89
0.566613
sereilly