hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
198afa841e2b4b299cfac1ee12484b0c5f49e1f8 | 7,593 | cpp | C++ | editor/mainwindow.cpp | ErrrOrrr503/DOORkaEngine | 90084cc622b1bcc021d9c3de5ccb52b349d4217e | [
"WTFPL"
] | null | null | null | editor/mainwindow.cpp | ErrrOrrr503/DOORkaEngine | 90084cc622b1bcc021d9c3de5ccb52b349d4217e | [
"WTFPL"
] | null | null | null | editor/mainwindow.cpp | ErrrOrrr503/DOORkaEngine | 90084cc622b1bcc021d9c3de5ccb52b349d4217e | [
"WTFPL"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->console->setReadOnly(true);
ui->texture_label->clear();
ogl_layout = new QHBoxLayout(ui->frame_ogl);
ogl_layout->setContentsMargins(0, 0, 0, 0);
ogl_layout->setSpacing(0);
ogl_out = new oGL_out(ui->frame_ogl, &level);
ogl_layout->addWidget(ogl_out);
ogl_out->show();
QObject::connect(ogl_out, &oGL_out::print_console,
this, &MainWindow::print_console);
QObject::connect(&level, &Level::print_console,
this, &MainWindow::print_console);
QObject::connect(this, &MainWindow::ogl_change_mode,
ogl_out, &oGL_out::ogl_change_mode);
change_mode(draw_clipping_mode);
print_console("Ready");
}
MainWindow::~MainWindow()
{
delete ui;
delete ogl_out;
delete ogl_layout;
outfile.close();
}
void MainWindow::on_drawButton_clicked()
{
change_mode (draw_mode);
}
void MainWindow::on_selectButton_clicked()
{
change_mode (sel_mode);
}
void MainWindow::on_unselButton_clicked()
{
change_mode (unsel_mode);
}
void MainWindow::on_clippingButton_clicked()
{
change_mode (draw_clipping_mode);
}
void MainWindow::on_setPosButton_clicked()
{
change_mode (set_pos_mode);
}
void MainWindow::print_console (const std::string &s)
{
ui->console->insertPlainText ("[");
ui->console->insertPlainText (QTime::currentTime().toString("h:m:s"));
ui->console->insertPlainText ("]> ");
ui->console->insertPlainText (QString::fromStdString (s));
ui->console->insertPlainText ("\n");
ui->console->ensureCursorVisible ();
}
void MainWindow::change_mode (edit_mode in_mode)
{
mode = in_mode;
std::string console = "switched to ";
switch (in_mode) {
case draw_mode:
console += "'draw'";
ui->text_tool->setText ("draw");
ui->drawButton->setDown (1);
ui->clippingButton->setDown (0);
ui->selectButton->setDown (0);
ui->unselButton->setDown (0);
ui->setPosButton->setDown (0);
break;
case draw_clipping_mode:
console += "'draw_clipping'";
ui->text_tool->setText ("clip");
ui->drawButton->setDown (0);
ui->clippingButton->setDown (1);
ui->selectButton->setDown (0);
ui->unselButton->setDown (0);
ui->setPosButton->setDown (0);
break;
case sel_mode:
console += "'select'";
ui->text_tool->setText ("select");
ui->drawButton->setDown (0);
ui->clippingButton->setDown (0);
ui->selectButton->setDown (1);
ui->unselButton->setDown (0);
ui->setPosButton->setDown (0);
break;
case unsel_mode:
console += "'unselect'";
ui->text_tool->setText ("unsel");
ui->drawButton->setDown (0);
ui->clippingButton->setDown (0);
ui->selectButton->setDown (0);
ui->unselButton->setDown (1);
ui->setPosButton->setDown (0);
break;
case set_pos_mode:
console += "'set player position'";
ui->text_tool->setText ("setPos");
ui->drawButton->setDown (0);
ui->clippingButton->setDown (0);
ui->selectButton->setDown (0);
ui->unselButton->setDown (0);
ui->setPosButton->setDown (1);
default:
break;
}
console += " mode";
#ifdef DEBUG_MISC
print_console(console);
#endif
emit ogl_change_mode(in_mode);
}
void MainWindow::on_actionSave_triggered()
{
if (outfile.is_open ()) {
outfile.close ();
outfile.open (outfilename, outfile.binary | outfile.out | outfile.trunc); //truncate
if (!outfile.is_open()) {
print_console ("failed to truncate file while saving");
return;
}
level.save_level (outfile);
}
else {
open_file_dialog (save);
}
}
void MainWindow::on_actionLoad_triggered ()
{
if (0){
//fixme::unsaved dialog
}
else {
open_file_dialog (load);
}
}
void MainWindow::on_actionDelete_wall_triggered ()
{
print_console ("sorry from v0.hz deletion is unsuported due to triangles. No money, but hold on, best wishes, good mood...");
//level.delete_wall ();
//ogl_out->update ();
}
void MainWindow::open_file_dialog (flag_saveload flag)
{
opendialog = new OpenDialog(this, flag);
QObject::connect(opendialog, &OpenDialog::filename_read,
this, &MainWindow::on_opendialog_finish);
opendialog->show();
}
void MainWindow::on_opendialog_finish(const std::string &filename, flag_saveload flag)
{
outfilename = filename;
std::string console;
console = "opening for ";
if (flag == save)
console += "save '";
else
console += "load '";
console += filename;
console += "' ";
if (!std::filesystem::exists(filename) && flag == load){ // if no file to load
console += "FAILED: check existing";
print_console (console);
return;
}
//file exists
if (flag == save) {
outfile.open(filename, outfile.binary | outfile.out | outfile.trunc);
if (!outfile.is_open()) {
print_console(console + "FAILED");
return;
}
print_console(console + "SUCCESS");
level.save_level (outfile);
}
if (flag == load) {
std::ifstream infile;
infile.open(filename, infile.binary | infile.in);
if (!infile.is_open()) {
print_console(console + "FAILED for read");
return;
}
if (level.load_level (infile)) {
infile.close ();
print_console (console + "SUCCESS for read");
print_console ("level loading failed!");
return;
}
infile.close ();
outfile.open(filename, outfile.binary | outfile.out | outfile.in);
if (!outfile.is_open()) {
print_console(console + "FAILED for write");
return;
}
print_console (console += "SUCCESS");
ogl_out->update ();
}
}
void MainWindow::on_trig_sideButton_clicked()
{
if (level.trig_side_mode == both_sides) {
level.trig_side_mode = one_side;
ui->trig_sideButton->setDown (1);
}
else {
level.trig_side_mode = both_sides;
ui->trig_sideButton->setDown (0);
}
}
void MainWindow::on_colorButoon_clicked()
{
QColorDialog *colordialog = new QColorDialog (this);
QObject::connect(colordialog, &QColorDialog::colorSelected,
this, &MainWindow::on_color_selected);
colordialog->show();
}
void MainWindow::on_color_selected (const QColor &newcolor)
{
level.wall_color[0] = newcolor.redF ();
level.wall_color[1] = newcolor.greenF ();
level.wall_color[2] = newcolor.blueF ();
level.cur_texture_index = -1;
ui->texture_label->clear ();
}
void MainWindow::on_actionRevert_chandes_triggered()
{
print_console ("ctrlz");
level.ctrl_z ();
ogl_out->update ();
}
void MainWindow::on_sel_textureButton_clicked()
{
std::string tex_filename = QFileDialog::getOpenFileName (this, "Open level", "./textures").toUtf8 ().constData ();
size_t last_slash_idx = tex_filename.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
{
tex_filename.erase(0, last_slash_idx + 1);
}
level.select_texture (tex_filename);
ui->texture_label->clear ();
ui->texture_label->setText (QString::fromStdString (tex_filename));
}
| 28.226766 | 129 | 0.613591 |
198d0718efc73c0de5a00ae19fa727d5b91c2511 | 466 | cpp | C++ | cpp1st/week08/taehwan/example_regex_error.cpp | th4inquiry/PentaDevs | aa379d24494a485ad5e7fdcc385c6ccfb02cf307 | [
"Apache-2.0"
] | 2 | 2022-03-10T10:18:23.000Z | 2022-03-16T15:37:22.000Z | cpp1st/week08/taehwan/example_regex_error.cpp | th4inquiry/PentaDevs | aa379d24494a485ad5e7fdcc385c6ccfb02cf307 | [
"Apache-2.0"
] | 8 | 2022-03-09T16:14:47.000Z | 2022-03-28T15:35:17.000Z | cpp1st/week08/taehwan/example_regex_error.cpp | th4inquiry/PentaDevs | aa379d24494a485ad5e7fdcc385c6ccfb02cf307 | [
"Apache-2.0"
] | 4 | 2022-03-08T00:22:29.000Z | 2022-03-12T13:22:43.000Z | ///
/// Copyright 2022 PentaDevs
/// Author: Taehwan Kim
/// Contents: Examples of regex_error (referenced from CppReference)
#include <regex>
#include <iostream>
int main()
{
try {
std::regex re("[a-b][a");
}
catch (const std::regex_error& e) {
std::cout << "regex_error caught: " << e.what() << '\n';
if (e.code() == std::regex_constants::error_brack) {
std::cout << "The code was error_brack\n";
}
}
} | 23.3 | 68 | 0.564378 |
198f28e392557799ceb6a4a19f49e5e08e2c58a7 | 7,134 | cpp | C++ | src/rc_utils.cpp | mjdousti/therminator | d706ab43ac97a4266ce19618b1e35d4e0245cd5b | [
"Xnet",
"X11",
"RSA-MD"
] | 3 | 2019-09-26T00:09:50.000Z | 2021-08-09T03:19:38.000Z | src/rc_utils.cpp | mjdousti/therminator | d706ab43ac97a4266ce19618b1e35d4e0245cd5b | [
"Xnet",
"X11",
"RSA-MD"
] | null | null | null | src/rc_utils.cpp | mjdousti/therminator | d706ab43ac97a4266ce19618b1e35d4e0245cd5b | [
"Xnet",
"X11",
"RSA-MD"
] | 5 | 2015-08-03T01:41:39.000Z | 2021-01-06T18:14:11.000Z | /**
*
* Copyright (C) 2021 Mohammad Javad Dousti, Qing Xie, Mahdi Nazemi,
* and Massoud Pedram. All rights reserved.
*
* Please refer to the LICENSE file for terms of use.
*
*/
#include "headers/rc_utils.hpp"
#include <omp.h>
VALUE RCutils::calcThermalConductivity(VALUE k, VALUE thickness,
VALUE area) {
ASSERT(thickness != 0, "The thickness of an element cannot be zero.");
return k * area / thickness;
}
VALUE RCutils::calcSubComponentCapacitance(SubComponent *sc) {
auto volume = sc->getLength() * sc->getWidth() * sc->getHeight();
if (volume == 0)
cout << sc->getName() << " has nil volume.\n";
else if (sc->getComponent()->getMaterial()->getSpecificHeat() == 0)
cout << sc->getName() << " has nil specific heat.\n";
else if (sc->getComponent()->getMaterial()->getDensity() == 0)
cout << sc->getName() << " has nil density.\n";
return C_FACTOR * sc->getComponent()->getMaterial()->getSpecificHeat() *
sc->getComponent()->getMaterial()->getDensity() * volume;
}
VALUE RCutils::calcAmbientResistance(VALUE h, VALUE area) {
return 1 / (h * area);
}
VALUE RCutils::overallParallelConductivity(VALUE k1, VALUE k2) {
return (k1 * k2) / (k1 + k2);
}
bool RCutils::touchesAirInXDir(SubComponent *sc, Device *device) {
if (utils::eq(sc->getX(), device->getX()) ||
utils::eq(sc->getX() + sc->getLength(),
device->getX() + device->getLength()))
return true;
else
return false;
}
bool RCutils::touchesAirInYDir(SubComponent *sc, Device *device) {
if (utils::eq(sc->getY(), device->getY()) ||
utils::eq(sc->getY() + sc->getWidth(),
device->getY() + device->getWidth())) {
return true;
} else {
return false;
}
}
bool RCutils::touchesAirFromTopBot(SubComponent *sc, Device *device) {
if (utils::eq(sc->getZ(), device->getZ()) ||
utils::eq(sc->getZ() + sc->getHeight(),
device->getZ() + device->getHeight()))
return true;
else
return false;
}
VALUE RCutils::calcConductanceToAmbient(SubComponent *sc, Device *device) {
VALUE commonArea;
VALUE t1 = 0.0;
VALUE k = 0.0;
VALUE Kx = 0.0, Ky = 0.0, Kz = 0.0, Rx, Ry, Rz;
// Unit: W/m^2/K; Source:
// <http://www.engineeringtoolbox.com/convective-heat-transfer-d_430.html>
VALUE h = 10 * 1.15;
if (touchesAirFromTopBot(sc, device)) { // Touches air from top or bottom
t1 = sc->getHeight() / 2;
commonArea = sc->getLength() * sc->getWidth();
k = sc->getComponent()->getMaterial()->getNormalConductivity();
Kz = RCutils::calcThermalConductivity(k, t1, commonArea);
Rz = RCutils::calcAmbientResistance(h, commonArea);
Kz = RCutils::overallParallelConductivity(Kz, 1 / Rz);
}
if (touchesAirInXDir(sc, device)) { // Touches air from the X side
t1 = sc->getLength() / 2;
commonArea = sc->getWidth() * sc->getHeight();
// Setting the k1 value to the proper value if the planar conductivity
// differs from the normal conductivity
if (sc->getComponent()->getMaterial()->hasPlanarConductivity()) {
k = sc->getComponent()->getMaterial()->getPlanarConductivity();
} else {
k = sc->getComponent()->getMaterial()->getNormalConductivity();
}
Kx = RCutils::calcThermalConductivity(k, t1, commonArea);
Rx = RCutils::calcAmbientResistance(h, commonArea);
Kx = RCutils::overallParallelConductivity(Kx, 1 / Rx);
}
if (touchesAirInYDir(sc, device)) { // Touches air from the Y side
t1 = sc->getWidth() / 2;
commonArea = sc->getLength() * sc->getHeight();
// Setting the k1 value to the proper value if the planar conductivity
// differs from the normal conductivity
if (sc->getComponent()->getMaterial()->hasPlanarConductivity()) {
k = sc->getComponent()->getMaterial()->getPlanarConductivity();
} else {
k = sc->getComponent()->getMaterial()->getNormalConductivity();
}
Ky = RCutils::calcThermalConductivity(k, t1, commonArea);
Ry = RCutils::calcAmbientResistance(h, commonArea);
Ky = RCutils::overallParallelConductivity(Ky, 1 / Ry);
}
return Kx + Ky + Kz;
}
VALUE RCutils::calcCommonConductance(SubComponent *sc1, SubComponent *sc2) {
VALUE commonArea;
VALUE t1 = 0, t2 = 0;
VALUE k1, k2;
// common area in the Y & Z planes
VALUE commonX, commonY, commonZ;
commonX =
min(sc1->getX() + sc1->getLength(), sc2->getX() + sc2->getLength()) -
max(sc1->getX(), sc2->getX());
commonY = min(sc1->getY() + sc1->getWidth(), sc2->getY() + sc2->getWidth()) -
max(sc1->getY(), sc2->getY());
commonZ =
min(sc1->getZ() + sc1->getHeight(), sc2->getZ() + sc2->getHeight()) -
max(sc1->getZ(), sc2->getZ());
if (commonZ > 0 && commonY > 0 &&
(utils::eq(sc1->getX() + sc1->getLength(), sc2->getX()) ||
utils::eq(sc2->getX() + sc2->getLength(), sc1->getX()))) {
commonArea = commonY * commonZ;
t1 = sc1->getLength() / 2;
t2 = sc2->getLength() / 2;
// using planar thermal conductivity if the material has different value for
// it
if (sc1->getComponent()->getMaterial()->hasPlanarConductivity()) {
k1 = sc1->getComponent()->getMaterial()->getPlanarConductivity();
} else {
k1 = sc1->getComponent()->getMaterial()->getNormalConductivity();
}
if (sc2->getComponent()->getMaterial()->hasPlanarConductivity()) {
k2 = sc2->getComponent()->getMaterial()->getPlanarConductivity();
} else {
k2 = sc2->getComponent()->getMaterial()->getNormalConductivity();
}
} else if (commonX > 0 && commonZ > 0 &&
(utils::eq(sc1->getY() + sc1->getWidth(), sc2->getY()) ||
utils::eq(sc2->getY() + sc2->getWidth(), sc1->getY()))) {
commonArea = commonX * commonZ;
t1 = sc1->getWidth() / 2;
t2 = sc2->getWidth() / 2;
// using planar thermal conductivity if the material has different value for
// it
if (sc1->getComponent()->getMaterial()->hasPlanarConductivity()) {
k1 = sc1->getComponent()->getMaterial()->getPlanarConductivity();
} else {
k1 = sc1->getComponent()->getMaterial()->getNormalConductivity();
}
if (sc2->getComponent()->getMaterial()->hasPlanarConductivity()) {
k2 = sc2->getComponent()->getMaterial()->getPlanarConductivity();
} else {
k2 = sc2->getComponent()->getMaterial()->getNormalConductivity();
}
} else if (commonX > 0 && commonY > 0 &&
(utils::eq(sc1->getZ() + sc1->getHeight(), sc2->getZ()) ||
utils::eq(sc2->getZ() + sc2->getHeight(), sc1->getZ()))) {
commonArea = commonX * commonY;
t1 = sc1->getHeight() / 2;
t2 = sc2->getHeight() / 2;
// using normal conductivity since it is in the vertical direction
k1 = sc1->getComponent()->getMaterial()->getNormalConductivity();
k2 = sc2->getComponent()->getMaterial()->getNormalConductivity();
} else {
commonArea = 0;
return 0;
}
auto K1 = RCutils::calcThermalConductivity(k1, t1, commonArea);
auto K2 = RCutils::calcThermalConductivity(k2, t2, commonArea);
return RCutils::overallParallelConductivity(K1, K2);
}
| 35.492537 | 80 | 0.624895 |
199034cd2c78220b6d27610356901fd7f2406bb0 | 1,685 | cpp | C++ | G53GRA.Framework/Code/Sky.cpp | baisebaoma/COMP3069CW | 731627a4d5d961435f3c4064e2c789db6a70423a | [
"MIT"
] | null | null | null | G53GRA.Framework/Code/Sky.cpp | baisebaoma/COMP3069CW | 731627a4d5d961435f3c4064e2c789db6a70423a | [
"MIT"
] | null | null | null | G53GRA.Framework/Code/Sky.cpp | baisebaoma/COMP3069CW | 731627a4d5d961435f3c4064e2c789db6a70423a | [
"MIT"
] | null | null | null | #include "Sky.hpp"
#include <iostream>
#include <cmath>
// TODO: 现在是全写在Sky里,到时候得分开成各个东西。(refactor)
#include <stdio.h>
#include <stdlib.h>
// MAKE SURE WE INITIALISE OUR VARIABLES
Sky::Sky() : keyframe(-1), animateTime(0.0), animateRotation(0.0), animateTranslation(0.0),
interpA(0.0), interpB(0.0), interpTime(0.0){}
Sky::Sky(const std::string& filename) : Sky()
{
texID = Scene::GetTexture(filename);
}
/// Update the Skys position in releation to delta time by use of mathematical
/// mechanics, eq SUVAT
void Sky::Update(const double& deltaTime)
{
// update the time and rotation steps
animateTime += static_cast<float>(deltaTime);
// animateRotation = animateTime*10;// animateRotation += static_cast<float>(deltaTime);
}
void Sky::drawPlane(GLfloat R, GLfloat G, GLfloat B, GLfloat size){
glColor3f(R, G, B);
glEnable(GL_TEXTURE_2D);
// Enable setting the colour of the material the cube is made from
// as well as the material for blending.
// glEnable(GL_COLOR_MATERIAL);
// Tell openGL which texture buffer to use
glBindTexture(GL_TEXTURE_2D, texID);
glBegin(GL_POLYGON);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1*size, 0, -1*size);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1*size, 0, 1*size);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(size, 0, size);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(size, 0, -1*size);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void Sky::Display(void){
glPushMatrix();
glRotatef(animateRotation,0,1,0);
// Sky
glPushMatrix();
glTranslatef(5, 0, 5);
drawPlane(0.7f, 0.7f, 0.7f, 20);
glPopMatrix();
glPopMatrix();
}
| 24.42029 | 95 | 0.659347 |
19963cc8374e09c591274312c5cda381f5d7e39d | 12,753 | cc | C++ | src/core/user_interface.cc | juliomarcelopicardo/Wolfy2D | 34cf5afca05e1f1cf57ad7899152efe09391ac7b | [
"MIT"
] | null | null | null | src/core/user_interface.cc | juliomarcelopicardo/Wolfy2D | 34cf5afca05e1f1cf57ad7899152efe09391ac7b | [
"MIT"
] | null | null | null | src/core/user_interface.cc | juliomarcelopicardo/Wolfy2D | 34cf5afca05e1f1cf57ad7899152efe09391ac7b | [
"MIT"
] | null | null | null | /** Copyright Julio Marcelo Picardo 2017-18, all rights reserved.
*
* @project Wolfy2D - Including JMP scripting language.
* @author Julio Marcelo Picardo <juliomarcelopicardo@gmail.com>
*/
#include "core/user_interface.h"
#include "GLFW/glfw3.h"
#include "imgui.h"
#include "imgui_dock.h"
#include "core/core.h"
#include <fstream>
namespace W2D {
/*******************************************************************************
*** Constructor And Destructor ***
*******************************************************************************/
UserInterface::UserInterface() {
top_bar_height_ = 0.0f;
bottom_bar_height_ = 30.0f;
save_mode_ = 0;
log_.set_active(true);
}
UserInterface::~UserInterface() {}
/*******************************************************************************
*** Public Methods ***
*******************************************************************************/
void UserInterface::init() {
setupInputKeys();
setupColors();
setupStyle();
setupUsersGuideText();
}
void UserInterface::update() {
updateTopBar();
updateEditorLayout();
updateBottomBar();
}
/*******************************************************************************
*** Private Methods ***
*******************************************************************************/
void UserInterface::setupColors() const {
ImVec4* colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.59f, 0.59f, 0.59f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 1.00f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f);
colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f);
colors[ImGuiCol_Button] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f);
colors[ImGuiCol_Header] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f);
colors[ImGuiCol_Separator] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.95f);
colors[ImGuiCol_CloseButton] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f);
colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f);
colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
}
void UserInterface::setupInputKeys() const {
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
}
void UserInterface::setupStyle() const {
ImGuiStyle& style = ImGui::GetStyle();
// Editor style
style.FrameRounding = 6.0f;
style.WindowRounding = 7.0f;
style.ChildRounding = 0.0f;
style.ScrollbarRounding = 9.0f;
style.GrabRounding = 6.0f;
style.PopupRounding = 16.0f;
style.WindowPadding = { 8.0f, 8.0f };
style.FramePadding = { 4.0f, 3.0f };
style.TouchExtraPadding = { 0.0f, 0.0f };
style.ItemSpacing = { 8.0f, 4.0f };
style.ItemInnerSpacing = { 4.0f, 4.0f };
style.IndentSpacing = 24.0f;
style.ScrollbarSize = 15.0f;
style.GrabMinSize = 12.0f;
style.WindowBorderSize = 1.0f;
style.ChildBorderSize = 1.0f;
style.PopupBorderSize = 1.0f;
style.FrameBorderSize = 0.0f;
style.WindowTitleAlign = { 0.0f, 0.5f };
style.ButtonTextAlign = { 0.5f, 0.5f };
}
void UserInterface::setupUsersGuideText() {
std::ifstream ug(kUsersGuideFilename);
std::string temp{ std::istreambuf_iterator<char>(ug), std::istreambuf_iterator<char>() };
users_guide_text_ = temp;
}
void UserInterface::updateTopBar() {
auto& core = Core::instance();
if (ImGui::BeginMainMenuBar()) {
top_bar_height_ = ImGui::GetWindowSize().y;
bottom_bar_height_ = top_bar_height_ + 8.0f;
if (ImGui::BeginMenu("Application")) {
if (ImGui::MenuItem("Quit", "ESC")) {
core.window_.is_opened_ = false;
}
showLastItemDescriptionTooltip("Exit application and closes window");
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Editor")) {
if (ImGui::MenuItem("Save Layout")) {
ImGui::SaveDock();
log_.AddLog_I("Editor layout style saved.");
}
showLastItemDescriptionTooltip("Saves the editor layout in a configuration file.\n"
"So next time that we execute the program, this last\n"
"configuration saved will be loaded.");
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void UserInterface::updateEditorLayout() {
auto& core = Core::instance();
ImVec2 editor_size = ImGui::GetIO().DisplaySize;
editor_size.y -= top_bar_height_ + bottom_bar_height_;
ImGui::SetWindowPos("UserInterface", { 0.0f, top_bar_height_ });
ImGui::SetWindowSize("UserInterface", editor_size);
const ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoMove;
if (ImGui::Begin("UserInterface", nullptr, window_flags)) {
// dock layout by hard-coded or .ini file
ImGui::BeginDockspace();
updateSceneDock();
updateScriptDock();
updateHierarchyDock();
updateUsersGuideDock();
/*
if (ImGui::BeginDock("EditorConfig")) {
ImGui::ShowStyleEditor();
}
ImGui::EndDock();
*/
if (ImGui::BeginDock("Log")) {
log_.Draw("Wolfy2D log");
}
ImGui::EndDock();
ImGui::EndDockspace();
}
ImGui::End();
}
void UserInterface::updateBottomBar() const {
const ImVec2 display_size = ImGui::GetIO().DisplaySize;
const ImGuiWindowFlags flags = ImGuiWindowFlags_NoBringToFrontOnFocus |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoSavedSettings;
ImGui::SetNextWindowPos({ 0.0f, display_size.y - bottom_bar_height_ }, ImGuiSetCond_Always);
ImGui::SetNextWindowSize({ display_size.x, bottom_bar_height_ }, ImGuiSetCond_Always);
ImGui::Begin("statusbar", nullptr, flags);
ImGui::TextColored({ 202,81,0,255 }, "Wolfy2D & JMP - A Scripting Language for Game Engines"); ImGui::SameLine();
ImGui::Text(" "); ImGui::SameLine();
ImGui::Text("Author: Julio Marcelo Picardo Pena"); ImGui::SameLine();
ImGui::Text(" "); ImGui::SameLine();
ImGui::Text("Contact: juliomarcelopicardo@gmail.com"); ImGui::SameLine();
ImGui::Text(" "); ImGui::SameLine();
ImGui::Text("BSc in Computer Science for Games - Sheffield Hallam University"); ImGui::SameLine();
ImGui::End();
}
void UserInterface::updateHierarchyDock() const {
if (ImGui::BeginDock("Scene Hierarchy")) {
auto& map = Core::instance().sprite_factory_;
for (const auto& pair : map) {
ImGui::PushID(&pair.second);
if (ImGui::TreeNode(pair.first.c_str())) {
auto& sprite = map[pair.first];
ImGui::Image((ImTextureID)sprite.textureID(), { 50.0f, 50.0f });
glm::vec2 temp = sprite.position();
if (ImGui::DragFloat2("Position", &temp.x)) { sprite.set_position(temp); }
temp = sprite.size();
if (ImGui::DragFloat2("Size", &temp.x)) { sprite.set_size(temp); }
temp.x = sprite.rotation();
if (ImGui::DragFloat("Rotation", &temp.x, 0.01f)) { sprite.set_rotation(temp.x); }
ImGui::TreePop();
}
ImGui::PopID();
}
}
ImGui::EndDock();
}
void UserInterface::updateScriptDock() {
auto& core = Core::instance();
std::string text = "Compiles and executes the existing code";
if (ImGui::BeginDock("JMP Scripting Language")) {
if (ImGui::Button("Compile")) {
log_.AddLog_I("Compiling and executing script...");
core.texture_factory_.clear();
core.sprite_factory_.clear();
core.machine_.reloadFromString(core.script_code_);
core.machine_.runFunction("Init()");
}
showLastItemDescriptionTooltip(text.c_str());
ImGui::SameLine();
if (ImGui::Button("Save")) {
if (save_mode_ == 0) {
ImGui::SetClipboardText(core.script_code_);
log_.AddLog_I("Script copied to clipboard.");
}
else {
std::ofstream file(kScriptFilename, std::ios_base::out);
if (file.is_open()) {
file << core.script_code_;
}
file.close();
// log
std::string info = "Script saved into file: \"";
info = info + kScriptFilename;
info = info + '\"';
log_.AddLog_I(info);
}
}
text = "Save mode: \nClipbard - Will copy the whole script text into the clipboard\nFile - Save and overwrite file \"";
text = text + kScriptFilename;
text = text + '\"';
showLastItemDescriptionTooltip(text.c_str());
ImGui::SameLine();
ImGui::Combo("##destination", (int*)&save_mode_, "Clipboard\0File\0");
ImGui::InputTextMultiline("", Core::instance().script_code_, SCRIPT_CODE_MAX_LENGTH, ImGui::GetContentRegionAvail());
}
ImGui::EndDock();
}
void UserInterface::updateUsersGuideDock() const {
if (ImGui::BeginDock("User's Guide")) {
ImGui::TextUnformatted(users_guide_text_.c_str());
}
ImGui::EndDock();
}
void UserInterface::updateSceneDock() const {
if (ImGui::BeginDock("Scene")) {
ImGui::Image((ImTextureID)Core::instance().window_.frame_buffer_.texture(), ImGui::GetContentRegionAvail(), ImVec2(0, 1), ImVec2(1, 0));
}
ImGui::EndDock();
}
void UserInterface::showLastItemDescriptionTooltip(const char* description) const {
if (ImGui::IsItemHovered()) {
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(description);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
}; /* W2D */
| 35.035714 | 140 | 0.632165 |
199b46ae2e5d531d246a12762b8d9930fa3aafba | 7,620 | cpp | C++ | Data Structures/Heaps/Fibonacci Heap.cpp | Rand0mUsername/Algorithms | 05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0 | [
"MIT"
] | 2 | 2020-01-10T14:12:03.000Z | 2020-05-28T19:12:21.000Z | Data Structures/Heaps/Fibonacci Heap.cpp | Rand0mUsername/algorithms | 05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0 | [
"MIT"
] | null | null | null | Data Structures/Heaps/Fibonacci Heap.cpp | Rand0mUsername/algorithms | 05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0 | [
"MIT"
] | 1 | 2022-01-11T03:14:48.000Z | 2022-01-11T03:14:48.000Z | // RandomUsername (Nikola Jovanovic)
// Fibonacci Heap
// Source: CLRS, Third Edition
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
struct Node {
Node* left;
Node* right;
Node* parent;
Node* first_child;
int key;
int degree;
bool marked;
explicit Node(int key) {
this -> key = key;
this -> degree = 0;
this -> parent = this -> first_child = NULL;
this -> left = this -> right = this;
this -> marked = false;
}
};
class FibonacciHeap {
public:
FibonacciHeap();
Node* FindMin();
void DeleteMin();
void Insert(Node* curr);
void DecreaseKey(Node* curr, int new_key);
void Merge(FibonacciHeap* h);
int GetSize();
void Draw(std::string name);
private:
void LinkRootNodes(Node* top, Node* bottom);
void MakeRootNode(Node* curr);
void PrintToDot(Node* curr, std::ofstream& dot_file);
Node* min_node;
int size;
};
FibonacciHeap::FibonacciHeap() {
size = 0;
min_node = NULL;
}
Node* FibonacciHeap::FindMin() {
return min_node;
}
void FibonacciHeap::DeleteMin() {
if (size == 0) {
return;
}
if (size == 1) {
delete min_node;
min_node = NULL;
size = 0;
return;
}
Node* child = min_node -> first_child;
int deg = min_node -> degree;
for (int i = 0; i < deg; i++) {
Node* next = child -> right;
MakeRootNode(child);
child = next;
}
int D = 2 * ceil(log2(size));
Node* tmp[D];
for (int i = 0; i < D; i++) {
tmp[i] = NULL;
}
Node* curr = min_node -> right;
while (curr != min_node) {
Node* next = curr -> right;
int deg = curr -> degree;
while (tmp[deg] != NULL) {
Node* other = tmp[deg];
if (curr -> key > other -> key) {
std::swap(curr, other);
}
LinkRootNodes(curr, other);
tmp[deg++] = NULL;
}
tmp[deg] = curr;
curr = next;
}
delete min_node;
// Rebuild the heap
size--;
Node* first;
Node* last;
first = last = min_node = NULL;
for (int i = 0; i < D; i++) {
if (tmp[i] != NULL) {
if (first == NULL) {
min_node = first = last = tmp[i];
} else {
if (tmp[i] -> key < min_node -> key) {
min_node = tmp[i];
}
last -> right = tmp[i];
tmp[i] -> left = last;
last = tmp[i];
}
}
}
if (first != NULL) {
last -> right = first;
first -> left = last;
}
}
void FibonacciHeap::Insert(Node* curr) {
FibonacciHeap* unit_heap = new FibonacciHeap();
unit_heap -> min_node = curr;
unit_heap -> size = 1;
Merge(unit_heap);
delete unit_heap;
}
void FibonacciHeap::DecreaseKey(Node* curr, int new_key) {
curr -> key = new_key;
Node* parent = curr -> parent;
if (parent != NULL && curr -> key < parent -> key) {
// Cut this child and update min node
MakeRootNode(curr);
curr -> marked = false;
if (curr -> key < min_node -> key) {
min_node = curr;
}
// Do a cascading cut
curr = parent;
while (curr != NULL && curr -> marked) {
parent = curr -> parent;
MakeRootNode(curr);
curr -> marked = false;
curr = parent;
}
if (curr != NULL && curr -> parent != NULL) {
curr -> marked = true;
}
} else if (parent == NULL && curr -> key < min_node -> key) {
min_node = curr;
}
}
void FibonacciHeap::Merge(FibonacciHeap* other) {
if (other -> size == 0) {
return;
}
if (this -> size == 0) {
this -> min_node = other -> min_node;
} else {
Node* this_right = this -> min_node -> right;
Node* other_left = other -> min_node -> left;
this -> min_node -> right = other -> min_node;
other -> min_node -> left = this -> min_node;
this_right -> left = other_left;
other_left -> right = this_right;
}
this -> size += other -> size;
}
int FibonacciHeap::GetSize() {
return size;
}
// Visualizes the heap using GraphViz.
void FibonacciHeap::Draw(std::string name) {
std::ofstream dot_file;
dot_file.open(name + ".dot");
dot_file << "digraph{\n";
Node* root = min_node;
if (root != NULL) {
do {
PrintToDot(root, dot_file);
root = root -> right;
} while (root != min_node);
}
dot_file << "}\n";
dot_file.close();
std::string command = "dot -Tpng " + name + ".dot -o " + name + ".png";
system(command.c_str());
}
void FibonacciHeap::LinkRootNodes(Node* top, Node* bottom) {
bottom -> left -> right = bottom -> right;
bottom -> right -> left = bottom -> left;
Node* child = top -> first_child;
bottom -> parent = top;
top -> first_child = bottom;
bottom -> left = bottom -> right = NULL;
if (child != NULL) {
bottom -> right = child;
child -> left = bottom;
}
top -> degree++;
top -> marked = false;
}
void FibonacciHeap::MakeRootNode(Node* curr) {
if (curr -> left != NULL) {
curr -> left -> right = curr -> right;
}
if (curr -> right != NULL) {
curr -> right -> left = curr -> left;
}
if (curr -> parent != NULL) {
if (curr -> parent -> first_child == curr) {
curr -> parent -> first_child = curr -> right;
}
curr -> parent -> degree--;
}
curr -> parent = NULL;
Node* min_right = min_node -> right;
curr -> right = min_right;
min_right -> left = curr;
curr -> left = min_node;
min_node -> right = curr;
}
void FibonacciHeap::PrintToDot(Node* curr, std::ofstream& dot_file) {
if (curr == NULL) {
return;
}
dot_file << curr -> key << "[label=\"" << curr -> key << "\"";
if (curr -> marked) {
dot_file << " color=red fontcolor=red";
}
dot_file << "];\n";
Node* child = curr -> first_child;
if (child == NULL) {
dot_file << "null_l_" << curr -> key << "[shape=point];\n";
dot_file << curr -> key << " -> " << "null_l_" << curr -> key << "\n";
} else {
while (child != NULL) {
PrintToDot(child, dot_file);
dot_file << curr -> key << " -> " << child -> key << "\n";
child = child -> right;
}
}
}
int main() {
FibonacciHeap* heap = new FibonacciHeap();
heap -> Insert(new Node(4));
heap -> DeleteMin();
heap -> DeleteMin();
heap -> Insert(new Node(4));
heap -> Insert(new Node(5));
heap -> Insert(new Node(16));
heap -> Insert(new Node(26));
heap -> Insert(new Node(7));
Node* n11 = new Node(11); heap -> Insert(n11);
Node* n17 = new Node(17); heap -> Insert(n17);
Node* n12 = new Node(12); heap -> Insert(n12);
heap -> Insert(new Node(10));
Node* n99 = new Node(99); heap -> Insert(n99);
heap -> Insert(new Node(33));
heap -> Insert(new Node(95));
heap -> Insert(new Node(14));
heap -> Insert(new Node(6));
heap -> Insert(new Node(9));
heap -> Insert(new Node(96));
heap -> Insert(new Node(19));
heap -> Insert(new Node(8));
heap -> Draw("fibheap_full");
heap -> DeleteMin();
std::cout << "Size: " << heap -> GetSize();
Node* min_node = heap -> FindMin();
if (min_node != NULL) {
std::cout << " Min: " << min_node -> key << std::endl;
} else {
std::cout << " Empty" << std::endl;
}
heap -> Draw("fibheap_del");
heap -> DeleteMin();
std::cout << "Size: " << heap -> GetSize();
min_node = heap -> FindMin();
if (min_node != NULL) {
std::cout << " Min: " << min_node -> key << std::endl;
} else {
std::cout << " Empty" << std::endl;
}
heap -> Draw("fibheap_del2");
heap -> DecreaseKey(n11, 3);
heap -> DecreaseKey(n99, 0);
heap -> DecreaseKey(n17, 2);
heap -> DecreaseKey(n12, 1); // Cascade
heap -> Draw("fibheap_dec");
heap -> DeleteMin();
heap -> DeleteMin();
heap -> DeleteMin();
heap -> DeleteMin();
heap -> DeleteMin();
heap -> Draw("fibheap_end");
return 0;
}
| 25.065789 | 74 | 0.56168 |
19a273935ae0662816c7a68f7d39f79db444aea3 | 7,301 | hpp | C++ | src/byl_avl_tree.hpp | superboy0712/toy_template_library | 4b62a52bf0789472807206997253b0cc7cdd8102 | [
"MIT"
] | null | null | null | src/byl_avl_tree.hpp | superboy0712/toy_template_library | 4b62a52bf0789472807206997253b0cc7cdd8102 | [
"MIT"
] | null | null | null | src/byl_avl_tree.hpp | superboy0712/toy_template_library | 4b62a52bf0789472807206997253b0cc7cdd8102 | [
"MIT"
] | null | null | null | //
// Created by yulong on 3/31/17.
//
#ifndef BYL_TEMPLATE_LIBRARY_AVL_TREE_H
#define BYL_TEMPLATE_LIBRARY_AVL_TREE_H
#include "byl_bst.hpp"
#include <cstddef>
namespace byl {
template<typename T> struct avl_tree;
template<typename T>
struct avl_node {
typedef T value_type;
typedef size_t size_type;;
friend struct avl_tree<T>;
typedef avl_node * node_ptr;
node_ptr left, right, parent;
T m_data;
int height;
size_type n_size;
avl_node(const value_type& v = value_type(), int h = 0)
: left(NULL), right(NULL), parent(NULL)
, m_data(v), height(h), n_size(1) {}
};
template<typename T>
struct avl_tree : public bst<T, avl_node> {
typedef T value_type;
typedef bst<T, avl_node> base_tree;
typedef avl_node<T> node_type;
typedef avl_node<T> *node_pointer;
typedef typename bst<T, avl_node>::size_type size_type;
inline int max(int a, int b) {
return (a > b) ? a : b;
}
inline int height(node_pointer p) {
return p? p->height : (-1);
}
inline void update_height(node_pointer p) {
p->height = 1 + max(height(p->left), height(p->right));
}
void update_height_above(node_pointer p) {
if(!p) return;
while(p->parent) {
update_height(p->parent);
p = p->parent;
}
}
inline int bal_fac(const node_pointer p) {
return (height(p->left) - height(p->right));
}
inline bool is_balenced(const node_pointer p) {
int fac = bal_fac(p);
return (-2 < fac && fac < 2);
}
inline node_pointer connect34(
node_pointer a, node_pointer b, node_pointer c,
node_pointer t0, node_pointer t1, node_pointer t2, node_pointer t3) {
a->left = t0; if(t0) t0->parent = a;
a->right = t1; if(t1) t1->parent = a; update_height(a); update_size(a);
c->left = t2; if(t2) t2->parent = c;
c->right = t3; if(t3) t3->parent = c; update_height(c); update_size(c);
b->left = a; a->parent = b;
b->right = c; c->parent = b; update_height(b); update_size(b);
return b;
}
inline bool is_lchild(node_pointer p) {
return (p->parent->left == p);
}
inline bool is_rchild(node_pointer p) {
return (p->parent->right == p);
}
inline node_pointer rebalenced_at(node_pointer g, node_pointer p, node_pointer v) {
// assert(v);
if (is_lchild(p)) {
if(is_lchild(v)) {
p->parent = g->parent;
return connect34(v, p, g, v->left, v->right, p->right, g->right);
} else {
v->parent = g->parent;
return connect34(p, v, g, p->left, v->left, v->right, g->right);
}
} else {
if(is_rchild(v)) {
p->parent = g->parent;
return connect34(g, p, v, g->left, p->left, v->left, v->right);
} else {
v->parent = g->parent;
return connect34(g, v, p, g->left, v->left, v->right, p->right);
}
}
}
inline node_pointer *from_parent_to(node_pointer p) {
return &((p == this->root()) ? this->m_dummy_super_root.left
: ( (is_lchild(p)) ? p->parent->left : p->parent->right) );
}
inline size_type size_of_node(node_pointer p) {
return p ? p->n_size : 0;
}
inline void update_size(node_pointer p) {
if(!p) return;
p->n_size = size_of_node(p->left) + size_of_node(p->right) + 1;
}
inline void update_size_above(node_pointer p) {
while (p->parent) {
update_size(p->parent);
p = p->parent;
}
}
node_pointer insert(const value_type& val) {
node_pointer *t, p;
t = this->search(val, &p);
if(*t) {
(*t)->m_data = val;
return *t;
}
*t = new node_type(val); (*t)->parent = p; this->m_size++;
update_height(p);
update_size(p);
update_size_above(p);
node_pointer v = *t;
for (node_pointer g = p->parent; g && g!=&(this->m_dummy_super_root); v = p, p = g, g = g->parent) {
if (!is_balenced(g)) {
*from_parent_to(g) = rebalenced_at(g, p, v);
break;
} else {
update_height(g);
}
}
return *t;
}
inline node_pointer taller_child(node_pointer p) {
return (
(height(p->left) > height(p->right)) ?
p->left : (
(height(p->left) < height(p->right)) ? p->right :
(is_lchild(p) ? p->left : p->right)));
}
bool remove(const value_type& val) {
node_pointer *r, g;
r = this->search(val, &g);
if(!*r) return false;
this->remove_at(r, &g);
update_size(g);
update_size_above(g);
while (g && g!=&(this->m_dummy_super_root)) {
update_height(g);
if (!is_balenced(g)) {
node_pointer p = taller_child(g);
node_pointer v = taller_child(p);
*from_parent_to(g) = rebalenced_at(g, p, v);
}
g = g->parent;
}
return true;
}
bool remove_by_rank(size_type rank) {
node_pointer *r, g;
r = this->select(rank, &g);
if(!r || !*r) return false;
this->remove_at(r, &g);
update_size(g);
update_size_above(g);
while (g && g!=&(this->m_dummy_super_root)) {
update_height(g);
if (!is_balenced(g)) {
node_pointer p = taller_child(g);
node_pointer v = taller_child(p);
*from_parent_to(g) = rebalenced_at(g, p, v);
}
g = g->parent;
}
return true;
}
inline node_pointer *select(size_type rank, node_pointer *parent) {
if(rank >= this->m_size) return NULL;
*parent = &(this->m_dummy_super_root);
node_pointer* ret = &(this->m_dummy_super_root.left);
size_t r = size_of_node((*ret)->left);
while(r != rank) {
if (rank < r) {
*parent = *ret;
ret = &(*ret)->left;
r = r - size_of_node((*ret)->right) - 1;
} else if (rank > r) {
*parent = *ret;
ret = &(*ret)->right;
r = r + size_of_node((*ret)->left) + 1;
}
}
return ret;
}
size_type rank(value_type &val) {
node_pointer p = this->root();
size_t r = size_of_node(p->left);
while(p) {
if (p->m_data > val) {
p = p->left;
r = r - size_of_node(p? p->right : NULL) - 1;
} else if (p->m_data < val) {
p = p->right;
r = r + size_of_node(p? p->left : NULL) + 1;
} else {
return r;
}
}
return r; // if r = -1 or size, then seach failed
}
const value_type& operator [](size_type rank) {
node_pointer *q, p;
q = select(rank, &p);
return (*q)->m_data;
}
};
}//namespace btl
#endif //BYL_TEMPLATE_LIBRARY_AVL_TREE_H
| 31.200855 | 108 | 0.506506 |
19ac69b353212e5cb772c9447e2512f70e77bf4a | 243 | cpp | C++ | 24_qstackedwidget/src/pessoa.cpp | josersi/qt_cppmaster | 62e8499c1f17463bd4209ac61ae4fc8d49da69e4 | [
"MIT"
] | 1 | 2018-09-01T05:57:29.000Z | 2018-09-01T05:57:29.000Z | 24_qstackedwidget/src/pessoa.cpp | josersi/qt_cppmaster | 62e8499c1f17463bd4209ac61ae4fc8d49da69e4 | [
"MIT"
] | null | null | null | 24_qstackedwidget/src/pessoa.cpp | josersi/qt_cppmaster | 62e8499c1f17463bd4209ac61ae4fc8d49da69e4 | [
"MIT"
] | 1 | 2019-09-26T01:45:10.000Z | 2019-09-26T01:45:10.000Z | #include "pessoa.h"
Pessoa::Pessoa(QObject *parent) : QObject(parent)
{
}
QString Pessoa::getNome() const
{
return nome;
}
void Pessoa::setNome(const QString &value)
{
nome = value;
emit nomeChanged(nome);
}
| 12.789474 | 50 | 0.613169 |
30abe44edfcc28fa640af9703d47dcf0c8fc614e | 600 | cpp | C++ | 3D-TV/PerfTimer.cpp | TheByteKitchen/Kinect_client_server | 47bd066199f5b112b476e4d34ad333a535baa314 | [
"MS-PL"
] | null | null | null | 3D-TV/PerfTimer.cpp | TheByteKitchen/Kinect_client_server | 47bd066199f5b112b476e4d34ad333a535baa314 | [
"MS-PL"
] | null | null | null | 3D-TV/PerfTimer.cpp | TheByteKitchen/Kinect_client_server | 47bd066199f5b112b476e4d34ad333a535baa314 | [
"MS-PL"
] | null | null | null | //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "PerfTimer.h"
// Initialize the resolution of the timer
LARGE_INTEGER PerfTimer::m_freq = \
(QueryPerformanceFrequency(&PerfTimer::m_freq), PerfTimer::m_freq);
// Calculate the overhead of the timer
LONGLONG PerfTimer::m_overhead = PerfTimer::GetOverhead(); | 37.5 | 77 | 0.743333 |
30acddda17fe21c4369a615ea1200d62f0b10f6d | 2,174 | cpp | C++ | Engine/Platforms/Public/Tools/GPUThreadHelper.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | Engine/Platforms/Public/Tools/GPUThreadHelper.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | Engine/Platforms/Public/Tools/GPUThreadHelper.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "Engine/Platforms/Public/Tools/GPUThreadHelper.h"
namespace Engine
{
namespace PlatformTools
{
/*
=================================================
FindGraphicsThread
=================================================
*/
ModulePtr GPUThreadHelper::FindGraphicsThread (GlobalSystemsRef gs)
{
using MsgList_t = ModuleMsg::MessageListFrom<
GpuMsg::ThreadBeginFrame,
GpuMsg::ThreadEndFrame,
GpuMsg::SubmitCommands,
GpuMsg::GetDeviceInfo,
GpuMsg::GetGraphicsModules,
GpuMsg::GetGraphicsSettings
>;
using EventList_t = ModuleMsg::MessageListFrom<
GpuMsg::DeviceCreated,
GpuMsg::DeviceBeforeDestroy
>;
return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >();
}
/*
=================================================
FindComputeThread
=================================================
*/
ModulePtr GPUThreadHelper::FindComputeThread (GlobalSystemsRef gs)
{
using MsgList_t = ModuleMsg::MessageListFrom<
GpuMsg::SubmitCommands,
GpuMsg::GetDeviceInfo,
GpuMsg::GetGraphicsModules,
GpuMsg::GetComputeSettings
>;
using EventList_t = ModuleMsg::MessageListFrom<
GpuMsg::DeviceCreated,
GpuMsg::DeviceBeforeDestroy
>;
return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >();
}
/*
=================================================
FindVRThread
=================================================
*/
ModulePtr GPUThreadHelper::FindVRThread (GlobalSystemsRef gs)
{
using MsgList_t = ModuleMsg::MessageListFrom<
GpuMsg::ThreadBeginVRFrame,
GpuMsg::ThreadEndVRFrame,
GpuMsg::SubmitCommands,
GpuMsg::GetVRDeviceInfo,
GpuMsg::GetGraphicsModules,
GpuMsg::GetGraphicsSettings
>;
using EventList_t = ModuleMsg::MessageListFrom<
GpuMsg::DeviceCreated,
GpuMsg::DeviceBeforeDestroy
>;
return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >();
}
} // PlatformTools
} // Engine
| 27.175 | 77 | 0.589236 |
30b4715024c575a744b186b209157ca94722c5af | 456 | cpp | C++ | cpp/inifile/test.cpp | 0382/util | b8163f52352341ae7872d95b7f18542f17a94633 | [
"MIT"
] | null | null | null | cpp/inifile/test.cpp | 0382/util | b8163f52352341ae7872d95b7f18542f17a94633 | [
"MIT"
] | null | null | null | cpp/inifile/test.cpp | 0382/util | b8163f52352341ae7872d95b7f18542f17a94633 | [
"MIT"
] | null | null | null | #include "inifile.hpp"
int main()
{
auto ini = util::inifile("test.ini");
if (!ini.good())
{
std::cerr << ini.error() << std::endl;
exit(-1);
}
std::cout << "default section: name = " << ini.get_string("name") << '\n';
ini.set_string("set", "string");
std::cout << "section1: test = " << ini.section("section1").get_int("test") << '\n';
std::cout << "\nshow all data:\n--------------\n";
ini.show();
} | 25.333333 | 88 | 0.497807 |
30bef042a86014e87ff42405dc8b3b8c1eb84f9c | 974 | hpp | C++ | admin/dcpromo/exe/configurednsclientpage.hpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/dcpromo/exe/configurednsclientpage.hpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/dcpromo/exe/configurednsclientpage.hpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // Copyright (C) 1997 Microsoft Corporation
//
// dns client configuration page
//
// 12-22-97 sburns
#ifndef CONFIGUREDNSCLIENTPAGE_HPP_INCLUDED
#define CONFIGUREDNSCLIENTPAGE_HPP_INCLUDED
class ConfigureDnsClientPage : public DCPromoWizardPage
{
public:
ConfigureDnsClientPage();
protected:
virtual ~ConfigureDnsClientPage();
// Dialog overrides
virtual
bool
OnNotify(
HWND windowFrom,
UINT_PTR controlIDFrom,
UINT code,
LPARAM lParam);
virtual
void
OnInit();
// PropertyPage overrides
virtual
bool
OnSetActive();
// DCPromoWizardPage overrides
virtual
int
Validate();
private:
// not defined; no copying allowed
ConfigureDnsClientPage(const ConfigureDnsClientPage&);
const ConfigureDnsClientPage& operator=(const ConfigureDnsClientPage&);
};
#endif // CONFIGUREDNSCLIENTPAGE_HPP_INCLUDED | 16.508475 | 75 | 0.664271 |
30c2cccfa2f3c1e5f3de472b340de4aafaedccca | 22 | cpp | C++ | src/mjast_and.cpp | lucasalj/mjcompiler | 4404e4ce25f009c60d9f93d0118f33bb1d56b2cf | [
"MIT"
] | null | null | null | src/mjast_and.cpp | lucasalj/mjcompiler | 4404e4ce25f009c60d9f93d0118f33bb1d56b2cf | [
"MIT"
] | null | null | null | src/mjast_and.cpp | lucasalj/mjcompiler | 4404e4ce25f009c60d9f93d0118f33bb1d56b2cf | [
"MIT"
] | null | null | null | #include <mjast_and.h> | 22 | 22 | 0.772727 |
30c8bdffa3d58ca082d8be23f1bc689bfba89220 | 412 | cpp | C++ | compiler/crtp/foo/crtp.cpp | lijiansong/deep-learning | 7c78061775e47785dfcc4088e93dc4368d16334f | [
"WTFPL"
] | 4 | 2018-05-19T00:55:36.000Z | 2020-08-30T23:31:26.000Z | compiler/crtp/foo/crtp.cpp | lijiansong/deep-learning | 7c78061775e47785dfcc4088e93dc4368d16334f | [
"WTFPL"
] | null | null | null | compiler/crtp/foo/crtp.cpp | lijiansong/deep-learning | 7c78061775e47785dfcc4088e93dc4368d16334f | [
"WTFPL"
] | null | null | null | // Curiously Recurring Template Pattern
// static polymorphism
#include <iostream>
using namespace std;
template <typename Child>
struct Base {
void interface() {
static_cast<Child *>(this)->implementation();
}
};
struct Derived : Base<Derived> {
void implementation() {
cerr << "Derived implementation\n";
}
};
int main() {
Derived d;
d.interface(); // Prints "Derived implementation"
}
| 17.166667 | 51 | 0.682039 |
30cf79f21e82a1d1ae95a5e7baa57f4321c29b03 | 17,711 | cpp | C++ | src/ringmesh/geomodel/tools/mesh_quality.cpp | ringmesh/RINGMesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 74 | 2017-10-26T15:40:23.000Z | 2022-03-22T09:27:39.000Z | src/ringmesh/geomodel/tools/mesh_quality.cpp | ringmesh/ringmesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 45 | 2017-10-26T15:54:01.000Z | 2021-01-27T10:16:34.000Z | src/ringmesh/geomodel/tools/mesh_quality.cpp | ringmesh/ringmesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 17 | 2018-03-27T11:31:24.000Z | 2022-03-06T18:41:52.000Z | /*
* Copyright (c) 2012-2018, Association Scientifique pour la Geologie et ses
* Applications (ASGA). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of ASGA 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 ASGA 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.
*
* http://www.ring-team.org
*
* RING Project
* Ecole Nationale Superieure de Geologie - GeoRessources
* 2 Rue du Doyen Marcel Roubault - TSA 70605
* 54518 VANDOEUVRE-LES-NANCY
* FRANCE
*/
#include <algorithm>
#include <geogram/basic/attributes.h>
#include <ringmesh/geomodel/core/geomodel.h>
#include <ringmesh/geomodel/core/geomodel_mesh_entity.h>
#include <ringmesh/geomodel/tools/mesh_quality.h>
#include <ringmesh/mesh/mesh_builder.h>
#include <ringmesh/mesh/mesh_index.h>
#include <ringmesh/mesh/volume_mesh.h>
/*!
* @author Benjamin Chauvin
* This code is inspired from
* http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html
*/
namespace
{
using namespace RINGMesh;
/*!
* @brief Computes the radius of the tetrahedron insphere.
*
* The tetrahedron insphere is the sphere inside the tetrahedron which
* is tangent to each tetrahedron facet.
*
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @return the radius of the tetrahedron insphere.
*/
double tetra_insphere_radius(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 );
double A1 = GEO::Geom::triangle_area( v0, v1, v2 );
double A2 = GEO::Geom::triangle_area( v1, v2, v3 );
double A3 = GEO::Geom::triangle_area( v2, v3, v0 );
double A4 = GEO::Geom::triangle_area( v3, v0, v1 );
ringmesh_assert( A1 + A2 + A3 + A4 > global_epsilon );
return ( 3 * tet_volume ) / ( A1 + A2 + A3 + A4 );
}
/*!
* @brief Tetrahedron quality based on the insphere and circumsphere radii.
*
* The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and
* 1 to a good tetrahedron (equilaterality).
* For more information, see
* <a
* href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html">
* TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a>
*
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @return 3 * the insphere radius divided by the circumsphere radius.
*/
double tet_quality_insphere_radius_by_circumsphere_radius(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
const vec3 tetra_circum_center =
GEO::Geom::tetra_circum_center( v0, v1, v2, v3 );
const double tetra_circum_radius =
vec3( tetra_circum_center - v0 ).length();
ringmesh_assert( std::abs( tetra_circum_radius
- ( tetra_circum_center - v1 ).length() )
< global_epsilon );
ringmesh_assert( std::abs( tetra_circum_radius
- ( tetra_circum_center - v2 ).length() )
< global_epsilon );
ringmesh_assert( std::abs( tetra_circum_radius
- ( tetra_circum_center - v3 ).length() )
< global_epsilon );
// insphere computation
double in_radius = tetra_insphere_radius( v0, v1, v2, v3 );
return 3. * in_radius / tetra_circum_radius;
}
/*!
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @return the maximum of the tetrahedron edge length.
*/
double max_tet_edge_length(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
std::initializer_list< double > edge_length{ ( v1 - v0 ).length(),
( v2 - v0 ).length(), ( v3 - v0 ).length(), ( v2 - v1 ).length(),
( v3 - v1 ).length(), ( v3 - v2 ).length() };
return std::max( edge_length );
}
/*!
* @brief Tetrahedron quality based on the insphere radius and the maximum
* edge length.
*
* The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and
* 1 to a good tetrahedron (equilaterality).
* For more information see
* Du, Q., and D. Wang, 2005,
* The optimal centroidal Voronoi tessellations and the gersho's conjecture
* in the three-dimensional space,
* Computers & Mathematics with Applications, v. 49, no. 9, p. 1355-1373,
* <a href="http://doi.org/10.1016/j.camwa.2004.12.008">doi</a>,
* <a
* href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html">
* TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a>
*
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @return 2 * sqrt( 6 ) * the insphere radius divided by the maximum of the
* tetrhedron edge length.
*/
double tet_quality_insphere_radius_by_max_edge_length(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
double in_radius = tetra_insphere_radius( v0, v1, v2, v3 );
double edge_length = max_tet_edge_length( v0, v1, v2, v3 );
return 2 * std::sqrt( 6. ) * in_radius / edge_length;
}
/*!
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @return the sum of the square tetrahedron edge length.
*/
double sum_square_edge_length(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
double l1 = vec3( v1 - v0 ).length2();
double l2 = vec3( v2 - v0 ).length2();
double l3 = vec3( v3 - v0 ).length2();
double l4 = vec3( v2 - v1 ).length2();
double l5 = vec3( v3 - v1 ).length2();
double l6 = vec3( v3 - v2 ).length2();
return l1 + l2 + l3 + l4 + l5 + l6;
}
/*!
* @brief Tetrahedron quality based on the tetrahedron volume and
* the sum of the square edges.
*
* The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and
* 1 to a good tetrahedron (equilaterality).
* For more information see
* <a
* href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html">
* TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a>
*
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
*
* @return 12. * (3 * volume)^(2/3) / sum of the square edge.
*/
double tet_quality_volume_by_sum_square_edges(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
const double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 );
double sum_square_edge = sum_square_edge_length( v0, v1, v2, v3 );
ringmesh_assert( sum_square_edge > global_epsilon );
return 12. * std::pow( 3. * tet_volume, 2. / 3. ) / sum_square_edge;
}
/*!
* @bried Computes the sinus of the half solid angle relatively to a
* tetrahedron vertex.
* @param[in] v0 first vertex of the tetrahedron. The solid angle is
* computed
* relatively to this vertex.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @return the sinus of the half solid angle on the vertex \p v0.
*/
double sin_half_solid_angle(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 );
double l01 = ( v1 - v0 ).length();
double l02 = ( v2 - v0 ).length();
double l03 = ( v3 - v0 ).length();
double l12 = ( v2 - v1 ).length();
double l13 = ( v3 - v1 ).length();
double l23 = ( v3 - v2 ).length();
double denominator = ( l01 + l02 + l12 ) * ( l01 + l02 - l12 )
* ( l02 + l03 + l23 ) * ( l02 + l03 - l23 )
* ( l03 + l01 + l13 ) * ( l03 + l01 - l13 );
ringmesh_assert( denominator > global_epsilon_sq );
denominator = std::sqrt( denominator );
return 12 * tet_volume / denominator;
}
/*!
* @brief Tetrahedron quality based on the solid angles.
*
* This metrics is based on the sinus of the half solid angle on each
* vertex. It was shown on the literature that the minimum of the four
* values provides an estimate of the tetrahedron quality.
* For more information, see:
* <a
* href="http://people.eecs.berkeley.edu/~jrs/meshpapers/robnotes.pdf">robnotes.pdf</a>
* p15,
* Liu, A., and B. Joe, 1994, Relationship between tetrahedron shape
* measures,
* BIT, v. 34, no. 2, p. 268-287, <a
* href="http://doi.org/10.1007/BF01955874">doi</a> and
* <a
* href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html">
* TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a>
*
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
*
* @return 1.5 * sqrt( 6 ) * the minimun of the sinus of the half
* solid angles. 1.5 * sqrt( 6 ) is a factor to scale the metrics between
* 0 and 1.
* 0 corresponds to a bad tetrahedron, and
* 1 to a good tetrahedron (equilaterality).
*/
double tet_quality_min_solid_angle(
const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 )
{
double min_sin_half_solid_angle = std::min(
std::min( std::min( sin_half_solid_angle( v0, v1, v2, v3 ),
sin_half_solid_angle( v1, v0, v2, v3 ) ),
sin_half_solid_angle( v2, v0, v1, v3 ) ),
sin_half_solid_angle( v3, v0, v1, v2 ) );
return 1.5 * std::sqrt( 6. ) * min_sin_half_solid_angle;
}
/*!
* @param[in] mesh_qual_mode mesh quality number.
* @return the property name associated to the mesh quality number
* \p mesh_qual_mode.
*/
std::string mesh_qual_mode_to_prop_name( MeshQualityMode mesh_qual_mode )
{
std::string quality_name;
switch( mesh_qual_mode )
{
case INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS:
quality_name = "INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS";
break;
case INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH:
quality_name = "INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH";
break;
case VOLUME_BY_SUM_SQUARE_EDGE:
quality_name = "VOLUME_BY_SUM_SQUARE_EDGE";
break;
case MIN_SOLID_ANGLE:
quality_name = "MIN_SOLID_ANGLE";
break;
default:
ringmesh_assert_not_reached;
}
ringmesh_assert( !quality_name.empty() );
return quality_name;
}
/*!
* @brief Gets the quality for one tetrahedron.
*
* The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and
* 1 to a good tetrahedron (equilaterality).
*
* @param[in] v0 first vertex of the tetrahedron.
* @param[in] v1 second vertex of the tetrahedron.
* @param[in] v2 third vertex of the tetrahedron.
* @param[in] v3 fourth vertex of the tetrahedron.
* @param[in] mesh_qual_mode tetrahedron quality to get.
* @return the tetrahedron quality.
*/
double get_tet_quality( const vec3& v0,
const vec3& v1,
const vec3& v2,
const vec3& v3,
MeshQualityMode mesh_qual_mode )
{
double quality = -1;
switch( mesh_qual_mode )
{
case INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS:
quality = tet_quality_insphere_radius_by_circumsphere_radius(
v0, v1, v2, v3 );
break;
case INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH:
quality = tet_quality_insphere_radius_by_max_edge_length(
v0, v1, v2, v3 );
break;
case VOLUME_BY_SUM_SQUARE_EDGE:
quality = tet_quality_volume_by_sum_square_edges( v0, v1, v2, v3 );
break;
case MIN_SOLID_ANGLE:
quality = tet_quality_min_solid_angle( v0, v1, v2, v3 );
break;
default:
ringmesh_assert_not_reached;
}
ringmesh_assert(
quality > -1 * global_epsilon && quality < 1 + global_epsilon );
return quality;
}
} // namespace
namespace RINGMesh
{
void compute_prop_tet_mesh_quality(
MeshQualityMode mesh_qual_mode, const GeoModel3D& geomodel )
{
ringmesh_assert( geomodel.nb_regions() != 0 );
for( const auto& region : geomodel.regions() )
{
ringmesh_assert( region.is_meshed() );
ringmesh_assert( region.is_simplicial() );
GEO::AttributesManager& reg_attr_mgr =
region.cell_attribute_manager();
GEO::Attribute< double > attr(
reg_attr_mgr, mesh_qual_mode_to_prop_name( mesh_qual_mode ) );
for( auto cell_itr : range( region.nb_mesh_elements() ) )
{
attr[cell_itr] = get_tet_quality(
region.mesh_element_vertex( { cell_itr, 0 } ),
region.mesh_element_vertex( { cell_itr, 1 } ),
region.mesh_element_vertex( { cell_itr, 2 } ),
region.mesh_element_vertex( { cell_itr, 3 } ),
mesh_qual_mode );
}
}
}
double fill_mesh_with_low_quality_cells( MeshQualityMode mesh_qual_mode,
double min_quality,
const GeoModel3D& geomodel,
VolumeMesh3D& output_mesh )
{
ringmesh_assert( geomodel.nb_regions() != 0 );
auto mesh_builder = VolumeMeshBuilder3D::create_builder( output_mesh );
double min_qual_value{ max_float64() };
for( const auto& region : geomodel.regions() )
{
ringmesh_assert( region.is_meshed() );
ringmesh_assert( region.is_simplicial() );
GEO::Attribute< double > quality_attribute(
region.cell_attribute_manager(),
mesh_qual_mode_to_prop_name( mesh_qual_mode ) );
for( auto cell_id : range( region.nb_mesh_elements() ) )
{
if( quality_attribute[cell_id] < min_quality )
{
auto first_new_vertex_id = output_mesh.nb_vertices();
for( auto v : range( 4 ) )
{
mesh_builder->create_vertex(
region.mesh_element_vertex( { cell_id, v } ) );
}
auto new_cell_id =
mesh_builder->create_cells( 1, CellType::TETRAHEDRON );
for( auto v_id : range( 4 ) )
{
mesh_builder->set_cell_vertex(
{ new_cell_id, v_id }, first_new_vertex_id + v_id );
}
if( quality_attribute[cell_id] < min_qual_value )
{
min_qual_value = quality_attribute[cell_id];
}
}
}
}
return min_qual_value;
}
} // namespace RINGMesh
| 41.575117 | 97 | 0.611484 |
30cf9a1e4c280de211c6f47e1da4bb8d58ea336d | 2,835 | cpp | C++ | primitive_roots_tests.cpp | Mirraz/number-theory | 30f444f8b61cc5946d4615bafe237994d7836cbf | [
"MIT"
] | null | null | null | primitive_roots_tests.cpp | Mirraz/number-theory | 30f444f8b61cc5946d4615bafe237994d7836cbf | [
"MIT"
] | null | null | null | primitive_roots_tests.cpp | Mirraz/number-theory | 30f444f8b61cc5946d4615bafe237994d7836cbf | [
"MIT"
] | null | null | null | #include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <math.h>
#include "primitive_roots.h"
#define main HIDE_main
#define tests_suite HIDE_tests_suite
#define test_max_primitive_root HIDE_test_max_primitive_root
#include "mul_group_mod_tests.cpp"
#undef main
#undef tests_suite
#undef test_max_primitive_root
void test_is_primitive_root() {
typedef uint_fast32_t num_type;
typedef PrimitiveRoots<num_type, 9, ((num_type)1)<<31, uint_fast64_t> prrs_type;
typedef prrs_type::canonic_factorizer_type cfzr_type;
typedef cfzr_type::primes_array_type primes_array_type;
// pi(2^16) = 6542
num_type primes[6542];
size_t primes_count = primes_array_type::fill_primes(
primes,
sizeof(primes) / sizeof(primes[0]),
(num_type)UINT16_MAX + 1
);
assert(primes_count == sizeof(primes) / sizeof(primes[0]));
cfzr_type cfzr(primes_array_type(primes, primes_count));
for (size_t idx=0; idx<sizeof(primes) / sizeof(primes[0]); ++idx) {
num_type modulo = primes[idx];
prrs_type primitive_roots(cfzr, modulo);
num_type min_root = 0;
for (num_type i=1; i<modulo; ++i) {
bool is_primitive_root = primitive_roots.is_primitive_root(i);
if (is_primitive_root) {min_root = i; break;}
}
num_type max_root = 0;
for (num_type i=modulo-1; i>=1; --i) {
bool is_primitive_root = primitive_roots.is_primitive_root(i);
if (is_primitive_root) {max_root = i; break;}
}
assert(min_root != 0);
assert(max_root != 0);
assert((modulo-1) % 4 != 0 || modulo-max_root == min_root);
printf("%" PRIuFAST64 "\t %" PRIuFAST64 "\n", modulo, min_root);
printf("%" PRIuFAST64 "\t-%" PRIuFAST64 "\n", modulo, modulo-max_root);
printf("\n");
}
}
void test_max_primitive_root() {
fill_myprimes();
fill_max_roots();
typedef uint_fast32_t num_type;
typedef PrimitiveRoots<num_type, 9, ((num_type)1)<<31, uint_fast64_t> prrs_type;
typedef prrs_type::canonic_factorizer_type cfzr_type;
typedef cfzr_type::primes_array_type primes_array_type;
// pi(2^16) = 6542
num_type primes[6542];
size_t primes_count = primes_array_type::fill_primes(
primes,
sizeof(primes) / sizeof(primes[0]),
(num_type)UINT16_MAX + 1
);
assert(primes_count == sizeof(primes) / sizeof(primes[0]));
cfzr_type cfzr(primes_array_type(primes, primes_count));
for (size_t idx=0; idx<sizeof(primes) / sizeof(primes[0]); ++idx) {
num_type modulo = primes[idx];
prrs_type primitive_roots(cfzr, modulo);
num_type max_root = 0;
for (num_type i=modulo-1; i>=1; --i) {
bool is_primitive_root = primitive_roots.is_primitive_root(i);
if (is_primitive_root) {max_root = i; break;}
}
assert(max_root != 0);
assert(max_root == myprimes[idx] - max_roots[idx]);
}
}
void tests_suite() {
//test_is_primitive_root();
test_max_primitive_root();
}
int main() {
tests_suite();
return 0;
}
| 29.53125 | 81 | 0.722751 |
30d0ce1ea78572de8c984a5eaa443dd2aadc4520 | 4,446 | cc | C++ | stapl_release/benchmarks/kernels/jacobi_1d/jacobi_1d_mpi_omp.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/benchmarks/kernels/jacobi_1d/jacobi_1d_mpi_omp.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/benchmarks/kernels/jacobi_1d/jacobi_1d_mpi_omp.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
//////////////////////////////////////////////////////////////////////
/// @file
/// Hybrid MPI+OpenMP implementation of http://www.mcs.anl.gov/research/projects/mpi/tutorial/mpiexmpl/src/jacobi/C/main.html
//////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cfloat>
#include <cmath>
#include <vector>
#include <mpi.h>
#ifdef _OPENMP
# include <omp.h>
#endif
template<typename T>
class matrix
{
private:
std::size_t m_nrows;
std::size_t m_ncols;
std::vector<T> m_data;
public:
matrix(std::size_t nrows, std::size_t ncols)
: m_nrows(nrows), m_ncols(ncols), m_data(ncols * nrows)
{ }
T const& operator()(std::size_t row, std::size_t ncol) const noexcept
{ return m_data[row * m_ncols + ncol]; }
T& operator()(std::size_t row, std::size_t ncol) noexcept
{ return m_data[row * m_ncols + ncol]; }
T const* operator[](std::size_t row) const noexcept
{ return &m_data[row * m_ncols]; }
T* operator[](std::size_t row) noexcept
{ return &m_data[row * m_ncols]; }
};
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);
MPI_Comm comm = MPI_COMM_WORLD;
int rank = MPI_PROC_NULL, size = MPI_PROC_NULL;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &size);
const std::size_t maxn = (argc < 2 ? 12 : std::atoi(argv[1]));
if (maxn % size != 0) {
std::cerr << "Incorrect size of " << maxn << std::endl;
MPI_Abort( comm, 1 );
}
/* xlocal[][0] is lower ghostpoints, xlocal[][maxn+2] is upper */
// top and bottom processes have one less row of interior points
std::size_t i_first = 1;
std::size_t i_last = maxn/size;
if (rank == 0)
i_first++;
if (rank == size - 1)
i_last--;
// create data
typedef matrix<double> matrix_type;
matrix_type xlocal(maxn/size + 2 ,maxn);
matrix_type xnew(maxn/size + 2, maxn);
for (std::size_t i=1; i<=maxn/size; i++)
for (std::size_t j=0; j<maxn; j++)
xlocal[i][j] = rank;
for (std::size_t j=0; j<maxn; j++) {
xlocal[i_first-1][j] = -1;
xlocal[i_last+1][j] = -1;
}
double gdiffnorm = DBL_MAX;
double diffnorm = 0.0;
int itcnt = 0;
const double time = MPI_Wtime();
#pragma omp parallel firstprivate(itcnt)
for (itcnt=0; itcnt<100 && gdiffnorm > 1.0e-3; ++itcnt) {
# pragma omp master
{
/* Send up unless I'm at the top, then receive from below */
/* Note the use of xlocal[i] for &xlocal[i][0] */
if (rank < size - 1)
MPI_Send(xlocal[maxn/size], maxn, MPI_DOUBLE, rank + 1, 0, comm);
if (rank > 0)
MPI_Recv(xlocal[0], maxn, MPI_DOUBLE, rank - 1, 0,
comm, MPI_STATUS_IGNORE);
/* Send down unless I'm at the bottom */
if (rank > 0)
MPI_Send(xlocal[1], maxn, MPI_DOUBLE, rank - 1, 1, comm);
if (rank < size - 1)
MPI_Recv(xlocal[maxn/size+1], maxn, MPI_DOUBLE, rank + 1, 1,
comm, MPI_STATUS_IGNORE);
}
#pragma omp barrier
/* Compute new values (but not on boundary) */
# pragma omp for reduction(+:diffnorm)
for (std::size_t i=i_first; i<=i_last; i++) {
for (std::size_t j=1; j<maxn-1; j++) {
xnew[i][j] = (xlocal[i][j+1] + xlocal[i][j-1] +
xlocal[i+1][j] + xlocal[i-1][j]) / 4.0;
diffnorm += (xnew[i][j] - xlocal[i][j]) * (xnew[i][j] - xlocal[i][j]);
}
}
/* Only transfer the interior points */
# pragma omp for
for (std::size_t i=i_first; i<=i_last; i++) {
for (std::size_t j=1; j<maxn-1; j++) {
xlocal[i][j] = xnew[i][j];
}
}
# pragma omp master
{
MPI_Allreduce(&diffnorm, &gdiffnorm, 1, MPI_DOUBLE, MPI_SUM, comm);
diffnorm = 0.0;
gdiffnorm = std::sqrt(gdiffnorm);
}
}
const double elapsed = MPI_Wtime() - time;
if (rank==0)
std::cout << "jacobi_1d_mpi_omp "
<< size << ' '
#ifdef _OPENMP
<< omp_get_max_threads() << ' '
#else
<< 1 << ' '
#endif
<< elapsed << ' '
<< itcnt << "\n";
MPI_Finalize();
return 0;
}
| 28.318471 | 125 | 0.573324 |
30d264b409b79ef46efb5821f7ccf8183efb324c | 3,943 | cpp | C++ | Source/Workbenches/PartDesign/feature_line.cpp | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | Source/Workbenches/PartDesign/feature_line.cpp | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | Source/Workbenches/PartDesign/feature_line.cpp | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | /*** Included Header Files ***/
#include <feature_line.h>
#include <document.h>
#include <feature_point.h>
#include <tree_view.h>
#include <line_layer.h>
#include <feature_line_action.h>
#include <feature_line_controller.h>
/***********************************************~***************************************************/
WCFeatureLine::WCFeatureLine(WCFeature *creator, const std::string &name, WCFeaturePoint *p0, WCFeaturePoint *p1) :
::WCFeature(creator, name), _base(NULL), _p0(p0), _p1(p1) {
//Make sure p0 and p1 are not null
if ((p0 == NULL) || (p1 == NULL)) {
CLOGGER_ERROR(WCLogManager::RootLogger(), "WCFeatureLine::WCFeatureLine - NULL points passed.\n");
//throw error
return;
}
//Create the base line
this->_base = new WCGeometricLine(p0->Base(), p1->Base());
this->_base->Retain(*this);
//Retain both p0 and p1
this->_p0->Retain(*this);
this->_p1->Retain(*this);
//Check feature name
if (this->_name == "") this->_name = this->_document->GenerateFeatureName(this);
//Create event handler
this->_controller = new WCFeatureLineController(this);
//Create tree element and add into the tree (beneath the creator)
this->_treeElement = new WCTreeElement(this->_document->TreeView(), this->_name, this->_controller, NULL);
//Add p0 and p1 as a children in the tree view
this->_treeElement->AddLastChild(this->_p0->TreeElement());
this->_treeElement->AddLastChild(this->_p1->TreeElement());
//Mark as closed
this->_treeElement->IsOpen(false);
//Add to the creator
this->_creator->TreeElement()->AddLastChild(this->_treeElement);
//Add into document
this->_document->AddFeature(this);
//Add to the lines layer
this->_document->LinesLayer()->AddLine(this->_base);
}
WCFeatureLine::~WCFeatureLine() {
//Remove the line from the layer
this->_document->LinesLayer()->RemoveLine(this->_base);
//Remove the line from the document
this->_document->RemoveFeature(this);
//Release and delete the base
this->_base->Release(*this);
delete this->_base;
//Release the points
this->_p0->Release(*this);
this->_p1->Release(*this);
}
void WCFeatureLine::ReceiveNotice(WCObjectMsg msg, WCObject *sender) {
//Just need to mark line layer as dirty
this->_document->LinesLayer()->MarkDirty();
// CLOGGER_WARN(WCLogManager::RootLogger(), "WCFeatureLine::ReceiveNotice - Not yet implemented.\n");
}
bool WCFeatureLine::Regenerate(void) {
return false;
}
xercesc::DOMElement* WCFeatureLine::Serialize(xercesc::DOMDocument *document) {
return NULL;
}
WCFeatureLine* WCFeatureLine::Deserialize(xercesc::DOMElement* obj) {
return NULL;
}
bool WCFeatureLine::Validate(xercesc::DOMElement* obj) {
return false;
}
/*
WCVisualObject* WCFeatureLine::HitTest(const WCRay &ray, const WPFloat tolerance) {
return NULL;
}
void WCFeatureLine::ApplyTransform(const WCMatrix4 &transform) {
}
void WCFeatureLine::ApplyTranslation(const WCVector4 &translation) {
}
*/
void WCFeatureLine::Render(const GLuint defaultProg, const WCColor color) {
//Make sure is visible
if (!this->_isVisible) return;
this->_base->Render(defaultProg, color);
}
/***********************************************~***************************************************/
WCFeatureLineAction* WCFeatureLine::ActionCreate(WCFeature *creator, const std::string lineName, WCFeaturePoint *p0, WCFeaturePoint *p1) {
WCFeatureLineAction* action;
action = new WCFeatureLineAction(creator, lineName, p0, p1);
return action;
}
//WCFeatureLineAction* WCFeatureLine::ActionModify() {
//}
WCFeatureLineAction* WCFeatureLine::ActionDelete(WCFeatureLine *line) {
return NULL;
}
/***********************************************~***************************************************/
std::ostream& operator<<(std::ostream& out, const WCFeatureLine &line) {
out << "FeatureLine( " << &line << ")\n";
return out;
}
/***********************************************~***************************************************/
| 27.964539 | 138 | 0.652042 |
30d3f168dd50e3f6162768d0f9b6d9bfcf56fc02 | 447 | cpp | C++ | Course 201809/homework/4/B2.cpp | Seizzzz/DailyCodes | 9a617fb64ee27b9f254be161850e9c9a61747cb1 | [
"MIT"
] | null | null | null | Course 201809/homework/4/B2.cpp | Seizzzz/DailyCodes | 9a617fb64ee27b9f254be161850e9c9a61747cb1 | [
"MIT"
] | null | null | null | Course 201809/homework/4/B2.cpp | Seizzzz/DailyCodes | 9a617fb64ee27b9f254be161850e9c9a61747cb1 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
int main()
{
int n1,n2,n,i;
scanf("%d",&n);
for (n1=2;n1<=n/2;n1++)
{
for (i=2;i<=sqrt(n1);i++)
{
if (n1%i==0) break;
}
if (i==(int)sqrt(n1)+1)
{
for (i=2,n2=n-n1;i<=sqrt(n2);i++)
{
if (n2%i==0) break;
}
if (i==(int)sqrt(n2)+1)
printf("%d and %d\n",n1,n2);
}
}
printf("\n");
return 0;
}
| 13.96875 | 41 | 0.378076 |
30d4c2054b988f10e08e7936105ba79a20ce2dfd | 9,263 | cpp | C++ | maya/Workshop2017/src/BBoxCubeCmd.cpp | smoi23/sandbox | 4d02a509c82b2ec3712f91bbc86cc5df37174396 | [
"MIT"
] | null | null | null | maya/Workshop2017/src/BBoxCubeCmd.cpp | smoi23/sandbox | 4d02a509c82b2ec3712f91bbc86cc5df37174396 | [
"MIT"
] | null | null | null | maya/Workshop2017/src/BBoxCubeCmd.cpp | smoi23/sandbox | 4d02a509c82b2ec3712f91bbc86cc5df37174396 | [
"MIT"
] | null | null | null | /*
* WorkshopCmd3.cpp
*
* Created on: May 15, 2017
* Author: Andreas Schuster
*
*/
#include <stdio.h>
#include <iostream>
#include <maya/MPxCommand.h>
#include <maya/MArgList.h>
#include <maya/MStatus.h>
#include <maya/MSyntax.h>
#include <maya/MStringArray.h>
#include <maya/MGlobal.h>
#include <maya/MArgDatabase.h>
#include <maya/MItSelectionList.h>
#include <maya/MDagPath.h>
#include <maya/MItMeshVertex.h>
#include <maya/MPoint.h>
#include <maya/MPointArray.h>
#include <maya/MMatrix.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnMesh.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MItMeshEdge.h>
#include <maya/MFnTransform.h>
#include <maya/MFnMeshData.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MPlug.h>
#include <maya/MBoundingBox.h>
#include <maya/MFnSet.h>
#include "BBoxCubeCmd.h"
//
#define kHelpFlag "-h"
#define kHelpFlagLong "-help"
// //
#define kSizeFlag "s"
#define kSizeFlagLong "size"
MObject BBoxCubeCmd::m_meshTransform;
MString BBoxCubeCmd::s_name("BBoxCube");
BBoxCubeCmd::BBoxCubeCmd():
m_doHelp(false),
m_size(1.0),
m_isQuery(false)
{
std::cout << "In BBoxCubeCmd::BBoxCubeCmd()" << std::endl;
}
BBoxCubeCmd::~BBoxCubeCmd()
{
std::cout << "In BBoxCubeCmd::~BBoxCubeCmd()" << std::endl;
}
MSyntax BBoxCubeCmd::newSyntax()
{
MSyntax syntax;
std::cout << "In BBoxCubeCmd::BBoxCubeCmd()" << std::endl;
// //
syntax.enableQuery(true);
syntax.enableEdit(false);
syntax.useSelectionAsDefault(true);
syntax.setObjectType(MSyntax::kSelectionList, 1);
syntax.addFlag(kHelpFlag, kHelpFlagLong, MSyntax::kNoArg);
syntax.addFlag(kSizeFlag, kSizeFlagLong, MSyntax::kDouble);
return syntax;
}
MStatus BBoxCubeCmd::doIt(const MArgList &args)
{
MStatus stat = MS::kSuccess;
std::cout << "In BBoxCubeCmd::doIt()" << std::endl;
stat = parseArgs(args);
if (m_doHelp)
{
MGlobal::displayInfo("Show help");
}
else if (m_isQuery)
{
MString selectionString("");
MItSelectionList iter(m_selection);
for (iter.reset(); !iter.isDone(); iter.next())
{
MDagPath dagpath;
iter.getDagPath(dagpath);
selectionString += dagpath.fullPathName();
}
MGlobal::displayInfo(selectionString);
}
else
{
if (m_selection.length() > 0)
{
stat = redoIt();
}
else
{
MGlobal::displayError("Pass or select at least one polygon object.");
}
}
return stat;
}
MStatus BBoxCubeCmd::redoIt()
{
std::cout << "In BBoxCubeCmd::redoIt()" << std::endl;
MStatus stat;
// start new buffers
MPointArray vertexBuffer;
MIntArray faceCount;
MIntArray vertexIndex;
MItSelectionList iter(m_selection, MFn::kTransform);
for (iter.reset(); !iter.isDone(); iter.next())
{
MDagPath dagpath;
iter.getDagPath(dagpath);
MGlobal::displayInfo(dagpath.fullPathName());
MMatrix dagMatrix = dagpath.inclusiveMatrix();
stat = dagpath.extendToShape();
if (stat == MS::kSuccess)
{
MFnDagNode fnDagNode(dagpath);
MBoundingBox bbox = fnDagNode.boundingBox();
bbox.transformUsing(dagMatrix);
addCubeFromBbox(vertexBuffer, faceCount, vertexIndex, bbox);
}
}
MGlobal::displayInfo(MString("VertexBufferlength: ") + vertexBuffer.length());
// create place for the data
MFnMeshData dataFn;
MObject dataWrapper = dataFn.create();
// create the mesh from the mesh function set
MFnMesh fnMesh;
fnMesh.create(vertexBuffer.length(), faceCount.length(), vertexBuffer, faceCount, vertexIndex, dataWrapper, &stat);
if (stat != MS::kSuccess)
{
MGlobal::displayError("Failed to create mesh: " + stat.errorString());
return stat;
}
// set normals to make the cube hard edged
int numFaceVertices = faceCount.length() * 4; // assuming quads!
MVectorArray normals(numFaceVertices);
MIntArray faces(numFaceVertices);
MIntArray vertices(numFaceVertices);
MItMeshPolygon iterFace(dataWrapper);
int idx = 0;
for (iterFace.reset(); !iterFace.isDone(); iterFace.next())
{
MIntArray vertexIds;
iterFace.getVertices(vertexIds);
//std::cout << "faceVertices count " << vertexIds.length() << std::endl;
//std::cout << vertexIds[0] << " " << vertexIds[1] << " " << vertexIds[2] << " " << vertexIds[3] << std::endl;
MVector faceNormal;
iterFace.getNormal(faceNormal);
//std::cout << "Face normal: " << faceNormal.x << " " << faceNormal.y << " " << faceNormal.z << std::endl;
for (int i = 0; i < 4; i++) // assuming quads!
{
faces.set(iterFace.index(), idx * 4+i);
vertices.set(vertexIds[i], idx * 4 + i);
normals.set(faceNormal, idx * 4 + i);
// fnMesh.setFaceVertexNormal(faceNormal, iterFace.index(), vertexIds[i]); // set normal for every face vertex separately
}
idx++;
}
fnMesh.setFaceVertexNormals(normals, faces, vertices);
fnMesh.updateSurface();
MObject transformNode = dagModifier.createNode("mesh", MObject::kNullObj, &stat);
if (stat != MS::kSuccess)
{
MGlobal::displayError("Failed to create transform: " + stat.errorString());
return stat;
}
dagModifier.doIt();
// Set the mesh node to use the geometry we created for it.
setMeshData(transformNode, dataWrapper);
// assign to shading group
MSelectionList selectionList;
stat = selectionList.add("initialShadingGroup");
if (stat == MS::kSuccess)
{
MObject shaderNode;
selectionList.getDependNode(0, shaderNode);
MFnSet setFn(shaderNode);
MFnDagNode dagFn(transformNode);
MObject mesh = dagFn.child(0);
setFn.addMember(mesh);
}
return MS::kSuccess;
}
void BBoxCubeCmd::addCubeFromBbox(MPointArray &o_vertexBuffer, MIntArray &o_vertexCount, MIntArray &o_vertexIndex, MBoundingBox &i_bbox)
{
int offset = o_vertexBuffer.length();
// 8 vertices
o_vertexBuffer.append(i_bbox.max());
o_vertexBuffer.append(MPoint(i_bbox.max().x, i_bbox.max().y, i_bbox.min().z));
o_vertexBuffer.append(MPoint(i_bbox.min().x, i_bbox.max().y, i_bbox.min().z));
o_vertexBuffer.append(MPoint(i_bbox.min().x, i_bbox.max().y, i_bbox.max().z));
o_vertexBuffer.append(i_bbox.min());
o_vertexBuffer.append(MPoint(i_bbox.max().x, i_bbox.min().y, i_bbox.min().z));
o_vertexBuffer.append(MPoint(i_bbox.max().x, i_bbox.min().y, i_bbox.max().z));
o_vertexBuffer.append(MPoint(i_bbox.min().x, i_bbox.min().y, i_bbox.max().z));
// every face has 4 vertices
for (int i = 0; i < 6; i++)
{
o_vertexCount.append(4);
}
// face top
o_vertexIndex.append(offset + 0);
o_vertexIndex.append(offset + 1);
o_vertexIndex.append(offset + 2);
o_vertexIndex.append(offset + 3);
// face front
o_vertexIndex.append(offset + 0);
o_vertexIndex.append(offset + 3);
o_vertexIndex.append(offset + 7);
o_vertexIndex.append(offset + 6);
// face right
o_vertexIndex.append(offset + 1);
o_vertexIndex.append(offset + 0);
o_vertexIndex.append(offset + 6);
o_vertexIndex.append(offset + 5);
// face left
o_vertexIndex.append(offset + 3);
o_vertexIndex.append(offset + 2);
o_vertexIndex.append(offset + 4);
o_vertexIndex.append(offset + 7);
// face back
o_vertexIndex.append(offset + 2);
o_vertexIndex.append(offset + 1);
o_vertexIndex.append(offset + 5);
o_vertexIndex.append(offset + 4);
// face bottom
o_vertexIndex.append(offset + 4);
o_vertexIndex.append(offset + 5);
o_vertexIndex.append(offset + 6);
o_vertexIndex.append(offset + 7);
}
MStatus BBoxCubeCmd::setMeshData(MObject transform, MObject dataWrapper)
{
MStatus st;
// Get the mesh node.
MFnDagNode dagFn(transform);
MObject mesh = dagFn.child(0);
// The mesh node has two geometry inputs: 'inMesh' and 'cachedInMesh'.
// 'inMesh' is only used when it has an incoming connection, otherwise
// 'cachedInMesh' is used. Unfortunately, the docs say that 'cachedInMesh'
// is for internal use only and that changing it may render Maya
// unstable.
//
// To get around that, we do the little dance below...
// Use a temporary MDagModifier to create a temporary mesh attribute on
// the node.
MFnTypedAttribute tAttr;
MObject tempAttr = tAttr.create("tempMesh", "tmpm", MFnData::kMesh);
MDagModifier tempMod;
st = tempMod.addAttribute(mesh, tempAttr);
st = tempMod.doIt();
// Set the geometry data onto the temp attribute.
dagFn.setObject(mesh);
MPlug tempPlug = dagFn.findPlug(tempAttr);
st = tempPlug.setValue(dataWrapper);
// Use the temporary MDagModifier to connect the temp attribute to the
// node's 'inMesh'.
MPlug inMeshPlug = dagFn.findPlug("inMesh");
st = tempMod.connect(tempPlug, inMeshPlug);
st = tempMod.doIt();
// Force the mesh to update by grabbing its output geometry.
dagFn.findPlug("outMesh").asMObject();
// Undo the temporary modifier.
st = tempMod.undoIt();
return st;
}
MStatus BBoxCubeCmd::undoIt()
{
std::cout << "In BBoxCubeCmd::undoIt()" << std::endl;
dagModifier.undoIt();
return MS::kSuccess;
}
bool BBoxCubeCmd::isUndoable() const
{
std::cout << "In BBoxCubeCmd::isUndoable()" << std::endl;
return !m_isQuery;
}
void* BBoxCubeCmd::creator()
{
std::cout << "In BBoxCubeCmd::creator()" << std::endl;
return new BBoxCubeCmd();
}
MStatus BBoxCubeCmd::parseArgs(const MArgList &args)
{
MStatus stat = MS::kSuccess;
MArgDatabase argData(syntax(), args);
m_doHelp = argData.isFlagSet(kHelpFlag);
m_isQuery = argData.isQuery();
if (!m_isQuery) // only update selection if not in query mode
{
argData.getObjects(m_selection);
}
return stat;
}
| 24.967655 | 136 | 0.703768 |
30d61e145e98bb61d3e96be726741974debf1d6d | 602 | cpp | C++ | replace_character.cpp | chandan9369/Recursion-backtracking-problems | 360e5de72e23dfd4e3f343baa1e1abdfb801ccc3 | [
"MIT"
] | null | null | null | replace_character.cpp | chandan9369/Recursion-backtracking-problems | 360e5de72e23dfd4e3f343baa1e1abdfb801ccc3 | [
"MIT"
] | null | null | null | replace_character.cpp | chandan9369/Recursion-backtracking-problems | 360e5de72e23dfd4e3f343baa1e1abdfb801ccc3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void replace(char s[], char c1, char c2)
{
//base case
if (s[0] == '\0')
{
return;
}
if (s[0] == c1)
{
s[0] = c2;
}
replace(s + 1, c1, c2);
}
int main()
{
char s[100];
cin >> s;
char c1, c2;
cout << "Enter character to be replaced : ";
cin >> c1;
cout << "Enter character with which you want to replace : ";
cin >> c2;
replace(s, c1, c2);
cout << "After replacing character " << c1 << " with character" << c2 << "string we have new string : " << s << endl;
return 0;
} | 21.5 | 121 | 0.501661 |
30d6d8f00f7fdc97dab807313fc63d794818aa5a | 16,614 | cpp | C++ | modules/src/projectors/standardpipeline.cpp | phernst/ctl | f2369cf3141ff6a696219f99b09fd60c0ea12eac | [
"MIT"
] | null | null | null | modules/src/projectors/standardpipeline.cpp | phernst/ctl | f2369cf3141ff6a696219f99b09fd60c0ea12eac | [
"MIT"
] | null | null | null | modules/src/projectors/standardpipeline.cpp | phernst/ctl | f2369cf3141ff6a696219f99b09fd60c0ea12eac | [
"MIT"
] | null | null | null | #include "standardpipeline.h"
#include "arealfocalspotextension.h"
#include "detectorsaturationextension.h"
#include "poissonnoiseextension.h"
#include "raycasterprojector.h"
#include "spectraleffectsextension.h"
namespace CTL {
DECLARE_SERIALIZABLE_TYPE(StandardPipeline)
/*!
* Constructs a StandardPipeline object and with the ApproximationPolicy \a policy.
*
* The default configuration enables spectral effects and Poisson noise simulation.
*/
StandardPipeline::StandardPipeline(ApproximationPolicy policy)
: _projector(new OCL::RayCasterProjector)
, _extAFS(new ArealFocalSpotExtension)
, _extDetSat(new DetectorSaturationExtension)
, _extPoisson(new PoissonNoiseExtension)
, _extSpectral(new SpectralEffectsExtension)
, _approxMode(policy)
{
_pipeline.setProjector(_projector);
// configure extensions
_extAFS->setDiscretization({ 3, 3 });
if(policy == ApproximationPolicy::Full_Approximation)
_extAFS->enableLowExtinctionApproximation();
enableArealFocalSpot(false);
enableDetectorSaturation(false);
enablePoissonNoise(true);
enableSpectralEffects(true);
}
StandardPipeline::~StandardPipeline()
{
// handover ownership to ProjectionPipeline member
enableArealFocalSpot(true);
enableDetectorSaturation(true);
enablePoissonNoise(true);
enableSpectralEffects(true);
}
/*!
* \brief Sets the acquisition setup for the simulation to \a setup.
*
* Sets the acquisition setup for the simulation to \a setup. This needs to be done prior to calling
* project().
*/
void StandardPipeline::configure(const AcquisitionSetup& setup) { _pipeline.configure(setup); }
/*!
* \brief Creates projection data from \a volume.
*
* Creates projection data from \a volume using the current processing pipeline configuration of
* this instance. Uses the last acquisition setup set by configure().
*/
ProjectionData StandardPipeline::project(const VolumeData& volume)
{
return _pipeline.project(volume);
}
/*!
* \brief Creates projection data from the composite volume \a volume.
*
* Creates projection data from the composite volume \a volume using the current processing pipeline
* configuration of this instance. Uses the last acquisition setup set by configure().
*/
ProjectionData StandardPipeline::projectComposite(const CompositeVolume& volume)
{
return _pipeline.projectComposite(volume);
}
/*!
* Returns true if the application of the full processing pipeline is linear.
*/
bool StandardPipeline::isLinear() const { return _pipeline.isLinear(); }
ProjectorNotifier* StandardPipeline::notifier() { return _pipeline.notifier(); }
void StandardPipeline::fromVariant(const QVariant& variant)
{
AbstractProjector::fromVariant(variant);
QVariantMap map = variant.toMap();
enableArealFocalSpot(false);
enableDetectorSaturation(false);
enablePoissonNoise(false);
enableSpectralEffects(false);
_pipeline.setProjector(SerializationHelper::parseProjector(map.value("projector")));
_extAFS->fromVariant(map.value("ext AFS"));
_extDetSat->fromVariant(map.value("ext DetSat"));
_extPoisson->fromVariant(map.value("ext Poisson"));
_extSpectral->fromVariant(map.value("ext spectral"));
_approxMode = ApproximationPolicy(map.value("approximation policy",
int(Default_Approximation)).toInt());
enableArealFocalSpot(map.value("use areal focal spot").toBool());
enableDetectorSaturation(map.value("use detector saturation").toBool());
enablePoissonNoise(map.value("use poisson noise").toBool());
enableSpectralEffects(map.value("use spectral effects").toBool());
}
QVariant StandardPipeline::toVariant() const
{
QVariantMap ret = AbstractProjector::toVariant().toMap();
ret.insert("#", "StandardPipeline");
ret.insert("use areal focal spot", _arealFSEnabled);
ret.insert("use detector saturation", _detSatEnabled);
ret.insert("use poisson noise", _poissonEnabled);
ret.insert("use spectral effects", _spectralEffEnabled);
ret.insert("approximation policy", _approxMode);
ret.insert("projector", _projector->toVariant());
ret.insert("ext AFS", _extAFS->toVariant());
ret.insert("ext DetSat", _extDetSat->toVariant());
ret.insert("ext Poisson", _extPoisson->toVariant());
ret.insert("ext spectral", _extSpectral->toVariant());
return ret;
}
/*!
* Enables/disables the simulation of areal focal spot effects, according to \a enable.
*/
void StandardPipeline::enableArealFocalSpot(bool enable)
{
if(enable == _arealFSEnabled) // no change
return;
if(enable) // insert AFS into pipeline (first position)
_pipeline.insertExtension(posAFS(), _extAFS);
else // remove AFS from pipeline (first position)
_pipeline.releaseExtension(posAFS());
_arealFSEnabled = enable;
}
/*!
* Enables/disables the simulation of detector saturation effects, according to \a enable.
*
* This only has an effect on the simulation if the detector component of the system passed with
* the setup during configure() has a detector response model (see
* AbstractDetector::setSaturationModel()).
*/
void StandardPipeline::enableDetectorSaturation(bool enable)
{
if(enable == _detSatEnabled) // no change
return;
if(enable) // insert det. sat. into pipeline (last position)
_pipeline.appendExtension(_extDetSat);
else // remove det. sat. from pipeline (last position)
_pipeline.releaseExtension(_pipeline.nbExtensions() - 1u);
_detSatEnabled = enable;
}
/*!
* Enables/disables the simulation of Poisson noise, according to \a enable.
*/
void StandardPipeline::enablePoissonNoise(bool enable)
{
if(enable == _poissonEnabled) // no change
return;
if(enable) // insert Poisson into pipeline (after AFS and spectral)
_pipeline.insertExtension(posPoisson(), _extPoisson);
else // remove Poisson from pipeline (after AFS and spectral)
_pipeline.releaseExtension(posPoisson());
_poissonEnabled = enable;
}
/*!
* Enables/disables the simulation of spectral effects, according to \a enable.
*
* Spectral effects require full spectral information (see SpectralVolumeData) in the volume data
* passed to project(). Otherwise, the spectral effects step will be skipped.
*
* Spectral detector response effects will be considered if a corresponding response model has been
* set to the detector component (see AbstractDetector::setSpectralResponseModel()) of the system
* passed with the setup during configure(). Note that trying to simulate settings with a spectral
* response model in combination with volume data without full spectral information is not supported
* and leads to an exception.
*/
void StandardPipeline::enableSpectralEffects(bool enable)
{
if(enable == _spectralEffEnabled) // no change
return;
if(enable) // insert spectral ext. into pipeline (after AFS)
_pipeline.insertExtension(posSpectral(), _extSpectral);
else // remove Poisson from pipeline (after AFS)
_pipeline.releaseExtension(posSpectral());
_spectralEffEnabled = enable;
}
/*!
* Returns a handle to the settings for the areal focal spot simulation.
*
* Areal focal spot settings are:
* - setDiscretization(const QSize& discretization): sets the number of sampling
* points for the subsampling of the areal focal spot to \a discretization (width x height)
* [ default value: {3, 3} ]
* - enableLowExtinctionApproximation(bool enable): sets the use of the linear approximation to
* \a enable. [ default: \c false (\c true for StandardPipeline::Full_Approximation) ]
*
* Example:
* \code
* StandardPipeline pipe;
* pipe.enableArealFocalSpot();
* pipe.settingsArealFocalSpot().setDiscretization( { 2, 2 } );
* \endcode
*
* \sa ArealFocalSpotExtension::setDiscretization()
*/
StandardPipeline::SettingsAFS StandardPipeline::settingsArealFocalSpot()
{
return { *_extAFS };
}
/*!
* Returns a handle to the settings for the detector saturation simulation.
*
* Detector saturation settings are:
* - setSpectralSamples(uint nbSamples): sets the number of energy bins used to sample the spectrum
* when processing intensity saturation to \a nbSamples [ default value: 0 (i.e. use sampling hint
* of source component) ]
*
* Example:
* \code
* StandardPipeline pipe;
* pipe.enableDetectorSaturation();
* pipe.settingsDetectorSaturation().setSpectralSamples(10);
* \endcode
*
* \sa DetectorSaturationExtension::setIntensitySampling()
*/
StandardPipeline::SettingsDetectorSaturation StandardPipeline::settingsDetectorSaturation()
{
return { *_extDetSat };
}
/*!
* Returns a handle to the settings for the Poisson noise simulation.
*
* Poisson noise settings are:
* - setFixedSeed(uint seed): sets a fixed seed for the pseudo random number generation [ default
* value: not used]
* - setRandomSeedMode(): (re-)enables the random seed mode, any fixed seed set will be ignored
* until setFixedSeed() is called again [ default: random seed mode used ]
* - setParallelizationMode(bool enabled): sets the use of parallelization to \a enabled [ default
* value: true (i.e. parallelization enabled) ]
*
* Example:
* \code
* StandardPipeline pipe;
* pipe.settingsPoissonNoise().setFixedSeed(1337);
* pipe.settingsPoissonNoise().setParallelizationMode(false);
* \endcode
*
* \sa PoissonNoiseExtension::setFixedSeed(), PoissonNoiseExtension::setRandomSeedMode(),
* PoissonNoiseExtension::setParallelizationEnabled()
*/
StandardPipeline::SettingsPoissonNoise StandardPipeline::settingsPoissonNoise()
{
return { *_extPoisson };
}
/*!
* Returns a handle to the settings for the spectral effects simulation.
*
* Spectral effects settings are:
* - setSamplingResolution(float energyBinWidth): sets the energy bin width used to sample the
* spectrum to \a energyBinWidth (in keV) [ default value: 0 (i.e. resolution determined
* automatically based on sampling hint of source component) ]
*
* Example:
* \code
* StandardPipeline pipe;
* pipe.settingsSpectralEffects().setSamplingResolution(5.0f);
* \endcode
*
* \sa SpectralEffectsExtension::setSpectralSamplingResolution()
*/
StandardPipeline::SettingsSpectralEffects StandardPipeline::settingsSpectralEffects()
{
return { *_extSpectral };
}
/*!
* Returns a handle to the settings for the ray caster projector.
*
* Ray caster settings are:
* - setInterpolation(bool enabled): sets the use of interpolation in the OpenCL kernel to
* \a enabled; disable interpolation when your OpenCL device does not have image support
* [ default value: true (i.e. interpolation enabled) ]
* - setRaysPerPixel(const QSize& sampling): sets the number of rays cast per pixel to \a sampling
* (width x height) [ default value: {1, 1} ]
* - setRaySampling(float sampling): sets the step length used to traverse the ray to \a sampling,
* which is defined as the fraction of the length of a voxel in its shortest dimension [ default
* value: 0.3 ]
* - setVolumeUpSampling(uint upSamplingFactor): sets the factor for upsampling of the input volume
* data to \a upSamplingFactor [ default value: 1 (i.e. no upsampling) ]
*
* Example:
* \code
* StandardPipeline pipe;
* pipe.settingsRayCaster().setRaysPerPixel( { 2, 2 } );
* pipe.settingsRayCaster().setVolumeUpSampling(2);
* \endcode
*
* \sa OCL::RayCasterProjector::settings()
*/
StandardPipeline::SettingsRayCaster StandardPipeline::settingsRayCaster()
{
return { *_projector };
}
// ###############
// private methods
// ###############
/*!
* Returns the position of the areal focal spot extension in the standard pipeline.
* This is defined to always be the first position (maximum efficiency).
*/
uint StandardPipeline::posAFS() const
{
return 0;
}
/*!
* Returns the position of the detector saturation extension in the standard pipeline.
* This is defined to always be the last position, as it is only accurate in this spot.
*/
uint StandardPipeline::posDetSat() const
{
return uint(_arealFSEnabled) + uint(_spectralEffEnabled) + uint(_poissonEnabled);
}
/*!
* Returns the position of the Poisson noise extension in the standard pipeline.
* Depending on whether the mode has been set to StandardPipeline::No_Approximation or not (i.e.
* StandardPipeline::Full_Approximation or StandardPipeline::Default_Approximation), the
* Poisson extension is placed before or after the spectral effects extension, respectively.
*/
uint StandardPipeline::posPoisson() const
{
return (_approxMode == No_Approximation) ? uint(_arealFSEnabled)
: uint(_arealFSEnabled) + uint(_spectralEffEnabled);
}
/*!
* Returns the position of the spectral effects extension in the standard pipeline.
* Depending on whether the mode has been set to StandardPipeline::No_Approximation or not (i.e.
* StandardPipeline::Full_Approximation or StandardPipeline::Default_Approximation), the
* spectral effects extension is placed after or before the Poisson noise extension, respectively.
*/
uint StandardPipeline::posSpectral() const
{
return (_approxMode == No_Approximation) ? uint(_arealFSEnabled) + uint(_poissonEnabled)
: uint(_arealFSEnabled);
}
void StandardPipeline::SettingsPoissonNoise::setFixedSeed(uint seed)
{
_ext.setFixedSeed(seed);
}
void StandardPipeline::SettingsPoissonNoise::setRandomSeedMode()
{
_ext.setRandomSeedMode();
}
void StandardPipeline::SettingsPoissonNoise::setParallelizationMode(bool enabled)
{
_ext.setParallelizationEnabled(enabled);
}
void StandardPipeline::SettingsAFS::setDiscretization(const QSize& discretization)
{
_ext.setDiscretization(discretization);
}
void StandardPipeline::SettingsAFS::enableLowExtinctionApproximation(bool enable)
{
_ext.enableLowExtinctionApproximation(enable);
}
void StandardPipeline::SettingsDetectorSaturation::setSpectralSamples(uint nbSamples)
{
_ext.setIntensitySampling(nbSamples);
}
void StandardPipeline::SettingsSpectralEffects::setSamplingResolution(float energyBinWidth)
{
_ext.setSpectralSamplingResolution(energyBinWidth);
}
void StandardPipeline::SettingsRayCaster::setInterpolation(bool enabled)
{
_proj.settings().interpolate = enabled;
}
void StandardPipeline::SettingsRayCaster::setRaysPerPixel(const QSize& sampling)
{
_proj.settings().raysPerPixel[0] = static_cast<uint>(sampling.width());
_proj.settings().raysPerPixel[1] = static_cast<uint>(sampling.height());
}
void StandardPipeline::SettingsRayCaster::setRaySampling(float sampling)
{
_proj.settings().raySampling = sampling;
}
void StandardPipeline::SettingsRayCaster::setVolumeUpSampling(uint upSamplingFactor)
{
_proj.settings().volumeUpSampling = upSamplingFactor;
}
/*!
* \enum StandardPipeline::ApproximationPolicy
* Enumeration for the approximation behavior in the standard pipeline. See Detailed Description
* for more details.
*/
/*! \var StandardPipeline::ApproximationPolicy StandardPipeline::Full_Approximation,
* Same configuration as in Default_Approximation setting. Additionally, a linearized approach is
* used in the ArealFocalSpotExtension (if enabled).
* Not suited in combination with a spectral detector response and inaccurate in case of high
* extinction gradients (e.g. edges of highly absorbing material) in the projection images.
*/
/*! \var StandardPipeline::ApproximationPolicy StandardPipeline::Default_Approximation,
* The default setting for the StandardPipeline.
* Configuration in which Poisson noise addition is applied to final result of the spectral effects
* simulation. Approximation with substantially increased computation speed. Not suited in
* combination with a spectral detector response.
*/
/*! \var StandardPipeline::ApproximationPolicy StandardPipeline::No_Approximation
* Configuration with spectral effects simulation wrapping Poisson noise addition for each energy
* bin. Approximation-free but increased computation effort. Can be used in combination with a
* spectral detector response.
*/
} // namespace CTL
| 36.117391 | 101 | 0.726255 |
30d8ff7f806b8df3c1432089cc2fa984b9b9120e | 2,508 | cpp | C++ | Count_test.cpp | som-dev/Count | 68caf6014ce067ac0e0129454db2c6b131f3380d | [
"MIT"
] | null | null | null | Count_test.cpp | som-dev/Count | 68caf6014ce067ac0e0129454db2c6b131f3380d | [
"MIT"
] | null | null | null | Count_test.cpp | som-dev/Count | 68caf6014ce067ac0e0129454db2c6b131f3380d | [
"MIT"
] | null | null | null | #include "DefineCounters.hpp"
#include "gtest/gtest.h"
namespace // anonymous
{
template <typename T>
class CounterTest : public ::testing::Test
{
public:
typedef Count::Counter<T> Counter;
};
using CounterTestTypes = ::testing::Types<
char, unsigned char,
short, unsigned short,
int, unsigned int,
long int, unsigned long int,
size_t>;
TYPED_TEST_SUITE(CounterTest, CounterTestTypes);
TYPED_TEST(CounterTest, Constructor)
{
std::string expectedCounterName = "Test Counter Name";
typename TestFixture::Counter counter(expectedCounterName);
EXPECT_EQ(counter, 0);
EXPECT_EQ(counter.Name(), expectedCounterName);
}
TYPED_TEST(CounterTest, PostIncrement)
{
typename TestFixture::Counter counter("Test");
EXPECT_EQ(counter++, 0);
EXPECT_EQ(counter++, 1);
EXPECT_EQ(counter++, 2);
}
TYPED_TEST(CounterTest, PreIncrement)
{
typename TestFixture::Counter counter("Test");
EXPECT_EQ(++counter, 1);
EXPECT_EQ(++counter, 2);
EXPECT_EQ(++counter, 3);
}
TYPED_TEST(CounterTest, operator_plus_equal)
{
typename TestFixture::Counter counter("Test");
EXPECT_EQ(counter += 10, 10);
}
TYPED_TEST(CounterTest, operator_assignment)
{
typename TestFixture::Counter counter("Test");
counter = 123;
EXPECT_EQ(counter, 123);
}
DEFINE_COUNTERS(TestCounters, A,
B, C, TestCounterD );
TEST(DefineCounters, ConstructorSizeName)
{
TestCounters counters;
EXPECT_EQ(counters.Size(), 4);
EXPECT_EQ(counters.get<TestCounters::A>(), 0);
EXPECT_EQ(counters.get<TestCounters::B>(), 0);
EXPECT_EQ(counters.get<TestCounters::C>(), 0);
EXPECT_EQ(counters.get<TestCounters::C>(), 0);
EXPECT_EQ(counters.get<TestCounters::A>().Name(), "A");
EXPECT_EQ(counters.get<TestCounters::B>().Name(), "B");
EXPECT_EQ(counters.get<TestCounters::C>().Name(), "C");
EXPECT_EQ(counters.get<TestCounters::TestCounterD>().Name(), "TestCounterD");
}
DEFINE_COUNTERS(TestCountersForReset, A, B, C);
TEST(DefineCounters, Reset)
{
TestCountersForReset counters;
counters.get<counters.A>() = 10;
counters.get<counters.B>() = 100;
counters.get<counters.C>() = 1000;
EXPECT_EQ(counters.get<counters.A>(), 10);
EXPECT_EQ(counters.get<counters.B>(), 100);
EXPECT_EQ(counters.get<counters.C>(), 1000);
counters.Reset();
EXPECT_EQ(counters.get<counters.A>(), 0);
EXPECT_EQ(counters.get<counters.B>(), 0);
EXPECT_EQ(counters.get<counters.C>(), 0);
}
} // namespace anonymous
| 26.680851 | 81 | 0.689793 |
30dd8562f1660168b8dfe9e37926033955f4dcb3 | 1,448 | hpp | C++ | test/include/nuschl/unittests/vector_printer.hpp | behlec/nuschl | 35dbdd6dca8e59387623cc8a23f71324e07ea98c | [
"MIT"
] | null | null | null | test/include/nuschl/unittests/vector_printer.hpp | behlec/nuschl | 35dbdd6dca8e59387623cc8a23f71324e07ea98c | [
"MIT"
] | null | null | null | test/include/nuschl/unittests/vector_printer.hpp | behlec/nuschl | 35dbdd6dca8e59387623cc8a23f71324e07ea98c | [
"MIT"
] | null | null | null | #pragma once
// clang-format off
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
// clang-format on
#include <nuschl/s_exp.hpp>
#include <iostream>
#include <vector>
std::ostream &operator<<(std::ostream &os, const std::vector<int> &vec);
std::ostream &operator<<(std::ostream &os, const std::vector<std::string> &vec);
std::ostream &operator<<(std::ostream &os,
const std::vector<std::vector<std::string>> &vec);
std::ostream &operator<<(std::ostream &os,
const std::vector<const nuschl::s_exp *> &vec);
namespace boost {
namespace test_tools {
namespace tt_detail {
template <> struct print_log_value<std::vector<int>> {
void operator()(std::ostream &os, std::vector<int> const &vec) {
::operator<<(os, vec);
}
};
template <> struct print_log_value<std::vector<std::string>> {
void operator()(std::ostream &os, std::vector<std::string> const &vec) {
::operator<<(os, vec);
}
};
template <> struct print_log_value<std::vector<std::vector<std::string>>> {
void operator()(std::ostream &os,
std::vector<std::vector<std::string>> const &vec) {
::operator<<(os, vec);
}
};
template <> struct print_log_value<std::vector<const nuschl::s_exp *>> {
void operator()(std::ostream &os,
std::vector<const nuschl::s_exp *> const &vec) {
::operator<<(os, vec);
}
};
}
}
}
| 27.846154 | 80 | 0.61326 |
30e4366ca4acaeb0c34139660604e0b0fb006729 | 354 | hh | C++ | app/jni/live/BasicUsageEnvironment/include/BasicUsageEnvironment_version.hh | 8kEatRadish/Live555OnAndroid | 255df615f251ac7827d379a679b2b60e7af6be51 | [
"Apache-2.0"
] | 3 | 2021-03-30T13:24:22.000Z | 2021-12-15T04:11:34.000Z | app/jni/live/BasicUsageEnvironment/include/BasicUsageEnvironment_version.hh | 8kEatRadish/Live555OnAndroid | 255df615f251ac7827d379a679b2b60e7af6be51 | [
"Apache-2.0"
] | null | null | null | app/jni/live/BasicUsageEnvironment/include/BasicUsageEnvironment_version.hh | 8kEatRadish/Live555OnAndroid | 255df615f251ac7827d379a679b2b60e7af6be51 | [
"Apache-2.0"
] | 2 | 2022-01-20T09:39:16.000Z | 2022-03-25T08:38:39.000Z | // Version information for the "BasicUsageEnvironment" library
// Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved.
#ifndef _BASICUSAGEENVIRONMENT_VERSION_HH
#define _BASICUSAGEENVIRONMENT_VERSION_HH
#define BASICUSAGEENVIRONMENT_LIBRARY_VERSION_STRING "2015.01.04"
#define BASICUSAGEENVIRONMENT_LIBRARY_VERSION_INT 1420329600
#endif
| 32.181818 | 68 | 0.847458 |
30e549f21dcaeb32f35b09eac05118becd16f41b | 1,842 | cpp | C++ | COCI/PATULJCI.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | 1 | 2017-10-01T00:51:39.000Z | 2017-10-01T00:51:39.000Z | COCI/PATULJCI.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | COCI/PATULJCI.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
int N,C,M;
int cs[300001];
vector<int> cis[10001];
int cunt(int a,int b,int c)
{
return upper_bound(cis[c].begin(),cis[c].end(),b)-lower_bound(cis[c].begin(),cis[c].end(),a);
}
int tree[2000000];
void update(int node,int a,int b)
{
if(a > b) return;
if(a == b) {
tree[node] = cs[a];
return;
}
update(node*2, a, (a+b)/2);
update(node*2+1, (a+b)/2+1, b);
if(tree[node*2] == tree[node*2+1]) {
tree[node] = tree[node*2];
} else {
int c1 = cunt(a,b,tree[node*2]);
int c2 = cunt(a,b,tree[node*2+1]);
if(c1 > c2 && c1 > (b-a+1)/2)
tree[node] = tree[node*2];
else if( c2 > c1 && c2 > (b-a+1)/2)
tree[node] = tree[node*2+1];
else
tree[node] = 0;
}
}
int query(int node, int a,int b,int i,int j)
{
if( a > b || j < a || i > b) return 0;
//printf("%d %d %d %d %d: %d\n",node, a,b,i,j,tree[node]);
if( a>=i && b<=j ) return tree[node];
int c1 = query(node*2, a,(a+b)/2,i,j);
int c2 = query(node*2+1, (a+b)/2+1,b,i,j);
if(c1 == c2) {
return c1;
} else {
//i - j
int n1 = cunt(i,j,c1);
int n2 = cunt(i,j,c2);
if(n1 > n2 && n1 > (j-i+1)/2)
return c1;
else if( n2 > n1 && n2 > (j-i+1)/2)
return c2;
else
return 0;
}
}
int main()
{
scanf("%d%d",&N,&C);
for(int i=1;i<=N;i++)
{
scanf("%d",cs+i);
cis[cs[i]].push_back(i);
}
update(1,1,N);
scanf("%d",&M);
for(int i=0;i!=M;i++)
{
int a,b;
scanf("%d%d",&a,&b);
int c = query(1,1,N,a,b);
if(!c) {
cout << "no" << endl;
} else {
cout << "yes " << c << endl;
}
}
return 0;
} | 19.1875 | 95 | 0.505972 |
30e7d2e53190c7233c9b8b7e6a1b419d84210a71 | 7,271 | cpp | C++ | src/tests/gmath.cpp | Pnikanti/gmath | 4e2de0546b3ca19d2571ec30784a482e90b57382 | [
"MIT"
] | null | null | null | src/tests/gmath.cpp | Pnikanti/gmath | 4e2de0546b3ca19d2571ec30784a482e90b57382 | [
"MIT"
] | null | null | null | src/tests/gmath.cpp | Pnikanti/gmath | 4e2de0546b3ca19d2571ec30784a482e90b57382 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include <catch2.h>
#include "gmath.h"
TEST_CASE("vector2 calculations", "[!mayfail]")
{
SECTION("Sum of two vectors should provide correct output")
{
vec2f a = vec2f(2.0f, 1.0f) + vec2f(3.0f, 4.2f);
REQUIRE(a == vec2f(5.0f, 5.2f));
}
SECTION("Difference of two vectors should provide correct output")
{
vec2f a = vec2f(10.2f, 763.0f) - vec2f(5.2f, 760.0f);
REQUIRE(a == vec2f(5.0f, 3.0f));
}
SECTION("Product of two vectors should provide correct output")
{
vec2f a = vec2f(5.0f) * vec2f(1.0f, 5.0f);
REQUIRE(a == vec2f(5.0f, 25.0f));
}
SECTION("Sum of vector and scalar should provide correct output")
{
vec2f a = vec2f(5.0f, 2.5f) + 1.0f;
REQUIRE(a == vec2f(6.0f, 3.5f));
}
SECTION("Difference of vector and scalar should provide correct output")
{
vec2f a = vec2f(5.0f, 1.4f) - 0.3f;
REQUIRE(a == vec2f(4.7f, 1.1f));
}
SECTION("Quotient of vector and scalar should provide correct output")
{
vec2f a = vec2f(2.5f, 5.0f) / 2.0f;
REQUIRE(a == vec2f(1.25f, 2.5f));
}
SECTION("Product of vector and scalar should provide correct output")
{
vec2f a = vec2f(2.5f, 5.0f) * 2.0f;
REQUIRE(a == vec2f(5.0f, 10.0f));
}
}
TEST_CASE("vector3 calculations", "[!mayfail]")
{
SECTION("Sum of two vectors should provide correct output")
{
vec3f a = vec3f(2.0f, 1.0f, 2.0f) + vec3f(3.0f, 4.2f, 3.0f);
REQUIRE(a == vec3f(5.0f, 5.2f, 5.0f));
}
SECTION("Difference of two vectors should provide correct output")
{
vec3f a = vec3f(10.2f, 763.0f, 0.5f) - vec3f(5.2f, 760.0f, 0.2f);
REQUIRE(a == vec3f(5.0f, 3.0f, 0.3f));
}
SECTION("Product of two vectors should provide correct output")
{
vec3f a = vec3f(5.0f) * vec3f(1.0f, 5.0f, 0.0f);
REQUIRE(a == vec3f(5.0f, 25.0f, 0.0f));
}
SECTION("Sum of vector and scalar should provide correct output")
{
vec3f a = vec3f(5.0f, 2.5f, 7.0f) + 1.0f;
REQUIRE(a == vec3f(6.0f, 3.5f, 8.0f));
}
SECTION("Difference of vector and scalar should provide correct output")
{
vec3f a = vec3f(5.0f, 1.4f, 0.3f) - 0.3f;
REQUIRE(a == vec3f(4.7f, 1.1f, 0.0f));
}
SECTION("Quotient of vector and scalar should provide correct output")
{
vec3f a = vec3f(2.5f, 5.0f, 10.0f) / 2.0f;
REQUIRE(a == vec3f(1.25f, 2.5f, 5.0f));
}
SECTION("Product of vector and scalar should provide correct output")
{
vec3f a = vec3f(2.5f, 5.0f, 10.0f) * 2.0f;
REQUIRE(a == vec3f(5.0f, 10.0f, 20.0f));
}
}
TEST_CASE("vector4 calculations", "[!mayfail]")
{
SECTION("Sum of two vectors should provide correct output")
{
vec4f a = vec4f(2.0f, 1.0f, 2.0f, 0.2f) + vec4f(3.0f, 4.2f, 3.0f, 0.5f);
REQUIRE(a == vec4f(5.0f, 5.2f, 5.0f, 0.7f));
}
SECTION("Difference of two vectors should provide correct output")
{
vec4f a = vec4f(10.2f, 763.0f, 0.5f, 0.2f) - vec4f(5.2f, 760.0f, 0.2f, 0.1f);
REQUIRE(a == vec4f(5.0f, 3.0f, 0.3f, 0.1f));
}
SECTION("Product of two vectors should provide correct output")
{
vec4f a = vec4f(5.0f) * vec4f(1.0f, 5.0f, 0.0f, 25.0f);
REQUIRE(a == vec4f(5.0f, 25.0f, 0.0f, 125.0f));
}
SECTION("Sum of vector and scalar should provide correct output")
{
vec4f a = vec4f(5.0f, 2.5f, 7.0f, 0.0f) + 1.0f;
REQUIRE(a == vec4f(6.0f, 3.5f, 8.0f, 1.0f));
}
SECTION("Difference of vector and scalar should provide correct output")
{
vec4f a = vec4f(5.0f, 1.4f, 0.3f, 0.0f) - 0.3f;
REQUIRE(a == vec4f(4.7f, 1.1f, 0.0f, -0.3f));
}
SECTION("Quotient of vector and scalar should provide correct output")
{
vec4f a = vec4f(2.5f, 5.0f, 10.0f, -5.0f) / 2.0f;
REQUIRE(a == vec4f(1.25f, 2.5f, 5.0f, -2.5f));
}
SECTION("Product of vector and scalar should provide correct output")
{
vec4f a = vec4f(2.5f, 5.0f, 10.0f, -10.0f) * 2.0f;
REQUIRE(a == vec4f(5.0f, 10.0f, 20.0f, -20.0f));
}
}
TEST_CASE("2x2 matrix calculations", "[!mayfail]")
{
SECTION("Sum of two matrices should provide correct output")
{
mat2f a = mat2f(0.5f, 0.1f, 0.2f, 0.3f) +
mat2f(0.5f, 0.9f, 0.8f, 0.7f);
REQUIRE(a == mat2f(1.0f));
}
SECTION("Difference of two matrices should provide correct output")
{
mat2f a = mat2f(1.5f, 2.2f, 10.2f, 5.3f) -
mat2f(0.5f, 1.2f, 9.2f, 4.3f);
REQUIRE(a == mat2f(1.0f));
}
SECTION("Product of two matrices should provide correct output")
{
mat2f a = mat2f(1.5f, 2.2f, 10.2f, 5.3f) *
mat2f(0.5f, 1.2f, 9.2f, 4.3f);
REQUIRE(a == mat2f(12.99f, 7.46f, 57.66f, 43.03f));
}
SECTION("Sum of matrix and scalar should provide correct output")
{
mat2f a = mat2f(1.5f, 2.2f, 10.2f, 5.3f) + 1.0f;
REQUIRE(a == mat2f(2.5f, 3.2f, 11.2f, 6.3f));
}
SECTION("Difference of matrix and scalar should provide correct output")
{
mat2f a = mat2f(1.5f, 2.2f, 10.2f, 5.3f) - 1.0f;
REQUIRE(a == mat2f(0.5f, 1.2f, 9.2f, 4.3f));
}
SECTION("Quotient of matrix and scalar should provide correct output")
{
mat2f a = mat2f(1.5f, 2.2f, 10.2f, 5.3f) / 2.0f;
REQUIRE(a == mat2f(0.75f, 1.1f, 5.1f, 2.65f));
}
SECTION("Product of matrix and scalar should provide correct output")
{
mat2f a = mat2f(1.5f, 2.2f, 10.2f, 5.3f) * 2.0f;
REQUIRE(a == mat2f(3.0f, 4.4f, 20.4f, 10.6f));
}
}
TEST_CASE("3x3 matrix calculations", "[!mayfail]")
{
SECTION("Sum of two matrices should provide correct output")
{
mat3f a = mat3f(0.5f, 0.1f, 0.2f,
0.3f, 0.2f, 0.5f,
0.2f, 0.5f, 0.1f) +
mat3f(0.5f, 0.9f, 0.8f,
0.2f, 0.3f, 0.7f,
0.7f, 0.4f, 0.8f);
REQUIRE(a == mat3f(1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 1.2f,
0.9f, 0.9f, 0.9f
));
}
SECTION("Difference of two matrices should provide correct output")
{
mat3f a = mat3f(1.5f, 1.1f, 1.2f,
1.3f, 1.2f, 1.5f,
1.2f, 1.5f, 1.1f) -
mat3f(0.5f, 0.1f, 0.2f,
0.3f, 0.2f, 0.5f,
0.2f, 0.5f, 0.1f);
REQUIRE(a == mat3f(1.0f));
}
SECTION("Product of two matrices should provide correct output")
{
mat3f a = mat3f(15.5f, 11.1f, 2.2f,
4.3f, 22.2f, 8.5f,
5.2f, 33.5f, 5.1f) *
mat3f(2.5f, 1.1f, 25.2f,
2.3f, 4.2f, 32.5f,
5.2f, 7.5f, 12.1f);
REQUIRE(a == mat3f(
174.52f, 896.37f, 143.37f,
222.71f, 1207.52f, 206.51f,
175.77f, 629.57f, 136.9f
));
}
SECTION("Sum of matrix and scalar should provide correct output")
{
mat3f a = mat3f(0.5f, 0.1f, 0.2f,
0.3f, 0.2f, 0.5f,
0.2f, 0.5f, 0.1f) + 1.0f;
REQUIRE(a == mat3f(1.5f, 1.1f, 1.2f,
1.3f, 1.2f, 1.5f,
1.2f, 1.5f, 1.1f
));
}
SECTION("Difference of matrix and scalar should provide correct output")
{
mat3f a = mat3f(1.5f, -2.2f, 10.2f,
5.3f, 2.3f, 11.1f,
-2.2f, 4.2f, 100.0f) - 1.0f;
REQUIRE(a == mat3f(0.5f, -3.2f, 9.2f,
4.3f, 1.3f, 10.1f,
-3.2f, 3.2f, 99.0f
));
}
SECTION("Quotient of matrix and scalar should provide correct output")
{
mat3f a = mat3f(5.5f, 4.2f, -10.2f,
0.5f, 7.7f, 1.5f,
-5.0f, 3.0f, 100.0f) / 2.0f;
REQUIRE(a == mat3f(2.75f, 2.1f, -5.1f,
0.25f, 3.85f, 0.75f,
-2.5f, 1.5f, 50.0f
));
}
SECTION("Product of matrix and scalar should provide correct output")
{
mat3f a = mat3f(5.5f, 4.2f, -10.2f,
0.5f, 7.7f, 1.5f,
-5.0f, 3.0f, 100.0f) * 2.0f;
REQUIRE(a == mat3f(11.0f, 8.4f, -20.4f,
1.0f, 15.4f, 3.0f,
-10.0f, 6.0f, 200.0f
));
}
} | 24.986254 | 79 | 0.590978 |
30eed884d544b2307a3ba04a3e865cfebe277d50 | 1,028 | cpp | C++ | ui/logview.cpp | VITObelgium/cpp-infra | 2a95a112439b21ff9125c2e6e29810a418b94a4d | [
"MIT"
] | 1 | 2022-02-23T03:15:54.000Z | 2022-02-23T03:15:54.000Z | ui/logview.cpp | VITObelgium/cpp-infra | 2a95a112439b21ff9125c2e6e29810a418b94a4d | [
"MIT"
] | null | null | null | ui/logview.cpp | VITObelgium/cpp-infra | 2a95a112439b21ff9125c2e6e29810a418b94a4d | [
"MIT"
] | null | null | null | #include "uiinfra/logview.h"
#include "ui_logview.h"
#include <qevent.h>
#include <qtimer.h>
namespace inf::ui {
static auto s_maxUpdateInterval = std::chrono::milliseconds(200);
LogView::LogView(QWidget* parent)
: QWidget(parent)
, _ui(std::make_unique<Ui::LogView>())
, _timer(new QTimer(this))
{
_ui->setupUi(this);
connect(_timer, &QTimer::timeout, this, &LogView::updateView);
}
LogView::~LogView() = default;
void LogView::setModel(QAbstractItemModel* model)
{
_ui->tableView->setModel(model);
connect(model, &QAbstractItemModel::rowsInserted, this, [this]() {
if (!_timer->isActive()) {
updateView();
_timer->start(s_maxUpdateInterval);
}
});
}
void LogView::resizeEvent(QResizeEvent* event)
{
_ui->tableView->horizontalHeader()->resizeSection(0, event->size().width());
QWidget::resizeEvent(event);
}
void LogView::updateView()
{
_timer->stop();
if (_ui->tableView->isVisible()) {
_ui->tableView->scrollToBottom();
}
}
}
| 20.56 | 80 | 0.654669 |
30f0492c13b7d0c77afdb5ff14fd3b37c0725986 | 32,079 | cpp | C++ | esl/economics/markets/walras/tatonnement.cpp | vishalbelsare/ESL | cea6feda1e588d5f441742dbb1e4c5479b47d357 | [
"Apache-2.0"
] | 37 | 2019-10-13T12:23:32.000Z | 2022-03-19T10:40:29.000Z | esl/economics/markets/walras/tatonnement.cpp | vishalbelsare/ESL | cea6feda1e588d5f441742dbb1e4c5479b47d357 | [
"Apache-2.0"
] | 3 | 2020-03-20T04:44:06.000Z | 2021-01-12T06:18:33.000Z | esl/economics/markets/walras/tatonnement.cpp | vishalbelsare/ESL | cea6feda1e588d5f441742dbb1e4c5479b47d357 | [
"Apache-2.0"
] | 10 | 2019-11-06T15:59:06.000Z | 2021-08-09T17:28:24.000Z | /// \file tatonnement.hpp
///
/// \brief Implements the tâtonnement process (hill climbing), implemented as a
/// numerical optimisation.
///
/// \authors Maarten P. Scholl
/// \date 2018-02-02
/// \copyright Copyright 2017-2019 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
/// 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.
///
/// You may obtain instructions to fulfill the attribution
/// requirements in CITATION.cff
///
#include <esl/economics/markets/walras/tatonnement.hpp>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_multiroots.h>
#pragma warning(push, 0) // supress warnings in MSVC from external code
#include <adept_source.h>
#pragma warning(pop)
#include <esl/economics/markets/quote.hpp>
#include <esl/data/log.hpp>
#include <esl/mathematics/variable.hpp>
#include <esl/invalid_parameters.hpp>
using esl::economics::markets::tatonnement::excess_demand_model;
using esl::/*mathematics::*/variable;
///
/// \brief C compatible callback for the minimizer to find the function value.
///
/// \param variables
/// \param params Pointer to the excess_demand_model instance
///
extern "C" double c_minimizer_function_value
( const gsl_vector *variables
, void *model)
{
auto *model_ = static_cast<excess_demand_model *>(model);
assert(model_ && "parameter must be (excess_demand_model *)");
return model_->excess_demand_function_value(variables->data);
}
///
/// \req this function should store the vector result f(x,params)
/// in f for argument x and parameters params, returning an appropriate
/// error code if the function cannot be computed.
///
///
extern "C" int
multiroot_function_value_cb(const gsl_vector *x, void *params, gsl_vector *f)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
auto cb_ = model_->multiroot_function_value(x->data);
for(size_t i = 0; i < cb_.size(); ++i){
gsl_vector_set(f, i, cb_[i]);
}
return GSL_SUCCESS;
}
#if !defined(ADEPT_VERSION) || !defined(ADEPT_NO_AUTOMATIC_DIFFERENTIATION)
///
/// \brief C wrapper for minimization problem, gsl callback
/// Return gradient of function with respect to each state variable x
///
extern "C" void c_minimizer_function_gradient( const gsl_vector *x
, void *params
, gsl_vector *gradient)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
model_->minimizer_function_value_and_gradient(x->data, gradient->data);
}
///
/// \req this function should store the n-by-n matrix result
/// J_{ij} = \partial f_i(x,\hbox{\it params}) / \partial x_j
/// in J for argument x and parameters params, returning an appropriate
/// error code if the function cannot be computed.
///
///
extern "C" int multiroot_function_jacobian_cb(const gsl_vector * x, void * params, gsl_matrix * df)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
auto cb_ = model_->multiroot_function_value_and_gradient(x->data, df->data);
return GSL_SUCCESS;
}
///
/// \brief C wrapper for minimization problem
///
extern "C" void c_minimizer_function_value_and_gradient
( const gsl_vector *x
, void *params
, double *jacobian
, gsl_vector *gradient
)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
*jacobian = model_->minimizer_function_value_and_gradient(x->data, gradient->data);
}
///
/// \brief
///
extern "C" int multiroot_function_value_and_gradient_cb( const gsl_vector *x
, void *params
, gsl_vector *f
, gsl_matrix *df
)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
auto cb_ = model_->multiroot_function_value_and_gradient(x->data, df->data);
for(size_t i = 0; i < cb_.size(); ++i){
gsl_vector_set(f, i, cb_[i]);
}
return GSL_SUCCESS;
}
extern "C" double uniroot_function_value (double x, void *params)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
auto cb_ = model_->multiroot_function_value(&x);
return cb_[0];
}
extern "C" double uniroot_function_value_and_gradient (double x, void *params)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
double df = 0.;
auto cb_ = model_->multiroot_function_value_and_gradient(&x, &df);
return df;
}
extern "C" void uniroot_function_jacobian_cb ( double x
, void *params
, double *f
, double *df)
{
auto *model_ = static_cast<excess_demand_model *>(params);
assert(model_ && "parameter must be (excess_demand_model *)");
double jacobian_ = 0.;
auto cb_ = model_->multiroot_function_value_and_gradient(&x, &jacobian_);
*f = cb_[0];
if(!std::isfinite(jacobian_)){
jacobian_ = (x-1);
}
*df = jacobian_;
}
#endif
///
/// \brief Callback for errors from the optimizer.
/// \details We silence errors
///
/// \param reason
/// \param file
/// \param line
/// \param gsl_errno
void handler ([[maybe_unused]] const char *reason,
[[maybe_unused]] const char *file,
[[maybe_unused]] int line,
[[maybe_unused]] int gsl_errno)
{
}
namespace esl::economics::markets::tatonnement {
///
/// \brief Initializes a stack for automatic differentiation
///
/// \param initial_quotes
excess_demand_model::excess_demand_model(
law::property_map<quote> initial_quotes)
: quotes(initial_quotes)
#if defined(ADEPT_VERSION)
, stack_()
#endif
{
}
excess_demand_model::~excess_demand_model() = default;
///
/// \brief The optimisation version of the market clearing problem,
/// with automatic differentiation
///
/// \param x
/// \return
adept::adouble excess_demand_model::demand_supply_mismatch(const adept::adouble *x)
{
std::map<identity<law::property>,
std::tuple<quote, adept::adouble>>
quote_scalars_;
size_t n = 0;
for(auto [k, v]: quotes) {
quote_scalars_.emplace(*k, std::make_tuple(v, x[n]));
++n;
}
std::map<identity<law::property>, adept::adouble> terms_map;
for(const auto &f : excess_demand_functions_) {
auto demand_per_property_ = f->excess_demand(quote_scalars_);
for(auto [k, v]: demand_per_property_) {
if(terms_map.find(k) == terms_map.end()){
terms_map.emplace(k, v);
}else{
(terms_map.find(k)->second) += v;
}
}
}
variable target_ = 0.0;
for(auto [p, t] : terms_map) {
(void)p;
target_ += (pow(t, 2));
}
//LOG(notice) << " clearing error " << target_.value() << std::endl;
return target_;
}
///
/// \brief Root-finding version of the market clearing problem.
///
/// \details Tries to set excess demand for all goods to zero, for all
/// goods individually.
/// \param x
/// \return
std::vector<variable>
excess_demand_model::excess_demand(const variable *x)
{
std::map<identity<law::property>, std::tuple<quote, variable>> quote_scalars_;
size_t n = 0;
for(auto [k, v]: quotes) {
quote_scalars_.emplace(*k, std::make_tuple(v, x[n]));
++n;
}
std::map<identity<law::property>, variable> terms_map;
for(const auto &f : excess_demand_functions_) {
auto demand_per_property_ = f->excess_demand(quote_scalars_);
for(auto [k, ed]: demand_per_property_) {
auto i = terms_map.emplace(k, variable(0.));
i.first->second += ed;//long_ + ed - short_;
}
}
std::vector<variable> result_;
for(auto [k, v]: quotes) {
assert(terms_map.end() != terms_map.find(*k));
result_.push_back(terms_map.find(*k)->second);
}
return result_;
}
///
/// \brief Used to convert the optimization version of the problem back to
/// machine double precision floats.
/// Also uused when not using automatic differentiation.
///
/// \param multipliers Price multipliers
/// \return
double excess_demand_model::excess_demand_function_value(const double *multipliers)
{
stack_.pause_recording();
for(unsigned int i = 0; i < active_.size(); ++i) {
active_[i] = multipliers[i];
}
double result = adept::value(demand_supply_mismatch(&active_[0]));
stack_.continue_recording();
return result;
}
///
/// \brief Wraps the root finding problem (value only)
///
/// \param x
/// \return
std::vector<double> excess_demand_model::multiroot_function_value(const double *multipliers)
{
stack_.pause_recording();
for(unsigned int i = 0; i < active_.size(); ++i) {
active_[i] = multipliers[i];
}
auto intermediate_ = excess_demand(&active_[0]);
std::vector<double> result;
for(const auto &v: intermediate_){
result.push_back(adept::value(v));
}
stack_.continue_recording();
return result;
}
///
/// \brief wrapper for minimization problem, value and gradient
///
/// \param x
/// \param dJ_dx
/// \return
double
excess_demand_model::minimizer_function_value_and_gradient(const double *multipliers, double *derivatives)
{
for(unsigned int i = 0; i < active_.size(); ++i) {
active_[i] = multipliers[i];
}
stack_.new_recording();
adept::adouble derivative_ = demand_supply_mismatch(&active_[0]);
// in the minimization problem, the output is a single scalar
derivative_.set_gradient(1.0);
stack_.compute_adjoint();
adept::get_gradients(&active_[0], active_.size(), derivatives);
return adept::value(derivative_);
}
///
/// \brief Root-finding version, value and gradient wrapper.
///
/// \param multipliers Price multipliers
/// \param jacobian output for jacobian matrix
/// \return
std::vector<double>
excess_demand_model::multiroot_function_value_and_gradient
( const double *multipliers
, double *jacobian
)
{
for(unsigned int i = 0; i < active_.size(); ++i) {
active_[i] = multipliers[i];
}
stack_.new_recording();
auto values_ = excess_demand(&active_[0]);
stack_.independent(&active_[0], active_.size());
stack_.dependent(&values_[0], values_.size());
stack_.jacobian(jacobian);
std::vector<double> result_;
for(auto &v : values_) {
result_.emplace_back(adept::value(v));
}
return result_;
}
///
/// \brief Goes through the selected solution methods and applies them.
///
/// \return numerical approximate multipliers for the quotes
std::optional<std::map<identity<law::property>, double>>
excess_demand_model::compute_clearing_quotes(size_t max_iterations)
{
if(methods.empty()){
const auto error_no_solvers_ = "no solution method specified";
LOG(errorlog) << error_no_solvers_ << std::endl;
throw esl::invalid_parameters(error_no_solvers_);
}
for(auto method_: methods){
// for every method we try, we need to reset our variables
active_.clear();
std::vector<identity<law::property>> mapping_index_;
mapping_index_.reserve(quotes.size());
// initial values are the solutions at the previous time step, or
// the initial values provided to the model if this is the first
for(auto [k, v] : quotes) {
(void) v;
mapping_index_.emplace_back(*k);
active_.emplace_back(1.0 );
}
// root finding methods try to set excess demand to zero for
// all properties traded in the market
if (method_ == root){
// This compile time definition is here such that the library will still compile
// when Adept is absent.
#if defined(ADEPT_VERSION) && !defined(ADEPT_NO_AUTOMATIC_DIFFERENTIATION)
// if there is only one property traded, we specialize with
// algorithms that do well on univariate root finding
if(1 == quotes.size()){
constexpr double absolute_tolerance = 1e-6;
// capture previous error handler to restore later
auto old_handler_ = gsl_set_error_handler (&handler);
// solver and solver type
const gsl_root_fdfsolver_type *solver_type_;
gsl_root_fdfsolver *s;
// the initial guess is 1 times the previous quote
double xt = 1.;
// the function structure with gradient and jacobian
gsl_function_fdf target_;
target_.f = &uniroot_function_value;
target_.df = &uniroot_function_value_and_gradient;
target_.fdf = &uniroot_function_jacobian_cb;
target_.params = static_cast<void *>(this);
// use steffenson's method
// Newton algorithm with an Aitken "delta-squared" acceleration
solver_type_ = gsl_root_fdfsolver_steffenson;
s = gsl_root_fdfsolver_alloc (solver_type_);
gsl_root_fdfsolver_set (s, &target_, xt);
size_t iteration_ = 0;
int status_;
double best_quote_ = 1.0;
double best_error_ = uniroot_function_value(best_quote_, this);//std::numeric_limits<double>::max();
do {
++iteration_;
// perform one solver step
status_ = gsl_root_fdfsolver_iterate(s);
// store initial position to compute delta
xt = gsl_root_fdfsolver_root(s);
auto errors_ = uniroot_function_value(xt, this);
if(abs(errors_) < abs(best_error_)){
best_error_ = errors_;
best_quote_ = xt;
}
if(abs(errors_) < absolute_tolerance){
status_ = GSL_SUCCESS;
break;
}
//status_ = gsl_root_test_delta (xt, x0, delta_absolute_tolerance, delta_relative_tolerance);
} while (GSL_CONTINUE == status_ && iteration_ < max_iterations);
if (GSL_SUCCESS == status_) {
std::map<esl::identity<esl::law::property>, double> result_;
// apply circuit breaker retro-actively
best_quote_ = std::max(best_quote_, circuit_breaker.first);
best_quote_ = std::min(best_quote_, circuit_breaker.second);
result_.emplace(mapping_index_[0], best_quote_);
gsl_root_fdfsolver_free (s);
return result_;
}
gsl_root_fdfsolver_free (s);
// reset the old error handler.
gsl_set_error_handler(old_handler_);
} else {
// else, we solve for multiple roots at once
// TODO: set adaptively
constexpr double residual_tolerance = 1e-4;
gsl_multiroot_function_fdf target_;
target_.n = active_.size();
target_.f = &multiroot_function_value_cb;
target_.df = &multiroot_function_jacobian_cb;
target_.fdf = &multiroot_function_value_and_gradient_cb;
target_.params = static_cast<void *>(this);
gsl_vector *variables_ = gsl_vector_alloc(active_.size());
for (size_t i = 0; i < active_.size(); ++i) {
// initial solution is 1.0 times previous prices
gsl_vector_set(variables_, i, 1.);
}
// modified version of Powell’s Hybrid method
const gsl_multiroot_fdfsolver_type *solver_t_ = gsl_multiroot_fdfsolver_hybridsj;
gsl_multiroot_fdfsolver *solver_ = gsl_multiroot_fdfsolver_alloc(solver_t_, active_.size());
gsl_multiroot_fdfsolver_set(solver_, &target_, variables_);
int status = GSL_CONTINUE;
for (size_t i = 0; i < max_iterations && GSL_CONTINUE == status; ++i) {
status = gsl_multiroot_fdfsolver_iterate(solver_);
if (GSL_SUCCESS != status) {
break;
}
status = gsl_multiroot_test_residual(solver_->f, residual_tolerance);
}
if (GSL_SUCCESS == status) {
std::map<esl::identity<law::property>, double> result_;
auto solver_best_ = gsl_multiroot_fdfsolver_root(solver_);
for (size_t i = 0; i < active_.size(); ++i) {
auto scalar_ = gsl_vector_get(solver_best_, i);
// apply circuit breaker
scalar_ = std::min(scalar_, circuit_breaker.second);
scalar_ = std::max(scalar_, circuit_breaker.first);
result_.emplace(mapping_index_[i], scalar_);
}
gsl_multiroot_fdfsolver_free(solver_);
gsl_vector_free(variables_);
return result_;
}
gsl_multiroot_fdfsolver_free(solver_);
gsl_vector_free(variables_);
}
#else
constexpr double residual_tolerance = 1e-4;
gsl_multiroot_function root_function;
root_function.n = active_.size();
root_function.f = &multiroot_function_value_cb;
//root_function.df = &multiroot_function_jacobian_cb;
//root_function.fdf = &multiroot_function_value_and_gradient_cb;
root_function.params = static_cast<void *>(this);
gsl_vector *variables_ = gsl_vector_alloc(active_.size());
for(size_t i = 0; i < active_.size(); ++i) {
gsl_vector_set(variables_, i, 1.0);
}
// Powell's Hybrid method, but with finite-difference approximation
const gsl_multiroot_fsolver_type *solver_t_ = gsl_multiroot_fsolver_hybrids;
gsl_multiroot_fsolver *solver_ = gsl_multiroot_fsolver_alloc(solver_t_, active_.size());
gsl_multiroot_fsolver_set (solver_, &root_function, variables_);
int status = GSL_CONTINUE;
for(size_t iter = 0; iter < max_iterations && GSL_CONTINUE == status; ++iter){
status = gsl_multiroot_fsolver_iterate (solver_);
if (GSL_SUCCESS != status){
break;
}
status = gsl_multiroot_test_residual (solver_->f, residual_tolerance);
}
std::map<esl::identity<esl::law::property>, double> result_;
for(size_t i = 0; i < active_.size(); ++i) {
result_.emplace(mapping_index_[i], gsl_vector_get(solver_->x, i));
}
gsl_multiroot_fsolver_free (solver_);
gsl_vector_free(variables_);
#endif
continue;
}else if (method_ == minimization){
// If Adept is absent
#if !defined(ADEPT_VERSION) || !defined(ADEPT_NO_AUTOMATIC_DIFFERENTIATION)
// TODO: set adaptively
constexpr double initial_step_size = 1.0e-5;
constexpr double line_search_tolerance = 1.0e-5;
constexpr double converged_gradient_norm = 1.0e-4;
constexpr double error_tolerance = 0.0001;
// we use the vector Broyden-Fletcher-Goldfarb-Shanno algorithm
const auto *minimizer_type = gsl_multimin_fdfminimizer_vector_bfgs2;
gsl_multimin_function_fdf target_;
target_.n = active_.size();
target_.f = c_minimizer_function_value;
target_.df = c_minimizer_function_gradient;
target_.fdf = c_minimizer_function_value_and_gradient;
target_.params = static_cast<void *>(this);
gsl_vector *x = gsl_vector_alloc(active_.size());
for(size_t i = 0; i < active_.size(); ++i) {
// initial solution is 1.0 * previous quote
gsl_vector_set(x, i, 1.0);
}
auto *minimizer =
gsl_multimin_fdfminimizer_alloc(minimizer_type, active_.size());
gsl_multimin_fdfminimizer_set(minimizer, &target_, x,
initial_step_size, line_search_tolerance);
size_t iteration_ = 0;
int status;
do {
++iteration_;
status = gsl_multimin_fdfminimizer_iterate(minimizer);
std::vector<double> solution_;
for(size_t param = 0; param < active_.size(); ++param){
solution_.push_back(gsl_vector_get (minimizer->x, param));
}
auto error_ = excess_demand_function_value(&solution_[0]);
if(error_ <= error_tolerance){
status = GSL_SUCCESS;
break;
}
if(status != GSL_SUCCESS) {
break;
}
status = gsl_multimin_test_gradient(minimizer->gradient,
converged_gradient_norm);
} while(GSL_CONTINUE == status && iteration_ < max_iterations);
if(status == GSL_SUCCESS){
std::map<esl::identity<esl::law::property>, double> result_;
for(size_t i = 0; i < active_.size(); ++i) {
auto scalar_ = gsl_vector_get (minimizer->x, i);
result_.insert({mapping_index_[i], scalar_});
}
gsl_multimin_fdfminimizer_free(minimizer);
gsl_vector_free(x);
return result_;
}
gsl_multimin_fdfminimizer_free(minimizer);
gsl_vector_free(x);
#else
LOG(errorlog) << "gradient-free minimizer failed after " << iteration_
<< " iterations: " << gsl_strerror(status) << std::endl;
#endif
}else if (method_ == derivative_free_minimization) {
// TODO: set adaptively
auto initial_step_size = gsl_vector_alloc(active_.size());
constexpr double error_tolerance = 0.0001;
// we use the vector Broyden-Fletcher-Goldfarb-Shanno algorithm
const gsl_multimin_fminimizer_type *minimizer_type =
gsl_multimin_fminimizer_nmsimplex2;
//const auto *minimizer_type = gsl_multimin_fdfminimizer_vector_bfgs2;
gsl_multimin_function target_;
target_.n = active_.size();
target_.f = c_minimizer_function_value;
//target_.df = c_minimizer_function_gradient;
//target_.fdf = c_minimizer_function_value_and_gradient;
target_.params = static_cast<void *>(this);
gsl_vector *x = gsl_vector_alloc(active_.size());
for(size_t i = 0; i < active_.size(); ++i) {
// initial solution is 1.0 * previous quote
gsl_vector_set(x, i, 1.0);
}
auto *minimizer =
gsl_multimin_fminimizer_alloc (minimizer_type, active_.size());
gsl_multimin_fminimizer_set (minimizer, &target_, x,
initial_step_size
//, line_search_tolerance
);
size_t iteration_ = 0;
int status;
do {
++iteration_;
status = gsl_multimin_fminimizer_iterate(minimizer);
std::vector<double> solution_;
for(size_t param = 0; param < active_.size(); ++param){
solution_.push_back(gsl_vector_get (minimizer->x, param));
}
auto error_ = excess_demand_function_value(&solution_[0]);
if(error_ <= error_tolerance){
status = GSL_SUCCESS;
break;
}
if(status != GSL_SUCCESS) {
break;
}
status = gsl_multimin_test_size (active_.size(), error_tolerance);
//status = gsl_multimin_test_gradient(minimizer->gradient,
// converged_gradient_norm);
} while(GSL_CONTINUE == status && iteration_ < max_iterations);
if(status == GSL_SUCCESS){
std::map<esl::identity<esl::law::property>, double> result_;
for(size_t i = 0; i < active_.size(); ++i) {
auto scalar_ = gsl_vector_get (minimizer->x, i);
result_.insert({mapping_index_[i], scalar_});
}
gsl_multimin_fminimizer_free(minimizer);
gsl_vector_free(x);
gsl_vector_free(initial_step_size);
return result_;
}
gsl_multimin_fminimizer_free(minimizer);
gsl_vector_free(x);
gsl_vector_free(initial_step_size);
}else if (method_ == derivative_free_root) {
constexpr double residual_tolerance = 1e-4;
gsl_multiroot_function root_function;
root_function.n = active_.size();
root_function.f = &multiroot_function_value_cb;
root_function.params = static_cast<void *>(this);
constexpr auto start_multiplier_ = 1.0;
std::vector<double> multipliers_;
double best_residual_ = 0;
gsl_vector *variables_ = gsl_vector_alloc(active_.size());
for(size_t i = 0; i < active_.size(); ++i) {
gsl_vector_set(variables_, i, start_multiplier_);
multipliers_.push_back(start_multiplier_);
best_residual_ += abs(start_multiplier_);
}
// Powell's Hybrid method, but with finite-difference approximation
const gsl_multiroot_fsolver_type *solver_t_ = gsl_multiroot_fsolver_hybrids;
gsl_multiroot_fsolver *solver_ = gsl_multiroot_fsolver_alloc(solver_t_, active_.size());
gsl_multiroot_fsolver_set (solver_, &root_function, variables_);
int status = GSL_CONTINUE;
//LOG(trace) << "initial status = " << status << std::endl;
for(size_t iter = 0; iter < max_iterations && GSL_CONTINUE == status; ++iter){
//LOG(trace) << "iter = " << iter << "/" << max_iterations<< std::endl;
status = gsl_multiroot_fsolver_iterate (solver_);
if (GSL_SUCCESS != status){
//LOG(trace) << "status = " << status << std::endl;
break;
}
status = gsl_multiroot_test_residual (solver_->f, residual_tolerance);
if(GSL_SUCCESS == status){
double residual_ = 0.;
for(size_t i = 0; i < active_.size(); ++i) {
residual_ += abs(gsl_vector_get(solver_->f, i));
}
//LOG(trace) << "residual_" << residual_ << std::endl;
if(residual_ < best_residual_) {
best_residual_ = residual_;
for(size_t i = 0; i < active_.size(); ++i) {
multipliers_[i] = gsl_vector_get(solver_->x, i);
//LOG(trace) << "updating multipliers_[" << i << "] " << multipliers_[i] << std::endl;
}
}
break;
}
if(GSL_CONTINUE != status) {
break;
}
double residual_ = 0.;
for(size_t i = 0; i < active_.size(); ++i) {
residual_ += abs(gsl_vector_get(solver_->f, i));
}
//LOG(trace) << "residual_" << residual_ << std::endl;
if(residual_ < best_residual_) {
best_residual_ = residual_;
for(size_t i = 0; i < active_.size(); ++i) {
multipliers_[i] = gsl_vector_get(solver_->x, i);
//LOG(trace) << "udating multipliers_[" << i << "] " << multipliers_[i] << std::endl;
}
}
}
//LOG(trace) << "final status = " << status << std::endl;
std::map<esl::identity<esl::law::property>, double> result_;
for(size_t i = 0; i < active_.size(); ++i) {
//LOG(trace) << "outcome: " << multipliers_[i] << std::endl;
result_.emplace(mapping_index_[i], multipliers_[i]);
}
gsl_multiroot_fsolver_free (solver_);
gsl_vector_free(variables_);
return result_;
}
}
return std::nullopt;
}
} // namespace tatonnement
| 39.948941 | 120 | 0.547056 |
30f08690e448df39c2889d227793a0054a3f0339 | 842 | cpp | C++ | Depth-first Search/max-area-of-island.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | 2 | 2021-03-05T22:32:23.000Z | 2021-03-05T22:32:29.000Z | Questions Level-Wise/Medium/max-area-of-island.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | Questions Level-Wise/Medium/max-area-of-island.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | class Solution {
public:
void findarea(vector<vector<int>>& grid,int r,int c,int &t)
{
grid[r][c]=0,t++;
if(r+1<grid.size()&&grid[r+1][c])
findarea(grid,r+1,c,t);
if(r-1>=0&&grid[r-1][c])
findarea(grid,r-1,c,t);
if(c+1<grid[0].size()&&grid[r][c+1])
findarea(grid,r,c+1,t);
if(c-1>=0&&grid[r][c-1])
findarea(grid,r,c-1,t);
}
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int t,area=0;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[i].size();j++)
{
if(grid[i][j])
{
t=0,findarea(grid,i,j,t);
if(t>area)
area=t;
}
}
}
return area;
}
}; | 26.3125 | 63 | 0.388361 |
30f14197cb37bf8e3010ef847f96019be218d229 | 3,258 | cpp | C++ | src/tools/boot/src/reader/reader.cpp | firebolt-ai/robotos | e506eb79ea0ebf004558d0154ea3e323a634d3cc | [
"MIT"
] | null | null | null | src/tools/boot/src/reader/reader.cpp | firebolt-ai/robotos | e506eb79ea0ebf004558d0154ea3e323a634d3cc | [
"MIT"
] | null | null | null | src/tools/boot/src/reader/reader.cpp | firebolt-ai/robotos | e506eb79ea0ebf004558d0154ea3e323a634d3cc | [
"MIT"
] | 1 | 2020-03-06T03:11:38.000Z | 2020-03-06T03:11:38.000Z | #include "reader.h"
#include "../../../math/geometry/coordinates/vol/vol.h"
#include "../../../tcp/Socket.h"
#include <rec/robotino/api2/Com.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <string>
#include <cstring>
#include <iostream>
int KinectReader::readPosition(unsigned int average)
{
std::string input;
float
xCurVal = 0.0,
yCurVal = 0.0,
zCurVal = 0.0;
unsigned int
i = 0,
endx = 0,
endy = 0;
TcpSocket tcpClient(this->port, this->server);
this->runLoop = true;
while (this->runLoop)
{
xCurVal = 0.0;
yCurVal = 0.0;
zCurVal = 0.0;
i = 0;
while (tcpClient.read(input))
{
if (input == "Click")
{
this->clickTime = pCom->msecsElapsed();
continue;
}
endx = input.find(',', 0);
if (endx == std::string::npos)
continue;
endy = input.find(',', endx + 1);
if (endy == std::string::npos)
continue;
xCurVal += (float)std::atof(input.substr(0, endx).c_str());
yCurVal += (float)std::atof(input.substr(endx + 1, endy).c_str());
zCurVal += (float)std::atof(input.substr(endy + 1).c_str());
if ((fabs(xCurVal) + fabs(yCurVal) + fabs(zCurVal)) < 0.1f)
continue;
if (++i >= average)
break;
}
if (i < average)
{
this->runLoop = false;
std::cerr << "KinectReader: Connection lost" << std::endl;
return KINECTREADER_LOST_CONNECTION;
}
this->x = ((zCurVal / average) / 1000.0) + KINECTREADER_DEPTH_ADJUSTMENT;
this->y = ((xCurVal / average) / 1000.0);
this->z = ((yCurVal / average) / 1000.0) + this->height;
this->updateTime = this->pCom->msecsElapsed();
this->updated = true;
}
return KINECTREADER_NORMAL_EXIT;
}
KinectReader::KinectReader(std::string server, std::string port, rec::robotino::api2::Com *pCom)
{
this->server = server;
this->port = port;
this->pCom = pCom;
this->x = 0.0;
this->y = 0.0;
this->z = 0.0;
this->height = KINECTREADER_MIN_HEIGHT;
this->updateTime = 0;
this->clickTime = 0;
this->runLoop = false;
this->updated = false;
}
VolumeCoordinate KinectReader::getCoordinate()
{
this->updated = false;
return VolumeCoordinate(this->x, this->y, this->z);
}
bool KinectReader::isUpdated()
{
return this->updated;
}
unsigned int KinectReader::dataAge()
{
return (this->pCom->msecsElapsed() - this->updateTime);
}
unsigned int KinectReader::clickAge()
{
return this->pCom->msecsElapsed() - this->clickTime;
}
bool KinectReader::isRunning()
{
return this->runLoop;
}
void KinectReader::stopLoop()
{
this->runLoop = false;
}
void KinectReader::setHeight(float height)
{
if (height > KINECTREADER_MIN_HEIGHT)
{
this->height = height;
std::cout << "Kinect height set to " << height << " meters" << std::endl;
}
else
std::cout << "Could not set kinect height to " << height << " meters, too low" << std::endl;
}
| 22.468966 | 100 | 0.550338 |
30f193a757d6a35bd19a711a276b02e2fcbfbcba | 174 | cpp | C++ | address1.cpp | Biteliuying/address | d2ef3a79b214d5282e8307cde741a8938830d6b2 | [
"Apache-2.0"
] | null | null | null | address1.cpp | Biteliuying/address | d2ef3a79b214d5282e8307cde741a8938830d6b2 | [
"Apache-2.0"
] | 1 | 2022-02-10T15:28:30.000Z | 2022-02-10T15:28:30.000Z | address1.cpp | Biteliuying/address | d2ef3a79b214d5282e8307cde741a8938830d6b2 | [
"Apache-2.0"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
char a,b;
a = 'a';
b = 'b';
putchar(a);
putchar('\n');
putchar(b);
printf("\n%c\n%c", a,b);
} | 14.5 | 32 | 0.545977 |
30f54b4f48d2376297310dd98ca85d87ff9407b5 | 1,359 | tcc | C++ | include/bits/sqlite_iterator.tcc | vashman/data_pattern_sqlite | 8ed3d1fe3e86ea7165d43277feb05d84189f696e | [
"BSL-1.0"
] | null | null | null | include/bits/sqlite_iterator.tcc | vashman/data_pattern_sqlite | 8ed3d1fe3e86ea7165d43277feb05d84189f696e | [
"BSL-1.0"
] | null | null | null | include/bits/sqlite_iterator.tcc | vashman/data_pattern_sqlite | 8ed3d1fe3e86ea7165d43277feb05d84189f696e | [
"BSL-1.0"
] | null | null | null | //
// Copyright Sundeep S. Sangha 2013 - 2017.
// 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)
#ifndef DATA_PATTERN_SQLITE_SQLITE_ITERATOR_TCC
#define DATA_PATTERN_SQLITE_SQLITE_ITERATOR_TCC
#include <iterator>
#include <memory>
namespace data_pattern_sqlite {
template <typename T>
sqlite_iterator_input<T>::sqlite_iterator_input (
sqlite_statement & _stmt
)
: stmt (& _stmt)
, temp ()
, got_var (false)
, index (_stmt.index)
{}
template <typename T>
sqlite_iterator_input<T>::sqlite_iterator_input (
sqlite_statement & _stmt
, int _index
)
: stmt (& _stmt)
, temp ()
, got_var (false)
, index (_index)
{}
template <typename T>
template <typename U>
sqlite_iterator_input<T>::sqlite_iterator_input (
sqlite_statement & _stmt
, sqlite_iterator_input<U> const & _stmt2
)
: stmt (& _stmt)
, temp ()
, got_var (false)
, index (_stmt2.index)
{}
template <typename T>
sqlite_iterator_input<T>::sqlite_iterator_input ()
: stmt (nullptr)
, temp ()
, got_var(true)
, index(-1)
{}
sqlite_iterator_output::sqlite_iterator_output (
sqlite_statement & _stmt
)
: stmt (& _stmt)
, index (1+_stmt.index)
{}
sqlite_iterator_output::sqlite_iterator_output ()
: stmt (nullptr)
, index (-1)
{}
} /* data_pattern_sqlite */
#endif
| 18.875 | 61 | 0.721854 |
30f6a483bbbcea158e3a1f7db24adebe272959f3 | 584 | cpp | C++ | KM/03code/book/Thinking-In-C-resource-master/C09/c0905.cpp | wangcy6/weekly.github.io | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 10 | 2019-03-17T10:13:04.000Z | 2021-03-03T03:23:34.000Z | KM/03code/book/Thinking-In-C-resource-master/C09/c0905.cpp | wangcy6/weekly.github.io | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | 44 | 2018-12-14T02:35:47.000Z | 2021-02-06T09:12:10.000Z | KM/03code/book/Thinking-In-C-resource-master/C09/c0905.cpp | wangcy6/weekly | f249bed5cf5a2b14d798ac33086cea0c1efe432e | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <ctime>
inline int f1(int a, int b)
{
a++;
a += b;
b += a;
return a + b;
}
int f2(int a, int b)
{
a++;
a += b;
b += a;
return a + b;
}
int main(void)
{
clock_t t1, t2;
printf("Calculating time...\n");
t1 = clock();
for (int i = 0; i < 10000000; i++)
f1(100, 100);
t1 = clock() - t1;
printf("f1 take %ld clicks(%f seconds)\n", t1, ((float)t1)/CLOCKS_PER_SEC);
t2 = clock();
for (int i = 0; i < 10000000; i++)
f2(100, 100);
t2 = clock() - t2;
printf("f2 take %ld clicks(%f seconds)\n", t2, ((float)t2)/CLOCKS_PER_SEC);
return 0;
}
| 15.368421 | 76 | 0.55137 |
30fce0782844fc8a96e20fe088fe8cc794d2812c | 3,890 | cpp | C++ | darkness-engine/src/tools/Process.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 6 | 2019-10-17T11:31:55.000Z | 2022-02-11T08:51:20.000Z | darkness-engine/src/tools/Process.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-08-11T09:01:29.000Z | 2020-08-11T09:01:29.000Z | darkness-engine/src/tools/Process.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-06-02T15:48:20.000Z | 2020-06-02T15:48:20.000Z | #include "tools/Process.h"
#include "tools/Debug.h"
#include "tools/PathTools.h"
#include "platform/Platform.h"
#include <vector>
namespace engine
{
Process::Process(
const std::string& executable,
const std::string& arguments,
const std::string& workingDirectory,
OnProcessMessage onMessage)
: m_executable{ executable }
, m_arguments{ arguments }
, m_workingDirectory{ workingDirectory }
, m_onMessage{ onMessage }
{
m_work = std::move(
std::unique_ptr<std::thread, std::function<void(std::thread*)>>(
new std::thread(
// task
[&]()
{
run();
}),
// deleter
[&](std::thread* ptr) {
ptr->join();
delete ptr;
}));
}
int readFromProcessPipe(HANDLE pipe, std::vector<char>& output)
{
DWORD bytesRead = 0;
DWORD availableBytes = 0;
char tmp = 0;
PeekNamedPipe(pipe, &tmp, 1, NULL, &availableBytes, NULL);
if (availableBytes == 0)
return bytesRead;
output.resize(availableBytes);
if (!ReadFile(pipe, output.data(), static_cast<DWORD>(output.size()), &bytesRead, NULL))
ASSERT(false, "Could not read compilation output");
return bytesRead;
}
void Process::run()
{
//auto widePath = toWideString(m_executable);
//auto wideParameters = toWideString(m_arguments);
auto wideWorkingDirectory = toWideString(m_workingDirectory);
SECURITY_ATTRIBUTES securityAttributes = {};
securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttributes.bInheritHandle = TRUE;
HANDLE readPipe, writePipe;
CreatePipe(&readPipe, &writePipe, &securityAttributes, 0);
PROCESS_INFORMATION processInfo = {};
STARTUPINFO startupInfo = {};
startupInfo.cb = sizeof(STARTUPINFO);
startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
startupInfo.wShowWindow = SW_HIDE;
startupInfo.hStdOutput = writePipe;
startupInfo.hStdError = writePipe;
// for some reason having executable as part of arguments works best
auto starting = toWideString(m_executable + " " + m_arguments);
std::vector<wchar_t> params(starting.size() + 1, 0);
memcpy(¶ms[0], starting.data(), starting.size() * sizeof(wchar_t));
bool res = CreateProcess(
NULL,//widePath.data(),
params.data(),
NULL, NULL,
TRUE,
0,
NULL,
wideWorkingDirectory.data(),
&startupInfo,
&processInfo
);
auto ut = toUtf8String(std::wstring(params.data()));
ASSERT(res, "Failed to start process: %", ut.c_str());
std::vector<char> buffer;
DWORD waitResult = WAIT_TIMEOUT;
while (waitResult != WAIT_OBJECT_0)
{
waitResult = WaitForSingleObject(processInfo.hProcess, 100);
if (waitResult == WAIT_ABANDONED)
break;
int bytesRead = readFromProcessPipe(readPipe, buffer);
while (bytesRead > 0)
{
std::string currentMessage = std::string(buffer.data(), bytesRead);
//LOG("%s", soFar.c_str());
if (m_onMessage)
m_onMessage(currentMessage);
bytesRead = readFromProcessPipe(readPipe, buffer);
}
}
//if (processInfo.hProcess)
// WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(readPipe);
CloseHandle(writePipe);
CloseHandle(processInfo.hThread);
CloseHandle(processInfo.hProcess);
}
}
| 32.689076 | 96 | 0.568638 |
a50234b69510521939af84a4e1bde78580e5c823 | 1,118 | cpp | C++ | DBServer/Main.cpp | Addision/EventServer | 2fd13eb5440769da6fb19c6540fb25db09b8cc75 | [
"MIT"
] | 15 | 2020-04-22T04:32:12.000Z | 2022-01-06T12:40:44.000Z | DBServer/Main.cpp | Addision/EventServer | 2fd13eb5440769da6fb19c6540fb25db09b8cc75 | [
"MIT"
] | 1 | 2020-11-30T07:20:17.000Z | 2020-11-30T07:20:17.000Z | DBServer/Main.cpp | Addision/EventServer | 2fd13eb5440769da6fb19c6540fb25db09b8cc75 | [
"MIT"
] | 8 | 2020-04-21T02:15:04.000Z | 2021-12-31T17:34:02.000Z | #include "DB.h"
#include "JsonConfig.h"
#include "Util.h"
#include "LogUtil.h"
#include "SePlatForm.h"
#include <signal.h>
bool bStopServer = false;
void OnSignal(int sig)
{
switch (sig)
{
case SIGINT:
case SIGTERM:
#ifdef SF_PLATFORM_WIN
case SIGBREAK:
#else
case SIGPIPE:
#endif
{
CLOG_ERR << "Master Server Stop !!!, signal=" << sig << CLOG_END;
bStopServer = true;
break;
}
default:
break;
}
}
void OnHookSignal()
{
signal(SIGINT, OnSignal);
signal(SIGTERM, OnSignal);
#ifdef SF_PLATFORM_WIN
signal(SIGBREAK, OnSignal);
#else
signal(SIGPIPE, OnSignal);
#endif
}
int main()
{
OnHookSignal();
//server config
g_pConfig.reset(new JsonConfig());
g_pConfig->Load(SERVER_CFG);
g_pConfig->m_ServerConf = g_pConfig->m_Root["DBServer"];
std::cout << g_pConfig->m_ServerConf["NodeName"].asString() << std::endl;
//mariadb config
g_pConfig->m_dbConf = g_pConfig->m_Root["MariaDB"];
std::cout << g_pConfig->m_dbConf["uri"].asString() << std::endl;
INIT_SFLOG("DBServer");
DB db;
db.Init();
db.Start();
while (bStopServer == false)
{
sf_sleep(500);
}
db.Stop();
return 0;
} | 15.971429 | 74 | 0.678891 |
a502a181be3839ebda6aad9ff55c19e4a4eb8099 | 1,337 | cpp | C++ | shaders/src/sib_vector_switch.cpp | caron/sitoa | 52a0a4b35f51bccb6223a8206d04b40edc80071c | [
"Apache-2.0"
] | 34 | 2018-02-01T16:13:48.000Z | 2021-07-16T07:37:47.000Z | shaders/src/sib_vector_switch.cpp | 625002974/sitoa | 46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589 | [
"Apache-2.0"
] | 72 | 2018-02-16T17:30:41.000Z | 2021-11-22T11:41:45.000Z | shaders/src/sib_vector_switch.cpp | 625002974/sitoa | 46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589 | [
"Apache-2.0"
] | 15 | 2018-02-15T15:36:58.000Z | 2021-04-14T03:54:25.000Z | /************************************************************************************************************************************
Copyright 2017 Autodesk, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
************************************************************************************************************************************/
#include <ai.h>
AI_SHADER_NODE_EXPORT_METHODS(SIBVectorSwitchMethods);
enum SIBVectorSwitchParams
{
p_vector1,
p_vector2,
p_input
};
node_parameters
{
AiParameterVec ( "vector1", 0.0f, 0.0f, 0.0f );
AiParameterVec ( "vector2", 0.0f, 0.0f, 0.0f );
AiParameterBool( "input" , true );
}
node_initialize{}
node_update{}
node_finish{}
shader_evaluate
{
bool input = AiShaderEvalParamBool(p_input);
sg->out.VEC() = AiShaderEvalParamVec(input ? p_vector2 : p_vector1);
}
| 34.282051 | 134 | 0.60359 |
a50d463ed9da3f14cd8ee894f64c8461bb2cb32e | 4,983 | cpp | C++ | Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp | IsfahanUniversityOfTechnology-CE2019-23/Onket | 403d982f7c80d522ca28bb5f757a295eb02b3807 | [
"MIT"
] | 1 | 2021-01-03T21:33:26.000Z | 2021-01-03T21:33:26.000Z | Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp | IsfahanUniversityOfTechnology-CE2019-23/Onket | 403d982f7c80d522ca28bb5f757a295eb02b3807 | [
"MIT"
] | null | null | null | Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp | IsfahanUniversityOfTechnology-CE2019-23/Onket | 403d982f7c80d522ca28bb5f757a295eb02b3807 | [
"MIT"
] | 1 | 2020-07-22T14:48:58.000Z | 2020-07-22T14:48:58.000Z | /****************************************************************************
** Meta object code from reading C++ file 'basketview.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../Onket/basketview.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'basketview.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.14.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_BasketView_t {
QByteArrayData data[9];
char stringdata0[113];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_BasketView_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_BasketView_t qt_meta_stringdata_BasketView = {
{
QT_MOC_LITERAL(0, 0, 10), // "BasketView"
QT_MOC_LITERAL(1, 11, 18), // "returningRequested"
QT_MOC_LITERAL(2, 30, 0), // ""
QT_MOC_LITERAL(3, 31, 6), // "update"
QT_MOC_LITERAL(4, 38, 16), // "updateFinalPrice"
QT_MOC_LITERAL(5, 55, 11), // "removedItem"
QT_MOC_LITERAL(6, 67, 4), // "Item"
QT_MOC_LITERAL(7, 72, 21), // "on_btn_return_clicked"
QT_MOC_LITERAL(8, 94, 18) // "on_btn_buy_clicked"
},
"BasketView\0returningRequested\0\0update\0"
"updateFinalPrice\0removedItem\0Item\0"
"on_btn_return_clicked\0on_btn_buy_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_BasketView[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 44, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 45, 2, 0x0a /* Public */,
4, 0, 46, 2, 0x08 /* Private */,
5, 1, 47, 2, 0x08 /* Private */,
7, 0, 50, 2, 0x08 /* Private */,
8, 0, 51, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 6, 2,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void BasketView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<BasketView *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->returningRequested(); break;
case 1: _t->update(); break;
case 2: _t->updateFinalPrice(); break;
case 3: _t->removedItem((*reinterpret_cast< const Item(*)>(_a[1]))); break;
case 4: _t->on_btn_return_clicked(); break;
case 5: _t->on_btn_buy_clicked(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (BasketView::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&BasketView::returningRequested)) {
*result = 0;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject BasketView::staticMetaObject = { {
QMetaObject::SuperData::link<QScrollArea::staticMetaObject>(),
qt_meta_stringdata_BasketView.data,
qt_meta_data_BasketView,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *BasketView::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *BasketView::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_BasketView.stringdata0))
return static_cast<void*>(this);
return QScrollArea::qt_metacast(_clname);
}
int BasketView::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QScrollArea::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 6;
}
return _id;
}
// SIGNAL 0
void BasketView::returningRequested()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 30.950311 | 101 | 0.609874 |
a50d528cc0ce030f6198e6d87f6ff351af11526d | 898 | hpp | C++ | Examples/PuzzleGenerator/Generator.hpp | jamesfer/Pathfinder | c1e770624a3b163f2dd173f38228e93d7eb80367 | [
"MIT"
] | null | null | null | Examples/PuzzleGenerator/Generator.hpp | jamesfer/Pathfinder | c1e770624a3b163f2dd173f38228e93d7eb80367 | [
"MIT"
] | null | null | null | Examples/PuzzleGenerator/Generator.hpp | jamesfer/Pathfinder | c1e770624a3b163f2dd173f38228e93d7eb80367 | [
"MIT"
] | null | null | null | #ifndef Generator_hpp
#define Generator_hpp
#include "BFSSearcher.hpp"
#include "DFSSearcher.hpp"
#include <sstream>
#include "Puzzle.hpp"
/**
* Success functor that checks if the node has the required depth
*/
struct BranchDepthCheck
{
private:
int goalDepth;
public:
BranchDepthCheck(int goalDepth) : goalDepth(goalDepth)
{
}
bool operator()(const Node<Puzzle>& node) const
{
return node.getBranchCost() >= goalDepth;
}
};
/**
* A DFS searcher type that starts with an ordered board with its given size
* and then a set number of moves on it.
*/
class Generator : public DFSSearcher<Puzzle, BranchDepthCheck>
{
public:
typedef DFSSearcher<Puzzle, BranchDepthCheck> Super;
public:
Generator(int goalDepth);
/**
* Creates an ordered puzzle and then performs moves on it.
*/
shared_ptr<Puzzle> generate(int width, int height);
};
#endif /* Generator_hpp */
| 17.607843 | 77 | 0.72049 |
a50e20287e54709ed9a8da4dc392d83a61834f4c | 1,661 | cpp | C++ | GUI/test/alta_participante.cpp | bertilxi/Pegaso | 41ddde19f203424d68e8ede3e47450bb22bee0f6 | [
"MIT"
] | null | null | null | GUI/test/alta_participante.cpp | bertilxi/Pegaso | 41ddde19f203424d68e8ede3e47450bb22bee0f6 | [
"MIT"
] | null | null | null | GUI/test/alta_participante.cpp | bertilxi/Pegaso | 41ddde19f203424d68e8ede3e47450bb22bee0f6 | [
"MIT"
] | null | null | null | #include "alta_participante.h"
#include "ui_alta_participante.h"
#include "qpixmap.h"
alta_participante::alta_participante(GUI *guiP, QWidget *parent) :
QDialog(parent),
ui(new Ui::alta_participante), gui(guiP)
{
ui->setupUi(this);
QPixmap pix(":/images/Heros64.png");
ui->label_logo->setPixmap(pix);
QRegExp nombre("[a-zA-Z0-9.-]*");
QValidator* nomValidator = new QRegExpValidator(nombre,this);
ui->lineEdit->setValidator(nomValidator);
// validador del email
EmailValidator* emailValidator = new EmailValidator(this);
ui->lineEdit_2->setValidator(emailValidator);
}
alta_participante::~alta_participante()
{
delete ui;
}
void alta_participante::on_pushButton_3_clicked()
{
this->close();
}
EmailValidator::EmailValidator(QObject *parent) :
QValidator(parent),
m_validMailRegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}"),
m_intermediateMailRegExp("[a-z0-9._%+-]*@?[a-z0-9.-]*\\.?[a-z]*"){}
QValidator::State EmailValidator::validate(QString &text, int &pos) const
{
Q_UNUSED(pos)
fixup(text);
if (m_validMailRegExp.exactMatch(text))
return Acceptable;
if (m_intermediateMailRegExp.exactMatch(text))
return Intermediate;
return Invalid;
}
void EmailValidator::fixup(QString &text) const
{
text = text.trimmed().toLower();
}
void alta_participante::on_pushButton_2_clicked()
{
QString email = ui->lineEdit_2->text();
QString nombre = ui->lineEdit->text();
// tomar ruta de imagen
QString imgUrl = "";
gui->handleAltaParticipante(NULL,nombre,email,imgUrl);
}
void alta_participante::on_pushButton_clicked()
{
}
| 21.571429 | 73 | 0.680915 |
a50e40c4d1c9fa60a110e1332f774ae56811c795 | 1,253 | cc | C++ | leetcode/leetcode_199.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_199.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | leetcode/leetcode_199.cc | math715/arts | ff73ccb7d67f7f7c87150204e15aeb46047f0e02 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void rightTree( TreeNode *root, int &depth, int cur_depth, vector<int> &result){
if (root) {
if (depth < cur_depth) {
depth += 1;
result.push_back(root->val);
}
if (root->right){
rightTree(root->right, depth, cur_depth+1, result);
}
if (root->left) {
rightTree(root->left, depth, cur_depth+1, result);
}
}
}
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
int depth = 0;
rightTree(root, depth, 1, result);
return result;
}
int main( int argc, char *argv[] ) {
TreeNode *root = new TreeNode(4);
root->left = new TreeNode(3);
root->left->left = new TreeNode(2);
root->left->left->left = new TreeNode(1);
root->right = new TreeNode(5);
root->right->right = new TreeNode(6);
/*
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
*/
auto vs = rightSideView(root);
for (auto v : vs ){
cout << v << " ";
}
cout << endl;
return 0;
}
| 21.982456 | 80 | 0.581804 |
a5115bd910e444bdcc0eac1e882e56b4acc3158c | 541 | cpp | C++ | redfish-core/ut/stl_utils_test.cpp | cjcain/bmcweb | 80badf7ceff486ef2bcb912309563919fc5326ea | [
"Apache-2.0"
] | 96 | 2018-01-23T10:17:55.000Z | 2022-03-22T08:49:41.000Z | redfish-core/ut/stl_utils_test.cpp | cjcain/bmcweb | 80badf7ceff486ef2bcb912309563919fc5326ea | [
"Apache-2.0"
] | 233 | 2018-08-06T05:55:44.000Z | 2022-02-23T08:19:04.000Z | redfish-core/ut/stl_utils_test.cpp | cjcain/bmcweb | 80badf7ceff486ef2bcb912309563919fc5326ea | [
"Apache-2.0"
] | 97 | 2018-03-23T07:56:55.000Z | 2022-03-16T15:51:48.000Z | #include "utils/stl_utils.hpp"
#include <gmock/gmock.h>
TEST(STLUtilesTest, RemoveDuplicates)
{
std::vector<std::string> strVec = {"s1", "s4", "s1", "s2", "", "s3", "s3"};
auto iter =
redfish::stl_utils::firstDuplicate(strVec.begin(), strVec.end());
EXPECT_EQ(*iter, "s3");
redfish::stl_utils::removeDuplicate(strVec);
EXPECT_EQ(strVec.size(), 5);
EXPECT_EQ(strVec[0], "s1");
EXPECT_EQ(strVec[1], "s4");
EXPECT_EQ(strVec[2], "s2");
EXPECT_EQ(strVec[3], "");
EXPECT_EQ(strVec[4], "s3");
}
| 24.590909 | 79 | 0.608133 |
a511af29e5823b82098463c7e263ab70f8e134a3 | 380 | cpp | C++ | UVA/11172-Relational Operator.cpp | alielsokary/Competitive-programming | 7dffaa334e18c61c8a7985f5bbb64e3613d1008b | [
"MIT"
] | null | null | null | UVA/11172-Relational Operator.cpp | alielsokary/Competitive-programming | 7dffaa334e18c61c8a7985f5bbb64e3613d1008b | [
"MIT"
] | null | null | null | UVA/11172-Relational Operator.cpp | alielsokary/Competitive-programming | 7dffaa334e18c61c8a7985f5bbb64e3613d1008b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int participants,budget,hotles,weeks;
int price, bed;
int finalCost;
bool isAvail = false;
long long n,a,b;
int main(int argc, char *argv[]) {
scanf("%lld", &n);
for (int i = 0; i<n; i++) {
scanf("%lld%lld", &a,&b);
if (a > b) {
printf(">\n");
} else if (a < b) {
printf("<\n");
} else {
printf("=\n");
}
}
}
| 16.521739 | 37 | 0.544737 |
a51239ead5eda370a34e6c7386b21e83b4e009ea | 1,402 | cpp | C++ | Lydsy/P1483 [HNOI2009]梦幻布丁/P1483.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 22 | 2018-08-07T06:55:10.000Z | 2021-06-12T02:12:19.000Z | Lydsy/P1483 [HNOI2009]梦幻布丁/P1483.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 28 | 2020-03-04T23:47:22.000Z | 2022-02-26T18:50:00.000Z | Lydsy/P1483 [HNOI2009]梦幻布丁/P1483.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 4 | 2019-11-09T15:41:26.000Z | 2021-10-10T08:56:57.000Z | #include <cstdio>
#include <algorithm>
const int N = 100000 + 10;
const int M = 1000000 + 10;
using namespace std;
int Read()
{
int x = 0;char ch = getchar();
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9') x = x * 10 + ch - 48,ch = getchar();
return x;
}
int c[N],next[N],f[M],head[M],s[M],st[M];
int n,m,cnt = 0;
void Init()
{
n = Read();m = Read();
for (int i=1;i<=n;++i)
{
c[i] = Read();
f[c[i]] = c[i];
if (c[i] != c[i - 1])
++cnt;
if (!head[c[i]])
st[c[i]] = i;
++s[c[i]];next[i] = head[c[i]];
head[c[i]] = i;
}
}
void Solve(int x,int y)
{
for (int i=head[x];i;i=next[i])
{
if (c[i + 1] == y) --cnt;
if (c[i - 1] == y) --cnt;
}
for (int i=head[x];i;i=next[i])
c[i] = y;
next[st[x]] = head[y]; //
head[y] = head[x];
s[y] += s[x];
head[x] = st[x] = s[x] = 0;
}
void Work()
{
int opt,x,y;
while (m--)
{
opt = Read();
if (opt == 2)
printf("%d\n",cnt);
else
{
x = Read();y = Read();
if (x == y) continue;
if (s[f[x]] > s[f[y]])
swap(f[x],f[y]);
x = f[x];y = f[y];
if (!s[x]) continue;
Solve(x,y);
}
}
}
int main()
{
Init();
Work();
return 0;
}
| 19.746479 | 71 | 0.373752 |
a5135f2bffbefb3b6ff81037e622c3307d690ae3 | 206 | cpp | C++ | lio/message.cpp | liuyuan185442111/misc | 26920202198658c21784d25ab33e1b245d28ca12 | [
"Apache-2.0"
] | 1 | 2021-01-23T09:24:35.000Z | 2021-01-23T09:24:35.000Z | lio/message.cpp | liuyuan185442111/misc | 26920202198658c21784d25ab33e1b245d28ca12 | [
"Apache-2.0"
] | null | null | null | lio/message.cpp | liuyuan185442111/misc | 26920202198658c21784d25ab33e1b245d28ca12 | [
"Apache-2.0"
] | null | null | null | #include "message.h"
#include "gmatrix.h"
void MsgQueue::Send()
{
MSGQUEUE::iterator it = _queue.begin();
for(; it != _queue.end(); ++it)
gmatrix::HandleMessage(*it);
_queue.clear();
}
| 18.727273 | 43 | 0.601942 |
a513c5c220b84956647261ac91202c4978e7b58f | 280 | cpp | C++ | act_map_exp/src/planner_base_node.cpp | debugCVML/rpg_information_field | 56f9ffba83aaee796502116e1cf651c5bc405bf6 | [
"MIT"
] | 149 | 2020-06-23T12:08:47.000Z | 2022-03-31T08:18:52.000Z | act_map_exp/src/planner_base_node.cpp | debugCVML/rpg_information_field | 56f9ffba83aaee796502116e1cf651c5bc405bf6 | [
"MIT"
] | 4 | 2020-08-28T07:51:15.000Z | 2021-04-09T13:18:49.000Z | act_map_exp/src/planner_base_node.cpp | debugCVML/rpg_information_field | 56f9ffba83aaee796502116e1cf651c5bc405bf6 | [
"MIT"
] | 34 | 2020-06-26T14:50:34.000Z | 2022-03-04T06:45:55.000Z | #include "act_map_exp/planner_base.h"
#include <rpg_common/main.h>
RPG_COMMON_MAIN
{
ros::init(argc, argv, "planner_base");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
act_map_exp::PlannerBase<act_map::GPTraceVoxel> planner(nh, pnh);
ros::spin();
return 0;
}
| 14.736842 | 67 | 0.689286 |
a5177f9b1d3d7b1d6c09f3b5c9e71a2a6adec0ca | 486 | hpp | C++ | tinyraytracing/src/graphX/geometry/shapes/shpere.hpp | nicolaszordan/tinygrafX | 5460b98459ec5e050ae6c0fb53de2f31c80243a9 | [
"Unlicense"
] | null | null | null | tinyraytracing/src/graphX/geometry/shapes/shpere.hpp | nicolaszordan/tinygrafX | 5460b98459ec5e050ae6c0fb53de2f31c80243a9 | [
"Unlicense"
] | null | null | null | tinyraytracing/src/graphX/geometry/shapes/shpere.hpp | nicolaszordan/tinygrafX | 5460b98459ec5e050ae6c0fb53de2f31c80243a9 | [
"Unlicense"
] | null | null | null | //
// graphX - geometry - shapes - sphere.hpp
//
#pragma once
#include "Ishape.hpp"
namespace graphX::geometry {
struct Sphere : IShape {
public:
Sphere(const vec3f& center_, float radius_)
: center{center_}, radius{radius_} {
}
public:
bool ray_intersect(const vec3f& orig_, const vec3f& dir_, float& t0_, vec3f& N_) const override;
public:
vec3f center;
float radius;
};
} // namespace graphX::geometry
| 20.25 | 104 | 0.604938 |
a51a2cc5253a0e0355c9a1693576d8eb80a9f8bf | 160 | hxx | C++ | code/temunt/interface/TemUnt/Direction.hxx | Angew/temple-untrap | bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc | [
"MIT"
] | 1 | 2021-08-20T08:22:18.000Z | 2021-08-20T08:22:18.000Z | code/temunt/interface/TemUnt/Direction.hxx | Angew/temple-untrap | bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc | [
"MIT"
] | null | null | null | code/temunt/interface/TemUnt/Direction.hxx | Angew/temple-untrap | bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc | [
"MIT"
] | null | null | null | #pragma once
#include "TemUnt/Direction.hh"
namespace TemUnt {
enum class Direction
{
North = 0,
South = 1,
East = 2,
West = 3
};
} //namespace TemUnt
| 9.411765 | 30 | 0.65 |
a51fb1c6f5dd006fdbb28730c2e30292906dfe38 | 32,750 | cc | C++ | physicalrobots/player/server/drivers/blobfinder/searchpattern/searchpattern.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/server/drivers/blobfinder/searchpattern/searchpattern.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/server/drivers/blobfinder/searchpattern/searchpattern.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
* Player - One Hell of a Robot Server
* Copyright (C) 2000 Brian Gerkey et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/** @ingroup drivers */
/** @{ */
/** @defgroup driver_searchpattern searchpattern
* @brief Pattern finder
The searchpattern driver searches for given patern in the camera image.
@par Compile-time dependencies
- none
@par Provides
- @ref interface_blobfinder
- (optionally) @ref interface_camera (thresholded image)
@par Requires
- @ref interface_camera
@par Configuration requests
- none
@par Configuration file options
- patterns (string array)
- Default: Nothing! Explicit settings required.
- Each string should contain one s-expression (a LISP-style list)
which define one pattern; first element of a list is a 8-digit hex color
value (0x prefixed): whenever given pattern is found it will be denoted by
a blob of this color.
- debug (integer)
- Default: 0
- If it is set to non-zero, debug messages will be printed
@par Properties
- threshold (integer)
- Default: 112
- Valid values: 0..255
- Luminance threshold used during thresholding
see http://en.wikipedia.org/wiki/Thresholding_%28image_processing%29
- min_blob_pixels (integer)
- Default: 16
- Valid values: greater than 0
- Minimal number of pixel for a blob to be considered as blob
(used for noise elimination).
- sleep_nsec (integer)
- Default: 10000
- timespec value for additional nanosleep()
@par Example
@verbatim
driver
(
name "searchpattern"
provides ["blobfinder:0"]
requires ["camera:0"]
patterns ["(0x00ff0000 (black (white (black) (black (white)))))" "(0x0000ff00 (black (white) (white (black))))"]
threshold 112
min_blob_pixels 16
debug 1
)
@endverbatim
@author Paul Osmialowski
*/
/** @} */
#include <libplayercore/playercore.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <config.h>
#if HAVE_JPEG
#include <libplayerjpeg/playerjpeg.h>
#endif
#define EPS 0.000001
#define QUEUE_LEN 1
#define MAX_PATTERNS 10
#define MAX_DESCRIPTIONS (MAX_PATTERNS * 10)
#define CHECK_TOKEN(str, token) (!(strncmp((str), (token), strlen(token))))
#define EAT_TOKEN(str, token, tmp) \
do \
{ \
for (tmp = (token); (*(tmp)); (tmp)++, (str)++) \
{ \
if ((*str) != (*tmp)) \
{ \
str = NULL; \
break; \
} \
} \
} while (0)
#define IS_HEX_DIGIT(chr) ((((chr) >= '0') && ((chr) <= '9')) || (((chr) >= 'A') && ((chr) <= 'F')) || (((chr) >= 'a') && ((chr) <= 'f')))
#define NO_PARENT -1
#define ERR_TOO_MANY_BLACKS -1
#define ERR_TOO_MANY_WHITES -2
#define ERR_TOO_MANY_PIXELS -3
class Searchpattern: public ThreadedDriver
{
public:
// Constructor; need that
Searchpattern(ConfigFile * cf, int section);
virtual ~Searchpattern();
// Must implement the following methods.
virtual int MainSetup();
virtual void MainQuit();
virtual void Main();
// This method will be invoked on each incoming message
virtual int ProcessMessage(QueuePointer & resp_queue,
player_msghdr * hdr,
void * data);
private:
player_devaddr_t blobfinder_provided_addr, camera_provided_addr;
player_devaddr_t camera_id;
Device * camera;
int publish_timg;
uint32_t colors[MAX_PATTERNS];
struct pattern_description
{
int parent_id;
int internals;
unsigned char color;
} descriptions[MAX_DESCRIPTIONS];
struct blob_struct
{
int minx, miny;
int maxx, maxy;
size_t pixels;
int internals;
int parent;
unsigned char color;
unsigned char in_use;
} blobs[256];
size_t descNum;
int numpatterns;
int debug;
int * _stack;
int _sp;
size_t _stack_size;
size_t max_blob_pixels;
int * blob_x;
int * blob_y;
unsigned char * buffer;
size_t bufsize;
size_t numresults;
int * results;
IntProperty threshold;
IntProperty min_blob_pixels;
IntProperty sleep_nsec;
int find_pattern(const struct pattern_description * pattern, int id, int blob_parent) const;
int searchpattern(unsigned char * area, int width, int height, int min_blob_pixels, const struct pattern_description * pattern, int * results);
#define SEARCH_STACK_GUARD -1
#define SEARCH_STACK_PUSH(value) do \
{ \
if ((this->_sp) == static_cast<int>(this->_stack_size)) PLAYER_ERROR("Stack overflow"); \
else this->_stack[(this->_sp)++] = (value); \
} while (0)
#define SEARCH_STACK_POP() ((this->_sp) ? this->_stack[--(this->_sp)] : SEARCH_STACK_GUARD)
#define SEARCH_STACK_WIPE() (this->_sp = 0)
#define CHECK_PIXEL(line, x, y, blobnum) do \
{ \
switch ((line)[x]) \
{ \
case 0: \
case 255: \
if (this->blobs[blobnum].color == ((line)[x])) \
{ \
SEARCH_STACK_PUSH(x); \
SEARCH_STACK_PUSH(y); \
((line)[x]) = (blobnum); \
} \
break; \
default: \
if (((line)[x]) != (blobnum)) \
{ \
if ((this->blobs[blobnum].parent) == NO_PARENT) \
{ \
this->blobs[blobnum].parent = ((line)[x]); \
this->blobs[this->blobs[blobnum].parent].internals++; \
} else if (((line)[x]) != (this->blobs[blobnum].parent)) PLAYER_ERROR3("Internal error (multiple parents? %d %d) (color %d)", this->blobs[blobnum].parent, (line)[x], this->blobs[blobnum].color); \
} \
} \
} while (0)
};
Searchpattern::Searchpattern(ConfigFile * cf, int section)
: ThreadedDriver(cf, section, true, QUEUE_LEN),
threshold("threshold", 112, false),
min_blob_pixels("min_blob_pixels", 16, false),
sleep_nsec("sleep_nsec", 10000, false)
{
const char * str;
const char * tmp;
char hexbuf[9];
int i, j, k, parent;
memset(&(this->blobfinder_provided_addr), 0, sizeof(player_devaddr_t));
memset(&(this->camera_provided_addr), 0, sizeof(player_devaddr_t));
memset(&(this->camera_id), 0, sizeof(player_devaddr_t));
this->camera = NULL;
this->publish_timg = 0;
memset(this->colors, 0, sizeof this->colors);
memset(this->descriptions, 0, sizeof this->descriptions);
memset(this->blobs, 0, sizeof this->blobs);
this->descNum = 0;
this->numpatterns = 0;
this->debug = 0;
this->_stack = NULL;
this->_sp = 0;
this->_stack_size = 0;
this->max_blob_pixels = 0;
this->blob_x = NULL;
this->blob_y = NULL;
this->buffer = NULL;
this->bufsize = 0;
this->numresults = 0;
this->results = NULL;
if (cf->ReadDeviceAddr(&(this->blobfinder_provided_addr), section, "provides",
PLAYER_BLOBFINDER_CODE, -1, NULL))
{
this->SetError(-1);
return;
}
if (this->AddInterface(this->blobfinder_provided_addr))
{
this->SetError(-1);
return;
}
if (cf->ReadDeviceAddr(&(this->camera_provided_addr), section, "provides",
PLAYER_CAMERA_CODE, -1, NULL))
{
this->publish_timg = 0;
} else
{
if (this->AddInterface(this->camera_provided_addr))
{
this->SetError(-1);
return;
}
this->publish_timg = !0;
}
if (cf->ReadDeviceAddr(&(this->camera_id), section, "requires", PLAYER_CAMERA_CODE, -1, NULL) != 0)
{
this->SetError(-1);
return;
}
this->debug = cf->ReadInt(section, "debug", 0);
this->numpatterns = cf->GetTupleCount(section, "patterns");
if (!((this->numpatterns) > 0))
{
PLAYER_ERROR("No patterns given");
this->SetError(-1);
return;
}
if ((this->numpatterns) > MAX_PATTERNS)
{
PLAYER_ERROR("Too many paterns given");
this->SetError(-1);
return;
}
j = (this->numpatterns);
for (i = 0; i < (this->numpatterns); i++)
{
str = cf->ReadTupleString(section, "patterns", i, "");
if (!str)
{
PLAYER_ERROR1("NULL pattern %d", i);
this->SetError(-1);
return;
}
if (!(strlen(str) > 0))
{
PLAYER_ERROR1("Empty pattern %d", i);
this->SetError(-1);
return;
}
if ((*str) != '(')
{
PLAYER_ERROR1("Syntax error in pattern %d (1)", i);
this->SetError(-1);
return;
}
str++;
if ((*str) != '0')
{
PLAYER_ERROR1("Syntax error in pattern %d (2)", i);
this->SetError(-1);
return;
}
str++;
if ((*str) != 'x')
{
PLAYER_ERROR1("Syntax error in pattern %d (3)", i);
this->SetError(-1);
return;
}
str++;
for (k = 0; k < 8; k++, str++)
{
if (!IS_HEX_DIGIT(*str))
{
PLAYER_ERROR1("Syntax error in pattern %d (4)", i);
this->SetError(-1);
return;
}
hexbuf[k] = (*str);
}
hexbuf[8] = '\0';
sscanf(hexbuf, "%x", &(this->colors[i]));
if ((*str) != ' ')
{
PLAYER_ERROR1("Syntax error in pattern %d (5)", i);
this->SetError(-1);
return;
}
str++;
if ((*str) != '(')
{
PLAYER_ERROR1("Syntax error in pattern %d (6)", i);
this->SetError(-1);
return;
}
str++;
this->descriptions[i].parent_id = NO_PARENT;
this->descriptions[i].internals = 0;
if (CHECK_TOKEN(str, "black"))
{
this->descriptions[i].color = 0;
EAT_TOKEN(str, "black", tmp);
} else if (CHECK_TOKEN(str, "white"))
{
this->descriptions[i].color = 255;
EAT_TOKEN(str, "white", tmp);
} else
{
PLAYER_ERROR1("Syntax error in pattern %d (7)", i);
this->SetError(-1);
return;
}
if (!str)
{
PLAYER_ERROR("Internal error within the parser");
this->SetError(-1);
return;
}
parent = i;
for (;;)
{
if ((*str) == ')')
{
str++;
if ((this->descriptions[parent].parent_id) == NO_PARENT) break;
parent = (this->descriptions[parent].parent_id);
continue;
}
if ((*str) != ' ')
{
PLAYER_ERROR1("Syntax error in pattern %d (8)", i);
this->SetError(-1);
return;
}
str++;
if ((*str) != '(')
{
PLAYER_ERROR1("Syntax error in pattern %d (9)", i);
this->SetError(-1);
return;
}
str++;
if (j >= MAX_DESCRIPTIONS)
{
PLAYER_ERROR("Pattern set too complex");
this->SetError(-1);
return;
}
this->descriptions[parent].internals++;
this->descriptions[j].parent_id = parent;
this->descriptions[j].internals = 0;
if (CHECK_TOKEN(str, "black"))
{
this->descriptions[j].color = 0;
EAT_TOKEN(str, "black", tmp);
} else if (CHECK_TOKEN(str, "white"))
{
this->descriptions[j].color = 255;
EAT_TOKEN(str, "white", tmp);
} else
{
PLAYER_ERROR1("Syntax error in pattern %d (10)", i);
this->SetError(-1);
return;
}
if (!str)
{
PLAYER_ERROR("Internal error within the parser");
this->SetError(-1);
return;
}
parent = j;
j++;
}
if ((*str) != ')')
{
PLAYER_ERROR1("Syntax error in pattern %d (11)", i);
this->SetError(-1);
return;
}
str++;
if (*str)
{
PLAYER_ERROR1("Syntax error in pattern %d (12)", i);
this->SetError(-1);
return;
}
}
if (this->debug)
{
PLAYER_WARN2("patterns: %d, descriptions = %d", this->numpatterns, j);
for (i = 0; i < (this->numpatterns); i++)
{
PLAYER_WARN4("%d: key: 0x%08x internals: %d color: %s", i, this->colors[i], this->descriptions[i].internals, (this->descriptions[i].color) ? "white" : "black");
if ((this->descriptions[i].parent_id) != NO_PARENT)
{
PLAYER_ERROR1("Pattern integrity check failed for pattern %i", i);
this->SetError(-1);
return;
}
}
for (; i < j; i++)
{
PLAYER_WARN4("%d: parent: %d internals: %d color: %s", i, this->descriptions[i].parent_id, this->descriptions[i].internals, (this->descriptions[i].color) ? "white" : "black");
if ((this->descriptions[i].parent_id) == NO_PARENT)
{
PLAYER_ERROR1("Pattern integrity check failed for pattern %i", i);
this->SetError(-1);
return;
}
}
}
this->descNum = j;
if (!(this->RegisterProperty("threshold", &(this->threshold), cf, section)))
{
PLAYER_ERROR("Cannot register 'threshold' property");
this->SetError(-1);
return;
}
if (((this->threshold.GetValue()) < 0) || ((this->threshold.GetValue()) > 255))
{
PLAYER_ERROR("Invalid threshold value");
this->SetError(-1);
return;
}
if (!(this->RegisterProperty("min_blob_pixels", &(this->min_blob_pixels), cf, section)))
{
PLAYER_ERROR("Cannot register 'min_blob_pixels' property");
this->SetError(-1);
return;
}
if ((this->min_blob_pixels.GetValue()) <= 0)
{
PLAYER_ERROR("Invalid min_blob_pixels value");
this->SetError(-1);
return;
}
if (!(this->RegisterProperty("sleep_nsec", &(this->sleep_nsec), cf, section)))
{
this->SetError(-1);
return;
}
if ((this->sleep_nsec.GetValue()) < 0)
{
this->SetError(-1);
return;
}
this->numresults = ((this->numpatterns) * 4);
this->results = reinterpret_cast<int *>(malloc((this->numresults) * sizeof(int)));
if (!(this->results))
{
PLAYER_ERROR("Out of memory");
this->SetError(-1);
return;
}
memset(this->results, 0, sizeof((this->numresults) * sizeof(int)));
}
Searchpattern::~Searchpattern()
{
if (this->results) free(this->results);
this->results = NULL;
if (this->_stack) free(this->_stack);
this->_stack = NULL;
if (this->blob_x) free(this->blob_x);
this->blob_x = NULL;
if (this->blob_y) free(this->blob_y);
this->blob_y = NULL;
if (this->buffer) free(this->buffer);
this->buffer = NULL;
}
////////////////////////////////////////////////////////////////////////////////
// Set up the device. Return 0 if things go well, and -1 otherwise.
int Searchpattern::MainSetup()
{
if (this->publish_timg)
{
if (Device::MatchDeviceAddress(this->camera_id, this->camera_provided_addr))
{
PLAYER_ERROR("attempt to subscribe to self");
return -1;
}
}
this->camera = deviceTable->GetDevice(this->camera_id);
if (!this->camera)
{
PLAYER_ERROR("unable to locate suitable camera device");
return -1;
}
if (this->camera->Subscribe(this->InQueue) != 0)
{
PLAYER_ERROR("unable to subscribe to camera device");
this->camera = NULL;
return -1;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Shutdown the device
void Searchpattern::MainQuit()
{
if (this->camera) this->camera->Unsubscribe(this->InQueue);
this->camera = NULL;
}
void Searchpattern::Main()
{
struct timespec tspec;
for (;;)
{
this->InQueue->Wait();
pthread_testcancel();
this->ProcessMessages();
pthread_testcancel();
tspec.tv_sec = 0;
tspec.tv_nsec = this->sleep_nsec.GetValue();
if (tspec.tv_nsec > 0)
{
nanosleep(&tspec, NULL);
pthread_testcancel();
}
}
}
int Searchpattern::ProcessMessage(QueuePointer & resp_queue,
player_msghdr * hdr,
void * data)
{
int i, j, found;
size_t area_width, area_height;
double lum;
size_t new_size = 0;
size_t new_buf_size = 0;
size_t ns = 0;
player_camera_data_t * rawdata = NULL;
player_camera_data_t * timg_output = NULL;
player_blobfinder_data_t * output = NULL;
unsigned char * ptr = NULL;
unsigned char * ptr1 = NULL;
unsigned char thresh = static_cast<unsigned char>(this->threshold.GetValue());
if (!hdr)
{
PLAYER_ERROR("NULL header");
return -1;
}
if (Message::MatchMessage(hdr, PLAYER_MSGTYPE_DATA, PLAYER_CAMERA_DATA_STATE, this->camera_id))
{
if (!data)
{
PLAYER_ERROR("NULL data");
return -1;
}
rawdata = reinterpret_cast<player_camera_data_t *>(data);
if ((static_cast<int>(rawdata->width) <= 0) || (static_cast<int>(rawdata->height) <= 0))
{
return -1;
} else
{
new_size = rawdata->width * rawdata->height;
new_buf_size = new_size * 3;
if ((this->bufsize) != new_buf_size)
{
if (this->_stack) free(this->_stack);
this->_stack = NULL;
if (this->blob_x) free(this->blob_x);
this->blob_x = NULL;
if (this->blob_y) free(this->blob_y);
this->blob_y = NULL;
if (this->buffer) free(this->buffer);
this->buffer = NULL;
this->bufsize = 0;
this->_stack_size = 0;
this->_sp = 0;
this->max_blob_pixels = 0;
}
if (!(this->buffer))
{
this->bufsize = 0;
this->buffer = reinterpret_cast<unsigned char *>(malloc(new_buf_size));
if (!(this->buffer))
{
PLAYER_ERROR("Out of memory");
return -1;
}
this->bufsize = new_buf_size;
}
if (!(this->_stack))
{
this->_stack_size = 0;
this->_sp = 0;
ns = (new_size * 2);
this->_stack = reinterpret_cast<int *>(malloc(ns * sizeof(int)));
if (!(this->_stack))
{
PLAYER_ERROR("Out of memory");
return -1;
}
this->_stack_size = ns;
this->_sp = 0;
}
if (!(this->blob_x))
{
this->blob_x = reinterpret_cast<int *>(malloc(new_size * sizeof(int)));
if (!(this->blob_x))
{
PLAYER_ERROR("Out of memory");
return -1;
}
}
if (!(this->blob_y))
{
this->blob_y = reinterpret_cast<int *>(malloc(new_size * sizeof(int)));
if (!(this->blob_y))
{
PLAYER_ERROR("Out of memory");
return -1;
}
}
if ((this->blob_x) && (this->blob_y)) this->max_blob_pixels = new_size;
else
{
PLAYER_ERROR("Internal error");
return -1;
}
switch (rawdata->compression)
{
case PLAYER_CAMERA_COMPRESS_RAW:
switch (rawdata->bpp)
{
case 8:
ptr = this->buffer;
ptr1 = reinterpret_cast<unsigned char *>(rawdata->image);
for (i = 0; i < static_cast<int>(rawdata->height); i++)
{
for (j = 0; j < static_cast<int>(rawdata->width); j++)
{
(*ptr) = ((*ptr1) >= thresh) ? 255 : 0;
ptr++; ptr1++;
}
}
break;
case 24:
ptr = this->buffer;
ptr1 = reinterpret_cast<unsigned char *>(rawdata->image);
for (i = 0; i < static_cast<int>(rawdata->height); i++)
{
for (j = 0; j < static_cast<int>(rawdata->width); j++)
{
lum = (0.299 * static_cast<double>(ptr1[0])) + (0.587 * static_cast<double>(ptr1[1])) + (0.114 * static_cast<double>(ptr1[2]));
if (lum < EPS) lum = 0.0;
if (lum > (255.0 - EPS)) lum = 255.0;
(*ptr) = static_cast<unsigned char>(lum);
(*ptr) = ((*ptr) >= thresh) ? 255 : 0;
ptr++; ptr1 += 3;
}
}
break;
case 32:
ptr = this->buffer;
ptr1 = reinterpret_cast<unsigned char *>(rawdata->image);
for (i = 0; i < static_cast<int>(rawdata->height); i++)
{
for (j = 0; j < static_cast<int>(rawdata->width); j++)
{
lum = (0.299 * static_cast<double>(ptr1[0])) + (0.587 * static_cast<double>(ptr1[1])) + (0.114 * static_cast<double>(ptr1[2]));
if (lum < EPS) lum = 0.0;
if (lum > (255.0 - EPS)) lum = 255.0;
(*ptr) = static_cast<unsigned char>(lum);
(*ptr) = ((*ptr) >= thresh) ? 255 : 0;
ptr++; ptr1 += 4;
}
}
break;
default:
PLAYER_WARN("unsupported image depth (not good)");
return -1;
}
break;
#if HAVE_JPEG
case PLAYER_CAMERA_COMPRESS_JPEG:
jpeg_decompress(this->buffer, this->bufsize, rawdata->image, rawdata->image_count);
ptr = this->buffer;
ptr1 = this->buffer;
for (i = 0; i < static_cast<int>(rawdata->height); i++)
{
for (j = 0; j < static_cast<int>(rawdata->width); j++)
{
lum = (0.299 * static_cast<double>(ptr1[0])) + (0.587 * static_cast<double>(ptr1[1])) + (0.114 * static_cast<double>(ptr1[2]));
if (lum < EPS) lum = 0.0;
if (lum > (255.0 - EPS)) lum = 255.0;
(*ptr) = static_cast<unsigned char>(lum);
(*ptr) = ((*ptr) >= thresh) ? 255 : 0;
ptr++; ptr1 += 3;
}
}
break;
#endif
default:
PLAYER_WARN("unsupported compression scheme (not good)");
return -1;
}
if (this->publish_timg)
{
timg_output = reinterpret_cast<player_camera_data_t *>(malloc(sizeof(player_camera_data_t)));
if (!timg_output)
{
PLAYER_ERROR("Out of memory");
return -1;
}
memset(timg_output, 0, sizeof(player_camera_data_t));
timg_output->bpp = 8;
timg_output->compression = PLAYER_CAMERA_COMPRESS_RAW;
timg_output->format = PLAYER_CAMERA_FORMAT_MONO8;
timg_output->fdiv = rawdata->fdiv;
timg_output->width = rawdata->width;
timg_output->height = rawdata->height;
timg_output->image_count = (rawdata->width * rawdata->height);
timg_output->image = reinterpret_cast<uint8_t *>(malloc(timg_output->image_count));
if (!(timg_output->image))
{
free(timg_output);
PLAYER_ERROR("Out of memory");
return -1;
}
memcpy(timg_output->image, this->buffer, timg_output->image_count);
this->Publish(this->camera_provided_addr, PLAYER_MSGTYPE_DATA, PLAYER_CAMERA_DATA_STATE, reinterpret_cast<void *>(timg_output), 0, &(hdr->timestamp), false); // copy = false
// I assume that Publish() (with copy = false) freed those output data!
timg_output = NULL;
}
found = searchpattern(this->buffer, rawdata->width, rawdata->height, this->min_blob_pixels.GetValue(), this->descriptions, this->results);
if (found <= 0)
{
for (i = 0; i < static_cast<int>(this->numresults); i++) results[i] = -1;
}
if (this->debug)
{
switch (found)
{
case 0:
PLAYER_WARN("Found nothing");
break;
case ERR_TOO_MANY_BLACKS:
PLAYER_ERROR("Searchpattern error: Too many blacks");
break;
case ERR_TOO_MANY_WHITES:
PLAYER_ERROR("Searchpattern error: Too many whites");
break;
case ERR_TOO_MANY_PIXELS:
PLAYER_ERROR("Searchpattern error: Too many whites");
break;
default:
if (found < 0)
{
PLAYER_ERROR1("Unknown error code %d", found);
} else PLAYER_WARN1("Found %d", found);
}
for (i = 0; i < (this->numpatterns); i++)
{
PLAYER_WARN5("%d. %d %d - %d %d", i + 1, results[i * 4], results[(i * 4) + 1], results[(i * 4) + 2], results[(i * 4) + 3]);
}
PLAYER_WARN("==============");
}
if (found < 0) found = 0;
output = reinterpret_cast<player_blobfinder_data_t *>(malloc(sizeof(player_blobfinder_data_t)));
if (!output)
{
PLAYER_ERROR("Out of memory");
return -1;
}
memset(output, 0, sizeof(player_blobfinder_data_t));
output->width = (rawdata->width);
output->height = (rawdata->height);
output->blobs_count = found;
output->blobs = reinterpret_cast<player_blobfinder_blob_t *>(malloc(found * sizeof(player_blobfinder_blob_t)));
if (!(output->blobs))
{
free(output);
PLAYER_ERROR("Out of memory");
return -1;
}
j = 0;
for (i = 0; i < (this->numpatterns); i++)
{
if (!((results[i * 4] < 0) || (results[(i * 4) + 1] < 0) || (results[(i * 4) + 2] < 0) || (results[(i * 4) + 3] < 0)))
{
if (j >= found)
{
PLAYER_ERROR("Internal error: unexpected number of results");
return -1;
}
area_width = static_cast<size_t>(results[(i * 4) + 1] - results[i * 4]);
area_height = static_cast<size_t>(results[(i * 4) + 3] - results[(i * 4) + 2]);
memset(&(output->blobs[j]), 0, sizeof output->blobs[j]);
output->blobs[j].id = i;
output->blobs[j].color = this->colors[i];
output->blobs[j].area = (area_width * area_height);
output->blobs[j].x = ((static_cast<unsigned>(results[i * 4])) + (area_width >> 1));
output->blobs[j].y = ((static_cast<unsigned>(results[(i * 4) + 2])) + (area_height >> 1));
output->blobs[j].left = results[i * 4];
output->blobs[j].right = results[(i * 4) + 1];
output->blobs[j].top = results[(i * 4) + 2];
output->blobs[j].bottom = results[(i * 4) + 3];
output->blobs[j].range = 0;
j++;
}
}
this->Publish(this->blobfinder_provided_addr, PLAYER_MSGTYPE_DATA, PLAYER_BLOBFINDER_DATA_BLOBS, reinterpret_cast<void *>(output), 0, &(hdr->timestamp), false); // copy = false
// I assume that Publish() (with copy = false) freed those output data!
output = NULL;
}
return 0;
}
return -1;
}
int Searchpattern::find_pattern(const struct pattern_description * pattern, int id, int blob_parent) const
{
int f, i, j, k;
f = 0;
for (i = 1; i < 255; i++) if ((this->blobs[i].in_use) && ((this->blobs[i].internals) == (pattern[id].internals)))
{
if (((pattern[id].parent_id) == NO_PARENT) && ((this->blobs[i].color) != (pattern[id].color))) continue;
if ((blob_parent != NO_PARENT) && ((this->blobs[i].parent) != blob_parent)) continue;
for (j = 0, k = 0; k < (pattern[id].internals); j++) if ((pattern[j].parent_id) == id)
{
k++;
if ((this->find_pattern(pattern, j, i)) <= 0) return f;
}
if (f) return -1;
f = i;
}
return f;
}
int Searchpattern::searchpattern(unsigned char * area, int width, int height, int min_blob_pixels, const struct pattern_description * pattern, int * results)
{
int i, j, k, x, y, mustcheck = 0;
unsigned char blobnum = 0;
int blackblobs = 0;
int whiteblobs = 0;
unsigned char * line;
unsigned char * current_line;
for (i = 0; i < 256; i++) (this->blobs[i].in_use) = 0;
line = area + ((height - 1) * width);
for (i = 0; i < width; i++)
{
area[i] = 0;
line[i] = 0;
}
for (i = 1; i < (height - 1); i++)
{
line = area + (i * width);
line[0] = 0;
line[width - 1] = 0;
}
for (i = 0; i < height; i++)
{
current_line = area + (i * width);
for (j = 0; j < width; j++)
{
switch (current_line[j])
{
case 0:
blobnum = blackblobs + 1;
if (blobnum >= 128)
{
PLAYER_ERROR("Too many black blobs");
return ERR_TOO_MANY_BLACKS;
}
break;
case 255:
blobnum = 255 - (whiteblobs + 1);
if (blobnum <= 127)
{
PLAYER_ERROR("Too many white blobs");
return ERR_TOO_MANY_WHITES;
}
break;
default:
blobnum = 0;
}
if (blobnum)
{
this->blobs[blobnum].pixels = 0;
this->blobs[blobnum].minx = j;
this->blobs[blobnum].maxx = j;
this->blobs[blobnum].miny = i;
this->blobs[blobnum].maxy = i;
this->blobs[blobnum].parent = NO_PARENT;
this->blobs[blobnum].internals = 0;
this->blobs[blobnum].color = current_line[j];
mustcheck = !0;
while (blobnum)
{
if ((current_line[j]) != (this->blobs[blobnum].color)) PLAYER_ERROR("Internal error, something has changed");
SEARCH_STACK_WIPE();
SEARCH_STACK_PUSH(j);
SEARCH_STACK_PUSH(i);
current_line[j] = blobnum;
for (;;)
{
y = SEARCH_STACK_POP();
x = SEARCH_STACK_POP();
if ((x < 0) || (y < 0)) break;
line = area + (y * width);
if (y > 0)
{
line -= width; y--;
if (x > 0)
{
x--;
CHECK_PIXEL(line, x, y, blobnum);
x++;
}
CHECK_PIXEL(line, x, y, blobnum);
if (x < (width - 1))
{
x++;
CHECK_PIXEL(line, x, y, blobnum);
x--;
}
line += width; y++;
}
if (y < (height - 1))
{
line += width; y++;
if (x > 0)
{
x--;
CHECK_PIXEL(line, x, y, blobnum);
x++;
}
CHECK_PIXEL(line, x, y, blobnum);
if (x < (width - 1))
{
x++;
CHECK_PIXEL(line, x, y, blobnum);
x--;
}
line -= width; y--;
}
if (x > 0)
{
x--;
CHECK_PIXEL(line, x, y, blobnum);
x++;
}
if (x < (width - 1))
{
x++;
CHECK_PIXEL(line, x, y, blobnum);
x--;
}
if (x < (this->blobs[blobnum].minx)) this->blobs[blobnum].minx = x;
if (x > (this->blobs[blobnum].maxx)) this->blobs[blobnum].maxx = x;
if (y < (this->blobs[blobnum].miny)) this->blobs[blobnum].miny = y;
if (y > (this->blobs[blobnum].maxy)) this->blobs[blobnum].maxy = y;
this->blob_x[this->blobs[blobnum].pixels] = x;
this->blob_y[this->blobs[blobnum].pixels] = y;
(this->blobs[blobnum].pixels)++;
if ((this->blobs[blobnum].pixels) >= (this->max_blob_pixels))
{
PLAYER_ERROR("Blob too big");
return ERR_TOO_MANY_PIXELS;
}
}
if (mustcheck)
{
mustcheck = 0;
if (((this->blobs[blobnum].pixels) < static_cast<size_t>(min_blob_pixels)) && ((this->blobs[blobnum].parent) > 0))
{
for (k = 0; k < static_cast<int>(this->blobs[blobnum].pixels); k++)
{
area[((this->blob_y[k]) * width) + (this->blob_x[k])] = this->blobs[this->blobs[blobnum].parent].color;
}
this->blobs[this->blobs[blobnum].parent].internals--;
blobnum = (this->blobs[blobnum].parent);
} else
{
if (!(this->blobs[blobnum].color)) blackblobs++; else whiteblobs++;
this->blobs[blobnum].in_use = !0;
blobnum = 0;
}
} else blobnum = 0;
}
}
}
}
k = 0;
for (i = 0; (pattern[i].parent_id) == NO_PARENT; i++)
{
results[i * 4] = -1;
results[(i * 4) + 1] = -1;
results[(i * 4) + 2] = -1;
results[(i * 4) + 3] = -1;
j = (this->find_pattern(pattern, i, NO_PARENT));
switch (j)
{
case -1:
PLAYER_ERROR1("Too many occurences of pattern %d", i);
break;
case 0:
break;
default:
results[i * 4] = (this->blobs[j].minx);
results[(i * 4) + 1] = (this->blobs[j].maxx);
results[(i * 4) + 2] = (this->blobs[j].miny);
results[(i * 4) + 3] = (this->blobs[j].maxy);
k++;
}
}
return k;
}
Driver * Searchpattern_Init(ConfigFile * cf, int section)
{
// Create and return a new instance of this driver
return reinterpret_cast<Driver *>(new Searchpattern(cf, section));
}
////////////////////////////////////////////////////////////////////////////////
// a driver registration function
void searchpattern_Register(DriverTable* table)
{
table->AddDriver("searchpattern", Searchpattern_Init);
}
| 29.881387 | 208 | 0.543939 |
a526c90cfd414f0b7e8e693779b6674323672347 | 920 | cc | C++ | flecsi/utils/test/reflection.cc | manopapad/flecsi | 8bb06e4375f454a0680564c76df2c60ffe49c770 | [
"Unlicense"
] | null | null | null | flecsi/utils/test/reflection.cc | manopapad/flecsi | 8bb06e4375f454a0680564c76df2c60ffe49c770 | [
"Unlicense"
] | null | null | null | flecsi/utils/test/reflection.cc | manopapad/flecsi | 8bb06e4375f454a0680564c76df2c60ffe49c770 | [
"Unlicense"
] | null | null | null | /*~-------------------------------------------------------------------------~~*
* Copyright (c) 2014 Los Alamos National Security, LLC
* All rights reserved.
*~-------------------------------------------------------------------------~~*/
#include <cinchdevel.h>
#include <flecsi/utils/reflection.h>
struct test_type_t {
declare_reflected((double)r1, (int)r2)
}; // struct test_type_t
using namespace flecsi::utils;
DEVEL(reflection) {
test_type_t t;
t.r1 = 1.0;
clog(info) << t.r1 << std::endl;
clog(info) << reflection::num_variables<test_type_t>::value << std::endl;
t.r1 = 2.0;
clog(info) << reflection::variable<0>(t).get() << std::endl;
} // DEVEL
/*~------------------------------------------------------------------------~--*
* Formatting options for vim.
* vim: set tabstop=2 shiftwidth=2 expandtab :
*~------------------------------------------------------------------------~--*/
| 27.058824 | 80 | 0.43913 |
a528599a53644c4700efa428c3f8c495bb6285a4 | 44 | cpp | C++ | PolygonTriangulationC/Vertex.cpp | sbrodehl/cg-lab-1516 | fc4a09679bbce502f59f66a581077417b39edb15 | [
"MIT"
] | null | null | null | PolygonTriangulationC/Vertex.cpp | sbrodehl/cg-lab-1516 | fc4a09679bbce502f59f66a581077417b39edb15 | [
"MIT"
] | 5 | 2016-03-16T09:43:19.000Z | 2016-03-25T12:11:19.000Z | PolygonTriangulationC/Vertex.cpp | sbrodehl/cg-lab-1516 | fc4a09679bbce502f59f66a581077417b39edb15 | [
"MIT"
] | null | null | null | //
// Created by clamber on 21.03.2016.
//
| 8.8 | 36 | 0.590909 |
a52f7fe7b8ba648cfe89fbb8bc15dd779ba0f115 | 5,779 | cpp | C++ | tests/test_file.cpp | adamelliot/stitch | e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3 | [
"MIT"
] | 4 | 2017-11-28T17:22:46.000Z | 2022-03-17T07:47:19.000Z | tests/test_file.cpp | adamelliot/stitch | e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3 | [
"MIT"
] | 10 | 2017-10-04T01:20:25.000Z | 2017-11-23T06:15:23.000Z | tests/test_file.cpp | adamelliot/stitch | e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3 | [
"MIT"
] | 1 | 2019-06-13T23:05:49.000Z | 2019-06-13T23:05:49.000Z | #include "../stitch/file.h"
#include "../testing/testing.h"
#include <thread>
#include <chrono>
#include <iostream>
#include <sstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
using namespace Stitch;
using namespace std;
using namespace Testing;
static bool test_basic()
{
Test test;
const string path("test.fifo");
{
remove(path.c_str());
int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR);
if (result == -1)
{
throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno));
}
}
int reps = 5;
auto make_data = [](int rep) -> string
{
ostringstream s;
s << "data";
for(int i = 0; i < rep; ++i)
s << '.' << to_string(i+1);
return s.str();
};
thread writer([&]()
{
File f(path, File::WriteOnly);
uint32_t d = 0;
for(int rep = 0; rep < reps; ++rep)
{
wait(f.write_ready());
printf("Write ready\n");
++d;
int c = f.write(&d, sizeof(d));
printf("Written %d\n", d);
if (c != sizeof(d))
throw std::runtime_error("Failed write.");
this_thread::sleep_for(chrono::milliseconds(250));
}
});
thread reader([&]()
{
File f(path, File::ReadOnly);
uint32_t expected = 0;
for(int rep = 0; rep < reps; ++rep)
{
wait(f.read_ready());
printf("Read ready\n");
++expected;
uint32_t received = 0;
int c = f.read(&received, sizeof(uint32_t));
printf("Read %d\n", received);
if (c != sizeof(uint32_t))
throw std::runtime_error("Failed read.");
test.assert("Received = " + to_string(expected), received == expected);
}
});
writer.join();
reader.join();
return test.success();
}
static bool test_blocking_read()
{
Test test;
const string path("test.fifo");
{
remove(path.c_str());
int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR);
if (result == -1)
{
throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno));
}
}
int reps = 5;
auto make_data = [](int rep) -> string
{
ostringstream s;
s << "data";
for(int i = 0; i < rep; ++i)
s << '.' << to_string(i+1);
return s.str();
};
thread writer([&]()
{
File f(path, File::WriteOnly);
uint32_t d = 0;
for(int rep = 0; rep < reps; ++rep)
{
wait(f.write_ready());
printf("Write ready\n");
++d;
int c = f.write(&d, sizeof(d));
printf("Written %d\n", d);
if (c != sizeof(d))
throw std::runtime_error("Failed write.");
this_thread::sleep_for(chrono::milliseconds(250));
}
});
thread reader([&]()
{
File f(path, File::ReadOnly);
vector<uint32_t> received(reps, 0);
wait(f.read_ready());
printf("Read ready\n");
int c = f.read(&received[0], sizeof(uint32_t) * reps);
printf("Read count = %d\n", c);
if (c != sizeof(uint32_t) * reps)
throw std::runtime_error("Failed read.");
for(int rep = 0; rep < reps; ++rep)
{
auto & v = received[rep];
test.assert("Received = " + to_string(v), v == rep + 1);
}
});
writer.join();
reader.join();
return test.success();
}
static bool test_nonblocking_read()
{
Test test;
const string path("test.fifo");
{
remove(path.c_str());
int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR);
if (result == -1)
{
throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno));
}
}
int reps = 5;
auto make_data = [](int rep) -> string
{
ostringstream s;
s << "data";
for(int i = 0; i < rep; ++i)
s << '.' << to_string(i+1);
return s.str();
};
thread writer([&]()
{
File f(path, File::WriteOnly);
uint32_t d = 0;
for(int rep = 0; rep < reps; ++rep)
{
wait(f.write_ready());
printf("Write ready\n");
++d;
int c = f.write(&d, sizeof(d));
printf("Written %d\n", d);
if (c != sizeof(d))
throw std::runtime_error("Failed write.");
this_thread::sleep_for(chrono::milliseconds(250));
}
});
thread reader([&]()
{
File f(path, File::ReadOnly, false);
vector<uint32_t> received(reps, 0);
int total_size = sizeof(uint32_t) * reps;
int received_size = 0;
char * dst = (char*) &received[0];
while(received_size < total_size)
{
wait(f.read_ready());
printf("Read ready\n");
int c = f.read(dst, total_size - received_size);
if (c <= 0)
throw std::runtime_error("Failed read.");
printf("Read count = %d\n", c);
received_size += c;
dst += c;
}
for(int rep = 0; rep < reps; ++rep)
{
auto & v = received[rep];
assert("Received = " + to_string(v), v == rep + 1);
}
});
writer.join();
reader.join();
return test.success();
}
Test_Set file_tests()
{
return {
{ "basic", test_basic },
{ "blocking read", test_blocking_read },
{ "nonblocking read", test_nonblocking_read },
};
}
| 19.791096 | 90 | 0.477072 |
a531999941aba44ec04c231ab80f563fbf87b381 | 6,732 | cpp | C++ | clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIPipelineBranchesitem.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 23 | 2017-08-01T12:25:26.000Z | 2022-01-25T03:44:11.000Z | clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIPipelineBranchesitem.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 35 | 2017-06-14T03:28:15.000Z | 2022-02-14T10:25:54.000Z | clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIPipelineBranchesitem.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 11 | 2017-08-31T19:00:20.000Z | 2021-12-19T12:04:12.000Z | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIPipelineBranchesitem.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAIPipelineBranchesitem::OAIPipelineBranchesitem(QString json) {
this->fromJson(json);
}
OAIPipelineBranchesitem::OAIPipelineBranchesitem() {
this->init();
}
OAIPipelineBranchesitem::~OAIPipelineBranchesitem() {
}
void
OAIPipelineBranchesitem::init() {
m_display_name_isSet = false;
m_estimated_duration_in_millis_isSet = false;
m_name_isSet = false;
m_weather_score_isSet = false;
m_latest_run_isSet = false;
m_organization_isSet = false;
m_pull_request_isSet = false;
m_total_number_of_pull_requests_isSet = false;
m__class_isSet = false;
}
void
OAIPipelineBranchesitem::fromJson(QString jsonString) {
QByteArray array (jsonString.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void
OAIPipelineBranchesitem::fromJsonObject(QJsonObject json) {
::OpenAPI::fromJsonValue(display_name, json[QString("displayName")]);
::OpenAPI::fromJsonValue(estimated_duration_in_millis, json[QString("estimatedDurationInMillis")]);
::OpenAPI::fromJsonValue(name, json[QString("name")]);
::OpenAPI::fromJsonValue(weather_score, json[QString("weatherScore")]);
::OpenAPI::fromJsonValue(latest_run, json[QString("latestRun")]);
::OpenAPI::fromJsonValue(organization, json[QString("organization")]);
::OpenAPI::fromJsonValue(pull_request, json[QString("pullRequest")]);
::OpenAPI::fromJsonValue(total_number_of_pull_requests, json[QString("totalNumberOfPullRequests")]);
::OpenAPI::fromJsonValue(_class, json[QString("_class")]);
}
QString
OAIPipelineBranchesitem::asJson () const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAIPipelineBranchesitem::asJsonObject() const {
QJsonObject obj;
if(m_display_name_isSet){
obj.insert(QString("displayName"), ::OpenAPI::toJsonValue(display_name));
}
if(m_estimated_duration_in_millis_isSet){
obj.insert(QString("estimatedDurationInMillis"), ::OpenAPI::toJsonValue(estimated_duration_in_millis));
}
if(m_name_isSet){
obj.insert(QString("name"), ::OpenAPI::toJsonValue(name));
}
if(m_weather_score_isSet){
obj.insert(QString("weatherScore"), ::OpenAPI::toJsonValue(weather_score));
}
if(latest_run.isSet()){
obj.insert(QString("latestRun"), ::OpenAPI::toJsonValue(latest_run));
}
if(m_organization_isSet){
obj.insert(QString("organization"), ::OpenAPI::toJsonValue(organization));
}
if(pull_request.isSet()){
obj.insert(QString("pullRequest"), ::OpenAPI::toJsonValue(pull_request));
}
if(m_total_number_of_pull_requests_isSet){
obj.insert(QString("totalNumberOfPullRequests"), ::OpenAPI::toJsonValue(total_number_of_pull_requests));
}
if(m__class_isSet){
obj.insert(QString("_class"), ::OpenAPI::toJsonValue(_class));
}
return obj;
}
QString
OAIPipelineBranchesitem::getDisplayName() const {
return display_name;
}
void
OAIPipelineBranchesitem::setDisplayName(const QString &display_name) {
this->display_name = display_name;
this->m_display_name_isSet = true;
}
qint32
OAIPipelineBranchesitem::getEstimatedDurationInMillis() const {
return estimated_duration_in_millis;
}
void
OAIPipelineBranchesitem::setEstimatedDurationInMillis(const qint32 &estimated_duration_in_millis) {
this->estimated_duration_in_millis = estimated_duration_in_millis;
this->m_estimated_duration_in_millis_isSet = true;
}
QString
OAIPipelineBranchesitem::getName() const {
return name;
}
void
OAIPipelineBranchesitem::setName(const QString &name) {
this->name = name;
this->m_name_isSet = true;
}
qint32
OAIPipelineBranchesitem::getWeatherScore() const {
return weather_score;
}
void
OAIPipelineBranchesitem::setWeatherScore(const qint32 &weather_score) {
this->weather_score = weather_score;
this->m_weather_score_isSet = true;
}
OAIPipelineBranchesitemlatestRun
OAIPipelineBranchesitem::getLatestRun() const {
return latest_run;
}
void
OAIPipelineBranchesitem::setLatestRun(const OAIPipelineBranchesitemlatestRun &latest_run) {
this->latest_run = latest_run;
this->m_latest_run_isSet = true;
}
QString
OAIPipelineBranchesitem::getOrganization() const {
return organization;
}
void
OAIPipelineBranchesitem::setOrganization(const QString &organization) {
this->organization = organization;
this->m_organization_isSet = true;
}
OAIPipelineBranchesitempullRequest
OAIPipelineBranchesitem::getPullRequest() const {
return pull_request;
}
void
OAIPipelineBranchesitem::setPullRequest(const OAIPipelineBranchesitempullRequest &pull_request) {
this->pull_request = pull_request;
this->m_pull_request_isSet = true;
}
qint32
OAIPipelineBranchesitem::getTotalNumberOfPullRequests() const {
return total_number_of_pull_requests;
}
void
OAIPipelineBranchesitem::setTotalNumberOfPullRequests(const qint32 &total_number_of_pull_requests) {
this->total_number_of_pull_requests = total_number_of_pull_requests;
this->m_total_number_of_pull_requests_isSet = true;
}
QString
OAIPipelineBranchesitem::getClass() const {
return _class;
}
void
OAIPipelineBranchesitem::setClass(const QString &_class) {
this->_class = _class;
this->m__class_isSet = true;
}
bool
OAIPipelineBranchesitem::isSet() const {
bool isObjectUpdated = false;
do{
if(m_display_name_isSet){ isObjectUpdated = true; break;}
if(m_estimated_duration_in_millis_isSet){ isObjectUpdated = true; break;}
if(m_name_isSet){ isObjectUpdated = true; break;}
if(m_weather_score_isSet){ isObjectUpdated = true; break;}
if(latest_run.isSet()){ isObjectUpdated = true; break;}
if(m_organization_isSet){ isObjectUpdated = true; break;}
if(pull_request.isSet()){ isObjectUpdated = true; break;}
if(m_total_number_of_pull_requests_isSet){ isObjectUpdated = true; break;}
if(m__class_isSet){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| 28.167364 | 112 | 0.738562 |
a531f88b830fa58c47ddcc7d015872bf18c81664 | 55,115 | cc | C++ | raft_impl.cc | dengoswei/craft | 16c4d403c0b1819dc21258cc4cbff6ffb8bf6457 | [
"Apache-2.0"
] | 5 | 2015-12-10T02:28:33.000Z | 2019-06-02T18:20:53.000Z | raft_impl.cc | dengoswei/craft | 16c4d403c0b1819dc21258cc4cbff6ffb8bf6457 | [
"Apache-2.0"
] | null | null | null | raft_impl.cc | dengoswei/craft | 16c4d403c0b1819dc21258cc4cbff6ffb8bf6457 | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <sstream>
#include "raft_impl.h"
#include "replicate_tracker.h"
#include "time_utils.h"
#include "hassert.h"
#include "mem_utils.h"
using namespace std;
namespace {
using namespace raft;
inline void assert_role(const RaftImpl& raft_impl, RaftRole expected_role)
{
hassert(raft_impl.getRole() == expected_role,
"expected role %d but %d", static_cast<int>(expected_role),
static_cast<int>(raft_impl.getRole()));
}
inline void assert_term(RaftImpl& raft_impl, uint64_t term)
{
hassert(raft_impl.getTerm() == term,
"expected term %" PRIu64 " but term %" PRIu64,
raft_impl.getTerm(), term);
}
template <typename T>
bool isMajority(
T expected,
const std::map<uint64_t, T>& votes,
size_t peer_ids_size,
const std::set<uint64_t>& old_peer_ids,
const std::set<uint64_t>& new_peer_ids)
{
bool major = countMajor(expected, votes, peer_ids_size);
if (true == old_peer_ids.empty() || false == major) {
return major;
}
assert(false == old_peer_ids.empty());
assert(false == new_peer_ids.empty());
// joint consensus
// raft paper:
// Agreement(for elections and entry commitment) requires
// seperate majorities from both the old and new configrations.
if (false == countMajor(expected, votes, old_peer_ids)) {
return false;
}
return countMajor(expected, votes, new_peer_ids);
}
std::vector<const Entry*> make_vec_entries(const raft::Message& msg)
{
vector<const Entry*> vec_entries(msg.entries_size(), nullptr);
for (int idx = 0; idx < msg.entries_size(); ++idx) {
vec_entries[idx] = &msg.entries(idx);
assert(nullptr != vec_entries[idx]);
}
assert(vec_entries.size() == static_cast<size_t>(msg.entries_size()));
return vec_entries;
}
std::vector<const Entry*>
shrinkEntries(uint64_t conflict_index, const std::vector<const Entry*>& entries)
{
if (size_t(0) == entries.size() || 0ull == conflict_index) {
return vector<const Entry*>{entries.begin(), entries.end()};
}
assert(size_t(0) < entries.size());
assert(nullptr != entries[0]);
uint64_t base_index = entries[0]->index();
assert(conflict_index >= base_index);
size_t idx = conflict_index - base_index;
if (idx >= entries.size()) {
return vector<const Entry*>{};
}
return vector<const Entry*>{entries.begin() + idx, entries.end()};
}
inline uint64_t getBaseLogIndex(std::deque<std::unique_ptr<Entry>>& logs)
{
if (true == logs.empty()) {
return 0ull;
}
assert(nullptr != logs.front());
assert(0ull < logs.front()->index());
return logs.front()->index();
}
size_t truncateLogs(
std::deque<std::unique_ptr<Entry>>& logs, uint64_t truncate_index)
{
uint64_t base_index = getBaseLogIndex(logs);
size_t idx = truncate_index - base_index;
if (idx >= logs.size()) {
return size_t{0};
}
size_t prev_size = logs.size();
logs.erase(logs.begin() + idx, logs.end());
return prev_size - logs.size();
}
inline bool IsAGroupMember(
const RaftImpl& raft_impl, uint64_t peer_id, bool check_current)
{
if (true == check_current) {
return raft_impl.GetCurrentConfig().IsAGroupMember(peer_id);
}
return raft_impl.GetCommitedConfig().IsAGroupMember(peer_id);
}
inline bool IsAReplicateMember(
const RaftImpl& raft_impl, uint64_t peer_id)
{
return raft_impl.GetCurrentConfig().IsAReplicateMember(peer_id);
}
int ApplyConfChange(
const Entry& conf_entry, bool check_pending,
ConfChange& conf_change, RaftConfig& raft_config)
{
if (EntryType::EntryConfChange != conf_entry.type()) {
logerr("expectecd %d but conf_entry.type %d",
static_cast<int>(EntryType::EntryConfChange),
static_cast<int>(conf_entry.type()));
return -1;
}
// 1.
if (false == conf_change.ParseFromString(conf_entry.data())) {
return -2;
}
raft_config.ApplyConfChange(conf_change, check_pending);
return 0;
}
std::vector<std::unique_ptr<raft::Message>>
batchBuildMsgApp(raft::RaftImpl& raft_impl)
{
vector<unique_ptr<Message>> vec_msg;
const auto& replicate_group =
raft_impl.GetCurrentConfig().GetReplicateGroup();
uint64_t last_log_index = raft_impl.getLastLogIndex();
for (auto peer_id : replicate_group) {
auto msg =
raft_impl.GetReplicateTracker().BuildMsgApp(
last_log_index, peer_id,
[&](uint64_t to, uint64_t next_index, size_t batch_size) {
return raft_impl.buildMsgApp(
to, next_index, batch_size);
});
if (nullptr != msg) {
vec_msg.emplace_back(move(msg));
}
assert(nullptr == msg);
}
return vec_msg;
}
std::vector<std::unique_ptr<raft::Message>>
batchBuildMsgHeartbeat(raft::RaftImpl& raft_impl)
{
vector<unique_ptr<Message>> vec_msg;
const auto& replicate_group =
raft_impl.GetCurrentConfig().GetReplicateGroup();
for (auto peer_id : replicate_group) {
auto msg =
raft_impl.GetReplicateTracker().BuildMsgHeartbeat(
peer_id,
[&](uint64_t to, uint64_t next_index, size_t /* */) {
return raft_impl.buildMsgHeartbeat(to, next_index);
});
if (nullptr != msg) {
vec_msg.emplace_back(move(msg));
}
assert(nullptr == msg);
}
return vec_msg;
}
} // namespace
namespace raft {
const uint64_t META_INDEX = 0ull;
const size_t MAX_BATCH_SIZE = 10;
namespace candidate {
MessageType onTimeout(
RaftImpl& raft_impl,
std::chrono::time_point<std::chrono::system_clock> time_now);
} // namespace candidate
namespace follower {
MessageType onTimeout(
RaftImpl& raft_impl,
std::chrono::time_point<std::chrono::system_clock> time_now)
{
assert_role(raft_impl, RaftRole::FOLLOWER);
logdebug("selfid(follower) %" PRIu64 " term %" PRIu64,
raft_impl.getSelfId(), raft_impl.getTerm());
// only timeout if selfid IsAGroupMember
if (false == IsAGroupMember(raft_impl, raft_impl.getSelfId(), true)) {
// don't have MsgVote right;
raft_impl.updateActiveTime(time_now);
return MessageType::MsgNull;
}
// raft paper:
// Followers 5.2
// if election timeout elapses without receiving AppendEntries
// RPC from current leader or granting vote to candidate:
// convert to candidate
raft_impl.becomeCandidate();
return MessageType::MsgVote;
}
MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg)
{
assert_role(raft_impl, RaftRole::FOLLOWER);
assert_term(raft_impl, msg.term());
auto time_now = std::chrono::system_clock::now();
auto rsp_msg_type = MessageType::MsgNull;
switch (msg.type()) {
case MessageType::MsgVote:
// valid check
// 1. msg.from => is a valid group member in current config;
// 2. selfid => is a valid group member in current config;
if (false == IsAGroupMember(raft_impl, msg.from(), true) ||
false == IsAGroupMember(
raft_impl, raft_impl.getSelfId(), true)) {
logerr("NotAGroupMember: msg.to %" PRIu64 " msg.from %" PRIu64,
msg.to(), msg.from());
break;
}
// candidate requestVote msg
//
// raft paper: 5.1 & 5.4
// if votedFor is null or candidateid, and candidate's log is
// at least as up-to-date as receiver's log, grant vote
//
// MORE DETAIL:
// - each server will vote for at most one candidate in a
// given term, on a first-come-first-served basis;
// - the voter denies its vote if its own log is more up-to-date
// then that of the candidate.
if (raft_impl.isUpToDate(msg.log_term(), msg.index())) {
// CAN'T RESET vote_for_
if (0ull == raft_impl.getVoteFor()) {
raft_impl.setVoteFor(false, msg.from());
raft_impl.assignStoreSeq(META_INDEX);
}
assert(0ull != raft_impl.getVoteFor());
}
// check getVoteFor() != msg.from() => reject!
rsp_msg_type = MessageType::MsgVoteResp;
raft_impl.updateActiveTime(time_now);
logdebug("selfid %" PRIu64
" handle MsgVote", raft_impl.getSelfId());
break;
case MessageType::MsgHeartbeat:
{
// leader heart beat msg
// => Heartbeat with same term always from active leader
raft_impl.setLeader(false, msg.from());
assert(msg.from() == raft_impl.getLeader());
rsp_msg_type = MessageType::MsgHeartbeatResp;
raft_impl.updateActiveTime(time_now);
logdebug("selfid %" PRIu64
" recv heartbeat from leader %" PRIu64,
raft_impl.getSelfId(), msg.from());
}
break;
case MessageType::MsgApp:
{
// leader appendEntry msg
// => AppendEntries always from active leader!
raft_impl.setLeader(false, msg.from());
assert(msg.from() == raft_impl.getLeader());
// auto vec_entries = make_vec_entries(msg);
auto entries = make_vec_entries(msg);
// auto entries = make_entries(vec_entries);
assert(static_cast<size_t>(
msg.entries_size()) == entries.size());
auto append_count =
raft_impl.appendEntries(
msg.index(), msg.log_term(), msg.commit(), entries);
auto store_seq = 0 < append_count ?
raft_impl.assignStoreSeq(msg.index() + 1ull) :
0ull;
logdebug("selfid(follower) %" PRIu64 " index %" PRIu64
" term %" PRIu64 " log_term %" PRIu64
" entries_size %zu append_count %d"
" store_seq %" PRIu64,
raft_impl.getSelfId(), msg.index(), msg.term(),
msg.log_term(),
entries.size(), append_count, store_seq);
raft_impl.updateActiveTime(time_now);
rsp_msg_type = MessageType::MsgAppResp;
// 0 == msg.entries_size() => indicate already up-to-date
}
break;
default:
logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type()));
// TODO ?: MsgProp: redirect to leader ?
break;
}
return rsp_msg_type;
}
} // namespace follower
namespace candidate {
MessageType onTimeout(
RaftImpl& raft_impl,
std::chrono::time_point<std::chrono::system_clock> time_now)
{
assert_role(raft_impl, RaftRole::CANDIDATE);
logdebug("selfid(candidate) %" PRIu64 " term %" PRIu64,
raft_impl.getSelfId(), raft_impl.getTerm());
assert(true == IsAGroupMember(raft_impl, raft_impl.getSelfId(), true));
// raft paper:
// Candidates 5.2
// On conversion to candidate or election timeout elapse,
// start election:
raft_impl.beginVote();
raft_impl.updateActiveTime(time_now);
return MessageType::MsgVote;
}
MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg)
{
assert_role(raft_impl, RaftRole::CANDIDATE);
assert_term(raft_impl, msg.term());
auto rsp_msg_type = MessageType::MsgNull;
switch (msg.type()) {
case MessageType::MsgVoteResp:
// valid check
if (false == IsAGroupMember(raft_impl, msg.from(), true) ||
false == IsAGroupMember(
raft_impl, raft_impl.getSelfId(), true)) {
logerr("NotAGroupMember: msg.to %" PRIu64 " msg.from %" PRIu64,
msg.to(), msg.from());
break;
}
// collect vote resp
raft_impl.updateVote(msg.from(), !msg.reject());
if (raft_impl.isMajorVoteYes()) {
// step as leader: TODO ?
raft_impl.becomeLeader();
// => immidicate send out headbeat ?
// raft paper:
// Rules for Servers, Leaders:
// upon election: send initial empty AppendEntries RPCs
// (heartbeat) to each server; repeat during idle periods
// to prevent election timeouts 5.2
rsp_msg_type = MessageType::MsgHeartbeat;
}
logdebug("selfid %" PRIu64
" handle MsgVoteResp", raft_impl.getSelfId());
break;
default:
logdebug("IGNORE: recv msg type %d",
static_cast<int>(msg.type()));
// TODO: ?
break;
}
return rsp_msg_type;
}
} // namespace candidate
namespace leader {
MessageType onTimeout(
RaftImpl& raft_impl,
std::chrono::time_point<std::chrono::system_clock> time_now)
{
assert_role(raft_impl, RaftRole::LEADER);
raft_impl.updateActiveTime(time_now);
return MessageType::MsgNull;
}
MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg)
{
assert_role(raft_impl, RaftRole::LEADER);
assert_term(raft_impl, msg.term());
auto rsp_msg_type = MessageType::MsgNull;
// check msg.from
switch (msg.type()) {
case MessageType::MsgProp:
{
// client prop
// auto vec_entries = make_vec_entries(msg);
// auto entries = make_entries(vec_entries);
auto entries = make_vec_entries(msg);
assert(static_cast<size_t>(
msg.entries_size()) == entries.size());
auto ret =
raft_impl.checkAndAppendEntries(msg.index(), entries);
if (0 != ret) {
logerr("checkAndAppendEntries ret %d", ret);
break;
}
assert(0ull < msg.index() + 1ull);
auto store_seq = raft_impl.assignStoreSeq(msg.index() + 1ull);
logdebug("selfid(leader) %" PRIu64 " MsgProp index %" PRIu64
" store_seq %" PRIu64 " entries_size %zu "
"last_index %" PRIu64,
raft_impl.getSelfId(), msg.index(), store_seq,
entries.size(), raft_impl.getLastLogIndex());
rsp_msg_type = MessageType::MsgApp;
}
break;
case MessageType::MsgAppResp:
{
if (false == IsAReplicateMember(raft_impl, msg.from())) {
// not a replicate member now
// => ignore this request
logerr("selfid %" PRIu64
" recv MsgAppResp from NotAReplicateMember %" PRIu64,
raft_impl.getSelfId(), msg.from());
break;
}
// collect appendEntry resp
// TODO: update commited!
bool update =
raft_impl.updateReplicateState(
msg.from(), msg.reject(),
msg.reject_hint(), msg.index());
if (update) {
rsp_msg_type = MessageType::MsgApp;
}
else {
assert(false == msg.reject());
if (1ull == msg.index() &&
0ull < raft_impl.getLastLogIndex()) {
// MsgApp prode reach match_index == 0ull
// && leader log isn't empty;
rsp_msg_type = MessageType::MsgApp;
}
}
logdebug("selfid(leader) %" PRIu64
" MsgAppResp msg.from %" PRIu64
" msg.index %" PRIu64
" update %d reject %d rsp_msg_type %d",
raft_impl.getSelfId(), msg.from(), msg.index(),
static_cast<int>(update),
static_cast<int>(msg.reject()),
static_cast<int>(rsp_msg_type));
}
break;
case MessageType::MsgHeartbeatResp:
{
if (false == IsAReplicateMember(raft_impl, msg.from())) {
// not a replicate member now
// => ignore this request
logerr("selfid %" PRIu64
" recv MsgHeartbeatResp from "
"NotAReplicateMember %" PRIu64,
raft_impl.getSelfId(), msg.from());
break;
}
// collect heartbeat resp
bool update = raft_impl.updateReplicateState(
msg.from(), msg.reject(),
msg.reject_hint(), msg.index());
if (true == update) {
rsp_msg_type = MessageType::MsgHeartbeat;
}
// TODO: logdebug
}
break;
case MessageType::MsgNull:
{
// check followers timeout ?
assert(0ull == msg.from());
auto time_now = chrono::system_clock::now();
if (raft_impl.isHeartbeatTimeout(time_now)) {
raft_impl.updateHeartbeatTime(time_now);
rsp_msg_type = MessageType::MsgHeartbeat;
}
}
break;
default:
logdebug("IGNORE: recv msg type %d",
static_cast<int>(msg.type()));
// TODO: ?
break;
}
return rsp_msg_type;
}
} // namespace leader
RaftImpl::RaftImpl(
uint64_t logid,
uint64_t selfid,
const std::set<uint64_t>& peer_ids,
int min_election_timeout,
int max_election_timeout)
: logid_(logid)
, selfid_(selfid)
, current_config_(selfid)
, commited_config_(selfid)
, rtimeout_(min_election_timeout, max_election_timeout)
, election_timeout_(rtimeout_())
, active_time_(chrono::system_clock::now())
, hb_timeout_(min_election_timeout / 2)
{
assert(0 < min_election_timeout);
assert(min_election_timeout <= max_election_timeout);
// fake ?
for (auto id : peer_ids) {
ConfChange conf_change;
conf_change.set_type(ConfChangeType::ConfChangeAddNode);
conf_change.set_node_id(id);
current_config_.ApplyConfChange(conf_change, false);
commited_config_.ApplyConfChange(conf_change, false);
}
assert(false == current_config_.IsPending());
assert(false == commited_config_.IsPending());
assert(0 < election_timeout_.count());
assert(0 < hb_timeout_.count());
setRole(RaftRole::FOLLOWER);
}
RaftImpl::RaftImpl(
uint64_t logid,
uint64_t selfid,
const std::set<uint64_t>& peer_ids,
int min_election_timeout,
int max_election_timeout,
const std::deque<std::unique_ptr<Entry>>& entry_queue,
uint64_t commited_index,
const RaftState* raft_state)
: logid_(logid)
, selfid_(selfid)
, current_config_(selfid)
, commited_config_(selfid)
, rtimeout_(min_election_timeout, max_election_timeout)
, election_timeout_(rtimeout_())
, active_time_(chrono::system_clock::now())
, hb_timeout_(min_election_timeout / 2)
{
assert(0 < min_election_timeout);
assert(min_election_timeout < max_election_timeout);
for (auto id : peer_ids) {
ConfChange conf_change;
conf_change.set_type(ConfChangeType::ConfChangeAddNode);
conf_change.set_node_id(id);
current_config_.ApplyConfChange(conf_change, false);
commited_config_.ApplyConfChange(conf_change, false);
}
assert(false == current_config_.IsPending());
assert(false == commited_config_.IsPending());
assert(0 < election_timeout_.count());
assert(0 < hb_timeout_.count());
setRole(RaftRole::FOLLOWER);
uint64_t index = 0;
uint64_t max_term = 0;
uint64_t max_seq = 0;
for (auto& entry : entry_queue) {
assert(nullptr != entry);
assert(entry->index() > index);
assert(entry->index() >= commited_index);
index = entry->index();
assert(max_term <= entry->term());
max_term = entry->term();
max_seq = max(max_seq, entry->seq());
if (EntryType::EntryConfChange == entry->type()) {
applyCommitedConfEntry(*entry);
// applyCommitedConfEntry ?
}
logs_.emplace_back(
cutils::make_unique<Entry>(*entry));
assert(nullptr != logs_.back());
}
assert(entry_queue.empty() == logs_.empty());
if (0 != commited_index) {
assert(0 != index);
assert(nullptr != raft_state);
assert(true == isIndexInMem(commited_index));
}
uint64_t vote_for = 0ull;
if (nullptr != raft_state) {
assert(commited_index >= raft_state->commit());
assert(max_term <= raft_state->term());
max_term = raft_state->term();
vote_for = raft_state->vote();
max_seq = max(max_seq, raft_state->seq());
}
if (0 != max_term) {
setTerm(max_term);
}
setVoteFor(true, vote_for);
assert(getTerm() == max_term);
assert(getVoteFor() == vote_for);
commited_index_ = commited_index;
store_seq_ = max_seq+1;
}
RaftImpl::~RaftImpl() = default;
MessageType RaftImpl::CheckTerm(uint64_t msg_term)
{
// raft paper: rules for servers: 5.1
// => If RPC request or response contains term T > currentTerm:
// set currentTerm = T, convert to follower;
if (msg_term != term_) {
if (msg_term > term_) {
becomeFollower(msg_term);
return MessageType::MsgNull;
}
assert(msg_term < term_);
return MessageType::MsgInvalidTerm;
}
assert(msg_term == term_);
return MessageType::MsgNull;
}
MessageType
RaftImpl::CheckTimout(
std::chrono::time_point<std::chrono::system_clock> time_now)
{
if (active_time_ + election_timeout_ < time_now) {
// TIME OUT:
assert(nullptr != timeout_handler_);
return timeout_handler_(*this, time_now);
}
return MessageType::MsgNull;
}
MessageType RaftImpl::step(const Message& msg)
{
assert(msg.logid() == logid_);
assert(msg.to() == selfid_);
// 1. check term
auto rsp_msg_type = CheckTerm(msg.term());
if (MessageType::MsgNull != rsp_msg_type) {
assert(MessageType::MsgInvalidTerm == rsp_msg_type);
return rsp_msg_type;
}
assert(msg.term() == term_);
// 2. check timeout
// ! IMPORTANT !
// if setTerm => false == CheckTimeout
rsp_msg_type = CheckTimout(chrono::system_clock::now());
if (MessageType::MsgNull != rsp_msg_type) {
assert(MessageType::MsgVote == rsp_msg_type);
return rsp_msg_type;
}
// 3. step message
return step_handler_(*this, msg);
}
std::vector<std::unique_ptr<Message>>
RaftImpl::produceRsp(
const Message& req_msg, MessageType rsp_msg_type)
{
assert(req_msg.logid() == logid_);
assert(req_msg.to() == selfid_);
vector<unique_ptr<Message>> vec_msg;
if (MessageType::MsgNull == rsp_msg_type) {
return vec_msg;
}
Message msg_template;
msg_template.set_type(rsp_msg_type);
msg_template.set_logid(logid_);
msg_template.set_from(selfid_);
msg_template.set_term(term_);
msg_template.set_to(req_msg.from());
switch (rsp_msg_type) {
case MessageType::MsgVote:
// raft paper:
// RequestVote RPC Arguments:
// - term
// - candidicateId
// - lastLogIndex
// - lastLogTerm
msg_template.set_index(getLastLogIndex());
msg_template.set_log_term(getLastLogTerm());
vec_msg = current_config_.BroadcastGroupMsg(msg_template);
logdebug("MsgVote term %" PRIu64 " candidate %" PRIu64
" lastLogIndex %" PRIu64 " lastLogTerm %" PRIu64
" vec_msg.size %zu",
term_, selfid_, msg_template.index(),
msg_template.log_term(), vec_msg.size());
break;
case MessageType::MsgVoteResp:
{
// raft paper:
// RequestVote RPC Results:
// - term
// - voteGranted
assert(0ull != req_msg.from());
vec_msg.emplace_back(cutils::make_unique<Message>(msg_template));
auto& rsp_msg = vec_msg.back();
assert(nullptr != rsp_msg);
rsp_msg->set_reject(req_msg.from() != getVoteFor());
logdebug("MsgVoteResp term %" PRIu64 " req_msg.from %" PRIu64
" getVoteFor %" PRIu64 " reject %d",
term_, req_msg.from(), getVoteFor(),
static_cast<int>(rsp_msg->reject()));
}
break;
case MessageType::MsgApp:
{
assert(nullptr != replicate_states_);
// req_msg.type() == MessageType::MsgProp
if (0ull == req_msg.from()) {
vec_msg = batchBuildMsgApp(*this);
logdebug("MsgApp BatchBuildMsgAppUpToDate "
"vec_msg.size %zu", vec_msg.size());
}
else {
assert(0ull != req_msg.from());
// catch-up mode maybe
assert(MessageType::MsgAppResp == req_msg.type());
auto rsp_msg =
replicate_states_->BuildMsgApp(
getLastLogIndex(), req_msg.from(),
[&](uint64_t to,
uint64_t next_index, size_t batch_size) {
return buildMsgApp(to, next_index, batch_size);
});
if (nullptr != rsp_msg) {
logdebug("MsgApp from %" PRIu64 " to %" PRIu64
" index %" PRIu64 " log_term %" PRIu64,
rsp_msg->from(), rsp_msg->to(),
rsp_msg->index(), rsp_msg->log_term());
if (0 != rsp_msg->entries_size() ||
!isPeerUpToDate(req_msg.commit())) {
vec_msg.emplace_back(move(rsp_msg));
assert(size_t{1} == vec_msg.size());
}
else {
logdebug("INGORE: peer_id %" PRIu64
" rsp_msg->entries_size %d"
" req_msg.commit %" PRIu64
" commited_index_ %" PRIu64,
req_msg.from(),
rsp_msg->entries_size(),
req_msg.commit(),
getCommitedIndex());
}
// else => ignore
}
logdebug("MsgApp selfid %" PRIu64 " req_msg.from %" PRIu64
" req_msg.index %" PRIu64 " vec_msg.size %zu",
selfid_, req_msg.from(), req_msg.index(),
vec_msg.size());
}
}
break;
case MessageType::MsgAppResp:
{
// req_msg.type() == MessageType::MsgApp
// raft paper:
// AppendEntries RPC, Results:
// - reply false if term < currentTerm
// - reply false if log don't contain an entry at prevLogIndex
// whose term matchs prevLogTerm
assert(0ull != req_msg.from());
vec_msg.emplace_back(cutils::make_unique<Message>(msg_template));
auto& rsp_msg = vec_msg.back();
assert(nullptr != rsp_msg);
// TODO: reject hint ?
rsp_msg->set_reject(!isMatch(req_msg.index(), req_msg.log_term()));
if (false == rsp_msg->reject()) {
// set index to next_index
if (0 < req_msg.entries_size()) {
rsp_msg->set_index(
req_msg.entries(
req_msg.entries_size() - 1).index() + 1ull);
}
else {
rsp_msg->set_index(req_msg.index() + 1ull);
}
}
rsp_msg->set_commit(getCommitedIndex());
logdebug("MsgAppResp term %" PRIu64 " req_msg.from(leader) %"
PRIu64 " prev_index %" PRIu64 " prev_log_term %" PRIu64
" entries_size %d reject %d next_index %" PRIu64,
term_, req_msg.from(), req_msg.index(),
req_msg.log_term(), req_msg.entries_size(),
static_cast<int>(rsp_msg->reject()),
rsp_msg->index());
}
break;
case MessageType::MsgHeartbeat:
{
assert(nullptr != replicate_states_);
// TODO:
// better way to probe the next_indexes_ & match_indexes_
//
// MsgHeartbeat => empty AppendEntries RPCs
if (MessageType::MsgHeartbeatResp == req_msg.type()) {
// 1 : 1
assert(MessageType::MsgHeartbeatResp == req_msg.type());
assert(true == req_msg.reject());
auto hb_msg =
replicate_states_->BuildMsgHeartbeat(
req_msg.from(),
[&](uint64_t to,
uint64_t next_index, size_t /* */) {
return buildMsgHeartbeat(to, next_index);
});
if (nullptr != hb_msg) {
vec_msg.emplace_back(move(hb_msg));
}
assert(nullptr == hb_msg);
}
else {
// broad cast
vec_msg = batchBuildMsgHeartbeat(*this);
}
}
break;
case MessageType::MsgHeartbeatResp:
{
// rsp to leader
assert(req_msg.from() == getLeader());
vec_msg.emplace_back(cutils::make_unique<Message>(msg_template));
auto& rsp_msg = vec_msg.back();
assert(nullptr != rsp_msg);
rsp_msg->set_reject(!isMatch(req_msg.index(), req_msg.log_term()));
if (false == rsp_msg->reject()) {
rsp_msg->set_index(req_msg.index() + 1ull);
}
logdebug("MsgHeartbeatResp term %" PRIu64 " req_msg.from(leader) %"
PRIu64 " prev_index %" PRIu64 " prev_log_term %" PRIu64
" reject %d next_index %" PRIu64 ,
term_, req_msg.from(), req_msg.index(),
req_msg.log_term(),
static_cast<int>(rsp_msg->reject()), rsp_msg->index());
}
break;
case MessageType::MsgNull:
// DO NOTHING ?
break;
case MessageType::MsgInvalidTerm:
logdebug("MsgInvalidTerm selfid %" PRIu64
" role %d term_ %" PRIu64 " msg.from %" PRIu64
" msg.term %" PRIu64,
getSelfId(), static_cast<int>(getRole()),
getTerm(), req_msg.from(), req_msg.term());
// TODO: rsp with ?
break;
default:
hassert(false, "invalid rsp_msg_type %d",
static_cast<int>(rsp_msg_type));
break;
}
return vec_msg;
}
std::unique_ptr<Message>
RaftImpl::buildMsgApp(
uint64_t peer_id, uint64_t index, size_t max_batch_size)
{
// raft paper
// AppendEntries RPC Arguments:
// - leader term
// - leader id
// - prevLogIndex
// - prevLogTerm
// - entries[]
// - leaderCommit
assert(size_t{0} <= max_batch_size);
assert(0ull < index);
auto app_msg = cutils::make_unique<Message>();
assert(nullptr != app_msg);
app_msg->set_type(MessageType::MsgApp);
app_msg->set_logid(logid_);
app_msg->set_term(term_);
app_msg->set_from(selfid_);
app_msg->set_to(peer_id);
app_msg->set_commit(commited_index_);
uint64_t base_index = 0ull;
uint64_t last_index = 0ull;
tie(base_index, last_index) = getInMemIndex();
logdebug("selfid %" PRIu64 " leader_id %" PRIu64
" index %" PRIu64 " base_index %" PRIu64
" last_index %" PRIu64 " logs_.size %zu max_batch_size %zu",
selfid_, leader_id_,
index, base_index, last_index, logs_.size(), max_batch_size);
if (index < base_index || index > last_index + 1ull) {
if (index < base_index) {
// report: not in mem
// => or submit a catch-up job ?
// => catch-up to commited_index point ?
// => which will read log from db directly ??
ids_not_in_mem_.insert(peer_id);
}
return nullptr;
}
assert(size_t{0} <= last_index - index + 1ull);
app_msg->set_index(index - 1ull);
app_msg->set_log_term(getLogTerm(index - 1ull));
app_msg->set_commit(commited_index_);
assert(size_t{0} <= last_index - index + 1ull);
max_batch_size = min<size_t>(
max_batch_size, last_index - index + 1ull);
for (auto i = size_t{0}; i < max_batch_size; ++i) {
auto entry = app_msg->add_entries();
assert(nullptr != entry);
*entry = *logs_[index + i - base_index];
}
assert(max_batch_size == static_cast<size_t>(app_msg->entries_size()));
logdebug("selfid %" PRIu64 " peer_id %" PRIu64 " index %" PRIu64
" max_batch_size %zu",
getSelfId(), peer_id, index, max_batch_size);
return app_msg;
}
std::unique_ptr<Message>
RaftImpl::buildMsgHeartbeat(
uint64_t peer_id, uint64_t next_index) const
{
assert(0ull < next_index);
auto hb_msg = cutils::make_unique<Message>();
assert(nullptr != hb_msg);
hb_msg->set_type(MessageType::MsgHeartbeat);
hb_msg->set_logid(logid_);
hb_msg->set_term(term_);
hb_msg->set_from(selfid_);
hb_msg->set_to(peer_id);
// heartbeat
uint64_t base_index = 0ull;
uint64_t last_index = 0ull;
tie(base_index, last_index) = getInMemIndex();
next_index = max(base_index + 1, next_index);
next_index = min(last_index + 1, next_index);
hb_msg->set_index(next_index - 1ull);
hb_msg->set_log_term(getLogTerm(next_index - 1ull));
hb_msg->set_commit(commited_index_);
return hb_msg;
}
bool RaftImpl::isUpToDate(
uint64_t peer_log_term, uint64_t peer_max_index)
{
// raft paper
// 5.4.1 Election restriction
// raft determines which of two logs is more up-to-date by
// comparing the index and term of the last entries in the logs.
// - If the logs have last entries with different terms, then the log
// with the later term is more up-to-date;
// - If the logs end with the same term, then whichever log is longer
// is more up-to-date.
uint64_t log_term = getLastLogTerm();
if (peer_log_term > log_term) {
return true;
}
assert(peer_log_term <= log_term);
if (peer_log_term == log_term) {
return peer_max_index >= getLastLogIndex();
}
// else
return false;
}
int RaftImpl::appendLogs(const std::vector<const Entry*>& entries)
{
if (size_t(0) == entries.size()) {
return 0; // do nothing;
}
assert(nullptr != entries[0]);
uint64_t base_index = entries[0]->index();
auto truncate_size = truncateLogs(logs_, base_index);
if (size_t{0} < truncate_size) {
logerr("INFO selfid %" PRIu64 " truncate_size %zu",
getSelfId(), truncate_size);
assert(0 == reconstructCurrentConfig()); // reset currentConfig;
}
uint64_t last_index = getLastLogIndex();
assert(last_index + 1 == base_index);
for (size_t idx = 0; idx < entries.size(); ++idx) {
assert(nullptr != entries[idx]);
if (EntryType::EntryConfChange == entries[idx]->type()) {
applyCommitedConfEntry(*entries[idx]);
}
logs_.emplace_back(cutils::make_unique<Entry>(*entries[idx]));
assert(nullptr != logs_.back());
}
return entries.size();
}
int RaftImpl::appendEntries(
uint64_t prev_log_index,
uint64_t prev_log_term,
uint64_t leader_commited_index,
const std::vector<const Entry*>& entries)
{
assert_role(*this, RaftRole::FOLLOWER);
assert(leader_commited_index >= commited_index_);
if (!isMatch(prev_log_index, prev_log_term)) {
return -1;
}
// match
// raft paper:
// - If an existing entry conflicts with a new one(same index but
// different terms), delete the existing entry and all that follow it
// - Append any new entries not already in the log
uint64_t conflict_index = findConflict(entries);
assert(0ull == conflict_index || commited_index_ < conflict_index);
auto new_entries = shrinkEntries(conflict_index, entries);
int append_count = appendLogs(new_entries);
updateFollowerCommitedIndex(leader_commited_index);
return append_count;
}
int RaftImpl::checkAndAppendEntries(
uint64_t prev_log_index,
const std::vector<const Entry*>& entries)
{
assert_role(*this, RaftRole::LEADER);
assert(nullptr != replicate_states_);
uint64_t last_index = getLastLogIndex();
if (prev_log_index != last_index) {
return -1;
}
// max length control ?
for (size_t idx = 0; idx < entries.size(); ++idx) {
assert(nullptr != entries[idx]);
// apply conf change before push entries into logs_
if (EntryType::EntryConfChange == entries[idx]->type()) {
assert(size_t{1} == entries.size());
assert(size_t{0} == idx);
// applyConfChange:
auto ret = applyUnCommitedConfEntry(*entries[idx]);
if (0 != ret) {
// drop conf change request
logerr("applyUnCommitedConfEntry ret %d", ret);
return -2;
}
}
logs_.emplace_back(
cutils::make_unique<Entry>(*entries[idx]));
assert(nullptr != logs_.back());
logs_.back()->set_term(term_);
logs_.back()->set_index(last_index + 1ull + idx);
}
replicate_states_->UpdateSelfState(getLastLogIndex());
logdebug("selfid %" PRIu64 " last_index %" PRIu64 " logs_size %zu",
selfid_, getLastLogIndex(), logs_.size());
// TODO: find a way to store logs_ to disk
return 0;
}
void RaftImpl::setRole(RaftRole new_role)
{
logdebug("selfid %" PRIu64 " change role_ %d new_role %d",
selfid_, static_cast<int>(role_), static_cast<int>(new_role));
role_ = new_role;
switch (role_) {
case RaftRole::FOLLOWER:
timeout_handler_ = ::raft::follower::onTimeout;
step_handler_ = ::raft::follower::onStepMessage;
break;
case RaftRole::CANDIDATE:
timeout_handler_ = ::raft::candidate::onTimeout;
step_handler_ = ::raft::candidate::onStepMessage;
break;
case RaftRole::LEADER:
timeout_handler_ = ::raft::leader::onTimeout;
step_handler_ = ::raft::leader::onStepMessage;
break;
}
return ;
}
void RaftImpl::setTerm(uint64_t new_term)
{
logdebug("selfid %" PRIu64 " role %d change current term %" PRIu64
" new_term %" PRIu64,
selfid_, static_cast<int>(role_), term_, new_term);
assert(term_ < new_term);
term_ = new_term;
return ;
}
void RaftImpl::setVoteFor(bool reset, uint64_t candidate)
{
logdebug("selfid_ %" PRIu64 " reset %d vote_for_ %" PRIu64
" to candidate %" PRIu64,
selfid_, static_cast<int>(reset), vote_for_, candidate);
if (true == reset || 0ull == vote_for_) {
vote_for_ = candidate;
}
}
uint64_t RaftImpl::assignStoreSeq(uint64_t index)
{
auto seq = ++store_seq_;
if (0ull == index) {
pending_meta_seq_ = seq;
}
else {
pending_log_idx_ =
0ull == pending_log_idx_ ?
index : min(pending_log_idx_, index);
pending_log_seq_ = seq;
}
// logdebug("selfid %" PRIu64 " index %" PRIu64
// " pending_meta_seq_ %" PRIu64
// " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64,
// getSelfId(), index, pending_meta_seq_,
// pending_log_idx_, pending_log_seq_);
return seq;
}
std::tuple<uint64_t, uint64_t, uint64_t>
RaftImpl::getStoreSeq() const
{
logdebug("selfid %" PRIu64
" pending_meta_seq_ %" PRIu64
" pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64,
getSelfId(), pending_meta_seq_,
pending_log_idx_, pending_log_seq_);
return make_tuple(
pending_meta_seq_, pending_log_idx_, pending_log_seq_);
}
void RaftImpl::commitedStoreSeq(
uint64_t meta_seq, uint64_t log_idx, uint64_t log_seq)
{
logdebug("selfid %" PRIu64
" meta_seq %" PRIu64 " log_idx %" PRIu64
" log_seq %" PRIu64
" pending_meta_seq_ %" PRIu64 " pending_log_idx_ %"
PRIu64 " pending_log_seq_ %" PRIu64,
getSelfId(), meta_seq, log_idx, log_seq,
pending_meta_seq_, pending_log_idx_,
pending_log_seq_);
if (meta_seq == pending_meta_seq_) {
pending_meta_seq_ = 0ull; // reset
}
if (log_idx == pending_log_idx_ &&
log_seq == pending_log_seq_) {
pending_log_idx_ = 0ull;
pending_log_seq_ = 0ull;
}
}
void RaftImpl::updateActiveTime(
std::chrono::time_point<std::chrono::system_clock> time_now)
{
{
auto at_str = cutils::format_time(active_time_);
auto time_str = cutils::format_time(time_now);
// logdebug("selfid %" PRIu64 " update active_time_ %s "
// "to time_now %s",
// getSelfId(), at_str.c_str(), time_str.c_str());
}
active_time_ = time_now;
}
uint64_t RaftImpl::getLastLogIndex() const
{
auto t = getInMemIndex();
return get<1>(t);
}
uint64_t RaftImpl::getLastLogTerm() const
{
if (true == logs_.empty()) {
assert(0ull == commited_index_);
return 0ull;
}
assert(nullptr != logs_.back());
assert(term_ >= logs_.back()->term());
return logs_.back()->term();
}
uint64_t RaftImpl::getBaseLogTerm() const
{
if (true == logs_.empty()) {
assert(0ull == commited_index_);
return 0ull;
}
assert(nullptr != logs_.front());
assert(0ull != logs_.front()->term());
assert(term_ >= logs_.front()->term());
return logs_.front()->term();
}
std::tuple<uint64_t, uint64_t> RaftImpl::getInMemIndex() const
{
if (true == logs_.empty()) {
assert(0ull == commited_index_);
return make_tuple(0ull, 0ull);
}
assert(nullptr != logs_.front());
assert(0ull < logs_.front()->index());
assert(0ull == commited_index_ ||
commited_index_ >= logs_.front()->index());
assert(nullptr != logs_.back());
assert(logs_.back()->index() ==
logs_.front()->index() + logs_.size() - 1ull);
return make_tuple(logs_.front()->index(), logs_.back()->index());
}
uint64_t RaftImpl::getBaseLogIndex() const
{
auto t = getInMemIndex();
return get<0>(t);
}
const Entry* RaftImpl::getLogEntry(uint64_t log_index) const
{
if (0ull == log_index) {
return nullptr;
}
assert(0ull < log_index);
auto base_index = 0ull;
auto last_index = 0ull;
tie(base_index, last_index) = getInMemIndex();
if (log_index < base_index || log_index > last_index) {
return nullptr;
}
assert(false == logs_.empty());
size_t idx = log_index - base_index;
assert(0 <= idx && idx < logs_.size());
assert(nullptr != logs_[idx]);
assert(log_index == logs_[idx]->index());
assert(0 < logs_[idx]->term());
return logs_[idx].get();
}
std::vector<std::unique_ptr<raft::Entry>>
RaftImpl::getLogEntriesAfter(uint64_t log_index) const
{
vector<unique_ptr<Entry>> vec_entries;
uint64_t base_index = 0ull;
uint64_t last_index = 0ull;
tie(base_index, last_index) = getInMemIndex();
assert(base_index <= log_index + 1ull);
if (log_index >= last_index) {
return vec_entries;
}
assert(0ull < last_index - log_index);
vec_entries.reserve(last_index - log_index);
for (; log_index < last_index; ++log_index) {
auto index = log_index + 1;
auto entry = getLogEntry(index);
assert(nullptr != entry);
assert(index == entry->index());
vec_entries.emplace_back(
cutils::make_unique<Entry>(*entry));
assert(nullptr != vec_entries.back());
vec_entries.back()->set_seq(pending_log_seq_);
}
return vec_entries;
}
std::unique_ptr<raft::RaftState>
RaftImpl::getCurrentRaftState() const
{
auto hs = cutils::make_unique<RaftState>();
assert(nullptr != hs);
hs->set_term(term_);
hs->set_vote(vote_for_);
hs->set_commit(commited_index_);
hs->set_seq(pending_meta_seq_);
return hs;
}
uint64_t RaftImpl::getLogTerm(uint64_t log_index) const
{
const auto entry = getLogEntry(log_index);
if (nullptr == entry) {
return 0ull;
}
return entry->term();
}
bool RaftImpl::isIndexInMem(uint64_t log_index) const
{
return getBaseLogIndex() <= log_index;
}
void RaftImpl::beginVote()
{
assert_role(*this, RaftRole::CANDIDATE);
// start election:
// - increment currentTerm
// - vote for self
// - reset election timer
// - send requestVote RPCs to all other servers
setTerm(term_ + 1); // aka inc term
setVoteFor(true, selfid_);
assignStoreSeq(META_INDEX);
// reset
vote_resps_.clear();
vote_resps_[selfid_] = true;
return ;
}
void RaftImpl::updateVote(uint64_t peer_id, bool current_rsp)
{
// current_rsp:
// - true: vote yes;
// - false: vote no;
assert_role(*this, RaftRole::CANDIDATE);
if (vote_resps_.end() == vote_resps_.find(peer_id)) {
vote_resps_[peer_id] = current_rsp;
return ;
}
bool prev_rsp = vote_resps_[peer_id];
logerr("peer_id %" PRIu64 " prev_rsp %d current_rsp %d",
peer_id, static_cast<int>(prev_rsp), static_cast<int>(current_rsp));
// assert ?
return ;
}
bool RaftImpl::isMajorVoteYes() const
{
assert_role(*this, RaftRole::CANDIDATE);
return current_config_.IsMajorVoteYes(vote_resps_);
}
bool RaftImpl::isMatch(uint64_t log_index, uint64_t log_term) const
{
assert_role(*this, RaftRole::FOLLOWER);
if (0ull == log_index) {
assert(0ull == log_term);
return true; // always
}
assert(0ull < log_index);
assert(0ull < log_term);
const uint64_t local_log_term = getLogTerm(log_index);
if (local_log_term == log_term) {
return true;
}
if (log_index <= commited_index_) {
assert(0ull == local_log_term);
return true;
}
assert(0ull == local_log_term || log_index <= getLastLogIndex());
return false;
}
void RaftImpl::updateLeaderCommitedIndex(uint64_t new_commited_index)
{
assert_role(*this, RaftRole::LEADER);
assert(commited_index_ < new_commited_index);
logdebug("selfid(leader) %" PRIu64 " commited_index_ %" PRIu64
" new_commited_index %" PRIu64,
selfid_, commited_index_, new_commited_index);
commited_index_ = new_commited_index;
}
void RaftImpl::updateFollowerCommitedIndex(uint64_t leader_commited_index)
{
assert_role(*this, RaftRole::FOLLOWER);
assert(commited_index_ <= leader_commited_index);
const uint64_t last_index = getLastLogIndex();
logdebug("selfid %" PRIu64 " commited_index_ %" PRIu64
" last_index %" PRIu64 " leader_commited_index %" PRIu64,
selfid_, commited_index_, last_index, leader_commited_index);
// if leaderCommit > commitIndex,
// set commitIndex = min(leaderCommit, index of last new entry)
commited_index_ = min(leader_commited_index, last_index);
return ;
}
uint64_t
RaftImpl::findConflict(const std::vector<const Entry*>& entries) const
{
if (size_t{0} == entries.size() || true == logs_.empty()) {
return 0ull;
}
assert(size_t{0} < entries.size());
assert(false == logs_.empty());
for (size_t idx = 0; idx < entries.size(); ++idx) {
assert(nullptr != entries[idx]);
if (!isMatch(entries[idx]->index(), entries[idx]->term())) {
return entries[idx]->index();
}
}
return entries[entries.size() -1]->index() + 1ull;
}
bool RaftImpl::updateReplicateState(
uint64_t peer_id,
bool reject, uint64_t reject_hint, uint64_t peer_next_index)
{
assert_role(*this, RaftRole::LEADER);
assert(nullptr != replicate_states_);
bool update =
replicate_states_->UpdateReplicateState(
peer_id, reject, reject_hint, peer_next_index);
if (true == update) {
auto new_commited_index =
0ull == peer_next_index ? 0ull : peer_next_index - 1ull;
if (getTerm() == getLogTerm(new_commited_index) &&
new_commited_index > getCommitedIndex()) {
if (current_config_.IsMajorCommited(
new_commited_index,
replicate_states_->peekMatchIndexes())) {
updateLeaderCommitedIndex(new_commited_index);
}
}
}
return update;
}
void RaftImpl::becomeFollower(uint64_t term)
{
if (nullptr != replicate_states_) {
replicate_states_.reset();
}
assert(nullptr == replicate_states_);
setRole(RaftRole::FOLLOWER);
term = 0ull == term ? term_ + 1ull : term;
assert(term_ < term);
setTerm(term);
setLeader(true, 0ull);
setVoteFor(true, 0ull); // reset vote_for_
assignStoreSeq(META_INDEX);
// new follower => will not timeout immidiate;
resetElectionTimeout();
updateActiveTime(chrono::system_clock::now());
// TODO ??
return ;
}
void RaftImpl::becomeCandidate()
{
assert(nullptr == replicate_states_);
setRole(RaftRole::CANDIDATE);
setLeader(true, 0ull);
// raft paper
// Candidates 5.2
// On conversion to candidate or election timeout elapse,
// start election:
// - inc term
// - set vote for
// - assign store seq
beginVote();
resetElectionTimeout();
updateActiveTime(chrono::system_clock::now());
return ;
}
void RaftImpl::becomeLeader()
{
setRole(RaftRole::LEADER);
// raft paper
// State
// nextIndex[]
// for each server, index of the next log entry to send to that
// server(initialized to leader last log index + 1)
// matchIndex[]
// for each server, index of highest log entry known to be
// replicated on server(initailzed to 0, increases monotonically)
setLeader(false, selfid_);
assert(selfid_ == leader_id_);
assert(nullptr == replicate_states_);
replicate_states_ =
current_config_.CreateReplicateTracker(getLastLogIndex(), MAX_BATCH_SIZE);
assert(nullptr != replicate_states_);
makeHeartbeatTimeout(chrono::system_clock::now());
return ;
}
void RaftImpl::setLeader(bool reset, uint64_t leader_id)
{
logdebug("selfid_ %" PRIu64 " reset %d leader_id_ %" PRIu64
" to leader_id %" PRIu64,
selfid_, static_cast<int>(reset), leader_id_, leader_id);
if (true == reset || 0ull == leader_id_) {
leader_id_ = leader_id;
}
}
bool RaftImpl::isHeartbeatTimeout(
std::chrono::time_point<
std::chrono::system_clock> time_now)
{
return hb_time_ + hb_timeout_ < time_now;
}
void RaftImpl::updateHeartbeatTime(
std::chrono::time_point<
std::chrono::system_clock> next_hb_time)
{
{
auto hb_str = cutils::format_time(hb_time_);
auto next_hb_str = cutils::format_time(next_hb_time);
logdebug("selfid %" PRIu64
" update hb_time_ %s to next_hb_time %s",
getSelfId(),
hb_str.c_str(), next_hb_str.c_str());
}
hb_time_ = next_hb_time;
}
void RaftImpl::makeElectionTimeout(
std::chrono::time_point<std::chrono::system_clock> tp)
{
tp -= chrono::milliseconds{getElectionTimeout() + 1};
updateActiveTime(tp);
}
void RaftImpl::makeHeartbeatTimeout(
std::chrono::time_point<std::chrono::system_clock> tp)
{
tp -= chrono::milliseconds{getHeartbeatTimeout() + 1};
updateHeartbeatTime(tp);
}
std::unique_ptr<raft::RaftState>
RaftImpl::getPendingRaftState() const
{
if (0ull == pending_meta_seq_) {
return nullptr;
}
return getCurrentRaftState();
}
std::vector<std::unique_ptr<raft::Entry>>
RaftImpl::getPendingLogEntries() const
{
if (0ull == pending_log_idx_) {
assert(0ull == pending_log_seq_);
return vector<unique_ptr<Entry>>{};
}
assert(0ull < pending_log_idx_);
assert(0ull < pending_log_seq_);
return getLogEntriesAfter(pending_log_idx_ - 1ull);
}
void RaftImpl::resetElectionTimeout()
{
int next_election_timeout = rtimeout_();
assert(0 < next_election_timeout);
logdebug("election_timeout_ %d next_election_timeout %d",
static_cast<int>(election_timeout_.count()),
next_election_timeout);
election_timeout_ = chrono::milliseconds{next_election_timeout};
}
bool RaftImpl::isPeerUpToDate(uint64_t peer_commited_index) const
{
assert(peer_commited_index <= commited_index_);
return peer_commited_index == commited_index_;
}
void RaftImpl::assertNoPending() const
{
assert(RaftRole::LEADER == getRole());
assert(nullptr != replicate_states_);
for (const auto& id_pending : replicate_states_->peekPendingState()) {
if (getSelfId() == id_pending.first) {
continue;
}
assert(false == id_pending.second);
}
}
int RaftImpl::applyUnCommitedConfEntry(const Entry& conf_entry)
{
ConfChange conf_change;
auto ret = ApplyConfChange(
conf_entry, true, conf_change, current_config_);
if (0 != ret) {
return ret;
}
// 3.
if (nullptr == replicate_states_) {
return 0;
}
assert(RaftRole::LEADER == getRole());
replicate_states_->ApplyConfChange(conf_change, getLastLogIndex());
return 0;
}
int RaftImpl::applyCommitedConfEntry(const Entry& conf_entry)
{
ConfChange conf_change;
return ApplyConfChange(
conf_entry, false, conf_change, commited_config_);
}
int RaftImpl::reconstructCurrentConfig()
{
assert(RaftRole::FOLLOWER == getRole());
current_config_ = commited_config_;
auto last_index = getLastLogIndex();
for (auto index =
getCommitedIndex() + 1ull; index <= last_index; ++index) {
auto entry = getLogEntry(index);
assert(nullptr != entry);
ConfChange conf_change;
auto ret = ApplyConfChange(
*entry, true, conf_change, current_config_);
if (0 != ret) {
return ret;
}
assert(0 == ret);
}
return 0;
}
} // namespace raft
| 31.015757 | 82 | 0.589749 |
a53314e22a638de0302a218fb6db0734a3235269 | 364 | cpp | C++ | headers/main/bw_encode.cpp | SamBuckberry/readslam | 47c5cd0e407f17db08a70488913905f86cffe054 | [
"CC-BY-3.0"
] | null | null | null | headers/main/bw_encode.cpp | SamBuckberry/readslam | 47c5cd0e407f17db08a70488913905f86cffe054 | [
"CC-BY-3.0"
] | null | null | null | headers/main/bw_encode.cpp | SamBuckberry/readslam | 47c5cd0e407f17db08a70488913905f86cffe054 | [
"CC-BY-3.0"
] | null | null | null | #include "../algorithms/sorting.h"
#include "../tools/_fasta.h"
int main (int argc, char * const argv[])
{
if (argc != 3)
{
cout << "Encode a genome's fasta sequences using the Burrows-Wheeler algorithm." << endl;
cout << "Usage: ./burrows_wheeler /infile.fa /outfile.fa" << endl;
exit(0);
}
ReadSlam::FastA::Genome g;
g.bw_encode(argv[1], argv[2]);
}
| 24.266667 | 91 | 0.645604 |
a53361e4645143c7ce4a6fb44ce50adbc3a85dd6 | 2,148 | cpp | C++ | apps/xcomp/src/XCConfig.cpp | gugenstudio/Xcomp | b8c572ec618fa157c4ed07845b87d0ced21b2dd5 | [
"MIT"
] | 1 | 2022-02-18T11:55:57.000Z | 2022-02-18T11:55:57.000Z | apps/xcomp/src/XCConfig.cpp | gugenstudio/xComp | b8c572ec618fa157c4ed07845b87d0ced21b2dd5 | [
"MIT"
] | null | null | null | apps/xcomp/src/XCConfig.cpp | gugenstudio/xComp | b8c572ec618fa157c4ed07845b87d0ced21b2dd5 | [
"MIT"
] | null | null | null | //==================================================================
/// XCConfig.cpp
///
/// Created by Davide Pasca - 2022/01/21
/// See the file "license.txt" that comes with this project for
/// copyright info.
//==================================================================
#include "GTVersions.h"
#include "XCConfig.h"
//==================================================================
void XCConfig::Serialize( SerialJS &v_ ) const
{
v_.MSerializeObjectStart();
SerializeMember( v_, "cfg_savedVer", DStr(GTV_SUITE_VERSION) );
SERIALIZE_THIS_MEMBER( v_, cfg_scanDir );
SERIALIZE_THIS_MEMBER( v_, cfg_scanDirHist );
SERIALIZE_THIS_MEMBER( v_, cfg_saveDir );
SERIALIZE_THIS_MEMBER( v_, cfg_ctrlPanButton );
SERIALIZE_THIS_MEMBER( v_, cfg_dispAutoFit );
SERIALIZE_THIS_MEMBER( v_, cfg_imsConfig );
v_.MSerializeObjectEnd();
}
void XCConfig::Deserialize( DeserialJS &v_ )
{
DESERIALIZE_THIS_MEMBER( v_, cfg_savedVer );
DESERIALIZE_THIS_MEMBER( v_, cfg_scanDir );
DESERIALIZE_THIS_MEMBER( v_, cfg_scanDirHist );
DESERIALIZE_THIS_MEMBER( v_, cfg_saveDir );
DESERIALIZE_THIS_MEMBER( v_, cfg_ctrlPanButton );
DESERIALIZE_THIS_MEMBER( v_, cfg_dispAutoFit );
DESERIALIZE_THIS_MEMBER( v_, cfg_imsConfig );
// remove empty or unreachable directories
for (auto it=cfg_scanDirHist.begin(); it != cfg_scanDirHist.end();)
{
if ( it->empty() || !FU_DirectoryExists( *it ) )
it = cfg_scanDirHist.erase( it );
else
++it;
}
}
//==================================================================
bool XCConfig::AddScanDirToHistory()
{
auto &v = cfg_scanDirHist;
if ( !cfg_scanDir.empty() &&
v.end() == std::find( v.begin(), v.end(), cfg_scanDir ) )
{
// erase the oldest, if there are too many entries
if ( v.size() >= 10 )
v.erase( v.begin() );
// append the new one
v.push_back( cfg_scanDir );
return true;
}
return false;
}
| 33.5625 | 71 | 0.533985 |
a5341057111530e24eeb851aa8f9fe420ae62ddd | 16,339 | cpp | C++ | libcsvsqldb/sql_lexer.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 5 | 2015-09-10T08:53:41.000Z | 2020-05-30T18:42:20.000Z | libcsvsqldb/sql_lexer.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 20 | 2015-09-29T16:16:07.000Z | 2021-06-13T08:08:05.000Z | libcsvsqldb/sql_lexer.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 3 | 2015-09-09T22:51:44.000Z | 2020-11-11T13:19:42.000Z | //
// sql_lexer.h
// csv db
//
// BSD 3-Clause License
// Copyright (c) 2015, Lars-Christian Fürstenberg
// 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.
//
#include "sql_lexer.h"
#include "base/logging.h"
#include "base/string_helper.h"
namespace csvsqldb
{
std::string tokenToString(eToken token)
{
switch(static_cast<csvsqldb::lexer::eToken>(token)) {
case csvsqldb::lexer::UNDEFINED:
return "UNDEFINED";
case csvsqldb::lexer::NEWLINE:
return "NEWLINE";
case csvsqldb::lexer::WHITESPACE:
return "WHITESPACE";
case csvsqldb::lexer::EOI:
return "EOI";
}
switch(token) {
case TOK_NONE:
return "TOK_NONE";
case TOK_IDENTIFIER:
return "identifier";
case TOK_QUOTED_IDENTIFIER:
return "quoted identifier";
case TOK_CONST_STRING:
return "string constant";
case TOK_CONST_INTEGER:
return "integer constant";
case TOK_CONST_BOOLEAN:
return "boolean constant";
case TOK_CONST_DATE:
return "date constant";
case TOK_CONST_REAL:
return "real constant";
case TOK_CONST_CHAR:
return "char constant";
case TOK_DOT:
return ".";
case TOK_DESCRIBE:
return "DESCRIBE";
case TOK_AST:
return "AST";
case TOK_SMALLER:
return "<";
case TOK_GREATER:
return ">";
case TOK_EQUAL:
return "=";
case TOK_NOTEQUAL:
return "<>";
case TOK_GREATEREQUAL:
return ">=";
case TOK_SMALLEREQUAL:
return "<=";
case TOK_CONCAT:
return "||";
case TOK_ADD:
return "+";
case TOK_SUB:
return "-";
case TOK_DIV:
return "/";
case TOK_MOD:
return "%";
case TOK_ASTERISK:
return "*";
case TOK_COMMA:
return ",";
case TOK_SEMICOLON:
return ";";
case TOK_LEFT_PAREN:
return "(";
case TOK_RIGHT_PAREN:
return ")";
case TOK_COMMENT:
return "comment";
case TOK_UNION:
return "UNION";
case TOK_INTERSECT:
return "INTERSECT";
case TOK_EXCEPT:
return "EXCEPT";
case TOK_SELECT:
return "SELECT";
case TOK_AS:
return "AS";
case TOK_ALL:
return "ALL";
case TOK_CAST:
return "CAST";
case TOK_DISTINCT:
return "DISTINCT";
case TOK_FROM:
return "FROM";
case TOK_WHERE:
return "WHERE";
case TOK_ON:
return "ON";
case TOK_USING:
return "USING";
case TOK_NATURAL:
return "NATURAL";
case TOK_LEFT:
return "LEFT";
case TOK_RIGHT:
return "RIGHT";
case TOK_INNER:
return "INNER";
case TOK_OUTER:
return "OUTER";
case TOK_CROSS:
return "CROSS";
case TOK_FULL:
return "FULL";
case TOK_JOIN:
return "JOIN";
case TOK_LIKE:
return "LIKE";
case TOK_AND:
return "AND";
case TOK_OR:
return "OR";
case TOK_NOT:
return "NOT";
case TOK_IS:
return "IS";
case TOK_NULL:
return "NULL";
case TOK_BETWEEN:
return "BETWEEN";
case TOK_IN:
return "IN";
case TOK_EXISTS:
return "EXISTS";
case TOK_GROUP:
return "GROUP";
case TOK_ORDER:
return "ORDER";
case TOK_BY:
return "BY";
case TOK_COLLATE:
return "COLLATE";
case TOK_ASC:
return "ASC";
case TOK_DESC:
return "DESC";
case TOK_HAVING:
return "HAVING";
case TOK_LIMIT:
return "LIMIT";
case TOK_OFFSET:
return "OFFSET";
case TOK_CREATE:
return "CREATE";
case TOK_TABLE:
return "TABLE";
case TOK_IF:
return "IF";
case TOK_CONSTRAINT:
return "CONSTRAINT";
case TOK_PRIMARY:
return "PRIMARY";
case TOK_KEY:
return "KEY";
case TOK_UNIQUE:
return "UNIQUE";
case TOK_DEFAULT:
return "DEFAULT";
case TOK_CHECK:
return "CHECK";
case TOK_BOOL:
return "BOOLEAN";
case TOK_INT:
return "INTEGER";
case TOK_REAL:
return "REAL";
case TOK_STRING:
return "STRING";
case TOK_CHAR:
return "CHARACTER";
case TOK_DATE:
return "DATE";
case TOK_TIME:
return "TIME";
case TOK_TIMESTAMP:
return "TIMESTAMP";
case TOK_ALTER:
return "ALTER";
case TOK_COLUMN:
return "COLUMN";
case TOK_DROP:
return "DROP";
case TOK_ADD_KEYWORD:
return "ADD";
case TOK_SUM:
return "SUM";
case TOK_COUNT:
return "COUNT";
case TOK_AVG:
return "AVG";
case TOK_MAX:
return "MAX";
case TOK_MIN:
return "MIN";
case TOK_CURRENT_DATE:
return "CURRENT_DATE";
case TOK_CURRENT_TIME:
return "CURRENT_TIME";
case TOK_CURRENT_TIMESTAMP:
return "CURRENT_TIMESTAMP";
case TOK_VARYING:
return "VARYING";
case TOK_EXTRACT:
return "EXTRACT";
case TOK_SECOND:
return "SECOND";
case TOK_MINUTE:
return "MINUTE";
case TOK_HOUR:
return "HOUR";
case TOK_YEAR:
return "YEAR";
case TOK_MONTH:
return "MONTH";
case TOK_DAY:
return "DAY";
case TOK_EXPLAIN:
return "EXPLAIN";
case TOK_SHOW:
return "SHOW";
case TOK_MAPPING:
return "MAPPING";
case TOK_EXEC:
return "EXEC";
case TOK_ARBITRARY:
return "ARBITRARY";
}
throw std::runtime_error("just to make VC2013 happy");
}
SQLLexer::SQLLexer(const std::string& input)
: _lexer(std::bind(&SQLLexer::inspectToken, this, std::placeholders::_1))
{
initDefinitions();
initKeywords();
_lexer.setInput(input);
}
void SQLLexer::setInput(const std::string& input)
{
_lexer.setInput(input);
}
void SQLLexer::initDefinitions()
{
_lexer.addDefinition("bool", R"([tT][rR][uU][eE])", TOK_CONST_BOOLEAN);
_lexer.addDefinition("bool", R"([fF][aA][lL][sS][eE])", TOK_CONST_BOOLEAN);
_lexer.addDefinition("bool", R"([uU][nN][kK][nN][oO][wW][nN])", TOK_CONST_BOOLEAN);
_lexer.addDefinition("identifier", R"([_a-zA-Z][_a-zA-Z0-9]*)", TOK_IDENTIFIER);
_lexer.addDefinition("quoted identifier", R"(\"([^\"]*)\")", TOK_QUOTED_IDENTIFIER);
_lexer.addDefinition("char", R"('([^'])')", TOK_CONST_CHAR);
_lexer.addDefinition("string", R"('([^']*)')", TOK_CONST_STRING);
_lexer.addDefinition("concat", R"(\|\|)", TOK_CONCAT);
_lexer.addDefinition("add", R"(\+)", TOK_ADD);
_lexer.addDefinition("comment", R"(--([^\r\n]*))", TOK_COMMENT);
_lexer.addDefinition("sub", R"(-)", TOK_SUB);
_lexer.addDefinition("point", R"(\.)", TOK_DOT);
_lexer.addDefinition("real", R"((?:0|[1-9]\d*)\.\d+)", TOK_CONST_REAL);
_lexer.addDefinition("integer", R"(0|[1-9]\d*)", TOK_CONST_INTEGER);
_lexer.addDefinition("string", R"('([^']*)')", TOK_CONST_STRING);
_lexer.addDefinition("equal", R"(=)", TOK_EQUAL);
_lexer.addDefinition("greater equal", R"(>=)", TOK_GREATEREQUAL);
_lexer.addDefinition("smaller equal", R"(<=)", TOK_SMALLEREQUAL);
_lexer.addDefinition("notequal", R"(<>)", TOK_NOTEQUAL);
_lexer.addDefinition("smaller", R"(<)", TOK_SMALLER);
_lexer.addDefinition("greater", R"(>)", TOK_GREATER);
_lexer.addDefinition("comma", R"(,)", TOK_COMMA);
_lexer.addDefinition("semicolon", R"(;)", TOK_SEMICOLON);
_lexer.addDefinition("asterisk", R"(\*)", TOK_ASTERISK);
_lexer.addDefinition("left_paren", R"(\()", TOK_LEFT_PAREN);
_lexer.addDefinition("right_paren", R"(\))", TOK_RIGHT_PAREN);
_lexer.addDefinition("comment", R"(/\*((.|[\r\n])*?)\*/)", TOK_COMMENT);
_lexer.addDefinition("div", R"(/)", TOK_DIV);
_lexer.addDefinition("mod", R"(%)", TOK_MOD);
}
void SQLLexer::initKeywords()
{
_keywords["UNION"] = eToken(TOK_UNION);
_keywords["SELECT"] = eToken(TOK_SELECT);
_keywords["FROM"] = eToken(TOK_FROM);
_keywords["WHERE"] = eToken(TOK_WHERE);
_keywords["USING"] = eToken(TOK_USING);
_keywords["INTERSECT"] = eToken(TOK_INTERSECT);
_keywords["EXCEPT"] = eToken(TOK_EXCEPT);
_keywords["AS"] = eToken(TOK_AS);
_keywords["ALL"] = eToken(TOK_ALL);
_keywords["CAST"] = eToken(TOK_CAST);
_keywords["DISTINCT"] = eToken(TOK_DISTINCT);
_keywords["ON"] = eToken(TOK_ON);
_keywords["NATURAL"] = eToken(TOK_NATURAL);
_keywords["LEFT"] = eToken(TOK_LEFT);
_keywords["RIGHT"] = eToken(TOK_RIGHT);
_keywords["INNER"] = eToken(TOK_INNER);
_keywords["OUTER"] = eToken(TOK_OUTER);
_keywords["CROSS"] = eToken(TOK_CROSS);
_keywords["FULL"] = eToken(TOK_FULL);
_keywords["JOIN"] = eToken(TOK_JOIN);
_keywords["LIKE"] = eToken(TOK_LIKE);
_keywords["AND"] = eToken(TOK_AND);
_keywords["OR"] = eToken(TOK_OR);
_keywords["NOT"] = eToken(TOK_NOT);
_keywords["IS"] = eToken(TOK_IS);
_keywords["NULL"] = eToken(TOK_NULL);
_keywords["BETWEEN"] = eToken(TOK_BETWEEN);
_keywords["IN"] = eToken(TOK_IN);
_keywords["EXISTS"] = eToken(TOK_EXISTS);
_keywords["GROUP"] = eToken(TOK_GROUP);
_keywords["ORDER"] = eToken(TOK_ORDER);
_keywords["BY"] = eToken(TOK_BY);
_keywords["COLLATE"] = eToken(TOK_COLLATE);
_keywords["ASC"] = eToken(TOK_ASC);
_keywords["DESC"] = eToken(TOK_DESC);
_keywords["HAVING"] = eToken(TOK_HAVING);
_keywords["LIMIT"] = eToken(TOK_LIMIT);
_keywords["OFFSET"] = eToken(TOK_OFFSET);
_keywords["CREATE"] = eToken(TOK_CREATE);
_keywords["TABLE"] = eToken(TOK_TABLE);
_keywords["IF"] = eToken(TOK_IF);
_keywords["BOOLEAN"] = eToken(TOK_BOOL);
_keywords["BOOL"] = eToken(TOK_BOOL);
_keywords["INT"] = eToken(TOK_INT);
_keywords["INTEGER"] = eToken(TOK_INT);
_keywords["REAL"] = eToken(TOK_REAL);
_keywords["FLOAT"] = eToken(TOK_REAL);
_keywords["DOUBLE"] = eToken(TOK_REAL);
_keywords["VARCHAR"] = eToken(TOK_STRING);
_keywords["CHAR"] = eToken(TOK_CHAR);
_keywords["CHARACTER"] = eToken(TOK_CHAR);
_keywords["DATE"] = eToken(TOK_DATE);
_keywords["TIME"] = eToken(TOK_TIME);
_keywords["TIMESTAMP"] = eToken(TOK_TIMESTAMP);
_keywords["CONSTRAINT"] = eToken(TOK_CONSTRAINT);
_keywords["PRIMARY"] = eToken(TOK_PRIMARY);
_keywords["KEY"] = eToken(TOK_KEY);
_keywords["UNIQUE"] = eToken(TOK_UNIQUE);
_keywords["DEFAULT"] = eToken(TOK_DEFAULT);
_keywords["CHECK"] = eToken(TOK_CHECK);
_keywords["ALTER"] = eToken(TOK_ALTER);
_keywords["COLUMN"] = eToken(TOK_COLUMN);
_keywords["DROP"] = eToken(TOK_DROP);
_keywords["ADD"] = eToken(TOK_ADD_KEYWORD);
_keywords["SUM"] = eToken(TOK_SUM);
_keywords["COUNT"] = eToken(TOK_COUNT);
_keywords["AVG"] = eToken(TOK_AVG);
_keywords["MAX"] = eToken(TOK_MAX);
_keywords["MIN"] = eToken(TOK_MIN);
_keywords["CURRENT_DATE"] = eToken(TOK_CURRENT_DATE);
_keywords["CURRENT_TIME"] = eToken(TOK_CURRENT_TIME);
_keywords["CURRENT_TIMESTAMP"] = eToken(TOK_CURRENT_TIMESTAMP);
_keywords["VARYING"] = eToken(TOK_VARYING);
_keywords["DESCRIBE"] = eToken(TOK_DESCRIBE);
_keywords["AST"] = eToken(TOK_AST);
_keywords["EXTRACT"] = eToken(TOK_EXTRACT);
_keywords["SECOND"] = eToken(TOK_SECOND);
_keywords["MINUTE"] = eToken(TOK_MINUTE);
_keywords["HOUR"] = eToken(TOK_HOUR);
_keywords["YEAR"] = eToken(TOK_YEAR);
_keywords["MONTH"] = eToken(TOK_MONTH);
_keywords["DAY"] = eToken(TOK_DAY);
_keywords["EXPLAIN"] = eToken(TOK_EXPLAIN);
_keywords["SHOW"] = eToken(TOK_SHOW);
_keywords["MAPPING"] = eToken(TOK_MAPPING);
_keywords["EXEC"] = eToken(TOK_EXEC);
_keywords["ARBITRARY"] = eToken(TOK_ARBITRARY);
}
void SQLLexer::inspectToken(csvsqldb::lexer::Token& token)
{
CSVSQLDB_CLASSLOG(SQLLexer, 2, "Intercepted : " << token._value);
if(token._token == TOK_IDENTIFIER) {
Keywords::const_iterator iter = _keywords.find(csvsqldb::toupper(token._value));
if(iter != _keywords.end()) {
token._token = iter->second;
CSVSQLDB_CLASSLOG(SQLLexer, 2, "Intercepted : adapted token");
}
}
}
csvsqldb::lexer::Token SQLLexer::next()
{
csvsqldb::lexer::Token tok = _lexer.next();
while(tok._token == TOK_COMMENT) {
tok = _lexer.next();
}
return tok;
}
}
| 37.134091 | 98 | 0.53461 |
a536ed610414892db435e13ee5d94da23e0df509 | 3,828 | hpp | C++ | rosidl_typesupport_introspection_tests/include/rosidl_typesupport_introspection_tests/libraries.hpp | tsungchent/rosidl | caef9b8f820dfcb16e6a2df9118c5669cc816642 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:29:46.000Z | 2022-02-28T21:29:46.000Z | rosidl_typesupport_introspection_tests/include/rosidl_typesupport_introspection_tests/libraries.hpp | tsungchent/rosidl | caef9b8f820dfcb16e6a2df9118c5669cc816642 | [
"Apache-2.0"
] | null | null | null | rosidl_typesupport_introspection_tests/include/rosidl_typesupport_introspection_tests/libraries.hpp | tsungchent/rosidl | caef9b8f820dfcb16e6a2df9118c5669cc816642 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROSIDL_TYPESUPPORT_INTROSPECTION_TESTS__LIBRARIES_HPP_
#define ROSIDL_TYPESUPPORT_INTROSPECTION_TESTS__LIBRARIES_HPP_
#include <rcutils/macros.h>
namespace rosidl_typesupport_introspection_tests
{
/// A literal type to hold message symbols.
struct MessageTypeSupportSymbolRecord
{
const char * symbol;
};
/// A literal type to hold service symbols.
struct ServiceTypeSupportSymbolRecord
{
const char * symbol;
const MessageTypeSupportSymbolRecord request;
const MessageTypeSupportSymbolRecord response;
};
/// A literal type to hold action symbols.
struct ActionTypeSupportSymbolRecord
{
const char * symbol;
const MessageTypeSupportSymbolRecord feedback;
const MessageTypeSupportSymbolRecord feedback_message;
const MessageTypeSupportSymbolRecord result;
const MessageTypeSupportSymbolRecord goal;
const ServiceTypeSupportSymbolRecord send_goal;
const ServiceTypeSupportSymbolRecord get_result;
};
/// Makes a MessageTypeSupportSymbolRecord literal for a message.
#define MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, interface_type, message_name) \
{RCUTILS_STRINGIFY( \
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME( \
typesupport_name, package_name, interface_type, message_name))}
/// Makes a MessageTypeSupportSymbolRecord literal for a service.
#define SERVICE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, interface_type, service_name) \
{RCUTILS_STRINGIFY( \
ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME( \
typesupport_name, package_name, interface_type, service_name)), \
MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(service_name, _Request)), \
MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(service_name, _Response))}
/// Makes a MessageTypeSupportSymbolRecord literal for an action.
#define ACTION_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, interface_type, action_name) \
{RCUTILS_STRINGIFY( \
ROSIDL_TYPESUPPORT_INTERFACE__ACTION_SYMBOL_NAME( \
typesupport_name, package_name, interface_type, action_name)), \
MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(action_name, _Feedback)), \
MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(action_name, _FeedbackMessage)), \
MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(action_name, _Result)), \
MESSAGE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(action_name, _Goal)), \
SERVICE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(action_name, _SendGoal)), \
SERVICE_TYPESUPPORT_SYMBOL_RECORD( \
typesupport_name, package_name, \
interface_type, RCUTILS_JOIN(action_name, _GetResult))}
} // namespace rosidl_typesupport_introspection_tests
#endif // ROSIDL_TYPESUPPORT_INTROSPECTION_TESTS__LIBRARIES_HPP_
| 39.463918 | 75 | 0.785005 |
a536f2d5e320c70a40fa940527f46bc4c9407327 | 10,256 | cpp | C++ | 11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp | EatAllBugs/autonomous_learning | 02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47 | [
"MIT"
] | 14 | 2021-09-01T14:25:45.000Z | 2022-02-21T08:49:57.000Z | 11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp | yinflight/autonomous_learning | 02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47 | [
"MIT"
] | null | null | null | 11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp | yinflight/autonomous_learning | 02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47 | [
"MIT"
] | 3 | 2021-10-10T00:58:29.000Z | 2022-01-23T13:16:09.000Z | /********************************************************
Stanford Driving Software
Copyright (c) 2011 Stanford University
All rights reserved.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* The names of the contributors may not be used to endorse
or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
********************************************************/
#include <iostream>
#include <global.h>
#include <textureCache.h>
#include <imageryServer.h>
#include <imagery_proj.h>
namespace vlr {
TextureCache::TextureCache(const std::string& imagery_root, uint64_t max_images) :
comp_refs_(image_), version_num_(0), max_images_(max_images), imagery_root_(imagery_root),
last_grayscale_(false), current_reference_(0), stop_thread_(false) {
for (uint64_t i = 0; i < max_images_; i++) {
image_.push_back(new TimedImage);
}
pthread_create(&loader_thread_id_, NULL, threadCBWrapper<TextureCache, &TextureCache::loaderThread>, this);
}
TextureCache::~TextureCache() {
stop_thread_ = true;
pthread_join(loader_thread_id_, NULL);
for (uint64_t i = 0; i < max_images_; i++) {
delete image_[i];
}
}
bool TextureCache::sameId(TileId& id1, TileId& id2) {
if (id1.type != id2.type) return false;
if (id1.x != id2.x) return false;
if (id1.y != id2.y) return false;
if (id1.res != id2.res) return false;
if (id1.zone != id2.zone) return false;
return true;
}
uint64_t TextureCache::lookup(TileId id) {
/* locate image in cache */
bool found = false;
uint64_t which = 0;
for (uint64_t i = 0; i < max_images_; i++) {
if (image_[i]->state != UNINITIALIZED && sameId(image_[i]->id, id)) {
which = i;
found = true;
break;
}
}
if (found) {
// image is in cache
image_[which]->last_reference = current_reference_;
current_reference_++;
return which;
}
// image is not in cache
// find unused or oldest used image; TODO: optimize search
for (uint64_t i = 0; i < max_images_; i++) {
if (image_[i]->state == UNINITIALIZED) {
found = true;
which = i;
break;
}
else if (image_[i]->state == READY && (!found || (found && image_[i]->last_reference < image_[which]->last_reference))) {
found = true;
which = i;
}
}
if (found) {
if (image_[which]->state == READY) {
if (image_[which]->image != NULL) {
delete image_[which]->image;
image_[which]->image = NULL;
}
}
image_[which]->exists = true;
image_[which]->last_reference = current_reference_;
image_[which]->id = id;
image_[which]->state = REQUESTED;
current_reference_++;
return which;
}
else {
throw VLRException("Image list has no empty spots. This shouldn't happen.");
}
}
void TextureCache::resetCounters() {
static std::vector<int64_t> id;
if (id.size() != max_images_) {
id.resize(max_images_);
}
for (uint64_t i = 0; i < max_images_; i++) {id[i] = i;}
sort(id.begin(), id.end(), comp_refs_);
for (uint64_t i = 0; i < max_images_; i++) {
image_[id[i]]->last_reference = i;
}
current_reference_ = max_images_ + 1;
}
void TextureCache::syncTexture(uint64_t i) {
TimedImage& image = *image_[i];
if (image.state == READY && image.needs_sync) {
image.needs_sync = false;
if (image.image == NULL) return;
image.texture.updateFromImage(*image.image);
delete image.image;
image.image = NULL;
}
}
bool TextureCache::syncCache() {
static int32_t count = 0;
if (count > 10) { // ?!?
resetCounters();
count = 0;
}
count++;
bool needs_sync = false;
for (uint64_t i = 0; i < max_images_; i++)
if (image_[i]->needs_sync) {
needs_sync = true;
break;
}
if (needs_sync) {
for (uint64_t i = 0; i < max_images_; i++) {
if (image_[i]->needs_sync) {
syncTexture(i);
}
}
return true;
}
return false;
}
Texture* TextureCache::get(const std::string& detected_subdir, TileId& id, int priority, ImageState_t& state) {
// std:: cout << "detected_subdir: " << detected_subdir << std::endl;
// std:: cout << "imagery_root_: " << imagery_root_ << std::endl;
// std:: cout << "Requested tile id with type " << id.type << "; x, y: " << id.x << ", " << id.y << "; res: " << id.res << "; zone: "<< id.zone << std::endl;
if(!detected_subdir.empty() && detected_subdir_ != detected_subdir) {
detected_subdir_ = detected_subdir;
}
uint64_t i = 0;
try {
i = lookup(id);
}
catch(vlr::Ex<>& e) {
std::cout << e.what() << std::endl;
state = UNINITIALIZED;
return NULL;
}
if (priority && image_[i]->state == READY) {syncTexture(i);}
image_[i]->last_reference = current_reference_;
current_reference_++;
if (image_[i]->state != UNINITIALIZED && image_[i]->exists) {
state = image_[i]->state;
last_grayscale_ = image_[i]->grayscale;
return &image_[i]->texture;
}
state = UNINITIALIZED;
return NULL;
}
size_t curl_callback(void* ptr, size_t size, size_t nmemb, void* data) {
std::vector<uint8_t>* mem = static_cast<std::vector<uint8_t>*>(data);
size_t realsize = size * nmemb;
mem->resize(mem->size() + realsize + 1); // +1 to have a final zero element
memcpy(&((*mem)[mem->size()]), ptr, realsize);
return realsize;
}
void* TextureCache::loaderThread() {
char server_name[200], filename[200], whole_filename[200];
int server_port;
char *mark, *mark2;
#ifdef HAVE_LIBCURL
CURLcode curl_return;
/* init the curl session */
curl_global_init(CURL_GLOBAL_ALL);
CURL* curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, curl_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&curl_buf_);
curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 1);
curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1);
curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);
#endif
sleep(1); // ?!?
while (!stop_thread_) {
for (uint64_t i = 0; i < max_images_; i++) {
if (image_[i]->state == REQUESTED) {
if (version_num_ != 2) {
if (image_[i]->id.type == Imagery::COLOR) dgc_terra_color_tile_filename(image_[i]->id, filename, version_num_);
else if (image_[i]->id.type == Imagery::TOPO) dgc_terra_topo_tile_filename(image_[i]->id, filename, version_num_);
else if (image_[i]->id.type == Imagery::LASER) dgc_laser_tile_filename(image_[i]->id, filename, version_num_);
else if (image_[i]->id.type == Imagery::GSAT) dgc_gmaps_tile_filename(image_[i]->id, filename);
else if (image_[i]->id.type == Imagery::DARPA) dgc_darpa_tile_filename(image_[i]->id, filename, version_num_);
else if (image_[i]->id.type == Imagery::BW) dgc_terra_bw_tile_filename(image_[i]->id, filename);
if (version_num_ == 0) {
sprintf(whole_filename, "%s/%s/%s", imagery_root_.c_str(), detected_subdir_.c_str(), filename);
}
else if (version_num_ == 1) {
sprintf(whole_filename, "%s/%s", imagery_root_.c_str(), filename);
}
}
switch (version_num_) {
case 0:
if (dgc::dgc_file_exists(whole_filename)) {
image_[i]->image = new cv::Mat;
*image_[i]->image = cv::imread(whole_filename, CV_LOAD_IMAGE_ANYCOLOR);
}
else {
image_[i]->image = NULL;
}
break;
case 1:
#ifdef HAVE_LIBCURL
/* handle http queries with libcurl */
curl_easy_setopt(curl_handle, CURLOPT_URL, whole_filename);
curl_return = curl_easy_perform(curl_handle);
if(stop_thread_) {return NULL;} // ?!?
if(curl_return == 0) {
image_[i]->image = cv::imdecode(cv::Mat(curl_buf_, false), CV_LOAD_IMAGE_ANYCOLOR);
}
curl_buf_.clear();
#else
image_[i]->image = new cv::Mat;
*image_[i]->image = cv::imread(whole_filename, CV_LOAD_IMAGE_ANYCOLOR);
#endif
break;
case 2:
strcpy(server_name, imagery_root_.c_str() + 6);
if ((mark = strchr(server_name, ':')) != NULL) {
server_port = strtol(mark + 1, &mark2, 10);
*mark = '\0';
}
else {
server_port = 3000;
if ((mark = strchr(server_name, '/')) != NULL) *mark = '\0';
}
image_[i]->image = img_server_.getImage(server_name, server_port, image_[i]->id);
break;
}
if (!image_[i]->image) {
image_[i]->exists = false;
}
else {
image_[i]->grayscale = (image_[i]->image->channels() == 1);
}
image_[i]->needs_sync = true;
image_[i]->state = READY;
}
}
usleep(10000);
}
return NULL;
}
} // namespace vlr
| 30.984894 | 158 | 0.621002 |
a537453ebe8afbcecef93c2edf6967138dd7c11d | 1,899 | hxx | C++ | session/KAutoLogon.hxx | Peter2121/kts | fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a | [
"BSD-3-Clause"
] | null | null | null | session/KAutoLogon.hxx | Peter2121/kts | fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a | [
"BSD-3-Clause"
] | null | null | null | session/KAutoLogon.hxx | Peter2121/kts | fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <algorithm>
#include "..\shared\KTrace.hxx"
#include "..\shared\Kini.hxx"
#include "..\shared\KSlre.hxx"
class KAutoLogon
{
private:
/*==============================================================================
* var
*=============================================================================*/
struct Pattern
{
std::string address;
std::string username;
std::string password;
std::string domain;
};
std::vector < Pattern > patterns;
public:
/*==============================================================================
* load from file
*=============================================================================*/
void Load( std::string file )
{
ktrace_in( );
ktrace( "KAutoLogon::Load( " << file << " )" );
KIni ini;
ini.File( file );
for( unsigned i = 0; i < 1024; i++ )
{
Pattern p;
std::stringstream s;
s << "address" << i;
if( !ini.GetKey( "KAutoLogon", s.str( ), p.address, "eof" ) ) break;
s.str( "" );
s << "username" << i;
ini.GetKey( "KAutoLogon", s.str( ), p.username );
s.str( "" );
s << "password" << i;
ini.GetKey( "KAutoLogon", s.str( ), p.password );
s.str( "" );
s << "domain" << i;
ini.GetKey( "KAutoLogon", s.str( ), p.domain );
this->patterns.push_back( p );
}
}
bool GetAutoCredentials( const std::string& ipaddress, std::string& username, std::string& password, std::string& domain )
{
ktrace_in( );
ktrace( "KAutoLogon::GetAutoCredentials( " << ipaddress << ", <out> )" );
for( unsigned i = 0; i < this->patterns.size( ); i++ )
{
KSlre kslre;
if(kslre.Match(ipaddress, patterns[i].address))
{
username = patterns[i].username;
password = patterns[i].password;
domain = patterns[i].domain;
return true;
}
}
return false;
}
};
| 23.7375 | 124 | 0.460242 |
a539d799a6c38157168ce01558691874c43f1187 | 1,216 | cpp | C++ | src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp | Armanimani/Game-Engine | 8087cd999f7264488d24a5dc5571b659347a49dd | [
"MIT"
] | null | null | null | src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp | Armanimani/Game-Engine | 8087cd999f7264488d24a5dc5571b659347a49dd | [
"MIT"
] | 1 | 2017-04-05T01:40:02.000Z | 2017-04-05T07:36:55.000Z | src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp | Armanimani/Game-Engine | 8087cd999f7264488d24a5dc5571b659347a49dd | [
"MIT"
] | null | null | null | #include "SingnedDistanceOutlineTextShader.h"
void SignedDistanceOutlineTextShader::loadAllToUniform(const std::shared_ptr<GUITextModel> model)
{
SignedDistanceTextShader::loadAllToUniform(model);
loadToUniform(location_outlineColor, model->getMaterial()->getProperties().color2);
loadToUniform(location_outlineWidth, model->getMaterial()->getProperties().fontOutlineWidth);
loadToUniform(location_outlineEdge, model->getMaterial()->getProperties().fontOutlineEdge);
loadToUniform(location_outlineOffsetX, model->getMaterial()->getProperties().fontOutlineOffsetX);
loadToUniform(location_outlineOffsetY, model->getMaterial()->getProperties().fontOutlineOffsetY);
}
void SignedDistanceOutlineTextShader::getAllUniformLocations()
{
SignedDistanceTextShader::getAllUniformLocations();
std::string temp;
temp = "matOutlineColor";
location_outlineColor = getUniformLocation(temp);
temp = "matOutlineWidth";
location_outlineWidth = getUniformLocation(temp);
temp = "matOutlineEdge";
location_outlineEdge = getUniformLocation(temp);
temp = "matOutlineOffsetX";
location_outlineOffsetX = getUniformLocation(temp);
temp = "matOutlineOffsetY";
location_outlineOffsetY = getUniformLocation(temp);
}
| 34.742857 | 98 | 0.817434 |
a53a645d257e0e8c8f80c93d96c20b152697713a | 4,263 | hpp | C++ | src/graph/include/graph/breadth_first_search.hpp | SkyterX/rpclass | 5e80ec4e0b876eb498351bcf7d6f5983fe5c7934 | [
"Apache-2.0"
] | null | null | null | src/graph/include/graph/breadth_first_search.hpp | SkyterX/rpclass | 5e80ec4e0b876eb498351bcf7d6f5983fe5c7934 | [
"Apache-2.0"
] | null | null | null | src/graph/include/graph/breadth_first_search.hpp | SkyterX/rpclass | 5e80ec4e0b876eb498351bcf7d6f5983fe5c7934 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <queue>
#include <graph/graph.hpp>
#include <graph/properties.hpp>
#include <graph/static_graph.hpp>
namespace graph {
template <typename ColorMapTag, typename V, typename E>
struct GenerateBFSGraph {};
template <typename ColorMapTag, typename... P1s, typename... P2s>
struct GenerateBFSGraph<ColorMapTag, Properties<P1s...>, Properties<P2s...>> {
using type = StaticGraph<Properties<Property<ColorMapTag, char>, P1s...>, Properties<P2s...>>;
};
template <typename Graph, typename ColorMap>
struct DefaultBFSVisitor {
//is invoked on every vertex before the start of the search.
void initialize_vertex(const typename graph_traits<Graph>::vertex_descriptor& v,
Graph&) {
graph::put(color, v, typename property_traits<ColorMap>::value_type(0));
};
// is invoked in each vertex as it is removed from the queue.
void examine_vertex(const typename graph_traits<Graph>::vertex_descriptor&,
Graph&) {};
//is invoked on every out - edge of each vertex immediately after the vertex
// is removed from the queue.
void examine_edge(const typename graph_traits<Graph>::edge_descriptor&,
Graph& g) {};
// is invoked(in addition to examine_edge()) if the edge is a tree edge.
// The target vertex of edge e is discovered at this time.
void tree_edge(const typename graph_traits<Graph>::edge_descriptor&,
Graph& g) {};
// is invoked the first time the algorithm encounters vertex u.
// All vertices closer to the source vertex have been discovered,
// and vertices further from the source have not yet been discovered.
void discover_vertex(const typename graph_traits<Graph>::vertex_descriptor&,
Graph&) {};
//is invoked(in addition to examine_edge()) if the edge is not a tree edge.
void non_tree_edge(const typename graph_traits<Graph>::edge_descriptor&,
Graph&) {};
// is invoked(in addition to non_tree_edge()) if the target vertex is colored
// gray at the time of examination.The color gray indicates that the vertex
// is currently in the queue.
void gray_target(const typename graph_traits<Graph>::edge_descriptor&,
Graph&) {};
// is invoked(in addition to non_tree_edge()) if the target vertex is colored
// black at the time of examination.The color black indicates that the vertex
// is no longer in the queue.
void black_target(const typename graph_traits<Graph>::edge_descriptor&,
Graph&) {};
// is invoked after all of the out edges of u have been examined and all of
// the adjacent vertices have been discovered.
void finish_vertex(const typename graph_traits<Graph>::vertex_descriptor&,
Graph&) {};
DefaultBFSVisitor(ColorMap& color) :color(color) {};
DefaultBFSVisitor(ColorMap&& color) :color(color) {};
ColorMap color;
};
template <class Graph, class ColorMap,
class BFSVisitor = DefaultBFSVisitor<Graph, ColorMap>>
void breadth_first_search(Graph& graph,
const typename graph_traits<Graph>::vertex_descriptor& s,
ColorMap& color, BFSVisitor visitor = BFSVisitor{}) {
typename property_traits<ColorMap>::value_type white = 0;
typename property_traits<ColorMap>::value_type grey = 1;
typename property_traits<ColorMap>::value_type black = 2;
if (graph::get(color, s) != white)
return;
std::queue<typename graph_traits<Graph>::vertex_descriptor> vQueue;
auto vRange = vertices(graph);
for (auto vIt = vRange.first; vIt != vRange.second; ++vIt) {
visitor.initialize_vertex(*vIt, graph);
}
vQueue.push(s);
while (!vQueue.empty()) {
auto src = vQueue.front();
visitor.examine_vertex(src, graph);
auto outRange = out_edges(src, graph);
graph::put(color, src, black);
for (auto outIt = outRange.first; outIt != outRange.second; ++outIt) {
auto e = *outIt;
auto tgt = target(e, graph);
visitor.examine_edge(e, graph);
if (graph::get(color, tgt) == white) {
visitor.discover_vertex(tgt, graph);
visitor.tree_edge(e, graph);
graph::put(color, tgt, grey);
vQueue.push(tgt);
}
else if (graph::get(color, tgt) == grey) visitor.gray_target(e, graph);
else visitor.black_target(e, graph);
};
visitor.finish_vertex(src, graph);
vQueue.pop();
}
};
}
| 36.435897 | 96 | 0.703964 |
a53bcff7875e40227554a2f5c083863f61245ec9 | 6,622 | cpp | C++ | test/unittest/step_tileset_test.cpp | albin-johansson/step | f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab | [
"MIT"
] | 4 | 2020-06-05T11:56:11.000Z | 2020-11-13T14:49:06.000Z | test/unittest/step_tileset_test.cpp | albin-johansson/step | f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab | [
"MIT"
] | 8 | 2020-05-23T09:35:03.000Z | 2020-06-20T22:15:02.000Z | test/unittest/step_tileset_test.cpp | albin-johansson/step | f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab | [
"MIT"
] | null | null | null | #include "step_tileset.hpp"
#include <doctest.h>
#include <string_view>
#include "step_exception.hpp"
#include "step_test_utils.h"
using namespace step;
inline static constexpr std::string_view prefix = "resource/tileset/";
TEST_SUITE("Tileset")
{
TEST_CASE("Parsing external tileset")
{
const auto tileset = tileset::external(
prefix, 4_gid, "tileset_data_for_external_tileset.json");
CHECK(tileset->columns() == 32);
CHECK(tileset->first_gid() == 4_gid);
CHECK(tileset->source() == "tileset_data_for_external_tileset.json");
CHECK(tileset->image() == "../terrain.png");
CHECK(tileset->image_width() == 1024);
CHECK(tileset->image_height() == 768);
CHECK(tileset->margin() == 18);
CHECK(tileset->name() == "external_tileset");
CHECK(tileset->spacing() == 7);
CHECK(tileset->tile_count() == 1024);
CHECK(tileset->tile_width() == 64);
CHECK(tileset->tile_height() == 32);
CHECK(tileset->json_version() == 1.2);
CHECK(tileset->tiled_version() == "1.3.4");
CHECK(!tileset->get_grid());
CHECK(!tileset->get_tile_offset());
}
TEST_CASE("Parsing embedded tileset")
{
const auto tileset = tileset::embedded(
detail::parse_json("resource/tileset/embedded_tileset.json"));
CHECK(tileset->first_gid() == 7_gid);
CHECK(tileset->columns() == 48);
CHECK(tileset->source() == "");
CHECK(tileset->image() == "sam/is/the/hero.png");
CHECK(tileset->image_width() == 1270);
CHECK(tileset->image_height() == 960);
CHECK(tileset->margin() == 77);
CHECK(tileset->name() == "embedded_tileset");
CHECK(tileset->tile_count() == 63);
CHECK(tileset->spacing() == 82);
CHECK(tileset->tile_width() == 55);
CHECK(tileset->tile_height() == 27);
CHECK(tileset->background_color() == color{"#12345678"});
CHECK(tileset->transparent_color() == color{"#CCDDEEFF"});
CHECK(tileset->json_version() == 1.2);
CHECK(tileset->tiled_version() == "1.3.4");
SUBCASE("Parsing grid")
{
const auto grid = tileset->get_grid();
REQUIRE(grid);
CHECK(grid->get_orientation() == grid::orientation::isometric);
CHECK(grid->width() == 48);
CHECK(grid->height() == 64);
}
SUBCASE("Parsing tile offset")
{
const auto tileOffset = tileset->get_tile_offset();
REQUIRE(tileOffset);
CHECK(tileOffset->x() == 1574);
CHECK(tileOffset->y() == 753);
}
SUBCASE("Parsing terrains")
{
const auto& terrains = tileset->terrains();
REQUIRE(terrains.size() == 3);
const auto& firstTerrain = terrains.at(0);
CHECK(firstTerrain.name() == "ground");
CHECK(firstTerrain.tile() == 4_lid);
{
REQUIRE(firstTerrain.get_properties()->amount() != 0);
const auto property = firstTerrain.get_properties()->get("foo");
CHECK(property.name() == "foo");
REQUIRE(property.get_type() == property::type::boolean);
CHECK(property.get<bool>());
}
const auto& secondTerrain = terrains.at(1);
CHECK(secondTerrain.name() == "chasm");
CHECK(secondTerrain.tile() == 12_lid);
const auto& thirdTerrain = terrains.at(2);
CHECK(thirdTerrain.name() == "cliff");
CHECK(thirdTerrain.tile() == 36_lid);
}
}
TEST_CASE("Tileset with properties")
{
const auto tileset = tileset::embedded(
detail::parse_json("resource/tileset/with_properties.json"));
const auto* properties = tileset->get_properties();
REQUIRE(properties);
REQUIRE(properties->amount() == 2);
const auto& firstProperty = properties->get("aFloat");
CHECK(firstProperty.name() == "aFloat");
CHECK(firstProperty.get_type() == property::type::floating);
CHECK(firstProperty.get<float>() == 7.5f);
const auto& secondProperty = properties->get("aString");
CHECK(secondProperty.name() == "aString");
CHECK(secondProperty.get_type() == property::type::string);
CHECK(secondProperty.get<std::string>() == "Hello");
}
TEST_CASE("Tileset with tiles")
{
SUBCASE("Check first tile")
{
const auto tileset = tileset::embedded(
detail::parse_json("resource/tileset/with_tiles.json"));
const auto& tiles = tileset->tiles();
REQUIRE(tiles.size() == 2);
const auto& tile = tiles.at(0);
CHECK(tile.id() == 187_lid);
SUBCASE("Animation")
{
const auto animation = tile.get_animation();
REQUIRE(animation);
CHECK(animation->num_frames() == 3);
const auto& frames = animation->frames();
for (int i = 0; i < 3; ++i) {
CHECK(frames.at(i).duration() == 900);
CHECK(frames.at(i).tile_id() == 187_lid + local_id{i});
}
}
SUBCASE("Properties")
{
const auto* properties = tile.get_properties();
REQUIRE(properties);
REQUIRE(properties->amount() == 1);
const auto& property = properties->get("name");
CHECK(property.name() == "name");
CHECK(property.get_type() == property::type::string);
CHECK(property.get<std::string>() == "waterTile");
}
}
SUBCASE("Check second tile")
{
const auto tileset = tileset::embedded(
detail::parse_json("resource/tileset/with_tiles.json"));
auto& tiles = tileset->tiles();
REQUIRE(tiles.size() == 2);
const auto& tile = tiles.at(1);
CHECK(tile.id() == 370_lid);
SUBCASE("Properties")
{
const auto properties = tile.get_properties();
REQUIRE(properties->amount() == 2);
const auto& firstProperty = properties->get("coolness");
CHECK(firstProperty.name() == "coolness");
REQUIRE(firstProperty.get_type() == property::type::integer);
CHECK(firstProperty.get<int>() == 9000);
const auto& secondProperty = properties->get("frodo");
CHECK(secondProperty.name() == "frodo");
REQUIRE(secondProperty.get_type() == property::type::string);
CHECK(secondProperty.get<std::string>() == "sandTile");
}
}
}
TEST_CASE("Embedded tileset without explicit first GID")
{
const auto tileset = tileset::embedded(
detail::parse_json("resource/tileset/embedded_tileset_no_gid.json"));
CHECK(tileset->first_gid() == 1_gid);
}
TEST_CASE("Tileset missing type attribute")
{
CHECK_THROWS_WITH_AS(tileset::embedded(detail::parse_json(
"resource/tileset/tileset_wrong_type.json")),
"Tileset \"type\" must be \"tileset\"!",
step_exception);
}
}
| 31.836538 | 77 | 0.609333 |
a53d3078d6e68e6aca1bc30353ac37d5efc991bf | 1,410 | cpp | C++ | sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | 1 | 2020-02-29T03:26:32.000Z | 2020-02-29T03:26:32.000Z | sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp | ashtonmv/sphinx_vdw | 5896fee0d92c06e883b72725cb859d732b8b801f | [
"Apache-2.0"
] | null | null | null | // ---------------------------------------------------------------------------
//
// The general purpose cross platform C/C++ framework
//
// S x A c c e l e r a t e
//
// Home: https://www.sxlib.de
// License: Apache 2
// Authors: see src/AUTHORS
//
// ---------------------------------------------------------------------------
#include <SxDemo4Parser.h>
SxDemo4Parser::SxDemo4Parser ()
: SxParserBase (),
SxDemo4Ast ()
{
SX_TRACE ();
ssize_t rootId = 0;
push (rootId);
}
SxDemo4Parser::~SxDemo4Parser ()
{
// empty
}
void SxDemo4Parser::push (ssize_t id)
{
SX_TRACE ();
stack.append (id);
}
SxDemo4AstNode &SxDemo4Parser::pop ()
{
SX_TRACE ();
SX_CHECK (errors.getSize() > 0 || stack.getSize() > 0);
ssize_t id = stack.last ();
stack.removeLast ();
return *(ast.begin(sx::Forward, id));
}
SxDemo4AstNode &SxDemo4Parser::getCurrent ()
{
SX_TRACE ();
return *(ast.begin(sx::Forward, stack.last()));
}
SxDemo4AstNode &SxDemo4Parser::getParent ()
{
SX_TRACE ();
ssize_t i = stack.getSize()-2;
if (i >= 0) return *(ast.begin(sx::Forward, stack(i)));
else return *(ast.begin(sx::Forward, 0)); // top level
}
int SxDemo4Parser_parse (SxDemo4Parser *); // defined by LEX
int SxDemo4Parser::parse ()
{
return SxDemo4Parser_parse (this); // enter LEX
}
| 21.363636 | 78 | 0.521986 |
a53d6c0c94a22872150b79b2baf203f7c9f35780 | 2,582 | hpp | C++ | openbmc_modules/phosphor-ipmi-blobs/example/example.hpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | openbmc_modules/phosphor-ipmi-blobs/example/example.hpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | null | null | null | openbmc_modules/phosphor-ipmi-blobs/example/example.hpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | #pragma once
#include <blobs-ipmid/blobs.hpp>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#ifdef __cplusplus
extern "C" {
#endif
/**
* This method must be declared as extern C for blob manager to lookup the
* symbol.
*/
std::unique_ptr<blobs::GenericBlobInterface> createHandler();
#ifdef __cplusplus
}
#endif
namespace blobs
{
constexpr int kBufferSize = 1024;
struct ExampleBlob
{
ExampleBlob() = default;
ExampleBlob(uint16_t id, uint16_t flags) :
sessionId(id), flags(flags),
state(StateFlags::open_read | StateFlags::open_write), length(0)
{
}
/* The blob handler session id. */
uint16_t sessionId;
/* The flags passed into open. */
uint16_t flags;
/* The current state. */
uint16_t state;
/* The buffer is a fixed size, but length represents the number of bytes
* expected to be used contiguously from offset 0.
*/
uint32_t length;
/* The staging buffer. */
uint8_t buffer[kBufferSize];
};
class ExampleBlobHandler : public GenericBlobInterface
{
public:
/* We want everything explicitly default. */
ExampleBlobHandler() = default;
~ExampleBlobHandler() = default;
ExampleBlobHandler(const ExampleBlobHandler&) = default;
ExampleBlobHandler& operator=(const ExampleBlobHandler&) = default;
ExampleBlobHandler(ExampleBlobHandler&&) = default;
ExampleBlobHandler& operator=(ExampleBlobHandler&&) = default;
bool canHandleBlob(const std::string& path) override;
std::vector<std::string> getBlobIds() override;
bool deleteBlob(const std::string& path) override;
bool stat(const std::string& path, BlobMeta* meta) override;
bool open(uint16_t session, uint16_t flags,
const std::string& path) override;
std::vector<uint8_t> read(uint16_t session, uint32_t offset,
uint32_t requestedSize) override;
bool write(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool writeMeta(uint16_t session, uint32_t offset,
const std::vector<uint8_t>& data) override;
bool commit(uint16_t session, const std::vector<uint8_t>& data) override;
bool close(uint16_t session) override;
bool stat(uint16_t session, BlobMeta* meta) override;
bool expire(uint16_t session) override;
constexpr static char supportedPath[] = "/dev/fake/command";
private:
ExampleBlob* getSession(uint16_t id);
std::unordered_map<uint16_t, ExampleBlob> sessions;
};
} // namespace blobs
| 28.065217 | 77 | 0.691712 |
a53da97f92c9b880a510e5ab6779e4f1cb5b9316 | 2,706 | cc | C++ | src/third_party/abseil-cpp/absl/base/internal/strerror_test.cc | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T20:46:41.000Z | 2021-04-14T17:48:54.000Z | src/third_party/abseil-cpp/absl/base/internal/strerror_test.cc | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 54 | 2020-06-23T17:34:04.000Z | 2022-03-31T02:04:06.000Z | src/third_party/abseil-cpp/absl/base/internal/strerror_test.cc | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 12 | 2020-07-14T23:59:57.000Z | 2022-03-22T09:59:18.000Z | // Copyright 2020 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "absl/base/internal/strerror.h"
#include <atomic>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <string>
#include <thread> // NOLINT(build/c++11)
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/match.h"
namespace {
using ::testing::AnyOf;
using ::testing::Eq;
TEST(StrErrorTest, ValidErrorCode) {
errno = ERANGE;
EXPECT_THAT(absl::base_internal::StrError(EDOM), Eq(strerror(EDOM)));
EXPECT_THAT(errno, Eq(ERANGE));
}
TEST(StrErrorTest, InvalidErrorCode) {
errno = ERANGE;
EXPECT_THAT(absl::base_internal::StrError(-1),
AnyOf(Eq("No error information"), Eq("Unknown error -1")));
EXPECT_THAT(errno, Eq(ERANGE));
}
TEST(StrErrorTest, MultipleThreads) {
// In this test, we will start up 2 threads and have each one call
// StrError 1000 times, each time with a different errnum. We
// expect that StrError(errnum) will return a string equal to the
// one returned by strerror(errnum), if the code is known. Since
// strerror is known to be thread-hostile, collect all the expected
// strings up front.
const int kNumCodes = 1000;
std::vector<std::string> expected_strings(kNumCodes);
for (int i = 0; i < kNumCodes; ++i) {
expected_strings[i] = strerror(i);
}
std::atomic_int counter(0);
auto thread_fun = [&]() {
for (int i = 0; i < kNumCodes; ++i) {
++counter;
errno = ERANGE;
const std::string value = absl::base_internal::StrError(i);
// Only the GNU implementation is guaranteed to provide the
// string "Unknown error nnn". POSIX doesn't say anything.
if (!absl::StartsWith(value, "Unknown error ")) {
EXPECT_THAT(absl::base_internal::StrError(i), Eq(expected_strings[i]));
}
EXPECT_THAT(errno, Eq(ERANGE));
}
};
const int kNumThreads = 100;
std::vector<std::thread> threads;
for (int i = 0; i < kNumThreads; ++i) {
threads.push_back(std::thread(thread_fun));
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_THAT(counter, Eq(kNumThreads * kNumCodes));
}
} // namespace
| 31.103448 | 79 | 0.684405 |
a53ea9be9c6f82a33b219a687dcdb2d0d3cb7486 | 1,435 | hh | C++ | src/transform/vector/vector4.hh | CompaqDisc/libtransform | db9dcbc39cd7d3af904c1bc2131544c1908522e1 | [
"MIT"
] | null | null | null | src/transform/vector/vector4.hh | CompaqDisc/libtransform | db9dcbc39cd7d3af904c1bc2131544c1908522e1 | [
"MIT"
] | null | null | null | src/transform/vector/vector4.hh | CompaqDisc/libtransform | db9dcbc39cd7d3af904c1bc2131544c1908522e1 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include "vector.hh"
namespace transform
{
template <class T>
class Vector4 : public Vector<4, T>
{
private:
typedef Vector<4, T> super;
public:
Vector4() : super() {} // default construct
Vector4(const T x, const T y, const T z, const T w); // member construct
Vector4(const Vector4<T>& v) : super(v) {} // copy construct
Vector4(const Vector<4, T>& v) : super(v) {} // copy construct from superclass
template <class U>
Vector4(const Vector4<U>& v) // convert construct
{
this->_v[0] = v[0];
this->_v[1] = v[1];
this->_v[2] = v[2];
this->_v[3] = v[3];
}
template <class U>
Vector4(const Vector<4, U>& v) // convert construct
{
this->_v[0] = v[0];
this->_v[1] = v[1];
this->_v[2] = v[2];
this->_v[3] = v[3];
}
// members
T& x = this->_v[0];
T& y = this->_v[1];
T& z = this->_v[2];
T& w = this->_v[3];
T& r = this->_v[0];
T& g = this->_v[1];
T& b = this->_v[2];
T& a = this->_v[3];
// utility
Vector4<T>& set(const T x, const T y, const T z, const T w);
};
}
using transform::Vector4;
template <class T>
Vector4<T>::Vector4(T x, T y, T z, T w)
{
this->_v[0] = x;
this->_v[1] = y;
this->_v[2] = z;
this->_v[3] = w;
}
template <class T>
Vector4<T>& Vector4<T>::set(const T x, const T y, const T z, const T w)
{
this->_v[0] = x;
this->_v[1] = y;
this->_v[2] = z;
this->_v[3] = w;
return *this;
}
| 19.133333 | 82 | 0.552613 |
a54038616b95c435f358914cdf01cdeeee72e878 | 22,450 | cpp | C++ | platform/mt6592/hardware/audio/aud_drv/AudioPlatformDevice.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | platform/mt6592/hardware/audio/aud_drv/AudioPlatformDevice.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | platform/mt6592/hardware/audio/aud_drv/AudioPlatformDevice.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | #include "AudioPlatformDevice.h"
#include "AudioAnalogType.h"
#include "audio_custom_exp.h"
#define LOG_TAG "AudioPlatformDevice"
#ifndef ANDROID_DEFAULT_CODE
#include <cutils/xlog.h>
#ifdef ALOGE
#undef ALOGE
#endif
#ifdef ALOGW
#undef ALOGW
#endif ALOGI
#undef ALOGI
#ifdef ALOGD
#undef ALOGD
#endif
#ifdef ALOGV
#undef ALOGV
#endif
#define ALOGE XLOGE
#define ALOGW XLOGW
#define ALOGI XLOGI
#define ALOGD XLOGD
#define ALOGV XLOGV
#else
#include <utils/Log.h>
#endif
namespace android
{
status_t AudioPlatformDevice::InitCheck()
{
ALOGD("InitCheck");
return NO_ERROR;
}
AudioPlatformDevice::AudioPlatformDevice()
{
ALOGD("AudioPlatformDevice constructor");
mAudioAnalogReg = NULL;
mAudioAnalogReg = AudioAnalogReg::getInstance();
if (!mAudioAnalogReg)
{
ALOGW("mAudioAnalogReg = %p", mAudioAnalogReg);
}
// init analog part.
for (int i = 0; i < AudioAnalogType::DEVICE_MAX; i++)
{
memset((void *)&mBlockAttribute[i], 0, sizeof(AnalogBlockAttribute));
}
for (int i = 0; i < AudioAnalogType::VOLUME_TYPE_MAX; i++)
{
memset((void *)&mVolumeAttribute[i], 0, sizeof(AnalogVolumeAttribute));
}
mHpRightDcCalibration = mHpLeftDcCalibration = 0;
}
/**
* a basic function for SetAnalogGain for different Volume Type
* @param VoleumType value want to set to analog volume
* @param volume function of analog gain , value between 0 ~ 255
* @return status_t
*/
status_t AudioPlatformDevice::SetAnalogGain(AudioAnalogType::VOLUME_TYPE VoleumType, int volume)
{
ALOGD("SetAnalogGain VOLUME_TYPE = %d volume = %d ", VoleumType, volume);
return NO_ERROR;
}
/**
* a basic function fo SetAnalogMute, if provide mute function of hardware.
* @param VoleumType value want to set to analog volume
* @param mute of volume type
* @return status_t
*/
status_t AudioPlatformDevice::SetAnalogMute(AudioAnalogType::VOLUME_TYPE VoleumType, bool mute)
{
ALOGD("AudioPlatformDevice SetAnalogMute VOLUME_TYPE = %d mute = %d ", VoleumType, mute);
return NO_ERROR;
}
status_t AudioPlatformDevice::SetFrequency(AudioAnalogType::DEVICE_SAMPLERATE_TYPE DeviceType, unsigned int frequency)
{
ALOGD("AudioPlatformDevice SetFrequency");
mBlockSampleRate[DeviceType] = frequency;
return NO_ERROR;
}
uint32 AudioPlatformDevice::GetDLFrequency(unsigned int frequency)
{
ALOGD("AudioPlatformDevice GetDLFrequency = %d", frequency);
uint32 Reg_value = 0;
switch (frequency)
{
case 8000:
Reg_value = 0;
break;
case 11025:
Reg_value = 1;
break;
case 12000:
Reg_value = 2;
break;
case 16000:
Reg_value = 4;
break;
case 22050:
Reg_value = 5;
break;
case 24000:
Reg_value = 6;
break;
case 32000:
Reg_value = 8;
break;
case 44100:
Reg_value = 9;
break;
case 48000:
Reg_value = 10;
default:
ALOGW("GetDLFrequency with frequency = %d", frequency);
}
return Reg_value;
}
uint32 AudioPlatformDevice::GetULFrequency(unsigned int frequency)
{
ALOGD("AudioPlatformDevice GetULFrequencyGroup = %d", frequency);
uint32 Reg_value = 0;
switch (frequency)
{
case 8000:
case 16000:
case 32000:
Reg_value = 0x0;
break;
case 48000:
Reg_value = 0x1;
default:
ALOGW("GetULFrequency with frequency = %d", frequency);
}
ALOGD("AudioPlatformDevice GetULFrequencyGroup Reg_value = %d", Reg_value);
return Reg_value;
}
uint32 AudioPlatformDevice::GetDLNewIFFrequency(unsigned int frequency)
{
ALOGD("AudioPlatformDevice ApplyDLNewIFFrequency ApplyDLNewIFFrequency = %d", frequency);
uint32 Reg_value = 0;
switch (frequency)
{
case 8000:
Reg_value = 0;
break;
case 11025:
Reg_value = 1;
break;
case 12000:
Reg_value = 2;
break;
case 16000:
Reg_value = 3;
break;
case 22050:
Reg_value = 4;
break;
case 24000:
Reg_value = 5;
break;
case 32000:
Reg_value = 6;
break;
case 44100:
Reg_value = 7;
break;
case 48000:
Reg_value = 8;
default:
ALOGW("ApplyDLNewIFFrequency with frequency = %d", frequency);
}
return Reg_value;
}
uint32 AudioPlatformDevice::GetULNewIFFrequency(unsigned int frequency)
{
ALOGD("AudioPlatformDevice GetULNewIFFrequency ApplyULNewIFFrequency = %d", frequency);
uint32 Reg_value = 0;
switch (frequency)
{
case 8000:
case 16000:
case 32000:
Reg_value = 1;
break;
case 48000:
Reg_value = 3;
default:
ALOGW("GetULNewIFFrequency with frequency = %d", frequency);
}
ALOGD("AudioPlatformDevice GetULNewIFFrequency Reg_value = %d", Reg_value);
return Reg_value;
}
status_t AudioPlatformDevice::TopCtlChangeTrigger(void)
{
uint32_t top_ctrl_status_now = mAudioAnalogReg->GetAnalogReg(ABB_AFE_CON11);
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON11, ((top_ctrl_status_now & 0x0001) ? 0 : 1) << 8, 0x0100);
return NO_ERROR;
}
status_t AudioPlatformDevice::DCChangeTrigger(void)
{
uint32_t dc_status_now = mAudioAnalogReg->GetAnalogReg(0x4016);
mAudioAnalogReg->SetAnalogReg(0x4016, ((dc_status_now & 0x0002) ? 0 : 1) << 9, 0x0200);
return NO_ERROR;
}
bool AudioPlatformDevice::GetDownLinkStatus(void)
{
for (int i = 0; i <= AudioAnalogType::DEVICE_2IN1_SPK; i++)
{
if (mBlockAttribute[i].mEnable == true)
{
ALOGD("GetDownLinkStatus True : i = %d DeviceType = %s", i, kAudioAnalogDeviceTypeName[i]);
return true;
}
}
return false;
}
bool AudioPlatformDevice::GetULinkStatus(void)
{
for (int i = AudioAnalogType::DEVICE_2IN1_SPK; i <= AudioAnalogType::DEVICE_IN_DIGITAL_MIC; i++)
{
if (mBlockAttribute[i].mEnable == true)
{
ALOGD("GetULinkStatus True : i = %d DeviceType = %s", i, kAudioAnalogDeviceTypeName[i]);
return true;
}
}
return false;
}
/**
* a basic function fo AnalogOpen, open analog power
* @param DeviceType analog part power
* @return status_t
*/
status_t AudioPlatformDevice::AnalogOpen(AudioAnalogType::DEVICE_TYPE DeviceType)
{
ALOGD("AudioPlatformDevice AnalogOpen DeviceType = %s ", kAudioAnalogDeviceTypeName[DeviceType]);
uint32 ulFreq, dlFreq;
mLock.lock();
if (mBlockAttribute[DeviceType].mEnable == true)
{
ALOGW("AudioPlatformDevice AnalogOpen bypass with DeviceType = %d", DeviceType);
mLock.unlock();
return NO_ERROR;;
}
mBlockAttribute[DeviceType].mEnable = true;
// here to open pmic digital part
ulFreq = GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]);
dlFreq = GetDLFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]);
switch (DeviceType)
{
case AudioAnalogType::DEVICE_OUT_EARPIECER:
case AudioAnalogType::DEVICE_OUT_EARPIECEL:
#if 0
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetDLFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]), 0x000f);
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0 , GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12, 0xf000);
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON5 , 0x28, 0x003f); //Use Default SDM Gain 0x28/0x3f = 0.63
mAudioAnalogReg->SetAnalogReg(ABB_AFE_TOP_CON0 , 0, 0xffff); //Use Normal Path
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON2 , 0, 0xffff); //Use Normal Path
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 1, 0x0001); //Enable DL path
TopCtlChangeTrigger();
#else
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0, GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12 | 0x330, 0xffff); // config up8x_rxif
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, dlFreq, 0x000f); // DL sampling rate
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0001, 0x0001); // turn on DL
#endif
break;
case AudioAnalogType::DEVICE_OUT_HEADSETR:
case AudioAnalogType::DEVICE_OUT_HEADSETL:
#if 0
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetDLFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]), 0x000f);
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0 , GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12, 0xf000);
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON5 , 0x28, 0x003f); //Use Default SDM Gain 0x28/0x3f = 0.63
mAudioAnalogReg->SetAnalogReg(ABB_AFE_TOP_CON0 , 0, 0xffff); //Use Normal Path
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON2 , 0, 0xffff); //Use Normal Path
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 1, 0x0001); //Enable DL path
TopCtlChangeTrigger();
#else
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG0, GetDLNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_OUT_DAC]) << 12 | 0x330, 0xffff); // config up8x_rxif
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, dlFreq, 0x000f); // DL sampling rate
//DC compensation setting
ALOGD("AnalogOpen mHpRightDcCalibration [0x%x] mHpLeftDcCalibration [0x%x]", mHpRightDcCalibration, mHpLeftDcCalibration);
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON3, mHpLeftDcCalibration, 0xffff); // LCH cpmpensation value
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON4, mHpRightDcCalibration, 0xffff); // RCH cpmpensation value
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON10, 0x0001, 0x0001); // enable DC cpmpensation
DCChangeTrigger();//Trigger DC compensation
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0001, 0x0001); // turn on DL
#endif
break;
case AudioAnalogType::DEVICE_OUT_SPEAKERR:
case AudioAnalogType::DEVICE_OUT_SPEAKERL:
#ifdef USING_EXTAMP_HP
mLock.unlock();
AnalogOpen(AudioAnalogType::DEVICE_OUT_HEADSETR);
mLock.lock();
#else
mLock.unlock();
AnalogOpen(AudioAnalogType::DEVICE_OUT_EARPIECER);
mLock.lock();
#endif
break;
case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R:
case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_L:
mLock.unlock();
AnalogOpen(AudioAnalogType::DEVICE_OUT_HEADSETR);
mLock.lock();
break;
case AudioAnalogType::DEVICE_IN_ADC1:
case AudioAnalogType::DEVICE_IN_ADC2:
ALOGD("AudioPlatformDevice::DEVICE_IN_ADC2:");
#if 0
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 4, 0x0010);
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 0x02, 0x0002); //Enable UL path
TopCtlChangeTrigger();
#else
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 4, 0x0010); // UL sampling rate
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0002, 0x0002); // turn on UL
#endif
break;
case AudioAnalogType::DEVICE_IN_DIGITAL_MIC:
#if 0
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1 , GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]), 0x0010);
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON9 , 0x0011, 0x0011); // enable digital mic, 3.25M clock rate
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0 , 0x02, 0x0002); //Enable UL path
TopCtlChangeTrigger();
#else
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_CLR, 0x0100, 0x0100); // AUD 26M clock power down release
mAudioAnalogReg->SetAnalogReg(AFE_PMIC_NEWIF_CFG2, 0x302F | (GetULNewIFFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 10), 0xffff); // config UL up8x_rxif adc voice mode
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON1, GetULFrequency(mBlockSampleRate[AudioAnalogType::DEVICE_IN_ADC]) << 4, 0x0010); // UL sampling rate
TopCtlChangeTrigger();
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON9, 0x0011, 0x0011); // enable digital mic, 3.25M clock rate
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0002, 0x0002); // turn on UL
#endif
break;
case AudioAnalogType::DEVICE_2IN1_SPK:
if (IsAudioSupportFeature(AUDIO_SUPPORT_2IN1_SPEAKER))
{
mLock.unlock();
AnalogOpen(AudioAnalogType::DEVICE_OUT_EARPIECER);
mLock.lock();
}
break;
}
mLock.unlock();
return NO_ERROR;
}
status_t AudioPlatformDevice::AnalogOpenForAddSPK(AudioAnalogType::DEVICE_TYPE DeviceType)
{
ALOGD("AudioPlatformDevice AnalogOpenForAddSPK DeviceType = %s ", kAudioAnalogDeviceTypeName[DeviceType]);
// uint32 ulFreq, dlFreq;
mLock.lock();
mBlockAttribute[AudioAnalogType::DEVICE_OUT_HEADSETR].mEnable = false;
mBlockAttribute[AudioAnalogType::DEVICE_OUT_HEADSETL].mEnable = false;
mBlockAttribute[AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R].mEnable = true;
mLock.unlock();
return NO_ERROR;
}
status_t AudioPlatformDevice::AnalogCloseForSubSPK(AudioAnalogType::DEVICE_TYPE DeviceType)
{
ALOGD("AudioPlatformDevice AnalogCloseForSubSPK DeviceType = %s", kAudioAnalogDeviceTypeName[DeviceType]);
mLock.lock();
mBlockAttribute[AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R].mEnable = false;
mBlockAttribute[AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_L].mEnable = false;
mBlockAttribute[AudioAnalogType::DEVICE_OUT_HEADSETR].mEnable = true;
mLock.unlock();
return NO_ERROR;
}
/**
* a basic function fo AnalogClose, ckose analog power
* @param DeviceType analog part power
* @return status_t
*/
status_t AudioPlatformDevice::AnalogClose(AudioAnalogType::DEVICE_TYPE DeviceType)
{
ALOGD("AudioPlatformDevice AnalogClose DeviceType = %s", kAudioAnalogDeviceTypeName[DeviceType]);
mLock.lock();
mBlockAttribute[DeviceType].mEnable = false;
// here to open pmic digital part
switch (DeviceType)
{
case AudioAnalogType::DEVICE_OUT_EARPIECER:
case AudioAnalogType::DEVICE_OUT_EARPIECEL:
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0001); // turn off DL
// TopCtlChangeTrigger();
break;
case AudioAnalogType::DEVICE_OUT_HEADSETR:
case AudioAnalogType::DEVICE_OUT_HEADSETL:
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0001); // turn off DL
TopCtlChangeTrigger();
ALOGD("AnalogClose Reset mHpRightDcCalibration/mHpLeftDcCalibration from [0x%x] [0x%x]", mHpRightDcCalibration, mHpLeftDcCalibration);
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON3, 0, 0xffff); // LCH cancel DC
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON4, 0, 0xffff); // RCH cancel DC
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON10, 0x0000, 0x0001); // enable DC cpmpensation
DCChangeTrigger();//Trigger DC compensation
break;
case AudioAnalogType::DEVICE_OUT_SPEAKERR:
case AudioAnalogType::DEVICE_OUT_SPEAKERL:
#ifdef USING_EXTAMP_HP
mLock.unlock();
AnalogClose(AudioAnalogType::DEVICE_OUT_HEADSETR);
mLock.lock();
#else
mLock.unlock();
AnalogClose(AudioAnalogType::DEVICE_OUT_EARPIECER);
mLock.lock();
#endif
break;
case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_R:
case AudioAnalogType::DEVICE_OUT_SPEAKER_HEADSET_L:
mLock.unlock();
AnalogClose(AudioAnalogType::DEVICE_OUT_HEADSETR);
mLock.lock();
break;
case AudioAnalogType::DEVICE_IN_ADC1:
case AudioAnalogType::DEVICE_IN_ADC2:
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0002); // turn off UL
// TopCtlChangeTrigger();
break;
case AudioAnalogType::DEVICE_IN_DIGITAL_MIC:
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON9, 0x0000, 0x0010); // disable digital mic
mAudioAnalogReg->SetAnalogReg(ABB_AFE_CON0, 0x0000, 0x0002); // turn off UL
// TopCtlChangeTrigger();
break;
case AudioAnalogType::DEVICE_2IN1_SPK:
if (IsAudioSupportFeature(AUDIO_SUPPORT_2IN1_SPEAKER))
{
mLock.unlock();
AnalogClose(AudioAnalogType::DEVICE_OUT_EARPIECER);
mLock.lock();
}
break;
}
if (!GetDownLinkStatus() && !GetULinkStatus())
{
mAudioAnalogReg->SetAnalogReg(TOP_CKPDN1_SET, 0x0100, 0x0100); // AUD 26M clock power down
ALOGD("AudioPlatformDevice AnalogClose Power Down TOP_CKPDN1_SET");
}
else
{
ALOGD("AudioPlatformDevice AnalogClose No Power Down TOP_CKPDN1_SET");
}
mLock.unlock();
return NO_ERROR;
}
/**
* a basic function fo select mux of device type, not all device may have mux
* if select a device with no mux support , report error.
* @param DeviceType analog part
* @param MuxType analog mux selection
* @return status_t
*/
status_t AudioPlatformDevice::AnalogSetMux(AudioAnalogType::DEVICE_TYPE DeviceType, AudioAnalogType::MUX_TYPE MuxType)
{
ALOGD("AAudioPlatformDevice nalogSetMux DeviceType = %s MuxType = %s", kAudioAnalogDeviceTypeName[DeviceType], kAudioAnalogMuxTypeName[MuxType]);
return NO_ERROR;
}
/**
* a function for setParameters , provide wide usage of analog control
* @param command1
* @param command2
* @param data
* @return status_t
*/
status_t AudioPlatformDevice::setParameters(int command1 , int command2 , unsigned int data)
{
return NO_ERROR;
}
/**
* a function for setParameters , provide wide usage of analog control
* @param command1
* @param data
* @return status_t
*/
status_t AudioPlatformDevice::setParameters(int command1 , void *data)
{
return NO_ERROR;
}
/**
* a function fo getParameters , provide wide usage of analog control
* @param command1
* @param command2
* @param data
* @return copy_size
*/
int AudioPlatformDevice::getParameters(int command1 , int command2 , void *data)
{
return 0;
}
//static const uint32_t kFadeSamples[4] = {4096, 2048, 1024, 512};
status_t AudioPlatformDevice::FadeOutDownlink(uint16_t sample_rate)
{
#if 0
const uint16_t fade_unit_index = 3;
// Set gain speed: bit[9:10] = 0x3 => FadeSamples/sample_rate (sec)
uint32_t time_ms = (kFadeSamples[fade_unit_index] * 1000) / sample_rate;
mAudioAnalogReg->SetAnalogReg(0x4004, fade_unit_index << 9, 3 << 9);
// Set ch1 & ch2 fade type: bit[3:4] = 0x3 => fade out
mAudioAnalogReg->SetAnalogReg(0x4004, 3 << 3, 3 << 3);
// Mute function of ch1 & ch2: bit[11:12] = 0x0 => Enable
mAudioAnalogReg->SetAnalogReg(0x4004, 0 << 11, 3 << 11);
// Sleep
usleep(time_ms * 1000);
#endif
return NO_ERROR;
}
status_t AudioPlatformDevice::FadeInDownlink(uint16_t sample_rate)
{
#if 0
const uint16_t fade_unit_index = 3;
// Set gain speed: bit[9:10] = 0x3 => FadeSamples/sample_rate (sec)
uint32_t time_ms = (kFadeSamples[fade_unit_index] * 1000) / sample_rate;
mAudioAnalogReg->SetAnalogReg(0x4004, fade_unit_index << 9, 3 << 9);
// Set ch1 & ch2 fade type: bit[3:4] = 0x0 => fade in
mAudioAnalogReg->SetAnalogReg(0x4004, 0 << 3, 3 << 3);
// Sleep
usleep(time_ms * 1000);
// Mute function of ch1 & ch2: bit[11:12] = 0x3 => Disable
mAudioAnalogReg->SetAnalogReg(0x4004, 3 << 11, 3 << 11);
#endif
return NO_ERROR;
}
status_t AudioPlatformDevice::SetDcCalibration(AudioAnalogType::DEVICE_TYPE DeviceType, int dc_cali_value)
{
ALOGD("SetDcCalibration Type[%d] value[0x%x]", DeviceType, dc_cali_value);
switch (DeviceType)
{
case AudioAnalogType::DEVICE_OUT_HEADSETR:
mHpRightDcCalibration = dc_cali_value;
break;
case AudioAnalogType::DEVICE_OUT_HEADSETL:
mHpLeftDcCalibration = dc_cali_value;
break;
default:
break;
}
ALOGD("SetDcCalibration mHpRightDcCalibration [0x%x] mHpLeftDcCalibration [0x%x]", mHpRightDcCalibration, mHpLeftDcCalibration);
return NO_ERROR;
}
}
| 36.863711 | 197 | 0.671448 |
a54540bdad511b2641bac5b0129de33591cace4e | 4,347 | cpp | C++ | ProtoTcpClient/CmdLineExec.cpp | EvanGertis/Dev_RisLib | 1aa185d1092bd703a0867bcc36106886baea3454 | [
"MIT"
] | null | null | null | ProtoTcpClient/CmdLineExec.cpp | EvanGertis/Dev_RisLib | 1aa185d1092bd703a0867bcc36106886baea3454 | [
"MIT"
] | null | null | null | ProtoTcpClient/CmdLineExec.cpp | EvanGertis/Dev_RisLib | 1aa185d1092bd703a0867bcc36106886baea3454 | [
"MIT"
] | 1 | 2019-03-28T15:09:48.000Z | 2019-03-28T15:09:48.000Z |
#include "stdafx.h"
#include "procoTcpSettings.h"
#include "procoMsg.h"
#include "procoMsgHelper.h"
#include "procoClientThread.h"
#include "CmdLineExec.h"
using namespace ProtoComm;
//******************************************************************************
//******************************************************************************
//******************************************************************************
CmdLineExec::CmdLineExec()
{
}
void CmdLineExec::reset()
{
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::execute(Ris::CmdLineCmd* aCmd)
{
if (aCmd->isCmd("TP")) gClientThread->mTPFlag = aCmd->argBool(1);
if (aCmd->isCmd("TX")) executeTx(aCmd);
if (aCmd->isCmd("ECHO")) executeEcho(aCmd);
if (aCmd->isCmd("DATA")) executeData(aCmd);
if (aCmd->isCmd("GO1")) executeGo1(aCmd);
if (aCmd->isCmd("GO2")) executeGo2(aCmd);
if (aCmd->isCmd("T1")) executeTest1(aCmd);
if (aCmd->isCmd("Parms")) executeParms(aCmd);
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeTx (Ris::CmdLineCmd* aCmd)
{
gClientThread->sendTestMsg();
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeEcho(Ris::CmdLineCmd* aCmd)
{
aCmd->setArgDefault(1, 0);
int tNumWords = aCmd->argInt(1);
ProtoComm::EchoRequestMsg* tMsg = new ProtoComm::EchoRequestMsg;
MsgHelper::initialize(tMsg, tNumWords);
gClientThread->sendMsg(tMsg);
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeData(Ris::CmdLineCmd* aCmd)
{
ProtoComm::DataMsg* tMsg = new ProtoComm::DataMsg;
MsgHelper::initialize(tMsg);
gClientThread->sendMsg(tMsg);
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeGo1(Ris::CmdLineCmd* aCmd)
{
aCmd->setArgDefault(1, 1);
ProtoComm::TestMsg* tMsg = new ProtoComm::TestMsg;
gClientThread->sendMsg(tMsg);
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeGo2(Ris::CmdLineCmd* aCmd)
{
aCmd->setArgDefault(1,1);
int tN = aCmd->argInt(1);
for (int i=0;i<tN;i++)
{
ProtoComm::EchoRequestMsg* tMsg = new ProtoComm::EchoRequestMsg;
gClientThread->sendMsg(tMsg);
gClientThread->threadSleep(10);
}
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeTest1(Ris::CmdLineCmd* aCmd)
{
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
void CmdLineExec::executeParms(Ris::CmdLineCmd* aCmd)
{
ProtoComm::gTcpSettings.show();
}
//******************************************************************************
//******************************************************************************
//******************************************************************************
| 34.228346 | 80 | 0.296526 |
a54d3255d9b64c01987dcbf06a6bf5a4e3af694a | 2,205 | cpp | C++ | src/DashboardLayout.cpp | 00steve/Lapster | 42c11d7bf96694c36f75d938563031cb08951ff1 | [
"Apache-2.0"
] | null | null | null | src/DashboardLayout.cpp | 00steve/Lapster | 42c11d7bf96694c36f75d938563031cb08951ff1 | [
"Apache-2.0"
] | null | null | null | src/DashboardLayout.cpp | 00steve/Lapster | 42c11d7bf96694c36f75d938563031cb08951ff1 | [
"Apache-2.0"
] | null | null | null | #include "DashboardLayout.h"
void DashboardLayout::Setup(){
switch(layoutID){
case LAYOUT_SINGLE:
Serial.println("use default single widget dashboard");
widget[0] = new DashboardWidget(Int2(10,10),Int2(470,310),GAUGE_TYPE_BAR,INPUT_ANALOG1);
widgetCount = 1;
break;
case LAYOUT_SIDE_BY_SIDE:
Serial.println("use double widget dashboard");
widget[0] = new DashboardWidget(Int2(10,10),Int2(235,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1);
widget[1] = new DashboardWidget(Int2(245,10),Int2(470,310),GAUGE_TYPE_BAR,INPUT_ANALOG1);
widgetCount = 2;
break;
case LAYOUT_QUADS:
Serial.println("use quad widget dashboard");
widget[0] = new DashboardWidget(Int2(10,10),Int2(235,155),GAUGE_TYPE_EMPTY,INPUT_ANALOG1);
widget[1] = new DashboardWidget(Int2(245,10),Int2(470,155),GAUGE_TYPE_BAR,INPUT_ANALOG1);
widget[2] = new DashboardWidget(Int2(10,165),Int2(235,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1);
widget[3] = new DashboardWidget(Int2(245,165),Int2(470,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1);
widgetCount = 4;
break;
}
}
DashboardLayout::DashboardLayout(int layoutID) :
layoutID(layoutID),
editWidgetIndex(-1){
Setup();
//stuff in the layout
}
DashboardLayout::~DashboardLayout(){
int i = widgetCount;
while(i --> 0){
delete widget[i];
}
}
void DashboardLayout::Update(){
if(Button::CheckForScreenHolding()){
Serial.println("check for button");
int i = widgetCount;
while(i --> 0){
if(widget[i]->Holding()){
editWidgetIndex = i;
Serial.println("edit widget");
return;
}
}
}
}
void DashboardLayout::Redraw(){
int i=widgetCount;
while(i --> 0){
widget[i]->Redraw();
}
}
void DashboardLayout::Draw(){
int i=widgetCount;
while(i --> 0){
widget[i]->Draw();
}
}
bool DashboardLayout::ShouldEditWidget(){
return editWidgetIndex > -1;
}
DashboardWidget* DashboardLayout::EditWidget(){
int ind = editWidgetIndex;
editWidgetIndex = -1;
return widget[ind];
}
| 25.639535 | 100 | 0.623583 |
a5547fdf56655ca4bf73afa96bd8cb653764d9c2 | 598 | cpp | C++ | pointer_main.cpp | zhichengMLE/Cplusplus | 525d80550c2460b0504926a26beaa67ca91bb848 | [
"MIT"
] | 1 | 2019-03-29T21:07:37.000Z | 2019-03-29T21:07:37.000Z | pointer_main.cpp | zhichengMLE/Cplusplus | 525d80550c2460b0504926a26beaa67ca91bb848 | [
"MIT"
] | null | null | null | pointer_main.cpp | zhichengMLE/Cplusplus | 525d80550c2460b0504926a26beaa67ca91bb848 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
bool printArray(string* arr, int length){
if(arr == NULL){
return false;
}
for(int i = 0; i < length; i++){
cout << arr[i] << endl;
}
return true;
}
int main() {
string arrMonth[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
string* pMonth = NULL;
pMonth = arrMonth;
cout << printArray(pMonth, sizeof(arrMonth) / sizeof(*arrMonth)) << endl;
return 0;
}
/*
>>
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
1
Process finished with exit code 0
*/
| 13 | 111 | 0.560201 |
a559a8d25755123fb6296d027efb72d08bb91b83 | 9,590 | hpp | C++ | src/Serialize.hpp | Mercerenies/latitude | 29b1697f1f615d52480197a52e20ff8c1872f07d | [
"MIT"
] | 3 | 2021-09-02T18:19:25.000Z | 2021-12-26T23:33:32.000Z | src/Serialize.hpp | Mercerenies/latitude | 29b1697f1f615d52480197a52e20ff8c1872f07d | [
"MIT"
] | 45 | 2017-11-28T15:13:59.000Z | 2022-02-19T18:45:46.000Z | src/Serialize.hpp | Mercerenies/proto-lang | 29b1697f1f615d52480197a52e20ff8c1872f07d | [
"MIT"
] | null | null | null | //// Copyright (c) 2018 Silvio Mayolo
//// See LICENSE.txt for licensing details
#ifndef SERIALIZE_HPP
#define SERIALIZE_HPP
#include "Instructions.hpp"
#include "Assembler.hpp"
/// \file
///
/// \brief Serialization structures and helpers.
/// serialize_t, on its own, is an incomplete type. Any type which is
/// serializable should implement a partial specialization of
/// serialize_t for its particular type. The specialization should
/// define, publicly, a typedef and two methods.
///
/// * `using type = ...` should be defined to be the type parameter
/// `T`.
///
/// * `void serialize(const type&, OutputIterator&)` should, for any
/// output iterator type, serialize a value of the type to the
/// iterator.
///
/// * `type deserialize(InputIterator&)` should, for any input
/// iterator type, deserialize a value of the type to out of the
/// iterator.
///
/// Serializers are allowed to assume the iterators are valid and, in
/// the input case, that the iterator contains a value of the
/// appropriate type. Additionally, if the type is small (such as an
/// arithmetic type), serializers may replace `const type&` with
/// simply `type`.
template <typename T>
struct serialize_t;
template <>
struct serialize_t<long> {
using type = long;
template <typename OutputIterator>
void serialize(type arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
template <>
struct serialize_t<char> {
using type = char;
template <typename OutputIterator>
void serialize(type arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
template <>
struct serialize_t<Reg> {
using type = Reg;
template <typename OutputIterator>
void serialize(type arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
template <>
struct serialize_t<Instr> {
using type = Instr;
template <typename OutputIterator>
void serialize(type arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
template <>
struct serialize_t<std::string> {
using type = std::string;
template <typename OutputIterator>
void serialize(const type& arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
template <>
struct serialize_t<FunctionIndex> {
using type = FunctionIndex;
template <typename OutputIterator>
void serialize(const type& arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
template <>
struct serialize_t<AssemblerLine> {
using type = AssemblerLine;
template <typename OutputIterator>
void serialize(const type& arg, OutputIterator& iter) const;
template <typename InputIterator>
type deserialize(InputIterator& iter) const;
};
/// Serializes the argument into the output iterator.
///
/// \pre A partial specialization `serialize_t<T>` must be in scope
/// \param arg the value to serialize
/// \param iter an output iterator
template <typename T, typename OutputIterator>
void serialize(const T& arg, OutputIterator& iter);
/// Deserializes a value of the given type from the iterator.
///
/// \pre A partial specialization `serialize_t<T>` must be in scope
/// \param iter an input iterator
/// \return the value
template <typename T, typename InputIterator>
T deserialize(InputIterator& iter);
/// Serializes the value within the variant structure. The
/// serialization does not mark which variant was saved, so the value
/// must be deserialized with ::deserialize<T> (for the appropriate type
/// `T`).
///
/// \pre A partial specialization `serialize_t<T>` must be in scope,
/// for each `T` in `Ts...`
/// \param arg the variant
/// \param iter an output iterator
template <typename OutputIterator, typename... Ts>
void serializeVariant(const boost::variant<Ts...>& arg, OutputIterator& iter);
// ----
template <typename OutputIterator>
auto serialize_t<long>::serialize(type arg, OutputIterator& iter) const -> void {
long val1 = arg;
if (val1 < 0)
*iter++ = 0xFF;
else
*iter++ = 0x00;
val1 = abs(val1);
for (int i = 0; i < 4; i++) {
*iter++ = (unsigned char)(val1 % 256);
val1 /= 256;
}
}
template <typename InputIterator>
auto serialize_t<long>::deserialize(InputIterator& iter) const -> type {
int sign = 1;
if (*iter > 0)
sign *= -1;
++iter;
long value = 0;
long pow = 1;
for (int i = 0; i < 4; i++) {
value += pow * (long)(*iter);
++iter;
pow <<= 8;
}
return sign * value;
}
template <typename OutputIterator>
auto serialize_t<char>::serialize(type arg, OutputIterator& iter) const -> void {
*iter++ = (unsigned char)arg;
}
template <typename InputIterator>
auto serialize_t<char>::deserialize(InputIterator& iter) const -> type {
char ch = *iter;
++iter;
return ch;
}
template <typename OutputIterator>
auto serialize_t<Reg>::serialize(type arg, OutputIterator& iter) const -> void {
*iter++ = (unsigned char)arg;
}
template <typename InputIterator>
auto serialize_t<Reg>::deserialize(InputIterator& iter) const -> type {
unsigned char ch = *iter;
++iter;
return (Reg)ch;
}
template <typename OutputIterator>
auto serialize_t<Instr>::serialize(type arg, OutputIterator& iter) const -> void {
*iter++ = (unsigned char)arg;
}
template <typename InputIterator>
auto serialize_t<Instr>::deserialize(InputIterator& iter) const -> type {
unsigned char ch = *iter;
++iter;
return (Instr)ch;
}
template <typename OutputIterator>
auto serialize_t<std::string>::serialize(const type& arg, OutputIterator& iter) const -> void {
for (char ch : arg) {
if (ch == 0) {
*iter++ = '\0';
*iter++ = '.';
} else {
*iter++ = ch;
}
}
*iter++ = '\0';
*iter++ = '\0';
}
template <typename InputIterator>
auto serialize_t<std::string>::deserialize(InputIterator& iter) const -> type {
std::string str;
unsigned char ch;
while (true) {
ch = *iter;
++iter;
if (ch == '\0') {
ch = *iter;
++iter;
if (ch == '.')
str += '\0';
else if (ch == '\0')
break;
} else {
str += ch;
}
}
return str;
}
template <typename OutputIterator>
auto serialize_t<FunctionIndex>::serialize(const type& arg, OutputIterator& iter) const -> void {
// No need for a sign bit; this is an index so it's always nonnegative
int val1 = arg.index;
for (int i = 0; i < 4; i++) {
*iter++ = (unsigned char)(val1 % 256);
val1 /= 256;
}
}
template <typename InputIterator>
auto serialize_t<FunctionIndex>::deserialize(InputIterator& iter) const -> type {
int value = 0;
int pow = 1;
for (int i = 0; i < 4; i++) {
value += pow * (long)(*iter);
++iter;
pow <<= 8;
}
return { value };
}
template <typename OutputIterator>
auto serialize_t<AssemblerLine>::serialize(const type& instr, OutputIterator& iter) const -> void {
::serialize<Instr>(instr.getCommand(), iter);
for (const auto& arg : instr.arguments()) {
serializeVariant(arg, iter);
}
}
/// \cond
template <typename InputIterator>
struct _AsmArgDeserializeVisitor {
InputIterator& iter;
template <typename T>
RegisterArg operator()(Proxy<T>) {
return deserialize<T>(iter);
}
};
/// \endcond
template <typename InputIterator>
auto serialize_t<AssemblerLine>::deserialize(InputIterator& iter) const -> type {
Instr instr = ::deserialize<Instr>(iter);
AssemblerLine instruction { instr };
_AsmArgDeserializeVisitor<InputIterator> visitor { iter };
for (const auto& arg : getAsmArguments(instr)) {
instruction.addRegisterArg(callOnAsmArgType(visitor, arg));
}
return instruction;
}
/// Serializes the object into the given output iterator. There must
/// be a compatible specialization of `serialize_t` of the form
/// `serialize_t<T>`.
///
/// \tparam T the object type
/// \tparam OutputIterator the type of the output iterator
/// \param arg the object to serialize
/// \param iter the output iterator
template <typename T, typename OutputIterator>
void serialize(const T& arg, OutputIterator& iter) {
serialize_t<T>().serialize(arg, iter);
}
/// Deserializes an object of the given type from the input iterator.
///
/// \tparam T the object type
/// \tparam InputIterator the type of the input iterator
/// \param iter the input iterator
/// \return the object
template <typename T, typename InputIterator>
T deserialize(InputIterator& iter) {
return serialize_t<T>().deserialize(iter);
}
/// \cond
template <typename OutputIterator>
struct _VariantSerializeVisitor : boost::static_visitor<void> {
OutputIterator& iter;
_VariantSerializeVisitor(OutputIterator& iter) : iter(iter) {}
template <typename T>
void operator()(const T& arg) {
serialize(arg, iter);
}
};
/// \endcond
template <typename OutputIterator, typename... Ts>
void serializeVariant(const boost::variant<Ts...>& arg, OutputIterator& iter) {
_VariantSerializeVisitor<OutputIterator> visitor { iter };
boost::apply_visitor(visitor, arg);
}
#endif // SERIALIZE_HPP
| 26.862745 | 99 | 0.665485 |
a55a285e827647b249f13c23efeff1dc550898ef | 3,208 | cpp | C++ | CCC/ccc04s5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | CCC/ccc04s5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | CCC/ccc04s5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define MM 102
int dp[MM][MM][3],arr[MM][MM];
//moved up, down, right
char c;
int main(){
while(1){
int m,n;
scanf("%d%d",&m,&n);
if(m == 0)
break;
for(int i = m; i > 0; i--){
scanf("%c",&c); //nl
for(int j = 1; j <= n; j++){
scanf("%c",&c);
if(c == '*'){
arr[i][j] = -1;
}else if(c == '.'){
arr[i][j] = 0;
}else{
arr[i][j] = c-'0';
}
//printf("%d ",arr[i][j]);
}
//printf("\n");
}
memset(dp,-1,sizeof(dp));
dp[1][1][2] = max(0, arr[1][1]);
for(int j = 1; j <= n; j++){
for(int i = m; i > 0; i--){
if(arr[i][j] == -1)
continue;
if(dp[i][j-1][2] != -1)
dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][2] + arr[i][j]);
if(dp[i][j-1][1] != -1)
dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][1] + arr[i][j]);
if(dp[i][j-1][0] != -1)
dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][0] + arr[i][j]);
//down
if(dp[i-1][j][1] != -1)
dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][1] + arr[i][j]);
if(dp[i-1][j][2] != -1)
dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][2] + arr[i][j]);
//up
if(dp[i+1][j][0] != -1)
dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][0] + arr[i][j]);
if(dp[i+1][j][2] != -1)
dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][2] + arr[i][j]);
}
for(int i = 1; i <= m; i++){
if(arr[i][j] == -1)
continue;
if(dp[i][j-1][2] != -1)
dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][2] + arr[i][j]);
if(dp[i][j-1][1] != -1)
dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][1] + arr[i][j]);
if(dp[i][j-1][0] != -1)
dp[i][j][2] = max(dp[i][j][2], dp[i][j-1][0] + arr[i][j]);
//down
if(dp[i-1][j][1] != -1)
dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][1] + arr[i][j]);
if(dp[i-1][j][2] != -1)
dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][2] + arr[i][j]);
//up
if(dp[i+1][j][0] != -1)
dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][0] + arr[i][j]);
if(dp[i+1][j][2] != -1)
dp[i][j][0] = max(dp[i][j][0], dp[i+1][j][2] + arr[i][j]);
}
}
printf("%d\n",max(max(dp[1][n][0],dp[1][n][1]),dp[1][n][2]));
#ifdef def
for(int i = m; i > 0; i--){
for(int j = 1; j <= n; j++){
printf("%d ",max(max(dp[i][j][0],dp[i][j][1]),dp[i][j][2]));
}
printf("\n");
}
#endif
}
return 0;
} | 36.873563 | 79 | 0.275561 |
a222d9ab01460056f957119aaeb4bd94ebf3684e | 29,324 | cpp | C++ | src/Image.cpp | i-saint/glSpriteFont | 8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1 | [
"Unlicense"
] | 2 | 2015-11-07T11:31:55.000Z | 2021-04-16T15:20:44.000Z | src/Image.cpp | i-saint/glSpriteFont | 8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1 | [
"Unlicense"
] | null | null | null | src/Image.cpp | i-saint/glSpriteFont | 8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1 | [
"Unlicense"
] | 1 | 2020-06-09T10:45:28.000Z | 2020-06-09T10:45:28.000Z | #include "stdafx.h"
#include "Image.h"
#ifdef __ist_with_gli__
#include "gli/gli.hpp"
#include "gli/gtx/loader.hpp"
#endif // __ist_with_gli__
namespace ist {
struct BMPHEAD
{
char B;
char M;
int32 file_size;
int16 reserve1;
int16 reserve2;
int32 offset;
BMPHEAD()
{
memset(this, 0, sizeof(*this));
B = 'B';
M = 'M';
offset = 54;
}
};
struct BMPINFOHEAD
{
int32 header_size;
int32 width;
int32 height;
int16 plane;
int16 bits;
int32 compression;
int32 comp_image_size;
int32 x_resolution;
int32 y_resolution;
int32 pallete_num;
int32 important_pallete_num;
BMPINFOHEAD()
{
memset(this, 0, sizeof(*this));
header_size=sizeof(*this);
plane = 1;
bits = 24;
}
};
struct TGAHEAD
{
uint8 No_ID;
uint8 CMap_Type;
uint8 image_type;
uint8 CMap_Spec[5];
int16 Ox;
int16 Oy;
int16 width;
int16 height;
uint8 pixel;
uint8 IDesc_Type;
TGAHEAD()
{
memset(this, 0, sizeof(*this));
pixel = 32;
IDesc_Type = 8;
}
};
Image::FileType GetFileTypeByFileHeader(IBinaryStream &f)
{
char m[4];
f >> m; f.setReadPos(0);
if(m[0]=='B' && m[1]=='M') { return Image::FileType_BMP; }
if(m[1]=='P' && m[2]=='N' && m[3]=='G') { return Image::FileType_PNG; }
if(m[0]=='D' && m[1]=='D' && m[2]=='S') { return Image::FileType_DDS; }
if(m[0]==0xff && m[1]==0xd8) { return Image::FileType_JPG; }
{
// tga は magic code がないので、それっぽい値が入ってるかで判断
TGAHEAD tga;
f.read(&tga, sizeof(tga)); f.setReadPos(0);
if( (tga.image_type==2 || tga.image_type==10) && tga.Ox==0 && tga.Oy==0 && (tga.pixel==32 || tga.pixel==24)) {
return Image::FileType_TGA;
}
}
return Image::FileType_Unknown;
}
Image::FileType GetFileTypeByExtention(const char *path)
{
uint32 len = strlen(path);
if(len<5) { return Image::FileType_Unknown; }
if(strncmp(&path[len-3], "bmp", 3)==0) { return Image::FileType_BMP; }
if(strncmp(&path[len-3], "tga", 3)==0) { return Image::FileType_TGA; }
if(strncmp(&path[len-3], "png", 3)==0) { return Image::FileType_PNG; }
if(strncmp(&path[len-3], "jpg", 3)==0) { return Image::FileType_JPG; }
if(strncmp(&path[len-3], "dds", 3)==0) { return Image::FileType_DDS; }
return Image::FileType_Unknown;
}
bool Image::load(const char *path, const IOConfig &conf)
{
FileStream f(path, "rb");
if(!f.isOpened()) { return false; }
IOConfig c = conf;
if(c.getFileType()==FileType_Auto) {
c.setFileType( GetFileTypeByExtention(path) );
}
return load(f, c);
}
bool Image::load(IBinaryStream &f, const IOConfig &conf)
{
clear();
FileType ft = conf.getFileType();
if(ft==FileType_Auto) {
ft = GetFileTypeByFileHeader(f);
}
switch(ft)
{
case FileType_BMP: return loadBMP(f, conf);
case FileType_TGA: return loadTGA(f, conf);
case FileType_PNG: return loadPNG(f, conf);
case FileType_JPG: return loadJPG(f, conf);
case FileType_DDS: return loadDDS(f, conf);
}
istPrint("認識できないフォーマットが指定されました。\n");
return false;
}
bool Image::save(const char *path, const IOConfig &conf) const
{
FileStream f(path, "wb");
if(!f.isOpened()) { return false; }
IOConfig c = conf;
if(c.getFileType()==FileType_Auto) {
c.setFileType(GetFileTypeByExtention(path));
}
return save(f, c);
}
bool Image::save(IBinaryStream &f, const IOConfig &conf) const
{
switch(conf.getFileType())
{
case FileType_BMP: return saveBMP(f, conf);
case FileType_TGA: return saveTGA(f, conf);
case FileType_PNG: return savePNG(f, conf);
case FileType_JPG: return saveJPG(f, conf);
case FileType_DDS: return saveDDS(f, conf);
}
istPrint(L"認識できないフォーマットが指定されました。\n");
return false;
}
static RGBA_8U Read1Pixel(IBinaryStream &bf)
{
RGBA_8U t;
bf >> t.b >> t.g >> t.r >> t.a;
return t;
}
// BMP
bool Image::loadBMP(IBinaryStream &bf, const IOConfig &conf)
{
BMPHEAD head;
BMPINFOHEAD infohead;
bf >> head.B >> head.M;
if(head.B!='B' || head.M!='M') { return false; }
bf >> head.file_size
>> head.reserve1
>> head.reserve2
>> head.offset;
bf >> infohead.header_size
>> infohead.width
>> infohead.height
>> infohead.plane
>> infohead.bits
>> infohead.compression
>> infohead.comp_image_size
>> infohead.x_resolution
>> infohead.y_resolution
>> infohead.pallete_num
>> infohead.important_pallete_num;
if(infohead.bits!=24 && infohead.bits!=32) {
istPrint(L"bmp は現在 24bit か 32bit しか対応していません。\n");
return false;
}
resize<RGBA_8U>(infohead.width, infohead.height);
if(infohead.bits==24) {
for(int32 yi=(int32)height()-1; yi>=0; --yi) {
for(int32 xi=0; xi<(int32)width(); ++xi) {
RGBA_8U& c = get<RGBA_8U>(yi, xi);
bf >> c.b >> c.g >> c.r;
c.a = 255;
}
}
}
else if(infohead.bits==32) {
for(int32 yi=(int32)height()-1; yi>=0; --yi) {
for(int32 xi=0; xi<(int32)width(); ++xi) {
RGBA_8U& c = get<RGBA_8U>(yi, xi);
bf >> c.b >> c.g >> c.r >> c.a;
}
}
}
return true;
}
bool Image::saveBMP(IBinaryStream &bf, const IOConfig &conf) const
{
BMPHEAD head;
BMPINFOHEAD infohead;
head.file_size = sizeof(BMPHEAD)+sizeof(BMPINFOHEAD)+width()*height()*3;
infohead.width = width();
infohead.height = height();
bf << head.B
<< head.M
<< head.file_size
<< head.reserve1
<< head.reserve2
<< head.offset;
bf << infohead.header_size
<< infohead.width
<< infohead.height
<< infohead.plane
<< infohead.bits
<< infohead.compression
<< infohead.comp_image_size
<< infohead.x_resolution
<< infohead.y_resolution
<< infohead.pallete_num
<< infohead.important_pallete_num;
for(int32 yi=(int32)height()-1; yi>=0; --yi) {
for(int32 xi=0; xi<(int32)width(); ++xi) {
const RGBA_8U& c = get<RGBA_8U>(yi, xi);
bf << c.b << c.g << c.r;
}
}
return true;
}
// TGA
bool Image::loadTGA(IBinaryStream &bf, const IOConfig &conf)
{
TGAHEAD head;
bf >> head.No_ID
>> head.CMap_Type
>> head.image_type
>> head.CMap_Spec
>> head.Ox
>> head.Oy
>> head.width
>> head.height
>> head.pixel
>> head.IDesc_Type;
if(head.pixel!=32)
{
istPrint("32bit データしか対応していません。\n");
return false;
}
resize<RGBA_8U>(head.width, head.height);
for(int32 yi=(int32)height()-1; yi>=0; --yi) {
if(head.image_type==2) {
for(int32 xi=0; xi<(int32)width(); xi++) {
get<RGBA_8U>(yi, xi) = Read1Pixel(bf);
}
}
else if(head.image_type==10) {
uint32 loaded = 0;
while(loaded<width()) {
uint8 dist = 0;
bf >> dist;
if( dist<0x80) {
for(int32 xi=0; xi<dist+1; ++xi, ++loaded) {
get<RGBA_8U>(yi, loaded) = Read1Pixel(bf);
}
}
else {
RGBA_8U t = Read1Pixel(bf);
for(int32 xi=0x80; xi<dist+1; ++xi, ++loaded) {
get<RGBA_8U>(yi, loaded) = t;
}
}
}
}
}
return true;
}
class TGACompress
{
public:
TGACompress() {}
const stl::vector<uint8>& getCompressedData() const { return m_comp_pixel; }
void compress(const RGBA_8U *start, int32 width)
{
stl::vector<RGBA_8U> same, diff;
for(int32 i=0; i!=width; ++i, ++start)
{
const RGBA_8U *ip=start; ++ip;
RGBA_8U dist=*start;
if( i+1!=width && dist==*ip && same.size()<0x79 )
{
same.push_back(dist);
if(diff.size()!=0)
{
writeDifferentData(diff);
}
}
else
{
if(same.size()>0x00)
{
writeSameData(same);
}
else
{
diff.push_back(dist);
if(diff.size()==0x79 )
{
writeDifferentData(diff);
}
}
}
}
if(same.size()!=0x00)
{
writeSameData(same);
}
else if(diff.size()!=0)
{
writeDifferentData(diff);
}
}
private:
void writeSameData(stl::vector<RGBA_8U> &temp_pixel)
{
m_comp_pixel.push_back( temp_pixel.size()+0x80 );
m_comp_pixel.push_back( temp_pixel[0].b );
m_comp_pixel.push_back( temp_pixel[0].g );
m_comp_pixel.push_back( temp_pixel[0].r );
m_comp_pixel.push_back( temp_pixel[0].a );
temp_pixel.clear();
}
void writeDifferentData(stl::vector<RGBA_8U> &temp_pixel)
{
m_comp_pixel.push_back( temp_pixel.size()-1 );
for(int32 d=0; d<(int32)temp_pixel.size(); d++)
{
m_comp_pixel.push_back( temp_pixel[d].b );
m_comp_pixel.push_back( temp_pixel[d].g );
m_comp_pixel.push_back( temp_pixel[d].r );
m_comp_pixel.push_back( temp_pixel[d].a );
}
temp_pixel.clear();
}
private:
stl::vector<uint8> m_comp_pixel;
};
bool Image::saveTGA(IBinaryStream &bf, const Image::IOConfig &conf) const
{
TGAHEAD head;
head.width = width();
head.height = height();
head.image_type = 10;
bf << head.No_ID
<< head.CMap_Type
<< head.image_type
<< head.CMap_Spec
<< head.Ox
<< head.Oy
<< head.width
<< head.height
<< head.pixel
<< head.IDesc_Type;
{
TGACompress comp;
for(int32 yi=(int32)height()-1; yi>=0; --yi)
{
comp.compress(&get<RGBA_8U>(yi, 0), width());
}
const stl::vector<uint8>& data = comp.getCompressedData();
bf.write(&data[0], data.size());
}
return true;
}
// PNG
#ifdef __ist_with_png__
namespace
{
void png_streambuf_read(png_structp png_ptr, png_bytep data, png_size_t length)
{
IBinaryStream *f = reinterpret_cast<IBinaryStream*>(png_get_io_ptr(png_ptr));
f->read(data, length);
}
void png_streambuf_write(png_structp png_ptr, png_bytep data, png_size_t length)
{
IBinaryStream *f = reinterpret_cast<IBinaryStream*>(png_get_io_ptr(png_ptr));
f->write(data, length);
}
void png_streambuf_flush(png_structp png_ptr)
{
}
} // namespace
#endif // __ist_with_png__
bool Image::loadPNG(IBinaryStream &f, const IOConfig &conf)
{
#ifdef __ist_with_png__
png_structp png_ptr = ::png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
if(png_ptr==0)
{
istPrint("失敗: png_create_read_struct() が null を返しました。\n");
return false;
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if(info_ptr==0)
{
::png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
istPrint("失敗: png_create_info_struct() が null を返しました。\n");
return false;
}
::png_set_read_fn(png_ptr, &f, png_streambuf_read);
png_uint_32 w, h;
int32 bit_depth, color_type, interlace_type;
::png_read_info(png_ptr, info_ptr);
::png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type, &interlace_type, NULL, NULL);
resize<RGBA_8U>(w, h);
::png_set_strip_16(png_ptr);
::png_set_packing(png_ptr);
if(color_type==PNG_COLOR_TYPE_PALETTE)
{
::png_set_palette_to_rgb(png_ptr);
}
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth<8)
{
::png_set_expand_gray_1_2_4_to_8(png_ptr);
}
if(::png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
{
::png_set_tRNS_to_alpha(png_ptr);
}
::png_read_update_info(png_ptr, info_ptr);
// 読み込み
stl::vector<png_bytep> row_pointers(height());
for(int32 row=0; row<(int32)height(); ++row) {
row_pointers[row] = (png_bytep)png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
}
png_read_image(png_ptr, &row_pointers[0]);
for(int32 yi=0; yi<(int32)height(); ++yi) {
for(int32 xi=0; xi<(int32)width(); ++xi) {
RGBA_8U& c = get<RGBA_8U>(yi, xi);
if(color_type==PNG_COLOR_TYPE_RGB_ALPHA) {
c.r = row_pointers[yi][xi*4+0];
c.g = row_pointers[yi][xi*4+1];
c.b = row_pointers[yi][xi*4+2];
c.a = row_pointers[yi][xi*4+3];
}
else if(color_type==PNG_COLOR_TYPE_RGB) {
c.r = row_pointers[yi][xi*3+0];
c.g = row_pointers[yi][xi*3+1];
c.b = row_pointers[yi][xi*3+2];
c.a = 255;
}
}
}
for(int32 row=0; row<(int32)height(); ++row) {
png_free(png_ptr, row_pointers[row]);
}
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return true;
#else
istPrint("失敗: png 使用を無効化した設定でビルドされています。\n");
return false;
#endif // __ist_with_png__
}
bool Image::savePNG(IBinaryStream &f, const Image::IOConfig &conf) const
{
#ifdef __ist_with_png__
png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
if(png_ptr==0)
{
istPrint("失敗: png_create_write_struct() が null を返しました。");
return false;
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if(info_ptr==0)
{
::png_destroy_write_struct(&png_ptr, NULL);
istPrint("失敗: png_create_info_struct() が null を返しました。");
return false;
}
::png_set_write_fn(png_ptr, &f, png_streambuf_write, png_streambuf_flush);
::png_set_IHDR(png_ptr, info_ptr, width(), height(), 8,
PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
::png_write_info(png_ptr, info_ptr);
Image tmp(*this);
stl::vector<png_bytep> row_pointers(height());
for(int32 yi=0; yi<(int32)height(); ++yi)
{
row_pointers[yi] = tmp.get<RGBA_8U>(yi, 0).v;
}
::png_write_image(png_ptr, &row_pointers[0]);
::png_write_end(png_ptr, info_ptr);
::png_destroy_write_struct(&png_ptr, &info_ptr);
return true;
#else
istPrint("失敗: png 使用を無効化した設定でビルドされています。");
return false;
#endif // __ist_with_png__
}
// JPG
#ifdef __ist_with_jpeg__
namespace
{
struct my_error_mgr
{
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
typedef struct my_error_mgr * my_error_ptr;
void my_error_exit(j_common_ptr cinfo)
{
my_error_ptr myerr = (my_error_ptr) cinfo->err;
(*cinfo->err->output_message)(cinfo);
longjmp(myerr->setjmp_buffer, 1);
}
typedef struct {
struct jpeg_source_mgr pub; /* public fields */
IBinaryStream *infile; /* source stream */
JOCTET * buffer; /* start of buffer */
boolean start_of_file; /* have we gotten any data yet? */
} my_source_mgr;
typedef my_source_mgr * my_src_ptr;
#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
typedef struct {
struct jpeg_destination_mgr pub; /* public fields */
IBinaryStream * outfile; /* target stream */
JOCTET * buffer; /* start of buffer */
} my_destination_mgr;
typedef my_destination_mgr * my_dest_ptr;
#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
#define SIZEOF(object) ((size_t) sizeof(object))
void init_streambuf_source (j_decompress_ptr cinfo)
{
my_src_ptr src = (my_src_ptr) cinfo->src;
src->start_of_file = TRUE;
}
boolean fill_streambuf_input_buffer (j_decompress_ptr cinfo)
{
my_src_ptr src = (my_src_ptr) cinfo->src;
size_t nbytes;
nbytes = src->infile->read(src->buffer, INPUT_BUF_SIZE);
if (nbytes <= 0) {
if (src->start_of_file) /* Treat empty input file as fatal error */
ERREXIT(cinfo, JERR_INPUT_EMPTY);
WARNMS(cinfo, JWRN_JPEG_EOF);
/* Insert a fake EOI marker */
src->buffer[0] = (JOCTET) 0xFF;
src->buffer[1] = (JOCTET) JPEG_EOI;
nbytes = 2;
}
src->pub.next_input_byte = src->buffer;
src->pub.bytes_in_buffer = nbytes;
src->start_of_file = FALSE;
return TRUE;
}
void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
struct jpeg_source_mgr * src = cinfo->src;
if (num_bytes > 0) {
while (num_bytes > (long) src->bytes_in_buffer) {
num_bytes -= (long) src->bytes_in_buffer;
(void) (*src->fill_input_buffer) (cinfo);
}
src->next_input_byte += (size_t) num_bytes;
src->bytes_in_buffer -= (size_t) num_bytes;
}
}
void term_source (j_decompress_ptr cinfo)
{
}
void jpeg_streambuf_src (j_decompress_ptr cinfo, IBinaryStream &streambuf)
{
my_src_ptr src;
if (cinfo->src == NULL) { /* first time for this JPEG object? */
cinfo->src = (struct jpeg_source_mgr *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_source_mgr));
src = (my_src_ptr) cinfo->src;
src->buffer = (JOCTET *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * SIZEOF(JOCTET));
}
src = (my_src_ptr) cinfo->src;
src->pub.init_source = init_streambuf_source;
src->pub.fill_input_buffer = fill_streambuf_input_buffer;
src->pub.skip_input_data = skip_input_data;
src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
src->pub.term_source = term_source;
src->infile = &streambuf;
src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
src->pub.next_input_byte = NULL; /* until buffer loaded */
}
void init_streambuf_destination (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
/* Allocate the output buffer --- it will be released when done with image */
dest->buffer = (JOCTET *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
}
boolean empty_streambuf_output_buffer (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
if (dest->outfile->write(dest->buffer, OUTPUT_BUF_SIZE) != (size_t) OUTPUT_BUF_SIZE)
ERREXIT(cinfo, JERR_FILE_WRITE);
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
return TRUE;
}
void term_destination (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
/* Write any data remaining in the buffer */
if (datacount > 0) {
if (dest->outfile->write(dest->buffer, datacount) != datacount)
ERREXIT(cinfo, JERR_FILE_WRITE);
}
}
void jpeg_streambuf_dest (j_compress_ptr cinfo, std::streambuf& outfile)
{
my_dest_ptr dest;
if (cinfo->dest == NULL) { /* first time for this JPEG object? */
cinfo->dest = (struct jpeg_destination_mgr *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
SIZEOF(my_destination_mgr));
}
dest = (my_dest_ptr) cinfo->dest;
dest->pub.init_destination = init_streambuf_destination;
dest->pub.empty_output_buffer = empty_streambuf_output_buffer;
dest->pub.term_destination = term_destination;
dest->outfile = &outfile;
}
} // namespace
#endif // __ist_with_jpeg__
bool Image::loadJPG(IBinaryStream &f, const IOConfig &conf)
{
clear();
#ifdef __ist_with_jpeg__
jpeg_decompress_struct cinfo;
my_error_mgr jerr;
JSAMPARRAY buffer;
int32 row_stride;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if(setjmp(jerr.setjmp_buffer))
{
jpeg_destroy_decompress(&cinfo);
return false;
}
jpeg_create_decompress(&cinfo);
jpeg_streambuf_src(&cinfo, f);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
resize(cinfo.image_width, cinfo.image_height);
uint32 pix_count = 0;
while (cinfo.output_scanline < cinfo.output_height)
{
jpeg_read_scanlines(&cinfo, buffer, 1);
for(int32 i=0; i<(int32)row_stride/3; ++i)
{
RGBA_8U col(buffer[0][i*3+0], buffer[0][i*3+1], buffer[0][i*3+2], 255);
at(pix_count) = col;
++pix_count;
}
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return true;
#else
istPrint("失敗: jpg 使用を無効化した設定でビルドされています。");
return false;
#endif // __ist_with_jpeg__
}
bool Image::saveJPG(IBinaryStream &f, const IOConfig &conf) const
{
#ifdef __ist_with_jpeg__
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
JSAMPROW row_pointer[1];
int32 row_stride;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_streambuf_dest(&cinfo, f);
cinfo.image_width = width();
cinfo.image_height = height();
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, conf.getJpgQuality(), TRUE);
jpeg_start_compress(&cinfo, TRUE);
row_stride = cinfo.image_width*3;
uint8 *buf = new uint8[width()*height()*3];
for(int32 i=0; i<(int32)width()*(int32)height(); ++i)
{
buf[i*3+0] = at(i).r;
buf[i*3+1] = at(i).g;
buf[i*3+2] = at(i).b;
}
while (cinfo.next_scanline < cinfo.image_height)
{
row_pointer[0] = &buf[cinfo.next_scanline * row_stride];
jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
delete[] buf;
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
return true;
#else // __ist_with_jpeg__
istPrint("失敗: jpg 使用を無効化した設定でビルドされています。");
return false;
#endif // __ist_with_jpeg__
}
} // namespace ist
#ifdef __ist_with_gli__
namespace gli {
namespace gtx {
namespace loader_dds10{
namespace detail {
// gli には std::string を引数にとるやつしかないので、ストリーム版をコピペ改変実装します。参考: loadDDS10()
inline texture2D loadDDS10_ex( ist::IBinaryStream &bin )
{
loader_dds9::detail::ddsHeader HeaderDesc;
detail::ddsHeader10 HeaderDesc10;
char Magic[4];
//* Read magic number and check if valid .dds file
bin.read((char*)&Magic, sizeof(Magic));
assert(strncmp(Magic, "DDS ", 4) == 0);
// Get the surface descriptor
bin.read(&HeaderDesc, sizeof(HeaderDesc));
if(HeaderDesc.format.flags & loader_dds9::detail::GLI_DDPF_FOURCC && HeaderDesc.format.fourCC == loader_dds9::detail::GLI_FOURCC_DX10)
bin.read(&HeaderDesc10, sizeof(HeaderDesc10));
loader_dds9::detail::DDLoader Loader;
if(HeaderDesc.format.fourCC == loader_dds9::detail::GLI_FOURCC_DX10)
Loader.Format = detail::format_dds2gli_cast(HeaderDesc10.dxgiFormat);
else if(HeaderDesc.format.flags & loader_dds9::detail::GLI_DDPF_FOURCC)
Loader.Format = detail::format_fourcc2gli_cast(HeaderDesc.format.fourCC);
else
{
switch(HeaderDesc.format.bpp)
{
case 8:
Loader.Format = R8U;
break;
case 16:
Loader.Format = RG8U;
break;
case 24:
Loader.Format = RGB8U;
break;
case 32:
Loader.Format = RGBA8U;
break;
}
}
Loader.BlockSize = size(image(texture2D::dimensions_type(0), Loader.Format), BLOCK_SIZE);
Loader.BPP = size(image(texture2D::dimensions_type(0), Loader.Format), BIT_PER_PIXEL);
std::size_t Width = HeaderDesc.width;
std::size_t Height = HeaderDesc.height;
gli::format Format = Loader.Format;
std::streamoff Curr = bin.getReadPos();
bin.setReadPos(0, ist::IBinaryStream::Seek_End);
std::streamoff End = bin.getReadPos();
bin.setReadPos(Curr);
std::vector<glm::byte> Data(std::size_t(End - Curr), 0);
std::size_t Offset = 0;
bin.read(&Data[0], std::streamsize(Data.size()));
//texture2D Image(glm::min(MipMapCount, Levels));//SurfaceDesc.mipMapLevels);
std::size_t MipMapCount = (HeaderDesc.flags & loader_dds9::detail::GLI_DDSD_MIPMAPCOUNT) ? HeaderDesc.mipMapLevels : 1;
//if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5)
// MipMapCount -= 2;
texture2D Image(MipMapCount);
for(std::size_t Level = 0; Level < Image.levels() && (Width || Height); ++Level)
{
Width = glm::max(std::size_t(Width), std::size_t(1));
Height = glm::max(std::size_t(Height), std::size_t(1));
std::size_t MipmapSize = 0;
if((Loader.BlockSize << 3) > Loader.BPP)
MipmapSize = ((Width + 3) >> 2) * ((Height + 3) >> 2) * Loader.BlockSize;
else
MipmapSize = Width * Height * Loader.BlockSize;
std::vector<glm::byte> MipmapData(MipmapSize, 0);
memcpy(&MipmapData[0], &Data[0] + Offset, MipmapSize);
texture2D::dimensions_type Dimensions(Width, Height);
Image[Level] = texture2D::image(Dimensions, Format, MipmapData);
Offset += MipmapSize;
Width >>= 1;
Height >>= 1;
}
return Image;
}
} // detail
} // loader_dds10
} // namespace gtx
} // namespace gli
#endif // __ist_with_gli__
namespace ist {
bool Image::loadDDS( IBinaryStream &f, const IOConfig &conf )
{
#ifdef __ist_with_gli__
gli::texture2D tex = gli::gtx::loader_dds10::detail::loadDDS10_ex(f);
ivec2 dim = ivec2(tex[0].dimensions().x, tex[0].dimensions().y);
switch(tex.format()) {
case gli::R8U: setup(IF_R8U, dim.x, dim.y, tex[0].capacity()); break;
case gli::R8I: setup(IF_R8I, dim.x, dim.y, tex[0].capacity()); break;
case gli::R32F: setup(IF_R32F, dim.x, dim.y, tex[0].capacity()); break;
case gli::RG8U: setup(IF_RG8U, dim.x, dim.y, tex[0].capacity()); break;
case gli::RG8I: setup(IF_RG8I, dim.x, dim.y, tex[0].capacity()); break;
case gli::RG32F: setup(IF_RG32F, dim.x, dim.y, tex[0].capacity()); break;
case gli::RGB8U: setup(IF_RGB8U, dim.x, dim.y, tex[0].capacity()); break;
case gli::RGB8I: setup(IF_RGB8I, dim.x, dim.y, tex[0].capacity()); break;
case gli::RGB32F: setup(IF_RGB32F, dim.x, dim.y, tex[0].capacity()); break;
case gli::RGBA8U: setup(IF_RGBA8U, dim.x, dim.y, tex[0].capacity()); break;
case gli::RGBA8I: setup(IF_RGBA8I, dim.x, dim.y, tex[0].capacity()); break;
case gli::RGBA32F: setup(IF_RGBA32F, dim.x, dim.y, tex[0].capacity()); break;
case gli::DXT1: setup(IF_RGBA_DXT1, dim.x, dim.y, tex[0].capacity()); break;
case gli::DXT3: setup(IF_RGBA_DXT3, dim.x, dim.y, tex[0].capacity()); break;
case gli::DXT5: setup(IF_RGBA_DXT5, dim.x, dim.y, tex[0].capacity()); break;
default: return false;
}
memcpy(data(), tex[0].data(), tex[0].capacity());
return true;
#endif // __ist_with_gli__
return false;
}
bool Image::saveDDS( IBinaryStream &f, const IOConfig &conf ) const
{
istPrint("未実装");
return false;
}
} // namespace ist
| 28.805501 | 139 | 0.572228 |
a226d7a69e226236adfc97177d46fabe4d53b894 | 1,793 | cpp | C++ | CompetitiveCodingTemplates/cpp_template.cpp | niranjan09/DataStructures_Algorithms | df2801f7ea48a39a55a6d79fd66ad200a2de0145 | [
"MIT"
] | null | null | null | CompetitiveCodingTemplates/cpp_template.cpp | niranjan09/DataStructures_Algorithms | df2801f7ea48a39a55a6d79fd66ad200a2de0145 | [
"MIT"
] | null | null | null | CompetitiveCodingTemplates/cpp_template.cpp | niranjan09/DataStructures_Algorithms | df2801f7ea48a39a55a6d79fd66ad200a2de0145 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
/* Start of commonly used datatypes and constructs*/
using L = long long;
#define FOR(i, s, e) for(L i = s; i<e; ++i)
#define RFOR(i, s, e) for(L i = s; i>e; --i)
#define F first
#define S second
#define SZ(container) ((int)container.size())
#define ALL(container) container.begin(), container.end()
#define MP(k, v) make_pair(k, v)
#define MT(i1, i2, i3) make_tuple(i1, i2, i3)
#define PB(vi) push_back(vi)
#define POP(vi) pop_back(vi)
#define UM unordered_map
#define US unordered_set
using PII = pair<int, int>; using PLL = pair<L, L>;
using VI = vector<int>; using VL = vector<L>;
using VVI = vector<VI>; using VVL = vector<VL>;
using VPII = vector<PII>; using VPLL = vector<PLL>;
using UMII = UM<int, int>; using UMLL = UM<L, L>;
using USI = US<int>; using USL = US<L>;
/* Start of commonly used functions */
void SC(int &i) {scanf("%d", &i);}
void SC(int &i, int &j) {scanf("%d %d", &i, &j);}
void SC(int &i, int &j, int &k) {scanf("%d %d %d", &i, &j, &k);}
void SC(L &i) {scanf("%lld", &i);}
void SC(L &i, L &j) {scanf("%lld %lld", &i, &j);}
void SC(L &i, L &j, L &k) {scanf("%lld %lld %lld", &i, &j, &k);}
void print(VL arr, const string sep = " ", const string end = "\n"){FOR(i, 0, SZ(arr) - 1) printf("%lld%s", arr[i], sep.c_str()); printf("%lld", arr.back()); printf("%s", end.c_str());}
void print(VI arr, const string sep = " ", const string end = "\n"){FOR(i, 0, SZ(arr) - 1) printf("%d%s", arr[i], sep.c_str()); printf("%d", arr.back()); printf("%s", end.c_str());}
/* Start of commonly used constants */
const int INF = 1e9;
const int MOD = 1e9+7;
void solve(){
int m, n;
SC(m, n);
}
int main(){
int T;
SC(T);
while(T--){
solve();
}
return 0;
}
| 23.285714 | 185 | 0.577245 |
a22992aa915dd06e962163704b713c016925eb26 | 2,215 | cpp | C++ | tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 30 | 2018-03-05T17:35:29.000Z | 2022-03-17T18:59:34.000Z | tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 2 | 2016-05-26T04:47:13.000Z | 2019-02-15T05:17:43.000Z | tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 5 | 2019-02-15T05:09:22.000Z | 2021-04-14T12:10:16.000Z | #include "__zz_cib_StlDependencyTest-decl.h"
#include "__zz_cib_StlDependencyTest-export.h"
#include "__zz_cib_StlDependencyTest-ids.h"
#include "__zz_cib_StlDependencyTest-mtable.h"
namespace __zz_cib_ { namespace __zz_cib_Class263 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}
namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class258 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}}
namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class257 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}}
namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class260 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}}
namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class259 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}}
namespace __zz_cib_ { namespace __zz_cib_Class261 { namespace __zz_cib_Class262 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}}
extern "C" __zz_cib_export
const __zz_cib_::__zz_cib_MethodTable* __zz_cib_decl __zz_cib_StlDependencyTestGetMethodTable(std::uint32_t classId)
{
switch(classId) {
case __zz_cib_::__zz_cib_ids::__zz_cib_Class263::__zz_cib_classId:
return __zz_cib_::__zz_cib_Class263::__zz_cib_GetMethodTable();
case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class258::__zz_cib_classId:
return __zz_cib_::__zz_cib_Class256::__zz_cib_Class258::__zz_cib_GetMethodTable();
case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class257::__zz_cib_classId:
return __zz_cib_::__zz_cib_Class256::__zz_cib_Class257::__zz_cib_GetMethodTable();
case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class260::__zz_cib_classId:
return __zz_cib_::__zz_cib_Class256::__zz_cib_Class260::__zz_cib_GetMethodTable();
case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class259::__zz_cib_classId:
return __zz_cib_::__zz_cib_Class256::__zz_cib_Class259::__zz_cib_GetMethodTable();
case __zz_cib_::__zz_cib_ids::__zz_cib_Class261::__zz_cib_Class262::__zz_cib_classId:
return __zz_cib_::__zz_cib_Class261::__zz_cib_Class262::__zz_cib_GetMethodTable();
default:
return nullptr;
}
}
| 67.121212 | 140 | 0.832957 |
a22ae189aaa5767f514c0572455824bc70973c43 | 3,128 | cc | C++ | Pulse/src/InputStream.cc | frankencode/CoreComponents | 4c66d7ff9fc5be19222906ba89ba0e98951179de | [
"Zlib"
] | 1 | 2019-07-29T04:07:29.000Z | 2019-07-29T04:07:29.000Z | Pulse/src/InputStream.cc | frankencode/CoreComponents | 4c66d7ff9fc5be19222906ba89ba0e98951179de | [
"Zlib"
] | null | null | null | Pulse/src/InputStream.cc | frankencode/CoreComponents | 4c66d7ff9fc5be19222906ba89ba0e98951179de | [
"Zlib"
] | 1 | 2020-03-04T17:13:04.000Z | 2020-03-04T17:13:04.000Z | /*
* Copyright (C) 2021 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/pulse/InputStream>
#include <cc/Format>
#include <cc/DEBUG>
#include <pulse/stream.h>
#include <cassert>
namespace cc::pulse {
struct InputStream::State: public Object::State
{
State(const Context &context, const String &name, int sampleRate, int channelCount):
context_{context},
name_{name}
{
if (name_.count() == 0) {
name_ = Format{"input_%%_%%"} << sampleRate << channelCount;
}
sampleSpec_.format = PA_SAMPLE_S16NE;
sampleSpec_.rate = sampleRate;
sampleSpec_.channels = channelCount;
stream_ = pa_stream_new(context_, name_, &sampleSpec_, nullptr);
pa_stream_set_state_callback(stream_, &stateChanged, this);
pa_stream_set_read_callback(stream_, &incoming, this);
}
~State()
{
if (stream_) {
pa_stream_unref(stream_);
}
}
static void stateChanged(pa_stream *stream, void *userData)
{
static_cast<State *>(userData)->stateChanged(pa_stream_get_state(stream));
}
void stateChanged(pa_stream_state newState)
{
// CC_INSPECT(newState);
if (newState == PA_STREAM_READY && onReady_) onReady_();
}
static void incoming(pa_stream *stream, size_t fill, void *userData)
{
static_cast<State *>(userData)->incoming(fill);
}
void incoming(size_t fill)
{
if (sample_) {
const void *data = nullptr;
CC_PULSE(pa_stream_peek(stream_, &data, &fill));
if (data != nullptr && fill > 0 && sample_) {
wrapping_.wrapAround(const_cast<void *>(data), fill);
sample_(wrapping_);
}
if (fill > 0) {
CC_PULSE(pa_stream_drop(stream_));
}
}
}
void connect(const String &target, Fun<void()> &&ready)
{
if (ready) {
onReady_ = move(ready);
}
const char *device = nullptr;
if (target.count() > 0) device = target;
CC_PULSE(
pa_stream_connect_record(stream_, device, nullptr, PA_STREAM_NOFLAGS)
);
}
Context context_;
pa_stream *stream_ { nullptr };
pa_sample_spec sampleSpec_ {};
String name_;
Fun<void()> onReady_;
Fun<void(const Bytes &data)> sample_;
Bytes wrapping_;
};
InputStream::InputStream(const Context &context, int sampleRate, int channelCount):
Object{new State{context, {}, sampleRate, channelCount}}
{}
int InputStream::sampleRate() const
{
return me().sampleSpec_.rate;
}
void InputStream::incoming(Fun<void(const Bytes &data)> &&sample)
{
me().sample_ = move(sample);
}
void InputStream::connect(const String &target, Fun<void()> &&ready)
{
me().connect(target, move(ready));
}
InputStream::State &InputStream::me()
{
return Object::me.as<State>();
}
const InputStream::State &InputStream::me() const
{
return Object::me.as<State>();
}
} // namespace cc::pulse
| 24.4375 | 88 | 0.609655 |
a22d4c1cc7f16d757453e4eb88c8537cf9153bef | 224 | hpp | C++ | cpp/include/mh/concurrency/main_thread.hpp | PazerOP/stuff | 8ef31153dce1c9593d59fe7fb731fca4d15f3fa6 | [
"MIT"
] | null | null | null | cpp/include/mh/concurrency/main_thread.hpp | PazerOP/stuff | 8ef31153dce1c9593d59fe7fb731fca4d15f3fa6 | [
"MIT"
] | 4 | 2020-01-04T02:26:00.000Z | 2020-04-19T10:46:50.000Z | cpp/include/mh/concurrency/main_thread.hpp | PazerOP/stuff | 8ef31153dce1c9593d59fe7fb731fca4d15f3fa6 | [
"MIT"
] | null | null | null | #pragma once
#include <thread>
namespace mh
{
inline static const std::thread::id main_thread_id = std::this_thread::get_id();
inline bool is_main_thread()
{
return main_thread_id == std::this_thread::get_id();
}
}
| 16 | 81 | 0.714286 |
a2344908796c529df62a337119c9aae152cbd0ea | 751 | cc | C++ | c-deps/libroach/cache.cc | benlong-transloc/cockroach | 9a38931424b4b84116da606820d3cde699c90879 | [
"MIT",
"BSD-3-Clause"
] | 2 | 2020-02-28T02:40:42.000Z | 2020-02-28T04:08:48.000Z | c-deps/libroach/cache.cc | benlong-transloc/cockroach | 9a38931424b4b84116da606820d3cde699c90879 | [
"MIT",
"BSD-3-Clause"
] | 10 | 2020-09-06T14:29:19.000Z | 2022-03-02T04:56:13.000Z | c-deps/libroach/cache.cc | rohany/cockroach | 12c640b74f8a16a27eb5ba03df9628cec4c99400 | [
"MIT",
"BSD-3-Clause"
] | 2 | 2019-11-12T13:38:48.000Z | 2020-02-02T09:38:19.000Z | // Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
#include "cache.h"
DBCache* DBNewCache(uint64_t size) {
const int num_cache_shard_bits = 4;
DBCache* cache = new DBCache;
cache->rep = rocksdb::NewLRUCache(size, num_cache_shard_bits);
return cache;
}
DBCache* DBRefCache(DBCache* cache) {
DBCache* res = new DBCache;
res->rep = cache->rep;
return res;
}
void DBReleaseCache(DBCache* cache) { delete cache; }
| 27.814815 | 69 | 0.729694 |
a2384a8034b31e628d6bcb624278352b1066ef01 | 835 | cpp | C++ | projects/client/visual/scenery/test/source/tests/donut_test.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | projects/client/visual/scenery/test/source/tests/donut_test.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | projects/client/visual/scenery/test/source/tests/donut_test.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include <glaze/definition/Material.h>
#include <glaze/brushes/GL_Desktop_Brush.h>
#include "glaze_test/utility.h"
using namespace std;
using namespace glaze::definition;
using namespace glaze;
TEST(Box_Test, test_test) {
auto code = load_shader("colored.vertex");
Material material;
material.add_inputs(
{
{types::vec3, "position"},
{types::vec3, "normal"},
{types::vec4, "color"},
});
material.add_uniforms(
{
{types::mat4, "model"},
{types::mat4, "normal_transform"},
{types::vec4, "color_filter"},
});
auto donut = brushes::GL_Desktop_Brush(material);
compare_text(code, donut.vertex);
// EXPECT_EQ(0, 1);
// EXPECT_EQ(30, second->get_cache().y.near);
// EXPECT_EQ(60, third->get_cache().y.near);
} | 23.857143 | 52 | 0.631138 |
a23b954d4f083885e3d2212f014d11bba31dab9e | 7,356 | cpp | C++ | Src/widget.cpp | BastiaanOlij/omnis.xcomp.widget | 629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a | [
"MIT"
] | 1 | 2018-08-09T23:44:54.000Z | 2018-08-09T23:44:54.000Z | Src/widget.cpp | BastiaanOlij/omnis.xcomp.widget | 629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a | [
"MIT"
] | 2 | 2015-01-20T03:51:53.000Z | 2020-03-27T04:45:38.000Z | Src/widget.cpp | BastiaanOlij/omnis.xcomp.widget | 629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a | [
"MIT"
] | 1 | 2018-09-13T05:07:08.000Z | 2018-09-13T05:07:08.000Z | /*
* omnis.xcomp.widget
* ===================
*
* widget.cpp
* Widget library implementation
*
* Bastiaan Olij
*/
#include "widget.h"
#ifdef iswin32
/* not yet supported */
#else
#include "monitor_mac.h"
#endif
qshort mainlib::major() {
return OMNISSDK;
};
qshort mainlib::minor() {
return 124;
};
ECOmethodEvent widgetStaticFuncs[] = {
// ID, Resource, Flags
9000, 9000, fftList, 0, 0, 0, 0,
};
/* see omnis.xcomp.framework\oXCompLib.h for methods to implement here */
qint mainlib::ecm_connect(void) {
OXFcomponent lvComponent;
addStaticMethods(widgetStaticFuncs, 1);
// add our component definitions here...
lvComponent.componentType = cObjType_NVObject;
lvComponent.componentID = 2000;
lvComponent.bitmapID = 0;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oDateTime::newObject);
lvComponent.mProperties = oDateTime::properties();
lvComponent.mMethods = oDateTime::methods();
lvComponent.mEventMethodID = 0;
lvComponent.mEvents = oDateTime::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_Basic;
lvComponent.componentID = 2001;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oCountButton::newObject);
lvComponent.mProperties = oCountButton::properties();
lvComponent.mMethods = oCountButton::methods();
lvComponent.mEventMethodID = 10000;
lvComponent.mEvents = oCountButton::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_Basic;
lvComponent.componentID = 2006;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oRoundedButton::newObject);
lvComponent.mProperties = oRoundedButton::properties();
lvComponent.mMethods = oRoundedButton::methods();
lvComponent.mEventMethodID = 10000;
lvComponent.mEvents = oRoundedButton::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_Basic;
lvComponent.componentID = 2002;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oDataList::newObject);
lvComponent.mProperties = oDataList::properties();
lvComponent.mMethods = oDataList::methods();
lvComponent.mEventMethodID = 10010;
lvComponent.mEvents = oDataList::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_DropList;
lvComponent.componentID = 2003;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oDropDown::newObject);
lvComponent.mProperties = oDropDown::properties();
lvComponent.mMethods = oDropDown::methods();
lvComponent.mEventMethodID = 10020;
lvComponent.mEvents = oDropDown::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_DropList;
lvComponent.componentID = 2005;
lvComponent.bitmapID = 1;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oFontDropDown::newObject);
lvComponent.mProperties = oFontDropDown::properties();
lvComponent.mMethods = oFontDropDown::methods();
lvComponent.mEventMethodID = 10020;
lvComponent.mEvents = oFontDropDown::events();
addComponent(lvComponent);
lvComponent.componentType = cObjType_NVObject;
lvComponent.componentID = 2004;
lvComponent.bitmapID = 0;
lvComponent.flags = 0;
lvComponent.groupResID = 0;
lvComponent.newObjectFunction = (void * (*)()) &(oImage::newObject);
lvComponent.mProperties = oImage::properties();
lvComponent.mMethods = oImage::methods();
lvComponent.mEventMethodID = 0;
lvComponent.mEvents = oImage::events();
addComponent(lvComponent);
return oXCompLib::ecm_connect();
};
qbool mainlib::ecm_disconnect(void) {
// nothing to do here..
return oXCompLib::ecm_disconnect();
};
#ifdef iswin32
void addActiveWindowToMonitorList(EXTqlist * pMonitorList) {
/* Get some info about the active window */
TCHAR name[250];
qchar qname[250];
RECT position;
HWND hWnd = GetActiveWindow();
int len = GetWindowTextLength(hWnd);
if (len > 0) {
if (len > 249) {
len = 249;
};
GetWindowText(hWnd, name, len+1);
CHRconvFromOs::convFromOs(name, len, qname, 250);
};
GetWindowRect(hWnd, &position);
/* now add it to our list */
EXTfldval colFld;
qlong rowNo = pMonitorList->insertRow();
pMonitorList->getColValRef(rowNo, 1, colFld, qtrue);
colFld.setLong(position.left);
pMonitorList->getColValRef(rowNo, 2, colFld, qtrue);
colFld.setLong(position.top);
pMonitorList->getColValRef(rowNo, 3, colFld, qtrue);
colFld.setLong(position.right);
pMonitorList->getColValRef(rowNo, 4, colFld, qtrue);
colFld.setLong(position.bottom);
if (len > 0) {
pMonitorList->getColValRef(rowNo, 5, colFld, qtrue);
colFld.setChar(qname, len);
};
};
#endif
int mainlib::invokeMethod(qlong pMethodId, EXTCompInfo* pECI) {
switch (pMethodId) {
case 9000: { /* $monitors - get list with monitor info */
EXTfldval result;
EXTqlist * monitorList = new EXTqlist(listVlen);
str255 colName;
/* add some columns */
colName = QTEXT("Left");
monitorList->addCol(1, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Top");
monitorList->addCol(2, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Right");
monitorList->addCol(3, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Bottom");
monitorList->addCol(4, fftInteger, 0, 0, NULL, &colName);
colName = QTEXT("Name");
monitorList->addCol(5, fftCharacter, dpFcharacter, 250, NULL, &colName);
#ifdef iswin32
/* on windows Omnis is contained within its main window, so we add its dimensions */
addActiveWindowToMonitorList(monitorList);
/* may in due time add the actual monitors to this list as well */
#else
/* lets see if we can call some obj-c */
monitor_mac * moninfo = new monitor_mac();
for (int i = 0; i < moninfo->mNumActiveMonitors; i++) {
EXTfldval colFld;
qlong rowNo = monitorList->insertRow();
monitorList->getColValRef(rowNo, 1, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].left);
monitorList->getColValRef(rowNo, 2, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].top);
monitorList->getColValRef(rowNo, 3, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].right);
monitorList->getColValRef(rowNo, 4, colFld, qtrue);
colFld.setLong(moninfo->mMonitors[i].bottom);
};
delete moninfo;
#endif
/* and return our list */
result.setList(monitorList, qtrue);
delete monitorList;
ECOaddParam(pECI, &result);
return 1L;
} break;
default: {
return oXCompLib::invokeMethod(pMethodId, pECI);
} break;
}
};
| 31.302128 | 87 | 0.660821 |
a23c10157cbcccec5e57087d42760495ea114d95 | 1,008 | cc | C++ | zircon/system/ulib/storage/buffer/test/vmoid_registry_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | zircon/system/ulib/storage/buffer/test/vmoid_registry_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | zircon/system/ulib/storage/buffer/test/vmoid_registry_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2020 The Fuchsia 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 "storage/buffer/vmoid_registry.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace storage {
namespace {
using ::testing::_;
TEST(VmoidTest, Move) {
Vmoid vmoid(1), vmoid2;
vmoid2 = std::move(vmoid);
EXPECT_FALSE(vmoid.IsAttached());
EXPECT_TRUE(vmoid2.IsAttached());
[[maybe_unused]] vmoid_t id = vmoid2.TakeId();
}
TEST(VmoidDeathTest, ForgottenDetachAssertsInDebug) {
#if ZX_DEBUG_ASSERT_IMPLEMENTED
ASSERT_DEATH({ Vmoid vmoid(1); }, _);
#else
Vmoid vmoid(1);
#endif
}
TEST(VmoidDeathTest, MoveToAttachedVmoidAssertsInDebug) {
#if ZX_DEBUG_ASSERT_IMPLEMENTED
ASSERT_DEATH(
{
Vmoid vmoid(1);
Vmoid vmoid2(2);
vmoid = std::move(vmoid2);
},
_);
#else
Vmoid vmoid(1), vmoid2(2);
vmoid = std::move(vmoid2);
#endif
}
} // namespace
} // namespace storage
| 21 | 73 | 0.690476 |
a24577b30f05e6f83b580fe4ce44fbce0ab7c8da | 1,834 | cpp | C++ | collection/cp/Algorithm_Collection-master/firstMissingPositive.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | 1 | 2019-03-24T13:12:01.000Z | 2019-03-24T13:12:01.000Z | collection/cp/Algorithm_Collection-master/firstMissingPositive.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | collection/cp/Algorithm_Collection-master/firstMissingPositive.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | /*Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Analysis:
If we can use another array flag, we can assign flag[A[i]-1] = A[i] to present its occurrence.And get the first element from flag that the flag[i-1]!=i as the result. Here A[i]-1 and i-1 because the array is from 0 to n-1 to store 1 to n.
But the question requires that we can not use additional space. So we have to use the original array A, to save the flag.
The idea is as follow:
e.g. 3,2,5,1,7
For each element,
1. Do not consider the element which <=0, or value > length n
2. Swap this element A[i] with the A[A[i]-1], e.g. when we met A[0]=3, we swap A[0] and A[2], then A[0]=5
3. For the current element A[i], if A[i]<=0 or A[i]>length n, or A[i] has already occurred, break. Else go to step 2.
e.g. A[0]=5, swap A[0] and A[5], A[0]=7, break.Now the array A is {7,2,3,1,5}.
Next round, A is {1,2,3,7,5}
4. Scan the array A and find the result. e.g. {1,2,3,7,5}, the A[3]!=3+1, print 3+1, result =4.
*/
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for (int i = 0; i<n;i++){
if ( (A[i]>0)&&(A[i]<=n)){
while (A[i]!=(i+1)){
if ((A[i]>n)||(A[i]<=0)||(A[A[i]-1]==A[i])) {break;}
int tmp;
tmp = A[A[i]-1];
A[A[i]-1]=A[i];
A[i]=tmp;
}
}
}
int i=0;
for (; i<n;i++){
if (A[i]!=(i+1)){
return i+1;
}
}
return i+1;
}
};
| 37.428571 | 238 | 0.531625 |
a245b10013ce2468db678e9bc23521ab7c66b945 | 3,684 | cc | C++ | algorithms/forculus/forculus_decrypter.cc | reMarkable/cobalt | 3feead337a6bdf620df7a62abb72c910a566a38c | [
"BSD-3-Clause"
] | null | null | null | algorithms/forculus/forculus_decrypter.cc | reMarkable/cobalt | 3feead337a6bdf620df7a62abb72c910a566a38c | [
"BSD-3-Clause"
] | null | null | null | algorithms/forculus/forculus_decrypter.cc | reMarkable/cobalt | 3feead337a6bdf620df7a62abb72c910a566a38c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "algorithms/forculus/forculus_decrypter.h"
#include <functional>
#include <vector>
#include "algorithms/forculus/polynomial_computations.h"
#include "util/crypto_util/cipher.h"
namespace cobalt {
namespace forculus {
using crypto::SymmetricCipher;
ForculusDecrypter::ForculusDecrypter(uint32_t threshold,
std::string ciphertext) :
threshold_(threshold), num_seen_(0), ciphertext_(std::move(ciphertext)) {}
ForculusDecrypter::Status ForculusDecrypter::AddObservation(
const ForculusObservation& obs) {
if (obs.ciphertext() != ciphertext_) {
return kWrongCiphertext;
}
// Keep a copy of y so we can check it its the same as a previously added
// point.
FieldElement y(obs.point_y());
auto result = points_.insert(std::make_pair(FieldElement(obs.point_x()), y));
auto key_value_pair = result.first;
auto success = result.second;
if (!success) {
if (key_value_pair->second != y) {
return kInconsistentPoints;
}
}
num_seen_++;
return kOK;
}
uint32_t ForculusDecrypter::size() {
return points_.size();
}
ForculusDecrypter::Status ForculusDecrypter::Decrypt(
std::string *plain_text_out) {
if (size() < threshold_) {
return kNotEnoughPoints;
}
// Put pointers to the first |threshold_| x and y values into vectors.
std::vector<const FieldElement*> x_values(threshold_);
std::vector<const FieldElement*> y_values(threshold_);
uint32_t point_index = 0;
for (const auto& point : points_) {
if (point_index >= threshold_) {
break;
}
x_values[point_index] = &point.first;
y_values[point_index++] = &point.second;
}
// The decryption key we need is the constant term of the unique polynomial of
// degree (threshold_ - 1) that passes through the points given by the
// x_values and y_values. We can find this using interpolation.
FieldElement c0 = InterpolateConstant(x_values, y_values);
// Now we have the key, decrypt.
SymmetricCipher cipher;
cipher.set_key(c0.KeyBytes());
std::vector<byte> recoverd_text;
// Our encryption scheme uses a zero nonce. (Note that C++11 initializes
// the entire array to 0 with this syntax.)
static const byte kZeroNonce[SymmetricCipher::NONCE_SIZE] = {0};
if (!cipher.Decrypt(kZeroNonce,
reinterpret_cast<const byte*>(ciphertext_.data()),
ciphertext_.size(), &recoverd_text)) {
// TODO(pseudorandom, rudominer) One reason that decryption might fail
// is a ballot suppression attack. An adversary may intentionally flood
// us with bad (x, y) values in order to keep us from decrypting a
// ciphertext. Because we use authenticated encryption, the result of
// invalid (x, y) values will be failure to decrypt. One way to combat
// this attack might be to try different sets of points of size
// |threshold| iteratively until decryption succeeds.
return kDecryptionFailed;
}
plain_text_out->assign(recoverd_text.begin(), recoverd_text.end());
return kOK;
}
} // namespace forculus
} // namespace cobalt
| 35.085714 | 80 | 0.711183 |
a24bbd680103c5e0bd7054b3e95aa6a8eb8d8e3e | 3,303 | cpp | C++ | compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp | chunseoklee/ONE-1 | f45d579eb78e7e3cd1d878b4137ed23ab569081b | [
"Apache-2.0"
] | null | null | null | compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp | chunseoklee/ONE-1 | f45d579eb78e7e3cd1d878b4137ed23ab569081b | [
"Apache-2.0"
] | null | null | null | compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp | chunseoklee/ONE-1 | f45d579eb78e7e3cd1d878b4137ed23ab569081b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "luci/Pass/RemoveUnnecessarySplitPass.h"
#include <luci/IR/CircleNodes.h>
#include <gtest/gtest.h>
namespace
{
void create_unnecessary_split_graph(loco::Graph *g, bool remove)
{
assert(g);
auto input = g->nodes()->create<luci::CircleInput>();
auto graph_input = g->inputs()->create();
input->index(graph_input->index());
auto dim = g->nodes()->create<luci::CircleConst>();
dim->dtype(loco::DataType::S32);
dim->size<loco::DataType::S32>(1);
dim->rank(1);
dim->dim(0).set(1);
dim->at<loco::DataType::S32>(0) = 0;
auto split_node = g->nodes()->create<luci::CircleSplit>();
split_node->split_dim(dim);
split_node->input(input);
if (remove)
split_node->num_split(1);
else
split_node->num_split(2);
auto split_out_node0 = g->nodes()->create<luci::CircleSplitOut>();
split_out_node0->input(split_node);
split_out_node0->index(0);
auto output0 = g->nodes()->create<luci::CircleOutput>();
output0->from(split_out_node0);
auto graph_output0 = g->outputs()->create();
output0->index(graph_output0->index());
if (!remove)
{
auto split_out_node1 = g->nodes()->create<luci::CircleSplitOut>();
split_out_node1->input(split_node);
split_out_node1->index(1);
auto output1 = g->nodes()->create<luci::CircleOutput>();
output1->from(split_out_node1);
auto graph_output1 = g->outputs()->create();
output1->index(graph_output1->index());
}
}
} // namespace
TEST(RemoveUnnecessarySplitPass, name)
{
luci::RemoveUnnecessarySplitPass pass;
auto const name = pass.name();
ASSERT_NE(nullptr, name);
}
TEST(RemoveUnnecessarySplitPass, create_unnecessary_split)
{
auto graph = loco::make_graph();
create_unnecessary_split_graph(graph.get(), true);
luci::RemoveUnnecessarySplitPass pass;
while (pass.run(graph.get()))
;
luci::CircleSplit *split_node = nullptr;
for (auto node : loco::active_nodes(loco::output_nodes(graph.get())))
{
auto split = dynamic_cast<luci::CircleSplit *>(node);
if (not split)
continue;
split_node = split;
}
// No Split node is in graph.
ASSERT_EQ(nullptr, split_node);
}
TEST(RemoveUnnecessarySplitPass, create_unnecessary_split_NEG)
{
auto graph = loco::make_graph();
create_unnecessary_split_graph(graph.get(), false);
luci::RemoveUnnecessarySplitPass pass;
while (pass.run(graph.get()))
;
luci::CircleSplit *split_node = nullptr;
for (auto node : loco::active_nodes(loco::output_nodes(graph.get())))
{
auto split = dynamic_cast<luci::CircleSplit *>(node);
if (not split)
continue;
split_node = split;
}
// Split node is in graph.
ASSERT_NE(nullptr, split_node);
}
| 27.991525 | 75 | 0.696942 |
a24bfb0a5c845c9ca80feb2549a6fff554012fcd | 5,151 | hpp | C++ | src/helics/cpp98/Endpoint.hpp | dnadeau4/HELICS-src | cad21acaac68d25b50e08b185d4fe5a1ae054241 | [
"BSD-3-Clause"
] | null | null | null | src/helics/cpp98/Endpoint.hpp | dnadeau4/HELICS-src | cad21acaac68d25b50e08b185d4fe5a1ae054241 | [
"BSD-3-Clause"
] | null | null | null | src/helics/cpp98/Endpoint.hpp | dnadeau4/HELICS-src | cad21acaac68d25b50e08b185d4fe5a1ae054241 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright © 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef HELICS_CPP98_ENDPOINT_HPP_
#define HELICS_CPP98_ENDPOINT_HPP_
#pragma once
#include "../shared_api_library/MessageFederate.h"
#include "helicsExceptions.hpp"
#include <vector>
#include <string>
namespace helicscpp
{
class Endpoint
{
public:
explicit Endpoint (helics_endpoint hep) HELICS_NOTHROW: ep (hep) {}
Endpoint () HELICS_NOTHROW : ep (HELICS_NULL_POINTER){};
Endpoint (const Endpoint &endpoint) HELICS_NOTHROW: ep (endpoint.ep) {}
Endpoint &operator= (const Endpoint &endpoint)
{
ep = endpoint.ep;
return *this;
}
operator helics_endpoint () { return ep; }
helics_endpoint baseObject () const { return ep; }
/* Checks if endpoint has unread messages **/
bool hasMessage () const
{
// returns int, 1 = true, 0 = false
return helicsEndpointHasMessage (ep) > 0;
}
/** set the default destination for an endpoint*/
void setDefaultDestination (const std::string &dest)
{
helicsEndpointSetDefaultDestination (ep, dest.c_str (), hThrowOnError ());
}
/** get the default destination for an endpoint*/
const char *getDefaultDestination () const { return helicsEndpointGetDefaultDestination (ep); }
/** Returns the number of pending receives for endpoint **/
uint64_t pendingMessages () const { return helicsEndpointPendingMessages (ep); }
/** Get a packet from an endpoint **/
helics_message getMessage () { return helicsEndpointGetMessage (ep); }
/** Methods for sending a message **/
void sendMessage (const char *data, size_t len)
{
helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data, static_cast<int> (len), hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &dest, const char *data, size_t len)
{
helicsEndpointSendMessageRaw (ep, dest.c_str (), data, static_cast<int> (len), hThrowOnError ());
}
void sendMessage (const char *data, size_t len, helics_time time)
{
helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data, static_cast<int> (len), time, hThrowOnError ());
}
void sendMessage (const std::string &dest, const char *data, size_t len, helics_time time)
{
helicsEndpointSendEventRaw (ep, dest.c_str (), data, static_cast<int> (len), time, hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &data)
{
helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data.c_str (), static_cast<int> (data.size ()),
hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &dest, const std::string &data)
{
helicsEndpointSendMessageRaw (ep, dest.c_str (), data.c_str (), static_cast<int> (data.size ()),
hThrowOnError ());
}
void sendMessage (const std::string &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data.c_str (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
void sendMessage (const std::string &dest, const std::string &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, dest.c_str (), data.c_str (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::vector<char> &data)
{
helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data.data (), static_cast<int> (data.size ()),
hThrowOnError ());
}
/** Methods for sending a message **/
void sendMessage (const std::string &dest, const std::vector<char> &data)
{
helicsEndpointSendMessageRaw (ep, dest.c_str (), data.data (), static_cast<int> (data.size ()),
hThrowOnError ());
}
void sendMessage (const std::vector<char> &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data.data (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
void sendMessage (const std::string &dest, const std::vector<char> &data, helics_time time)
{
helicsEndpointSendEventRaw (ep, dest.c_str (), data.data (), static_cast<int> (data.size ()), time,
hThrowOnError ());
}
void sendMessage (helics_message &message)
{
// returns helicsStatus
helicsEndpointSendMessage (ep, &message, hThrowOnError ());
}
const char *getName () const { return helicsEndpointGetName (ep); }
std::string getType () { return helicsEndpointGetType (ep); }
private:
helics_endpoint ep;
};
} // namespace helicscpp
#endif
| 36.531915 | 115 | 0.635411 |
a2500101143a610b8c7fa14d6da625291270a722 | 22,104 | cpp | C++ | thirdparty/ULib/src/ulib/ldap/ldap.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/ldap/ldap.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | thirdparty/ULib/src/ulib/ldap/ldap.cpp | liftchampion/nativejson-benchmark | 6d575ffa4359a5c4230f74b07d994602a8016fb5 | [
"MIT"
] | null | null | null | // ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// ldap.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
#include <ulib/url.h>
#include <ulib/ldap/ldap.h>
struct timeval ULDAP::timeOut = { 30L, 0L }; // 30 second connection/search timeout
ULDAPEntry::ULDAPEntry(int num_names, const char** names, int num_entry)
{
U_TRACE_REGISTER_OBJECT(0, ULDAPEntry, "%d,%p,%d", num_names, names, num_entry)
U_INTERNAL_ASSERT_EQUALS(names[num_names], 0)
U_DUMP_ATTRS(names)
n_attr = num_names;
n_entry = num_entry;
attr_name = names;
dn = (char**) UMemoryPool::_malloc(num_entry, sizeof(char*), true);
attr_val = (UString**) UMemoryPool::_malloc(num_entry * num_names, sizeof(UString*), true);
}
ULDAPEntry::~ULDAPEntry()
{
U_TRACE_UNREGISTER_OBJECT(0, ULDAPEntry)
for (int i = 0, j, k = 0; i < n_entry; ++i)
{
if (dn[i])
{
U_INTERNAL_DUMP("dn[%d]: %S", i, dn[i])
ldap_memfree(dn[i]);
for (j = 0; j < n_attr; ++j, ++k)
{
if (attr_val[k])
{
U_INTERNAL_DUMP("ULDAPEntry(%d): %S = %V", k, attr_name[j], attr_val[k]->rep)
delete attr_val[k];
}
}
}
}
UMemoryPool::_free(dn, n_entry, sizeof(char*));
UMemoryPool::_free(attr_val, n_entry * n_attr, sizeof(UString*));
}
void ULDAPEntry::set(char* attribute, char** values, int index_entry)
{
U_TRACE(0, "ULDAPEntry::set(%S,%p,%d)", attribute, values, index_entry)
U_DUMP_ATTRS(values)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
for (int j = 0, k = index_entry * n_attr; j < n_attr; ++j, ++k)
{
if (strcmp(attr_name[j], attribute) == 0)
{
U_INTERNAL_DUMP("ULDAPEntry(%d): %S", k, attr_name[j])
U_NEW(UString, attr_val[k], UString((void*)values[0], u__strlen(values[0], __PRETTY_FUNCTION__)));
for (j = 1; values[j]; ++j)
{
attr_val[k]->append(U_CONSTANT_TO_PARAM("; "));
attr_val[k]->append(values[j]);
}
U_INTERNAL_DUMP("value = %V", attr_val[k]->rep)
break;
}
}
}
void ULDAPEntry::set(char* attribute, char* value, uint32_t len, int index_entry)
{
U_TRACE(0, "ULDAPEntry::set(%S,%.*S,%u,%d)", attribute, len, value, len, index_entry)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
for (int j = 0, k = index_entry * n_attr; j < n_attr; ++j, ++k)
{
if (strcmp(attr_name[j], attribute) == 0)
{
U_INTERNAL_DUMP("ULDAPEntry(%d): %S", k, attr_name[j])
U_NEW(UString, attr_val[k], UString((void*)value, len));
U_INTERNAL_DUMP("value = %V", attr_val[k]->rep)
break;
}
}
}
UString ULDAPEntry::getString(int index_names, int index_entry)
{
U_TRACE(0, "ULDAPEntry::getString(%d,%d)", index_names, index_entry)
U_INTERNAL_ASSERT_MINOR(index_names, n_attr)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
int k = (index_entry * n_attr) + index_names;
if (attr_val[k])
{
UString str = *(attr_val[k]);
U_RETURN_STRING(str);
}
return UString::getStringNull();
}
const char* ULDAPEntry::getCStr(int index_names, int index_entry)
{
U_TRACE(0, "ULDAPEntry::getCStr(%d,%d)", index_names, index_entry)
U_INTERNAL_ASSERT_MINOR(index_names, n_attr)
U_INTERNAL_ASSERT_MINOR(index_entry, n_entry)
int k = (index_entry * n_attr) + index_names;
if (attr_val[k])
{
const char* str = attr_val[k]->c_str();
U_RETURN(str);
}
U_RETURN("");
}
void ULDAP::clear()
{
U_TRACE_NO_PARAM(1, "ULDAP::clear()")
if (ludpp)
{
# if !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H)
U_SYSCALL_VOID(ldap_free_urldesc, "%p", ludpp);
# else
int i;
if (ludpp->lud_dn) U_SYSCALL_VOID(free, "%p", (void*)ludpp->lud_dn);
if (ludpp->lud_host) U_SYSCALL_VOID(free, "%p", (void*)ludpp->lud_host);
if (ludpp->lud_filter) U_SYSCALL_VOID(free, "%p", ludpp->lud_filter);
if (ludpp->lud_attrs)
{
for (i = 0; ludpp->lud_attrs[i]; ++i) U_SYSCALL_VOID(free, "%p", ludpp->lud_attrs[i]);
U_SYSCALL_VOID(free, "%p", ludpp->lud_attrs);
}
if (ludpp->lud_exts)
{
for (i = 0; ludpp->lud_exts[i]; ++i) U_SYSCALL_VOID(free, "%p", ludpp->lud_exts[i]);
U_SYSCALL_VOID(free, "%p", ludpp->lud_exts);
}
U_SYSCALL_VOID(free, "%p", ludpp);
# endif
ludpp = 0;
}
if (ld)
{
if (searchResult)
{
U_SYSCALL(ldap_msgfree, "%p", searchResult);
searchResult = 0;
}
U_SYSCALL(ldap_unbind_s, "%p", ld);
ld = 0;
# if defined(HAVE_LDAP_SSL_H) && defined(HAS_NOVELL_LDAPSDK)
if (isSecure) U_SYSCALL_NO_PARAM(ldapssl_client_deinit);
# endif
}
}
void ULDAP::setStatus()
{
U_TRACE_NO_PARAM(0, "ULDAP::setStatus()")
U_CHECK_MEMORY
static const char* errlist[] = {
"LDAP_SUCCESS", // 0 0x00
"LDAP_OPERATIONS_ERROR", // 1 0x01
"LDAP_PROTOCOL_ERROR", // 2 0x02
"LDAP_TIMELIMIT_EXCEEDED", // 3 0x03
"LDAP_SIZELIMIT_EXCEEDED", // 4 0x04
"LDAP_COMPARE_FALSE", // 5 0x05
"LDAP_COMPARE_TRUE", // 6 0x06
"LDAP_STRONG_AUTH_NOT_SUPPORTED", // 7 0x07
"LDAP_STRONG_AUTH_REQUIRED", // 8 0x08
"LDAP_PARTIAL_RESULTS", // 9 0x09
"LDAP_REFERRAL", // 10
"LDAP_ADMINLIMIT_EXCEEDED", // 11
"LDAP_UNAVAILABLE_CRITICAL_EXTENSION", // 12
"LDAP_CONFIDENTIALITY_REQUIRED", // 13
"LDAP_SASL_BIND_IN_PROGRESS", // 14
"", // 15
"LDAP_NO_SUCH_ATTRIBUTE", // 16 0x10
"LDAP_UNDEFINED_TYPE", // 17 0x11
"LDAP_INAPPROPRIATE_MATCHING", // 18 0x12
"LDAP_CONSTRAINT_VIOLATION", // 19 0x13
"LDAP_TYPE_OR_VALUE_EXISTS", // 20 0x14
"LDAP_INVALID_SYNTAX", // 21 0x15
"", // 22
"", // 23
"", // 24
"", // 25
"", // 26
"", // 27
"", // 28
"", // 29
"", // 30
"", // 31
"LDAP_NO_SUCH_OBJECT", // 32 0x20
"LDAP_ALIAS_PROBLEM", // 33 0x21
"LDAP_INVALID_DN_SYNTAX", // 34 0x22
"LDAP_IS_LEAF", // 35 0x23
"LDAP_ALIAS_DEREF_PROBLEM", // 36 0x24
"", // 37
"", // 38
"", // 39
"", // 40
"", // 41
"", // 42
"", // 43
"", // 44
"", // 45
"", // 46
"", // 47
"LDAP_INAPPROPRIATE_AUTH", // 48 0x30
"LDAP_INVALID_CREDENTIALS", // 49 0x31
"LDAP_INSUFFICIENT_ACCESS", // 50 0x32
"LDAP_BUSY", // 51 0x33
"LDAP_UNAVAILABLE", // 52 0x34
"LDAP_UNWILLING_TO_PERFORM", // 53 0x35
"LDAP_LOOP_DETECT", // 54 0x36
"", // 55
"", // 56
"", // 57
"", // 58
"", // 59
"", // 60
"", // 61
"", // 62
"", // 63
"LDAP_NAMING_VIOLATION", // 64 0x40
"LDAP_OBJECT_CLASS_VIOLATION", // 65 0x41
"LDAP_NOT_ALLOWED_ON_NONLEAF", // 66 0x42
"LDAP_NOT_ALLOWED_ON_RDN", // 67 0x43
"LDAP_ALREADY_EXISTS", // 68 0x44
"LDAP_NO_OBJECT_CLASS_MODS", // 69 0x45
"LDAP_RESULTS_TOO_LARGE", // 70 0x46
"LDAP_AFFECTS_MULTIPLE_DSAS", // 71
"", // 72
"", // 73
"", // 74
"", // 75
"", // 76
"", // 77
"", // 78
"", // 79
"LDAP_OTHER", // 80 0x50
"LDAP_SERVER_DOWN", // 81 0x51
"LDAP_LOCAL_ERROR", // 82 0x52
"LDAP_ENCODING_ERROR", // 83 0x53
"LDAP_DECODING_ERROR", // 84 0x54
"LDAP_TIMEOUT", // 85 0x55
"LDAP_AUTH_UNKNOWN", // 86 0x56
"LDAP_FILTER_ERROR", // 87 0x57
"LDAP_USER_CANCELLED", // 88 0x58
"LDAP_PARAM_ERROR", // 89 0x59
"LDAP_NO_MEMORY", // 90 0x5a
"LDAP_CONNECT_ERROR", // 91 0x5b
"LDAP_NOT_SUPPORTED", // 92 0x5c
"LDAP_CONTROL_NOT_FOUND", // 93 0x5d
"LDAP_NO_RESULTS_RETURNED", // 94 0x5e
"LDAP_MORE_RESULTS_TO_RETURN", // 95 0x5f
"LDAP_CLIENT_LOOP", // 96 0x60
"LDAP_REFERRAL_LIMIT_EXCEEDED" // 97 0x61
};
char* descr = ldap_err2string(result);
/**
* get a meaningful error string back from the security library
* this function should be called, if ldap_err2string doesn't
* identify the error code
*/
#if defined(HAVE_LDAP_SSL_H) && !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H)
if (descr == 0) descr = (char*)ldapssl_err2string(result);
#endif
U_INTERNAL_ASSERT_EQUALS(u_buffer_len, 0)
u_buffer_len = u__snprintf(u_buffer, U_BUFFER_SIZE, U_CONSTANT_TO_PARAM("%s (%d, %s)"), (result >= 0 && result < 97 ? errlist[result] : ""), result, descr);
}
#if defined(_MSWINDOWS_) && defined(HAVE_WINLDAP_H)
/**
* Split 'str' into strings separated by commas.
*
* Note: res[] points into 'str'
*/
U_NO_EXPORT char** ULDAP::split_str(char* str)
{
U_TRACE(0, "ULDAP::split_str(%S)", str)
int i;
char **res, *s;
for (i = 2, s = strchr(str, ','); s; ++i) s = strchr(++s, ',');
res = (char**)calloc(i, sizeof(char*));
for (i = 0, s = strtok(str, ","); s; s = strtok(0, ","), ++i) res[i] = s;
U_DUMP_ATTRS(res)
return res;
}
#endif
/* Initialize the LDAP session */
bool ULDAP::init(const char* url)
{
U_TRACE(1, "ULDAP::init(%S)", url)
U_CHECK_MEMORY
U_INTERNAL_ASSERT_POINTER(url)
if (ludpp) clear();
#if !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H)
result = U_SYSCALL(ldap_url_parse, "%S,%p", url, &ludpp);
#else
result = LDAP_INVALID_SYNTAX;
/**
* Break apart the pieces of an LDAP URL
*
* Syntax:
* ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
*
* Defined in RFC4516 section 2
*/
Url _url(url, u__strlen(url, __PRETTY_FUNCTION__));
ludpp = (LDAPURLDesc*) calloc(1, sizeof(LDAPURLDesc));
ludpp->lud_host = _url.getHost().c_strdup();
ludpp->lud_port = _url.getPort();
ludpp->lud_dn = _url.getPath().c_strndup(1);
ludpp->lud_scope = LDAP_SCOPE_BASE;
U_INTERNAL_DUMP("host = %S dn = %S", ludpp->lud_host, ludpp->lud_dn)
// parse attributes, skip "??"
UString query = _url.getQuery();
char* p = query.data();
char* q = strchr(p, '?');
if (q) *q++ = '\0';
U_INTERNAL_DUMP("attributes = %S", p)
if (*p && *p != '?') ludpp->lud_attrs = split_str(p);
p = q;
if (!p) goto next;
// parse scope, skip "??"
q = strchr(p, '?');
if (q) *q++ = '\0';
if (*p && *p != '?')
{
if (strncmp(p, U_CONSTANT_TO_PARAM("base")) == 0) ludpp->lud_scope = LDAP_SCOPE_BASE;
else if (strncmp(p, U_CONSTANT_TO_PARAM("one")) == 0) ludpp->lud_scope = LDAP_SCOPE_ONELEVEL;
else if (strncmp(p, U_CONSTANT_TO_PARAM("onetree")) == 0) ludpp->lud_scope = LDAP_SCOPE_ONELEVEL;
else if (strncmp(p, U_CONSTANT_TO_PARAM("sub")) == 0) ludpp->lud_scope = LDAP_SCOPE_SUBTREE;
else if (strncmp(p, U_CONSTANT_TO_PARAM("subtree")) == 0) ludpp->lud_scope = LDAP_SCOPE_SUBTREE;
U_INTERNAL_DUMP("scope = %d %S", ludpp->lud_scope, p)
}
p = q;
if (!p) goto next;
// parse filter
q = strchr(p, '?');
if (q) *q++ = '\0';
if (!*p) goto next;
ludpp->lud_filter = strdup(p);
U_INTERNAL_DUMP("filter = %S", ludpp->lud_filter)
// parse extensions
if (q) ludpp->lud_exts = split_str(q);
result = LDAP_SUCCESS;
next:
#endif
if (result != LDAP_SUCCESS)
{
# ifdef DEBUG
char buffer[1024];
const char* descr = "???";
const char* errstr = "";
switch (result)
{
# if !defined(_MSWINDOWS_) || !defined(HAVE_WINLDAP_H)
case LDAP_INVALID_SYNTAX:
descr = "LDAP_INVALID_SYNTAX";
errstr = "Invalid URL syntax";
break;
case LDAP_URL_ERR_MEM:
descr = "LDAP_URL_ERR_MEM";
errstr = "Cannot allocate memory space";
break;
case LDAP_URL_ERR_PARAM:
descr = "LDAP_URL_ERR_PARAM";
errstr = "Invalid parameter";
break;
case LDAP_URL_ERR_BADSCOPE:
descr = "LDAP_URL_ERR_BADSCOPE";
errstr = "Invalid or missing scope string";
break;
# if defined(HAVE_LDAP_SSL_H)
case LDAP_URL_ERR_NOTLDAP:
descr = "LDAP_URL_ERR_NOTLDAP";
errstr = "URL doesn't begin with \"ldap://\"";
break;
case LDAP_URL_ERR_NODN:
descr = "LDAP_URL_ERR_NODN";
errstr = "URL has no DN (required)";
break;
case LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION:
descr = "LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION";
errstr = "";
break;
# else
case LDAP_URL_ERR_BADSCHEME:
descr = "LDAP_URL_ERR_BADSCHEME";
errstr = "URL doesnt begin with \"ldap[s]://\"";
break;
case LDAP_URL_ERR_BADENCLOSURE:
descr = "LDAP_URL_ERR_BADENCLOSURE";
errstr = "URL is missing trailing \">\"";
break;
case LDAP_URL_ERR_BADURL:
descr = "LDAP_URL_ERR_BADURL";
errstr = "Invalid URL";
break;
case LDAP_URL_ERR_BADHOST:
descr = "LDAP_URL_ERR_BADHOST";
errstr = "Host port is invalid";
break;
case LDAP_URL_ERR_BADATTRS:
descr = "LDAP_URL_ERR_BADATTRS";
errstr = "Invalid or missing attributes";
break;
case LDAP_URL_ERR_BADFILTER:
descr = "LDAP_URL_ERR_BADFILTER";
errstr = "Invalid or missing filter";
break;
case LDAP_URL_ERR_BADEXTS:
descr = "LDAP_URL_ERR_BADEXTS";
errstr = "Invalid or missing extensions";
break;
# endif
# endif
}
U_INTERNAL_DUMP("ldap_url_parse() failed - %.*s", u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("(%d, %s) - %s"), result, descr, errstr), buffer)
# endif
U_RETURN(false);
}
/* Get the URL scheme (either ldap or ldaps) */
#ifdef HAVE_LDAP_SSL_H
if (strncmp(url, U_CONSTANT_TO_PARAM("ldaps:")) == 0)
{
/* Making encrypted connection */
isSecure = true;
# ifdef HAS_NOVELL_LDAPSDK
/**
* Initialize the ssl library. The first parameter of ldapssl_client_init is a certificate file. However, when used
* the file must be a DER encoded file. 0 is passed in for the certificate file because ldapssl_set_verify_mode will be used
* to specify no server certificate verification. ldapssl_client_init is an application level initialization not a
* thread level initilization and should be done once
*/
result = U_SYSCALL(ldapssl_client_init, "%p,%p", 0, /* DER encoded cert file */
0); /* reserved, use 0 */
if (result != LDAP_SUCCESS) U_RETURN(false);
/**
* Configure the LDAP SSL library to not verify the server certificate. The default is LDAPSSL_VERIFY_SERVER which validates all servers
* against the trusted certificates normally passed in during ldapssl_client_init or ldapssl_add_trusted_cert.
*
* WARNING: Setting the verify mode to LDAPSSL_VERIFY_NONE turns off server certificate verification. This means all servers are
* considered trusted. This should be used only in controlled environments where encrypted communication between servers and
* clients is desired but server verification is not necessary
*/
result = U_SYSCALL(ldapssl_set_verify_mode, "%d", LDAPSSL_VERIFY_NONE);
if (result != LDAP_SUCCESS)
{
U_SYSCALL_NO_PARAM(ldapssl_client_deinit);
U_RETURN(false);
}
# endif
/* create a LDAP session handle that is enabled for ssl connection */
ld = (LDAP*) U_SYSCALL(ldapssl_init, "%S,%d,%d", (char*)ludpp->lud_host, /* host name */
(ludpp->lud_port ? ludpp->lud_port : LDAPS_PORT), /* port number */
1); /* 0 - clear text, 1 - enable for ssl */
if (ld == 0)
{
# ifdef HAS_NOVELL_LDAPSDK
U_SYSCALL_NO_PARAM(ldapssl_client_deinit);
# endif
U_RETURN(false);
}
# if defined(_MSWINDOWS_) && defined(HAVE_WINLDAP_H)
(void) U_SYSCALL(ldap_set_option, "%p,%d,%d", ld, LDAP_OPT_SSL, LDAP_OPT_ON);
# endif
}
else
#endif
{
/* Making clear text connection */
if (init(ludpp->lud_host, ludpp->lud_port) == false) U_RETURN(false);
}
U_RETURN(true);
}
void ULDAP::get(ULDAPEntry& e)
{
U_TRACE(1, "ULDAP::get(%p)", &e)
U_CHECK_MEMORY
U_INTERNAL_ASSERT_POINTER(ld)
U_INTERNAL_ASSERT_POINTER(searchResult)
// Go through the search results by checking entries
int i = 0, j;
char** values;
char* attribute;
LDAPMessage* entry;
BerElement* ber = 0;
char* _attribute;
struct berval** bvs = 0;
for (entry = ldap_first_entry(ld, searchResult); entry;
entry = ldap_next_entry( ld, entry), ++i)
{
e.dn[i] = ldap_get_dn(ld, entry);
U_INTERNAL_DUMP("dn[%d]: %S", i, e.dn[i])
for (attribute = ldap_first_attribute(ld, entry, &ber); attribute;
attribute = ldap_next_attribute( ld, entry, ber))
{
values = ldap_get_values(ld, entry, attribute); /* Get values */
U_INTERNAL_DUMP("values = %p attribute = %S", values, attribute)
if (values)
{
e.set(attribute, values, i);
ldap_value_free(values);
}
else
{
for (j = 0; j < e.n_attr; ++j)
{
// be prepared to the 'attr;binary' versions of 'attr'
_attribute = (char*)e.attr_name[j];
U_INTERNAL_DUMP("e.attr_name[%d] = %S", j, _attribute)
if (strncmp(attribute, _attribute, u__strlen(_attribute, __PRETTY_FUNCTION__)) == 0)
{
bvs = ldap_get_values_len(ld, entry, attribute);
if (bvs)
{
e.set(_attribute, bvs[0]->bv_val, bvs[0]->bv_len, i);
ldap_value_free_len(bvs);
break;
}
}
}
}
ldap_memfree(attribute);
}
ber_free(ber, 0);
}
}
// DEBUG
#if defined(U_STDCPP_ENABLE) && defined(DEBUG)
const char* ULDAPEntry::dump(bool reset) const
{
*UObjectIO::os << "dn " << (void*)dn << '\n'
<< "n_attr " << n_attr << '\n'
<< "n_entry " << n_entry << '\n'
<< "attr_val " << (void*)attr_val << '\n'
<< "attr_name " << (void*)attr_name;
if (reset)
{
UObjectIO::output();
return UObjectIO::buffer_output;
}
return 0;
}
const char* ULDAP::dump(bool reset) const
{
*UObjectIO::os << "ld " << (void*)ld << '\n'
<< "ludpp " << (void*)ludpp << '\n'
<< "result " << result << '\n'
<< "isSecure " << isSecure << '\n'
<< "pTimeOut " << (void*)pTimeOut << '\n'
<< "searchResult " << (void*)searchResult;
if (reset)
{
UObjectIO::output();
return UObjectIO::buffer_output;
}
return 0;
}
#endif
| 30.530387 | 161 | 0.497647 |
a2525c82eb57edaf137e876962602c448c65bbc4 | 3,334 | cpp | C++ | gmsh/Geo/discreteRegion.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | 4 | 2019-05-06T09:35:08.000Z | 2021-05-14T16:26:45.000Z | gmsh/Geo/discreteRegion.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | null | null | null | gmsh/Geo/discreteRegion.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | 1 | 2019-06-28T09:23:43.000Z | 2019-06-28T09:23:43.000Z | // Gmsh - Copyright (C) 1997-2019 C. Geuzaine, J.-F. Remacle
//
// See the LICENSE.txt file for license information. Please report all
// issues on https://gitlab.onelab.info/gmsh/gmsh/issues.
#include "GmshConfig.h"
#include "discreteRegion.h"
#include "MVertex.h"
#include "GModelIO_GEO.h"
#include "Geo.h"
#include "Context.h"
#if defined(HAVE_MESH)
#include "meshGRegion.h"
#include "meshGRegionDelaunayInsertion.h"
#endif
discreteRegion::discreteRegion(GModel *model, int num) : GRegion(model, num)
{
::Volume *v = CreateVolume(num, MSH_VOLUME_DISCRETE);
Tree_Add(model->getGEOInternals()->Volumes, &v);
}
void discreteRegion::setBoundFaces(const std::set<int> &tagFaces)
{
for(std::set<int>::const_iterator it = tagFaces.begin(); it != tagFaces.end();
++it) {
GFace *face = model()->getFaceByTag(*it);
if(face) {
l_faces.push_back(face);
face->addRegion(this);
}
else {
Msg::Error("Unknown model face %d", *it);
}
}
}
void discreteRegion::setBoundFaces(const std::vector<int> &tagFaces,
const std::vector<int> &signFaces)
{
if(tagFaces.size() != signFaces.size()) {
Msg::Error("Wrong number of face signs in setBoundFaces");
std::set<int> tags;
tags.insert(tagFaces.begin(), tagFaces.end());
setBoundFaces(tags);
}
for(std::size_t i = 0; i != tagFaces.size(); i++) {
GFace *face = model()->getFaceByTag(tagFaces[i]);
if(face) {
l_faces.push_back(face);
face->addRegion(this);
l_dirs.push_back(signFaces[i]);
}
else {
Msg::Error("Unknown model face %d", tagFaces[i]);
}
}
}
void discreteRegion::findFaces(
std::map<MFace, std::vector<int>, Less_Face> &map_faces)
{
std::set<MFace, Less_Face> bound_faces;
for(std::size_t elem = 0; elem < getNumMeshElements(); elem++) {
MElement *e = getMeshElement(elem);
for(int iFace = 0; iFace < e->getNumFaces(); iFace++) {
MFace tmp_face = e->getFace(iFace);
std::set<MFace, Less_Face>::iterator itset = bound_faces.find(tmp_face);
if(itset == bound_faces.end())
bound_faces.insert(tmp_face);
else
bound_faces.erase(itset);
}
}
// for the boundary faces, associate the tag of the discrete face
for(std::set<MFace, Less_Face>::iterator itv = bound_faces.begin();
itv != bound_faces.end(); ++itv) {
std::map<MFace, std::vector<int>, Less_Face>::iterator itmap =
map_faces.find(*itv);
if(itmap == map_faces.end()) {
std::vector<int> tagRegions;
tagRegions.push_back(tag());
map_faces.insert(std::make_pair(*itv, tagRegions));
}
else {
std::vector<int> tagRegions = itmap->second;
tagRegions.push_back(tag());
itmap->second = tagRegions;
}
}
}
void discreteRegion::remesh()
{
#if defined(HAVE_MESH)
bool classify = false;
insertVerticesInRegion(this, 2000000000, classify);
// not functional yet: need boundaries
for(int i = 0; i < std::max(CTX::instance()->mesh.optimize,
CTX::instance()->mesh.optimizeNetgen); i++) {
if(CTX::instance()->mesh.optimize >= i) {
optimizeMeshGRegion opt;
opt(this, true);
}
if(CTX::instance()->mesh.optimizeNetgen >= i) {
optimizeMeshGRegionNetgen opt;
opt(this, true);
}
}
#endif
}
| 28.495726 | 80 | 0.632873 |
a252ec135691e83d5217af10e0e71a2280678bd1 | 8,114 | cpp | C++ | Classic DLL Injection/DLLInj.cpp | Aporlorxl23/Windows-Process-Injection | a63a24286aca6ec761904c8900976e6ddfb600d9 | [
"MIT"
] | 2 | 2021-07-15T23:57:45.000Z | 2021-07-16T01:04:01.000Z | Classic DLL Injection/DLLInj.cpp | Aporlorxl23/Windows-Process-Injection | a63a24286aca6ec761904c8900976e6ddfb600d9 | [
"MIT"
] | null | null | null | Classic DLL Injection/DLLInj.cpp | Aporlorxl23/Windows-Process-Injection | a63a24286aca6ec761904c8900976e6ddfb600d9 | [
"MIT"
] | null | null | null | #undef UNICODE
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
LPCSTR Banner = \
"Usage>\n DLLInj.exe name notepad.exe DLLInj.dll\n DLLInj.exe pid 2323 DLLInj.dll";
DWORD FindProcess(DWORD PID, LPCSTR ProcessName, LPCSTR Mode) {
HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, FALSE);
/*
https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot
TH32CS_SNAPPROCESS = Includes all processes in the system in the snapshot. To enumerate the processes, see Process32First.
FALSE = The process identifier of the process to be included in the snapshot. This parameter can be zero to indicate the current process.
*/
PROCESSENTRY32 Entry;
/*
The size of the structure, in bytes. Before calling the Process32First function, set this member to sizeof(PROCESSENTRY32).
If you do not initialize dwSize, Process32First fails
https://docs.microsoft.com/tr-tr/windows/win32/api/tlhelp32/ns-tlhelp32-processentry32
*/
Entry.dwSize = sizeof(Entry);
if (strcmp(Mode, "Name") == 0) {
//Here the purpose is to find the PID of the entered process name.
if (Process32First(Snapshot, &Entry) == TRUE) {
/*
https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32first
Snapshot = A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
Entry = A pointer to a PROCESSENTRY32 structure. It contains process information such as the name of the executable file, the process identifier, and the process identifier of the parent process.
*/
while (Process32Next(Snapshot, &Entry) == TRUE) {
/*
https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32next
Snapshot = A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
Entry = A pointer to a PROCESSENTRY32 structure.
*/
if (strcmp(Entry.szExeFile, ProcessName) == 0) {
CloseHandle(Snapshot);
return Entry.th32ProcessID; // This return my process PID
}
}
}
}
else if (strcmp(Mode, "Pid") == 0) {
//The purpose here is to learn whether the entered PID value works in the system.
if (Process32First(Snapshot, &Entry) == TRUE) {
while (Process32Next(Snapshot, &Entry) == TRUE) {
if (Entry.th32ProcessID == PID) {
CloseHandle(Snapshot);
return TRUE;
}
}
CloseHandle(Snapshot);
return FALSE;
}
}
else {
std::cout << "[?] Mode Not Found ?" << std::endl;
CloseHandle(Snapshot);
}
}
void InjectProcess(DWORD PID, LPCSTR DllPath) {
std::cout << "[+] Started DLL Injection on " << PID << " Dll Path> " << DllPath << std::endl;
HANDLE hProcess = OpenProcess(
PROCESS_ALL_ACCESS, //The access to the process object. This access right is checked against the security descriptor for the process.
FALSE, //If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle.
PID); //The identifier of the local process to be opened.
//https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
LPVOID LoadLibrary = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
/*
https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea
https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress
Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL).
A handle to the DLL module that contains the function or variable.
The LoadLibrary, LoadLibraryEx, LoadPackagedLibrary, or GetModuleHandle function returns this handle.
*/
LPVOID Mem = VirtualAllocEx(
hProcess, //The handle to a process. The function allocates memory within the virtual address space of this process.
NULL, //The pointer that specifies a desired starting address for the region of pages that you want to allocate.
strlen(DllPath) + 1, //The size of the region of memory to allocate, in bytes.
// Note : You have to allocate 1 extra byte for the null-character at the end.
(MEM_COMMIT | MEM_RESERVE), //The type of memory allocation.
//To reserve and commit pages in one step, call VirtualAllocEx with MEM_COMMIT | MEM_RESERVE.
PAGE_READWRITE); //The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the memory protection constants.
/*
https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex
Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process.
The function initializes the memory it allocates to zero.
*/
WriteProcessMemory(
hProcess, //A handle to the process memory to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process.
Mem, //A pointer to the base address in the specified process to which data is written.
DllPath, //A pointer to the buffer that contains data to be written in the address space of the specified process.
strlen(DllPath) + 1, // The number of bytes to be written to the specified process. (Note valid here)
NULL); //A pointer to a variable that receives the number of bytes transferred into the specified process. This parameter is optional.
//If lpNumberOfBytesWritten is NULL, the parameter is ignored.
/*
https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory
Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails.
*/
HANDLE ThreadID = CreateRemoteThread(
hProcess, // A handle to the process in which the thread is to be created.
NULL, NULL,
// First Parameter A pointer to a SECURITY_ATTRIBUTES structure that specifies a security descriptor for the new thread and determines whether child processes can inherit the returned handle.
//If lpThreadAttributes is NULL, the thread gets a default security descriptor and the handle cannot be inherited.
// Second Parameter The initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is 0 (zero), the new thread uses the default size for the executable.
(LPTHREAD_START_ROUTINE)LoadLibrary, // A pointer to the application-defined function of type LPTHREAD_START_ROUTINE to be executed by the thread and represents the starting address of the thread in the remote process. The function must exist in the remote process.
Mem, // A pointer to a variable to be passed to the thread function.
NULL, NULL);
// First Parameter The flags that control the creation of the thread. 0 The thread runs immediately after creation.
// Second Parameter A pointer to a variable that receives the thread identifier.
// If this parameter is NULL, the thread identifier is not returned.
/*
https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread
Creates a thread that runs in the virtual address space of another process.
*/
if (ThreadID != NULL) { // Here we check if the operation was successful
std::cout << "[+] DLL Successfully Injected !" << std::endl;
}
else {
std::cout << "[-] DLL Failed to Inject !" << std::endl;
}
CloseHandle(hProcess);
}
int main(int argc, char *argv[])
{
if (argv[1] == NULL || argv[2] == NULL || argv[3] == NULL) {
std::cout << Banner << std::endl;
exit(0);
}
std::string Option = argv[1];
if (strcmp(argv[1], "name") == 0) {
if (FindProcess(NULL, argv[2], "Name") == 0) {
std::cout << "[-] Process Not Found !" << std::endl;
exit(0);
}
InjectProcess(FindProcess(NULL, argv[2], "Name"), argv[3]);
}
else if (strcmp(argv[1], "pid") == 0) {
int PID = atoi((char*)argv[2]);
if (FindProcess(PID, NULL, "Pid") == 0) {
std::cout << "[-] Process Not Found !" << std::endl;
exit(0);
}
InjectProcess(PID, argv[3]);
}
else {
std::cout << Banner << std::endl;
exit(0);
}
return 0;
}
| 42.481675 | 268 | 0.733547 |
a25812c405b0455b36c0084c8766f1fffafe2b9d | 6,616 | cpp | C++ | src/Node.cpp | caitp/TimedText | 7fa0724b3ba99539d17cd0c8be59922676f7114c | [
"Unlicense"
] | 2 | 2017-08-01T11:17:43.000Z | 2022-03-19T21:26:45.000Z | src/Node.cpp | caitp/TimedText | 7fa0724b3ba99539d17cd0c8be59922676f7114c | [
"Unlicense"
] | null | null | null | src/Node.cpp | caitp/TimedText | 7fa0724b3ba99539d17cd0c8be59922676f7114c | [
"Unlicense"
] | null | null | null | //
// Copyright (c) 2013 Caitlin Potter and Contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 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.
//
#include "NodeData.h"
namespace TimedText
{
class EmptyNodeData : public NodeData
{
public:
EmptyNodeData() : NodeData(EmptyNode,NullNode) {}
} emptyNode;
Node::Node()
: d(&emptyNode)
{
d->ref.ref();
}
static bool isInternalNode(NodeElementType type)
{
if(type > FirstNodeElementType && type < LastNodeElementType) {
// There are currently only two leaf nodes...
if(type == TextNode || type == TimestampNode)
return false;
return true;
}
return false;
}
static NodeData *internalNodeData(NodeElementType type)
{
if(isInternalNode(type)) {
if(type == InternalTextNode)
return new InternalNodeData(InternalTextNode);
if(type == VoiceNode)
return new VoiceNodeData();
if(type == LangNode)
return new LangNodeData();
else
return new ElementNodeData(type);
}
return 0;
}
static NodeData *leafNodeData(NodeElementType type)
{
if(type == TextNode)
return new TextNodeData();
if(type == TimestampNode)
return new TimestampNodeData();
return 0;
}
static NodeData *createNodeData(NodeType type, NodeElementType elem)
{
NodeData *d = 0;
if(type == InternalNode && (d = internalNodeData(elem)))
return d;
if(type == LeafNode && (d = leafNodeData(elem)))
return d;
d = &emptyNode;
d->ref.ref();
return d;
}
static NodeData *createNodeData(NodeElementType type)
{
NodeData *d = 0;
if((d = internalNodeData(type)))
return d;
if((d = leafNodeData(type)))
return d;
d = &emptyNode;
d->ref.ref();
return d;
}
Node::Node(NodeType type, NodeElementType elementType)
: d(createNodeData(type,elementType))
{
}
Node::Node(NodeElementType type)
: d(createNodeData(type))
{
}
Node::Node(const Node &other)
: d(other.d)
{
d->ref.ref();
}
Node::~Node()
{
if(!d->ref.deref())
delete d;
}
Node &
Node::operator=(const Node &other)
{
other.d->ref.ref();
if(!d->ref.deref())
delete d;
d = other.d;
return *this;
}
NodeType
Node::type() const
{
return d->type;
}
NodeElementType
Node::elementType() const
{
return d->element;
}
Timestamp
Node::timestamp() const
{
return d->timestamp();
}
String
Node::voice() const
{
return d->voice();
}
String
Node::text() const
{
return d->text();
}
String
Node::lang() const
{
return d->lang();
}
List<String>
Node::applicableClasses() const
{
return d->applicableClasses();
}
bool
Node::setTimestamp(const Timestamp &ts)
{
return d->setTimestamp(ts);
}
bool
Node::setVoice(const String &voice)
{
return d->setVoice(voice);
}
bool
Node::setText(const String &text)
{
return d->setText(text);
}
bool
Node::setLang(const String &lang)
{
return d->setLang(lang);
}
bool
Node::setApplicableClasses(const List<String> &classes)
{
return d->setApplicableClasses(classes);
}
const List<Node> &
Node::children() const
{
return d->children();
}
bool
Node::push(const Node &node)
{
return d->push(node);
}
bool
Node::pop(Node &result)
{
return d->pop(result);
}
bool
Node::unshift(const Node &node)
{
return d->unshift(node);
}
bool
Node::shift(Node &result)
{
return d->shift(result);
}
bool
Node::insert(int i, const Node &node)
{
return d->insert(i, node);
}
bool
Node::take(int i, Node &result)
{
return d->take(i, result);
}
bool
Node::itemAt(int i, Node &result)
{
return d->itemAt(i, result);
}
Node::iterator
Node::begin()
{
return d->begin();
}
Node::iterator
Node::end()
{
return d->end();
}
Node::const_iterator
Node::begin() const
{
const NodeData *x = d;
return x->begin();
}
Node::const_iterator
Node::end() const
{
const NodeData *x = d;
return x->end();
}
int
Node::childCount() const
{
return d->childCount();
}
struct VisitState
{
public:
inline VisitState() : i(0) {}
inline VisitState(const VisitState &v) : n(v.n), i(v.i) {}
inline VisitState(const Node &node) : n(node), i(0) {}
inline VisitState(const Node &node, int pos) : n(node), i(pos) {}
inline bool hasChildren() const { return n.childCount() > 0; }
inline bool isLeaf() const { return n.type() == LeafNode; }
inline bool isInternal() const { return n.type() == InternalNode; }
inline bool isInternalText() const {
return n.element() == InternalTextNode;
}
inline bool isEmpty() const { return n.type() == EmptyNode; }
inline bool next(VisitState &result) {
Node tmp;
if(n.itemAt(i++, tmp)) {
result = VisitState(tmp);
return true;
}
return false;
}
operator Node &() { return n; }
operator const Node &() const { return n; }
Node n;
int i;
};
void
Node::visit(NodeVisitor &visitor)
{
List<VisitState> stack;
stack.push(*this);
VisitState *top;
while(stack.lastPtr(top)) {
VisitState it;
if(top->next(it)) {
// Don't visit empty nodes.
if(it.isEmpty())
continue;
// Visit the item before descending
visitor.visit(it);
// We might need to descend, if it's
if(it.isInternal()) {
if(it.hasChildren() && (it.isInternalText() || visitor.enter(it)))
stack.push(it);
}
} else {
// Notify visitor that we are leaving a branch of the tree
if(!top->isInternalText())
visitor.leave(*top);
stack.pop(it);
}
}
}
} // TimedText
| 19.011494 | 74 | 0.667322 |
a25927d2398bfb6687a194c53b94670436c395d0 | 19,351 | cpp | C++ | src/ofApp.cpp | Pitchless/taAsteroids | b041e4ff57ec314a230fcb6b89d39a30e029dfc7 | [
"MIT"
] | null | null | null | src/ofApp.cpp | Pitchless/taAsteroids | b041e4ff57ec314a230fcb6b89d39a30e029dfc7 | [
"MIT"
] | 1 | 2017-03-03T16:38:42.000Z | 2017-03-04T21:16:21.000Z | src/ofApp.cpp | Pitchless/taAsteroids | b041e4ff57ec314a230fcb6b89d39a30e029dfc7 | [
"MIT"
] | null | null | null | #include "ofApp.h"
#include "photon.h"
//--------------------------------------------------------------
void ofApp::setup() {
ofSetWindowTitle("Annoianoids");
//ofSetLogLevel(OF_LOG_VERBOSE);
ofSetFrameRate(60);
ofEnableAlphaBlending();
ofEnableSmoothing();
ofSetWindowShape(1280, 960);
maskFilename = "mask.png";
// Video
iCurVideo = 0;
showVideo.set("Show Video", false);
loadVideoDir("video");
//playVideo();
//pauseVideo();
showMain.set("Show Main", true);
showWorld.set("Show World", true);
mainAlpha.set("Main Alpha", 223, 0, 255);
mainHue.set("Main Hue", 255, 0, 255);
mainSaturation.set("Main Saturation", 255, 0, 255);
imgMain.allocate(kinect.kinect.width, kinect.kinect.height, OF_IMAGE_COLOR_ALPHA);
mainRotation.set("Rotation", 0, 0, 360);
scale.set("Scale", 1.0, 0.1, 10.0);
pointMode.set("Point Mode",6,0,6);
bPointColor.set("Point Color", true);
bg.setup("bg");
kinect.setup();
setupGui();
loadSettings();
kinect.connect();
cueVideo(0);
world.setup(VIEW_W, VIEW_H);
world.gravityY = 2.3;
}
//--------------------------------------------------------------
void ofApp::loadVideoDir(string dirname) {
ofLogNotice() << "Loading video from: " << dirname;
iCurVideo = 0;
ofDirectory dir(dirname);
dir.listDir();
if (dir.size() == 0) {
videos.resize(1); // at least one blank video
ofLogNotice() << "No video found, added default blank video.";
return;
}
vector<string> names;
for (size_t i=0; i < dir.size(); i++) {
names.push_back(dir.getPath(i));
}
sort(names.begin(), names.end());
int num_loaded = 0;
for (size_t i=0; i < names.size(); i++) {
if ( addVideo(names[i]) ) {
num_loaded++;
}
}
ofLogNotice() << "Loaded " << num_loaded << " video(s) in: " << dirname;
}
ofVideoPlayer& ofApp::getCurVideo() {
return videos[iCurVideo];
}
bool ofApp::addVideo(string filename) {
ofVideoPlayer vid;
ofLogNotice() << "Loading movie: " << filename;
//videoPlayer.setPixelFormat(OF_PIXELS_RGBA);
if (!vid.load(filename)) {
ofLogError() << "Failed to load movie: " << filename;
return false;
}
vid.setLoopState(OF_LOOP_NONE);
videos.push_back(vid);
return true;
}
void ofApp::playVideo() {
getCurVideo().play();
ofLogNotice() << "Playing video: " << getCurVideo().getMoviePath();
}
void ofApp::togglePlayVideo() {
ofVideoPlayer vid = getCurVideo();
if ( vid.isPaused() ) {
playVideo();
}
else {
pauseVideo();
}
}
void ofApp::pauseVideo() {
getCurVideo().setPaused(true);
ofLogNotice() << "Pause video: " << getCurVideo().getMoviePath();
}
void ofApp::cueNextVideo() {
int num = iCurVideo + 1;
if ( num > videos.size()-1 ) {
num = 0;
}
cueVideo(num);
}
void ofApp::cueVideo(int num) {
return;
if ( num < 0 || num > videos.size()-1 ) {
ofLogWarning() << "Attempt to cue unknown video: " << num;
return;
}
getCurVideo().stop();
iCurVideo = num;
videos[iCurVideo].play();
videos[iCurVideo].setPaused(true);
videos[iCurVideo].firstFrame();
ofLogNotice() << "Cue video: " << getCurVideo().getMoviePath();
}
void ofApp::playNextVideo() {
cueNextVideo();
playVideo();
}
void ofApp::setupGui() {
ofxGuiSetHeaderColor( ofColor(100) ); // param group headers
ofxGuiSetBackgroundColor( ofColor(60) ); // bg of params (sliders and stuff but not buttons)
ofxGuiSetBorderColor( ofColor(200) ); // bg of param groups (but not panels)
ofxGuiSetFillColor( ofColor(175,145,0) ); // Fill on slider bars etc
ofxGuiSetTextColor( ofColor::white );
ofxGuiSetFont("verdana.ttf", 10);
//ofxGuiSetFont("Hyperspace Bold.otf", 10);
// Note: The panels will get repositioned in windowResized
guiApp.setup("KinectGui");
guiApp.add( fpsSlider.setup("FPS", 60) );
guiApp.add( reConnectButton.setup("Connect") );
guiApp.add( loadButton.setup("Load") );
guiApp.add( saveButton.setup("Save") );
guiApp.add( grabMaskButton.setup("Grab Mask") );
guiApp.add( clearMaskButton.setup("Clear Mask") );
//guiApp.add( playVideoButton.setup("Play Video") );
//guiApp.add( pauseVideoButton.setup("Pause Video") );
//guiApp.add( cueNextVideoButton.setup("Cue Next Video") );
//guiApp.add( nextVideoButton.setup("Play Next Video") );
appParams.setName("Display");
appParams.add( showGui.set("Show Gui", true) );
appParams.add( showPointCloud.set("Show Point Cloud", false) );
appParams.add( pointMode );
appParams.add( bPointColor );
appParams.add( showColorImg.set("RGB", false) );
appParams.add( showDepthImg.set("Depth", false) );
appParams.add( showMaskImg.set("Mask", false) );
appParams.add( showStencilImg.set("Stencil", false) );
appParams.add( showGrayImg.set("Gray", false) );
appParams.add( showBlobs.set("Show Blobs", true) );
appParams.add( showWorld );
appParams.add( autoAddRate.set("Auto Add Rate", 0, 0, 10) );
appParams.add( autoAddMinBlobs.set("Auto Add Min Blobs", 0, 0, 10) );
appParams.add( autoHueRate.set("Auto Hue Rate", 3, 1, 20) );
appParams.add( autoOutline.set("Auto Outline", 0, 0, 20) );
//appParams.add( showVideo );
appParams.add( mainRotation );
appParams.add( scale );
appParams.add( showMain );
appParams.add( mainAlpha );
appParams.add( mainHue );
appParams.add( mainSaturation );
guiApp.add( appParams );
guiApp.add( status.setup("Status","") );
reConnectButton.addListener(this, &ofApp::connect);
loadButton.addListener(this, &ofApp::loadSettings);
saveButton.addListener(this, &ofApp::saveSettings);
grabMaskButton.addListener(this, &ofApp::grabMask);
clearMaskButton.addListener(this, &ofApp::clearMask);
playVideoButton.addListener(this, &ofApp::playVideo);
pauseVideoButton.addListener(this, &ofApp::pauseVideo);
cueNextVideoButton.addListener(this, &ofApp::cueNextVideo);
nextVideoButton.addListener(this, &ofApp::playNextVideo);
guiKinect.setup("Kinect");
ofxGuiGroup * guiKinectGroup = new ofxGuiGroup();
guiKinectGroup->setup("");
// Open settings
connectionParams.setName("Connection");
connectionParams.add( kinect.deviceId );
connectionParams.add( kinect.serial );
connectionParams.add( kinect.bDepthRegistration );
connectionParams.add( kinect.bVideo );
connectionParams.add( kinect.bInfrared );
connectionParams.add( kinect.bTexture );
guiKinectGroup->add( connectionParams );
// Run time settings
kinectParams.setName("Settings");
kinectParams.add( kinect.kinectAngle );
kinectParams.add( kinect.kinectFlip );
kinectParams.add( kinect.nearThreshold );
kinectParams.add( kinect.farThreshold );
kinectParams.add( kinect.bThresholds );
kinectParams.add( kinect.nearClip );
kinectParams.add( kinect.farClip );
kinectParams.add( kinect.extraMaskDepth );
kinectParams.add( kinect.bMask );
guiKinectGroup->add( kinectParams );
blobParams.setName("Blobs");
blobParams.add( kinect.medianBlur );
blobParams.add( kinect.gaussianBlur );
blobParams.add( kinect.minArea );
blobParams.add( kinect.maxArea );
blobParams.add( kinect.maxBlobs );
blobParams.add( kinect.bFindHoles );
blobParams.add( kinect.bUseApproximation );
blobParams.add( kinect.simplify );
blobParams.add( kinect.resampleSpacing );
blobParams.add( kinect.resampleCount );
blobParams.add( kinect.showInfo );
blobParams.add( kinect.showVerts );
blobParams.add( kinect.lineWidth );
blobParams.add( kinect.lineColor );
blobParams.add( kinect.bFill );
guiKinectGroup->add(blobParams);
guiKinect.add( guiKinectGroup );
// Images
// Hide the names and use toggles as labels on the images.
guiImages.setup("Images");
//guiImages.setSize(100,100);
ofxGuiGroup * guiImgGroup = new ofxGuiGroup();
guiImgGroup->setup("");
//guiImgGroup->setSize(100,18);
int imgWidth = 200;
guiImgGroup->add( colorImgGui.setup("Color", (ofImage*)&kinect.colorImg, true, imgWidth) );
guiImgGroup->add( depthImgGui.setup("Depth", (ofImage*)&kinect.depthImg, true) );
guiImgGroup->add( maskImgGui.setup("Mask", (ofImage*)&kinect.maskImg, true) );
guiImgGroup->add( stencilImgGui.setup("Stencil", (ofImage*)&kinect.stencilImg, true) );
guiImgGroup->add( grayImgGui.setup("Gray", (ofImage*)&kinect.grayImg, true) );
guiImages.add( guiImgGroup );
world.setupGui();
}
void ofApp::connect() {
kinect.reConnect();
}
//--------------------------------------------------------------
void ofApp::loadSettings() {
guiApp.loadFromFile("settings.xml");
guiKinect.loadFromFile("kinect.xml");
bg.gui.loadFromFile("bg.xml");
world.gui.loadFromFile("world.xml");
kinect.loadMask(maskFilename);
}
void ofApp::saveSettings() {
guiApp.saveToFile("settings.xml");
guiKinect.saveToFile("kinect.xml");
bg.gui.saveToFile("bg.xml");
world.gui.saveToFile("world.xml");
kinect.saveMask(maskFilename);
}
void ofApp::grabMask() {
kinect.grabMask();
}
void ofApp::clearMask() {
kinect.clearMask();
ofFile maskfile(maskFilename);
if (maskfile.exists())
maskfile.remove();
}
//--------------------------------------------------------------
void ofApp::update() {
bg.update();
getCurVideo().update();
kinect.update();
float scalex = VIEW_W/kinect.kinect.width;
float scaley = VIEW_H/kinect.kinect.height;
vector<ofPolyline> bloblines;
for (int i=0; i<kinect.blobs.size(); i++ ) {
ofPolyline ln;
vector<ofPoint> verts = kinect.blobs[i].getVertices();
for (int j=0; j<verts.size(); j++) {
ln.addVertex(verts[j].x *scalex, verts[j].y*scaley);
}
bloblines.push_back(ln);
}
world.updateOutlines(bloblines);
size_t numBlobs = kinect.blobs.size();
if (autoAddRate > 0 && (int)numBlobs >= autoAddMinBlobs) {
static int last = 0;
int elapsed = int(ofGetElapsedTimef());
if ((elapsed % autoAddRate) == 0 && last != elapsed) {
last = elapsed;
addShiz();
}
}
if (autoHueRate > 0) {
static int last = 0;
int elapsed = int(ofGetElapsedTimef());
if ((elapsed % autoHueRate) == 0 && last != elapsed) {
last = elapsed;
mainHue += 1;
}
}
if (autoOutline > 0) {
static int last = 0;
int elapsed = int(ofGetElapsedTimef());
if ((elapsed % autoOutline) == 0 && last != elapsed) {
int roll = ofRandom(1,3);
last = elapsed;
if (roll==1) {
showBlobs = true;
showMain = false;
}
if (roll==2) {
showBlobs = false;
showMain = true;
}
if (roll==3) {
showBlobs = true;
showMain = true;
}
}
}
world.update();
// Copy the kinect grey image into our video layer
ofPixels newPix = imgMain.getPixels();
ofPixels pix = kinect.grayImg.getPixels();
ofColor col(0,0,0,0);
ofColor blank(0,0,0,0);
for ( int i=0; i<pix.size(); i++ ) {
if ( pix[i] < 1 ) {
newPix[i*4] = 0;
newPix[i*4+1] = 0;
newPix[i*4+2] = 0;
newPix[i*4+3] = 0;
}
else {
int val = pix[i];
ofColor newcol = ofColor::fromHsb(mainHue, mainSaturation, pix[i], mainAlpha);
newPix[i*4] = newcol.r;
newPix[i*4+1] = newcol.g;
newPix[i*4+2] = newcol.b;
newPix[i*4+3] = newcol[3];
}
}
imgMain.update();
}
//--------------------------------------------------------------
void ofApp::draw() {
float w = VIEW_W;
float h = VIEW_H;
bg.draw();
drawKinectImages();
ofPushStyle();
ofPushMatrix();
ofTranslate((w/2.0), (h/2.0));
ofRotate(mainRotation);
ofTranslate(-(w/2.0), -(h/2.0));
ofScale(scale, scale, 0.0);
//if (showVideo)
// getCurVideo().draw(0,0,w,h);
if (showPointCloud) {
easyCam.begin();
//kinect.drawPointCloud();
drawPointCloud();
easyCam.end();
}
if (showWorld) world.draw();
if (showMain) imgMain.draw(0,0,w,h);
if (showBlobs) kinect.drawBlobs(0,0,w,h);
ofPopMatrix();
ofPopStyle();
if (showGui) {
bg.gui.draw();
guiApp.draw();
guiKinect.draw();
guiImages.draw();
world.gui.draw();
}
}
void ofApp::drawKinectImages() {
vector<ofxCvImage*> images;
if (showColorImg) images.push_back(&kinect.colorImg);
if (showDepthImg) images.push_back(&kinect.depthImg);
if (showMaskImg) images.push_back(&kinect.maskImg);
if (showStencilImg) images.push_back(&kinect.stencilImg);
if (showGrayImg) images.push_back(&kinect.grayImg);
int numImg = images.size();
int ww = ofGetWidth();
int wh = ofGetHeight();
ofRectangle rects[4];
if (numImg == 1) {
rects[0] = ofRectangle(0,0,ww,wh);
}
else if (numImg < 5) { // 2 - 4
int w = ww/2;
int h = wh/2;
rects[0] = ofRectangle(0,0,w,h);
rects[1] = ofRectangle(w,0,w,h);
rects[2] = ofRectangle(0,h,w,h);
rects[3] = ofRectangle(w,h,w,h);
}
else {
// 4 max!
numImg = 4;
}
for (int i = 0; i < numImg; ++i)
images[i]->draw(rects[i]);
}
void ofApp::drawPointCloud() {
int w = 640;
int h = 480;
ofMesh mesh;
//mesh.setMode(OF_PRIMITIVE_POINTS);
//mesh.setMode(OF_PRIMITIVE_TRIANGLES); // needs indices
//mesh.setMode(OF_PRIMITIVE_LINES); // excellent crazy lines
//mesh.setMode(OF_PRIMITIVE_LINE_STRIP); // wicked crazy lines
//mesh.setMode(OF_PRIMITIVE_LINE_LOOP); // wicked crazy lines
mesh.setMode(static_cast<ofPrimitiveMode>(pointMode.get()));
int step = 2;
for(int y = 0; y < h; y += step) {
for(int x = 0; x < w; x += step) {
if(kinect.kinect.getDistanceAt(x, y) > 0) {
if (bPointColor) {
mesh.addColor(kinect.kinect.getColorAt(x,y));
}
else {
mesh.addColor(kinect.lineColor.get());
}
mesh.addVertex(kinect.kinect.getWorldCoordinateAt(x, y));
}
}
}
glPointSize(3);
ofPushMatrix();
// the projected points are 'upside down' and 'backwards'
ofScale(1, -1, -1);
ofTranslate(0, 0, -1000); // center the points a bit
glEnable(GL_DEPTH_TEST);
mesh.drawVertices();
glDisable(GL_DEPTH_TEST);
ofPopMatrix();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
if (key == '\t') {
showGui = !showGui;
}
if (key == 'F') {
ofToggleFullscreen();
}
if (key == 'S') {
saveSettings();
}
if (key == 'L') {
loadSettings();
}
if (key == 'g') {
grabMask();
}
if(key == 'C') {
world.clear();
}
if(key == 'c') {
world.addCircle(mouseX/scale, mouseY/scale);
}
if(key == 'b') {
world.addRect(mouseX/scale, mouseY/scale);
}
if(key == 'a') {
world.addAsteroid(mouseX/scale, mouseY/scale);
}
if(key == 'n') {
addShiz();
}
if (key == '1') addShiz(1);
if (key == '2') addShiz(2);
if (key == '3') addShiz(3);
if (key == '4') addShiz(4);
if (key == '5') addShiz(5);
if (key == '6') addShiz(6);
if (key == '7') addShiz(7);
if (key == '8') addShiz(8);
if (key == '9') addShiz(9);
if(key == 'p') {
PhotonPtr p = PhotonPtr(new Photon);
p->setup(world.getB2World(), mouseX/scale, mouseY/scale);
world.add((StuffPtr)p);
p->setVelocity(ofRandom(-10, 10), ofRandom(-10, 10));
}
}
void ofApp::addShiz() {
addShiz(int(ofRandom(1,11)));
};
void ofApp::addShiz(int shiz) {
float x = ofRandom(0.0, world.width);
float y = -50;
ofLogNotice() << "SHIZ " << shiz << " " << x << "x" << y;
if(shiz == 1) {
world.addSprite(x, y, "smiley_yell.png", 23);
}
if(shiz == 2) {
world.addSprite(x, y, "smiley_pink.png", 42, 1, 1, 1.4);
}
if(shiz == 3) {
world.addSprite(x, y, "axe.png", 42, 2.2, 2.0, 0.02, 0.6);
}
if(shiz == 4) {
world.addBoxSprite(x, y, "raggy1.png", 6, 3.0, 1.0, 0.1, 1.6);
}
if(shiz == 5) {
for (int i=0; i<int(ofRandom(1,3)); i++) {
float s = ofRandom(3,6);
world.addBoxSprite(x, y, "dildo.gif", s, 0.9, 1.0, 0.5, 1.6);
}
}
if(shiz == 6) {
world.addSprite(x, y, "fanny.png", 40, 1.0, 1.0, 1.4, 0.5);
}
if(shiz == 7) {
world.addSprite(x, y, "dino.png", 20, 2.0, 3.0, 0.4, 1.5);
}
if(shiz == 8) {
world.addBoxSprite(x, y, "spider5.png", 5, 2.0, 1.0, 1.4, 0.5);
}
if(shiz == 9) {
for (int i=0; i<int(ofRandom(1,3)); i++) {
float s = ofRandom(20,30);
world.addSprite(x, y, "raggy2.png", s, 2.0, 1.0, 1.4, 0.5);
}
}
};
//--------------------------------------------------------------
void ofApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h) {
float sw = ofGetWidth()/VIEW_W;
float sh = ofGetHeight()/VIEW_H;
scale = sw > sh ? sh : sw;
ofLogNotice() << "Window: " << w << " x " << h << "Scale " << scale;
// Re-layout the gui
status = ofToString(w) + "x" + ofToString(h);
bg.gui.setPosition(10,10);
world.gui.setPosition(bg.gui.getShape().getRight()+10,10);
guiImages.setPosition(world.gui.getShape().getRight()+10,10);
guiKinect.setPosition(guiImages.getShape().getRight()+10,10);
guiApp.setPosition(ofGetWidth()-guiApp.getShape().width-10, 10);
bg.gui.minimizeAll();
guiImages.minimizeAll();
guiKinect.minimizeAll();
guiBox2d.minimizeAll();
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
}
//--------------------------------------------------------------
void ofApp::exit() {
// kinect.setCameraTiltAngle(0); // zero the tilt on exit
kinect.close();
loadButton.removeListener(this, &ofApp::loadSettings);
saveButton.removeListener(this, &ofApp::saveSettings);
grabMaskButton.removeListener(this, &ofApp::grabMask);
}
| 30.522082 | 96 | 0.561056 |
a25d5c53b29e80e096b16da7437b5840896c5bae | 2,684 | cpp | C++ | examples/file_loader/file_loader.cpp | torbjoernk/CTML | 0eb16c35c591f990db32d41c58bce71d41817b8c | [
"MIT"
] | 1 | 2018-08-07T15:07:26.000Z | 2018-08-07T15:07:26.000Z | examples/file_loader/file_loader.cpp | torbjoernk/CTML | 0eb16c35c591f990db32d41c58bce71d41817b8c | [
"MIT"
] | null | null | null | examples/file_loader/file_loader.cpp | torbjoernk/CTML | 0eb16c35c591f990db32d41c58bce71d41817b8c | [
"MIT"
] | null | null | null | #include "CTML.h"
#include "dirent.h"
bool add_files_to_doc(std::string folderPath, CTML::Node* containerNode) {
DIR *directory = NULL;
// open the folder path
directory = opendir(folderPath.c_str());
// return false if it doesn't exist
if (directory == NULL) {
std::cout << "Directory not found!\n";
return false;
}
// the directory entry struct
struct dirent *ent;
while ((ent = readdir(directory)) != NULL)
{
// if the current entry is a file
if (ent->d_type == DT_REG) {
// the file name as a string
std::string fileName = std::string(ent->d_name);
// the content of the document
std::string docContent;
std::ifstream textFile(folderPath + fileName);
std::string line;
// loop through the lines in the file
while (std::getline(textFile, line))
{
// append the line to the doc content
docContent += line + '\n';
}
// hacky way of removing the last new line in the doc content
int lastNewLine = docContent.find_last_of('\n');
if (lastNewLine != std::string::npos)
docContent.erase(docContent.find_last_of('\n'));
// remove the extention from the file name
fileName = fileName.substr(0, fileName.find('.'));
// the container for this file
CTML::Node fileContainer("div.post");
CTML::Node fileTitle("h1", fileName);
CTML::Node fileContent("p", docContent);
// append the title and content to the file container
fileContainer.AppendChild(fileTitle).AppendChild(fileContent);
// append the file container to the root container
containerNode->AppendChild(fileContainer);
}
}
// if we can't close the directory for some reason
if (closedir(directory) < 0) {
std::cout << "Could not close the stream to the directory!\n";
return false;
}
// finished
return true;
}
int main()
{
CTML::Document doc;
doc.AddNodeToHead(CTML::Node("title", "CTML Test"));
// force utf-8 encoding
doc.AddNodeToHead(CTML::Node("meta").SetAttribute("charset", "UTF-8"));
CTML::Node containerNode("div.container");
std::string dir;
// input the directory to look for files
std::cout << "Input the directory name with the files: ";
std::cin >> dir;
bool result = add_files_to_doc(dir, &containerNode);
// add the files container to the body
doc.AddNodeToBody(containerNode);
bool fileWriteResult = false;
// if finding files was successful, try to write to a file
if (result)
fileWriteResult = doc.WriteToFile("index.html", CTML::MULTILINE_BR);
// if we wrote to the file successfully
if (fileWriteResult)
std::cout << "All files in \"" + dir + "\" written to index.html successfully!\n";
else
std::cout << "Writing to index.html was unsuccessful!\n";
return fileWriteResult;
} | 33.55 | 84 | 0.69076 |
a25dfa61654baf386d71959105626bfe2049567e | 57 | cpp | C++ | algorithms/des/info.cpp | playahammer/crypto | 27db00a5e1c58bd78dae34164fad4c719ff7f2cf | [
"MIT"
] | null | null | null | algorithms/des/info.cpp | playahammer/crypto | 27db00a5e1c58bd78dae34164fad4c719ff7f2cf | [
"MIT"
] | null | null | null | algorithms/des/info.cpp | playahammer/crypto | 27db00a5e1c58bd78dae34164fad4c719ff7f2cf | [
"MIT"
] | 1 | 2019-04-26T02:23:44.000Z | 2019-04-26T02:23:44.000Z | #include "log.h"
Info::Info()
{
}
QString Info::Info
| 5.7 | 18 | 0.596491 |
a262f7b192a34e3efee1f74fc4223861f275b0fd | 4,487 | cpp | C++ | src/server/protocol/ServerProtocol.cpp | zminor/Zony_CPP | 311c75a3d6acebb7f4265b63813b19eeaa9d8926 | [
"MIT"
] | null | null | null | src/server/protocol/ServerProtocol.cpp | zminor/Zony_CPP | 311c75a3d6acebb7f4265b63813b19eeaa9d8926 | [
"MIT"
] | null | null | null | src/server/protocol/ServerProtocol.cpp | zminor/Zony_CPP | 311c75a3d6acebb7f4265b63813b19eeaa9d8926 | [
"MIT"
] | null | null | null |
#include "ServerProtocol.h"
#include "../../utils/Utils.h"
namespace HttpServer
{
ServerProtocol::ServerProtocol(
Socket::Adapter &sock,
const ServerSettings &settings,
ServerControls &controls
) noexcept
: sock(sock), settings(settings), controls(controls)
{
}
ServerProtocol::ServerProtocol(const ServerProtocol &prot) noexcept
: sock(prot.sock), settings(prot.settings), controls(prot.controls)
{
}
DataVariant::DataReceiver *
ServerProtocol::createDataReceiver(
const Transfer::request_data *rd,
const std::unordered_map<std::string,
DataVariant::Abstract *> &variants
) {
auto const it = rd->incoming_headers.find("content-type");
if (rd->incoming_headers.cend() == it) {
return nullptr;
}
// get the value of the header
const std::string &header_value = it->second;
std::string data_variant_name; // name of data query
std::unordered_map<std::string, std::string> content_params;
// to determine whether the data type query additional parameters
size_t delimiter = header_value.find(';');
// if there are additional parameters - remove them
if (std::string::npos != delimiter) {
data_variant_name = header_value.substr(0, delimiter);
Utils::trim(data_variant_name);
for (
size_t str_param_cur = delimiter + 1, str_param_end = 0;
std::string::npos != str_param_end;
str_param_cur = str_param_end + 1
) {
str_param_end = header_value.find(';', str_param_cur);
delimiter = header_value.find('=', str_param_cur);
if (delimiter >= str_param_end) {
std::string param_name = header_value.substr(
str_param_cur,
std::string::npos != str_param_end
? str_param_end - str_param_cur
: std::string::npos
);
Utils::trim(param_name);
content_params.emplace(
std::move(param_name),
std::string()
);
} else {
std::string param_name = header_value.substr(
str_param_cur,
delimiter - str_param_cur
);
Utils::trim(param_name);
++delimiter;
std::string param_value = header_value.substr(
delimiter,
std::string::npos != str_param_end
? str_param_end - delimiter
: std::string::npos
);
Utils::trim(param_value);
content_params.emplace(
std::move(param_name),
std::move(param_value)
);
}
}
} else {
data_variant_name = header_value;
}
auto const variant = variants.find(data_variant_name);
if (variants.cend() == variant) {
return nullptr;
}
const DataVariant::Abstract *data_variant = variant->second;
size_t data_length = 0;
auto const it_len = rd->incoming_headers.find("content-length");
if (rd->incoming_headers.cend() != it_len) {
data_length = std::strtoull(
it_len->second.c_str(),
nullptr,
10
);
}
return new DataVariant::DataReceiver {
data_variant,
data_variant->createStateStruct(rd, content_params),
data_length,
0, 0, nullptr,
};
}
void ServerProtocol::destroyDataReceiver(void *src)
{
DataVariant::DataReceiver *dr = reinterpret_cast<DataVariant::DataReceiver *>(src);
if (dr) {
dr->data_variant->destroyStateStruct(dr->ss);
if (dr->reserved) {
delete reinterpret_cast<std::string *>(dr->reserved);
dr->reserved = nullptr;
}
}
delete dr;
}
void ServerProtocol::runApplication(
struct Request &req,
const ServerApplicationSettings &appSets
) const {
std::vector<char> buf;
buf.reserve(4096);
if (this->packRequestParameters(buf, req, appSets.root_dir) == false) {
return;
}
Transfer::app_request request {
this->sock.get_handle(),
this->sock.get_tls_session(),
buf.data()
};
Transfer::app_response response {
nullptr, 0
};
try {
// Launch application
req.app_exit_code = appSets.application_call(&request, &response);
}
catch (std::exception &exc) {
// TODO: exception output
}
if (response.response_data && response.data_size)
{
if (EXIT_SUCCESS == req.app_exit_code) {
this->unpackResponseParameters(req, response.response_data);
}
// Clear outgoing data of application
try {
appSets.application_clear(response.response_data, response.data_size);
}
catch (std::exception &exc) {
// TODO: exception output
}
}
}
}
| 23.615789 | 86 | 0.640517 |
a264baaa6da8b663d483dfc76c2506d201409a6f | 2,434 | hpp | C++ | include/domain/structure/field/svector_center.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/domain/structure/field/svector_center.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/domain/structure/field/svector_center.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | #ifndef _S_VECTOR_CENTER_HPP_
#define _S_VECTOR_CENTER_HPP_
#include "sfield.hpp"
#include "utility/tinyformat.hpp"
#include "algebra/array/multi_array.hpp"
#include <limits>
namespace carpio{
template<St DIM, class FIELD>
class SVectorCenter_{
public:
typedef SIndex_<DIM> Index;
typedef SGrid_<DIM> GridBase;
typedef SGhost_<DIM> GhostBase;
typedef SOrder_<DIM> OrderBase;
typedef FIELD Field;
typedef typename FIELD::Grid Grid;
typedef typename FIELD::Ghost Ghost;
typedef typename FIELD::Order Order;
typedef std::shared_ptr<SIndex_<DIM> > spIndex;
typedef std::shared_ptr<SGrid_<DIM> > spGrid;
typedef std::shared_ptr<SGhost_<DIM> > spGhost;
typedef std::shared_ptr<SOrder_<DIM> > spOrder;
typedef MultiArrayV_<Vt, DIM> Mat;
typedef typename Mat::reference reference;
typedef typename Mat::const_reference const_reference;
typedef SVectorCenter_<DIM, FIELD> Self;
typedef std::shared_ptr<Field> spField;
protected:
std::array<spField, DIM> _arrs;
public:
SVectorCenter_() {
FOR_EACH_DIM{
_arrs[d] = nullptr;
}
}
SVectorCenter_(
spField u,
spField v = nullptr,
spField w = nullptr){
spField a[] = {u,v,w};
FOR_EACH_DIM{
ASSERT(a[d] != nullptr);
_arrs[d] = a[d];
}
}
void set(Axes a, spField sps){
ASSERT(a < DIM);
_arrs[a] = sps;
}
const Order& order() const {
return _arrs[_X_]->order();
}
const Grid& grid() const {
return _arrs[_X_]->grid();
}
const Ghost& ghost() const {
return _arrs[_X_]->ghost();
}
Field& operator[](St d){
return *(_arrs[d]);
}
const Field& operator[](St d) const{
return *(_arrs[d]);
}
Vt max() const{
Vt m = _arrs[_X_]->max();
for(St d = 1; d< DIM; d++){
Vt md = _arrs[d]->max();
if(m < md){
m = md;
}
}
return m;
}
Vt max_norm2() const{
if(DIM == 1){
return max();
}else if(DIM == 2){
auto sum = SqareSum(*(_arrs[_X_]), *(_arrs[_Y_]));
return std::sqrt(sum.max());
}else{
auto sum = SqareSum(_arrs[_X_], _arrs[_Y_], _arrs[_Z_]);
return std::sqrt(sum.max());
}
}
};
}
#endif | 21.927928 | 68 | 0.554232 |
a26caffc313c3585b461573217a412f2b87ff712 | 3,139 | cpp | C++ | computer_vision/video_audio/video_decode_ffmpeg/rtsp_ffmpeg_test/src/test.cpp | magic428/subjects_notes | 6930adbb3f445c11ca9d024abb12a53d6aca19e7 | [
"MIT"
] | 2 | 2020-03-18T17:13:00.000Z | 2020-03-25T02:34:03.000Z | computer_vision/video_audio/video_decode_ffmpeg/rtsp_ffmpeg_test/src/test.cpp | magic428/subjects_notes | 6930adbb3f445c11ca9d024abb12a53d6aca19e7 | [
"MIT"
] | null | null | null | computer_vision/video_audio/video_decode_ffmpeg/rtsp_ffmpeg_test/src/test.cpp | magic428/subjects_notes | 6930adbb3f445c11ca9d024abb12a53d6aca19e7 | [
"MIT"
] | null | null | null | /*******************************************************************************
* Video encoding example
*******************************************************************************/
int main(int argc, char** argv)
{
AVCodec *codec = NULL;
AVCodecContext *codecCtx= NULL;
AVFormatContext *pFormatCtx = NULL;
AVStream * pVideoStream = NULL;
AVFrame *picture = NULL;
int i, x, y, //
ret, // Return value
got_packet_ptr; // Data encoded into packet
// Register all formats and codecs
avcodec_register_all();
av_register_all();
avformat_network_init();
char filename[100] ;
sprintf_s(filename,sizeof(filename),"%s","rtsp://192.168.1.7:8554/live.sdp");
if(argc>1)
{
sprintf_s(filename,sizeof(filename),"%s",argv[1]);
}
printf_s("URL: %s\n", filename);
// allocate context
ret = avformat_alloc_output_context2( &pFormatCtx, NULL, "rtsp", filename );
if ( !pFormatCtx || ret < 0 )
{
fprintf(stderr,"Could not allocate output context" );
}
pFormatCtx->flags |= AVFMT_FLAG_NOBUFFER|AVFMT_FLAG_FLUSH_PACKETS;
pFormatCtx->max_interleave_delta = 1;
pFormatCtx->oformat->video_codec = AV_CODEC_ID_H264;
// Find the codec.
codec = avcodec_find_encoder(pFormatCtx->oformat->video_codec);
if (codec == NULL) {
fprintf(stderr, "Codec not found\n");
return -1;
}
// Add stream to pFormatCtx
pVideoStream = avformat_new_stream(pFormatCtx, codec);
if (!pVideoStream)
{
fprintf(stderr, "Cannot add new video stream\n");
return -1;
}
int framerate = 10;
pVideoStream->id = pFormatCtx->nb_streams-1;
pVideoStream->time_base.den = framerate;
pVideoStream->time_base.num = 1;
// Set context
codecCtx = pVideoStream->codec;
codecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
codecCtx->profile = FF_PROFILE_H264_BASELINE;
// Resolution must be a multiple of two.
codecCtx->width = 320;
codecCtx->height = 240;
codecCtx->bit_rate = 1000000;
codecCtx->time_base.den = framerate;
codecCtx->time_base.num = 1;
codecCtx->gop_size = 12; // emit one intra frame every twelve frames at most
if (pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
codecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
// Open the codec.
if (avcodec_open2(codecCtx, codec, NULL) < 0)
{
fprintf(stderr, "Cannot open video codec\n");
return -1;
}
ret = avio_open2(&pFormatCtx->pb, filename, AVIO_FLAG_WRITE, NULL, NULL);
if (ret < 0)
{
// Error "Protocol not found"
av_strerror(ret,errbuf, ERRBUFFLEN);
fprintf(stderr, "avio_open2() fail: %s\n", errbuf);
//return -1;
}
// Write file header. (Gets stuck here)
ret = avformat_write_header(pFormatCtx, NULL);
if ( ret < 0 )
{
fprintf(stderr, "error writing header");
return -1;
}
// ...more code
}
--
Ang | 30.182692 | 82 | 0.566104 |
a2700571f7e9bf2d6a9e6a83e91970a8e058ad46 | 1,442 | cpp | C++ | src/code-examples/chapter-10/functors-optional/main.cpp | nhatvu148/helpers | 1a6875017cf39790dfe40ecec9dcee4410b1d89e | [
"MIT"
] | null | null | null | src/code-examples/chapter-10/functors-optional/main.cpp | nhatvu148/helpers | 1a6875017cf39790dfe40ecec9dcee4410b1d89e | [
"MIT"
] | null | null | null | src/code-examples/chapter-10/functors-optional/main.cpp | nhatvu148/helpers | 1a6875017cf39790dfe40ecec9dcee4410b1d89e | [
"MIT"
] | null | null | null | #include <optional>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/filter.hpp>
// We can define a range facade that allows using std::optional
// as if it was a proper range (as in range-v3 library).
// If the optional is empty, the range is empty. If it contains
// a value, it generates a range that contains a single value.
template <typename T1, typename F>
auto transform(const std::optional<T1> &opt, F f)
-> decltype(f(opt.value()))
{
if (opt) {
return f(opt.value());
} else {
return {};
}
}
template <typename T>
class optional_range
: public ranges::v3::view_facade<optional_range<T>> {
public:
optional_range() = default;
explicit optional_range(const std::optional<T> &opt)
: m_opt_ptr(opt ? &opt.value() : nullptr)
{
}
private:
friend ranges::v3::range_access;
const T *m_opt_ptr;
const T & read() const { return *m_opt_ptr; }
bool equal(ranges::v3::default_sentinel) const {
return m_opt_ptr == nullptr;
}
void next() { m_opt_ptr = nullptr; }
};
template <typename T>
optional_range<T> as_range(const std::optional<T> &opt)
{
return optional_range<T>(opt);
}
int main(int argc, char *argv[])
{
std::optional<int> i;
transform(i, isalnum);
auto r = as_range(i) | ranges::v3::view::transform(isalnum);
return 0;
}
| 22.888889 | 64 | 0.653259 |
a27073b60d9cad11e32d5c469bca677e37901975 | 3,951 | cpp | C++ | src_test/test_utils/TestCase.cpp | alinous-core/codable-cash | 32a86a152a146c592bcfd8cc712f4e8cb38ee1a0 | [
"MIT"
] | 6 | 2019-01-06T05:02:39.000Z | 2020-10-01T11:45:32.000Z | src_test/test_utils/TestCase.cpp | Codablecash/codablecash | 8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9 | [
"MIT"
] | 209 | 2018-05-18T03:07:02.000Z | 2022-03-26T11:42:41.000Z | src_test/test_utils/TestCase.cpp | Codablecash/codablecash | 8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9 | [
"MIT"
] | 3 | 2019-07-06T09:16:36.000Z | 2020-10-15T08:23:28.000Z | /*
* TestCase.cpp
*
* Created on: 2018/05/06
* Author: iizuka
*/
#include "test_utils/TestCase.h"
#include "test_utils/TestGroup.h"
#include "test_utils/TestGroupActions.h"
#include "test_utils/Check.h"
#include "test_utils/TestEnv.h"
#include "test_utils/TestParams.h"
#include "base/UnicodeString.h"
#include <chrono>
#include "base_io_stream/Writer.h"
using namespace std::chrono;
namespace alinous {
TestCase::TestCase(TestGroup* group, const wchar_t* name, TestGroupActions* setup, const char* file, int line) noexcept {
this->group = group;
this->name = new UnicodeString(name);
this->setup = setup;
this->file = new UnicodeString(file);
this->line = line;
this->checks = new ArrayList<Check>();
this->env = new TestEnv(this);
this->done = false;
this->failed = false;
this->microsec = 0;
this->setup->setNames(group->getName(), this->name);
this->setup->setTestEnv(this->env);
group->addTestCase(this->name, this);
}
TestCase::~TestCase() noexcept {
delete this->name;
delete this->setup;
delete this->file;
this->checks->deleteElements();
delete this->checks;
}
void TestCase::doTest(TestParams* params) {
const char* result = "OK";
setDone();
try{
this->setup->setup();
}catch(...){
setFailed();
if(params->isV()){
printf(" %ls [%ls at %d]... failed in setup()\n", this->name->towString(), this->file->towString(), getLine());
}
return;
}
uint64_t start, end;
try{
Check::getThreadKeyRegistory()->registerTestCase(this);
start = Os::getMicroSec();
testBody();
end = Os::getMicroSec();
}catch(...){
end = Os::getMicroSec();
setFailed();
if(params->isV()){
printf(" !!!!! %ls [%ls at %d]... failed. Exception was thrown on test body.\n", this->name->towString(), this->file->towString(), getLine());
}
}
this->microsec = end - start;
try{
this->setup->teardown();
}
catch(...){
setFailed();
if(params->isV()){
printf(" !!!!! %ls [%ls at %d]... failed in teardown()\n", this->name->towString(), this->file->towString(), getLine());
}
return;
}
if(params->isV()){
if(isFailed()){
result = "Failed!!!!!!!!!!!";
}else{
result = "OK";
}
double milli = ((double)this->microsec) / (double)1000;
printf(" %ls() [%ls at %d]... %s(%lf ms)\n", this->name->towString(), this->file->towString(), getLine(), result, milli);
}
else{
printf(".");
fflush( stdout );
}
}
Check* TestCase::addCheck(Check* check) noexcept {
this->checks->addElement(check);
return check;
}
const TestGroup* TestCase::getGroup() const noexcept {
return this->group;
}
TestEnv* TestCase::getEnv() noexcept {
return this->env;
}
const UnicodeString* TestCase::getName() const noexcept {
return this->name;
}
const UnicodeString* TestCase::getFile() const noexcept {
return this->file;
}
const int TestCase::getLine() const noexcept {
return this->line;
}
bool TestCase::isDone() const noexcept {
return this->done;
}
void TestCase::setDone() noexcept {
this->done = true;
}
bool TestCase::isFailed() const noexcept {
return this->failed;
}
void TestCase::setFailed() noexcept {
this->failed = true;
}
ArrayList<Check>* TestCase::getChecks() const noexcept {
return this->checks;
}
void TestCase::exportJUnitXML(Writer* writer) const {
char buff[255]{};
double sec = ((double)this->microsec) / (double)1000000;
::sprintf(buff, "%lf", sec);
UnicodeString milStr(buff);
UnicodeString caseStr(L" <testcase classname=\"");
caseStr.append(this->group->getName()).append(L"\" name=\"").append(this->name).append(L"\" time=\"")
.append(&milStr).append(L"\">\n");
writer->write(&caseStr);
if(failed){
writer->write(L" <failure>\n");
UnicodeString failure(L"");
failure.append(this->file).append(L" at ").append(this->line).append(L"\n");
writer->write(L" ");
writer->write(&failure);
writer->write(L" </failure>\n");
}
writer->write(L" </testcase>\n");
}
} /* namespace alinous */
| 21.95 | 146 | 0.647684 |
a2746799b5f0e0552105b05d98da248b16a6d79b | 6,463 | cpp | C++ | lib/dirac_domain_wall.cpp | Marcogarofalo/quda | 7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda | [
"MIT"
] | null | null | null | lib/dirac_domain_wall.cpp | Marcogarofalo/quda | 7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda | [
"MIT"
] | null | null | null | lib/dirac_domain_wall.cpp | Marcogarofalo/quda | 7dd7ba316d5f872d1a332bdf55a2204a1a4a7dda | [
"MIT"
] | null | null | null | #include <iostream>
#include <dirac_quda.h>
#include <dslash_quda.h>
#include <blas_quda.h>
namespace quda {
DiracDomainWall::DiracDomainWall(const DiracParam ¶m) :
DiracWilson(param, 5),
m5(param.m5),
kappa5(0.5 / (5.0 + m5)),
Ls(param.Ls)
{
}
DiracDomainWall::DiracDomainWall(const DiracDomainWall &dirac) :
DiracWilson(dirac),
m5(dirac.m5),
kappa5(0.5 / (5.0 + m5)),
Ls(dirac.Ls)
{
}
DiracDomainWall::~DiracDomainWall() { }
DiracDomainWall& DiracDomainWall::operator=(const DiracDomainWall &dirac)
{
if (&dirac != this) {
DiracWilson::operator=(dirac);
m5 = dirac.m5;
kappa5 = dirac.kappa5;
}
return *this;
}
void DiracDomainWall::checkDWF(const ColorSpinorField &out, const ColorSpinorField &in) const
{
if (in.Ndim() != 5 || out.Ndim() != 5) errorQuda("Wrong number of dimensions\n");
if (in.X(4) != Ls) errorQuda("Expected Ls = %d, not %d\n", Ls, in.X(4));
if (out.X(4) != Ls) errorQuda("Expected Ls = %d, not %d\n", Ls, out.X(4));
}
void DiracDomainWall::Dslash(ColorSpinorField &out, const ColorSpinorField &in,
const QudaParity parity) const
{
checkDWF(out, in);
checkParitySpinor(in, out);
checkSpinorAlias(in, out);
ApplyDomainWall5D(out, in, *gauge, 0.0, mass, in, parity, dagger, commDim, profile);
long long Ls = in.X(4);
long long bulk = (Ls-2)*(in.Volume()/Ls);
long long wall = 2*in.Volume()/Ls;
flops += 1320LL*(long long)in.Volume() + 96LL*bulk + 120LL*wall;
}
void DiracDomainWall::DslashXpay(ColorSpinorField &out, const ColorSpinorField &in,
const QudaParity parity, const ColorSpinorField &x,
const double &k) const
{
checkDWF(out, in);
checkParitySpinor(in, out);
checkSpinorAlias(in, out);
ApplyDomainWall5D(out, in, *gauge, k, mass, x, parity, dagger, commDim, profile);
long long Ls = in.X(4);
long long bulk = (Ls-2)*(in.Volume()/Ls);
long long wall = 2*in.Volume()/Ls;
flops += (1320LL+48LL)*(long long)in.Volume() + 96LL*bulk + 120LL*wall;
}
void DiracDomainWall::M(ColorSpinorField &out, const ColorSpinorField &in) const
{
checkFullSpinor(out, in);
ApplyDomainWall5D(out, in, *gauge, -kappa5, mass, in, QUDA_INVALID_PARITY, dagger, commDim, profile);
long long Ls = in.X(4);
long long bulk = (Ls - 2) * (in.Volume() / Ls);
long long wall = 2 * in.Volume() / Ls;
flops += (1320LL + 48LL) * (long long)in.Volume() + 96LL * bulk + 120LL * wall;
}
void DiracDomainWall::MdagM(ColorSpinorField &out, const ColorSpinorField &in) const
{
checkFullSpinor(out, in);
bool reset = newTmp(&tmp1, in);
M(*tmp1, in);
Mdag(out, *tmp1);
deleteTmp(&tmp1, reset);
}
void DiracDomainWall::prepare(ColorSpinorField* &src, ColorSpinorField* &sol,
ColorSpinorField &x, ColorSpinorField &b,
const QudaSolutionType solType) const
{
if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) {
errorQuda("Preconditioned solution requires a preconditioned solve_type");
}
src = &b;
sol = &x;
}
void DiracDomainWall::reconstruct(ColorSpinorField &, const ColorSpinorField &, const QudaSolutionType) const
{
// do nothing
}
DiracDomainWallPC::DiracDomainWallPC(const DiracParam ¶m)
: DiracDomainWall(param)
{
}
DiracDomainWallPC::DiracDomainWallPC(const DiracDomainWallPC &dirac)
: DiracDomainWall(dirac)
{
}
DiracDomainWallPC::~DiracDomainWallPC()
{
}
DiracDomainWallPC& DiracDomainWallPC::operator=(const DiracDomainWallPC &dirac)
{
if (&dirac != this) {
DiracDomainWall::operator=(dirac);
}
return *this;
}
// Apply the even-odd preconditioned clover-improved Dirac operator
void DiracDomainWallPC::M(ColorSpinorField &out, const ColorSpinorField &in) const
{
checkDWF(out, in);
double kappa2 = -kappa5*kappa5;
bool reset = newTmp(&tmp1, in);
if (matpcType == QUDA_MATPC_EVEN_EVEN) {
Dslash(*tmp1, in, QUDA_ODD_PARITY);
DslashXpay(out, *tmp1, QUDA_EVEN_PARITY, in, kappa2);
} else if (matpcType == QUDA_MATPC_ODD_ODD) {
Dslash(*tmp1, in, QUDA_EVEN_PARITY);
DslashXpay(out, *tmp1, QUDA_ODD_PARITY, in, kappa2);
} else {
errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType);
}
deleteTmp(&tmp1, reset);
}
void DiracDomainWallPC::MdagM(ColorSpinorField &out, const ColorSpinorField &in) const
{
//M(out, in);
//Mdag(out, out);
bool reset = newTmp(&tmp2, in);
M(*tmp2, in);
Mdag(out, *tmp2);
deleteTmp(&tmp2, reset);
}
void DiracDomainWallPC::prepare(ColorSpinorField* &src, ColorSpinorField* &sol,
ColorSpinorField &x, ColorSpinorField &b,
const QudaSolutionType solType) const
{
// we desire solution to preconditioned system
if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) {
src = &b;
sol = &x;
} else {
// we desire solution to full system
if (matpcType == QUDA_MATPC_EVEN_EVEN) {
// src = b_e + k D_eo b_o
DslashXpay(x.Odd(), b.Odd(), QUDA_EVEN_PARITY, b.Even(), kappa5);
src = &(x.Odd());
sol = &(x.Even());
} else if (matpcType == QUDA_MATPC_ODD_ODD) {
// src = b_o + k D_oe b_e
DslashXpay(x.Even(), b.Even(), QUDA_ODD_PARITY, b.Odd(), kappa5);
src = &(x.Even());
sol = &(x.Odd());
} else {
errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType);
}
// here we use final solution to store parity solution and parity source
// b is now up for grabs if we want
}
}
void DiracDomainWallPC::reconstruct(ColorSpinorField &x, const ColorSpinorField &b,
const QudaSolutionType solType) const
{
if (solType == QUDA_MATPC_SOLUTION || solType == QUDA_MATPCDAG_MATPC_SOLUTION) {
return;
}
// create full solution
checkFullSpinor(x, b);
if (matpcType == QUDA_MATPC_EVEN_EVEN) {
// x_o = b_o + k D_oe x_e
DslashXpay(x.Odd(), x.Even(), QUDA_ODD_PARITY, b.Odd(), kappa5);
} else if (matpcType == QUDA_MATPC_ODD_ODD) {
// x_e = b_e + k D_eo x_o
DslashXpay(x.Even(), x.Odd(), QUDA_EVEN_PARITY, b.Even(), kappa5);
} else {
errorQuda("MatPCType %d not valid for DiracDomainWallPC", matpcType);
}
}
} // namespace quda
| 28.852679 | 111 | 0.63763 |
a275d83966ec6be72dd542828a1ce98022ac2fe0 | 7,914 | cpp | C++ | Source/CoverSystem/Private/CoverSystem/CoverSubsystem.cpp | DavidRadobenko/CoverSystem | 6c5826a53da9817743b82b4904aa006f697e9afb | [
"MIT"
] | null | null | null | Source/CoverSystem/Private/CoverSystem/CoverSubsystem.cpp | DavidRadobenko/CoverSystem | 6c5826a53da9817743b82b4904aa006f697e9afb | [
"MIT"
] | null | null | null | Source/CoverSystem/Private/CoverSystem/CoverSubsystem.cpp | DavidRadobenko/CoverSystem | 6c5826a53da9817743b82b4904aa006f697e9afb | [
"MIT"
] | null | null | null | // Copyright (c) 2018 David Nadaski. All Rights Reserved.
#include "CoverSystem/CoverSubsystem.h"
#include "EngineUtils.h"
#include "Tasks/NavmeshCoverPointGeneratorTask.h"
#if DEBUG_RENDERING
#include "DrawDebugHelpers.h"
#endif
// PROFILER INTEGRATION //
DEFINE_STAT(STAT_GenerateCover);
DEFINE_STAT(STAT_GenerateCoverInBounds);
DEFINE_STAT(STAT_FindCover);
UCoverSubsystem::UCoverSubsystem()
{
//TODO: take the extents of the underlying navigation mesh instead of using 64000, see NavData->GetBounds() in OnNavmeshUpdated
CoverOctree = MakeShareable(new TCoverOctree(FVector(0, 0, 0), 64000));
}
UCoverSubsystem::~UCoverSubsystem()
{
if (CoverOctree.IsValid())
{
CoverOctree->Destroy();
CoverOctree = nullptr;
}
ElementToID.Empty();
CoverObjectToID.Empty();
}
bool ContainsCoverPoint(FCoverPointOctreeElement CoverPoint, TArray<FCoverPointOctreeElement> CoverPoints)
{
for (FCoverPointOctreeElement cp : CoverPoints)
if (CoverPoint.Data->Location == cp.Data->Location)
return true;
return false;
}
bool UCoverSubsystem::GetElementID(FOctreeElementId2& OutElementID, const FVector ElementLocation) const
{
const FOctreeElementId2* element = ElementToID.Find(ElementLocation);
if (!element || !element->IsValidId())
return false;
OutElementID = *element;
return true;
}
void UCoverSubsystem::AssignIDToElement(const FVector ElementLocation, FOctreeElementId2 ID)
{
ElementToID.Add(ElementLocation, ID);
}
bool UCoverSubsystem::RemoveIDToElementMapping(const FVector ElementLocation)
{
return ElementToID.Remove(ElementLocation) > 0;
}
void UCoverSubsystem::OnNavMeshTilesUpdated(const TSet<uint32>& UpdatedTiles)
{
// regenerate cover points within the updated navmesh tiles
TArray<const AActor*> dirtyCoverActors;
for (uint32 tileIdx : UpdatedTiles)
{
#if DEBUG_RENDERING
// DrawDebugXXX calls may crash UE4 when not called from the main thread, so start synchronous tasks in case we're planning on drawing debug shapes
if (bDebugDraw)
(new FAutoDeleteAsyncTask<FNavmeshCoverPointGeneratorTask>(
CoverPointMinDistance,
SmallestAgentHeight,
CoverPointGroundOffset,
MapBounds,
tileIdx,
GetWorld()
))->StartSynchronousTask();
else
#endif
(new FAutoDeleteAsyncTask<FNavmeshCoverPointGeneratorTask>(
CoverPointMinDistance,
SmallestAgentHeight,
CoverPointGroundOffset,
MapBounds,
tileIdx,
GetWorld()
))->StartBackgroundTask();
}
}
void UCoverSubsystem::FindCoverPoints(TArray<FCoverPointOctreeElement>& OutCoverPoints, const FBox& QueryBox) const
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_ReadOnly);
CoverOctree->FindCoverPoints(OutCoverPoints, QueryBox);
}
void UCoverSubsystem::FindCoverPoints(TArray<FCoverPointOctreeElement>& OutCoverPoints, const FSphere& QuerySphere) const
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_ReadOnly);
CoverOctree->FindCoverPoints(OutCoverPoints, QuerySphere);
}
void UCoverSubsystem::AddCoverPoints(const TArray<FDTOCoverData>& CoverPointDTOs)
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_Write);
for (FDTOCoverData coverPointDTO : CoverPointDTOs)
CoverOctree->AddCoverPoint(coverPointDTO, CoverPointMinDistance * 0.9f);
// optimize the octree
CoverOctree->ShrinkElements();
}
FBox UCoverSubsystem::EnlargeAABB(FBox Box)
{
return Box.ExpandBy(FVector(
(Box.Max.X - Box.Min.X) * 0.5f,
(Box.Max.Y - Box.Min.Y) * 0.5f,
(Box.Max.Z - Box.Min.Z) * 0.5f
));
}
void UCoverSubsystem::RemoveStaleCoverPoints(FBox Area)
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_Write);
// enlarge the clean-up area to x1.5 its size
Area = EnlargeAABB(Area);
// find all the cover points in the specified area
TArray<FCoverPointOctreeElement> coverPoints;
CoverOctree->FindCoverPoints(coverPoints, Area);
for (FCoverPointOctreeElement coverPoint : coverPoints)
{
// check if the cover point still has an owner and still falls on the exact same location on the navmesh as it did when it was generated
FNavLocation navLocation;
if (IsValid(coverPoint.GetOwner())
&& UNavigationSystemV1::GetCurrent(GetWorld())->ProjectPointToNavigation(coverPoint.Data->Location, navLocation, FVector(0.1f, 0.1f, CoverPointGroundOffset)))
continue;
FOctreeElementId2 id;
GetElementID(id, coverPoint.Data->Location);
// remove the cover point from the octree
if (id.IsValidId())
CoverOctree->RemoveElement(id);
// remove the cover point from the element-to-id and object-to-location maps
RemoveIDToElementMapping(coverPoint.Data->Location);
CoverObjectToID.RemoveSingle(coverPoint.Data->CoverObject, coverPoint.Data->Location);
}
// optimize the octree
CoverOctree->ShrinkElements();
}
void UCoverSubsystem::RemoveStaleCoverPoints(FVector Origin, FVector Extent)
{
RemoveStaleCoverPoints(FBoxCenterAndExtent(Origin, Extent * 2.0f).GetBox());
}
void UCoverSubsystem::RemoveCoverPointsOfObject(const AActor* CoverObject)
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_Write);
TArray<FVector> coverPointLocations;
CoverObjectToID.MultiFind(CoverObject, coverPointLocations, false);
for (const FVector coverPointLocation : coverPointLocations)
{
FOctreeElementId2 elementID;
GetElementID(elementID, coverPointLocation);
CoverOctree->RemoveElement(elementID);
RemoveIDToElementMapping(coverPointLocation);
CoverObjectToID.Remove(CoverObject);
#if DEBUG_RENDERING
if (bDebugDraw)
DrawDebugSphere(GetWorld(), coverPointLocation, 20.0f, 4, FColor::Red, true, -1.0f, 0, 2.0f);
#endif
}
// optimize the octree
CoverOctree->ShrinkElements();
}
void UCoverSubsystem::RemoveAll()
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_Write);
// destroy the octree
if (CoverOctree.IsValid())
{
CoverOctree->Destroy();
CoverOctree = nullptr;
}
// remove the id-to-element mappings
ElementToID.Empty();
// make a new octree
CoverOctree = MakeShareable(new TCoverOctree(FVector(0, 0, 0), 64000));
}
bool UCoverSubsystem::HoldCover(FVector ElementLocation)
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_Write);
FOctreeElementId2 elemID;
if (!GetElementID(elemID, ElementLocation))
return false;
return CoverOctree->HoldCover(elemID);
}
bool UCoverSubsystem::ReleaseCover(FVector ElementLocation)
{
FRWScopeLock CoverDataLock(CoverDataLockObject, FRWScopeLockType::SLT_Write);
FOctreeElementId2 elemID;
if (!GetElementID(elemID, ElementLocation))
return false;
return CoverOctree->ReleaseCover(elemID);
}
void UCoverSubsystem::OnWorldBeginPlay(UWorld& InWorld)
{
Super::OnWorldBeginPlay(InWorld);
UNavigationSystemV1* NavSys = UNavigationSystemV1::GetCurrent(GetWorld());
if (!IsValid(NavSys))
return;
// subscribe to tile update events on the navmesh
const ANavigationData* MainNavData = NavSys->MainNavData;
if (MainNavData && MainNavData->IsA(AChangeNotifyingRecastNavMesh::StaticClass()))
{
Navmesh = const_cast<AChangeNotifyingRecastNavMesh*>(Cast<AChangeNotifyingRecastNavMesh>(MainNavData));
Navmesh->NavmeshTilesUpdatedBufferedDelegate.AddDynamic(this, &UCoverSubsystem::OnNavMeshTilesUpdated);
bool bFoundCoverSystemBoundsActor;
for (FActorIterator It(GetWorld()); It; ++It)
{
AActor* Actor = *It;
if (Actor->ActorHasTag(FName("CoverSystemBounds")))
{
FVector Origin, BoxExtent;
Actor->GetActorBounds(false, Origin, BoxExtent, false);
MapBounds = FBox(Origin - BoxExtent, Origin + BoxExtent);
bFoundCoverSystemBoundsActor = true;
break;
}
}
if (bFoundCoverSystemBoundsActor == false)
{
UE_LOG(LogTemp, Warning, TEXT("No Actor found with the Actor tag CoverSystemBounds. CoverPoints won't get generated."));
}
Navmesh->RebuildAll();
}
}
float UCoverSubsystem::GetCoverPointGroundOffset()
{
return CoverPointGroundOffset;
} | 28.989011 | 161 | 0.776219 |