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
109
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
48.5k
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
a30edb5b7df06e3eeeb36a1e86e746d9db32f323
7,084
cpp
C++
src/gui/TActionCuePaletteView.cpp
thezealousfool/UltraDV
470840a298a306495e59fb2d00b730edf04b4506
[ "Unlicense" ]
null
null
null
src/gui/TActionCuePaletteView.cpp
thezealousfool/UltraDV
470840a298a306495e59fb2d00b730edf04b4506
[ "Unlicense" ]
null
null
null
src/gui/TActionCuePaletteView.cpp
thezealousfool/UltraDV
470840a298a306495e59fb2d00b730edf04b4506
[ "Unlicense" ]
2
2021-08-19T20:37:23.000Z
2021-08-20T00:35:19.000Z
//--------------------------------------------------------------------- // // File: TActionCuePaletteView.cpp // // Author: Gene Z. Ragan // // Date: 01.26.98 // // Desc: MediaCue sheet view // // Copyright ©1998 mediapede Software // //--------------------------------------------------------------------- // Includes #include "BuildApp.h" #include <app/Application.h> #include <support/Debug.h> #include "AppConstants.h" #include "ResourceManager.h" #include "TMuseumIcons.h" #include "TActionCuePaletteView.h" #include "TCueButton.h" // Constants // I am subtracting l pixel of the width and height to create an actual // width offset from 0 (ie: 0-31 = 32 pixels) // The media cue button itself is offset form thesides and top of the // surrounding palette area. const BRect kCueButtonBounds(0, 0, kCueIconWidth-1, kCueIconHeight-1); //--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- // // TActionCuePaletteView::TActionCuePaletteView(BRect bounds) : BView(bounds, "ActionCueView", B_FOLLOW_ALL, B_WILL_DRAW) { // Perform default initialization Init(); } //--------------------------------------------------------------------- // Destructor //--------------------------------------------------------------------- // // TActionCuePaletteView::~TActionCuePaletteView() { // Cue button bitmaps are owned by TMuseumIcon object } //--------------------------------------------------------------------- // Init //--------------------------------------------------------------------- // // Perform default initialization tasks void TActionCuePaletteView::Init() { BBitmap* offBitmap; BBitmap* onBitmap; // Set view background color SetViewColor(kSteelGrey); // Get application info app_info info; be_app->GetAppInfo(&info); BFile file(&info.ref, O_RDONLY); if (file.InitCheck()) return; BResources res(&file); // // Create the media cue icon subviews // BRect cueRect = Bounds(); // Action Cue // // Set button location cueRect.Set( kCueButtonOffset, kCueButtonOffset, kCueIconWidth+kCueButtonOffset-1, kCueIconHeight+kCueButtonOffset-1); // Load bitmaps // ABH offBitmap = GetAppIcons()->fActionIcon; // ABH onBitmap = GetAppIcons()->fActionIcon; // Create button fActionCueButton = new TCueButton(cueRect, "ActionCue", offBitmap, onBitmap, new BMessage(ACTION_CUE_MSG), kActionCue); AddChild(fActionCueButton); // // Button Cue // Set button location cueRect.top = cueRect.top+kCueIconHeight+kCueTextOffset; cueRect.bottom = cueRect.top+kCueIconHeight-1; // Load bitmaps // ABH offBitmap = GetAppIcons()->fButtonIcon; // ABH onBitmap = GetAppIcons()->fButtonIcon; // Create button fButtonCueButton = new TCueButton(cueRect, "ButtonCue", offBitmap, onBitmap, new BMessage(BUTTON_CUE_MSG), kButtonCue); AddChild(fButtonCueButton); // CD Cue // // Set button location cueRect.top = cueRect.top+kCueIconHeight+kCueTextOffset; cueRect.bottom = cueRect.top+kCueIconHeight-1; // Load bitmaps //ABH offBitmap = GetAppIcons()->fCDIcon; //ABH onBitmap = GetAppIcons()->fCDIcon; // Create button fCDCueButton = new TCueButton(cueRect, "CDCue", offBitmap, onBitmap, new BMessage(CD_CUE_MSG), kCDCue); AddChild(fCDCueButton); // Control Cue // // Set button location cueRect.top = cueRect.top+kCueIconHeight+kCueTextOffset; cueRect.bottom = cueRect.top+kCueIconHeight-1; // Load bitmaps // ABH offBitmap = GetAppIcons()->fControlIcon; // ABH onBitmap = GetAppIcons()->fControlIcon; // Create button fControlCueButton = new TCueButton(cueRect, "ControlCue", offBitmap, onBitmap, new BMessage(CONTROL_CUE_MSG), kControlCue); AddChild(fControlCueButton); // Marker Cue // // Set button location cueRect.top = cueRect.top+kCueIconHeight+kCueTextOffset; cueRect.bottom = cueRect.top+kCueIconHeight-1; // Load bitmaps // ABH offBitmap = GetAppIcons()->fMarkerIcon; // ABH onBitmap = GetAppIcons()->fMarkerIcon; // Create button fMarkerCueButton = new TCueButton(cueRect, "", offBitmap, onBitmap, new BMessage(MARKER_CUE_MSG), kMarkerCue); AddChild(fMarkerCueButton); // Pause Cue // // Set button location cueRect.top = cueRect.top+kCueIconHeight+kCueTextOffset; cueRect.bottom = cueRect.top+kCueIconHeight-1; // Load bitmaps // ABH offBitmap = GetAppIcons()->fPauseIcon; // ABH onBitmap = GetAppIcons()->fPauseIcon; // Create button fPauseCueButton = new TCueButton(cueRect, "PauseCue", offBitmap, onBitmap, new BMessage(PAUSE_CUE_MSG), kPauseCue); AddChild(fPauseCueButton); // Video Cue // // Set button location cueRect.top = cueRect.top+kCueIconHeight+kCueTextOffset; cueRect.bottom = cueRect.top+kCueIconHeight-1; // Load bitmaps // ABH offBitmap = GetAppIcons()->fVideoIcon; // ABH onBitmap = GetAppIcons()->fVideoIcon; // Create button fVideoCueButton = new TCueButton(cueRect, "VideoCue", offBitmap, onBitmap, new BMessage(VIDEO_CUE_MSG), kVideoCue); AddChild(fVideoCueButton); } //--------------------------------------------------------------------- // Draw //--------------------------------------------------------------------- // // void TActionCuePaletteView::Draw(BRect updateRect) { rgb_color saveColor = HighColor(); // Setup font BFont saveFont; GetFont(&saveFont); SetFont(be_bold_font); SetFontSize(10); SetHighColor(kBlack); // Draw the cue item text descriptions // float stringWidth; BPoint textPt; // Action textPt.y = kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("Action"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("Action", textPt); // Button textPt.y += kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("Button"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("Button", textPt); // CD textPt.y += kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("CD"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("CD", textPt); // Control textPt.y += kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("Control"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("Control", textPt); // Marker textPt.y += kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("Marker"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("Marker", textPt); // Pause textPt.y += kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("Pause"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("Pause", textPt); // Video textPt.y += kCueIconHeight+(kCueButtonOffset*3); stringWidth = StringWidth("Video"); textPt.x = ( (Bounds().right - Bounds().left)/ 2) - (stringWidth /2); DrawString("Video", textPt); // Restore environment SetFont(&saveFont); SetHighColor(saveColor); }
25.482014
124
0.632129
thezealousfool
a30f415007d528b0323b5e899ce825139147b803
2,405
cpp
C++
src/bindings/bindings.cpp
RUrlus/ModelMetricUncertainty
f401a25dd196d6e4edf4901fcfee4b56ebd7c10b
[ "Apache-2.0" ]
null
null
null
src/bindings/bindings.cpp
RUrlus/ModelMetricUncertainty
f401a25dd196d6e4edf4901fcfee4b56ebd7c10b
[ "Apache-2.0" ]
11
2021-12-08T10:34:17.000Z
2022-01-20T13:40:05.000Z
src/bindings/bindings.cpp
RUrlus/ModelMetricUncertainty
f401a25dd196d6e4edf4901fcfee4b56ebd7c10b
[ "Apache-2.0" ]
null
null
null
/* bindings.cpp -- Python bindings for MMU * Copyright 2022 Ralph Urlus */ #include <pybind11/pybind11.h> #include <mmu/bindings/confusion_matrix.hpp> #include <mmu/bindings/metrics.hpp> #include <mmu/bindings/bvn_error.hpp> #include <mmu/bindings/pr_bvn_grid.hpp> #include <mmu/bindings/pr_multn_loglike.hpp> #include <mmu/bindings/utils.hpp> #include <mmu/core/common.hpp> namespace py = pybind11; namespace mmu { namespace bindings { PYBIND11_MODULE(EXTENSION_MODULE_NAME, m) { // confusion_matrix bind_confusion_matrix(m); bind_confusion_matrix_score(m); bind_confusion_matrix_runs(m); bind_confusion_matrix_score_runs(m); bind_confusion_matrix_thresholds(m); bind_confusion_matrix_runs_thresholds(m); bind_confusion_matrix_thresholds_runs(m); // metrics bind_precision_recall(m); bind_precision_recall_2d(m); bind_precision_recall_flattened(m); bind_binary_metrics(m); bind_binary_metrics_2d(m); bind_binary_metrics_flattened(m); // npy bind_all_finite(m); bind_is_well_behaved_finite(m); // lep_bvn pr::bind_bvn_error(m); pr::bind_bvn_error_runs(m); pr::bind_curve_bvn_error(m); pr::bind_bvn_cov(m); pr::bind_bvn_cov_runs(m); pr::bind_curve_bvn_cov(m); pr::bind_bvn_grid_error(m); pr::bind_bvn_grid_curve_error(m); pr::bind_bvn_grid_curve_error_wtrain(m); pr::bind_bvn_chi2_score(m); pr::bind_bvn_chi2_scores(m); // multn_loglike pr::bind_multn_error(m); pr::bind_multn_grid_error(m); pr::bind_multn_grid_curve_error(m); pr::bind_multn_sim_error(m); pr::bind_multn_chi2_score(m); pr::bind_multn_chi2_scores(m); #ifdef MMU_HAS_OPENMP_SUPPORT // lep_bvn pr::bind_bvn_grid_curve_error_mt(m); pr::bind_bvn_grid_curve_error_wtrain_mt(m); pr::bind_bvn_chi2_scores_mt(m); // multn_loglike pr::bind_multn_error_mt(m); pr::bind_multn_grid_curve_error_mt(m); pr::bind_multn_sim_error_mt(m); pr::bind_multn_chi2_scores_mt(m); #endif // MMU_HAS_OPENMP_SUPPORT #ifndef OS_WIN #ifdef VERSION_INFO m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); #else m.attr("__version__") = "dev"; #endif #endif #ifdef MMU_HAS_OPENMP_SUPPORT m.attr("_has_openmp_support") = true; #else m.attr("_has_openmp_support") = false; #endif // MMU_HAS_OPENMP_SUPPORT } } // namespace bindings } // namespace mmu
26.141304
58
0.730561
RUrlus
a31039f4da79a37297db4fae02bc08b2a84540c7
4,547
cpp
C++
src/demo_server.cpp
xiyou-linuxer/demo
e1176dde72be50732e39e289d91a0c14ece964d7
[ "MIT" ]
7
2019-04-26T03:49:55.000Z
2019-04-27T10:03:00.000Z
src/demo_server.cpp
xiyou-linuxer/demo
e1176dde72be50732e39e289d91a0c14ece964d7
[ "MIT" ]
null
null
null
src/demo_server.cpp
xiyou-linuxer/demo
e1176dde72be50732e39e289d91a0c14ece964d7
[ "MIT" ]
null
null
null
#include "demo_server.hpp" #include "statistics.hpp" namespace Demo { bool DemoServer::initNetwork() { Config *config = Config::getInstance(); started_ = true; if (!config->dev_name.empty()) { uint32_t addr = Util::getLocalAddr(config->dev_name.c_str()); if (addr) { listen_ip_ = Util::address2string(addr); LOG(WARNING) << "Demo listen addr: " << listen_ip_ << ":" << config->listen_port; } else { LOG(WARNING) << "Cannot get IP from dev[" << config->dev_name << "], listen 0.0.0.0:" << config->listen_port; } } else { LOG(WARNING) << "dev_name is empty, listen 0.0.0.0:" << config->listen_port; } struct sockaddr_in addr = {0}; uv_ip4_addr(listen_ip_.c_str(), config->listen_port, &addr); int status = uv_tcp_bind(server_, reinterpret_cast<const struct sockaddr *>(&addr), 0); if (status != UV_OK) { LOG(WARNING) << "Tcp Bind failed: " << uv_strerror(status); return false; } status = uv_tcp_nodelay(server_, 1); if (status != UV_OK) { LOG(WARNING) << "Tcp set nodelay failed: " << uv_strerror(status); return false; } status = uv_listen(reinterpret_cast<uv_stream_t *>(server_), DEFAULT_BACKLOG, onNewConnection); if (status != UV_OK) { LOG(WARNING) << "Tcp Listen failed: " << uv_strerror(status); return false; } listen_addr_ = listen_ip_ + ":" + std::to_string(config->listen_port); return true; } void DemoServer::onNewConnection(uv_stream_t *server, int status) { if (status < 0) { LOG(WARNING) << "New connection error: " << uv_strerror(status); return; } auto *client = new DemoClient(server->loop); if (uv_accept(server, client->getUvStream()) == UV_OK) { Statistics::getInstance()->incrConnectionsCount(); client->updateClientInfo(); client->getUvHandle()->data = client; LOG(INFO) << "Accept a new connection: " << client->toString(); uv_read_start(client->getUvStream(), allocBuffer, onConnectionRead); } else { uv_close(client->getUvHandle(), onClose); } } void DemoServer::allocBuffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { DemoClient *client = reinterpret_cast<DemoClient *>(handle->data); Buffer *buffer = client->getReadBuffer(); size_t readable = buffer->readableBytes(); if (readable < CLIENT_READ_BUFFER_MAX) { buffer->ensureWritableBytes(suggested_size); *buf = uv_buf_init(buffer->beginWrite(), static_cast<unsigned int >(buffer->writableBytes())); } else { LOG(WARNING) << "Client read_buffer.size[" << readable << "]> CLIENT_READ_BUFFER_MAX[" << CLIENT_READ_BUFFER_MAX << "], force close it: " << client->toString(); *buf = uv_buf_init(NULL, 0); // close in on_connection_read } } void DemoServer::onConnectionRead(uv_stream_t *stream, ssize_t nread, UNUSED const uv_buf_t *buf) { if (nread > 0) { DemoClient *client = reinterpret_cast<DemoClient *>(stream->data); Buffer *buffer = client->getReadBuffer(); buffer->incrWriteIndex(static_cast<size_t >(nread)); int decode_ret = 0; while (buffer->readableBytes() > 0) { // decode } if (decode_ret == 0) { // ... } else if (decode_ret == 1) { // ... } else { LOG(WARNING) << "Connection protocol decode error[" << decode_ret << "], abort it: " << client->toString(); uv_close(reinterpret_cast<uv_handle_t *>(stream), onClose); } } else { if (nread < 0) { if (nread != UV_EOF) { LOG(WARNING) << "Connection read error: " << uv_strerror(static_cast<int>(nread)); } uv_close(reinterpret_cast<uv_handle_t *>(stream), onClose); } } } void DemoServer::writeCallback(uv_write_t *req, int status) { if (status < 0) { LOG(WARNING) << "Connection write error: " << uv_strerror(status); } delete req; } void DemoServer::onClose(uv_handle_t *handle) { Statistics::getInstance()->decrConnectionsCount(); DemoClient *client = reinterpret_cast<DemoClient *>(handle->data); LOG(INFO) << "Close connection: " << client->toString(); delete client; } void DemoServer::onAsyncClose(uv_async_t* handle) { DemoServer *server = reinterpret_cast<DemoServer *>(handle->data); server->stopUv(); } } // namespace Demo
37.270492
121
0.607873
xiyou-linuxer
a3104b9f1b01da13d583e52f6c986cac2a0d97a9
10,665
cpp
C++
printtext.cpp
Begasus/beos-fakBEtur
2cfd06d73801a218f35c0591f071f9fcfa11a747
[ "MIT" ]
null
null
null
printtext.cpp
Begasus/beos-fakBEtur
2cfd06d73801a218f35c0591f071f9fcfa11a747
[ "MIT" ]
null
null
null
printtext.cpp
Begasus/beos-fakBEtur
2cfd06d73801a218f35c0591f071f9fcfa11a747
[ "MIT" ]
null
null
null
// // TODO: // usunąć niepotrzebne .String()? // IDEAS: // szerokosci,parametry dla 80/136 do osobnej tabeli, indeksowac // #include "printtext.h" #include "globals.h" #include <stdio.h> printText::printText(int id, sqlite3 *db, int numkopii) : beFakPrint(id,db,numkopii) { wide = ( p_textcols > 80 ); switch ( p_texteol ) { case 2: eol = "\r"; break; case 1: eol = "\r\n"; break; case 0: default: eol = "\n"; break; } } void printText::Go(void) { BString tmp, out, line, hline, hline2; out = ""; line="", tmp = ""; //[1] nazwasprzedawcy .... miejscewyst,datawyst line = own[0].String(); tmp = fdata->ogol[0].String(); tmp += ", "; tmp += fdata->ogol[2]; line = rightAlign(line, tmp); line += ELINE; out += line; //[2] kodsprz miejscesprz, adres sprz line = own[3].String(); line += " "; line += own[4].String(); line += ", "; line += own[2].String(); line += ELINE; out += line; //[3] telsprz, emailsprz line = "tel. "; line += own[5].String(); line += ", "; line += own[6].String(); line += ELINE; out += line; //[4] banksprz kontosprz line = own[9].String(); line += " "; line += own[10].String(); line += ELINE; out += line; //[5] [REGON: XXX][ NIP XXX] line = ""; if (own[8].Length()>0) { line += "REGON: "; line += own[8].String(); } if (own[7].Length()>0) { if (line.Length()>0) line += ", "; line += "NIP: "; line += own[7].String(); } if (line.Length()>0) line += ELINE; out += line; //[6] [wolna/missing] out += ELINE; //[7] [wolna] out += ELINE; //[8] ...Faktura VAT nr XXX.... line = "Faktura VAT nr "; line += fdata->nazwa.String(); line = centerAlign(line); line += ELINE; out += line; //[9] ...[typ faktury]... line = centerAlign(typfaktury); line += ELINE; out += line; //[10] [wolna] out += ELINE; //[11] Nabywca: [nabywca] line = "Nabywca: "; line += fdata->odata[0].String(); line += ELINE; out += line; //[12] Adres: [adresnab], [kodnab] [miejscnab] line = " Adres: "; line += fdata->odata[2].String(); line += ", "; line += fdata->odata[3]; line += " "; line += fdata->odata[4]; line += ELINE; out += line; //[13] [telnab], [emailnab] line = " tel. "; line += fdata->odata[5].String(); line += ", "; line += fdata->odata[6]; line += ELINE; out += line; //[13] [NIP: [nipnab]], [REGON: [regonab]] line = " "; if (fdata->odata[8].Length()>0) { line += "REGON: "; line += fdata->odata[8].String(); } if (fdata->odata[7].Length()>0) { if (line.Length()>0) line += ", "; line += "NIP: "; line += fdata->odata[7].String(); } if (line.Length()>0) line += ELINE; out += line; //[14] [wolna] out += ELINE; //[15] sposob zaplaty [sposob]...termin zaplaty [termin] line = "Sposób zapłaty: "; line += fdata->ogol[5]; tmp = "Termin zapłaty: "; tmp += fdata->ogol[6]; line = halfAlign(line, tmp); line += ELINE; out += line; //[16] data sprzedazy [data]...srodek transportu [srodek] line = "Data sprzedaży: "; line += fdata->ogol[3]; tmp = "Środek transp.: "; tmp += fdata->ogol[4]; line = halfAlign(line, tmp); line += ELINE; out += line; //[17] [wolna] out += ELINE; //[] [tabela] // [naglowek] if (wide) { hline = "+----+-----------------------------------------+-------------+---------+------+-------+----------+----------+---+----------+----------+"; hline += ELINE; out += hline; line = "| | | | | | | | | | | |"; line += ELINE; out += line; line = "| Lp | Nazwa towaru/uslugi | PKWiU | Ilosc | Jm | Rabat | Cena z | Wartosc |VAT| Wartosc | Wartosc |"; line += ELINE; out += line; line = "| | | | | | (%) | rabatem | netto | | VAT | brutto |"; line += ELINE; out += line; out += hline; } else { hline = "+--+-------+--------+-------+----+-----+--------+--------+---+--------+--------+"; hline += ELINE; out += hline; line = "| | | | | | | | | | | |"; line += ELINE; out += line; line = "|Lp| Nazwa | PKWiU | Ilosc | Jm | Rab.| Cena z | Wartosc|VAT| Wartosc| Wartosc|"; line += ELINE; out += line; line = "| | | | | | (%) | rab. | netto | | VAT | brutto |"; line += ELINE; out += line; out += hline; } // iteruj po towarach pozfakitem *cur = flist->start; while (cur!=NULL) { line = "|"; if (wide) { // lp tmp = ""; tmp << cur->lp; line += fitAlignR(tmp,4,true); line += "|"; // nazwa line += fitAlignL(cur->data->data[1],41,true); line += "|"; // pkwiu line += fitAlignR(cur->data->data[2],13,true); line += "|"; // ilosc line += fitAlignR(cur->data->data[3],9,true); line += "|"; // jm line += fitAlignR(cur->data->data[4],6,true); line += "|"; // rabat line += fitAlignR(cur->data->data[5],7,true); line += "|"; // cenajednostkowa line += fitAlignR(cur->data->data[6],10,true); line += "|"; // w.netto line += fitAlignR(cur->data->data[7],10,true); line += "|"; // vat % line += fitAlignR(cur->data->data[8],3); line += "|"; // w.vat line += fitAlignR(cur->data->data[9],10,true); line += "|"; // w.brutto line += fitAlignR(cur->data->data[10],10,true); line += "|"; } else { // lp tmp = ""; tmp << cur->lp; line += fitAlignR(tmp,2); line += "|"; // nazwa line += fitAlignL(cur->data->data[1],7); line += "|"; // pkwiu line += fitAlignR(cur->data->data[2],8); line += "|"; // ilosc line += fitAlignR(cur->data->data[3],7); line += "|"; // jm line += fitAlignR(cur->data->data[4],4); line += "|"; // rabat line += fitAlignR(cur->data->data[5],5); line += "|"; // cenajednostkowa line += fitAlignR(cur->data->data[6],8); line += "|"; // w.netto line += fitAlignR(cur->data->data[7],8); line += "|"; // vat % line += fitAlignR(cur->data->data[8],3); line += "|"; // w.vat line += fitAlignR(cur->data->data[9],8); line += "|"; // w.brutto line += fitAlignR(cur->data->data[10],8); line += "|"; } updateSummary(cur->data->data[7].String(), cur->data->vatid, cur->data->data[9].String(), cur->data->data[10].String()); // printf("result: %i, %s\n", ret, dbErrMsg); cur = cur->nxt; line += ELINE; out += line; } //[] stopka out += hline; // podsumuj makeSummary(); //[] wypisac podsumowanie for (int i=0;i<fsummarows;i++) { if (wide) { line = leftFill("|", 97); line += fitAlignR(fsumma[i].summa[0],10,true); line += "|"; line += fitAlignR(fsumma[i].summa[1],3); line += "|"; line += fitAlignR(fsumma[i].summa[2],10,true); line += "|"; line += fitAlignR(fsumma[i].summa[3],10,true); line += "|"; } else { line = leftFill("|", 48); line += fitAlignR(fsumma[i].summa[0],8); line += "|"; line += fitAlignR(fsumma[i].summa[1],3); line += "|"; line += fitAlignR(fsumma[i].summa[2],8); line += "|"; line += fitAlignR(fsumma[i].summa[3],8); line += "|"; } line += ELINE; out += line; } //[] oddzielenie od podsumowania if (wide) { hline2 = leftFill("+----------+---+----------+----------+", 97); hline2 += ELINE; } else { hline2 = leftFill("+--------+---+--------+--------+", 48); hline2 += ELINE; } out += hline2; //[] RAZEM if (wide) { line = leftFill("RAZEM: |", 97-7); line += fitAlignR(razem.summa[0],10,true); line += "|"; line += fitAlignR(razem.summa[1],3); line += "|"; line += fitAlignR(razem.summa[2],10,true); line += "|"; line += fitAlignR(razem.summa[3],10,true); line += "|"; } else { line = leftFill("RAZEM: |", 48-7); line += fitAlignR(razem.summa[0],8); line += "|"; line += fitAlignR(razem.summa[1],3); line += "|"; line += fitAlignR(razem.summa[2],8); line += "|"; line += fitAlignR(razem.summa[3],8); line += "|"; } line += ELINE; out += line; //[] stopka out += hline2; //[] wolna out += ELINE; //[] Do zapłaty: [kwota], lub polaczone z RAZEM | line = " Do zapłaty zł: "; line += razem.summa[3]; line += ELINE; out += line; //[] Słownie: [kwota] lib polaczone z +---+---+ pod razem line = " Słownie: "; line += slownie(razem.summa[3].String()); line += ELINE; out += line; //[] wolna x 3 out += ELINE; out += ELINE; out += ELINE; //[] uwagi: [uwagi, multiline, wrap!] //[] wystawil: [wystawil]...odebral: line = " wystawił: "; line += fdata->ogol[1]; tmp = "odebrał: "; line = halfAlign(line, tmp); line += ELINE; out += line; //[] ---------- -------------- line = " ----------------------"; tmp = " ----------------------"; line = halfAlign(line, tmp); line += ELINE; out += line; //[] podpis osoby upow. podpis osoby upow. line = " podpis osoby upow."; tmp = " podpis osoby upow."; line = halfAlign(line, tmp); line += ELINE; out += line; //[] wolna out += ELINE; //printf("---------------------\n"); //printf("%s",out.String()); //printf("---------------------\n"); tmp = "faktura-"; tmp += makeName(); tmp += ".txt"; saveToFile(tmp.String(), &out); } const char *printText::rightAlign(const BString line, const BString right) { static BString tmp; int j; tmp = line; j = line.CountChars() + right.CountChars(); if (j < p_textcols) { j = p_textcols-j; while (j>0) { tmp += " "; j--; }; } tmp += right; return tmp.String(); } const char *printText::centerAlign(const BString line) { static BString tmp; int j; tmp = ""; j = p_textcols/2 - line.CountChars()/2; while (j>0) { tmp += " "; j--; } tmp += line; return tmp.String(); } const char *printText::halfAlign(const BString line, const BString right) { static BString tmp; int j; tmp = line; j = p_textcols/2 - line.CountChars(); while (j>0) { tmp += " "; j--; } tmp += right; return tmp.String(); } const char *printText::fitAlignR(const BString line, int len, bool space) { static BString tmp; int j; if (space) len--; tmp = line; tmp.Truncate(len); j = tmp.CountChars(); if (j<len) { j = len-j; while (j>0) { tmp.Prepend(" "); j--; } } if (space) tmp.Append(" "); return tmp.String(); } const char *printText::fitAlignL(const BString line, int len, bool space) { static BString tmp; int j; tmp = line; if (space) tmp.Prepend(" "); tmp.Truncate(len); j = len-tmp.CountChars(); while (j>0) { tmp.Append(" "); j--; } return tmp.String(); } const char *printText::leftFill(const BString line, int spaces) { static BString tmp; int j; tmp = ""; j = spaces; while (j>0) { tmp.Append(" "); j--; } tmp += line; return tmp.String(); }
30.73487
166
0.509423
Begasus
a31275d7856913dafa17f5eacc7022eb0da992c5
807
hpp
C++
include/domains/tests/State_test.hpp
vieiramanoel/TP1-2019-1
4d68de98efcb0b77d921b3b0dc4c922a41ac7db3
[ "MIT" ]
null
null
null
include/domains/tests/State_test.hpp
vieiramanoel/TP1-2019-1
4d68de98efcb0b77d921b3b0dc4c922a41ac7db3
[ "MIT" ]
null
null
null
include/domains/tests/State_test.hpp
vieiramanoel/TP1-2019-1
4d68de98efcb0b77d921b3b0dc4c922a41ac7db3
[ "MIT" ]
null
null
null
#include "domains/State.hpp" #include <gtest/gtest.h> #include <stdexcept> #include <string> TEST(StateTest, StateWithNumbers) { ASSERT_THROW(State("14"), std::invalid_argument); ASSERT_THROW(State("154"), std::invalid_argument); } TEST(StateTest, StateWithMoreLetters) { ASSERT_THROW(State("DFT"), std::invalid_argument); } // Ludum Dare TEST(StateTest, StateWith1digit) { ASSERT_THROW(State("D"), std::invalid_argument); } TEST(StateTest, StateDontExist) { ASSERT_THROW(State("AB"), std::invalid_argument) << "Correct Format but dont exist that State!"; } TEST(StateTest, CorrectScenario) { ASSERT_NO_THROW(State("DF")) << "didnt throw invalid_Argument->Correct input!"; } State n("DF"); TEST(StateTestTest, TestingReturns) { EXPECT_EQ("DF", n.getState()); }
25.21875
70
0.702602
vieiramanoel
a312fd88cd17580a38289e199cbd1f8d96b02de7
104,535
cpp
C++
lib/test/public-api.cpp
K-H-Ismail/irritator
ff9f1706f5d8c93c93131259e91b8db53a6ea146
[ "BSL-1.0" ]
null
null
null
lib/test/public-api.cpp
K-H-Ismail/irritator
ff9f1706f5d8c93c93131259e91b8db53a6ea146
[ "BSL-1.0" ]
null
null
null
lib/test/public-api.cpp
K-H-Ismail/irritator
ff9f1706f5d8c93c93131259e91b8db53a6ea146
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2020 INRA 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 <irritator/core.hpp> #include <irritator/io.hpp> #include <boost/ut.hpp> #include <fmt/format.h> #include <iostream> struct file_output { file_output(const char* file_path) noexcept : os(std::fopen(file_path, "w")) {} ~file_output() noexcept { if (os) std::fclose(os); } std::FILE* os = nullptr; }; void file_output_initialize(const irt::observer& obs, const irt::time /*t*/) noexcept { if (!obs.user_data) return; auto* output = reinterpret_cast<file_output*>(obs.user_data); fmt::print(output->os, "t,{}\n", obs.name.c_str()); } void file_output_observe(const irt::observer& obs, const irt::time t, const irt::message& msg) noexcept { if (!obs.user_data) return; auto* output = reinterpret_cast<file_output*>(obs.user_data); fmt::print(output->os, "{},{}\n", t, msg.real[0]); } int main() { using namespace boost::ut; "model_constepxr"_test = [] { expect(irt::is_detected_v<irt::initialize_function_t, irt::counter> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::counter> == false); expect(irt::is_detected_v<irt::transition_function_t, irt::counter> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::counter> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::counter> == false); expect(irt::is_detected_v<irt::initialize_function_t, irt::generator> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::generator> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::generator> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::generator> == false); expect(irt::is_detected_v<irt::has_output_port_t, irt::generator> == true); expect(irt::is_detected_v<irt::initialize_function_t, irt::adder_2> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::adder_2> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::adder_2> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::adder_2> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::adder_2> == true); expect(irt::is_detected_v<irt::initialize_function_t, irt::adder_3> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::adder_3> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::adder_3> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::adder_3> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::adder_3> == true); expect(irt::is_detected_v<irt::initialize_function_t, irt::adder_4> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::adder_4> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::adder_4> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::adder_4> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::adder_4> == true); expect(irt::is_detected_v<irt::initialize_function_t, irt::mult_2> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::mult_2> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::mult_2> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::mult_2> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::mult_2> == true); expect(irt::is_detected_v<irt::initialize_function_t, irt::mult_3> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::mult_3> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::mult_3> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::mult_3> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::mult_3> == true); expect(irt::is_detected_v<irt::initialize_function_t, irt::mult_4> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::mult_4> == true); expect(irt::is_detected_v<irt::transition_function_t, irt::mult_4> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::mult_4> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::mult_4> == true); expect( irt::is_detected_v<irt::initialize_function_t, irt::integrator> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::integrator> == true); expect( irt::is_detected_v<irt::transition_function_t, irt::integrator> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::integrator> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::integrator> == true); expect( irt::is_detected_v<irt::initialize_function_t, irt::quantifier> == true); expect(irt::is_detected_v<irt::lambda_function_t, irt::quantifier> == true); expect( irt::is_detected_v<irt::transition_function_t, irt::quantifier> == true); expect(irt::is_detected_v<irt::has_input_port_t, irt::quantifier> == true); expect(irt::is_detected_v<irt::has_output_port_t, irt::quantifier> == true); }; "status"_test = [] { irt::status s1 = irt::status::success; expect(irt::is_success(s1) == true); expect(irt::is_bad(s1) == false); irt::status s2 = irt::status::block_allocator_not_enough_memory; expect(irt::is_success(s2) == false); expect(irt::is_bad(s2) == true); }; "time"_test = [] { expect(irt::time_domain<irt::time>::infinity > irt::time_domain<irt::time>::zero); expect(irt::time_domain<irt::time>::zero > irt::time_domain<irt::time>::negative_infinity); }; "small_string"_test = [] { irt::small_string<8> f1; expect(f1.capacity() == 8_ul); expect(f1 == ""); expect(f1.size() == 0_ul); f1.append("ok"); expect(f1 == "ok"); expect(f1.size() == 2_ul); f1.append("ok"); expect(f1 == "okok"); expect(f1.size() == 4_ul); f1.append("1234"); expect(f1 == "okok123"); expect(f1.size() == 7_ul); irt::small_string<8> f2(f1); expect(f2 == "okok123"); expect(f2.size() == 7_ul); expect(f1.c_str() != f2.c_str()); irt::small_string<8> f3("012345678"); expect(f3 == "0123456"); expect(f3.size() == 7_ul); f3.clear(); expect(f3 == ""); expect(f3.size() == 0_ul); f3 = f2; expect(f3 == "okok123"); expect(f3.size() == 7_ul); }; "list"_test = [] { irt::flat_list<int>::allocator_type allocator; expect(is_success(allocator.init(32))); irt::flat_list<int> lst(&allocator); lst.emplace_front(5); lst.emplace_front(4); lst.emplace_front(3); lst.emplace_front(2); lst.emplace_front(1); { int i = 1; for (auto it = lst.begin(); it != lst.end(); ++it) expect(*it == i++); } lst.pop_front(); { int i = 2; for (auto it = lst.begin(); it != lst.end(); ++it) expect(*it == i++); } }; "double_list"_test = [] { irt::flat_double_list<int>::allocator_type allocator; expect(is_success(allocator.init(32))); irt::flat_double_list<int> lst(&allocator); expect(lst.empty()); expect(lst.begin() == lst.end()); lst.emplace_front(0); expect(lst.begin() == --lst.end()); expect(++lst.begin() == lst.end()); lst.clear(); expect(lst.empty()); expect(lst.begin() == lst.end()); lst.emplace_front(5); lst.emplace_front(4); lst.emplace_front(3); lst.emplace_front(2); lst.emplace_front(1); lst.emplace_back(6); lst.emplace_back(7); lst.emplace_back(8); { int i = 1; for (auto it = lst.begin(); it != lst.end(); ++it) expect(*it == i++); } lst.pop_front(); { int i = 2; for (auto it = lst.begin(); it != lst.end(); ++it) expect(*it == i++); } { auto it = lst.begin(); expect(*it == 2); --it; expect(it == lst.end()); --it; expect(it == --lst.end()); } { auto it = lst.end(); expect(it == lst.end()); --it; expect(*it == 8); --it; expect(*it == 7); } }; "array_api"_test = [] { struct position { position() noexcept = default; position(int x_, int y_) : x(x_) , y(y_) {} int x = 0, y = 0; }; irt::array<position> positions; !expect(irt::status::success == positions.init(16u)); expect(positions.size() == 16_u); expect(positions.capacity() == 16u); for (int i = 0; i != 16; ++i) { positions[i].x = i; positions[i].y = i; } for (int i = 0; i != 16; ++i) { expect(positions[i].x == i); expect(positions[i].y == i); } }; "vector_api"_test = [] { struct position { position() noexcept = default; position(int x_, int y_) : x(x_) , y(y_) {} int x = 0, y = 0; }; irt::vector<position> positions; !expect(irt::status::success == positions.init(16u)); expect(positions.size() == 0_u); expect(positions.capacity() == 16u); { expect(positions.can_alloc(1u)); auto it = positions.emplace_back(0, 1); expect(positions.size() == 1_u); expect(positions.begin() == it); expect(it->x == 0); expect(it->y == 1); } { auto ret = positions.try_emplace_back(2, 3); expect(ret.first == true); expect(ret.second == positions.begin() + 1); expect(positions.size() == 2_u); expect(positions.begin()->x == 0); expect(positions.begin()->y == 1); expect((positions.begin() + 1)->x == 2); expect((positions.begin() + 1)->y == 3); } { auto it = positions.erase_and_swap(positions.begin()); expect(positions.size() == 1_u); expect(it == positions.begin()); expect(it->x == 2); expect(it->y == 3); } positions.clear(); expect(positions.size() == 0_ul); expect(positions.capacity() == 16_u); expect(positions.can_alloc(16u)); for (int i = 0; i != 16; ++i) positions.emplace_back(i, i); auto ret = positions.try_emplace_back(16, 16); expect(ret.first == false); expect(positions.size() == 16_ul); expect(positions.capacity() == 16_u); auto it = positions.begin(); while (it != positions.end()) it = positions.erase_and_swap(it); expect(positions.size() == 0_ul); expect(positions.capacity() == 16_u); }; "data_array_api"_test = [] { struct position { position() = default; constexpr position(float x_) : x(x_) {} float x; }; enum class position_id : std::uint64_t { }; irt::data_array<position, position_id> array; expect(array.max_size() == 0); expect(array.max_used() == 0); expect(array.capacity() == 0); expect(array.next_key() == 1); expect(array.is_free_list_empty()); bool is_init = irt::is_success(array.init(3)); expect(array.max_size() == 0); expect(array.max_used() == 0); expect(array.capacity() == 3); expect(array.next_key() == 1); expect(array.is_free_list_empty()); expect(is_init); { auto& first = array.alloc(); first.x = 0.f; expect(array.max_size() == 1); expect(array.max_used() == 1); expect(array.capacity() == 3); expect(array.next_key() == 2); expect(array.is_free_list_empty()); auto& second = array.alloc(); expect(array.max_size() == 2); expect(array.max_used() == 2); expect(array.capacity() == 3); expect(array.next_key() == 3); expect(array.is_free_list_empty()); second.x = 1.f; auto& third = array.alloc(); expect(array.max_size() == 3); expect(array.max_used() == 3); expect(array.capacity() == 3); expect(array.next_key() == 4); expect(array.is_free_list_empty()); third.x = 2.f; expect(array.full()); } array.clear(); expect(array.max_size() == 0); expect(array.max_used() == 0); expect(array.capacity() == 3); expect(array.next_key() == 1); expect(array.is_free_list_empty()); is_init = irt::is_success(array.init(3)); { auto& d1 = array.alloc(1.f); auto& d2 = array.alloc(2.f); auto& d3 = array.alloc(3.f); expect(array.max_size() == 3); expect(array.max_used() == 3); expect(array.capacity() == 3); expect(array.next_key() == 4); expect(array.is_free_list_empty()); array.free(d1); expect(array.max_size() == 2); expect(array.max_used() == 3); expect(array.capacity() == 3); expect(array.next_key() == 4); expect(!array.is_free_list_empty()); array.free(d2); expect(array.max_size() == 1); expect(array.max_used() == 3); expect(array.capacity() == 3); expect(array.next_key() == 4); expect(!array.is_free_list_empty()); array.free(d3); expect(array.max_size() == 0); expect(array.max_used() == 3); expect(array.capacity() == 3); expect(array.next_key() == 4); expect(!array.is_free_list_empty()); auto& n1 = array.alloc(); auto& n2 = array.alloc(); auto& n3 = array.alloc(); expect(irt::get_index(array.get_id(n1)) == 2_u); expect(irt::get_index(array.get_id(n2)) == 1_u); expect(irt::get_index(array.get_id(n3)) == 0_u); expect(array.max_size() == 3); expect(array.max_used() == 3); expect(array.capacity() == 3); expect(array.next_key() == 7); expect(array.is_free_list_empty()); } }; "message"_test = [] { { irt::message vdouble; expect(vdouble.real[0] == 0.0); expect(vdouble.real[1] == 0.0); expect(vdouble.real[2] == 0.0); expect(vdouble.size() == 0_ul); } { irt::message vdouble(1.0); expect(vdouble[0] == 1.0); expect(vdouble.size() == 1_ul); } { irt::message vdouble(0.0, 1.0); expect(vdouble[0] == 0.0); expect(vdouble[1] == 1.0); expect(vdouble.size() == 2_ul); } { irt::message vdouble(1.0, 2.0, 3.0); expect(vdouble[0] == 1.0); expect(vdouble[1] == 2.0); expect(vdouble[2] == 3.0); expect(vdouble.size() == 3_ul); } }; "heap_order"_test = [] { irt::heap h; h.init(4u); irt::heap::handle i1 = h.insert(0.0, irt::model_id{ 0 }); irt::heap::handle i2 = h.insert(1.0, irt::model_id{ 1 }); irt::heap::handle i3 = h.insert(-1.0, irt::model_id{ 2 }); irt::heap::handle i4 = h.insert(2.0, irt::model_id{ 3 }); expect(h.full()); expect(i1->tn == 0.0_d); expect(i2->tn == 1.0_d); expect(i3->tn == -1.0_d); expect(i4->tn == 2.0_d); expect(h.top() == i3); h.pop(); expect(h.top() == i1); h.pop(); expect(h.top() == i2); h.pop(); expect(h.top() == i4); h.pop(); expect(h.empty()); expect(!h.full()); }; "heap_insert_pop"_test = [] { irt::heap h; h.init(4u); irt::heap::handle i1 = h.insert(0.0, irt::model_id{ 0 }); irt::heap::handle i2 = h.insert(1.0, irt::model_id{ 1 }); irt::heap::handle i3 = h.insert(-1.0, irt::model_id{ 2 }); irt::heap::handle i4 = h.insert(2.0, irt::model_id{ 3 }); expect(i1 != nullptr); expect(i2 != nullptr); expect(i3 != nullptr); expect(i4 != nullptr); expect(!h.empty()); expect(h.top() == i3); h.pop(); // remove i3 h.pop(); // rmeove i1 expect(h.top() == i2); i3->tn = -10.0; h.insert(i3); i1->tn = -1.0; h.insert(i1); expect(h.top() == i3); h.pop(); expect(h.top() == i1); h.pop(); expect(h.top() == i2); h.pop(); expect(h.top() == i4); h.pop(); expect(h.empty()); }; "heap_with_equality"_test = [] { irt::heap h; h.init(256u); for (double t = 0; t < 100.0; ++t) h.insert(t, irt::model_id{ static_cast<unsigned>(t) }); expect(h.size() == 100_ul); h.insert(50.0, irt::model_id{ 502 }); h.insert(50.0, irt::model_id{ 503 }); h.insert(50.0, irt::model_id{ 504 }); expect(h.size() == 103_ul); for (double t = 0.0; t < 50.0; ++t) { expect(h.top()->tn == t); h.pop(); } expect(h.top()->tn == 50.0_d); h.pop(); expect(h.top()->tn == 50.0_d); h.pop(); expect(h.top()->tn == 50.0_d); h.pop(); expect(h.top()->tn == 50.0_d); h.pop(); for (double t = 51.0; t < 100.0; ++t) { expect(h.top()->tn == t); h.pop(); } }; "constant_simulation"_test = [] { irt::simulation sim; expect(irt::is_success(sim.init(16lu, 256lu))); expect(sim.constant_models.can_alloc(2)); expect(sim.counter_models.can_alloc(1)); auto& cnt = sim.counter_models.alloc(); auto& c1 = sim.constant_models.alloc(); auto& c2 = sim.constant_models.alloc(); c1.default_value = 0.0; c2.default_value = 0.0; expect(sim.models.can_alloc(3)); expect(irt::is_success(sim.alloc(cnt, sim.counter_models.get_id(cnt)))); expect(irt::is_success(sim.alloc(c1, sim.constant_models.get_id(c1)))); expect(irt::is_success(sim.alloc(c2, sim.constant_models.get_id(c2)))); expect(sim.connect(c1.y[0], cnt.x[0]) == irt::status::success); expect(sim.connect(c2.y[0], cnt.x[0]) == irt::status::success); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); irt::status st; do { st = sim.run(t); expect(irt::is_success(st)); } while (t < sim.end); expect(cnt.number == 2_ul); }; "cross_simulation"_test = [] { irt::simulation sim; expect(irt::is_success(sim.init(16lu, 256lu))); expect(sim.counter_models.can_alloc(1)); expect(sim.cross_models.can_alloc(1)); expect(sim.constant_models.can_alloc(1)); auto& cnt = sim.counter_models.alloc(); auto& cross1 = sim.cross_models.alloc(); auto& c1 = sim.constant_models.alloc(); // auto& value = sim.messages.alloc(3.0); // auto& threshold = sim.messages.alloc(0.0); // // c1.init[0] = sim.messages.get_id(value); // cross1.init[0] = sim.messages.get_id(threshold); c1.default_value = 3.0; cross1.default_threshold = 0.0; expect(sim.models.can_alloc(3)); expect(irt::is_success(sim.alloc(cnt, sim.counter_models.get_id(cnt)))); expect( irt::is_success(sim.alloc(cross1, sim.cross_models.get_id(cross1)))); expect(irt::is_success(sim.alloc(c1, sim.constant_models.get_id(c1)))); expect(sim.connect(c1.y[0], cross1.x[0]) == irt::status::success); expect(sim.connect(c1.y[0], cross1.x[1]) == irt::status::success); expect(sim.connect(c1.y[0], cross1.x[2]) == irt::status::success); expect(sim.connect(cross1.y[0], cnt.x[0]) == irt::status::success); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); irt::status st; do { st = sim.run(t); expect(irt::is_success(st)); } while (t < sim.end); expect(cnt.number == 2_ul); }; "generator_counter_simluation"_test = [] { fmt::print("generator_counter_simluation\n"); irt::simulation sim; expect(irt::is_success(sim.init(16lu, 256lu))); expect(sim.generator_models.can_alloc(1)); expect(sim.counter_models.can_alloc(1)); auto& gen = sim.generator_models.alloc(); auto& cnt = sim.counter_models.alloc(); expect(sim.models.can_alloc(2)); expect( irt::is_success(sim.alloc(gen, sim.generator_models.get_id(gen)))); expect(irt::is_success(sim.alloc(cnt, sim.counter_models.get_id(cnt)))); expect(sim.connect(gen.y[0], cnt.x[0]) == irt::status::success); expect(sim.begin == irt::time_domain<irt::time>::zero); expect(sim.end == irt::time_domain<irt::time>::infinity); sim.end = 10.0; irt::time t = sim.begin; expect(sim.initialize(t) == irt::status::success); irt::status st; do { st = sim.run(t); expect(irt::is_success(st)); expect(cnt.number <= static_cast<irt::i64>(t)); } while (t < sim.end); expect(cnt.number == 9_ul); }; "time_func"_test = [] { fmt::print("time_func\n"); irt::simulation sim; const double duration = 30; expect(irt::is_success(sim.init(16lu, 256lu))); expect(sim.time_func_models.can_alloc(1)); expect(sim.counter_models.can_alloc(1)); auto& time_fun = sim.time_func_models.alloc(); auto& cnt = sim.counter_models.alloc(); time_fun.default_f = &irt::square_time_function; time_fun.default_sigma = 0.1; expect(sim.models.can_alloc(2)); expect(irt::is_success( sim.alloc(time_fun, sim.time_func_models.get_id(time_fun)))); expect(irt::is_success(sim.alloc(cnt, sim.counter_models.get_id(cnt)))); expect(sim.connect(time_fun.y[0], cnt.x[0]) == irt::status::success); irt::time t{ 0 }; !expect(sim.initialize(t) == irt::status::success); double c = 0.0; do { auto st = sim.run(t); !expect(irt::is_success(st)); expect(time_fun.value == t * t); c++; } while (t < duration); expect(c == 2.0 * duration / time_fun.default_sigma - 1.0); }; "time_func_sin"_test = [] { fmt::print("time_func_sin\n"); const double pi = std::acos(-1); const double f0 = 0.1; const double duration = 30; irt::simulation sim; expect(irt::is_success(sim.init(16lu, 256lu))); expect(sim.time_func_models.can_alloc(1)); expect(sim.counter_models.can_alloc(1)); auto& time_fun = sim.time_func_models.alloc(); auto& cnt = sim.counter_models.alloc(); time_fun.default_f = &irt::sin_time_function; time_fun.default_sigma = 0.1; expect(sim.models.can_alloc(2)); expect(irt::is_success( sim.alloc(time_fun, sim.time_func_models.get_id(time_fun)))); expect(irt::is_success(sim.alloc(cnt, sim.counter_models.get_id(cnt)))); expect(sim.connect(time_fun.y[0], cnt.x[0]) == irt::status::success); irt::time t{ 0 }; !expect(sim.initialize(t) == irt::status::success); double c = 0; do { auto st = sim.run(t); !expect(irt::is_success(st)); expect(time_fun.value == std::sin(2 * pi * f0 * t)); c++; } while (t < duration); expect(c == 2.0 * duration / time_fun.default_sigma - 1.0); }; "time_func_sin"_test = [] { const double pi = std::acos(-1); const double f0 = 0.1; irt::simulation sim; expect(irt::is_success(sim.init(16lu, 256lu))); expect(sim.time_func_models.can_alloc(1)); expect(sim.counter_models.can_alloc(1)); auto& time_fun = sim.time_func_models.alloc(); auto& cnt = sim.counter_models.alloc(); time_fun.default_f = &irt::sin_time_function; expect(sim.models.can_alloc(2)); expect(irt::is_success( sim.alloc(time_fun, sim.time_func_models.get_id(time_fun)))); expect(irt::is_success(sim.alloc(cnt, sim.counter_models.get_id(cnt)))); expect(sim.connect(time_fun.y[0], cnt.x[0]) == irt::status::success); irt::time t{ 0 }; !expect(sim.initialize(t) == irt::status::success); do { auto st = sim.run(t); !expect(irt::is_success(st)); expect(time_fun.value == std::sin(2 * pi * f0 * t)); //expect(cnt.number <= static_cast<irt::i64>(t)); } while (t < 30); }; "lotka_volterra_simulation"_test = [] { fmt::print("lotka_volterra_simulation\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.adder_2_models.can_alloc(2)); expect(sim.mult_2_models.can_alloc(2)); expect(sim.integrator_models.can_alloc(2)); expect(sim.quantifier_models.can_alloc(2)); auto& sum_a = sim.adder_2_models.alloc(); auto& sum_b = sim.adder_2_models.alloc(); auto& product = sim.mult_2_models.alloc(); auto& integrator_a = sim.integrator_models.alloc(); auto& integrator_b = sim.integrator_models.alloc(); auto& quantifier_a = sim.quantifier_models.alloc(); auto& quantifier_b = sim.quantifier_models.alloc(); integrator_a.default_current_value = 18.0; quantifier_a.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier_a.default_zero_init_offset = true; quantifier_a.default_step_size = 0.01; quantifier_a.default_past_length = 3; integrator_b.default_current_value = 7.0; quantifier_b.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier_b.default_zero_init_offset = true; quantifier_b.default_step_size = 0.01; quantifier_b.default_past_length = 3; product.default_input_coeffs[0] = 1.0; product.default_input_coeffs[1] = 1.0; sum_a.default_input_coeffs[0] = 2.0; sum_a.default_input_coeffs[1] = -0.4; sum_b.default_input_coeffs[0] = -1.0; sum_b.default_input_coeffs[1] = 0.1; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum_a, sim.adder_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.adder_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success( sim.alloc(product, sim.mult_2_models.get_id(product), "prod"))); !expect(irt::is_success(sim.alloc( integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success(sim.alloc( integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"))); !expect(irt::is_success(sim.alloc( quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"))); !expect(irt::is_success(sim.alloc( quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"))); !expect(sim.models.size() == 7_ul); expect(sim.connect(sum_a.y[0], integrator_a.x[1]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], sum_a.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_a.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_b.x[1]) == irt::status::success); expect(sim.connect(quantifier_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(quantifier_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], quantifier_a.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], quantifier_b.x[0]) == irt::status::success); file_output fo_a("lotka-volterra_a.csv"); file_output fo_b("lotka-volterra_b.csv"); expect(fo_a.os != nullptr); expect(fo_b.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 7_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 15.0); }; "izhikevitch_simulation"_test = [] { fmt::print("izhikevitch_simulation\n"); irt::simulation sim; expect(irt::is_success(sim.init(64lu, 256lu))); expect(sim.constant_models.can_alloc(3)); expect(sim.adder_2_models.can_alloc(3)); expect(sim.adder_4_models.can_alloc(1)); expect(sim.mult_2_models.can_alloc(1)); expect(sim.integrator_models.can_alloc(2)); expect(sim.quantifier_models.can_alloc(2)); expect(sim.cross_models.can_alloc(2)); auto& constant = sim.constant_models.alloc(); auto& constant2 = sim.constant_models.alloc(); auto& constant3 = sim.constant_models.alloc(); auto& sum_a = sim.adder_2_models.alloc(); auto& sum_b = sim.adder_2_models.alloc(); auto& sum_c = sim.adder_4_models.alloc(); auto& sum_d = sim.adder_2_models.alloc(); auto& product = sim.mult_2_models.alloc(); auto& integrator_a = sim.integrator_models.alloc(); auto& integrator_b = sim.integrator_models.alloc(); auto& quantifier_a = sim.quantifier_models.alloc(); auto& quantifier_b = sim.quantifier_models.alloc(); auto& cross = sim.cross_models.alloc(); auto& cross2 = sim.cross_models.alloc(); double a = 0.2; double b = 2.0; double c = -56.0; double d = -16.0; double I = -99.0; double vt = 30.0; constant.default_value = 1.0; constant2.default_value = c; constant3.default_value = I; cross.default_threshold = vt; cross2.default_threshold = vt; integrator_a.default_current_value = 0.0; quantifier_a.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier_a.default_zero_init_offset = true; quantifier_a.default_step_size = 0.01; quantifier_a.default_past_length = 3; integrator_b.default_current_value = 0.0; quantifier_b.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier_b.default_zero_init_offset = true; quantifier_b.default_step_size = 0.01; quantifier_b.default_past_length = 3; product.default_input_coeffs[0] = 1.0; product.default_input_coeffs[1] = 1.0; sum_a.default_input_coeffs[0] = 1.0; sum_a.default_input_coeffs[1] = -1.0; sum_b.default_input_coeffs[0] = -a; sum_b.default_input_coeffs[1] = a * b; sum_c.default_input_coeffs[0] = 0.04; sum_c.default_input_coeffs[1] = 5.0; sum_c.default_input_coeffs[2] = 140.0; sum_c.default_input_coeffs[3] = 1.0; sum_d.default_input_coeffs[0] = 1.0; sum_d.default_input_coeffs[1] = d; expect(sim.models.can_alloc(14)); !expect(irt::is_success( sim.alloc(constant3, sim.constant_models.get_id(constant3), "tfun"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "1.0"))); !expect(irt::is_success(sim.alloc( constant2, sim.constant_models.get_id(constant2), "-56.0"))); !expect(irt::is_success( sim.alloc(sum_a, sim.adder_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.adder_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success( sim.alloc(sum_c, sim.adder_4_models.get_id(sum_c), "sum_c"))); !expect(irt::is_success( sim.alloc(sum_d, sim.adder_2_models.get_id(sum_d), "sum_d"))); !expect(irt::is_success( sim.alloc(product, sim.mult_2_models.get_id(product), "prod"))); !expect(irt::is_success(sim.alloc( integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success(sim.alloc( integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"))); !expect(irt::is_success(sim.alloc( quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"))); !expect(irt::is_success(sim.alloc( quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"))); !expect(irt::is_success( sim.alloc(cross, sim.cross_models.get_id(cross), "cross"))); !expect(irt::is_success( sim.alloc(cross2, sim.cross_models.get_id(cross2), "cross2"))); !expect(sim.models.size() == 14_ul); expect(sim.connect(integrator_a.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(constant2.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(cross.y[0], quantifier_a.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], product.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_c.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], sum_c.x[1]) == irt::status::success); expect(sim.connect(cross.y[0], sum_b.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum_c.x[2]) == irt::status::success); expect(sim.connect(constant3.y[0], sum_c.x[3]) == irt::status::success); expect(sim.connect(sum_c.y[0], sum_a.x[0]) == irt::status::success); // expect(sim.connect(integrator_b.y[0], sum_a.x[1]) == // irt::status::success); expect(sim.connect(cross2.y[0], sum_a.x[1]) == irt::status::success); expect(sim.connect(sum_a.y[0], integrator_a.x[1]) == irt::status::success); expect(sim.connect(cross.y[0], integrator_a.x[2]) == irt::status::success); expect(sim.connect(quantifier_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(cross2.y[0], quantifier_b.x[0]) == irt::status::success); expect(sim.connect(cross2.y[0], sum_b.x[0]) == irt::status::success); expect(sim.connect(quantifier_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[1]) == irt::status::success); expect(sim.connect(cross2.y[0], integrator_b.x[2]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross2.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], cross2.x[2]) == irt::status::success); expect(sim.connect(sum_d.y[0], cross2.x[1]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_d.x[0]) == irt::status::success); expect(sim.connect(constant.y[0], sum_d.x[1]) == irt::status::success); file_output fo_a("izhikevitch_a.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), &file_output_initialize, &file_output_observe, nullptr); file_output fo_b("izhikevitch_b.csv"); expect(fo_b.os != nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), &file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(irt::status::success == sim.initialize(t)); !expect(sim.sched.size() == 14_ul); do { irt::status st = sim.run(t); expect(st == irt::status::success); } while (t < 120); }; "lotka_volterra_simulation_qss1"_test = [] { fmt::print("lotka_volterra_simulation_qss1\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss1_wsum_2_models.can_alloc(2)); expect(sim.qss1_multiplier_models.can_alloc(2)); expect(sim.qss1_integrator_models.can_alloc(2)); auto& sum_a = sim.qss1_wsum_2_models.alloc(); auto& sum_b = sim.qss1_wsum_2_models.alloc(); auto& product = sim.qss1_multiplier_models.alloc(); auto& integrator_a = sim.qss1_integrator_models.alloc(); auto& integrator_b = sim.qss1_integrator_models.alloc(); integrator_a.default_X = 18.0; integrator_a.default_dQ = 0.1; integrator_b.default_X = 7.0; integrator_b.default_dQ = 0.1; sum_a.default_input_coeffs[0] = 2.0; sum_a.default_input_coeffs[1] = -0.4; sum_b.default_input_coeffs[0] = -1.0; sum_b.default_input_coeffs[1] = 0.1; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum_a, sim.qss1_wsum_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.qss1_wsum_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success(sim.alloc( product, sim.qss1_multiplier_models.get_id(product), "prod"))); !expect(irt::is_success( sim.alloc(integrator_a, sim.qss1_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success( sim.alloc(integrator_b, sim.qss1_integrator_models.get_id(integrator_b), "int_b"))); !expect(sim.models.size() == 5_ul); expect(sim.connect(sum_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], sum_a.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_a.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_b.x[1]) == irt::status::success); file_output fo_a("lotka-volterra-qss1_a.csv"); file_output fo_b("lotka-volterra-qss1_b.csv"); expect(fo_a.os != nullptr); expect(fo_b.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 15.0); }; "lotka_volterra_simulation_qss2"_test = [] { fmt::print("lotka_volterra_simulation_qss2\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss2_wsum_2_models.can_alloc(2)); expect(sim.qss2_multiplier_models.can_alloc(2)); expect(sim.qss2_integrator_models.can_alloc(2)); auto& sum_a = sim.qss2_wsum_2_models.alloc(); auto& sum_b = sim.qss2_wsum_2_models.alloc(); auto& product = sim.qss2_multiplier_models.alloc(); auto& integrator_a = sim.qss2_integrator_models.alloc(); auto& integrator_b = sim.qss2_integrator_models.alloc(); integrator_a.default_X = 18.0; integrator_a.default_dQ = 0.1; integrator_b.default_X = 7.0; integrator_b.default_dQ = 0.1; sum_a.default_input_coeffs[0] = 2.0; sum_a.default_input_coeffs[1] = -0.4; sum_b.default_input_coeffs[0] = -1.0; sum_b.default_input_coeffs[1] = 0.1; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum_a, sim.qss2_wsum_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.qss2_wsum_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success(sim.alloc( product, sim.qss2_multiplier_models.get_id(product), "prod"))); !expect(irt::is_success( sim.alloc(integrator_a, sim.qss2_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success( sim.alloc(integrator_b, sim.qss2_integrator_models.get_id(integrator_b), "int_b"))); !expect(sim.models.size() == 5_ul); expect(sim.connect(sum_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], sum_a.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_a.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_b.x[1]) == irt::status::success); file_output fo_a("lotka-volterra-qss2_a.csv"); file_output fo_b("lotka-volterra-qss2_b.csv"); expect(fo_a.os != nullptr); expect(fo_b.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 15.0); }; "lif_simulation_qss"_test = [] { fmt::print("lif_simulation_qss\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.adder_2_models.can_alloc(1)); expect(sim.integrator_models.can_alloc(1)); expect(sim.time_func_models.can_alloc(1)); expect(sim.constant_models.can_alloc(1)); expect(sim.cross_models.can_alloc(1)); auto& sum = sim.adder_2_models.alloc(); auto& quantifier = sim.quantifier_models.alloc(); auto& integrator = sim.integrator_models.alloc(); auto& I = sim.time_func_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.cross_models.alloc(); double tau = 10.0; double Vt = 1.0; double V0 = 10.0; double Vr = -V0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant_cross.default_value = Vr; integrator.default_current_value = 0.0; quantifier.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier.default_zero_init_offset = true; quantifier.default_step_size = 0.1; quantifier.default_past_length = 3; I.default_f = &irt::sin_time_function; I.default_sigma = quantifier.default_step_size; cross.default_threshold = Vt; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.adder_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( quantifier, sim.quantifier_models.get_id(quantifier), "qua"))); !expect(irt::is_success(sim.alloc( integrator, sim.integrator_models.get_id(integrator), "int"))); !expect( irt::is_success(sim.alloc(I, sim.time_func_models.get_id(I), "I"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 6_ul); // Connections expect(sim.connect(quantifier.y[0], integrator.x[0]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[0], integrator.x[2]) == irt::status::success); expect(sim.connect(cross.y[0], quantifier.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(I.y[0], sum.x[1]) == irt::status::success); file_output fo_a("lif-qss.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 6_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; "lif_simulation_qss1"_test = [] { fmt::print("lif_simulation_qss1\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss1_wsum_2_models.can_alloc(1)); expect(sim.qss1_integrator_models.can_alloc(1)); expect(sim.constant_models.can_alloc(2)); expect(sim.qss1_cross_models.can_alloc(1)); auto& sum = sim.qss1_wsum_2_models.alloc(); auto& integrator = sim.qss1_integrator_models.alloc(); auto& constant = sim.constant_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.qss1_cross_models.alloc(); double tau = 10.0; double Vt = 1.0; double V0 = 10.0; double Vr = 0.0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant.default_value = 1.0; constant_cross.default_value = Vr; integrator.default_X = 0.0; integrator.default_dQ = 0.001; cross.default_threshold = Vt; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss1_wsum_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( integrator, sim.qss1_integrator_models.get_id(integrator), "int"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "cte"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.qss1_cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 5_ul); // Connections // expect(sim.connect(cross.y[1], integrator.x[0]) == // irt::status::success); expect(sim.connect(cross.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[0]) == irt::status::success); file_output fo_a("lif-qss1.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; "lif_simulation_qss2"_test = [] { fmt::print("lif_simulation_qss2\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss2_wsum_2_models.can_alloc(1)); expect(sim.qss2_integrator_models.can_alloc(1)); expect(sim.constant_models.can_alloc(2)); expect(sim.qss2_cross_models.can_alloc(1)); auto& sum = sim.qss2_wsum_2_models.alloc(); auto& integrator = sim.qss2_integrator_models.alloc(); auto& constant = sim.constant_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.qss2_cross_models.alloc(); double tau = 10.0; double Vt = 1.0; double V0 = 10.0; double Vr = 0.0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant.default_value = 1.0; constant_cross.default_value = Vr; integrator.default_X = 0.0; integrator.default_dQ = 0.001; cross.default_threshold = Vt; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss2_wsum_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( integrator, sim.qss2_integrator_models.get_id(integrator), "int"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "cte"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.qss2_cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 5_ul); // Connections // expect(sim.connect(cross.y[1], integrator.x[0]) == // irt::status::success); expect(sim.connect(cross.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[0]) == irt::status::success); file_output fo_a("lif-qss2.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.001, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { // printf("--------------------------------------------\n"); auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; "izhikevich_simulation_qss1"_test = [] { fmt::print("izhikevich_simulation_qss1\n"); irt::simulation sim; expect(irt::is_success(sim.init(128lu, 256))); expect(sim.constant_models.can_alloc(3)); expect(sim.qss1_wsum_2_models.can_alloc(3)); expect(sim.qss1_wsum_4_models.can_alloc(1)); expect(sim.qss1_multiplier_models.can_alloc(1)); expect(sim.qss1_integrator_models.can_alloc(2)); expect(sim.qss1_cross_models.can_alloc(2)); auto& constant = sim.constant_models.alloc(); auto& constant2 = sim.constant_models.alloc(); auto& constant3 = sim.constant_models.alloc(); auto& sum_a = sim.qss1_wsum_2_models.alloc(); auto& sum_b = sim.qss1_wsum_2_models.alloc(); auto& sum_c = sim.qss1_wsum_4_models.alloc(); auto& sum_d = sim.qss1_wsum_2_models.alloc(); auto& product = sim.qss1_multiplier_models.alloc(); auto& integrator_a = sim.qss1_integrator_models.alloc(); auto& integrator_b = sim.qss1_integrator_models.alloc(); auto& cross = sim.qss1_cross_models.alloc(); auto& cross2 = sim.qss1_cross_models.alloc(); double a = 0.2; double b = 2.0; double c = -56.0; double d = -16.0; double I = -99.0; double vt = 30.0; constant.default_value = 1.0; constant2.default_value = c; constant3.default_value = I; cross.default_threshold = vt; cross2.default_threshold = vt; integrator_a.default_X = 0.0; integrator_a.default_dQ = 0.01; integrator_b.default_X = 0.0; integrator_b.default_dQ = 0.01; sum_a.default_input_coeffs[0] = 1.0; sum_a.default_input_coeffs[1] = -1.0; sum_b.default_input_coeffs[0] = -a; sum_b.default_input_coeffs[1] = a * b; sum_c.default_input_coeffs[0] = 0.04; sum_c.default_input_coeffs[1] = 5.0; sum_c.default_input_coeffs[2] = 140.0; sum_c.default_input_coeffs[3] = 1.0; sum_d.default_input_coeffs[0] = 1.0; sum_d.default_input_coeffs[1] = d; expect(sim.models.can_alloc(12)); !expect(irt::is_success( sim.alloc(constant3, sim.constant_models.get_id(constant3), "tfun"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "1.0"))); !expect(irt::is_success(sim.alloc( constant2, sim.constant_models.get_id(constant2), "-56.0"))); !expect(irt::is_success( sim.alloc(sum_a, sim.qss1_wsum_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.qss1_wsum_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success( sim.alloc(sum_c, sim.qss1_wsum_4_models.get_id(sum_c), "sum_c"))); !expect(irt::is_success( sim.alloc(sum_d, sim.qss1_wsum_2_models.get_id(sum_d), "sum_d"))); !expect(irt::is_success(sim.alloc( product, sim.qss1_multiplier_models.get_id(product), "prod"))); !expect(irt::is_success( sim.alloc(integrator_a, sim.qss1_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success( sim.alloc(integrator_b, sim.qss1_integrator_models.get_id(integrator_b), "int_b"))); !expect(irt::is_success( sim.alloc(cross, sim.qss1_cross_models.get_id(cross), "cross"))); !expect(irt::is_success( sim.alloc(cross2, sim.qss1_cross_models.get_id(cross2), "cross2"))); !expect(sim.models.size() == 12_ul); expect(sim.connect(integrator_a.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(constant2.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(cross.y[1], product.x[0]) == irt::status::success); expect(sim.connect(cross.y[1], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_c.x[0]) == irt::status::success); expect(sim.connect(cross.y[1], sum_c.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum_b.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum_c.x[2]) == irt::status::success); expect(sim.connect(constant3.y[0], sum_c.x[3]) == irt::status::success); expect(sim.connect(sum_c.y[0], sum_a.x[0]) == irt::status::success); // expect(sim.connect(integrator_b.y[0], sum_a.x[1]) == // irt::status::success); expect(sim.connect(cross2.y[1], sum_a.x[1]) == irt::status::success); expect(sim.connect(sum_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], integrator_a.x[1]) == irt::status::success); expect(sim.connect(cross2.y[1], sum_b.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(cross2.y[0], integrator_b.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross2.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], cross2.x[2]) == irt::status::success); expect(sim.connect(sum_d.y[0], cross2.x[1]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_d.x[0]) == irt::status::success); expect(sim.connect(constant.y[0], sum_d.x[1]) == irt::status::success); file_output fo_a("izhikevitch-qss1_a.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.1, "A", static_cast<void*>(&fo_a), &file_output_initialize, &file_output_observe, nullptr); file_output fo_b("izhikevitch-qss1_b.csv"); expect(fo_b.os != nullptr); auto& obs_b = sim.observers.alloc(0.1, "B", static_cast<void*>(&fo_b), &file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(irt::status::success == sim.initialize(t)); !expect(sim.sched.size() == 12_ul); do { irt::status st = sim.run(t); expect(st == irt::status::success); } while (t < 140); }; "izhikevich_simulation_qss2"_test = [] { fmt::print("izhikevich_simulation_qss2\n"); irt::simulation sim; expect(irt::is_success(sim.init(64lu, 256lu))); expect(sim.constant_models.can_alloc(3)); expect(sim.qss2_wsum_2_models.can_alloc(3)); expect(sim.qss2_wsum_4_models.can_alloc(1)); expect(sim.qss2_multiplier_models.can_alloc(1)); expect(sim.qss2_integrator_models.can_alloc(2)); auto& constant = sim.constant_models.alloc(); auto& constant2 = sim.constant_models.alloc(); auto& constant3 = sim.constant_models.alloc(); auto& sum_a = sim.qss2_wsum_2_models.alloc(); auto& sum_b = sim.qss2_wsum_2_models.alloc(); auto& sum_c = sim.qss2_wsum_4_models.alloc(); auto& sum_d = sim.qss2_wsum_2_models.alloc(); auto& product = sim.qss2_multiplier_models.alloc(); auto& integrator_a = sim.qss2_integrator_models.alloc(); auto& integrator_b = sim.qss2_integrator_models.alloc(); auto& cross = sim.qss2_cross_models.alloc(); auto& cross2 = sim.qss2_cross_models.alloc(); double a = 0.2; double b = 2.0; double c = -56.0; double d = -16.0; double I = -99.0; double vt = 30.0; constant.default_value = 1.0; constant2.default_value = c; constant3.default_value = I; cross.default_threshold = vt; cross2.default_threshold = vt; integrator_a.default_X = 0.0; integrator_a.default_dQ = 0.01; integrator_b.default_X = 0.0; integrator_b.default_dQ = 0.01; sum_a.default_input_coeffs[0] = 1.0; sum_a.default_input_coeffs[1] = -1.0; sum_b.default_input_coeffs[0] = -a; sum_b.default_input_coeffs[1] = a * b; sum_c.default_input_coeffs[0] = 0.04; sum_c.default_input_coeffs[1] = 5.0; sum_c.default_input_coeffs[2] = 140.0; sum_c.default_input_coeffs[3] = 1.0; sum_d.default_input_coeffs[0] = 1.0; sum_d.default_input_coeffs[1] = d; expect(sim.models.can_alloc(12)); !expect(irt::is_success( sim.alloc(constant3, sim.constant_models.get_id(constant3), "tfun"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "1.0"))); !expect(irt::is_success(sim.alloc( constant2, sim.constant_models.get_id(constant2), "-56.0"))); !expect(irt::is_success( sim.alloc(sum_a, sim.qss2_wsum_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.qss2_wsum_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success( sim.alloc(sum_c, sim.qss2_wsum_4_models.get_id(sum_c), "sum_c"))); !expect(irt::is_success( sim.alloc(sum_d, sim.qss2_wsum_2_models.get_id(sum_d), "sum_d"))); !expect(irt::is_success(sim.alloc( product, sim.qss2_multiplier_models.get_id(product), "prod"))); !expect(irt::is_success( sim.alloc(integrator_a, sim.qss2_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success( sim.alloc(integrator_b, sim.qss2_integrator_models.get_id(integrator_b), "int_b"))); !expect(irt::is_success( sim.alloc(cross, sim.qss2_cross_models.get_id(cross), "cross"))); !expect(irt::is_success( sim.alloc(cross2, sim.qss2_cross_models.get_id(cross2), "cross2"))); !expect(sim.models.size() == 12_ul); expect(sim.connect(integrator_a.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(constant2.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(cross.y[1], product.x[0]) == irt::status::success); expect(sim.connect(cross.y[1], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_c.x[0]) == irt::status::success); expect(sim.connect(cross.y[1], sum_c.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum_b.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum_c.x[2]) == irt::status::success); expect(sim.connect(constant3.y[0], sum_c.x[3]) == irt::status::success); expect(sim.connect(sum_c.y[0], sum_a.x[0]) == irt::status::success); // expect(sim.connect(integrator_b.y[0], sum_a.x[1]) == // irt::status::success); expect(sim.connect(cross2.y[1], sum_a.x[1]) == irt::status::success); expect(sim.connect(sum_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], integrator_a.x[1]) == irt::status::success); expect(sim.connect(cross2.y[1], sum_b.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(cross2.y[0], integrator_b.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross2.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], cross2.x[2]) == irt::status::success); expect(sim.connect(sum_d.y[0], cross2.x[1]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_d.x[0]) == irt::status::success); expect(sim.connect(constant.y[0], sum_d.x[1]) == irt::status::success); file_output fo_a("izhikevitch-qss2_a.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), &file_output_initialize, &file_output_observe, nullptr); file_output fo_b("izhikevitch-qss2_b.csv"); expect(fo_b.os != nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), &file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(irt::status::success == sim.initialize(t)); !expect(sim.sched.size() == 12_ul); do { irt::status st = sim.run(t); expect(st == irt::status::success); } while (t < 30.); // 140. error! }; #if 0 "lotka_volterra_simulation_qss3"_test = [] { fmt::print("lotka_volterra_simulation_qss3\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss3_wsum_2_models.can_alloc(2)); expect(sim.qss3_multiplier_models.can_alloc(2)); expect(sim.qss3_integrator_models.can_alloc(2)); auto& sum_a = sim.qss3_wsum_2_models.alloc(); auto& sum_b = sim.qss3_wsum_2_models.alloc(); auto& product = sim.qss3_multiplier_models.alloc(); auto& integrator_a = sim.qss3_integrator_models.alloc(); auto& integrator_b = sim.qss3_integrator_models.alloc(); integrator_a.default_X = 18.0; integrator_a.default_dQ = 0.1; integrator_b.default_X = 7.0; integrator_b.default_dQ = 0.1; sum_a.default_input_coeffs[0] = 2.0; sum_a.default_input_coeffs[1] = -0.4; sum_b.default_input_coeffs[0] = -1.0; sum_b.default_input_coeffs[1] = 0.1; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum_a, sim.qss3_wsum_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.qss3_wsum_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success(sim.alloc( product, sim.qss3_multiplier_models.get_id(product), "prod"))); !expect(irt::is_success( sim.alloc(integrator_a, sim.qss3_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success( sim.alloc(integrator_b, sim.qss3_integrator_models.get_id(integrator_b), "int_b"))); !expect(sim.models.size() == 5_ul); expect(sim.connect(sum_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], sum_a.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_a.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_b.x[1]) == irt::status::success); file_output fo_a("lotka-volterra-qss3_a.csv"); file_output fo_b("lotka-volterra-qss3_b.csv"); expect(fo_a.os != nullptr); expect(fo_b.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 15.0); }; #endif "lif_simulation_qss3"_test = [] { fmt::print("lif_simulation_qss3\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss3_wsum_2_models.can_alloc(1)); expect(sim.qss3_integrator_models.can_alloc(1)); expect(sim.constant_models.can_alloc(2)); expect(sim.qss3_cross_models.can_alloc(1)); auto& sum = sim.qss3_wsum_2_models.alloc(); auto& integrator = sim.qss3_integrator_models.alloc(); auto& constant = sim.constant_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.qss3_cross_models.alloc(); double tau = 10.0; double Vt = 1.0; double V0 = 10.0; double Vr = 0.0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant.default_value = 1.0; constant_cross.default_value = Vr; integrator.default_X = 0.0; integrator.default_dQ = 0.01; cross.default_threshold = Vt; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss3_wsum_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( integrator, sim.qss3_integrator_models.get_id(integrator), "int"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "cte"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.qss3_cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 5_ul); // Connections // expect(sim.connect(cross.y[1], integrator.x[0]) == // irt::status::success); expect(sim.connect(cross.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[0]) == irt::status::success); file_output fo_a("lif-qss3.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.001, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { // printf("--------------------------------------------\n"); auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; "izhikevich_simulation_qss3"_test = [] { fmt::print("izhikevich_simulation_qss3\n"); irt::simulation sim; expect(irt::is_success(sim.init(64lu, 256lu))); expect(sim.constant_models.can_alloc(3)); expect(sim.qss3_wsum_2_models.can_alloc(3)); expect(sim.qss3_wsum_4_models.can_alloc(1)); expect(sim.qss3_multiplier_models.can_alloc(1)); expect(sim.qss3_integrator_models.can_alloc(2)); auto& constant = sim.constant_models.alloc(); auto& constant2 = sim.constant_models.alloc(); auto& constant3 = sim.constant_models.alloc(); auto& sum_a = sim.qss3_wsum_2_models.alloc(); auto& sum_b = sim.qss3_wsum_2_models.alloc(); auto& sum_c = sim.qss3_wsum_4_models.alloc(); auto& sum_d = sim.qss3_wsum_2_models.alloc(); auto& product = sim.qss3_multiplier_models.alloc(); auto& integrator_a = sim.qss3_integrator_models.alloc(); auto& integrator_b = sim.qss3_integrator_models.alloc(); auto& cross = sim.qss3_cross_models.alloc(); auto& cross2 = sim.qss3_cross_models.alloc(); double a = 0.2; double b = 2.0; double c = -56.0; double d = -16.0; double I = -99.0; double vt = 30.0; constant.default_value = 1.0; constant2.default_value = c; constant3.default_value = I; cross.default_threshold = vt; cross2.default_threshold = vt; integrator_a.default_X = 0.0; integrator_a.default_dQ = 0.01; integrator_b.default_X = 0.0; integrator_b.default_dQ = 0.01; sum_a.default_input_coeffs[0] = 1.0; sum_a.default_input_coeffs[1] = -1.0; sum_b.default_input_coeffs[0] = -a; sum_b.default_input_coeffs[1] = a * b; sum_c.default_input_coeffs[0] = 0.04; sum_c.default_input_coeffs[1] = 5.0; sum_c.default_input_coeffs[2] = 140.0; sum_c.default_input_coeffs[3] = 1.0; sum_d.default_input_coeffs[0] = 1.0; sum_d.default_input_coeffs[1] = d; expect(sim.models.can_alloc(12)); !expect(irt::is_success( sim.alloc(constant3, sim.constant_models.get_id(constant3), "tfun"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "1.0"))); !expect(irt::is_success(sim.alloc( constant2, sim.constant_models.get_id(constant2), "-56.0"))); !expect(irt::is_success( sim.alloc(sum_a, sim.qss3_wsum_2_models.get_id(sum_a), "sum_a"))); !expect(irt::is_success( sim.alloc(sum_b, sim.qss3_wsum_2_models.get_id(sum_b), "sum_b"))); !expect(irt::is_success( sim.alloc(sum_c, sim.qss3_wsum_4_models.get_id(sum_c), "sum_c"))); !expect(irt::is_success( sim.alloc(sum_d, sim.qss3_wsum_2_models.get_id(sum_d), "sum_d"))); !expect(irt::is_success(sim.alloc( product, sim.qss3_multiplier_models.get_id(product), "prod"))); !expect(irt::is_success( sim.alloc(integrator_a, sim.qss3_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success( sim.alloc(integrator_b, sim.qss3_integrator_models.get_id(integrator_b), "int_b"))); !expect(irt::is_success( sim.alloc(cross, sim.qss3_cross_models.get_id(cross), "cross"))); !expect(irt::is_success( sim.alloc(cross2, sim.qss3_cross_models.get_id(cross2), "cross2"))); !expect(sim.models.size() == 12_ul); expect(sim.connect(integrator_a.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(constant2.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(cross.y[1], product.x[0]) == irt::status::success); expect(sim.connect(cross.y[1], product.x[1]) == irt::status::success); expect(sim.connect(product.y[0], sum_c.x[0]) == irt::status::success); expect(sim.connect(cross.y[1], sum_c.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum_b.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum_c.x[2]) == irt::status::success); expect(sim.connect(constant3.y[0], sum_c.x[3]) == irt::status::success); expect(sim.connect(sum_c.y[0], sum_a.x[0]) == irt::status::success); // expect(sim.connect(integrator_b.y[0], sum_a.x[1]) == // irt::status::success); expect(sim.connect(cross2.y[1], sum_a.x[1]) == irt::status::success); expect(sim.connect(sum_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(cross.y[0], integrator_a.x[1]) == irt::status::success); expect(sim.connect(cross2.y[1], sum_b.x[0]) == irt::status::success); expect(sim.connect(sum_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(cross2.y[0], integrator_b.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], cross2.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], cross2.x[2]) == irt::status::success); expect(sim.connect(sum_d.y[0], cross2.x[1]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum_d.x[0]) == irt::status::success); expect(sim.connect(constant.y[0], sum_d.x[1]) == irt::status::success); file_output fo_a("izhikevitch-qss3_a.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), &file_output_initialize, &file_output_observe, nullptr); file_output fo_b("izhikevitch-qss3_b.csv"); expect(fo_b.os != nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), &file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(irt::status::success == sim.initialize(t)); !expect(sim.sched.size() == 12_ul); do { irt::status st = sim.run(t); expect(st == irt::status::success); } while (t < 140); }; "van_der_pol_simulation"_test = [] { fmt::print("van_der_pol_simulation\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.adder_3_models.can_alloc(1)); expect(sim.mult_3_models.can_alloc(1)); expect(sim.integrator_models.can_alloc(2)); expect(sim.quantifier_models.can_alloc(2)); auto& sum = sim.adder_3_models.alloc(); auto& product = sim.mult_3_models.alloc(); auto& integrator_a = sim.integrator_models.alloc(); auto& integrator_b = sim.integrator_models.alloc(); auto& quantifier_a = sim.quantifier_models.alloc(); auto& quantifier_b = sim.quantifier_models.alloc(); integrator_a.default_current_value = 0.0; quantifier_a.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier_a.default_zero_init_offset = true; quantifier_a.default_step_size = 0.01; quantifier_a.default_past_length = 3; integrator_b.default_current_value = 10.0; quantifier_b.default_adapt_state = irt::quantifier::adapt_state::possible; quantifier_b.default_zero_init_offset = true; quantifier_b.default_step_size = 0.01; quantifier_b.default_past_length = 3; product.default_input_coeffs[0] = 1.0; product.default_input_coeffs[1] = 1.0; product.default_input_coeffs[2] = 1.0; double mu = 4.0; sum.default_input_coeffs[0] = mu; sum.default_input_coeffs[1] = -mu; sum.default_input_coeffs[2] = -1.0; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.adder_3_models.get_id(sum), "sum"))); !expect(irt::is_success( sim.alloc(product, sim.mult_3_models.get_id(product), "prod"))); !expect(irt::is_success(sim.alloc( integrator_a, sim.integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success(sim.alloc( integrator_b, sim.integrator_models.get_id(integrator_b), "int_b"))); !expect(irt::is_success(sim.alloc( quantifier_a, sim.quantifier_models.get_id(quantifier_a), "qua_a"))); !expect(irt::is_success(sim.alloc( quantifier_b, sim.quantifier_models.get_id(quantifier_b), "qua_b"))); !expect(sim.models.size() == 6_ul); expect(sim.connect(integrator_b.y[0], integrator_a.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator_b.x[1]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum.x[0]) == irt::status::success); expect(sim.connect(product.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], sum.x[2]) == irt::status::success); expect(sim.connect(integrator_b.y[0], product.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product.x[2]) == irt::status::success); expect(sim.connect(quantifier_a.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(quantifier_b.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], quantifier_a.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], quantifier_b.x[0]) == irt::status::success); file_output fo_a("van_der_pol_a.csv"); file_output fo_b("van_der_pol_b.csv"); expect(fo_a.os != nullptr); expect(fo_b.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 6_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 150.0); }; "van_der_pol_simulation_qss3"_test = [] { fmt::print("van_der_pol_simulation_qss3\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss3_wsum_3_models.can_alloc(1)); expect(sim.qss3_multiplier_models.can_alloc(2)); expect(sim.qss3_integrator_models.can_alloc(2)); auto& sum = sim.qss3_wsum_3_models.alloc(); auto& product1 = sim.qss3_multiplier_models.alloc(); auto& product2 = sim.qss3_multiplier_models.alloc(); auto& integrator_a = sim.qss3_integrator_models.alloc(); auto& integrator_b = sim.qss3_integrator_models.alloc(); integrator_a.default_X = 0.0; integrator_a.default_dQ = 0.001; integrator_b.default_X = 10.0; integrator_b.default_dQ = 0.001; double mu = 4.0; sum.default_input_coeffs[0] = mu; sum.default_input_coeffs[1] = -mu; sum.default_input_coeffs[2] = -1.0; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss3_wsum_3_models.get_id(sum), "sum"))); !expect(irt::is_success( sim.alloc(product1, sim.qss3_multiplier_models.get_id(product1), "prod1"))); !expect(irt::is_success( sim.alloc(product2, sim.qss3_multiplier_models.get_id(product2), "prod2"))); !expect(irt::is_success(sim.alloc( integrator_a, sim.qss3_integrator_models.get_id(integrator_a), "int_a"))); !expect(irt::is_success(sim.alloc( integrator_b, sim.qss3_integrator_models.get_id(integrator_b), "int_b"))); !expect(sim.models.size() == 5_ul); expect(sim.connect(integrator_b.y[0], integrator_a.x[0]) == irt::status::success); expect(sim.connect(sum.y[0], integrator_b.x[0]) == irt::status::success); expect(sim.connect(integrator_b.y[0], sum.x[0]) == irt::status::success); expect(sim.connect(product2.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(integrator_a.y[0], sum.x[2]) == irt::status::success); expect(sim.connect(integrator_b.y[0], product1.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product1.x[1]) == irt::status::success); expect(sim.connect(product1.y[0], product2.x[0]) == irt::status::success); expect(sim.connect(integrator_a.y[0], product2.x[1]) == irt::status::success); file_output fo_a("van_der_pol_qss3_a.csv"); file_output fo_b("van_der_pol_qss3_b.csv"); expect(fo_a.os != nullptr); expect(fo_b.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); auto& obs_b = sim.observers.alloc(0.01, "B", static_cast<void*>(&fo_b), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator_a.id), obs_a); sim.observe(sim.models.get(integrator_b.id), obs_b); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 1500.0); }; "neg_lif_simulation_qss1"_test = [] { fmt::print("neg_lif_simulation_qss1\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss1_wsum_2_models.can_alloc(1)); expect(sim.qss1_integrator_models.can_alloc(1)); expect(sim.constant_models.can_alloc(2)); expect(sim.qss1_cross_models.can_alloc(1)); auto& sum = sim.qss1_wsum_2_models.alloc(); auto& integrator = sim.qss1_integrator_models.alloc(); auto& constant = sim.constant_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.qss1_cross_models.alloc(); double tau = 10.0; double Vt = -1.0; double V0 = -10.0; double Vr = 0.0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant.default_value = 1.0; constant_cross.default_value = Vr; integrator.default_X = 0.0; integrator.default_dQ = 0.001; cross.default_threshold = Vt; cross.default_detect_up = false; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss1_wsum_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( integrator, sim.qss1_integrator_models.get_id(integrator), "int"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "cte"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.qss1_cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 5_ul); // Connections // expect(sim.connect(cross.y[1], integrator.x[0]) == // irt::status::success); expect(sim.connect(cross.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[0]) == irt::status::success); file_output fo_a("neg-lif-qss1.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; "neg_lif_simulation_qss2"_test = [] { fmt::print("neg_lif_simulation_qss2\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss2_wsum_2_models.can_alloc(1)); expect(sim.qss2_integrator_models.can_alloc(1)); expect(sim.constant_models.can_alloc(2)); expect(sim.qss2_cross_models.can_alloc(1)); auto& sum = sim.qss2_wsum_2_models.alloc(); auto& integrator = sim.qss2_integrator_models.alloc(); auto& constant = sim.constant_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.qss2_cross_models.alloc(); double tau = 10.0; double Vt = -1.0; double V0 = -10.0; double Vr = 0.0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant.default_value = 1.0; constant_cross.default_value = Vr; integrator.default_X = 0.0; integrator.default_dQ = 0.000001; cross.default_threshold = Vt; cross.default_detect_up = false; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss2_wsum_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( integrator, sim.qss2_integrator_models.get_id(integrator), "int"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "cte"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.qss2_cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 5_ul); // Connections // expect(sim.connect(cross.y[1], integrator.x[0]) == // irt::status::success); expect(sim.connect(cross.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[0]) == irt::status::success); file_output fo_a("neg-lif-qss2.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; "neg_lif_simulation_qss3"_test = [] { fmt::print("neg_lif_simulation_qss3\n"); irt::simulation sim; expect(irt::is_success(sim.init(32lu, 512lu))); expect(sim.qss3_wsum_2_models.can_alloc(1)); expect(sim.qss3_integrator_models.can_alloc(1)); expect(sim.constant_models.can_alloc(2)); expect(sim.qss3_cross_models.can_alloc(1)); auto& sum = sim.qss3_wsum_2_models.alloc(); auto& integrator = sim.qss3_integrator_models.alloc(); auto& constant = sim.constant_models.alloc(); auto& constant_cross = sim.constant_models.alloc(); auto& cross = sim.qss3_cross_models.alloc(); double tau = 10.0; double Vt = -1.0; double V0 = -10.0; double Vr = 0.0; sum.default_input_coeffs[0] = -1.0 / tau; sum.default_input_coeffs[1] = V0 / tau; constant.default_value = 1.0; constant_cross.default_value = Vr; integrator.default_X = 0.0; integrator.default_dQ = 0.00000001; cross.default_threshold = Vt; cross.default_detect_up = false; expect(sim.models.can_alloc(10)); !expect(irt::is_success( sim.alloc(sum, sim.qss3_wsum_2_models.get_id(sum), "sum"))); !expect(irt::is_success(sim.alloc( integrator, sim.qss3_integrator_models.get_id(integrator), "int"))); !expect(irt::is_success( sim.alloc(constant, sim.constant_models.get_id(constant), "cte"))); !expect( irt::is_success(sim.alloc(constant_cross, sim.constant_models.get_id(constant_cross), "ctecro"))); !expect(irt::is_success( sim.alloc(cross, sim.qss3_cross_models.get_id(cross), "cro"))); !expect(sim.models.size() == 5_ul); // Connections // expect(sim.connect(cross.y[1], integrator.x[0]) == // irt::status::success); expect(sim.connect(cross.y[0], integrator.x[1]) == irt::status::success); expect(sim.connect(cross.y[1], sum.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[0]) == irt::status::success); expect(sim.connect(integrator.y[0], cross.x[2]) == irt::status::success); expect(sim.connect(constant_cross.y[0], cross.x[1]) == irt::status::success); expect(sim.connect(constant.y[0], sum.x[1]) == irt::status::success); expect(sim.connect(sum.y[0], integrator.x[0]) == irt::status::success); file_output fo_a("neg-lif-qss3.csv"); expect(fo_a.os != nullptr); auto& obs_a = sim.observers.alloc(0.01, "A", static_cast<void*>(&fo_a), file_output_initialize, &file_output_observe, nullptr); sim.observe(sim.models.get(integrator.id), obs_a); irt::time t = 0.0; expect(sim.initialize(t) == irt::status::success); !expect(sim.sched.size() == 5_ul); do { auto st = sim.run(t); expect(st == irt::status::success); } while (t < 100.0); }; }
37.240827
86
0.544258
K-H-Ismail
a315495f76fbfbb100e12ea2c9037b4daafcb65d
3,160
cpp
C++
examples_rpx/apps/app2.cpp
alsaibie/MachineRX
a92a951e72fb63b03a69a64bc545c9fe91ccee89
[ "MIT" ]
null
null
null
examples_rpx/apps/app2.cpp
alsaibie/MachineRX
a92a951e72fb63b03a69a64bc545c9fe91ccee89
[ "MIT" ]
null
null
null
examples_rpx/apps/app2.cpp
alsaibie/MachineRX
a92a951e72fb63b03a69a64bc545c9fe91ccee89
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2020 Ali AlSaibie * * 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. * * * File: app2.cpp * Project: MachineRX * Author: Ali AlSaibie (ali.alsaibie@ku.edu.kw) * ----- * Modified By: Ali AlSaibie (ali.alsaibie@ku.edu.kw>) */ #include "MachineRPX.hpp" #include "main_app.hpp" #include "topic1.hpp" #include "topic2.hpp" using namespace MachineRPX; class Application2 : public MThread { public: Application2() : MThread("Application 2", 512 * 4, 20, 1000), topic_2_pub(gTopic2MTHandle), topic_1_sub(gTopic1MTHandle, std::bind(&Application2::on_topic_1_read, this, std::placeholders::_1)) { } virtual ~Application2() { } protected: virtual void run() { topic_1_sub.initialize(); topic_2_pub.initialize(); printf("Thread Priority: %d\n", getThreadPriority()); printf("Thread Name: "); printf("%s", getThreadName()); printf("\n"); while (1) { // struct timespec begin, end; //TODO: move time example to separate app // double elapsed; // clock_gettime(CLOCK_MONOTONIC, &begin); topic2Msg.P.a = 2; topic_2_pub.publish(topic2Msg); topic_1_sub.read(); thread_lap(); // clock_gettime(CLOCK_MONOTONIC, &end); // elapsed = end.tv_sec - begin.tv_sec; // elapsed += (end.tv_nsec - begin.tv_nsec) / 1000000000.0L; // printf("ET %fms\n", elapsed * 1000L); } } private: void on_topic_1_read(const Topic1_msg_t &msg) { topic1Msg = msg; printf("App 2 Received Message - Count: %i, Time(ms): %i\n", topic1Msg.msg_count, topic1Msg.tick_stamp_ms); } /* Pubs */ MTopicPublisher<Topic2_msg_t> topic_2_pub; Topic2_msg_t topic2Msg; /* Subs */ MTopicSubscriber<Topic1_msg_t> topic_1_sub; Topic1_msg_t topic1Msg; }; void start_application_2() { Application2 *ptr = new Application2(); ptr->start(); }
32.244898
115
0.640506
alsaibie
a315c44ddb945948ae9741af654b6f1a988ff30f
349
cpp
C++
tests/simplelog.backend.spdlog/test_main.cpp
ClausKlein/cxx.simplelog
73365bd126ca49ab7bd02e2bd53738f296cdb83a
[ "MIT" ]
null
null
null
tests/simplelog.backend.spdlog/test_main.cpp
ClausKlein/cxx.simplelog
73365bd126ca49ab7bd02e2bd53738f296cdb83a
[ "MIT" ]
8
2020-01-31T20:07:27.000Z
2021-03-06T13:13:25.000Z
tests/simplelog.backend.spdlog/test_main.cpp
ClausKlein/cxx.simplelog
73365bd126ca49ab7bd02e2bd53738f296cdb83a
[ "MIT" ]
3
2020-01-31T20:03:24.000Z
2021-02-28T11:34:42.000Z
/** * @file tests/simplelog.backend.spdlog/test_main.cpp * Unit tests main-function by using the doctest C++ testing framework. * * @see https://github.com/onqtam/doctest * @see https://github.com/onqtam/doctest/blob/master/doc/markdown/tutorial.md **/ // -- TEST MAIN: #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest/doctest.h"
29.083333
78
0.74212
ClausKlein
a316b21a015649ec3bfba6d1ff255372bff3e6dd
2,576
hxx
C++
xsd-4.0.0/xsd/cxx/tree/comparison-map.hxx
beroset/OpenADR-VEN-Library
16546464fe1dc714a126474aaadf75483ec9cbc6
[ "Apache-2.0" ]
12
2016-09-21T19:07:13.000Z
2021-12-13T06:17:36.000Z
xsd-4.0.0/xsd/cxx/tree/comparison-map.hxx
beroset/OpenADR-VEN-Library
16546464fe1dc714a126474aaadf75483ec9cbc6
[ "Apache-2.0" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
xsd-4.0.0/xsd/cxx/tree/comparison-map.hxx
beroset/OpenADR-VEN-Library
16546464fe1dc714a126474aaadf75483ec9cbc6
[ "Apache-2.0" ]
12
2018-06-10T10:52:56.000Z
2020-12-08T15:47:13.000Z
// file : xsd/cxx/tree/comparison-map.hxx // copyright : Copyright (c) 2005-2014 Code Synthesis Tools CC // license : GNU GPL v2 + exceptions; see accompanying LICENSE file #ifndef XSD_CXX_TREE_COMPARISON_MAP_HXX #define XSD_CXX_TREE_COMPARISON_MAP_HXX #include <map> #include <cstddef> // std::size_t #include <typeinfo> #include <xsd/cxx/tree/elements.hxx> namespace xsd { namespace cxx { namespace tree { template <typename C> struct comparison_map { typedef std::type_info type_id; typedef bool (*comparator) (const type&, const type&); comparison_map (); void register_type (const type_id&, comparator, bool replace = true); void unregister_type (const type_id&); bool compare (const type&, const type&); public: comparator find (const type_id&) const; private: struct type_id_comparator { bool operator() (const type_id* x, const type_id* y) const { // XL C++ on AIX has buggy type_info::before() in that // it returns true for two different type_info objects // that happened to be for the same type. // #if defined(__xlC__) && defined(_AIX) return *x != *y && x->before (*y); #else return x->before (*y); #endif } }; typedef std::map<const type_id*, comparator, type_id_comparator> type_map; type_map type_map_; }; // // template<unsigned long id, typename C> struct comparison_plate { static comparison_map<C>* map; static std::size_t count; comparison_plate (); ~comparison_plate (); }; template<unsigned long id, typename C> comparison_map<C>* comparison_plate<id, C>::map = 0; template<unsigned long id, typename C> std::size_t comparison_plate<id, C>::count = 0; // // template<unsigned long id, typename C> inline comparison_map<C>& comparison_map_instance () { return *comparison_plate<id, C>::map; } // // template<typename T> bool comparator_impl (const type&, const type&); template<unsigned long id, typename C, typename T> struct comparison_initializer { comparison_initializer (); ~comparison_initializer (); }; } } } #include <xsd/cxx/tree/comparison-map.txx> #endif // XSD_CXX_TREE_COMPARISON_MAP_HXX
22.79646
72
0.586957
beroset
a316ef1993a0f3c08ac59c75f35e65fed9c9ebed
111
cpp
C++
Classes/MyMoveTo.cpp
FrSanchez/snake
4e2260d0784cd90ddf28a9f209b0d00da3cf66d0
[ "MIT" ]
null
null
null
Classes/MyMoveTo.cpp
FrSanchez/snake
4e2260d0784cd90ddf28a9f209b0d00da3cf66d0
[ "MIT" ]
null
null
null
Classes/MyMoveTo.cpp
FrSanchez/snake
4e2260d0784cd90ddf28a9f209b0d00da3cf66d0
[ "MIT" ]
null
null
null
// // MyMoveTo.cpp // snake-mobile // // Created by Francisco Sanchez on 3/15/21. // #include "MyMoveTo.h"
12.333333
44
0.630631
FrSanchez
a3173f544567b22c78af825942e0376bf6e0364d
6,161
cc
C++
quic/core/crypto/aead_base_encrypter.cc
itangwang/quiche
6f18a8295cc1f00b1b7e0adad70e7b764cf9dd51
[ "BSD-3-Clause" ]
1
2020-03-11T03:44:02.000Z
2020-03-11T03:44:02.000Z
src/net/third_party/quiche/src/quic/core/crypto/aead_base_encrypter.cc
bylond/naiveproxy
a04a8330a8bb0d0892259cf6d795271fbe6e6d0e
[ "BSD-3-Clause" ]
null
null
null
src/net/third_party/quiche/src/quic/core/crypto/aead_base_encrypter.cc
bylond/naiveproxy
a04a8330a8bb0d0892259cf6d795271fbe6e6d0e
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/crypto/aead_base_encrypter.h" #include "third_party/boringssl/src/include/openssl/crypto.h" #include "third_party/boringssl/src/include/openssl/err.h" #include "third_party/boringssl/src/include/openssl/evp.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h" #include "net/third_party/quiche/src/quic/platform/api/quic_arraysize.h" #include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" namespace quic { namespace { // In debug builds only, log OpenSSL error stack. Then clear OpenSSL error // stack. void DLogOpenSslErrors() { #ifdef NDEBUG while (ERR_get_error()) { } #else while (unsigned long error = ERR_get_error()) { char buf[120]; ERR_error_string_n(error, buf, QUIC_ARRAYSIZE(buf)); QUIC_DLOG(ERROR) << "OpenSSL error: " << buf; } #endif } const EVP_AEAD* InitAndCall(const EVP_AEAD* (*aead_getter)()) { // Ensure BoringSSL is initialized before calling |aead_getter|. In Chromium, // the static initializer is disabled. CRYPTO_library_init(); return aead_getter(); } } // namespace AeadBaseEncrypter::AeadBaseEncrypter(const EVP_AEAD* (*aead_getter)(), size_t key_size, size_t auth_tag_size, size_t nonce_size, bool use_ietf_nonce_construction) : aead_alg_(InitAndCall(aead_getter)), key_size_(key_size), auth_tag_size_(auth_tag_size), nonce_size_(nonce_size), use_ietf_nonce_construction_(use_ietf_nonce_construction) { DCHECK_LE(key_size_, sizeof(key_)); DCHECK_LE(nonce_size_, sizeof(iv_)); DCHECK_GE(kMaxNonceSize, nonce_size_); } AeadBaseEncrypter::~AeadBaseEncrypter() {} bool AeadBaseEncrypter::SetKey(QuicStringPiece key) { DCHECK_EQ(key.size(), key_size_); if (key.size() != key_size_) { return false; } memcpy(key_, key.data(), key.size()); EVP_AEAD_CTX_cleanup(ctx_.get()); if (!EVP_AEAD_CTX_init(ctx_.get(), aead_alg_, key_, key_size_, auth_tag_size_, nullptr)) { DLogOpenSslErrors(); return false; } return true; } bool AeadBaseEncrypter::SetNoncePrefix(QuicStringPiece nonce_prefix) { if (use_ietf_nonce_construction_) { QUIC_BUG << "Attempted to set nonce prefix on IETF QUIC crypter"; return false; } DCHECK_EQ(nonce_prefix.size(), nonce_size_ - sizeof(QuicPacketNumber)); if (nonce_prefix.size() != nonce_size_ - sizeof(QuicPacketNumber)) { return false; } memcpy(iv_, nonce_prefix.data(), nonce_prefix.size()); return true; } bool AeadBaseEncrypter::SetIV(QuicStringPiece iv) { if (!use_ietf_nonce_construction_) { QUIC_BUG << "Attempted to set IV on Google QUIC crypter"; return false; } DCHECK_EQ(iv.size(), nonce_size_); if (iv.size() != nonce_size_) { return false; } memcpy(iv_, iv.data(), iv.size()); return true; } bool AeadBaseEncrypter::Encrypt(QuicStringPiece nonce, QuicStringPiece associated_data, QuicStringPiece plaintext, unsigned char* output) { DCHECK_EQ(nonce.size(), nonce_size_); size_t ciphertext_len; if (!EVP_AEAD_CTX_seal( ctx_.get(), output, &ciphertext_len, plaintext.size() + auth_tag_size_, reinterpret_cast<const uint8_t*>(nonce.data()), nonce.size(), reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size(), reinterpret_cast<const uint8_t*>(associated_data.data()), associated_data.size())) { DLogOpenSslErrors(); return false; } return true; } bool AeadBaseEncrypter::EncryptPacket(uint64_t packet_number, QuicStringPiece associated_data, QuicStringPiece plaintext, char* output, size_t* output_length, size_t max_output_length) { size_t ciphertext_size = GetCiphertextSize(plaintext.length()); if (max_output_length < ciphertext_size) { return false; } // TODO(ianswett): Introduce a check to ensure that we don't encrypt with the // same packet number twice. QUIC_ALIGNED(4) char nonce_buffer[kMaxNonceSize]; memcpy(nonce_buffer, iv_, nonce_size_); size_t prefix_len = nonce_size_ - sizeof(packet_number); if (use_ietf_nonce_construction_) { for (size_t i = 0; i < sizeof(packet_number); ++i) { nonce_buffer[prefix_len + i] ^= (packet_number >> ((sizeof(packet_number) - i - 1) * 8)) & 0xff; } } else { memcpy(nonce_buffer + prefix_len, &packet_number, sizeof(packet_number)); } if (!Encrypt(QuicStringPiece(nonce_buffer, nonce_size_), associated_data, plaintext, reinterpret_cast<unsigned char*>(output))) { return false; } *output_length = ciphertext_size; return true; } size_t AeadBaseEncrypter::GetKeySize() const { return key_size_; } size_t AeadBaseEncrypter::GetNoncePrefixSize() const { return nonce_size_ - sizeof(QuicPacketNumber); } size_t AeadBaseEncrypter::GetIVSize() const { return nonce_size_; } size_t AeadBaseEncrypter::GetMaxPlaintextSize(size_t ciphertext_size) const { return ciphertext_size - std::min(ciphertext_size, auth_tag_size_); } size_t AeadBaseEncrypter::GetCiphertextSize(size_t plaintext_size) const { return plaintext_size + auth_tag_size_; } QuicStringPiece AeadBaseEncrypter::GetKey() const { return QuicStringPiece(reinterpret_cast<const char*>(key_), key_size_); } QuicStringPiece AeadBaseEncrypter::GetNoncePrefix() const { return QuicStringPiece(reinterpret_cast<const char*>(iv_), GetNoncePrefixSize()); } } // namespace quic
32.771277
80
0.677325
itangwang
a3181a0b68c7adc5906f4a8f8b477d6905f260c9
387
cpp
C++
competitive_programming/programming_contests/uri/flavious_josephus_legend3.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/flavious_josephus_legend3.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/flavious_josephus_legend3.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/en/problems/view/1030 #include <iostream> using namespace std; int josephus(int n, int k) { if (n == 1) return 0; return (josephus(n-1, k) + k) % n; } int main() { int n, n1, n2, counter = 1; cin >> n; while (n--) { cin >> n1 >> n2; cout << "Case " << counter << ": " << josephus(n1, n2)+1 << endl; counter++; } return 0; }
16.125
67
0.560724
LeandroTk
a31d494ee8bba2254641e5f955b492d03ce109ec
8,339
cpp
C++
src/Engine/PVSearch.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
4
2015-12-24T04:52:48.000Z
2021-11-09T11:31:36.000Z
src/Engine/PVSearch.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
src/Engine/PVSearch.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // Name: PVSearch.cpp // Description: Implementation for class that performs a // principle variation search // Created: 07/09/2004 04:34:22 Eastern Standard Time // Last Updated: $Date: 2004/09/18 21:59:43 $ // Revision: $Revision: 1.3 $ // Author: John Weathers // Email: hotanguish@hotmail.com // Copyright: (c) 2004 John Weathers //////////////////////////////////////////////////////////////////////////// // STL header files #include <vector> #include <string> #include <iostream> #include <sstream> // Local header files #include "common.hpp" #include "PVSearch.hpp" #include "Engine.hpp" #include "Game.hpp" #include "Board.hpp" #include "MoveGenerator.hpp" #include "Evaluator.hpp" #include "Notator.hpp" #include "Move.hpp" #include "ByValue.hpp" #include "RepetitionTable.hpp" using std::vector; using std::string; using std::ostringstream; using std::endl; #ifdef DEBUG #include <fstream> #include <iomanip> using std::setw; extern std::ofstream gLog; #define PRINT_DESCENT(depth, alpha, beta, move, name) \ if (keeplog) { \ gLog << setw(2*depth) << " " \ << (depth+1) \ << setw(10) << mpNotator->Notate(move) \ << " [" << setw(9) << alpha \ << "," << setw(9) << beta << "] " << name << endl; \ } \ #define PRINT_SCORE(depth, score, alpha, beta) \ if (keeplog) { \ gLog << setw(2*depth) << " " \ << (depth+1) << " SCORE =" << setw(10) << score \ << " [" << setw(9) << alpha \ << "," << setw(9) << beta << "] " << endl; \ } \ #define LINE_REACHED(value) \ if (keeplog) { \ gLog << "Line #" << value << " Reached" << endl; \ } #else #define PRINT_DESCENT(depth, alpha, beta, move, name) #define PRINT_SCORE(depth, score, alpha, beta) #define LINE_REACHED(value) #endif //-------------------------------------------------------------------------- // Class: PVSearch // Method: GetBestMove // Description: Return the best move available for the given side as // determined by the search algorithm //-------------------------------------------------------------------------- Move* PVSearch::GetBestMove(int side) { bool winningMove = false; bool foundPV = false; int alpha = MINIMUM_SCORE; int beta = MAXIMUM_SCORE; int score; PRECISION_TIME startTime, finishTime; vector<Move> movelist; vector<Move> line; Move* bestmove = 0; Move* move = 0; // Get the start time for the search GET_PRECISION_TIME(startTime); // For which side are we searching? mSide = side; // Generate all legal moves for the first ply mpMoveGenerator->GenerateMoves(movelist, side); // Perform a special move sort for the root of the search SortRootChildren(winningMove, movelist); // We're done if we found a winning move during the sort if (winningMove) { mPVScore = MAXIMUM_SCORE; mPrincipleVariation.push_back( movelist.back() ); bestmove = new Move( movelist.back() ); } else { // Prep the search PrepareSearch(); // Clear out the line line.clear(); // Initialize our optimal move, line, and score if (!movelist.empty()) { bestmove = new Move( movelist.back() ); mPVScore = bestmove->mValue; mPrincipleVariation.push_back(*bestmove); } // Initialize values for monitoring whether we need to stop mNextCheck = NODES_BETWEEN_TIME_CHECKS; mAbort = false; // Recursively search each move do { move = &(movelist.back()); mNodes++; // Count the nodes that we've search mpRepTable->AddKey( mpBoard->MakeMove(move) ); PRINT_DESCENT(0, alpha, beta, move, "Root"); if (foundPV) { score = -DoSearch(1, -alpha-1, -alpha, line); if ((score > alpha) && (score < beta)) { // Oops. This wasn't really a Principle Variation node score = -DoSearch(1, -beta, -alpha, line); } } else { score = -DoSearch(1, -beta, -alpha, line); } if (mAbort) break; mpRepTable->RemoveKey( mpBoard->UnmakeMove(move) ); PRINT_SCORE(0, score, alpha, beta); if (score > alpha) { // Is this score good enough? bestmove->Copy(*move); alpha = score; foundPV = true; mPVScore = alpha; mPrincipleVariation.clear(); mPrincipleVariation.push_back(*move); mPrincipleVariation.insert(mPrincipleVariation.end(), line.begin(), line.end()); } movelist.pop_back(); } while( !movelist.empty() ); } // Get the finish time for the search GET_PRECISION_TIME(finishTime); // Calculate the time difference in seconds DIFF_PRECISION_TIME(mSeconds, finishTime, startTime); return bestmove; } //-------------------------------------------------------------------------- // Class: PVSearch // Method: DoSearch // Description: Performs the actual principle variation search //-------------------------------------------------------------------------- int PVSearch::DoSearch(int depth, int alpha, int beta, vector<Move>& pline) { bool foundPV = false; int score; vector<Move> line; // Check to see whether we should abort if (--mNextCheck <= 0) { mNextCheck = NODES_BETWEEN_TIME_CHECKS; if ( mpEngine->SearchAborted() ) { mAbort = true; return 0; } } // Flip sides mSide = 1 - mSide; // Check for any search repetitions if ( mpRepTable->CheckForRepetition(mpBoard->mHashKey) ) { // Make sure that our opponent doesn't win on the next move score = DoQuiescenceSearch(mQuiescenceDepth-1, MINIMUM_SCORE, MAXIMUM_SCORE, line); if (score != MAXIMUM_SCORE) { score = REPETITION_SCORE; } } // Check for whether we have reached the end of our search depth else if (depth == mSearchDepth) { if (mQuiescenceOn) score = DoQuiescenceSearch(1, alpha, beta, line); else score = mpEvaluator->FullEvaluation(mSide); } // Conduct an actual search else { int phase = MoveGenerator::GENERATE_CAPTURES; vector<Move> movelist; // Start generating moves Move* move = mpMoveGenerator->GetNextMove(movelist, phase, mSide); // Recursively search each move while(move) { mNodes++; // Count the nodes that we search mpRepTable->AddKey( mpBoard->MakeMove(move) ); PRINT_DESCENT(depth, alpha, beta, move, "Search"); if ( mpGame->GameWon(mSide) ) { score = MAXIMUM_SCORE; } else { if (foundPV) { score = -DoSearch(depth+1, -alpha-1, -alpha, line); if ((score > alpha) && (score < beta)) { // Oops. This wasn't really a Principle Variation node score = -DoSearch(depth+1, -beta, -alpha, line); } } else { score = -DoSearch(depth+1, -beta, -alpha, line); } } if (mAbort) return 0; mpRepTable->RemoveKey( mpBoard->UnmakeMove(move) ); PRINT_SCORE(depth, score, alpha, beta); if (score >= beta) { // Check for a beta cutoff mCutOffs++; alpha = beta; move = 0; } else if (score > alpha) { // Is this score good enough to use? alpha = score; pline.clear(); pline.push_back(*move); pline.insert(pline.end(), line.begin(), line.end()); foundPV = true; movelist.pop_back(); move = mpMoveGenerator->GetNextMove(movelist, phase, mSide); } else { movelist.pop_back(); move = mpMoveGenerator->GetNextMove(movelist, phase, mSide); } } // Set the score that we will return score = alpha; } // Flip sides back mSide = 1 - mSide; return score; }
29.570922
76
0.536515
jweathers777
a320643d640b715c53ff9a7f368226971eaf910f
571
hpp
C++
include/RED4ext/Scripting/Natives/Generated/vehicle/DetachAllPartsEvent.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/vehicle/DetachAllPartsEvent.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/vehicle/DetachAllPartsEvent.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/red/Event.hpp> namespace RED4ext { namespace vehicle { struct DetachAllPartsEvent : red::Event { static constexpr const char* NAME = "vehicleDetachAllPartsEvent"; static constexpr const char* ALIAS = "VehicleDetachAllPartsEvent"; }; RED4EXT_ASSERT_SIZE(DetachAllPartsEvent, 0x40); } // namespace vehicle using VehicleDetachAllPartsEvent = vehicle::DetachAllPartsEvent; } // namespace RED4ext
25.954545
70
0.782837
jackhumbert
a322f838d16e31946c4de0677916fd636994edf5
4,091
cpp
C++
kd_tree/ut/kd_tree_ut.cpp
Abergard/rtc
e0cdbbb4a005b7d9f3b10d1a519fcb6be876e65f
[ "MIT" ]
3
2019-05-25T01:03:38.000Z
2019-06-29T07:43:49.000Z
kd_tree/ut/kd_tree_ut.cpp
Abergard/rtc
e0cdbbb4a005b7d9f3b10d1a519fcb6be876e65f
[ "MIT" ]
1
2019-05-24T22:16:30.000Z
2019-05-24T22:16:30.000Z
kd_tree/ut/kd_tree_ut.cpp
Abergard/rtc
e0cdbbb4a005b7d9f3b10d1a519fcb6be876e65f
[ "MIT" ]
1
2019-05-24T19:12:44.000Z
2019-05-24T19:12:44.000Z
#include "gtest/gtest.h" #include "kd_tree.hpp" #include "scene_model.hpp" #include "brs.hpp" #include "point_in_triangle_test.hpp" #include "math_plane.hpp" #include "rtc_log.hpp" #include "scoped_timer.hpp" #include "ray_tracer.hpp" namespace rtc::ut { TEST(kd_tree_ut, room_test_found_1032) { auto scene = std::make_shared<rtc::brs>("./room.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{-6.788838F, 2.300512F, 4.642227F}; const rtc::math_ray ray{v, scene->optical_system.view_point}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(1032)); } TEST(kd_tree_ut, room_test_found_) { auto scene = std::make_shared<rtc::brs>("./room.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{-5.145645F, -0.382301F, 5.584966F}; const rtc::math_ray ray{v, scene->optical_system.view_point}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(843)); } TEST(kd_tree_ut, room_test_found_2) { auto scene = std::make_shared<rtc::brs>("./room.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{-4.396932F, -0.778016F, 6.014521F}; const rtc::math_ray ray{v, scene->optical_system.view_point}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(619)); } TEST(kd_tree_ut, kitchen_test_found) { auto scene = std::make_shared<rtc::brs>("./kitchen.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{2.139743F, -0.249007F, -1.756500F}; const rtc::math_ray ray{v, {2.435057F, 2.308806F, -0.50000F}}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(6695)); } TEST(kd_tree_ut, DISABLED_kitchen_test_found_2) { auto scene = std::make_shared<rtc::brs>("./kitchen.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{-3.624093F, 0.389207F, 3.397013F}; const rtc::math_ray ray{v, scene->optical_system.view_point}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(6721)); } TEST(kd_tree_ut, ulica_test_found) { auto scene = std::make_shared<rtc::brs>("./ulica.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{35.994164F, 12.552099F, 10.576778F}; const rtc::math_ray ray{v, scene->optical_system.view_point}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(15391)); } TEST(kd_tree_ut, ulica_test_found_2) { auto scene = std::make_shared<rtc::brs>("./ulica.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{-12.702606F, -25.481249F, 39.070004F}; const rtc::math_ray ray{v, {78.202606F, 28.281248F, 25.230000F}}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(15637)); } TEST(kd_tree_ut, ulica_test_found_3) { auto scene = std::make_shared<rtc::brs>("./ulica.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{-22.110607F, -23.501247F, 21.443001F}; const rtc::math_ray ray{v, {78.202606F, 28.281248F, 25.230000F}}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(31642)); } TEST(kd_tree_ut, DISABLED_cornell_box_test) { auto scene = std::make_shared<rtc::brs>("./cornell_box.xml"); rtc::kd_tree acc{*scene}; const rtc::math_vector v{1.066667F, 0.951870F, 3.365898F}; const rtc::math_ray ray{v, scene->optical_system.view_point}; rtc::ray_tracer<rtc::kd_tree> finder{std::move(acc), scene}; const auto intersect = finder.trace_ray(ray); ASSERT_TRUE(intersect && intersect.is_with(2)); } }
28.608392
67
0.712051
Abergard
a326145e89950ce2e2c611e9bd8f009190efbfd9
16,879
hh
C++
cpu6502.hh
bellcorreia/cpu6502
4fc1bc463ccdfac46e8443bfc14d4cbadf0d5736
[ "MIT" ]
3
2022-01-21T19:54:57.000Z
2022-01-23T04:44:56.000Z
cpu6502.hh
bellcorreia/cpu6502
4fc1bc463ccdfac46e8443bfc14d4cbadf0d5736
[ "MIT" ]
null
null
null
cpu6502.hh
bellcorreia/cpu6502
4fc1bc463ccdfac46e8443bfc14d4cbadf0d5736
[ "MIT" ]
null
null
null
/* * Source code written by Gabriel Correia */ #pragma once #include <array> #include <cstdint> #include <string_view> #include <cstdarg> #include <fmt/core.h> /* Set to 1 to enable callback functions */ #define USE_6502_CALLBACKS 1 /* Set to 1 to enable the internal ram memory (You don't will need to provide one into the constructor) */ #define USE_INTERNAL_RAM 0 constexpr uint16_t /* The start address location for the stack pointer, the stack will growing from 0x1ff to 0x100 */ START_STACK_ADDRESS = 0x1ff, /* The base stack address */ BASE_STACK_ADDRESS = 0x100, /* Default max RAM size (can be change normally by the developer) */ /* Using only 2KiB of memory (Nothing more) */ MAX_RAM_STORAGE = 0x800, /* Max rom storage */ MAX_ROM_STORAGE = 0xffff - MAX_RAM_STORAGE; /* The count of official 6502 instructions count */ constexpr unsigned CPU_6502_INSTRUCTION_COUNT = 151; /* The status after the reset signal */ constexpr uint8_t RESET_STATUS_SIGNAL = 0xfb; enum class IVT_index { ABORT, COP, IRQ_BRK, NMI, RESET }; enum class CPU_status { CARRY, ZERO, IRQ, DECIMAL, BRK, OVERFLOW, NEGATIVE }; enum class CPU_content { REG_A, REG_X, REG_Y, PC, SP, DATA, ADDRESS }; constexpr uint16_t INTERRUPT_VECTOR_TABLE[5][2] = { /* ABORT */ {0xfff8, 0xfff9}, /* COP (UNUSED) */ {0xfff4, 0xfff5}, /* IRQ AND BRK */ {0xfffe, 0xffff}, /* NMI REQUEST */ {0xfffa, 0xfffb}, /* RESET */ {0xfffc, 0xfffd} }; /* 6502 Memory layout [END ROM] [0xffff] |INT VECTORS| [0xfff4] |ROM MEMORY] [0x7fff] |MAIN RAM| [0x01ff] |STACK| [0x0100] |ZERO PAGE| [0x0000] */ #if USE_6502_CALLBACKS typedef uint8_t (*cpu_read) (uint16_t); typedef void (*cpu_write) (uint16_t, uint8_t); #endif class cpu6502 { public: #if USE_6502_CALLBACKS cpu6502 (cpu_read read_function, cpu_write write_function); #else cpu6502 (uint8_t *ram, uint8_t *rom); #endif ~cpu6502 () = default; void reset (); void printcs (); /* Interrupt request functions */ void nmi (); void irq (); /* ABORT is raised when a invalid opcode has been detected */ void abort (); /* Execute cycles_count cycles */ std::pair<size_t, size_t> clock (size_t cycles_count, size_t &executed_cycles); size_t step (size_t &executed_cycles); std::pair<size_t, size_t> step_count (size_t cycles_count, size_t &executed_cycles); /* Processor status manipulation functions */ bool getf (CPU_status status) const; void setf (CPU_status status, bool state); /* Some get functions, commoly used into unit test code section */ auto get_register_a () const { return m_a; } auto get_register_x () const { return m_x; } auto get_register_y () const { return m_y; } auto get_register_pc () const { return m_pc; } auto get_register_s () const { return m_s; } auto get_last_fetched_data () const { return m_data; } auto get_last_acceded_address () const { return m_address; } private: /* Functions and variables used in the read/write data operations */ /* This variables will be used to read and write into the memory (a read operation will store the result * in 2 bytes, a write operation will perform a AND with 0x00ff and a cast for uint8_t before wrote the data) */ uint16_t m_data{}; uint16_t m_address{}; #if USE_6502_CALLBACKS #else constexpr uint8_t* select_memory (uint16_t address) const { uint8_t *memory{}; if (address < MAX_RAM_STORAGE) memory = m_ram; else memory = m_rom; return memory; } #endif uint8_t make_branch (bool condition) { uint16_t branch_address; read_memory8 (); if (condition) { branch_address = m_pc + ((int8_t)m_data); m_pc = branch_address; } return check_pages (branch_address, m_pc) + 1; } /* CPU read/write operations (8 and 16 bit ranges are implemented) */ void read_memory16 (); void read_memory8 (); void write_memory8 (); void write_memory16 (); #if USE_6502_CALLBACKS cpu_read m_cpu_read_function{}; cpu_write m_cpu_write_function{}; #endif bool check_pages (uint16_t first, uint16_t second) { /* 0x`00´ff ONE PAGE */ /* 0x`01´00 ANOTHER PAGE */ if ((first & 0xff00) != (second & 0xff00)) return true; return false; } void push8 () { m_address = --m_s | BASE_STACK_ADDRESS; /* "Allocating" memory into the stack */ /* Writting data into it */ write_memory8 (); } void push16 () { push8 (); m_data >>= 8; push8 (); } void pop8 () { /* Pop a 8 bit value from the stack */ m_address = m_s++ | BASE_STACK_ADDRESS; read_memory8 (); } void pop16 () { m_address = m_s++; read_memory16 (); m_s++; } /* General purposes registers */ uint8_t m_a{}, m_x{}, m_y{}; #if USE_6502_CALLBACKS #else #if USE_INTERNAL_RAM std::array<uint8_t, MAX_RAM_STORAGE> m_ram; #else uint8_t *m_ram{}; #endif uint8_t *m_rom{}; #endif /* CPU status register */ union { struct { unsigned carry: 1; unsigned zero: 1; unsigned irq: 1; unsigned decimal: 1; unsigned brk: 1; unsigned reserved: 1; unsigned overflow: 1; unsigned negative: 1; }; uint8_t status; } m_p{}; /* Stack pointer register */ uint8_t m_s{}; /* PC (The program counter) the dual register used to pointer to the next operation to be executed by the CPU */ uint16_t m_pc{}; /* All cycles wasted will be stored into this variable */ uint64_t m_cycles_wasted{}; /* Skip N cycles, this ability is used into emulators/simulators env */ uint16_t m_skip_cycles{}; /* A specif status to determine if the instruction will use the accumulator register * to retrieve the operand or not */ bool m_use_accumulator{}; /* Setted if the current operation can promove a cross a page */ bool m_can_page_cross{}; /* Helper functions with the addressing processor specs */ typedef void (cpu6502::*loadaddr_t) (); loadaddr_t m_load_address{}; #pragma region /* Instruction operations */ uint8_t cpu_adc (); uint8_t cpu_and (); uint8_t cpu_asl (); uint8_t cpu_bcc (); uint8_t cpu_bcs (); uint8_t cpu_beq (); uint8_t cpu_bit (); uint8_t cpu_bmi (); uint8_t cpu_bne (); uint8_t cpu_bpl (); uint8_t cpu_brk (); uint8_t cpu_bvc (); uint8_t cpu_bvs (); uint8_t cpu_clc (); uint8_t cpu_cld (); uint8_t cpu_cli (); uint8_t cpu_clv (); uint8_t cpu_cmp (); uint8_t cpu_cpx (); uint8_t cpu_cpy (); uint8_t cpu_dec (); uint8_t cpu_dex (); uint8_t cpu_dey (); uint8_t cpu_eor (); uint8_t cpu_inc (); uint8_t cpu_inx (); uint8_t cpu_iny (); uint8_t cpu_jmp (); uint8_t cpu_jsr (); uint8_t cpu_lda (); uint8_t cpu_ldx (); uint8_t cpu_ldy (); uint8_t cpu_lsr (); uint8_t cpu_nop (); uint8_t cpu_ora (); uint8_t cpu_pha (); uint8_t cpu_php (); uint8_t cpu_pla (); uint8_t cpu_plp (); uint8_t cpu_rol (); uint8_t cpu_ror (); uint8_t cpu_rti (); uint8_t cpu_rts (); uint8_t cpu_sbc (); uint8_t cpu_sec (); uint8_t cpu_sed (); uint8_t cpu_sei (); uint8_t cpu_sta (); uint8_t cpu_stx (); uint8_t cpu_sty (); uint8_t cpu_tax (); uint8_t cpu_tay (); uint8_t cpu_tsx (); uint8_t cpu_txa (); uint8_t cpu_txs (); uint8_t cpu_tya (); /* Addressing modes operations */ void mem_none (); void mem_a (); void mem_abs (); void mem_absx (); void mem_absy (); void mem_imm (); void mem_impl (); void mem_ind (); void mem_indx (); void mem_indy (); void mem_rel (); void mem_zp (); void mem_zpx (); void mem_zpy (); #pragma endregion "CPU instructions definition" #pragma region typedef struct opcode_info_st { /* Referenced function to be executed */ uint8_t (cpu6502::* instruction) (); /* The addressing mode needed to be performed until the operation call */ void (cpu6502::* addressing) (); /* The count of cycles wasted to execute the current instruction */ uint8_t cycles_wasted; /* The switch to advice the CPU that the current instruction can extrapolate the wasted cycles */ uint8_t can_exceeded; /* The count of bytes consumed inside all operation */ uint8_t bytes_consumed; } opcode_info_t; using cpu = cpu6502; std::array<opcode_info_t, 0x100> const m_cpu_isa {{ {&cpu::cpu_brk, &cpu::mem_impl, 7, 0, 1}, {&cpu::cpu_ora, &cpu::mem_indx, 6, 0, 2}, {}, {}, {}, {&cpu::cpu_ora, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_asl, &cpu::mem_zpx, 5, 0, 2}, {}, {&cpu::cpu_php, &cpu::mem_impl, 3, 0, 1}, {&cpu::cpu_ora, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_asl, &cpu::mem_a, 2, 0, 1}, {}, {}, {&cpu::cpu_ora, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_asl, &cpu::mem_abs, 6, 0, 3}, {}, {&cpu::cpu_bpl, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_ora, &cpu::mem_indy, 5, 0, 2}, {}, {}, {}, {&cpu::cpu_ora, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_asl, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_clc, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_ora, &cpu::mem_absy, 4, 1, 3}, {}, {}, {}, {&cpu::cpu_ora, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_asl, &cpu::mem_absx, 7, 0, 3}, {}, {&cpu::cpu_jsr, &cpu::mem_abs, 6, 0, 3}, {&cpu::cpu_and, &cpu::mem_indx, 6, 0, 2}, {}, {}, {&cpu::cpu_bit, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_and, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_rol, &cpu::mem_zp, 5, 0, 2}, {}, {&cpu::cpu_plp, &cpu::mem_impl, 4, 0, 1}, {&cpu::cpu_and, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_rol, &cpu::mem_a, 2, 0, 1}, {}, {&cpu::cpu_bit, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_and, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_rol, &cpu::mem_abs, 6, 0, 3}, {}, {&cpu::cpu_bmi, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_and, &cpu::mem_indy, 5, 1, 2}, {}, {}, {}, {&cpu::cpu_and, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_rol, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_sec, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_and, &cpu::mem_absy, 5, 1, 2}, {}, {}, {}, {&cpu::cpu_and, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_rol, &cpu::mem_absx, 7, 0, 3}, {}, {&cpu::cpu_rti, &cpu::mem_impl, 6, 0, 1}, {&cpu::cpu_eor, &cpu::mem_indx, 6, 0, 2}, {}, {}, {}, {&cpu::cpu_eor, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_lsr, &cpu::mem_zp, 5, 0, 2}, {}, {&cpu::cpu_pha, &cpu::mem_impl, 3, 0, 1}, {&cpu::cpu_eor, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_lsr, &cpu::mem_a, 2, 0, 1}, {}, {&cpu::cpu_jmp, &cpu::mem_abs, 3, 0, 3}, {&cpu::cpu_eor, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_lsr, &cpu::mem_abs, 6, 0, 3}, {}, {&cpu::cpu_bvc, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_eor, &cpu::mem_indy, 5, 1, 2}, {}, {}, {}, {&cpu::cpu_eor, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_lsr, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_cli, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_eor, &cpu::mem_absy, 4, 1, 3}, {}, {}, {}, {&cpu::cpu_eor, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_lsr, &cpu::mem_absx, 7, 0, 3}, {}, {&cpu::cpu_rts, &cpu::mem_impl, 6, 0, 1}, {&cpu::cpu_adc, &cpu::mem_indx, 6, 0, 2}, {}, {}, {}, {&cpu::cpu_adc, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_ror, &cpu::mem_zp, 5, 0, 2}, {}, {&cpu::cpu_pla, &cpu::mem_impl, 4, 0, 1}, {&cpu::cpu_adc, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_ror, &cpu::mem_a, 2, 0, 1}, {}, {&cpu::cpu_jmp, &cpu::mem_ind, 5, 0, 3}, {&cpu::cpu_adc, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_ror, &cpu::mem_abs, 6, 0, 3}, {}, {&cpu::cpu_bvs, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_adc, &cpu::mem_indy, 5, 1, 2}, {}, {}, {}, {&cpu::cpu_adc, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_ror, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_sei, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_adc, &cpu::mem_absy, 4, 1, 3}, {}, {}, {}, {&cpu::cpu_adc, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_ror, &cpu::mem_absx, 7, 0, 3}, {}, {}, {&cpu::cpu_sta, &cpu::mem_indx, 6, 0, 2}, {}, {}, {&cpu::cpu_sty, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_sta, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_stx, &cpu::mem_zp, 3, 0, 2}, {}, {&cpu::cpu_dey, &cpu::mem_impl, 2, 0, 1}, {}, {&cpu::cpu_tax, &cpu::mem_impl, 2, 0, 1}, {}, {&cpu::cpu_sty, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_sta, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_stx, &cpu::mem_zp, 3, 0, 2}, {}, {&cpu::cpu_bcc, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_sta, &cpu::mem_indy, 6, 0, 2}, {}, {}, {&cpu::cpu_sty, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_sta, &cpu::mem_absx, 5, 0, 3}, {&cpu::cpu_stx, &cpu::mem_zpy, 4, 0, 2}, {}, {&cpu::cpu_tya, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_sta, &cpu::mem_absy, 5, 0, 3}, {&cpu::cpu_txs, &cpu::mem_impl, 2, 0, 1}, {}, {}, {&cpu::cpu_sta, &cpu::mem_absx, 5, 0, 3}, {}, {}, {&cpu::cpu_ldy, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_lda, &cpu::mem_indx, 6, 0, 2}, {&cpu::cpu_ldx, &cpu::mem_imm, 2, 0, 2}, {}, {&cpu::cpu_ldy, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_lda, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_ldx, &cpu::mem_zp, 3, 0, 2}, {}, {&cpu::cpu_tay, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_lda, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_tax, &cpu::mem_impl, 2, 0, 1}, {}, {&cpu::cpu_ldy, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_lda, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_ldx, &cpu::mem_abs, 4, 0, 3}, {}, {&cpu::cpu_bcs, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_lda, &cpu::mem_indy, 5, 1, 2}, {}, {}, {&cpu::cpu_ldy, &cpu::mem_zp, 4, 0, 2}, {&cpu::cpu_lda, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_lda, &cpu::mem_zpy, 4, 0, 2}, {}, {&cpu::cpu_clv, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_lda, &cpu::mem_absy, 4, 1, 3}, {&cpu::cpu_tsx, &cpu::mem_impl, 2, 0, 1}, {}, {&cpu::cpu_ldy, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_lda, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_ldx, &cpu::mem_absy, 4, 1, 3}, {}, {&cpu::cpu_cpy, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_cmp, &cpu::mem_indx, 6, 0, 2}, {}, {}, {&cpu::cpu_cpy, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_cmp, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_dec, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_iny, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_cmp, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_dex, &cpu::mem_impl, 2, 0, 1}, {}, {&cpu::cpu_cpy, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_cmp, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_dec, &cpu::mem_abs, 6, 0, 3}, {}, {&cpu::cpu_bne, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_cmp, &cpu::mem_indy, 5, 1, 2}, {}, {}, {}, {&cpu::cpu_cmp, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_dec, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_cld, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_cmp, &cpu::mem_absy, 4, 1, 3}, {}, {}, {}, {&cpu::cpu_cmp, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_dec, &cpu::mem_absx, 7, 0, 3}, {}, {&cpu::cpu_cpx, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_sbc, &cpu::mem_indx, 6, 0, 2}, {}, {}, {&cpu::cpu_cpx, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_sbc, &cpu::mem_zp, 3, 0, 2}, {&cpu::cpu_inc, &cpu::mem_zp, 5, 0, 2}, {}, {&cpu::cpu_inx, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_sbc, &cpu::mem_imm, 2, 0, 2}, {&cpu::cpu_nop, &cpu::mem_impl, 2, 0, 1}, {}, {&cpu::cpu_cpx, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_sbc, &cpu::mem_abs, 4, 0, 3}, {&cpu::cpu_inc, &cpu::mem_abs, 6, 0, 3}, {}, {&cpu::cpu_beq, &cpu::mem_rel, 2, 1, 2}, {&cpu::cpu_sbc, &cpu::mem_indy, 5, 1, 2}, {}, {}, {}, {&cpu::cpu_sbc, &cpu::mem_zpx, 4, 0, 2}, {&cpu::cpu_inc, &cpu::mem_zpx, 6, 0, 2}, {}, {&cpu::cpu_sed, &cpu::mem_impl, 2, 0, 1}, {&cpu::cpu_sbc, &cpu::mem_absy, 4, 1, 3}, {}, {}, {}, {&cpu::cpu_sbc, &cpu::mem_absx, 4, 1, 3}, {&cpu::cpu_inc, &cpu::mem_absx, 7, 0, 3}, {} }}; #pragma endregion "Opcodes table" };
38.802299
117
0.538361
bellcorreia
cd11546ea1f13d1c68b459d3a0a1c84a18081463
1,496
cpp
C++
tools/PTPServerProc/ErrorIds.cpp
SergeyStrukov/CCore-4-xx
5faeadd50a24a7dbe18ffff8efe5f49212588637
[ "BSL-1.0" ]
null
null
null
tools/PTPServerProc/ErrorIds.cpp
SergeyStrukov/CCore-4-xx
5faeadd50a24a7dbe18ffff8efe5f49212588637
[ "BSL-1.0" ]
null
null
null
tools/PTPServerProc/ErrorIds.cpp
SergeyStrukov/CCore-4-xx
5faeadd50a24a7dbe18ffff8efe5f49212588637
[ "BSL-1.0" ]
null
null
null
/* ErrorIds.cpp */ //---------------------------------------------------------------------------------------- // // Project: PTPServerProc 1.00 // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2021 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include "ErrorIds.h" namespace PTPServerProc { /* functions */ StrLen GetErrorDesc(ErrorIdType error_id) { if( error_id>=ErrorBase && error_id<=ErrorBase+FileError_Some ) { FileError fe=FileError(error_id-ErrorBase); return GetTextDesc(fe); } switch( error_id ) { case NoError : return "Ok"; case Error_NoFunction : return "No such service/function"; case Error_BadInput : return "Bad input data format"; case Error_Exhausted : return "Not enough resources"; case Error_Unknown : return "Unknown error"; case Error_ConNotOpened : return "Console is not opened"; case Error_BadConId : return "Bad console id"; case Error_CannotOpenMoreCon : return "Cannot open more consoles"; case Error_ReadStarted : return "Console read is already started"; case Error_WriteFault : return "Write fault"; default: return "Unknown error code"; } } } // namespace PTPServerProc
25.355932
90
0.562834
SergeyStrukov
cd130eaee54e95d1ac77e222e60be8edc99fc892
18,264
cpp
C++
1368 - Truchet Tiling .cpp
anirudha-ani/LightOJ
619d637f28fce3c9e15d0d3590d59ef75d8d6cb3
[ "Apache-2.0" ]
1
2020-04-25T03:09:12.000Z
2020-04-25T03:09:12.000Z
1368 - Truchet Tiling .cpp
anirudha-ani/LightOJ
619d637f28fce3c9e15d0d3590d59ef75d8d6cb3
[ "Apache-2.0" ]
null
null
null
1368 - Truchet Tiling .cpp
anirudha-ani/LightOJ
619d637f28fce3c9e15d0d3590d59ef75d8d6cb3
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string graph[105]; double PI = acos(-1.0); double area[6]; int test_case , R , C , query_no , row , column; double BFS(int row , int column) { double answer = 0.0; queue<int> row_line; queue<int> column_line; queue<int> type_line; bool visited[105][105][6]; int pushing; for(int i = 0 ; i < 105 ; i++) { for(int j = 0 ; j < 105 ; j++) { for(int k = 0 ; k < 6 ; k++) { visited[i][j][k] = false; } } } if(row%2 != 0) { int ROW = row/2; int COL = column/2; if(graph[ROW][COL] == '0') { pushing = 1; type_line.push(1); } else { pushing = 4; type_line.push(4); } row_line.push(ROW); column_line.push(COL); visited[ROW][COL][pushing] = true; } else if(row == 0 || column == 0) { if(row == 0 && column == 0) { if(graph[0][0] == '0') { pushing = 0; type_line.push(0); } else { pushing = 4; type_line.push(4); } row_line.push(0); column_line.push(0); visited[0][0][pushing] = true; } else if(row == 0) { int COL = (column/2) - 1; if(graph[0][COL] == '0') { pushing = 1; type_line.push(1); } else { pushing = 5; type_line.push(5); } row_line.push(0); column_line.push(COL); visited[0][COL][pushing] = true; } else if(column == 0) { int ROW = (row/2) - 1; if(graph[ROW][0] == '0') { pushing = 1; type_line.push(1); } else { pushing = 3; type_line.push(3); } row_line.push(ROW); column_line.push(0); visited[ROW][0][pushing] = true; } } else { int ROW = (row/2)-1; int COL = (column/2) - 1; if(graph[ROW][COL] == '0') { pushing = 2; type_line.push(2); } else { pushing = 4; type_line.push(4); } row_line.push(ROW); column_line.push(COL); visited[ROW][COL][pushing] = true; } while(row_line.empty() != true) { int current_row = row_line.front(); int current_column = column_line.front(); int current_type = type_line.front(); // cout << "Current Row = " << current_row << endl; // cout << "Current Column = " << current_column << endl; // cout << "Current Type = " << current_type << endl; // cout << "Area = " << area[current_type]<< endl; answer += area[current_type]; // cout << "Answer = " << answer << endl; row_line.pop(); column_line.pop(); type_line.pop(); if(current_type == 0) { if(current_column - 1 >=0 ) { if(graph[current_row][current_column - 1] == '0' && visited[current_row][current_column - 1][1] != true) { visited[current_row][current_column - 1][1] = true; type_line.push(1); row_line.push(current_row); column_line.push(current_column - 1); } else if (graph[current_row][current_column - 1] == '1' && visited[current_row][current_column - 1][5] != true) { visited[current_row][current_column - 1][5] = true; type_line.push(5); row_line.push(current_row); column_line.push(current_column - 1); } } if(current_row - 1 >= 0 ) { if(graph[current_row - 1][current_column] == '0' && visited[current_row - 1][current_column][1] == false) { visited[current_row - 1][current_column][1] = true; type_line.push(1); row_line.push(current_row - 1); column_line.push(current_column ); } else if(graph[current_row - 1][current_column] == '1' && visited[current_row - 1][current_column][3] == false) { visited[current_row - 1][current_column][3] = true; type_line.push(3); row_line.push(current_row - 1); column_line.push(current_column ); } } } else if(current_type == 1) { if(current_column - 1 >=0 ) { if(graph[current_row][current_column - 1] == '0'&& visited[current_row][current_column - 1][2] == false) { visited[current_row][current_column - 1][2] = true; type_line.push(2); row_line.push(current_row); column_line.push(current_column - 1); } else if(graph[current_row][current_column - 1] == '1'&& visited[current_row][current_column - 1][4] == false) { visited[current_row][current_column - 1][4] = true; type_line.push(4); row_line.push(current_row); column_line.push(current_column - 1); } } if(current_row - 1 >= 0 ) { if(graph[current_row - 1][current_column] == '0'&& visited[current_row - 1][current_column][2] == false) { visited[current_row - 1][current_column][2] = true; type_line.push(2); row_line.push(current_row - 1); column_line.push(current_column); } else if(graph[current_row - 1][current_column] == '1'&& visited[current_row - 1][current_column][4] == false) { visited[current_row - 1][current_column][4] = true; type_line.push(4); row_line.push(current_row - 1); column_line.push(current_column); } } if(current_row + 1 < R) { if(graph[current_row + 1][current_column] == '0' && visited[current_row + 1][current_column][0] == false) { visited[current_row + 1][current_column][0] = true; type_line.push(0); row_line.push(current_row + 1); column_line.push(current_column); } else if(graph[current_row + 1][current_column] == '1' && visited[current_row + 1][current_column][4] == false) { visited[current_row + 1][current_column][4] = true; type_line.push(4); row_line.push(current_row + 1); column_line.push(current_column); } } if(current_column + 1 < C) { if(graph[current_row][current_column+1] == '0' && visited[current_row][current_column+1][0] == false) { visited[current_row][current_column+1][0] = true; type_line.push(0); row_line.push(current_row); column_line.push(current_column + 1); } else if(graph[current_row][current_column+1] == '1' && visited[current_row][current_column+1][4] == false) { visited[current_row][current_column+1][4] = true; type_line.push(4); row_line.push(current_row); column_line.push(current_column + 1); } } } // I finished here else if(current_type == 2) { if(current_row + 1 < R ) { if(graph[current_row + 1][current_column] == '0' && visited[current_row + 1][current_column][1] == false) { visited[current_row + 1][current_column][1] = true; type_line.push(1); row_line.push(current_row + 1); column_line.push(current_column); } else if(graph[current_row + 1][current_column] == '1' && visited[current_row + 1][current_column][5] == false) { visited[current_row + 1][current_column][5] = true; type_line.push(5); row_line.push(current_row + 1); column_line.push(current_column); } } if(current_column + 1 < C ) { if(graph[current_row][current_column+1] == '0'&& visited[current_row][current_column+1][1] == false) { visited[current_row][current_column+1][1] = true; type_line.push(1); row_line.push(current_row); column_line.push(current_column + 1); } else if(graph[current_row][current_column+1] == '1'&& visited[current_row][current_column+1][3] == false) { visited[current_row][current_column+1][3] = true; type_line.push(3); row_line.push(current_row); column_line.push(current_column + 1); } } } else if(current_type == 3) { if(current_column - 1 >=0 ) { if(graph[current_row][current_column - 1] == '0' && visited[current_row][current_column - 1][2] == false) { visited[current_row][current_column - 1][2] = true; type_line.push(2); row_line.push(current_row); column_line.push(current_column - 1); } else if(graph[current_row][current_column - 1] == '1' && visited[current_row][current_column - 1][4] == false) { visited[current_row][current_column - 1][4] = true; type_line.push(4); row_line.push(current_row); column_line.push(current_column - 1); } } if(current_row + 1 < R ) { if(graph[current_row + 1][current_column] == '0' && visited[current_row + 1][current_column][0] == false) { visited[current_row + 1][current_column][0] = true; type_line.push(0); row_line.push(current_row + 1); column_line.push(current_column); } else if(graph[current_row + 1][current_column] == '1' && visited[current_row + 1][current_column][4] == false) { visited[current_row + 1][current_column][4] = true; type_line.push(4); row_line.push(current_row + 1); column_line.push(current_column); } } } else if(current_type == 4) { if(current_column - 1 >=0) { if(graph[current_row][current_column - 1] == '0' && visited[current_row][current_column - 1][1] == false) { visited[current_row][current_column - 1][1] = true; type_line.push(1); row_line.push(current_row); column_line.push(current_column - 1); } else if(graph[current_row][current_column - 1] == '1' && visited[current_row][current_column - 1][5]== false) { visited[current_row][current_column - 1][5] = true; type_line.push(5); row_line.push(current_row); column_line.push(current_column - 1); } } if(current_row - 1 >= 0) { if(graph[current_row - 1][current_column] == '0' && visited[current_row - 1][current_column][1] == false) { visited[current_row - 1][current_column][1] = true; type_line.push(1); row_line.push(current_row - 1); column_line.push(current_column); } else if(graph[current_row - 1][current_column] == '1' && visited[current_row - 1][current_column][3] == false) { visited[current_row - 1][current_column][3] = true; type_line.push(3); row_line.push(current_row - 1); column_line.push(current_column); } } if(current_row + 1 < R ) { if(graph[current_row + 1][current_column] == '0' && visited[current_row + 1][current_column][1] == false) { visited[current_row + 1][current_column][1] = true; type_line.push(1); row_line.push(current_row + 1); column_line.push(current_column); } else if(graph[current_row + 1][current_column] == '1' && visited[current_row + 1][current_column][5] == false) { visited[current_row + 1][current_column][5] = true; type_line.push(5); row_line.push(current_row + 1); column_line.push(current_column); } } if(current_column + 1 < C ) { if(graph[current_row][current_column+1] == '0' && visited[current_row][current_column+1][1] == false) { visited[current_row][current_column+1][1] = true; type_line.push(1); row_line.push(current_row); column_line.push(current_column + 1); } else if(graph[current_row][current_column+1] == '1' && visited[current_row][current_column+1][3] == false) { visited[current_row][current_column+1][3] = true; type_line.push(3); row_line.push(current_row); column_line.push(current_column + 1); } } } else if(current_type == 5) { if(current_row - 1 >= 0 ) { if(graph[current_row - 1][current_column] == '0' && visited[current_row - 1][current_column][2] == false) { visited[current_row - 1][current_column][2] = true; type_line.push(2); row_line.push(current_row - 1); column_line.push(current_column); } else if(graph[current_row - 1][current_column] == '1' && visited[current_row - 1][current_column][4] == false) { visited[current_row - 1][current_column][4] = true; type_line.push(4); row_line.push(current_row - 1); column_line.push(current_column); } } if(current_column + 1 < C) { if(graph[current_row][current_column+1] == '0' && visited[current_row][current_column+1][0] == false) { visited[current_row][current_column+1][0] = true; type_line.push(0); row_line.push(current_row); column_line.push(current_column + 1); } else if(graph[current_row][current_column+1] == '1' && visited[current_row][current_column+1][4] == false) { visited[current_row][current_column+1][4] = true; type_line.push(4); row_line.push(current_row); column_line.push(current_column + 1); } } } } return answer; } int main() { // freopen("input.txt" , "r", stdin); // freopen("output.txt" , "w" , stdout); area[0] = PI / 4.0; area[1] = 4.0 - (2.0 *area[0]); area[2] = area[0]; area[3] = area[0]; area[4] = area[1]; area[5] = area[0]; // cout << area[0] << endl; // cout << area[1] << endl; scanf("%d", &test_case); for(int i = 0 ; i < test_case ; i++) { scanf("%d %d", &R , &C); for(int j = 0 ; j < R ; j++) { cin >> graph[j]; } scanf("%d", &query_no); printf("Case %d:\n",i+1); for(int j = 0 ; j < query_no ; j++) { scanf("%d %d", &row , &column); if((row%2 == 0 && column % 2 == 0) || (row%2 != 0 && column%2 != 0)) { printf("%.10lf\n",BFS(row , column)); } else { printf("0\n", row ,column); } } } return 0 ; }
35.952756
128
0.426796
anirudha-ani
cd155d5b088d7fe5e4a9dff4bd963338c350ef28
4,955
cpp
C++
ios/Arasan/src/searchc.cpp
mono424/flutter-arasan
9dc537c6bf84eb52998497fcd0cc754b6a5e22f9
[ "MIT" ]
1
2021-08-31T06:03:40.000Z
2021-08-31T06:03:40.000Z
ios/Arasan/src/searchc.cpp
mono424/flutter-arasan
9dc537c6bf84eb52998497fcd0cc754b6a5e22f9
[ "MIT" ]
null
null
null
ios/Arasan/src/searchc.cpp
mono424/flutter-arasan
9dc537c6bf84eb52998497fcd0cc754b6a5e22f9
[ "MIT" ]
1
2021-08-31T06:03:41.000Z
2021-08-31T06:03:41.000Z
// Copyright 2006-2008, 2011, 2017-2021 by Jon Dart. All Rights Reserved. #include "searchc.h" #include "search.h" SearchContext::SearchContext() { history = new ButterflyArray<int>(); counterMoves = new PieceToArray<Move>(); counterMoveHistory = new PieceTypeToMatrix<int>(); fuMoveHistory = new PieceTypeToMatrix<int>(); clear(); } SearchContext::~SearchContext() { delete history; delete counterMoves; delete counterMoveHistory; delete fuMoveHistory; } void SearchContext::clear() { clearKiller(); for (int side = 0; side < 2; side++) for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { (*history)[side][i][j] = 0; } } for (int i = 0; i < 16; i++) { for (int j = 0; j < 64; j++) { (*counterMoves)[i][j] = NullMove; } } // clear counter move history for (int i = 0; i < 8; i++) for (int j = 0; j < 64; j++) for (int k = 0; k < 8; k++) for (int l = 0; l < 64; l++) { (*counterMoveHistory)[i][j][k][l] = 0; (*fuMoveHistory)[i][j][k][l] = 0; } } void SearchContext::clearKiller() { for (int i = 0; i < Constants::MaxPly + 2; i++) { killers1[i] = killers2[i] = NullMove; } } int SearchContext::scoreForOrdering(Move m, NodeInfo *node, ColorType side) const noexcept { int score = (*history)[side][StartSquare(m)][DestSquare(m)]; if (node->ply > 0 && !IsNull((node - 1)->last_move)) { Move prevMove = (node - 1)->last_move; score += (*counterMoveHistory)[PieceMoved(prevMove)][DestSquare(prevMove)] [PieceMoved(m)][DestSquare(m)]; } if (node->ply > 1 && !IsNull((node - 2)->last_move)) { Move prevMove = (node - 2)->last_move; score += (*fuMoveHistory)[PieceMoved(prevMove)][DestSquare(prevMove)] [PieceMoved(m)][DestSquare(m)]; } return score; } static constexpr int MAX_HISTORY_DEPTH = 17; static constexpr int HISTORY_DIVISOR = 448; int SearchContext::bonus(int depth) const noexcept { const int d = depth / DEPTH_INCREMENT; return d <= MAX_HISTORY_DEPTH ? d * d + 5 * d - 2 : 0; } void SearchContext::update(int &val, int bonus, int divisor, bool is_best) { val -= val * bonus / divisor; if (is_best) val += bonus; else val -= bonus; } void SearchContext::updateStats(const Board &board, NodeInfo *node) { // sanity checks ASSERT(!IsNull(node->best)); ASSERT(OnBoard(StartSquare(node->best)) && OnBoard(DestSquare(node->best))); ASSERT(node->num_quiets < Constants::MaxMoves); // Do not update on fail high of 1st quiet and low depth (idea from // Ethereal). if (node->num_quiets == 1 && node->depth <= 3 * DEPTH_INCREMENT) return; for (int i = 0; i < node->num_quiets; i++) { const Move m = node->quiets[i]; updateMove(board,node,m,MovesEqual(m,node->best),false); } } void SearchContext::updateMove(const Board &board, NodeInfo *node, Move m, bool positive, bool continuationOnly) { const int b = bonus(node->depth); if (!continuationOnly) { update((*history)[board.sideToMove()][StartSquare(m)][DestSquare(m)], b, HISTORY_DIVISOR, positive); if (positive && PieceMoved(m) != Pawn) { update((*history)[board.sideToMove()][DestSquare(m)][StartSquare(m)], b, HISTORY_DIVISOR, false); } } if (node->ply > 0) { Move lastMove = (node - 1)->last_move; if (!IsNull(lastMove)) { update((*counterMoveHistory)[PieceMoved(lastMove)][DestSquare( lastMove)][PieceMoved(m)][DestSquare(m)], b, HISTORY_DIVISOR, positive); } if (node->ply > 1) { Move lastMove = (node - 2)->last_move; if (!IsNull(lastMove)) { update((*fuMoveHistory)[PieceMoved(lastMove)][DestSquare( lastMove)][PieceMoved(m)][DestSquare(m)], b, HISTORY_DIVISOR, positive); } } } } int SearchContext::getCmHistory(NodeInfo *node, Move move) const noexcept { if (node->ply == 0 || IsNull((node - 1)->last_move)) { return 0; } Move prev((node - 1)->last_move); return (*counterMoveHistory)[PieceMoved(prev)][DestSquare(prev)] [PieceMoved(move)][DestSquare(move)]; } int SearchContext::getFuHistory(NodeInfo *node, Move move) const noexcept { if (node->ply < 2 || IsNull((node - 2)->last_move)) { return 0; } Move prev((node - 2)->last_move); return (*fuMoveHistory)[PieceMoved(prev)][DestSquare(prev)] [PieceMoved(move)][DestSquare(move)]; }
34.409722
84
0.552775
mono424
cd180f290f5a7d4a21d7636ac0213e28d198ff6a
2,608
cpp
C++
examples/api/linear_arith.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
examples/api/linear_arith.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
examples/api/linear_arith.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file linear_arith.cpp ** \verbatim ** Top contributors (to current version): ** Tim King, Morgan Deters ** This file is part of the CVC4 project. ** Copyright (c) 2009-2016 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file COPYING in the top-level source ** directory for licensing information.\endverbatim ** ** \brief A simple demonstration of the linear arithmetic capabilities of CVC4 ** ** A simple demonstration of the linear arithmetic solving capabilities and ** the push pop of CVC4. This also gives an example option. **/ #include <iostream> //#include <cvc4/cvc4.h> // use this after CVC4 is properly installed #include "smt/smt_engine.h" using namespace std; using namespace CVC4; int main() { ExprManager em; SmtEngine smt(&em); smt.setLogic("QF_LIRA"); // Set the logic // Prove that if given x (Integer) and y (Real) then // the maximum value of y - x is 2/3 // Types Type real = em.realType(); Type integer = em.integerType(); // Variables Expr x = em.mkVar("x", integer); Expr y = em.mkVar("y", real); // Constants Expr three = em.mkConst(Rational(3)); Expr neg2 = em.mkConst(Rational(-2)); Expr two_thirds = em.mkConst(Rational(2,3)); // Terms Expr three_y = em.mkExpr(kind::MULT, three, y); Expr diff = em.mkExpr(kind::MINUS, y, x); // Formulas Expr x_geq_3y = em.mkExpr(kind::GEQ, x, three_y); Expr x_leq_y = em.mkExpr(kind::LEQ, x, y); Expr neg2_lt_x = em.mkExpr(kind::LT, neg2, x); Expr assumptions = em.mkExpr(kind::AND, x_geq_3y, x_leq_y, neg2_lt_x); cout << "Given the assumptions " << assumptions << endl; smt.assertFormula(assumptions); smt.push(); Expr diff_leq_two_thirds = em.mkExpr(kind::LEQ, diff, two_thirds); cout << "Prove that " << diff_leq_two_thirds << " with CVC4." << endl; cout << "CVC4 should report VALID." << endl; cout << "Result from CVC4 is: " << smt.query(diff_leq_two_thirds) << endl; smt.pop(); cout << endl; smt.push(); Expr diff_is_two_thirds = em.mkExpr(kind::EQUAL, diff, two_thirds); smt.assertFormula(diff_is_two_thirds); cout << "Show that the asserts are consistent with " << endl; cout << diff_is_two_thirds << " with CVC4." << endl; cout << "CVC4 should report SAT." << endl; cout << "Result from CVC4 is: " << smt.checkSat(em.mkConst(true)) << endl; smt.pop(); cout << "Thus the maximum value of (y - x) is 2/3."<< endl; return 0; }
30.682353
80
0.65069
guykatzz
cd1f034be9296a516ae1cd49c49cefe74a2ff2a2
5,856
cpp
C++
samples/Hello/third-party/fuzzylite/fuzzylite/src/activation/Threshold.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
samples/Hello/third-party/fuzzylite/fuzzylite/src/activation/Threshold.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
samples/Hello/third-party/fuzzylite/fuzzylite/src/activation/Threshold.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
/* fuzzylite (R), a fuzzy logic control library in C++. Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved. Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com> This file is part of fuzzylite. fuzzylite is free software: you can redistribute it and/or modify it under the terms of the FuzzyLite License included with the software. You should have received a copy of the FuzzyLite License along with fuzzylite. If not, see <http://www.fuzzylite.com/license/>. fuzzylite is a registered trademark of FuzzyLite Limited. */ #include "fl/activation/Threshold.h" #include "fl/rule/RuleBlock.h" #include "fl/rule/Rule.h" #include "fl/Operation.h" namespace fl { Threshold::Threshold(Comparison comparison, scalar threshold) : Activation(), _comparison(comparison), _value(threshold) { } Threshold::Threshold(const std::string& comparison, scalar threshold) : Activation(), _comparison(parseComparison(comparison)), _value(threshold) { } Threshold::~Threshold() { } std::string Threshold::className() const { return "Threshold"; } std::string Threshold::parameters() const { std::ostringstream ss; ss << comparisonOperator() << " " << Op::str(getValue()); return ss.str(); } void Threshold::configure(const std::string& parameters) { if (parameters.empty()) return; std::vector<std::string> values = Op::split(parameters, " "); std::size_t required = 2; if (values.size() < required) { std::ostringstream ex; ex << "[configuration error] activation <" << className() << ">" << " requires <" << required << "> parameters"; throw Exception(ex.str(), FL_AT); } setComparison(parseComparison(values.at(0))); setValue(Op::toScalar(values.at(1))); } void Threshold::setComparison(Comparison comparison) { this->_comparison = comparison; } Threshold::Comparison Threshold::getComparison() const { return this->_comparison; } std::string Threshold::comparisonOperator() const { return comparisonOperator(getComparison()); } std::string Threshold::comparisonOperator(Comparison comparison) const { switch (comparison) { case LessThan: return "<"; case LessThanOrEqualTo: return "<="; case EqualTo: return "=="; case NotEqualTo: return "!="; case GreaterThanOrEqualTo: return ">="; case GreaterThan: return ">"; default: return "?"; } } std::vector<std::string> Threshold::availableComparisonOperators() const { std::vector<std::string> result; result.push_back("<"); result.push_back("<="); result.push_back("=="); result.push_back("!="); result.push_back(">="); result.push_back(">"); return result; } Threshold::Comparison Threshold::parseComparison(const std::string& name) const { if (name == "<") return LessThan; if (name == "<=") return LessThanOrEqualTo; if (name == "==") return EqualTo; if (name == "!=") return NotEqualTo; if (name == ">=") return GreaterThanOrEqualTo; if (name == ">") return GreaterThan; throw Exception("[syntax error] invalid threshold type by name <" + name + ">", FL_AT); } void Threshold::setValue(scalar value) { this->_value = value; } scalar Threshold::getValue() const { return this->_value; } void Threshold::setThreshold(Comparison comparison, scalar threshold) { setComparison(comparison); setValue(threshold); } void Threshold::setThreshold(const std::string& comparison, scalar value) { setComparison(parseComparison(comparison)); setValue(value); } bool Threshold::activatesWith(scalar activationDegree) const { switch (getComparison()) { case LessThan: return Op::isLt(activationDegree, getValue()); case LessThanOrEqualTo: return Op::isLE(activationDegree, getValue()); case EqualTo: return Op::isEq(activationDegree, getValue()); case NotEqualTo: return not Op::isEq(activationDegree, getValue()); case GreaterThanOrEqualTo: return Op::isGE(activationDegree, getValue()); case GreaterThan: return Op::isGt(activationDegree, getValue()); default: return false; } } Complexity Threshold::complexity(const RuleBlock* ruleBlock) const { Complexity result; for (std::size_t i = 0; i < ruleBlock->rules().size(); ++i) { result.comparison(2); result += ruleBlock->rules().at(i)->complexity( ruleBlock->getConjunction(), ruleBlock->getDisjunction(), ruleBlock->getImplication()); } return result; } void Threshold::activate(RuleBlock* ruleBlock) { FL_DBG("Activation: " << className() << " " << parameters()); const TNorm* conjunction = ruleBlock->getConjunction(); const SNorm* disjunction = ruleBlock->getDisjunction(); const TNorm* implication = ruleBlock->getImplication(); for (std::size_t i = 0; i < ruleBlock->numberOfRules(); ++i) { Rule* rule = ruleBlock->getRule(i); rule->deactivate(); if (rule->isLoaded()) { scalar activationDegree = rule->activateWith(conjunction, disjunction); if (activatesWith(activationDegree)) { rule->trigger(implication); } } } } Threshold* Threshold::clone() const { return new Threshold(*this); } Activation* Threshold::constructor() { return new Threshold; } }
34.245614
95
0.608265
okocsis
cd1f6ba5b738ccf8d12b09698a881e4b19709038
760
hpp
C++
test/addrlist.hpp
zenomt/rtmfp-cpp
e85d8928d5192c5e16f963ca281a4c5a701dae7b
[ "MIT" ]
21
2021-01-25T07:33:12.000Z
2022-02-09T08:08:51.000Z
test/addrlist.hpp
zenomt/rtmfp-cpp
e85d8928d5192c5e16f963ca281a4c5a701dae7b
[ "MIT" ]
2
2021-04-25T15:30:27.000Z
2021-06-26T22:56:31.000Z
test/addrlist.hpp
zenomt/rtmfp-cpp
e85d8928d5192c5e16f963ca281a4c5a701dae7b
[ "MIT" ]
null
null
null
namespace { bool addrlist_parse(int argc, char * const *argv, int start_at, bool combined, std::vector<com::zenomt::rtmfp::Address> &dst) { int parts = combined ? 1 : 2; while(start_at < argc - parts + 1) { com::zenomt::rtmfp::Address each; if(not each.setFromPresentation(argv[start_at], combined)) { printf("can't parse address: %s\n", argv[start_at]); return false; } if(not combined) each.setPort(atoi(argv[start_at + 1])); dst.push_back(each); start_at += parts; } return true; } void add_candidates(std::shared_ptr<com::zenomt::rtmfp::SendFlow> flow, std::vector<com::zenomt::rtmfp::Address> &addrs) { for(auto it = addrs.begin(); it != addrs.end(); it++) flow->addCandidateAddress(*it, 0); } } // anonymous namespace
24.516129
125
0.672368
zenomt
cd2048965dfdb894aac2e660b85ca7ed263bcc6e
1,532
hpp
C++
libRay/Math/Vector.hpp
RA-Kooi/Ray-Tracer
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
[ "MIT" ]
3
2019-03-22T02:15:18.000Z
2019-11-12T08:12:57.000Z
libRay/Math/Vector.hpp
RA-Kooi/Ray-Tracer
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
[ "MIT" ]
null
null
null
libRay/Math/Vector.hpp
RA-Kooi/Ray-Tracer
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
[ "MIT" ]
null
null
null
#ifndef f51e2d4a_b54f_2fdf_a142_ebc7a4bcf3a3 #define f51e2d4a_b54f_2fdf_a142_ebc7a4bcf3a3 #include <cstddef> #include <ostream> #include <glm/gtx/extended_min_max.hpp> #include <glm/gtx/component_wise.hpp> #include <glm/gtx/norm.hpp> #include <glm/geometric.hpp> #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> namespace LibRay::Math { using Vector2 = glm::vec2; using Vector2st = glm::vec<2, std::size_t, glm::highp>; using Vector3 = glm::vec3; using Vector4 = glm::vec4; } // namespace LibRay::Math inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector4 const &v); inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector4 const &v) { return o << "[X: " << v.x << ", Y: " << v.y << ", Z: " << v.z << ", W: " << v.w << "]"; } inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector3 const &v); inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector3 const &v) { return o << "[X: " << v.x << ", Y: " << v.y << ", Z: " << v.z << "]"; } inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector2 const &v); inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector2 const &v) { return o << "[X: " << v.x << ", Y: " << v.y << "]"; } inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector2st const &v); inline std::ostream &operator<<(std::ostream &o, LibRay::Math::Vector2st const &v) { return o << "[X: " << v.x << ", Y: " << v.y << "]"; } #endif // f51e2d4a_b54f_2fdf_a142_ebc7a4bcf3a3
28.90566
83
0.633159
RA-Kooi
cd211fbfb0df0a4fecbc4a8b616854913fa3900e
2,449
cc
C++
lib/sanitizer_common/sanitizer_unwind_win.cc
remote-android/toolchain_compiler-rt
2ab6b9526fadddd76a15e0ecedf60462b2de2ed7
[ "Apache-2.0" ]
null
null
null
lib/sanitizer_common/sanitizer_unwind_win.cc
remote-android/toolchain_compiler-rt
2ab6b9526fadddd76a15e0ecedf60462b2de2ed7
[ "Apache-2.0" ]
null
null
null
lib/sanitizer_common/sanitizer_unwind_win.cc
remote-android/toolchain_compiler-rt
2ab6b9526fadddd76a15e0ecedf60462b2de2ed7
[ "Apache-2.0" ]
3
2021-11-28T11:21:54.000Z
2022-03-13T11:10:01.000Z
//===-- sanitizer_unwind_win.cc -------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// Sanitizer unwind Windows specific functions. // //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_WINDOWS #define WIN32_LEAN_AND_MEAN #define NOGDI #include <windows.h> #include "sanitizer_dbghelp.h" // for StackWalk64 #include "sanitizer_stacktrace.h" #include "sanitizer_symbolizer.h" // for InitializeDbgHelpIfNeeded using namespace __sanitizer; #if !SANITIZER_GO void BufferedStackTrace::SlowUnwindStack(uptr pc, u32 max_depth) { CHECK_GE(max_depth, 2); // FIXME: CaptureStackBackTrace might be too slow for us. // FIXME: Compare with StackWalk64. // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc size = CaptureStackBackTrace(1, Min(max_depth, kStackTraceMax), (void **)&trace_buffer[0], 0); if (size == 0) return; // Skip the RTL frames by searching for the PC in the stacktrace. uptr pc_location = LocatePcInTrace(pc); PopStackFrames(pc_location); } void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context, u32 max_depth) { CONTEXT ctx = *(CONTEXT *)context; STACKFRAME64 stack_frame; memset(&stack_frame, 0, sizeof(stack_frame)); InitializeDbgHelpIfNeeded(); size = 0; #if defined(_WIN64) int machine_type = IMAGE_FILE_MACHINE_AMD64; stack_frame.AddrPC.Offset = ctx.Rip; stack_frame.AddrFrame.Offset = ctx.Rbp; stack_frame.AddrStack.Offset = ctx.Rsp; #else int machine_type = IMAGE_FILE_MACHINE_I386; stack_frame.AddrPC.Offset = ctx.Eip; stack_frame.AddrFrame.Offset = ctx.Ebp; stack_frame.AddrStack.Offset = ctx.Esp; #endif stack_frame.AddrPC.Mode = AddrModeFlat; stack_frame.AddrFrame.Mode = AddrModeFlat; stack_frame.AddrStack.Mode = AddrModeFlat; while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(), &stack_frame, &ctx, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL) && size < Min(max_depth, kStackTraceMax)) { trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset; } } #endif // #if !SANITIZER_GO #endif // SANITIZER_WINDOWS
32.653333
80
0.685586
remote-android
cd2152777213364448188ea5ea4c3c6f7452ce6f
3,420
cpp
C++
Chapter_27/Model/Model.cpp
9ndres/Ray-Tracing-Gems-II
5fef3b49375c823431ef06f8c67d1b44b432304a
[ "MIT" ]
603
2021-08-04T11:46:33.000Z
2022-03-28T12:12:31.000Z
Chapter_27/Model/Model.cpp
9ndres/Ray-Tracing-Gems-II
5fef3b49375c823431ef06f8c67d1b44b432304a
[ "MIT" ]
null
null
null
Chapter_27/Model/Model.cpp
9ndres/Ray-Tracing-Gems-II
5fef3b49375c823431ef06f8c67d1b44b432304a
[ "MIT" ]
45
2021-08-04T18:57:37.000Z
2022-03-11T11:33:49.000Z
// // 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. // // Developed by Minigraph // // Author: Alex Nankervis // #include "Model.h" #include <string.h> #include <float.h> Model::Model() : m_pMesh(nullptr) , m_pMaterial(nullptr) , m_pVertexData(nullptr) , m_pIndexData(nullptr) , m_pVertexDataDepth(nullptr) , m_pIndexDataDepth(nullptr) , m_SRVs(nullptr) { Clear(); } Model::~Model() { Clear(); } void Model::Clear() { m_VertexBuffer.Destroy(); m_IndexBuffer.Destroy(); m_VertexBufferDepth.Destroy(); m_IndexBufferDepth.Destroy(); delete [] m_pMesh; m_pMesh = nullptr; m_Header.meshCount = 0; delete [] m_pMaterial; m_pMaterial = nullptr; m_Header.materialCount = 0; delete [] m_pVertexData; delete [] m_pIndexData; delete [] m_pVertexDataDepth; delete [] m_pIndexDataDepth; m_pVertexData = nullptr; m_Header.vertexDataByteSize = 0; m_pIndexData = nullptr; m_Header.indexDataByteSize = 0; m_pVertexDataDepth = nullptr; m_Header.vertexDataByteSizeDepth = 0; m_pIndexDataDepth = nullptr; ReleaseTextures(); m_Header.boundingBox.min = Vector3(0.0f); m_Header.boundingBox.max = Vector3(0.0f); } // assuming at least 3 floats for position void Model::ComputeMeshBoundingBox(unsigned int meshIndex, BoundingBox &bbox) const { const Mesh *mesh = m_pMesh + meshIndex; if (mesh->vertexCount > 0) { unsigned int vertexStride = mesh->vertexStride; const float *p = (float*)(m_pVertexData + mesh->vertexDataByteOffset + mesh->attrib[attrib_position].offset); const float *pEnd = (float*)(m_pVertexData + mesh->vertexDataByteOffset + mesh->vertexCount * mesh->vertexStride + mesh->attrib[attrib_position].offset); bbox.min = Scalar(FLT_MAX); bbox.max = Scalar(-FLT_MAX); while (p < pEnd) { Vector3 pos(*(p + 0), *(p + 1), *(p + 2)); bbox.min = Min(bbox.min, pos); bbox.max = Max(bbox.max, pos); (*(uint8_t**)&p) += vertexStride; } } else { bbox.min = Scalar(0.0f); bbox.max = Scalar(0.0f); } } void Model::ComputeGlobalBoundingBox(BoundingBox &bbox) const { if (m_Header.meshCount > 0) { bbox.min = Scalar(FLT_MAX); bbox.max = Scalar(-FLT_MAX); for (unsigned int meshIndex = 0; meshIndex < m_Header.meshCount; meshIndex++) { const Mesh *mesh = m_pMesh + meshIndex; bbox.min = Min(bbox.min, mesh->boundingBox.min); bbox.max = Max(bbox.max, mesh->boundingBox.max); } } else { bbox.min = Scalar(0.0f); bbox.max = Scalar(0.0f); } } void Model::ComputeAllBoundingBoxes() { for (unsigned int meshIndex = 0; meshIndex < m_Header.meshCount; meshIndex++) { Mesh *mesh = m_pMesh + meshIndex; ComputeMeshBoundingBox(meshIndex, mesh->boundingBox); } ComputeGlobalBoundingBox(m_Header.boundingBox); }
26.307692
162
0.609649
9ndres
cd228184f392b1e510e5ac075719c098c7f028c3
5,815
hpp
C++
arbor/include/arbor/math.hpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
53
2018-10-18T12:08:21.000Z
2022-03-26T22:03:51.000Z
arbor/include/arbor/math.hpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
864
2018-10-01T08:06:00.000Z
2022-03-31T08:06:48.000Z
arbor/include/arbor/math.hpp
kanzl/arbor
86b1eb065ac252bf0026de7cf7cbc6748a528254
[ "BSD-3-Clause" ]
37
2019-03-03T16:18:49.000Z
2022-03-24T10:39:51.000Z
#pragma once #include <cmath> #include <limits> #include <type_traits> #include <utility> #include <arbor/util/compat.hpp> namespace arb { namespace math { template <typename T> T constexpr pi = 3.1415926535897932384626433832795l; template <typename T = float> T constexpr infinity = std::numeric_limits<T>::infinity(); template <typename T> T constexpr square(T a) { return a*a; } template <typename T> T constexpr cube(T a) { return a*a*a; } // Area of circle radius r. template <typename T> T constexpr area_circle(T r) { return pi<T> * square(r); } // Surface area of conic frustrum excluding the discs at each end, // with length L, end radii r1, r2. template <typename T> T constexpr area_frustrum(T L, T r1, T r2) { return pi<T> * (r1+r2) * sqrt(square(L) + square(r1-r2)); } // Volume of conic frustrum of length L, end radii r1, r2. template <typename T> T constexpr volume_frustrum(T L, T r1, T r2) { return pi<T>/T(3) * (square(r1+r2) - r1*r2) * L; } // Linear interpolation by u in interval [a,b]: (1-u)*a + u*b. template <typename T, typename U> T constexpr lerp(T a, T b, U u) { return compat::fma(T(u), b, compat::fma(T(-u), a, a)); } // Return -1, 0 or 1 according to sign of parameter. template <typename T> int signum(T x) { return (x>T(0)) - (x<T(0)); } // Next integral power of 2 for unsigned integers: // // next_pow2(x) returns 0 if x==0, else returns smallest 2^k such // that 2^k>=x. template <typename U, typename = std::enable_if_t<std::is_unsigned<U>::value>> U next_pow2(U x) { --x; for (unsigned s=1; s<std::numeric_limits<U>::digits; s<<=1) { x|=(x>>s); } return ++x; } namespace impl { template <typename T> T abs_if_signed(const T& x, std::true_type) { return std::abs(x); } template <typename T> T abs_if_signed(const T& x, std::false_type) { return x; } } // round_up(v, b) returns r, the smallest magnitude multiple of b // such that v lies between 0 and r inclusive. // // Examples: // round_up( 7, 3) == 9 // round_up( 7, -3) == 9 // round_up(-7, 3) == -9 // round_up(-7, -3) == -9 // round_up( 8, 4) == 8 template < typename T, typename U, typename C = std::common_type_t<T, U>, typename Signed = std::is_signed<C> > C round_up(T v, U b) { C m = v%b; return v-m+signum(m)*impl::abs_if_signed(b, Signed{}); } // Returns 1/x if x != 0; 0 otherwise template <typename T> inline T safeinv(T x) { // If abs(x) is less than epsilon return epsilon, else calculate the result directly. return (T(1)==T(1)+x)? 1/std::numeric_limits<T>::epsilon(): 1/x; } // Value of x/(exp(x)-1) with care taken to handle x=0 case template <typename T> inline T exprelr(T x) { // If abs(x) is less than epsilon return 1, else calculate the result directly. return (T(1)==T(1)+x)? T(1): x/std::expm1(x); } // Quaternion implementation. // Represents w + x.i + y.j + z.k. struct quaternion { double w, x, y, z; constexpr quaternion(): w(0), x(0), y(0), z(0) {} // scalar constexpr quaternion(double w): w(w), x(0), y(0), z(0) {} // vector (pure imaginary) constexpr quaternion(double x, double y, double z): w(0), x(x), y(y), z(z) {} // all 4-components constexpr quaternion(double w, double x, double y, double z): w(w), x(x), y(y), z(z) {} // equality testing constexpr bool operator==(quaternion q) const { return w==q.w && x==q.x && y==q.y && z==q.z; } constexpr bool operator!=(quaternion q) const { return !(*this==q); } constexpr quaternion conj() const { return {w, -x, -y, -z}; } constexpr quaternion operator*(quaternion q) const { return {w*q.w-x*q.x-y*q.y-z*q.z, w*q.x+x*q.w+y*q.z-z*q.y, w*q.y-x*q.z+y*q.w+z*q.x, w*q.z+x*q.y-y*q.x+z*q.w}; } quaternion& operator*=(quaternion q) { return (*this=*this*q); } constexpr quaternion operator*(double d) const { return {w*d, x*d, y*d, z*d}; } quaternion& operator*=(double d) { return (*this=*this*d); } friend constexpr quaternion operator*(double d, quaternion q) { return q*d; } constexpr quaternion operator+(quaternion q) const { return {w+q.w, x+q.x, y+q.y, z+q.z}; } quaternion& operator+=(quaternion q) { w += q.w; x += q.x; y += q.y; z += q.z; return *this; } constexpr quaternion operator-() const { return {-w, -x, -y, -z}; } constexpr quaternion operator-(quaternion q) const { return {w-q.w, x-q.x, y-q.y, z-q.z}; } quaternion& operator-=(quaternion q) { w -= q.w; x -= q.x; y -= q.y; z -= q.z; return *this; } constexpr double sqnorm() const { return w*w+x*x+y*y+z*z; } double norm() const { return std::sqrt(sqnorm()); } // Conjugation a ^ b = b a b*. constexpr quaternion operator^(quaternion b) const { return b*(*this)*b.conj(); } quaternion& operator^=(quaternion b) { return *this = b*(*this)*b.conj(); } // add more as required... }; // Quaternionic representations of axis rotations. // Given a vector v = (x, y, z), and r a quaternion representing // a rotation as below, then then (0, x, y, z) ^ r = (0, x', y', z') // represents the rotated vector. inline quaternion rotation_x(double phi) { return {std::cos(phi/2), std::sin(phi/2), 0, 0}; } inline quaternion rotation_y(double theta) { return {std::cos(theta/2), 0, std::sin(theta/2), 0}; } inline quaternion rotation_z(double psi) { return {std::cos(psi/2), 0, 0, std::sin(psi/2)}; } } // namespace math } // namespace arb
23.831967
91
0.582115
kanzl
cd23334900f5c0d6a2f516206c87edd95ac34c5f
2,793
hpp
C++
include/Nazara/VulkanRenderer/VulkanDevice.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
376
2015-01-09T03:14:48.000Z
2022-03-26T17:59:18.000Z
include/Nazara/VulkanRenderer/VulkanDevice.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
252
2015-01-21T17:34:39.000Z
2022-03-20T16:15:50.000Z
include/Nazara/VulkanRenderer/VulkanDevice.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
104
2015-01-18T11:03:41.000Z
2022-03-11T05:40:47.000Z
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Vulkan Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_VULKANRENDERER_VULKANDEVICE_HPP #define NAZARA_VULKANRENDERER_VULKANDEVICE_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Renderer/RenderDevice.hpp> #include <Nazara/VulkanRenderer/VulkanBuffer.hpp> #include <Nazara/VulkanRenderer/Wrapper/Device.hpp> #include <vector> namespace Nz { class NAZARA_VULKANRENDERER_API VulkanDevice : public RenderDevice, public Vk::Device { public: inline VulkanDevice(Vk::Instance& instance, const RenderDeviceFeatures& enabledFeatures, RenderDeviceInfo renderDeviceInfo); VulkanDevice(const VulkanDevice&) = delete; VulkanDevice(VulkanDevice&&) = delete; ///TODO? ~VulkanDevice(); const RenderDeviceInfo& GetDeviceInfo() const override; const RenderDeviceFeatures& GetEnabledFeatures() const override; std::shared_ptr<AbstractBuffer> InstantiateBuffer(BufferType type) override; std::shared_ptr<CommandPool> InstantiateCommandPool(QueueType queueType) override; std::shared_ptr<Framebuffer> InstantiateFramebuffer(unsigned int width, unsigned int height, const std::shared_ptr<RenderPass>& renderPass, const std::vector<std::shared_ptr<Texture>>& attachments) override; std::shared_ptr<RenderPass> InstantiateRenderPass(std::vector<RenderPass::Attachment> attachments, std::vector<RenderPass::SubpassDescription> subpassDescriptions, std::vector<RenderPass::SubpassDependency> subpassDependencies) override; std::shared_ptr<RenderPipeline> InstantiateRenderPipeline(RenderPipelineInfo pipelineInfo) override; std::shared_ptr<RenderPipelineLayout> InstantiateRenderPipelineLayout(RenderPipelineLayoutInfo pipelineLayoutInfo) override; std::shared_ptr<ShaderModule> InstantiateShaderModule(ShaderStageTypeFlags stages, ShaderAst::Statement& shaderAst, const ShaderWriter::States& states) override; std::shared_ptr<ShaderModule> InstantiateShaderModule(ShaderStageTypeFlags stages, ShaderLanguage lang, const void* source, std::size_t sourceSize, const ShaderWriter::States& states) override; std::shared_ptr<Texture> InstantiateTexture(const TextureInfo& params) override; std::shared_ptr<TextureSampler> InstantiateTextureSampler(const TextureSamplerInfo& params) override; bool IsTextureFormatSupported(PixelFormat format, TextureUsage usage) const override; VulkanDevice& operator=(const VulkanDevice&) = delete; VulkanDevice& operator=(VulkanDevice&&) = delete; ///TODO? private: RenderDeviceFeatures m_enabledFeatures; RenderDeviceInfo m_renderDeviceInfo; }; } #include <Nazara/VulkanRenderer/VulkanDevice.inl> #endif // NAZARA_VULKANRENDERER_VULKANDEVICE_HPP
51.722222
240
0.814536
gogo2464
cd2525f5b0bf5d04677e0a7884490f9527341f8a
20,108
cpp
C++
automated-tests/src/dali/utc-Dali-Matrix.cpp
pwisbey/dali-core
53117f5d4178001b0d688c5bce14d7bf8e861631
[ "Apache-2.0" ]
1
2016-08-05T09:58:38.000Z
2016-08-05T09:58:38.000Z
automated-tests/src/dali/utc-Dali-Matrix.cpp
tizenorg/platform.core.uifw.dali-core
dd89513b4bb1fdde74a83996c726e10adaf58349
[ "Apache-2.0" ]
null
null
null
automated-tests/src/dali/utc-Dali-Matrix.cpp
tizenorg/platform.core.uifw.dali-core
dd89513b4bb1fdde74a83996c726e10adaf58349
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * 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 <iostream> #include <sstream> #include <stdlib.h> #include <dali/public-api/dali-core.h> #include <dali-test-suite-utils.h> using namespace Dali; void utc_dali_matrix_startup(void) { test_return_value = TET_UNDEF; } void utc_dali_matrix_cleanup(void) { test_return_value = TET_PASS; } int UtcDaliMatrixConstructor01P(void) { Matrix m2(false); bool initialised = true; { float* els = m2.AsFloat(); for(size_t idx=0; idx<16; ++idx, ++els) { if(*els != 0.0f) initialised = false; } } DALI_TEST_EQUALS(initialised, false, TEST_LOCATION); END_TEST; } int UtcDaliMatrixConstructor02P(void) { float r[] = { 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f}; Matrix m(r); float* els = m.AsFloat(); float* init = r; bool initialised = true; for(size_t idx=0; idx<16; ++idx, ++els, ++init) { if(*els != *init) initialised = false; } DALI_TEST_EQUALS(initialised, true, TEST_LOCATION); END_TEST; } int UtcDaliMatrixConstructor03P(void) { float r[] = { 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f}; Matrix ma(r); Matrix mb(ma); float* els = ma.AsFloat(); float* init = mb.AsFloat(); bool initialised = true; for(size_t idx=0; idx<16; ++idx, ++els, ++init) { if(*els != *init) initialised = false; } DALI_TEST_EQUALS(initialised, true, TEST_LOCATION); END_TEST; } int UtcDaliMatrixConstructor04P(void) { Quaternion q(Quaternion::IDENTITY); Matrix m(q); DALI_TEST_EQUALS(Matrix(Matrix::IDENTITY), m, 0.001, TEST_LOCATION); END_TEST; } int UtcDaliMatrixAssignP(void) { Matrix a(Matrix::IDENTITY); Matrix b = a; DALI_TEST_EQUALS(a, b, 0.001, TEST_LOCATION); END_TEST; } int UtcDaliMatrixAssign02P(void) { Matrix a(Matrix::IDENTITY); a = a; // self assign does the do nothing branch DALI_TEST_EQUALS(Matrix(Matrix::IDENTITY), a, 0.001, TEST_LOCATION); END_TEST; } int UtcDaliMatrixSetIdentityP(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); m.SetIdentity(); DALI_TEST_EQUALS(m, Matrix::IDENTITY, 0.001f, TEST_LOCATION); END_TEST; } int UtcDaliMatrixSetIdentityAndScaleP(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); m.SetIdentityAndScale(Vector3(4.0f, 4.0f, 4.0f)); float els2[] = { 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; Matrix r(els2); DALI_TEST_EQUALS(m, r, 0.001f, TEST_LOCATION); END_TEST; } int UtcDaliMatrixInvertTransformP(void) { for (int i=0;i<1000;++i) { float f = i; Vector3 axis(cosf(f*0.001f), cosf(f*0.02f), cosf(f*0.03f)); axis.Normalize(); Vector3 center(f, cosf(f) * 100.0f, cosf(f*0.5f) * 50.0f); Matrix m0; m0.SetIdentity(); m0.SetTransformComponents( Vector3::ONE, Quaternion(Radian(1.0f), axis), center ); Matrix m1; m0.InvertTransform(m1); Matrix m2( false ); Matrix::Multiply( m2, m0, m1 ); DALI_TEST_EQUALS(m2, Matrix::IDENTITY, 0.001f, TEST_LOCATION); } END_TEST; } int UtcDaliMatrixInvertTransformN(void) { std::string exceptionString( "EqualsZero( mMatrix[3] ) && EqualsZero( mMatrix[7] ) && EqualsZero( mMatrix[11] ) && Equals( mMatrix[15], 1.0f" ); try { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); Matrix it; m.InvertTransform(it); tet_result(TET_FAIL); } catch (Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT( e ); DALI_TEST_ASSERT( e, exceptionString, TEST_LOCATION ); } try { float els[] = { 0.0f, 1.0f, 2.0f, 0.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); Matrix it; m.InvertTransform(it); tet_result(TET_FAIL); } catch (Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT( e ); DALI_TEST_ASSERT( e, exceptionString, TEST_LOCATION ); } try { float els[] = { 0.0f, 1.0f, 2.0f, 0.0f, 4.0f, 5.0f, 6.0f, 0.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); Matrix it; m.InvertTransform(it); tet_result(TET_FAIL); } catch (Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT( e ); DALI_TEST_ASSERT( e, exceptionString, TEST_LOCATION ); } try { float els[] = { 0.0f, 1.0f, 2.0f, 0.0f, 4.0f, 5.0f, 6.0f, 0.0f, 8.0f, 9.0f, 10.0f, 0.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); Matrix it; m.InvertTransform(it); tet_result(TET_FAIL); } catch (Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT( e ); DALI_TEST_ASSERT( e, exceptionString, TEST_LOCATION ); } END_TEST; } int UtcDaliMatrixInvert01P(void) { // We're going to invert a whole load of different matrices to make sure we don't // fail on particular orientations. for (int i=0;i<1000;++i) { float f = i; Vector3 axis(cosf(f*0.001f), cosf(f*0.02f), cosf(f*0.03f)); axis.Normalize(); Vector3 center(f, cosf(f) * 100.0f, cosf(f*0.5f) * 50.0f); Matrix m0; m0.SetIdentity(); m0.SetTransformComponents( Vector3::ONE, Quaternion(Radian(1.0f), axis), center ); Matrix m1(m0); m1.Invert(); Matrix m2( false ); Matrix::Multiply( m2, m0, m1 ); DALI_TEST_EQUALS(m2, Matrix::IDENTITY, 0.001f, TEST_LOCATION); m1.Invert(); // doube invert - should be back to m0 DALI_TEST_EQUALS(m0, m1, 0.001f, TEST_LOCATION); } END_TEST; } int UtcDaliMatrixInvert02P(void) { Matrix m1 = Matrix::IDENTITY; m1.SetXAxis(Vector3(0.0f, 0.0f, 0.0f)); DALI_TEST_EQUALS(m1.Invert(), false, TEST_LOCATION); END_TEST; } int UtcDaliMatrixTransposeP(void) { float floats[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(floats); m.Transpose(); bool success = true; for (int x=0;x<4;++x) { for (int y=0;y<4;++y) { success &= (m.AsFloat()[x+y*4] == floats[x*4+y]); } } DALI_TEST_CHECK(success); END_TEST; } int UtcDaliMatrixGetXAxisP(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); DALI_TEST_CHECK(m.GetXAxis() == Vector3(0.0f, 1.0f, 2.0f)); END_TEST; } int UtcDaliMatrixGetYAxisP(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); DALI_TEST_CHECK(m.GetYAxis() == Vector3(4.0f, 5.0f, 6.0f)); END_TEST; } int UtcDaliMatrixGetZAxisP(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); DALI_TEST_CHECK(m.GetZAxis() == Vector3(8.0f, 9.0f, 10.0f)); END_TEST; } int UtcDaliMatrixSetXAxisP(void) { Matrix m; Vector3 v(2.0f, 3.0f, 4.0f); m.SetXAxis(v); DALI_TEST_CHECK(m.GetXAxis() == v); END_TEST; } int UtcDaliMatrixSetYAxisP(void) { Matrix m; Vector3 v(2.0f, 3.0f, 4.0f); m.SetYAxis(v); DALI_TEST_CHECK(m.GetYAxis() == v); END_TEST; } int UtcDaliMatrixSetZAxisP(void) { Matrix m; Vector3 v(2.0f, 3.0f, 4.0f); m.SetZAxis(v); DALI_TEST_CHECK(m.GetZAxis() == v); END_TEST; } int UtcDaliMatrixGetTranslationP(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); DALI_TEST_EQUALS(m.GetTranslation(), Vector4(12.0f, 13.0f, 14.0f, 15.0f), TEST_LOCATION); END_TEST; } int UtcDaliMatrixGetTranslation3P(void) { float els[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f, 13.0f, 14.0f, 15.0f }; Matrix m(els); DALI_TEST_EQUALS(m.GetTranslation3(), Vector3(12.0f, 13.0f, 14.0f), TEST_LOCATION); END_TEST; } int UtcDaliMatrixSetTranslationP(void) { Matrix m; Vector4 v(2.0f, 3.0f, 4.0f, 5.0f); m.SetTranslation(v); DALI_TEST_CHECK(m.GetTranslation() == v); END_TEST; } int UtcDaliMatrixSetTranslation3P(void) { Matrix m; Vector3 v(2.0f, 3.0f, 4.0f); m.SetTranslation(v); DALI_TEST_CHECK(m.GetTranslation3() == v); END_TEST; } int UtcDaliMatrixOrthoNormalize0P(void) { // OrthoNormalise fixes floating point errors from matrix rotations Matrix m; m.SetIdentity(); for (int i=0;i<1000;++i) { float f = i; Vector3 axis(cosf(f*0.001f), cosf(f*0.02f), cosf(f*0.03f)); axis.Normalize(); m.SetTransformComponents( Vector3::ONE, Quaternion(Radian(1.0f), axis), Vector3::ZERO ); m.OrthoNormalize(); } bool success = true; success &= fabsf(m.GetXAxis().Dot(m.GetYAxis())) < 0.001f; success &= fabsf(m.GetYAxis().Dot(m.GetXAxis())) < 0.001f; success &= fabsf(m.GetZAxis().Dot(m.GetYAxis())) < 0.001f; success &= fabsf(m.GetXAxis().Length() - 1.0f) < 0.001f; success &= fabsf(m.GetYAxis().Length() - 1.0f) < 0.001f; success &= fabsf(m.GetZAxis().Length() - 1.0f) < 0.001f; DALI_TEST_CHECK(success); END_TEST; } int UtcDaliMatrixOrthoNormalize1P(void) { // OrthoNormalize is not flipping the axes and is maintaining the translation for (int i=0;i<1000;++i) { float f = i; Vector3 axis(cosf(f*0.001f), cosf(f*0.02f), cosf(f*0.03f)); axis.Normalize(); Vector3 center(10.0f, 15.0f, 5.0f); Matrix m0; m0.SetIdentity(); m0.SetTransformComponents( Vector3::ONE, Quaternion(Radian(1.0f), axis), center ); Matrix m1(m0); m1.OrthoNormalize(); DALI_TEST_EQUALS(m0.GetXAxis(), m1.GetXAxis(), 0.001f, TEST_LOCATION); DALI_TEST_EQUALS(m0.GetYAxis(), m1.GetYAxis(), 0.001f, TEST_LOCATION); DALI_TEST_EQUALS(m0.GetZAxis(), m1.GetZAxis(), 0.001f, TEST_LOCATION); DALI_TEST_EQUALS(m0.GetTranslation(), m1.GetTranslation(), 0.001f, TEST_LOCATION); } END_TEST; } int UtcDaliMatrixConstAsFloatP(void) { float r[] = { 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f}; const Matrix m(r); const float* els = m.AsFloat(); const float* init = r; bool initialised = true; for(size_t idx=0; idx<16; ++idx, ++els, ++init) { if(*els != *init) initialised = false; } DALI_TEST_EQUALS(initialised, true, TEST_LOCATION); END_TEST; } int UtcDaliMatrixAsFloatP(void) { float r[] = { 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f}; Matrix m(r); float* els = m.AsFloat(); float* init = r; bool initialised = true; for(size_t idx=0; idx<16; ++idx, ++els, ++init) { if(*els != *init) initialised = false; } DALI_TEST_EQUALS(initialised, true, TEST_LOCATION); END_TEST; } int UtcDaliMatrixMultiplyP(void) { Matrix m1 = Matrix::IDENTITY; float els[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.707f, 0.707f, 0.0f, 0.0f, -0.707f, 0.707f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; Matrix result(els); Quaternion q(Radian(Degree(45.0f)), Vector3::XAXIS); Matrix m2(false); Matrix::Multiply(m2, m1, q); DALI_TEST_EQUALS(m2, result, 0.01f, TEST_LOCATION); END_TEST; } int UtcDaliMatrixOperatorMultiply01P(void) { Vector4 v1(2.0f, 5.0f, 4.0f, 0.0f); float els[] = {2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; Matrix m1(els); Vector4 v2 = m1 * v1; Vector4 r1(4.0f, 15.0f, 16.0f, 0.0f); DALI_TEST_EQUALS(v2, r1, 0.01f, TEST_LOCATION); END_TEST; } int UtcDaliMatrixOperatorMultiply02P(void) { TestApplication application; Vector3 position ( 30.f, 40.f, 50.f); Matrix m1(false); m1.SetIdentity(); m1.SetTranslation(-position); Vector4 positionV4(position); positionV4.w=1.0f; Vector4 output = m1 * positionV4; output.w = 0.0f; DALI_TEST_EQUALS(output, Vector4::ZERO, 0.01f, TEST_LOCATION); END_TEST; } int UtcDaliMatrixOperatorEqualsP(void) { Matrix m1 = Matrix::IDENTITY; float els[] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; Matrix r2(els); DALI_TEST_EQUALS(m1 == r2, true, TEST_LOCATION); float *f = m1.AsFloat(); for(size_t i=0; i<16; i++) { f[15-i] = 1.2f; DALI_TEST_EQUALS(m1 == r2, false, TEST_LOCATION); } END_TEST; } int UtcDaliMatrixOperatorNotEqualsP(void) { Matrix m1 = Matrix::IDENTITY; float els[] = {2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; Matrix r1(els); DALI_TEST_CHECK(m1 != r1); DALI_TEST_CHECK(!(m1 != m1)); END_TEST; } int UtcDaliMatrixSetTransformComponents01P(void) { // Create an arbitrary vector for( float x=-1.0f; x<=1.0f; x+=0.1f ) { for( float y=-1.0f; y<1.0f; y+=0.1f ) { for( float z=-1.0f; z<1.0f; z+=0.1f ) { Vector3 vForward(x, y, z); vForward.Normalize(); for( float angle = 5.0f; angle <= 360.0f; angle += 15.0f) { Quaternion rotation1(Radian(Degree(angle)), vForward); Matrix m1(rotation1); Matrix result1(false); Vector3 vForward3(vForward.x, vForward.y, vForward.z); result1.SetTransformComponents( Vector3::ONE, Quaternion(Radian(Degree(angle)), vForward3), Vector3::ZERO ); DALI_TEST_EQUALS(m1, result1, 0.001, TEST_LOCATION); Matrix m2(false); m2.SetTransformComponents(vForward, Quaternion::IDENTITY, Vector3::ZERO); Matrix result2a(Matrix::IDENTITY); result2a.SetXAxis(result2a.GetXAxis() * vForward[0]); result2a.SetYAxis(result2a.GetYAxis() * vForward[1]); result2a.SetZAxis(result2a.GetZAxis() * vForward[2]); DALI_TEST_EQUALS(m2, result2a, 0.001, TEST_LOCATION); Matrix m3(false); m3.SetTransformComponents(vForward, rotation1, Vector3::ZERO); Matrix result3(Matrix::IDENTITY); result3.SetXAxis(result3.GetXAxis() * vForward[0]); result3.SetYAxis(result3.GetYAxis() * vForward[1]); result3.SetZAxis(result3.GetZAxis() * vForward[2]); Matrix::Multiply(result3, result3, m1); DALI_TEST_EQUALS(m3, result3, 0.001, TEST_LOCATION); } } } } END_TEST; } int UtcDaliMatrixSetInverseTransformComponent01P(void) { // Create an arbitrary vector for( float x=-1.0f; x<=1.0f; x+=0.1f ) { for( float y=-1.0f; y<1.0f; y+=0.1f ) { for( float z=-1.0f; z<1.0f; z+=0.1f ) { Vector3 vForward(x, y, z); vForward.Normalize(); { Quaternion rotation1(Quaternion::IDENTITY); // test no rotation branch Vector3 scale1(2.0f, 3.0f, 4.0f); Vector3 position1(1.0f, 2.0f, 3.0f); Matrix m1(false); m1.SetTransformComponents(scale1, rotation1, position1); Matrix m2(false); m2.SetInverseTransformComponents(scale1, rotation1, position1); Matrix result; Matrix::Multiply(result, m1, m2); DALI_TEST_EQUALS(result, Matrix::IDENTITY, 0.001, TEST_LOCATION); } } } } END_TEST; } int UtcDaliMatrixSetInverseTransformComponent02P(void) { // Create an arbitrary vector for( float x=-1.0f; x<=1.0f; x+=0.1f ) { for( float y=-1.0f; y<1.0f; y+=0.1f ) { for( float z=-1.0f; z<1.0f; z+=0.1f ) { Vector3 vForward(x, y, z); vForward.Normalize(); for( float angle = 5.0f; angle <= 360.0f; angle += 15.0f) { Quaternion rotation1(Radian(Degree(angle)), vForward); Matrix rotationMatrix(rotation1); // TEST RELIES ON THIS METHOD WORKING!!! Vector3 position1(5.0f, -6.0f, 7.0f); Matrix m1(false); m1.SetTransformComponents( Vector3::ONE, rotation1, position1 ); Matrix m2(false); m2.SetInverseTransformComponents( rotationMatrix.GetXAxis(), rotationMatrix.GetYAxis(), rotationMatrix.GetZAxis(), position1 ); Matrix result; Matrix::Multiply(result, m1, m2); DALI_TEST_EQUALS(result, Matrix::IDENTITY, 0.001, TEST_LOCATION); } } } } END_TEST; } int UtcDaliMatrixGetTransformComponents01P(void) { Matrix m2(Matrix::IDENTITY.AsFloat()); Vector3 pos2; Vector3 scale2; Quaternion q2; m2.GetTransformComponents(pos2, q2, scale2); DALI_TEST_EQUALS(Vector3(0.0f, 0.0f, 0.0f), pos2, 0.001, TEST_LOCATION); DALI_TEST_EQUALS(Vector3(1.0f, 1.0f, 1.0f), scale2, 0.001, TEST_LOCATION); DALI_TEST_EQUALS(Quaternion(), q2, 0.001, TEST_LOCATION); END_TEST; } int UtcDaliMatrixGetTransformComponents02P(void) { // Create an arbitrary vector for( float x=-1.0f; x<=1.0f; x+=0.1f ) { for( float y=-1.0f; y<1.0f; y+=0.1f ) { for( float z=-1.0f; z<1.0f; z+=0.1f ) { Vector3 vForward(x, y, z); vForward.Normalize(); for( float angle = 5.0f; angle <= 360.0f; angle += 15.0f) { Quaternion rotation1(Radian(Degree(angle)), vForward); Vector3 scale1(2.0f, 3.0f, 4.0f); Vector3 position1(1.0f, 2.0f, 3.0f); Matrix m1(false); m1.SetTransformComponents(scale1, rotation1, position1); Vector3 position2; Quaternion rotation2; Vector3 scale2; m1.GetTransformComponents(position2, rotation2, scale2); DALI_TEST_EQUALS(position1, position2, 0.001, TEST_LOCATION); DALI_TEST_EQUALS(scale1, scale2, 0.001, TEST_LOCATION); DALI_TEST_EQUALS(rotation1, rotation2, 0.001, TEST_LOCATION); } } } } END_TEST; } int UtcDaliMatrixGetTransformComponents03P(void) { Matrix m2; // zero branch Vector3 pos2; Vector3 scale2; Quaternion q2; m2.GetTransformComponents(pos2, q2, scale2); DALI_TEST_EQUALS(Vector3(0.0f, 0.0f, 0.0f), pos2, 0.001, TEST_LOCATION); DALI_TEST_EQUALS(Vector3(0.0f, 0.0f, 0.0f), scale2, 0.001, TEST_LOCATION); // DALI_TEST_EQUALS(Quaternion(), q2, 0.001, TEST_LOCATION); END_TEST; } int UtcDaliMatrixOStreamOperator(void) { std::ostringstream oss; Matrix matrix; matrix.SetIdentity(); oss << matrix; std::string expectedOutput = "[ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ]"; DALI_TEST_EQUALS( oss.str(), expectedOutput, TEST_LOCATION); END_TEST; }
25.041096
146
0.592202
pwisbey
cd2915f9deadd1c1cb19fdea87a0b1e38ed6f705
8,790
cpp
C++
src/test/TestRcClipGeneric.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/test/TestRcClipGeneric.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/test/TestRcClipGeneric.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
/***************************************************************************** TestRcClipGeneric.cpp Author: Laurent de Soras, 2020 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif // 1 or 4 #define TestRcClipGeneric_OVRSPL (4) /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Approx.h" #include "fstb/fnc.h" #include "fstb/SingleObj.h" #include "hiir/PolyphaseIir2Designer.h" #include "mfx/dsp/iir/Downsampler4xSimd.h" #include "mfx/dsp/iir/Upsampler4xSimd.h" #include "mfx/dsp/osc/SweepingSin.h" #include "mfx/dsp/va/RcClipGeneric.h" #include "mfx/dsp/va/IvDiodeAntipar.h" #include "mfx/dsp/va/IvPoly.h" #include "mfx/FileOpWav.h" #include "test/TestRcClipGeneric.h" #include "test/TimerAccurate.h" #include <cassert> #include <cmath> #include <cstdio> /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ int TestRcClipGeneric::perform_test () { int ret_val = 0; if (ret_val == 0) { ret_val = perform_test <mfx::dsp::va::IvDiodeAntipar> ( "IvDiodeAntipar", "diodeap" ); } if (ret_val == 0) { ret_val = perform_test <mfx::dsp::va::IvPoly <17, 5> > ( "IvPoly <17, 5>", "poly17o5o-" ); } #if 1 if (ret_val == 0) { ret_val = perform_test <mfx::dsp::va::IvPoly <9, 2> > ( "IvPoly <9, 2>", "poly9o2o-" ); } #endif return ret_val; } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ template <class T> int TestRcClipGeneric::perform_test (const char classname_0 [], const char filename_0 []) { int ret_val = 0; printf ( "Testing dsp::va::RcClipGeneric + mfx::dsp::va::%s...\n", classname_0 ); const double sample_freq = 44100; const int ssin_len = fstb::round_int (sample_freq * 10); std::vector <float> src (ssin_len); // Sweeping sine mfx::dsp::osc::SweepingSin ssin (sample_freq, 20.0, 20000.0); ssin.generate (src.data (), ssin_len); // Sawtooth const int saw_len = fstb::round_int (sample_freq * 1); for (int o = -3; o < 7; ++o) { const double freq = 220 * pow (2.0, o + 3 / 12.0); gen_saw (src, sample_freq, freq, saw_len); } const int len = int (src.size ()); std::vector <float> dst (len); const int nbr_coef_42 = 4; const int nbr_coef_21 = 8; struct UpDown { mfx::dsp::iir::Upsampler4xSimd <nbr_coef_42, nbr_coef_21> _up; mfx::dsp::iir::Downsampler4xSimd <nbr_coef_42, nbr_coef_21> _dw; }; fstb::SingleObj <UpDown> updw; double coef_42 [nbr_coef_42]; double coef_21 [nbr_coef_21]; // Rejection : 103.4 dB // Bandwidth : 20.0 kHz @ 44.1 kHz // Total group delay: 5.0 spl @ 1 kHz hiir::PolyphaseIir2Designer::compute_coefs_spec_order_tbw ( &coef_42 [0], nbr_coef_42, 0.216404 ); hiir::PolyphaseIir2Designer::compute_coefs_spec_order_tbw ( &coef_21 [0], nbr_coef_21, 0.0455352 ); updw->_up.set_coefs (coef_42, coef_21); updw->_dw.set_coefs (coef_42, coef_21); mfx::dsp::va::RcClipGeneric <T> dclip; dclip.set_sample_freq (sample_freq * TestRcClipGeneric_OVRSPL); #if defined (mfx_dsp_va_RcClipGeneric_STAT) dclip.reset_stat (); #endif // mfx_dsp_va_RcClipGeneric_STAT float gain = 1; for (int pos = 0; pos < len; ++pos) { float x = src [pos] * gain; #if (TestRcClipGeneric_OVRSPL == 1) // W/o oversampling x = dclip.process_sample (x); #else // With oversampling float tmp [TestRcClipGeneric_OVRSPL]; updw->_up.process_sample (tmp, x); for (int k = 0; k < TestRcClipGeneric_OVRSPL; ++k) { tmp [k] = dclip.process_sample (tmp [k]); } x = updw->_dw.process_sample (tmp); #endif dst [pos] = x; } #if defined (mfx_dsp_va_RcClipGeneric_STAT) print_stats (dclip, "Standard"); dclip.reset_stat (); #endif // mfx_dsp_va_RcClipGeneric_STAT mfx::FileOpWav::save ( (std::string ("results/rclipgen") + filename_0 + "1.wav").c_str (), dst, sample_freq, 0.5f ); // High gain (+40 dB) dclip.clear_buffers (); dclip.set_cutoff_freq (float (sample_freq * 0.49)); gain = 100; for (int pos = 0; pos < len; ++pos) { float x = src [pos] * gain; #if (TestRcClipGeneric_OVRSPL == 1) // W/o oversampling x = dclip.process_sample (x); #else // With oversampling float tmp [TestRcClipGeneric_OVRSPL]; updw->_up.process_sample (tmp, x); for (int k = 0; k < TestRcClipGeneric_OVRSPL; ++k) { tmp [k] = dclip.process_sample (tmp [k]); } x = updw->_dw.process_sample (tmp); #endif dst [pos] = x; } #if defined (mfx_dsp_va_RcClipGeneric_STAT) print_stats (dclip, "High gain"); dclip.reset_stat (); #endif // mfx_dsp_va_RcClipGeneric_STAT mfx::FileOpWav::save ( (std::string ("results/rclipgen") + filename_0 + "3.wav").c_str (), dst, sample_freq, 0.5f ); // Now with variable gain with fixed GBP (gain-bandwidth product) dclip.clear_buffers (); const double per_spl = 2 * sample_freq; for (int pos = 0; pos < len; ++pos) { double a = fmod (pos / per_spl, 1.0); a = 1 - fabs (a * 2 - 1); gain = fstb::Approx::exp2 (float (a * a) * 8 - 1); dclip.set_capa (gain * 10e-9f); float x = src [pos] * gain; #if (TestRcClipGeneric_OVRSPL == 1) // W/o oversampling x = dclip.process_sample (x); #else // With oversampling float tmp [TestRcClipGeneric_OVRSPL]; updw->_up.process_sample (tmp, x); for (int k = 0; k < TestRcClipGeneric_OVRSPL; ++k) { tmp [k] = dclip.process_sample (tmp [k]); } x = updw->_dw.process_sample (tmp); #endif dst [pos] = x; } #if defined (mfx_dsp_va_RcClipGeneric_STAT) print_stats (dclip, "Variable gain, fixed GBP"); dclip.reset_stat (); #endif // mfx_dsp_va_RcClipGeneric_STAT mfx::FileOpWav::save ( (std::string ("results/rclipgen") + filename_0 + "2.wav").c_str (), dst, sample_freq, 0.5f ); // Speed test TimerAccurate chrono; dclip.set_capa (10e-9f); const int nbr_passes = 10; for (int g = 1; g <= 100; g *= 100) { float acc_dummy = 0; chrono.reset (); chrono.start (); for (int pass_cnt = 0; pass_cnt < nbr_passes; ++pass_cnt) { for (int pos = 0; pos < len; ++pos) { acc_dummy += dclip.process_sample (src [pos] * g); } } chrono.stop (); double spl_per_s = chrono.get_best_rate (len * nbr_passes); spl_per_s += fstb::limit (acc_dummy, -1e-30f, 1e-30f); // Anti-optimizer trick const double mega_sps = spl_per_s / 1000000.0; printf ("Speed (gain = %4d):%9.3f Mspl/s\n", g, mega_sps); } return ret_val; } void TestRcClipGeneric::gen_saw (std::vector <float> &data, double sample_freq, double freq, int len) { const int per = fstb::round_int (sample_freq / freq); for (int pos = 0; pos < len; ++pos) { const float val = (pos % per) * (2.f / per) - 1.f; data.push_back (val); } } #if defined (mfx_dsp_va_RcClipGeneric_STAT) template <class T> void TestRcClipGeneric::print_stats (T &dclip, const char msg_0 []) { printf ("%s\n", msg_0); typename T::Stat stat; dclip.get_stats (stat); printf ("=== Iterations ===\n"); print_histo ( stat._hist_it.data (), int (stat._hist_it.size ()), stat._nbr_spl_proc ); printf ("\n"); } void TestRcClipGeneric::print_histo (int hist_arr [], int nbr_bars, int nbr_spl) { int bar_max = 0; int total = 0; for (int k = 0; k < nbr_bars; ++k) { const int val = hist_arr [k]; bar_max = std::max (bar_max, val); total += val * k; } const int bar_size = 64; char bar_0 [bar_size+1]; for (int k = 0; k < bar_size; ++k) { bar_0 [k] = '#'; } bar_0 [bar_size] = '\0'; const double nbr_spl_inv = 1.0 / double (nbr_spl); const double total_inv = 1.0 / (double (total) + 1e-12); const double bar_scale = double (bar_size) / double (bar_max); printf ("Average: %.2f\n", double (total) * nbr_spl_inv); for (int k = 0; k < nbr_bars; ++k) { const int val = hist_arr [k]; if (val > 0) { const double prop = double (val) * nbr_spl_inv; printf ("%3d: %10d, %5.1f %% ", k, val, prop * 100); const int bar_len = fstb::round_int (val * bar_scale); printf ("%s\n", bar_0 + bar_size - bar_len); } } } #endif // mfx_dsp_va_RcClipGeneric_STAT /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
25.258621
101
0.604096
mikelange49
cd30eab09ec4f82b8e2a95cd14abf583c430cb86
8,062
cpp
C++
Sources/Display/Platform/Win32/cursor_provider_win32.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
248
2015-01-08T05:21:40.000Z
2022-03-20T02:59:16.000Z
Sources/Display/Platform/Win32/cursor_provider_win32.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
39
2015-01-14T17:37:07.000Z
2022-03-17T12:59:26.000Z
Sources/Display/Platform/Win32/cursor_provider_win32.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
82
2015-01-11T13:23:49.000Z
2022-02-19T03:17:24.000Z
/* ** ClanLib SDK ** Copyright (c) 1997-2020 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "Display/precomp.h" #include "cursor_provider_win32.h" #include "API/Core/System/databuffer.h" #include "API/Core/IOData/memory_device.h" #include "API/Display/Image/pixel_buffer.h" #include "API/Display/Window/cursor_description.h" #ifdef __MINGW32__ #include "API/Display/Window/display_window.h" #endif #include "win32_window.h" namespace clan { CursorProvider_Win32::CursorProvider_Win32(const CursorDescription &cursor_description) : handle(0) { handle = create_cursor(cursor_description); } CursorProvider_Win32::~CursorProvider_Win32() { if (handle) DestroyCursor(handle); } HCURSOR CursorProvider_Win32::create_cursor(const CursorDescription &cursor_description) { if (cursor_description.get_frames().empty()) throw Exception("Cannot create cursor with no image frames"); DataBuffer ani_file = create_ani_file(cursor_description); int desired_width = cursor_description.get_frames().front().rect.get_width(); int desired_height = cursor_description.get_frames().front().rect.get_height(); HICON icon = CreateIconFromResourceEx((PBYTE)ani_file.get_data(), ani_file.get_size(), FALSE, 0x00030000, desired_width, desired_height, LR_DEFAULTCOLOR); return (HCURSOR)icon; } DataBuffer CursorProvider_Win32::create_ico_file(const PixelBuffer &image) { return create_ico_helper(image, Rectf(image.get_size()), 1, Point(0, 0)); } DataBuffer CursorProvider_Win32::create_cur_file(const PixelBuffer &image, const Rect &rect, const Point &hotspot) { return create_ico_helper(image, rect, 2, hotspot); } DataBuffer CursorProvider_Win32::create_ico_helper(const PixelBuffer &image, const Rect &rect, WORD type, const Point &hotspot) { std::vector<PixelBuffer> images; std::vector<Rect> rects; std::vector<Point> hotspots; images.push_back(image); rects.push_back(rect); hotspots.push_back(hotspot); return create_ico_helper(images, rects, type, hotspots); } DataBuffer CursorProvider_Win32::create_ico_helper(const std::vector<PixelBuffer> &images, const std::vector<Rect> &rects, WORD type, const std::vector<Point> &hotspots) { DataBuffer buf; buf.set_capacity(32 * 1024); MemoryDevice device(buf); ICONHEADER header; memset(&header, 0, sizeof(ICONHEADER)); header.idType = type; header.idCount = images.size(); device.write(&header, sizeof(ICONHEADER)); std::vector<PixelBuffer> bmp_images; for (size_t i = 0; i < images.size(); i++) bmp_images.push_back(Win32Window::create_bitmap_data(images[i], rects[i])); for (size_t i = 0; i < bmp_images.size(); i++) { IconDirectoryEntry entry; memset(&entry, 0, sizeof(IconDirectoryEntry)); entry.bWidth = bmp_images[i].get_width(); entry.bHeight = bmp_images[i].get_height(); entry.bColorCount = 0; entry.wPlanes = 1; entry.wBitCount = 32; entry.dwBytesInRes = sizeof(BITMAPINFOHEADER) + bmp_images[i].get_pitch() * bmp_images[i].get_height(); entry.dwImageOffset = size_header + size_direntry*bmp_images.size(); if (type == 2) { entry.XHotspot = hotspots[i].x; entry.YHotspot = hotspots[i].y; } device.write(&entry, sizeof(IconDirectoryEntry)); } for (size_t i = 0; i < bmp_images.size(); i++) { BITMAPINFOHEADER bmp_header; memset(&bmp_header, 0, sizeof(BITMAPINFOHEADER)); bmp_header.biSize = sizeof(BITMAPINFOHEADER); bmp_header.biWidth = bmp_images[i].get_width(); bmp_header.biHeight = bmp_images[i].get_height() * 2; // why on earth do I have to multiply this by two?? bmp_header.biPlanes = 1; bmp_header.biBitCount = 32; bmp_header.biCompression = BI_RGB; bmp_header.biSizeImage = bmp_images[i].get_pitch() * bmp_images[i].get_height(); device.write(&bmp_header, sizeof(BITMAPINFOHEADER)); device.write(bmp_images[i].get_data(), bmp_images[i].get_pitch() * bmp_images[i].get_height()); } return device.get_data(); } DataBuffer CursorProvider_Win32::create_ani_file(const CursorDescription &cursor_description) { /* "RIFF" {Length of File} "ACON" "LIST" {Length of List} "INFO" "INAM" {Length of Title} {Data} "IART" {Length of Author} {Data} "anih" {Length of ANI header (36 bytes)} {Data} ; (see ANI Header TypeDef ) "rate" {Length of rate block} {Data} ; ea. rate is a long (length is 1 to cSteps) "seq " {Length of sequence block} {Data} ; ea. seq is a long (length is 1 to cSteps) "LIST" {Length of List} "fram" "icon" {Length of Icon} {Data} ; 1st in list ... "icon" {Length of Icon} {Data} ; Last in list (1 to cFrames) */ ANIFrames ani_frames; std::vector<DWORD> rates; std::vector<DWORD> steps; const std::vector<CursorDescriptionFrame> &frames = cursor_description.get_frames(); for (std::vector<CursorDescriptionFrame>::size_type i = 0; i < frames.size(); i++) { DataBuffer ico_file = create_cur_file(frames[i].pixelbuffer, frames[i].rect, cursor_description.get_hotspot()); ani_frames.icons.push_back(ico_file); DWORD rate = static_cast<DWORD>(frames[i].delay * 60); if (rate == 0) rate = 1; rates.push_back(rate); steps.push_back(i); } ANIHeader ani_header; memset(&ani_header, 0, sizeof(ANIHeader)); ani_header.cbSizeOf = sizeof(ANIHeader); ani_header.flags = AF_ICON; ani_header.JifRate = 30; ani_header.cBitCount = 32; ani_header.cPlanes = 1; ani_header.cFrames = ani_frames.icons.size(); ani_header.cSteps = steps.size(); ani_header.cx = cursor_description.get_hotspot().x; ani_header.cy = cursor_description.get_hotspot().y; ANIInfo ani_info; ani_info.author = "clanlib"; ani_info.title = "clanlib"; int size_file_header = 8 + 4; int size_list1 = 8 + ani_info.length(); int size_anih = 8 + sizeof(ANIHeader); int size_rate = 8 + ani_header.cSteps * 4; int size_seq = 8 + ani_header.cSteps * 4; int size_list2 = 8 + ani_frames.length(); int size = size_file_header + size_list1 + size_anih + size_rate + size_seq + size_list2; DataBuffer ani_file(size); char *data = ani_file.get_data(); set_riff_header(data, "RIFF", size); memcpy(data + 8, "ACON", 4); data += size_file_header; set_riff_header(data, "LIST", size_list1); ani_info.write(data + 8); data += size_list1; set_riff_header(data, "anih", size_anih); memcpy(data + 8, &ani_header, sizeof(ANIHeader)); data += size_anih; set_riff_header(data, "rate", size_rate); DWORD *rate = (DWORD *)(data + 8); for (DWORD i = 0; i < ani_header.cSteps; i++) rate[i] = rates[i]; data += size_rate; set_riff_header(data, "seq ", size_seq); DWORD *seq = (DWORD *)(data + 8); for (DWORD i = 0; i < ani_header.cSteps; i++) seq[i] = steps[i]; data += size_rate; set_riff_header(data, "LIST", size_list2); ani_frames.write(data + 8); data += size_list2; return ani_file; } void CursorProvider_Win32::set_riff_header(char *data, const char *type, DWORD size) { memcpy(data, type, 4); DWORD *s = (DWORD *)(data + 4); *s = size - 8; } }
33.591667
170
0.708013
xctan
cd3513680c3ae35f2ccf1890a8827e010bbfd761
1,123
hh
C++
gsky/net/pp/writer.hh
pwnsky/gsky
8d671c949a88726c6923f44cdce38699fc7fe660
[ "Apache-2.0" ]
1
2021-10-30T14:40:59.000Z
2021-10-30T14:40:59.000Z
gsky/net/pp/writer.hh
pwnsky/gsky
8d671c949a88726c6923f44cdce38699fc7fe660
[ "Apache-2.0" ]
null
null
null
gsky/net/pp/writer.hh
pwnsky/gsky
8d671c949a88726c6923f44cdce38699fc7fe660
[ "Apache-2.0" ]
null
null
null
#pragma once #include <map> #include <string> #include <gsky/gsky.hh> #include <gsky/util/vessel.hh> #include <gsky/util/json.hh> namespace gsky { namespace net { namespace pp { class writer { using json = gsky::util::json; public: explicit writer(); // uid for deal with offline ~writer(); void set_send_data_handler(std::function<void(const std::string &)> h); void set_push_data_handler(std::function<void(const std::string &)> h); void set_route_handler(std::function<void(unsigned char [])> h); bool send_data(const std::string &content); // 同步发送数据, 一次请求只能发送一次 bool push_data(const std::string &content); // 异步发送数据, 一次请求可以发送多次 bool send_json(gsky::util::json &json_obj); bool push_json(gsky::util::json &json_obj); void clean_handler(); void set_route(unsigned char route []); private: std::string json_to_string(json &json_obj); std::function<void(const std::string &)> send_data_handler_ = nullptr; std::function<void(const std::string &)> push_data_handler_ = nullptr; std::function<void(unsigned char [])> set_route_handler_ = nullptr; }; } } }
29.552632
75
0.69724
pwnsky
cd38d9dae4018330c6caa49ac82c8b981c30a82e
879
cpp
C++
Source/TPSOnline/Private/Actors/AmmoPickupActor.cpp
DanialKama/TPSOnline
0c683be23882a72ca8f1daf6e62728fabf1db913
[ "MIT" ]
2
2022-01-20T19:29:43.000Z
2022-01-26T15:01:32.000Z
Source/TPSOnline/Private/Actors/AmmoPickupActor.cpp
DanialKama/TPSOnline
0c683be23882a72ca8f1daf6e62728fabf1db913
[ "MIT" ]
42
2022-01-15T09:20:06.000Z
2022-02-01T19:28:04.000Z
Source/TPSOnline/Private/Actors/AmmoPickupActor.cpp
DanialKama/TPSOnline
0c683be23882a72ca8f1daf6e62728fabf1db913
[ "MIT" ]
null
null
null
// Copyright 2022 Danial Kamali. All Rights Reserved. #include "Actors/AmmoPickupActor.h" AAmmoPickupActor::AAmmoPickupActor() { PrimaryActorTick.bCanEverTick = false; MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh")); SetRootComponent(MeshComponent); MeshComponent->SetComponentTickEnabled(false); MeshComponent->CanCharacterStepUpOn = ECB_No; MeshComponent->SetGenerateOverlapEvents(false); MeshComponent->SetCollisionProfileName("Pickup"); // Initialize variables PickupType = EPickupType::Ammo; AmmoType = EAmmoType::FiveFiveSix; Amount = 90; } void AAmmoPickupActor::OnRep_PickupState() { switch (PickupState) { case 0: case 2: // Picked up, Used if (Amount <= 0) { Destroy(); } break; case 1: // Dropped MeshComponent->SetSimulatePhysics(true); MeshComponent->SetCollisionProfileName("Pickup"); break; } }
22.538462
76
0.754266
DanialKama
cd3c01a6a17c5cbf71efa33dc3a7311e4aebb12b
878
cpp
C++
ConsoleWriterFactory.cpp
nwehr/eloquent-ext-consolewriter
35ce11895fb092120689359a0b80d4e47632a029
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
ConsoleWriterFactory.cpp
nwehr/eloquent-ext-consolewriter
35ce11895fb092120689359a0b80d4e47632a029
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
ConsoleWriterFactory.cpp
nwehr/eloquent-ext-consolewriter
35ce11895fb092120689359a0b80d4e47632a029
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // Copyright 2013-2014 EvriChart, Inc. All Rights Reserved. // See LICENSE.txt // // Internal #include "ConsoleWriter.h" #include "ConsoleWriterFactory.h" /////////////////////////////////////////////////////////////////////////////// // ConsoleWriterFactory : IOExtensionFactory /////////////////////////////////////////////////////////////////////////////// Eloquent::ConsoleWriterFactory::ConsoleWriterFactory() {} Eloquent::ConsoleWriterFactory::~ConsoleWriterFactory() {} Eloquent::IO* Eloquent::ConsoleWriterFactory::New( const boost::property_tree::ptree::value_type& i_Config , std::mutex& i_QueueMutex , std::condition_variable& i_QueueCV , std::queue<QueueItem>& i_Queue , unsigned int& i_NumWriters ) { return new ConsoleWriter( i_Config, i_QueueMutex, i_QueueCV, i_Queue, i_NumWriters ); }
36.583333
106
0.574032
nwehr
cd3c2eeb055fef1a26ec3b781c3bf0a173fddbb9
19,764
cpp
C++
src/3rd_party/miniz_cpp.cpp
Eisenwave/voxel-io
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
[ "MIT" ]
12
2020-06-25T13:40:22.000Z
2021-12-06T04:00:29.000Z
src/3rd_party/miniz_cpp.cpp
Eisenwave/voxel-io
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
[ "MIT" ]
2
2021-02-04T16:19:40.000Z
2021-06-25T09:39:20.000Z
src/3rd_party/miniz_cpp.cpp
Eisenwave/voxel-io
d902568de2d4afda254e533a5ee9e4ad5fe7d2be
[ "MIT" ]
null
null
null
#include "voxelio/3rd_party/miniz_cpp.hpp" #include "voxelio/3rd_party/miniz.h" #include <assert.h> #include <iostream> #include <fstream> #include <cstring> namespace miniz_cpp { namespace detail { #ifdef _WIN32 char directory_separator = '\\'; char alt_directory_separator = '/'; #else constexpr char directory_separator = '/'; constexpr char alt_directory_separator = '\\'; #endif static std::string join_path(const std::vector<std::string> &parts) { std::string joined; std::size_t i = 0; for(const auto &part : parts) { joined.append(part); if(i++ != parts.size() - 1) { joined.append(1, '/'); } } return joined; } static std::vector<std::string> split_path(const std::string &path, char delim = directory_separator) { std::vector<std::string> split; std::string::size_type previous_index = 0; auto separator_index = path.find(delim); while(separator_index != std::string::npos) { auto part = path.substr(previous_index, separator_index - previous_index); if(part != "..") { split.push_back(part); } else { split.pop_back(); } previous_index = separator_index + 1; separator_index = path.find(delim, previous_index); } split.push_back(path.substr(previous_index)); if(split.size() == 1 && delim == directory_separator) { auto alternative = split_path(path, alt_directory_separator); if(alternative.size() > 1) { return alternative; } } return split; } static uint32_t crc32buf(const char *buf, std::size_t len) { uint32_t oldcrc32 = 0xFFFFFFFF; uint32_t crc_32_tab[] = { /* CRC polynomial 0xedb88320 */ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; #define UPDC32(octet,crc) (crc_32_tab[((crc)\ ^ static_cast<uint8_t>(octet)) & 0xff] ^ ((crc) >> 8)) for ( ; len; --len, ++buf) { oldcrc32 = UPDC32(*buf, oldcrc32); } return ~oldcrc32; } static tm safe_localtime(const time_t &t) { #ifdef _WIN32 tm time; localtime_s(&time, &t); return time; #else tm *time = localtime(&t); assert(time != nullptr); return *time; #endif } static std::size_t write_callback(void *opaque, std::uint64_t file_ofs, const void *pBuf, std::size_t n) { auto buffer = static_cast<std::vector<char> *>(opaque); if(file_ofs + n > buffer->size()) { auto new_size = static_cast<std::vector<char>::size_type>(file_ofs + n); buffer->resize(new_size); } for(std::size_t i = 0; i < n; i++) { (*buffer)[static_cast<std::size_t>(file_ofs + i)] = (static_cast<const char *>(pBuf))[i]; } return n; } } // namespace detail zip_file::zip_file() : archive_(new mz_zip_archive()) { reset(); } zip_file::~zip_file() { reset(); } void zip_file::load(std::istream &stream) { reset(); buffer_.assign(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()); remove_comment(); start_read(); } void zip_file::load(const std::string &filename) { filename_ = filename; std::ifstream stream(filename, std::ios::binary); load(stream); } void zip_file::load(const std::vector<unsigned char> &bytes) { reset(); buffer_.assign(bytes.begin(), bytes.end()); remove_comment(); start_read(); } void zip_file::save(const std::function<void(const char* data, size_t size)> &consumer) { if(archive_->m_zip_mode == MZ_ZIP_MODE_WRITING) { mz_zip_writer_finalize_archive(archive_.get()); } if(archive_->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED) { mz_zip_writer_end(archive_.get()); } if(archive_->m_zip_mode == MZ_ZIP_MODE_INVALID) { start_read(); } append_comment(); consumer(buffer_.data(), buffer_.size()); } void zip_file::save(const std::string &filename) { filename_ = filename; std::ofstream stream(filename, std::ios::binary); save(stream); } void zip_file::save(std::ostream &stream) { save([&stream](const char *data, size_t size){ stream.write(data, static_cast<std::streamsize>(size)); }); } void zip_file::save(std::vector<unsigned char> &bytes) { save([&bytes](const char *data, size_t size){ bytes.assign(data, data + size); }); } void zip_file::reset() { switch(archive_->m_zip_mode) { case MZ_ZIP_MODE_READING: mz_zip_reader_end(archive_.get()); break; case MZ_ZIP_MODE_WRITING: mz_zip_writer_finalize_archive(archive_.get()); mz_zip_writer_end(archive_.get()); break; case MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED: mz_zip_writer_end(archive_.get()); break; case MZ_ZIP_MODE_INVALID: break; } if(archive_->m_zip_mode != MZ_ZIP_MODE_INVALID) { throw std::runtime_error(""); } buffer_.clear(); comment.clear(); start_write(); mz_zip_writer_finalize_archive(archive_.get()); mz_zip_writer_end(archive_.get()); } bool zip_file::has_file(const std::string &name) { if(archive_->m_zip_mode != MZ_ZIP_MODE_READING) { start_read(); } int index = mz_zip_reader_locate_file(archive_.get(), name.c_str(), nullptr, 0); return index != -1; } bool zip_file::has_file(const zip_info &name) { return has_file(name.filename); } zip_info zip_file::getinfo(const std::string &name) { if(archive_->m_zip_mode != MZ_ZIP_MODE_READING) { start_read(); } int index = mz_zip_reader_locate_file(archive_.get(), name.c_str(), nullptr, 0); if(index == -1) { throw std::runtime_error("not found"); } return getinfo(index); } std::vector<zip_info> zip_file::infolist() { if(archive_->m_zip_mode != MZ_ZIP_MODE_READING) { start_read(); } std::vector<zip_info> info; for(std::size_t i = 0; i < mz_zip_reader_get_num_files(archive_.get()); i++) { info.push_back(getinfo(static_cast<int>(i))); } return info; } std::vector<std::string> zip_file::namelist() { std::vector<std::string> names; for(auto &info : infolist()) { names.push_back(info.filename); } return names; } std::ostream &zip_file::open(const std::string &name) { return open(getinfo(name)); } std::ostream &zip_file::open(const zip_info &name) { auto data = read(name); std::string data_string(data.begin(), data.end()); open_stream_ << data_string; return open_stream_; } void zip_file::extract(const std::string &member, const std::string &path) { std::fstream stream(detail::join_path({path, member}), std::ios::binary | std::ios::out); stream << open(member).rdbuf(); } void zip_file::extract(const zip_info &member, const std::string &path) { std::fstream stream(detail::join_path({path, member.filename}), std::ios::binary | std::ios::out); stream << open(member).rdbuf(); } void zip_file::extractall(const std::string &path) { extractall(path, infolist()); } void zip_file::extractall(const std::string &path, const std::vector<std::string> &members) { for(auto &member : members) { extract(member, path); } } void zip_file::extractall(const std::string &path, const std::vector<zip_info> &members) { for(auto &member : members) { extract(member, path); } } void zip_file::printdir() { printdir(std::cout); } void zip_file::printdir(std::ostream &stream) { stream << " Length " << " " << " " << "Date" << " " << " " << "Time " << " " << "Name" << std::endl; stream << "--------- ---------- ----- ----" << std::endl; std::size_t sum_length = 0; std::size_t file_count = 0; for(auto &member : infolist()) { sum_length += member.file_size; file_count++; std::string length_string = std::to_string(member.file_size); while(length_string.length() < 9) { length_string = " " + length_string; } stream << length_string; stream << " "; stream << (member.date_time.month < 10 ? "0" : "") << member.date_time.month; stream << "/"; stream << (member.date_time.day < 10 ? "0" : "") << member.date_time.day; stream << "/"; stream << member.date_time.year; stream << " "; stream << (member.date_time.hours < 10 ? "0" : "") << member.date_time.hours; stream << ":"; stream << (member.date_time.minutes < 10 ? "0" : "") << member.date_time.minutes; stream << " "; stream << member.filename; stream << std::endl; } stream << "--------- -------" << std::endl; std::string length_string = std::to_string(sum_length); while(length_string.length() < 9) { length_string = " " + length_string; } stream << length_string << " " << file_count << " " << (file_count == 1 ? "file" : "files"); stream << std::endl; } std::string zip_file::read(const zip_info &info) { std::size_t size; char *data = static_cast<char *>(mz_zip_reader_extract_file_to_heap(archive_.get(), info.filename.c_str(), &size, 0)); if(data == nullptr) { throw std::runtime_error("file couldn't be read"); } std::string extracted(data, data + size); mz_free(data); return extracted; } std::string zip_file::read(const std::string &name) { return read(getinfo(name)); } std::pair<bool, std::string> zip_file::testzip() { if(archive_->m_zip_mode == MZ_ZIP_MODE_INVALID) { throw std::runtime_error("not open"); } for(auto &file : infolist()) { auto content = read(file); auto crc = detail::crc32buf(content.c_str(), content.size()); if(crc != file.crc) { return {false, file.filename}; } } return {true, ""}; } void zip_file::write(const std::string &filename) { auto split = detail::split_path(filename); if(split.size() > 1) { split.erase(split.begin()); } auto arcname = detail::join_path(split); write(filename, arcname); } void zip_file::write(const std::string &filename, const std::string &arcname) { std::fstream file(filename, std::ios::binary | std::ios::in); std::stringstream ss; ss << file.rdbuf(); std::string bytes = ss.str(); writestr(arcname, bytes); } void zip_file::writestr(const std::string &arcname, const std::string &bytes) { if(archive_->m_zip_mode != MZ_ZIP_MODE_WRITING) { start_write(); } if(!mz_zip_writer_add_mem(archive_.get(), arcname.c_str(), bytes.data(), bytes.size(), MZ_BEST_COMPRESSION)) { throw std::runtime_error("write error"); } } void zip_file::writestr(const zip_info &info, const std::string &bytes) { if(info.filename.empty() || info.date_time.year < 1980) { throw std::runtime_error("must specify a filename and valid date (year >= 1980"); } if(archive_->m_zip_mode != MZ_ZIP_MODE_WRITING) { start_write(); } auto crc = detail::crc32buf(bytes.c_str(), bytes.size()); if(!mz_zip_writer_add_mem_ex(archive_.get(), info.filename.c_str(), bytes.data(), bytes.size(), info.comment.c_str(), static_cast<mz_uint16>(info.comment.size()), MZ_BEST_COMPRESSION, 0, crc)) { throw std::runtime_error("write error"); } } void zip_file::start_read() { if(archive_->m_zip_mode == MZ_ZIP_MODE_READING) return; if(archive_->m_zip_mode == MZ_ZIP_MODE_WRITING) { mz_zip_writer_finalize_archive(archive_.get()); } if(archive_->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED) { mz_zip_writer_end(archive_.get()); } if(!mz_zip_reader_init_mem(archive_.get(), buffer_.data(), buffer_.size(), 0)) { throw std::runtime_error("bad zip"); } } void zip_file::start_write() { if(archive_->m_zip_mode == MZ_ZIP_MODE_WRITING) return; switch(archive_->m_zip_mode) { case MZ_ZIP_MODE_READING: { mz_zip_archive archive_copy; std::memset(&archive_copy, 0, sizeof(mz_zip_archive)); std::vector<char> buffer_copy(buffer_.begin(), buffer_.end()); if(!mz_zip_reader_init_mem(&archive_copy, buffer_copy.data(), buffer_copy.size(), 0)) { throw std::runtime_error("bad zip"); } mz_zip_reader_end(archive_.get()); archive_->m_pWrite = &detail::write_callback; archive_->m_pIO_opaque = &buffer_; buffer_ = std::vector<char>(); if(!mz_zip_writer_init(archive_.get(), 0)) { throw std::runtime_error("bad zip"); } for(unsigned int i = 0; i < static_cast<unsigned int>(archive_copy.m_total_files); i++) { if(!mz_zip_writer_add_from_zip_reader(archive_.get(), &archive_copy, i)) { throw std::runtime_error("fail"); } } mz_zip_reader_end(&archive_copy); return; } case MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED: mz_zip_writer_end(archive_.get()); break; case MZ_ZIP_MODE_INVALID: case MZ_ZIP_MODE_WRITING: break; } archive_->m_pWrite = &detail::write_callback; archive_->m_pIO_opaque = &buffer_; if(!mz_zip_writer_init(archive_.get(), 0)) { throw std::runtime_error("bad zip"); } } void zip_file::append_comment() { if(!comment.empty()) { auto comment_length = std::min(static_cast<uint16_t>(comment.length()), std::numeric_limits<uint16_t>::max()); buffer_[buffer_.size() - 2] = static_cast<char>(comment_length); buffer_[buffer_.size() - 1] = static_cast<char>(comment_length >> 8); std::copy(comment.begin(), comment.end(), std::back_inserter(buffer_)); } } void zip_file::remove_comment() { if(buffer_.empty()) return; std::size_t position = buffer_.size() - 1; for(; position >= 3; position--) { if(buffer_[position - 3] == 'P' && buffer_[position - 2] == 'K' && buffer_[position - 1] == '\x05' && buffer_[position] == '\x06') { position = position + 17; break; } } if(position == 3) { throw std::runtime_error("didn't find end of central directory signature"); } uint16_t length = static_cast<uint16_t>(buffer_[position + 1]); length = static_cast<uint16_t>(length << 8) + static_cast<uint16_t>(buffer_[position]); position += 2; if(length != 0) { comment = std::string(buffer_.data() + position, buffer_.data() + position + length); buffer_.resize(buffer_.size() - length); buffer_[buffer_.size() - 1] = 0; buffer_[buffer_.size() - 2] = 0; } } zip_info zip_file::getinfo(int index) { if(archive_->m_zip_mode != MZ_ZIP_MODE_READING) { start_read(); } mz_zip_archive_file_stat stat; mz_zip_reader_file_stat(archive_.get(), static_cast<mz_uint>(index), &stat); zip_info result; result.filename = std::string(stat.m_filename, stat.m_filename + std::strlen(stat.m_filename)); result.comment = std::string(stat.m_comment, stat.m_comment + stat.m_comment_size); result.compress_size = static_cast<std::size_t>(stat.m_comp_size); result.file_size = static_cast<std::size_t>(stat.m_uncomp_size); result.header_offset = static_cast<std::size_t>(stat.m_local_header_ofs); result.crc = stat.m_crc32; auto time = detail::safe_localtime(stat.m_time); result.date_time.year = 1900 + time.tm_year; result.date_time.month = 1 + time.tm_mon; result.date_time.day = time.tm_mday; result.date_time.hours = time.tm_hour; result.date_time.minutes = time.tm_min; result.date_time.seconds = time.tm_sec; result.flag_bits = stat.m_bit_flag; result.internal_attr = stat.m_internal_attr; result.external_attr = stat.m_external_attr; result.extract_version = stat.m_version_needed; result.create_version = stat.m_version_made_by; result.volume = stat.m_file_index; result.create_system = stat.m_method; return result; } }
28.810496
196
0.635499
Eisenwave
cd3f7ea62174f82d1dded06605810dbaa95730a2
473
cpp
C++
NJUPT-ACM/2017.4.15/A.cpp
ZsgsDesign/My_ACM_Life
9cd5e6dedbf58d8dd2322d5f06ea9d86583f7c46
[ "CC-BY-4.0" ]
4
2019-02-17T15:14:21.000Z
2019-03-30T11:34:19.000Z
NJUPT-ACM/2017.4.15/A.cpp
ZsgsDesign/My_ACM_Life
9cd5e6dedbf58d8dd2322d5f06ea9d86583f7c46
[ "CC-BY-4.0" ]
null
null
null
NJUPT-ACM/2017.4.15/A.cpp
ZsgsDesign/My_ACM_Life
9cd5e6dedbf58d8dd2322d5f06ea9d86583f7c46
[ "CC-BY-4.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> using namespace std; int n,ans; int a,b,c,t; int main() { //ios::sync_with_stdio(false); cin >> n; //cin >> n; for(int i=1;i<=n;i++) { cin >> a >> b >> c; if(a>b){t=a;a=b;b=t;} if(b>c){t=b;b=c;c=t;} if(a>b){t=a;a=b;b=t;} ans=c-b; b+=ans; a+=ans; ans+=(c-a)/2; if((c-a)%2) ans+=2; cout << ans << endl; //printf("%d\n",ans); } return 0; }
14.333333
31
0.513742
ZsgsDesign
cd41b3c1ef6d919f19e570969e364f866be9fe4b
7,086
cpp
C++
Platform/Serializer.cpp
kaizen365/truecrypt
4033160fd27dd0182a7b88f63faee1e4e32b709e
[ "Zlib" ]
23
2015-02-15T19:46:22.000Z
2019-08-14T16:53:52.000Z
Platform/Serializer.cpp
pustladi/TrueCrypt
df093ae9b4c5f15e4d494658fa19f459ad77e6d3
[ "Zlib", "MIT" ]
1
2018-11-04T13:57:55.000Z
2018-11-04T15:59:40.000Z
Platform/Serializer.cpp
pustladi/TrueCrypt
df093ae9b4c5f15e4d494658fa19f459ad77e6d3
[ "Zlib", "MIT" ]
8
2015-04-03T14:01:20.000Z
2020-05-17T03:26:19.000Z
/* Copyright (c) 2008 TrueCrypt Developers Association. All rights reserved. Governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #include "Exception.h" #include "ForEach.h" #include "Memory.h" #include "Serializer.h" namespace TrueCrypt { template <typename T> T Serializer::Deserialize () { uint64 size; DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &size, sizeof (size))); if (Endian::Big (size) != sizeof (T)) throw ParameterIncorrect (SRC_POS); T data; DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data, sizeof (data))); return Endian::Big (data); } void Serializer::Deserialize (const string &name, bool &data) { ValidateName (name); data = Deserialize <byte> () == 1; } void Serializer::Deserialize (const string &name, byte &data) { ValidateName (name); data = Deserialize <byte> (); } void Serializer::Deserialize (const string &name, int32 &data) { ValidateName (name); data = (int32) Deserialize <uint32> (); } void Serializer::Deserialize (const string &name, int64 &data) { ValidateName (name); data = (int64) Deserialize <uint64> (); } void Serializer::Deserialize (const string &name, uint32 &data) { ValidateName (name); data = Deserialize <uint32> (); } void Serializer::Deserialize (const string &name, uint64 &data) { ValidateName (name); data = Deserialize <uint64> (); } void Serializer::Deserialize (const string &name, string &data) { ValidateName (name); data = DeserializeString (); } void Serializer::Deserialize (const string &name, wstring &data) { ValidateName (name); data = DeserializeWString (); } void Serializer::Deserialize (const string &name, const BufferPtr &data) { ValidateName (name); uint64 size = Deserialize <uint64> (); if (data.Size() != size) throw ParameterIncorrect (SRC_POS); DataStream->ReadCompleteBuffer (data); } bool Serializer::DeserializeBool (const string &name) { bool data; Deserialize (name, data); return data; } int32 Serializer::DeserializeInt32 (const string &name) { ValidateName (name); return Deserialize <uint32> (); } int64 Serializer::DeserializeInt64 (const string &name) { ValidateName (name); return Deserialize <uint64> (); } uint32 Serializer::DeserializeUInt32 (const string &name) { ValidateName (name); return Deserialize <uint32> (); } uint64 Serializer::DeserializeUInt64 (const string &name) { ValidateName (name); return Deserialize <uint64> (); } string Serializer::DeserializeString () { uint64 size = Deserialize <uint64> (); vector <char> data ((size_t) size); DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data[0], (size_t) size)); return string (&data[0]); } string Serializer::DeserializeString (const string &name) { ValidateName (name); return DeserializeString (); } list <string> Serializer::DeserializeStringList (const string &name) { ValidateName (name); list <string> deserializedList; uint64 listSize = Deserialize <uint64> (); for (size_t i = 0; i < listSize; i++) deserializedList.push_back (DeserializeString ()); return deserializedList; } wstring Serializer::DeserializeWString () { uint64 size = Deserialize <uint64> (); vector <wchar_t> data ((size_t) size / sizeof (wchar_t)); DataStream->ReadCompleteBuffer (BufferPtr ((byte *) &data[0], (size_t) size)); return wstring (&data[0]); } list <wstring> Serializer::DeserializeWStringList (const string &name) { ValidateName (name); list <wstring> deserializedList; uint64 listSize = Deserialize <uint64> (); for (size_t i = 0; i < listSize; i++) deserializedList.push_back (DeserializeWString ()); return deserializedList; } wstring Serializer::DeserializeWString (const string &name) { ValidateName (name); return DeserializeWString (); } template <typename T> void Serializer::Serialize (T data) { uint64 size = Endian::Big (uint64 (sizeof (data))); DataStream->Write (ConstBufferPtr ((byte *) &size, sizeof (size))); data = Endian::Big (data); DataStream->Write (ConstBufferPtr ((byte *) &data, sizeof (data))); } void Serializer::Serialize (const string &name, bool data) { SerializeString (name); byte d = data ? 1 : 0; Serialize (d); } void Serializer::Serialize (const string &name, byte data) { SerializeString (name); Serialize (data); } void Serializer::Serialize (const string &name, const char *data) { Serialize (name, string (data)); } void Serializer::Serialize (const string &name, int32 data) { SerializeString (name); Serialize ((uint32) data); } void Serializer::Serialize (const string &name, int64 data) { SerializeString (name); Serialize ((uint64) data); } void Serializer::Serialize (const string &name, uint32 data) { SerializeString (name); Serialize (data); } void Serializer::Serialize (const string &name, uint64 data) { SerializeString (name); Serialize (data); } void Serializer::Serialize (const string &name, const string &data) { SerializeString (name); SerializeString (data); } void Serializer::Serialize (const string &name, const wchar_t *data) { Serialize (name, wstring (data)); } void Serializer::Serialize (const string &name, const wstring &data) { SerializeString (name); SerializeWString (data); } void Serializer::Serialize (const string &name, const list <string> &stringList) { SerializeString (name); uint64 listSize = stringList.size(); Serialize (listSize); foreach (const string &item, stringList) SerializeString (item); } void Serializer::Serialize (const string &name, const list <wstring> &stringList) { SerializeString (name); uint64 listSize = stringList.size(); Serialize (listSize); foreach (const wstring &item, stringList) SerializeWString (item); } void Serializer::Serialize (const string &name, const ConstBufferPtr &data) { SerializeString (name); uint64 size = data.Size(); Serialize (size); DataStream->Write (data); } void Serializer::SerializeString (const string &data) { Serialize ((uint64) data.size() + 1); DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), data.size() + 1)); } void Serializer::SerializeWString (const wstring &data) { uint64 size = (data.size() + 1) * sizeof (wchar_t); Serialize (size); DataStream->Write (ConstBufferPtr ((byte *) (data.data() ? data.data() : data.c_str()), (size_t) size)); } void Serializer::ValidateName (const string &name) { string dName = DeserializeString(); if (dName != name) { throw ParameterIncorrect (SRC_POS); } } }
23.62
109
0.659328
kaizen365
cd4249b7289bbddad74b859af29bd91b5f15b6c0
10,830
hpp
C++
include/caffe/util/math_functions.hpp
oscmansan/nvcaffe
22738c97e9c6991e49a12a924c3c773d95795b5c
[ "BSD-2-Clause" ]
null
null
null
include/caffe/util/math_functions.hpp
oscmansan/nvcaffe
22738c97e9c6991e49a12a924c3c773d95795b5c
[ "BSD-2-Clause" ]
null
null
null
include/caffe/util/math_functions.hpp
oscmansan/nvcaffe
22738c97e9c6991e49a12a924c3c773d95795b5c
[ "BSD-2-Clause" ]
null
null
null
#ifndef CAFFE_UTIL_MATH_FUNCTIONS_H_ #define CAFFE_UTIL_MATH_FUNCTIONS_H_ #include <stdint.h> #include <cmath> // for std::fabs and std::signbit #include "glog/logging.h" #include "caffe/common.hpp" #include "caffe/util/device_alternate.hpp" #include "caffe/util/mkl_alternate.hpp" #include "caffe/util/get.hpp" namespace caffe { template <typename T_IN, typename T_OUT> void caffe_cpu_convert(const size_t N, const T_IN *in, T_OUT *out) { for (size_t i = 0; i < N; ++i) { out[i] = Get<T_OUT>(in[i]); } } // Caffe gemm provides a simpler interface to the gemm functions, with the // limitation that the data has to be contiguous in memory. template <typename Dtype, typename Mtype> void caffe_cpu_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const Mtype alpha, const Dtype* A, const Dtype* B, const Mtype beta, Dtype* C); template <typename Dtype, typename Mtype> void caffe_cpu_gemv(const CBLAS_TRANSPOSE TransA, const int M, const int N, const Mtype alpha, const Dtype* A, const Dtype* x, const Mtype beta, Dtype* y); template <typename Dtype, typename Mtype> void caffe_axpy(const int N, const Mtype alpha, const Dtype* X, Dtype* Y); template <typename Dtype, typename Mtype> void caffe_cpu_axpby(const int N, const Mtype alpha, const Dtype* X, const Mtype beta, Dtype* Y); template <typename Dtype, typename Mtype> void caffe_copy(const int N, const Dtype *X, Dtype *Y); template <typename Dtype> void caffe_set(const int N, const Dtype alpha, Dtype *X); inline void caffe_memset(const size_t N, const int alpha, void* X) { memset(X, alpha, N); // NOLINT(caffe/alt_fn) } template <typename Dtype, typename Mtype> void caffe_add_scalar(const int N, const Mtype alpha, Dtype *X); template <typename Dtype, typename Mtype> void caffe_scal(const int N, const Mtype alpha, Dtype *X); template <typename Dtype, typename Mtype> void caffe_sqr(const int N, const Dtype* a, Dtype* y); template <typename Dtype, typename Mtype> void caffe_add(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_sub(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_mul(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_div(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_powx(const int n, const Dtype* a, const Mtype b, Dtype* y); unsigned int caffe_rng_rand(); template <typename Dtype> Dtype caffe_nextafter(const Dtype b); template <typename Dtype, typename Mtype> void caffe_rng_uniform(const int n, const Mtype a, const Mtype b, Dtype* r); template <typename Dtype, typename Mtype> void caffe_rng_gaussian(const int n, const Mtype mu, const Mtype sigma, Dtype* r); template <typename Dtype, typename Mtype> void caffe_rng_bernoulli(const int n, const Mtype p, int* r); template <typename Dtype, typename Mtype> void caffe_rng_bernoulli(const int n, const Mtype p, unsigned int* r); template <typename Dtype, typename Mtype> void caffe_exp(const int n, const Dtype* a, Dtype* y); template <typename Dtype> void caffe_log(const int n, const Dtype* a, Dtype* y); template <typename Dtype> void caffe_abs(const int n, const Dtype* a, Dtype* y); template <typename Dtype, typename Mtype> Mtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y); template <typename Dtype, typename Mtype> Mtype caffe_cpu_strided_dot(const int n, const Dtype* x, const int incx, const Dtype* y, const int incy); template <typename Dtype> int caffe_cpu_hamming_distance(const int n, const Dtype* x, const Dtype* y); // Returns the sum of the absolute values of the elements of vector x template <typename Dtype, typename Mtype> Mtype caffe_cpu_asum(const int n, const Dtype* x); // the branchless, type-safe version from // http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c template<typename Dtype, typename Mtype> inline int8_t caffe_sign(Mtype val) { return (Mtype(0) < val) - (val < Mtype(0)); } // The following two macros are modifications of DEFINE_VSL_UNARY_FUNC // in include/caffe/util/mkl_alternate.hpp authored by @Rowland Depp. // Please refer to commit 7e8ef25c7 of the boost-eigen branch. // Git cherry picking that commit caused a conflict hard to resolve and // copying that file in convenient for code reviewing. // So they have to be pasted here temporarily. #define DEFINE_CAFFE_CPU_UNARY_FUNC(name, operation) \ template<typename Dtype, typename Mtype> \ void caffe_cpu_##name(const int n, const Dtype* x, Dtype* y) { \ CHECK_GT(n, 0); CHECK(x); CHECK(y); \ for (int i = 0; i < n; ++i) { \ operation; \ } \ } // output is 1 for the positives, 0 for zero, and -1 for the negatives #define TYPE Dtype,Mtype DEFINE_CAFFE_CPU_UNARY_FUNC(sign, y[i] = Get<Dtype>(caffe_sign<TYPE>(Get<Mtype>(x[i])))); // This returns a nonzero value if the input has its sign bit set. // The name sngbit is meant to avoid conflicts with std::signbit in the macro. // The extra parens are needed because CUDA < 6.5 defines signbit as a macro, // and we don't want that to expand here when CUDA headers are also included. DEFINE_CAFFE_CPU_UNARY_FUNC(sgnbit, \ y[i] = Get<Dtype>(static_cast<int>(std::signbit(Get<double>(x[i]))))); DEFINE_CAFFE_CPU_UNARY_FUNC(fabs, y[i] = std::fabs(x[i])); template <typename Dtype, typename Mtype> void caffe_cpu_scale(const int n, const Mtype alpha, const Dtype *x, Dtype* y); #ifndef CPU_ONLY // GPU // Decaf gpu gemm provides an interface that is almost the same as the cpu // gemm function - following the c convention and calling the fortran-order // gpu code under the hood. template <typename Dtype, typename Mtype> void caffe_gpu_gemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const Mtype alpha, const Dtype* A, const Dtype* B, const Mtype beta, Dtype* C); template <typename Dtype, typename Mtype> void caffe_gpu_gemv(const CBLAS_TRANSPOSE TransA, const int M, const int N, const Mtype alpha, const Dtype* A, const Dtype* x, const Mtype beta, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_axpy(const int N, const Mtype alpha, const Dtype* X, Dtype* Y); template <typename Dtype, typename Mtype> void caffe_gpu_axpby(const int N, const Mtype alpha, const Dtype* X, const Mtype beta, Dtype* Y); void caffe_gpu_memcpy(const size_t N, const void *X, void *Y); template <typename Dtype, typename Mtype> void caffe_gpu_set(const int N, const Mtype alpha, Dtype *X); inline void caffe_gpu_memset(const size_t N, const int alpha, void* X) { #ifndef CPU_ONLY CUDA_CHECK(cudaMemset(X, alpha, N)); // NOLINT(caffe/alt_fn) #else NO_GPU; #endif } template <typename Dtype, typename Mtype> void caffe_gpu_add_scalar(const int N, const Mtype alpha, Dtype *X); template <typename Dtype, typename Mtype> void caffe_gpu_scal(const int N, const Mtype alpha, Dtype *X); template <typename Dtype, typename Mtype> void caffe_gpu_add(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_sub(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_mul(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_div(const int N, const Dtype* a, const Dtype* b, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_abs(const int n, const Dtype* a, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_exp(const int n, const Dtype* a, Dtype* y); template <typename Dtype> void caffe_gpu_log(const int n, const Dtype* a, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_powx(const int n, const Dtype* a, const Mtype b, Dtype* y); // caffe_gpu_rng_uniform with two arguments generates integers in the range // [0, UINT_MAX]. void caffe_gpu_rng_uniform(const int n, unsigned int* r); // caffe_gpu_rng_uniform with four arguments generates floats in the range // (a, b] (strictly greater than a, less than or equal to b) due to the // specification of curandGenerateUniform. With a = 0, b = 1, just calls // curandGenerateUniform; with other limits will shift and scale the outputs // appropriately after calling curandGenerateUniform. template <typename Dtype, typename Mtype> void caffe_gpu_rng_uniform(const int n, const Mtype a, const Mtype b, Dtype* r); template <typename Dtype, typename Mtype> void caffe_gpu_rng_gaussian(const int n, const Mtype mu, const Mtype sigma, Dtype* r); template <typename Dtype, typename Mtype> void caffe_gpu_rng_bernoulli(const int n, const Mtype p, int* r); template <typename Dtype, typename Mtype> void caffe_gpu_dot(const int n, const Dtype* x, const Dtype* y, Mtype* out); template <typename Dtype> uint32_t caffe_gpu_hamming_distance(const int n, const Dtype* x, const Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_asum(const int n, const Dtype* x, Mtype* y); template<typename Dtype, typename Mtype> void caffe_gpu_sign(const int n, const Dtype* x, Dtype* y); template<typename Dtype, typename Mtype> void caffe_gpu_sgnbit(const int n, const Dtype* x, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_fabs(const int n, const Dtype* x, Dtype* y); template <typename Dtype, typename Mtype> void caffe_gpu_scale(const int n, const Mtype alpha, const Dtype *x, Dtype* y); #define DEFINE_AND_INSTANTIATE_GPU_UNARY_FUNC(name, operation) \ template<typename Dtype, typename Mtype> \ __global__ void name##_kernel(const int n, const Dtype* x, Dtype* y) { \ CUDA_KERNEL_LOOP(index, n) { \ operation; \ } \ } \ template <> \ void caffe_gpu_##name<float,float>(const int n, const float* x, float* y) { \ /* NOLINT_NEXT_LINE(whitespace/operators) */ \ name##_kernel<float,float><<<CAFFE_GET_BLOCKS(n), CAFFE_CUDA_NUM_THREADS>>>( \ n, x, y); \ } \ template <> \ void caffe_gpu_##name<double,double>(const int n, const double* x, double* y) { \ /* NOLINT_NEXT_LINE(whitespace/operators) */ \ name##_kernel<double,double><<<CAFFE_GET_BLOCKS(n), CAFFE_CUDA_NUM_THREADS>>>( \ n, x, y); \ } \ template <> \ void caffe_gpu_##name<float16,CAFFE_FP16_MTYPE>(const int n, const float16* x, float16* y) { \ /* NOLINT_NEXT_LINE(whitespace/operators) */ \ name##_kernel<float16,CAFFE_FP16_MTYPE><<<CAFFE_GET_BLOCKS(n), CAFFE_CUDA_NUM_THREADS>>>( \ n, x, y); \ } #endif // !CPU_ONLY } // namespace caffe #endif // CAFFE_UTIL_MATH_FUNCTIONS_H_
36.464646
97
0.734718
oscmansan
cd49ab9f5f1345fb41366b8b8db9410425d26416
1,791
cpp
C++
JobduInCPlusPlus/1013 开门人和关门人.cpp
zpfbuaa/JobduInCPlusPlus
067db56ee952660c6ee6e6ab958747d566f3da02
[ "MIT" ]
16
2017-04-17T03:52:51.000Z
2021-01-21T07:56:50.000Z
JobduInCPlusPlus/1013 开门人和关门人.cpp
zpfbuaa/JobduInCPlusPlus
067db56ee952660c6ee6e6ab958747d566f3da02
[ "MIT" ]
null
null
null
JobduInCPlusPlus/1013 开门人和关门人.cpp
zpfbuaa/JobduInCPlusPlus
067db56ee952660c6ee6e6ab958747d566f3da02
[ "MIT" ]
7
2017-04-17T03:52:52.000Z
2019-09-26T08:41:08.000Z
// // 1013 开门人和关门人.cpp // Jobdu // // Created by PengFei_Zheng on 28/04/2017. // Copyright © 2017 PengFei_Zheng. All rights reserved. // #include <stdio.h> #include <iostream> #include <algorithm> #include <string.h> #include <cstring> #include <cmath> #define MAX_SIZE 21 #define MAX_HUMAN 110 using namespace std; int n, m; struct Sign{ char id[MAX_SIZE]; int comeH; int comeM; int comeS; int leftH; int leftM; int leftS; }; int cmpOpenDoor(const void *a , const void *b){ Sign *c = (Sign *)a; Sign *d = (Sign *)b; if(c->comeH != d->comeH){ return c->comeH - d->comeH; } else if(c->comeM != d->comeH){ return c->comeM - d->comeM; } else return c->comeS - d->comeS; } int cmpCloseDoor(const void *a , const void *b){ Sign *c = (Sign *)a; Sign *d = (Sign *)b; if(c->leftH != d->leftH){ return d->leftH - c->leftH; } else if(c->leftM != d->leftM){ return d->leftM - c->leftM; } else { return d->leftS - c->leftS; } } Sign sign[MAX_HUMAN]; int main(){ // freopen("/Users/pengfei_zheng/Desktop/input.txt", "r", stdin); scanf("%d",&n); while(n--){ scanf("%d",&m); for(int i = 0 ; i < m ; i++){ scanf("%s %d:%d:%d %d:%d:%d",sign[i].id,&sign[i].comeH,&sign[i].comeM,&sign[i].comeS,&sign[i].leftH,&sign[i].leftM,&sign[i].leftS); } qsort(sign,m,sizeof(Sign),cmpOpenDoor); printf("%s ",sign[0].id); qsort(sign,m,sizeof(Sign),cmpCloseDoor); printf("%s\n",sign[0].id); // for(int i = 0 ; i < m ; i++){ // printf("%s %d:%d:%d %d:%d:%d\n",sign[i].id,sign[i].comeH,sign[i].comeM,sign[i].comeS,sign[i].leftH,sign[i].leftM,sign[i].leftS); // } } }
22.111111
143
0.535455
zpfbuaa
cd4f45c69789cbc1c4c4d87fb97175f7a7d4540d
529
cxx
C++
firmware/MXKeyboard.cxx
bad-alloc-heavy-industries/MXKeyboard
b1637ba3b2eb9a741559ceb789452127e1a441a6
[ "BSD-3-Clause" ]
5
2021-03-07T00:19:15.000Z
2021-09-02T22:34:19.000Z
firmware/MXKeyboard.cxx
bad-alloc-heavy-industries/MXKeyboard
b1637ba3b2eb9a741559ceb789452127e1a441a6
[ "BSD-3-Clause" ]
null
null
null
firmware/MXKeyboard.cxx
bad-alloc-heavy-industries/MXKeyboard
b1637ba3b2eb9a741559ceb789452127e1a441a6
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause #include <avr/builtins.h> #include <usb/core.hxx> #include "MXKeyboard.hxx" #include "interrupts.hxx" #include "usb/hid.hxx" void run() { __builtin_avr_cli(); oscInit(); //ps2Init(); dmaInit(); ledInit(); keyInit(); usb::core::init(); usb::hid::registerHandlers(1, 0, 1); usb::core::attach(); PMIC.CTRL = 0x87; __builtin_avr_sei(); while (true) continue; } void usbBusEvtIRQ() noexcept { usb::core::handleIRQ(); } void usbIOCompIRQ() noexcept { usb::core::handleIRQ(); }
18.892857
56
0.674858
bad-alloc-heavy-industries
cd4fcfa8ce8324da396dfd5d3570eb2cd7f56a51
5,309
hpp
C++
lib/ModbusAPI.hpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
1
2020-03-15T18:53:26.000Z
2020-03-15T18:53:26.000Z
lib/ModbusAPI.hpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
null
null
null
lib/ModbusAPI.hpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
1
2022-03-14T11:06:26.000Z
2022-03-14T11:06:26.000Z
//! \file /* * Copyright (C) 2018 Daniel Mensinger * * 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 #include "mSMAConfig.hpp" #include <memory> #include <string> #include "DataBase.hpp" #include "Enums.hpp" #include "MBConnectionBase.hpp" #include "RegisterContainer.hpp" //! The main namespace of this library. namespace modbusSMA { /*! * \mainpage ModbusSMA * * modbusSMA is a smal and easy to use library for accessing the modbus interface of SMA inverters. * * The following code shows a basic example: * * \code{.cpp} * #include <modbusSMA/ModbusAPI.hpp> * #include <vector> * * using namespace modbusSMA; * using namespace std; * * int main() { * ModbusAPI mapi("127.0.0.1", 502); // Create the main API object * * // Call further configuration functions here. * * ErrorCode err = mapi.setup(); // Connect to the modbus interface with ModbusAPI::setup() * auto reg = mapi.getRegisters(); // Get a pointer to the RegisterContainer where all registers are stored. * * // Use the shared RegisterContainer pointer (reg) to get a list of supported registers. * vector<uint16_t> toFetch = {30051, 30053, 30529, 30535, 30538}; * * err = mapi.updateRegisters(toFetch); // Fetch the values of the registers and store them in the RegisterContainer * * // The fetched register values can now be retrieved from the shared RegisterContainer * vector<Register> registersWithValues = reg->getRegisters(toFetch); * * return 0; * } * \endcode * * \sa ModbusAPI for more information */ /*! * \brief Main ModbusSMA class * * This class is the main ModbusSMA interface. The connection to the modbus interface is handled here. * * The following state machine illustrates the state changes of this class: * * \dot * digraph ModbusAPI_State { * rankdir=LR; * size="8,5"; * * node [shape = point]; qi; * * node [shape = circle, label="CFG"] cfg; * node [shape = circle, label="CON"] con; * node [shape = circle, label="INI"] init; * node [shape = circle, label="ERR"] err; * * qi -> cfg; * cfg -> con [label="connect()"]; * con -> init [label="initialize()"]; * cfg -> init [label="setup()"]; * con -> cfg [label="reset()"]; * init -> cfg [label="reset()"]; * err -> cfg [label="reset()"]; * cfg -> cfg [label="reset()"]; * } * \enddot */ class ModbusAPI { private: std::unique_ptr<MBConnectionBase> mConn = nullptr; std::shared_ptr<DataBase> mDB = nullptr; std::shared_ptr<RegisterContainer> mRegisters = nullptr; std::string mInverterType = ""; uint32_t mInverterTypeID = 0; State mState = State::CONFIGURE; public: ModbusAPI() = delete; ModbusAPI(std::string _ip, uint32_t _port, std::shared_ptr<DataBase> _db = nullptr); ModbusAPI(std::string _node, std::string _service, std::shared_ptr<DataBase> _db = nullptr); ModbusAPI(std::string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit, std::shared_ptr<DataBase> _db = nullptr); ModbusAPI(std::string _ip, uint32_t _port, std::string _dbPath); ModbusAPI(std::string _node, std::string _service, std::string _dbPath); ModbusAPI(std::string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit, std::string _dbPath); virtual ~ModbusAPI(); ModbusAPI(ModbusAPI const &) = delete; void operator=(ModbusAPI const &) = delete; ErrorCode connect(); ErrorCode initialize(); ErrorCode setup(); void reset(); ErrorCode updateRegisters(std::vector<uint16_t> _regList, size_t *_numUpdated = nullptr); ErrorCode updateRegisters(std::vector<Register> _regList, size_t *_numUpdated = nullptr); ErrorCode setDataBase(std::shared_ptr<DataBase> _db); ErrorCode setDataBase(std::string _dbPath); ErrorCode setConnectionTCP_IP(std::string _ip, uint32_t _port); ErrorCode setConnectionTCP_IP_PI(std::string _node, std::string _service); ErrorCode setConnectionRTU(std::string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit); inline State getState() const { return mState; } //!< Returns the current state. inline std::shared_ptr<DataBase> getDataBase() { return mDB; } //!< Returns the used DataBase. inline std::shared_ptr<RegisterContainer> getRegisters() const { return mRegisters; } //!< Returns the registers. inline std::string inverterType() const { return mInverterType; } //!< Returns the inverter type. inline uint32_t inverterTypeID() const { return mInverterTypeID; } //!< Returns the inverter type (ID). }; } // namespace modbusSMA
34.474026
119
0.666227
mensinda
cd52a00ff1fd417431d11df6686e97b729ad523a
2,042
cc
C++
graph/mst-kruskal.cc
deyuan/coding-practice
82bdf719397507601e582ab6d5693e4e50e96a3a
[ "MIT" ]
null
null
null
graph/mst-kruskal.cc
deyuan/coding-practice
82bdf719397507601e582ab6d5693e4e50e96a3a
[ "MIT" ]
null
null
null
graph/mst-kruskal.cc
deyuan/coding-practice
82bdf719397507601e582ab6d5693e4e50e96a3a
[ "MIT" ]
null
null
null
// Minimum Spanning Tree, Kruskal Algorithm // Copyright (c) 2021 Deyuan Guo <guodeyuan@gmail.com>. All rights reserved. #include <iostream> #include <vector> #include "graph_util.h" class UnionFind { public: UnionFind(int n) : root(n), rank(n) { for (int i = 0; i < n; i++) { root[i] = i; } } int find(int x) { if (root[x] == x) { return root[x]; } return root[x] = find(root[x]); } void unionSet(int x, int y) { int rootX = root[x]; int rootY = root[y]; if (rootX != rootY) { int rankX = rank[rootX]; int rankY = rank[rootY]; if (rankX < rankY) { root[rootX] = rootY; } else if (rankX > rankY) { root[rootY] = rootX; } else { root[rootY] = rootX; rank[rootX] += 1; } } } bool isConnected(int x, int y) { return find(x) == find(y); } private: std::vector<int> root; std::vector<int> rank; }; int kruskal(int n, const std::vector<std::vector<int>> &edges, std::vector<std::vector<int>> &mst) { // sort all edges by cost std::vector<std::tuple<int, int, int>> sortedEdges; for (auto& edge : edges) { int u = edge[0]; int v = edge[1]; int c = edge[2]; sortedEdges.push_back(std::make_tuple(c, u, v)); } sort(sortedEdges.begin(), sortedEdges.end()); // build MST with union-find UnionFind uf(n); int totalCost = 0; for (auto& edge : sortedEdges) { int u = std::get<1>(edge); int v = std::get<2>(edge); int c = std::get<0>(edge); if (!uf.isConnected(u, v)) { totalCost += c; uf.unionSet(u, v); mst.push_back({u, v}); } } return totalCost; } int main() { // read in graph int n = 0; std::vector<std::vector<int>> edges; ReadWeightedEdgeListFromStdIn(n, edges); // test kruskal std::vector<std::vector<int>> mst; int cost = kruskal(n, edges, mst); std::cout << "MST cost (Kruskal): " << cost << std::endl; for (auto& edge : mst) { std::cout << edge[0] << " " << edge[1] << std::endl; } }
22.195652
76
0.554358
deyuan
cd5ef5628c996ec0cae3f8d242ac50f518c663a4
606
cpp
C++
t/tests.cpp
chickchirik/randcrypt
b216d3dc70ff432a8c1d65945a414e00ada4f7bf
[ "MIT" ]
1
2020-05-08T12:55:58.000Z
2020-05-08T12:55:58.000Z
t/tests.cpp
chickchirik/randcrypt
b216d3dc70ff432a8c1d65945a414e00ada4f7bf
[ "MIT" ]
null
null
null
t/tests.cpp
chickchirik/randcrypt
b216d3dc70ff432a8c1d65945a414e00ada4f7bf
[ "MIT" ]
null
null
null
/* tests.cpp Created by <chickchirik> on 08/10/2019. DESCRIPTION: tests sub-project based on Catch2 testing framework that runs tests on core modules. In order to run tests - just build this project and execute t. In order to add tests - create new cpp file, include Catch2 and fill it with tests. Then add it as executable to this project's CMakeLists. Do NOT change this (tests.cpp) file, because it will lead to recompilation of entire Catch2 framework. */ /* Catch2 initialisation */ #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp"
24.24
46
0.69637
chickchirik
cd62dd60e4583da7c78b8913d5d40913adcf642a
2,424
cpp
C++
src/1_digital/cclight/exe_flag_gen.cpp
gtaifu/CACTUS
a05f47423ac37b14989ec38c525741ec597b4826
[ "Apache-2.0" ]
8
2020-01-04T06:40:13.000Z
2020-12-04T19:29:02.000Z
src/1_digital/cclight/exe_flag_gen.cpp
gtaifu/CACTUS
a05f47423ac37b14989ec38c525741ec597b4826
[ "Apache-2.0" ]
null
null
null
src/1_digital/cclight/exe_flag_gen.cpp
gtaifu/CACTUS
a05f47423ac37b14989ec38c525741ec597b4826
[ "Apache-2.0" ]
1
2021-07-05T02:14:05.000Z
2021-07-05T02:14:05.000Z
#include "exe_flag_gen.h" #include <vector> namespace cactus { Fce_logic::Fce_logic(const sc_core::sc_module_name& n) : sc_core::sc_module(n) { msmt_res_his.init(NUM_HIS_MSMT_RES); SC_CTHREAD(log_msmt_his, clock); SC_CTHREAD(gen_exe_flag, clock); } void Fce_logic::log_msmt_his() { std::vector<sc_uint<1>> i_msmt_res_his; i_msmt_res_his.resize(msmt_res_his.size()); while (true) { wait(); if (reset.read()) { for (size_t i = 0; i < msmt_res_his.size(); ++i) { msmt_res_his[i].write(0); i_msmt_res_his[i] = 0; } } else if (QM2MRF_qubit_ena.read()) { // shift the value i_msmt_res_his[0] = QM2MRF_qubit_data.read(); for (size_t i = 0; i < msmt_res_his.size() - 1; ++i) { i_msmt_res_his[i + 1] = msmt_res_his[i].read(); } // update the value for (size_t i = 0; i < msmt_res_his.size(); ++i) { msmt_res_his[i].write(i_msmt_res_his[i]); } } } } void Fce_logic::gen_exe_flag() { sc_uint<NUM_EXE_FLAGS> exe_flag = 0; while (true) { wait(); exe_flag[0] = 1; exe_flag[1] = msmt_res_his[0].read(); exe_flag[2] = ~msmt_res_his[0].read(); exe_flag[3] = msmt_res_his[0].read() ^ msmt_res_his[1].read(); out_exe_flag.write(exe_flag); } } void Exe_flag_gen::config() { Global_config& global_config = Global_config::get_instance(); num_qubits = global_config.num_qubits; } Exe_flag_gen::Exe_flag_gen(const sc_core::sc_module_name& n) : sc_core::sc_module(n) , vec_fce_logic("fce_logic", Global_config::get_instance().num_qubits, [&](const char* nm, size_t i) { return new Fce_logic(nm); }) { config(); QM2MRF_qubit_data.init(num_qubits); QM2MRF_qubit_ena.init(num_qubits); exe_flag_per_qubit.init(num_qubits); for (size_t i = 0; i < vec_fce_logic.size(); i++) { vec_fce_logic[i].clock(clock); vec_fce_logic[i].reset(reset); } sc_assemble_vector(vec_fce_logic, &Fce_logic::QM2MRF_qubit_data).bind(QM2MRF_qubit_data); sc_assemble_vector(vec_fce_logic, &Fce_logic::QM2MRF_qubit_ena).bind(QM2MRF_qubit_ena); sc_assemble_vector(vec_fce_logic, &Fce_logic::out_exe_flag).bind(exe_flag_per_qubit); } } // namespace cactus
27.545455
93
0.608911
gtaifu
cd6632a23b49abd05da65718cdd28b6192597a9d
797
hpp
C++
vp/src/platform/redv/i2c/i2cclient.hpp
U2654/riscv-vp
2ecb20927d72bf8431c7b436ddbe90d634d32c64
[ "MIT" ]
null
null
null
vp/src/platform/redv/i2c/i2cclient.hpp
U2654/riscv-vp
2ecb20927d72bf8431c7b436ddbe90d634d32c64
[ "MIT" ]
null
null
null
vp/src/platform/redv/i2c/i2cclient.hpp
U2654/riscv-vp
2ecb20927d72bf8431c7b436ddbe90d634d32c64
[ "MIT" ]
1
2021-11-04T14:18:06.000Z
2021-11-04T14:18:06.000Z
#ifndef I2C_CLIENT_H #define I2C_CLIENT_H #define I2C_CMD_STA 7 #define I2C_CMD_STO 6 #define I2C_CMD_ACK 3 #define I2C_STAT_RXACK 7 #define I2C_STAT_BUSY 6 #define I2C_STAT_ARLO 5 #define I2C_STAT_TIP 1 #define I2C_STAT_IF 0 class I2CClient { public: enum State { IDLE, ADDRESS, REGISTER, READ, WRITE }; I2CClient(const uint8_t f_id) : m_id(f_id) { } virtual ~I2CClient() { } // start processing of i2c transmissions bool run(); protected: // required for specific i2c handling virtual uint8_t readRegister(uint8_t f_reg) = 0; virtual void writeRegister(uint8_t f_reg, uint8_t f_val) = 0; private: const uint8_t m_id; State m_state = IDLE; uint32_t m_regPointer = 0x0; }; #endif
16.265306
65
0.662484
U2654
cd6d8e155d23c304eac4357f682ac51845b1b14e
1,498
cpp
C++
c++/leetcode/0065-Valid_Number-H.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0065-Valid_Number-H.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0065-Valid_Number-H.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 65 Valid Number // https://leetcode.com/problems/valid-number // version: 1; create time: 2020-02-06 21:40:48; class Solution { public: bool isNumber(string s) { const int n = s.size(); int i = 0, j = n - 1; while (i < n && s[i] == ' ') ++i; while (j >= 0 && s[j] == ' ') --j; bool sign_set = false; bool int_num_set = false; bool dec_set = false; bool dec_num_set = false; bool exp_set = false; bool exp_num_set = false; while (i <= j) { if (s[i] == '+' || s[i] == '-') { if (sign_set) return false; sign_set = true; } else if (s[i] == '.') { if (dec_set) return false; dec_set = true; sign_set = true; } else if (s[i] == 'e') { if (!int_num_set && !dec_num_set || exp_set) return false; exp_set = true; sign_set = false; dec_set = true; } else if (isdigit(s[i])) { if (exp_set) { exp_num_set = true; } else if (dec_set) { dec_num_set = true; } else { int_num_set = true; } sign_set = true; } else { return false; } ++i; } return !(!int_num_set && !dec_num_set || exp_set && !exp_num_set); } };
29.96
74
0.408545
levendlee
cd6eea94294b20e4d6c5b8fbe78f139389e3366a
8,161
cpp
C++
build/src/DistributedEnergyResource.cpp
Tylores/DCS
2fc852b4a044d371795f1ddc63e0cb1b0cbd303d
[ "Apache-2.0" ]
null
null
null
build/src/DistributedEnergyResource.cpp
Tylores/DCS
2fc852b4a044d371795f1ddc63e0cb1b0cbd303d
[ "Apache-2.0" ]
null
null
null
build/src/DistributedEnergyResource.cpp
Tylores/DCS
2fc852b4a044d371795f1ddc63e0cb1b0cbd303d
[ "Apache-2.0" ]
null
null
null
#include "include/DistributedEnergyResource.hpp" DistributedEnergyResource::DistributedEnergyResource ( std::map <std::string, std::string> init) : rated_export_power_(stoul(init["RatedExportPower"])), rated_export_energy_(stoul(init["RatedExportEnergy"])), export_ramp_(stoul(init["ExportRamp"])), rated_import_power_(stoul(init["RatedImportPower"])), rated_import_energy_(stoul(init["RatedImportEnergy"])), import_ramp_(stoul(init["ImportRamp"])), idle_losses_(stoul(init["IdleLosses"])), export_power_(stoul(init["ExportPower"])), export_energy_(stoul(init["ExportEnergy"])), import_power_(stoul(init["ImportPower"])), import_energy_(stoul(init["ImportEnergy"])), export_watts_(0), import_watts_(0), delta_time_(0) { //ctor } DistributedEnergyResource::~DistributedEnergyResource () { //dtor } // Set Export Watts // - set the export control property used in the control loop void DistributedEnergyResource::SetExportWatts (unsigned int power) { import_watts_ = 0; import_power_ = 0; if (power > rated_export_power_) { power = rated_export_power_; } export_watts_ = power; } // end Set Export Watts // Set Rated Export Power // - set the watt value available to export to the grid void DistributedEnergyResource::SetRatedExportPower (unsigned int power) { rated_export_power_ = power; } // end Rated Export Power // Set Rated Export Energy // - set the watt-hour value available to export to the grid void DistributedEnergyResource::SetRatedExportEnergy (unsigned int energy) { rated_export_energy_ = energy; } // end Set Export Energy // Set Export Ramp // - set the watt per second value available to export to the grid void DistributedEnergyResource::SetExportRamp (unsigned int ramp) { export_ramp_ = ramp; } // end Set Export Ramp // Set Import Watts // - set the import control property used in the control loop void DistributedEnergyResource::SetImportWatts (unsigned int power) { export_watts_ = 0; export_power_ = 0; if (power > rated_import_power_) { power = rated_import_power_; } import_watts_ = power; } // end Set Import Watts // Set Rated Import Power // - set the watt value available to import from the grid void DistributedEnergyResource::SetRatedImportPower (unsigned int power) { rated_import_power_ = power; } // end Set Rated Import Power // Set Rated Import Energy // - set the watt-hour value available to import from the grid void DistributedEnergyResource::SetRatedImportEnergy (unsigned int energy) { rated_import_energy_ = energy; } // end Set Import Energy // Set Import Ramp // - set the watt per second value available to import from the grid void DistributedEnergyResource::SetImportRamp (unsigned int ramp) { import_ramp_ = ramp; } // end Set Import Ramp // Set Idle Losses // - set the watt-hours per hour loss when idle void DistributedEnergyResource::SetIdleLosses (unsigned int losses) { idle_losses_ = losses; } // end Set Idle Losses // Get Rated Export Power // - get the watt value available to export to the grid unsigned int DistributedEnergyResource::GetRatedExportPower () { return rated_export_power_; } // end Get Rated Export Power // Get Export Power // - get the watt value available to export to the grid unsigned int DistributedEnergyResource::GetExportPower () { unsigned int power = export_power_; return power; } // end Get Export Power // Get Rated Export Energy // - get the watt value available to import from the grid unsigned int DistributedEnergyResource::GetRatedExportEnergy () { return rated_export_energy_; } // end Rated Export energy // Get Export Energy // - get the watt-hour value available to export to the grid unsigned int DistributedEnergyResource::GetExportEnergy () { unsigned int energy = export_energy_; return energy; } // end Get Export Energy // Get Export Ramp // - get the watt per second value available to export to the grid unsigned int DistributedEnergyResource::GetExportRamp () { return export_ramp_; } // end Get Export Ramp // Get Rated Import Power // - get the watt value available to import from the grid unsigned int DistributedEnergyResource::GetRatedImportPower () { return rated_import_power_; } // end Rated Import Power // Get Import Power // - get the watt value available to import from the grid unsigned int DistributedEnergyResource::GetImportPower () { unsigned int power = import_power_; return power; } // end Get Import Power // Get Rated Import Energy // - get the watt value available to import from the grid unsigned int DistributedEnergyResource::GetRatedImportEnergy () { return rated_import_energy_; } // end Rated Import energy // Get Import Energy // - get the watt-hour value available to import from the grid unsigned int DistributedEnergyResource::GetImportEnergy () { unsigned int energy = import_energy_; return energy; } // end Get Import Energy // Get Import Ramp // - get the watt per second value available to import from the grid unsigned int DistributedEnergyResource::GetImportRamp () { return import_ramp_; } // end Get Import Ramp // Get Idle Losses // - get the watt-hours per hour loss when idle unsigned int DistributedEnergyResource::GetIdleLosses () { return idle_losses_; } // end Get Idle Losses // Import Power // - called by control loop if import power is set // - assume loss is factored into import power void DistributedEnergyResource::ImportPower () { float seconds = delta_time_ / 1000; float watts = import_ramp_ * seconds; // regulate import power if (import_power_ + watts < import_watts_) { import_power_ += watts; } else { import_power_ = import_watts_; } // regulate energy float hours = seconds / (60*60); if (import_energy_ - import_power_ > 0) { // area under the linear function import_energy_ -= (import_power_*hours + watts*hours/2); export_energy_ = rated_export_energy_ - import_energy_; } else { import_power_ = 0; import_energy_ = 0; export_energy_ = rated_export_energy_; } } // end Import Power // Export Power // - called by control loop if export power is set // - assume loss is factored into export power void DistributedEnergyResource::ExportPower () { float seconds = delta_time_ / 1000; float watts = export_ramp_ * seconds; // regulate import power if (export_power_ + watts < export_watts_) { export_power_ += watts; } else { export_power_ = export_watts_; } // regulate energy float hours = seconds / (60*60); if (export_energy_ - export_power_ > 0) { // area under the linear function export_energy_ -= (export_power_*hours + watts*hours/2); import_energy_ = rated_import_energy_ - export_energy_; } else { export_power_ = 0; export_energy_ = 0; import_energy_ = rated_import_energy_; } } // end Export Power // Idle Loss // - update energy available based on energy lost void DistributedEnergyResource::IdleLoss () { float seconds = delta_time_ / 1000; float hours = seconds / (60*60); float energy_loss = idle_losses_ * hours; if (import_energy_ + energy_loss < rated_import_energy_) { import_energy_ += energy_loss; } if (export_energy_ - energy_loss > 0) { export_energy_ -= energy_loss; } } // end Idle Loss // Control // - check state of import / export power properties from main loop on a timer void DistributedEnergyResource::Loop (float delta_time) { delta_time_ = delta_time; if (import_watts_ > 0) { DistributedEnergyResource::ImportPower (); } else if (export_watts_ > 0) { DistributedEnergyResource::ExportPower (); } else { IdleLoss (); } } // end Control
33.72314
79
0.689621
Tylores
cd6f34c4e79b5a101c8b875154fac6e32ad91f24
2,008
cc
C++
ACAP_linux/3rd/CoMISo/Base/Test/ChecksumCondition.cc
shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
216
2018-09-09T11:53:56.000Z
2022-03-19T13:41:35.000Z
ACAP_linux/3rd/CoMISo/Base/Test/ChecksumCondition.cc
gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
13
2018-10-23T08:29:09.000Z
2021-09-08T06:45:34.000Z
ACAP_linux/3rd/CoMISo/Base/Test/ChecksumCondition.cc
shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer
8c9afe017769f9554706bcd267b6861c4c144999
[ "MIT" ]
41
2018-09-13T08:50:41.000Z
2022-02-23T00:33:54.000Z
// (C) Copyright 2016 by Autodesk, Inc. #if defined(TEST_ON) #include "ChecksumCondition.hh" #include "TestResult.hh" #include "Base/Code/CodeLink.hh" #include <algorithm> namespace Test { namespace Checksum { const char* const CHECKED_TAG = " checked "; const char* const TOTAL_TAG = "total#: "; const char* const FAILED_TAG = "failed#: "; void Condition::record(const char* const _cndt, const Base::CodeLink& _lnk, const bool _rslt) { Base::OStringStream strm; strm << _cndt << CHECKED_TAG << _lnk; add(_rslt ? Result::OK : Result::ERROR, strm.str); ++nmbr_; fail_nmbr_ += int(!_rslt); } void Condition::record_number() { if (nmbr_ == 0) return; { Base::OStringStream strm; strm << TOTAL_TAG << nmbr_; add(Result::OK, strm.str); } { Base::OStringStream strm; strm << FAILED_TAG << fail_nmbr_; add(fail_nmbr_ == 0 ? Result::OK : Result::ERROR, strm.str); } } Difference Condition::compare_data(const String& _old, const String& _new) const { // exclude the code link from the comparison auto old_tmp = _old; auto new_tmp = _new; const auto old_link_pos = old_tmp.rfind(CHECKED_TAG); const auto new_link_pos = new_tmp.rfind(CHECKED_TAG); if (old_link_pos != String::npos && new_link_pos != String::npos) { old_tmp.resize(old_link_pos); new_tmp.resize(new_link_pos); } // exclude the Condition prefix, e.g., number from the comparison //auto old_prfx_pos = old_tmp.find(PREFIX_MARK); //auto new_prfx_pos = new_tmp.find(PREFIX_MARK); //if (old_prfx_pos != String::npos && new_prfx_pos != String::npos) //{// remove the prefix and add white-spaces instead // String prfx(new_prfx_pos, ' '); // align wrt the new result // old_tmp = prfx + String(old_tmp.begin() + old_prfx_pos, old_tmp.end()); // new_tmp = prfx + String(new_tmp.begin() + new_prfx_pos, new_tmp.end()); //} return Object::compare_data(old_tmp, new_tmp); } Condition condition; }//Checksum }//namespace Test #endif//defined(TEST_ON)
25.74359
80
0.683267
shubhMaheshwari
cd70c597028af6688e991c5f834f1ef966dfddf4
2,988
cpp
C++
ion/ServerSettingsPage.cpp
dtylman/ion
219a84761ff9213a53c79d3447b03ae620711024
[ "MIT" ]
2
2018-01-15T12:22:31.000Z
2018-03-16T12:43:32.000Z
ion/ServerSettingsPage.cpp
dtylman/ion
219a84761ff9213a53c79d3447b03ae620711024
[ "MIT" ]
null
null
null
ion/ServerSettingsPage.cpp
dtylman/ion
219a84761ff9213a53c79d3447b03ae620711024
[ "MIT" ]
null
null
null
/* * File: ServerSettingsPage.cpp * Author: danny * * Created on February 24, 2015, 4:15 PM */ #include "ServerSettingsPage.h" #include "WebMenu.h" #include "WebForm.h" #include "Main.h" #include <Poco/Util/LayeredConfiguration.h> #include <Poco/Util/Application.h> const std::string ServerSettingsPage::Link("settings.bin"); const std::string ServerSettingsPage::Title("Server Settings"); ServerSettingsPage::ServerSettingsPage() { } ServerSettingsPage::~ServerSettingsPage() { } std::string ServerSettingsPage::title() const { return Title; } std::string ServerSettingsPage::subtitle() const { return "General configuration settings:"; } bool ServerSettingsPage::handleForm(Poco::Net::HTMLForm& form, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { updateSettings(form, "offline", "ion.offline-interval"); updateSettings(form, "traffic", "ion.traffic-interval"); updateSettings(form, "eventsage", "ion.eventsage"); updateSettings(form, "trafficsage", "ion.trafficage"); if (form.has("linklocal")) { Poco::Util::Application::instance().config().setBool("ion.ignoreLinkLocal", true); } else { Poco::Util::Application::instance().config().setBool("ion.ignoreLinkLocal", false); } Main& main = dynamic_cast<Main&> (Poco::Util::Application::instance()); main.saveConfig(); return false; } bool ServerSettingsPage::renderFormStart(std::ostream& output) { output << Poco::format("<form method='POST' action='%s' >", Link); return true; } void ServerSettingsPage::renderButtons(std::ostream& output) { output << "<input class='btn btn-success' type='submit' value='Save'> "; WebMenu::renderHomeButton(output, "Close"); } void ServerSettingsPage::renderPanelBody(std::ostream& output, Poco::Net::HTTPServerRequest& request) { Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config(); WebForm wf(output); wf.startRow(); wf.renderInput("offline", "Offline interval (minutes):", "minutes", config.getString("ion.offline-interval"), true, "number", 3); wf.renderInput("traffic", "Traffic check interval (minutes):", "minutes", config.getString("ion.traffic-interval"), true, "number", 3); wf.endRow(); wf.startRow(); wf.renderInput("eventsage", "Events age (days):", "days", config.getString("ion.eventsage"), true, "number", 3); wf.renderInput("trafficsage", "Traffic age (days):", "days", config.getString("ion.trafficage"), true, "number", 3); wf.endRow(); wf.startRow(); wf.renderChkbox("linklocal", "Ignore link local addresses:", config.getBool("ion.ignoreLinkLocal"), 3); wf.endRow(); } bool ServerSettingsPage::updateSettings(Poco::Net::HTMLForm& form, const std::string& name, const std::string& confKey) { if (form.has(name)) { Poco::Util::Application::instance().config().setString(confKey, form.get(name)); return true; } return false; }
32.478261
142
0.691098
dtylman
cd71b09fc5ca6ab9ac9795e6df6838a78d93b13f
1,730
cpp
C++
Drone.cpp
IrrationalKyo/ViconMAVLink
6a13eaa3722d5871c23f6bbda43fa068d23e0349
[ "MIT" ]
18
2017-12-07T23:40:29.000Z
2022-01-30T05:47:25.000Z
Drone.cpp
IrrationalKyo/ViconMAVLink
6a13eaa3722d5871c23f6bbda43fa068d23e0349
[ "MIT" ]
null
null
null
Drone.cpp
IrrationalKyo/ViconMAVLink
6a13eaa3722d5871c23f6bbda43fa068d23e0349
[ "MIT" ]
15
2017-12-08T16:56:04.000Z
2021-10-04T16:31:55.000Z
/*************************************************************************** * * * Copyright (C) 2017 by University of Illinois * * * * http://illinois.edu * * * ***************************************************************************/ /** * @file Drone.cpp * * A Drone object stores raw measurements fetched from Vicon. * * @author Bo Liu <boliu1@illinois.edu> * */ #include "Drone.h" Drone::Drone() { } Drone::Drone(QString droneName) { name = droneName; } Drone::~Drone() { // nothing to do } Drone::Drone(QString droneName, double x, double y, double z, double q_0, double q_1, double q_2, double q_3) { name = droneName; pos.x = x; pos.y = y; pos.z = z; pos.q[0] = q_0; pos.q[1] = q_1; pos.q[2] = q_2; pos.q[3] = q_3; } QString Drone::getName() const { return name; } void Drone::setName(const QString &value) { name = value; } mavlink_att_pos_mocap_t Drone::getPos(long long& ret_frame) const { ret_frame = frame; return pos; } mavlink_att_pos_mocap_t Drone::getPos() const { return pos; } void Drone::setPos(const mavlink_att_pos_mocap_t &value) { pos = value; } void Drone::reset() { name = ""; pos.x = 0; pos.y = 0; pos.z = 0; pos.q[0] = 1; pos.q[1] = 1; pos.q[2] = 1; pos.q[3] = 1; frame = 0; } long long Drone::getTime() const { return frame; } void Drone::setTime(long long value) { frame = value; }
18.404255
109
0.44104
IrrationalKyo
cd72d74e259b63d263f890f1220576b9a8819a61
5,700
cpp
C++
3rdparty/jsonrpc-cpp-0.4/src/jsonrpc_tcpserver.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
3rdparty/jsonrpc-cpp-0.4/src/jsonrpc_tcpserver.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
3rdparty/jsonrpc-cpp-0.4/src/jsonrpc_tcpserver.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* * JsonRpc-Cpp - JSON-RPC implementation. * Copyright (C) 2008-2011 Sebastien Vincent <sebastien.vincent@cppextrem.com> * * 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/>. */ /** * \file jsonrpc_tcpserver.cpp * \brief JSON-RPC TCP server. * \author Sebastien Vincent */ #include <stdexcept> #include "jsonrpc_tcpserver.h" #include "netstring.h" #include <cstring> #include <cerrno> namespace Json { namespace Rpc { TcpServer::TcpServer(const std::string& address, uint16_t port) : Server(address, port) { m_protocol = networking::TCP; } TcpServer::~TcpServer() { if(m_sock != -1) { Close(); } } ssize_t TcpServer::Send(int fd, const std::string& data) { std::string rep = data; /* encoding if any */ if(GetEncapsulatedFormat() == Json::Rpc::NETSTRING) { rep = netstring::encode(rep); } return ::send(fd, rep.c_str(), rep.length(), 0); } bool TcpServer::Recv(int fd) { Json::Value response; ssize_t nb = -1; char buf[1500]; nb = recv(fd, buf, sizeof(buf), 0); /* give the message to JsonHandler */ if(nb > 0) { std::string msg = std::string(buf, nb); if(GetEncapsulatedFormat() == Json::Rpc::NETSTRING) { try { msg = netstring::decode(msg); } catch(const netstring::NetstringException& e) { /* error parsing Netstring */ std::cerr << e.what() << std::endl; return false; } } m_jsonHandler.Process(msg, response); /* in case of notification message received, the response could be Json::Value::null */ if(response != Json::Value::null) { std::string rep = m_jsonHandler.GetString(response); /* encoding */ if(GetEncapsulatedFormat() == Json::Rpc::NETSTRING) { rep = netstring::encode(rep); } int bytesToSend = rep.length(); const char* ptrBuffer = rep.c_str(); do { int retVal = send(fd, ptrBuffer, bytesToSend, 0); if(retVal == -1) { /* error */ std::cerr << "Error while sending data: " << strerror(errno) << std::endl; return false; } bytesToSend -= retVal; ptrBuffer += retVal; }while(bytesToSend > 0); } return true; } else { m_purge.push_back(fd); return false; } } void TcpServer::WaitMessage(uint32_t ms) { fd_set fdsr; struct timeval tv; int max_sock = m_sock; tv.tv_sec = ms / 1000; tv.tv_usec = (ms % 1000 ) / 1000; FD_ZERO(&fdsr); #ifdef _WIN32 /* on Windows, a socket is not an int but a SOCKET (unsigned int) */ FD_SET((SOCKET)m_sock, &fdsr); #else FD_SET(m_sock, &fdsr); #endif for(std::list<int>::iterator it = m_clients.begin() ; it != m_clients.end() ; it++) { #ifdef _WIN32 FD_SET((SOCKET)(*it), &fdsr); #else FD_SET((*it), &fdsr); #endif if((*it) > max_sock) { max_sock = (*it); } } max_sock++; if(select(max_sock, &fdsr, NULL, NULL, ms ? &tv : NULL) > 0) { if(FD_ISSET(m_sock, &fdsr)) { Accept(); } for(std::list<int>::iterator it = m_clients.begin() ; it != m_clients.end() ; it++) { if(FD_ISSET((*it), &fdsr)) { Recv((*it)); } } /* remove disconnect socket descriptor */ for(std::list<int>::iterator it = m_purge.begin() ; it != m_purge.end() ; it++) { m_clients.remove((*it)); } /* purge disconnected list */ m_purge.erase(m_purge.begin(), m_purge.end()); } else { /* error */ } } bool TcpServer::Listen() const { if(m_sock == -1) { return false; } if(listen(m_sock, 5) == -1) { return false; } return true; } bool TcpServer::Accept() { int client = -1; socklen_t addrlen = sizeof(struct sockaddr_storage); if(m_sock == -1) { return false; } client = accept(m_sock, 0, &addrlen); if(client == -1) { return false; } m_clients.push_back(client); return true; } void TcpServer::Close() { /* close all client sockets */ for(std::list<int>::iterator it = m_clients.begin() ; it != m_clients.end() ; it++) { ::close((*it)); } m_clients.erase(m_clients.begin(), m_clients.end()); /* listen socket should be closed in Server destructor */ } const std::list<int> TcpServer::GetClients() const { return m_clients; } } /* namespace Rpc */ } /* namespace Json */
22.529644
95
0.527368
wohaaitinciu
cd72dd25a2b8d31063d22e2eee0d06f59dec3e45
77
hh
C++
kernel/arch/rtc.hh
ErrorOnUsername/axiom
1455e10e8528cf272bea38c46bc05966a108215c
[ "MIT" ]
null
null
null
kernel/arch/rtc.hh
ErrorOnUsername/axiom
1455e10e8528cf272bea38c46bc05966a108215c
[ "MIT" ]
null
null
null
kernel/arch/rtc.hh
ErrorOnUsername/axiom
1455e10e8528cf272bea38c46bc05966a108215c
[ "MIT" ]
null
null
null
#pragma once namespace Kernel::RTC { void initialize_real_time_clock(); }
9.625
34
0.753247
ErrorOnUsername
cd75b6371618ec1e5d9cea82be8890060d0f2827
992
cpp
C++
src/sketchup/RubyUtils/mbRubyUtils.cpp
sonicth/SUMB_ShapeFitting
65f5debdbe6729d21543b532b97367bd99b54b73
[ "BSL-1.0" ]
1
2016-09-06T09:14:48.000Z
2016-09-06T09:14:48.000Z
src/sketchup/RubyUtils/mbRubyUtils.cpp
sonicth/SUMB_ShapeFitting
65f5debdbe6729d21543b532b97367bd99b54b73
[ "BSL-1.0" ]
null
null
null
src/sketchup/RubyUtils/mbRubyUtils.cpp
sonicth/SUMB_ShapeFitting
65f5debdbe6729d21543b532b97367bd99b54b73
[ "BSL-1.0" ]
null
null
null
/* * copyright 2016 mike vasiljevs (contact@michaelvasiljevs.com) * ShapeFitting SU plugin */ #include "mbRubyUtils.h" #include <boost/foreach.hpp> void getShapePts(VALUE shape, Pts_t& pts) { // convert to ruby DS auto iregion_num = RARRAY_LEN(shape); pts.reserve(iregion_num); for (int i = 0; i < iregion_num; ++i) { auto pt_v = rb_ary_entry(shape, i); auto x = NUM2DBL(rb_ary_entry(pt_v, 0)); auto y = NUM2DBL(rb_ary_entry(pt_v, 1)); Pts_t::value_type pt(x, y); pts.push_back(pt); } } VALUE setShapePts(Pts_t& pts) { // Ruby array to store the points to VALUE pts_ar = rb_ary_new2((long) pts.size()); int i = 0; BOOST_FOREACH(auto const &pt, pts) { // store coordiantes in the vector VALUE vecar = rb_ary_new2(2); rb_ary_store(vecar, 0, DBL2NUM(pt.x)); rb_ary_store(vecar, 1, DBL2NUM(pt.y)); // store current vector in the array of vectors rb_ary_store(pts_ar, i, vecar); ++i; } return pts_ar; }
21.565217
64
0.650202
sonicth
cd7a69fc9dfc2313564660106bf7d4047a1af35d
1,224
cpp
C++
src/Address.cpp
evenleo/leo
67e148e04eb7b3af9890f907f24fb4f63d8405b0
[ "MIT" ]
null
null
null
src/Address.cpp
evenleo/leo
67e148e04eb7b3af9890f907f24fb4f63d8405b0
[ "MIT" ]
null
null
null
src/Address.cpp
evenleo/leo
67e148e04eb7b3af9890f907f24fb4f63d8405b0
[ "MIT" ]
null
null
null
#include "Address.h" #include "Log.h" #include <arpa/inet.h> #include <string.h> #include <sstream> namespace leo { IpAddress::IpAddress(std::string ip, in_port_t port) { bzero(&addr_, sizeof(addr_)); addr_.sin_family = AF_INET; addr_.sin_port = htons(port); if (int rt = ::inet_pton(AF_INET, ip.c_str(), &addr_.sin_addr) <= 0) { if (rt == 0) { LOG_FATAL << "inet_pton: Not in presentation format"; } else { LOG_FATAL << "inet_pton: " << strerror(errno); } } } IpAddress::IpAddress(in_port_t port) { bzero(&addr_, sizeof(addr_)); addr_.sin_family = AF_INET; addr_.sin_port = htons(port); addr_.sin_addr.s_addr = ::htonl(INADDR_ANY); } IpAddress::IpAddress(const struct sockaddr_in& addr) : addr_(addr) { } std::string IpAddress::toString() const { std::stringstream ss; char buf[20]; const char* ip = ::inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof(buf)); if (ip) { ss << ip; } else { ss << "invalid ip"; } ss << ":" << ntohs(addr_.sin_port); return ss.str(); } const struct sockaddr* IpAddress::getSockAddr() const { return reinterpret_cast<const struct sockaddr*>(&addr_); } struct sockaddr* IpAddress::getSockAddr() { return reinterpret_cast<struct sockaddr*>(&addr_); } }
21.473684
74
0.67402
evenleo
cd7c00d67bfbd5f4ec766b70046d9dc0cede3935
3,694
cpp
C++
src/Flownodes/CFlowCUITriggerEvent.cpp
CoherentLabs/CoherentUI_CryEngine3
44b30e41e37a92ee16edbc6b738f996cfb3bd67e
[ "BSD-2-Clause" ]
12
2015-04-04T17:21:06.000Z
2021-05-11T16:03:36.000Z
src/Flownodes/CFlowCUITriggerEvent.cpp
CoherentLabs/CoherentUI_CryEngine3
44b30e41e37a92ee16edbc6b738f996cfb3bd67e
[ "BSD-2-Clause" ]
1
2015-06-23T21:24:38.000Z
2015-06-25T03:42:39.000Z
src/Flownodes/CFlowCUITriggerEvent.cpp
CoherentLabs/CoherentUI_CryEngine3
44b30e41e37a92ee16edbc6b738f996cfb3bd67e
[ "BSD-2-Clause" ]
5
2015-02-11T22:43:43.000Z
2017-12-03T00:38:46.000Z
#include <StdAfx.h> #include <Nodes/G2FlowBaseNode.h> #include <CPluginCoherentUI.h> #include <Coherent/UI/View.h> #include "CoherentViewListener.h" #include "CoherentUISystem.h" namespace CoherentUIPlugin { class CFlowCUITriggerEvent : public CFlowBaseNode<eNCT_Instanced> { private: enum EInputPorts { EIP_ACTIVATE = 0, EIP_VIEWID, EIP_EVENT, EIP_ARG1, }; public: CFlowCUITriggerEvent( SActivationInfo* pActInfo ) { } virtual ~CFlowCUITriggerEvent() { } virtual IFlowNodePtr Clone( SActivationInfo* pActInfo ) { return new CFlowCUITriggerEvent( pActInfo ); } virtual void GetMemoryUsage( ICrySizer* s ) const { s->Add( *this ); } void Serialize( SActivationInfo* pActInfo, TSerialize ser ) { } virtual void GetConfiguration( SFlowNodeConfig& config ) { static const SInputPortConfig inputs[] = { InputPortConfig_Void( "Activate", _HELP( "Activate View" ) ), InputPortConfig<int>( "ViewID", 0, _HELP( "View ID" ) ), InputPortConfig<string>( "Event", "", _HELP( "Event Name" ) ), InputPortConfig<bool>( "Arg1", _HELP( "Argument 1 (optional: boolean)" ) ), InputPortConfig_AnyType( NULL ), }; config.pInputPorts = inputs; config.pOutputPorts = NULL;//output config.sDescription = _HELP( PLUGIN_CONSOLE_PREFIX "CoherentUI event trigger (1 argument)" ); //config.nFlags |= EFLN_TARGET_ENTITY; config.SetCategory( EFLN_APPROVED ); } virtual void ProcessEvent( EFlowEvent evt, SActivationInfo* pActInfo ) { switch ( evt ) { case eFE_Suspend: break; case eFE_Resume: break; case eFE_Initialize: break; case eFE_Activate: { if ( IsPortActive( pActInfo, EIP_ACTIVATE ) ) { int viewId = GetPortInt( pActInfo, EIP_VIEWID ); CCoherentViewListener* pViewListener = gCoherentUISystem->GetViewListener( viewId ); if ( pViewListener && pViewListener->IsReadyForBindings() ) { Coherent::UI::View* pView = pViewListener->GetView(); if ( pView ) { std::string sEvent = GetPortString( pActInfo, EIP_EVENT ); bool bArg1 = GetPortBool( pActInfo, EIP_ARG1 ); pView->TriggerEvent(sEvent.c_str(), bArg1); } } } } break; case eFE_Update: break; } } }; } REGISTER_FLOW_NODE_EX( "CoherentUI_Plugin:TriggerEvent", CoherentUIPlugin::CFlowCUITriggerEvent, CFlowCUITriggerEvent );
35.864078
120
0.442339
CoherentLabs
cd7c046a95f658b316d02b79b95f521be9824890
1,027
cpp
C++
A_problems/GoofNumber.cpp
tarek99samy/code_forces_problems
a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e
[ "MIT" ]
null
null
null
A_problems/GoofNumber.cpp
tarek99samy/code_forces_problems
a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e
[ "MIT" ]
null
null
null
A_problems/GoofNumber.cpp
tarek99samy/code_forces_problems
a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; //#include<windows.h> #include<cstring> #include<string> #include<algorithm> #include<stack> #include<vector> #include<cmath> #include<list> #include<cstdlib> long long GCD(long long A, long long B) { if (B > A) { swap(A, B); } long long gcd = A % B; if (gcd == 0) { return B; } long long next; while (gcd!=0) { next = gcd; A=B; B = gcd; gcd = A % B; } return next; } int main() { int size, k; cin >> size >> k; vector <string >v1(size); int count=0; bool exit = false ; for (int i = 0; i < size; i++) { cin >> v1[i]; } int * arr = new int[k+1]; for (int i = 0; i < k + 1; i++) { arr[i] = i; } for (int i = 0; i < size; i++) { for (int j = 0; j < k+1; j++) { for (int m = 0; m < v1[i].size(); m++) { exit = false; if ((v1[i][m] - '0') == arr[j]) { exit = true; break; } } if (exit != true) break; } if (exit) count++; exit = false; } cout << count << endl; return 0; }
13.513158
42
0.497566
tarek99samy
cd7eed23799a026711a64cc5d2bb32a827b96c57
3,123
cpp
C++
opencl/test/unit_test/sku_info/sku_info_receiver_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/test/unit_test/sku_info/sku_info_receiver_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/test/unit_test/sku_info/sku_info_receiver_tests.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2018-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/sku_info/operations/windows/sku_info_receiver.h" #include "opencl/test/unit_test/sku_info/sku_info_base_reference.h" #include "gtest/gtest.h" using namespace NEO; inline bool operator==(const FeatureTable &lhs, const FeatureTable &rhs) { return lhs.ftrBcsInfo == rhs.ftrBcsInfo && lhs.packed == rhs.packed; } TEST(SkuInfoReceiverTest, givenAdapterInfoWhenReceivingThenUpdateFtrTable) { FeatureTable refFeatureTable = {}; FeatureTable requestedFeatureTable = {}; ADAPTER_INFO adapterInfo = {}; memset(&adapterInfo.SkuTable, ~0, sizeof(adapterInfo.SkuTable)); EXPECT_EQ(1lu, requestedFeatureTable.ftrBcsInfo.to_ulong()); SkuInfoReceiver::receiveFtrTableFromAdapterInfo(&requestedFeatureTable, &adapterInfo); SkuInfoBaseReference::fillReferenceFtrToReceive(refFeatureTable); EXPECT_EQ(1lu, requestedFeatureTable.ftrBcsInfo.to_ulong()); EXPECT_TRUE(refFeatureTable == requestedFeatureTable); refFeatureTable.flags.ftr3dMidBatchPreempt = false; requestedFeatureTable.flags.ftr3dMidBatchPreempt = true; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); } TEST(SkuInfoReceiverTest, givenFeatureTableWhenDifferentDataThenEqualityOperatorReturnsCorrectScore) { FeatureTable refFeatureTable = {}; FeatureTable requestedFeatureTable = {}; refFeatureTable.ftrBcsInfo = 1; requestedFeatureTable.ftrBcsInfo = 0; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); refFeatureTable.ftrBcsInfo = 0; requestedFeatureTable.ftrBcsInfo = 1; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); refFeatureTable.ftrBcsInfo = 1; requestedFeatureTable.ftrBcsInfo = 1; refFeatureTable.packed[0] = 1u; requestedFeatureTable.packed[0] = 0; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); refFeatureTable.packed[0] = 0; requestedFeatureTable.packed[0] = 1; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); refFeatureTable.packed[0] = 0; requestedFeatureTable.packed[0] = 0; refFeatureTable.packed[1] = 0; requestedFeatureTable.packed[1] = 1; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); refFeatureTable.packed[0] = 0; requestedFeatureTable.packed[0] = 0; refFeatureTable.packed[1] = 1; requestedFeatureTable.packed[1] = 0; EXPECT_FALSE(refFeatureTable == requestedFeatureTable); refFeatureTable.packed[1] = 1; requestedFeatureTable.packed[1] = 1; EXPECT_TRUE(refFeatureTable == requestedFeatureTable); } TEST(SkuInfoReceiverTest, givenAdapterInfoWhenReceivingThenUpdateWaTable) { WorkaroundTable refWaTable = {}; WorkaroundTable requestedWaTable = {}; ADAPTER_INFO adapterInfo = {}; memset(&adapterInfo.WaTable, ~0, sizeof(adapterInfo.WaTable)); SkuInfoReceiver::receiveWaTableFromAdapterInfo(&requestedWaTable, &adapterInfo); SkuInfoBaseReference::fillReferenceWaToReceive(refWaTable); EXPECT_TRUE(memcmp(&requestedWaTable, &refWaTable, sizeof(WorkaroundTable)) == 0); }
31.545455
102
0.759206
mattcarter2017
cd831dad499aa8163113b632a8bcc9f4649acd36
1,166
hpp
C++
src/krnl/hpp/gdt.hpp
maximsmol/nos
386b4166b3fd1701b734bfcd50ace1b9e1ea38ee
[ "MIT" ]
1
2019-04-29T05:10:52.000Z
2019-04-29T05:10:52.000Z
src/krnl/hpp/gdt.hpp
maximsmol/nos
386b4166b3fd1701b734bfcd50ace1b9e1ea38ee
[ "MIT" ]
null
null
null
src/krnl/hpp/gdt.hpp
maximsmol/nos
386b4166b3fd1701b734bfcd50ace1b9e1ea38ee
[ "MIT" ]
1
2021-12-06T23:49:27.000Z
2021-12-06T23:49:27.000Z
#pragma once #include "util/gdt.hpp" namespace gdt { constexpr uint64_t gdt[] = { 0, // null-selector is invalid, no matter what the entry is, so set to an invalid value util::gdt::Entry( /*.base = */0, /*.limit = */0xffff'ffff, /*.ring = */0, /*.rw = */true, /*.size = */util::gdt::entry::Size::bit32, /*.type = */util::gdt::entry::Type::code, /*.code_flags = */util::gdt::entry::CodeFlags { /*.conforming = */false } ).bin(), util::gdt::Entry( /*.base = */0, /*.limit = */0xffff'ffff, /*.ring = */0, /*.rw = */true, /*.size = */util::gdt::entry::Size::bit32, /*.type = */util::gdt::entry::Type::data, /*.data_flags = */util::gdt::entry::DataFlags { /*.dir = */util::gdt::entry::Direction::up } ).bin() }; constexpr util::gdt::GDTR gdtr = { /*.gdt_size = */sizeof(gdt)-1, /*.gdt = */gdt }; constexpr unsigned int getSelector(const unsigned int n) { return sizeof(gdt[0])*n; } namespace selector { constexpr unsigned int code = getSelector(1); constexpr unsigned int data = getSelector(2); } }
25.911111
91
0.530875
maximsmol
cd84d8f21f88c36ad4fd4088940a84ada0f6adc2
2,268
cpp
C++
libs/ledger/tests/consensus/proof_of_work_tests.cpp
n-hutton/ledger-1
909a81c415a73c38fb3d7f486dfcf93d7f87adaf
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/ledger/tests/consensus/proof_of_work_tests.cpp
n-hutton/ledger-1
909a81c415a73c38fb3d7f486dfcf93d7f87adaf
[ "Apache-2.0" ]
null
null
null
libs/ledger/tests/consensus/proof_of_work_tests.cpp
n-hutton/ledger-1
909a81c415a73c38fb3d7f486dfcf93d7f87adaf
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/byte_array/encoders.hpp" #include "ledger/chain/consensus/proof_of_work.hpp" #include <gtest/gtest.h> using namespace fetch::ledger::consensus; using namespace fetch::byte_array; ProofOfWork Test1(ByteArray tx, uint64_t diff) { ProofOfWork proof(tx); proof.SetTarget(diff); while (!proof()) { ++proof; } return proof; } bool TestCompare(ByteArray tx, uint64_t diff1, uint64_t diff2) { ProofOfWork proof1(tx), proof2(tx); proof1.SetTarget(diff1); proof2.SetTarget(diff2); while (!proof1()) { ++proof1; } while (!proof2()) { ++proof2; } return (proof1.digest() > proof2.digest()); } TEST(ledger_proof_of_work_gtest, Easy_difficulty) { auto proof = Test1("Hello world", 1); EXPECT_LT(proof.digest(), proof.target()); proof = Test1("FETCH", 1); EXPECT_LT(proof.digest(), proof.target()); proof = Test1("Blah blah", 1); EXPECT_LT(proof.digest(), proof.target()); } TEST(ledger_proof_of_work_gtest, Slightly_hard_difficulty) { auto proof = Test1("Hello world", 10); EXPECT_LT(proof.digest(), proof.target()); proof = Test1("FETCH", 12); EXPECT_LT(proof.digest(), proof.target()); proof = Test1("Blah blah", 15); EXPECT_LT(proof.digest(), proof.target()); } TEST(ledger_proof_of_work_gtest, Comparing) { EXPECT_TRUE(TestCompare("Hello world", 1, 2)); EXPECT_TRUE(TestCompare("Hello world", 9, 10)); EXPECT_TRUE(TestCompare("FETCH", 10, 12)); EXPECT_TRUE(TestCompare("Blah blah", 3, 15)); }
28
80
0.646825
n-hutton
cd891243366127f14167731d254d77a61f18c7cf
197
cpp
C++
sample/test_server/main.cpp
iwtbabc/irpc
647b126450b986e73b350ed451c90d48ec3a420c
[ "MIT" ]
1
2018-08-28T12:01:01.000Z
2018-08-28T12:01:01.000Z
sample/test_server/main.cpp
majianfei/irpc
647b126450b986e73b350ed451c90d48ec3a420c
[ "MIT" ]
null
null
null
sample/test_server/main.cpp
majianfei/irpc
647b126450b986e73b350ed451c90d48ec3a420c
[ "MIT" ]
1
2018-07-28T04:53:12.000Z
2018-07-28T04:53:12.000Z
#include "dispatcher.h" #include "tcp_server.h" using namespace inet; int main(){ Dispatcher dispatcher; TcpServer server(&dispatcher, 8888); server.start(); dispatcher.loop(); return 0; }
14.071429
37
0.720812
iwtbabc
cd8a89ea84e1cb2da9b36beb2a06683579000597
849
cpp
C++
src/scenes/mainMenu.cpp
AndreJFBico/RadRts_BGFX
c8d37d95e68e2fc2b3db09a94f2817533e4aa700
[ "MIT" ]
null
null
null
src/scenes/mainMenu.cpp
AndreJFBico/RadRts_BGFX
c8d37d95e68e2fc2b3db09a94f2817533e4aa700
[ "MIT" ]
null
null
null
src/scenes/mainMenu.cpp
AndreJFBico/RadRts_BGFX
c8d37d95e68e2fc2b3db09a94f2817533e4aa700
[ "MIT" ]
null
null
null
#include "mainMenu.hpp" #include "materials/wireframe.hpp" #include "gameObjects/meshObject.hpp" #include "gameObjects/player.hpp" #include "core/sceneManager.hpp" #include "gameScene.hpp" namespace mainMenu { struct MainMenu { }; void init(scene::Scene& scene, MainMenu& mainMenu) { //TODO there should be a button to push the game scene and pop the main menu scene::Scene gameScene = gameScene::createInstance(); sceneManager::pushScene(gameScene); } void fixedUpdate(scene::Scene& scene, MainMenu& game, float deltaTimeInSeconds) { } void update(scene::Scene& scene, MainMenu& mainMenu, float deltaTimeInSeconds) { } void destroy(scene::Scene& scene, MainMenu& mainMenu) { } scene::Scene createInstance() { MainMenu mainMenu; return scene::createInstance<MainMenu>(init, fixedUpdate, update, destroy, mainMenu); } }
23.583333
89
0.742049
AndreJFBico
cd8e4afcbdff2edbe9516e592533ef6095aab261
741
cc
C++
349.IntersectionofTwoArrays/349.InterTwoArr.cc
stdbilly/leetcode
752704ff99c21863bde4c929b7cc4fa18128cf39
[ "MIT" ]
null
null
null
349.IntersectionofTwoArrays/349.InterTwoArr.cc
stdbilly/leetcode
752704ff99c21863bde4c929b7cc4fa18128cf39
[ "MIT" ]
null
null
null
349.IntersectionofTwoArrays/349.InterTwoArr.cc
stdbilly/leetcode
752704ff99c21863bde4c929b7cc4fa18128cf39
[ "MIT" ]
null
null
null
#include <iostream> #include <unordered_set> #include <vector> using std::cout; using std::endl; using std::unordered_set; using std::vector; class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> record(nums1.begin(), nums1.end()); vector<int> res; for (auto& i : nums2) { if (record.erase(i)) { res.push_back(i); } } return res; } }; int main() { Solution solution; vector<int> nums1{4, 9, 5}; vector<int> nums2{9, 4, 9, 8, 4}; vector<int> res = solution.intersection(nums1, nums2); for (auto& i : res) { cout << i << " "; } cout << endl; return 0; }
22.454545
70
0.550607
stdbilly
cd8ea4bfce741ab5ad6ebfad1066efe2157d4b29
469
hpp
C++
pythran/pythonic/include/numpy/tan.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/tan.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/tan.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_NUMPY_TAN_HPP #define PYTHONIC_INCLUDE_NUMPY_TAN_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/numexpr_to_ndarray.hpp" #include "pythonic/utils/numpy_traits.hpp" #include <nt2/include/functions/tan.hpp> namespace pythonic { namespace numpy { #define NUMPY_NARY_FUNC_NAME tan #define NUMPY_NARY_FUNC_SYM nt2::tan #include "pythonic/include/types/numpy_nary_expr.hpp" } } #endif
21.318182
53
0.808102
artas360
cd8f6e2a61c752896ed720aaa8c03aced8ad9ec7
16,924
cc
C++
test/runSimxAnisoAdapt.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
test/runSimxAnisoAdapt.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
test/runSimxAnisoAdapt.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
#include <gmi_mesh.h> #include <gmi_null.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apfConvert.h> #include <apfNumbering.h> #include <apfShape.h> #include <apf.h> #include <PCU.h> #include <pcu_util.h> #include "MeshSim.h" #include "MeshSimAdapt.h" #include "SimDiscrete.h" #include "SimMessages.h" #include "SimError.h" #include "SimErrorCodes.h" #include "SimMeshingErrorCodes.h" #include "SimDiscreteErrorCodes.h" #include <iostream> #include <cassert> #include <cstdlib> #include <iostream> using namespace std; typedef vector<double> vec; typedef vector<vec> mat; void printModelStats(pGModel model); void makeSimxModelAndMesh( double* coords, int nverts, int* conn, int nelem, pMesh& mesh, pDiscreteModel& model, pVertex* vReturn, pEntity* eReturn); bool checkVertexOrder( apf::Mesh2* mesh, pVertex* vReturn, int nverts); bool checkVertexOrder( apf::Mesh2* mesh, const apf::GlobalToVert & map, double* coords); void getSizesAndFrames( apf::Mesh2* m, apf::Field* sizes, apf::Field* frames, vector<apf::Vector3>& sz, vector<apf::Matrix3x3>& fr); pMSAdapt addSizesToSimxMesh( pMesh mesh, int nverts, pVertex* vReturn, const vector<apf::Vector3>& sizes, const vector<apf::Matrix3x3>& frames); double runSimxAdapt(pMSAdapt adapter); double runSimxMeshImprover( pMesh mesh, double minQuality); void destructSimxMesh( pMesh simxMesh, double*& adaptedCoords, int*& adaptedConns, int& nverts, int& nelem, vector<apf::Vector3> & adaptedSizes, vector<apf::Matrix3x3> & adaptedFrames); void addFields(apf::Mesh2* m, const apf::GlobalToVert & map, const char* sizeName, const char* frameName, const vector<apf::Vector3> & adaptedSizes, const vector<apf::Matrix3x3> &adaptedFrames); apf::Mesh2* convertToPumi( pMesh simxMesh, int dim, const char* sizeName, const char* frameName); int main(int argc, char** argv) { MPI_Init(&argc,&argv); PCU_Comm_Init(); MS_init(); // Call before calling Sim_readLicenseFile Sim_readLicenseFile(0); SimDiscrete_start(0); // initialize GeomSim Discrete library if (argc < 7) { if (PCU_Comm_Self() == 0) { printf("USAGE: %s <model.dmg> <mesh.smb> <prefix>" "<scale field name> <frame field name> <min_quality>\n", argv[0]); } MPI_Finalize(); exit(EXIT_FAILURE); } gmi_register_mesh(); gmi_register_null(); PCU_ALWAYS_ASSERT_VERBOSE(PCU_Comm_Peers() == 1, "This utility only works for serial meshes!"); const char* inputPumiModel = argv[1]; const char* inputPumiMesh = argv[2]; const char* prefix = argv[3]; const char* sizeName = argv[4]; const char* frameName = argv[5]; double minQuality = atof(argv[6]); char outSimxModel[256]; char outInitialSimxMesh[256]; char outAdaptedSimxMesh[256]; char outAdaptedPumiMesh[256]; char outImprovedSimxMesh[256]; char outImprovedPumiMesh[256]; sprintf(outSimxModel, "%s.smd", prefix); sprintf(outInitialSimxMesh, "%s_initial.sms", prefix); sprintf(outAdaptedSimxMesh, "%s_adapted.sms", prefix); sprintf(outAdaptedPumiMesh, "%s_adapted.smb", prefix); sprintf(outImprovedSimxMesh, "%s_adapted_improved.sms", prefix); sprintf(outImprovedPumiMesh, "%s_adapted_improved.smb", prefix); apf::Mesh2* m = apf::loadMdsMesh(inputPumiModel, inputPumiMesh); char message[512]; // first find the sizes field apf::Field* sizes = m->findField(sizeName); sprintf(message, "Couldn't find a field with name %s in mesh!", sizeName); PCU_ALWAYS_ASSERT_VERBOSE(sizes, message); // then find the frames field if they exist apf::Field* frames; frames = m->findField(frameName); sprintf(message, "Couldn't find a field with name %s in mesh!", frameName); PCU_ALWAYS_ASSERT_VERBOSE(frames, message); // remove every field except for sizes and frames int index = 0; while (m->countFields() > 2) { apf::Field* f = m->getField(index); if (f == sizes || f == frames) { index++; continue; } m->removeField(f); apf::destroyField(f); } m->verify(); // extract the coordinates and connectivities int* conn; double* coords; int nelem; int etype; int nverts; int dim = m->getDimension(); extractCoords(m, coords, nverts); destruct(m, conn, nelem, etype); // make/save Simx mesh and model printf("\n===CONVERTING THE PUMI MESH TO SIMX===\n"); pMesh simxMesh = 0; pDiscreteModel simxModel = 0; pVertex* vReturn = new pVertex[nverts]; pEntity* eReturn = new pEntity[nelem]; makeSimxModelAndMesh(coords, nverts, conn, nelem, simxMesh, simxModel, vReturn, eReturn); printf("===DONE===\n"); printf("\n===WRITING THE SIMX MODEL %s===\n", outSimxModel); GM_write(simxModel,outSimxModel,0,0); // save the discrete model cout<<"Model stats: "<<endl; printModelStats(simxModel); printf("===DONE===\n"); printf("\n===WRITING THE SIMX INITIAL MESH %s===\n", outInitialSimxMesh); M_write(simxMesh,outInitialSimxMesh, 0,0); // write out the initial mesh data printf("===DONE===\n"); printf("\n===RUNNING SIMX ADAPT===\n"); PCU_ALWAYS_ASSERT_VERBOSE(checkVertexOrder(m, vReturn, nverts), "The verts orders in the pumi mesh and the created simx mesh appear to be different!\n"); vector<apf::Vector3> sz; vector<apf::Matrix3x3> fr; getSizesAndFrames(m, sizes, frames, sz, fr); pMSAdapt adapter = addSizesToSimxMesh(simxMesh, nverts, vReturn, sz, fr); double adaptTime = runSimxAdapt(adapter); printf("\nSIMX ADAPT RUN-TIME: %f \n", adaptTime); printf("===DONE===\n"); printf("\n===WRITING THE SIMX/SMB ADAPTED MESHES===\n"); printf("%s\n", outAdaptedSimxMesh); printf("%s\n", outAdaptedPumiMesh); M_write(simxMesh,outAdaptedSimxMesh, 0,0); // write out the initial mesh data apf::Mesh2* m2 = convertToPumi(simxMesh, dim, sizeName, frameName); m2->writeNative(outAdaptedPumiMesh); printf("===DONE===\n"); printf("\n===RUNNING SIMX IMPROVER WITH TARGET QUALITY %f===\n", minQuality); double improveTime = runSimxMeshImprover(simxMesh, minQuality); printf("\nSIMX IMPROVER RUN-TIME: %f \n", improveTime); printf("===DONE===\n"); printf("\n===WRITING THE SIMX/SMB IMPROVED MESHES===\n"); printf("%s\n", outImprovedSimxMesh); printf("%s\n", outImprovedPumiMesh); M_write(simxMesh,outImprovedSimxMesh, 0,0); // write out the initial mesh data apf::Mesh2* m3 = convertToPumi(simxMesh, dim, sizeName, frameName); m3->writeNative(outImprovedPumiMesh); printf("===DONE===\n"); // cleanup M_release(simxMesh); GM_release(simxModel); m->destroyNative(); apf::destroyMesh(m); m2->destroyNative(); apf::destroyMesh(m2); m3->destroyNative(); apf::destroyMesh(m3); SimDiscrete_stop(0); Sim_unregisterAllKeys(); MS_exit(); PCU_Comm_Free(); MPI_Finalize(); } void printModelStats(pGModel model) { cout<<" Number of model vertices: "<<GM_numVertices(model)<<endl; cout<<" Vertex tags: "; GVIter modelVertices = GM_vertexIter(model); // initialize the iterator pGVertex modelVertex; while( (modelVertex=GVIter_next(modelVertices)) ){ // get next vertex cout<<" "<<GEN_tag(modelVertex); } GVIter_delete(modelVertices); cout<<endl; cout<<" Number of model edges: "<<GM_numEdges(model)<<endl; cout<<" Number of model faces: "<<GM_numFaces(model)<<endl; cout<<" Face tags: "; GFIter modelFaces = GM_faceIter(model); // initialize the iterator pGFace modelFace; while( (modelFace=GFIter_next(modelFaces)) ){ // get next face cout<<" " << GEN_tag(modelFace); } GFIter_delete(modelFaces); cout<<""<<endl; cout<<" Number of model regions: "<<GM_numRegions(model)<<endl; } void makeSimxModelAndMesh( double* coords, int nverts, int* conn, int nelem, pMesh& mesh, pDiscreteModel& model, pVertex* vReturn, pEntity* eReturn) { // assuming all tet elements int* elementType = new int[nelem]; for (int i = 0; i < nelem; i++) elementType[i] = 10; Sim_setMessageHandler(0); mesh = M_new(0,0); if(M_importFromData(mesh,nverts,coords,nelem, elementType,conn,vReturn,eReturn,0)) { //check for error cerr<<"Error importing mesh data"<<endl; M_release(mesh); return; } // check the input mesh for intersections // this call must occur before the discrete model is created if(MS_checkMeshIntersections(mesh,0,0)) { cerr<<"There are intersections in the input mesh"<<endl; M_release(mesh); return; } // create the Discrete model model = DM_createFromMesh(mesh, 0, 0); if(!model) { //check for error cerr<<"Error creating Discrete model from mesh"<<endl; M_release(mesh); return; } DM_findEdgesByFaceNormals(model, 0, 0); DM_eliminateDanglingEdges(model, 0); if(DM_completeTopology(model, 0)) { //check for error cerr<<"Error completing Discrete model topology"<<endl; M_release(mesh); GM_release(model); return; } } bool checkVertexOrder( apf::Mesh2* mesh, pVertex* vReturn, int nverts) { PCU_ALWAYS_ASSERT((size_t)nverts == mesh->count(0)); double tol = 1.e-12; apf::MeshEntity* ent; apf::MeshIterator* it; it = mesh->begin(0); int count = 0; while( (ent = mesh->iterate(it)) ){ // get the coordinates for pumi vert apf::Vector3 pumiVertCoords; mesh->getPoint(ent, 0, pumiVertCoords); // get the coordinates for simx vert double xyz[3]; pVertex vertex = vReturn[count]; V_coord(vertex,xyz); apf::Vector3 simxVertCoords(xyz[0], xyz[1], xyz[2]); // compare the length of the difference between the two if ( (pumiVertCoords - simxVertCoords).getLength() > tol) return false; count++; } mesh->end(it); return true; } bool checkVertexOrder( apf::Mesh2* mesh, const apf::GlobalToVert & map, double* coords) { double tol = 1.e-12; APF_CONST_ITERATE(apf::GlobalToVert, map, it) { int key = it->first; apf::MeshEntity* vert = it->second; apf::Vector3 pt; mesh->getPoint(vert, 0, pt); apf::Vector3 ptFromInput(coords[3*key], coords[3*key+1], coords[3*key+2]); if ( (pt - ptFromInput).getLength() > tol) return false; } return true; } void getSizesAndFrames( apf::Mesh2* m, apf::Field* sizes, apf::Field* frames, vector<apf::Vector3>& sz, vector<apf::Matrix3x3>& fr) { sz.clear(); fr.clear(); apf::MeshEntity* ent; apf::MeshIterator* it; it = m->begin(0); while( (ent = m->iterate(it)) ){ // get the coordinates for pumi vert apf::Vector3 sizeVector; apf::Matrix3x3 frameTensor; apf::getVector(sizes, ent, 0, sizeVector); apf::getMatrix(frames, ent, 0, frameTensor); sz.push_back(sizeVector); fr.push_back(frameTensor); } m->end(it); } pMSAdapt addSizesToSimxMesh( pMesh mesh, int nverts, pVertex* vReturn, const vector<apf::Vector3>& sizes, const vector<apf::Matrix3x3>& frames) { PCU_ALWAYS_ASSERT_VERBOSE((size_t)nverts == sizes.size(), "Expecting the size of the vector to be the same as nverts!\n"); PCU_ALWAYS_ASSERT_VERBOSE((size_t)nverts == frames.size(), "Expecting the size of the vector to be the same as nverts!\n"); pMSAdapt adapter = MSA_new(mesh, 1); pVertex vertex; for (int i = 0; i < nverts; i++) { vertex = vReturn[i]; apf::Vector3 sz = sizes[i]; apf::Matrix3x3 fr = frames[i]; apf::Vector3 row0 = apf::Vector3(fr[0][0], fr[1][0], fr[2][0]); apf::Vector3 row1 = apf::Vector3(fr[0][1], fr[1][1], fr[2][1]); apf::Vector3 row2 = apf::Vector3(fr[0][2], fr[1][2], fr[2][2]); row0 = row0 * sz[0]; row1 = row1 * sz[1]; row2 = row2 * sz[2]; double anisoSize[3][3] = { {row0[0], row0[1], row0[2]}, {row1[0], row1[1], row1[2]}, {row2[0], row2[1], row2[2]} }; MSA_setAnisoVertexSize(adapter, vertex, anisoSize); } return adapter; } double runSimxAdapt(pMSAdapt adapter) { double t0 = PCU_Time(); MSA_adapt(adapter, 0); MSA_delete(adapter); double t1 = PCU_Time(); return t1 - t0; } double runSimxMeshImprover(pMesh mesh, double minQuality) { double t0 = PCU_Time(); pVolumeMeshImprover vmi = VolumeMeshImprover_new(mesh); VolumeMeshImprover_setShapeMetric(vmi, ShapeMetricType_VolLenRatio, minQuality); VolumeMeshImprover_execute(vmi, 0); VolumeMeshImprover_delete(vmi); double t1 = PCU_Time(); return t1 - t0; } static int countVerts(pMesh mesh) { VIter vit; pVertex vert; vit = M_vertexIter(mesh); int count = 0; while( (vert = VIter_next(vit)) ) count++; VIter_delete(vit); return count; } static int countRegions(pMesh mesh) { RIter rit; pRegion region; rit = M_regionIter(mesh); int count = 0; while( (region = RIter_next(rit)) ) count++; RIter_delete(rit); return count; } static void getSizeAndFramesFromArray( double anisoSize[3][3], apf::Vector3 &sizes, apf::Matrix3x3 &frame) { apf::Vector3 v0 = apf::Vector3(anisoSize[0][0], anisoSize[0][1], anisoSize[0][2]); apf::Vector3 v1 = apf::Vector3(anisoSize[1][0], anisoSize[1][1], anisoSize[1][2]); apf::Vector3 v2 = apf::Vector3(anisoSize[2][0], anisoSize[2][1], anisoSize[2][2]); sizes = apf::Vector3(v0.getLength(), v1.getLength(), v2.getLength()); v0 = v0 / v0.getLength(); v1 = v1 / v1.getLength(); v2 = v2 / v2.getLength(); /* // in pumi we store the directions in columns */ frame = apf::Matrix3x3(v0[0], v1[0], v2[0], v0[1], v1[1], v2[1], v0[2], v1[2], v2[2]); } void destructSimxMesh( pMesh mesh, double*& adaptedCoords, int*& adaptedConns, int& nverts, int& nelem, vector<apf::Vector3>& adaptedSizes, vector<apf::Matrix3x3>& adaptedFrames) { nverts = countVerts(mesh); nelem = countRegions(mesh); adaptedCoords = new double[3*nverts]; adaptedConns = new int[4*nelem]; VIter vertices; RIter regions; pVertex vertex; pRegion region; double xyz[3]; pPList regionVerts; int i,j; vertices = M_vertexIter(mesh); i=0; while( (vertex=VIter_next(vertices)) ){ V_coord(vertex,xyz); adaptedCoords[i*3] = xyz[0]; adaptedCoords[i*3+1] = xyz[1]; adaptedCoords[i*3+2] = xyz[2]; double anisoSize[3][3]; V_size(vertex, NULL, anisoSize); apf::Vector3 sizes; apf::Matrix3x3 frame; getSizeAndFramesFromArray(anisoSize, sizes, frame); adaptedSizes.push_back(sizes); adaptedFrames.push_back(frame); EN_setID((pEntity)vertex,i); i++; } VIter_delete(vertices); regions = M_regionIter(mesh); i=0; while( (region = RIter_next(regions)) ){ regionVerts = R_vertices(region,0); vector<int> ids; for(j=0; j < 4; j++){ vertex = (pVertex)PList_item(regionVerts,j); int id = EN_id((pEntity)vertex); ids.push_back(id); } // simmetrix's local ordering is different from pumi's adaptedConns[i*4] = ids[0]; adaptedConns[i*4+1] = ids[2]; adaptedConns[i*4+2] = ids[1]; adaptedConns[i*4+3] = ids[3]; PList_delete(regionVerts); i++; } RIter_delete(regions); } void addFields(apf::Mesh2* m, const apf::GlobalToVert & map, const char* sizeName, const char* frameName, const vector<apf::Vector3> & adaptedSizes, const vector<apf::Matrix3x3> &adaptedFrames) { apf::Field* adaptedSizeField = apf::createFieldOn(m, sizeName, apf::VECTOR); apf::Field* adaptedFrameField = apf::createFieldOn(m, frameName, apf::MATRIX); APF_CONST_ITERATE(apf::GlobalToVert, map, it) { int key = it->first; apf::MeshEntity* vert = it->second; apf::setVector(adaptedSizeField, vert, 0, adaptedSizes[key]); apf::setMatrix(adaptedFrameField, vert, 0, adaptedFrames[key]); } } apf::Mesh2* convertToPumi( pMesh simxMesh, int dim, const char* sizeName, const char* frameName) { double* adaptedCoords; int* adaptedConns; int adaptedNumVerts, adaptedNumElems; vector<apf::Vector3> adaptedSizes; vector<apf::Matrix3x3> adaptedFrames; destructSimxMesh(simxMesh, adaptedCoords, adaptedConns, adaptedNumVerts, adaptedNumElems, adaptedSizes, adaptedFrames); gmi_model* nullModel = gmi_load(".null"); apf::Mesh2* m2 = apf::makeEmptyMdsMesh(nullModel, dim, false); apf::GlobalToVert outMap; apf::construct(m2, adaptedConns, adaptedNumElems, apf::Mesh::TET, outMap);; apf::alignMdsRemotes(m2); apf::deriveMdsModel(m2); apf::setCoords(m2, adaptedCoords, adaptedNumVerts, outMap); m2->verify(); // make sure ordering of verts is what it is supposed to be. PCU_ALWAYS_ASSERT_VERBOSE(checkVertexOrder(m2, outMap, adaptedCoords), "The verts order in the adapted simx mesh and the created pumi mesh appear to be different!\n"); // add the fields addFields(m2, outMap, sizeName, frameName, adaptedSizes, adaptedFrames); outMap.clear(); return m2; }
27.744262
102
0.666273
cwsmith
cd914db2ff3374cdabf10971d522c98f164b3d90
1,302
cpp
C++
example/cmd_pwd.cpp
moslevin/mark3-terminal
3ff9e46e6d731e44b71ea3d329008a673da9efff
[ "BSD-3-Clause" ]
null
null
null
example/cmd_pwd.cpp
moslevin/mark3-terminal
3ff9e46e6d731e44b71ea3d329008a673da9efff
[ "BSD-3-Clause" ]
null
null
null
example/cmd_pwd.cpp
moslevin/mark3-terminal
3ff9e46e6d731e44b71ea3d329008a673da9efff
[ "BSD-3-Clause" ]
null
null
null
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012 - 2018 m0slevin, all rights reserved. See license.txt for more information =========================================================================== */ #include "cmd_pwd.h" #include "cmd.h" #include "shell_env.h" #include "stdio.h" #include "getopt.h" //--------------------------------------------------------------------------- namespace pwd { using namespace Mark3; int main(int /*argc*/, const char** /*argv*/) { const char* pathv[10]; auto pathc = 0; auto* node = envPwd; while (node && (pathc < 10)) { pathv[pathc++] = node->name(); node = node->parent(); } pathc--; printf("/"); while (pathc) { printf("%s/", pathv[--pathc]); } return 0; } } // namespace pwd
31
79
0.364055
moslevin
cd92e551a6643b555479c00a1d40cec3e8f59322
2,283
hpp
C++
include/StringAlgo/Convert.hpp
PoetaKodu/string-algo
666496207db5cab4622d9c073eaecd6560d72d3c
[ "MIT" ]
null
null
null
include/StringAlgo/Convert.hpp
PoetaKodu/string-algo
666496207db5cab4622d9c073eaecd6560d72d3c
[ "MIT" ]
null
null
null
include/StringAlgo/Convert.hpp
PoetaKodu/string-algo
666496207db5cab4622d9c073eaecd6560d72d3c
[ "MIT" ]
1
2021-08-05T11:15:15.000Z
2021-08-05T11:15:15.000Z
#pragma once #include STRINGALGO_PCH namespace string_algo { //////////////////////////////////////// template <typename T, typename = std::enable_if_t<std::is_integral_v<T>> > inline bool toIntNoSkipWs(T& int_, char const* begin_, char const* end_) { if (begin_ == end_) return false; [[maybe_unused]] bool negative; if constexpr (!std::is_unsigned_v<T>) negative = (*begin_ == '-'); if (negative) ++begin_; int val = 0; for(; begin_ != end_; ++begin_) { val = val*10 + (*begin_ - '0'); } if constexpr (!std::is_unsigned_v<T>) int_ = (negative ? -val : val); else int_ = val; return true; } //////////////////////////////////////// template <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>> > inline bool toFloatNoSkipWs(T& float_, char const* begin_, char const* end_) { if (begin_ == end_) return false; constexpr size_t MaxDigits = 64; char buf[MaxDigits]; size_t numToCopy = std::min(size_t(end_ - begin_), MaxDigits - 1); std::memcpy( buf, begin_, numToCopy ); buf[numToCopy] = '\0'; char * end; T val; if constexpr(std::is_same_v<T, double>) val = std::strtod(buf, &end); else if constexpr(std::is_same_v<T, long double>) val = std::strtold(buf, &end); else // float or other val = static_cast<T>( std::strtof(buf, &end) ); if (errno != 0) { // TODO: could be ERANGE errno = 0; return false; } float_ = val; return true; } //////////////////////////////////////// template <typename T> inline bool to(T& outValue_, char const* begin_, char const* end_) { while(begin_ != end_ && *begin_ != '-' && (*begin_ < '0' || *begin_ > '9')) ++begin_; if constexpr (std::is_integral_v<T>) return toIntNoSkipWs<T>(outValue_, begin_, end_); else return toFloatNoSkipWs<T>(outValue_, begin_, end_); } //////////////////////////////////////// template <typename T> inline std::optional<T> to(char const* begin_, char const* end_) { T result; if (to<T>(result, begin_, end_)) return result; return std::nullopt; } //////////////////////////////////////// template <typename T = int> inline std::optional<T> to(std::string_view const& str_) { T result; if ( to<T>(result, str_.data(), str_.data() + str_.length()) ) return result; return std::nullopt; } }
20.754545
76
0.590889
PoetaKodu
cd94708744e2511956b2348b6a276fc3ec2d7274
1,914
cpp
C++
modules/ext/Logger/Logger.cpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
4
2017-07-06T22:18:41.000Z
2021-05-24T21:28:37.000Z
modules/ext/Logger/Logger.cpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
null
null
null
modules/ext/Logger/Logger.cpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
1
2020-08-02T13:00:38.000Z
2020-08-02T13:00:38.000Z
/* * Print message on terminal or user given target. */ #include <luapp.hpp> #include <toy/Oops.hpp> #include <toy/Log.hpp> #include <toy/Utf.hpp> #include <toy/io/Writer.hpp> namespace toy{ namespace luamodule{ namespace logger{ static int IsUTF8(lua::NativeState L) { lua::Str str; lua::CheckVarFromLua(L,&str,-1); lua::Pop(L,1); lua::PushVarToLua( L, static_cast<lua::Bool>(toy::utf::IsUtf8(str)) ); return 1; } static inline void PrintString(lua::NativeState L) { lua::Str str; if ( lua::IsType<lua::Str>(L,-1) ) { lua::CheckVarFromLua(L,&str,-1); } else { toy::Oops(TOY_MARK); str = "[Error]"; } lua::Pop(L,1); toy::Logger<<str; } static int Log(lua::NativeState L) { PrintString(L); return 0; } static int LogWithNewLine(lua::NativeState L) { PrintString(L); toy::Logger<<toy::NewLine; return 0; } static int CleanOutputLog(lua::NativeState) { toy::log::BackDefaultDevice(); return 0; } static int SetOutputLog(lua::NativeState L) { lua::Str str; lua::CheckVarFromLua(L,&str,-1); lua::Pop(L,1); auto dev = std::make_shared<toy::io::Writer<toy::io::Stream>>(); dev->open(str); std::function<void(const char*)> func = [dev](const char* msg) { dev->printf(msg); }; std::function<void(const wchar_t*)> funcw = [dev](const wchar_t* msg) { dev->printf(toy::utf::WCharToUTF8(msg)); }; toy::log::PushDevice(func,funcw); return 0; } }}} #if defined(_WIN32) #define MY_DLL_API __declspec(dllexport) #else #define MY_DLL_API #endif extern "C" MY_DLL_API int luaopen_toy_logger(lua::NativeState L) { namespace module = ::toy::luamodule::logger; lua::State<> lua(L); lua.setFunc( "printf", module::Log ); lua.setFunc( "print", module::LogWithNewLine ); lua.setFunc( "is_utf8", module::IsUTF8 ); lua.setFunc( "as_file", module::SetOutputLog ); lua.setFunc( "reset", module::CleanOutputLog ); return 1; }
17.089286
71
0.657262
ToyAuthor
cd994e696e6e0a7da03aea2ed7243d88bb0b2f34
1,602
cpp
C++
test/any/array.cpp
mkn/mkn.gpu
22946338e6a4790cc056708aa141c1a31538ba1c
[ "BSD-3-Clause" ]
null
null
null
test/any/array.cpp
mkn/mkn.gpu
22946338e6a4790cc056708aa141c1a31538ba1c
[ "BSD-3-Clause" ]
1
2020-09-13T10:39:29.000Z
2021-05-07T08:12:11.000Z
test/any/array.cpp
mkn/mkn.gpu
22946338e6a4790cc056708aa141c1a31538ba1c
[ "BSD-3-Clause" ]
null
null
null
#include "kul/gpu.hpp" static constexpr uint32_t WIDTH = 1024, HEIGHT = 1024; static constexpr uint32_t NUM = WIDTH * HEIGHT; static constexpr uint32_t THREADS_PER_BLOCK_X = 16, THREADS_PER_BLOCK_Y = 16; template <typename T> __global__ void vectoradd(T* a, const T* b, const T* c) { auto i = kul::gpu::idx(); a[i] = b[i] + c[i]; } template <typename Float> uint32_t test_1() { kul::gpu::HostArray<Float, NUM> b, c; for (uint32_t i = 0; i < NUM; ++i) b[i] = i; for (uint32_t i = 0; i < NUM; ++i) c[i] = i * 100.0f; kul::gpu::DeviceMem<Float> devA(NUM), devB(b), devC(c); kul::gpu::Launcher{WIDTH, HEIGHT, THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y}(vectoradd<Float>, devA, devB, devC); auto a = devA(); for (uint32_t i = 0; i < NUM; ++i) if (a[i] != b[i] + c[i]) return 1; return 0; } template <typename T> __global__ void vectorinc(T* a) { auto i = kul::gpu::idx(); a[i] = a[i] + 1; } template <typename Float> uint32_t test_2() { kul::gpu::HostArray<Float, NUM> host; for (uint32_t i = 0; i < NUM; ++i) host[i] = i; kul::gpu::DeviceMem<Float> dev{host}; kul::gpu::Launcher{WIDTH, HEIGHT, THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y}(vectorinc<Float>, dev); auto a = dev(); for (uint32_t i = 0; i < NUM; ++i) if (a[i] != host[i] + 1) return 1; return 0; } int main() { KOUT(NON) << __FILE__; return test_1<float>() + test_1<double>() + // test_2<float>() + test_2<double>(); }
27.62069
96
0.559301
mkn
cd9c70a8f76ca7ebaaf764edee1bab5151d7ae1c
20,649
cpp
C++
src/bricklet_ambient_light.cpp
davidplotzki/sensorlogger
8ee255fba5f8560650e2b79fc967aeec8d8ec7b7
[ "MIT" ]
null
null
null
src/bricklet_ambient_light.cpp
davidplotzki/sensorlogger
8ee255fba5f8560650e2b79fc967aeec8d8ec7b7
[ "MIT" ]
null
null
null
src/bricklet_ambient_light.cpp
davidplotzki/sensorlogger
8ee255fba5f8560650e2b79fc967aeec8d8ec7b7
[ "MIT" ]
null
null
null
/* *********************************************************** * This file was automatically generated on 2021-05-06. * * * * C/C++ Bindings Version 2.1.32 * * * * If you have a bugfix for this file and want to commit it, * * please fix the bug in the generator. You can find a link * * to the generators git repository on tinkerforge.com * *************************************************************/ #define IPCON_EXPOSE_INTERNALS #include "bricklet_ambient_light.h" #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void (*Illuminance_CallbackFunction)(uint16_t illuminance, void *user_data); typedef void (*AnalogValue_CallbackFunction)(uint16_t value, void *user_data); typedef void (*IlluminanceReached_CallbackFunction)(uint16_t illuminance, void *user_data); typedef void (*AnalogValueReached_CallbackFunction)(uint16_t value, void *user_data); #if defined _MSC_VER || defined __BORLANDC__ #pragma pack(push) #pragma pack(1) #define ATTRIBUTE_PACKED #elif defined __GNUC__ #ifdef _WIN32 // workaround struct packing bug in GCC 4.7 on Windows // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991 #define ATTRIBUTE_PACKED __attribute__((gcc_struct, packed)) #else #define ATTRIBUTE_PACKED __attribute__((packed)) #endif #else #error unknown compiler, do not know how to enable struct packing #endif typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetIlluminance_Request; typedef struct { PacketHeader header; uint16_t illuminance; } ATTRIBUTE_PACKED GetIlluminance_Response; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetAnalogValue_Request; typedef struct { PacketHeader header; uint16_t value; } ATTRIBUTE_PACKED GetAnalogValue_Response; typedef struct { PacketHeader header; uint32_t period; } ATTRIBUTE_PACKED SetIlluminanceCallbackPeriod_Request; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetIlluminanceCallbackPeriod_Request; typedef struct { PacketHeader header; uint32_t period; } ATTRIBUTE_PACKED GetIlluminanceCallbackPeriod_Response; typedef struct { PacketHeader header; uint32_t period; } ATTRIBUTE_PACKED SetAnalogValueCallbackPeriod_Request; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetAnalogValueCallbackPeriod_Request; typedef struct { PacketHeader header; uint32_t period; } ATTRIBUTE_PACKED GetAnalogValueCallbackPeriod_Response; typedef struct { PacketHeader header; char option; uint16_t min; uint16_t max; } ATTRIBUTE_PACKED SetIlluminanceCallbackThreshold_Request; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetIlluminanceCallbackThreshold_Request; typedef struct { PacketHeader header; char option; uint16_t min; uint16_t max; } ATTRIBUTE_PACKED GetIlluminanceCallbackThreshold_Response; typedef struct { PacketHeader header; char option; uint16_t min; uint16_t max; } ATTRIBUTE_PACKED SetAnalogValueCallbackThreshold_Request; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetAnalogValueCallbackThreshold_Request; typedef struct { PacketHeader header; char option; uint16_t min; uint16_t max; } ATTRIBUTE_PACKED GetAnalogValueCallbackThreshold_Response; typedef struct { PacketHeader header; uint32_t debounce; } ATTRIBUTE_PACKED SetDebouncePeriod_Request; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetDebouncePeriod_Request; typedef struct { PacketHeader header; uint32_t debounce; } ATTRIBUTE_PACKED GetDebouncePeriod_Response; typedef struct { PacketHeader header; uint16_t illuminance; } ATTRIBUTE_PACKED Illuminance_Callback; typedef struct { PacketHeader header; uint16_t value; } ATTRIBUTE_PACKED AnalogValue_Callback; typedef struct { PacketHeader header; uint16_t illuminance; } ATTRIBUTE_PACKED IlluminanceReached_Callback; typedef struct { PacketHeader header; uint16_t value; } ATTRIBUTE_PACKED AnalogValueReached_Callback; typedef struct { PacketHeader header; } ATTRIBUTE_PACKED GetIdentity_Request; typedef struct { PacketHeader header; char uid[8]; char connected_uid[8]; char position; uint8_t hardware_version[3]; uint8_t firmware_version[3]; uint16_t device_identifier; } ATTRIBUTE_PACKED GetIdentity_Response; #if defined _MSC_VER || defined __BORLANDC__ #pragma pack(pop) #endif #undef ATTRIBUTE_PACKED static void ambient_light_callback_wrapper_illuminance(DevicePrivate *device_p, Packet *packet) { Illuminance_CallbackFunction callback_function; void *user_data; Illuminance_Callback *callback; if (packet->header.length != sizeof(Illuminance_Callback)) { return; // silently ignoring callback with wrong length } callback_function = (Illuminance_CallbackFunction)device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ILLUMINANCE]; user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ILLUMINANCE]; callback = (Illuminance_Callback *)packet; (void)callback; // avoid unused variable warning if (callback_function == NULL) { return; } callback->illuminance = leconvert_uint16_from(callback->illuminance); callback_function(callback->illuminance, user_data); } static void ambient_light_callback_wrapper_analog_value(DevicePrivate *device_p, Packet *packet) { AnalogValue_CallbackFunction callback_function; void *user_data; AnalogValue_Callback *callback; if (packet->header.length != sizeof(AnalogValue_Callback)) { return; // silently ignoring callback with wrong length } callback_function = (AnalogValue_CallbackFunction)device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ANALOG_VALUE]; user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ANALOG_VALUE]; callback = (AnalogValue_Callback *)packet; (void)callback; // avoid unused variable warning if (callback_function == NULL) { return; } callback->value = leconvert_uint16_from(callback->value); callback_function(callback->value, user_data); } static void ambient_light_callback_wrapper_illuminance_reached(DevicePrivate *device_p, Packet *packet) { IlluminanceReached_CallbackFunction callback_function; void *user_data; IlluminanceReached_Callback *callback; if (packet->header.length != sizeof(IlluminanceReached_Callback)) { return; // silently ignoring callback with wrong length } callback_function = (IlluminanceReached_CallbackFunction)device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ILLUMINANCE_REACHED]; user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ILLUMINANCE_REACHED]; callback = (IlluminanceReached_Callback *)packet; (void)callback; // avoid unused variable warning if (callback_function == NULL) { return; } callback->illuminance = leconvert_uint16_from(callback->illuminance); callback_function(callback->illuminance, user_data); } static void ambient_light_callback_wrapper_analog_value_reached(DevicePrivate *device_p, Packet *packet) { AnalogValueReached_CallbackFunction callback_function; void *user_data; AnalogValueReached_Callback *callback; if (packet->header.length != sizeof(AnalogValueReached_Callback)) { return; // silently ignoring callback with wrong length } callback_function = (AnalogValueReached_CallbackFunction)device_p->registered_callbacks[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ANALOG_VALUE_REACHED]; user_data = device_p->registered_callback_user_data[DEVICE_NUM_FUNCTION_IDS + AMBIENT_LIGHT_CALLBACK_ANALOG_VALUE_REACHED]; callback = (AnalogValueReached_Callback *)packet; (void)callback; // avoid unused variable warning if (callback_function == NULL) { return; } callback->value = leconvert_uint16_from(callback->value); callback_function(callback->value, user_data); } void ambient_light_create(AmbientLight *ambient_light, const char *uid, IPConnection *ipcon) { IPConnectionPrivate *ipcon_p = ipcon->p; DevicePrivate *device_p; device_create(ambient_light, uid, ipcon_p, 2, 0, 1, AMBIENT_LIGHT_DEVICE_IDENTIFIER); device_p = ambient_light->p; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_ILLUMINANCE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_ANALOG_VALUE] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_SET_ILLUMINANCE_CALLBACK_PERIOD] = DEVICE_RESPONSE_EXPECTED_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_ILLUMINANCE_CALLBACK_PERIOD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_SET_ANALOG_VALUE_CALLBACK_PERIOD] = DEVICE_RESPONSE_EXPECTED_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_ANALOG_VALUE_CALLBACK_PERIOD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_SET_ILLUMINANCE_CALLBACK_THRESHOLD] = DEVICE_RESPONSE_EXPECTED_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_ILLUMINANCE_CALLBACK_THRESHOLD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_SET_ANALOG_VALUE_CALLBACK_THRESHOLD] = DEVICE_RESPONSE_EXPECTED_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_ANALOG_VALUE_CALLBACK_THRESHOLD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_SET_DEBOUNCE_PERIOD] = DEVICE_RESPONSE_EXPECTED_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_DEBOUNCE_PERIOD] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->response_expected[AMBIENT_LIGHT_FUNCTION_GET_IDENTITY] = DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; device_p->callback_wrappers[AMBIENT_LIGHT_CALLBACK_ILLUMINANCE] = ambient_light_callback_wrapper_illuminance; device_p->callback_wrappers[AMBIENT_LIGHT_CALLBACK_ANALOG_VALUE] = ambient_light_callback_wrapper_analog_value; device_p->callback_wrappers[AMBIENT_LIGHT_CALLBACK_ILLUMINANCE_REACHED] = ambient_light_callback_wrapper_illuminance_reached; device_p->callback_wrappers[AMBIENT_LIGHT_CALLBACK_ANALOG_VALUE_REACHED] = ambient_light_callback_wrapper_analog_value_reached; ipcon_add_device(ipcon_p, device_p); } void ambient_light_destroy(AmbientLight *ambient_light) { device_release(ambient_light->p); } int ambient_light_get_response_expected(AmbientLight *ambient_light, uint8_t function_id, bool *ret_response_expected) { return device_get_response_expected(ambient_light->p, function_id, ret_response_expected); } int ambient_light_set_response_expected(AmbientLight *ambient_light, uint8_t function_id, bool response_expected) { return device_set_response_expected(ambient_light->p, function_id, response_expected); } int ambient_light_set_response_expected_all(AmbientLight *ambient_light, bool response_expected) { return device_set_response_expected_all(ambient_light->p, response_expected); } void ambient_light_register_callback(AmbientLight *ambient_light, int16_t callback_id, void (*function)(void), void *user_data) { device_register_callback(ambient_light->p, callback_id, function, user_data); } int ambient_light_get_api_version(AmbientLight *ambient_light, uint8_t ret_api_version[3]) { return device_get_api_version(ambient_light->p, ret_api_version); } int ambient_light_get_illuminance(AmbientLight *ambient_light, uint16_t *ret_illuminance) { DevicePrivate *device_p = ambient_light->p; GetIlluminance_Request request; GetIlluminance_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_ILLUMINANCE, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_illuminance = leconvert_uint16_from(response.illuminance); return ret; } int ambient_light_get_analog_value(AmbientLight *ambient_light, uint16_t *ret_value) { DevicePrivate *device_p = ambient_light->p; GetAnalogValue_Request request; GetAnalogValue_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_ANALOG_VALUE, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_value = leconvert_uint16_from(response.value); return ret; } int ambient_light_set_illuminance_callback_period(AmbientLight *ambient_light, uint32_t period) { DevicePrivate *device_p = ambient_light->p; SetIlluminanceCallbackPeriod_Request request; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_SET_ILLUMINANCE_CALLBACK_PERIOD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } request.period = leconvert_uint32_to(period); ret = device_send_request(device_p, (Packet *)&request, NULL, 0); return ret; } int ambient_light_get_illuminance_callback_period(AmbientLight *ambient_light, uint32_t *ret_period) { DevicePrivate *device_p = ambient_light->p; GetIlluminanceCallbackPeriod_Request request; GetIlluminanceCallbackPeriod_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_ILLUMINANCE_CALLBACK_PERIOD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_period = leconvert_uint32_from(response.period); return ret; } int ambient_light_set_analog_value_callback_period(AmbientLight *ambient_light, uint32_t period) { DevicePrivate *device_p = ambient_light->p; SetAnalogValueCallbackPeriod_Request request; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_SET_ANALOG_VALUE_CALLBACK_PERIOD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } request.period = leconvert_uint32_to(period); ret = device_send_request(device_p, (Packet *)&request, NULL, 0); return ret; } int ambient_light_get_analog_value_callback_period(AmbientLight *ambient_light, uint32_t *ret_period) { DevicePrivate *device_p = ambient_light->p; GetAnalogValueCallbackPeriod_Request request; GetAnalogValueCallbackPeriod_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_ANALOG_VALUE_CALLBACK_PERIOD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_period = leconvert_uint32_from(response.period); return ret; } int ambient_light_set_illuminance_callback_threshold(AmbientLight *ambient_light, char option, uint16_t min, uint16_t max) { DevicePrivate *device_p = ambient_light->p; SetIlluminanceCallbackThreshold_Request request; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_SET_ILLUMINANCE_CALLBACK_THRESHOLD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } request.option = option; request.min = leconvert_uint16_to(min); request.max = leconvert_uint16_to(max); ret = device_send_request(device_p, (Packet *)&request, NULL, 0); return ret; } int ambient_light_get_illuminance_callback_threshold(AmbientLight *ambient_light, char *ret_option, uint16_t *ret_min, uint16_t *ret_max) { DevicePrivate *device_p = ambient_light->p; GetIlluminanceCallbackThreshold_Request request; GetIlluminanceCallbackThreshold_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_ILLUMINANCE_CALLBACK_THRESHOLD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_option = response.option; *ret_min = leconvert_uint16_from(response.min); *ret_max = leconvert_uint16_from(response.max); return ret; } int ambient_light_set_analog_value_callback_threshold(AmbientLight *ambient_light, char option, uint16_t min, uint16_t max) { DevicePrivate *device_p = ambient_light->p; SetAnalogValueCallbackThreshold_Request request; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_SET_ANALOG_VALUE_CALLBACK_THRESHOLD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } request.option = option; request.min = leconvert_uint16_to(min); request.max = leconvert_uint16_to(max); ret = device_send_request(device_p, (Packet *)&request, NULL, 0); return ret; } int ambient_light_get_analog_value_callback_threshold(AmbientLight *ambient_light, char *ret_option, uint16_t *ret_min, uint16_t *ret_max) { DevicePrivate *device_p = ambient_light->p; GetAnalogValueCallbackThreshold_Request request; GetAnalogValueCallbackThreshold_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_ANALOG_VALUE_CALLBACK_THRESHOLD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_option = response.option; *ret_min = leconvert_uint16_from(response.min); *ret_max = leconvert_uint16_from(response.max); return ret; } int ambient_light_set_debounce_period(AmbientLight *ambient_light, uint32_t debounce) { DevicePrivate *device_p = ambient_light->p; SetDebouncePeriod_Request request; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_SET_DEBOUNCE_PERIOD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } request.debounce = leconvert_uint32_to(debounce); ret = device_send_request(device_p, (Packet *)&request, NULL, 0); return ret; } int ambient_light_get_debounce_period(AmbientLight *ambient_light, uint32_t *ret_debounce) { DevicePrivate *device_p = ambient_light->p; GetDebouncePeriod_Request request; GetDebouncePeriod_Response response; int ret; ret = device_check_validity(device_p); if (ret < 0) { return ret; } ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_DEBOUNCE_PERIOD, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } *ret_debounce = leconvert_uint32_from(response.debounce); return ret; } int ambient_light_get_identity(AmbientLight *ambient_light, char ret_uid[8], char ret_connected_uid[8], char *ret_position, uint8_t ret_hardware_version[3], uint8_t ret_firmware_version[3], uint16_t *ret_device_identifier) { DevicePrivate *device_p = ambient_light->p; GetIdentity_Request request; GetIdentity_Response response; int ret; ret = packet_header_create(&request.header, sizeof(request), AMBIENT_LIGHT_FUNCTION_GET_IDENTITY, device_p->ipcon_p, device_p); if (ret < 0) { return ret; } ret = device_send_request(device_p, (Packet *)&request, (Packet *)&response, sizeof(response)); if (ret < 0) { return ret; } memcpy(ret_uid, response.uid, 8); memcpy(ret_connected_uid, response.connected_uid, 8); *ret_position = response.position; memcpy(ret_hardware_version, response.hardware_version, 3 * sizeof(uint8_t)); memcpy(ret_firmware_version, response.firmware_version, 3 * sizeof(uint8_t)); *ret_device_identifier = leconvert_uint16_from(response.device_identifier); return ret; } #ifdef __cplusplus } #endif
29.882779
224
0.791661
davidplotzki
cd9cbc111bdccff963aa565b984d050e634d2e72
41
hpp
C++
src/boost_metaparse_v1_one_of.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_metaparse_v1_one_of.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_metaparse_v1_one_of.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/metaparse/v1/one_of.hpp>
20.5
40
0.780488
miathedev
cd9e8610913475188b761e021e535988af73f889
9,406
cpp
C++
UrhoTest2.cpp
LeithKetchell/Humble
f71016d8a13c931da1aae0af49018c014c4f8c8e
[ "MIT" ]
null
null
null
UrhoTest2.cpp
LeithKetchell/Humble
f71016d8a13c931da1aae0af49018c014c4f8c8e
[ "MIT" ]
null
null
null
UrhoTest2.cpp
LeithKetchell/Humble
f71016d8a13c931da1aae0af49018c014c4f8c8e
[ "MIT" ]
null
null
null
#define URHO3D_ANGELSCRIPT 1 // we want angelscript support #define URHO3D_LOGGING 1 // we want debug log message support #include <Urho3D/Urho3DAll.h> using namespace Urho3D; /// Let's define (and implement) our custom application class /// Note it derives from Urho3D::Application class - there's some virtual methods we can override... /// class MyApp : public Application { public: MyApp(Context* context):Application(context) { } void Setup() { engineParameters_["FullScreen"]=true; //engineParameters_["FullScreen"]=false; //engineParameters_["WindowWidth"]=1280; //engineParameters_["WindowHeight"]=720; //engineParameters_["WindowResizable"]=true; //engine_->DumpResources(); } /// Let's set up a simple scene, using "hardcode" to do it... void Start() { // We're not using AngelScript just yet... // context_->RegisterSubsystem(new Script(context_)); /// Register to receive keypress events SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(MyApp,HandleKeyDown)); /// Create a new Scene, and store the pointer in a "SharedPtr" smartpointer container /// This arrangement ensures that when our App dies, the Scene will be automatically deleted. gameScene_ = new Scene(context_); /// We'll give our new scene a name, just because we can gameScene_->SetName("My Game Scene"); /// The first component our new scene needs is an Octree. /// This component allows Urho to perform visibility based culling /// which helps improve rendering performance in more complex scenes /// Since this component does not require a Transform, we'll attach it /// directly to the scene root (whose transform is always Identity). gameScene_->CreateComponent<Octree>(); /// Next we'll create a Camera for rendering a 3D scene ... /// The camera will require a node to provide rotation and translation. /// We'll create a new Node as a child of our scene /// and we'll store it in a "WeakPtr" smartpointer object. /// The reason we use WeakPtr, and not SharedPtr, is because /// the Node was not created with "new" - its lifetime is already /// being managed by the scene. /// WeakPtr won't "keep the object alive", but should the object die, /// the weakptr will hold "null", which alerts us that the pointer has become invalid. Node* cameraNode_ = gameScene_->CreateChild("Camera Node"); cameraNode_->Translate(Vector3(0,50,-20)); /// Move camera back, and way up cameraNode_->LookAt(Vector3::ZERO, Vector3::UP); /// Make camera look down and forward at the World Origin /// We'll create the Camera component itself as a child of our "Camera Node" /// The node provides us with a "transform" to position and rotate the camera, /// while the camera component contains the camera-specific code and data. Camera* camera = cameraNode_->CreateComponent<Camera>(); /// We'll set the camera's far clip plane to something reasonable for our scene /// This effectively sets the limit for the max. viewing distance that the camera can "see" camera->SetFarClip(100.0f); /// Create and Setup a Viewport - effectively associating a camera with the scene it will render /// We need WeakPtr here to safely hand over ownership of this special object to Urho /// Even though we used "new", we don't own this object - this is an exception to the rule! WeakPtr<Viewport> viewport (new Viewport(context_, gameScene_, camera)); /// Hand (ownership of) the viewport to the Rendering system GetSubsystem<Renderer>()->SetViewport(0, viewport); /// That's the camera creation taken care of... /// Next we'll add a "Zone" component. /// This component provides ambient light and fog. /// Without a Zone, and with no other sources of light, our scene will remain totally black... /// Our scene objects don't need to be children of the zone to fall within its volume... Node* zoneNode = gameScene_->CreateChild("My Zone"); auto* zone = zoneNode->CreateComponent<Zone>(); /// Set Ambient Light (RGB) to soft white, almost black zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f)); /// Set up Fog zone->SetFogColor(Color(0.5f, 0.5f, 0.7f)); zone->SetFogStart(80.0f); zone->SetFogEnd(100.0f); /// Provide the extents (or size) of the Zone BoundingBox zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f)); /// Create "the floor" using a StaticModel component with its own transform node /// We'll use "Scale" to stretch a "unit cube" model to form the floor. /// First we create our node, and may as well set up its transform Node* floorNode = gameScene_->CreateChild("Floor"); floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f)); floorNode->SetScale(Vector3(100.0f, 1.0f, 100.0f)); /// Then we attach our component to the node auto* object = floorNode->CreateComponent<StaticModel>(); /// We'll manually set up a Model and Material for this simple entity /// Urho provides some assets we can play with while getting started... auto* cache = GetSubsystem<ResourceCache>(); object->SetModel(cache->GetResource<Model>("Models/Box.mdl")); object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml")); URHO3D_LOGINFO("OK! Our application is now ready to rock!"); // Set mouse behaviour: //GetSubsystem<Input>()->SetMouseMode(MM_RELATIVE); // GetSubsystem<Input>()->SetMouseVisible(true); } /// A keyboard press was detected.. /// This "event handler" will be triggered to respond to that particular event. // void HandleKeyDown(StringHash eventType, VariantMap& eventData) { using namespace KeyDown; // Check KeyPress. Note the engine_ member variable for convenience access to the Engine object int key = eventData[P_KEY].GetInt(); if (key == KEY_ESCAPE) // Escape key to quit application engine_->Exit(); else if(key==KEY_TAB) // toggle mouse cursor visibility { auto* input = GetSubsystem<Input>(); input->SetMouseVisible(!input->IsMouseVisible()); } /// TAKE SCREEN SHOT else if(key==KEY_BACKSPACE) { // Create temporary Urho3D::Image object to receive screenshot Image screenshot(context_); // Take screen shot GetSubsystem<Graphics>()->TakeScreenShot(screenshot); // Save image to file screenshot.SavePNG("ScreenShot.png"); } /// LOAD SCENE FROM XML FILE else if(key==KEY_F11){ /// Open a SceneFile for Loading Urho3D::File file(context_, "MyGameScene.xml", FILE_READ); if(file.IsOpen()) { bool success = gameScene_->LoadXML(file); if(success) { /// When the new scene is loaded, the old one is destroyed! /// gameScene_ is still valid, but the scene has changed. /// Our cameraNode_ is invalid, and our viewport, is trashed. /// We need to restore them! /// Locate our camera node in the reloaded scene cameraNode_ = gameScene_->GetChild("Camera Node"); /// Access our camera component auto* camera = cameraNode_->GetComponent<Camera>(); /// Restore our viewport WeakPtr<Viewport> viewport (new Viewport(context_, gameScene_, camera)); GetSubsystem<Renderer>()->SetViewport(0, viewport); } file.Close(); } } /// SAVE SCENE TO XML FILE else if(key==KEY_F12){ // Dump our Scene to disk, so we can use it to load from in future Urho3D::File file(context_, "MyGameScene.xml", FILE_WRITE); gameScene_->SaveXML(file); file.Close(); } } /// Our scene object - we used "new" - we very much own it, so we use a SharedPtr to hold it /// This object will live until our MyApp object is about to be destroyed /// at which point SharedPtr will delete it. SharedPtr<Scene> gameScene_; /// Our camera control node, used to rotate and translate our camera /// We don't own nodes or components, scenes do... /// Since "its not ours", we store it in a WeakPtr /// Why not just store it in a naked Node* ??? /// Because if the node was for any reason destroyed "somewhere else", we'd never know, /// and the next time we tried to access the pointer, we'd crash badly. /// At least with a weak pointer, you will end up landing in a "null pointer exception" /// which is a massive clue that your weakptr became invalidated... /// WeakPtr lets you at least check before you try to use a bad pointer /// eg "if (cameraNode_ != nullptr) doStuff();" WeakPtr<Node> cameraNode_; }; URHO3D_DEFINE_APPLICATION_MAIN(MyApp)
45.439614
117
0.628535
LeithKetchell
cd9fe4880ed50f3bbe02a66218e41d53daff8b16
2,240
hpp
C++
common/util/rviz_plugins/autoware_vehicle_rviz_plugin/src/tools/steering_angle.hpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
1
2022-03-09T05:53:04.000Z
2022-03-09T05:53:04.000Z
common/util/rviz_plugins/autoware_vehicle_rviz_plugin/src/tools/steering_angle.hpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
4
2022-01-07T21:21:04.000Z
2022-03-14T21:25:37.000Z
common/util/rviz_plugins/autoware_vehicle_rviz_plugin/src/tools/steering_angle.hpp
loop-perception/AutowareArchitectureProposal.iv
5d8dff0db51634f0c42d2a3e87ca423fbee84348
[ "Apache-2.0" ]
2
2021-03-09T00:20:39.000Z
2021-04-16T10:23:36.000Z
// Copyright 2020 Tier IV, 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. #ifndef TOOLS__STEERING_ANGLE_HPP_ #define TOOLS__STEERING_ANGLE_HPP_ #include <memory> #include <mutex> #ifndef Q_MOC_RUN #include "jsk_overlay_utils.hpp" #include <rviz_common/properties/color_property.hpp> #include <rviz_common/properties/float_property.hpp> #include <rviz_common/properties/int_property.hpp> #include <rviz_common/ros_topic_display.hpp> #include <autoware_vehicle_msgs/msg/steering.hpp> #endif namespace rviz_plugins { class SteeringAngleDisplay : public rviz_common::RosTopicDisplay<autoware_vehicle_msgs::msg::Steering> { Q_OBJECT public: SteeringAngleDisplay(); ~SteeringAngleDisplay() override; void onInitialize() override; void onDisable() override; void onEnable() override; private Q_SLOTS: void updateVisualization(); protected: void update(float wall_dt, float ros_dt) override; void processMessage(const autoware_vehicle_msgs::msg::Steering::ConstSharedPtr msg_ptr) override; jsk_rviz_plugins::OverlayObject::Ptr overlay_; rviz_common::properties::ColorProperty * property_text_color_; rviz_common::properties::IntProperty * property_left_; rviz_common::properties::IntProperty * property_top_; rviz_common::properties::IntProperty * property_length_; rviz_common::properties::FloatProperty * property_handle_angle_scale_; rviz_common::properties::IntProperty * property_value_height_offset_; rviz_common::properties::FloatProperty * property_value_scale_; QPixmap handle_image_; // QImage hud_; private: std::mutex mutex_; autoware_vehicle_msgs::msg::Steering::ConstSharedPtr last_msg_ptr_; }; } // namespace rviz_plugins #endif // TOOLS__STEERING_ANGLE_HPP_
30.684932
99
0.789286
loop-perception
cda2e263fa9b65e7637b4ab7e7d4f559eeac87a0
552
cpp
C++
ugly-number-ii/solution-1.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
ugly-number-ii/solution-1.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
ugly-number-ii/solution-1.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
class Solution { public: int nthUglyNumber(int n) { int indices[] = {0, 0, 0}; int primes[] = {2, 3, 5}; int uglyNumbers[n]; uglyNumbers[0] = 1; for (int i = 1; i < n; ++i) { int minVal = INT_MAX; for (int j = 0; j < 3; ++j) { minVal = min(minVal, uglyNumbers[indices[j]] * primes[j]); } uglyNumbers[i] = minVal; for (int j = 0; j < 3; ++j) { if (uglyNumbers[indices[j]] * primes[j] == minVal) { indices[j]++; } } } return uglyNumbers[n - 1]; } };
24
67
0.472826
tsenmu
cda6263fcc74bdd940839ef0ce12fb718c862bfb
1,887
cpp
C++
gui/frequencytickbuilder.cpp
keur/prettyeq
c6d300b9070da3a35c4c534120361feb920c98ef
[ "BSD-3-Clause" ]
167
2020-08-31T00:05:03.000Z
2022-01-12T19:14:53.000Z
gui/frequencytickbuilder.cpp
keur/prettyeq
c6d300b9070da3a35c4c534120361feb920c98ef
[ "BSD-3-Clause" ]
2
2020-09-29T00:05:08.000Z
2021-04-22T12:52:49.000Z
gui/frequencytickbuilder.cpp
keur/prettyeq
c6d300b9070da3a35c4c534120361feb920c98ef
[ "BSD-3-Clause" ]
2
2020-09-27T14:25:58.000Z
2021-02-18T19:41:23.000Z
#include "frequencytick.h" #include "frequencytickbuilder.h" #include "macro.h" #include <QGraphicsScene> FrequencyTickBuilder::FrequencyTickBuilder(QGraphicsScene *scene, int width, int xmin, int xmax, int ymin, int ymax) { /* y-axis frequency markers */ int tickWidth = width / (NUM_TICKS - 1); tick[0] = new FrequencyTick(scene, xmin, ymin, ymax, F1); tick[1] = new FrequencyTick(scene, xmin + tickWidth * 1, ymin, ymax, F2); tick[2] = new FrequencyTick(scene, xmin + tickWidth * 2, ymin, ymax, F3); tick[3] = new FrequencyTick(scene, xmin + tickWidth * 3, ymin, ymax, F4); tick[4] = new FrequencyTick(scene, xmin + tickWidth * 4, ymin, ymax, F5); tick[5] = new FrequencyTick(scene, xmin + tickWidth * 5, ymin, ymax, F6); tick[6] = new FrequencyTick(scene, xmin + tickWidth * 6, ymin, ymax, F7); tick[7] = new FrequencyTick(scene, xmin + tickWidth * 7, ymin, ymax, F8); tick[8] = new FrequencyTick(scene, xmin + tickWidth * 8, ymin, ymax, F9); tick[9] = new FrequencyTick(scene, xmax, ymin, ymax, F10); } qreal FrequencyTickBuilder::lerpTick(qreal x) { FrequencyTick *tp, *tq; for (int i = 1; i < NUM_TICKS; i++) { tp = tick[i-1]; tq = tick[i]; if (x >= tp->getX() && x <= tq->getX()) break; } return LINEAR_REMAP(x, tp->getX(), tq->getX(), tp->getFrequency(), tq->getFrequency()); } qreal FrequencyTickBuilder::unlerpTick(qreal f) { FrequencyTick *tp, *tq; for (int i = 1; i < NUM_TICKS; i++) { tp = tick[i-1]; tq = tick[i]; if (f >= tp->getFrequency() && f <= tq->getFrequency()) break; } return LINEAR_REMAP(f, tp->getFrequency(), tq->getFrequency(), tp->getX(), tq->getX()); } FrequencyTickBuilder::~FrequencyTickBuilder() { for (int i = 0; i < NUM_TICKS; i++) delete tick[i]; }
36.288462
116
0.601484
keur
cda65c29255d279c84208b589e0e9b7176944a90
125,285
hpp
C++
include/third_party/fmt/format.hpp
BenBE/bun
027275d5e2b392a57610842a084a3809d1a23804
[ "BSD-3-Clause" ]
null
null
null
include/third_party/fmt/format.hpp
BenBE/bun
027275d5e2b392a57610842a084a3809d1a23804
[ "BSD-3-Clause" ]
null
null
null
include/third_party/fmt/format.hpp
BenBE/bun
027275d5e2b392a57610842a084a3809d1a23804
[ "BSD-3-Clause" ]
null
null
null
/* Formatting library for C++ Copyright (c) 2012 - 2016, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FMT_FORMAT_H_ #define FMT_FORMAT_H_ #include <cassert> #include <clocale> #include <cmath> #include <cstdio> #include <cstring> #include <limits> #include <memory> #include <stdexcept> #include <string> #include <vector> #include <utility> #ifdef _SECURE_SCL # define FMT_SECURE_SCL _SECURE_SCL #else # define FMT_SECURE_SCL 0 #endif #if FMT_SECURE_SCL # include <iterator> #endif #if defined(_MSC_VER) && _MSC_VER <= 1500 typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; typedef __int64 intmax_t; #else #include <stdint.h> #endif // #define FMT_HEADER_ONLY #if !defined(FMT_HEADER_ONLY) && defined(_WIN32) # ifdef FMT_EXPORT # define FMT_API __declspec(dllexport) # elif defined(FMT_SHARED) # define FMT_API __declspec(dllimport) # endif #endif #ifndef FMT_API # define FMT_API #endif #ifdef __GNUC__ # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) # define FMT_GCC_EXTENSION __extension__ # if FMT_GCC_VERSION >= 406 # pragma GCC diagnostic push // Disable the warning about "long long" which is sometimes reported even // when using __extension__. # pragma GCC diagnostic ignored "-Wlong-long" // Disable the warning about declaration shadowing because it affects too // many valid cases. # pragma GCC diagnostic ignored "-Wshadow" // Disable the warning about implicit conversions that may change the sign of // an integer; silencing it otherwise would require many explicit casts. # pragma GCC diagnostic ignored "-Wsign-conversion" # endif # if __cplusplus >= 201103L || defined __GXX_EXPERIMENTAL_CXX0X__ # define FMT_HAS_GXX_CXX11 1 # endif #else # define FMT_GCC_EXTENSION #endif #if defined(__INTEL_COMPILER) # define FMT_ICC_VERSION __INTEL_COMPILER #elif defined(__ICL) # define FMT_ICC_VERSION __ICL #endif #if defined(__clang__) && !defined(FMT_ICC_VERSION) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wdocumentation" #endif #ifdef __GNUC_LIBSTD__ # define FMT_GNUC_LIBSTD_VERSION (__GNUC_LIBSTD__ * 100 + __GNUC_LIBSTD_MINOR__) #endif #ifdef __has_feature # define FMT_HAS_FEATURE(x) __has_feature(x) #else # define FMT_HAS_FEATURE(x) 0 #endif #ifdef __has_builtin # define FMT_HAS_BUILTIN(x) __has_builtin(x) #else # define FMT_HAS_BUILTIN(x) 0 #endif #ifdef __has_cpp_attribute # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) #else # define FMT_HAS_CPP_ATTRIBUTE(x) 0 #endif #ifndef FMT_USE_VARIADIC_TEMPLATES // Variadic templates are available in GCC since version 4.4 // (http://gcc.gnu.org/projects/cxx0x.html) and in Visual C++ // since version 2013. # define FMT_USE_VARIADIC_TEMPLATES \ (FMT_HAS_FEATURE(cxx_variadic_templates) || \ (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800) #endif #ifndef FMT_USE_RVALUE_REFERENCES // Don't use rvalue references when compiling with clang and an old libstdc++ // as the latter doesn't provide std::move. # if defined(FMT_GNUC_LIBSTD_VERSION) && FMT_GNUC_LIBSTD_VERSION <= 402 # define FMT_USE_RVALUE_REFERENCES 0 # else # define FMT_USE_RVALUE_REFERENCES \ (FMT_HAS_FEATURE(cxx_rvalue_references) || \ (FMT_GCC_VERSION >= 403 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1600) # endif #endif #if FMT_USE_RVALUE_REFERENCES # include <utility> // for std::move #endif // Check if exceptions are disabled. #if defined(__GNUC__) && !defined(__EXCEPTIONS) # define FMT_EXCEPTIONS 0 #endif #if defined(_MSC_VER) && !_HAS_EXCEPTIONS # define FMT_EXCEPTIONS 0 #endif #ifndef FMT_EXCEPTIONS # define FMT_EXCEPTIONS 1 #endif #ifndef FMT_THROW # if FMT_EXCEPTIONS # define FMT_THROW(x) throw x # else # define FMT_THROW(x) assert(false) # endif #endif // Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature). #ifndef FMT_USE_NOEXCEPT # define FMT_USE_NOEXCEPT 0 #endif #ifndef FMT_NOEXCEPT # if FMT_EXCEPTIONS # if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \ (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || \ _MSC_VER >= 1900 # define FMT_NOEXCEPT noexcept # else # define FMT_NOEXCEPT throw() # endif # else # define FMT_NOEXCEPT # endif #endif // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #ifndef FMT_USE_DELETED_FUNCTIONS # define FMT_USE_DELETED_FUNCTIONS 0 #endif #if FMT_USE_DELETED_FUNCTIONS || FMT_HAS_FEATURE(cxx_deleted_functions) || \ (FMT_GCC_VERSION >= 404 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1800 # define FMT_DELETED_OR_UNDEFINED = delete # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&) = delete; \ TypeName& operator=(const TypeName&) = delete #else # define FMT_DELETED_OR_UNDEFINED # define FMT_DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ TypeName& operator=(const TypeName&) #endif #ifndef FMT_USE_USER_DEFINED_LITERALS // All compilers which support UDLs also support variadic templates. This // makes the fmt::literals implementation easier. However, an explicit check // for variadic templates is added here just in case. // For Intel's compiler both it and the system gcc/msc must support UDLs. # define FMT_USE_USER_DEFINED_LITERALS \ FMT_USE_VARIADIC_TEMPLATES && FMT_USE_RVALUE_REFERENCES && \ (FMT_HAS_FEATURE(cxx_user_literals) || \ (FMT_GCC_VERSION >= 407 && FMT_HAS_GXX_CXX11) || _MSC_VER >= 1900) && \ (!defined(FMT_ICC_VERSION) || FMT_ICC_VERSION >= 1500) #endif #ifndef FMT_ASSERT # define FMT_ASSERT(condition, message) assert((condition) && message) #endif #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clz) # define FMT_BUILTIN_CLZ(n) __builtin_clz(n) #endif #if FMT_GCC_VERSION >= 400 || FMT_HAS_BUILTIN(__builtin_clzll) # define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) #endif // Some compilers masquerade as both MSVC and GCC-likes or // otherwise support __builtin_clz and __builtin_clzll, so // only define FMT_BUILTIN_CLZ using the MSVC intrinsics // if the clz and clzll builtins are not available. #if defined(_MSC_VER) && !defined(FMT_BUILTIN_CLZLL) # include <intrin.h> // _BitScanReverse, _BitScanReverse64 namespace fmt { namespace internal { # pragma intrinsic(_BitScanReverse) inline uint32_t clz(uint32_t x) { unsigned long r = 0; _BitScanReverse(&r, x); assert(x != 0); // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. # pragma warning(suppress: 6102) return 31 - r; } # define FMT_BUILTIN_CLZ(n) fmt::internal::clz(n) # ifdef _WIN64 # pragma intrinsic(_BitScanReverse64) # endif inline uint32_t clzll(uint64_t x) { unsigned long r = 0; # ifdef _WIN64 _BitScanReverse64(&r, x); # else // Scan the high 32 bits. if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 - (r + 32); // Scan the low 32 bits. _BitScanReverse(&r, static_cast<uint32_t>(x)); # endif assert(x != 0); // Static analysis complains about using uninitialized data // "r", but the only way that can happen is if "x" is 0, // which the callers guarantee to not happen. # pragma warning(suppress: 6102) return 63 - r; } # define FMT_BUILTIN_CLZLL(n) fmt::internal::clzll(n) } } #endif namespace fmt { namespace internal { struct DummyInt { int data[2]; operator int() const { return 0; } }; typedef std::numeric_limits<fmt::internal::DummyInt> FPUtil; // Dummy implementations of system functions such as signbit and ecvt called // if the latter are not available. inline DummyInt signbit(...) { return DummyInt(); } inline DummyInt _ecvt_s(...) { return DummyInt(); } inline DummyInt isinf(...) { return DummyInt(); } inline DummyInt _finite(...) { return DummyInt(); } inline DummyInt isnan(...) { return DummyInt(); } inline DummyInt _isnan(...) { return DummyInt(); } // A helper function to suppress bogus "conditional expression is constant" // warnings. template <typename T> inline T check(T value) { return value; } } } // namespace fmt namespace std { // Standard permits specialization of std::numeric_limits. This specialization // is used to resolve ambiguity between isinf and std::isinf in glibc: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48891 // and the same for isnan and signbit. template <> class numeric_limits<fmt::internal::DummyInt> : public std::numeric_limits<int> { public: // Portable version of isinf. template <typename T> static bool isinfinity(T x) { using namespace fmt::internal; // The resolution "priority" is: // isinf macro > std::isinf > ::isinf > fmt::internal::isinf if (check(sizeof(isinf(x)) == sizeof(bool) || sizeof(isinf(x)) == sizeof(int))) { return isinf(x) != 0; } return !_finite(static_cast<double>(x)); } // Portable version of isnan. template <typename T> static bool isnotanumber(T x) { using namespace fmt::internal; if (check(sizeof(isnan(x)) == sizeof(bool) || sizeof(isnan(x)) == sizeof(int))) { return isnan(x) != 0; } return _isnan(static_cast<double>(x)) != 0; } // Portable version of signbit. static bool isnegative(double x) { using namespace fmt::internal; if (check(sizeof(signbit(x)) == sizeof(int))) return signbit(x) != 0; if (x < 0) return true; if (!isnotanumber(x)) return false; int dec = 0, sign = 0; char buffer[2]; // The buffer size must be >= 2 or _ecvt_s will fail. _ecvt_s(buffer, sizeof(buffer), x, 0, &dec, &sign); return sign != 0; } }; } // namespace std namespace fmt { // Fix the warning about long long on older versions of GCC // that don't support the diagnostic pragma. FMT_GCC_EXTENSION typedef long long LongLong; FMT_GCC_EXTENSION typedef unsigned long long ULongLong; #if FMT_USE_RVALUE_REFERENCES using std::move; #endif template <typename Char> class BasicWriter; typedef BasicWriter<char> Writer; typedef BasicWriter<wchar_t> WWriter; template <typename Char> class ArgFormatter; template <typename CharType, typename ArgFormatter = fmt::ArgFormatter<CharType> > class BasicFormatter; /** \rst A string reference. It can be constructed from a C string or ``std::string``. You can use one of the following typedefs for common character types: +------------+-------------------------+ | Type | Definition | +============+=========================+ | StringRef | BasicStringRef<char> | +------------+-------------------------+ | WStringRef | BasicStringRef<wchar_t> | +------------+-------------------------+ This class is most useful as a parameter type to allow passing different types of strings to a function, for example:: template <typename... Args> std::string format(StringRef format_str, const Args & ... args); format("{}", 42); format(std::string("{}"), 42); \endrst */ template <typename Char> class BasicStringRef { private: const Char *data_; std::size_t size_; public: /** Constructs a string reference object from a C string and a size. */ BasicStringRef(const Char *s, std::size_t size) : data_(s), size_(size) {} /** \rst Constructs a string reference object from a C string computing the size with ``std::char_traits<Char>::length``. \endrst */ BasicStringRef(const Char *s) : data_(s), size_(std::char_traits<Char>::length(s)) {} /** \rst Constructs a string reference from an ``std::string`` object. \endrst */ BasicStringRef(const std::basic_string<Char> &s) : data_(s.c_str()), size_(s.size()) {} /** \rst Converts a string reference to an ``std::string`` object. \endrst */ std::basic_string<Char> to_string() const { return std::basic_string<Char>(data_, size_); } /** Returns a pointer to the string data. */ const Char *data() const { return data_; } /** Returns the string size. */ std::size_t size() const { return size_; } // Lexicographically compare this string reference to other. int compare(BasicStringRef other) const { std::size_t size = size_ < other.size_ ? size_ : other.size_; int result = std::char_traits<Char>::compare(data_, other.data_, size); if (result == 0) result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); return result; } friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) == 0; } friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) != 0; } friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) < 0; } friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) <= 0; } friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) > 0; } friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) { return lhs.compare(rhs) >= 0; } }; typedef BasicStringRef<char> StringRef; typedef BasicStringRef<wchar_t> WStringRef; /** \rst A reference to a null terminated string. It can be constructed from a C string or ``std::string``. You can use one of the following typedefs for common character types: +-------------+--------------------------+ | Type | Definition | +=============+==========================+ | CStringRef | BasicCStringRef<char> | +-------------+--------------------------+ | WCStringRef | BasicCStringRef<wchar_t> | +-------------+--------------------------+ This class is most useful as a parameter type to allow passing different types of strings to a function, for example:: template <typename... Args> std::string format(CStringRef format_str, const Args & ... args); format("{}", 42); format(std::string("{}"), 42); \endrst */ template <typename Char> class BasicCStringRef { private: const Char *data_; public: /** Constructs a string reference object from a C string. */ BasicCStringRef(const Char *s) : data_(s) {} /** \rst Constructs a string reference from an ``std::string`` object. \endrst */ BasicCStringRef(const std::basic_string<Char> &s) : data_(s.c_str()) {} /** Returns the pointer to a C string. */ const Char *c_str() const { return data_; } }; typedef BasicCStringRef<char> CStringRef; typedef BasicCStringRef<wchar_t> WCStringRef; /** A formatting error such as invalid format string. */ class FormatError : public std::runtime_error { public: explicit FormatError(CStringRef message) : std::runtime_error(message.c_str()) {} }; namespace internal { // MakeUnsigned<T>::Type gives an unsigned type corresponding to integer type T. template <typename T> struct MakeUnsigned { typedef T Type; }; #define FMT_SPECIALIZE_MAKE_UNSIGNED(T, U) \ template <> \ struct MakeUnsigned<T> { typedef U Type; } FMT_SPECIALIZE_MAKE_UNSIGNED(char, unsigned char); FMT_SPECIALIZE_MAKE_UNSIGNED(signed char, unsigned char); FMT_SPECIALIZE_MAKE_UNSIGNED(short, unsigned short); FMT_SPECIALIZE_MAKE_UNSIGNED(int, unsigned); FMT_SPECIALIZE_MAKE_UNSIGNED(long, unsigned long); FMT_SPECIALIZE_MAKE_UNSIGNED(LongLong, ULongLong); // Casts nonnegative integer to unsigned. template <typename Int> inline typename MakeUnsigned<Int>::Type to_unsigned(Int value) { FMT_ASSERT(value >= 0, "negative value"); return static_cast<typename MakeUnsigned<Int>::Type>(value); } // The number of characters to store in the MemoryBuffer object itself // to avoid dynamic memory allocation. enum { INLINE_BUFFER_SIZE = 500 }; #if FMT_SECURE_SCL // Use checked iterator to avoid warnings on MSVC. template <typename T> inline stdext::checked_array_iterator<T*> make_ptr(T *ptr, std::size_t size) { return stdext::checked_array_iterator<T*>(ptr, size); } #else template <typename T> inline T *make_ptr(T *ptr, std::size_t) { return ptr; } #endif } // namespace internal /** \rst A buffer supporting a subset of ``std::vector``'s operations. \endrst */ template <typename T> class Buffer { private: FMT_DISALLOW_COPY_AND_ASSIGN(Buffer); protected: T *ptr_; std::size_t size_; std::size_t capacity_; Buffer(T *ptr = 0, std::size_t capacity = 0) : ptr_(ptr), size_(0), capacity_(capacity) {} /** \rst Increases the buffer capacity to hold at least *size* elements updating ``ptr_`` and ``capacity_``. \endrst */ virtual void grow(std::size_t size) = 0; public: virtual ~Buffer() {} /** Returns the size of this buffer. */ std::size_t size() const { return size_; } /** Returns the capacity of this buffer. */ std::size_t capacity() const { return capacity_; } /** Resizes the buffer. If T is a POD type new elements may not be initialized. */ void resize(std::size_t new_size) { if (new_size > capacity_) grow(new_size); size_ = new_size; } /** \rst Reserves space to store at least *capacity* elements. \endrst */ void reserve(std::size_t capacity) { if (capacity > capacity_) grow(capacity); } void clear() FMT_NOEXCEPT { size_ = 0; } void push_back(const T &value) { if (size_ == capacity_) grow(size_ + 1); ptr_[size_++] = value; } /** Appends data to the end of the buffer. */ template <typename U> void append(const U *begin, const U *end); T &operator[](std::size_t index) { return ptr_[index]; } const T &operator[](std::size_t index) const { return ptr_[index]; } }; template <typename T> template <typename U> void Buffer<T>::append(const U *begin, const U *end) { std::size_t new_size = size_ + internal::to_unsigned(end - begin); if (new_size > capacity_) grow(new_size); std::uninitialized_copy(begin, end, internal::make_ptr(ptr_, capacity_) + size_); size_ = new_size; } namespace internal { // A memory buffer for trivially copyable/constructible types with the first SIZE // elements stored in the object itself. template <typename T, std::size_t SIZE, typename Allocator = std::allocator<T> > class MemoryBuffer : private Allocator, public Buffer<T> { private: T data_[SIZE]; // Deallocate memory allocated by the buffer. void deallocate() { if (this->ptr_ != data_) Allocator::deallocate(this->ptr_, this->capacity_); } protected: void grow(std::size_t size); public: explicit MemoryBuffer(const Allocator &alloc = Allocator()) : Allocator(alloc), Buffer<T>(data_, SIZE) {} ~MemoryBuffer() { deallocate(); } #if FMT_USE_RVALUE_REFERENCES private: // Move data from other to this buffer. void move(MemoryBuffer &other) { Allocator &this_alloc = *this, &other_alloc = other; this_alloc = std::move(other_alloc); this->size_ = other.size_; this->capacity_ = other.capacity_; if (other.ptr_ == other.data_) { this->ptr_ = data_; std::uninitialized_copy(other.data_, other.data_ + this->size_, make_ptr(data_, this->capacity_)); } else { this->ptr_ = other.ptr_; // Set pointer to the inline array so that delete is not called // when deallocating. other.ptr_ = other.data_; } } public: MemoryBuffer(MemoryBuffer &&other) { move(other); } MemoryBuffer &operator=(MemoryBuffer &&other) { assert(this != &other); deallocate(); move(other); return *this; } #endif // Returns a copy of the allocator associated with this buffer. Allocator get_allocator() const { return *this; } }; template <typename T, std::size_t SIZE, typename Allocator> void MemoryBuffer<T, SIZE, Allocator>::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) new_capacity = size; T *new_ptr = this->allocate(new_capacity); // The following code doesn't throw, so the raw pointer above doesn't leak. std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity)); std::size_t old_capacity = this->capacity_; T *old_ptr = this->ptr_; this->capacity_ = new_capacity; this->ptr_ = new_ptr; // deallocate may throw (at least in principle), but it doesn't matter since // the buffer already uses the new storage and will deallocate it in case // of exception. if (old_ptr != data_) Allocator::deallocate(old_ptr, old_capacity); } // A fixed-size buffer. template <typename Char> class FixedBuffer : public fmt::Buffer<Char> { public: FixedBuffer(Char *array, std::size_t size) : fmt::Buffer<Char>(array, size) {} protected: FMT_API void grow(std::size_t size); }; template <typename Char> class BasicCharTraits { public: #if FMT_SECURE_SCL typedef stdext::checked_array_iterator<Char*> CharPtr; #else typedef Char *CharPtr; #endif static Char cast(int value) { return static_cast<Char>(value); } }; template <typename Char> class CharTraits; template <> class CharTraits<char> : public BasicCharTraits<char> { private: // Conversion from wchar_t to char is not allowed. static char convert(wchar_t); public: static char convert(char value) { return value; } // Formats a floating-point number. template <typename T> FMT_API static int format_float(char *buffer, std::size_t size, const char *format, unsigned width, int precision, T value); }; template <> class CharTraits<wchar_t> : public BasicCharTraits<wchar_t> { public: static wchar_t convert(char value) { return value; } static wchar_t convert(wchar_t value) { return value; } template <typename T> FMT_API static int format_float(wchar_t *buffer, std::size_t size, const wchar_t *format, unsigned width, int precision, T value); }; // Checks if a number is negative - used to avoid warnings. template <bool IsSigned> struct SignChecker { template <typename T> static bool is_negative(T value) { return value < 0; } }; template <> struct SignChecker<false> { template <typename T> static bool is_negative(T) { return false; } }; // Returns true if value is negative, false otherwise. // Same as (value < 0) but doesn't produce warnings if T is an unsigned type. template <typename T> inline bool is_negative(T value) { return SignChecker<std::numeric_limits<T>::is_signed>::is_negative(value); } // Selects uint32_t if FitsIn32Bits is true, uint64_t otherwise. template <bool FitsIn32Bits> struct TypeSelector { typedef uint32_t Type; }; template <> struct TypeSelector<false> { typedef uint64_t Type; }; template <typename T> struct IntTraits { // Smallest of uint32_t and uint64_t that is large enough to represent // all values of T. typedef typename TypeSelector<std::numeric_limits<T>::digits <= 32>::Type MainType; }; FMT_API void report_unknown_type(char code, const char *type); // Static data is placed in this class template to allow header-only // configuration. template <typename T = void> struct FMT_API BasicData { static const uint32_t POWERS_OF_10_32[]; static const uint64_t POWERS_OF_10_64[]; static const char DIGITS[]; }; typedef BasicData<> Data; #ifdef FMT_BUILTIN_CLZLL // Returns the number of decimal digits in n. Leading zeros are not counted // except for n == 0 in which case count_digits returns 1. inline unsigned count_digits(uint64_t n) { // Based on http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 // and the benchmark https://github.com/localvoid/cxx-benchmark-count-digits. int t = (64 - FMT_BUILTIN_CLZLL(n | 1)) * 1233 >> 12; return to_unsigned(t) - (n < Data::POWERS_OF_10_64[t]) + 1; } #else // Fallback version of count_digits used when __builtin_clz is not available. inline unsigned count_digits(uint64_t n) { unsigned count = 1; for (;;) { // Integer division is slow so do it for a group of four digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. if (n < 10) return count; if (n < 100) return count + 1; if (n < 1000) return count + 2; if (n < 10000) return count + 3; n /= 10000u; count += 4; } } #endif #ifdef FMT_BUILTIN_CLZ // Optional version of count_digits for better performance on 32-bit platforms. inline unsigned count_digits(uint32_t n) { int t = (32 - FMT_BUILTIN_CLZ(n | 1)) * 1233 >> 12; return to_unsigned(t) - (n < Data::POWERS_OF_10_32[t]) + 1; } #endif // A functor that doesn't add a thousands separator. struct NoThousandsSep { template <typename Char> void operator()(Char *) {} }; // A functor that adds a thousands separator. class ThousandsSep { private: fmt::StringRef sep_; // Index of a decimal digit with the least significant digit having index 0. unsigned digit_index_; public: explicit ThousandsSep(fmt::StringRef sep) : sep_(sep), digit_index_(0) {} template <typename Char> void operator()(Char *&buffer) { if (++digit_index_ % 3 != 0) return; buffer -= sep_.size(); std::uninitialized_copy(sep_.data(), sep_.data() + sep_.size(), internal::make_ptr(buffer, sep_.size())); } }; // Formats a decimal unsigned integer value writing into buffer. // thousands_sep is a functor that is called after writing each char to // add a thousands separator if necessary. template <typename UInt, typename Char, typename ThousandsSep> inline void format_decimal(Char *buffer, UInt value, unsigned num_digits, ThousandsSep thousands_sep) { buffer += num_digits; while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = static_cast<unsigned>((value % 100) * 2); value /= 100; *--buffer = Data::DIGITS[index + 1]; thousands_sep(buffer); *--buffer = Data::DIGITS[index]; thousands_sep(buffer); } if (value < 10) { *--buffer = static_cast<char>('0' + value); return; } unsigned index = static_cast<unsigned>(value * 2); *--buffer = Data::DIGITS[index + 1]; *--buffer = Data::DIGITS[index]; } template <typename UInt, typename Char> inline void format_decimal(Char *buffer, UInt value, unsigned num_digits) { return format_decimal(buffer, value, num_digits, NoThousandsSep()); } #ifndef _WIN32 # define FMT_USE_WINDOWS_H 0 #elif !defined(FMT_USE_WINDOWS_H) # define FMT_USE_WINDOWS_H 1 #endif // Define FMT_USE_WINDOWS_H to 0 to disable use of windows.h. // All the functionality that relies on it will be disabled too. #if FMT_USE_WINDOWS_H // A converter from UTF-8 to UTF-16. // It is only provided for Windows since other systems support UTF-8 natively. class UTF8ToUTF16 { private: MemoryBuffer<wchar_t, INLINE_BUFFER_SIZE> buffer_; public: FMT_API explicit UTF8ToUTF16(StringRef s); operator WStringRef() const { return WStringRef(&buffer_[0], size()); } size_t size() const { return buffer_.size() - 1; } const wchar_t *c_str() const { return &buffer_[0]; } std::wstring str() const { return std::wstring(&buffer_[0], size()); } }; // A converter from UTF-16 to UTF-8. // It is only provided for Windows since other systems support UTF-8 natively. class UTF16ToUTF8 { private: MemoryBuffer<char, INLINE_BUFFER_SIZE> buffer_; public: UTF16ToUTF8() {} FMT_API explicit UTF16ToUTF8(WStringRef s); operator StringRef() const { return StringRef(&buffer_[0], size()); } size_t size() const { return buffer_.size() - 1; } const char *c_str() const { return &buffer_[0]; } std::string str() const { return std::string(&buffer_[0], size()); } // Performs conversion returning a system error code instead of // throwing exception on conversion error. This method may still throw // in case of memory allocation error. FMT_API int convert(WStringRef s); }; FMT_API void format_windows_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; #endif FMT_API void format_system_error(fmt::Writer &out, int error_code, fmt::StringRef message) FMT_NOEXCEPT; // A formatting argument value. struct Value { template <typename Char> struct StringValue { const Char *value; std::size_t size; }; typedef void (*FormatFunc)( void *formatter, const void *arg, void *format_str_ptr); struct CustomValue { const void *value; FormatFunc format; }; union { int int_value; unsigned uint_value; LongLong long_long_value; ULongLong ulong_long_value; double double_value; long double long_double_value; const void *pointer; StringValue<char> string; StringValue<signed char> sstring; StringValue<unsigned char> ustring; StringValue<wchar_t> wstring; CustomValue custom; }; enum Type { NONE, NAMED_ARG, // Integer types should go first, INT, UINT, LONG_LONG, ULONG_LONG, BOOL, CHAR, LAST_INTEGER_TYPE = CHAR, // followed by floating-point types. DOUBLE, LONG_DOUBLE, LAST_NUMERIC_TYPE = LONG_DOUBLE, CSTRING, STRING, WSTRING, POINTER, CUSTOM }; }; // A formatting argument. It is a trivially copyable/constructible type to // allow storage in internal::MemoryBuffer. struct Arg : Value { Type type; }; template <typename Char> struct NamedArg; template <typename T = void> struct Null {}; // A helper class template to enable or disable overloads taking wide // characters and strings in MakeValue. template <typename T, typename Char> struct WCharHelper { typedef Null<T> Supported; typedef T Unsupported; }; template <typename T> struct WCharHelper<T, wchar_t> { typedef T Supported; typedef Null<T> Unsupported; }; typedef char Yes[1]; typedef char No[2]; template <typename T> T &get(); // These are non-members to workaround an overload resolution bug in bcc32. Yes &convert(fmt::ULongLong); No &convert(...); template<typename T, bool ENABLE_CONVERSION> struct ConvertToIntImpl { enum { value = ENABLE_CONVERSION }; }; template<typename T, bool ENABLE_CONVERSION> struct ConvertToIntImpl2 { enum { value = false }; }; template<typename T> struct ConvertToIntImpl2<T, true> { enum { // Don't convert numeric types. value = ConvertToIntImpl<T, !std::numeric_limits<T>::is_specialized>::value }; }; template<typename T> struct ConvertToInt { enum { enable_conversion = sizeof(convert(get<T>())) == sizeof(Yes) }; enum { value = ConvertToIntImpl2<T, enable_conversion>::value }; }; #define FMT_DISABLE_CONVERSION_TO_INT(Type) \ template <> \ struct ConvertToInt<Type> { enum { value = 0 }; } // Silence warnings about convering float to int. FMT_DISABLE_CONVERSION_TO_INT(float); FMT_DISABLE_CONVERSION_TO_INT(double); FMT_DISABLE_CONVERSION_TO_INT(long double); template<bool B, class T = void> struct EnableIf {}; template<class T> struct EnableIf<true, T> { typedef T type; }; template<bool B, class T, class F> struct Conditional { typedef T type; }; template<class T, class F> struct Conditional<false, T, F> { typedef F type; }; // For bcc32 which doesn't understand ! in template arguments. template<bool> struct Not { enum { value = 0 }; }; template<> struct Not<false> { enum { value = 1 }; }; // Makes an Arg object from any type. template <typename Formatter> class MakeValue : public Arg { public: typedef typename Formatter::Char Char; private: // The following two methods are private to disallow formatting of // arbitrary pointers. If you want to output a pointer cast it to // "void *" or "const void *". In particular, this forbids formatting // of "[const] volatile char *" which is printed as bool by iostreams. // Do not implement! template <typename T> MakeValue(const T *value); template <typename T> MakeValue(T *value); // The following methods are private to disallow formatting of wide // characters and strings into narrow strings as in // fmt::format("{}", L"test"); // To fix this, use a wide format string: fmt::format(L"{}", L"test"). #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) MakeValue(typename WCharHelper<wchar_t, Char>::Unsupported); #endif MakeValue(typename WCharHelper<wchar_t *, Char>::Unsupported); MakeValue(typename WCharHelper<const wchar_t *, Char>::Unsupported); MakeValue(typename WCharHelper<const std::wstring &, Char>::Unsupported); MakeValue(typename WCharHelper<WStringRef, Char>::Unsupported); void set_string(StringRef str) { string.value = str.data(); string.size = str.size(); } void set_string(WStringRef str) { wstring.value = str.data(); wstring.size = str.size(); } // Formats an argument of a custom type, such as a user-defined class. template <typename T> static void format_custom_arg( void *formatter, const void *arg, void *format_str_ptr) { format(*static_cast<Formatter*>(formatter), *static_cast<const Char**>(format_str_ptr), *static_cast<const T*>(arg)); } public: MakeValue() {} #define FMT_MAKE_VALUE_(Type, field, TYPE, rhs) \ MakeValue(Type value) { field = rhs; } \ static uint64_t type(Type) { return Arg::TYPE; } #define FMT_MAKE_VALUE(Type, field, TYPE) \ FMT_MAKE_VALUE_(Type, field, TYPE, value) FMT_MAKE_VALUE(bool, int_value, BOOL) FMT_MAKE_VALUE(short, int_value, INT) FMT_MAKE_VALUE(unsigned short, uint_value, UINT) FMT_MAKE_VALUE(int, int_value, INT) FMT_MAKE_VALUE(unsigned, uint_value, UINT) MakeValue(long value) { // To minimize the number of types we need to deal with, long is // translated either to int or to long long depending on its size. if (check(sizeof(long) == sizeof(int))) int_value = static_cast<int>(value); else long_long_value = value; } static uint64_t type(long) { return sizeof(long) == sizeof(int) ? Arg::INT : Arg::LONG_LONG; } MakeValue(unsigned long value) { if (check(sizeof(unsigned long) == sizeof(unsigned))) uint_value = static_cast<unsigned>(value); else ulong_long_value = value; } static uint64_t type(unsigned long) { return sizeof(unsigned long) == sizeof(unsigned) ? Arg::UINT : Arg::ULONG_LONG; } FMT_MAKE_VALUE(LongLong, long_long_value, LONG_LONG) FMT_MAKE_VALUE(ULongLong, ulong_long_value, ULONG_LONG) FMT_MAKE_VALUE(float, double_value, DOUBLE) FMT_MAKE_VALUE(double, double_value, DOUBLE) FMT_MAKE_VALUE(long double, long_double_value, LONG_DOUBLE) FMT_MAKE_VALUE(signed char, int_value, INT) FMT_MAKE_VALUE(unsigned char, uint_value, UINT) FMT_MAKE_VALUE(char, int_value, CHAR) #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) MakeValue(typename WCharHelper<wchar_t, Char>::Supported value) { int_value = value; } static uint64_t type(wchar_t) { return Arg::CHAR; } #endif #define FMT_MAKE_STR_VALUE(Type, TYPE) \ MakeValue(Type value) { set_string(value); } \ static uint64_t type(Type) { return Arg::TYPE; } FMT_MAKE_VALUE(char *, string.value, CSTRING) FMT_MAKE_VALUE(const char *, string.value, CSTRING) FMT_MAKE_VALUE(const signed char *, sstring.value, CSTRING) FMT_MAKE_VALUE(const unsigned char *, ustring.value, CSTRING) FMT_MAKE_STR_VALUE(const std::string &, STRING) FMT_MAKE_STR_VALUE(StringRef, STRING) FMT_MAKE_VALUE_(CStringRef, string.value, CSTRING, value.c_str()) #define FMT_MAKE_WSTR_VALUE(Type, TYPE) \ MakeValue(typename WCharHelper<Type, Char>::Supported value) { \ set_string(value); \ } \ static uint64_t type(Type) { return Arg::TYPE; } FMT_MAKE_WSTR_VALUE(wchar_t *, WSTRING) FMT_MAKE_WSTR_VALUE(const wchar_t *, WSTRING) FMT_MAKE_WSTR_VALUE(const std::wstring &, WSTRING) FMT_MAKE_WSTR_VALUE(WStringRef, WSTRING) FMT_MAKE_VALUE(void *, pointer, POINTER) FMT_MAKE_VALUE(const void *, pointer, POINTER) template <typename T> MakeValue(const T &value, typename EnableIf<Not< ConvertToInt<T>::value>::value, int>::type = 0) { custom.value = &value; custom.format = &format_custom_arg<T>; } template <typename T> MakeValue(const T &value, typename EnableIf<ConvertToInt<T>::value, int>::type = 0) { int_value = value; } template <typename T> static uint64_t type(const T &) { return ConvertToInt<T>::value ? Arg::INT : Arg::CUSTOM; } // Additional template param `Char_` is needed here because make_type always // uses char. template <typename Char_> MakeValue(const NamedArg<Char_> &value) { pointer = &value; } template <typename Char_> static uint64_t type(const NamedArg<Char_> &) { return Arg::NAMED_ARG; } }; template <typename Formatter> class MakeArg : public Arg { public: MakeArg() { type = Arg::NONE; } template <typename T> MakeArg(const T &value) : Arg(MakeValue<Formatter>(value)) { type = static_cast<Arg::Type>(MakeValue<Formatter>::type(value)); } }; template <typename Char> struct NamedArg : Arg { BasicStringRef<Char> name; template <typename T> NamedArg(BasicStringRef<Char> argname, const T &value) : Arg(MakeArg< BasicFormatter<Char> >(value)), name(argname) {} }; class RuntimeError : public std::runtime_error { protected: RuntimeError() : std::runtime_error("") {} }; template <typename Char> class PrintfArgFormatter; template <typename Char> class ArgMap; } // namespace internal /** An argument list. */ class ArgList { private: // To reduce compiled code size per formatting function call, types of first // MAX_PACKED_ARGS arguments are passed in the types_ field. uint64_t types_; union { // If the number of arguments is less than MAX_PACKED_ARGS, the argument // values are stored in values_, otherwise they are stored in args_. // This is done to reduce compiled code size as storing larger objects // may require more code (at least on x86-64) even if the same amount of // data is actually copied to stack. It saves ~10% on the bloat test. const internal::Value *values_; const internal::Arg *args_; }; internal::Arg::Type type(unsigned index) const { unsigned shift = index * 4; uint64_t mask = 0xf; return static_cast<internal::Arg::Type>( (types_ & (mask << shift)) >> shift); } template <typename Char> friend class internal::ArgMap; public: // Maximum number of arguments with packed types. enum { MAX_PACKED_ARGS = 16 }; ArgList() : types_(0) {} ArgList(ULongLong types, const internal::Value *values) : types_(types), values_(values) {} ArgList(ULongLong types, const internal::Arg *args) : types_(types), args_(args) {} /** Returns the argument at specified index. */ internal::Arg operator[](unsigned index) const { using internal::Arg; Arg arg; bool use_values = type(MAX_PACKED_ARGS - 1) == Arg::NONE; if (index < MAX_PACKED_ARGS) { Arg::Type arg_type = type(index); internal::Value &val = arg; if (arg_type != Arg::NONE) val = use_values ? values_[index] : args_[index]; arg.type = arg_type; return arg; } if (use_values) { // The index is greater than the number of arguments that can be stored // in values, so return a "none" argument. arg.type = Arg::NONE; return arg; } for (unsigned i = MAX_PACKED_ARGS; i <= index; ++i) { if (args_[i].type == Arg::NONE) return args_[i]; } return args_[index]; } }; #define FMT_DISPATCH(call) static_cast<Impl*>(this)->call /** \rst An argument visitor based on the `curiously recurring template pattern <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_. To use `~fmt::ArgVisitor` define a subclass that implements some or all of the visit methods with the same signatures as the methods in `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`. Pass the subclass as the *Impl* template parameter. Then calling `~fmt::ArgVisitor::visit` for some argument will dispatch to a visit method specific to the argument type. For example, if the argument type is ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass will be called. If the subclass doesn't contain a method with this signature, then a corresponding method of `~fmt::ArgVisitor` will be called. **Example**:: class MyArgVisitor : public fmt::ArgVisitor<MyArgVisitor, void> { public: void visit_int(int value) { fmt::print("{}", value); } void visit_double(double value) { fmt::print("{}", value ); } }; \endrst */ template <typename Impl, typename Result> class ArgVisitor { private: typedef internal::Arg Arg; public: void report_unhandled_arg() {} Result visit_unhandled_arg() { FMT_DISPATCH(report_unhandled_arg()); return Result(); } /** Visits an ``int`` argument. **/ Result visit_int(int value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits a ``long long`` argument. **/ Result visit_long_long(LongLong value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits an ``unsigned`` argument. **/ Result visit_uint(unsigned value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits an ``unsigned long long`` argument. **/ Result visit_ulong_long(ULongLong value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits a ``bool`` argument. **/ Result visit_bool(bool value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits a ``char`` or ``wchar_t`` argument. **/ Result visit_char(int value) { return FMT_DISPATCH(visit_any_int(value)); } /** Visits an argument of any integral type. **/ template <typename T> Result visit_any_int(T) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a ``double`` argument. **/ Result visit_double(double value) { return FMT_DISPATCH(visit_any_double(value)); } /** Visits a ``long double`` argument. **/ Result visit_long_double(long double value) { return FMT_DISPATCH(visit_any_double(value)); } /** Visits a ``double`` or ``long double`` argument. **/ template <typename T> Result visit_any_double(T) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a null-terminated C string (``const char *``) argument. **/ Result visit_cstring(const char *) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a string argument. **/ Result visit_string(Arg::StringValue<char>) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a wide string argument. **/ Result visit_wstring(Arg::StringValue<wchar_t>) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits a pointer argument. **/ Result visit_pointer(const void *) { return FMT_DISPATCH(visit_unhandled_arg()); } /** Visits an argument of a custom (user-defined) type. **/ Result visit_custom(Arg::CustomValue) { return FMT_DISPATCH(visit_unhandled_arg()); } /** \rst Visits an argument dispatching to the appropriate visit method based on the argument type. For example, if the argument type is ``double`` then the `~fmt::ArgVisitor::visit_double()` method of the *Impl* class will be called. \endrst */ Result visit(const Arg &arg) { switch (arg.type) { default: FMT_ASSERT(false, "invalid argument type"); return Result(); case Arg::INT: return FMT_DISPATCH(visit_int(arg.int_value)); case Arg::UINT: return FMT_DISPATCH(visit_uint(arg.uint_value)); case Arg::LONG_LONG: return FMT_DISPATCH(visit_long_long(arg.long_long_value)); case Arg::ULONG_LONG: return FMT_DISPATCH(visit_ulong_long(arg.ulong_long_value)); case Arg::BOOL: return FMT_DISPATCH(visit_bool(arg.int_value != 0)); case Arg::CHAR: return FMT_DISPATCH(visit_char(arg.int_value)); case Arg::DOUBLE: return FMT_DISPATCH(visit_double(arg.double_value)); case Arg::LONG_DOUBLE: return FMT_DISPATCH(visit_long_double(arg.long_double_value)); case Arg::CSTRING: return FMT_DISPATCH(visit_cstring(arg.string.value)); case Arg::STRING: return FMT_DISPATCH(visit_string(arg.string)); case Arg::WSTRING: return FMT_DISPATCH(visit_wstring(arg.wstring)); case Arg::POINTER: return FMT_DISPATCH(visit_pointer(arg.pointer)); case Arg::CUSTOM: return FMT_DISPATCH(visit_custom(arg.custom)); } } }; enum Alignment { ALIGN_DEFAULT, ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER, ALIGN_NUMERIC }; // Flags. enum { SIGN_FLAG = 1, PLUS_FLAG = 2, MINUS_FLAG = 4, HASH_FLAG = 8, CHAR_FLAG = 0x10 // Argument has char type - used in error reporting. }; // An empty format specifier. struct EmptySpec {}; // A type specifier. template <char TYPE> struct TypeSpec : EmptySpec { Alignment align() const { return ALIGN_DEFAULT; } unsigned width() const { return 0; } int precision() const { return -1; } bool flag(unsigned) const { return false; } char type() const { return TYPE; } char fill() const { return ' '; } }; // A width specifier. struct WidthSpec { unsigned width_; // Fill is always wchar_t and cast to char if necessary to avoid having // two specialization of WidthSpec and its subclasses. wchar_t fill_; WidthSpec(unsigned width, wchar_t fill) : width_(width), fill_(fill) {} unsigned width() const { return width_; } wchar_t fill() const { return fill_; } }; // An alignment specifier. struct AlignSpec : WidthSpec { Alignment align_; AlignSpec(unsigned width, wchar_t fill, Alignment align = ALIGN_DEFAULT) : WidthSpec(width, fill), align_(align) {} Alignment align() const { return align_; } int precision() const { return -1; } }; // An alignment and type specifier. template <char TYPE> struct AlignTypeSpec : AlignSpec { AlignTypeSpec(unsigned width, wchar_t fill) : AlignSpec(width, fill) {} bool flag(unsigned) const { return false; } char type() const { return TYPE; } }; // A full format specifier. struct FormatSpec : AlignSpec { unsigned flags_; int precision_; char type_; FormatSpec( unsigned width = 0, char type = 0, wchar_t fill = ' ') : AlignSpec(width, fill), flags_(0), precision_(-1), type_(type) {} bool flag(unsigned f) const { return (flags_ & f) != 0; } int precision() const { return precision_; } char type() const { return type_; } }; // An integer format specifier. template <typename T, typename SpecT = TypeSpec<0>, typename Char = char> class IntFormatSpec : public SpecT { private: T value_; public: IntFormatSpec(T val, const SpecT &spec = SpecT()) : SpecT(spec), value_(val) {} T value() const { return value_; } }; // A string format specifier. template <typename Char> class StrFormatSpec : public AlignSpec { private: const Char *str_; public: template <typename FillChar> StrFormatSpec(const Char *str, unsigned width, FillChar fill) : AlignSpec(width, fill), str_(str) { internal::CharTraits<Char>::convert(FillChar()); } const Char *str() const { return str_; } }; /** Returns an integer format specifier to format the value in base 2. */ IntFormatSpec<int, TypeSpec<'b'> > bin(int value); /** Returns an integer format specifier to format the value in base 8. */ IntFormatSpec<int, TypeSpec<'o'> > oct(int value); /** Returns an integer format specifier to format the value in base 16 using lower-case letters for the digits above 9. */ IntFormatSpec<int, TypeSpec<'x'> > hex(int value); /** Returns an integer formatter format specifier to format in base 16 using upper-case letters for the digits above 9. */ IntFormatSpec<int, TypeSpec<'X'> > hexu(int value); /** \rst Returns an integer format specifier to pad the formatted argument with the fill character to the specified width using the default (right) numeric alignment. **Example**:: MemoryWriter out; out << pad(hex(0xcafe), 8, '0'); // out.str() == "0000cafe" \endrst */ template <char TYPE_CODE, typename Char> IntFormatSpec<int, AlignTypeSpec<TYPE_CODE>, Char> pad( int value, unsigned width, Char fill = ' '); #define FMT_DEFINE_INT_FORMATTERS(TYPE) \ inline IntFormatSpec<TYPE, TypeSpec<'b'> > bin(TYPE value) { \ return IntFormatSpec<TYPE, TypeSpec<'b'> >(value, TypeSpec<'b'>()); \ } \ \ inline IntFormatSpec<TYPE, TypeSpec<'o'> > oct(TYPE value) { \ return IntFormatSpec<TYPE, TypeSpec<'o'> >(value, TypeSpec<'o'>()); \ } \ \ inline IntFormatSpec<TYPE, TypeSpec<'x'> > hex(TYPE value) { \ return IntFormatSpec<TYPE, TypeSpec<'x'> >(value, TypeSpec<'x'>()); \ } \ \ inline IntFormatSpec<TYPE, TypeSpec<'X'> > hexu(TYPE value) { \ return IntFormatSpec<TYPE, TypeSpec<'X'> >(value, TypeSpec<'X'>()); \ } \ \ template <char TYPE_CODE> \ inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> > pad( \ IntFormatSpec<TYPE, TypeSpec<TYPE_CODE> > f, unsigned width) { \ return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE> >( \ f.value(), AlignTypeSpec<TYPE_CODE>(width, ' ')); \ } \ \ /* For compatibility with older compilers we provide two overloads for pad, */ \ /* one that takes a fill character and one that doesn't. In the future this */ \ /* can be replaced with one overload making the template argument Char */ \ /* default to char (C++11). */ \ template <char TYPE_CODE, typename Char> \ inline IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char> pad( \ IntFormatSpec<TYPE, TypeSpec<TYPE_CODE>, Char> f, \ unsigned width, Char fill) { \ return IntFormatSpec<TYPE, AlignTypeSpec<TYPE_CODE>, Char>( \ f.value(), AlignTypeSpec<TYPE_CODE>(width, fill)); \ } \ \ inline IntFormatSpec<TYPE, AlignTypeSpec<0> > pad( \ TYPE value, unsigned width) { \ return IntFormatSpec<TYPE, AlignTypeSpec<0> >( \ value, AlignTypeSpec<0>(width, ' ')); \ } \ \ template <typename Char> \ inline IntFormatSpec<TYPE, AlignTypeSpec<0>, Char> pad( \ TYPE value, unsigned width, Char fill) { \ return IntFormatSpec<TYPE, AlignTypeSpec<0>, Char>( \ value, AlignTypeSpec<0>(width, fill)); \ } FMT_DEFINE_INT_FORMATTERS(int) FMT_DEFINE_INT_FORMATTERS(long) FMT_DEFINE_INT_FORMATTERS(unsigned) FMT_DEFINE_INT_FORMATTERS(unsigned long) FMT_DEFINE_INT_FORMATTERS(LongLong) FMT_DEFINE_INT_FORMATTERS(ULongLong) /** \rst Returns a string formatter that pads the formatted argument with the fill character to the specified width using the default (left) string alignment. **Example**:: std::string s = str(MemoryWriter() << pad("abc", 8)); // s == "abc " \endrst */ template <typename Char> inline StrFormatSpec<Char> pad( const Char *str, unsigned width, Char fill = ' ') { return StrFormatSpec<Char>(str, width, fill); } inline StrFormatSpec<wchar_t> pad( const wchar_t *str, unsigned width, char fill = ' ') { return StrFormatSpec<wchar_t>(str, width, fill); } namespace internal { template <typename Char> class ArgMap { private: typedef std::vector< std::pair<fmt::BasicStringRef<Char>, internal::Arg> > MapType; typedef typename MapType::value_type Pair; MapType map_; public: FMT_API void init(const ArgList &args); const internal::Arg* find(const fmt::BasicStringRef<Char> &name) const { // The list is unsorted, so just return the first matching name. for (typename MapType::const_iterator it = map_.begin(), end = map_.end(); it != end; ++it) { if (it->first == name) return &it->second; } return 0; } }; template <typename Impl, typename Char> class ArgFormatterBase : public ArgVisitor<Impl, void> { private: BasicWriter<Char> &writer_; FormatSpec &spec_; FMT_DISALLOW_COPY_AND_ASSIGN(ArgFormatterBase); void write_pointer(const void *p) { spec_.flags_ = HASH_FLAG; spec_.type_ = 'x'; writer_.write_int(reinterpret_cast<uintptr_t>(p), spec_); } protected: BasicWriter<Char> &writer() { return writer_; } FormatSpec &spec() { return spec_; } void write(bool value) { const char *str_value = value ? "true" : "false"; Arg::StringValue<char> str = { str_value, std::strlen(str_value) }; writer_.write_str(str, spec_); } void write(const char *value) { Arg::StringValue<char> str = {value, value != 0 ? std::strlen(value) : 0}; writer_.write_str(str, spec_); } public: ArgFormatterBase(BasicWriter<Char> &w, FormatSpec &s) : writer_(w), spec_(s) {} template <typename T> void visit_any_int(T value) { writer_.write_int(value, spec_); } template <typename T> void visit_any_double(T value) { writer_.write_double(value, spec_); } void visit_bool(bool value) { if (spec_.type_) return visit_any_int(value); write(value); } void visit_char(int value) { if (spec_.type_ && spec_.type_ != 'c') { spec_.flags_ |= CHAR_FLAG; writer_.write_int(value, spec_); return; } if (spec_.align_ == ALIGN_NUMERIC || spec_.flags_ != 0) FMT_THROW(FormatError("invalid format specifier for char")); typedef typename BasicWriter<Char>::CharPtr CharPtr; Char fill = internal::CharTraits<Char>::cast(spec_.fill()); CharPtr out = CharPtr(); const unsigned CHAR_WIDTH = 1; if (spec_.width_ > CHAR_WIDTH) { out = writer_.grow_buffer(spec_.width_); if (spec_.align_ == ALIGN_RIGHT) { std::uninitialized_fill_n(out, spec_.width_ - CHAR_WIDTH, fill); out += spec_.width_ - CHAR_WIDTH; } else if (spec_.align_ == ALIGN_CENTER) { out = writer_.fill_padding(out, spec_.width_, internal::check(CHAR_WIDTH), fill); } else { std::uninitialized_fill_n(out + CHAR_WIDTH, spec_.width_ - CHAR_WIDTH, fill); } } else { out = writer_.grow_buffer(CHAR_WIDTH); } *out = internal::CharTraits<Char>::cast(value); } void visit_cstring(const char *value) { if (spec_.type_ == 'p') return write_pointer(value); write(value); } void visit_string(Arg::StringValue<char> value) { writer_.write_str(value, spec_); } using ArgVisitor<Impl, void>::visit_wstring; void visit_wstring(Arg::StringValue<Char> value) { writer_.write_str(value, spec_); } void visit_pointer(const void *value) { if (spec_.type_ && spec_.type_ != 'p') report_unknown_type(spec_.type_, "pointer"); write_pointer(value); } }; class FormatterBase { private: ArgList args_; int next_arg_index_; // Returns the argument with specified index. FMT_API Arg do_get_arg(unsigned arg_index, const char *&error); protected: const ArgList &args() const { return args_; } explicit FormatterBase(const ArgList &args) { args_ = args; next_arg_index_ = 0; } // Returns the next argument. Arg next_arg(const char *&error) { if (next_arg_index_ >= 0) return do_get_arg(internal::to_unsigned(next_arg_index_++), error); error = "cannot switch from manual to automatic argument indexing"; return Arg(); } // Checks if manual indexing is used and returns the argument with // specified index. Arg get_arg(unsigned arg_index, const char *&error) { return check_no_auto_index(error) ? do_get_arg(arg_index, error) : Arg(); } bool check_no_auto_index(const char *&error) { if (next_arg_index_ > 0) { error = "cannot switch from automatic to manual argument indexing"; return false; } next_arg_index_ = -1; return true; } template <typename Char> void write(BasicWriter<Char> &w, const Char *start, const Char *end) { if (start != end) w << BasicStringRef<Char>(start, internal::to_unsigned(end - start)); } }; // A printf formatter. template <typename Char> class PrintfFormatter : private FormatterBase { private: void parse_flags(FormatSpec &spec, const Char *&s); // Returns the argument with specified index or, if arg_index is equal // to the maximum unsigned value, the next argument. Arg get_arg(const Char *s, unsigned arg_index = (std::numeric_limits<unsigned>::max)()); // Parses argument index, flags and width and returns the argument index. unsigned parse_header(const Char *&s, FormatSpec &spec); public: explicit PrintfFormatter(const ArgList &args) : FormatterBase(args) {} FMT_API void format(BasicWriter<Char> &writer, BasicCStringRef<Char> format_str); }; } // namespace internal /** \rst An argument formatter based on the `curiously recurring template pattern <http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_. To use `~fmt::BasicArgFormatter` define a subclass that implements some or all of the visit methods with the same signatures as the methods in `~fmt::ArgVisitor`, for example, `~fmt::ArgVisitor::visit_int()`. Pass the subclass as the *Impl* template parameter. When a formatting function processes an argument, it will dispatch to a visit method specific to the argument type. For example, if the argument type is ``double`` then the `~fmt::ArgVisitor::visit_double()` method of a subclass will be called. If the subclass doesn't contain a method with this signature, then a corresponding method of `~fmt::BasicArgFormatter` or its superclass will be called. \endrst */ template <typename Impl, typename Char> class BasicArgFormatter : public internal::ArgFormatterBase<Impl, Char> { private: BasicFormatter<Char, Impl> &formatter_; const Char *format_; public: /** \rst Constructs an argument formatter object. *formatter* is a reference to the main formatter object, *spec* contains format specifier information for standard argument types, and *fmt* points to the part of the format string being parsed for custom argument types. \endrst */ BasicArgFormatter(BasicFormatter<Char, Impl> &formatter, FormatSpec &spec, const Char *fmt) : internal::ArgFormatterBase<Impl, Char>(formatter.writer(), spec), formatter_(formatter), format_(fmt) {} /** Formats argument of a custom (user-defined) type. */ void visit_custom(internal::Arg::CustomValue c) { c.format(&formatter_, c.value, &format_); } }; /** The default argument formatter. */ template <typename Char> class ArgFormatter : public BasicArgFormatter<ArgFormatter<Char>, Char> { public: /** Constructs an argument formatter object. */ ArgFormatter(BasicFormatter<Char> &formatter, FormatSpec &spec, const Char *fmt) : BasicArgFormatter<ArgFormatter<Char>, Char>(formatter, spec, fmt) {} }; /** This template formats data and writes the output to a writer. */ template <typename CharType, typename ArgFormatter> class BasicFormatter : private internal::FormatterBase { public: /** The character type for the output. */ typedef CharType Char; private: BasicWriter<Char> &writer_; internal::ArgMap<Char> map_; FMT_DISALLOW_COPY_AND_ASSIGN(BasicFormatter); using internal::FormatterBase::get_arg; // Checks if manual indexing is used and returns the argument with // specified name. internal::Arg get_arg(BasicStringRef<Char> arg_name, const char *&error); // Parses argument index and returns corresponding argument. internal::Arg parse_arg_index(const Char *&s); // Parses argument name and returns corresponding argument. internal::Arg parse_arg_name(const Char *&s); public: /** \rst Constructs a ``BasicFormatter`` object. References to the arguments and the writer are stored in the formatter object so make sure they have appropriate lifetimes. \endrst */ BasicFormatter(const ArgList &args, BasicWriter<Char> &w) : internal::FormatterBase(args), writer_(w) {} /** Returns a reference to the writer associated with this formatter. */ BasicWriter<Char> &writer() { return writer_; } /** Formats stored arguments and writes the output to the writer. */ void format(BasicCStringRef<Char> format_str); // Formats a single argument and advances format_str, a format string pointer. const Char *format(const Char *&format_str, const internal::Arg &arg); }; // Generates a comma-separated list with results of applying f to // numbers 0..n-1. # define FMT_GEN(n, f) FMT_GEN##n(f) # define FMT_GEN1(f) f(0) # define FMT_GEN2(f) FMT_GEN1(f), f(1) # define FMT_GEN3(f) FMT_GEN2(f), f(2) # define FMT_GEN4(f) FMT_GEN3(f), f(3) # define FMT_GEN5(f) FMT_GEN4(f), f(4) # define FMT_GEN6(f) FMT_GEN5(f), f(5) # define FMT_GEN7(f) FMT_GEN6(f), f(6) # define FMT_GEN8(f) FMT_GEN7(f), f(7) # define FMT_GEN9(f) FMT_GEN8(f), f(8) # define FMT_GEN10(f) FMT_GEN9(f), f(9) # define FMT_GEN11(f) FMT_GEN10(f), f(10) # define FMT_GEN12(f) FMT_GEN11(f), f(11) # define FMT_GEN13(f) FMT_GEN12(f), f(12) # define FMT_GEN14(f) FMT_GEN13(f), f(13) # define FMT_GEN15(f) FMT_GEN14(f), f(14) namespace internal { inline uint64_t make_type() { return 0; } template <typename T> inline uint64_t make_type(const T &arg) { return MakeValue< BasicFormatter<char> >::type(arg); } template <unsigned N, bool/*IsPacked*/= (N < ArgList::MAX_PACKED_ARGS)> struct ArgArray; template <unsigned N> struct ArgArray<N, true/*IsPacked*/> { typedef Value Type[N > 0 ? N : 1]; template <typename Formatter, typename T> static Value make(const T &value) { #ifdef __clang__ Value result = MakeValue<Formatter>(value); // Workaround a bug in Apple LLVM version 4.2 (clang-425.0.28) of clang: // https://github.com/fmtlib/fmt/issues/276 (void)result.custom.format; return result; #else return MakeValue<Formatter>(value); #endif } }; template <unsigned N> struct ArgArray<N, false/*IsPacked*/> { typedef Arg Type[N + 1]; // +1 for the list end Arg::NONE template <typename Formatter, typename T> static Arg make(const T &value) { return MakeArg<Formatter>(value); } }; #if FMT_USE_VARIADIC_TEMPLATES template <typename Arg, typename... Args> inline uint64_t make_type(const Arg &first, const Args & ... tail) { return make_type(first) | (make_type(tail...) << 4); } #else struct ArgType { uint64_t type; ArgType() : type(0) {} template <typename T> ArgType(const T &arg) : type(make_type(arg)) {} }; # define FMT_ARG_TYPE_DEFAULT(n) ArgType t##n = ArgType() inline uint64_t make_type(FMT_GEN15(FMT_ARG_TYPE_DEFAULT)) { return t0.type | (t1.type << 4) | (t2.type << 8) | (t3.type << 12) | (t4.type << 16) | (t5.type << 20) | (t6.type << 24) | (t7.type << 28) | (t8.type << 32) | (t9.type << 36) | (t10.type << 40) | (t11.type << 44) | (t12.type << 48) | (t13.type << 52) | (t14.type << 56); } #endif } // namespace internal # define FMT_MAKE_TEMPLATE_ARG(n) typename T##n # define FMT_MAKE_ARG_TYPE(n) T##n # define FMT_MAKE_ARG(n) const T##n &v##n # define FMT_ASSIGN_char(n) \ arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<char> >(v##n) # define FMT_ASSIGN_wchar_t(n) \ arr[n] = fmt::internal::MakeValue< fmt::BasicFormatter<wchar_t> >(v##n) #if FMT_USE_VARIADIC_TEMPLATES // Defines a variadic function returning void. # define FMT_VARIADIC_VOID(func, arg_type) \ template <typename... Args> \ void func(arg_type arg0, const Args & ... args) { \ typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \ typename ArgArray::Type array{ \ ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \ func(arg0, fmt::ArgList(fmt::internal::make_type(args...), array)); \ } // Defines a variadic constructor. # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ template <typename... Args> \ ctor(arg0_type arg0, arg1_type arg1, const Args & ... args) { \ typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \ typename ArgArray::Type array{ \ ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \ func(arg0, arg1, fmt::ArgList(fmt::internal::make_type(args...), array)); \ } #else # define FMT_MAKE_REF(n) \ fmt::internal::MakeValue< fmt::BasicFormatter<Char> >(v##n) # define FMT_MAKE_REF2(n) v##n // Defines a wrapper for a function taking one argument of type arg_type // and n additional arguments of arbitrary types. # define FMT_WRAP1(func, arg_type, n) \ template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \ inline void func(arg_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg1, fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ } // Emulates a variadic function returning void on a pre-C++11 compiler. # define FMT_VARIADIC_VOID(func, arg_type) \ inline void func(arg_type arg) { func(arg, fmt::ArgList()); } \ FMT_WRAP1(func, arg_type, 1) FMT_WRAP1(func, arg_type, 2) \ FMT_WRAP1(func, arg_type, 3) FMT_WRAP1(func, arg_type, 4) \ FMT_WRAP1(func, arg_type, 5) FMT_WRAP1(func, arg_type, 6) \ FMT_WRAP1(func, arg_type, 7) FMT_WRAP1(func, arg_type, 8) \ FMT_WRAP1(func, arg_type, 9) FMT_WRAP1(func, arg_type, 10) # define FMT_CTOR(ctor, func, arg0_type, arg1_type, n) \ template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \ ctor(arg0_type arg0, arg1_type arg1, FMT_GEN(n, FMT_MAKE_ARG)) { \ const fmt::internal::ArgArray<n>::Type array = {FMT_GEN(n, FMT_MAKE_REF)}; \ func(arg0, arg1, fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), array)); \ } // Emulates a variadic constructor on a pre-C++11 compiler. # define FMT_VARIADIC_CTOR(ctor, func, arg0_type, arg1_type) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 1) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 2) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 3) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 4) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 5) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 6) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 7) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 8) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 9) \ FMT_CTOR(ctor, func, arg0_type, arg1_type, 10) #endif // Generates a comma-separated list with results of applying f to pairs // (argument, index). #define FMT_FOR_EACH1(f, x0) f(x0, 0) #define FMT_FOR_EACH2(f, x0, x1) \ FMT_FOR_EACH1(f, x0), f(x1, 1) #define FMT_FOR_EACH3(f, x0, x1, x2) \ FMT_FOR_EACH2(f, x0 ,x1), f(x2, 2) #define FMT_FOR_EACH4(f, x0, x1, x2, x3) \ FMT_FOR_EACH3(f, x0, x1, x2), f(x3, 3) #define FMT_FOR_EACH5(f, x0, x1, x2, x3, x4) \ FMT_FOR_EACH4(f, x0, x1, x2, x3), f(x4, 4) #define FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5) \ FMT_FOR_EACH5(f, x0, x1, x2, x3, x4), f(x5, 5) #define FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6) \ FMT_FOR_EACH6(f, x0, x1, x2, x3, x4, x5), f(x6, 6) #define FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7) \ FMT_FOR_EACH7(f, x0, x1, x2, x3, x4, x5, x6), f(x7, 7) #define FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8) \ FMT_FOR_EACH8(f, x0, x1, x2, x3, x4, x5, x6, x7), f(x8, 8) #define FMT_FOR_EACH10(f, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9) \ FMT_FOR_EACH9(f, x0, x1, x2, x3, x4, x5, x6, x7, x8), f(x9, 9) /** An error returned by an operating system or a language runtime, for example a file opening error. */ class SystemError : public internal::RuntimeError { private: void init(int err_code, CStringRef format_str, ArgList args); protected: int error_code_; typedef char Char; // For FMT_VARIADIC_CTOR. SystemError() {} public: /** \rst Constructs a :class:`fmt::SystemError` object with the description of the form .. parsed-literal:: *<message>*: *<system-message>* where *<message>* is the formatted message and *<system-message>* is the system message corresponding to the error code. *error_code* is a system error code as given by ``errno``. If *error_code* is not a valid error code such as -1, the system message may look like "Unknown error -1" and is platform-dependent. **Example**:: // This throws a SystemError with the description // cannot open file 'madeup': No such file or directory // or similar (system message may vary). const char *filename = "madeup"; std::FILE *file = std::fopen(filename, "r"); if (!file) throw fmt::SystemError(errno, "cannot open file '{}'", filename); \endrst */ SystemError(int error_code, CStringRef message) { init(error_code, message, ArgList()); } FMT_VARIADIC_CTOR(SystemError, init, int, CStringRef) int error_code() const { return error_code_; } }; /** \rst This template provides operations for formatting and writing data into a character stream. The output is stored in a buffer provided by a subclass such as :class:`fmt::BasicMemoryWriter`. You can use one of the following typedefs for common character types: +---------+----------------------+ | Type | Definition | +=========+======================+ | Writer | BasicWriter<char> | +---------+----------------------+ | WWriter | BasicWriter<wchar_t> | +---------+----------------------+ \endrst */ template <typename Char> class BasicWriter { private: // Output buffer. Buffer<Char> &buffer_; FMT_DISALLOW_COPY_AND_ASSIGN(BasicWriter); typedef typename internal::CharTraits<Char>::CharPtr CharPtr; #if FMT_SECURE_SCL // Returns pointer value. static Char *get(CharPtr p) { return p.base(); } #else static Char *get(Char *p) { return p; } #endif // Fills the padding around the content and returns the pointer to the // content area. static CharPtr fill_padding(CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill); // Grows the buffer by n characters and returns a pointer to the newly // allocated area. CharPtr grow_buffer(std::size_t n) { std::size_t size = buffer_.size(); buffer_.resize(size + n); return internal::make_ptr(&buffer_[size], n); } // Writes an unsigned decimal integer. template <typename UInt> Char *write_unsigned_decimal(UInt value, unsigned prefix_size = 0) { unsigned num_digits = internal::count_digits(value); Char *ptr = get(grow_buffer(prefix_size + num_digits)); internal::format_decimal(ptr + prefix_size, value, num_digits); return ptr; } // Writes a decimal integer. template <typename Int> void write_decimal(Int value) { typedef typename internal::IntTraits<Int>::MainType MainType; MainType abs_value = static_cast<MainType>(value); if (internal::is_negative(value)) { abs_value = 0 - abs_value; *write_unsigned_decimal(abs_value, 1) = '-'; } else { write_unsigned_decimal(abs_value, 0); } } // Prepare a buffer for integer formatting. CharPtr prepare_int_buffer(unsigned num_digits, const EmptySpec &, const char *prefix, unsigned prefix_size) { unsigned size = prefix_size + num_digits; CharPtr p = grow_buffer(size); std::uninitialized_copy(prefix, prefix + prefix_size, p); return p + size - 1; } template <typename Spec> CharPtr prepare_int_buffer(unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size); // Formats an integer. template <typename T, typename Spec> void write_int(T value, Spec spec); // Formats a floating-point number (double or long double). template <typename T> void write_double(T value, const FormatSpec &spec); // Writes a formatted string. template <typename StrChar> CharPtr write_str(const StrChar *s, std::size_t size, const AlignSpec &spec); template <typename StrChar> void write_str(const internal::Arg::StringValue<StrChar> &str, const FormatSpec &spec); // This following methods are private to disallow writing wide characters // and strings to a char stream. If you want to print a wide string as a // pointer as std::ostream does, cast it to const void*. // Do not implement! void operator<<(typename internal::WCharHelper<wchar_t, Char>::Unsupported); void operator<<( typename internal::WCharHelper<const wchar_t *, Char>::Unsupported); // Appends floating-point length specifier to the format string. // The second argument is only used for overload resolution. void append_float_length(Char *&format_ptr, long double) { *format_ptr++ = 'L'; } template<typename T> void append_float_length(Char *&, T) {} template <typename Impl, typename Char_> friend class internal::ArgFormatterBase; friend class internal::PrintfArgFormatter<Char>; protected: /** Constructs a ``BasicWriter`` object. */ explicit BasicWriter(Buffer<Char> &b) : buffer_(b) {} public: /** \rst Destroys a ``BasicWriter`` object. \endrst */ virtual ~BasicWriter() {} /** Returns the total number of characters written. */ std::size_t size() const { return buffer_.size(); } /** Returns a pointer to the output buffer content. No terminating null character is appended. */ const Char *data() const FMT_NOEXCEPT { return &buffer_[0]; } /** Returns a pointer to the output buffer content with terminating null character appended. */ const Char *c_str() const { std::size_t size = buffer_.size(); buffer_.reserve(size + 1); buffer_[size] = '\0'; return &buffer_[0]; } /** \rst Returns the content of the output buffer as an `std::string`. \endrst */ std::basic_string<Char> str() const { return std::basic_string<Char>(&buffer_[0], buffer_.size()); } /** \rst Writes formatted data. *args* is an argument list representing arbitrary arguments. **Example**:: MemoryWriter out; out.write("Current point:\n"); out.write("({:+f}, {:+f})", -3.14, 3.14); This will write the following output to the ``out`` object: .. code-block:: none Current point: (-3.140000, +3.140000) The output can be accessed using :func:`data()`, :func:`c_str` or :func:`str` methods. See also :ref:`syntax`. \endrst */ void write(BasicCStringRef<Char> format, ArgList args) { BasicFormatter<Char>(args, *this).format(format); } FMT_VARIADIC_VOID(write, BasicCStringRef<Char>) BasicWriter &operator<<(int value) { write_decimal(value); return *this; } BasicWriter &operator<<(unsigned value) { return *this << IntFormatSpec<unsigned>(value); } BasicWriter &operator<<(long value) { write_decimal(value); return *this; } BasicWriter &operator<<(unsigned long value) { return *this << IntFormatSpec<unsigned long>(value); } BasicWriter &operator<<(LongLong value) { write_decimal(value); return *this; } /** \rst Formats *value* and writes it to the stream. \endrst */ BasicWriter &operator<<(ULongLong value) { return *this << IntFormatSpec<ULongLong>(value); } BasicWriter &operator<<(double value) { write_double(value, FormatSpec()); return *this; } /** \rst Formats *value* using the general format for floating-point numbers (``'g'``) and writes it to the stream. \endrst */ BasicWriter &operator<<(long double value) { write_double(value, FormatSpec()); return *this; } /** Writes a character to the stream. */ BasicWriter &operator<<(char value) { buffer_.push_back(value); return *this; } BasicWriter &operator<<( typename internal::WCharHelper<wchar_t, Char>::Supported value) { buffer_.push_back(value); return *this; } /** \rst Writes *value* to the stream. \endrst */ BasicWriter &operator<<(fmt::BasicStringRef<Char> value) { const Char *str = value.data(); buffer_.append(str, str + value.size()); return *this; } BasicWriter &operator<<( typename internal::WCharHelper<StringRef, Char>::Supported value) { const char *str = value.data(); buffer_.append(str, str + value.size()); return *this; } template <typename T, typename Spec, typename FillChar> BasicWriter &operator<<(IntFormatSpec<T, Spec, FillChar> spec) { internal::CharTraits<Char>::convert(FillChar()); write_int(spec.value(), spec); return *this; } template <typename StrChar> BasicWriter &operator<<(const StrFormatSpec<StrChar> &spec) { const StrChar *s = spec.str(); write_str(s, std::char_traits<Char>::length(s), spec); return *this; } void clear() FMT_NOEXCEPT { buffer_.clear(); } Buffer<Char> &buffer() FMT_NOEXCEPT { return buffer_; } }; template <typename Char> template <typename StrChar> typename BasicWriter<Char>::CharPtr BasicWriter<Char>::write_str( const StrChar *s, std::size_t size, const AlignSpec &spec) { CharPtr out = CharPtr(); if (spec.width() > size) { out = grow_buffer(spec.width()); Char fill = internal::CharTraits<Char>::cast(spec.fill()); if (spec.align() == ALIGN_RIGHT) { std::uninitialized_fill_n(out, spec.width() - size, fill); out += spec.width() - size; } else if (spec.align() == ALIGN_CENTER) { out = fill_padding(out, spec.width(), size, fill); } else { std::uninitialized_fill_n(out + size, spec.width() - size, fill); } } else { out = grow_buffer(size); } std::uninitialized_copy(s, s + size, out); return out; } template <typename Char> template <typename StrChar> void BasicWriter<Char>::write_str( const internal::Arg::StringValue<StrChar> &s, const FormatSpec &spec) { // Check if StrChar is convertible to Char. internal::CharTraits<Char>::convert(StrChar()); if (spec.type_ && spec.type_ != 's') internal::report_unknown_type(spec.type_, "string"); const StrChar *str_value = s.value; std::size_t str_size = s.size; if (str_size == 0) { if (!str_value) { FMT_THROW(FormatError("string pointer is null")); return; } } std::size_t precision = static_cast<std::size_t>(spec.precision_); if (spec.precision_ >= 0 && precision < str_size) str_size = precision; write_str(str_value, str_size, spec); } template <typename Char> typename BasicWriter<Char>::CharPtr BasicWriter<Char>::fill_padding( CharPtr buffer, unsigned total_size, std::size_t content_size, wchar_t fill) { std::size_t padding = total_size - content_size; std::size_t left_padding = padding / 2; Char fill_char = internal::CharTraits<Char>::cast(fill); std::uninitialized_fill_n(buffer, left_padding, fill_char); buffer += left_padding; CharPtr content = buffer; std::uninitialized_fill_n(buffer + content_size, padding - left_padding, fill_char); return content; } template <typename Char> template <typename Spec> typename BasicWriter<Char>::CharPtr BasicWriter<Char>::prepare_int_buffer( unsigned num_digits, const Spec &spec, const char *prefix, unsigned prefix_size) { unsigned width = spec.width(); Alignment align = spec.align(); Char fill = internal::CharTraits<Char>::cast(spec.fill()); if (spec.precision() > static_cast<int>(num_digits)) { // Octal prefix '0' is counted as a digit, so ignore it if precision // is specified. if (prefix_size > 0 && prefix[prefix_size - 1] == '0') --prefix_size; unsigned number_size = prefix_size + internal::to_unsigned(spec.precision()); AlignSpec subspec(number_size, '0', ALIGN_NUMERIC); if (number_size >= width) return prepare_int_buffer(num_digits, subspec, prefix, prefix_size); buffer_.reserve(width); unsigned fill_size = width - number_size; if (align != ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); std::uninitialized_fill(p, p + fill_size, fill); } CharPtr result = prepare_int_buffer( num_digits, subspec, prefix, prefix_size); if (align == ALIGN_LEFT) { CharPtr p = grow_buffer(fill_size); std::uninitialized_fill(p, p + fill_size, fill); } return result; } unsigned size = prefix_size + num_digits; if (width <= size) { CharPtr p = grow_buffer(size); std::uninitialized_copy(prefix, prefix + prefix_size, p); return p + size - 1; } CharPtr p = grow_buffer(width); CharPtr end = p + width; if (align == ALIGN_LEFT) { std::uninitialized_copy(prefix, prefix + prefix_size, p); p += size; std::uninitialized_fill(p, end, fill); } else if (align == ALIGN_CENTER) { p = fill_padding(p, width, size, fill); std::uninitialized_copy(prefix, prefix + prefix_size, p); p += size; } else { if (align == ALIGN_NUMERIC) { if (prefix_size != 0) { p = std::uninitialized_copy(prefix, prefix + prefix_size, p); size -= prefix_size; } } else { std::uninitialized_copy(prefix, prefix + prefix_size, end - size); } std::uninitialized_fill(p, end - size, fill); p = end; } return p - 1; } template <typename Char> template <typename T, typename Spec> void BasicWriter<Char>::write_int(T value, Spec spec) { unsigned prefix_size = 0; typedef typename internal::IntTraits<T>::MainType UnsignedType; UnsignedType abs_value = static_cast<UnsignedType>(value); char prefix[4] = ""; if (internal::is_negative(value)) { prefix[0] = '-'; ++prefix_size; abs_value = 0 - abs_value; } else if (spec.flag(SIGN_FLAG)) { prefix[0] = spec.flag(PLUS_FLAG) ? '+' : ' '; ++prefix_size; } switch (spec.type()) { case 0: case 'd': { unsigned num_digits = internal::count_digits(abs_value); CharPtr p = prepare_int_buffer(num_digits, spec, prefix, prefix_size) + 1; internal::format_decimal(get(p), abs_value, 0); break; } case 'x': case 'X': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = spec.type(); } unsigned num_digits = 0; do { ++num_digits; } while ((n >>= 4) != 0); Char *p = get(prepare_int_buffer( num_digits, spec, prefix, prefix_size)); n = abs_value; const char *digits = spec.type() == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; do { *p-- = digits[n & 0xf]; } while ((n >>= 4) != 0); break; } case 'b': case 'B': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) { prefix[prefix_size++] = '0'; prefix[prefix_size++] = spec.type(); } unsigned num_digits = 0; do { ++num_digits; } while ((n >>= 1) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = static_cast<Char>('0' + (n & 1)); } while ((n >>= 1) != 0); break; } case 'o': { UnsignedType n = abs_value; if (spec.flag(HASH_FLAG)) prefix[prefix_size++] = '0'; unsigned num_digits = 0; do { ++num_digits; } while ((n >>= 3) != 0); Char *p = get(prepare_int_buffer(num_digits, spec, prefix, prefix_size)); n = abs_value; do { *p-- = static_cast<Char>('0' + (n & 7)); } while ((n >>= 3) != 0); break; } case 'n': { unsigned num_digits = internal::count_digits(abs_value); fmt::StringRef sep = std::localeconv()->thousands_sep; unsigned size = static_cast<unsigned>( num_digits + sep.size() * (num_digits - 1) / 3); CharPtr p = prepare_int_buffer(size, spec, prefix, prefix_size) + 1; internal::format_decimal(get(p), abs_value, 0, internal::ThousandsSep(sep)); break; } default: internal::report_unknown_type( spec.type(), spec.flag(CHAR_FLAG) ? "char" : "integer"); break; } } template <typename Char> template <typename T> void BasicWriter<Char>::write_double(T value, const FormatSpec &spec) { // Check type. char type = spec.type(); bool upper = false; switch (type) { case 0: type = 'g'; break; case 'e': case 'f': case 'g': case 'a': break; case 'F': #ifdef _MSC_VER // MSVC's printf doesn't support 'F'. type = 'f'; #endif // Fall through. case 'E': case 'G': case 'A': upper = true; break; default: internal::report_unknown_type(type, "double"); break; } char sign = 0; // Use isnegative instead of value < 0 because the latter is always // false for NaN. if (internal::FPUtil::isnegative(static_cast<double>(value))) { sign = '-'; value = -value; } else if (spec.flag(SIGN_FLAG)) { sign = spec.flag(PLUS_FLAG) ? '+' : ' '; } if (internal::FPUtil::isnotanumber(value)) { // Format NaN ourselves because sprintf's output is not consistent // across platforms. std::size_t nan_size = 4; const char *nan = upper ? " NAN" : " nan"; if (!sign) { --nan_size; ++nan; } CharPtr out = write_str(nan, nan_size, spec); if (sign) *out = sign; return; } if (internal::FPUtil::isinfinity(value)) { // Format infinity ourselves because sprintf's output is not consistent // across platforms. std::size_t inf_size = 4; const char *inf = upper ? " INF" : " inf"; if (!sign) { --inf_size; ++inf; } CharPtr out = write_str(inf, inf_size, spec); if (sign) *out = sign; return; } std::size_t offset = buffer_.size(); unsigned width = spec.width(); if (sign) { buffer_.reserve(buffer_.size() + (width > 1u ? width : 1u)); if (width > 0) --width; ++offset; } // Build format string. enum { MAX_FORMAT_SIZE = 10}; // longest format: %#-*.*Lg Char format[MAX_FORMAT_SIZE]; Char *format_ptr = format; *format_ptr++ = '%'; unsigned width_for_sprintf = width; if (spec.flag(HASH_FLAG)) *format_ptr++ = '#'; if (spec.align() == ALIGN_CENTER) { width_for_sprintf = 0; } else { if (spec.align() == ALIGN_LEFT) *format_ptr++ = '-'; if (width != 0) *format_ptr++ = '*'; } if (spec.precision() >= 0) { *format_ptr++ = '.'; *format_ptr++ = '*'; } append_float_length(format_ptr, value); *format_ptr++ = type; *format_ptr = '\0'; // Format using snprintf. Char fill = internal::CharTraits<Char>::cast(spec.fill()); unsigned n = 0; Char *start = 0; for (;;) { std::size_t buffer_size = buffer_.capacity() - offset; #ifdef _MSC_VER // MSVC's vsnprintf_s doesn't work with zero size, so reserve // space for at least one extra character to make the size non-zero. // Note that the buffer's capacity will increase by more than 1. if (buffer_size == 0) { buffer_.reserve(offset + 1); buffer_size = buffer_.capacity() - offset; } #endif start = &buffer_[offset]; int result = internal::CharTraits<Char>::format_float( start, buffer_size, format, width_for_sprintf, spec.precision(), value); if (result >= 0) { n = internal::to_unsigned(result); if (offset + n < buffer_.capacity()) break; // The buffer is large enough - continue with formatting. buffer_.reserve(offset + n + 1); } else { // If result is negative we ask to increase the capacity by at least 1, // but as std::vector, the buffer grows exponentially. buffer_.reserve(buffer_.capacity() + 1); } } if (sign) { if ((spec.align() != ALIGN_RIGHT && spec.align() != ALIGN_DEFAULT) || *start != ' ') { *(start - 1) = sign; sign = 0; } else { *(start - 1) = fill; } ++n; } if (spec.align() == ALIGN_CENTER && spec.width() > n) { width = spec.width(); CharPtr p = grow_buffer(width); std::memmove(get(p) + (width - n) / 2, get(p), n * sizeof(Char)); fill_padding(p, spec.width(), n, fill); return; } if (spec.fill() != ' ' || sign) { while (*start == ' ') *start++ = fill; if (sign) *(start - 1) = sign; } grow_buffer(n); } /** \rst This class template provides operations for formatting and writing data into a character stream. The output is stored in a memory buffer that grows dynamically. You can use one of the following typedefs for common character types and the standard allocator: +---------------+-----------------------------------------------------+ | Type | Definition | +===============+=====================================================+ | MemoryWriter | BasicMemoryWriter<char, std::allocator<char>> | +---------------+-----------------------------------------------------+ | WMemoryWriter | BasicMemoryWriter<wchar_t, std::allocator<wchar_t>> | +---------------+-----------------------------------------------------+ **Example**:: MemoryWriter out; out << "The answer is " << 42 << "\n"; out.write("({:+f}, {:+f})", -3.14, 3.14); This will write the following output to the ``out`` object: .. code-block:: none The answer is 42 (-3.140000, +3.140000) The output can be converted to an ``std::string`` with ``out.str()`` or accessed as a C string with ``out.c_str()``. \endrst */ template <typename Char, typename Allocator = std::allocator<Char> > class BasicMemoryWriter : public BasicWriter<Char> { private: internal::MemoryBuffer<Char, internal::INLINE_BUFFER_SIZE, Allocator> buffer_; public: explicit BasicMemoryWriter(const Allocator& alloc = Allocator()) : BasicWriter<Char>(buffer_), buffer_(alloc) {} #if FMT_USE_RVALUE_REFERENCES /** \rst Constructs a :class:`fmt::BasicMemoryWriter` object moving the content of the other object to it. \endrst */ BasicMemoryWriter(BasicMemoryWriter &&other) : BasicWriter<Char>(buffer_), buffer_(std::move(other.buffer_)) { } /** \rst Moves the content of the other ``BasicMemoryWriter`` object to this one. \endrst */ BasicMemoryWriter &operator=(BasicMemoryWriter &&other) { buffer_ = std::move(other.buffer_); return *this; } #endif }; typedef BasicMemoryWriter<char> MemoryWriter; typedef BasicMemoryWriter<wchar_t> WMemoryWriter; /** \rst This class template provides operations for formatting and writing data into a fixed-size array. For writing into a dynamically growing buffer use :class:`fmt::BasicMemoryWriter`. Any write method will throw ``std::runtime_error`` if the output doesn't fit into the array. You can use one of the following typedefs for common character types: +--------------+---------------------------+ | Type | Definition | +==============+===========================+ | ArrayWriter | BasicArrayWriter<char> | +--------------+---------------------------+ | WArrayWriter | BasicArrayWriter<wchar_t> | +--------------+---------------------------+ \endrst */ template <typename Char> class BasicArrayWriter : public BasicWriter<Char> { private: internal::FixedBuffer<Char> buffer_; public: /** \rst Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the given size. \endrst */ BasicArrayWriter(Char *array, std::size_t size) : BasicWriter<Char>(buffer_), buffer_(array, size) {} /** \rst Constructs a :class:`fmt::BasicArrayWriter` object for *array* of the size known at compile time. \endrst */ template <std::size_t SIZE> explicit BasicArrayWriter(Char (&array)[SIZE]) : BasicWriter<Char>(buffer_), buffer_(array, SIZE) {} }; typedef BasicArrayWriter<char> ArrayWriter; typedef BasicArrayWriter<wchar_t> WArrayWriter; // Reports a system error without throwing an exception. // Can be used to report errors from destructors. FMT_API void report_system_error(int error_code, StringRef message) FMT_NOEXCEPT; #if FMT_USE_WINDOWS_H /** A Windows error. */ class WindowsError : public SystemError { private: FMT_API void init(int error_code, CStringRef format_str, ArgList args); public: /** \rst Constructs a :class:`fmt::WindowsError` object with the description of the form .. parsed-literal:: *<message>*: *<system-message>* where *<message>* is the formatted message and *<system-message>* is the system message corresponding to the error code. *error_code* is a Windows error code as given by ``GetLastError``. If *error_code* is not a valid error code such as -1, the system message will look like "error -1". **Example**:: // This throws a WindowsError with the description // cannot open file 'madeup': The system cannot find the file specified. // or similar (system message may vary). const char *filename = "madeup"; LPOFSTRUCT of = LPOFSTRUCT(); HFILE file = OpenFile(filename, &of, OF_READ); if (file == HFILE_ERROR) { throw fmt::WindowsError(GetLastError(), "cannot open file '{}'", filename); } \endrst */ WindowsError(int error_code, CStringRef message) { init(error_code, message, ArgList()); } FMT_VARIADIC_CTOR(WindowsError, init, int, CStringRef) }; // Reports a Windows error without throwing an exception. // Can be used to report errors from destructors. FMT_API void report_windows_error(int error_code, StringRef message) FMT_NOEXCEPT; #endif enum Color { BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; /** Formats a string and prints it to stdout using ANSI escape sequences to specify color (experimental). Example: print_colored(fmt::RED, "Elapsed time: {0:.2f} seconds", 1.23); */ FMT_API void print_colored(Color c, CStringRef format, ArgList args); /** \rst Formats arguments and returns the result as a string. **Example**:: std::string message = format("The answer is {}", 42); \endrst */ inline std::string format(CStringRef format_str, ArgList args) { MemoryWriter w; w.write(format_str, args); return w.str(); } inline std::wstring format(WCStringRef format_str, ArgList args) { WMemoryWriter w; w.write(format_str, args); return w.str(); } /** \rst Prints formatted data to the file *f*. **Example**:: print(stderr, "Don't {}!", "panic"); \endrst */ FMT_API void print(std::FILE *f, CStringRef format_str, ArgList args); /** \rst Prints formatted data to ``stdout``. **Example**:: print("Elapsed time: {0:.2f} seconds", 1.23); \endrst */ FMT_API void print(CStringRef format_str, ArgList args); template <typename Char> void printf(BasicWriter<Char> &w, BasicCStringRef<Char> format, ArgList args) { internal::PrintfFormatter<Char>(args).format(w, format); } /** \rst Formats arguments and returns the result as a string. **Example**:: std::string message = fmt::sprintf("The answer is %d", 42); \endrst */ inline std::string sprintf(CStringRef format, ArgList args) { MemoryWriter w; printf(w, format, args); return w.str(); } inline std::wstring sprintf(WCStringRef format, ArgList args) { WMemoryWriter w; printf(w, format, args); return w.str(); } /** \rst Prints formatted data to the file *f*. **Example**:: fmt::fprintf(stderr, "Don't %s!", "panic"); \endrst */ FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args); /** \rst Prints formatted data to ``stdout``. **Example**:: fmt::printf("Elapsed time: %.2f seconds", 1.23); \endrst */ inline int printf(CStringRef format, ArgList args) { return fprintf(stdout, format, args); } /** Fast integer formatter. */ class FormatInt { private: // Buffer should be large enough to hold all digits (digits10 + 1), // a sign and a null character. enum {BUFFER_SIZE = std::numeric_limits<ULongLong>::digits10 + 3}; mutable char buffer_[BUFFER_SIZE]; char *str_; // Formats value in reverse and returns the number of digits. char *format_decimal(ULongLong value) { char *buffer_end = buffer_ + BUFFER_SIZE - 1; while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu // "Three Optimization Tips for C++". See speed-test for a comparison. unsigned index = static_cast<unsigned>((value % 100) * 2); value /= 100; *--buffer_end = internal::Data::DIGITS[index + 1]; *--buffer_end = internal::Data::DIGITS[index]; } if (value < 10) { *--buffer_end = static_cast<char>('0' + value); return buffer_end; } unsigned index = static_cast<unsigned>(value * 2); *--buffer_end = internal::Data::DIGITS[index + 1]; *--buffer_end = internal::Data::DIGITS[index]; return buffer_end; } void FormatSigned(LongLong value) { ULongLong abs_value = static_cast<ULongLong>(value); bool negative = value < 0; if (negative) abs_value = 0 - abs_value; str_ = format_decimal(abs_value); if (negative) *--str_ = '-'; } public: explicit FormatInt(int value) { FormatSigned(value); } explicit FormatInt(long value) { FormatSigned(value); } explicit FormatInt(LongLong value) { FormatSigned(value); } explicit FormatInt(unsigned value) : str_(format_decimal(value)) {} explicit FormatInt(unsigned long value) : str_(format_decimal(value)) {} explicit FormatInt(ULongLong value) : str_(format_decimal(value)) {} /** Returns the number of characters written to the output buffer. */ std::size_t size() const { return internal::to_unsigned(buffer_ - str_ + BUFFER_SIZE - 1); } /** Returns a pointer to the output buffer content. No terminating null character is appended. */ const char *data() const { return str_; } /** Returns a pointer to the output buffer content with terminating null character appended. */ const char *c_str() const { buffer_[BUFFER_SIZE - 1] = '\0'; return str_; } /** \rst Returns the content of the output buffer as an ``std::string``. \endrst */ std::string str() const { return std::string(str_, size()); } }; // Formats a decimal integer value writing into buffer and returns // a pointer to the end of the formatted string. This function doesn't // write a terminating null character. template <typename T> inline void format_decimal(char *&buffer, T value) { typedef typename internal::IntTraits<T>::MainType MainType; MainType abs_value = static_cast<MainType>(value); if (internal::is_negative(value)) { *buffer++ = '-'; abs_value = 0 - abs_value; } if (abs_value < 100) { if (abs_value < 10) { *buffer++ = static_cast<char>('0' + abs_value); return; } unsigned index = static_cast<unsigned>(abs_value * 2); *buffer++ = internal::Data::DIGITS[index]; *buffer++ = internal::Data::DIGITS[index + 1]; return; } unsigned num_digits = internal::count_digits(abs_value); internal::format_decimal(buffer, abs_value, num_digits); buffer += num_digits; } /** \rst Returns a named argument for formatting functions. **Example**:: print("Elapsed time: {s:.2f} seconds", arg("s", 1.23)); \endrst */ template <typename T> inline internal::NamedArg<char> arg(StringRef name, const T &arg) { return internal::NamedArg<char>(name, arg); } template <typename T> inline internal::NamedArg<wchar_t> arg(WStringRef name, const T &arg) { return internal::NamedArg<wchar_t>(name, arg); } // The following two functions are deleted intentionally to disable // nested named arguments as in ``format("{}", arg("a", arg("b", 42)))``. template <typename Char> void arg(StringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED; template <typename Char> void arg(WStringRef, const internal::NamedArg<Char>&) FMT_DELETED_OR_UNDEFINED; } #if FMT_GCC_VERSION // Use the system_header pragma to suppress warnings about variadic macros // because suppressing -Wvariadic-macros with the diagnostic pragma doesn't // work. It is used at the end because we want to suppress as little warnings // as possible. # pragma GCC system_header #endif // This is used to work around VC++ bugs in handling variadic macros. #define FMT_EXPAND(args) args // Returns the number of arguments. // Based on https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s. #define FMT_NARG(...) FMT_NARG_(__VA_ARGS__, FMT_RSEQ_N()) #define FMT_NARG_(...) FMT_EXPAND(FMT_ARG_N(__VA_ARGS__)) #define FMT_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N #define FMT_RSEQ_N() 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 #define FMT_CONCAT(a, b) a##b #define FMT_FOR_EACH_(N, f, ...) \ FMT_EXPAND(FMT_CONCAT(FMT_FOR_EACH, N)(f, __VA_ARGS__)) #define FMT_FOR_EACH(f, ...) \ FMT_EXPAND(FMT_FOR_EACH_(FMT_NARG(__VA_ARGS__), f, __VA_ARGS__)) #define FMT_ADD_ARG_NAME(type, index) type arg##index #define FMT_GET_ARG_NAME(type, index) arg##index #if FMT_USE_VARIADIC_TEMPLATES # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ template <typename... Args> \ ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ const Args & ... args) { \ typedef fmt::internal::ArgArray<sizeof...(Args)> ArgArray; \ typename ArgArray::Type array{ \ ArgArray::template make<fmt::BasicFormatter<Char> >(args)...}; \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), \ fmt::ArgList(fmt::internal::make_type(args...), array)); \ } #else // Defines a wrapper for a function taking __VA_ARGS__ arguments // and n additional arguments of arbitrary types. # define FMT_WRAP(Char, ReturnType, func, call, n, ...) \ template <FMT_GEN(n, FMT_MAKE_TEMPLATE_ARG)> \ inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ FMT_GEN(n, FMT_MAKE_ARG)) { \ fmt::internal::ArgArray<n>::Type arr; \ FMT_GEN(n, FMT_ASSIGN_##Char); \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ } # define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ } \ FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \ FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__) #endif // FMT_USE_VARIADIC_TEMPLATES /** \rst Defines a variadic function with the specified return type, function name and argument types passed as variable arguments to this macro. **Example**:: void print_error(const char *file, int line, const char *format, fmt::ArgList args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args); } FMT_VARIADIC(void, print_error, const char *, int, const char *) ``FMT_VARIADIC`` is used for compatibility with legacy C++ compilers that don't implement variadic templates. You don't have to use this macro if you don't need legacy compiler support and can use variadic templates directly:: template <typename... Args> void print_error(const char *file, int line, const char *format, const Args & ... args) { fmt::print("{}: {}: ", file, line); fmt::print(format, args...); } \endrst */ #define FMT_VARIADIC(ReturnType, func, ...) \ FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__) #define FMT_VARIADIC_W(ReturnType, func, ...) \ FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__) #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id) #define FMT_CAPTURE_ARG_W_(id, index) ::fmt::arg(L###id, id) /** \rst Convenient macro to capture the arguments' names and values into several ``fmt::arg(name, value)``. **Example**:: int x = 1, y = 2; print("point: ({x}, {y})", FMT_CAPTURE(x, y)); // same as: // print("point: ({x}, {y})", arg("x", x), arg("y", y)); \endrst */ #define FMT_CAPTURE(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_, __VA_ARGS__) #define FMT_CAPTURE_W(...) FMT_FOR_EACH(FMT_CAPTURE_ARG_W_, __VA_ARGS__) namespace fmt { FMT_VARIADIC(std::string, format, CStringRef) FMT_VARIADIC_W(std::wstring, format, WCStringRef) FMT_VARIADIC(void, print, CStringRef) FMT_VARIADIC(void, print, std::FILE *, CStringRef) FMT_VARIADIC(void, print_colored, Color, CStringRef) FMT_VARIADIC(std::string, sprintf, CStringRef) FMT_VARIADIC_W(std::wstring, sprintf, WCStringRef) FMT_VARIADIC(int, printf, CStringRef) FMT_VARIADIC(int, fprintf, std::FILE *, CStringRef) namespace internal { template <typename Char> inline bool is_name_start(Char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c; } // Parses an unsigned integer advancing s to the end of the parsed input. // This function assumes that the first character of s is a digit. template <typename Char> unsigned parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; do { unsigned new_value = value * 10 + (*s++ - '0'); // Check if value wrapped around. if (new_value < value) { value = (std::numeric_limits<unsigned>::max)(); break; } value = new_value; } while ('0' <= *s && *s <= '9'); // Convert to unsigned to prevent a warning. unsigned max_int = (std::numeric_limits<int>::max)(); if (value > max_int) FMT_THROW(FormatError("number is too big")); return value; } inline void require_numeric_argument(const Arg &arg, char spec) { if (arg.type > Arg::LAST_NUMERIC_TYPE) { std::string message = fmt::format("format specifier '{}' requires numeric argument", spec); FMT_THROW(fmt::FormatError(message)); } } template <typename Char> void check_sign(const Char *&s, const Arg &arg) { char sign = static_cast<char>(*s); require_numeric_argument(arg, sign); if (arg.type == Arg::UINT || arg.type == Arg::ULONG_LONG) { FMT_THROW(FormatError(fmt::format( "format specifier '{}' requires signed argument", sign))); } ++s; } } // namespace internal template <typename Char, typename AF> inline internal::Arg BasicFormatter<Char, AF>::get_arg( BasicStringRef<Char> arg_name, const char *&error) { if (check_no_auto_index(error)) { map_.init(args()); const internal::Arg *arg = map_.find(arg_name); if (arg) return *arg; error = "argument not found"; } return internal::Arg(); } template <typename Char, typename AF> inline internal::Arg BasicFormatter<Char, AF>::parse_arg_index(const Char *&s) { const char *error = 0; internal::Arg arg = *s < '0' || *s > '9' ? next_arg(error) : get_arg(internal::parse_nonnegative_int(s), error); if (error) { FMT_THROW(FormatError( *s != '}' && *s != ':' ? "invalid format string" : error)); } return arg; } template <typename Char, typename AF> inline internal::Arg BasicFormatter<Char, AF>::parse_arg_name(const Char *&s) { assert(internal::is_name_start(*s)); const Char *start = s; Char c; do { c = *++s; } while (internal::is_name_start(c) || ('0' <= c && c <= '9')); const char *error = 0; internal::Arg arg = get_arg(BasicStringRef<Char>(start, s - start), error); if (error) FMT_THROW(FormatError(error)); return arg; } template <typename Char, typename ArgFormatter> const Char *BasicFormatter<Char, ArgFormatter>::format( const Char *&format_str, const internal::Arg &arg) { using internal::Arg; const Char *s = format_str; FormatSpec spec; if (*s == ':') { if (arg.type == Arg::CUSTOM) { arg.custom.format(this, arg.custom.value, &s); return s; } ++s; // Parse fill and alignment. if (Char c = *s) { const Char *p = s + 1; spec.align_ = ALIGN_DEFAULT; do { switch (*p) { case '<': spec.align_ = ALIGN_LEFT; break; case '>': spec.align_ = ALIGN_RIGHT; break; case '=': spec.align_ = ALIGN_NUMERIC; break; case '^': spec.align_ = ALIGN_CENTER; break; } if (spec.align_ != ALIGN_DEFAULT) { if (p != s) { if (c == '}') break; if (c == '{') FMT_THROW(FormatError("invalid fill character '{'")); s += 2; spec.fill_ = c; } else ++s; if (spec.align_ == ALIGN_NUMERIC) require_numeric_argument(arg, '='); break; } } while (--p >= s); } // Parse sign. switch (*s) { case '+': check_sign(s, arg); spec.flags_ |= SIGN_FLAG | PLUS_FLAG; break; case '-': check_sign(s, arg); spec.flags_ |= MINUS_FLAG; break; case ' ': check_sign(s, arg); spec.flags_ |= SIGN_FLAG; break; } if (*s == '#') { require_numeric_argument(arg, '#'); spec.flags_ |= HASH_FLAG; ++s; } // Parse zero flag. if (*s == '0') { require_numeric_argument(arg, '0'); spec.align_ = ALIGN_NUMERIC; spec.fill_ = '0'; ++s; } // Parse width. if ('0' <= *s && *s <= '9') { spec.width_ = internal::parse_nonnegative_int(s); } else if (*s == '{') { ++s; Arg width_arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; switch (width_arg.type) { case Arg::INT: if (width_arg.int_value < 0) FMT_THROW(FormatError("negative width")); value = width_arg.int_value; break; case Arg::UINT: value = width_arg.uint_value; break; case Arg::LONG_LONG: if (width_arg.long_long_value < 0) FMT_THROW(FormatError("negative width")); value = width_arg.long_long_value; break; case Arg::ULONG_LONG: value = width_arg.ulong_long_value; break; default: FMT_THROW(FormatError("width is not integer")); } if (value > (std::numeric_limits<int>::max)()) FMT_THROW(FormatError("number is too big")); spec.width_ = static_cast<int>(value); } // Parse precision. if (*s == '.') { ++s; spec.precision_ = 0; if ('0' <= *s && *s <= '9') { spec.precision_ = internal::parse_nonnegative_int(s); } else if (*s == '{') { ++s; Arg precision_arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); if (*s++ != '}') FMT_THROW(FormatError("invalid format string")); ULongLong value = 0; switch (precision_arg.type) { case Arg::INT: if (precision_arg.int_value < 0) FMT_THROW(FormatError("negative precision")); value = precision_arg.int_value; break; case Arg::UINT: value = precision_arg.uint_value; break; case Arg::LONG_LONG: if (precision_arg.long_long_value < 0) FMT_THROW(FormatError("negative precision")); value = precision_arg.long_long_value; break; case Arg::ULONG_LONG: value = precision_arg.ulong_long_value; break; default: FMT_THROW(FormatError("precision is not integer")); } if (value > (std::numeric_limits<int>::max)()) FMT_THROW(FormatError("number is too big")); spec.precision_ = static_cast<int>(value); } else { FMT_THROW(FormatError("missing precision specifier")); } if (arg.type <= Arg::LAST_INTEGER_TYPE || arg.type == Arg::POINTER) { FMT_THROW(FormatError( fmt::format("precision not allowed in {} format specifier", arg.type == Arg::POINTER ? "pointer" : "integer"))); } } // Parse type. if (*s != '}' && *s) spec.type_ = static_cast<char>(*s++); } if (*s++ != '}') FMT_THROW(FormatError("missing '}' in format string")); // Format argument. ArgFormatter(*this, spec, s - 1).visit(arg); return s; } template <typename Char, typename AF> void BasicFormatter<Char, AF>::format(BasicCStringRef<Char> format_str) { const Char *s = format_str.c_str(); const Char *start = s; while (*s) { Char c = *s++; if (c != '{' && c != '}') continue; if (*s == c) { write(writer_, start, s); start = ++s; continue; } if (c == '}') FMT_THROW(FormatError("unmatched '}' in format string")); write(writer_, start, s - 1); internal::Arg arg = internal::is_name_start(*s) ? parse_arg_name(s) : parse_arg_index(s); start = s = format(s, arg); } write(writer_, start, s); } } // namespace fmt #if FMT_USE_USER_DEFINED_LITERALS namespace fmt { namespace internal { template <typename Char> struct UdlFormat { const Char *str; template <typename... Args> auto operator()(Args && ... args) const -> decltype(format(str, std::forward<Args>(args)...)) { return format(str, std::forward<Args>(args)...); } }; template <typename Char> struct UdlArg { const Char *str; template <typename T> NamedArg<Char> operator=(T &&value) const { return {str, std::forward<T>(value)}; } }; } // namespace internal inline namespace literals { /** \rst C++11 literal equivalent of :func:`fmt::format`. **Example**:: using namespace fmt::literals; std::string message = "The answer is {}"_format(42); \endrst */ inline internal::UdlFormat<char> operator"" _format(const char *s, std::size_t) { return {s}; } inline internal::UdlFormat<wchar_t> operator"" _format(const wchar_t *s, std::size_t) { return {s}; } /** \rst C++11 literal equivalent of :func:`fmt::arg`. **Example**:: using namespace fmt::literals; print("Elapsed time: {s:.2f} seconds", "s"_a=1.23); \endrst */ inline internal::UdlArg<char> operator"" _a(const char *s, std::size_t) { return {s}; } inline internal::UdlArg<wchar_t> operator"" _a(const wchar_t *s, std::size_t) { return {s}; } } // inline namespace literals } // namespace fmt #endif // FMT_USE_USER_DEFINED_LITERALS // Restore warnings. #if FMT_GCC_VERSION >= 406 # pragma GCC diagnostic pop #endif #if defined(__clang__) && !defined(FMT_ICC_VERSION) # pragma clang diagnostic pop #endif #ifdef FMT_HEADER_ONLY # define FMT_FUNC inline # include "fmt/format_impl.hpp" #else # define FMT_FUNC #endif #endif // FMT_FORMAT_H_
32.685886
132
0.619755
BenBE
cda700bc2549a61fb7f0943032d5505c70aef575
509
cpp
C++
src/cpsl.cpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/cpsl.cpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/cpsl.cpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include "src/AST/Program.hpp" extern int yyparse(); extern FILE *yyin; int main(int argc, char **argv) { if (argc > 1) { const auto infile = std::fopen(argv[1], "r"); if (!infile) { std::perror("Error opening file"); return EXIT_FAILURE; } yyin = infile; } yyparse(); // Program::main->fold_constants(); // Program::main->prettyPrint(); Program::main->emit(); return EXIT_SUCCESS; }
19.576923
53
0.563851
CarsonFox
cda995ab48c2b6b1c2e07954f505d836ac578669
371
hpp
C++
wave_optimization/include/wave/optimization/ceres/loss_function/bisquare_loss.hpp
Jebediah/libwave
c04998c964f0dc7d414783c6e8cf989a2716ad54
[ "MIT" ]
2
2019-06-13T13:47:18.000Z
2019-06-13T14:54:35.000Z
wave_optimization/include/wave/optimization/ceres/loss_function/bisquare_loss.hpp
Jebediah/libwave
c04998c964f0dc7d414783c6e8cf989a2716ad54
[ "MIT" ]
null
null
null
wave_optimization/include/wave/optimization/ceres/loss_function/bisquare_loss.hpp
Jebediah/libwave
c04998c964f0dc7d414783c6e8cf989a2716ad54
[ "MIT" ]
1
2020-02-13T02:27:29.000Z
2020-02-13T02:27:29.000Z
#ifndef WAVE_BISQUARE_LOSS_HPP #define WAVE_BISQUARE_LOSS_HPP #include <ceres/loss_function.h> namespace wave { class BisquareLoss : public ceres::LossFunction { public: explicit BisquareLoss(double k) : k2_(k*k) {} virtual void Evaluate(double ip, double* op) const; private: const double k2_; }; } // namespace wave #endif //WAVE_BISQUARE_LOSS_HPP
18.55
55
0.738544
Jebediah
cdaa6fa4da3fcbe8b1ccc1e9ba9c8c9c116ff7ee
5,075
cpp
C++
drivers/Atmel/AT24MAC/example/src/main.cpp
microHAL/microhal-drivers
09925a9696e4794f9ca0b2e9b5e61908ac99b84b
[ "BSD-3-Clause" ]
null
null
null
drivers/Atmel/AT24MAC/example/src/main.cpp
microHAL/microhal-drivers
09925a9696e4794f9ca0b2e9b5e61908ac99b84b
[ "BSD-3-Clause" ]
null
null
null
drivers/Atmel/AT24MAC/example/src/main.cpp
microHAL/microhal-drivers
09925a9696e4794f9ca0b2e9b5e61908ac99b84b
[ "BSD-3-Clause" ]
null
null
null
/** * @license BSD 3-Clause * @copyright Pawel Okas * @version $Id$ * @brief * * @authors Pawel Okas * created on: 30-03-2019 * * @copyright Copyright (c) 2019, Pawel Okas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* ************************************************************************************************************************************************** * INCLUDES */ #include "at24mac.h" #include "bsp.h" #include "diagnostic/diagnostic.h" #define DOCTEST_CONFIG_IMPLEMENT #include "doctest.h" using namespace microhal; using namespace diagnostic; AT24MAC mac(bsp::i2c, 0xA0); doctest::String toString(const AT24MAC::Error& error) { auto string = AT24MAC::toString(error); return {string.data(), string.size()}; } TEST_CASE("Read MAC") { uint64_t eui = 0; // Check if we can read eui CHECK(mac.readEUI(eui) == AT24MAC::Error::None); const uint64_t AtmelMACMask = 0xFCC2'3D00'0000'0000; CHECK((eui & 0xFFFF'FF00'0000'0000) == AtmelMACMask); } TEST_CASE("Read serial number") { AT24MAC::SerialNumber serial; CHECK(mac.readSerialNumber(serial) == AT24MAC::Error::None); } TEST_CASE("Memory read") { uint8_t data[256]; CHECK(mac.read(0x00, data) == AT24MAC::Error::None); uint8_t byte; CHECK(mac.readByte(0x00, byte) == AT24MAC::Error::None); } TEST_CASE("Memory write") { CHECK(mac.writeByte(0x00, 'a') == AT24MAC::Error::None); mac.writeWait(); uint8_t pageData[16] = {0}; CHECK(mac.writePage(0x00, pageData) == AT24MAC::Error::None); mac.writeWait(); // try to write page but not from page begin CHECK(mac.writePage(0x01, pageData) == AT24MAC::Error::Addres); // try write to may data so page may overflow uint8_t overflowPage[17] = {0}; CHECK(mac.writePage(0x01, overflowPage) == AT24MAC::Error::DataOverflow); } TEST_CASE("Memory single byte write read") { uint8_t write = 'a'; CHECK(mac.writeByte(0x00, write) == AT24MAC::Error::None); mac.writeWait(); uint8_t read; CHECK(mac.readByte(0x00, read) == AT24MAC::Error::None); CHECK(write == read); } TEST_CASE("Memory page write read") { uint8_t write[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; CHECK(mac.writePage(0x00, write) == AT24MAC::Error::None); mac.writeWait(); mac.writeWait(); std::array<uint8_t, 16> read = {0}; CHECK(mac.read(0x00, read) == AT24MAC::Error::None); std::array<uint8_t, 16> write_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; CHECK(write_data == read); if (write_data != read) { bsp::debugPort.write((char*)read.data(), read.size()); uint8_t data[256]; if (mac.read(0x00, data) == AT24MAC::Error::None) { bsp::debugPort.write((char*)data, 256); } } } int main(int argc, char* const argv[]) { int result = -1; if (bsp::init()) { bsp::debugPort.write("\n\r------------------- AT24MAC Demo -------------------------\n\r"); diagChannel.setOutputDevice(bsp::debugPort); diagChannel << lock << MICROHAL_INFORMATIONAL << "Starting unit tests." << endl << unlock; doctest::Context context(argc, argv); result = context.run(); if (context.shouldExit()) { // important - query flags (and --exit) rely on the user doing this bsp::deinit(); return result; // propagate the result of the tests } } else { diagChannel << lock << MICROHAL_EMERGENCY << "Unable to open communication ports." << endl << unlock; } return result; }
36.775362
149
0.644532
microHAL
cdae6afc1eaff72126b4a96cc93e3a33739688d3
15,521
cc
C++
.generated/gen/parser/emit_lowering_spec.cc
blutmond/danach
0cd3b27f03d2d2cf563f90a14628b8bf5bb36283
[ "Apache-2.0" ]
null
null
null
.generated/gen/parser/emit_lowering_spec.cc
blutmond/danach
0cd3b27f03d2d2cf563f90a14628b8bf5bb36283
[ "Apache-2.0" ]
null
null
null
.generated/gen/parser/emit_lowering_spec.cc
blutmond/danach
0cd3b27f03d2d2cf563f90a14628b8bf5bb36283
[ "Apache-2.0" ]
null
null
null
namespace lowering_spec { void EmitType(std::ostream& stream, TypeRef* t); void EmitTypeSignature(std::ostream& stream, TypeRef* t); void EmitExpr(std::ostream& stream, ContextFinderContext* ctx, Expr* expr); void EmitStmt(std::ostream& stream, ContextFinderContext* ctx, Stmt* stmt); void EmitFuncDeclHeader(std::ostream& stream, FuncDecl* decl); void EmitFuncDecl(std::ostream& stream, ContextFinderContext* ctx, FuncDecl* decl); void Emit(ASTContext* ast, std::ostream& stream, Module* m); void EmitType(std::ostream& stream, TypeRef* t) { { auto __tmp_switch_name = t; switch (t->getKind()) { case TypeRef::Kind::Void: { auto* t = reinterpret_cast<VoidTypeRef*>(__tmp_switch_name); (void)t; stream << ("void"); break; } case TypeRef::Kind::Member: { auto* t = reinterpret_cast<MemberTypeRef*>(__tmp_switch_name); (void)t; EmitType(stream, t->base); stream << ("::"); stream << (t->name.str); break; } case TypeRef::Kind::Named: { auto* t = reinterpret_cast<NamedTypeRef*>(__tmp_switch_name); (void)t; stream << (t->name.str); break; } default: { stream << ("unknown"); } } } } void EmitTypeSignature(std::ostream& stream, TypeRef* t) { { auto __tmp_switch_name = t; switch (t->getKind()) { case TypeRef::Kind::Void: { auto* t = reinterpret_cast<VoidTypeRef*>(__tmp_switch_name); (void)t; stream << ("void"); break; } case TypeRef::Kind::Template: { auto* t = reinterpret_cast<TemplateTypeRef*>(__tmp_switch_name); (void)t; EmitTypeSignature(stream, t->base); stream << ("<"); int i;i = 0; for (auto arg : t->args) { if (i == 0) { } else { stream << (", "); } increment(i); EmitTypeSignature(stream, arg); } stream << (">"); break; } case TypeRef::Kind::Member: { auto* t = reinterpret_cast<MemberTypeRef*>(__tmp_switch_name); (void)t; EmitType(stream, t->base); stream << ("::"); stream << (t->name.str); break; } case TypeRef::Kind::Named: { auto* t = reinterpret_cast<NamedTypeRef*>(__tmp_switch_name); (void)t; if (t->name.str == "Token") { stream << ("tok::Token"); return; } if (t->name.str == "Array") { stream << ("std::vector"); return; } if (t->name.str == "Map") { stream << ("std::map"); return; } if (t->name.str == "String") { stream << ("string_view"); return; } if (t->name.str == "Stream") { stream << ("std::ostream&"); return; } if (t->name.str == "char") { stream << ("char"); return; } if (t->name.str == "int") { stream << ("int"); return; } if (t->name.str == "bool") { stream << ("bool"); return; } stream << (t->name.str); stream << ("*"); } } } } void EmitExpr(std::ostream& stream, ContextFinderContext* ctx, Expr* expr) { { auto __tmp_switch_name = expr; switch (expr->getKind()) { case Expr::Kind::New: { auto* expr = reinterpret_cast<NewExpr*>(__tmp_switch_name); (void)expr; stream << ("({\nauto* self = new "); EmitType(stream, expr->type); stream << (";\n"); EmitStmt(stream, ctx, expr->body); stream << ("self;\n"); stream << ("})"); break; } case Expr::Kind::NewArena: { auto* expr = reinterpret_cast<NewArenaExpr*>(__tmp_switch_name); (void)expr; stream << ("({\nauto* self = "); stream << (expr->arena_name.str); stream << ("->New<"); EmitType(stream, expr->type); stream << (">();\n"); EmitStmt(stream, ctx, expr->body); stream << ("self;\n"); stream << ("})"); break; } case Expr::Kind::Number: { auto* expr = reinterpret_cast<NumberExpr*>(__tmp_switch_name); (void)expr; stream << (expr->value.str); break; } case Expr::Kind::Str: { auto* expr = reinterpret_cast<StrExpr*>(__tmp_switch_name); (void)expr; stream << (expr->value.str); break; } case Expr::Kind::Dot: { auto* expr = reinterpret_cast<DotExpr*>(__tmp_switch_name); (void)expr; EmitExpr(stream, ctx, expr->base); stream << ("."); stream << (expr->name.str); break; } case Expr::Kind::Arrow: { auto* expr = reinterpret_cast<ArrowExpr*>(__tmp_switch_name); (void)expr; EmitExpr(stream, ctx, expr->base); stream << ("->"); stream << (expr->name.str); break; } case Expr::Kind::Named: { auto* expr = reinterpret_cast<NamedExpr*>(__tmp_switch_name); (void)expr; stream << (expr->name.str); break; } case Expr::Kind::Index: { auto* expr = reinterpret_cast<IndexExpr*>(__tmp_switch_name); (void)expr; EmitExpr(stream, ctx, expr->base); int i;i = 0; stream << ("["); for (auto arg : expr->args) { if (i == 0) { } else { stream << (", "); } increment(i); EmitExpr(stream, ctx, arg); } stream << ("]"); break; } case Expr::Kind::ColonColon: { auto* expr = reinterpret_cast<ColonColonExpr*>(__tmp_switch_name); (void)expr; EmitExpr(stream, ctx, expr->base); stream << ("::"); stream << (expr->name.str); break; } case Expr::Kind::Call: { auto* expr = reinterpret_cast<CallExpr*>(__tmp_switch_name); (void)expr; auto __tmp__base = expr->base; auto base = std::move(__tmp__base); { auto __tmp_switch_name = base; switch (base->getKind()) { case Expr::Kind::Named: { auto* base = reinterpret_cast<NamedExpr*>(__tmp_switch_name); (void)base; if (base->name.str == "assert") { stream << ("({\n"); stream << ("if (!("); EmitExpr(stream, ctx, expr->args[0]); stream << (")) {\n"); stream << ("std::cerr << R\"ASSERT(Assert failed: "); int i;i = 0; for (auto arg : expr->args) { if (i == 0) { } else { stream << (", "); } increment(i); EmitExpr(stream, ctx, arg); } stream << ("\n)ASSERT\";\n"); stream << ("exit(-1);\n"); stream << ("}\n})"); return; } if (base->name.str == "error") { stream << ("({\n"); stream << ("std::cerr << R\"ASSERT(Assert failed: "); int i;i = 0; for (auto arg : expr->args) { if (i == 0) { } else { stream << (", "); } increment(i); EmitExpr(stream, ctx, arg); } stream << ("\n)ASSERT\";\n"); stream << ("exit(-1);\n"); stream << ("})"); return; } break; } default: { } } } EmitExpr(stream, ctx, expr->base); stream << ("("); int i;i = 0; { auto __tmp_switch_name = base; switch (base->getKind()) { case Expr::Kind::Named: { auto* base = reinterpret_cast<NamedExpr*>(__tmp_switch_name); (void)base; for (auto param : ctx->GetHiddenParams(base->name.str)) { if (i == 0) { } else { stream << (", "); } increment(i); stream << (param->name.str); } break; } default: { } } } for (auto arg : expr->args) { if (i == 0) { } else { stream << (", "); } increment(i); EmitExpr(stream, ctx, arg); } stream << (")"); break; } case Expr::Kind::CompEqEq: { auto* expr = reinterpret_cast<CompEqEqExpr*>(__tmp_switch_name); (void)expr; EmitExpr(stream, ctx, expr->lhs); stream << (" == "); EmitExpr(stream, ctx, expr->rhs); break; } case Expr::Kind::Assign: { auto* expr = reinterpret_cast<AssignExpr*>(__tmp_switch_name); (void)expr; EmitExpr(stream, ctx, expr->lhs); stream << (" = "); EmitExpr(stream, ctx, expr->rhs); } } } } void EmitStmt(std::ostream& stream, ContextFinderContext* ctx, Stmt* stmt) { { auto __tmp_switch_name = stmt; switch (stmt->getKind()) { case Stmt::Kind::Compound: { auto* stmt = reinterpret_cast<CompoundStmt*>(__tmp_switch_name); (void)stmt; for (auto cstmt : stmt->stmts) { EmitStmt(stream, ctx, cstmt); } break; } case Stmt::Kind::Return: { auto* stmt = reinterpret_cast<ReturnStmt*>(__tmp_switch_name); (void)stmt; stream << ("return "); EmitExpr(stream, ctx, stmt->expr); stream << (";\n"); break; } case Stmt::Kind::Let: { auto* stmt = reinterpret_cast<LetStmt*>(__tmp_switch_name); (void)stmt; stream << ("auto __tmp__"); stream << (stmt->name.str); stream << (" = "); EmitExpr(stream, ctx, stmt->expr); stream << (";\n"); stream << ("auto "); stream << (stmt->name.str); stream << (" = std::move(__tmp__"); stream << (stmt->name.str); stream << (");\n"); break; } case Stmt::Kind::Var: { auto* stmt = reinterpret_cast<VarStmt*>(__tmp_switch_name); (void)stmt; EmitTypeSignature(stream, stmt->type); stream << (" "); stream << (stmt->name.str); stream << (";"); break; } case Stmt::Kind::OpenWithType: { auto* stmt = reinterpret_cast<OpenWithTypeStmt*>(__tmp_switch_name); (void)stmt; stream << ("{\n"); stream << ("auto __tmp_switch_name = "); stream << (stmt->name.str); stream << (";\n"); stream << ("switch ("); stream << (stmt->name.str); stream << ("->getKind()) {\n"); bool case_open;case_open = false; for (auto cstmt : AsCompound(stmt->body)->stmts) { { auto __tmp_switch_name = cstmt; switch (cstmt->getKind()) { case Stmt::Kind::Case: { auto* cstmt = reinterpret_cast<CaseStmt*>(__tmp_switch_name); (void)cstmt; if (case_open) { stream << ("break;\n} "); } case_open = true; stream << ("case "); EmitType(stream, stmt->type); stream << ("::Kind::"); stream << (cstmt->name.str); stream << (": {\n"); stream << ("auto* "); stream << (stmt->name.str); stream << (" = reinterpret_cast<"); stream << (cstmt->name.str); EmitType(stream, stmt->type); stream << ("*>(__tmp_switch_name);\n"); stream << ("(void)"); stream << (stmt->name.str); stream << (";\n"); break; } case Stmt::Kind::Default: { auto* cstmt = reinterpret_cast<DefaultStmt*>(__tmp_switch_name); (void)cstmt; if (case_open) { stream << ("break;\n} "); } case_open = true; stream << ("default: {\n"); break; } default: { EmitStmt(stream, ctx, cstmt); } } } } if (case_open) { stream << ("}\n"); } stream << ("}\n"); stream << ("}\n"); break; } case Stmt::Kind::Open: { auto* stmt = reinterpret_cast<OpenStmt*>(__tmp_switch_name); (void)stmt; stream << ("{\n"); stream << ("auto __tmp_switch_name = "); stream << (stmt->name.str); stream << (";\n"); stream << ("switch ("); stream << (stmt->name.str); stream << ("->getKind()) {\n"); bool case_open;case_open = false; for (auto cstmt : AsCompound(stmt->body)->stmts) { { auto __tmp_switch_name = cstmt; switch (cstmt->getKind()) { case Stmt::Kind::Case: { auto* cstmt = reinterpret_cast<CaseStmt*>(__tmp_switch_name); (void)cstmt; if (case_open) { stream << ("break;\n} "); } case_open = true; stream << ("case Kind::"); stream << (cstmt->name.str); stream << (": {\n"); stream << ("auto* "); stream << (stmt->name.str); stream << (" = reinterpret_cast<"); stream << (cstmt->name.str); stream << (">(__tmp_switch_name);\n"); break; } case Stmt::Kind::Default: { auto* cstmt = reinterpret_cast<DefaultStmt*>(__tmp_switch_name); (void)cstmt; if (case_open) { stream << ("break;\n} "); } case_open = true; stream << ("default: {\n"); break; } default: { EmitStmt(stream, ctx, cstmt); } } } } if (case_open) { stream << ("}\n"); } stream << ("}\n"); stream << ("}\n"); break; } case Stmt::Kind::Case: { auto* stmt = reinterpret_cast<CaseStmt*>(__tmp_switch_name); (void)stmt; ({ std::cerr << R"ASSERT(Assert failed: "Case can only be used as part of a switch...\n" )ASSERT"; exit(-1); }); break; } case Stmt::Kind::Emitter: { auto* stmt = reinterpret_cast<EmitterStmt*>(__tmp_switch_name); (void)stmt; for (auto cstmt : AsCompound(stmt->body)->stmts) { { auto __tmp_switch_name = cstmt; switch (cstmt->getKind()) { case Stmt::Kind::Discard: { auto* cstmt = reinterpret_cast<DiscardStmt*>(__tmp_switch_name); (void)cstmt; stream << (ctx->GetStdoutContext()); stream << (" << ("); EmitExpr(stream, ctx, cstmt->expr); stream << (");\n"); break; } default: { EmitStmt(stream, ctx, cstmt); } } } } break; } case Stmt::Kind::DbgEmitter: { auto* stmt = reinterpret_cast<DbgEmitterStmt*>(__tmp_switch_name); (void)stmt; for (auto cstmt : AsCompound(stmt->body)->stmts) { { auto __tmp_switch_name = cstmt; switch (cstmt->getKind()) { case Stmt::Kind::Discard: { auto* cstmt = reinterpret_cast<DiscardStmt*>(__tmp_switch_name); (void)cstmt; stream << ("std::cerr << ("); EmitExpr(stream, ctx, cstmt->expr); stream << (");\n"); break; } default: { EmitStmt(stream, ctx, cstmt); } } } } break; } case Stmt::Kind::Break: { auto* stmt = reinterpret_cast<BreakStmt*>(__tmp_switch_name); (void)stmt; stream << ("break;\n"); break; } case Stmt::Kind::ReturnVoid: { auto* stmt = reinterpret_cast<ReturnVoidStmt*>(__tmp_switch_name); (void)stmt; stream << ("return;\n"); break; } case Stmt::Kind::If: { auto* stmt = reinterpret_cast<IfStmt*>(__tmp_switch_name); (void)stmt; stream << ("if ("); EmitExpr(stream, ctx, stmt->cond); stream << (") {\n"); EmitStmt(stream, ctx, stmt->body); stream << ("}\n"); break; } case Stmt::Kind::IfElse: { auto* stmt = reinterpret_cast<IfElseStmt*>(__tmp_switch_name); (void)stmt; stream << ("if ("); EmitExpr(stream, ctx, stmt->cond); stream << (") {\n"); EmitStmt(stream, ctx, stmt->body); stream << ("} else {\n"); EmitStmt(stream, ctx, stmt->else_body); stream << ("}\n"); break; } case Stmt::Kind::Loop: { auto* stmt = reinterpret_cast<LoopStmt*>(__tmp_switch_name); (void)stmt; stream << ("while (true) {\n"); EmitStmt(stream, ctx, stmt->body); stream << ("}\n"); break; } case Stmt::Kind::For: { auto* stmt = reinterpret_cast<ForStmt*>(__tmp_switch_name); (void)stmt; stream << ("for (auto "); stream << (stmt->name.str); stream << (" : "); EmitExpr(stream, ctx, stmt->sequence); stream << (") {\n"); EmitStmt(stream, ctx, stmt->body); stream << ("}\n"); break; } case Stmt::Kind::Scope: { auto* stmt = reinterpret_cast<ScopeStmt*>(__tmp_switch_name); (void)stmt; stream << ("{\n"); stream << ("auto __tmp__"); stream << (stmt->name.str); stream << (" = "); EmitExpr(stream, ctx, stmt->expr); stream << (";\n"); stream << ("auto "); stream << (stmt->name.str); stream << (" = std::move(__tmp__"); stream << (stmt->name.str); stream << (");\n"); EmitStmt(stream, ctx, stmt->body); stream << ("}\n"); break; } case Stmt::Kind::Default: { auto* stmt = reinterpret_cast<DefaultStmt*>(__tmp_switch_name); (void)stmt; ({ std::cerr << R"ASSERT(Assert failed: "Default can only be used as part of a switch...\n" )ASSERT"; exit(-1); }); break; } case Stmt::Kind::Discard: { auto* stmt = reinterpret_cast<DiscardStmt*>(__tmp_switch_name); (void)stmt; EmitExpr(stream, ctx, stmt->expr); stream << (";\n"); } } } } void EmitFuncDeclHeader(std::ostream& stream, FuncDecl* decl) { EmitTypeSignature(stream, decl->ret_t); stream << (" "); stream << (decl->name.str); stream << ("("); int i;i = 0; for (auto arg : decl->args) { if (i == 0) { } else { stream << (", "); } increment(i); EmitTypeSignature(stream, arg->type); stream << (" "); stream << (arg->name.str); } stream << (")"); } void EmitFuncDecl(std::ostream& stream, ContextFinderContext* ctx, FuncDecl* decl) { EmitFuncDeclHeader(stream, decl); stream << (" {\n"); EmitStmt(stream, ctx, decl->body); stream << ("}\n"); } void Emit(ASTContext* ast, std::ostream& stream, Module* m) { stream << ("namespace "); stream << (m->mod_name.str); stream << (" {\n\n"); auto __tmp__ctx = ({ auto* self = ast->New<ContextFinderContext>(); self; }); auto ctx = std::move(__tmp__ctx); for (auto decl : m->decls) { { auto __tmp_switch_name = decl; switch (decl->getKind()) { default: { break; } case Decl::Kind::Func: { auto* decl = reinterpret_cast<FuncDecl*>(__tmp_switch_name); (void)decl; EmitFuncDeclHeader(stream, decl); stream << (";\n"); ctx->RegisterFunc(decl); break; } case Decl::Kind::Context: { auto* decl = reinterpret_cast<ContextDecl*>(__tmp_switch_name); (void)decl; ctx->RegisterContext(decl); } } } } for (auto decl : m->decls) { { auto __tmp_switch_name = decl; switch (decl->getKind()) { default: { break; } case Decl::Kind::Func: { auto* decl = reinterpret_cast<FuncDecl*>(__tmp_switch_name); (void)decl; for (auto arg : decl->args) { auto __tmp__sub_ctx = ctx->isContextUsage(arg->name.str); auto sub_ctx = std::move(__tmp__sub_ctx); if (sub_ctx) { ctx->HardSetContext(decl, sub_ctx); } else { break; } } } } } } stream << ("\n"); for (auto decl : m->decls) { { auto __tmp_switch_name = decl; switch (decl->getKind()) { default: { break; } case Decl::Kind::Func: { auto* decl = reinterpret_cast<FuncDecl*>(__tmp_switch_name); (void)decl; EmitFuncDecl(stream, ctx, decl); } } } } stream << ("\n} // namespace "); stream << (m->mod_name.str); stream << ("\n"); } } // namespace lowering_spec
23.062407
88
0.642613
blutmond
cdb054135f212aecce4815730df925a488dace29
8,185
cc
C++
test/src/test_swdevice.cc
tim-schoenmackers/hippo
ce381551898b4eba7ca73fc64bf138b6ba93a66c
[ "MIT" ]
null
null
null
test/src/test_swdevice.cc
tim-schoenmackers/hippo
ce381551898b4eba7ca73fc64bf138b6ba93a66c
[ "MIT" ]
null
null
null
test/src/test_swdevice.cc
tim-schoenmackers/hippo
ce381551898b4eba7ca73fc64bf138b6ba93a66c
[ "MIT" ]
null
null
null
 // Copyright 2019 HP Development Company, L.P. // SPDX-License-Identifier: MIT #include <windows.h> // for Sleep() #include <cstdio> #include <cstring> #include <cstdlib> #include <fstream> #include <vector> #include <thread> // NOLINT #include <mutex> // NOLINT #include "../include/adder.h" #include "include/sohal.h" extern void print_error(uint64_t err); std::mutex badder_mutex; std::condition_variable badder_condition; // // 'adder' sw device // class BlackAdder : public hippo::Adder { uint64_t add_point_cb(const hippo::PointX &p1, const hippo::PointX &p2, hippo::PointX *pr) override { fprintf(stderr, "%s\n", __FUNCTION__); // add them pr->x = p1.x + p2.x; pr->y = p1.y + p2.y; return 0LL; } uint64_t keystone_cb(const hippo::CameraKeystoneX &k, hippo::CameraKeystoneX *kr) override { fprintf(stderr, "%s\n", __FUNCTION__); // copy param into result memcpy(kr, &k, sizeof(hippo::CameraKeystoneX)); return 0LL; } uint64_t version_cb(hippo::wcharptr *v) override { fprintf(stderr, "%s\n", __FUNCTION__); const wchar_t *msg = L"你好, I don't know my version" L" but here is a \U0001f412 with a \U0001f34c"; size_t len = wcslen(msg)+1; v->resize(len); memcpy(v->data, msg, len*sizeof(wchar_t)); return 0LL; } uint64_t binary_data_cb(const hippo::b64bytes &b1, const hippo::b64bytes &b2, hippo::b64bytes *br1) override { fprintf(stderr, "%s\n", __FUNCTION__); if (b1.len != b2.len) { return -1; } br1->resize(b1.len); for (int i=0; i < b1.len; i++) { br1->data[i] = b1.data[i] + b2.data[i]; } return 0LL; } uint64_t return_error_cb() { fprintf(stderr, "%s\n", __FUNCTION__); return MAKE_HIPPO_ERROR(facility_, hippo::HIPPO_ERROR); } // this funtion has a long timeout, so we'll just sleep for 15 seconds uint64_t slow_call_cb(const int32_t &i, int32_t *j) { fprintf(stderr, "%s\n", __FUNCTION__); for (int i=15; i > 0; i--) { fprintf(stderr, "%s ** %d\n", __FUNCTION__, i); Sleep(1000); } fprintf(stderr, "%s Finished\n", __FUNCTION__); return 0LL; } uint64_t hidden_array_cb(const hippo::DataWithB64Bytes &data_b64, const hippo::DataWithWcharptr &data_wcharptr, hippo::DataWithB64Bytes *ret) override { fprintf(stderr, "%s\n", __FUNCTION__); ret->counter = data_b64.counter; ret->hidden_b64bytes.resize(ret->counter); for (int i=0; i < ret->counter; i++) { ret->hidden_b64bytes.data[i] = data_b64.hidden_b64bytes.data[i] + data_wcharptr.hidden_wcharptr.data[i]; } return 0LL; } uint64_t infinite_timeout_cb() override { for (int i = 17; i > 0; i--) { fprintf(stderr, "%s will return in %d seconds\n", __FUNCTION__, i); Sleep(1000); } fprintf(stderr, "%s Finished\n", __FUNCTION__); return 0LL; } // will disconnect the sw device uint64_t disconnect_device_cb() { fprintf(stderr, "%s\n", __FUNCTION__); // tell the main sw device loop to exit needs_to_disconnect(true); return 0LL; } }; int RunBlackAdder() { uint64_t err = 0LL; BlackAdder badder; // Note that we can run normal SoHal commands from here: hippo::SoHal sohal; char *version = NULL; if (err = sohal.version(&version)) { print_error(err); sohal.free_version(version); } else { fprintf(stderr, "sohal.version: '%s'\n", version); } // grab the mutex std::unique_lock<std::mutex> lock(badder_mutex, std::defer_lock); try { lock.lock(); } catch (std::system_error e) { return -1; } // now connect as a SW device if (err = badder.connect_device()) { print_error(err); goto clean_up; } // and motify the caller lock.unlock(); badder_condition.notify_all(); // and wait for commands while (!badder.needs_to_disconnect()) { Sleep(1000); } // now disconnect as a SW device badder.disconnect_device(); clean_up: fprintf(stderr, "%s EXITING\n", __FUNCTION__); return 0; } // // functions to connect and test the 'adder' sw device // void printCameraKeystone(const hippo::CameraKeystoneX &ks) { fprintf(stderr, "-> Camera Keystone\n"); fprintf(stderr, " \\ -> Enabled: %i\n", ks.enabled); fprintf(stderr, " \\ -> Value\n"); fprintf(stderr, " \\ -> Bottom Left: (%i, %i)\n", ks.value.bottom_left.x, ks.value.bottom_left.y); fprintf(stderr, " \\ -> Bottom Right: (%i, %i)\n", ks.value.bottom_right.x, ks.value.bottom_right.y); fprintf(stderr, " \\ -> Top Left: (%i, %i)\n", ks.value.top_left.x, ks.value.top_left.y); fprintf(stderr, " \\ -> Top Right: (%i, %i)\n", ks.value.top_right.x, ks.value.top_right.y); } uint64_t TestSWDevice(void) { uint64_t err = 0LL; fprintf(stderr, "######################################\n"); fprintf(stderr, " Now Testing Adder SW device Commands\n"); fprintf(stderr, "######################################\n"); ADD_FILE_TO_MAP(); // will add this file to the file/error map std::unique_lock<std::mutex> lock(badder_mutex, std::defer_lock); try { lock.lock(); } catch (std::system_error e) { return MAKE_HIPPO_ERROR(hippo::HIPPO_SWDEVICE, hippo::HIPPO_ERROR); } std::thread badder_th(RunBlackAdder); // and wait for the SW device to start int timeout = 1; if (std::cv_status::timeout == badder_condition.wait_for(lock, std::chrono::seconds(timeout))) { fprintf(stderr, "** TIMEOUT!!\n"); return MAKE_HIPPO_ERROR(hippo::HIPPO_SWDEVICE, hippo::HIPPO_TIMEOUT); } hippo::Adder adder; // PointX from ./py/adder.json hippo::PointX p1, p2, pr; p1.x = 1; p1.y = 2; p2.x = 3; p2.y = 4; if (err = adder.add_point(p1, p2, &pr)) { print_error(err); } else { fprintf(stderr, "adder.add_point((%d,%d),(%d,%d)) = (%d, %d)\n", p1.x, p1.y, p2.x, p2.y, pr.x, pr.y); } // CameraKeystoneX from ./py/adder.json hippo::CameraKeystoneX k, kr; k.enabled = true; k.value.bottom_left.x = 10; k.value.bottom_left.y = 11; k.value.bottom_right.x = 12; k.value.bottom_right.y = 13; k.value.top_left.x = 14; k.value.top_left.y = 15; k.value.top_right.x = 16; k.value.top_right.y = 17; if (err=adder.keystone(k, &kr)) { print_error(err); } else { printCameraKeystone(kr); } hippo::wcharptr v; if (err=adder.version(&v)) { print_error(err); } else { fwprintf(stderr, L"version: '%s'\n", v.data); } if (err = adder.return_error()) { print_error(err); } hippo::b64bytes b1(127), b2(127), br1; for (int i=0; i < b1.len; i++) { b1.data[i] = i; b2.data[i] = i; } if (err = adder.binary_data(b1, b2, &br1)) { print_error(err); } else { for (int i=0; i < b1.len; i++) { if (b1.data[i] + b2.data[i] != br1.data[i]) { fprintf(stderr, "data[%d] %02x + %02x != %02x\n", i, b1.data[i], b2.data[i], br1.data[i]); } } } int32_t i, j; if (err = adder.slow_call(i, &j)) { print_error(err); } if (err = adder.infinite_timeout()) { print_error(err); } hippo::DataWithB64Bytes h1, hr1; hippo::DataWithWcharptr h2; h1.counter = 10; h1.hidden_b64bytes.resize(h1.counter); h2.counter = h1.counter + 1; // need space for '\0' h2.hidden_wcharptr.resize(h2.counter); for (int i=0; i < h1.counter; i++) { h1.hidden_b64bytes.data[i] = i; h2.hidden_wcharptr.data[i] = i+1; } if (err = adder.hidden_array(h1, h2, &hr1)) { print_error(err); } else { fprintf(stderr, "<h1,h2,hr1>:\n "); for (int i=0; i < h1.counter; i++) { fprintf(stderr, "<%02x,%02x,%02x>,", h1.hidden_b64bytes.data[i], h2.hidden_wcharptr.data[i], hr1.hidden_b64bytes.data[i]); } fprintf(stderr, "\n"); } if (err = adder.disconnect_device()) { print_error(err); } badder_th.join(); return 0LL; }
27.013201
72
0.589982
tim-schoenmackers
cdb1b79894bf89c40fe8cf13629450393d27bfd7
204
cpp
C++
src/Circuit.cpp
bu-cms/dtcq
aef2da62f91ecf1694c1669d301f9cf0bf096c9e
[ "MIT" ]
null
null
null
src/Circuit.cpp
bu-cms/dtcq
aef2da62f91ecf1694c1669d301f9cf0bf096c9e
[ "MIT" ]
4
2021-04-26T07:28:03.000Z
2021-06-16T15:47:37.000Z
src/Circuit.cpp
bu-cms/dtcq
aef2da62f91ecf1694c1669d301f9cf0bf096c9e
[ "MIT" ]
null
null
null
#include<interface/Circuit.h> void Circuit::tick(){ for(auto component : components) { component->tick(); } for(auto component : components) { component->post_tick(); } };
20.4
38
0.598039
bu-cms
cdb442671ac1c9dbd791e828bd41c97017751d3b
2,381
cc
C++
Core/DianYing/Source/Core/Resource/Resource/Attachment/FDyAttachmentGeneralResource.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
4
2019-03-17T19:46:54.000Z
2019-12-09T20:11:01.000Z
Core/DianYing/Source/Core/Resource/Resource/Attachment/FDyAttachmentGeneralResource.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
Core/DianYing/Source/Core/Resource/Resource/Attachment/FDyAttachmentGeneralResource.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
#include <precompiled.h> /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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 <Dy/Core/Resource/Resource/Attachment/FResourceAttachmentGeneral.h> #include <Dy/Core/Rendering/Wrapper/XGLWrapper.h> #include <Dy/Core/Rendering/Wrapper/PGLAttachmentDescriptor.h> namespace dy { FResourceAttachmentGeneral::FResourceAttachmentGeneral(const FInformationAttachment& iInformation) { this->mSpecifierName = iInformation.GetSpecifierName(); this->mInformationBinder.TryRequireResource(this->mSpecifierName); PGLAttachmentDescriptor descriptor; descriptor.mBorderColor = iInformation.GetBorderColor(); descriptor.mBufferSize = iInformation.GetBufferSize(); descriptor.mParameterList = iInformation.GetParameterList(); descriptor.mBufferFormat = iInformation.GetBufferType(); descriptor.mAttachmentType = iInformation.GetAttachmentType(); descriptor.mSpecifiedMipmapLevel = iInformation.GetMipmapLevel(); descriptor.mDepthNumber = iInformation.GetDepthNumber(); if (descriptor.mParameterList.empty() == false) { descriptor.mIsUsingCustomizedParameter = true; } { MDY_GRAPHIC_SET_CRITICALSECITON(); const auto optAttachmentId = XGLWrapper::CreateAttachment(descriptor); MDY_ASSERT_MSG(optAttachmentId.has_value() == true, "Attachment creation must be succeeded."); this->mAttachmentId = optAttachmentId.value(); } } FResourceAttachmentGeneral::~FResourceAttachmentGeneral() { MDY_GRAPHIC_SET_CRITICALSECITON(); MDY_CALL_ASSERT_SUCCESS( XGLWrapper::DeleteAttachment(this->mAttachmentId, this->IsRenderBuffer()) ); } TU32 FResourceAttachmentGeneral::GetSourceAttachmentId() const noexcept { return this->mAttachmentId; } TU32 FResourceAttachmentGeneral::GetTargetAttachmentId() const noexcept { return this->GetSourceAttachmentId(); } } /// ::dy namespace
36.630769
98
0.764385
liliilli
cdb4f17d406f3f836bf741e76de5dd35389842cb
9,594
hh
C++
thirdparty/graph-tools-master/include/graphalign/dagAligner/AffineAlignMatrix.hh
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
122
2017-01-06T16:19:31.000Z
2022-03-08T00:05:50.000Z
thirdparty/graph-tools-master/include/graphalign/dagAligner/AffineAlignMatrix.hh
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
90
2017-01-04T00:23:34.000Z
2022-02-27T12:55:52.000Z
thirdparty/graph-tools-master/include/graphalign/dagAligner/AffineAlignMatrix.hh
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
35
2017-03-02T13:39:58.000Z
2022-03-30T17:34:11.000Z
// // GraphTools library // Copyright 2017-2019 Illumina, Inc. // All rights reserved. // // Author: Roman Petrovski <RPetrovski@illumina.com> // // 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 #include <algorithm> #include <iostream> #include "Details.hh" namespace graphalign { namespace dagAligner { // the 2-d table of scores filled during the alignment template <typename PenaltyMatrixT, bool penalizeMove> class AffineAlignMatrix { public: typedef PenaltyMatrixT PenaltyMatrix; private: const PenaltyMatrix penaltyMatrix_; const Score gapOpen_; const Score gapExt_; AlignMatrix v_; AlignMatrix g_; AlignMatrix f_; AlignMatrix e_; std::vector<typename PenaltyMatrix::QueryChar> query_; std::vector<typename PenaltyMatrix::TargetChar> target_; public: AffineAlignMatrix(const PenaltyMatrix& penaltyMatrix, Score gapOpen, Score gapExt) : penaltyMatrix_(penaltyMatrix) , gapOpen_(gapOpen) , gapExt_(gapExt) { } template <typename QueryIt, typename TargetIt> void init(QueryIt queryBegin, QueryIt queryEnd, TargetIt targetBegin, TargetIt targetEnd, const EdgeMap& edgeMap) { if (queryEnd == queryBegin) { throw std::logic_error("Empty query is not allowed."); } if (targetEnd == targetBegin) { throw std::logic_error("Empty target is not allowed."); } query_.clear(); penaltyMatrix_.translateQuery(queryBegin, queryEnd, std::back_inserter(query_)); target_.clear(); penaltyMatrix_.translateTarget(targetBegin, targetEnd, std::back_inserter(target_)); reset(edgeMap); fill(edgeMap); } typedef AlignMatrix::const_iterator const_iterator; template <bool localAlign> const_iterator nextBestAlign(const_iterator start, Score& bestScore) const { return !localAlign ? v_.nextBestAlign(start, queryLen() - 1, bestScore) : v_.nextBestAlign(start, bestScore); } const_iterator alignBegin() const { return v_.cellOneOne(); } const_iterator alignEnd() const { return v_.end(); } int targetOffset(const_iterator cell) const { return std::distance(v_.cellOneOne(), cell) / v_.paddedRowLen(); } int queryOffset(const_iterator cell) const { return std::distance(v_.cellOneOne(), cell) % v_.paddedRowLen(); } int queryLen() const { return query_.size(); } bool isInsertion(int q, int t) const { if (-1 == q) { return false; } const Score insExtScore = v_.at(q, t) - f_.at(q - 1, t); const Score insOpenScore = v_.at(q, t) - v_.at(q - 1, t); return gapExt_ == insExtScore || gapOpen_ + gapExt_ == insOpenScore; } bool isDeletion(int q, int t, int p) const { // q == -1 is ok here, just check the score match as usual const Score delExtScore = v_.at(q, t) - e_.at(q, p); const Score delOpenScore = v_.at(q, t) - v_.at(q, p); return gapExt_ == delExtScore || gapOpen_ + gapExt_ == delOpenScore; } bool isMatch(int q, int t, int p) const { if (-1 == q) { return false; } typename PenaltyMatrix::QueryChar queryChar = query_[q]; typename PenaltyMatrix::TargetChar targetChar = target_[t]; const Score alnScore = v_.at(q, t) - v_.at(q - 1, p); return penaltyMatrix_.isMatch(queryChar, targetChar) && penaltyMatrix_(queryChar, targetChar) == alnScore; } bool isMismatch(int q, int t, int p) const { if (-1 == q) { return false; } typename PenaltyMatrix::QueryChar queryChar = query_[q]; typename PenaltyMatrix::TargetChar targetChar = target_[t]; const Score alnScore = v_.at(q, t) - v_.at(q - 1, p); return !penaltyMatrix_.isMatch(queryChar, targetChar) && penaltyMatrix_(queryChar, targetChar) == alnScore; } private: void computeAlignPenalties(int q, typename PenaltyMatrix::TargetChar tc, Score penalties[16]) { const typename PenaltyMatrix::QueryChar* query = &query_[q]; for (int i = 0; i < 16; ++i) { penalties[i] = penaltyMatrix_(query[i], tc); } } void reset(const EdgeMap& edgeMap) { const int qLen = query_.size(); const int tLen = target_.size(); v_.reset(qLen, tLen); g_.reset(qLen, tLen); f_.reset(qLen, tLen); e_.reset(qLen, tLen); // top left must be 0 and never change if (v_.at(-1, -1)) { throw std::logic_error("Incorrectly initialized v_"); } if (g_.at(-1, -1)) { throw std::logic_error("Incorrectly initialized g_"); } if (f_.at(-1, -1)) { throw std::logic_error("Incorrectly initialized f_"); } if (e_.at(-1, -1)) { throw std::logic_error("Incorrectly initialized e_"); } // first column penalises for deletion for (int t = 0; t < tLen; ++t) { if (penalizeMove) { for (EdgeMap::OffsetEdges::const_iterator prevNodeIndexIt = edgeMap.prevNodesBegin(t); prevNodeIndexIt != edgeMap.prevNodesEnd(t); ++prevNodeIndexIt) { const int p = *prevNodeIndexIt; v_.at(-1, t) = std::max(v_.at(-1, t), Score(v_.at(-1, p) + gapOpen_ + gapExt_)); f_.at(-1, t) = std::max(v_.at(-1, t), Score(f_.at(-1, p) + gapOpen_ + gapExt_)); } } else { v_.at(-1, t) = 0; f_.at(-1, t) = 0; } } // first row penalises for insertion for (int q = 0; q < qLen; ++q) { v_.at(q, -1) = v_.at(q - 1, -1) + gapOpen_ + gapExt_; e_.at(q, -1) = e_.at(q - 1, -1) + gapOpen_ + gapExt_; } } void fill(const EdgeMap& edgeMap) { const int qLen = query_.size(); const int tLen = target_.size(); for (int t = 0; t < tLen; ++t) { for (EdgeMap::OffsetEdges::const_iterator prevNodeIndexIt = edgeMap.prevNodesBegin(t); edgeMap.prevNodesEnd(t) != prevNodeIndexIt; ++prevNodeIndexIt) { const int p = *prevNodeIndexIt; recomputeForDeletion(qLen, t, p); recomputeForAlign(qLen, t, p); } consolidate(qLen, t); recomputeForInsertion(qLen, t); } } void recomputeForDeletion(int qLen, int t, int p) { Score* ep = e_.row(0, p); Score* v = v_.row(0, p); Score* et = e_.row(0, t); for (int i = 0; i < qLen; ++i) { et[i] = std::max<Score>(et[i], std::max(ep[i] + gapExt_, v[i] + gapOpen_ + gapExt_)); } } void recomputeForAlign(int qLen, int t, int p) { const typename PenaltyMatrix::QueryChar* query = &query_[0]; Score* g = g_.row(0, t); Score* v = v_.row(-1, p); for (int i = 0; i < qLen; ++i) { g[i] = std::max<Score>(g[i], v[i] + penaltyMatrix_(query[i], target_[t])); } } void consolidate(int qLen, int t) { Score* e = e_.row(0, t); Score* g = g_.row(0, t); Score* v = v_.row(0, t); for (int i = 0; i < qLen; ++i) { v[i] = std::max(v[i], std::max(g[i], e[i])); } } void recomputeForInsertion(int qLen, int t) { Score* v = v_.row(0, t); Score* f = f_.row(0, t); Score* fp = f_.row(-1, t); Score* vp = v_.row(-1, t); for (int i = 0; i < qLen; ++i) { f[i] = std::max<Score>(f[i], std::max<Score>((fp[i] + gapExt_), (vp[i] + gapOpen_ + gapExt_))); v[i] = std::max(v[i], f[i]); } } friend std::ostream& operator<<(std::ostream& os, const AffineAlignMatrix& matrix) { return os << "AffineAlignMatrix(" << matrix.v_ << ")"; } }; } // namespace dagAligner } // namespace graphalign
33.545455
120
0.512508
AlesMaver
cdb7f0ea55b3f2d936588d240c160439709e54f5
20,848
cpp
C++
src/vtk_viz.cpp
sphamil/enrico
7a346c14d113c0068382fdd5ae82f6c7d253c9eb
[ "BSD-3-Clause" ]
null
null
null
src/vtk_viz.cpp
sphamil/enrico
7a346c14d113c0068382fdd5ae82f6c7d253c9eb
[ "BSD-3-Clause" ]
null
null
null
src/vtk_viz.cpp
sphamil/enrico
7a346c14d113c0068382fdd5ae82f6c7d253c9eb
[ "BSD-3-Clause" ]
null
null
null
#include <cmath> #include "enrico/vtk_viz.h" #include "xtensor/xadapt.hpp" #include "xtensor/xbuilder.hpp" #include "xtensor/xtensor.hpp" #include "xtensor/xview.hpp" #include "openmc/constants.h" // some constant values const int WEDGE_TYPE_ = 13; const size_t WEDGE_SIZE_ = 6; const int HEX_TYPE_ = 12; const size_t HEX_SIZE_ = 8; const int INVALID_CONN_ = -1; const size_t CONN_STRIDE_ = HEX_SIZE_ + 1; namespace enrico { using std::ofstream; using xt::xtensor; using xt::placeholders::_; xtensor<double, 2> create_ring(double radius, size_t t_resolution) { xtensor<double, 1> x({t_resolution}, 0.0); xtensor<double, 1> y({t_resolution}, 0.0); xtensor<double, 1> theta; theta = xt::linspace<double>(0., 2. * M_PI, t_resolution + 1); theta = xt::view(theta, xt::range(0, -1)); // remove last value x = radius * xt::cos(theta); y = radius * xt::sin(theta); xtensor<double, 2> out({2, (size_t)t_resolution}, 0.0); xt::view(out, 0, xt::all()) = x; xt::view(out, 1, xt::all()) = y; return out; } xtensor<int, 2> hex_ring(size_t start_idx, size_t resolution, size_t z_shift) { xtensor<int, 2> out({resolution, HEX_SIZE_}, 0); // set connectivity of the first z-layer // first two points - along the inner radial ring xt::view(out, xt::all(), 0) = xt::arange(start_idx, resolution + start_idx); xt::view(out, xt::all(), 1) = xt::arange(start_idx + 1, resolution + start_idx + 1); // second two poitns - along the outer radial ring, going back toward the starting point xt::view(out, xt::all(), 2) = xt::view(out, xt::all(), 1) + resolution; xt::view(out, xt::all(), 3) = xt::view(out, xt::all(), 0) + resolution; // adjust last point id for periodic condition on both layers, using hexes now xt::view(out, resolution - 1, 1) = start_idx; xt::view(out, resolution - 1, 2) = resolution + start_idx; // copy connectivity of the first layer to the second // and shift by number of points xt::view(out, xt::all(), xt::range(4, HEX_SIZE_)) += xt::view(out, xt::all(), xt::range(0, 4)); // shift connectivity down one layer xt::view(out, xt::all(), xt::range(4, HEX_SIZE_)) += z_shift; return out; } SurrogateVtkWriter::SurrogateVtkWriter(const SurrogateHeatDriver& surrogate_ref, size_t t_res, const std::string& regions_to_write, const std::string& data_to_write) : surrogate_(surrogate_ref) , radial_res_(t_res) { // read data specs data_out_ = VizDataType::all; if ("all" == data_to_write) { data_out_ = VizDataType::all; } else if ("source" == data_to_write) { data_out_ = VizDataType::source; } else if ("temp" == data_to_write || "temperature" == data_to_write) { data_out_ = VizDataType::temp; } // read data specs regions_out_ = VizRegionType::all; if ("all" == regions_to_write) { regions_out_ = VizRegionType::all; } else if ("fuel" == regions_to_write) { regions_out_ = VizRegionType::fuel; } else if ("cladding" == regions_to_write) { regions_out_ = VizRegionType::clad; } // Set some necessary values ahead of time n_axial_sections_ = surrogate_.z_.size() - 1; n_axial_points_ = surrogate_.z_.size(); n_radial_fuel_sections_ = surrogate_.r_grid_fuel_.size() - 1; n_radial_clad_sections_ = surrogate_.r_grid_clad_.size() - 1; n_radial_sections_ = n_radial_fuel_sections_ + n_radial_clad_sections_; n_sections_per_plane_ = n_radial_sections_ * radial_res_; // fuel points fuel_points_per_plane_ = n_radial_fuel_sections_ * radial_res_ + 1; n_fuel_points_ = fuel_points_per_plane_ * surrogate_.z_.size(); // cladding points clad_points_per_plane_ = surrogate_.r_grid_clad_.size() * radial_res_; n_clad_points_ = clad_points_per_plane_ * surrogate_.r_grid_clad_.size(); // fuel elements, entries n_fuel_elements_ = n_radial_fuel_sections_ * radial_res_ * n_axial_sections_; n_clad_elements_ = n_radial_clad_sections_ * radial_res_ * n_axial_sections_; // wedge regions n_fuel_entries_per_plane_ = radial_res_ * (WEDGE_SIZE_ + 1); // other radial regions n_fuel_entries_per_plane_ += radial_res_ * (HEX_SIZE_ + 1) * (n_radial_fuel_sections_ - 1); n_clad_entries_per_plane_ = radial_res_ * (HEX_SIZE_ + 1) * n_radial_clad_sections_; n_entries_per_plane_ = n_fuel_entries_per_plane_ + n_clad_entries_per_plane_; // set totals based on region if (VizRegionType::all == regions_out_) { points_per_plane_ = fuel_points_per_plane_ + clad_points_per_plane_; n_radial_sections_ = n_radial_fuel_sections_ + n_radial_clad_sections_; n_entries_per_plane_ = n_fuel_entries_per_plane_ + n_clad_entries_per_plane_; } else if (VizRegionType::fuel == regions_out_) { points_per_plane_ = fuel_points_per_plane_; n_radial_sections_ = n_radial_fuel_sections_; n_entries_per_plane_ = n_fuel_entries_per_plane_; } else if (VizRegionType::clad == regions_out_) { points_per_plane_ = clad_points_per_plane_; n_radial_sections_ = n_radial_clad_sections_; n_entries_per_plane_ = n_clad_entries_per_plane_; } // totals n_points_ = points_per_plane_ * surrogate_.z_.size(); n_mesh_elements_ = n_radial_sections_ * radial_res_ * n_axial_sections_; n_entries_ = n_entries_per_plane_ * n_axial_sections_; // generate a representative set of points and connectivity points_ = points(); conn_ = conn(); types_ = types(); } void SurrogateVtkWriter::write(std::string filename) { // open file ofstream fh(filename, std::ofstream::out); // write vtk header write_header(fh); // write vertex locations write_points(fh); // write wedge/hex element connectivity write_element_connectivity(fh); // write types for wedge/hex elements write_element_types(fh); // write specified data to the vtk file write_data(fh); // close the file fh.close(); } // write_vtk void SurrogateVtkWriter::write_header(ofstream& vtk_file) { vtk_file << "# vtk DataFile Version 2.0\n"; vtk_file << "No comment\nASCII\nDATASET UNSTRUCTURED_GRID\n"; } void SurrogateVtkWriter::write_points(ofstream& vtk_file) { vtk_file << "POINTS " << surrogate_.n_pins_ * n_points_ << " float\n"; for (size_t pin = 0; pin < surrogate_.n_pins_; pin++) { // translate pin template to pin center xtensor<double, 1> pnts = points_for_pin(surrogate_.pin_centers_(pin, 0), surrogate_.pin_centers_(pin, 1)); for (auto val = pnts.cbegin(); val != pnts.cend(); val += 3) { vtk_file << *val << " " << *(val + 1) << " " << *(val + 2) << "\n"; } } } // write_points void SurrogateVtkWriter::write_element_connectivity(ofstream& vtk_file) { // write number of connectivity entries vtk_file << "\nCELLS " << surrogate_.n_pins_ * n_mesh_elements_ << " " << surrogate_.n_pins_ * n_entries_ << "\n"; // pin loop for (size_t pin = 0; pin < surrogate_.n_pins_; pin++) { // get the connectivity for a given pin, using an // offset to get the connectivity values correct xtensor<int, 1> conn = conn_for_pin(pin * n_points_); // write the connectivity values to file for this pin for (auto val = conn.cbegin(); val != conn.cend(); val += CONN_STRIDE_) { for (size_t i = 0; i < CONN_STRIDE_; i++) { auto v = *(val + i); // mask out any negative connectivity values if (v != INVALID_CONN_) { vtk_file << v << " "; } } vtk_file << "\n"; } } } // write_element_connectivity void SurrogateVtkWriter::write_element_types(ofstream& vtk_file) { // write number of cell type entries vtk_file << "\nCELL_TYPES " << surrogate_.n_pins_ * n_mesh_elements_ << "\n"; // pin loop for (size_t pin = 0; pin < surrogate_.n_pins_; pin++) { // write the template for each pin for (auto v : types_) { vtk_file << v << "\n"; } } vtk_file << "\n"; } // write_element_types void SurrogateVtkWriter::write_data(ofstream& vtk_file) { // fuel mesh elements are written first, followed by cladding elements // the data needs to be written in a similar matter // for each radial section, the data point for that radial ring // is repeated radial_res times vtk_file << "CELL_DATA " << surrogate_.n_pins_ * n_mesh_elements_ << "\n"; // check what data we're writing if (VizDataType::all == data_out_ || VizDataType::temp == data_out_) { // temperature data vtk_file << "SCALARS TEMPERATURE double 1\n"; vtk_file << "LOOKUP_TABLE default\n"; // write data for each pin for (size_t pin = 0; pin < surrogate_.n_pins_; pin++) { // write data for specified regions if (VizRegionType::fuel == regions_out_ || VizRegionType::all == regions_out_) { // write all fuel data first for (size_t i = 0; i < n_axial_sections_; i++) { for (size_t j = 0; j < n_radial_fuel_sections_; j++) { for (size_t k = 0; k < radial_res_; k++) { vtk_file << surrogate_.temperature(pin, i, j) << "\n"; } } } } // then write cladding data if (VizRegionType::clad == regions_out_ || VizRegionType::all == regions_out_) { for (size_t i = 0; i < n_axial_sections_; i++) { for (size_t j = 0; j < n_radial_clad_sections_; j++) { for (size_t k = 0; k < radial_res_; k++) { vtk_file << surrogate_.temperature(pin, i, j + n_radial_fuel_sections_) << "\n"; } } } } } // end pin for } if (VizDataType::all == data_out_ || VizDataType::source == data_out_) { // source data vtk_file << "SCALARS SOURCE double 1\n"; vtk_file << "LOOKUP_TABLE default\n"; for (size_t pin = 0; pin < surrogate_.n_pins_; pin++) { // write all fuel data first if (VizRegionType::fuel == regions_out_ || VizRegionType::all == regions_out_) { for (size_t i = 0; i < n_axial_sections_; i++) { for (size_t j = 0; j < n_radial_fuel_sections_; j++) { for (size_t k = 0; k < radial_res_; k++) { vtk_file << surrogate_.source_(pin, i, j) << "\n"; } } } } // then write the cladding data if (VizRegionType::clad == regions_out_ || VizRegionType::all == regions_out_) { for (size_t i = 0; i < n_axial_sections_; i++) { for (size_t j = 0; j < n_radial_clad_sections_; j++) { for (size_t k = 0; k < radial_res_; k++) { vtk_file << surrogate_.source_(pin, i, j + n_radial_fuel_sections_) << "\n"; } } } } } // end pin loop } } // write_data xtensor<double, 1> SurrogateVtkWriter::points_for_pin(double x, double y) { // start with the origin-centered template xtensor<double, 1> points_out = points_; // translate points to pin center xt::view(points_out, xt::range(0, _, 3)) += x; xt::view(points_out, xt::range(1, _, 3)) += y; return points_out; } xtensor<double, 1> SurrogateVtkWriter::points() { xtensor<double, 1> points; if (VizRegionType::fuel == regions_out_) { // get fuel points xtensor<double, 3> fuel_pnts = fuel_points(); points = xt::flatten(fuel_pnts); } else if (VizRegionType::clad == regions_out_) { // get cladding points xtensor<double, 3> clad_pnts = clad_points(); points = xt::flatten(clad_pnts); } else if (VizRegionType::all == regions_out_) { // get both sets of points xtensor<double, 3> fuel_pnts = fuel_points(); xtensor<double, 3> clad_pnts = clad_points(); // concatenate in 1-D and return points = xt::concatenate(xt::xtuple(xt::flatten(fuel_pnts), xt::flatten(clad_pnts))); } return points; } xtensor<double, 3> SurrogateVtkWriter::fuel_points() { // array to hold all point data xt::xarray<double> pnts_out({n_axial_points_, fuel_points_per_plane_, 3}, 0.0); // x and y for a single axial plane in the rod xt::xarray<double> x = xt::zeros<double>({n_radial_fuel_sections_, radial_res_}); xt::xarray<double> y = xt::zeros<double>({n_radial_fuel_sections_, radial_res_}); // generate x/y points for each raidal section for (size_t i = 0; i < n_radial_fuel_sections_; i++) { // first radius in r_grid_fuel_ is zero, start at one double ring_rad = surrogate_.r_grid_fuel_(i + 1); // create a unit ring scaled by radius xtensor<double, 2> ring = create_ring(ring_rad, radial_res_); // set x/y values for this ring xt::view(x, i, xt::all()) = xt::view(ring, 0, xt::all()); xt::view(y, i, xt::all()) = xt::view(ring, 1, xt::all()); } // flatten radial point arrays x = xt::flatten(x); y = xt::flatten(y); // set the point values for each axial plane for (size_t i = 0; i < n_axial_points_; i++) { // set all but the center point, which is always (0,0,z) xt::view(pnts_out, i, xt::range(1, _), 0) = x; xt::view(pnts_out, i, xt::range(1, _), 1) = y; xt::view(pnts_out, i, xt::all(), 2) = surrogate_.z_(i); } return pnts_out; } xtensor<double, 3> SurrogateVtkWriter::clad_points() { // array to hold all point data xt::xarray<double> pnts_out({n_axial_points_, clad_points_per_plane_, 3}, 0.0); // x and y for a single axial plane in the rod xt::xarray<double> x = xt::zeros<double>({n_radial_clad_sections_ + 1, radial_res_}); xt::xarray<double> y = xt::zeros<double>({n_radial_clad_sections_ + 1, radial_res_}); // generate x/y points for each radial ring for (size_t i = 0; i < n_radial_clad_sections_ + 1; i++) { double ring_rad = surrogate_.r_grid_clad_(i); // create a unit ring scaled by radius xtensor<double, 2> ring = create_ring(ring_rad, radial_res_); // set x/y values for this ring xt::view(x, i, xt::all()) = xt::view(ring, 0, xt::all()); xt::view(y, i, xt::all()) = xt::view(ring, 1, xt::all()); } // flatten x,y point arrays x = xt::flatten(x); y = xt::flatten(y); for (size_t i = 0; i < n_axial_points_; i++) { // set all points, no center point for cladding xt::view(pnts_out, i, xt::all(), 0) = x; xt::view(pnts_out, i, xt::all(), 1) = y; xt::view(pnts_out, i, xt::all(), 2) = surrogate_.z_[i]; } return pnts_out; } xtensor<int, 1> SurrogateVtkWriter::conn() { xtensor<int, 1> conn_out; if (VizRegionType::fuel == regions_out_) { // get the fuel connectivity xtensor<int, 4> f_conn = fuel_conn(); conn_out = xt::flatten(f_conn); } else if (VizRegionType::clad == regions_out_) { // get the cladding connectivity xtensor<int, 4> c_conn = clad_conn(); conn_out = xt::flatten(c_conn); } else if (VizRegionType::all == regions_out_) { // get both sets of points xtensor<int, 4> f_conn = fuel_conn(); xtensor<int, 4> c_conn = clad_conn(); // adjust the cladding connectivity by // the number of points in the fuel mesh xt::view(c_conn, xt::all(), xt::all(), xt::all(), xt::range(1, _)) += fuel_points_per_plane_ * n_axial_points_; // concatenate in 1-D and return conn_out = xt::concatenate(xt::xtuple(xt::flatten(f_conn), xt::flatten(c_conn))); } return conn_out; } xtensor<int, 1> SurrogateVtkWriter::conn_for_pin(size_t offset) { xt::xarray<int> conn_out = conn_; conn_out.reshape({n_mesh_elements_, CONN_STRIDE_}); // get locations of all values less than 0 xt::xarray<bool> mask = conn_out < 0; xt::view(conn_out, xt::all(), xt::range(1, _)) += offset; conn_out = xt::flatten(conn_out); // no masked_view in this version of xtensor, // making do with this for now for (size_t i = 0; i < mask.size(); i++) { if (mask(i)) { conn_out(i) = INVALID_CONN_; } } return conn_out; } xtensor<int, 4> SurrogateVtkWriter::fuel_conn() { // size output array xtensor<int, 4> cells_out = xt::zeros<int>( {n_axial_sections_, n_radial_fuel_sections_, radial_res_, HEX_SIZE_ + 1}); // generate a base layer to be extended in Z xtensor<int, 3> base = xt::zeros<int>({n_radial_fuel_sections_, radial_res_, HEX_SIZE_}); // innermost ring (wedges only) xtensor<int, 2> inner_base = xt::zeros<int>({radial_res_, HEX_SIZE_}); size_t one_ = 1, two_ = 2; xt::view(inner_base, xt::all(), 1) = xt::arange(size_t(1), radial_res_ + 1); xt::view(inner_base, xt::all(), 2) = xt::arange(two_, radial_res_ + 2); // adjust last point id for perioic condition xt::view(inner_base, radial_res_ - 1, 2) = 1; // copy connectivity of first z-layer to the second and shift // by the number of points in a plane xt::view(inner_base, xt::all(), xt::range(3, 6)) = xt::view(inner_base, xt::all(), xt::range(0, 3)); xt::strided_view(inner_base, {xt::all(), xt::range(3, 6)}) += fuel_points_per_plane_; // set values for the innermost ring xt::view(base, 0, xt::all(), xt::all()) = inner_base; // outer rings (hexes) // create a radial base starting at point zero // with a shift between the first and second layer of connectivity // equal to the number of fuel points in a plane xtensor<int, 2> radial_base = hex_ring(1, radial_res_, fuel_points_per_plane_); // set the other rings by shifting the initial base // by radial_res_ for each ring for (size_t i = 1; i < n_radial_fuel_sections_; i++) { xt::view(base, i, xt::all(), xt::all()) = radial_base; radial_base += radial_res_; } // set all axial divs using the base connectivity // and shifting by the number of points in a plane for (size_t j = 0; j < n_axial_sections_; j++) { // set layer and increment connectivity by number of points in axial div xt::view(cells_out, j, xt::all(), xt::all(), xt::range(1, _)) = base; base += fuel_points_per_plane_; } // innermost ring is always wedges xt::view(cells_out, xt::all(), 0, xt::all(), 0) = WEDGE_SIZE_; // the reset are hexes xt::view(cells_out, xt::all(), xt::range(1, _), xt::all(), 0) = HEX_SIZE_; // first ring should be wedges only, invalidate last two entries xt::view(cells_out, xt::all(), 0, xt::all(), xt::range(7, _)) = INVALID_CONN_; return cells_out; } xtensor<int, 4> SurrogateVtkWriter::clad_conn() { // size output array xtensor<int, 4> cells_out = xt::zeros<int>( {n_axial_sections_, n_radial_clad_sections_, radial_res_, HEX_SIZE_ + 1}); // base layer to be extended in Z xtensor<int, 3> base = xt::zeros<int>({n_radial_clad_sections_, radial_res_, HEX_SIZE_}); // element rings (hexes) // create a radial base starting at point zero // with a shift between the first and second layer of connectivity // equal to the number of cladding points in a plane xtensor<int, 2> radial_base = hex_ring(0, radial_res_, clad_points_per_plane_); // set the other rings by shifting the initial base // by radial_res_ for each ring for (size_t i = 0; i < n_radial_clad_sections_; i++) { xt::view(base, i, xt::all(), xt::all()) = radial_base; radial_base += radial_res_; } // set all axial divs using base for the first layer and // shift by the number of points in a plane for (size_t i = 0; i < n_axial_sections_; i++) { // set layer and increment connectivity by number of points in axial div xt::view(cells_out, i, xt::all(), xt::all(), xt::range(1, _)) = base; base += clad_points_per_plane_; } // all are hexes xt::view(cells_out, xt::all(), xt::all(), xt::all(), 0) = HEX_SIZE_; return cells_out; } xtensor<int, 1> SurrogateVtkWriter::types() { xtensor<int, 1> types_out; if (VizRegionType::fuel == regions_out_) { // get fuel types xtensor<int, 3> ftypes = fuel_types(); types_out = xt::flatten(ftypes); } else if (VizRegionType::clad == regions_out_) { // get the cladding types xtensor<int, 3> ctypes = clad_types(); types_out = xt::flatten(ctypes); } else if (VizRegionType::all == regions_out_) { // get fuel types xtensor<int, 3> ftypes = fuel_types(); // get the cladding types xtensor<int, 3> ctypes = clad_types(); // concatenate and return 1-D form types_out = xt::concatenate(xt::xtuple(xt::flatten(ftypes), xt::flatten(ctypes))); } return types_out; } xtensor<int, 3> SurrogateVtkWriter::fuel_types() { // size the output array xtensor<int, 3> types_out = xt::zeros<int>({n_axial_sections_, n_radial_fuel_sections_, radial_res_}); // the inner ring is wedges xt::view(types_out, xt::all(), 0, xt::all()) = WEDGE_TYPE_; // the rest are hexes xt::view(types_out, xt::all(), xt::range(1, _), xt::all()) = HEX_TYPE_; return types_out; } xtensor<int, 3> SurrogateVtkWriter::clad_types() { // size output array xtensor<int, 3> clad_types_out = xt::zeros<int>({n_axial_sections_, n_radial_clad_sections_, radial_res_}); // all elements are hexes clad_types_out = xt::full_like(clad_types_out, HEX_TYPE_); return clad_types_out; } } // namespace enrico
34.345964
90
0.65565
sphamil
cdbab8b3fdb14dba995821a6aec79ee0874c3b7e
24,293
cxx
C++
Filters/General/vtkMergeCells.cxx
isi-research/VTK
56a615b4e54233b65072d3eddd89dd6c0df78dd6
[ "BSD-3-Clause" ]
null
null
null
Filters/General/vtkMergeCells.cxx
isi-research/VTK
56a615b4e54233b65072d3eddd89dd6c0df78dd6
[ "BSD-3-Clause" ]
null
null
null
Filters/General/vtkMergeCells.cxx
isi-research/VTK
56a615b4e54233b65072d3eddd89dd6c0df78dd6
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkMergeCells.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkMergeCells.h" #include "vtkUnstructuredGrid.h" #include "vtkCell.h" #include "vtkPoints.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkObjectFactory.h" #include "vtkCellArray.h" #include "vtkUnsignedCharArray.h" #include "vtkObjectFactory.h" #include "vtkIntArray.h" #include "vtkCharArray.h" #include "vtkLongArray.h" #include "vtkShortArray.h" #include "vtkIdTypeArray.h" #include "vtkDataArray.h" #include "vtkMergePoints.h" #include "vtkKdTree.h" #include <cstdlib> #include <map> #include <algorithm> vtkStandardNewMacro(vtkMergeCells); vtkCxxSetObjectMacro(vtkMergeCells, UnstructuredGrid, vtkUnstructuredGrid); class vtkMergeCellsSTLCloak { public: std::map<vtkIdType, vtkIdType> IdTypeMap; }; vtkMergeCells::vtkMergeCells() { this->TotalNumberOfDataSets = 0; this->TotalNumberOfCells = 0; this->TotalNumberOfPoints = 0; this->NumberOfCells = 0; this->NumberOfPoints = 0; this->PointMergeTolerance = 10e-4; this->MergeDuplicatePoints = 1; this->InputIsUGrid = 0; this->InputIsPointSet = 0; this->ptList = NULL; this->cellList = NULL; this->UnstructuredGrid = NULL; this->GlobalIdMap = new vtkMergeCellsSTLCloak; this->GlobalCellIdMap = new vtkMergeCellsSTLCloak; this->UseGlobalIds = 0; this->UseGlobalCellIds = 0; this->nextGrid = 0; } vtkMergeCells::~vtkMergeCells() { this->FreeLists(); delete this->GlobalIdMap; delete this->GlobalCellIdMap; this->SetUnstructuredGrid(0); } void vtkMergeCells::FreeLists() { delete this->ptList; this->ptList = NULL; delete this->cellList; this->cellList = NULL; } int vtkMergeCells::MergeDataSet(vtkDataSet *set) { vtkIdType newPtId, oldPtId, newCellId; vtkIdType *idMap; vtkUnstructuredGrid *ugrid = this->UnstructuredGrid; if (!ugrid) { vtkErrorMacro(<< "SetUnstructuredGrid first"); return -1; } if (this->TotalNumberOfDataSets <= 0) { // TotalNumberOfCells and TotalNumberOfPoints may both be zero // if all data sets to be merged are empty vtkErrorMacro(<< "Must SetTotalNumberOfCells, SetTotalNumberOfPoints and SetTotalNumberOfDataSets (upper bounds at least)" " before starting to MergeDataSets"); return -1; } vtkPointData *pointArrays = set->GetPointData(); vtkCellData *cellArrays = set->GetCellData(); // Since vtkMergeCells is to be used only on distributed vtkDataSets, // each DataSet should have the same field arrays. However I've been // told that the field arrays may get rearranged in the process of // Marshalling/UnMarshalling. So we use a // vtkDataSetAttributes::FieldList to ensure the field arrays are // merged in the right order. if (ugrid->GetNumberOfCells() == 0) { vtkPointSet *check1 = vtkPointSet::SafeDownCast(set); if (check1) { this->InputIsPointSet = 1; vtkUnstructuredGrid *check2 = vtkUnstructuredGrid::SafeDownCast(set); this->InputIsUGrid = (check2 != NULL); } this->StartUGrid(set); } else { this->ptList->IntersectFieldList(pointArrays); this->cellList->IntersectFieldList(cellArrays); } vtkIdType numPoints = set->GetNumberOfPoints(); vtkIdType numCells = set->GetNumberOfCells(); if (numCells == 0) { return 0; } if (this->MergeDuplicatePoints) { if (this->UseGlobalIds) // faster by far { // Note: It has been observed that an input dataset may // have an invalid global ID array. Using the array to // merge points results in bad geometry. It may be // worthwhile to do a quick sanity check when merging // points. Downside is that will slow down this filter. idMap = this->MapPointsToIdsUsingGlobalIds(set); } else { idMap = this->MapPointsToIdsUsingLocator(set); } } else { idMap = NULL; } vtkIdType nextPt = (vtkIdType)this->NumberOfPoints; vtkPoints *pts = ugrid->GetPoints(); for (oldPtId=0; oldPtId < numPoints; oldPtId++) { if (idMap) { newPtId = idMap[oldPtId]; } else { newPtId = nextPt; } if (newPtId == nextPt) { pts->SetPoint(nextPt, set->GetPoint(oldPtId)); ugrid->GetPointData()->CopyData(*this->ptList, pointArrays, this->nextGrid, oldPtId, nextPt); nextPt++; } } pts->Modified(); // so that subsequent GetBounds will be correct if (this->InputIsUGrid) { newCellId = this->AddNewCellsUnstructuredGrid(set, idMap); } else { newCellId = this->AddNewCellsDataSet(set, idMap); } delete [] idMap; idMap = 0; this->NumberOfPoints = nextPt; this->NumberOfCells = newCellId; this->nextGrid++; return 0; } vtkIdType vtkMergeCells::AddNewCellsDataSet(vtkDataSet *set, vtkIdType *idMap) { vtkIdType oldCellId, id, newPtId, newCellId = 0, oldPtId; vtkUnstructuredGrid *ugrid = this->UnstructuredGrid; vtkCellData *cellArrays = set->GetCellData(); vtkIdType numCells = set->GetNumberOfCells(); vtkIdList *cellPoints = vtkIdList::New(); cellPoints->Allocate(VTK_CELL_SIZE); vtkIdType nextCellId = 0; int duplicateCellTest = 0; if (this->UseGlobalCellIds) { int success = this->GlobalCellIdAccessStart(set); if (success) { nextCellId = static_cast<vtkIdType>(this->GlobalCellIdMap->IdTypeMap.size()); duplicateCellTest = 1; } } for (oldCellId=0; oldCellId < numCells; oldCellId++) { if (duplicateCellTest) { vtkIdType globalId = this->GlobalCellIdAccessGetId(oldCellId); std::pair<std::map<vtkIdType, vtkIdType>::iterator, bool> inserted = this->GlobalCellIdMap->IdTypeMap.insert( std::map<vtkIdType, vtkIdType>::value_type(globalId, nextCellId)); if (inserted.second) { nextCellId++; } else { continue; // skip it, we already have this cell } } set->GetCellPoints(oldCellId, cellPoints); for (id=0; id < cellPoints->GetNumberOfIds(); id++) { oldPtId = cellPoints->GetId(id); if (idMap) { newPtId = idMap[oldPtId]; } else { newPtId = this->NumberOfPoints + oldPtId; } cellPoints->SetId(id, newPtId); } newCellId = (vtkIdType)ugrid->InsertNextCell(set->GetCellType(oldCellId), cellPoints); ugrid->GetCellData()->CopyData(*(this->cellList), cellArrays, this->nextGrid, oldCellId, newCellId); } cellPoints->Delete(); return newCellId; } vtkIdType vtkMergeCells::AddNewCellsUnstructuredGrid(vtkDataSet *set, vtkIdType *idMap) { vtkIdType id; char firstSet = 0; if (this->nextGrid == 0) firstSet = 1; vtkUnstructuredGrid *newUgrid = vtkUnstructuredGrid::SafeDownCast(set); vtkUnstructuredGrid *Ugrid = this->UnstructuredGrid; // connectivity information for the new data set vtkCellArray *newCellArray = newUgrid->GetCells(); vtkIdType *newCells = newCellArray->GetPointer(); vtkIdType *newLocs = newUgrid->GetCellLocationsArray()->GetPointer(0); unsigned char *newTypes = newUgrid->GetCellTypesArray()->GetPointer(0); int newNumCells = newUgrid->GetNumberOfCells(); int newNumConnections = newCellArray->GetData()->GetNumberOfTuples(); // If we are checking for duplicate cells, create a list now of // any cells in the new data set that we already have. vtkIdList *duplicateCellIds = NULL; int numDuplicateCells = 0; int numDuplicateConnections = 0; if (this->UseGlobalCellIds) { int success = this->GlobalCellIdAccessStart(set); if (success) { vtkIdType nextLocalId = static_cast<vtkIdType>(this->GlobalCellIdMap->IdTypeMap.size()); duplicateCellIds = vtkIdList::New(); for (id = 0; id < newNumCells; id++) { vtkIdType globalId = this->GlobalCellIdAccessGetId(id); std::pair<std::map<vtkIdType, vtkIdType>::iterator, bool> inserted = this->GlobalCellIdMap->IdTypeMap.insert( std::map<vtkIdType, vtkIdType>::value_type(globalId, nextLocalId)); if (inserted.second) { nextLocalId++; } else { duplicateCellIds->InsertNextId(id); numDuplicateCells++; int npoints = newCells[newLocs[id]]; numDuplicateConnections += (npoints + 1); } } if (numDuplicateCells == 0) { duplicateCellIds->Delete(); duplicateCellIds = NULL; } } } // connectivity for the merged ugrid so far vtkCellArray *cellArray = NULL; vtkIdType *cells = NULL; vtkIdType *locs = NULL; unsigned char *types = NULL; int numCells = 0; int numConnections = 0; if (!firstSet) { cellArray = Ugrid->GetCells(); cells = cellArray->GetPointer(); locs = Ugrid->GetCellLocationsArray()->GetPointer(0); types = Ugrid->GetCellTypesArray()->GetPointer(0);; numCells = Ugrid->GetNumberOfCells(); numConnections = cellArray->GetData()->GetNumberOfTuples(); } // New output grid: merging of existing and incoming grids // CELL ARRAY int totalNumCells = numCells + newNumCells - numDuplicateCells; int totalNumConnections = numConnections + newNumConnections - numDuplicateConnections; vtkIdTypeArray *mergedcells = vtkIdTypeArray::New(); mergedcells->SetNumberOfValues(totalNumConnections); if (!firstSet) { vtkIdType *idptr = mergedcells->GetPointer(0); memcpy(idptr, cells, sizeof(vtkIdType) * numConnections); } vtkCellArray *finalCellArray = vtkCellArray::New(); finalCellArray->SetCells(totalNumCells, mergedcells); // LOCATION ARRAY vtkIdTypeArray *locationArray = vtkIdTypeArray::New(); locationArray->SetNumberOfValues(totalNumCells); vtkIdType *iptr = locationArray->GetPointer(0); // new output dataset if (!firstSet) { memcpy(iptr, locs, numCells * sizeof(vtkIdType)); // existing set } // TYPE ARRAY vtkUnsignedCharArray *typeArray = vtkUnsignedCharArray::New(); typeArray->SetNumberOfValues(totalNumCells); unsigned char *cptr = typeArray->GetPointer(0); if (!firstSet) { memcpy(cptr, types, numCells * sizeof(unsigned char)); } // set up new cell data vtkIdType finalCellId = numCells; vtkIdType nextCellArrayIndex = static_cast<vtkIdType>(numConnections); vtkCellData *cellArrays = set->GetCellData(); vtkIdType oldPtId, finalPtId; int nextDuplicateCellId = 0; for (vtkIdType oldCellId=0; oldCellId < newNumCells; oldCellId++) { vtkIdType size = *newCells++; if (duplicateCellIds) { vtkIdType skipId = duplicateCellIds->GetId(nextDuplicateCellId); if (skipId == oldCellId) { newCells += size; nextDuplicateCellId++; continue; } } locationArray->SetValue(finalCellId, nextCellArrayIndex); typeArray->SetValue(finalCellId, newTypes[oldCellId]); mergedcells->SetValue(nextCellArrayIndex++, size); for (id=0; id < size; id++) { oldPtId = *newCells++; if (idMap) { finalPtId = idMap[oldPtId]; } else { finalPtId = this->NumberOfPoints + oldPtId; } mergedcells->SetValue(nextCellArrayIndex++, finalPtId); } Ugrid->GetCellData()->CopyData(*(this->cellList), cellArrays, this->nextGrid, oldCellId, finalCellId); finalCellId++; } Ugrid->SetCells(typeArray, locationArray, finalCellArray); mergedcells->Delete(); typeArray->Delete(); locationArray->Delete(); finalCellArray->Delete(); if (duplicateCellIds) { duplicateCellIds->Delete(); } return finalCellId; } void vtkMergeCells::StartUGrid(vtkDataSet *set) { vtkPointData *PD = set->GetPointData(); vtkCellData *CD = set->GetCellData(); vtkUnstructuredGrid *ugrid = this->UnstructuredGrid; if (!this->InputIsUGrid) { ugrid->Allocate(this->TotalNumberOfCells); } vtkPoints *pts = vtkPoints::New(); // If the input has a vtkPoints object, we'll make the merged output // grid have a vtkPoints object of the same data type. Otherwise, // the merged output grid will have the default of points of type float. if (this->InputIsPointSet) { vtkPointSet *ps = vtkPointSet::SafeDownCast(set); pts->SetDataType(ps->GetPoints()->GetDataType()); } pts->SetNumberOfPoints(this->TotalNumberOfPoints); // allocate for upper bound ugrid->SetPoints(pts); pts->Delete(); // Order of field arrays may get changed when data sets are // marshalled/sent/unmarshalled. So we need to re-index the // field arrays before copying them using a FieldList this->ptList = new vtkDataSetAttributes::FieldList(this->TotalNumberOfDataSets); this->cellList = new vtkDataSetAttributes::FieldList(this->TotalNumberOfDataSets); this->ptList->InitializeFieldList(PD); this->cellList->InitializeFieldList(CD); if (this->UseGlobalIds) { ugrid->GetPointData()->CopyGlobalIdsOn(); } ugrid->GetPointData()->CopyAllocate(*ptList, this->TotalNumberOfPoints); if (this->UseGlobalCellIds) { ugrid->GetCellData()->CopyGlobalIdsOn(); } ugrid->GetCellData()->CopyAllocate(*cellList, this->TotalNumberOfCells); } void vtkMergeCells::Finish() { this->FreeLists(); vtkUnstructuredGrid *ugrid = this->UnstructuredGrid; if (this->NumberOfPoints < this->TotalNumberOfPoints) { // if we don't do this, ugrid->GetNumberOfPoints() gives // the wrong value ugrid->GetPoints()->GetData()->Resize(this->NumberOfPoints); } ugrid->Squeeze(); } // Use an array of global node ids to map all points to // their new Ids in the merged grid. vtkIdType *vtkMergeCells::MapPointsToIdsUsingGlobalIds(vtkDataSet *set) { int success = this->GlobalNodeIdAccessStart(set); if (!success) { vtkErrorMacro("global id array is not available"); return NULL; } vtkIdType npoints = set->GetNumberOfPoints(); vtkIdType *idMap = new vtkIdType [npoints]; vtkIdType nextNewLocalId = static_cast<vtkIdType>(this->GlobalIdMap->IdTypeMap.size()); // map global point Ids to Ids in the new data set for (vtkIdType oldId=0; oldId<npoints; oldId++) { vtkIdType globalId = this->GlobalNodeIdAccessGetId(oldId); std::pair<std::map<vtkIdType, vtkIdType>::iterator, bool> inserted = this->GlobalIdMap->IdTypeMap.insert( std::map<vtkIdType, vtkIdType>::value_type(globalId, nextNewLocalId)); if (inserted.second) { // this is a new global node Id idMap[oldId] = nextNewLocalId; nextNewLocalId++; } else { // a repeat, it was not inserted idMap[oldId] = inserted.first->second; } } return idMap; } // Use a spatial locator to filter out duplicate points and map // the new Ids to their Ids in the merged grid. vtkIdType *vtkMergeCells::MapPointsToIdsUsingLocator(vtkDataSet *set) { vtkIdType ptId; vtkUnstructuredGrid *grid = this->UnstructuredGrid; vtkPoints *points0 = grid->GetPoints(); vtkIdType npoints0 = (vtkIdType)this->NumberOfPoints; vtkPointSet *ps = vtkPointSet::SafeDownCast(set); vtkPoints *points1; vtkIdType npoints1 = set->GetNumberOfPoints(); if (ps) { points1 = ps->GetPoints(); } else { points1 = vtkPoints::New(); points1->SetNumberOfPoints(npoints1); for (ptId=0; ptId<npoints1; ptId++) { points1->SetPoint(ptId, set->GetPoint(ptId)); } } vtkIdType *idMap = new vtkIdType [npoints1]; vtkIdType nextNewLocalId = npoints0; if (this->PointMergeTolerance == 0.0) { // testing shows vtkMergePoints is fastest when tolerance is 0 vtkMergePoints *locator = vtkMergePoints::New(); vtkPoints *ptarray = vtkPoints::New(); double bounds[6]; set->GetBounds(bounds); if (npoints0 > 0) { double tmpbounds[6]; // Prior to MapPointsToIdsUsingLocator(), points0->SetNumberOfPoints() // has been called to set the number of points to the upper bound on the // points TO BE merged and now points0->GetNumberOfPoints() does not // refer to the number of the points merged so far. Thus we need to // temporarily set the number to the latter such that grid->GetBounds() // is able to return the correct bounding information. This is a fix to // bug #0009626. points0->GetData()->SetNumberOfTuples( npoints0 ); grid->GetBounds( tmpbounds ); // safe to call GetBounds() for real info points0->GetData()->SetNumberOfTuples( this->TotalNumberOfPoints ); bounds[0] = ((tmpbounds[0] < bounds[0]) ? tmpbounds[0] : bounds[0]); bounds[2] = ((tmpbounds[2] < bounds[2]) ? tmpbounds[2] : bounds[2]); bounds[4] = ((tmpbounds[4] < bounds[4]) ? tmpbounds[4] : bounds[4]); bounds[1] = ((tmpbounds[1] > bounds[1]) ? tmpbounds[1] : bounds[1]); bounds[3] = ((tmpbounds[3] > bounds[3]) ? tmpbounds[3] : bounds[3]); bounds[5] = ((tmpbounds[5] > bounds[5]) ? tmpbounds[5] : bounds[5]); } locator->InitPointInsertion(ptarray, bounds); vtkIdType newId; double x[3]; for (ptId = 0; ptId < npoints0; ptId++) { // We already know there are no duplicates in this array. // Just add them to the locator's point array. points0->GetPoint(ptId, x); locator->InsertUniquePoint(x, newId); } for (ptId = 0; ptId < npoints1; ptId++) { points1->GetPoint(ptId, x); locator->InsertUniquePoint(x, newId); idMap[ptId] = newId; } locator->Delete(); ptarray->Delete(); } else { // testing shows vtkKdTree is fastest when tolerance is > 0 vtkKdTree *kd = vtkKdTree::New(); vtkPoints *ptArrays[2]; int numArrays; if (npoints0 > 0) { // points0->GetNumberOfPoints() is equal to the upper bound // on the points in the final merged grid. We need to temporarily // set it to the number of points added to the merged grid so far. points0->GetData()->SetNumberOfTuples(npoints0); ptArrays[0] = points0; ptArrays[1] = points1; numArrays = 2; } else { ptArrays[0] = points1; numArrays = 1; } kd->BuildLocatorFromPoints(ptArrays, numArrays); vtkIdTypeArray *pointToEquivClassMap = kd->BuildMapForDuplicatePoints(this->PointMergeTolerance); kd->Delete(); if (npoints0 > 0) { points0->GetData()->SetNumberOfTuples(this->TotalNumberOfPoints); } // The map we get back isn't quite what we need. The range of // the map is a subset of original point IDs which each // represent an equivalence class of duplicate points. But the // point chosen to represent the class could be any one of the // equivalent points. We need to create a map that uses IDs // of points in the points0 array as the representative, and // then new logical contiguous point IDs // (npoints0, npoints0+1, ..., numUniquePoints-1) for the // points in the new set that are not duplicates of points // in the points0 array. std::map<vtkIdType, vtkIdType> newIdMap; if (npoints0 > 0) // these were already a unique set { for (ptId = 0; ptId < npoints0 ; ptId++) { vtkIdType EqClassRep = pointToEquivClassMap->GetValue(ptId); if (EqClassRep != ptId) { newIdMap.insert(std::map<vtkIdType, vtkIdType>::value_type(EqClassRep, ptId)); } } } for (ptId = 0; ptId < npoints1; ptId++) { vtkIdType EqClassRep = pointToEquivClassMap->GetValue(ptId + npoints0); if (EqClassRep < npoints0){ idMap[ptId] = EqClassRep; // a duplicate of a point in the first set continue; } std::pair<std::map<vtkIdType, vtkIdType>::iterator, bool> inserted = newIdMap.insert( std::map<vtkIdType, vtkIdType>::value_type(EqClassRep, nextNewLocalId)); bool newEqClassRep = inserted.second; vtkIdType existingMappedId = inserted.first->second; if (newEqClassRep) { idMap[ptId] = nextNewLocalId; // here's a new unique point nextNewLocalId++; } else { idMap[ptId] = existingMappedId; // a duplicate of a point in the new set } } pointToEquivClassMap->Delete(); newIdMap.clear(); } if (!ps) { points1->Delete(); } return idMap; } //------------------------------------------------------------------------- // Help with the complex business of efficient access to the node ID arrays. // The array was given to us by the user, and we don't know the data type or // size. //------------------------------------------------------------------------- vtkIdType vtkMergeCells::GlobalCellIdAccessGetId(vtkIdType idx) { if(this->GlobalCellIdArray) { switch (this->GlobalCellIdArrayType) { vtkTemplateMacro( VTK_TT* ids = static_cast<VTK_TT*>(this->GlobalCellIdArray); return static_cast<vtkIdType>(ids[idx]) ); } } return 0; } int vtkMergeCells::GlobalCellIdAccessStart(vtkDataSet *set) { if(this->UseGlobalCellIds) { vtkDataArray* da = set->GetCellData()->GetGlobalIds(); if (da) { this->GlobalCellIdArray = da->GetVoidPointer(0); this->GlobalCellIdArrayType = da->GetDataType(); return 1; } } this->GlobalCellIdArray = 0; return 0; } vtkIdType vtkMergeCells::GlobalNodeIdAccessGetId(vtkIdType idx) { if(this->GlobalIdArray) { switch (this->GlobalIdArrayType) { vtkTemplateMacro( VTK_TT* ids = static_cast<VTK_TT*>(this->GlobalIdArray); return static_cast<vtkIdType>(ids[idx]) ); } } return 0; } int vtkMergeCells::GlobalNodeIdAccessStart(vtkDataSet *set) { if(this->UseGlobalIds) { vtkDataArray* da = set->GetPointData()->GetGlobalIds(); if (da) { this->GlobalIdArray = da->GetVoidPointer(0); this->GlobalIdArrayType = da->GetDataType(); return 1; } } this->GlobalIdArray = 0; return 0; } void vtkMergeCells::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "TotalNumberOfDataSets: " << this->TotalNumberOfDataSets << endl; os << indent << "TotalNumberOfCells: " << this->TotalNumberOfCells << endl; os << indent << "TotalNumberOfPoints: " << this->TotalNumberOfPoints << endl; os << indent << "NumberOfCells: " << this->NumberOfCells << endl; os << indent << "NumberOfPoints: " << this->NumberOfPoints << endl; os << indent << "GlobalIdMap: " << this->GlobalIdMap->IdTypeMap.size() << endl; os << indent << "GlobalCellIdMap: " << this->GlobalCellIdMap->IdTypeMap.size() << endl; os << indent << "PointMergeTolerance: " << this->PointMergeTolerance << endl; os << indent << "MergeDuplicatePoints: " << this->MergeDuplicatePoints << endl; os << indent << "InputIsUGrid: " << this->InputIsUGrid << endl; os << indent << "InputIsPointSet: " << this->InputIsPointSet << endl; os << indent << "UnstructuredGrid: " << this->UnstructuredGrid << endl; os << indent << "ptList: " << this->ptList << endl; os << indent << "cellList: " << this->cellList << endl; os << indent << "UseGlobalIds: " << this->UseGlobalIds << endl; os << indent << "UseGlobalCellIds: " << this->UseGlobalCellIds << endl; }
26.177802
110
0.646771
isi-research
cdbc03b806cfb680bab72f0cb749596ac1dd012f
15,608
hpp
C++
boost/gil/extension/io/detail/read_and_convert_image.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2017-11-27T11:50:20.000Z
2021-04-04T13:26:45.000Z
boost/gil/extension/io/detail/read_and_convert_image.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2019-01-13T23:45:51.000Z
2019-02-03T08:13:26.000Z
boost/gil/extension/io/detail/read_and_convert_image.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2018-04-04T10:55:01.000Z
2020-04-23T18:52:06.000Z
/* Copyright 2007-2012 Christian Henning, Andreas Pokorny, Lubomir Bourdev Use, modification and distribution are subject to 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). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_IMAGE_HPP #define BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_IMAGE_HPP //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning, Andreas Pokorny, Lubomir Bourdev \n /// /// \date 2007-2012 \n /// //////////////////////////////////////////////////////////////////////////////////////// #include <boost/type_traits/is_base_and_derived.hpp> #include <boost/mpl/and.hpp> #include <boost/utility/enable_if.hpp> #include "base.hpp" #include "io_device.hpp" #include "path_spec.hpp" #include "conversion_policies.hpp" namespace boost{ namespace gil { /// \ingroup IO /// \brief Reads and color-converts an image. Image memory is allocated. /// \param reader An image reader. /// \param img The image in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \param cc Color converter function object. /// \throw std::ios_base::failure template< typename Reader , typename Image > inline void read_and_convert_image( Reader& reader , Image& img , typename enable_if< mpl::and_< detail::is_reader< Reader > , is_format_tag< typename Reader::format_tag_t > > >::type* /* ptr */ = 0 ) { reader.init_image( img , reader._settings ); reader.apply( view( img )); } /// \brief Reads and color-converts an image. Image memory is allocated. /// \param device Must satisfy is_input_device metafunction. /// \param img The image in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \param cc Color converter function object. /// \throw std::ios_base::failure template< typename Device , typename Image , typename ColorConverter , typename FormatTag > inline void read_and_convert_image( Device& device , Image& img , const image_read_settings< FormatTag >& settings , const ColorConverter& cc , typename enable_if< mpl::and_< detail::is_read_device< FormatTag , Device > , is_format_tag< FormatTag > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< Device , FormatTag , detail::read_and_convert< ColorConverter > >::type reader_t; reader_t reader = make_reader( device , settings , detail::read_and_convert< ColorConverter >( cc ) ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param img The image in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \param cc Color converter function object. /// \throw std::ios_base::failure template < typename String , typename Image , typename ColorConverter , typename FormatTag > inline void read_and_convert_image( const String& file_name , Image& img , const image_read_settings< FormatTag >& settings , const ColorConverter& cc , typename enable_if< mpl::and_< is_format_tag< FormatTag > , detail::is_supported_path_spec< String > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< String , FormatTag , detail::read_and_convert< ColorConverter > >::type reader_t; reader_t reader = make_reader( file_name , settings , detail::read_and_convert< ColorConverter >( cc ) ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param img The image in which the data is read into. /// \param cc Color converter function object. /// \param tag Defines the image format. Must satisfy is_format_tag metafunction. /// \throw std::ios_base::failure template < typename String , typename Image , typename ColorConverter , typename FormatTag > inline void read_and_convert_image( const String& file_name , Image& img , const ColorConverter& cc , const FormatTag& tag , typename enable_if< mpl::and_< is_format_tag< FormatTag > , detail::is_supported_path_spec< String > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< String , FormatTag , detail::read_and_convert< ColorConverter > >::type reader_t; reader_t reader = make_reader( file_name , tag , detail::read_and_convert< ColorConverter >( cc ) ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. /// \param device Must satisfy is_input_device metafunction or is_adaptable_input_device. /// \param img The image in which the data is read into. /// \param cc Color converter function object. /// \param tag Defines the image format. Must satisfy is_format_tag metafunction. /// \throw std::ios_base::failure template < typename Device , typename Image , typename ColorConverter , typename FormatTag > inline void read_and_convert_image( Device& device , Image& img , const ColorConverter& cc , const FormatTag& tag , typename enable_if< mpl::and_< detail::is_read_device< FormatTag , Device > , is_format_tag< FormatTag > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< Device , FormatTag , detail::read_and_convert< ColorConverter > >::type reader_t; reader_t reader = make_reader( device , tag , detail::read_and_convert< ColorConverter >( cc ) ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param img The image in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \throw std::ios_base::failure template < typename String , typename Image , typename FormatTag > inline void read_and_convert_image( const String& file_name , Image& img , const image_read_settings< FormatTag >& settings , typename enable_if< mpl::and_< is_format_tag< FormatTag > , detail::is_supported_path_spec< String > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< String , FormatTag , detail::read_and_convert< default_color_converter > >::type reader_t; reader_t reader = make_reader( file_name , settings , detail::read_and_convert< default_color_converter >() ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used. /// \param device It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device. /// \param img The image in which the data is read into. /// \param settings Specifies read settings depending on the image format. /// \throw std::ios_base::failure template < typename Device , typename Image , typename FormatTag > inline void read_and_convert_image( Device& device , Image& img , const image_read_settings< FormatTag >& settings , typename enable_if< mpl::and_< detail::is_read_device< FormatTag , Device > , is_format_tag< FormatTag > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< Device , FormatTag , detail::read_and_convert< default_color_converter > >::type reader_t; reader_t reader = make_reader( device , settings , detail::read_and_convert< default_color_converter >() ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param img The image in which the data is read into. /// \param tag Defines the image format. Must satisfy is_format_tag metafunction. /// \throw std::ios_base::failure template < typename String , typename Image , typename FormatTag > inline void read_and_convert_image( const String& file_name , Image& img , const FormatTag& tag , typename enable_if< mpl::and_< is_format_tag< FormatTag > , detail::is_supported_path_spec< String > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< String , FormatTag , detail::read_and_convert< default_color_converter > >::type reader_t; reader_t reader = make_reader( file_name , tag , detail::read_and_convert< default_color_converter >() ); read_and_convert_image( reader , img ); } /// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used. /// \param file_name File name. Must satisfy is_supported_path_spec metafunction. /// \param img The image in which the data is read into. /// \param tag Defines the image format. Must satisfy is_format_tag metafunction. /// \throw std::ios_base::failure template < typename Device , typename Image , typename FormatTag > inline void read_and_convert_image( Device& device , Image& img , const FormatTag& tag , typename enable_if< mpl::and_< detail::is_read_device< FormatTag , Device > , is_format_tag< FormatTag > > >::type* /* ptr */ = 0 ) { typedef typename get_reader< Device , FormatTag , detail::read_and_convert< default_color_converter > >::type reader_t; reader_t reader = make_reader( device , tag , detail::read_and_convert< default_color_converter >() ); read_and_convert_image( reader , img ); } } // namespace gil } // namespace boost #endif // BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_IMAGE_HPP
43.842697
107
0.447335
ballisticwhisper
cdc1503427eed6246f4f81c6a6505dd350768155
3,186
cpp
C++
src/gui/message_box.cpp
Piepenguin1995/retro-rpg
09b72d7a8a4d2a9e94b09957bcb88bcf08a67eeb
[ "MIT" ]
5
2016-02-09T20:05:57.000Z
2016-11-02T01:48:54.000Z
src/gui/message_box.cpp
dbMansfield/retro-rpg
09b72d7a8a4d2a9e94b09957bcb88bcf08a67eeb
[ "MIT" ]
null
null
null
src/gui/message_box.cpp
dbMansfield/retro-rpg
09b72d7a8a4d2a9e94b09957bcb88bcf08a67eeb
[ "MIT" ]
3
2016-02-09T20:06:04.000Z
2016-06-23T13:12:22.000Z
#include <SFML/Graphics.hpp> #include <vector> #include <string> #include "gui.hpp" #include "message_box.hpp" #include "text.hpp" gui::MessageBox::MessageBox(const sf::Vector2u& dimensions, const std::string& text, const gui::Font& font, const sf::Color& backgroundCol, const sf::Color& textCol) : mDimensions(dimensions), mFont(&font), mCurrentPage(0), mBackgroundCol(backgroundCol), mTextCol(textCol) { createPages(gui::alignString(text, dimensions.x)); } void gui::MessageBox::createPages(const std::vector<std::string>& lines) { unsigned int borderWidth = mDimensions.x + 2; unsigned int& maxWidth = mDimensions.x; unsigned int& maxHeight = mDimensions.y; std::string page = gui::Border::genTop(borderWidth); // If the lines vector is empty, we'll just make a blank box if(lines.size() == 0) { for(size_t i = 0; i < maxHeight; ++i) { page += gui::Border::genRow(borderWidth); } page += gui::Border::genBottom(borderWidth); mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); return; } // Otherwise there are lines of text so we can add them for(size_t i = 0; i < lines.size(); ++i) { // There are maxHeight lines, so this is true on the last line if(i % maxHeight == maxHeight-1) { // Expand the line to the width of the box std::string padding; if(lines[i].size() < maxWidth) { padding = std::string(maxWidth - lines[i].size(), ' '); } // Surround the line with border to pieces and add it to the page page += gui::Border::surround(lines[i]+padding) + "\n"; // Add the bottom border of the page page += gui::Border::genBottom(borderWidth); // Add the page to the list of pages and reset mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); page = gui::Border::genTop(borderWidth); } else { std::string padding; if(lines[i].size() < maxWidth) { padding = std::string(maxWidth-lines[i].size(), ' '); } page += gui::Border::surround(lines[i] + padding) + "\n"; } } // We'll still have a partial page unless the number of // lines is divisible by the maximum height if(lines.size() % maxHeight != 0) { // Add padding lines to make the page the desired height for(size_t i = lines.size() % maxHeight; i < maxHeight; ++i) { page += gui::Border::genRow(borderWidth); } page += gui::Border::genBottom(borderWidth); mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); } } void gui::MessageBox::setPage(unsigned int page) { if(page >= mPages.size()) page = mPages.size() % page; mCurrentPage = page; } unsigned int gui::MessageBox::getPage() const { return mCurrentPage; } unsigned int gui::MessageBox::numPages() const { return mPages.size(); } void gui::MessageBox::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); mPages.at(mCurrentPage).draw(target, states); } sf::Vector2u gui::MessageBox::getSize() const { return mDimensions + sf::Vector2u(2, 2); } void gui::MessageBox::setText(const std::string& text) { mPages.clear(); createPages(gui::alignString(text, mDimensions.x)); mCurrentPage = 0; }
26.114754
72
0.670747
Piepenguin1995
cdc18018eafd3c9196318fe30cbe2b310e41432b
787
cpp
C++
LeetCode/ThousandTwo/1688-count_match_in_tournament.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1688-count_match_in_tournament.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandTwo/1688-count_match_in_tournament.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 1688. 比赛中的配对次数 给你一个整数 n ,表示比赛中的队伍数。比赛遵循一种独特的赛制: 如果当前队伍数是 偶数 ,那么每支队伍都会与另一支队伍配对。 总共进行 n / 2 场比赛,且产生 n / 2 支队伍进入下一轮。 如果当前队伍数为 奇数 ,那么将会随机轮空并晋级一支队伍,其余的队伍配对。 总共进行 (n - 1) / 2 场比赛,且产生 (n - 1) / 2 + 1 支队伍进入下一轮。 返回在比赛中进行的配对次数,直到决出获胜队伍为止。 示例 1: 输入:n = 7 输出:6 解释:比赛详情: - 第 1 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。 - 第 2 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。 - 第 3 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。 总配对次数 = 3 + 2 + 1 = 6 示例 2: 输入:n = 14 输出:13 解释:比赛详情: - 第 1 轮:队伍数 = 14 ,配对次数 = 7 ,7 支队伍晋级。 - 第 2 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。 - 第 3 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。 - 第 4 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。 总配对次数 = 7 + 3 + 2 + 1 = 13 提示: 1 <= n <= 200 */ int numberOfMatches(int n) { int x = 0; while (n > 1) { x = (n - 1) / 2; n = (n + 1) / 2; } return x; } int main() {}
15.74
51
0.550191
Ginkgo-Biloba
02cf44e1fde012dbc47e28a846e04c1a34c498f2
10,866
cpp
C++
src/storage/buffer_manager.cpp
c5sire/duckdb
2266d0e6e353aab104026c9674af7158b948bae0
[ "MIT" ]
1
2021-06-14T08:09:40.000Z
2021-06-14T08:09:40.000Z
src/storage/buffer_manager.cpp
c5sire/duckdb
2266d0e6e353aab104026c9674af7158b948bae0
[ "MIT" ]
null
null
null
src/storage/buffer_manager.cpp
c5sire/duckdb
2266d0e6e353aab104026c9674af7158b948bae0
[ "MIT" ]
null
null
null
#include "duckdb/storage/buffer_manager.hpp" #include "duckdb/common/to_string.hpp" #include "duckdb/storage/storage_manager.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/parallel/concurrentqueue.hpp" namespace duckdb { BlockHandle::BlockHandle(DatabaseInstance &db, block_id_t block_id_p) : db(db) { block_id = block_id_p; readers = 0; buffer = nullptr; eviction_timestamp = 0; state = BlockState::BLOCK_UNLOADED; can_destroy = false; memory_usage = Storage::BLOCK_ALLOC_SIZE; } BlockHandle::BlockHandle(DatabaseInstance &db, block_id_t block_id_p, unique_ptr<FileBuffer> buffer_p, bool can_destroy_p, idx_t alloc_size) : db(db) { D_ASSERT(alloc_size >= Storage::BLOCK_SIZE); block_id = block_id_p; readers = 0; buffer = move(buffer_p); eviction_timestamp = 0; state = BlockState::BLOCK_LOADED; can_destroy = can_destroy_p; memory_usage = alloc_size; } BlockHandle::~BlockHandle() { auto &buffer_manager = BufferManager::GetBufferManager(db); // no references remain to this block: erase if (state == BlockState::BLOCK_LOADED) { // the block is still loaded in memory: erase it buffer.reset(); buffer_manager.current_memory -= memory_usage; } buffer_manager.UnregisterBlock(block_id, can_destroy); } unique_ptr<BufferHandle> BlockHandle::Load(shared_ptr<BlockHandle> &handle) { if (handle->state == BlockState::BLOCK_LOADED) { // already loaded D_ASSERT(handle->buffer); return make_unique<BufferHandle>(handle, handle->buffer.get()); } handle->state = BlockState::BLOCK_LOADED; auto &buffer_manager = BufferManager::GetBufferManager(handle->db); auto &block_manager = BlockManager::GetBlockManager(handle->db); if (handle->block_id < MAXIMUM_BLOCK) { // FIXME: currently we still require a lock for reading blocks from disk // this is mainly down to the block manager only having a single pointer into the file // this is relatively easy to fix later on lock_guard<mutex> buffer_lock(buffer_manager.manager_lock); auto block = make_unique<Block>(handle->block_id); block_manager.Read(*block); handle->buffer = move(block); } else { if (handle->can_destroy) { return nullptr; } else { handle->buffer = buffer_manager.ReadTemporaryBuffer(handle->block_id); } } return make_unique<BufferHandle>(handle, handle->buffer.get()); } void BlockHandle::Unload() { if (state == BlockState::BLOCK_UNLOADED) { // already unloaded: nothing to do return; } D_ASSERT(CanUnload()); D_ASSERT(memory_usage >= Storage::BLOCK_SIZE); state = BlockState::BLOCK_UNLOADED; auto &buffer_manager = BufferManager::GetBufferManager(db); if (block_id >= MAXIMUM_BLOCK && !can_destroy) { // temporary block that cannot be destroyed: write to temporary file buffer_manager.WriteTemporaryBuffer((ManagedBuffer &)*buffer); } buffer.reset(); buffer_manager.current_memory -= memory_usage; } bool BlockHandle::CanUnload() { if (state == BlockState::BLOCK_UNLOADED) { // already unloaded return false; } if (readers > 0) { // there are active readers return false; } auto &buffer_manager = BufferManager::GetBufferManager(db); if (block_id >= MAXIMUM_BLOCK && !can_destroy && buffer_manager.temp_directory.empty()) { // in order to unload this block we need to write it to a temporary buffer // however, no temporary directory is specified! // hence we cannot unload the block return false; } return true; } struct BufferEvictionNode { BufferEvictionNode(weak_ptr<BlockHandle> handle_p, idx_t timestamp_p) : handle(move(handle_p)), timestamp(timestamp_p) { D_ASSERT(!handle.expired()); } weak_ptr<BlockHandle> handle; idx_t timestamp; bool CanUnload(BlockHandle &handle) { if (timestamp != handle.eviction_timestamp) { // handle was used in between return false; } return handle.CanUnload(); } }; typedef moodycamel::ConcurrentQueue<unique_ptr<BufferEvictionNode>> eviction_queue_t; struct EvictionQueue { eviction_queue_t q; }; BufferManager::BufferManager(DatabaseInstance &db, string tmp, idx_t maximum_memory) : db(db), current_memory(0), maximum_memory(maximum_memory), temp_directory(move(tmp)), queue(make_unique<EvictionQueue>()), temporary_id(MAXIMUM_BLOCK) { auto &fs = FileSystem::GetFileSystem(db); if (!temp_directory.empty()) { fs.CreateDirectory(temp_directory); } } BufferManager::~BufferManager() { auto &fs = FileSystem::GetFileSystem(db); if (!temp_directory.empty()) { fs.RemoveDirectory(temp_directory); } } shared_ptr<BlockHandle> BufferManager::RegisterBlock(block_id_t block_id) { lock_guard<mutex> lock(manager_lock); // check if the block already exists auto entry = blocks.find(block_id); if (entry != blocks.end()) { // already exists: check if it hasn't expired yet auto existing_ptr = entry->second.lock(); if (existing_ptr) { //! it hasn't! return it return existing_ptr; } } // create a new block pointer for this block auto result = make_shared<BlockHandle>(db, block_id); // register the block pointer in the set of blocks as a weak pointer blocks[block_id] = weak_ptr<BlockHandle>(result); return result; } shared_ptr<BlockHandle> BufferManager::RegisterMemory(idx_t alloc_size, bool can_destroy) { // first evict blocks until we have enough memory to store this buffer if (!EvictBlocks(alloc_size, maximum_memory)) { throw OutOfRangeException("Not enough memory to complete operation: could not allocate block of %lld bytes", alloc_size); } // allocate the buffer auto temp_id = ++temporary_id; auto buffer = make_unique<ManagedBuffer>(db, alloc_size, can_destroy, temp_id); // create a new block pointer for this block return make_shared<BlockHandle>(db, temp_id, move(buffer), can_destroy, alloc_size); } unique_ptr<BufferHandle> BufferManager::Allocate(idx_t alloc_size) { auto block = RegisterMemory(alloc_size, true); return Pin(block); } unique_ptr<BufferHandle> BufferManager::Pin(shared_ptr<BlockHandle> &handle) { // lock the block lock_guard<mutex> lock(handle->lock); // check if the block is already loaded if (handle->state == BlockState::BLOCK_LOADED) { // the block is loaded, increment the reader count and return a pointer to the handle handle->readers++; return handle->Load(handle); } // evict blocks until we have space for the current block if (!EvictBlocks(handle->memory_usage, maximum_memory)) { throw OutOfRangeException("Not enough memory to complete operation: failed to pin block"); } // now we can actually load the current block D_ASSERT(handle->readers == 0); handle->readers = 1; return handle->Load(handle); } void BufferManager::Unpin(shared_ptr<BlockHandle> &handle) { lock_guard<mutex> lock(handle->lock); D_ASSERT(handle->readers > 0); handle->readers--; if (handle->readers == 0) { handle->eviction_timestamp++; queue->q.enqueue(make_unique<BufferEvictionNode>(weak_ptr<BlockHandle>(handle), handle->eviction_timestamp)); // FIXME: do some house-keeping to prevent the queue from being flooded with many old blocks } } bool BufferManager::EvictBlocks(idx_t extra_memory, idx_t memory_limit) { unique_ptr<BufferEvictionNode> node; current_memory += extra_memory; while (current_memory > memory_limit) { // get a block to unpin from the queue if (!queue->q.try_dequeue(node)) { current_memory -= extra_memory; return false; } // get a reference to the underlying block pointer auto handle = node->handle.lock(); if (!handle) { continue; } if (!node->CanUnload(*handle)) { // early out: we already know that we cannot unload this node continue; } // we might be able to free this block: grab the mutex and check if we can free it lock_guard<mutex> lock(handle->lock); if (!node->CanUnload(*handle)) { // something changed in the mean-time, bail out continue; } // hooray, we can unload the block // release the memory and mark the block as unloaded handle->Unload(); } return true; } void BufferManager::UnregisterBlock(block_id_t block_id, bool can_destroy) { if (block_id >= MAXIMUM_BLOCK) { // in-memory buffer: destroy the buffer if (!can_destroy) { // buffer could have been offloaded to disk: remove the file DeleteTemporaryFile(block_id); } } else { lock_guard<mutex> lock(manager_lock); // on-disk block: erase from list of blocks in manager blocks.erase(block_id); } } void BufferManager::SetLimit(idx_t limit) { lock_guard<mutex> buffer_lock(manager_lock); // try to evict until the limit is reached if (!EvictBlocks(0, limit)) { throw OutOfRangeException( "Failed to change memory limit to new limit %lld: could not free up enough memory for the new limit", limit); } idx_t old_limit = maximum_memory; // set the global maximum memory to the new limit if successful maximum_memory = limit; // evict again if (!EvictBlocks(0, limit)) { // failed: go back to old limit maximum_memory = old_limit; throw OutOfRangeException( "Failed to change memory limit to new limit %lld: could not free up enough memory for the new limit", limit); } } string BufferManager::GetTemporaryPath(block_id_t id) { auto &fs = FileSystem::GetFileSystem(db); return fs.JoinPath(temp_directory, to_string(id) + ".block"); } void BufferManager::WriteTemporaryBuffer(ManagedBuffer &buffer) { D_ASSERT(!temp_directory.empty()); D_ASSERT(buffer.size + Storage::BLOCK_HEADER_SIZE >= Storage::BLOCK_ALLOC_SIZE); // get the path to write to auto path = GetTemporaryPath(buffer.id); // create the file and write the size followed by the buffer contents auto &fs = FileSystem::GetFileSystem(db); auto handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE); handle->Write(&buffer.size, sizeof(idx_t), 0); buffer.Write(*handle, sizeof(idx_t)); } unique_ptr<FileBuffer> BufferManager::ReadTemporaryBuffer(block_id_t id) { if (temp_directory.empty()) { throw Exception("Out-of-memory: cannot read buffer because no temporary directory is specified!\nTo enable " "temporary buffer eviction set a temporary directory in the configuration"); } idx_t alloc_size; // open the temporary file and read the size auto path = GetTemporaryPath(id); auto &fs = FileSystem::GetFileSystem(db); auto handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ); handle->Read(&alloc_size, sizeof(idx_t), 0); // now allocate a buffer of this size and read the data into that buffer auto buffer = make_unique<ManagedBuffer>(db, alloc_size + Storage::BLOCK_HEADER_SIZE, false, id); buffer->Read(*handle, sizeof(idx_t)); return move(buffer); } void BufferManager::DeleteTemporaryFile(block_id_t id) { auto &fs = FileSystem::GetFileSystem(db); auto path = GetTemporaryPath(id); if (fs.FileExists(path)) { fs.RemoveFile(path); } } } // namespace duckdb
33.229358
111
0.734585
c5sire
02d6501c286de5b002517feda7534d916ddcd9b7
7,766
cpp
C++
os/fs/fat/testsuite/fat32_time.cpp
rvedam/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
2
2020-11-30T18:38:20.000Z
2021-06-07T07:44:03.000Z
os/fs/fat/testsuite/fat32_time.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
1
2019-01-14T03:09:45.000Z
2019-01-14T03:09:45.000Z
os/fs/fat/testsuite/fat32_time.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006 Nintendo Co., Ltd. * * 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 <new> #include <stdlib.h> #include <es.h> #include <es/handle.h> #include <es/exception.h> #include <es/dateTime.h> #include "vdisk.h" #include "fatStream.h" #define TEST(exp) \ (void) ((exp) || \ (esPanic(__FILE__, __LINE__, "\nFailed test " #exp), 0)) static void SetData(u8* buf, long long size) { buf[size-1] = 0; while (--size) { *buf++ = 'a' + size % 26; } } static long TestReadWrite(Handle<es::Stream> stream) { u8* writeBuf; u8* readBuf; long long size = 1024LL; long ret = 0; writeBuf = new u8[size]; readBuf = new u8[size]; memset(readBuf, 0, size); SetData(writeBuf, size); ret = stream->write(writeBuf, size); TEST(ret == size); stream->setPosition(0); ret = stream->read(readBuf, size); TEST(ret == size); TEST (memcmp(writeBuf, readBuf, size) == 0); ERR: delete [] writeBuf; delete [] readBuf; return ret; } static long TestFileSystem(Handle<es::Context> root) { long long creationTime; long long lastAccessTime; long long lastWriteTime; Handle<es::File> file; const char* filename = "test.txt"; // create file. DateTime d = DateTime::getNow(); file = root->bind(filename, 0); DateTime end = DateTime::getNow(); DateTime start = DateTime(d.getYear(), d.getMonth(), d.getDay(), d.getHour(), d.getMinute(), d.getSecond(), d.getMillisecond() - d.getMillisecond() % 10); #ifdef VERBOSE DateTime dc(creationTime); esReport("creation %d/%d/%d %d:%d:%d.%d\n", dc.getYear(), dc.getMonth(), dc.getDay(), dc.getHour(), dc.getMinute(), dc.getSecond(), dc.getMillisecond()); esReport("start %d/%d/%d %d:%d:%d.%d\n", start.getYear(), start.getMonth(), start.getDay(), start.getHour(), start.getMinute(), start.getSecond(), start.getMillisecond()); esReport("end %d/%d/%d %d:%d:%d.%d\n", end.getYear(), end.getMonth(), end.getDay(), end.getHour(), end.getMinute(), end.getSecond(), end.getMillisecond()); #endif // VERBOSE // check creation time. creationTime = file->getCreationTime(); TEST(start.getTicks() <= creationTime && creationTime <= end.getTicks()); // read and write data to the file. Handle<es::Stream> stream = file->getStream(); d = DateTime::getNow(); TestReadWrite(stream); end = DateTime::getNow(); // check the last access time and the last write time. DateTime day = DateTime(d.getYear(), d.getMonth(), d.getDay(), 0, 0, 0); start = DateTime(d.getYear(), d.getMonth(), d.getDay(), d.getHour(), d.getMinute(), d.getSecond() - d.getSecond() % 2); lastAccessTime = file->getLastAccessTime(); lastWriteTime = file->getLastWriteTime(); TEST(day.getTicks() <= lastAccessTime && lastAccessTime <= end.getTicks()); TEST(start.getTicks() <= lastWriteTime && lastWriteTime <= end.getTicks()); #ifdef VERBOSE DateTime da(lastAccessTime); esReport("last access time %d/%d/%d %d:%d:%d.%d\n", da.getYear(), da.getMonth(), da.getDay(), da.getHour(), da.getMinute(), da.getSecond(), da.getMillisecond()); DateTime dw(lastWriteTime); esReport("start %d/%d/%d %d:%d:%d.%d\n", start.getYear(), start.getMonth(), start.getDay(), start.getHour(), start.getMinute(), start.getSecond(), start.getMillisecond()); esReport("lastWriteTime %d/%d/%d %d:%d:%d.%d\n", dw.getYear(), dw.getMonth(), dw.getDay(), dw.getHour(), dw.getMinute(), dw.getSecond(), dw.getMillisecond()); esReport("end %d/%d/%d %d:%d:%d.%d\n", end.getYear(), end.getMonth(), end.getDay(), end.getHour(), end.getMinute(), end.getSecond(), end.getMillisecond()); #endif // read the file, and check the last write time. u8 buf[512]; d = DateTime::getNow(); stream->read(buf, sizeof(buf)); end = DateTime::getNow(); start = DateTime(d.getYear(), d.getMonth(), d.getDay(), d.getHour(), d.getMinute(), d.getSecond()); long long lastWriteTime2; lastWriteTime2 = file->getLastWriteTime(); TEST(lastWriteTime == lastWriteTime2); long long creationTime2; creationTime2 = file->getCreationTime(); TEST(creationTime == creationTime2); d = DateTime::getNow(); DateTime now = DateTime(d.getYear(), d.getMonth(), d.getDay(), d.getHour(), d.getMinute(), d.getSecond(), d.getMillisecond() - d.getMillisecond() % 10); // check setCreationTime, setLastAccessTime and setLastWriteTime. file->setCreationTime(now.getTicks()); creationTime = file->getCreationTime(); TEST(now.getTicks() == creationTime); now = DateTime(d.getYear(), d.getMonth(), d.getDay(), 0, 0, 0, 0); file->setLastAccessTime(now.getTicks()); lastAccessTime = file->getLastAccessTime(); TEST(now.getTicks() == lastAccessTime); now = DateTime(d.getYear(), d.getMonth(), d.getDay(), d.getHour(), d.getMinute(), d.getSecond() - d.getSecond() % 2); file->setLastWriteTime(now.getTicks()); lastWriteTime = file->getLastWriteTime(); TEST(now.getTicks() == lastWriteTime); return 0; } int main(void) { Object* ns = 0; esInit(&ns); FatFileSystem::initializeConstructor(); Handle<es::Context> nameSpace(ns); #ifdef __es__ Handle<es::Stream> disk = nameSpace->lookup("device/ata/channel0/device0"); #else Handle<es::Stream> disk = new VDisk(static_cast<char*>("fat32.img")); #endif long long diskSize; diskSize = disk->getSize(); esReport("diskSize: %lld\n", diskSize); Handle<es::FileSystem> fatFileSystem; long long freeSpace; long long totalSpace; fatFileSystem = es::FatFileSystem::createInstance(); fatFileSystem->mount(disk); fatFileSystem->format(); freeSpace = fatFileSystem->getFreeSpace(); totalSpace = fatFileSystem->getTotalSpace(); esReport("Free space %lld, Total space %lld\n", freeSpace, totalSpace); { Handle<es::Context> root; root = fatFileSystem->getRoot(); long ret = TestFileSystem(root); TEST (ret == 0); freeSpace = fatFileSystem->getFreeSpace(); totalSpace = fatFileSystem->getTotalSpace(); esReport("Free space %lld, Total space %lld\n", freeSpace, totalSpace); esReport("\nChecking the file system...\n"); TEST(fatFileSystem->checkDisk(false)); } fatFileSystem->dismount(); fatFileSystem = 0; fatFileSystem = es::FatFileSystem::createInstance(); fatFileSystem->mount(disk); freeSpace = fatFileSystem->getFreeSpace(); totalSpace = fatFileSystem->getTotalSpace(); esReport("Free space %lld, Total space %lld\n", freeSpace, totalSpace); esReport("\nChecking the file system...\n"); TEST(fatFileSystem->checkDisk(false)); fatFileSystem->dismount(); fatFileSystem = 0; esReport("done.\n\n"); }
32.767932
97
0.61692
rvedam
02db7cd6952d7132a7503ab172e0932af88317b5
2,153
cpp
C++
src/cpp/camera.cpp
BrunodaSilvaBelo/historyCentral_cg
f0b10c1f8978610ac37c931259c33d6e3503d77f
[ "MIT" ]
null
null
null
src/cpp/camera.cpp
BrunodaSilvaBelo/historyCentral_cg
f0b10c1f8978610ac37c931259c33d6e3503d77f
[ "MIT" ]
null
null
null
src/cpp/camera.cpp
BrunodaSilvaBelo/historyCentral_cg
f0b10c1f8978610ac37c931259c33d6e3503d77f
[ "MIT" ]
null
null
null
#include "camera.h" #include <glm/gtx/transform.hpp> #include <GLFW/glfw3.h> Camera::Camera(const glm::vec3 &position, float fov, float aspect, float near, float far) : position(position) { forward = glm::vec3(0.f, 0.f, -1.f); up = glm::vec3(0.f, 1.f, 0.f); projection = glm::perspective(fov, aspect, near, far); } glm::mat4 Camera::getView() const { return glm::lookAt(position, position + forward, up); } glm::mat4 Camera::getProjection() const { return projection; } glm::vec3 Camera::getPosition() const { return position; } void Camera::update(GLfloat delta, const std::function<int(int)> &getKey, const std::function<void(double*,double*)> &getMousePosition, const std::function<int(int)> &getMouseButton) { auto velocity = speed * delta; if (getKey(GLFW_KEY_W) == GLFW_PRESS) position += velocity * forward; if (getKey(GLFW_KEY_S) == GLFW_PRESS) position -= velocity * forward; if (getKey(GLFW_KEY_A) == GLFW_PRESS) position -= velocity * glm::normalize(glm::cross(forward, up)); if (getKey(GLFW_KEY_D) == GLFW_PRESS) position += velocity * glm::normalize(glm::cross(forward, up)); if (getKey(GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) speed = 100.f; else speed = 5.f; GLdouble xpos, ypos; getMousePosition(&xpos, &ypos); static GLfloat lastX = static_cast<GLfloat>(xpos); static GLfloat lastY = static_cast<GLfloat>(ypos); GLfloat xoffset = static_cast<GLfloat>(xpos) - lastX; GLfloat yoffset = lastY - static_cast<GLfloat>(ypos); lastX = static_cast<GLfloat>(xpos); lastY = static_cast<GLfloat>(ypos); xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; pitch = (pitch > 89.f) ? 89.f : pitch; pitch = (pitch < -89.f) ? -89.f : pitch; forward = glm::normalize(glm::vec3( cos(glm::radians(yaw)) * cos(glm::radians(pitch)), sin(glm::radians(pitch)), sin(glm::radians(yaw)) * cos(glm::radians(pitch)))); } glm::vec3 Camera::getForward() const { return forward; }
30.757143
89
0.625174
BrunodaSilvaBelo
02db871fa595de0dc54085ca4467499ca2d1f656
8,488
cpp
C++
cpdp/src/v20190820/model/CreateSinglePayResult.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cpdp/src/v20190820/model/CreateSinglePayResult.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cpdp/src/v20190820/model/CreateSinglePayResult.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cpdp/v20190820/model/CreateSinglePayResult.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace std; CreateSinglePayResult::CreateSinglePayResult() : m_handleStatusHasBeenSet(false), m_handleMsgHasBeenSet(false), m_serialNoHasBeenSet(false), m_bankSerialNoHasBeenSet(false), m_payStatusHasBeenSet(false), m_bankRetCodeHasBeenSet(false), m_bankRetMsgHasBeenSet(false) { } CoreInternalOutcome CreateSinglePayResult::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("HandleStatus") && !value["HandleStatus"].IsNull()) { if (!value["HandleStatus"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.HandleStatus` IsString=false incorrectly").SetRequestId(requestId)); } m_handleStatus = string(value["HandleStatus"].GetString()); m_handleStatusHasBeenSet = true; } if (value.HasMember("HandleMsg") && !value["HandleMsg"].IsNull()) { if (!value["HandleMsg"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.HandleMsg` IsString=false incorrectly").SetRequestId(requestId)); } m_handleMsg = string(value["HandleMsg"].GetString()); m_handleMsgHasBeenSet = true; } if (value.HasMember("SerialNo") && !value["SerialNo"].IsNull()) { if (!value["SerialNo"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.SerialNo` IsString=false incorrectly").SetRequestId(requestId)); } m_serialNo = string(value["SerialNo"].GetString()); m_serialNoHasBeenSet = true; } if (value.HasMember("BankSerialNo") && !value["BankSerialNo"].IsNull()) { if (!value["BankSerialNo"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.BankSerialNo` IsString=false incorrectly").SetRequestId(requestId)); } m_bankSerialNo = string(value["BankSerialNo"].GetString()); m_bankSerialNoHasBeenSet = true; } if (value.HasMember("PayStatus") && !value["PayStatus"].IsNull()) { if (!value["PayStatus"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.PayStatus` IsString=false incorrectly").SetRequestId(requestId)); } m_payStatus = string(value["PayStatus"].GetString()); m_payStatusHasBeenSet = true; } if (value.HasMember("BankRetCode") && !value["BankRetCode"].IsNull()) { if (!value["BankRetCode"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.BankRetCode` IsString=false incorrectly").SetRequestId(requestId)); } m_bankRetCode = string(value["BankRetCode"].GetString()); m_bankRetCodeHasBeenSet = true; } if (value.HasMember("BankRetMsg") && !value["BankRetMsg"].IsNull()) { if (!value["BankRetMsg"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateSinglePayResult.BankRetMsg` IsString=false incorrectly").SetRequestId(requestId)); } m_bankRetMsg = string(value["BankRetMsg"].GetString()); m_bankRetMsgHasBeenSet = true; } return CoreInternalOutcome(true); } void CreateSinglePayResult::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_handleStatusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HandleStatus"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_handleStatus.c_str(), allocator).Move(), allocator); } if (m_handleMsgHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HandleMsg"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_handleMsg.c_str(), allocator).Move(), allocator); } if (m_serialNoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SerialNo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_serialNo.c_str(), allocator).Move(), allocator); } if (m_bankSerialNoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BankSerialNo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_bankSerialNo.c_str(), allocator).Move(), allocator); } if (m_payStatusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PayStatus"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_payStatus.c_str(), allocator).Move(), allocator); } if (m_bankRetCodeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BankRetCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_bankRetCode.c_str(), allocator).Move(), allocator); } if (m_bankRetMsgHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BankRetMsg"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_bankRetMsg.c_str(), allocator).Move(), allocator); } } string CreateSinglePayResult::GetHandleStatus() const { return m_handleStatus; } void CreateSinglePayResult::SetHandleStatus(const string& _handleStatus) { m_handleStatus = _handleStatus; m_handleStatusHasBeenSet = true; } bool CreateSinglePayResult::HandleStatusHasBeenSet() const { return m_handleStatusHasBeenSet; } string CreateSinglePayResult::GetHandleMsg() const { return m_handleMsg; } void CreateSinglePayResult::SetHandleMsg(const string& _handleMsg) { m_handleMsg = _handleMsg; m_handleMsgHasBeenSet = true; } bool CreateSinglePayResult::HandleMsgHasBeenSet() const { return m_handleMsgHasBeenSet; } string CreateSinglePayResult::GetSerialNo() const { return m_serialNo; } void CreateSinglePayResult::SetSerialNo(const string& _serialNo) { m_serialNo = _serialNo; m_serialNoHasBeenSet = true; } bool CreateSinglePayResult::SerialNoHasBeenSet() const { return m_serialNoHasBeenSet; } string CreateSinglePayResult::GetBankSerialNo() const { return m_bankSerialNo; } void CreateSinglePayResult::SetBankSerialNo(const string& _bankSerialNo) { m_bankSerialNo = _bankSerialNo; m_bankSerialNoHasBeenSet = true; } bool CreateSinglePayResult::BankSerialNoHasBeenSet() const { return m_bankSerialNoHasBeenSet; } string CreateSinglePayResult::GetPayStatus() const { return m_payStatus; } void CreateSinglePayResult::SetPayStatus(const string& _payStatus) { m_payStatus = _payStatus; m_payStatusHasBeenSet = true; } bool CreateSinglePayResult::PayStatusHasBeenSet() const { return m_payStatusHasBeenSet; } string CreateSinglePayResult::GetBankRetCode() const { return m_bankRetCode; } void CreateSinglePayResult::SetBankRetCode(const string& _bankRetCode) { m_bankRetCode = _bankRetCode; m_bankRetCodeHasBeenSet = true; } bool CreateSinglePayResult::BankRetCodeHasBeenSet() const { return m_bankRetCodeHasBeenSet; } string CreateSinglePayResult::GetBankRetMsg() const { return m_bankRetMsg; } void CreateSinglePayResult::SetBankRetMsg(const string& _bankRetMsg) { m_bankRetMsg = _bankRetMsg; m_bankRetMsgHasBeenSet = true; } bool CreateSinglePayResult::BankRetMsgHasBeenSet() const { return m_bankRetMsgHasBeenSet; }
29.574913
152
0.699222
suluner
02dc9bc94ffc741362e21ebdb3d2073bf9014a04
3,244
hpp
C++
test/set.hpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
1
2017-05-10T05:42:43.000Z
2017-05-10T05:42:43.000Z
test/set.hpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
null
null
null
test/set.hpp
LeslieW/gecode-clone
ab3ab207c98981abfe4c52f01b248ec7bc4e8e8c
[ "MIT-feh" ]
1
2017-01-27T14:52:22.000Z
2017-01-27T14:52:22.000Z
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2005 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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. * */ namespace Test { namespace Set { inline std::string SetTest::str(int i) { std::stringstream s; s << i; return s.str(); } inline std::string SetTest::str(Gecode::SetRelType srt) { switch (srt) { case Gecode::SRT_EQ: return "Eq"; case Gecode::SRT_LQ: return "Lq"; case Gecode::SRT_LE: return "Le"; case Gecode::SRT_GQ: return "Gq"; case Gecode::SRT_GR: return "Gr"; case Gecode::SRT_NQ: return "Nq"; case Gecode::SRT_SUB: return "Sub"; case Gecode::SRT_SUP: return "Sup"; case Gecode::SRT_DISJ: return "Disj"; case Gecode::SRT_CMPL: return "Cmpl"; } return ""; } inline std::string SetTest::str(Gecode::SetOpType sot) { switch (sot) { case Gecode::SOT_UNION: return "Union"; case Gecode::SOT_DUNION: return "DUnion"; case Gecode::SOT_INTER: return "Inter"; case Gecode::SOT_MINUS: return "Minus"; } return ""; } inline std::string SetTest::str(const Gecode::IntArgs& x) { std::string s = ""; for (int i=0; i<x.size()-1; i++) s += str(x[i]) + ","; return "[" + s + str(x[x.size()-1]) + "]"; } inline SetRelTypes::SetRelTypes(void) : i(sizeof(srts)/sizeof(Gecode::SetRelType)-1) {} inline bool SetRelTypes::operator()(void) const { return i>=0; } inline void SetRelTypes::operator++(void) { i--; } inline Gecode::SetRelType SetRelTypes::srt(void) const { return srts[i]; } inline SetOpTypes::SetOpTypes(void) : i(sizeof(sots)/sizeof(Gecode::SetOpType)-1) {} inline bool SetOpTypes::operator()(void) const { return i>=0; } inline void SetOpTypes::operator++(void) { i--; } inline Gecode::SetOpType SetOpTypes::sot(void) const { return sots[i]; } }} // STATISTICS: test-set
26.590164
74
0.649815
LeslieW
02dd77740c65e387a581758908730ba9bfb4e1d2
8,105
hpp
C++
esp/platform/esptraceloggingcomponent.hpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
esp/platform/esptraceloggingcomponent.hpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
esp/platform/esptraceloggingcomponent.hpp
jakesmith/HPCC-Platform
c3b9268c492e473176ea36e3e916c4a544f47561
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2021 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #ifndef _EspTraceLoggingComponent_HPP_ #define _EspTraceLoggingComponent_HPP_ #include "espcontext.hpp" #include "jlog.hpp" /// Common log message detail priority values. namespace TraceLoggingPriority { static const LogMsgDetail Critical = 1; static const LogMsgDetail Major = 10; static const LogMsgDetail Highest = 20; static const LogMsgDetail High = 30; static const LogMsgDetail Medium = 40; static const LogMsgDetail Normal = 50; static const LogMsgDetail Low = 60; static const LogMsgDetail Lowest = 70; static const LogMsgDetail Trivial = 80; static const LogMsgDetail DataDump = 90; static const LogMsgDetail CallStack = 100; } // namespace TraceLoggingPriority /** * ITraceLoggingComponent reimagines multiple platform approahes to trace log output. Specifically, * it is a hybrid of the jlog LOG-related functions and the ESP's ESPLOG. Like jlog, trace content * is associated with an audience, a classification, and a priority. Like ESPLOG, the priority is * assigned by the caller instead of the function. Also like ESPLOG, generated content is filtered * by comparing the assigned priority to a user configured limit. * * The logging methods in the interface are not virtual. The encapsulation of them within an * interface allows the use of virtual helper functions that enable transparent support for * additional functionality, including: * - define its own priority limit; * - adjust prepared content before output; * - direct prepared content to any combination of output targets. * * Why multiple priority limits? Especially during development and testing, it is often the case * that a desire for verbose output is limited to the area(s) under review. Raising A single limit, * such as is done with ESPLOG, can increase the volume of log content to the point that finding * content of interest is unnecessarily difficult. This enables, without requiring, a more granular * configuration of limits. * * Why message content adjustments? Knowing that a class instance failed is good, but knowning which * instance failed is better. Obviously the content passed to each log call can be composed to * include identifying information, but this enables identifying information to be automatically * attached to each message. * * Why multiple output targets? A proposal has been made to allow transactional trace log entries * to be returned in some ESP responses. The proposal is primarily concerned with returning entries * generated by DESDL custom transforms to the users developing and testing said transforms. This * provides a hook where accumulation of relevant entries can occur. */ interface ITraceLoggingComponent : extends IInterface { /// Returns the highest accepted message priority for the given message category. virtual LogMsgDetail tracePriorityLimit(const LogMsgCategory& category) const = 0; /// Directs accepted content to implemtation-defined targets. virtual void traceOutput(const LogMsgCategory& category, const char* format, va_list& arguments) const = 0; /// Defines optional instance identification for content adjustment. virtual const char* traceId() const = 0; /** * LOG_METHOD_TEMPLATE defines a non-virtual method using its first parameter. The method * defines a shared instance of a LogMsgCategory using the remaining parameters. If the * requested message priority is neither zero nor greater than the message priority limit, the * message will be logged. */ #define LOG_METHOD_TEMPLATE(function, audience, classification) \ void function(LogMsgDetail priorityRequested, const char* format, ...) const __attribute__((format(printf, 3, 4))) \ { \ static const LogMsgCategory LMC##function(audience, classification, 1); \ if (priorityRequested && priorityRequested <= tracePriorityLimit(LMC##function)) \ { \ va_list arguments; \ va_start(arguments, format); \ traceOutput(LMC##function, format, arguments); \ va_end(arguments); \ } \ } LOG_METHOD_TEMPLATE(uerrlog, MSGAUD_user, MSGCLS_error); LOG_METHOD_TEMPLATE(uwarnlog, MSGAUD_user, MSGCLS_warning); LOG_METHOD_TEMPLATE(uproglog, MSGAUD_user, MSGCLS_progress); LOG_METHOD_TEMPLATE(uinfolog, MSGAUD_user, MSGCLS_information); LOG_METHOD_TEMPLATE(ierrlog, MSGAUD_programmer, MSGCLS_error); LOG_METHOD_TEMPLATE(iwarnlog, MSGAUD_programmer, MSGCLS_warning); LOG_METHOD_TEMPLATE(iproglog, MSGAUD_programmer, MSGCLS_progress); LOG_METHOD_TEMPLATE(iinfolog, MSGAUD_programmer, MSGCLS_information); LOG_METHOD_TEMPLATE(oerrlog, MSGAUD_operator, MSGCLS_error); LOG_METHOD_TEMPLATE(owarnlog, MSGAUD_operator, MSGCLS_warning); LOG_METHOD_TEMPLATE(oproglog, MSGAUD_operator, MSGCLS_progress); LOG_METHOD_TEMPLATE(oinfolog, MSGAUD_operator, MSGCLS_information); #undef LOG_METHOD_TEMPLATE }; /** * Standard interface implementation, inheriting behavior from base class 'C'. */ #define IMPLEMENT_ITRACELOGGINGCOMPONENT_WITH(C) \ inline LogMsgDetail tracePriorityLimit(LogMsgAudience audience, LogMsgClass classification) const { return tracePriorityLimit(LogMsgCategory(audience, classification, 1)); } \ virtual LogMsgDetail tracePriorityLimit(const LogMsgCategory& category) const override { return C::tracePriorityLimit(category); } \ virtual void traceOutput(const LogMsgCategory& category, const char* format, va_list& arguments) const override __attribute__((format(printf, 3, 0))) { return C::traceOutput(category, format, arguments); } \ virtual const char* traceId() const override { return C::traceId(); } /** * Utility class for logging entry to and exit from a block of code. */ class CTraceBlock { private: const ITraceLoggingComponent& m_component; StringBuffer m_caption; public: CTraceBlock(const ITraceLoggingComponent& component, const char* caption) : m_component(component) , m_caption(caption) { m_component.iproglog(TraceLoggingPriority::CallStack, "Enter '%s'", m_caption.str()); } ~CTraceBlock() { m_component.iproglog(TraceLoggingPriority::CallStack, "Exit '%s'", m_caption.str()); } }; #define TRACE_BLOCK_WITH(component, caption) CTraceBlock traceBlock(component, caption) #define TRACE_BLOCK(caption) TRACE_BLOCK_WITH(*this, caption) /** * Basic implementation of the ITraceLoggingComponent interface for use as a mixin base, exposing * the logging methods with default behavior. */ class CEspTraceLoggingComponent : implements ITraceLoggingComponent, extends CInterface { public: IMPLEMENT_IINTERFACE; virtual LogMsgDetail tracePriorityLimit(const LogMsgCategory& category) const override { return (getEspLogLevel() * 10); } virtual void traceOutput(const LogMsgCategory& category, const char* format, va_list& arguments) const override { VALOG(category, format, arguments); } virtual const char* traceId() const override { return nullptr; } inline LogMsgDetail tracePriorityLimit(LogMsgAudience audience, LogMsgClass classification) const { return tracePriorityLimit(LogMsgCategory(audience, classification, 1)); } \ }; #endif // _EspTraceLoggingComponent_HPP_
49.121212
220
0.741024
jeclrsg
02dfbb902eade56371c5928ff45c8610e0860600
235
cpp
C++
main.cpp
bguina/gomoku
bfce942ba8c0b5cb75675772eaf36ea0611c60b2
[ "Apache-2.0" ]
null
null
null
main.cpp
bguina/gomoku
bfce942ba8c0b5cb75675772eaf36ea0611c60b2
[ "Apache-2.0" ]
null
null
null
main.cpp
bguina/gomoku
bfce942ba8c0b5cb75675772eaf36ea0611c60b2
[ "Apache-2.0" ]
null
null
null
#include <libgen.h> #include "Gomoku.hpp" #include "ResourceMgr.hpp" int main(int ac, char** av) { Gomoku app; (void)ac; ResourceMgr::set_binary_directory(std::string(dirname(av[0]))); app.run(); return 0; }
14.6875
67
0.625532
bguina
02e13227a9bdbeb5269f929e0625f1b0a96d2149
2,474
cpp
C++
games_old/Pacman/lib/Ncurse.cpp
HugoSohm/Arcade
2363078a8bd5864c3812d1a25061ac72dd099eee
[ "MIT" ]
null
null
null
games_old/Pacman/lib/Ncurse.cpp
HugoSohm/Arcade
2363078a8bd5864c3812d1a25061ac72dd099eee
[ "MIT" ]
null
null
null
games_old/Pacman/lib/Ncurse.cpp
HugoSohm/Arcade
2363078a8bd5864c3812d1a25061ac72dd099eee
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** OOP_arcade_2018 ** File description: ** ncurse.cpp */ #include "Ncurse.hpp" Ncurse::Ncurse() { initscr(); //noecho(); //cbreak(); //getch(); } Ncurse::~Ncurse() = default; void Ncurse::drawASquare(float x, float y, float width, float height, unsigned int color) { /* if (has_colors() == FALSE) { endwin(); printf("Your terminal does not support color\n"); exit(84); } */ start_color(); init_pair(1, COLOR_BLUE, COLOR_BLUE); attron(COLOR_PAIR(color)); mvprintw(x, y, "*"); attroff(COLOR_PAIR(color)); } void Ncurse::drawASquare(float x, float y, float width, float height, std::string map) { map += ".txt"; if (has_colors() == FALSE) { endwin(); printf("Your terminal does not support color\n"); exit(84); } start_color(); init_pair(1, COLOR_BLUE, COLOR_BLUE); attron(COLOR_PAIR(1)); mvprintw(x, y, "*"); attroff(COLOR_PAIR(1)); } void Ncurse::drawASquare(float x, float y, float width, float height, std::string map, unsigned int color, bool = true, bool = false) { map += ".txt"; if (has_colors() == FALSE) { endwin(); printf("Your terminal does not support color\n"); exit(84); } start_color(); init_pair(1, COLOR_BLUE, COLOR_BLUE); attron(COLOR_PAIR(1)); mvprintw(x, y, "*"); attroff(COLOR_PAIR(1)); } void Ncurse::setATextField(float x, float y, std::string fontPath) { _inputwin = newwin(3, static_cast<int>(x), static_cast<int>(y), 5); box(_inputwin, 0, 0); } void Ncurse::drawATextField(std::string &textToDraw) { wrefresh(_inputwin); } void Ncurse::drawAText(float x, float y, std::string str) { mvprintw(x, y, str.c_str()); } void Ncurse::clearThisSquare(float x, float y, char c) { mvwprintw(_window, x, y, &c); } void Ncurse::clearAll() { clear(); } int Ncurse::getKeyPress() { return(wgetch(_window)); } void Ncurse::display() { wrefresh(_window); } void Ncurse::clear() { } void Ncurse::initSprite(std::string, int, int, int) { } void Ncurse::execThisSprite(float sizeX, float sizeY, float x, float y, std::string name, unsigned int color, bool dinamic, bool bold) { } void Ncurse::drawThisSprite(float sizeX, float sizeY, float x, float y, std::string name, unsigned int color, bool dinamic, bool bold) { } void Ncurse::drawASquare(float x, float y, float width, float height, std::string map, unsigned int color, bool, bool) { } extern "C" { void *LoadMap() { Ncurse *a = new Ncurse(); return(a); } }
18.191176
134
0.656023
HugoSohm
02e5d887a776d290e7c1d6c775d66222d0b22583
4,697
cpp
C++
fake_main.cpp
AmberLJC/FALCONN
9438b38633283c851f8dd2692586e692260ac7b3
[ "MIT" ]
null
null
null
fake_main.cpp
AmberLJC/FALCONN
9438b38633283c851f8dd2692586e692260ac7b3
[ "MIT" ]
null
null
null
fake_main.cpp
AmberLJC/FALCONN
9438b38633283c851f8dd2692586e692260ac7b3
[ "MIT" ]
null
null
null
// // Created by 刘嘉晨 on 2019-06-22. // #include <omp.h> #include <numeric> #include <iostream> #include <vector> #include <algorithm> using namespace std; #include <string.h> #include <cstdlib> #include <string> #include<fstream> #include "float.h" #include<sstream> template <typename T> vector<size_t> sort_indexes(const vector<T> &v) { vector<size_t> idx(v.size()); //使用iota对向量赋0~?的连续值 iota(idx.begin(), idx.end(), 0); // 通过比较v的值对索引idx进行排序 sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];}); //increasing order return idx; } //./main dense1k 1000 100 int main(int argc, char *argv[]) //int main() { const int NUM = std::atoi( argv[2]); const int Q=1000; const int K=100; const int DIM= atoi(argv[3]); /* char a[20];//定义字符数组a,b strcpy(a,argv[1]);//将b中 const char *LEARN =strcat(a,"_learn.txt"); strcpy(a,argv[1]); const char *GT =strcat(a,"_gt.txt"); strcpy(a,argv[1]); const char *BASE =strcat(a,"_base.txt"); strcpy(a,argv[1]); const char *QUERY =strcat(a,"_query.txt"); */ char IN[20]; strcpy(IN,argv[1]); const char *a =strcat(IN,".txt"); vector< vector<float> > data(NUM,vector<float> (DIM+1)); cout<<"Generating input "<< IN <<" for faiss, "<< NUM <<" data with "<<DIM<<" dimension."<<endl; ifstream infile;//定义读取文件流,相对于程序来说是in cout<<"Start reading !"<<endl; infile.open( IN );//打开文件 for (int i = 0; i < NUM; i++)//定义行循环 {data[i][0]=i; for (int j = 1; j < 1+ DIM; j++)//定义列循环 { infile >> data[i][j];//读取一个值(空格、制表符、换行隔开)就写入到矩阵中,行列不断循环进行 //cout << data[i][j]<< " , "; } } infile.close();//读取完成之后关闭文件 cout<<"finish reading !"<<endl; for (int j = 0; j < DIM+1; j++)//定义列循环 { cout << data[0][j]<< " ,";//以下代码是用来验证读取到的值是否正确 } cout<<endl; char BASE[20];//定义字符数组a,b strcpy(BASE,argv[1]);//将b中 strcat(BASE,"_base.txt"); ofstream outfile (BASE); if(!outfile.is_open()) { cout<<" the file open fail"<<endl; exit(1); } for(int i=0;i<NUM;i++) { for(int j=0;j<DIM+1;j++) { outfile<<data[i][j]<<" "; } outfile<<"\r\n"; } cout<<"finish writing to "<<BASE<<endl; outfile.flush(); outfile.close(); char LEARN[20];//定义字符数组a,b strcpy(LEARN,argv[1]);//将b中 strcat(LEARN,"_learn.txt"); ofstream outfile2 (LEARN); if(!outfile2.is_open()) { cout<<" the file open fail"<<endl; exit(1); } int str = int(NUM/10); int end = int(NUM/5) ; for(int i= str ;i< end ;i++) { for(int j=0;j<DIM+1;j++) { outfile2<<data[i][j]<<" "; } outfile2<<"\r\n"; } cout<<"finish writing to "<<LEARN<<endl; outfile2.close(); outfile2.flush(); char QUERY[20];//定义字符数组a,b strcpy(QUERY,argv[1]);//将b中 strcat(QUERY,"_query.txt"); ofstream outfile3(QUERY); if(!outfile3.is_open()) { cout<<QUERY<< " file open fail"<<endl; exit(1); } for(int i = 0 ;i < Q ; i++) { for(int j = 0 ;j < DIM+1 ; j++ ) { outfile3<<data[i][j]<<" "; } outfile3<<"\r\n"; } cout<<"finish writing to "<<QUERY<<endl; outfile3.close(); outfile3.flush(); char GT[20];//定义字符数组a,b strcpy(GT,argv[1]);//将b中 strcat(GT,"_gt.txt"); int const THREAD_NUM = 60 ; ofstream outfile4 (GT); if(!outfile4.is_open()) { cout<<GT<< " file open fail"<<endl; exit(1); } #pragma omp parallel for num_threads(THREAD_NUM) for(int i = 0 ;i < Q ; i++){// 1000 query // vector<int> dis_list(NUM); float min_dis =DBL_MAX; int min_idx=i; #pragma omp parallel for num_threads(THREAD_NUM) for(int j = 0 ;j < NUM ; j++ ){// linear scan float dis=0; //#pragma omp parallel for num_threads(THREAD_NUM) for(int d = 1 ; d< DIM+1 ; d++) { dis+= ( data[j][d]-data[i][d])*( data[j][d]-data[i][d]); if (dis > min_dis) break; } if( dis < min_dis && dis>0){ min_idx=j; min_dis=dis; } // dis_list[j]=dis; } // vector<size_t> res(NUM); //res= sort_indexes (dis_list); outfile4<< 0 <<" "<<min_idx<<" "; for(int j = 2 ;j < K+1 ; j++ ) { outfile4<< 0 <<" "; } outfile4<<"\r\n"; if(i%100==0) cout<<"Find 10% 1nn groundtruth : "<<min_idx<<endl; } outfile4.close(); return 0; }
21.545872
100
0.507984
AmberLJC
02e66dc92c0347f55b5f2fbc2db2245d183e668a
880
cpp
C++
gameobjects/PlayerServer.cpp
notbaab/HEAT
c8821a789e530216aa961ac9a4bee7f0a1a8736b
[ "MIT" ]
2
2019-11-15T18:49:09.000Z
2022-01-31T04:12:29.000Z
gameobjects/PlayerServer.cpp
notbaab/HEAT
c8821a789e530216aa961ac9a4bee7f0a1a8736b
[ "MIT" ]
37
2019-08-08T01:53:51.000Z
2022-02-01T04:35:03.000Z
gameobjects/PlayerServer.cpp
notbaab/HEAT
c8821a789e530216aa961ac9a4bee7f0a1a8736b
[ "MIT" ]
null
null
null
#include "PlayerServer.h" #include "events/PlayerInputEvent.h" namespace gameobjects { std::shared_ptr<PhysicsComponentUpdate> PlayerServer::CreateStateUpdateEvent() { return std::make_shared<PhysicsComponentUpdate>(this->GetWorldId(), lastMoveSeq, this->physicsComponent); } void PlayerServer::Update() { if (moves.empty()) { return; } // apply any moves we got from the players ApplyMoves(physicsComponent, moves); lastMoveSeq = moves.back()->moveSeq; moves.clear(); // send an update message. For now it's just the physics component that is // being updated. auto phyEvt = CreateStateUpdateEvent(); EventManager::sInstance->QueueEvent(phyEvt); TRACE("Sent {}, {}", phyEvt->x, phyEvt->y); } void PlayerServer::HandleStateMessage(std::shared_ptr<PhysicsComponentUpdate> stateEvent) {} } // namespace gameobjects
25.882353
109
0.711364
notbaab
02e75331acc5259abc0e8746e7cd0d371642a31a
1,365
cpp
C++
problems/election.cpp
migcruz/algorithms
802d6e4e0b463d887be1c2d62a6dbdd543522a7c
[ "MIT" ]
null
null
null
problems/election.cpp
migcruz/algorithms
802d6e4e0b463d887be1c2d62a6dbdd543522a7c
[ "MIT" ]
null
null
null
problems/election.cpp
migcruz/algorithms
802d6e4e0b463d887be1c2d62a6dbdd543522a7c
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; struct candidate { int votes; string name; }; candidate findWinner(vector<candidate> &candidateList){ candidate winner; int currentVotes = 0; for (vector<candidate>::iterator it = candidateList.begin(); it != candidateList.end(); ++it) { if (it->votes > currentVotes){ currentVotes = it->votes; winner = *it; cout << winner.name << endl; } } return winner; } // void sortCandidates(vector<candidate> &candidateList){ //do a quick sort but use votes as conditions and swap the vector indices // } int main(void){ vector<candidate> candidateList; candidate winner; //Candidates candidateList.push_back(candidate()); candidateList.push_back(candidate()); candidateList.push_back(candidate()); candidateList.push_back(candidate()); candidateList.push_back(candidate()); //Modify its name and votes. candidateList[0].name = "Jessica"; candidateList[0].votes = 98; candidateList[1].name = "David"; candidateList[1].votes = 45; candidateList[2].name = "Miguel"; candidateList[2].votes = 98; candidateList[3].name = "Gina"; candidateList[3].votes = 76; candidateList[4].name = "Bob"; candidateList[4].votes = 82; cout << "LOL" << endl; winner = findWinner(candidateList); return 0; }
21.328125
96
0.676923
migcruz
02e998d09bfce8e0465620db48d00f93573f7bc2
3,174
cpp
C++
tests/Unit/NumericalAlgorithms/SphericalHarmonics/Test_SpherepackIterator.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
tests/Unit/NumericalAlgorithms/SphericalHarmonics/Test_SpherepackIterator.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
tests/Unit/NumericalAlgorithms/SphericalHarmonics/Test_SpherepackIterator.cpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <algorithm> #include <cstddef> #include <string> #include <vector> #include "Framework/TestHelpers.hpp" #include "NumericalAlgorithms/SphericalHarmonics/SpherepackIterator.hpp" #include "Utilities/GetOutput.hpp" #include "Utilities/Literals.hpp" SPECTRE_TEST_CASE("Unit.SphericalHarmonics.SpherepackIterator", "[NumericalAlgorithms][Unit]") { const std::vector<size_t> test_l = {0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 2, 2, 3, 3, 4, 4}; const std::vector<size_t> test_m = {0, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 1, 1, 2, 1, 2, 1, 2}; const std::vector<size_t> test_index = {0, 15, 20, 30, 35, 40, 45, 50, 55, 60, 65, 70, 95, 110, 115, 125, 130, 140, 145}; // [spherepack_iterator_example] const size_t l_max = 4; const size_t m_max = 2; const size_t stride = 5; SpherepackIterator iter(l_max, m_max, stride); // Allocate space for a SPHEREPACK array std::vector<double> array(iter.spherepack_array_size() * stride); // Set each array element equal to l+m for real part // and l-m for imaginary part. size_t i = 0; for (iter.reset(); iter; ++iter, ++i) { if (iter.coefficient_array() == SpherepackIterator::CoefficientArray::a) { array[iter()] = iter.l() + iter.m(); } else { array[iter()] = iter.l() - iter.m(); } CHECK(iter.l() == test_l[i]); CHECK(iter.m() == test_m[i]); CHECK(iter() == test_index[i]); } // [spherepack_iterator_example] CHECK(iter.l_max() == 4); CHECK(iter.m_max() == 2); CHECK(iter.n_th() == 5); CHECK(iter.n_ph() == 5); for (i = 0; i < test_index.size(); ++i) { auto j = test_index[i]; if (i > 11) { // For specific test_index chosen above. // imag part CHECK(array[j] == test_l[i] - test_m[i]); } else { // real part CHECK(array[j] == test_l[i] + test_m[i]); } } // Test set functions CHECK(iter.set(2, 1, SpherepackIterator::CoefficientArray::b)() == 110); // Test the set function for the case l>m_max+1 CHECK(iter.set(4, 1, SpherepackIterator::CoefficientArray::a)() == 65); CHECK(iter.set(4, 1, SpherepackIterator::CoefficientArray::b)() == 140); CHECK(iter.reset()() == 0); CHECK(iter.set(2, 1)() == 35); CHECK(iter.set(2, -1)() == 110); // Test coefficient_arrya stream operator (assumes output of last 'set'). CHECK(get_output(iter.coefficient_array()) == "b"); // Test inequality const SpherepackIterator iter2(3, 2, 5); // Different lmax,mmax const SpherepackIterator iter3(4, 2, 4); // Different stride const SpherepackIterator iter4(4, 2, 5); // Different current state CHECK(iter2 != iter); CHECK(iter != iter2); CHECK(iter != iter3); CHECK(iter3 != iter); CHECK(iter4 != iter); CHECK(iter != iter4); test_copy_semantics(iter); const auto iter_copy = iter; CHECK(iter_copy == iter); test_move_semantics(std::move(iter), iter_copy, 3_st, 2_st, 3_st); }
35.266667
78
0.603025
nilsvu
02eab0641c46b403b2d3713b545cab51fe645fab
1,673
cpp
C++
Project/Part4/Example/driver.cpp
BlakeBerry26/ProgLangS22
32619e751f3a9a7ff2ff0f9ed31d9b6817303420
[ "MIT" ]
null
null
null
Project/Part4/Example/driver.cpp
BlakeBerry26/ProgLangS22
32619e751f3a9a7ff2ff0f9ed31d9b6817303420
[ "MIT" ]
null
null
null
Project/Part4/Example/driver.cpp
BlakeBerry26/ProgLangS22
32619e751f3a9a7ff2ff0f9ed31d9b6817303420
[ "MIT" ]
null
null
null
//***************************************************************************** // purpose: driver file for interpreter example // version: Spring 2022 // author: Joe Crumpton / Ed Swan //***************************************************************************** #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include "lexer.h" #include "parser.h" #include "parse_tree_nodes.h" #include <iostream> using namespace std; extern "C" { // Instantiate global variables extern FILE *yyin; // input stream extern FILE *yyout; // output stream extern int yyleng; // length of current lexeme extern char *yytext; // text of current lexeme extern int yylex(); // the generated lexical analyzer extern int yylex_destroy(); // deletes memory allocated by yylex } int main( int argc, char* argv[] ) { // Open the input data file and process its contents if ((yyin = fopen("front.in", "r")) == NULL) { cout << "ERROR - cannot open front.in" << endl; return(EXIT_FAILURE); } // This line allows typing in an expression interactively yyin = stdin; // Create the root of the parse tree ExprNode* root = nullptr; lex(); // prime the pump (get first token) do { root = expr(); // start symbol is <expr> } while (nextToken != TOK_EOF); if (yyin) fclose(yyin); yylex_destroy(); cout << endl << "*** In order traversal of parse tree ***" << endl; cout << *root << endl << endl; cout << "*** Interpreting the Arithmetic Expression ***" << endl; cout << root->interpret() << endl << endl; cout << "*** Delete the parse tree ***" << endl; delete root; root = nullptr; return(EXIT_SUCCESS); }
26.555556
79
0.588763
BlakeBerry26